DependencyAnalysis.cpp 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. //===- DependencyAnalysis.cpp - ObjC ARC Optimization ---------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. /// \file
  9. ///
  10. /// This file defines special dependency analysis routines used in Objective C
  11. /// ARC Optimizations.
  12. ///
  13. /// WARNING: This file knows about certain library functions. It recognizes them
  14. /// by name, and hardwires knowledge of their semantics.
  15. ///
  16. /// WARNING: This file knows about how certain Objective-C library functions are
  17. /// used. Naive LLVM IR transformations which would otherwise be
  18. /// behavior-preserving may break these assumptions.
  19. ///
  20. //===----------------------------------------------------------------------===//
  21. #include "DependencyAnalysis.h"
  22. #include "ObjCARC.h"
  23. #include "ProvenanceAnalysis.h"
  24. #include "llvm/Analysis/AliasAnalysis.h"
  25. #include "llvm/IR/CFG.h"
  26. using namespace llvm;
  27. using namespace llvm::objcarc;
  28. #define DEBUG_TYPE "objc-arc-dependency"
  29. /// Test whether the given instruction can result in a reference count
  30. /// modification (positive or negative) for the pointer's object.
  31. bool llvm::objcarc::CanAlterRefCount(const Instruction *Inst, const Value *Ptr,
  32. ProvenanceAnalysis &PA,
  33. ARCInstKind Class) {
  34. switch (Class) {
  35. case ARCInstKind::Autorelease:
  36. case ARCInstKind::AutoreleaseRV:
  37. case ARCInstKind::IntrinsicUser:
  38. case ARCInstKind::User:
  39. // These operations never directly modify a reference count.
  40. return false;
  41. default: break;
  42. }
  43. const auto *Call = cast<CallBase>(Inst);
  44. // See if AliasAnalysis can help us with the call.
  45. FunctionModRefBehavior MRB = PA.getAA()->getModRefBehavior(Call);
  46. if (AliasAnalysis::onlyReadsMemory(MRB))
  47. return false;
  48. if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
  49. for (const Value *Op : Call->args()) {
  50. if (IsPotentialRetainableObjPtr(Op, *PA.getAA()) && PA.related(Ptr, Op))
  51. return true;
  52. }
  53. return false;
  54. }
  55. // Assume the worst.
  56. return true;
  57. }
  58. bool llvm::objcarc::CanDecrementRefCount(const Instruction *Inst,
  59. const Value *Ptr,
  60. ProvenanceAnalysis &PA,
  61. ARCInstKind Class) {
  62. // First perform a quick check if Class can not touch ref counts.
  63. if (!CanDecrementRefCount(Class))
  64. return false;
  65. // Otherwise, just use CanAlterRefCount for now.
  66. return CanAlterRefCount(Inst, Ptr, PA, Class);
  67. }
  68. /// Test whether the given instruction can "use" the given pointer's object in a
  69. /// way that requires the reference count to be positive.
  70. bool llvm::objcarc::CanUse(const Instruction *Inst, const Value *Ptr,
  71. ProvenanceAnalysis &PA, ARCInstKind Class) {
  72. // ARCInstKind::Call operations (as opposed to
  73. // ARCInstKind::CallOrUser) never "use" objc pointers.
  74. if (Class == ARCInstKind::Call)
  75. return false;
  76. // Consider various instructions which may have pointer arguments which are
  77. // not "uses".
  78. if (const ICmpInst *ICI = dyn_cast<ICmpInst>(Inst)) {
  79. // Comparing a pointer with null, or any other constant, isn't really a use,
  80. // because we don't care what the pointer points to, or about the values
  81. // of any other dynamic reference-counted pointers.
  82. if (!IsPotentialRetainableObjPtr(ICI->getOperand(1), *PA.getAA()))
  83. return false;
  84. } else if (const auto *CS = dyn_cast<CallBase>(Inst)) {
  85. // For calls, just check the arguments (and not the callee operand).
  86. for (const Value *Op : CS->args())
  87. if (IsPotentialRetainableObjPtr(Op, *PA.getAA()) && PA.related(Ptr, Op))
  88. return true;
  89. return false;
  90. } else if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
  91. // Special-case stores, because we don't care about the stored value, just
  92. // the store address.
  93. const Value *Op = GetUnderlyingObjCPtr(SI->getPointerOperand());
  94. // If we can't tell what the underlying object was, assume there is a
  95. // dependence.
  96. return IsPotentialRetainableObjPtr(Op, *PA.getAA()) && PA.related(Op, Ptr);
  97. }
  98. // Check each operand for a match.
  99. for (const Use &U : Inst->operands()) {
  100. const Value *Op = U;
  101. if (IsPotentialRetainableObjPtr(Op, *PA.getAA()) && PA.related(Ptr, Op))
  102. return true;
  103. }
  104. return false;
  105. }
  106. /// Test if there can be dependencies on Inst through Arg. This function only
  107. /// tests dependencies relevant for removing pairs of calls.
  108. bool
  109. llvm::objcarc::Depends(DependenceKind Flavor, Instruction *Inst,
  110. const Value *Arg, ProvenanceAnalysis &PA) {
  111. // If we've reached the definition of Arg, stop.
  112. if (Inst == Arg)
  113. return true;
  114. switch (Flavor) {
  115. case NeedsPositiveRetainCount: {
  116. ARCInstKind Class = GetARCInstKind(Inst);
  117. switch (Class) {
  118. case ARCInstKind::AutoreleasepoolPop:
  119. case ARCInstKind::AutoreleasepoolPush:
  120. case ARCInstKind::None:
  121. return false;
  122. default:
  123. return CanUse(Inst, Arg, PA, Class);
  124. }
  125. }
  126. case AutoreleasePoolBoundary: {
  127. ARCInstKind Class = GetARCInstKind(Inst);
  128. switch (Class) {
  129. case ARCInstKind::AutoreleasepoolPop:
  130. case ARCInstKind::AutoreleasepoolPush:
  131. // These mark the end and begin of an autorelease pool scope.
  132. return true;
  133. default:
  134. // Nothing else does this.
  135. return false;
  136. }
  137. }
  138. case CanChangeRetainCount: {
  139. ARCInstKind Class = GetARCInstKind(Inst);
  140. switch (Class) {
  141. case ARCInstKind::AutoreleasepoolPop:
  142. // Conservatively assume this can decrement any count.
  143. return true;
  144. case ARCInstKind::AutoreleasepoolPush:
  145. case ARCInstKind::None:
  146. return false;
  147. default:
  148. return CanAlterRefCount(Inst, Arg, PA, Class);
  149. }
  150. }
  151. case RetainAutoreleaseDep:
  152. switch (GetBasicARCInstKind(Inst)) {
  153. case ARCInstKind::AutoreleasepoolPop:
  154. case ARCInstKind::AutoreleasepoolPush:
  155. // Don't merge an objc_autorelease with an objc_retain inside a different
  156. // autoreleasepool scope.
  157. return true;
  158. case ARCInstKind::Retain:
  159. case ARCInstKind::RetainRV:
  160. // Check for a retain of the same pointer for merging.
  161. return GetArgRCIdentityRoot(Inst) == Arg;
  162. default:
  163. // Nothing else matters for objc_retainAutorelease formation.
  164. return false;
  165. }
  166. case RetainAutoreleaseRVDep: {
  167. ARCInstKind Class = GetBasicARCInstKind(Inst);
  168. switch (Class) {
  169. case ARCInstKind::Retain:
  170. case ARCInstKind::RetainRV:
  171. // Check for a retain of the same pointer for merging.
  172. return GetArgRCIdentityRoot(Inst) == Arg;
  173. default:
  174. // Anything that can autorelease interrupts
  175. // retainAutoreleaseReturnValue formation.
  176. return CanInterruptRV(Class);
  177. }
  178. }
  179. }
  180. llvm_unreachable("Invalid dependence flavor");
  181. }
  182. /// Walk up the CFG from StartPos (which is in StartBB) and find local and
  183. /// non-local dependencies on Arg.
  184. ///
  185. /// TODO: Cache results?
  186. static bool findDependencies(DependenceKind Flavor, const Value *Arg,
  187. BasicBlock *StartBB, Instruction *StartInst,
  188. SmallPtrSetImpl<Instruction *> &DependingInsts,
  189. ProvenanceAnalysis &PA) {
  190. BasicBlock::iterator StartPos = StartInst->getIterator();
  191. SmallPtrSet<const BasicBlock *, 4> Visited;
  192. SmallVector<std::pair<BasicBlock *, BasicBlock::iterator>, 4> Worklist;
  193. Worklist.push_back(std::make_pair(StartBB, StartPos));
  194. do {
  195. std::pair<BasicBlock *, BasicBlock::iterator> Pair =
  196. Worklist.pop_back_val();
  197. BasicBlock *LocalStartBB = Pair.first;
  198. BasicBlock::iterator LocalStartPos = Pair.second;
  199. BasicBlock::iterator StartBBBegin = LocalStartBB->begin();
  200. for (;;) {
  201. if (LocalStartPos == StartBBBegin) {
  202. pred_iterator PI(LocalStartBB), PE(LocalStartBB, false);
  203. if (PI == PE)
  204. // Return if we've reached the function entry.
  205. return false;
  206. // Add the predecessors to the worklist.
  207. do {
  208. BasicBlock *PredBB = *PI;
  209. if (Visited.insert(PredBB).second)
  210. Worklist.push_back(std::make_pair(PredBB, PredBB->end()));
  211. } while (++PI != PE);
  212. break;
  213. }
  214. Instruction *Inst = &*--LocalStartPos;
  215. if (Depends(Flavor, Inst, Arg, PA)) {
  216. DependingInsts.insert(Inst);
  217. break;
  218. }
  219. }
  220. } while (!Worklist.empty());
  221. // Determine whether the original StartBB post-dominates all of the blocks we
  222. // visited. If not, insert a sentinal indicating that most optimizations are
  223. // not safe.
  224. for (const BasicBlock *BB : Visited) {
  225. if (BB == StartBB)
  226. continue;
  227. for (const BasicBlock *Succ : successors(BB))
  228. if (Succ != StartBB && !Visited.count(Succ))
  229. return false;
  230. }
  231. return true;
  232. }
  233. llvm::Instruction *llvm::objcarc::findSingleDependency(DependenceKind Flavor,
  234. const Value *Arg,
  235. BasicBlock *StartBB,
  236. Instruction *StartInst,
  237. ProvenanceAnalysis &PA) {
  238. SmallPtrSet<Instruction *, 4> DependingInsts;
  239. if (!findDependencies(Flavor, Arg, StartBB, StartInst, DependingInsts, PA) ||
  240. DependingInsts.size() != 1)
  241. return nullptr;
  242. return *DependingInsts.begin();
  243. }