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