BasicAliasAnalysis.cpp revision 201d1e56bb7535802c70d5eb46601afcc325045d
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, bool OrLocal);
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/// pointsToConstantMemory - Returns whether the given pointer value
521/// points to memory that is local to the function, with global constants being
522/// considered local to all functions.
523bool
524BasicAliasAnalysis::pointsToConstantMemory(const Location &Loc, bool OrLocal) {
525  assert(Visited.empty() && "Visited must be cleared after use!");
526
527  unsigned MaxLookup = 8;
528  SmallVector<const Value *, 16> Worklist;
529  Worklist.push_back(Loc.Ptr);
530  do {
531    const Value *V = Worklist.pop_back_val()->getUnderlyingObject();
532    if (!Visited.insert(V)) {
533      Visited.clear();
534      return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
535    }
536
537    // An alloca instruction defines local memory.
538    if (OrLocal && isa<AllocaInst>(V))
539      continue;
540
541    // A global constant counts as local memory for our purposes.
542    if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
543      // Note: this doesn't require GV to be "ODR" because it isn't legal for a
544      // global to be marked constant in some modules and non-constant in
545      // others.  GV may even be a declaration, not a definition.
546      if (!GV->isConstant()) {
547        Visited.clear();
548        return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
549      }
550      continue;
551    }
552
553    // If both select values point to local memory, then so does the select.
554    if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
555      Worklist.push_back(SI->getTrueValue());
556      Worklist.push_back(SI->getFalseValue());
557      continue;
558    }
559
560    // If all values incoming to a phi node point to local memory, then so does
561    // the phi.
562    if (const PHINode *PN = dyn_cast<PHINode>(V)) {
563      // Don't bother inspecting phi nodes with many operands.
564      if (PN->getNumIncomingValues() > MaxLookup) {
565        Visited.clear();
566        return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
567      }
568      for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
569        Worklist.push_back(PN->getIncomingValue(i));
570      continue;
571    }
572
573    // Otherwise be conservative.
574    Visited.clear();
575    return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
576
577  } while (!Worklist.empty() && --MaxLookup);
578
579  Visited.clear();
580  return Worklist.empty();
581}
582
583/// getModRefBehavior - Return the behavior when calling the given call site.
584AliasAnalysis::ModRefBehavior
585BasicAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
586  if (CS.doesNotAccessMemory())
587    // Can't do better than this.
588    return DoesNotAccessMemory;
589
590  ModRefBehavior Min = UnknownModRefBehavior;
591
592  // If the callsite knows it only reads memory, don't return worse
593  // than that.
594  if (CS.onlyReadsMemory())
595    Min = OnlyReadsMemory;
596
597  // The AliasAnalysis base class has some smarts, lets use them.
598  return ModRefBehavior(AliasAnalysis::getModRefBehavior(CS) & Min);
599}
600
601/// getModRefBehavior - Return the behavior when calling the given function.
602/// For use when the call site is not known.
603AliasAnalysis::ModRefBehavior
604BasicAliasAnalysis::getModRefBehavior(const Function *F) {
605  // If the function declares it doesn't access memory, we can't do better.
606  if (F->doesNotAccessMemory())
607    return DoesNotAccessMemory;
608
609  // For intrinsics, we can check the table.
610  if (unsigned iid = F->getIntrinsicID()) {
611#define GET_INTRINSIC_MODREF_BEHAVIOR
612#include "llvm/Intrinsics.gen"
613#undef GET_INTRINSIC_MODREF_BEHAVIOR
614  }
615
616  ModRefBehavior Min = UnknownModRefBehavior;
617
618  // If the function declares it only reads memory, go with that.
619  if (F->onlyReadsMemory())
620    Min = OnlyReadsMemory;
621
622  // Otherwise be conservative.
623  return ModRefBehavior(AliasAnalysis::getModRefBehavior(F) & Min);
624}
625
626/// getModRefInfo - Check to see if the specified callsite can clobber the
627/// specified memory object.  Since we only look at local properties of this
628/// function, we really can't say much about this query.  We do, however, use
629/// simple "address taken" analysis on local objects.
630AliasAnalysis::ModRefResult
631BasicAliasAnalysis::getModRefInfo(ImmutableCallSite CS,
632                                  const Location &Loc) {
633  assert(notDifferentParent(CS.getInstruction(), Loc.Ptr) &&
634         "AliasAnalysis query involving multiple functions!");
635
636  const Value *Object = Loc.Ptr->getUnderlyingObject();
637
638  // If this is a tail call and Loc.Ptr points to a stack location, we know that
639  // the tail call cannot access or modify the local stack.
640  // We cannot exclude byval arguments here; these belong to the caller of
641  // the current function not to the current function, and a tail callee
642  // may reference them.
643  if (isa<AllocaInst>(Object))
644    if (const CallInst *CI = dyn_cast<CallInst>(CS.getInstruction()))
645      if (CI->isTailCall())
646        return NoModRef;
647
648  // If the pointer is to a locally allocated object that does not escape,
649  // then the call can not mod/ref the pointer unless the call takes the pointer
650  // as an argument, and itself doesn't capture it.
651  if (!isa<Constant>(Object) && CS.getInstruction() != Object &&
652      isNonEscapingLocalObject(Object)) {
653    bool PassedAsArg = false;
654    unsigned ArgNo = 0;
655    for (ImmutableCallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
656         CI != CE; ++CI, ++ArgNo) {
657      // Only look at the no-capture pointer arguments.
658      if (!(*CI)->getType()->isPointerTy() ||
659          !CS.paramHasAttr(ArgNo+1, Attribute::NoCapture))
660        continue;
661
662      // If this is a no-capture pointer argument, see if we can tell that it
663      // is impossible to alias the pointer we're checking.  If not, we have to
664      // assume that the call could touch the pointer, even though it doesn't
665      // escape.
666      if (!isNoAlias(Location(cast<Value>(CI)), Loc)) {
667        PassedAsArg = true;
668        break;
669      }
670    }
671
672    if (!PassedAsArg)
673      return NoModRef;
674  }
675
676  ModRefResult Min = ModRef;
677
678  // Finally, handle specific knowledge of intrinsics.
679  const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction());
680  if (II != 0)
681    switch (II->getIntrinsicID()) {
682    default: break;
683    case Intrinsic::memcpy:
684    case Intrinsic::memmove: {
685      uint64_t Len = UnknownSize;
686      if (ConstantInt *LenCI = dyn_cast<ConstantInt>(II->getArgOperand(2)))
687        Len = LenCI->getZExtValue();
688      Value *Dest = II->getArgOperand(0);
689      Value *Src = II->getArgOperand(1);
690      if (isNoAlias(Location(Dest, Len), Loc)) {
691        if (isNoAlias(Location(Src, Len), Loc))
692          return NoModRef;
693        Min = Ref;
694      }
695      break;
696    }
697    case Intrinsic::memset:
698      // Since memset is 'accesses arguments' only, the AliasAnalysis base class
699      // will handle it for the variable length case.
700      if (ConstantInt *LenCI = dyn_cast<ConstantInt>(II->getArgOperand(2))) {
701        uint64_t Len = LenCI->getZExtValue();
702        Value *Dest = II->getArgOperand(0);
703        if (isNoAlias(Location(Dest, Len), Loc))
704          return NoModRef;
705      }
706      // We know that memset doesn't load anything.
707      Min = Mod;
708      break;
709    case Intrinsic::atomic_cmp_swap:
710    case Intrinsic::atomic_swap:
711    case Intrinsic::atomic_load_add:
712    case Intrinsic::atomic_load_sub:
713    case Intrinsic::atomic_load_and:
714    case Intrinsic::atomic_load_nand:
715    case Intrinsic::atomic_load_or:
716    case Intrinsic::atomic_load_xor:
717    case Intrinsic::atomic_load_max:
718    case Intrinsic::atomic_load_min:
719    case Intrinsic::atomic_load_umax:
720    case Intrinsic::atomic_load_umin:
721      if (TD) {
722        Value *Op1 = II->getArgOperand(0);
723        uint64_t Op1Size = TD->getTypeStoreSize(Op1->getType());
724        MDNode *Tag = II->getMetadata(LLVMContext::MD_tbaa);
725        if (isNoAlias(Location(Op1, Op1Size, Tag), Loc))
726          return NoModRef;
727      }
728      break;
729    case Intrinsic::lifetime_start:
730    case Intrinsic::lifetime_end:
731    case Intrinsic::invariant_start: {
732      uint64_t PtrSize =
733        cast<ConstantInt>(II->getArgOperand(0))->getZExtValue();
734      if (isNoAlias(Location(II->getArgOperand(1),
735                             PtrSize,
736                             II->getMetadata(LLVMContext::MD_tbaa)),
737                    Loc))
738        return NoModRef;
739      break;
740    }
741    case Intrinsic::invariant_end: {
742      uint64_t PtrSize =
743        cast<ConstantInt>(II->getArgOperand(1))->getZExtValue();
744      if (isNoAlias(Location(II->getArgOperand(2),
745                             PtrSize,
746                             II->getMetadata(LLVMContext::MD_tbaa)),
747                    Loc))
748        return NoModRef;
749      break;
750    }
751    }
752
753  // The AliasAnalysis base class has some smarts, lets use them.
754  return ModRefResult(AliasAnalysis::getModRefInfo(CS, Loc) & Min);
755}
756
757/// aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP instruction
758/// against another pointer.  We know that V1 is a GEP, but we don't know
759/// anything about V2.  UnderlyingV1 is GEP1->getUnderlyingObject(),
760/// UnderlyingV2 is the same for V2.
761///
762AliasAnalysis::AliasResult
763BasicAliasAnalysis::aliasGEP(const GEPOperator *GEP1, uint64_t V1Size,
764                             const Value *V2, uint64_t V2Size,
765                             const MDNode *V2TBAAInfo,
766                             const Value *UnderlyingV1,
767                             const Value *UnderlyingV2) {
768  // If this GEP has been visited before, we're on a use-def cycle.
769  // Such cycles are only valid when PHI nodes are involved or in unreachable
770  // code. The visitPHI function catches cycles containing PHIs, but there
771  // could still be a cycle without PHIs in unreachable code.
772  if (!Visited.insert(GEP1))
773    return MayAlias;
774
775  int64_t GEP1BaseOffset;
776  SmallVector<VariableGEPIndex, 4> GEP1VariableIndices;
777
778  // If we have two gep instructions with must-alias'ing base pointers, figure
779  // out if the indexes to the GEP tell us anything about the derived pointer.
780  if (const GEPOperator *GEP2 = dyn_cast<GEPOperator>(V2)) {
781    // Do the base pointers alias?
782    AliasResult BaseAlias = aliasCheck(UnderlyingV1, UnknownSize, 0,
783                                       UnderlyingV2, UnknownSize, 0);
784
785    // If we get a No or May, then return it immediately, no amount of analysis
786    // will improve this situation.
787    if (BaseAlias != MustAlias) return BaseAlias;
788
789    // Otherwise, we have a MustAlias.  Since the base pointers alias each other
790    // exactly, see if the computed offset from the common pointer tells us
791    // about the relation of the resulting pointer.
792    const Value *GEP1BasePtr =
793      DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices, TD);
794
795    int64_t GEP2BaseOffset;
796    SmallVector<VariableGEPIndex, 4> GEP2VariableIndices;
797    const Value *GEP2BasePtr =
798      DecomposeGEPExpression(GEP2, GEP2BaseOffset, GEP2VariableIndices, TD);
799
800    // If DecomposeGEPExpression isn't able to look all the way through the
801    // addressing operation, we must not have TD and this is too complex for us
802    // to handle without it.
803    if (GEP1BasePtr != UnderlyingV1 || GEP2BasePtr != UnderlyingV2) {
804      assert(TD == 0 &&
805             "DecomposeGEPExpression and getUnderlyingObject disagree!");
806      return MayAlias;
807    }
808
809    // Subtract the GEP2 pointer from the GEP1 pointer to find out their
810    // symbolic difference.
811    GEP1BaseOffset -= GEP2BaseOffset;
812    GetIndexDifference(GEP1VariableIndices, GEP2VariableIndices);
813
814  } else {
815    // Check to see if these two pointers are related by the getelementptr
816    // instruction.  If one pointer is a GEP with a non-zero index of the other
817    // pointer, we know they cannot alias.
818
819    // If both accesses are unknown size, we can't do anything useful here.
820    if (V1Size == UnknownSize && V2Size == UnknownSize)
821      return MayAlias;
822
823    AliasResult R = aliasCheck(UnderlyingV1, UnknownSize, 0,
824                               V2, V2Size, V2TBAAInfo);
825    if (R != MustAlias)
826      // If V2 may alias GEP base pointer, conservatively returns MayAlias.
827      // If V2 is known not to alias GEP base pointer, then the two values
828      // cannot alias per GEP semantics: "A pointer value formed from a
829      // getelementptr instruction is associated with the addresses associated
830      // with the first operand of the getelementptr".
831      return R;
832
833    const Value *GEP1BasePtr =
834      DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices, TD);
835
836    // If DecomposeGEPExpression isn't able to look all the way through the
837    // addressing operation, we must not have TD and this is too complex for us
838    // to handle without it.
839    if (GEP1BasePtr != UnderlyingV1) {
840      assert(TD == 0 &&
841             "DecomposeGEPExpression and getUnderlyingObject disagree!");
842      return MayAlias;
843    }
844  }
845
846  // In the two GEP Case, if there is no difference in the offsets of the
847  // computed pointers, the resultant pointers are a must alias.  This
848  // hapens when we have two lexically identical GEP's (for example).
849  //
850  // In the other case, if we have getelementptr <ptr>, 0, 0, 0, 0, ... and V2
851  // must aliases the GEP, the end result is a must alias also.
852  if (GEP1BaseOffset == 0 && GEP1VariableIndices.empty())
853    return MustAlias;
854
855  // If we have a known constant offset, see if this offset is larger than the
856  // access size being queried.  If so, and if no variable indices can remove
857  // pieces of this constant, then we know we have a no-alias.  For example,
858  //   &A[100] != &A.
859
860  // In order to handle cases like &A[100][i] where i is an out of range
861  // subscript, we have to ignore all constant offset pieces that are a multiple
862  // of a scaled index.  Do this by removing constant offsets that are a
863  // multiple of any of our variable indices.  This allows us to transform
864  // things like &A[i][1] because i has a stride of (e.g.) 8 bytes but the 1
865  // provides an offset of 4 bytes (assuming a <= 4 byte access).
866  for (unsigned i = 0, e = GEP1VariableIndices.size();
867       i != e && GEP1BaseOffset;++i)
868    if (int64_t RemovedOffset = GEP1BaseOffset/GEP1VariableIndices[i].Scale)
869      GEP1BaseOffset -= RemovedOffset*GEP1VariableIndices[i].Scale;
870
871  // If our known offset is bigger than the access size, we know we don't have
872  // an alias.
873  if (GEP1BaseOffset) {
874    if (GEP1BaseOffset >= 0 ?
875        (V2Size != UnknownSize && (uint64_t)GEP1BaseOffset >= V2Size) :
876        (V1Size != UnknownSize && -(uint64_t)GEP1BaseOffset >= V1Size &&
877         GEP1BaseOffset != INT64_MIN))
878      return NoAlias;
879  }
880
881  return MayAlias;
882}
883
884/// aliasSelect - Provide a bunch of ad-hoc rules to disambiguate a Select
885/// instruction against another.
886AliasAnalysis::AliasResult
887BasicAliasAnalysis::aliasSelect(const SelectInst *SI, uint64_t SISize,
888                                const MDNode *SITBAAInfo,
889                                const Value *V2, uint64_t V2Size,
890                                const MDNode *V2TBAAInfo) {
891  // If this select has been visited before, we're on a use-def cycle.
892  // Such cycles are only valid when PHI nodes are involved or in unreachable
893  // code. The visitPHI function catches cycles containing PHIs, but there
894  // could still be a cycle without PHIs in unreachable code.
895  if (!Visited.insert(SI))
896    return MayAlias;
897
898  // If the values are Selects with the same condition, we can do a more precise
899  // check: just check for aliases between the values on corresponding arms.
900  if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2))
901    if (SI->getCondition() == SI2->getCondition()) {
902      AliasResult Alias =
903        aliasCheck(SI->getTrueValue(), SISize, SITBAAInfo,
904                   SI2->getTrueValue(), V2Size, V2TBAAInfo);
905      if (Alias == MayAlias)
906        return MayAlias;
907      AliasResult ThisAlias =
908        aliasCheck(SI->getFalseValue(), SISize, SITBAAInfo,
909                   SI2->getFalseValue(), V2Size, V2TBAAInfo);
910      if (ThisAlias != Alias)
911        return MayAlias;
912      return Alias;
913    }
914
915  // If both arms of the Select node NoAlias or MustAlias V2, then returns
916  // NoAlias / MustAlias. Otherwise, returns MayAlias.
917  AliasResult Alias =
918    aliasCheck(V2, V2Size, V2TBAAInfo, SI->getTrueValue(), SISize, SITBAAInfo);
919  if (Alias == MayAlias)
920    return MayAlias;
921
922  // If V2 is visited, the recursive case will have been caught in the
923  // above aliasCheck call, so these subsequent calls to aliasCheck
924  // don't need to assume that V2 is being visited recursively.
925  Visited.erase(V2);
926
927  AliasResult ThisAlias =
928    aliasCheck(V2, V2Size, V2TBAAInfo, SI->getFalseValue(), SISize, SITBAAInfo);
929  if (ThisAlias != Alias)
930    return MayAlias;
931  return Alias;
932}
933
934// aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI instruction
935// against another.
936AliasAnalysis::AliasResult
937BasicAliasAnalysis::aliasPHI(const PHINode *PN, uint64_t PNSize,
938                             const MDNode *PNTBAAInfo,
939                             const Value *V2, uint64_t V2Size,
940                             const MDNode *V2TBAAInfo) {
941  // The PHI node has already been visited, avoid recursion any further.
942  if (!Visited.insert(PN))
943    return MayAlias;
944
945  // If the values are PHIs in the same block, we can do a more precise
946  // as well as efficient check: just check for aliases between the values
947  // on corresponding edges.
948  if (const PHINode *PN2 = dyn_cast<PHINode>(V2))
949    if (PN2->getParent() == PN->getParent()) {
950      AliasResult Alias =
951        aliasCheck(PN->getIncomingValue(0), PNSize, PNTBAAInfo,
952                   PN2->getIncomingValueForBlock(PN->getIncomingBlock(0)),
953                   V2Size, V2TBAAInfo);
954      if (Alias == MayAlias)
955        return MayAlias;
956      for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
957        AliasResult ThisAlias =
958          aliasCheck(PN->getIncomingValue(i), PNSize, PNTBAAInfo,
959                     PN2->getIncomingValueForBlock(PN->getIncomingBlock(i)),
960                     V2Size, V2TBAAInfo);
961        if (ThisAlias != Alias)
962          return MayAlias;
963      }
964      return Alias;
965    }
966
967  SmallPtrSet<Value*, 4> UniqueSrc;
968  SmallVector<Value*, 4> V1Srcs;
969  for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
970    Value *PV1 = PN->getIncomingValue(i);
971    if (isa<PHINode>(PV1))
972      // If any of the source itself is a PHI, return MayAlias conservatively
973      // to avoid compile time explosion. The worst possible case is if both
974      // sides are PHI nodes. In which case, this is O(m x n) time where 'm'
975      // and 'n' are the number of PHI sources.
976      return MayAlias;
977    if (UniqueSrc.insert(PV1))
978      V1Srcs.push_back(PV1);
979  }
980
981  AliasResult Alias = aliasCheck(V2, V2Size, V2TBAAInfo,
982                                 V1Srcs[0], PNSize, PNTBAAInfo);
983  // Early exit if the check of the first PHI source against V2 is MayAlias.
984  // Other results are not possible.
985  if (Alias == MayAlias)
986    return MayAlias;
987
988  // If all sources of the PHI node NoAlias or MustAlias V2, then returns
989  // NoAlias / MustAlias. Otherwise, returns MayAlias.
990  for (unsigned i = 1, e = V1Srcs.size(); i != e; ++i) {
991    Value *V = V1Srcs[i];
992
993    // If V2 is visited, the recursive case will have been caught in the
994    // above aliasCheck call, so these subsequent calls to aliasCheck
995    // don't need to assume that V2 is being visited recursively.
996    Visited.erase(V2);
997
998    AliasResult ThisAlias = aliasCheck(V2, V2Size, V2TBAAInfo,
999                                       V, PNSize, PNTBAAInfo);
1000    if (ThisAlias != Alias || ThisAlias == MayAlias)
1001      return MayAlias;
1002  }
1003
1004  return Alias;
1005}
1006
1007// aliasCheck - Provide a bunch of ad-hoc rules to disambiguate in common cases,
1008// such as array references.
1009//
1010AliasAnalysis::AliasResult
1011BasicAliasAnalysis::aliasCheck(const Value *V1, uint64_t V1Size,
1012                               const MDNode *V1TBAAInfo,
1013                               const Value *V2, uint64_t V2Size,
1014                               const MDNode *V2TBAAInfo) {
1015  // If either of the memory references is empty, it doesn't matter what the
1016  // pointer values are.
1017  if (V1Size == 0 || V2Size == 0)
1018    return NoAlias;
1019
1020  // Strip off any casts if they exist.
1021  V1 = V1->stripPointerCasts();
1022  V2 = V2->stripPointerCasts();
1023
1024  // Are we checking for alias of the same value?
1025  if (V1 == V2) return MustAlias;
1026
1027  if (!V1->getType()->isPointerTy() || !V2->getType()->isPointerTy())
1028    return NoAlias;  // Scalars cannot alias each other
1029
1030  // Figure out what objects these things are pointing to if we can.
1031  const Value *O1 = V1->getUnderlyingObject();
1032  const Value *O2 = V2->getUnderlyingObject();
1033
1034  // Null values in the default address space don't point to any object, so they
1035  // don't alias any other pointer.
1036  if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O1))
1037    if (CPN->getType()->getAddressSpace() == 0)
1038      return NoAlias;
1039  if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O2))
1040    if (CPN->getType()->getAddressSpace() == 0)
1041      return NoAlias;
1042
1043  if (O1 != O2) {
1044    // If V1/V2 point to two different objects we know that we have no alias.
1045    if (isIdentifiedObject(O1) && isIdentifiedObject(O2))
1046      return NoAlias;
1047
1048    // Constant pointers can't alias with non-const isIdentifiedObject objects.
1049    if ((isa<Constant>(O1) && isIdentifiedObject(O2) && !isa<Constant>(O2)) ||
1050        (isa<Constant>(O2) && isIdentifiedObject(O1) && !isa<Constant>(O1)))
1051      return NoAlias;
1052
1053    // Arguments can't alias with local allocations or noalias calls
1054    // in the same function.
1055    if (((isa<Argument>(O1) && (isa<AllocaInst>(O2) || isNoAliasCall(O2))) ||
1056         (isa<Argument>(O2) && (isa<AllocaInst>(O1) || isNoAliasCall(O1)))))
1057      return NoAlias;
1058
1059    // Most objects can't alias null.
1060    if ((isa<ConstantPointerNull>(O2) && isKnownNonNull(O1)) ||
1061        (isa<ConstantPointerNull>(O1) && isKnownNonNull(O2)))
1062      return NoAlias;
1063
1064    // If one pointer is the result of a call/invoke or load and the other is a
1065    // non-escaping local object within the same function, then we know the
1066    // object couldn't escape to a point where the call could return it.
1067    //
1068    // Note that if the pointers are in different functions, there are a
1069    // variety of complications. A call with a nocapture argument may still
1070    // temporary store the nocapture argument's value in a temporary memory
1071    // location if that memory location doesn't escape. Or it may pass a
1072    // nocapture value to other functions as long as they don't capture it.
1073    if (isEscapeSource(O1) && isNonEscapingLocalObject(O2))
1074      return NoAlias;
1075    if (isEscapeSource(O2) && isNonEscapingLocalObject(O1))
1076      return NoAlias;
1077  }
1078
1079  // If the size of one access is larger than the entire object on the other
1080  // side, then we know such behavior is undefined and can assume no alias.
1081  if (TD)
1082    if ((V1Size != UnknownSize && isObjectSmallerThan(O2, V1Size, *TD)) ||
1083        (V2Size != UnknownSize && isObjectSmallerThan(O1, V2Size, *TD)))
1084      return NoAlias;
1085
1086  // FIXME: This isn't aggressively handling alias(GEP, PHI) for example: if the
1087  // GEP can't simplify, we don't even look at the PHI cases.
1088  if (!isa<GEPOperator>(V1) && isa<GEPOperator>(V2)) {
1089    std::swap(V1, V2);
1090    std::swap(V1Size, V2Size);
1091    std::swap(O1, O2);
1092  }
1093  if (const GEPOperator *GV1 = dyn_cast<GEPOperator>(V1)) {
1094    AliasResult Result = aliasGEP(GV1, V1Size, V2, V2Size, V2TBAAInfo, O1, O2);
1095    if (Result != MayAlias) return Result;
1096  }
1097
1098  if (isa<PHINode>(V2) && !isa<PHINode>(V1)) {
1099    std::swap(V1, V2);
1100    std::swap(V1Size, V2Size);
1101  }
1102  if (const PHINode *PN = dyn_cast<PHINode>(V1)) {
1103    AliasResult Result = aliasPHI(PN, V1Size, V1TBAAInfo,
1104                                  V2, V2Size, V2TBAAInfo);
1105    if (Result != MayAlias) return Result;
1106  }
1107
1108  if (isa<SelectInst>(V2) && !isa<SelectInst>(V1)) {
1109    std::swap(V1, V2);
1110    std::swap(V1Size, V2Size);
1111  }
1112  if (const SelectInst *S1 = dyn_cast<SelectInst>(V1)) {
1113    AliasResult Result = aliasSelect(S1, V1Size, V1TBAAInfo,
1114                                     V2, V2Size, V2TBAAInfo);
1115    if (Result != MayAlias) return Result;
1116  }
1117
1118  return AliasAnalysis::alias(Location(V1, V1Size, V1TBAAInfo),
1119                              Location(V2, V2Size, V2TBAAInfo));
1120}
1121