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