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"
33 #include "llvm/Support/GetElementPtrTypeIterator.h"
37 //===----------------------------------------------------------------------===//
39 //===----------------------------------------------------------------------===//
41 /// isKnownNonNull - Return true if we know that the specified value is never
43 static bool isKnownNonNull(const Value *V) {
44 // Alloca never returns null, malloc might.
45 if (isa<AllocaInst>(V)) return true;
47 // A byval argument is never null.
48 if (const Argument *A = dyn_cast<Argument>(V))
49 return A->hasByValAttr();
51 // Global values are not null unless extern weak.
52 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
53 return !GV->hasExternalWeakLinkage();
57 /// isNonEscapingLocalObject - Return true if the pointer is to a function-local
58 /// object that never escapes from the function.
59 static bool isNonEscapingLocalObject(const Value *V) {
60 // If this is a local allocation, check to see if it escapes.
61 if (isa<AllocaInst>(V) || 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.
72 if (const Argument *A = dyn_cast<Argument>(V))
73 if (A->hasByValAttr() || A->hasNoAliasAttr()) {
74 // Don't bother analyzing arguments already known not to escape.
75 if (A->hasNoCaptureAttr())
77 return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
82 /// isEscapeSource - Return true if the pointer is one which would have
83 /// been considered an escape by isNonEscapingLocalObject.
84 static bool isEscapeSource(const Value *V) {
85 if (isa<CallInst>(V) || isa<InvokeInst>(V) || isa<Argument>(V))
88 // The load case works because isNonEscapingLocalObject considers all
89 // stores to be escapes (it passes true for the StoreCaptures argument
90 // to PointerMayBeCaptured).
97 /// isObjectSmallerThan - Return true if we can prove that the object specified
98 /// by V is smaller than Size.
99 static bool isObjectSmallerThan(const Value *V, unsigned Size,
100 const TargetData &TD) {
101 const Type *AccessTy;
102 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
103 AccessTy = GV->getType()->getElementType();
104 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
105 if (!AI->isArrayAllocation())
106 AccessTy = AI->getType()->getElementType();
109 } else if (const CallInst* CI = extractMallocCall(V)) {
110 if (!isArrayMalloc(V, &TD))
111 // The size is the argument to the malloc call.
112 if (const ConstantInt* C = dyn_cast<ConstantInt>(CI->getArgOperand(0)))
113 return (C->getZExtValue() < Size);
115 } else if (const Argument *A = dyn_cast<Argument>(V)) {
116 if (A->hasByValAttr())
117 AccessTy = cast<PointerType>(A->getType())->getElementType();
124 if (AccessTy->isSized())
125 return TD.getTypeAllocSize(AccessTy) < Size;
129 //===----------------------------------------------------------------------===//
131 //===----------------------------------------------------------------------===//
134 /// NoAA - This class implements the -no-aa pass, which always returns "I
135 /// don't know" for alias queries. NoAA is unlike other alias analysis
136 /// implementations, in that it does not chain to a previous analysis. As
137 /// such it doesn't follow many of the rules that other alias analyses must.
139 struct NoAA : public ImmutablePass, public AliasAnalysis {
140 static char ID; // Class identification, replacement for typeinfo
141 NoAA() : ImmutablePass(ID) {}
142 explicit NoAA(char &PID) : ImmutablePass(PID) { }
144 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
147 virtual void initializePass() {
148 TD = getAnalysisIfAvailable<TargetData>();
151 virtual AliasResult alias(const Value *V1, unsigned V1Size,
152 const Value *V2, unsigned V2Size) {
156 virtual ModRefBehavior getModRefBehavior(ImmutableCallSite CS) {
157 return UnknownModRefBehavior;
159 virtual ModRefBehavior getModRefBehavior(const Function *F) {
160 return UnknownModRefBehavior;
163 virtual bool pointsToConstantMemory(const Value *P) { return false; }
164 virtual ModRefResult getModRefInfo(ImmutableCallSite CS,
165 const Value *P, unsigned Size) {
168 virtual ModRefResult getModRefInfo(ImmutableCallSite CS1,
169 ImmutableCallSite CS2) {
173 virtual void deleteValue(Value *V) {}
174 virtual void copyValue(Value *From, Value *To) {}
176 /// getAdjustedAnalysisPointer - This method is used when a pass implements
177 /// an analysis interface through multiple inheritance. If needed, it
178 /// should override this to adjust the this pointer as needed for the
179 /// specified pass info.
180 virtual void *getAdjustedAnalysisPointer(const void *ID) {
181 if (ID == &AliasAnalysis::ID)
182 return (AliasAnalysis*)this;
186 } // End of anonymous namespace
188 // Register this pass...
190 INITIALIZE_AG_PASS(NoAA, AliasAnalysis, "no-aa",
191 "No Alias Analysis (always returns 'may' alias)",
194 ImmutablePass *llvm::createNoAAPass() { return new NoAA(); }
196 //===----------------------------------------------------------------------===//
197 // GetElementPtr Instruction Decomposition and Analysis
198 //===----------------------------------------------------------------------===//
201 /// GetLinearExpression - Analyze the specified value as a linear expression:
202 /// "A*V + B", where A and B are constant integers. Return the scale and offset
203 /// values as APInts and return V as a Value*. The incoming Value is known to
204 /// have IntegerType. Note that this looks through extends, so the high bits
205 /// may not be represented in the result.
206 static Value *GetLinearExpression(Value *V, APInt &Scale, APInt &Offset,
207 const TargetData *TD, unsigned Depth) {
208 assert(V->getType()->isIntegerTy() && "Not an integer value");
210 // Limit our recursion depth.
217 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(V)) {
218 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(BOp->getOperand(1))) {
219 switch (BOp->getOpcode()) {
221 case Instruction::Or:
222 // X|C == X+C if all the bits in C are unset in X. Otherwise we can't
224 if (!MaskedValueIsZero(BOp->getOperand(0), RHSC->getValue(), TD))
227 case Instruction::Add:
228 V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, TD, Depth+1);
229 Offset += RHSC->getValue();
231 case Instruction::Mul:
232 V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, TD, Depth+1);
233 Offset *= RHSC->getValue();
234 Scale *= RHSC->getValue();
236 case Instruction::Shl:
237 V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, TD, Depth+1);
238 Offset <<= RHSC->getValue().getLimitedValue();
239 Scale <<= RHSC->getValue().getLimitedValue();
245 // Since GEP indices are sign extended anyway, we don't care about the high
246 // bits of a sign extended value - just scales and offsets.
247 if (isa<SExtInst>(V)) {
248 Value *CastOp = cast<CastInst>(V)->getOperand(0);
249 unsigned OldWidth = Scale.getBitWidth();
250 unsigned SmallWidth = CastOp->getType()->getPrimitiveSizeInBits();
251 Scale.trunc(SmallWidth);
252 Offset.trunc(SmallWidth);
253 Value *Result = GetLinearExpression(CastOp, Scale, Offset, TD, Depth+1);
254 Scale.zext(OldWidth);
255 Offset.zext(OldWidth);
264 /// DecomposeGEPExpression - If V is a symbolic pointer expression, decompose it
265 /// into a base pointer with a constant offset and a number of scaled symbolic
268 /// The scaled symbolic offsets (represented by pairs of a Value* and a scale in
269 /// the VarIndices vector) are Value*'s that are known to be scaled by the
270 /// specified amount, but which may have other unrepresented high bits. As such,
271 /// the gep cannot necessarily be reconstructed from its decomposed form.
273 /// When TargetData is around, this function is capable of analyzing everything
274 /// that Value::getUnderlyingObject() can look through. When not, it just looks
275 /// through pointer casts.
278 DecomposeGEPExpression(const Value *V, int64_t &BaseOffs,
279 SmallVectorImpl<std::pair<const Value*, int64_t> > &VarIndices,
280 const TargetData *TD) {
281 // Limit recursion depth to limit compile time in crazy cases.
282 unsigned MaxLookup = 6;
286 // Look through global aliases and bitcasts.
287 V = V->stripPointerCasts();
289 const GEPOperator *GEPOp = dyn_cast<GEPOperator>(V);
293 // Don't attempt to analyze GEPs over unsized objects.
294 if (!cast<PointerType>(GEPOp->getOperand(0)->getType())
295 ->getElementType()->isSized())
298 // If we are lacking TargetData information, we can't compute the offets of
299 // elements computed by GEPs. However, we can handle bitcast equivalent
302 if (!GEPOp->hasAllZeroIndices())
304 V = GEPOp->getOperand(0);
308 // Walk the indices of the GEP, accumulating them into BaseOff/VarIndices.
309 gep_type_iterator GTI = gep_type_begin(GEPOp);
310 for (User::const_op_iterator I = GEPOp->op_begin()+1,
311 E = GEPOp->op_end(); I != E; ++I) {
313 // Compute the (potentially symbolic) offset in bytes for this index.
314 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
315 // For a struct, add the member offset.
316 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
317 if (FieldNo == 0) continue;
319 BaseOffs += TD->getStructLayout(STy)->getElementOffset(FieldNo);
323 // For an array/pointer, add the element offset, explicitly scaled.
324 if (ConstantInt *CIdx = dyn_cast<ConstantInt>(Index)) {
325 if (CIdx->isZero()) continue;
326 BaseOffs += TD->getTypeAllocSize(*GTI)*CIdx->getSExtValue();
330 uint64_t Scale = TD->getTypeAllocSize(*GTI);
332 // Use GetLinearExpression to decompose the index into a C1*V+C2 form.
333 unsigned Width = cast<IntegerType>(Index->getType())->getBitWidth();
334 APInt IndexScale(Width, 0), IndexOffset(Width, 0);
335 Index = GetLinearExpression(Index, IndexScale, IndexOffset, TD, 0);
337 // The GEP index scale ("Scale") scales C1*V+C2, yielding (C1*V+C2)*Scale.
338 // This gives us an aggregate computation of (C1*Scale)*V + C2*Scale.
339 BaseOffs += IndexOffset.getZExtValue()*Scale;
340 Scale *= IndexScale.getZExtValue();
343 // If we already had an occurrance of this index variable, merge this
344 // scale into it. For example, we want to handle:
345 // A[x][x] -> x*16 + x*4 -> x*20
346 // This also ensures that 'x' only appears in the index list once.
347 for (unsigned i = 0, e = VarIndices.size(); i != e; ++i) {
348 if (VarIndices[i].first == Index) {
349 Scale += VarIndices[i].second;
350 VarIndices.erase(VarIndices.begin()+i);
355 // Make sure that we have a scale that makes sense for this target's
357 if (unsigned ShiftBits = 64-TD->getPointerSizeInBits()) {
363 VarIndices.push_back(std::make_pair(Index, Scale));
366 // Analyze the base pointer next.
367 V = GEPOp->getOperand(0);
368 } while (--MaxLookup);
370 // If the chain of expressions is too deep, just return early.
374 /// GetIndexDifference - Dest and Src are the variable indices from two
375 /// decomposed GetElementPtr instructions GEP1 and GEP2 which have common base
376 /// pointers. Subtract the GEP2 indices from GEP1 to find the symbolic
377 /// difference between the two pointers.
378 static void GetIndexDifference(
379 SmallVectorImpl<std::pair<const Value*, int64_t> > &Dest,
380 const SmallVectorImpl<std::pair<const Value*, int64_t> > &Src) {
381 if (Src.empty()) return;
383 for (unsigned i = 0, e = Src.size(); i != e; ++i) {
384 const Value *V = Src[i].first;
385 int64_t Scale = Src[i].second;
387 // Find V in Dest. This is N^2, but pointer indices almost never have more
388 // than a few variable indexes.
389 for (unsigned j = 0, e = Dest.size(); j != e; ++j) {
390 if (Dest[j].first != V) continue;
392 // If we found it, subtract off Scale V's from the entry in Dest. If it
393 // goes to zero, remove the entry.
394 if (Dest[j].second != Scale)
395 Dest[j].second -= Scale;
397 Dest.erase(Dest.begin()+j);
402 // If we didn't consume this entry, add it to the end of the Dest list.
404 Dest.push_back(std::make_pair(V, -Scale));
408 //===----------------------------------------------------------------------===//
409 // BasicAliasAnalysis Pass
410 //===----------------------------------------------------------------------===//
413 static const Function *getParent(const Value *V) {
414 if (const Instruction *inst = dyn_cast<Instruction>(V))
415 return inst->getParent()->getParent();
417 if (const Argument *arg = dyn_cast<Argument>(V))
418 return arg->getParent();
423 static bool notDifferentParent(const Value *O1, const Value *O2) {
425 const Function *F1 = getParent(O1);
426 const Function *F2 = getParent(O2);
428 return !F1 || !F2 || F1 == F2;
433 /// BasicAliasAnalysis - This is the default alias analysis implementation.
434 /// Because it doesn't chain to a previous alias analysis (like -no-aa), it
435 /// derives from the NoAA class.
436 struct BasicAliasAnalysis : public NoAA {
437 static char ID; // Class identification, replacement for typeinfo
438 BasicAliasAnalysis() : NoAA(ID) {}
440 virtual AliasResult alias(const Value *V1, unsigned V1Size,
441 const Value *V2, unsigned V2Size) {
442 assert(Visited.empty() && "Visited must be cleared after use!");
443 assert(notDifferentParent(V1, V2) &&
444 "BasicAliasAnalysis doesn't support interprocedural queries.");
445 AliasResult Alias = aliasCheck(V1, V1Size, V2, V2Size);
450 virtual ModRefResult getModRefInfo(ImmutableCallSite CS,
451 const Value *P, unsigned Size);
453 virtual ModRefResult getModRefInfo(ImmutableCallSite CS1,
454 ImmutableCallSite CS2) {
455 // The AliasAnalysis base class has some smarts, lets use them.
456 return AliasAnalysis::getModRefInfo(CS1, CS2);
459 /// pointsToConstantMemory - Chase pointers until we find a (constant
461 virtual bool pointsToConstantMemory(const Value *P);
463 /// getModRefBehavior - Return the behavior when calling the given
465 virtual ModRefBehavior getModRefBehavior(ImmutableCallSite CS);
467 /// getModRefBehavior - Return the behavior when calling the given function.
468 /// For use when the call site is not known.
469 virtual ModRefBehavior getModRefBehavior(const Function *F);
471 /// getAdjustedAnalysisPointer - This method is used when a pass implements
472 /// an analysis interface through multiple inheritance. If needed, it
473 /// should override this to adjust the this pointer as needed for the
474 /// specified pass info.
475 virtual void *getAdjustedAnalysisPointer(const void *ID) {
476 if (ID == &AliasAnalysis::ID)
477 return (AliasAnalysis*)this;
482 // Visited - Track instructions visited by a aliasPHI, aliasSelect(), and aliasGEP().
483 SmallPtrSet<const Value*, 16> Visited;
485 // aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP
486 // instruction against another.
487 AliasResult aliasGEP(const GEPOperator *V1, unsigned V1Size,
488 const Value *V2, unsigned V2Size,
489 const Value *UnderlyingV1, const Value *UnderlyingV2);
491 // aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI
492 // instruction against another.
493 AliasResult aliasPHI(const PHINode *PN, unsigned PNSize,
494 const Value *V2, unsigned V2Size);
496 /// aliasSelect - Disambiguate a Select instruction against another value.
497 AliasResult aliasSelect(const SelectInst *SI, unsigned SISize,
498 const Value *V2, unsigned V2Size);
500 AliasResult aliasCheck(const Value *V1, unsigned V1Size,
501 const Value *V2, unsigned V2Size);
503 } // End of anonymous namespace
505 // Register this pass...
506 char BasicAliasAnalysis::ID = 0;
507 INITIALIZE_AG_PASS(BasicAliasAnalysis, AliasAnalysis, "basicaa",
508 "Basic Alias Analysis (default AA impl)",
511 ImmutablePass *llvm::createBasicAliasAnalysisPass() {
512 return new BasicAliasAnalysis();
516 /// pointsToConstantMemory - Chase pointers until we find a (constant
518 bool BasicAliasAnalysis::pointsToConstantMemory(const Value *P) {
519 if (const GlobalVariable *GV =
520 dyn_cast<GlobalVariable>(P->getUnderlyingObject()))
521 // Note: this doesn't require GV to be "ODR" because it isn't legal for a
522 // global to be marked constant in some modules and non-constant in others.
523 // GV may even be a declaration, not a definition.
524 return GV->isConstant();
526 return NoAA::pointsToConstantMemory(P);
529 /// getModRefBehavior - Return the behavior when calling the given call site.
530 AliasAnalysis::ModRefBehavior
531 BasicAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
532 if (CS.doesNotAccessMemory())
533 // Can't do better than this.
534 return DoesNotAccessMemory;
536 ModRefBehavior Min = UnknownModRefBehavior;
538 // If the callsite knows it only reads memory, don't return worse
540 if (CS.onlyReadsMemory())
541 Min = OnlyReadsMemory;
543 // The AliasAnalysis base class has some smarts, lets use them.
544 return std::min(AliasAnalysis::getModRefBehavior(CS), Min);
547 /// getModRefBehavior - Return the behavior when calling the given function.
548 /// For use when the call site is not known.
549 AliasAnalysis::ModRefBehavior
550 BasicAliasAnalysis::getModRefBehavior(const Function *F) {
551 if (F->doesNotAccessMemory())
552 // Can't do better than this.
553 return DoesNotAccessMemory;
554 if (F->onlyReadsMemory())
555 return OnlyReadsMemory;
556 if (unsigned id = F->getIntrinsicID())
557 return getIntrinsicModRefBehavior(id);
559 return NoAA::getModRefBehavior(F);
562 /// getModRefInfo - Check to see if the specified callsite can clobber the
563 /// specified memory object. Since we only look at local properties of this
564 /// function, we really can't say much about this query. We do, however, use
565 /// simple "address taken" analysis on local objects.
566 AliasAnalysis::ModRefResult
567 BasicAliasAnalysis::getModRefInfo(ImmutableCallSite CS,
568 const Value *P, unsigned Size) {
569 assert(notDifferentParent(CS.getInstruction(), P) &&
570 "AliasAnalysis query involving multiple functions!");
572 const Value *Object = P->getUnderlyingObject();
574 // If this is a tail call and P points to a stack location, we know that
575 // the tail call cannot access or modify the local stack.
576 // We cannot exclude byval arguments here; these belong to the caller of
577 // the current function not to the current function, and a tail callee
578 // may reference them.
579 if (isa<AllocaInst>(Object))
580 if (const CallInst *CI = dyn_cast<CallInst>(CS.getInstruction()))
581 if (CI->isTailCall())
584 // If the pointer is to a locally allocated object that does not escape,
585 // then the call can not mod/ref the pointer unless the call takes the pointer
586 // as an argument, and itself doesn't capture it.
587 if (!isa<Constant>(Object) && CS.getInstruction() != Object &&
588 isNonEscapingLocalObject(Object)) {
589 bool PassedAsArg = false;
591 for (ImmutableCallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
592 CI != CE; ++CI, ++ArgNo) {
593 // Only look at the no-capture pointer arguments.
594 if (!(*CI)->getType()->isPointerTy() ||
595 !CS.paramHasAttr(ArgNo+1, Attribute::NoCapture))
598 // If this is a no-capture pointer argument, see if we can tell that it
599 // is impossible to alias the pointer we're checking. If not, we have to
600 // assume that the call could touch the pointer, even though it doesn't
602 if (!isNoAlias(cast<Value>(CI), UnknownSize, P, UnknownSize)) {
612 // Finally, handle specific knowledge of intrinsics.
613 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction());
615 switch (II->getIntrinsicID()) {
617 case Intrinsic::memcpy:
618 case Intrinsic::memmove: {
619 unsigned Len = UnknownSize;
620 if (ConstantInt *LenCI = dyn_cast<ConstantInt>(II->getArgOperand(2)))
621 Len = LenCI->getZExtValue();
622 Value *Dest = II->getArgOperand(0);
623 Value *Src = II->getArgOperand(1);
624 if (isNoAlias(Dest, Len, P, Size)) {
625 if (isNoAlias(Src, Len, P, Size))
631 case Intrinsic::memset:
632 // Since memset is 'accesses arguments' only, the AliasAnalysis base class
633 // will handle it for the variable length case.
634 if (ConstantInt *LenCI = dyn_cast<ConstantInt>(II->getArgOperand(2))) {
635 unsigned Len = LenCI->getZExtValue();
636 Value *Dest = II->getArgOperand(0);
637 if (isNoAlias(Dest, Len, P, Size))
641 case Intrinsic::atomic_cmp_swap:
642 case Intrinsic::atomic_swap:
643 case Intrinsic::atomic_load_add:
644 case Intrinsic::atomic_load_sub:
645 case Intrinsic::atomic_load_and:
646 case Intrinsic::atomic_load_nand:
647 case Intrinsic::atomic_load_or:
648 case Intrinsic::atomic_load_xor:
649 case Intrinsic::atomic_load_max:
650 case Intrinsic::atomic_load_min:
651 case Intrinsic::atomic_load_umax:
652 case Intrinsic::atomic_load_umin:
654 Value *Op1 = II->getArgOperand(0);
655 unsigned Op1Size = TD->getTypeStoreSize(Op1->getType());
656 if (isNoAlias(Op1, Op1Size, P, Size))
660 case Intrinsic::lifetime_start:
661 case Intrinsic::lifetime_end:
662 case Intrinsic::invariant_start: {
664 cast<ConstantInt>(II->getArgOperand(0))->getZExtValue();
665 if (isNoAlias(II->getArgOperand(1), PtrSize, P, Size))
669 case Intrinsic::invariant_end: {
671 cast<ConstantInt>(II->getArgOperand(1))->getZExtValue();
672 if (isNoAlias(II->getArgOperand(2), PtrSize, P, Size))
678 // The AliasAnalysis base class has some smarts, lets use them.
679 return AliasAnalysis::getModRefInfo(CS, P, Size);
683 /// aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP instruction
684 /// against another pointer. We know that V1 is a GEP, but we don't know
685 /// anything about V2. UnderlyingV1 is GEP1->getUnderlyingObject(),
686 /// UnderlyingV2 is the same for V2.
688 AliasAnalysis::AliasResult
689 BasicAliasAnalysis::aliasGEP(const GEPOperator *GEP1, unsigned V1Size,
690 const Value *V2, unsigned V2Size,
691 const Value *UnderlyingV1,
692 const Value *UnderlyingV2) {
693 // If this GEP has been visited before, we're on a use-def cycle.
694 // Such cycles are only valid when PHI nodes are involved or in unreachable
695 // code. The visitPHI function catches cycles containing PHIs, but there
696 // could still be a cycle without PHIs in unreachable code.
697 if (!Visited.insert(GEP1))
700 int64_t GEP1BaseOffset;
701 SmallVector<std::pair<const Value*, int64_t>, 4> GEP1VariableIndices;
703 // If we have two gep instructions with must-alias'ing base pointers, figure
704 // out if the indexes to the GEP tell us anything about the derived pointer.
705 if (const GEPOperator *GEP2 = dyn_cast<GEPOperator>(V2)) {
706 // Do the base pointers alias?
707 AliasResult BaseAlias = aliasCheck(UnderlyingV1, UnknownSize,
708 UnderlyingV2, UnknownSize);
710 // If we get a No or May, then return it immediately, no amount of analysis
711 // will improve this situation.
712 if (BaseAlias != MustAlias) return BaseAlias;
714 // Otherwise, we have a MustAlias. Since the base pointers alias each other
715 // exactly, see if the computed offset from the common pointer tells us
716 // about the relation of the resulting pointer.
717 const Value *GEP1BasePtr =
718 DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices, TD);
720 int64_t GEP2BaseOffset;
721 SmallVector<std::pair<const Value*, int64_t>, 4> GEP2VariableIndices;
722 const Value *GEP2BasePtr =
723 DecomposeGEPExpression(GEP2, GEP2BaseOffset, GEP2VariableIndices, TD);
725 // If DecomposeGEPExpression isn't able to look all the way through the
726 // addressing operation, we must not have TD and this is too complex for us
727 // to handle without it.
728 if (GEP1BasePtr != UnderlyingV1 || GEP2BasePtr != UnderlyingV2) {
730 "DecomposeGEPExpression and getUnderlyingObject disagree!");
734 // Subtract the GEP2 pointer from the GEP1 pointer to find out their
735 // symbolic difference.
736 GEP1BaseOffset -= GEP2BaseOffset;
737 GetIndexDifference(GEP1VariableIndices, GEP2VariableIndices);
740 // Check to see if these two pointers are related by the getelementptr
741 // instruction. If one pointer is a GEP with a non-zero index of the other
742 // pointer, we know they cannot alias.
744 // If both accesses are unknown size, we can't do anything useful here.
745 if (V1Size == UnknownSize && V2Size == UnknownSize)
748 AliasResult R = aliasCheck(UnderlyingV1, UnknownSize, V2, V2Size);
750 // If V2 may alias GEP base pointer, conservatively returns MayAlias.
751 // If V2 is known not to alias GEP base pointer, then the two values
752 // cannot alias per GEP semantics: "A pointer value formed from a
753 // getelementptr instruction is associated with the addresses associated
754 // with the first operand of the getelementptr".
757 const Value *GEP1BasePtr =
758 DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices, TD);
760 // If DecomposeGEPExpression isn't able to look all the way through the
761 // addressing operation, we must not have TD and this is too complex for us
762 // to handle without it.
763 if (GEP1BasePtr != UnderlyingV1) {
765 "DecomposeGEPExpression and getUnderlyingObject disagree!");
770 // In the two GEP Case, if there is no difference in the offsets of the
771 // computed pointers, the resultant pointers are a must alias. This
772 // hapens when we have two lexically identical GEP's (for example).
774 // In the other case, if we have getelementptr <ptr>, 0, 0, 0, 0, ... and V2
775 // must aliases the GEP, the end result is a must alias also.
776 if (GEP1BaseOffset == 0 && GEP1VariableIndices.empty())
779 // If we have a known constant offset, see if this offset is larger than the
780 // access size being queried. If so, and if no variable indices can remove
781 // pieces of this constant, then we know we have a no-alias. For example,
784 // In order to handle cases like &A[100][i] where i is an out of range
785 // subscript, we have to ignore all constant offset pieces that are a multiple
786 // of a scaled index. Do this by removing constant offsets that are a
787 // multiple of any of our variable indices. This allows us to transform
788 // things like &A[i][1] because i has a stride of (e.g.) 8 bytes but the 1
789 // provides an offset of 4 bytes (assuming a <= 4 byte access).
790 for (unsigned i = 0, e = GEP1VariableIndices.size();
791 i != e && GEP1BaseOffset;++i)
792 if (int64_t RemovedOffset = GEP1BaseOffset/GEP1VariableIndices[i].second)
793 GEP1BaseOffset -= RemovedOffset*GEP1VariableIndices[i].second;
795 // If our known offset is bigger than the access size, we know we don't have
797 if (GEP1BaseOffset) {
798 if (GEP1BaseOffset >= (int64_t)V2Size ||
799 GEP1BaseOffset <= -(int64_t)V1Size)
806 /// aliasSelect - Provide a bunch of ad-hoc rules to disambiguate a Select
807 /// instruction against another.
808 AliasAnalysis::AliasResult
809 BasicAliasAnalysis::aliasSelect(const SelectInst *SI, unsigned SISize,
810 const Value *V2, unsigned V2Size) {
811 // If this select has been visited before, we're on a use-def cycle.
812 // Such cycles are only valid when PHI nodes are involved or in unreachable
813 // code. The visitPHI function catches cycles containing PHIs, but there
814 // could still be a cycle without PHIs in unreachable code.
815 if (!Visited.insert(SI))
818 // If the values are Selects with the same condition, we can do a more precise
819 // check: just check for aliases between the values on corresponding arms.
820 if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2))
821 if (SI->getCondition() == SI2->getCondition()) {
823 aliasCheck(SI->getTrueValue(), SISize,
824 SI2->getTrueValue(), V2Size);
825 if (Alias == MayAlias)
827 AliasResult ThisAlias =
828 aliasCheck(SI->getFalseValue(), SISize,
829 SI2->getFalseValue(), V2Size);
830 if (ThisAlias != Alias)
835 // If both arms of the Select node NoAlias or MustAlias V2, then returns
836 // NoAlias / MustAlias. Otherwise, returns MayAlias.
838 aliasCheck(V2, V2Size, SI->getTrueValue(), SISize);
839 if (Alias == MayAlias)
842 // If V2 is visited, the recursive case will have been caught in the
843 // above aliasCheck call, so these subsequent calls to aliasCheck
844 // don't need to assume that V2 is being visited recursively.
847 AliasResult ThisAlias =
848 aliasCheck(V2, V2Size, SI->getFalseValue(), SISize);
849 if (ThisAlias != Alias)
854 // aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI instruction
856 AliasAnalysis::AliasResult
857 BasicAliasAnalysis::aliasPHI(const PHINode *PN, unsigned PNSize,
858 const Value *V2, unsigned V2Size) {
859 // The PHI node has already been visited, avoid recursion any further.
860 if (!Visited.insert(PN))
863 // If the values are PHIs in the same block, we can do a more precise
864 // as well as efficient check: just check for aliases between the values
865 // on corresponding edges.
866 if (const PHINode *PN2 = dyn_cast<PHINode>(V2))
867 if (PN2->getParent() == PN->getParent()) {
869 aliasCheck(PN->getIncomingValue(0), PNSize,
870 PN2->getIncomingValueForBlock(PN->getIncomingBlock(0)),
872 if (Alias == MayAlias)
874 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
875 AliasResult ThisAlias =
876 aliasCheck(PN->getIncomingValue(i), PNSize,
877 PN2->getIncomingValueForBlock(PN->getIncomingBlock(i)),
879 if (ThisAlias != Alias)
885 SmallPtrSet<Value*, 4> UniqueSrc;
886 SmallVector<Value*, 4> V1Srcs;
887 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
888 Value *PV1 = PN->getIncomingValue(i);
889 if (isa<PHINode>(PV1))
890 // If any of the source itself is a PHI, return MayAlias conservatively
891 // to avoid compile time explosion. The worst possible case is if both
892 // sides are PHI nodes. In which case, this is O(m x n) time where 'm'
893 // and 'n' are the number of PHI sources.
895 if (UniqueSrc.insert(PV1))
896 V1Srcs.push_back(PV1);
899 AliasResult Alias = aliasCheck(V2, V2Size, V1Srcs[0], PNSize);
900 // Early exit if the check of the first PHI source against V2 is MayAlias.
901 // Other results are not possible.
902 if (Alias == MayAlias)
905 // If all sources of the PHI node NoAlias or MustAlias V2, then returns
906 // NoAlias / MustAlias. Otherwise, returns MayAlias.
907 for (unsigned i = 1, e = V1Srcs.size(); i != e; ++i) {
908 Value *V = V1Srcs[i];
910 // If V2 is visited, the recursive case will have been caught in the
911 // above aliasCheck call, so these subsequent calls to aliasCheck
912 // don't need to assume that V2 is being visited recursively.
915 AliasResult ThisAlias = aliasCheck(V2, V2Size, V, PNSize);
916 if (ThisAlias != Alias || ThisAlias == MayAlias)
923 // aliasCheck - Provide a bunch of ad-hoc rules to disambiguate in common cases,
924 // such as array references.
926 AliasAnalysis::AliasResult
927 BasicAliasAnalysis::aliasCheck(const Value *V1, unsigned V1Size,
928 const Value *V2, unsigned V2Size) {
929 // If either of the memory references is empty, it doesn't matter what the
930 // pointer values are.
931 if (V1Size == 0 || V2Size == 0)
934 // Strip off any casts if they exist.
935 V1 = V1->stripPointerCasts();
936 V2 = V2->stripPointerCasts();
938 // Are we checking for alias of the same value?
939 if (V1 == V2) return MustAlias;
941 if (!V1->getType()->isPointerTy() || !V2->getType()->isPointerTy())
942 return NoAlias; // Scalars cannot alias each other
944 // Figure out what objects these things are pointing to if we can.
945 const Value *O1 = V1->getUnderlyingObject();
946 const Value *O2 = V2->getUnderlyingObject();
948 // Null values in the default address space don't point to any object, so they
949 // don't alias any other pointer.
950 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O1))
951 if (CPN->getType()->getAddressSpace() == 0)
953 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O2))
954 if (CPN->getType()->getAddressSpace() == 0)
958 // If V1/V2 point to two different objects we know that we have no alias.
959 if (isIdentifiedObject(O1) && isIdentifiedObject(O2))
962 // Constant pointers can't alias with non-const isIdentifiedObject objects.
963 if ((isa<Constant>(O1) && isIdentifiedObject(O2) && !isa<Constant>(O2)) ||
964 (isa<Constant>(O2) && isIdentifiedObject(O1) && !isa<Constant>(O1)))
967 // Arguments can't alias with local allocations or noalias calls
968 // in the same function.
969 if (((isa<Argument>(O1) && (isa<AllocaInst>(O2) || isNoAliasCall(O2))) ||
970 (isa<Argument>(O2) && (isa<AllocaInst>(O1) || isNoAliasCall(O1)))))
973 // Most objects can't alias null.
974 if ((isa<ConstantPointerNull>(O2) && isKnownNonNull(O1)) ||
975 (isa<ConstantPointerNull>(O1) && isKnownNonNull(O2)))
978 // If one pointer is the result of a call/invoke or load and the other is a
979 // non-escaping local object within the same function, then we know the
980 // object couldn't escape to a point where the call could return it.
982 // Note that if the pointers are in different functions, there are a
983 // variety of complications. A call with a nocapture argument may still
984 // temporary store the nocapture argument's value in a temporary memory
985 // location if that memory location doesn't escape. Or it may pass a
986 // nocapture value to other functions as long as they don't capture it.
987 if (isEscapeSource(O1) && isNonEscapingLocalObject(O2))
989 if (isEscapeSource(O2) && isNonEscapingLocalObject(O1))
993 // If the size of one access is larger than the entire object on the other
994 // side, then we know such behavior is undefined and can assume no alias.
996 if ((V1Size != UnknownSize && isObjectSmallerThan(O2, V1Size, *TD)) ||
997 (V2Size != UnknownSize && isObjectSmallerThan(O1, V2Size, *TD)))
1000 // FIXME: This isn't aggressively handling alias(GEP, PHI) for example: if the
1001 // GEP can't simplify, we don't even look at the PHI cases.
1002 if (!isa<GEPOperator>(V1) && isa<GEPOperator>(V2)) {
1004 std::swap(V1Size, V2Size);
1007 if (const GEPOperator *GV1 = dyn_cast<GEPOperator>(V1))
1008 return aliasGEP(GV1, V1Size, V2, V2Size, O1, O2);
1010 if (isa<PHINode>(V2) && !isa<PHINode>(V1)) {
1012 std::swap(V1Size, V2Size);
1014 if (const PHINode *PN = dyn_cast<PHINode>(V1))
1015 return aliasPHI(PN, V1Size, V2, V2Size);
1017 if (isa<SelectInst>(V2) && !isa<SelectInst>(V1)) {
1019 std::swap(V1Size, V2Size);
1021 if (const SelectInst *S1 = dyn_cast<SelectInst>(V1))
1022 return aliasSelect(S1, V1Size, V2, V2Size);
1024 return NoAA::alias(V1, V1Size, V2, V2Size);
1027 // Make sure that anything that uses AliasAnalysis pulls in this file.
1028 DEFINING_FILE_FOR(BasicAliasAnalysis)