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