blob: 017df8f1a4db7f7d109e4679bf2031eecafcfd78 [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"
Dan Gohman0d1bc5f2012-09-12 20:45:17 +000032#include "llvm/Support/raw_ostream.h"
John McCall9fbd3182011-06-15 23:37:01 +000033#include "llvm/Support/CommandLine.h"
John McCall9fbd3182011-06-15 23:37:01 +000034#include "llvm/ADT/DenseMap.h"
John McCall9fbd3182011-06-15 23:37:01 +000035using namespace llvm;
36
37// A handy option to enable/disable all optimizations in this file.
38static cl::opt<bool> EnableARCOpts("enable-objc-arc-opts", cl::init(true));
39
40//===----------------------------------------------------------------------===//
41// Misc. Utilities
42//===----------------------------------------------------------------------===//
43
44namespace {
45 /// MapVector - An associative container with fast insertion-order
46 /// (deterministic) iteration over its elements. Plus the special
47 /// blot operation.
48 template<class KeyT, class ValueT>
49 class MapVector {
50 /// Map - Map keys to indices in Vector.
51 typedef DenseMap<KeyT, size_t> MapTy;
52 MapTy Map;
53
54 /// Vector - Keys and values.
55 typedef std::vector<std::pair<KeyT, ValueT> > VectorTy;
56 VectorTy Vector;
57
58 public:
59 typedef typename VectorTy::iterator iterator;
60 typedef typename VectorTy::const_iterator const_iterator;
61 iterator begin() { return Vector.begin(); }
62 iterator end() { return Vector.end(); }
63 const_iterator begin() const { return Vector.begin(); }
64 const_iterator end() const { return Vector.end(); }
65
66#ifdef XDEBUG
67 ~MapVector() {
68 assert(Vector.size() >= Map.size()); // May differ due to blotting.
69 for (typename MapTy::const_iterator I = Map.begin(), E = Map.end();
70 I != E; ++I) {
71 assert(I->second < Vector.size());
72 assert(Vector[I->second].first == I->first);
73 }
74 for (typename VectorTy::const_iterator I = Vector.begin(),
75 E = Vector.end(); I != E; ++I)
76 assert(!I->first ||
77 (Map.count(I->first) &&
78 Map[I->first] == size_t(I - Vector.begin())));
79 }
80#endif
81
Dan Gohman22cc4cc2012-03-02 01:13:53 +000082 ValueT &operator[](const KeyT &Arg) {
John McCall9fbd3182011-06-15 23:37:01 +000083 std::pair<typename MapTy::iterator, bool> Pair =
84 Map.insert(std::make_pair(Arg, size_t(0)));
85 if (Pair.second) {
Dan Gohman22cc4cc2012-03-02 01:13:53 +000086 size_t Num = Vector.size();
87 Pair.first->second = Num;
John McCall9fbd3182011-06-15 23:37:01 +000088 Vector.push_back(std::make_pair(Arg, ValueT()));
Dan Gohman22cc4cc2012-03-02 01:13:53 +000089 return Vector[Num].second;
John McCall9fbd3182011-06-15 23:37:01 +000090 }
91 return Vector[Pair.first->second].second;
92 }
93
94 std::pair<iterator, bool>
95 insert(const std::pair<KeyT, ValueT> &InsertPair) {
96 std::pair<typename MapTy::iterator, bool> Pair =
97 Map.insert(std::make_pair(InsertPair.first, size_t(0)));
98 if (Pair.second) {
Dan Gohman22cc4cc2012-03-02 01:13:53 +000099 size_t Num = Vector.size();
100 Pair.first->second = Num;
John McCall9fbd3182011-06-15 23:37:01 +0000101 Vector.push_back(InsertPair);
Dan Gohman22cc4cc2012-03-02 01:13:53 +0000102 return std::make_pair(Vector.begin() + Num, true);
John McCall9fbd3182011-06-15 23:37:01 +0000103 }
104 return std::make_pair(Vector.begin() + Pair.first->second, false);
105 }
106
Dan Gohman22cc4cc2012-03-02 01:13:53 +0000107 const_iterator find(const KeyT &Key) const {
John McCall9fbd3182011-06-15 23:37:01 +0000108 typename MapTy::const_iterator It = Map.find(Key);
109 if (It == Map.end()) return Vector.end();
110 return Vector.begin() + It->second;
111 }
112
113 /// blot - This is similar to erase, but instead of removing the element
114 /// from the vector, it just zeros out the key in the vector. This leaves
115 /// iterators intact, but clients must be prepared for zeroed-out keys when
116 /// iterating.
Dan Gohman22cc4cc2012-03-02 01:13:53 +0000117 void blot(const KeyT &Key) {
John McCall9fbd3182011-06-15 23:37:01 +0000118 typename MapTy::iterator It = Map.find(Key);
119 if (It == Map.end()) return;
120 Vector[It->second].first = KeyT();
121 Map.erase(It);
122 }
123
124 void clear() {
125 Map.clear();
126 Vector.clear();
127 }
128 };
129}
130
131//===----------------------------------------------------------------------===//
132// ARC Utilities.
133//===----------------------------------------------------------------------===//
134
Dan Gohman0daef3d2012-05-08 23:39:44 +0000135#include "llvm/Intrinsics.h"
136#include "llvm/Module.h"
137#include "llvm/Analysis/ValueTracking.h"
138#include "llvm/Transforms/Utils/Local.h"
139#include "llvm/Support/CallSite.h"
140#include "llvm/ADT/StringSwitch.h"
141
John McCall9fbd3182011-06-15 23:37:01 +0000142namespace {
143 /// InstructionClass - A simple classification for instructions.
144 enum InstructionClass {
145 IC_Retain, ///< objc_retain
146 IC_RetainRV, ///< objc_retainAutoreleasedReturnValue
147 IC_RetainBlock, ///< objc_retainBlock
148 IC_Release, ///< objc_release
149 IC_Autorelease, ///< objc_autorelease
150 IC_AutoreleaseRV, ///< objc_autoreleaseReturnValue
151 IC_AutoreleasepoolPush, ///< objc_autoreleasePoolPush
152 IC_AutoreleasepoolPop, ///< objc_autoreleasePoolPop
153 IC_NoopCast, ///< objc_retainedObject, etc.
154 IC_FusedRetainAutorelease, ///< objc_retainAutorelease
155 IC_FusedRetainAutoreleaseRV, ///< objc_retainAutoreleaseReturnValue
156 IC_LoadWeakRetained, ///< objc_loadWeakRetained (primitive)
157 IC_StoreWeak, ///< objc_storeWeak (primitive)
158 IC_InitWeak, ///< objc_initWeak (derived)
159 IC_LoadWeak, ///< objc_loadWeak (derived)
160 IC_MoveWeak, ///< objc_moveWeak (derived)
161 IC_CopyWeak, ///< objc_copyWeak (derived)
162 IC_DestroyWeak, ///< objc_destroyWeak (derived)
Dan Gohman44234772012-04-13 18:28:58 +0000163 IC_StoreStrong, ///< objc_storeStrong (derived)
John McCall9fbd3182011-06-15 23:37:01 +0000164 IC_CallOrUser, ///< could call objc_release and/or "use" pointers
165 IC_Call, ///< could call objc_release
166 IC_User, ///< could "use" a pointer
167 IC_None ///< anything else
168 };
169}
170
171/// IsPotentialUse - Test whether the given value is possible a
172/// reference-counted pointer.
173static bool IsPotentialUse(const Value *Op) {
174 // Pointers to static or stack storage are not reference-counted pointers.
175 if (isa<Constant>(Op) || isa<AllocaInst>(Op))
176 return false;
177 // Special arguments are not reference-counted.
178 if (const Argument *Arg = dyn_cast<Argument>(Op))
179 if (Arg->hasByValAttr() ||
180 Arg->hasNestAttr() ||
181 Arg->hasStructRetAttr())
182 return false;
Dan Gohmanf9096e42011-12-14 19:10:53 +0000183 // Only consider values with pointer types.
184 // It seemes intuitive to exclude function pointer types as well, since
185 // functions are never reference-counted, however clang occasionally
186 // bitcasts reference-counted pointers to function-pointer type
187 // temporarily.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000188 PointerType *Ty = dyn_cast<PointerType>(Op->getType());
Dan Gohmanf9096e42011-12-14 19:10:53 +0000189 if (!Ty)
John McCall9fbd3182011-06-15 23:37:01 +0000190 return false;
191 // Conservatively assume anything else is a potential use.
192 return true;
193}
194
195/// GetCallSiteClass - Helper for GetInstructionClass. Determines what kind
196/// of construct CS is.
197static InstructionClass GetCallSiteClass(ImmutableCallSite CS) {
198 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
199 I != E; ++I)
200 if (IsPotentialUse(*I))
201 return CS.onlyReadsMemory() ? IC_User : IC_CallOrUser;
202
203 return CS.onlyReadsMemory() ? IC_None : IC_Call;
204}
205
206/// GetFunctionClass - Determine if F is one of the special known Functions.
207/// If it isn't, return IC_CallOrUser.
208static InstructionClass GetFunctionClass(const Function *F) {
209 Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
210
211 // No arguments.
212 if (AI == AE)
213 return StringSwitch<InstructionClass>(F->getName())
214 .Case("objc_autoreleasePoolPush", IC_AutoreleasepoolPush)
215 .Default(IC_CallOrUser);
216
217 // One argument.
218 const Argument *A0 = AI++;
219 if (AI == AE)
220 // Argument is a pointer.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000221 if (PointerType *PTy = dyn_cast<PointerType>(A0->getType())) {
222 Type *ETy = PTy->getElementType();
John McCall9fbd3182011-06-15 23:37:01 +0000223 // Argument is i8*.
224 if (ETy->isIntegerTy(8))
225 return StringSwitch<InstructionClass>(F->getName())
226 .Case("objc_retain", IC_Retain)
227 .Case("objc_retainAutoreleasedReturnValue", IC_RetainRV)
228 .Case("objc_retainBlock", IC_RetainBlock)
229 .Case("objc_release", IC_Release)
230 .Case("objc_autorelease", IC_Autorelease)
231 .Case("objc_autoreleaseReturnValue", IC_AutoreleaseRV)
232 .Case("objc_autoreleasePoolPop", IC_AutoreleasepoolPop)
233 .Case("objc_retainedObject", IC_NoopCast)
234 .Case("objc_unretainedObject", IC_NoopCast)
235 .Case("objc_unretainedPointer", IC_NoopCast)
236 .Case("objc_retain_autorelease", IC_FusedRetainAutorelease)
237 .Case("objc_retainAutorelease", IC_FusedRetainAutorelease)
238 .Case("objc_retainAutoreleaseReturnValue",IC_FusedRetainAutoreleaseRV)
239 .Default(IC_CallOrUser);
240
241 // Argument is i8**
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000242 if (PointerType *Pte = dyn_cast<PointerType>(ETy))
John McCall9fbd3182011-06-15 23:37:01 +0000243 if (Pte->getElementType()->isIntegerTy(8))
244 return StringSwitch<InstructionClass>(F->getName())
245 .Case("objc_loadWeakRetained", IC_LoadWeakRetained)
246 .Case("objc_loadWeak", IC_LoadWeak)
247 .Case("objc_destroyWeak", IC_DestroyWeak)
248 .Default(IC_CallOrUser);
249 }
250
251 // Two arguments, first is i8**.
252 const Argument *A1 = AI++;
253 if (AI == AE)
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000254 if (PointerType *PTy = dyn_cast<PointerType>(A0->getType()))
255 if (PointerType *Pte = dyn_cast<PointerType>(PTy->getElementType()))
John McCall9fbd3182011-06-15 23:37:01 +0000256 if (Pte->getElementType()->isIntegerTy(8))
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000257 if (PointerType *PTy1 = dyn_cast<PointerType>(A1->getType())) {
258 Type *ETy1 = PTy1->getElementType();
John McCall9fbd3182011-06-15 23:37:01 +0000259 // Second argument is i8*
260 if (ETy1->isIntegerTy(8))
261 return StringSwitch<InstructionClass>(F->getName())
262 .Case("objc_storeWeak", IC_StoreWeak)
263 .Case("objc_initWeak", IC_InitWeak)
Dan Gohman44234772012-04-13 18:28:58 +0000264 .Case("objc_storeStrong", IC_StoreStrong)
John McCall9fbd3182011-06-15 23:37:01 +0000265 .Default(IC_CallOrUser);
266 // Second argument is i8**.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000267 if (PointerType *Pte1 = dyn_cast<PointerType>(ETy1))
John McCall9fbd3182011-06-15 23:37:01 +0000268 if (Pte1->getElementType()->isIntegerTy(8))
269 return StringSwitch<InstructionClass>(F->getName())
270 .Case("objc_moveWeak", IC_MoveWeak)
271 .Case("objc_copyWeak", IC_CopyWeak)
272 .Default(IC_CallOrUser);
273 }
274
275 // Anything else.
276 return IC_CallOrUser;
277}
278
279/// GetInstructionClass - Determine what kind of construct V is.
280static InstructionClass GetInstructionClass(const Value *V) {
281 if (const Instruction *I = dyn_cast<Instruction>(V)) {
282 // Any instruction other than bitcast and gep with a pointer operand have a
283 // use of an objc pointer. Bitcasts, GEPs, Selects, PHIs transfer a pointer
284 // to a subsequent use, rather than using it themselves, in this sense.
285 // As a short cut, several other opcodes are known to have no pointer
286 // operands of interest. And ret is never followed by a release, so it's
287 // not interesting to examine.
288 switch (I->getOpcode()) {
289 case Instruction::Call: {
290 const CallInst *CI = cast<CallInst>(I);
291 // Check for calls to special functions.
292 if (const Function *F = CI->getCalledFunction()) {
293 InstructionClass Class = GetFunctionClass(F);
294 if (Class != IC_CallOrUser)
295 return Class;
296
297 // None of the intrinsic functions do objc_release. For intrinsics, the
298 // only question is whether or not they may be users.
299 switch (F->getIntrinsicID()) {
John McCall9fbd3182011-06-15 23:37:01 +0000300 case Intrinsic::returnaddress: case Intrinsic::frameaddress:
301 case Intrinsic::stacksave: case Intrinsic::stackrestore:
302 case Intrinsic::vastart: case Intrinsic::vacopy: case Intrinsic::vaend:
Dan Gohman0daef3d2012-05-08 23:39:44 +0000303 case Intrinsic::objectsize: case Intrinsic::prefetch:
304 case Intrinsic::stackprotector:
305 case Intrinsic::eh_return_i32: case Intrinsic::eh_return_i64:
306 case Intrinsic::eh_typeid_for: case Intrinsic::eh_dwarf_cfa:
307 case Intrinsic::eh_sjlj_lsda: case Intrinsic::eh_sjlj_functioncontext:
308 case Intrinsic::init_trampoline: case Intrinsic::adjust_trampoline:
309 case Intrinsic::lifetime_start: case Intrinsic::lifetime_end:
310 case Intrinsic::invariant_start: case Intrinsic::invariant_end:
John McCall9fbd3182011-06-15 23:37:01 +0000311 // Don't let dbg info affect our results.
312 case Intrinsic::dbg_declare: case Intrinsic::dbg_value:
313 // Short cut: Some intrinsics obviously don't use ObjC pointers.
314 return IC_None;
315 default:
Dan Gohman0daef3d2012-05-08 23:39:44 +0000316 break;
John McCall9fbd3182011-06-15 23:37:01 +0000317 }
318 }
319 return GetCallSiteClass(CI);
320 }
321 case Instruction::Invoke:
322 return GetCallSiteClass(cast<InvokeInst>(I));
323 case Instruction::BitCast:
324 case Instruction::GetElementPtr:
325 case Instruction::Select: case Instruction::PHI:
326 case Instruction::Ret: case Instruction::Br:
327 case Instruction::Switch: case Instruction::IndirectBr:
328 case Instruction::Alloca: case Instruction::VAArg:
329 case Instruction::Add: case Instruction::FAdd:
330 case Instruction::Sub: case Instruction::FSub:
331 case Instruction::Mul: case Instruction::FMul:
332 case Instruction::SDiv: case Instruction::UDiv: case Instruction::FDiv:
333 case Instruction::SRem: case Instruction::URem: case Instruction::FRem:
334 case Instruction::Shl: case Instruction::LShr: case Instruction::AShr:
335 case Instruction::And: case Instruction::Or: case Instruction::Xor:
336 case Instruction::SExt: case Instruction::ZExt: case Instruction::Trunc:
337 case Instruction::IntToPtr: case Instruction::FCmp:
338 case Instruction::FPTrunc: case Instruction::FPExt:
339 case Instruction::FPToUI: case Instruction::FPToSI:
340 case Instruction::UIToFP: case Instruction::SIToFP:
341 case Instruction::InsertElement: case Instruction::ExtractElement:
342 case Instruction::ShuffleVector:
343 case Instruction::ExtractValue:
344 break;
345 case Instruction::ICmp:
346 // Comparing a pointer with null, or any other constant, isn't an
347 // interesting use, because we don't care what the pointer points to, or
348 // about the values of any other dynamic reference-counted pointers.
349 if (IsPotentialUse(I->getOperand(1)))
350 return IC_User;
351 break;
352 default:
353 // For anything else, check all the operands.
Dan Gohmand4464602011-08-22 17:29:37 +0000354 // Note that this includes both operands of a Store: while the first
355 // operand isn't actually being dereferenced, it is being stored to
356 // memory where we can no longer track who might read it and dereference
357 // it, so we have to consider it potentially used.
John McCall9fbd3182011-06-15 23:37:01 +0000358 for (User::const_op_iterator OI = I->op_begin(), OE = I->op_end();
359 OI != OE; ++OI)
360 if (IsPotentialUse(*OI))
361 return IC_User;
362 }
363 }
364
365 // Otherwise, it's totally inert for ARC purposes.
366 return IC_None;
367}
368
369/// GetBasicInstructionClass - Determine what kind of construct V is. This is
370/// similar to GetInstructionClass except that it only detects objc runtine
371/// calls. This allows it to be faster.
372static InstructionClass GetBasicInstructionClass(const Value *V) {
373 if (const CallInst *CI = dyn_cast<CallInst>(V)) {
374 if (const Function *F = CI->getCalledFunction())
375 return GetFunctionClass(F);
376 // Otherwise, be conservative.
377 return IC_CallOrUser;
378 }
379
380 // Otherwise, be conservative.
Dan Gohman2f6263c2012-01-17 20:52:24 +0000381 return isa<InvokeInst>(V) ? IC_CallOrUser : IC_User;
John McCall9fbd3182011-06-15 23:37:01 +0000382}
383
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +0000384/// IsRetain - Test if the given class is objc_retain or
John McCall9fbd3182011-06-15 23:37:01 +0000385/// equivalent.
386static bool IsRetain(InstructionClass Class) {
387 return Class == IC_Retain ||
388 Class == IC_RetainRV;
389}
390
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +0000391/// IsAutorelease - Test if the given class is objc_autorelease or
John McCall9fbd3182011-06-15 23:37:01 +0000392/// equivalent.
393static bool IsAutorelease(InstructionClass Class) {
394 return Class == IC_Autorelease ||
395 Class == IC_AutoreleaseRV;
396}
397
398/// IsForwarding - Test if the given class represents instructions which return
399/// their argument verbatim.
400static bool IsForwarding(InstructionClass Class) {
401 // objc_retainBlock technically doesn't always return its argument
402 // verbatim, but it doesn't matter for our purposes here.
403 return Class == IC_Retain ||
404 Class == IC_RetainRV ||
405 Class == IC_Autorelease ||
406 Class == IC_AutoreleaseRV ||
407 Class == IC_RetainBlock ||
408 Class == IC_NoopCast;
409}
410
411/// IsNoopOnNull - Test if the given class represents instructions which do
412/// nothing if passed a null pointer.
413static bool IsNoopOnNull(InstructionClass Class) {
414 return Class == IC_Retain ||
415 Class == IC_RetainRV ||
416 Class == IC_Release ||
417 Class == IC_Autorelease ||
418 Class == IC_AutoreleaseRV ||
419 Class == IC_RetainBlock;
420}
421
422/// IsAlwaysTail - Test if the given class represents instructions which are
423/// always safe to mark with the "tail" keyword.
424static bool IsAlwaysTail(InstructionClass Class) {
425 // IC_RetainBlock may be given a stack argument.
426 return Class == IC_Retain ||
427 Class == IC_RetainRV ||
428 Class == IC_Autorelease ||
429 Class == IC_AutoreleaseRV;
430}
431
432/// IsNoThrow - Test if the given class represents instructions which are always
433/// safe to mark with the nounwind attribute..
434static bool IsNoThrow(InstructionClass Class) {
Dan Gohman1d2fd752011-09-14 18:33:34 +0000435 // objc_retainBlock is not nounwind because it calls user copy constructors
436 // which could theoretically throw.
John McCall9fbd3182011-06-15 23:37:01 +0000437 return Class == IC_Retain ||
438 Class == IC_RetainRV ||
John McCall9fbd3182011-06-15 23:37:01 +0000439 Class == IC_Release ||
440 Class == IC_Autorelease ||
441 Class == IC_AutoreleaseRV ||
442 Class == IC_AutoreleasepoolPush ||
443 Class == IC_AutoreleasepoolPop;
444}
445
Dan Gohman447989c2012-04-27 18:56:31 +0000446/// EraseInstruction - Erase the given instruction. Many ObjC calls return their
John McCall9fbd3182011-06-15 23:37:01 +0000447/// argument verbatim, so if it's such a call and the return value has users,
448/// replace them with the argument value.
449static void EraseInstruction(Instruction *CI) {
450 Value *OldArg = cast<CallInst>(CI)->getArgOperand(0);
451
452 bool Unused = CI->use_empty();
453
454 if (!Unused) {
455 // Replace the return value with the argument.
456 assert(IsForwarding(GetBasicInstructionClass(CI)) &&
457 "Can't delete non-forwarding instruction with users!");
458 CI->replaceAllUsesWith(OldArg);
459 }
460
461 CI->eraseFromParent();
462
463 if (Unused)
464 RecursivelyDeleteTriviallyDeadInstructions(OldArg);
465}
466
467/// GetUnderlyingObjCPtr - This is a wrapper around getUnderlyingObject which
468/// also knows how to look through objc_retain and objc_autorelease calls, which
469/// we know to return their argument verbatim.
470static const Value *GetUnderlyingObjCPtr(const Value *V) {
471 for (;;) {
472 V = GetUnderlyingObject(V);
473 if (!IsForwarding(GetBasicInstructionClass(V)))
474 break;
475 V = cast<CallInst>(V)->getArgOperand(0);
476 }
477
478 return V;
479}
480
481/// StripPointerCastsAndObjCCalls - This is a wrapper around
482/// Value::stripPointerCasts which also knows how to look through objc_retain
483/// and objc_autorelease calls, which we know to return their argument verbatim.
484static const Value *StripPointerCastsAndObjCCalls(const Value *V) {
485 for (;;) {
486 V = V->stripPointerCasts();
487 if (!IsForwarding(GetBasicInstructionClass(V)))
488 break;
489 V = cast<CallInst>(V)->getArgOperand(0);
490 }
491 return V;
492}
493
494/// StripPointerCastsAndObjCCalls - This is a wrapper around
495/// Value::stripPointerCasts which also knows how to look through objc_retain
496/// and objc_autorelease calls, which we know to return their argument verbatim.
497static Value *StripPointerCastsAndObjCCalls(Value *V) {
498 for (;;) {
499 V = V->stripPointerCasts();
500 if (!IsForwarding(GetBasicInstructionClass(V)))
501 break;
502 V = cast<CallInst>(V)->getArgOperand(0);
503 }
504 return V;
505}
506
507/// GetObjCArg - Assuming the given instruction is one of the special calls such
508/// as objc_retain or objc_release, return the argument value, stripped of no-op
509/// casts and forwarding calls.
510static Value *GetObjCArg(Value *Inst) {
511 return StripPointerCastsAndObjCCalls(cast<CallInst>(Inst)->getArgOperand(0));
512}
513
514/// IsObjCIdentifiedObject - This is similar to AliasAnalysis'
515/// isObjCIdentifiedObject, except that it uses special knowledge of
516/// ObjC conventions...
517static bool IsObjCIdentifiedObject(const Value *V) {
518 // Assume that call results and arguments have their own "provenance".
519 // Constants (including GlobalVariables) and Allocas are never
520 // reference-counted.
521 if (isa<CallInst>(V) || isa<InvokeInst>(V) ||
522 isa<Argument>(V) || isa<Constant>(V) ||
523 isa<AllocaInst>(V))
524 return true;
525
526 if (const LoadInst *LI = dyn_cast<LoadInst>(V)) {
527 const Value *Pointer =
528 StripPointerCastsAndObjCCalls(LI->getPointerOperand());
529 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Pointer)) {
Dan Gohman1b31ea82011-08-22 17:29:11 +0000530 // A constant pointer can't be pointing to an object on the heap. It may
531 // be reference-counted, but it won't be deleted.
532 if (GV->isConstant())
533 return true;
John McCall9fbd3182011-06-15 23:37:01 +0000534 StringRef Name = GV->getName();
535 // These special variables are known to hold values which are not
536 // reference-counted pointers.
537 if (Name.startswith("\01L_OBJC_SELECTOR_REFERENCES_") ||
538 Name.startswith("\01L_OBJC_CLASSLIST_REFERENCES_") ||
539 Name.startswith("\01L_OBJC_CLASSLIST_SUP_REFS_$_") ||
540 Name.startswith("\01L_OBJC_METH_VAR_NAME_") ||
541 Name.startswith("\01l_objc_msgSend_fixup_"))
542 return true;
543 }
544 }
545
546 return false;
547}
548
549/// FindSingleUseIdentifiedObject - This is similar to
550/// StripPointerCastsAndObjCCalls but it stops as soon as it finds a value
551/// with multiple uses.
552static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
553 if (Arg->hasOneUse()) {
554 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
555 return FindSingleUseIdentifiedObject(BC->getOperand(0));
556 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
557 if (GEP->hasAllZeroIndices())
558 return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
559 if (IsForwarding(GetBasicInstructionClass(Arg)))
560 return FindSingleUseIdentifiedObject(
561 cast<CallInst>(Arg)->getArgOperand(0));
562 if (!IsObjCIdentifiedObject(Arg))
563 return 0;
564 return Arg;
565 }
566
Dan Gohman0daef3d2012-05-08 23:39:44 +0000567 // If we found an identifiable object but it has multiple uses, but they are
568 // trivial uses, we can still consider this to be a single-use value.
John McCall9fbd3182011-06-15 23:37:01 +0000569 if (IsObjCIdentifiedObject(Arg)) {
570 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
571 UI != UE; ++UI) {
572 const User *U = *UI;
573 if (!U->use_empty() || StripPointerCastsAndObjCCalls(U) != Arg)
574 return 0;
575 }
576
577 return Arg;
578 }
579
580 return 0;
581}
582
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000583/// ModuleHasARC - Test if the given module looks interesting to run ARC
584/// optimization on.
585static bool ModuleHasARC(const Module &M) {
586 return
587 M.getNamedValue("objc_retain") ||
588 M.getNamedValue("objc_release") ||
589 M.getNamedValue("objc_autorelease") ||
590 M.getNamedValue("objc_retainAutoreleasedReturnValue") ||
591 M.getNamedValue("objc_retainBlock") ||
592 M.getNamedValue("objc_autoreleaseReturnValue") ||
593 M.getNamedValue("objc_autoreleasePoolPush") ||
594 M.getNamedValue("objc_loadWeakRetained") ||
595 M.getNamedValue("objc_loadWeak") ||
596 M.getNamedValue("objc_destroyWeak") ||
597 M.getNamedValue("objc_storeWeak") ||
598 M.getNamedValue("objc_initWeak") ||
599 M.getNamedValue("objc_moveWeak") ||
600 M.getNamedValue("objc_copyWeak") ||
601 M.getNamedValue("objc_retainedObject") ||
602 M.getNamedValue("objc_unretainedObject") ||
603 M.getNamedValue("objc_unretainedPointer");
604}
605
Dan Gohman79522dc2012-01-13 00:39:07 +0000606/// DoesObjCBlockEscape - Test whether the given pointer, which is an
607/// Objective C block pointer, does not "escape". This differs from regular
608/// escape analysis in that a use as an argument to a call is not considered
609/// an escape.
610static bool DoesObjCBlockEscape(const Value *BlockPtr) {
611 // Walk the def-use chains.
612 SmallVector<const Value *, 4> Worklist;
613 Worklist.push_back(BlockPtr);
614 do {
615 const Value *V = Worklist.pop_back_val();
616 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
617 UI != UE; ++UI) {
618 const User *UUser = *UI;
619 // Special - Use by a call (callee or argument) is not considered
620 // to be an escape.
Dan Gohman44234772012-04-13 18:28:58 +0000621 switch (GetBasicInstructionClass(UUser)) {
622 case IC_StoreWeak:
623 case IC_InitWeak:
624 case IC_StoreStrong:
625 case IC_Autorelease:
626 case IC_AutoreleaseRV:
627 // These special functions make copies of their pointer arguments.
628 return true;
629 case IC_User:
630 case IC_None:
631 // Use by an instruction which copies the value is an escape if the
632 // result is an escape.
633 if (isa<BitCastInst>(UUser) || isa<GetElementPtrInst>(UUser) ||
634 isa<PHINode>(UUser) || isa<SelectInst>(UUser)) {
635 Worklist.push_back(UUser);
636 continue;
637 }
638 // Use by a load is not an escape.
639 if (isa<LoadInst>(UUser))
640 continue;
641 // Use by a store is not an escape if the use is the address.
642 if (const StoreInst *SI = dyn_cast<StoreInst>(UUser))
643 if (V != SI->getValueOperand())
644 continue;
645 break;
646 default:
647 // Regular calls and other stuff are not considered escapes.
Dan Gohman79522dc2012-01-13 00:39:07 +0000648 continue;
649 }
Dan Gohmana3b08d62012-02-13 22:57:02 +0000650 // Otherwise, conservatively assume an escape.
Dan Gohman79522dc2012-01-13 00:39:07 +0000651 return true;
652 }
653 } while (!Worklist.empty());
654
655 // No escapes found.
656 return false;
657}
658
John McCall9fbd3182011-06-15 23:37:01 +0000659//===----------------------------------------------------------------------===//
660// ARC AliasAnalysis.
661//===----------------------------------------------------------------------===//
662
663#include "llvm/Pass.h"
664#include "llvm/Analysis/AliasAnalysis.h"
665#include "llvm/Analysis/Passes.h"
666
667namespace {
668 /// ObjCARCAliasAnalysis - This is a simple alias analysis
669 /// implementation that uses knowledge of ARC constructs to answer queries.
670 ///
671 /// TODO: This class could be generalized to know about other ObjC-specific
672 /// tricks. Such as knowing that ivars in the non-fragile ABI are non-aliasing
673 /// even though their offsets are dynamic.
674 class ObjCARCAliasAnalysis : public ImmutablePass,
675 public AliasAnalysis {
676 public:
677 static char ID; // Class identification, replacement for typeinfo
678 ObjCARCAliasAnalysis() : ImmutablePass(ID) {
679 initializeObjCARCAliasAnalysisPass(*PassRegistry::getPassRegistry());
680 }
681
682 private:
683 virtual void initializePass() {
684 InitializeAliasAnalysis(this);
685 }
686
687 /// getAdjustedAnalysisPointer - This method is used when a pass implements
688 /// an analysis interface through multiple inheritance. If needed, it
689 /// should override this to adjust the this pointer as needed for the
690 /// specified pass info.
691 virtual void *getAdjustedAnalysisPointer(const void *PI) {
692 if (PI == &AliasAnalysis::ID)
Dan Gohman447989c2012-04-27 18:56:31 +0000693 return static_cast<AliasAnalysis *>(this);
John McCall9fbd3182011-06-15 23:37:01 +0000694 return this;
695 }
696
697 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
698 virtual AliasResult alias(const Location &LocA, const Location &LocB);
699 virtual bool pointsToConstantMemory(const Location &Loc, bool OrLocal);
700 virtual ModRefBehavior getModRefBehavior(ImmutableCallSite CS);
701 virtual ModRefBehavior getModRefBehavior(const Function *F);
702 virtual ModRefResult getModRefInfo(ImmutableCallSite CS,
703 const Location &Loc);
704 virtual ModRefResult getModRefInfo(ImmutableCallSite CS1,
705 ImmutableCallSite CS2);
706 };
707} // End of anonymous namespace
708
709// Register this pass...
710char ObjCARCAliasAnalysis::ID = 0;
711INITIALIZE_AG_PASS(ObjCARCAliasAnalysis, AliasAnalysis, "objc-arc-aa",
712 "ObjC-ARC-Based Alias Analysis", false, true, false)
713
714ImmutablePass *llvm::createObjCARCAliasAnalysisPass() {
715 return new ObjCARCAliasAnalysis();
716}
717
718void
719ObjCARCAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
720 AU.setPreservesAll();
721 AliasAnalysis::getAnalysisUsage(AU);
722}
723
724AliasAnalysis::AliasResult
725ObjCARCAliasAnalysis::alias(const Location &LocA, const Location &LocB) {
726 if (!EnableARCOpts)
727 return AliasAnalysis::alias(LocA, LocB);
728
729 // First, strip off no-ops, including ObjC-specific no-ops, and try making a
730 // precise alias query.
731 const Value *SA = StripPointerCastsAndObjCCalls(LocA.Ptr);
732 const Value *SB = StripPointerCastsAndObjCCalls(LocB.Ptr);
733 AliasResult Result =
734 AliasAnalysis::alias(Location(SA, LocA.Size, LocA.TBAATag),
735 Location(SB, LocB.Size, LocB.TBAATag));
736 if (Result != MayAlias)
737 return Result;
738
739 // If that failed, climb to the underlying object, including climbing through
740 // ObjC-specific no-ops, and try making an imprecise alias query.
741 const Value *UA = GetUnderlyingObjCPtr(SA);
742 const Value *UB = GetUnderlyingObjCPtr(SB);
743 if (UA != SA || UB != SB) {
744 Result = AliasAnalysis::alias(Location(UA), Location(UB));
745 // We can't use MustAlias or PartialAlias results here because
746 // GetUnderlyingObjCPtr may return an offsetted pointer value.
747 if (Result == NoAlias)
748 return NoAlias;
749 }
750
751 // If that failed, fail. We don't need to chain here, since that's covered
752 // by the earlier precise query.
753 return MayAlias;
754}
755
756bool
757ObjCARCAliasAnalysis::pointsToConstantMemory(const Location &Loc,
758 bool OrLocal) {
759 if (!EnableARCOpts)
760 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
761
762 // First, strip off no-ops, including ObjC-specific no-ops, and try making
763 // a precise alias query.
764 const Value *S = StripPointerCastsAndObjCCalls(Loc.Ptr);
765 if (AliasAnalysis::pointsToConstantMemory(Location(S, Loc.Size, Loc.TBAATag),
766 OrLocal))
767 return true;
768
769 // If that failed, climb to the underlying object, including climbing through
770 // ObjC-specific no-ops, and try making an imprecise alias query.
771 const Value *U = GetUnderlyingObjCPtr(S);
772 if (U != S)
773 return AliasAnalysis::pointsToConstantMemory(Location(U), OrLocal);
774
775 // If that failed, fail. We don't need to chain here, since that's covered
776 // by the earlier precise query.
777 return false;
778}
779
780AliasAnalysis::ModRefBehavior
781ObjCARCAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
782 // We have nothing to do. Just chain to the next AliasAnalysis.
783 return AliasAnalysis::getModRefBehavior(CS);
784}
785
786AliasAnalysis::ModRefBehavior
787ObjCARCAliasAnalysis::getModRefBehavior(const Function *F) {
788 if (!EnableARCOpts)
789 return AliasAnalysis::getModRefBehavior(F);
790
791 switch (GetFunctionClass(F)) {
792 case IC_NoopCast:
793 return DoesNotAccessMemory;
794 default:
795 break;
796 }
797
798 return AliasAnalysis::getModRefBehavior(F);
799}
800
801AliasAnalysis::ModRefResult
802ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS, const Location &Loc) {
803 if (!EnableARCOpts)
804 return AliasAnalysis::getModRefInfo(CS, Loc);
805
806 switch (GetBasicInstructionClass(CS.getInstruction())) {
807 case IC_Retain:
808 case IC_RetainRV:
John McCall9fbd3182011-06-15 23:37:01 +0000809 case IC_Autorelease:
810 case IC_AutoreleaseRV:
811 case IC_NoopCast:
812 case IC_AutoreleasepoolPush:
813 case IC_FusedRetainAutorelease:
814 case IC_FusedRetainAutoreleaseRV:
815 // These functions don't access any memory visible to the compiler.
Benjamin Kramerd9b0b022012-06-02 10:20:22 +0000816 // Note that this doesn't include objc_retainBlock, because it updates
Dan Gohman21104822011-09-14 18:13:00 +0000817 // pointers when it copies block data.
John McCall9fbd3182011-06-15 23:37:01 +0000818 return NoModRef;
819 default:
820 break;
821 }
822
823 return AliasAnalysis::getModRefInfo(CS, Loc);
824}
825
826AliasAnalysis::ModRefResult
827ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
828 ImmutableCallSite CS2) {
829 // TODO: Theoretically we could check for dependencies between objc_* calls
830 // and OnlyAccessesArgumentPointees calls or other well-behaved calls.
831 return AliasAnalysis::getModRefInfo(CS1, CS2);
832}
833
834//===----------------------------------------------------------------------===//
835// ARC expansion.
836//===----------------------------------------------------------------------===//
837
838#include "llvm/Support/InstIterator.h"
839#include "llvm/Transforms/Scalar.h"
840
841namespace {
842 /// ObjCARCExpand - Early ARC transformations.
843 class ObjCARCExpand : public FunctionPass {
844 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000845 virtual bool doInitialization(Module &M);
John McCall9fbd3182011-06-15 23:37:01 +0000846 virtual bool runOnFunction(Function &F);
847
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000848 /// Run - A flag indicating whether this optimization pass should run.
849 bool Run;
850
John McCall9fbd3182011-06-15 23:37:01 +0000851 public:
852 static char ID;
853 ObjCARCExpand() : FunctionPass(ID) {
854 initializeObjCARCExpandPass(*PassRegistry::getPassRegistry());
855 }
856 };
857}
858
859char ObjCARCExpand::ID = 0;
860INITIALIZE_PASS(ObjCARCExpand,
861 "objc-arc-expand", "ObjC ARC expansion", false, false)
862
863Pass *llvm::createObjCARCExpandPass() {
864 return new ObjCARCExpand();
865}
866
867void ObjCARCExpand::getAnalysisUsage(AnalysisUsage &AU) const {
868 AU.setPreservesCFG();
869}
870
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000871bool ObjCARCExpand::doInitialization(Module &M) {
872 Run = ModuleHasARC(M);
873 return false;
874}
875
John McCall9fbd3182011-06-15 23:37:01 +0000876bool ObjCARCExpand::runOnFunction(Function &F) {
877 if (!EnableARCOpts)
878 return false;
879
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000880 // If nothing in the Module uses ARC, don't do anything.
881 if (!Run)
882 return false;
883
John McCall9fbd3182011-06-15 23:37:01 +0000884 bool Changed = false;
885
886 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
887 Instruction *Inst = &*I;
888
889 switch (GetBasicInstructionClass(Inst)) {
890 case IC_Retain:
891 case IC_RetainRV:
892 case IC_Autorelease:
893 case IC_AutoreleaseRV:
894 case IC_FusedRetainAutorelease:
895 case IC_FusedRetainAutoreleaseRV:
896 // These calls return their argument verbatim, as a low-level
897 // optimization. However, this makes high-level optimizations
898 // harder. Undo any uses of this optimization that the front-end
Dan Gohmand6bf2012012-04-13 18:57:48 +0000899 // emitted here. We'll redo them in the contract pass.
John McCall9fbd3182011-06-15 23:37:01 +0000900 Changed = true;
901 Inst->replaceAllUsesWith(cast<CallInst>(Inst)->getArgOperand(0));
902 break;
903 default:
904 break;
905 }
906 }
907
908 return Changed;
909}
910
911//===----------------------------------------------------------------------===//
Dan Gohman2f6263c2012-01-17 20:52:24 +0000912// ARC autorelease pool elimination.
913//===----------------------------------------------------------------------===//
914
Dan Gohman1dae3e92012-01-18 21:19:38 +0000915#include "llvm/Constants.h"
Dan Gohman0daef3d2012-05-08 23:39:44 +0000916#include "llvm/ADT/STLExtras.h"
Dan Gohman1dae3e92012-01-18 21:19:38 +0000917
Dan Gohman2f6263c2012-01-17 20:52:24 +0000918namespace {
919 /// ObjCARCAPElim - Autorelease pool elimination.
920 class ObjCARCAPElim : public ModulePass {
921 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
922 virtual bool runOnModule(Module &M);
923
Dan Gohman447989c2012-04-27 18:56:31 +0000924 static bool MayAutorelease(ImmutableCallSite CS, unsigned Depth = 0);
925 static bool OptimizeBB(BasicBlock *BB);
Dan Gohman2f6263c2012-01-17 20:52:24 +0000926
927 public:
928 static char ID;
929 ObjCARCAPElim() : ModulePass(ID) {
930 initializeObjCARCAPElimPass(*PassRegistry::getPassRegistry());
931 }
932 };
933}
934
935char ObjCARCAPElim::ID = 0;
936INITIALIZE_PASS(ObjCARCAPElim,
937 "objc-arc-apelim",
938 "ObjC ARC autorelease pool elimination",
939 false, false)
940
941Pass *llvm::createObjCARCAPElimPass() {
942 return new ObjCARCAPElim();
943}
944
945void ObjCARCAPElim::getAnalysisUsage(AnalysisUsage &AU) const {
946 AU.setPreservesCFG();
947}
948
949/// MayAutorelease - Interprocedurally determine if calls made by the
950/// given call site can possibly produce autoreleases.
Dan Gohman447989c2012-04-27 18:56:31 +0000951bool ObjCARCAPElim::MayAutorelease(ImmutableCallSite CS, unsigned Depth) {
952 if (const Function *Callee = CS.getCalledFunction()) {
Dan Gohman2f6263c2012-01-17 20:52:24 +0000953 if (Callee->isDeclaration() || Callee->mayBeOverridden())
954 return true;
Dan Gohman447989c2012-04-27 18:56:31 +0000955 for (Function::const_iterator I = Callee->begin(), E = Callee->end();
Dan Gohman2f6263c2012-01-17 20:52:24 +0000956 I != E; ++I) {
Dan Gohman447989c2012-04-27 18:56:31 +0000957 const BasicBlock *BB = I;
958 for (BasicBlock::const_iterator J = BB->begin(), F = BB->end();
959 J != F; ++J)
960 if (ImmutableCallSite JCS = ImmutableCallSite(J))
Dan Gohman2f77bbd2012-01-18 21:24:45 +0000961 // This recursion depth limit is arbitrary. It's just great
962 // enough to cover known interesting testcases.
963 if (Depth < 3 &&
964 !JCS.onlyReadsMemory() &&
965 MayAutorelease(JCS, Depth + 1))
Dan Gohman2f6263c2012-01-17 20:52:24 +0000966 return true;
967 }
968 return false;
969 }
970
971 return true;
972}
973
974bool ObjCARCAPElim::OptimizeBB(BasicBlock *BB) {
975 bool Changed = false;
976
977 Instruction *Push = 0;
978 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
979 Instruction *Inst = I++;
980 switch (GetBasicInstructionClass(Inst)) {
981 case IC_AutoreleasepoolPush:
982 Push = Inst;
983 break;
984 case IC_AutoreleasepoolPop:
985 // If this pop matches a push and nothing in between can autorelease,
986 // zap the pair.
987 if (Push && cast<CallInst>(Inst)->getArgOperand(0) == Push) {
988 Changed = true;
989 Inst->eraseFromParent();
990 Push->eraseFromParent();
991 }
992 Push = 0;
993 break;
994 case IC_CallOrUser:
Dan Gohman447989c2012-04-27 18:56:31 +0000995 if (MayAutorelease(ImmutableCallSite(Inst)))
Dan Gohman2f6263c2012-01-17 20:52:24 +0000996 Push = 0;
997 break;
998 default:
999 break;
1000 }
1001 }
1002
1003 return Changed;
1004}
1005
1006bool ObjCARCAPElim::runOnModule(Module &M) {
1007 if (!EnableARCOpts)
1008 return false;
1009
1010 // If nothing in the Module uses ARC, don't do anything.
1011 if (!ModuleHasARC(M))
1012 return false;
1013
Dan Gohman1dae3e92012-01-18 21:19:38 +00001014 // Find the llvm.global_ctors variable, as the first step in
Dan Gohmand6bf2012012-04-13 18:57:48 +00001015 // identifying the global constructors. In theory, unnecessary autorelease
1016 // pools could occur anywhere, but in practice it's pretty rare. Global
1017 // ctors are a place where autorelease pools get inserted automatically,
1018 // so it's pretty common for them to be unnecessary, and it's pretty
1019 // profitable to eliminate them.
Dan Gohman1dae3e92012-01-18 21:19:38 +00001020 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1021 if (!GV)
1022 return false;
1023
1024 assert(GV->hasDefinitiveInitializer() &&
1025 "llvm.global_ctors is uncooperative!");
1026
Dan Gohman2f6263c2012-01-17 20:52:24 +00001027 bool Changed = false;
1028
Dan Gohman1dae3e92012-01-18 21:19:38 +00001029 // Dig the constructor functions out of GV's initializer.
1030 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
1031 for (User::op_iterator OI = Init->op_begin(), OE = Init->op_end();
1032 OI != OE; ++OI) {
1033 Value *Op = *OI;
1034 // llvm.global_ctors is an array of pairs where the second members
1035 // are constructor functions.
Dan Gohman3b5b2a22012-04-18 22:24:33 +00001036 Function *F = dyn_cast<Function>(cast<ConstantStruct>(Op)->getOperand(1));
1037 // If the user used a constructor function with the wrong signature and
1038 // it got bitcasted or whatever, look the other way.
1039 if (!F)
1040 continue;
Dan Gohman2f6263c2012-01-17 20:52:24 +00001041 // Only look at function definitions.
1042 if (F->isDeclaration())
1043 continue;
Dan Gohman2f6263c2012-01-17 20:52:24 +00001044 // Only look at functions with one basic block.
1045 if (llvm::next(F->begin()) != F->end())
1046 continue;
1047 // Ok, a single-block constructor function definition. Try to optimize it.
1048 Changed |= OptimizeBB(F->begin());
1049 }
1050
1051 return Changed;
1052}
1053
1054//===----------------------------------------------------------------------===//
John McCall9fbd3182011-06-15 23:37:01 +00001055// ARC optimization.
1056//===----------------------------------------------------------------------===//
1057
1058// TODO: On code like this:
1059//
1060// objc_retain(%x)
1061// stuff_that_cannot_release()
1062// objc_autorelease(%x)
1063// stuff_that_cannot_release()
1064// objc_retain(%x)
1065// stuff_that_cannot_release()
1066// objc_autorelease(%x)
1067//
1068// The second retain and autorelease can be deleted.
1069
1070// TODO: It should be possible to delete
1071// objc_autoreleasePoolPush and objc_autoreleasePoolPop
1072// pairs if nothing is actually autoreleased between them. Also, autorelease
1073// calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
1074// after inlining) can be turned into plain release calls.
1075
1076// TODO: Critical-edge splitting. If the optimial insertion point is
1077// a critical edge, the current algorithm has to fail, because it doesn't
1078// know how to split edges. It should be possible to make the optimizer
1079// think in terms of edges, rather than blocks, and then split critical
1080// edges on demand.
1081
1082// TODO: OptimizeSequences could generalized to be Interprocedural.
1083
1084// TODO: Recognize that a bunch of other objc runtime calls have
1085// non-escaping arguments and non-releasing arguments, and may be
1086// non-autoreleasing.
1087
1088// TODO: Sink autorelease calls as far as possible. Unfortunately we
1089// usually can't sink them past other calls, which would be the main
1090// case where it would be useful.
1091
Dan Gohmane6d5e882011-08-19 00:26:36 +00001092// TODO: The pointer returned from objc_loadWeakRetained is retained.
1093
1094// TODO: Delete release+retain pairs (rare).
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00001095
John McCall9fbd3182011-06-15 23:37:01 +00001096#include "llvm/LLVMContext.h"
John McCall9fbd3182011-06-15 23:37:01 +00001097#include "llvm/Support/CFG.h"
John McCall9fbd3182011-06-15 23:37:01 +00001098#include "llvm/ADT/Statistic.h"
Dan Gohman59a1c932011-12-12 19:42:25 +00001099#include "llvm/ADT/SmallPtrSet.h"
John McCall9fbd3182011-06-15 23:37:01 +00001100
1101STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
1102STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
1103STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
1104STATISTIC(NumRets, "Number of return value forwarding "
1105 "retain+autoreleaes eliminated");
1106STATISTIC(NumRRs, "Number of retain+release paths eliminated");
1107STATISTIC(NumPeeps, "Number of calls peephole-optimized");
1108
1109namespace {
1110 /// ProvenanceAnalysis - This is similar to BasicAliasAnalysis, and it
1111 /// uses many of the same techniques, except it uses special ObjC-specific
1112 /// reasoning about pointer relationships.
1113 class ProvenanceAnalysis {
1114 AliasAnalysis *AA;
1115
1116 typedef std::pair<const Value *, const Value *> ValuePairTy;
1117 typedef DenseMap<ValuePairTy, bool> CachedResultsTy;
1118 CachedResultsTy CachedResults;
1119
1120 bool relatedCheck(const Value *A, const Value *B);
1121 bool relatedSelect(const SelectInst *A, const Value *B);
1122 bool relatedPHI(const PHINode *A, const Value *B);
1123
Craig Topperc2945e42012-09-18 02:01:41 +00001124 void operator=(const ProvenanceAnalysis &) LLVM_DELETED_FUNCTION;
1125 ProvenanceAnalysis(const ProvenanceAnalysis &) LLVM_DELETED_FUNCTION;
John McCall9fbd3182011-06-15 23:37:01 +00001126
1127 public:
1128 ProvenanceAnalysis() {}
1129
1130 void setAA(AliasAnalysis *aa) { AA = aa; }
1131
1132 AliasAnalysis *getAA() const { return AA; }
1133
1134 bool related(const Value *A, const Value *B);
1135
1136 void clear() {
1137 CachedResults.clear();
1138 }
1139 };
1140}
1141
1142bool ProvenanceAnalysis::relatedSelect(const SelectInst *A, const Value *B) {
1143 // If the values are Selects with the same condition, we can do a more precise
1144 // check: just check for relations between the values on corresponding arms.
1145 if (const SelectInst *SB = dyn_cast<SelectInst>(B))
Dan Gohman447989c2012-04-27 18:56:31 +00001146 if (A->getCondition() == SB->getCondition())
1147 return related(A->getTrueValue(), SB->getTrueValue()) ||
1148 related(A->getFalseValue(), SB->getFalseValue());
John McCall9fbd3182011-06-15 23:37:01 +00001149
1150 // Check both arms of the Select node individually.
Dan Gohman447989c2012-04-27 18:56:31 +00001151 return related(A->getTrueValue(), B) ||
1152 related(A->getFalseValue(), B);
John McCall9fbd3182011-06-15 23:37:01 +00001153}
1154
1155bool ProvenanceAnalysis::relatedPHI(const PHINode *A, const Value *B) {
1156 // If the values are PHIs in the same block, we can do a more precise as well
1157 // as efficient check: just check for relations between the values on
1158 // corresponding edges.
1159 if (const PHINode *PNB = dyn_cast<PHINode>(B))
1160 if (PNB->getParent() == A->getParent()) {
1161 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i)
1162 if (related(A->getIncomingValue(i),
1163 PNB->getIncomingValueForBlock(A->getIncomingBlock(i))))
1164 return true;
1165 return false;
1166 }
1167
1168 // Check each unique source of the PHI node against B.
1169 SmallPtrSet<const Value *, 4> UniqueSrc;
1170 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i) {
1171 const Value *PV1 = A->getIncomingValue(i);
1172 if (UniqueSrc.insert(PV1) && related(PV1, B))
1173 return true;
1174 }
1175
1176 // All of the arms checked out.
1177 return false;
1178}
1179
1180/// isStoredObjCPointer - Test if the value of P, or any value covered by its
1181/// provenance, is ever stored within the function (not counting callees).
1182static bool isStoredObjCPointer(const Value *P) {
1183 SmallPtrSet<const Value *, 8> Visited;
1184 SmallVector<const Value *, 8> Worklist;
1185 Worklist.push_back(P);
1186 Visited.insert(P);
1187 do {
1188 P = Worklist.pop_back_val();
1189 for (Value::const_use_iterator UI = P->use_begin(), UE = P->use_end();
1190 UI != UE; ++UI) {
1191 const User *Ur = *UI;
1192 if (isa<StoreInst>(Ur)) {
1193 if (UI.getOperandNo() == 0)
1194 // The pointer is stored.
1195 return true;
1196 // The pointed is stored through.
1197 continue;
1198 }
1199 if (isa<CallInst>(Ur))
1200 // The pointer is passed as an argument, ignore this.
1201 continue;
1202 if (isa<PtrToIntInst>(P))
1203 // Assume the worst.
1204 return true;
1205 if (Visited.insert(Ur))
1206 Worklist.push_back(Ur);
1207 }
1208 } while (!Worklist.empty());
1209
1210 // Everything checked out.
1211 return false;
1212}
1213
1214bool ProvenanceAnalysis::relatedCheck(const Value *A, const Value *B) {
1215 // Skip past provenance pass-throughs.
1216 A = GetUnderlyingObjCPtr(A);
1217 B = GetUnderlyingObjCPtr(B);
1218
1219 // Quick check.
1220 if (A == B)
1221 return true;
1222
1223 // Ask regular AliasAnalysis, for a first approximation.
1224 switch (AA->alias(A, B)) {
1225 case AliasAnalysis::NoAlias:
1226 return false;
1227 case AliasAnalysis::MustAlias:
1228 case AliasAnalysis::PartialAlias:
1229 return true;
1230 case AliasAnalysis::MayAlias:
1231 break;
1232 }
1233
1234 bool AIsIdentified = IsObjCIdentifiedObject(A);
1235 bool BIsIdentified = IsObjCIdentifiedObject(B);
1236
1237 // An ObjC-Identified object can't alias a load if it is never locally stored.
1238 if (AIsIdentified) {
Dan Gohman230768b2012-09-04 23:16:20 +00001239 // Check for an obvious escape.
1240 if (isa<LoadInst>(B))
1241 return isStoredObjCPointer(A);
John McCall9fbd3182011-06-15 23:37:01 +00001242 if (BIsIdentified) {
Dan Gohman230768b2012-09-04 23:16:20 +00001243 // Check for an obvious escape.
1244 if (isa<LoadInst>(A))
1245 return isStoredObjCPointer(B);
1246 // Both pointers are identified and escapes aren't an evident problem.
1247 return false;
John McCall9fbd3182011-06-15 23:37:01 +00001248 }
Dan Gohman230768b2012-09-04 23:16:20 +00001249 } else if (BIsIdentified) {
1250 // Check for an obvious escape.
1251 if (isa<LoadInst>(A))
John McCall9fbd3182011-06-15 23:37:01 +00001252 return isStoredObjCPointer(B);
1253 }
1254
1255 // Special handling for PHI and Select.
1256 if (const PHINode *PN = dyn_cast<PHINode>(A))
1257 return relatedPHI(PN, B);
1258 if (const PHINode *PN = dyn_cast<PHINode>(B))
1259 return relatedPHI(PN, A);
1260 if (const SelectInst *S = dyn_cast<SelectInst>(A))
1261 return relatedSelect(S, B);
1262 if (const SelectInst *S = dyn_cast<SelectInst>(B))
1263 return relatedSelect(S, A);
1264
1265 // Conservative.
1266 return true;
1267}
1268
1269bool ProvenanceAnalysis::related(const Value *A, const Value *B) {
1270 // Begin by inserting a conservative value into the map. If the insertion
1271 // fails, we have the answer already. If it succeeds, leave it there until we
1272 // compute the real answer to guard against recursive queries.
1273 if (A > B) std::swap(A, B);
1274 std::pair<CachedResultsTy::iterator, bool> Pair =
1275 CachedResults.insert(std::make_pair(ValuePairTy(A, B), true));
1276 if (!Pair.second)
1277 return Pair.first->second;
1278
1279 bool Result = relatedCheck(A, B);
1280 CachedResults[ValuePairTy(A, B)] = Result;
1281 return Result;
1282}
1283
1284namespace {
1285 // Sequence - A sequence of states that a pointer may go through in which an
1286 // objc_retain and objc_release are actually needed.
1287 enum Sequence {
1288 S_None,
1289 S_Retain, ///< objc_retain(x)
1290 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement
1291 S_Use, ///< any use of x
1292 S_Stop, ///< like S_Release, but code motion is stopped
1293 S_Release, ///< objc_release(x)
1294 S_MovableRelease ///< objc_release(x), !clang.imprecise_release
1295 };
1296}
1297
1298static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
1299 // The easy cases.
1300 if (A == B)
1301 return A;
1302 if (A == S_None || B == S_None)
1303 return S_None;
1304
John McCall9fbd3182011-06-15 23:37:01 +00001305 if (A > B) std::swap(A, B);
1306 if (TopDown) {
1307 // Choose the side which is further along in the sequence.
Dan Gohmana7f7db22011-08-12 00:26:31 +00001308 if ((A == S_Retain || A == S_CanRelease) &&
1309 (B == S_CanRelease || B == S_Use))
John McCall9fbd3182011-06-15 23:37:01 +00001310 return B;
1311 } else {
1312 // Choose the side which is further along in the sequence.
1313 if ((A == S_Use || A == S_CanRelease) &&
Dan Gohmana7f7db22011-08-12 00:26:31 +00001314 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
John McCall9fbd3182011-06-15 23:37:01 +00001315 return A;
1316 // If both sides are releases, choose the more conservative one.
1317 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
1318 return A;
1319 if (A == S_Release && B == S_MovableRelease)
1320 return A;
1321 }
1322
1323 return S_None;
1324}
1325
1326namespace {
1327 /// RRInfo - Unidirectional information about either a
1328 /// retain-decrement-use-release sequence or release-use-decrement-retain
1329 /// reverese sequence.
1330 struct RRInfo {
Dan Gohmane6d5e882011-08-19 00:26:36 +00001331 /// KnownSafe - After an objc_retain, the reference count of the referenced
1332 /// object is known to be positive. Similarly, before an objc_release, the
1333 /// reference count of the referenced object is known to be positive. If
1334 /// there are retain-release pairs in code regions where the retain count
1335 /// is known to be positive, they can be eliminated, regardless of any side
1336 /// effects between them.
1337 ///
1338 /// Also, a retain+release pair nested within another retain+release
1339 /// pair all on the known same pointer value can be eliminated, regardless
1340 /// of any intervening side effects.
1341 ///
1342 /// KnownSafe is true when either of these conditions is satisfied.
1343 bool KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00001344
1345 /// IsRetainBlock - True if the Calls are objc_retainBlock calls (as
1346 /// opposed to objc_retain calls).
1347 bool IsRetainBlock;
1348
1349 /// IsTailCallRelease - True of the objc_release calls are all marked
1350 /// with the "tail" keyword.
1351 bool IsTailCallRelease;
1352
1353 /// ReleaseMetadata - If the Calls are objc_release calls and they all have
1354 /// a clang.imprecise_release tag, this is the metadata tag.
1355 MDNode *ReleaseMetadata;
1356
1357 /// Calls - For a top-down sequence, the set of objc_retains or
1358 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
1359 SmallPtrSet<Instruction *, 2> Calls;
1360
1361 /// ReverseInsertPts - The set of optimal insert positions for
1362 /// moving calls in the opposite sequence.
1363 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
1364
1365 RRInfo() :
Dan Gohman79522dc2012-01-13 00:39:07 +00001366 KnownSafe(false), IsRetainBlock(false),
Dan Gohman50ade652012-04-25 00:50:46 +00001367 IsTailCallRelease(false),
John McCall9fbd3182011-06-15 23:37:01 +00001368 ReleaseMetadata(0) {}
1369
1370 void clear();
1371 };
1372}
1373
1374void RRInfo::clear() {
Dan Gohmane6d5e882011-08-19 00:26:36 +00001375 KnownSafe = false;
John McCall9fbd3182011-06-15 23:37:01 +00001376 IsRetainBlock = false;
1377 IsTailCallRelease = false;
1378 ReleaseMetadata = 0;
1379 Calls.clear();
1380 ReverseInsertPts.clear();
1381}
1382
1383namespace {
1384 /// PtrState - This class summarizes several per-pointer runtime properties
1385 /// which are propogated through the flow graph.
1386 class PtrState {
Dan Gohman50ade652012-04-25 00:50:46 +00001387 /// KnownPositiveRefCount - True if the reference count is known to
1388 /// be incremented.
1389 bool KnownPositiveRefCount;
1390
1391 /// Partial - True of we've seen an opportunity for partial RR elimination,
1392 /// such as pushing calls into a CFG triangle or into one side of a
1393 /// CFG diamond.
1394 bool Partial;
John McCall9fbd3182011-06-15 23:37:01 +00001395
1396 /// Seq - The current position in the sequence.
Dan Gohman0daef3d2012-05-08 23:39:44 +00001397 Sequence Seq : 8;
John McCall9fbd3182011-06-15 23:37:01 +00001398
1399 public:
1400 /// RRI - Unidirectional information about the current sequence.
1401 /// TODO: Encapsulate this better.
1402 RRInfo RRI;
1403
Dan Gohman230768b2012-09-04 23:16:20 +00001404 PtrState() : KnownPositiveRefCount(false), Partial(false),
Dan Gohman0daef3d2012-05-08 23:39:44 +00001405 Seq(S_None) {}
John McCall9fbd3182011-06-15 23:37:01 +00001406
Dan Gohman50ade652012-04-25 00:50:46 +00001407 void SetKnownPositiveRefCount() {
1408 KnownPositiveRefCount = true;
Dan Gohmana7f7db22011-08-12 00:26:31 +00001409 }
1410
Dan Gohman50ade652012-04-25 00:50:46 +00001411 void ClearRefCount() {
1412 KnownPositiveRefCount = false;
John McCall9fbd3182011-06-15 23:37:01 +00001413 }
1414
John McCall9fbd3182011-06-15 23:37:01 +00001415 bool IsKnownIncremented() const {
Dan Gohman50ade652012-04-25 00:50:46 +00001416 return KnownPositiveRefCount;
John McCall9fbd3182011-06-15 23:37:01 +00001417 }
1418
1419 void SetSeq(Sequence NewSeq) {
1420 Seq = NewSeq;
1421 }
1422
John McCall9fbd3182011-06-15 23:37:01 +00001423 Sequence GetSeq() const {
1424 return Seq;
1425 }
1426
1427 void ClearSequenceProgress() {
Dan Gohman50ade652012-04-25 00:50:46 +00001428 ResetSequenceProgress(S_None);
1429 }
1430
1431 void ResetSequenceProgress(Sequence NewSeq) {
1432 Seq = NewSeq;
1433 Partial = false;
John McCall9fbd3182011-06-15 23:37:01 +00001434 RRI.clear();
1435 }
1436
1437 void Merge(const PtrState &Other, bool TopDown);
1438 };
1439}
1440
1441void
1442PtrState::Merge(const PtrState &Other, bool TopDown) {
1443 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
Dan Gohman50ade652012-04-25 00:50:46 +00001444 KnownPositiveRefCount = KnownPositiveRefCount && Other.KnownPositiveRefCount;
John McCall9fbd3182011-06-15 23:37:01 +00001445
1446 // We can't merge a plain objc_retain with an objc_retainBlock.
1447 if (RRI.IsRetainBlock != Other.RRI.IsRetainBlock)
1448 Seq = S_None;
1449
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001450 // If we're not in a sequence (anymore), drop all associated state.
John McCall9fbd3182011-06-15 23:37:01 +00001451 if (Seq == S_None) {
Dan Gohman50ade652012-04-25 00:50:46 +00001452 Partial = false;
John McCall9fbd3182011-06-15 23:37:01 +00001453 RRI.clear();
Dan Gohman50ade652012-04-25 00:50:46 +00001454 } else if (Partial || Other.Partial) {
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001455 // If we're doing a merge on a path that's previously seen a partial
1456 // merge, conservatively drop the sequence, to avoid doing partial
1457 // RR elimination. If the branch predicates for the two merge differ,
1458 // mixing them is unsafe.
Dan Gohman50ade652012-04-25 00:50:46 +00001459 ClearSequenceProgress();
John McCall9fbd3182011-06-15 23:37:01 +00001460 } else {
1461 // Conservatively merge the ReleaseMetadata information.
1462 if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
1463 RRI.ReleaseMetadata = 0;
1464
Dan Gohmane6d5e882011-08-19 00:26:36 +00001465 RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
Dan Gohman0daef3d2012-05-08 23:39:44 +00001466 RRI.IsTailCallRelease = RRI.IsTailCallRelease &&
1467 Other.RRI.IsTailCallRelease;
John McCall9fbd3182011-06-15 23:37:01 +00001468 RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001469
1470 // Merge the insert point sets. If there are any differences,
1471 // that makes this a partial merge.
Dan Gohman0daef3d2012-05-08 23:39:44 +00001472 Partial = RRI.ReverseInsertPts.size() != Other.RRI.ReverseInsertPts.size();
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001473 for (SmallPtrSet<Instruction *, 2>::const_iterator
1474 I = Other.RRI.ReverseInsertPts.begin(),
1475 E = Other.RRI.ReverseInsertPts.end(); I != E; ++I)
Dan Gohman50ade652012-04-25 00:50:46 +00001476 Partial |= RRI.ReverseInsertPts.insert(*I);
John McCall9fbd3182011-06-15 23:37:01 +00001477 }
1478}
1479
1480namespace {
1481 /// BBState - Per-BasicBlock state.
1482 class BBState {
1483 /// TopDownPathCount - The number of unique control paths from the entry
1484 /// which can reach this block.
1485 unsigned TopDownPathCount;
1486
1487 /// BottomUpPathCount - The number of unique control paths to exits
1488 /// from this block.
1489 unsigned BottomUpPathCount;
1490
1491 /// MapTy - A type for PerPtrTopDown and PerPtrBottomUp.
1492 typedef MapVector<const Value *, PtrState> MapTy;
1493
1494 /// PerPtrTopDown - The top-down traversal uses this to record information
1495 /// known about a pointer at the bottom of each block.
1496 MapTy PerPtrTopDown;
1497
1498 /// PerPtrBottomUp - The bottom-up traversal uses this to record information
1499 /// known about a pointer at the top of each block.
1500 MapTy PerPtrBottomUp;
1501
Dan Gohmaneeeb7752012-04-24 22:53:18 +00001502 /// Preds, Succs - Effective successors and predecessors of the current
1503 /// block (this ignores ignorable edges and ignored backedges).
1504 SmallVector<BasicBlock *, 2> Preds;
1505 SmallVector<BasicBlock *, 2> Succs;
1506
John McCall9fbd3182011-06-15 23:37:01 +00001507 public:
1508 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
1509
1510 typedef MapTy::iterator ptr_iterator;
1511 typedef MapTy::const_iterator ptr_const_iterator;
1512
1513 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
1514 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
1515 ptr_const_iterator top_down_ptr_begin() const {
1516 return PerPtrTopDown.begin();
1517 }
1518 ptr_const_iterator top_down_ptr_end() const {
1519 return PerPtrTopDown.end();
1520 }
1521
1522 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
1523 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
1524 ptr_const_iterator bottom_up_ptr_begin() const {
1525 return PerPtrBottomUp.begin();
1526 }
1527 ptr_const_iterator bottom_up_ptr_end() const {
1528 return PerPtrBottomUp.end();
1529 }
1530
1531 /// SetAsEntry - Mark this block as being an entry block, which has one
1532 /// path from the entry by definition.
1533 void SetAsEntry() { TopDownPathCount = 1; }
1534
1535 /// SetAsExit - Mark this block as being an exit block, which has one
1536 /// path to an exit by definition.
1537 void SetAsExit() { BottomUpPathCount = 1; }
1538
1539 PtrState &getPtrTopDownState(const Value *Arg) {
1540 return PerPtrTopDown[Arg];
1541 }
1542
1543 PtrState &getPtrBottomUpState(const Value *Arg) {
1544 return PerPtrBottomUp[Arg];
1545 }
1546
1547 void clearBottomUpPointers() {
Evan Chenga81388f2011-08-04 18:40:26 +00001548 PerPtrBottomUp.clear();
John McCall9fbd3182011-06-15 23:37:01 +00001549 }
1550
1551 void clearTopDownPointers() {
1552 PerPtrTopDown.clear();
1553 }
1554
1555 void InitFromPred(const BBState &Other);
1556 void InitFromSucc(const BBState &Other);
1557 void MergePred(const BBState &Other);
1558 void MergeSucc(const BBState &Other);
1559
1560 /// GetAllPathCount - Return the number of possible unique paths from an
1561 /// entry to an exit which pass through this block. This is only valid
1562 /// after both the top-down and bottom-up traversals are complete.
1563 unsigned GetAllPathCount() const {
Dan Gohmaneeeb7752012-04-24 22:53:18 +00001564 assert(TopDownPathCount != 0);
1565 assert(BottomUpPathCount != 0);
John McCall9fbd3182011-06-15 23:37:01 +00001566 return TopDownPathCount * BottomUpPathCount;
1567 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00001568
Dan Gohmaneeeb7752012-04-24 22:53:18 +00001569 // Specialized CFG utilities.
Dan Gohman447989c2012-04-27 18:56:31 +00001570 typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
Dan Gohmaneeeb7752012-04-24 22:53:18 +00001571 edge_iterator pred_begin() { return Preds.begin(); }
1572 edge_iterator pred_end() { return Preds.end(); }
1573 edge_iterator succ_begin() { return Succs.begin(); }
1574 edge_iterator succ_end() { return Succs.end(); }
1575
1576 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
1577 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
1578
1579 bool isExit() const { return Succs.empty(); }
John McCall9fbd3182011-06-15 23:37:01 +00001580 };
1581}
1582
1583void BBState::InitFromPred(const BBState &Other) {
1584 PerPtrTopDown = Other.PerPtrTopDown;
1585 TopDownPathCount = Other.TopDownPathCount;
1586}
1587
1588void BBState::InitFromSucc(const BBState &Other) {
1589 PerPtrBottomUp = Other.PerPtrBottomUp;
1590 BottomUpPathCount = Other.BottomUpPathCount;
1591}
1592
1593/// MergePred - The top-down traversal uses this to merge information about
1594/// predecessors to form the initial state for a new block.
1595void BBState::MergePred(const BBState &Other) {
1596 // Other.TopDownPathCount can be 0, in which case it is either dead or a
1597 // loop backedge. Loop backedges are special.
1598 TopDownPathCount += Other.TopDownPathCount;
1599
Dan Gohman0d1bc5f2012-09-12 20:45:17 +00001600 // Check for overflow. If we have overflow, fall back to conservative behavior.
1601 if (TopDownPathCount < Other.TopDownPathCount) {
1602 clearTopDownPointers();
1603 return;
1604 }
1605
John McCall9fbd3182011-06-15 23:37:01 +00001606 // For each entry in the other set, if our set has an entry with the same key,
1607 // merge the entries. Otherwise, copy the entry and merge it with an empty
1608 // entry.
1609 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
1610 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
1611 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
1612 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1613 /*TopDown=*/true);
1614 }
1615
Dan Gohmanfa7eed12011-08-11 21:06:32 +00001616 // For each entry in our set, if the other set doesn't have an entry with the
John McCall9fbd3182011-06-15 23:37:01 +00001617 // same key, force it to merge with an empty entry.
1618 for (ptr_iterator MI = top_down_ptr_begin(),
1619 ME = top_down_ptr_end(); MI != ME; ++MI)
1620 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
1621 MI->second.Merge(PtrState(), /*TopDown=*/true);
1622}
1623
1624/// MergeSucc - The bottom-up traversal uses this to merge information about
1625/// successors to form the initial state for a new block.
1626void BBState::MergeSucc(const BBState &Other) {
1627 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
1628 // loop backedge. Loop backedges are special.
1629 BottomUpPathCount += Other.BottomUpPathCount;
1630
Dan Gohman0d1bc5f2012-09-12 20:45:17 +00001631 // Check for overflow. If we have overflow, fall back to conservative behavior.
1632 if (BottomUpPathCount < Other.BottomUpPathCount) {
1633 clearBottomUpPointers();
1634 return;
1635 }
1636
John McCall9fbd3182011-06-15 23:37:01 +00001637 // For each entry in the other set, if our set has an entry with the
1638 // same key, merge the entries. Otherwise, copy the entry and merge
1639 // it with an empty entry.
1640 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
1641 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
1642 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
1643 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1644 /*TopDown=*/false);
1645 }
1646
Dan Gohmanfa7eed12011-08-11 21:06:32 +00001647 // For each entry in our set, if the other set doesn't have an entry
John McCall9fbd3182011-06-15 23:37:01 +00001648 // with the same key, force it to merge with an empty entry.
1649 for (ptr_iterator MI = bottom_up_ptr_begin(),
1650 ME = bottom_up_ptr_end(); MI != ME; ++MI)
1651 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
1652 MI->second.Merge(PtrState(), /*TopDown=*/false);
1653}
1654
1655namespace {
1656 /// ObjCARCOpt - The main ARC optimization pass.
1657 class ObjCARCOpt : public FunctionPass {
1658 bool Changed;
1659 ProvenanceAnalysis PA;
1660
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00001661 /// Run - A flag indicating whether this optimization pass should run.
1662 bool Run;
1663
John McCall9fbd3182011-06-15 23:37:01 +00001664 /// RetainRVCallee, etc. - Declarations for ObjC runtime
1665 /// functions, for use in creating calls to them. These are initialized
1666 /// lazily to avoid cluttering up the Module with unused declarations.
1667 Constant *RetainRVCallee, *AutoreleaseRVCallee, *ReleaseCallee,
Dan Gohman44280692011-07-22 22:29:21 +00001668 *RetainCallee, *RetainBlockCallee, *AutoreleaseCallee;
John McCall9fbd3182011-06-15 23:37:01 +00001669
1670 /// UsedInThisFunciton - Flags which determine whether each of the
1671 /// interesting runtine functions is in fact used in the current function.
1672 unsigned UsedInThisFunction;
1673
1674 /// ImpreciseReleaseMDKind - The Metadata Kind for clang.imprecise_release
1675 /// metadata.
1676 unsigned ImpreciseReleaseMDKind;
1677
Dan Gohman62e5b402011-12-12 18:20:00 +00001678 /// CopyOnEscapeMDKind - The Metadata Kind for clang.arc.copy_on_escape
Dan Gohmana974bea2011-10-17 22:53:25 +00001679 /// metadata.
1680 unsigned CopyOnEscapeMDKind;
1681
Dan Gohmandbe266b2012-02-17 18:59:53 +00001682 /// NoObjCARCExceptionsMDKind - The Metadata Kind for
1683 /// clang.arc.no_objc_arc_exceptions metadata.
1684 unsigned NoObjCARCExceptionsMDKind;
1685
John McCall9fbd3182011-06-15 23:37:01 +00001686 Constant *getRetainRVCallee(Module *M);
1687 Constant *getAutoreleaseRVCallee(Module *M);
1688 Constant *getReleaseCallee(Module *M);
1689 Constant *getRetainCallee(Module *M);
Dan Gohman44280692011-07-22 22:29:21 +00001690 Constant *getRetainBlockCallee(Module *M);
John McCall9fbd3182011-06-15 23:37:01 +00001691 Constant *getAutoreleaseCallee(Module *M);
1692
Dan Gohman79522dc2012-01-13 00:39:07 +00001693 bool IsRetainBlockOptimizable(const Instruction *Inst);
1694
John McCall9fbd3182011-06-15 23:37:01 +00001695 void OptimizeRetainCall(Function &F, Instruction *Retain);
1696 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
1697 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV);
1698 void OptimizeIndividualCalls(Function &F);
1699
1700 void CheckForCFGHazards(const BasicBlock *BB,
1701 DenseMap<const BasicBlock *, BBState> &BBStates,
1702 BBState &MyStates) const;
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00001703 bool VisitInstructionBottomUp(Instruction *Inst,
Dan Gohmanfbab4a82012-03-23 17:47:54 +00001704 BasicBlock *BB,
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00001705 MapVector<Value *, RRInfo> &Retains,
1706 BBState &MyStates);
John McCall9fbd3182011-06-15 23:37:01 +00001707 bool VisitBottomUp(BasicBlock *BB,
1708 DenseMap<const BasicBlock *, BBState> &BBStates,
1709 MapVector<Value *, RRInfo> &Retains);
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00001710 bool VisitInstructionTopDown(Instruction *Inst,
1711 DenseMap<Value *, RRInfo> &Releases,
1712 BBState &MyStates);
John McCall9fbd3182011-06-15 23:37:01 +00001713 bool VisitTopDown(BasicBlock *BB,
1714 DenseMap<const BasicBlock *, BBState> &BBStates,
1715 DenseMap<Value *, RRInfo> &Releases);
1716 bool Visit(Function &F,
1717 DenseMap<const BasicBlock *, BBState> &BBStates,
1718 MapVector<Value *, RRInfo> &Retains,
1719 DenseMap<Value *, RRInfo> &Releases);
1720
1721 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1722 MapVector<Value *, RRInfo> &Retains,
1723 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman44280692011-07-22 22:29:21 +00001724 SmallVectorImpl<Instruction *> &DeadInsts,
1725 Module *M);
John McCall9fbd3182011-06-15 23:37:01 +00001726
1727 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1728 MapVector<Value *, RRInfo> &Retains,
Dan Gohman44280692011-07-22 22:29:21 +00001729 DenseMap<Value *, RRInfo> &Releases,
1730 Module *M);
John McCall9fbd3182011-06-15 23:37:01 +00001731
1732 void OptimizeWeakCalls(Function &F);
1733
1734 bool OptimizeSequences(Function &F);
1735
1736 void OptimizeReturns(Function &F);
1737
1738 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1739 virtual bool doInitialization(Module &M);
1740 virtual bool runOnFunction(Function &F);
1741 virtual void releaseMemory();
1742
1743 public:
1744 static char ID;
1745 ObjCARCOpt() : FunctionPass(ID) {
1746 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1747 }
1748 };
1749}
1750
1751char ObjCARCOpt::ID = 0;
1752INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1753 "objc-arc", "ObjC ARC optimization", false, false)
1754INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1755INITIALIZE_PASS_END(ObjCARCOpt,
1756 "objc-arc", "ObjC ARC optimization", false, false)
1757
1758Pass *llvm::createObjCARCOptPass() {
1759 return new ObjCARCOpt();
1760}
1761
1762void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1763 AU.addRequired<ObjCARCAliasAnalysis>();
1764 AU.addRequired<AliasAnalysis>();
1765 // ARC optimization doesn't currently split critical edges.
1766 AU.setPreservesCFG();
1767}
1768
Dan Gohman79522dc2012-01-13 00:39:07 +00001769bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1770 // Without the magic metadata tag, we have to assume this might be an
1771 // objc_retainBlock call inserted to convert a block pointer to an id,
1772 // in which case it really is needed.
1773 if (!Inst->getMetadata(CopyOnEscapeMDKind))
1774 return false;
1775
1776 // If the pointer "escapes" (not including being used in a call),
1777 // the copy may be needed.
1778 if (DoesObjCBlockEscape(Inst))
1779 return false;
1780
1781 // Otherwise, it's not needed.
1782 return true;
1783}
1784
John McCall9fbd3182011-06-15 23:37:01 +00001785Constant *ObjCARCOpt::getRetainRVCallee(Module *M) {
1786 if (!RetainRVCallee) {
1787 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001788 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman0daef3d2012-05-08 23:39:44 +00001789 Type *Params[] = { I8X };
1790 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendlingc40abb02012-10-09 00:47:36 +00001791 Attributes::Builder B;
Bill Wendling2e879bc2012-10-09 09:11:20 +00001792 B.addAttribute(Attributes::NoUnwind);
Bill Wendling07aae2e2012-10-15 07:29:08 +00001793 AttrListPtr Attributes =
1794 AttrListPtr().addAttr(M->getContext(), AttrListPtr::FunctionIndex,
1795 Attributes::get(M->getContext(), B));
John McCall9fbd3182011-06-15 23:37:01 +00001796 RetainRVCallee =
1797 M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy,
1798 Attributes);
1799 }
1800 return RetainRVCallee;
1801}
1802
1803Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1804 if (!AutoreleaseRVCallee) {
1805 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001806 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman0daef3d2012-05-08 23:39:44 +00001807 Type *Params[] = { I8X };
1808 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendlingc40abb02012-10-09 00:47:36 +00001809 Attributes::Builder B;
Bill Wendling2e879bc2012-10-09 09:11:20 +00001810 B.addAttribute(Attributes::NoUnwind);
Bill Wendling07aae2e2012-10-15 07:29:08 +00001811 AttrListPtr Attributes =
1812 AttrListPtr().addAttr(M->getContext(), AttrListPtr::FunctionIndex,
1813 Attributes::get(C, B));
John McCall9fbd3182011-06-15 23:37:01 +00001814 AutoreleaseRVCallee =
1815 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
1816 Attributes);
1817 }
1818 return AutoreleaseRVCallee;
1819}
1820
1821Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1822 if (!ReleaseCallee) {
1823 LLVMContext &C = M->getContext();
Dan Gohman0daef3d2012-05-08 23:39:44 +00001824 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendlingc40abb02012-10-09 00:47:36 +00001825 Attributes::Builder B;
Bill Wendling2e879bc2012-10-09 09:11:20 +00001826 B.addAttribute(Attributes::NoUnwind);
Bill Wendling07aae2e2012-10-15 07:29:08 +00001827 AttrListPtr Attributes =
1828 AttrListPtr().addAttr(M->getContext(), AttrListPtr::FunctionIndex,
1829 Attributes::get(C, B));
John McCall9fbd3182011-06-15 23:37:01 +00001830 ReleaseCallee =
1831 M->getOrInsertFunction(
1832 "objc_release",
1833 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
1834 Attributes);
1835 }
1836 return ReleaseCallee;
1837}
1838
1839Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1840 if (!RetainCallee) {
1841 LLVMContext &C = M->getContext();
Dan Gohman0daef3d2012-05-08 23:39:44 +00001842 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendlingc40abb02012-10-09 00:47:36 +00001843 Attributes::Builder B;
Bill Wendling2e879bc2012-10-09 09:11:20 +00001844 B.addAttribute(Attributes::NoUnwind);
Bill Wendling07aae2e2012-10-15 07:29:08 +00001845 AttrListPtr Attributes =
1846 AttrListPtr().addAttr(M->getContext(), AttrListPtr::FunctionIndex,
1847 Attributes::get(C, B));
John McCall9fbd3182011-06-15 23:37:01 +00001848 RetainCallee =
1849 M->getOrInsertFunction(
1850 "objc_retain",
1851 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1852 Attributes);
1853 }
1854 return RetainCallee;
1855}
1856
Dan Gohman44280692011-07-22 22:29:21 +00001857Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1858 if (!RetainBlockCallee) {
1859 LLVMContext &C = M->getContext();
Dan Gohman0daef3d2012-05-08 23:39:44 +00001860 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Dan Gohman1d2fd752011-09-14 18:33:34 +00001861 // objc_retainBlock is not nounwind because it calls user copy constructors
1862 // which could theoretically throw.
Dan Gohman44280692011-07-22 22:29:21 +00001863 RetainBlockCallee =
1864 M->getOrInsertFunction(
1865 "objc_retainBlock",
1866 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Dan Gohman0daef3d2012-05-08 23:39:44 +00001867 AttrListPtr());
Dan Gohman44280692011-07-22 22:29:21 +00001868 }
1869 return RetainBlockCallee;
1870}
1871
John McCall9fbd3182011-06-15 23:37:01 +00001872Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1873 if (!AutoreleaseCallee) {
1874 LLVMContext &C = M->getContext();
Dan Gohman0daef3d2012-05-08 23:39:44 +00001875 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendlingc40abb02012-10-09 00:47:36 +00001876 Attributes::Builder B;
Bill Wendling2e879bc2012-10-09 09:11:20 +00001877 B.addAttribute(Attributes::NoUnwind);
Bill Wendling07aae2e2012-10-15 07:29:08 +00001878 AttrListPtr Attributes =
1879 AttrListPtr().addAttr(M->getContext(), AttrListPtr::FunctionIndex,
1880 Attributes::get(C, B));
John McCall9fbd3182011-06-15 23:37:01 +00001881 AutoreleaseCallee =
1882 M->getOrInsertFunction(
1883 "objc_autorelease",
1884 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1885 Attributes);
1886 }
1887 return AutoreleaseCallee;
1888}
1889
Dan Gohman230768b2012-09-04 23:16:20 +00001890/// IsPotentialUse - Test whether the given value is possible a
1891/// reference-counted pointer, including tests which utilize AliasAnalysis.
1892static bool IsPotentialUse(const Value *Op, AliasAnalysis &AA) {
1893 // First make the rudimentary check.
1894 if (!IsPotentialUse(Op))
1895 return false;
1896
1897 // Objects in constant memory are not reference-counted.
1898 if (AA.pointsToConstantMemory(Op))
1899 return false;
1900
1901 // Pointers in constant memory are not pointing to reference-counted objects.
1902 if (const LoadInst *LI = dyn_cast<LoadInst>(Op))
1903 if (AA.pointsToConstantMemory(LI->getPointerOperand()))
1904 return false;
1905
1906 // Otherwise assume the worst.
1907 return true;
1908}
1909
John McCall9fbd3182011-06-15 23:37:01 +00001910/// CanAlterRefCount - Test whether the given instruction can result in a
1911/// reference count modification (positive or negative) for the pointer's
1912/// object.
1913static bool
1914CanAlterRefCount(const Instruction *Inst, const Value *Ptr,
1915 ProvenanceAnalysis &PA, InstructionClass Class) {
1916 switch (Class) {
1917 case IC_Autorelease:
1918 case IC_AutoreleaseRV:
1919 case IC_User:
1920 // These operations never directly modify a reference count.
1921 return false;
1922 default: break;
1923 }
1924
1925 ImmutableCallSite CS = static_cast<const Value *>(Inst);
1926 assert(CS && "Only calls can alter reference counts!");
1927
1928 // See if AliasAnalysis can help us with the call.
1929 AliasAnalysis::ModRefBehavior MRB = PA.getAA()->getModRefBehavior(CS);
1930 if (AliasAnalysis::onlyReadsMemory(MRB))
1931 return false;
1932 if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
1933 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1934 I != E; ++I) {
1935 const Value *Op = *I;
Dan Gohman230768b2012-09-04 23:16:20 +00001936 if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
John McCall9fbd3182011-06-15 23:37:01 +00001937 return true;
1938 }
1939 return false;
1940 }
1941
1942 // Assume the worst.
1943 return true;
1944}
1945
1946/// CanUse - Test whether the given instruction can "use" the given pointer's
1947/// object in a way that requires the reference count to be positive.
1948static bool
1949CanUse(const Instruction *Inst, const Value *Ptr, ProvenanceAnalysis &PA,
1950 InstructionClass Class) {
1951 // IC_Call operations (as opposed to IC_CallOrUser) never "use" objc pointers.
1952 if (Class == IC_Call)
1953 return false;
1954
1955 // Consider various instructions which may have pointer arguments which are
1956 // not "uses".
1957 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(Inst)) {
1958 // Comparing a pointer with null, or any other constant, isn't really a use,
1959 // because we don't care what the pointer points to, or about the values
1960 // of any other dynamic reference-counted pointers.
Dan Gohman230768b2012-09-04 23:16:20 +00001961 if (!IsPotentialUse(ICI->getOperand(1), *PA.getAA()))
John McCall9fbd3182011-06-15 23:37:01 +00001962 return false;
1963 } else if (ImmutableCallSite CS = static_cast<const Value *>(Inst)) {
1964 // For calls, just check the arguments (and not the callee operand).
1965 for (ImmutableCallSite::arg_iterator OI = CS.arg_begin(),
1966 OE = CS.arg_end(); OI != OE; ++OI) {
1967 const Value *Op = *OI;
Dan Gohman230768b2012-09-04 23:16:20 +00001968 if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
John McCall9fbd3182011-06-15 23:37:01 +00001969 return true;
1970 }
1971 return false;
1972 } else if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1973 // Special-case stores, because we don't care about the stored value, just
1974 // the store address.
1975 const Value *Op = GetUnderlyingObjCPtr(SI->getPointerOperand());
1976 // If we can't tell what the underlying object was, assume there is a
1977 // dependence.
Dan Gohman230768b2012-09-04 23:16:20 +00001978 return IsPotentialUse(Op, *PA.getAA()) && PA.related(Op, Ptr);
John McCall9fbd3182011-06-15 23:37:01 +00001979 }
1980
1981 // Check each operand for a match.
1982 for (User::const_op_iterator OI = Inst->op_begin(), OE = Inst->op_end();
1983 OI != OE; ++OI) {
1984 const Value *Op = *OI;
Dan Gohman230768b2012-09-04 23:16:20 +00001985 if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
John McCall9fbd3182011-06-15 23:37:01 +00001986 return true;
1987 }
1988 return false;
1989}
1990
1991/// CanInterruptRV - Test whether the given instruction can autorelease
1992/// any pointer or cause an autoreleasepool pop.
1993static bool
1994CanInterruptRV(InstructionClass Class) {
1995 switch (Class) {
1996 case IC_AutoreleasepoolPop:
1997 case IC_CallOrUser:
1998 case IC_Call:
1999 case IC_Autorelease:
2000 case IC_AutoreleaseRV:
2001 case IC_FusedRetainAutorelease:
2002 case IC_FusedRetainAutoreleaseRV:
2003 return true;
2004 default:
2005 return false;
2006 }
2007}
2008
2009namespace {
2010 /// DependenceKind - There are several kinds of dependence-like concepts in
2011 /// use here.
2012 enum DependenceKind {
2013 NeedsPositiveRetainCount,
Dan Gohman511568d2012-04-13 00:59:57 +00002014 AutoreleasePoolBoundary,
John McCall9fbd3182011-06-15 23:37:01 +00002015 CanChangeRetainCount,
2016 RetainAutoreleaseDep, ///< Blocks objc_retainAutorelease.
2017 RetainAutoreleaseRVDep, ///< Blocks objc_retainAutoreleaseReturnValue.
2018 RetainRVDep ///< Blocks objc_retainAutoreleasedReturnValue.
2019 };
2020}
2021
2022/// Depends - Test if there can be dependencies on Inst through Arg. This
2023/// function only tests dependencies relevant for removing pairs of calls.
2024static bool
2025Depends(DependenceKind Flavor, Instruction *Inst, const Value *Arg,
2026 ProvenanceAnalysis &PA) {
2027 // If we've reached the definition of Arg, stop.
2028 if (Inst == Arg)
2029 return true;
2030
2031 switch (Flavor) {
2032 case NeedsPositiveRetainCount: {
2033 InstructionClass Class = GetInstructionClass(Inst);
2034 switch (Class) {
2035 case IC_AutoreleasepoolPop:
2036 case IC_AutoreleasepoolPush:
2037 case IC_None:
2038 return false;
2039 default:
2040 return CanUse(Inst, Arg, PA, Class);
2041 }
2042 }
2043
Dan Gohman511568d2012-04-13 00:59:57 +00002044 case AutoreleasePoolBoundary: {
2045 InstructionClass Class = GetInstructionClass(Inst);
2046 switch (Class) {
2047 case IC_AutoreleasepoolPop:
2048 case IC_AutoreleasepoolPush:
2049 // These mark the end and begin of an autorelease pool scope.
2050 return true;
2051 default:
2052 // Nothing else does this.
2053 return false;
2054 }
2055 }
2056
John McCall9fbd3182011-06-15 23:37:01 +00002057 case CanChangeRetainCount: {
2058 InstructionClass Class = GetInstructionClass(Inst);
2059 switch (Class) {
2060 case IC_AutoreleasepoolPop:
2061 // Conservatively assume this can decrement any count.
2062 return true;
2063 case IC_AutoreleasepoolPush:
2064 case IC_None:
2065 return false;
2066 default:
2067 return CanAlterRefCount(Inst, Arg, PA, Class);
2068 }
2069 }
2070
2071 case RetainAutoreleaseDep:
2072 switch (GetBasicInstructionClass(Inst)) {
2073 case IC_AutoreleasepoolPop:
Dan Gohman511568d2012-04-13 00:59:57 +00002074 case IC_AutoreleasepoolPush:
John McCall9fbd3182011-06-15 23:37:01 +00002075 // Don't merge an objc_autorelease with an objc_retain inside a different
2076 // autoreleasepool scope.
2077 return true;
2078 case IC_Retain:
2079 case IC_RetainRV:
2080 // Check for a retain of the same pointer for merging.
2081 return GetObjCArg(Inst) == Arg;
2082 default:
2083 // Nothing else matters for objc_retainAutorelease formation.
2084 return false;
2085 }
John McCall9fbd3182011-06-15 23:37:01 +00002086
2087 case RetainAutoreleaseRVDep: {
2088 InstructionClass Class = GetBasicInstructionClass(Inst);
2089 switch (Class) {
2090 case IC_Retain:
2091 case IC_RetainRV:
2092 // Check for a retain of the same pointer for merging.
2093 return GetObjCArg(Inst) == Arg;
2094 default:
2095 // Anything that can autorelease interrupts
2096 // retainAutoreleaseReturnValue formation.
2097 return CanInterruptRV(Class);
2098 }
John McCall9fbd3182011-06-15 23:37:01 +00002099 }
2100
2101 case RetainRVDep:
2102 return CanInterruptRV(GetBasicInstructionClass(Inst));
2103 }
2104
2105 llvm_unreachable("Invalid dependence flavor");
John McCall9fbd3182011-06-15 23:37:01 +00002106}
2107
2108/// FindDependencies - Walk up the CFG from StartPos (which is in StartBB) and
2109/// find local and non-local dependencies on Arg.
2110/// TODO: Cache results?
2111static void
2112FindDependencies(DependenceKind Flavor,
2113 const Value *Arg,
2114 BasicBlock *StartBB, Instruction *StartInst,
2115 SmallPtrSet<Instruction *, 4> &DependingInstructions,
2116 SmallPtrSet<const BasicBlock *, 4> &Visited,
2117 ProvenanceAnalysis &PA) {
2118 BasicBlock::iterator StartPos = StartInst;
2119
2120 SmallVector<std::pair<BasicBlock *, BasicBlock::iterator>, 4> Worklist;
2121 Worklist.push_back(std::make_pair(StartBB, StartPos));
2122 do {
2123 std::pair<BasicBlock *, BasicBlock::iterator> Pair =
2124 Worklist.pop_back_val();
2125 BasicBlock *LocalStartBB = Pair.first;
2126 BasicBlock::iterator LocalStartPos = Pair.second;
2127 BasicBlock::iterator StartBBBegin = LocalStartBB->begin();
2128 for (;;) {
2129 if (LocalStartPos == StartBBBegin) {
2130 pred_iterator PI(LocalStartBB), PE(LocalStartBB, false);
2131 if (PI == PE)
2132 // If we've reached the function entry, produce a null dependence.
2133 DependingInstructions.insert(0);
2134 else
2135 // Add the predecessors to the worklist.
2136 do {
2137 BasicBlock *PredBB = *PI;
2138 if (Visited.insert(PredBB))
2139 Worklist.push_back(std::make_pair(PredBB, PredBB->end()));
2140 } while (++PI != PE);
2141 break;
2142 }
2143
2144 Instruction *Inst = --LocalStartPos;
2145 if (Depends(Flavor, Inst, Arg, PA)) {
2146 DependingInstructions.insert(Inst);
2147 break;
2148 }
2149 }
2150 } while (!Worklist.empty());
2151
2152 // Determine whether the original StartBB post-dominates all of the blocks we
2153 // visited. If not, insert a sentinal indicating that most optimizations are
2154 // not safe.
2155 for (SmallPtrSet<const BasicBlock *, 4>::const_iterator I = Visited.begin(),
2156 E = Visited.end(); I != E; ++I) {
2157 const BasicBlock *BB = *I;
2158 if (BB == StartBB)
2159 continue;
2160 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2161 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2162 const BasicBlock *Succ = *SI;
2163 if (Succ != StartBB && !Visited.count(Succ)) {
2164 DependingInstructions.insert(reinterpret_cast<Instruction *>(-1));
2165 return;
2166 }
2167 }
2168 }
2169}
2170
2171static bool isNullOrUndef(const Value *V) {
2172 return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
2173}
2174
2175static bool isNoopInstruction(const Instruction *I) {
2176 return isa<BitCastInst>(I) ||
2177 (isa<GetElementPtrInst>(I) &&
2178 cast<GetElementPtrInst>(I)->hasAllZeroIndices());
2179}
2180
2181/// OptimizeRetainCall - Turn objc_retain into
2182/// objc_retainAutoreleasedReturnValue if the operand is a return value.
2183void
2184ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) {
Dan Gohman447989c2012-04-27 18:56:31 +00002185 ImmutableCallSite CS(GetObjCArg(Retain));
2186 const Instruction *Call = CS.getInstruction();
John McCall9fbd3182011-06-15 23:37:01 +00002187 if (!Call) return;
2188 if (Call->getParent() != Retain->getParent()) return;
2189
2190 // Check that the call is next to the retain.
Dan Gohman447989c2012-04-27 18:56:31 +00002191 BasicBlock::const_iterator I = Call;
John McCall9fbd3182011-06-15 23:37:01 +00002192 ++I;
2193 while (isNoopInstruction(I)) ++I;
2194 if (&*I != Retain)
2195 return;
2196
2197 // Turn it to an objc_retainAutoreleasedReturnValue..
2198 Changed = true;
2199 ++NumPeeps;
2200 cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent()));
2201}
2202
2203/// OptimizeRetainRVCall - Turn objc_retainAutoreleasedReturnValue into
Dan Gohman447989c2012-04-27 18:56:31 +00002204/// objc_retain if the operand is not a return value. Or, if it can be paired
2205/// with an objc_autoreleaseReturnValue, delete the pair and return true.
John McCall9fbd3182011-06-15 23:37:01 +00002206bool
2207ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
Dan Gohman6fedb3c2012-03-23 18:09:00 +00002208 // Check for the argument being from an immediately preceding call or invoke.
Dan Gohman447989c2012-04-27 18:56:31 +00002209 const Value *Arg = GetObjCArg(RetainRV);
2210 ImmutableCallSite CS(Arg);
2211 if (const Instruction *Call = CS.getInstruction()) {
John McCall9fbd3182011-06-15 23:37:01 +00002212 if (Call->getParent() == RetainRV->getParent()) {
Dan Gohman447989c2012-04-27 18:56:31 +00002213 BasicBlock::const_iterator I = Call;
John McCall9fbd3182011-06-15 23:37:01 +00002214 ++I;
2215 while (isNoopInstruction(I)) ++I;
2216 if (&*I == RetainRV)
2217 return false;
Dan Gohman447989c2012-04-27 18:56:31 +00002218 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Dan Gohman6fedb3c2012-03-23 18:09:00 +00002219 BasicBlock *RetainRVParent = RetainRV->getParent();
2220 if (II->getNormalDest() == RetainRVParent) {
Dan Gohman447989c2012-04-27 18:56:31 +00002221 BasicBlock::const_iterator I = RetainRVParent->begin();
Dan Gohman6fedb3c2012-03-23 18:09:00 +00002222 while (isNoopInstruction(I)) ++I;
2223 if (&*I == RetainRV)
2224 return false;
2225 }
John McCall9fbd3182011-06-15 23:37:01 +00002226 }
Dan Gohman6fedb3c2012-03-23 18:09:00 +00002227 }
John McCall9fbd3182011-06-15 23:37:01 +00002228
2229 // Check for being preceded by an objc_autoreleaseReturnValue on the same
2230 // pointer. In this case, we can delete the pair.
2231 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
2232 if (I != Begin) {
2233 do --I; while (I != Begin && isNoopInstruction(I));
2234 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
2235 GetObjCArg(I) == Arg) {
2236 Changed = true;
2237 ++NumPeeps;
2238 EraseInstruction(I);
2239 EraseInstruction(RetainRV);
2240 return true;
2241 }
2242 }
2243
2244 // Turn it to a plain objc_retain.
2245 Changed = true;
2246 ++NumPeeps;
2247 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
2248 return false;
2249}
2250
2251/// OptimizeAutoreleaseRVCall - Turn objc_autoreleaseReturnValue into
2252/// objc_autorelease if the result is not used as a return value.
2253void
2254ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV) {
2255 // Check for a return of the pointer value.
2256 const Value *Ptr = GetObjCArg(AutoreleaseRV);
Dan Gohman126a54f2011-08-12 00:36:31 +00002257 SmallVector<const Value *, 2> Users;
2258 Users.push_back(Ptr);
2259 do {
2260 Ptr = Users.pop_back_val();
2261 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
2262 UI != UE; ++UI) {
2263 const User *I = *UI;
2264 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
2265 return;
2266 if (isa<BitCastInst>(I))
2267 Users.push_back(I);
2268 }
2269 } while (!Users.empty());
John McCall9fbd3182011-06-15 23:37:01 +00002270
2271 Changed = true;
2272 ++NumPeeps;
2273 cast<CallInst>(AutoreleaseRV)->
2274 setCalledFunction(getAutoreleaseCallee(F.getParent()));
2275}
2276
2277/// OptimizeIndividualCalls - Visit each call, one at a time, and make
2278/// simplifications without doing any additional analysis.
2279void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
2280 // Reset all the flags in preparation for recomputing them.
2281 UsedInThisFunction = 0;
2282
2283 // Visit all objc_* calls in F.
2284 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2285 Instruction *Inst = &*I++;
2286 InstructionClass Class = GetBasicInstructionClass(Inst);
2287
2288 switch (Class) {
2289 default: break;
2290
2291 // Delete no-op casts. These function calls have special semantics, but
2292 // the semantics are entirely implemented via lowering in the front-end,
2293 // so by the time they reach the optimizer, they are just no-op calls
2294 // which return their argument.
2295 //
2296 // There are gray areas here, as the ability to cast reference-counted
2297 // pointers to raw void* and back allows code to break ARC assumptions,
2298 // however these are currently considered to be unimportant.
2299 case IC_NoopCast:
2300 Changed = true;
2301 ++NumNoops;
2302 EraseInstruction(Inst);
2303 continue;
2304
2305 // If the pointer-to-weak-pointer is null, it's undefined behavior.
2306 case IC_StoreWeak:
2307 case IC_LoadWeak:
2308 case IC_LoadWeakRetained:
2309 case IC_InitWeak:
2310 case IC_DestroyWeak: {
2311 CallInst *CI = cast<CallInst>(Inst);
2312 if (isNullOrUndef(CI->getArgOperand(0))) {
Dan Gohmand6bf2012012-04-13 18:57:48 +00002313 Changed = true;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002314 Type *Ty = CI->getArgOperand(0)->getType();
John McCall9fbd3182011-06-15 23:37:01 +00002315 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2316 Constant::getNullValue(Ty),
2317 CI);
2318 CI->replaceAllUsesWith(UndefValue::get(CI->getType()));
2319 CI->eraseFromParent();
2320 continue;
2321 }
2322 break;
2323 }
2324 case IC_CopyWeak:
2325 case IC_MoveWeak: {
2326 CallInst *CI = cast<CallInst>(Inst);
2327 if (isNullOrUndef(CI->getArgOperand(0)) ||
2328 isNullOrUndef(CI->getArgOperand(1))) {
Dan Gohmand6bf2012012-04-13 18:57:48 +00002329 Changed = true;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002330 Type *Ty = CI->getArgOperand(0)->getType();
John McCall9fbd3182011-06-15 23:37:01 +00002331 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2332 Constant::getNullValue(Ty),
2333 CI);
2334 CI->replaceAllUsesWith(UndefValue::get(CI->getType()));
2335 CI->eraseFromParent();
2336 continue;
2337 }
2338 break;
2339 }
2340 case IC_Retain:
2341 OptimizeRetainCall(F, Inst);
2342 break;
2343 case IC_RetainRV:
2344 if (OptimizeRetainRVCall(F, Inst))
2345 continue;
2346 break;
2347 case IC_AutoreleaseRV:
2348 OptimizeAutoreleaseRVCall(F, Inst);
2349 break;
2350 }
2351
2352 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
2353 if (IsAutorelease(Class) && Inst->use_empty()) {
2354 CallInst *Call = cast<CallInst>(Inst);
2355 const Value *Arg = Call->getArgOperand(0);
2356 Arg = FindSingleUseIdentifiedObject(Arg);
2357 if (Arg) {
2358 Changed = true;
2359 ++NumAutoreleases;
2360
2361 // Create the declaration lazily.
2362 LLVMContext &C = Inst->getContext();
2363 CallInst *NewCall =
2364 CallInst::Create(getReleaseCallee(F.getParent()),
2365 Call->getArgOperand(0), "", Call);
2366 NewCall->setMetadata(ImpreciseReleaseMDKind,
2367 MDNode::get(C, ArrayRef<Value *>()));
2368 EraseInstruction(Call);
2369 Inst = NewCall;
2370 Class = IC_Release;
2371 }
2372 }
2373
2374 // For functions which can never be passed stack arguments, add
2375 // a tail keyword.
2376 if (IsAlwaysTail(Class)) {
2377 Changed = true;
2378 cast<CallInst>(Inst)->setTailCall();
2379 }
2380
2381 // Set nounwind as needed.
2382 if (IsNoThrow(Class)) {
2383 Changed = true;
2384 cast<CallInst>(Inst)->setDoesNotThrow();
2385 }
2386
2387 if (!IsNoopOnNull(Class)) {
2388 UsedInThisFunction |= 1 << Class;
2389 continue;
2390 }
2391
2392 const Value *Arg = GetObjCArg(Inst);
2393
2394 // ARC calls with null are no-ops. Delete them.
2395 if (isNullOrUndef(Arg)) {
2396 Changed = true;
2397 ++NumNoops;
2398 EraseInstruction(Inst);
2399 continue;
2400 }
2401
2402 // Keep track of which of retain, release, autorelease, and retain_block
2403 // are actually present in this function.
2404 UsedInThisFunction |= 1 << Class;
2405
2406 // If Arg is a PHI, and one or more incoming values to the
2407 // PHI are null, and the call is control-equivalent to the PHI, and there
2408 // are no relevant side effects between the PHI and the call, the call
2409 // could be pushed up to just those paths with non-null incoming values.
2410 // For now, don't bother splitting critical edges for this.
2411 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
2412 Worklist.push_back(std::make_pair(Inst, Arg));
2413 do {
2414 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
2415 Inst = Pair.first;
2416 Arg = Pair.second;
2417
2418 const PHINode *PN = dyn_cast<PHINode>(Arg);
2419 if (!PN) continue;
2420
2421 // Determine if the PHI has any null operands, or any incoming
2422 // critical edges.
2423 bool HasNull = false;
2424 bool HasCriticalEdges = false;
2425 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2426 Value *Incoming =
2427 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2428 if (isNullOrUndef(Incoming))
2429 HasNull = true;
2430 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
2431 .getNumSuccessors() != 1) {
2432 HasCriticalEdges = true;
2433 break;
2434 }
2435 }
2436 // If we have null operands and no critical edges, optimize.
2437 if (!HasCriticalEdges && HasNull) {
2438 SmallPtrSet<Instruction *, 4> DependingInstructions;
2439 SmallPtrSet<const BasicBlock *, 4> Visited;
2440
2441 // Check that there is nothing that cares about the reference
2442 // count between the call and the phi.
Dan Gohman511568d2012-04-13 00:59:57 +00002443 switch (Class) {
2444 case IC_Retain:
2445 case IC_RetainBlock:
2446 // These can always be moved up.
2447 break;
2448 case IC_Release:
Dan Gohman0daef3d2012-05-08 23:39:44 +00002449 // These can't be moved across things that care about the retain
2450 // count.
Dan Gohman511568d2012-04-13 00:59:57 +00002451 FindDependencies(NeedsPositiveRetainCount, Arg,
2452 Inst->getParent(), Inst,
2453 DependingInstructions, Visited, PA);
2454 break;
2455 case IC_Autorelease:
2456 // These can't be moved across autorelease pool scope boundaries.
2457 FindDependencies(AutoreleasePoolBoundary, Arg,
2458 Inst->getParent(), Inst,
2459 DependingInstructions, Visited, PA);
2460 break;
2461 case IC_RetainRV:
2462 case IC_AutoreleaseRV:
2463 // Don't move these; the RV optimization depends on the autoreleaseRV
2464 // being tail called, and the retainRV being immediately after a call
2465 // (which might still happen if we get lucky with codegen layout, but
2466 // it's not worth taking the chance).
2467 continue;
2468 default:
2469 llvm_unreachable("Invalid dependence flavor");
2470 }
2471
John McCall9fbd3182011-06-15 23:37:01 +00002472 if (DependingInstructions.size() == 1 &&
2473 *DependingInstructions.begin() == PN) {
2474 Changed = true;
2475 ++NumPartialNoops;
2476 // Clone the call into each predecessor that has a non-null value.
2477 CallInst *CInst = cast<CallInst>(Inst);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002478 Type *ParamTy = CInst->getArgOperand(0)->getType();
John McCall9fbd3182011-06-15 23:37:01 +00002479 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2480 Value *Incoming =
2481 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2482 if (!isNullOrUndef(Incoming)) {
2483 CallInst *Clone = cast<CallInst>(CInst->clone());
2484 Value *Op = PN->getIncomingValue(i);
2485 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
2486 if (Op->getType() != ParamTy)
2487 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
2488 Clone->setArgOperand(0, Op);
2489 Clone->insertBefore(InsertPos);
2490 Worklist.push_back(std::make_pair(Clone, Incoming));
2491 }
2492 }
2493 // Erase the original call.
2494 EraseInstruction(CInst);
2495 continue;
2496 }
2497 }
2498 } while (!Worklist.empty());
2499 }
2500}
2501
2502/// CheckForCFGHazards - Check for critical edges, loop boundaries, irreducible
2503/// control flow, or other CFG structures where moving code across the edge
2504/// would result in it being executed more.
2505void
2506ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
2507 DenseMap<const BasicBlock *, BBState> &BBStates,
2508 BBState &MyStates) const {
2509 // If any top-down local-use or possible-dec has a succ which is earlier in
2510 // the sequence, forget it.
Dan Gohman22cc4cc2012-03-02 01:13:53 +00002511 for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
John McCall9fbd3182011-06-15 23:37:01 +00002512 E = MyStates.top_down_ptr_end(); I != E; ++I)
2513 switch (I->second.GetSeq()) {
2514 default: break;
2515 case S_Use: {
2516 const Value *Arg = I->first;
2517 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2518 bool SomeSuccHasSame = false;
2519 bool AllSuccsHaveSame = true;
Dan Gohman22cc4cc2012-03-02 01:13:53 +00002520 PtrState &S = I->second;
Dan Gohmandbe266b2012-02-17 18:59:53 +00002521 succ_const_iterator SI(TI), SE(TI, false);
2522
2523 // If the terminator is an invoke marked with the
2524 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
2525 // ignored, for ARC purposes.
2526 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind))
2527 --SE;
2528
2529 for (; SI != SE; ++SI) {
Dan Gohman70e29682012-03-02 01:26:46 +00002530 Sequence SuccSSeq = S_None;
2531 bool SuccSRRIKnownSafe = false;
Dan Gohman0daef3d2012-05-08 23:39:44 +00002532 // If VisitBottomUp has pointer information for this successor, take
2533 // what we know about it.
Dan Gohman447989c2012-04-27 18:56:31 +00002534 DenseMap<const BasicBlock *, BBState>::iterator BBI =
2535 BBStates.find(*SI);
2536 assert(BBI != BBStates.end());
2537 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2538 SuccSSeq = SuccS.GetSeq();
2539 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
Dan Gohman70e29682012-03-02 01:26:46 +00002540 switch (SuccSSeq) {
John McCall9fbd3182011-06-15 23:37:01 +00002541 case S_None:
Dan Gohmana7f7db22011-08-12 00:26:31 +00002542 case S_CanRelease: {
Dan Gohman70e29682012-03-02 01:26:46 +00002543 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
Dan Gohmana7f7db22011-08-12 00:26:31 +00002544 S.ClearSequenceProgress();
Dan Gohman70e29682012-03-02 01:26:46 +00002545 break;
2546 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002547 continue;
2548 }
John McCall9fbd3182011-06-15 23:37:01 +00002549 case S_Use:
2550 SomeSuccHasSame = true;
2551 break;
2552 case S_Stop:
2553 case S_Release:
2554 case S_MovableRelease:
Dan Gohman70e29682012-03-02 01:26:46 +00002555 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002556 AllSuccsHaveSame = false;
John McCall9fbd3182011-06-15 23:37:01 +00002557 break;
2558 case S_Retain:
2559 llvm_unreachable("bottom-up pointer in retain state!");
2560 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002561 }
John McCall9fbd3182011-06-15 23:37:01 +00002562 // If the state at the other end of any of the successor edges
2563 // matches the current state, require all edges to match. This
2564 // guards against loops in the middle of a sequence.
2565 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002566 S.ClearSequenceProgress();
Dan Gohman2e68beb2011-12-12 18:13:53 +00002567 break;
John McCall9fbd3182011-06-15 23:37:01 +00002568 }
2569 case S_CanRelease: {
2570 const Value *Arg = I->first;
2571 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2572 bool SomeSuccHasSame = false;
2573 bool AllSuccsHaveSame = true;
Dan Gohman22cc4cc2012-03-02 01:13:53 +00002574 PtrState &S = I->second;
Dan Gohmandbe266b2012-02-17 18:59:53 +00002575 succ_const_iterator SI(TI), SE(TI, false);
2576
2577 // If the terminator is an invoke marked with the
2578 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
2579 // ignored, for ARC purposes.
2580 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind))
2581 --SE;
2582
2583 for (; SI != SE; ++SI) {
Dan Gohman70e29682012-03-02 01:26:46 +00002584 Sequence SuccSSeq = S_None;
2585 bool SuccSRRIKnownSafe = false;
Dan Gohman0daef3d2012-05-08 23:39:44 +00002586 // If VisitBottomUp has pointer information for this successor, take
2587 // what we know about it.
Dan Gohman447989c2012-04-27 18:56:31 +00002588 DenseMap<const BasicBlock *, BBState>::iterator BBI =
2589 BBStates.find(*SI);
2590 assert(BBI != BBStates.end());
2591 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2592 SuccSSeq = SuccS.GetSeq();
2593 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
Dan Gohman70e29682012-03-02 01:26:46 +00002594 switch (SuccSSeq) {
Dan Gohmana7f7db22011-08-12 00:26:31 +00002595 case S_None: {
Dan Gohman70e29682012-03-02 01:26:46 +00002596 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
Dan Gohmana7f7db22011-08-12 00:26:31 +00002597 S.ClearSequenceProgress();
Dan Gohman70e29682012-03-02 01:26:46 +00002598 break;
2599 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002600 continue;
2601 }
John McCall9fbd3182011-06-15 23:37:01 +00002602 case S_CanRelease:
2603 SomeSuccHasSame = true;
2604 break;
2605 case S_Stop:
2606 case S_Release:
2607 case S_MovableRelease:
2608 case S_Use:
Dan Gohman70e29682012-03-02 01:26:46 +00002609 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002610 AllSuccsHaveSame = false;
John McCall9fbd3182011-06-15 23:37:01 +00002611 break;
2612 case S_Retain:
2613 llvm_unreachable("bottom-up pointer in retain state!");
2614 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002615 }
John McCall9fbd3182011-06-15 23:37:01 +00002616 // If the state at the other end of any of the successor edges
2617 // matches the current state, require all edges to match. This
2618 // guards against loops in the middle of a sequence.
2619 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002620 S.ClearSequenceProgress();
Dan Gohman2e68beb2011-12-12 18:13:53 +00002621 break;
John McCall9fbd3182011-06-15 23:37:01 +00002622 }
2623 }
2624}
2625
2626bool
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002627ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002628 BasicBlock *BB,
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002629 MapVector<Value *, RRInfo> &Retains,
2630 BBState &MyStates) {
2631 bool NestingDetected = false;
2632 InstructionClass Class = GetInstructionClass(Inst);
2633 const Value *Arg = 0;
2634
2635 switch (Class) {
2636 case IC_Release: {
2637 Arg = GetObjCArg(Inst);
2638
2639 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2640
2641 // If we see two releases in a row on the same pointer. If so, make
2642 // a note, and we'll cicle back to revisit it after we've
2643 // hopefully eliminated the second release, which may allow us to
2644 // eliminate the first release too.
2645 // Theoretically we could implement removal of nested retain+release
2646 // pairs by making PtrState hold a stack of states, but this is
2647 // simple and avoids adding overhead for the non-nested case.
2648 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease)
2649 NestingDetected = true;
2650
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002651 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
Dan Gohman50ade652012-04-25 00:50:46 +00002652 S.ResetSequenceProgress(ReleaseMetadata ? S_MovableRelease : S_Release);
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002653 S.RRI.ReleaseMetadata = ReleaseMetadata;
Dan Gohman230768b2012-09-04 23:16:20 +00002654 S.RRI.KnownSafe = S.IsKnownIncremented();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002655 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2656 S.RRI.Calls.insert(Inst);
2657
Dan Gohman230768b2012-09-04 23:16:20 +00002658 S.SetKnownPositiveRefCount();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002659 break;
2660 }
2661 case IC_RetainBlock:
2662 // An objc_retainBlock call with just a use may need to be kept,
2663 // because it may be copying a block from the stack to the heap.
2664 if (!IsRetainBlockOptimizable(Inst))
2665 break;
2666 // FALLTHROUGH
2667 case IC_Retain:
2668 case IC_RetainRV: {
2669 Arg = GetObjCArg(Inst);
2670
2671 PtrState &S = MyStates.getPtrBottomUpState(Arg);
Dan Gohman50ade652012-04-25 00:50:46 +00002672 S.SetKnownPositiveRefCount();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002673
2674 switch (S.GetSeq()) {
2675 case S_Stop:
2676 case S_Release:
2677 case S_MovableRelease:
2678 case S_Use:
2679 S.RRI.ReverseInsertPts.clear();
2680 // FALL THROUGH
2681 case S_CanRelease:
2682 // Don't do retain+release tracking for IC_RetainRV, because it's
2683 // better to let it remain as the first instruction after a call.
2684 if (Class != IC_RetainRV) {
2685 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2686 Retains[Inst] = S.RRI;
2687 }
2688 S.ClearSequenceProgress();
2689 break;
2690 case S_None:
2691 break;
2692 case S_Retain:
2693 llvm_unreachable("bottom-up pointer in retain state!");
2694 }
2695 return NestingDetected;
2696 }
2697 case IC_AutoreleasepoolPop:
2698 // Conservatively, clear MyStates for all known pointers.
2699 MyStates.clearBottomUpPointers();
2700 return NestingDetected;
2701 case IC_AutoreleasepoolPush:
2702 case IC_None:
2703 // These are irrelevant.
2704 return NestingDetected;
2705 default:
2706 break;
2707 }
2708
2709 // Consider any other possible effects of this instruction on each
2710 // pointer being tracked.
2711 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
2712 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
2713 const Value *Ptr = MI->first;
2714 if (Ptr == Arg)
2715 continue; // Handled above.
2716 PtrState &S = MI->second;
2717 Sequence Seq = S.GetSeq();
2718
2719 // Check for possible releases.
2720 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Dan Gohman50ade652012-04-25 00:50:46 +00002721 S.ClearRefCount();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002722 switch (Seq) {
2723 case S_Use:
2724 S.SetSeq(S_CanRelease);
2725 continue;
2726 case S_CanRelease:
2727 case S_Release:
2728 case S_MovableRelease:
2729 case S_Stop:
2730 case S_None:
2731 break;
2732 case S_Retain:
2733 llvm_unreachable("bottom-up pointer in retain state!");
2734 }
2735 }
2736
2737 // Check for possible direct uses.
2738 switch (Seq) {
2739 case S_Release:
2740 case S_MovableRelease:
2741 if (CanUse(Inst, Ptr, PA, Class)) {
2742 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002743 // If this is an invoke instruction, we're scanning it as part of
2744 // one of its successor blocks, since we can't insert code after it
2745 // in its own block, and we don't want to split critical edges.
2746 if (isa<InvokeInst>(Inst))
2747 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2748 else
Francois Pichetb54a5ed2012-03-24 01:36:37 +00002749 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002750 S.SetSeq(S_Use);
2751 } else if (Seq == S_Release &&
2752 (Class == IC_User || Class == IC_CallOrUser)) {
2753 // Non-movable releases depend on any possible objc pointer use.
2754 S.SetSeq(S_Stop);
2755 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002756 // As above; handle invoke specially.
2757 if (isa<InvokeInst>(Inst))
2758 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2759 else
Francois Pichetb54a5ed2012-03-24 01:36:37 +00002760 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002761 }
2762 break;
2763 case S_Stop:
2764 if (CanUse(Inst, Ptr, PA, Class))
2765 S.SetSeq(S_Use);
2766 break;
2767 case S_CanRelease:
2768 case S_Use:
2769 case S_None:
2770 break;
2771 case S_Retain:
2772 llvm_unreachable("bottom-up pointer in retain state!");
2773 }
2774 }
2775
2776 return NestingDetected;
2777}
2778
2779bool
John McCall9fbd3182011-06-15 23:37:01 +00002780ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2781 DenseMap<const BasicBlock *, BBState> &BBStates,
2782 MapVector<Value *, RRInfo> &Retains) {
2783 bool NestingDetected = false;
2784 BBState &MyStates = BBStates[BB];
2785
2786 // Merge the states from each successor to compute the initial state
2787 // for the current block.
Dan Gohman40e46602012-08-27 18:31:36 +00002788 BBState::edge_iterator SI(MyStates.succ_begin()),
2789 SE(MyStates.succ_end());
2790 if (SI != SE) {
Dan Gohmaneeeb7752012-04-24 22:53:18 +00002791 const BasicBlock *Succ = *SI;
2792 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
2793 assert(I != BBStates.end());
2794 MyStates.InitFromSucc(I->second);
2795 ++SI;
2796 for (; SI != SE; ++SI) {
2797 Succ = *SI;
2798 I = BBStates.find(Succ);
2799 assert(I != BBStates.end());
2800 MyStates.MergeSucc(I->second);
2801 }
Dan Gohmandbe266b2012-02-17 18:59:53 +00002802 }
John McCall9fbd3182011-06-15 23:37:01 +00002803
2804 // Visit all the instructions, bottom-up.
2805 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2806 Instruction *Inst = llvm::prior(I);
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002807
2808 // Invoke instructions are visited as part of their successors (below).
2809 if (isa<InvokeInst>(Inst))
2810 continue;
2811
2812 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
2813 }
2814
Dan Gohman447989c2012-04-27 18:56:31 +00002815 // If there's a predecessor with an invoke, visit the invoke as if it were
2816 // part of this block, since we can't insert code after an invoke in its own
2817 // block, and we don't want to split critical edges.
Dan Gohmaneeeb7752012-04-24 22:53:18 +00002818 for (BBState::edge_iterator PI(MyStates.pred_begin()),
2819 PE(MyStates.pred_end()); PI != PE; ++PI) {
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002820 BasicBlock *Pred = *PI;
Dan Gohman447989c2012-04-27 18:56:31 +00002821 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
2822 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002823 }
John McCall9fbd3182011-06-15 23:37:01 +00002824
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002825 return NestingDetected;
2826}
John McCall9fbd3182011-06-15 23:37:01 +00002827
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002828bool
2829ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
2830 DenseMap<Value *, RRInfo> &Releases,
2831 BBState &MyStates) {
2832 bool NestingDetected = false;
2833 InstructionClass Class = GetInstructionClass(Inst);
2834 const Value *Arg = 0;
John McCall9fbd3182011-06-15 23:37:01 +00002835
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002836 switch (Class) {
2837 case IC_RetainBlock:
2838 // An objc_retainBlock call with just a use may need to be kept,
2839 // because it may be copying a block from the stack to the heap.
2840 if (!IsRetainBlockOptimizable(Inst))
2841 break;
2842 // FALLTHROUGH
2843 case IC_Retain:
2844 case IC_RetainRV: {
2845 Arg = GetObjCArg(Inst);
2846
2847 PtrState &S = MyStates.getPtrTopDownState(Arg);
2848
2849 // Don't do retain+release tracking for IC_RetainRV, because it's
2850 // better to let it remain as the first instruction after a call.
2851 if (Class != IC_RetainRV) {
2852 // If we see two retains in a row on the same pointer. If so, make
John McCall9fbd3182011-06-15 23:37:01 +00002853 // a note, and we'll cicle back to revisit it after we've
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002854 // hopefully eliminated the second retain, which may allow us to
2855 // eliminate the first retain too.
John McCall9fbd3182011-06-15 23:37:01 +00002856 // Theoretically we could implement removal of nested retain+release
2857 // pairs by making PtrState hold a stack of states, but this is
2858 // simple and avoids adding overhead for the non-nested case.
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002859 if (S.GetSeq() == S_Retain)
John McCall9fbd3182011-06-15 23:37:01 +00002860 NestingDetected = true;
2861
Dan Gohman50ade652012-04-25 00:50:46 +00002862 S.ResetSequenceProgress(S_Retain);
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002863 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
Dan Gohman230768b2012-09-04 23:16:20 +00002864 S.RRI.KnownSafe = S.IsKnownIncremented();
John McCall9fbd3182011-06-15 23:37:01 +00002865 S.RRI.Calls.insert(Inst);
John McCall9fbd3182011-06-15 23:37:01 +00002866 }
John McCall9fbd3182011-06-15 23:37:01 +00002867
Dan Gohman230768b2012-09-04 23:16:20 +00002868 S.SetKnownPositiveRefCount();
Dan Gohmanc72d3be2012-07-23 19:27:31 +00002869
2870 // A retain can be a potential use; procede to the generic checking
2871 // code below.
2872 break;
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002873 }
2874 case IC_Release: {
2875 Arg = GetObjCArg(Inst);
2876
2877 PtrState &S = MyStates.getPtrTopDownState(Arg);
Dan Gohman230768b2012-09-04 23:16:20 +00002878 S.ClearRefCount();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002879
2880 switch (S.GetSeq()) {
2881 case S_Retain:
2882 case S_CanRelease:
2883 S.RRI.ReverseInsertPts.clear();
2884 // FALL THROUGH
2885 case S_Use:
2886 S.RRI.ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2887 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2888 Releases[Inst] = S.RRI;
2889 S.ClearSequenceProgress();
2890 break;
2891 case S_None:
2892 break;
2893 case S_Stop:
2894 case S_Release:
2895 case S_MovableRelease:
2896 llvm_unreachable("top-down pointer in release state!");
2897 }
2898 break;
2899 }
2900 case IC_AutoreleasepoolPop:
2901 // Conservatively, clear MyStates for all known pointers.
2902 MyStates.clearTopDownPointers();
2903 return NestingDetected;
2904 case IC_AutoreleasepoolPush:
2905 case IC_None:
2906 // These are irrelevant.
2907 return NestingDetected;
2908 default:
2909 break;
2910 }
2911
2912 // Consider any other possible effects of this instruction on each
2913 // pointer being tracked.
2914 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
2915 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
2916 const Value *Ptr = MI->first;
2917 if (Ptr == Arg)
2918 continue; // Handled above.
2919 PtrState &S = MI->second;
2920 Sequence Seq = S.GetSeq();
2921
2922 // Check for possible releases.
2923 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Dan Gohman50ade652012-04-25 00:50:46 +00002924 S.ClearRefCount();
John McCall9fbd3182011-06-15 23:37:01 +00002925 switch (Seq) {
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002926 case S_Retain:
2927 S.SetSeq(S_CanRelease);
2928 assert(S.RRI.ReverseInsertPts.empty());
2929 S.RRI.ReverseInsertPts.insert(Inst);
2930
2931 // One call can't cause a transition from S_Retain to S_CanRelease
2932 // and S_CanRelease to S_Use. If we've made the first transition,
2933 // we're done.
2934 continue;
John McCall9fbd3182011-06-15 23:37:01 +00002935 case S_Use:
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002936 case S_CanRelease:
John McCall9fbd3182011-06-15 23:37:01 +00002937 case S_None:
2938 break;
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002939 case S_Stop:
2940 case S_Release:
2941 case S_MovableRelease:
2942 llvm_unreachable("top-down pointer in release state!");
John McCall9fbd3182011-06-15 23:37:01 +00002943 }
2944 }
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002945
2946 // Check for possible direct uses.
2947 switch (Seq) {
2948 case S_CanRelease:
2949 if (CanUse(Inst, Ptr, PA, Class))
2950 S.SetSeq(S_Use);
2951 break;
2952 case S_Retain:
2953 case S_Use:
2954 case S_None:
2955 break;
2956 case S_Stop:
2957 case S_Release:
2958 case S_MovableRelease:
2959 llvm_unreachable("top-down pointer in release state!");
2960 }
John McCall9fbd3182011-06-15 23:37:01 +00002961 }
2962
2963 return NestingDetected;
2964}
2965
2966bool
2967ObjCARCOpt::VisitTopDown(BasicBlock *BB,
2968 DenseMap<const BasicBlock *, BBState> &BBStates,
2969 DenseMap<Value *, RRInfo> &Releases) {
2970 bool NestingDetected = false;
2971 BBState &MyStates = BBStates[BB];
2972
2973 // Merge the states from each predecessor to compute the initial state
2974 // for the current block.
Dan Gohman40e46602012-08-27 18:31:36 +00002975 BBState::edge_iterator PI(MyStates.pred_begin()),
2976 PE(MyStates.pred_end());
2977 if (PI != PE) {
Dan Gohmaneeeb7752012-04-24 22:53:18 +00002978 const BasicBlock *Pred = *PI;
2979 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
2980 assert(I != BBStates.end());
2981 MyStates.InitFromPred(I->second);
2982 ++PI;
2983 for (; PI != PE; ++PI) {
2984 Pred = *PI;
2985 I = BBStates.find(Pred);
2986 assert(I != BBStates.end());
2987 MyStates.MergePred(I->second);
2988 }
Dan Gohmaneeeb7752012-04-24 22:53:18 +00002989 }
John McCall9fbd3182011-06-15 23:37:01 +00002990
2991 // Visit all the instructions, top-down.
2992 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2993 Instruction *Inst = I;
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002994 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
John McCall9fbd3182011-06-15 23:37:01 +00002995 }
2996
2997 CheckForCFGHazards(BB, BBStates, MyStates);
2998 return NestingDetected;
2999}
3000
Dan Gohman59a1c932011-12-12 19:42:25 +00003001static void
3002ComputePostOrders(Function &F,
3003 SmallVectorImpl<BasicBlock *> &PostOrder,
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003004 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
3005 unsigned NoObjCARCExceptionsMDKind,
3006 DenseMap<const BasicBlock *, BBState> &BBStates) {
Dan Gohman59a1c932011-12-12 19:42:25 +00003007 /// Visited - The visited set, for doing DFS walks.
3008 SmallPtrSet<BasicBlock *, 16> Visited;
3009
3010 // Do DFS, computing the PostOrder.
3011 SmallPtrSet<BasicBlock *, 16> OnStack;
3012 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003013
3014 // Functions always have exactly one entry block, and we don't have
3015 // any other block that we treat like an entry block.
Dan Gohman59a1c932011-12-12 19:42:25 +00003016 BasicBlock *EntryBB = &F.getEntryBlock();
Dan Gohman0daef3d2012-05-08 23:39:44 +00003017 BBState &MyStates = BBStates[EntryBB];
3018 MyStates.SetAsEntry();
3019 TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
3020 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
Dan Gohman59a1c932011-12-12 19:42:25 +00003021 Visited.insert(EntryBB);
3022 OnStack.insert(EntryBB);
3023 do {
3024 dfs_next_succ:
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003025 BasicBlock *CurrBB = SuccStack.back().first;
3026 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
3027 succ_iterator SE(TI, false);
Dan Gohman0daef3d2012-05-08 23:39:44 +00003028
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003029 // If the terminator is an invoke marked with the
3030 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
3031 // ignored, for ARC purposes.
3032 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind))
3033 --SE;
3034
3035 while (SuccStack.back().second != SE) {
3036 BasicBlock *SuccBB = *SuccStack.back().second++;
3037 if (Visited.insert(SuccBB)) {
Dan Gohman0daef3d2012-05-08 23:39:44 +00003038 TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
3039 SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003040 BBStates[CurrBB].addSucc(SuccBB);
Dan Gohman0daef3d2012-05-08 23:39:44 +00003041 BBState &SuccStates = BBStates[SuccBB];
3042 SuccStates.addPred(CurrBB);
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003043 OnStack.insert(SuccBB);
Dan Gohman59a1c932011-12-12 19:42:25 +00003044 goto dfs_next_succ;
3045 }
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003046
3047 if (!OnStack.count(SuccBB)) {
3048 BBStates[CurrBB].addSucc(SuccBB);
3049 BBStates[SuccBB].addPred(CurrBB);
3050 }
Dan Gohman59a1c932011-12-12 19:42:25 +00003051 }
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003052 OnStack.erase(CurrBB);
3053 PostOrder.push_back(CurrBB);
3054 SuccStack.pop_back();
Dan Gohman59a1c932011-12-12 19:42:25 +00003055 } while (!SuccStack.empty());
3056
3057 Visited.clear();
3058
Dan Gohman59a1c932011-12-12 19:42:25 +00003059 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003060 // Functions may have many exits, and there also blocks which we treat
3061 // as exits due to ignored edges.
3062 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
3063 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
3064 BasicBlock *ExitBB = I;
3065 BBState &MyStates = BBStates[ExitBB];
3066 if (!MyStates.isExit())
3067 continue;
3068
Dan Gohman447989c2012-04-27 18:56:31 +00003069 MyStates.SetAsExit();
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003070
3071 PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
Dan Gohman59a1c932011-12-12 19:42:25 +00003072 Visited.insert(ExitBB);
3073 while (!PredStack.empty()) {
3074 reverse_dfs_next_succ:
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003075 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
3076 while (PredStack.back().second != PE) {
Dan Gohman59a1c932011-12-12 19:42:25 +00003077 BasicBlock *BB = *PredStack.back().second++;
Dan Gohman59a1c932011-12-12 19:42:25 +00003078 if (Visited.insert(BB)) {
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003079 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
Dan Gohman59a1c932011-12-12 19:42:25 +00003080 goto reverse_dfs_next_succ;
3081 }
3082 }
3083 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
3084 }
3085 }
3086}
3087
John McCall9fbd3182011-06-15 23:37:01 +00003088// Visit - Visit the function both top-down and bottom-up.
3089bool
3090ObjCARCOpt::Visit(Function &F,
3091 DenseMap<const BasicBlock *, BBState> &BBStates,
3092 MapVector<Value *, RRInfo> &Retains,
3093 DenseMap<Value *, RRInfo> &Releases) {
Dan Gohman59a1c932011-12-12 19:42:25 +00003094
3095 // Use reverse-postorder traversals, because we magically know that loops
3096 // will be well behaved, i.e. they won't repeatedly call retain on a single
3097 // pointer without doing a release. We can't use the ReversePostOrderTraversal
3098 // class here because we want the reverse-CFG postorder to consider each
3099 // function exit point, and we want to ignore selected cycle edges.
3100 SmallVector<BasicBlock *, 16> PostOrder;
3101 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003102 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
3103 NoObjCARCExceptionsMDKind,
3104 BBStates);
Dan Gohman59a1c932011-12-12 19:42:25 +00003105
3106 // Use reverse-postorder on the reverse CFG for bottom-up.
John McCall9fbd3182011-06-15 23:37:01 +00003107 bool BottomUpNestingDetected = false;
Dan Gohmanb48ef3a2011-08-18 21:27:42 +00003108 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
Dan Gohman59a1c932011-12-12 19:42:25 +00003109 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
3110 I != E; ++I)
3111 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
John McCall9fbd3182011-06-15 23:37:01 +00003112
Dan Gohman59a1c932011-12-12 19:42:25 +00003113 // Use reverse-postorder for top-down.
John McCall9fbd3182011-06-15 23:37:01 +00003114 bool TopDownNestingDetected = false;
Dan Gohman59a1c932011-12-12 19:42:25 +00003115 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
3116 PostOrder.rbegin(), E = PostOrder.rend();
3117 I != E; ++I)
3118 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
John McCall9fbd3182011-06-15 23:37:01 +00003119
3120 return TopDownNestingDetected && BottomUpNestingDetected;
3121}
3122
3123/// MoveCalls - Move the calls in RetainsToMove and ReleasesToMove.
3124void ObjCARCOpt::MoveCalls(Value *Arg,
3125 RRInfo &RetainsToMove,
3126 RRInfo &ReleasesToMove,
3127 MapVector<Value *, RRInfo> &Retains,
3128 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman44280692011-07-22 22:29:21 +00003129 SmallVectorImpl<Instruction *> &DeadInsts,
3130 Module *M) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003131 Type *ArgTy = Arg->getType();
Dan Gohman44280692011-07-22 22:29:21 +00003132 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
John McCall9fbd3182011-06-15 23:37:01 +00003133
3134 // Insert the new retain and release calls.
3135 for (SmallPtrSet<Instruction *, 2>::const_iterator
3136 PI = ReleasesToMove.ReverseInsertPts.begin(),
3137 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
3138 Instruction *InsertPt = *PI;
3139 Value *MyArg = ArgTy == ParamTy ? Arg :
3140 new BitCastInst(Arg, ParamTy, "", InsertPt);
3141 CallInst *Call =
3142 CallInst::Create(RetainsToMove.IsRetainBlock ?
Dan Gohman44280692011-07-22 22:29:21 +00003143 getRetainBlockCallee(M) : getRetainCallee(M),
John McCall9fbd3182011-06-15 23:37:01 +00003144 MyArg, "", InsertPt);
3145 Call->setDoesNotThrow();
Dan Gohman79522dc2012-01-13 00:39:07 +00003146 if (RetainsToMove.IsRetainBlock)
Dan Gohmana974bea2011-10-17 22:53:25 +00003147 Call->setMetadata(CopyOnEscapeMDKind,
3148 MDNode::get(M->getContext(), ArrayRef<Value *>()));
Dan Gohman79522dc2012-01-13 00:39:07 +00003149 else
John McCall9fbd3182011-06-15 23:37:01 +00003150 Call->setTailCall();
3151 }
3152 for (SmallPtrSet<Instruction *, 2>::const_iterator
3153 PI = RetainsToMove.ReverseInsertPts.begin(),
3154 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
Dan Gohmanfbab4a82012-03-23 17:47:54 +00003155 Instruction *InsertPt = *PI;
3156 Value *MyArg = ArgTy == ParamTy ? Arg :
3157 new BitCastInst(Arg, ParamTy, "", InsertPt);
3158 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
3159 "", InsertPt);
3160 // Attach a clang.imprecise_release metadata tag, if appropriate.
3161 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
3162 Call->setMetadata(ImpreciseReleaseMDKind, M);
3163 Call->setDoesNotThrow();
3164 if (ReleasesToMove.IsTailCallRelease)
3165 Call->setTailCall();
John McCall9fbd3182011-06-15 23:37:01 +00003166 }
3167
3168 // Delete the original retain and release calls.
3169 for (SmallPtrSet<Instruction *, 2>::const_iterator
3170 AI = RetainsToMove.Calls.begin(),
3171 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
3172 Instruction *OrigRetain = *AI;
3173 Retains.blot(OrigRetain);
3174 DeadInsts.push_back(OrigRetain);
3175 }
3176 for (SmallPtrSet<Instruction *, 2>::const_iterator
3177 AI = ReleasesToMove.Calls.begin(),
3178 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
3179 Instruction *OrigRelease = *AI;
3180 Releases.erase(OrigRelease);
3181 DeadInsts.push_back(OrigRelease);
3182 }
3183}
3184
Dan Gohmand6bf2012012-04-13 18:57:48 +00003185/// PerformCodePlacement - Identify pairings between the retains and releases,
3186/// and delete and/or move them.
John McCall9fbd3182011-06-15 23:37:01 +00003187bool
3188ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
3189 &BBStates,
3190 MapVector<Value *, RRInfo> &Retains,
Dan Gohman44280692011-07-22 22:29:21 +00003191 DenseMap<Value *, RRInfo> &Releases,
3192 Module *M) {
John McCall9fbd3182011-06-15 23:37:01 +00003193 bool AnyPairsCompletelyEliminated = false;
3194 RRInfo RetainsToMove;
3195 RRInfo ReleasesToMove;
3196 SmallVector<Instruction *, 4> NewRetains;
3197 SmallVector<Instruction *, 4> NewReleases;
3198 SmallVector<Instruction *, 8> DeadInsts;
3199
Dan Gohmand6bf2012012-04-13 18:57:48 +00003200 // Visit each retain.
John McCall9fbd3182011-06-15 23:37:01 +00003201 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
Dan Gohman597fece2011-09-29 22:25:23 +00003202 E = Retains.end(); I != E; ++I) {
3203 Value *V = I->first;
John McCall9fbd3182011-06-15 23:37:01 +00003204 if (!V) continue; // blotted
3205
3206 Instruction *Retain = cast<Instruction>(V);
3207 Value *Arg = GetObjCArg(Retain);
3208
Dan Gohman79522dc2012-01-13 00:39:07 +00003209 // If the object being released is in static or stack storage, we know it's
John McCall9fbd3182011-06-15 23:37:01 +00003210 // not being managed by ObjC reference counting, so we can delete pairs
3211 // regardless of what possible decrements or uses lie between them.
Dan Gohman79522dc2012-01-13 00:39:07 +00003212 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
Dan Gohman0daef3d2012-05-08 23:39:44 +00003213
Dan Gohman1b31ea82011-08-22 17:29:11 +00003214 // A constant pointer can't be pointing to an object on the heap. It may
3215 // be reference-counted, but it won't be deleted.
3216 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
3217 if (const GlobalVariable *GV =
3218 dyn_cast<GlobalVariable>(
3219 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
3220 if (GV->isConstant())
3221 KnownSafe = true;
3222
John McCall9fbd3182011-06-15 23:37:01 +00003223 // If a pair happens in a region where it is known that the reference count
3224 // is already incremented, we can similarly ignore possible decrements.
Dan Gohmane6d5e882011-08-19 00:26:36 +00003225 bool KnownSafeTD = true, KnownSafeBU = true;
John McCall9fbd3182011-06-15 23:37:01 +00003226
3227 // Connect the dots between the top-down-collected RetainsToMove and
3228 // bottom-up-collected ReleasesToMove to form sets of related calls.
3229 // This is an iterative process so that we connect multiple releases
3230 // to multiple retains if needed.
3231 unsigned OldDelta = 0;
3232 unsigned NewDelta = 0;
3233 unsigned OldCount = 0;
3234 unsigned NewCount = 0;
3235 bool FirstRelease = true;
3236 bool FirstRetain = true;
3237 NewRetains.push_back(Retain);
3238 for (;;) {
3239 for (SmallVectorImpl<Instruction *>::const_iterator
3240 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
3241 Instruction *NewRetain = *NI;
3242 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
3243 assert(It != Retains.end());
3244 const RRInfo &NewRetainRRI = It->second;
Dan Gohmane6d5e882011-08-19 00:26:36 +00003245 KnownSafeTD &= NewRetainRRI.KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00003246 for (SmallPtrSet<Instruction *, 2>::const_iterator
3247 LI = NewRetainRRI.Calls.begin(),
3248 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
3249 Instruction *NewRetainRelease = *LI;
3250 DenseMap<Value *, RRInfo>::const_iterator Jt =
3251 Releases.find(NewRetainRelease);
3252 if (Jt == Releases.end())
3253 goto next_retain;
3254 const RRInfo &NewRetainReleaseRRI = Jt->second;
3255 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
3256 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
3257 OldDelta -=
3258 BBStates[NewRetainRelease->getParent()].GetAllPathCount();
3259
3260 // Merge the ReleaseMetadata and IsTailCallRelease values.
3261 if (FirstRelease) {
3262 ReleasesToMove.ReleaseMetadata =
3263 NewRetainReleaseRRI.ReleaseMetadata;
3264 ReleasesToMove.IsTailCallRelease =
3265 NewRetainReleaseRRI.IsTailCallRelease;
3266 FirstRelease = false;
3267 } else {
3268 if (ReleasesToMove.ReleaseMetadata !=
3269 NewRetainReleaseRRI.ReleaseMetadata)
3270 ReleasesToMove.ReleaseMetadata = 0;
3271 if (ReleasesToMove.IsTailCallRelease !=
3272 NewRetainReleaseRRI.IsTailCallRelease)
3273 ReleasesToMove.IsTailCallRelease = false;
3274 }
3275
3276 // Collect the optimal insertion points.
3277 if (!KnownSafe)
3278 for (SmallPtrSet<Instruction *, 2>::const_iterator
3279 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
3280 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
3281 RI != RE; ++RI) {
3282 Instruction *RIP = *RI;
3283 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
3284 NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
3285 }
3286 NewReleases.push_back(NewRetainRelease);
3287 }
3288 }
3289 }
3290 NewRetains.clear();
3291 if (NewReleases.empty()) break;
3292
3293 // Back the other way.
3294 for (SmallVectorImpl<Instruction *>::const_iterator
3295 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
3296 Instruction *NewRelease = *NI;
3297 DenseMap<Value *, RRInfo>::const_iterator It =
3298 Releases.find(NewRelease);
3299 assert(It != Releases.end());
3300 const RRInfo &NewReleaseRRI = It->second;
Dan Gohmane6d5e882011-08-19 00:26:36 +00003301 KnownSafeBU &= NewReleaseRRI.KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00003302 for (SmallPtrSet<Instruction *, 2>::const_iterator
3303 LI = NewReleaseRRI.Calls.begin(),
3304 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
3305 Instruction *NewReleaseRetain = *LI;
3306 MapVector<Value *, RRInfo>::const_iterator Jt =
3307 Retains.find(NewReleaseRetain);
3308 if (Jt == Retains.end())
3309 goto next_retain;
3310 const RRInfo &NewReleaseRetainRRI = Jt->second;
3311 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
3312 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
3313 unsigned PathCount =
3314 BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
3315 OldDelta += PathCount;
3316 OldCount += PathCount;
3317
3318 // Merge the IsRetainBlock values.
3319 if (FirstRetain) {
3320 RetainsToMove.IsRetainBlock = NewReleaseRetainRRI.IsRetainBlock;
3321 FirstRetain = false;
3322 } else if (ReleasesToMove.IsRetainBlock !=
3323 NewReleaseRetainRRI.IsRetainBlock)
3324 // It's not possible to merge the sequences if one uses
3325 // objc_retain and the other uses objc_retainBlock.
3326 goto next_retain;
3327
3328 // Collect the optimal insertion points.
3329 if (!KnownSafe)
3330 for (SmallPtrSet<Instruction *, 2>::const_iterator
3331 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
3332 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
3333 RI != RE; ++RI) {
3334 Instruction *RIP = *RI;
3335 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
3336 PathCount = BBStates[RIP->getParent()].GetAllPathCount();
3337 NewDelta += PathCount;
3338 NewCount += PathCount;
3339 }
3340 }
3341 NewRetains.push_back(NewReleaseRetain);
3342 }
3343 }
3344 }
3345 NewReleases.clear();
3346 if (NewRetains.empty()) break;
3347 }
3348
Dan Gohmane6d5e882011-08-19 00:26:36 +00003349 // If the pointer is known incremented or nested, we can safely delete the
3350 // pair regardless of what's between them.
3351 if (KnownSafeTD || KnownSafeBU) {
John McCall9fbd3182011-06-15 23:37:01 +00003352 RetainsToMove.ReverseInsertPts.clear();
3353 ReleasesToMove.ReverseInsertPts.clear();
3354 NewCount = 0;
Dan Gohmana7f7db22011-08-12 00:26:31 +00003355 } else {
3356 // Determine whether the new insertion points we computed preserve the
3357 // balance of retain and release calls through the program.
3358 // TODO: If the fully aggressive solution isn't valid, try to find a
3359 // less aggressive solution which is.
3360 if (NewDelta != 0)
3361 goto next_retain;
John McCall9fbd3182011-06-15 23:37:01 +00003362 }
3363
3364 // Determine whether the original call points are balanced in the retain and
3365 // release calls through the program. If not, conservatively don't touch
3366 // them.
3367 // TODO: It's theoretically possible to do code motion in this case, as
3368 // long as the existing imbalances are maintained.
3369 if (OldDelta != 0)
3370 goto next_retain;
3371
John McCall9fbd3182011-06-15 23:37:01 +00003372 // Ok, everything checks out and we're all set. Let's move some code!
3373 Changed = true;
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003374 assert(OldCount != 0 && "Unreachable code?");
3375 AnyPairsCompletelyEliminated = NewCount == 0;
John McCall9fbd3182011-06-15 23:37:01 +00003376 NumRRs += OldCount - NewCount;
Dan Gohman44280692011-07-22 22:29:21 +00003377 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
3378 Retains, Releases, DeadInsts, M);
John McCall9fbd3182011-06-15 23:37:01 +00003379
3380 next_retain:
3381 NewReleases.clear();
3382 NewRetains.clear();
3383 RetainsToMove.clear();
3384 ReleasesToMove.clear();
3385 }
3386
3387 // Now that we're done moving everything, we can delete the newly dead
3388 // instructions, as we no longer need them as insert points.
3389 while (!DeadInsts.empty())
3390 EraseInstruction(DeadInsts.pop_back_val());
3391
3392 return AnyPairsCompletelyEliminated;
3393}
3394
3395/// OptimizeWeakCalls - Weak pointer optimizations.
3396void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
3397 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
3398 // itself because it uses AliasAnalysis and we need to do provenance
3399 // queries instead.
3400 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3401 Instruction *Inst = &*I++;
3402 InstructionClass Class = GetBasicInstructionClass(Inst);
3403 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
3404 continue;
3405
3406 // Delete objc_loadWeak calls with no users.
3407 if (Class == IC_LoadWeak && Inst->use_empty()) {
3408 Inst->eraseFromParent();
3409 continue;
3410 }
3411
3412 // TODO: For now, just look for an earlier available version of this value
3413 // within the same block. Theoretically, we could do memdep-style non-local
3414 // analysis too, but that would want caching. A better approach would be to
3415 // use the technique that EarlyCSE uses.
3416 inst_iterator Current = llvm::prior(I);
3417 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
3418 for (BasicBlock::iterator B = CurrentBB->begin(),
3419 J = Current.getInstructionIterator();
3420 J != B; --J) {
3421 Instruction *EarlierInst = &*llvm::prior(J);
3422 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
3423 switch (EarlierClass) {
3424 case IC_LoadWeak:
3425 case IC_LoadWeakRetained: {
3426 // If this is loading from the same pointer, replace this load's value
3427 // with that one.
3428 CallInst *Call = cast<CallInst>(Inst);
3429 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3430 Value *Arg = Call->getArgOperand(0);
3431 Value *EarlierArg = EarlierCall->getArgOperand(0);
3432 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3433 case AliasAnalysis::MustAlias:
3434 Changed = true;
3435 // If the load has a builtin retain, insert a plain retain for it.
3436 if (Class == IC_LoadWeakRetained) {
3437 CallInst *CI =
3438 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3439 "", Call);
3440 CI->setTailCall();
3441 }
3442 // Zap the fully redundant load.
3443 Call->replaceAllUsesWith(EarlierCall);
3444 Call->eraseFromParent();
3445 goto clobbered;
3446 case AliasAnalysis::MayAlias:
3447 case AliasAnalysis::PartialAlias:
3448 goto clobbered;
3449 case AliasAnalysis::NoAlias:
3450 break;
3451 }
3452 break;
3453 }
3454 case IC_StoreWeak:
3455 case IC_InitWeak: {
3456 // If this is storing to the same pointer and has the same size etc.
3457 // replace this load's value with the stored value.
3458 CallInst *Call = cast<CallInst>(Inst);
3459 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3460 Value *Arg = Call->getArgOperand(0);
3461 Value *EarlierArg = EarlierCall->getArgOperand(0);
3462 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3463 case AliasAnalysis::MustAlias:
3464 Changed = true;
3465 // If the load has a builtin retain, insert a plain retain for it.
3466 if (Class == IC_LoadWeakRetained) {
3467 CallInst *CI =
3468 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3469 "", Call);
3470 CI->setTailCall();
3471 }
3472 // Zap the fully redundant load.
3473 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
3474 Call->eraseFromParent();
3475 goto clobbered;
3476 case AliasAnalysis::MayAlias:
3477 case AliasAnalysis::PartialAlias:
3478 goto clobbered;
3479 case AliasAnalysis::NoAlias:
3480 break;
3481 }
3482 break;
3483 }
3484 case IC_MoveWeak:
3485 case IC_CopyWeak:
3486 // TOOD: Grab the copied value.
3487 goto clobbered;
3488 case IC_AutoreleasepoolPush:
3489 case IC_None:
3490 case IC_User:
3491 // Weak pointers are only modified through the weak entry points
3492 // (and arbitrary calls, which could call the weak entry points).
3493 break;
3494 default:
3495 // Anything else could modify the weak pointer.
3496 goto clobbered;
3497 }
3498 }
3499 clobbered:;
3500 }
3501
3502 // Then, for each destroyWeak with an alloca operand, check to see if
3503 // the alloca and all its users can be zapped.
3504 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3505 Instruction *Inst = &*I++;
3506 InstructionClass Class = GetBasicInstructionClass(Inst);
3507 if (Class != IC_DestroyWeak)
3508 continue;
3509
3510 CallInst *Call = cast<CallInst>(Inst);
3511 Value *Arg = Call->getArgOperand(0);
3512 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
3513 for (Value::use_iterator UI = Alloca->use_begin(),
3514 UE = Alloca->use_end(); UI != UE; ++UI) {
Dan Gohman447989c2012-04-27 18:56:31 +00003515 const Instruction *UserInst = cast<Instruction>(*UI);
John McCall9fbd3182011-06-15 23:37:01 +00003516 switch (GetBasicInstructionClass(UserInst)) {
3517 case IC_InitWeak:
3518 case IC_StoreWeak:
3519 case IC_DestroyWeak:
3520 continue;
3521 default:
3522 goto done;
3523 }
3524 }
3525 Changed = true;
3526 for (Value::use_iterator UI = Alloca->use_begin(),
3527 UE = Alloca->use_end(); UI != UE; ) {
3528 CallInst *UserInst = cast<CallInst>(*UI++);
Dan Gohmance5d8b02012-05-18 22:17:29 +00003529 switch (GetBasicInstructionClass(UserInst)) {
3530 case IC_InitWeak:
3531 case IC_StoreWeak:
3532 // These functions return their second argument.
3533 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
3534 break;
3535 case IC_DestroyWeak:
3536 // No return value.
3537 break;
3538 default:
Dan Gohman4c8f9092012-05-21 17:41:28 +00003539 llvm_unreachable("alloca really is used!");
Dan Gohmance5d8b02012-05-18 22:17:29 +00003540 }
John McCall9fbd3182011-06-15 23:37:01 +00003541 UserInst->eraseFromParent();
3542 }
3543 Alloca->eraseFromParent();
3544 done:;
3545 }
3546 }
3547}
3548
3549/// OptimizeSequences - Identify program paths which execute sequences of
3550/// retains and releases which can be eliminated.
3551bool ObjCARCOpt::OptimizeSequences(Function &F) {
3552 /// Releases, Retains - These are used to store the results of the main flow
3553 /// analysis. These use Value* as the key instead of Instruction* so that the
3554 /// map stays valid when we get around to rewriting code and calls get
3555 /// replaced by arguments.
3556 DenseMap<Value *, RRInfo> Releases;
3557 MapVector<Value *, RRInfo> Retains;
3558
3559 /// BBStates, This is used during the traversal of the function to track the
3560 /// states for each identified object at each block.
3561 DenseMap<const BasicBlock *, BBState> BBStates;
3562
3563 // Analyze the CFG of the function, and all instructions.
3564 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
3565
3566 // Transform.
Dan Gohman44280692011-07-22 22:29:21 +00003567 return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) &&
3568 NestingDetected;
John McCall9fbd3182011-06-15 23:37:01 +00003569}
3570
3571/// OptimizeReturns - Look for this pattern:
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +00003572/// \code
John McCall9fbd3182011-06-15 23:37:01 +00003573/// %call = call i8* @something(...)
3574/// %2 = call i8* @objc_retain(i8* %call)
3575/// %3 = call i8* @objc_autorelease(i8* %2)
3576/// ret i8* %3
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +00003577/// \endcode
John McCall9fbd3182011-06-15 23:37:01 +00003578/// And delete the retain and autorelease.
3579///
3580/// Otherwise if it's just this:
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +00003581/// \code
John McCall9fbd3182011-06-15 23:37:01 +00003582/// %3 = call i8* @objc_autorelease(i8* %2)
3583/// ret i8* %3
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +00003584/// \endcode
John McCall9fbd3182011-06-15 23:37:01 +00003585/// convert the autorelease to autoreleaseRV.
3586void ObjCARCOpt::OptimizeReturns(Function &F) {
3587 if (!F.getReturnType()->isPointerTy())
3588 return;
3589
3590 SmallPtrSet<Instruction *, 4> DependingInstructions;
3591 SmallPtrSet<const BasicBlock *, 4> Visited;
3592 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3593 BasicBlock *BB = FI;
3594 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
3595 if (!Ret) continue;
3596
3597 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
3598 FindDependencies(NeedsPositiveRetainCount, Arg,
3599 BB, Ret, DependingInstructions, Visited, PA);
3600 if (DependingInstructions.size() != 1)
3601 goto next_block;
3602
3603 {
3604 CallInst *Autorelease =
3605 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3606 if (!Autorelease)
3607 goto next_block;
Dan Gohman0daef3d2012-05-08 23:39:44 +00003608 InstructionClass AutoreleaseClass = GetBasicInstructionClass(Autorelease);
John McCall9fbd3182011-06-15 23:37:01 +00003609 if (!IsAutorelease(AutoreleaseClass))
3610 goto next_block;
3611 if (GetObjCArg(Autorelease) != Arg)
3612 goto next_block;
3613
3614 DependingInstructions.clear();
3615 Visited.clear();
3616
3617 // Check that there is nothing that can affect the reference
3618 // count between the autorelease and the retain.
3619 FindDependencies(CanChangeRetainCount, Arg,
3620 BB, Autorelease, DependingInstructions, Visited, PA);
3621 if (DependingInstructions.size() != 1)
3622 goto next_block;
3623
3624 {
3625 CallInst *Retain =
3626 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3627
3628 // Check that we found a retain with the same argument.
3629 if (!Retain ||
3630 !IsRetain(GetBasicInstructionClass(Retain)) ||
3631 GetObjCArg(Retain) != Arg)
3632 goto next_block;
3633
3634 DependingInstructions.clear();
3635 Visited.clear();
3636
3637 // Convert the autorelease to an autoreleaseRV, since it's
3638 // returning the value.
3639 if (AutoreleaseClass == IC_Autorelease) {
3640 Autorelease->setCalledFunction(getAutoreleaseRVCallee(F.getParent()));
3641 AutoreleaseClass = IC_AutoreleaseRV;
3642 }
3643
3644 // Check that there is nothing that can affect the reference
3645 // count between the retain and the call.
Dan Gohman27e06662011-09-29 22:27:34 +00003646 // Note that Retain need not be in BB.
3647 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
John McCall9fbd3182011-06-15 23:37:01 +00003648 DependingInstructions, Visited, PA);
3649 if (DependingInstructions.size() != 1)
3650 goto next_block;
3651
3652 {
3653 CallInst *Call =
3654 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3655
3656 // Check that the pointer is the return value of the call.
3657 if (!Call || Arg != Call)
3658 goto next_block;
3659
3660 // Check that the call is a regular call.
3661 InstructionClass Class = GetBasicInstructionClass(Call);
3662 if (Class != IC_CallOrUser && Class != IC_Call)
3663 goto next_block;
3664
3665 // If so, we can zap the retain and autorelease.
3666 Changed = true;
3667 ++NumRets;
3668 EraseInstruction(Retain);
3669 EraseInstruction(Autorelease);
3670 }
3671 }
3672 }
3673
3674 next_block:
3675 DependingInstructions.clear();
3676 Visited.clear();
3677 }
3678}
3679
3680bool ObjCARCOpt::doInitialization(Module &M) {
3681 if (!EnableARCOpts)
3682 return false;
3683
Dan Gohmand6bf2012012-04-13 18:57:48 +00003684 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003685 Run = ModuleHasARC(M);
3686 if (!Run)
3687 return false;
3688
John McCall9fbd3182011-06-15 23:37:01 +00003689 // Identify the imprecise release metadata kind.
3690 ImpreciseReleaseMDKind =
3691 M.getContext().getMDKindID("clang.imprecise_release");
Dan Gohmana974bea2011-10-17 22:53:25 +00003692 CopyOnEscapeMDKind =
3693 M.getContext().getMDKindID("clang.arc.copy_on_escape");
Dan Gohmandbe266b2012-02-17 18:59:53 +00003694 NoObjCARCExceptionsMDKind =
3695 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
John McCall9fbd3182011-06-15 23:37:01 +00003696
John McCall9fbd3182011-06-15 23:37:01 +00003697 // Intuitively, objc_retain and others are nocapture, however in practice
3698 // they are not, because they return their argument value. And objc_release
Dan Gohman447989c2012-04-27 18:56:31 +00003699 // calls finalizers which can have arbitrary side effects.
John McCall9fbd3182011-06-15 23:37:01 +00003700
3701 // These are initialized lazily.
3702 RetainRVCallee = 0;
3703 AutoreleaseRVCallee = 0;
3704 ReleaseCallee = 0;
3705 RetainCallee = 0;
Dan Gohman44280692011-07-22 22:29:21 +00003706 RetainBlockCallee = 0;
John McCall9fbd3182011-06-15 23:37:01 +00003707 AutoreleaseCallee = 0;
3708
3709 return false;
3710}
3711
3712bool ObjCARCOpt::runOnFunction(Function &F) {
3713 if (!EnableARCOpts)
3714 return false;
3715
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003716 // If nothing in the Module uses ARC, don't do anything.
3717 if (!Run)
3718 return false;
3719
John McCall9fbd3182011-06-15 23:37:01 +00003720 Changed = false;
3721
3722 PA.setAA(&getAnalysis<AliasAnalysis>());
3723
3724 // This pass performs several distinct transformations. As a compile-time aid
3725 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3726 // library functions aren't declared.
3727
3728 // Preliminary optimizations. This also computs UsedInThisFunction.
3729 OptimizeIndividualCalls(F);
3730
3731 // Optimizations for weak pointers.
3732 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3733 (1 << IC_LoadWeakRetained) |
3734 (1 << IC_StoreWeak) |
3735 (1 << IC_InitWeak) |
3736 (1 << IC_CopyWeak) |
3737 (1 << IC_MoveWeak) |
3738 (1 << IC_DestroyWeak)))
3739 OptimizeWeakCalls(F);
3740
3741 // Optimizations for retain+release pairs.
3742 if (UsedInThisFunction & ((1 << IC_Retain) |
3743 (1 << IC_RetainRV) |
3744 (1 << IC_RetainBlock)))
3745 if (UsedInThisFunction & (1 << IC_Release))
3746 // Run OptimizeSequences until it either stops making changes or
3747 // no retain+release pair nesting is detected.
3748 while (OptimizeSequences(F)) {}
3749
3750 // Optimizations if objc_autorelease is used.
Dan Gohman0daef3d2012-05-08 23:39:44 +00003751 if (UsedInThisFunction & ((1 << IC_Autorelease) |
3752 (1 << IC_AutoreleaseRV)))
John McCall9fbd3182011-06-15 23:37:01 +00003753 OptimizeReturns(F);
3754
3755 return Changed;
3756}
3757
3758void ObjCARCOpt::releaseMemory() {
3759 PA.clear();
3760}
3761
3762//===----------------------------------------------------------------------===//
3763// ARC contraction.
3764//===----------------------------------------------------------------------===//
3765
3766// TODO: ObjCARCContract could insert PHI nodes when uses aren't
3767// dominated by single calls.
3768
3769#include "llvm/Operator.h"
3770#include "llvm/InlineAsm.h"
3771#include "llvm/Analysis/Dominators.h"
3772
3773STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed");
3774
3775namespace {
3776 /// ObjCARCContract - Late ARC optimizations. These change the IR in a way
3777 /// that makes it difficult to be analyzed by ObjCARCOpt, so it's run late.
3778 class ObjCARCContract : public FunctionPass {
3779 bool Changed;
3780 AliasAnalysis *AA;
3781 DominatorTree *DT;
3782 ProvenanceAnalysis PA;
3783
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003784 /// Run - A flag indicating whether this optimization pass should run.
3785 bool Run;
3786
John McCall9fbd3182011-06-15 23:37:01 +00003787 /// StoreStrongCallee, etc. - Declarations for ObjC runtime
3788 /// functions, for use in creating calls to them. These are initialized
3789 /// lazily to avoid cluttering up the Module with unused declarations.
3790 Constant *StoreStrongCallee,
3791 *RetainAutoreleaseCallee, *RetainAutoreleaseRVCallee;
3792
3793 /// RetainRVMarker - The inline asm string to insert between calls and
3794 /// RetainRV calls to make the optimization work on targets which need it.
3795 const MDString *RetainRVMarker;
3796
Dan Gohman0cdece42012-01-19 19:14:36 +00003797 /// StoreStrongCalls - The set of inserted objc_storeStrong calls. If
3798 /// at the end of walking the function we have found no alloca
3799 /// instructions, these calls can be marked "tail".
Dan Gohman0daef3d2012-05-08 23:39:44 +00003800 SmallPtrSet<CallInst *, 8> StoreStrongCalls;
Dan Gohman0cdece42012-01-19 19:14:36 +00003801
John McCall9fbd3182011-06-15 23:37:01 +00003802 Constant *getStoreStrongCallee(Module *M);
3803 Constant *getRetainAutoreleaseCallee(Module *M);
3804 Constant *getRetainAutoreleaseRVCallee(Module *M);
3805
3806 bool ContractAutorelease(Function &F, Instruction *Autorelease,
3807 InstructionClass Class,
3808 SmallPtrSet<Instruction *, 4>
3809 &DependingInstructions,
3810 SmallPtrSet<const BasicBlock *, 4>
3811 &Visited);
3812
3813 void ContractRelease(Instruction *Release,
3814 inst_iterator &Iter);
3815
3816 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
3817 virtual bool doInitialization(Module &M);
3818 virtual bool runOnFunction(Function &F);
3819
3820 public:
3821 static char ID;
3822 ObjCARCContract() : FunctionPass(ID) {
3823 initializeObjCARCContractPass(*PassRegistry::getPassRegistry());
3824 }
3825 };
3826}
3827
3828char ObjCARCContract::ID = 0;
3829INITIALIZE_PASS_BEGIN(ObjCARCContract,
3830 "objc-arc-contract", "ObjC ARC contraction", false, false)
3831INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3832INITIALIZE_PASS_DEPENDENCY(DominatorTree)
3833INITIALIZE_PASS_END(ObjCARCContract,
3834 "objc-arc-contract", "ObjC ARC contraction", false, false)
3835
3836Pass *llvm::createObjCARCContractPass() {
3837 return new ObjCARCContract();
3838}
3839
3840void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const {
3841 AU.addRequired<AliasAnalysis>();
3842 AU.addRequired<DominatorTree>();
3843 AU.setPreservesCFG();
3844}
3845
3846Constant *ObjCARCContract::getStoreStrongCallee(Module *M) {
3847 if (!StoreStrongCallee) {
3848 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00003849 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3850 Type *I8XX = PointerType::getUnqual(I8X);
Dan Gohman0daef3d2012-05-08 23:39:44 +00003851 Type *Params[] = { I8XX, I8X };
John McCall9fbd3182011-06-15 23:37:01 +00003852
Bill Wendling3fa57092012-10-09 00:51:40 +00003853 Attributes::Builder BNoUnwind;
Bill Wendling2e879bc2012-10-09 09:11:20 +00003854 BNoUnwind.addAttribute(Attributes::NoUnwind);
Bill Wendling3fa57092012-10-09 00:51:40 +00003855 Attributes::Builder BNoCapture;
Bill Wendling2e879bc2012-10-09 09:11:20 +00003856 BNoCapture.addAttribute(Attributes::NoCapture);
Bill Wendling3fa57092012-10-09 00:51:40 +00003857 AttrListPtr Attributes = AttrListPtr()
Bill Wendling07aae2e2012-10-15 07:29:08 +00003858 .addAttr(M->getContext(), AttrListPtr::FunctionIndex,
3859 Attributes::get(C, BNoUnwind))
Bill Wendlingcb3de0b2012-10-15 04:46:55 +00003860 .addAttr(M->getContext(), 1, Attributes::get(C, BNoCapture));
John McCall9fbd3182011-06-15 23:37:01 +00003861
3862 StoreStrongCallee =
3863 M->getOrInsertFunction(
3864 "objc_storeStrong",
3865 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
3866 Attributes);
3867 }
3868 return StoreStrongCallee;
3869}
3870
3871Constant *ObjCARCContract::getRetainAutoreleaseCallee(Module *M) {
3872 if (!RetainAutoreleaseCallee) {
3873 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00003874 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman0daef3d2012-05-08 23:39:44 +00003875 Type *Params[] = { I8X };
3876 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendlingc40abb02012-10-09 00:47:36 +00003877 Attributes::Builder B;
Bill Wendling2e879bc2012-10-09 09:11:20 +00003878 B.addAttribute(Attributes::NoUnwind);
Bill Wendling07aae2e2012-10-15 07:29:08 +00003879 AttrListPtr Attributes =
3880 AttrListPtr().addAttr(M->getContext(), AttrListPtr::FunctionIndex,
3881 Attributes::get(C, B));
John McCall9fbd3182011-06-15 23:37:01 +00003882 RetainAutoreleaseCallee =
3883 M->getOrInsertFunction("objc_retainAutorelease", FTy, Attributes);
3884 }
3885 return RetainAutoreleaseCallee;
3886}
3887
3888Constant *ObjCARCContract::getRetainAutoreleaseRVCallee(Module *M) {
3889 if (!RetainAutoreleaseRVCallee) {
3890 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00003891 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman0daef3d2012-05-08 23:39:44 +00003892 Type *Params[] = { I8X };
3893 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendlingc40abb02012-10-09 00:47:36 +00003894 Attributes::Builder B;
Bill Wendling2e879bc2012-10-09 09:11:20 +00003895 B.addAttribute(Attributes::NoUnwind);
Bill Wendling07aae2e2012-10-15 07:29:08 +00003896 AttrListPtr Attributes =
3897 AttrListPtr().addAttr(M->getContext(), AttrListPtr::FunctionIndex,
3898 Attributes::get(C, B));
John McCall9fbd3182011-06-15 23:37:01 +00003899 RetainAutoreleaseRVCallee =
3900 M->getOrInsertFunction("objc_retainAutoreleaseReturnValue", FTy,
3901 Attributes);
3902 }
3903 return RetainAutoreleaseRVCallee;
3904}
3905
Dan Gohman447989c2012-04-27 18:56:31 +00003906/// ContractAutorelease - Merge an autorelease with a retain into a fused call.
John McCall9fbd3182011-06-15 23:37:01 +00003907bool
3908ObjCARCContract::ContractAutorelease(Function &F, Instruction *Autorelease,
3909 InstructionClass Class,
3910 SmallPtrSet<Instruction *, 4>
3911 &DependingInstructions,
3912 SmallPtrSet<const BasicBlock *, 4>
3913 &Visited) {
3914 const Value *Arg = GetObjCArg(Autorelease);
3915
3916 // Check that there are no instructions between the retain and the autorelease
3917 // (such as an autorelease_pop) which may change the count.
3918 CallInst *Retain = 0;
3919 if (Class == IC_AutoreleaseRV)
3920 FindDependencies(RetainAutoreleaseRVDep, Arg,
3921 Autorelease->getParent(), Autorelease,
3922 DependingInstructions, Visited, PA);
3923 else
3924 FindDependencies(RetainAutoreleaseDep, Arg,
3925 Autorelease->getParent(), Autorelease,
3926 DependingInstructions, Visited, PA);
3927
3928 Visited.clear();
3929 if (DependingInstructions.size() != 1) {
3930 DependingInstructions.clear();
3931 return false;
3932 }
3933
3934 Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3935 DependingInstructions.clear();
3936
3937 if (!Retain ||
3938 GetBasicInstructionClass(Retain) != IC_Retain ||
3939 GetObjCArg(Retain) != Arg)
3940 return false;
3941
3942 Changed = true;
3943 ++NumPeeps;
3944
3945 if (Class == IC_AutoreleaseRV)
3946 Retain->setCalledFunction(getRetainAutoreleaseRVCallee(F.getParent()));
3947 else
3948 Retain->setCalledFunction(getRetainAutoreleaseCallee(F.getParent()));
3949
3950 EraseInstruction(Autorelease);
3951 return true;
3952}
3953
3954/// ContractRelease - Attempt to merge an objc_release with a store, load, and
3955/// objc_retain to form an objc_storeStrong. This can be a little tricky because
3956/// the instructions don't always appear in order, and there may be unrelated
3957/// intervening instructions.
3958void ObjCARCContract::ContractRelease(Instruction *Release,
3959 inst_iterator &Iter) {
3960 LoadInst *Load = dyn_cast<LoadInst>(GetObjCArg(Release));
Eli Friedman2bc3d522011-09-12 20:23:13 +00003961 if (!Load || !Load->isSimple()) return;
John McCall9fbd3182011-06-15 23:37:01 +00003962
3963 // For now, require everything to be in one basic block.
3964 BasicBlock *BB = Release->getParent();
3965 if (Load->getParent() != BB) return;
3966
Dan Gohman4670dac2012-05-08 23:34:08 +00003967 // Walk down to find the store and the release, which may be in either order.
Dan Gohman95b8cf12012-05-09 23:08:33 +00003968 BasicBlock::iterator I = Load, End = BB->end();
John McCall9fbd3182011-06-15 23:37:01 +00003969 ++I;
3970 AliasAnalysis::Location Loc = AA->getLocation(Load);
Dan Gohman4670dac2012-05-08 23:34:08 +00003971 StoreInst *Store = 0;
3972 bool SawRelease = false;
3973 for (; !Store || !SawRelease; ++I) {
Dan Gohman95b8cf12012-05-09 23:08:33 +00003974 if (I == End)
3975 return;
3976
Dan Gohman4670dac2012-05-08 23:34:08 +00003977 Instruction *Inst = I;
3978 if (Inst == Release) {
3979 SawRelease = true;
3980 continue;
3981 }
3982
3983 InstructionClass Class = GetBasicInstructionClass(Inst);
3984
3985 // Unrelated retains are harmless.
3986 if (IsRetain(Class))
3987 continue;
3988
3989 if (Store) {
3990 // The store is the point where we're going to put the objc_storeStrong,
3991 // so make sure there are no uses after it.
3992 if (CanUse(Inst, Load, PA, Class))
3993 return;
3994 } else if (AA->getModRefInfo(Inst, Loc) & AliasAnalysis::Mod) {
3995 // We are moving the load down to the store, so check for anything
3996 // else which writes to the memory between the load and the store.
3997 Store = dyn_cast<StoreInst>(Inst);
3998 if (!Store || !Store->isSimple()) return;
3999 if (Store->getPointerOperand() != Loc.Ptr) return;
4000 }
4001 }
John McCall9fbd3182011-06-15 23:37:01 +00004002
4003 Value *New = StripPointerCastsAndObjCCalls(Store->getValueOperand());
4004
4005 // Walk up to find the retain.
4006 I = Store;
4007 BasicBlock::iterator Begin = BB->begin();
4008 while (I != Begin && GetBasicInstructionClass(I) != IC_Retain)
4009 --I;
4010 Instruction *Retain = I;
4011 if (GetBasicInstructionClass(Retain) != IC_Retain) return;
4012 if (GetObjCArg(Retain) != New) return;
4013
4014 Changed = true;
4015 ++NumStoreStrongs;
4016
4017 LLVMContext &C = Release->getContext();
Chris Lattnerdb125cf2011-07-18 04:54:35 +00004018 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
4019 Type *I8XX = PointerType::getUnqual(I8X);
John McCall9fbd3182011-06-15 23:37:01 +00004020
4021 Value *Args[] = { Load->getPointerOperand(), New };
4022 if (Args[0]->getType() != I8XX)
4023 Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
4024 if (Args[1]->getType() != I8X)
4025 Args[1] = new BitCastInst(Args[1], I8X, "", Store);
4026 CallInst *StoreStrong =
4027 CallInst::Create(getStoreStrongCallee(BB->getParent()->getParent()),
Jay Foada3efbb12011-07-15 08:37:34 +00004028 Args, "", Store);
John McCall9fbd3182011-06-15 23:37:01 +00004029 StoreStrong->setDoesNotThrow();
4030 StoreStrong->setDebugLoc(Store->getDebugLoc());
4031
Dan Gohman0cdece42012-01-19 19:14:36 +00004032 // We can't set the tail flag yet, because we haven't yet determined
4033 // whether there are any escaping allocas. Remember this call, so that
4034 // we can set the tail flag once we know it's safe.
4035 StoreStrongCalls.insert(StoreStrong);
4036
John McCall9fbd3182011-06-15 23:37:01 +00004037 if (&*Iter == Store) ++Iter;
4038 Store->eraseFromParent();
4039 Release->eraseFromParent();
4040 EraseInstruction(Retain);
4041 if (Load->use_empty())
4042 Load->eraseFromParent();
4043}
4044
4045bool ObjCARCContract::doInitialization(Module &M) {
Dan Gohmand6bf2012012-04-13 18:57:48 +00004046 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00004047 Run = ModuleHasARC(M);
4048 if (!Run)
4049 return false;
4050
John McCall9fbd3182011-06-15 23:37:01 +00004051 // These are initialized lazily.
4052 StoreStrongCallee = 0;
4053 RetainAutoreleaseCallee = 0;
4054 RetainAutoreleaseRVCallee = 0;
4055
4056 // Initialize RetainRVMarker.
4057 RetainRVMarker = 0;
4058 if (NamedMDNode *NMD =
4059 M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker"))
4060 if (NMD->getNumOperands() == 1) {
4061 const MDNode *N = NMD->getOperand(0);
4062 if (N->getNumOperands() == 1)
4063 if (const MDString *S = dyn_cast<MDString>(N->getOperand(0)))
4064 RetainRVMarker = S;
4065 }
4066
4067 return false;
4068}
4069
4070bool ObjCARCContract::runOnFunction(Function &F) {
4071 if (!EnableARCOpts)
4072 return false;
4073
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00004074 // If nothing in the Module uses ARC, don't do anything.
4075 if (!Run)
4076 return false;
4077
John McCall9fbd3182011-06-15 23:37:01 +00004078 Changed = false;
4079 AA = &getAnalysis<AliasAnalysis>();
4080 DT = &getAnalysis<DominatorTree>();
4081
4082 PA.setAA(&getAnalysis<AliasAnalysis>());
4083
Dan Gohman0cdece42012-01-19 19:14:36 +00004084 // Track whether it's ok to mark objc_storeStrong calls with the "tail"
4085 // keyword. Be conservative if the function has variadic arguments.
4086 // It seems that functions which "return twice" are also unsafe for the
4087 // "tail" argument, because they are setjmp, which could need to
4088 // return to an earlier stack state.
Dan Gohman0daef3d2012-05-08 23:39:44 +00004089 bool TailOkForStoreStrongs = !F.isVarArg() &&
4090 !F.callsFunctionThatReturnsTwice();
Dan Gohman0cdece42012-01-19 19:14:36 +00004091
John McCall9fbd3182011-06-15 23:37:01 +00004092 // For ObjC library calls which return their argument, replace uses of the
4093 // argument with uses of the call return value, if it dominates the use. This
4094 // reduces register pressure.
4095 SmallPtrSet<Instruction *, 4> DependingInstructions;
4096 SmallPtrSet<const BasicBlock *, 4> Visited;
4097 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
4098 Instruction *Inst = &*I++;
4099
4100 // Only these library routines return their argument. In particular,
4101 // objc_retainBlock does not necessarily return its argument.
4102 InstructionClass Class = GetBasicInstructionClass(Inst);
4103 switch (Class) {
4104 case IC_Retain:
4105 case IC_FusedRetainAutorelease:
4106 case IC_FusedRetainAutoreleaseRV:
4107 break;
4108 case IC_Autorelease:
4109 case IC_AutoreleaseRV:
4110 if (ContractAutorelease(F, Inst, Class, DependingInstructions, Visited))
4111 continue;
4112 break;
4113 case IC_RetainRV: {
4114 // If we're compiling for a target which needs a special inline-asm
4115 // marker to do the retainAutoreleasedReturnValue optimization,
4116 // insert it now.
4117 if (!RetainRVMarker)
4118 break;
4119 BasicBlock::iterator BBI = Inst;
Dan Gohman58fb3402012-06-25 19:47:37 +00004120 BasicBlock *InstParent = Inst->getParent();
4121
4122 // Step up to see if the call immediately precedes the RetainRV call.
4123 // If it's an invoke, we have to cross a block boundary. And we have
4124 // to carefully dodge no-op instructions.
4125 do {
4126 if (&*BBI == InstParent->begin()) {
4127 BasicBlock *Pred = InstParent->getSinglePredecessor();
4128 if (!Pred)
4129 goto decline_rv_optimization;
4130 BBI = Pred->getTerminator();
4131 break;
4132 }
4133 --BBI;
4134 } while (isNoopInstruction(BBI));
4135
John McCall9fbd3182011-06-15 23:37:01 +00004136 if (&*BBI == GetObjCArg(Inst)) {
Dan Gohmand6bf2012012-04-13 18:57:48 +00004137 Changed = true;
John McCall9fbd3182011-06-15 23:37:01 +00004138 InlineAsm *IA =
4139 InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()),
4140 /*isVarArg=*/false),
4141 RetainRVMarker->getString(),
4142 /*Constraints=*/"", /*hasSideEffects=*/true);
4143 CallInst::Create(IA, "", Inst);
4144 }
Dan Gohman58fb3402012-06-25 19:47:37 +00004145 decline_rv_optimization:
John McCall9fbd3182011-06-15 23:37:01 +00004146 break;
4147 }
4148 case IC_InitWeak: {
4149 // objc_initWeak(p, null) => *p = null
4150 CallInst *CI = cast<CallInst>(Inst);
4151 if (isNullOrUndef(CI->getArgOperand(1))) {
4152 Value *Null =
4153 ConstantPointerNull::get(cast<PointerType>(CI->getType()));
4154 Changed = true;
4155 new StoreInst(Null, CI->getArgOperand(0), CI);
4156 CI->replaceAllUsesWith(Null);
4157 CI->eraseFromParent();
4158 }
4159 continue;
4160 }
4161 case IC_Release:
4162 ContractRelease(Inst, I);
4163 continue;
Dan Gohman0cdece42012-01-19 19:14:36 +00004164 case IC_User:
4165 // Be conservative if the function has any alloca instructions.
4166 // Technically we only care about escaping alloca instructions,
4167 // but this is sufficient to handle some interesting cases.
4168 if (isa<AllocaInst>(Inst))
4169 TailOkForStoreStrongs = false;
4170 continue;
John McCall9fbd3182011-06-15 23:37:01 +00004171 default:
4172 continue;
4173 }
4174
4175 // Don't use GetObjCArg because we don't want to look through bitcasts
4176 // and such; to do the replacement, the argument must have type i8*.
4177 const Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
4178 for (;;) {
4179 // If we're compiling bugpointed code, don't get in trouble.
4180 if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
4181 break;
4182 // Look through the uses of the pointer.
4183 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
4184 UI != UE; ) {
4185 Use &U = UI.getUse();
4186 unsigned OperandNo = UI.getOperandNo();
4187 ++UI; // Increment UI now, because we may unlink its element.
Dan Gohmand6bf2012012-04-13 18:57:48 +00004188
4189 // If the call's return value dominates a use of the call's argument
4190 // value, rewrite the use to use the return value. We check for
4191 // reachability here because an unreachable call is considered to
4192 // trivially dominate itself, which would lead us to rewriting its
4193 // argument in terms of its return value, which would lead to
4194 // infinite loops in GetObjCArg.
Dan Gohman0daef3d2012-05-08 23:39:44 +00004195 if (DT->isReachableFromEntry(U) && DT->dominates(Inst, U)) {
Rafael Espindola2453dff2012-03-15 15:52:59 +00004196 Changed = true;
4197 Instruction *Replacement = Inst;
4198 Type *UseTy = U.get()->getType();
Dan Gohman6c189ec2012-04-13 01:08:28 +00004199 if (PHINode *PHI = dyn_cast<PHINode>(U.getUser())) {
Rafael Espindola2453dff2012-03-15 15:52:59 +00004200 // For PHI nodes, insert the bitcast in the predecessor block.
Dan Gohman0daef3d2012-05-08 23:39:44 +00004201 unsigned ValNo = PHINode::getIncomingValueNumForOperand(OperandNo);
4202 BasicBlock *BB = PHI->getIncomingBlock(ValNo);
Rafael Espindola2453dff2012-03-15 15:52:59 +00004203 if (Replacement->getType() != UseTy)
4204 Replacement = new BitCastInst(Replacement, UseTy, "",
4205 &BB->back());
Dan Gohmand6bf2012012-04-13 18:57:48 +00004206 // While we're here, rewrite all edges for this PHI, rather
4207 // than just one use at a time, to minimize the number of
4208 // bitcasts we emit.
Dan Gohman447989c2012-04-27 18:56:31 +00004209 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
Rafael Espindola2453dff2012-03-15 15:52:59 +00004210 if (PHI->getIncomingBlock(i) == BB) {
4211 // Keep the UI iterator valid.
4212 if (&PHI->getOperandUse(
4213 PHINode::getOperandNumForIncomingValue(i)) ==
4214 &UI.getUse())
4215 ++UI;
4216 PHI->setIncomingValue(i, Replacement);
4217 }
4218 } else {
4219 if (Replacement->getType() != UseTy)
Dan Gohman6c189ec2012-04-13 01:08:28 +00004220 Replacement = new BitCastInst(Replacement, UseTy, "",
4221 cast<Instruction>(U.getUser()));
Rafael Espindola2453dff2012-03-15 15:52:59 +00004222 U.set(Replacement);
John McCall9fbd3182011-06-15 23:37:01 +00004223 }
Rafael Espindola2453dff2012-03-15 15:52:59 +00004224 }
John McCall9fbd3182011-06-15 23:37:01 +00004225 }
4226
Dan Gohman447989c2012-04-27 18:56:31 +00004227 // If Arg is a no-op casted pointer, strip one level of casts and iterate.
John McCall9fbd3182011-06-15 23:37:01 +00004228 if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
4229 Arg = BI->getOperand(0);
4230 else if (isa<GEPOperator>(Arg) &&
4231 cast<GEPOperator>(Arg)->hasAllZeroIndices())
4232 Arg = cast<GEPOperator>(Arg)->getPointerOperand();
4233 else if (isa<GlobalAlias>(Arg) &&
4234 !cast<GlobalAlias>(Arg)->mayBeOverridden())
4235 Arg = cast<GlobalAlias>(Arg)->getAliasee();
4236 else
4237 break;
4238 }
4239 }
4240
Dan Gohman0cdece42012-01-19 19:14:36 +00004241 // If this function has no escaping allocas or suspicious vararg usage,
4242 // objc_storeStrong calls can be marked with the "tail" keyword.
4243 if (TailOkForStoreStrongs)
Dan Gohman0daef3d2012-05-08 23:39:44 +00004244 for (SmallPtrSet<CallInst *, 8>::iterator I = StoreStrongCalls.begin(),
Dan Gohman0cdece42012-01-19 19:14:36 +00004245 E = StoreStrongCalls.end(); I != E; ++I)
4246 (*I)->setTailCall();
4247 StoreStrongCalls.clear();
4248
John McCall9fbd3182011-06-15 23:37:01 +00004249 return Changed;
4250}