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/ValueTracking.h"
31 #include "llvm/IR/BasicBlock.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/Dominators.h"
34 #include "llvm/IR/Function.h"
35 #include "llvm/IR/Instructions.h"
36 #include "llvm/IR/IntrinsicInst.h"
37 #include "llvm/IR/LLVMContext.h"
38 #include "llvm/IR/Type.h"
39 #include "llvm/Pass.h"
40 #include "llvm/Target/TargetLibraryInfo.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 AliasAnalysis::AliasResult
52 AliasAnalysis::alias(const Location &LocA, const Location &LocB) {
53 assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
54 return AA->alias(LocA, LocB);
57 bool AliasAnalysis::pointsToConstantMemory(const Location &Loc,
59 assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
60 return AA->pointsToConstantMemory(Loc, OrLocal);
63 AliasAnalysis::Location
64 AliasAnalysis::getArgLocation(ImmutableCallSite CS, unsigned ArgIdx,
65 AliasAnalysis::ModRefResult &Mask) {
66 assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
67 return AA->getArgLocation(CS, ArgIdx, Mask);
70 void AliasAnalysis::deleteValue(Value *V) {
71 assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
75 void AliasAnalysis::copyValue(Value *From, Value *To) {
76 assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
77 AA->copyValue(From, To);
80 void AliasAnalysis::addEscapingUse(Use &U) {
81 assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
82 AA->addEscapingUse(U);
86 AliasAnalysis::ModRefResult
87 AliasAnalysis::getModRefInfo(ImmutableCallSite CS,
88 const Location &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 ModRefResult ArgMask;
110 getArgLocation(CS, (unsigned) std::distance(CS.arg_begin(), AI),
112 if (!isNoAlias(CSLoc, Loc)) {
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 ModRefResult ArgMask;
171 getArgLocation(CS2, (unsigned) std::distance(CS2.arg_begin(), I),
173 // ArgMask indicates what CS2 might do to CS2Loc, and the dependence of
174 // CS1 on that location is the inverse.
177 else if (ArgMask == Ref)
180 R = ModRefResult((R | (getModRefInfo(CS1, CS2Loc) & 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 ModRefResult ArgMask;
200 getArgLocation(CS1, (unsigned) std::distance(CS1.arg_begin(), I),
202 if ((getModRefInfo(CS2, CS1Loc) & ArgMask) != NoModRef) {
212 // If this is the end of the chain, don't forward.
213 if (!AA) return Mask;
215 // Otherwise, fall back to the next AA in the chain. But we can merge
216 // in any mask we've managed to compute.
217 return ModRefResult(AA->getModRefInfo(CS1, CS2) & Mask);
220 AliasAnalysis::ModRefBehavior
221 AliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
222 assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
224 ModRefBehavior Min = UnknownModRefBehavior;
226 // Call back into the alias analysis with the other form of getModRefBehavior
227 // to see if it can give a better response.
228 if (const Function *F = CS.getCalledFunction())
229 Min = getModRefBehavior(F);
231 // If this is the end of the chain, don't forward.
234 // Otherwise, fall back to the next AA in the chain. But we can merge
235 // in any result we've managed to compute.
236 return ModRefBehavior(AA->getModRefBehavior(CS) & Min);
239 AliasAnalysis::ModRefBehavior
240 AliasAnalysis::getModRefBehavior(const Function *F) {
241 assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
242 return AA->getModRefBehavior(F);
245 //===----------------------------------------------------------------------===//
246 // AliasAnalysis non-virtual helper method implementation
247 //===----------------------------------------------------------------------===//
249 AliasAnalysis::Location AliasAnalysis::getLocation(const LoadInst *LI) {
250 return Location(LI->getPointerOperand(),
251 getTypeStoreSize(LI->getType()),
252 LI->getMetadata(LLVMContext::MD_tbaa));
255 AliasAnalysis::Location AliasAnalysis::getLocation(const StoreInst *SI) {
256 return Location(SI->getPointerOperand(),
257 getTypeStoreSize(SI->getValueOperand()->getType()),
258 SI->getMetadata(LLVMContext::MD_tbaa));
261 AliasAnalysis::Location AliasAnalysis::getLocation(const VAArgInst *VI) {
262 return Location(VI->getPointerOperand(),
264 VI->getMetadata(LLVMContext::MD_tbaa));
267 AliasAnalysis::Location
268 AliasAnalysis::getLocation(const AtomicCmpXchgInst *CXI) {
269 return Location(CXI->getPointerOperand(),
270 getTypeStoreSize(CXI->getCompareOperand()->getType()),
271 CXI->getMetadata(LLVMContext::MD_tbaa));
274 AliasAnalysis::Location
275 AliasAnalysis::getLocation(const AtomicRMWInst *RMWI) {
276 return Location(RMWI->getPointerOperand(),
277 getTypeStoreSize(RMWI->getValOperand()->getType()),
278 RMWI->getMetadata(LLVMContext::MD_tbaa));
281 AliasAnalysis::Location
282 AliasAnalysis::getLocationForSource(const MemTransferInst *MTI) {
283 uint64_t Size = UnknownSize;
284 if (ConstantInt *C = dyn_cast<ConstantInt>(MTI->getLength()))
285 Size = C->getValue().getZExtValue();
287 // memcpy/memmove can have TBAA tags. For memcpy, they apply
288 // to both the source and the destination.
289 MDNode *TBAATag = MTI->getMetadata(LLVMContext::MD_tbaa);
291 return Location(MTI->getRawSource(), Size, TBAATag);
294 AliasAnalysis::Location
295 AliasAnalysis::getLocationForDest(const MemIntrinsic *MTI) {
296 uint64_t Size = UnknownSize;
297 if (ConstantInt *C = dyn_cast<ConstantInt>(MTI->getLength()))
298 Size = C->getValue().getZExtValue();
300 // memcpy/memmove can have TBAA tags. For memcpy, they apply
301 // to both the source and the destination.
302 MDNode *TBAATag = MTI->getMetadata(LLVMContext::MD_tbaa);
304 return Location(MTI->getRawDest(), Size, TBAATag);
309 AliasAnalysis::ModRefResult
310 AliasAnalysis::getModRefInfo(const LoadInst *L, const Location &Loc) {
311 // Be conservative in the face of volatile/atomic.
312 if (!L->isUnordered())
315 // If the load address doesn't alias the given address, it doesn't read
316 // or write the specified memory.
317 if (!alias(getLocation(L), Loc))
320 // Otherwise, a load just reads.
324 AliasAnalysis::ModRefResult
325 AliasAnalysis::getModRefInfo(const StoreInst *S, const Location &Loc) {
326 // Be conservative in the face of volatile/atomic.
327 if (!S->isUnordered())
330 // If the store address cannot alias the pointer in question, then the
331 // specified memory cannot be modified by the store.
332 if (!alias(getLocation(S), Loc))
335 // If the pointer is a pointer to constant memory, then it could not have been
336 // modified by this store.
337 if (pointsToConstantMemory(Loc))
340 // Otherwise, a store just writes.
344 AliasAnalysis::ModRefResult
345 AliasAnalysis::getModRefInfo(const VAArgInst *V, const Location &Loc) {
346 // If the va_arg address cannot alias the pointer in question, then the
347 // specified memory cannot be accessed by the va_arg.
348 if (!alias(getLocation(V), Loc))
351 // If the pointer is a pointer to constant memory, then it could not have been
352 // modified by this va_arg.
353 if (pointsToConstantMemory(Loc))
356 // Otherwise, a va_arg reads and writes.
360 AliasAnalysis::ModRefResult
361 AliasAnalysis::getModRefInfo(const AtomicCmpXchgInst *CX, const Location &Loc) {
362 // Acquire/Release cmpxchg has properties that matter for arbitrary addresses.
363 if (CX->getSuccessOrdering() > Monotonic)
366 // If the cmpxchg address does not alias the location, it does not access it.
367 if (!alias(getLocation(CX), Loc))
373 AliasAnalysis::ModRefResult
374 AliasAnalysis::getModRefInfo(const AtomicRMWInst *RMW, const Location &Loc) {
375 // Acquire/Release atomicrmw has properties that matter for arbitrary addresses.
376 if (RMW->getOrdering() > Monotonic)
379 // If the atomicrmw address does not alias the location, it does not access it.
380 if (!alias(getLocation(RMW), Loc))
387 /// Only find pointer captures which happen before the given instruction. Uses
388 /// the dominator tree to determine whether one instruction is before another.
389 /// Only support the case where the Value is defined in the same basic block
390 /// as the given instruction and the use.
391 struct CapturesBefore : public CaptureTracker {
392 CapturesBefore(const Instruction *I, DominatorTree *DT)
393 : BeforeHere(I), DT(DT), Captured(false) {}
395 void tooManyUses() override { Captured = true; }
397 bool shouldExplore(const Use *U) override {
398 Instruction *I = cast<Instruction>(U->getUser());
399 BasicBlock *BB = I->getParent();
400 // We explore this usage only if the usage can reach "BeforeHere".
401 // If use is not reachable from entry, there is no need to explore.
402 if (BeforeHere != I && !DT->isReachableFromEntry(BB))
404 // If the value is defined in the same basic block as use and BeforeHere,
405 // there is no need to explore the use if BeforeHere dominates use.
406 // Check whether there is a path from I to BeforeHere.
407 if (BeforeHere != I && DT->dominates(BeforeHere, I) &&
408 !isPotentiallyReachable(I, BeforeHere, DT))
413 bool captured(const Use *U) override {
414 Instruction *I = cast<Instruction>(U->getUser());
415 BasicBlock *BB = I->getParent();
416 // Same logic as in shouldExplore.
417 if (BeforeHere != I && !DT->isReachableFromEntry(BB))
419 if (BeforeHere != I && DT->dominates(BeforeHere, I) &&
420 !isPotentiallyReachable(I, BeforeHere, DT))
426 const Instruction *BeforeHere;
433 // FIXME: this is really just shoring-up a deficiency in alias analysis.
434 // BasicAA isn't willing to spend linear time determining whether an alloca
435 // was captured before or after this particular call, while we are. However,
436 // with a smarter AA in place, this test is just wasting compile time.
437 AliasAnalysis::ModRefResult
438 AliasAnalysis::callCapturesBefore(const Instruction *I,
439 const AliasAnalysis::Location &MemLoc,
441 if (!DT || !DL) return AliasAnalysis::ModRef;
443 const Value *Object = GetUnderlyingObject(MemLoc.Ptr, DL);
444 if (!isIdentifiedObject(Object) || isa<GlobalValue>(Object) ||
445 isa<Constant>(Object))
446 return AliasAnalysis::ModRef;
448 ImmutableCallSite CS(I);
449 if (!CS.getInstruction() || CS.getInstruction() == Object)
450 return AliasAnalysis::ModRef;
452 CapturesBefore CB(I, DT);
453 llvm::PointerMayBeCaptured(Object, &CB);
455 return AliasAnalysis::ModRef;
458 AliasAnalysis::ModRefResult R = AliasAnalysis::NoModRef;
459 for (ImmutableCallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
460 CI != CE; ++CI, ++ArgNo) {
461 // Only look at the no-capture or byval pointer arguments. If this
462 // pointer were passed to arguments that were neither of these, then it
463 // couldn't be no-capture.
464 if (!(*CI)->getType()->isPointerTy() ||
465 (!CS.doesNotCapture(ArgNo) && !CS.isByValArgument(ArgNo)))
468 // If this is a no-capture pointer argument, see if we can tell that it
469 // is impossible to alias the pointer we're checking. If not, we have to
470 // assume that the call could touch the pointer, even though it doesn't
472 if (isNoAlias(AliasAnalysis::Location(*CI),
473 AliasAnalysis::Location(Object)))
475 if (CS.doesNotAccessMemory(ArgNo))
477 if (CS.onlyReadsMemory(ArgNo)) {
478 R = AliasAnalysis::Ref;
481 return AliasAnalysis::ModRef;
486 // AliasAnalysis destructor: DO NOT move this to the header file for
487 // AliasAnalysis or else clients of the AliasAnalysis class may not depend on
488 // the AliasAnalysis.o file in the current .a file, causing alias analysis
489 // support to not be included in the tool correctly!
491 AliasAnalysis::~AliasAnalysis() {}
493 /// InitializeAliasAnalysis - Subclasses must call this method to initialize the
494 /// AliasAnalysis interface before any other methods are called.
496 void AliasAnalysis::InitializeAliasAnalysis(Pass *P) {
497 DataLayoutPass *DLP = P->getAnalysisIfAvailable<DataLayoutPass>();
498 DL = DLP ? &DLP->getDataLayout() : nullptr;
499 TLI = P->getAnalysisIfAvailable<TargetLibraryInfo>();
500 AA = &P->getAnalysis<AliasAnalysis>();
503 // getAnalysisUsage - All alias analysis implementations should invoke this
504 // directly (using AliasAnalysis::getAnalysisUsage(AU)).
505 void AliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
506 AU.addRequired<AliasAnalysis>(); // All AA's chain
509 /// getTypeStoreSize - Return the DataLayout store size for the given type,
510 /// if known, or a conservative value otherwise.
512 uint64_t AliasAnalysis::getTypeStoreSize(Type *Ty) {
513 return DL ? DL->getTypeStoreSize(Ty) : UnknownSize;
516 /// canBasicBlockModify - Return true if it is possible for execution of the
517 /// specified basic block to modify the value pointed to by Ptr.
519 bool AliasAnalysis::canBasicBlockModify(const BasicBlock &BB,
520 const Location &Loc) {
521 return canInstructionRangeModify(BB.front(), BB.back(), Loc);
524 /// canInstructionRangeModify - Return true if it is possible for the execution
525 /// of the specified instructions to modify the value pointed to by Ptr. The
526 /// instructions to consider are all of the instructions in the range of [I1,I2]
527 /// INCLUSIVE. I1 and I2 must be in the same basic block.
529 bool AliasAnalysis::canInstructionRangeModify(const Instruction &I1,
530 const Instruction &I2,
531 const Location &Loc) {
532 assert(I1.getParent() == I2.getParent() &&
533 "Instructions not in same basic block!");
534 BasicBlock::const_iterator I = &I1;
535 BasicBlock::const_iterator E = &I2;
536 ++E; // Convert from inclusive to exclusive range.
538 for (; I != E; ++I) // Check every instruction in range
539 if (getModRefInfo(I, Loc) & Mod)
544 /// isNoAliasCall - Return true if this pointer is returned by a noalias
546 bool llvm::isNoAliasCall(const Value *V) {
547 if (isa<CallInst>(V) || isa<InvokeInst>(V))
548 return ImmutableCallSite(cast<Instruction>(V))
549 .paramHasAttr(0, Attribute::NoAlias);
553 /// isNoAliasArgument - Return true if this is an argument with the noalias
555 bool llvm::isNoAliasArgument(const Value *V)
557 if (const Argument *A = dyn_cast<Argument>(V))
558 return A->hasNoAliasAttr();
562 /// isIdentifiedObject - Return true if this pointer refers to a distinct and
563 /// identifiable object. This returns true for:
564 /// Global Variables and Functions (but not Global Aliases)
565 /// Allocas and Mallocs
566 /// ByVal and NoAlias Arguments
569 bool llvm::isIdentifiedObject(const Value *V) {
570 if (isa<AllocaInst>(V))
572 if (isa<GlobalValue>(V) && !isa<GlobalAlias>(V))
574 if (isNoAliasCall(V))
576 if (const Argument *A = dyn_cast<Argument>(V))
577 return A->hasNoAliasAttr() || A->hasByValAttr();