Extracted ObjCARCContract from ObjCARCOpts into its own file.
[oota-llvm.git] / lib / Transforms / ObjCARC / ObjCARC.h
1 //===- ObjCARC.h - ObjC ARC Optimization --------------*- mode: 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
23 #ifndef LLVM_TRANSFORMS_SCALAR_OBJCARC_H
24 #define LLVM_TRANSFORMS_SCALAR_OBJCARC_H
25
26 #include "llvm/ADT/StringSwitch.h"
27 #include "llvm/Analysis/AliasAnalysis.h"
28 #include "llvm/Analysis/Passes.h"
29 #include "llvm/Analysis/ValueTracking.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/Pass.h"
32 #include "llvm/Support/CallSite.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/InstIterator.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Transforms/ObjCARC.h"
37 #include "llvm/Transforms/Utils/Local.h"
38
39 namespace llvm {
40 namespace objcarc {
41
42 /// \brief A handy option to enable/disable all ARC Optimizations.
43 extern bool EnableARCOpts;
44
45 /// \brief Test if the given module looks interesting to run ARC optimization
46 /// on.
47 static inline bool ModuleHasARC(const Module &M) {
48   return
49     M.getNamedValue("objc_retain") ||
50     M.getNamedValue("objc_release") ||
51     M.getNamedValue("objc_autorelease") ||
52     M.getNamedValue("objc_retainAutoreleasedReturnValue") ||
53     M.getNamedValue("objc_retainBlock") ||
54     M.getNamedValue("objc_autoreleaseReturnValue") ||
55     M.getNamedValue("objc_autoreleasePoolPush") ||
56     M.getNamedValue("objc_loadWeakRetained") ||
57     M.getNamedValue("objc_loadWeak") ||
58     M.getNamedValue("objc_destroyWeak") ||
59     M.getNamedValue("objc_storeWeak") ||
60     M.getNamedValue("objc_initWeak") ||
61     M.getNamedValue("objc_moveWeak") ||
62     M.getNamedValue("objc_copyWeak") ||
63     M.getNamedValue("objc_retainedObject") ||
64     M.getNamedValue("objc_unretainedObject") ||
65     M.getNamedValue("objc_unretainedPointer");
66 }
67
68 /// \enum InstructionClass
69 /// \brief A simple classification for instructions.
70 enum InstructionClass {
71   IC_Retain,              ///< objc_retain
72   IC_RetainRV,            ///< objc_retainAutoreleasedReturnValue
73   IC_RetainBlock,         ///< objc_retainBlock
74   IC_Release,             ///< objc_release
75   IC_Autorelease,         ///< objc_autorelease
76   IC_AutoreleaseRV,       ///< objc_autoreleaseReturnValue
77   IC_AutoreleasepoolPush, ///< objc_autoreleasePoolPush
78   IC_AutoreleasepoolPop,  ///< objc_autoreleasePoolPop
79   IC_NoopCast,            ///< objc_retainedObject, etc.
80   IC_FusedRetainAutorelease, ///< objc_retainAutorelease
81   IC_FusedRetainAutoreleaseRV, ///< objc_retainAutoreleaseReturnValue
82   IC_LoadWeakRetained,    ///< objc_loadWeakRetained (primitive)
83   IC_StoreWeak,           ///< objc_storeWeak (primitive)
84   IC_InitWeak,            ///< objc_initWeak (derived)
85   IC_LoadWeak,            ///< objc_loadWeak (derived)
86   IC_MoveWeak,            ///< objc_moveWeak (derived)
87   IC_CopyWeak,            ///< objc_copyWeak (derived)
88   IC_DestroyWeak,         ///< objc_destroyWeak (derived)
89   IC_StoreStrong,         ///< objc_storeStrong (derived)
90   IC_CallOrUser,          ///< could call objc_release and/or "use" pointers
91   IC_Call,                ///< could call objc_release
92   IC_User,                ///< could "use" a pointer
93   IC_None                 ///< anything else
94 };
95
96 raw_ostream &operator<<(raw_ostream &OS, const InstructionClass Class);
97
98 /// \brief Test if the given class is objc_retain or equivalent.
99 static inline bool IsRetain(InstructionClass Class) {
100   return Class == IC_Retain ||
101          Class == IC_RetainRV;
102 }
103
104 /// \brief Test if the given class is objc_autorelease or equivalent.
105 static inline bool IsAutorelease(InstructionClass Class) {
106   return Class == IC_Autorelease ||
107          Class == IC_AutoreleaseRV;
108 }
109
110 /// \brief Test if the given class represents instructions which return their
111 /// argument verbatim.
112 static inline bool IsForwarding(InstructionClass Class) {
113   // objc_retainBlock technically doesn't always return its argument
114   // verbatim, but it doesn't matter for our purposes here.
115   return Class == IC_Retain ||
116          Class == IC_RetainRV ||
117          Class == IC_Autorelease ||
118          Class == IC_AutoreleaseRV ||
119          Class == IC_RetainBlock ||
120          Class == IC_NoopCast;
121 }
122
123 /// \brief Test if the given class represents instructions which do nothing if
124 /// passed a null pointer.
125 static inline bool IsNoopOnNull(InstructionClass Class) {
126   return Class == IC_Retain ||
127          Class == IC_RetainRV ||
128          Class == IC_Release ||
129          Class == IC_Autorelease ||
130          Class == IC_AutoreleaseRV ||
131          Class == IC_RetainBlock;
132 }
133
134 /// \brief Test if the given class represents instructions which are always safe
135 /// to mark with the "tail" keyword.
136 static inline bool IsAlwaysTail(InstructionClass Class) {
137   // IC_RetainBlock may be given a stack argument.
138   return Class == IC_Retain ||
139          Class == IC_RetainRV ||
140          Class == IC_AutoreleaseRV;
141 }
142
143 /// \brief Test if the given class represents instructions which are never safe
144 /// to mark with the "tail" keyword.
145 static inline bool IsNeverTail(InstructionClass Class) {
146   /// It is never safe to tail call objc_autorelease since by tail calling
147   /// objc_autorelease, we also tail call -[NSObject autorelease] which supports
148   /// fast autoreleasing causing our object to be potentially reclaimed from the
149   /// autorelease pool which violates the semantics of __autoreleasing types in
150   /// ARC.
151   return Class == IC_Autorelease;
152 }
153
154 /// \brief Test if the given class represents instructions which are always safe
155 /// to mark with the nounwind attribute.
156 static inline bool IsNoThrow(InstructionClass Class) {
157   // objc_retainBlock is not nounwind because it calls user copy constructors
158   // which could theoretically throw.
159   return Class == IC_Retain ||
160          Class == IC_RetainRV ||
161          Class == IC_Release ||
162          Class == IC_Autorelease ||
163          Class == IC_AutoreleaseRV ||
164          Class == IC_AutoreleasepoolPush ||
165          Class == IC_AutoreleasepoolPop;
166 }
167
168 /// Test whether the given instruction can autorelease any pointer or cause an
169 /// autoreleasepool pop.
170 static inline bool
171 CanInterruptRV(InstructionClass Class) {
172   switch (Class) {
173   case IC_AutoreleasepoolPop:
174   case IC_CallOrUser:
175   case IC_Call:
176   case IC_Autorelease:
177   case IC_AutoreleaseRV:
178   case IC_FusedRetainAutorelease:
179   case IC_FusedRetainAutoreleaseRV:
180     return true;
181   default:
182     return false;
183   }
184 }
185
186 /// \brief Determine if F is one of the special known Functions.  If it isn't,
187 /// return IC_CallOrUser.
188 InstructionClass GetFunctionClass(const Function *F);
189
190 /// \brief Determine which objc runtime call instruction class V belongs to.
191 ///
192 /// This is similar to GetInstructionClass except that it only detects objc
193 /// runtime calls. This allows it to be faster.
194 ///
195 static inline InstructionClass GetBasicInstructionClass(const Value *V) {
196   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
197     if (const Function *F = CI->getCalledFunction())
198       return GetFunctionClass(F);
199     // Otherwise, be conservative.
200     return IC_CallOrUser;
201   }
202
203   // Otherwise, be conservative.
204   return isa<InvokeInst>(V) ? IC_CallOrUser : IC_User;
205 }
206
207 /// \brief Determine what kind of construct V is.
208 InstructionClass GetInstructionClass(const Value *V);
209
210 /// \brief This is a wrapper around getUnderlyingObject which also knows how to
211 /// look through objc_retain and objc_autorelease calls, which we know to return
212 /// their argument verbatim.
213 static inline const Value *GetUnderlyingObjCPtr(const Value *V) {
214   for (;;) {
215     V = GetUnderlyingObject(V);
216     if (!IsForwarding(GetBasicInstructionClass(V)))
217       break;
218     V = cast<CallInst>(V)->getArgOperand(0);
219   }
220
221   return V;
222 }
223
224 /// \brief This is a wrapper around Value::stripPointerCasts which also knows
225 /// how to look through objc_retain and objc_autorelease calls, which we know to
226 /// return their argument verbatim.
227 static inline const Value *StripPointerCastsAndObjCCalls(const Value *V) {
228   for (;;) {
229     V = V->stripPointerCasts();
230     if (!IsForwarding(GetBasicInstructionClass(V)))
231       break;
232     V = cast<CallInst>(V)->getArgOperand(0);
233   }
234   return V;
235 }
236
237 /// \brief This is a wrapper around Value::stripPointerCasts which also knows
238 /// how to look through objc_retain and objc_autorelease calls, which we know to
239 /// return their argument verbatim.
240 static inline Value *StripPointerCastsAndObjCCalls(Value *V) {
241   for (;;) {
242     V = V->stripPointerCasts();
243     if (!IsForwarding(GetBasicInstructionClass(V)))
244       break;
245     V = cast<CallInst>(V)->getArgOperand(0);
246   }
247   return V;
248 }
249
250 /// \brief Assuming the given instruction is one of the special calls such as
251 /// objc_retain or objc_release, return the argument value, stripped of no-op
252 /// casts and forwarding calls.
253 static inline Value *GetObjCArg(Value *Inst) {
254   return StripPointerCastsAndObjCCalls(cast<CallInst>(Inst)->getArgOperand(0));
255 }
256
257 static inline bool isNullOrUndef(const Value *V) {
258   return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
259 }
260
261 static inline bool isNoopInstruction(const Instruction *I) {
262   return isa<BitCastInst>(I) ||
263     (isa<GetElementPtrInst>(I) &&
264      cast<GetElementPtrInst>(I)->hasAllZeroIndices());
265 }
266
267
268 /// \brief Erase the given instruction.
269 ///
270 /// Many ObjC calls return their argument verbatim,
271 /// so if it's such a call and the return value has users, replace them with the
272 /// argument value.
273 ///
274 static inline void EraseInstruction(Instruction *CI) {
275   Value *OldArg = cast<CallInst>(CI)->getArgOperand(0);
276
277   bool Unused = CI->use_empty();
278
279   if (!Unused) {
280     // Replace the return value with the argument.
281     assert(IsForwarding(GetBasicInstructionClass(CI)) &&
282            "Can't delete non-forwarding instruction with users!");
283     CI->replaceAllUsesWith(OldArg);
284   }
285
286   CI->eraseFromParent();
287
288   if (Unused)
289     RecursivelyDeleteTriviallyDeadInstructions(OldArg);
290 }
291
292 /// \brief Test whether the given value is possible a retainable object pointer.
293 static inline bool IsPotentialRetainableObjPtr(const Value *Op) {
294   // Pointers to static or stack storage are not valid retainable object pointers.
295   if (isa<Constant>(Op) || isa<AllocaInst>(Op))
296     return false;
297   // Special arguments can not be a valid retainable object pointer.
298   if (const Argument *Arg = dyn_cast<Argument>(Op))
299     if (Arg->hasByValAttr() ||
300         Arg->hasNestAttr() ||
301         Arg->hasStructRetAttr())
302       return false;
303   // Only consider values with pointer types.
304   //
305   // It seemes intuitive to exclude function pointer types as well, since
306   // functions are never retainable object pointers, however clang occasionally
307   // bitcasts retainable object pointers to function-pointer type temporarily.
308   PointerType *Ty = dyn_cast<PointerType>(Op->getType());
309   if (!Ty)
310     return false;
311   // Conservatively assume anything else is a potential retainable object pointer.
312   return true;
313 }
314
315 static inline bool IsPotentialRetainableObjPtr(const Value *Op,
316                                                AliasAnalysis &AA) {
317   // First make the rudimentary check.
318   if (!IsPotentialRetainableObjPtr(Op))
319     return false;
320
321   // Objects in constant memory are not reference-counted.
322   if (AA.pointsToConstantMemory(Op))
323     return false;
324
325   // Pointers in constant memory are not pointing to reference-counted objects.
326   if (const LoadInst *LI = dyn_cast<LoadInst>(Op))
327     if (AA.pointsToConstantMemory(LI->getPointerOperand()))
328       return false;
329
330   // Otherwise assume the worst.
331   return true;
332 }
333
334 /// \brief Helper for GetInstructionClass. Determines what kind of construct CS
335 /// is.
336 static inline InstructionClass GetCallSiteClass(ImmutableCallSite CS) {
337   for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
338        I != E; ++I)
339     if (IsPotentialRetainableObjPtr(*I))
340       return CS.onlyReadsMemory() ? IC_User : IC_CallOrUser;
341
342   return CS.onlyReadsMemory() ? IC_None : IC_Call;
343 }
344
345 /// \brief Return true if this value refers to a distinct and identifiable
346 /// object.
347 ///
348 /// This is similar to AliasAnalysis's isIdentifiedObject, except that it uses
349 /// special knowledge of ObjC conventions.
350 static inline bool IsObjCIdentifiedObject(const Value *V) {
351   // Assume that call results and arguments have their own "provenance".
352   // Constants (including GlobalVariables) and Allocas are never
353   // reference-counted.
354   if (isa<CallInst>(V) || isa<InvokeInst>(V) ||
355       isa<Argument>(V) || isa<Constant>(V) ||
356       isa<AllocaInst>(V))
357     return true;
358
359   if (const LoadInst *LI = dyn_cast<LoadInst>(V)) {
360     const Value *Pointer =
361       StripPointerCastsAndObjCCalls(LI->getPointerOperand());
362     if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Pointer)) {
363       // A constant pointer can't be pointing to an object on the heap. It may
364       // be reference-counted, but it won't be deleted.
365       if (GV->isConstant())
366         return true;
367       StringRef Name = GV->getName();
368       // These special variables are known to hold values which are not
369       // reference-counted pointers.
370       if (Name.startswith("\01L_OBJC_SELECTOR_REFERENCES_") ||
371           Name.startswith("\01L_OBJC_CLASSLIST_REFERENCES_") ||
372           Name.startswith("\01L_OBJC_CLASSLIST_SUP_REFS_$_") ||
373           Name.startswith("\01L_OBJC_METH_VAR_NAME_") ||
374           Name.startswith("\01l_objc_msgSend_fixup_"))
375         return true;
376     }
377   }
378
379   return false;
380 }
381
382 } // end namespace objcarc
383 } // end namespace llvm
384
385 #endif // LLVM_TRANSFORMS_SCALAR_OBJCARC_H