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) {
59 // If this is a local allocation, check to see if it escapes.
60 if (isa<AllocaInst>(V) || isNoAliasCall(V))
61 // Set StoreCaptures to True so that we can assume in our callers that the
62 // pointer is not the result of a load instruction. Currently
63 // PointerMayBeCaptured doesn't have any special analysis for the
64 // StoreCaptures=false case; if it did, our callers could be refined to be
66 return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
68 // If this is an argument that corresponds to a byval or noalias argument,
69 // then it has not escaped before entering the function. Check if it escapes
70 // inside the function.
71 if (const Argument *A = dyn_cast<Argument>(V))
72 if (A->hasByValAttr() || A->hasNoAliasAttr()) {
73 // Don't bother analyzing arguments already known not to escape.
74 if (A->hasNoCaptureAttr())
76 return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
81 /// isEscapeSource - Return true if the pointer is one which would have
82 /// been considered an escape by isNonEscapingLocalObject.
83 static bool isEscapeSource(const Value *V) {
84 if (isa<CallInst>(V) || isa<InvokeInst>(V) || isa<Argument>(V))
87 // The load case works because isNonEscapingLocalObject considers all
88 // stores to be escapes (it passes true for the StoreCaptures argument
89 // to PointerMayBeCaptured).
96 /// isObjectSmallerThan - Return true if we can prove that the object specified
97 /// by V is smaller than Size.
98 static bool isObjectSmallerThan(const Value *V, unsigned Size,
99 const TargetData &TD) {
100 const Type *AccessTy;
101 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
102 AccessTy = GV->getType()->getElementType();
103 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
104 if (!AI->isArrayAllocation())
105 AccessTy = AI->getType()->getElementType();
108 } else if (const CallInst* CI = extractMallocCall(V)) {
109 if (!isArrayMalloc(V, &TD))
110 // The size is the argument to the malloc call.
111 if (const ConstantInt* C = dyn_cast<ConstantInt>(CI->getArgOperand(0)))
112 return (C->getZExtValue() < Size);
114 } else if (const Argument *A = dyn_cast<Argument>(V)) {
115 if (A->hasByValAttr())
116 AccessTy = cast<PointerType>(A->getType())->getElementType();
123 if (AccessTy->isSized())
124 return TD.getTypeAllocSize(AccessTy) < Size;
128 //===----------------------------------------------------------------------===//
130 //===----------------------------------------------------------------------===//
133 /// NoAA - This class implements the -no-aa pass, which always returns "I
134 /// don't know" for alias queries. NoAA is unlike other alias analysis
135 /// implementations, in that it does not chain to a previous analysis. As
136 /// such it doesn't follow many of the rules that other alias analyses must.
138 struct NoAA : public ImmutablePass, public AliasAnalysis {
139 static char ID; // Class identification, replacement for typeinfo
140 NoAA() : ImmutablePass(&ID) {}
141 explicit NoAA(void *PID) : ImmutablePass(PID) { }
143 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
146 virtual void initializePass() {
147 TD = getAnalysisIfAvailable<TargetData>();
150 virtual AliasResult alias(const Value *V1, unsigned V1Size,
151 const Value *V2, unsigned V2Size) {
155 virtual bool pointsToConstantMemory(const Value *P) { return false; }
156 virtual ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size) {
159 virtual ModRefResult getModRefInfo(CallSite CS1, CallSite CS2) {
163 virtual void deleteValue(Value *V) {}
164 virtual void copyValue(Value *From, Value *To) {}
166 /// getAdjustedAnalysisPointer - This method is used when a pass implements
167 /// an analysis interface through multiple inheritance. If needed, it should
168 /// override this to adjust the this pointer as needed for the specified pass
170 virtual void *getAdjustedAnalysisPointer(const PassInfo *PI) {
171 if (PI->isPassID(&AliasAnalysis::ID))
172 return (AliasAnalysis*)this;
176 } // End of anonymous namespace
178 // Register this pass...
180 INITIALIZE_AG_PASS(NoAA, AliasAnalysis, "no-aa",
181 "No Alias Analysis (always returns 'may' alias)",
184 ImmutablePass *llvm::createNoAAPass() { return new NoAA(); }
186 //===----------------------------------------------------------------------===//
187 // BasicAliasAnalysis Pass
188 //===----------------------------------------------------------------------===//
191 static const Function *getParent(const Value *V) {
192 if (const Instruction *inst = dyn_cast<Instruction>(V))
193 return inst->getParent()->getParent();
195 if (const Argument *arg = dyn_cast<Argument>(V))
196 return arg->getParent();
201 static bool notDifferentParent(const Value *O1, const Value *O2) {
203 const Function *F1 = getParent(O1);
204 const Function *F2 = getParent(O2);
206 return !F1 || !F2 || F1 == F2;
211 /// BasicAliasAnalysis - This is the default alias analysis implementation.
212 /// Because it doesn't chain to a previous alias analysis (like -no-aa), it
213 /// derives from the NoAA class.
214 struct BasicAliasAnalysis : public NoAA {
215 static char ID; // Class identification, replacement for typeinfo
216 BasicAliasAnalysis() : NoAA(&ID) {}
218 AliasResult alias(const Value *V1, unsigned V1Size,
219 const Value *V2, unsigned V2Size) {
220 assert(Visited.empty() && "Visited must be cleared after use!");
221 assert(notDifferentParent(V1, V2) &&
222 "BasicAliasAnalysis doesn't support interprocedural queries.");
223 AliasResult Alias = aliasCheck(V1, V1Size, V2, V2Size);
228 ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
229 ModRefResult getModRefInfo(CallSite CS1, CallSite CS2);
231 /// pointsToConstantMemory - Chase pointers until we find a (constant
233 bool pointsToConstantMemory(const Value *P);
235 /// getAdjustedAnalysisPointer - This method is used when a pass implements
236 /// an analysis interface through multiple inheritance. If needed, it should
237 /// override this to adjust the this pointer as needed for the specified pass
239 virtual void *getAdjustedAnalysisPointer(const PassInfo *PI) {
240 if (PI->isPassID(&AliasAnalysis::ID))
241 return (AliasAnalysis*)this;
246 // Visited - Track instructions visited by a aliasPHI, aliasSelect(), and aliasGEP().
247 SmallPtrSet<const Value*, 16> Visited;
249 // aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP
250 // instruction against another.
251 AliasResult aliasGEP(const GEPOperator *V1, unsigned V1Size,
252 const Value *V2, unsigned V2Size,
253 const Value *UnderlyingV1, const Value *UnderlyingV2);
255 // aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI
256 // instruction against another.
257 AliasResult aliasPHI(const PHINode *PN, unsigned PNSize,
258 const Value *V2, unsigned V2Size);
260 /// aliasSelect - Disambiguate a Select instruction against another value.
261 AliasResult aliasSelect(const SelectInst *SI, unsigned SISize,
262 const Value *V2, unsigned V2Size);
264 AliasResult aliasCheck(const Value *V1, unsigned V1Size,
265 const Value *V2, unsigned V2Size);
267 } // End of anonymous namespace
269 // Register this pass...
270 char BasicAliasAnalysis::ID = 0;
271 INITIALIZE_AG_PASS(BasicAliasAnalysis, AliasAnalysis, "basicaa",
272 "Basic Alias Analysis (default AA impl)",
275 ImmutablePass *llvm::createBasicAliasAnalysisPass() {
276 return new BasicAliasAnalysis();
280 /// pointsToConstantMemory - Chase pointers until we find a (constant
282 bool BasicAliasAnalysis::pointsToConstantMemory(const Value *P) {
283 if (const GlobalVariable *GV =
284 dyn_cast<GlobalVariable>(P->getUnderlyingObject()))
285 // Note: this doesn't require GV to be "ODR" because it isn't legal for a
286 // global to be marked constant in some modules and non-constant in others.
287 // GV may even be a declaration, not a definition.
288 return GV->isConstant();
293 /// getModRefInfo - Check to see if the specified callsite can clobber the
294 /// specified memory object. Since we only look at local properties of this
295 /// function, we really can't say much about this query. We do, however, use
296 /// simple "address taken" analysis on local objects.
297 AliasAnalysis::ModRefResult
298 BasicAliasAnalysis::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
299 assert(notDifferentParent(CS.getInstruction(), P) &&
300 "AliasAnalysis query involving multiple functions!");
302 const Value *Object = P->getUnderlyingObject();
304 // If this is a tail call and P points to a stack location, we know that
305 // the tail call cannot access or modify the local stack.
306 // We cannot exclude byval arguments here; these belong to the caller of
307 // the current function not to the current function, and a tail callee
308 // may reference them.
309 if (isa<AllocaInst>(Object))
310 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction()))
311 if (CI->isTailCall())
314 // If the pointer is to a locally allocated object that does not escape,
315 // then the call can not mod/ref the pointer unless the call takes the pointer
316 // as an argument, and itself doesn't capture it.
317 if (!isa<Constant>(Object) && CS.getInstruction() != Object &&
318 isNonEscapingLocalObject(Object)) {
319 bool PassedAsArg = false;
321 for (CallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
322 CI != CE; ++CI, ++ArgNo) {
323 // Only look at the no-capture pointer arguments.
324 if (!(*CI)->getType()->isPointerTy() ||
325 !CS.paramHasAttr(ArgNo+1, Attribute::NoCapture))
328 // If this is a no-capture pointer argument, see if we can tell that it
329 // is impossible to alias the pointer we're checking. If not, we have to
330 // assume that the call could touch the pointer, even though it doesn't
332 if (!isNoAlias(cast<Value>(CI), UnknownSize, P, UnknownSize)) {
342 // Finally, handle specific knowledge of intrinsics.
343 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction());
345 return AliasAnalysis::getModRefInfo(CS, P, Size);
347 switch (II->getIntrinsicID()) {
349 case Intrinsic::memcpy:
350 case Intrinsic::memmove: {
351 unsigned Len = UnknownSize;
352 if (ConstantInt *LenCI = dyn_cast<ConstantInt>(II->getArgOperand(2)))
353 Len = LenCI->getZExtValue();
354 Value *Dest = II->getArgOperand(0);
355 Value *Src = II->getArgOperand(1);
356 if (isNoAlias(Dest, Len, P, Size)) {
357 if (isNoAlias(Src, Len, P, Size))
363 case Intrinsic::memset:
364 // Since memset is 'accesses arguments' only, the AliasAnalysis base class
365 // will handle it for the variable length case.
366 if (ConstantInt *LenCI = dyn_cast<ConstantInt>(II->getArgOperand(2))) {
367 unsigned Len = LenCI->getZExtValue();
368 Value *Dest = II->getArgOperand(0);
369 if (isNoAlias(Dest, Len, P, Size))
373 case Intrinsic::atomic_cmp_swap:
374 case Intrinsic::atomic_swap:
375 case Intrinsic::atomic_load_add:
376 case Intrinsic::atomic_load_sub:
377 case Intrinsic::atomic_load_and:
378 case Intrinsic::atomic_load_nand:
379 case Intrinsic::atomic_load_or:
380 case Intrinsic::atomic_load_xor:
381 case Intrinsic::atomic_load_max:
382 case Intrinsic::atomic_load_min:
383 case Intrinsic::atomic_load_umax:
384 case Intrinsic::atomic_load_umin:
386 Value *Op1 = II->getArgOperand(0);
387 unsigned Op1Size = TD->getTypeStoreSize(Op1->getType());
388 if (isNoAlias(Op1, Op1Size, P, Size))
392 case Intrinsic::lifetime_start:
393 case Intrinsic::lifetime_end:
394 case Intrinsic::invariant_start: {
395 unsigned PtrSize = cast<ConstantInt>(II->getArgOperand(0))->getZExtValue();
396 if (isNoAlias(II->getArgOperand(1), PtrSize, P, Size))
400 case Intrinsic::invariant_end: {
401 unsigned PtrSize = cast<ConstantInt>(II->getArgOperand(1))->getZExtValue();
402 if (isNoAlias(II->getArgOperand(2), PtrSize, P, Size))
408 // The AliasAnalysis base class has some smarts, lets use them.
409 return AliasAnalysis::getModRefInfo(CS, P, Size);
413 AliasAnalysis::ModRefResult
414 BasicAliasAnalysis::getModRefInfo(CallSite CS1, CallSite CS2) {
415 // If CS1 or CS2 are readnone, they don't interact.
416 ModRefBehavior CS1B = AliasAnalysis::getModRefBehavior(CS1);
417 if (CS1B == DoesNotAccessMemory) return NoModRef;
419 ModRefBehavior CS2B = AliasAnalysis::getModRefBehavior(CS2);
420 if (CS2B == DoesNotAccessMemory) return NoModRef;
422 // If they both only read from memory, just return ref.
423 if (CS1B == OnlyReadsMemory && CS2B == OnlyReadsMemory)
426 // Otherwise, fall back to NoAA (mod+ref).
427 return NoAA::getModRefInfo(CS1, CS2);
430 /// GetIndiceDifference - Dest and Src are the variable indices from two
431 /// decomposed GetElementPtr instructions GEP1 and GEP2 which have common base
432 /// pointers. Subtract the GEP2 indices from GEP1 to find the symbolic
433 /// difference between the two pointers.
434 static void GetIndiceDifference(
435 SmallVectorImpl<std::pair<const Value*, int64_t> > &Dest,
436 const SmallVectorImpl<std::pair<const Value*, int64_t> > &Src) {
437 if (Src.empty()) return;
439 for (unsigned i = 0, e = Src.size(); i != e; ++i) {
440 const Value *V = Src[i].first;
441 int64_t Scale = Src[i].second;
443 // Find V in Dest. This is N^2, but pointer indices almost never have more
444 // than a few variable indexes.
445 for (unsigned j = 0, e = Dest.size(); j != e; ++j) {
446 if (Dest[j].first != V) continue;
448 // If we found it, subtract off Scale V's from the entry in Dest. If it
449 // goes to zero, remove the entry.
450 if (Dest[j].second != Scale)
451 Dest[j].second -= Scale;
453 Dest.erase(Dest.begin()+j);
458 // If we didn't consume this entry, add it to the end of the Dest list.
460 Dest.push_back(std::make_pair(V, -Scale));
464 /// aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP instruction
465 /// against another pointer. We know that V1 is a GEP, but we don't know
466 /// anything about V2. UnderlyingV1 is GEP1->getUnderlyingObject(),
467 /// UnderlyingV2 is the same for V2.
469 AliasAnalysis::AliasResult
470 BasicAliasAnalysis::aliasGEP(const GEPOperator *GEP1, unsigned V1Size,
471 const Value *V2, unsigned V2Size,
472 const Value *UnderlyingV1,
473 const Value *UnderlyingV2) {
474 // If this GEP has been visited before, we're on a use-def cycle.
475 // Such cycles are only valid when PHI nodes are involved or in unreachable
476 // code. The visitPHI function catches cycles containing PHIs, but there
477 // could still be a cycle without PHIs in unreachable code.
478 if (!Visited.insert(GEP1))
481 int64_t GEP1BaseOffset;
482 SmallVector<std::pair<const Value*, int64_t>, 4> GEP1VariableIndices;
484 // If we have two gep instructions with must-alias'ing base pointers, figure
485 // out if the indexes to the GEP tell us anything about the derived pointer.
486 if (const GEPOperator *GEP2 = dyn_cast<GEPOperator>(V2)) {
487 // Do the base pointers alias?
488 AliasResult BaseAlias = aliasCheck(UnderlyingV1, UnknownSize,
489 UnderlyingV2, UnknownSize);
491 // If we get a No or May, then return it immediately, no amount of analysis
492 // will improve this situation.
493 if (BaseAlias != MustAlias) return BaseAlias;
495 // Otherwise, we have a MustAlias. Since the base pointers alias each other
496 // exactly, see if the computed offset from the common pointer tells us
497 // about the relation of the resulting pointer.
498 const Value *GEP1BasePtr =
499 DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices, TD);
501 int64_t GEP2BaseOffset;
502 SmallVector<std::pair<const Value*, int64_t>, 4> GEP2VariableIndices;
503 const Value *GEP2BasePtr =
504 DecomposeGEPExpression(GEP2, GEP2BaseOffset, GEP2VariableIndices, TD);
506 // If DecomposeGEPExpression isn't able to look all the way through the
507 // addressing operation, we must not have TD and this is too complex for us
508 // to handle without it.
509 if (GEP1BasePtr != UnderlyingV1 || GEP2BasePtr != UnderlyingV2) {
511 "DecomposeGEPExpression and getUnderlyingObject disagree!");
515 // Subtract the GEP2 pointer from the GEP1 pointer to find out their
516 // symbolic difference.
517 GEP1BaseOffset -= GEP2BaseOffset;
518 GetIndiceDifference(GEP1VariableIndices, GEP2VariableIndices);
521 // Check to see if these two pointers are related by the getelementptr
522 // instruction. If one pointer is a GEP with a non-zero index of the other
523 // pointer, we know they cannot alias.
525 // If both accesses are unknown size, we can't do anything useful here.
526 if (V1Size == UnknownSize && V2Size == UnknownSize)
529 AliasResult R = aliasCheck(UnderlyingV1, UnknownSize, V2, V2Size);
531 // If V2 may alias GEP base pointer, conservatively returns MayAlias.
532 // If V2 is known not to alias GEP base pointer, then the two values
533 // cannot alias per GEP semantics: "A pointer value formed from a
534 // getelementptr instruction is associated with the addresses associated
535 // with the first operand of the getelementptr".
538 const Value *GEP1BasePtr =
539 DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices, TD);
541 // If DecomposeGEPExpression isn't able to look all the way through the
542 // addressing operation, we must not have TD and this is too complex for us
543 // to handle without it.
544 if (GEP1BasePtr != UnderlyingV1) {
546 "DecomposeGEPExpression and getUnderlyingObject disagree!");
551 // In the two GEP Case, if there is no difference in the offsets of the
552 // computed pointers, the resultant pointers are a must alias. This
553 // hapens when we have two lexically identical GEP's (for example).
555 // In the other case, if we have getelementptr <ptr>, 0, 0, 0, 0, ... and V2
556 // must aliases the GEP, the end result is a must alias also.
557 if (GEP1BaseOffset == 0 && GEP1VariableIndices.empty())
560 // If we have a known constant offset, see if this offset is larger than the
561 // access size being queried. If so, and if no variable indices can remove
562 // pieces of this constant, then we know we have a no-alias. For example,
565 // In order to handle cases like &A[100][i] where i is an out of range
566 // subscript, we have to ignore all constant offset pieces that are a multiple
567 // of a scaled index. Do this by removing constant offsets that are a
568 // multiple of any of our variable indices. This allows us to transform
569 // things like &A[i][1] because i has a stride of (e.g.) 8 bytes but the 1
570 // provides an offset of 4 bytes (assuming a <= 4 byte access).
571 for (unsigned i = 0, e = GEP1VariableIndices.size();
572 i != e && GEP1BaseOffset;++i)
573 if (int64_t RemovedOffset = GEP1BaseOffset/GEP1VariableIndices[i].second)
574 GEP1BaseOffset -= RemovedOffset*GEP1VariableIndices[i].second;
576 // If our known offset is bigger than the access size, we know we don't have
578 if (GEP1BaseOffset) {
579 if (GEP1BaseOffset >= (int64_t)V2Size ||
580 GEP1BaseOffset <= -(int64_t)V1Size)
587 /// aliasSelect - Provide a bunch of ad-hoc rules to disambiguate a Select
588 /// instruction against another.
589 AliasAnalysis::AliasResult
590 BasicAliasAnalysis::aliasSelect(const SelectInst *SI, unsigned SISize,
591 const Value *V2, unsigned V2Size) {
592 // If this select has been visited before, we're on a use-def cycle.
593 // Such cycles are only valid when PHI nodes are involved or in unreachable
594 // code. The visitPHI function catches cycles containing PHIs, but there
595 // could still be a cycle without PHIs in unreachable code.
596 if (!Visited.insert(SI))
599 // If the values are Selects with the same condition, we can do a more precise
600 // check: just check for aliases between the values on corresponding arms.
601 if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2))
602 if (SI->getCondition() == SI2->getCondition()) {
604 aliasCheck(SI->getTrueValue(), SISize,
605 SI2->getTrueValue(), V2Size);
606 if (Alias == MayAlias)
608 AliasResult ThisAlias =
609 aliasCheck(SI->getFalseValue(), SISize,
610 SI2->getFalseValue(), V2Size);
611 if (ThisAlias != Alias)
616 // If both arms of the Select node NoAlias or MustAlias V2, then returns
617 // NoAlias / MustAlias. Otherwise, returns MayAlias.
619 aliasCheck(V2, V2Size, SI->getTrueValue(), SISize);
620 if (Alias == MayAlias)
623 // If V2 is visited, the recursive case will have been caught in the
624 // above aliasCheck call, so these subsequent calls to aliasCheck
625 // don't need to assume that V2 is being visited recursively.
628 AliasResult ThisAlias =
629 aliasCheck(V2, V2Size, SI->getFalseValue(), SISize);
630 if (ThisAlias != Alias)
635 // aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI instruction
637 AliasAnalysis::AliasResult
638 BasicAliasAnalysis::aliasPHI(const PHINode *PN, unsigned PNSize,
639 const Value *V2, unsigned V2Size) {
640 // The PHI node has already been visited, avoid recursion any further.
641 if (!Visited.insert(PN))
644 // If the values are PHIs in the same block, we can do a more precise
645 // as well as efficient check: just check for aliases between the values
646 // on corresponding edges.
647 if (const PHINode *PN2 = dyn_cast<PHINode>(V2))
648 if (PN2->getParent() == PN->getParent()) {
650 aliasCheck(PN->getIncomingValue(0), PNSize,
651 PN2->getIncomingValueForBlock(PN->getIncomingBlock(0)),
653 if (Alias == MayAlias)
655 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
656 AliasResult ThisAlias =
657 aliasCheck(PN->getIncomingValue(i), PNSize,
658 PN2->getIncomingValueForBlock(PN->getIncomingBlock(i)),
660 if (ThisAlias != Alias)
666 SmallPtrSet<Value*, 4> UniqueSrc;
667 SmallVector<Value*, 4> V1Srcs;
668 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
669 Value *PV1 = PN->getIncomingValue(i);
670 if (isa<PHINode>(PV1))
671 // If any of the source itself is a PHI, return MayAlias conservatively
672 // to avoid compile time explosion. The worst possible case is if both
673 // sides are PHI nodes. In which case, this is O(m x n) time where 'm'
674 // and 'n' are the number of PHI sources.
676 if (UniqueSrc.insert(PV1))
677 V1Srcs.push_back(PV1);
680 AliasResult Alias = aliasCheck(V2, V2Size, V1Srcs[0], PNSize);
681 // Early exit if the check of the first PHI source against V2 is MayAlias.
682 // Other results are not possible.
683 if (Alias == MayAlias)
686 // If all sources of the PHI node NoAlias or MustAlias V2, then returns
687 // NoAlias / MustAlias. Otherwise, returns MayAlias.
688 for (unsigned i = 1, e = V1Srcs.size(); i != e; ++i) {
689 Value *V = V1Srcs[i];
691 // If V2 is visited, the recursive case will have been caught in the
692 // above aliasCheck call, so these subsequent calls to aliasCheck
693 // don't need to assume that V2 is being visited recursively.
696 AliasResult ThisAlias = aliasCheck(V2, V2Size, V, PNSize);
697 if (ThisAlias != Alias || ThisAlias == MayAlias)
704 // aliasCheck - Provide a bunch of ad-hoc rules to disambiguate in common cases,
705 // such as array references.
707 AliasAnalysis::AliasResult
708 BasicAliasAnalysis::aliasCheck(const Value *V1, unsigned V1Size,
709 const Value *V2, unsigned V2Size) {
710 // If either of the memory references is empty, it doesn't matter what the
711 // pointer values are.
712 if (V1Size == 0 || V2Size == 0)
715 // Strip off any casts if they exist.
716 V1 = V1->stripPointerCasts();
717 V2 = V2->stripPointerCasts();
719 // Are we checking for alias of the same value?
720 if (V1 == V2) return MustAlias;
722 if (!V1->getType()->isPointerTy() || !V2->getType()->isPointerTy())
723 return NoAlias; // Scalars cannot alias each other
725 // Figure out what objects these things are pointing to if we can.
726 const Value *O1 = V1->getUnderlyingObject();
727 const Value *O2 = V2->getUnderlyingObject();
729 // Null values in the default address space don't point to any object, so they
730 // don't alias any other pointer.
731 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O1))
732 if (CPN->getType()->getAddressSpace() == 0)
734 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O2))
735 if (CPN->getType()->getAddressSpace() == 0)
739 // If V1/V2 point to two different objects we know that we have no alias.
740 if (isIdentifiedObject(O1) && isIdentifiedObject(O2))
743 // Constant pointers can't alias with non-const isIdentifiedObject objects.
744 if ((isa<Constant>(O1) && isIdentifiedObject(O2) && !isa<Constant>(O2)) ||
745 (isa<Constant>(O2) && isIdentifiedObject(O1) && !isa<Constant>(O1)))
748 // Arguments can't alias with local allocations or noalias calls
749 // in the same function.
750 if (((isa<Argument>(O1) && (isa<AllocaInst>(O2) || isNoAliasCall(O2))) ||
751 (isa<Argument>(O2) && (isa<AllocaInst>(O1) || isNoAliasCall(O1)))))
754 // Most objects can't alias null.
755 if ((isa<ConstantPointerNull>(O2) && isKnownNonNull(O1)) ||
756 (isa<ConstantPointerNull>(O1) && isKnownNonNull(O2)))
759 // If one pointer is the result of a call/invoke or load and the other is a
760 // non-escaping local object within the same function, then we know the
761 // object couldn't escape to a point where the call could return it.
763 // Note that if the pointers are in different functions, there are a
764 // variety of complications. A call with a nocapture argument may still
765 // temporary store the nocapture argument's value in a temporary memory
766 // location if that memory location doesn't escape. Or it may pass a
767 // nocapture value to other functions as long as they don't capture it.
768 if (isEscapeSource(O1) && isNonEscapingLocalObject(O2))
770 if (isEscapeSource(O2) && isNonEscapingLocalObject(O1))
774 // If the size of one access is larger than the entire object on the other
775 // side, then we know such behavior is undefined and can assume no alias.
777 if ((V1Size != UnknownSize && isObjectSmallerThan(O2, V1Size, *TD)) ||
778 (V2Size != UnknownSize && isObjectSmallerThan(O1, V2Size, *TD)))
781 // FIXME: This isn't aggressively handling alias(GEP, PHI) for example: if the
782 // GEP can't simplify, we don't even look at the PHI cases.
783 if (!isa<GEPOperator>(V1) && isa<GEPOperator>(V2)) {
785 std::swap(V1Size, V2Size);
788 if (const GEPOperator *GV1 = dyn_cast<GEPOperator>(V1))
789 return aliasGEP(GV1, V1Size, V2, V2Size, O1, O2);
791 if (isa<PHINode>(V2) && !isa<PHINode>(V1)) {
793 std::swap(V1Size, V2Size);
795 if (const PHINode *PN = dyn_cast<PHINode>(V1))
796 return aliasPHI(PN, V1Size, V2, V2Size);
798 if (isa<SelectInst>(V2) && !isa<SelectInst>(V1)) {
800 std::swap(V1Size, V2Size);
802 if (const SelectInst *S1 = dyn_cast<SelectInst>(V1))
803 return aliasSelect(S1, V1Size, V2, V2Size);
808 // Make sure that anything that uses AliasAnalysis pulls in this file.
809 DEFINING_FILE_FOR(BasicAliasAnalysis)