LLVM API Documentation
00001 //===- BasicAliasAnalysis.cpp - Local Alias Analysis Impl -----------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file defines the default implementation of the Alias Analysis interface 00011 // that simply implements a few identities (two different globals cannot alias, 00012 // etc), but otherwise does no analysis. 00013 // 00014 //===----------------------------------------------------------------------===// 00015 00016 #include "llvm/Analysis/AliasAnalysis.h" 00017 #include "llvm/Analysis/CaptureTracking.h" 00018 #include "llvm/Analysis/Passes.h" 00019 #include "llvm/Constants.h" 00020 #include "llvm/DerivedTypes.h" 00021 #include "llvm/Function.h" 00022 #include "llvm/GlobalVariable.h" 00023 #include "llvm/Instructions.h" 00024 #include "llvm/IntrinsicInst.h" 00025 #include "llvm/Pass.h" 00026 #include "llvm/Target/TargetData.h" 00027 #include "llvm/ADT/SmallVector.h" 00028 #include "llvm/ADT/STLExtras.h" 00029 #include "llvm/Support/Compiler.h" 00030 #include "llvm/Support/GetElementPtrTypeIterator.h" 00031 #include "llvm/Support/ManagedStatic.h" 00032 #include <algorithm> 00033 using namespace llvm; 00034 00035 //===----------------------------------------------------------------------===// 00036 // Useful predicates 00037 //===----------------------------------------------------------------------===// 00038 00039 static const User *isGEP(const Value *V) { 00040 if (isa<GetElementPtrInst>(V) || 00041 (isa<ConstantExpr>(V) && 00042 cast<ConstantExpr>(V)->getOpcode() == Instruction::GetElementPtr)) 00043 return cast<User>(V); 00044 return 0; 00045 } 00046 00047 static const Value *GetGEPOperands(const Value *V, 00048 SmallVector<Value*, 16> &GEPOps) { 00049 assert(GEPOps.empty() && "Expect empty list to populate!"); 00050 GEPOps.insert(GEPOps.end(), cast<User>(V)->op_begin()+1, 00051 cast<User>(V)->op_end()); 00052 00053 // Accumulate all of the chained indexes into the operand array 00054 V = cast<User>(V)->getOperand(0); 00055 00056 while (const User *G = isGEP(V)) { 00057 if (!isa<Constant>(GEPOps[0]) || isa<GlobalValue>(GEPOps[0]) || 00058 !cast<Constant>(GEPOps[0])->isNullValue()) 00059 break; // Don't handle folding arbitrary pointer offsets yet... 00060 GEPOps.erase(GEPOps.begin()); // Drop the zero index 00061 GEPOps.insert(GEPOps.begin(), G->op_begin()+1, G->op_end()); 00062 V = G->getOperand(0); 00063 } 00064 return V; 00065 } 00066 00067 /// isKnownNonNull - Return true if we know that the specified value is never 00068 /// null. 00069 static bool isKnownNonNull(const Value *V) { 00070 // Alloca never returns null, malloc might. 00071 if (isa<AllocaInst>(V)) return true; 00072 00073 // A byval argument is never null. 00074 if (const Argument *A = dyn_cast<Argument>(V)) 00075 return A->hasByValAttr(); 00076 00077 // Global values are not null unless extern weak. 00078 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) 00079 return !GV->hasExternalWeakLinkage(); 00080 return false; 00081 } 00082 00083 /// isNonEscapingLocalObject - Return true if the pointer is to a function-local 00084 /// object that never escapes from the function. 00085 static bool isNonEscapingLocalObject(const Value *V) { 00086 // If this is a local allocation, check to see if it escapes. 00087 if (isa<AllocationInst>(V) || isNoAliasCall(V)) 00088 return !PointerMayBeCaptured(V, false); 00089 00090 // If this is an argument that corresponds to a byval or noalias argument, 00091 // then it has not escaped before entering the function. Check if it escapes 00092 // inside the function. 00093 if (const Argument *A = dyn_cast<Argument>(V)) 00094 if (A->hasByValAttr() || A->hasNoAliasAttr()) { 00095 // Don't bother analyzing arguments already known not to escape. 00096 if (A->hasNoCaptureAttr()) 00097 return true; 00098 return !PointerMayBeCaptured(V, false); 00099 } 00100 return false; 00101 } 00102 00103 00104 /// isObjectSmallerThan - Return true if we can prove that the object specified 00105 /// by V is smaller than Size. 00106 static bool isObjectSmallerThan(const Value *V, unsigned Size, 00107 const TargetData &TD) { 00108 const Type *AccessTy; 00109 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) { 00110 AccessTy = GV->getType()->getElementType(); 00111 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(V)) { 00112 if (!AI->isArrayAllocation()) 00113 AccessTy = AI->getType()->getElementType(); 00114 else 00115 return false; 00116 } else if (const Argument *A = dyn_cast<Argument>(V)) { 00117 if (A->hasByValAttr()) 00118 AccessTy = cast<PointerType>(A->getType())->getElementType(); 00119 else 00120 return false; 00121 } else { 00122 return false; 00123 } 00124 00125 if (AccessTy->isSized()) 00126 return TD.getTypePaddedSize(AccessTy) < Size; 00127 return false; 00128 } 00129 00130 //===----------------------------------------------------------------------===// 00131 // NoAA Pass 00132 //===----------------------------------------------------------------------===// 00133 00134 namespace { 00135 /// NoAA - This class implements the -no-aa pass, which always returns "I 00136 /// don't know" for alias queries. NoAA is unlike other alias analysis 00137 /// implementations, in that it does not chain to a previous analysis. As 00138 /// such it doesn't follow many of the rules that other alias analyses must. 00139 /// 00140 struct VISIBILITY_HIDDEN NoAA : public ImmutablePass, public AliasAnalysis { 00141 static char ID; // Class identification, replacement for typeinfo 00142 NoAA() : ImmutablePass(&ID) {} 00143 explicit NoAA(void *PID) : ImmutablePass(PID) { } 00144 00145 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 00146 AU.addRequired<TargetData>(); 00147 } 00148 00149 virtual void initializePass() { 00150 TD = &getAnalysis<TargetData>(); 00151 } 00152 00153 virtual AliasResult alias(const Value *V1, unsigned V1Size, 00154 const Value *V2, unsigned V2Size) { 00155 return MayAlias; 00156 } 00157 00158 virtual ModRefBehavior getModRefBehavior(Function *F, CallSite CS, 00159 std::vector<PointerAccessInfo> *Info) { 00160 return UnknownModRefBehavior; 00161 } 00162 00163 virtual void getArgumentAccesses(Function *F, CallSite CS, 00164 std::vector<PointerAccessInfo> &Info) { 00165 assert(0 && "This method may not be called on this function!"); 00166 } 00167 00168 virtual void getMustAliases(Value *P, std::vector<Value*> &RetVals) { } 00169 virtual bool pointsToConstantMemory(const Value *P) { return false; } 00170 virtual ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size) { 00171 return ModRef; 00172 } 00173 virtual ModRefResult getModRefInfo(CallSite CS1, CallSite CS2) { 00174 return ModRef; 00175 } 00176 virtual bool hasNoModRefInfoForCalls() const { return true; } 00177 00178 virtual void deleteValue(Value *V) {} 00179 virtual void copyValue(Value *From, Value *To) {} 00180 }; 00181 } // End of anonymous namespace 00182 00183 // Register this pass... 00184 char NoAA::ID = 0; 00185 static RegisterPass<NoAA> 00186 U("no-aa", "No Alias Analysis (always returns 'may' alias)", true, true); 00187 00188 // Declare that we implement the AliasAnalysis interface 00189 static RegisterAnalysisGroup<AliasAnalysis> V(U); 00190 00191 ImmutablePass *llvm::createNoAAPass() { return new NoAA(); } 00192 00193 //===----------------------------------------------------------------------===// 00194 // BasicAA Pass 00195 //===----------------------------------------------------------------------===// 00196 00197 namespace { 00198 /// BasicAliasAnalysis - This is the default alias analysis implementation. 00199 /// Because it doesn't chain to a previous alias analysis (like -no-aa), it 00200 /// derives from the NoAA class. 00201 struct VISIBILITY_HIDDEN BasicAliasAnalysis : public NoAA { 00202 static char ID; // Class identification, replacement for typeinfo 00203 BasicAliasAnalysis() : NoAA(&ID) {} 00204 AliasResult alias(const Value *V1, unsigned V1Size, 00205 const Value *V2, unsigned V2Size); 00206 00207 ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size); 00208 ModRefResult getModRefInfo(CallSite CS1, CallSite CS2); 00209 00210 /// hasNoModRefInfoForCalls - We can provide mod/ref information against 00211 /// non-escaping allocations. 00212 virtual bool hasNoModRefInfoForCalls() const { return false; } 00213 00214 /// pointsToConstantMemory - Chase pointers until we find a (constant 00215 /// global) or not. 00216 bool pointsToConstantMemory(const Value *P); 00217 00218 private: 00219 // CheckGEPInstructions - Check two GEP instructions with known 00220 // must-aliasing base pointers. This checks to see if the index expressions 00221 // preclude the pointers from aliasing... 00222 AliasResult 00223 CheckGEPInstructions(const Type* BasePtr1Ty, 00224 Value **GEP1Ops, unsigned NumGEP1Ops, unsigned G1Size, 00225 const Type *BasePtr2Ty, 00226 Value **GEP2Ops, unsigned NumGEP2Ops, unsigned G2Size); 00227 }; 00228 } // End of anonymous namespace 00229 00230 // Register this pass... 00231 char BasicAliasAnalysis::ID = 0; 00232 static RegisterPass<BasicAliasAnalysis> 00233 X("basicaa", "Basic Alias Analysis (default AA impl)", false, true); 00234 00235 // Declare that we implement the AliasAnalysis interface 00236 static RegisterAnalysisGroup<AliasAnalysis, true> Y(X); 00237 00238 ImmutablePass *llvm::createBasicAliasAnalysisPass() { 00239 return new BasicAliasAnalysis(); 00240 } 00241 00242 00243 /// pointsToConstantMemory - Chase pointers until we find a (constant 00244 /// global) or not. 00245 bool BasicAliasAnalysis::pointsToConstantMemory(const Value *P) { 00246 if (const GlobalVariable *GV = 00247 dyn_cast<GlobalVariable>(P->getUnderlyingObject())) 00248 return GV->isConstant(); 00249 return false; 00250 } 00251 00252 // getModRefInfo - Check to see if the specified callsite can clobber the 00253 // specified memory object. Since we only look at local properties of this 00254 // function, we really can't say much about this query. We do, however, use 00255 // simple "address taken" analysis on local objects. 00256 // 00257 AliasAnalysis::ModRefResult 00258 BasicAliasAnalysis::getModRefInfo(CallSite CS, Value *P, unsigned Size) { 00259 if (!isa<Constant>(P)) { 00260 const Value *Object = P->getUnderlyingObject(); 00261 00262 // If this is a tail call and P points to a stack location, we know that 00263 // the tail call cannot access or modify the local stack. 00264 // We cannot exclude byval arguments here; these belong to the caller of 00265 // the current function not to the current function, and a tail callee 00266 // may reference them. 00267 if (isa<AllocaInst>(Object)) 00268 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) 00269 if (CI->isTailCall()) 00270 return NoModRef; 00271 00272 // If the pointer is to a locally allocated object that does not escape, 00273 // then the call can not mod/ref the pointer unless the call takes the 00274 // argument without capturing it. 00275 if (isNonEscapingLocalObject(Object)) { 00276 bool passedAsArg = false; 00277 // TODO: Eventually only check 'nocapture' arguments. 00278 for (CallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end(); 00279 CI != CE; ++CI) 00280 if (isa<PointerType>((*CI)->getType()) && 00281 alias(cast<Value>(CI), ~0U, P, ~0U) != NoAlias) 00282 passedAsArg = true; 00283 00284 if (!passedAsArg) 00285 return NoModRef; 00286 } 00287 } 00288 00289 // The AliasAnalysis base class has some smarts, lets use them. 00290 return AliasAnalysis::getModRefInfo(CS, P, Size); 00291 } 00292 00293 00294 AliasAnalysis::ModRefResult 00295 BasicAliasAnalysis::getModRefInfo(CallSite CS1, CallSite CS2) { 00296 // If CS1 or CS2 are readnone, they don't interact. 00297 ModRefBehavior CS1B = AliasAnalysis::getModRefBehavior(CS1); 00298 if (CS1B == DoesNotAccessMemory) return NoModRef; 00299 00300 ModRefBehavior CS2B = AliasAnalysis::getModRefBehavior(CS2); 00301 if (CS2B == DoesNotAccessMemory) return NoModRef; 00302 00303 // If they both only read from memory, just return ref. 00304 if (CS1B == OnlyReadsMemory && CS2B == OnlyReadsMemory) 00305 return Ref; 00306 00307 // Otherwise, fall back to NoAA (mod+ref). 00308 return NoAA::getModRefInfo(CS1, CS2); 00309 } 00310 00311 00312 // alias - Provide a bunch of ad-hoc rules to disambiguate in common cases, such 00313 // as array references. 00314 // 00315 AliasAnalysis::AliasResult 00316 BasicAliasAnalysis::alias(const Value *V1, unsigned V1Size, 00317 const Value *V2, unsigned V2Size) { 00318 // Strip off any constant expression casts if they exist 00319 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V1)) 00320 if (CE->isCast() && isa<PointerType>(CE->getOperand(0)->getType())) 00321 V1 = CE->getOperand(0); 00322 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V2)) 00323 if (CE->isCast() && isa<PointerType>(CE->getOperand(0)->getType())) 00324 V2 = CE->getOperand(0); 00325 00326 // Are we checking for alias of the same value? 00327 if (V1 == V2) return MustAlias; 00328 00329 if (!isa<PointerType>(V1->getType()) || !isa<PointerType>(V2->getType())) 00330 return NoAlias; // Scalars cannot alias each other 00331 00332 // Strip off cast instructions. Since V1 and V2 are pointers, they must be 00333 // pointer<->pointer bitcasts. 00334 if (const BitCastInst *I = dyn_cast<BitCastInst>(V1)) 00335 return alias(I->getOperand(0), V1Size, V2, V2Size); 00336 if (const BitCastInst *I = dyn_cast<BitCastInst>(V2)) 00337 return alias(V1, V1Size, I->getOperand(0), V2Size); 00338 00339 // Figure out what objects these things are pointing to if we can. 00340 const Value *O1 = V1->getUnderlyingObject(); 00341 const Value *O2 = V2->getUnderlyingObject(); 00342 00343 if (O1 != O2) { 00344 // If V1/V2 point to two different objects we know that we have no alias. 00345 if (isIdentifiedObject(O1) && isIdentifiedObject(O2)) 00346 return NoAlias; 00347 00348 // Arguments can't alias with local allocations or noalias calls. 00349 if ((isa<Argument>(O1) && (isa<AllocationInst>(O2) || isNoAliasCall(O2))) || 00350 (isa<Argument>(O2) && (isa<AllocationInst>(O1) || isNoAliasCall(O1)))) 00351 return NoAlias; 00352 00353 // Most objects can't alias null. 00354 if ((isa<ConstantPointerNull>(V2) && isKnownNonNull(O1)) || 00355 (isa<ConstantPointerNull>(V1) && isKnownNonNull(O2))) 00356 return NoAlias; 00357 } 00358 00359 // If the size of one access is larger than the entire object on the other 00360 // side, then we know such behavior is undefined and can assume no alias. 00361 const TargetData &TD = getTargetData(); 00362 if ((V1Size != ~0U && isObjectSmallerThan(O2, V1Size, TD)) || 00363 (V2Size != ~0U && isObjectSmallerThan(O1, V2Size, TD))) 00364 return NoAlias; 00365 00366 // If one pointer is the result of a call/invoke and the other is a 00367 // non-escaping local object, then we know the object couldn't escape to a 00368 // point where the call could return it. 00369 if ((isa<CallInst>(O1) || isa<InvokeInst>(O1)) && 00370 isNonEscapingLocalObject(O2)) 00371 return NoAlias; 00372 if ((isa<CallInst>(O2) || isa<InvokeInst>(O2)) && 00373 isNonEscapingLocalObject(O1)) 00374 return NoAlias; 00375 00376 // If we have two gep instructions with must-alias'ing base pointers, figure 00377 // out if the indexes to the GEP tell us anything about the derived pointer. 00378 // Note that we also handle chains of getelementptr instructions as well as 00379 // constant expression getelementptrs here. 00380 // 00381 if (isGEP(V1) && isGEP(V2)) { 00382 const User *GEP1 = cast<User>(V1); 00383 const User *GEP2 = cast<User>(V2); 00384 00385 // If V1 and V2 are identical GEPs, just recurse down on both of them. 00386 // This allows us to analyze things like: 00387 // P = gep A, 0, i, 1 00388 // Q = gep B, 0, i, 1 00389 // by just analyzing A and B. This is even safe for variable indices. 00390 if (GEP1->getType() == GEP2->getType() && 00391 GEP1->getNumOperands() == GEP2->getNumOperands() && 00392 GEP1->getOperand(0)->getType() == GEP2->getOperand(0)->getType() && 00393 // All operands are the same, ignoring the base. 00394 std::equal(GEP1->op_begin()+1, GEP1->op_end(), GEP2->op_begin()+1)) 00395 return alias(GEP1->getOperand(0), V1Size, GEP2->getOperand(0), V2Size); 00396 00397 00398 // Drill down into the first non-gep value, to test for must-aliasing of 00399 // the base pointers. 00400 while (isGEP(GEP1->getOperand(0)) && 00401 GEP1->getOperand(1) == 00402 Constant::getNullValue(GEP1->getOperand(1)->getType())) 00403 GEP1 = cast<User>(GEP1->getOperand(0)); 00404 const Value *BasePtr1 = GEP1->getOperand(0); 00405 00406 while (isGEP(GEP2->getOperand(0)) && 00407 GEP2->getOperand(1) == 00408 Constant::getNullValue(GEP2->getOperand(1)->getType())) 00409 GEP2 = cast<User>(GEP2->getOperand(0)); 00410 const Value *BasePtr2 = GEP2->getOperand(0); 00411 00412 // Do the base pointers alias? 00413 AliasResult BaseAlias = alias(BasePtr1, ~0U, BasePtr2, ~0U); 00414 if (BaseAlias == NoAlias) return NoAlias; 00415 if (BaseAlias == MustAlias) { 00416 // If the base pointers alias each other exactly, check to see if we can 00417 // figure out anything about the resultant pointers, to try to prove 00418 // non-aliasing. 00419 00420 // Collect all of the chained GEP operands together into one simple place 00421 SmallVector<Value*, 16> GEP1Ops, GEP2Ops; 00422 BasePtr1 = GetGEPOperands(V1, GEP1Ops); 00423 BasePtr2 = GetGEPOperands(V2, GEP2Ops); 00424 00425 // If GetGEPOperands were able to fold to the same must-aliased pointer, 00426 // do the comparison. 00427 if (BasePtr1 == BasePtr2) { 00428 AliasResult GAlias = 00429 CheckGEPInstructions(BasePtr1->getType(), 00430 &GEP1Ops[0], GEP1Ops.size(), V1Size, 00431 BasePtr2->getType(), 00432 &GEP2Ops[0], GEP2Ops.size(), V2Size); 00433 if (GAlias != MayAlias) 00434 return GAlias; 00435 } 00436 } 00437 } 00438 00439 // Check to see if these two pointers are related by a getelementptr 00440 // instruction. If one pointer is a GEP with a non-zero index of the other 00441 // pointer, we know they cannot alias. 00442 // 00443 if (isGEP(V2)) { 00444 std::swap(V1, V2); 00445 std::swap(V1Size, V2Size); 00446 } 00447 00448 if (V1Size != ~0U && V2Size != ~0U) 00449 if (isGEP(V1)) { 00450 SmallVector<Value*, 16> GEPOperands; 00451 const Value *BasePtr = GetGEPOperands(V1, GEPOperands); 00452 00453 AliasResult R = alias(BasePtr, V1Size, V2, V2Size); 00454 if (R == MustAlias) { 00455 // If there is at least one non-zero constant index, we know they cannot 00456 // alias. 00457 bool ConstantFound = false; 00458 bool AllZerosFound = true; 00459 for (unsigned i = 0, e = GEPOperands.size(); i != e; ++i) 00460 if (const Constant *C = dyn_cast<Constant>(GEPOperands[i])) { 00461 if (!C->isNullValue()) { 00462 ConstantFound = true; 00463 AllZerosFound = false; 00464 break; 00465 } 00466 } else { 00467 AllZerosFound = false; 00468 } 00469 00470 // If we have getelementptr <ptr>, 0, 0, 0, 0, ... and V2 must aliases 00471 // the ptr, the end result is a must alias also. 00472 if (AllZerosFound) 00473 return MustAlias; 00474 00475 if (ConstantFound) { 00476 if (V2Size <= 1 && V1Size <= 1) // Just pointer check? 00477 return NoAlias; 00478 00479 // Otherwise we have to check to see that the distance is more than 00480 // the size of the argument... build an index vector that is equal to 00481 // the arguments provided, except substitute 0's for any variable 00482 // indexes we find... 00483 if (cast<PointerType>( 00484 BasePtr->getType())->getElementType()->isSized()) { 00485 for (unsigned i = 0; i != GEPOperands.size(); ++i) 00486 if (!isa<ConstantInt>(GEPOperands[i])) 00487 GEPOperands[i] = 00488 Constant::getNullValue(GEPOperands[i]->getType()); 00489 int64_t Offset = 00490 getTargetData().getIndexedOffset(BasePtr->getType(), 00491 &GEPOperands[0], 00492 GEPOperands.size()); 00493 00494 if (Offset >= (int64_t)V2Size || Offset <= -(int64_t)V1Size) 00495 return NoAlias; 00496 } 00497 } 00498 } 00499 } 00500 00501 return MayAlias; 00502 } 00503 00504 // This function is used to determine if the indices of two GEP instructions are 00505 // equal. V1 and V2 are the indices. 00506 static bool IndexOperandsEqual(Value *V1, Value *V2) { 00507 if (V1->getType() == V2->getType()) 00508 return V1 == V2; 00509 if (Constant *C1 = dyn_cast<Constant>(V1)) 00510 if (Constant *C2 = dyn_cast<Constant>(V2)) { 00511 // Sign extend the constants to long types, if necessary 00512 if (C1->getType() != Type::Int64Ty) 00513 C1 = ConstantExpr::getSExt(C1, Type::Int64Ty); 00514 if (C2->getType() != Type::Int64Ty) 00515 C2 = ConstantExpr::getSExt(C2, Type::Int64Ty); 00516 return C1 == C2; 00517 } 00518 return false; 00519 } 00520 00521 /// CheckGEPInstructions - Check two GEP instructions with known must-aliasing 00522 /// base pointers. This checks to see if the index expressions preclude the 00523 /// pointers from aliasing... 00524 AliasAnalysis::AliasResult 00525 BasicAliasAnalysis::CheckGEPInstructions( 00526 const Type* BasePtr1Ty, Value **GEP1Ops, unsigned NumGEP1Ops, unsigned G1S, 00527 const Type *BasePtr2Ty, Value **GEP2Ops, unsigned NumGEP2Ops, unsigned G2S) { 00528 // We currently can't handle the case when the base pointers have different 00529 // primitive types. Since this is uncommon anyway, we are happy being 00530 // extremely conservative. 00531 if (BasePtr1Ty != BasePtr2Ty) 00532 return MayAlias; 00533 00534 const PointerType *GEPPointerTy = cast<PointerType>(BasePtr1Ty); 00535 00536 // Find the (possibly empty) initial sequence of equal values... which are not 00537 // necessarily constants. 00538 unsigned NumGEP1Operands = NumGEP1Ops, NumGEP2Operands = NumGEP2Ops; 00539 unsigned MinOperands = std::min(NumGEP1Operands, NumGEP2Operands); 00540 unsigned MaxOperands = std::max(NumGEP1Operands, NumGEP2Operands); 00541 unsigned UnequalOper = 0; 00542 while (UnequalOper != MinOperands && 00543 IndexOperandsEqual(GEP1Ops[UnequalOper], GEP2Ops[UnequalOper])) { 00544 // Advance through the type as we go... 00545 ++UnequalOper; 00546 if (const CompositeType *CT = dyn_cast<CompositeType>(BasePtr1Ty)) 00547 BasePtr1Ty = CT->getTypeAtIndex(GEP1Ops[UnequalOper-1]); 00548 else { 00549 // If all operands equal each other, then the derived pointers must 00550 // alias each other... 00551 BasePtr1Ty = 0; 00552 assert(UnequalOper == NumGEP1Operands && UnequalOper == NumGEP2Operands && 00553 "Ran out of type nesting, but not out of operands?"); 00554 return MustAlias; 00555 } 00556 } 00557 00558 // If we have seen all constant operands, and run out of indexes on one of the 00559 // getelementptrs, check to see if the tail of the leftover one is all zeros. 00560 // If so, return mustalias. 00561 if (UnequalOper == MinOperands) { 00562 if (NumGEP1Ops < NumGEP2Ops) { 00563 std::swap(GEP1Ops, GEP2Ops); 00564 std::swap(NumGEP1Ops, NumGEP2Ops); 00565 } 00566 00567 bool AllAreZeros = true; 00568 for (unsigned i = UnequalOper; i != MaxOperands; ++i) 00569 if (!isa<Constant>(GEP1Ops[i]) || 00570 !cast<Constant>(GEP1Ops[i])->isNullValue()) { 00571 AllAreZeros = false; 00572 break; 00573 } 00574 if (AllAreZeros) return MustAlias; 00575 } 00576 00577 00578 // So now we know that the indexes derived from the base pointers, 00579 // which are known to alias, are different. We can still determine a 00580 // no-alias result if there are differing constant pairs in the index 00581 // chain. For example: 00582 // A[i][0] != A[j][1] iff (&A[0][1]-&A[0][0] >= std::max(G1S, G2S)) 00583 // 00584 // We have to be careful here about array accesses. In particular, consider: 00585 // A[1][0] vs A[0][i] 00586 // In this case, we don't *know* that the array will be accessed in bounds: 00587 // the index could even be negative. Because of this, we have to 00588 // conservatively *give up* and return may alias. We disregard differing 00589 // array subscripts that are followed by a variable index without going 00590 // through a struct. 00591 // 00592 unsigned SizeMax = std::max(G1S, G2S); 00593 if (SizeMax == ~0U) return MayAlias; // Avoid frivolous work. 00594 00595 // Scan for the first operand that is constant and unequal in the 00596 // two getelementptrs... 00597 unsigned FirstConstantOper = UnequalOper; 00598 for (; FirstConstantOper != MinOperands; ++FirstConstantOper) { 00599 const Value *G1Oper = GEP1Ops[FirstConstantOper]; 00600 const Value *G2Oper = GEP2Ops[FirstConstantOper]; 00601 00602 if (G1Oper != G2Oper) // Found non-equal constant indexes... 00603 if (Constant *G1OC = dyn_cast<ConstantInt>(const_cast<Value*>(G1Oper))) 00604 if (Constant *G2OC = dyn_cast<ConstantInt>(const_cast<Value*>(G2Oper))){ 00605 if (G1OC->getType() != G2OC->getType()) { 00606 // Sign extend both operands to long. 00607 if (G1OC->getType() != Type::Int64Ty) 00608 G1OC = ConstantExpr::getSExt(G1OC, Type::Int64Ty); 00609 if (G2OC->getType() != Type::Int64Ty) 00610 G2OC = ConstantExpr::getSExt(G2OC, Type::Int64Ty); 00611 GEP1Ops[FirstConstantOper] = G1OC; 00612 GEP2Ops[FirstConstantOper] = G2OC; 00613 } 00614 00615 if (G1OC != G2OC) { 00616 // Handle the "be careful" case above: if this is an array/vector 00617 // subscript, scan for a subsequent variable array index. 00618 if (isa<SequentialType>(BasePtr1Ty)) { 00619 const Type *NextTy = 00620 cast<SequentialType>(BasePtr1Ty)->getElementType(); 00621 bool isBadCase = false; 00622 00623 for (unsigned Idx = FirstConstantOper+1; 00624 Idx != MinOperands && isa<SequentialType>(NextTy); ++Idx) { 00625 const Value *V1 = GEP1Ops[Idx], *V2 = GEP2Ops[Idx]; 00626 if (!isa<Constant>(V1) || !isa<Constant>(V2)) { 00627 isBadCase = true; 00628 break; 00629 } 00630 NextTy = cast<SequentialType>(NextTy)->getElementType(); 00631 } 00632 00633 if (isBadCase) G1OC = 0; 00634 } 00635 00636 // Make sure they are comparable (ie, not constant expressions), and 00637 // make sure the GEP with the smaller leading constant is GEP1. 00638 if (G1OC) { 00639 Constant *Compare = ConstantExpr::getICmp(ICmpInst::ICMP_SGT, 00640 G1OC, G2OC); 00641 if (ConstantInt *CV = dyn_cast<ConstantInt>(Compare)) { 00642 if (CV->getZExtValue()) { // If they are comparable and G2 > G1 00643 std::swap(GEP1Ops, GEP2Ops); // Make GEP1 < GEP2 00644 std::swap(NumGEP1Ops, NumGEP2Ops); 00645 } 00646 break; 00647 } 00648 } 00649 } 00650 } 00651 BasePtr1Ty = cast<CompositeType>(BasePtr1Ty)->getTypeAtIndex(G1Oper); 00652 } 00653 00654 // No shared constant operands, and we ran out of common operands. At this 00655 // point, the GEP instructions have run through all of their operands, and we 00656 // haven't found evidence that there are any deltas between the GEP's. 00657 // However, one GEP may have more operands than the other. If this is the 00658 // case, there may still be hope. Check this now. 00659 if (FirstConstantOper == MinOperands) { 00660 // Make GEP1Ops be the longer one if there is a longer one. 00661 if (NumGEP1Ops < NumGEP2Ops) { 00662 std::swap(GEP1Ops, GEP2Ops); 00663 std::swap(NumGEP1Ops, NumGEP2Ops); 00664 } 00665 00666 // Is there anything to check? 00667 if (NumGEP1Ops > MinOperands) { 00668 for (unsigned i = FirstConstantOper; i != MaxOperands; ++i) 00669 if (isa<ConstantInt>(GEP1Ops[i]) && 00670 !cast<ConstantInt>(GEP1Ops[i])->isZero()) { 00671 // Yup, there's a constant in the tail. Set all variables to 00672 // constants in the GEP instruction to make it suitable for 00673 // TargetData::getIndexedOffset. 00674 for (i = 0; i != MaxOperands; ++i) 00675 if (!isa<ConstantInt>(GEP1Ops[i])) 00676 GEP1Ops[i] = Constant::getNullValue(GEP1Ops[i]->getType()); 00677 // Okay, now get the offset. This is the relative offset for the full 00678 // instruction. 00679 const TargetData &TD = getTargetData(); 00680 int64_t Offset1 = TD.getIndexedOffset(GEPPointerTy, GEP1Ops, 00681 NumGEP1Ops); 00682 00683 // Now check without any constants at the end. 00684 int64_t Offset2 = TD.getIndexedOffset(GEPPointerTy, GEP1Ops, 00685 MinOperands); 00686 00687 // Make sure we compare the absolute difference. 00688 if (Offset1 > Offset2) 00689 std::swap(Offset1, Offset2); 00690 00691 // If the tail provided a bit enough offset, return noalias! 00692 if ((uint64_t)(Offset2-Offset1) >= SizeMax) 00693 return NoAlias; 00694 // Otherwise break - we don't look for another constant in the tail. 00695 break; 00696 } 00697 } 00698 00699 // Couldn't find anything useful. 00700 return MayAlias; 00701 } 00702 00703 // If there are non-equal constants arguments, then we can figure 00704 // out a minimum known delta between the two index expressions... at 00705 // this point we know that the first constant index of GEP1 is less 00706 // than the first constant index of GEP2. 00707 00708 // Advance BasePtr[12]Ty over this first differing constant operand. 00709 BasePtr2Ty = cast<CompositeType>(BasePtr1Ty)-> 00710 getTypeAtIndex(GEP2Ops[FirstConstantOper]); 00711 BasePtr1Ty = cast<CompositeType>(BasePtr1Ty)-> 00712 getTypeAtIndex(GEP1Ops[FirstConstantOper]); 00713 00714 // We are going to be using TargetData::getIndexedOffset to determine the 00715 // offset that each of the GEP's is reaching. To do this, we have to convert 00716 // all variable references to constant references. To do this, we convert the 00717 // initial sequence of array subscripts into constant zeros to start with. 00718 const Type *ZeroIdxTy = GEPPointerTy; 00719 for (unsigned i = 0; i != FirstConstantOper; ++i) { 00720 if (!isa<StructType>(ZeroIdxTy)) 00721 GEP1Ops[i] = GEP2Ops[i] = Constant::getNullValue(Type::Int32Ty); 00722 00723 if (const CompositeType *CT = dyn_cast<CompositeType>(ZeroIdxTy)) 00724 ZeroIdxTy = CT->getTypeAtIndex(GEP1Ops[i]); 00725 } 00726 00727 // We know that GEP1Ops[FirstConstantOper] & GEP2Ops[FirstConstantOper] are ok 00728 00729 // Loop over the rest of the operands... 00730 for (unsigned i = FirstConstantOper+1; i != MaxOperands; ++i) { 00731 const Value *Op1 = i < NumGEP1Ops ? GEP1Ops[i] : 0; 00732 const Value *Op2 = i < NumGEP2Ops ? GEP2Ops[i] : 0; 00733 // If they are equal, use a zero index... 00734 if (Op1 == Op2 && BasePtr1Ty == BasePtr2Ty) { 00735 if (!isa<ConstantInt>(Op1)) 00736 GEP1Ops[i] = GEP2Ops[i] = Constant::getNullValue(Op1->getType()); 00737 // Otherwise, just keep the constants we have. 00738 } else { 00739 if (Op1) { 00740 if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) { 00741 // If this is an array index, make sure the array element is in range. 00742 if (const ArrayType *AT = dyn_cast<ArrayType>(BasePtr1Ty)) { 00743 if (Op1C->getZExtValue() >= AT->getNumElements()) 00744 return MayAlias; // Be conservative with out-of-range accesses 00745 } else if (const VectorType *VT = dyn_cast<VectorType>(BasePtr1Ty)) { 00746 if (Op1C->getZExtValue() >= VT->getNumElements()) 00747 return MayAlias; // Be conservative with out-of-range accesses 00748 } 00749 00750 } else { 00751 // GEP1 is known to produce a value less than GEP2. To be 00752 // conservatively correct, we must assume the largest possible 00753 // constant is used in this position. This cannot be the initial 00754 // index to the GEP instructions (because we know we have at least one 00755 // element before this one with the different constant arguments), so 00756 // we know that the current index must be into either a struct or 00757 // array. Because we know it's not constant, this cannot be a 00758 // structure index. Because of this, we can calculate the maximum 00759 // value possible. 00760 // 00761 if (const ArrayType *AT = dyn_cast<ArrayType>(BasePtr1Ty)) 00762 GEP1Ops[i] = ConstantInt::get(Type::Int64Ty,AT->getNumElements()-1); 00763 else if (const VectorType *VT = dyn_cast<VectorType>(BasePtr1Ty)) 00764 GEP1Ops[i] = ConstantInt::get(Type::Int64Ty,VT->getNumElements()-1); 00765 } 00766 } 00767 00768 if (Op2) { 00769 if (const ConstantInt *Op2C = dyn_cast<ConstantInt>(Op2)) { 00770 // If this is an array index, make sure the array element is in range. 00771 if (const ArrayType *AT = dyn_cast<ArrayType>(BasePtr2Ty)) { 00772 if (Op2C->getZExtValue() >= AT->getNumElements()) 00773 return MayAlias; // Be conservative with out-of-range accesses 00774 } else if (const VectorType *VT = dyn_cast<VectorType>(BasePtr2Ty)) { 00775 if (Op2C->getZExtValue() >= VT->getNumElements()) 00776 return MayAlias; // Be conservative with out-of-range accesses 00777 } 00778 } else { // Conservatively assume the minimum value for this index 00779 GEP2Ops[i] = Constant::getNullValue(Op2->getType()); 00780 } 00781 } 00782 } 00783 00784 if (BasePtr1Ty && Op1) { 00785 if (const CompositeType *CT = dyn_cast<CompositeType>(BasePtr1Ty)) 00786 BasePtr1Ty = CT->getTypeAtIndex(GEP1Ops[i]); 00787 else 00788 BasePtr1Ty = 0; 00789 } 00790 00791 if (BasePtr2Ty && Op2) { 00792 if (const CompositeType *CT = dyn_cast<CompositeType>(BasePtr2Ty)) 00793 BasePtr2Ty = CT->getTypeAtIndex(GEP2Ops[i]); 00794 else 00795 BasePtr2Ty = 0; 00796 } 00797 } 00798 00799 if (GEPPointerTy->getElementType()->isSized()) { 00800 int64_t Offset1 = 00801 getTargetData().getIndexedOffset(GEPPointerTy, GEP1Ops, NumGEP1Ops); 00802 int64_t Offset2 = 00803 getTargetData().getIndexedOffset(GEPPointerTy, GEP2Ops, NumGEP2Ops); 00804 assert(Offset1 != Offset2 && 00805 "There is at least one different constant here!"); 00806 00807 // Make sure we compare the absolute difference. 00808 if (Offset1 > Offset2) 00809 std::swap(Offset1, Offset2); 00810 00811 if ((uint64_t)(Offset2-Offset1) >= SizeMax) { 00812 //cerr << "Determined that these two GEP's don't alias [" 00813 // << SizeMax << " bytes]: \n" << *GEP1 << *GEP2; 00814 return NoAlias; 00815 } 00816 } 00817 return MayAlias; 00818 } 00819 00820 // Make sure that anything that uses AliasAnalysis pulls in this file... 00821 DEFINING_FILE_FOR(BasicAliasAnalysis)