blob: 37af1f5affd86108d684a764968ac2e2df94b50d [file] [log] [blame]
John McCall9fbd3182011-06-15 23:37:01 +00001//===- ObjCARC.cpp - ObjC ARC Optimization --------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines ObjC ARC optimizations. ARC stands for
11// Automatic Reference Counting and is a system for managing reference counts
12// for objects in Objective C.
13//
14// The optimizations performed include elimination of redundant, partially
15// redundant, and inconsequential reference count operations, elimination of
16// redundant weak pointer operations, pattern-matching and replacement of
17// low-level operations into higher-level operations, and numerous minor
18// simplifications.
19//
20// This file also defines a simple ARC-aware AliasAnalysis.
21//
22// WARNING: This file knows about certain library functions. It recognizes them
Chris Lattner55dc5c72012-05-27 19:37:05 +000023// by name, and hardwires knowledge of their semantics.
John McCall9fbd3182011-06-15 23:37:01 +000024//
25// WARNING: This file knows about how certain Objective-C library functions are
26// used. Naive LLVM IR transformations which would otherwise be
27// behavior-preserving may break these assumptions.
28//
29//===----------------------------------------------------------------------===//
30
31#define DEBUG_TYPE "objc-arc"
John McCall9fbd3182011-06-15 23:37:01 +000032#include "llvm/ADT/DenseMap.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000033#include "llvm/Support/CommandLine.h"
Chandler Carruth58a2cbe2013-01-02 10:22:59 +000034#include "llvm/Support/Debug.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000035#include "llvm/Support/raw_ostream.h"
John McCall9fbd3182011-06-15 23:37:01 +000036using namespace llvm;
37
38// A handy option to enable/disable all optimizations in this file.
39static cl::opt<bool> EnableARCOpts("enable-objc-arc-opts", cl::init(true));
40
41//===----------------------------------------------------------------------===//
42// Misc. Utilities
43//===----------------------------------------------------------------------===//
44
45namespace {
46 /// MapVector - An associative container with fast insertion-order
47 /// (deterministic) iteration over its elements. Plus the special
48 /// blot operation.
49 template<class KeyT, class ValueT>
50 class MapVector {
51 /// Map - Map keys to indices in Vector.
52 typedef DenseMap<KeyT, size_t> MapTy;
53 MapTy Map;
54
55 /// Vector - Keys and values.
56 typedef std::vector<std::pair<KeyT, ValueT> > VectorTy;
57 VectorTy Vector;
58
59 public:
60 typedef typename VectorTy::iterator iterator;
61 typedef typename VectorTy::const_iterator const_iterator;
62 iterator begin() { return Vector.begin(); }
63 iterator end() { return Vector.end(); }
64 const_iterator begin() const { return Vector.begin(); }
65 const_iterator end() const { return Vector.end(); }
66
67#ifdef XDEBUG
68 ~MapVector() {
69 assert(Vector.size() >= Map.size()); // May differ due to blotting.
70 for (typename MapTy::const_iterator I = Map.begin(), E = Map.end();
71 I != E; ++I) {
72 assert(I->second < Vector.size());
73 assert(Vector[I->second].first == I->first);
74 }
75 for (typename VectorTy::const_iterator I = Vector.begin(),
76 E = Vector.end(); I != E; ++I)
77 assert(!I->first ||
78 (Map.count(I->first) &&
79 Map[I->first] == size_t(I - Vector.begin())));
80 }
81#endif
82
Dan Gohman22cc4cc2012-03-02 01:13:53 +000083 ValueT &operator[](const KeyT &Arg) {
John McCall9fbd3182011-06-15 23:37:01 +000084 std::pair<typename MapTy::iterator, bool> Pair =
85 Map.insert(std::make_pair(Arg, size_t(0)));
86 if (Pair.second) {
Dan Gohman22cc4cc2012-03-02 01:13:53 +000087 size_t Num = Vector.size();
88 Pair.first->second = Num;
John McCall9fbd3182011-06-15 23:37:01 +000089 Vector.push_back(std::make_pair(Arg, ValueT()));
Dan Gohman22cc4cc2012-03-02 01:13:53 +000090 return Vector[Num].second;
John McCall9fbd3182011-06-15 23:37:01 +000091 }
92 return Vector[Pair.first->second].second;
93 }
94
95 std::pair<iterator, bool>
96 insert(const std::pair<KeyT, ValueT> &InsertPair) {
97 std::pair<typename MapTy::iterator, bool> Pair =
98 Map.insert(std::make_pair(InsertPair.first, size_t(0)));
99 if (Pair.second) {
Dan Gohman22cc4cc2012-03-02 01:13:53 +0000100 size_t Num = Vector.size();
101 Pair.first->second = Num;
John McCall9fbd3182011-06-15 23:37:01 +0000102 Vector.push_back(InsertPair);
Dan Gohman22cc4cc2012-03-02 01:13:53 +0000103 return std::make_pair(Vector.begin() + Num, true);
John McCall9fbd3182011-06-15 23:37:01 +0000104 }
105 return std::make_pair(Vector.begin() + Pair.first->second, false);
106 }
107
Dan Gohman22cc4cc2012-03-02 01:13:53 +0000108 const_iterator find(const KeyT &Key) const {
John McCall9fbd3182011-06-15 23:37:01 +0000109 typename MapTy::const_iterator It = Map.find(Key);
110 if (It == Map.end()) return Vector.end();
111 return Vector.begin() + It->second;
112 }
113
114 /// blot - This is similar to erase, but instead of removing the element
115 /// from the vector, it just zeros out the key in the vector. This leaves
116 /// iterators intact, but clients must be prepared for zeroed-out keys when
117 /// iterating.
Dan Gohman22cc4cc2012-03-02 01:13:53 +0000118 void blot(const KeyT &Key) {
John McCall9fbd3182011-06-15 23:37:01 +0000119 typename MapTy::iterator It = Map.find(Key);
120 if (It == Map.end()) return;
121 Vector[It->second].first = KeyT();
122 Map.erase(It);
123 }
124
125 void clear() {
126 Map.clear();
127 Vector.clear();
128 }
129 };
130}
131
132//===----------------------------------------------------------------------===//
133// ARC Utilities.
134//===----------------------------------------------------------------------===//
135
Chandler Carruthd04a8d42012-12-03 16:50:05 +0000136#include "llvm/ADT/StringSwitch.h"
137#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +0000138#include "llvm/IR/Intrinsics.h"
139#include "llvm/IR/Module.h"
Dan Gohman0daef3d2012-05-08 23:39:44 +0000140#include "llvm/Support/CallSite.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +0000141#include "llvm/Transforms/Utils/Local.h"
Dan Gohman0daef3d2012-05-08 23:39:44 +0000142
John McCall9fbd3182011-06-15 23:37:01 +0000143namespace {
144 /// InstructionClass - A simple classification for instructions.
145 enum InstructionClass {
146 IC_Retain, ///< objc_retain
147 IC_RetainRV, ///< objc_retainAutoreleasedReturnValue
148 IC_RetainBlock, ///< objc_retainBlock
149 IC_Release, ///< objc_release
150 IC_Autorelease, ///< objc_autorelease
151 IC_AutoreleaseRV, ///< objc_autoreleaseReturnValue
152 IC_AutoreleasepoolPush, ///< objc_autoreleasePoolPush
153 IC_AutoreleasepoolPop, ///< objc_autoreleasePoolPop
154 IC_NoopCast, ///< objc_retainedObject, etc.
155 IC_FusedRetainAutorelease, ///< objc_retainAutorelease
156 IC_FusedRetainAutoreleaseRV, ///< objc_retainAutoreleaseReturnValue
157 IC_LoadWeakRetained, ///< objc_loadWeakRetained (primitive)
158 IC_StoreWeak, ///< objc_storeWeak (primitive)
159 IC_InitWeak, ///< objc_initWeak (derived)
160 IC_LoadWeak, ///< objc_loadWeak (derived)
161 IC_MoveWeak, ///< objc_moveWeak (derived)
162 IC_CopyWeak, ///< objc_copyWeak (derived)
163 IC_DestroyWeak, ///< objc_destroyWeak (derived)
Dan Gohman44234772012-04-13 18:28:58 +0000164 IC_StoreStrong, ///< objc_storeStrong (derived)
John McCall9fbd3182011-06-15 23:37:01 +0000165 IC_CallOrUser, ///< could call objc_release and/or "use" pointers
166 IC_Call, ///< could call objc_release
167 IC_User, ///< could "use" a pointer
168 IC_None ///< anything else
169 };
170}
171
172/// IsPotentialUse - Test whether the given value is possible a
173/// reference-counted pointer.
174static bool IsPotentialUse(const Value *Op) {
175 // Pointers to static or stack storage are not reference-counted pointers.
176 if (isa<Constant>(Op) || isa<AllocaInst>(Op))
177 return false;
178 // Special arguments are not reference-counted.
179 if (const Argument *Arg = dyn_cast<Argument>(Op))
180 if (Arg->hasByValAttr() ||
181 Arg->hasNestAttr() ||
182 Arg->hasStructRetAttr())
183 return false;
Dan Gohmanf9096e42011-12-14 19:10:53 +0000184 // Only consider values with pointer types.
185 // It seemes intuitive to exclude function pointer types as well, since
186 // functions are never reference-counted, however clang occasionally
187 // bitcasts reference-counted pointers to function-pointer type
188 // temporarily.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000189 PointerType *Ty = dyn_cast<PointerType>(Op->getType());
Dan Gohmanf9096e42011-12-14 19:10:53 +0000190 if (!Ty)
John McCall9fbd3182011-06-15 23:37:01 +0000191 return false;
192 // Conservatively assume anything else is a potential use.
193 return true;
194}
195
196/// GetCallSiteClass - Helper for GetInstructionClass. Determines what kind
197/// of construct CS is.
198static InstructionClass GetCallSiteClass(ImmutableCallSite CS) {
199 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
200 I != E; ++I)
201 if (IsPotentialUse(*I))
202 return CS.onlyReadsMemory() ? IC_User : IC_CallOrUser;
203
204 return CS.onlyReadsMemory() ? IC_None : IC_Call;
205}
206
207/// GetFunctionClass - Determine if F is one of the special known Functions.
208/// If it isn't, return IC_CallOrUser.
209static InstructionClass GetFunctionClass(const Function *F) {
210 Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
211
212 // No arguments.
213 if (AI == AE)
214 return StringSwitch<InstructionClass>(F->getName())
215 .Case("objc_autoreleasePoolPush", IC_AutoreleasepoolPush)
216 .Default(IC_CallOrUser);
217
218 // One argument.
219 const Argument *A0 = AI++;
220 if (AI == AE)
221 // Argument is a pointer.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000222 if (PointerType *PTy = dyn_cast<PointerType>(A0->getType())) {
223 Type *ETy = PTy->getElementType();
John McCall9fbd3182011-06-15 23:37:01 +0000224 // Argument is i8*.
225 if (ETy->isIntegerTy(8))
226 return StringSwitch<InstructionClass>(F->getName())
227 .Case("objc_retain", IC_Retain)
228 .Case("objc_retainAutoreleasedReturnValue", IC_RetainRV)
229 .Case("objc_retainBlock", IC_RetainBlock)
230 .Case("objc_release", IC_Release)
231 .Case("objc_autorelease", IC_Autorelease)
232 .Case("objc_autoreleaseReturnValue", IC_AutoreleaseRV)
233 .Case("objc_autoreleasePoolPop", IC_AutoreleasepoolPop)
234 .Case("objc_retainedObject", IC_NoopCast)
235 .Case("objc_unretainedObject", IC_NoopCast)
236 .Case("objc_unretainedPointer", IC_NoopCast)
237 .Case("objc_retain_autorelease", IC_FusedRetainAutorelease)
238 .Case("objc_retainAutorelease", IC_FusedRetainAutorelease)
239 .Case("objc_retainAutoreleaseReturnValue",IC_FusedRetainAutoreleaseRV)
240 .Default(IC_CallOrUser);
241
242 // Argument is i8**
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000243 if (PointerType *Pte = dyn_cast<PointerType>(ETy))
John McCall9fbd3182011-06-15 23:37:01 +0000244 if (Pte->getElementType()->isIntegerTy(8))
245 return StringSwitch<InstructionClass>(F->getName())
246 .Case("objc_loadWeakRetained", IC_LoadWeakRetained)
247 .Case("objc_loadWeak", IC_LoadWeak)
248 .Case("objc_destroyWeak", IC_DestroyWeak)
249 .Default(IC_CallOrUser);
250 }
251
252 // Two arguments, first is i8**.
253 const Argument *A1 = AI++;
254 if (AI == AE)
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000255 if (PointerType *PTy = dyn_cast<PointerType>(A0->getType()))
256 if (PointerType *Pte = dyn_cast<PointerType>(PTy->getElementType()))
John McCall9fbd3182011-06-15 23:37:01 +0000257 if (Pte->getElementType()->isIntegerTy(8))
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000258 if (PointerType *PTy1 = dyn_cast<PointerType>(A1->getType())) {
259 Type *ETy1 = PTy1->getElementType();
John McCall9fbd3182011-06-15 23:37:01 +0000260 // Second argument is i8*
261 if (ETy1->isIntegerTy(8))
262 return StringSwitch<InstructionClass>(F->getName())
263 .Case("objc_storeWeak", IC_StoreWeak)
264 .Case("objc_initWeak", IC_InitWeak)
Dan Gohman44234772012-04-13 18:28:58 +0000265 .Case("objc_storeStrong", IC_StoreStrong)
John McCall9fbd3182011-06-15 23:37:01 +0000266 .Default(IC_CallOrUser);
267 // Second argument is i8**.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000268 if (PointerType *Pte1 = dyn_cast<PointerType>(ETy1))
John McCall9fbd3182011-06-15 23:37:01 +0000269 if (Pte1->getElementType()->isIntegerTy(8))
270 return StringSwitch<InstructionClass>(F->getName())
271 .Case("objc_moveWeak", IC_MoveWeak)
272 .Case("objc_copyWeak", IC_CopyWeak)
273 .Default(IC_CallOrUser);
274 }
275
276 // Anything else.
277 return IC_CallOrUser;
278}
279
280/// GetInstructionClass - Determine what kind of construct V is.
281static InstructionClass GetInstructionClass(const Value *V) {
282 if (const Instruction *I = dyn_cast<Instruction>(V)) {
283 // Any instruction other than bitcast and gep with a pointer operand have a
284 // use of an objc pointer. Bitcasts, GEPs, Selects, PHIs transfer a pointer
285 // to a subsequent use, rather than using it themselves, in this sense.
286 // As a short cut, several other opcodes are known to have no pointer
287 // operands of interest. And ret is never followed by a release, so it's
288 // not interesting to examine.
289 switch (I->getOpcode()) {
290 case Instruction::Call: {
291 const CallInst *CI = cast<CallInst>(I);
292 // Check for calls to special functions.
293 if (const Function *F = CI->getCalledFunction()) {
294 InstructionClass Class = GetFunctionClass(F);
295 if (Class != IC_CallOrUser)
296 return Class;
297
298 // None of the intrinsic functions do objc_release. For intrinsics, the
299 // only question is whether or not they may be users.
300 switch (F->getIntrinsicID()) {
John McCall9fbd3182011-06-15 23:37:01 +0000301 case Intrinsic::returnaddress: case Intrinsic::frameaddress:
302 case Intrinsic::stacksave: case Intrinsic::stackrestore:
303 case Intrinsic::vastart: case Intrinsic::vacopy: case Intrinsic::vaend:
Dan Gohman0daef3d2012-05-08 23:39:44 +0000304 case Intrinsic::objectsize: case Intrinsic::prefetch:
305 case Intrinsic::stackprotector:
306 case Intrinsic::eh_return_i32: case Intrinsic::eh_return_i64:
307 case Intrinsic::eh_typeid_for: case Intrinsic::eh_dwarf_cfa:
308 case Intrinsic::eh_sjlj_lsda: case Intrinsic::eh_sjlj_functioncontext:
309 case Intrinsic::init_trampoline: case Intrinsic::adjust_trampoline:
310 case Intrinsic::lifetime_start: case Intrinsic::lifetime_end:
311 case Intrinsic::invariant_start: case Intrinsic::invariant_end:
John McCall9fbd3182011-06-15 23:37:01 +0000312 // Don't let dbg info affect our results.
313 case Intrinsic::dbg_declare: case Intrinsic::dbg_value:
314 // Short cut: Some intrinsics obviously don't use ObjC pointers.
315 return IC_None;
316 default:
Dan Gohman0daef3d2012-05-08 23:39:44 +0000317 break;
John McCall9fbd3182011-06-15 23:37:01 +0000318 }
319 }
320 return GetCallSiteClass(CI);
321 }
322 case Instruction::Invoke:
323 return GetCallSiteClass(cast<InvokeInst>(I));
324 case Instruction::BitCast:
325 case Instruction::GetElementPtr:
326 case Instruction::Select: case Instruction::PHI:
327 case Instruction::Ret: case Instruction::Br:
328 case Instruction::Switch: case Instruction::IndirectBr:
329 case Instruction::Alloca: case Instruction::VAArg:
330 case Instruction::Add: case Instruction::FAdd:
331 case Instruction::Sub: case Instruction::FSub:
332 case Instruction::Mul: case Instruction::FMul:
333 case Instruction::SDiv: case Instruction::UDiv: case Instruction::FDiv:
334 case Instruction::SRem: case Instruction::URem: case Instruction::FRem:
335 case Instruction::Shl: case Instruction::LShr: case Instruction::AShr:
336 case Instruction::And: case Instruction::Or: case Instruction::Xor:
337 case Instruction::SExt: case Instruction::ZExt: case Instruction::Trunc:
338 case Instruction::IntToPtr: case Instruction::FCmp:
339 case Instruction::FPTrunc: case Instruction::FPExt:
340 case Instruction::FPToUI: case Instruction::FPToSI:
341 case Instruction::UIToFP: case Instruction::SIToFP:
342 case Instruction::InsertElement: case Instruction::ExtractElement:
343 case Instruction::ShuffleVector:
344 case Instruction::ExtractValue:
345 break;
346 case Instruction::ICmp:
347 // Comparing a pointer with null, or any other constant, isn't an
348 // interesting use, because we don't care what the pointer points to, or
349 // about the values of any other dynamic reference-counted pointers.
350 if (IsPotentialUse(I->getOperand(1)))
351 return IC_User;
352 break;
353 default:
354 // For anything else, check all the operands.
Dan Gohmand4464602011-08-22 17:29:37 +0000355 // Note that this includes both operands of a Store: while the first
356 // operand isn't actually being dereferenced, it is being stored to
357 // memory where we can no longer track who might read it and dereference
358 // it, so we have to consider it potentially used.
John McCall9fbd3182011-06-15 23:37:01 +0000359 for (User::const_op_iterator OI = I->op_begin(), OE = I->op_end();
360 OI != OE; ++OI)
361 if (IsPotentialUse(*OI))
362 return IC_User;
363 }
364 }
365
366 // Otherwise, it's totally inert for ARC purposes.
367 return IC_None;
368}
369
370/// GetBasicInstructionClass - Determine what kind of construct V is. This is
371/// similar to GetInstructionClass except that it only detects objc runtine
372/// calls. This allows it to be faster.
373static InstructionClass GetBasicInstructionClass(const Value *V) {
374 if (const CallInst *CI = dyn_cast<CallInst>(V)) {
375 if (const Function *F = CI->getCalledFunction())
376 return GetFunctionClass(F);
377 // Otherwise, be conservative.
378 return IC_CallOrUser;
379 }
380
381 // Otherwise, be conservative.
Dan Gohman2f6263c2012-01-17 20:52:24 +0000382 return isa<InvokeInst>(V) ? IC_CallOrUser : IC_User;
John McCall9fbd3182011-06-15 23:37:01 +0000383}
384
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +0000385/// IsRetain - Test if the given class is objc_retain or
John McCall9fbd3182011-06-15 23:37:01 +0000386/// equivalent.
387static bool IsRetain(InstructionClass Class) {
388 return Class == IC_Retain ||
389 Class == IC_RetainRV;
390}
391
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +0000392/// IsAutorelease - Test if the given class is objc_autorelease or
John McCall9fbd3182011-06-15 23:37:01 +0000393/// equivalent.
394static bool IsAutorelease(InstructionClass Class) {
395 return Class == IC_Autorelease ||
396 Class == IC_AutoreleaseRV;
397}
398
399/// IsForwarding - Test if the given class represents instructions which return
400/// their argument verbatim.
401static bool IsForwarding(InstructionClass Class) {
402 // objc_retainBlock technically doesn't always return its argument
403 // verbatim, but it doesn't matter for our purposes here.
404 return Class == IC_Retain ||
405 Class == IC_RetainRV ||
406 Class == IC_Autorelease ||
407 Class == IC_AutoreleaseRV ||
408 Class == IC_RetainBlock ||
409 Class == IC_NoopCast;
410}
411
412/// IsNoopOnNull - Test if the given class represents instructions which do
413/// nothing if passed a null pointer.
414static bool IsNoopOnNull(InstructionClass Class) {
415 return Class == IC_Retain ||
416 Class == IC_RetainRV ||
417 Class == IC_Release ||
418 Class == IC_Autorelease ||
419 Class == IC_AutoreleaseRV ||
420 Class == IC_RetainBlock;
421}
422
423/// IsAlwaysTail - Test if the given class represents instructions which are
424/// always safe to mark with the "tail" keyword.
425static bool IsAlwaysTail(InstructionClass Class) {
426 // IC_RetainBlock may be given a stack argument.
427 return Class == IC_Retain ||
428 Class == IC_RetainRV ||
John McCall9fbd3182011-06-15 23:37:01 +0000429 Class == IC_AutoreleaseRV;
430}
431
Michael Gottesmane8c161a2013-01-12 01:25:15 +0000432/// \brief Test if the given class represents instructions which are never safe
433/// to mark with the "tail" keyword.
434static bool IsNeverTail(InstructionClass Class) {
435 /// It is never safe to tail call objc_autorelease since by tail calling
436 /// objc_autorelease, we also tail call -[NSObject autorelease] which supports
437 /// fast autoreleasing causing our object to be potentially reclaimed from the
438 /// autorelease pool which violates the semantics of __autoreleasing types in
439 /// ARC.
440 return Class == IC_Autorelease;
441}
442
John McCall9fbd3182011-06-15 23:37:01 +0000443/// IsNoThrow - Test if the given class represents instructions which are always
444/// safe to mark with the nounwind attribute..
445static bool IsNoThrow(InstructionClass Class) {
Dan Gohman1d2fd752011-09-14 18:33:34 +0000446 // objc_retainBlock is not nounwind because it calls user copy constructors
447 // which could theoretically throw.
John McCall9fbd3182011-06-15 23:37:01 +0000448 return Class == IC_Retain ||
449 Class == IC_RetainRV ||
John McCall9fbd3182011-06-15 23:37:01 +0000450 Class == IC_Release ||
451 Class == IC_Autorelease ||
452 Class == IC_AutoreleaseRV ||
453 Class == IC_AutoreleasepoolPush ||
454 Class == IC_AutoreleasepoolPop;
455}
456
Dan Gohman447989c2012-04-27 18:56:31 +0000457/// EraseInstruction - Erase the given instruction. Many ObjC calls return their
John McCall9fbd3182011-06-15 23:37:01 +0000458/// argument verbatim, so if it's such a call and the return value has users,
459/// replace them with the argument value.
460static void EraseInstruction(Instruction *CI) {
461 Value *OldArg = cast<CallInst>(CI)->getArgOperand(0);
462
463 bool Unused = CI->use_empty();
464
465 if (!Unused) {
466 // Replace the return value with the argument.
467 assert(IsForwarding(GetBasicInstructionClass(CI)) &&
468 "Can't delete non-forwarding instruction with users!");
469 CI->replaceAllUsesWith(OldArg);
470 }
471
472 CI->eraseFromParent();
473
474 if (Unused)
475 RecursivelyDeleteTriviallyDeadInstructions(OldArg);
476}
477
478/// GetUnderlyingObjCPtr - This is a wrapper around getUnderlyingObject which
479/// also knows how to look through objc_retain and objc_autorelease calls, which
480/// we know to return their argument verbatim.
481static const Value *GetUnderlyingObjCPtr(const Value *V) {
482 for (;;) {
483 V = GetUnderlyingObject(V);
484 if (!IsForwarding(GetBasicInstructionClass(V)))
485 break;
486 V = cast<CallInst>(V)->getArgOperand(0);
487 }
488
489 return V;
490}
491
492/// StripPointerCastsAndObjCCalls - This is a wrapper around
493/// Value::stripPointerCasts which also knows how to look through objc_retain
494/// and objc_autorelease calls, which we know to return their argument verbatim.
495static const Value *StripPointerCastsAndObjCCalls(const Value *V) {
496 for (;;) {
497 V = V->stripPointerCasts();
498 if (!IsForwarding(GetBasicInstructionClass(V)))
499 break;
500 V = cast<CallInst>(V)->getArgOperand(0);
501 }
502 return V;
503}
504
505/// StripPointerCastsAndObjCCalls - This is a wrapper around
506/// Value::stripPointerCasts which also knows how to look through objc_retain
507/// and objc_autorelease calls, which we know to return their argument verbatim.
508static Value *StripPointerCastsAndObjCCalls(Value *V) {
509 for (;;) {
510 V = V->stripPointerCasts();
511 if (!IsForwarding(GetBasicInstructionClass(V)))
512 break;
513 V = cast<CallInst>(V)->getArgOperand(0);
514 }
515 return V;
516}
517
518/// GetObjCArg - Assuming the given instruction is one of the special calls such
519/// as objc_retain or objc_release, return the argument value, stripped of no-op
520/// casts and forwarding calls.
521static Value *GetObjCArg(Value *Inst) {
522 return StripPointerCastsAndObjCCalls(cast<CallInst>(Inst)->getArgOperand(0));
523}
524
525/// IsObjCIdentifiedObject - This is similar to AliasAnalysis'
526/// isObjCIdentifiedObject, except that it uses special knowledge of
527/// ObjC conventions...
528static bool IsObjCIdentifiedObject(const Value *V) {
529 // Assume that call results and arguments have their own "provenance".
530 // Constants (including GlobalVariables) and Allocas are never
531 // reference-counted.
532 if (isa<CallInst>(V) || isa<InvokeInst>(V) ||
533 isa<Argument>(V) || isa<Constant>(V) ||
534 isa<AllocaInst>(V))
535 return true;
536
537 if (const LoadInst *LI = dyn_cast<LoadInst>(V)) {
538 const Value *Pointer =
539 StripPointerCastsAndObjCCalls(LI->getPointerOperand());
540 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Pointer)) {
Dan Gohman1b31ea82011-08-22 17:29:11 +0000541 // A constant pointer can't be pointing to an object on the heap. It may
542 // be reference-counted, but it won't be deleted.
543 if (GV->isConstant())
544 return true;
John McCall9fbd3182011-06-15 23:37:01 +0000545 StringRef Name = GV->getName();
546 // These special variables are known to hold values which are not
547 // reference-counted pointers.
548 if (Name.startswith("\01L_OBJC_SELECTOR_REFERENCES_") ||
549 Name.startswith("\01L_OBJC_CLASSLIST_REFERENCES_") ||
550 Name.startswith("\01L_OBJC_CLASSLIST_SUP_REFS_$_") ||
551 Name.startswith("\01L_OBJC_METH_VAR_NAME_") ||
552 Name.startswith("\01l_objc_msgSend_fixup_"))
553 return true;
554 }
555 }
556
557 return false;
558}
559
560/// FindSingleUseIdentifiedObject - This is similar to
561/// StripPointerCastsAndObjCCalls but it stops as soon as it finds a value
562/// with multiple uses.
563static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
564 if (Arg->hasOneUse()) {
565 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
566 return FindSingleUseIdentifiedObject(BC->getOperand(0));
567 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
568 if (GEP->hasAllZeroIndices())
569 return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
570 if (IsForwarding(GetBasicInstructionClass(Arg)))
571 return FindSingleUseIdentifiedObject(
572 cast<CallInst>(Arg)->getArgOperand(0));
573 if (!IsObjCIdentifiedObject(Arg))
574 return 0;
575 return Arg;
576 }
577
Dan Gohman0daef3d2012-05-08 23:39:44 +0000578 // If we found an identifiable object but it has multiple uses, but they are
579 // trivial uses, we can still consider this to be a single-use value.
John McCall9fbd3182011-06-15 23:37:01 +0000580 if (IsObjCIdentifiedObject(Arg)) {
581 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
582 UI != UE; ++UI) {
583 const User *U = *UI;
584 if (!U->use_empty() || StripPointerCastsAndObjCCalls(U) != Arg)
585 return 0;
586 }
587
588 return Arg;
589 }
590
591 return 0;
592}
593
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000594/// ModuleHasARC - Test if the given module looks interesting to run ARC
595/// optimization on.
596static bool ModuleHasARC(const Module &M) {
597 return
598 M.getNamedValue("objc_retain") ||
599 M.getNamedValue("objc_release") ||
600 M.getNamedValue("objc_autorelease") ||
601 M.getNamedValue("objc_retainAutoreleasedReturnValue") ||
602 M.getNamedValue("objc_retainBlock") ||
603 M.getNamedValue("objc_autoreleaseReturnValue") ||
604 M.getNamedValue("objc_autoreleasePoolPush") ||
605 M.getNamedValue("objc_loadWeakRetained") ||
606 M.getNamedValue("objc_loadWeak") ||
607 M.getNamedValue("objc_destroyWeak") ||
608 M.getNamedValue("objc_storeWeak") ||
609 M.getNamedValue("objc_initWeak") ||
610 M.getNamedValue("objc_moveWeak") ||
611 M.getNamedValue("objc_copyWeak") ||
612 M.getNamedValue("objc_retainedObject") ||
613 M.getNamedValue("objc_unretainedObject") ||
614 M.getNamedValue("objc_unretainedPointer");
615}
616
Dan Gohman79522dc2012-01-13 00:39:07 +0000617/// DoesObjCBlockEscape - Test whether the given pointer, which is an
618/// Objective C block pointer, does not "escape". This differs from regular
619/// escape analysis in that a use as an argument to a call is not considered
620/// an escape.
621static bool DoesObjCBlockEscape(const Value *BlockPtr) {
622 // Walk the def-use chains.
623 SmallVector<const Value *, 4> Worklist;
624 Worklist.push_back(BlockPtr);
625 do {
626 const Value *V = Worklist.pop_back_val();
627 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
628 UI != UE; ++UI) {
629 const User *UUser = *UI;
630 // Special - Use by a call (callee or argument) is not considered
631 // to be an escape.
Dan Gohman44234772012-04-13 18:28:58 +0000632 switch (GetBasicInstructionClass(UUser)) {
633 case IC_StoreWeak:
634 case IC_InitWeak:
635 case IC_StoreStrong:
636 case IC_Autorelease:
637 case IC_AutoreleaseRV:
638 // These special functions make copies of their pointer arguments.
639 return true;
640 case IC_User:
641 case IC_None:
642 // Use by an instruction which copies the value is an escape if the
643 // result is an escape.
644 if (isa<BitCastInst>(UUser) || isa<GetElementPtrInst>(UUser) ||
645 isa<PHINode>(UUser) || isa<SelectInst>(UUser)) {
646 Worklist.push_back(UUser);
647 continue;
648 }
649 // Use by a load is not an escape.
650 if (isa<LoadInst>(UUser))
651 continue;
652 // Use by a store is not an escape if the use is the address.
653 if (const StoreInst *SI = dyn_cast<StoreInst>(UUser))
654 if (V != SI->getValueOperand())
655 continue;
656 break;
657 default:
658 // Regular calls and other stuff are not considered escapes.
Dan Gohman79522dc2012-01-13 00:39:07 +0000659 continue;
660 }
Dan Gohmana3b08d62012-02-13 22:57:02 +0000661 // Otherwise, conservatively assume an escape.
Dan Gohman79522dc2012-01-13 00:39:07 +0000662 return true;
663 }
664 } while (!Worklist.empty());
665
666 // No escapes found.
667 return false;
668}
669
John McCall9fbd3182011-06-15 23:37:01 +0000670//===----------------------------------------------------------------------===//
671// ARC AliasAnalysis.
672//===----------------------------------------------------------------------===//
673
John McCall9fbd3182011-06-15 23:37:01 +0000674#include "llvm/Analysis/AliasAnalysis.h"
675#include "llvm/Analysis/Passes.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +0000676#include "llvm/Pass.h"
John McCall9fbd3182011-06-15 23:37:01 +0000677
678namespace {
679 /// ObjCARCAliasAnalysis - This is a simple alias analysis
680 /// implementation that uses knowledge of ARC constructs to answer queries.
681 ///
682 /// TODO: This class could be generalized to know about other ObjC-specific
683 /// tricks. Such as knowing that ivars in the non-fragile ABI are non-aliasing
684 /// even though their offsets are dynamic.
685 class ObjCARCAliasAnalysis : public ImmutablePass,
686 public AliasAnalysis {
687 public:
688 static char ID; // Class identification, replacement for typeinfo
689 ObjCARCAliasAnalysis() : ImmutablePass(ID) {
690 initializeObjCARCAliasAnalysisPass(*PassRegistry::getPassRegistry());
691 }
692
693 private:
694 virtual void initializePass() {
695 InitializeAliasAnalysis(this);
696 }
697
698 /// getAdjustedAnalysisPointer - This method is used when a pass implements
699 /// an analysis interface through multiple inheritance. If needed, it
700 /// should override this to adjust the this pointer as needed for the
701 /// specified pass info.
702 virtual void *getAdjustedAnalysisPointer(const void *PI) {
703 if (PI == &AliasAnalysis::ID)
Dan Gohman447989c2012-04-27 18:56:31 +0000704 return static_cast<AliasAnalysis *>(this);
John McCall9fbd3182011-06-15 23:37:01 +0000705 return this;
706 }
707
708 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
709 virtual AliasResult alias(const Location &LocA, const Location &LocB);
710 virtual bool pointsToConstantMemory(const Location &Loc, bool OrLocal);
711 virtual ModRefBehavior getModRefBehavior(ImmutableCallSite CS);
712 virtual ModRefBehavior getModRefBehavior(const Function *F);
713 virtual ModRefResult getModRefInfo(ImmutableCallSite CS,
714 const Location &Loc);
715 virtual ModRefResult getModRefInfo(ImmutableCallSite CS1,
716 ImmutableCallSite CS2);
717 };
718} // End of anonymous namespace
719
720// Register this pass...
721char ObjCARCAliasAnalysis::ID = 0;
722INITIALIZE_AG_PASS(ObjCARCAliasAnalysis, AliasAnalysis, "objc-arc-aa",
723 "ObjC-ARC-Based Alias Analysis", false, true, false)
724
725ImmutablePass *llvm::createObjCARCAliasAnalysisPass() {
726 return new ObjCARCAliasAnalysis();
727}
728
729void
730ObjCARCAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
731 AU.setPreservesAll();
732 AliasAnalysis::getAnalysisUsage(AU);
733}
734
735AliasAnalysis::AliasResult
736ObjCARCAliasAnalysis::alias(const Location &LocA, const Location &LocB) {
737 if (!EnableARCOpts)
738 return AliasAnalysis::alias(LocA, LocB);
739
740 // First, strip off no-ops, including ObjC-specific no-ops, and try making a
741 // precise alias query.
742 const Value *SA = StripPointerCastsAndObjCCalls(LocA.Ptr);
743 const Value *SB = StripPointerCastsAndObjCCalls(LocB.Ptr);
744 AliasResult Result =
745 AliasAnalysis::alias(Location(SA, LocA.Size, LocA.TBAATag),
746 Location(SB, LocB.Size, LocB.TBAATag));
747 if (Result != MayAlias)
748 return Result;
749
750 // If that failed, climb to the underlying object, including climbing through
751 // ObjC-specific no-ops, and try making an imprecise alias query.
752 const Value *UA = GetUnderlyingObjCPtr(SA);
753 const Value *UB = GetUnderlyingObjCPtr(SB);
754 if (UA != SA || UB != SB) {
755 Result = AliasAnalysis::alias(Location(UA), Location(UB));
756 // We can't use MustAlias or PartialAlias results here because
757 // GetUnderlyingObjCPtr may return an offsetted pointer value.
758 if (Result == NoAlias)
759 return NoAlias;
760 }
761
762 // If that failed, fail. We don't need to chain here, since that's covered
763 // by the earlier precise query.
764 return MayAlias;
765}
766
767bool
768ObjCARCAliasAnalysis::pointsToConstantMemory(const Location &Loc,
769 bool OrLocal) {
770 if (!EnableARCOpts)
771 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
772
773 // First, strip off no-ops, including ObjC-specific no-ops, and try making
774 // a precise alias query.
775 const Value *S = StripPointerCastsAndObjCCalls(Loc.Ptr);
776 if (AliasAnalysis::pointsToConstantMemory(Location(S, Loc.Size, Loc.TBAATag),
777 OrLocal))
778 return true;
779
780 // If that failed, climb to the underlying object, including climbing through
781 // ObjC-specific no-ops, and try making an imprecise alias query.
782 const Value *U = GetUnderlyingObjCPtr(S);
783 if (U != S)
784 return AliasAnalysis::pointsToConstantMemory(Location(U), OrLocal);
785
786 // If that failed, fail. We don't need to chain here, since that's covered
787 // by the earlier precise query.
788 return false;
789}
790
791AliasAnalysis::ModRefBehavior
792ObjCARCAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
793 // We have nothing to do. Just chain to the next AliasAnalysis.
794 return AliasAnalysis::getModRefBehavior(CS);
795}
796
797AliasAnalysis::ModRefBehavior
798ObjCARCAliasAnalysis::getModRefBehavior(const Function *F) {
799 if (!EnableARCOpts)
800 return AliasAnalysis::getModRefBehavior(F);
801
802 switch (GetFunctionClass(F)) {
803 case IC_NoopCast:
804 return DoesNotAccessMemory;
805 default:
806 break;
807 }
808
809 return AliasAnalysis::getModRefBehavior(F);
810}
811
812AliasAnalysis::ModRefResult
813ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS, const Location &Loc) {
814 if (!EnableARCOpts)
815 return AliasAnalysis::getModRefInfo(CS, Loc);
816
817 switch (GetBasicInstructionClass(CS.getInstruction())) {
818 case IC_Retain:
819 case IC_RetainRV:
John McCall9fbd3182011-06-15 23:37:01 +0000820 case IC_Autorelease:
821 case IC_AutoreleaseRV:
822 case IC_NoopCast:
823 case IC_AutoreleasepoolPush:
824 case IC_FusedRetainAutorelease:
825 case IC_FusedRetainAutoreleaseRV:
826 // These functions don't access any memory visible to the compiler.
Benjamin Kramerd9b0b022012-06-02 10:20:22 +0000827 // Note that this doesn't include objc_retainBlock, because it updates
Dan Gohman21104822011-09-14 18:13:00 +0000828 // pointers when it copies block data.
John McCall9fbd3182011-06-15 23:37:01 +0000829 return NoModRef;
830 default:
831 break;
832 }
833
834 return AliasAnalysis::getModRefInfo(CS, Loc);
835}
836
837AliasAnalysis::ModRefResult
838ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
839 ImmutableCallSite CS2) {
840 // TODO: Theoretically we could check for dependencies between objc_* calls
841 // and OnlyAccessesArgumentPointees calls or other well-behaved calls.
842 return AliasAnalysis::getModRefInfo(CS1, CS2);
843}
844
845//===----------------------------------------------------------------------===//
846// ARC expansion.
847//===----------------------------------------------------------------------===//
848
849#include "llvm/Support/InstIterator.h"
850#include "llvm/Transforms/Scalar.h"
851
852namespace {
853 /// ObjCARCExpand - Early ARC transformations.
854 class ObjCARCExpand : public FunctionPass {
855 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000856 virtual bool doInitialization(Module &M);
John McCall9fbd3182011-06-15 23:37:01 +0000857 virtual bool runOnFunction(Function &F);
858
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000859 /// Run - A flag indicating whether this optimization pass should run.
860 bool Run;
861
John McCall9fbd3182011-06-15 23:37:01 +0000862 public:
863 static char ID;
864 ObjCARCExpand() : FunctionPass(ID) {
865 initializeObjCARCExpandPass(*PassRegistry::getPassRegistry());
866 }
867 };
868}
869
870char ObjCARCExpand::ID = 0;
871INITIALIZE_PASS(ObjCARCExpand,
872 "objc-arc-expand", "ObjC ARC expansion", false, false)
873
874Pass *llvm::createObjCARCExpandPass() {
875 return new ObjCARCExpand();
876}
877
878void ObjCARCExpand::getAnalysisUsage(AnalysisUsage &AU) const {
879 AU.setPreservesCFG();
880}
881
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000882bool ObjCARCExpand::doInitialization(Module &M) {
883 Run = ModuleHasARC(M);
884 return false;
885}
886
John McCall9fbd3182011-06-15 23:37:01 +0000887bool ObjCARCExpand::runOnFunction(Function &F) {
888 if (!EnableARCOpts)
889 return false;
890
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000891 // If nothing in the Module uses ARC, don't do anything.
892 if (!Run)
893 return false;
894
John McCall9fbd3182011-06-15 23:37:01 +0000895 bool Changed = false;
896
Michael Gottesmancf140052013-01-13 07:00:51 +0000897 DEBUG(dbgs() << "ObjCARCExpand: Visiting Function: " << F.getName() << "\n");
898
John McCall9fbd3182011-06-15 23:37:01 +0000899 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
900 Instruction *Inst = &*I;
Michael Gottesman2f1bfc42013-01-07 21:26:07 +0000901
Michael Gottesman8f22c8b2013-01-01 16:05:48 +0000902 DEBUG(dbgs() << "ObjCARCExpand: Visiting: " << *Inst << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +0000903
John McCall9fbd3182011-06-15 23:37:01 +0000904 switch (GetBasicInstructionClass(Inst)) {
905 case IC_Retain:
906 case IC_RetainRV:
907 case IC_Autorelease:
908 case IC_AutoreleaseRV:
909 case IC_FusedRetainAutorelease:
Michael Gottesmana6e23cc2013-01-01 16:05:54 +0000910 case IC_FusedRetainAutoreleaseRV: {
John McCall9fbd3182011-06-15 23:37:01 +0000911 // These calls return their argument verbatim, as a low-level
912 // optimization. However, this makes high-level optimizations
913 // harder. Undo any uses of this optimization that the front-end
Dan Gohmand6bf2012012-04-13 18:57:48 +0000914 // emitted here. We'll redo them in the contract pass.
John McCall9fbd3182011-06-15 23:37:01 +0000915 Changed = true;
Michael Gottesmana6e23cc2013-01-01 16:05:54 +0000916 Value *Value = cast<CallInst>(Inst)->getArgOperand(0);
917 DEBUG(dbgs() << "ObjCARCExpand: Old = " << *Inst << "\n"
918 " New = " << *Value << "\n");
919 Inst->replaceAllUsesWith(Value);
John McCall9fbd3182011-06-15 23:37:01 +0000920 break;
Michael Gottesmana6e23cc2013-01-01 16:05:54 +0000921 }
John McCall9fbd3182011-06-15 23:37:01 +0000922 default:
923 break;
924 }
925 }
Michael Gottesman2f1bfc42013-01-07 21:26:07 +0000926
Michael Gottesmanec21e2a2013-01-03 08:09:27 +0000927 DEBUG(dbgs() << "ObjCARCExpand: Finished List.\n\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +0000928
John McCall9fbd3182011-06-15 23:37:01 +0000929 return Changed;
930}
931
932//===----------------------------------------------------------------------===//
Dan Gohman2f6263c2012-01-17 20:52:24 +0000933// ARC autorelease pool elimination.
934//===----------------------------------------------------------------------===//
935
Dan Gohman0daef3d2012-05-08 23:39:44 +0000936#include "llvm/ADT/STLExtras.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +0000937#include "llvm/IR/Constants.h"
Dan Gohman1dae3e92012-01-18 21:19:38 +0000938
Dan Gohman2f6263c2012-01-17 20:52:24 +0000939namespace {
940 /// ObjCARCAPElim - Autorelease pool elimination.
941 class ObjCARCAPElim : public ModulePass {
942 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
943 virtual bool runOnModule(Module &M);
944
Dan Gohman447989c2012-04-27 18:56:31 +0000945 static bool MayAutorelease(ImmutableCallSite CS, unsigned Depth = 0);
946 static bool OptimizeBB(BasicBlock *BB);
Dan Gohman2f6263c2012-01-17 20:52:24 +0000947
948 public:
949 static char ID;
950 ObjCARCAPElim() : ModulePass(ID) {
951 initializeObjCARCAPElimPass(*PassRegistry::getPassRegistry());
952 }
953 };
954}
955
956char ObjCARCAPElim::ID = 0;
957INITIALIZE_PASS(ObjCARCAPElim,
958 "objc-arc-apelim",
959 "ObjC ARC autorelease pool elimination",
960 false, false)
961
962Pass *llvm::createObjCARCAPElimPass() {
963 return new ObjCARCAPElim();
964}
965
966void ObjCARCAPElim::getAnalysisUsage(AnalysisUsage &AU) const {
967 AU.setPreservesCFG();
968}
969
970/// MayAutorelease - Interprocedurally determine if calls made by the
971/// given call site can possibly produce autoreleases.
Dan Gohman447989c2012-04-27 18:56:31 +0000972bool ObjCARCAPElim::MayAutorelease(ImmutableCallSite CS, unsigned Depth) {
973 if (const Function *Callee = CS.getCalledFunction()) {
Dan Gohman2f6263c2012-01-17 20:52:24 +0000974 if (Callee->isDeclaration() || Callee->mayBeOverridden())
975 return true;
Dan Gohman447989c2012-04-27 18:56:31 +0000976 for (Function::const_iterator I = Callee->begin(), E = Callee->end();
Dan Gohman2f6263c2012-01-17 20:52:24 +0000977 I != E; ++I) {
Dan Gohman447989c2012-04-27 18:56:31 +0000978 const BasicBlock *BB = I;
979 for (BasicBlock::const_iterator J = BB->begin(), F = BB->end();
980 J != F; ++J)
981 if (ImmutableCallSite JCS = ImmutableCallSite(J))
Dan Gohman2f77bbd2012-01-18 21:24:45 +0000982 // This recursion depth limit is arbitrary. It's just great
983 // enough to cover known interesting testcases.
984 if (Depth < 3 &&
985 !JCS.onlyReadsMemory() &&
986 MayAutorelease(JCS, Depth + 1))
Dan Gohman2f6263c2012-01-17 20:52:24 +0000987 return true;
988 }
989 return false;
990 }
991
992 return true;
993}
994
995bool ObjCARCAPElim::OptimizeBB(BasicBlock *BB) {
996 bool Changed = false;
997
998 Instruction *Push = 0;
999 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1000 Instruction *Inst = I++;
1001 switch (GetBasicInstructionClass(Inst)) {
1002 case IC_AutoreleasepoolPush:
1003 Push = Inst;
1004 break;
1005 case IC_AutoreleasepoolPop:
1006 // If this pop matches a push and nothing in between can autorelease,
1007 // zap the pair.
1008 if (Push && cast<CallInst>(Inst)->getArgOperand(0) == Push) {
1009 Changed = true;
Michael Gottesman5c0ae472013-01-04 21:29:57 +00001010 DEBUG(dbgs() << "ObjCARCAPElim::OptimizeBB: Zapping push pop autorelease pair:\n"
Michael Gottesmandf379f42013-01-03 08:09:17 +00001011 << " Pop: " << *Inst << "\n"
1012 << " Push: " << *Push << "\n");
Dan Gohman2f6263c2012-01-17 20:52:24 +00001013 Inst->eraseFromParent();
1014 Push->eraseFromParent();
1015 }
1016 Push = 0;
1017 break;
1018 case IC_CallOrUser:
Dan Gohman447989c2012-04-27 18:56:31 +00001019 if (MayAutorelease(ImmutableCallSite(Inst)))
Dan Gohman2f6263c2012-01-17 20:52:24 +00001020 Push = 0;
1021 break;
1022 default:
1023 break;
1024 }
1025 }
1026
1027 return Changed;
1028}
1029
1030bool ObjCARCAPElim::runOnModule(Module &M) {
1031 if (!EnableARCOpts)
1032 return false;
1033
1034 // If nothing in the Module uses ARC, don't do anything.
1035 if (!ModuleHasARC(M))
1036 return false;
1037
Dan Gohman1dae3e92012-01-18 21:19:38 +00001038 // Find the llvm.global_ctors variable, as the first step in
Dan Gohmand6bf2012012-04-13 18:57:48 +00001039 // identifying the global constructors. In theory, unnecessary autorelease
1040 // pools could occur anywhere, but in practice it's pretty rare. Global
1041 // ctors are a place where autorelease pools get inserted automatically,
1042 // so it's pretty common for them to be unnecessary, and it's pretty
1043 // profitable to eliminate them.
Dan Gohman1dae3e92012-01-18 21:19:38 +00001044 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1045 if (!GV)
1046 return false;
1047
1048 assert(GV->hasDefinitiveInitializer() &&
1049 "llvm.global_ctors is uncooperative!");
1050
Dan Gohman2f6263c2012-01-17 20:52:24 +00001051 bool Changed = false;
1052
Dan Gohman1dae3e92012-01-18 21:19:38 +00001053 // Dig the constructor functions out of GV's initializer.
1054 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
1055 for (User::op_iterator OI = Init->op_begin(), OE = Init->op_end();
1056 OI != OE; ++OI) {
1057 Value *Op = *OI;
1058 // llvm.global_ctors is an array of pairs where the second members
1059 // are constructor functions.
Dan Gohman3b5b2a22012-04-18 22:24:33 +00001060 Function *F = dyn_cast<Function>(cast<ConstantStruct>(Op)->getOperand(1));
1061 // If the user used a constructor function with the wrong signature and
1062 // it got bitcasted or whatever, look the other way.
1063 if (!F)
1064 continue;
Dan Gohman2f6263c2012-01-17 20:52:24 +00001065 // Only look at function definitions.
1066 if (F->isDeclaration())
1067 continue;
Dan Gohman2f6263c2012-01-17 20:52:24 +00001068 // Only look at functions with one basic block.
1069 if (llvm::next(F->begin()) != F->end())
1070 continue;
1071 // Ok, a single-block constructor function definition. Try to optimize it.
1072 Changed |= OptimizeBB(F->begin());
1073 }
1074
1075 return Changed;
1076}
1077
1078//===----------------------------------------------------------------------===//
John McCall9fbd3182011-06-15 23:37:01 +00001079// ARC optimization.
1080//===----------------------------------------------------------------------===//
1081
1082// TODO: On code like this:
1083//
1084// objc_retain(%x)
1085// stuff_that_cannot_release()
1086// objc_autorelease(%x)
1087// stuff_that_cannot_release()
1088// objc_retain(%x)
1089// stuff_that_cannot_release()
1090// objc_autorelease(%x)
1091//
1092// The second retain and autorelease can be deleted.
1093
1094// TODO: It should be possible to delete
1095// objc_autoreleasePoolPush and objc_autoreleasePoolPop
1096// pairs if nothing is actually autoreleased between them. Also, autorelease
1097// calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
1098// after inlining) can be turned into plain release calls.
1099
1100// TODO: Critical-edge splitting. If the optimial insertion point is
1101// a critical edge, the current algorithm has to fail, because it doesn't
1102// know how to split edges. It should be possible to make the optimizer
1103// think in terms of edges, rather than blocks, and then split critical
1104// edges on demand.
1105
1106// TODO: OptimizeSequences could generalized to be Interprocedural.
1107
1108// TODO: Recognize that a bunch of other objc runtime calls have
1109// non-escaping arguments and non-releasing arguments, and may be
1110// non-autoreleasing.
1111
1112// TODO: Sink autorelease calls as far as possible. Unfortunately we
1113// usually can't sink them past other calls, which would be the main
1114// case where it would be useful.
1115
Dan Gohmane6d5e882011-08-19 00:26:36 +00001116// TODO: The pointer returned from objc_loadWeakRetained is retained.
1117
1118// TODO: Delete release+retain pairs (rare).
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00001119
Chandler Carruthd04a8d42012-12-03 16:50:05 +00001120#include "llvm/ADT/SmallPtrSet.h"
1121#include "llvm/ADT/Statistic.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +00001122#include "llvm/IR/LLVMContext.h"
John McCall9fbd3182011-06-15 23:37:01 +00001123#include "llvm/Support/CFG.h"
John McCall9fbd3182011-06-15 23:37:01 +00001124
1125STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
1126STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
1127STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
1128STATISTIC(NumRets, "Number of return value forwarding "
1129 "retain+autoreleaes eliminated");
1130STATISTIC(NumRRs, "Number of retain+release paths eliminated");
1131STATISTIC(NumPeeps, "Number of calls peephole-optimized");
1132
1133namespace {
1134 /// ProvenanceAnalysis - This is similar to BasicAliasAnalysis, and it
1135 /// uses many of the same techniques, except it uses special ObjC-specific
1136 /// reasoning about pointer relationships.
1137 class ProvenanceAnalysis {
1138 AliasAnalysis *AA;
1139
1140 typedef std::pair<const Value *, const Value *> ValuePairTy;
1141 typedef DenseMap<ValuePairTy, bool> CachedResultsTy;
1142 CachedResultsTy CachedResults;
1143
1144 bool relatedCheck(const Value *A, const Value *B);
1145 bool relatedSelect(const SelectInst *A, const Value *B);
1146 bool relatedPHI(const PHINode *A, const Value *B);
1147
Craig Topperc2945e42012-09-18 02:01:41 +00001148 void operator=(const ProvenanceAnalysis &) LLVM_DELETED_FUNCTION;
1149 ProvenanceAnalysis(const ProvenanceAnalysis &) LLVM_DELETED_FUNCTION;
John McCall9fbd3182011-06-15 23:37:01 +00001150
1151 public:
1152 ProvenanceAnalysis() {}
1153
1154 void setAA(AliasAnalysis *aa) { AA = aa; }
1155
1156 AliasAnalysis *getAA() const { return AA; }
1157
1158 bool related(const Value *A, const Value *B);
1159
1160 void clear() {
1161 CachedResults.clear();
1162 }
1163 };
1164}
1165
1166bool ProvenanceAnalysis::relatedSelect(const SelectInst *A, const Value *B) {
1167 // If the values are Selects with the same condition, we can do a more precise
1168 // check: just check for relations between the values on corresponding arms.
1169 if (const SelectInst *SB = dyn_cast<SelectInst>(B))
Dan Gohman447989c2012-04-27 18:56:31 +00001170 if (A->getCondition() == SB->getCondition())
1171 return related(A->getTrueValue(), SB->getTrueValue()) ||
1172 related(A->getFalseValue(), SB->getFalseValue());
John McCall9fbd3182011-06-15 23:37:01 +00001173
1174 // Check both arms of the Select node individually.
Dan Gohman447989c2012-04-27 18:56:31 +00001175 return related(A->getTrueValue(), B) ||
1176 related(A->getFalseValue(), B);
John McCall9fbd3182011-06-15 23:37:01 +00001177}
1178
1179bool ProvenanceAnalysis::relatedPHI(const PHINode *A, const Value *B) {
1180 // If the values are PHIs in the same block, we can do a more precise as well
1181 // as efficient check: just check for relations between the values on
1182 // corresponding edges.
1183 if (const PHINode *PNB = dyn_cast<PHINode>(B))
1184 if (PNB->getParent() == A->getParent()) {
1185 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i)
1186 if (related(A->getIncomingValue(i),
1187 PNB->getIncomingValueForBlock(A->getIncomingBlock(i))))
1188 return true;
1189 return false;
1190 }
1191
1192 // Check each unique source of the PHI node against B.
1193 SmallPtrSet<const Value *, 4> UniqueSrc;
1194 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i) {
1195 const Value *PV1 = A->getIncomingValue(i);
1196 if (UniqueSrc.insert(PV1) && related(PV1, B))
1197 return true;
1198 }
1199
1200 // All of the arms checked out.
1201 return false;
1202}
1203
1204/// isStoredObjCPointer - Test if the value of P, or any value covered by its
1205/// provenance, is ever stored within the function (not counting callees).
1206static bool isStoredObjCPointer(const Value *P) {
1207 SmallPtrSet<const Value *, 8> Visited;
1208 SmallVector<const Value *, 8> Worklist;
1209 Worklist.push_back(P);
1210 Visited.insert(P);
1211 do {
1212 P = Worklist.pop_back_val();
1213 for (Value::const_use_iterator UI = P->use_begin(), UE = P->use_end();
1214 UI != UE; ++UI) {
1215 const User *Ur = *UI;
1216 if (isa<StoreInst>(Ur)) {
1217 if (UI.getOperandNo() == 0)
1218 // The pointer is stored.
1219 return true;
1220 // The pointed is stored through.
1221 continue;
1222 }
1223 if (isa<CallInst>(Ur))
1224 // The pointer is passed as an argument, ignore this.
1225 continue;
1226 if (isa<PtrToIntInst>(P))
1227 // Assume the worst.
1228 return true;
1229 if (Visited.insert(Ur))
1230 Worklist.push_back(Ur);
1231 }
1232 } while (!Worklist.empty());
1233
1234 // Everything checked out.
1235 return false;
1236}
1237
1238bool ProvenanceAnalysis::relatedCheck(const Value *A, const Value *B) {
1239 // Skip past provenance pass-throughs.
1240 A = GetUnderlyingObjCPtr(A);
1241 B = GetUnderlyingObjCPtr(B);
1242
1243 // Quick check.
1244 if (A == B)
1245 return true;
1246
1247 // Ask regular AliasAnalysis, for a first approximation.
1248 switch (AA->alias(A, B)) {
1249 case AliasAnalysis::NoAlias:
1250 return false;
1251 case AliasAnalysis::MustAlias:
1252 case AliasAnalysis::PartialAlias:
1253 return true;
1254 case AliasAnalysis::MayAlias:
1255 break;
1256 }
1257
1258 bool AIsIdentified = IsObjCIdentifiedObject(A);
1259 bool BIsIdentified = IsObjCIdentifiedObject(B);
1260
1261 // An ObjC-Identified object can't alias a load if it is never locally stored.
1262 if (AIsIdentified) {
Dan Gohman230768b2012-09-04 23:16:20 +00001263 // Check for an obvious escape.
1264 if (isa<LoadInst>(B))
1265 return isStoredObjCPointer(A);
John McCall9fbd3182011-06-15 23:37:01 +00001266 if (BIsIdentified) {
Dan Gohman230768b2012-09-04 23:16:20 +00001267 // Check for an obvious escape.
1268 if (isa<LoadInst>(A))
1269 return isStoredObjCPointer(B);
1270 // Both pointers are identified and escapes aren't an evident problem.
1271 return false;
John McCall9fbd3182011-06-15 23:37:01 +00001272 }
Dan Gohman230768b2012-09-04 23:16:20 +00001273 } else if (BIsIdentified) {
1274 // Check for an obvious escape.
1275 if (isa<LoadInst>(A))
John McCall9fbd3182011-06-15 23:37:01 +00001276 return isStoredObjCPointer(B);
1277 }
1278
1279 // Special handling for PHI and Select.
1280 if (const PHINode *PN = dyn_cast<PHINode>(A))
1281 return relatedPHI(PN, B);
1282 if (const PHINode *PN = dyn_cast<PHINode>(B))
1283 return relatedPHI(PN, A);
1284 if (const SelectInst *S = dyn_cast<SelectInst>(A))
1285 return relatedSelect(S, B);
1286 if (const SelectInst *S = dyn_cast<SelectInst>(B))
1287 return relatedSelect(S, A);
1288
1289 // Conservative.
1290 return true;
1291}
1292
1293bool ProvenanceAnalysis::related(const Value *A, const Value *B) {
1294 // Begin by inserting a conservative value into the map. If the insertion
1295 // fails, we have the answer already. If it succeeds, leave it there until we
1296 // compute the real answer to guard against recursive queries.
1297 if (A > B) std::swap(A, B);
1298 std::pair<CachedResultsTy::iterator, bool> Pair =
1299 CachedResults.insert(std::make_pair(ValuePairTy(A, B), true));
1300 if (!Pair.second)
1301 return Pair.first->second;
1302
1303 bool Result = relatedCheck(A, B);
1304 CachedResults[ValuePairTy(A, B)] = Result;
1305 return Result;
1306}
1307
1308namespace {
1309 // Sequence - A sequence of states that a pointer may go through in which an
1310 // objc_retain and objc_release are actually needed.
1311 enum Sequence {
1312 S_None,
1313 S_Retain, ///< objc_retain(x)
1314 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement
1315 S_Use, ///< any use of x
1316 S_Stop, ///< like S_Release, but code motion is stopped
1317 S_Release, ///< objc_release(x)
1318 S_MovableRelease ///< objc_release(x), !clang.imprecise_release
1319 };
1320}
1321
1322static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
1323 // The easy cases.
1324 if (A == B)
1325 return A;
1326 if (A == S_None || B == S_None)
1327 return S_None;
1328
John McCall9fbd3182011-06-15 23:37:01 +00001329 if (A > B) std::swap(A, B);
1330 if (TopDown) {
1331 // Choose the side which is further along in the sequence.
Dan Gohmana7f7db22011-08-12 00:26:31 +00001332 if ((A == S_Retain || A == S_CanRelease) &&
1333 (B == S_CanRelease || B == S_Use))
John McCall9fbd3182011-06-15 23:37:01 +00001334 return B;
1335 } else {
1336 // Choose the side which is further along in the sequence.
1337 if ((A == S_Use || A == S_CanRelease) &&
Dan Gohmana7f7db22011-08-12 00:26:31 +00001338 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
John McCall9fbd3182011-06-15 23:37:01 +00001339 return A;
1340 // If both sides are releases, choose the more conservative one.
1341 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
1342 return A;
1343 if (A == S_Release && B == S_MovableRelease)
1344 return A;
1345 }
1346
1347 return S_None;
1348}
1349
1350namespace {
1351 /// RRInfo - Unidirectional information about either a
1352 /// retain-decrement-use-release sequence or release-use-decrement-retain
1353 /// reverese sequence.
1354 struct RRInfo {
Dan Gohmane6d5e882011-08-19 00:26:36 +00001355 /// KnownSafe - After an objc_retain, the reference count of the referenced
1356 /// object is known to be positive. Similarly, before an objc_release, the
1357 /// reference count of the referenced object is known to be positive. If
1358 /// there are retain-release pairs in code regions where the retain count
1359 /// is known to be positive, they can be eliminated, regardless of any side
1360 /// effects between them.
1361 ///
1362 /// Also, a retain+release pair nested within another retain+release
1363 /// pair all on the known same pointer value can be eliminated, regardless
1364 /// of any intervening side effects.
1365 ///
1366 /// KnownSafe is true when either of these conditions is satisfied.
1367 bool KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00001368
1369 /// IsRetainBlock - True if the Calls are objc_retainBlock calls (as
1370 /// opposed to objc_retain calls).
1371 bool IsRetainBlock;
1372
1373 /// IsTailCallRelease - True of the objc_release calls are all marked
1374 /// with the "tail" keyword.
1375 bool IsTailCallRelease;
1376
1377 /// ReleaseMetadata - If the Calls are objc_release calls and they all have
1378 /// a clang.imprecise_release tag, this is the metadata tag.
1379 MDNode *ReleaseMetadata;
1380
1381 /// Calls - For a top-down sequence, the set of objc_retains or
1382 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
1383 SmallPtrSet<Instruction *, 2> Calls;
1384
1385 /// ReverseInsertPts - The set of optimal insert positions for
1386 /// moving calls in the opposite sequence.
1387 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
1388
1389 RRInfo() :
Dan Gohman79522dc2012-01-13 00:39:07 +00001390 KnownSafe(false), IsRetainBlock(false),
Dan Gohman50ade652012-04-25 00:50:46 +00001391 IsTailCallRelease(false),
John McCall9fbd3182011-06-15 23:37:01 +00001392 ReleaseMetadata(0) {}
1393
1394 void clear();
1395 };
1396}
1397
1398void RRInfo::clear() {
Dan Gohmane6d5e882011-08-19 00:26:36 +00001399 KnownSafe = false;
John McCall9fbd3182011-06-15 23:37:01 +00001400 IsRetainBlock = false;
1401 IsTailCallRelease = false;
1402 ReleaseMetadata = 0;
1403 Calls.clear();
1404 ReverseInsertPts.clear();
1405}
1406
1407namespace {
1408 /// PtrState - This class summarizes several per-pointer runtime properties
1409 /// which are propogated through the flow graph.
1410 class PtrState {
Dan Gohman50ade652012-04-25 00:50:46 +00001411 /// KnownPositiveRefCount - True if the reference count is known to
1412 /// be incremented.
1413 bool KnownPositiveRefCount;
1414
1415 /// Partial - True of we've seen an opportunity for partial RR elimination,
1416 /// such as pushing calls into a CFG triangle or into one side of a
1417 /// CFG diamond.
1418 bool Partial;
John McCall9fbd3182011-06-15 23:37:01 +00001419
1420 /// Seq - The current position in the sequence.
Dan Gohman0daef3d2012-05-08 23:39:44 +00001421 Sequence Seq : 8;
John McCall9fbd3182011-06-15 23:37:01 +00001422
1423 public:
1424 /// RRI - Unidirectional information about the current sequence.
1425 /// TODO: Encapsulate this better.
1426 RRInfo RRI;
1427
Dan Gohman230768b2012-09-04 23:16:20 +00001428 PtrState() : KnownPositiveRefCount(false), Partial(false),
Dan Gohman0daef3d2012-05-08 23:39:44 +00001429 Seq(S_None) {}
John McCall9fbd3182011-06-15 23:37:01 +00001430
Dan Gohman50ade652012-04-25 00:50:46 +00001431 void SetKnownPositiveRefCount() {
1432 KnownPositiveRefCount = true;
Dan Gohmana7f7db22011-08-12 00:26:31 +00001433 }
1434
Dan Gohman50ade652012-04-25 00:50:46 +00001435 void ClearRefCount() {
1436 KnownPositiveRefCount = false;
John McCall9fbd3182011-06-15 23:37:01 +00001437 }
1438
John McCall9fbd3182011-06-15 23:37:01 +00001439 bool IsKnownIncremented() const {
Dan Gohman50ade652012-04-25 00:50:46 +00001440 return KnownPositiveRefCount;
John McCall9fbd3182011-06-15 23:37:01 +00001441 }
1442
1443 void SetSeq(Sequence NewSeq) {
1444 Seq = NewSeq;
1445 }
1446
John McCall9fbd3182011-06-15 23:37:01 +00001447 Sequence GetSeq() const {
1448 return Seq;
1449 }
1450
1451 void ClearSequenceProgress() {
Dan Gohman50ade652012-04-25 00:50:46 +00001452 ResetSequenceProgress(S_None);
1453 }
1454
1455 void ResetSequenceProgress(Sequence NewSeq) {
1456 Seq = NewSeq;
1457 Partial = false;
John McCall9fbd3182011-06-15 23:37:01 +00001458 RRI.clear();
1459 }
1460
1461 void Merge(const PtrState &Other, bool TopDown);
1462 };
1463}
1464
1465void
1466PtrState::Merge(const PtrState &Other, bool TopDown) {
1467 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
Dan Gohman50ade652012-04-25 00:50:46 +00001468 KnownPositiveRefCount = KnownPositiveRefCount && Other.KnownPositiveRefCount;
John McCall9fbd3182011-06-15 23:37:01 +00001469
1470 // We can't merge a plain objc_retain with an objc_retainBlock.
1471 if (RRI.IsRetainBlock != Other.RRI.IsRetainBlock)
1472 Seq = S_None;
1473
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001474 // If we're not in a sequence (anymore), drop all associated state.
John McCall9fbd3182011-06-15 23:37:01 +00001475 if (Seq == S_None) {
Dan Gohman50ade652012-04-25 00:50:46 +00001476 Partial = false;
John McCall9fbd3182011-06-15 23:37:01 +00001477 RRI.clear();
Dan Gohman50ade652012-04-25 00:50:46 +00001478 } else if (Partial || Other.Partial) {
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001479 // If we're doing a merge on a path that's previously seen a partial
1480 // merge, conservatively drop the sequence, to avoid doing partial
1481 // RR elimination. If the branch predicates for the two merge differ,
1482 // mixing them is unsafe.
Dan Gohman50ade652012-04-25 00:50:46 +00001483 ClearSequenceProgress();
John McCall9fbd3182011-06-15 23:37:01 +00001484 } else {
1485 // Conservatively merge the ReleaseMetadata information.
1486 if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
1487 RRI.ReleaseMetadata = 0;
1488
Dan Gohmane6d5e882011-08-19 00:26:36 +00001489 RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
Dan Gohman0daef3d2012-05-08 23:39:44 +00001490 RRI.IsTailCallRelease = RRI.IsTailCallRelease &&
1491 Other.RRI.IsTailCallRelease;
John McCall9fbd3182011-06-15 23:37:01 +00001492 RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001493
1494 // Merge the insert point sets. If there are any differences,
1495 // that makes this a partial merge.
Dan Gohman0daef3d2012-05-08 23:39:44 +00001496 Partial = RRI.ReverseInsertPts.size() != Other.RRI.ReverseInsertPts.size();
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001497 for (SmallPtrSet<Instruction *, 2>::const_iterator
1498 I = Other.RRI.ReverseInsertPts.begin(),
1499 E = Other.RRI.ReverseInsertPts.end(); I != E; ++I)
Dan Gohman50ade652012-04-25 00:50:46 +00001500 Partial |= RRI.ReverseInsertPts.insert(*I);
John McCall9fbd3182011-06-15 23:37:01 +00001501 }
1502}
1503
1504namespace {
1505 /// BBState - Per-BasicBlock state.
1506 class BBState {
1507 /// TopDownPathCount - The number of unique control paths from the entry
1508 /// which can reach this block.
1509 unsigned TopDownPathCount;
1510
1511 /// BottomUpPathCount - The number of unique control paths to exits
1512 /// from this block.
1513 unsigned BottomUpPathCount;
1514
1515 /// MapTy - A type for PerPtrTopDown and PerPtrBottomUp.
1516 typedef MapVector<const Value *, PtrState> MapTy;
1517
1518 /// PerPtrTopDown - The top-down traversal uses this to record information
1519 /// known about a pointer at the bottom of each block.
1520 MapTy PerPtrTopDown;
1521
1522 /// PerPtrBottomUp - The bottom-up traversal uses this to record information
1523 /// known about a pointer at the top of each block.
1524 MapTy PerPtrBottomUp;
1525
Dan Gohmaneeeb7752012-04-24 22:53:18 +00001526 /// Preds, Succs - Effective successors and predecessors of the current
1527 /// block (this ignores ignorable edges and ignored backedges).
1528 SmallVector<BasicBlock *, 2> Preds;
1529 SmallVector<BasicBlock *, 2> Succs;
1530
John McCall9fbd3182011-06-15 23:37:01 +00001531 public:
1532 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
1533
1534 typedef MapTy::iterator ptr_iterator;
1535 typedef MapTy::const_iterator ptr_const_iterator;
1536
1537 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
1538 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
1539 ptr_const_iterator top_down_ptr_begin() const {
1540 return PerPtrTopDown.begin();
1541 }
1542 ptr_const_iterator top_down_ptr_end() const {
1543 return PerPtrTopDown.end();
1544 }
1545
1546 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
1547 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
1548 ptr_const_iterator bottom_up_ptr_begin() const {
1549 return PerPtrBottomUp.begin();
1550 }
1551 ptr_const_iterator bottom_up_ptr_end() const {
1552 return PerPtrBottomUp.end();
1553 }
1554
1555 /// SetAsEntry - Mark this block as being an entry block, which has one
1556 /// path from the entry by definition.
1557 void SetAsEntry() { TopDownPathCount = 1; }
1558
1559 /// SetAsExit - Mark this block as being an exit block, which has one
1560 /// path to an exit by definition.
1561 void SetAsExit() { BottomUpPathCount = 1; }
1562
1563 PtrState &getPtrTopDownState(const Value *Arg) {
1564 return PerPtrTopDown[Arg];
1565 }
1566
1567 PtrState &getPtrBottomUpState(const Value *Arg) {
1568 return PerPtrBottomUp[Arg];
1569 }
1570
1571 void clearBottomUpPointers() {
Evan Chenga81388f2011-08-04 18:40:26 +00001572 PerPtrBottomUp.clear();
John McCall9fbd3182011-06-15 23:37:01 +00001573 }
1574
1575 void clearTopDownPointers() {
1576 PerPtrTopDown.clear();
1577 }
1578
1579 void InitFromPred(const BBState &Other);
1580 void InitFromSucc(const BBState &Other);
1581 void MergePred(const BBState &Other);
1582 void MergeSucc(const BBState &Other);
1583
1584 /// GetAllPathCount - Return the number of possible unique paths from an
1585 /// entry to an exit which pass through this block. This is only valid
1586 /// after both the top-down and bottom-up traversals are complete.
1587 unsigned GetAllPathCount() const {
Dan Gohmaneeeb7752012-04-24 22:53:18 +00001588 assert(TopDownPathCount != 0);
1589 assert(BottomUpPathCount != 0);
John McCall9fbd3182011-06-15 23:37:01 +00001590 return TopDownPathCount * BottomUpPathCount;
1591 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00001592
Dan Gohmaneeeb7752012-04-24 22:53:18 +00001593 // Specialized CFG utilities.
Dan Gohman447989c2012-04-27 18:56:31 +00001594 typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
Dan Gohmaneeeb7752012-04-24 22:53:18 +00001595 edge_iterator pred_begin() { return Preds.begin(); }
1596 edge_iterator pred_end() { return Preds.end(); }
1597 edge_iterator succ_begin() { return Succs.begin(); }
1598 edge_iterator succ_end() { return Succs.end(); }
1599
1600 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
1601 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
1602
1603 bool isExit() const { return Succs.empty(); }
John McCall9fbd3182011-06-15 23:37:01 +00001604 };
1605}
1606
1607void BBState::InitFromPred(const BBState &Other) {
1608 PerPtrTopDown = Other.PerPtrTopDown;
1609 TopDownPathCount = Other.TopDownPathCount;
1610}
1611
1612void BBState::InitFromSucc(const BBState &Other) {
1613 PerPtrBottomUp = Other.PerPtrBottomUp;
1614 BottomUpPathCount = Other.BottomUpPathCount;
1615}
1616
1617/// MergePred - The top-down traversal uses this to merge information about
1618/// predecessors to form the initial state for a new block.
1619void BBState::MergePred(const BBState &Other) {
1620 // Other.TopDownPathCount can be 0, in which case it is either dead or a
1621 // loop backedge. Loop backedges are special.
1622 TopDownPathCount += Other.TopDownPathCount;
1623
Dan Gohman0d1bc5f2012-09-12 20:45:17 +00001624 // Check for overflow. If we have overflow, fall back to conservative behavior.
1625 if (TopDownPathCount < Other.TopDownPathCount) {
1626 clearTopDownPointers();
1627 return;
1628 }
1629
John McCall9fbd3182011-06-15 23:37:01 +00001630 // For each entry in the other set, if our set has an entry with the same key,
1631 // merge the entries. Otherwise, copy the entry and merge it with an empty
1632 // entry.
1633 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
1634 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
1635 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
1636 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1637 /*TopDown=*/true);
1638 }
1639
Dan Gohmanfa7eed12011-08-11 21:06:32 +00001640 // For each entry in our set, if the other set doesn't have an entry with the
John McCall9fbd3182011-06-15 23:37:01 +00001641 // same key, force it to merge with an empty entry.
1642 for (ptr_iterator MI = top_down_ptr_begin(),
1643 ME = top_down_ptr_end(); MI != ME; ++MI)
1644 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
1645 MI->second.Merge(PtrState(), /*TopDown=*/true);
1646}
1647
1648/// MergeSucc - The bottom-up traversal uses this to merge information about
1649/// successors to form the initial state for a new block.
1650void BBState::MergeSucc(const BBState &Other) {
1651 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
1652 // loop backedge. Loop backedges are special.
1653 BottomUpPathCount += Other.BottomUpPathCount;
1654
Dan Gohman0d1bc5f2012-09-12 20:45:17 +00001655 // Check for overflow. If we have overflow, fall back to conservative behavior.
1656 if (BottomUpPathCount < Other.BottomUpPathCount) {
1657 clearBottomUpPointers();
1658 return;
1659 }
1660
John McCall9fbd3182011-06-15 23:37:01 +00001661 // For each entry in the other set, if our set has an entry with the
1662 // same key, merge the entries. Otherwise, copy the entry and merge
1663 // it with an empty entry.
1664 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
1665 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
1666 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
1667 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1668 /*TopDown=*/false);
1669 }
1670
Dan Gohmanfa7eed12011-08-11 21:06:32 +00001671 // For each entry in our set, if the other set doesn't have an entry
John McCall9fbd3182011-06-15 23:37:01 +00001672 // with the same key, force it to merge with an empty entry.
1673 for (ptr_iterator MI = bottom_up_ptr_begin(),
1674 ME = bottom_up_ptr_end(); MI != ME; ++MI)
1675 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
1676 MI->second.Merge(PtrState(), /*TopDown=*/false);
1677}
1678
1679namespace {
1680 /// ObjCARCOpt - The main ARC optimization pass.
1681 class ObjCARCOpt : public FunctionPass {
1682 bool Changed;
1683 ProvenanceAnalysis PA;
1684
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00001685 /// Run - A flag indicating whether this optimization pass should run.
1686 bool Run;
1687
John McCall9fbd3182011-06-15 23:37:01 +00001688 /// RetainRVCallee, etc. - Declarations for ObjC runtime
1689 /// functions, for use in creating calls to them. These are initialized
1690 /// lazily to avoid cluttering up the Module with unused declarations.
1691 Constant *RetainRVCallee, *AutoreleaseRVCallee, *ReleaseCallee,
Dan Gohman44280692011-07-22 22:29:21 +00001692 *RetainCallee, *RetainBlockCallee, *AutoreleaseCallee;
John McCall9fbd3182011-06-15 23:37:01 +00001693
1694 /// UsedInThisFunciton - Flags which determine whether each of the
1695 /// interesting runtine functions is in fact used in the current function.
1696 unsigned UsedInThisFunction;
1697
1698 /// ImpreciseReleaseMDKind - The Metadata Kind for clang.imprecise_release
1699 /// metadata.
1700 unsigned ImpreciseReleaseMDKind;
1701
Dan Gohman62e5b402011-12-12 18:20:00 +00001702 /// CopyOnEscapeMDKind - The Metadata Kind for clang.arc.copy_on_escape
Dan Gohmana974bea2011-10-17 22:53:25 +00001703 /// metadata.
1704 unsigned CopyOnEscapeMDKind;
1705
Dan Gohmandbe266b2012-02-17 18:59:53 +00001706 /// NoObjCARCExceptionsMDKind - The Metadata Kind for
1707 /// clang.arc.no_objc_arc_exceptions metadata.
1708 unsigned NoObjCARCExceptionsMDKind;
1709
John McCall9fbd3182011-06-15 23:37:01 +00001710 Constant *getRetainRVCallee(Module *M);
1711 Constant *getAutoreleaseRVCallee(Module *M);
1712 Constant *getReleaseCallee(Module *M);
1713 Constant *getRetainCallee(Module *M);
Dan Gohman44280692011-07-22 22:29:21 +00001714 Constant *getRetainBlockCallee(Module *M);
John McCall9fbd3182011-06-15 23:37:01 +00001715 Constant *getAutoreleaseCallee(Module *M);
1716
Dan Gohman79522dc2012-01-13 00:39:07 +00001717 bool IsRetainBlockOptimizable(const Instruction *Inst);
1718
John McCall9fbd3182011-06-15 23:37:01 +00001719 void OptimizeRetainCall(Function &F, Instruction *Retain);
1720 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
Michael Gottesman0e385452013-01-12 01:25:19 +00001721 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1722 InstructionClass &Class);
John McCall9fbd3182011-06-15 23:37:01 +00001723 void OptimizeIndividualCalls(Function &F);
1724
1725 void CheckForCFGHazards(const BasicBlock *BB,
1726 DenseMap<const BasicBlock *, BBState> &BBStates,
1727 BBState &MyStates) const;
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00001728 bool VisitInstructionBottomUp(Instruction *Inst,
Dan Gohmanfbab4a82012-03-23 17:47:54 +00001729 BasicBlock *BB,
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00001730 MapVector<Value *, RRInfo> &Retains,
1731 BBState &MyStates);
John McCall9fbd3182011-06-15 23:37:01 +00001732 bool VisitBottomUp(BasicBlock *BB,
1733 DenseMap<const BasicBlock *, BBState> &BBStates,
1734 MapVector<Value *, RRInfo> &Retains);
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00001735 bool VisitInstructionTopDown(Instruction *Inst,
1736 DenseMap<Value *, RRInfo> &Releases,
1737 BBState &MyStates);
John McCall9fbd3182011-06-15 23:37:01 +00001738 bool VisitTopDown(BasicBlock *BB,
1739 DenseMap<const BasicBlock *, BBState> &BBStates,
1740 DenseMap<Value *, RRInfo> &Releases);
1741 bool Visit(Function &F,
1742 DenseMap<const BasicBlock *, BBState> &BBStates,
1743 MapVector<Value *, RRInfo> &Retains,
1744 DenseMap<Value *, RRInfo> &Releases);
1745
1746 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1747 MapVector<Value *, RRInfo> &Retains,
1748 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman44280692011-07-22 22:29:21 +00001749 SmallVectorImpl<Instruction *> &DeadInsts,
1750 Module *M);
John McCall9fbd3182011-06-15 23:37:01 +00001751
1752 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1753 MapVector<Value *, RRInfo> &Retains,
Dan Gohman44280692011-07-22 22:29:21 +00001754 DenseMap<Value *, RRInfo> &Releases,
1755 Module *M);
John McCall9fbd3182011-06-15 23:37:01 +00001756
1757 void OptimizeWeakCalls(Function &F);
1758
1759 bool OptimizeSequences(Function &F);
1760
1761 void OptimizeReturns(Function &F);
1762
1763 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1764 virtual bool doInitialization(Module &M);
1765 virtual bool runOnFunction(Function &F);
1766 virtual void releaseMemory();
1767
1768 public:
1769 static char ID;
1770 ObjCARCOpt() : FunctionPass(ID) {
1771 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1772 }
1773 };
1774}
1775
1776char ObjCARCOpt::ID = 0;
1777INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1778 "objc-arc", "ObjC ARC optimization", false, false)
1779INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1780INITIALIZE_PASS_END(ObjCARCOpt,
1781 "objc-arc", "ObjC ARC optimization", false, false)
1782
1783Pass *llvm::createObjCARCOptPass() {
1784 return new ObjCARCOpt();
1785}
1786
1787void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1788 AU.addRequired<ObjCARCAliasAnalysis>();
1789 AU.addRequired<AliasAnalysis>();
1790 // ARC optimization doesn't currently split critical edges.
1791 AU.setPreservesCFG();
1792}
1793
Dan Gohman79522dc2012-01-13 00:39:07 +00001794bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1795 // Without the magic metadata tag, we have to assume this might be an
1796 // objc_retainBlock call inserted to convert a block pointer to an id,
1797 // in which case it really is needed.
1798 if (!Inst->getMetadata(CopyOnEscapeMDKind))
1799 return false;
1800
1801 // If the pointer "escapes" (not including being used in a call),
1802 // the copy may be needed.
1803 if (DoesObjCBlockEscape(Inst))
1804 return false;
1805
1806 // Otherwise, it's not needed.
1807 return true;
1808}
1809
John McCall9fbd3182011-06-15 23:37:01 +00001810Constant *ObjCARCOpt::getRetainRVCallee(Module *M) {
1811 if (!RetainRVCallee) {
1812 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001813 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman0daef3d2012-05-08 23:39:44 +00001814 Type *Params[] = { I8X };
1815 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling034b94b2012-12-19 07:18:57 +00001816 AttributeSet Attribute =
Bill Wendling99faa3b2012-12-07 23:16:57 +00001817 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00001818 Attribute::get(C, Attribute::NoUnwind));
John McCall9fbd3182011-06-15 23:37:01 +00001819 RetainRVCallee =
1820 M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy,
Bill Wendling034b94b2012-12-19 07:18:57 +00001821 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00001822 }
1823 return RetainRVCallee;
1824}
1825
1826Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1827 if (!AutoreleaseRVCallee) {
1828 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001829 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman0daef3d2012-05-08 23:39:44 +00001830 Type *Params[] = { I8X };
1831 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling034b94b2012-12-19 07:18:57 +00001832 AttributeSet Attribute =
Bill Wendling99faa3b2012-12-07 23:16:57 +00001833 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00001834 Attribute::get(C, Attribute::NoUnwind));
John McCall9fbd3182011-06-15 23:37:01 +00001835 AutoreleaseRVCallee =
1836 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
Bill Wendling034b94b2012-12-19 07:18:57 +00001837 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00001838 }
1839 return AutoreleaseRVCallee;
1840}
1841
1842Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1843 if (!ReleaseCallee) {
1844 LLVMContext &C = M->getContext();
Dan Gohman0daef3d2012-05-08 23:39:44 +00001845 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling034b94b2012-12-19 07:18:57 +00001846 AttributeSet Attribute =
Bill Wendling99faa3b2012-12-07 23:16:57 +00001847 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00001848 Attribute::get(C, Attribute::NoUnwind));
John McCall9fbd3182011-06-15 23:37:01 +00001849 ReleaseCallee =
1850 M->getOrInsertFunction(
1851 "objc_release",
1852 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
Bill Wendling034b94b2012-12-19 07:18:57 +00001853 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00001854 }
1855 return ReleaseCallee;
1856}
1857
1858Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1859 if (!RetainCallee) {
1860 LLVMContext &C = M->getContext();
Dan Gohman0daef3d2012-05-08 23:39:44 +00001861 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling034b94b2012-12-19 07:18:57 +00001862 AttributeSet Attribute =
Bill Wendling99faa3b2012-12-07 23:16:57 +00001863 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00001864 Attribute::get(C, Attribute::NoUnwind));
John McCall9fbd3182011-06-15 23:37:01 +00001865 RetainCallee =
1866 M->getOrInsertFunction(
1867 "objc_retain",
1868 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling034b94b2012-12-19 07:18:57 +00001869 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00001870 }
1871 return RetainCallee;
1872}
1873
Dan Gohman44280692011-07-22 22:29:21 +00001874Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1875 if (!RetainBlockCallee) {
1876 LLVMContext &C = M->getContext();
Dan Gohman0daef3d2012-05-08 23:39:44 +00001877 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Dan Gohman1d2fd752011-09-14 18:33:34 +00001878 // objc_retainBlock is not nounwind because it calls user copy constructors
1879 // which could theoretically throw.
Dan Gohman44280692011-07-22 22:29:21 +00001880 RetainBlockCallee =
1881 M->getOrInsertFunction(
1882 "objc_retainBlock",
1883 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling99faa3b2012-12-07 23:16:57 +00001884 AttributeSet());
Dan Gohman44280692011-07-22 22:29:21 +00001885 }
1886 return RetainBlockCallee;
1887}
1888
John McCall9fbd3182011-06-15 23:37:01 +00001889Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1890 if (!AutoreleaseCallee) {
1891 LLVMContext &C = M->getContext();
Dan Gohman0daef3d2012-05-08 23:39:44 +00001892 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling034b94b2012-12-19 07:18:57 +00001893 AttributeSet Attribute =
Bill Wendling99faa3b2012-12-07 23:16:57 +00001894 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00001895 Attribute::get(C, Attribute::NoUnwind));
John McCall9fbd3182011-06-15 23:37:01 +00001896 AutoreleaseCallee =
1897 M->getOrInsertFunction(
1898 "objc_autorelease",
1899 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling034b94b2012-12-19 07:18:57 +00001900 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00001901 }
1902 return AutoreleaseCallee;
1903}
1904
Dan Gohman230768b2012-09-04 23:16:20 +00001905/// IsPotentialUse - Test whether the given value is possible a
1906/// reference-counted pointer, including tests which utilize AliasAnalysis.
1907static bool IsPotentialUse(const Value *Op, AliasAnalysis &AA) {
1908 // First make the rudimentary check.
1909 if (!IsPotentialUse(Op))
1910 return false;
1911
1912 // Objects in constant memory are not reference-counted.
1913 if (AA.pointsToConstantMemory(Op))
1914 return false;
1915
1916 // Pointers in constant memory are not pointing to reference-counted objects.
1917 if (const LoadInst *LI = dyn_cast<LoadInst>(Op))
1918 if (AA.pointsToConstantMemory(LI->getPointerOperand()))
1919 return false;
1920
1921 // Otherwise assume the worst.
1922 return true;
1923}
1924
John McCall9fbd3182011-06-15 23:37:01 +00001925/// CanAlterRefCount - Test whether the given instruction can result in a
1926/// reference count modification (positive or negative) for the pointer's
1927/// object.
1928static bool
1929CanAlterRefCount(const Instruction *Inst, const Value *Ptr,
1930 ProvenanceAnalysis &PA, InstructionClass Class) {
1931 switch (Class) {
1932 case IC_Autorelease:
1933 case IC_AutoreleaseRV:
1934 case IC_User:
1935 // These operations never directly modify a reference count.
1936 return false;
1937 default: break;
1938 }
1939
1940 ImmutableCallSite CS = static_cast<const Value *>(Inst);
1941 assert(CS && "Only calls can alter reference counts!");
1942
1943 // See if AliasAnalysis can help us with the call.
1944 AliasAnalysis::ModRefBehavior MRB = PA.getAA()->getModRefBehavior(CS);
1945 if (AliasAnalysis::onlyReadsMemory(MRB))
1946 return false;
1947 if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
1948 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1949 I != E; ++I) {
1950 const Value *Op = *I;
Dan Gohman230768b2012-09-04 23:16:20 +00001951 if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
John McCall9fbd3182011-06-15 23:37:01 +00001952 return true;
1953 }
1954 return false;
1955 }
1956
1957 // Assume the worst.
1958 return true;
1959}
1960
1961/// CanUse - Test whether the given instruction can "use" the given pointer's
1962/// object in a way that requires the reference count to be positive.
1963static bool
1964CanUse(const Instruction *Inst, const Value *Ptr, ProvenanceAnalysis &PA,
1965 InstructionClass Class) {
1966 // IC_Call operations (as opposed to IC_CallOrUser) never "use" objc pointers.
1967 if (Class == IC_Call)
1968 return false;
1969
1970 // Consider various instructions which may have pointer arguments which are
1971 // not "uses".
1972 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(Inst)) {
1973 // Comparing a pointer with null, or any other constant, isn't really a use,
1974 // because we don't care what the pointer points to, or about the values
1975 // of any other dynamic reference-counted pointers.
Dan Gohman230768b2012-09-04 23:16:20 +00001976 if (!IsPotentialUse(ICI->getOperand(1), *PA.getAA()))
John McCall9fbd3182011-06-15 23:37:01 +00001977 return false;
1978 } else if (ImmutableCallSite CS = static_cast<const Value *>(Inst)) {
1979 // For calls, just check the arguments (and not the callee operand).
1980 for (ImmutableCallSite::arg_iterator OI = CS.arg_begin(),
1981 OE = CS.arg_end(); OI != OE; ++OI) {
1982 const Value *Op = *OI;
Dan Gohman230768b2012-09-04 23:16:20 +00001983 if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
John McCall9fbd3182011-06-15 23:37:01 +00001984 return true;
1985 }
1986 return false;
1987 } else if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1988 // Special-case stores, because we don't care about the stored value, just
1989 // the store address.
1990 const Value *Op = GetUnderlyingObjCPtr(SI->getPointerOperand());
1991 // If we can't tell what the underlying object was, assume there is a
1992 // dependence.
Dan Gohman230768b2012-09-04 23:16:20 +00001993 return IsPotentialUse(Op, *PA.getAA()) && PA.related(Op, Ptr);
John McCall9fbd3182011-06-15 23:37:01 +00001994 }
1995
1996 // Check each operand for a match.
1997 for (User::const_op_iterator OI = Inst->op_begin(), OE = Inst->op_end();
1998 OI != OE; ++OI) {
1999 const Value *Op = *OI;
Dan Gohman230768b2012-09-04 23:16:20 +00002000 if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
John McCall9fbd3182011-06-15 23:37:01 +00002001 return true;
2002 }
2003 return false;
2004}
2005
2006/// CanInterruptRV - Test whether the given instruction can autorelease
2007/// any pointer or cause an autoreleasepool pop.
2008static bool
2009CanInterruptRV(InstructionClass Class) {
2010 switch (Class) {
2011 case IC_AutoreleasepoolPop:
2012 case IC_CallOrUser:
2013 case IC_Call:
2014 case IC_Autorelease:
2015 case IC_AutoreleaseRV:
2016 case IC_FusedRetainAutorelease:
2017 case IC_FusedRetainAutoreleaseRV:
2018 return true;
2019 default:
2020 return false;
2021 }
2022}
2023
2024namespace {
2025 /// DependenceKind - There are several kinds of dependence-like concepts in
2026 /// use here.
2027 enum DependenceKind {
2028 NeedsPositiveRetainCount,
Dan Gohman511568d2012-04-13 00:59:57 +00002029 AutoreleasePoolBoundary,
John McCall9fbd3182011-06-15 23:37:01 +00002030 CanChangeRetainCount,
2031 RetainAutoreleaseDep, ///< Blocks objc_retainAutorelease.
2032 RetainAutoreleaseRVDep, ///< Blocks objc_retainAutoreleaseReturnValue.
2033 RetainRVDep ///< Blocks objc_retainAutoreleasedReturnValue.
2034 };
2035}
2036
2037/// Depends - Test if there can be dependencies on Inst through Arg. This
2038/// function only tests dependencies relevant for removing pairs of calls.
2039static bool
2040Depends(DependenceKind Flavor, Instruction *Inst, const Value *Arg,
2041 ProvenanceAnalysis &PA) {
2042 // If we've reached the definition of Arg, stop.
2043 if (Inst == Arg)
2044 return true;
2045
2046 switch (Flavor) {
2047 case NeedsPositiveRetainCount: {
2048 InstructionClass Class = GetInstructionClass(Inst);
2049 switch (Class) {
2050 case IC_AutoreleasepoolPop:
2051 case IC_AutoreleasepoolPush:
2052 case IC_None:
2053 return false;
2054 default:
2055 return CanUse(Inst, Arg, PA, Class);
2056 }
2057 }
2058
Dan Gohman511568d2012-04-13 00:59:57 +00002059 case AutoreleasePoolBoundary: {
2060 InstructionClass Class = GetInstructionClass(Inst);
2061 switch (Class) {
2062 case IC_AutoreleasepoolPop:
2063 case IC_AutoreleasepoolPush:
2064 // These mark the end and begin of an autorelease pool scope.
2065 return true;
2066 default:
2067 // Nothing else does this.
2068 return false;
2069 }
2070 }
2071
John McCall9fbd3182011-06-15 23:37:01 +00002072 case CanChangeRetainCount: {
2073 InstructionClass Class = GetInstructionClass(Inst);
2074 switch (Class) {
2075 case IC_AutoreleasepoolPop:
2076 // Conservatively assume this can decrement any count.
2077 return true;
2078 case IC_AutoreleasepoolPush:
2079 case IC_None:
2080 return false;
2081 default:
2082 return CanAlterRefCount(Inst, Arg, PA, Class);
2083 }
2084 }
2085
2086 case RetainAutoreleaseDep:
2087 switch (GetBasicInstructionClass(Inst)) {
2088 case IC_AutoreleasepoolPop:
Dan Gohman511568d2012-04-13 00:59:57 +00002089 case IC_AutoreleasepoolPush:
John McCall9fbd3182011-06-15 23:37:01 +00002090 // Don't merge an objc_autorelease with an objc_retain inside a different
2091 // autoreleasepool scope.
2092 return true;
2093 case IC_Retain:
2094 case IC_RetainRV:
2095 // Check for a retain of the same pointer for merging.
2096 return GetObjCArg(Inst) == Arg;
2097 default:
2098 // Nothing else matters for objc_retainAutorelease formation.
2099 return false;
2100 }
John McCall9fbd3182011-06-15 23:37:01 +00002101
2102 case RetainAutoreleaseRVDep: {
2103 InstructionClass Class = GetBasicInstructionClass(Inst);
2104 switch (Class) {
2105 case IC_Retain:
2106 case IC_RetainRV:
2107 // Check for a retain of the same pointer for merging.
2108 return GetObjCArg(Inst) == Arg;
2109 default:
2110 // Anything that can autorelease interrupts
2111 // retainAutoreleaseReturnValue formation.
2112 return CanInterruptRV(Class);
2113 }
John McCall9fbd3182011-06-15 23:37:01 +00002114 }
2115
2116 case RetainRVDep:
2117 return CanInterruptRV(GetBasicInstructionClass(Inst));
2118 }
2119
2120 llvm_unreachable("Invalid dependence flavor");
John McCall9fbd3182011-06-15 23:37:01 +00002121}
2122
2123/// FindDependencies - Walk up the CFG from StartPos (which is in StartBB) and
2124/// find local and non-local dependencies on Arg.
2125/// TODO: Cache results?
2126static void
2127FindDependencies(DependenceKind Flavor,
2128 const Value *Arg,
2129 BasicBlock *StartBB, Instruction *StartInst,
2130 SmallPtrSet<Instruction *, 4> &DependingInstructions,
2131 SmallPtrSet<const BasicBlock *, 4> &Visited,
2132 ProvenanceAnalysis &PA) {
2133 BasicBlock::iterator StartPos = StartInst;
2134
2135 SmallVector<std::pair<BasicBlock *, BasicBlock::iterator>, 4> Worklist;
2136 Worklist.push_back(std::make_pair(StartBB, StartPos));
2137 do {
2138 std::pair<BasicBlock *, BasicBlock::iterator> Pair =
2139 Worklist.pop_back_val();
2140 BasicBlock *LocalStartBB = Pair.first;
2141 BasicBlock::iterator LocalStartPos = Pair.second;
2142 BasicBlock::iterator StartBBBegin = LocalStartBB->begin();
2143 for (;;) {
2144 if (LocalStartPos == StartBBBegin) {
2145 pred_iterator PI(LocalStartBB), PE(LocalStartBB, false);
2146 if (PI == PE)
2147 // If we've reached the function entry, produce a null dependence.
2148 DependingInstructions.insert(0);
2149 else
2150 // Add the predecessors to the worklist.
2151 do {
2152 BasicBlock *PredBB = *PI;
2153 if (Visited.insert(PredBB))
2154 Worklist.push_back(std::make_pair(PredBB, PredBB->end()));
2155 } while (++PI != PE);
2156 break;
2157 }
2158
2159 Instruction *Inst = --LocalStartPos;
2160 if (Depends(Flavor, Inst, Arg, PA)) {
2161 DependingInstructions.insert(Inst);
2162 break;
2163 }
2164 }
2165 } while (!Worklist.empty());
2166
2167 // Determine whether the original StartBB post-dominates all of the blocks we
2168 // visited. If not, insert a sentinal indicating that most optimizations are
2169 // not safe.
2170 for (SmallPtrSet<const BasicBlock *, 4>::const_iterator I = Visited.begin(),
2171 E = Visited.end(); I != E; ++I) {
2172 const BasicBlock *BB = *I;
2173 if (BB == StartBB)
2174 continue;
2175 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2176 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2177 const BasicBlock *Succ = *SI;
2178 if (Succ != StartBB && !Visited.count(Succ)) {
2179 DependingInstructions.insert(reinterpret_cast<Instruction *>(-1));
2180 return;
2181 }
2182 }
2183 }
2184}
2185
2186static bool isNullOrUndef(const Value *V) {
2187 return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
2188}
2189
2190static bool isNoopInstruction(const Instruction *I) {
2191 return isa<BitCastInst>(I) ||
2192 (isa<GetElementPtrInst>(I) &&
2193 cast<GetElementPtrInst>(I)->hasAllZeroIndices());
2194}
2195
2196/// OptimizeRetainCall - Turn objc_retain into
2197/// objc_retainAutoreleasedReturnValue if the operand is a return value.
2198void
2199ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) {
Dan Gohman447989c2012-04-27 18:56:31 +00002200 ImmutableCallSite CS(GetObjCArg(Retain));
2201 const Instruction *Call = CS.getInstruction();
John McCall9fbd3182011-06-15 23:37:01 +00002202 if (!Call) return;
2203 if (Call->getParent() != Retain->getParent()) return;
2204
2205 // Check that the call is next to the retain.
Dan Gohman447989c2012-04-27 18:56:31 +00002206 BasicBlock::const_iterator I = Call;
John McCall9fbd3182011-06-15 23:37:01 +00002207 ++I;
2208 while (isNoopInstruction(I)) ++I;
2209 if (&*I != Retain)
2210 return;
2211
2212 // Turn it to an objc_retainAutoreleasedReturnValue..
2213 Changed = true;
2214 ++NumPeeps;
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002215
Michael Gottesman715f6a62013-01-04 21:30:38 +00002216 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainCall: Transforming "
Michael Gottesmane7a715f2013-01-12 03:45:49 +00002217 "objc_retain => objc_retainAutoreleasedReturnValue"
2218 " since the operand is a return value.\n"
Michael Gottesman715f6a62013-01-04 21:30:38 +00002219 " Old: "
2220 << *Retain << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002221
John McCall9fbd3182011-06-15 23:37:01 +00002222 cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent()));
Michael Gottesman715f6a62013-01-04 21:30:38 +00002223
2224 DEBUG(dbgs() << " New: "
2225 << *Retain << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00002226}
2227
2228/// OptimizeRetainRVCall - Turn objc_retainAutoreleasedReturnValue into
Dan Gohman447989c2012-04-27 18:56:31 +00002229/// objc_retain if the operand is not a return value. Or, if it can be paired
2230/// with an objc_autoreleaseReturnValue, delete the pair and return true.
John McCall9fbd3182011-06-15 23:37:01 +00002231bool
2232ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
Dan Gohman6fedb3c2012-03-23 18:09:00 +00002233 // Check for the argument being from an immediately preceding call or invoke.
Dan Gohman447989c2012-04-27 18:56:31 +00002234 const Value *Arg = GetObjCArg(RetainRV);
2235 ImmutableCallSite CS(Arg);
2236 if (const Instruction *Call = CS.getInstruction()) {
John McCall9fbd3182011-06-15 23:37:01 +00002237 if (Call->getParent() == RetainRV->getParent()) {
Dan Gohman447989c2012-04-27 18:56:31 +00002238 BasicBlock::const_iterator I = Call;
John McCall9fbd3182011-06-15 23:37:01 +00002239 ++I;
2240 while (isNoopInstruction(I)) ++I;
2241 if (&*I == RetainRV)
2242 return false;
Dan Gohman447989c2012-04-27 18:56:31 +00002243 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Dan Gohman6fedb3c2012-03-23 18:09:00 +00002244 BasicBlock *RetainRVParent = RetainRV->getParent();
2245 if (II->getNormalDest() == RetainRVParent) {
Dan Gohman447989c2012-04-27 18:56:31 +00002246 BasicBlock::const_iterator I = RetainRVParent->begin();
Dan Gohman6fedb3c2012-03-23 18:09:00 +00002247 while (isNoopInstruction(I)) ++I;
2248 if (&*I == RetainRV)
2249 return false;
2250 }
John McCall9fbd3182011-06-15 23:37:01 +00002251 }
Dan Gohman6fedb3c2012-03-23 18:09:00 +00002252 }
John McCall9fbd3182011-06-15 23:37:01 +00002253
2254 // Check for being preceded by an objc_autoreleaseReturnValue on the same
2255 // pointer. In this case, we can delete the pair.
2256 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
2257 if (I != Begin) {
2258 do --I; while (I != Begin && isNoopInstruction(I));
2259 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
2260 GetObjCArg(I) == Arg) {
2261 Changed = true;
2262 ++NumPeeps;
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002263
Michael Gottesman87a0f022013-01-05 17:55:35 +00002264 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainRVCall: Erasing " << *I << "\n"
2265 << " Erasing " << *RetainRV
2266 << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002267
John McCall9fbd3182011-06-15 23:37:01 +00002268 EraseInstruction(I);
2269 EraseInstruction(RetainRV);
2270 return true;
2271 }
2272 }
2273
2274 // Turn it to a plain objc_retain.
2275 Changed = true;
2276 ++NumPeeps;
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002277
Michael Gottesman36e4bc42013-01-05 17:55:42 +00002278 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainRVCall: Transforming "
2279 "objc_retainAutoreleasedReturnValue => "
2280 "objc_retain since the operand is not a return value.\n"
2281 " Old: "
2282 << *RetainRV << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002283
John McCall9fbd3182011-06-15 23:37:01 +00002284 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
Michael Gottesman36e4bc42013-01-05 17:55:42 +00002285
2286 DEBUG(dbgs() << " New: "
2287 << *RetainRV << "\n");
2288
John McCall9fbd3182011-06-15 23:37:01 +00002289 return false;
2290}
2291
2292/// OptimizeAutoreleaseRVCall - Turn objc_autoreleaseReturnValue into
2293/// objc_autorelease if the result is not used as a return value.
2294void
Michael Gottesman0e385452013-01-12 01:25:19 +00002295ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
2296 InstructionClass &Class) {
John McCall9fbd3182011-06-15 23:37:01 +00002297 // Check for a return of the pointer value.
2298 const Value *Ptr = GetObjCArg(AutoreleaseRV);
Dan Gohman126a54f2011-08-12 00:36:31 +00002299 SmallVector<const Value *, 2> Users;
2300 Users.push_back(Ptr);
2301 do {
2302 Ptr = Users.pop_back_val();
2303 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
2304 UI != UE; ++UI) {
2305 const User *I = *UI;
2306 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
2307 return;
2308 if (isa<BitCastInst>(I))
2309 Users.push_back(I);
2310 }
2311 } while (!Users.empty());
John McCall9fbd3182011-06-15 23:37:01 +00002312
2313 Changed = true;
2314 ++NumPeeps;
Michael Gottesman48239c72013-01-06 21:07:11 +00002315
2316 DEBUG(dbgs() << "ObjCARCOpt::OptimizeAutoreleaseRVCall: Transforming "
2317 "objc_autoreleaseReturnValue => "
2318 "objc_autorelease since its operand is not used as a return "
2319 "value.\n"
2320 " Old: "
2321 << *AutoreleaseRV << "\n");
2322
Michael Gottesmane8c161a2013-01-12 01:25:15 +00002323 CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
2324 AutoreleaseRVCI->
John McCall9fbd3182011-06-15 23:37:01 +00002325 setCalledFunction(getAutoreleaseCallee(F.getParent()));
Michael Gottesmane8c161a2013-01-12 01:25:15 +00002326 AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
Michael Gottesman0e385452013-01-12 01:25:19 +00002327 Class = IC_Autorelease;
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002328
Michael Gottesman48239c72013-01-06 21:07:11 +00002329 DEBUG(dbgs() << " New: "
2330 << *AutoreleaseRV << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002331
John McCall9fbd3182011-06-15 23:37:01 +00002332}
2333
2334/// OptimizeIndividualCalls - Visit each call, one at a time, and make
2335/// simplifications without doing any additional analysis.
2336void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
2337 // Reset all the flags in preparation for recomputing them.
2338 UsedInThisFunction = 0;
2339
2340 // Visit all objc_* calls in F.
2341 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2342 Instruction *Inst = &*I++;
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00002343
Michael Gottesman5c0ae472013-01-04 21:29:57 +00002344 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Visiting: " <<
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00002345 *Inst << "\n");
2346
John McCall9fbd3182011-06-15 23:37:01 +00002347 InstructionClass Class = GetBasicInstructionClass(Inst);
2348
2349 switch (Class) {
2350 default: break;
2351
2352 // Delete no-op casts. These function calls have special semantics, but
2353 // the semantics are entirely implemented via lowering in the front-end,
2354 // so by the time they reach the optimizer, they are just no-op calls
2355 // which return their argument.
2356 //
2357 // There are gray areas here, as the ability to cast reference-counted
2358 // pointers to raw void* and back allows code to break ARC assumptions,
2359 // however these are currently considered to be unimportant.
2360 case IC_NoopCast:
2361 Changed = true;
2362 ++NumNoops;
Michael Gottesman4680abe2013-01-06 21:07:15 +00002363 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Erasing no-op cast:"
2364 " " << *Inst << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00002365 EraseInstruction(Inst);
2366 continue;
2367
2368 // If the pointer-to-weak-pointer is null, it's undefined behavior.
2369 case IC_StoreWeak:
2370 case IC_LoadWeak:
2371 case IC_LoadWeakRetained:
2372 case IC_InitWeak:
2373 case IC_DestroyWeak: {
2374 CallInst *CI = cast<CallInst>(Inst);
2375 if (isNullOrUndef(CI->getArgOperand(0))) {
Dan Gohmand6bf2012012-04-13 18:57:48 +00002376 Changed = true;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002377 Type *Ty = CI->getArgOperand(0)->getType();
John McCall9fbd3182011-06-15 23:37:01 +00002378 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2379 Constant::getNullValue(Ty),
2380 CI);
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002381 llvm::Value *NewValue = UndefValue::get(CI->getType());
Michael Gottesmane5494922013-01-06 21:54:30 +00002382 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: A null "
2383 "pointer-to-weak-pointer is undefined behavior.\n"
2384 " Old = " << *CI <<
2385 "\n New = " <<
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002386 *NewValue << "\n");
Michael Gottesmane5494922013-01-06 21:54:30 +00002387 CI->replaceAllUsesWith(NewValue);
John McCall9fbd3182011-06-15 23:37:01 +00002388 CI->eraseFromParent();
2389 continue;
2390 }
2391 break;
2392 }
2393 case IC_CopyWeak:
2394 case IC_MoveWeak: {
2395 CallInst *CI = cast<CallInst>(Inst);
2396 if (isNullOrUndef(CI->getArgOperand(0)) ||
2397 isNullOrUndef(CI->getArgOperand(1))) {
Dan Gohmand6bf2012012-04-13 18:57:48 +00002398 Changed = true;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002399 Type *Ty = CI->getArgOperand(0)->getType();
John McCall9fbd3182011-06-15 23:37:01 +00002400 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2401 Constant::getNullValue(Ty),
2402 CI);
Michael Gottesmane5494922013-01-06 21:54:30 +00002403
2404 llvm::Value *NewValue = UndefValue::get(CI->getType());
2405 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: A null "
2406 "pointer-to-weak-pointer is undefined behavior.\n"
2407 " Old = " << *CI <<
2408 "\n New = " <<
2409 *NewValue << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002410
Michael Gottesmane5494922013-01-06 21:54:30 +00002411 CI->replaceAllUsesWith(NewValue);
John McCall9fbd3182011-06-15 23:37:01 +00002412 CI->eraseFromParent();
2413 continue;
2414 }
2415 break;
2416 }
2417 case IC_Retain:
2418 OptimizeRetainCall(F, Inst);
2419 break;
2420 case IC_RetainRV:
2421 if (OptimizeRetainRVCall(F, Inst))
2422 continue;
2423 break;
2424 case IC_AutoreleaseRV:
Michael Gottesman0e385452013-01-12 01:25:19 +00002425 OptimizeAutoreleaseRVCall(F, Inst, Class);
John McCall9fbd3182011-06-15 23:37:01 +00002426 break;
2427 }
2428
2429 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
2430 if (IsAutorelease(Class) && Inst->use_empty()) {
2431 CallInst *Call = cast<CallInst>(Inst);
2432 const Value *Arg = Call->getArgOperand(0);
2433 Arg = FindSingleUseIdentifiedObject(Arg);
2434 if (Arg) {
2435 Changed = true;
2436 ++NumAutoreleases;
2437
2438 // Create the declaration lazily.
2439 LLVMContext &C = Inst->getContext();
2440 CallInst *NewCall =
2441 CallInst::Create(getReleaseCallee(F.getParent()),
2442 Call->getArgOperand(0), "", Call);
2443 NewCall->setMetadata(ImpreciseReleaseMDKind,
2444 MDNode::get(C, ArrayRef<Value *>()));
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002445
Michael Gottesman20d9fff2013-01-06 22:56:50 +00002446 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Replacing "
2447 "objc_autorelease(x) with objc_release(x) since x is "
2448 "otherwise unused.\n"
Michael Gottesman79561272013-01-06 22:56:54 +00002449 " Old: " << *Call <<
Michael Gottesman20d9fff2013-01-06 22:56:50 +00002450 "\n New: " <<
2451 *NewCall << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002452
John McCall9fbd3182011-06-15 23:37:01 +00002453 EraseInstruction(Call);
2454 Inst = NewCall;
2455 Class = IC_Release;
2456 }
2457 }
2458
2459 // For functions which can never be passed stack arguments, add
2460 // a tail keyword.
2461 if (IsAlwaysTail(Class)) {
2462 Changed = true;
Michael Gottesman817d4e92013-01-06 23:39:09 +00002463 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Adding tail keyword"
2464 " to function since it can never be passed stack args: " << *Inst <<
2465 "\n");
John McCall9fbd3182011-06-15 23:37:01 +00002466 cast<CallInst>(Inst)->setTailCall();
2467 }
2468
Michael Gottesmane8c161a2013-01-12 01:25:15 +00002469 // Ensure that functions that can never have a "tail" keyword due to the
2470 // semantics of ARC truly do not do so.
2471 if (IsNeverTail(Class)) {
2472 Changed = true;
2473 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Removing tail keyword"
2474 " from function: " << *Inst <<
2475 "\n");
2476 cast<CallInst>(Inst)->setTailCall(false);
2477 }
2478
John McCall9fbd3182011-06-15 23:37:01 +00002479 // Set nounwind as needed.
2480 if (IsNoThrow(Class)) {
2481 Changed = true;
Michael Gottesman38bc25a2013-01-06 23:39:13 +00002482 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Found no throw"
2483 " class. Setting nounwind on: " << *Inst << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00002484 cast<CallInst>(Inst)->setDoesNotThrow();
2485 }
2486
2487 if (!IsNoopOnNull(Class)) {
2488 UsedInThisFunction |= 1 << Class;
2489 continue;
2490 }
2491
2492 const Value *Arg = GetObjCArg(Inst);
2493
2494 // ARC calls with null are no-ops. Delete them.
2495 if (isNullOrUndef(Arg)) {
2496 Changed = true;
2497 ++NumNoops;
Michael Gottesmanfbe4d6b2013-01-07 00:04:52 +00002498 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: ARC calls with "
2499 " null are no-ops. Erasing: " << *Inst << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00002500 EraseInstruction(Inst);
2501 continue;
2502 }
2503
2504 // Keep track of which of retain, release, autorelease, and retain_block
2505 // are actually present in this function.
2506 UsedInThisFunction |= 1 << Class;
2507
2508 // If Arg is a PHI, and one or more incoming values to the
2509 // PHI are null, and the call is control-equivalent to the PHI, and there
2510 // are no relevant side effects between the PHI and the call, the call
2511 // could be pushed up to just those paths with non-null incoming values.
2512 // For now, don't bother splitting critical edges for this.
2513 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
2514 Worklist.push_back(std::make_pair(Inst, Arg));
2515 do {
2516 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
2517 Inst = Pair.first;
2518 Arg = Pair.second;
2519
2520 const PHINode *PN = dyn_cast<PHINode>(Arg);
2521 if (!PN) continue;
2522
2523 // Determine if the PHI has any null operands, or any incoming
2524 // critical edges.
2525 bool HasNull = false;
2526 bool HasCriticalEdges = false;
2527 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2528 Value *Incoming =
2529 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2530 if (isNullOrUndef(Incoming))
2531 HasNull = true;
2532 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
2533 .getNumSuccessors() != 1) {
2534 HasCriticalEdges = true;
2535 break;
2536 }
2537 }
2538 // If we have null operands and no critical edges, optimize.
2539 if (!HasCriticalEdges && HasNull) {
2540 SmallPtrSet<Instruction *, 4> DependingInstructions;
2541 SmallPtrSet<const BasicBlock *, 4> Visited;
2542
2543 // Check that there is nothing that cares about the reference
2544 // count between the call and the phi.
Dan Gohman511568d2012-04-13 00:59:57 +00002545 switch (Class) {
2546 case IC_Retain:
2547 case IC_RetainBlock:
2548 // These can always be moved up.
2549 break;
2550 case IC_Release:
Dan Gohman0daef3d2012-05-08 23:39:44 +00002551 // These can't be moved across things that care about the retain
2552 // count.
Dan Gohman511568d2012-04-13 00:59:57 +00002553 FindDependencies(NeedsPositiveRetainCount, Arg,
2554 Inst->getParent(), Inst,
2555 DependingInstructions, Visited, PA);
2556 break;
2557 case IC_Autorelease:
2558 // These can't be moved across autorelease pool scope boundaries.
2559 FindDependencies(AutoreleasePoolBoundary, Arg,
2560 Inst->getParent(), Inst,
2561 DependingInstructions, Visited, PA);
2562 break;
2563 case IC_RetainRV:
2564 case IC_AutoreleaseRV:
2565 // Don't move these; the RV optimization depends on the autoreleaseRV
2566 // being tail called, and the retainRV being immediately after a call
2567 // (which might still happen if we get lucky with codegen layout, but
2568 // it's not worth taking the chance).
2569 continue;
2570 default:
2571 llvm_unreachable("Invalid dependence flavor");
2572 }
2573
John McCall9fbd3182011-06-15 23:37:01 +00002574 if (DependingInstructions.size() == 1 &&
2575 *DependingInstructions.begin() == PN) {
2576 Changed = true;
2577 ++NumPartialNoops;
2578 // Clone the call into each predecessor that has a non-null value.
2579 CallInst *CInst = cast<CallInst>(Inst);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002580 Type *ParamTy = CInst->getArgOperand(0)->getType();
John McCall9fbd3182011-06-15 23:37:01 +00002581 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2582 Value *Incoming =
2583 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2584 if (!isNullOrUndef(Incoming)) {
2585 CallInst *Clone = cast<CallInst>(CInst->clone());
2586 Value *Op = PN->getIncomingValue(i);
2587 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
2588 if (Op->getType() != ParamTy)
2589 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
2590 Clone->setArgOperand(0, Op);
2591 Clone->insertBefore(InsertPos);
Michael Gottesman55811152013-01-09 19:23:24 +00002592
2593 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Cloning "
2594 << *CInst << "\n"
2595 " And inserting "
2596 "clone at " << *InsertPos << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00002597 Worklist.push_back(std::make_pair(Clone, Incoming));
2598 }
2599 }
2600 // Erase the original call.
Michael Gottesman55811152013-01-09 19:23:24 +00002601 DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00002602 EraseInstruction(CInst);
2603 continue;
2604 }
2605 }
2606 } while (!Worklist.empty());
2607 }
Michael Gottesman0d3582b2013-01-12 02:57:16 +00002608 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Finished List.\n");
John McCall9fbd3182011-06-15 23:37:01 +00002609}
2610
2611/// CheckForCFGHazards - Check for critical edges, loop boundaries, irreducible
2612/// control flow, or other CFG structures where moving code across the edge
2613/// would result in it being executed more.
2614void
2615ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
2616 DenseMap<const BasicBlock *, BBState> &BBStates,
2617 BBState &MyStates) const {
2618 // If any top-down local-use or possible-dec has a succ which is earlier in
2619 // the sequence, forget it.
Dan Gohman22cc4cc2012-03-02 01:13:53 +00002620 for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
John McCall9fbd3182011-06-15 23:37:01 +00002621 E = MyStates.top_down_ptr_end(); I != E; ++I)
2622 switch (I->second.GetSeq()) {
2623 default: break;
2624 case S_Use: {
2625 const Value *Arg = I->first;
2626 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2627 bool SomeSuccHasSame = false;
2628 bool AllSuccsHaveSame = true;
Dan Gohman22cc4cc2012-03-02 01:13:53 +00002629 PtrState &S = I->second;
Dan Gohmandbe266b2012-02-17 18:59:53 +00002630 succ_const_iterator SI(TI), SE(TI, false);
2631
2632 // If the terminator is an invoke marked with the
2633 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
2634 // ignored, for ARC purposes.
Michael Gottesmancf140052013-01-13 07:00:51 +00002635 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind)) {
2636 DEBUG(dbgs() << "ObjCARCOpt::CheckForCFGHazards: Found an invoke "
2637 "terminator marked with "
2638 "clang.arc.no_objc_arc_exceptions. Ignoring unwind "
2639 "edge.\n");
Dan Gohmandbe266b2012-02-17 18:59:53 +00002640 --SE;
Michael Gottesmancf140052013-01-13 07:00:51 +00002641 }
Dan Gohmandbe266b2012-02-17 18:59:53 +00002642
2643 for (; SI != SE; ++SI) {
Dan Gohman70e29682012-03-02 01:26:46 +00002644 Sequence SuccSSeq = S_None;
2645 bool SuccSRRIKnownSafe = false;
Dan Gohman0daef3d2012-05-08 23:39:44 +00002646 // If VisitBottomUp has pointer information for this successor, take
2647 // what we know about it.
Dan Gohman447989c2012-04-27 18:56:31 +00002648 DenseMap<const BasicBlock *, BBState>::iterator BBI =
2649 BBStates.find(*SI);
2650 assert(BBI != BBStates.end());
2651 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2652 SuccSSeq = SuccS.GetSeq();
2653 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
Dan Gohman70e29682012-03-02 01:26:46 +00002654 switch (SuccSSeq) {
John McCall9fbd3182011-06-15 23:37:01 +00002655 case S_None:
Dan Gohmana7f7db22011-08-12 00:26:31 +00002656 case S_CanRelease: {
Dan Gohman70e29682012-03-02 01:26:46 +00002657 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
Dan Gohmana7f7db22011-08-12 00:26:31 +00002658 S.ClearSequenceProgress();
Dan Gohman70e29682012-03-02 01:26:46 +00002659 break;
2660 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002661 continue;
2662 }
John McCall9fbd3182011-06-15 23:37:01 +00002663 case S_Use:
2664 SomeSuccHasSame = true;
2665 break;
2666 case S_Stop:
2667 case S_Release:
2668 case S_MovableRelease:
Dan Gohman70e29682012-03-02 01:26:46 +00002669 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002670 AllSuccsHaveSame = false;
John McCall9fbd3182011-06-15 23:37:01 +00002671 break;
2672 case S_Retain:
2673 llvm_unreachable("bottom-up pointer in retain state!");
2674 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002675 }
John McCall9fbd3182011-06-15 23:37:01 +00002676 // If the state at the other end of any of the successor edges
2677 // matches the current state, require all edges to match. This
2678 // guards against loops in the middle of a sequence.
2679 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002680 S.ClearSequenceProgress();
Dan Gohman2e68beb2011-12-12 18:13:53 +00002681 break;
John McCall9fbd3182011-06-15 23:37:01 +00002682 }
2683 case S_CanRelease: {
2684 const Value *Arg = I->first;
2685 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2686 bool SomeSuccHasSame = false;
2687 bool AllSuccsHaveSame = true;
Dan Gohman22cc4cc2012-03-02 01:13:53 +00002688 PtrState &S = I->second;
Dan Gohmandbe266b2012-02-17 18:59:53 +00002689 succ_const_iterator SI(TI), SE(TI, false);
2690
2691 // If the terminator is an invoke marked with the
2692 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
2693 // ignored, for ARC purposes.
Michael Gottesmancf140052013-01-13 07:00:51 +00002694 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind)) {
2695 DEBUG(dbgs() << "ObjCARCOpt::CheckForCFGHazards: Found an invoke "
2696 "terminator marked with "
2697 "clang.arc.no_objc_arc_exceptions. Ignoring unwind "
2698 "edge.\n");
Dan Gohmandbe266b2012-02-17 18:59:53 +00002699 --SE;
Michael Gottesmancf140052013-01-13 07:00:51 +00002700 }
Dan Gohmandbe266b2012-02-17 18:59:53 +00002701
2702 for (; SI != SE; ++SI) {
Dan Gohman70e29682012-03-02 01:26:46 +00002703 Sequence SuccSSeq = S_None;
2704 bool SuccSRRIKnownSafe = false;
Dan Gohman0daef3d2012-05-08 23:39:44 +00002705 // If VisitBottomUp has pointer information for this successor, take
2706 // what we know about it.
Dan Gohman447989c2012-04-27 18:56:31 +00002707 DenseMap<const BasicBlock *, BBState>::iterator BBI =
2708 BBStates.find(*SI);
2709 assert(BBI != BBStates.end());
2710 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2711 SuccSSeq = SuccS.GetSeq();
2712 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
Dan Gohman70e29682012-03-02 01:26:46 +00002713 switch (SuccSSeq) {
Dan Gohmana7f7db22011-08-12 00:26:31 +00002714 case S_None: {
Dan Gohman70e29682012-03-02 01:26:46 +00002715 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
Dan Gohmana7f7db22011-08-12 00:26:31 +00002716 S.ClearSequenceProgress();
Dan Gohman70e29682012-03-02 01:26:46 +00002717 break;
2718 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002719 continue;
2720 }
John McCall9fbd3182011-06-15 23:37:01 +00002721 case S_CanRelease:
2722 SomeSuccHasSame = true;
2723 break;
2724 case S_Stop:
2725 case S_Release:
2726 case S_MovableRelease:
2727 case S_Use:
Dan Gohman70e29682012-03-02 01:26:46 +00002728 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002729 AllSuccsHaveSame = false;
John McCall9fbd3182011-06-15 23:37:01 +00002730 break;
2731 case S_Retain:
2732 llvm_unreachable("bottom-up pointer in retain state!");
2733 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002734 }
John McCall9fbd3182011-06-15 23:37:01 +00002735 // If the state at the other end of any of the successor edges
2736 // matches the current state, require all edges to match. This
2737 // guards against loops in the middle of a sequence.
2738 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002739 S.ClearSequenceProgress();
Dan Gohman2e68beb2011-12-12 18:13:53 +00002740 break;
John McCall9fbd3182011-06-15 23:37:01 +00002741 }
2742 }
2743}
2744
2745bool
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002746ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002747 BasicBlock *BB,
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002748 MapVector<Value *, RRInfo> &Retains,
2749 BBState &MyStates) {
2750 bool NestingDetected = false;
2751 InstructionClass Class = GetInstructionClass(Inst);
2752 const Value *Arg = 0;
2753
2754 switch (Class) {
2755 case IC_Release: {
2756 Arg = GetObjCArg(Inst);
2757
2758 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2759
2760 // If we see two releases in a row on the same pointer. If so, make
2761 // a note, and we'll cicle back to revisit it after we've
2762 // hopefully eliminated the second release, which may allow us to
2763 // eliminate the first release too.
2764 // Theoretically we could implement removal of nested retain+release
2765 // pairs by making PtrState hold a stack of states, but this is
2766 // simple and avoids adding overhead for the non-nested case.
Michael Gottesmancf140052013-01-13 07:00:51 +00002767 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease) {
2768 DEBUG(dbgs() << "ObjCARCOpt::VisitInstructionBottomUp: Found nested "
2769 "releases (i.e. a release pair)\n");
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002770 NestingDetected = true;
Michael Gottesmancf140052013-01-13 07:00:51 +00002771 }
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002772
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002773 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
Dan Gohman50ade652012-04-25 00:50:46 +00002774 S.ResetSequenceProgress(ReleaseMetadata ? S_MovableRelease : S_Release);
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002775 S.RRI.ReleaseMetadata = ReleaseMetadata;
Dan Gohman230768b2012-09-04 23:16:20 +00002776 S.RRI.KnownSafe = S.IsKnownIncremented();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002777 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2778 S.RRI.Calls.insert(Inst);
2779
Dan Gohman230768b2012-09-04 23:16:20 +00002780 S.SetKnownPositiveRefCount();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002781 break;
2782 }
2783 case IC_RetainBlock:
2784 // An objc_retainBlock call with just a use may need to be kept,
2785 // because it may be copying a block from the stack to the heap.
2786 if (!IsRetainBlockOptimizable(Inst))
2787 break;
2788 // FALLTHROUGH
2789 case IC_Retain:
2790 case IC_RetainRV: {
2791 Arg = GetObjCArg(Inst);
2792
2793 PtrState &S = MyStates.getPtrBottomUpState(Arg);
Dan Gohman50ade652012-04-25 00:50:46 +00002794 S.SetKnownPositiveRefCount();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002795
2796 switch (S.GetSeq()) {
2797 case S_Stop:
2798 case S_Release:
2799 case S_MovableRelease:
2800 case S_Use:
2801 S.RRI.ReverseInsertPts.clear();
2802 // FALL THROUGH
2803 case S_CanRelease:
2804 // Don't do retain+release tracking for IC_RetainRV, because it's
2805 // better to let it remain as the first instruction after a call.
2806 if (Class != IC_RetainRV) {
2807 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2808 Retains[Inst] = S.RRI;
2809 }
2810 S.ClearSequenceProgress();
2811 break;
2812 case S_None:
2813 break;
2814 case S_Retain:
2815 llvm_unreachable("bottom-up pointer in retain state!");
2816 }
2817 return NestingDetected;
2818 }
2819 case IC_AutoreleasepoolPop:
2820 // Conservatively, clear MyStates for all known pointers.
2821 MyStates.clearBottomUpPointers();
2822 return NestingDetected;
2823 case IC_AutoreleasepoolPush:
2824 case IC_None:
2825 // These are irrelevant.
2826 return NestingDetected;
2827 default:
2828 break;
2829 }
2830
2831 // Consider any other possible effects of this instruction on each
2832 // pointer being tracked.
2833 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
2834 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
2835 const Value *Ptr = MI->first;
2836 if (Ptr == Arg)
2837 continue; // Handled above.
2838 PtrState &S = MI->second;
2839 Sequence Seq = S.GetSeq();
2840
2841 // Check for possible releases.
2842 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Dan Gohman50ade652012-04-25 00:50:46 +00002843 S.ClearRefCount();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002844 switch (Seq) {
2845 case S_Use:
2846 S.SetSeq(S_CanRelease);
2847 continue;
2848 case S_CanRelease:
2849 case S_Release:
2850 case S_MovableRelease:
2851 case S_Stop:
2852 case S_None:
2853 break;
2854 case S_Retain:
2855 llvm_unreachable("bottom-up pointer in retain state!");
2856 }
2857 }
2858
2859 // Check for possible direct uses.
2860 switch (Seq) {
2861 case S_Release:
2862 case S_MovableRelease:
2863 if (CanUse(Inst, Ptr, PA, Class)) {
2864 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002865 // If this is an invoke instruction, we're scanning it as part of
2866 // one of its successor blocks, since we can't insert code after it
2867 // in its own block, and we don't want to split critical edges.
2868 if (isa<InvokeInst>(Inst))
2869 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2870 else
Francois Pichetb54a5ed2012-03-24 01:36:37 +00002871 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002872 S.SetSeq(S_Use);
2873 } else if (Seq == S_Release &&
2874 (Class == IC_User || Class == IC_CallOrUser)) {
2875 // Non-movable releases depend on any possible objc pointer use.
2876 S.SetSeq(S_Stop);
2877 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002878 // As above; handle invoke specially.
2879 if (isa<InvokeInst>(Inst))
2880 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2881 else
Francois Pichetb54a5ed2012-03-24 01:36:37 +00002882 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002883 }
2884 break;
2885 case S_Stop:
2886 if (CanUse(Inst, Ptr, PA, Class))
2887 S.SetSeq(S_Use);
2888 break;
2889 case S_CanRelease:
2890 case S_Use:
2891 case S_None:
2892 break;
2893 case S_Retain:
2894 llvm_unreachable("bottom-up pointer in retain state!");
2895 }
2896 }
2897
2898 return NestingDetected;
2899}
2900
2901bool
John McCall9fbd3182011-06-15 23:37:01 +00002902ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2903 DenseMap<const BasicBlock *, BBState> &BBStates,
2904 MapVector<Value *, RRInfo> &Retains) {
2905 bool NestingDetected = false;
2906 BBState &MyStates = BBStates[BB];
2907
2908 // Merge the states from each successor to compute the initial state
2909 // for the current block.
Dan Gohman40e46602012-08-27 18:31:36 +00002910 BBState::edge_iterator SI(MyStates.succ_begin()),
2911 SE(MyStates.succ_end());
2912 if (SI != SE) {
Dan Gohmaneeeb7752012-04-24 22:53:18 +00002913 const BasicBlock *Succ = *SI;
2914 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
2915 assert(I != BBStates.end());
2916 MyStates.InitFromSucc(I->second);
2917 ++SI;
2918 for (; SI != SE; ++SI) {
2919 Succ = *SI;
2920 I = BBStates.find(Succ);
2921 assert(I != BBStates.end());
2922 MyStates.MergeSucc(I->second);
2923 }
Dan Gohmandbe266b2012-02-17 18:59:53 +00002924 }
John McCall9fbd3182011-06-15 23:37:01 +00002925
2926 // Visit all the instructions, bottom-up.
2927 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2928 Instruction *Inst = llvm::prior(I);
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002929
2930 // Invoke instructions are visited as part of their successors (below).
2931 if (isa<InvokeInst>(Inst))
2932 continue;
2933
Michael Gottesmancf140052013-01-13 07:00:51 +00002934 DEBUG(dbgs() << "ObjCARCOpt::VisitButtonUp: Visiting " << *Inst << "\n");
2935
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002936 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
2937 }
2938
Dan Gohman447989c2012-04-27 18:56:31 +00002939 // If there's a predecessor with an invoke, visit the invoke as if it were
2940 // part of this block, since we can't insert code after an invoke in its own
2941 // block, and we don't want to split critical edges.
Dan Gohmaneeeb7752012-04-24 22:53:18 +00002942 for (BBState::edge_iterator PI(MyStates.pred_begin()),
2943 PE(MyStates.pred_end()); PI != PE; ++PI) {
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002944 BasicBlock *Pred = *PI;
Dan Gohman447989c2012-04-27 18:56:31 +00002945 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
2946 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002947 }
John McCall9fbd3182011-06-15 23:37:01 +00002948
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002949 return NestingDetected;
2950}
John McCall9fbd3182011-06-15 23:37:01 +00002951
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002952bool
2953ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
2954 DenseMap<Value *, RRInfo> &Releases,
2955 BBState &MyStates) {
2956 bool NestingDetected = false;
2957 InstructionClass Class = GetInstructionClass(Inst);
2958 const Value *Arg = 0;
John McCall9fbd3182011-06-15 23:37:01 +00002959
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002960 switch (Class) {
2961 case IC_RetainBlock:
2962 // An objc_retainBlock call with just a use may need to be kept,
2963 // because it may be copying a block from the stack to the heap.
2964 if (!IsRetainBlockOptimizable(Inst))
2965 break;
2966 // FALLTHROUGH
2967 case IC_Retain:
2968 case IC_RetainRV: {
2969 Arg = GetObjCArg(Inst);
2970
2971 PtrState &S = MyStates.getPtrTopDownState(Arg);
2972
2973 // Don't do retain+release tracking for IC_RetainRV, because it's
2974 // better to let it remain as the first instruction after a call.
2975 if (Class != IC_RetainRV) {
2976 // If we see two retains in a row on the same pointer. If so, make
John McCall9fbd3182011-06-15 23:37:01 +00002977 // a note, and we'll cicle back to revisit it after we've
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002978 // hopefully eliminated the second retain, which may allow us to
2979 // eliminate the first retain too.
John McCall9fbd3182011-06-15 23:37:01 +00002980 // Theoretically we could implement removal of nested retain+release
2981 // pairs by making PtrState hold a stack of states, but this is
2982 // simple and avoids adding overhead for the non-nested case.
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002983 if (S.GetSeq() == S_Retain)
John McCall9fbd3182011-06-15 23:37:01 +00002984 NestingDetected = true;
2985
Dan Gohman50ade652012-04-25 00:50:46 +00002986 S.ResetSequenceProgress(S_Retain);
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002987 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
Dan Gohman230768b2012-09-04 23:16:20 +00002988 S.RRI.KnownSafe = S.IsKnownIncremented();
John McCall9fbd3182011-06-15 23:37:01 +00002989 S.RRI.Calls.insert(Inst);
John McCall9fbd3182011-06-15 23:37:01 +00002990 }
John McCall9fbd3182011-06-15 23:37:01 +00002991
Dan Gohman230768b2012-09-04 23:16:20 +00002992 S.SetKnownPositiveRefCount();
Dan Gohmanc72d3be2012-07-23 19:27:31 +00002993
2994 // A retain can be a potential use; procede to the generic checking
2995 // code below.
2996 break;
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002997 }
2998 case IC_Release: {
2999 Arg = GetObjCArg(Inst);
3000
3001 PtrState &S = MyStates.getPtrTopDownState(Arg);
Dan Gohman230768b2012-09-04 23:16:20 +00003002 S.ClearRefCount();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003003
3004 switch (S.GetSeq()) {
3005 case S_Retain:
3006 case S_CanRelease:
3007 S.RRI.ReverseInsertPts.clear();
3008 // FALL THROUGH
3009 case S_Use:
3010 S.RRI.ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
3011 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
3012 Releases[Inst] = S.RRI;
3013 S.ClearSequenceProgress();
3014 break;
3015 case S_None:
3016 break;
3017 case S_Stop:
3018 case S_Release:
3019 case S_MovableRelease:
3020 llvm_unreachable("top-down pointer in release state!");
3021 }
3022 break;
3023 }
3024 case IC_AutoreleasepoolPop:
3025 // Conservatively, clear MyStates for all known pointers.
3026 MyStates.clearTopDownPointers();
3027 return NestingDetected;
3028 case IC_AutoreleasepoolPush:
3029 case IC_None:
3030 // These are irrelevant.
3031 return NestingDetected;
3032 default:
3033 break;
3034 }
3035
3036 // Consider any other possible effects of this instruction on each
3037 // pointer being tracked.
3038 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
3039 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
3040 const Value *Ptr = MI->first;
3041 if (Ptr == Arg)
3042 continue; // Handled above.
3043 PtrState &S = MI->second;
3044 Sequence Seq = S.GetSeq();
3045
3046 // Check for possible releases.
3047 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Dan Gohman50ade652012-04-25 00:50:46 +00003048 S.ClearRefCount();
John McCall9fbd3182011-06-15 23:37:01 +00003049 switch (Seq) {
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003050 case S_Retain:
3051 S.SetSeq(S_CanRelease);
3052 assert(S.RRI.ReverseInsertPts.empty());
3053 S.RRI.ReverseInsertPts.insert(Inst);
3054
3055 // One call can't cause a transition from S_Retain to S_CanRelease
3056 // and S_CanRelease to S_Use. If we've made the first transition,
3057 // we're done.
3058 continue;
John McCall9fbd3182011-06-15 23:37:01 +00003059 case S_Use:
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003060 case S_CanRelease:
John McCall9fbd3182011-06-15 23:37:01 +00003061 case S_None:
3062 break;
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003063 case S_Stop:
3064 case S_Release:
3065 case S_MovableRelease:
3066 llvm_unreachable("top-down pointer in release state!");
John McCall9fbd3182011-06-15 23:37:01 +00003067 }
3068 }
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003069
3070 // Check for possible direct uses.
3071 switch (Seq) {
3072 case S_CanRelease:
3073 if (CanUse(Inst, Ptr, PA, Class))
3074 S.SetSeq(S_Use);
3075 break;
3076 case S_Retain:
3077 case S_Use:
3078 case S_None:
3079 break;
3080 case S_Stop:
3081 case S_Release:
3082 case S_MovableRelease:
3083 llvm_unreachable("top-down pointer in release state!");
3084 }
John McCall9fbd3182011-06-15 23:37:01 +00003085 }
3086
3087 return NestingDetected;
3088}
3089
3090bool
3091ObjCARCOpt::VisitTopDown(BasicBlock *BB,
3092 DenseMap<const BasicBlock *, BBState> &BBStates,
3093 DenseMap<Value *, RRInfo> &Releases) {
3094 bool NestingDetected = false;
3095 BBState &MyStates = BBStates[BB];
3096
3097 // Merge the states from each predecessor to compute the initial state
3098 // for the current block.
Dan Gohman40e46602012-08-27 18:31:36 +00003099 BBState::edge_iterator PI(MyStates.pred_begin()),
3100 PE(MyStates.pred_end());
3101 if (PI != PE) {
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003102 const BasicBlock *Pred = *PI;
3103 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
3104 assert(I != BBStates.end());
3105 MyStates.InitFromPred(I->second);
3106 ++PI;
3107 for (; PI != PE; ++PI) {
3108 Pred = *PI;
3109 I = BBStates.find(Pred);
3110 assert(I != BBStates.end());
3111 MyStates.MergePred(I->second);
3112 }
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003113 }
John McCall9fbd3182011-06-15 23:37:01 +00003114
3115 // Visit all the instructions, top-down.
3116 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3117 Instruction *Inst = I;
Michael Gottesmancf140052013-01-13 07:00:51 +00003118
3119 DEBUG(dbgs() << "ObjCARCOpt::VisitTopDown: Visiting " << *Inst << "\n");
3120
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003121 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
John McCall9fbd3182011-06-15 23:37:01 +00003122 }
3123
3124 CheckForCFGHazards(BB, BBStates, MyStates);
3125 return NestingDetected;
3126}
3127
Dan Gohman59a1c932011-12-12 19:42:25 +00003128static void
3129ComputePostOrders(Function &F,
3130 SmallVectorImpl<BasicBlock *> &PostOrder,
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003131 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
3132 unsigned NoObjCARCExceptionsMDKind,
3133 DenseMap<const BasicBlock *, BBState> &BBStates) {
Dan Gohman59a1c932011-12-12 19:42:25 +00003134 /// Visited - The visited set, for doing DFS walks.
3135 SmallPtrSet<BasicBlock *, 16> Visited;
3136
3137 // Do DFS, computing the PostOrder.
3138 SmallPtrSet<BasicBlock *, 16> OnStack;
3139 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003140
3141 // Functions always have exactly one entry block, and we don't have
3142 // any other block that we treat like an entry block.
Dan Gohman59a1c932011-12-12 19:42:25 +00003143 BasicBlock *EntryBB = &F.getEntryBlock();
Dan Gohman0daef3d2012-05-08 23:39:44 +00003144 BBState &MyStates = BBStates[EntryBB];
3145 MyStates.SetAsEntry();
3146 TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
3147 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
Dan Gohman59a1c932011-12-12 19:42:25 +00003148 Visited.insert(EntryBB);
3149 OnStack.insert(EntryBB);
3150 do {
3151 dfs_next_succ:
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003152 BasicBlock *CurrBB = SuccStack.back().first;
3153 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
3154 succ_iterator SE(TI, false);
Dan Gohman0daef3d2012-05-08 23:39:44 +00003155
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003156 // If the terminator is an invoke marked with the
3157 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
3158 // ignored, for ARC purposes.
Michael Gottesmancf140052013-01-13 07:00:51 +00003159 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind)) {
3160 DEBUG(dbgs() << "ObjCARCOpt::ComputePostOrders: Found an invoke "
3161 "terminator marked with "
3162 "clang.arc.no_objc_arc_exceptions. Ignoring unwind "
3163 "edge.\n");
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003164 --SE;
Michael Gottesmancf140052013-01-13 07:00:51 +00003165 }
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003166
3167 while (SuccStack.back().second != SE) {
3168 BasicBlock *SuccBB = *SuccStack.back().second++;
3169 if (Visited.insert(SuccBB)) {
Dan Gohman0daef3d2012-05-08 23:39:44 +00003170 TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
3171 SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003172 BBStates[CurrBB].addSucc(SuccBB);
Dan Gohman0daef3d2012-05-08 23:39:44 +00003173 BBState &SuccStates = BBStates[SuccBB];
3174 SuccStates.addPred(CurrBB);
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003175 OnStack.insert(SuccBB);
Dan Gohman59a1c932011-12-12 19:42:25 +00003176 goto dfs_next_succ;
3177 }
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003178
3179 if (!OnStack.count(SuccBB)) {
3180 BBStates[CurrBB].addSucc(SuccBB);
3181 BBStates[SuccBB].addPred(CurrBB);
3182 }
Dan Gohman59a1c932011-12-12 19:42:25 +00003183 }
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003184 OnStack.erase(CurrBB);
3185 PostOrder.push_back(CurrBB);
3186 SuccStack.pop_back();
Dan Gohman59a1c932011-12-12 19:42:25 +00003187 } while (!SuccStack.empty());
3188
3189 Visited.clear();
3190
Dan Gohman59a1c932011-12-12 19:42:25 +00003191 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003192 // Functions may have many exits, and there also blocks which we treat
3193 // as exits due to ignored edges.
3194 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
3195 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
3196 BasicBlock *ExitBB = I;
3197 BBState &MyStates = BBStates[ExitBB];
3198 if (!MyStates.isExit())
3199 continue;
3200
Dan Gohman447989c2012-04-27 18:56:31 +00003201 MyStates.SetAsExit();
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003202
3203 PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
Dan Gohman59a1c932011-12-12 19:42:25 +00003204 Visited.insert(ExitBB);
3205 while (!PredStack.empty()) {
3206 reverse_dfs_next_succ:
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003207 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
3208 while (PredStack.back().second != PE) {
Dan Gohman59a1c932011-12-12 19:42:25 +00003209 BasicBlock *BB = *PredStack.back().second++;
Dan Gohman59a1c932011-12-12 19:42:25 +00003210 if (Visited.insert(BB)) {
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003211 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
Dan Gohman59a1c932011-12-12 19:42:25 +00003212 goto reverse_dfs_next_succ;
3213 }
3214 }
3215 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
3216 }
3217 }
3218}
3219
John McCall9fbd3182011-06-15 23:37:01 +00003220// Visit - Visit the function both top-down and bottom-up.
3221bool
3222ObjCARCOpt::Visit(Function &F,
3223 DenseMap<const BasicBlock *, BBState> &BBStates,
3224 MapVector<Value *, RRInfo> &Retains,
3225 DenseMap<Value *, RRInfo> &Releases) {
Dan Gohman59a1c932011-12-12 19:42:25 +00003226
3227 // Use reverse-postorder traversals, because we magically know that loops
3228 // will be well behaved, i.e. they won't repeatedly call retain on a single
3229 // pointer without doing a release. We can't use the ReversePostOrderTraversal
3230 // class here because we want the reverse-CFG postorder to consider each
3231 // function exit point, and we want to ignore selected cycle edges.
3232 SmallVector<BasicBlock *, 16> PostOrder;
3233 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003234 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
3235 NoObjCARCExceptionsMDKind,
3236 BBStates);
Dan Gohman59a1c932011-12-12 19:42:25 +00003237
3238 // Use reverse-postorder on the reverse CFG for bottom-up.
John McCall9fbd3182011-06-15 23:37:01 +00003239 bool BottomUpNestingDetected = false;
Dan Gohmanb48ef3a2011-08-18 21:27:42 +00003240 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
Dan Gohman59a1c932011-12-12 19:42:25 +00003241 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
3242 I != E; ++I)
3243 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
John McCall9fbd3182011-06-15 23:37:01 +00003244
Dan Gohman59a1c932011-12-12 19:42:25 +00003245 // Use reverse-postorder for top-down.
John McCall9fbd3182011-06-15 23:37:01 +00003246 bool TopDownNestingDetected = false;
Dan Gohman59a1c932011-12-12 19:42:25 +00003247 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
3248 PostOrder.rbegin(), E = PostOrder.rend();
3249 I != E; ++I)
3250 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
John McCall9fbd3182011-06-15 23:37:01 +00003251
3252 return TopDownNestingDetected && BottomUpNestingDetected;
3253}
3254
3255/// MoveCalls - Move the calls in RetainsToMove and ReleasesToMove.
3256void ObjCARCOpt::MoveCalls(Value *Arg,
3257 RRInfo &RetainsToMove,
3258 RRInfo &ReleasesToMove,
3259 MapVector<Value *, RRInfo> &Retains,
3260 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman44280692011-07-22 22:29:21 +00003261 SmallVectorImpl<Instruction *> &DeadInsts,
3262 Module *M) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003263 Type *ArgTy = Arg->getType();
Dan Gohman44280692011-07-22 22:29:21 +00003264 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
John McCall9fbd3182011-06-15 23:37:01 +00003265
3266 // Insert the new retain and release calls.
3267 for (SmallPtrSet<Instruction *, 2>::const_iterator
3268 PI = ReleasesToMove.ReverseInsertPts.begin(),
3269 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
3270 Instruction *InsertPt = *PI;
3271 Value *MyArg = ArgTy == ParamTy ? Arg :
3272 new BitCastInst(Arg, ParamTy, "", InsertPt);
3273 CallInst *Call =
3274 CallInst::Create(RetainsToMove.IsRetainBlock ?
Dan Gohman44280692011-07-22 22:29:21 +00003275 getRetainBlockCallee(M) : getRetainCallee(M),
John McCall9fbd3182011-06-15 23:37:01 +00003276 MyArg, "", InsertPt);
3277 Call->setDoesNotThrow();
Dan Gohman79522dc2012-01-13 00:39:07 +00003278 if (RetainsToMove.IsRetainBlock)
Dan Gohmana974bea2011-10-17 22:53:25 +00003279 Call->setMetadata(CopyOnEscapeMDKind,
3280 MDNode::get(M->getContext(), ArrayRef<Value *>()));
Dan Gohman79522dc2012-01-13 00:39:07 +00003281 else
John McCall9fbd3182011-06-15 23:37:01 +00003282 Call->setTailCall();
Michael Gottesman55811152013-01-09 19:23:24 +00003283
3284 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Inserting new Release: " << *Call
3285 << "\n"
3286 " At insertion point: " << *InsertPt
3287 << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00003288 }
3289 for (SmallPtrSet<Instruction *, 2>::const_iterator
3290 PI = RetainsToMove.ReverseInsertPts.begin(),
3291 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
Dan Gohmanfbab4a82012-03-23 17:47:54 +00003292 Instruction *InsertPt = *PI;
3293 Value *MyArg = ArgTy == ParamTy ? Arg :
3294 new BitCastInst(Arg, ParamTy, "", InsertPt);
3295 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
3296 "", InsertPt);
3297 // Attach a clang.imprecise_release metadata tag, if appropriate.
3298 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
3299 Call->setMetadata(ImpreciseReleaseMDKind, M);
3300 Call->setDoesNotThrow();
3301 if (ReleasesToMove.IsTailCallRelease)
3302 Call->setTailCall();
Michael Gottesman55811152013-01-09 19:23:24 +00003303
3304 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Inserting new Retain: " << *Call
3305 << "\n"
3306 " At insertion point: " << *InsertPt
3307 << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00003308 }
3309
3310 // Delete the original retain and release calls.
3311 for (SmallPtrSet<Instruction *, 2>::const_iterator
3312 AI = RetainsToMove.Calls.begin(),
3313 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
3314 Instruction *OrigRetain = *AI;
3315 Retains.blot(OrigRetain);
3316 DeadInsts.push_back(OrigRetain);
Michael Gottesman55811152013-01-09 19:23:24 +00003317 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Deleting retain: " << *OrigRetain <<
3318 "\n");
John McCall9fbd3182011-06-15 23:37:01 +00003319 }
3320 for (SmallPtrSet<Instruction *, 2>::const_iterator
3321 AI = ReleasesToMove.Calls.begin(),
3322 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
3323 Instruction *OrigRelease = *AI;
3324 Releases.erase(OrigRelease);
3325 DeadInsts.push_back(OrigRelease);
Michael Gottesman55811152013-01-09 19:23:24 +00003326 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Deleting release: " << *OrigRelease
3327 << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00003328 }
3329}
3330
Dan Gohmand6bf2012012-04-13 18:57:48 +00003331/// PerformCodePlacement - Identify pairings between the retains and releases,
3332/// and delete and/or move them.
John McCall9fbd3182011-06-15 23:37:01 +00003333bool
3334ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
3335 &BBStates,
3336 MapVector<Value *, RRInfo> &Retains,
Dan Gohman44280692011-07-22 22:29:21 +00003337 DenseMap<Value *, RRInfo> &Releases,
3338 Module *M) {
John McCall9fbd3182011-06-15 23:37:01 +00003339 bool AnyPairsCompletelyEliminated = false;
3340 RRInfo RetainsToMove;
3341 RRInfo ReleasesToMove;
3342 SmallVector<Instruction *, 4> NewRetains;
3343 SmallVector<Instruction *, 4> NewReleases;
3344 SmallVector<Instruction *, 8> DeadInsts;
3345
Dan Gohmand6bf2012012-04-13 18:57:48 +00003346 // Visit each retain.
John McCall9fbd3182011-06-15 23:37:01 +00003347 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
Dan Gohman597fece2011-09-29 22:25:23 +00003348 E = Retains.end(); I != E; ++I) {
3349 Value *V = I->first;
John McCall9fbd3182011-06-15 23:37:01 +00003350 if (!V) continue; // blotted
3351
3352 Instruction *Retain = cast<Instruction>(V);
Michael Gottesman55811152013-01-09 19:23:24 +00003353
3354 DEBUG(dbgs() << "ObjCARCOpt::PerformCodePlacement: Visiting: " << *Retain
3355 << "\n");
3356
John McCall9fbd3182011-06-15 23:37:01 +00003357 Value *Arg = GetObjCArg(Retain);
3358
Dan Gohman79522dc2012-01-13 00:39:07 +00003359 // If the object being released is in static or stack storage, we know it's
John McCall9fbd3182011-06-15 23:37:01 +00003360 // not being managed by ObjC reference counting, so we can delete pairs
3361 // regardless of what possible decrements or uses lie between them.
Dan Gohman79522dc2012-01-13 00:39:07 +00003362 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
Dan Gohman0daef3d2012-05-08 23:39:44 +00003363
Dan Gohman1b31ea82011-08-22 17:29:11 +00003364 // A constant pointer can't be pointing to an object on the heap. It may
3365 // be reference-counted, but it won't be deleted.
3366 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
3367 if (const GlobalVariable *GV =
3368 dyn_cast<GlobalVariable>(
3369 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
3370 if (GV->isConstant())
3371 KnownSafe = true;
3372
John McCall9fbd3182011-06-15 23:37:01 +00003373 // If a pair happens in a region where it is known that the reference count
3374 // is already incremented, we can similarly ignore possible decrements.
Dan Gohmane6d5e882011-08-19 00:26:36 +00003375 bool KnownSafeTD = true, KnownSafeBU = true;
John McCall9fbd3182011-06-15 23:37:01 +00003376
3377 // Connect the dots between the top-down-collected RetainsToMove and
3378 // bottom-up-collected ReleasesToMove to form sets of related calls.
3379 // This is an iterative process so that we connect multiple releases
3380 // to multiple retains if needed.
3381 unsigned OldDelta = 0;
3382 unsigned NewDelta = 0;
3383 unsigned OldCount = 0;
3384 unsigned NewCount = 0;
3385 bool FirstRelease = true;
3386 bool FirstRetain = true;
3387 NewRetains.push_back(Retain);
3388 for (;;) {
3389 for (SmallVectorImpl<Instruction *>::const_iterator
3390 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
3391 Instruction *NewRetain = *NI;
3392 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
3393 assert(It != Retains.end());
3394 const RRInfo &NewRetainRRI = It->second;
Dan Gohmane6d5e882011-08-19 00:26:36 +00003395 KnownSafeTD &= NewRetainRRI.KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00003396 for (SmallPtrSet<Instruction *, 2>::const_iterator
3397 LI = NewRetainRRI.Calls.begin(),
3398 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
3399 Instruction *NewRetainRelease = *LI;
3400 DenseMap<Value *, RRInfo>::const_iterator Jt =
3401 Releases.find(NewRetainRelease);
3402 if (Jt == Releases.end())
3403 goto next_retain;
3404 const RRInfo &NewRetainReleaseRRI = Jt->second;
3405 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
3406 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
3407 OldDelta -=
3408 BBStates[NewRetainRelease->getParent()].GetAllPathCount();
3409
3410 // Merge the ReleaseMetadata and IsTailCallRelease values.
3411 if (FirstRelease) {
3412 ReleasesToMove.ReleaseMetadata =
3413 NewRetainReleaseRRI.ReleaseMetadata;
3414 ReleasesToMove.IsTailCallRelease =
3415 NewRetainReleaseRRI.IsTailCallRelease;
3416 FirstRelease = false;
3417 } else {
3418 if (ReleasesToMove.ReleaseMetadata !=
3419 NewRetainReleaseRRI.ReleaseMetadata)
3420 ReleasesToMove.ReleaseMetadata = 0;
3421 if (ReleasesToMove.IsTailCallRelease !=
3422 NewRetainReleaseRRI.IsTailCallRelease)
3423 ReleasesToMove.IsTailCallRelease = false;
3424 }
3425
3426 // Collect the optimal insertion points.
3427 if (!KnownSafe)
3428 for (SmallPtrSet<Instruction *, 2>::const_iterator
3429 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
3430 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
3431 RI != RE; ++RI) {
3432 Instruction *RIP = *RI;
3433 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
3434 NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
3435 }
3436 NewReleases.push_back(NewRetainRelease);
3437 }
3438 }
3439 }
3440 NewRetains.clear();
3441 if (NewReleases.empty()) break;
3442
3443 // Back the other way.
3444 for (SmallVectorImpl<Instruction *>::const_iterator
3445 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
3446 Instruction *NewRelease = *NI;
3447 DenseMap<Value *, RRInfo>::const_iterator It =
3448 Releases.find(NewRelease);
3449 assert(It != Releases.end());
3450 const RRInfo &NewReleaseRRI = It->second;
Dan Gohmane6d5e882011-08-19 00:26:36 +00003451 KnownSafeBU &= NewReleaseRRI.KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00003452 for (SmallPtrSet<Instruction *, 2>::const_iterator
3453 LI = NewReleaseRRI.Calls.begin(),
3454 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
3455 Instruction *NewReleaseRetain = *LI;
3456 MapVector<Value *, RRInfo>::const_iterator Jt =
3457 Retains.find(NewReleaseRetain);
3458 if (Jt == Retains.end())
3459 goto next_retain;
3460 const RRInfo &NewReleaseRetainRRI = Jt->second;
3461 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
3462 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
3463 unsigned PathCount =
3464 BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
3465 OldDelta += PathCount;
3466 OldCount += PathCount;
3467
3468 // Merge the IsRetainBlock values.
3469 if (FirstRetain) {
3470 RetainsToMove.IsRetainBlock = NewReleaseRetainRRI.IsRetainBlock;
3471 FirstRetain = false;
3472 } else if (ReleasesToMove.IsRetainBlock !=
3473 NewReleaseRetainRRI.IsRetainBlock)
3474 // It's not possible to merge the sequences if one uses
3475 // objc_retain and the other uses objc_retainBlock.
3476 goto next_retain;
3477
3478 // Collect the optimal insertion points.
3479 if (!KnownSafe)
3480 for (SmallPtrSet<Instruction *, 2>::const_iterator
3481 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
3482 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
3483 RI != RE; ++RI) {
3484 Instruction *RIP = *RI;
3485 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
3486 PathCount = BBStates[RIP->getParent()].GetAllPathCount();
3487 NewDelta += PathCount;
3488 NewCount += PathCount;
3489 }
3490 }
3491 NewRetains.push_back(NewReleaseRetain);
3492 }
3493 }
3494 }
3495 NewReleases.clear();
3496 if (NewRetains.empty()) break;
3497 }
3498
Dan Gohmane6d5e882011-08-19 00:26:36 +00003499 // If the pointer is known incremented or nested, we can safely delete the
3500 // pair regardless of what's between them.
3501 if (KnownSafeTD || KnownSafeBU) {
John McCall9fbd3182011-06-15 23:37:01 +00003502 RetainsToMove.ReverseInsertPts.clear();
3503 ReleasesToMove.ReverseInsertPts.clear();
3504 NewCount = 0;
Dan Gohmana7f7db22011-08-12 00:26:31 +00003505 } else {
3506 // Determine whether the new insertion points we computed preserve the
3507 // balance of retain and release calls through the program.
3508 // TODO: If the fully aggressive solution isn't valid, try to find a
3509 // less aggressive solution which is.
3510 if (NewDelta != 0)
3511 goto next_retain;
John McCall9fbd3182011-06-15 23:37:01 +00003512 }
3513
3514 // Determine whether the original call points are balanced in the retain and
3515 // release calls through the program. If not, conservatively don't touch
3516 // them.
3517 // TODO: It's theoretically possible to do code motion in this case, as
3518 // long as the existing imbalances are maintained.
3519 if (OldDelta != 0)
3520 goto next_retain;
3521
John McCall9fbd3182011-06-15 23:37:01 +00003522 // Ok, everything checks out and we're all set. Let's move some code!
3523 Changed = true;
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003524 assert(OldCount != 0 && "Unreachable code?");
3525 AnyPairsCompletelyEliminated = NewCount == 0;
John McCall9fbd3182011-06-15 23:37:01 +00003526 NumRRs += OldCount - NewCount;
Dan Gohman44280692011-07-22 22:29:21 +00003527 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
3528 Retains, Releases, DeadInsts, M);
John McCall9fbd3182011-06-15 23:37:01 +00003529
3530 next_retain:
3531 NewReleases.clear();
3532 NewRetains.clear();
3533 RetainsToMove.clear();
3534 ReleasesToMove.clear();
3535 }
3536
3537 // Now that we're done moving everything, we can delete the newly dead
3538 // instructions, as we no longer need them as insert points.
3539 while (!DeadInsts.empty())
3540 EraseInstruction(DeadInsts.pop_back_val());
3541
3542 return AnyPairsCompletelyEliminated;
3543}
3544
3545/// OptimizeWeakCalls - Weak pointer optimizations.
3546void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
3547 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
3548 // itself because it uses AliasAnalysis and we need to do provenance
3549 // queries instead.
3550 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3551 Instruction *Inst = &*I++;
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00003552
Michael Gottesman5c0ae472013-01-04 21:29:57 +00003553 DEBUG(dbgs() << "ObjCARCOpt::OptimizeWeakCalls: Visiting: " << *Inst <<
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00003554 "\n");
3555
John McCall9fbd3182011-06-15 23:37:01 +00003556 InstructionClass Class = GetBasicInstructionClass(Inst);
3557 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
3558 continue;
3559
3560 // Delete objc_loadWeak calls with no users.
3561 if (Class == IC_LoadWeak && Inst->use_empty()) {
3562 Inst->eraseFromParent();
3563 continue;
3564 }
3565
3566 // TODO: For now, just look for an earlier available version of this value
3567 // within the same block. Theoretically, we could do memdep-style non-local
3568 // analysis too, but that would want caching. A better approach would be to
3569 // use the technique that EarlyCSE uses.
3570 inst_iterator Current = llvm::prior(I);
3571 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
3572 for (BasicBlock::iterator B = CurrentBB->begin(),
3573 J = Current.getInstructionIterator();
3574 J != B; --J) {
3575 Instruction *EarlierInst = &*llvm::prior(J);
3576 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
3577 switch (EarlierClass) {
3578 case IC_LoadWeak:
3579 case IC_LoadWeakRetained: {
3580 // If this is loading from the same pointer, replace this load's value
3581 // with that one.
3582 CallInst *Call = cast<CallInst>(Inst);
3583 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3584 Value *Arg = Call->getArgOperand(0);
3585 Value *EarlierArg = EarlierCall->getArgOperand(0);
3586 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3587 case AliasAnalysis::MustAlias:
3588 Changed = true;
3589 // If the load has a builtin retain, insert a plain retain for it.
3590 if (Class == IC_LoadWeakRetained) {
3591 CallInst *CI =
3592 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3593 "", Call);
3594 CI->setTailCall();
3595 }
3596 // Zap the fully redundant load.
3597 Call->replaceAllUsesWith(EarlierCall);
3598 Call->eraseFromParent();
3599 goto clobbered;
3600 case AliasAnalysis::MayAlias:
3601 case AliasAnalysis::PartialAlias:
3602 goto clobbered;
3603 case AliasAnalysis::NoAlias:
3604 break;
3605 }
3606 break;
3607 }
3608 case IC_StoreWeak:
3609 case IC_InitWeak: {
3610 // If this is storing to the same pointer and has the same size etc.
3611 // replace this load's value with the stored value.
3612 CallInst *Call = cast<CallInst>(Inst);
3613 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3614 Value *Arg = Call->getArgOperand(0);
3615 Value *EarlierArg = EarlierCall->getArgOperand(0);
3616 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3617 case AliasAnalysis::MustAlias:
3618 Changed = true;
3619 // If the load has a builtin retain, insert a plain retain for it.
3620 if (Class == IC_LoadWeakRetained) {
3621 CallInst *CI =
3622 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3623 "", Call);
3624 CI->setTailCall();
3625 }
3626 // Zap the fully redundant load.
3627 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
3628 Call->eraseFromParent();
3629 goto clobbered;
3630 case AliasAnalysis::MayAlias:
3631 case AliasAnalysis::PartialAlias:
3632 goto clobbered;
3633 case AliasAnalysis::NoAlias:
3634 break;
3635 }
3636 break;
3637 }
3638 case IC_MoveWeak:
3639 case IC_CopyWeak:
3640 // TOOD: Grab the copied value.
3641 goto clobbered;
3642 case IC_AutoreleasepoolPush:
3643 case IC_None:
3644 case IC_User:
3645 // Weak pointers are only modified through the weak entry points
3646 // (and arbitrary calls, which could call the weak entry points).
3647 break;
3648 default:
3649 // Anything else could modify the weak pointer.
3650 goto clobbered;
3651 }
3652 }
3653 clobbered:;
3654 }
3655
3656 // Then, for each destroyWeak with an alloca operand, check to see if
3657 // the alloca and all its users can be zapped.
3658 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3659 Instruction *Inst = &*I++;
3660 InstructionClass Class = GetBasicInstructionClass(Inst);
3661 if (Class != IC_DestroyWeak)
3662 continue;
3663
3664 CallInst *Call = cast<CallInst>(Inst);
3665 Value *Arg = Call->getArgOperand(0);
3666 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
3667 for (Value::use_iterator UI = Alloca->use_begin(),
3668 UE = Alloca->use_end(); UI != UE; ++UI) {
Dan Gohman447989c2012-04-27 18:56:31 +00003669 const Instruction *UserInst = cast<Instruction>(*UI);
John McCall9fbd3182011-06-15 23:37:01 +00003670 switch (GetBasicInstructionClass(UserInst)) {
3671 case IC_InitWeak:
3672 case IC_StoreWeak:
3673 case IC_DestroyWeak:
3674 continue;
3675 default:
3676 goto done;
3677 }
3678 }
3679 Changed = true;
3680 for (Value::use_iterator UI = Alloca->use_begin(),
3681 UE = Alloca->use_end(); UI != UE; ) {
3682 CallInst *UserInst = cast<CallInst>(*UI++);
Dan Gohmance5d8b02012-05-18 22:17:29 +00003683 switch (GetBasicInstructionClass(UserInst)) {
3684 case IC_InitWeak:
3685 case IC_StoreWeak:
3686 // These functions return their second argument.
3687 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
3688 break;
3689 case IC_DestroyWeak:
3690 // No return value.
3691 break;
3692 default:
Dan Gohman4c8f9092012-05-21 17:41:28 +00003693 llvm_unreachable("alloca really is used!");
Dan Gohmance5d8b02012-05-18 22:17:29 +00003694 }
John McCall9fbd3182011-06-15 23:37:01 +00003695 UserInst->eraseFromParent();
3696 }
3697 Alloca->eraseFromParent();
3698 done:;
3699 }
3700 }
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00003701
Michael Gottesman5c0ae472013-01-04 21:29:57 +00003702 DEBUG(dbgs() << "ObjCARCOpt::OptimizeWeakCalls: Finished List.\n\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00003703
John McCall9fbd3182011-06-15 23:37:01 +00003704}
3705
3706/// OptimizeSequences - Identify program paths which execute sequences of
3707/// retains and releases which can be eliminated.
3708bool ObjCARCOpt::OptimizeSequences(Function &F) {
3709 /// Releases, Retains - These are used to store the results of the main flow
3710 /// analysis. These use Value* as the key instead of Instruction* so that the
3711 /// map stays valid when we get around to rewriting code and calls get
3712 /// replaced by arguments.
3713 DenseMap<Value *, RRInfo> Releases;
3714 MapVector<Value *, RRInfo> Retains;
3715
3716 /// BBStates, This is used during the traversal of the function to track the
3717 /// states for each identified object at each block.
3718 DenseMap<const BasicBlock *, BBState> BBStates;
3719
3720 // Analyze the CFG of the function, and all instructions.
3721 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
3722
3723 // Transform.
Dan Gohman44280692011-07-22 22:29:21 +00003724 return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) &&
3725 NestingDetected;
John McCall9fbd3182011-06-15 23:37:01 +00003726}
3727
3728/// OptimizeReturns - Look for this pattern:
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +00003729/// \code
John McCall9fbd3182011-06-15 23:37:01 +00003730/// %call = call i8* @something(...)
3731/// %2 = call i8* @objc_retain(i8* %call)
3732/// %3 = call i8* @objc_autorelease(i8* %2)
3733/// ret i8* %3
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +00003734/// \endcode
John McCall9fbd3182011-06-15 23:37:01 +00003735/// And delete the retain and autorelease.
3736///
3737/// Otherwise if it's just this:
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +00003738/// \code
John McCall9fbd3182011-06-15 23:37:01 +00003739/// %3 = call i8* @objc_autorelease(i8* %2)
3740/// ret i8* %3
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +00003741/// \endcode
John McCall9fbd3182011-06-15 23:37:01 +00003742/// convert the autorelease to autoreleaseRV.
3743void ObjCARCOpt::OptimizeReturns(Function &F) {
3744 if (!F.getReturnType()->isPointerTy())
3745 return;
3746
3747 SmallPtrSet<Instruction *, 4> DependingInstructions;
3748 SmallPtrSet<const BasicBlock *, 4> Visited;
3749 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3750 BasicBlock *BB = FI;
3751 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00003752
Michael Gottesman5c0ae472013-01-04 21:29:57 +00003753 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Visiting: " << *Ret << "\n");
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00003754
John McCall9fbd3182011-06-15 23:37:01 +00003755 if (!Ret) continue;
3756
3757 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
3758 FindDependencies(NeedsPositiveRetainCount, Arg,
3759 BB, Ret, DependingInstructions, Visited, PA);
3760 if (DependingInstructions.size() != 1)
3761 goto next_block;
3762
3763 {
3764 CallInst *Autorelease =
3765 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3766 if (!Autorelease)
3767 goto next_block;
Dan Gohman0daef3d2012-05-08 23:39:44 +00003768 InstructionClass AutoreleaseClass = GetBasicInstructionClass(Autorelease);
John McCall9fbd3182011-06-15 23:37:01 +00003769 if (!IsAutorelease(AutoreleaseClass))
3770 goto next_block;
3771 if (GetObjCArg(Autorelease) != Arg)
3772 goto next_block;
3773
3774 DependingInstructions.clear();
3775 Visited.clear();
3776
3777 // Check that there is nothing that can affect the reference
3778 // count between the autorelease and the retain.
3779 FindDependencies(CanChangeRetainCount, Arg,
3780 BB, Autorelease, DependingInstructions, Visited, PA);
3781 if (DependingInstructions.size() != 1)
3782 goto next_block;
3783
3784 {
3785 CallInst *Retain =
3786 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3787
3788 // Check that we found a retain with the same argument.
3789 if (!Retain ||
3790 !IsRetain(GetBasicInstructionClass(Retain)) ||
3791 GetObjCArg(Retain) != Arg)
3792 goto next_block;
3793
3794 DependingInstructions.clear();
3795 Visited.clear();
3796
3797 // Convert the autorelease to an autoreleaseRV, since it's
3798 // returning the value.
3799 if (AutoreleaseClass == IC_Autorelease) {
Michael Gottesman5dc30012013-01-10 02:03:50 +00003800 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Converting autorelease "
3801 "=> autoreleaseRV since it's returning a value.\n"
3802 " In: " << *Autorelease
3803 << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00003804 Autorelease->setCalledFunction(getAutoreleaseRVCallee(F.getParent()));
Michael Gottesman5dc30012013-01-10 02:03:50 +00003805 DEBUG(dbgs() << " Out: " << *Autorelease
3806 << "\n");
Michael Gottesmane8c161a2013-01-12 01:25:15 +00003807 Autorelease->setTailCall(); // Always tail call autoreleaseRV.
John McCall9fbd3182011-06-15 23:37:01 +00003808 AutoreleaseClass = IC_AutoreleaseRV;
3809 }
3810
3811 // Check that there is nothing that can affect the reference
3812 // count between the retain and the call.
Dan Gohman27e06662011-09-29 22:27:34 +00003813 // Note that Retain need not be in BB.
3814 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
John McCall9fbd3182011-06-15 23:37:01 +00003815 DependingInstructions, Visited, PA);
3816 if (DependingInstructions.size() != 1)
3817 goto next_block;
3818
3819 {
3820 CallInst *Call =
3821 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3822
3823 // Check that the pointer is the return value of the call.
3824 if (!Call || Arg != Call)
3825 goto next_block;
3826
3827 // Check that the call is a regular call.
3828 InstructionClass Class = GetBasicInstructionClass(Call);
3829 if (Class != IC_CallOrUser && Class != IC_Call)
3830 goto next_block;
3831
3832 // If so, we can zap the retain and autorelease.
3833 Changed = true;
3834 ++NumRets;
Michael Gottesmanf93109a2013-01-07 00:04:56 +00003835 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Erasing: " << *Retain
3836 << "\n Erasing: "
3837 << *Autorelease << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00003838 EraseInstruction(Retain);
3839 EraseInstruction(Autorelease);
3840 }
3841 }
3842 }
3843
3844 next_block:
3845 DependingInstructions.clear();
3846 Visited.clear();
3847 }
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00003848
Michael Gottesman5c0ae472013-01-04 21:29:57 +00003849 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Finished List.\n\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00003850
John McCall9fbd3182011-06-15 23:37:01 +00003851}
3852
3853bool ObjCARCOpt::doInitialization(Module &M) {
3854 if (!EnableARCOpts)
3855 return false;
3856
Dan Gohmand6bf2012012-04-13 18:57:48 +00003857 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003858 Run = ModuleHasARC(M);
3859 if (!Run)
3860 return false;
3861
John McCall9fbd3182011-06-15 23:37:01 +00003862 // Identify the imprecise release metadata kind.
3863 ImpreciseReleaseMDKind =
3864 M.getContext().getMDKindID("clang.imprecise_release");
Dan Gohmana974bea2011-10-17 22:53:25 +00003865 CopyOnEscapeMDKind =
3866 M.getContext().getMDKindID("clang.arc.copy_on_escape");
Dan Gohmandbe266b2012-02-17 18:59:53 +00003867 NoObjCARCExceptionsMDKind =
3868 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
John McCall9fbd3182011-06-15 23:37:01 +00003869
John McCall9fbd3182011-06-15 23:37:01 +00003870 // Intuitively, objc_retain and others are nocapture, however in practice
3871 // they are not, because they return their argument value. And objc_release
Dan Gohman447989c2012-04-27 18:56:31 +00003872 // calls finalizers which can have arbitrary side effects.
John McCall9fbd3182011-06-15 23:37:01 +00003873
3874 // These are initialized lazily.
3875 RetainRVCallee = 0;
3876 AutoreleaseRVCallee = 0;
3877 ReleaseCallee = 0;
3878 RetainCallee = 0;
Dan Gohman44280692011-07-22 22:29:21 +00003879 RetainBlockCallee = 0;
John McCall9fbd3182011-06-15 23:37:01 +00003880 AutoreleaseCallee = 0;
3881
3882 return false;
3883}
3884
3885bool ObjCARCOpt::runOnFunction(Function &F) {
3886 if (!EnableARCOpts)
3887 return false;
3888
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003889 // If nothing in the Module uses ARC, don't do anything.
3890 if (!Run)
3891 return false;
3892
John McCall9fbd3182011-06-15 23:37:01 +00003893 Changed = false;
3894
Michael Gottesman0d3582b2013-01-12 02:57:16 +00003895 DEBUG(dbgs() << "ObjCARCOpt: Visiting Function: " << F.getName() << "\n");
3896
John McCall9fbd3182011-06-15 23:37:01 +00003897 PA.setAA(&getAnalysis<AliasAnalysis>());
3898
3899 // This pass performs several distinct transformations. As a compile-time aid
3900 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3901 // library functions aren't declared.
3902
3903 // Preliminary optimizations. This also computs UsedInThisFunction.
3904 OptimizeIndividualCalls(F);
3905
3906 // Optimizations for weak pointers.
3907 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3908 (1 << IC_LoadWeakRetained) |
3909 (1 << IC_StoreWeak) |
3910 (1 << IC_InitWeak) |
3911 (1 << IC_CopyWeak) |
3912 (1 << IC_MoveWeak) |
3913 (1 << IC_DestroyWeak)))
3914 OptimizeWeakCalls(F);
3915
3916 // Optimizations for retain+release pairs.
3917 if (UsedInThisFunction & ((1 << IC_Retain) |
3918 (1 << IC_RetainRV) |
3919 (1 << IC_RetainBlock)))
3920 if (UsedInThisFunction & (1 << IC_Release))
3921 // Run OptimizeSequences until it either stops making changes or
3922 // no retain+release pair nesting is detected.
3923 while (OptimizeSequences(F)) {}
3924
3925 // Optimizations if objc_autorelease is used.
Dan Gohman0daef3d2012-05-08 23:39:44 +00003926 if (UsedInThisFunction & ((1 << IC_Autorelease) |
3927 (1 << IC_AutoreleaseRV)))
John McCall9fbd3182011-06-15 23:37:01 +00003928 OptimizeReturns(F);
3929
Michael Gottesman0d3582b2013-01-12 02:57:16 +00003930 DEBUG(dbgs() << "\n");
3931
John McCall9fbd3182011-06-15 23:37:01 +00003932 return Changed;
3933}
3934
3935void ObjCARCOpt::releaseMemory() {
3936 PA.clear();
3937}
3938
3939//===----------------------------------------------------------------------===//
3940// ARC contraction.
3941//===----------------------------------------------------------------------===//
3942
3943// TODO: ObjCARCContract could insert PHI nodes when uses aren't
3944// dominated by single calls.
3945
John McCall9fbd3182011-06-15 23:37:01 +00003946#include "llvm/Analysis/Dominators.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +00003947#include "llvm/IR/InlineAsm.h"
3948#include "llvm/IR/Operator.h"
John McCall9fbd3182011-06-15 23:37:01 +00003949
3950STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed");
3951
3952namespace {
3953 /// ObjCARCContract - Late ARC optimizations. These change the IR in a way
3954 /// that makes it difficult to be analyzed by ObjCARCOpt, so it's run late.
3955 class ObjCARCContract : public FunctionPass {
3956 bool Changed;
3957 AliasAnalysis *AA;
3958 DominatorTree *DT;
3959 ProvenanceAnalysis PA;
3960
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003961 /// Run - A flag indicating whether this optimization pass should run.
3962 bool Run;
3963
John McCall9fbd3182011-06-15 23:37:01 +00003964 /// StoreStrongCallee, etc. - Declarations for ObjC runtime
3965 /// functions, for use in creating calls to them. These are initialized
3966 /// lazily to avoid cluttering up the Module with unused declarations.
3967 Constant *StoreStrongCallee,
3968 *RetainAutoreleaseCallee, *RetainAutoreleaseRVCallee;
3969
3970 /// RetainRVMarker - The inline asm string to insert between calls and
3971 /// RetainRV calls to make the optimization work on targets which need it.
3972 const MDString *RetainRVMarker;
3973
Dan Gohman0cdece42012-01-19 19:14:36 +00003974 /// StoreStrongCalls - The set of inserted objc_storeStrong calls. If
3975 /// at the end of walking the function we have found no alloca
3976 /// instructions, these calls can be marked "tail".
Dan Gohman0daef3d2012-05-08 23:39:44 +00003977 SmallPtrSet<CallInst *, 8> StoreStrongCalls;
Dan Gohman0cdece42012-01-19 19:14:36 +00003978
John McCall9fbd3182011-06-15 23:37:01 +00003979 Constant *getStoreStrongCallee(Module *M);
3980 Constant *getRetainAutoreleaseCallee(Module *M);
3981 Constant *getRetainAutoreleaseRVCallee(Module *M);
3982
3983 bool ContractAutorelease(Function &F, Instruction *Autorelease,
3984 InstructionClass Class,
3985 SmallPtrSet<Instruction *, 4>
3986 &DependingInstructions,
3987 SmallPtrSet<const BasicBlock *, 4>
3988 &Visited);
3989
3990 void ContractRelease(Instruction *Release,
3991 inst_iterator &Iter);
3992
3993 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
3994 virtual bool doInitialization(Module &M);
3995 virtual bool runOnFunction(Function &F);
3996
3997 public:
3998 static char ID;
3999 ObjCARCContract() : FunctionPass(ID) {
4000 initializeObjCARCContractPass(*PassRegistry::getPassRegistry());
4001 }
4002 };
4003}
4004
4005char ObjCARCContract::ID = 0;
4006INITIALIZE_PASS_BEGIN(ObjCARCContract,
4007 "objc-arc-contract", "ObjC ARC contraction", false, false)
4008INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
4009INITIALIZE_PASS_DEPENDENCY(DominatorTree)
4010INITIALIZE_PASS_END(ObjCARCContract,
4011 "objc-arc-contract", "ObjC ARC contraction", false, false)
4012
4013Pass *llvm::createObjCARCContractPass() {
4014 return new ObjCARCContract();
4015}
4016
4017void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const {
4018 AU.addRequired<AliasAnalysis>();
4019 AU.addRequired<DominatorTree>();
4020 AU.setPreservesCFG();
4021}
4022
4023Constant *ObjCARCContract::getStoreStrongCallee(Module *M) {
4024 if (!StoreStrongCallee) {
4025 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00004026 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
4027 Type *I8XX = PointerType::getUnqual(I8X);
Dan Gohman0daef3d2012-05-08 23:39:44 +00004028 Type *Params[] = { I8XX, I8X };
John McCall9fbd3182011-06-15 23:37:01 +00004029
Bill Wendling034b94b2012-12-19 07:18:57 +00004030 AttributeSet Attribute = AttributeSet()
Bill Wendling99faa3b2012-12-07 23:16:57 +00004031 .addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00004032 Attribute::get(C, Attribute::NoUnwind))
4033 .addAttr(M->getContext(), 1, Attribute::get(C, Attribute::NoCapture));
John McCall9fbd3182011-06-15 23:37:01 +00004034
4035 StoreStrongCallee =
4036 M->getOrInsertFunction(
4037 "objc_storeStrong",
4038 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
Bill Wendling034b94b2012-12-19 07:18:57 +00004039 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00004040 }
4041 return StoreStrongCallee;
4042}
4043
4044Constant *ObjCARCContract::getRetainAutoreleaseCallee(Module *M) {
4045 if (!RetainAutoreleaseCallee) {
4046 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00004047 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman0daef3d2012-05-08 23:39:44 +00004048 Type *Params[] = { I8X };
4049 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling034b94b2012-12-19 07:18:57 +00004050 AttributeSet Attribute =
Bill Wendling99faa3b2012-12-07 23:16:57 +00004051 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00004052 Attribute::get(C, Attribute::NoUnwind));
John McCall9fbd3182011-06-15 23:37:01 +00004053 RetainAutoreleaseCallee =
Bill Wendling034b94b2012-12-19 07:18:57 +00004054 M->getOrInsertFunction("objc_retainAutorelease", FTy, Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00004055 }
4056 return RetainAutoreleaseCallee;
4057}
4058
4059Constant *ObjCARCContract::getRetainAutoreleaseRVCallee(Module *M) {
4060 if (!RetainAutoreleaseRVCallee) {
4061 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00004062 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman0daef3d2012-05-08 23:39:44 +00004063 Type *Params[] = { I8X };
4064 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling034b94b2012-12-19 07:18:57 +00004065 AttributeSet Attribute =
Bill Wendling99faa3b2012-12-07 23:16:57 +00004066 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00004067 Attribute::get(C, Attribute::NoUnwind));
John McCall9fbd3182011-06-15 23:37:01 +00004068 RetainAutoreleaseRVCallee =
4069 M->getOrInsertFunction("objc_retainAutoreleaseReturnValue", FTy,
Bill Wendling034b94b2012-12-19 07:18:57 +00004070 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00004071 }
4072 return RetainAutoreleaseRVCallee;
4073}
4074
Dan Gohman447989c2012-04-27 18:56:31 +00004075/// ContractAutorelease - Merge an autorelease with a retain into a fused call.
John McCall9fbd3182011-06-15 23:37:01 +00004076bool
4077ObjCARCContract::ContractAutorelease(Function &F, Instruction *Autorelease,
4078 InstructionClass Class,
4079 SmallPtrSet<Instruction *, 4>
4080 &DependingInstructions,
4081 SmallPtrSet<const BasicBlock *, 4>
4082 &Visited) {
4083 const Value *Arg = GetObjCArg(Autorelease);
4084
4085 // Check that there are no instructions between the retain and the autorelease
4086 // (such as an autorelease_pop) which may change the count.
4087 CallInst *Retain = 0;
4088 if (Class == IC_AutoreleaseRV)
4089 FindDependencies(RetainAutoreleaseRVDep, Arg,
4090 Autorelease->getParent(), Autorelease,
4091 DependingInstructions, Visited, PA);
4092 else
4093 FindDependencies(RetainAutoreleaseDep, Arg,
4094 Autorelease->getParent(), Autorelease,
4095 DependingInstructions, Visited, PA);
4096
4097 Visited.clear();
4098 if (DependingInstructions.size() != 1) {
4099 DependingInstructions.clear();
4100 return false;
4101 }
4102
4103 Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
4104 DependingInstructions.clear();
4105
4106 if (!Retain ||
4107 GetBasicInstructionClass(Retain) != IC_Retain ||
4108 GetObjCArg(Retain) != Arg)
4109 return false;
4110
4111 Changed = true;
4112 ++NumPeeps;
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004113
Michael Gottesman916d52a2013-01-07 00:31:26 +00004114 DEBUG(dbgs() << "ObjCARCContract::ContractAutorelease: Fusing "
4115 "retain/autorelease. Erasing: " << *Autorelease << "\n"
4116 " Old Retain: "
4117 << *Retain << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004118
John McCall9fbd3182011-06-15 23:37:01 +00004119 if (Class == IC_AutoreleaseRV)
4120 Retain->setCalledFunction(getRetainAutoreleaseRVCallee(F.getParent()));
4121 else
4122 Retain->setCalledFunction(getRetainAutoreleaseCallee(F.getParent()));
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004123
Michael Gottesman916d52a2013-01-07 00:31:26 +00004124 DEBUG(dbgs() << " New Retain: "
4125 << *Retain << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004126
John McCall9fbd3182011-06-15 23:37:01 +00004127 EraseInstruction(Autorelease);
4128 return true;
4129}
4130
4131/// ContractRelease - Attempt to merge an objc_release with a store, load, and
4132/// objc_retain to form an objc_storeStrong. This can be a little tricky because
4133/// the instructions don't always appear in order, and there may be unrelated
4134/// intervening instructions.
4135void ObjCARCContract::ContractRelease(Instruction *Release,
4136 inst_iterator &Iter) {
4137 LoadInst *Load = dyn_cast<LoadInst>(GetObjCArg(Release));
Eli Friedman2bc3d522011-09-12 20:23:13 +00004138 if (!Load || !Load->isSimple()) return;
John McCall9fbd3182011-06-15 23:37:01 +00004139
4140 // For now, require everything to be in one basic block.
4141 BasicBlock *BB = Release->getParent();
4142 if (Load->getParent() != BB) return;
4143
Dan Gohman4670dac2012-05-08 23:34:08 +00004144 // Walk down to find the store and the release, which may be in either order.
Dan Gohman95b8cf12012-05-09 23:08:33 +00004145 BasicBlock::iterator I = Load, End = BB->end();
John McCall9fbd3182011-06-15 23:37:01 +00004146 ++I;
4147 AliasAnalysis::Location Loc = AA->getLocation(Load);
Dan Gohman4670dac2012-05-08 23:34:08 +00004148 StoreInst *Store = 0;
4149 bool SawRelease = false;
4150 for (; !Store || !SawRelease; ++I) {
Dan Gohman95b8cf12012-05-09 23:08:33 +00004151 if (I == End)
4152 return;
4153
Dan Gohman4670dac2012-05-08 23:34:08 +00004154 Instruction *Inst = I;
4155 if (Inst == Release) {
4156 SawRelease = true;
4157 continue;
4158 }
4159
4160 InstructionClass Class = GetBasicInstructionClass(Inst);
4161
4162 // Unrelated retains are harmless.
4163 if (IsRetain(Class))
4164 continue;
4165
4166 if (Store) {
4167 // The store is the point where we're going to put the objc_storeStrong,
4168 // so make sure there are no uses after it.
4169 if (CanUse(Inst, Load, PA, Class))
4170 return;
4171 } else if (AA->getModRefInfo(Inst, Loc) & AliasAnalysis::Mod) {
4172 // We are moving the load down to the store, so check for anything
4173 // else which writes to the memory between the load and the store.
4174 Store = dyn_cast<StoreInst>(Inst);
4175 if (!Store || !Store->isSimple()) return;
4176 if (Store->getPointerOperand() != Loc.Ptr) return;
4177 }
4178 }
John McCall9fbd3182011-06-15 23:37:01 +00004179
4180 Value *New = StripPointerCastsAndObjCCalls(Store->getValueOperand());
4181
4182 // Walk up to find the retain.
4183 I = Store;
4184 BasicBlock::iterator Begin = BB->begin();
4185 while (I != Begin && GetBasicInstructionClass(I) != IC_Retain)
4186 --I;
4187 Instruction *Retain = I;
4188 if (GetBasicInstructionClass(Retain) != IC_Retain) return;
4189 if (GetObjCArg(Retain) != New) return;
4190
4191 Changed = true;
4192 ++NumStoreStrongs;
4193
4194 LLVMContext &C = Release->getContext();
Chris Lattnerdb125cf2011-07-18 04:54:35 +00004195 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
4196 Type *I8XX = PointerType::getUnqual(I8X);
John McCall9fbd3182011-06-15 23:37:01 +00004197
4198 Value *Args[] = { Load->getPointerOperand(), New };
4199 if (Args[0]->getType() != I8XX)
4200 Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
4201 if (Args[1]->getType() != I8X)
4202 Args[1] = new BitCastInst(Args[1], I8X, "", Store);
4203 CallInst *StoreStrong =
4204 CallInst::Create(getStoreStrongCallee(BB->getParent()->getParent()),
Jay Foada3efbb12011-07-15 08:37:34 +00004205 Args, "", Store);
John McCall9fbd3182011-06-15 23:37:01 +00004206 StoreStrong->setDoesNotThrow();
4207 StoreStrong->setDebugLoc(Store->getDebugLoc());
4208
Dan Gohman0cdece42012-01-19 19:14:36 +00004209 // We can't set the tail flag yet, because we haven't yet determined
4210 // whether there are any escaping allocas. Remember this call, so that
4211 // we can set the tail flag once we know it's safe.
4212 StoreStrongCalls.insert(StoreStrong);
4213
John McCall9fbd3182011-06-15 23:37:01 +00004214 if (&*Iter == Store) ++Iter;
4215 Store->eraseFromParent();
4216 Release->eraseFromParent();
4217 EraseInstruction(Retain);
4218 if (Load->use_empty())
4219 Load->eraseFromParent();
4220}
4221
4222bool ObjCARCContract::doInitialization(Module &M) {
Dan Gohmand6bf2012012-04-13 18:57:48 +00004223 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00004224 Run = ModuleHasARC(M);
4225 if (!Run)
4226 return false;
4227
John McCall9fbd3182011-06-15 23:37:01 +00004228 // These are initialized lazily.
4229 StoreStrongCallee = 0;
4230 RetainAutoreleaseCallee = 0;
4231 RetainAutoreleaseRVCallee = 0;
4232
4233 // Initialize RetainRVMarker.
4234 RetainRVMarker = 0;
4235 if (NamedMDNode *NMD =
4236 M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker"))
4237 if (NMD->getNumOperands() == 1) {
4238 const MDNode *N = NMD->getOperand(0);
4239 if (N->getNumOperands() == 1)
4240 if (const MDString *S = dyn_cast<MDString>(N->getOperand(0)))
4241 RetainRVMarker = S;
4242 }
4243
4244 return false;
4245}
4246
4247bool ObjCARCContract::runOnFunction(Function &F) {
4248 if (!EnableARCOpts)
4249 return false;
4250
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00004251 // If nothing in the Module uses ARC, don't do anything.
4252 if (!Run)
4253 return false;
4254
John McCall9fbd3182011-06-15 23:37:01 +00004255 Changed = false;
4256 AA = &getAnalysis<AliasAnalysis>();
4257 DT = &getAnalysis<DominatorTree>();
4258
4259 PA.setAA(&getAnalysis<AliasAnalysis>());
4260
Dan Gohman0cdece42012-01-19 19:14:36 +00004261 // Track whether it's ok to mark objc_storeStrong calls with the "tail"
4262 // keyword. Be conservative if the function has variadic arguments.
4263 // It seems that functions which "return twice" are also unsafe for the
4264 // "tail" argument, because they are setjmp, which could need to
4265 // return to an earlier stack state.
Dan Gohman0daef3d2012-05-08 23:39:44 +00004266 bool TailOkForStoreStrongs = !F.isVarArg() &&
4267 !F.callsFunctionThatReturnsTwice();
Dan Gohman0cdece42012-01-19 19:14:36 +00004268
John McCall9fbd3182011-06-15 23:37:01 +00004269 // For ObjC library calls which return their argument, replace uses of the
4270 // argument with uses of the call return value, if it dominates the use. This
4271 // reduces register pressure.
4272 SmallPtrSet<Instruction *, 4> DependingInstructions;
4273 SmallPtrSet<const BasicBlock *, 4> Visited;
4274 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
4275 Instruction *Inst = &*I++;
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004276
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00004277 DEBUG(dbgs() << "ObjCARCContract: Visiting: " << *Inst << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004278
John McCall9fbd3182011-06-15 23:37:01 +00004279 // Only these library routines return their argument. In particular,
4280 // objc_retainBlock does not necessarily return its argument.
4281 InstructionClass Class = GetBasicInstructionClass(Inst);
4282 switch (Class) {
4283 case IC_Retain:
4284 case IC_FusedRetainAutorelease:
4285 case IC_FusedRetainAutoreleaseRV:
4286 break;
4287 case IC_Autorelease:
4288 case IC_AutoreleaseRV:
4289 if (ContractAutorelease(F, Inst, Class, DependingInstructions, Visited))
4290 continue;
4291 break;
4292 case IC_RetainRV: {
4293 // If we're compiling for a target which needs a special inline-asm
4294 // marker to do the retainAutoreleasedReturnValue optimization,
4295 // insert it now.
4296 if (!RetainRVMarker)
4297 break;
4298 BasicBlock::iterator BBI = Inst;
Dan Gohman58fb3402012-06-25 19:47:37 +00004299 BasicBlock *InstParent = Inst->getParent();
4300
4301 // Step up to see if the call immediately precedes the RetainRV call.
4302 // If it's an invoke, we have to cross a block boundary. And we have
4303 // to carefully dodge no-op instructions.
4304 do {
4305 if (&*BBI == InstParent->begin()) {
4306 BasicBlock *Pred = InstParent->getSinglePredecessor();
4307 if (!Pred)
4308 goto decline_rv_optimization;
4309 BBI = Pred->getTerminator();
4310 break;
4311 }
4312 --BBI;
4313 } while (isNoopInstruction(BBI));
4314
John McCall9fbd3182011-06-15 23:37:01 +00004315 if (&*BBI == GetObjCArg(Inst)) {
Michael Gottesman50652cd2013-01-03 07:32:41 +00004316 DEBUG(dbgs() << "ObjCARCContract: Adding inline asm marker for "
Michael Gottesman5c0ae472013-01-04 21:29:57 +00004317 "retainAutoreleasedReturnValue optimization.\n");
Dan Gohmand6bf2012012-04-13 18:57:48 +00004318 Changed = true;
John McCall9fbd3182011-06-15 23:37:01 +00004319 InlineAsm *IA =
4320 InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()),
4321 /*isVarArg=*/false),
4322 RetainRVMarker->getString(),
4323 /*Constraints=*/"", /*hasSideEffects=*/true);
4324 CallInst::Create(IA, "", Inst);
4325 }
Dan Gohman58fb3402012-06-25 19:47:37 +00004326 decline_rv_optimization:
John McCall9fbd3182011-06-15 23:37:01 +00004327 break;
4328 }
4329 case IC_InitWeak: {
4330 // objc_initWeak(p, null) => *p = null
4331 CallInst *CI = cast<CallInst>(Inst);
4332 if (isNullOrUndef(CI->getArgOperand(1))) {
4333 Value *Null =
4334 ConstantPointerNull::get(cast<PointerType>(CI->getType()));
4335 Changed = true;
4336 new StoreInst(Null, CI->getArgOperand(0), CI);
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004337
Michael Gottesman1ebbdcf2013-01-03 07:32:53 +00004338 DEBUG(dbgs() << "OBJCARCContract: Old = " << *CI << "\n"
4339 << " New = " << *Null << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004340
John McCall9fbd3182011-06-15 23:37:01 +00004341 CI->replaceAllUsesWith(Null);
4342 CI->eraseFromParent();
4343 }
4344 continue;
4345 }
4346 case IC_Release:
4347 ContractRelease(Inst, I);
4348 continue;
Dan Gohman0cdece42012-01-19 19:14:36 +00004349 case IC_User:
4350 // Be conservative if the function has any alloca instructions.
4351 // Technically we only care about escaping alloca instructions,
4352 // but this is sufficient to handle some interesting cases.
4353 if (isa<AllocaInst>(Inst))
4354 TailOkForStoreStrongs = false;
4355 continue;
John McCall9fbd3182011-06-15 23:37:01 +00004356 default:
4357 continue;
4358 }
4359
Michael Gottesmanec21e2a2013-01-03 08:09:27 +00004360 DEBUG(dbgs() << "ObjCARCContract: Finished List.\n\n");
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00004361
John McCall9fbd3182011-06-15 23:37:01 +00004362 // Don't use GetObjCArg because we don't want to look through bitcasts
4363 // and such; to do the replacement, the argument must have type i8*.
4364 const Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
4365 for (;;) {
4366 // If we're compiling bugpointed code, don't get in trouble.
4367 if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
4368 break;
4369 // Look through the uses of the pointer.
4370 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
4371 UI != UE; ) {
4372 Use &U = UI.getUse();
4373 unsigned OperandNo = UI.getOperandNo();
4374 ++UI; // Increment UI now, because we may unlink its element.
Dan Gohmand6bf2012012-04-13 18:57:48 +00004375
4376 // If the call's return value dominates a use of the call's argument
4377 // value, rewrite the use to use the return value. We check for
4378 // reachability here because an unreachable call is considered to
4379 // trivially dominate itself, which would lead us to rewriting its
4380 // argument in terms of its return value, which would lead to
4381 // infinite loops in GetObjCArg.
Dan Gohman0daef3d2012-05-08 23:39:44 +00004382 if (DT->isReachableFromEntry(U) && DT->dominates(Inst, U)) {
Rafael Espindola2453dff2012-03-15 15:52:59 +00004383 Changed = true;
4384 Instruction *Replacement = Inst;
4385 Type *UseTy = U.get()->getType();
Dan Gohman6c189ec2012-04-13 01:08:28 +00004386 if (PHINode *PHI = dyn_cast<PHINode>(U.getUser())) {
Rafael Espindola2453dff2012-03-15 15:52:59 +00004387 // For PHI nodes, insert the bitcast in the predecessor block.
Dan Gohman0daef3d2012-05-08 23:39:44 +00004388 unsigned ValNo = PHINode::getIncomingValueNumForOperand(OperandNo);
4389 BasicBlock *BB = PHI->getIncomingBlock(ValNo);
Rafael Espindola2453dff2012-03-15 15:52:59 +00004390 if (Replacement->getType() != UseTy)
4391 Replacement = new BitCastInst(Replacement, UseTy, "",
4392 &BB->back());
Dan Gohmand6bf2012012-04-13 18:57:48 +00004393 // While we're here, rewrite all edges for this PHI, rather
4394 // than just one use at a time, to minimize the number of
4395 // bitcasts we emit.
Dan Gohman447989c2012-04-27 18:56:31 +00004396 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
Rafael Espindola2453dff2012-03-15 15:52:59 +00004397 if (PHI->getIncomingBlock(i) == BB) {
4398 // Keep the UI iterator valid.
4399 if (&PHI->getOperandUse(
4400 PHINode::getOperandNumForIncomingValue(i)) ==
4401 &UI.getUse())
4402 ++UI;
4403 PHI->setIncomingValue(i, Replacement);
4404 }
4405 } else {
4406 if (Replacement->getType() != UseTy)
Dan Gohman6c189ec2012-04-13 01:08:28 +00004407 Replacement = new BitCastInst(Replacement, UseTy, "",
4408 cast<Instruction>(U.getUser()));
Rafael Espindola2453dff2012-03-15 15:52:59 +00004409 U.set(Replacement);
John McCall9fbd3182011-06-15 23:37:01 +00004410 }
Rafael Espindola2453dff2012-03-15 15:52:59 +00004411 }
John McCall9fbd3182011-06-15 23:37:01 +00004412 }
4413
Dan Gohman447989c2012-04-27 18:56:31 +00004414 // If Arg is a no-op casted pointer, strip one level of casts and iterate.
John McCall9fbd3182011-06-15 23:37:01 +00004415 if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
4416 Arg = BI->getOperand(0);
4417 else if (isa<GEPOperator>(Arg) &&
4418 cast<GEPOperator>(Arg)->hasAllZeroIndices())
4419 Arg = cast<GEPOperator>(Arg)->getPointerOperand();
4420 else if (isa<GlobalAlias>(Arg) &&
4421 !cast<GlobalAlias>(Arg)->mayBeOverridden())
4422 Arg = cast<GlobalAlias>(Arg)->getAliasee();
4423 else
4424 break;
4425 }
4426 }
4427
Dan Gohman0cdece42012-01-19 19:14:36 +00004428 // If this function has no escaping allocas or suspicious vararg usage,
4429 // objc_storeStrong calls can be marked with the "tail" keyword.
4430 if (TailOkForStoreStrongs)
Dan Gohman0daef3d2012-05-08 23:39:44 +00004431 for (SmallPtrSet<CallInst *, 8>::iterator I = StoreStrongCalls.begin(),
Dan Gohman0cdece42012-01-19 19:14:36 +00004432 E = StoreStrongCalls.end(); I != E; ++I)
4433 (*I)->setTailCall();
4434 StoreStrongCalls.clear();
4435
John McCall9fbd3182011-06-15 23:37:01 +00004436 return Changed;
4437}