1 //===- ObjCARCAnalysisUtils.h - ObjC ARC Analysis Utilities -----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 /// This file defines common analysis utilities used by the ObjC ARC Optimizer.
11 /// ARC stands for Automatic Reference Counting and is a system for managing
12 /// reference counts for objects in Objective C.
14 /// WARNING: This file knows about certain library functions. It recognizes them
15 /// by name, and hardwires knowledge of their semantics.
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.
21 //===----------------------------------------------------------------------===//
23 #ifndef LLVM_LIB_ANALYSIS_OBJCARCANALYSISUTILS_H
24 #define LLVM_LIB_ANALYSIS_OBJCARCANALYSISUTILS_H
26 #include "llvm/ADT/StringSwitch.h"
27 #include "llvm/ADT/Optional.h"
28 #include "llvm/Analysis/AliasAnalysis.h"
29 #include "llvm/Analysis/ObjCARCInstKind.h"
30 #include "llvm/Analysis/Passes.h"
31 #include "llvm/Analysis/ValueTracking.h"
32 #include "llvm/IR/CallSite.h"
33 #include "llvm/IR/InstIterator.h"
34 #include "llvm/IR/Module.h"
35 #include "llvm/Pass.h"
36 #include "llvm/Transforms/ObjCARC.h"
37 #include "llvm/Transforms/Utils/Local.h"
46 /// \brief A handy option to enable/disable all ARC Optimizations.
47 extern bool EnableARCOpts;
49 /// \brief Test if the given module looks interesting to run ARC optimization
51 inline bool ModuleHasARC(const Module &M) {
53 M.getNamedValue("objc_retain") ||
54 M.getNamedValue("objc_release") ||
55 M.getNamedValue("objc_autorelease") ||
56 M.getNamedValue("objc_retainAutoreleasedReturnValue") ||
57 M.getNamedValue("objc_retainBlock") ||
58 M.getNamedValue("objc_autoreleaseReturnValue") ||
59 M.getNamedValue("objc_autoreleasePoolPush") ||
60 M.getNamedValue("objc_loadWeakRetained") ||
61 M.getNamedValue("objc_loadWeak") ||
62 M.getNamedValue("objc_destroyWeak") ||
63 M.getNamedValue("objc_storeWeak") ||
64 M.getNamedValue("objc_initWeak") ||
65 M.getNamedValue("objc_moveWeak") ||
66 M.getNamedValue("objc_copyWeak") ||
67 M.getNamedValue("objc_retainedObject") ||
68 M.getNamedValue("objc_unretainedObject") ||
69 M.getNamedValue("objc_unretainedPointer") ||
70 M.getNamedValue("clang.arc.use");
73 /// \brief This is a wrapper around getUnderlyingObject which also knows how to
74 /// look through objc_retain and objc_autorelease calls, which we know to return
75 /// their argument verbatim.
76 inline const Value *GetUnderlyingObjCPtr(const Value *V,
77 const DataLayout &DL) {
79 V = GetUnderlyingObject(V, DL);
80 if (!IsForwarding(GetBasicARCInstKind(V)))
82 V = cast<CallInst>(V)->getArgOperand(0);
88 /// The RCIdentity root of a value \p V is a dominating value U for which
89 /// retaining or releasing U is equivalent to retaining or releasing V. In other
90 /// words, ARC operations on \p V are equivalent to ARC operations on \p U.
92 /// We use this in the ARC optimizer to make it easier to match up ARC
93 /// operations by always mapping ARC operations to RCIdentityRoots instead of
94 /// pointers themselves.
96 /// The two ways that we see RCIdentical values in ObjC are via:
99 /// 2. Forwarding Calls that return their argument verbatim.
101 /// Thus this function strips off pointer casts and forwarding calls. *NOTE*
102 /// This implies that two RCIdentical values must alias.
103 inline const Value *GetRCIdentityRoot(const Value *V) {
105 V = V->stripPointerCasts();
106 if (!IsForwarding(GetBasicARCInstKind(V)))
108 V = cast<CallInst>(V)->getArgOperand(0);
113 /// Helper which calls const Value *GetRCIdentityRoot(const Value *V) and just
114 /// casts away the const of the result. For documentation about what an
115 /// RCIdentityRoot (and by extension GetRCIdentityRoot is) look at that
117 inline Value *GetRCIdentityRoot(Value *V) {
118 return const_cast<Value *>(GetRCIdentityRoot((const Value *)V));
121 /// \brief Assuming the given instruction is one of the special calls such as
122 /// objc_retain or objc_release, return the RCIdentity root of the argument of
124 inline Value *GetArgRCIdentityRoot(Value *Inst) {
125 return GetRCIdentityRoot(cast<CallInst>(Inst)->getArgOperand(0));
128 inline bool IsNullOrUndef(const Value *V) {
129 return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
132 inline bool IsNoopInstruction(const Instruction *I) {
133 return isa<BitCastInst>(I) ||
134 (isa<GetElementPtrInst>(I) &&
135 cast<GetElementPtrInst>(I)->hasAllZeroIndices());
138 /// \brief Test whether the given value is possible a retainable object pointer.
139 inline bool IsPotentialRetainableObjPtr(const Value *Op) {
140 // Pointers to static or stack storage are not valid retainable object
142 if (isa<Constant>(Op) || isa<AllocaInst>(Op))
144 // Special arguments can not be a valid retainable object pointer.
145 if (const Argument *Arg = dyn_cast<Argument>(Op))
146 if (Arg->hasByValAttr() ||
147 Arg->hasInAllocaAttr() ||
148 Arg->hasNestAttr() ||
149 Arg->hasStructRetAttr())
151 // Only consider values with pointer types.
153 // It seemes intuitive to exclude function pointer types as well, since
154 // functions are never retainable object pointers, however clang occasionally
155 // bitcasts retainable object pointers to function-pointer type temporarily.
156 PointerType *Ty = dyn_cast<PointerType>(Op->getType());
159 // Conservatively assume anything else is a potential retainable object
164 inline bool IsPotentialRetainableObjPtr(const Value *Op,
166 // First make the rudimentary check.
167 if (!IsPotentialRetainableObjPtr(Op))
170 // Objects in constant memory are not reference-counted.
171 if (AA.pointsToConstantMemory(Op))
174 // Pointers in constant memory are not pointing to reference-counted objects.
175 if (const LoadInst *LI = dyn_cast<LoadInst>(Op))
176 if (AA.pointsToConstantMemory(LI->getPointerOperand()))
179 // Otherwise assume the worst.
183 /// \brief Helper for GetARCInstKind. Determines what kind of construct CS
185 inline ARCInstKind GetCallSiteClass(ImmutableCallSite CS) {
186 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
188 if (IsPotentialRetainableObjPtr(*I))
189 return CS.onlyReadsMemory() ? ARCInstKind::User : ARCInstKind::CallOrUser;
191 return CS.onlyReadsMemory() ? ARCInstKind::None : ARCInstKind::Call;
194 /// \brief Return true if this value refers to a distinct and identifiable
197 /// This is similar to AliasAnalysis's isIdentifiedObject, except that it uses
198 /// special knowledge of ObjC conventions.
199 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) ||
208 if (const LoadInst *LI = dyn_cast<LoadInst>(V)) {
209 const Value *Pointer =
210 GetRCIdentityRoot(LI->getPointerOperand());
211 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Pointer)) {
212 // A constant pointer can't be pointing to an object on the heap. It may
213 // be reference-counted, but it won't be deleted.
214 if (GV->isConstant())
216 StringRef Name = GV->getName();
217 // These special variables are known to hold values which are not
218 // reference-counted pointers.
219 if (Name.startswith("\01l_objc_msgSend_fixup_"))
222 StringRef Section = GV->getSection();
223 if (Section.find("__message_refs") != StringRef::npos ||
224 Section.find("__objc_classrefs") != StringRef::npos ||
225 Section.find("__objc_superrefs") != StringRef::npos ||
226 Section.find("__objc_methname") != StringRef::npos ||
227 Section.find("__cstring") != StringRef::npos)
235 enum class ARCMDKindID {
241 /// A cache of MDKinds used by various ARC optimizations.
242 class ARCMDKindCache {
245 /// The Metadata Kind for clang.imprecise_release metadata.
246 llvm::Optional<unsigned> ImpreciseReleaseMDKind;
248 /// The Metadata Kind for clang.arc.copy_on_escape metadata.
249 llvm::Optional<unsigned> CopyOnEscapeMDKind;
251 /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata.
252 llvm::Optional<unsigned> NoObjCARCExceptionsMDKind;
255 void init(Module *Mod) {
257 ImpreciseReleaseMDKind = NoneType::None;
258 CopyOnEscapeMDKind = NoneType::None;
259 NoObjCARCExceptionsMDKind = NoneType::None;
262 unsigned get(ARCMDKindID ID) {
264 case ARCMDKindID::ImpreciseRelease:
265 if (!ImpreciseReleaseMDKind)
266 ImpreciseReleaseMDKind =
267 M->getContext().getMDKindID("clang.imprecise_release");
268 return *ImpreciseReleaseMDKind;
269 case ARCMDKindID::CopyOnEscape:
270 if (!CopyOnEscapeMDKind)
272 M->getContext().getMDKindID("clang.arc.copy_on_escape");
273 return *CopyOnEscapeMDKind;
274 case ARCMDKindID::NoObjCARCExceptions:
275 if (!NoObjCARCExceptionsMDKind)
276 NoObjCARCExceptionsMDKind =
277 M->getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
278 return *NoObjCARCExceptionsMDKind;
280 llvm_unreachable("Covered switch isn't covered?!");
284 } // end namespace objcarc
285 } // end namespace llvm