BasicAliasAnalysis.cpp revision db4708cf86cece22539ff022cc0601612dd02ead
1//===- BasicAliasAnalysis.cpp - Stateless Alias Analysis Impl -------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the primary stateless implementation of the
11// Alias Analysis interface that implements identities (two different
12// globals cannot alias, etc), but does no stateful analysis.
13//
14//===----------------------------------------------------------------------===//
15
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/GlobalAlias.h"
22#include "llvm/GlobalVariable.h"
23#include "llvm/Instructions.h"
24#include "llvm/IntrinsicInst.h"
25#include "llvm/LLVMContext.h"
26#include "llvm/Operator.h"
27#include "llvm/Pass.h"
28#include "llvm/Analysis/CaptureTracking.h"
29#include "llvm/Analysis/MemoryBuiltins.h"
30#include "llvm/Analysis/ValueTracking.h"
31#include "llvm/Target/TargetData.h"
32#include "llvm/ADT/SmallPtrSet.h"
33#include "llvm/ADT/SmallVector.h"
34#include "llvm/Support/ErrorHandling.h"
35#include "llvm/Support/GetElementPtrTypeIterator.h"
36#include <algorithm>
37using namespace llvm;
38
39//===----------------------------------------------------------------------===//
40// Useful predicates
41//===----------------------------------------------------------------------===//
42
43/// isKnownNonNull - Return true if we know that the specified value is never
44/// null.
45static bool isKnownNonNull(const Value *V) {
46  // Alloca never returns null, malloc might.
47  if (isa<AllocaInst>(V)) return true;
48
49  // A byval argument is never null.
50  if (const Argument *A = dyn_cast<Argument>(V))
51    return A->hasByValAttr();
52
53  // Global values are not null unless extern weak.
54  if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
55    return !GV->hasExternalWeakLinkage();
56  return false;
57}
58
59/// isNonEscapingLocalObject - Return true if the pointer is to a function-local
60/// object that never escapes from the function.
61static bool isNonEscapingLocalObject(const Value *V) {
62  // If this is a local allocation, check to see if it escapes.
63  if (isa<AllocaInst>(V) || isNoAliasCall(V))
64    // Set StoreCaptures to True so that we can assume in our callers that the
65    // pointer is not the result of a load instruction. Currently
66    // PointerMayBeCaptured doesn't have any special analysis for the
67    // StoreCaptures=false case; if it did, our callers could be refined to be
68    // more precise.
69    return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
70
71  // If this is an argument that corresponds to a byval or noalias argument,
72  // then it has not escaped before entering the function.  Check if it escapes
73  // inside the function.
74  if (const Argument *A = dyn_cast<Argument>(V))
75    if (A->hasByValAttr() || A->hasNoAliasAttr()) {
76      // Don't bother analyzing arguments already known not to escape.
77      if (A->hasNoCaptureAttr())
78        return true;
79      return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
80    }
81  return false;
82}
83
84/// isEscapeSource - Return true if the pointer is one which would have
85/// been considered an escape by isNonEscapingLocalObject.
86static bool isEscapeSource(const Value *V) {
87  if (isa<CallInst>(V) || isa<InvokeInst>(V) || isa<Argument>(V))
88    return true;
89
90  // The load case works because isNonEscapingLocalObject considers all
91  // stores to be escapes (it passes true for the StoreCaptures argument
92  // to PointerMayBeCaptured).
93  if (isa<LoadInst>(V))
94    return true;
95
96  return false;
97}
98
99/// isObjectSmallerThan - Return true if we can prove that the object specified
100/// by V is smaller than Size.
101static bool isObjectSmallerThan(const Value *V, uint64_t Size,
102                                const TargetData &TD) {
103  const Type *AccessTy;
104  if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
105    AccessTy = GV->getType()->getElementType();
106  } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
107    if (!AI->isArrayAllocation())
108      AccessTy = AI->getType()->getElementType();
109    else
110      return false;
111  } else if (const CallInst* CI = extractMallocCall(V)) {
112    if (!isArrayMalloc(V, &TD))
113      // The size is the argument to the malloc call.
114      if (const ConstantInt* C = dyn_cast<ConstantInt>(CI->getArgOperand(0)))
115        return (C->getZExtValue() < Size);
116    return false;
117  } else if (const Argument *A = dyn_cast<Argument>(V)) {
118    if (A->hasByValAttr())
119      AccessTy = cast<PointerType>(A->getType())->getElementType();
120    else
121      return false;
122  } else {
123    return false;
124  }
125
126  if (AccessTy->isSized())
127    return TD.getTypeAllocSize(AccessTy) < Size;
128  return false;
129}
130
131//===----------------------------------------------------------------------===//
132// GetElementPtr Instruction Decomposition and Analysis
133//===----------------------------------------------------------------------===//
134
135namespace {
136  enum ExtensionKind {
137    EK_NotExtended,
138    EK_SignExt,
139    EK_ZeroExt
140  };
141
142  struct VariableGEPIndex {
143    const Value *V;
144    ExtensionKind Extension;
145    int64_t Scale;
146  };
147}
148
149
150/// GetLinearExpression - Analyze the specified value as a linear expression:
151/// "A*V + B", where A and B are constant integers.  Return the scale and offset
152/// values as APInts and return V as a Value*, and return whether we looked
153/// through any sign or zero extends.  The incoming Value is known to have
154/// IntegerType and it may already be sign or zero extended.
155///
156/// Note that this looks through extends, so the high bits may not be
157/// represented in the result.
158static Value *GetLinearExpression(Value *V, APInt &Scale, APInt &Offset,
159                                  ExtensionKind &Extension,
160                                  const TargetData &TD, unsigned Depth) {
161  assert(V->getType()->isIntegerTy() && "Not an integer value");
162
163  // Limit our recursion depth.
164  if (Depth == 6) {
165    Scale = 1;
166    Offset = 0;
167    return V;
168  }
169
170  if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(V)) {
171    if (ConstantInt *RHSC = dyn_cast<ConstantInt>(BOp->getOperand(1))) {
172      switch (BOp->getOpcode()) {
173      default: break;
174      case Instruction::Or:
175        // X|C == X+C if all the bits in C are unset in X.  Otherwise we can't
176        // analyze it.
177        if (!MaskedValueIsZero(BOp->getOperand(0), RHSC->getValue(), &TD))
178          break;
179        // FALL THROUGH.
180      case Instruction::Add:
181        V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
182                                TD, Depth+1);
183        Offset += RHSC->getValue();
184        return V;
185      case Instruction::Mul:
186        V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
187                                TD, Depth+1);
188        Offset *= RHSC->getValue();
189        Scale *= RHSC->getValue();
190        return V;
191      case Instruction::Shl:
192        V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
193                                TD, Depth+1);
194        Offset <<= RHSC->getValue().getLimitedValue();
195        Scale <<= RHSC->getValue().getLimitedValue();
196        return V;
197      }
198    }
199  }
200
201  // Since GEP indices are sign extended anyway, we don't care about the high
202  // bits of a sign or zero extended value - just scales and offsets.  The
203  // extensions have to be consistent though.
204  if ((isa<SExtInst>(V) && Extension != EK_ZeroExt) ||
205      (isa<ZExtInst>(V) && Extension != EK_SignExt)) {
206    Value *CastOp = cast<CastInst>(V)->getOperand(0);
207    unsigned OldWidth = Scale.getBitWidth();
208    unsigned SmallWidth = CastOp->getType()->getPrimitiveSizeInBits();
209    Scale.trunc(SmallWidth);
210    Offset.trunc(SmallWidth);
211    Extension = isa<SExtInst>(V) ? EK_SignExt : EK_ZeroExt;
212
213    Value *Result = GetLinearExpression(CastOp, Scale, Offset, Extension,
214                                        TD, Depth+1);
215    Scale.zext(OldWidth);
216    Offset.zext(OldWidth);
217
218    return Result;
219  }
220
221  Scale = 1;
222  Offset = 0;
223  return V;
224}
225
226/// DecomposeGEPExpression - If V is a symbolic pointer expression, decompose it
227/// into a base pointer with a constant offset and a number of scaled symbolic
228/// offsets.
229///
230/// The scaled symbolic offsets (represented by pairs of a Value* and a scale in
231/// the VarIndices vector) are Value*'s that are known to be scaled by the
232/// specified amount, but which may have other unrepresented high bits. As such,
233/// the gep cannot necessarily be reconstructed from its decomposed form.
234///
235/// When TargetData is around, this function is capable of analyzing everything
236/// that Value::getUnderlyingObject() can look through.  When not, it just looks
237/// through pointer casts.
238///
239static const Value *
240DecomposeGEPExpression(const Value *V, int64_t &BaseOffs,
241                       SmallVectorImpl<VariableGEPIndex> &VarIndices,
242                       const TargetData *TD) {
243  // Limit recursion depth to limit compile time in crazy cases.
244  unsigned MaxLookup = 6;
245
246  BaseOffs = 0;
247  do {
248    // See if this is a bitcast or GEP.
249    const Operator *Op = dyn_cast<Operator>(V);
250    if (Op == 0) {
251      // The only non-operator case we can handle are GlobalAliases.
252      if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
253        if (!GA->mayBeOverridden()) {
254          V = GA->getAliasee();
255          continue;
256        }
257      }
258      return V;
259    }
260
261    if (Op->getOpcode() == Instruction::BitCast) {
262      V = Op->getOperand(0);
263      continue;
264    }
265
266    const GEPOperator *GEPOp = dyn_cast<GEPOperator>(Op);
267    if (GEPOp == 0)
268      return V;
269
270    // Don't attempt to analyze GEPs over unsized objects.
271    if (!cast<PointerType>(GEPOp->getOperand(0)->getType())
272        ->getElementType()->isSized())
273      return V;
274
275    // If we are lacking TargetData information, we can't compute the offets of
276    // elements computed by GEPs.  However, we can handle bitcast equivalent
277    // GEPs.
278    if (TD == 0) {
279      if (!GEPOp->hasAllZeroIndices())
280        return V;
281      V = GEPOp->getOperand(0);
282      continue;
283    }
284
285    // Walk the indices of the GEP, accumulating them into BaseOff/VarIndices.
286    gep_type_iterator GTI = gep_type_begin(GEPOp);
287    for (User::const_op_iterator I = GEPOp->op_begin()+1,
288         E = GEPOp->op_end(); I != E; ++I) {
289      Value *Index = *I;
290      // Compute the (potentially symbolic) offset in bytes for this index.
291      if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
292        // For a struct, add the member offset.
293        unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
294        if (FieldNo == 0) continue;
295
296        BaseOffs += TD->getStructLayout(STy)->getElementOffset(FieldNo);
297        continue;
298      }
299
300      // For an array/pointer, add the element offset, explicitly scaled.
301      if (ConstantInt *CIdx = dyn_cast<ConstantInt>(Index)) {
302        if (CIdx->isZero()) continue;
303        BaseOffs += TD->getTypeAllocSize(*GTI)*CIdx->getSExtValue();
304        continue;
305      }
306
307      uint64_t Scale = TD->getTypeAllocSize(*GTI);
308      ExtensionKind Extension = EK_NotExtended;
309
310      // If the integer type is smaller than the pointer size, it is implicitly
311      // sign extended to pointer size.
312      unsigned Width = cast<IntegerType>(Index->getType())->getBitWidth();
313      if (TD->getPointerSizeInBits() > Width)
314        Extension = EK_SignExt;
315
316      // Use GetLinearExpression to decompose the index into a C1*V+C2 form.
317      APInt IndexScale(Width, 0), IndexOffset(Width, 0);
318      Index = GetLinearExpression(Index, IndexScale, IndexOffset, Extension,
319                                  *TD, 0);
320
321      // The GEP index scale ("Scale") scales C1*V+C2, yielding (C1*V+C2)*Scale.
322      // This gives us an aggregate computation of (C1*Scale)*V + C2*Scale.
323      BaseOffs += IndexOffset.getSExtValue()*Scale;
324      Scale *= IndexScale.getSExtValue();
325
326
327      // If we already had an occurrance of this index variable, merge this
328      // scale into it.  For example, we want to handle:
329      //   A[x][x] -> x*16 + x*4 -> x*20
330      // This also ensures that 'x' only appears in the index list once.
331      for (unsigned i = 0, e = VarIndices.size(); i != e; ++i) {
332        if (VarIndices[i].V == Index &&
333            VarIndices[i].Extension == Extension) {
334          Scale += VarIndices[i].Scale;
335          VarIndices.erase(VarIndices.begin()+i);
336          break;
337        }
338      }
339
340      // Make sure that we have a scale that makes sense for this target's
341      // pointer size.
342      if (unsigned ShiftBits = 64-TD->getPointerSizeInBits()) {
343        Scale <<= ShiftBits;
344        Scale = (int64_t)Scale >> ShiftBits;
345      }
346
347      if (Scale) {
348        VariableGEPIndex Entry = {Index, Extension, Scale};
349        VarIndices.push_back(Entry);
350      }
351    }
352
353    // Analyze the base pointer next.
354    V = GEPOp->getOperand(0);
355  } while (--MaxLookup);
356
357  // If the chain of expressions is too deep, just return early.
358  return V;
359}
360
361/// GetIndexDifference - Dest and Src are the variable indices from two
362/// decomposed GetElementPtr instructions GEP1 and GEP2 which have common base
363/// pointers.  Subtract the GEP2 indices from GEP1 to find the symbolic
364/// difference between the two pointers.
365static void GetIndexDifference(SmallVectorImpl<VariableGEPIndex> &Dest,
366                               const SmallVectorImpl<VariableGEPIndex> &Src) {
367  if (Src.empty()) return;
368
369  for (unsigned i = 0, e = Src.size(); i != e; ++i) {
370    const Value *V = Src[i].V;
371    ExtensionKind Extension = Src[i].Extension;
372    int64_t Scale = Src[i].Scale;
373
374    // Find V in Dest.  This is N^2, but pointer indices almost never have more
375    // than a few variable indexes.
376    for (unsigned j = 0, e = Dest.size(); j != e; ++j) {
377      if (Dest[j].V != V || Dest[j].Extension != Extension) continue;
378
379      // If we found it, subtract off Scale V's from the entry in Dest.  If it
380      // goes to zero, remove the entry.
381      if (Dest[j].Scale != Scale)
382        Dest[j].Scale -= Scale;
383      else
384        Dest.erase(Dest.begin()+j);
385      Scale = 0;
386      break;
387    }
388
389    // If we didn't consume this entry, add it to the end of the Dest list.
390    if (Scale) {
391      VariableGEPIndex Entry = { V, Extension, -Scale };
392      Dest.push_back(Entry);
393    }
394  }
395}
396
397//===----------------------------------------------------------------------===//
398// BasicAliasAnalysis Pass
399//===----------------------------------------------------------------------===//
400
401#ifndef NDEBUG
402static const Function *getParent(const Value *V) {
403  if (const Instruction *inst = dyn_cast<Instruction>(V))
404    return inst->getParent()->getParent();
405
406  if (const Argument *arg = dyn_cast<Argument>(V))
407    return arg->getParent();
408
409  return NULL;
410}
411
412static bool notDifferentParent(const Value *O1, const Value *O2) {
413
414  const Function *F1 = getParent(O1);
415  const Function *F2 = getParent(O2);
416
417  return !F1 || !F2 || F1 == F2;
418}
419#endif
420
421namespace {
422  /// BasicAliasAnalysis - This is the primary alias analysis implementation.
423  struct BasicAliasAnalysis : public ImmutablePass, public AliasAnalysis {
424    static char ID; // Class identification, replacement for typeinfo
425    BasicAliasAnalysis() : ImmutablePass(ID) {
426      initializeBasicAliasAnalysisPass(*PassRegistry::getPassRegistry());
427    }
428
429    virtual void initializePass() {
430      InitializeAliasAnalysis(this);
431    }
432
433    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
434      AU.addRequired<AliasAnalysis>();
435    }
436
437    virtual AliasResult alias(const Location &LocA,
438                              const Location &LocB) {
439      assert(Visited.empty() && "Visited must be cleared after use!");
440      assert(notDifferentParent(LocA.Ptr, LocB.Ptr) &&
441             "BasicAliasAnalysis doesn't support interprocedural queries.");
442      AliasResult Alias = aliasCheck(LocA.Ptr, LocA.Size, LocA.TBAATag,
443                                     LocB.Ptr, LocB.Size, LocB.TBAATag);
444      Visited.clear();
445      return Alias;
446    }
447
448    virtual ModRefResult getModRefInfo(ImmutableCallSite CS,
449                                       const Location &Loc);
450
451    virtual ModRefResult getModRefInfo(ImmutableCallSite CS1,
452                                       ImmutableCallSite CS2) {
453      // The AliasAnalysis base class has some smarts, lets use them.
454      return AliasAnalysis::getModRefInfo(CS1, CS2);
455    }
456
457    /// pointsToConstantMemory - Chase pointers until we find a (constant
458    /// global) or not.
459    virtual bool pointsToConstantMemory(const Location &Loc);
460
461    /// getModRefBehavior - Return the behavior when calling the given
462    /// call site.
463    virtual ModRefBehavior getModRefBehavior(ImmutableCallSite CS);
464
465    /// getModRefBehavior - Return the behavior when calling the given function.
466    /// For use when the call site is not known.
467    virtual ModRefBehavior getModRefBehavior(const Function *F);
468
469    /// getAdjustedAnalysisPointer - This method is used when a pass implements
470    /// an analysis interface through multiple inheritance.  If needed, it
471    /// should override this to adjust the this pointer as needed for the
472    /// specified pass info.
473    virtual void *getAdjustedAnalysisPointer(const void *ID) {
474      if (ID == &AliasAnalysis::ID)
475        return (AliasAnalysis*)this;
476      return this;
477    }
478
479  private:
480    // Visited - Track instructions visited by a aliasPHI, aliasSelect(), and aliasGEP().
481    SmallPtrSet<const Value*, 16> Visited;
482
483    // aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP
484    // instruction against another.
485    AliasResult aliasGEP(const GEPOperator *V1, uint64_t V1Size,
486                         const Value *V2, uint64_t V2Size,
487                         const MDNode *V2TBAAInfo,
488                         const Value *UnderlyingV1, const Value *UnderlyingV2);
489
490    // aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI
491    // instruction against another.
492    AliasResult aliasPHI(const PHINode *PN, uint64_t PNSize,
493                         const MDNode *PNTBAAInfo,
494                         const Value *V2, uint64_t V2Size,
495                         const MDNode *V2TBAAInfo);
496
497    /// aliasSelect - Disambiguate a Select instruction against another value.
498    AliasResult aliasSelect(const SelectInst *SI, uint64_t SISize,
499                            const MDNode *SITBAAInfo,
500                            const Value *V2, uint64_t V2Size,
501                            const MDNode *V2TBAAInfo);
502
503    AliasResult aliasCheck(const Value *V1, uint64_t V1Size,
504                           const MDNode *V1TBAATag,
505                           const Value *V2, uint64_t V2Size,
506                           const MDNode *V2TBAATag);
507  };
508}  // End of anonymous namespace
509
510// Register this pass...
511char BasicAliasAnalysis::ID = 0;
512INITIALIZE_AG_PASS(BasicAliasAnalysis, AliasAnalysis, "basicaa",
513                   "Basic Alias Analysis (stateless AA impl)",
514                   false, true, false)
515
516ImmutablePass *llvm::createBasicAliasAnalysisPass() {
517  return new BasicAliasAnalysis();
518}
519
520
521/// pointsToConstantMemory - Chase pointers until we find a (constant
522/// global) or not.
523bool BasicAliasAnalysis::pointsToConstantMemory(const Location &Loc) {
524  if (const GlobalVariable *GV =
525        dyn_cast<GlobalVariable>(Loc.Ptr->getUnderlyingObject()))
526    // Note: this doesn't require GV to be "ODR" because it isn't legal for a
527    // global to be marked constant in some modules and non-constant in others.
528    // GV may even be a declaration, not a definition.
529    return GV->isConstant();
530
531  return AliasAnalysis::pointsToConstantMemory(Loc);
532}
533
534/// getModRefBehavior - Return the behavior when calling the given call site.
535AliasAnalysis::ModRefBehavior
536BasicAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
537  if (CS.doesNotAccessMemory())
538    // Can't do better than this.
539    return DoesNotAccessMemory;
540
541  ModRefBehavior Min = UnknownModRefBehavior;
542
543  // If the callsite knows it only reads memory, don't return worse
544  // than that.
545  if (CS.onlyReadsMemory())
546    Min = OnlyReadsMemory;
547
548  // The AliasAnalysis base class has some smarts, lets use them.
549  return std::min(AliasAnalysis::getModRefBehavior(CS), Min);
550}
551
552/// getModRefBehavior - Return the behavior when calling the given function.
553/// For use when the call site is not known.
554AliasAnalysis::ModRefBehavior
555BasicAliasAnalysis::getModRefBehavior(const Function *F) {
556  if (F->doesNotAccessMemory())
557    // Can't do better than this.
558    return DoesNotAccessMemory;
559  if (F->onlyReadsMemory())
560    return OnlyReadsMemory;
561  if (unsigned id = F->getIntrinsicID())
562    return getIntrinsicModRefBehavior(id);
563
564  return AliasAnalysis::getModRefBehavior(F);
565}
566
567/// getModRefInfo - Check to see if the specified callsite can clobber the
568/// specified memory object.  Since we only look at local properties of this
569/// function, we really can't say much about this query.  We do, however, use
570/// simple "address taken" analysis on local objects.
571AliasAnalysis::ModRefResult
572BasicAliasAnalysis::getModRefInfo(ImmutableCallSite CS,
573                                  const Location &Loc) {
574  assert(notDifferentParent(CS.getInstruction(), Loc.Ptr) &&
575         "AliasAnalysis query involving multiple functions!");
576
577  const Value *Object = Loc.Ptr->getUnderlyingObject();
578
579  // If this is a tail call and Loc.Ptr points to a stack location, we know that
580  // the tail call cannot access or modify the local stack.
581  // We cannot exclude byval arguments here; these belong to the caller of
582  // the current function not to the current function, and a tail callee
583  // may reference them.
584  if (isa<AllocaInst>(Object))
585    if (const CallInst *CI = dyn_cast<CallInst>(CS.getInstruction()))
586      if (CI->isTailCall())
587        return NoModRef;
588
589  // If the pointer is to a locally allocated object that does not escape,
590  // then the call can not mod/ref the pointer unless the call takes the pointer
591  // as an argument, and itself doesn't capture it.
592  if (!isa<Constant>(Object) && CS.getInstruction() != Object &&
593      isNonEscapingLocalObject(Object)) {
594    bool PassedAsArg = false;
595    unsigned ArgNo = 0;
596    for (ImmutableCallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
597         CI != CE; ++CI, ++ArgNo) {
598      // Only look at the no-capture pointer arguments.
599      if (!(*CI)->getType()->isPointerTy() ||
600          !CS.paramHasAttr(ArgNo+1, Attribute::NoCapture))
601        continue;
602
603      // If this is a no-capture pointer argument, see if we can tell that it
604      // is impossible to alias the pointer we're checking.  If not, we have to
605      // assume that the call could touch the pointer, even though it doesn't
606      // escape.
607      if (!isNoAlias(Location(cast<Value>(CI)), Loc)) {
608        PassedAsArg = true;
609        break;
610      }
611    }
612
613    if (!PassedAsArg)
614      return NoModRef;
615  }
616
617  // Finally, handle specific knowledge of intrinsics.
618  const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction());
619  if (II != 0)
620    switch (II->getIntrinsicID()) {
621    default: break;
622    case Intrinsic::memcpy:
623    case Intrinsic::memmove: {
624      uint64_t Len = UnknownSize;
625      if (ConstantInt *LenCI = dyn_cast<ConstantInt>(II->getArgOperand(2)))
626        Len = LenCI->getZExtValue();
627      Value *Dest = II->getArgOperand(0);
628      Value *Src = II->getArgOperand(1);
629      if (isNoAlias(Location(Dest, Len), Loc)) {
630        if (isNoAlias(Location(Src, Len), Loc))
631          return NoModRef;
632        return Ref;
633      }
634      break;
635    }
636    case Intrinsic::memset:
637      // Since memset is 'accesses arguments' only, the AliasAnalysis base class
638      // will handle it for the variable length case.
639      if (ConstantInt *LenCI = dyn_cast<ConstantInt>(II->getArgOperand(2))) {
640        uint64_t Len = LenCI->getZExtValue();
641        Value *Dest = II->getArgOperand(0);
642        if (isNoAlias(Location(Dest, Len), Loc))
643          return NoModRef;
644      }
645      break;
646    case Intrinsic::atomic_cmp_swap:
647    case Intrinsic::atomic_swap:
648    case Intrinsic::atomic_load_add:
649    case Intrinsic::atomic_load_sub:
650    case Intrinsic::atomic_load_and:
651    case Intrinsic::atomic_load_nand:
652    case Intrinsic::atomic_load_or:
653    case Intrinsic::atomic_load_xor:
654    case Intrinsic::atomic_load_max:
655    case Intrinsic::atomic_load_min:
656    case Intrinsic::atomic_load_umax:
657    case Intrinsic::atomic_load_umin:
658      if (TD) {
659        Value *Op1 = II->getArgOperand(0);
660        uint64_t Op1Size = TD->getTypeStoreSize(Op1->getType());
661        MDNode *Tag = II->getMetadata(LLVMContext::MD_tbaa);
662        if (isNoAlias(Location(Op1, Op1Size, Tag), Loc))
663          return NoModRef;
664      }
665      break;
666    case Intrinsic::lifetime_start:
667    case Intrinsic::lifetime_end:
668    case Intrinsic::invariant_start: {
669      uint64_t PtrSize =
670        cast<ConstantInt>(II->getArgOperand(0))->getZExtValue();
671      if (isNoAlias(Location(II->getArgOperand(1),
672                             PtrSize,
673                             II->getMetadata(LLVMContext::MD_tbaa)),
674                    Loc))
675        return NoModRef;
676      break;
677    }
678    case Intrinsic::invariant_end: {
679      uint64_t PtrSize =
680        cast<ConstantInt>(II->getArgOperand(1))->getZExtValue();
681      if (isNoAlias(Location(II->getArgOperand(2),
682                             PtrSize,
683                             II->getMetadata(LLVMContext::MD_tbaa)),
684                    Loc))
685        return NoModRef;
686      break;
687    }
688    }
689
690  // The AliasAnalysis base class has some smarts, lets use them.
691  return AliasAnalysis::getModRefInfo(CS, Loc);
692}
693
694/// aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP instruction
695/// against another pointer.  We know that V1 is a GEP, but we don't know
696/// anything about V2.  UnderlyingV1 is GEP1->getUnderlyingObject(),
697/// UnderlyingV2 is the same for V2.
698///
699AliasAnalysis::AliasResult
700BasicAliasAnalysis::aliasGEP(const GEPOperator *GEP1, uint64_t V1Size,
701                             const Value *V2, uint64_t V2Size,
702                             const MDNode *V2TBAAInfo,
703                             const Value *UnderlyingV1,
704                             const Value *UnderlyingV2) {
705  // If this GEP has been visited before, we're on a use-def cycle.
706  // Such cycles are only valid when PHI nodes are involved or in unreachable
707  // code. The visitPHI function catches cycles containing PHIs, but there
708  // could still be a cycle without PHIs in unreachable code.
709  if (!Visited.insert(GEP1))
710    return MayAlias;
711
712  int64_t GEP1BaseOffset;
713  SmallVector<VariableGEPIndex, 4> GEP1VariableIndices;
714
715  // If we have two gep instructions with must-alias'ing base pointers, figure
716  // out if the indexes to the GEP tell us anything about the derived pointer.
717  if (const GEPOperator *GEP2 = dyn_cast<GEPOperator>(V2)) {
718    // Do the base pointers alias?
719    AliasResult BaseAlias = aliasCheck(UnderlyingV1, UnknownSize, 0,
720                                       UnderlyingV2, UnknownSize, 0);
721
722    // If we get a No or May, then return it immediately, no amount of analysis
723    // will improve this situation.
724    if (BaseAlias != MustAlias) return BaseAlias;
725
726    // Otherwise, we have a MustAlias.  Since the base pointers alias each other
727    // exactly, see if the computed offset from the common pointer tells us
728    // about the relation of the resulting pointer.
729    const Value *GEP1BasePtr =
730      DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices, TD);
731
732    int64_t GEP2BaseOffset;
733    SmallVector<VariableGEPIndex, 4> GEP2VariableIndices;
734    const Value *GEP2BasePtr =
735      DecomposeGEPExpression(GEP2, GEP2BaseOffset, GEP2VariableIndices, TD);
736
737    // If DecomposeGEPExpression isn't able to look all the way through the
738    // addressing operation, we must not have TD and this is too complex for us
739    // to handle without it.
740    if (GEP1BasePtr != UnderlyingV1 || GEP2BasePtr != UnderlyingV2) {
741      assert(TD == 0 &&
742             "DecomposeGEPExpression and getUnderlyingObject disagree!");
743      return MayAlias;
744    }
745
746    // Subtract the GEP2 pointer from the GEP1 pointer to find out their
747    // symbolic difference.
748    GEP1BaseOffset -= GEP2BaseOffset;
749    GetIndexDifference(GEP1VariableIndices, GEP2VariableIndices);
750
751  } else {
752    // Check to see if these two pointers are related by the getelementptr
753    // instruction.  If one pointer is a GEP with a non-zero index of the other
754    // pointer, we know they cannot alias.
755
756    // If both accesses are unknown size, we can't do anything useful here.
757    if (V1Size == UnknownSize && V2Size == UnknownSize)
758      return MayAlias;
759
760    AliasResult R = aliasCheck(UnderlyingV1, UnknownSize, 0,
761                               V2, V2Size, V2TBAAInfo);
762    if (R != MustAlias)
763      // If V2 may alias GEP base pointer, conservatively returns MayAlias.
764      // If V2 is known not to alias GEP base pointer, then the two values
765      // cannot alias per GEP semantics: "A pointer value formed from a
766      // getelementptr instruction is associated with the addresses associated
767      // with the first operand of the getelementptr".
768      return R;
769
770    const Value *GEP1BasePtr =
771      DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices, TD);
772
773    // If DecomposeGEPExpression isn't able to look all the way through the
774    // addressing operation, we must not have TD and this is too complex for us
775    // to handle without it.
776    if (GEP1BasePtr != UnderlyingV1) {
777      assert(TD == 0 &&
778             "DecomposeGEPExpression and getUnderlyingObject disagree!");
779      return MayAlias;
780    }
781  }
782
783  // In the two GEP Case, if there is no difference in the offsets of the
784  // computed pointers, the resultant pointers are a must alias.  This
785  // hapens when we have two lexically identical GEP's (for example).
786  //
787  // In the other case, if we have getelementptr <ptr>, 0, 0, 0, 0, ... and V2
788  // must aliases the GEP, the end result is a must alias also.
789  if (GEP1BaseOffset == 0 && GEP1VariableIndices.empty())
790    return MustAlias;
791
792  // If we have a known constant offset, see if this offset is larger than the
793  // access size being queried.  If so, and if no variable indices can remove
794  // pieces of this constant, then we know we have a no-alias.  For example,
795  //   &A[100] != &A.
796
797  // In order to handle cases like &A[100][i] where i is an out of range
798  // subscript, we have to ignore all constant offset pieces that are a multiple
799  // of a scaled index.  Do this by removing constant offsets that are a
800  // multiple of any of our variable indices.  This allows us to transform
801  // things like &A[i][1] because i has a stride of (e.g.) 8 bytes but the 1
802  // provides an offset of 4 bytes (assuming a <= 4 byte access).
803  for (unsigned i = 0, e = GEP1VariableIndices.size();
804       i != e && GEP1BaseOffset;++i)
805    if (int64_t RemovedOffset = GEP1BaseOffset/GEP1VariableIndices[i].Scale)
806      GEP1BaseOffset -= RemovedOffset*GEP1VariableIndices[i].Scale;
807
808  // If our known offset is bigger than the access size, we know we don't have
809  // an alias.
810  if (GEP1BaseOffset) {
811    if (GEP1BaseOffset >= 0 ?
812        (V2Size != UnknownSize && (uint64_t)GEP1BaseOffset >= V2Size) :
813        (V1Size != UnknownSize && -(uint64_t)GEP1BaseOffset >= V1Size &&
814         GEP1BaseOffset != INT64_MIN))
815      return NoAlias;
816  }
817
818  return MayAlias;
819}
820
821/// aliasSelect - Provide a bunch of ad-hoc rules to disambiguate a Select
822/// instruction against another.
823AliasAnalysis::AliasResult
824BasicAliasAnalysis::aliasSelect(const SelectInst *SI, uint64_t SISize,
825                                const MDNode *SITBAAInfo,
826                                const Value *V2, uint64_t V2Size,
827                                const MDNode *V2TBAAInfo) {
828  // If this select has been visited before, we're on a use-def cycle.
829  // Such cycles are only valid when PHI nodes are involved or in unreachable
830  // code. The visitPHI function catches cycles containing PHIs, but there
831  // could still be a cycle without PHIs in unreachable code.
832  if (!Visited.insert(SI))
833    return MayAlias;
834
835  // If the values are Selects with the same condition, we can do a more precise
836  // check: just check for aliases between the values on corresponding arms.
837  if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2))
838    if (SI->getCondition() == SI2->getCondition()) {
839      AliasResult Alias =
840        aliasCheck(SI->getTrueValue(), SISize, SITBAAInfo,
841                   SI2->getTrueValue(), V2Size, V2TBAAInfo);
842      if (Alias == MayAlias)
843        return MayAlias;
844      AliasResult ThisAlias =
845        aliasCheck(SI->getFalseValue(), SISize, SITBAAInfo,
846                   SI2->getFalseValue(), V2Size, V2TBAAInfo);
847      if (ThisAlias != Alias)
848        return MayAlias;
849      return Alias;
850    }
851
852  // If both arms of the Select node NoAlias or MustAlias V2, then returns
853  // NoAlias / MustAlias. Otherwise, returns MayAlias.
854  AliasResult Alias =
855    aliasCheck(V2, V2Size, V2TBAAInfo, SI->getTrueValue(), SISize, SITBAAInfo);
856  if (Alias == MayAlias)
857    return MayAlias;
858
859  // If V2 is visited, the recursive case will have been caught in the
860  // above aliasCheck call, so these subsequent calls to aliasCheck
861  // don't need to assume that V2 is being visited recursively.
862  Visited.erase(V2);
863
864  AliasResult ThisAlias =
865    aliasCheck(V2, V2Size, V2TBAAInfo, SI->getFalseValue(), SISize, SITBAAInfo);
866  if (ThisAlias != Alias)
867    return MayAlias;
868  return Alias;
869}
870
871// aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI instruction
872// against another.
873AliasAnalysis::AliasResult
874BasicAliasAnalysis::aliasPHI(const PHINode *PN, uint64_t PNSize,
875                             const MDNode *PNTBAAInfo,
876                             const Value *V2, uint64_t V2Size,
877                             const MDNode *V2TBAAInfo) {
878  // The PHI node has already been visited, avoid recursion any further.
879  if (!Visited.insert(PN))
880    return MayAlias;
881
882  // If the values are PHIs in the same block, we can do a more precise
883  // as well as efficient check: just check for aliases between the values
884  // on corresponding edges.
885  if (const PHINode *PN2 = dyn_cast<PHINode>(V2))
886    if (PN2->getParent() == PN->getParent()) {
887      AliasResult Alias =
888        aliasCheck(PN->getIncomingValue(0), PNSize, PNTBAAInfo,
889                   PN2->getIncomingValueForBlock(PN->getIncomingBlock(0)),
890                   V2Size, V2TBAAInfo);
891      if (Alias == MayAlias)
892        return MayAlias;
893      for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
894        AliasResult ThisAlias =
895          aliasCheck(PN->getIncomingValue(i), PNSize, PNTBAAInfo,
896                     PN2->getIncomingValueForBlock(PN->getIncomingBlock(i)),
897                     V2Size, V2TBAAInfo);
898        if (ThisAlias != Alias)
899          return MayAlias;
900      }
901      return Alias;
902    }
903
904  SmallPtrSet<Value*, 4> UniqueSrc;
905  SmallVector<Value*, 4> V1Srcs;
906  for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
907    Value *PV1 = PN->getIncomingValue(i);
908    if (isa<PHINode>(PV1))
909      // If any of the source itself is a PHI, return MayAlias conservatively
910      // to avoid compile time explosion. The worst possible case is if both
911      // sides are PHI nodes. In which case, this is O(m x n) time where 'm'
912      // and 'n' are the number of PHI sources.
913      return MayAlias;
914    if (UniqueSrc.insert(PV1))
915      V1Srcs.push_back(PV1);
916  }
917
918  AliasResult Alias = aliasCheck(V2, V2Size, V2TBAAInfo,
919                                 V1Srcs[0], PNSize, PNTBAAInfo);
920  // Early exit if the check of the first PHI source against V2 is MayAlias.
921  // Other results are not possible.
922  if (Alias == MayAlias)
923    return MayAlias;
924
925  // If all sources of the PHI node NoAlias or MustAlias V2, then returns
926  // NoAlias / MustAlias. Otherwise, returns MayAlias.
927  for (unsigned i = 1, e = V1Srcs.size(); i != e; ++i) {
928    Value *V = V1Srcs[i];
929
930    // If V2 is visited, the recursive case will have been caught in the
931    // above aliasCheck call, so these subsequent calls to aliasCheck
932    // don't need to assume that V2 is being visited recursively.
933    Visited.erase(V2);
934
935    AliasResult ThisAlias = aliasCheck(V2, V2Size, V2TBAAInfo,
936                                       V, PNSize, PNTBAAInfo);
937    if (ThisAlias != Alias || ThisAlias == MayAlias)
938      return MayAlias;
939  }
940
941  return Alias;
942}
943
944// aliasCheck - Provide a bunch of ad-hoc rules to disambiguate in common cases,
945// such as array references.
946//
947AliasAnalysis::AliasResult
948BasicAliasAnalysis::aliasCheck(const Value *V1, uint64_t V1Size,
949                               const MDNode *V1TBAAInfo,
950                               const Value *V2, uint64_t V2Size,
951                               const MDNode *V2TBAAInfo) {
952  // If either of the memory references is empty, it doesn't matter what the
953  // pointer values are.
954  if (V1Size == 0 || V2Size == 0)
955    return NoAlias;
956
957  // Strip off any casts if they exist.
958  V1 = V1->stripPointerCasts();
959  V2 = V2->stripPointerCasts();
960
961  // Are we checking for alias of the same value?
962  if (V1 == V2) return MustAlias;
963
964  if (!V1->getType()->isPointerTy() || !V2->getType()->isPointerTy())
965    return NoAlias;  // Scalars cannot alias each other
966
967  // Figure out what objects these things are pointing to if we can.
968  const Value *O1 = V1->getUnderlyingObject();
969  const Value *O2 = V2->getUnderlyingObject();
970
971  // Null values in the default address space don't point to any object, so they
972  // don't alias any other pointer.
973  if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O1))
974    if (CPN->getType()->getAddressSpace() == 0)
975      return NoAlias;
976  if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O2))
977    if (CPN->getType()->getAddressSpace() == 0)
978      return NoAlias;
979
980  if (O1 != O2) {
981    // If V1/V2 point to two different objects we know that we have no alias.
982    if (isIdentifiedObject(O1) && isIdentifiedObject(O2))
983      return NoAlias;
984
985    // Constant pointers can't alias with non-const isIdentifiedObject objects.
986    if ((isa<Constant>(O1) && isIdentifiedObject(O2) && !isa<Constant>(O2)) ||
987        (isa<Constant>(O2) && isIdentifiedObject(O1) && !isa<Constant>(O1)))
988      return NoAlias;
989
990    // Arguments can't alias with local allocations or noalias calls
991    // in the same function.
992    if (((isa<Argument>(O1) && (isa<AllocaInst>(O2) || isNoAliasCall(O2))) ||
993         (isa<Argument>(O2) && (isa<AllocaInst>(O1) || isNoAliasCall(O1)))))
994      return NoAlias;
995
996    // Most objects can't alias null.
997    if ((isa<ConstantPointerNull>(O2) && isKnownNonNull(O1)) ||
998        (isa<ConstantPointerNull>(O1) && isKnownNonNull(O2)))
999      return NoAlias;
1000
1001    // If one pointer is the result of a call/invoke or load and the other is a
1002    // non-escaping local object within the same function, then we know the
1003    // object couldn't escape to a point where the call could return it.
1004    //
1005    // Note that if the pointers are in different functions, there are a
1006    // variety of complications. A call with a nocapture argument may still
1007    // temporary store the nocapture argument's value in a temporary memory
1008    // location if that memory location doesn't escape. Or it may pass a
1009    // nocapture value to other functions as long as they don't capture it.
1010    if (isEscapeSource(O1) && isNonEscapingLocalObject(O2))
1011      return NoAlias;
1012    if (isEscapeSource(O2) && isNonEscapingLocalObject(O1))
1013      return NoAlias;
1014  }
1015
1016  // If the size of one access is larger than the entire object on the other
1017  // side, then we know such behavior is undefined and can assume no alias.
1018  if (TD)
1019    if ((V1Size != UnknownSize && isObjectSmallerThan(O2, V1Size, *TD)) ||
1020        (V2Size != UnknownSize && isObjectSmallerThan(O1, V2Size, *TD)))
1021      return NoAlias;
1022
1023  // FIXME: This isn't aggressively handling alias(GEP, PHI) for example: if the
1024  // GEP can't simplify, we don't even look at the PHI cases.
1025  if (!isa<GEPOperator>(V1) && isa<GEPOperator>(V2)) {
1026    std::swap(V1, V2);
1027    std::swap(V1Size, V2Size);
1028    std::swap(O1, O2);
1029  }
1030  if (const GEPOperator *GV1 = dyn_cast<GEPOperator>(V1)) {
1031    AliasResult Result = aliasGEP(GV1, V1Size, V2, V2Size, V2TBAAInfo, O1, O2);
1032    if (Result != MayAlias) return Result;
1033  }
1034
1035  if (isa<PHINode>(V2) && !isa<PHINode>(V1)) {
1036    std::swap(V1, V2);
1037    std::swap(V1Size, V2Size);
1038  }
1039  if (const PHINode *PN = dyn_cast<PHINode>(V1)) {
1040    AliasResult Result = aliasPHI(PN, V1Size, V1TBAAInfo,
1041                                  V2, V2Size, V2TBAAInfo);
1042    if (Result != MayAlias) return Result;
1043  }
1044
1045  if (isa<SelectInst>(V2) && !isa<SelectInst>(V1)) {
1046    std::swap(V1, V2);
1047    std::swap(V1Size, V2Size);
1048  }
1049  if (const SelectInst *S1 = dyn_cast<SelectInst>(V1)) {
1050    AliasResult Result = aliasSelect(S1, V1Size, V1TBAAInfo,
1051                                     V2, V2Size, V2TBAAInfo);
1052    if (Result != MayAlias) return Result;
1053  }
1054
1055  return AliasAnalysis::alias(Location(V1, V1Size, V1TBAAInfo),
1056                              Location(V2, V2Size, V2TBAAInfo));
1057}
1058