Reapply r110396, with fixes to appease the Linux buildbot gods.
[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/GlobalVariable.h"
22 #include "llvm/Instructions.h"
23 #include "llvm/IntrinsicInst.h"
24 #include "llvm/Operator.h"
25 #include "llvm/Pass.h"
26 #include "llvm/Analysis/CaptureTracking.h"
27 #include "llvm/Analysis/MemoryBuiltins.h"
28 #include "llvm/Analysis/ValueTracking.h"
29 #include "llvm/Target/TargetData.h"
30 #include "llvm/ADT/SmallPtrSet.h"
31 #include "llvm/ADT/SmallVector.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include <algorithm>
34 using namespace llvm;
35
36 //===----------------------------------------------------------------------===//
37 // Useful predicates
38 //===----------------------------------------------------------------------===//
39
40 /// isKnownNonNull - Return true if we know that the specified value is never
41 /// null.
42 static bool isKnownNonNull(const Value *V) {
43   // Alloca never returns null, malloc might.
44   if (isa<AllocaInst>(V)) return true;
45   
46   // A byval argument is never null.
47   if (const Argument *A = dyn_cast<Argument>(V))
48     return A->hasByValAttr();
49
50   // Global values are not null unless extern weak.
51   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
52     return !GV->hasExternalWeakLinkage();
53   return false;
54 }
55
56 /// isNonEscapingLocalObject - Return true if the pointer is to a function-local
57 /// object that never escapes from the function.
58 static bool isNonEscapingLocalObject(const Value *V) {
59   // If this is a local allocation, check to see if it escapes.
60   if (isa<AllocaInst>(V) || isNoAliasCall(V))
61     // Set StoreCaptures to True so that we can assume in our callers that the
62     // pointer is not the result of a load instruction. Currently
63     // PointerMayBeCaptured doesn't have any special analysis for the
64     // StoreCaptures=false case; if it did, our callers could be refined to be
65     // more precise.
66     return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
67
68   // If this is an argument that corresponds to a byval or noalias argument,
69   // then it has not escaped before entering the function.  Check if it escapes
70   // inside the function.
71   if (const Argument *A = dyn_cast<Argument>(V))
72     if (A->hasByValAttr() || A->hasNoAliasAttr()) {
73       // Don't bother analyzing arguments already known not to escape.
74       if (A->hasNoCaptureAttr())
75         return true;
76       return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
77     }
78   return false;
79 }
80
81 /// isEscapeSource - Return true if the pointer is one which would have
82 /// been considered an escape by isNonEscapingLocalObject.
83 static bool isEscapeSource(const Value *V) {
84   if (isa<CallInst>(V) || isa<InvokeInst>(V) || isa<Argument>(V))
85     return true;
86
87   // The load case works because isNonEscapingLocalObject considers all
88   // stores to be escapes (it passes true for the StoreCaptures argument
89   // to PointerMayBeCaptured).
90   if (isa<LoadInst>(V))
91     return true;
92
93   return false;
94 }
95
96 /// isObjectSmallerThan - Return true if we can prove that the object specified
97 /// by V is smaller than Size.
98 static bool isObjectSmallerThan(const Value *V, unsigned Size,
99                                 const TargetData &TD) {
100   const Type *AccessTy;
101   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
102     AccessTy = GV->getType()->getElementType();
103   } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
104     if (!AI->isArrayAllocation())
105       AccessTy = AI->getType()->getElementType();
106     else
107       return false;
108   } else if (const CallInst* CI = extractMallocCall(V)) {
109     if (!isArrayMalloc(V, &TD))
110       // The size is the argument to the malloc call.
111       if (const ConstantInt* C = dyn_cast<ConstantInt>(CI->getArgOperand(0)))
112         return (C->getZExtValue() < Size);
113     return false;
114   } else if (const Argument *A = dyn_cast<Argument>(V)) {
115     if (A->hasByValAttr())
116       AccessTy = cast<PointerType>(A->getType())->getElementType();
117     else
118       return false;
119   } else {
120     return false;
121   }
122   
123   if (AccessTy->isSized())
124     return TD.getTypeAllocSize(AccessTy) < Size;
125   return false;
126 }
127
128 //===----------------------------------------------------------------------===//
129 // NoAA Pass
130 //===----------------------------------------------------------------------===//
131
132 namespace {
133   /// NoAA - This class implements the -no-aa pass, which always returns "I
134   /// don't know" for alias queries.  NoAA is unlike other alias analysis
135   /// implementations, in that it does not chain to a previous analysis.  As
136   /// such it doesn't follow many of the rules that other alias analyses must.
137   ///
138   struct NoAA : public ImmutablePass, public AliasAnalysis {
139     static char ID; // Class identification, replacement for typeinfo
140     NoAA() : ImmutablePass(ID) {}
141     explicit NoAA(char &PID) : ImmutablePass(PID) { }
142
143     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
144     }
145
146     virtual void initializePass() {
147       TD = getAnalysisIfAvailable<TargetData>();
148     }
149
150     virtual AliasResult alias(const Value *V1, unsigned V1Size,
151                               const Value *V2, unsigned V2Size) {
152       return MayAlias;
153     }
154
155     virtual ModRefBehavior getModRefBehavior(ImmutableCallSite CS) {
156       return UnknownModRefBehavior;
157     }
158     virtual ModRefBehavior getModRefBehavior(const Function *F) {
159       return UnknownModRefBehavior;
160     }
161
162     virtual bool pointsToConstantMemory(const Value *P) { return false; }
163     virtual ModRefResult getModRefInfo(ImmutableCallSite CS,
164                                        const Value *P, unsigned Size) {
165       return ModRef;
166     }
167     virtual ModRefResult getModRefInfo(ImmutableCallSite CS1,
168                                        ImmutableCallSite CS2) {
169       return ModRef;
170     }
171
172     virtual void deleteValue(Value *V) {}
173     virtual void copyValue(Value *From, Value *To) {}
174     
175     /// getAdjustedAnalysisPointer - This method is used when a pass implements
176     /// an analysis interface through multiple inheritance.  If needed, it
177     /// should override this to adjust the this pointer as needed for the
178     /// specified pass info.
179     virtual void *getAdjustedAnalysisPointer(const void *ID) {
180       if (ID == &AliasAnalysis::ID)
181         return (AliasAnalysis*)this;
182       return this;
183     }
184   };
185 }  // End of anonymous namespace
186
187 // Register this pass...
188 char NoAA::ID = 0;
189 INITIALIZE_AG_PASS(NoAA, AliasAnalysis, "no-aa",
190                    "No Alias Analysis (always returns 'may' alias)",
191                    true, true, false);
192
193 ImmutablePass *llvm::createNoAAPass() { return new NoAA(); }
194
195 //===----------------------------------------------------------------------===//
196 // BasicAliasAnalysis Pass
197 //===----------------------------------------------------------------------===//
198
199 #ifndef NDEBUG
200 static const Function *getParent(const Value *V) {
201   if (const Instruction *inst = dyn_cast<Instruction>(V))
202     return inst->getParent()->getParent();
203
204   if (const Argument *arg = dyn_cast<Argument>(V))
205     return arg->getParent();
206
207   return NULL;
208 }
209
210 static bool notDifferentParent(const Value *O1, const Value *O2) {
211
212   const Function *F1 = getParent(O1);
213   const Function *F2 = getParent(O2);
214
215   return !F1 || !F2 || F1 == F2;
216 }
217 #endif
218
219 namespace {
220   /// BasicAliasAnalysis - This is the default alias analysis implementation.
221   /// Because it doesn't chain to a previous alias analysis (like -no-aa), it
222   /// derives from the NoAA class.
223   struct BasicAliasAnalysis : public NoAA {
224     static char ID; // Class identification, replacement for typeinfo
225     BasicAliasAnalysis() : NoAA(ID) {}
226
227     virtual AliasResult alias(const Value *V1, unsigned V1Size,
228                               const Value *V2, unsigned V2Size) {
229       assert(Visited.empty() && "Visited must be cleared after use!");
230       assert(notDifferentParent(V1, V2) &&
231              "BasicAliasAnalysis doesn't support interprocedural queries.");
232       AliasResult Alias = aliasCheck(V1, V1Size, V2, V2Size);
233       Visited.clear();
234       return Alias;
235     }
236
237     virtual ModRefResult getModRefInfo(ImmutableCallSite CS,
238                                        const Value *P, unsigned Size);
239
240     virtual ModRefResult getModRefInfo(ImmutableCallSite CS1,
241                                        ImmutableCallSite CS2) {
242       // The AliasAnalysis base class has some smarts, lets use them.
243       return AliasAnalysis::getModRefInfo(CS1, CS2);
244     }
245
246     /// pointsToConstantMemory - Chase pointers until we find a (constant
247     /// global) or not.
248     virtual bool pointsToConstantMemory(const Value *P);
249
250     /// getModRefBehavior - Return the behavior when calling the given
251     /// call site.
252     virtual ModRefBehavior getModRefBehavior(ImmutableCallSite CS);
253
254     /// getModRefBehavior - Return the behavior when calling the given function.
255     /// For use when the call site is not known.
256     virtual ModRefBehavior getModRefBehavior(const Function *F);
257
258     /// getAdjustedAnalysisPointer - This method is used when a pass implements
259     /// an analysis interface through multiple inheritance.  If needed, it
260     /// should override this to adjust the this pointer as needed for the
261     /// specified pass info.
262     virtual void *getAdjustedAnalysisPointer(const void *ID) {
263       if (ID == &AliasAnalysis::ID)
264         return (AliasAnalysis*)this;
265       return this;
266     }
267     
268   private:
269     // Visited - Track instructions visited by a aliasPHI, aliasSelect(), and aliasGEP().
270     SmallPtrSet<const Value*, 16> Visited;
271
272     // aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP
273     // instruction against another.
274     AliasResult aliasGEP(const GEPOperator *V1, unsigned V1Size,
275                          const Value *V2, unsigned V2Size,
276                          const Value *UnderlyingV1, const Value *UnderlyingV2);
277
278     // aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI
279     // instruction against another.
280     AliasResult aliasPHI(const PHINode *PN, unsigned PNSize,
281                          const Value *V2, unsigned V2Size);
282
283     /// aliasSelect - Disambiguate a Select instruction against another value.
284     AliasResult aliasSelect(const SelectInst *SI, unsigned SISize,
285                             const Value *V2, unsigned V2Size);
286
287     AliasResult aliasCheck(const Value *V1, unsigned V1Size,
288                            const Value *V2, unsigned V2Size);
289   };
290 }  // End of anonymous namespace
291
292 // Register this pass...
293 char BasicAliasAnalysis::ID = 0;
294 INITIALIZE_AG_PASS(BasicAliasAnalysis, AliasAnalysis, "basicaa",
295                    "Basic Alias Analysis (default AA impl)",
296                    false, true, true);
297
298 ImmutablePass *llvm::createBasicAliasAnalysisPass() {
299   return new BasicAliasAnalysis();
300 }
301
302
303 /// pointsToConstantMemory - Chase pointers until we find a (constant
304 /// global) or not.
305 bool BasicAliasAnalysis::pointsToConstantMemory(const Value *P) {
306   if (const GlobalVariable *GV = 
307         dyn_cast<GlobalVariable>(P->getUnderlyingObject()))
308     // Note: this doesn't require GV to be "ODR" because it isn't legal for a
309     // global to be marked constant in some modules and non-constant in others.
310     // GV may even be a declaration, not a definition.
311     return GV->isConstant();
312
313   return NoAA::pointsToConstantMemory(P);
314 }
315
316 /// getModRefBehavior - Return the behavior when calling the given call site.
317 AliasAnalysis::ModRefBehavior
318 BasicAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
319   if (CS.doesNotAccessMemory())
320     // Can't do better than this.
321     return DoesNotAccessMemory;
322
323   ModRefBehavior Min = UnknownModRefBehavior;
324
325   // If the callsite knows it only reads memory, don't return worse
326   // than that.
327   if (CS.onlyReadsMemory())
328     Min = OnlyReadsMemory;
329
330   // The AliasAnalysis base class has some smarts, lets use them.
331   return std::min(AliasAnalysis::getModRefBehavior(CS), Min);
332 }
333
334 /// getModRefBehavior - Return the behavior when calling the given function.
335 /// For use when the call site is not known.
336 AliasAnalysis::ModRefBehavior
337 BasicAliasAnalysis::getModRefBehavior(const Function *F) {
338   if (F->doesNotAccessMemory())
339     // Can't do better than this.
340     return DoesNotAccessMemory;
341   if (F->onlyReadsMemory())
342     return OnlyReadsMemory;
343   if (unsigned id = F->getIntrinsicID())
344     return getIntrinsicModRefBehavior(id);
345
346   return NoAA::getModRefBehavior(F);
347 }
348
349 /// getModRefInfo - Check to see if the specified callsite can clobber the
350 /// specified memory object.  Since we only look at local properties of this
351 /// function, we really can't say much about this query.  We do, however, use
352 /// simple "address taken" analysis on local objects.
353 AliasAnalysis::ModRefResult
354 BasicAliasAnalysis::getModRefInfo(ImmutableCallSite CS,
355                                   const Value *P, unsigned Size) {
356   assert(notDifferentParent(CS.getInstruction(), P) &&
357          "AliasAnalysis query involving multiple functions!");
358
359   const Value *Object = P->getUnderlyingObject();
360   
361   // If this is a tail call and P points to a stack location, we know that
362   // the tail call cannot access or modify the local stack.
363   // We cannot exclude byval arguments here; these belong to the caller of
364   // the current function not to the current function, and a tail callee
365   // may reference them.
366   if (isa<AllocaInst>(Object))
367     if (const CallInst *CI = dyn_cast<CallInst>(CS.getInstruction()))
368       if (CI->isTailCall())
369         return NoModRef;
370   
371   // If the pointer is to a locally allocated object that does not escape,
372   // then the call can not mod/ref the pointer unless the call takes the pointer
373   // as an argument, and itself doesn't capture it.
374   if (!isa<Constant>(Object) && CS.getInstruction() != Object &&
375       isNonEscapingLocalObject(Object)) {
376     bool PassedAsArg = false;
377     unsigned ArgNo = 0;
378     for (ImmutableCallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
379          CI != CE; ++CI, ++ArgNo) {
380       // Only look at the no-capture pointer arguments.
381       if (!(*CI)->getType()->isPointerTy() ||
382           !CS.paramHasAttr(ArgNo+1, Attribute::NoCapture))
383         continue;
384       
385       // If  this is a no-capture pointer argument, see if we can tell that it
386       // is impossible to alias the pointer we're checking.  If not, we have to
387       // assume that the call could touch the pointer, even though it doesn't
388       // escape.
389       if (!isNoAlias(cast<Value>(CI), UnknownSize, P, UnknownSize)) {
390         PassedAsArg = true;
391         break;
392       }
393     }
394     
395     if (!PassedAsArg)
396       return NoModRef;
397   }
398
399   // Finally, handle specific knowledge of intrinsics.
400   const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction());
401   if (II != 0)
402     switch (II->getIntrinsicID()) {
403     default: break;
404     case Intrinsic::memcpy:
405     case Intrinsic::memmove: {
406       unsigned Len = UnknownSize;
407       if (ConstantInt *LenCI = dyn_cast<ConstantInt>(II->getArgOperand(2)))
408         Len = LenCI->getZExtValue();
409       Value *Dest = II->getArgOperand(0);
410       Value *Src = II->getArgOperand(1);
411       if (isNoAlias(Dest, Len, P, Size)) {
412         if (isNoAlias(Src, Len, P, Size))
413           return NoModRef;
414         return Ref;
415       }
416       break;
417     }
418     case Intrinsic::memset:
419       // Since memset is 'accesses arguments' only, the AliasAnalysis base class
420       // will handle it for the variable length case.
421       if (ConstantInt *LenCI = dyn_cast<ConstantInt>(II->getArgOperand(2))) {
422         unsigned Len = LenCI->getZExtValue();
423         Value *Dest = II->getArgOperand(0);
424         if (isNoAlias(Dest, Len, P, Size))
425           return NoModRef;
426       }
427       break;
428     case Intrinsic::atomic_cmp_swap:
429     case Intrinsic::atomic_swap:
430     case Intrinsic::atomic_load_add:
431     case Intrinsic::atomic_load_sub:
432     case Intrinsic::atomic_load_and:
433     case Intrinsic::atomic_load_nand:
434     case Intrinsic::atomic_load_or:
435     case Intrinsic::atomic_load_xor:
436     case Intrinsic::atomic_load_max:
437     case Intrinsic::atomic_load_min:
438     case Intrinsic::atomic_load_umax:
439     case Intrinsic::atomic_load_umin:
440       if (TD) {
441         Value *Op1 = II->getArgOperand(0);
442         unsigned Op1Size = TD->getTypeStoreSize(Op1->getType());
443         if (isNoAlias(Op1, Op1Size, P, Size))
444           return NoModRef;
445       }
446       break;
447     case Intrinsic::lifetime_start:
448     case Intrinsic::lifetime_end:
449     case Intrinsic::invariant_start: {
450       unsigned PtrSize =
451         cast<ConstantInt>(II->getArgOperand(0))->getZExtValue();
452       if (isNoAlias(II->getArgOperand(1), PtrSize, P, Size))
453         return NoModRef;
454       break;
455     }
456     case Intrinsic::invariant_end: {
457       unsigned PtrSize =
458         cast<ConstantInt>(II->getArgOperand(1))->getZExtValue();
459       if (isNoAlias(II->getArgOperand(2), PtrSize, P, Size))
460         return NoModRef;
461       break;
462     }
463     }
464
465   // The AliasAnalysis base class has some smarts, lets use them.
466   return AliasAnalysis::getModRefInfo(CS, P, Size);
467 }
468
469
470 /// GetIndexDifference - Dest and Src are the variable indices from two
471 /// decomposed GetElementPtr instructions GEP1 and GEP2 which have common base
472 /// pointers.  Subtract the GEP2 indices from GEP1 to find the symbolic
473 /// difference between the two pointers. 
474 static void GetIndexDifference(
475                       SmallVectorImpl<std::pair<const Value*, int64_t> > &Dest,
476                 const SmallVectorImpl<std::pair<const Value*, int64_t> > &Src) {
477   if (Src.empty()) return;
478
479   for (unsigned i = 0, e = Src.size(); i != e; ++i) {
480     const Value *V = Src[i].first;
481     int64_t Scale = Src[i].second;
482     
483     // Find V in Dest.  This is N^2, but pointer indices almost never have more
484     // than a few variable indexes.
485     for (unsigned j = 0, e = Dest.size(); j != e; ++j) {
486       if (Dest[j].first != V) continue;
487       
488       // If we found it, subtract off Scale V's from the entry in Dest.  If it
489       // goes to zero, remove the entry.
490       if (Dest[j].second != Scale)
491         Dest[j].second -= Scale;
492       else
493         Dest.erase(Dest.begin()+j);
494       Scale = 0;
495       break;
496     }
497     
498     // If we didn't consume this entry, add it to the end of the Dest list.
499     if (Scale)
500       Dest.push_back(std::make_pair(V, -Scale));
501   }
502 }
503
504 /// aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP instruction
505 /// against another pointer.  We know that V1 is a GEP, but we don't know
506 /// anything about V2.  UnderlyingV1 is GEP1->getUnderlyingObject(),
507 /// UnderlyingV2 is the same for V2.
508 ///
509 AliasAnalysis::AliasResult
510 BasicAliasAnalysis::aliasGEP(const GEPOperator *GEP1, unsigned V1Size,
511                              const Value *V2, unsigned V2Size,
512                              const Value *UnderlyingV1,
513                              const Value *UnderlyingV2) {
514   // If this GEP has been visited before, we're on a use-def cycle.
515   // Such cycles are only valid when PHI nodes are involved or in unreachable
516   // code. The visitPHI function catches cycles containing PHIs, but there
517   // could still be a cycle without PHIs in unreachable code.
518   if (!Visited.insert(GEP1))
519     return MayAlias;
520
521   int64_t GEP1BaseOffset;
522   SmallVector<std::pair<const Value*, int64_t>, 4> GEP1VariableIndices;
523
524   // If we have two gep instructions with must-alias'ing base pointers, figure
525   // out if the indexes to the GEP tell us anything about the derived pointer.
526   if (const GEPOperator *GEP2 = dyn_cast<GEPOperator>(V2)) {
527     // Do the base pointers alias?
528     AliasResult BaseAlias = aliasCheck(UnderlyingV1, UnknownSize,
529                                        UnderlyingV2, UnknownSize);
530     
531     // If we get a No or May, then return it immediately, no amount of analysis
532     // will improve this situation.
533     if (BaseAlias != MustAlias) return BaseAlias;
534     
535     // Otherwise, we have a MustAlias.  Since the base pointers alias each other
536     // exactly, see if the computed offset from the common pointer tells us
537     // about the relation of the resulting pointer.
538     const Value *GEP1BasePtr =
539       DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices, TD);
540     
541     int64_t GEP2BaseOffset;
542     SmallVector<std::pair<const Value*, int64_t>, 4> GEP2VariableIndices;
543     const Value *GEP2BasePtr =
544       DecomposeGEPExpression(GEP2, GEP2BaseOffset, GEP2VariableIndices, TD);
545     
546     // If DecomposeGEPExpression isn't able to look all the way through the
547     // addressing operation, we must not have TD and this is too complex for us
548     // to handle without it.
549     if (GEP1BasePtr != UnderlyingV1 || GEP2BasePtr != UnderlyingV2) {
550       assert(TD == 0 &&
551              "DecomposeGEPExpression and getUnderlyingObject disagree!");
552       return MayAlias;
553     }
554     
555     // Subtract the GEP2 pointer from the GEP1 pointer to find out their
556     // symbolic difference.
557     GEP1BaseOffset -= GEP2BaseOffset;
558     GetIndexDifference(GEP1VariableIndices, GEP2VariableIndices);
559     
560   } else {
561     // Check to see if these two pointers are related by the getelementptr
562     // instruction.  If one pointer is a GEP with a non-zero index of the other
563     // pointer, we know they cannot alias.
564
565     // If both accesses are unknown size, we can't do anything useful here.
566     if (V1Size == UnknownSize && V2Size == UnknownSize)
567       return MayAlias;
568
569     AliasResult R = aliasCheck(UnderlyingV1, UnknownSize, V2, V2Size);
570     if (R != MustAlias)
571       // If V2 may alias GEP base pointer, conservatively returns MayAlias.
572       // If V2 is known not to alias GEP base pointer, then the two values
573       // cannot alias per GEP semantics: "A pointer value formed from a
574       // getelementptr instruction is associated with the addresses associated
575       // with the first operand of the getelementptr".
576       return R;
577
578     const Value *GEP1BasePtr =
579       DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices, TD);
580     
581     // If DecomposeGEPExpression isn't able to look all the way through the
582     // addressing operation, we must not have TD and this is too complex for us
583     // to handle without it.
584     if (GEP1BasePtr != UnderlyingV1) {
585       assert(TD == 0 &&
586              "DecomposeGEPExpression and getUnderlyingObject disagree!");
587       return MayAlias;
588     }
589   }
590   
591   // In the two GEP Case, if there is no difference in the offsets of the
592   // computed pointers, the resultant pointers are a must alias.  This
593   // hapens when we have two lexically identical GEP's (for example).
594   //
595   // In the other case, if we have getelementptr <ptr>, 0, 0, 0, 0, ... and V2
596   // must aliases the GEP, the end result is a must alias also.
597   if (GEP1BaseOffset == 0 && GEP1VariableIndices.empty())
598     return MustAlias;
599
600   // If we have a known constant offset, see if this offset is larger than the
601   // access size being queried.  If so, and if no variable indices can remove
602   // pieces of this constant, then we know we have a no-alias.  For example,
603   //   &A[100] != &A.
604   
605   // In order to handle cases like &A[100][i] where i is an out of range
606   // subscript, we have to ignore all constant offset pieces that are a multiple
607   // of a scaled index.  Do this by removing constant offsets that are a
608   // multiple of any of our variable indices.  This allows us to transform
609   // things like &A[i][1] because i has a stride of (e.g.) 8 bytes but the 1
610   // provides an offset of 4 bytes (assuming a <= 4 byte access).
611   for (unsigned i = 0, e = GEP1VariableIndices.size();
612        i != e && GEP1BaseOffset;++i)
613     if (int64_t RemovedOffset = GEP1BaseOffset/GEP1VariableIndices[i].second)
614       GEP1BaseOffset -= RemovedOffset*GEP1VariableIndices[i].second;
615   
616   // If our known offset is bigger than the access size, we know we don't have
617   // an alias.
618   if (GEP1BaseOffset) {
619     if (GEP1BaseOffset >= (int64_t)V2Size ||
620         GEP1BaseOffset <= -(int64_t)V1Size)
621       return NoAlias;
622   }
623   
624   return MayAlias;
625 }
626
627 /// aliasSelect - Provide a bunch of ad-hoc rules to disambiguate a Select
628 /// instruction against another.
629 AliasAnalysis::AliasResult
630 BasicAliasAnalysis::aliasSelect(const SelectInst *SI, unsigned SISize,
631                                 const Value *V2, unsigned V2Size) {
632   // If this select has been visited before, we're on a use-def cycle.
633   // Such cycles are only valid when PHI nodes are involved or in unreachable
634   // code. The visitPHI function catches cycles containing PHIs, but there
635   // could still be a cycle without PHIs in unreachable code.
636   if (!Visited.insert(SI))
637     return MayAlias;
638
639   // If the values are Selects with the same condition, we can do a more precise
640   // check: just check for aliases between the values on corresponding arms.
641   if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2))
642     if (SI->getCondition() == SI2->getCondition()) {
643       AliasResult Alias =
644         aliasCheck(SI->getTrueValue(), SISize,
645                    SI2->getTrueValue(), V2Size);
646       if (Alias == MayAlias)
647         return MayAlias;
648       AliasResult ThisAlias =
649         aliasCheck(SI->getFalseValue(), SISize,
650                    SI2->getFalseValue(), V2Size);
651       if (ThisAlias != Alias)
652         return MayAlias;
653       return Alias;
654     }
655
656   // If both arms of the Select node NoAlias or MustAlias V2, then returns
657   // NoAlias / MustAlias. Otherwise, returns MayAlias.
658   AliasResult Alias =
659     aliasCheck(V2, V2Size, SI->getTrueValue(), SISize);
660   if (Alias == MayAlias)
661     return MayAlias;
662
663   // If V2 is visited, the recursive case will have been caught in the
664   // above aliasCheck call, so these subsequent calls to aliasCheck
665   // don't need to assume that V2 is being visited recursively.
666   Visited.erase(V2);
667
668   AliasResult ThisAlias =
669     aliasCheck(V2, V2Size, SI->getFalseValue(), SISize);
670   if (ThisAlias != Alias)
671     return MayAlias;
672   return Alias;
673 }
674
675 // aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI instruction
676 // against another.
677 AliasAnalysis::AliasResult
678 BasicAliasAnalysis::aliasPHI(const PHINode *PN, unsigned PNSize,
679                              const Value *V2, unsigned V2Size) {
680   // The PHI node has already been visited, avoid recursion any further.
681   if (!Visited.insert(PN))
682     return MayAlias;
683
684   // If the values are PHIs in the same block, we can do a more precise
685   // as well as efficient check: just check for aliases between the values
686   // on corresponding edges.
687   if (const PHINode *PN2 = dyn_cast<PHINode>(V2))
688     if (PN2->getParent() == PN->getParent()) {
689       AliasResult Alias =
690         aliasCheck(PN->getIncomingValue(0), PNSize,
691                    PN2->getIncomingValueForBlock(PN->getIncomingBlock(0)),
692                    V2Size);
693       if (Alias == MayAlias)
694         return MayAlias;
695       for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
696         AliasResult ThisAlias =
697           aliasCheck(PN->getIncomingValue(i), PNSize,
698                      PN2->getIncomingValueForBlock(PN->getIncomingBlock(i)),
699                      V2Size);
700         if (ThisAlias != Alias)
701           return MayAlias;
702       }
703       return Alias;
704     }
705
706   SmallPtrSet<Value*, 4> UniqueSrc;
707   SmallVector<Value*, 4> V1Srcs;
708   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
709     Value *PV1 = PN->getIncomingValue(i);
710     if (isa<PHINode>(PV1))
711       // If any of the source itself is a PHI, return MayAlias conservatively
712       // to avoid compile time explosion. The worst possible case is if both
713       // sides are PHI nodes. In which case, this is O(m x n) time where 'm'
714       // and 'n' are the number of PHI sources.
715       return MayAlias;
716     if (UniqueSrc.insert(PV1))
717       V1Srcs.push_back(PV1);
718   }
719
720   AliasResult Alias = aliasCheck(V2, V2Size, V1Srcs[0], PNSize);
721   // Early exit if the check of the first PHI source against V2 is MayAlias.
722   // Other results are not possible.
723   if (Alias == MayAlias)
724     return MayAlias;
725
726   // If all sources of the PHI node NoAlias or MustAlias V2, then returns
727   // NoAlias / MustAlias. Otherwise, returns MayAlias.
728   for (unsigned i = 1, e = V1Srcs.size(); i != e; ++i) {
729     Value *V = V1Srcs[i];
730
731     // If V2 is visited, the recursive case will have been caught in the
732     // above aliasCheck call, so these subsequent calls to aliasCheck
733     // don't need to assume that V2 is being visited recursively.
734     Visited.erase(V2);
735
736     AliasResult ThisAlias = aliasCheck(V2, V2Size, V, PNSize);
737     if (ThisAlias != Alias || ThisAlias == MayAlias)
738       return MayAlias;
739   }
740
741   return Alias;
742 }
743
744 // aliasCheck - Provide a bunch of ad-hoc rules to disambiguate in common cases,
745 // such as array references.
746 //
747 AliasAnalysis::AliasResult
748 BasicAliasAnalysis::aliasCheck(const Value *V1, unsigned V1Size,
749                                const Value *V2, unsigned V2Size) {
750   // If either of the memory references is empty, it doesn't matter what the
751   // pointer values are.
752   if (V1Size == 0 || V2Size == 0)
753     return NoAlias;
754
755   // Strip off any casts if they exist.
756   V1 = V1->stripPointerCasts();
757   V2 = V2->stripPointerCasts();
758
759   // Are we checking for alias of the same value?
760   if (V1 == V2) return MustAlias;
761
762   if (!V1->getType()->isPointerTy() || !V2->getType()->isPointerTy())
763     return NoAlias;  // Scalars cannot alias each other
764
765   // Figure out what objects these things are pointing to if we can.
766   const Value *O1 = V1->getUnderlyingObject();
767   const Value *O2 = V2->getUnderlyingObject();
768
769   // Null values in the default address space don't point to any object, so they
770   // don't alias any other pointer.
771   if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O1))
772     if (CPN->getType()->getAddressSpace() == 0)
773       return NoAlias;
774   if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O2))
775     if (CPN->getType()->getAddressSpace() == 0)
776       return NoAlias;
777
778   if (O1 != O2) {
779     // If V1/V2 point to two different objects we know that we have no alias.
780     if (isIdentifiedObject(O1) && isIdentifiedObject(O2))
781       return NoAlias;
782
783     // Constant pointers can't alias with non-const isIdentifiedObject objects.
784     if ((isa<Constant>(O1) && isIdentifiedObject(O2) && !isa<Constant>(O2)) ||
785         (isa<Constant>(O2) && isIdentifiedObject(O1) && !isa<Constant>(O1)))
786       return NoAlias;
787
788     // Arguments can't alias with local allocations or noalias calls
789     // in the same function.
790     if (((isa<Argument>(O1) && (isa<AllocaInst>(O2) || isNoAliasCall(O2))) ||
791          (isa<Argument>(O2) && (isa<AllocaInst>(O1) || isNoAliasCall(O1)))))
792       return NoAlias;
793
794     // Most objects can't alias null.
795     if ((isa<ConstantPointerNull>(O2) && isKnownNonNull(O1)) ||
796         (isa<ConstantPointerNull>(O1) && isKnownNonNull(O2)))
797       return NoAlias;
798   
799     // If one pointer is the result of a call/invoke or load and the other is a
800     // non-escaping local object within the same function, then we know the
801     // object couldn't escape to a point where the call could return it.
802     //
803     // Note that if the pointers are in different functions, there are a
804     // variety of complications. A call with a nocapture argument may still
805     // temporary store the nocapture argument's value in a temporary memory
806     // location if that memory location doesn't escape. Or it may pass a
807     // nocapture value to other functions as long as they don't capture it.
808     if (isEscapeSource(O1) && isNonEscapingLocalObject(O2))
809       return NoAlias;
810     if (isEscapeSource(O2) && isNonEscapingLocalObject(O1))
811       return NoAlias;
812   }
813
814   // If the size of one access is larger than the entire object on the other
815   // side, then we know such behavior is undefined and can assume no alias.
816   if (TD)
817     if ((V1Size != UnknownSize && isObjectSmallerThan(O2, V1Size, *TD)) ||
818         (V2Size != UnknownSize && isObjectSmallerThan(O1, V2Size, *TD)))
819       return NoAlias;
820   
821   // FIXME: This isn't aggressively handling alias(GEP, PHI) for example: if the
822   // GEP can't simplify, we don't even look at the PHI cases.
823   if (!isa<GEPOperator>(V1) && isa<GEPOperator>(V2)) {
824     std::swap(V1, V2);
825     std::swap(V1Size, V2Size);
826     std::swap(O1, O2);
827   }
828   if (const GEPOperator *GV1 = dyn_cast<GEPOperator>(V1))
829     return aliasGEP(GV1, V1Size, V2, V2Size, O1, O2);
830
831   if (isa<PHINode>(V2) && !isa<PHINode>(V1)) {
832     std::swap(V1, V2);
833     std::swap(V1Size, V2Size);
834   }
835   if (const PHINode *PN = dyn_cast<PHINode>(V1))
836     return aliasPHI(PN, V1Size, V2, V2Size);
837
838   if (isa<SelectInst>(V2) && !isa<SelectInst>(V1)) {
839     std::swap(V1, V2);
840     std::swap(V1Size, V2Size);
841   }
842   if (const SelectInst *S1 = dyn_cast<SelectInst>(V1))
843     return aliasSelect(S1, V1Size, V2, V2Size);
844
845   return NoAA::alias(V1, V1Size, V2, V2Size);
846 }
847
848 // Make sure that anything that uses AliasAnalysis pulls in this file.
849 DEFINING_FILE_FOR(BasicAliasAnalysis)