ObjCARC.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. //===- ObjCARC.h - ObjC ARC Optimization --------------*- C++ -*-----------===//
  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. /// \file
  10. /// This file defines common definitions/declarations used by the ObjC ARC
  11. /// Optimizer. ARC stands for Automatic Reference Counting and is a system for
  12. /// managing reference counts for objects in Objective C.
  13. ///
  14. /// WARNING: This file knows about certain library functions. It recognizes them
  15. /// by name, and hardwires knowledge of their semantics.
  16. ///
  17. /// WARNING: This file knows about how certain Objective-C library functions are
  18. /// used. Naive LLVM IR transformations which would otherwise be
  19. /// behavior-preserving may break these assumptions.
  20. ///
  21. //===----------------------------------------------------------------------===//
  22. #ifndef LLVM_LIB_TRANSFORMS_OBJCARC_OBJCARC_H
  23. #define LLVM_LIB_TRANSFORMS_OBJCARC_OBJCARC_H
  24. #include "llvm/ADT/StringSwitch.h"
  25. #include "llvm/ADT/Optional.h"
  26. #include "llvm/Analysis/AliasAnalysis.h"
  27. #include "llvm/Analysis/Passes.h"
  28. #include "llvm/Analysis/ValueTracking.h"
  29. #include "llvm/IR/CallSite.h"
  30. #include "llvm/IR/InstIterator.h"
  31. #include "llvm/IR/Module.h"
  32. #include "llvm/Pass.h"
  33. #include "llvm/Transforms/ObjCARC.h"
  34. #include "llvm/Transforms/Utils/Local.h"
  35. #include "ARCInstKind.h"
  36. namespace llvm {
  37. class raw_ostream;
  38. }
  39. namespace llvm {
  40. namespace objcarc {
  41. /// \brief A handy option to enable/disable all ARC Optimizations.
  42. extern bool EnableARCOpts;
  43. /// \brief Test if the given module looks interesting to run ARC optimization
  44. /// on.
  45. static inline bool ModuleHasARC(const Module &M) {
  46. return
  47. M.getNamedValue("objc_retain") ||
  48. M.getNamedValue("objc_release") ||
  49. M.getNamedValue("objc_autorelease") ||
  50. M.getNamedValue("objc_retainAutoreleasedReturnValue") ||
  51. M.getNamedValue("objc_retainBlock") ||
  52. M.getNamedValue("objc_autoreleaseReturnValue") ||
  53. M.getNamedValue("objc_autoreleasePoolPush") ||
  54. M.getNamedValue("objc_loadWeakRetained") ||
  55. M.getNamedValue("objc_loadWeak") ||
  56. M.getNamedValue("objc_destroyWeak") ||
  57. M.getNamedValue("objc_storeWeak") ||
  58. M.getNamedValue("objc_initWeak") ||
  59. M.getNamedValue("objc_moveWeak") ||
  60. M.getNamedValue("objc_copyWeak") ||
  61. M.getNamedValue("objc_retainedObject") ||
  62. M.getNamedValue("objc_unretainedObject") ||
  63. M.getNamedValue("objc_unretainedPointer") ||
  64. M.getNamedValue("clang.arc.use");
  65. }
  66. /// \brief This is a wrapper around getUnderlyingObject which also knows how to
  67. /// look through objc_retain and objc_autorelease calls, which we know to return
  68. /// their argument verbatim.
  69. static inline const Value *GetUnderlyingObjCPtr(const Value *V,
  70. const DataLayout &DL) {
  71. for (;;) {
  72. V = GetUnderlyingObject(V, DL);
  73. if (!IsForwarding(GetBasicARCInstKind(V)))
  74. break;
  75. V = cast<CallInst>(V)->getArgOperand(0);
  76. }
  77. return V;
  78. }
  79. /// The RCIdentity root of a value \p V is a dominating value U for which
  80. /// retaining or releasing U is equivalent to retaining or releasing V. In other
  81. /// words, ARC operations on \p V are equivalent to ARC operations on \p U.
  82. ///
  83. /// We use this in the ARC optimizer to make it easier to match up ARC
  84. /// operations by always mapping ARC operations to RCIdentityRoots instead of
  85. /// pointers themselves.
  86. ///
  87. /// The two ways that we see RCIdentical values in ObjC are via:
  88. ///
  89. /// 1. PointerCasts
  90. /// 2. Forwarding Calls that return their argument verbatim.
  91. ///
  92. /// Thus this function strips off pointer casts and forwarding calls. *NOTE*
  93. /// This implies that two RCIdentical values must alias.
  94. static inline const Value *GetRCIdentityRoot(const Value *V) {
  95. for (;;) {
  96. V = V->stripPointerCasts();
  97. if (!IsForwarding(GetBasicARCInstKind(V)))
  98. break;
  99. V = cast<CallInst>(V)->getArgOperand(0);
  100. }
  101. return V;
  102. }
  103. /// Helper which calls const Value *GetRCIdentityRoot(const Value *V) and just
  104. /// casts away the const of the result. For documentation about what an
  105. /// RCIdentityRoot (and by extension GetRCIdentityRoot is) look at that
  106. /// function.
  107. static inline Value *GetRCIdentityRoot(Value *V) {
  108. return const_cast<Value *>(GetRCIdentityRoot((const Value *)V));
  109. }
  110. /// \brief Assuming the given instruction is one of the special calls such as
  111. /// objc_retain or objc_release, return the RCIdentity root of the argument of
  112. /// the call.
  113. static inline Value *GetArgRCIdentityRoot(Value *Inst) {
  114. return GetRCIdentityRoot(cast<CallInst>(Inst)->getArgOperand(0));
  115. }
  116. static inline bool IsNullOrUndef(const Value *V) {
  117. return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
  118. }
  119. static inline bool IsNoopInstruction(const Instruction *I) {
  120. return isa<BitCastInst>(I) ||
  121. (isa<GetElementPtrInst>(I) &&
  122. cast<GetElementPtrInst>(I)->hasAllZeroIndices());
  123. }
  124. /// \brief Erase the given instruction.
  125. ///
  126. /// Many ObjC calls return their argument verbatim,
  127. /// so if it's such a call and the return value has users, replace them with the
  128. /// argument value.
  129. ///
  130. static inline void EraseInstruction(Instruction *CI) {
  131. Value *OldArg = cast<CallInst>(CI)->getArgOperand(0);
  132. bool Unused = CI->use_empty();
  133. if (!Unused) {
  134. // Replace the return value with the argument.
  135. assert((IsForwarding(GetBasicARCInstKind(CI)) ||
  136. (IsNoopOnNull(GetBasicARCInstKind(CI)) &&
  137. isa<ConstantPointerNull>(OldArg))) &&
  138. "Can't delete non-forwarding instruction with users!");
  139. CI->replaceAllUsesWith(OldArg);
  140. }
  141. CI->eraseFromParent();
  142. if (Unused)
  143. RecursivelyDeleteTriviallyDeadInstructions(OldArg);
  144. }
  145. /// \brief Test whether the given value is possible a retainable object pointer.
  146. static inline bool IsPotentialRetainableObjPtr(const Value *Op) {
  147. // Pointers to static or stack storage are not valid retainable object
  148. // pointers.
  149. if (isa<Constant>(Op) || isa<AllocaInst>(Op))
  150. return false;
  151. // Special arguments can not be a valid retainable object pointer.
  152. if (const Argument *Arg = dyn_cast<Argument>(Op))
  153. if (Arg->hasByValAttr() ||
  154. Arg->hasInAllocaAttr() ||
  155. Arg->hasNestAttr() ||
  156. Arg->hasStructRetAttr())
  157. return false;
  158. // Only consider values with pointer types.
  159. //
  160. // It seemes intuitive to exclude function pointer types as well, since
  161. // functions are never retainable object pointers, however clang occasionally
  162. // bitcasts retainable object pointers to function-pointer type temporarily.
  163. PointerType *Ty = dyn_cast<PointerType>(Op->getType());
  164. if (!Ty)
  165. return false;
  166. // Conservatively assume anything else is a potential retainable object
  167. // pointer.
  168. return true;
  169. }
  170. static inline bool IsPotentialRetainableObjPtr(const Value *Op,
  171. AliasAnalysis &AA) {
  172. // First make the rudimentary check.
  173. if (!IsPotentialRetainableObjPtr(Op))
  174. return false;
  175. // Objects in constant memory are not reference-counted.
  176. if (AA.pointsToConstantMemory(Op))
  177. return false;
  178. // Pointers in constant memory are not pointing to reference-counted objects.
  179. if (const LoadInst *LI = dyn_cast<LoadInst>(Op))
  180. if (AA.pointsToConstantMemory(LI->getPointerOperand()))
  181. return false;
  182. // Otherwise assume the worst.
  183. return true;
  184. }
  185. /// \brief Helper for GetARCInstKind. Determines what kind of construct CS
  186. /// is.
  187. static inline ARCInstKind GetCallSiteClass(ImmutableCallSite CS) {
  188. for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
  189. I != E; ++I)
  190. if (IsPotentialRetainableObjPtr(*I))
  191. return CS.onlyReadsMemory() ? ARCInstKind::User : ARCInstKind::CallOrUser;
  192. return CS.onlyReadsMemory() ? ARCInstKind::None : ARCInstKind::Call;
  193. }
  194. /// \brief Return true if this value refers to a distinct and identifiable
  195. /// object.
  196. ///
  197. /// This is similar to AliasAnalysis's isIdentifiedObject, except that it uses
  198. /// special knowledge of ObjC conventions.
  199. static inline bool IsObjCIdentifiedObject(const Value *V) {
  200. // Assume that call results and arguments have their own "provenance".
  201. // Constants (including GlobalVariables) and Allocas are never
  202. // reference-counted.
  203. if (isa<CallInst>(V) || isa<InvokeInst>(V) ||
  204. isa<Argument>(V) || isa<Constant>(V) ||
  205. isa<AllocaInst>(V))
  206. return true;
  207. if (const LoadInst *LI = dyn_cast<LoadInst>(V)) {
  208. const Value *Pointer =
  209. GetRCIdentityRoot(LI->getPointerOperand());
  210. if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Pointer)) {
  211. // A constant pointer can't be pointing to an object on the heap. It may
  212. // be reference-counted, but it won't be deleted.
  213. if (GV->isConstant())
  214. return true;
  215. StringRef Name = GV->getName();
  216. // These special variables are known to hold values which are not
  217. // reference-counted pointers.
  218. if (Name.startswith("\01l_objc_msgSend_fixup_"))
  219. return true;
  220. StringRef Section = GV->getSection();
  221. if (Section.find("__message_refs") != StringRef::npos ||
  222. Section.find("__objc_classrefs") != StringRef::npos ||
  223. Section.find("__objc_superrefs") != StringRef::npos ||
  224. Section.find("__objc_methname") != StringRef::npos ||
  225. Section.find("__cstring") != StringRef::npos)
  226. return true;
  227. }
  228. }
  229. return false;
  230. }
  231. enum class ARCMDKindID {
  232. ImpreciseRelease,
  233. CopyOnEscape,
  234. NoObjCARCExceptions,
  235. };
  236. /// A cache of MDKinds used by various ARC optimizations.
  237. class ARCMDKindCache {
  238. Module *M;
  239. /// The Metadata Kind for clang.imprecise_release metadata.
  240. llvm::Optional<unsigned> ImpreciseReleaseMDKind;
  241. /// The Metadata Kind for clang.arc.copy_on_escape metadata.
  242. llvm::Optional<unsigned> CopyOnEscapeMDKind;
  243. /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata.
  244. llvm::Optional<unsigned> NoObjCARCExceptionsMDKind;
  245. public:
  246. void init(Module *Mod) {
  247. M = Mod;
  248. ImpreciseReleaseMDKind = NoneType::None;
  249. CopyOnEscapeMDKind = NoneType::None;
  250. NoObjCARCExceptionsMDKind = NoneType::None;
  251. }
  252. unsigned get(ARCMDKindID ID) {
  253. switch (ID) {
  254. case ARCMDKindID::ImpreciseRelease:
  255. if (!ImpreciseReleaseMDKind)
  256. ImpreciseReleaseMDKind =
  257. M->getContext().getMDKindID("clang.imprecise_release");
  258. return *ImpreciseReleaseMDKind;
  259. case ARCMDKindID::CopyOnEscape:
  260. if (!CopyOnEscapeMDKind)
  261. CopyOnEscapeMDKind =
  262. M->getContext().getMDKindID("clang.arc.copy_on_escape");
  263. return *CopyOnEscapeMDKind;
  264. case ARCMDKindID::NoObjCARCExceptions:
  265. if (!NoObjCARCExceptionsMDKind)
  266. NoObjCARCExceptionsMDKind =
  267. M->getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
  268. return *NoObjCARCExceptionsMDKind;
  269. }
  270. llvm_unreachable("Covered switch isn't covered?!");
  271. }
  272. };
  273. } // end namespace objcarc
  274. } // end namespace llvm
  275. #endif