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