blob: 1607e8e80a5d5b6d58e3f77144048a6f8dd8acae [file] [log] [blame]
John McCall9fbd3182011-06-15 23:37:01 +00001//===- ObjCARC.cpp - ObjC ARC Optimization --------------------------------===//
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//
10// This file defines ObjC ARC optimizations. ARC stands for
11// Automatic Reference Counting and is a system for managing reference counts
12// for objects in Objective C.
13//
14// The optimizations performed include elimination of redundant, partially
15// redundant, and inconsequential reference count operations, elimination of
16// redundant weak pointer operations, pattern-matching and replacement of
17// low-level operations into higher-level operations, and numerous minor
18// simplifications.
19//
20// This file also defines a simple ARC-aware AliasAnalysis.
21//
22// WARNING: This file knows about certain library functions. It recognizes them
Chris Lattner55dc5c72012-05-27 19:37:05 +000023// by name, and hardwires knowledge of their semantics.
John McCall9fbd3182011-06-15 23:37:01 +000024//
25// WARNING: This file knows about how certain Objective-C library functions are
26// used. Naive LLVM IR transformations which would otherwise be
27// behavior-preserving may break these assumptions.
28//
29//===----------------------------------------------------------------------===//
30
31#define DEBUG_TYPE "objc-arc"
John McCall9fbd3182011-06-15 23:37:01 +000032#include "llvm/ADT/DenseMap.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000033#include "llvm/Support/CommandLine.h"
Chandler Carruth58a2cbe2013-01-02 10:22:59 +000034#include "llvm/Support/Debug.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000035#include "llvm/Support/raw_ostream.h"
John McCall9fbd3182011-06-15 23:37:01 +000036using namespace llvm;
37
38// A handy option to enable/disable all optimizations in this file.
39static cl::opt<bool> EnableARCOpts("enable-objc-arc-opts", cl::init(true));
40
41//===----------------------------------------------------------------------===//
42// Misc. Utilities
43//===----------------------------------------------------------------------===//
44
45namespace {
46 /// MapVector - An associative container with fast insertion-order
47 /// (deterministic) iteration over its elements. Plus the special
48 /// blot operation.
49 template<class KeyT, class ValueT>
50 class MapVector {
51 /// Map - Map keys to indices in Vector.
52 typedef DenseMap<KeyT, size_t> MapTy;
53 MapTy Map;
54
55 /// Vector - Keys and values.
56 typedef std::vector<std::pair<KeyT, ValueT> > VectorTy;
57 VectorTy Vector;
58
59 public:
60 typedef typename VectorTy::iterator iterator;
61 typedef typename VectorTy::const_iterator const_iterator;
62 iterator begin() { return Vector.begin(); }
63 iterator end() { return Vector.end(); }
64 const_iterator begin() const { return Vector.begin(); }
65 const_iterator end() const { return Vector.end(); }
66
67#ifdef XDEBUG
68 ~MapVector() {
69 assert(Vector.size() >= Map.size()); // May differ due to blotting.
70 for (typename MapTy::const_iterator I = Map.begin(), E = Map.end();
71 I != E; ++I) {
72 assert(I->second < Vector.size());
73 assert(Vector[I->second].first == I->first);
74 }
75 for (typename VectorTy::const_iterator I = Vector.begin(),
76 E = Vector.end(); I != E; ++I)
77 assert(!I->first ||
78 (Map.count(I->first) &&
79 Map[I->first] == size_t(I - Vector.begin())));
80 }
81#endif
82
Dan Gohman22cc4cc2012-03-02 01:13:53 +000083 ValueT &operator[](const KeyT &Arg) {
John McCall9fbd3182011-06-15 23:37:01 +000084 std::pair<typename MapTy::iterator, bool> Pair =
85 Map.insert(std::make_pair(Arg, size_t(0)));
86 if (Pair.second) {
Dan Gohman22cc4cc2012-03-02 01:13:53 +000087 size_t Num = Vector.size();
88 Pair.first->second = Num;
John McCall9fbd3182011-06-15 23:37:01 +000089 Vector.push_back(std::make_pair(Arg, ValueT()));
Dan Gohman22cc4cc2012-03-02 01:13:53 +000090 return Vector[Num].second;
John McCall9fbd3182011-06-15 23:37:01 +000091 }
92 return Vector[Pair.first->second].second;
93 }
94
95 std::pair<iterator, bool>
96 insert(const std::pair<KeyT, ValueT> &InsertPair) {
97 std::pair<typename MapTy::iterator, bool> Pair =
98 Map.insert(std::make_pair(InsertPair.first, size_t(0)));
99 if (Pair.second) {
Dan Gohman22cc4cc2012-03-02 01:13:53 +0000100 size_t Num = Vector.size();
101 Pair.first->second = Num;
John McCall9fbd3182011-06-15 23:37:01 +0000102 Vector.push_back(InsertPair);
Dan Gohman22cc4cc2012-03-02 01:13:53 +0000103 return std::make_pair(Vector.begin() + Num, true);
John McCall9fbd3182011-06-15 23:37:01 +0000104 }
105 return std::make_pair(Vector.begin() + Pair.first->second, false);
106 }
107
Dan Gohman22cc4cc2012-03-02 01:13:53 +0000108 const_iterator find(const KeyT &Key) const {
John McCall9fbd3182011-06-15 23:37:01 +0000109 typename MapTy::const_iterator It = Map.find(Key);
110 if (It == Map.end()) return Vector.end();
111 return Vector.begin() + It->second;
112 }
113
114 /// blot - This is similar to erase, but instead of removing the element
115 /// from the vector, it just zeros out the key in the vector. This leaves
116 /// iterators intact, but clients must be prepared for zeroed-out keys when
117 /// iterating.
Dan Gohman22cc4cc2012-03-02 01:13:53 +0000118 void blot(const KeyT &Key) {
John McCall9fbd3182011-06-15 23:37:01 +0000119 typename MapTy::iterator It = Map.find(Key);
120 if (It == Map.end()) return;
121 Vector[It->second].first = KeyT();
122 Map.erase(It);
123 }
124
125 void clear() {
126 Map.clear();
127 Vector.clear();
128 }
129 };
130}
131
132//===----------------------------------------------------------------------===//
133// ARC Utilities.
134//===----------------------------------------------------------------------===//
135
Chandler Carruthd04a8d42012-12-03 16:50:05 +0000136#include "llvm/ADT/StringSwitch.h"
137#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +0000138#include "llvm/IR/Intrinsics.h"
139#include "llvm/IR/Module.h"
Dan Gohman0daef3d2012-05-08 23:39:44 +0000140#include "llvm/Support/CallSite.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +0000141#include "llvm/Transforms/Utils/Local.h"
Dan Gohman0daef3d2012-05-08 23:39:44 +0000142
John McCall9fbd3182011-06-15 23:37:01 +0000143namespace {
144 /// InstructionClass - A simple classification for instructions.
145 enum InstructionClass {
146 IC_Retain, ///< objc_retain
147 IC_RetainRV, ///< objc_retainAutoreleasedReturnValue
148 IC_RetainBlock, ///< objc_retainBlock
149 IC_Release, ///< objc_release
150 IC_Autorelease, ///< objc_autorelease
151 IC_AutoreleaseRV, ///< objc_autoreleaseReturnValue
152 IC_AutoreleasepoolPush, ///< objc_autoreleasePoolPush
153 IC_AutoreleasepoolPop, ///< objc_autoreleasePoolPop
154 IC_NoopCast, ///< objc_retainedObject, etc.
155 IC_FusedRetainAutorelease, ///< objc_retainAutorelease
156 IC_FusedRetainAutoreleaseRV, ///< objc_retainAutoreleaseReturnValue
157 IC_LoadWeakRetained, ///< objc_loadWeakRetained (primitive)
158 IC_StoreWeak, ///< objc_storeWeak (primitive)
159 IC_InitWeak, ///< objc_initWeak (derived)
160 IC_LoadWeak, ///< objc_loadWeak (derived)
161 IC_MoveWeak, ///< objc_moveWeak (derived)
162 IC_CopyWeak, ///< objc_copyWeak (derived)
163 IC_DestroyWeak, ///< objc_destroyWeak (derived)
Dan Gohman44234772012-04-13 18:28:58 +0000164 IC_StoreStrong, ///< objc_storeStrong (derived)
John McCall9fbd3182011-06-15 23:37:01 +0000165 IC_CallOrUser, ///< could call objc_release and/or "use" pointers
166 IC_Call, ///< could call objc_release
167 IC_User, ///< could "use" a pointer
168 IC_None ///< anything else
169 };
170}
171
172/// IsPotentialUse - Test whether the given value is possible a
173/// reference-counted pointer.
174static bool IsPotentialUse(const Value *Op) {
175 // Pointers to static or stack storage are not reference-counted pointers.
176 if (isa<Constant>(Op) || isa<AllocaInst>(Op))
177 return false;
178 // Special arguments are not reference-counted.
179 if (const Argument *Arg = dyn_cast<Argument>(Op))
180 if (Arg->hasByValAttr() ||
181 Arg->hasNestAttr() ||
182 Arg->hasStructRetAttr())
183 return false;
Dan Gohmanf9096e42011-12-14 19:10:53 +0000184 // Only consider values with pointer types.
185 // It seemes intuitive to exclude function pointer types as well, since
186 // functions are never reference-counted, however clang occasionally
187 // bitcasts reference-counted pointers to function-pointer type
188 // temporarily.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000189 PointerType *Ty = dyn_cast<PointerType>(Op->getType());
Dan Gohmanf9096e42011-12-14 19:10:53 +0000190 if (!Ty)
John McCall9fbd3182011-06-15 23:37:01 +0000191 return false;
192 // Conservatively assume anything else is a potential use.
193 return true;
194}
195
196/// GetCallSiteClass - Helper for GetInstructionClass. Determines what kind
197/// of construct CS is.
198static InstructionClass GetCallSiteClass(ImmutableCallSite CS) {
199 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
200 I != E; ++I)
201 if (IsPotentialUse(*I))
202 return CS.onlyReadsMemory() ? IC_User : IC_CallOrUser;
203
204 return CS.onlyReadsMemory() ? IC_None : IC_Call;
205}
206
207/// GetFunctionClass - Determine if F is one of the special known Functions.
208/// If it isn't, return IC_CallOrUser.
209static InstructionClass GetFunctionClass(const Function *F) {
210 Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
211
212 // No arguments.
213 if (AI == AE)
214 return StringSwitch<InstructionClass>(F->getName())
215 .Case("objc_autoreleasePoolPush", IC_AutoreleasepoolPush)
216 .Default(IC_CallOrUser);
217
218 // One argument.
219 const Argument *A0 = AI++;
220 if (AI == AE)
221 // Argument is a pointer.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000222 if (PointerType *PTy = dyn_cast<PointerType>(A0->getType())) {
223 Type *ETy = PTy->getElementType();
John McCall9fbd3182011-06-15 23:37:01 +0000224 // Argument is i8*.
225 if (ETy->isIntegerTy(8))
226 return StringSwitch<InstructionClass>(F->getName())
227 .Case("objc_retain", IC_Retain)
228 .Case("objc_retainAutoreleasedReturnValue", IC_RetainRV)
229 .Case("objc_retainBlock", IC_RetainBlock)
230 .Case("objc_release", IC_Release)
231 .Case("objc_autorelease", IC_Autorelease)
232 .Case("objc_autoreleaseReturnValue", IC_AutoreleaseRV)
233 .Case("objc_autoreleasePoolPop", IC_AutoreleasepoolPop)
234 .Case("objc_retainedObject", IC_NoopCast)
235 .Case("objc_unretainedObject", IC_NoopCast)
236 .Case("objc_unretainedPointer", IC_NoopCast)
237 .Case("objc_retain_autorelease", IC_FusedRetainAutorelease)
238 .Case("objc_retainAutorelease", IC_FusedRetainAutorelease)
239 .Case("objc_retainAutoreleaseReturnValue",IC_FusedRetainAutoreleaseRV)
240 .Default(IC_CallOrUser);
241
242 // Argument is i8**
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000243 if (PointerType *Pte = dyn_cast<PointerType>(ETy))
John McCall9fbd3182011-06-15 23:37:01 +0000244 if (Pte->getElementType()->isIntegerTy(8))
245 return StringSwitch<InstructionClass>(F->getName())
246 .Case("objc_loadWeakRetained", IC_LoadWeakRetained)
247 .Case("objc_loadWeak", IC_LoadWeak)
248 .Case("objc_destroyWeak", IC_DestroyWeak)
249 .Default(IC_CallOrUser);
250 }
251
252 // Two arguments, first is i8**.
253 const Argument *A1 = AI++;
254 if (AI == AE)
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000255 if (PointerType *PTy = dyn_cast<PointerType>(A0->getType()))
256 if (PointerType *Pte = dyn_cast<PointerType>(PTy->getElementType()))
John McCall9fbd3182011-06-15 23:37:01 +0000257 if (Pte->getElementType()->isIntegerTy(8))
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000258 if (PointerType *PTy1 = dyn_cast<PointerType>(A1->getType())) {
259 Type *ETy1 = PTy1->getElementType();
John McCall9fbd3182011-06-15 23:37:01 +0000260 // Second argument is i8*
261 if (ETy1->isIntegerTy(8))
262 return StringSwitch<InstructionClass>(F->getName())
263 .Case("objc_storeWeak", IC_StoreWeak)
264 .Case("objc_initWeak", IC_InitWeak)
Dan Gohman44234772012-04-13 18:28:58 +0000265 .Case("objc_storeStrong", IC_StoreStrong)
John McCall9fbd3182011-06-15 23:37:01 +0000266 .Default(IC_CallOrUser);
267 // Second argument is i8**.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000268 if (PointerType *Pte1 = dyn_cast<PointerType>(ETy1))
John McCall9fbd3182011-06-15 23:37:01 +0000269 if (Pte1->getElementType()->isIntegerTy(8))
270 return StringSwitch<InstructionClass>(F->getName())
271 .Case("objc_moveWeak", IC_MoveWeak)
272 .Case("objc_copyWeak", IC_CopyWeak)
273 .Default(IC_CallOrUser);
274 }
275
276 // Anything else.
277 return IC_CallOrUser;
278}
279
280/// GetInstructionClass - Determine what kind of construct V is.
281static InstructionClass GetInstructionClass(const Value *V) {
282 if (const Instruction *I = dyn_cast<Instruction>(V)) {
283 // Any instruction other than bitcast and gep with a pointer operand have a
284 // use of an objc pointer. Bitcasts, GEPs, Selects, PHIs transfer a pointer
285 // to a subsequent use, rather than using it themselves, in this sense.
286 // As a short cut, several other opcodes are known to have no pointer
287 // operands of interest. And ret is never followed by a release, so it's
288 // not interesting to examine.
289 switch (I->getOpcode()) {
290 case Instruction::Call: {
291 const CallInst *CI = cast<CallInst>(I);
292 // Check for calls to special functions.
293 if (const Function *F = CI->getCalledFunction()) {
294 InstructionClass Class = GetFunctionClass(F);
295 if (Class != IC_CallOrUser)
296 return Class;
297
298 // None of the intrinsic functions do objc_release. For intrinsics, the
299 // only question is whether or not they may be users.
300 switch (F->getIntrinsicID()) {
John McCall9fbd3182011-06-15 23:37:01 +0000301 case Intrinsic::returnaddress: case Intrinsic::frameaddress:
302 case Intrinsic::stacksave: case Intrinsic::stackrestore:
303 case Intrinsic::vastart: case Intrinsic::vacopy: case Intrinsic::vaend:
Dan Gohman0daef3d2012-05-08 23:39:44 +0000304 case Intrinsic::objectsize: case Intrinsic::prefetch:
305 case Intrinsic::stackprotector:
306 case Intrinsic::eh_return_i32: case Intrinsic::eh_return_i64:
307 case Intrinsic::eh_typeid_for: case Intrinsic::eh_dwarf_cfa:
308 case Intrinsic::eh_sjlj_lsda: case Intrinsic::eh_sjlj_functioncontext:
309 case Intrinsic::init_trampoline: case Intrinsic::adjust_trampoline:
310 case Intrinsic::lifetime_start: case Intrinsic::lifetime_end:
311 case Intrinsic::invariant_start: case Intrinsic::invariant_end:
John McCall9fbd3182011-06-15 23:37:01 +0000312 // Don't let dbg info affect our results.
313 case Intrinsic::dbg_declare: case Intrinsic::dbg_value:
314 // Short cut: Some intrinsics obviously don't use ObjC pointers.
315 return IC_None;
316 default:
Dan Gohman0daef3d2012-05-08 23:39:44 +0000317 break;
John McCall9fbd3182011-06-15 23:37:01 +0000318 }
319 }
320 return GetCallSiteClass(CI);
321 }
322 case Instruction::Invoke:
323 return GetCallSiteClass(cast<InvokeInst>(I));
324 case Instruction::BitCast:
325 case Instruction::GetElementPtr:
326 case Instruction::Select: case Instruction::PHI:
327 case Instruction::Ret: case Instruction::Br:
328 case Instruction::Switch: case Instruction::IndirectBr:
329 case Instruction::Alloca: case Instruction::VAArg:
330 case Instruction::Add: case Instruction::FAdd:
331 case Instruction::Sub: case Instruction::FSub:
332 case Instruction::Mul: case Instruction::FMul:
333 case Instruction::SDiv: case Instruction::UDiv: case Instruction::FDiv:
334 case Instruction::SRem: case Instruction::URem: case Instruction::FRem:
335 case Instruction::Shl: case Instruction::LShr: case Instruction::AShr:
336 case Instruction::And: case Instruction::Or: case Instruction::Xor:
337 case Instruction::SExt: case Instruction::ZExt: case Instruction::Trunc:
338 case Instruction::IntToPtr: case Instruction::FCmp:
339 case Instruction::FPTrunc: case Instruction::FPExt:
340 case Instruction::FPToUI: case Instruction::FPToSI:
341 case Instruction::UIToFP: case Instruction::SIToFP:
342 case Instruction::InsertElement: case Instruction::ExtractElement:
343 case Instruction::ShuffleVector:
344 case Instruction::ExtractValue:
345 break;
346 case Instruction::ICmp:
347 // Comparing a pointer with null, or any other constant, isn't an
348 // interesting use, because we don't care what the pointer points to, or
349 // about the values of any other dynamic reference-counted pointers.
350 if (IsPotentialUse(I->getOperand(1)))
351 return IC_User;
352 break;
353 default:
354 // For anything else, check all the operands.
Dan Gohmand4464602011-08-22 17:29:37 +0000355 // Note that this includes both operands of a Store: while the first
356 // operand isn't actually being dereferenced, it is being stored to
357 // memory where we can no longer track who might read it and dereference
358 // it, so we have to consider it potentially used.
John McCall9fbd3182011-06-15 23:37:01 +0000359 for (User::const_op_iterator OI = I->op_begin(), OE = I->op_end();
360 OI != OE; ++OI)
361 if (IsPotentialUse(*OI))
362 return IC_User;
363 }
364 }
365
366 // Otherwise, it's totally inert for ARC purposes.
367 return IC_None;
368}
369
370/// GetBasicInstructionClass - Determine what kind of construct V is. This is
371/// similar to GetInstructionClass except that it only detects objc runtine
372/// calls. This allows it to be faster.
373static InstructionClass GetBasicInstructionClass(const Value *V) {
374 if (const CallInst *CI = dyn_cast<CallInst>(V)) {
375 if (const Function *F = CI->getCalledFunction())
376 return GetFunctionClass(F);
377 // Otherwise, be conservative.
378 return IC_CallOrUser;
379 }
380
381 // Otherwise, be conservative.
Dan Gohman2f6263c2012-01-17 20:52:24 +0000382 return isa<InvokeInst>(V) ? IC_CallOrUser : IC_User;
John McCall9fbd3182011-06-15 23:37:01 +0000383}
384
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +0000385/// IsRetain - Test if the given class is objc_retain or
John McCall9fbd3182011-06-15 23:37:01 +0000386/// equivalent.
387static bool IsRetain(InstructionClass Class) {
388 return Class == IC_Retain ||
389 Class == IC_RetainRV;
390}
391
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +0000392/// IsAutorelease - Test if the given class is objc_autorelease or
John McCall9fbd3182011-06-15 23:37:01 +0000393/// equivalent.
394static bool IsAutorelease(InstructionClass Class) {
395 return Class == IC_Autorelease ||
396 Class == IC_AutoreleaseRV;
397}
398
399/// IsForwarding - Test if the given class represents instructions which return
400/// their argument verbatim.
401static bool IsForwarding(InstructionClass Class) {
402 // objc_retainBlock technically doesn't always return its argument
403 // verbatim, but it doesn't matter for our purposes here.
404 return Class == IC_Retain ||
405 Class == IC_RetainRV ||
406 Class == IC_Autorelease ||
407 Class == IC_AutoreleaseRV ||
408 Class == IC_RetainBlock ||
409 Class == IC_NoopCast;
410}
411
412/// IsNoopOnNull - Test if the given class represents instructions which do
413/// nothing if passed a null pointer.
414static bool IsNoopOnNull(InstructionClass Class) {
415 return Class == IC_Retain ||
416 Class == IC_RetainRV ||
417 Class == IC_Release ||
418 Class == IC_Autorelease ||
419 Class == IC_AutoreleaseRV ||
420 Class == IC_RetainBlock;
421}
422
423/// IsAlwaysTail - Test if the given class represents instructions which are
424/// always safe to mark with the "tail" keyword.
425static bool IsAlwaysTail(InstructionClass Class) {
426 // IC_RetainBlock may be given a stack argument.
427 return Class == IC_Retain ||
428 Class == IC_RetainRV ||
John McCall9fbd3182011-06-15 23:37:01 +0000429 Class == IC_AutoreleaseRV;
430}
431
Michael Gottesmane8c161a2013-01-12 01:25:15 +0000432/// \brief Test if the given class represents instructions which are never safe
433/// to mark with the "tail" keyword.
434static bool IsNeverTail(InstructionClass Class) {
435 /// It is never safe to tail call objc_autorelease since by tail calling
436 /// objc_autorelease, we also tail call -[NSObject autorelease] which supports
437 /// fast autoreleasing causing our object to be potentially reclaimed from the
438 /// autorelease pool which violates the semantics of __autoreleasing types in
439 /// ARC.
440 return Class == IC_Autorelease;
441}
442
John McCall9fbd3182011-06-15 23:37:01 +0000443/// IsNoThrow - Test if the given class represents instructions which are always
444/// safe to mark with the nounwind attribute..
445static bool IsNoThrow(InstructionClass Class) {
Dan Gohman1d2fd752011-09-14 18:33:34 +0000446 // objc_retainBlock is not nounwind because it calls user copy constructors
447 // which could theoretically throw.
John McCall9fbd3182011-06-15 23:37:01 +0000448 return Class == IC_Retain ||
449 Class == IC_RetainRV ||
John McCall9fbd3182011-06-15 23:37:01 +0000450 Class == IC_Release ||
451 Class == IC_Autorelease ||
452 Class == IC_AutoreleaseRV ||
453 Class == IC_AutoreleasepoolPush ||
454 Class == IC_AutoreleasepoolPop;
455}
456
Dan Gohman447989c2012-04-27 18:56:31 +0000457/// EraseInstruction - Erase the given instruction. Many ObjC calls return their
John McCall9fbd3182011-06-15 23:37:01 +0000458/// argument verbatim, so if it's such a call and the return value has users,
459/// replace them with the argument value.
460static void EraseInstruction(Instruction *CI) {
461 Value *OldArg = cast<CallInst>(CI)->getArgOperand(0);
462
463 bool Unused = CI->use_empty();
464
465 if (!Unused) {
466 // Replace the return value with the argument.
467 assert(IsForwarding(GetBasicInstructionClass(CI)) &&
468 "Can't delete non-forwarding instruction with users!");
469 CI->replaceAllUsesWith(OldArg);
470 }
471
472 CI->eraseFromParent();
473
474 if (Unused)
475 RecursivelyDeleteTriviallyDeadInstructions(OldArg);
476}
477
478/// GetUnderlyingObjCPtr - This is a wrapper around getUnderlyingObject which
479/// also knows how to look through objc_retain and objc_autorelease calls, which
480/// we know to return their argument verbatim.
481static const Value *GetUnderlyingObjCPtr(const Value *V) {
482 for (;;) {
483 V = GetUnderlyingObject(V);
484 if (!IsForwarding(GetBasicInstructionClass(V)))
485 break;
486 V = cast<CallInst>(V)->getArgOperand(0);
487 }
488
489 return V;
490}
491
492/// StripPointerCastsAndObjCCalls - This is a wrapper around
493/// Value::stripPointerCasts which also knows how to look through objc_retain
494/// and objc_autorelease calls, which we know to return their argument verbatim.
495static const Value *StripPointerCastsAndObjCCalls(const Value *V) {
496 for (;;) {
497 V = V->stripPointerCasts();
498 if (!IsForwarding(GetBasicInstructionClass(V)))
499 break;
500 V = cast<CallInst>(V)->getArgOperand(0);
501 }
502 return V;
503}
504
505/// StripPointerCastsAndObjCCalls - This is a wrapper around
506/// Value::stripPointerCasts which also knows how to look through objc_retain
507/// and objc_autorelease calls, which we know to return their argument verbatim.
508static Value *StripPointerCastsAndObjCCalls(Value *V) {
509 for (;;) {
510 V = V->stripPointerCasts();
511 if (!IsForwarding(GetBasicInstructionClass(V)))
512 break;
513 V = cast<CallInst>(V)->getArgOperand(0);
514 }
515 return V;
516}
517
518/// GetObjCArg - Assuming the given instruction is one of the special calls such
519/// as objc_retain or objc_release, return the argument value, stripped of no-op
520/// casts and forwarding calls.
521static Value *GetObjCArg(Value *Inst) {
522 return StripPointerCastsAndObjCCalls(cast<CallInst>(Inst)->getArgOperand(0));
523}
524
525/// IsObjCIdentifiedObject - This is similar to AliasAnalysis'
526/// isObjCIdentifiedObject, except that it uses special knowledge of
527/// ObjC conventions...
528static bool IsObjCIdentifiedObject(const Value *V) {
529 // Assume that call results and arguments have their own "provenance".
530 // Constants (including GlobalVariables) and Allocas are never
531 // reference-counted.
532 if (isa<CallInst>(V) || isa<InvokeInst>(V) ||
533 isa<Argument>(V) || isa<Constant>(V) ||
534 isa<AllocaInst>(V))
535 return true;
536
537 if (const LoadInst *LI = dyn_cast<LoadInst>(V)) {
538 const Value *Pointer =
539 StripPointerCastsAndObjCCalls(LI->getPointerOperand());
540 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Pointer)) {
Dan Gohman1b31ea82011-08-22 17:29:11 +0000541 // A constant pointer can't be pointing to an object on the heap. It may
542 // be reference-counted, but it won't be deleted.
543 if (GV->isConstant())
544 return true;
John McCall9fbd3182011-06-15 23:37:01 +0000545 StringRef Name = GV->getName();
546 // These special variables are known to hold values which are not
547 // reference-counted pointers.
548 if (Name.startswith("\01L_OBJC_SELECTOR_REFERENCES_") ||
549 Name.startswith("\01L_OBJC_CLASSLIST_REFERENCES_") ||
550 Name.startswith("\01L_OBJC_CLASSLIST_SUP_REFS_$_") ||
551 Name.startswith("\01L_OBJC_METH_VAR_NAME_") ||
552 Name.startswith("\01l_objc_msgSend_fixup_"))
553 return true;
554 }
555 }
556
557 return false;
558}
559
560/// FindSingleUseIdentifiedObject - This is similar to
561/// StripPointerCastsAndObjCCalls but it stops as soon as it finds a value
562/// with multiple uses.
563static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
564 if (Arg->hasOneUse()) {
565 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
566 return FindSingleUseIdentifiedObject(BC->getOperand(0));
567 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
568 if (GEP->hasAllZeroIndices())
569 return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
570 if (IsForwarding(GetBasicInstructionClass(Arg)))
571 return FindSingleUseIdentifiedObject(
572 cast<CallInst>(Arg)->getArgOperand(0));
573 if (!IsObjCIdentifiedObject(Arg))
574 return 0;
575 return Arg;
576 }
577
Dan Gohman0daef3d2012-05-08 23:39:44 +0000578 // If we found an identifiable object but it has multiple uses, but they are
579 // trivial uses, we can still consider this to be a single-use value.
John McCall9fbd3182011-06-15 23:37:01 +0000580 if (IsObjCIdentifiedObject(Arg)) {
581 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
582 UI != UE; ++UI) {
583 const User *U = *UI;
584 if (!U->use_empty() || StripPointerCastsAndObjCCalls(U) != Arg)
585 return 0;
586 }
587
588 return Arg;
589 }
590
591 return 0;
592}
593
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000594/// ModuleHasARC - Test if the given module looks interesting to run ARC
595/// optimization on.
596static bool ModuleHasARC(const Module &M) {
597 return
598 M.getNamedValue("objc_retain") ||
599 M.getNamedValue("objc_release") ||
600 M.getNamedValue("objc_autorelease") ||
601 M.getNamedValue("objc_retainAutoreleasedReturnValue") ||
602 M.getNamedValue("objc_retainBlock") ||
603 M.getNamedValue("objc_autoreleaseReturnValue") ||
604 M.getNamedValue("objc_autoreleasePoolPush") ||
605 M.getNamedValue("objc_loadWeakRetained") ||
606 M.getNamedValue("objc_loadWeak") ||
607 M.getNamedValue("objc_destroyWeak") ||
608 M.getNamedValue("objc_storeWeak") ||
609 M.getNamedValue("objc_initWeak") ||
610 M.getNamedValue("objc_moveWeak") ||
611 M.getNamedValue("objc_copyWeak") ||
612 M.getNamedValue("objc_retainedObject") ||
613 M.getNamedValue("objc_unretainedObject") ||
614 M.getNamedValue("objc_unretainedPointer");
615}
616
Dan Gohman79522dc2012-01-13 00:39:07 +0000617/// DoesObjCBlockEscape - Test whether the given pointer, which is an
618/// Objective C block pointer, does not "escape". This differs from regular
619/// escape analysis in that a use as an argument to a call is not considered
620/// an escape.
621static bool DoesObjCBlockEscape(const Value *BlockPtr) {
622 // Walk the def-use chains.
623 SmallVector<const Value *, 4> Worklist;
624 Worklist.push_back(BlockPtr);
625 do {
626 const Value *V = Worklist.pop_back_val();
627 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
628 UI != UE; ++UI) {
629 const User *UUser = *UI;
630 // Special - Use by a call (callee or argument) is not considered
631 // to be an escape.
Dan Gohman44234772012-04-13 18:28:58 +0000632 switch (GetBasicInstructionClass(UUser)) {
633 case IC_StoreWeak:
634 case IC_InitWeak:
635 case IC_StoreStrong:
636 case IC_Autorelease:
637 case IC_AutoreleaseRV:
638 // These special functions make copies of their pointer arguments.
639 return true;
640 case IC_User:
641 case IC_None:
642 // Use by an instruction which copies the value is an escape if the
643 // result is an escape.
644 if (isa<BitCastInst>(UUser) || isa<GetElementPtrInst>(UUser) ||
645 isa<PHINode>(UUser) || isa<SelectInst>(UUser)) {
646 Worklist.push_back(UUser);
647 continue;
648 }
649 // Use by a load is not an escape.
650 if (isa<LoadInst>(UUser))
651 continue;
652 // Use by a store is not an escape if the use is the address.
653 if (const StoreInst *SI = dyn_cast<StoreInst>(UUser))
654 if (V != SI->getValueOperand())
655 continue;
656 break;
657 default:
658 // Regular calls and other stuff are not considered escapes.
Dan Gohman79522dc2012-01-13 00:39:07 +0000659 continue;
660 }
Dan Gohmana3b08d62012-02-13 22:57:02 +0000661 // Otherwise, conservatively assume an escape.
Dan Gohman79522dc2012-01-13 00:39:07 +0000662 return true;
663 }
664 } while (!Worklist.empty());
665
666 // No escapes found.
667 return false;
668}
669
John McCall9fbd3182011-06-15 23:37:01 +0000670//===----------------------------------------------------------------------===//
671// ARC AliasAnalysis.
672//===----------------------------------------------------------------------===//
673
John McCall9fbd3182011-06-15 23:37:01 +0000674#include "llvm/Analysis/AliasAnalysis.h"
675#include "llvm/Analysis/Passes.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +0000676#include "llvm/Pass.h"
John McCall9fbd3182011-06-15 23:37:01 +0000677
678namespace {
679 /// ObjCARCAliasAnalysis - This is a simple alias analysis
680 /// implementation that uses knowledge of ARC constructs to answer queries.
681 ///
682 /// TODO: This class could be generalized to know about other ObjC-specific
683 /// tricks. Such as knowing that ivars in the non-fragile ABI are non-aliasing
684 /// even though their offsets are dynamic.
685 class ObjCARCAliasAnalysis : public ImmutablePass,
686 public AliasAnalysis {
687 public:
688 static char ID; // Class identification, replacement for typeinfo
689 ObjCARCAliasAnalysis() : ImmutablePass(ID) {
690 initializeObjCARCAliasAnalysisPass(*PassRegistry::getPassRegistry());
691 }
692
693 private:
694 virtual void initializePass() {
695 InitializeAliasAnalysis(this);
696 }
697
698 /// getAdjustedAnalysisPointer - This method is used when a pass implements
699 /// an analysis interface through multiple inheritance. If needed, it
700 /// should override this to adjust the this pointer as needed for the
701 /// specified pass info.
702 virtual void *getAdjustedAnalysisPointer(const void *PI) {
703 if (PI == &AliasAnalysis::ID)
Dan Gohman447989c2012-04-27 18:56:31 +0000704 return static_cast<AliasAnalysis *>(this);
John McCall9fbd3182011-06-15 23:37:01 +0000705 return this;
706 }
707
708 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
709 virtual AliasResult alias(const Location &LocA, const Location &LocB);
710 virtual bool pointsToConstantMemory(const Location &Loc, bool OrLocal);
711 virtual ModRefBehavior getModRefBehavior(ImmutableCallSite CS);
712 virtual ModRefBehavior getModRefBehavior(const Function *F);
713 virtual ModRefResult getModRefInfo(ImmutableCallSite CS,
714 const Location &Loc);
715 virtual ModRefResult getModRefInfo(ImmutableCallSite CS1,
716 ImmutableCallSite CS2);
717 };
718} // End of anonymous namespace
719
720// Register this pass...
721char ObjCARCAliasAnalysis::ID = 0;
722INITIALIZE_AG_PASS(ObjCARCAliasAnalysis, AliasAnalysis, "objc-arc-aa",
723 "ObjC-ARC-Based Alias Analysis", false, true, false)
724
725ImmutablePass *llvm::createObjCARCAliasAnalysisPass() {
726 return new ObjCARCAliasAnalysis();
727}
728
729void
730ObjCARCAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
731 AU.setPreservesAll();
732 AliasAnalysis::getAnalysisUsage(AU);
733}
734
735AliasAnalysis::AliasResult
736ObjCARCAliasAnalysis::alias(const Location &LocA, const Location &LocB) {
737 if (!EnableARCOpts)
738 return AliasAnalysis::alias(LocA, LocB);
739
740 // First, strip off no-ops, including ObjC-specific no-ops, and try making a
741 // precise alias query.
742 const Value *SA = StripPointerCastsAndObjCCalls(LocA.Ptr);
743 const Value *SB = StripPointerCastsAndObjCCalls(LocB.Ptr);
744 AliasResult Result =
745 AliasAnalysis::alias(Location(SA, LocA.Size, LocA.TBAATag),
746 Location(SB, LocB.Size, LocB.TBAATag));
747 if (Result != MayAlias)
748 return Result;
749
750 // If that failed, climb to the underlying object, including climbing through
751 // ObjC-specific no-ops, and try making an imprecise alias query.
752 const Value *UA = GetUnderlyingObjCPtr(SA);
753 const Value *UB = GetUnderlyingObjCPtr(SB);
754 if (UA != SA || UB != SB) {
755 Result = AliasAnalysis::alias(Location(UA), Location(UB));
756 // We can't use MustAlias or PartialAlias results here because
757 // GetUnderlyingObjCPtr may return an offsetted pointer value.
758 if (Result == NoAlias)
759 return NoAlias;
760 }
761
762 // If that failed, fail. We don't need to chain here, since that's covered
763 // by the earlier precise query.
764 return MayAlias;
765}
766
767bool
768ObjCARCAliasAnalysis::pointsToConstantMemory(const Location &Loc,
769 bool OrLocal) {
770 if (!EnableARCOpts)
771 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
772
773 // First, strip off no-ops, including ObjC-specific no-ops, and try making
774 // a precise alias query.
775 const Value *S = StripPointerCastsAndObjCCalls(Loc.Ptr);
776 if (AliasAnalysis::pointsToConstantMemory(Location(S, Loc.Size, Loc.TBAATag),
777 OrLocal))
778 return true;
779
780 // If that failed, climb to the underlying object, including climbing through
781 // ObjC-specific no-ops, and try making an imprecise alias query.
782 const Value *U = GetUnderlyingObjCPtr(S);
783 if (U != S)
784 return AliasAnalysis::pointsToConstantMemory(Location(U), OrLocal);
785
786 // If that failed, fail. We don't need to chain here, since that's covered
787 // by the earlier precise query.
788 return false;
789}
790
791AliasAnalysis::ModRefBehavior
792ObjCARCAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
793 // We have nothing to do. Just chain to the next AliasAnalysis.
794 return AliasAnalysis::getModRefBehavior(CS);
795}
796
797AliasAnalysis::ModRefBehavior
798ObjCARCAliasAnalysis::getModRefBehavior(const Function *F) {
799 if (!EnableARCOpts)
800 return AliasAnalysis::getModRefBehavior(F);
801
802 switch (GetFunctionClass(F)) {
803 case IC_NoopCast:
804 return DoesNotAccessMemory;
805 default:
806 break;
807 }
808
809 return AliasAnalysis::getModRefBehavior(F);
810}
811
812AliasAnalysis::ModRefResult
813ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS, const Location &Loc) {
814 if (!EnableARCOpts)
815 return AliasAnalysis::getModRefInfo(CS, Loc);
816
817 switch (GetBasicInstructionClass(CS.getInstruction())) {
818 case IC_Retain:
819 case IC_RetainRV:
John McCall9fbd3182011-06-15 23:37:01 +0000820 case IC_Autorelease:
821 case IC_AutoreleaseRV:
822 case IC_NoopCast:
823 case IC_AutoreleasepoolPush:
824 case IC_FusedRetainAutorelease:
825 case IC_FusedRetainAutoreleaseRV:
826 // These functions don't access any memory visible to the compiler.
Benjamin Kramerd9b0b022012-06-02 10:20:22 +0000827 // Note that this doesn't include objc_retainBlock, because it updates
Dan Gohman21104822011-09-14 18:13:00 +0000828 // pointers when it copies block data.
John McCall9fbd3182011-06-15 23:37:01 +0000829 return NoModRef;
830 default:
831 break;
832 }
833
834 return AliasAnalysis::getModRefInfo(CS, Loc);
835}
836
837AliasAnalysis::ModRefResult
838ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
839 ImmutableCallSite CS2) {
840 // TODO: Theoretically we could check for dependencies between objc_* calls
841 // and OnlyAccessesArgumentPointees calls or other well-behaved calls.
842 return AliasAnalysis::getModRefInfo(CS1, CS2);
843}
844
845//===----------------------------------------------------------------------===//
846// ARC expansion.
847//===----------------------------------------------------------------------===//
848
849#include "llvm/Support/InstIterator.h"
850#include "llvm/Transforms/Scalar.h"
851
852namespace {
853 /// ObjCARCExpand - Early ARC transformations.
854 class ObjCARCExpand : public FunctionPass {
855 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000856 virtual bool doInitialization(Module &M);
John McCall9fbd3182011-06-15 23:37:01 +0000857 virtual bool runOnFunction(Function &F);
858
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000859 /// Run - A flag indicating whether this optimization pass should run.
860 bool Run;
861
John McCall9fbd3182011-06-15 23:37:01 +0000862 public:
863 static char ID;
864 ObjCARCExpand() : FunctionPass(ID) {
865 initializeObjCARCExpandPass(*PassRegistry::getPassRegistry());
866 }
867 };
868}
869
870char ObjCARCExpand::ID = 0;
871INITIALIZE_PASS(ObjCARCExpand,
872 "objc-arc-expand", "ObjC ARC expansion", false, false)
873
874Pass *llvm::createObjCARCExpandPass() {
875 return new ObjCARCExpand();
876}
877
878void ObjCARCExpand::getAnalysisUsage(AnalysisUsage &AU) const {
879 AU.setPreservesCFG();
880}
881
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000882bool ObjCARCExpand::doInitialization(Module &M) {
883 Run = ModuleHasARC(M);
884 return false;
885}
886
John McCall9fbd3182011-06-15 23:37:01 +0000887bool ObjCARCExpand::runOnFunction(Function &F) {
888 if (!EnableARCOpts)
889 return false;
890
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000891 // If nothing in the Module uses ARC, don't do anything.
892 if (!Run)
893 return false;
894
John McCall9fbd3182011-06-15 23:37:01 +0000895 bool Changed = false;
896
897 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
898 Instruction *Inst = &*I;
Michael Gottesman2f1bfc42013-01-07 21:26:07 +0000899
Michael Gottesman8f22c8b2013-01-01 16:05:48 +0000900 DEBUG(dbgs() << "ObjCARCExpand: Visiting: " << *Inst << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +0000901
John McCall9fbd3182011-06-15 23:37:01 +0000902 switch (GetBasicInstructionClass(Inst)) {
903 case IC_Retain:
904 case IC_RetainRV:
905 case IC_Autorelease:
906 case IC_AutoreleaseRV:
907 case IC_FusedRetainAutorelease:
Michael Gottesmana6e23cc2013-01-01 16:05:54 +0000908 case IC_FusedRetainAutoreleaseRV: {
John McCall9fbd3182011-06-15 23:37:01 +0000909 // These calls return their argument verbatim, as a low-level
910 // optimization. However, this makes high-level optimizations
911 // harder. Undo any uses of this optimization that the front-end
Dan Gohmand6bf2012012-04-13 18:57:48 +0000912 // emitted here. We'll redo them in the contract pass.
John McCall9fbd3182011-06-15 23:37:01 +0000913 Changed = true;
Michael Gottesmana6e23cc2013-01-01 16:05:54 +0000914 Value *Value = cast<CallInst>(Inst)->getArgOperand(0);
915 DEBUG(dbgs() << "ObjCARCExpand: Old = " << *Inst << "\n"
916 " New = " << *Value << "\n");
917 Inst->replaceAllUsesWith(Value);
John McCall9fbd3182011-06-15 23:37:01 +0000918 break;
Michael Gottesmana6e23cc2013-01-01 16:05:54 +0000919 }
John McCall9fbd3182011-06-15 23:37:01 +0000920 default:
921 break;
922 }
923 }
Michael Gottesman2f1bfc42013-01-07 21:26:07 +0000924
Michael Gottesmanec21e2a2013-01-03 08:09:27 +0000925 DEBUG(dbgs() << "ObjCARCExpand: Finished List.\n\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +0000926
John McCall9fbd3182011-06-15 23:37:01 +0000927 return Changed;
928}
929
930//===----------------------------------------------------------------------===//
Dan Gohman2f6263c2012-01-17 20:52:24 +0000931// ARC autorelease pool elimination.
932//===----------------------------------------------------------------------===//
933
Dan Gohman0daef3d2012-05-08 23:39:44 +0000934#include "llvm/ADT/STLExtras.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +0000935#include "llvm/IR/Constants.h"
Dan Gohman1dae3e92012-01-18 21:19:38 +0000936
Dan Gohman2f6263c2012-01-17 20:52:24 +0000937namespace {
938 /// ObjCARCAPElim - Autorelease pool elimination.
939 class ObjCARCAPElim : public ModulePass {
940 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
941 virtual bool runOnModule(Module &M);
942
Dan Gohman447989c2012-04-27 18:56:31 +0000943 static bool MayAutorelease(ImmutableCallSite CS, unsigned Depth = 0);
944 static bool OptimizeBB(BasicBlock *BB);
Dan Gohman2f6263c2012-01-17 20:52:24 +0000945
946 public:
947 static char ID;
948 ObjCARCAPElim() : ModulePass(ID) {
949 initializeObjCARCAPElimPass(*PassRegistry::getPassRegistry());
950 }
951 };
952}
953
954char ObjCARCAPElim::ID = 0;
955INITIALIZE_PASS(ObjCARCAPElim,
956 "objc-arc-apelim",
957 "ObjC ARC autorelease pool elimination",
958 false, false)
959
960Pass *llvm::createObjCARCAPElimPass() {
961 return new ObjCARCAPElim();
962}
963
964void ObjCARCAPElim::getAnalysisUsage(AnalysisUsage &AU) const {
965 AU.setPreservesCFG();
966}
967
968/// MayAutorelease - Interprocedurally determine if calls made by the
969/// given call site can possibly produce autoreleases.
Dan Gohman447989c2012-04-27 18:56:31 +0000970bool ObjCARCAPElim::MayAutorelease(ImmutableCallSite CS, unsigned Depth) {
971 if (const Function *Callee = CS.getCalledFunction()) {
Dan Gohman2f6263c2012-01-17 20:52:24 +0000972 if (Callee->isDeclaration() || Callee->mayBeOverridden())
973 return true;
Dan Gohman447989c2012-04-27 18:56:31 +0000974 for (Function::const_iterator I = Callee->begin(), E = Callee->end();
Dan Gohman2f6263c2012-01-17 20:52:24 +0000975 I != E; ++I) {
Dan Gohman447989c2012-04-27 18:56:31 +0000976 const BasicBlock *BB = I;
977 for (BasicBlock::const_iterator J = BB->begin(), F = BB->end();
978 J != F; ++J)
979 if (ImmutableCallSite JCS = ImmutableCallSite(J))
Dan Gohman2f77bbd2012-01-18 21:24:45 +0000980 // This recursion depth limit is arbitrary. It's just great
981 // enough to cover known interesting testcases.
982 if (Depth < 3 &&
983 !JCS.onlyReadsMemory() &&
984 MayAutorelease(JCS, Depth + 1))
Dan Gohman2f6263c2012-01-17 20:52:24 +0000985 return true;
986 }
987 return false;
988 }
989
990 return true;
991}
992
993bool ObjCARCAPElim::OptimizeBB(BasicBlock *BB) {
994 bool Changed = false;
995
996 Instruction *Push = 0;
997 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
998 Instruction *Inst = I++;
999 switch (GetBasicInstructionClass(Inst)) {
1000 case IC_AutoreleasepoolPush:
1001 Push = Inst;
1002 break;
1003 case IC_AutoreleasepoolPop:
1004 // If this pop matches a push and nothing in between can autorelease,
1005 // zap the pair.
1006 if (Push && cast<CallInst>(Inst)->getArgOperand(0) == Push) {
1007 Changed = true;
Michael Gottesman5c0ae472013-01-04 21:29:57 +00001008 DEBUG(dbgs() << "ObjCARCAPElim::OptimizeBB: Zapping push pop autorelease pair:\n"
Michael Gottesmandf379f42013-01-03 08:09:17 +00001009 << " Pop: " << *Inst << "\n"
1010 << " Push: " << *Push << "\n");
Dan Gohman2f6263c2012-01-17 20:52:24 +00001011 Inst->eraseFromParent();
1012 Push->eraseFromParent();
1013 }
1014 Push = 0;
1015 break;
1016 case IC_CallOrUser:
Dan Gohman447989c2012-04-27 18:56:31 +00001017 if (MayAutorelease(ImmutableCallSite(Inst)))
Dan Gohman2f6263c2012-01-17 20:52:24 +00001018 Push = 0;
1019 break;
1020 default:
1021 break;
1022 }
1023 }
1024
1025 return Changed;
1026}
1027
1028bool ObjCARCAPElim::runOnModule(Module &M) {
1029 if (!EnableARCOpts)
1030 return false;
1031
1032 // If nothing in the Module uses ARC, don't do anything.
1033 if (!ModuleHasARC(M))
1034 return false;
1035
Dan Gohman1dae3e92012-01-18 21:19:38 +00001036 // Find the llvm.global_ctors variable, as the first step in
Dan Gohmand6bf2012012-04-13 18:57:48 +00001037 // identifying the global constructors. In theory, unnecessary autorelease
1038 // pools could occur anywhere, but in practice it's pretty rare. Global
1039 // ctors are a place where autorelease pools get inserted automatically,
1040 // so it's pretty common for them to be unnecessary, and it's pretty
1041 // profitable to eliminate them.
Dan Gohman1dae3e92012-01-18 21:19:38 +00001042 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1043 if (!GV)
1044 return false;
1045
1046 assert(GV->hasDefinitiveInitializer() &&
1047 "llvm.global_ctors is uncooperative!");
1048
Dan Gohman2f6263c2012-01-17 20:52:24 +00001049 bool Changed = false;
1050
Dan Gohman1dae3e92012-01-18 21:19:38 +00001051 // Dig the constructor functions out of GV's initializer.
1052 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
1053 for (User::op_iterator OI = Init->op_begin(), OE = Init->op_end();
1054 OI != OE; ++OI) {
1055 Value *Op = *OI;
1056 // llvm.global_ctors is an array of pairs where the second members
1057 // are constructor functions.
Dan Gohman3b5b2a22012-04-18 22:24:33 +00001058 Function *F = dyn_cast<Function>(cast<ConstantStruct>(Op)->getOperand(1));
1059 // If the user used a constructor function with the wrong signature and
1060 // it got bitcasted or whatever, look the other way.
1061 if (!F)
1062 continue;
Dan Gohman2f6263c2012-01-17 20:52:24 +00001063 // Only look at function definitions.
1064 if (F->isDeclaration())
1065 continue;
Dan Gohman2f6263c2012-01-17 20:52:24 +00001066 // Only look at functions with one basic block.
1067 if (llvm::next(F->begin()) != F->end())
1068 continue;
1069 // Ok, a single-block constructor function definition. Try to optimize it.
1070 Changed |= OptimizeBB(F->begin());
1071 }
1072
1073 return Changed;
1074}
1075
1076//===----------------------------------------------------------------------===//
John McCall9fbd3182011-06-15 23:37:01 +00001077// ARC optimization.
1078//===----------------------------------------------------------------------===//
1079
1080// TODO: On code like this:
1081//
1082// objc_retain(%x)
1083// stuff_that_cannot_release()
1084// objc_autorelease(%x)
1085// stuff_that_cannot_release()
1086// objc_retain(%x)
1087// stuff_that_cannot_release()
1088// objc_autorelease(%x)
1089//
1090// The second retain and autorelease can be deleted.
1091
1092// TODO: It should be possible to delete
1093// objc_autoreleasePoolPush and objc_autoreleasePoolPop
1094// pairs if nothing is actually autoreleased between them. Also, autorelease
1095// calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
1096// after inlining) can be turned into plain release calls.
1097
1098// TODO: Critical-edge splitting. If the optimial insertion point is
1099// a critical edge, the current algorithm has to fail, because it doesn't
1100// know how to split edges. It should be possible to make the optimizer
1101// think in terms of edges, rather than blocks, and then split critical
1102// edges on demand.
1103
1104// TODO: OptimizeSequences could generalized to be Interprocedural.
1105
1106// TODO: Recognize that a bunch of other objc runtime calls have
1107// non-escaping arguments and non-releasing arguments, and may be
1108// non-autoreleasing.
1109
1110// TODO: Sink autorelease calls as far as possible. Unfortunately we
1111// usually can't sink them past other calls, which would be the main
1112// case where it would be useful.
1113
Dan Gohmane6d5e882011-08-19 00:26:36 +00001114// TODO: The pointer returned from objc_loadWeakRetained is retained.
1115
1116// TODO: Delete release+retain pairs (rare).
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00001117
Chandler Carruthd04a8d42012-12-03 16:50:05 +00001118#include "llvm/ADT/SmallPtrSet.h"
1119#include "llvm/ADT/Statistic.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +00001120#include "llvm/IR/LLVMContext.h"
John McCall9fbd3182011-06-15 23:37:01 +00001121#include "llvm/Support/CFG.h"
John McCall9fbd3182011-06-15 23:37:01 +00001122
1123STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
1124STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
1125STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
1126STATISTIC(NumRets, "Number of return value forwarding "
1127 "retain+autoreleaes eliminated");
1128STATISTIC(NumRRs, "Number of retain+release paths eliminated");
1129STATISTIC(NumPeeps, "Number of calls peephole-optimized");
1130
1131namespace {
1132 /// ProvenanceAnalysis - This is similar to BasicAliasAnalysis, and it
1133 /// uses many of the same techniques, except it uses special ObjC-specific
1134 /// reasoning about pointer relationships.
1135 class ProvenanceAnalysis {
1136 AliasAnalysis *AA;
1137
1138 typedef std::pair<const Value *, const Value *> ValuePairTy;
1139 typedef DenseMap<ValuePairTy, bool> CachedResultsTy;
1140 CachedResultsTy CachedResults;
1141
1142 bool relatedCheck(const Value *A, const Value *B);
1143 bool relatedSelect(const SelectInst *A, const Value *B);
1144 bool relatedPHI(const PHINode *A, const Value *B);
1145
Craig Topperc2945e42012-09-18 02:01:41 +00001146 void operator=(const ProvenanceAnalysis &) LLVM_DELETED_FUNCTION;
1147 ProvenanceAnalysis(const ProvenanceAnalysis &) LLVM_DELETED_FUNCTION;
John McCall9fbd3182011-06-15 23:37:01 +00001148
1149 public:
1150 ProvenanceAnalysis() {}
1151
1152 void setAA(AliasAnalysis *aa) { AA = aa; }
1153
1154 AliasAnalysis *getAA() const { return AA; }
1155
1156 bool related(const Value *A, const Value *B);
1157
1158 void clear() {
1159 CachedResults.clear();
1160 }
1161 };
1162}
1163
1164bool ProvenanceAnalysis::relatedSelect(const SelectInst *A, const Value *B) {
1165 // If the values are Selects with the same condition, we can do a more precise
1166 // check: just check for relations between the values on corresponding arms.
1167 if (const SelectInst *SB = dyn_cast<SelectInst>(B))
Dan Gohman447989c2012-04-27 18:56:31 +00001168 if (A->getCondition() == SB->getCondition())
1169 return related(A->getTrueValue(), SB->getTrueValue()) ||
1170 related(A->getFalseValue(), SB->getFalseValue());
John McCall9fbd3182011-06-15 23:37:01 +00001171
1172 // Check both arms of the Select node individually.
Dan Gohman447989c2012-04-27 18:56:31 +00001173 return related(A->getTrueValue(), B) ||
1174 related(A->getFalseValue(), B);
John McCall9fbd3182011-06-15 23:37:01 +00001175}
1176
1177bool ProvenanceAnalysis::relatedPHI(const PHINode *A, const Value *B) {
1178 // If the values are PHIs in the same block, we can do a more precise as well
1179 // as efficient check: just check for relations between the values on
1180 // corresponding edges.
1181 if (const PHINode *PNB = dyn_cast<PHINode>(B))
1182 if (PNB->getParent() == A->getParent()) {
1183 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i)
1184 if (related(A->getIncomingValue(i),
1185 PNB->getIncomingValueForBlock(A->getIncomingBlock(i))))
1186 return true;
1187 return false;
1188 }
1189
1190 // Check each unique source of the PHI node against B.
1191 SmallPtrSet<const Value *, 4> UniqueSrc;
1192 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i) {
1193 const Value *PV1 = A->getIncomingValue(i);
1194 if (UniqueSrc.insert(PV1) && related(PV1, B))
1195 return true;
1196 }
1197
1198 // All of the arms checked out.
1199 return false;
1200}
1201
1202/// isStoredObjCPointer - Test if the value of P, or any value covered by its
1203/// provenance, is ever stored within the function (not counting callees).
1204static bool isStoredObjCPointer(const Value *P) {
1205 SmallPtrSet<const Value *, 8> Visited;
1206 SmallVector<const Value *, 8> Worklist;
1207 Worklist.push_back(P);
1208 Visited.insert(P);
1209 do {
1210 P = Worklist.pop_back_val();
1211 for (Value::const_use_iterator UI = P->use_begin(), UE = P->use_end();
1212 UI != UE; ++UI) {
1213 const User *Ur = *UI;
1214 if (isa<StoreInst>(Ur)) {
1215 if (UI.getOperandNo() == 0)
1216 // The pointer is stored.
1217 return true;
1218 // The pointed is stored through.
1219 continue;
1220 }
1221 if (isa<CallInst>(Ur))
1222 // The pointer is passed as an argument, ignore this.
1223 continue;
1224 if (isa<PtrToIntInst>(P))
1225 // Assume the worst.
1226 return true;
1227 if (Visited.insert(Ur))
1228 Worklist.push_back(Ur);
1229 }
1230 } while (!Worklist.empty());
1231
1232 // Everything checked out.
1233 return false;
1234}
1235
1236bool ProvenanceAnalysis::relatedCheck(const Value *A, const Value *B) {
1237 // Skip past provenance pass-throughs.
1238 A = GetUnderlyingObjCPtr(A);
1239 B = GetUnderlyingObjCPtr(B);
1240
1241 // Quick check.
1242 if (A == B)
1243 return true;
1244
1245 // Ask regular AliasAnalysis, for a first approximation.
1246 switch (AA->alias(A, B)) {
1247 case AliasAnalysis::NoAlias:
1248 return false;
1249 case AliasAnalysis::MustAlias:
1250 case AliasAnalysis::PartialAlias:
1251 return true;
1252 case AliasAnalysis::MayAlias:
1253 break;
1254 }
1255
1256 bool AIsIdentified = IsObjCIdentifiedObject(A);
1257 bool BIsIdentified = IsObjCIdentifiedObject(B);
1258
1259 // An ObjC-Identified object can't alias a load if it is never locally stored.
1260 if (AIsIdentified) {
Dan Gohman230768b2012-09-04 23:16:20 +00001261 // Check for an obvious escape.
1262 if (isa<LoadInst>(B))
1263 return isStoredObjCPointer(A);
John McCall9fbd3182011-06-15 23:37:01 +00001264 if (BIsIdentified) {
Dan Gohman230768b2012-09-04 23:16:20 +00001265 // Check for an obvious escape.
1266 if (isa<LoadInst>(A))
1267 return isStoredObjCPointer(B);
1268 // Both pointers are identified and escapes aren't an evident problem.
1269 return false;
John McCall9fbd3182011-06-15 23:37:01 +00001270 }
Dan Gohman230768b2012-09-04 23:16:20 +00001271 } else if (BIsIdentified) {
1272 // Check for an obvious escape.
1273 if (isa<LoadInst>(A))
John McCall9fbd3182011-06-15 23:37:01 +00001274 return isStoredObjCPointer(B);
1275 }
1276
1277 // Special handling for PHI and Select.
1278 if (const PHINode *PN = dyn_cast<PHINode>(A))
1279 return relatedPHI(PN, B);
1280 if (const PHINode *PN = dyn_cast<PHINode>(B))
1281 return relatedPHI(PN, A);
1282 if (const SelectInst *S = dyn_cast<SelectInst>(A))
1283 return relatedSelect(S, B);
1284 if (const SelectInst *S = dyn_cast<SelectInst>(B))
1285 return relatedSelect(S, A);
1286
1287 // Conservative.
1288 return true;
1289}
1290
1291bool ProvenanceAnalysis::related(const Value *A, const Value *B) {
1292 // Begin by inserting a conservative value into the map. If the insertion
1293 // fails, we have the answer already. If it succeeds, leave it there until we
1294 // compute the real answer to guard against recursive queries.
1295 if (A > B) std::swap(A, B);
1296 std::pair<CachedResultsTy::iterator, bool> Pair =
1297 CachedResults.insert(std::make_pair(ValuePairTy(A, B), true));
1298 if (!Pair.second)
1299 return Pair.first->second;
1300
1301 bool Result = relatedCheck(A, B);
1302 CachedResults[ValuePairTy(A, B)] = Result;
1303 return Result;
1304}
1305
1306namespace {
1307 // Sequence - A sequence of states that a pointer may go through in which an
1308 // objc_retain and objc_release are actually needed.
1309 enum Sequence {
1310 S_None,
1311 S_Retain, ///< objc_retain(x)
1312 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement
1313 S_Use, ///< any use of x
1314 S_Stop, ///< like S_Release, but code motion is stopped
1315 S_Release, ///< objc_release(x)
1316 S_MovableRelease ///< objc_release(x), !clang.imprecise_release
1317 };
1318}
1319
1320static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
1321 // The easy cases.
1322 if (A == B)
1323 return A;
1324 if (A == S_None || B == S_None)
1325 return S_None;
1326
John McCall9fbd3182011-06-15 23:37:01 +00001327 if (A > B) std::swap(A, B);
1328 if (TopDown) {
1329 // Choose the side which is further along in the sequence.
Dan Gohmana7f7db22011-08-12 00:26:31 +00001330 if ((A == S_Retain || A == S_CanRelease) &&
1331 (B == S_CanRelease || B == S_Use))
John McCall9fbd3182011-06-15 23:37:01 +00001332 return B;
1333 } else {
1334 // Choose the side which is further along in the sequence.
1335 if ((A == S_Use || A == S_CanRelease) &&
Dan Gohmana7f7db22011-08-12 00:26:31 +00001336 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
John McCall9fbd3182011-06-15 23:37:01 +00001337 return A;
1338 // If both sides are releases, choose the more conservative one.
1339 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
1340 return A;
1341 if (A == S_Release && B == S_MovableRelease)
1342 return A;
1343 }
1344
1345 return S_None;
1346}
1347
1348namespace {
1349 /// RRInfo - Unidirectional information about either a
1350 /// retain-decrement-use-release sequence or release-use-decrement-retain
1351 /// reverese sequence.
1352 struct RRInfo {
Dan Gohmane6d5e882011-08-19 00:26:36 +00001353 /// KnownSafe - After an objc_retain, the reference count of the referenced
1354 /// object is known to be positive. Similarly, before an objc_release, the
1355 /// reference count of the referenced object is known to be positive. If
1356 /// there are retain-release pairs in code regions where the retain count
1357 /// is known to be positive, they can be eliminated, regardless of any side
1358 /// effects between them.
1359 ///
1360 /// Also, a retain+release pair nested within another retain+release
1361 /// pair all on the known same pointer value can be eliminated, regardless
1362 /// of any intervening side effects.
1363 ///
1364 /// KnownSafe is true when either of these conditions is satisfied.
1365 bool KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00001366
1367 /// IsRetainBlock - True if the Calls are objc_retainBlock calls (as
1368 /// opposed to objc_retain calls).
1369 bool IsRetainBlock;
1370
1371 /// IsTailCallRelease - True of the objc_release calls are all marked
1372 /// with the "tail" keyword.
1373 bool IsTailCallRelease;
1374
1375 /// ReleaseMetadata - If the Calls are objc_release calls and they all have
1376 /// a clang.imprecise_release tag, this is the metadata tag.
1377 MDNode *ReleaseMetadata;
1378
1379 /// Calls - For a top-down sequence, the set of objc_retains or
1380 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
1381 SmallPtrSet<Instruction *, 2> Calls;
1382
1383 /// ReverseInsertPts - The set of optimal insert positions for
1384 /// moving calls in the opposite sequence.
1385 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
1386
1387 RRInfo() :
Dan Gohman79522dc2012-01-13 00:39:07 +00001388 KnownSafe(false), IsRetainBlock(false),
Dan Gohman50ade652012-04-25 00:50:46 +00001389 IsTailCallRelease(false),
John McCall9fbd3182011-06-15 23:37:01 +00001390 ReleaseMetadata(0) {}
1391
1392 void clear();
1393 };
1394}
1395
1396void RRInfo::clear() {
Dan Gohmane6d5e882011-08-19 00:26:36 +00001397 KnownSafe = false;
John McCall9fbd3182011-06-15 23:37:01 +00001398 IsRetainBlock = false;
1399 IsTailCallRelease = false;
1400 ReleaseMetadata = 0;
1401 Calls.clear();
1402 ReverseInsertPts.clear();
1403}
1404
1405namespace {
1406 /// PtrState - This class summarizes several per-pointer runtime properties
1407 /// which are propogated through the flow graph.
1408 class PtrState {
Dan Gohman50ade652012-04-25 00:50:46 +00001409 /// KnownPositiveRefCount - True if the reference count is known to
1410 /// be incremented.
1411 bool KnownPositiveRefCount;
1412
1413 /// Partial - True of we've seen an opportunity for partial RR elimination,
1414 /// such as pushing calls into a CFG triangle or into one side of a
1415 /// CFG diamond.
1416 bool Partial;
John McCall9fbd3182011-06-15 23:37:01 +00001417
1418 /// Seq - The current position in the sequence.
Dan Gohman0daef3d2012-05-08 23:39:44 +00001419 Sequence Seq : 8;
John McCall9fbd3182011-06-15 23:37:01 +00001420
1421 public:
1422 /// RRI - Unidirectional information about the current sequence.
1423 /// TODO: Encapsulate this better.
1424 RRInfo RRI;
1425
Dan Gohman230768b2012-09-04 23:16:20 +00001426 PtrState() : KnownPositiveRefCount(false), Partial(false),
Dan Gohman0daef3d2012-05-08 23:39:44 +00001427 Seq(S_None) {}
John McCall9fbd3182011-06-15 23:37:01 +00001428
Dan Gohman50ade652012-04-25 00:50:46 +00001429 void SetKnownPositiveRefCount() {
1430 KnownPositiveRefCount = true;
Dan Gohmana7f7db22011-08-12 00:26:31 +00001431 }
1432
Dan Gohman50ade652012-04-25 00:50:46 +00001433 void ClearRefCount() {
1434 KnownPositiveRefCount = false;
John McCall9fbd3182011-06-15 23:37:01 +00001435 }
1436
John McCall9fbd3182011-06-15 23:37:01 +00001437 bool IsKnownIncremented() const {
Dan Gohman50ade652012-04-25 00:50:46 +00001438 return KnownPositiveRefCount;
John McCall9fbd3182011-06-15 23:37:01 +00001439 }
1440
1441 void SetSeq(Sequence NewSeq) {
1442 Seq = NewSeq;
1443 }
1444
John McCall9fbd3182011-06-15 23:37:01 +00001445 Sequence GetSeq() const {
1446 return Seq;
1447 }
1448
1449 void ClearSequenceProgress() {
Dan Gohman50ade652012-04-25 00:50:46 +00001450 ResetSequenceProgress(S_None);
1451 }
1452
1453 void ResetSequenceProgress(Sequence NewSeq) {
1454 Seq = NewSeq;
1455 Partial = false;
John McCall9fbd3182011-06-15 23:37:01 +00001456 RRI.clear();
1457 }
1458
1459 void Merge(const PtrState &Other, bool TopDown);
1460 };
1461}
1462
1463void
1464PtrState::Merge(const PtrState &Other, bool TopDown) {
1465 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
Dan Gohman50ade652012-04-25 00:50:46 +00001466 KnownPositiveRefCount = KnownPositiveRefCount && Other.KnownPositiveRefCount;
John McCall9fbd3182011-06-15 23:37:01 +00001467
1468 // We can't merge a plain objc_retain with an objc_retainBlock.
1469 if (RRI.IsRetainBlock != Other.RRI.IsRetainBlock)
1470 Seq = S_None;
1471
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001472 // If we're not in a sequence (anymore), drop all associated state.
John McCall9fbd3182011-06-15 23:37:01 +00001473 if (Seq == S_None) {
Dan Gohman50ade652012-04-25 00:50:46 +00001474 Partial = false;
John McCall9fbd3182011-06-15 23:37:01 +00001475 RRI.clear();
Dan Gohman50ade652012-04-25 00:50:46 +00001476 } else if (Partial || Other.Partial) {
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001477 // If we're doing a merge on a path that's previously seen a partial
1478 // merge, conservatively drop the sequence, to avoid doing partial
1479 // RR elimination. If the branch predicates for the two merge differ,
1480 // mixing them is unsafe.
Dan Gohman50ade652012-04-25 00:50:46 +00001481 ClearSequenceProgress();
John McCall9fbd3182011-06-15 23:37:01 +00001482 } else {
1483 // Conservatively merge the ReleaseMetadata information.
1484 if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
1485 RRI.ReleaseMetadata = 0;
1486
Dan Gohmane6d5e882011-08-19 00:26:36 +00001487 RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
Dan Gohman0daef3d2012-05-08 23:39:44 +00001488 RRI.IsTailCallRelease = RRI.IsTailCallRelease &&
1489 Other.RRI.IsTailCallRelease;
John McCall9fbd3182011-06-15 23:37:01 +00001490 RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001491
1492 // Merge the insert point sets. If there are any differences,
1493 // that makes this a partial merge.
Dan Gohman0daef3d2012-05-08 23:39:44 +00001494 Partial = RRI.ReverseInsertPts.size() != Other.RRI.ReverseInsertPts.size();
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001495 for (SmallPtrSet<Instruction *, 2>::const_iterator
1496 I = Other.RRI.ReverseInsertPts.begin(),
1497 E = Other.RRI.ReverseInsertPts.end(); I != E; ++I)
Dan Gohman50ade652012-04-25 00:50:46 +00001498 Partial |= RRI.ReverseInsertPts.insert(*I);
John McCall9fbd3182011-06-15 23:37:01 +00001499 }
1500}
1501
1502namespace {
1503 /// BBState - Per-BasicBlock state.
1504 class BBState {
1505 /// TopDownPathCount - The number of unique control paths from the entry
1506 /// which can reach this block.
1507 unsigned TopDownPathCount;
1508
1509 /// BottomUpPathCount - The number of unique control paths to exits
1510 /// from this block.
1511 unsigned BottomUpPathCount;
1512
1513 /// MapTy - A type for PerPtrTopDown and PerPtrBottomUp.
1514 typedef MapVector<const Value *, PtrState> MapTy;
1515
1516 /// PerPtrTopDown - The top-down traversal uses this to record information
1517 /// known about a pointer at the bottom of each block.
1518 MapTy PerPtrTopDown;
1519
1520 /// PerPtrBottomUp - The bottom-up traversal uses this to record information
1521 /// known about a pointer at the top of each block.
1522 MapTy PerPtrBottomUp;
1523
Dan Gohmaneeeb7752012-04-24 22:53:18 +00001524 /// Preds, Succs - Effective successors and predecessors of the current
1525 /// block (this ignores ignorable edges and ignored backedges).
1526 SmallVector<BasicBlock *, 2> Preds;
1527 SmallVector<BasicBlock *, 2> Succs;
1528
John McCall9fbd3182011-06-15 23:37:01 +00001529 public:
1530 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
1531
1532 typedef MapTy::iterator ptr_iterator;
1533 typedef MapTy::const_iterator ptr_const_iterator;
1534
1535 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
1536 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
1537 ptr_const_iterator top_down_ptr_begin() const {
1538 return PerPtrTopDown.begin();
1539 }
1540 ptr_const_iterator top_down_ptr_end() const {
1541 return PerPtrTopDown.end();
1542 }
1543
1544 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
1545 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
1546 ptr_const_iterator bottom_up_ptr_begin() const {
1547 return PerPtrBottomUp.begin();
1548 }
1549 ptr_const_iterator bottom_up_ptr_end() const {
1550 return PerPtrBottomUp.end();
1551 }
1552
1553 /// SetAsEntry - Mark this block as being an entry block, which has one
1554 /// path from the entry by definition.
1555 void SetAsEntry() { TopDownPathCount = 1; }
1556
1557 /// SetAsExit - Mark this block as being an exit block, which has one
1558 /// path to an exit by definition.
1559 void SetAsExit() { BottomUpPathCount = 1; }
1560
1561 PtrState &getPtrTopDownState(const Value *Arg) {
1562 return PerPtrTopDown[Arg];
1563 }
1564
1565 PtrState &getPtrBottomUpState(const Value *Arg) {
1566 return PerPtrBottomUp[Arg];
1567 }
1568
1569 void clearBottomUpPointers() {
Evan Chenga81388f2011-08-04 18:40:26 +00001570 PerPtrBottomUp.clear();
John McCall9fbd3182011-06-15 23:37:01 +00001571 }
1572
1573 void clearTopDownPointers() {
1574 PerPtrTopDown.clear();
1575 }
1576
1577 void InitFromPred(const BBState &Other);
1578 void InitFromSucc(const BBState &Other);
1579 void MergePred(const BBState &Other);
1580 void MergeSucc(const BBState &Other);
1581
1582 /// GetAllPathCount - Return the number of possible unique paths from an
1583 /// entry to an exit which pass through this block. This is only valid
1584 /// after both the top-down and bottom-up traversals are complete.
1585 unsigned GetAllPathCount() const {
Dan Gohmaneeeb7752012-04-24 22:53:18 +00001586 assert(TopDownPathCount != 0);
1587 assert(BottomUpPathCount != 0);
John McCall9fbd3182011-06-15 23:37:01 +00001588 return TopDownPathCount * BottomUpPathCount;
1589 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00001590
Dan Gohmaneeeb7752012-04-24 22:53:18 +00001591 // Specialized CFG utilities.
Dan Gohman447989c2012-04-27 18:56:31 +00001592 typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
Dan Gohmaneeeb7752012-04-24 22:53:18 +00001593 edge_iterator pred_begin() { return Preds.begin(); }
1594 edge_iterator pred_end() { return Preds.end(); }
1595 edge_iterator succ_begin() { return Succs.begin(); }
1596 edge_iterator succ_end() { return Succs.end(); }
1597
1598 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
1599 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
1600
1601 bool isExit() const { return Succs.empty(); }
John McCall9fbd3182011-06-15 23:37:01 +00001602 };
1603}
1604
1605void BBState::InitFromPred(const BBState &Other) {
1606 PerPtrTopDown = Other.PerPtrTopDown;
1607 TopDownPathCount = Other.TopDownPathCount;
1608}
1609
1610void BBState::InitFromSucc(const BBState &Other) {
1611 PerPtrBottomUp = Other.PerPtrBottomUp;
1612 BottomUpPathCount = Other.BottomUpPathCount;
1613}
1614
1615/// MergePred - The top-down traversal uses this to merge information about
1616/// predecessors to form the initial state for a new block.
1617void BBState::MergePred(const BBState &Other) {
1618 // Other.TopDownPathCount can be 0, in which case it is either dead or a
1619 // loop backedge. Loop backedges are special.
1620 TopDownPathCount += Other.TopDownPathCount;
1621
Dan Gohman0d1bc5f2012-09-12 20:45:17 +00001622 // Check for overflow. If we have overflow, fall back to conservative behavior.
1623 if (TopDownPathCount < Other.TopDownPathCount) {
1624 clearTopDownPointers();
1625 return;
1626 }
1627
John McCall9fbd3182011-06-15 23:37:01 +00001628 // For each entry in the other set, if our set has an entry with the same key,
1629 // merge the entries. Otherwise, copy the entry and merge it with an empty
1630 // entry.
1631 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
1632 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
1633 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
1634 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1635 /*TopDown=*/true);
1636 }
1637
Dan Gohmanfa7eed12011-08-11 21:06:32 +00001638 // For each entry in our set, if the other set doesn't have an entry with the
John McCall9fbd3182011-06-15 23:37:01 +00001639 // same key, force it to merge with an empty entry.
1640 for (ptr_iterator MI = top_down_ptr_begin(),
1641 ME = top_down_ptr_end(); MI != ME; ++MI)
1642 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
1643 MI->second.Merge(PtrState(), /*TopDown=*/true);
1644}
1645
1646/// MergeSucc - The bottom-up traversal uses this to merge information about
1647/// successors to form the initial state for a new block.
1648void BBState::MergeSucc(const BBState &Other) {
1649 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
1650 // loop backedge. Loop backedges are special.
1651 BottomUpPathCount += Other.BottomUpPathCount;
1652
Dan Gohman0d1bc5f2012-09-12 20:45:17 +00001653 // Check for overflow. If we have overflow, fall back to conservative behavior.
1654 if (BottomUpPathCount < Other.BottomUpPathCount) {
1655 clearBottomUpPointers();
1656 return;
1657 }
1658
John McCall9fbd3182011-06-15 23:37:01 +00001659 // For each entry in the other set, if our set has an entry with the
1660 // same key, merge the entries. Otherwise, copy the entry and merge
1661 // it with an empty entry.
1662 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
1663 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
1664 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
1665 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1666 /*TopDown=*/false);
1667 }
1668
Dan Gohmanfa7eed12011-08-11 21:06:32 +00001669 // For each entry in our set, if the other set doesn't have an entry
John McCall9fbd3182011-06-15 23:37:01 +00001670 // with the same key, force it to merge with an empty entry.
1671 for (ptr_iterator MI = bottom_up_ptr_begin(),
1672 ME = bottom_up_ptr_end(); MI != ME; ++MI)
1673 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
1674 MI->second.Merge(PtrState(), /*TopDown=*/false);
1675}
1676
1677namespace {
1678 /// ObjCARCOpt - The main ARC optimization pass.
1679 class ObjCARCOpt : public FunctionPass {
1680 bool Changed;
1681 ProvenanceAnalysis PA;
1682
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00001683 /// Run - A flag indicating whether this optimization pass should run.
1684 bool Run;
1685
John McCall9fbd3182011-06-15 23:37:01 +00001686 /// RetainRVCallee, etc. - Declarations for ObjC runtime
1687 /// functions, for use in creating calls to them. These are initialized
1688 /// lazily to avoid cluttering up the Module with unused declarations.
1689 Constant *RetainRVCallee, *AutoreleaseRVCallee, *ReleaseCallee,
Dan Gohman44280692011-07-22 22:29:21 +00001690 *RetainCallee, *RetainBlockCallee, *AutoreleaseCallee;
John McCall9fbd3182011-06-15 23:37:01 +00001691
1692 /// UsedInThisFunciton - Flags which determine whether each of the
1693 /// interesting runtine functions is in fact used in the current function.
1694 unsigned UsedInThisFunction;
1695
1696 /// ImpreciseReleaseMDKind - The Metadata Kind for clang.imprecise_release
1697 /// metadata.
1698 unsigned ImpreciseReleaseMDKind;
1699
Dan Gohman62e5b402011-12-12 18:20:00 +00001700 /// CopyOnEscapeMDKind - The Metadata Kind for clang.arc.copy_on_escape
Dan Gohmana974bea2011-10-17 22:53:25 +00001701 /// metadata.
1702 unsigned CopyOnEscapeMDKind;
1703
Dan Gohmandbe266b2012-02-17 18:59:53 +00001704 /// NoObjCARCExceptionsMDKind - The Metadata Kind for
1705 /// clang.arc.no_objc_arc_exceptions metadata.
1706 unsigned NoObjCARCExceptionsMDKind;
1707
John McCall9fbd3182011-06-15 23:37:01 +00001708 Constant *getRetainRVCallee(Module *M);
1709 Constant *getAutoreleaseRVCallee(Module *M);
1710 Constant *getReleaseCallee(Module *M);
1711 Constant *getRetainCallee(Module *M);
Dan Gohman44280692011-07-22 22:29:21 +00001712 Constant *getRetainBlockCallee(Module *M);
John McCall9fbd3182011-06-15 23:37:01 +00001713 Constant *getAutoreleaseCallee(Module *M);
1714
Dan Gohman79522dc2012-01-13 00:39:07 +00001715 bool IsRetainBlockOptimizable(const Instruction *Inst);
1716
John McCall9fbd3182011-06-15 23:37:01 +00001717 void OptimizeRetainCall(Function &F, Instruction *Retain);
1718 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
1719 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV);
1720 void OptimizeIndividualCalls(Function &F);
1721
1722 void CheckForCFGHazards(const BasicBlock *BB,
1723 DenseMap<const BasicBlock *, BBState> &BBStates,
1724 BBState &MyStates) const;
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00001725 bool VisitInstructionBottomUp(Instruction *Inst,
Dan Gohmanfbab4a82012-03-23 17:47:54 +00001726 BasicBlock *BB,
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00001727 MapVector<Value *, RRInfo> &Retains,
1728 BBState &MyStates);
John McCall9fbd3182011-06-15 23:37:01 +00001729 bool VisitBottomUp(BasicBlock *BB,
1730 DenseMap<const BasicBlock *, BBState> &BBStates,
1731 MapVector<Value *, RRInfo> &Retains);
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00001732 bool VisitInstructionTopDown(Instruction *Inst,
1733 DenseMap<Value *, RRInfo> &Releases,
1734 BBState &MyStates);
John McCall9fbd3182011-06-15 23:37:01 +00001735 bool VisitTopDown(BasicBlock *BB,
1736 DenseMap<const BasicBlock *, BBState> &BBStates,
1737 DenseMap<Value *, RRInfo> &Releases);
1738 bool Visit(Function &F,
1739 DenseMap<const BasicBlock *, BBState> &BBStates,
1740 MapVector<Value *, RRInfo> &Retains,
1741 DenseMap<Value *, RRInfo> &Releases);
1742
1743 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1744 MapVector<Value *, RRInfo> &Retains,
1745 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman44280692011-07-22 22:29:21 +00001746 SmallVectorImpl<Instruction *> &DeadInsts,
1747 Module *M);
John McCall9fbd3182011-06-15 23:37:01 +00001748
1749 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1750 MapVector<Value *, RRInfo> &Retains,
Dan Gohman44280692011-07-22 22:29:21 +00001751 DenseMap<Value *, RRInfo> &Releases,
1752 Module *M);
John McCall9fbd3182011-06-15 23:37:01 +00001753
1754 void OptimizeWeakCalls(Function &F);
1755
1756 bool OptimizeSequences(Function &F);
1757
1758 void OptimizeReturns(Function &F);
1759
1760 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1761 virtual bool doInitialization(Module &M);
1762 virtual bool runOnFunction(Function &F);
1763 virtual void releaseMemory();
1764
1765 public:
1766 static char ID;
1767 ObjCARCOpt() : FunctionPass(ID) {
1768 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1769 }
1770 };
1771}
1772
1773char ObjCARCOpt::ID = 0;
1774INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1775 "objc-arc", "ObjC ARC optimization", false, false)
1776INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1777INITIALIZE_PASS_END(ObjCARCOpt,
1778 "objc-arc", "ObjC ARC optimization", false, false)
1779
1780Pass *llvm::createObjCARCOptPass() {
1781 return new ObjCARCOpt();
1782}
1783
1784void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1785 AU.addRequired<ObjCARCAliasAnalysis>();
1786 AU.addRequired<AliasAnalysis>();
1787 // ARC optimization doesn't currently split critical edges.
1788 AU.setPreservesCFG();
1789}
1790
Dan Gohman79522dc2012-01-13 00:39:07 +00001791bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1792 // Without the magic metadata tag, we have to assume this might be an
1793 // objc_retainBlock call inserted to convert a block pointer to an id,
1794 // in which case it really is needed.
1795 if (!Inst->getMetadata(CopyOnEscapeMDKind))
1796 return false;
1797
1798 // If the pointer "escapes" (not including being used in a call),
1799 // the copy may be needed.
1800 if (DoesObjCBlockEscape(Inst))
1801 return false;
1802
1803 // Otherwise, it's not needed.
1804 return true;
1805}
1806
John McCall9fbd3182011-06-15 23:37:01 +00001807Constant *ObjCARCOpt::getRetainRVCallee(Module *M) {
1808 if (!RetainRVCallee) {
1809 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001810 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman0daef3d2012-05-08 23:39:44 +00001811 Type *Params[] = { I8X };
1812 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling034b94b2012-12-19 07:18:57 +00001813 AttributeSet Attribute =
Bill Wendling99faa3b2012-12-07 23:16:57 +00001814 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00001815 Attribute::get(C, Attribute::NoUnwind));
John McCall9fbd3182011-06-15 23:37:01 +00001816 RetainRVCallee =
1817 M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy,
Bill Wendling034b94b2012-12-19 07:18:57 +00001818 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00001819 }
1820 return RetainRVCallee;
1821}
1822
1823Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1824 if (!AutoreleaseRVCallee) {
1825 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001826 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman0daef3d2012-05-08 23:39:44 +00001827 Type *Params[] = { I8X };
1828 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling034b94b2012-12-19 07:18:57 +00001829 AttributeSet Attribute =
Bill Wendling99faa3b2012-12-07 23:16:57 +00001830 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00001831 Attribute::get(C, Attribute::NoUnwind));
John McCall9fbd3182011-06-15 23:37:01 +00001832 AutoreleaseRVCallee =
1833 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
Bill Wendling034b94b2012-12-19 07:18:57 +00001834 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00001835 }
1836 return AutoreleaseRVCallee;
1837}
1838
1839Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1840 if (!ReleaseCallee) {
1841 LLVMContext &C = M->getContext();
Dan Gohman0daef3d2012-05-08 23:39:44 +00001842 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling034b94b2012-12-19 07:18:57 +00001843 AttributeSet Attribute =
Bill Wendling99faa3b2012-12-07 23:16:57 +00001844 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00001845 Attribute::get(C, Attribute::NoUnwind));
John McCall9fbd3182011-06-15 23:37:01 +00001846 ReleaseCallee =
1847 M->getOrInsertFunction(
1848 "objc_release",
1849 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
Bill Wendling034b94b2012-12-19 07:18:57 +00001850 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00001851 }
1852 return ReleaseCallee;
1853}
1854
1855Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1856 if (!RetainCallee) {
1857 LLVMContext &C = M->getContext();
Dan Gohman0daef3d2012-05-08 23:39:44 +00001858 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling034b94b2012-12-19 07:18:57 +00001859 AttributeSet Attribute =
Bill Wendling99faa3b2012-12-07 23:16:57 +00001860 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00001861 Attribute::get(C, Attribute::NoUnwind));
John McCall9fbd3182011-06-15 23:37:01 +00001862 RetainCallee =
1863 M->getOrInsertFunction(
1864 "objc_retain",
1865 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling034b94b2012-12-19 07:18:57 +00001866 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00001867 }
1868 return RetainCallee;
1869}
1870
Dan Gohman44280692011-07-22 22:29:21 +00001871Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1872 if (!RetainBlockCallee) {
1873 LLVMContext &C = M->getContext();
Dan Gohman0daef3d2012-05-08 23:39:44 +00001874 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Dan Gohman1d2fd752011-09-14 18:33:34 +00001875 // objc_retainBlock is not nounwind because it calls user copy constructors
1876 // which could theoretically throw.
Dan Gohman44280692011-07-22 22:29:21 +00001877 RetainBlockCallee =
1878 M->getOrInsertFunction(
1879 "objc_retainBlock",
1880 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling99faa3b2012-12-07 23:16:57 +00001881 AttributeSet());
Dan Gohman44280692011-07-22 22:29:21 +00001882 }
1883 return RetainBlockCallee;
1884}
1885
John McCall9fbd3182011-06-15 23:37:01 +00001886Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1887 if (!AutoreleaseCallee) {
1888 LLVMContext &C = M->getContext();
Dan Gohman0daef3d2012-05-08 23:39:44 +00001889 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling034b94b2012-12-19 07:18:57 +00001890 AttributeSet Attribute =
Bill Wendling99faa3b2012-12-07 23:16:57 +00001891 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00001892 Attribute::get(C, Attribute::NoUnwind));
John McCall9fbd3182011-06-15 23:37:01 +00001893 AutoreleaseCallee =
1894 M->getOrInsertFunction(
1895 "objc_autorelease",
1896 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling034b94b2012-12-19 07:18:57 +00001897 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00001898 }
1899 return AutoreleaseCallee;
1900}
1901
Dan Gohman230768b2012-09-04 23:16:20 +00001902/// IsPotentialUse - Test whether the given value is possible a
1903/// reference-counted pointer, including tests which utilize AliasAnalysis.
1904static bool IsPotentialUse(const Value *Op, AliasAnalysis &AA) {
1905 // First make the rudimentary check.
1906 if (!IsPotentialUse(Op))
1907 return false;
1908
1909 // Objects in constant memory are not reference-counted.
1910 if (AA.pointsToConstantMemory(Op))
1911 return false;
1912
1913 // Pointers in constant memory are not pointing to reference-counted objects.
1914 if (const LoadInst *LI = dyn_cast<LoadInst>(Op))
1915 if (AA.pointsToConstantMemory(LI->getPointerOperand()))
1916 return false;
1917
1918 // Otherwise assume the worst.
1919 return true;
1920}
1921
John McCall9fbd3182011-06-15 23:37:01 +00001922/// CanAlterRefCount - Test whether the given instruction can result in a
1923/// reference count modification (positive or negative) for the pointer's
1924/// object.
1925static bool
1926CanAlterRefCount(const Instruction *Inst, const Value *Ptr,
1927 ProvenanceAnalysis &PA, InstructionClass Class) {
1928 switch (Class) {
1929 case IC_Autorelease:
1930 case IC_AutoreleaseRV:
1931 case IC_User:
1932 // These operations never directly modify a reference count.
1933 return false;
1934 default: break;
1935 }
1936
1937 ImmutableCallSite CS = static_cast<const Value *>(Inst);
1938 assert(CS && "Only calls can alter reference counts!");
1939
1940 // See if AliasAnalysis can help us with the call.
1941 AliasAnalysis::ModRefBehavior MRB = PA.getAA()->getModRefBehavior(CS);
1942 if (AliasAnalysis::onlyReadsMemory(MRB))
1943 return false;
1944 if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
1945 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1946 I != E; ++I) {
1947 const Value *Op = *I;
Dan Gohman230768b2012-09-04 23:16:20 +00001948 if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
John McCall9fbd3182011-06-15 23:37:01 +00001949 return true;
1950 }
1951 return false;
1952 }
1953
1954 // Assume the worst.
1955 return true;
1956}
1957
1958/// CanUse - Test whether the given instruction can "use" the given pointer's
1959/// object in a way that requires the reference count to be positive.
1960static bool
1961CanUse(const Instruction *Inst, const Value *Ptr, ProvenanceAnalysis &PA,
1962 InstructionClass Class) {
1963 // IC_Call operations (as opposed to IC_CallOrUser) never "use" objc pointers.
1964 if (Class == IC_Call)
1965 return false;
1966
1967 // Consider various instructions which may have pointer arguments which are
1968 // not "uses".
1969 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(Inst)) {
1970 // Comparing a pointer with null, or any other constant, isn't really a use,
1971 // because we don't care what the pointer points to, or about the values
1972 // of any other dynamic reference-counted pointers.
Dan Gohman230768b2012-09-04 23:16:20 +00001973 if (!IsPotentialUse(ICI->getOperand(1), *PA.getAA()))
John McCall9fbd3182011-06-15 23:37:01 +00001974 return false;
1975 } else if (ImmutableCallSite CS = static_cast<const Value *>(Inst)) {
1976 // For calls, just check the arguments (and not the callee operand).
1977 for (ImmutableCallSite::arg_iterator OI = CS.arg_begin(),
1978 OE = CS.arg_end(); OI != OE; ++OI) {
1979 const Value *Op = *OI;
Dan Gohman230768b2012-09-04 23:16:20 +00001980 if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
John McCall9fbd3182011-06-15 23:37:01 +00001981 return true;
1982 }
1983 return false;
1984 } else if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1985 // Special-case stores, because we don't care about the stored value, just
1986 // the store address.
1987 const Value *Op = GetUnderlyingObjCPtr(SI->getPointerOperand());
1988 // If we can't tell what the underlying object was, assume there is a
1989 // dependence.
Dan Gohman230768b2012-09-04 23:16:20 +00001990 return IsPotentialUse(Op, *PA.getAA()) && PA.related(Op, Ptr);
John McCall9fbd3182011-06-15 23:37:01 +00001991 }
1992
1993 // Check each operand for a match.
1994 for (User::const_op_iterator OI = Inst->op_begin(), OE = Inst->op_end();
1995 OI != OE; ++OI) {
1996 const Value *Op = *OI;
Dan Gohman230768b2012-09-04 23:16:20 +00001997 if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
John McCall9fbd3182011-06-15 23:37:01 +00001998 return true;
1999 }
2000 return false;
2001}
2002
2003/// CanInterruptRV - Test whether the given instruction can autorelease
2004/// any pointer or cause an autoreleasepool pop.
2005static bool
2006CanInterruptRV(InstructionClass Class) {
2007 switch (Class) {
2008 case IC_AutoreleasepoolPop:
2009 case IC_CallOrUser:
2010 case IC_Call:
2011 case IC_Autorelease:
2012 case IC_AutoreleaseRV:
2013 case IC_FusedRetainAutorelease:
2014 case IC_FusedRetainAutoreleaseRV:
2015 return true;
2016 default:
2017 return false;
2018 }
2019}
2020
2021namespace {
2022 /// DependenceKind - There are several kinds of dependence-like concepts in
2023 /// use here.
2024 enum DependenceKind {
2025 NeedsPositiveRetainCount,
Dan Gohman511568d2012-04-13 00:59:57 +00002026 AutoreleasePoolBoundary,
John McCall9fbd3182011-06-15 23:37:01 +00002027 CanChangeRetainCount,
2028 RetainAutoreleaseDep, ///< Blocks objc_retainAutorelease.
2029 RetainAutoreleaseRVDep, ///< Blocks objc_retainAutoreleaseReturnValue.
2030 RetainRVDep ///< Blocks objc_retainAutoreleasedReturnValue.
2031 };
2032}
2033
2034/// Depends - Test if there can be dependencies on Inst through Arg. This
2035/// function only tests dependencies relevant for removing pairs of calls.
2036static bool
2037Depends(DependenceKind Flavor, Instruction *Inst, const Value *Arg,
2038 ProvenanceAnalysis &PA) {
2039 // If we've reached the definition of Arg, stop.
2040 if (Inst == Arg)
2041 return true;
2042
2043 switch (Flavor) {
2044 case NeedsPositiveRetainCount: {
2045 InstructionClass Class = GetInstructionClass(Inst);
2046 switch (Class) {
2047 case IC_AutoreleasepoolPop:
2048 case IC_AutoreleasepoolPush:
2049 case IC_None:
2050 return false;
2051 default:
2052 return CanUse(Inst, Arg, PA, Class);
2053 }
2054 }
2055
Dan Gohman511568d2012-04-13 00:59:57 +00002056 case AutoreleasePoolBoundary: {
2057 InstructionClass Class = GetInstructionClass(Inst);
2058 switch (Class) {
2059 case IC_AutoreleasepoolPop:
2060 case IC_AutoreleasepoolPush:
2061 // These mark the end and begin of an autorelease pool scope.
2062 return true;
2063 default:
2064 // Nothing else does this.
2065 return false;
2066 }
2067 }
2068
John McCall9fbd3182011-06-15 23:37:01 +00002069 case CanChangeRetainCount: {
2070 InstructionClass Class = GetInstructionClass(Inst);
2071 switch (Class) {
2072 case IC_AutoreleasepoolPop:
2073 // Conservatively assume this can decrement any count.
2074 return true;
2075 case IC_AutoreleasepoolPush:
2076 case IC_None:
2077 return false;
2078 default:
2079 return CanAlterRefCount(Inst, Arg, PA, Class);
2080 }
2081 }
2082
2083 case RetainAutoreleaseDep:
2084 switch (GetBasicInstructionClass(Inst)) {
2085 case IC_AutoreleasepoolPop:
Dan Gohman511568d2012-04-13 00:59:57 +00002086 case IC_AutoreleasepoolPush:
John McCall9fbd3182011-06-15 23:37:01 +00002087 // Don't merge an objc_autorelease with an objc_retain inside a different
2088 // autoreleasepool scope.
2089 return true;
2090 case IC_Retain:
2091 case IC_RetainRV:
2092 // Check for a retain of the same pointer for merging.
2093 return GetObjCArg(Inst) == Arg;
2094 default:
2095 // Nothing else matters for objc_retainAutorelease formation.
2096 return false;
2097 }
John McCall9fbd3182011-06-15 23:37:01 +00002098
2099 case RetainAutoreleaseRVDep: {
2100 InstructionClass Class = GetBasicInstructionClass(Inst);
2101 switch (Class) {
2102 case IC_Retain:
2103 case IC_RetainRV:
2104 // Check for a retain of the same pointer for merging.
2105 return GetObjCArg(Inst) == Arg;
2106 default:
2107 // Anything that can autorelease interrupts
2108 // retainAutoreleaseReturnValue formation.
2109 return CanInterruptRV(Class);
2110 }
John McCall9fbd3182011-06-15 23:37:01 +00002111 }
2112
2113 case RetainRVDep:
2114 return CanInterruptRV(GetBasicInstructionClass(Inst));
2115 }
2116
2117 llvm_unreachable("Invalid dependence flavor");
John McCall9fbd3182011-06-15 23:37:01 +00002118}
2119
2120/// FindDependencies - Walk up the CFG from StartPos (which is in StartBB) and
2121/// find local and non-local dependencies on Arg.
2122/// TODO: Cache results?
2123static void
2124FindDependencies(DependenceKind Flavor,
2125 const Value *Arg,
2126 BasicBlock *StartBB, Instruction *StartInst,
2127 SmallPtrSet<Instruction *, 4> &DependingInstructions,
2128 SmallPtrSet<const BasicBlock *, 4> &Visited,
2129 ProvenanceAnalysis &PA) {
2130 BasicBlock::iterator StartPos = StartInst;
2131
2132 SmallVector<std::pair<BasicBlock *, BasicBlock::iterator>, 4> Worklist;
2133 Worklist.push_back(std::make_pair(StartBB, StartPos));
2134 do {
2135 std::pair<BasicBlock *, BasicBlock::iterator> Pair =
2136 Worklist.pop_back_val();
2137 BasicBlock *LocalStartBB = Pair.first;
2138 BasicBlock::iterator LocalStartPos = Pair.second;
2139 BasicBlock::iterator StartBBBegin = LocalStartBB->begin();
2140 for (;;) {
2141 if (LocalStartPos == StartBBBegin) {
2142 pred_iterator PI(LocalStartBB), PE(LocalStartBB, false);
2143 if (PI == PE)
2144 // If we've reached the function entry, produce a null dependence.
2145 DependingInstructions.insert(0);
2146 else
2147 // Add the predecessors to the worklist.
2148 do {
2149 BasicBlock *PredBB = *PI;
2150 if (Visited.insert(PredBB))
2151 Worklist.push_back(std::make_pair(PredBB, PredBB->end()));
2152 } while (++PI != PE);
2153 break;
2154 }
2155
2156 Instruction *Inst = --LocalStartPos;
2157 if (Depends(Flavor, Inst, Arg, PA)) {
2158 DependingInstructions.insert(Inst);
2159 break;
2160 }
2161 }
2162 } while (!Worklist.empty());
2163
2164 // Determine whether the original StartBB post-dominates all of the blocks we
2165 // visited. If not, insert a sentinal indicating that most optimizations are
2166 // not safe.
2167 for (SmallPtrSet<const BasicBlock *, 4>::const_iterator I = Visited.begin(),
2168 E = Visited.end(); I != E; ++I) {
2169 const BasicBlock *BB = *I;
2170 if (BB == StartBB)
2171 continue;
2172 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2173 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2174 const BasicBlock *Succ = *SI;
2175 if (Succ != StartBB && !Visited.count(Succ)) {
2176 DependingInstructions.insert(reinterpret_cast<Instruction *>(-1));
2177 return;
2178 }
2179 }
2180 }
2181}
2182
2183static bool isNullOrUndef(const Value *V) {
2184 return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
2185}
2186
2187static bool isNoopInstruction(const Instruction *I) {
2188 return isa<BitCastInst>(I) ||
2189 (isa<GetElementPtrInst>(I) &&
2190 cast<GetElementPtrInst>(I)->hasAllZeroIndices());
2191}
2192
2193/// OptimizeRetainCall - Turn objc_retain into
2194/// objc_retainAutoreleasedReturnValue if the operand is a return value.
2195void
2196ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) {
Dan Gohman447989c2012-04-27 18:56:31 +00002197 ImmutableCallSite CS(GetObjCArg(Retain));
2198 const Instruction *Call = CS.getInstruction();
John McCall9fbd3182011-06-15 23:37:01 +00002199 if (!Call) return;
2200 if (Call->getParent() != Retain->getParent()) return;
2201
2202 // Check that the call is next to the retain.
Dan Gohman447989c2012-04-27 18:56:31 +00002203 BasicBlock::const_iterator I = Call;
John McCall9fbd3182011-06-15 23:37:01 +00002204 ++I;
2205 while (isNoopInstruction(I)) ++I;
2206 if (&*I != Retain)
2207 return;
2208
2209 // Turn it to an objc_retainAutoreleasedReturnValue..
2210 Changed = true;
2211 ++NumPeeps;
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002212
Michael Gottesman715f6a62013-01-04 21:30:38 +00002213 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainCall: Transforming "
2214 "objc_retainAutoreleasedReturnValue => "
2215 "objc_retain since the operand is not a return value.\n"
2216 " Old: "
2217 << *Retain << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002218
John McCall9fbd3182011-06-15 23:37:01 +00002219 cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent()));
Michael Gottesman715f6a62013-01-04 21:30:38 +00002220
2221 DEBUG(dbgs() << " New: "
2222 << *Retain << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00002223}
2224
2225/// OptimizeRetainRVCall - Turn objc_retainAutoreleasedReturnValue into
Dan Gohman447989c2012-04-27 18:56:31 +00002226/// objc_retain if the operand is not a return value. Or, if it can be paired
2227/// with an objc_autoreleaseReturnValue, delete the pair and return true.
John McCall9fbd3182011-06-15 23:37:01 +00002228bool
2229ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
Dan Gohman6fedb3c2012-03-23 18:09:00 +00002230 // Check for the argument being from an immediately preceding call or invoke.
Dan Gohman447989c2012-04-27 18:56:31 +00002231 const Value *Arg = GetObjCArg(RetainRV);
2232 ImmutableCallSite CS(Arg);
2233 if (const Instruction *Call = CS.getInstruction()) {
John McCall9fbd3182011-06-15 23:37:01 +00002234 if (Call->getParent() == RetainRV->getParent()) {
Dan Gohman447989c2012-04-27 18:56:31 +00002235 BasicBlock::const_iterator I = Call;
John McCall9fbd3182011-06-15 23:37:01 +00002236 ++I;
2237 while (isNoopInstruction(I)) ++I;
2238 if (&*I == RetainRV)
2239 return false;
Dan Gohman447989c2012-04-27 18:56:31 +00002240 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Dan Gohman6fedb3c2012-03-23 18:09:00 +00002241 BasicBlock *RetainRVParent = RetainRV->getParent();
2242 if (II->getNormalDest() == RetainRVParent) {
Dan Gohman447989c2012-04-27 18:56:31 +00002243 BasicBlock::const_iterator I = RetainRVParent->begin();
Dan Gohman6fedb3c2012-03-23 18:09:00 +00002244 while (isNoopInstruction(I)) ++I;
2245 if (&*I == RetainRV)
2246 return false;
2247 }
John McCall9fbd3182011-06-15 23:37:01 +00002248 }
Dan Gohman6fedb3c2012-03-23 18:09:00 +00002249 }
John McCall9fbd3182011-06-15 23:37:01 +00002250
2251 // Check for being preceded by an objc_autoreleaseReturnValue on the same
2252 // pointer. In this case, we can delete the pair.
2253 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
2254 if (I != Begin) {
2255 do --I; while (I != Begin && isNoopInstruction(I));
2256 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
2257 GetObjCArg(I) == Arg) {
2258 Changed = true;
2259 ++NumPeeps;
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002260
Michael Gottesman87a0f022013-01-05 17:55:35 +00002261 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainRVCall: Erasing " << *I << "\n"
2262 << " Erasing " << *RetainRV
2263 << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002264
John McCall9fbd3182011-06-15 23:37:01 +00002265 EraseInstruction(I);
2266 EraseInstruction(RetainRV);
2267 return true;
2268 }
2269 }
2270
2271 // Turn it to a plain objc_retain.
2272 Changed = true;
2273 ++NumPeeps;
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002274
Michael Gottesman36e4bc42013-01-05 17:55:42 +00002275 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainRVCall: Transforming "
2276 "objc_retainAutoreleasedReturnValue => "
2277 "objc_retain since the operand is not a return value.\n"
2278 " Old: "
2279 << *RetainRV << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002280
John McCall9fbd3182011-06-15 23:37:01 +00002281 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
Michael Gottesman36e4bc42013-01-05 17:55:42 +00002282
2283 DEBUG(dbgs() << " New: "
2284 << *RetainRV << "\n");
2285
John McCall9fbd3182011-06-15 23:37:01 +00002286 return false;
2287}
2288
2289/// OptimizeAutoreleaseRVCall - Turn objc_autoreleaseReturnValue into
2290/// objc_autorelease if the result is not used as a return value.
2291void
2292ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV) {
2293 // Check for a return of the pointer value.
2294 const Value *Ptr = GetObjCArg(AutoreleaseRV);
Dan Gohman126a54f2011-08-12 00:36:31 +00002295 SmallVector<const Value *, 2> Users;
2296 Users.push_back(Ptr);
2297 do {
2298 Ptr = Users.pop_back_val();
2299 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
2300 UI != UE; ++UI) {
2301 const User *I = *UI;
2302 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
2303 return;
2304 if (isa<BitCastInst>(I))
2305 Users.push_back(I);
2306 }
2307 } while (!Users.empty());
John McCall9fbd3182011-06-15 23:37:01 +00002308
2309 Changed = true;
2310 ++NumPeeps;
Michael Gottesman48239c72013-01-06 21:07:11 +00002311
2312 DEBUG(dbgs() << "ObjCARCOpt::OptimizeAutoreleaseRVCall: Transforming "
2313 "objc_autoreleaseReturnValue => "
2314 "objc_autorelease since its operand is not used as a return "
2315 "value.\n"
2316 " Old: "
2317 << *AutoreleaseRV << "\n");
2318
Michael Gottesmane8c161a2013-01-12 01:25:15 +00002319 CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
2320 AutoreleaseRVCI->
John McCall9fbd3182011-06-15 23:37:01 +00002321 setCalledFunction(getAutoreleaseCallee(F.getParent()));
Michael Gottesmane8c161a2013-01-12 01:25:15 +00002322 AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002323
Michael Gottesman48239c72013-01-06 21:07:11 +00002324 DEBUG(dbgs() << " New: "
2325 << *AutoreleaseRV << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002326
John McCall9fbd3182011-06-15 23:37:01 +00002327}
2328
2329/// OptimizeIndividualCalls - Visit each call, one at a time, and make
2330/// simplifications without doing any additional analysis.
2331void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
2332 // Reset all the flags in preparation for recomputing them.
2333 UsedInThisFunction = 0;
2334
2335 // Visit all objc_* calls in F.
2336 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2337 Instruction *Inst = &*I++;
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00002338
Michael Gottesman5c0ae472013-01-04 21:29:57 +00002339 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Visiting: " <<
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00002340 *Inst << "\n");
2341
John McCall9fbd3182011-06-15 23:37:01 +00002342 InstructionClass Class = GetBasicInstructionClass(Inst);
2343
2344 switch (Class) {
2345 default: break;
2346
2347 // Delete no-op casts. These function calls have special semantics, but
2348 // the semantics are entirely implemented via lowering in the front-end,
2349 // so by the time they reach the optimizer, they are just no-op calls
2350 // which return their argument.
2351 //
2352 // There are gray areas here, as the ability to cast reference-counted
2353 // pointers to raw void* and back allows code to break ARC assumptions,
2354 // however these are currently considered to be unimportant.
2355 case IC_NoopCast:
2356 Changed = true;
2357 ++NumNoops;
Michael Gottesman4680abe2013-01-06 21:07:15 +00002358 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Erasing no-op cast:"
2359 " " << *Inst << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00002360 EraseInstruction(Inst);
2361 continue;
2362
2363 // If the pointer-to-weak-pointer is null, it's undefined behavior.
2364 case IC_StoreWeak:
2365 case IC_LoadWeak:
2366 case IC_LoadWeakRetained:
2367 case IC_InitWeak:
2368 case IC_DestroyWeak: {
2369 CallInst *CI = cast<CallInst>(Inst);
2370 if (isNullOrUndef(CI->getArgOperand(0))) {
Dan Gohmand6bf2012012-04-13 18:57:48 +00002371 Changed = true;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002372 Type *Ty = CI->getArgOperand(0)->getType();
John McCall9fbd3182011-06-15 23:37:01 +00002373 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2374 Constant::getNullValue(Ty),
2375 CI);
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002376 llvm::Value *NewValue = UndefValue::get(CI->getType());
Michael Gottesmane5494922013-01-06 21:54:30 +00002377 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: A null "
2378 "pointer-to-weak-pointer is undefined behavior.\n"
2379 " Old = " << *CI <<
2380 "\n New = " <<
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002381 *NewValue << "\n");
Michael Gottesmane5494922013-01-06 21:54:30 +00002382 CI->replaceAllUsesWith(NewValue);
John McCall9fbd3182011-06-15 23:37:01 +00002383 CI->eraseFromParent();
2384 continue;
2385 }
2386 break;
2387 }
2388 case IC_CopyWeak:
2389 case IC_MoveWeak: {
2390 CallInst *CI = cast<CallInst>(Inst);
2391 if (isNullOrUndef(CI->getArgOperand(0)) ||
2392 isNullOrUndef(CI->getArgOperand(1))) {
Dan Gohmand6bf2012012-04-13 18:57:48 +00002393 Changed = true;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002394 Type *Ty = CI->getArgOperand(0)->getType();
John McCall9fbd3182011-06-15 23:37:01 +00002395 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2396 Constant::getNullValue(Ty),
2397 CI);
Michael Gottesmane5494922013-01-06 21:54:30 +00002398
2399 llvm::Value *NewValue = UndefValue::get(CI->getType());
2400 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: A null "
2401 "pointer-to-weak-pointer is undefined behavior.\n"
2402 " Old = " << *CI <<
2403 "\n New = " <<
2404 *NewValue << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002405
Michael Gottesmane5494922013-01-06 21:54:30 +00002406 CI->replaceAllUsesWith(NewValue);
John McCall9fbd3182011-06-15 23:37:01 +00002407 CI->eraseFromParent();
2408 continue;
2409 }
2410 break;
2411 }
2412 case IC_Retain:
2413 OptimizeRetainCall(F, Inst);
2414 break;
2415 case IC_RetainRV:
2416 if (OptimizeRetainRVCall(F, Inst))
2417 continue;
2418 break;
2419 case IC_AutoreleaseRV:
2420 OptimizeAutoreleaseRVCall(F, Inst);
2421 break;
2422 }
2423
2424 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
2425 if (IsAutorelease(Class) && Inst->use_empty()) {
2426 CallInst *Call = cast<CallInst>(Inst);
2427 const Value *Arg = Call->getArgOperand(0);
2428 Arg = FindSingleUseIdentifiedObject(Arg);
2429 if (Arg) {
2430 Changed = true;
2431 ++NumAutoreleases;
2432
2433 // Create the declaration lazily.
2434 LLVMContext &C = Inst->getContext();
2435 CallInst *NewCall =
2436 CallInst::Create(getReleaseCallee(F.getParent()),
2437 Call->getArgOperand(0), "", Call);
2438 NewCall->setMetadata(ImpreciseReleaseMDKind,
2439 MDNode::get(C, ArrayRef<Value *>()));
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002440
Michael Gottesman20d9fff2013-01-06 22:56:50 +00002441 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Replacing "
2442 "objc_autorelease(x) with objc_release(x) since x is "
2443 "otherwise unused.\n"
Michael Gottesman79561272013-01-06 22:56:54 +00002444 " Old: " << *Call <<
Michael Gottesman20d9fff2013-01-06 22:56:50 +00002445 "\n New: " <<
2446 *NewCall << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002447
John McCall9fbd3182011-06-15 23:37:01 +00002448 EraseInstruction(Call);
2449 Inst = NewCall;
2450 Class = IC_Release;
2451 }
2452 }
2453
2454 // For functions which can never be passed stack arguments, add
2455 // a tail keyword.
2456 if (IsAlwaysTail(Class)) {
2457 Changed = true;
Michael Gottesman817d4e92013-01-06 23:39:09 +00002458 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Adding tail keyword"
2459 " to function since it can never be passed stack args: " << *Inst <<
2460 "\n");
John McCall9fbd3182011-06-15 23:37:01 +00002461 cast<CallInst>(Inst)->setTailCall();
2462 }
2463
Michael Gottesmane8c161a2013-01-12 01:25:15 +00002464 // Ensure that functions that can never have a "tail" keyword due to the
2465 // semantics of ARC truly do not do so.
2466 if (IsNeverTail(Class)) {
2467 Changed = true;
2468 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Removing tail keyword"
2469 " from function: " << *Inst <<
2470 "\n");
2471 cast<CallInst>(Inst)->setTailCall(false);
2472 }
2473
John McCall9fbd3182011-06-15 23:37:01 +00002474 // Set nounwind as needed.
2475 if (IsNoThrow(Class)) {
2476 Changed = true;
Michael Gottesman38bc25a2013-01-06 23:39:13 +00002477 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Found no throw"
2478 " class. Setting nounwind on: " << *Inst << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00002479 cast<CallInst>(Inst)->setDoesNotThrow();
2480 }
2481
2482 if (!IsNoopOnNull(Class)) {
2483 UsedInThisFunction |= 1 << Class;
2484 continue;
2485 }
2486
2487 const Value *Arg = GetObjCArg(Inst);
2488
2489 // ARC calls with null are no-ops. Delete them.
2490 if (isNullOrUndef(Arg)) {
2491 Changed = true;
2492 ++NumNoops;
Michael Gottesmanfbe4d6b2013-01-07 00:04:52 +00002493 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: ARC calls with "
2494 " null are no-ops. Erasing: " << *Inst << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00002495 EraseInstruction(Inst);
2496 continue;
2497 }
2498
2499 // Keep track of which of retain, release, autorelease, and retain_block
2500 // are actually present in this function.
2501 UsedInThisFunction |= 1 << Class;
2502
2503 // If Arg is a PHI, and one or more incoming values to the
2504 // PHI are null, and the call is control-equivalent to the PHI, and there
2505 // are no relevant side effects between the PHI and the call, the call
2506 // could be pushed up to just those paths with non-null incoming values.
2507 // For now, don't bother splitting critical edges for this.
2508 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
2509 Worklist.push_back(std::make_pair(Inst, Arg));
2510 do {
2511 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
2512 Inst = Pair.first;
2513 Arg = Pair.second;
2514
2515 const PHINode *PN = dyn_cast<PHINode>(Arg);
2516 if (!PN) continue;
2517
2518 // Determine if the PHI has any null operands, or any incoming
2519 // critical edges.
2520 bool HasNull = false;
2521 bool HasCriticalEdges = false;
2522 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2523 Value *Incoming =
2524 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2525 if (isNullOrUndef(Incoming))
2526 HasNull = true;
2527 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
2528 .getNumSuccessors() != 1) {
2529 HasCriticalEdges = true;
2530 break;
2531 }
2532 }
2533 // If we have null operands and no critical edges, optimize.
2534 if (!HasCriticalEdges && HasNull) {
2535 SmallPtrSet<Instruction *, 4> DependingInstructions;
2536 SmallPtrSet<const BasicBlock *, 4> Visited;
2537
2538 // Check that there is nothing that cares about the reference
2539 // count between the call and the phi.
Dan Gohman511568d2012-04-13 00:59:57 +00002540 switch (Class) {
2541 case IC_Retain:
2542 case IC_RetainBlock:
2543 // These can always be moved up.
2544 break;
2545 case IC_Release:
Dan Gohman0daef3d2012-05-08 23:39:44 +00002546 // These can't be moved across things that care about the retain
2547 // count.
Dan Gohman511568d2012-04-13 00:59:57 +00002548 FindDependencies(NeedsPositiveRetainCount, Arg,
2549 Inst->getParent(), Inst,
2550 DependingInstructions, Visited, PA);
2551 break;
2552 case IC_Autorelease:
2553 // These can't be moved across autorelease pool scope boundaries.
2554 FindDependencies(AutoreleasePoolBoundary, Arg,
2555 Inst->getParent(), Inst,
2556 DependingInstructions, Visited, PA);
2557 break;
2558 case IC_RetainRV:
2559 case IC_AutoreleaseRV:
2560 // Don't move these; the RV optimization depends on the autoreleaseRV
2561 // being tail called, and the retainRV being immediately after a call
2562 // (which might still happen if we get lucky with codegen layout, but
2563 // it's not worth taking the chance).
2564 continue;
2565 default:
2566 llvm_unreachable("Invalid dependence flavor");
2567 }
2568
John McCall9fbd3182011-06-15 23:37:01 +00002569 if (DependingInstructions.size() == 1 &&
2570 *DependingInstructions.begin() == PN) {
2571 Changed = true;
2572 ++NumPartialNoops;
2573 // Clone the call into each predecessor that has a non-null value.
2574 CallInst *CInst = cast<CallInst>(Inst);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002575 Type *ParamTy = CInst->getArgOperand(0)->getType();
John McCall9fbd3182011-06-15 23:37:01 +00002576 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2577 Value *Incoming =
2578 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2579 if (!isNullOrUndef(Incoming)) {
2580 CallInst *Clone = cast<CallInst>(CInst->clone());
2581 Value *Op = PN->getIncomingValue(i);
2582 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
2583 if (Op->getType() != ParamTy)
2584 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
2585 Clone->setArgOperand(0, Op);
2586 Clone->insertBefore(InsertPos);
Michael Gottesman55811152013-01-09 19:23:24 +00002587
2588 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Cloning "
2589 << *CInst << "\n"
2590 " And inserting "
2591 "clone at " << *InsertPos << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00002592 Worklist.push_back(std::make_pair(Clone, Incoming));
2593 }
2594 }
2595 // Erase the original call.
Michael Gottesman55811152013-01-09 19:23:24 +00002596 DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00002597 EraseInstruction(CInst);
2598 continue;
2599 }
2600 }
2601 } while (!Worklist.empty());
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00002602
Michael Gottesman5c0ae472013-01-04 21:29:57 +00002603 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Finished Queue.\n\n");
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00002604
John McCall9fbd3182011-06-15 23:37:01 +00002605 }
2606}
2607
2608/// CheckForCFGHazards - Check for critical edges, loop boundaries, irreducible
2609/// control flow, or other CFG structures where moving code across the edge
2610/// would result in it being executed more.
2611void
2612ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
2613 DenseMap<const BasicBlock *, BBState> &BBStates,
2614 BBState &MyStates) const {
2615 // If any top-down local-use or possible-dec has a succ which is earlier in
2616 // the sequence, forget it.
Dan Gohman22cc4cc2012-03-02 01:13:53 +00002617 for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
John McCall9fbd3182011-06-15 23:37:01 +00002618 E = MyStates.top_down_ptr_end(); I != E; ++I)
2619 switch (I->second.GetSeq()) {
2620 default: break;
2621 case S_Use: {
2622 const Value *Arg = I->first;
2623 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2624 bool SomeSuccHasSame = false;
2625 bool AllSuccsHaveSame = true;
Dan Gohman22cc4cc2012-03-02 01:13:53 +00002626 PtrState &S = I->second;
Dan Gohmandbe266b2012-02-17 18:59:53 +00002627 succ_const_iterator SI(TI), SE(TI, false);
2628
2629 // If the terminator is an invoke marked with the
2630 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
2631 // ignored, for ARC purposes.
2632 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind))
2633 --SE;
2634
2635 for (; SI != SE; ++SI) {
Dan Gohman70e29682012-03-02 01:26:46 +00002636 Sequence SuccSSeq = S_None;
2637 bool SuccSRRIKnownSafe = false;
Dan Gohman0daef3d2012-05-08 23:39:44 +00002638 // If VisitBottomUp has pointer information for this successor, take
2639 // what we know about it.
Dan Gohman447989c2012-04-27 18:56:31 +00002640 DenseMap<const BasicBlock *, BBState>::iterator BBI =
2641 BBStates.find(*SI);
2642 assert(BBI != BBStates.end());
2643 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2644 SuccSSeq = SuccS.GetSeq();
2645 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
Dan Gohman70e29682012-03-02 01:26:46 +00002646 switch (SuccSSeq) {
John McCall9fbd3182011-06-15 23:37:01 +00002647 case S_None:
Dan Gohmana7f7db22011-08-12 00:26:31 +00002648 case S_CanRelease: {
Dan Gohman70e29682012-03-02 01:26:46 +00002649 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
Dan Gohmana7f7db22011-08-12 00:26:31 +00002650 S.ClearSequenceProgress();
Dan Gohman70e29682012-03-02 01:26:46 +00002651 break;
2652 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002653 continue;
2654 }
John McCall9fbd3182011-06-15 23:37:01 +00002655 case S_Use:
2656 SomeSuccHasSame = true;
2657 break;
2658 case S_Stop:
2659 case S_Release:
2660 case S_MovableRelease:
Dan Gohman70e29682012-03-02 01:26:46 +00002661 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002662 AllSuccsHaveSame = false;
John McCall9fbd3182011-06-15 23:37:01 +00002663 break;
2664 case S_Retain:
2665 llvm_unreachable("bottom-up pointer in retain state!");
2666 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002667 }
John McCall9fbd3182011-06-15 23:37:01 +00002668 // If the state at the other end of any of the successor edges
2669 // matches the current state, require all edges to match. This
2670 // guards against loops in the middle of a sequence.
2671 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002672 S.ClearSequenceProgress();
Dan Gohman2e68beb2011-12-12 18:13:53 +00002673 break;
John McCall9fbd3182011-06-15 23:37:01 +00002674 }
2675 case S_CanRelease: {
2676 const Value *Arg = I->first;
2677 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2678 bool SomeSuccHasSame = false;
2679 bool AllSuccsHaveSame = true;
Dan Gohman22cc4cc2012-03-02 01:13:53 +00002680 PtrState &S = I->second;
Dan Gohmandbe266b2012-02-17 18:59:53 +00002681 succ_const_iterator SI(TI), SE(TI, false);
2682
2683 // If the terminator is an invoke marked with the
2684 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
2685 // ignored, for ARC purposes.
2686 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind))
2687 --SE;
2688
2689 for (; SI != SE; ++SI) {
Dan Gohman70e29682012-03-02 01:26:46 +00002690 Sequence SuccSSeq = S_None;
2691 bool SuccSRRIKnownSafe = false;
Dan Gohman0daef3d2012-05-08 23:39:44 +00002692 // If VisitBottomUp has pointer information for this successor, take
2693 // what we know about it.
Dan Gohman447989c2012-04-27 18:56:31 +00002694 DenseMap<const BasicBlock *, BBState>::iterator BBI =
2695 BBStates.find(*SI);
2696 assert(BBI != BBStates.end());
2697 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2698 SuccSSeq = SuccS.GetSeq();
2699 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
Dan Gohman70e29682012-03-02 01:26:46 +00002700 switch (SuccSSeq) {
Dan Gohmana7f7db22011-08-12 00:26:31 +00002701 case S_None: {
Dan Gohman70e29682012-03-02 01:26:46 +00002702 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
Dan Gohmana7f7db22011-08-12 00:26:31 +00002703 S.ClearSequenceProgress();
Dan Gohman70e29682012-03-02 01:26:46 +00002704 break;
2705 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002706 continue;
2707 }
John McCall9fbd3182011-06-15 23:37:01 +00002708 case S_CanRelease:
2709 SomeSuccHasSame = true;
2710 break;
2711 case S_Stop:
2712 case S_Release:
2713 case S_MovableRelease:
2714 case S_Use:
Dan Gohman70e29682012-03-02 01:26:46 +00002715 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002716 AllSuccsHaveSame = false;
John McCall9fbd3182011-06-15 23:37:01 +00002717 break;
2718 case S_Retain:
2719 llvm_unreachable("bottom-up pointer in retain state!");
2720 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002721 }
John McCall9fbd3182011-06-15 23:37:01 +00002722 // If the state at the other end of any of the successor edges
2723 // matches the current state, require all edges to match. This
2724 // guards against loops in the middle of a sequence.
2725 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002726 S.ClearSequenceProgress();
Dan Gohman2e68beb2011-12-12 18:13:53 +00002727 break;
John McCall9fbd3182011-06-15 23:37:01 +00002728 }
2729 }
2730}
2731
2732bool
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002733ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002734 BasicBlock *BB,
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002735 MapVector<Value *, RRInfo> &Retains,
2736 BBState &MyStates) {
2737 bool NestingDetected = false;
2738 InstructionClass Class = GetInstructionClass(Inst);
2739 const Value *Arg = 0;
2740
2741 switch (Class) {
2742 case IC_Release: {
2743 Arg = GetObjCArg(Inst);
2744
2745 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2746
2747 // If we see two releases in a row on the same pointer. If so, make
2748 // a note, and we'll cicle back to revisit it after we've
2749 // hopefully eliminated the second release, which may allow us to
2750 // eliminate the first release too.
2751 // Theoretically we could implement removal of nested retain+release
2752 // pairs by making PtrState hold a stack of states, but this is
2753 // simple and avoids adding overhead for the non-nested case.
2754 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease)
2755 NestingDetected = true;
2756
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002757 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
Dan Gohman50ade652012-04-25 00:50:46 +00002758 S.ResetSequenceProgress(ReleaseMetadata ? S_MovableRelease : S_Release);
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002759 S.RRI.ReleaseMetadata = ReleaseMetadata;
Dan Gohman230768b2012-09-04 23:16:20 +00002760 S.RRI.KnownSafe = S.IsKnownIncremented();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002761 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2762 S.RRI.Calls.insert(Inst);
2763
Dan Gohman230768b2012-09-04 23:16:20 +00002764 S.SetKnownPositiveRefCount();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002765 break;
2766 }
2767 case IC_RetainBlock:
2768 // An objc_retainBlock call with just a use may need to be kept,
2769 // because it may be copying a block from the stack to the heap.
2770 if (!IsRetainBlockOptimizable(Inst))
2771 break;
2772 // FALLTHROUGH
2773 case IC_Retain:
2774 case IC_RetainRV: {
2775 Arg = GetObjCArg(Inst);
2776
2777 PtrState &S = MyStates.getPtrBottomUpState(Arg);
Dan Gohman50ade652012-04-25 00:50:46 +00002778 S.SetKnownPositiveRefCount();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002779
2780 switch (S.GetSeq()) {
2781 case S_Stop:
2782 case S_Release:
2783 case S_MovableRelease:
2784 case S_Use:
2785 S.RRI.ReverseInsertPts.clear();
2786 // FALL THROUGH
2787 case S_CanRelease:
2788 // Don't do retain+release tracking for IC_RetainRV, because it's
2789 // better to let it remain as the first instruction after a call.
2790 if (Class != IC_RetainRV) {
2791 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2792 Retains[Inst] = S.RRI;
2793 }
2794 S.ClearSequenceProgress();
2795 break;
2796 case S_None:
2797 break;
2798 case S_Retain:
2799 llvm_unreachable("bottom-up pointer in retain state!");
2800 }
2801 return NestingDetected;
2802 }
2803 case IC_AutoreleasepoolPop:
2804 // Conservatively, clear MyStates for all known pointers.
2805 MyStates.clearBottomUpPointers();
2806 return NestingDetected;
2807 case IC_AutoreleasepoolPush:
2808 case IC_None:
2809 // These are irrelevant.
2810 return NestingDetected;
2811 default:
2812 break;
2813 }
2814
2815 // Consider any other possible effects of this instruction on each
2816 // pointer being tracked.
2817 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
2818 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
2819 const Value *Ptr = MI->first;
2820 if (Ptr == Arg)
2821 continue; // Handled above.
2822 PtrState &S = MI->second;
2823 Sequence Seq = S.GetSeq();
2824
2825 // Check for possible releases.
2826 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Dan Gohman50ade652012-04-25 00:50:46 +00002827 S.ClearRefCount();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002828 switch (Seq) {
2829 case S_Use:
2830 S.SetSeq(S_CanRelease);
2831 continue;
2832 case S_CanRelease:
2833 case S_Release:
2834 case S_MovableRelease:
2835 case S_Stop:
2836 case S_None:
2837 break;
2838 case S_Retain:
2839 llvm_unreachable("bottom-up pointer in retain state!");
2840 }
2841 }
2842
2843 // Check for possible direct uses.
2844 switch (Seq) {
2845 case S_Release:
2846 case S_MovableRelease:
2847 if (CanUse(Inst, Ptr, PA, Class)) {
2848 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002849 // If this is an invoke instruction, we're scanning it as part of
2850 // one of its successor blocks, since we can't insert code after it
2851 // in its own block, and we don't want to split critical edges.
2852 if (isa<InvokeInst>(Inst))
2853 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2854 else
Francois Pichetb54a5ed2012-03-24 01:36:37 +00002855 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002856 S.SetSeq(S_Use);
2857 } else if (Seq == S_Release &&
2858 (Class == IC_User || Class == IC_CallOrUser)) {
2859 // Non-movable releases depend on any possible objc pointer use.
2860 S.SetSeq(S_Stop);
2861 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002862 // As above; handle invoke specially.
2863 if (isa<InvokeInst>(Inst))
2864 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2865 else
Francois Pichetb54a5ed2012-03-24 01:36:37 +00002866 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002867 }
2868 break;
2869 case S_Stop:
2870 if (CanUse(Inst, Ptr, PA, Class))
2871 S.SetSeq(S_Use);
2872 break;
2873 case S_CanRelease:
2874 case S_Use:
2875 case S_None:
2876 break;
2877 case S_Retain:
2878 llvm_unreachable("bottom-up pointer in retain state!");
2879 }
2880 }
2881
2882 return NestingDetected;
2883}
2884
2885bool
John McCall9fbd3182011-06-15 23:37:01 +00002886ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2887 DenseMap<const BasicBlock *, BBState> &BBStates,
2888 MapVector<Value *, RRInfo> &Retains) {
2889 bool NestingDetected = false;
2890 BBState &MyStates = BBStates[BB];
2891
2892 // Merge the states from each successor to compute the initial state
2893 // for the current block.
Dan Gohman40e46602012-08-27 18:31:36 +00002894 BBState::edge_iterator SI(MyStates.succ_begin()),
2895 SE(MyStates.succ_end());
2896 if (SI != SE) {
Dan Gohmaneeeb7752012-04-24 22:53:18 +00002897 const BasicBlock *Succ = *SI;
2898 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
2899 assert(I != BBStates.end());
2900 MyStates.InitFromSucc(I->second);
2901 ++SI;
2902 for (; SI != SE; ++SI) {
2903 Succ = *SI;
2904 I = BBStates.find(Succ);
2905 assert(I != BBStates.end());
2906 MyStates.MergeSucc(I->second);
2907 }
Dan Gohmandbe266b2012-02-17 18:59:53 +00002908 }
John McCall9fbd3182011-06-15 23:37:01 +00002909
2910 // Visit all the instructions, bottom-up.
2911 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2912 Instruction *Inst = llvm::prior(I);
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002913
2914 // Invoke instructions are visited as part of their successors (below).
2915 if (isa<InvokeInst>(Inst))
2916 continue;
2917
2918 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
2919 }
2920
Dan Gohman447989c2012-04-27 18:56:31 +00002921 // If there's a predecessor with an invoke, visit the invoke as if it were
2922 // part of this block, since we can't insert code after an invoke in its own
2923 // block, and we don't want to split critical edges.
Dan Gohmaneeeb7752012-04-24 22:53:18 +00002924 for (BBState::edge_iterator PI(MyStates.pred_begin()),
2925 PE(MyStates.pred_end()); PI != PE; ++PI) {
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002926 BasicBlock *Pred = *PI;
Dan Gohman447989c2012-04-27 18:56:31 +00002927 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
2928 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002929 }
John McCall9fbd3182011-06-15 23:37:01 +00002930
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002931 return NestingDetected;
2932}
John McCall9fbd3182011-06-15 23:37:01 +00002933
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002934bool
2935ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
2936 DenseMap<Value *, RRInfo> &Releases,
2937 BBState &MyStates) {
2938 bool NestingDetected = false;
2939 InstructionClass Class = GetInstructionClass(Inst);
2940 const Value *Arg = 0;
John McCall9fbd3182011-06-15 23:37:01 +00002941
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002942 switch (Class) {
2943 case IC_RetainBlock:
2944 // An objc_retainBlock call with just a use may need to be kept,
2945 // because it may be copying a block from the stack to the heap.
2946 if (!IsRetainBlockOptimizable(Inst))
2947 break;
2948 // FALLTHROUGH
2949 case IC_Retain:
2950 case IC_RetainRV: {
2951 Arg = GetObjCArg(Inst);
2952
2953 PtrState &S = MyStates.getPtrTopDownState(Arg);
2954
2955 // Don't do retain+release tracking for IC_RetainRV, because it's
2956 // better to let it remain as the first instruction after a call.
2957 if (Class != IC_RetainRV) {
2958 // If we see two retains in a row on the same pointer. If so, make
John McCall9fbd3182011-06-15 23:37:01 +00002959 // a note, and we'll cicle back to revisit it after we've
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002960 // hopefully eliminated the second retain, which may allow us to
2961 // eliminate the first retain too.
John McCall9fbd3182011-06-15 23:37:01 +00002962 // Theoretically we could implement removal of nested retain+release
2963 // pairs by making PtrState hold a stack of states, but this is
2964 // simple and avoids adding overhead for the non-nested case.
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002965 if (S.GetSeq() == S_Retain)
John McCall9fbd3182011-06-15 23:37:01 +00002966 NestingDetected = true;
2967
Dan Gohman50ade652012-04-25 00:50:46 +00002968 S.ResetSequenceProgress(S_Retain);
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002969 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
Dan Gohman230768b2012-09-04 23:16:20 +00002970 S.RRI.KnownSafe = S.IsKnownIncremented();
John McCall9fbd3182011-06-15 23:37:01 +00002971 S.RRI.Calls.insert(Inst);
John McCall9fbd3182011-06-15 23:37:01 +00002972 }
John McCall9fbd3182011-06-15 23:37:01 +00002973
Dan Gohman230768b2012-09-04 23:16:20 +00002974 S.SetKnownPositiveRefCount();
Dan Gohmanc72d3be2012-07-23 19:27:31 +00002975
2976 // A retain can be a potential use; procede to the generic checking
2977 // code below.
2978 break;
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002979 }
2980 case IC_Release: {
2981 Arg = GetObjCArg(Inst);
2982
2983 PtrState &S = MyStates.getPtrTopDownState(Arg);
Dan Gohman230768b2012-09-04 23:16:20 +00002984 S.ClearRefCount();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002985
2986 switch (S.GetSeq()) {
2987 case S_Retain:
2988 case S_CanRelease:
2989 S.RRI.ReverseInsertPts.clear();
2990 // FALL THROUGH
2991 case S_Use:
2992 S.RRI.ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2993 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2994 Releases[Inst] = S.RRI;
2995 S.ClearSequenceProgress();
2996 break;
2997 case S_None:
2998 break;
2999 case S_Stop:
3000 case S_Release:
3001 case S_MovableRelease:
3002 llvm_unreachable("top-down pointer in release state!");
3003 }
3004 break;
3005 }
3006 case IC_AutoreleasepoolPop:
3007 // Conservatively, clear MyStates for all known pointers.
3008 MyStates.clearTopDownPointers();
3009 return NestingDetected;
3010 case IC_AutoreleasepoolPush:
3011 case IC_None:
3012 // These are irrelevant.
3013 return NestingDetected;
3014 default:
3015 break;
3016 }
3017
3018 // Consider any other possible effects of this instruction on each
3019 // pointer being tracked.
3020 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
3021 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
3022 const Value *Ptr = MI->first;
3023 if (Ptr == Arg)
3024 continue; // Handled above.
3025 PtrState &S = MI->second;
3026 Sequence Seq = S.GetSeq();
3027
3028 // Check for possible releases.
3029 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Dan Gohman50ade652012-04-25 00:50:46 +00003030 S.ClearRefCount();
John McCall9fbd3182011-06-15 23:37:01 +00003031 switch (Seq) {
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003032 case S_Retain:
3033 S.SetSeq(S_CanRelease);
3034 assert(S.RRI.ReverseInsertPts.empty());
3035 S.RRI.ReverseInsertPts.insert(Inst);
3036
3037 // One call can't cause a transition from S_Retain to S_CanRelease
3038 // and S_CanRelease to S_Use. If we've made the first transition,
3039 // we're done.
3040 continue;
John McCall9fbd3182011-06-15 23:37:01 +00003041 case S_Use:
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003042 case S_CanRelease:
John McCall9fbd3182011-06-15 23:37:01 +00003043 case S_None:
3044 break;
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003045 case S_Stop:
3046 case S_Release:
3047 case S_MovableRelease:
3048 llvm_unreachable("top-down pointer in release state!");
John McCall9fbd3182011-06-15 23:37:01 +00003049 }
3050 }
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003051
3052 // Check for possible direct uses.
3053 switch (Seq) {
3054 case S_CanRelease:
3055 if (CanUse(Inst, Ptr, PA, Class))
3056 S.SetSeq(S_Use);
3057 break;
3058 case S_Retain:
3059 case S_Use:
3060 case S_None:
3061 break;
3062 case S_Stop:
3063 case S_Release:
3064 case S_MovableRelease:
3065 llvm_unreachable("top-down pointer in release state!");
3066 }
John McCall9fbd3182011-06-15 23:37:01 +00003067 }
3068
3069 return NestingDetected;
3070}
3071
3072bool
3073ObjCARCOpt::VisitTopDown(BasicBlock *BB,
3074 DenseMap<const BasicBlock *, BBState> &BBStates,
3075 DenseMap<Value *, RRInfo> &Releases) {
3076 bool NestingDetected = false;
3077 BBState &MyStates = BBStates[BB];
3078
3079 // Merge the states from each predecessor to compute the initial state
3080 // for the current block.
Dan Gohman40e46602012-08-27 18:31:36 +00003081 BBState::edge_iterator PI(MyStates.pred_begin()),
3082 PE(MyStates.pred_end());
3083 if (PI != PE) {
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003084 const BasicBlock *Pred = *PI;
3085 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
3086 assert(I != BBStates.end());
3087 MyStates.InitFromPred(I->second);
3088 ++PI;
3089 for (; PI != PE; ++PI) {
3090 Pred = *PI;
3091 I = BBStates.find(Pred);
3092 assert(I != BBStates.end());
3093 MyStates.MergePred(I->second);
3094 }
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003095 }
John McCall9fbd3182011-06-15 23:37:01 +00003096
3097 // Visit all the instructions, top-down.
3098 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3099 Instruction *Inst = I;
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003100 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
John McCall9fbd3182011-06-15 23:37:01 +00003101 }
3102
3103 CheckForCFGHazards(BB, BBStates, MyStates);
3104 return NestingDetected;
3105}
3106
Dan Gohman59a1c932011-12-12 19:42:25 +00003107static void
3108ComputePostOrders(Function &F,
3109 SmallVectorImpl<BasicBlock *> &PostOrder,
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003110 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
3111 unsigned NoObjCARCExceptionsMDKind,
3112 DenseMap<const BasicBlock *, BBState> &BBStates) {
Dan Gohman59a1c932011-12-12 19:42:25 +00003113 /// Visited - The visited set, for doing DFS walks.
3114 SmallPtrSet<BasicBlock *, 16> Visited;
3115
3116 // Do DFS, computing the PostOrder.
3117 SmallPtrSet<BasicBlock *, 16> OnStack;
3118 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003119
3120 // Functions always have exactly one entry block, and we don't have
3121 // any other block that we treat like an entry block.
Dan Gohman59a1c932011-12-12 19:42:25 +00003122 BasicBlock *EntryBB = &F.getEntryBlock();
Dan Gohman0daef3d2012-05-08 23:39:44 +00003123 BBState &MyStates = BBStates[EntryBB];
3124 MyStates.SetAsEntry();
3125 TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
3126 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
Dan Gohman59a1c932011-12-12 19:42:25 +00003127 Visited.insert(EntryBB);
3128 OnStack.insert(EntryBB);
3129 do {
3130 dfs_next_succ:
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003131 BasicBlock *CurrBB = SuccStack.back().first;
3132 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
3133 succ_iterator SE(TI, false);
Dan Gohman0daef3d2012-05-08 23:39:44 +00003134
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003135 // If the terminator is an invoke marked with the
3136 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
3137 // ignored, for ARC purposes.
3138 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind))
3139 --SE;
3140
3141 while (SuccStack.back().second != SE) {
3142 BasicBlock *SuccBB = *SuccStack.back().second++;
3143 if (Visited.insert(SuccBB)) {
Dan Gohman0daef3d2012-05-08 23:39:44 +00003144 TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
3145 SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003146 BBStates[CurrBB].addSucc(SuccBB);
Dan Gohman0daef3d2012-05-08 23:39:44 +00003147 BBState &SuccStates = BBStates[SuccBB];
3148 SuccStates.addPred(CurrBB);
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003149 OnStack.insert(SuccBB);
Dan Gohman59a1c932011-12-12 19:42:25 +00003150 goto dfs_next_succ;
3151 }
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003152
3153 if (!OnStack.count(SuccBB)) {
3154 BBStates[CurrBB].addSucc(SuccBB);
3155 BBStates[SuccBB].addPred(CurrBB);
3156 }
Dan Gohman59a1c932011-12-12 19:42:25 +00003157 }
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003158 OnStack.erase(CurrBB);
3159 PostOrder.push_back(CurrBB);
3160 SuccStack.pop_back();
Dan Gohman59a1c932011-12-12 19:42:25 +00003161 } while (!SuccStack.empty());
3162
3163 Visited.clear();
3164
Dan Gohman59a1c932011-12-12 19:42:25 +00003165 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003166 // Functions may have many exits, and there also blocks which we treat
3167 // as exits due to ignored edges.
3168 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
3169 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
3170 BasicBlock *ExitBB = I;
3171 BBState &MyStates = BBStates[ExitBB];
3172 if (!MyStates.isExit())
3173 continue;
3174
Dan Gohman447989c2012-04-27 18:56:31 +00003175 MyStates.SetAsExit();
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003176
3177 PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
Dan Gohman59a1c932011-12-12 19:42:25 +00003178 Visited.insert(ExitBB);
3179 while (!PredStack.empty()) {
3180 reverse_dfs_next_succ:
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003181 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
3182 while (PredStack.back().second != PE) {
Dan Gohman59a1c932011-12-12 19:42:25 +00003183 BasicBlock *BB = *PredStack.back().second++;
Dan Gohman59a1c932011-12-12 19:42:25 +00003184 if (Visited.insert(BB)) {
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003185 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
Dan Gohman59a1c932011-12-12 19:42:25 +00003186 goto reverse_dfs_next_succ;
3187 }
3188 }
3189 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
3190 }
3191 }
3192}
3193
John McCall9fbd3182011-06-15 23:37:01 +00003194// Visit - Visit the function both top-down and bottom-up.
3195bool
3196ObjCARCOpt::Visit(Function &F,
3197 DenseMap<const BasicBlock *, BBState> &BBStates,
3198 MapVector<Value *, RRInfo> &Retains,
3199 DenseMap<Value *, RRInfo> &Releases) {
Dan Gohman59a1c932011-12-12 19:42:25 +00003200
3201 // Use reverse-postorder traversals, because we magically know that loops
3202 // will be well behaved, i.e. they won't repeatedly call retain on a single
3203 // pointer without doing a release. We can't use the ReversePostOrderTraversal
3204 // class here because we want the reverse-CFG postorder to consider each
3205 // function exit point, and we want to ignore selected cycle edges.
3206 SmallVector<BasicBlock *, 16> PostOrder;
3207 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003208 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
3209 NoObjCARCExceptionsMDKind,
3210 BBStates);
Dan Gohman59a1c932011-12-12 19:42:25 +00003211
3212 // Use reverse-postorder on the reverse CFG for bottom-up.
John McCall9fbd3182011-06-15 23:37:01 +00003213 bool BottomUpNestingDetected = false;
Dan Gohmanb48ef3a2011-08-18 21:27:42 +00003214 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
Dan Gohman59a1c932011-12-12 19:42:25 +00003215 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
3216 I != E; ++I)
3217 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
John McCall9fbd3182011-06-15 23:37:01 +00003218
Dan Gohman59a1c932011-12-12 19:42:25 +00003219 // Use reverse-postorder for top-down.
John McCall9fbd3182011-06-15 23:37:01 +00003220 bool TopDownNestingDetected = false;
Dan Gohman59a1c932011-12-12 19:42:25 +00003221 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
3222 PostOrder.rbegin(), E = PostOrder.rend();
3223 I != E; ++I)
3224 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
John McCall9fbd3182011-06-15 23:37:01 +00003225
3226 return TopDownNestingDetected && BottomUpNestingDetected;
3227}
3228
3229/// MoveCalls - Move the calls in RetainsToMove and ReleasesToMove.
3230void ObjCARCOpt::MoveCalls(Value *Arg,
3231 RRInfo &RetainsToMove,
3232 RRInfo &ReleasesToMove,
3233 MapVector<Value *, RRInfo> &Retains,
3234 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman44280692011-07-22 22:29:21 +00003235 SmallVectorImpl<Instruction *> &DeadInsts,
3236 Module *M) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003237 Type *ArgTy = Arg->getType();
Dan Gohman44280692011-07-22 22:29:21 +00003238 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
John McCall9fbd3182011-06-15 23:37:01 +00003239
3240 // Insert the new retain and release calls.
3241 for (SmallPtrSet<Instruction *, 2>::const_iterator
3242 PI = ReleasesToMove.ReverseInsertPts.begin(),
3243 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
3244 Instruction *InsertPt = *PI;
3245 Value *MyArg = ArgTy == ParamTy ? Arg :
3246 new BitCastInst(Arg, ParamTy, "", InsertPt);
3247 CallInst *Call =
3248 CallInst::Create(RetainsToMove.IsRetainBlock ?
Dan Gohman44280692011-07-22 22:29:21 +00003249 getRetainBlockCallee(M) : getRetainCallee(M),
John McCall9fbd3182011-06-15 23:37:01 +00003250 MyArg, "", InsertPt);
3251 Call->setDoesNotThrow();
Dan Gohman79522dc2012-01-13 00:39:07 +00003252 if (RetainsToMove.IsRetainBlock)
Dan Gohmana974bea2011-10-17 22:53:25 +00003253 Call->setMetadata(CopyOnEscapeMDKind,
3254 MDNode::get(M->getContext(), ArrayRef<Value *>()));
Dan Gohman79522dc2012-01-13 00:39:07 +00003255 else
John McCall9fbd3182011-06-15 23:37:01 +00003256 Call->setTailCall();
Michael Gottesman55811152013-01-09 19:23:24 +00003257
3258 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Inserting new Release: " << *Call
3259 << "\n"
3260 " At insertion point: " << *InsertPt
3261 << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00003262 }
3263 for (SmallPtrSet<Instruction *, 2>::const_iterator
3264 PI = RetainsToMove.ReverseInsertPts.begin(),
3265 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
Dan Gohmanfbab4a82012-03-23 17:47:54 +00003266 Instruction *InsertPt = *PI;
3267 Value *MyArg = ArgTy == ParamTy ? Arg :
3268 new BitCastInst(Arg, ParamTy, "", InsertPt);
3269 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
3270 "", InsertPt);
3271 // Attach a clang.imprecise_release metadata tag, if appropriate.
3272 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
3273 Call->setMetadata(ImpreciseReleaseMDKind, M);
3274 Call->setDoesNotThrow();
3275 if (ReleasesToMove.IsTailCallRelease)
3276 Call->setTailCall();
Michael Gottesman55811152013-01-09 19:23:24 +00003277
3278 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Inserting new Retain: " << *Call
3279 << "\n"
3280 " At insertion point: " << *InsertPt
3281 << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00003282 }
3283
3284 // Delete the original retain and release calls.
3285 for (SmallPtrSet<Instruction *, 2>::const_iterator
3286 AI = RetainsToMove.Calls.begin(),
3287 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
3288 Instruction *OrigRetain = *AI;
3289 Retains.blot(OrigRetain);
3290 DeadInsts.push_back(OrigRetain);
Michael Gottesman55811152013-01-09 19:23:24 +00003291 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Deleting retain: " << *OrigRetain <<
3292 "\n");
John McCall9fbd3182011-06-15 23:37:01 +00003293 }
3294 for (SmallPtrSet<Instruction *, 2>::const_iterator
3295 AI = ReleasesToMove.Calls.begin(),
3296 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
3297 Instruction *OrigRelease = *AI;
3298 Releases.erase(OrigRelease);
3299 DeadInsts.push_back(OrigRelease);
Michael Gottesman55811152013-01-09 19:23:24 +00003300 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Deleting release: " << *OrigRelease
3301 << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00003302 }
3303}
3304
Dan Gohmand6bf2012012-04-13 18:57:48 +00003305/// PerformCodePlacement - Identify pairings between the retains and releases,
3306/// and delete and/or move them.
John McCall9fbd3182011-06-15 23:37:01 +00003307bool
3308ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
3309 &BBStates,
3310 MapVector<Value *, RRInfo> &Retains,
Dan Gohman44280692011-07-22 22:29:21 +00003311 DenseMap<Value *, RRInfo> &Releases,
3312 Module *M) {
John McCall9fbd3182011-06-15 23:37:01 +00003313 bool AnyPairsCompletelyEliminated = false;
3314 RRInfo RetainsToMove;
3315 RRInfo ReleasesToMove;
3316 SmallVector<Instruction *, 4> NewRetains;
3317 SmallVector<Instruction *, 4> NewReleases;
3318 SmallVector<Instruction *, 8> DeadInsts;
3319
Dan Gohmand6bf2012012-04-13 18:57:48 +00003320 // Visit each retain.
John McCall9fbd3182011-06-15 23:37:01 +00003321 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
Dan Gohman597fece2011-09-29 22:25:23 +00003322 E = Retains.end(); I != E; ++I) {
3323 Value *V = I->first;
John McCall9fbd3182011-06-15 23:37:01 +00003324 if (!V) continue; // blotted
3325
3326 Instruction *Retain = cast<Instruction>(V);
Michael Gottesman55811152013-01-09 19:23:24 +00003327
3328 DEBUG(dbgs() << "ObjCARCOpt::PerformCodePlacement: Visiting: " << *Retain
3329 << "\n");
3330
John McCall9fbd3182011-06-15 23:37:01 +00003331 Value *Arg = GetObjCArg(Retain);
3332
Dan Gohman79522dc2012-01-13 00:39:07 +00003333 // If the object being released is in static or stack storage, we know it's
John McCall9fbd3182011-06-15 23:37:01 +00003334 // not being managed by ObjC reference counting, so we can delete pairs
3335 // regardless of what possible decrements or uses lie between them.
Dan Gohman79522dc2012-01-13 00:39:07 +00003336 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
Dan Gohman0daef3d2012-05-08 23:39:44 +00003337
Dan Gohman1b31ea82011-08-22 17:29:11 +00003338 // A constant pointer can't be pointing to an object on the heap. It may
3339 // be reference-counted, but it won't be deleted.
3340 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
3341 if (const GlobalVariable *GV =
3342 dyn_cast<GlobalVariable>(
3343 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
3344 if (GV->isConstant())
3345 KnownSafe = true;
3346
John McCall9fbd3182011-06-15 23:37:01 +00003347 // If a pair happens in a region where it is known that the reference count
3348 // is already incremented, we can similarly ignore possible decrements.
Dan Gohmane6d5e882011-08-19 00:26:36 +00003349 bool KnownSafeTD = true, KnownSafeBU = true;
John McCall9fbd3182011-06-15 23:37:01 +00003350
3351 // Connect the dots between the top-down-collected RetainsToMove and
3352 // bottom-up-collected ReleasesToMove to form sets of related calls.
3353 // This is an iterative process so that we connect multiple releases
3354 // to multiple retains if needed.
3355 unsigned OldDelta = 0;
3356 unsigned NewDelta = 0;
3357 unsigned OldCount = 0;
3358 unsigned NewCount = 0;
3359 bool FirstRelease = true;
3360 bool FirstRetain = true;
3361 NewRetains.push_back(Retain);
3362 for (;;) {
3363 for (SmallVectorImpl<Instruction *>::const_iterator
3364 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
3365 Instruction *NewRetain = *NI;
3366 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
3367 assert(It != Retains.end());
3368 const RRInfo &NewRetainRRI = It->second;
Dan Gohmane6d5e882011-08-19 00:26:36 +00003369 KnownSafeTD &= NewRetainRRI.KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00003370 for (SmallPtrSet<Instruction *, 2>::const_iterator
3371 LI = NewRetainRRI.Calls.begin(),
3372 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
3373 Instruction *NewRetainRelease = *LI;
3374 DenseMap<Value *, RRInfo>::const_iterator Jt =
3375 Releases.find(NewRetainRelease);
3376 if (Jt == Releases.end())
3377 goto next_retain;
3378 const RRInfo &NewRetainReleaseRRI = Jt->second;
3379 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
3380 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
3381 OldDelta -=
3382 BBStates[NewRetainRelease->getParent()].GetAllPathCount();
3383
3384 // Merge the ReleaseMetadata and IsTailCallRelease values.
3385 if (FirstRelease) {
3386 ReleasesToMove.ReleaseMetadata =
3387 NewRetainReleaseRRI.ReleaseMetadata;
3388 ReleasesToMove.IsTailCallRelease =
3389 NewRetainReleaseRRI.IsTailCallRelease;
3390 FirstRelease = false;
3391 } else {
3392 if (ReleasesToMove.ReleaseMetadata !=
3393 NewRetainReleaseRRI.ReleaseMetadata)
3394 ReleasesToMove.ReleaseMetadata = 0;
3395 if (ReleasesToMove.IsTailCallRelease !=
3396 NewRetainReleaseRRI.IsTailCallRelease)
3397 ReleasesToMove.IsTailCallRelease = false;
3398 }
3399
3400 // Collect the optimal insertion points.
3401 if (!KnownSafe)
3402 for (SmallPtrSet<Instruction *, 2>::const_iterator
3403 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
3404 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
3405 RI != RE; ++RI) {
3406 Instruction *RIP = *RI;
3407 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
3408 NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
3409 }
3410 NewReleases.push_back(NewRetainRelease);
3411 }
3412 }
3413 }
3414 NewRetains.clear();
3415 if (NewReleases.empty()) break;
3416
3417 // Back the other way.
3418 for (SmallVectorImpl<Instruction *>::const_iterator
3419 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
3420 Instruction *NewRelease = *NI;
3421 DenseMap<Value *, RRInfo>::const_iterator It =
3422 Releases.find(NewRelease);
3423 assert(It != Releases.end());
3424 const RRInfo &NewReleaseRRI = It->second;
Dan Gohmane6d5e882011-08-19 00:26:36 +00003425 KnownSafeBU &= NewReleaseRRI.KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00003426 for (SmallPtrSet<Instruction *, 2>::const_iterator
3427 LI = NewReleaseRRI.Calls.begin(),
3428 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
3429 Instruction *NewReleaseRetain = *LI;
3430 MapVector<Value *, RRInfo>::const_iterator Jt =
3431 Retains.find(NewReleaseRetain);
3432 if (Jt == Retains.end())
3433 goto next_retain;
3434 const RRInfo &NewReleaseRetainRRI = Jt->second;
3435 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
3436 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
3437 unsigned PathCount =
3438 BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
3439 OldDelta += PathCount;
3440 OldCount += PathCount;
3441
3442 // Merge the IsRetainBlock values.
3443 if (FirstRetain) {
3444 RetainsToMove.IsRetainBlock = NewReleaseRetainRRI.IsRetainBlock;
3445 FirstRetain = false;
3446 } else if (ReleasesToMove.IsRetainBlock !=
3447 NewReleaseRetainRRI.IsRetainBlock)
3448 // It's not possible to merge the sequences if one uses
3449 // objc_retain and the other uses objc_retainBlock.
3450 goto next_retain;
3451
3452 // Collect the optimal insertion points.
3453 if (!KnownSafe)
3454 for (SmallPtrSet<Instruction *, 2>::const_iterator
3455 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
3456 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
3457 RI != RE; ++RI) {
3458 Instruction *RIP = *RI;
3459 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
3460 PathCount = BBStates[RIP->getParent()].GetAllPathCount();
3461 NewDelta += PathCount;
3462 NewCount += PathCount;
3463 }
3464 }
3465 NewRetains.push_back(NewReleaseRetain);
3466 }
3467 }
3468 }
3469 NewReleases.clear();
3470 if (NewRetains.empty()) break;
3471 }
3472
Dan Gohmane6d5e882011-08-19 00:26:36 +00003473 // If the pointer is known incremented or nested, we can safely delete the
3474 // pair regardless of what's between them.
3475 if (KnownSafeTD || KnownSafeBU) {
John McCall9fbd3182011-06-15 23:37:01 +00003476 RetainsToMove.ReverseInsertPts.clear();
3477 ReleasesToMove.ReverseInsertPts.clear();
3478 NewCount = 0;
Dan Gohmana7f7db22011-08-12 00:26:31 +00003479 } else {
3480 // Determine whether the new insertion points we computed preserve the
3481 // balance of retain and release calls through the program.
3482 // TODO: If the fully aggressive solution isn't valid, try to find a
3483 // less aggressive solution which is.
3484 if (NewDelta != 0)
3485 goto next_retain;
John McCall9fbd3182011-06-15 23:37:01 +00003486 }
3487
3488 // Determine whether the original call points are balanced in the retain and
3489 // release calls through the program. If not, conservatively don't touch
3490 // them.
3491 // TODO: It's theoretically possible to do code motion in this case, as
3492 // long as the existing imbalances are maintained.
3493 if (OldDelta != 0)
3494 goto next_retain;
3495
John McCall9fbd3182011-06-15 23:37:01 +00003496 // Ok, everything checks out and we're all set. Let's move some code!
3497 Changed = true;
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003498 assert(OldCount != 0 && "Unreachable code?");
3499 AnyPairsCompletelyEliminated = NewCount == 0;
John McCall9fbd3182011-06-15 23:37:01 +00003500 NumRRs += OldCount - NewCount;
Dan Gohman44280692011-07-22 22:29:21 +00003501 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
3502 Retains, Releases, DeadInsts, M);
John McCall9fbd3182011-06-15 23:37:01 +00003503
3504 next_retain:
3505 NewReleases.clear();
3506 NewRetains.clear();
3507 RetainsToMove.clear();
3508 ReleasesToMove.clear();
3509 }
3510
3511 // Now that we're done moving everything, we can delete the newly dead
3512 // instructions, as we no longer need them as insert points.
3513 while (!DeadInsts.empty())
3514 EraseInstruction(DeadInsts.pop_back_val());
3515
3516 return AnyPairsCompletelyEliminated;
3517}
3518
3519/// OptimizeWeakCalls - Weak pointer optimizations.
3520void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
3521 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
3522 // itself because it uses AliasAnalysis and we need to do provenance
3523 // queries instead.
3524 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3525 Instruction *Inst = &*I++;
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00003526
Michael Gottesman5c0ae472013-01-04 21:29:57 +00003527 DEBUG(dbgs() << "ObjCARCOpt::OptimizeWeakCalls: Visiting: " << *Inst <<
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00003528 "\n");
3529
John McCall9fbd3182011-06-15 23:37:01 +00003530 InstructionClass Class = GetBasicInstructionClass(Inst);
3531 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
3532 continue;
3533
3534 // Delete objc_loadWeak calls with no users.
3535 if (Class == IC_LoadWeak && Inst->use_empty()) {
3536 Inst->eraseFromParent();
3537 continue;
3538 }
3539
3540 // TODO: For now, just look for an earlier available version of this value
3541 // within the same block. Theoretically, we could do memdep-style non-local
3542 // analysis too, but that would want caching. A better approach would be to
3543 // use the technique that EarlyCSE uses.
3544 inst_iterator Current = llvm::prior(I);
3545 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
3546 for (BasicBlock::iterator B = CurrentBB->begin(),
3547 J = Current.getInstructionIterator();
3548 J != B; --J) {
3549 Instruction *EarlierInst = &*llvm::prior(J);
3550 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
3551 switch (EarlierClass) {
3552 case IC_LoadWeak:
3553 case IC_LoadWeakRetained: {
3554 // If this is loading from the same pointer, replace this load's value
3555 // with that one.
3556 CallInst *Call = cast<CallInst>(Inst);
3557 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3558 Value *Arg = Call->getArgOperand(0);
3559 Value *EarlierArg = EarlierCall->getArgOperand(0);
3560 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3561 case AliasAnalysis::MustAlias:
3562 Changed = true;
3563 // If the load has a builtin retain, insert a plain retain for it.
3564 if (Class == IC_LoadWeakRetained) {
3565 CallInst *CI =
3566 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3567 "", Call);
3568 CI->setTailCall();
3569 }
3570 // Zap the fully redundant load.
3571 Call->replaceAllUsesWith(EarlierCall);
3572 Call->eraseFromParent();
3573 goto clobbered;
3574 case AliasAnalysis::MayAlias:
3575 case AliasAnalysis::PartialAlias:
3576 goto clobbered;
3577 case AliasAnalysis::NoAlias:
3578 break;
3579 }
3580 break;
3581 }
3582 case IC_StoreWeak:
3583 case IC_InitWeak: {
3584 // If this is storing to the same pointer and has the same size etc.
3585 // replace this load's value with the stored value.
3586 CallInst *Call = cast<CallInst>(Inst);
3587 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3588 Value *Arg = Call->getArgOperand(0);
3589 Value *EarlierArg = EarlierCall->getArgOperand(0);
3590 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3591 case AliasAnalysis::MustAlias:
3592 Changed = true;
3593 // If the load has a builtin retain, insert a plain retain for it.
3594 if (Class == IC_LoadWeakRetained) {
3595 CallInst *CI =
3596 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3597 "", Call);
3598 CI->setTailCall();
3599 }
3600 // Zap the fully redundant load.
3601 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
3602 Call->eraseFromParent();
3603 goto clobbered;
3604 case AliasAnalysis::MayAlias:
3605 case AliasAnalysis::PartialAlias:
3606 goto clobbered;
3607 case AliasAnalysis::NoAlias:
3608 break;
3609 }
3610 break;
3611 }
3612 case IC_MoveWeak:
3613 case IC_CopyWeak:
3614 // TOOD: Grab the copied value.
3615 goto clobbered;
3616 case IC_AutoreleasepoolPush:
3617 case IC_None:
3618 case IC_User:
3619 // Weak pointers are only modified through the weak entry points
3620 // (and arbitrary calls, which could call the weak entry points).
3621 break;
3622 default:
3623 // Anything else could modify the weak pointer.
3624 goto clobbered;
3625 }
3626 }
3627 clobbered:;
3628 }
3629
3630 // Then, for each destroyWeak with an alloca operand, check to see if
3631 // the alloca and all its users can be zapped.
3632 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3633 Instruction *Inst = &*I++;
3634 InstructionClass Class = GetBasicInstructionClass(Inst);
3635 if (Class != IC_DestroyWeak)
3636 continue;
3637
3638 CallInst *Call = cast<CallInst>(Inst);
3639 Value *Arg = Call->getArgOperand(0);
3640 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
3641 for (Value::use_iterator UI = Alloca->use_begin(),
3642 UE = Alloca->use_end(); UI != UE; ++UI) {
Dan Gohman447989c2012-04-27 18:56:31 +00003643 const Instruction *UserInst = cast<Instruction>(*UI);
John McCall9fbd3182011-06-15 23:37:01 +00003644 switch (GetBasicInstructionClass(UserInst)) {
3645 case IC_InitWeak:
3646 case IC_StoreWeak:
3647 case IC_DestroyWeak:
3648 continue;
3649 default:
3650 goto done;
3651 }
3652 }
3653 Changed = true;
3654 for (Value::use_iterator UI = Alloca->use_begin(),
3655 UE = Alloca->use_end(); UI != UE; ) {
3656 CallInst *UserInst = cast<CallInst>(*UI++);
Dan Gohmance5d8b02012-05-18 22:17:29 +00003657 switch (GetBasicInstructionClass(UserInst)) {
3658 case IC_InitWeak:
3659 case IC_StoreWeak:
3660 // These functions return their second argument.
3661 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
3662 break;
3663 case IC_DestroyWeak:
3664 // No return value.
3665 break;
3666 default:
Dan Gohman4c8f9092012-05-21 17:41:28 +00003667 llvm_unreachable("alloca really is used!");
Dan Gohmance5d8b02012-05-18 22:17:29 +00003668 }
John McCall9fbd3182011-06-15 23:37:01 +00003669 UserInst->eraseFromParent();
3670 }
3671 Alloca->eraseFromParent();
3672 done:;
3673 }
3674 }
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00003675
Michael Gottesman5c0ae472013-01-04 21:29:57 +00003676 DEBUG(dbgs() << "ObjCARCOpt::OptimizeWeakCalls: Finished List.\n\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00003677
John McCall9fbd3182011-06-15 23:37:01 +00003678}
3679
3680/// OptimizeSequences - Identify program paths which execute sequences of
3681/// retains and releases which can be eliminated.
3682bool ObjCARCOpt::OptimizeSequences(Function &F) {
3683 /// Releases, Retains - These are used to store the results of the main flow
3684 /// analysis. These use Value* as the key instead of Instruction* so that the
3685 /// map stays valid when we get around to rewriting code and calls get
3686 /// replaced by arguments.
3687 DenseMap<Value *, RRInfo> Releases;
3688 MapVector<Value *, RRInfo> Retains;
3689
3690 /// BBStates, This is used during the traversal of the function to track the
3691 /// states for each identified object at each block.
3692 DenseMap<const BasicBlock *, BBState> BBStates;
3693
3694 // Analyze the CFG of the function, and all instructions.
3695 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
3696
3697 // Transform.
Dan Gohman44280692011-07-22 22:29:21 +00003698 return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) &&
3699 NestingDetected;
John McCall9fbd3182011-06-15 23:37:01 +00003700}
3701
3702/// OptimizeReturns - Look for this pattern:
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +00003703/// \code
John McCall9fbd3182011-06-15 23:37:01 +00003704/// %call = call i8* @something(...)
3705/// %2 = call i8* @objc_retain(i8* %call)
3706/// %3 = call i8* @objc_autorelease(i8* %2)
3707/// ret i8* %3
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +00003708/// \endcode
John McCall9fbd3182011-06-15 23:37:01 +00003709/// And delete the retain and autorelease.
3710///
3711/// Otherwise if it's just this:
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +00003712/// \code
John McCall9fbd3182011-06-15 23:37:01 +00003713/// %3 = call i8* @objc_autorelease(i8* %2)
3714/// ret i8* %3
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +00003715/// \endcode
John McCall9fbd3182011-06-15 23:37:01 +00003716/// convert the autorelease to autoreleaseRV.
3717void ObjCARCOpt::OptimizeReturns(Function &F) {
3718 if (!F.getReturnType()->isPointerTy())
3719 return;
3720
3721 SmallPtrSet<Instruction *, 4> DependingInstructions;
3722 SmallPtrSet<const BasicBlock *, 4> Visited;
3723 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3724 BasicBlock *BB = FI;
3725 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00003726
Michael Gottesman5c0ae472013-01-04 21:29:57 +00003727 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Visiting: " << *Ret << "\n");
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00003728
John McCall9fbd3182011-06-15 23:37:01 +00003729 if (!Ret) continue;
3730
3731 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
3732 FindDependencies(NeedsPositiveRetainCount, Arg,
3733 BB, Ret, DependingInstructions, Visited, PA);
3734 if (DependingInstructions.size() != 1)
3735 goto next_block;
3736
3737 {
3738 CallInst *Autorelease =
3739 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3740 if (!Autorelease)
3741 goto next_block;
Dan Gohman0daef3d2012-05-08 23:39:44 +00003742 InstructionClass AutoreleaseClass = GetBasicInstructionClass(Autorelease);
John McCall9fbd3182011-06-15 23:37:01 +00003743 if (!IsAutorelease(AutoreleaseClass))
3744 goto next_block;
3745 if (GetObjCArg(Autorelease) != Arg)
3746 goto next_block;
3747
3748 DependingInstructions.clear();
3749 Visited.clear();
3750
3751 // Check that there is nothing that can affect the reference
3752 // count between the autorelease and the retain.
3753 FindDependencies(CanChangeRetainCount, Arg,
3754 BB, Autorelease, DependingInstructions, Visited, PA);
3755 if (DependingInstructions.size() != 1)
3756 goto next_block;
3757
3758 {
3759 CallInst *Retain =
3760 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3761
3762 // Check that we found a retain with the same argument.
3763 if (!Retain ||
3764 !IsRetain(GetBasicInstructionClass(Retain)) ||
3765 GetObjCArg(Retain) != Arg)
3766 goto next_block;
3767
3768 DependingInstructions.clear();
3769 Visited.clear();
3770
3771 // Convert the autorelease to an autoreleaseRV, since it's
3772 // returning the value.
3773 if (AutoreleaseClass == IC_Autorelease) {
Michael Gottesman5dc30012013-01-10 02:03:50 +00003774 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Converting autorelease "
3775 "=> autoreleaseRV since it's returning a value.\n"
3776 " In: " << *Autorelease
3777 << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00003778 Autorelease->setCalledFunction(getAutoreleaseRVCallee(F.getParent()));
Michael Gottesman5dc30012013-01-10 02:03:50 +00003779 DEBUG(dbgs() << " Out: " << *Autorelease
3780 << "\n");
Michael Gottesmane8c161a2013-01-12 01:25:15 +00003781 Autorelease->setTailCall(); // Always tail call autoreleaseRV.
John McCall9fbd3182011-06-15 23:37:01 +00003782 AutoreleaseClass = IC_AutoreleaseRV;
3783 }
3784
3785 // Check that there is nothing that can affect the reference
3786 // count between the retain and the call.
Dan Gohman27e06662011-09-29 22:27:34 +00003787 // Note that Retain need not be in BB.
3788 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
John McCall9fbd3182011-06-15 23:37:01 +00003789 DependingInstructions, Visited, PA);
3790 if (DependingInstructions.size() != 1)
3791 goto next_block;
3792
3793 {
3794 CallInst *Call =
3795 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3796
3797 // Check that the pointer is the return value of the call.
3798 if (!Call || Arg != Call)
3799 goto next_block;
3800
3801 // Check that the call is a regular call.
3802 InstructionClass Class = GetBasicInstructionClass(Call);
3803 if (Class != IC_CallOrUser && Class != IC_Call)
3804 goto next_block;
3805
3806 // If so, we can zap the retain and autorelease.
3807 Changed = true;
3808 ++NumRets;
Michael Gottesmanf93109a2013-01-07 00:04:56 +00003809 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Erasing: " << *Retain
3810 << "\n Erasing: "
3811 << *Autorelease << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00003812 EraseInstruction(Retain);
3813 EraseInstruction(Autorelease);
3814 }
3815 }
3816 }
3817
3818 next_block:
3819 DependingInstructions.clear();
3820 Visited.clear();
3821 }
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00003822
Michael Gottesman5c0ae472013-01-04 21:29:57 +00003823 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Finished List.\n\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00003824
John McCall9fbd3182011-06-15 23:37:01 +00003825}
3826
3827bool ObjCARCOpt::doInitialization(Module &M) {
3828 if (!EnableARCOpts)
3829 return false;
3830
Dan Gohmand6bf2012012-04-13 18:57:48 +00003831 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003832 Run = ModuleHasARC(M);
3833 if (!Run)
3834 return false;
3835
John McCall9fbd3182011-06-15 23:37:01 +00003836 // Identify the imprecise release metadata kind.
3837 ImpreciseReleaseMDKind =
3838 M.getContext().getMDKindID("clang.imprecise_release");
Dan Gohmana974bea2011-10-17 22:53:25 +00003839 CopyOnEscapeMDKind =
3840 M.getContext().getMDKindID("clang.arc.copy_on_escape");
Dan Gohmandbe266b2012-02-17 18:59:53 +00003841 NoObjCARCExceptionsMDKind =
3842 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
John McCall9fbd3182011-06-15 23:37:01 +00003843
John McCall9fbd3182011-06-15 23:37:01 +00003844 // Intuitively, objc_retain and others are nocapture, however in practice
3845 // they are not, because they return their argument value. And objc_release
Dan Gohman447989c2012-04-27 18:56:31 +00003846 // calls finalizers which can have arbitrary side effects.
John McCall9fbd3182011-06-15 23:37:01 +00003847
3848 // These are initialized lazily.
3849 RetainRVCallee = 0;
3850 AutoreleaseRVCallee = 0;
3851 ReleaseCallee = 0;
3852 RetainCallee = 0;
Dan Gohman44280692011-07-22 22:29:21 +00003853 RetainBlockCallee = 0;
John McCall9fbd3182011-06-15 23:37:01 +00003854 AutoreleaseCallee = 0;
3855
3856 return false;
3857}
3858
3859bool ObjCARCOpt::runOnFunction(Function &F) {
3860 if (!EnableARCOpts)
3861 return false;
3862
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003863 // If nothing in the Module uses ARC, don't do anything.
3864 if (!Run)
3865 return false;
3866
John McCall9fbd3182011-06-15 23:37:01 +00003867 Changed = false;
3868
3869 PA.setAA(&getAnalysis<AliasAnalysis>());
3870
3871 // This pass performs several distinct transformations. As a compile-time aid
3872 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3873 // library functions aren't declared.
3874
3875 // Preliminary optimizations. This also computs UsedInThisFunction.
3876 OptimizeIndividualCalls(F);
3877
3878 // Optimizations for weak pointers.
3879 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3880 (1 << IC_LoadWeakRetained) |
3881 (1 << IC_StoreWeak) |
3882 (1 << IC_InitWeak) |
3883 (1 << IC_CopyWeak) |
3884 (1 << IC_MoveWeak) |
3885 (1 << IC_DestroyWeak)))
3886 OptimizeWeakCalls(F);
3887
3888 // Optimizations for retain+release pairs.
3889 if (UsedInThisFunction & ((1 << IC_Retain) |
3890 (1 << IC_RetainRV) |
3891 (1 << IC_RetainBlock)))
3892 if (UsedInThisFunction & (1 << IC_Release))
3893 // Run OptimizeSequences until it either stops making changes or
3894 // no retain+release pair nesting is detected.
3895 while (OptimizeSequences(F)) {}
3896
3897 // Optimizations if objc_autorelease is used.
Dan Gohman0daef3d2012-05-08 23:39:44 +00003898 if (UsedInThisFunction & ((1 << IC_Autorelease) |
3899 (1 << IC_AutoreleaseRV)))
John McCall9fbd3182011-06-15 23:37:01 +00003900 OptimizeReturns(F);
3901
3902 return Changed;
3903}
3904
3905void ObjCARCOpt::releaseMemory() {
3906 PA.clear();
3907}
3908
3909//===----------------------------------------------------------------------===//
3910// ARC contraction.
3911//===----------------------------------------------------------------------===//
3912
3913// TODO: ObjCARCContract could insert PHI nodes when uses aren't
3914// dominated by single calls.
3915
John McCall9fbd3182011-06-15 23:37:01 +00003916#include "llvm/Analysis/Dominators.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +00003917#include "llvm/IR/InlineAsm.h"
3918#include "llvm/IR/Operator.h"
John McCall9fbd3182011-06-15 23:37:01 +00003919
3920STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed");
3921
3922namespace {
3923 /// ObjCARCContract - Late ARC optimizations. These change the IR in a way
3924 /// that makes it difficult to be analyzed by ObjCARCOpt, so it's run late.
3925 class ObjCARCContract : public FunctionPass {
3926 bool Changed;
3927 AliasAnalysis *AA;
3928 DominatorTree *DT;
3929 ProvenanceAnalysis PA;
3930
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003931 /// Run - A flag indicating whether this optimization pass should run.
3932 bool Run;
3933
John McCall9fbd3182011-06-15 23:37:01 +00003934 /// StoreStrongCallee, etc. - Declarations for ObjC runtime
3935 /// functions, for use in creating calls to them. These are initialized
3936 /// lazily to avoid cluttering up the Module with unused declarations.
3937 Constant *StoreStrongCallee,
3938 *RetainAutoreleaseCallee, *RetainAutoreleaseRVCallee;
3939
3940 /// RetainRVMarker - The inline asm string to insert between calls and
3941 /// RetainRV calls to make the optimization work on targets which need it.
3942 const MDString *RetainRVMarker;
3943
Dan Gohman0cdece42012-01-19 19:14:36 +00003944 /// StoreStrongCalls - The set of inserted objc_storeStrong calls. If
3945 /// at the end of walking the function we have found no alloca
3946 /// instructions, these calls can be marked "tail".
Dan Gohman0daef3d2012-05-08 23:39:44 +00003947 SmallPtrSet<CallInst *, 8> StoreStrongCalls;
Dan Gohman0cdece42012-01-19 19:14:36 +00003948
John McCall9fbd3182011-06-15 23:37:01 +00003949 Constant *getStoreStrongCallee(Module *M);
3950 Constant *getRetainAutoreleaseCallee(Module *M);
3951 Constant *getRetainAutoreleaseRVCallee(Module *M);
3952
3953 bool ContractAutorelease(Function &F, Instruction *Autorelease,
3954 InstructionClass Class,
3955 SmallPtrSet<Instruction *, 4>
3956 &DependingInstructions,
3957 SmallPtrSet<const BasicBlock *, 4>
3958 &Visited);
3959
3960 void ContractRelease(Instruction *Release,
3961 inst_iterator &Iter);
3962
3963 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
3964 virtual bool doInitialization(Module &M);
3965 virtual bool runOnFunction(Function &F);
3966
3967 public:
3968 static char ID;
3969 ObjCARCContract() : FunctionPass(ID) {
3970 initializeObjCARCContractPass(*PassRegistry::getPassRegistry());
3971 }
3972 };
3973}
3974
3975char ObjCARCContract::ID = 0;
3976INITIALIZE_PASS_BEGIN(ObjCARCContract,
3977 "objc-arc-contract", "ObjC ARC contraction", false, false)
3978INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3979INITIALIZE_PASS_DEPENDENCY(DominatorTree)
3980INITIALIZE_PASS_END(ObjCARCContract,
3981 "objc-arc-contract", "ObjC ARC contraction", false, false)
3982
3983Pass *llvm::createObjCARCContractPass() {
3984 return new ObjCARCContract();
3985}
3986
3987void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const {
3988 AU.addRequired<AliasAnalysis>();
3989 AU.addRequired<DominatorTree>();
3990 AU.setPreservesCFG();
3991}
3992
3993Constant *ObjCARCContract::getStoreStrongCallee(Module *M) {
3994 if (!StoreStrongCallee) {
3995 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00003996 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3997 Type *I8XX = PointerType::getUnqual(I8X);
Dan Gohman0daef3d2012-05-08 23:39:44 +00003998 Type *Params[] = { I8XX, I8X };
John McCall9fbd3182011-06-15 23:37:01 +00003999
Bill Wendling034b94b2012-12-19 07:18:57 +00004000 AttributeSet Attribute = AttributeSet()
Bill Wendling99faa3b2012-12-07 23:16:57 +00004001 .addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00004002 Attribute::get(C, Attribute::NoUnwind))
4003 .addAttr(M->getContext(), 1, Attribute::get(C, Attribute::NoCapture));
John McCall9fbd3182011-06-15 23:37:01 +00004004
4005 StoreStrongCallee =
4006 M->getOrInsertFunction(
4007 "objc_storeStrong",
4008 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
Bill Wendling034b94b2012-12-19 07:18:57 +00004009 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00004010 }
4011 return StoreStrongCallee;
4012}
4013
4014Constant *ObjCARCContract::getRetainAutoreleaseCallee(Module *M) {
4015 if (!RetainAutoreleaseCallee) {
4016 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00004017 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman0daef3d2012-05-08 23:39:44 +00004018 Type *Params[] = { I8X };
4019 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling034b94b2012-12-19 07:18:57 +00004020 AttributeSet Attribute =
Bill Wendling99faa3b2012-12-07 23:16:57 +00004021 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00004022 Attribute::get(C, Attribute::NoUnwind));
John McCall9fbd3182011-06-15 23:37:01 +00004023 RetainAutoreleaseCallee =
Bill Wendling034b94b2012-12-19 07:18:57 +00004024 M->getOrInsertFunction("objc_retainAutorelease", FTy, Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00004025 }
4026 return RetainAutoreleaseCallee;
4027}
4028
4029Constant *ObjCARCContract::getRetainAutoreleaseRVCallee(Module *M) {
4030 if (!RetainAutoreleaseRVCallee) {
4031 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00004032 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman0daef3d2012-05-08 23:39:44 +00004033 Type *Params[] = { I8X };
4034 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling034b94b2012-12-19 07:18:57 +00004035 AttributeSet Attribute =
Bill Wendling99faa3b2012-12-07 23:16:57 +00004036 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00004037 Attribute::get(C, Attribute::NoUnwind));
John McCall9fbd3182011-06-15 23:37:01 +00004038 RetainAutoreleaseRVCallee =
4039 M->getOrInsertFunction("objc_retainAutoreleaseReturnValue", FTy,
Bill Wendling034b94b2012-12-19 07:18:57 +00004040 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00004041 }
4042 return RetainAutoreleaseRVCallee;
4043}
4044
Dan Gohman447989c2012-04-27 18:56:31 +00004045/// ContractAutorelease - Merge an autorelease with a retain into a fused call.
John McCall9fbd3182011-06-15 23:37:01 +00004046bool
4047ObjCARCContract::ContractAutorelease(Function &F, Instruction *Autorelease,
4048 InstructionClass Class,
4049 SmallPtrSet<Instruction *, 4>
4050 &DependingInstructions,
4051 SmallPtrSet<const BasicBlock *, 4>
4052 &Visited) {
4053 const Value *Arg = GetObjCArg(Autorelease);
4054
4055 // Check that there are no instructions between the retain and the autorelease
4056 // (such as an autorelease_pop) which may change the count.
4057 CallInst *Retain = 0;
4058 if (Class == IC_AutoreleaseRV)
4059 FindDependencies(RetainAutoreleaseRVDep, Arg,
4060 Autorelease->getParent(), Autorelease,
4061 DependingInstructions, Visited, PA);
4062 else
4063 FindDependencies(RetainAutoreleaseDep, Arg,
4064 Autorelease->getParent(), Autorelease,
4065 DependingInstructions, Visited, PA);
4066
4067 Visited.clear();
4068 if (DependingInstructions.size() != 1) {
4069 DependingInstructions.clear();
4070 return false;
4071 }
4072
4073 Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
4074 DependingInstructions.clear();
4075
4076 if (!Retain ||
4077 GetBasicInstructionClass(Retain) != IC_Retain ||
4078 GetObjCArg(Retain) != Arg)
4079 return false;
4080
4081 Changed = true;
4082 ++NumPeeps;
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004083
Michael Gottesman916d52a2013-01-07 00:31:26 +00004084 DEBUG(dbgs() << "ObjCARCContract::ContractAutorelease: Fusing "
4085 "retain/autorelease. Erasing: " << *Autorelease << "\n"
4086 " Old Retain: "
4087 << *Retain << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004088
John McCall9fbd3182011-06-15 23:37:01 +00004089 if (Class == IC_AutoreleaseRV)
4090 Retain->setCalledFunction(getRetainAutoreleaseRVCallee(F.getParent()));
4091 else
4092 Retain->setCalledFunction(getRetainAutoreleaseCallee(F.getParent()));
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004093
Michael Gottesman916d52a2013-01-07 00:31:26 +00004094 DEBUG(dbgs() << " New Retain: "
4095 << *Retain << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004096
John McCall9fbd3182011-06-15 23:37:01 +00004097 EraseInstruction(Autorelease);
4098 return true;
4099}
4100
4101/// ContractRelease - Attempt to merge an objc_release with a store, load, and
4102/// objc_retain to form an objc_storeStrong. This can be a little tricky because
4103/// the instructions don't always appear in order, and there may be unrelated
4104/// intervening instructions.
4105void ObjCARCContract::ContractRelease(Instruction *Release,
4106 inst_iterator &Iter) {
4107 LoadInst *Load = dyn_cast<LoadInst>(GetObjCArg(Release));
Eli Friedman2bc3d522011-09-12 20:23:13 +00004108 if (!Load || !Load->isSimple()) return;
John McCall9fbd3182011-06-15 23:37:01 +00004109
4110 // For now, require everything to be in one basic block.
4111 BasicBlock *BB = Release->getParent();
4112 if (Load->getParent() != BB) return;
4113
Dan Gohman4670dac2012-05-08 23:34:08 +00004114 // Walk down to find the store and the release, which may be in either order.
Dan Gohman95b8cf12012-05-09 23:08:33 +00004115 BasicBlock::iterator I = Load, End = BB->end();
John McCall9fbd3182011-06-15 23:37:01 +00004116 ++I;
4117 AliasAnalysis::Location Loc = AA->getLocation(Load);
Dan Gohman4670dac2012-05-08 23:34:08 +00004118 StoreInst *Store = 0;
4119 bool SawRelease = false;
4120 for (; !Store || !SawRelease; ++I) {
Dan Gohman95b8cf12012-05-09 23:08:33 +00004121 if (I == End)
4122 return;
4123
Dan Gohman4670dac2012-05-08 23:34:08 +00004124 Instruction *Inst = I;
4125 if (Inst == Release) {
4126 SawRelease = true;
4127 continue;
4128 }
4129
4130 InstructionClass Class = GetBasicInstructionClass(Inst);
4131
4132 // Unrelated retains are harmless.
4133 if (IsRetain(Class))
4134 continue;
4135
4136 if (Store) {
4137 // The store is the point where we're going to put the objc_storeStrong,
4138 // so make sure there are no uses after it.
4139 if (CanUse(Inst, Load, PA, Class))
4140 return;
4141 } else if (AA->getModRefInfo(Inst, Loc) & AliasAnalysis::Mod) {
4142 // We are moving the load down to the store, so check for anything
4143 // else which writes to the memory between the load and the store.
4144 Store = dyn_cast<StoreInst>(Inst);
4145 if (!Store || !Store->isSimple()) return;
4146 if (Store->getPointerOperand() != Loc.Ptr) return;
4147 }
4148 }
John McCall9fbd3182011-06-15 23:37:01 +00004149
4150 Value *New = StripPointerCastsAndObjCCalls(Store->getValueOperand());
4151
4152 // Walk up to find the retain.
4153 I = Store;
4154 BasicBlock::iterator Begin = BB->begin();
4155 while (I != Begin && GetBasicInstructionClass(I) != IC_Retain)
4156 --I;
4157 Instruction *Retain = I;
4158 if (GetBasicInstructionClass(Retain) != IC_Retain) return;
4159 if (GetObjCArg(Retain) != New) return;
4160
4161 Changed = true;
4162 ++NumStoreStrongs;
4163
4164 LLVMContext &C = Release->getContext();
Chris Lattnerdb125cf2011-07-18 04:54:35 +00004165 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
4166 Type *I8XX = PointerType::getUnqual(I8X);
John McCall9fbd3182011-06-15 23:37:01 +00004167
4168 Value *Args[] = { Load->getPointerOperand(), New };
4169 if (Args[0]->getType() != I8XX)
4170 Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
4171 if (Args[1]->getType() != I8X)
4172 Args[1] = new BitCastInst(Args[1], I8X, "", Store);
4173 CallInst *StoreStrong =
4174 CallInst::Create(getStoreStrongCallee(BB->getParent()->getParent()),
Jay Foada3efbb12011-07-15 08:37:34 +00004175 Args, "", Store);
John McCall9fbd3182011-06-15 23:37:01 +00004176 StoreStrong->setDoesNotThrow();
4177 StoreStrong->setDebugLoc(Store->getDebugLoc());
4178
Dan Gohman0cdece42012-01-19 19:14:36 +00004179 // We can't set the tail flag yet, because we haven't yet determined
4180 // whether there are any escaping allocas. Remember this call, so that
4181 // we can set the tail flag once we know it's safe.
4182 StoreStrongCalls.insert(StoreStrong);
4183
John McCall9fbd3182011-06-15 23:37:01 +00004184 if (&*Iter == Store) ++Iter;
4185 Store->eraseFromParent();
4186 Release->eraseFromParent();
4187 EraseInstruction(Retain);
4188 if (Load->use_empty())
4189 Load->eraseFromParent();
4190}
4191
4192bool ObjCARCContract::doInitialization(Module &M) {
Dan Gohmand6bf2012012-04-13 18:57:48 +00004193 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00004194 Run = ModuleHasARC(M);
4195 if (!Run)
4196 return false;
4197
John McCall9fbd3182011-06-15 23:37:01 +00004198 // These are initialized lazily.
4199 StoreStrongCallee = 0;
4200 RetainAutoreleaseCallee = 0;
4201 RetainAutoreleaseRVCallee = 0;
4202
4203 // Initialize RetainRVMarker.
4204 RetainRVMarker = 0;
4205 if (NamedMDNode *NMD =
4206 M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker"))
4207 if (NMD->getNumOperands() == 1) {
4208 const MDNode *N = NMD->getOperand(0);
4209 if (N->getNumOperands() == 1)
4210 if (const MDString *S = dyn_cast<MDString>(N->getOperand(0)))
4211 RetainRVMarker = S;
4212 }
4213
4214 return false;
4215}
4216
4217bool ObjCARCContract::runOnFunction(Function &F) {
4218 if (!EnableARCOpts)
4219 return false;
4220
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00004221 // If nothing in the Module uses ARC, don't do anything.
4222 if (!Run)
4223 return false;
4224
John McCall9fbd3182011-06-15 23:37:01 +00004225 Changed = false;
4226 AA = &getAnalysis<AliasAnalysis>();
4227 DT = &getAnalysis<DominatorTree>();
4228
4229 PA.setAA(&getAnalysis<AliasAnalysis>());
4230
Dan Gohman0cdece42012-01-19 19:14:36 +00004231 // Track whether it's ok to mark objc_storeStrong calls with the "tail"
4232 // keyword. Be conservative if the function has variadic arguments.
4233 // It seems that functions which "return twice" are also unsafe for the
4234 // "tail" argument, because they are setjmp, which could need to
4235 // return to an earlier stack state.
Dan Gohman0daef3d2012-05-08 23:39:44 +00004236 bool TailOkForStoreStrongs = !F.isVarArg() &&
4237 !F.callsFunctionThatReturnsTwice();
Dan Gohman0cdece42012-01-19 19:14:36 +00004238
John McCall9fbd3182011-06-15 23:37:01 +00004239 // For ObjC library calls which return their argument, replace uses of the
4240 // argument with uses of the call return value, if it dominates the use. This
4241 // reduces register pressure.
4242 SmallPtrSet<Instruction *, 4> DependingInstructions;
4243 SmallPtrSet<const BasicBlock *, 4> Visited;
4244 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
4245 Instruction *Inst = &*I++;
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004246
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00004247 DEBUG(dbgs() << "ObjCARCContract: Visiting: " << *Inst << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004248
John McCall9fbd3182011-06-15 23:37:01 +00004249 // Only these library routines return their argument. In particular,
4250 // objc_retainBlock does not necessarily return its argument.
4251 InstructionClass Class = GetBasicInstructionClass(Inst);
4252 switch (Class) {
4253 case IC_Retain:
4254 case IC_FusedRetainAutorelease:
4255 case IC_FusedRetainAutoreleaseRV:
4256 break;
4257 case IC_Autorelease:
4258 case IC_AutoreleaseRV:
4259 if (ContractAutorelease(F, Inst, Class, DependingInstructions, Visited))
4260 continue;
4261 break;
4262 case IC_RetainRV: {
4263 // If we're compiling for a target which needs a special inline-asm
4264 // marker to do the retainAutoreleasedReturnValue optimization,
4265 // insert it now.
4266 if (!RetainRVMarker)
4267 break;
4268 BasicBlock::iterator BBI = Inst;
Dan Gohman58fb3402012-06-25 19:47:37 +00004269 BasicBlock *InstParent = Inst->getParent();
4270
4271 // Step up to see if the call immediately precedes the RetainRV call.
4272 // If it's an invoke, we have to cross a block boundary. And we have
4273 // to carefully dodge no-op instructions.
4274 do {
4275 if (&*BBI == InstParent->begin()) {
4276 BasicBlock *Pred = InstParent->getSinglePredecessor();
4277 if (!Pred)
4278 goto decline_rv_optimization;
4279 BBI = Pred->getTerminator();
4280 break;
4281 }
4282 --BBI;
4283 } while (isNoopInstruction(BBI));
4284
John McCall9fbd3182011-06-15 23:37:01 +00004285 if (&*BBI == GetObjCArg(Inst)) {
Michael Gottesman50652cd2013-01-03 07:32:41 +00004286 DEBUG(dbgs() << "ObjCARCContract: Adding inline asm marker for "
Michael Gottesman5c0ae472013-01-04 21:29:57 +00004287 "retainAutoreleasedReturnValue optimization.\n");
Dan Gohmand6bf2012012-04-13 18:57:48 +00004288 Changed = true;
John McCall9fbd3182011-06-15 23:37:01 +00004289 InlineAsm *IA =
4290 InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()),
4291 /*isVarArg=*/false),
4292 RetainRVMarker->getString(),
4293 /*Constraints=*/"", /*hasSideEffects=*/true);
4294 CallInst::Create(IA, "", Inst);
4295 }
Dan Gohman58fb3402012-06-25 19:47:37 +00004296 decline_rv_optimization:
John McCall9fbd3182011-06-15 23:37:01 +00004297 break;
4298 }
4299 case IC_InitWeak: {
4300 // objc_initWeak(p, null) => *p = null
4301 CallInst *CI = cast<CallInst>(Inst);
4302 if (isNullOrUndef(CI->getArgOperand(1))) {
4303 Value *Null =
4304 ConstantPointerNull::get(cast<PointerType>(CI->getType()));
4305 Changed = true;
4306 new StoreInst(Null, CI->getArgOperand(0), CI);
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004307
Michael Gottesman1ebbdcf2013-01-03 07:32:53 +00004308 DEBUG(dbgs() << "OBJCARCContract: Old = " << *CI << "\n"
4309 << " New = " << *Null << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004310
John McCall9fbd3182011-06-15 23:37:01 +00004311 CI->replaceAllUsesWith(Null);
4312 CI->eraseFromParent();
4313 }
4314 continue;
4315 }
4316 case IC_Release:
4317 ContractRelease(Inst, I);
4318 continue;
Dan Gohman0cdece42012-01-19 19:14:36 +00004319 case IC_User:
4320 // Be conservative if the function has any alloca instructions.
4321 // Technically we only care about escaping alloca instructions,
4322 // but this is sufficient to handle some interesting cases.
4323 if (isa<AllocaInst>(Inst))
4324 TailOkForStoreStrongs = false;
4325 continue;
John McCall9fbd3182011-06-15 23:37:01 +00004326 default:
4327 continue;
4328 }
4329
Michael Gottesmanec21e2a2013-01-03 08:09:27 +00004330 DEBUG(dbgs() << "ObjCARCContract: Finished List.\n\n");
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00004331
John McCall9fbd3182011-06-15 23:37:01 +00004332 // Don't use GetObjCArg because we don't want to look through bitcasts
4333 // and such; to do the replacement, the argument must have type i8*.
4334 const Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
4335 for (;;) {
4336 // If we're compiling bugpointed code, don't get in trouble.
4337 if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
4338 break;
4339 // Look through the uses of the pointer.
4340 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
4341 UI != UE; ) {
4342 Use &U = UI.getUse();
4343 unsigned OperandNo = UI.getOperandNo();
4344 ++UI; // Increment UI now, because we may unlink its element.
Dan Gohmand6bf2012012-04-13 18:57:48 +00004345
4346 // If the call's return value dominates a use of the call's argument
4347 // value, rewrite the use to use the return value. We check for
4348 // reachability here because an unreachable call is considered to
4349 // trivially dominate itself, which would lead us to rewriting its
4350 // argument in terms of its return value, which would lead to
4351 // infinite loops in GetObjCArg.
Dan Gohman0daef3d2012-05-08 23:39:44 +00004352 if (DT->isReachableFromEntry(U) && DT->dominates(Inst, U)) {
Rafael Espindola2453dff2012-03-15 15:52:59 +00004353 Changed = true;
4354 Instruction *Replacement = Inst;
4355 Type *UseTy = U.get()->getType();
Dan Gohman6c189ec2012-04-13 01:08:28 +00004356 if (PHINode *PHI = dyn_cast<PHINode>(U.getUser())) {
Rafael Espindola2453dff2012-03-15 15:52:59 +00004357 // For PHI nodes, insert the bitcast in the predecessor block.
Dan Gohman0daef3d2012-05-08 23:39:44 +00004358 unsigned ValNo = PHINode::getIncomingValueNumForOperand(OperandNo);
4359 BasicBlock *BB = PHI->getIncomingBlock(ValNo);
Rafael Espindola2453dff2012-03-15 15:52:59 +00004360 if (Replacement->getType() != UseTy)
4361 Replacement = new BitCastInst(Replacement, UseTy, "",
4362 &BB->back());
Dan Gohmand6bf2012012-04-13 18:57:48 +00004363 // While we're here, rewrite all edges for this PHI, rather
4364 // than just one use at a time, to minimize the number of
4365 // bitcasts we emit.
Dan Gohman447989c2012-04-27 18:56:31 +00004366 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
Rafael Espindola2453dff2012-03-15 15:52:59 +00004367 if (PHI->getIncomingBlock(i) == BB) {
4368 // Keep the UI iterator valid.
4369 if (&PHI->getOperandUse(
4370 PHINode::getOperandNumForIncomingValue(i)) ==
4371 &UI.getUse())
4372 ++UI;
4373 PHI->setIncomingValue(i, Replacement);
4374 }
4375 } else {
4376 if (Replacement->getType() != UseTy)
Dan Gohman6c189ec2012-04-13 01:08:28 +00004377 Replacement = new BitCastInst(Replacement, UseTy, "",
4378 cast<Instruction>(U.getUser()));
Rafael Espindola2453dff2012-03-15 15:52:59 +00004379 U.set(Replacement);
John McCall9fbd3182011-06-15 23:37:01 +00004380 }
Rafael Espindola2453dff2012-03-15 15:52:59 +00004381 }
John McCall9fbd3182011-06-15 23:37:01 +00004382 }
4383
Dan Gohman447989c2012-04-27 18:56:31 +00004384 // If Arg is a no-op casted pointer, strip one level of casts and iterate.
John McCall9fbd3182011-06-15 23:37:01 +00004385 if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
4386 Arg = BI->getOperand(0);
4387 else if (isa<GEPOperator>(Arg) &&
4388 cast<GEPOperator>(Arg)->hasAllZeroIndices())
4389 Arg = cast<GEPOperator>(Arg)->getPointerOperand();
4390 else if (isa<GlobalAlias>(Arg) &&
4391 !cast<GlobalAlias>(Arg)->mayBeOverridden())
4392 Arg = cast<GlobalAlias>(Arg)->getAliasee();
4393 else
4394 break;
4395 }
4396 }
4397
Dan Gohman0cdece42012-01-19 19:14:36 +00004398 // If this function has no escaping allocas or suspicious vararg usage,
4399 // objc_storeStrong calls can be marked with the "tail" keyword.
4400 if (TailOkForStoreStrongs)
Dan Gohman0daef3d2012-05-08 23:39:44 +00004401 for (SmallPtrSet<CallInst *, 8>::iterator I = StoreStrongCalls.begin(),
Dan Gohman0cdece42012-01-19 19:14:36 +00004402 E = StoreStrongCalls.end(); I != E; ++I)
4403 (*I)->setTailCall();
4404 StoreStrongCalls.clear();
4405
John McCall9fbd3182011-06-15 23:37:01 +00004406 return Changed;
4407}