1 //===- BasicAliasAnalysis.cpp - Local Alias Analysis Impl -----------------===//
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 defines the default implementation of the Alias Analysis interface
11 // that simply implements a few identities (two different globals cannot alias,
12 // etc), but otherwise does no analysis.
14 //===----------------------------------------------------------------------===//
16 #include "llvm/Analysis/AliasAnalysis.h"
17 #include "llvm/Analysis/Passes.h"
18 #include "llvm/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Function.h"
21 #include "llvm/GlobalVariable.h"
22 #include "llvm/Instructions.h"
23 #include "llvm/IntrinsicInst.h"
24 #include "llvm/Operator.h"
25 #include "llvm/Pass.h"
26 #include "llvm/Analysis/CaptureTracking.h"
27 #include "llvm/Analysis/MemoryBuiltins.h"
28 #include "llvm/Analysis/ValueTracking.h"
29 #include "llvm/Target/TargetData.h"
30 #include "llvm/ADT/SmallPtrSet.h"
31 #include "llvm/ADT/SmallVector.h"
32 #include "llvm/Support/ErrorHandling.h"
36 //===----------------------------------------------------------------------===//
38 //===----------------------------------------------------------------------===//
40 /// isKnownNonNull - Return true if we know that the specified value is never
42 static bool isKnownNonNull(const Value *V) {
43 // Alloca never returns null, malloc might.
44 if (isa<AllocaInst>(V)) return true;
46 // A byval argument is never null.
47 if (const Argument *A = dyn_cast<Argument>(V))
48 return A->hasByValAttr();
50 // Global values are not null unless extern weak.
51 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
52 return !GV->hasExternalWeakLinkage();
56 /// isNonEscapingLocalObject - Return true if the pointer is to a function-local
57 /// object that never escapes from the function.
58 static bool isNonEscapingLocalObject(const Value *V, bool Interprocedural) {
59 // If this is a local allocation, check to see if it escapes.
60 if (isa<AllocaInst>(V) ||
61 (!Interprocedural && isNoAliasCall(V)))
62 // Set StoreCaptures to True so that we can assume in our callers that the
63 // pointer is not the result of a load instruction. Currently
64 // PointerMayBeCaptured doesn't have any special analysis for the
65 // StoreCaptures=false case; if it did, our callers could be refined to be
67 return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
69 // If this is an argument that corresponds to a byval or noalias argument,
70 // then it has not escaped before entering the function. Check if it escapes
71 // inside the function.
73 if (const Argument *A = dyn_cast<Argument>(V))
74 if (A->hasByValAttr() || A->hasNoAliasAttr()) {
75 // Don't bother analyzing arguments already known not to escape.
76 if (A->hasNoCaptureAttr())
78 return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
83 /// isEscapeSource - Return true if the pointer is one which would have
84 /// been considered an escape by isNonEscapingLocalObject.
85 static bool isEscapeSource(const Value *V, bool Interprocedural) {
87 if (isa<CallInst>(V) || isa<InvokeInst>(V) || isa<Argument>(V))
90 // The load case works because isNonEscapingLocalObject considers all
91 // stores to be escapes (it passes true for the StoreCaptures argument
92 // to PointerMayBeCaptured).
99 /// isObjectSmallerThan - Return true if we can prove that the object specified
100 /// by V is smaller than Size.
101 static bool isObjectSmallerThan(const Value *V, unsigned Size,
102 const TargetData &TD) {
103 const Type *AccessTy;
104 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
105 AccessTy = GV->getType()->getElementType();
106 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
107 if (!AI->isArrayAllocation())
108 AccessTy = AI->getType()->getElementType();
111 } else if (const CallInst* CI = extractMallocCall(V)) {
112 if (!isArrayMalloc(V, &TD))
113 // The size is the argument to the malloc call.
114 if (const ConstantInt* C = dyn_cast<ConstantInt>(CI->getArgOperand(0)))
115 return (C->getZExtValue() < Size);
117 } else if (const Argument *A = dyn_cast<Argument>(V)) {
118 if (A->hasByValAttr())
119 AccessTy = cast<PointerType>(A->getType())->getElementType();
126 if (AccessTy->isSized())
127 return TD.getTypeAllocSize(AccessTy) < Size;
131 //===----------------------------------------------------------------------===//
133 //===----------------------------------------------------------------------===//
136 /// NoAA - This class implements the -no-aa pass, which always returns "I
137 /// don't know" for alias queries. NoAA is unlike other alias analysis
138 /// implementations, in that it does not chain to a previous analysis. As
139 /// such it doesn't follow many of the rules that other alias analyses must.
141 struct NoAA : public ImmutablePass, public AliasAnalysis {
142 static char ID; // Class identification, replacement for typeinfo
143 NoAA() : ImmutablePass(&ID) {}
144 explicit NoAA(void *PID) : ImmutablePass(PID) { }
146 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
149 virtual void initializePass() {
150 TD = getAnalysisIfAvailable<TargetData>();
153 virtual AliasResult alias(const Value *V1, unsigned V1Size,
154 const Value *V2, unsigned V2Size) {
158 virtual void getArgumentAccesses(Function *F, CallSite CS,
159 std::vector<PointerAccessInfo> &Info) {
160 llvm_unreachable("This method may not be called on this function!");
163 virtual bool pointsToConstantMemory(const Value *P) { return false; }
164 virtual ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size) {
167 virtual ModRefResult getModRefInfo(CallSite CS1, CallSite CS2) {
171 virtual void deleteValue(Value *V) {}
172 virtual void copyValue(Value *From, Value *To) {}
174 /// getAdjustedAnalysisPointer - This method is used when a pass implements
175 /// an analysis interface through multiple inheritance. If needed, it should
176 /// override this to adjust the this pointer as needed for the specified pass
178 virtual void *getAdjustedAnalysisPointer(const PassInfo *PI) {
179 if (PI->isPassID(&AliasAnalysis::ID))
180 return (AliasAnalysis*)this;
184 } // End of anonymous namespace
186 // Register this pass...
188 static RegisterPass<NoAA>
189 U("no-aa", "No Alias Analysis (always returns 'may' alias)", true, true);
191 // Declare that we implement the AliasAnalysis interface
192 static RegisterAnalysisGroup<AliasAnalysis> V(U);
194 ImmutablePass *llvm::createNoAAPass() { return new NoAA(); }
196 //===----------------------------------------------------------------------===//
197 // BasicAliasAnalysis Pass
198 //===----------------------------------------------------------------------===//
200 static const Function *getParent(const Value *V) {
201 if(const Instruction *inst = dyn_cast<Instruction>(V))
202 return inst->getParent()->getParent();
204 if(const Argument *arg = dyn_cast<Argument>(V))
205 return arg->getParent();
210 static bool sameParent(const Value *O1, const Value *O2) {
212 const Function *F1 = getParent(O1);
213 const Function *F2 = getParent(O2);
215 return !F1 || !F2 || F1 == F2;
219 /// BasicAliasAnalysis - This is the default alias analysis implementation.
220 /// Because it doesn't chain to a previous alias analysis (like -no-aa), it
221 /// derives from the NoAA class.
222 struct BasicAliasAnalysis : public NoAA {
223 /// Interprocedural - Flag for "interprocedural" mode, where we must
224 /// support queries of values which live in different functions.
225 bool Interprocedural;
227 static char ID; // Class identification, replacement for typeinfo
229 : NoAA(&ID), Interprocedural(false) {}
230 BasicAliasAnalysis(void *PID, bool interprocedural)
231 : NoAA(PID), Interprocedural(interprocedural) {}
233 AliasResult alias(const Value *V1, unsigned V1Size,
234 const Value *V2, unsigned V2Size) {
235 assert(Visited.empty() && "Visited must be cleared after use!");
237 assert((Interprocedural || sameParent(V1, V2)) &&
238 "BasicAliasAnalysis (-basicaa) doesn't support interprocedural "
239 "queries; use InterproceduralAliasAnalysis "
240 "(-interprocedural-basic-aa) instead.");
242 AliasResult Alias = aliasCheck(V1, V1Size, V2, V2Size);
247 ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
248 ModRefResult getModRefInfo(CallSite CS1, CallSite CS2);
250 /// pointsToConstantMemory - Chase pointers until we find a (constant
252 bool pointsToConstantMemory(const Value *P);
254 /// getAdjustedAnalysisPointer - This method is used when a pass implements
255 /// an analysis interface through multiple inheritance. If needed, it should
256 /// override this to adjust the this pointer as needed for the specified pass
258 virtual void *getAdjustedAnalysisPointer(const PassInfo *PI) {
259 if (PI->isPassID(&AliasAnalysis::ID))
260 return (AliasAnalysis*)this;
265 // Visited - Track instructions visited by a aliasPHI, aliasSelect(), and aliasGEP().
266 SmallPtrSet<const Value*, 16> Visited;
268 // aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP
269 // instruction against another.
270 AliasResult aliasGEP(const GEPOperator *V1, unsigned V1Size,
271 const Value *V2, unsigned V2Size,
272 const Value *UnderlyingV1, const Value *UnderlyingV2);
274 // aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI
275 // instruction against another.
276 AliasResult aliasPHI(const PHINode *PN, unsigned PNSize,
277 const Value *V2, unsigned V2Size);
279 /// aliasSelect - Disambiguate a Select instruction against another value.
280 AliasResult aliasSelect(const SelectInst *SI, unsigned SISize,
281 const Value *V2, unsigned V2Size);
283 AliasResult aliasCheck(const Value *V1, unsigned V1Size,
284 const Value *V2, unsigned V2Size);
286 } // End of anonymous namespace
288 // Register this pass...
289 char BasicAliasAnalysis::ID = 0;
290 static RegisterPass<BasicAliasAnalysis>
291 X("basicaa", "Basic Alias Analysis (default AA impl)", false, true);
293 // Declare that we implement the AliasAnalysis interface
294 static RegisterAnalysisGroup<AliasAnalysis, true> Y(X);
296 ImmutablePass *llvm::createBasicAliasAnalysisPass() {
297 return new BasicAliasAnalysis();
301 /// pointsToConstantMemory - Chase pointers until we find a (constant
303 bool BasicAliasAnalysis::pointsToConstantMemory(const Value *P) {
304 if (const GlobalVariable *GV =
305 dyn_cast<GlobalVariable>(P->getUnderlyingObject()))
306 // Note: this doesn't require GV to be "ODR" because it isn't legal for a
307 // global to be marked constant in some modules and non-constant in others.
308 // GV may even be a declaration, not a definition.
309 return GV->isConstant();
314 /// getModRefInfo - Check to see if the specified callsite can clobber the
315 /// specified memory object. Since we only look at local properties of this
316 /// function, we really can't say much about this query. We do, however, use
317 /// simple "address taken" analysis on local objects.
318 AliasAnalysis::ModRefResult
319 BasicAliasAnalysis::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
320 const Value *Object = P->getUnderlyingObject();
322 // If this is a tail call and P points to a stack location, we know that
323 // the tail call cannot access or modify the local stack.
324 // We cannot exclude byval arguments here; these belong to the caller of
325 // the current function not to the current function, and a tail callee
326 // may reference them.
327 if (isa<AllocaInst>(Object))
328 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction()))
329 if (CI->isTailCall())
332 // If the pointer is to a locally allocated object that does not escape,
333 // then the call can not mod/ref the pointer unless the call takes the pointer
334 // as an argument, and itself doesn't capture it.
335 if (!isa<Constant>(Object) && CS.getInstruction() != Object &&
336 isNonEscapingLocalObject(Object, Interprocedural)) {
337 bool PassedAsArg = false;
339 for (CallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
340 CI != CE; ++CI, ++ArgNo) {
341 // Only look at the no-capture pointer arguments.
342 if (!(*CI)->getType()->isPointerTy() ||
343 !CS.paramHasAttr(ArgNo+1, Attribute::NoCapture))
346 // If this is a no-capture pointer argument, see if we can tell that it
347 // is impossible to alias the pointer we're checking. If not, we have to
348 // assume that the call could touch the pointer, even though it doesn't
350 if (!isNoAlias(cast<Value>(CI), ~0U, P, ~0U)) {
360 // Finally, handle specific knowledge of intrinsics.
361 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction());
363 return AliasAnalysis::getModRefInfo(CS, P, Size);
365 switch (II->getIntrinsicID()) {
367 case Intrinsic::memcpy:
368 case Intrinsic::memmove: {
370 if (ConstantInt *LenCI = dyn_cast<ConstantInt>(II->getArgOperand(2)))
371 Len = LenCI->getZExtValue();
372 Value *Dest = II->getArgOperand(0);
373 Value *Src = II->getArgOperand(1);
374 if (isNoAlias(Dest, Len, P, Size)) {
375 if (isNoAlias(Src, Len, P, Size))
381 case Intrinsic::memset:
382 // Since memset is 'accesses arguments' only, the AliasAnalysis base class
383 // will handle it for the variable length case.
384 if (ConstantInt *LenCI = dyn_cast<ConstantInt>(II->getArgOperand(2))) {
385 unsigned Len = LenCI->getZExtValue();
386 Value *Dest = II->getArgOperand(0);
387 if (isNoAlias(Dest, Len, P, Size))
391 case Intrinsic::atomic_cmp_swap:
392 case Intrinsic::atomic_swap:
393 case Intrinsic::atomic_load_add:
394 case Intrinsic::atomic_load_sub:
395 case Intrinsic::atomic_load_and:
396 case Intrinsic::atomic_load_nand:
397 case Intrinsic::atomic_load_or:
398 case Intrinsic::atomic_load_xor:
399 case Intrinsic::atomic_load_max:
400 case Intrinsic::atomic_load_min:
401 case Intrinsic::atomic_load_umax:
402 case Intrinsic::atomic_load_umin:
404 Value *Op1 = II->getArgOperand(0);
405 unsigned Op1Size = TD->getTypeStoreSize(Op1->getType());
406 if (isNoAlias(Op1, Op1Size, P, Size))
410 case Intrinsic::lifetime_start:
411 case Intrinsic::lifetime_end:
412 case Intrinsic::invariant_start: {
413 unsigned PtrSize = cast<ConstantInt>(II->getArgOperand(0))->getZExtValue();
414 if (isNoAlias(II->getArgOperand(1), PtrSize, P, Size))
418 case Intrinsic::invariant_end: {
419 unsigned PtrSize = cast<ConstantInt>(II->getArgOperand(1))->getZExtValue();
420 if (isNoAlias(II->getArgOperand(2), PtrSize, P, Size))
426 // The AliasAnalysis base class has some smarts, lets use them.
427 return AliasAnalysis::getModRefInfo(CS, P, Size);
431 AliasAnalysis::ModRefResult
432 BasicAliasAnalysis::getModRefInfo(CallSite CS1, CallSite CS2) {
433 // If CS1 or CS2 are readnone, they don't interact.
434 ModRefBehavior CS1B = AliasAnalysis::getModRefBehavior(CS1);
435 if (CS1B == DoesNotAccessMemory) return NoModRef;
437 ModRefBehavior CS2B = AliasAnalysis::getModRefBehavior(CS2);
438 if (CS2B == DoesNotAccessMemory) return NoModRef;
440 // If they both only read from memory, just return ref.
441 if (CS1B == OnlyReadsMemory && CS2B == OnlyReadsMemory)
444 // Otherwise, fall back to NoAA (mod+ref).
445 return NoAA::getModRefInfo(CS1, CS2);
448 /// GetIndiceDifference - Dest and Src are the variable indices from two
449 /// decomposed GetElementPtr instructions GEP1 and GEP2 which have common base
450 /// pointers. Subtract the GEP2 indices from GEP1 to find the symbolic
451 /// difference between the two pointers.
452 static void GetIndiceDifference(
453 SmallVectorImpl<std::pair<const Value*, int64_t> > &Dest,
454 const SmallVectorImpl<std::pair<const Value*, int64_t> > &Src) {
455 if (Src.empty()) return;
457 for (unsigned i = 0, e = Src.size(); i != e; ++i) {
458 const Value *V = Src[i].first;
459 int64_t Scale = Src[i].second;
461 // Find V in Dest. This is N^2, but pointer indices almost never have more
462 // than a few variable indexes.
463 for (unsigned j = 0, e = Dest.size(); j != e; ++j) {
464 if (Dest[j].first != V) continue;
466 // If we found it, subtract off Scale V's from the entry in Dest. If it
467 // goes to zero, remove the entry.
468 if (Dest[j].second != Scale)
469 Dest[j].second -= Scale;
471 Dest.erase(Dest.begin()+j);
476 // If we didn't consume this entry, add it to the end of the Dest list.
478 Dest.push_back(std::make_pair(V, -Scale));
482 /// aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP instruction
483 /// against another pointer. We know that V1 is a GEP, but we don't know
484 /// anything about V2. UnderlyingV1 is GEP1->getUnderlyingObject(),
485 /// UnderlyingV2 is the same for V2.
487 AliasAnalysis::AliasResult
488 BasicAliasAnalysis::aliasGEP(const GEPOperator *GEP1, unsigned V1Size,
489 const Value *V2, unsigned V2Size,
490 const Value *UnderlyingV1,
491 const Value *UnderlyingV2) {
492 // If this GEP has been visited before, we're on a use-def cycle.
493 // Such cycles are only valid when PHI nodes are involved or in unreachable
494 // code. The visitPHI function catches cycles containing PHIs, but there
495 // could still be a cycle without PHIs in unreachable code.
496 if (!Visited.insert(GEP1))
499 int64_t GEP1BaseOffset;
500 SmallVector<std::pair<const Value*, int64_t>, 4> GEP1VariableIndices;
502 // If we have two gep instructions with must-alias'ing base pointers, figure
503 // out if the indexes to the GEP tell us anything about the derived pointer.
504 if (const GEPOperator *GEP2 = dyn_cast<GEPOperator>(V2)) {
505 // Do the base pointers alias?
506 AliasResult BaseAlias = aliasCheck(UnderlyingV1, ~0U, UnderlyingV2, ~0U);
508 // If we get a No or May, then return it immediately, no amount of analysis
509 // will improve this situation.
510 if (BaseAlias != MustAlias) return BaseAlias;
512 // Otherwise, we have a MustAlias. Since the base pointers alias each other
513 // exactly, see if the computed offset from the common pointer tells us
514 // about the relation of the resulting pointer.
515 const Value *GEP1BasePtr =
516 DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices, TD);
518 int64_t GEP2BaseOffset;
519 SmallVector<std::pair<const Value*, int64_t>, 4> GEP2VariableIndices;
520 const Value *GEP2BasePtr =
521 DecomposeGEPExpression(GEP2, GEP2BaseOffset, GEP2VariableIndices, TD);
523 // If DecomposeGEPExpression isn't able to look all the way through the
524 // addressing operation, we must not have TD and this is too complex for us
525 // to handle without it.
526 if (GEP1BasePtr != UnderlyingV1 || GEP2BasePtr != UnderlyingV2) {
528 "DecomposeGEPExpression and getUnderlyingObject disagree!");
532 // Subtract the GEP2 pointer from the GEP1 pointer to find out their
533 // symbolic difference.
534 GEP1BaseOffset -= GEP2BaseOffset;
535 GetIndiceDifference(GEP1VariableIndices, GEP2VariableIndices);
538 // Check to see if these two pointers are related by the getelementptr
539 // instruction. If one pointer is a GEP with a non-zero index of the other
540 // pointer, we know they cannot alias.
542 // If both accesses are unknown size, we can't do anything useful here.
543 if (V1Size == ~0U && V2Size == ~0U)
546 AliasResult R = aliasCheck(UnderlyingV1, ~0U, V2, V2Size);
548 // If V2 may alias GEP base pointer, conservatively returns MayAlias.
549 // If V2 is known not to alias GEP base pointer, then the two values
550 // cannot alias per GEP semantics: "A pointer value formed from a
551 // getelementptr instruction is associated with the addresses associated
552 // with the first operand of the getelementptr".
555 const Value *GEP1BasePtr =
556 DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices, TD);
558 // If DecomposeGEPExpression isn't able to look all the way through the
559 // addressing operation, we must not have TD and this is too complex for us
560 // to handle without it.
561 if (GEP1BasePtr != UnderlyingV1) {
563 "DecomposeGEPExpression and getUnderlyingObject disagree!");
568 // In the two GEP Case, if there is no difference in the offsets of the
569 // computed pointers, the resultant pointers are a must alias. This
570 // hapens when we have two lexically identical GEP's (for example).
572 // In the other case, if we have getelementptr <ptr>, 0, 0, 0, 0, ... and V2
573 // must aliases the GEP, the end result is a must alias also.
574 if (GEP1BaseOffset == 0 && GEP1VariableIndices.empty())
577 // If we have a known constant offset, see if this offset is larger than the
578 // access size being queried. If so, and if no variable indices can remove
579 // pieces of this constant, then we know we have a no-alias. For example,
582 // In order to handle cases like &A[100][i] where i is an out of range
583 // subscript, we have to ignore all constant offset pieces that are a multiple
584 // of a scaled index. Do this by removing constant offsets that are a
585 // multiple of any of our variable indices. This allows us to transform
586 // things like &A[i][1] because i has a stride of (e.g.) 8 bytes but the 1
587 // provides an offset of 4 bytes (assuming a <= 4 byte access).
588 for (unsigned i = 0, e = GEP1VariableIndices.size();
589 i != e && GEP1BaseOffset;++i)
590 if (int64_t RemovedOffset = GEP1BaseOffset/GEP1VariableIndices[i].second)
591 GEP1BaseOffset -= RemovedOffset*GEP1VariableIndices[i].second;
593 // If our known offset is bigger than the access size, we know we don't have
595 if (GEP1BaseOffset) {
596 if (GEP1BaseOffset >= (int64_t)V2Size ||
597 GEP1BaseOffset <= -(int64_t)V1Size)
604 /// aliasSelect - Provide a bunch of ad-hoc rules to disambiguate a Select
605 /// instruction against another.
606 AliasAnalysis::AliasResult
607 BasicAliasAnalysis::aliasSelect(const SelectInst *SI, unsigned SISize,
608 const Value *V2, unsigned V2Size) {
609 // If this select has been visited before, we're on a use-def cycle.
610 // Such cycles are only valid when PHI nodes are involved or in unreachable
611 // code. The visitPHI function catches cycles containing PHIs, but there
612 // could still be a cycle without PHIs in unreachable code.
613 if (!Visited.insert(SI))
616 // If the values are Selects with the same condition, we can do a more precise
617 // check: just check for aliases between the values on corresponding arms.
618 if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2))
619 if (SI->getCondition() == SI2->getCondition()) {
621 aliasCheck(SI->getTrueValue(), SISize,
622 SI2->getTrueValue(), V2Size);
623 if (Alias == MayAlias)
625 AliasResult ThisAlias =
626 aliasCheck(SI->getFalseValue(), SISize,
627 SI2->getFalseValue(), V2Size);
628 if (ThisAlias != Alias)
633 // If both arms of the Select node NoAlias or MustAlias V2, then returns
634 // NoAlias / MustAlias. Otherwise, returns MayAlias.
636 aliasCheck(V2, V2Size, SI->getTrueValue(), SISize);
637 if (Alias == MayAlias)
640 // If V2 is visited, the recursive case will have been caught in the
641 // above aliasCheck call, so these subsequent calls to aliasCheck
642 // don't need to assume that V2 is being visited recursively.
645 AliasResult ThisAlias =
646 aliasCheck(V2, V2Size, SI->getFalseValue(), SISize);
647 if (ThisAlias != Alias)
652 // aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI instruction
654 AliasAnalysis::AliasResult
655 BasicAliasAnalysis::aliasPHI(const PHINode *PN, unsigned PNSize,
656 const Value *V2, unsigned V2Size) {
657 // The PHI node has already been visited, avoid recursion any further.
658 if (!Visited.insert(PN))
661 // If the values are PHIs in the same block, we can do a more precise
662 // as well as efficient check: just check for aliases between the values
663 // on corresponding edges.
664 if (const PHINode *PN2 = dyn_cast<PHINode>(V2))
665 if (PN2->getParent() == PN->getParent()) {
667 aliasCheck(PN->getIncomingValue(0), PNSize,
668 PN2->getIncomingValueForBlock(PN->getIncomingBlock(0)),
670 if (Alias == MayAlias)
672 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
673 AliasResult ThisAlias =
674 aliasCheck(PN->getIncomingValue(i), PNSize,
675 PN2->getIncomingValueForBlock(PN->getIncomingBlock(i)),
677 if (ThisAlias != Alias)
683 SmallPtrSet<Value*, 4> UniqueSrc;
684 SmallVector<Value*, 4> V1Srcs;
685 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
686 Value *PV1 = PN->getIncomingValue(i);
687 if (isa<PHINode>(PV1))
688 // If any of the source itself is a PHI, return MayAlias conservatively
689 // to avoid compile time explosion. The worst possible case is if both
690 // sides are PHI nodes. In which case, this is O(m x n) time where 'm'
691 // and 'n' are the number of PHI sources.
693 if (UniqueSrc.insert(PV1))
694 V1Srcs.push_back(PV1);
697 AliasResult Alias = aliasCheck(V2, V2Size, V1Srcs[0], PNSize);
698 // Early exit if the check of the first PHI source against V2 is MayAlias.
699 // Other results are not possible.
700 if (Alias == MayAlias)
703 // If all sources of the PHI node NoAlias or MustAlias V2, then returns
704 // NoAlias / MustAlias. Otherwise, returns MayAlias.
705 for (unsigned i = 1, e = V1Srcs.size(); i != e; ++i) {
706 Value *V = V1Srcs[i];
708 // If V2 is visited, the recursive case will have been caught in the
709 // above aliasCheck call, so these subsequent calls to aliasCheck
710 // don't need to assume that V2 is being visited recursively.
713 AliasResult ThisAlias = aliasCheck(V2, V2Size, V, PNSize);
714 if (ThisAlias != Alias || ThisAlias == MayAlias)
721 // aliasCheck - Provide a bunch of ad-hoc rules to disambiguate in common cases,
722 // such as array references.
724 AliasAnalysis::AliasResult
725 BasicAliasAnalysis::aliasCheck(const Value *V1, unsigned V1Size,
726 const Value *V2, unsigned V2Size) {
727 // If either of the memory references is empty, it doesn't matter what the
728 // pointer values are.
729 if (V1Size == 0 || V2Size == 0)
732 // Strip off any casts if they exist.
733 V1 = V1->stripPointerCasts();
734 V2 = V2->stripPointerCasts();
736 // Are we checking for alias of the same value?
737 if (V1 == V2) return MustAlias;
739 if (!V1->getType()->isPointerTy() || !V2->getType()->isPointerTy())
740 return NoAlias; // Scalars cannot alias each other
742 // Figure out what objects these things are pointing to if we can.
743 const Value *O1 = V1->getUnderlyingObject();
744 const Value *O2 = V2->getUnderlyingObject();
746 // Null values in the default address space don't point to any object, so they
747 // don't alias any other pointer.
748 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O1))
749 if (CPN->getType()->getAddressSpace() == 0)
751 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O2))
752 if (CPN->getType()->getAddressSpace() == 0)
756 // If V1/V2 point to two different objects we know that we have no alias.
757 if (isIdentifiedObject(O1, Interprocedural) &&
758 isIdentifiedObject(O2, Interprocedural))
761 // Constant pointers can't alias with non-const isIdentifiedObject objects.
762 if ((isa<Constant>(O1) &&
763 isIdentifiedObject(O2, Interprocedural) &&
764 !isa<Constant>(O2)) ||
765 (isa<Constant>(O2) &&
766 isIdentifiedObject(O1, Interprocedural) &&
770 // Arguments can't alias with local allocations or noalias calls, unless
771 // we have to consider interprocedural aliasing.
772 if (!Interprocedural)
773 if ((isa<Argument>(O1) && (isa<AllocaInst>(O2) || isNoAliasCall(O2))) ||
774 (isa<Argument>(O2) && (isa<AllocaInst>(O1) || isNoAliasCall(O1))))
777 // Most objects can't alias null.
778 if ((isa<ConstantPointerNull>(V2) && isKnownNonNull(O1)) ||
779 (isa<ConstantPointerNull>(V1) && isKnownNonNull(O2)))
783 // If the size of one access is larger than the entire object on the other
784 // side, then we know such behavior is undefined and can assume no alias.
786 if ((V1Size != ~0U && isObjectSmallerThan(O2, V1Size, *TD)) ||
787 (V2Size != ~0U && isObjectSmallerThan(O1, V2Size, *TD)))
790 // If one pointer is the result of a call/invoke or load and the other is a
791 // non-escaping local object, then we know the object couldn't escape to a
792 // point where the call could return it.
794 if (isEscapeSource(O1, Interprocedural) &&
795 isNonEscapingLocalObject(O2, Interprocedural))
797 if (isEscapeSource(O2, Interprocedural) &&
798 isNonEscapingLocalObject(O1, Interprocedural))
802 // FIXME: This isn't aggressively handling alias(GEP, PHI) for example: if the
803 // GEP can't simplify, we don't even look at the PHI cases.
804 if (!isa<GEPOperator>(V1) && isa<GEPOperator>(V2)) {
806 std::swap(V1Size, V2Size);
809 if (const GEPOperator *GV1 = dyn_cast<GEPOperator>(V1))
810 return aliasGEP(GV1, V1Size, V2, V2Size, O1, O2);
812 if (isa<PHINode>(V2) && !isa<PHINode>(V1)) {
814 std::swap(V1Size, V2Size);
816 if (const PHINode *PN = dyn_cast<PHINode>(V1))
817 return aliasPHI(PN, V1Size, V2, V2Size);
819 if (isa<SelectInst>(V2) && !isa<SelectInst>(V1)) {
821 std::swap(V1Size, V2Size);
823 if (const SelectInst *S1 = dyn_cast<SelectInst>(V1))
824 return aliasSelect(S1, V1Size, V2, V2Size);
829 // Make sure that anything that uses AliasAnalysis pulls in this file.
830 DEFINING_FILE_FOR(BasicAliasAnalysis)
832 //===----------------------------------------------------------------------===//
833 // InterproceduralBasicAliasAnalysis Pass
834 //===----------------------------------------------------------------------===//
837 /// InterproceduralBasicAliasAnalysis - This is similar to basicaa, except
838 /// that it properly supports queries to values which live in different
841 /// Note that we don't currently take this to the extreme, analyzing all
842 /// call sites of a function to answer a query about an Argument.
844 struct InterproceduralBasicAliasAnalysis : public BasicAliasAnalysis {
845 static char ID; // Class identification, replacement for typeinfo
846 InterproceduralBasicAliasAnalysis() : BasicAliasAnalysis(&ID, true) {}
850 // Register this pass...
851 char InterproceduralBasicAliasAnalysis::ID = 0;
852 static RegisterPass<InterproceduralBasicAliasAnalysis>
853 W("interprocedural-basic-aa", "Interprocedural Basic Alias Analysis", false, true);
855 // Declare that we implement the AliasAnalysis interface
856 static RegisterAnalysisGroup<AliasAnalysis> Z(W);
858 ImmutablePass *llvm::createInterproceduralBasicAliasAnalysisPass() {
859 return new InterproceduralBasicAliasAnalysis();