speed up BasicAA a bit by implementing a long-standing TODO.
[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/CaptureTracking.h"
18 #include "llvm/Analysis/MemoryBuiltins.h"
19 #include "llvm/Analysis/Passes.h"
20 #include "llvm/Constants.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Function.h"
23 #include "llvm/GlobalVariable.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/IntrinsicInst.h"
26 #include "llvm/Operator.h"
27 #include "llvm/Pass.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/ADT/SmallSet.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/GetElementPtrTypeIterator.h"
34 #include <algorithm>
35 using namespace llvm;
36
37 //===----------------------------------------------------------------------===//
38 // Useful predicates
39 //===----------------------------------------------------------------------===//
40
41 static const Value *GetGEPOperands(const Value *V, 
42                                    SmallVector<Value*, 16> &GEPOps) {
43   assert(GEPOps.empty() && "Expect empty list to populate!");
44   GEPOps.insert(GEPOps.end(), cast<User>(V)->op_begin()+1,
45                 cast<User>(V)->op_end());
46
47   // Accumulate all of the chained indexes into the operand array
48   V = cast<User>(V)->getOperand(0);
49
50   while (const GEPOperator *G = dyn_cast<GEPOperator>(V)) {
51     if (!isa<Constant>(GEPOps[0]) || isa<GlobalValue>(GEPOps[0]) ||
52         !cast<Constant>(GEPOps[0])->isNullValue())
53       break;  // Don't handle folding arbitrary pointer offsets yet...
54     GEPOps.erase(GEPOps.begin());   // Drop the zero index
55     GEPOps.insert(GEPOps.begin(), G->op_begin()+1, G->op_end());
56     V = G->getOperand(0);
57   }
58   return V;
59 }
60
61 /// isKnownNonNull - Return true if we know that the specified value is never
62 /// null.
63 static bool isKnownNonNull(const Value *V) {
64   // Alloca never returns null, malloc might.
65   if (isa<AllocaInst>(V)) return true;
66   
67   // A byval argument is never null.
68   if (const Argument *A = dyn_cast<Argument>(V))
69     return A->hasByValAttr();
70
71   // Global values are not null unless extern weak.
72   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
73     return !GV->hasExternalWeakLinkage();
74   return false;
75 }
76
77 /// isNonEscapingLocalObject - Return true if the pointer is to a function-local
78 /// object that never escapes from the function.
79 static bool isNonEscapingLocalObject(const Value *V) {
80   // If this is a local allocation, check to see if it escapes.
81   if (isa<AllocaInst>(V) || isNoAliasCall(V))
82     // Set StoreCaptures to True so that we can assume in our callers that the
83     // pointer is not the result of a load instruction. Currently
84     // PointerMayBeCaptured doesn't have any special analysis for the
85     // StoreCaptures=false case; if it did, our callers could be refined to be
86     // more precise.
87     return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
88
89   // If this is an argument that corresponds to a byval or noalias argument,
90   // then it has not escaped before entering the function.  Check if it escapes
91   // inside the function.
92   if (const Argument *A = dyn_cast<Argument>(V))
93     if (A->hasByValAttr() || A->hasNoAliasAttr()) {
94       // Don't bother analyzing arguments already known not to escape.
95       if (A->hasNoCaptureAttr())
96         return true;
97       return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
98     }
99   return false;
100 }
101
102
103 /// isObjectSmallerThan - Return true if we can prove that the object specified
104 /// by V is smaller than Size.
105 static bool isObjectSmallerThan(const Value *V, unsigned Size,
106                                 const TargetData &TD) {
107   const Type *AccessTy;
108   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
109     AccessTy = GV->getType()->getElementType();
110   } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
111     if (!AI->isArrayAllocation())
112       AccessTy = AI->getType()->getElementType();
113     else
114       return false;
115   } else if (const CallInst* CI = extractMallocCall(V)) {
116     if (!isArrayMalloc(V, &TD))
117       // The size is the argument to the malloc call.
118       if (const ConstantInt* C = dyn_cast<ConstantInt>(CI->getOperand(1)))
119         return (C->getZExtValue() < Size);
120     return false;
121   } else if (const Argument *A = dyn_cast<Argument>(V)) {
122     if (A->hasByValAttr())
123       AccessTy = cast<PointerType>(A->getType())->getElementType();
124     else
125       return false;
126   } else {
127     return false;
128   }
129   
130   if (AccessTy->isSized())
131     return TD.getTypeAllocSize(AccessTy) < Size;
132   return false;
133 }
134
135 //===----------------------------------------------------------------------===//
136 // NoAA Pass
137 //===----------------------------------------------------------------------===//
138
139 namespace {
140   /// NoAA - This class implements the -no-aa pass, which always returns "I
141   /// don't know" for alias queries.  NoAA is unlike other alias analysis
142   /// implementations, in that it does not chain to a previous analysis.  As
143   /// such it doesn't follow many of the rules that other alias analyses must.
144   ///
145   struct NoAA : public ImmutablePass, public AliasAnalysis {
146     static char ID; // Class identification, replacement for typeinfo
147     NoAA() : ImmutablePass(&ID) {}
148     explicit NoAA(void *PID) : ImmutablePass(PID) { }
149
150     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
151     }
152
153     virtual void initializePass() {
154       TD = getAnalysisIfAvailable<TargetData>();
155     }
156
157     virtual AliasResult alias(const Value *V1, unsigned V1Size,
158                               const Value *V2, unsigned V2Size) {
159       return MayAlias;
160     }
161
162     virtual void getArgumentAccesses(Function *F, CallSite CS,
163                                      std::vector<PointerAccessInfo> &Info) {
164       llvm_unreachable("This method may not be called on this function!");
165     }
166
167     virtual bool pointsToConstantMemory(const Value *P) { return false; }
168     virtual ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size) {
169       return ModRef;
170     }
171     virtual ModRefResult getModRefInfo(CallSite CS1, CallSite CS2) {
172       return ModRef;
173     }
174
175     virtual void deleteValue(Value *V) {}
176     virtual void copyValue(Value *From, Value *To) {}
177   };
178 }  // End of anonymous namespace
179
180 // Register this pass...
181 char NoAA::ID = 0;
182 static RegisterPass<NoAA>
183 U("no-aa", "No Alias Analysis (always returns 'may' alias)", true, true);
184
185 // Declare that we implement the AliasAnalysis interface
186 static RegisterAnalysisGroup<AliasAnalysis> V(U);
187
188 ImmutablePass *llvm::createNoAAPass() { return new NoAA(); }
189
190 //===----------------------------------------------------------------------===//
191 // BasicAA Pass
192 //===----------------------------------------------------------------------===//
193
194 namespace {
195   /// BasicAliasAnalysis - This is the default alias analysis implementation.
196   /// Because it doesn't chain to a previous alias analysis (like -no-aa), it
197   /// derives from the NoAA class.
198   struct BasicAliasAnalysis : public NoAA {
199     static char ID; // Class identification, replacement for typeinfo
200     BasicAliasAnalysis() : NoAA(&ID) {}
201     AliasResult alias(const Value *V1, unsigned V1Size,
202                       const Value *V2, unsigned V2Size) {
203       assert(VisitedPHIs.empty() && "VisitedPHIs must be cleared after use!");
204       AliasResult Alias = aliasCheck(V1, V1Size, V2, V2Size);
205       VisitedPHIs.clear();
206       return Alias;
207     }
208
209     ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
210     ModRefResult getModRefInfo(CallSite CS1, CallSite CS2);
211
212     /// pointsToConstantMemory - Chase pointers until we find a (constant
213     /// global) or not.
214     bool pointsToConstantMemory(const Value *P);
215
216   private:
217     // VisitedPHIs - Track PHI nodes visited by a aliasCheck() call.
218     SmallPtrSet<const Value*, 16> VisitedPHIs;
219
220     // aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP instruction
221     // against another.
222     AliasResult aliasGEP(const Value *V1, unsigned V1Size,
223                          const Value *V2, unsigned V2Size);
224
225     // aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI instruction
226     // 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     // CheckGEPInstructions - Check two GEP instructions with known
238     // must-aliasing base pointers.  This checks to see if the index expressions
239     // preclude the pointers from aliasing...
240     AliasResult
241     CheckGEPInstructions(const Type* BasePtr1Ty,
242                          Value **GEP1Ops, unsigned NumGEP1Ops, unsigned G1Size,
243                          const Type *BasePtr2Ty,
244                          Value **GEP2Ops, unsigned NumGEP2Ops, unsigned G2Size);
245   };
246 }  // End of anonymous namespace
247
248 // Register this pass...
249 char BasicAliasAnalysis::ID = 0;
250 static RegisterPass<BasicAliasAnalysis>
251 X("basicaa", "Basic Alias Analysis (default AA impl)", false, true);
252
253 // Declare that we implement the AliasAnalysis interface
254 static RegisterAnalysisGroup<AliasAnalysis, true> Y(X);
255
256 ImmutablePass *llvm::createBasicAliasAnalysisPass() {
257   return new BasicAliasAnalysis();
258 }
259
260
261 /// pointsToConstantMemory - Chase pointers until we find a (constant
262 /// global) or not.
263 bool BasicAliasAnalysis::pointsToConstantMemory(const Value *P) {
264   if (const GlobalVariable *GV = 
265         dyn_cast<GlobalVariable>(P->getUnderlyingObject()))
266     // FIXME: shouldn't this require GV to be "ODR"?
267     return GV->isConstant();
268   return false;
269 }
270
271
272 // getModRefInfo - Check to see if the specified callsite can clobber the
273 // specified memory object.  Since we only look at local properties of this
274 // function, we really can't say much about this query.  We do, however, use
275 // simple "address taken" analysis on local objects.
276 //
277 AliasAnalysis::ModRefResult
278 BasicAliasAnalysis::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
279   const Value *Object = P->getUnderlyingObject();
280   
281   // If this is a tail call and P points to a stack location, we know that
282   // the tail call cannot access or modify the local stack.
283   // We cannot exclude byval arguments here; these belong to the caller of
284   // the current function not to the current function, and a tail callee
285   // may reference them.
286   if (isa<AllocaInst>(Object))
287     if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction()))
288       if (CI->isTailCall())
289         return NoModRef;
290   
291   // If the pointer is to a locally allocated object that does not escape,
292   // then the call can not mod/ref the pointer unless the call takes the pointer
293   // as an argument, and itself doesn't capture it.
294   if (isNonEscapingLocalObject(Object) && CS.getInstruction() != Object) {
295     bool PassedAsArg = false;
296     unsigned ArgNo = 0;
297     for (CallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
298          CI != CE; ++CI, ++ArgNo) {
299       // Only look at the no-capture pointer arguments.
300       if (!isa<PointerType>((*CI)->getType()) ||
301           !CS.paramHasAttr(ArgNo+1, Attribute::NoCapture))
302         continue;
303       
304       // If  this is a no-capture pointer argument, see if we can tell that it
305       // is impossible to alias the pointer we're checking.  If not, we have to
306       // assume that the call could touch the pointer, even though it doesn't
307       // escape.
308       if (alias(cast<Value>(CI), ~0U, P, ~0U) != NoAlias) {
309         PassedAsArg = true;
310         break;
311       }
312     }
313     
314     if (!PassedAsArg)
315       return NoModRef;
316   }
317
318   // Finally, handle specific knowledge of intrinsics.
319   IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction());
320   if (II == 0)
321     return AliasAnalysis::getModRefInfo(CS, P, Size);
322
323   switch (II->getIntrinsicID()) {
324   default: break;
325   case Intrinsic::memcpy:
326   case Intrinsic::memmove: {
327     unsigned Len = ~0U;
328     if (ConstantInt *LenCI = dyn_cast<ConstantInt>(II->getOperand(3)))
329       Len = LenCI->getZExtValue();
330     Value *Dest = II->getOperand(1);
331     Value *Src = II->getOperand(2);
332     if (alias(Dest, Len, P, Size) == NoAlias) {
333       if (alias(Src, Len, P, Size) == NoAlias)
334         return NoModRef;
335       return Ref;
336     }
337     break;
338   }
339   case Intrinsic::memset:
340     if (ConstantInt *LenCI = dyn_cast<ConstantInt>(II->getOperand(3))) {
341       unsigned Len = LenCI->getZExtValue();
342       Value *Dest = II->getOperand(1);
343       if (alias(Dest, Len, P, Size) == NoAlias)
344         return NoModRef;
345     }
346     break;
347   case Intrinsic::atomic_cmp_swap:
348   case Intrinsic::atomic_swap:
349   case Intrinsic::atomic_load_add:
350   case Intrinsic::atomic_load_sub:
351   case Intrinsic::atomic_load_and:
352   case Intrinsic::atomic_load_nand:
353   case Intrinsic::atomic_load_or:
354   case Intrinsic::atomic_load_xor:
355   case Intrinsic::atomic_load_max:
356   case Intrinsic::atomic_load_min:
357   case Intrinsic::atomic_load_umax:
358   case Intrinsic::atomic_load_umin:
359     if (TD) {
360       Value *Op1 = II->getOperand(1);
361       unsigned Op1Size = TD->getTypeStoreSize(Op1->getType());
362       if (alias(Op1, Op1Size, P, Size) == NoAlias)
363         return NoModRef;
364     }
365     break;
366   case Intrinsic::lifetime_start:
367   case Intrinsic::lifetime_end:
368   case Intrinsic::invariant_start: {
369     unsigned PtrSize = cast<ConstantInt>(II->getOperand(1))->getZExtValue();
370     if (alias(II->getOperand(2), PtrSize, P, Size) == NoAlias)
371       return NoModRef;
372     break;
373   }
374   case Intrinsic::invariant_end: {
375     unsigned PtrSize = cast<ConstantInt>(II->getOperand(2))->getZExtValue();
376     if (alias(II->getOperand(3), PtrSize, P, Size) == NoAlias)
377       return NoModRef;
378     break;
379   }
380   }
381
382   // The AliasAnalysis base class has some smarts, lets use them.
383   return AliasAnalysis::getModRefInfo(CS, P, Size);
384 }
385
386
387 AliasAnalysis::ModRefResult 
388 BasicAliasAnalysis::getModRefInfo(CallSite CS1, CallSite CS2) {
389   // If CS1 or CS2 are readnone, they don't interact.
390   ModRefBehavior CS1B = AliasAnalysis::getModRefBehavior(CS1);
391   if (CS1B == DoesNotAccessMemory) return NoModRef;
392   
393   ModRefBehavior CS2B = AliasAnalysis::getModRefBehavior(CS2);
394   if (CS2B == DoesNotAccessMemory) return NoModRef;
395   
396   // If they both only read from memory, just return ref.
397   if (CS1B == OnlyReadsMemory && CS2B == OnlyReadsMemory)
398     return Ref;
399   
400   // Otherwise, fall back to NoAA (mod+ref).
401   return NoAA::getModRefInfo(CS1, CS2);
402 }
403
404 // aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP instruction
405 // against another.
406 //
407 AliasAnalysis::AliasResult
408 BasicAliasAnalysis::aliasGEP(const Value *V1, unsigned V1Size,
409                              const Value *V2, unsigned V2Size) {
410   // If we have two gep instructions with must-alias'ing base pointers, figure
411   // out if the indexes to the GEP tell us anything about the derived pointer.
412   // Note that we also handle chains of getelementptr instructions as well as
413   // constant expression getelementptrs here.
414   //
415   if (isa<GEPOperator>(V1) && isa<GEPOperator>(V2)) {
416     const User *GEP1 = cast<User>(V1);
417     const User *GEP2 = cast<User>(V2);
418     
419     // If V1 and V2 are identical GEPs, just recurse down on both of them.
420     // This allows us to analyze things like:
421     //   P = gep A, 0, i, 1
422     //   Q = gep B, 0, i, 1
423     // by just analyzing A and B.  This is even safe for variable indices.
424     if (GEP1->getType() == GEP2->getType() &&
425         GEP1->getNumOperands() == GEP2->getNumOperands() &&
426         GEP1->getOperand(0)->getType() == GEP2->getOperand(0)->getType() &&
427         // All operands are the same, ignoring the base.
428         std::equal(GEP1->op_begin()+1, GEP1->op_end(), GEP2->op_begin()+1))
429       return aliasCheck(GEP1->getOperand(0), V1Size,
430                         GEP2->getOperand(0), V2Size);
431     
432     // Drill down into the first non-gep value, to test for must-aliasing of
433     // the base pointers.
434     while (isa<GEPOperator>(GEP1->getOperand(0)) &&
435            GEP1->getOperand(1) ==
436            Constant::getNullValue(GEP1->getOperand(1)->getType()))
437       GEP1 = cast<User>(GEP1->getOperand(0));
438     const Value *BasePtr1 = GEP1->getOperand(0);
439
440     while (isa<GEPOperator>(GEP2->getOperand(0)) &&
441            GEP2->getOperand(1) ==
442            Constant::getNullValue(GEP2->getOperand(1)->getType()))
443       GEP2 = cast<User>(GEP2->getOperand(0));
444     const Value *BasePtr2 = GEP2->getOperand(0);
445
446     // Do the base pointers alias?
447     AliasResult BaseAlias = aliasCheck(BasePtr1, ~0U, BasePtr2, ~0U);
448     if (BaseAlias == NoAlias) return NoAlias;
449     if (BaseAlias == MustAlias) {
450       // If the base pointers alias each other exactly, check to see if we can
451       // figure out anything about the resultant pointers, to try to prove
452       // non-aliasing.
453
454       // Collect all of the chained GEP operands together into one simple place
455       SmallVector<Value*, 16> GEP1Ops, GEP2Ops;
456       BasePtr1 = GetGEPOperands(V1, GEP1Ops);
457       BasePtr2 = GetGEPOperands(V2, GEP2Ops);
458
459       // If GetGEPOperands were able to fold to the same must-aliased pointer,
460       // do the comparison.
461       if (BasePtr1 == BasePtr2) {
462         AliasResult GAlias =
463           CheckGEPInstructions(BasePtr1->getType(),
464                                &GEP1Ops[0], GEP1Ops.size(), V1Size,
465                                BasePtr2->getType(),
466                                &GEP2Ops[0], GEP2Ops.size(), V2Size);
467         if (GAlias != MayAlias)
468           return GAlias;
469       }
470     }
471   }
472
473   // Check to see if these two pointers are related by a getelementptr
474   // instruction.  If one pointer is a GEP with a non-zero index of the other
475   // pointer, we know they cannot alias.
476   //
477   if (V1Size == ~0U || V2Size == ~0U)
478     return MayAlias;
479
480   SmallVector<Value*, 16> GEPOperands;
481   const Value *BasePtr = GetGEPOperands(V1, GEPOperands);
482
483   AliasResult R = aliasCheck(BasePtr, ~0U, V2, V2Size);
484   if (R != MustAlias)
485     // If V2 may alias GEP base pointer, conservatively returns MayAlias.
486     // If V2 is known not to alias GEP base pointer, then the two values
487     // cannot alias per GEP semantics: "A pointer value formed from a
488     // getelementptr instruction is associated with the addresses associated
489     // with the first operand of the getelementptr".
490     return R;
491
492   // If there is at least one non-zero constant index, we know they cannot
493   // alias.
494   bool ConstantFound = false;
495   bool AllZerosFound = true;
496   for (unsigned i = 0, e = GEPOperands.size(); i != e; ++i)
497     if (const Constant *C = dyn_cast<Constant>(GEPOperands[i])) {
498       if (!C->isNullValue()) {
499         ConstantFound = true;
500         AllZerosFound = false;
501         break;
502       }
503     } else {
504       AllZerosFound = false;
505     }
506
507   // If we have getelementptr <ptr>, 0, 0, 0, 0, ... and V2 must aliases
508   // the ptr, the end result is a must alias also.
509   if (AllZerosFound)
510     return MustAlias;
511
512   if (ConstantFound) {
513     if (V2Size <= 1 && V1Size <= 1)  // Just pointer check?
514       return NoAlias;
515
516     // Otherwise we have to check to see that the distance is more than
517     // the size of the argument... build an index vector that is equal to
518     // the arguments provided, except substitute 0's for any variable
519     // indexes we find...
520     if (TD &&
521         cast<PointerType>(BasePtr->getType())->getElementType()->isSized()) {
522       for (unsigned i = 0; i != GEPOperands.size(); ++i)
523         if (!isa<ConstantInt>(GEPOperands[i]))
524           GEPOperands[i] = Constant::getNullValue(GEPOperands[i]->getType());
525       int64_t Offset = TD->getIndexedOffset(BasePtr->getType(),
526                                             &GEPOperands[0],
527                                             GEPOperands.size());
528
529       if (Offset >= (int64_t)V2Size || Offset <= -(int64_t)V1Size)
530         return NoAlias;
531     }
532   }
533
534   return MayAlias;
535 }
536
537 // aliasSelect - Provide a bunch of ad-hoc rules to disambiguate a Select instruction
538 // against another.
539 AliasAnalysis::AliasResult
540 BasicAliasAnalysis::aliasSelect(const SelectInst *SI, unsigned SISize,
541                                 const Value *V2, unsigned V2Size) {
542   // If the values are Selects with the same condition, we can do a more precise
543   // check: just check for aliases between the values on corresponding arms.
544   if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2))
545     if (SI->getCondition() == SI2->getCondition()) {
546       AliasResult Alias =
547         aliasCheck(SI->getTrueValue(), SISize,
548                    SI2->getTrueValue(), V2Size);
549       if (Alias == MayAlias)
550         return MayAlias;
551       AliasResult ThisAlias =
552         aliasCheck(SI->getFalseValue(), SISize,
553                    SI2->getFalseValue(), V2Size);
554       if (ThisAlias != Alias)
555         return MayAlias;
556       return Alias;
557     }
558
559   // If both arms of the Select node NoAlias or MustAlias V2, then returns
560   // NoAlias / MustAlias. Otherwise, returns MayAlias.
561   AliasResult Alias =
562     aliasCheck(SI->getTrueValue(), SISize, V2, V2Size);
563   if (Alias == MayAlias)
564     return MayAlias;
565   AliasResult ThisAlias =
566     aliasCheck(SI->getFalseValue(), SISize, V2, V2Size);
567   if (ThisAlias != Alias)
568     return MayAlias;
569   return Alias;
570 }
571
572 // aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI instruction
573 // against another.
574 AliasAnalysis::AliasResult
575 BasicAliasAnalysis::aliasPHI(const PHINode *PN, unsigned PNSize,
576                              const Value *V2, unsigned V2Size) {
577   // The PHI node has already been visited, avoid recursion any further.
578   if (!VisitedPHIs.insert(PN))
579     return MayAlias;
580
581   // If the values are PHIs in the same block, we can do a more precise
582   // as well as efficient check: just check for aliases between the values
583   // on corresponding edges.
584   if (const PHINode *PN2 = dyn_cast<PHINode>(V2))
585     if (PN2->getParent() == PN->getParent()) {
586       AliasResult Alias =
587         aliasCheck(PN->getIncomingValue(0), PNSize,
588                    PN2->getIncomingValueForBlock(PN->getIncomingBlock(0)),
589                    V2Size);
590       if (Alias == MayAlias)
591         return MayAlias;
592       for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
593         AliasResult ThisAlias =
594           aliasCheck(PN->getIncomingValue(i), PNSize,
595                      PN2->getIncomingValueForBlock(PN->getIncomingBlock(i)),
596                      V2Size);
597         if (ThisAlias != Alias)
598           return MayAlias;
599       }
600       return Alias;
601     }
602
603   SmallPtrSet<Value*, 4> UniqueSrc;
604   SmallVector<Value*, 4> V1Srcs;
605   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
606     Value *PV1 = PN->getIncomingValue(i);
607     if (isa<PHINode>(PV1))
608       // If any of the source itself is a PHI, return MayAlias conservatively
609       // to avoid compile time explosion. The worst possible case is if both
610       // sides are PHI nodes. In which case, this is O(m x n) time where 'm'
611       // and 'n' are the number of PHI sources.
612       return MayAlias;
613     if (UniqueSrc.insert(PV1))
614       V1Srcs.push_back(PV1);
615   }
616
617   AliasResult Alias = aliasCheck(V2, V2Size, V1Srcs[0], PNSize);
618   // Early exit if the check of the first PHI source against V2 is MayAlias.
619   // Other results are not possible.
620   if (Alias == MayAlias)
621     return MayAlias;
622
623   // If all sources of the PHI node NoAlias or MustAlias V2, then returns
624   // NoAlias / MustAlias. Otherwise, returns MayAlias.
625   for (unsigned i = 1, e = V1Srcs.size(); i != e; ++i) {
626     Value *V = V1Srcs[i];
627
628     // If V2 is a PHI, the recursive case will have been caught in the
629     // above aliasCheck call, so these subsequent calls to aliasCheck
630     // don't need to assume that V2 is being visited recursively.
631     VisitedPHIs.erase(V2);
632
633     AliasResult ThisAlias = aliasCheck(V2, V2Size, V, PNSize);
634     if (ThisAlias != Alias || ThisAlias == MayAlias)
635       return MayAlias;
636   }
637
638   return Alias;
639 }
640
641 // aliasCheck - Provide a bunch of ad-hoc rules to disambiguate in common cases,
642 // such as array references.
643 //
644 AliasAnalysis::AliasResult
645 BasicAliasAnalysis::aliasCheck(const Value *V1, unsigned V1Size,
646                                const Value *V2, unsigned V2Size) {
647   // Strip off any casts if they exist.
648   V1 = V1->stripPointerCasts();
649   V2 = V2->stripPointerCasts();
650
651   // Are we checking for alias of the same value?
652   if (V1 == V2) return MustAlias;
653
654   if (!isa<PointerType>(V1->getType()) || !isa<PointerType>(V2->getType()))
655     return NoAlias;  // Scalars cannot alias each other
656
657   // Figure out what objects these things are pointing to if we can.
658   const Value *O1 = V1->getUnderlyingObject();
659   const Value *O2 = V2->getUnderlyingObject();
660
661   // Null values in the default address space don't point to any object, so they
662   // don't alias any other pointer.
663   if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O1))
664     if (CPN->getType()->getAddressSpace() == 0)
665       return NoAlias;
666   if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O2))
667     if (CPN->getType()->getAddressSpace() == 0)
668       return NoAlias;
669
670   if (O1 != O2) {
671     // If V1/V2 point to two different objects we know that we have no alias.
672     if (isIdentifiedObject(O1) && isIdentifiedObject(O2))
673       return NoAlias;
674
675     // Constant pointers can't alias with non-const isIdentifiedObject objects.
676     if ((isa<Constant>(O1) && isIdentifiedObject(O2) && !isa<Constant>(O2)) ||
677         (isa<Constant>(O2) && isIdentifiedObject(O1) && !isa<Constant>(O1)))
678       return NoAlias;
679
680     // Arguments can't alias with local allocations or noalias calls.
681     if ((isa<Argument>(O1) && (isa<AllocaInst>(O2) || isNoAliasCall(O2))) ||
682         (isa<Argument>(O2) && (isa<AllocaInst>(O1) || isNoAliasCall(O1))))
683       return NoAlias;
684
685     // Most objects can't alias null.
686     if ((isa<ConstantPointerNull>(V2) && isKnownNonNull(O1)) ||
687         (isa<ConstantPointerNull>(V1) && isKnownNonNull(O2)))
688       return NoAlias;
689   }
690   
691   // If the size of one access is larger than the entire object on the other
692   // side, then we know such behavior is undefined and can assume no alias.
693   if (TD)
694     if ((V1Size != ~0U && isObjectSmallerThan(O2, V1Size, *TD)) ||
695         (V2Size != ~0U && isObjectSmallerThan(O1, V2Size, *TD)))
696       return NoAlias;
697   
698   // If one pointer is the result of a call/invoke or load and the other is a
699   // non-escaping local object, then we know the object couldn't escape to a
700   // point where the call could return it. The load case works because
701   // isNonEscapingLocalObject considers all stores to be escapes (it
702   // passes true for the StoreCaptures argument to PointerMayBeCaptured).
703   if (O1 != O2) {
704     if ((isa<CallInst>(O1) || isa<InvokeInst>(O1) || isa<LoadInst>(O1)) &&
705         isNonEscapingLocalObject(O2))
706       return NoAlias;
707     if ((isa<CallInst>(O2) || isa<InvokeInst>(O2) || isa<LoadInst>(O2)) &&
708         isNonEscapingLocalObject(O1))
709       return NoAlias;
710   }
711
712   if (!isa<GEPOperator>(V1) && isa<GEPOperator>(V2)) {
713     std::swap(V1, V2);
714     std::swap(V1Size, V2Size);
715   }
716   if (isa<GEPOperator>(V1))
717     return aliasGEP(V1, V1Size, V2, V2Size);
718
719   if (isa<PHINode>(V2) && !isa<PHINode>(V1)) {
720     std::swap(V1, V2);
721     std::swap(V1Size, V2Size);
722   }
723   if (const PHINode *PN = dyn_cast<PHINode>(V1))
724     return aliasPHI(PN, V1Size, V2, V2Size);
725
726   if (isa<SelectInst>(V2) && !isa<SelectInst>(V1)) {
727     std::swap(V1, V2);
728     std::swap(V1Size, V2Size);
729   }
730   if (const SelectInst *S1 = dyn_cast<SelectInst>(V1))
731     return aliasSelect(S1, V1Size, V2, V2Size);
732
733   return MayAlias;
734 }
735
736 // This function is used to determine if the indices of two GEP instructions are
737 // equal. V1 and V2 are the indices.
738 static bool IndexOperandsEqual(Value *V1, Value *V2) {
739   if (V1->getType() == V2->getType())
740     return V1 == V2;
741   if (Constant *C1 = dyn_cast<Constant>(V1))
742     if (Constant *C2 = dyn_cast<Constant>(V2)) {
743       // Sign extend the constants to long types, if necessary
744       if (C1->getType() != Type::getInt64Ty(C1->getContext()))
745         C1 = ConstantExpr::getSExt(C1, Type::getInt64Ty(C1->getContext()));
746       if (C2->getType() != Type::getInt64Ty(C1->getContext())) 
747         C2 = ConstantExpr::getSExt(C2, Type::getInt64Ty(C1->getContext()));
748       return C1 == C2;
749     }
750   return false;
751 }
752
753 /// CheckGEPInstructions - Check two GEP instructions with known must-aliasing
754 /// base pointers.  This checks to see if the index expressions preclude the
755 /// pointers from aliasing...
756 AliasAnalysis::AliasResult 
757 BasicAliasAnalysis::CheckGEPInstructions(
758   const Type* BasePtr1Ty, Value **GEP1Ops, unsigned NumGEP1Ops, unsigned G1S,
759   const Type *BasePtr2Ty, Value **GEP2Ops, unsigned NumGEP2Ops, unsigned G2S) {
760   // We currently can't handle the case when the base pointers have different
761   // primitive types.  Since this is uncommon anyway, we are happy being
762   // extremely conservative.
763   if (BasePtr1Ty != BasePtr2Ty)
764     return MayAlias;
765
766   const PointerType *GEPPointerTy = cast<PointerType>(BasePtr1Ty);
767
768   // Find the (possibly empty) initial sequence of equal values... which are not
769   // necessarily constants.
770   unsigned NumGEP1Operands = NumGEP1Ops, NumGEP2Operands = NumGEP2Ops;
771   unsigned MinOperands = std::min(NumGEP1Operands, NumGEP2Operands);
772   unsigned MaxOperands = std::max(NumGEP1Operands, NumGEP2Operands);
773   unsigned UnequalOper = 0;
774   while (UnequalOper != MinOperands &&
775          IndexOperandsEqual(GEP1Ops[UnequalOper], GEP2Ops[UnequalOper])) {
776     // Advance through the type as we go...
777     ++UnequalOper;
778     if (const CompositeType *CT = dyn_cast<CompositeType>(BasePtr1Ty))
779       BasePtr1Ty = CT->getTypeAtIndex(GEP1Ops[UnequalOper-1]);
780     else {
781       // If all operands equal each other, then the derived pointers must
782       // alias each other...
783       BasePtr1Ty = 0;
784       assert(UnequalOper == NumGEP1Operands && UnequalOper == NumGEP2Operands &&
785              "Ran out of type nesting, but not out of operands?");
786       return MustAlias;
787     }
788   }
789
790   // If we have seen all constant operands, and run out of indexes on one of the
791   // getelementptrs, check to see if the tail of the leftover one is all zeros.
792   // If so, return mustalias.
793   if (UnequalOper == MinOperands) {
794     if (NumGEP1Ops < NumGEP2Ops) {
795       std::swap(GEP1Ops, GEP2Ops);
796       std::swap(NumGEP1Ops, NumGEP2Ops);
797     }
798
799     bool AllAreZeros = true;
800     for (unsigned i = UnequalOper; i != MaxOperands; ++i)
801       if (!isa<Constant>(GEP1Ops[i]) ||
802           !cast<Constant>(GEP1Ops[i])->isNullValue()) {
803         AllAreZeros = false;
804         break;
805       }
806     if (AllAreZeros) return MustAlias;
807   }
808
809
810   // So now we know that the indexes derived from the base pointers,
811   // which are known to alias, are different.  We can still determine a
812   // no-alias result if there are differing constant pairs in the index
813   // chain.  For example:
814   //        A[i][0] != A[j][1] iff (&A[0][1]-&A[0][0] >= std::max(G1S, G2S))
815   //
816   // We have to be careful here about array accesses.  In particular, consider:
817   //        A[1][0] vs A[0][i]
818   // In this case, we don't *know* that the array will be accessed in bounds:
819   // the index could even be negative.  Because of this, we have to
820   // conservatively *give up* and return may alias.  We disregard differing
821   // array subscripts that are followed by a variable index without going
822   // through a struct.
823   //
824   unsigned SizeMax = std::max(G1S, G2S);
825   if (SizeMax == ~0U) return MayAlias; // Avoid frivolous work.
826
827   // Scan for the first operand that is constant and unequal in the
828   // two getelementptrs...
829   unsigned FirstConstantOper = UnequalOper;
830   for (; FirstConstantOper != MinOperands; ++FirstConstantOper) {
831     const Value *G1Oper = GEP1Ops[FirstConstantOper];
832     const Value *G2Oper = GEP2Ops[FirstConstantOper];
833
834     if (G1Oper != G2Oper)   // Found non-equal constant indexes...
835       if (Constant *G1OC = dyn_cast<ConstantInt>(const_cast<Value*>(G1Oper)))
836         if (Constant *G2OC = dyn_cast<ConstantInt>(const_cast<Value*>(G2Oper))){
837           if (G1OC->getType() != G2OC->getType()) {
838             // Sign extend both operands to long.
839             const Type *Int64Ty = Type::getInt64Ty(G1OC->getContext());
840             if (G1OC->getType() != Int64Ty)
841               G1OC = ConstantExpr::getSExt(G1OC, Int64Ty);
842             if (G2OC->getType() != Int64Ty) 
843               G2OC = ConstantExpr::getSExt(G2OC, Int64Ty);
844             GEP1Ops[FirstConstantOper] = G1OC;
845             GEP2Ops[FirstConstantOper] = G2OC;
846           }
847           
848           if (G1OC != G2OC) {
849             // Handle the "be careful" case above: if this is an array/vector
850             // subscript, scan for a subsequent variable array index.
851             if (const SequentialType *STy =
852                   dyn_cast<SequentialType>(BasePtr1Ty)) {
853               const Type *NextTy = STy;
854               bool isBadCase = false;
855               
856               for (unsigned Idx = FirstConstantOper;
857                    Idx != MinOperands && isa<SequentialType>(NextTy); ++Idx) {
858                 const Value *V1 = GEP1Ops[Idx], *V2 = GEP2Ops[Idx];
859                 if (!isa<Constant>(V1) || !isa<Constant>(V2)) {
860                   isBadCase = true;
861                   break;
862                 }
863                 // If the array is indexed beyond the bounds of the static type
864                 // at this level, it will also fall into the "be careful" case.
865                 // It would theoretically be possible to analyze these cases,
866                 // but for now just be conservatively correct.
867                 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
868                   if (cast<ConstantInt>(G1OC)->getZExtValue() >=
869                         ATy->getNumElements() ||
870                       cast<ConstantInt>(G2OC)->getZExtValue() >=
871                         ATy->getNumElements()) {
872                     isBadCase = true;
873                     break;
874                   }
875                 if (const VectorType *VTy = dyn_cast<VectorType>(STy))
876                   if (cast<ConstantInt>(G1OC)->getZExtValue() >=
877                         VTy->getNumElements() ||
878                       cast<ConstantInt>(G2OC)->getZExtValue() >=
879                         VTy->getNumElements()) {
880                     isBadCase = true;
881                     break;
882                   }
883                 STy = cast<SequentialType>(NextTy);
884                 NextTy = cast<SequentialType>(NextTy)->getElementType();
885               }
886               
887               if (isBadCase) G1OC = 0;
888             }
889
890             // Make sure they are comparable (ie, not constant expressions), and
891             // make sure the GEP with the smaller leading constant is GEP1.
892             if (G1OC) {
893               Constant *Compare = ConstantExpr::getICmp(ICmpInst::ICMP_SGT, 
894                                                         G1OC, G2OC);
895               if (ConstantInt *CV = dyn_cast<ConstantInt>(Compare)) {
896                 if (CV->getZExtValue()) {  // If they are comparable and G2 > G1
897                   std::swap(GEP1Ops, GEP2Ops);  // Make GEP1 < GEP2
898                   std::swap(NumGEP1Ops, NumGEP2Ops);
899                 }
900                 break;
901               }
902             }
903           }
904         }
905     BasePtr1Ty = cast<CompositeType>(BasePtr1Ty)->getTypeAtIndex(G1Oper);
906   }
907
908   // No shared constant operands, and we ran out of common operands.  At this
909   // point, the GEP instructions have run through all of their operands, and we
910   // haven't found evidence that there are any deltas between the GEP's.
911   // However, one GEP may have more operands than the other.  If this is the
912   // case, there may still be hope.  Check this now.
913   if (FirstConstantOper == MinOperands) {
914     // Without TargetData, we won't know what the offsets are.
915     if (!TD)
916       return MayAlias;
917
918     // Make GEP1Ops be the longer one if there is a longer one.
919     if (NumGEP1Ops < NumGEP2Ops) {
920       std::swap(GEP1Ops, GEP2Ops);
921       std::swap(NumGEP1Ops, NumGEP2Ops);
922     }
923
924     // Is there anything to check?
925     if (NumGEP1Ops > MinOperands) {
926       for (unsigned i = FirstConstantOper; i != MaxOperands; ++i)
927         if (isa<ConstantInt>(GEP1Ops[i]) && 
928             !cast<ConstantInt>(GEP1Ops[i])->isZero()) {
929           // Yup, there's a constant in the tail.  Set all variables to
930           // constants in the GEP instruction to make it suitable for
931           // TargetData::getIndexedOffset.
932           for (i = 0; i != MaxOperands; ++i)
933             if (!isa<ConstantInt>(GEP1Ops[i]))
934               GEP1Ops[i] = Constant::getNullValue(GEP1Ops[i]->getType());
935           // Okay, now get the offset.  This is the relative offset for the full
936           // instruction.
937           int64_t Offset1 = TD->getIndexedOffset(GEPPointerTy, GEP1Ops,
938                                                  NumGEP1Ops);
939
940           // Now check without any constants at the end.
941           int64_t Offset2 = TD->getIndexedOffset(GEPPointerTy, GEP1Ops,
942                                                  MinOperands);
943
944           // Make sure we compare the absolute difference.
945           if (Offset1 > Offset2)
946             std::swap(Offset1, Offset2);
947
948           // If the tail provided a bit enough offset, return noalias!
949           if ((uint64_t)(Offset2-Offset1) >= SizeMax)
950             return NoAlias;
951           // Otherwise break - we don't look for another constant in the tail.
952           break;
953         }
954     }
955
956     // Couldn't find anything useful.
957     return MayAlias;
958   }
959
960   // If there are non-equal constants arguments, then we can figure
961   // out a minimum known delta between the two index expressions... at
962   // this point we know that the first constant index of GEP1 is less
963   // than the first constant index of GEP2.
964
965   // Advance BasePtr[12]Ty over this first differing constant operand.
966   BasePtr2Ty = cast<CompositeType>(BasePtr1Ty)->
967       getTypeAtIndex(GEP2Ops[FirstConstantOper]);
968   BasePtr1Ty = cast<CompositeType>(BasePtr1Ty)->
969       getTypeAtIndex(GEP1Ops[FirstConstantOper]);
970
971   // We are going to be using TargetData::getIndexedOffset to determine the
972   // offset that each of the GEP's is reaching.  To do this, we have to convert
973   // all variable references to constant references.  To do this, we convert the
974   // initial sequence of array subscripts into constant zeros to start with.
975   const Type *ZeroIdxTy = GEPPointerTy;
976   for (unsigned i = 0; i != FirstConstantOper; ++i) {
977     if (!isa<StructType>(ZeroIdxTy))
978       GEP1Ops[i] = GEP2Ops[i] = 
979               Constant::getNullValue(Type::getInt32Ty(ZeroIdxTy->getContext()));
980
981     if (const CompositeType *CT = dyn_cast<CompositeType>(ZeroIdxTy))
982       ZeroIdxTy = CT->getTypeAtIndex(GEP1Ops[i]);
983   }
984
985   // We know that GEP1Ops[FirstConstantOper] & GEP2Ops[FirstConstantOper] are ok
986
987   // Loop over the rest of the operands...
988   for (unsigned i = FirstConstantOper+1; i != MaxOperands; ++i) {
989     const Value *Op1 = i < NumGEP1Ops ? GEP1Ops[i] : 0;
990     const Value *Op2 = i < NumGEP2Ops ? GEP2Ops[i] : 0;
991     // If they are equal, use a zero index...
992     if (Op1 == Op2 && BasePtr1Ty == BasePtr2Ty) {
993       if (!isa<ConstantInt>(Op1))
994         GEP1Ops[i] = GEP2Ops[i] = Constant::getNullValue(Op1->getType());
995       // Otherwise, just keep the constants we have.
996     } else {
997       if (Op1) {
998         if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
999           // If this is an array index, make sure the array element is in range.
1000           if (const ArrayType *AT = dyn_cast<ArrayType>(BasePtr1Ty)) {
1001             if (Op1C->getZExtValue() >= AT->getNumElements())
1002               return MayAlias;  // Be conservative with out-of-range accesses
1003           } else if (const VectorType *VT = dyn_cast<VectorType>(BasePtr1Ty)) {
1004             if (Op1C->getZExtValue() >= VT->getNumElements())
1005               return MayAlias;  // Be conservative with out-of-range accesses
1006           }
1007           
1008         } else {
1009           // GEP1 is known to produce a value less than GEP2.  To be
1010           // conservatively correct, we must assume the largest possible
1011           // constant is used in this position.  This cannot be the initial
1012           // index to the GEP instructions (because we know we have at least one
1013           // element before this one with the different constant arguments), so
1014           // we know that the current index must be into either a struct or
1015           // array.  Because we know it's not constant, this cannot be a
1016           // structure index.  Because of this, we can calculate the maximum
1017           // value possible.
1018           //
1019           if (const ArrayType *AT = dyn_cast<ArrayType>(BasePtr1Ty))
1020             GEP1Ops[i] =
1021                   ConstantInt::get(Type::getInt64Ty(AT->getContext()), 
1022                                    AT->getNumElements()-1);
1023           else if (const VectorType *VT = dyn_cast<VectorType>(BasePtr1Ty))
1024             GEP1Ops[i] = 
1025                   ConstantInt::get(Type::getInt64Ty(VT->getContext()),
1026                                    VT->getNumElements()-1);
1027         }
1028       }
1029
1030       if (Op2) {
1031         if (const ConstantInt *Op2C = dyn_cast<ConstantInt>(Op2)) {
1032           // If this is an array index, make sure the array element is in range.
1033           if (const ArrayType *AT = dyn_cast<ArrayType>(BasePtr2Ty)) {
1034             if (Op2C->getZExtValue() >= AT->getNumElements())
1035               return MayAlias;  // Be conservative with out-of-range accesses
1036           } else if (const VectorType *VT = dyn_cast<VectorType>(BasePtr2Ty)) {
1037             if (Op2C->getZExtValue() >= VT->getNumElements())
1038               return MayAlias;  // Be conservative with out-of-range accesses
1039           }
1040         } else {  // Conservatively assume the minimum value for this index
1041           GEP2Ops[i] = Constant::getNullValue(Op2->getType());
1042         }
1043       }
1044     }
1045
1046     if (BasePtr1Ty && Op1) {
1047       if (const CompositeType *CT = dyn_cast<CompositeType>(BasePtr1Ty))
1048         BasePtr1Ty = CT->getTypeAtIndex(GEP1Ops[i]);
1049       else
1050         BasePtr1Ty = 0;
1051     }
1052
1053     if (BasePtr2Ty && Op2) {
1054       if (const CompositeType *CT = dyn_cast<CompositeType>(BasePtr2Ty))
1055         BasePtr2Ty = CT->getTypeAtIndex(GEP2Ops[i]);
1056       else
1057         BasePtr2Ty = 0;
1058     }
1059   }
1060
1061   if (TD && GEPPointerTy->getElementType()->isSized()) {
1062     int64_t Offset1 =
1063       TD->getIndexedOffset(GEPPointerTy, GEP1Ops, NumGEP1Ops);
1064     int64_t Offset2 = 
1065       TD->getIndexedOffset(GEPPointerTy, GEP2Ops, NumGEP2Ops);
1066     assert(Offset1 != Offset2 &&
1067            "There is at least one different constant here!");
1068     
1069     // Make sure we compare the absolute difference.
1070     if (Offset1 > Offset2)
1071       std::swap(Offset1, Offset2);
1072     
1073     if ((uint64_t)(Offset2-Offset1) >= SizeMax) {
1074       //cerr << "Determined that these two GEP's don't alias ["
1075       //     << SizeMax << " bytes]: \n" << *GEP1 << *GEP2;
1076       return NoAlias;
1077     }
1078   }
1079   return MayAlias;
1080 }
1081
1082 // Make sure that anything that uses AliasAnalysis pulls in this file...
1083 DEFINING_FILE_FOR(BasicAliasAnalysis)