ObjCARCAnalysisUtils.h 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. //===- ObjCARCAnalysisUtils.h - ObjC ARC Analysis Utilities -----*- C++ -*-===//
  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. /// This file defines common analysis utilities used by the ObjC ARC Optimizer.
  10. /// ARC stands for Automatic Reference Counting and is a system for managing
  11. /// reference counts for objects in Objective C.
  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. #ifndef LLVM_ANALYSIS_OBJCARCANALYSISUTILS_H
  22. #define LLVM_ANALYSIS_OBJCARCANALYSISUTILS_H
  23. #include "llvm/ADT/Optional.h"
  24. #include "llvm/Analysis/ObjCARCInstKind.h"
  25. #include "llvm/Analysis/ValueTracking.h"
  26. #include "llvm/IR/Constants.h"
  27. #include "llvm/IR/Module.h"
  28. #include "llvm/IR/ValueHandle.h"
  29. namespace llvm {
  30. class AAResults;
  31. namespace objcarc {
  32. /// A handy option to enable/disable all ARC Optimizations.
  33. extern bool EnableARCOpts;
  34. /// Test if the given module looks interesting to run ARC optimization
  35. /// on.
  36. inline bool ModuleHasARC(const Module &M) {
  37. return
  38. M.getNamedValue("llvm.objc.retain") ||
  39. M.getNamedValue("llvm.objc.release") ||
  40. M.getNamedValue("llvm.objc.autorelease") ||
  41. M.getNamedValue("llvm.objc.retainAutoreleasedReturnValue") ||
  42. M.getNamedValue("llvm.objc.unsafeClaimAutoreleasedReturnValue") ||
  43. M.getNamedValue("llvm.objc.retainBlock") ||
  44. M.getNamedValue("llvm.objc.autoreleaseReturnValue") ||
  45. M.getNamedValue("llvm.objc.autoreleasePoolPush") ||
  46. M.getNamedValue("llvm.objc.loadWeakRetained") ||
  47. M.getNamedValue("llvm.objc.loadWeak") ||
  48. M.getNamedValue("llvm.objc.destroyWeak") ||
  49. M.getNamedValue("llvm.objc.storeWeak") ||
  50. M.getNamedValue("llvm.objc.initWeak") ||
  51. M.getNamedValue("llvm.objc.moveWeak") ||
  52. M.getNamedValue("llvm.objc.copyWeak") ||
  53. M.getNamedValue("llvm.objc.retainedObject") ||
  54. M.getNamedValue("llvm.objc.unretainedObject") ||
  55. M.getNamedValue("llvm.objc.unretainedPointer") ||
  56. M.getNamedValue("llvm.objc.clang.arc.use");
  57. }
  58. /// This is a wrapper around getUnderlyingObject which also knows how to
  59. /// look through objc_retain and objc_autorelease calls, which we know to return
  60. /// their argument verbatim.
  61. inline const Value *GetUnderlyingObjCPtr(const Value *V) {
  62. for (;;) {
  63. V = getUnderlyingObject(V);
  64. if (!IsForwarding(GetBasicARCInstKind(V)))
  65. break;
  66. V = cast<CallInst>(V)->getArgOperand(0);
  67. }
  68. return V;
  69. }
  70. /// A wrapper for GetUnderlyingObjCPtr used for results memoization.
  71. inline const Value *
  72. GetUnderlyingObjCPtrCached(const Value *V,
  73. DenseMap<const Value *, WeakTrackingVH> &Cache) {
  74. if (auto InCache = Cache.lookup(V))
  75. return InCache;
  76. const Value *Computed = GetUnderlyingObjCPtr(V);
  77. Cache[V] = const_cast<Value *>(Computed);
  78. return Computed;
  79. }
  80. /// The RCIdentity root of a value \p V is a dominating value U for which
  81. /// retaining or releasing U is equivalent to retaining or releasing V. In other
  82. /// words, ARC operations on \p V are equivalent to ARC operations on \p U.
  83. ///
  84. /// We use this in the ARC optimizer to make it easier to match up ARC
  85. /// operations by always mapping ARC operations to RCIdentityRoots instead of
  86. /// pointers themselves.
  87. ///
  88. /// The two ways that we see RCIdentical values in ObjC are via:
  89. ///
  90. /// 1. PointerCasts
  91. /// 2. Forwarding Calls that return their argument verbatim.
  92. ///
  93. /// Thus this function strips off pointer casts and forwarding calls. *NOTE*
  94. /// This implies that two RCIdentical values must alias.
  95. inline const Value *GetRCIdentityRoot(const Value *V) {
  96. for (;;) {
  97. V = V->stripPointerCasts();
  98. if (!IsForwarding(GetBasicARCInstKind(V)))
  99. break;
  100. V = cast<CallInst>(V)->getArgOperand(0);
  101. }
  102. return V;
  103. }
  104. /// Helper which calls const Value *GetRCIdentityRoot(const Value *V) and just
  105. /// casts away the const of the result. For documentation about what an
  106. /// RCIdentityRoot (and by extension GetRCIdentityRoot is) look at that
  107. /// function.
  108. inline Value *GetRCIdentityRoot(Value *V) {
  109. return const_cast<Value *>(GetRCIdentityRoot((const Value *)V));
  110. }
  111. /// Assuming the given instruction is one of the special calls such as
  112. /// objc_retain or objc_release, return the RCIdentity root of the argument of
  113. /// the call.
  114. inline Value *GetArgRCIdentityRoot(Value *Inst) {
  115. return GetRCIdentityRoot(cast<CallInst>(Inst)->getArgOperand(0));
  116. }
  117. inline bool IsNullOrUndef(const Value *V) {
  118. return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
  119. }
  120. inline bool IsNoopInstruction(const Instruction *I) {
  121. return isa<BitCastInst>(I) ||
  122. (isa<GetElementPtrInst>(I) &&
  123. cast<GetElementPtrInst>(I)->hasAllZeroIndices());
  124. }
  125. /// Test whether the given value is possible a retainable object pointer.
  126. inline bool IsPotentialRetainableObjPtr(const Value *Op) {
  127. // Pointers to static or stack storage are not valid retainable object
  128. // pointers.
  129. if (isa<Constant>(Op) || isa<AllocaInst>(Op))
  130. return false;
  131. // Special arguments can not be a valid retainable object pointer.
  132. if (const Argument *Arg = dyn_cast<Argument>(Op))
  133. if (Arg->hasPassPointeeByValueCopyAttr() || Arg->hasNestAttr() ||
  134. Arg->hasStructRetAttr())
  135. return false;
  136. // Only consider values with pointer types.
  137. //
  138. // It seemes intuitive to exclude function pointer types as well, since
  139. // functions are never retainable object pointers, however clang occasionally
  140. // bitcasts retainable object pointers to function-pointer type temporarily.
  141. PointerType *Ty = dyn_cast<PointerType>(Op->getType());
  142. if (!Ty)
  143. return false;
  144. // Conservatively assume anything else is a potential retainable object
  145. // pointer.
  146. return true;
  147. }
  148. bool IsPotentialRetainableObjPtr(const Value *Op, AAResults &AA);
  149. /// Helper for GetARCInstKind. Determines what kind of construct CS
  150. /// is.
  151. inline ARCInstKind GetCallSiteClass(const CallBase &CB) {
  152. for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I)
  153. if (IsPotentialRetainableObjPtr(*I))
  154. return CB.onlyReadsMemory() ? ARCInstKind::User : ARCInstKind::CallOrUser;
  155. return CB.onlyReadsMemory() ? ARCInstKind::None : ARCInstKind::Call;
  156. }
  157. /// Return true if this value refers to a distinct and identifiable
  158. /// object.
  159. ///
  160. /// This is similar to AliasAnalysis's isIdentifiedObject, except that it uses
  161. /// special knowledge of ObjC conventions.
  162. inline bool IsObjCIdentifiedObject(const Value *V) {
  163. // Assume that call results and arguments have their own "provenance".
  164. // Constants (including GlobalVariables) and Allocas are never
  165. // reference-counted.
  166. if (isa<CallInst>(V) || isa<InvokeInst>(V) ||
  167. isa<Argument>(V) || isa<Constant>(V) ||
  168. isa<AllocaInst>(V))
  169. return true;
  170. if (const LoadInst *LI = dyn_cast<LoadInst>(V)) {
  171. const Value *Pointer =
  172. GetRCIdentityRoot(LI->getPointerOperand());
  173. if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Pointer)) {
  174. // A constant pointer can't be pointing to an object on the heap. It may
  175. // be reference-counted, but it won't be deleted.
  176. if (GV->isConstant())
  177. return true;
  178. StringRef Name = GV->getName();
  179. // These special variables are known to hold values which are not
  180. // reference-counted pointers.
  181. if (Name.startswith("\01l_objc_msgSend_fixup_"))
  182. return true;
  183. StringRef Section = GV->getSection();
  184. if (Section.find("__message_refs") != StringRef::npos ||
  185. Section.find("__objc_classrefs") != StringRef::npos ||
  186. Section.find("__objc_superrefs") != StringRef::npos ||
  187. Section.find("__objc_methname") != StringRef::npos ||
  188. Section.find("__cstring") != StringRef::npos)
  189. return true;
  190. }
  191. }
  192. return false;
  193. }
  194. enum class ARCMDKindID {
  195. ImpreciseRelease,
  196. CopyOnEscape,
  197. NoObjCARCExceptions,
  198. };
  199. /// A cache of MDKinds used by various ARC optimizations.
  200. class ARCMDKindCache {
  201. Module *M;
  202. /// The Metadata Kind for clang.imprecise_release metadata.
  203. llvm::Optional<unsigned> ImpreciseReleaseMDKind;
  204. /// The Metadata Kind for clang.arc.copy_on_escape metadata.
  205. llvm::Optional<unsigned> CopyOnEscapeMDKind;
  206. /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata.
  207. llvm::Optional<unsigned> NoObjCARCExceptionsMDKind;
  208. public:
  209. void init(Module *Mod) {
  210. M = Mod;
  211. ImpreciseReleaseMDKind = NoneType::None;
  212. CopyOnEscapeMDKind = NoneType::None;
  213. NoObjCARCExceptionsMDKind = NoneType::None;
  214. }
  215. unsigned get(ARCMDKindID ID) {
  216. switch (ID) {
  217. case ARCMDKindID::ImpreciseRelease:
  218. if (!ImpreciseReleaseMDKind)
  219. ImpreciseReleaseMDKind =
  220. M->getContext().getMDKindID("clang.imprecise_release");
  221. return *ImpreciseReleaseMDKind;
  222. case ARCMDKindID::CopyOnEscape:
  223. if (!CopyOnEscapeMDKind)
  224. CopyOnEscapeMDKind =
  225. M->getContext().getMDKindID("clang.arc.copy_on_escape");
  226. return *CopyOnEscapeMDKind;
  227. case ARCMDKindID::NoObjCARCExceptions:
  228. if (!NoObjCARCExceptionsMDKind)
  229. NoObjCARCExceptionsMDKind =
  230. M->getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
  231. return *NoObjCARCExceptionsMDKind;
  232. }
  233. llvm_unreachable("Covered switch isn't covered?!");
  234. }
  235. };
  236. } // end namespace objcarc
  237. } // end namespace llvm
  238. #endif