blob: 9fd68e62445b0472da64c60169bd8252cc10568b [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
1124 // Do not implement.
1125 void operator=(const ProvenanceAnalysis &);
1126 ProvenanceAnalysis(const ProvenanceAnalysis &);
1127
1128 public:
1129 ProvenanceAnalysis() {}
1130
1131 void setAA(AliasAnalysis *aa) { AA = aa; }
1132
1133 AliasAnalysis *getAA() const { return AA; }
1134
1135 bool related(const Value *A, const Value *B);
1136
1137 void clear() {
1138 CachedResults.clear();
1139 }
1140 };
1141}
1142
1143bool ProvenanceAnalysis::relatedSelect(const SelectInst *A, const Value *B) {
1144 // If the values are Selects with the same condition, we can do a more precise
1145 // check: just check for relations between the values on corresponding arms.
1146 if (const SelectInst *SB = dyn_cast<SelectInst>(B))
Dan Gohman447989c2012-04-27 18:56:31 +00001147 if (A->getCondition() == SB->getCondition())
1148 return related(A->getTrueValue(), SB->getTrueValue()) ||
1149 related(A->getFalseValue(), SB->getFalseValue());
John McCall9fbd3182011-06-15 23:37:01 +00001150
1151 // Check both arms of the Select node individually.
Dan Gohman447989c2012-04-27 18:56:31 +00001152 return related(A->getTrueValue(), B) ||
1153 related(A->getFalseValue(), B);
John McCall9fbd3182011-06-15 23:37:01 +00001154}
1155
1156bool ProvenanceAnalysis::relatedPHI(const PHINode *A, const Value *B) {
1157 // If the values are PHIs in the same block, we can do a more precise as well
1158 // as efficient check: just check for relations between the values on
1159 // corresponding edges.
1160 if (const PHINode *PNB = dyn_cast<PHINode>(B))
1161 if (PNB->getParent() == A->getParent()) {
1162 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i)
1163 if (related(A->getIncomingValue(i),
1164 PNB->getIncomingValueForBlock(A->getIncomingBlock(i))))
1165 return true;
1166 return false;
1167 }
1168
1169 // Check each unique source of the PHI node against B.
1170 SmallPtrSet<const Value *, 4> UniqueSrc;
1171 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i) {
1172 const Value *PV1 = A->getIncomingValue(i);
1173 if (UniqueSrc.insert(PV1) && related(PV1, B))
1174 return true;
1175 }
1176
1177 // All of the arms checked out.
1178 return false;
1179}
1180
1181/// isStoredObjCPointer - Test if the value of P, or any value covered by its
1182/// provenance, is ever stored within the function (not counting callees).
1183static bool isStoredObjCPointer(const Value *P) {
1184 SmallPtrSet<const Value *, 8> Visited;
1185 SmallVector<const Value *, 8> Worklist;
1186 Worklist.push_back(P);
1187 Visited.insert(P);
1188 do {
1189 P = Worklist.pop_back_val();
1190 for (Value::const_use_iterator UI = P->use_begin(), UE = P->use_end();
1191 UI != UE; ++UI) {
1192 const User *Ur = *UI;
1193 if (isa<StoreInst>(Ur)) {
1194 if (UI.getOperandNo() == 0)
1195 // The pointer is stored.
1196 return true;
1197 // The pointed is stored through.
1198 continue;
1199 }
1200 if (isa<CallInst>(Ur))
1201 // The pointer is passed as an argument, ignore this.
1202 continue;
1203 if (isa<PtrToIntInst>(P))
1204 // Assume the worst.
1205 return true;
1206 if (Visited.insert(Ur))
1207 Worklist.push_back(Ur);
1208 }
1209 } while (!Worklist.empty());
1210
1211 // Everything checked out.
1212 return false;
1213}
1214
1215bool ProvenanceAnalysis::relatedCheck(const Value *A, const Value *B) {
1216 // Skip past provenance pass-throughs.
1217 A = GetUnderlyingObjCPtr(A);
1218 B = GetUnderlyingObjCPtr(B);
1219
1220 // Quick check.
1221 if (A == B)
1222 return true;
1223
1224 // Ask regular AliasAnalysis, for a first approximation.
1225 switch (AA->alias(A, B)) {
1226 case AliasAnalysis::NoAlias:
1227 return false;
1228 case AliasAnalysis::MustAlias:
1229 case AliasAnalysis::PartialAlias:
1230 return true;
1231 case AliasAnalysis::MayAlias:
1232 break;
1233 }
1234
1235 bool AIsIdentified = IsObjCIdentifiedObject(A);
1236 bool BIsIdentified = IsObjCIdentifiedObject(B);
1237
1238 // An ObjC-Identified object can't alias a load if it is never locally stored.
1239 if (AIsIdentified) {
Dan Gohman230768b2012-09-04 23:16:20 +00001240 // Check for an obvious escape.
1241 if (isa<LoadInst>(B))
1242 return isStoredObjCPointer(A);
John McCall9fbd3182011-06-15 23:37:01 +00001243 if (BIsIdentified) {
Dan Gohman230768b2012-09-04 23:16:20 +00001244 // Check for an obvious escape.
1245 if (isa<LoadInst>(A))
1246 return isStoredObjCPointer(B);
1247 // Both pointers are identified and escapes aren't an evident problem.
1248 return false;
John McCall9fbd3182011-06-15 23:37:01 +00001249 }
Dan Gohman230768b2012-09-04 23:16:20 +00001250 } else if (BIsIdentified) {
1251 // Check for an obvious escape.
1252 if (isa<LoadInst>(A))
John McCall9fbd3182011-06-15 23:37:01 +00001253 return isStoredObjCPointer(B);
1254 }
1255
1256 // Special handling for PHI and Select.
1257 if (const PHINode *PN = dyn_cast<PHINode>(A))
1258 return relatedPHI(PN, B);
1259 if (const PHINode *PN = dyn_cast<PHINode>(B))
1260 return relatedPHI(PN, A);
1261 if (const SelectInst *S = dyn_cast<SelectInst>(A))
1262 return relatedSelect(S, B);
1263 if (const SelectInst *S = dyn_cast<SelectInst>(B))
1264 return relatedSelect(S, A);
1265
1266 // Conservative.
1267 return true;
1268}
1269
1270bool ProvenanceAnalysis::related(const Value *A, const Value *B) {
1271 // Begin by inserting a conservative value into the map. If the insertion
1272 // fails, we have the answer already. If it succeeds, leave it there until we
1273 // compute the real answer to guard against recursive queries.
1274 if (A > B) std::swap(A, B);
1275 std::pair<CachedResultsTy::iterator, bool> Pair =
1276 CachedResults.insert(std::make_pair(ValuePairTy(A, B), true));
1277 if (!Pair.second)
1278 return Pair.first->second;
1279
1280 bool Result = relatedCheck(A, B);
1281 CachedResults[ValuePairTy(A, B)] = Result;
1282 return Result;
1283}
1284
1285namespace {
1286 // Sequence - A sequence of states that a pointer may go through in which an
1287 // objc_retain and objc_release are actually needed.
1288 enum Sequence {
1289 S_None,
1290 S_Retain, ///< objc_retain(x)
1291 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement
1292 S_Use, ///< any use of x
1293 S_Stop, ///< like S_Release, but code motion is stopped
1294 S_Release, ///< objc_release(x)
1295 S_MovableRelease ///< objc_release(x), !clang.imprecise_release
1296 };
1297}
1298
1299static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
1300 // The easy cases.
1301 if (A == B)
1302 return A;
1303 if (A == S_None || B == S_None)
1304 return S_None;
1305
John McCall9fbd3182011-06-15 23:37:01 +00001306 if (A > B) std::swap(A, B);
1307 if (TopDown) {
1308 // Choose the side which is further along in the sequence.
Dan Gohmana7f7db22011-08-12 00:26:31 +00001309 if ((A == S_Retain || A == S_CanRelease) &&
1310 (B == S_CanRelease || B == S_Use))
John McCall9fbd3182011-06-15 23:37:01 +00001311 return B;
1312 } else {
1313 // Choose the side which is further along in the sequence.
1314 if ((A == S_Use || A == S_CanRelease) &&
Dan Gohmana7f7db22011-08-12 00:26:31 +00001315 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
John McCall9fbd3182011-06-15 23:37:01 +00001316 return A;
1317 // If both sides are releases, choose the more conservative one.
1318 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
1319 return A;
1320 if (A == S_Release && B == S_MovableRelease)
1321 return A;
1322 }
1323
1324 return S_None;
1325}
1326
1327namespace {
1328 /// RRInfo - Unidirectional information about either a
1329 /// retain-decrement-use-release sequence or release-use-decrement-retain
1330 /// reverese sequence.
1331 struct RRInfo {
Dan Gohmane6d5e882011-08-19 00:26:36 +00001332 /// KnownSafe - After an objc_retain, the reference count of the referenced
1333 /// object is known to be positive. Similarly, before an objc_release, the
1334 /// reference count of the referenced object is known to be positive. If
1335 /// there are retain-release pairs in code regions where the retain count
1336 /// is known to be positive, they can be eliminated, regardless of any side
1337 /// effects between them.
1338 ///
1339 /// Also, a retain+release pair nested within another retain+release
1340 /// pair all on the known same pointer value can be eliminated, regardless
1341 /// of any intervening side effects.
1342 ///
1343 /// KnownSafe is true when either of these conditions is satisfied.
1344 bool KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00001345
1346 /// IsRetainBlock - True if the Calls are objc_retainBlock calls (as
1347 /// opposed to objc_retain calls).
1348 bool IsRetainBlock;
1349
1350 /// IsTailCallRelease - True of the objc_release calls are all marked
1351 /// with the "tail" keyword.
1352 bool IsTailCallRelease;
1353
1354 /// ReleaseMetadata - If the Calls are objc_release calls and they all have
1355 /// a clang.imprecise_release tag, this is the metadata tag.
1356 MDNode *ReleaseMetadata;
1357
1358 /// Calls - For a top-down sequence, the set of objc_retains or
1359 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
1360 SmallPtrSet<Instruction *, 2> Calls;
1361
1362 /// ReverseInsertPts - The set of optimal insert positions for
1363 /// moving calls in the opposite sequence.
1364 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
1365
1366 RRInfo() :
Dan Gohman79522dc2012-01-13 00:39:07 +00001367 KnownSafe(false), IsRetainBlock(false),
Dan Gohman50ade652012-04-25 00:50:46 +00001368 IsTailCallRelease(false),
John McCall9fbd3182011-06-15 23:37:01 +00001369 ReleaseMetadata(0) {}
1370
1371 void clear();
1372 };
1373}
1374
1375void RRInfo::clear() {
Dan Gohmane6d5e882011-08-19 00:26:36 +00001376 KnownSafe = false;
John McCall9fbd3182011-06-15 23:37:01 +00001377 IsRetainBlock = false;
1378 IsTailCallRelease = false;
1379 ReleaseMetadata = 0;
1380 Calls.clear();
1381 ReverseInsertPts.clear();
1382}
1383
1384namespace {
1385 /// PtrState - This class summarizes several per-pointer runtime properties
1386 /// which are propogated through the flow graph.
1387 class PtrState {
Dan Gohman50ade652012-04-25 00:50:46 +00001388 /// KnownPositiveRefCount - True if the reference count is known to
1389 /// be incremented.
1390 bool KnownPositiveRefCount;
1391
1392 /// Partial - True of we've seen an opportunity for partial RR elimination,
1393 /// such as pushing calls into a CFG triangle or into one side of a
1394 /// CFG diamond.
1395 bool Partial;
John McCall9fbd3182011-06-15 23:37:01 +00001396
1397 /// Seq - The current position in the sequence.
Dan Gohman0daef3d2012-05-08 23:39:44 +00001398 Sequence Seq : 8;
John McCall9fbd3182011-06-15 23:37:01 +00001399
1400 public:
1401 /// RRI - Unidirectional information about the current sequence.
1402 /// TODO: Encapsulate this better.
1403 RRInfo RRI;
1404
Dan Gohman230768b2012-09-04 23:16:20 +00001405 PtrState() : KnownPositiveRefCount(false), Partial(false),
Dan Gohman0daef3d2012-05-08 23:39:44 +00001406 Seq(S_None) {}
John McCall9fbd3182011-06-15 23:37:01 +00001407
Dan Gohman50ade652012-04-25 00:50:46 +00001408 void SetKnownPositiveRefCount() {
1409 KnownPositiveRefCount = true;
Dan Gohmana7f7db22011-08-12 00:26:31 +00001410 }
1411
Dan Gohman50ade652012-04-25 00:50:46 +00001412 void ClearRefCount() {
1413 KnownPositiveRefCount = false;
John McCall9fbd3182011-06-15 23:37:01 +00001414 }
1415
John McCall9fbd3182011-06-15 23:37:01 +00001416 bool IsKnownIncremented() const {
Dan Gohman50ade652012-04-25 00:50:46 +00001417 return KnownPositiveRefCount;
John McCall9fbd3182011-06-15 23:37:01 +00001418 }
1419
1420 void SetSeq(Sequence NewSeq) {
1421 Seq = NewSeq;
1422 }
1423
John McCall9fbd3182011-06-15 23:37:01 +00001424 Sequence GetSeq() const {
1425 return Seq;
1426 }
1427
1428 void ClearSequenceProgress() {
Dan Gohman50ade652012-04-25 00:50:46 +00001429 ResetSequenceProgress(S_None);
1430 }
1431
1432 void ResetSequenceProgress(Sequence NewSeq) {
1433 Seq = NewSeq;
1434 Partial = false;
John McCall9fbd3182011-06-15 23:37:01 +00001435 RRI.clear();
1436 }
1437
1438 void Merge(const PtrState &Other, bool TopDown);
1439 };
1440}
1441
1442void
1443PtrState::Merge(const PtrState &Other, bool TopDown) {
1444 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
Dan Gohman50ade652012-04-25 00:50:46 +00001445 KnownPositiveRefCount = KnownPositiveRefCount && Other.KnownPositiveRefCount;
John McCall9fbd3182011-06-15 23:37:01 +00001446
1447 // We can't merge a plain objc_retain with an objc_retainBlock.
1448 if (RRI.IsRetainBlock != Other.RRI.IsRetainBlock)
1449 Seq = S_None;
1450
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001451 // If we're not in a sequence (anymore), drop all associated state.
John McCall9fbd3182011-06-15 23:37:01 +00001452 if (Seq == S_None) {
Dan Gohman50ade652012-04-25 00:50:46 +00001453 Partial = false;
John McCall9fbd3182011-06-15 23:37:01 +00001454 RRI.clear();
Dan Gohman50ade652012-04-25 00:50:46 +00001455 } else if (Partial || Other.Partial) {
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001456 // If we're doing a merge on a path that's previously seen a partial
1457 // merge, conservatively drop the sequence, to avoid doing partial
1458 // RR elimination. If the branch predicates for the two merge differ,
1459 // mixing them is unsafe.
Dan Gohman50ade652012-04-25 00:50:46 +00001460 ClearSequenceProgress();
John McCall9fbd3182011-06-15 23:37:01 +00001461 } else {
1462 // Conservatively merge the ReleaseMetadata information.
1463 if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
1464 RRI.ReleaseMetadata = 0;
1465
Dan Gohmane6d5e882011-08-19 00:26:36 +00001466 RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
Dan Gohman0daef3d2012-05-08 23:39:44 +00001467 RRI.IsTailCallRelease = RRI.IsTailCallRelease &&
1468 Other.RRI.IsTailCallRelease;
John McCall9fbd3182011-06-15 23:37:01 +00001469 RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001470
1471 // Merge the insert point sets. If there are any differences,
1472 // that makes this a partial merge.
Dan Gohman0daef3d2012-05-08 23:39:44 +00001473 Partial = RRI.ReverseInsertPts.size() != Other.RRI.ReverseInsertPts.size();
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001474 for (SmallPtrSet<Instruction *, 2>::const_iterator
1475 I = Other.RRI.ReverseInsertPts.begin(),
1476 E = Other.RRI.ReverseInsertPts.end(); I != E; ++I)
Dan Gohman50ade652012-04-25 00:50:46 +00001477 Partial |= RRI.ReverseInsertPts.insert(*I);
John McCall9fbd3182011-06-15 23:37:01 +00001478 }
1479}
1480
1481namespace {
1482 /// BBState - Per-BasicBlock state.
1483 class BBState {
1484 /// TopDownPathCount - The number of unique control paths from the entry
1485 /// which can reach this block.
1486 unsigned TopDownPathCount;
1487
1488 /// BottomUpPathCount - The number of unique control paths to exits
1489 /// from this block.
1490 unsigned BottomUpPathCount;
1491
1492 /// MapTy - A type for PerPtrTopDown and PerPtrBottomUp.
1493 typedef MapVector<const Value *, PtrState> MapTy;
1494
1495 /// PerPtrTopDown - The top-down traversal uses this to record information
1496 /// known about a pointer at the bottom of each block.
1497 MapTy PerPtrTopDown;
1498
1499 /// PerPtrBottomUp - The bottom-up traversal uses this to record information
1500 /// known about a pointer at the top of each block.
1501 MapTy PerPtrBottomUp;
1502
Dan Gohmaneeeb7752012-04-24 22:53:18 +00001503 /// Preds, Succs - Effective successors and predecessors of the current
1504 /// block (this ignores ignorable edges and ignored backedges).
1505 SmallVector<BasicBlock *, 2> Preds;
1506 SmallVector<BasicBlock *, 2> Succs;
1507
John McCall9fbd3182011-06-15 23:37:01 +00001508 public:
1509 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
1510
1511 typedef MapTy::iterator ptr_iterator;
1512 typedef MapTy::const_iterator ptr_const_iterator;
1513
1514 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
1515 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
1516 ptr_const_iterator top_down_ptr_begin() const {
1517 return PerPtrTopDown.begin();
1518 }
1519 ptr_const_iterator top_down_ptr_end() const {
1520 return PerPtrTopDown.end();
1521 }
1522
1523 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
1524 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
1525 ptr_const_iterator bottom_up_ptr_begin() const {
1526 return PerPtrBottomUp.begin();
1527 }
1528 ptr_const_iterator bottom_up_ptr_end() const {
1529 return PerPtrBottomUp.end();
1530 }
1531
1532 /// SetAsEntry - Mark this block as being an entry block, which has one
1533 /// path from the entry by definition.
1534 void SetAsEntry() { TopDownPathCount = 1; }
1535
1536 /// SetAsExit - Mark this block as being an exit block, which has one
1537 /// path to an exit by definition.
1538 void SetAsExit() { BottomUpPathCount = 1; }
1539
1540 PtrState &getPtrTopDownState(const Value *Arg) {
1541 return PerPtrTopDown[Arg];
1542 }
1543
1544 PtrState &getPtrBottomUpState(const Value *Arg) {
1545 return PerPtrBottomUp[Arg];
1546 }
1547
1548 void clearBottomUpPointers() {
Evan Chenga81388f2011-08-04 18:40:26 +00001549 PerPtrBottomUp.clear();
John McCall9fbd3182011-06-15 23:37:01 +00001550 }
1551
1552 void clearTopDownPointers() {
1553 PerPtrTopDown.clear();
1554 }
1555
1556 void InitFromPred(const BBState &Other);
1557 void InitFromSucc(const BBState &Other);
1558 void MergePred(const BBState &Other);
1559 void MergeSucc(const BBState &Other);
1560
1561 /// GetAllPathCount - Return the number of possible unique paths from an
1562 /// entry to an exit which pass through this block. This is only valid
1563 /// after both the top-down and bottom-up traversals are complete.
1564 unsigned GetAllPathCount() const {
Dan Gohmaneeeb7752012-04-24 22:53:18 +00001565 assert(TopDownPathCount != 0);
1566 assert(BottomUpPathCount != 0);
John McCall9fbd3182011-06-15 23:37:01 +00001567 return TopDownPathCount * BottomUpPathCount;
1568 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00001569
Dan Gohmaneeeb7752012-04-24 22:53:18 +00001570 // Specialized CFG utilities.
Dan Gohman447989c2012-04-27 18:56:31 +00001571 typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
Dan Gohmaneeeb7752012-04-24 22:53:18 +00001572 edge_iterator pred_begin() { return Preds.begin(); }
1573 edge_iterator pred_end() { return Preds.end(); }
1574 edge_iterator succ_begin() { return Succs.begin(); }
1575 edge_iterator succ_end() { return Succs.end(); }
1576
1577 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
1578 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
1579
1580 bool isExit() const { return Succs.empty(); }
John McCall9fbd3182011-06-15 23:37:01 +00001581 };
1582}
1583
1584void BBState::InitFromPred(const BBState &Other) {
1585 PerPtrTopDown = Other.PerPtrTopDown;
1586 TopDownPathCount = Other.TopDownPathCount;
1587}
1588
1589void BBState::InitFromSucc(const BBState &Other) {
1590 PerPtrBottomUp = Other.PerPtrBottomUp;
1591 BottomUpPathCount = Other.BottomUpPathCount;
1592}
1593
1594/// MergePred - The top-down traversal uses this to merge information about
1595/// predecessors to form the initial state for a new block.
1596void BBState::MergePred(const BBState &Other) {
1597 // Other.TopDownPathCount can be 0, in which case it is either dead or a
1598 // loop backedge. Loop backedges are special.
1599 TopDownPathCount += Other.TopDownPathCount;
1600
Dan Gohman0d1bc5f2012-09-12 20:45:17 +00001601 // Check for overflow. If we have overflow, fall back to conservative behavior.
1602 if (TopDownPathCount < Other.TopDownPathCount) {
1603 clearTopDownPointers();
1604 return;
1605 }
1606
John McCall9fbd3182011-06-15 23:37:01 +00001607 // For each entry in the other set, if our set has an entry with the same key,
1608 // merge the entries. Otherwise, copy the entry and merge it with an empty
1609 // entry.
1610 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
1611 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
1612 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
1613 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1614 /*TopDown=*/true);
1615 }
1616
Dan Gohmanfa7eed12011-08-11 21:06:32 +00001617 // For each entry in our set, if the other set doesn't have an entry with the
John McCall9fbd3182011-06-15 23:37:01 +00001618 // same key, force it to merge with an empty entry.
1619 for (ptr_iterator MI = top_down_ptr_begin(),
1620 ME = top_down_ptr_end(); MI != ME; ++MI)
1621 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
1622 MI->second.Merge(PtrState(), /*TopDown=*/true);
1623}
1624
1625/// MergeSucc - The bottom-up traversal uses this to merge information about
1626/// successors to form the initial state for a new block.
1627void BBState::MergeSucc(const BBState &Other) {
1628 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
1629 // loop backedge. Loop backedges are special.
1630 BottomUpPathCount += Other.BottomUpPathCount;
1631
Dan Gohman0d1bc5f2012-09-12 20:45:17 +00001632 // Check for overflow. If we have overflow, fall back to conservative behavior.
1633 if (BottomUpPathCount < Other.BottomUpPathCount) {
1634 clearBottomUpPointers();
1635 return;
1636 }
1637
John McCall9fbd3182011-06-15 23:37:01 +00001638 // For each entry in the other set, if our set has an entry with the
1639 // same key, merge the entries. Otherwise, copy the entry and merge
1640 // it with an empty entry.
1641 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
1642 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
1643 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
1644 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1645 /*TopDown=*/false);
1646 }
1647
Dan Gohmanfa7eed12011-08-11 21:06:32 +00001648 // For each entry in our set, if the other set doesn't have an entry
John McCall9fbd3182011-06-15 23:37:01 +00001649 // with the same key, force it to merge with an empty entry.
1650 for (ptr_iterator MI = bottom_up_ptr_begin(),
1651 ME = bottom_up_ptr_end(); MI != ME; ++MI)
1652 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
1653 MI->second.Merge(PtrState(), /*TopDown=*/false);
1654}
1655
1656namespace {
1657 /// ObjCARCOpt - The main ARC optimization pass.
1658 class ObjCARCOpt : public FunctionPass {
1659 bool Changed;
1660 ProvenanceAnalysis PA;
1661
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00001662 /// Run - A flag indicating whether this optimization pass should run.
1663 bool Run;
1664
John McCall9fbd3182011-06-15 23:37:01 +00001665 /// RetainRVCallee, etc. - Declarations for ObjC runtime
1666 /// functions, for use in creating calls to them. These are initialized
1667 /// lazily to avoid cluttering up the Module with unused declarations.
1668 Constant *RetainRVCallee, *AutoreleaseRVCallee, *ReleaseCallee,
Dan Gohman44280692011-07-22 22:29:21 +00001669 *RetainCallee, *RetainBlockCallee, *AutoreleaseCallee;
John McCall9fbd3182011-06-15 23:37:01 +00001670
1671 /// UsedInThisFunciton - Flags which determine whether each of the
1672 /// interesting runtine functions is in fact used in the current function.
1673 unsigned UsedInThisFunction;
1674
1675 /// ImpreciseReleaseMDKind - The Metadata Kind for clang.imprecise_release
1676 /// metadata.
1677 unsigned ImpreciseReleaseMDKind;
1678
Dan Gohman62e5b402011-12-12 18:20:00 +00001679 /// CopyOnEscapeMDKind - The Metadata Kind for clang.arc.copy_on_escape
Dan Gohmana974bea2011-10-17 22:53:25 +00001680 /// metadata.
1681 unsigned CopyOnEscapeMDKind;
1682
Dan Gohmandbe266b2012-02-17 18:59:53 +00001683 /// NoObjCARCExceptionsMDKind - The Metadata Kind for
1684 /// clang.arc.no_objc_arc_exceptions metadata.
1685 unsigned NoObjCARCExceptionsMDKind;
1686
John McCall9fbd3182011-06-15 23:37:01 +00001687 Constant *getRetainRVCallee(Module *M);
1688 Constant *getAutoreleaseRVCallee(Module *M);
1689 Constant *getReleaseCallee(Module *M);
1690 Constant *getRetainCallee(Module *M);
Dan Gohman44280692011-07-22 22:29:21 +00001691 Constant *getRetainBlockCallee(Module *M);
John McCall9fbd3182011-06-15 23:37:01 +00001692 Constant *getAutoreleaseCallee(Module *M);
1693
Dan Gohman79522dc2012-01-13 00:39:07 +00001694 bool IsRetainBlockOptimizable(const Instruction *Inst);
1695
John McCall9fbd3182011-06-15 23:37:01 +00001696 void OptimizeRetainCall(Function &F, Instruction *Retain);
1697 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
1698 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV);
1699 void OptimizeIndividualCalls(Function &F);
1700
1701 void CheckForCFGHazards(const BasicBlock *BB,
1702 DenseMap<const BasicBlock *, BBState> &BBStates,
1703 BBState &MyStates) const;
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00001704 bool VisitInstructionBottomUp(Instruction *Inst,
Dan Gohmanfbab4a82012-03-23 17:47:54 +00001705 BasicBlock *BB,
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00001706 MapVector<Value *, RRInfo> &Retains,
1707 BBState &MyStates);
John McCall9fbd3182011-06-15 23:37:01 +00001708 bool VisitBottomUp(BasicBlock *BB,
1709 DenseMap<const BasicBlock *, BBState> &BBStates,
1710 MapVector<Value *, RRInfo> &Retains);
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00001711 bool VisitInstructionTopDown(Instruction *Inst,
1712 DenseMap<Value *, RRInfo> &Releases,
1713 BBState &MyStates);
John McCall9fbd3182011-06-15 23:37:01 +00001714 bool VisitTopDown(BasicBlock *BB,
1715 DenseMap<const BasicBlock *, BBState> &BBStates,
1716 DenseMap<Value *, RRInfo> &Releases);
1717 bool Visit(Function &F,
1718 DenseMap<const BasicBlock *, BBState> &BBStates,
1719 MapVector<Value *, RRInfo> &Retains,
1720 DenseMap<Value *, RRInfo> &Releases);
1721
1722 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1723 MapVector<Value *, RRInfo> &Retains,
1724 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman44280692011-07-22 22:29:21 +00001725 SmallVectorImpl<Instruction *> &DeadInsts,
1726 Module *M);
John McCall9fbd3182011-06-15 23:37:01 +00001727
1728 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1729 MapVector<Value *, RRInfo> &Retains,
Dan Gohman44280692011-07-22 22:29:21 +00001730 DenseMap<Value *, RRInfo> &Releases,
1731 Module *M);
John McCall9fbd3182011-06-15 23:37:01 +00001732
1733 void OptimizeWeakCalls(Function &F);
1734
1735 bool OptimizeSequences(Function &F);
1736
1737 void OptimizeReturns(Function &F);
1738
1739 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1740 virtual bool doInitialization(Module &M);
1741 virtual bool runOnFunction(Function &F);
1742 virtual void releaseMemory();
1743
1744 public:
1745 static char ID;
1746 ObjCARCOpt() : FunctionPass(ID) {
1747 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1748 }
1749 };
1750}
1751
1752char ObjCARCOpt::ID = 0;
1753INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1754 "objc-arc", "ObjC ARC optimization", false, false)
1755INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1756INITIALIZE_PASS_END(ObjCARCOpt,
1757 "objc-arc", "ObjC ARC optimization", false, false)
1758
1759Pass *llvm::createObjCARCOptPass() {
1760 return new ObjCARCOpt();
1761}
1762
1763void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1764 AU.addRequired<ObjCARCAliasAnalysis>();
1765 AU.addRequired<AliasAnalysis>();
1766 // ARC optimization doesn't currently split critical edges.
1767 AU.setPreservesCFG();
1768}
1769
Dan Gohman79522dc2012-01-13 00:39:07 +00001770bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1771 // Without the magic metadata tag, we have to assume this might be an
1772 // objc_retainBlock call inserted to convert a block pointer to an id,
1773 // in which case it really is needed.
1774 if (!Inst->getMetadata(CopyOnEscapeMDKind))
1775 return false;
1776
1777 // If the pointer "escapes" (not including being used in a call),
1778 // the copy may be needed.
1779 if (DoesObjCBlockEscape(Inst))
1780 return false;
1781
1782 // Otherwise, it's not needed.
1783 return true;
1784}
1785
John McCall9fbd3182011-06-15 23:37:01 +00001786Constant *ObjCARCOpt::getRetainRVCallee(Module *M) {
1787 if (!RetainRVCallee) {
1788 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001789 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman0daef3d2012-05-08 23:39:44 +00001790 Type *Params[] = { I8X };
1791 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
1792 AttrListPtr Attributes = AttrListPtr().addAttr(~0u, Attribute::NoUnwind);
John McCall9fbd3182011-06-15 23:37:01 +00001793 RetainRVCallee =
1794 M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy,
1795 Attributes);
1796 }
1797 return RetainRVCallee;
1798}
1799
1800Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1801 if (!AutoreleaseRVCallee) {
1802 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001803 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman0daef3d2012-05-08 23:39:44 +00001804 Type *Params[] = { I8X };
1805 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
1806 AttrListPtr Attributes = AttrListPtr().addAttr(~0u, Attribute::NoUnwind);
John McCall9fbd3182011-06-15 23:37:01 +00001807 AutoreleaseRVCallee =
1808 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
1809 Attributes);
1810 }
1811 return AutoreleaseRVCallee;
1812}
1813
1814Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1815 if (!ReleaseCallee) {
1816 LLVMContext &C = M->getContext();
Dan Gohman0daef3d2012-05-08 23:39:44 +00001817 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1818 AttrListPtr Attributes = AttrListPtr().addAttr(~0u, Attribute::NoUnwind);
John McCall9fbd3182011-06-15 23:37:01 +00001819 ReleaseCallee =
1820 M->getOrInsertFunction(
1821 "objc_release",
1822 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
1823 Attributes);
1824 }
1825 return ReleaseCallee;
1826}
1827
1828Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1829 if (!RetainCallee) {
1830 LLVMContext &C = M->getContext();
Dan Gohman0daef3d2012-05-08 23:39:44 +00001831 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1832 AttrListPtr Attributes = AttrListPtr().addAttr(~0u, Attribute::NoUnwind);
John McCall9fbd3182011-06-15 23:37:01 +00001833 RetainCallee =
1834 M->getOrInsertFunction(
1835 "objc_retain",
1836 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1837 Attributes);
1838 }
1839 return RetainCallee;
1840}
1841
Dan Gohman44280692011-07-22 22:29:21 +00001842Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1843 if (!RetainBlockCallee) {
1844 LLVMContext &C = M->getContext();
Dan Gohman0daef3d2012-05-08 23:39:44 +00001845 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Dan Gohman1d2fd752011-09-14 18:33:34 +00001846 // objc_retainBlock is not nounwind because it calls user copy constructors
1847 // which could theoretically throw.
Dan Gohman44280692011-07-22 22:29:21 +00001848 RetainBlockCallee =
1849 M->getOrInsertFunction(
1850 "objc_retainBlock",
1851 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Dan Gohman0daef3d2012-05-08 23:39:44 +00001852 AttrListPtr());
Dan Gohman44280692011-07-22 22:29:21 +00001853 }
1854 return RetainBlockCallee;
1855}
1856
John McCall9fbd3182011-06-15 23:37:01 +00001857Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1858 if (!AutoreleaseCallee) {
1859 LLVMContext &C = M->getContext();
Dan Gohman0daef3d2012-05-08 23:39:44 +00001860 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1861 AttrListPtr Attributes = AttrListPtr().addAttr(~0u, Attribute::NoUnwind);
John McCall9fbd3182011-06-15 23:37:01 +00001862 AutoreleaseCallee =
1863 M->getOrInsertFunction(
1864 "objc_autorelease",
1865 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1866 Attributes);
1867 }
1868 return AutoreleaseCallee;
1869}
1870
Dan Gohman230768b2012-09-04 23:16:20 +00001871/// IsPotentialUse - Test whether the given value is possible a
1872/// reference-counted pointer, including tests which utilize AliasAnalysis.
1873static bool IsPotentialUse(const Value *Op, AliasAnalysis &AA) {
1874 // First make the rudimentary check.
1875 if (!IsPotentialUse(Op))
1876 return false;
1877
1878 // Objects in constant memory are not reference-counted.
1879 if (AA.pointsToConstantMemory(Op))
1880 return false;
1881
1882 // Pointers in constant memory are not pointing to reference-counted objects.
1883 if (const LoadInst *LI = dyn_cast<LoadInst>(Op))
1884 if (AA.pointsToConstantMemory(LI->getPointerOperand()))
1885 return false;
1886
1887 // Otherwise assume the worst.
1888 return true;
1889}
1890
John McCall9fbd3182011-06-15 23:37:01 +00001891/// CanAlterRefCount - Test whether the given instruction can result in a
1892/// reference count modification (positive or negative) for the pointer's
1893/// object.
1894static bool
1895CanAlterRefCount(const Instruction *Inst, const Value *Ptr,
1896 ProvenanceAnalysis &PA, InstructionClass Class) {
1897 switch (Class) {
1898 case IC_Autorelease:
1899 case IC_AutoreleaseRV:
1900 case IC_User:
1901 // These operations never directly modify a reference count.
1902 return false;
1903 default: break;
1904 }
1905
1906 ImmutableCallSite CS = static_cast<const Value *>(Inst);
1907 assert(CS && "Only calls can alter reference counts!");
1908
1909 // See if AliasAnalysis can help us with the call.
1910 AliasAnalysis::ModRefBehavior MRB = PA.getAA()->getModRefBehavior(CS);
1911 if (AliasAnalysis::onlyReadsMemory(MRB))
1912 return false;
1913 if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
1914 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1915 I != E; ++I) {
1916 const Value *Op = *I;
Dan Gohman230768b2012-09-04 23:16:20 +00001917 if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
John McCall9fbd3182011-06-15 23:37:01 +00001918 return true;
1919 }
1920 return false;
1921 }
1922
1923 // Assume the worst.
1924 return true;
1925}
1926
1927/// CanUse - Test whether the given instruction can "use" the given pointer's
1928/// object in a way that requires the reference count to be positive.
1929static bool
1930CanUse(const Instruction *Inst, const Value *Ptr, ProvenanceAnalysis &PA,
1931 InstructionClass Class) {
1932 // IC_Call operations (as opposed to IC_CallOrUser) never "use" objc pointers.
1933 if (Class == IC_Call)
1934 return false;
1935
1936 // Consider various instructions which may have pointer arguments which are
1937 // not "uses".
1938 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(Inst)) {
1939 // Comparing a pointer with null, or any other constant, isn't really a use,
1940 // because we don't care what the pointer points to, or about the values
1941 // of any other dynamic reference-counted pointers.
Dan Gohman230768b2012-09-04 23:16:20 +00001942 if (!IsPotentialUse(ICI->getOperand(1), *PA.getAA()))
John McCall9fbd3182011-06-15 23:37:01 +00001943 return false;
1944 } else if (ImmutableCallSite CS = static_cast<const Value *>(Inst)) {
1945 // For calls, just check the arguments (and not the callee operand).
1946 for (ImmutableCallSite::arg_iterator OI = CS.arg_begin(),
1947 OE = CS.arg_end(); OI != OE; ++OI) {
1948 const Value *Op = *OI;
Dan Gohman230768b2012-09-04 23:16:20 +00001949 if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
John McCall9fbd3182011-06-15 23:37:01 +00001950 return true;
1951 }
1952 return false;
1953 } else if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1954 // Special-case stores, because we don't care about the stored value, just
1955 // the store address.
1956 const Value *Op = GetUnderlyingObjCPtr(SI->getPointerOperand());
1957 // If we can't tell what the underlying object was, assume there is a
1958 // dependence.
Dan Gohman230768b2012-09-04 23:16:20 +00001959 return IsPotentialUse(Op, *PA.getAA()) && PA.related(Op, Ptr);
John McCall9fbd3182011-06-15 23:37:01 +00001960 }
1961
1962 // Check each operand for a match.
1963 for (User::const_op_iterator OI = Inst->op_begin(), OE = Inst->op_end();
1964 OI != OE; ++OI) {
1965 const Value *Op = *OI;
Dan Gohman230768b2012-09-04 23:16:20 +00001966 if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
John McCall9fbd3182011-06-15 23:37:01 +00001967 return true;
1968 }
1969 return false;
1970}
1971
1972/// CanInterruptRV - Test whether the given instruction can autorelease
1973/// any pointer or cause an autoreleasepool pop.
1974static bool
1975CanInterruptRV(InstructionClass Class) {
1976 switch (Class) {
1977 case IC_AutoreleasepoolPop:
1978 case IC_CallOrUser:
1979 case IC_Call:
1980 case IC_Autorelease:
1981 case IC_AutoreleaseRV:
1982 case IC_FusedRetainAutorelease:
1983 case IC_FusedRetainAutoreleaseRV:
1984 return true;
1985 default:
1986 return false;
1987 }
1988}
1989
1990namespace {
1991 /// DependenceKind - There are several kinds of dependence-like concepts in
1992 /// use here.
1993 enum DependenceKind {
1994 NeedsPositiveRetainCount,
Dan Gohman511568d2012-04-13 00:59:57 +00001995 AutoreleasePoolBoundary,
John McCall9fbd3182011-06-15 23:37:01 +00001996 CanChangeRetainCount,
1997 RetainAutoreleaseDep, ///< Blocks objc_retainAutorelease.
1998 RetainAutoreleaseRVDep, ///< Blocks objc_retainAutoreleaseReturnValue.
1999 RetainRVDep ///< Blocks objc_retainAutoreleasedReturnValue.
2000 };
2001}
2002
2003/// Depends - Test if there can be dependencies on Inst through Arg. This
2004/// function only tests dependencies relevant for removing pairs of calls.
2005static bool
2006Depends(DependenceKind Flavor, Instruction *Inst, const Value *Arg,
2007 ProvenanceAnalysis &PA) {
2008 // If we've reached the definition of Arg, stop.
2009 if (Inst == Arg)
2010 return true;
2011
2012 switch (Flavor) {
2013 case NeedsPositiveRetainCount: {
2014 InstructionClass Class = GetInstructionClass(Inst);
2015 switch (Class) {
2016 case IC_AutoreleasepoolPop:
2017 case IC_AutoreleasepoolPush:
2018 case IC_None:
2019 return false;
2020 default:
2021 return CanUse(Inst, Arg, PA, Class);
2022 }
2023 }
2024
Dan Gohman511568d2012-04-13 00:59:57 +00002025 case AutoreleasePoolBoundary: {
2026 InstructionClass Class = GetInstructionClass(Inst);
2027 switch (Class) {
2028 case IC_AutoreleasepoolPop:
2029 case IC_AutoreleasepoolPush:
2030 // These mark the end and begin of an autorelease pool scope.
2031 return true;
2032 default:
2033 // Nothing else does this.
2034 return false;
2035 }
2036 }
2037
John McCall9fbd3182011-06-15 23:37:01 +00002038 case CanChangeRetainCount: {
2039 InstructionClass Class = GetInstructionClass(Inst);
2040 switch (Class) {
2041 case IC_AutoreleasepoolPop:
2042 // Conservatively assume this can decrement any count.
2043 return true;
2044 case IC_AutoreleasepoolPush:
2045 case IC_None:
2046 return false;
2047 default:
2048 return CanAlterRefCount(Inst, Arg, PA, Class);
2049 }
2050 }
2051
2052 case RetainAutoreleaseDep:
2053 switch (GetBasicInstructionClass(Inst)) {
2054 case IC_AutoreleasepoolPop:
Dan Gohman511568d2012-04-13 00:59:57 +00002055 case IC_AutoreleasepoolPush:
John McCall9fbd3182011-06-15 23:37:01 +00002056 // Don't merge an objc_autorelease with an objc_retain inside a different
2057 // autoreleasepool scope.
2058 return true;
2059 case IC_Retain:
2060 case IC_RetainRV:
2061 // Check for a retain of the same pointer for merging.
2062 return GetObjCArg(Inst) == Arg;
2063 default:
2064 // Nothing else matters for objc_retainAutorelease formation.
2065 return false;
2066 }
John McCall9fbd3182011-06-15 23:37:01 +00002067
2068 case RetainAutoreleaseRVDep: {
2069 InstructionClass Class = GetBasicInstructionClass(Inst);
2070 switch (Class) {
2071 case IC_Retain:
2072 case IC_RetainRV:
2073 // Check for a retain of the same pointer for merging.
2074 return GetObjCArg(Inst) == Arg;
2075 default:
2076 // Anything that can autorelease interrupts
2077 // retainAutoreleaseReturnValue formation.
2078 return CanInterruptRV(Class);
2079 }
John McCall9fbd3182011-06-15 23:37:01 +00002080 }
2081
2082 case RetainRVDep:
2083 return CanInterruptRV(GetBasicInstructionClass(Inst));
2084 }
2085
2086 llvm_unreachable("Invalid dependence flavor");
John McCall9fbd3182011-06-15 23:37:01 +00002087}
2088
2089/// FindDependencies - Walk up the CFG from StartPos (which is in StartBB) and
2090/// find local and non-local dependencies on Arg.
2091/// TODO: Cache results?
2092static void
2093FindDependencies(DependenceKind Flavor,
2094 const Value *Arg,
2095 BasicBlock *StartBB, Instruction *StartInst,
2096 SmallPtrSet<Instruction *, 4> &DependingInstructions,
2097 SmallPtrSet<const BasicBlock *, 4> &Visited,
2098 ProvenanceAnalysis &PA) {
2099 BasicBlock::iterator StartPos = StartInst;
2100
2101 SmallVector<std::pair<BasicBlock *, BasicBlock::iterator>, 4> Worklist;
2102 Worklist.push_back(std::make_pair(StartBB, StartPos));
2103 do {
2104 std::pair<BasicBlock *, BasicBlock::iterator> Pair =
2105 Worklist.pop_back_val();
2106 BasicBlock *LocalStartBB = Pair.first;
2107 BasicBlock::iterator LocalStartPos = Pair.second;
2108 BasicBlock::iterator StartBBBegin = LocalStartBB->begin();
2109 for (;;) {
2110 if (LocalStartPos == StartBBBegin) {
2111 pred_iterator PI(LocalStartBB), PE(LocalStartBB, false);
2112 if (PI == PE)
2113 // If we've reached the function entry, produce a null dependence.
2114 DependingInstructions.insert(0);
2115 else
2116 // Add the predecessors to the worklist.
2117 do {
2118 BasicBlock *PredBB = *PI;
2119 if (Visited.insert(PredBB))
2120 Worklist.push_back(std::make_pair(PredBB, PredBB->end()));
2121 } while (++PI != PE);
2122 break;
2123 }
2124
2125 Instruction *Inst = --LocalStartPos;
2126 if (Depends(Flavor, Inst, Arg, PA)) {
2127 DependingInstructions.insert(Inst);
2128 break;
2129 }
2130 }
2131 } while (!Worklist.empty());
2132
2133 // Determine whether the original StartBB post-dominates all of the blocks we
2134 // visited. If not, insert a sentinal indicating that most optimizations are
2135 // not safe.
2136 for (SmallPtrSet<const BasicBlock *, 4>::const_iterator I = Visited.begin(),
2137 E = Visited.end(); I != E; ++I) {
2138 const BasicBlock *BB = *I;
2139 if (BB == StartBB)
2140 continue;
2141 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2142 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2143 const BasicBlock *Succ = *SI;
2144 if (Succ != StartBB && !Visited.count(Succ)) {
2145 DependingInstructions.insert(reinterpret_cast<Instruction *>(-1));
2146 return;
2147 }
2148 }
2149 }
2150}
2151
2152static bool isNullOrUndef(const Value *V) {
2153 return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
2154}
2155
2156static bool isNoopInstruction(const Instruction *I) {
2157 return isa<BitCastInst>(I) ||
2158 (isa<GetElementPtrInst>(I) &&
2159 cast<GetElementPtrInst>(I)->hasAllZeroIndices());
2160}
2161
2162/// OptimizeRetainCall - Turn objc_retain into
2163/// objc_retainAutoreleasedReturnValue if the operand is a return value.
2164void
2165ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) {
Dan Gohman447989c2012-04-27 18:56:31 +00002166 ImmutableCallSite CS(GetObjCArg(Retain));
2167 const Instruction *Call = CS.getInstruction();
John McCall9fbd3182011-06-15 23:37:01 +00002168 if (!Call) return;
2169 if (Call->getParent() != Retain->getParent()) return;
2170
2171 // Check that the call is next to the retain.
Dan Gohman447989c2012-04-27 18:56:31 +00002172 BasicBlock::const_iterator I = Call;
John McCall9fbd3182011-06-15 23:37:01 +00002173 ++I;
2174 while (isNoopInstruction(I)) ++I;
2175 if (&*I != Retain)
2176 return;
2177
2178 // Turn it to an objc_retainAutoreleasedReturnValue..
2179 Changed = true;
2180 ++NumPeeps;
2181 cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent()));
2182}
2183
2184/// OptimizeRetainRVCall - Turn objc_retainAutoreleasedReturnValue into
Dan Gohman447989c2012-04-27 18:56:31 +00002185/// objc_retain if the operand is not a return value. Or, if it can be paired
2186/// with an objc_autoreleaseReturnValue, delete the pair and return true.
John McCall9fbd3182011-06-15 23:37:01 +00002187bool
2188ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
Dan Gohman6fedb3c2012-03-23 18:09:00 +00002189 // Check for the argument being from an immediately preceding call or invoke.
Dan Gohman447989c2012-04-27 18:56:31 +00002190 const Value *Arg = GetObjCArg(RetainRV);
2191 ImmutableCallSite CS(Arg);
2192 if (const Instruction *Call = CS.getInstruction()) {
John McCall9fbd3182011-06-15 23:37:01 +00002193 if (Call->getParent() == RetainRV->getParent()) {
Dan Gohman447989c2012-04-27 18:56:31 +00002194 BasicBlock::const_iterator I = Call;
John McCall9fbd3182011-06-15 23:37:01 +00002195 ++I;
2196 while (isNoopInstruction(I)) ++I;
2197 if (&*I == RetainRV)
2198 return false;
Dan Gohman447989c2012-04-27 18:56:31 +00002199 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Dan Gohman6fedb3c2012-03-23 18:09:00 +00002200 BasicBlock *RetainRVParent = RetainRV->getParent();
2201 if (II->getNormalDest() == RetainRVParent) {
Dan Gohman447989c2012-04-27 18:56:31 +00002202 BasicBlock::const_iterator I = RetainRVParent->begin();
Dan Gohman6fedb3c2012-03-23 18:09:00 +00002203 while (isNoopInstruction(I)) ++I;
2204 if (&*I == RetainRV)
2205 return false;
2206 }
John McCall9fbd3182011-06-15 23:37:01 +00002207 }
Dan Gohman6fedb3c2012-03-23 18:09:00 +00002208 }
John McCall9fbd3182011-06-15 23:37:01 +00002209
2210 // Check for being preceded by an objc_autoreleaseReturnValue on the same
2211 // pointer. In this case, we can delete the pair.
2212 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
2213 if (I != Begin) {
2214 do --I; while (I != Begin && isNoopInstruction(I));
2215 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
2216 GetObjCArg(I) == Arg) {
2217 Changed = true;
2218 ++NumPeeps;
2219 EraseInstruction(I);
2220 EraseInstruction(RetainRV);
2221 return true;
2222 }
2223 }
2224
2225 // Turn it to a plain objc_retain.
2226 Changed = true;
2227 ++NumPeeps;
2228 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
2229 return false;
2230}
2231
2232/// OptimizeAutoreleaseRVCall - Turn objc_autoreleaseReturnValue into
2233/// objc_autorelease if the result is not used as a return value.
2234void
2235ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV) {
2236 // Check for a return of the pointer value.
2237 const Value *Ptr = GetObjCArg(AutoreleaseRV);
Dan Gohman126a54f2011-08-12 00:36:31 +00002238 SmallVector<const Value *, 2> Users;
2239 Users.push_back(Ptr);
2240 do {
2241 Ptr = Users.pop_back_val();
2242 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
2243 UI != UE; ++UI) {
2244 const User *I = *UI;
2245 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
2246 return;
2247 if (isa<BitCastInst>(I))
2248 Users.push_back(I);
2249 }
2250 } while (!Users.empty());
John McCall9fbd3182011-06-15 23:37:01 +00002251
2252 Changed = true;
2253 ++NumPeeps;
2254 cast<CallInst>(AutoreleaseRV)->
2255 setCalledFunction(getAutoreleaseCallee(F.getParent()));
2256}
2257
2258/// OptimizeIndividualCalls - Visit each call, one at a time, and make
2259/// simplifications without doing any additional analysis.
2260void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
2261 // Reset all the flags in preparation for recomputing them.
2262 UsedInThisFunction = 0;
2263
2264 // Visit all objc_* calls in F.
2265 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2266 Instruction *Inst = &*I++;
2267 InstructionClass Class = GetBasicInstructionClass(Inst);
2268
2269 switch (Class) {
2270 default: break;
2271
2272 // Delete no-op casts. These function calls have special semantics, but
2273 // the semantics are entirely implemented via lowering in the front-end,
2274 // so by the time they reach the optimizer, they are just no-op calls
2275 // which return their argument.
2276 //
2277 // There are gray areas here, as the ability to cast reference-counted
2278 // pointers to raw void* and back allows code to break ARC assumptions,
2279 // however these are currently considered to be unimportant.
2280 case IC_NoopCast:
2281 Changed = true;
2282 ++NumNoops;
2283 EraseInstruction(Inst);
2284 continue;
2285
2286 // If the pointer-to-weak-pointer is null, it's undefined behavior.
2287 case IC_StoreWeak:
2288 case IC_LoadWeak:
2289 case IC_LoadWeakRetained:
2290 case IC_InitWeak:
2291 case IC_DestroyWeak: {
2292 CallInst *CI = cast<CallInst>(Inst);
2293 if (isNullOrUndef(CI->getArgOperand(0))) {
Dan Gohmand6bf2012012-04-13 18:57:48 +00002294 Changed = true;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002295 Type *Ty = CI->getArgOperand(0)->getType();
John McCall9fbd3182011-06-15 23:37:01 +00002296 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2297 Constant::getNullValue(Ty),
2298 CI);
2299 CI->replaceAllUsesWith(UndefValue::get(CI->getType()));
2300 CI->eraseFromParent();
2301 continue;
2302 }
2303 break;
2304 }
2305 case IC_CopyWeak:
2306 case IC_MoveWeak: {
2307 CallInst *CI = cast<CallInst>(Inst);
2308 if (isNullOrUndef(CI->getArgOperand(0)) ||
2309 isNullOrUndef(CI->getArgOperand(1))) {
Dan Gohmand6bf2012012-04-13 18:57:48 +00002310 Changed = true;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002311 Type *Ty = CI->getArgOperand(0)->getType();
John McCall9fbd3182011-06-15 23:37:01 +00002312 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2313 Constant::getNullValue(Ty),
2314 CI);
2315 CI->replaceAllUsesWith(UndefValue::get(CI->getType()));
2316 CI->eraseFromParent();
2317 continue;
2318 }
2319 break;
2320 }
2321 case IC_Retain:
2322 OptimizeRetainCall(F, Inst);
2323 break;
2324 case IC_RetainRV:
2325 if (OptimizeRetainRVCall(F, Inst))
2326 continue;
2327 break;
2328 case IC_AutoreleaseRV:
2329 OptimizeAutoreleaseRVCall(F, Inst);
2330 break;
2331 }
2332
2333 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
2334 if (IsAutorelease(Class) && Inst->use_empty()) {
2335 CallInst *Call = cast<CallInst>(Inst);
2336 const Value *Arg = Call->getArgOperand(0);
2337 Arg = FindSingleUseIdentifiedObject(Arg);
2338 if (Arg) {
2339 Changed = true;
2340 ++NumAutoreleases;
2341
2342 // Create the declaration lazily.
2343 LLVMContext &C = Inst->getContext();
2344 CallInst *NewCall =
2345 CallInst::Create(getReleaseCallee(F.getParent()),
2346 Call->getArgOperand(0), "", Call);
2347 NewCall->setMetadata(ImpreciseReleaseMDKind,
2348 MDNode::get(C, ArrayRef<Value *>()));
2349 EraseInstruction(Call);
2350 Inst = NewCall;
2351 Class = IC_Release;
2352 }
2353 }
2354
2355 // For functions which can never be passed stack arguments, add
2356 // a tail keyword.
2357 if (IsAlwaysTail(Class)) {
2358 Changed = true;
2359 cast<CallInst>(Inst)->setTailCall();
2360 }
2361
2362 // Set nounwind as needed.
2363 if (IsNoThrow(Class)) {
2364 Changed = true;
2365 cast<CallInst>(Inst)->setDoesNotThrow();
2366 }
2367
2368 if (!IsNoopOnNull(Class)) {
2369 UsedInThisFunction |= 1 << Class;
2370 continue;
2371 }
2372
2373 const Value *Arg = GetObjCArg(Inst);
2374
2375 // ARC calls with null are no-ops. Delete them.
2376 if (isNullOrUndef(Arg)) {
2377 Changed = true;
2378 ++NumNoops;
2379 EraseInstruction(Inst);
2380 continue;
2381 }
2382
2383 // Keep track of which of retain, release, autorelease, and retain_block
2384 // are actually present in this function.
2385 UsedInThisFunction |= 1 << Class;
2386
2387 // If Arg is a PHI, and one or more incoming values to the
2388 // PHI are null, and the call is control-equivalent to the PHI, and there
2389 // are no relevant side effects between the PHI and the call, the call
2390 // could be pushed up to just those paths with non-null incoming values.
2391 // For now, don't bother splitting critical edges for this.
2392 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
2393 Worklist.push_back(std::make_pair(Inst, Arg));
2394 do {
2395 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
2396 Inst = Pair.first;
2397 Arg = Pair.second;
2398
2399 const PHINode *PN = dyn_cast<PHINode>(Arg);
2400 if (!PN) continue;
2401
2402 // Determine if the PHI has any null operands, or any incoming
2403 // critical edges.
2404 bool HasNull = false;
2405 bool HasCriticalEdges = false;
2406 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2407 Value *Incoming =
2408 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2409 if (isNullOrUndef(Incoming))
2410 HasNull = true;
2411 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
2412 .getNumSuccessors() != 1) {
2413 HasCriticalEdges = true;
2414 break;
2415 }
2416 }
2417 // If we have null operands and no critical edges, optimize.
2418 if (!HasCriticalEdges && HasNull) {
2419 SmallPtrSet<Instruction *, 4> DependingInstructions;
2420 SmallPtrSet<const BasicBlock *, 4> Visited;
2421
2422 // Check that there is nothing that cares about the reference
2423 // count between the call and the phi.
Dan Gohman511568d2012-04-13 00:59:57 +00002424 switch (Class) {
2425 case IC_Retain:
2426 case IC_RetainBlock:
2427 // These can always be moved up.
2428 break;
2429 case IC_Release:
Dan Gohman0daef3d2012-05-08 23:39:44 +00002430 // These can't be moved across things that care about the retain
2431 // count.
Dan Gohman511568d2012-04-13 00:59:57 +00002432 FindDependencies(NeedsPositiveRetainCount, Arg,
2433 Inst->getParent(), Inst,
2434 DependingInstructions, Visited, PA);
2435 break;
2436 case IC_Autorelease:
2437 // These can't be moved across autorelease pool scope boundaries.
2438 FindDependencies(AutoreleasePoolBoundary, Arg,
2439 Inst->getParent(), Inst,
2440 DependingInstructions, Visited, PA);
2441 break;
2442 case IC_RetainRV:
2443 case IC_AutoreleaseRV:
2444 // Don't move these; the RV optimization depends on the autoreleaseRV
2445 // being tail called, and the retainRV being immediately after a call
2446 // (which might still happen if we get lucky with codegen layout, but
2447 // it's not worth taking the chance).
2448 continue;
2449 default:
2450 llvm_unreachable("Invalid dependence flavor");
2451 }
2452
John McCall9fbd3182011-06-15 23:37:01 +00002453 if (DependingInstructions.size() == 1 &&
2454 *DependingInstructions.begin() == PN) {
2455 Changed = true;
2456 ++NumPartialNoops;
2457 // Clone the call into each predecessor that has a non-null value.
2458 CallInst *CInst = cast<CallInst>(Inst);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002459 Type *ParamTy = CInst->getArgOperand(0)->getType();
John McCall9fbd3182011-06-15 23:37:01 +00002460 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2461 Value *Incoming =
2462 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2463 if (!isNullOrUndef(Incoming)) {
2464 CallInst *Clone = cast<CallInst>(CInst->clone());
2465 Value *Op = PN->getIncomingValue(i);
2466 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
2467 if (Op->getType() != ParamTy)
2468 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
2469 Clone->setArgOperand(0, Op);
2470 Clone->insertBefore(InsertPos);
2471 Worklist.push_back(std::make_pair(Clone, Incoming));
2472 }
2473 }
2474 // Erase the original call.
2475 EraseInstruction(CInst);
2476 continue;
2477 }
2478 }
2479 } while (!Worklist.empty());
2480 }
2481}
2482
2483/// CheckForCFGHazards - Check for critical edges, loop boundaries, irreducible
2484/// control flow, or other CFG structures where moving code across the edge
2485/// would result in it being executed more.
2486void
2487ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
2488 DenseMap<const BasicBlock *, BBState> &BBStates,
2489 BBState &MyStates) const {
2490 // If any top-down local-use or possible-dec has a succ which is earlier in
2491 // the sequence, forget it.
Dan Gohman22cc4cc2012-03-02 01:13:53 +00002492 for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
John McCall9fbd3182011-06-15 23:37:01 +00002493 E = MyStates.top_down_ptr_end(); I != E; ++I)
2494 switch (I->second.GetSeq()) {
2495 default: break;
2496 case S_Use: {
2497 const Value *Arg = I->first;
2498 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2499 bool SomeSuccHasSame = false;
2500 bool AllSuccsHaveSame = true;
Dan Gohman22cc4cc2012-03-02 01:13:53 +00002501 PtrState &S = I->second;
Dan Gohmandbe266b2012-02-17 18:59:53 +00002502 succ_const_iterator SI(TI), SE(TI, false);
2503
2504 // If the terminator is an invoke marked with the
2505 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
2506 // ignored, for ARC purposes.
2507 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind))
2508 --SE;
2509
2510 for (; SI != SE; ++SI) {
Dan Gohman70e29682012-03-02 01:26:46 +00002511 Sequence SuccSSeq = S_None;
2512 bool SuccSRRIKnownSafe = false;
Dan Gohman0daef3d2012-05-08 23:39:44 +00002513 // If VisitBottomUp has pointer information for this successor, take
2514 // what we know about it.
Dan Gohman447989c2012-04-27 18:56:31 +00002515 DenseMap<const BasicBlock *, BBState>::iterator BBI =
2516 BBStates.find(*SI);
2517 assert(BBI != BBStates.end());
2518 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2519 SuccSSeq = SuccS.GetSeq();
2520 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
Dan Gohman70e29682012-03-02 01:26:46 +00002521 switch (SuccSSeq) {
John McCall9fbd3182011-06-15 23:37:01 +00002522 case S_None:
Dan Gohmana7f7db22011-08-12 00:26:31 +00002523 case S_CanRelease: {
Dan Gohman70e29682012-03-02 01:26:46 +00002524 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
Dan Gohmana7f7db22011-08-12 00:26:31 +00002525 S.ClearSequenceProgress();
Dan Gohman70e29682012-03-02 01:26:46 +00002526 break;
2527 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002528 continue;
2529 }
John McCall9fbd3182011-06-15 23:37:01 +00002530 case S_Use:
2531 SomeSuccHasSame = true;
2532 break;
2533 case S_Stop:
2534 case S_Release:
2535 case S_MovableRelease:
Dan Gohman70e29682012-03-02 01:26:46 +00002536 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002537 AllSuccsHaveSame = false;
John McCall9fbd3182011-06-15 23:37:01 +00002538 break;
2539 case S_Retain:
2540 llvm_unreachable("bottom-up pointer in retain state!");
2541 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002542 }
John McCall9fbd3182011-06-15 23:37:01 +00002543 // If the state at the other end of any of the successor edges
2544 // matches the current state, require all edges to match. This
2545 // guards against loops in the middle of a sequence.
2546 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002547 S.ClearSequenceProgress();
Dan Gohman2e68beb2011-12-12 18:13:53 +00002548 break;
John McCall9fbd3182011-06-15 23:37:01 +00002549 }
2550 case S_CanRelease: {
2551 const Value *Arg = I->first;
2552 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2553 bool SomeSuccHasSame = false;
2554 bool AllSuccsHaveSame = true;
Dan Gohman22cc4cc2012-03-02 01:13:53 +00002555 PtrState &S = I->second;
Dan Gohmandbe266b2012-02-17 18:59:53 +00002556 succ_const_iterator SI(TI), SE(TI, false);
2557
2558 // If the terminator is an invoke marked with the
2559 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
2560 // ignored, for ARC purposes.
2561 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind))
2562 --SE;
2563
2564 for (; SI != SE; ++SI) {
Dan Gohman70e29682012-03-02 01:26:46 +00002565 Sequence SuccSSeq = S_None;
2566 bool SuccSRRIKnownSafe = false;
Dan Gohman0daef3d2012-05-08 23:39:44 +00002567 // If VisitBottomUp has pointer information for this successor, take
2568 // what we know about it.
Dan Gohman447989c2012-04-27 18:56:31 +00002569 DenseMap<const BasicBlock *, BBState>::iterator BBI =
2570 BBStates.find(*SI);
2571 assert(BBI != BBStates.end());
2572 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2573 SuccSSeq = SuccS.GetSeq();
2574 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
Dan Gohman70e29682012-03-02 01:26:46 +00002575 switch (SuccSSeq) {
Dan Gohmana7f7db22011-08-12 00:26:31 +00002576 case S_None: {
Dan Gohman70e29682012-03-02 01:26:46 +00002577 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
Dan Gohmana7f7db22011-08-12 00:26:31 +00002578 S.ClearSequenceProgress();
Dan Gohman70e29682012-03-02 01:26:46 +00002579 break;
2580 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002581 continue;
2582 }
John McCall9fbd3182011-06-15 23:37:01 +00002583 case S_CanRelease:
2584 SomeSuccHasSame = true;
2585 break;
2586 case S_Stop:
2587 case S_Release:
2588 case S_MovableRelease:
2589 case S_Use:
Dan Gohman70e29682012-03-02 01:26:46 +00002590 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002591 AllSuccsHaveSame = false;
John McCall9fbd3182011-06-15 23:37:01 +00002592 break;
2593 case S_Retain:
2594 llvm_unreachable("bottom-up pointer in retain state!");
2595 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002596 }
John McCall9fbd3182011-06-15 23:37:01 +00002597 // If the state at the other end of any of the successor edges
2598 // matches the current state, require all edges to match. This
2599 // guards against loops in the middle of a sequence.
2600 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002601 S.ClearSequenceProgress();
Dan Gohman2e68beb2011-12-12 18:13:53 +00002602 break;
John McCall9fbd3182011-06-15 23:37:01 +00002603 }
2604 }
2605}
2606
2607bool
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002608ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002609 BasicBlock *BB,
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002610 MapVector<Value *, RRInfo> &Retains,
2611 BBState &MyStates) {
2612 bool NestingDetected = false;
2613 InstructionClass Class = GetInstructionClass(Inst);
2614 const Value *Arg = 0;
2615
2616 switch (Class) {
2617 case IC_Release: {
2618 Arg = GetObjCArg(Inst);
2619
2620 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2621
2622 // If we see two releases in a row on the same pointer. If so, make
2623 // a note, and we'll cicle back to revisit it after we've
2624 // hopefully eliminated the second release, which may allow us to
2625 // eliminate the first release too.
2626 // Theoretically we could implement removal of nested retain+release
2627 // pairs by making PtrState hold a stack of states, but this is
2628 // simple and avoids adding overhead for the non-nested case.
2629 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease)
2630 NestingDetected = true;
2631
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002632 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
Dan Gohman50ade652012-04-25 00:50:46 +00002633 S.ResetSequenceProgress(ReleaseMetadata ? S_MovableRelease : S_Release);
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002634 S.RRI.ReleaseMetadata = ReleaseMetadata;
Dan Gohman230768b2012-09-04 23:16:20 +00002635 S.RRI.KnownSafe = S.IsKnownIncremented();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002636 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2637 S.RRI.Calls.insert(Inst);
2638
Dan Gohman230768b2012-09-04 23:16:20 +00002639 S.SetKnownPositiveRefCount();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002640 break;
2641 }
2642 case IC_RetainBlock:
2643 // An objc_retainBlock call with just a use may need to be kept,
2644 // because it may be copying a block from the stack to the heap.
2645 if (!IsRetainBlockOptimizable(Inst))
2646 break;
2647 // FALLTHROUGH
2648 case IC_Retain:
2649 case IC_RetainRV: {
2650 Arg = GetObjCArg(Inst);
2651
2652 PtrState &S = MyStates.getPtrBottomUpState(Arg);
Dan Gohman50ade652012-04-25 00:50:46 +00002653 S.SetKnownPositiveRefCount();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002654
2655 switch (S.GetSeq()) {
2656 case S_Stop:
2657 case S_Release:
2658 case S_MovableRelease:
2659 case S_Use:
2660 S.RRI.ReverseInsertPts.clear();
2661 // FALL THROUGH
2662 case S_CanRelease:
2663 // Don't do retain+release tracking for IC_RetainRV, because it's
2664 // better to let it remain as the first instruction after a call.
2665 if (Class != IC_RetainRV) {
2666 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2667 Retains[Inst] = S.RRI;
2668 }
2669 S.ClearSequenceProgress();
2670 break;
2671 case S_None:
2672 break;
2673 case S_Retain:
2674 llvm_unreachable("bottom-up pointer in retain state!");
2675 }
2676 return NestingDetected;
2677 }
2678 case IC_AutoreleasepoolPop:
2679 // Conservatively, clear MyStates for all known pointers.
2680 MyStates.clearBottomUpPointers();
2681 return NestingDetected;
2682 case IC_AutoreleasepoolPush:
2683 case IC_None:
2684 // These are irrelevant.
2685 return NestingDetected;
2686 default:
2687 break;
2688 }
2689
2690 // Consider any other possible effects of this instruction on each
2691 // pointer being tracked.
2692 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
2693 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
2694 const Value *Ptr = MI->first;
2695 if (Ptr == Arg)
2696 continue; // Handled above.
2697 PtrState &S = MI->second;
2698 Sequence Seq = S.GetSeq();
2699
2700 // Check for possible releases.
2701 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Dan Gohman50ade652012-04-25 00:50:46 +00002702 S.ClearRefCount();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002703 switch (Seq) {
2704 case S_Use:
2705 S.SetSeq(S_CanRelease);
2706 continue;
2707 case S_CanRelease:
2708 case S_Release:
2709 case S_MovableRelease:
2710 case S_Stop:
2711 case S_None:
2712 break;
2713 case S_Retain:
2714 llvm_unreachable("bottom-up pointer in retain state!");
2715 }
2716 }
2717
2718 // Check for possible direct uses.
2719 switch (Seq) {
2720 case S_Release:
2721 case S_MovableRelease:
2722 if (CanUse(Inst, Ptr, PA, Class)) {
2723 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002724 // If this is an invoke instruction, we're scanning it as part of
2725 // one of its successor blocks, since we can't insert code after it
2726 // in its own block, and we don't want to split critical edges.
2727 if (isa<InvokeInst>(Inst))
2728 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2729 else
Francois Pichetb54a5ed2012-03-24 01:36:37 +00002730 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002731 S.SetSeq(S_Use);
2732 } else if (Seq == S_Release &&
2733 (Class == IC_User || Class == IC_CallOrUser)) {
2734 // Non-movable releases depend on any possible objc pointer use.
2735 S.SetSeq(S_Stop);
2736 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002737 // As above; handle invoke specially.
2738 if (isa<InvokeInst>(Inst))
2739 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2740 else
Francois Pichetb54a5ed2012-03-24 01:36:37 +00002741 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002742 }
2743 break;
2744 case S_Stop:
2745 if (CanUse(Inst, Ptr, PA, Class))
2746 S.SetSeq(S_Use);
2747 break;
2748 case S_CanRelease:
2749 case S_Use:
2750 case S_None:
2751 break;
2752 case S_Retain:
2753 llvm_unreachable("bottom-up pointer in retain state!");
2754 }
2755 }
2756
2757 return NestingDetected;
2758}
2759
2760bool
John McCall9fbd3182011-06-15 23:37:01 +00002761ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2762 DenseMap<const BasicBlock *, BBState> &BBStates,
2763 MapVector<Value *, RRInfo> &Retains) {
2764 bool NestingDetected = false;
2765 BBState &MyStates = BBStates[BB];
2766
2767 // Merge the states from each successor to compute the initial state
2768 // for the current block.
Dan Gohman40e46602012-08-27 18:31:36 +00002769 BBState::edge_iterator SI(MyStates.succ_begin()),
2770 SE(MyStates.succ_end());
2771 if (SI != SE) {
Dan Gohmaneeeb7752012-04-24 22:53:18 +00002772 const BasicBlock *Succ = *SI;
2773 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
2774 assert(I != BBStates.end());
2775 MyStates.InitFromSucc(I->second);
2776 ++SI;
2777 for (; SI != SE; ++SI) {
2778 Succ = *SI;
2779 I = BBStates.find(Succ);
2780 assert(I != BBStates.end());
2781 MyStates.MergeSucc(I->second);
2782 }
Dan Gohmandbe266b2012-02-17 18:59:53 +00002783 }
John McCall9fbd3182011-06-15 23:37:01 +00002784
2785 // Visit all the instructions, bottom-up.
2786 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2787 Instruction *Inst = llvm::prior(I);
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002788
2789 // Invoke instructions are visited as part of their successors (below).
2790 if (isa<InvokeInst>(Inst))
2791 continue;
2792
2793 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
2794 }
2795
Dan Gohman447989c2012-04-27 18:56:31 +00002796 // If there's a predecessor with an invoke, visit the invoke as if it were
2797 // part of this block, since we can't insert code after an invoke in its own
2798 // block, and we don't want to split critical edges.
Dan Gohmaneeeb7752012-04-24 22:53:18 +00002799 for (BBState::edge_iterator PI(MyStates.pred_begin()),
2800 PE(MyStates.pred_end()); PI != PE; ++PI) {
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002801 BasicBlock *Pred = *PI;
Dan Gohman447989c2012-04-27 18:56:31 +00002802 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
2803 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002804 }
John McCall9fbd3182011-06-15 23:37:01 +00002805
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002806 return NestingDetected;
2807}
John McCall9fbd3182011-06-15 23:37:01 +00002808
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002809bool
2810ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
2811 DenseMap<Value *, RRInfo> &Releases,
2812 BBState &MyStates) {
2813 bool NestingDetected = false;
2814 InstructionClass Class = GetInstructionClass(Inst);
2815 const Value *Arg = 0;
John McCall9fbd3182011-06-15 23:37:01 +00002816
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002817 switch (Class) {
2818 case IC_RetainBlock:
2819 // An objc_retainBlock call with just a use may need to be kept,
2820 // because it may be copying a block from the stack to the heap.
2821 if (!IsRetainBlockOptimizable(Inst))
2822 break;
2823 // FALLTHROUGH
2824 case IC_Retain:
2825 case IC_RetainRV: {
2826 Arg = GetObjCArg(Inst);
2827
2828 PtrState &S = MyStates.getPtrTopDownState(Arg);
2829
2830 // Don't do retain+release tracking for IC_RetainRV, because it's
2831 // better to let it remain as the first instruction after a call.
2832 if (Class != IC_RetainRV) {
2833 // If we see two retains in a row on the same pointer. If so, make
John McCall9fbd3182011-06-15 23:37:01 +00002834 // a note, and we'll cicle back to revisit it after we've
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002835 // hopefully eliminated the second retain, which may allow us to
2836 // eliminate the first retain too.
John McCall9fbd3182011-06-15 23:37:01 +00002837 // Theoretically we could implement removal of nested retain+release
2838 // pairs by making PtrState hold a stack of states, but this is
2839 // simple and avoids adding overhead for the non-nested case.
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002840 if (S.GetSeq() == S_Retain)
John McCall9fbd3182011-06-15 23:37:01 +00002841 NestingDetected = true;
2842
Dan Gohman50ade652012-04-25 00:50:46 +00002843 S.ResetSequenceProgress(S_Retain);
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002844 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
Dan Gohman230768b2012-09-04 23:16:20 +00002845 S.RRI.KnownSafe = S.IsKnownIncremented();
John McCall9fbd3182011-06-15 23:37:01 +00002846 S.RRI.Calls.insert(Inst);
John McCall9fbd3182011-06-15 23:37:01 +00002847 }
John McCall9fbd3182011-06-15 23:37:01 +00002848
Dan Gohman230768b2012-09-04 23:16:20 +00002849 S.SetKnownPositiveRefCount();
Dan Gohmanc72d3be2012-07-23 19:27:31 +00002850
2851 // A retain can be a potential use; procede to the generic checking
2852 // code below.
2853 break;
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002854 }
2855 case IC_Release: {
2856 Arg = GetObjCArg(Inst);
2857
2858 PtrState &S = MyStates.getPtrTopDownState(Arg);
Dan Gohman230768b2012-09-04 23:16:20 +00002859 S.ClearRefCount();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002860
2861 switch (S.GetSeq()) {
2862 case S_Retain:
2863 case S_CanRelease:
2864 S.RRI.ReverseInsertPts.clear();
2865 // FALL THROUGH
2866 case S_Use:
2867 S.RRI.ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2868 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2869 Releases[Inst] = S.RRI;
2870 S.ClearSequenceProgress();
2871 break;
2872 case S_None:
2873 break;
2874 case S_Stop:
2875 case S_Release:
2876 case S_MovableRelease:
2877 llvm_unreachable("top-down pointer in release state!");
2878 }
2879 break;
2880 }
2881 case IC_AutoreleasepoolPop:
2882 // Conservatively, clear MyStates for all known pointers.
2883 MyStates.clearTopDownPointers();
2884 return NestingDetected;
2885 case IC_AutoreleasepoolPush:
2886 case IC_None:
2887 // These are irrelevant.
2888 return NestingDetected;
2889 default:
2890 break;
2891 }
2892
2893 // Consider any other possible effects of this instruction on each
2894 // pointer being tracked.
2895 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
2896 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
2897 const Value *Ptr = MI->first;
2898 if (Ptr == Arg)
2899 continue; // Handled above.
2900 PtrState &S = MI->second;
2901 Sequence Seq = S.GetSeq();
2902
2903 // Check for possible releases.
2904 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Dan Gohman50ade652012-04-25 00:50:46 +00002905 S.ClearRefCount();
John McCall9fbd3182011-06-15 23:37:01 +00002906 switch (Seq) {
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002907 case S_Retain:
2908 S.SetSeq(S_CanRelease);
2909 assert(S.RRI.ReverseInsertPts.empty());
2910 S.RRI.ReverseInsertPts.insert(Inst);
2911
2912 // One call can't cause a transition from S_Retain to S_CanRelease
2913 // and S_CanRelease to S_Use. If we've made the first transition,
2914 // we're done.
2915 continue;
John McCall9fbd3182011-06-15 23:37:01 +00002916 case S_Use:
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002917 case S_CanRelease:
John McCall9fbd3182011-06-15 23:37:01 +00002918 case S_None:
2919 break;
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002920 case S_Stop:
2921 case S_Release:
2922 case S_MovableRelease:
2923 llvm_unreachable("top-down pointer in release state!");
John McCall9fbd3182011-06-15 23:37:01 +00002924 }
2925 }
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002926
2927 // Check for possible direct uses.
2928 switch (Seq) {
2929 case S_CanRelease:
2930 if (CanUse(Inst, Ptr, PA, Class))
2931 S.SetSeq(S_Use);
2932 break;
2933 case S_Retain:
2934 case S_Use:
2935 case S_None:
2936 break;
2937 case S_Stop:
2938 case S_Release:
2939 case S_MovableRelease:
2940 llvm_unreachable("top-down pointer in release state!");
2941 }
John McCall9fbd3182011-06-15 23:37:01 +00002942 }
2943
2944 return NestingDetected;
2945}
2946
2947bool
2948ObjCARCOpt::VisitTopDown(BasicBlock *BB,
2949 DenseMap<const BasicBlock *, BBState> &BBStates,
2950 DenseMap<Value *, RRInfo> &Releases) {
2951 bool NestingDetected = false;
2952 BBState &MyStates = BBStates[BB];
2953
2954 // Merge the states from each predecessor to compute the initial state
2955 // for the current block.
Dan Gohman40e46602012-08-27 18:31:36 +00002956 BBState::edge_iterator PI(MyStates.pred_begin()),
2957 PE(MyStates.pred_end());
2958 if (PI != PE) {
Dan Gohmaneeeb7752012-04-24 22:53:18 +00002959 const BasicBlock *Pred = *PI;
2960 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
2961 assert(I != BBStates.end());
2962 MyStates.InitFromPred(I->second);
2963 ++PI;
2964 for (; PI != PE; ++PI) {
2965 Pred = *PI;
2966 I = BBStates.find(Pred);
2967 assert(I != BBStates.end());
2968 MyStates.MergePred(I->second);
2969 }
Dan Gohmaneeeb7752012-04-24 22:53:18 +00002970 }
John McCall9fbd3182011-06-15 23:37:01 +00002971
2972 // Visit all the instructions, top-down.
2973 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2974 Instruction *Inst = I;
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002975 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
John McCall9fbd3182011-06-15 23:37:01 +00002976 }
2977
2978 CheckForCFGHazards(BB, BBStates, MyStates);
2979 return NestingDetected;
2980}
2981
Dan Gohman59a1c932011-12-12 19:42:25 +00002982static void
2983ComputePostOrders(Function &F,
2984 SmallVectorImpl<BasicBlock *> &PostOrder,
Dan Gohmaneeeb7752012-04-24 22:53:18 +00002985 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
2986 unsigned NoObjCARCExceptionsMDKind,
2987 DenseMap<const BasicBlock *, BBState> &BBStates) {
Dan Gohman59a1c932011-12-12 19:42:25 +00002988 /// Visited - The visited set, for doing DFS walks.
2989 SmallPtrSet<BasicBlock *, 16> Visited;
2990
2991 // Do DFS, computing the PostOrder.
2992 SmallPtrSet<BasicBlock *, 16> OnStack;
2993 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
Dan Gohmaneeeb7752012-04-24 22:53:18 +00002994
2995 // Functions always have exactly one entry block, and we don't have
2996 // any other block that we treat like an entry block.
Dan Gohman59a1c932011-12-12 19:42:25 +00002997 BasicBlock *EntryBB = &F.getEntryBlock();
Dan Gohman0daef3d2012-05-08 23:39:44 +00002998 BBState &MyStates = BBStates[EntryBB];
2999 MyStates.SetAsEntry();
3000 TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
3001 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
Dan Gohman59a1c932011-12-12 19:42:25 +00003002 Visited.insert(EntryBB);
3003 OnStack.insert(EntryBB);
3004 do {
3005 dfs_next_succ:
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003006 BasicBlock *CurrBB = SuccStack.back().first;
3007 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
3008 succ_iterator SE(TI, false);
Dan Gohman0daef3d2012-05-08 23:39:44 +00003009
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003010 // If the terminator is an invoke marked with the
3011 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
3012 // ignored, for ARC purposes.
3013 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind))
3014 --SE;
3015
3016 while (SuccStack.back().second != SE) {
3017 BasicBlock *SuccBB = *SuccStack.back().second++;
3018 if (Visited.insert(SuccBB)) {
Dan Gohman0daef3d2012-05-08 23:39:44 +00003019 TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
3020 SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003021 BBStates[CurrBB].addSucc(SuccBB);
Dan Gohman0daef3d2012-05-08 23:39:44 +00003022 BBState &SuccStates = BBStates[SuccBB];
3023 SuccStates.addPred(CurrBB);
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003024 OnStack.insert(SuccBB);
Dan Gohman59a1c932011-12-12 19:42:25 +00003025 goto dfs_next_succ;
3026 }
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003027
3028 if (!OnStack.count(SuccBB)) {
3029 BBStates[CurrBB].addSucc(SuccBB);
3030 BBStates[SuccBB].addPred(CurrBB);
3031 }
Dan Gohman59a1c932011-12-12 19:42:25 +00003032 }
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003033 OnStack.erase(CurrBB);
3034 PostOrder.push_back(CurrBB);
3035 SuccStack.pop_back();
Dan Gohman59a1c932011-12-12 19:42:25 +00003036 } while (!SuccStack.empty());
3037
3038 Visited.clear();
3039
Dan Gohman59a1c932011-12-12 19:42:25 +00003040 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003041 // Functions may have many exits, and there also blocks which we treat
3042 // as exits due to ignored edges.
3043 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
3044 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
3045 BasicBlock *ExitBB = I;
3046 BBState &MyStates = BBStates[ExitBB];
3047 if (!MyStates.isExit())
3048 continue;
3049
Dan Gohman447989c2012-04-27 18:56:31 +00003050 MyStates.SetAsExit();
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003051
3052 PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
Dan Gohman59a1c932011-12-12 19:42:25 +00003053 Visited.insert(ExitBB);
3054 while (!PredStack.empty()) {
3055 reverse_dfs_next_succ:
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003056 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
3057 while (PredStack.back().second != PE) {
Dan Gohman59a1c932011-12-12 19:42:25 +00003058 BasicBlock *BB = *PredStack.back().second++;
Dan Gohman59a1c932011-12-12 19:42:25 +00003059 if (Visited.insert(BB)) {
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003060 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
Dan Gohman59a1c932011-12-12 19:42:25 +00003061 goto reverse_dfs_next_succ;
3062 }
3063 }
3064 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
3065 }
3066 }
3067}
3068
John McCall9fbd3182011-06-15 23:37:01 +00003069// Visit - Visit the function both top-down and bottom-up.
3070bool
3071ObjCARCOpt::Visit(Function &F,
3072 DenseMap<const BasicBlock *, BBState> &BBStates,
3073 MapVector<Value *, RRInfo> &Retains,
3074 DenseMap<Value *, RRInfo> &Releases) {
Dan Gohman59a1c932011-12-12 19:42:25 +00003075
3076 // Use reverse-postorder traversals, because we magically know that loops
3077 // will be well behaved, i.e. they won't repeatedly call retain on a single
3078 // pointer without doing a release. We can't use the ReversePostOrderTraversal
3079 // class here because we want the reverse-CFG postorder to consider each
3080 // function exit point, and we want to ignore selected cycle edges.
3081 SmallVector<BasicBlock *, 16> PostOrder;
3082 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003083 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
3084 NoObjCARCExceptionsMDKind,
3085 BBStates);
Dan Gohman59a1c932011-12-12 19:42:25 +00003086
3087 // Use reverse-postorder on the reverse CFG for bottom-up.
John McCall9fbd3182011-06-15 23:37:01 +00003088 bool BottomUpNestingDetected = false;
Dan Gohmanb48ef3a2011-08-18 21:27:42 +00003089 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
Dan Gohman59a1c932011-12-12 19:42:25 +00003090 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
3091 I != E; ++I)
3092 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
John McCall9fbd3182011-06-15 23:37:01 +00003093
Dan Gohman59a1c932011-12-12 19:42:25 +00003094 // Use reverse-postorder for top-down.
John McCall9fbd3182011-06-15 23:37:01 +00003095 bool TopDownNestingDetected = false;
Dan Gohman59a1c932011-12-12 19:42:25 +00003096 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
3097 PostOrder.rbegin(), E = PostOrder.rend();
3098 I != E; ++I)
3099 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
John McCall9fbd3182011-06-15 23:37:01 +00003100
3101 return TopDownNestingDetected && BottomUpNestingDetected;
3102}
3103
3104/// MoveCalls - Move the calls in RetainsToMove and ReleasesToMove.
3105void ObjCARCOpt::MoveCalls(Value *Arg,
3106 RRInfo &RetainsToMove,
3107 RRInfo &ReleasesToMove,
3108 MapVector<Value *, RRInfo> &Retains,
3109 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman44280692011-07-22 22:29:21 +00003110 SmallVectorImpl<Instruction *> &DeadInsts,
3111 Module *M) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003112 Type *ArgTy = Arg->getType();
Dan Gohman44280692011-07-22 22:29:21 +00003113 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
John McCall9fbd3182011-06-15 23:37:01 +00003114
3115 // Insert the new retain and release calls.
3116 for (SmallPtrSet<Instruction *, 2>::const_iterator
3117 PI = ReleasesToMove.ReverseInsertPts.begin(),
3118 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
3119 Instruction *InsertPt = *PI;
3120 Value *MyArg = ArgTy == ParamTy ? Arg :
3121 new BitCastInst(Arg, ParamTy, "", InsertPt);
3122 CallInst *Call =
3123 CallInst::Create(RetainsToMove.IsRetainBlock ?
Dan Gohman44280692011-07-22 22:29:21 +00003124 getRetainBlockCallee(M) : getRetainCallee(M),
John McCall9fbd3182011-06-15 23:37:01 +00003125 MyArg, "", InsertPt);
3126 Call->setDoesNotThrow();
Dan Gohman79522dc2012-01-13 00:39:07 +00003127 if (RetainsToMove.IsRetainBlock)
Dan Gohmana974bea2011-10-17 22:53:25 +00003128 Call->setMetadata(CopyOnEscapeMDKind,
3129 MDNode::get(M->getContext(), ArrayRef<Value *>()));
Dan Gohman79522dc2012-01-13 00:39:07 +00003130 else
John McCall9fbd3182011-06-15 23:37:01 +00003131 Call->setTailCall();
3132 }
3133 for (SmallPtrSet<Instruction *, 2>::const_iterator
3134 PI = RetainsToMove.ReverseInsertPts.begin(),
3135 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
Dan Gohmanfbab4a82012-03-23 17:47:54 +00003136 Instruction *InsertPt = *PI;
3137 Value *MyArg = ArgTy == ParamTy ? Arg :
3138 new BitCastInst(Arg, ParamTy, "", InsertPt);
3139 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
3140 "", InsertPt);
3141 // Attach a clang.imprecise_release metadata tag, if appropriate.
3142 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
3143 Call->setMetadata(ImpreciseReleaseMDKind, M);
3144 Call->setDoesNotThrow();
3145 if (ReleasesToMove.IsTailCallRelease)
3146 Call->setTailCall();
John McCall9fbd3182011-06-15 23:37:01 +00003147 }
3148
3149 // Delete the original retain and release calls.
3150 for (SmallPtrSet<Instruction *, 2>::const_iterator
3151 AI = RetainsToMove.Calls.begin(),
3152 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
3153 Instruction *OrigRetain = *AI;
3154 Retains.blot(OrigRetain);
3155 DeadInsts.push_back(OrigRetain);
3156 }
3157 for (SmallPtrSet<Instruction *, 2>::const_iterator
3158 AI = ReleasesToMove.Calls.begin(),
3159 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
3160 Instruction *OrigRelease = *AI;
3161 Releases.erase(OrigRelease);
3162 DeadInsts.push_back(OrigRelease);
3163 }
3164}
3165
Dan Gohmand6bf2012012-04-13 18:57:48 +00003166/// PerformCodePlacement - Identify pairings between the retains and releases,
3167/// and delete and/or move them.
John McCall9fbd3182011-06-15 23:37:01 +00003168bool
3169ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
3170 &BBStates,
3171 MapVector<Value *, RRInfo> &Retains,
Dan Gohman44280692011-07-22 22:29:21 +00003172 DenseMap<Value *, RRInfo> &Releases,
3173 Module *M) {
John McCall9fbd3182011-06-15 23:37:01 +00003174 bool AnyPairsCompletelyEliminated = false;
3175 RRInfo RetainsToMove;
3176 RRInfo ReleasesToMove;
3177 SmallVector<Instruction *, 4> NewRetains;
3178 SmallVector<Instruction *, 4> NewReleases;
3179 SmallVector<Instruction *, 8> DeadInsts;
3180
Dan Gohmand6bf2012012-04-13 18:57:48 +00003181 // Visit each retain.
John McCall9fbd3182011-06-15 23:37:01 +00003182 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
Dan Gohman597fece2011-09-29 22:25:23 +00003183 E = Retains.end(); I != E; ++I) {
3184 Value *V = I->first;
John McCall9fbd3182011-06-15 23:37:01 +00003185 if (!V) continue; // blotted
3186
3187 Instruction *Retain = cast<Instruction>(V);
3188 Value *Arg = GetObjCArg(Retain);
3189
Dan Gohman79522dc2012-01-13 00:39:07 +00003190 // If the object being released is in static or stack storage, we know it's
John McCall9fbd3182011-06-15 23:37:01 +00003191 // not being managed by ObjC reference counting, so we can delete pairs
3192 // regardless of what possible decrements or uses lie between them.
Dan Gohman79522dc2012-01-13 00:39:07 +00003193 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
Dan Gohman0daef3d2012-05-08 23:39:44 +00003194
Dan Gohman1b31ea82011-08-22 17:29:11 +00003195 // A constant pointer can't be pointing to an object on the heap. It may
3196 // be reference-counted, but it won't be deleted.
3197 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
3198 if (const GlobalVariable *GV =
3199 dyn_cast<GlobalVariable>(
3200 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
3201 if (GV->isConstant())
3202 KnownSafe = true;
3203
John McCall9fbd3182011-06-15 23:37:01 +00003204 // If a pair happens in a region where it is known that the reference count
3205 // is already incremented, we can similarly ignore possible decrements.
Dan Gohmane6d5e882011-08-19 00:26:36 +00003206 bool KnownSafeTD = true, KnownSafeBU = true;
John McCall9fbd3182011-06-15 23:37:01 +00003207
3208 // Connect the dots between the top-down-collected RetainsToMove and
3209 // bottom-up-collected ReleasesToMove to form sets of related calls.
3210 // This is an iterative process so that we connect multiple releases
3211 // to multiple retains if needed.
3212 unsigned OldDelta = 0;
3213 unsigned NewDelta = 0;
3214 unsigned OldCount = 0;
3215 unsigned NewCount = 0;
3216 bool FirstRelease = true;
3217 bool FirstRetain = true;
3218 NewRetains.push_back(Retain);
3219 for (;;) {
3220 for (SmallVectorImpl<Instruction *>::const_iterator
3221 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
3222 Instruction *NewRetain = *NI;
3223 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
3224 assert(It != Retains.end());
3225 const RRInfo &NewRetainRRI = It->second;
Dan Gohmane6d5e882011-08-19 00:26:36 +00003226 KnownSafeTD &= NewRetainRRI.KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00003227 for (SmallPtrSet<Instruction *, 2>::const_iterator
3228 LI = NewRetainRRI.Calls.begin(),
3229 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
3230 Instruction *NewRetainRelease = *LI;
3231 DenseMap<Value *, RRInfo>::const_iterator Jt =
3232 Releases.find(NewRetainRelease);
3233 if (Jt == Releases.end())
3234 goto next_retain;
3235 const RRInfo &NewRetainReleaseRRI = Jt->second;
3236 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
3237 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
3238 OldDelta -=
3239 BBStates[NewRetainRelease->getParent()].GetAllPathCount();
3240
3241 // Merge the ReleaseMetadata and IsTailCallRelease values.
3242 if (FirstRelease) {
3243 ReleasesToMove.ReleaseMetadata =
3244 NewRetainReleaseRRI.ReleaseMetadata;
3245 ReleasesToMove.IsTailCallRelease =
3246 NewRetainReleaseRRI.IsTailCallRelease;
3247 FirstRelease = false;
3248 } else {
3249 if (ReleasesToMove.ReleaseMetadata !=
3250 NewRetainReleaseRRI.ReleaseMetadata)
3251 ReleasesToMove.ReleaseMetadata = 0;
3252 if (ReleasesToMove.IsTailCallRelease !=
3253 NewRetainReleaseRRI.IsTailCallRelease)
3254 ReleasesToMove.IsTailCallRelease = false;
3255 }
3256
3257 // Collect the optimal insertion points.
3258 if (!KnownSafe)
3259 for (SmallPtrSet<Instruction *, 2>::const_iterator
3260 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
3261 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
3262 RI != RE; ++RI) {
3263 Instruction *RIP = *RI;
3264 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
3265 NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
3266 }
3267 NewReleases.push_back(NewRetainRelease);
3268 }
3269 }
3270 }
3271 NewRetains.clear();
3272 if (NewReleases.empty()) break;
3273
3274 // Back the other way.
3275 for (SmallVectorImpl<Instruction *>::const_iterator
3276 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
3277 Instruction *NewRelease = *NI;
3278 DenseMap<Value *, RRInfo>::const_iterator It =
3279 Releases.find(NewRelease);
3280 assert(It != Releases.end());
3281 const RRInfo &NewReleaseRRI = It->second;
Dan Gohmane6d5e882011-08-19 00:26:36 +00003282 KnownSafeBU &= NewReleaseRRI.KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00003283 for (SmallPtrSet<Instruction *, 2>::const_iterator
3284 LI = NewReleaseRRI.Calls.begin(),
3285 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
3286 Instruction *NewReleaseRetain = *LI;
3287 MapVector<Value *, RRInfo>::const_iterator Jt =
3288 Retains.find(NewReleaseRetain);
3289 if (Jt == Retains.end())
3290 goto next_retain;
3291 const RRInfo &NewReleaseRetainRRI = Jt->second;
3292 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
3293 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
3294 unsigned PathCount =
3295 BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
3296 OldDelta += PathCount;
3297 OldCount += PathCount;
3298
3299 // Merge the IsRetainBlock values.
3300 if (FirstRetain) {
3301 RetainsToMove.IsRetainBlock = NewReleaseRetainRRI.IsRetainBlock;
3302 FirstRetain = false;
3303 } else if (ReleasesToMove.IsRetainBlock !=
3304 NewReleaseRetainRRI.IsRetainBlock)
3305 // It's not possible to merge the sequences if one uses
3306 // objc_retain and the other uses objc_retainBlock.
3307 goto next_retain;
3308
3309 // Collect the optimal insertion points.
3310 if (!KnownSafe)
3311 for (SmallPtrSet<Instruction *, 2>::const_iterator
3312 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
3313 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
3314 RI != RE; ++RI) {
3315 Instruction *RIP = *RI;
3316 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
3317 PathCount = BBStates[RIP->getParent()].GetAllPathCount();
3318 NewDelta += PathCount;
3319 NewCount += PathCount;
3320 }
3321 }
3322 NewRetains.push_back(NewReleaseRetain);
3323 }
3324 }
3325 }
3326 NewReleases.clear();
3327 if (NewRetains.empty()) break;
3328 }
3329
Dan Gohmane6d5e882011-08-19 00:26:36 +00003330 // If the pointer is known incremented or nested, we can safely delete the
3331 // pair regardless of what's between them.
3332 if (KnownSafeTD || KnownSafeBU) {
John McCall9fbd3182011-06-15 23:37:01 +00003333 RetainsToMove.ReverseInsertPts.clear();
3334 ReleasesToMove.ReverseInsertPts.clear();
3335 NewCount = 0;
Dan Gohmana7f7db22011-08-12 00:26:31 +00003336 } else {
3337 // Determine whether the new insertion points we computed preserve the
3338 // balance of retain and release calls through the program.
3339 // TODO: If the fully aggressive solution isn't valid, try to find a
3340 // less aggressive solution which is.
3341 if (NewDelta != 0)
3342 goto next_retain;
John McCall9fbd3182011-06-15 23:37:01 +00003343 }
3344
3345 // Determine whether the original call points are balanced in the retain and
3346 // release calls through the program. If not, conservatively don't touch
3347 // them.
3348 // TODO: It's theoretically possible to do code motion in this case, as
3349 // long as the existing imbalances are maintained.
3350 if (OldDelta != 0)
3351 goto next_retain;
3352
John McCall9fbd3182011-06-15 23:37:01 +00003353 // Ok, everything checks out and we're all set. Let's move some code!
3354 Changed = true;
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003355 assert(OldCount != 0 && "Unreachable code?");
3356 AnyPairsCompletelyEliminated = NewCount == 0;
John McCall9fbd3182011-06-15 23:37:01 +00003357 NumRRs += OldCount - NewCount;
Dan Gohman44280692011-07-22 22:29:21 +00003358 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
3359 Retains, Releases, DeadInsts, M);
John McCall9fbd3182011-06-15 23:37:01 +00003360
3361 next_retain:
3362 NewReleases.clear();
3363 NewRetains.clear();
3364 RetainsToMove.clear();
3365 ReleasesToMove.clear();
3366 }
3367
3368 // Now that we're done moving everything, we can delete the newly dead
3369 // instructions, as we no longer need them as insert points.
3370 while (!DeadInsts.empty())
3371 EraseInstruction(DeadInsts.pop_back_val());
3372
3373 return AnyPairsCompletelyEliminated;
3374}
3375
3376/// OptimizeWeakCalls - Weak pointer optimizations.
3377void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
3378 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
3379 // itself because it uses AliasAnalysis and we need to do provenance
3380 // queries instead.
3381 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3382 Instruction *Inst = &*I++;
3383 InstructionClass Class = GetBasicInstructionClass(Inst);
3384 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
3385 continue;
3386
3387 // Delete objc_loadWeak calls with no users.
3388 if (Class == IC_LoadWeak && Inst->use_empty()) {
3389 Inst->eraseFromParent();
3390 continue;
3391 }
3392
3393 // TODO: For now, just look for an earlier available version of this value
3394 // within the same block. Theoretically, we could do memdep-style non-local
3395 // analysis too, but that would want caching. A better approach would be to
3396 // use the technique that EarlyCSE uses.
3397 inst_iterator Current = llvm::prior(I);
3398 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
3399 for (BasicBlock::iterator B = CurrentBB->begin(),
3400 J = Current.getInstructionIterator();
3401 J != B; --J) {
3402 Instruction *EarlierInst = &*llvm::prior(J);
3403 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
3404 switch (EarlierClass) {
3405 case IC_LoadWeak:
3406 case IC_LoadWeakRetained: {
3407 // If this is loading from the same pointer, replace this load's value
3408 // with that one.
3409 CallInst *Call = cast<CallInst>(Inst);
3410 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3411 Value *Arg = Call->getArgOperand(0);
3412 Value *EarlierArg = EarlierCall->getArgOperand(0);
3413 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3414 case AliasAnalysis::MustAlias:
3415 Changed = true;
3416 // If the load has a builtin retain, insert a plain retain for it.
3417 if (Class == IC_LoadWeakRetained) {
3418 CallInst *CI =
3419 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3420 "", Call);
3421 CI->setTailCall();
3422 }
3423 // Zap the fully redundant load.
3424 Call->replaceAllUsesWith(EarlierCall);
3425 Call->eraseFromParent();
3426 goto clobbered;
3427 case AliasAnalysis::MayAlias:
3428 case AliasAnalysis::PartialAlias:
3429 goto clobbered;
3430 case AliasAnalysis::NoAlias:
3431 break;
3432 }
3433 break;
3434 }
3435 case IC_StoreWeak:
3436 case IC_InitWeak: {
3437 // If this is storing to the same pointer and has the same size etc.
3438 // replace this load's value with the stored value.
3439 CallInst *Call = cast<CallInst>(Inst);
3440 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3441 Value *Arg = Call->getArgOperand(0);
3442 Value *EarlierArg = EarlierCall->getArgOperand(0);
3443 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3444 case AliasAnalysis::MustAlias:
3445 Changed = true;
3446 // If the load has a builtin retain, insert a plain retain for it.
3447 if (Class == IC_LoadWeakRetained) {
3448 CallInst *CI =
3449 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3450 "", Call);
3451 CI->setTailCall();
3452 }
3453 // Zap the fully redundant load.
3454 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
3455 Call->eraseFromParent();
3456 goto clobbered;
3457 case AliasAnalysis::MayAlias:
3458 case AliasAnalysis::PartialAlias:
3459 goto clobbered;
3460 case AliasAnalysis::NoAlias:
3461 break;
3462 }
3463 break;
3464 }
3465 case IC_MoveWeak:
3466 case IC_CopyWeak:
3467 // TOOD: Grab the copied value.
3468 goto clobbered;
3469 case IC_AutoreleasepoolPush:
3470 case IC_None:
3471 case IC_User:
3472 // Weak pointers are only modified through the weak entry points
3473 // (and arbitrary calls, which could call the weak entry points).
3474 break;
3475 default:
3476 // Anything else could modify the weak pointer.
3477 goto clobbered;
3478 }
3479 }
3480 clobbered:;
3481 }
3482
3483 // Then, for each destroyWeak with an alloca operand, check to see if
3484 // the alloca and all its users can be zapped.
3485 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3486 Instruction *Inst = &*I++;
3487 InstructionClass Class = GetBasicInstructionClass(Inst);
3488 if (Class != IC_DestroyWeak)
3489 continue;
3490
3491 CallInst *Call = cast<CallInst>(Inst);
3492 Value *Arg = Call->getArgOperand(0);
3493 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
3494 for (Value::use_iterator UI = Alloca->use_begin(),
3495 UE = Alloca->use_end(); UI != UE; ++UI) {
Dan Gohman447989c2012-04-27 18:56:31 +00003496 const Instruction *UserInst = cast<Instruction>(*UI);
John McCall9fbd3182011-06-15 23:37:01 +00003497 switch (GetBasicInstructionClass(UserInst)) {
3498 case IC_InitWeak:
3499 case IC_StoreWeak:
3500 case IC_DestroyWeak:
3501 continue;
3502 default:
3503 goto done;
3504 }
3505 }
3506 Changed = true;
3507 for (Value::use_iterator UI = Alloca->use_begin(),
3508 UE = Alloca->use_end(); UI != UE; ) {
3509 CallInst *UserInst = cast<CallInst>(*UI++);
Dan Gohmance5d8b02012-05-18 22:17:29 +00003510 switch (GetBasicInstructionClass(UserInst)) {
3511 case IC_InitWeak:
3512 case IC_StoreWeak:
3513 // These functions return their second argument.
3514 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
3515 break;
3516 case IC_DestroyWeak:
3517 // No return value.
3518 break;
3519 default:
Dan Gohman4c8f9092012-05-21 17:41:28 +00003520 llvm_unreachable("alloca really is used!");
Dan Gohmance5d8b02012-05-18 22:17:29 +00003521 }
John McCall9fbd3182011-06-15 23:37:01 +00003522 UserInst->eraseFromParent();
3523 }
3524 Alloca->eraseFromParent();
3525 done:;
3526 }
3527 }
3528}
3529
3530/// OptimizeSequences - Identify program paths which execute sequences of
3531/// retains and releases which can be eliminated.
3532bool ObjCARCOpt::OptimizeSequences(Function &F) {
3533 /// Releases, Retains - These are used to store the results of the main flow
3534 /// analysis. These use Value* as the key instead of Instruction* so that the
3535 /// map stays valid when we get around to rewriting code and calls get
3536 /// replaced by arguments.
3537 DenseMap<Value *, RRInfo> Releases;
3538 MapVector<Value *, RRInfo> Retains;
3539
3540 /// BBStates, This is used during the traversal of the function to track the
3541 /// states for each identified object at each block.
3542 DenseMap<const BasicBlock *, BBState> BBStates;
3543
3544 // Analyze the CFG of the function, and all instructions.
3545 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
3546
3547 // Transform.
Dan Gohman44280692011-07-22 22:29:21 +00003548 return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) &&
3549 NestingDetected;
John McCall9fbd3182011-06-15 23:37:01 +00003550}
3551
3552/// OptimizeReturns - Look for this pattern:
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +00003553/// \code
John McCall9fbd3182011-06-15 23:37:01 +00003554/// %call = call i8* @something(...)
3555/// %2 = call i8* @objc_retain(i8* %call)
3556/// %3 = call i8* @objc_autorelease(i8* %2)
3557/// ret i8* %3
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +00003558/// \endcode
John McCall9fbd3182011-06-15 23:37:01 +00003559/// And delete the retain and autorelease.
3560///
3561/// Otherwise if it's just this:
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +00003562/// \code
John McCall9fbd3182011-06-15 23:37:01 +00003563/// %3 = call i8* @objc_autorelease(i8* %2)
3564/// ret i8* %3
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +00003565/// \endcode
John McCall9fbd3182011-06-15 23:37:01 +00003566/// convert the autorelease to autoreleaseRV.
3567void ObjCARCOpt::OptimizeReturns(Function &F) {
3568 if (!F.getReturnType()->isPointerTy())
3569 return;
3570
3571 SmallPtrSet<Instruction *, 4> DependingInstructions;
3572 SmallPtrSet<const BasicBlock *, 4> Visited;
3573 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3574 BasicBlock *BB = FI;
3575 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
3576 if (!Ret) continue;
3577
3578 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
3579 FindDependencies(NeedsPositiveRetainCount, Arg,
3580 BB, Ret, DependingInstructions, Visited, PA);
3581 if (DependingInstructions.size() != 1)
3582 goto next_block;
3583
3584 {
3585 CallInst *Autorelease =
3586 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3587 if (!Autorelease)
3588 goto next_block;
Dan Gohman0daef3d2012-05-08 23:39:44 +00003589 InstructionClass AutoreleaseClass = GetBasicInstructionClass(Autorelease);
John McCall9fbd3182011-06-15 23:37:01 +00003590 if (!IsAutorelease(AutoreleaseClass))
3591 goto next_block;
3592 if (GetObjCArg(Autorelease) != Arg)
3593 goto next_block;
3594
3595 DependingInstructions.clear();
3596 Visited.clear();
3597
3598 // Check that there is nothing that can affect the reference
3599 // count between the autorelease and the retain.
3600 FindDependencies(CanChangeRetainCount, Arg,
3601 BB, Autorelease, DependingInstructions, Visited, PA);
3602 if (DependingInstructions.size() != 1)
3603 goto next_block;
3604
3605 {
3606 CallInst *Retain =
3607 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3608
3609 // Check that we found a retain with the same argument.
3610 if (!Retain ||
3611 !IsRetain(GetBasicInstructionClass(Retain)) ||
3612 GetObjCArg(Retain) != Arg)
3613 goto next_block;
3614
3615 DependingInstructions.clear();
3616 Visited.clear();
3617
3618 // Convert the autorelease to an autoreleaseRV, since it's
3619 // returning the value.
3620 if (AutoreleaseClass == IC_Autorelease) {
3621 Autorelease->setCalledFunction(getAutoreleaseRVCallee(F.getParent()));
3622 AutoreleaseClass = IC_AutoreleaseRV;
3623 }
3624
3625 // Check that there is nothing that can affect the reference
3626 // count between the retain and the call.
Dan Gohman27e06662011-09-29 22:27:34 +00003627 // Note that Retain need not be in BB.
3628 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
John McCall9fbd3182011-06-15 23:37:01 +00003629 DependingInstructions, Visited, PA);
3630 if (DependingInstructions.size() != 1)
3631 goto next_block;
3632
3633 {
3634 CallInst *Call =
3635 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3636
3637 // Check that the pointer is the return value of the call.
3638 if (!Call || Arg != Call)
3639 goto next_block;
3640
3641 // Check that the call is a regular call.
3642 InstructionClass Class = GetBasicInstructionClass(Call);
3643 if (Class != IC_CallOrUser && Class != IC_Call)
3644 goto next_block;
3645
3646 // If so, we can zap the retain and autorelease.
3647 Changed = true;
3648 ++NumRets;
3649 EraseInstruction(Retain);
3650 EraseInstruction(Autorelease);
3651 }
3652 }
3653 }
3654
3655 next_block:
3656 DependingInstructions.clear();
3657 Visited.clear();
3658 }
3659}
3660
3661bool ObjCARCOpt::doInitialization(Module &M) {
3662 if (!EnableARCOpts)
3663 return false;
3664
Dan Gohmand6bf2012012-04-13 18:57:48 +00003665 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003666 Run = ModuleHasARC(M);
3667 if (!Run)
3668 return false;
3669
John McCall9fbd3182011-06-15 23:37:01 +00003670 // Identify the imprecise release metadata kind.
3671 ImpreciseReleaseMDKind =
3672 M.getContext().getMDKindID("clang.imprecise_release");
Dan Gohmana974bea2011-10-17 22:53:25 +00003673 CopyOnEscapeMDKind =
3674 M.getContext().getMDKindID("clang.arc.copy_on_escape");
Dan Gohmandbe266b2012-02-17 18:59:53 +00003675 NoObjCARCExceptionsMDKind =
3676 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
John McCall9fbd3182011-06-15 23:37:01 +00003677
John McCall9fbd3182011-06-15 23:37:01 +00003678 // Intuitively, objc_retain and others are nocapture, however in practice
3679 // they are not, because they return their argument value. And objc_release
Dan Gohman447989c2012-04-27 18:56:31 +00003680 // calls finalizers which can have arbitrary side effects.
John McCall9fbd3182011-06-15 23:37:01 +00003681
3682 // These are initialized lazily.
3683 RetainRVCallee = 0;
3684 AutoreleaseRVCallee = 0;
3685 ReleaseCallee = 0;
3686 RetainCallee = 0;
Dan Gohman44280692011-07-22 22:29:21 +00003687 RetainBlockCallee = 0;
John McCall9fbd3182011-06-15 23:37:01 +00003688 AutoreleaseCallee = 0;
3689
3690 return false;
3691}
3692
3693bool ObjCARCOpt::runOnFunction(Function &F) {
3694 if (!EnableARCOpts)
3695 return false;
3696
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003697 // If nothing in the Module uses ARC, don't do anything.
3698 if (!Run)
3699 return false;
3700
John McCall9fbd3182011-06-15 23:37:01 +00003701 Changed = false;
3702
3703 PA.setAA(&getAnalysis<AliasAnalysis>());
3704
3705 // This pass performs several distinct transformations. As a compile-time aid
3706 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3707 // library functions aren't declared.
3708
3709 // Preliminary optimizations. This also computs UsedInThisFunction.
3710 OptimizeIndividualCalls(F);
3711
3712 // Optimizations for weak pointers.
3713 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3714 (1 << IC_LoadWeakRetained) |
3715 (1 << IC_StoreWeak) |
3716 (1 << IC_InitWeak) |
3717 (1 << IC_CopyWeak) |
3718 (1 << IC_MoveWeak) |
3719 (1 << IC_DestroyWeak)))
3720 OptimizeWeakCalls(F);
3721
3722 // Optimizations for retain+release pairs.
3723 if (UsedInThisFunction & ((1 << IC_Retain) |
3724 (1 << IC_RetainRV) |
3725 (1 << IC_RetainBlock)))
3726 if (UsedInThisFunction & (1 << IC_Release))
3727 // Run OptimizeSequences until it either stops making changes or
3728 // no retain+release pair nesting is detected.
3729 while (OptimizeSequences(F)) {}
3730
3731 // Optimizations if objc_autorelease is used.
Dan Gohman0daef3d2012-05-08 23:39:44 +00003732 if (UsedInThisFunction & ((1 << IC_Autorelease) |
3733 (1 << IC_AutoreleaseRV)))
John McCall9fbd3182011-06-15 23:37:01 +00003734 OptimizeReturns(F);
3735
3736 return Changed;
3737}
3738
3739void ObjCARCOpt::releaseMemory() {
3740 PA.clear();
3741}
3742
3743//===----------------------------------------------------------------------===//
3744// ARC contraction.
3745//===----------------------------------------------------------------------===//
3746
3747// TODO: ObjCARCContract could insert PHI nodes when uses aren't
3748// dominated by single calls.
3749
3750#include "llvm/Operator.h"
3751#include "llvm/InlineAsm.h"
3752#include "llvm/Analysis/Dominators.h"
3753
3754STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed");
3755
3756namespace {
3757 /// ObjCARCContract - Late ARC optimizations. These change the IR in a way
3758 /// that makes it difficult to be analyzed by ObjCARCOpt, so it's run late.
3759 class ObjCARCContract : public FunctionPass {
3760 bool Changed;
3761 AliasAnalysis *AA;
3762 DominatorTree *DT;
3763 ProvenanceAnalysis PA;
3764
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003765 /// Run - A flag indicating whether this optimization pass should run.
3766 bool Run;
3767
John McCall9fbd3182011-06-15 23:37:01 +00003768 /// StoreStrongCallee, etc. - Declarations for ObjC runtime
3769 /// functions, for use in creating calls to them. These are initialized
3770 /// lazily to avoid cluttering up the Module with unused declarations.
3771 Constant *StoreStrongCallee,
3772 *RetainAutoreleaseCallee, *RetainAutoreleaseRVCallee;
3773
3774 /// RetainRVMarker - The inline asm string to insert between calls and
3775 /// RetainRV calls to make the optimization work on targets which need it.
3776 const MDString *RetainRVMarker;
3777
Dan Gohman0cdece42012-01-19 19:14:36 +00003778 /// StoreStrongCalls - The set of inserted objc_storeStrong calls. If
3779 /// at the end of walking the function we have found no alloca
3780 /// instructions, these calls can be marked "tail".
Dan Gohman0daef3d2012-05-08 23:39:44 +00003781 SmallPtrSet<CallInst *, 8> StoreStrongCalls;
Dan Gohman0cdece42012-01-19 19:14:36 +00003782
John McCall9fbd3182011-06-15 23:37:01 +00003783 Constant *getStoreStrongCallee(Module *M);
3784 Constant *getRetainAutoreleaseCallee(Module *M);
3785 Constant *getRetainAutoreleaseRVCallee(Module *M);
3786
3787 bool ContractAutorelease(Function &F, Instruction *Autorelease,
3788 InstructionClass Class,
3789 SmallPtrSet<Instruction *, 4>
3790 &DependingInstructions,
3791 SmallPtrSet<const BasicBlock *, 4>
3792 &Visited);
3793
3794 void ContractRelease(Instruction *Release,
3795 inst_iterator &Iter);
3796
3797 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
3798 virtual bool doInitialization(Module &M);
3799 virtual bool runOnFunction(Function &F);
3800
3801 public:
3802 static char ID;
3803 ObjCARCContract() : FunctionPass(ID) {
3804 initializeObjCARCContractPass(*PassRegistry::getPassRegistry());
3805 }
3806 };
3807}
3808
3809char ObjCARCContract::ID = 0;
3810INITIALIZE_PASS_BEGIN(ObjCARCContract,
3811 "objc-arc-contract", "ObjC ARC contraction", false, false)
3812INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3813INITIALIZE_PASS_DEPENDENCY(DominatorTree)
3814INITIALIZE_PASS_END(ObjCARCContract,
3815 "objc-arc-contract", "ObjC ARC contraction", false, false)
3816
3817Pass *llvm::createObjCARCContractPass() {
3818 return new ObjCARCContract();
3819}
3820
3821void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const {
3822 AU.addRequired<AliasAnalysis>();
3823 AU.addRequired<DominatorTree>();
3824 AU.setPreservesCFG();
3825}
3826
3827Constant *ObjCARCContract::getStoreStrongCallee(Module *M) {
3828 if (!StoreStrongCallee) {
3829 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00003830 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3831 Type *I8XX = PointerType::getUnqual(I8X);
Dan Gohman0daef3d2012-05-08 23:39:44 +00003832 Type *Params[] = { I8XX, I8X };
John McCall9fbd3182011-06-15 23:37:01 +00003833
Dan Gohman0daef3d2012-05-08 23:39:44 +00003834 AttrListPtr Attributes = AttrListPtr()
3835 .addAttr(~0u, Attribute::NoUnwind)
3836 .addAttr(1, Attribute::NoCapture);
John McCall9fbd3182011-06-15 23:37:01 +00003837
3838 StoreStrongCallee =
3839 M->getOrInsertFunction(
3840 "objc_storeStrong",
3841 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
3842 Attributes);
3843 }
3844 return StoreStrongCallee;
3845}
3846
3847Constant *ObjCARCContract::getRetainAutoreleaseCallee(Module *M) {
3848 if (!RetainAutoreleaseCallee) {
3849 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00003850 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman0daef3d2012-05-08 23:39:44 +00003851 Type *Params[] = { I8X };
3852 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
3853 AttrListPtr Attributes = AttrListPtr().addAttr(~0u, Attribute::NoUnwind);
John McCall9fbd3182011-06-15 23:37:01 +00003854 RetainAutoreleaseCallee =
3855 M->getOrInsertFunction("objc_retainAutorelease", FTy, Attributes);
3856 }
3857 return RetainAutoreleaseCallee;
3858}
3859
3860Constant *ObjCARCContract::getRetainAutoreleaseRVCallee(Module *M) {
3861 if (!RetainAutoreleaseRVCallee) {
3862 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00003863 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman0daef3d2012-05-08 23:39:44 +00003864 Type *Params[] = { I8X };
3865 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
3866 AttrListPtr Attributes = AttrListPtr().addAttr(~0u, Attribute::NoUnwind);
John McCall9fbd3182011-06-15 23:37:01 +00003867 RetainAutoreleaseRVCallee =
3868 M->getOrInsertFunction("objc_retainAutoreleaseReturnValue", FTy,
3869 Attributes);
3870 }
3871 return RetainAutoreleaseRVCallee;
3872}
3873
Dan Gohman447989c2012-04-27 18:56:31 +00003874/// ContractAutorelease - Merge an autorelease with a retain into a fused call.
John McCall9fbd3182011-06-15 23:37:01 +00003875bool
3876ObjCARCContract::ContractAutorelease(Function &F, Instruction *Autorelease,
3877 InstructionClass Class,
3878 SmallPtrSet<Instruction *, 4>
3879 &DependingInstructions,
3880 SmallPtrSet<const BasicBlock *, 4>
3881 &Visited) {
3882 const Value *Arg = GetObjCArg(Autorelease);
3883
3884 // Check that there are no instructions between the retain and the autorelease
3885 // (such as an autorelease_pop) which may change the count.
3886 CallInst *Retain = 0;
3887 if (Class == IC_AutoreleaseRV)
3888 FindDependencies(RetainAutoreleaseRVDep, Arg,
3889 Autorelease->getParent(), Autorelease,
3890 DependingInstructions, Visited, PA);
3891 else
3892 FindDependencies(RetainAutoreleaseDep, Arg,
3893 Autorelease->getParent(), Autorelease,
3894 DependingInstructions, Visited, PA);
3895
3896 Visited.clear();
3897 if (DependingInstructions.size() != 1) {
3898 DependingInstructions.clear();
3899 return false;
3900 }
3901
3902 Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3903 DependingInstructions.clear();
3904
3905 if (!Retain ||
3906 GetBasicInstructionClass(Retain) != IC_Retain ||
3907 GetObjCArg(Retain) != Arg)
3908 return false;
3909
3910 Changed = true;
3911 ++NumPeeps;
3912
3913 if (Class == IC_AutoreleaseRV)
3914 Retain->setCalledFunction(getRetainAutoreleaseRVCallee(F.getParent()));
3915 else
3916 Retain->setCalledFunction(getRetainAutoreleaseCallee(F.getParent()));
3917
3918 EraseInstruction(Autorelease);
3919 return true;
3920}
3921
3922/// ContractRelease - Attempt to merge an objc_release with a store, load, and
3923/// objc_retain to form an objc_storeStrong. This can be a little tricky because
3924/// the instructions don't always appear in order, and there may be unrelated
3925/// intervening instructions.
3926void ObjCARCContract::ContractRelease(Instruction *Release,
3927 inst_iterator &Iter) {
3928 LoadInst *Load = dyn_cast<LoadInst>(GetObjCArg(Release));
Eli Friedman2bc3d522011-09-12 20:23:13 +00003929 if (!Load || !Load->isSimple()) return;
John McCall9fbd3182011-06-15 23:37:01 +00003930
3931 // For now, require everything to be in one basic block.
3932 BasicBlock *BB = Release->getParent();
3933 if (Load->getParent() != BB) return;
3934
Dan Gohman4670dac2012-05-08 23:34:08 +00003935 // Walk down to find the store and the release, which may be in either order.
Dan Gohman95b8cf12012-05-09 23:08:33 +00003936 BasicBlock::iterator I = Load, End = BB->end();
John McCall9fbd3182011-06-15 23:37:01 +00003937 ++I;
3938 AliasAnalysis::Location Loc = AA->getLocation(Load);
Dan Gohman4670dac2012-05-08 23:34:08 +00003939 StoreInst *Store = 0;
3940 bool SawRelease = false;
3941 for (; !Store || !SawRelease; ++I) {
Dan Gohman95b8cf12012-05-09 23:08:33 +00003942 if (I == End)
3943 return;
3944
Dan Gohman4670dac2012-05-08 23:34:08 +00003945 Instruction *Inst = I;
3946 if (Inst == Release) {
3947 SawRelease = true;
3948 continue;
3949 }
3950
3951 InstructionClass Class = GetBasicInstructionClass(Inst);
3952
3953 // Unrelated retains are harmless.
3954 if (IsRetain(Class))
3955 continue;
3956
3957 if (Store) {
3958 // The store is the point where we're going to put the objc_storeStrong,
3959 // so make sure there are no uses after it.
3960 if (CanUse(Inst, Load, PA, Class))
3961 return;
3962 } else if (AA->getModRefInfo(Inst, Loc) & AliasAnalysis::Mod) {
3963 // We are moving the load down to the store, so check for anything
3964 // else which writes to the memory between the load and the store.
3965 Store = dyn_cast<StoreInst>(Inst);
3966 if (!Store || !Store->isSimple()) return;
3967 if (Store->getPointerOperand() != Loc.Ptr) return;
3968 }
3969 }
John McCall9fbd3182011-06-15 23:37:01 +00003970
3971 Value *New = StripPointerCastsAndObjCCalls(Store->getValueOperand());
3972
3973 // Walk up to find the retain.
3974 I = Store;
3975 BasicBlock::iterator Begin = BB->begin();
3976 while (I != Begin && GetBasicInstructionClass(I) != IC_Retain)
3977 --I;
3978 Instruction *Retain = I;
3979 if (GetBasicInstructionClass(Retain) != IC_Retain) return;
3980 if (GetObjCArg(Retain) != New) return;
3981
3982 Changed = true;
3983 ++NumStoreStrongs;
3984
3985 LLVMContext &C = Release->getContext();
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003986 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3987 Type *I8XX = PointerType::getUnqual(I8X);
John McCall9fbd3182011-06-15 23:37:01 +00003988
3989 Value *Args[] = { Load->getPointerOperand(), New };
3990 if (Args[0]->getType() != I8XX)
3991 Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
3992 if (Args[1]->getType() != I8X)
3993 Args[1] = new BitCastInst(Args[1], I8X, "", Store);
3994 CallInst *StoreStrong =
3995 CallInst::Create(getStoreStrongCallee(BB->getParent()->getParent()),
Jay Foada3efbb12011-07-15 08:37:34 +00003996 Args, "", Store);
John McCall9fbd3182011-06-15 23:37:01 +00003997 StoreStrong->setDoesNotThrow();
3998 StoreStrong->setDebugLoc(Store->getDebugLoc());
3999
Dan Gohman0cdece42012-01-19 19:14:36 +00004000 // We can't set the tail flag yet, because we haven't yet determined
4001 // whether there are any escaping allocas. Remember this call, so that
4002 // we can set the tail flag once we know it's safe.
4003 StoreStrongCalls.insert(StoreStrong);
4004
John McCall9fbd3182011-06-15 23:37:01 +00004005 if (&*Iter == Store) ++Iter;
4006 Store->eraseFromParent();
4007 Release->eraseFromParent();
4008 EraseInstruction(Retain);
4009 if (Load->use_empty())
4010 Load->eraseFromParent();
4011}
4012
4013bool ObjCARCContract::doInitialization(Module &M) {
Dan Gohmand6bf2012012-04-13 18:57:48 +00004014 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00004015 Run = ModuleHasARC(M);
4016 if (!Run)
4017 return false;
4018
John McCall9fbd3182011-06-15 23:37:01 +00004019 // These are initialized lazily.
4020 StoreStrongCallee = 0;
4021 RetainAutoreleaseCallee = 0;
4022 RetainAutoreleaseRVCallee = 0;
4023
4024 // Initialize RetainRVMarker.
4025 RetainRVMarker = 0;
4026 if (NamedMDNode *NMD =
4027 M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker"))
4028 if (NMD->getNumOperands() == 1) {
4029 const MDNode *N = NMD->getOperand(0);
4030 if (N->getNumOperands() == 1)
4031 if (const MDString *S = dyn_cast<MDString>(N->getOperand(0)))
4032 RetainRVMarker = S;
4033 }
4034
4035 return false;
4036}
4037
4038bool ObjCARCContract::runOnFunction(Function &F) {
4039 if (!EnableARCOpts)
4040 return false;
4041
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00004042 // If nothing in the Module uses ARC, don't do anything.
4043 if (!Run)
4044 return false;
4045
John McCall9fbd3182011-06-15 23:37:01 +00004046 Changed = false;
4047 AA = &getAnalysis<AliasAnalysis>();
4048 DT = &getAnalysis<DominatorTree>();
4049
4050 PA.setAA(&getAnalysis<AliasAnalysis>());
4051
Dan Gohman0cdece42012-01-19 19:14:36 +00004052 // Track whether it's ok to mark objc_storeStrong calls with the "tail"
4053 // keyword. Be conservative if the function has variadic arguments.
4054 // It seems that functions which "return twice" are also unsafe for the
4055 // "tail" argument, because they are setjmp, which could need to
4056 // return to an earlier stack state.
Dan Gohman0daef3d2012-05-08 23:39:44 +00004057 bool TailOkForStoreStrongs = !F.isVarArg() &&
4058 !F.callsFunctionThatReturnsTwice();
Dan Gohman0cdece42012-01-19 19:14:36 +00004059
John McCall9fbd3182011-06-15 23:37:01 +00004060 // For ObjC library calls which return their argument, replace uses of the
4061 // argument with uses of the call return value, if it dominates the use. This
4062 // reduces register pressure.
4063 SmallPtrSet<Instruction *, 4> DependingInstructions;
4064 SmallPtrSet<const BasicBlock *, 4> Visited;
4065 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
4066 Instruction *Inst = &*I++;
4067
4068 // Only these library routines return their argument. In particular,
4069 // objc_retainBlock does not necessarily return its argument.
4070 InstructionClass Class = GetBasicInstructionClass(Inst);
4071 switch (Class) {
4072 case IC_Retain:
4073 case IC_FusedRetainAutorelease:
4074 case IC_FusedRetainAutoreleaseRV:
4075 break;
4076 case IC_Autorelease:
4077 case IC_AutoreleaseRV:
4078 if (ContractAutorelease(F, Inst, Class, DependingInstructions, Visited))
4079 continue;
4080 break;
4081 case IC_RetainRV: {
4082 // If we're compiling for a target which needs a special inline-asm
4083 // marker to do the retainAutoreleasedReturnValue optimization,
4084 // insert it now.
4085 if (!RetainRVMarker)
4086 break;
4087 BasicBlock::iterator BBI = Inst;
Dan Gohman58fb3402012-06-25 19:47:37 +00004088 BasicBlock *InstParent = Inst->getParent();
4089
4090 // Step up to see if the call immediately precedes the RetainRV call.
4091 // If it's an invoke, we have to cross a block boundary. And we have
4092 // to carefully dodge no-op instructions.
4093 do {
4094 if (&*BBI == InstParent->begin()) {
4095 BasicBlock *Pred = InstParent->getSinglePredecessor();
4096 if (!Pred)
4097 goto decline_rv_optimization;
4098 BBI = Pred->getTerminator();
4099 break;
4100 }
4101 --BBI;
4102 } while (isNoopInstruction(BBI));
4103
John McCall9fbd3182011-06-15 23:37:01 +00004104 if (&*BBI == GetObjCArg(Inst)) {
Dan Gohmand6bf2012012-04-13 18:57:48 +00004105 Changed = true;
John McCall9fbd3182011-06-15 23:37:01 +00004106 InlineAsm *IA =
4107 InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()),
4108 /*isVarArg=*/false),
4109 RetainRVMarker->getString(),
4110 /*Constraints=*/"", /*hasSideEffects=*/true);
4111 CallInst::Create(IA, "", Inst);
4112 }
Dan Gohman58fb3402012-06-25 19:47:37 +00004113 decline_rv_optimization:
John McCall9fbd3182011-06-15 23:37:01 +00004114 break;
4115 }
4116 case IC_InitWeak: {
4117 // objc_initWeak(p, null) => *p = null
4118 CallInst *CI = cast<CallInst>(Inst);
4119 if (isNullOrUndef(CI->getArgOperand(1))) {
4120 Value *Null =
4121 ConstantPointerNull::get(cast<PointerType>(CI->getType()));
4122 Changed = true;
4123 new StoreInst(Null, CI->getArgOperand(0), CI);
4124 CI->replaceAllUsesWith(Null);
4125 CI->eraseFromParent();
4126 }
4127 continue;
4128 }
4129 case IC_Release:
4130 ContractRelease(Inst, I);
4131 continue;
Dan Gohman0cdece42012-01-19 19:14:36 +00004132 case IC_User:
4133 // Be conservative if the function has any alloca instructions.
4134 // Technically we only care about escaping alloca instructions,
4135 // but this is sufficient to handle some interesting cases.
4136 if (isa<AllocaInst>(Inst))
4137 TailOkForStoreStrongs = false;
4138 continue;
John McCall9fbd3182011-06-15 23:37:01 +00004139 default:
4140 continue;
4141 }
4142
4143 // Don't use GetObjCArg because we don't want to look through bitcasts
4144 // and such; to do the replacement, the argument must have type i8*.
4145 const Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
4146 for (;;) {
4147 // If we're compiling bugpointed code, don't get in trouble.
4148 if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
4149 break;
4150 // Look through the uses of the pointer.
4151 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
4152 UI != UE; ) {
4153 Use &U = UI.getUse();
4154 unsigned OperandNo = UI.getOperandNo();
4155 ++UI; // Increment UI now, because we may unlink its element.
Dan Gohmand6bf2012012-04-13 18:57:48 +00004156
4157 // If the call's return value dominates a use of the call's argument
4158 // value, rewrite the use to use the return value. We check for
4159 // reachability here because an unreachable call is considered to
4160 // trivially dominate itself, which would lead us to rewriting its
4161 // argument in terms of its return value, which would lead to
4162 // infinite loops in GetObjCArg.
Dan Gohman0daef3d2012-05-08 23:39:44 +00004163 if (DT->isReachableFromEntry(U) && DT->dominates(Inst, U)) {
Rafael Espindola2453dff2012-03-15 15:52:59 +00004164 Changed = true;
4165 Instruction *Replacement = Inst;
4166 Type *UseTy = U.get()->getType();
Dan Gohman6c189ec2012-04-13 01:08:28 +00004167 if (PHINode *PHI = dyn_cast<PHINode>(U.getUser())) {
Rafael Espindola2453dff2012-03-15 15:52:59 +00004168 // For PHI nodes, insert the bitcast in the predecessor block.
Dan Gohman0daef3d2012-05-08 23:39:44 +00004169 unsigned ValNo = PHINode::getIncomingValueNumForOperand(OperandNo);
4170 BasicBlock *BB = PHI->getIncomingBlock(ValNo);
Rafael Espindola2453dff2012-03-15 15:52:59 +00004171 if (Replacement->getType() != UseTy)
4172 Replacement = new BitCastInst(Replacement, UseTy, "",
4173 &BB->back());
Dan Gohmand6bf2012012-04-13 18:57:48 +00004174 // While we're here, rewrite all edges for this PHI, rather
4175 // than just one use at a time, to minimize the number of
4176 // bitcasts we emit.
Dan Gohman447989c2012-04-27 18:56:31 +00004177 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
Rafael Espindola2453dff2012-03-15 15:52:59 +00004178 if (PHI->getIncomingBlock(i) == BB) {
4179 // Keep the UI iterator valid.
4180 if (&PHI->getOperandUse(
4181 PHINode::getOperandNumForIncomingValue(i)) ==
4182 &UI.getUse())
4183 ++UI;
4184 PHI->setIncomingValue(i, Replacement);
4185 }
4186 } else {
4187 if (Replacement->getType() != UseTy)
Dan Gohman6c189ec2012-04-13 01:08:28 +00004188 Replacement = new BitCastInst(Replacement, UseTy, "",
4189 cast<Instruction>(U.getUser()));
Rafael Espindola2453dff2012-03-15 15:52:59 +00004190 U.set(Replacement);
John McCall9fbd3182011-06-15 23:37:01 +00004191 }
Rafael Espindola2453dff2012-03-15 15:52:59 +00004192 }
John McCall9fbd3182011-06-15 23:37:01 +00004193 }
4194
Dan Gohman447989c2012-04-27 18:56:31 +00004195 // If Arg is a no-op casted pointer, strip one level of casts and iterate.
John McCall9fbd3182011-06-15 23:37:01 +00004196 if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
4197 Arg = BI->getOperand(0);
4198 else if (isa<GEPOperator>(Arg) &&
4199 cast<GEPOperator>(Arg)->hasAllZeroIndices())
4200 Arg = cast<GEPOperator>(Arg)->getPointerOperand();
4201 else if (isa<GlobalAlias>(Arg) &&
4202 !cast<GlobalAlias>(Arg)->mayBeOverridden())
4203 Arg = cast<GlobalAlias>(Arg)->getAliasee();
4204 else
4205 break;
4206 }
4207 }
4208
Dan Gohman0cdece42012-01-19 19:14:36 +00004209 // If this function has no escaping allocas or suspicious vararg usage,
4210 // objc_storeStrong calls can be marked with the "tail" keyword.
4211 if (TailOkForStoreStrongs)
Dan Gohman0daef3d2012-05-08 23:39:44 +00004212 for (SmallPtrSet<CallInst *, 8>::iterator I = StoreStrongCalls.begin(),
Dan Gohman0cdece42012-01-19 19:14:36 +00004213 E = StoreStrongCalls.end(); I != E; ++I)
4214 (*I)->setTailCall();
4215 StoreStrongCalls.clear();
4216
John McCall9fbd3182011-06-15 23:37:01 +00004217 return Changed;
4218}