BasicAliasAnalysis.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846
  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. #include "llvm/Analysis/AliasAnalysis.h"
  16. #include "llvm/Analysis/CaptureTracking.h"
  17. #include "llvm/Analysis/Passes.h"
  18. #include "llvm/Constants.h"
  19. #include "llvm/DerivedTypes.h"
  20. #include "llvm/Function.h"
  21. #include "llvm/GlobalVariable.h"
  22. #include "llvm/Instructions.h"
  23. #include "llvm/IntrinsicInst.h"
  24. #include "llvm/LLVMContext.h"
  25. #include "llvm/Operator.h"
  26. #include "llvm/Pass.h"
  27. #include "llvm/Target/TargetData.h"
  28. #include "llvm/ADT/SmallVector.h"
  29. #include "llvm/ADT/STLExtras.h"
  30. #include "llvm/Support/Compiler.h"
  31. #include "llvm/Support/ErrorHandling.h"
  32. #include "llvm/Support/GetElementPtrTypeIterator.h"
  33. #include <algorithm>
  34. using namespace llvm;
  35. //===----------------------------------------------------------------------===//
  36. // Useful predicates
  37. //===----------------------------------------------------------------------===//
  38. static const GEPOperator *isGEP(const Value *V) {
  39. return dyn_cast<GEPOperator>(V);
  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. // Accumulate all of the chained indexes into the operand array
  47. V = cast<User>(V)->getOperand(0);
  48. while (const User *G = isGEP(V)) {
  49. if (!isa<Constant>(GEPOps[0]) || isa<GlobalValue>(GEPOps[0]) ||
  50. !cast<Constant>(GEPOps[0])->isNullValue())
  51. break; // Don't handle folding arbitrary pointer offsets yet...
  52. GEPOps.erase(GEPOps.begin()); // Drop the zero index
  53. GEPOps.insert(GEPOps.begin(), G->op_begin()+1, G->op_end());
  54. V = G->getOperand(0);
  55. }
  56. return V;
  57. }
  58. /// isKnownNonNull - Return true if we know that the specified value is never
  59. /// null.
  60. static bool isKnownNonNull(const Value *V) {
  61. // Alloca never returns null, malloc might.
  62. if (isa<AllocaInst>(V)) return true;
  63. // A byval argument is never null.
  64. if (const Argument *A = dyn_cast<Argument>(V))
  65. return A->hasByValAttr();
  66. // Global values are not null unless extern weak.
  67. if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
  68. return !GV->hasExternalWeakLinkage();
  69. return false;
  70. }
  71. /// isNonEscapingLocalObject - Return true if the pointer is to a function-local
  72. /// object that never escapes from the function.
  73. static bool isNonEscapingLocalObject(const Value *V) {
  74. // If this is a local allocation, check to see if it escapes.
  75. if (isa<AllocationInst>(V) || isNoAliasCall(V))
  76. return !PointerMayBeCaptured(V, false);
  77. // If this is an argument that corresponds to a byval or noalias argument,
  78. // then it has not escaped before entering the function. Check if it escapes
  79. // inside the function.
  80. if (const Argument *A = dyn_cast<Argument>(V))
  81. if (A->hasByValAttr() || A->hasNoAliasAttr()) {
  82. // Don't bother analyzing arguments already known not to escape.
  83. if (A->hasNoCaptureAttr())
  84. return true;
  85. return !PointerMayBeCaptured(V, false);
  86. }
  87. return false;
  88. }
  89. /// isObjectSmallerThan - Return true if we can prove that the object specified
  90. /// by V is smaller than Size.
  91. static bool isObjectSmallerThan(const Value *V, unsigned Size,
  92. const TargetData &TD) {
  93. const Type *AccessTy;
  94. if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
  95. AccessTy = GV->getType()->getElementType();
  96. } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
  97. if (!AI->isArrayAllocation())
  98. AccessTy = AI->getType()->getElementType();
  99. else
  100. return false;
  101. } else if (const Argument *A = dyn_cast<Argument>(V)) {
  102. if (A->hasByValAttr())
  103. AccessTy = cast<PointerType>(A->getType())->getElementType();
  104. else
  105. return false;
  106. } else {
  107. return false;
  108. }
  109. if (AccessTy->isSized())
  110. return TD.getTypeAllocSize(AccessTy) < Size;
  111. return false;
  112. }
  113. //===----------------------------------------------------------------------===//
  114. // NoAA Pass
  115. //===----------------------------------------------------------------------===//
  116. namespace {
  117. /// NoAA - This class implements the -no-aa pass, which always returns "I
  118. /// don't know" for alias queries. NoAA is unlike other alias analysis
  119. /// implementations, in that it does not chain to a previous analysis. As
  120. /// such it doesn't follow many of the rules that other alias analyses must.
  121. ///
  122. struct VISIBILITY_HIDDEN NoAA : public ImmutablePass, public AliasAnalysis {
  123. static char ID; // Class identification, replacement for typeinfo
  124. NoAA() : ImmutablePass(&ID) {}
  125. explicit NoAA(void *PID) : ImmutablePass(PID) { }
  126. virtual void getAnalysisUsage(AnalysisUsage &AU) const {
  127. }
  128. virtual void initializePass() {
  129. TD = getAnalysisIfAvailable<TargetData>();
  130. }
  131. virtual AliasResult alias(const Value *V1, unsigned V1Size,
  132. const Value *V2, unsigned V2Size) {
  133. return MayAlias;
  134. }
  135. virtual void getArgumentAccesses(Function *F, CallSite CS,
  136. std::vector<PointerAccessInfo> &Info) {
  137. llvm_unreachable("This method may not be called on this function!");
  138. }
  139. virtual void getMustAliases(Value *P, std::vector<Value*> &RetVals) { }
  140. virtual bool pointsToConstantMemory(const Value *P) { return false; }
  141. virtual ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size) {
  142. return ModRef;
  143. }
  144. virtual ModRefResult getModRefInfo(CallSite CS1, CallSite CS2) {
  145. return ModRef;
  146. }
  147. virtual bool hasNoModRefInfoForCalls() const { return true; }
  148. virtual void deleteValue(Value *V) {}
  149. virtual void copyValue(Value *From, Value *To) {}
  150. };
  151. } // End of anonymous namespace
  152. // Register this pass...
  153. char NoAA::ID = 0;
  154. static RegisterPass<NoAA>
  155. U("no-aa", "No Alias Analysis (always returns 'may' alias)", true, true);
  156. // Declare that we implement the AliasAnalysis interface
  157. static RegisterAnalysisGroup<AliasAnalysis> V(U);
  158. ImmutablePass *llvm::createNoAAPass() { return new NoAA(); }
  159. //===----------------------------------------------------------------------===//
  160. // BasicAA Pass
  161. //===----------------------------------------------------------------------===//
  162. namespace {
  163. /// BasicAliasAnalysis - This is the default alias analysis implementation.
  164. /// Because it doesn't chain to a previous alias analysis (like -no-aa), it
  165. /// derives from the NoAA class.
  166. struct VISIBILITY_HIDDEN BasicAliasAnalysis : public NoAA {
  167. static char ID; // Class identification, replacement for typeinfo
  168. BasicAliasAnalysis() : NoAA(&ID) {}
  169. AliasResult alias(const Value *V1, unsigned V1Size,
  170. const Value *V2, unsigned V2Size);
  171. ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
  172. ModRefResult getModRefInfo(CallSite CS1, CallSite CS2);
  173. /// hasNoModRefInfoForCalls - We can provide mod/ref information against
  174. /// non-escaping allocations.
  175. virtual bool hasNoModRefInfoForCalls() const { return false; }
  176. /// pointsToConstantMemory - Chase pointers until we find a (constant
  177. /// global) or not.
  178. bool pointsToConstantMemory(const Value *P);
  179. private:
  180. // CheckGEPInstructions - Check two GEP instructions with known
  181. // must-aliasing base pointers. This checks to see if the index expressions
  182. // preclude the pointers from aliasing...
  183. AliasResult
  184. CheckGEPInstructions(const Type* BasePtr1Ty,
  185. Value **GEP1Ops, unsigned NumGEP1Ops, unsigned G1Size,
  186. const Type *BasePtr2Ty,
  187. Value **GEP2Ops, unsigned NumGEP2Ops, unsigned G2Size);
  188. };
  189. } // End of anonymous namespace
  190. // Register this pass...
  191. char BasicAliasAnalysis::ID = 0;
  192. static RegisterPass<BasicAliasAnalysis>
  193. X("basicaa", "Basic Alias Analysis (default AA impl)", false, true);
  194. // Declare that we implement the AliasAnalysis interface
  195. static RegisterAnalysisGroup<AliasAnalysis, true> Y(X);
  196. ImmutablePass *llvm::createBasicAliasAnalysisPass() {
  197. return new BasicAliasAnalysis();
  198. }
  199. /// pointsToConstantMemory - Chase pointers until we find a (constant
  200. /// global) or not.
  201. bool BasicAliasAnalysis::pointsToConstantMemory(const Value *P) {
  202. if (const GlobalVariable *GV =
  203. dyn_cast<GlobalVariable>(P->getUnderlyingObject()))
  204. return GV->isConstant();
  205. return false;
  206. }
  207. // getModRefInfo - Check to see if the specified callsite can clobber the
  208. // specified memory object. Since we only look at local properties of this
  209. // function, we really can't say much about this query. We do, however, use
  210. // simple "address taken" analysis on local objects.
  211. //
  212. AliasAnalysis::ModRefResult
  213. BasicAliasAnalysis::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
  214. if (!isa<Constant>(P)) {
  215. const Value *Object = P->getUnderlyingObject();
  216. // If this is a tail call and P points to a stack location, we know that
  217. // the tail call cannot access or modify the local stack.
  218. // We cannot exclude byval arguments here; these belong to the caller of
  219. // the current function not to the current function, and a tail callee
  220. // may reference them.
  221. if (isa<AllocaInst>(Object))
  222. if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction()))
  223. if (CI->isTailCall())
  224. return NoModRef;
  225. // If the pointer is to a locally allocated object that does not escape,
  226. // then the call can not mod/ref the pointer unless the call takes the
  227. // argument without capturing it.
  228. if (isNonEscapingLocalObject(Object) && CS.getInstruction() != Object) {
  229. bool passedAsArg = false;
  230. // TODO: Eventually only check 'nocapture' arguments.
  231. for (CallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
  232. CI != CE; ++CI)
  233. if (isa<PointerType>((*CI)->getType()) &&
  234. alias(cast<Value>(CI), ~0U, P, ~0U) != NoAlias)
  235. passedAsArg = true;
  236. if (!passedAsArg)
  237. return NoModRef;
  238. }
  239. }
  240. // The AliasAnalysis base class has some smarts, lets use them.
  241. return AliasAnalysis::getModRefInfo(CS, P, Size);
  242. }
  243. AliasAnalysis::ModRefResult
  244. BasicAliasAnalysis::getModRefInfo(CallSite CS1, CallSite CS2) {
  245. // If CS1 or CS2 are readnone, they don't interact.
  246. ModRefBehavior CS1B = AliasAnalysis::getModRefBehavior(CS1);
  247. if (CS1B == DoesNotAccessMemory) return NoModRef;
  248. ModRefBehavior CS2B = AliasAnalysis::getModRefBehavior(CS2);
  249. if (CS2B == DoesNotAccessMemory) return NoModRef;
  250. // If they both only read from memory, just return ref.
  251. if (CS1B == OnlyReadsMemory && CS2B == OnlyReadsMemory)
  252. return Ref;
  253. // Otherwise, fall back to NoAA (mod+ref).
  254. return NoAA::getModRefInfo(CS1, CS2);
  255. }
  256. // alias - Provide a bunch of ad-hoc rules to disambiguate in common cases, such
  257. // as array references.
  258. //
  259. AliasAnalysis::AliasResult
  260. BasicAliasAnalysis::alias(const Value *V1, unsigned V1Size,
  261. const Value *V2, unsigned V2Size) {
  262. // Strip off any constant expression casts if they exist
  263. if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V1))
  264. if (CE->isCast() && isa<PointerType>(CE->getOperand(0)->getType()))
  265. V1 = CE->getOperand(0);
  266. if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V2))
  267. if (CE->isCast() && isa<PointerType>(CE->getOperand(0)->getType()))
  268. V2 = CE->getOperand(0);
  269. // Are we checking for alias of the same value?
  270. if (V1 == V2) return MustAlias;
  271. if (!isa<PointerType>(V1->getType()) || !isa<PointerType>(V2->getType()))
  272. return NoAlias; // Scalars cannot alias each other
  273. // Strip off cast instructions. Since V1 and V2 are pointers, they must be
  274. // pointer<->pointer bitcasts.
  275. if (const BitCastInst *I = dyn_cast<BitCastInst>(V1))
  276. return alias(I->getOperand(0), V1Size, V2, V2Size);
  277. if (const BitCastInst *I = dyn_cast<BitCastInst>(V2))
  278. return alias(V1, V1Size, I->getOperand(0), V2Size);
  279. // Figure out what objects these things are pointing to if we can.
  280. const Value *O1 = V1->getUnderlyingObject();
  281. const Value *O2 = V2->getUnderlyingObject();
  282. if (O1 != O2) {
  283. // If V1/V2 point to two different objects we know that we have no alias.
  284. if (isIdentifiedObject(O1) && isIdentifiedObject(O2))
  285. return NoAlias;
  286. // Arguments can't alias with local allocations or noalias calls.
  287. if ((isa<Argument>(O1) && (isa<AllocationInst>(O2) || isNoAliasCall(O2))) ||
  288. (isa<Argument>(O2) && (isa<AllocationInst>(O1) || isNoAliasCall(O1))))
  289. return NoAlias;
  290. // Most objects can't alias null.
  291. if ((isa<ConstantPointerNull>(V2) && isKnownNonNull(O1)) ||
  292. (isa<ConstantPointerNull>(V1) && isKnownNonNull(O2)))
  293. return NoAlias;
  294. }
  295. // If the size of one access is larger than the entire object on the other
  296. // side, then we know such behavior is undefined and can assume no alias.
  297. if (TD)
  298. if ((V1Size != ~0U && isObjectSmallerThan(O2, V1Size, *TD)) ||
  299. (V2Size != ~0U && isObjectSmallerThan(O1, V2Size, *TD)))
  300. return NoAlias;
  301. // If one pointer is the result of a call/invoke and the other is a
  302. // non-escaping local object, then we know the object couldn't escape to a
  303. // point where the call could return it.
  304. if ((isa<CallInst>(O1) || isa<InvokeInst>(O1)) &&
  305. isNonEscapingLocalObject(O2) && O1 != O2)
  306. return NoAlias;
  307. if ((isa<CallInst>(O2) || isa<InvokeInst>(O2)) &&
  308. isNonEscapingLocalObject(O1) && O1 != O2)
  309. return NoAlias;
  310. // If we have two gep instructions with must-alias'ing base pointers, figure
  311. // out if the indexes to the GEP tell us anything about the derived pointer.
  312. // Note that we also handle chains of getelementptr instructions as well as
  313. // constant expression getelementptrs here.
  314. //
  315. if (isGEP(V1) && isGEP(V2)) {
  316. const User *GEP1 = cast<User>(V1);
  317. const User *GEP2 = cast<User>(V2);
  318. // If V1 and V2 are identical GEPs, just recurse down on both of them.
  319. // This allows us to analyze things like:
  320. // P = gep A, 0, i, 1
  321. // Q = gep B, 0, i, 1
  322. // by just analyzing A and B. This is even safe for variable indices.
  323. if (GEP1->getType() == GEP2->getType() &&
  324. GEP1->getNumOperands() == GEP2->getNumOperands() &&
  325. GEP1->getOperand(0)->getType() == GEP2->getOperand(0)->getType() &&
  326. // All operands are the same, ignoring the base.
  327. std::equal(GEP1->op_begin()+1, GEP1->op_end(), GEP2->op_begin()+1))
  328. return alias(GEP1->getOperand(0), V1Size, GEP2->getOperand(0), V2Size);
  329. // Drill down into the first non-gep value, to test for must-aliasing of
  330. // the base pointers.
  331. while (isGEP(GEP1->getOperand(0)) &&
  332. GEP1->getOperand(1) ==
  333. Constant::getNullValue(GEP1->getOperand(1)->getType()))
  334. GEP1 = cast<User>(GEP1->getOperand(0));
  335. const Value *BasePtr1 = GEP1->getOperand(0);
  336. while (isGEP(GEP2->getOperand(0)) &&
  337. GEP2->getOperand(1) ==
  338. Constant::getNullValue(GEP2->getOperand(1)->getType()))
  339. GEP2 = cast<User>(GEP2->getOperand(0));
  340. const Value *BasePtr2 = GEP2->getOperand(0);
  341. // Do the base pointers alias?
  342. AliasResult BaseAlias = alias(BasePtr1, ~0U, BasePtr2, ~0U);
  343. if (BaseAlias == NoAlias) return NoAlias;
  344. if (BaseAlias == MustAlias) {
  345. // If the base pointers alias each other exactly, check to see if we can
  346. // figure out anything about the resultant pointers, to try to prove
  347. // non-aliasing.
  348. // Collect all of the chained GEP operands together into one simple place
  349. SmallVector<Value*, 16> GEP1Ops, GEP2Ops;
  350. BasePtr1 = GetGEPOperands(V1, GEP1Ops);
  351. BasePtr2 = GetGEPOperands(V2, GEP2Ops);
  352. // If GetGEPOperands were able to fold to the same must-aliased pointer,
  353. // do the comparison.
  354. if (BasePtr1 == BasePtr2) {
  355. AliasResult GAlias =
  356. CheckGEPInstructions(BasePtr1->getType(),
  357. &GEP1Ops[0], GEP1Ops.size(), V1Size,
  358. BasePtr2->getType(),
  359. &GEP2Ops[0], GEP2Ops.size(), V2Size);
  360. if (GAlias != MayAlias)
  361. return GAlias;
  362. }
  363. }
  364. }
  365. // Check to see if these two pointers are related by a getelementptr
  366. // instruction. If one pointer is a GEP with a non-zero index of the other
  367. // pointer, we know they cannot alias.
  368. //
  369. if (isGEP(V2)) {
  370. std::swap(V1, V2);
  371. std::swap(V1Size, V2Size);
  372. }
  373. if (V1Size != ~0U && V2Size != ~0U)
  374. if (isGEP(V1)) {
  375. SmallVector<Value*, 16> GEPOperands;
  376. const Value *BasePtr = GetGEPOperands(V1, GEPOperands);
  377. AliasResult R = alias(BasePtr, V1Size, V2, V2Size);
  378. if (R == MustAlias) {
  379. // If there is at least one non-zero constant index, we know they cannot
  380. // alias.
  381. bool ConstantFound = false;
  382. bool AllZerosFound = true;
  383. for (unsigned i = 0, e = GEPOperands.size(); i != e; ++i)
  384. if (const Constant *C = dyn_cast<Constant>(GEPOperands[i])) {
  385. if (!C->isNullValue()) {
  386. ConstantFound = true;
  387. AllZerosFound = false;
  388. break;
  389. }
  390. } else {
  391. AllZerosFound = false;
  392. }
  393. // If we have getelementptr <ptr>, 0, 0, 0, 0, ... and V2 must aliases
  394. // the ptr, the end result is a must alias also.
  395. if (AllZerosFound)
  396. return MustAlias;
  397. if (ConstantFound) {
  398. if (V2Size <= 1 && V1Size <= 1) // Just pointer check?
  399. return NoAlias;
  400. // Otherwise we have to check to see that the distance is more than
  401. // the size of the argument... build an index vector that is equal to
  402. // the arguments provided, except substitute 0's for any variable
  403. // indexes we find...
  404. if (TD && cast<PointerType>(
  405. BasePtr->getType())->getElementType()->isSized()) {
  406. for (unsigned i = 0; i != GEPOperands.size(); ++i)
  407. if (!isa<ConstantInt>(GEPOperands[i]))
  408. GEPOperands[i] =
  409. Constant::getNullValue(GEPOperands[i]->getType());
  410. int64_t Offset =
  411. TD->getIndexedOffset(BasePtr->getType(),
  412. &GEPOperands[0],
  413. GEPOperands.size());
  414. if (Offset >= (int64_t)V2Size || Offset <= -(int64_t)V1Size)
  415. return NoAlias;
  416. }
  417. }
  418. }
  419. }
  420. return MayAlias;
  421. }
  422. // This function is used to determine if the indices of two GEP instructions are
  423. // equal. V1 and V2 are the indices.
  424. static bool IndexOperandsEqual(Value *V1, Value *V2, LLVMContext &Context) {
  425. if (V1->getType() == V2->getType())
  426. return V1 == V2;
  427. if (Constant *C1 = dyn_cast<Constant>(V1))
  428. if (Constant *C2 = dyn_cast<Constant>(V2)) {
  429. // Sign extend the constants to long types, if necessary
  430. if (C1->getType() != Type::getInt64Ty(Context))
  431. C1 = ConstantExpr::getSExt(C1, Type::getInt64Ty(Context));
  432. if (C2->getType() != Type::getInt64Ty(Context))
  433. C2 = ConstantExpr::getSExt(C2, Type::getInt64Ty(Context));
  434. return C1 == C2;
  435. }
  436. return false;
  437. }
  438. /// CheckGEPInstructions - Check two GEP instructions with known must-aliasing
  439. /// base pointers. This checks to see if the index expressions preclude the
  440. /// pointers from aliasing...
  441. AliasAnalysis::AliasResult
  442. BasicAliasAnalysis::CheckGEPInstructions(
  443. const Type* BasePtr1Ty, Value **GEP1Ops, unsigned NumGEP1Ops, unsigned G1S,
  444. const Type *BasePtr2Ty, Value **GEP2Ops, unsigned NumGEP2Ops, unsigned G2S) {
  445. // We currently can't handle the case when the base pointers have different
  446. // primitive types. Since this is uncommon anyway, we are happy being
  447. // extremely conservative.
  448. if (BasePtr1Ty != BasePtr2Ty)
  449. return MayAlias;
  450. const PointerType *GEPPointerTy = cast<PointerType>(BasePtr1Ty);
  451. LLVMContext &Context = GEPPointerTy->getContext();
  452. // Find the (possibly empty) initial sequence of equal values... which are not
  453. // necessarily constants.
  454. unsigned NumGEP1Operands = NumGEP1Ops, NumGEP2Operands = NumGEP2Ops;
  455. unsigned MinOperands = std::min(NumGEP1Operands, NumGEP2Operands);
  456. unsigned MaxOperands = std::max(NumGEP1Operands, NumGEP2Operands);
  457. unsigned UnequalOper = 0;
  458. while (UnequalOper != MinOperands &&
  459. IndexOperandsEqual(GEP1Ops[UnequalOper], GEP2Ops[UnequalOper],
  460. Context)) {
  461. // Advance through the type as we go...
  462. ++UnequalOper;
  463. if (const CompositeType *CT = dyn_cast<CompositeType>(BasePtr1Ty))
  464. BasePtr1Ty = CT->getTypeAtIndex(GEP1Ops[UnequalOper-1]);
  465. else {
  466. // If all operands equal each other, then the derived pointers must
  467. // alias each other...
  468. BasePtr1Ty = 0;
  469. assert(UnequalOper == NumGEP1Operands && UnequalOper == NumGEP2Operands &&
  470. "Ran out of type nesting, but not out of operands?");
  471. return MustAlias;
  472. }
  473. }
  474. // If we have seen all constant operands, and run out of indexes on one of the
  475. // getelementptrs, check to see if the tail of the leftover one is all zeros.
  476. // If so, return mustalias.
  477. if (UnequalOper == MinOperands) {
  478. if (NumGEP1Ops < NumGEP2Ops) {
  479. std::swap(GEP1Ops, GEP2Ops);
  480. std::swap(NumGEP1Ops, NumGEP2Ops);
  481. }
  482. bool AllAreZeros = true;
  483. for (unsigned i = UnequalOper; i != MaxOperands; ++i)
  484. if (!isa<Constant>(GEP1Ops[i]) ||
  485. !cast<Constant>(GEP1Ops[i])->isNullValue()) {
  486. AllAreZeros = false;
  487. break;
  488. }
  489. if (AllAreZeros) return MustAlias;
  490. }
  491. // So now we know that the indexes derived from the base pointers,
  492. // which are known to alias, are different. We can still determine a
  493. // no-alias result if there are differing constant pairs in the index
  494. // chain. For example:
  495. // A[i][0] != A[j][1] iff (&A[0][1]-&A[0][0] >= std::max(G1S, G2S))
  496. //
  497. // We have to be careful here about array accesses. In particular, consider:
  498. // A[1][0] vs A[0][i]
  499. // In this case, we don't *know* that the array will be accessed in bounds:
  500. // the index could even be negative. Because of this, we have to
  501. // conservatively *give up* and return may alias. We disregard differing
  502. // array subscripts that are followed by a variable index without going
  503. // through a struct.
  504. //
  505. unsigned SizeMax = std::max(G1S, G2S);
  506. if (SizeMax == ~0U) return MayAlias; // Avoid frivolous work.
  507. // Scan for the first operand that is constant and unequal in the
  508. // two getelementptrs...
  509. unsigned FirstConstantOper = UnequalOper;
  510. for (; FirstConstantOper != MinOperands; ++FirstConstantOper) {
  511. const Value *G1Oper = GEP1Ops[FirstConstantOper];
  512. const Value *G2Oper = GEP2Ops[FirstConstantOper];
  513. if (G1Oper != G2Oper) // Found non-equal constant indexes...
  514. if (Constant *G1OC = dyn_cast<ConstantInt>(const_cast<Value*>(G1Oper)))
  515. if (Constant *G2OC = dyn_cast<ConstantInt>(const_cast<Value*>(G2Oper))){
  516. if (G1OC->getType() != G2OC->getType()) {
  517. // Sign extend both operands to long.
  518. if (G1OC->getType() != Type::getInt64Ty(Context))
  519. G1OC = ConstantExpr::getSExt(G1OC, Type::getInt64Ty(Context));
  520. if (G2OC->getType() != Type::getInt64Ty(Context))
  521. G2OC = ConstantExpr::getSExt(G2OC, Type::getInt64Ty(Context));
  522. GEP1Ops[FirstConstantOper] = G1OC;
  523. GEP2Ops[FirstConstantOper] = G2OC;
  524. }
  525. if (G1OC != G2OC) {
  526. // Handle the "be careful" case above: if this is an array/vector
  527. // subscript, scan for a subsequent variable array index.
  528. if (const SequentialType *STy =
  529. dyn_cast<SequentialType>(BasePtr1Ty)) {
  530. const Type *NextTy = STy;
  531. bool isBadCase = false;
  532. for (unsigned Idx = FirstConstantOper;
  533. Idx != MinOperands && isa<SequentialType>(NextTy); ++Idx) {
  534. const Value *V1 = GEP1Ops[Idx], *V2 = GEP2Ops[Idx];
  535. if (!isa<Constant>(V1) || !isa<Constant>(V2)) {
  536. isBadCase = true;
  537. break;
  538. }
  539. // If the array is indexed beyond the bounds of the static type
  540. // at this level, it will also fall into the "be careful" case.
  541. // It would theoretically be possible to analyze these cases,
  542. // but for now just be conservatively correct.
  543. if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
  544. if (cast<ConstantInt>(G1OC)->getZExtValue() >=
  545. ATy->getNumElements() ||
  546. cast<ConstantInt>(G2OC)->getZExtValue() >=
  547. ATy->getNumElements()) {
  548. isBadCase = true;
  549. break;
  550. }
  551. if (const VectorType *VTy = dyn_cast<VectorType>(STy))
  552. if (cast<ConstantInt>(G1OC)->getZExtValue() >=
  553. VTy->getNumElements() ||
  554. cast<ConstantInt>(G2OC)->getZExtValue() >=
  555. VTy->getNumElements()) {
  556. isBadCase = true;
  557. break;
  558. }
  559. STy = cast<SequentialType>(NextTy);
  560. NextTy = cast<SequentialType>(NextTy)->getElementType();
  561. }
  562. if (isBadCase) G1OC = 0;
  563. }
  564. // Make sure they are comparable (ie, not constant expressions), and
  565. // make sure the GEP with the smaller leading constant is GEP1.
  566. if (G1OC) {
  567. Constant *Compare = ConstantExpr::getICmp(ICmpInst::ICMP_SGT,
  568. G1OC, G2OC);
  569. if (ConstantInt *CV = dyn_cast<ConstantInt>(Compare)) {
  570. if (CV->getZExtValue()) { // If they are comparable and G2 > G1
  571. std::swap(GEP1Ops, GEP2Ops); // Make GEP1 < GEP2
  572. std::swap(NumGEP1Ops, NumGEP2Ops);
  573. }
  574. break;
  575. }
  576. }
  577. }
  578. }
  579. BasePtr1Ty = cast<CompositeType>(BasePtr1Ty)->getTypeAtIndex(G1Oper);
  580. }
  581. // No shared constant operands, and we ran out of common operands. At this
  582. // point, the GEP instructions have run through all of their operands, and we
  583. // haven't found evidence that there are any deltas between the GEP's.
  584. // However, one GEP may have more operands than the other. If this is the
  585. // case, there may still be hope. Check this now.
  586. if (FirstConstantOper == MinOperands) {
  587. // Without TargetData, we won't know what the offsets are.
  588. if (!TD)
  589. return MayAlias;
  590. // Make GEP1Ops be the longer one if there is a longer one.
  591. if (NumGEP1Ops < NumGEP2Ops) {
  592. std::swap(GEP1Ops, GEP2Ops);
  593. std::swap(NumGEP1Ops, NumGEP2Ops);
  594. }
  595. // Is there anything to check?
  596. if (NumGEP1Ops > MinOperands) {
  597. for (unsigned i = FirstConstantOper; i != MaxOperands; ++i)
  598. if (isa<ConstantInt>(GEP1Ops[i]) &&
  599. !cast<ConstantInt>(GEP1Ops[i])->isZero()) {
  600. // Yup, there's a constant in the tail. Set all variables to
  601. // constants in the GEP instruction to make it suitable for
  602. // TargetData::getIndexedOffset.
  603. for (i = 0; i != MaxOperands; ++i)
  604. if (!isa<ConstantInt>(GEP1Ops[i]))
  605. GEP1Ops[i] = Constant::getNullValue(GEP1Ops[i]->getType());
  606. // Okay, now get the offset. This is the relative offset for the full
  607. // instruction.
  608. int64_t Offset1 = TD->getIndexedOffset(GEPPointerTy, GEP1Ops,
  609. NumGEP1Ops);
  610. // Now check without any constants at the end.
  611. int64_t Offset2 = TD->getIndexedOffset(GEPPointerTy, GEP1Ops,
  612. MinOperands);
  613. // Make sure we compare the absolute difference.
  614. if (Offset1 > Offset2)
  615. std::swap(Offset1, Offset2);
  616. // If the tail provided a bit enough offset, return noalias!
  617. if ((uint64_t)(Offset2-Offset1) >= SizeMax)
  618. return NoAlias;
  619. // Otherwise break - we don't look for another constant in the tail.
  620. break;
  621. }
  622. }
  623. // Couldn't find anything useful.
  624. return MayAlias;
  625. }
  626. // If there are non-equal constants arguments, then we can figure
  627. // out a minimum known delta between the two index expressions... at
  628. // this point we know that the first constant index of GEP1 is less
  629. // than the first constant index of GEP2.
  630. // Advance BasePtr[12]Ty over this first differing constant operand.
  631. BasePtr2Ty = cast<CompositeType>(BasePtr1Ty)->
  632. getTypeAtIndex(GEP2Ops[FirstConstantOper]);
  633. BasePtr1Ty = cast<CompositeType>(BasePtr1Ty)->
  634. getTypeAtIndex(GEP1Ops[FirstConstantOper]);
  635. // We are going to be using TargetData::getIndexedOffset to determine the
  636. // offset that each of the GEP's is reaching. To do this, we have to convert
  637. // all variable references to constant references. To do this, we convert the
  638. // initial sequence of array subscripts into constant zeros to start with.
  639. const Type *ZeroIdxTy = GEPPointerTy;
  640. for (unsigned i = 0; i != FirstConstantOper; ++i) {
  641. if (!isa<StructType>(ZeroIdxTy))
  642. GEP1Ops[i] = GEP2Ops[i] =
  643. Constant::getNullValue(Type::getInt32Ty(Context));
  644. if (const CompositeType *CT = dyn_cast<CompositeType>(ZeroIdxTy))
  645. ZeroIdxTy = CT->getTypeAtIndex(GEP1Ops[i]);
  646. }
  647. // We know that GEP1Ops[FirstConstantOper] & GEP2Ops[FirstConstantOper] are ok
  648. // Loop over the rest of the operands...
  649. for (unsigned i = FirstConstantOper+1; i != MaxOperands; ++i) {
  650. const Value *Op1 = i < NumGEP1Ops ? GEP1Ops[i] : 0;
  651. const Value *Op2 = i < NumGEP2Ops ? GEP2Ops[i] : 0;
  652. // If they are equal, use a zero index...
  653. if (Op1 == Op2 && BasePtr1Ty == BasePtr2Ty) {
  654. if (!isa<ConstantInt>(Op1))
  655. GEP1Ops[i] = GEP2Ops[i] = Constant::getNullValue(Op1->getType());
  656. // Otherwise, just keep the constants we have.
  657. } else {
  658. if (Op1) {
  659. if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
  660. // If this is an array index, make sure the array element is in range.
  661. if (const ArrayType *AT = dyn_cast<ArrayType>(BasePtr1Ty)) {
  662. if (Op1C->getZExtValue() >= AT->getNumElements())
  663. return MayAlias; // Be conservative with out-of-range accesses
  664. } else if (const VectorType *VT = dyn_cast<VectorType>(BasePtr1Ty)) {
  665. if (Op1C->getZExtValue() >= VT->getNumElements())
  666. return MayAlias; // Be conservative with out-of-range accesses
  667. }
  668. } else {
  669. // GEP1 is known to produce a value less than GEP2. To be
  670. // conservatively correct, we must assume the largest possible
  671. // constant is used in this position. This cannot be the initial
  672. // index to the GEP instructions (because we know we have at least one
  673. // element before this one with the different constant arguments), so
  674. // we know that the current index must be into either a struct or
  675. // array. Because we know it's not constant, this cannot be a
  676. // structure index. Because of this, we can calculate the maximum
  677. // value possible.
  678. //
  679. if (const ArrayType *AT = dyn_cast<ArrayType>(BasePtr1Ty))
  680. GEP1Ops[i] =
  681. ConstantInt::get(Type::getInt64Ty(Context),
  682. AT->getNumElements()-1);
  683. else if (const VectorType *VT = dyn_cast<VectorType>(BasePtr1Ty))
  684. GEP1Ops[i] =
  685. ConstantInt::get(Type::getInt64Ty(Context),
  686. VT->getNumElements()-1);
  687. }
  688. }
  689. if (Op2) {
  690. if (const ConstantInt *Op2C = dyn_cast<ConstantInt>(Op2)) {
  691. // If this is an array index, make sure the array element is in range.
  692. if (const ArrayType *AT = dyn_cast<ArrayType>(BasePtr2Ty)) {
  693. if (Op2C->getZExtValue() >= AT->getNumElements())
  694. return MayAlias; // Be conservative with out-of-range accesses
  695. } else if (const VectorType *VT = dyn_cast<VectorType>(BasePtr2Ty)) {
  696. if (Op2C->getZExtValue() >= VT->getNumElements())
  697. return MayAlias; // Be conservative with out-of-range accesses
  698. }
  699. } else { // Conservatively assume the minimum value for this index
  700. GEP2Ops[i] = Constant::getNullValue(Op2->getType());
  701. }
  702. }
  703. }
  704. if (BasePtr1Ty && Op1) {
  705. if (const CompositeType *CT = dyn_cast<CompositeType>(BasePtr1Ty))
  706. BasePtr1Ty = CT->getTypeAtIndex(GEP1Ops[i]);
  707. else
  708. BasePtr1Ty = 0;
  709. }
  710. if (BasePtr2Ty && Op2) {
  711. if (const CompositeType *CT = dyn_cast<CompositeType>(BasePtr2Ty))
  712. BasePtr2Ty = CT->getTypeAtIndex(GEP2Ops[i]);
  713. else
  714. BasePtr2Ty = 0;
  715. }
  716. }
  717. if (TD && GEPPointerTy->getElementType()->isSized()) {
  718. int64_t Offset1 =
  719. TD->getIndexedOffset(GEPPointerTy, GEP1Ops, NumGEP1Ops);
  720. int64_t Offset2 =
  721. TD->getIndexedOffset(GEPPointerTy, GEP2Ops, NumGEP2Ops);
  722. assert(Offset1 != Offset2 &&
  723. "There is at least one different constant here!");
  724. // Make sure we compare the absolute difference.
  725. if (Offset1 > Offset2)
  726. std::swap(Offset1, Offset2);
  727. if ((uint64_t)(Offset2-Offset1) >= SizeMax) {
  728. //cerr << "Determined that these two GEP's don't alias ["
  729. // << SizeMax << " bytes]: \n" << *GEP1 << *GEP2;
  730. return NoAlias;
  731. }
  732. }
  733. return MayAlias;
  734. }
  735. // Make sure that anything that uses AliasAnalysis pulls in this file...
  736. DEFINING_FILE_FOR(BasicAliasAnalysis)