blob: 66fcc98c2a18f36fbb8df0b5654517cce7b72445 [file] [log] [blame]
Michael Gottesman6eb95dc2013-07-10 18:49:00 +00001//===- ObjCARC.h - ObjC ARC Optimization --------------*- C++ -*-----------===//
Michael Gottesman08904e32013-01-28 03:28:38 +00002//
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
Benjamin Kramera7c40ef2014-08-13 16:26:38 +000023#ifndef LLVM_LIB_TRANSFORMS_OBJCARC_OBJCARC_H
24#define LLVM_LIB_TRANSFORMS_OBJCARC_OBJCARC_H
Michael Gottesman08904e32013-01-28 03:28:38 +000025
26#include "llvm/ADT/StringSwitch.h"
27#include "llvm/Analysis/AliasAnalysis.h"
28#include "llvm/Analysis/Passes.h"
Michael Gottesman294e7da2013-01-28 05:51:54 +000029#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000030#include "llvm/IR/CallSite.h"
Chandler Carruth83948572014-03-04 10:30:26 +000031#include "llvm/IR/InstIterator.h"
Michael Gottesman08904e32013-01-28 03:28:38 +000032#include "llvm/IR/Module.h"
33#include "llvm/Pass.h"
Michael Gottesman08904e32013-01-28 03:28:38 +000034#include "llvm/Transforms/ObjCARC.h"
Michael Gottesman778138e2013-01-29 03:03:03 +000035#include "llvm/Transforms/Utils/Local.h"
Michael Gottesman08904e32013-01-28 03:28:38 +000036
37namespace llvm {
Michael Gottesman13a5f1a2013-01-29 04:51:59 +000038class raw_ostream;
39}
40
41namespace llvm {
Michael Gottesman08904e32013-01-28 03:28:38 +000042namespace objcarc {
43
44/// \brief A handy option to enable/disable all ARC Optimizations.
45extern bool EnableARCOpts;
46
47/// \brief Test if the given module looks interesting to run ARC optimization
48/// on.
49static inline bool ModuleHasARC(const Module &M) {
50 return
51 M.getNamedValue("objc_retain") ||
52 M.getNamedValue("objc_release") ||
53 M.getNamedValue("objc_autorelease") ||
54 M.getNamedValue("objc_retainAutoreleasedReturnValue") ||
55 M.getNamedValue("objc_retainBlock") ||
56 M.getNamedValue("objc_autoreleaseReturnValue") ||
57 M.getNamedValue("objc_autoreleasePoolPush") ||
58 M.getNamedValue("objc_loadWeakRetained") ||
59 M.getNamedValue("objc_loadWeak") ||
60 M.getNamedValue("objc_destroyWeak") ||
61 M.getNamedValue("objc_storeWeak") ||
62 M.getNamedValue("objc_initWeak") ||
63 M.getNamedValue("objc_moveWeak") ||
64 M.getNamedValue("objc_copyWeak") ||
65 M.getNamedValue("objc_retainedObject") ||
66 M.getNamedValue("objc_unretainedObject") ||
Michael Gottesman3b8f8772013-03-29 21:15:23 +000067 M.getNamedValue("objc_unretainedPointer") ||
68 M.getNamedValue("clang.arc.use");
Michael Gottesman08904e32013-01-28 03:28:38 +000069}
70
71/// \enum InstructionClass
72/// \brief A simple classification for instructions.
73enum InstructionClass {
74 IC_Retain, ///< objc_retain
75 IC_RetainRV, ///< objc_retainAutoreleasedReturnValue
76 IC_RetainBlock, ///< objc_retainBlock
77 IC_Release, ///< objc_release
78 IC_Autorelease, ///< objc_autorelease
79 IC_AutoreleaseRV, ///< objc_autoreleaseReturnValue
80 IC_AutoreleasepoolPush, ///< objc_autoreleasePoolPush
81 IC_AutoreleasepoolPop, ///< objc_autoreleasePoolPop
82 IC_NoopCast, ///< objc_retainedObject, etc.
83 IC_FusedRetainAutorelease, ///< objc_retainAutorelease
84 IC_FusedRetainAutoreleaseRV, ///< objc_retainAutoreleaseReturnValue
85 IC_LoadWeakRetained, ///< objc_loadWeakRetained (primitive)
86 IC_StoreWeak, ///< objc_storeWeak (primitive)
87 IC_InitWeak, ///< objc_initWeak (derived)
88 IC_LoadWeak, ///< objc_loadWeak (derived)
89 IC_MoveWeak, ///< objc_moveWeak (derived)
90 IC_CopyWeak, ///< objc_copyWeak (derived)
91 IC_DestroyWeak, ///< objc_destroyWeak (derived)
92 IC_StoreStrong, ///< objc_storeStrong (derived)
John McCall20182ac2013-03-22 21:38:36 +000093 IC_IntrinsicUser, ///< clang.arc.use
Michael Gottesman08904e32013-01-28 03:28:38 +000094 IC_CallOrUser, ///< could call objc_release and/or "use" pointers
95 IC_Call, ///< could call objc_release
96 IC_User, ///< could "use" a pointer
97 IC_None ///< anything else
98};
99
Michael Gottesman5ed40af2013-01-28 06:39:31 +0000100raw_ostream &operator<<(raw_ostream &OS, const InstructionClass Class);
Michael Gottesman08904e32013-01-28 03:28:38 +0000101
John McCall20182ac2013-03-22 21:38:36 +0000102/// \brief Test if the given class is a kind of user.
103inline static bool IsUser(InstructionClass Class) {
104 return Class == IC_User ||
105 Class == IC_CallOrUser ||
106 Class == IC_IntrinsicUser;
107}
108
Michael Gottesman294e7da2013-01-28 05:51:54 +0000109/// \brief Test if the given class is objc_retain or equivalent.
110static inline bool IsRetain(InstructionClass Class) {
111 return Class == IC_Retain ||
112 Class == IC_RetainRV;
113}
114
115/// \brief Test if the given class is objc_autorelease or equivalent.
116static inline bool IsAutorelease(InstructionClass Class) {
117 return Class == IC_Autorelease ||
118 Class == IC_AutoreleaseRV;
119}
120
121/// \brief Test if the given class represents instructions which return their
122/// argument verbatim.
123static inline bool IsForwarding(InstructionClass Class) {
Michael Gottesman294e7da2013-01-28 05:51:54 +0000124 return Class == IC_Retain ||
125 Class == IC_RetainRV ||
126 Class == IC_Autorelease ||
127 Class == IC_AutoreleaseRV ||
Michael Gottesman294e7da2013-01-28 05:51:54 +0000128 Class == IC_NoopCast;
129}
130
131/// \brief Test if the given class represents instructions which do nothing if
132/// passed a null pointer.
133static inline bool IsNoopOnNull(InstructionClass Class) {
134 return Class == IC_Retain ||
135 Class == IC_RetainRV ||
136 Class == IC_Release ||
137 Class == IC_Autorelease ||
138 Class == IC_AutoreleaseRV ||
139 Class == IC_RetainBlock;
140}
141
142/// \brief Test if the given class represents instructions which are always safe
143/// to mark with the "tail" keyword.
144static inline bool IsAlwaysTail(InstructionClass Class) {
145 // IC_RetainBlock may be given a stack argument.
146 return Class == IC_Retain ||
147 Class == IC_RetainRV ||
148 Class == IC_AutoreleaseRV;
149}
150
151/// \brief Test if the given class represents instructions which are never safe
152/// to mark with the "tail" keyword.
153static inline bool IsNeverTail(InstructionClass Class) {
154 /// It is never safe to tail call objc_autorelease since by tail calling
155 /// objc_autorelease, we also tail call -[NSObject autorelease] which supports
156 /// fast autoreleasing causing our object to be potentially reclaimed from the
157 /// autorelease pool which violates the semantics of __autoreleasing types in
158 /// ARC.
159 return Class == IC_Autorelease;
160}
161
162/// \brief Test if the given class represents instructions which are always safe
163/// to mark with the nounwind attribute.
164static inline bool IsNoThrow(InstructionClass Class) {
165 // objc_retainBlock is not nounwind because it calls user copy constructors
166 // which could theoretically throw.
167 return Class == IC_Retain ||
168 Class == IC_RetainRV ||
169 Class == IC_Release ||
170 Class == IC_Autorelease ||
171 Class == IC_AutoreleaseRV ||
172 Class == IC_AutoreleasepoolPush ||
173 Class == IC_AutoreleasepoolPop;
174}
Michael Gottesman08904e32013-01-28 03:28:38 +0000175
Michael Gottesman778138e2013-01-29 03:03:03 +0000176/// Test whether the given instruction can autorelease any pointer or cause an
177/// autoreleasepool pop.
178static inline bool
179CanInterruptRV(InstructionClass Class) {
180 switch (Class) {
181 case IC_AutoreleasepoolPop:
182 case IC_CallOrUser:
183 case IC_Call:
184 case IC_Autorelease:
185 case IC_AutoreleaseRV:
186 case IC_FusedRetainAutorelease:
187 case IC_FusedRetainAutoreleaseRV:
188 return true;
189 default:
190 return false;
191 }
192}
193
Michael Gottesman08904e32013-01-28 03:28:38 +0000194/// \brief Determine if F is one of the special known Functions. If it isn't,
195/// return IC_CallOrUser.
Michael Gottesman5ed40af2013-01-28 06:39:31 +0000196InstructionClass GetFunctionClass(const Function *F);
Michael Gottesman08904e32013-01-28 03:28:38 +0000197
198/// \brief Determine which objc runtime call instruction class V belongs to.
199///
200/// This is similar to GetInstructionClass except that it only detects objc
201/// runtime calls. This allows it to be faster.
202///
203static inline InstructionClass GetBasicInstructionClass(const Value *V) {
204 if (const CallInst *CI = dyn_cast<CallInst>(V)) {
205 if (const Function *F = CI->getCalledFunction())
206 return GetFunctionClass(F);
207 // Otherwise, be conservative.
208 return IC_CallOrUser;
209 }
210
211 // Otherwise, be conservative.
212 return isa<InvokeInst>(V) ? IC_CallOrUser : IC_User;
213}
214
Michael Gottesman778138e2013-01-29 03:03:03 +0000215/// \brief Determine what kind of construct V is.
216InstructionClass GetInstructionClass(const Value *V);
Michael Gottesman294e7da2013-01-28 05:51:54 +0000217
218/// \brief This is a wrapper around getUnderlyingObject which also knows how to
219/// look through objc_retain and objc_autorelease calls, which we know to return
220/// their argument verbatim.
221static inline const Value *GetUnderlyingObjCPtr(const Value *V) {
222 for (;;) {
223 V = GetUnderlyingObject(V);
224 if (!IsForwarding(GetBasicInstructionClass(V)))
225 break;
226 V = cast<CallInst>(V)->getArgOperand(0);
227 }
228
229 return V;
230}
231
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000232/// The RCIdentity root of a value \p V is a dominating value U for which
233/// retaining or releasing U is equivalent to retaining or releasing V. In other
234/// words, ARC operations on \p V are equivalent to ARC operations on \p U.
235///
236/// We use this in the ARC optimizer to make it easier to match up ARC
237/// operations by always mapping ARC operations to RCIdentityRoots instead of
238/// pointers themselves.
239///
240/// The two ways that we see RCIdentical values in ObjC are via:
241///
242/// 1. PointerCasts
243/// 2. Forwarding Calls that return their argument verbatim.
244///
245/// Thus this function strips off pointer casts and forwarding calls. *NOTE*
246/// This implies that two RCIdentical values must alias.
247static inline const Value *GetRCIdentityRoot(const Value *V) {
Michael Gottesman294e7da2013-01-28 05:51:54 +0000248 for (;;) {
249 V = V->stripPointerCasts();
250 if (!IsForwarding(GetBasicInstructionClass(V)))
251 break;
252 V = cast<CallInst>(V)->getArgOperand(0);
253 }
254 return V;
255}
256
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000257/// Helper which calls const Value *GetRCIdentityRoot(const Value *V) and just
258/// casts away the const of the result. For documentation about what an
259/// RCIdentityRoot (and by extension GetRCIdentityRoot is) look at that
260/// function.
261static inline Value *GetRCIdentityRoot(Value *V) {
262 return const_cast<Value *>(GetRCIdentityRoot((const Value *)V));
Michael Gottesman294e7da2013-01-28 05:51:54 +0000263}
264
Michael Gottesman778138e2013-01-29 03:03:03 +0000265/// \brief Assuming the given instruction is one of the special calls such as
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000266/// objc_retain or objc_release, return the RCIdentity root of the argument of
267/// the call.
268static inline Value *GetArgRCIdentityRoot(Value *Inst) {
269 return GetRCIdentityRoot(cast<CallInst>(Inst)->getArgOperand(0));
Michael Gottesman778138e2013-01-29 03:03:03 +0000270}
271
Michael Gottesman65c24812013-03-25 09:27:43 +0000272static inline bool IsNullOrUndef(const Value *V) {
Michael Gottesman778138e2013-01-29 03:03:03 +0000273 return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
274}
275
Michael Gottesman65c24812013-03-25 09:27:43 +0000276static inline bool IsNoopInstruction(const Instruction *I) {
Michael Gottesman778138e2013-01-29 03:03:03 +0000277 return isa<BitCastInst>(I) ||
278 (isa<GetElementPtrInst>(I) &&
279 cast<GetElementPtrInst>(I)->hasAllZeroIndices());
280}
281
282
283/// \brief Erase the given instruction.
284///
285/// Many ObjC calls return their argument verbatim,
286/// so if it's such a call and the return value has users, replace them with the
287/// argument value.
288///
289static inline void EraseInstruction(Instruction *CI) {
290 Value *OldArg = cast<CallInst>(CI)->getArgOperand(0);
291
292 bool Unused = CI->use_empty();
293
294 if (!Unused) {
295 // Replace the return value with the argument.
Michael Gottesmanc1b648f2013-07-08 23:30:23 +0000296 assert((IsForwarding(GetBasicInstructionClass(CI)) ||
297 (IsNoopOnNull(GetBasicInstructionClass(CI)) &&
298 isa<ConstantPointerNull>(OldArg))) &&
Michael Gottesman778138e2013-01-29 03:03:03 +0000299 "Can't delete non-forwarding instruction with users!");
300 CI->replaceAllUsesWith(OldArg);
301 }
302
303 CI->eraseFromParent();
304
305 if (Unused)
306 RecursivelyDeleteTriviallyDeadInstructions(OldArg);
307}
308
309/// \brief Test whether the given value is possible a retainable object pointer.
310static inline bool IsPotentialRetainableObjPtr(const Value *Op) {
Michael Gottesman23a1ee52013-01-29 04:58:30 +0000311 // Pointers to static or stack storage are not valid retainable object
312 // pointers.
Michael Gottesman778138e2013-01-29 03:03:03 +0000313 if (isa<Constant>(Op) || isa<AllocaInst>(Op))
314 return false;
315 // Special arguments can not be a valid retainable object pointer.
316 if (const Argument *Arg = dyn_cast<Argument>(Op))
317 if (Arg->hasByValAttr() ||
Reid Kleckner26af2ca2014-01-28 02:38:36 +0000318 Arg->hasInAllocaAttr() ||
Michael Gottesman778138e2013-01-29 03:03:03 +0000319 Arg->hasNestAttr() ||
320 Arg->hasStructRetAttr())
321 return false;
322 // Only consider values with pointer types.
323 //
324 // It seemes intuitive to exclude function pointer types as well, since
325 // functions are never retainable object pointers, however clang occasionally
326 // bitcasts retainable object pointers to function-pointer type temporarily.
327 PointerType *Ty = dyn_cast<PointerType>(Op->getType());
328 if (!Ty)
329 return false;
Michael Gottesman23a1ee52013-01-29 04:58:30 +0000330 // Conservatively assume anything else is a potential retainable object
331 // pointer.
Michael Gottesman778138e2013-01-29 03:03:03 +0000332 return true;
333}
334
335static inline bool IsPotentialRetainableObjPtr(const Value *Op,
336 AliasAnalysis &AA) {
337 // First make the rudimentary check.
338 if (!IsPotentialRetainableObjPtr(Op))
339 return false;
340
341 // Objects in constant memory are not reference-counted.
342 if (AA.pointsToConstantMemory(Op))
343 return false;
344
345 // Pointers in constant memory are not pointing to reference-counted objects.
346 if (const LoadInst *LI = dyn_cast<LoadInst>(Op))
347 if (AA.pointsToConstantMemory(LI->getPointerOperand()))
348 return false;
349
350 // Otherwise assume the worst.
351 return true;
352}
353
354/// \brief Helper for GetInstructionClass. Determines what kind of construct CS
355/// is.
356static inline InstructionClass GetCallSiteClass(ImmutableCallSite CS) {
357 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
358 I != E; ++I)
359 if (IsPotentialRetainableObjPtr(*I))
360 return CS.onlyReadsMemory() ? IC_User : IC_CallOrUser;
361
362 return CS.onlyReadsMemory() ? IC_None : IC_Call;
363}
364
365/// \brief Return true if this value refers to a distinct and identifiable
366/// object.
367///
368/// This is similar to AliasAnalysis's isIdentifiedObject, except that it uses
369/// special knowledge of ObjC conventions.
370static inline bool IsObjCIdentifiedObject(const Value *V) {
371 // Assume that call results and arguments have their own "provenance".
372 // Constants (including GlobalVariables) and Allocas are never
373 // reference-counted.
374 if (isa<CallInst>(V) || isa<InvokeInst>(V) ||
375 isa<Argument>(V) || isa<Constant>(V) ||
376 isa<AllocaInst>(V))
377 return true;
378
379 if (const LoadInst *LI = dyn_cast<LoadInst>(V)) {
380 const Value *Pointer =
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000381 GetRCIdentityRoot(LI->getPointerOperand());
Michael Gottesman778138e2013-01-29 03:03:03 +0000382 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Pointer)) {
383 // A constant pointer can't be pointing to an object on the heap. It may
384 // be reference-counted, but it won't be deleted.
385 if (GV->isConstant())
386 return true;
387 StringRef Name = GV->getName();
388 // These special variables are known to hold values which are not
389 // reference-counted pointers.
Rafael Espindolaa3b5b602014-11-17 02:28:27 +0000390 if (Name.startswith("\01l_objc_msgSend_fixup_"))
391 return true;
392
393 StringRef Section = GV->getSection();
394 if (Section.find("__message_refs") != StringRef::npos ||
395 Section.find("__objc_classrefs") != StringRef::npos ||
396 Section.find("__objc_superrefs") != StringRef::npos ||
397 Section.find("__objc_methname") != StringRef::npos ||
398 Section.find("__cstring") != StringRef::npos)
Michael Gottesman778138e2013-01-29 03:03:03 +0000399 return true;
400 }
401 }
402
403 return false;
404}
Michael Gottesman294e7da2013-01-28 05:51:54 +0000405
Michael Gottesman08904e32013-01-28 03:28:38 +0000406} // end namespace objcarc
407} // end namespace llvm
408
Benjamin Kramera7c40ef2014-08-13 16:26:38 +0000409#endif