AliasAnalysis.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. //===- AliasAnalysis.cpp - Generic Alias Analysis Interface Implementation -==//
  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 implements the generic AliasAnalysis interface which is used as the
  11. // common interface used by all clients and implementations of alias analysis.
  12. //
  13. // This file also implements the default version of the AliasAnalysis interface
  14. // that is to be used when no other implementation is specified. This does some
  15. // simple tests that detect obvious cases: two different global pointers cannot
  16. // alias, a global cannot alias a malloc, two different mallocs cannot alias,
  17. // etc.
  18. //
  19. // This alias analysis implementation really isn't very good for anything, but
  20. // it is very fast, and makes a nice clean default implementation. Because it
  21. // handles lots of little corner cases, other, more complex, alias analysis
  22. // implementations may choose to rely on this pass to resolve these simple and
  23. // easy cases.
  24. //
  25. //===----------------------------------------------------------------------===//
  26. #include "llvm/Analysis/AliasAnalysis.h"
  27. #include "llvm/Analysis/CFG.h"
  28. #include "llvm/Analysis/CaptureTracking.h"
  29. #include "llvm/Analysis/TargetLibraryInfo.h"
  30. #include "llvm/Analysis/ValueTracking.h"
  31. #include "llvm/IR/BasicBlock.h"
  32. #include "llvm/IR/DataLayout.h"
  33. #include "llvm/IR/Dominators.h"
  34. #include "llvm/IR/Function.h"
  35. #include "llvm/IR/Instructions.h"
  36. #include "llvm/IR/IntrinsicInst.h"
  37. #include "llvm/IR/LLVMContext.h"
  38. #include "llvm/IR/Type.h"
  39. #include "llvm/Pass.h"
  40. using namespace llvm;
  41. // Register the AliasAnalysis interface, providing a nice name to refer to.
  42. INITIALIZE_ANALYSIS_GROUP(AliasAnalysis, "Alias Analysis", NoAA)
  43. char AliasAnalysis::ID = 0;
  44. //===----------------------------------------------------------------------===//
  45. // Default chaining methods
  46. //===----------------------------------------------------------------------===//
  47. AliasResult AliasAnalysis::alias(const MemoryLocation &LocA,
  48. const MemoryLocation &LocB) {
  49. assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
  50. return AA->alias(LocA, LocB);
  51. }
  52. bool AliasAnalysis::pointsToConstantMemory(const MemoryLocation &Loc,
  53. bool OrLocal) {
  54. assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
  55. return AA->pointsToConstantMemory(Loc, OrLocal);
  56. }
  57. AliasAnalysis::ModRefResult
  58. AliasAnalysis::getArgModRefInfo(ImmutableCallSite CS, unsigned ArgIdx) {
  59. assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
  60. return AA->getArgModRefInfo(CS, ArgIdx);
  61. }
  62. void AliasAnalysis::deleteValue(Value *V) {
  63. assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
  64. AA->deleteValue(V);
  65. }
  66. void AliasAnalysis::addEscapingUse(Use &U) {
  67. assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
  68. AA->addEscapingUse(U);
  69. }
  70. AliasAnalysis::ModRefResult
  71. AliasAnalysis::getModRefInfo(Instruction *I, ImmutableCallSite Call) {
  72. // We may have two calls
  73. if (auto CS = ImmutableCallSite(I)) {
  74. // Check if the two calls modify the same memory
  75. return getModRefInfo(Call, CS);
  76. } else {
  77. // Otherwise, check if the call modifies or references the
  78. // location this memory access defines. The best we can say
  79. // is that if the call references what this instruction
  80. // defines, it must be clobbered by this location.
  81. const MemoryLocation DefLoc = MemoryLocation::get(I);
  82. if (getModRefInfo(Call, DefLoc) != AliasAnalysis::NoModRef)
  83. return AliasAnalysis::ModRef;
  84. }
  85. return AliasAnalysis::NoModRef;
  86. }
  87. AliasAnalysis::ModRefResult
  88. AliasAnalysis::getModRefInfo(ImmutableCallSite CS, const MemoryLocation &Loc) {
  89. assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
  90. ModRefBehavior MRB = getModRefBehavior(CS);
  91. if (MRB == DoesNotAccessMemory)
  92. return NoModRef;
  93. ModRefResult Mask = ModRef;
  94. if (onlyReadsMemory(MRB))
  95. Mask = Ref;
  96. if (onlyAccessesArgPointees(MRB)) {
  97. bool doesAlias = false;
  98. ModRefResult AllArgsMask = NoModRef;
  99. if (doesAccessArgPointees(MRB)) {
  100. for (ImmutableCallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
  101. AI != AE; ++AI) {
  102. const Value *Arg = *AI;
  103. if (!Arg->getType()->isPointerTy())
  104. continue;
  105. unsigned ArgIdx = std::distance(CS.arg_begin(), AI);
  106. MemoryLocation ArgLoc =
  107. MemoryLocation::getForArgument(CS, ArgIdx, *TLI);
  108. if (!isNoAlias(ArgLoc, Loc)) {
  109. ModRefResult ArgMask = getArgModRefInfo(CS, ArgIdx);
  110. doesAlias = true;
  111. AllArgsMask = ModRefResult(AllArgsMask | ArgMask);
  112. }
  113. }
  114. }
  115. if (!doesAlias)
  116. return NoModRef;
  117. Mask = ModRefResult(Mask & AllArgsMask);
  118. }
  119. // If Loc is a constant memory location, the call definitely could not
  120. // modify the memory location.
  121. if ((Mask & Mod) && pointsToConstantMemory(Loc))
  122. Mask = ModRefResult(Mask & ~Mod);
  123. // If this is the end of the chain, don't forward.
  124. if (!AA) return Mask;
  125. // Otherwise, fall back to the next AA in the chain. But we can merge
  126. // in any mask we've managed to compute.
  127. return ModRefResult(AA->getModRefInfo(CS, Loc) & Mask);
  128. }
  129. AliasAnalysis::ModRefResult
  130. AliasAnalysis::getModRefInfo(ImmutableCallSite CS1, ImmutableCallSite CS2) {
  131. assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
  132. // If CS1 or CS2 are readnone, they don't interact.
  133. ModRefBehavior CS1B = getModRefBehavior(CS1);
  134. if (CS1B == DoesNotAccessMemory) return NoModRef;
  135. ModRefBehavior CS2B = getModRefBehavior(CS2);
  136. if (CS2B == DoesNotAccessMemory) return NoModRef;
  137. // If they both only read from memory, there is no dependence.
  138. if (onlyReadsMemory(CS1B) && onlyReadsMemory(CS2B))
  139. return NoModRef;
  140. AliasAnalysis::ModRefResult Mask = ModRef;
  141. // If CS1 only reads memory, the only dependence on CS2 can be
  142. // from CS1 reading memory written by CS2.
  143. if (onlyReadsMemory(CS1B))
  144. Mask = ModRefResult(Mask & Ref);
  145. // If CS2 only access memory through arguments, accumulate the mod/ref
  146. // information from CS1's references to the memory referenced by
  147. // CS2's arguments.
  148. if (onlyAccessesArgPointees(CS2B)) {
  149. AliasAnalysis::ModRefResult R = NoModRef;
  150. if (doesAccessArgPointees(CS2B)) {
  151. for (ImmutableCallSite::arg_iterator
  152. I = CS2.arg_begin(), E = CS2.arg_end(); I != E; ++I) {
  153. const Value *Arg = *I;
  154. if (!Arg->getType()->isPointerTy())
  155. continue;
  156. unsigned CS2ArgIdx = std::distance(CS2.arg_begin(), I);
  157. auto CS2ArgLoc = MemoryLocation::getForArgument(CS2, CS2ArgIdx, *TLI);
  158. // ArgMask indicates what CS2 might do to CS2ArgLoc, and the dependence of
  159. // CS1 on that location is the inverse.
  160. ModRefResult ArgMask = getArgModRefInfo(CS2, CS2ArgIdx);
  161. if (ArgMask == Mod)
  162. ArgMask = ModRef;
  163. else if (ArgMask == Ref)
  164. ArgMask = Mod;
  165. R = ModRefResult((R | (getModRefInfo(CS1, CS2ArgLoc) & ArgMask)) & Mask);
  166. if (R == Mask)
  167. break;
  168. }
  169. }
  170. return R;
  171. }
  172. // If CS1 only accesses memory through arguments, check if CS2 references
  173. // any of the memory referenced by CS1's arguments. If not, return NoModRef.
  174. if (onlyAccessesArgPointees(CS1B)) {
  175. AliasAnalysis::ModRefResult R = NoModRef;
  176. if (doesAccessArgPointees(CS1B)) {
  177. for (ImmutableCallSite::arg_iterator
  178. I = CS1.arg_begin(), E = CS1.arg_end(); I != E; ++I) {
  179. const Value *Arg = *I;
  180. if (!Arg->getType()->isPointerTy())
  181. continue;
  182. unsigned CS1ArgIdx = std::distance(CS1.arg_begin(), I);
  183. auto CS1ArgLoc = MemoryLocation::getForArgument(CS1, CS1ArgIdx, *TLI);
  184. // ArgMask indicates what CS1 might do to CS1ArgLoc; if CS1 might Mod
  185. // CS1ArgLoc, then we care about either a Mod or a Ref by CS2. If CS1
  186. // might Ref, then we care only about a Mod by CS2.
  187. ModRefResult ArgMask = getArgModRefInfo(CS1, CS1ArgIdx);
  188. ModRefResult ArgR = getModRefInfo(CS2, CS1ArgLoc);
  189. if (((ArgMask & Mod) != NoModRef && (ArgR & ModRef) != NoModRef) ||
  190. ((ArgMask & Ref) != NoModRef && (ArgR & Mod) != NoModRef))
  191. R = ModRefResult((R | ArgMask) & Mask);
  192. if (R == Mask)
  193. break;
  194. }
  195. }
  196. return R;
  197. }
  198. // If this is the end of the chain, don't forward.
  199. if (!AA) return Mask;
  200. // Otherwise, fall back to the next AA in the chain. But we can merge
  201. // in any mask we've managed to compute.
  202. return ModRefResult(AA->getModRefInfo(CS1, CS2) & Mask);
  203. }
  204. AliasAnalysis::ModRefBehavior
  205. AliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
  206. assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
  207. ModRefBehavior Min = UnknownModRefBehavior;
  208. // Call back into the alias analysis with the other form of getModRefBehavior
  209. // to see if it can give a better response.
  210. if (const Function *F = CS.getCalledFunction())
  211. Min = getModRefBehavior(F);
  212. // If this is the end of the chain, don't forward.
  213. if (!AA) return Min;
  214. // Otherwise, fall back to the next AA in the chain. But we can merge
  215. // in any result we've managed to compute.
  216. return ModRefBehavior(AA->getModRefBehavior(CS) & Min);
  217. }
  218. AliasAnalysis::ModRefBehavior
  219. AliasAnalysis::getModRefBehavior(const Function *F) {
  220. assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
  221. return AA->getModRefBehavior(F);
  222. }
  223. //===----------------------------------------------------------------------===//
  224. // AliasAnalysis non-virtual helper method implementation
  225. //===----------------------------------------------------------------------===//
  226. AliasAnalysis::ModRefResult
  227. AliasAnalysis::getModRefInfo(const LoadInst *L, const MemoryLocation &Loc) {
  228. // Be conservative in the face of volatile/atomic.
  229. if (!L->isUnordered())
  230. return ModRef;
  231. // If the load address doesn't alias the given address, it doesn't read
  232. // or write the specified memory.
  233. if (Loc.Ptr && !alias(MemoryLocation::get(L), Loc))
  234. return NoModRef;
  235. // Otherwise, a load just reads.
  236. return Ref;
  237. }
  238. AliasAnalysis::ModRefResult
  239. AliasAnalysis::getModRefInfo(const StoreInst *S, const MemoryLocation &Loc) {
  240. // Be conservative in the face of volatile/atomic.
  241. if (!S->isUnordered())
  242. return ModRef;
  243. if (Loc.Ptr) {
  244. // If the store address cannot alias the pointer in question, then the
  245. // specified memory cannot be modified by the store.
  246. if (!alias(MemoryLocation::get(S), Loc))
  247. return NoModRef;
  248. // If the pointer is a pointer to constant memory, then it could not have
  249. // been modified by this store.
  250. if (pointsToConstantMemory(Loc))
  251. return NoModRef;
  252. }
  253. // Otherwise, a store just writes.
  254. return Mod;
  255. }
  256. AliasAnalysis::ModRefResult
  257. AliasAnalysis::getModRefInfo(const VAArgInst *V, const MemoryLocation &Loc) {
  258. if (Loc.Ptr) {
  259. // If the va_arg address cannot alias the pointer in question, then the
  260. // specified memory cannot be accessed by the va_arg.
  261. if (!alias(MemoryLocation::get(V), Loc))
  262. return NoModRef;
  263. // If the pointer is a pointer to constant memory, then it could not have
  264. // been modified by this va_arg.
  265. if (pointsToConstantMemory(Loc))
  266. return NoModRef;
  267. }
  268. // Otherwise, a va_arg reads and writes.
  269. return ModRef;
  270. }
  271. AliasAnalysis::ModRefResult
  272. AliasAnalysis::getModRefInfo(const AtomicCmpXchgInst *CX,
  273. const MemoryLocation &Loc) {
  274. // Acquire/Release cmpxchg has properties that matter for arbitrary addresses.
  275. if (CX->getSuccessOrdering() > Monotonic)
  276. return ModRef;
  277. // If the cmpxchg address does not alias the location, it does not access it.
  278. if (Loc.Ptr && !alias(MemoryLocation::get(CX), Loc))
  279. return NoModRef;
  280. return ModRef;
  281. }
  282. AliasAnalysis::ModRefResult
  283. AliasAnalysis::getModRefInfo(const AtomicRMWInst *RMW,
  284. const MemoryLocation &Loc) {
  285. // Acquire/Release atomicrmw has properties that matter for arbitrary addresses.
  286. if (RMW->getOrdering() > Monotonic)
  287. return ModRef;
  288. // If the atomicrmw address does not alias the location, it does not access it.
  289. if (Loc.Ptr && !alias(MemoryLocation::get(RMW), Loc))
  290. return NoModRef;
  291. return ModRef;
  292. }
  293. // FIXME: this is really just shoring-up a deficiency in alias analysis.
  294. // BasicAA isn't willing to spend linear time determining whether an alloca
  295. // was captured before or after this particular call, while we are. However,
  296. // with a smarter AA in place, this test is just wasting compile time.
  297. AliasAnalysis::ModRefResult AliasAnalysis::callCapturesBefore(
  298. const Instruction *I, const MemoryLocation &MemLoc, DominatorTree *DT) {
  299. if (!DT)
  300. return AliasAnalysis::ModRef;
  301. const Value *Object = GetUnderlyingObject(MemLoc.Ptr, *DL);
  302. if (!isIdentifiedObject(Object) || isa<GlobalValue>(Object) ||
  303. isa<Constant>(Object))
  304. return AliasAnalysis::ModRef;
  305. ImmutableCallSite CS(I);
  306. if (!CS.getInstruction() || CS.getInstruction() == Object)
  307. return AliasAnalysis::ModRef;
  308. if (llvm::PointerMayBeCapturedBefore(Object, /* ReturnCaptures */ true,
  309. /* StoreCaptures */ true, I, DT,
  310. /* include Object */ true))
  311. return AliasAnalysis::ModRef;
  312. unsigned ArgNo = 0;
  313. AliasAnalysis::ModRefResult R = AliasAnalysis::NoModRef;
  314. for (ImmutableCallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
  315. CI != CE; ++CI, ++ArgNo) {
  316. // Only look at the no-capture or byval pointer arguments. If this
  317. // pointer were passed to arguments that were neither of these, then it
  318. // couldn't be no-capture.
  319. if (!(*CI)->getType()->isPointerTy() ||
  320. (!CS.doesNotCapture(ArgNo) && !CS.isByValArgument(ArgNo)))
  321. continue;
  322. // If this is a no-capture pointer argument, see if we can tell that it
  323. // is impossible to alias the pointer we're checking. If not, we have to
  324. // assume that the call could touch the pointer, even though it doesn't
  325. // escape.
  326. if (isNoAlias(MemoryLocation(*CI), MemoryLocation(Object)))
  327. continue;
  328. if (CS.doesNotAccessMemory(ArgNo))
  329. continue;
  330. if (CS.onlyReadsMemory(ArgNo)) {
  331. R = AliasAnalysis::Ref;
  332. continue;
  333. }
  334. return AliasAnalysis::ModRef;
  335. }
  336. return R;
  337. }
  338. // AliasAnalysis destructor: DO NOT move this to the header file for
  339. // AliasAnalysis or else clients of the AliasAnalysis class may not depend on
  340. // the AliasAnalysis.o file in the current .a file, causing alias analysis
  341. // support to not be included in the tool correctly!
  342. //
  343. AliasAnalysis::~AliasAnalysis() {}
  344. /// InitializeAliasAnalysis - Subclasses must call this method to initialize the
  345. /// AliasAnalysis interface before any other methods are called.
  346. ///
  347. void AliasAnalysis::InitializeAliasAnalysis(Pass *P, const DataLayout *NewDL) {
  348. DL = NewDL;
  349. auto *TLIP = P->getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
  350. TLI = TLIP ? &TLIP->getTLI() : nullptr;
  351. AA = &P->getAnalysis<AliasAnalysis>();
  352. }
  353. // getAnalysisUsage - All alias analysis implementations should invoke this
  354. // directly (using AliasAnalysis::getAnalysisUsage(AU)).
  355. void AliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
  356. AU.addRequired<AliasAnalysis>(); // All AA's chain
  357. }
  358. /// getTypeStoreSize - Return the DataLayout store size for the given type,
  359. /// if known, or a conservative value otherwise.
  360. ///
  361. uint64_t AliasAnalysis::getTypeStoreSize(Type *Ty) {
  362. return DL ? DL->getTypeStoreSize(Ty) : MemoryLocation::UnknownSize;
  363. }
  364. /// canBasicBlockModify - Return true if it is possible for execution of the
  365. /// specified basic block to modify the location Loc.
  366. ///
  367. bool AliasAnalysis::canBasicBlockModify(const BasicBlock &BB,
  368. const MemoryLocation &Loc) {
  369. return canInstructionRangeModRef(BB.front(), BB.back(), Loc, Mod);
  370. }
  371. /// canInstructionRangeModRef - Return true if it is possible for the
  372. /// execution of the specified instructions to mod\ref (according to the
  373. /// mode) the location Loc. The instructions to consider are all
  374. /// of the instructions in the range of [I1,I2] INCLUSIVE.
  375. /// I1 and I2 must be in the same basic block.
  376. bool AliasAnalysis::canInstructionRangeModRef(const Instruction &I1,
  377. const Instruction &I2,
  378. const MemoryLocation &Loc,
  379. const ModRefResult Mode) {
  380. assert(I1.getParent() == I2.getParent() &&
  381. "Instructions not in same basic block!");
  382. BasicBlock::const_iterator I = &I1;
  383. BasicBlock::const_iterator E = &I2;
  384. ++E; // Convert from inclusive to exclusive range.
  385. for (; I != E; ++I) // Check every instruction in range
  386. if (getModRefInfo(I, Loc) & Mode)
  387. return true;
  388. return false;
  389. }
  390. /// isNoAliasCall - Return true if this pointer is returned by a noalias
  391. /// function.
  392. bool llvm::isNoAliasCall(const Value *V) {
  393. if (isa<CallInst>(V) || isa<InvokeInst>(V))
  394. return ImmutableCallSite(cast<Instruction>(V))
  395. .paramHasAttr(0, Attribute::NoAlias);
  396. return false;
  397. }
  398. /// isNoAliasArgument - Return true if this is an argument with the noalias
  399. /// attribute.
  400. bool llvm::isNoAliasArgument(const Value *V)
  401. {
  402. if (const Argument *A = dyn_cast<Argument>(V))
  403. return A->hasNoAliasAttr();
  404. return false;
  405. }
  406. /// isIdentifiedObject - Return true if this pointer refers to a distinct and
  407. /// identifiable object. This returns true for:
  408. /// Global Variables and Functions (but not Global Aliases)
  409. /// Allocas and Mallocs
  410. /// ByVal and NoAlias Arguments
  411. /// NoAlias returns
  412. ///
  413. bool llvm::isIdentifiedObject(const Value *V) {
  414. if (isa<AllocaInst>(V))
  415. return true;
  416. if (isa<GlobalValue>(V) && !isa<GlobalAlias>(V))
  417. return true;
  418. if (isNoAliasCall(V))
  419. return true;
  420. if (const Argument *A = dyn_cast<Argument>(V))
  421. return A->hasNoAliasAttr() || A->hasByValAttr();
  422. return false;
  423. }
  424. /// isIdentifiedFunctionLocal - Return true if V is umabigously identified
  425. /// at the function-level. Different IdentifiedFunctionLocals can't alias.
  426. /// Further, an IdentifiedFunctionLocal can not alias with any function
  427. /// arguments other than itself, which is not necessarily true for
  428. /// IdentifiedObjects.
  429. bool llvm::isIdentifiedFunctionLocal(const Value *V)
  430. {
  431. return isa<AllocaInst>(V) || isNoAliasCall(V) || isNoAliasArgument(V);
  432. }