blob: 2e75bb9391cda9b02d22a0740bed66d9dce14a52 [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"
Michael Gottesman6056b852013-01-13 22:12:06 +000033#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000034#include "llvm/Support/CommandLine.h"
Chandler Carruth58a2cbe2013-01-02 10:22:59 +000035#include "llvm/Support/Debug.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000036#include "llvm/Support/raw_ostream.h"
John McCall9fbd3182011-06-15 23:37:01 +000037using namespace llvm;
38
39// A handy option to enable/disable all optimizations in this file.
40static cl::opt<bool> EnableARCOpts("enable-objc-arc-opts", cl::init(true));
41
42//===----------------------------------------------------------------------===//
43// Misc. Utilities
44//===----------------------------------------------------------------------===//
45
46namespace {
47 /// MapVector - An associative container with fast insertion-order
48 /// (deterministic) iteration over its elements. Plus the special
49 /// blot operation.
50 template<class KeyT, class ValueT>
51 class MapVector {
52 /// Map - Map keys to indices in Vector.
53 typedef DenseMap<KeyT, size_t> MapTy;
54 MapTy Map;
55
56 /// Vector - Keys and values.
57 typedef std::vector<std::pair<KeyT, ValueT> > VectorTy;
58 VectorTy Vector;
59
60 public:
61 typedef typename VectorTy::iterator iterator;
62 typedef typename VectorTy::const_iterator const_iterator;
63 iterator begin() { return Vector.begin(); }
64 iterator end() { return Vector.end(); }
65 const_iterator begin() const { return Vector.begin(); }
66 const_iterator end() const { return Vector.end(); }
67
68#ifdef XDEBUG
69 ~MapVector() {
70 assert(Vector.size() >= Map.size()); // May differ due to blotting.
71 for (typename MapTy::const_iterator I = Map.begin(), E = Map.end();
72 I != E; ++I) {
73 assert(I->second < Vector.size());
74 assert(Vector[I->second].first == I->first);
75 }
76 for (typename VectorTy::const_iterator I = Vector.begin(),
77 E = Vector.end(); I != E; ++I)
78 assert(!I->first ||
79 (Map.count(I->first) &&
80 Map[I->first] == size_t(I - Vector.begin())));
81 }
82#endif
83
Dan Gohman22cc4cc2012-03-02 01:13:53 +000084 ValueT &operator[](const KeyT &Arg) {
John McCall9fbd3182011-06-15 23:37:01 +000085 std::pair<typename MapTy::iterator, bool> Pair =
86 Map.insert(std::make_pair(Arg, size_t(0)));
87 if (Pair.second) {
Dan Gohman22cc4cc2012-03-02 01:13:53 +000088 size_t Num = Vector.size();
89 Pair.first->second = Num;
John McCall9fbd3182011-06-15 23:37:01 +000090 Vector.push_back(std::make_pair(Arg, ValueT()));
Dan Gohman22cc4cc2012-03-02 01:13:53 +000091 return Vector[Num].second;
John McCall9fbd3182011-06-15 23:37:01 +000092 }
93 return Vector[Pair.first->second].second;
94 }
95
96 std::pair<iterator, bool>
97 insert(const std::pair<KeyT, ValueT> &InsertPair) {
98 std::pair<typename MapTy::iterator, bool> Pair =
99 Map.insert(std::make_pair(InsertPair.first, size_t(0)));
100 if (Pair.second) {
Dan Gohman22cc4cc2012-03-02 01:13:53 +0000101 size_t Num = Vector.size();
102 Pair.first->second = Num;
John McCall9fbd3182011-06-15 23:37:01 +0000103 Vector.push_back(InsertPair);
Dan Gohman22cc4cc2012-03-02 01:13:53 +0000104 return std::make_pair(Vector.begin() + Num, true);
John McCall9fbd3182011-06-15 23:37:01 +0000105 }
106 return std::make_pair(Vector.begin() + Pair.first->second, false);
107 }
108
Dan Gohman22cc4cc2012-03-02 01:13:53 +0000109 const_iterator find(const KeyT &Key) const {
John McCall9fbd3182011-06-15 23:37:01 +0000110 typename MapTy::const_iterator It = Map.find(Key);
111 if (It == Map.end()) return Vector.end();
112 return Vector.begin() + It->second;
113 }
114
115 /// blot - This is similar to erase, but instead of removing the element
116 /// from the vector, it just zeros out the key in the vector. This leaves
117 /// iterators intact, but clients must be prepared for zeroed-out keys when
118 /// iterating.
Dan Gohman22cc4cc2012-03-02 01:13:53 +0000119 void blot(const KeyT &Key) {
John McCall9fbd3182011-06-15 23:37:01 +0000120 typename MapTy::iterator It = Map.find(Key);
121 if (It == Map.end()) return;
122 Vector[It->second].first = KeyT();
123 Map.erase(It);
124 }
125
126 void clear() {
127 Map.clear();
128 Vector.clear();
129 }
130 };
131}
132
133//===----------------------------------------------------------------------===//
134// ARC Utilities.
135//===----------------------------------------------------------------------===//
136
Chandler Carruthd04a8d42012-12-03 16:50:05 +0000137#include "llvm/ADT/StringSwitch.h"
138#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +0000139#include "llvm/IR/Intrinsics.h"
140#include "llvm/IR/Module.h"
Dan Gohman0daef3d2012-05-08 23:39:44 +0000141#include "llvm/Support/CallSite.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +0000142#include "llvm/Transforms/Utils/Local.h"
Dan Gohman0daef3d2012-05-08 23:39:44 +0000143
John McCall9fbd3182011-06-15 23:37:01 +0000144namespace {
145 /// InstructionClass - A simple classification for instructions.
146 enum InstructionClass {
147 IC_Retain, ///< objc_retain
148 IC_RetainRV, ///< objc_retainAutoreleasedReturnValue
149 IC_RetainBlock, ///< objc_retainBlock
150 IC_Release, ///< objc_release
151 IC_Autorelease, ///< objc_autorelease
152 IC_AutoreleaseRV, ///< objc_autoreleaseReturnValue
153 IC_AutoreleasepoolPush, ///< objc_autoreleasePoolPush
154 IC_AutoreleasepoolPop, ///< objc_autoreleasePoolPop
155 IC_NoopCast, ///< objc_retainedObject, etc.
156 IC_FusedRetainAutorelease, ///< objc_retainAutorelease
157 IC_FusedRetainAutoreleaseRV, ///< objc_retainAutoreleaseReturnValue
158 IC_LoadWeakRetained, ///< objc_loadWeakRetained (primitive)
159 IC_StoreWeak, ///< objc_storeWeak (primitive)
160 IC_InitWeak, ///< objc_initWeak (derived)
161 IC_LoadWeak, ///< objc_loadWeak (derived)
162 IC_MoveWeak, ///< objc_moveWeak (derived)
163 IC_CopyWeak, ///< objc_copyWeak (derived)
164 IC_DestroyWeak, ///< objc_destroyWeak (derived)
Dan Gohman44234772012-04-13 18:28:58 +0000165 IC_StoreStrong, ///< objc_storeStrong (derived)
John McCall9fbd3182011-06-15 23:37:01 +0000166 IC_CallOrUser, ///< could call objc_release and/or "use" pointers
167 IC_Call, ///< could call objc_release
168 IC_User, ///< could "use" a pointer
169 IC_None ///< anything else
170 };
171}
172
173/// IsPotentialUse - Test whether the given value is possible a
174/// reference-counted pointer.
175static bool IsPotentialUse(const Value *Op) {
176 // Pointers to static or stack storage are not reference-counted pointers.
177 if (isa<Constant>(Op) || isa<AllocaInst>(Op))
178 return false;
179 // Special arguments are not reference-counted.
180 if (const Argument *Arg = dyn_cast<Argument>(Op))
181 if (Arg->hasByValAttr() ||
182 Arg->hasNestAttr() ||
183 Arg->hasStructRetAttr())
184 return false;
Dan Gohmanf9096e42011-12-14 19:10:53 +0000185 // Only consider values with pointer types.
186 // It seemes intuitive to exclude function pointer types as well, since
187 // functions are never reference-counted, however clang occasionally
188 // bitcasts reference-counted pointers to function-pointer type
189 // temporarily.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000190 PointerType *Ty = dyn_cast<PointerType>(Op->getType());
Dan Gohmanf9096e42011-12-14 19:10:53 +0000191 if (!Ty)
John McCall9fbd3182011-06-15 23:37:01 +0000192 return false;
193 // Conservatively assume anything else is a potential use.
194 return true;
195}
196
197/// GetCallSiteClass - Helper for GetInstructionClass. Determines what kind
198/// of construct CS is.
199static InstructionClass GetCallSiteClass(ImmutableCallSite CS) {
200 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
201 I != E; ++I)
202 if (IsPotentialUse(*I))
203 return CS.onlyReadsMemory() ? IC_User : IC_CallOrUser;
204
205 return CS.onlyReadsMemory() ? IC_None : IC_Call;
206}
207
208/// GetFunctionClass - Determine if F is one of the special known Functions.
209/// If it isn't, return IC_CallOrUser.
210static InstructionClass GetFunctionClass(const Function *F) {
211 Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
212
213 // No arguments.
214 if (AI == AE)
215 return StringSwitch<InstructionClass>(F->getName())
216 .Case("objc_autoreleasePoolPush", IC_AutoreleasepoolPush)
217 .Default(IC_CallOrUser);
218
219 // One argument.
220 const Argument *A0 = AI++;
221 if (AI == AE)
222 // Argument is a pointer.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000223 if (PointerType *PTy = dyn_cast<PointerType>(A0->getType())) {
224 Type *ETy = PTy->getElementType();
John McCall9fbd3182011-06-15 23:37:01 +0000225 // Argument is i8*.
226 if (ETy->isIntegerTy(8))
227 return StringSwitch<InstructionClass>(F->getName())
228 .Case("objc_retain", IC_Retain)
229 .Case("objc_retainAutoreleasedReturnValue", IC_RetainRV)
230 .Case("objc_retainBlock", IC_RetainBlock)
231 .Case("objc_release", IC_Release)
232 .Case("objc_autorelease", IC_Autorelease)
233 .Case("objc_autoreleaseReturnValue", IC_AutoreleaseRV)
234 .Case("objc_autoreleasePoolPop", IC_AutoreleasepoolPop)
235 .Case("objc_retainedObject", IC_NoopCast)
236 .Case("objc_unretainedObject", IC_NoopCast)
237 .Case("objc_unretainedPointer", IC_NoopCast)
238 .Case("objc_retain_autorelease", IC_FusedRetainAutorelease)
239 .Case("objc_retainAutorelease", IC_FusedRetainAutorelease)
240 .Case("objc_retainAutoreleaseReturnValue",IC_FusedRetainAutoreleaseRV)
241 .Default(IC_CallOrUser);
242
243 // Argument is i8**
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000244 if (PointerType *Pte = dyn_cast<PointerType>(ETy))
John McCall9fbd3182011-06-15 23:37:01 +0000245 if (Pte->getElementType()->isIntegerTy(8))
246 return StringSwitch<InstructionClass>(F->getName())
247 .Case("objc_loadWeakRetained", IC_LoadWeakRetained)
248 .Case("objc_loadWeak", IC_LoadWeak)
249 .Case("objc_destroyWeak", IC_DestroyWeak)
250 .Default(IC_CallOrUser);
251 }
252
253 // Two arguments, first is i8**.
254 const Argument *A1 = AI++;
255 if (AI == AE)
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000256 if (PointerType *PTy = dyn_cast<PointerType>(A0->getType()))
257 if (PointerType *Pte = dyn_cast<PointerType>(PTy->getElementType()))
John McCall9fbd3182011-06-15 23:37:01 +0000258 if (Pte->getElementType()->isIntegerTy(8))
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000259 if (PointerType *PTy1 = dyn_cast<PointerType>(A1->getType())) {
260 Type *ETy1 = PTy1->getElementType();
John McCall9fbd3182011-06-15 23:37:01 +0000261 // Second argument is i8*
262 if (ETy1->isIntegerTy(8))
263 return StringSwitch<InstructionClass>(F->getName())
264 .Case("objc_storeWeak", IC_StoreWeak)
265 .Case("objc_initWeak", IC_InitWeak)
Dan Gohman44234772012-04-13 18:28:58 +0000266 .Case("objc_storeStrong", IC_StoreStrong)
John McCall9fbd3182011-06-15 23:37:01 +0000267 .Default(IC_CallOrUser);
268 // Second argument is i8**.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000269 if (PointerType *Pte1 = dyn_cast<PointerType>(ETy1))
John McCall9fbd3182011-06-15 23:37:01 +0000270 if (Pte1->getElementType()->isIntegerTy(8))
271 return StringSwitch<InstructionClass>(F->getName())
272 .Case("objc_moveWeak", IC_MoveWeak)
273 .Case("objc_copyWeak", IC_CopyWeak)
274 .Default(IC_CallOrUser);
275 }
276
277 // Anything else.
278 return IC_CallOrUser;
279}
280
281/// GetInstructionClass - Determine what kind of construct V is.
282static InstructionClass GetInstructionClass(const Value *V) {
283 if (const Instruction *I = dyn_cast<Instruction>(V)) {
284 // Any instruction other than bitcast and gep with a pointer operand have a
285 // use of an objc pointer. Bitcasts, GEPs, Selects, PHIs transfer a pointer
286 // to a subsequent use, rather than using it themselves, in this sense.
287 // As a short cut, several other opcodes are known to have no pointer
288 // operands of interest. And ret is never followed by a release, so it's
289 // not interesting to examine.
290 switch (I->getOpcode()) {
291 case Instruction::Call: {
292 const CallInst *CI = cast<CallInst>(I);
293 // Check for calls to special functions.
294 if (const Function *F = CI->getCalledFunction()) {
295 InstructionClass Class = GetFunctionClass(F);
296 if (Class != IC_CallOrUser)
297 return Class;
298
299 // None of the intrinsic functions do objc_release. For intrinsics, the
300 // only question is whether or not they may be users.
301 switch (F->getIntrinsicID()) {
John McCall9fbd3182011-06-15 23:37:01 +0000302 case Intrinsic::returnaddress: case Intrinsic::frameaddress:
303 case Intrinsic::stacksave: case Intrinsic::stackrestore:
304 case Intrinsic::vastart: case Intrinsic::vacopy: case Intrinsic::vaend:
Dan Gohman0daef3d2012-05-08 23:39:44 +0000305 case Intrinsic::objectsize: case Intrinsic::prefetch:
306 case Intrinsic::stackprotector:
307 case Intrinsic::eh_return_i32: case Intrinsic::eh_return_i64:
308 case Intrinsic::eh_typeid_for: case Intrinsic::eh_dwarf_cfa:
309 case Intrinsic::eh_sjlj_lsda: case Intrinsic::eh_sjlj_functioncontext:
310 case Intrinsic::init_trampoline: case Intrinsic::adjust_trampoline:
311 case Intrinsic::lifetime_start: case Intrinsic::lifetime_end:
312 case Intrinsic::invariant_start: case Intrinsic::invariant_end:
John McCall9fbd3182011-06-15 23:37:01 +0000313 // Don't let dbg info affect our results.
314 case Intrinsic::dbg_declare: case Intrinsic::dbg_value:
315 // Short cut: Some intrinsics obviously don't use ObjC pointers.
316 return IC_None;
317 default:
Dan Gohman0daef3d2012-05-08 23:39:44 +0000318 break;
John McCall9fbd3182011-06-15 23:37:01 +0000319 }
320 }
321 return GetCallSiteClass(CI);
322 }
323 case Instruction::Invoke:
324 return GetCallSiteClass(cast<InvokeInst>(I));
325 case Instruction::BitCast:
326 case Instruction::GetElementPtr:
327 case Instruction::Select: case Instruction::PHI:
328 case Instruction::Ret: case Instruction::Br:
329 case Instruction::Switch: case Instruction::IndirectBr:
330 case Instruction::Alloca: case Instruction::VAArg:
331 case Instruction::Add: case Instruction::FAdd:
332 case Instruction::Sub: case Instruction::FSub:
333 case Instruction::Mul: case Instruction::FMul:
334 case Instruction::SDiv: case Instruction::UDiv: case Instruction::FDiv:
335 case Instruction::SRem: case Instruction::URem: case Instruction::FRem:
336 case Instruction::Shl: case Instruction::LShr: case Instruction::AShr:
337 case Instruction::And: case Instruction::Or: case Instruction::Xor:
338 case Instruction::SExt: case Instruction::ZExt: case Instruction::Trunc:
339 case Instruction::IntToPtr: case Instruction::FCmp:
340 case Instruction::FPTrunc: case Instruction::FPExt:
341 case Instruction::FPToUI: case Instruction::FPToSI:
342 case Instruction::UIToFP: case Instruction::SIToFP:
343 case Instruction::InsertElement: case Instruction::ExtractElement:
344 case Instruction::ShuffleVector:
345 case Instruction::ExtractValue:
346 break;
347 case Instruction::ICmp:
348 // Comparing a pointer with null, or any other constant, isn't an
349 // interesting use, because we don't care what the pointer points to, or
350 // about the values of any other dynamic reference-counted pointers.
351 if (IsPotentialUse(I->getOperand(1)))
352 return IC_User;
353 break;
354 default:
355 // For anything else, check all the operands.
Dan Gohmand4464602011-08-22 17:29:37 +0000356 // Note that this includes both operands of a Store: while the first
357 // operand isn't actually being dereferenced, it is being stored to
358 // memory where we can no longer track who might read it and dereference
359 // it, so we have to consider it potentially used.
John McCall9fbd3182011-06-15 23:37:01 +0000360 for (User::const_op_iterator OI = I->op_begin(), OE = I->op_end();
361 OI != OE; ++OI)
362 if (IsPotentialUse(*OI))
363 return IC_User;
364 }
365 }
366
367 // Otherwise, it's totally inert for ARC purposes.
368 return IC_None;
369}
370
371/// GetBasicInstructionClass - Determine what kind of construct V is. This is
372/// similar to GetInstructionClass except that it only detects objc runtine
373/// calls. This allows it to be faster.
374static InstructionClass GetBasicInstructionClass(const Value *V) {
375 if (const CallInst *CI = dyn_cast<CallInst>(V)) {
376 if (const Function *F = CI->getCalledFunction())
377 return GetFunctionClass(F);
378 // Otherwise, be conservative.
379 return IC_CallOrUser;
380 }
381
382 // Otherwise, be conservative.
Dan Gohman2f6263c2012-01-17 20:52:24 +0000383 return isa<InvokeInst>(V) ? IC_CallOrUser : IC_User;
John McCall9fbd3182011-06-15 23:37:01 +0000384}
385
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +0000386/// IsRetain - Test if the given class is objc_retain or
John McCall9fbd3182011-06-15 23:37:01 +0000387/// equivalent.
388static bool IsRetain(InstructionClass Class) {
389 return Class == IC_Retain ||
390 Class == IC_RetainRV;
391}
392
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +0000393/// IsAutorelease - Test if the given class is objc_autorelease or
John McCall9fbd3182011-06-15 23:37:01 +0000394/// equivalent.
395static bool IsAutorelease(InstructionClass Class) {
396 return Class == IC_Autorelease ||
397 Class == IC_AutoreleaseRV;
398}
399
400/// IsForwarding - Test if the given class represents instructions which return
401/// their argument verbatim.
402static bool IsForwarding(InstructionClass Class) {
403 // objc_retainBlock technically doesn't always return its argument
404 // verbatim, but it doesn't matter for our purposes here.
405 return Class == IC_Retain ||
406 Class == IC_RetainRV ||
407 Class == IC_Autorelease ||
408 Class == IC_AutoreleaseRV ||
409 Class == IC_RetainBlock ||
410 Class == IC_NoopCast;
411}
412
413/// IsNoopOnNull - Test if the given class represents instructions which do
414/// nothing if passed a null pointer.
415static bool IsNoopOnNull(InstructionClass Class) {
416 return Class == IC_Retain ||
417 Class == IC_RetainRV ||
418 Class == IC_Release ||
419 Class == IC_Autorelease ||
420 Class == IC_AutoreleaseRV ||
421 Class == IC_RetainBlock;
422}
423
424/// IsAlwaysTail - Test if the given class represents instructions which are
425/// always safe to mark with the "tail" keyword.
426static bool IsAlwaysTail(InstructionClass Class) {
427 // IC_RetainBlock may be given a stack argument.
428 return Class == IC_Retain ||
429 Class == IC_RetainRV ||
John McCall9fbd3182011-06-15 23:37:01 +0000430 Class == IC_AutoreleaseRV;
431}
432
Michael Gottesmane8c161a2013-01-12 01:25:15 +0000433/// \brief Test if the given class represents instructions which are never safe
434/// to mark with the "tail" keyword.
435static bool IsNeverTail(InstructionClass Class) {
436 /// It is never safe to tail call objc_autorelease since by tail calling
437 /// objc_autorelease, we also tail call -[NSObject autorelease] which supports
438 /// fast autoreleasing causing our object to be potentially reclaimed from the
439 /// autorelease pool which violates the semantics of __autoreleasing types in
440 /// ARC.
441 return Class == IC_Autorelease;
442}
443
John McCall9fbd3182011-06-15 23:37:01 +0000444/// IsNoThrow - Test if the given class represents instructions which are always
445/// safe to mark with the nounwind attribute..
446static bool IsNoThrow(InstructionClass Class) {
Dan Gohman1d2fd752011-09-14 18:33:34 +0000447 // objc_retainBlock is not nounwind because it calls user copy constructors
448 // which could theoretically throw.
John McCall9fbd3182011-06-15 23:37:01 +0000449 return Class == IC_Retain ||
450 Class == IC_RetainRV ||
John McCall9fbd3182011-06-15 23:37:01 +0000451 Class == IC_Release ||
452 Class == IC_Autorelease ||
453 Class == IC_AutoreleaseRV ||
454 Class == IC_AutoreleasepoolPush ||
455 Class == IC_AutoreleasepoolPop;
456}
457
Dan Gohman447989c2012-04-27 18:56:31 +0000458/// EraseInstruction - Erase the given instruction. Many ObjC calls return their
John McCall9fbd3182011-06-15 23:37:01 +0000459/// argument verbatim, so if it's such a call and the return value has users,
460/// replace them with the argument value.
461static void EraseInstruction(Instruction *CI) {
462 Value *OldArg = cast<CallInst>(CI)->getArgOperand(0);
463
464 bool Unused = CI->use_empty();
465
466 if (!Unused) {
467 // Replace the return value with the argument.
468 assert(IsForwarding(GetBasicInstructionClass(CI)) &&
469 "Can't delete non-forwarding instruction with users!");
470 CI->replaceAllUsesWith(OldArg);
471 }
472
473 CI->eraseFromParent();
474
475 if (Unused)
476 RecursivelyDeleteTriviallyDeadInstructions(OldArg);
477}
478
479/// GetUnderlyingObjCPtr - This is a wrapper around getUnderlyingObject which
480/// also knows how to look through objc_retain and objc_autorelease calls, which
481/// we know to return their argument verbatim.
482static const Value *GetUnderlyingObjCPtr(const Value *V) {
483 for (;;) {
484 V = GetUnderlyingObject(V);
485 if (!IsForwarding(GetBasicInstructionClass(V)))
486 break;
487 V = cast<CallInst>(V)->getArgOperand(0);
488 }
489
490 return V;
491}
492
493/// StripPointerCastsAndObjCCalls - This is a wrapper around
494/// Value::stripPointerCasts which also knows how to look through objc_retain
495/// and objc_autorelease calls, which we know to return their argument verbatim.
496static const Value *StripPointerCastsAndObjCCalls(const Value *V) {
497 for (;;) {
498 V = V->stripPointerCasts();
499 if (!IsForwarding(GetBasicInstructionClass(V)))
500 break;
501 V = cast<CallInst>(V)->getArgOperand(0);
502 }
503 return V;
504}
505
506/// StripPointerCastsAndObjCCalls - This is a wrapper around
507/// Value::stripPointerCasts which also knows how to look through objc_retain
508/// and objc_autorelease calls, which we know to return their argument verbatim.
509static Value *StripPointerCastsAndObjCCalls(Value *V) {
510 for (;;) {
511 V = V->stripPointerCasts();
512 if (!IsForwarding(GetBasicInstructionClass(V)))
513 break;
514 V = cast<CallInst>(V)->getArgOperand(0);
515 }
516 return V;
517}
518
519/// GetObjCArg - Assuming the given instruction is one of the special calls such
520/// as objc_retain or objc_release, return the argument value, stripped of no-op
521/// casts and forwarding calls.
522static Value *GetObjCArg(Value *Inst) {
523 return StripPointerCastsAndObjCCalls(cast<CallInst>(Inst)->getArgOperand(0));
524}
525
526/// IsObjCIdentifiedObject - This is similar to AliasAnalysis'
527/// isObjCIdentifiedObject, except that it uses special knowledge of
528/// ObjC conventions...
529static bool IsObjCIdentifiedObject(const Value *V) {
530 // Assume that call results and arguments have their own "provenance".
531 // Constants (including GlobalVariables) and Allocas are never
532 // reference-counted.
533 if (isa<CallInst>(V) || isa<InvokeInst>(V) ||
534 isa<Argument>(V) || isa<Constant>(V) ||
535 isa<AllocaInst>(V))
536 return true;
537
538 if (const LoadInst *LI = dyn_cast<LoadInst>(V)) {
539 const Value *Pointer =
540 StripPointerCastsAndObjCCalls(LI->getPointerOperand());
541 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Pointer)) {
Dan Gohman1b31ea82011-08-22 17:29:11 +0000542 // A constant pointer can't be pointing to an object on the heap. It may
543 // be reference-counted, but it won't be deleted.
544 if (GV->isConstant())
545 return true;
John McCall9fbd3182011-06-15 23:37:01 +0000546 StringRef Name = GV->getName();
547 // These special variables are known to hold values which are not
548 // reference-counted pointers.
549 if (Name.startswith("\01L_OBJC_SELECTOR_REFERENCES_") ||
550 Name.startswith("\01L_OBJC_CLASSLIST_REFERENCES_") ||
551 Name.startswith("\01L_OBJC_CLASSLIST_SUP_REFS_$_") ||
552 Name.startswith("\01L_OBJC_METH_VAR_NAME_") ||
553 Name.startswith("\01l_objc_msgSend_fixup_"))
554 return true;
555 }
556 }
557
558 return false;
559}
560
561/// FindSingleUseIdentifiedObject - This is similar to
562/// StripPointerCastsAndObjCCalls but it stops as soon as it finds a value
563/// with multiple uses.
564static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
565 if (Arg->hasOneUse()) {
566 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
567 return FindSingleUseIdentifiedObject(BC->getOperand(0));
568 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
569 if (GEP->hasAllZeroIndices())
570 return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
571 if (IsForwarding(GetBasicInstructionClass(Arg)))
572 return FindSingleUseIdentifiedObject(
573 cast<CallInst>(Arg)->getArgOperand(0));
574 if (!IsObjCIdentifiedObject(Arg))
575 return 0;
576 return Arg;
577 }
578
Dan Gohman0daef3d2012-05-08 23:39:44 +0000579 // If we found an identifiable object but it has multiple uses, but they are
580 // trivial uses, we can still consider this to be a single-use value.
John McCall9fbd3182011-06-15 23:37:01 +0000581 if (IsObjCIdentifiedObject(Arg)) {
582 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
583 UI != UE; ++UI) {
584 const User *U = *UI;
585 if (!U->use_empty() || StripPointerCastsAndObjCCalls(U) != Arg)
586 return 0;
587 }
588
589 return Arg;
590 }
591
592 return 0;
593}
594
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000595/// ModuleHasARC - Test if the given module looks interesting to run ARC
596/// optimization on.
597static bool ModuleHasARC(const Module &M) {
598 return
599 M.getNamedValue("objc_retain") ||
600 M.getNamedValue("objc_release") ||
601 M.getNamedValue("objc_autorelease") ||
602 M.getNamedValue("objc_retainAutoreleasedReturnValue") ||
603 M.getNamedValue("objc_retainBlock") ||
604 M.getNamedValue("objc_autoreleaseReturnValue") ||
605 M.getNamedValue("objc_autoreleasePoolPush") ||
606 M.getNamedValue("objc_loadWeakRetained") ||
607 M.getNamedValue("objc_loadWeak") ||
608 M.getNamedValue("objc_destroyWeak") ||
609 M.getNamedValue("objc_storeWeak") ||
610 M.getNamedValue("objc_initWeak") ||
611 M.getNamedValue("objc_moveWeak") ||
612 M.getNamedValue("objc_copyWeak") ||
613 M.getNamedValue("objc_retainedObject") ||
614 M.getNamedValue("objc_unretainedObject") ||
615 M.getNamedValue("objc_unretainedPointer");
616}
617
Dan Gohman79522dc2012-01-13 00:39:07 +0000618/// DoesObjCBlockEscape - Test whether the given pointer, which is an
619/// Objective C block pointer, does not "escape". This differs from regular
620/// escape analysis in that a use as an argument to a call is not considered
621/// an escape.
622static bool DoesObjCBlockEscape(const Value *BlockPtr) {
Michael Gottesman981308c2013-01-13 07:47:32 +0000623
624 DEBUG(dbgs() << "DoesObjCBlockEscape: Target: " << *BlockPtr << "\n");
625
Dan Gohman79522dc2012-01-13 00:39:07 +0000626 // Walk the def-use chains.
627 SmallVector<const Value *, 4> Worklist;
628 Worklist.push_back(BlockPtr);
Michael Gottesman6056b852013-01-13 22:12:06 +0000629
630 // Ensure we do not visit any value twice.
631 SmallPtrSet<const Value *, 4> VisitedSet;
632
Dan Gohman79522dc2012-01-13 00:39:07 +0000633 do {
634 const Value *V = Worklist.pop_back_val();
Michael Gottesman981308c2013-01-13 07:47:32 +0000635
636 DEBUG(dbgs() << "DoesObjCBlockEscape: Visiting: " << *V << "\n");
637
Dan Gohman79522dc2012-01-13 00:39:07 +0000638 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
639 UI != UE; ++UI) {
640 const User *UUser = *UI;
Michael Gottesman981308c2013-01-13 07:47:32 +0000641
642 DEBUG(dbgs() << "DoesObjCBlockEscape: User: " << *UUser << "\n");
643
Dan Gohman79522dc2012-01-13 00:39:07 +0000644 // Special - Use by a call (callee or argument) is not considered
645 // to be an escape.
Dan Gohman44234772012-04-13 18:28:58 +0000646 switch (GetBasicInstructionClass(UUser)) {
647 case IC_StoreWeak:
648 case IC_InitWeak:
649 case IC_StoreStrong:
650 case IC_Autorelease:
Michael Gottesman981308c2013-01-13 07:47:32 +0000651 case IC_AutoreleaseRV: {
652 DEBUG(dbgs() << "DoesObjCBlockEscape: User copies pointer arguments. "
653 "Block Escapes!\n");
Dan Gohman44234772012-04-13 18:28:58 +0000654 // These special functions make copies of their pointer arguments.
655 return true;
Michael Gottesman981308c2013-01-13 07:47:32 +0000656 }
Dan Gohman44234772012-04-13 18:28:58 +0000657 case IC_User:
658 case IC_None:
659 // Use by an instruction which copies the value is an escape if the
660 // result is an escape.
661 if (isa<BitCastInst>(UUser) || isa<GetElementPtrInst>(UUser) ||
662 isa<PHINode>(UUser) || isa<SelectInst>(UUser)) {
Michael Gottesman6056b852013-01-13 22:12:06 +0000663
664 if (!VisitedSet.count(UUser)) {
665 DEBUG(dbgs() << "DoesObjCBlockEscape: User copies value. Escapes if "
666 "result escapes. Adding to list.\n");
667 VisitedSet.insert(V);
668 Worklist.push_back(UUser);
669 } else {
670 DEBUG(dbgs() << "DoesObjCBlockEscape: Already visited node.\n");
671 }
Dan Gohman44234772012-04-13 18:28:58 +0000672 continue;
673 }
674 // Use by a load is not an escape.
675 if (isa<LoadInst>(UUser))
676 continue;
677 // Use by a store is not an escape if the use is the address.
678 if (const StoreInst *SI = dyn_cast<StoreInst>(UUser))
679 if (V != SI->getValueOperand())
680 continue;
681 break;
682 default:
683 // Regular calls and other stuff are not considered escapes.
Dan Gohman79522dc2012-01-13 00:39:07 +0000684 continue;
685 }
Dan Gohmana3b08d62012-02-13 22:57:02 +0000686 // Otherwise, conservatively assume an escape.
Michael Gottesman981308c2013-01-13 07:47:32 +0000687 DEBUG(dbgs() << "DoesObjCBlockEscape: Assuming block escapes.\n");
Dan Gohman79522dc2012-01-13 00:39:07 +0000688 return true;
689 }
690 } while (!Worklist.empty());
691
692 // No escapes found.
Michael Gottesman981308c2013-01-13 07:47:32 +0000693 DEBUG(dbgs() << "DoesObjCBlockEscape: Block does not escape.\n");
Dan Gohman79522dc2012-01-13 00:39:07 +0000694 return false;
695}
696
John McCall9fbd3182011-06-15 23:37:01 +0000697//===----------------------------------------------------------------------===//
698// ARC AliasAnalysis.
699//===----------------------------------------------------------------------===//
700
John McCall9fbd3182011-06-15 23:37:01 +0000701#include "llvm/Analysis/AliasAnalysis.h"
702#include "llvm/Analysis/Passes.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +0000703#include "llvm/Pass.h"
John McCall9fbd3182011-06-15 23:37:01 +0000704
705namespace {
706 /// ObjCARCAliasAnalysis - This is a simple alias analysis
707 /// implementation that uses knowledge of ARC constructs to answer queries.
708 ///
709 /// TODO: This class could be generalized to know about other ObjC-specific
710 /// tricks. Such as knowing that ivars in the non-fragile ABI are non-aliasing
711 /// even though their offsets are dynamic.
712 class ObjCARCAliasAnalysis : public ImmutablePass,
713 public AliasAnalysis {
714 public:
715 static char ID; // Class identification, replacement for typeinfo
716 ObjCARCAliasAnalysis() : ImmutablePass(ID) {
717 initializeObjCARCAliasAnalysisPass(*PassRegistry::getPassRegistry());
718 }
719
720 private:
721 virtual void initializePass() {
722 InitializeAliasAnalysis(this);
723 }
724
725 /// getAdjustedAnalysisPointer - This method is used when a pass implements
726 /// an analysis interface through multiple inheritance. If needed, it
727 /// should override this to adjust the this pointer as needed for the
728 /// specified pass info.
729 virtual void *getAdjustedAnalysisPointer(const void *PI) {
730 if (PI == &AliasAnalysis::ID)
Dan Gohman447989c2012-04-27 18:56:31 +0000731 return static_cast<AliasAnalysis *>(this);
John McCall9fbd3182011-06-15 23:37:01 +0000732 return this;
733 }
734
735 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
736 virtual AliasResult alias(const Location &LocA, const Location &LocB);
737 virtual bool pointsToConstantMemory(const Location &Loc, bool OrLocal);
738 virtual ModRefBehavior getModRefBehavior(ImmutableCallSite CS);
739 virtual ModRefBehavior getModRefBehavior(const Function *F);
740 virtual ModRefResult getModRefInfo(ImmutableCallSite CS,
741 const Location &Loc);
742 virtual ModRefResult getModRefInfo(ImmutableCallSite CS1,
743 ImmutableCallSite CS2);
744 };
745} // End of anonymous namespace
746
747// Register this pass...
748char ObjCARCAliasAnalysis::ID = 0;
749INITIALIZE_AG_PASS(ObjCARCAliasAnalysis, AliasAnalysis, "objc-arc-aa",
750 "ObjC-ARC-Based Alias Analysis", false, true, false)
751
752ImmutablePass *llvm::createObjCARCAliasAnalysisPass() {
753 return new ObjCARCAliasAnalysis();
754}
755
756void
757ObjCARCAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
758 AU.setPreservesAll();
759 AliasAnalysis::getAnalysisUsage(AU);
760}
761
762AliasAnalysis::AliasResult
763ObjCARCAliasAnalysis::alias(const Location &LocA, const Location &LocB) {
764 if (!EnableARCOpts)
765 return AliasAnalysis::alias(LocA, LocB);
766
767 // First, strip off no-ops, including ObjC-specific no-ops, and try making a
768 // precise alias query.
769 const Value *SA = StripPointerCastsAndObjCCalls(LocA.Ptr);
770 const Value *SB = StripPointerCastsAndObjCCalls(LocB.Ptr);
771 AliasResult Result =
772 AliasAnalysis::alias(Location(SA, LocA.Size, LocA.TBAATag),
773 Location(SB, LocB.Size, LocB.TBAATag));
774 if (Result != MayAlias)
775 return Result;
776
777 // If that failed, climb to the underlying object, including climbing through
778 // ObjC-specific no-ops, and try making an imprecise alias query.
779 const Value *UA = GetUnderlyingObjCPtr(SA);
780 const Value *UB = GetUnderlyingObjCPtr(SB);
781 if (UA != SA || UB != SB) {
782 Result = AliasAnalysis::alias(Location(UA), Location(UB));
783 // We can't use MustAlias or PartialAlias results here because
784 // GetUnderlyingObjCPtr may return an offsetted pointer value.
785 if (Result == NoAlias)
786 return NoAlias;
787 }
788
789 // If that failed, fail. We don't need to chain here, since that's covered
790 // by the earlier precise query.
791 return MayAlias;
792}
793
794bool
795ObjCARCAliasAnalysis::pointsToConstantMemory(const Location &Loc,
796 bool OrLocal) {
797 if (!EnableARCOpts)
798 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
799
800 // First, strip off no-ops, including ObjC-specific no-ops, and try making
801 // a precise alias query.
802 const Value *S = StripPointerCastsAndObjCCalls(Loc.Ptr);
803 if (AliasAnalysis::pointsToConstantMemory(Location(S, Loc.Size, Loc.TBAATag),
804 OrLocal))
805 return true;
806
807 // If that failed, climb to the underlying object, including climbing through
808 // ObjC-specific no-ops, and try making an imprecise alias query.
809 const Value *U = GetUnderlyingObjCPtr(S);
810 if (U != S)
811 return AliasAnalysis::pointsToConstantMemory(Location(U), OrLocal);
812
813 // If that failed, fail. We don't need to chain here, since that's covered
814 // by the earlier precise query.
815 return false;
816}
817
818AliasAnalysis::ModRefBehavior
819ObjCARCAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
820 // We have nothing to do. Just chain to the next AliasAnalysis.
821 return AliasAnalysis::getModRefBehavior(CS);
822}
823
824AliasAnalysis::ModRefBehavior
825ObjCARCAliasAnalysis::getModRefBehavior(const Function *F) {
826 if (!EnableARCOpts)
827 return AliasAnalysis::getModRefBehavior(F);
828
829 switch (GetFunctionClass(F)) {
830 case IC_NoopCast:
831 return DoesNotAccessMemory;
832 default:
833 break;
834 }
835
836 return AliasAnalysis::getModRefBehavior(F);
837}
838
839AliasAnalysis::ModRefResult
840ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS, const Location &Loc) {
841 if (!EnableARCOpts)
842 return AliasAnalysis::getModRefInfo(CS, Loc);
843
844 switch (GetBasicInstructionClass(CS.getInstruction())) {
845 case IC_Retain:
846 case IC_RetainRV:
John McCall9fbd3182011-06-15 23:37:01 +0000847 case IC_Autorelease:
848 case IC_AutoreleaseRV:
849 case IC_NoopCast:
850 case IC_AutoreleasepoolPush:
851 case IC_FusedRetainAutorelease:
852 case IC_FusedRetainAutoreleaseRV:
853 // These functions don't access any memory visible to the compiler.
Benjamin Kramerd9b0b022012-06-02 10:20:22 +0000854 // Note that this doesn't include objc_retainBlock, because it updates
Dan Gohman21104822011-09-14 18:13:00 +0000855 // pointers when it copies block data.
John McCall9fbd3182011-06-15 23:37:01 +0000856 return NoModRef;
857 default:
858 break;
859 }
860
861 return AliasAnalysis::getModRefInfo(CS, Loc);
862}
863
864AliasAnalysis::ModRefResult
865ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
866 ImmutableCallSite CS2) {
867 // TODO: Theoretically we could check for dependencies between objc_* calls
868 // and OnlyAccessesArgumentPointees calls or other well-behaved calls.
869 return AliasAnalysis::getModRefInfo(CS1, CS2);
870}
871
872//===----------------------------------------------------------------------===//
873// ARC expansion.
874//===----------------------------------------------------------------------===//
875
876#include "llvm/Support/InstIterator.h"
877#include "llvm/Transforms/Scalar.h"
878
879namespace {
880 /// ObjCARCExpand - Early ARC transformations.
881 class ObjCARCExpand : public FunctionPass {
882 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000883 virtual bool doInitialization(Module &M);
John McCall9fbd3182011-06-15 23:37:01 +0000884 virtual bool runOnFunction(Function &F);
885
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000886 /// Run - A flag indicating whether this optimization pass should run.
887 bool Run;
888
John McCall9fbd3182011-06-15 23:37:01 +0000889 public:
890 static char ID;
891 ObjCARCExpand() : FunctionPass(ID) {
892 initializeObjCARCExpandPass(*PassRegistry::getPassRegistry());
893 }
894 };
895}
896
897char ObjCARCExpand::ID = 0;
898INITIALIZE_PASS(ObjCARCExpand,
899 "objc-arc-expand", "ObjC ARC expansion", false, false)
900
901Pass *llvm::createObjCARCExpandPass() {
902 return new ObjCARCExpand();
903}
904
905void ObjCARCExpand::getAnalysisUsage(AnalysisUsage &AU) const {
906 AU.setPreservesCFG();
907}
908
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000909bool ObjCARCExpand::doInitialization(Module &M) {
910 Run = ModuleHasARC(M);
911 return false;
912}
913
John McCall9fbd3182011-06-15 23:37:01 +0000914bool ObjCARCExpand::runOnFunction(Function &F) {
915 if (!EnableARCOpts)
916 return false;
917
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000918 // If nothing in the Module uses ARC, don't do anything.
919 if (!Run)
920 return false;
921
John McCall9fbd3182011-06-15 23:37:01 +0000922 bool Changed = false;
923
Michael Gottesmancf140052013-01-13 07:00:51 +0000924 DEBUG(dbgs() << "ObjCARCExpand: Visiting Function: " << F.getName() << "\n");
925
John McCall9fbd3182011-06-15 23:37:01 +0000926 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
927 Instruction *Inst = &*I;
Michael Gottesman2f1bfc42013-01-07 21:26:07 +0000928
Michael Gottesman8f22c8b2013-01-01 16:05:48 +0000929 DEBUG(dbgs() << "ObjCARCExpand: Visiting: " << *Inst << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +0000930
John McCall9fbd3182011-06-15 23:37:01 +0000931 switch (GetBasicInstructionClass(Inst)) {
932 case IC_Retain:
933 case IC_RetainRV:
934 case IC_Autorelease:
935 case IC_AutoreleaseRV:
936 case IC_FusedRetainAutorelease:
Michael Gottesmana6e23cc2013-01-01 16:05:54 +0000937 case IC_FusedRetainAutoreleaseRV: {
John McCall9fbd3182011-06-15 23:37:01 +0000938 // These calls return their argument verbatim, as a low-level
939 // optimization. However, this makes high-level optimizations
940 // harder. Undo any uses of this optimization that the front-end
Dan Gohmand6bf2012012-04-13 18:57:48 +0000941 // emitted here. We'll redo them in the contract pass.
John McCall9fbd3182011-06-15 23:37:01 +0000942 Changed = true;
Michael Gottesmana6e23cc2013-01-01 16:05:54 +0000943 Value *Value = cast<CallInst>(Inst)->getArgOperand(0);
944 DEBUG(dbgs() << "ObjCARCExpand: Old = " << *Inst << "\n"
945 " New = " << *Value << "\n");
946 Inst->replaceAllUsesWith(Value);
John McCall9fbd3182011-06-15 23:37:01 +0000947 break;
Michael Gottesmana6e23cc2013-01-01 16:05:54 +0000948 }
John McCall9fbd3182011-06-15 23:37:01 +0000949 default:
950 break;
951 }
952 }
Michael Gottesman2f1bfc42013-01-07 21:26:07 +0000953
Michael Gottesmanec21e2a2013-01-03 08:09:27 +0000954 DEBUG(dbgs() << "ObjCARCExpand: Finished List.\n\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +0000955
John McCall9fbd3182011-06-15 23:37:01 +0000956 return Changed;
957}
958
959//===----------------------------------------------------------------------===//
Dan Gohman2f6263c2012-01-17 20:52:24 +0000960// ARC autorelease pool elimination.
961//===----------------------------------------------------------------------===//
962
Dan Gohman0daef3d2012-05-08 23:39:44 +0000963#include "llvm/ADT/STLExtras.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +0000964#include "llvm/IR/Constants.h"
Dan Gohman1dae3e92012-01-18 21:19:38 +0000965
Dan Gohman2f6263c2012-01-17 20:52:24 +0000966namespace {
967 /// ObjCARCAPElim - Autorelease pool elimination.
968 class ObjCARCAPElim : public ModulePass {
969 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
970 virtual bool runOnModule(Module &M);
971
Dan Gohman447989c2012-04-27 18:56:31 +0000972 static bool MayAutorelease(ImmutableCallSite CS, unsigned Depth = 0);
973 static bool OptimizeBB(BasicBlock *BB);
Dan Gohman2f6263c2012-01-17 20:52:24 +0000974
975 public:
976 static char ID;
977 ObjCARCAPElim() : ModulePass(ID) {
978 initializeObjCARCAPElimPass(*PassRegistry::getPassRegistry());
979 }
980 };
981}
982
983char ObjCARCAPElim::ID = 0;
984INITIALIZE_PASS(ObjCARCAPElim,
985 "objc-arc-apelim",
986 "ObjC ARC autorelease pool elimination",
987 false, false)
988
989Pass *llvm::createObjCARCAPElimPass() {
990 return new ObjCARCAPElim();
991}
992
993void ObjCARCAPElim::getAnalysisUsage(AnalysisUsage &AU) const {
994 AU.setPreservesCFG();
995}
996
997/// MayAutorelease - Interprocedurally determine if calls made by the
998/// given call site can possibly produce autoreleases.
Dan Gohman447989c2012-04-27 18:56:31 +0000999bool ObjCARCAPElim::MayAutorelease(ImmutableCallSite CS, unsigned Depth) {
1000 if (const Function *Callee = CS.getCalledFunction()) {
Dan Gohman2f6263c2012-01-17 20:52:24 +00001001 if (Callee->isDeclaration() || Callee->mayBeOverridden())
1002 return true;
Dan Gohman447989c2012-04-27 18:56:31 +00001003 for (Function::const_iterator I = Callee->begin(), E = Callee->end();
Dan Gohman2f6263c2012-01-17 20:52:24 +00001004 I != E; ++I) {
Dan Gohman447989c2012-04-27 18:56:31 +00001005 const BasicBlock *BB = I;
1006 for (BasicBlock::const_iterator J = BB->begin(), F = BB->end();
1007 J != F; ++J)
1008 if (ImmutableCallSite JCS = ImmutableCallSite(J))
Dan Gohman2f77bbd2012-01-18 21:24:45 +00001009 // This recursion depth limit is arbitrary. It's just great
1010 // enough to cover known interesting testcases.
1011 if (Depth < 3 &&
1012 !JCS.onlyReadsMemory() &&
1013 MayAutorelease(JCS, Depth + 1))
Dan Gohman2f6263c2012-01-17 20:52:24 +00001014 return true;
1015 }
1016 return false;
1017 }
1018
1019 return true;
1020}
1021
1022bool ObjCARCAPElim::OptimizeBB(BasicBlock *BB) {
1023 bool Changed = false;
1024
1025 Instruction *Push = 0;
1026 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1027 Instruction *Inst = I++;
1028 switch (GetBasicInstructionClass(Inst)) {
1029 case IC_AutoreleasepoolPush:
1030 Push = Inst;
1031 break;
1032 case IC_AutoreleasepoolPop:
1033 // If this pop matches a push and nothing in between can autorelease,
1034 // zap the pair.
1035 if (Push && cast<CallInst>(Inst)->getArgOperand(0) == Push) {
1036 Changed = true;
Michael Gottesman5c0ae472013-01-04 21:29:57 +00001037 DEBUG(dbgs() << "ObjCARCAPElim::OptimizeBB: Zapping push pop autorelease pair:\n"
Michael Gottesmandf379f42013-01-03 08:09:17 +00001038 << " Pop: " << *Inst << "\n"
1039 << " Push: " << *Push << "\n");
Dan Gohman2f6263c2012-01-17 20:52:24 +00001040 Inst->eraseFromParent();
1041 Push->eraseFromParent();
1042 }
1043 Push = 0;
1044 break;
1045 case IC_CallOrUser:
Dan Gohman447989c2012-04-27 18:56:31 +00001046 if (MayAutorelease(ImmutableCallSite(Inst)))
Dan Gohman2f6263c2012-01-17 20:52:24 +00001047 Push = 0;
1048 break;
1049 default:
1050 break;
1051 }
1052 }
1053
1054 return Changed;
1055}
1056
1057bool ObjCARCAPElim::runOnModule(Module &M) {
1058 if (!EnableARCOpts)
1059 return false;
1060
1061 // If nothing in the Module uses ARC, don't do anything.
1062 if (!ModuleHasARC(M))
1063 return false;
1064
Dan Gohman1dae3e92012-01-18 21:19:38 +00001065 // Find the llvm.global_ctors variable, as the first step in
Dan Gohmand6bf2012012-04-13 18:57:48 +00001066 // identifying the global constructors. In theory, unnecessary autorelease
1067 // pools could occur anywhere, but in practice it's pretty rare. Global
1068 // ctors are a place where autorelease pools get inserted automatically,
1069 // so it's pretty common for them to be unnecessary, and it's pretty
1070 // profitable to eliminate them.
Dan Gohman1dae3e92012-01-18 21:19:38 +00001071 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1072 if (!GV)
1073 return false;
1074
1075 assert(GV->hasDefinitiveInitializer() &&
1076 "llvm.global_ctors is uncooperative!");
1077
Dan Gohman2f6263c2012-01-17 20:52:24 +00001078 bool Changed = false;
1079
Dan Gohman1dae3e92012-01-18 21:19:38 +00001080 // Dig the constructor functions out of GV's initializer.
1081 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
1082 for (User::op_iterator OI = Init->op_begin(), OE = Init->op_end();
1083 OI != OE; ++OI) {
1084 Value *Op = *OI;
1085 // llvm.global_ctors is an array of pairs where the second members
1086 // are constructor functions.
Dan Gohman3b5b2a22012-04-18 22:24:33 +00001087 Function *F = dyn_cast<Function>(cast<ConstantStruct>(Op)->getOperand(1));
1088 // If the user used a constructor function with the wrong signature and
1089 // it got bitcasted or whatever, look the other way.
1090 if (!F)
1091 continue;
Dan Gohman2f6263c2012-01-17 20:52:24 +00001092 // Only look at function definitions.
1093 if (F->isDeclaration())
1094 continue;
Dan Gohman2f6263c2012-01-17 20:52:24 +00001095 // Only look at functions with one basic block.
1096 if (llvm::next(F->begin()) != F->end())
1097 continue;
1098 // Ok, a single-block constructor function definition. Try to optimize it.
1099 Changed |= OptimizeBB(F->begin());
1100 }
1101
1102 return Changed;
1103}
1104
1105//===----------------------------------------------------------------------===//
John McCall9fbd3182011-06-15 23:37:01 +00001106// ARC optimization.
1107//===----------------------------------------------------------------------===//
1108
1109// TODO: On code like this:
1110//
1111// objc_retain(%x)
1112// stuff_that_cannot_release()
1113// objc_autorelease(%x)
1114// stuff_that_cannot_release()
1115// objc_retain(%x)
1116// stuff_that_cannot_release()
1117// objc_autorelease(%x)
1118//
1119// The second retain and autorelease can be deleted.
1120
1121// TODO: It should be possible to delete
1122// objc_autoreleasePoolPush and objc_autoreleasePoolPop
1123// pairs if nothing is actually autoreleased between them. Also, autorelease
1124// calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
1125// after inlining) can be turned into plain release calls.
1126
1127// TODO: Critical-edge splitting. If the optimial insertion point is
1128// a critical edge, the current algorithm has to fail, because it doesn't
1129// know how to split edges. It should be possible to make the optimizer
1130// think in terms of edges, rather than blocks, and then split critical
1131// edges on demand.
1132
1133// TODO: OptimizeSequences could generalized to be Interprocedural.
1134
1135// TODO: Recognize that a bunch of other objc runtime calls have
1136// non-escaping arguments and non-releasing arguments, and may be
1137// non-autoreleasing.
1138
1139// TODO: Sink autorelease calls as far as possible. Unfortunately we
1140// usually can't sink them past other calls, which would be the main
1141// case where it would be useful.
1142
Dan Gohmane6d5e882011-08-19 00:26:36 +00001143// TODO: The pointer returned from objc_loadWeakRetained is retained.
1144
1145// TODO: Delete release+retain pairs (rare).
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00001146
Chandler Carruthd04a8d42012-12-03 16:50:05 +00001147#include "llvm/ADT/SmallPtrSet.h"
1148#include "llvm/ADT/Statistic.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +00001149#include "llvm/IR/LLVMContext.h"
John McCall9fbd3182011-06-15 23:37:01 +00001150#include "llvm/Support/CFG.h"
John McCall9fbd3182011-06-15 23:37:01 +00001151
1152STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
1153STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
1154STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
1155STATISTIC(NumRets, "Number of return value forwarding "
1156 "retain+autoreleaes eliminated");
1157STATISTIC(NumRRs, "Number of retain+release paths eliminated");
1158STATISTIC(NumPeeps, "Number of calls peephole-optimized");
1159
1160namespace {
1161 /// ProvenanceAnalysis - This is similar to BasicAliasAnalysis, and it
1162 /// uses many of the same techniques, except it uses special ObjC-specific
1163 /// reasoning about pointer relationships.
1164 class ProvenanceAnalysis {
1165 AliasAnalysis *AA;
1166
1167 typedef std::pair<const Value *, const Value *> ValuePairTy;
1168 typedef DenseMap<ValuePairTy, bool> CachedResultsTy;
1169 CachedResultsTy CachedResults;
1170
1171 bool relatedCheck(const Value *A, const Value *B);
1172 bool relatedSelect(const SelectInst *A, const Value *B);
1173 bool relatedPHI(const PHINode *A, const Value *B);
1174
Craig Topperc2945e42012-09-18 02:01:41 +00001175 void operator=(const ProvenanceAnalysis &) LLVM_DELETED_FUNCTION;
1176 ProvenanceAnalysis(const ProvenanceAnalysis &) LLVM_DELETED_FUNCTION;
John McCall9fbd3182011-06-15 23:37:01 +00001177
1178 public:
1179 ProvenanceAnalysis() {}
1180
1181 void setAA(AliasAnalysis *aa) { AA = aa; }
1182
1183 AliasAnalysis *getAA() const { return AA; }
1184
1185 bool related(const Value *A, const Value *B);
1186
1187 void clear() {
1188 CachedResults.clear();
1189 }
1190 };
1191}
1192
1193bool ProvenanceAnalysis::relatedSelect(const SelectInst *A, const Value *B) {
1194 // If the values are Selects with the same condition, we can do a more precise
1195 // check: just check for relations between the values on corresponding arms.
1196 if (const SelectInst *SB = dyn_cast<SelectInst>(B))
Dan Gohman447989c2012-04-27 18:56:31 +00001197 if (A->getCondition() == SB->getCondition())
1198 return related(A->getTrueValue(), SB->getTrueValue()) ||
1199 related(A->getFalseValue(), SB->getFalseValue());
John McCall9fbd3182011-06-15 23:37:01 +00001200
1201 // Check both arms of the Select node individually.
Dan Gohman447989c2012-04-27 18:56:31 +00001202 return related(A->getTrueValue(), B) ||
1203 related(A->getFalseValue(), B);
John McCall9fbd3182011-06-15 23:37:01 +00001204}
1205
1206bool ProvenanceAnalysis::relatedPHI(const PHINode *A, const Value *B) {
1207 // If the values are PHIs in the same block, we can do a more precise as well
1208 // as efficient check: just check for relations between the values on
1209 // corresponding edges.
1210 if (const PHINode *PNB = dyn_cast<PHINode>(B))
1211 if (PNB->getParent() == A->getParent()) {
1212 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i)
1213 if (related(A->getIncomingValue(i),
1214 PNB->getIncomingValueForBlock(A->getIncomingBlock(i))))
1215 return true;
1216 return false;
1217 }
1218
1219 // Check each unique source of the PHI node against B.
1220 SmallPtrSet<const Value *, 4> UniqueSrc;
1221 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i) {
1222 const Value *PV1 = A->getIncomingValue(i);
1223 if (UniqueSrc.insert(PV1) && related(PV1, B))
1224 return true;
1225 }
1226
1227 // All of the arms checked out.
1228 return false;
1229}
1230
1231/// isStoredObjCPointer - Test if the value of P, or any value covered by its
1232/// provenance, is ever stored within the function (not counting callees).
1233static bool isStoredObjCPointer(const Value *P) {
1234 SmallPtrSet<const Value *, 8> Visited;
1235 SmallVector<const Value *, 8> Worklist;
1236 Worklist.push_back(P);
1237 Visited.insert(P);
1238 do {
1239 P = Worklist.pop_back_val();
1240 for (Value::const_use_iterator UI = P->use_begin(), UE = P->use_end();
1241 UI != UE; ++UI) {
1242 const User *Ur = *UI;
1243 if (isa<StoreInst>(Ur)) {
1244 if (UI.getOperandNo() == 0)
1245 // The pointer is stored.
1246 return true;
1247 // The pointed is stored through.
1248 continue;
1249 }
1250 if (isa<CallInst>(Ur))
1251 // The pointer is passed as an argument, ignore this.
1252 continue;
1253 if (isa<PtrToIntInst>(P))
1254 // Assume the worst.
1255 return true;
1256 if (Visited.insert(Ur))
1257 Worklist.push_back(Ur);
1258 }
1259 } while (!Worklist.empty());
1260
1261 // Everything checked out.
1262 return false;
1263}
1264
1265bool ProvenanceAnalysis::relatedCheck(const Value *A, const Value *B) {
1266 // Skip past provenance pass-throughs.
1267 A = GetUnderlyingObjCPtr(A);
1268 B = GetUnderlyingObjCPtr(B);
1269
1270 // Quick check.
1271 if (A == B)
1272 return true;
1273
1274 // Ask regular AliasAnalysis, for a first approximation.
1275 switch (AA->alias(A, B)) {
1276 case AliasAnalysis::NoAlias:
1277 return false;
1278 case AliasAnalysis::MustAlias:
1279 case AliasAnalysis::PartialAlias:
1280 return true;
1281 case AliasAnalysis::MayAlias:
1282 break;
1283 }
1284
1285 bool AIsIdentified = IsObjCIdentifiedObject(A);
1286 bool BIsIdentified = IsObjCIdentifiedObject(B);
1287
1288 // An ObjC-Identified object can't alias a load if it is never locally stored.
1289 if (AIsIdentified) {
Dan Gohman230768b2012-09-04 23:16:20 +00001290 // Check for an obvious escape.
1291 if (isa<LoadInst>(B))
1292 return isStoredObjCPointer(A);
John McCall9fbd3182011-06-15 23:37:01 +00001293 if (BIsIdentified) {
Dan Gohman230768b2012-09-04 23:16:20 +00001294 // Check for an obvious escape.
1295 if (isa<LoadInst>(A))
1296 return isStoredObjCPointer(B);
1297 // Both pointers are identified and escapes aren't an evident problem.
1298 return false;
John McCall9fbd3182011-06-15 23:37:01 +00001299 }
Dan Gohman230768b2012-09-04 23:16:20 +00001300 } else if (BIsIdentified) {
1301 // Check for an obvious escape.
1302 if (isa<LoadInst>(A))
John McCall9fbd3182011-06-15 23:37:01 +00001303 return isStoredObjCPointer(B);
1304 }
1305
1306 // Special handling for PHI and Select.
1307 if (const PHINode *PN = dyn_cast<PHINode>(A))
1308 return relatedPHI(PN, B);
1309 if (const PHINode *PN = dyn_cast<PHINode>(B))
1310 return relatedPHI(PN, A);
1311 if (const SelectInst *S = dyn_cast<SelectInst>(A))
1312 return relatedSelect(S, B);
1313 if (const SelectInst *S = dyn_cast<SelectInst>(B))
1314 return relatedSelect(S, A);
1315
1316 // Conservative.
1317 return true;
1318}
1319
1320bool ProvenanceAnalysis::related(const Value *A, const Value *B) {
1321 // Begin by inserting a conservative value into the map. If the insertion
1322 // fails, we have the answer already. If it succeeds, leave it there until we
1323 // compute the real answer to guard against recursive queries.
1324 if (A > B) std::swap(A, B);
1325 std::pair<CachedResultsTy::iterator, bool> Pair =
1326 CachedResults.insert(std::make_pair(ValuePairTy(A, B), true));
1327 if (!Pair.second)
1328 return Pair.first->second;
1329
1330 bool Result = relatedCheck(A, B);
1331 CachedResults[ValuePairTy(A, B)] = Result;
1332 return Result;
1333}
1334
1335namespace {
1336 // Sequence - A sequence of states that a pointer may go through in which an
1337 // objc_retain and objc_release are actually needed.
1338 enum Sequence {
1339 S_None,
1340 S_Retain, ///< objc_retain(x)
1341 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement
1342 S_Use, ///< any use of x
1343 S_Stop, ///< like S_Release, but code motion is stopped
1344 S_Release, ///< objc_release(x)
1345 S_MovableRelease ///< objc_release(x), !clang.imprecise_release
1346 };
1347}
1348
1349static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
1350 // The easy cases.
1351 if (A == B)
1352 return A;
1353 if (A == S_None || B == S_None)
1354 return S_None;
1355
John McCall9fbd3182011-06-15 23:37:01 +00001356 if (A > B) std::swap(A, B);
1357 if (TopDown) {
1358 // Choose the side which is further along in the sequence.
Dan Gohmana7f7db22011-08-12 00:26:31 +00001359 if ((A == S_Retain || A == S_CanRelease) &&
1360 (B == S_CanRelease || B == S_Use))
John McCall9fbd3182011-06-15 23:37:01 +00001361 return B;
1362 } else {
1363 // Choose the side which is further along in the sequence.
1364 if ((A == S_Use || A == S_CanRelease) &&
Dan Gohmana7f7db22011-08-12 00:26:31 +00001365 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
John McCall9fbd3182011-06-15 23:37:01 +00001366 return A;
1367 // If both sides are releases, choose the more conservative one.
1368 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
1369 return A;
1370 if (A == S_Release && B == S_MovableRelease)
1371 return A;
1372 }
1373
1374 return S_None;
1375}
1376
1377namespace {
1378 /// RRInfo - Unidirectional information about either a
1379 /// retain-decrement-use-release sequence or release-use-decrement-retain
1380 /// reverese sequence.
1381 struct RRInfo {
Dan Gohmane6d5e882011-08-19 00:26:36 +00001382 /// KnownSafe - After an objc_retain, the reference count of the referenced
1383 /// object is known to be positive. Similarly, before an objc_release, the
1384 /// reference count of the referenced object is known to be positive. If
1385 /// there are retain-release pairs in code regions where the retain count
1386 /// is known to be positive, they can be eliminated, regardless of any side
1387 /// effects between them.
1388 ///
1389 /// Also, a retain+release pair nested within another retain+release
1390 /// pair all on the known same pointer value can be eliminated, regardless
1391 /// of any intervening side effects.
1392 ///
1393 /// KnownSafe is true when either of these conditions is satisfied.
1394 bool KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00001395
1396 /// IsRetainBlock - True if the Calls are objc_retainBlock calls (as
1397 /// opposed to objc_retain calls).
1398 bool IsRetainBlock;
1399
1400 /// IsTailCallRelease - True of the objc_release calls are all marked
1401 /// with the "tail" keyword.
1402 bool IsTailCallRelease;
1403
1404 /// ReleaseMetadata - If the Calls are objc_release calls and they all have
1405 /// a clang.imprecise_release tag, this is the metadata tag.
1406 MDNode *ReleaseMetadata;
1407
1408 /// Calls - For a top-down sequence, the set of objc_retains or
1409 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
1410 SmallPtrSet<Instruction *, 2> Calls;
1411
1412 /// ReverseInsertPts - The set of optimal insert positions for
1413 /// moving calls in the opposite sequence.
1414 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
1415
1416 RRInfo() :
Dan Gohman79522dc2012-01-13 00:39:07 +00001417 KnownSafe(false), IsRetainBlock(false),
Dan Gohman50ade652012-04-25 00:50:46 +00001418 IsTailCallRelease(false),
John McCall9fbd3182011-06-15 23:37:01 +00001419 ReleaseMetadata(0) {}
1420
1421 void clear();
1422 };
1423}
1424
1425void RRInfo::clear() {
Dan Gohmane6d5e882011-08-19 00:26:36 +00001426 KnownSafe = false;
John McCall9fbd3182011-06-15 23:37:01 +00001427 IsRetainBlock = false;
1428 IsTailCallRelease = false;
1429 ReleaseMetadata = 0;
1430 Calls.clear();
1431 ReverseInsertPts.clear();
1432}
1433
1434namespace {
1435 /// PtrState - This class summarizes several per-pointer runtime properties
1436 /// which are propogated through the flow graph.
1437 class PtrState {
Dan Gohman50ade652012-04-25 00:50:46 +00001438 /// KnownPositiveRefCount - True if the reference count is known to
1439 /// be incremented.
1440 bool KnownPositiveRefCount;
1441
1442 /// Partial - True of we've seen an opportunity for partial RR elimination,
1443 /// such as pushing calls into a CFG triangle or into one side of a
1444 /// CFG diamond.
1445 bool Partial;
John McCall9fbd3182011-06-15 23:37:01 +00001446
1447 /// Seq - The current position in the sequence.
Dan Gohman0daef3d2012-05-08 23:39:44 +00001448 Sequence Seq : 8;
John McCall9fbd3182011-06-15 23:37:01 +00001449
1450 public:
1451 /// RRI - Unidirectional information about the current sequence.
1452 /// TODO: Encapsulate this better.
1453 RRInfo RRI;
1454
Dan Gohman230768b2012-09-04 23:16:20 +00001455 PtrState() : KnownPositiveRefCount(false), Partial(false),
Dan Gohman0daef3d2012-05-08 23:39:44 +00001456 Seq(S_None) {}
John McCall9fbd3182011-06-15 23:37:01 +00001457
Dan Gohman50ade652012-04-25 00:50:46 +00001458 void SetKnownPositiveRefCount() {
1459 KnownPositiveRefCount = true;
Dan Gohmana7f7db22011-08-12 00:26:31 +00001460 }
1461
Dan Gohman50ade652012-04-25 00:50:46 +00001462 void ClearRefCount() {
1463 KnownPositiveRefCount = false;
John McCall9fbd3182011-06-15 23:37:01 +00001464 }
1465
John McCall9fbd3182011-06-15 23:37:01 +00001466 bool IsKnownIncremented() const {
Dan Gohman50ade652012-04-25 00:50:46 +00001467 return KnownPositiveRefCount;
John McCall9fbd3182011-06-15 23:37:01 +00001468 }
1469
1470 void SetSeq(Sequence NewSeq) {
1471 Seq = NewSeq;
1472 }
1473
John McCall9fbd3182011-06-15 23:37:01 +00001474 Sequence GetSeq() const {
1475 return Seq;
1476 }
1477
1478 void ClearSequenceProgress() {
Dan Gohman50ade652012-04-25 00:50:46 +00001479 ResetSequenceProgress(S_None);
1480 }
1481
1482 void ResetSequenceProgress(Sequence NewSeq) {
1483 Seq = NewSeq;
1484 Partial = false;
John McCall9fbd3182011-06-15 23:37:01 +00001485 RRI.clear();
1486 }
1487
1488 void Merge(const PtrState &Other, bool TopDown);
1489 };
1490}
1491
1492void
1493PtrState::Merge(const PtrState &Other, bool TopDown) {
1494 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
Dan Gohman50ade652012-04-25 00:50:46 +00001495 KnownPositiveRefCount = KnownPositiveRefCount && Other.KnownPositiveRefCount;
John McCall9fbd3182011-06-15 23:37:01 +00001496
1497 // We can't merge a plain objc_retain with an objc_retainBlock.
1498 if (RRI.IsRetainBlock != Other.RRI.IsRetainBlock)
1499 Seq = S_None;
1500
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001501 // If we're not in a sequence (anymore), drop all associated state.
John McCall9fbd3182011-06-15 23:37:01 +00001502 if (Seq == S_None) {
Dan Gohman50ade652012-04-25 00:50:46 +00001503 Partial = false;
John McCall9fbd3182011-06-15 23:37:01 +00001504 RRI.clear();
Dan Gohman50ade652012-04-25 00:50:46 +00001505 } else if (Partial || Other.Partial) {
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001506 // If we're doing a merge on a path that's previously seen a partial
1507 // merge, conservatively drop the sequence, to avoid doing partial
1508 // RR elimination. If the branch predicates for the two merge differ,
1509 // mixing them is unsafe.
Dan Gohman50ade652012-04-25 00:50:46 +00001510 ClearSequenceProgress();
John McCall9fbd3182011-06-15 23:37:01 +00001511 } else {
1512 // Conservatively merge the ReleaseMetadata information.
1513 if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
1514 RRI.ReleaseMetadata = 0;
1515
Dan Gohmane6d5e882011-08-19 00:26:36 +00001516 RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
Dan Gohman0daef3d2012-05-08 23:39:44 +00001517 RRI.IsTailCallRelease = RRI.IsTailCallRelease &&
1518 Other.RRI.IsTailCallRelease;
John McCall9fbd3182011-06-15 23:37:01 +00001519 RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001520
1521 // Merge the insert point sets. If there are any differences,
1522 // that makes this a partial merge.
Dan Gohman0daef3d2012-05-08 23:39:44 +00001523 Partial = RRI.ReverseInsertPts.size() != Other.RRI.ReverseInsertPts.size();
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001524 for (SmallPtrSet<Instruction *, 2>::const_iterator
1525 I = Other.RRI.ReverseInsertPts.begin(),
1526 E = Other.RRI.ReverseInsertPts.end(); I != E; ++I)
Dan Gohman50ade652012-04-25 00:50:46 +00001527 Partial |= RRI.ReverseInsertPts.insert(*I);
John McCall9fbd3182011-06-15 23:37:01 +00001528 }
1529}
1530
1531namespace {
1532 /// BBState - Per-BasicBlock state.
1533 class BBState {
1534 /// TopDownPathCount - The number of unique control paths from the entry
1535 /// which can reach this block.
1536 unsigned TopDownPathCount;
1537
1538 /// BottomUpPathCount - The number of unique control paths to exits
1539 /// from this block.
1540 unsigned BottomUpPathCount;
1541
1542 /// MapTy - A type for PerPtrTopDown and PerPtrBottomUp.
1543 typedef MapVector<const Value *, PtrState> MapTy;
1544
1545 /// PerPtrTopDown - The top-down traversal uses this to record information
1546 /// known about a pointer at the bottom of each block.
1547 MapTy PerPtrTopDown;
1548
1549 /// PerPtrBottomUp - The bottom-up traversal uses this to record information
1550 /// known about a pointer at the top of each block.
1551 MapTy PerPtrBottomUp;
1552
Dan Gohmaneeeb7752012-04-24 22:53:18 +00001553 /// Preds, Succs - Effective successors and predecessors of the current
1554 /// block (this ignores ignorable edges and ignored backedges).
1555 SmallVector<BasicBlock *, 2> Preds;
1556 SmallVector<BasicBlock *, 2> Succs;
1557
John McCall9fbd3182011-06-15 23:37:01 +00001558 public:
1559 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
1560
1561 typedef MapTy::iterator ptr_iterator;
1562 typedef MapTy::const_iterator ptr_const_iterator;
1563
1564 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
1565 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
1566 ptr_const_iterator top_down_ptr_begin() const {
1567 return PerPtrTopDown.begin();
1568 }
1569 ptr_const_iterator top_down_ptr_end() const {
1570 return PerPtrTopDown.end();
1571 }
1572
1573 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
1574 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
1575 ptr_const_iterator bottom_up_ptr_begin() const {
1576 return PerPtrBottomUp.begin();
1577 }
1578 ptr_const_iterator bottom_up_ptr_end() const {
1579 return PerPtrBottomUp.end();
1580 }
1581
1582 /// SetAsEntry - Mark this block as being an entry block, which has one
1583 /// path from the entry by definition.
1584 void SetAsEntry() { TopDownPathCount = 1; }
1585
1586 /// SetAsExit - Mark this block as being an exit block, which has one
1587 /// path to an exit by definition.
1588 void SetAsExit() { BottomUpPathCount = 1; }
1589
1590 PtrState &getPtrTopDownState(const Value *Arg) {
1591 return PerPtrTopDown[Arg];
1592 }
1593
1594 PtrState &getPtrBottomUpState(const Value *Arg) {
1595 return PerPtrBottomUp[Arg];
1596 }
1597
1598 void clearBottomUpPointers() {
Evan Chenga81388f2011-08-04 18:40:26 +00001599 PerPtrBottomUp.clear();
John McCall9fbd3182011-06-15 23:37:01 +00001600 }
1601
1602 void clearTopDownPointers() {
1603 PerPtrTopDown.clear();
1604 }
1605
1606 void InitFromPred(const BBState &Other);
1607 void InitFromSucc(const BBState &Other);
1608 void MergePred(const BBState &Other);
1609 void MergeSucc(const BBState &Other);
1610
1611 /// GetAllPathCount - Return the number of possible unique paths from an
1612 /// entry to an exit which pass through this block. This is only valid
1613 /// after both the top-down and bottom-up traversals are complete.
1614 unsigned GetAllPathCount() const {
Dan Gohmaneeeb7752012-04-24 22:53:18 +00001615 assert(TopDownPathCount != 0);
1616 assert(BottomUpPathCount != 0);
John McCall9fbd3182011-06-15 23:37:01 +00001617 return TopDownPathCount * BottomUpPathCount;
1618 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00001619
Dan Gohmaneeeb7752012-04-24 22:53:18 +00001620 // Specialized CFG utilities.
Dan Gohman447989c2012-04-27 18:56:31 +00001621 typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
Dan Gohmaneeeb7752012-04-24 22:53:18 +00001622 edge_iterator pred_begin() { return Preds.begin(); }
1623 edge_iterator pred_end() { return Preds.end(); }
1624 edge_iterator succ_begin() { return Succs.begin(); }
1625 edge_iterator succ_end() { return Succs.end(); }
1626
1627 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
1628 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
1629
1630 bool isExit() const { return Succs.empty(); }
John McCall9fbd3182011-06-15 23:37:01 +00001631 };
1632}
1633
1634void BBState::InitFromPred(const BBState &Other) {
1635 PerPtrTopDown = Other.PerPtrTopDown;
1636 TopDownPathCount = Other.TopDownPathCount;
1637}
1638
1639void BBState::InitFromSucc(const BBState &Other) {
1640 PerPtrBottomUp = Other.PerPtrBottomUp;
1641 BottomUpPathCount = Other.BottomUpPathCount;
1642}
1643
1644/// MergePred - The top-down traversal uses this to merge information about
1645/// predecessors to form the initial state for a new block.
1646void BBState::MergePred(const BBState &Other) {
1647 // Other.TopDownPathCount can be 0, in which case it is either dead or a
1648 // loop backedge. Loop backedges are special.
1649 TopDownPathCount += Other.TopDownPathCount;
1650
Dan Gohman0d1bc5f2012-09-12 20:45:17 +00001651 // Check for overflow. If we have overflow, fall back to conservative behavior.
1652 if (TopDownPathCount < Other.TopDownPathCount) {
1653 clearTopDownPointers();
1654 return;
1655 }
1656
John McCall9fbd3182011-06-15 23:37:01 +00001657 // For each entry in the other set, if our set has an entry with the same key,
1658 // merge the entries. Otherwise, copy the entry and merge it with an empty
1659 // entry.
1660 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
1661 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
1662 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
1663 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1664 /*TopDown=*/true);
1665 }
1666
Dan Gohmanfa7eed12011-08-11 21:06:32 +00001667 // For each entry in our set, if the other set doesn't have an entry with the
John McCall9fbd3182011-06-15 23:37:01 +00001668 // same key, force it to merge with an empty entry.
1669 for (ptr_iterator MI = top_down_ptr_begin(),
1670 ME = top_down_ptr_end(); MI != ME; ++MI)
1671 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
1672 MI->second.Merge(PtrState(), /*TopDown=*/true);
1673}
1674
1675/// MergeSucc - The bottom-up traversal uses this to merge information about
1676/// successors to form the initial state for a new block.
1677void BBState::MergeSucc(const BBState &Other) {
1678 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
1679 // loop backedge. Loop backedges are special.
1680 BottomUpPathCount += Other.BottomUpPathCount;
1681
Dan Gohman0d1bc5f2012-09-12 20:45:17 +00001682 // Check for overflow. If we have overflow, fall back to conservative behavior.
1683 if (BottomUpPathCount < Other.BottomUpPathCount) {
1684 clearBottomUpPointers();
1685 return;
1686 }
1687
John McCall9fbd3182011-06-15 23:37:01 +00001688 // For each entry in the other set, if our set has an entry with the
1689 // same key, merge the entries. Otherwise, copy the entry and merge
1690 // it with an empty entry.
1691 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
1692 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
1693 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
1694 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1695 /*TopDown=*/false);
1696 }
1697
Dan Gohmanfa7eed12011-08-11 21:06:32 +00001698 // For each entry in our set, if the other set doesn't have an entry
John McCall9fbd3182011-06-15 23:37:01 +00001699 // with the same key, force it to merge with an empty entry.
1700 for (ptr_iterator MI = bottom_up_ptr_begin(),
1701 ME = bottom_up_ptr_end(); MI != ME; ++MI)
1702 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
1703 MI->second.Merge(PtrState(), /*TopDown=*/false);
1704}
1705
1706namespace {
1707 /// ObjCARCOpt - The main ARC optimization pass.
1708 class ObjCARCOpt : public FunctionPass {
1709 bool Changed;
1710 ProvenanceAnalysis PA;
1711
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00001712 /// Run - A flag indicating whether this optimization pass should run.
1713 bool Run;
1714
John McCall9fbd3182011-06-15 23:37:01 +00001715 /// RetainRVCallee, etc. - Declarations for ObjC runtime
1716 /// functions, for use in creating calls to them. These are initialized
1717 /// lazily to avoid cluttering up the Module with unused declarations.
1718 Constant *RetainRVCallee, *AutoreleaseRVCallee, *ReleaseCallee,
Dan Gohman44280692011-07-22 22:29:21 +00001719 *RetainCallee, *RetainBlockCallee, *AutoreleaseCallee;
John McCall9fbd3182011-06-15 23:37:01 +00001720
1721 /// UsedInThisFunciton - Flags which determine whether each of the
1722 /// interesting runtine functions is in fact used in the current function.
1723 unsigned UsedInThisFunction;
1724
1725 /// ImpreciseReleaseMDKind - The Metadata Kind for clang.imprecise_release
1726 /// metadata.
1727 unsigned ImpreciseReleaseMDKind;
1728
Dan Gohman62e5b402011-12-12 18:20:00 +00001729 /// CopyOnEscapeMDKind - The Metadata Kind for clang.arc.copy_on_escape
Dan Gohmana974bea2011-10-17 22:53:25 +00001730 /// metadata.
1731 unsigned CopyOnEscapeMDKind;
1732
Dan Gohmandbe266b2012-02-17 18:59:53 +00001733 /// NoObjCARCExceptionsMDKind - The Metadata Kind for
1734 /// clang.arc.no_objc_arc_exceptions metadata.
1735 unsigned NoObjCARCExceptionsMDKind;
1736
John McCall9fbd3182011-06-15 23:37:01 +00001737 Constant *getRetainRVCallee(Module *M);
1738 Constant *getAutoreleaseRVCallee(Module *M);
1739 Constant *getReleaseCallee(Module *M);
1740 Constant *getRetainCallee(Module *M);
Dan Gohman44280692011-07-22 22:29:21 +00001741 Constant *getRetainBlockCallee(Module *M);
John McCall9fbd3182011-06-15 23:37:01 +00001742 Constant *getAutoreleaseCallee(Module *M);
1743
Dan Gohman79522dc2012-01-13 00:39:07 +00001744 bool IsRetainBlockOptimizable(const Instruction *Inst);
1745
John McCall9fbd3182011-06-15 23:37:01 +00001746 void OptimizeRetainCall(Function &F, Instruction *Retain);
1747 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
Michael Gottesman0e385452013-01-12 01:25:19 +00001748 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1749 InstructionClass &Class);
John McCall9fbd3182011-06-15 23:37:01 +00001750 void OptimizeIndividualCalls(Function &F);
1751
1752 void CheckForCFGHazards(const BasicBlock *BB,
1753 DenseMap<const BasicBlock *, BBState> &BBStates,
1754 BBState &MyStates) const;
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00001755 bool VisitInstructionBottomUp(Instruction *Inst,
Dan Gohmanfbab4a82012-03-23 17:47:54 +00001756 BasicBlock *BB,
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00001757 MapVector<Value *, RRInfo> &Retains,
1758 BBState &MyStates);
John McCall9fbd3182011-06-15 23:37:01 +00001759 bool VisitBottomUp(BasicBlock *BB,
1760 DenseMap<const BasicBlock *, BBState> &BBStates,
1761 MapVector<Value *, RRInfo> &Retains);
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00001762 bool VisitInstructionTopDown(Instruction *Inst,
1763 DenseMap<Value *, RRInfo> &Releases,
1764 BBState &MyStates);
John McCall9fbd3182011-06-15 23:37:01 +00001765 bool VisitTopDown(BasicBlock *BB,
1766 DenseMap<const BasicBlock *, BBState> &BBStates,
1767 DenseMap<Value *, RRInfo> &Releases);
1768 bool Visit(Function &F,
1769 DenseMap<const BasicBlock *, BBState> &BBStates,
1770 MapVector<Value *, RRInfo> &Retains,
1771 DenseMap<Value *, RRInfo> &Releases);
1772
1773 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1774 MapVector<Value *, RRInfo> &Retains,
1775 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman44280692011-07-22 22:29:21 +00001776 SmallVectorImpl<Instruction *> &DeadInsts,
1777 Module *M);
John McCall9fbd3182011-06-15 23:37:01 +00001778
1779 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1780 MapVector<Value *, RRInfo> &Retains,
Dan Gohman44280692011-07-22 22:29:21 +00001781 DenseMap<Value *, RRInfo> &Releases,
1782 Module *M);
John McCall9fbd3182011-06-15 23:37:01 +00001783
1784 void OptimizeWeakCalls(Function &F);
1785
1786 bool OptimizeSequences(Function &F);
1787
1788 void OptimizeReturns(Function &F);
1789
1790 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1791 virtual bool doInitialization(Module &M);
1792 virtual bool runOnFunction(Function &F);
1793 virtual void releaseMemory();
1794
1795 public:
1796 static char ID;
1797 ObjCARCOpt() : FunctionPass(ID) {
1798 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1799 }
1800 };
1801}
1802
1803char ObjCARCOpt::ID = 0;
1804INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1805 "objc-arc", "ObjC ARC optimization", false, false)
1806INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1807INITIALIZE_PASS_END(ObjCARCOpt,
1808 "objc-arc", "ObjC ARC optimization", false, false)
1809
1810Pass *llvm::createObjCARCOptPass() {
1811 return new ObjCARCOpt();
1812}
1813
1814void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1815 AU.addRequired<ObjCARCAliasAnalysis>();
1816 AU.addRequired<AliasAnalysis>();
1817 // ARC optimization doesn't currently split critical edges.
1818 AU.setPreservesCFG();
1819}
1820
Dan Gohman79522dc2012-01-13 00:39:07 +00001821bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1822 // Without the magic metadata tag, we have to assume this might be an
1823 // objc_retainBlock call inserted to convert a block pointer to an id,
1824 // in which case it really is needed.
1825 if (!Inst->getMetadata(CopyOnEscapeMDKind))
1826 return false;
1827
1828 // If the pointer "escapes" (not including being used in a call),
1829 // the copy may be needed.
1830 if (DoesObjCBlockEscape(Inst))
1831 return false;
1832
1833 // Otherwise, it's not needed.
1834 return true;
1835}
1836
John McCall9fbd3182011-06-15 23:37:01 +00001837Constant *ObjCARCOpt::getRetainRVCallee(Module *M) {
1838 if (!RetainRVCallee) {
1839 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001840 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman0daef3d2012-05-08 23:39:44 +00001841 Type *Params[] = { I8X };
1842 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
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 RetainRVCallee =
1847 M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy,
Bill Wendling034b94b2012-12-19 07:18:57 +00001848 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00001849 }
1850 return RetainRVCallee;
1851}
1852
1853Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1854 if (!AutoreleaseRVCallee) {
1855 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001856 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman0daef3d2012-05-08 23:39:44 +00001857 Type *Params[] = { I8X };
1858 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
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 AutoreleaseRVCallee =
1863 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
Bill Wendling034b94b2012-12-19 07:18:57 +00001864 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00001865 }
1866 return AutoreleaseRVCallee;
1867}
1868
1869Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1870 if (!ReleaseCallee) {
1871 LLVMContext &C = M->getContext();
Dan Gohman0daef3d2012-05-08 23:39:44 +00001872 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling034b94b2012-12-19 07:18:57 +00001873 AttributeSet Attribute =
Bill Wendling99faa3b2012-12-07 23:16:57 +00001874 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00001875 Attribute::get(C, Attribute::NoUnwind));
John McCall9fbd3182011-06-15 23:37:01 +00001876 ReleaseCallee =
1877 M->getOrInsertFunction(
1878 "objc_release",
1879 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
Bill Wendling034b94b2012-12-19 07:18:57 +00001880 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00001881 }
1882 return ReleaseCallee;
1883}
1884
1885Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1886 if (!RetainCallee) {
1887 LLVMContext &C = M->getContext();
Dan Gohman0daef3d2012-05-08 23:39:44 +00001888 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling034b94b2012-12-19 07:18:57 +00001889 AttributeSet Attribute =
Bill Wendling99faa3b2012-12-07 23:16:57 +00001890 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00001891 Attribute::get(C, Attribute::NoUnwind));
John McCall9fbd3182011-06-15 23:37:01 +00001892 RetainCallee =
1893 M->getOrInsertFunction(
1894 "objc_retain",
1895 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling034b94b2012-12-19 07:18:57 +00001896 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00001897 }
1898 return RetainCallee;
1899}
1900
Dan Gohman44280692011-07-22 22:29:21 +00001901Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1902 if (!RetainBlockCallee) {
1903 LLVMContext &C = M->getContext();
Dan Gohman0daef3d2012-05-08 23:39:44 +00001904 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Dan Gohman1d2fd752011-09-14 18:33:34 +00001905 // objc_retainBlock is not nounwind because it calls user copy constructors
1906 // which could theoretically throw.
Dan Gohman44280692011-07-22 22:29:21 +00001907 RetainBlockCallee =
1908 M->getOrInsertFunction(
1909 "objc_retainBlock",
1910 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling99faa3b2012-12-07 23:16:57 +00001911 AttributeSet());
Dan Gohman44280692011-07-22 22:29:21 +00001912 }
1913 return RetainBlockCallee;
1914}
1915
John McCall9fbd3182011-06-15 23:37:01 +00001916Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1917 if (!AutoreleaseCallee) {
1918 LLVMContext &C = M->getContext();
Dan Gohman0daef3d2012-05-08 23:39:44 +00001919 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling034b94b2012-12-19 07:18:57 +00001920 AttributeSet Attribute =
Bill Wendling99faa3b2012-12-07 23:16:57 +00001921 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00001922 Attribute::get(C, Attribute::NoUnwind));
John McCall9fbd3182011-06-15 23:37:01 +00001923 AutoreleaseCallee =
1924 M->getOrInsertFunction(
1925 "objc_autorelease",
1926 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling034b94b2012-12-19 07:18:57 +00001927 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00001928 }
1929 return AutoreleaseCallee;
1930}
1931
Dan Gohman230768b2012-09-04 23:16:20 +00001932/// IsPotentialUse - Test whether the given value is possible a
1933/// reference-counted pointer, including tests which utilize AliasAnalysis.
1934static bool IsPotentialUse(const Value *Op, AliasAnalysis &AA) {
1935 // First make the rudimentary check.
1936 if (!IsPotentialUse(Op))
1937 return false;
1938
1939 // Objects in constant memory are not reference-counted.
1940 if (AA.pointsToConstantMemory(Op))
1941 return false;
1942
1943 // Pointers in constant memory are not pointing to reference-counted objects.
1944 if (const LoadInst *LI = dyn_cast<LoadInst>(Op))
1945 if (AA.pointsToConstantMemory(LI->getPointerOperand()))
1946 return false;
1947
1948 // Otherwise assume the worst.
1949 return true;
1950}
1951
John McCall9fbd3182011-06-15 23:37:01 +00001952/// CanAlterRefCount - Test whether the given instruction can result in a
1953/// reference count modification (positive or negative) for the pointer's
1954/// object.
1955static bool
1956CanAlterRefCount(const Instruction *Inst, const Value *Ptr,
1957 ProvenanceAnalysis &PA, InstructionClass Class) {
1958 switch (Class) {
1959 case IC_Autorelease:
1960 case IC_AutoreleaseRV:
1961 case IC_User:
1962 // These operations never directly modify a reference count.
1963 return false;
1964 default: break;
1965 }
1966
1967 ImmutableCallSite CS = static_cast<const Value *>(Inst);
1968 assert(CS && "Only calls can alter reference counts!");
1969
1970 // See if AliasAnalysis can help us with the call.
1971 AliasAnalysis::ModRefBehavior MRB = PA.getAA()->getModRefBehavior(CS);
1972 if (AliasAnalysis::onlyReadsMemory(MRB))
1973 return false;
1974 if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
1975 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1976 I != E; ++I) {
1977 const Value *Op = *I;
Dan Gohman230768b2012-09-04 23:16:20 +00001978 if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
John McCall9fbd3182011-06-15 23:37:01 +00001979 return true;
1980 }
1981 return false;
1982 }
1983
1984 // Assume the worst.
1985 return true;
1986}
1987
1988/// CanUse - Test whether the given instruction can "use" the given pointer's
1989/// object in a way that requires the reference count to be positive.
1990static bool
1991CanUse(const Instruction *Inst, const Value *Ptr, ProvenanceAnalysis &PA,
1992 InstructionClass Class) {
1993 // IC_Call operations (as opposed to IC_CallOrUser) never "use" objc pointers.
1994 if (Class == IC_Call)
1995 return false;
1996
1997 // Consider various instructions which may have pointer arguments which are
1998 // not "uses".
1999 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(Inst)) {
2000 // Comparing a pointer with null, or any other constant, isn't really a use,
2001 // because we don't care what the pointer points to, or about the values
2002 // of any other dynamic reference-counted pointers.
Dan Gohman230768b2012-09-04 23:16:20 +00002003 if (!IsPotentialUse(ICI->getOperand(1), *PA.getAA()))
John McCall9fbd3182011-06-15 23:37:01 +00002004 return false;
2005 } else if (ImmutableCallSite CS = static_cast<const Value *>(Inst)) {
2006 // For calls, just check the arguments (and not the callee operand).
2007 for (ImmutableCallSite::arg_iterator OI = CS.arg_begin(),
2008 OE = CS.arg_end(); OI != OE; ++OI) {
2009 const Value *Op = *OI;
Dan Gohman230768b2012-09-04 23:16:20 +00002010 if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
John McCall9fbd3182011-06-15 23:37:01 +00002011 return true;
2012 }
2013 return false;
2014 } else if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
2015 // Special-case stores, because we don't care about the stored value, just
2016 // the store address.
2017 const Value *Op = GetUnderlyingObjCPtr(SI->getPointerOperand());
2018 // If we can't tell what the underlying object was, assume there is a
2019 // dependence.
Dan Gohman230768b2012-09-04 23:16:20 +00002020 return IsPotentialUse(Op, *PA.getAA()) && PA.related(Op, Ptr);
John McCall9fbd3182011-06-15 23:37:01 +00002021 }
2022
2023 // Check each operand for a match.
2024 for (User::const_op_iterator OI = Inst->op_begin(), OE = Inst->op_end();
2025 OI != OE; ++OI) {
2026 const Value *Op = *OI;
Dan Gohman230768b2012-09-04 23:16:20 +00002027 if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
John McCall9fbd3182011-06-15 23:37:01 +00002028 return true;
2029 }
2030 return false;
2031}
2032
2033/// CanInterruptRV - Test whether the given instruction can autorelease
2034/// any pointer or cause an autoreleasepool pop.
2035static bool
2036CanInterruptRV(InstructionClass Class) {
2037 switch (Class) {
2038 case IC_AutoreleasepoolPop:
2039 case IC_CallOrUser:
2040 case IC_Call:
2041 case IC_Autorelease:
2042 case IC_AutoreleaseRV:
2043 case IC_FusedRetainAutorelease:
2044 case IC_FusedRetainAutoreleaseRV:
2045 return true;
2046 default:
2047 return false;
2048 }
2049}
2050
2051namespace {
2052 /// DependenceKind - There are several kinds of dependence-like concepts in
2053 /// use here.
2054 enum DependenceKind {
2055 NeedsPositiveRetainCount,
Dan Gohman511568d2012-04-13 00:59:57 +00002056 AutoreleasePoolBoundary,
John McCall9fbd3182011-06-15 23:37:01 +00002057 CanChangeRetainCount,
2058 RetainAutoreleaseDep, ///< Blocks objc_retainAutorelease.
2059 RetainAutoreleaseRVDep, ///< Blocks objc_retainAutoreleaseReturnValue.
2060 RetainRVDep ///< Blocks objc_retainAutoreleasedReturnValue.
2061 };
2062}
2063
2064/// Depends - Test if there can be dependencies on Inst through Arg. This
2065/// function only tests dependencies relevant for removing pairs of calls.
2066static bool
2067Depends(DependenceKind Flavor, Instruction *Inst, const Value *Arg,
2068 ProvenanceAnalysis &PA) {
2069 // If we've reached the definition of Arg, stop.
2070 if (Inst == Arg)
2071 return true;
2072
2073 switch (Flavor) {
2074 case NeedsPositiveRetainCount: {
2075 InstructionClass Class = GetInstructionClass(Inst);
2076 switch (Class) {
2077 case IC_AutoreleasepoolPop:
2078 case IC_AutoreleasepoolPush:
2079 case IC_None:
2080 return false;
2081 default:
2082 return CanUse(Inst, Arg, PA, Class);
2083 }
2084 }
2085
Dan Gohman511568d2012-04-13 00:59:57 +00002086 case AutoreleasePoolBoundary: {
2087 InstructionClass Class = GetInstructionClass(Inst);
2088 switch (Class) {
2089 case IC_AutoreleasepoolPop:
2090 case IC_AutoreleasepoolPush:
2091 // These mark the end and begin of an autorelease pool scope.
2092 return true;
2093 default:
2094 // Nothing else does this.
2095 return false;
2096 }
2097 }
2098
John McCall9fbd3182011-06-15 23:37:01 +00002099 case CanChangeRetainCount: {
2100 InstructionClass Class = GetInstructionClass(Inst);
2101 switch (Class) {
2102 case IC_AutoreleasepoolPop:
2103 // Conservatively assume this can decrement any count.
2104 return true;
2105 case IC_AutoreleasepoolPush:
2106 case IC_None:
2107 return false;
2108 default:
2109 return CanAlterRefCount(Inst, Arg, PA, Class);
2110 }
2111 }
2112
2113 case RetainAutoreleaseDep:
2114 switch (GetBasicInstructionClass(Inst)) {
2115 case IC_AutoreleasepoolPop:
Dan Gohman511568d2012-04-13 00:59:57 +00002116 case IC_AutoreleasepoolPush:
John McCall9fbd3182011-06-15 23:37:01 +00002117 // Don't merge an objc_autorelease with an objc_retain inside a different
2118 // autoreleasepool scope.
2119 return true;
2120 case IC_Retain:
2121 case IC_RetainRV:
2122 // Check for a retain of the same pointer for merging.
2123 return GetObjCArg(Inst) == Arg;
2124 default:
2125 // Nothing else matters for objc_retainAutorelease formation.
2126 return false;
2127 }
John McCall9fbd3182011-06-15 23:37:01 +00002128
2129 case RetainAutoreleaseRVDep: {
2130 InstructionClass Class = GetBasicInstructionClass(Inst);
2131 switch (Class) {
2132 case IC_Retain:
2133 case IC_RetainRV:
2134 // Check for a retain of the same pointer for merging.
2135 return GetObjCArg(Inst) == Arg;
2136 default:
2137 // Anything that can autorelease interrupts
2138 // retainAutoreleaseReturnValue formation.
2139 return CanInterruptRV(Class);
2140 }
John McCall9fbd3182011-06-15 23:37:01 +00002141 }
2142
2143 case RetainRVDep:
2144 return CanInterruptRV(GetBasicInstructionClass(Inst));
2145 }
2146
2147 llvm_unreachable("Invalid dependence flavor");
John McCall9fbd3182011-06-15 23:37:01 +00002148}
2149
2150/// FindDependencies - Walk up the CFG from StartPos (which is in StartBB) and
2151/// find local and non-local dependencies on Arg.
2152/// TODO: Cache results?
2153static void
2154FindDependencies(DependenceKind Flavor,
2155 const Value *Arg,
2156 BasicBlock *StartBB, Instruction *StartInst,
2157 SmallPtrSet<Instruction *, 4> &DependingInstructions,
2158 SmallPtrSet<const BasicBlock *, 4> &Visited,
2159 ProvenanceAnalysis &PA) {
2160 BasicBlock::iterator StartPos = StartInst;
2161
2162 SmallVector<std::pair<BasicBlock *, BasicBlock::iterator>, 4> Worklist;
2163 Worklist.push_back(std::make_pair(StartBB, StartPos));
2164 do {
2165 std::pair<BasicBlock *, BasicBlock::iterator> Pair =
2166 Worklist.pop_back_val();
2167 BasicBlock *LocalStartBB = Pair.first;
2168 BasicBlock::iterator LocalStartPos = Pair.second;
2169 BasicBlock::iterator StartBBBegin = LocalStartBB->begin();
2170 for (;;) {
2171 if (LocalStartPos == StartBBBegin) {
2172 pred_iterator PI(LocalStartBB), PE(LocalStartBB, false);
2173 if (PI == PE)
2174 // If we've reached the function entry, produce a null dependence.
2175 DependingInstructions.insert(0);
2176 else
2177 // Add the predecessors to the worklist.
2178 do {
2179 BasicBlock *PredBB = *PI;
2180 if (Visited.insert(PredBB))
2181 Worklist.push_back(std::make_pair(PredBB, PredBB->end()));
2182 } while (++PI != PE);
2183 break;
2184 }
2185
2186 Instruction *Inst = --LocalStartPos;
2187 if (Depends(Flavor, Inst, Arg, PA)) {
2188 DependingInstructions.insert(Inst);
2189 break;
2190 }
2191 }
2192 } while (!Worklist.empty());
2193
2194 // Determine whether the original StartBB post-dominates all of the blocks we
2195 // visited. If not, insert a sentinal indicating that most optimizations are
2196 // not safe.
2197 for (SmallPtrSet<const BasicBlock *, 4>::const_iterator I = Visited.begin(),
2198 E = Visited.end(); I != E; ++I) {
2199 const BasicBlock *BB = *I;
2200 if (BB == StartBB)
2201 continue;
2202 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2203 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2204 const BasicBlock *Succ = *SI;
2205 if (Succ != StartBB && !Visited.count(Succ)) {
2206 DependingInstructions.insert(reinterpret_cast<Instruction *>(-1));
2207 return;
2208 }
2209 }
2210 }
2211}
2212
2213static bool isNullOrUndef(const Value *V) {
2214 return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
2215}
2216
2217static bool isNoopInstruction(const Instruction *I) {
2218 return isa<BitCastInst>(I) ||
2219 (isa<GetElementPtrInst>(I) &&
2220 cast<GetElementPtrInst>(I)->hasAllZeroIndices());
2221}
2222
2223/// OptimizeRetainCall - Turn objc_retain into
2224/// objc_retainAutoreleasedReturnValue if the operand is a return value.
2225void
2226ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) {
Dan Gohman447989c2012-04-27 18:56:31 +00002227 ImmutableCallSite CS(GetObjCArg(Retain));
2228 const Instruction *Call = CS.getInstruction();
John McCall9fbd3182011-06-15 23:37:01 +00002229 if (!Call) return;
2230 if (Call->getParent() != Retain->getParent()) return;
2231
2232 // Check that the call is next to the retain.
Dan Gohman447989c2012-04-27 18:56:31 +00002233 BasicBlock::const_iterator I = Call;
John McCall9fbd3182011-06-15 23:37:01 +00002234 ++I;
2235 while (isNoopInstruction(I)) ++I;
2236 if (&*I != Retain)
2237 return;
2238
2239 // Turn it to an objc_retainAutoreleasedReturnValue..
2240 Changed = true;
2241 ++NumPeeps;
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002242
Michael Gottesman715f6a62013-01-04 21:30:38 +00002243 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainCall: Transforming "
Michael Gottesmane7a715f2013-01-12 03:45:49 +00002244 "objc_retain => objc_retainAutoreleasedReturnValue"
2245 " since the operand is a return value.\n"
Michael Gottesman715f6a62013-01-04 21:30:38 +00002246 " Old: "
2247 << *Retain << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002248
John McCall9fbd3182011-06-15 23:37:01 +00002249 cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent()));
Michael Gottesman715f6a62013-01-04 21:30:38 +00002250
2251 DEBUG(dbgs() << " New: "
2252 << *Retain << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00002253}
2254
2255/// OptimizeRetainRVCall - Turn objc_retainAutoreleasedReturnValue into
Dan Gohman447989c2012-04-27 18:56:31 +00002256/// objc_retain if the operand is not a return value. Or, if it can be paired
2257/// with an objc_autoreleaseReturnValue, delete the pair and return true.
John McCall9fbd3182011-06-15 23:37:01 +00002258bool
2259ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
Dan Gohman6fedb3c2012-03-23 18:09:00 +00002260 // Check for the argument being from an immediately preceding call or invoke.
Dan Gohman447989c2012-04-27 18:56:31 +00002261 const Value *Arg = GetObjCArg(RetainRV);
2262 ImmutableCallSite CS(Arg);
2263 if (const Instruction *Call = CS.getInstruction()) {
John McCall9fbd3182011-06-15 23:37:01 +00002264 if (Call->getParent() == RetainRV->getParent()) {
Dan Gohman447989c2012-04-27 18:56:31 +00002265 BasicBlock::const_iterator I = Call;
John McCall9fbd3182011-06-15 23:37:01 +00002266 ++I;
2267 while (isNoopInstruction(I)) ++I;
2268 if (&*I == RetainRV)
2269 return false;
Dan Gohman447989c2012-04-27 18:56:31 +00002270 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Dan Gohman6fedb3c2012-03-23 18:09:00 +00002271 BasicBlock *RetainRVParent = RetainRV->getParent();
2272 if (II->getNormalDest() == RetainRVParent) {
Dan Gohman447989c2012-04-27 18:56:31 +00002273 BasicBlock::const_iterator I = RetainRVParent->begin();
Dan Gohman6fedb3c2012-03-23 18:09:00 +00002274 while (isNoopInstruction(I)) ++I;
2275 if (&*I == RetainRV)
2276 return false;
2277 }
John McCall9fbd3182011-06-15 23:37:01 +00002278 }
Dan Gohman6fedb3c2012-03-23 18:09:00 +00002279 }
John McCall9fbd3182011-06-15 23:37:01 +00002280
2281 // Check for being preceded by an objc_autoreleaseReturnValue on the same
2282 // pointer. In this case, we can delete the pair.
2283 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
2284 if (I != Begin) {
2285 do --I; while (I != Begin && isNoopInstruction(I));
2286 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
2287 GetObjCArg(I) == Arg) {
2288 Changed = true;
2289 ++NumPeeps;
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002290
Michael Gottesman87a0f022013-01-05 17:55:35 +00002291 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainRVCall: Erasing " << *I << "\n"
2292 << " Erasing " << *RetainRV
2293 << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002294
John McCall9fbd3182011-06-15 23:37:01 +00002295 EraseInstruction(I);
2296 EraseInstruction(RetainRV);
2297 return true;
2298 }
2299 }
2300
2301 // Turn it to a plain objc_retain.
2302 Changed = true;
2303 ++NumPeeps;
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002304
Michael Gottesman36e4bc42013-01-05 17:55:42 +00002305 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainRVCall: Transforming "
2306 "objc_retainAutoreleasedReturnValue => "
2307 "objc_retain since the operand is not a return value.\n"
2308 " Old: "
2309 << *RetainRV << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002310
John McCall9fbd3182011-06-15 23:37:01 +00002311 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
Michael Gottesman36e4bc42013-01-05 17:55:42 +00002312
2313 DEBUG(dbgs() << " New: "
2314 << *RetainRV << "\n");
2315
John McCall9fbd3182011-06-15 23:37:01 +00002316 return false;
2317}
2318
2319/// OptimizeAutoreleaseRVCall - Turn objc_autoreleaseReturnValue into
2320/// objc_autorelease if the result is not used as a return value.
2321void
Michael Gottesman0e385452013-01-12 01:25:19 +00002322ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
2323 InstructionClass &Class) {
John McCall9fbd3182011-06-15 23:37:01 +00002324 // Check for a return of the pointer value.
2325 const Value *Ptr = GetObjCArg(AutoreleaseRV);
Dan Gohman126a54f2011-08-12 00:36:31 +00002326 SmallVector<const Value *, 2> Users;
2327 Users.push_back(Ptr);
2328 do {
2329 Ptr = Users.pop_back_val();
2330 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
2331 UI != UE; ++UI) {
2332 const User *I = *UI;
2333 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
2334 return;
2335 if (isa<BitCastInst>(I))
2336 Users.push_back(I);
2337 }
2338 } while (!Users.empty());
John McCall9fbd3182011-06-15 23:37:01 +00002339
2340 Changed = true;
2341 ++NumPeeps;
Michael Gottesman48239c72013-01-06 21:07:11 +00002342
2343 DEBUG(dbgs() << "ObjCARCOpt::OptimizeAutoreleaseRVCall: Transforming "
2344 "objc_autoreleaseReturnValue => "
2345 "objc_autorelease since its operand is not used as a return "
2346 "value.\n"
2347 " Old: "
2348 << *AutoreleaseRV << "\n");
2349
Michael Gottesmane8c161a2013-01-12 01:25:15 +00002350 CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
2351 AutoreleaseRVCI->
John McCall9fbd3182011-06-15 23:37:01 +00002352 setCalledFunction(getAutoreleaseCallee(F.getParent()));
Michael Gottesmane8c161a2013-01-12 01:25:15 +00002353 AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
Michael Gottesman0e385452013-01-12 01:25:19 +00002354 Class = IC_Autorelease;
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002355
Michael Gottesman48239c72013-01-06 21:07:11 +00002356 DEBUG(dbgs() << " New: "
2357 << *AutoreleaseRV << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002358
John McCall9fbd3182011-06-15 23:37:01 +00002359}
2360
2361/// OptimizeIndividualCalls - Visit each call, one at a time, and make
2362/// simplifications without doing any additional analysis.
2363void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
2364 // Reset all the flags in preparation for recomputing them.
2365 UsedInThisFunction = 0;
2366
2367 // Visit all objc_* calls in F.
2368 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2369 Instruction *Inst = &*I++;
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00002370
Michael Gottesman5c0ae472013-01-04 21:29:57 +00002371 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Visiting: " <<
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00002372 *Inst << "\n");
2373
John McCall9fbd3182011-06-15 23:37:01 +00002374 InstructionClass Class = GetBasicInstructionClass(Inst);
2375
2376 switch (Class) {
2377 default: break;
2378
2379 // Delete no-op casts. These function calls have special semantics, but
2380 // the semantics are entirely implemented via lowering in the front-end,
2381 // so by the time they reach the optimizer, they are just no-op calls
2382 // which return their argument.
2383 //
2384 // There are gray areas here, as the ability to cast reference-counted
2385 // pointers to raw void* and back allows code to break ARC assumptions,
2386 // however these are currently considered to be unimportant.
2387 case IC_NoopCast:
2388 Changed = true;
2389 ++NumNoops;
Michael Gottesman4680abe2013-01-06 21:07:15 +00002390 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Erasing no-op cast:"
2391 " " << *Inst << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00002392 EraseInstruction(Inst);
2393 continue;
2394
2395 // If the pointer-to-weak-pointer is null, it's undefined behavior.
2396 case IC_StoreWeak:
2397 case IC_LoadWeak:
2398 case IC_LoadWeakRetained:
2399 case IC_InitWeak:
2400 case IC_DestroyWeak: {
2401 CallInst *CI = cast<CallInst>(Inst);
2402 if (isNullOrUndef(CI->getArgOperand(0))) {
Dan Gohmand6bf2012012-04-13 18:57:48 +00002403 Changed = true;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002404 Type *Ty = CI->getArgOperand(0)->getType();
John McCall9fbd3182011-06-15 23:37:01 +00002405 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2406 Constant::getNullValue(Ty),
2407 CI);
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002408 llvm::Value *NewValue = UndefValue::get(CI->getType());
Michael Gottesmane5494922013-01-06 21:54:30 +00002409 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: A null "
2410 "pointer-to-weak-pointer is undefined behavior.\n"
2411 " Old = " << *CI <<
2412 "\n New = " <<
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002413 *NewValue << "\n");
Michael Gottesmane5494922013-01-06 21:54:30 +00002414 CI->replaceAllUsesWith(NewValue);
John McCall9fbd3182011-06-15 23:37:01 +00002415 CI->eraseFromParent();
2416 continue;
2417 }
2418 break;
2419 }
2420 case IC_CopyWeak:
2421 case IC_MoveWeak: {
2422 CallInst *CI = cast<CallInst>(Inst);
2423 if (isNullOrUndef(CI->getArgOperand(0)) ||
2424 isNullOrUndef(CI->getArgOperand(1))) {
Dan Gohmand6bf2012012-04-13 18:57:48 +00002425 Changed = true;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002426 Type *Ty = CI->getArgOperand(0)->getType();
John McCall9fbd3182011-06-15 23:37:01 +00002427 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2428 Constant::getNullValue(Ty),
2429 CI);
Michael Gottesmane5494922013-01-06 21:54:30 +00002430
2431 llvm::Value *NewValue = UndefValue::get(CI->getType());
2432 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: A null "
2433 "pointer-to-weak-pointer is undefined behavior.\n"
2434 " Old = " << *CI <<
2435 "\n New = " <<
2436 *NewValue << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002437
Michael Gottesmane5494922013-01-06 21:54:30 +00002438 CI->replaceAllUsesWith(NewValue);
John McCall9fbd3182011-06-15 23:37:01 +00002439 CI->eraseFromParent();
2440 continue;
2441 }
2442 break;
2443 }
2444 case IC_Retain:
2445 OptimizeRetainCall(F, Inst);
2446 break;
2447 case IC_RetainRV:
2448 if (OptimizeRetainRVCall(F, Inst))
2449 continue;
2450 break;
2451 case IC_AutoreleaseRV:
Michael Gottesman0e385452013-01-12 01:25:19 +00002452 OptimizeAutoreleaseRVCall(F, Inst, Class);
John McCall9fbd3182011-06-15 23:37:01 +00002453 break;
2454 }
2455
2456 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
2457 if (IsAutorelease(Class) && Inst->use_empty()) {
2458 CallInst *Call = cast<CallInst>(Inst);
2459 const Value *Arg = Call->getArgOperand(0);
2460 Arg = FindSingleUseIdentifiedObject(Arg);
2461 if (Arg) {
2462 Changed = true;
2463 ++NumAutoreleases;
2464
2465 // Create the declaration lazily.
2466 LLVMContext &C = Inst->getContext();
2467 CallInst *NewCall =
2468 CallInst::Create(getReleaseCallee(F.getParent()),
2469 Call->getArgOperand(0), "", Call);
2470 NewCall->setMetadata(ImpreciseReleaseMDKind,
2471 MDNode::get(C, ArrayRef<Value *>()));
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002472
Michael Gottesman20d9fff2013-01-06 22:56:50 +00002473 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Replacing "
2474 "objc_autorelease(x) with objc_release(x) since x is "
2475 "otherwise unused.\n"
Michael Gottesman79561272013-01-06 22:56:54 +00002476 " Old: " << *Call <<
Michael Gottesman20d9fff2013-01-06 22:56:50 +00002477 "\n New: " <<
2478 *NewCall << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002479
John McCall9fbd3182011-06-15 23:37:01 +00002480 EraseInstruction(Call);
2481 Inst = NewCall;
2482 Class = IC_Release;
2483 }
2484 }
2485
2486 // For functions which can never be passed stack arguments, add
2487 // a tail keyword.
2488 if (IsAlwaysTail(Class)) {
2489 Changed = true;
Michael Gottesman817d4e92013-01-06 23:39:09 +00002490 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Adding tail keyword"
2491 " to function since it can never be passed stack args: " << *Inst <<
2492 "\n");
John McCall9fbd3182011-06-15 23:37:01 +00002493 cast<CallInst>(Inst)->setTailCall();
2494 }
2495
Michael Gottesmane8c161a2013-01-12 01:25:15 +00002496 // Ensure that functions that can never have a "tail" keyword due to the
2497 // semantics of ARC truly do not do so.
2498 if (IsNeverTail(Class)) {
2499 Changed = true;
2500 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Removing tail keyword"
2501 " from function: " << *Inst <<
2502 "\n");
2503 cast<CallInst>(Inst)->setTailCall(false);
2504 }
2505
John McCall9fbd3182011-06-15 23:37:01 +00002506 // Set nounwind as needed.
2507 if (IsNoThrow(Class)) {
2508 Changed = true;
Michael Gottesman38bc25a2013-01-06 23:39:13 +00002509 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Found no throw"
2510 " class. Setting nounwind on: " << *Inst << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00002511 cast<CallInst>(Inst)->setDoesNotThrow();
2512 }
2513
2514 if (!IsNoopOnNull(Class)) {
2515 UsedInThisFunction |= 1 << Class;
2516 continue;
2517 }
2518
2519 const Value *Arg = GetObjCArg(Inst);
2520
2521 // ARC calls with null are no-ops. Delete them.
2522 if (isNullOrUndef(Arg)) {
2523 Changed = true;
2524 ++NumNoops;
Michael Gottesmanfbe4d6b2013-01-07 00:04:52 +00002525 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: ARC calls with "
2526 " null are no-ops. Erasing: " << *Inst << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00002527 EraseInstruction(Inst);
2528 continue;
2529 }
2530
2531 // Keep track of which of retain, release, autorelease, and retain_block
2532 // are actually present in this function.
2533 UsedInThisFunction |= 1 << Class;
2534
2535 // If Arg is a PHI, and one or more incoming values to the
2536 // PHI are null, and the call is control-equivalent to the PHI, and there
2537 // are no relevant side effects between the PHI and the call, the call
2538 // could be pushed up to just those paths with non-null incoming values.
2539 // For now, don't bother splitting critical edges for this.
2540 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
2541 Worklist.push_back(std::make_pair(Inst, Arg));
2542 do {
2543 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
2544 Inst = Pair.first;
2545 Arg = Pair.second;
2546
2547 const PHINode *PN = dyn_cast<PHINode>(Arg);
2548 if (!PN) continue;
2549
2550 // Determine if the PHI has any null operands, or any incoming
2551 // critical edges.
2552 bool HasNull = false;
2553 bool HasCriticalEdges = false;
2554 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2555 Value *Incoming =
2556 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2557 if (isNullOrUndef(Incoming))
2558 HasNull = true;
2559 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
2560 .getNumSuccessors() != 1) {
2561 HasCriticalEdges = true;
2562 break;
2563 }
2564 }
2565 // If we have null operands and no critical edges, optimize.
2566 if (!HasCriticalEdges && HasNull) {
2567 SmallPtrSet<Instruction *, 4> DependingInstructions;
2568 SmallPtrSet<const BasicBlock *, 4> Visited;
2569
2570 // Check that there is nothing that cares about the reference
2571 // count between the call and the phi.
Dan Gohman511568d2012-04-13 00:59:57 +00002572 switch (Class) {
2573 case IC_Retain:
2574 case IC_RetainBlock:
2575 // These can always be moved up.
2576 break;
2577 case IC_Release:
Dan Gohman0daef3d2012-05-08 23:39:44 +00002578 // These can't be moved across things that care about the retain
2579 // count.
Dan Gohman511568d2012-04-13 00:59:57 +00002580 FindDependencies(NeedsPositiveRetainCount, Arg,
2581 Inst->getParent(), Inst,
2582 DependingInstructions, Visited, PA);
2583 break;
2584 case IC_Autorelease:
2585 // These can't be moved across autorelease pool scope boundaries.
2586 FindDependencies(AutoreleasePoolBoundary, Arg,
2587 Inst->getParent(), Inst,
2588 DependingInstructions, Visited, PA);
2589 break;
2590 case IC_RetainRV:
2591 case IC_AutoreleaseRV:
2592 // Don't move these; the RV optimization depends on the autoreleaseRV
2593 // being tail called, and the retainRV being immediately after a call
2594 // (which might still happen if we get lucky with codegen layout, but
2595 // it's not worth taking the chance).
2596 continue;
2597 default:
2598 llvm_unreachable("Invalid dependence flavor");
2599 }
2600
John McCall9fbd3182011-06-15 23:37:01 +00002601 if (DependingInstructions.size() == 1 &&
2602 *DependingInstructions.begin() == PN) {
2603 Changed = true;
2604 ++NumPartialNoops;
2605 // Clone the call into each predecessor that has a non-null value.
2606 CallInst *CInst = cast<CallInst>(Inst);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002607 Type *ParamTy = CInst->getArgOperand(0)->getType();
John McCall9fbd3182011-06-15 23:37:01 +00002608 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2609 Value *Incoming =
2610 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2611 if (!isNullOrUndef(Incoming)) {
2612 CallInst *Clone = cast<CallInst>(CInst->clone());
2613 Value *Op = PN->getIncomingValue(i);
2614 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
2615 if (Op->getType() != ParamTy)
2616 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
2617 Clone->setArgOperand(0, Op);
2618 Clone->insertBefore(InsertPos);
Michael Gottesman55811152013-01-09 19:23:24 +00002619
2620 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Cloning "
2621 << *CInst << "\n"
2622 " And inserting "
2623 "clone at " << *InsertPos << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00002624 Worklist.push_back(std::make_pair(Clone, Incoming));
2625 }
2626 }
2627 // Erase the original call.
Michael Gottesman55811152013-01-09 19:23:24 +00002628 DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00002629 EraseInstruction(CInst);
2630 continue;
2631 }
2632 }
2633 } while (!Worklist.empty());
2634 }
Michael Gottesman0d3582b2013-01-12 02:57:16 +00002635 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Finished List.\n");
John McCall9fbd3182011-06-15 23:37:01 +00002636}
2637
2638/// CheckForCFGHazards - Check for critical edges, loop boundaries, irreducible
2639/// control flow, or other CFG structures where moving code across the edge
2640/// would result in it being executed more.
2641void
2642ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
2643 DenseMap<const BasicBlock *, BBState> &BBStates,
2644 BBState &MyStates) const {
2645 // If any top-down local-use or possible-dec has a succ which is earlier in
2646 // the sequence, forget it.
Dan Gohman22cc4cc2012-03-02 01:13:53 +00002647 for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
John McCall9fbd3182011-06-15 23:37:01 +00002648 E = MyStates.top_down_ptr_end(); I != E; ++I)
2649 switch (I->second.GetSeq()) {
2650 default: break;
2651 case S_Use: {
2652 const Value *Arg = I->first;
2653 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2654 bool SomeSuccHasSame = false;
2655 bool AllSuccsHaveSame = true;
Dan Gohman22cc4cc2012-03-02 01:13:53 +00002656 PtrState &S = I->second;
Dan Gohmandbe266b2012-02-17 18:59:53 +00002657 succ_const_iterator SI(TI), SE(TI, false);
2658
2659 // If the terminator is an invoke marked with the
2660 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
2661 // ignored, for ARC purposes.
Michael Gottesmancf140052013-01-13 07:00:51 +00002662 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind)) {
2663 DEBUG(dbgs() << "ObjCARCOpt::CheckForCFGHazards: Found an invoke "
2664 "terminator marked with "
2665 "clang.arc.no_objc_arc_exceptions. Ignoring unwind "
2666 "edge.\n");
Dan Gohmandbe266b2012-02-17 18:59:53 +00002667 --SE;
Michael Gottesmancf140052013-01-13 07:00:51 +00002668 }
Dan Gohmandbe266b2012-02-17 18:59:53 +00002669
2670 for (; SI != SE; ++SI) {
Dan Gohman70e29682012-03-02 01:26:46 +00002671 Sequence SuccSSeq = S_None;
2672 bool SuccSRRIKnownSafe = false;
Dan Gohman0daef3d2012-05-08 23:39:44 +00002673 // If VisitBottomUp has pointer information for this successor, take
2674 // what we know about it.
Dan Gohman447989c2012-04-27 18:56:31 +00002675 DenseMap<const BasicBlock *, BBState>::iterator BBI =
2676 BBStates.find(*SI);
2677 assert(BBI != BBStates.end());
2678 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2679 SuccSSeq = SuccS.GetSeq();
2680 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
Dan Gohman70e29682012-03-02 01:26:46 +00002681 switch (SuccSSeq) {
John McCall9fbd3182011-06-15 23:37:01 +00002682 case S_None:
Dan Gohmana7f7db22011-08-12 00:26:31 +00002683 case S_CanRelease: {
Dan Gohman70e29682012-03-02 01:26:46 +00002684 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
Dan Gohmana7f7db22011-08-12 00:26:31 +00002685 S.ClearSequenceProgress();
Dan Gohman70e29682012-03-02 01:26:46 +00002686 break;
2687 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002688 continue;
2689 }
John McCall9fbd3182011-06-15 23:37:01 +00002690 case S_Use:
2691 SomeSuccHasSame = true;
2692 break;
2693 case S_Stop:
2694 case S_Release:
2695 case S_MovableRelease:
Dan Gohman70e29682012-03-02 01:26:46 +00002696 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002697 AllSuccsHaveSame = false;
John McCall9fbd3182011-06-15 23:37:01 +00002698 break;
2699 case S_Retain:
2700 llvm_unreachable("bottom-up pointer in retain state!");
2701 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002702 }
John McCall9fbd3182011-06-15 23:37:01 +00002703 // If the state at the other end of any of the successor edges
2704 // matches the current state, require all edges to match. This
2705 // guards against loops in the middle of a sequence.
2706 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002707 S.ClearSequenceProgress();
Dan Gohman2e68beb2011-12-12 18:13:53 +00002708 break;
John McCall9fbd3182011-06-15 23:37:01 +00002709 }
2710 case S_CanRelease: {
2711 const Value *Arg = I->first;
2712 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2713 bool SomeSuccHasSame = false;
2714 bool AllSuccsHaveSame = true;
Dan Gohman22cc4cc2012-03-02 01:13:53 +00002715 PtrState &S = I->second;
Dan Gohmandbe266b2012-02-17 18:59:53 +00002716 succ_const_iterator SI(TI), SE(TI, false);
2717
2718 // If the terminator is an invoke marked with the
2719 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
2720 // ignored, for ARC purposes.
Michael Gottesmancf140052013-01-13 07:00:51 +00002721 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind)) {
2722 DEBUG(dbgs() << "ObjCARCOpt::CheckForCFGHazards: Found an invoke "
2723 "terminator marked with "
2724 "clang.arc.no_objc_arc_exceptions. Ignoring unwind "
2725 "edge.\n");
Dan Gohmandbe266b2012-02-17 18:59:53 +00002726 --SE;
Michael Gottesmancf140052013-01-13 07:00:51 +00002727 }
Dan Gohmandbe266b2012-02-17 18:59:53 +00002728
2729 for (; SI != SE; ++SI) {
Dan Gohman70e29682012-03-02 01:26:46 +00002730 Sequence SuccSSeq = S_None;
2731 bool SuccSRRIKnownSafe = false;
Dan Gohman0daef3d2012-05-08 23:39:44 +00002732 // If VisitBottomUp has pointer information for this successor, take
2733 // what we know about it.
Dan Gohman447989c2012-04-27 18:56:31 +00002734 DenseMap<const BasicBlock *, BBState>::iterator BBI =
2735 BBStates.find(*SI);
2736 assert(BBI != BBStates.end());
2737 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2738 SuccSSeq = SuccS.GetSeq();
2739 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
Dan Gohman70e29682012-03-02 01:26:46 +00002740 switch (SuccSSeq) {
Dan Gohmana7f7db22011-08-12 00:26:31 +00002741 case S_None: {
Dan Gohman70e29682012-03-02 01:26:46 +00002742 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
Dan Gohmana7f7db22011-08-12 00:26:31 +00002743 S.ClearSequenceProgress();
Dan Gohman70e29682012-03-02 01:26:46 +00002744 break;
2745 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002746 continue;
2747 }
John McCall9fbd3182011-06-15 23:37:01 +00002748 case S_CanRelease:
2749 SomeSuccHasSame = true;
2750 break;
2751 case S_Stop:
2752 case S_Release:
2753 case S_MovableRelease:
2754 case S_Use:
Dan Gohman70e29682012-03-02 01:26:46 +00002755 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002756 AllSuccsHaveSame = false;
John McCall9fbd3182011-06-15 23:37:01 +00002757 break;
2758 case S_Retain:
2759 llvm_unreachable("bottom-up pointer in retain state!");
2760 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002761 }
John McCall9fbd3182011-06-15 23:37:01 +00002762 // If the state at the other end of any of the successor edges
2763 // matches the current state, require all edges to match. This
2764 // guards against loops in the middle of a sequence.
2765 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002766 S.ClearSequenceProgress();
Dan Gohman2e68beb2011-12-12 18:13:53 +00002767 break;
John McCall9fbd3182011-06-15 23:37:01 +00002768 }
2769 }
2770}
2771
2772bool
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002773ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002774 BasicBlock *BB,
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002775 MapVector<Value *, RRInfo> &Retains,
2776 BBState &MyStates) {
2777 bool NestingDetected = false;
2778 InstructionClass Class = GetInstructionClass(Inst);
2779 const Value *Arg = 0;
2780
2781 switch (Class) {
2782 case IC_Release: {
2783 Arg = GetObjCArg(Inst);
2784
2785 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2786
2787 // If we see two releases in a row on the same pointer. If so, make
2788 // a note, and we'll cicle back to revisit it after we've
2789 // hopefully eliminated the second release, which may allow us to
2790 // eliminate the first release too.
2791 // Theoretically we could implement removal of nested retain+release
2792 // pairs by making PtrState hold a stack of states, but this is
2793 // simple and avoids adding overhead for the non-nested case.
Michael Gottesmancf140052013-01-13 07:00:51 +00002794 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease) {
2795 DEBUG(dbgs() << "ObjCARCOpt::VisitInstructionBottomUp: Found nested "
2796 "releases (i.e. a release pair)\n");
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002797 NestingDetected = true;
Michael Gottesmancf140052013-01-13 07:00:51 +00002798 }
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002799
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002800 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
Dan Gohman50ade652012-04-25 00:50:46 +00002801 S.ResetSequenceProgress(ReleaseMetadata ? S_MovableRelease : S_Release);
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002802 S.RRI.ReleaseMetadata = ReleaseMetadata;
Dan Gohman230768b2012-09-04 23:16:20 +00002803 S.RRI.KnownSafe = S.IsKnownIncremented();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002804 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2805 S.RRI.Calls.insert(Inst);
2806
Dan Gohman230768b2012-09-04 23:16:20 +00002807 S.SetKnownPositiveRefCount();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002808 break;
2809 }
2810 case IC_RetainBlock:
2811 // An objc_retainBlock call with just a use may need to be kept,
2812 // because it may be copying a block from the stack to the heap.
2813 if (!IsRetainBlockOptimizable(Inst))
2814 break;
2815 // FALLTHROUGH
2816 case IC_Retain:
2817 case IC_RetainRV: {
2818 Arg = GetObjCArg(Inst);
2819
2820 PtrState &S = MyStates.getPtrBottomUpState(Arg);
Dan Gohman50ade652012-04-25 00:50:46 +00002821 S.SetKnownPositiveRefCount();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002822
2823 switch (S.GetSeq()) {
2824 case S_Stop:
2825 case S_Release:
2826 case S_MovableRelease:
2827 case S_Use:
2828 S.RRI.ReverseInsertPts.clear();
2829 // FALL THROUGH
2830 case S_CanRelease:
2831 // Don't do retain+release tracking for IC_RetainRV, because it's
2832 // better to let it remain as the first instruction after a call.
2833 if (Class != IC_RetainRV) {
2834 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2835 Retains[Inst] = S.RRI;
2836 }
2837 S.ClearSequenceProgress();
2838 break;
2839 case S_None:
2840 break;
2841 case S_Retain:
2842 llvm_unreachable("bottom-up pointer in retain state!");
2843 }
2844 return NestingDetected;
2845 }
2846 case IC_AutoreleasepoolPop:
2847 // Conservatively, clear MyStates for all known pointers.
2848 MyStates.clearBottomUpPointers();
2849 return NestingDetected;
2850 case IC_AutoreleasepoolPush:
2851 case IC_None:
2852 // These are irrelevant.
2853 return NestingDetected;
2854 default:
2855 break;
2856 }
2857
2858 // Consider any other possible effects of this instruction on each
2859 // pointer being tracked.
2860 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
2861 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
2862 const Value *Ptr = MI->first;
2863 if (Ptr == Arg)
2864 continue; // Handled above.
2865 PtrState &S = MI->second;
2866 Sequence Seq = S.GetSeq();
2867
2868 // Check for possible releases.
2869 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Dan Gohman50ade652012-04-25 00:50:46 +00002870 S.ClearRefCount();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002871 switch (Seq) {
2872 case S_Use:
2873 S.SetSeq(S_CanRelease);
2874 continue;
2875 case S_CanRelease:
2876 case S_Release:
2877 case S_MovableRelease:
2878 case S_Stop:
2879 case S_None:
2880 break;
2881 case S_Retain:
2882 llvm_unreachable("bottom-up pointer in retain state!");
2883 }
2884 }
2885
2886 // Check for possible direct uses.
2887 switch (Seq) {
2888 case S_Release:
2889 case S_MovableRelease:
2890 if (CanUse(Inst, Ptr, PA, Class)) {
2891 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002892 // If this is an invoke instruction, we're scanning it as part of
2893 // one of its successor blocks, since we can't insert code after it
2894 // in its own block, and we don't want to split critical edges.
2895 if (isa<InvokeInst>(Inst))
2896 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2897 else
Francois Pichetb54a5ed2012-03-24 01:36:37 +00002898 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002899 S.SetSeq(S_Use);
2900 } else if (Seq == S_Release &&
2901 (Class == IC_User || Class == IC_CallOrUser)) {
2902 // Non-movable releases depend on any possible objc pointer use.
2903 S.SetSeq(S_Stop);
2904 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002905 // As above; handle invoke specially.
2906 if (isa<InvokeInst>(Inst))
2907 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2908 else
Francois Pichetb54a5ed2012-03-24 01:36:37 +00002909 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002910 }
2911 break;
2912 case S_Stop:
2913 if (CanUse(Inst, Ptr, PA, Class))
2914 S.SetSeq(S_Use);
2915 break;
2916 case S_CanRelease:
2917 case S_Use:
2918 case S_None:
2919 break;
2920 case S_Retain:
2921 llvm_unreachable("bottom-up pointer in retain state!");
2922 }
2923 }
2924
2925 return NestingDetected;
2926}
2927
2928bool
John McCall9fbd3182011-06-15 23:37:01 +00002929ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2930 DenseMap<const BasicBlock *, BBState> &BBStates,
2931 MapVector<Value *, RRInfo> &Retains) {
2932 bool NestingDetected = false;
2933 BBState &MyStates = BBStates[BB];
2934
2935 // Merge the states from each successor to compute the initial state
2936 // for the current block.
Dan Gohman40e46602012-08-27 18:31:36 +00002937 BBState::edge_iterator SI(MyStates.succ_begin()),
2938 SE(MyStates.succ_end());
2939 if (SI != SE) {
Dan Gohmaneeeb7752012-04-24 22:53:18 +00002940 const BasicBlock *Succ = *SI;
2941 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
2942 assert(I != BBStates.end());
2943 MyStates.InitFromSucc(I->second);
2944 ++SI;
2945 for (; SI != SE; ++SI) {
2946 Succ = *SI;
2947 I = BBStates.find(Succ);
2948 assert(I != BBStates.end());
2949 MyStates.MergeSucc(I->second);
2950 }
Dan Gohmandbe266b2012-02-17 18:59:53 +00002951 }
John McCall9fbd3182011-06-15 23:37:01 +00002952
2953 // Visit all the instructions, bottom-up.
2954 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2955 Instruction *Inst = llvm::prior(I);
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002956
2957 // Invoke instructions are visited as part of their successors (below).
2958 if (isa<InvokeInst>(Inst))
2959 continue;
2960
Michael Gottesmancf140052013-01-13 07:00:51 +00002961 DEBUG(dbgs() << "ObjCARCOpt::VisitButtonUp: Visiting " << *Inst << "\n");
2962
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002963 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
2964 }
2965
Dan Gohman447989c2012-04-27 18:56:31 +00002966 // If there's a predecessor with an invoke, visit the invoke as if it were
2967 // part of this block, since we can't insert code after an invoke in its own
2968 // block, and we don't want to split critical edges.
Dan Gohmaneeeb7752012-04-24 22:53:18 +00002969 for (BBState::edge_iterator PI(MyStates.pred_begin()),
2970 PE(MyStates.pred_end()); PI != PE; ++PI) {
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002971 BasicBlock *Pred = *PI;
Dan Gohman447989c2012-04-27 18:56:31 +00002972 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
2973 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002974 }
John McCall9fbd3182011-06-15 23:37:01 +00002975
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002976 return NestingDetected;
2977}
John McCall9fbd3182011-06-15 23:37:01 +00002978
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002979bool
2980ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
2981 DenseMap<Value *, RRInfo> &Releases,
2982 BBState &MyStates) {
2983 bool NestingDetected = false;
2984 InstructionClass Class = GetInstructionClass(Inst);
2985 const Value *Arg = 0;
John McCall9fbd3182011-06-15 23:37:01 +00002986
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002987 switch (Class) {
2988 case IC_RetainBlock:
2989 // An objc_retainBlock call with just a use may need to be kept,
2990 // because it may be copying a block from the stack to the heap.
2991 if (!IsRetainBlockOptimizable(Inst))
2992 break;
2993 // FALLTHROUGH
2994 case IC_Retain:
2995 case IC_RetainRV: {
2996 Arg = GetObjCArg(Inst);
2997
2998 PtrState &S = MyStates.getPtrTopDownState(Arg);
2999
3000 // Don't do retain+release tracking for IC_RetainRV, because it's
3001 // better to let it remain as the first instruction after a call.
3002 if (Class != IC_RetainRV) {
3003 // If we see two retains in a row on the same pointer. If so, make
John McCall9fbd3182011-06-15 23:37:01 +00003004 // a note, and we'll cicle back to revisit it after we've
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003005 // hopefully eliminated the second retain, which may allow us to
3006 // eliminate the first retain too.
John McCall9fbd3182011-06-15 23:37:01 +00003007 // Theoretically we could implement removal of nested retain+release
3008 // pairs by making PtrState hold a stack of states, but this is
3009 // simple and avoids adding overhead for the non-nested case.
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003010 if (S.GetSeq() == S_Retain)
John McCall9fbd3182011-06-15 23:37:01 +00003011 NestingDetected = true;
3012
Dan Gohman50ade652012-04-25 00:50:46 +00003013 S.ResetSequenceProgress(S_Retain);
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003014 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
Dan Gohman230768b2012-09-04 23:16:20 +00003015 S.RRI.KnownSafe = S.IsKnownIncremented();
John McCall9fbd3182011-06-15 23:37:01 +00003016 S.RRI.Calls.insert(Inst);
John McCall9fbd3182011-06-15 23:37:01 +00003017 }
John McCall9fbd3182011-06-15 23:37:01 +00003018
Dan Gohman230768b2012-09-04 23:16:20 +00003019 S.SetKnownPositiveRefCount();
Dan Gohmanc72d3be2012-07-23 19:27:31 +00003020
3021 // A retain can be a potential use; procede to the generic checking
3022 // code below.
3023 break;
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003024 }
3025 case IC_Release: {
3026 Arg = GetObjCArg(Inst);
3027
3028 PtrState &S = MyStates.getPtrTopDownState(Arg);
Dan Gohman230768b2012-09-04 23:16:20 +00003029 S.ClearRefCount();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003030
3031 switch (S.GetSeq()) {
3032 case S_Retain:
3033 case S_CanRelease:
3034 S.RRI.ReverseInsertPts.clear();
3035 // FALL THROUGH
3036 case S_Use:
3037 S.RRI.ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
3038 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
3039 Releases[Inst] = S.RRI;
3040 S.ClearSequenceProgress();
3041 break;
3042 case S_None:
3043 break;
3044 case S_Stop:
3045 case S_Release:
3046 case S_MovableRelease:
3047 llvm_unreachable("top-down pointer in release state!");
3048 }
3049 break;
3050 }
3051 case IC_AutoreleasepoolPop:
3052 // Conservatively, clear MyStates for all known pointers.
3053 MyStates.clearTopDownPointers();
3054 return NestingDetected;
3055 case IC_AutoreleasepoolPush:
3056 case IC_None:
3057 // These are irrelevant.
3058 return NestingDetected;
3059 default:
3060 break;
3061 }
3062
3063 // Consider any other possible effects of this instruction on each
3064 // pointer being tracked.
3065 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
3066 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
3067 const Value *Ptr = MI->first;
3068 if (Ptr == Arg)
3069 continue; // Handled above.
3070 PtrState &S = MI->second;
3071 Sequence Seq = S.GetSeq();
3072
3073 // Check for possible releases.
3074 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Dan Gohman50ade652012-04-25 00:50:46 +00003075 S.ClearRefCount();
John McCall9fbd3182011-06-15 23:37:01 +00003076 switch (Seq) {
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003077 case S_Retain:
3078 S.SetSeq(S_CanRelease);
3079 assert(S.RRI.ReverseInsertPts.empty());
3080 S.RRI.ReverseInsertPts.insert(Inst);
3081
3082 // One call can't cause a transition from S_Retain to S_CanRelease
3083 // and S_CanRelease to S_Use. If we've made the first transition,
3084 // we're done.
3085 continue;
John McCall9fbd3182011-06-15 23:37:01 +00003086 case S_Use:
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003087 case S_CanRelease:
John McCall9fbd3182011-06-15 23:37:01 +00003088 case S_None:
3089 break;
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003090 case S_Stop:
3091 case S_Release:
3092 case S_MovableRelease:
3093 llvm_unreachable("top-down pointer in release state!");
John McCall9fbd3182011-06-15 23:37:01 +00003094 }
3095 }
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003096
3097 // Check for possible direct uses.
3098 switch (Seq) {
3099 case S_CanRelease:
3100 if (CanUse(Inst, Ptr, PA, Class))
3101 S.SetSeq(S_Use);
3102 break;
3103 case S_Retain:
3104 case S_Use:
3105 case S_None:
3106 break;
3107 case S_Stop:
3108 case S_Release:
3109 case S_MovableRelease:
3110 llvm_unreachable("top-down pointer in release state!");
3111 }
John McCall9fbd3182011-06-15 23:37:01 +00003112 }
3113
3114 return NestingDetected;
3115}
3116
3117bool
3118ObjCARCOpt::VisitTopDown(BasicBlock *BB,
3119 DenseMap<const BasicBlock *, BBState> &BBStates,
3120 DenseMap<Value *, RRInfo> &Releases) {
3121 bool NestingDetected = false;
3122 BBState &MyStates = BBStates[BB];
3123
3124 // Merge the states from each predecessor to compute the initial state
3125 // for the current block.
Dan Gohman40e46602012-08-27 18:31:36 +00003126 BBState::edge_iterator PI(MyStates.pred_begin()),
3127 PE(MyStates.pred_end());
3128 if (PI != PE) {
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003129 const BasicBlock *Pred = *PI;
3130 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
3131 assert(I != BBStates.end());
3132 MyStates.InitFromPred(I->second);
3133 ++PI;
3134 for (; PI != PE; ++PI) {
3135 Pred = *PI;
3136 I = BBStates.find(Pred);
3137 assert(I != BBStates.end());
3138 MyStates.MergePred(I->second);
3139 }
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003140 }
John McCall9fbd3182011-06-15 23:37:01 +00003141
3142 // Visit all the instructions, top-down.
3143 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3144 Instruction *Inst = I;
Michael Gottesmancf140052013-01-13 07:00:51 +00003145
3146 DEBUG(dbgs() << "ObjCARCOpt::VisitTopDown: Visiting " << *Inst << "\n");
3147
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003148 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
John McCall9fbd3182011-06-15 23:37:01 +00003149 }
3150
3151 CheckForCFGHazards(BB, BBStates, MyStates);
3152 return NestingDetected;
3153}
3154
Dan Gohman59a1c932011-12-12 19:42:25 +00003155static void
3156ComputePostOrders(Function &F,
3157 SmallVectorImpl<BasicBlock *> &PostOrder,
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003158 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
3159 unsigned NoObjCARCExceptionsMDKind,
3160 DenseMap<const BasicBlock *, BBState> &BBStates) {
Dan Gohman59a1c932011-12-12 19:42:25 +00003161 /// Visited - The visited set, for doing DFS walks.
3162 SmallPtrSet<BasicBlock *, 16> Visited;
3163
3164 // Do DFS, computing the PostOrder.
3165 SmallPtrSet<BasicBlock *, 16> OnStack;
3166 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003167
3168 // Functions always have exactly one entry block, and we don't have
3169 // any other block that we treat like an entry block.
Dan Gohman59a1c932011-12-12 19:42:25 +00003170 BasicBlock *EntryBB = &F.getEntryBlock();
Dan Gohman0daef3d2012-05-08 23:39:44 +00003171 BBState &MyStates = BBStates[EntryBB];
3172 MyStates.SetAsEntry();
3173 TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
3174 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
Dan Gohman59a1c932011-12-12 19:42:25 +00003175 Visited.insert(EntryBB);
3176 OnStack.insert(EntryBB);
3177 do {
3178 dfs_next_succ:
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003179 BasicBlock *CurrBB = SuccStack.back().first;
3180 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
3181 succ_iterator SE(TI, false);
Dan Gohman0daef3d2012-05-08 23:39:44 +00003182
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003183 // If the terminator is an invoke marked with the
3184 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
3185 // ignored, for ARC purposes.
Michael Gottesmancf140052013-01-13 07:00:51 +00003186 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind)) {
3187 DEBUG(dbgs() << "ObjCARCOpt::ComputePostOrders: Found an invoke "
3188 "terminator marked with "
3189 "clang.arc.no_objc_arc_exceptions. Ignoring unwind "
3190 "edge.\n");
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003191 --SE;
Michael Gottesmancf140052013-01-13 07:00:51 +00003192 }
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003193
3194 while (SuccStack.back().second != SE) {
3195 BasicBlock *SuccBB = *SuccStack.back().second++;
3196 if (Visited.insert(SuccBB)) {
Dan Gohman0daef3d2012-05-08 23:39:44 +00003197 TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
3198 SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003199 BBStates[CurrBB].addSucc(SuccBB);
Dan Gohman0daef3d2012-05-08 23:39:44 +00003200 BBState &SuccStates = BBStates[SuccBB];
3201 SuccStates.addPred(CurrBB);
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003202 OnStack.insert(SuccBB);
Dan Gohman59a1c932011-12-12 19:42:25 +00003203 goto dfs_next_succ;
3204 }
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003205
3206 if (!OnStack.count(SuccBB)) {
3207 BBStates[CurrBB].addSucc(SuccBB);
3208 BBStates[SuccBB].addPred(CurrBB);
3209 }
Dan Gohman59a1c932011-12-12 19:42:25 +00003210 }
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003211 OnStack.erase(CurrBB);
3212 PostOrder.push_back(CurrBB);
3213 SuccStack.pop_back();
Dan Gohman59a1c932011-12-12 19:42:25 +00003214 } while (!SuccStack.empty());
3215
3216 Visited.clear();
3217
Dan Gohman59a1c932011-12-12 19:42:25 +00003218 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003219 // Functions may have many exits, and there also blocks which we treat
3220 // as exits due to ignored edges.
3221 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
3222 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
3223 BasicBlock *ExitBB = I;
3224 BBState &MyStates = BBStates[ExitBB];
3225 if (!MyStates.isExit())
3226 continue;
3227
Dan Gohman447989c2012-04-27 18:56:31 +00003228 MyStates.SetAsExit();
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003229
3230 PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
Dan Gohman59a1c932011-12-12 19:42:25 +00003231 Visited.insert(ExitBB);
3232 while (!PredStack.empty()) {
3233 reverse_dfs_next_succ:
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003234 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
3235 while (PredStack.back().second != PE) {
Dan Gohman59a1c932011-12-12 19:42:25 +00003236 BasicBlock *BB = *PredStack.back().second++;
Dan Gohman59a1c932011-12-12 19:42:25 +00003237 if (Visited.insert(BB)) {
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003238 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
Dan Gohman59a1c932011-12-12 19:42:25 +00003239 goto reverse_dfs_next_succ;
3240 }
3241 }
3242 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
3243 }
3244 }
3245}
3246
John McCall9fbd3182011-06-15 23:37:01 +00003247// Visit - Visit the function both top-down and bottom-up.
3248bool
3249ObjCARCOpt::Visit(Function &F,
3250 DenseMap<const BasicBlock *, BBState> &BBStates,
3251 MapVector<Value *, RRInfo> &Retains,
3252 DenseMap<Value *, RRInfo> &Releases) {
Dan Gohman59a1c932011-12-12 19:42:25 +00003253
3254 // Use reverse-postorder traversals, because we magically know that loops
3255 // will be well behaved, i.e. they won't repeatedly call retain on a single
3256 // pointer without doing a release. We can't use the ReversePostOrderTraversal
3257 // class here because we want the reverse-CFG postorder to consider each
3258 // function exit point, and we want to ignore selected cycle edges.
3259 SmallVector<BasicBlock *, 16> PostOrder;
3260 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003261 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
3262 NoObjCARCExceptionsMDKind,
3263 BBStates);
Dan Gohman59a1c932011-12-12 19:42:25 +00003264
3265 // Use reverse-postorder on the reverse CFG for bottom-up.
John McCall9fbd3182011-06-15 23:37:01 +00003266 bool BottomUpNestingDetected = false;
Dan Gohmanb48ef3a2011-08-18 21:27:42 +00003267 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
Dan Gohman59a1c932011-12-12 19:42:25 +00003268 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
3269 I != E; ++I)
3270 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
John McCall9fbd3182011-06-15 23:37:01 +00003271
Dan Gohman59a1c932011-12-12 19:42:25 +00003272 // Use reverse-postorder for top-down.
John McCall9fbd3182011-06-15 23:37:01 +00003273 bool TopDownNestingDetected = false;
Dan Gohman59a1c932011-12-12 19:42:25 +00003274 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
3275 PostOrder.rbegin(), E = PostOrder.rend();
3276 I != E; ++I)
3277 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
John McCall9fbd3182011-06-15 23:37:01 +00003278
3279 return TopDownNestingDetected && BottomUpNestingDetected;
3280}
3281
3282/// MoveCalls - Move the calls in RetainsToMove and ReleasesToMove.
3283void ObjCARCOpt::MoveCalls(Value *Arg,
3284 RRInfo &RetainsToMove,
3285 RRInfo &ReleasesToMove,
3286 MapVector<Value *, RRInfo> &Retains,
3287 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman44280692011-07-22 22:29:21 +00003288 SmallVectorImpl<Instruction *> &DeadInsts,
3289 Module *M) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003290 Type *ArgTy = Arg->getType();
Dan Gohman44280692011-07-22 22:29:21 +00003291 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
John McCall9fbd3182011-06-15 23:37:01 +00003292
3293 // Insert the new retain and release calls.
3294 for (SmallPtrSet<Instruction *, 2>::const_iterator
3295 PI = ReleasesToMove.ReverseInsertPts.begin(),
3296 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
3297 Instruction *InsertPt = *PI;
3298 Value *MyArg = ArgTy == ParamTy ? Arg :
3299 new BitCastInst(Arg, ParamTy, "", InsertPt);
3300 CallInst *Call =
3301 CallInst::Create(RetainsToMove.IsRetainBlock ?
Dan Gohman44280692011-07-22 22:29:21 +00003302 getRetainBlockCallee(M) : getRetainCallee(M),
John McCall9fbd3182011-06-15 23:37:01 +00003303 MyArg, "", InsertPt);
3304 Call->setDoesNotThrow();
Dan Gohman79522dc2012-01-13 00:39:07 +00003305 if (RetainsToMove.IsRetainBlock)
Dan Gohmana974bea2011-10-17 22:53:25 +00003306 Call->setMetadata(CopyOnEscapeMDKind,
3307 MDNode::get(M->getContext(), ArrayRef<Value *>()));
Dan Gohman79522dc2012-01-13 00:39:07 +00003308 else
John McCall9fbd3182011-06-15 23:37:01 +00003309 Call->setTailCall();
Michael Gottesman55811152013-01-09 19:23:24 +00003310
3311 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Inserting new Release: " << *Call
3312 << "\n"
3313 " At insertion point: " << *InsertPt
3314 << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00003315 }
3316 for (SmallPtrSet<Instruction *, 2>::const_iterator
3317 PI = RetainsToMove.ReverseInsertPts.begin(),
3318 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
Dan Gohmanfbab4a82012-03-23 17:47:54 +00003319 Instruction *InsertPt = *PI;
3320 Value *MyArg = ArgTy == ParamTy ? Arg :
3321 new BitCastInst(Arg, ParamTy, "", InsertPt);
3322 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
3323 "", InsertPt);
3324 // Attach a clang.imprecise_release metadata tag, if appropriate.
3325 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
3326 Call->setMetadata(ImpreciseReleaseMDKind, M);
3327 Call->setDoesNotThrow();
3328 if (ReleasesToMove.IsTailCallRelease)
3329 Call->setTailCall();
Michael Gottesman55811152013-01-09 19:23:24 +00003330
3331 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Inserting new Retain: " << *Call
3332 << "\n"
3333 " At insertion point: " << *InsertPt
3334 << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00003335 }
3336
3337 // Delete the original retain and release calls.
3338 for (SmallPtrSet<Instruction *, 2>::const_iterator
3339 AI = RetainsToMove.Calls.begin(),
3340 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
3341 Instruction *OrigRetain = *AI;
3342 Retains.blot(OrigRetain);
3343 DeadInsts.push_back(OrigRetain);
Michael Gottesman55811152013-01-09 19:23:24 +00003344 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Deleting retain: " << *OrigRetain <<
3345 "\n");
John McCall9fbd3182011-06-15 23:37:01 +00003346 }
3347 for (SmallPtrSet<Instruction *, 2>::const_iterator
3348 AI = ReleasesToMove.Calls.begin(),
3349 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
3350 Instruction *OrigRelease = *AI;
3351 Releases.erase(OrigRelease);
3352 DeadInsts.push_back(OrigRelease);
Michael Gottesman55811152013-01-09 19:23:24 +00003353 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Deleting release: " << *OrigRelease
3354 << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00003355 }
3356}
3357
Dan Gohmand6bf2012012-04-13 18:57:48 +00003358/// PerformCodePlacement - Identify pairings between the retains and releases,
3359/// and delete and/or move them.
John McCall9fbd3182011-06-15 23:37:01 +00003360bool
3361ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
3362 &BBStates,
3363 MapVector<Value *, RRInfo> &Retains,
Dan Gohman44280692011-07-22 22:29:21 +00003364 DenseMap<Value *, RRInfo> &Releases,
3365 Module *M) {
John McCall9fbd3182011-06-15 23:37:01 +00003366 bool AnyPairsCompletelyEliminated = false;
3367 RRInfo RetainsToMove;
3368 RRInfo ReleasesToMove;
3369 SmallVector<Instruction *, 4> NewRetains;
3370 SmallVector<Instruction *, 4> NewReleases;
3371 SmallVector<Instruction *, 8> DeadInsts;
3372
Dan Gohmand6bf2012012-04-13 18:57:48 +00003373 // Visit each retain.
John McCall9fbd3182011-06-15 23:37:01 +00003374 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
Dan Gohman597fece2011-09-29 22:25:23 +00003375 E = Retains.end(); I != E; ++I) {
3376 Value *V = I->first;
John McCall9fbd3182011-06-15 23:37:01 +00003377 if (!V) continue; // blotted
3378
3379 Instruction *Retain = cast<Instruction>(V);
Michael Gottesman55811152013-01-09 19:23:24 +00003380
3381 DEBUG(dbgs() << "ObjCARCOpt::PerformCodePlacement: Visiting: " << *Retain
3382 << "\n");
3383
John McCall9fbd3182011-06-15 23:37:01 +00003384 Value *Arg = GetObjCArg(Retain);
3385
Dan Gohman79522dc2012-01-13 00:39:07 +00003386 // If the object being released is in static or stack storage, we know it's
John McCall9fbd3182011-06-15 23:37:01 +00003387 // not being managed by ObjC reference counting, so we can delete pairs
3388 // regardless of what possible decrements or uses lie between them.
Dan Gohman79522dc2012-01-13 00:39:07 +00003389 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
Dan Gohman0daef3d2012-05-08 23:39:44 +00003390
Dan Gohman1b31ea82011-08-22 17:29:11 +00003391 // A constant pointer can't be pointing to an object on the heap. It may
3392 // be reference-counted, but it won't be deleted.
3393 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
3394 if (const GlobalVariable *GV =
3395 dyn_cast<GlobalVariable>(
3396 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
3397 if (GV->isConstant())
3398 KnownSafe = true;
3399
John McCall9fbd3182011-06-15 23:37:01 +00003400 // If a pair happens in a region where it is known that the reference count
3401 // is already incremented, we can similarly ignore possible decrements.
Dan Gohmane6d5e882011-08-19 00:26:36 +00003402 bool KnownSafeTD = true, KnownSafeBU = true;
John McCall9fbd3182011-06-15 23:37:01 +00003403
3404 // Connect the dots between the top-down-collected RetainsToMove and
3405 // bottom-up-collected ReleasesToMove to form sets of related calls.
3406 // This is an iterative process so that we connect multiple releases
3407 // to multiple retains if needed.
3408 unsigned OldDelta = 0;
3409 unsigned NewDelta = 0;
3410 unsigned OldCount = 0;
3411 unsigned NewCount = 0;
3412 bool FirstRelease = true;
3413 bool FirstRetain = true;
3414 NewRetains.push_back(Retain);
3415 for (;;) {
3416 for (SmallVectorImpl<Instruction *>::const_iterator
3417 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
3418 Instruction *NewRetain = *NI;
3419 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
3420 assert(It != Retains.end());
3421 const RRInfo &NewRetainRRI = It->second;
Dan Gohmane6d5e882011-08-19 00:26:36 +00003422 KnownSafeTD &= NewRetainRRI.KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00003423 for (SmallPtrSet<Instruction *, 2>::const_iterator
3424 LI = NewRetainRRI.Calls.begin(),
3425 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
3426 Instruction *NewRetainRelease = *LI;
3427 DenseMap<Value *, RRInfo>::const_iterator Jt =
3428 Releases.find(NewRetainRelease);
3429 if (Jt == Releases.end())
3430 goto next_retain;
3431 const RRInfo &NewRetainReleaseRRI = Jt->second;
3432 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
3433 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
3434 OldDelta -=
3435 BBStates[NewRetainRelease->getParent()].GetAllPathCount();
3436
3437 // Merge the ReleaseMetadata and IsTailCallRelease values.
3438 if (FirstRelease) {
3439 ReleasesToMove.ReleaseMetadata =
3440 NewRetainReleaseRRI.ReleaseMetadata;
3441 ReleasesToMove.IsTailCallRelease =
3442 NewRetainReleaseRRI.IsTailCallRelease;
3443 FirstRelease = false;
3444 } else {
3445 if (ReleasesToMove.ReleaseMetadata !=
3446 NewRetainReleaseRRI.ReleaseMetadata)
3447 ReleasesToMove.ReleaseMetadata = 0;
3448 if (ReleasesToMove.IsTailCallRelease !=
3449 NewRetainReleaseRRI.IsTailCallRelease)
3450 ReleasesToMove.IsTailCallRelease = false;
3451 }
3452
3453 // Collect the optimal insertion points.
3454 if (!KnownSafe)
3455 for (SmallPtrSet<Instruction *, 2>::const_iterator
3456 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
3457 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
3458 RI != RE; ++RI) {
3459 Instruction *RIP = *RI;
3460 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
3461 NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
3462 }
3463 NewReleases.push_back(NewRetainRelease);
3464 }
3465 }
3466 }
3467 NewRetains.clear();
3468 if (NewReleases.empty()) break;
3469
3470 // Back the other way.
3471 for (SmallVectorImpl<Instruction *>::const_iterator
3472 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
3473 Instruction *NewRelease = *NI;
3474 DenseMap<Value *, RRInfo>::const_iterator It =
3475 Releases.find(NewRelease);
3476 assert(It != Releases.end());
3477 const RRInfo &NewReleaseRRI = It->second;
Dan Gohmane6d5e882011-08-19 00:26:36 +00003478 KnownSafeBU &= NewReleaseRRI.KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00003479 for (SmallPtrSet<Instruction *, 2>::const_iterator
3480 LI = NewReleaseRRI.Calls.begin(),
3481 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
3482 Instruction *NewReleaseRetain = *LI;
3483 MapVector<Value *, RRInfo>::const_iterator Jt =
3484 Retains.find(NewReleaseRetain);
3485 if (Jt == Retains.end())
3486 goto next_retain;
3487 const RRInfo &NewReleaseRetainRRI = Jt->second;
3488 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
3489 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
3490 unsigned PathCount =
3491 BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
3492 OldDelta += PathCount;
3493 OldCount += PathCount;
3494
3495 // Merge the IsRetainBlock values.
3496 if (FirstRetain) {
3497 RetainsToMove.IsRetainBlock = NewReleaseRetainRRI.IsRetainBlock;
3498 FirstRetain = false;
3499 } else if (ReleasesToMove.IsRetainBlock !=
3500 NewReleaseRetainRRI.IsRetainBlock)
3501 // It's not possible to merge the sequences if one uses
3502 // objc_retain and the other uses objc_retainBlock.
3503 goto next_retain;
3504
3505 // Collect the optimal insertion points.
3506 if (!KnownSafe)
3507 for (SmallPtrSet<Instruction *, 2>::const_iterator
3508 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
3509 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
3510 RI != RE; ++RI) {
3511 Instruction *RIP = *RI;
3512 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
3513 PathCount = BBStates[RIP->getParent()].GetAllPathCount();
3514 NewDelta += PathCount;
3515 NewCount += PathCount;
3516 }
3517 }
3518 NewRetains.push_back(NewReleaseRetain);
3519 }
3520 }
3521 }
3522 NewReleases.clear();
3523 if (NewRetains.empty()) break;
3524 }
3525
Dan Gohmane6d5e882011-08-19 00:26:36 +00003526 // If the pointer is known incremented or nested, we can safely delete the
3527 // pair regardless of what's between them.
3528 if (KnownSafeTD || KnownSafeBU) {
John McCall9fbd3182011-06-15 23:37:01 +00003529 RetainsToMove.ReverseInsertPts.clear();
3530 ReleasesToMove.ReverseInsertPts.clear();
3531 NewCount = 0;
Dan Gohmana7f7db22011-08-12 00:26:31 +00003532 } else {
3533 // Determine whether the new insertion points we computed preserve the
3534 // balance of retain and release calls through the program.
3535 // TODO: If the fully aggressive solution isn't valid, try to find a
3536 // less aggressive solution which is.
3537 if (NewDelta != 0)
3538 goto next_retain;
John McCall9fbd3182011-06-15 23:37:01 +00003539 }
3540
3541 // Determine whether the original call points are balanced in the retain and
3542 // release calls through the program. If not, conservatively don't touch
3543 // them.
3544 // TODO: It's theoretically possible to do code motion in this case, as
3545 // long as the existing imbalances are maintained.
3546 if (OldDelta != 0)
3547 goto next_retain;
3548
John McCall9fbd3182011-06-15 23:37:01 +00003549 // Ok, everything checks out and we're all set. Let's move some code!
3550 Changed = true;
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003551 assert(OldCount != 0 && "Unreachable code?");
3552 AnyPairsCompletelyEliminated = NewCount == 0;
John McCall9fbd3182011-06-15 23:37:01 +00003553 NumRRs += OldCount - NewCount;
Dan Gohman44280692011-07-22 22:29:21 +00003554 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
3555 Retains, Releases, DeadInsts, M);
John McCall9fbd3182011-06-15 23:37:01 +00003556
3557 next_retain:
3558 NewReleases.clear();
3559 NewRetains.clear();
3560 RetainsToMove.clear();
3561 ReleasesToMove.clear();
3562 }
3563
3564 // Now that we're done moving everything, we can delete the newly dead
3565 // instructions, as we no longer need them as insert points.
3566 while (!DeadInsts.empty())
3567 EraseInstruction(DeadInsts.pop_back_val());
3568
3569 return AnyPairsCompletelyEliminated;
3570}
3571
3572/// OptimizeWeakCalls - Weak pointer optimizations.
3573void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
3574 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
3575 // itself because it uses AliasAnalysis and we need to do provenance
3576 // queries instead.
3577 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3578 Instruction *Inst = &*I++;
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00003579
Michael Gottesman5c0ae472013-01-04 21:29:57 +00003580 DEBUG(dbgs() << "ObjCARCOpt::OptimizeWeakCalls: Visiting: " << *Inst <<
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00003581 "\n");
3582
John McCall9fbd3182011-06-15 23:37:01 +00003583 InstructionClass Class = GetBasicInstructionClass(Inst);
3584 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
3585 continue;
3586
3587 // Delete objc_loadWeak calls with no users.
3588 if (Class == IC_LoadWeak && Inst->use_empty()) {
3589 Inst->eraseFromParent();
3590 continue;
3591 }
3592
3593 // TODO: For now, just look for an earlier available version of this value
3594 // within the same block. Theoretically, we could do memdep-style non-local
3595 // analysis too, but that would want caching. A better approach would be to
3596 // use the technique that EarlyCSE uses.
3597 inst_iterator Current = llvm::prior(I);
3598 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
3599 for (BasicBlock::iterator B = CurrentBB->begin(),
3600 J = Current.getInstructionIterator();
3601 J != B; --J) {
3602 Instruction *EarlierInst = &*llvm::prior(J);
3603 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
3604 switch (EarlierClass) {
3605 case IC_LoadWeak:
3606 case IC_LoadWeakRetained: {
3607 // If this is loading from the same pointer, replace this load's value
3608 // with that one.
3609 CallInst *Call = cast<CallInst>(Inst);
3610 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3611 Value *Arg = Call->getArgOperand(0);
3612 Value *EarlierArg = EarlierCall->getArgOperand(0);
3613 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3614 case AliasAnalysis::MustAlias:
3615 Changed = true;
3616 // If the load has a builtin retain, insert a plain retain for it.
3617 if (Class == IC_LoadWeakRetained) {
3618 CallInst *CI =
3619 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3620 "", Call);
3621 CI->setTailCall();
3622 }
3623 // Zap the fully redundant load.
3624 Call->replaceAllUsesWith(EarlierCall);
3625 Call->eraseFromParent();
3626 goto clobbered;
3627 case AliasAnalysis::MayAlias:
3628 case AliasAnalysis::PartialAlias:
3629 goto clobbered;
3630 case AliasAnalysis::NoAlias:
3631 break;
3632 }
3633 break;
3634 }
3635 case IC_StoreWeak:
3636 case IC_InitWeak: {
3637 // If this is storing to the same pointer and has the same size etc.
3638 // replace this load's value with the stored value.
3639 CallInst *Call = cast<CallInst>(Inst);
3640 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3641 Value *Arg = Call->getArgOperand(0);
3642 Value *EarlierArg = EarlierCall->getArgOperand(0);
3643 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3644 case AliasAnalysis::MustAlias:
3645 Changed = true;
3646 // If the load has a builtin retain, insert a plain retain for it.
3647 if (Class == IC_LoadWeakRetained) {
3648 CallInst *CI =
3649 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3650 "", Call);
3651 CI->setTailCall();
3652 }
3653 // Zap the fully redundant load.
3654 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
3655 Call->eraseFromParent();
3656 goto clobbered;
3657 case AliasAnalysis::MayAlias:
3658 case AliasAnalysis::PartialAlias:
3659 goto clobbered;
3660 case AliasAnalysis::NoAlias:
3661 break;
3662 }
3663 break;
3664 }
3665 case IC_MoveWeak:
3666 case IC_CopyWeak:
3667 // TOOD: Grab the copied value.
3668 goto clobbered;
3669 case IC_AutoreleasepoolPush:
3670 case IC_None:
3671 case IC_User:
3672 // Weak pointers are only modified through the weak entry points
3673 // (and arbitrary calls, which could call the weak entry points).
3674 break;
3675 default:
3676 // Anything else could modify the weak pointer.
3677 goto clobbered;
3678 }
3679 }
3680 clobbered:;
3681 }
3682
3683 // Then, for each destroyWeak with an alloca operand, check to see if
3684 // the alloca and all its users can be zapped.
3685 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3686 Instruction *Inst = &*I++;
3687 InstructionClass Class = GetBasicInstructionClass(Inst);
3688 if (Class != IC_DestroyWeak)
3689 continue;
3690
3691 CallInst *Call = cast<CallInst>(Inst);
3692 Value *Arg = Call->getArgOperand(0);
3693 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
3694 for (Value::use_iterator UI = Alloca->use_begin(),
3695 UE = Alloca->use_end(); UI != UE; ++UI) {
Dan Gohman447989c2012-04-27 18:56:31 +00003696 const Instruction *UserInst = cast<Instruction>(*UI);
John McCall9fbd3182011-06-15 23:37:01 +00003697 switch (GetBasicInstructionClass(UserInst)) {
3698 case IC_InitWeak:
3699 case IC_StoreWeak:
3700 case IC_DestroyWeak:
3701 continue;
3702 default:
3703 goto done;
3704 }
3705 }
3706 Changed = true;
3707 for (Value::use_iterator UI = Alloca->use_begin(),
3708 UE = Alloca->use_end(); UI != UE; ) {
3709 CallInst *UserInst = cast<CallInst>(*UI++);
Dan Gohmance5d8b02012-05-18 22:17:29 +00003710 switch (GetBasicInstructionClass(UserInst)) {
3711 case IC_InitWeak:
3712 case IC_StoreWeak:
3713 // These functions return their second argument.
3714 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
3715 break;
3716 case IC_DestroyWeak:
3717 // No return value.
3718 break;
3719 default:
Dan Gohman4c8f9092012-05-21 17:41:28 +00003720 llvm_unreachable("alloca really is used!");
Dan Gohmance5d8b02012-05-18 22:17:29 +00003721 }
John McCall9fbd3182011-06-15 23:37:01 +00003722 UserInst->eraseFromParent();
3723 }
3724 Alloca->eraseFromParent();
3725 done:;
3726 }
3727 }
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00003728
Michael Gottesman5c0ae472013-01-04 21:29:57 +00003729 DEBUG(dbgs() << "ObjCARCOpt::OptimizeWeakCalls: Finished List.\n\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00003730
John McCall9fbd3182011-06-15 23:37:01 +00003731}
3732
3733/// OptimizeSequences - Identify program paths which execute sequences of
3734/// retains and releases which can be eliminated.
3735bool ObjCARCOpt::OptimizeSequences(Function &F) {
3736 /// Releases, Retains - These are used to store the results of the main flow
3737 /// analysis. These use Value* as the key instead of Instruction* so that the
3738 /// map stays valid when we get around to rewriting code and calls get
3739 /// replaced by arguments.
3740 DenseMap<Value *, RRInfo> Releases;
3741 MapVector<Value *, RRInfo> Retains;
3742
3743 /// BBStates, This is used during the traversal of the function to track the
3744 /// states for each identified object at each block.
3745 DenseMap<const BasicBlock *, BBState> BBStates;
3746
3747 // Analyze the CFG of the function, and all instructions.
3748 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
3749
3750 // Transform.
Dan Gohman44280692011-07-22 22:29:21 +00003751 return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) &&
3752 NestingDetected;
John McCall9fbd3182011-06-15 23:37:01 +00003753}
3754
3755/// OptimizeReturns - Look for this pattern:
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +00003756/// \code
John McCall9fbd3182011-06-15 23:37:01 +00003757/// %call = call i8* @something(...)
3758/// %2 = call i8* @objc_retain(i8* %call)
3759/// %3 = call i8* @objc_autorelease(i8* %2)
3760/// ret i8* %3
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +00003761/// \endcode
John McCall9fbd3182011-06-15 23:37:01 +00003762/// And delete the retain and autorelease.
3763///
3764/// Otherwise if it's just this:
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +00003765/// \code
John McCall9fbd3182011-06-15 23:37:01 +00003766/// %3 = call i8* @objc_autorelease(i8* %2)
3767/// ret i8* %3
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +00003768/// \endcode
John McCall9fbd3182011-06-15 23:37:01 +00003769/// convert the autorelease to autoreleaseRV.
3770void ObjCARCOpt::OptimizeReturns(Function &F) {
3771 if (!F.getReturnType()->isPointerTy())
3772 return;
3773
3774 SmallPtrSet<Instruction *, 4> DependingInstructions;
3775 SmallPtrSet<const BasicBlock *, 4> Visited;
3776 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3777 BasicBlock *BB = FI;
3778 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00003779
Michael Gottesman5c0ae472013-01-04 21:29:57 +00003780 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Visiting: " << *Ret << "\n");
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00003781
John McCall9fbd3182011-06-15 23:37:01 +00003782 if (!Ret) continue;
3783
3784 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
3785 FindDependencies(NeedsPositiveRetainCount, Arg,
3786 BB, Ret, DependingInstructions, Visited, PA);
3787 if (DependingInstructions.size() != 1)
3788 goto next_block;
3789
3790 {
3791 CallInst *Autorelease =
3792 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3793 if (!Autorelease)
3794 goto next_block;
Dan Gohman0daef3d2012-05-08 23:39:44 +00003795 InstructionClass AutoreleaseClass = GetBasicInstructionClass(Autorelease);
John McCall9fbd3182011-06-15 23:37:01 +00003796 if (!IsAutorelease(AutoreleaseClass))
3797 goto next_block;
3798 if (GetObjCArg(Autorelease) != Arg)
3799 goto next_block;
3800
3801 DependingInstructions.clear();
3802 Visited.clear();
3803
3804 // Check that there is nothing that can affect the reference
3805 // count between the autorelease and the retain.
3806 FindDependencies(CanChangeRetainCount, Arg,
3807 BB, Autorelease, DependingInstructions, Visited, PA);
3808 if (DependingInstructions.size() != 1)
3809 goto next_block;
3810
3811 {
3812 CallInst *Retain =
3813 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3814
3815 // Check that we found a retain with the same argument.
3816 if (!Retain ||
3817 !IsRetain(GetBasicInstructionClass(Retain)) ||
3818 GetObjCArg(Retain) != Arg)
3819 goto next_block;
3820
3821 DependingInstructions.clear();
3822 Visited.clear();
3823
3824 // Convert the autorelease to an autoreleaseRV, since it's
3825 // returning the value.
3826 if (AutoreleaseClass == IC_Autorelease) {
Michael Gottesman5dc30012013-01-10 02:03:50 +00003827 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Converting autorelease "
3828 "=> autoreleaseRV since it's returning a value.\n"
3829 " In: " << *Autorelease
3830 << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00003831 Autorelease->setCalledFunction(getAutoreleaseRVCallee(F.getParent()));
Michael Gottesman5dc30012013-01-10 02:03:50 +00003832 DEBUG(dbgs() << " Out: " << *Autorelease
3833 << "\n");
Michael Gottesmane8c161a2013-01-12 01:25:15 +00003834 Autorelease->setTailCall(); // Always tail call autoreleaseRV.
John McCall9fbd3182011-06-15 23:37:01 +00003835 AutoreleaseClass = IC_AutoreleaseRV;
3836 }
3837
3838 // Check that there is nothing that can affect the reference
3839 // count between the retain and the call.
Dan Gohman27e06662011-09-29 22:27:34 +00003840 // Note that Retain need not be in BB.
3841 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
John McCall9fbd3182011-06-15 23:37:01 +00003842 DependingInstructions, Visited, PA);
3843 if (DependingInstructions.size() != 1)
3844 goto next_block;
3845
3846 {
3847 CallInst *Call =
3848 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3849
3850 // Check that the pointer is the return value of the call.
3851 if (!Call || Arg != Call)
3852 goto next_block;
3853
3854 // Check that the call is a regular call.
3855 InstructionClass Class = GetBasicInstructionClass(Call);
3856 if (Class != IC_CallOrUser && Class != IC_Call)
3857 goto next_block;
3858
3859 // If so, we can zap the retain and autorelease.
3860 Changed = true;
3861 ++NumRets;
Michael Gottesmanf93109a2013-01-07 00:04:56 +00003862 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Erasing: " << *Retain
3863 << "\n Erasing: "
3864 << *Autorelease << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00003865 EraseInstruction(Retain);
3866 EraseInstruction(Autorelease);
3867 }
3868 }
3869 }
3870
3871 next_block:
3872 DependingInstructions.clear();
3873 Visited.clear();
3874 }
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00003875
Michael Gottesman5c0ae472013-01-04 21:29:57 +00003876 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Finished List.\n\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00003877
John McCall9fbd3182011-06-15 23:37:01 +00003878}
3879
3880bool ObjCARCOpt::doInitialization(Module &M) {
3881 if (!EnableARCOpts)
3882 return false;
3883
Dan Gohmand6bf2012012-04-13 18:57:48 +00003884 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003885 Run = ModuleHasARC(M);
3886 if (!Run)
3887 return false;
3888
John McCall9fbd3182011-06-15 23:37:01 +00003889 // Identify the imprecise release metadata kind.
3890 ImpreciseReleaseMDKind =
3891 M.getContext().getMDKindID("clang.imprecise_release");
Dan Gohmana974bea2011-10-17 22:53:25 +00003892 CopyOnEscapeMDKind =
3893 M.getContext().getMDKindID("clang.arc.copy_on_escape");
Dan Gohmandbe266b2012-02-17 18:59:53 +00003894 NoObjCARCExceptionsMDKind =
3895 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
John McCall9fbd3182011-06-15 23:37:01 +00003896
John McCall9fbd3182011-06-15 23:37:01 +00003897 // Intuitively, objc_retain and others are nocapture, however in practice
3898 // they are not, because they return their argument value. And objc_release
Dan Gohman447989c2012-04-27 18:56:31 +00003899 // calls finalizers which can have arbitrary side effects.
John McCall9fbd3182011-06-15 23:37:01 +00003900
3901 // These are initialized lazily.
3902 RetainRVCallee = 0;
3903 AutoreleaseRVCallee = 0;
3904 ReleaseCallee = 0;
3905 RetainCallee = 0;
Dan Gohman44280692011-07-22 22:29:21 +00003906 RetainBlockCallee = 0;
John McCall9fbd3182011-06-15 23:37:01 +00003907 AutoreleaseCallee = 0;
3908
3909 return false;
3910}
3911
3912bool ObjCARCOpt::runOnFunction(Function &F) {
3913 if (!EnableARCOpts)
3914 return false;
3915
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003916 // If nothing in the Module uses ARC, don't do anything.
3917 if (!Run)
3918 return false;
3919
John McCall9fbd3182011-06-15 23:37:01 +00003920 Changed = false;
3921
Michael Gottesman0d3582b2013-01-12 02:57:16 +00003922 DEBUG(dbgs() << "ObjCARCOpt: Visiting Function: " << F.getName() << "\n");
3923
John McCall9fbd3182011-06-15 23:37:01 +00003924 PA.setAA(&getAnalysis<AliasAnalysis>());
3925
3926 // This pass performs several distinct transformations. As a compile-time aid
3927 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3928 // library functions aren't declared.
3929
3930 // Preliminary optimizations. This also computs UsedInThisFunction.
3931 OptimizeIndividualCalls(F);
3932
3933 // Optimizations for weak pointers.
3934 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3935 (1 << IC_LoadWeakRetained) |
3936 (1 << IC_StoreWeak) |
3937 (1 << IC_InitWeak) |
3938 (1 << IC_CopyWeak) |
3939 (1 << IC_MoveWeak) |
3940 (1 << IC_DestroyWeak)))
3941 OptimizeWeakCalls(F);
3942
3943 // Optimizations for retain+release pairs.
3944 if (UsedInThisFunction & ((1 << IC_Retain) |
3945 (1 << IC_RetainRV) |
3946 (1 << IC_RetainBlock)))
3947 if (UsedInThisFunction & (1 << IC_Release))
3948 // Run OptimizeSequences until it either stops making changes or
3949 // no retain+release pair nesting is detected.
3950 while (OptimizeSequences(F)) {}
3951
3952 // Optimizations if objc_autorelease is used.
Dan Gohman0daef3d2012-05-08 23:39:44 +00003953 if (UsedInThisFunction & ((1 << IC_Autorelease) |
3954 (1 << IC_AutoreleaseRV)))
John McCall9fbd3182011-06-15 23:37:01 +00003955 OptimizeReturns(F);
3956
Michael Gottesman0d3582b2013-01-12 02:57:16 +00003957 DEBUG(dbgs() << "\n");
3958
John McCall9fbd3182011-06-15 23:37:01 +00003959 return Changed;
3960}
3961
3962void ObjCARCOpt::releaseMemory() {
3963 PA.clear();
3964}
3965
3966//===----------------------------------------------------------------------===//
3967// ARC contraction.
3968//===----------------------------------------------------------------------===//
3969
3970// TODO: ObjCARCContract could insert PHI nodes when uses aren't
3971// dominated by single calls.
3972
John McCall9fbd3182011-06-15 23:37:01 +00003973#include "llvm/Analysis/Dominators.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +00003974#include "llvm/IR/InlineAsm.h"
3975#include "llvm/IR/Operator.h"
John McCall9fbd3182011-06-15 23:37:01 +00003976
3977STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed");
3978
3979namespace {
3980 /// ObjCARCContract - Late ARC optimizations. These change the IR in a way
3981 /// that makes it difficult to be analyzed by ObjCARCOpt, so it's run late.
3982 class ObjCARCContract : public FunctionPass {
3983 bool Changed;
3984 AliasAnalysis *AA;
3985 DominatorTree *DT;
3986 ProvenanceAnalysis PA;
3987
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003988 /// Run - A flag indicating whether this optimization pass should run.
3989 bool Run;
3990
John McCall9fbd3182011-06-15 23:37:01 +00003991 /// StoreStrongCallee, etc. - Declarations for ObjC runtime
3992 /// functions, for use in creating calls to them. These are initialized
3993 /// lazily to avoid cluttering up the Module with unused declarations.
3994 Constant *StoreStrongCallee,
3995 *RetainAutoreleaseCallee, *RetainAutoreleaseRVCallee;
3996
3997 /// RetainRVMarker - The inline asm string to insert between calls and
3998 /// RetainRV calls to make the optimization work on targets which need it.
3999 const MDString *RetainRVMarker;
4000
Dan Gohman0cdece42012-01-19 19:14:36 +00004001 /// StoreStrongCalls - The set of inserted objc_storeStrong calls. If
4002 /// at the end of walking the function we have found no alloca
4003 /// instructions, these calls can be marked "tail".
Dan Gohman0daef3d2012-05-08 23:39:44 +00004004 SmallPtrSet<CallInst *, 8> StoreStrongCalls;
Dan Gohman0cdece42012-01-19 19:14:36 +00004005
John McCall9fbd3182011-06-15 23:37:01 +00004006 Constant *getStoreStrongCallee(Module *M);
4007 Constant *getRetainAutoreleaseCallee(Module *M);
4008 Constant *getRetainAutoreleaseRVCallee(Module *M);
4009
4010 bool ContractAutorelease(Function &F, Instruction *Autorelease,
4011 InstructionClass Class,
4012 SmallPtrSet<Instruction *, 4>
4013 &DependingInstructions,
4014 SmallPtrSet<const BasicBlock *, 4>
4015 &Visited);
4016
4017 void ContractRelease(Instruction *Release,
4018 inst_iterator &Iter);
4019
4020 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
4021 virtual bool doInitialization(Module &M);
4022 virtual bool runOnFunction(Function &F);
4023
4024 public:
4025 static char ID;
4026 ObjCARCContract() : FunctionPass(ID) {
4027 initializeObjCARCContractPass(*PassRegistry::getPassRegistry());
4028 }
4029 };
4030}
4031
4032char ObjCARCContract::ID = 0;
4033INITIALIZE_PASS_BEGIN(ObjCARCContract,
4034 "objc-arc-contract", "ObjC ARC contraction", false, false)
4035INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
4036INITIALIZE_PASS_DEPENDENCY(DominatorTree)
4037INITIALIZE_PASS_END(ObjCARCContract,
4038 "objc-arc-contract", "ObjC ARC contraction", false, false)
4039
4040Pass *llvm::createObjCARCContractPass() {
4041 return new ObjCARCContract();
4042}
4043
4044void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const {
4045 AU.addRequired<AliasAnalysis>();
4046 AU.addRequired<DominatorTree>();
4047 AU.setPreservesCFG();
4048}
4049
4050Constant *ObjCARCContract::getStoreStrongCallee(Module *M) {
4051 if (!StoreStrongCallee) {
4052 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00004053 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
4054 Type *I8XX = PointerType::getUnqual(I8X);
Dan Gohman0daef3d2012-05-08 23:39:44 +00004055 Type *Params[] = { I8XX, I8X };
John McCall9fbd3182011-06-15 23:37:01 +00004056
Bill Wendling034b94b2012-12-19 07:18:57 +00004057 AttributeSet Attribute = AttributeSet()
Bill Wendling99faa3b2012-12-07 23:16:57 +00004058 .addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00004059 Attribute::get(C, Attribute::NoUnwind))
4060 .addAttr(M->getContext(), 1, Attribute::get(C, Attribute::NoCapture));
John McCall9fbd3182011-06-15 23:37:01 +00004061
4062 StoreStrongCallee =
4063 M->getOrInsertFunction(
4064 "objc_storeStrong",
4065 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
Bill Wendling034b94b2012-12-19 07:18:57 +00004066 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00004067 }
4068 return StoreStrongCallee;
4069}
4070
4071Constant *ObjCARCContract::getRetainAutoreleaseCallee(Module *M) {
4072 if (!RetainAutoreleaseCallee) {
4073 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00004074 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman0daef3d2012-05-08 23:39:44 +00004075 Type *Params[] = { I8X };
4076 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling034b94b2012-12-19 07:18:57 +00004077 AttributeSet Attribute =
Bill Wendling99faa3b2012-12-07 23:16:57 +00004078 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00004079 Attribute::get(C, Attribute::NoUnwind));
John McCall9fbd3182011-06-15 23:37:01 +00004080 RetainAutoreleaseCallee =
Bill Wendling034b94b2012-12-19 07:18:57 +00004081 M->getOrInsertFunction("objc_retainAutorelease", FTy, Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00004082 }
4083 return RetainAutoreleaseCallee;
4084}
4085
4086Constant *ObjCARCContract::getRetainAutoreleaseRVCallee(Module *M) {
4087 if (!RetainAutoreleaseRVCallee) {
4088 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00004089 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman0daef3d2012-05-08 23:39:44 +00004090 Type *Params[] = { I8X };
4091 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling034b94b2012-12-19 07:18:57 +00004092 AttributeSet Attribute =
Bill Wendling99faa3b2012-12-07 23:16:57 +00004093 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00004094 Attribute::get(C, Attribute::NoUnwind));
John McCall9fbd3182011-06-15 23:37:01 +00004095 RetainAutoreleaseRVCallee =
4096 M->getOrInsertFunction("objc_retainAutoreleaseReturnValue", FTy,
Bill Wendling034b94b2012-12-19 07:18:57 +00004097 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00004098 }
4099 return RetainAutoreleaseRVCallee;
4100}
4101
Dan Gohman447989c2012-04-27 18:56:31 +00004102/// ContractAutorelease - Merge an autorelease with a retain into a fused call.
John McCall9fbd3182011-06-15 23:37:01 +00004103bool
4104ObjCARCContract::ContractAutorelease(Function &F, Instruction *Autorelease,
4105 InstructionClass Class,
4106 SmallPtrSet<Instruction *, 4>
4107 &DependingInstructions,
4108 SmallPtrSet<const BasicBlock *, 4>
4109 &Visited) {
4110 const Value *Arg = GetObjCArg(Autorelease);
4111
4112 // Check that there are no instructions between the retain and the autorelease
4113 // (such as an autorelease_pop) which may change the count.
4114 CallInst *Retain = 0;
4115 if (Class == IC_AutoreleaseRV)
4116 FindDependencies(RetainAutoreleaseRVDep, Arg,
4117 Autorelease->getParent(), Autorelease,
4118 DependingInstructions, Visited, PA);
4119 else
4120 FindDependencies(RetainAutoreleaseDep, Arg,
4121 Autorelease->getParent(), Autorelease,
4122 DependingInstructions, Visited, PA);
4123
4124 Visited.clear();
4125 if (DependingInstructions.size() != 1) {
4126 DependingInstructions.clear();
4127 return false;
4128 }
4129
4130 Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
4131 DependingInstructions.clear();
4132
4133 if (!Retain ||
4134 GetBasicInstructionClass(Retain) != IC_Retain ||
4135 GetObjCArg(Retain) != Arg)
4136 return false;
4137
4138 Changed = true;
4139 ++NumPeeps;
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004140
Michael Gottesman916d52a2013-01-07 00:31:26 +00004141 DEBUG(dbgs() << "ObjCARCContract::ContractAutorelease: Fusing "
4142 "retain/autorelease. Erasing: " << *Autorelease << "\n"
4143 " Old Retain: "
4144 << *Retain << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004145
John McCall9fbd3182011-06-15 23:37:01 +00004146 if (Class == IC_AutoreleaseRV)
4147 Retain->setCalledFunction(getRetainAutoreleaseRVCallee(F.getParent()));
4148 else
4149 Retain->setCalledFunction(getRetainAutoreleaseCallee(F.getParent()));
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004150
Michael Gottesman916d52a2013-01-07 00:31:26 +00004151 DEBUG(dbgs() << " New Retain: "
4152 << *Retain << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004153
John McCall9fbd3182011-06-15 23:37:01 +00004154 EraseInstruction(Autorelease);
4155 return true;
4156}
4157
4158/// ContractRelease - Attempt to merge an objc_release with a store, load, and
4159/// objc_retain to form an objc_storeStrong. This can be a little tricky because
4160/// the instructions don't always appear in order, and there may be unrelated
4161/// intervening instructions.
4162void ObjCARCContract::ContractRelease(Instruction *Release,
4163 inst_iterator &Iter) {
4164 LoadInst *Load = dyn_cast<LoadInst>(GetObjCArg(Release));
Eli Friedman2bc3d522011-09-12 20:23:13 +00004165 if (!Load || !Load->isSimple()) return;
John McCall9fbd3182011-06-15 23:37:01 +00004166
4167 // For now, require everything to be in one basic block.
4168 BasicBlock *BB = Release->getParent();
4169 if (Load->getParent() != BB) return;
4170
Dan Gohman4670dac2012-05-08 23:34:08 +00004171 // Walk down to find the store and the release, which may be in either order.
Dan Gohman95b8cf12012-05-09 23:08:33 +00004172 BasicBlock::iterator I = Load, End = BB->end();
John McCall9fbd3182011-06-15 23:37:01 +00004173 ++I;
4174 AliasAnalysis::Location Loc = AA->getLocation(Load);
Dan Gohman4670dac2012-05-08 23:34:08 +00004175 StoreInst *Store = 0;
4176 bool SawRelease = false;
4177 for (; !Store || !SawRelease; ++I) {
Dan Gohman95b8cf12012-05-09 23:08:33 +00004178 if (I == End)
4179 return;
4180
Dan Gohman4670dac2012-05-08 23:34:08 +00004181 Instruction *Inst = I;
4182 if (Inst == Release) {
4183 SawRelease = true;
4184 continue;
4185 }
4186
4187 InstructionClass Class = GetBasicInstructionClass(Inst);
4188
4189 // Unrelated retains are harmless.
4190 if (IsRetain(Class))
4191 continue;
4192
4193 if (Store) {
4194 // The store is the point where we're going to put the objc_storeStrong,
4195 // so make sure there are no uses after it.
4196 if (CanUse(Inst, Load, PA, Class))
4197 return;
4198 } else if (AA->getModRefInfo(Inst, Loc) & AliasAnalysis::Mod) {
4199 // We are moving the load down to the store, so check for anything
4200 // else which writes to the memory between the load and the store.
4201 Store = dyn_cast<StoreInst>(Inst);
4202 if (!Store || !Store->isSimple()) return;
4203 if (Store->getPointerOperand() != Loc.Ptr) return;
4204 }
4205 }
John McCall9fbd3182011-06-15 23:37:01 +00004206
4207 Value *New = StripPointerCastsAndObjCCalls(Store->getValueOperand());
4208
4209 // Walk up to find the retain.
4210 I = Store;
4211 BasicBlock::iterator Begin = BB->begin();
4212 while (I != Begin && GetBasicInstructionClass(I) != IC_Retain)
4213 --I;
4214 Instruction *Retain = I;
4215 if (GetBasicInstructionClass(Retain) != IC_Retain) return;
4216 if (GetObjCArg(Retain) != New) return;
4217
4218 Changed = true;
4219 ++NumStoreStrongs;
4220
4221 LLVMContext &C = Release->getContext();
Chris Lattnerdb125cf2011-07-18 04:54:35 +00004222 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
4223 Type *I8XX = PointerType::getUnqual(I8X);
John McCall9fbd3182011-06-15 23:37:01 +00004224
4225 Value *Args[] = { Load->getPointerOperand(), New };
4226 if (Args[0]->getType() != I8XX)
4227 Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
4228 if (Args[1]->getType() != I8X)
4229 Args[1] = new BitCastInst(Args[1], I8X, "", Store);
4230 CallInst *StoreStrong =
4231 CallInst::Create(getStoreStrongCallee(BB->getParent()->getParent()),
Jay Foada3efbb12011-07-15 08:37:34 +00004232 Args, "", Store);
John McCall9fbd3182011-06-15 23:37:01 +00004233 StoreStrong->setDoesNotThrow();
4234 StoreStrong->setDebugLoc(Store->getDebugLoc());
4235
Dan Gohman0cdece42012-01-19 19:14:36 +00004236 // We can't set the tail flag yet, because we haven't yet determined
4237 // whether there are any escaping allocas. Remember this call, so that
4238 // we can set the tail flag once we know it's safe.
4239 StoreStrongCalls.insert(StoreStrong);
4240
John McCall9fbd3182011-06-15 23:37:01 +00004241 if (&*Iter == Store) ++Iter;
4242 Store->eraseFromParent();
4243 Release->eraseFromParent();
4244 EraseInstruction(Retain);
4245 if (Load->use_empty())
4246 Load->eraseFromParent();
4247}
4248
4249bool ObjCARCContract::doInitialization(Module &M) {
Dan Gohmand6bf2012012-04-13 18:57:48 +00004250 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00004251 Run = ModuleHasARC(M);
4252 if (!Run)
4253 return false;
4254
John McCall9fbd3182011-06-15 23:37:01 +00004255 // These are initialized lazily.
4256 StoreStrongCallee = 0;
4257 RetainAutoreleaseCallee = 0;
4258 RetainAutoreleaseRVCallee = 0;
4259
4260 // Initialize RetainRVMarker.
4261 RetainRVMarker = 0;
4262 if (NamedMDNode *NMD =
4263 M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker"))
4264 if (NMD->getNumOperands() == 1) {
4265 const MDNode *N = NMD->getOperand(0);
4266 if (N->getNumOperands() == 1)
4267 if (const MDString *S = dyn_cast<MDString>(N->getOperand(0)))
4268 RetainRVMarker = S;
4269 }
4270
4271 return false;
4272}
4273
4274bool ObjCARCContract::runOnFunction(Function &F) {
4275 if (!EnableARCOpts)
4276 return false;
4277
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00004278 // If nothing in the Module uses ARC, don't do anything.
4279 if (!Run)
4280 return false;
4281
John McCall9fbd3182011-06-15 23:37:01 +00004282 Changed = false;
4283 AA = &getAnalysis<AliasAnalysis>();
4284 DT = &getAnalysis<DominatorTree>();
4285
4286 PA.setAA(&getAnalysis<AliasAnalysis>());
4287
Dan Gohman0cdece42012-01-19 19:14:36 +00004288 // Track whether it's ok to mark objc_storeStrong calls with the "tail"
4289 // keyword. Be conservative if the function has variadic arguments.
4290 // It seems that functions which "return twice" are also unsafe for the
4291 // "tail" argument, because they are setjmp, which could need to
4292 // return to an earlier stack state.
Dan Gohman0daef3d2012-05-08 23:39:44 +00004293 bool TailOkForStoreStrongs = !F.isVarArg() &&
4294 !F.callsFunctionThatReturnsTwice();
Dan Gohman0cdece42012-01-19 19:14:36 +00004295
John McCall9fbd3182011-06-15 23:37:01 +00004296 // For ObjC library calls which return their argument, replace uses of the
4297 // argument with uses of the call return value, if it dominates the use. This
4298 // reduces register pressure.
4299 SmallPtrSet<Instruction *, 4> DependingInstructions;
4300 SmallPtrSet<const BasicBlock *, 4> Visited;
4301 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
4302 Instruction *Inst = &*I++;
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004303
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00004304 DEBUG(dbgs() << "ObjCARCContract: Visiting: " << *Inst << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004305
John McCall9fbd3182011-06-15 23:37:01 +00004306 // Only these library routines return their argument. In particular,
4307 // objc_retainBlock does not necessarily return its argument.
4308 InstructionClass Class = GetBasicInstructionClass(Inst);
4309 switch (Class) {
4310 case IC_Retain:
4311 case IC_FusedRetainAutorelease:
4312 case IC_FusedRetainAutoreleaseRV:
4313 break;
4314 case IC_Autorelease:
4315 case IC_AutoreleaseRV:
4316 if (ContractAutorelease(F, Inst, Class, DependingInstructions, Visited))
4317 continue;
4318 break;
4319 case IC_RetainRV: {
4320 // If we're compiling for a target which needs a special inline-asm
4321 // marker to do the retainAutoreleasedReturnValue optimization,
4322 // insert it now.
4323 if (!RetainRVMarker)
4324 break;
4325 BasicBlock::iterator BBI = Inst;
Dan Gohman58fb3402012-06-25 19:47:37 +00004326 BasicBlock *InstParent = Inst->getParent();
4327
4328 // Step up to see if the call immediately precedes the RetainRV call.
4329 // If it's an invoke, we have to cross a block boundary. And we have
4330 // to carefully dodge no-op instructions.
4331 do {
4332 if (&*BBI == InstParent->begin()) {
4333 BasicBlock *Pred = InstParent->getSinglePredecessor();
4334 if (!Pred)
4335 goto decline_rv_optimization;
4336 BBI = Pred->getTerminator();
4337 break;
4338 }
4339 --BBI;
4340 } while (isNoopInstruction(BBI));
4341
John McCall9fbd3182011-06-15 23:37:01 +00004342 if (&*BBI == GetObjCArg(Inst)) {
Michael Gottesman50652cd2013-01-03 07:32:41 +00004343 DEBUG(dbgs() << "ObjCARCContract: Adding inline asm marker for "
Michael Gottesman5c0ae472013-01-04 21:29:57 +00004344 "retainAutoreleasedReturnValue optimization.\n");
Dan Gohmand6bf2012012-04-13 18:57:48 +00004345 Changed = true;
John McCall9fbd3182011-06-15 23:37:01 +00004346 InlineAsm *IA =
4347 InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()),
4348 /*isVarArg=*/false),
4349 RetainRVMarker->getString(),
4350 /*Constraints=*/"", /*hasSideEffects=*/true);
4351 CallInst::Create(IA, "", Inst);
4352 }
Dan Gohman58fb3402012-06-25 19:47:37 +00004353 decline_rv_optimization:
John McCall9fbd3182011-06-15 23:37:01 +00004354 break;
4355 }
4356 case IC_InitWeak: {
4357 // objc_initWeak(p, null) => *p = null
4358 CallInst *CI = cast<CallInst>(Inst);
4359 if (isNullOrUndef(CI->getArgOperand(1))) {
4360 Value *Null =
4361 ConstantPointerNull::get(cast<PointerType>(CI->getType()));
4362 Changed = true;
4363 new StoreInst(Null, CI->getArgOperand(0), CI);
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004364
Michael Gottesman1ebbdcf2013-01-03 07:32:53 +00004365 DEBUG(dbgs() << "OBJCARCContract: Old = " << *CI << "\n"
4366 << " New = " << *Null << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004367
John McCall9fbd3182011-06-15 23:37:01 +00004368 CI->replaceAllUsesWith(Null);
4369 CI->eraseFromParent();
4370 }
4371 continue;
4372 }
4373 case IC_Release:
4374 ContractRelease(Inst, I);
4375 continue;
Dan Gohman0cdece42012-01-19 19:14:36 +00004376 case IC_User:
4377 // Be conservative if the function has any alloca instructions.
4378 // Technically we only care about escaping alloca instructions,
4379 // but this is sufficient to handle some interesting cases.
4380 if (isa<AllocaInst>(Inst))
4381 TailOkForStoreStrongs = false;
4382 continue;
John McCall9fbd3182011-06-15 23:37:01 +00004383 default:
4384 continue;
4385 }
4386
Michael Gottesmanec21e2a2013-01-03 08:09:27 +00004387 DEBUG(dbgs() << "ObjCARCContract: Finished List.\n\n");
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00004388
John McCall9fbd3182011-06-15 23:37:01 +00004389 // Don't use GetObjCArg because we don't want to look through bitcasts
4390 // and such; to do the replacement, the argument must have type i8*.
4391 const Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
4392 for (;;) {
4393 // If we're compiling bugpointed code, don't get in trouble.
4394 if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
4395 break;
4396 // Look through the uses of the pointer.
4397 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
4398 UI != UE; ) {
4399 Use &U = UI.getUse();
4400 unsigned OperandNo = UI.getOperandNo();
4401 ++UI; // Increment UI now, because we may unlink its element.
Dan Gohmand6bf2012012-04-13 18:57:48 +00004402
4403 // If the call's return value dominates a use of the call's argument
4404 // value, rewrite the use to use the return value. We check for
4405 // reachability here because an unreachable call is considered to
4406 // trivially dominate itself, which would lead us to rewriting its
4407 // argument in terms of its return value, which would lead to
4408 // infinite loops in GetObjCArg.
Dan Gohman0daef3d2012-05-08 23:39:44 +00004409 if (DT->isReachableFromEntry(U) && DT->dominates(Inst, U)) {
Rafael Espindola2453dff2012-03-15 15:52:59 +00004410 Changed = true;
4411 Instruction *Replacement = Inst;
4412 Type *UseTy = U.get()->getType();
Dan Gohman6c189ec2012-04-13 01:08:28 +00004413 if (PHINode *PHI = dyn_cast<PHINode>(U.getUser())) {
Rafael Espindola2453dff2012-03-15 15:52:59 +00004414 // For PHI nodes, insert the bitcast in the predecessor block.
Dan Gohman0daef3d2012-05-08 23:39:44 +00004415 unsigned ValNo = PHINode::getIncomingValueNumForOperand(OperandNo);
4416 BasicBlock *BB = PHI->getIncomingBlock(ValNo);
Rafael Espindola2453dff2012-03-15 15:52:59 +00004417 if (Replacement->getType() != UseTy)
4418 Replacement = new BitCastInst(Replacement, UseTy, "",
4419 &BB->back());
Dan Gohmand6bf2012012-04-13 18:57:48 +00004420 // While we're here, rewrite all edges for this PHI, rather
4421 // than just one use at a time, to minimize the number of
4422 // bitcasts we emit.
Dan Gohman447989c2012-04-27 18:56:31 +00004423 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
Rafael Espindola2453dff2012-03-15 15:52:59 +00004424 if (PHI->getIncomingBlock(i) == BB) {
4425 // Keep the UI iterator valid.
4426 if (&PHI->getOperandUse(
4427 PHINode::getOperandNumForIncomingValue(i)) ==
4428 &UI.getUse())
4429 ++UI;
4430 PHI->setIncomingValue(i, Replacement);
4431 }
4432 } else {
4433 if (Replacement->getType() != UseTy)
Dan Gohman6c189ec2012-04-13 01:08:28 +00004434 Replacement = new BitCastInst(Replacement, UseTy, "",
4435 cast<Instruction>(U.getUser()));
Rafael Espindola2453dff2012-03-15 15:52:59 +00004436 U.set(Replacement);
John McCall9fbd3182011-06-15 23:37:01 +00004437 }
Rafael Espindola2453dff2012-03-15 15:52:59 +00004438 }
John McCall9fbd3182011-06-15 23:37:01 +00004439 }
4440
Dan Gohman447989c2012-04-27 18:56:31 +00004441 // If Arg is a no-op casted pointer, strip one level of casts and iterate.
John McCall9fbd3182011-06-15 23:37:01 +00004442 if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
4443 Arg = BI->getOperand(0);
4444 else if (isa<GEPOperator>(Arg) &&
4445 cast<GEPOperator>(Arg)->hasAllZeroIndices())
4446 Arg = cast<GEPOperator>(Arg)->getPointerOperand();
4447 else if (isa<GlobalAlias>(Arg) &&
4448 !cast<GlobalAlias>(Arg)->mayBeOverridden())
4449 Arg = cast<GlobalAlias>(Arg)->getAliasee();
4450 else
4451 break;
4452 }
4453 }
4454
Dan Gohman0cdece42012-01-19 19:14:36 +00004455 // If this function has no escaping allocas or suspicious vararg usage,
4456 // objc_storeStrong calls can be marked with the "tail" keyword.
4457 if (TailOkForStoreStrongs)
Dan Gohman0daef3d2012-05-08 23:39:44 +00004458 for (SmallPtrSet<CallInst *, 8>::iterator I = StoreStrongCalls.begin(),
Dan Gohman0cdece42012-01-19 19:14:36 +00004459 E = StoreStrongCalls.end(); I != E; ++I)
4460 (*I)->setTailCall();
4461 StoreStrongCalls.clear();
4462
John McCall9fbd3182011-06-15 23:37:01 +00004463 return Changed;
4464}