Fix PR86. This makes basicaa _SIGNIFICANLY_ more aggressive with getelementptr's
[oota-llvm.git] / lib / Analysis / BasicAliasAnalysis.cpp
1 //===- BasicAliasAnalysis.cpp - Local Alias Analysis Impl -----------------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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/Pass.h"
18 #include "llvm/Argument.h"
19 #include "llvm/iOther.h"
20 #include "llvm/ConstantHandling.h"
21 #include "llvm/GlobalValue.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/Target/TargetData.h"
24 #include "llvm/Support/GetElementPtrTypeIterator.h"
25 using namespace llvm;
26
27 // Make sure that anything that uses AliasAnalysis pulls in this file...
28 void llvm::BasicAAStub() {}
29
30 namespace {
31   struct BasicAliasAnalysis : public ImmutablePass, public AliasAnalysis {
32     
33     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
34       AliasAnalysis::getAnalysisUsage(AU);
35     }
36     
37     virtual void initializePass();
38
39     // alias - This is the only method here that does anything interesting...
40     //
41     AliasResult alias(const Value *V1, unsigned V1Size,
42                       const Value *V2, unsigned V2Size);
43   private:
44     // CheckGEPInstructions - Check two GEP instructions with known
45     // must-aliasing base pointers.  This checks to see if the index expressions
46     // preclude the pointers from aliasing...
47     AliasResult
48     CheckGEPInstructions(const Type* BasePtr1Ty, std::vector<Value*> &GEP1Ops,
49                          unsigned G1Size,
50                          const Type *BasePtr2Ty, std::vector<Value*> &GEP2Ops,
51                          unsigned G2Size);
52   };
53  
54   // Register this pass...
55   RegisterOpt<BasicAliasAnalysis>
56   X("basicaa", "Basic Alias Analysis (default AA impl)");
57
58   // Declare that we implement the AliasAnalysis interface
59   RegisterAnalysisGroup<AliasAnalysis, BasicAliasAnalysis, true> Y;
60 }  // End of anonymous namespace
61
62 void BasicAliasAnalysis::initializePass() {
63   InitializeAliasAnalysis(this);
64 }
65
66 // hasUniqueAddress - Return true if the specified value points to something
67 // with a unique, discernable, address.
68 static inline bool hasUniqueAddress(const Value *V) {
69   return isa<GlobalValue>(V) || isa<AllocationInst>(V);
70 }
71
72 // getUnderlyingObject - This traverses the use chain to figure out what object
73 // the specified value points to.  If the value points to, or is derived from, a
74 // unique object or an argument, return it.
75 static const Value *getUnderlyingObject(const Value *V) {
76   if (!isa<PointerType>(V->getType())) return 0;
77
78   // If we are at some type of object... return it.
79   if (hasUniqueAddress(V) || isa<Argument>(V)) return V;
80   
81   // Traverse through different addressing mechanisms...
82   if (const Instruction *I = dyn_cast<Instruction>(V)) {
83     if (isa<CastInst>(I) || isa<GetElementPtrInst>(I))
84       return getUnderlyingObject(I->getOperand(0));
85   } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
86     if (CE->getOpcode() == Instruction::Cast ||
87         CE->getOpcode() == Instruction::GetElementPtr)
88       return getUnderlyingObject(CE->getOperand(0));
89   } else if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(V)) {
90     return CPR->getValue();
91   }
92   return 0;
93 }
94
95 static const User *isGEP(const Value *V) {
96   if (isa<GetElementPtrInst>(V) ||
97       (isa<ConstantExpr>(V) &&
98        cast<ConstantExpr>(V)->getOpcode() == Instruction::GetElementPtr))
99     return cast<User>(V);
100   return 0;
101 }
102
103 // alias - Provide a bunch of ad-hoc rules to disambiguate in common cases, such
104 // as array references.  Note that this function is heavily tail recursive.
105 // Hopefully we have a smart C++ compiler.  :)
106 //
107 AliasAnalysis::AliasResult
108 BasicAliasAnalysis::alias(const Value *V1, unsigned V1Size,
109                           const Value *V2, unsigned V2Size) {
110   // Strip off any constant expression casts if they exist
111   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V1))
112     if (CE->getOpcode() == Instruction::Cast)
113       V1 = CE->getOperand(0);
114   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V2))
115     if (CE->getOpcode() == Instruction::Cast)
116       V2 = CE->getOperand(0);
117
118   // Strip off constant pointer refs if they exist
119   if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(V1))
120     V1 = CPR->getValue();
121   if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(V2))
122     V2 = CPR->getValue();
123
124   // Are we checking for alias of the same value?
125   if (V1 == V2) return MustAlias;
126
127   if ((!isa<PointerType>(V1->getType()) || !isa<PointerType>(V2->getType())) &&
128       V1->getType() != Type::LongTy && V2->getType() != Type::LongTy)
129     return NoAlias;  // Scalars cannot alias each other
130
131   // Strip off cast instructions...
132   if (const Instruction *I = dyn_cast<CastInst>(V1))
133     return alias(I->getOperand(0), V1Size, V2, V2Size);
134   if (const Instruction *I = dyn_cast<CastInst>(V2))
135     return alias(V1, V1Size, I->getOperand(0), V2Size);
136
137   // Figure out what objects these things are pointing to if we can...
138   const Value *O1 = getUnderlyingObject(V1);
139   const Value *O2 = getUnderlyingObject(V2);
140
141   // Pointing at a discernible object?
142   if (O1 && O2) {
143     if (isa<Argument>(O1)) {
144       // Incoming argument cannot alias locally allocated object!
145       if (isa<AllocationInst>(O2)) return NoAlias;
146       // Otherwise, nothing is known...
147     } else if (isa<Argument>(O2)) {
148       // Incoming argument cannot alias locally allocated object!
149       if (isa<AllocationInst>(O1)) return NoAlias;
150       // Otherwise, nothing is known...
151     } else {
152       // If they are two different objects, we know that we have no alias...
153       if (O1 != O2) return NoAlias;
154     }
155
156     // If they are the same object, they we can look at the indexes.  If they
157     // index off of the object is the same for both pointers, they must alias.
158     // If they are provably different, they must not alias.  Otherwise, we can't
159     // tell anything.
160   } else if (O1 && !isa<Argument>(O1) && isa<ConstantPointerNull>(V2)) {
161     return NoAlias;                    // Unique values don't alias null
162   } else if (O2 && !isa<Argument>(O2) && isa<ConstantPointerNull>(V1)) {
163     return NoAlias;                    // Unique values don't alias null
164   }
165
166   // If we have two gep instructions with must-alias'ing base pointers, figure
167   // out if the indexes to the GEP tell us anything about the derived pointer.
168   // Note that we also handle chains of getelementptr instructions as well as
169   // constant expression getelementptrs here.
170   //
171   if (isGEP(V1) && isGEP(V2)) {
172     // Drill down into the first non-gep value, to test for must-aliasing of
173     // the base pointers.
174     const Value *BasePtr1 = V1, *BasePtr2 = V2;
175     do {
176       BasePtr1 = cast<User>(BasePtr1)->getOperand(0);
177     } while (isGEP(BasePtr1) &&
178              cast<User>(BasePtr1)->getOperand(1) == 
179        Constant::getNullValue(cast<User>(BasePtr1)->getOperand(1)->getType()));
180     do {
181       BasePtr2 = cast<User>(BasePtr2)->getOperand(0);
182     } while (isGEP(BasePtr2) &&
183              cast<User>(BasePtr2)->getOperand(1) == 
184        Constant::getNullValue(cast<User>(BasePtr2)->getOperand(1)->getType()));
185
186     // Do the base pointers alias?
187     AliasResult BaseAlias = alias(BasePtr1, V1Size, BasePtr2, V2Size);
188     if (BaseAlias == NoAlias) return NoAlias;
189     if (BaseAlias == MustAlias) {
190       // If the base pointers alias each other exactly, check to see if we can
191       // figure out anything about the resultant pointers, to try to prove
192       // non-aliasing.
193
194       // Collect all of the chained GEP operands together into one simple place
195       std::vector<Value*> GEP1Ops(cast<User>(V1)->op_begin()+1,
196                                   cast<User>(V1)->op_end());
197       std::vector<Value*> GEP2Ops(cast<User>(V2)->op_begin()+1,
198                                   cast<User>(V2)->op_end());
199
200       // Accumulate all of the chained indexes into the operand arrays
201       BasePtr1 = cast<User>(V1)->getOperand(0);
202       BasePtr2 = cast<User>(V2)->getOperand(0);
203       while (const User *G = isGEP(BasePtr1)) {
204         if (!isa<Constant>(GEP1Ops[0]) ||
205             !cast<Constant>(GEP1Ops[0])->isNullValue())
206           break;  // Don't handle folding arbitrary pointer offsets yet...
207         GEP1Ops.erase(GEP1Ops.begin());
208         GEP1Ops.insert(GEP1Ops.begin(), G->op_begin()+1, G->op_end());
209         BasePtr1 = G->getOperand(0);
210       }
211       while (const User *G = isGEP(BasePtr2)) {
212         if (!isa<Constant>(GEP2Ops[0]) ||
213             !cast<Constant>(GEP2Ops[0])->isNullValue())
214           break;  // Don't handle folding arbitrary pointer offsets yet...
215         GEP2Ops.erase(GEP2Ops.begin());
216         GEP2Ops.insert(GEP2Ops.begin(), G->op_begin()+1, G->op_end());
217         BasePtr2 = G->getOperand(0);
218       }
219       
220       AliasResult GAlias =
221         CheckGEPInstructions(BasePtr1->getType(), GEP1Ops, V1Size,
222                              BasePtr2->getType(), GEP2Ops, V2Size);
223       if (GAlias != MayAlias)
224         return GAlias;
225     }
226   }
227
228   // Check to see if these two pointers are related by a getelementptr
229   // instruction.  If one pointer is a GEP with a non-zero index of the other
230   // pointer, we know they cannot alias.
231   //
232   if (isa<GetElementPtrInst>(V2)) {
233     std::swap(V1, V2);
234     std::swap(V1Size, V2Size);
235   }
236
237   if (V1Size != ~0U && V2Size != ~0U)
238     if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V1)) {
239       AliasResult R = alias(GEP->getOperand(0), V1Size, V2, V2Size);
240       if (R == MustAlias) {
241         // If there is at least one non-zero constant index, we know they cannot
242         // alias.
243         bool ConstantFound = false;
244         bool AllZerosFound = true;
245         for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
246           if (const Constant *C = dyn_cast<Constant>(GEP->getOperand(i))) {
247             if (!C->isNullValue()) {
248               ConstantFound = true;
249               AllZerosFound = false;
250               break;
251             }
252           } else {
253             AllZerosFound = false;
254           }
255
256         // If we have getelementptr <ptr>, 0, 0, 0, 0, ... and V2 must aliases
257         // the ptr, the end result is a must alias also.
258         if (AllZerosFound)
259           return MustAlias;
260
261         if (ConstantFound) {
262           if (V2Size <= 1 && V1Size <= 1)  // Just pointer check?
263             return NoAlias;
264           
265           // Otherwise we have to check to see that the distance is more than
266           // the size of the argument... build an index vector that is equal to
267           // the arguments provided, except substitute 0's for any variable
268           // indexes we find...
269           
270           std::vector<Value*> Indices;
271           Indices.reserve(GEP->getNumOperands()-1);
272           for (unsigned i = 1; i != GEP->getNumOperands(); ++i)
273             if (const Constant *C = dyn_cast<Constant>(GEP->getOperand(i)))
274               Indices.push_back((Value*)C);
275             else
276               Indices.push_back(Constant::getNullValue(Type::LongTy));
277           const Type *Ty = GEP->getOperand(0)->getType();
278           int Offset = getTargetData().getIndexedOffset(Ty, Indices);
279           if (Offset >= (int)V2Size || Offset <= -(int)V1Size)
280             return NoAlias;
281         }
282       }
283     }
284   
285   return MayAlias;
286 }
287
288 /// CheckGEPInstructions - Check two GEP instructions with known must-aliasing
289 /// base pointers.  This checks to see if the index expressions preclude the
290 /// pointers from aliasing...
291 AliasAnalysis::AliasResult BasicAliasAnalysis::
292 CheckGEPInstructions(const Type* BasePtr1Ty, std::vector<Value*> &GEP1Ops,
293                      unsigned G1S,
294                      const Type *BasePtr2Ty, std::vector<Value*> &GEP2Ops,
295                      unsigned G2S) {
296   // We currently can't handle the case when the base pointers have different
297   // primitive types.  Since this is uncommon anyway, we are happy being
298   // extremely conservative.
299   if (BasePtr1Ty != BasePtr2Ty)
300     return MayAlias;
301
302   const Type *GEPPointerTy = BasePtr1Ty;
303
304   // Find the (possibly empty) initial sequence of equal values... which are not
305   // necessarily constants.
306   unsigned NumGEP1Operands = GEP1Ops.size(), NumGEP2Operands = GEP2Ops.size();
307   unsigned MinOperands = std::min(NumGEP1Operands, NumGEP2Operands);
308   unsigned MaxOperands = std::max(NumGEP1Operands, NumGEP2Operands);
309   unsigned UnequalOper = 0;
310   while (UnequalOper != MinOperands &&
311          GEP1Ops[UnequalOper] == GEP2Ops[UnequalOper]) {
312     // Advance through the type as we go...
313     ++UnequalOper;
314     if (const CompositeType *CT = dyn_cast<CompositeType>(BasePtr1Ty))
315       BasePtr1Ty = CT->getTypeAtIndex(GEP1Ops[UnequalOper-1]);
316     else {
317       // If all operands equal each other, then the derived pointers must
318       // alias each other...
319       BasePtr1Ty = 0;
320       assert(UnequalOper == NumGEP1Operands && UnequalOper == NumGEP2Operands &&
321              "Ran out of type nesting, but not out of operands?");
322       return MustAlias;
323     }
324   }
325
326   // If we have seen all constant operands, and run out of indexes on one of the
327   // getelementptrs, check to see if the tail of the leftover one is all zeros.
328   // If so, return mustalias.
329   if (UnequalOper == MinOperands && MinOperands != MaxOperands) {
330     if (GEP1Ops.size() < GEP2Ops.size()) std::swap(GEP1Ops, GEP2Ops);
331     
332     bool AllAreZeros = true;
333     for (unsigned i = UnequalOper; i != MaxOperands; ++i)
334       if (!isa<Constant>(GEP1Ops[i]) ||
335           !cast<Constant>(GEP1Ops[i])->isNullValue()) {
336         AllAreZeros = false;
337         break;
338       }
339     if (AllAreZeros) return MustAlias;
340   }
341
342     
343   // So now we know that the indexes derived from the base pointers,
344   // which are known to alias, are different.  We can still determine a
345   // no-alias result if there are differing constant pairs in the index
346   // chain.  For example:
347   //        A[i][0] != A[j][1] iff (&A[0][1]-&A[0][0] >= std::max(G1S, G2S))
348   //
349   unsigned SizeMax = std::max(G1S, G2S);
350   if (SizeMax == ~0U) return MayAlias; // Avoid frivolous work...
351
352   // Scan for the first operand that is constant and unequal in the
353   // two getelemenptrs...
354   unsigned FirstConstantOper = UnequalOper;
355   for (; FirstConstantOper != MinOperands; ++FirstConstantOper) {
356     const Value *G1Oper = GEP1Ops[FirstConstantOper];
357     const Value *G2Oper = GEP2Ops[FirstConstantOper];
358     
359     if (G1Oper != G2Oper &&   // Found non-equal constant indexes...
360         isa<Constant>(G1Oper) && isa<Constant>(G2Oper)) {
361       // Make sure they are comparable (ie, not constant expressions)...  and
362       // make sure the GEP with the smaller leading constant is GEP1.
363       ConstantBool *Compare = *cast<Constant>(G1Oper) > *cast<Constant>(G2Oper);
364       if (Compare) {  // If they are comparable...
365         if (Compare->getValue())
366           std::swap(GEP1Ops, GEP2Ops);  // Make GEP1 < GEP2
367         break;
368       }
369     }
370     BasePtr1Ty = cast<CompositeType>(BasePtr1Ty)->getTypeAtIndex(G1Oper);
371   }
372   
373   // No shared constant operands, and we ran out of common operands.  At this
374   // point, the GEP instructions have run through all of their operands, and we
375   // haven't found evidence that there are any deltas between the GEP's.
376   // However, one GEP may have more operands than the other.  If this is the
377   // case, there may still be hope.  This this now.
378   if (FirstConstantOper == MinOperands) {
379     // Make GEP1Ops be the longer one if there is a longer one.
380     if (GEP1Ops.size() < GEP2Ops.size())
381       std::swap(GEP1Ops, GEP2Ops);
382
383     // Is there anything to check?
384     if (GEP1Ops.size() > MinOperands) {
385       for (unsigned i = FirstConstantOper; i != MaxOperands; ++i)
386         if (isa<Constant>(GEP1Ops[i]) && !isa<ConstantExpr>(GEP1Ops[i]) &&
387             !cast<Constant>(GEP1Ops[i])->isNullValue()) {
388           // Yup, there's a constant in the tail.  Set all variables to
389           // constants in the GEP instruction to make it suiteable for
390           // TargetData::getIndexedOffset.
391           for (i = 0; i != MaxOperands; ++i)
392             if (!isa<Constant>(GEP1Ops[i]) || isa<ConstantExpr>(GEP1Ops[i]))
393               GEP1Ops[i] = Constant::getNullValue(GEP1Ops[i]->getType());
394           // Okay, now get the offset.  This is the relative offset for the full
395           // instruction.
396           const TargetData &TD = getTargetData();
397           int64_t Offset1 = TD.getIndexedOffset(GEPPointerTy, GEP1Ops);
398
399           // Now crop off any constants from the end...
400           GEP1Ops.resize(MinOperands);
401           int64_t Offset2 = TD.getIndexedOffset(GEPPointerTy, GEP1Ops);
402         
403           // If the tail provided a bit enough offset, return noalias!
404           if ((uint64_t)(Offset2-Offset1) >= SizeMax)
405             return NoAlias;
406         }
407     }
408     
409     // Couldn't find anything useful.
410     return MayAlias;
411   }
412
413   // If there are non-equal constants arguments, then we can figure
414   // out a minimum known delta between the two index expressions... at
415   // this point we know that the first constant index of GEP1 is less
416   // than the first constant index of GEP2.
417
418   // Advance BasePtr[12]Ty over this first differing constant operand.
419   BasePtr2Ty = cast<CompositeType>(BasePtr1Ty)->getTypeAtIndex(GEP2Ops[FirstConstantOper]);
420   BasePtr1Ty = cast<CompositeType>(BasePtr1Ty)->getTypeAtIndex(GEP1Ops[FirstConstantOper]);
421   
422   // We are going to be using TargetData::getIndexedOffset to determine the
423   // offset that each of the GEP's is reaching.  To do this, we have to convert
424   // all variable references to constant references.  To do this, we convert the
425   // initial equal sequence of variables into constant zeros to start with.
426   for (unsigned i = 0; i != FirstConstantOper; ++i) {
427     if (!isa<Constant>(GEP1Ops[i]) || isa<ConstantExpr>(GEP1Ops[i]) ||
428         !isa<Constant>(GEP2Ops[i]) || isa<ConstantExpr>(GEP2Ops[i])) {
429       GEP1Ops[i] = Constant::getNullValue(GEP1Ops[i]->getType());
430       GEP2Ops[i] = Constant::getNullValue(GEP2Ops[i]->getType());
431     }
432   }
433
434   // We know that GEP1Ops[FirstConstantOper] & GEP2Ops[FirstConstantOper] are ok
435
436   
437   // Loop over the rest of the operands...
438   for (unsigned i = FirstConstantOper+1; i != MaxOperands; ++i) {
439     const Value *Op1 = i < GEP1Ops.size() ? GEP1Ops[i] : 0;
440     const Value *Op2 = i < GEP2Ops.size() ? GEP2Ops[i] : 0;
441     // If they are equal, use a zero index...
442     if (Op1 == Op2 && BasePtr1Ty == BasePtr2Ty) {
443       if (!isa<Constant>(Op1) || isa<ConstantExpr>(Op1))
444         GEP1Ops[i] = GEP2Ops[i] = Constant::getNullValue(Op1->getType());
445       // Otherwise, just keep the constants we have.
446     } else {
447       if (Op1) {
448         if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
449           // If this is an array index, make sure the array element is in range.
450           if (const ArrayType *AT = dyn_cast<ArrayType>(BasePtr1Ty))
451             if (Op1C->getRawValue() >= AT->getNumElements())
452               return MayAlias;  // Be conservative with out-of-range accesses
453           
454         } else {
455           // GEP1 is known to produce a value less than GEP2.  To be
456           // conservatively correct, we must assume the largest possible
457           // constant is used in this position.  This cannot be the initial
458           // index to the GEP instructions (because we know we have at least one
459           // element before this one with the different constant arguments), so
460           // we know that the current index must be into either a struct or
461           // array.  Because we know it's not constant, this cannot be a
462           // structure index.  Because of this, we can calculate the maximum
463           // value possible.
464           //
465           if (const ArrayType *AT = dyn_cast<ArrayType>(BasePtr1Ty))
466             GEP1Ops[i] = ConstantSInt::get(Type::LongTy,AT->getNumElements()-1);
467         }
468       }
469       
470       if (Op2) {
471         if (const ConstantInt *Op2C = dyn_cast<ConstantInt>(Op2)) {
472           // If this is an array index, make sure the array element is in range.
473           if (const ArrayType *AT = dyn_cast<ArrayType>(BasePtr1Ty))
474             if (Op2C->getRawValue() >= AT->getNumElements())
475               return MayAlias;  // Be conservative with out-of-range accesses
476         } else {  // Conservatively assume the minimum value for this index
477           GEP2Ops[i] = Constant::getNullValue(Op2->getType());
478         }
479       }
480     }
481
482     if (BasePtr1Ty && Op1) {
483       if (const CompositeType *CT = dyn_cast<CompositeType>(BasePtr1Ty))
484         BasePtr1Ty = CT->getTypeAtIndex(GEP1Ops[i]);
485       else
486         BasePtr1Ty = 0;
487     }
488
489     if (BasePtr2Ty && Op2) {
490       if (const CompositeType *CT = dyn_cast<CompositeType>(BasePtr2Ty))
491         BasePtr2Ty = CT->getTypeAtIndex(GEP2Ops[i]);
492       else
493         BasePtr2Ty = 0;
494     }
495   }
496   
497   int64_t Offset1 = getTargetData().getIndexedOffset(GEPPointerTy, GEP1Ops);
498   int64_t Offset2 = getTargetData().getIndexedOffset(GEPPointerTy, GEP2Ops);
499   assert(Offset1 < Offset2 &&"There is at least one different constant here!");
500
501   if ((uint64_t)(Offset2-Offset1) >= SizeMax) {
502     //std::cerr << "Determined that these two GEP's don't alias [" 
503     //          << SizeMax << " bytes]: \n" << *GEP1 << *GEP2;
504     return NoAlias;
505   }
506   return MayAlias;
507 }
508