1 //===- BasicAliasAnalysis.cpp - Local Alias Analysis Impl -----------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
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.
14 //===----------------------------------------------------------------------===//
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"
27 // Make sure that anything that uses AliasAnalysis pulls in this file...
28 void llvm::BasicAAStub() {}
31 struct BasicAliasAnalysis : public ImmutablePass, public AliasAnalysis {
33 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
34 AliasAnalysis::getAnalysisUsage(AU);
37 virtual void initializePass();
39 // alias - This is the only method here that does anything interesting...
41 AliasResult alias(const Value *V1, unsigned V1Size,
42 const Value *V2, unsigned V2Size);
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...
48 CheckGEPInstructions(const Type* BasePtr1Ty, std::vector<Value*> &GEP1Ops,
50 const Type *BasePtr2Ty, std::vector<Value*> &GEP2Ops,
54 // Register this pass...
55 RegisterOpt<BasicAliasAnalysis>
56 X("basicaa", "Basic Alias Analysis (default AA impl)");
58 // Declare that we implement the AliasAnalysis interface
59 RegisterAnalysisGroup<AliasAnalysis, BasicAliasAnalysis, true> Y;
60 } // End of anonymous namespace
62 void BasicAliasAnalysis::initializePass() {
63 InitializeAliasAnalysis(this);
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);
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;
78 // If we are at some type of object... return it.
79 if (hasUniqueAddress(V) || isa<Argument>(V)) return V;
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();
95 static const User *isGEP(const Value *V) {
96 if (isa<GetElementPtrInst>(V) ||
97 (isa<ConstantExpr>(V) &&
98 cast<ConstantExpr>(V)->getOpcode() == Instruction::GetElementPtr))
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. :)
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);
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();
124 // Are we checking for alias of the same value?
125 if (V1 == V2) return MustAlias;
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
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);
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);
141 // Pointing at a discernible object?
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...
152 // If they are two different objects, we know that we have no alias...
153 if (O1 != O2) return NoAlias;
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
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
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.
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;
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()));
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()));
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
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());
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);
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);
221 CheckGEPInstructions(BasePtr1->getType(), GEP1Ops, V1Size,
222 BasePtr2->getType(), GEP2Ops, V2Size);
223 if (GAlias != MayAlias)
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.
232 if (isa<GetElementPtrInst>(V2)) {
234 std::swap(V1Size, V2Size);
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
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;
253 AllZerosFound = false;
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.
262 if (V2Size <= 1 && V1Size <= 1) // Just pointer check?
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...
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);
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)
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,
294 const Type *BasePtr2Ty, std::vector<Value*> &GEP2Ops,
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)
302 const Type *GEPPointerTy = BasePtr1Ty;
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...
314 if (const CompositeType *CT = dyn_cast<CompositeType>(BasePtr1Ty))
315 BasePtr1Ty = CT->getTypeAtIndex(GEP1Ops[UnequalOper-1]);
317 // If all operands equal each other, then the derived pointers must
318 // alias each other...
320 assert(UnequalOper == NumGEP1Operands && UnequalOper == NumGEP2Operands &&
321 "Ran out of type nesting, but not out of operands?");
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);
332 bool AllAreZeros = true;
333 for (unsigned i = UnequalOper; i != MaxOperands; ++i)
334 if (!isa<Constant>(GEP1Ops[i]) ||
335 !cast<Constant>(GEP1Ops[i])->isNullValue()) {
339 if (AllAreZeros) return MustAlias;
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))
349 unsigned SizeMax = std::max(G1S, G2S);
350 if (SizeMax == ~0U) return MayAlias; // Avoid frivolous work...
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];
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
370 BasePtr1Ty = cast<CompositeType>(BasePtr1Ty)->getTypeAtIndex(G1Oper);
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);
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
396 const TargetData &TD = getTargetData();
397 int64_t Offset1 = TD.getIndexedOffset(GEPPointerTy, GEP1Ops);
399 // Now crop off any constants from the end...
400 GEP1Ops.resize(MinOperands);
401 int64_t Offset2 = TD.getIndexedOffset(GEPPointerTy, GEP1Ops);
403 // If the tail provided a bit enough offset, return noalias!
404 if ((uint64_t)(Offset2-Offset1) >= SizeMax)
409 // Couldn't find anything useful.
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.
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]);
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());
434 // We know that GEP1Ops[FirstConstantOper] & GEP2Ops[FirstConstantOper] are ok
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.
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
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
465 if (const ArrayType *AT = dyn_cast<ArrayType>(BasePtr1Ty))
466 GEP1Ops[i] = ConstantSInt::get(Type::LongTy,AT->getNumElements()-1);
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());
482 if (BasePtr1Ty && Op1) {
483 if (const CompositeType *CT = dyn_cast<CompositeType>(BasePtr1Ty))
484 BasePtr1Ty = CT->getTypeAtIndex(GEP1Ops[i]);
489 if (BasePtr2Ty && Op2) {
490 if (const CompositeType *CT = dyn_cast<CompositeType>(BasePtr2Ty))
491 BasePtr2Ty = CT->getTypeAtIndex(GEP2Ops[i]);
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!");
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;