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/CaptureTracking.h"
18 #include "llvm/Analysis/MemoryBuiltins.h"
19 #include "llvm/Analysis/Passes.h"
20 #include "llvm/Constants.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Function.h"
23 #include "llvm/GlobalAlias.h"
24 #include "llvm/GlobalVariable.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/IntrinsicInst.h"
27 #include "llvm/Operator.h"
28 #include "llvm/Pass.h"
29 #include "llvm/Target/TargetData.h"
30 #include "llvm/ADT/SmallSet.h"
31 #include "llvm/ADT/SmallVector.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/GetElementPtrTypeIterator.h"
38 //===----------------------------------------------------------------------===//
40 //===----------------------------------------------------------------------===//
42 /// isKnownNonNull - Return true if we know that the specified value is never
44 static bool isKnownNonNull(const Value *V) {
45 // Alloca never returns null, malloc might.
46 if (isa<AllocaInst>(V)) return true;
48 // A byval argument is never null.
49 if (const Argument *A = dyn_cast<Argument>(V))
50 return A->hasByValAttr();
52 // Global values are not null unless extern weak.
53 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
54 return !GV->hasExternalWeakLinkage();
58 /// isNonEscapingLocalObject - Return true if the pointer is to a function-local
59 /// object that never escapes from the function.
60 static bool isNonEscapingLocalObject(const Value *V) {
61 // If this is a local allocation, check to see if it escapes.
62 if (isa<AllocaInst>(V) || isNoAliasCall(V))
63 // Set StoreCaptures to True so that we can assume in our callers that the
64 // pointer is not the result of a load instruction. Currently
65 // PointerMayBeCaptured doesn't have any special analysis for the
66 // StoreCaptures=false case; if it did, our callers could be refined to be
68 return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
70 // If this is an argument that corresponds to a byval or noalias argument,
71 // then it has not escaped before entering the function. Check if it escapes
72 // 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);
84 /// isObjectSmallerThan - Return true if we can prove that the object specified
85 /// by V is smaller than Size.
86 static bool isObjectSmallerThan(const Value *V, unsigned Size,
87 const TargetData &TD) {
89 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
90 AccessTy = GV->getType()->getElementType();
91 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
92 if (!AI->isArrayAllocation())
93 AccessTy = AI->getType()->getElementType();
96 } else if (const CallInst* CI = extractMallocCall(V)) {
97 if (!isArrayMalloc(V, &TD))
98 // The size is the argument to the malloc call.
99 if (const ConstantInt* C = dyn_cast<ConstantInt>(CI->getOperand(1)))
100 return (C->getZExtValue() < Size);
102 } else if (const Argument *A = dyn_cast<Argument>(V)) {
103 if (A->hasByValAttr())
104 AccessTy = cast<PointerType>(A->getType())->getElementType();
111 if (AccessTy->isSized())
112 return TD.getTypeAllocSize(AccessTy) < Size;
116 //===----------------------------------------------------------------------===//
118 //===----------------------------------------------------------------------===//
121 /// NoAA - This class implements the -no-aa pass, which always returns "I
122 /// don't know" for alias queries. NoAA is unlike other alias analysis
123 /// implementations, in that it does not chain to a previous analysis. As
124 /// such it doesn't follow many of the rules that other alias analyses must.
126 struct NoAA : public ImmutablePass, public AliasAnalysis {
127 static char ID; // Class identification, replacement for typeinfo
128 NoAA() : ImmutablePass(&ID) {}
129 explicit NoAA(void *PID) : ImmutablePass(PID) { }
131 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
134 virtual void initializePass() {
135 TD = getAnalysisIfAvailable<TargetData>();
138 virtual AliasResult alias(const Value *V1, unsigned V1Size,
139 const Value *V2, unsigned V2Size) {
143 virtual void getArgumentAccesses(Function *F, CallSite CS,
144 std::vector<PointerAccessInfo> &Info) {
145 llvm_unreachable("This method may not be called on this function!");
148 virtual bool pointsToConstantMemory(const Value *P) { return false; }
149 virtual ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size) {
152 virtual ModRefResult getModRefInfo(CallSite CS1, CallSite CS2) {
156 virtual void deleteValue(Value *V) {}
157 virtual void copyValue(Value *From, Value *To) {}
159 } // End of anonymous namespace
161 // Register this pass...
163 static RegisterPass<NoAA>
164 U("no-aa", "No Alias Analysis (always returns 'may' alias)", true, true);
166 // Declare that we implement the AliasAnalysis interface
167 static RegisterAnalysisGroup<AliasAnalysis> V(U);
169 ImmutablePass *llvm::createNoAAPass() { return new NoAA(); }
171 //===----------------------------------------------------------------------===//
173 //===----------------------------------------------------------------------===//
176 /// BasicAliasAnalysis - This is the default alias analysis implementation.
177 /// Because it doesn't chain to a previous alias analysis (like -no-aa), it
178 /// derives from the NoAA class.
179 struct BasicAliasAnalysis : public NoAA {
180 static char ID; // Class identification, replacement for typeinfo
181 BasicAliasAnalysis() : NoAA(&ID) {}
182 AliasResult alias(const Value *V1, unsigned V1Size,
183 const Value *V2, unsigned V2Size) {
184 assert(VisitedPHIs.empty() && "VisitedPHIs must be cleared after use!");
185 AliasResult Alias = aliasCheck(V1, V1Size, V2, V2Size);
190 ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
191 ModRefResult getModRefInfo(CallSite CS1, CallSite CS2);
193 /// pointsToConstantMemory - Chase pointers until we find a (constant
195 bool pointsToConstantMemory(const Value *P);
198 // VisitedPHIs - Track PHI nodes visited by a aliasCheck() call.
199 SmallPtrSet<const Value*, 16> VisitedPHIs;
201 // aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP
202 // instruction against another.
203 AliasResult aliasGEP(const GEPOperator *V1, unsigned V1Size,
204 const Value *V2, unsigned V2Size,
205 const Value *UnderlyingV1, const Value *UnderlyingV2);
207 // aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI
208 // instruction against another.
209 AliasResult aliasPHI(const PHINode *PN, unsigned PNSize,
210 const Value *V2, unsigned V2Size);
212 /// aliasSelect - Disambiguate a Select instruction against another value.
213 AliasResult aliasSelect(const SelectInst *SI, unsigned SISize,
214 const Value *V2, unsigned V2Size);
216 AliasResult aliasCheck(const Value *V1, unsigned V1Size,
217 const Value *V2, unsigned V2Size);
219 } // End of anonymous namespace
221 // Register this pass...
222 char BasicAliasAnalysis::ID = 0;
223 static RegisterPass<BasicAliasAnalysis>
224 X("basicaa", "Basic Alias Analysis (default AA impl)", false, true);
226 // Declare that we implement the AliasAnalysis interface
227 static RegisterAnalysisGroup<AliasAnalysis, true> Y(X);
229 ImmutablePass *llvm::createBasicAliasAnalysisPass() {
230 return new BasicAliasAnalysis();
234 /// pointsToConstantMemory - Chase pointers until we find a (constant
236 bool BasicAliasAnalysis::pointsToConstantMemory(const Value *P) {
237 if (const GlobalVariable *GV =
238 dyn_cast<GlobalVariable>(P->getUnderlyingObject()))
239 // Note: this doesn't require GV to be "ODR" because it isn't legal for a
240 // global to be marked constant in some modules and non-constant in others.
241 // GV may even be a declaration, not a definition.
242 return GV->isConstant();
247 /// getModRefInfo - Check to see if the specified callsite can clobber the
248 /// specified memory object. Since we only look at local properties of this
249 /// function, we really can't say much about this query. We do, however, use
250 /// simple "address taken" analysis on local objects.
251 AliasAnalysis::ModRefResult
252 BasicAliasAnalysis::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
253 const Value *Object = P->getUnderlyingObject();
255 // If this is a tail call and P points to a stack location, we know that
256 // the tail call cannot access or modify the local stack.
257 // We cannot exclude byval arguments here; these belong to the caller of
258 // the current function not to the current function, and a tail callee
259 // may reference them.
260 if (isa<AllocaInst>(Object))
261 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction()))
262 if (CI->isTailCall())
265 // If the pointer is to a locally allocated object that does not escape,
266 // then the call can not mod/ref the pointer unless the call takes the pointer
267 // as an argument, and itself doesn't capture it.
268 if (!isa<Constant>(Object) && CS.getInstruction() != Object &&
269 isNonEscapingLocalObject(Object)) {
270 bool PassedAsArg = false;
272 for (CallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
273 CI != CE; ++CI, ++ArgNo) {
274 // Only look at the no-capture pointer arguments.
275 if (!isa<PointerType>((*CI)->getType()) ||
276 !CS.paramHasAttr(ArgNo+1, Attribute::NoCapture))
279 // If this is a no-capture pointer argument, see if we can tell that it
280 // is impossible to alias the pointer we're checking. If not, we have to
281 // assume that the call could touch the pointer, even though it doesn't
283 if (!isNoAlias(cast<Value>(CI), ~0U, P, ~0U)) {
293 // Finally, handle specific knowledge of intrinsics.
294 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction());
296 return AliasAnalysis::getModRefInfo(CS, P, Size);
298 switch (II->getIntrinsicID()) {
300 case Intrinsic::memcpy:
301 case Intrinsic::memmove: {
303 if (ConstantInt *LenCI = dyn_cast<ConstantInt>(II->getOperand(3)))
304 Len = LenCI->getZExtValue();
305 Value *Dest = II->getOperand(1);
306 Value *Src = II->getOperand(2);
307 if (isNoAlias(Dest, Len, P, Size)) {
308 if (isNoAlias(Src, Len, P, Size))
314 case Intrinsic::memset:
315 // Since memset is 'accesses arguments' only, the AliasAnalysis base class
316 // will handle it for the variable length case.
317 if (ConstantInt *LenCI = dyn_cast<ConstantInt>(II->getOperand(3))) {
318 unsigned Len = LenCI->getZExtValue();
319 Value *Dest = II->getOperand(1);
320 if (isNoAlias(Dest, Len, P, Size))
324 case Intrinsic::atomic_cmp_swap:
325 case Intrinsic::atomic_swap:
326 case Intrinsic::atomic_load_add:
327 case Intrinsic::atomic_load_sub:
328 case Intrinsic::atomic_load_and:
329 case Intrinsic::atomic_load_nand:
330 case Intrinsic::atomic_load_or:
331 case Intrinsic::atomic_load_xor:
332 case Intrinsic::atomic_load_max:
333 case Intrinsic::atomic_load_min:
334 case Intrinsic::atomic_load_umax:
335 case Intrinsic::atomic_load_umin:
337 Value *Op1 = II->getOperand(1);
338 unsigned Op1Size = TD->getTypeStoreSize(Op1->getType());
339 if (isNoAlias(Op1, Op1Size, P, Size))
343 case Intrinsic::lifetime_start:
344 case Intrinsic::lifetime_end:
345 case Intrinsic::invariant_start: {
346 unsigned PtrSize = cast<ConstantInt>(II->getOperand(1))->getZExtValue();
347 if (isNoAlias(II->getOperand(2), PtrSize, P, Size))
351 case Intrinsic::invariant_end: {
352 unsigned PtrSize = cast<ConstantInt>(II->getOperand(2))->getZExtValue();
353 if (isNoAlias(II->getOperand(3), PtrSize, P, Size))
359 // The AliasAnalysis base class has some smarts, lets use them.
360 return AliasAnalysis::getModRefInfo(CS, P, Size);
364 AliasAnalysis::ModRefResult
365 BasicAliasAnalysis::getModRefInfo(CallSite CS1, CallSite CS2) {
366 // If CS1 or CS2 are readnone, they don't interact.
367 ModRefBehavior CS1B = AliasAnalysis::getModRefBehavior(CS1);
368 if (CS1B == DoesNotAccessMemory) return NoModRef;
370 ModRefBehavior CS2B = AliasAnalysis::getModRefBehavior(CS2);
371 if (CS2B == DoesNotAccessMemory) return NoModRef;
373 // If they both only read from memory, just return ref.
374 if (CS1B == OnlyReadsMemory && CS2B == OnlyReadsMemory)
377 // Otherwise, fall back to NoAA (mod+ref).
378 return NoAA::getModRefInfo(CS1, CS2);
381 /// DecomposeGEPExpression - If V is a symbolic pointer expression, decompose it
382 /// into a base pointer with a constant offset and a number of scaled symbolic
385 /// When TargetData is around, this function is capable of analyzing everything
386 /// that Value::getUnderlyingObject() can look through. When not, it just looks
387 /// through pointer casts.
389 /// FIXME: Move this out to ValueTracking.cpp
391 static const Value *DecomposeGEPExpression(const Value *V, int64_t &BaseOffs,
392 SmallVectorImpl<std::pair<const Value*, int64_t> > &VarIndices,
393 const TargetData *TD) {
394 // FIXME: Should limit depth like getUnderlyingObject?
397 // See if this is a bitcast or GEP.
398 const Operator *Op = dyn_cast<Operator>(V);
400 // The only non-operator case we can handle are GlobalAliases.
401 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
402 if (!GA->mayBeOverridden()) {
403 V = GA->getAliasee();
410 if (Op->getOpcode() == Instruction::BitCast) {
411 V = Op->getOperand(0);
415 const GEPOperator *GEPOp = dyn_cast<GEPOperator>(Op);
419 // Don't attempt to analyze GEPs over unsized objects.
420 if (!cast<PointerType>(GEPOp->getOperand(0)->getType())
421 ->getElementType()->isSized())
424 // If we are lacking TargetData information, we can't compute the offets of
425 // elements computed by GEPs. However, we can handle bitcast equivalent
428 if (!GEPOp->hasAllZeroIndices())
430 V = GEPOp->getOperand(0);
434 // Walk the indices of the GEP, accumulating them into BaseOff/VarIndices.
435 gep_type_iterator GTI = gep_type_begin(GEPOp);
436 for (User::const_op_iterator I = next(GEPOp->op_begin()),
437 E = GEPOp->op_end(); I != E; ++I) {
439 // Compute the (potentially symbolic) offset in bytes for this index.
440 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
441 // For a struct, add the member offset.
442 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
443 if (FieldNo == 0) continue;
445 BaseOffs += TD->getStructLayout(STy)->getElementOffset(FieldNo);
449 // For an array/pointer, add the element offset, explicitly scaled.
450 if (ConstantInt *CIdx = dyn_cast<ConstantInt>(Index)) {
451 if (CIdx->isZero()) continue;
452 BaseOffs += TD->getTypeAllocSize(*GTI)*CIdx->getSExtValue();
456 // TODO: Could handle linear expressions here like A[X+1], also A[X*4|1].
457 uint64_t Scale = TD->getTypeAllocSize(*GTI);
459 // If we already had an occurrance of this index variable, merge this
460 // scale into it. For example, we want to handle:
461 // A[x][x] -> x*16 + x*4 -> x*20
462 // This also ensures that 'x' only appears in the index list once.
463 for (unsigned i = 0, e = VarIndices.size(); i != e; ++i) {
464 if (VarIndices[i].first == Index) {
465 Scale += VarIndices[i].second;
466 VarIndices.erase(VarIndices.begin()+i);
471 // Make sure that we have a scale that makes sense for this target's
473 if (unsigned ShiftBits = 64-TD->getPointerSizeInBits()) {
479 VarIndices.push_back(std::make_pair(Index, Scale));
482 // Analyze the base pointer next.
483 V = GEPOp->getOperand(0);
487 /// GetIndiceDifference - Dest and Src are the variable indices from two
488 /// decomposed GetElementPtr instructions GEP1 and GEP2 which have common base
489 /// pointers. Subtract the GEP2 indices from GEP1 to find the symbolic
490 /// difference between the two pointers.
491 static void GetIndiceDifference(
492 SmallVectorImpl<std::pair<const Value*, int64_t> > &Dest,
493 const SmallVectorImpl<std::pair<const Value*, int64_t> > &Src) {
494 if (Src.empty()) return;
496 for (unsigned i = 0, e = Src.size(); i != e; ++i) {
497 const Value *V = Src[i].first;
498 int64_t Scale = Src[i].second;
500 // Find V in Dest. This is N^2, but pointer indices almost never have more
501 // than a few variable indexes.
502 for (unsigned j = 0, e = Dest.size(); j != e; ++j) {
503 if (Dest[j].first != V) continue;
505 // If we found it, subtract off Scale V's from the entry in Dest. If it
506 // goes to zero, remove the entry.
507 if (Dest[j].second != Scale)
508 Dest[j].second -= Scale;
510 Dest.erase(Dest.begin()+j);
515 // If we didn't consume this entry, add it to the end of the Dest list.
517 Dest.push_back(std::make_pair(V, -Scale));
521 /// aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP instruction
522 /// against another pointer. We know that V1 is a GEP, but we don't know
523 /// anything about V2. UnderlyingV1 is GEP1->getUnderlyingObject(),
524 /// UnderlyingV2 is the same for V2.
526 AliasAnalysis::AliasResult
527 BasicAliasAnalysis::aliasGEP(const GEPOperator *GEP1, unsigned V1Size,
528 const Value *V2, unsigned V2Size,
529 const Value *UnderlyingV1,
530 const Value *UnderlyingV2) {
531 int64_t GEP1BaseOffset;
532 SmallVector<std::pair<const Value*, int64_t>, 4> GEP1VariableIndices;
534 // If we have two gep instructions with must-alias'ing base pointers, figure
535 // out if the indexes to the GEP tell us anything about the derived pointer.
536 if (const GEPOperator *GEP2 = dyn_cast<GEPOperator>(V2)) {
537 // Do the base pointers alias?
538 AliasResult BaseAlias = aliasCheck(UnderlyingV1, ~0U, UnderlyingV2, ~0U);
540 // If we get a No or May, then return it immediately, no amount of analysis
541 // will improve this situation.
542 if (BaseAlias != MustAlias) return BaseAlias;
544 // Otherwise, we have a MustAlias. Since the base pointers alias each other
545 // exactly, see if the computed offset from the common pointer tells us
546 // about the relation of the resulting pointer.
547 const Value *GEP1BasePtr =
548 DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices, TD);
550 int64_t GEP2BaseOffset;
551 SmallVector<std::pair<const Value*, int64_t>, 4> GEP2VariableIndices;
552 const Value *GEP2BasePtr =
553 DecomposeGEPExpression(GEP2, GEP2BaseOffset, GEP2VariableIndices, TD);
555 // If DecomposeGEPExpression isn't able to look all the way through the
556 // addressing operation, we must not have TD and this is too complex for us
557 // to handle without it.
558 if (GEP1BasePtr != UnderlyingV1 || GEP2BasePtr != UnderlyingV2) {
560 "DecomposeGEPExpression and getUnderlyingObject disagree!");
564 // Subtract the GEP2 pointer from the GEP1 pointer to find out their
565 // symbolic difference.
566 GEP1BaseOffset -= GEP2BaseOffset;
567 GetIndiceDifference(GEP1VariableIndices, GEP2VariableIndices);
570 // Check to see if these two pointers are related by the getelementptr
571 // instruction. If one pointer is a GEP with a non-zero index of the other
572 // pointer, we know they cannot alias.
574 // FIXME: The check below only looks at the size of one of the pointers, not
575 // both, this may cause us to miss things.
576 if (V1Size == ~0U || V2Size == ~0U)
579 AliasResult R = aliasCheck(UnderlyingV1, ~0U, V2, V2Size);
581 // If V2 may alias GEP base pointer, conservatively returns MayAlias.
582 // If V2 is known not to alias GEP base pointer, then the two values
583 // cannot alias per GEP semantics: "A pointer value formed from a
584 // getelementptr instruction is associated with the addresses associated
585 // with the first operand of the getelementptr".
588 const Value *GEP1BasePtr =
589 DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices, TD);
591 // If DecomposeGEPExpression isn't able to look all the way through the
592 // addressing operation, we must not have TD and this is too complex for us
593 // to handle without it.
594 if (GEP1BasePtr != UnderlyingV1) {
596 "DecomposeGEPExpression and getUnderlyingObject disagree!");
601 // In the two GEP Case, if there is no difference in the offsets of the
602 // computed pointers, the resultant pointers are a must alias. This
603 // hapens when we have two lexically identical GEP's (for example).
605 // In the other case, if we have getelementptr <ptr>, 0, 0, 0, 0, ... and V2
606 // must aliases the GEP, the end result is a must alias also.
607 if (GEP1BaseOffset == 0 && GEP1VariableIndices.empty())
610 // If we have a known constant offset, see if this offset is larger than the
611 // access size being queried. If so, and if no variable indices can remove
612 // pieces of this constant, then we know we have a no-alias. For example,
615 // In order to handle cases like &A[100][i] where i is an out of range
616 // subscript, we have to ignore all constant offset pieces that are a multiple
617 // of a scaled index. Do this by removing constant offsets that are a
618 // multiple of any of our variable indices. This allows us to transform
619 // things like &A[i][1] because i has a stride of (e.g.) 8 bytes but the 1
620 // provides an offset of 4 bytes (assuming a <= 4 byte access).
621 for (unsigned i = 0, e = GEP1VariableIndices.size();
622 i != e && GEP1BaseOffset;++i)
623 if (int64_t RemovedOffset = GEP1BaseOffset/GEP1VariableIndices[i].second)
624 GEP1BaseOffset -= RemovedOffset*GEP1VariableIndices[i].second;
626 // If our known offset is bigger than the access size, we know we don't have
628 if (GEP1BaseOffset) {
629 if (GEP1BaseOffset >= (int64_t)V2Size ||
630 GEP1BaseOffset <= -(int64_t)V1Size)
637 /// aliasSelect - Provide a bunch of ad-hoc rules to disambiguate a Select
638 /// instruction against another.
639 AliasAnalysis::AliasResult
640 BasicAliasAnalysis::aliasSelect(const SelectInst *SI, unsigned SISize,
641 const Value *V2, unsigned V2Size) {
642 // If the values are Selects with the same condition, we can do a more precise
643 // check: just check for aliases between the values on corresponding arms.
644 if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2))
645 if (SI->getCondition() == SI2->getCondition()) {
647 aliasCheck(SI->getTrueValue(), SISize,
648 SI2->getTrueValue(), V2Size);
649 if (Alias == MayAlias)
651 AliasResult ThisAlias =
652 aliasCheck(SI->getFalseValue(), SISize,
653 SI2->getFalseValue(), V2Size);
654 if (ThisAlias != Alias)
659 // If both arms of the Select node NoAlias or MustAlias V2, then returns
660 // NoAlias / MustAlias. Otherwise, returns MayAlias.
662 aliasCheck(SI->getTrueValue(), SISize, V2, V2Size);
663 if (Alias == MayAlias)
665 AliasResult ThisAlias =
666 aliasCheck(SI->getFalseValue(), SISize, V2, V2Size);
667 if (ThisAlias != Alias)
672 // aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI instruction
674 AliasAnalysis::AliasResult
675 BasicAliasAnalysis::aliasPHI(const PHINode *PN, unsigned PNSize,
676 const Value *V2, unsigned V2Size) {
677 // The PHI node has already been visited, avoid recursion any further.
678 if (!VisitedPHIs.insert(PN))
681 // If the values are PHIs in the same block, we can do a more precise
682 // as well as efficient check: just check for aliases between the values
683 // on corresponding edges.
684 if (const PHINode *PN2 = dyn_cast<PHINode>(V2))
685 if (PN2->getParent() == PN->getParent()) {
687 aliasCheck(PN->getIncomingValue(0), PNSize,
688 PN2->getIncomingValueForBlock(PN->getIncomingBlock(0)),
690 if (Alias == MayAlias)
692 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
693 AliasResult ThisAlias =
694 aliasCheck(PN->getIncomingValue(i), PNSize,
695 PN2->getIncomingValueForBlock(PN->getIncomingBlock(i)),
697 if (ThisAlias != Alias)
703 SmallPtrSet<Value*, 4> UniqueSrc;
704 SmallVector<Value*, 4> V1Srcs;
705 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
706 Value *PV1 = PN->getIncomingValue(i);
707 if (isa<PHINode>(PV1))
708 // If any of the source itself is a PHI, return MayAlias conservatively
709 // to avoid compile time explosion. The worst possible case is if both
710 // sides are PHI nodes. In which case, this is O(m x n) time where 'm'
711 // and 'n' are the number of PHI sources.
713 if (UniqueSrc.insert(PV1))
714 V1Srcs.push_back(PV1);
717 AliasResult Alias = aliasCheck(V2, V2Size, V1Srcs[0], PNSize);
718 // Early exit if the check of the first PHI source against V2 is MayAlias.
719 // Other results are not possible.
720 if (Alias == MayAlias)
723 // If all sources of the PHI node NoAlias or MustAlias V2, then returns
724 // NoAlias / MustAlias. Otherwise, returns MayAlias.
725 for (unsigned i = 1, e = V1Srcs.size(); i != e; ++i) {
726 Value *V = V1Srcs[i];
728 // If V2 is a PHI, the recursive case will have been caught in the
729 // above aliasCheck call, so these subsequent calls to aliasCheck
730 // don't need to assume that V2 is being visited recursively.
731 VisitedPHIs.erase(V2);
733 AliasResult ThisAlias = aliasCheck(V2, V2Size, V, PNSize);
734 if (ThisAlias != Alias || ThisAlias == MayAlias)
741 // aliasCheck - Provide a bunch of ad-hoc rules to disambiguate in common cases,
742 // such as array references.
744 AliasAnalysis::AliasResult
745 BasicAliasAnalysis::aliasCheck(const Value *V1, unsigned V1Size,
746 const Value *V2, unsigned V2Size) {
747 // Strip off any casts if they exist.
748 V1 = V1->stripPointerCasts();
749 V2 = V2->stripPointerCasts();
751 // Are we checking for alias of the same value?
752 if (V1 == V2) return MustAlias;
754 if (!isa<PointerType>(V1->getType()) || !isa<PointerType>(V2->getType()))
755 return NoAlias; // Scalars cannot alias each other
757 // Figure out what objects these things are pointing to if we can.
758 const Value *O1 = V1->getUnderlyingObject();
759 const Value *O2 = V2->getUnderlyingObject();
761 // Null values in the default address space don't point to any object, so they
762 // don't alias any other pointer.
763 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O1))
764 if (CPN->getType()->getAddressSpace() == 0)
766 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O2))
767 if (CPN->getType()->getAddressSpace() == 0)
771 // If V1/V2 point to two different objects we know that we have no alias.
772 if (isIdentifiedObject(O1) && isIdentifiedObject(O2))
775 // Constant pointers can't alias with non-const isIdentifiedObject objects.
776 if ((isa<Constant>(O1) && isIdentifiedObject(O2) && !isa<Constant>(O2)) ||
777 (isa<Constant>(O2) && isIdentifiedObject(O1) && !isa<Constant>(O1)))
780 // Arguments can't alias with local allocations or noalias calls.
781 if ((isa<Argument>(O1) && (isa<AllocaInst>(O2) || isNoAliasCall(O2))) ||
782 (isa<Argument>(O2) && (isa<AllocaInst>(O1) || isNoAliasCall(O1))))
785 // Most objects can't alias null.
786 if ((isa<ConstantPointerNull>(V2) && isKnownNonNull(O1)) ||
787 (isa<ConstantPointerNull>(V1) && isKnownNonNull(O2)))
791 // If the size of one access is larger than the entire object on the other
792 // side, then we know such behavior is undefined and can assume no alias.
794 if ((V1Size != ~0U && isObjectSmallerThan(O2, V1Size, *TD)) ||
795 (V2Size != ~0U && isObjectSmallerThan(O1, V2Size, *TD)))
798 // If one pointer is the result of a call/invoke or load and the other is a
799 // non-escaping local object, then we know the object couldn't escape to a
800 // point where the call could return it. The load case works because
801 // isNonEscapingLocalObject considers all stores to be escapes (it
802 // passes true for the StoreCaptures argument to PointerMayBeCaptured).
804 if ((isa<CallInst>(O1) || isa<InvokeInst>(O1) || isa<LoadInst>(O1) ||
805 isa<Argument>(O1)) &&
806 isNonEscapingLocalObject(O2))
808 if ((isa<CallInst>(O2) || isa<InvokeInst>(O2) || isa<LoadInst>(O2) ||
809 isa<Argument>(O2)) &&
810 isNonEscapingLocalObject(O1))
814 // FIXME: This isn't aggressively handling alias(GEP, PHI) for example: if the
815 // GEP can't simplify, we don't even look at the PHI cases.
816 if (!isa<GEPOperator>(V1) && isa<GEPOperator>(V2)) {
818 std::swap(V1Size, V2Size);
821 if (const GEPOperator *GV1 = dyn_cast<GEPOperator>(V1))
822 return aliasGEP(GV1, V1Size, V2, V2Size, O1, O2);
824 if (isa<PHINode>(V2) && !isa<PHINode>(V1)) {
826 std::swap(V1Size, V2Size);
828 if (const PHINode *PN = dyn_cast<PHINode>(V1))
829 return aliasPHI(PN, V1Size, V2, V2Size);
831 if (isa<SelectInst>(V2) && !isa<SelectInst>(V1)) {
833 std::swap(V1Size, V2Size);
835 if (const SelectInst *S1 = dyn_cast<SelectInst>(V1))
836 return aliasSelect(S1, V1Size, V2, V2Size);
841 // Make sure that anything that uses AliasAnalysis pulls in this file.
842 DEFINING_FILE_FOR(BasicAliasAnalysis)