blob: 928440150c23658deaeec84db83e0c50efdd2e39 [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
23// by name, and hardwires knowedge of their semantics.
24//
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"
32#include "llvm/Function.h"
33#include "llvm/Intrinsics.h"
34#include "llvm/GlobalVariable.h"
35#include "llvm/DerivedTypes.h"
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +000036#include "llvm/Module.h"
John McCall9fbd3182011-06-15 23:37:01 +000037#include "llvm/Analysis/ValueTracking.h"
38#include "llvm/Transforms/Utils/Local.h"
39#include "llvm/Support/CallSite.h"
40#include "llvm/Support/CommandLine.h"
41#include "llvm/ADT/StringSwitch.h"
42#include "llvm/ADT/DenseMap.h"
43#include "llvm/ADT/STLExtras.h"
44using namespace llvm;
45
46// A handy option to enable/disable all optimizations in this file.
47static cl::opt<bool> EnableARCOpts("enable-objc-arc-opts", cl::init(true));
48
49//===----------------------------------------------------------------------===//
50// Misc. Utilities
51//===----------------------------------------------------------------------===//
52
53namespace {
54 /// MapVector - An associative container with fast insertion-order
55 /// (deterministic) iteration over its elements. Plus the special
56 /// blot operation.
57 template<class KeyT, class ValueT>
58 class MapVector {
59 /// Map - Map keys to indices in Vector.
60 typedef DenseMap<KeyT, size_t> MapTy;
61 MapTy Map;
62
63 /// Vector - Keys and values.
64 typedef std::vector<std::pair<KeyT, ValueT> > VectorTy;
65 VectorTy Vector;
66
67 public:
68 typedef typename VectorTy::iterator iterator;
69 typedef typename VectorTy::const_iterator const_iterator;
70 iterator begin() { return Vector.begin(); }
71 iterator end() { return Vector.end(); }
72 const_iterator begin() const { return Vector.begin(); }
73 const_iterator end() const { return Vector.end(); }
74
75#ifdef XDEBUG
76 ~MapVector() {
77 assert(Vector.size() >= Map.size()); // May differ due to blotting.
78 for (typename MapTy::const_iterator I = Map.begin(), E = Map.end();
79 I != E; ++I) {
80 assert(I->second < Vector.size());
81 assert(Vector[I->second].first == I->first);
82 }
83 for (typename VectorTy::const_iterator I = Vector.begin(),
84 E = Vector.end(); I != E; ++I)
85 assert(!I->first ||
86 (Map.count(I->first) &&
87 Map[I->first] == size_t(I - Vector.begin())));
88 }
89#endif
90
91 ValueT &operator[](KeyT Arg) {
92 std::pair<typename MapTy::iterator, bool> Pair =
93 Map.insert(std::make_pair(Arg, size_t(0)));
94 if (Pair.second) {
95 Pair.first->second = Vector.size();
96 Vector.push_back(std::make_pair(Arg, ValueT()));
97 return Vector.back().second;
98 }
99 return Vector[Pair.first->second].second;
100 }
101
102 std::pair<iterator, bool>
103 insert(const std::pair<KeyT, ValueT> &InsertPair) {
104 std::pair<typename MapTy::iterator, bool> Pair =
105 Map.insert(std::make_pair(InsertPair.first, size_t(0)));
106 if (Pair.second) {
107 Pair.first->second = Vector.size();
108 Vector.push_back(InsertPair);
109 return std::make_pair(llvm::prior(Vector.end()), true);
110 }
111 return std::make_pair(Vector.begin() + Pair.first->second, false);
112 }
113
114 const_iterator find(KeyT Key) const {
115 typename MapTy::const_iterator It = Map.find(Key);
116 if (It == Map.end()) return Vector.end();
117 return Vector.begin() + It->second;
118 }
119
120 /// blot - This is similar to erase, but instead of removing the element
121 /// from the vector, it just zeros out the key in the vector. This leaves
122 /// iterators intact, but clients must be prepared for zeroed-out keys when
123 /// iterating.
124 void blot(KeyT Key) {
125 typename MapTy::iterator It = Map.find(Key);
126 if (It == Map.end()) return;
127 Vector[It->second].first = KeyT();
128 Map.erase(It);
129 }
130
131 void clear() {
132 Map.clear();
133 Vector.clear();
134 }
135 };
136}
137
138//===----------------------------------------------------------------------===//
139// ARC Utilities.
140//===----------------------------------------------------------------------===//
141
142namespace {
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)
163 IC_CallOrUser, ///< could call objc_release and/or "use" pointers
164 IC_Call, ///< could call objc_release
165 IC_User, ///< could "use" a pointer
166 IC_None ///< anything else
167 };
168}
169
170/// IsPotentialUse - Test whether the given value is possible a
171/// reference-counted pointer.
172static bool IsPotentialUse(const Value *Op) {
173 // Pointers to static or stack storage are not reference-counted pointers.
174 if (isa<Constant>(Op) || isa<AllocaInst>(Op))
175 return false;
176 // Special arguments are not reference-counted.
177 if (const Argument *Arg = dyn_cast<Argument>(Op))
178 if (Arg->hasByValAttr() ||
179 Arg->hasNestAttr() ||
180 Arg->hasStructRetAttr())
181 return false;
Dan Gohmanf9096e42011-12-14 19:10:53 +0000182 // Only consider values with pointer types.
183 // It seemes intuitive to exclude function pointer types as well, since
184 // functions are never reference-counted, however clang occasionally
185 // bitcasts reference-counted pointers to function-pointer type
186 // temporarily.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000187 PointerType *Ty = dyn_cast<PointerType>(Op->getType());
Dan Gohmanf9096e42011-12-14 19:10:53 +0000188 if (!Ty)
John McCall9fbd3182011-06-15 23:37:01 +0000189 return false;
190 // Conservatively assume anything else is a potential use.
191 return true;
192}
193
194/// GetCallSiteClass - Helper for GetInstructionClass. Determines what kind
195/// of construct CS is.
196static InstructionClass GetCallSiteClass(ImmutableCallSite CS) {
197 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
198 I != E; ++I)
199 if (IsPotentialUse(*I))
200 return CS.onlyReadsMemory() ? IC_User : IC_CallOrUser;
201
202 return CS.onlyReadsMemory() ? IC_None : IC_Call;
203}
204
205/// GetFunctionClass - Determine if F is one of the special known Functions.
206/// If it isn't, return IC_CallOrUser.
207static InstructionClass GetFunctionClass(const Function *F) {
208 Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
209
210 // No arguments.
211 if (AI == AE)
212 return StringSwitch<InstructionClass>(F->getName())
213 .Case("objc_autoreleasePoolPush", IC_AutoreleasepoolPush)
214 .Default(IC_CallOrUser);
215
216 // One argument.
217 const Argument *A0 = AI++;
218 if (AI == AE)
219 // Argument is a pointer.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000220 if (PointerType *PTy = dyn_cast<PointerType>(A0->getType())) {
221 Type *ETy = PTy->getElementType();
John McCall9fbd3182011-06-15 23:37:01 +0000222 // Argument is i8*.
223 if (ETy->isIntegerTy(8))
224 return StringSwitch<InstructionClass>(F->getName())
225 .Case("objc_retain", IC_Retain)
226 .Case("objc_retainAutoreleasedReturnValue", IC_RetainRV)
227 .Case("objc_retainBlock", IC_RetainBlock)
228 .Case("objc_release", IC_Release)
229 .Case("objc_autorelease", IC_Autorelease)
230 .Case("objc_autoreleaseReturnValue", IC_AutoreleaseRV)
231 .Case("objc_autoreleasePoolPop", IC_AutoreleasepoolPop)
232 .Case("objc_retainedObject", IC_NoopCast)
233 .Case("objc_unretainedObject", IC_NoopCast)
234 .Case("objc_unretainedPointer", IC_NoopCast)
235 .Case("objc_retain_autorelease", IC_FusedRetainAutorelease)
236 .Case("objc_retainAutorelease", IC_FusedRetainAutorelease)
237 .Case("objc_retainAutoreleaseReturnValue",IC_FusedRetainAutoreleaseRV)
238 .Default(IC_CallOrUser);
239
240 // Argument is i8**
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000241 if (PointerType *Pte = dyn_cast<PointerType>(ETy))
John McCall9fbd3182011-06-15 23:37:01 +0000242 if (Pte->getElementType()->isIntegerTy(8))
243 return StringSwitch<InstructionClass>(F->getName())
244 .Case("objc_loadWeakRetained", IC_LoadWeakRetained)
245 .Case("objc_loadWeak", IC_LoadWeak)
246 .Case("objc_destroyWeak", IC_DestroyWeak)
247 .Default(IC_CallOrUser);
248 }
249
250 // Two arguments, first is i8**.
251 const Argument *A1 = AI++;
252 if (AI == AE)
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000253 if (PointerType *PTy = dyn_cast<PointerType>(A0->getType()))
254 if (PointerType *Pte = dyn_cast<PointerType>(PTy->getElementType()))
John McCall9fbd3182011-06-15 23:37:01 +0000255 if (Pte->getElementType()->isIntegerTy(8))
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000256 if (PointerType *PTy1 = dyn_cast<PointerType>(A1->getType())) {
257 Type *ETy1 = PTy1->getElementType();
John McCall9fbd3182011-06-15 23:37:01 +0000258 // Second argument is i8*
259 if (ETy1->isIntegerTy(8))
260 return StringSwitch<InstructionClass>(F->getName())
261 .Case("objc_storeWeak", IC_StoreWeak)
262 .Case("objc_initWeak", IC_InitWeak)
263 .Default(IC_CallOrUser);
264 // Second argument is i8**.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000265 if (PointerType *Pte1 = dyn_cast<PointerType>(ETy1))
John McCall9fbd3182011-06-15 23:37:01 +0000266 if (Pte1->getElementType()->isIntegerTy(8))
267 return StringSwitch<InstructionClass>(F->getName())
268 .Case("objc_moveWeak", IC_MoveWeak)
269 .Case("objc_copyWeak", IC_CopyWeak)
270 .Default(IC_CallOrUser);
271 }
272
273 // Anything else.
274 return IC_CallOrUser;
275}
276
277/// GetInstructionClass - Determine what kind of construct V is.
278static InstructionClass GetInstructionClass(const Value *V) {
279 if (const Instruction *I = dyn_cast<Instruction>(V)) {
280 // Any instruction other than bitcast and gep with a pointer operand have a
281 // use of an objc pointer. Bitcasts, GEPs, Selects, PHIs transfer a pointer
282 // to a subsequent use, rather than using it themselves, in this sense.
283 // As a short cut, several other opcodes are known to have no pointer
284 // operands of interest. And ret is never followed by a release, so it's
285 // not interesting to examine.
286 switch (I->getOpcode()) {
287 case Instruction::Call: {
288 const CallInst *CI = cast<CallInst>(I);
289 // Check for calls to special functions.
290 if (const Function *F = CI->getCalledFunction()) {
291 InstructionClass Class = GetFunctionClass(F);
292 if (Class != IC_CallOrUser)
293 return Class;
294
295 // None of the intrinsic functions do objc_release. For intrinsics, the
296 // only question is whether or not they may be users.
297 switch (F->getIntrinsicID()) {
298 case 0: break;
299 case Intrinsic::bswap: case Intrinsic::ctpop:
300 case Intrinsic::ctlz: case Intrinsic::cttz:
301 case Intrinsic::returnaddress: case Intrinsic::frameaddress:
302 case Intrinsic::stacksave: case Intrinsic::stackrestore:
303 case Intrinsic::vastart: case Intrinsic::vacopy: case Intrinsic::vaend:
304 // Don't let dbg info affect our results.
305 case Intrinsic::dbg_declare: case Intrinsic::dbg_value:
306 // Short cut: Some intrinsics obviously don't use ObjC pointers.
307 return IC_None;
308 default:
309 for (Function::const_arg_iterator AI = F->arg_begin(),
310 AE = F->arg_end(); AI != AE; ++AI)
311 if (IsPotentialUse(AI))
312 return IC_User;
313 return IC_None;
314 }
315 }
316 return GetCallSiteClass(CI);
317 }
318 case Instruction::Invoke:
319 return GetCallSiteClass(cast<InvokeInst>(I));
320 case Instruction::BitCast:
321 case Instruction::GetElementPtr:
322 case Instruction::Select: case Instruction::PHI:
323 case Instruction::Ret: case Instruction::Br:
324 case Instruction::Switch: case Instruction::IndirectBr:
325 case Instruction::Alloca: case Instruction::VAArg:
326 case Instruction::Add: case Instruction::FAdd:
327 case Instruction::Sub: case Instruction::FSub:
328 case Instruction::Mul: case Instruction::FMul:
329 case Instruction::SDiv: case Instruction::UDiv: case Instruction::FDiv:
330 case Instruction::SRem: case Instruction::URem: case Instruction::FRem:
331 case Instruction::Shl: case Instruction::LShr: case Instruction::AShr:
332 case Instruction::And: case Instruction::Or: case Instruction::Xor:
333 case Instruction::SExt: case Instruction::ZExt: case Instruction::Trunc:
334 case Instruction::IntToPtr: case Instruction::FCmp:
335 case Instruction::FPTrunc: case Instruction::FPExt:
336 case Instruction::FPToUI: case Instruction::FPToSI:
337 case Instruction::UIToFP: case Instruction::SIToFP:
338 case Instruction::InsertElement: case Instruction::ExtractElement:
339 case Instruction::ShuffleVector:
340 case Instruction::ExtractValue:
341 break;
342 case Instruction::ICmp:
343 // Comparing a pointer with null, or any other constant, isn't an
344 // interesting use, because we don't care what the pointer points to, or
345 // about the values of any other dynamic reference-counted pointers.
346 if (IsPotentialUse(I->getOperand(1)))
347 return IC_User;
348 break;
349 default:
350 // For anything else, check all the operands.
Dan Gohmand4464602011-08-22 17:29:37 +0000351 // Note that this includes both operands of a Store: while the first
352 // operand isn't actually being dereferenced, it is being stored to
353 // memory where we can no longer track who might read it and dereference
354 // it, so we have to consider it potentially used.
John McCall9fbd3182011-06-15 23:37:01 +0000355 for (User::const_op_iterator OI = I->op_begin(), OE = I->op_end();
356 OI != OE; ++OI)
357 if (IsPotentialUse(*OI))
358 return IC_User;
359 }
360 }
361
362 // Otherwise, it's totally inert for ARC purposes.
363 return IC_None;
364}
365
366/// GetBasicInstructionClass - Determine what kind of construct V is. This is
367/// similar to GetInstructionClass except that it only detects objc runtine
368/// calls. This allows it to be faster.
369static InstructionClass GetBasicInstructionClass(const Value *V) {
370 if (const CallInst *CI = dyn_cast<CallInst>(V)) {
371 if (const Function *F = CI->getCalledFunction())
372 return GetFunctionClass(F);
373 // Otherwise, be conservative.
374 return IC_CallOrUser;
375 }
376
377 // Otherwise, be conservative.
Dan Gohman2f6263c2012-01-17 20:52:24 +0000378 return isa<InvokeInst>(V) ? IC_CallOrUser : IC_User;
John McCall9fbd3182011-06-15 23:37:01 +0000379}
380
381/// IsRetain - Test if the the given class is objc_retain or
382/// equivalent.
383static bool IsRetain(InstructionClass Class) {
384 return Class == IC_Retain ||
385 Class == IC_RetainRV;
386}
387
388/// IsAutorelease - Test if the the given class is objc_autorelease or
389/// equivalent.
390static bool IsAutorelease(InstructionClass Class) {
391 return Class == IC_Autorelease ||
392 Class == IC_AutoreleaseRV;
393}
394
395/// IsForwarding - Test if the given class represents instructions which return
396/// their argument verbatim.
397static bool IsForwarding(InstructionClass Class) {
398 // objc_retainBlock technically doesn't always return its argument
399 // verbatim, but it doesn't matter for our purposes here.
400 return Class == IC_Retain ||
401 Class == IC_RetainRV ||
402 Class == IC_Autorelease ||
403 Class == IC_AutoreleaseRV ||
404 Class == IC_RetainBlock ||
405 Class == IC_NoopCast;
406}
407
408/// IsNoopOnNull - Test if the given class represents instructions which do
409/// nothing if passed a null pointer.
410static bool IsNoopOnNull(InstructionClass Class) {
411 return Class == IC_Retain ||
412 Class == IC_RetainRV ||
413 Class == IC_Release ||
414 Class == IC_Autorelease ||
415 Class == IC_AutoreleaseRV ||
416 Class == IC_RetainBlock;
417}
418
419/// IsAlwaysTail - Test if the given class represents instructions which are
420/// always safe to mark with the "tail" keyword.
421static bool IsAlwaysTail(InstructionClass Class) {
422 // IC_RetainBlock may be given a stack argument.
423 return Class == IC_Retain ||
424 Class == IC_RetainRV ||
425 Class == IC_Autorelease ||
426 Class == IC_AutoreleaseRV;
427}
428
429/// IsNoThrow - Test if the given class represents instructions which are always
430/// safe to mark with the nounwind attribute..
431static bool IsNoThrow(InstructionClass Class) {
Dan Gohman1d2fd752011-09-14 18:33:34 +0000432 // objc_retainBlock is not nounwind because it calls user copy constructors
433 // which could theoretically throw.
John McCall9fbd3182011-06-15 23:37:01 +0000434 return Class == IC_Retain ||
435 Class == IC_RetainRV ||
John McCall9fbd3182011-06-15 23:37:01 +0000436 Class == IC_Release ||
437 Class == IC_Autorelease ||
438 Class == IC_AutoreleaseRV ||
439 Class == IC_AutoreleasepoolPush ||
440 Class == IC_AutoreleasepoolPop;
441}
442
443/// EraseInstruction - Erase the given instruction. ObjC calls return their
444/// argument verbatim, so if it's such a call and the return value has users,
445/// replace them with the argument value.
446static void EraseInstruction(Instruction *CI) {
447 Value *OldArg = cast<CallInst>(CI)->getArgOperand(0);
448
449 bool Unused = CI->use_empty();
450
451 if (!Unused) {
452 // Replace the return value with the argument.
453 assert(IsForwarding(GetBasicInstructionClass(CI)) &&
454 "Can't delete non-forwarding instruction with users!");
455 CI->replaceAllUsesWith(OldArg);
456 }
457
458 CI->eraseFromParent();
459
460 if (Unused)
461 RecursivelyDeleteTriviallyDeadInstructions(OldArg);
462}
463
464/// GetUnderlyingObjCPtr - This is a wrapper around getUnderlyingObject which
465/// also knows how to look through objc_retain and objc_autorelease calls, which
466/// we know to return their argument verbatim.
467static const Value *GetUnderlyingObjCPtr(const Value *V) {
468 for (;;) {
469 V = GetUnderlyingObject(V);
470 if (!IsForwarding(GetBasicInstructionClass(V)))
471 break;
472 V = cast<CallInst>(V)->getArgOperand(0);
473 }
474
475 return V;
476}
477
478/// StripPointerCastsAndObjCCalls - This is a wrapper around
479/// Value::stripPointerCasts which also knows how to look through objc_retain
480/// and objc_autorelease calls, which we know to return their argument verbatim.
481static const Value *StripPointerCastsAndObjCCalls(const Value *V) {
482 for (;;) {
483 V = V->stripPointerCasts();
484 if (!IsForwarding(GetBasicInstructionClass(V)))
485 break;
486 V = cast<CallInst>(V)->getArgOperand(0);
487 }
488 return V;
489}
490
491/// StripPointerCastsAndObjCCalls - This is a wrapper around
492/// Value::stripPointerCasts which also knows how to look through objc_retain
493/// and objc_autorelease calls, which we know to return their argument verbatim.
494static Value *StripPointerCastsAndObjCCalls(Value *V) {
495 for (;;) {
496 V = V->stripPointerCasts();
497 if (!IsForwarding(GetBasicInstructionClass(V)))
498 break;
499 V = cast<CallInst>(V)->getArgOperand(0);
500 }
501 return V;
502}
503
504/// GetObjCArg - Assuming the given instruction is one of the special calls such
505/// as objc_retain or objc_release, return the argument value, stripped of no-op
506/// casts and forwarding calls.
507static Value *GetObjCArg(Value *Inst) {
508 return StripPointerCastsAndObjCCalls(cast<CallInst>(Inst)->getArgOperand(0));
509}
510
511/// IsObjCIdentifiedObject - This is similar to AliasAnalysis'
512/// isObjCIdentifiedObject, except that it uses special knowledge of
513/// ObjC conventions...
514static bool IsObjCIdentifiedObject(const Value *V) {
515 // Assume that call results and arguments have their own "provenance".
516 // Constants (including GlobalVariables) and Allocas are never
517 // reference-counted.
518 if (isa<CallInst>(V) || isa<InvokeInst>(V) ||
519 isa<Argument>(V) || isa<Constant>(V) ||
520 isa<AllocaInst>(V))
521 return true;
522
523 if (const LoadInst *LI = dyn_cast<LoadInst>(V)) {
524 const Value *Pointer =
525 StripPointerCastsAndObjCCalls(LI->getPointerOperand());
526 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Pointer)) {
Dan Gohman1b31ea82011-08-22 17:29:11 +0000527 // A constant pointer can't be pointing to an object on the heap. It may
528 // be reference-counted, but it won't be deleted.
529 if (GV->isConstant())
530 return true;
John McCall9fbd3182011-06-15 23:37:01 +0000531 StringRef Name = GV->getName();
532 // These special variables are known to hold values which are not
533 // reference-counted pointers.
534 if (Name.startswith("\01L_OBJC_SELECTOR_REFERENCES_") ||
535 Name.startswith("\01L_OBJC_CLASSLIST_REFERENCES_") ||
536 Name.startswith("\01L_OBJC_CLASSLIST_SUP_REFS_$_") ||
537 Name.startswith("\01L_OBJC_METH_VAR_NAME_") ||
538 Name.startswith("\01l_objc_msgSend_fixup_"))
539 return true;
540 }
541 }
542
543 return false;
544}
545
546/// FindSingleUseIdentifiedObject - This is similar to
547/// StripPointerCastsAndObjCCalls but it stops as soon as it finds a value
548/// with multiple uses.
549static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
550 if (Arg->hasOneUse()) {
551 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
552 return FindSingleUseIdentifiedObject(BC->getOperand(0));
553 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
554 if (GEP->hasAllZeroIndices())
555 return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
556 if (IsForwarding(GetBasicInstructionClass(Arg)))
557 return FindSingleUseIdentifiedObject(
558 cast<CallInst>(Arg)->getArgOperand(0));
559 if (!IsObjCIdentifiedObject(Arg))
560 return 0;
561 return Arg;
562 }
563
564 // If we found an identifiable object but it has multiple uses, but they
565 // are trivial uses, we can still consider this to be a single-use
566 // value.
567 if (IsObjCIdentifiedObject(Arg)) {
568 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
569 UI != UE; ++UI) {
570 const User *U = *UI;
571 if (!U->use_empty() || StripPointerCastsAndObjCCalls(U) != Arg)
572 return 0;
573 }
574
575 return Arg;
576 }
577
578 return 0;
579}
580
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000581/// ModuleHasARC - Test if the given module looks interesting to run ARC
582/// optimization on.
583static bool ModuleHasARC(const Module &M) {
584 return
585 M.getNamedValue("objc_retain") ||
586 M.getNamedValue("objc_release") ||
587 M.getNamedValue("objc_autorelease") ||
588 M.getNamedValue("objc_retainAutoreleasedReturnValue") ||
589 M.getNamedValue("objc_retainBlock") ||
590 M.getNamedValue("objc_autoreleaseReturnValue") ||
591 M.getNamedValue("objc_autoreleasePoolPush") ||
592 M.getNamedValue("objc_loadWeakRetained") ||
593 M.getNamedValue("objc_loadWeak") ||
594 M.getNamedValue("objc_destroyWeak") ||
595 M.getNamedValue("objc_storeWeak") ||
596 M.getNamedValue("objc_initWeak") ||
597 M.getNamedValue("objc_moveWeak") ||
598 M.getNamedValue("objc_copyWeak") ||
599 M.getNamedValue("objc_retainedObject") ||
600 M.getNamedValue("objc_unretainedObject") ||
601 M.getNamedValue("objc_unretainedPointer");
602}
603
Dan Gohman79522dc2012-01-13 00:39:07 +0000604/// DoesObjCBlockEscape - Test whether the given pointer, which is an
605/// Objective C block pointer, does not "escape". This differs from regular
606/// escape analysis in that a use as an argument to a call is not considered
607/// an escape.
608static bool DoesObjCBlockEscape(const Value *BlockPtr) {
609 // Walk the def-use chains.
610 SmallVector<const Value *, 4> Worklist;
611 Worklist.push_back(BlockPtr);
612 do {
613 const Value *V = Worklist.pop_back_val();
614 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
615 UI != UE; ++UI) {
616 const User *UUser = *UI;
617 // Special - Use by a call (callee or argument) is not considered
618 // to be an escape.
Dan Gohman92180982012-01-14 00:47:44 +0000619 if (isa<CallInst>(UUser) || isa<InvokeInst>(UUser))
Dan Gohman79522dc2012-01-13 00:39:07 +0000620 continue;
621 if (isa<BitCastInst>(UUser) || isa<GetElementPtrInst>(UUser) ||
622 isa<PHINode>(UUser) || isa<SelectInst>(UUser)) {
623 Worklist.push_back(UUser);
624 continue;
625 }
626 return true;
627 }
628 } while (!Worklist.empty());
629
630 // No escapes found.
631 return false;
632}
633
John McCall9fbd3182011-06-15 23:37:01 +0000634//===----------------------------------------------------------------------===//
635// ARC AliasAnalysis.
636//===----------------------------------------------------------------------===//
637
638#include "llvm/Pass.h"
639#include "llvm/Analysis/AliasAnalysis.h"
640#include "llvm/Analysis/Passes.h"
641
642namespace {
643 /// ObjCARCAliasAnalysis - This is a simple alias analysis
644 /// implementation that uses knowledge of ARC constructs to answer queries.
645 ///
646 /// TODO: This class could be generalized to know about other ObjC-specific
647 /// tricks. Such as knowing that ivars in the non-fragile ABI are non-aliasing
648 /// even though their offsets are dynamic.
649 class ObjCARCAliasAnalysis : public ImmutablePass,
650 public AliasAnalysis {
651 public:
652 static char ID; // Class identification, replacement for typeinfo
653 ObjCARCAliasAnalysis() : ImmutablePass(ID) {
654 initializeObjCARCAliasAnalysisPass(*PassRegistry::getPassRegistry());
655 }
656
657 private:
658 virtual void initializePass() {
659 InitializeAliasAnalysis(this);
660 }
661
662 /// getAdjustedAnalysisPointer - This method is used when a pass implements
663 /// an analysis interface through multiple inheritance. If needed, it
664 /// should override this to adjust the this pointer as needed for the
665 /// specified pass info.
666 virtual void *getAdjustedAnalysisPointer(const void *PI) {
667 if (PI == &AliasAnalysis::ID)
668 return (AliasAnalysis*)this;
669 return this;
670 }
671
672 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
673 virtual AliasResult alias(const Location &LocA, const Location &LocB);
674 virtual bool pointsToConstantMemory(const Location &Loc, bool OrLocal);
675 virtual ModRefBehavior getModRefBehavior(ImmutableCallSite CS);
676 virtual ModRefBehavior getModRefBehavior(const Function *F);
677 virtual ModRefResult getModRefInfo(ImmutableCallSite CS,
678 const Location &Loc);
679 virtual ModRefResult getModRefInfo(ImmutableCallSite CS1,
680 ImmutableCallSite CS2);
681 };
682} // End of anonymous namespace
683
684// Register this pass...
685char ObjCARCAliasAnalysis::ID = 0;
686INITIALIZE_AG_PASS(ObjCARCAliasAnalysis, AliasAnalysis, "objc-arc-aa",
687 "ObjC-ARC-Based Alias Analysis", false, true, false)
688
689ImmutablePass *llvm::createObjCARCAliasAnalysisPass() {
690 return new ObjCARCAliasAnalysis();
691}
692
693void
694ObjCARCAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
695 AU.setPreservesAll();
696 AliasAnalysis::getAnalysisUsage(AU);
697}
698
699AliasAnalysis::AliasResult
700ObjCARCAliasAnalysis::alias(const Location &LocA, const Location &LocB) {
701 if (!EnableARCOpts)
702 return AliasAnalysis::alias(LocA, LocB);
703
704 // First, strip off no-ops, including ObjC-specific no-ops, and try making a
705 // precise alias query.
706 const Value *SA = StripPointerCastsAndObjCCalls(LocA.Ptr);
707 const Value *SB = StripPointerCastsAndObjCCalls(LocB.Ptr);
708 AliasResult Result =
709 AliasAnalysis::alias(Location(SA, LocA.Size, LocA.TBAATag),
710 Location(SB, LocB.Size, LocB.TBAATag));
711 if (Result != MayAlias)
712 return Result;
713
714 // If that failed, climb to the underlying object, including climbing through
715 // ObjC-specific no-ops, and try making an imprecise alias query.
716 const Value *UA = GetUnderlyingObjCPtr(SA);
717 const Value *UB = GetUnderlyingObjCPtr(SB);
718 if (UA != SA || UB != SB) {
719 Result = AliasAnalysis::alias(Location(UA), Location(UB));
720 // We can't use MustAlias or PartialAlias results here because
721 // GetUnderlyingObjCPtr may return an offsetted pointer value.
722 if (Result == NoAlias)
723 return NoAlias;
724 }
725
726 // If that failed, fail. We don't need to chain here, since that's covered
727 // by the earlier precise query.
728 return MayAlias;
729}
730
731bool
732ObjCARCAliasAnalysis::pointsToConstantMemory(const Location &Loc,
733 bool OrLocal) {
734 if (!EnableARCOpts)
735 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
736
737 // First, strip off no-ops, including ObjC-specific no-ops, and try making
738 // a precise alias query.
739 const Value *S = StripPointerCastsAndObjCCalls(Loc.Ptr);
740 if (AliasAnalysis::pointsToConstantMemory(Location(S, Loc.Size, Loc.TBAATag),
741 OrLocal))
742 return true;
743
744 // If that failed, climb to the underlying object, including climbing through
745 // ObjC-specific no-ops, and try making an imprecise alias query.
746 const Value *U = GetUnderlyingObjCPtr(S);
747 if (U != S)
748 return AliasAnalysis::pointsToConstantMemory(Location(U), OrLocal);
749
750 // If that failed, fail. We don't need to chain here, since that's covered
751 // by the earlier precise query.
752 return false;
753}
754
755AliasAnalysis::ModRefBehavior
756ObjCARCAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
757 // We have nothing to do. Just chain to the next AliasAnalysis.
758 return AliasAnalysis::getModRefBehavior(CS);
759}
760
761AliasAnalysis::ModRefBehavior
762ObjCARCAliasAnalysis::getModRefBehavior(const Function *F) {
763 if (!EnableARCOpts)
764 return AliasAnalysis::getModRefBehavior(F);
765
766 switch (GetFunctionClass(F)) {
767 case IC_NoopCast:
768 return DoesNotAccessMemory;
769 default:
770 break;
771 }
772
773 return AliasAnalysis::getModRefBehavior(F);
774}
775
776AliasAnalysis::ModRefResult
777ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS, const Location &Loc) {
778 if (!EnableARCOpts)
779 return AliasAnalysis::getModRefInfo(CS, Loc);
780
781 switch (GetBasicInstructionClass(CS.getInstruction())) {
782 case IC_Retain:
783 case IC_RetainRV:
John McCall9fbd3182011-06-15 23:37:01 +0000784 case IC_Autorelease:
785 case IC_AutoreleaseRV:
786 case IC_NoopCast:
787 case IC_AutoreleasepoolPush:
788 case IC_FusedRetainAutorelease:
789 case IC_FusedRetainAutoreleaseRV:
790 // These functions don't access any memory visible to the compiler.
Dan Gohman21104822011-09-14 18:13:00 +0000791 // Note that this doesn't include objc_retainBlock, becuase it updates
792 // pointers when it copies block data.
John McCall9fbd3182011-06-15 23:37:01 +0000793 return NoModRef;
794 default:
795 break;
796 }
797
798 return AliasAnalysis::getModRefInfo(CS, Loc);
799}
800
801AliasAnalysis::ModRefResult
802ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
803 ImmutableCallSite CS2) {
804 // TODO: Theoretically we could check for dependencies between objc_* calls
805 // and OnlyAccessesArgumentPointees calls or other well-behaved calls.
806 return AliasAnalysis::getModRefInfo(CS1, CS2);
807}
808
809//===----------------------------------------------------------------------===//
810// ARC expansion.
811//===----------------------------------------------------------------------===//
812
813#include "llvm/Support/InstIterator.h"
814#include "llvm/Transforms/Scalar.h"
815
816namespace {
817 /// ObjCARCExpand - Early ARC transformations.
818 class ObjCARCExpand : public FunctionPass {
819 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000820 virtual bool doInitialization(Module &M);
John McCall9fbd3182011-06-15 23:37:01 +0000821 virtual bool runOnFunction(Function &F);
822
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000823 /// Run - A flag indicating whether this optimization pass should run.
824 bool Run;
825
John McCall9fbd3182011-06-15 23:37:01 +0000826 public:
827 static char ID;
828 ObjCARCExpand() : FunctionPass(ID) {
829 initializeObjCARCExpandPass(*PassRegistry::getPassRegistry());
830 }
831 };
832}
833
834char ObjCARCExpand::ID = 0;
835INITIALIZE_PASS(ObjCARCExpand,
836 "objc-arc-expand", "ObjC ARC expansion", false, false)
837
838Pass *llvm::createObjCARCExpandPass() {
839 return new ObjCARCExpand();
840}
841
842void ObjCARCExpand::getAnalysisUsage(AnalysisUsage &AU) const {
843 AU.setPreservesCFG();
844}
845
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000846bool ObjCARCExpand::doInitialization(Module &M) {
847 Run = ModuleHasARC(M);
848 return false;
849}
850
John McCall9fbd3182011-06-15 23:37:01 +0000851bool ObjCARCExpand::runOnFunction(Function &F) {
852 if (!EnableARCOpts)
853 return false;
854
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000855 // If nothing in the Module uses ARC, don't do anything.
856 if (!Run)
857 return false;
858
John McCall9fbd3182011-06-15 23:37:01 +0000859 bool Changed = false;
860
861 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
862 Instruction *Inst = &*I;
863
864 switch (GetBasicInstructionClass(Inst)) {
865 case IC_Retain:
866 case IC_RetainRV:
867 case IC_Autorelease:
868 case IC_AutoreleaseRV:
869 case IC_FusedRetainAutorelease:
870 case IC_FusedRetainAutoreleaseRV:
871 // These calls return their argument verbatim, as a low-level
872 // optimization. However, this makes high-level optimizations
873 // harder. Undo any uses of this optimization that the front-end
874 // emitted here. We'll redo them in a later pass.
875 Changed = true;
876 Inst->replaceAllUsesWith(cast<CallInst>(Inst)->getArgOperand(0));
877 break;
878 default:
879 break;
880 }
881 }
882
883 return Changed;
884}
885
886//===----------------------------------------------------------------------===//
Dan Gohman2f6263c2012-01-17 20:52:24 +0000887// ARC autorelease pool elimination.
888//===----------------------------------------------------------------------===//
889
Dan Gohman1dae3e92012-01-18 21:19:38 +0000890#include "llvm/Constants.h"
891
Dan Gohman2f6263c2012-01-17 20:52:24 +0000892namespace {
893 /// ObjCARCAPElim - Autorelease pool elimination.
894 class ObjCARCAPElim : public ModulePass {
895 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
896 virtual bool runOnModule(Module &M);
897
Dan Gohman2f77bbd2012-01-18 21:24:45 +0000898 bool MayAutorelease(CallSite CS, unsigned Depth = 0);
Dan Gohman2f6263c2012-01-17 20:52:24 +0000899 bool OptimizeBB(BasicBlock *BB);
900
901 public:
902 static char ID;
903 ObjCARCAPElim() : ModulePass(ID) {
904 initializeObjCARCAPElimPass(*PassRegistry::getPassRegistry());
905 }
906 };
907}
908
909char ObjCARCAPElim::ID = 0;
910INITIALIZE_PASS(ObjCARCAPElim,
911 "objc-arc-apelim",
912 "ObjC ARC autorelease pool elimination",
913 false, false)
914
915Pass *llvm::createObjCARCAPElimPass() {
916 return new ObjCARCAPElim();
917}
918
919void ObjCARCAPElim::getAnalysisUsage(AnalysisUsage &AU) const {
920 AU.setPreservesCFG();
921}
922
923/// MayAutorelease - Interprocedurally determine if calls made by the
924/// given call site can possibly produce autoreleases.
Dan Gohman2f77bbd2012-01-18 21:24:45 +0000925bool ObjCARCAPElim::MayAutorelease(CallSite CS, unsigned Depth) {
Dan Gohman2f6263c2012-01-17 20:52:24 +0000926 if (Function *Callee = CS.getCalledFunction()) {
927 if (Callee->isDeclaration() || Callee->mayBeOverridden())
928 return true;
929 for (Function::iterator I = Callee->begin(), E = Callee->end();
930 I != E; ++I) {
931 BasicBlock *BB = I;
932 for (BasicBlock::iterator J = BB->begin(), F = BB->end(); J != F; ++J)
933 if (CallSite JCS = CallSite(J))
Dan Gohman2f77bbd2012-01-18 21:24:45 +0000934 // This recursion depth limit is arbitrary. It's just great
935 // enough to cover known interesting testcases.
936 if (Depth < 3 &&
937 !JCS.onlyReadsMemory() &&
938 MayAutorelease(JCS, Depth + 1))
Dan Gohman2f6263c2012-01-17 20:52:24 +0000939 return true;
940 }
941 return false;
942 }
943
944 return true;
945}
946
947bool ObjCARCAPElim::OptimizeBB(BasicBlock *BB) {
948 bool Changed = false;
949
950 Instruction *Push = 0;
951 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
952 Instruction *Inst = I++;
953 switch (GetBasicInstructionClass(Inst)) {
954 case IC_AutoreleasepoolPush:
955 Push = Inst;
956 break;
957 case IC_AutoreleasepoolPop:
958 // If this pop matches a push and nothing in between can autorelease,
959 // zap the pair.
960 if (Push && cast<CallInst>(Inst)->getArgOperand(0) == Push) {
961 Changed = true;
962 Inst->eraseFromParent();
963 Push->eraseFromParent();
964 }
965 Push = 0;
966 break;
967 case IC_CallOrUser:
968 if (MayAutorelease(CallSite(Inst)))
969 Push = 0;
970 break;
971 default:
972 break;
973 }
974 }
975
976 return Changed;
977}
978
979bool ObjCARCAPElim::runOnModule(Module &M) {
980 if (!EnableARCOpts)
981 return false;
982
983 // If nothing in the Module uses ARC, don't do anything.
984 if (!ModuleHasARC(M))
985 return false;
986
Dan Gohman1dae3e92012-01-18 21:19:38 +0000987 // Find the llvm.global_ctors variable, as the first step in
988 // identifying the global constructors.
989 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
990 if (!GV)
991 return false;
992
993 assert(GV->hasDefinitiveInitializer() &&
994 "llvm.global_ctors is uncooperative!");
995
Dan Gohman2f6263c2012-01-17 20:52:24 +0000996 bool Changed = false;
997
Dan Gohman1dae3e92012-01-18 21:19:38 +0000998 // Dig the constructor functions out of GV's initializer.
999 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
1000 for (User::op_iterator OI = Init->op_begin(), OE = Init->op_end();
1001 OI != OE; ++OI) {
1002 Value *Op = *OI;
1003 // llvm.global_ctors is an array of pairs where the second members
1004 // are constructor functions.
1005 Function *F = cast<Function>(cast<ConstantStruct>(Op)->getOperand(1));
Dan Gohman2f6263c2012-01-17 20:52:24 +00001006 // Only look at function definitions.
1007 if (F->isDeclaration())
1008 continue;
Dan Gohman2f6263c2012-01-17 20:52:24 +00001009 // Only look at functions with one basic block.
1010 if (llvm::next(F->begin()) != F->end())
1011 continue;
1012 // Ok, a single-block constructor function definition. Try to optimize it.
1013 Changed |= OptimizeBB(F->begin());
1014 }
1015
1016 return Changed;
1017}
1018
1019//===----------------------------------------------------------------------===//
John McCall9fbd3182011-06-15 23:37:01 +00001020// ARC optimization.
1021//===----------------------------------------------------------------------===//
1022
1023// TODO: On code like this:
1024//
1025// objc_retain(%x)
1026// stuff_that_cannot_release()
1027// objc_autorelease(%x)
1028// stuff_that_cannot_release()
1029// objc_retain(%x)
1030// stuff_that_cannot_release()
1031// objc_autorelease(%x)
1032//
1033// The second retain and autorelease can be deleted.
1034
1035// TODO: It should be possible to delete
1036// objc_autoreleasePoolPush and objc_autoreleasePoolPop
1037// pairs if nothing is actually autoreleased between them. Also, autorelease
1038// calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
1039// after inlining) can be turned into plain release calls.
1040
1041// TODO: Critical-edge splitting. If the optimial insertion point is
1042// a critical edge, the current algorithm has to fail, because it doesn't
1043// know how to split edges. It should be possible to make the optimizer
1044// think in terms of edges, rather than blocks, and then split critical
1045// edges on demand.
1046
1047// TODO: OptimizeSequences could generalized to be Interprocedural.
1048
1049// TODO: Recognize that a bunch of other objc runtime calls have
1050// non-escaping arguments and non-releasing arguments, and may be
1051// non-autoreleasing.
1052
1053// TODO: Sink autorelease calls as far as possible. Unfortunately we
1054// usually can't sink them past other calls, which would be the main
1055// case where it would be useful.
1056
Dan Gohmane6d5e882011-08-19 00:26:36 +00001057// TODO: The pointer returned from objc_loadWeakRetained is retained.
1058
1059// TODO: Delete release+retain pairs (rare).
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00001060
John McCall9fbd3182011-06-15 23:37:01 +00001061#include "llvm/GlobalAlias.h"
John McCall9fbd3182011-06-15 23:37:01 +00001062#include "llvm/Constants.h"
1063#include "llvm/LLVMContext.h"
1064#include "llvm/Support/ErrorHandling.h"
1065#include "llvm/Support/CFG.h"
John McCall9fbd3182011-06-15 23:37:01 +00001066#include "llvm/ADT/Statistic.h"
Dan Gohman59a1c932011-12-12 19:42:25 +00001067#include "llvm/ADT/SmallPtrSet.h"
1068#include "llvm/ADT/DenseSet.h"
John McCall9fbd3182011-06-15 23:37:01 +00001069
1070STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
1071STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
1072STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
1073STATISTIC(NumRets, "Number of return value forwarding "
1074 "retain+autoreleaes eliminated");
1075STATISTIC(NumRRs, "Number of retain+release paths eliminated");
1076STATISTIC(NumPeeps, "Number of calls peephole-optimized");
1077
1078namespace {
1079 /// ProvenanceAnalysis - This is similar to BasicAliasAnalysis, and it
1080 /// uses many of the same techniques, except it uses special ObjC-specific
1081 /// reasoning about pointer relationships.
1082 class ProvenanceAnalysis {
1083 AliasAnalysis *AA;
1084
1085 typedef std::pair<const Value *, const Value *> ValuePairTy;
1086 typedef DenseMap<ValuePairTy, bool> CachedResultsTy;
1087 CachedResultsTy CachedResults;
1088
1089 bool relatedCheck(const Value *A, const Value *B);
1090 bool relatedSelect(const SelectInst *A, const Value *B);
1091 bool relatedPHI(const PHINode *A, const Value *B);
1092
1093 // Do not implement.
1094 void operator=(const ProvenanceAnalysis &);
1095 ProvenanceAnalysis(const ProvenanceAnalysis &);
1096
1097 public:
1098 ProvenanceAnalysis() {}
1099
1100 void setAA(AliasAnalysis *aa) { AA = aa; }
1101
1102 AliasAnalysis *getAA() const { return AA; }
1103
1104 bool related(const Value *A, const Value *B);
1105
1106 void clear() {
1107 CachedResults.clear();
1108 }
1109 };
1110}
1111
1112bool ProvenanceAnalysis::relatedSelect(const SelectInst *A, const Value *B) {
1113 // If the values are Selects with the same condition, we can do a more precise
1114 // check: just check for relations between the values on corresponding arms.
1115 if (const SelectInst *SB = dyn_cast<SelectInst>(B))
1116 if (A->getCondition() == SB->getCondition()) {
1117 if (related(A->getTrueValue(), SB->getTrueValue()))
1118 return true;
1119 if (related(A->getFalseValue(), SB->getFalseValue()))
1120 return true;
1121 return false;
1122 }
1123
1124 // Check both arms of the Select node individually.
1125 if (related(A->getTrueValue(), B))
1126 return true;
1127 if (related(A->getFalseValue(), B))
1128 return true;
1129
1130 // The arms both checked out.
1131 return false;
1132}
1133
1134bool ProvenanceAnalysis::relatedPHI(const PHINode *A, const Value *B) {
1135 // If the values are PHIs in the same block, we can do a more precise as well
1136 // as efficient check: just check for relations between the values on
1137 // corresponding edges.
1138 if (const PHINode *PNB = dyn_cast<PHINode>(B))
1139 if (PNB->getParent() == A->getParent()) {
1140 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i)
1141 if (related(A->getIncomingValue(i),
1142 PNB->getIncomingValueForBlock(A->getIncomingBlock(i))))
1143 return true;
1144 return false;
1145 }
1146
1147 // Check each unique source of the PHI node against B.
1148 SmallPtrSet<const Value *, 4> UniqueSrc;
1149 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i) {
1150 const Value *PV1 = A->getIncomingValue(i);
1151 if (UniqueSrc.insert(PV1) && related(PV1, B))
1152 return true;
1153 }
1154
1155 // All of the arms checked out.
1156 return false;
1157}
1158
1159/// isStoredObjCPointer - Test if the value of P, or any value covered by its
1160/// provenance, is ever stored within the function (not counting callees).
1161static bool isStoredObjCPointer(const Value *P) {
1162 SmallPtrSet<const Value *, 8> Visited;
1163 SmallVector<const Value *, 8> Worklist;
1164 Worklist.push_back(P);
1165 Visited.insert(P);
1166 do {
1167 P = Worklist.pop_back_val();
1168 for (Value::const_use_iterator UI = P->use_begin(), UE = P->use_end();
1169 UI != UE; ++UI) {
1170 const User *Ur = *UI;
1171 if (isa<StoreInst>(Ur)) {
1172 if (UI.getOperandNo() == 0)
1173 // The pointer is stored.
1174 return true;
1175 // The pointed is stored through.
1176 continue;
1177 }
1178 if (isa<CallInst>(Ur))
1179 // The pointer is passed as an argument, ignore this.
1180 continue;
1181 if (isa<PtrToIntInst>(P))
1182 // Assume the worst.
1183 return true;
1184 if (Visited.insert(Ur))
1185 Worklist.push_back(Ur);
1186 }
1187 } while (!Worklist.empty());
1188
1189 // Everything checked out.
1190 return false;
1191}
1192
1193bool ProvenanceAnalysis::relatedCheck(const Value *A, const Value *B) {
1194 // Skip past provenance pass-throughs.
1195 A = GetUnderlyingObjCPtr(A);
1196 B = GetUnderlyingObjCPtr(B);
1197
1198 // Quick check.
1199 if (A == B)
1200 return true;
1201
1202 // Ask regular AliasAnalysis, for a first approximation.
1203 switch (AA->alias(A, B)) {
1204 case AliasAnalysis::NoAlias:
1205 return false;
1206 case AliasAnalysis::MustAlias:
1207 case AliasAnalysis::PartialAlias:
1208 return true;
1209 case AliasAnalysis::MayAlias:
1210 break;
1211 }
1212
1213 bool AIsIdentified = IsObjCIdentifiedObject(A);
1214 bool BIsIdentified = IsObjCIdentifiedObject(B);
1215
1216 // An ObjC-Identified object can't alias a load if it is never locally stored.
1217 if (AIsIdentified) {
1218 if (BIsIdentified) {
1219 // If both pointers have provenance, they can be directly compared.
1220 if (A != B)
1221 return false;
1222 } else {
1223 if (isa<LoadInst>(B))
1224 return isStoredObjCPointer(A);
1225 }
1226 } else {
1227 if (BIsIdentified && isa<LoadInst>(A))
1228 return isStoredObjCPointer(B);
1229 }
1230
1231 // Special handling for PHI and Select.
1232 if (const PHINode *PN = dyn_cast<PHINode>(A))
1233 return relatedPHI(PN, B);
1234 if (const PHINode *PN = dyn_cast<PHINode>(B))
1235 return relatedPHI(PN, A);
1236 if (const SelectInst *S = dyn_cast<SelectInst>(A))
1237 return relatedSelect(S, B);
1238 if (const SelectInst *S = dyn_cast<SelectInst>(B))
1239 return relatedSelect(S, A);
1240
1241 // Conservative.
1242 return true;
1243}
1244
1245bool ProvenanceAnalysis::related(const Value *A, const Value *B) {
1246 // Begin by inserting a conservative value into the map. If the insertion
1247 // fails, we have the answer already. If it succeeds, leave it there until we
1248 // compute the real answer to guard against recursive queries.
1249 if (A > B) std::swap(A, B);
1250 std::pair<CachedResultsTy::iterator, bool> Pair =
1251 CachedResults.insert(std::make_pair(ValuePairTy(A, B), true));
1252 if (!Pair.second)
1253 return Pair.first->second;
1254
1255 bool Result = relatedCheck(A, B);
1256 CachedResults[ValuePairTy(A, B)] = Result;
1257 return Result;
1258}
1259
1260namespace {
1261 // Sequence - A sequence of states that a pointer may go through in which an
1262 // objc_retain and objc_release are actually needed.
1263 enum Sequence {
1264 S_None,
1265 S_Retain, ///< objc_retain(x)
1266 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement
1267 S_Use, ///< any use of x
1268 S_Stop, ///< like S_Release, but code motion is stopped
1269 S_Release, ///< objc_release(x)
1270 S_MovableRelease ///< objc_release(x), !clang.imprecise_release
1271 };
1272}
1273
1274static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
1275 // The easy cases.
1276 if (A == B)
1277 return A;
1278 if (A == S_None || B == S_None)
1279 return S_None;
1280
John McCall9fbd3182011-06-15 23:37:01 +00001281 if (A > B) std::swap(A, B);
1282 if (TopDown) {
1283 // Choose the side which is further along in the sequence.
Dan Gohmana7f7db22011-08-12 00:26:31 +00001284 if ((A == S_Retain || A == S_CanRelease) &&
1285 (B == S_CanRelease || B == S_Use))
John McCall9fbd3182011-06-15 23:37:01 +00001286 return B;
1287 } else {
1288 // Choose the side which is further along in the sequence.
1289 if ((A == S_Use || A == S_CanRelease) &&
Dan Gohmana7f7db22011-08-12 00:26:31 +00001290 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
John McCall9fbd3182011-06-15 23:37:01 +00001291 return A;
1292 // If both sides are releases, choose the more conservative one.
1293 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
1294 return A;
1295 if (A == S_Release && B == S_MovableRelease)
1296 return A;
1297 }
1298
1299 return S_None;
1300}
1301
1302namespace {
1303 /// RRInfo - Unidirectional information about either a
1304 /// retain-decrement-use-release sequence or release-use-decrement-retain
1305 /// reverese sequence.
1306 struct RRInfo {
Dan Gohmane6d5e882011-08-19 00:26:36 +00001307 /// KnownSafe - After an objc_retain, the reference count of the referenced
1308 /// object is known to be positive. Similarly, before an objc_release, the
1309 /// reference count of the referenced object is known to be positive. If
1310 /// there are retain-release pairs in code regions where the retain count
1311 /// is known to be positive, they can be eliminated, regardless of any side
1312 /// effects between them.
1313 ///
1314 /// Also, a retain+release pair nested within another retain+release
1315 /// pair all on the known same pointer value can be eliminated, regardless
1316 /// of any intervening side effects.
1317 ///
1318 /// KnownSafe is true when either of these conditions is satisfied.
1319 bool KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00001320
1321 /// IsRetainBlock - True if the Calls are objc_retainBlock calls (as
1322 /// opposed to objc_retain calls).
1323 bool IsRetainBlock;
1324
1325 /// IsTailCallRelease - True of the objc_release calls are all marked
1326 /// with the "tail" keyword.
1327 bool IsTailCallRelease;
1328
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001329 /// Partial - True of we've seen an opportunity for partial RR elimination,
1330 /// such as pushing calls into a CFG triangle or into one side of a
1331 /// CFG diamond.
Dan Gohmanafee0272011-12-12 18:30:26 +00001332 /// TODO: Consider moving this to PtrState.
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001333 bool Partial;
1334
John McCall9fbd3182011-06-15 23:37:01 +00001335 /// ReleaseMetadata - If the Calls are objc_release calls and they all have
1336 /// a clang.imprecise_release tag, this is the metadata tag.
1337 MDNode *ReleaseMetadata;
1338
1339 /// Calls - For a top-down sequence, the set of objc_retains or
1340 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
1341 SmallPtrSet<Instruction *, 2> Calls;
1342
1343 /// ReverseInsertPts - The set of optimal insert positions for
1344 /// moving calls in the opposite sequence.
1345 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
1346
1347 RRInfo() :
Dan Gohman79522dc2012-01-13 00:39:07 +00001348 KnownSafe(false), IsRetainBlock(false),
Dan Gohmana974bea2011-10-17 22:53:25 +00001349 IsTailCallRelease(false), Partial(false),
John McCall9fbd3182011-06-15 23:37:01 +00001350 ReleaseMetadata(0) {}
1351
1352 void clear();
1353 };
1354}
1355
1356void RRInfo::clear() {
Dan Gohmane6d5e882011-08-19 00:26:36 +00001357 KnownSafe = false;
John McCall9fbd3182011-06-15 23:37:01 +00001358 IsRetainBlock = false;
1359 IsTailCallRelease = false;
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001360 Partial = false;
John McCall9fbd3182011-06-15 23:37:01 +00001361 ReleaseMetadata = 0;
1362 Calls.clear();
1363 ReverseInsertPts.clear();
1364}
1365
1366namespace {
1367 /// PtrState - This class summarizes several per-pointer runtime properties
1368 /// which are propogated through the flow graph.
1369 class PtrState {
1370 /// RefCount - The known minimum number of reference count increments.
1371 unsigned RefCount;
1372
Dan Gohmane6d5e882011-08-19 00:26:36 +00001373 /// NestCount - The known minimum level of retain+release nesting.
1374 unsigned NestCount;
1375
John McCall9fbd3182011-06-15 23:37:01 +00001376 /// Seq - The current position in the sequence.
1377 Sequence Seq;
1378
1379 public:
1380 /// RRI - Unidirectional information about the current sequence.
1381 /// TODO: Encapsulate this better.
1382 RRInfo RRI;
1383
Dan Gohmane6d5e882011-08-19 00:26:36 +00001384 PtrState() : RefCount(0), NestCount(0), Seq(S_None) {}
John McCall9fbd3182011-06-15 23:37:01 +00001385
Dan Gohmana7f7db22011-08-12 00:26:31 +00001386 void SetAtLeastOneRefCount() {
1387 if (RefCount == 0) RefCount = 1;
1388 }
1389
John McCall9fbd3182011-06-15 23:37:01 +00001390 void IncrementRefCount() {
1391 if (RefCount != UINT_MAX) ++RefCount;
1392 }
1393
1394 void DecrementRefCount() {
1395 if (RefCount != 0) --RefCount;
1396 }
1397
John McCall9fbd3182011-06-15 23:37:01 +00001398 bool IsKnownIncremented() const {
1399 return RefCount > 0;
1400 }
1401
Dan Gohmane6d5e882011-08-19 00:26:36 +00001402 void IncrementNestCount() {
1403 if (NestCount != UINT_MAX) ++NestCount;
1404 }
1405
1406 void DecrementNestCount() {
1407 if (NestCount != 0) --NestCount;
1408 }
1409
1410 bool IsKnownNested() const {
1411 return NestCount > 0;
1412 }
1413
John McCall9fbd3182011-06-15 23:37:01 +00001414 void SetSeq(Sequence NewSeq) {
1415 Seq = NewSeq;
1416 }
1417
John McCall9fbd3182011-06-15 23:37:01 +00001418 Sequence GetSeq() const {
1419 return Seq;
1420 }
1421
1422 void ClearSequenceProgress() {
1423 Seq = S_None;
1424 RRI.clear();
1425 }
1426
1427 void Merge(const PtrState &Other, bool TopDown);
1428 };
1429}
1430
1431void
1432PtrState::Merge(const PtrState &Other, bool TopDown) {
1433 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
1434 RefCount = std::min(RefCount, Other.RefCount);
Dan Gohmane6d5e882011-08-19 00:26:36 +00001435 NestCount = std::min(NestCount, Other.NestCount);
John McCall9fbd3182011-06-15 23:37:01 +00001436
1437 // We can't merge a plain objc_retain with an objc_retainBlock.
1438 if (RRI.IsRetainBlock != Other.RRI.IsRetainBlock)
1439 Seq = S_None;
1440
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001441 // If we're not in a sequence (anymore), drop all associated state.
John McCall9fbd3182011-06-15 23:37:01 +00001442 if (Seq == S_None) {
1443 RRI.clear();
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001444 } else if (RRI.Partial || Other.RRI.Partial) {
1445 // If we're doing a merge on a path that's previously seen a partial
1446 // merge, conservatively drop the sequence, to avoid doing partial
1447 // RR elimination. If the branch predicates for the two merge differ,
1448 // mixing them is unsafe.
1449 Seq = S_None;
1450 RRI.clear();
John McCall9fbd3182011-06-15 23:37:01 +00001451 } else {
1452 // Conservatively merge the ReleaseMetadata information.
1453 if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
1454 RRI.ReleaseMetadata = 0;
1455
Dan Gohmane6d5e882011-08-19 00:26:36 +00001456 RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00001457 RRI.IsTailCallRelease = RRI.IsTailCallRelease && Other.RRI.IsTailCallRelease;
1458 RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001459
1460 // Merge the insert point sets. If there are any differences,
1461 // that makes this a partial merge.
1462 RRI.Partial = RRI.ReverseInsertPts.size() !=
1463 Other.RRI.ReverseInsertPts.size();
1464 for (SmallPtrSet<Instruction *, 2>::const_iterator
1465 I = Other.RRI.ReverseInsertPts.begin(),
1466 E = Other.RRI.ReverseInsertPts.end(); I != E; ++I)
1467 RRI.Partial |= RRI.ReverseInsertPts.insert(*I);
John McCall9fbd3182011-06-15 23:37:01 +00001468 }
1469}
1470
1471namespace {
1472 /// BBState - Per-BasicBlock state.
1473 class BBState {
1474 /// TopDownPathCount - The number of unique control paths from the entry
1475 /// which can reach this block.
1476 unsigned TopDownPathCount;
1477
1478 /// BottomUpPathCount - The number of unique control paths to exits
1479 /// from this block.
1480 unsigned BottomUpPathCount;
1481
1482 /// MapTy - A type for PerPtrTopDown and PerPtrBottomUp.
1483 typedef MapVector<const Value *, PtrState> MapTy;
1484
1485 /// PerPtrTopDown - The top-down traversal uses this to record information
1486 /// known about a pointer at the bottom of each block.
1487 MapTy PerPtrTopDown;
1488
1489 /// PerPtrBottomUp - The bottom-up traversal uses this to record information
1490 /// known about a pointer at the top of each block.
1491 MapTy PerPtrBottomUp;
1492
1493 public:
1494 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
1495
1496 typedef MapTy::iterator ptr_iterator;
1497 typedef MapTy::const_iterator ptr_const_iterator;
1498
1499 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
1500 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
1501 ptr_const_iterator top_down_ptr_begin() const {
1502 return PerPtrTopDown.begin();
1503 }
1504 ptr_const_iterator top_down_ptr_end() const {
1505 return PerPtrTopDown.end();
1506 }
1507
1508 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
1509 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
1510 ptr_const_iterator bottom_up_ptr_begin() const {
1511 return PerPtrBottomUp.begin();
1512 }
1513 ptr_const_iterator bottom_up_ptr_end() const {
1514 return PerPtrBottomUp.end();
1515 }
1516
1517 /// SetAsEntry - Mark this block as being an entry block, which has one
1518 /// path from the entry by definition.
1519 void SetAsEntry() { TopDownPathCount = 1; }
1520
1521 /// SetAsExit - Mark this block as being an exit block, which has one
1522 /// path to an exit by definition.
1523 void SetAsExit() { BottomUpPathCount = 1; }
1524
1525 PtrState &getPtrTopDownState(const Value *Arg) {
1526 return PerPtrTopDown[Arg];
1527 }
1528
1529 PtrState &getPtrBottomUpState(const Value *Arg) {
1530 return PerPtrBottomUp[Arg];
1531 }
1532
1533 void clearBottomUpPointers() {
Evan Chenga81388f2011-08-04 18:40:26 +00001534 PerPtrBottomUp.clear();
John McCall9fbd3182011-06-15 23:37:01 +00001535 }
1536
1537 void clearTopDownPointers() {
1538 PerPtrTopDown.clear();
1539 }
1540
1541 void InitFromPred(const BBState &Other);
1542 void InitFromSucc(const BBState &Other);
1543 void MergePred(const BBState &Other);
1544 void MergeSucc(const BBState &Other);
1545
1546 /// GetAllPathCount - Return the number of possible unique paths from an
1547 /// entry to an exit which pass through this block. This is only valid
1548 /// after both the top-down and bottom-up traversals are complete.
1549 unsigned GetAllPathCount() const {
1550 return TopDownPathCount * BottomUpPathCount;
1551 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00001552
1553 /// IsVisitedTopDown - Test whether the block for this BBState has been
1554 /// visited by the top-down portion of the algorithm.
1555 bool isVisitedTopDown() const {
1556 return TopDownPathCount != 0;
1557 }
John McCall9fbd3182011-06-15 23:37:01 +00001558 };
1559}
1560
1561void BBState::InitFromPred(const BBState &Other) {
1562 PerPtrTopDown = Other.PerPtrTopDown;
1563 TopDownPathCount = Other.TopDownPathCount;
1564}
1565
1566void BBState::InitFromSucc(const BBState &Other) {
1567 PerPtrBottomUp = Other.PerPtrBottomUp;
1568 BottomUpPathCount = Other.BottomUpPathCount;
1569}
1570
1571/// MergePred - The top-down traversal uses this to merge information about
1572/// predecessors to form the initial state for a new block.
1573void BBState::MergePred(const BBState &Other) {
1574 // Other.TopDownPathCount can be 0, in which case it is either dead or a
1575 // loop backedge. Loop backedges are special.
1576 TopDownPathCount += Other.TopDownPathCount;
1577
1578 // For each entry in the other set, if our set has an entry with the same key,
1579 // merge the entries. Otherwise, copy the entry and merge it with an empty
1580 // entry.
1581 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
1582 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
1583 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
1584 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1585 /*TopDown=*/true);
1586 }
1587
Dan Gohmanfa7eed12011-08-11 21:06:32 +00001588 // For each entry in our set, if the other set doesn't have an entry with the
John McCall9fbd3182011-06-15 23:37:01 +00001589 // same key, force it to merge with an empty entry.
1590 for (ptr_iterator MI = top_down_ptr_begin(),
1591 ME = top_down_ptr_end(); MI != ME; ++MI)
1592 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
1593 MI->second.Merge(PtrState(), /*TopDown=*/true);
1594}
1595
1596/// MergeSucc - The bottom-up traversal uses this to merge information about
1597/// successors to form the initial state for a new block.
1598void BBState::MergeSucc(const BBState &Other) {
1599 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
1600 // loop backedge. Loop backedges are special.
1601 BottomUpPathCount += Other.BottomUpPathCount;
1602
1603 // For each entry in the other set, if our set has an entry with the
1604 // same key, merge the entries. Otherwise, copy the entry and merge
1605 // it with an empty entry.
1606 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
1607 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
1608 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
1609 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1610 /*TopDown=*/false);
1611 }
1612
Dan Gohmanfa7eed12011-08-11 21:06:32 +00001613 // For each entry in our set, if the other set doesn't have an entry
John McCall9fbd3182011-06-15 23:37:01 +00001614 // with the same key, force it to merge with an empty entry.
1615 for (ptr_iterator MI = bottom_up_ptr_begin(),
1616 ME = bottom_up_ptr_end(); MI != ME; ++MI)
1617 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
1618 MI->second.Merge(PtrState(), /*TopDown=*/false);
1619}
1620
1621namespace {
1622 /// ObjCARCOpt - The main ARC optimization pass.
1623 class ObjCARCOpt : public FunctionPass {
1624 bool Changed;
1625 ProvenanceAnalysis PA;
1626
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00001627 /// Run - A flag indicating whether this optimization pass should run.
1628 bool Run;
1629
John McCall9fbd3182011-06-15 23:37:01 +00001630 /// RetainRVCallee, etc. - Declarations for ObjC runtime
1631 /// functions, for use in creating calls to them. These are initialized
1632 /// lazily to avoid cluttering up the Module with unused declarations.
1633 Constant *RetainRVCallee, *AutoreleaseRVCallee, *ReleaseCallee,
Dan Gohman44280692011-07-22 22:29:21 +00001634 *RetainCallee, *RetainBlockCallee, *AutoreleaseCallee;
John McCall9fbd3182011-06-15 23:37:01 +00001635
1636 /// UsedInThisFunciton - Flags which determine whether each of the
1637 /// interesting runtine functions is in fact used in the current function.
1638 unsigned UsedInThisFunction;
1639
1640 /// ImpreciseReleaseMDKind - The Metadata Kind for clang.imprecise_release
1641 /// metadata.
1642 unsigned ImpreciseReleaseMDKind;
1643
Dan Gohman62e5b402011-12-12 18:20:00 +00001644 /// CopyOnEscapeMDKind - The Metadata Kind for clang.arc.copy_on_escape
Dan Gohmana974bea2011-10-17 22:53:25 +00001645 /// metadata.
1646 unsigned CopyOnEscapeMDKind;
1647
John McCall9fbd3182011-06-15 23:37:01 +00001648 Constant *getRetainRVCallee(Module *M);
1649 Constant *getAutoreleaseRVCallee(Module *M);
1650 Constant *getReleaseCallee(Module *M);
1651 Constant *getRetainCallee(Module *M);
Dan Gohman44280692011-07-22 22:29:21 +00001652 Constant *getRetainBlockCallee(Module *M);
John McCall9fbd3182011-06-15 23:37:01 +00001653 Constant *getAutoreleaseCallee(Module *M);
1654
Dan Gohman79522dc2012-01-13 00:39:07 +00001655 bool IsRetainBlockOptimizable(const Instruction *Inst);
1656
John McCall9fbd3182011-06-15 23:37:01 +00001657 void OptimizeRetainCall(Function &F, Instruction *Retain);
1658 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
1659 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV);
1660 void OptimizeIndividualCalls(Function &F);
1661
1662 void CheckForCFGHazards(const BasicBlock *BB,
1663 DenseMap<const BasicBlock *, BBState> &BBStates,
1664 BBState &MyStates) const;
1665 bool VisitBottomUp(BasicBlock *BB,
1666 DenseMap<const BasicBlock *, BBState> &BBStates,
1667 MapVector<Value *, RRInfo> &Retains);
1668 bool VisitTopDown(BasicBlock *BB,
1669 DenseMap<const BasicBlock *, BBState> &BBStates,
1670 DenseMap<Value *, RRInfo> &Releases);
1671 bool Visit(Function &F,
1672 DenseMap<const BasicBlock *, BBState> &BBStates,
1673 MapVector<Value *, RRInfo> &Retains,
1674 DenseMap<Value *, RRInfo> &Releases);
1675
1676 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1677 MapVector<Value *, RRInfo> &Retains,
1678 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman44280692011-07-22 22:29:21 +00001679 SmallVectorImpl<Instruction *> &DeadInsts,
1680 Module *M);
John McCall9fbd3182011-06-15 23:37:01 +00001681
1682 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1683 MapVector<Value *, RRInfo> &Retains,
Dan Gohman44280692011-07-22 22:29:21 +00001684 DenseMap<Value *, RRInfo> &Releases,
1685 Module *M);
John McCall9fbd3182011-06-15 23:37:01 +00001686
1687 void OptimizeWeakCalls(Function &F);
1688
1689 bool OptimizeSequences(Function &F);
1690
1691 void OptimizeReturns(Function &F);
1692
1693 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1694 virtual bool doInitialization(Module &M);
1695 virtual bool runOnFunction(Function &F);
1696 virtual void releaseMemory();
1697
1698 public:
1699 static char ID;
1700 ObjCARCOpt() : FunctionPass(ID) {
1701 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1702 }
1703 };
1704}
1705
1706char ObjCARCOpt::ID = 0;
1707INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1708 "objc-arc", "ObjC ARC optimization", false, false)
1709INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1710INITIALIZE_PASS_END(ObjCARCOpt,
1711 "objc-arc", "ObjC ARC optimization", false, false)
1712
1713Pass *llvm::createObjCARCOptPass() {
1714 return new ObjCARCOpt();
1715}
1716
1717void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1718 AU.addRequired<ObjCARCAliasAnalysis>();
1719 AU.addRequired<AliasAnalysis>();
1720 // ARC optimization doesn't currently split critical edges.
1721 AU.setPreservesCFG();
1722}
1723
Dan Gohman79522dc2012-01-13 00:39:07 +00001724bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1725 // Without the magic metadata tag, we have to assume this might be an
1726 // objc_retainBlock call inserted to convert a block pointer to an id,
1727 // in which case it really is needed.
1728 if (!Inst->getMetadata(CopyOnEscapeMDKind))
1729 return false;
1730
1731 // If the pointer "escapes" (not including being used in a call),
1732 // the copy may be needed.
1733 if (DoesObjCBlockEscape(Inst))
1734 return false;
1735
1736 // Otherwise, it's not needed.
1737 return true;
1738}
1739
John McCall9fbd3182011-06-15 23:37:01 +00001740Constant *ObjCARCOpt::getRetainRVCallee(Module *M) {
1741 if (!RetainRVCallee) {
1742 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001743 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1744 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00001745 Params.push_back(I8X);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001746 FunctionType *FTy =
John McCall9fbd3182011-06-15 23:37:01 +00001747 FunctionType::get(I8X, Params, /*isVarArg=*/false);
1748 AttrListPtr Attributes;
1749 Attributes.addAttr(~0u, Attribute::NoUnwind);
1750 RetainRVCallee =
1751 M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy,
1752 Attributes);
1753 }
1754 return RetainRVCallee;
1755}
1756
1757Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1758 if (!AutoreleaseRVCallee) {
1759 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001760 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1761 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00001762 Params.push_back(I8X);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001763 FunctionType *FTy =
John McCall9fbd3182011-06-15 23:37:01 +00001764 FunctionType::get(I8X, Params, /*isVarArg=*/false);
1765 AttrListPtr Attributes;
1766 Attributes.addAttr(~0u, Attribute::NoUnwind);
1767 AutoreleaseRVCallee =
1768 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
1769 Attributes);
1770 }
1771 return AutoreleaseRVCallee;
1772}
1773
1774Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1775 if (!ReleaseCallee) {
1776 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001777 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00001778 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1779 AttrListPtr Attributes;
1780 Attributes.addAttr(~0u, Attribute::NoUnwind);
1781 ReleaseCallee =
1782 M->getOrInsertFunction(
1783 "objc_release",
1784 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
1785 Attributes);
1786 }
1787 return ReleaseCallee;
1788}
1789
1790Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1791 if (!RetainCallee) {
1792 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001793 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00001794 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1795 AttrListPtr Attributes;
1796 Attributes.addAttr(~0u, Attribute::NoUnwind);
1797 RetainCallee =
1798 M->getOrInsertFunction(
1799 "objc_retain",
1800 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1801 Attributes);
1802 }
1803 return RetainCallee;
1804}
1805
Dan Gohman44280692011-07-22 22:29:21 +00001806Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1807 if (!RetainBlockCallee) {
1808 LLVMContext &C = M->getContext();
1809 std::vector<Type *> Params;
1810 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1811 AttrListPtr Attributes;
Dan Gohman1d2fd752011-09-14 18:33:34 +00001812 // objc_retainBlock is not nounwind because it calls user copy constructors
1813 // which could theoretically throw.
Dan Gohman44280692011-07-22 22:29:21 +00001814 RetainBlockCallee =
1815 M->getOrInsertFunction(
1816 "objc_retainBlock",
1817 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1818 Attributes);
1819 }
1820 return RetainBlockCallee;
1821}
1822
John McCall9fbd3182011-06-15 23:37:01 +00001823Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1824 if (!AutoreleaseCallee) {
1825 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001826 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00001827 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1828 AttrListPtr Attributes;
1829 Attributes.addAttr(~0u, Attribute::NoUnwind);
1830 AutoreleaseCallee =
1831 M->getOrInsertFunction(
1832 "objc_autorelease",
1833 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1834 Attributes);
1835 }
1836 return AutoreleaseCallee;
1837}
1838
1839/// CanAlterRefCount - Test whether the given instruction can result in a
1840/// reference count modification (positive or negative) for the pointer's
1841/// object.
1842static bool
1843CanAlterRefCount(const Instruction *Inst, const Value *Ptr,
1844 ProvenanceAnalysis &PA, InstructionClass Class) {
1845 switch (Class) {
1846 case IC_Autorelease:
1847 case IC_AutoreleaseRV:
1848 case IC_User:
1849 // These operations never directly modify a reference count.
1850 return false;
1851 default: break;
1852 }
1853
1854 ImmutableCallSite CS = static_cast<const Value *>(Inst);
1855 assert(CS && "Only calls can alter reference counts!");
1856
1857 // See if AliasAnalysis can help us with the call.
1858 AliasAnalysis::ModRefBehavior MRB = PA.getAA()->getModRefBehavior(CS);
1859 if (AliasAnalysis::onlyReadsMemory(MRB))
1860 return false;
1861 if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
1862 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1863 I != E; ++I) {
1864 const Value *Op = *I;
1865 if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1866 return true;
1867 }
1868 return false;
1869 }
1870
1871 // Assume the worst.
1872 return true;
1873}
1874
1875/// CanUse - Test whether the given instruction can "use" the given pointer's
1876/// object in a way that requires the reference count to be positive.
1877static bool
1878CanUse(const Instruction *Inst, const Value *Ptr, ProvenanceAnalysis &PA,
1879 InstructionClass Class) {
1880 // IC_Call operations (as opposed to IC_CallOrUser) never "use" objc pointers.
1881 if (Class == IC_Call)
1882 return false;
1883
1884 // Consider various instructions which may have pointer arguments which are
1885 // not "uses".
1886 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(Inst)) {
1887 // Comparing a pointer with null, or any other constant, isn't really a use,
1888 // because we don't care what the pointer points to, or about the values
1889 // of any other dynamic reference-counted pointers.
1890 if (!IsPotentialUse(ICI->getOperand(1)))
1891 return false;
1892 } else if (ImmutableCallSite CS = static_cast<const Value *>(Inst)) {
1893 // For calls, just check the arguments (and not the callee operand).
1894 for (ImmutableCallSite::arg_iterator OI = CS.arg_begin(),
1895 OE = CS.arg_end(); OI != OE; ++OI) {
1896 const Value *Op = *OI;
1897 if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1898 return true;
1899 }
1900 return false;
1901 } else if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1902 // Special-case stores, because we don't care about the stored value, just
1903 // the store address.
1904 const Value *Op = GetUnderlyingObjCPtr(SI->getPointerOperand());
1905 // If we can't tell what the underlying object was, assume there is a
1906 // dependence.
1907 return IsPotentialUse(Op) && PA.related(Op, Ptr);
1908 }
1909
1910 // Check each operand for a match.
1911 for (User::const_op_iterator OI = Inst->op_begin(), OE = Inst->op_end();
1912 OI != OE; ++OI) {
1913 const Value *Op = *OI;
1914 if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1915 return true;
1916 }
1917 return false;
1918}
1919
1920/// CanInterruptRV - Test whether the given instruction can autorelease
1921/// any pointer or cause an autoreleasepool pop.
1922static bool
1923CanInterruptRV(InstructionClass Class) {
1924 switch (Class) {
1925 case IC_AutoreleasepoolPop:
1926 case IC_CallOrUser:
1927 case IC_Call:
1928 case IC_Autorelease:
1929 case IC_AutoreleaseRV:
1930 case IC_FusedRetainAutorelease:
1931 case IC_FusedRetainAutoreleaseRV:
1932 return true;
1933 default:
1934 return false;
1935 }
1936}
1937
1938namespace {
1939 /// DependenceKind - There are several kinds of dependence-like concepts in
1940 /// use here.
1941 enum DependenceKind {
1942 NeedsPositiveRetainCount,
1943 CanChangeRetainCount,
1944 RetainAutoreleaseDep, ///< Blocks objc_retainAutorelease.
1945 RetainAutoreleaseRVDep, ///< Blocks objc_retainAutoreleaseReturnValue.
1946 RetainRVDep ///< Blocks objc_retainAutoreleasedReturnValue.
1947 };
1948}
1949
1950/// Depends - Test if there can be dependencies on Inst through Arg. This
1951/// function only tests dependencies relevant for removing pairs of calls.
1952static bool
1953Depends(DependenceKind Flavor, Instruction *Inst, const Value *Arg,
1954 ProvenanceAnalysis &PA) {
1955 // If we've reached the definition of Arg, stop.
1956 if (Inst == Arg)
1957 return true;
1958
1959 switch (Flavor) {
1960 case NeedsPositiveRetainCount: {
1961 InstructionClass Class = GetInstructionClass(Inst);
1962 switch (Class) {
1963 case IC_AutoreleasepoolPop:
1964 case IC_AutoreleasepoolPush:
1965 case IC_None:
1966 return false;
1967 default:
1968 return CanUse(Inst, Arg, PA, Class);
1969 }
1970 }
1971
1972 case CanChangeRetainCount: {
1973 InstructionClass Class = GetInstructionClass(Inst);
1974 switch (Class) {
1975 case IC_AutoreleasepoolPop:
1976 // Conservatively assume this can decrement any count.
1977 return true;
1978 case IC_AutoreleasepoolPush:
1979 case IC_None:
1980 return false;
1981 default:
1982 return CanAlterRefCount(Inst, Arg, PA, Class);
1983 }
1984 }
1985
1986 case RetainAutoreleaseDep:
1987 switch (GetBasicInstructionClass(Inst)) {
1988 case IC_AutoreleasepoolPop:
1989 // Don't merge an objc_autorelease with an objc_retain inside a different
1990 // autoreleasepool scope.
1991 return true;
1992 case IC_Retain:
1993 case IC_RetainRV:
1994 // Check for a retain of the same pointer for merging.
1995 return GetObjCArg(Inst) == Arg;
1996 default:
1997 // Nothing else matters for objc_retainAutorelease formation.
1998 return false;
1999 }
John McCall9fbd3182011-06-15 23:37:01 +00002000
2001 case RetainAutoreleaseRVDep: {
2002 InstructionClass Class = GetBasicInstructionClass(Inst);
2003 switch (Class) {
2004 case IC_Retain:
2005 case IC_RetainRV:
2006 // Check for a retain of the same pointer for merging.
2007 return GetObjCArg(Inst) == Arg;
2008 default:
2009 // Anything that can autorelease interrupts
2010 // retainAutoreleaseReturnValue formation.
2011 return CanInterruptRV(Class);
2012 }
John McCall9fbd3182011-06-15 23:37:01 +00002013 }
2014
2015 case RetainRVDep:
2016 return CanInterruptRV(GetBasicInstructionClass(Inst));
2017 }
2018
2019 llvm_unreachable("Invalid dependence flavor");
John McCall9fbd3182011-06-15 23:37:01 +00002020}
2021
2022/// FindDependencies - Walk up the CFG from StartPos (which is in StartBB) and
2023/// find local and non-local dependencies on Arg.
2024/// TODO: Cache results?
2025static void
2026FindDependencies(DependenceKind Flavor,
2027 const Value *Arg,
2028 BasicBlock *StartBB, Instruction *StartInst,
2029 SmallPtrSet<Instruction *, 4> &DependingInstructions,
2030 SmallPtrSet<const BasicBlock *, 4> &Visited,
2031 ProvenanceAnalysis &PA) {
2032 BasicBlock::iterator StartPos = StartInst;
2033
2034 SmallVector<std::pair<BasicBlock *, BasicBlock::iterator>, 4> Worklist;
2035 Worklist.push_back(std::make_pair(StartBB, StartPos));
2036 do {
2037 std::pair<BasicBlock *, BasicBlock::iterator> Pair =
2038 Worklist.pop_back_val();
2039 BasicBlock *LocalStartBB = Pair.first;
2040 BasicBlock::iterator LocalStartPos = Pair.second;
2041 BasicBlock::iterator StartBBBegin = LocalStartBB->begin();
2042 for (;;) {
2043 if (LocalStartPos == StartBBBegin) {
2044 pred_iterator PI(LocalStartBB), PE(LocalStartBB, false);
2045 if (PI == PE)
2046 // If we've reached the function entry, produce a null dependence.
2047 DependingInstructions.insert(0);
2048 else
2049 // Add the predecessors to the worklist.
2050 do {
2051 BasicBlock *PredBB = *PI;
2052 if (Visited.insert(PredBB))
2053 Worklist.push_back(std::make_pair(PredBB, PredBB->end()));
2054 } while (++PI != PE);
2055 break;
2056 }
2057
2058 Instruction *Inst = --LocalStartPos;
2059 if (Depends(Flavor, Inst, Arg, PA)) {
2060 DependingInstructions.insert(Inst);
2061 break;
2062 }
2063 }
2064 } while (!Worklist.empty());
2065
2066 // Determine whether the original StartBB post-dominates all of the blocks we
2067 // visited. If not, insert a sentinal indicating that most optimizations are
2068 // not safe.
2069 for (SmallPtrSet<const BasicBlock *, 4>::const_iterator I = Visited.begin(),
2070 E = Visited.end(); I != E; ++I) {
2071 const BasicBlock *BB = *I;
2072 if (BB == StartBB)
2073 continue;
2074 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2075 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2076 const BasicBlock *Succ = *SI;
2077 if (Succ != StartBB && !Visited.count(Succ)) {
2078 DependingInstructions.insert(reinterpret_cast<Instruction *>(-1));
2079 return;
2080 }
2081 }
2082 }
2083}
2084
2085static bool isNullOrUndef(const Value *V) {
2086 return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
2087}
2088
2089static bool isNoopInstruction(const Instruction *I) {
2090 return isa<BitCastInst>(I) ||
2091 (isa<GetElementPtrInst>(I) &&
2092 cast<GetElementPtrInst>(I)->hasAllZeroIndices());
2093}
2094
2095/// OptimizeRetainCall - Turn objc_retain into
2096/// objc_retainAutoreleasedReturnValue if the operand is a return value.
2097void
2098ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) {
2099 CallSite CS(GetObjCArg(Retain));
2100 Instruction *Call = CS.getInstruction();
2101 if (!Call) return;
2102 if (Call->getParent() != Retain->getParent()) return;
2103
2104 // Check that the call is next to the retain.
2105 BasicBlock::iterator I = Call;
2106 ++I;
2107 while (isNoopInstruction(I)) ++I;
2108 if (&*I != Retain)
2109 return;
2110
2111 // Turn it to an objc_retainAutoreleasedReturnValue..
2112 Changed = true;
2113 ++NumPeeps;
2114 cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent()));
2115}
2116
2117/// OptimizeRetainRVCall - Turn objc_retainAutoreleasedReturnValue into
2118/// objc_retain if the operand is not a return value. Or, if it can be
2119/// paired with an objc_autoreleaseReturnValue, delete the pair and
2120/// return true.
2121bool
2122ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
2123 // Check for the argument being from an immediately preceding call.
2124 Value *Arg = GetObjCArg(RetainRV);
2125 CallSite CS(Arg);
2126 if (Instruction *Call = CS.getInstruction())
2127 if (Call->getParent() == RetainRV->getParent()) {
2128 BasicBlock::iterator I = Call;
2129 ++I;
2130 while (isNoopInstruction(I)) ++I;
2131 if (&*I == RetainRV)
2132 return false;
2133 }
2134
2135 // Check for being preceded by an objc_autoreleaseReturnValue on the same
2136 // pointer. In this case, we can delete the pair.
2137 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
2138 if (I != Begin) {
2139 do --I; while (I != Begin && isNoopInstruction(I));
2140 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
2141 GetObjCArg(I) == Arg) {
2142 Changed = true;
2143 ++NumPeeps;
2144 EraseInstruction(I);
2145 EraseInstruction(RetainRV);
2146 return true;
2147 }
2148 }
2149
2150 // Turn it to a plain objc_retain.
2151 Changed = true;
2152 ++NumPeeps;
2153 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
2154 return false;
2155}
2156
2157/// OptimizeAutoreleaseRVCall - Turn objc_autoreleaseReturnValue into
2158/// objc_autorelease if the result is not used as a return value.
2159void
2160ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV) {
2161 // Check for a return of the pointer value.
2162 const Value *Ptr = GetObjCArg(AutoreleaseRV);
Dan Gohman126a54f2011-08-12 00:36:31 +00002163 SmallVector<const Value *, 2> Users;
2164 Users.push_back(Ptr);
2165 do {
2166 Ptr = Users.pop_back_val();
2167 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
2168 UI != UE; ++UI) {
2169 const User *I = *UI;
2170 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
2171 return;
2172 if (isa<BitCastInst>(I))
2173 Users.push_back(I);
2174 }
2175 } while (!Users.empty());
John McCall9fbd3182011-06-15 23:37:01 +00002176
2177 Changed = true;
2178 ++NumPeeps;
2179 cast<CallInst>(AutoreleaseRV)->
2180 setCalledFunction(getAutoreleaseCallee(F.getParent()));
2181}
2182
2183/// OptimizeIndividualCalls - Visit each call, one at a time, and make
2184/// simplifications without doing any additional analysis.
2185void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
2186 // Reset all the flags in preparation for recomputing them.
2187 UsedInThisFunction = 0;
2188
2189 // Visit all objc_* calls in F.
2190 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2191 Instruction *Inst = &*I++;
2192 InstructionClass Class = GetBasicInstructionClass(Inst);
2193
2194 switch (Class) {
2195 default: break;
2196
2197 // Delete no-op casts. These function calls have special semantics, but
2198 // the semantics are entirely implemented via lowering in the front-end,
2199 // so by the time they reach the optimizer, they are just no-op calls
2200 // which return their argument.
2201 //
2202 // There are gray areas here, as the ability to cast reference-counted
2203 // pointers to raw void* and back allows code to break ARC assumptions,
2204 // however these are currently considered to be unimportant.
2205 case IC_NoopCast:
2206 Changed = true;
2207 ++NumNoops;
2208 EraseInstruction(Inst);
2209 continue;
2210
2211 // If the pointer-to-weak-pointer is null, it's undefined behavior.
2212 case IC_StoreWeak:
2213 case IC_LoadWeak:
2214 case IC_LoadWeakRetained:
2215 case IC_InitWeak:
2216 case IC_DestroyWeak: {
2217 CallInst *CI = cast<CallInst>(Inst);
2218 if (isNullOrUndef(CI->getArgOperand(0))) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002219 Type *Ty = CI->getArgOperand(0)->getType();
John McCall9fbd3182011-06-15 23:37:01 +00002220 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2221 Constant::getNullValue(Ty),
2222 CI);
2223 CI->replaceAllUsesWith(UndefValue::get(CI->getType()));
2224 CI->eraseFromParent();
2225 continue;
2226 }
2227 break;
2228 }
2229 case IC_CopyWeak:
2230 case IC_MoveWeak: {
2231 CallInst *CI = cast<CallInst>(Inst);
2232 if (isNullOrUndef(CI->getArgOperand(0)) ||
2233 isNullOrUndef(CI->getArgOperand(1))) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002234 Type *Ty = CI->getArgOperand(0)->getType();
John McCall9fbd3182011-06-15 23:37:01 +00002235 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2236 Constant::getNullValue(Ty),
2237 CI);
2238 CI->replaceAllUsesWith(UndefValue::get(CI->getType()));
2239 CI->eraseFromParent();
2240 continue;
2241 }
2242 break;
2243 }
2244 case IC_Retain:
2245 OptimizeRetainCall(F, Inst);
2246 break;
2247 case IC_RetainRV:
2248 if (OptimizeRetainRVCall(F, Inst))
2249 continue;
2250 break;
2251 case IC_AutoreleaseRV:
2252 OptimizeAutoreleaseRVCall(F, Inst);
2253 break;
2254 }
2255
2256 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
2257 if (IsAutorelease(Class) && Inst->use_empty()) {
2258 CallInst *Call = cast<CallInst>(Inst);
2259 const Value *Arg = Call->getArgOperand(0);
2260 Arg = FindSingleUseIdentifiedObject(Arg);
2261 if (Arg) {
2262 Changed = true;
2263 ++NumAutoreleases;
2264
2265 // Create the declaration lazily.
2266 LLVMContext &C = Inst->getContext();
2267 CallInst *NewCall =
2268 CallInst::Create(getReleaseCallee(F.getParent()),
2269 Call->getArgOperand(0), "", Call);
2270 NewCall->setMetadata(ImpreciseReleaseMDKind,
2271 MDNode::get(C, ArrayRef<Value *>()));
2272 EraseInstruction(Call);
2273 Inst = NewCall;
2274 Class = IC_Release;
2275 }
2276 }
2277
2278 // For functions which can never be passed stack arguments, add
2279 // a tail keyword.
2280 if (IsAlwaysTail(Class)) {
2281 Changed = true;
2282 cast<CallInst>(Inst)->setTailCall();
2283 }
2284
2285 // Set nounwind as needed.
2286 if (IsNoThrow(Class)) {
2287 Changed = true;
2288 cast<CallInst>(Inst)->setDoesNotThrow();
2289 }
2290
2291 if (!IsNoopOnNull(Class)) {
2292 UsedInThisFunction |= 1 << Class;
2293 continue;
2294 }
2295
2296 const Value *Arg = GetObjCArg(Inst);
2297
2298 // ARC calls with null are no-ops. Delete them.
2299 if (isNullOrUndef(Arg)) {
2300 Changed = true;
2301 ++NumNoops;
2302 EraseInstruction(Inst);
2303 continue;
2304 }
2305
2306 // Keep track of which of retain, release, autorelease, and retain_block
2307 // are actually present in this function.
2308 UsedInThisFunction |= 1 << Class;
2309
2310 // If Arg is a PHI, and one or more incoming values to the
2311 // PHI are null, and the call is control-equivalent to the PHI, and there
2312 // are no relevant side effects between the PHI and the call, the call
2313 // could be pushed up to just those paths with non-null incoming values.
2314 // For now, don't bother splitting critical edges for this.
2315 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
2316 Worklist.push_back(std::make_pair(Inst, Arg));
2317 do {
2318 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
2319 Inst = Pair.first;
2320 Arg = Pair.second;
2321
2322 const PHINode *PN = dyn_cast<PHINode>(Arg);
2323 if (!PN) continue;
2324
2325 // Determine if the PHI has any null operands, or any incoming
2326 // critical edges.
2327 bool HasNull = false;
2328 bool HasCriticalEdges = false;
2329 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2330 Value *Incoming =
2331 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2332 if (isNullOrUndef(Incoming))
2333 HasNull = true;
2334 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
2335 .getNumSuccessors() != 1) {
2336 HasCriticalEdges = true;
2337 break;
2338 }
2339 }
2340 // If we have null operands and no critical edges, optimize.
2341 if (!HasCriticalEdges && HasNull) {
2342 SmallPtrSet<Instruction *, 4> DependingInstructions;
2343 SmallPtrSet<const BasicBlock *, 4> Visited;
2344
2345 // Check that there is nothing that cares about the reference
2346 // count between the call and the phi.
2347 FindDependencies(NeedsPositiveRetainCount, Arg,
2348 Inst->getParent(), Inst,
2349 DependingInstructions, Visited, PA);
2350 if (DependingInstructions.size() == 1 &&
2351 *DependingInstructions.begin() == PN) {
2352 Changed = true;
2353 ++NumPartialNoops;
2354 // Clone the call into each predecessor that has a non-null value.
2355 CallInst *CInst = cast<CallInst>(Inst);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002356 Type *ParamTy = CInst->getArgOperand(0)->getType();
John McCall9fbd3182011-06-15 23:37:01 +00002357 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2358 Value *Incoming =
2359 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2360 if (!isNullOrUndef(Incoming)) {
2361 CallInst *Clone = cast<CallInst>(CInst->clone());
2362 Value *Op = PN->getIncomingValue(i);
2363 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
2364 if (Op->getType() != ParamTy)
2365 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
2366 Clone->setArgOperand(0, Op);
2367 Clone->insertBefore(InsertPos);
2368 Worklist.push_back(std::make_pair(Clone, Incoming));
2369 }
2370 }
2371 // Erase the original call.
2372 EraseInstruction(CInst);
2373 continue;
2374 }
2375 }
2376 } while (!Worklist.empty());
2377 }
2378}
2379
2380/// CheckForCFGHazards - Check for critical edges, loop boundaries, irreducible
2381/// control flow, or other CFG structures where moving code across the edge
2382/// would result in it being executed more.
2383void
2384ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
2385 DenseMap<const BasicBlock *, BBState> &BBStates,
2386 BBState &MyStates) const {
2387 // If any top-down local-use or possible-dec has a succ which is earlier in
2388 // the sequence, forget it.
2389 for (BBState::ptr_const_iterator I = MyStates.top_down_ptr_begin(),
2390 E = MyStates.top_down_ptr_end(); I != E; ++I)
2391 switch (I->second.GetSeq()) {
2392 default: break;
2393 case S_Use: {
2394 const Value *Arg = I->first;
2395 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2396 bool SomeSuccHasSame = false;
2397 bool AllSuccsHaveSame = true;
Dan Gohmana7f7db22011-08-12 00:26:31 +00002398 PtrState &S = MyStates.getPtrTopDownState(Arg);
2399 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2400 PtrState &SuccS = BBStates[*SI].getPtrBottomUpState(Arg);
2401 switch (SuccS.GetSeq()) {
John McCall9fbd3182011-06-15 23:37:01 +00002402 case S_None:
Dan Gohmana7f7db22011-08-12 00:26:31 +00002403 case S_CanRelease: {
Dan Gohmane6d5e882011-08-19 00:26:36 +00002404 if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002405 S.ClearSequenceProgress();
2406 continue;
2407 }
John McCall9fbd3182011-06-15 23:37:01 +00002408 case S_Use:
2409 SomeSuccHasSame = true;
2410 break;
2411 case S_Stop:
2412 case S_Release:
2413 case S_MovableRelease:
Dan Gohmane6d5e882011-08-19 00:26:36 +00002414 if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002415 AllSuccsHaveSame = false;
John McCall9fbd3182011-06-15 23:37:01 +00002416 break;
2417 case S_Retain:
2418 llvm_unreachable("bottom-up pointer in retain state!");
2419 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002420 }
John McCall9fbd3182011-06-15 23:37:01 +00002421 // If the state at the other end of any of the successor edges
2422 // matches the current state, require all edges to match. This
2423 // guards against loops in the middle of a sequence.
2424 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002425 S.ClearSequenceProgress();
Dan Gohman2e68beb2011-12-12 18:13:53 +00002426 break;
John McCall9fbd3182011-06-15 23:37:01 +00002427 }
2428 case S_CanRelease: {
2429 const Value *Arg = I->first;
2430 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2431 bool SomeSuccHasSame = false;
2432 bool AllSuccsHaveSame = true;
Dan Gohmana7f7db22011-08-12 00:26:31 +00002433 PtrState &S = MyStates.getPtrTopDownState(Arg);
2434 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2435 PtrState &SuccS = BBStates[*SI].getPtrBottomUpState(Arg);
2436 switch (SuccS.GetSeq()) {
2437 case S_None: {
Dan Gohmane6d5e882011-08-19 00:26:36 +00002438 if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002439 S.ClearSequenceProgress();
2440 continue;
2441 }
John McCall9fbd3182011-06-15 23:37:01 +00002442 case S_CanRelease:
2443 SomeSuccHasSame = true;
2444 break;
2445 case S_Stop:
2446 case S_Release:
2447 case S_MovableRelease:
2448 case S_Use:
Dan Gohmane6d5e882011-08-19 00:26:36 +00002449 if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002450 AllSuccsHaveSame = false;
John McCall9fbd3182011-06-15 23:37:01 +00002451 break;
2452 case S_Retain:
2453 llvm_unreachable("bottom-up pointer in retain state!");
2454 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002455 }
John McCall9fbd3182011-06-15 23:37:01 +00002456 // If the state at the other end of any of the successor edges
2457 // matches the current state, require all edges to match. This
2458 // guards against loops in the middle of a sequence.
2459 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002460 S.ClearSequenceProgress();
Dan Gohman2e68beb2011-12-12 18:13:53 +00002461 break;
John McCall9fbd3182011-06-15 23:37:01 +00002462 }
2463 }
2464}
2465
2466bool
2467ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2468 DenseMap<const BasicBlock *, BBState> &BBStates,
2469 MapVector<Value *, RRInfo> &Retains) {
2470 bool NestingDetected = false;
2471 BBState &MyStates = BBStates[BB];
2472
2473 // Merge the states from each successor to compute the initial state
2474 // for the current block.
2475 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2476 succ_const_iterator SI(TI), SE(TI, false);
2477 if (SI == SE)
2478 MyStates.SetAsExit();
2479 else
2480 do {
2481 const BasicBlock *Succ = *SI++;
2482 if (Succ == BB)
2483 continue;
2484 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
Dan Gohmana7f7db22011-08-12 00:26:31 +00002485 // If we haven't seen this node yet, then we've found a CFG cycle.
2486 // Be optimistic here; it's CheckForCFGHazards' job detect trouble.
John McCall9fbd3182011-06-15 23:37:01 +00002487 if (I == BBStates.end())
2488 continue;
2489 MyStates.InitFromSucc(I->second);
2490 while (SI != SE) {
2491 Succ = *SI++;
2492 if (Succ != BB) {
2493 I = BBStates.find(Succ);
2494 if (I != BBStates.end())
2495 MyStates.MergeSucc(I->second);
2496 }
2497 }
2498 break;
2499 } while (SI != SE);
2500
2501 // Visit all the instructions, bottom-up.
2502 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2503 Instruction *Inst = llvm::prior(I);
2504 InstructionClass Class = GetInstructionClass(Inst);
2505 const Value *Arg = 0;
2506
2507 switch (Class) {
2508 case IC_Release: {
2509 Arg = GetObjCArg(Inst);
2510
2511 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2512
2513 // If we see two releases in a row on the same pointer. If so, make
2514 // a note, and we'll cicle back to revisit it after we've
2515 // hopefully eliminated the second release, which may allow us to
2516 // eliminate the first release too.
2517 // Theoretically we could implement removal of nested retain+release
2518 // pairs by making PtrState hold a stack of states, but this is
2519 // simple and avoids adding overhead for the non-nested case.
2520 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease)
2521 NestingDetected = true;
2522
John McCall9fbd3182011-06-15 23:37:01 +00002523 S.RRI.clear();
Dan Gohman28588ff2011-12-12 18:16:56 +00002524
2525 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2526 S.SetSeq(ReleaseMetadata ? S_MovableRelease : S_Release);
2527 S.RRI.ReleaseMetadata = ReleaseMetadata;
Dan Gohmane6d5e882011-08-19 00:26:36 +00002528 S.RRI.KnownSafe = S.IsKnownNested() || S.IsKnownIncremented();
John McCall9fbd3182011-06-15 23:37:01 +00002529 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2530 S.RRI.Calls.insert(Inst);
2531
2532 S.IncrementRefCount();
Dan Gohmane6d5e882011-08-19 00:26:36 +00002533 S.IncrementNestCount();
John McCall9fbd3182011-06-15 23:37:01 +00002534 break;
2535 }
2536 case IC_RetainBlock:
Dan Gohman79522dc2012-01-13 00:39:07 +00002537 // An objc_retainBlock call with just a use may need to be kept,
2538 // because it may be copying a block from the stack to the heap.
2539 if (!IsRetainBlockOptimizable(Inst))
2540 break;
2541 // FALLTHROUGH
John McCall9fbd3182011-06-15 23:37:01 +00002542 case IC_Retain:
2543 case IC_RetainRV: {
2544 Arg = GetObjCArg(Inst);
2545
2546 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2547 S.DecrementRefCount();
Dan Gohmana7f7db22011-08-12 00:26:31 +00002548 S.SetAtLeastOneRefCount();
Dan Gohmane6d5e882011-08-19 00:26:36 +00002549 S.DecrementNestCount();
John McCall9fbd3182011-06-15 23:37:01 +00002550
2551 switch (S.GetSeq()) {
2552 case S_Stop:
2553 case S_Release:
2554 case S_MovableRelease:
2555 case S_Use:
2556 S.RRI.ReverseInsertPts.clear();
2557 // FALL THROUGH
2558 case S_CanRelease:
2559 // Don't do retain+release tracking for IC_RetainRV, because it's
2560 // better to let it remain as the first instruction after a call.
2561 if (Class != IC_RetainRV) {
2562 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2563 Retains[Inst] = S.RRI;
2564 }
2565 S.ClearSequenceProgress();
2566 break;
2567 case S_None:
2568 break;
2569 case S_Retain:
2570 llvm_unreachable("bottom-up pointer in retain state!");
2571 }
Dan Gohmane6d5e882011-08-19 00:26:36 +00002572 continue;
John McCall9fbd3182011-06-15 23:37:01 +00002573 }
2574 case IC_AutoreleasepoolPop:
2575 // Conservatively, clear MyStates for all known pointers.
2576 MyStates.clearBottomUpPointers();
2577 continue;
2578 case IC_AutoreleasepoolPush:
2579 case IC_None:
2580 // These are irrelevant.
2581 continue;
2582 default:
2583 break;
2584 }
2585
2586 // Consider any other possible effects of this instruction on each
2587 // pointer being tracked.
2588 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
2589 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
2590 const Value *Ptr = MI->first;
2591 if (Ptr == Arg)
2592 continue; // Handled above.
2593 PtrState &S = MI->second;
2594 Sequence Seq = S.GetSeq();
2595
Dan Gohmane6d5e882011-08-19 00:26:36 +00002596 // Check for possible releases.
2597 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2598 S.DecrementRefCount();
Dan Gohmana7f7db22011-08-12 00:26:31 +00002599 switch (Seq) {
2600 case S_Use:
2601 S.SetSeq(S_CanRelease);
2602 continue;
2603 case S_CanRelease:
2604 case S_Release:
2605 case S_MovableRelease:
2606 case S_Stop:
2607 case S_None:
2608 break;
2609 case S_Retain:
2610 llvm_unreachable("bottom-up pointer in retain state!");
2611 }
Dan Gohmane6d5e882011-08-19 00:26:36 +00002612 }
John McCall9fbd3182011-06-15 23:37:01 +00002613
2614 // Check for possible direct uses.
2615 switch (Seq) {
2616 case S_Release:
2617 case S_MovableRelease:
2618 if (CanUse(Inst, Ptr, PA, Class)) {
Dan Gohman597fece2011-09-29 22:25:23 +00002619 assert(S.RRI.ReverseInsertPts.empty());
John McCall9fbd3182011-06-15 23:37:01 +00002620 S.RRI.ReverseInsertPts.insert(Inst);
2621 S.SetSeq(S_Use);
2622 } else if (Seq == S_Release &&
2623 (Class == IC_User || Class == IC_CallOrUser)) {
2624 // Non-movable releases depend on any possible objc pointer use.
2625 S.SetSeq(S_Stop);
Dan Gohman597fece2011-09-29 22:25:23 +00002626 assert(S.RRI.ReverseInsertPts.empty());
John McCall9fbd3182011-06-15 23:37:01 +00002627 S.RRI.ReverseInsertPts.insert(Inst);
2628 }
2629 break;
2630 case S_Stop:
2631 if (CanUse(Inst, Ptr, PA, Class))
2632 S.SetSeq(S_Use);
2633 break;
2634 case S_CanRelease:
2635 case S_Use:
2636 case S_None:
2637 break;
2638 case S_Retain:
2639 llvm_unreachable("bottom-up pointer in retain state!");
2640 }
2641 }
2642 }
2643
2644 return NestingDetected;
2645}
2646
2647bool
2648ObjCARCOpt::VisitTopDown(BasicBlock *BB,
2649 DenseMap<const BasicBlock *, BBState> &BBStates,
2650 DenseMap<Value *, RRInfo> &Releases) {
2651 bool NestingDetected = false;
2652 BBState &MyStates = BBStates[BB];
2653
2654 // Merge the states from each predecessor to compute the initial state
2655 // for the current block.
2656 const_pred_iterator PI(BB), PE(BB, false);
2657 if (PI == PE)
2658 MyStates.SetAsEntry();
2659 else
2660 do {
2661 const BasicBlock *Pred = *PI++;
2662 if (Pred == BB)
2663 continue;
2664 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
Dan Gohmana7f7db22011-08-12 00:26:31 +00002665 // If we haven't seen this node yet, then we've found a CFG cycle.
2666 // Be optimistic here; it's CheckForCFGHazards' job detect trouble.
Dan Gohman59a1c932011-12-12 19:42:25 +00002667 if (I == BBStates.end() || !I->second.isVisitedTopDown())
John McCall9fbd3182011-06-15 23:37:01 +00002668 continue;
2669 MyStates.InitFromPred(I->second);
2670 while (PI != PE) {
2671 Pred = *PI++;
2672 if (Pred != BB) {
2673 I = BBStates.find(Pred);
Dan Gohman48371602011-12-21 21:43:50 +00002674 if (I != BBStates.end() && I->second.isVisitedTopDown())
John McCall9fbd3182011-06-15 23:37:01 +00002675 MyStates.MergePred(I->second);
2676 }
2677 }
2678 break;
2679 } while (PI != PE);
2680
2681 // Visit all the instructions, top-down.
2682 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2683 Instruction *Inst = I;
2684 InstructionClass Class = GetInstructionClass(Inst);
2685 const Value *Arg = 0;
2686
2687 switch (Class) {
2688 case IC_RetainBlock:
Dan Gohman79522dc2012-01-13 00:39:07 +00002689 // An objc_retainBlock call with just a use may need to be kept,
2690 // because it may be copying a block from the stack to the heap.
2691 if (!IsRetainBlockOptimizable(Inst))
2692 break;
2693 // FALLTHROUGH
John McCall9fbd3182011-06-15 23:37:01 +00002694 case IC_Retain:
2695 case IC_RetainRV: {
2696 Arg = GetObjCArg(Inst);
2697
2698 PtrState &S = MyStates.getPtrTopDownState(Arg);
2699
2700 // Don't do retain+release tracking for IC_RetainRV, because it's
2701 // better to let it remain as the first instruction after a call.
2702 if (Class != IC_RetainRV) {
2703 // If we see two retains in a row on the same pointer. If so, make
2704 // a note, and we'll cicle back to revisit it after we've
2705 // hopefully eliminated the second retain, which may allow us to
2706 // eliminate the first retain too.
2707 // Theoretically we could implement removal of nested retain+release
2708 // pairs by making PtrState hold a stack of states, but this is
2709 // simple and avoids adding overhead for the non-nested case.
2710 if (S.GetSeq() == S_Retain)
2711 NestingDetected = true;
2712
2713 S.SetSeq(S_Retain);
2714 S.RRI.clear();
2715 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
Dan Gohmane6d5e882011-08-19 00:26:36 +00002716 // Don't check S.IsKnownIncremented() here because it's not
2717 // sufficient.
2718 S.RRI.KnownSafe = S.IsKnownNested();
John McCall9fbd3182011-06-15 23:37:01 +00002719 S.RRI.Calls.insert(Inst);
2720 }
2721
Dan Gohmana7f7db22011-08-12 00:26:31 +00002722 S.SetAtLeastOneRefCount();
John McCall9fbd3182011-06-15 23:37:01 +00002723 S.IncrementRefCount();
Dan Gohmane6d5e882011-08-19 00:26:36 +00002724 S.IncrementNestCount();
2725 continue;
John McCall9fbd3182011-06-15 23:37:01 +00002726 }
2727 case IC_Release: {
2728 Arg = GetObjCArg(Inst);
2729
2730 PtrState &S = MyStates.getPtrTopDownState(Arg);
2731 S.DecrementRefCount();
Dan Gohmane6d5e882011-08-19 00:26:36 +00002732 S.DecrementNestCount();
John McCall9fbd3182011-06-15 23:37:01 +00002733
2734 switch (S.GetSeq()) {
2735 case S_Retain:
2736 case S_CanRelease:
2737 S.RRI.ReverseInsertPts.clear();
2738 // FALL THROUGH
2739 case S_Use:
2740 S.RRI.ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2741 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2742 Releases[Inst] = S.RRI;
2743 S.ClearSequenceProgress();
2744 break;
2745 case S_None:
2746 break;
2747 case S_Stop:
2748 case S_Release:
2749 case S_MovableRelease:
2750 llvm_unreachable("top-down pointer in release state!");
2751 }
2752 break;
2753 }
2754 case IC_AutoreleasepoolPop:
2755 // Conservatively, clear MyStates for all known pointers.
2756 MyStates.clearTopDownPointers();
2757 continue;
2758 case IC_AutoreleasepoolPush:
2759 case IC_None:
2760 // These are irrelevant.
2761 continue;
2762 default:
2763 break;
2764 }
2765
2766 // Consider any other possible effects of this instruction on each
2767 // pointer being tracked.
2768 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
2769 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
2770 const Value *Ptr = MI->first;
2771 if (Ptr == Arg)
2772 continue; // Handled above.
2773 PtrState &S = MI->second;
2774 Sequence Seq = S.GetSeq();
2775
Dan Gohmane6d5e882011-08-19 00:26:36 +00002776 // Check for possible releases.
2777 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2778 S.DecrementRefCount();
John McCall9fbd3182011-06-15 23:37:01 +00002779 switch (Seq) {
2780 case S_Retain:
2781 S.SetSeq(S_CanRelease);
Dan Gohman597fece2011-09-29 22:25:23 +00002782 assert(S.RRI.ReverseInsertPts.empty());
John McCall9fbd3182011-06-15 23:37:01 +00002783 S.RRI.ReverseInsertPts.insert(Inst);
2784
2785 // One call can't cause a transition from S_Retain to S_CanRelease
2786 // and S_CanRelease to S_Use. If we've made the first transition,
2787 // we're done.
2788 continue;
2789 case S_Use:
2790 case S_CanRelease:
2791 case S_None:
2792 break;
2793 case S_Stop:
2794 case S_Release:
2795 case S_MovableRelease:
2796 llvm_unreachable("top-down pointer in release state!");
2797 }
Dan Gohmane6d5e882011-08-19 00:26:36 +00002798 }
John McCall9fbd3182011-06-15 23:37:01 +00002799
2800 // Check for possible direct uses.
2801 switch (Seq) {
2802 case S_CanRelease:
2803 if (CanUse(Inst, Ptr, PA, Class))
2804 S.SetSeq(S_Use);
2805 break;
John McCall9fbd3182011-06-15 23:37:01 +00002806 case S_Retain:
Dan Gohman597fece2011-09-29 22:25:23 +00002807 case S_Use:
John McCall9fbd3182011-06-15 23:37:01 +00002808 case S_None:
2809 break;
2810 case S_Stop:
2811 case S_Release:
2812 case S_MovableRelease:
2813 llvm_unreachable("top-down pointer in release state!");
2814 }
2815 }
2816 }
2817
2818 CheckForCFGHazards(BB, BBStates, MyStates);
2819 return NestingDetected;
2820}
2821
Dan Gohman59a1c932011-12-12 19:42:25 +00002822static void
2823ComputePostOrders(Function &F,
2824 SmallVectorImpl<BasicBlock *> &PostOrder,
2825 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder) {
2826 /// Backedges - Backedges detected in the DFS. These edges will be
2827 /// ignored in the reverse-CFG DFS, so that loops with multiple exits will be
2828 /// traversed in the desired order.
2829 DenseSet<std::pair<BasicBlock *, BasicBlock *> > Backedges;
2830
2831 /// Visited - The visited set, for doing DFS walks.
2832 SmallPtrSet<BasicBlock *, 16> Visited;
2833
2834 // Do DFS, computing the PostOrder.
2835 SmallPtrSet<BasicBlock *, 16> OnStack;
2836 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
2837 BasicBlock *EntryBB = &F.getEntryBlock();
2838 SuccStack.push_back(std::make_pair(EntryBB, succ_begin(EntryBB)));
2839 Visited.insert(EntryBB);
2840 OnStack.insert(EntryBB);
2841 do {
2842 dfs_next_succ:
2843 succ_iterator End = succ_end(SuccStack.back().first);
2844 while (SuccStack.back().second != End) {
2845 BasicBlock *BB = *SuccStack.back().second++;
2846 if (Visited.insert(BB)) {
2847 SuccStack.push_back(std::make_pair(BB, succ_begin(BB)));
2848 OnStack.insert(BB);
2849 goto dfs_next_succ;
2850 }
2851 if (OnStack.count(BB))
2852 Backedges.insert(std::make_pair(SuccStack.back().first, BB));
2853 }
2854 OnStack.erase(SuccStack.back().first);
2855 PostOrder.push_back(SuccStack.pop_back_val().first);
2856 } while (!SuccStack.empty());
2857
2858 Visited.clear();
2859
2860 // Compute the exits, which are the starting points for reverse-CFG DFS.
2861 SmallVector<BasicBlock *, 4> Exits;
2862 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
2863 BasicBlock *BB = I;
2864 if (BB->getTerminator()->getNumSuccessors() == 0)
2865 Exits.push_back(BB);
2866 }
2867
2868 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
2869 SmallVector<std::pair<BasicBlock *, pred_iterator>, 16> PredStack;
2870 for (SmallVectorImpl<BasicBlock *>::iterator I = Exits.begin(), E = Exits.end();
2871 I != E; ++I) {
2872 BasicBlock *ExitBB = *I;
2873 PredStack.push_back(std::make_pair(ExitBB, pred_begin(ExitBB)));
2874 Visited.insert(ExitBB);
2875 while (!PredStack.empty()) {
2876 reverse_dfs_next_succ:
2877 pred_iterator End = pred_end(PredStack.back().first);
2878 while (PredStack.back().second != End) {
2879 BasicBlock *BB = *PredStack.back().second++;
2880 // Skip backedges detected in the forward-CFG DFS.
2881 if (Backedges.count(std::make_pair(BB, PredStack.back().first)))
2882 continue;
2883 if (Visited.insert(BB)) {
2884 PredStack.push_back(std::make_pair(BB, pred_begin(BB)));
2885 goto reverse_dfs_next_succ;
2886 }
2887 }
2888 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
2889 }
2890 }
2891}
2892
John McCall9fbd3182011-06-15 23:37:01 +00002893// Visit - Visit the function both top-down and bottom-up.
2894bool
2895ObjCARCOpt::Visit(Function &F,
2896 DenseMap<const BasicBlock *, BBState> &BBStates,
2897 MapVector<Value *, RRInfo> &Retains,
2898 DenseMap<Value *, RRInfo> &Releases) {
Dan Gohman59a1c932011-12-12 19:42:25 +00002899
2900 // Use reverse-postorder traversals, because we magically know that loops
2901 // will be well behaved, i.e. they won't repeatedly call retain on a single
2902 // pointer without doing a release. We can't use the ReversePostOrderTraversal
2903 // class here because we want the reverse-CFG postorder to consider each
2904 // function exit point, and we want to ignore selected cycle edges.
2905 SmallVector<BasicBlock *, 16> PostOrder;
2906 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
2907 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder);
2908
2909 // Use reverse-postorder on the reverse CFG for bottom-up.
John McCall9fbd3182011-06-15 23:37:01 +00002910 bool BottomUpNestingDetected = false;
Dan Gohmanb48ef3a2011-08-18 21:27:42 +00002911 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
Dan Gohman59a1c932011-12-12 19:42:25 +00002912 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
2913 I != E; ++I)
2914 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
John McCall9fbd3182011-06-15 23:37:01 +00002915
Dan Gohman59a1c932011-12-12 19:42:25 +00002916 // Use reverse-postorder for top-down.
John McCall9fbd3182011-06-15 23:37:01 +00002917 bool TopDownNestingDetected = false;
Dan Gohman59a1c932011-12-12 19:42:25 +00002918 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2919 PostOrder.rbegin(), E = PostOrder.rend();
2920 I != E; ++I)
2921 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
John McCall9fbd3182011-06-15 23:37:01 +00002922
2923 return TopDownNestingDetected && BottomUpNestingDetected;
2924}
2925
2926/// MoveCalls - Move the calls in RetainsToMove and ReleasesToMove.
2927void ObjCARCOpt::MoveCalls(Value *Arg,
2928 RRInfo &RetainsToMove,
2929 RRInfo &ReleasesToMove,
2930 MapVector<Value *, RRInfo> &Retains,
2931 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman44280692011-07-22 22:29:21 +00002932 SmallVectorImpl<Instruction *> &DeadInsts,
2933 Module *M) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002934 Type *ArgTy = Arg->getType();
Dan Gohman44280692011-07-22 22:29:21 +00002935 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
John McCall9fbd3182011-06-15 23:37:01 +00002936
2937 // Insert the new retain and release calls.
2938 for (SmallPtrSet<Instruction *, 2>::const_iterator
2939 PI = ReleasesToMove.ReverseInsertPts.begin(),
2940 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2941 Instruction *InsertPt = *PI;
2942 Value *MyArg = ArgTy == ParamTy ? Arg :
2943 new BitCastInst(Arg, ParamTy, "", InsertPt);
2944 CallInst *Call =
2945 CallInst::Create(RetainsToMove.IsRetainBlock ?
Dan Gohman44280692011-07-22 22:29:21 +00002946 getRetainBlockCallee(M) : getRetainCallee(M),
John McCall9fbd3182011-06-15 23:37:01 +00002947 MyArg, "", InsertPt);
2948 Call->setDoesNotThrow();
Dan Gohman79522dc2012-01-13 00:39:07 +00002949 if (RetainsToMove.IsRetainBlock)
Dan Gohmana974bea2011-10-17 22:53:25 +00002950 Call->setMetadata(CopyOnEscapeMDKind,
2951 MDNode::get(M->getContext(), ArrayRef<Value *>()));
Dan Gohman79522dc2012-01-13 00:39:07 +00002952 else
John McCall9fbd3182011-06-15 23:37:01 +00002953 Call->setTailCall();
2954 }
2955 for (SmallPtrSet<Instruction *, 2>::const_iterator
2956 PI = RetainsToMove.ReverseInsertPts.begin(),
2957 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
Dan Gohman0860d0b2011-06-16 20:57:14 +00002958 Instruction *LastUse = *PI;
2959 Instruction *InsertPts[] = { 0, 0, 0 };
2960 if (InvokeInst *II = dyn_cast<InvokeInst>(LastUse)) {
2961 // We can't insert code immediately after an invoke instruction, so
2962 // insert code at the beginning of both successor blocks instead.
2963 // The invoke's return value isn't available in the unwind block,
2964 // but our releases will never depend on it, because they must be
2965 // paired with retains from before the invoke.
Bill Wendling89d44112011-08-25 01:08:34 +00002966 InsertPts[0] = II->getNormalDest()->getFirstInsertionPt();
2967 InsertPts[1] = II->getUnwindDest()->getFirstInsertionPt();
Dan Gohman0860d0b2011-06-16 20:57:14 +00002968 } else {
2969 // Insert code immediately after the last use.
2970 InsertPts[0] = llvm::next(BasicBlock::iterator(LastUse));
2971 }
2972
2973 for (Instruction **I = InsertPts; *I; ++I) {
2974 Instruction *InsertPt = *I;
2975 Value *MyArg = ArgTy == ParamTy ? Arg :
2976 new BitCastInst(Arg, ParamTy, "", InsertPt);
Dan Gohman44280692011-07-22 22:29:21 +00002977 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
2978 "", InsertPt);
Dan Gohman0860d0b2011-06-16 20:57:14 +00002979 // Attach a clang.imprecise_release metadata tag, if appropriate.
2980 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
2981 Call->setMetadata(ImpreciseReleaseMDKind, M);
2982 Call->setDoesNotThrow();
2983 if (ReleasesToMove.IsTailCallRelease)
2984 Call->setTailCall();
2985 }
John McCall9fbd3182011-06-15 23:37:01 +00002986 }
2987
2988 // Delete the original retain and release calls.
2989 for (SmallPtrSet<Instruction *, 2>::const_iterator
2990 AI = RetainsToMove.Calls.begin(),
2991 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
2992 Instruction *OrigRetain = *AI;
2993 Retains.blot(OrigRetain);
2994 DeadInsts.push_back(OrigRetain);
2995 }
2996 for (SmallPtrSet<Instruction *, 2>::const_iterator
2997 AI = ReleasesToMove.Calls.begin(),
2998 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
2999 Instruction *OrigRelease = *AI;
3000 Releases.erase(OrigRelease);
3001 DeadInsts.push_back(OrigRelease);
3002 }
3003}
3004
3005bool
3006ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
3007 &BBStates,
3008 MapVector<Value *, RRInfo> &Retains,
Dan Gohman44280692011-07-22 22:29:21 +00003009 DenseMap<Value *, RRInfo> &Releases,
3010 Module *M) {
John McCall9fbd3182011-06-15 23:37:01 +00003011 bool AnyPairsCompletelyEliminated = false;
3012 RRInfo RetainsToMove;
3013 RRInfo ReleasesToMove;
3014 SmallVector<Instruction *, 4> NewRetains;
3015 SmallVector<Instruction *, 4> NewReleases;
3016 SmallVector<Instruction *, 8> DeadInsts;
3017
3018 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
Dan Gohman597fece2011-09-29 22:25:23 +00003019 E = Retains.end(); I != E; ++I) {
3020 Value *V = I->first;
John McCall9fbd3182011-06-15 23:37:01 +00003021 if (!V) continue; // blotted
3022
3023 Instruction *Retain = cast<Instruction>(V);
3024 Value *Arg = GetObjCArg(Retain);
3025
Dan Gohman79522dc2012-01-13 00:39:07 +00003026 // If the object being released is in static or stack storage, we know it's
John McCall9fbd3182011-06-15 23:37:01 +00003027 // not being managed by ObjC reference counting, so we can delete pairs
3028 // regardless of what possible decrements or uses lie between them.
Dan Gohman79522dc2012-01-13 00:39:07 +00003029 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
Dan Gohman597fece2011-09-29 22:25:23 +00003030
Dan Gohman1b31ea82011-08-22 17:29:11 +00003031 // A constant pointer can't be pointing to an object on the heap. It may
3032 // be reference-counted, but it won't be deleted.
3033 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
3034 if (const GlobalVariable *GV =
3035 dyn_cast<GlobalVariable>(
3036 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
3037 if (GV->isConstant())
3038 KnownSafe = true;
3039
John McCall9fbd3182011-06-15 23:37:01 +00003040 // If a pair happens in a region where it is known that the reference count
3041 // is already incremented, we can similarly ignore possible decrements.
Dan Gohmane6d5e882011-08-19 00:26:36 +00003042 bool KnownSafeTD = true, KnownSafeBU = true;
John McCall9fbd3182011-06-15 23:37:01 +00003043
3044 // Connect the dots between the top-down-collected RetainsToMove and
3045 // bottom-up-collected ReleasesToMove to form sets of related calls.
3046 // This is an iterative process so that we connect multiple releases
3047 // to multiple retains if needed.
3048 unsigned OldDelta = 0;
3049 unsigned NewDelta = 0;
3050 unsigned OldCount = 0;
3051 unsigned NewCount = 0;
3052 bool FirstRelease = true;
3053 bool FirstRetain = true;
3054 NewRetains.push_back(Retain);
3055 for (;;) {
3056 for (SmallVectorImpl<Instruction *>::const_iterator
3057 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
3058 Instruction *NewRetain = *NI;
3059 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
3060 assert(It != Retains.end());
3061 const RRInfo &NewRetainRRI = It->second;
Dan Gohmane6d5e882011-08-19 00:26:36 +00003062 KnownSafeTD &= NewRetainRRI.KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00003063 for (SmallPtrSet<Instruction *, 2>::const_iterator
3064 LI = NewRetainRRI.Calls.begin(),
3065 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
3066 Instruction *NewRetainRelease = *LI;
3067 DenseMap<Value *, RRInfo>::const_iterator Jt =
3068 Releases.find(NewRetainRelease);
3069 if (Jt == Releases.end())
3070 goto next_retain;
3071 const RRInfo &NewRetainReleaseRRI = Jt->second;
3072 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
3073 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
3074 OldDelta -=
3075 BBStates[NewRetainRelease->getParent()].GetAllPathCount();
3076
3077 // Merge the ReleaseMetadata and IsTailCallRelease values.
3078 if (FirstRelease) {
3079 ReleasesToMove.ReleaseMetadata =
3080 NewRetainReleaseRRI.ReleaseMetadata;
3081 ReleasesToMove.IsTailCallRelease =
3082 NewRetainReleaseRRI.IsTailCallRelease;
3083 FirstRelease = false;
3084 } else {
3085 if (ReleasesToMove.ReleaseMetadata !=
3086 NewRetainReleaseRRI.ReleaseMetadata)
3087 ReleasesToMove.ReleaseMetadata = 0;
3088 if (ReleasesToMove.IsTailCallRelease !=
3089 NewRetainReleaseRRI.IsTailCallRelease)
3090 ReleasesToMove.IsTailCallRelease = false;
3091 }
3092
3093 // Collect the optimal insertion points.
3094 if (!KnownSafe)
3095 for (SmallPtrSet<Instruction *, 2>::const_iterator
3096 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
3097 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
3098 RI != RE; ++RI) {
3099 Instruction *RIP = *RI;
3100 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
3101 NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
3102 }
3103 NewReleases.push_back(NewRetainRelease);
3104 }
3105 }
3106 }
3107 NewRetains.clear();
3108 if (NewReleases.empty()) break;
3109
3110 // Back the other way.
3111 for (SmallVectorImpl<Instruction *>::const_iterator
3112 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
3113 Instruction *NewRelease = *NI;
3114 DenseMap<Value *, RRInfo>::const_iterator It =
3115 Releases.find(NewRelease);
3116 assert(It != Releases.end());
3117 const RRInfo &NewReleaseRRI = It->second;
Dan Gohmane6d5e882011-08-19 00:26:36 +00003118 KnownSafeBU &= NewReleaseRRI.KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00003119 for (SmallPtrSet<Instruction *, 2>::const_iterator
3120 LI = NewReleaseRRI.Calls.begin(),
3121 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
3122 Instruction *NewReleaseRetain = *LI;
3123 MapVector<Value *, RRInfo>::const_iterator Jt =
3124 Retains.find(NewReleaseRetain);
3125 if (Jt == Retains.end())
3126 goto next_retain;
3127 const RRInfo &NewReleaseRetainRRI = Jt->second;
3128 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
3129 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
3130 unsigned PathCount =
3131 BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
3132 OldDelta += PathCount;
3133 OldCount += PathCount;
3134
3135 // Merge the IsRetainBlock values.
3136 if (FirstRetain) {
3137 RetainsToMove.IsRetainBlock = NewReleaseRetainRRI.IsRetainBlock;
3138 FirstRetain = false;
3139 } else if (ReleasesToMove.IsRetainBlock !=
3140 NewReleaseRetainRRI.IsRetainBlock)
3141 // It's not possible to merge the sequences if one uses
3142 // objc_retain and the other uses objc_retainBlock.
3143 goto next_retain;
3144
3145 // Collect the optimal insertion points.
3146 if (!KnownSafe)
3147 for (SmallPtrSet<Instruction *, 2>::const_iterator
3148 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
3149 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
3150 RI != RE; ++RI) {
3151 Instruction *RIP = *RI;
3152 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
3153 PathCount = BBStates[RIP->getParent()].GetAllPathCount();
3154 NewDelta += PathCount;
3155 NewCount += PathCount;
3156 }
3157 }
3158 NewRetains.push_back(NewReleaseRetain);
3159 }
3160 }
3161 }
3162 NewReleases.clear();
3163 if (NewRetains.empty()) break;
3164 }
3165
Dan Gohmane6d5e882011-08-19 00:26:36 +00003166 // If the pointer is known incremented or nested, we can safely delete the
3167 // pair regardless of what's between them.
3168 if (KnownSafeTD || KnownSafeBU) {
John McCall9fbd3182011-06-15 23:37:01 +00003169 RetainsToMove.ReverseInsertPts.clear();
3170 ReleasesToMove.ReverseInsertPts.clear();
3171 NewCount = 0;
Dan Gohmana7f7db22011-08-12 00:26:31 +00003172 } else {
3173 // Determine whether the new insertion points we computed preserve the
3174 // balance of retain and release calls through the program.
3175 // TODO: If the fully aggressive solution isn't valid, try to find a
3176 // less aggressive solution which is.
3177 if (NewDelta != 0)
3178 goto next_retain;
John McCall9fbd3182011-06-15 23:37:01 +00003179 }
3180
3181 // Determine whether the original call points are balanced in the retain and
3182 // release calls through the program. If not, conservatively don't touch
3183 // them.
3184 // TODO: It's theoretically possible to do code motion in this case, as
3185 // long as the existing imbalances are maintained.
3186 if (OldDelta != 0)
3187 goto next_retain;
3188
John McCall9fbd3182011-06-15 23:37:01 +00003189 // Ok, everything checks out and we're all set. Let's move some code!
3190 Changed = true;
3191 AnyPairsCompletelyEliminated = NewCount == 0;
3192 NumRRs += OldCount - NewCount;
Dan Gohman44280692011-07-22 22:29:21 +00003193 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
3194 Retains, Releases, DeadInsts, M);
John McCall9fbd3182011-06-15 23:37:01 +00003195
3196 next_retain:
3197 NewReleases.clear();
3198 NewRetains.clear();
3199 RetainsToMove.clear();
3200 ReleasesToMove.clear();
3201 }
3202
3203 // Now that we're done moving everything, we can delete the newly dead
3204 // instructions, as we no longer need them as insert points.
3205 while (!DeadInsts.empty())
3206 EraseInstruction(DeadInsts.pop_back_val());
3207
3208 return AnyPairsCompletelyEliminated;
3209}
3210
3211/// OptimizeWeakCalls - Weak pointer optimizations.
3212void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
3213 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
3214 // itself because it uses AliasAnalysis and we need to do provenance
3215 // queries instead.
3216 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3217 Instruction *Inst = &*I++;
3218 InstructionClass Class = GetBasicInstructionClass(Inst);
3219 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
3220 continue;
3221
3222 // Delete objc_loadWeak calls with no users.
3223 if (Class == IC_LoadWeak && Inst->use_empty()) {
3224 Inst->eraseFromParent();
3225 continue;
3226 }
3227
3228 // TODO: For now, just look for an earlier available version of this value
3229 // within the same block. Theoretically, we could do memdep-style non-local
3230 // analysis too, but that would want caching. A better approach would be to
3231 // use the technique that EarlyCSE uses.
3232 inst_iterator Current = llvm::prior(I);
3233 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
3234 for (BasicBlock::iterator B = CurrentBB->begin(),
3235 J = Current.getInstructionIterator();
3236 J != B; --J) {
3237 Instruction *EarlierInst = &*llvm::prior(J);
3238 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
3239 switch (EarlierClass) {
3240 case IC_LoadWeak:
3241 case IC_LoadWeakRetained: {
3242 // If this is loading from the same pointer, replace this load's value
3243 // with that one.
3244 CallInst *Call = cast<CallInst>(Inst);
3245 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3246 Value *Arg = Call->getArgOperand(0);
3247 Value *EarlierArg = EarlierCall->getArgOperand(0);
3248 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3249 case AliasAnalysis::MustAlias:
3250 Changed = true;
3251 // If the load has a builtin retain, insert a plain retain for it.
3252 if (Class == IC_LoadWeakRetained) {
3253 CallInst *CI =
3254 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3255 "", Call);
3256 CI->setTailCall();
3257 }
3258 // Zap the fully redundant load.
3259 Call->replaceAllUsesWith(EarlierCall);
3260 Call->eraseFromParent();
3261 goto clobbered;
3262 case AliasAnalysis::MayAlias:
3263 case AliasAnalysis::PartialAlias:
3264 goto clobbered;
3265 case AliasAnalysis::NoAlias:
3266 break;
3267 }
3268 break;
3269 }
3270 case IC_StoreWeak:
3271 case IC_InitWeak: {
3272 // If this is storing to the same pointer and has the same size etc.
3273 // replace this load's value with the stored value.
3274 CallInst *Call = cast<CallInst>(Inst);
3275 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3276 Value *Arg = Call->getArgOperand(0);
3277 Value *EarlierArg = EarlierCall->getArgOperand(0);
3278 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3279 case AliasAnalysis::MustAlias:
3280 Changed = true;
3281 // If the load has a builtin retain, insert a plain retain for it.
3282 if (Class == IC_LoadWeakRetained) {
3283 CallInst *CI =
3284 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3285 "", Call);
3286 CI->setTailCall();
3287 }
3288 // Zap the fully redundant load.
3289 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
3290 Call->eraseFromParent();
3291 goto clobbered;
3292 case AliasAnalysis::MayAlias:
3293 case AliasAnalysis::PartialAlias:
3294 goto clobbered;
3295 case AliasAnalysis::NoAlias:
3296 break;
3297 }
3298 break;
3299 }
3300 case IC_MoveWeak:
3301 case IC_CopyWeak:
3302 // TOOD: Grab the copied value.
3303 goto clobbered;
3304 case IC_AutoreleasepoolPush:
3305 case IC_None:
3306 case IC_User:
3307 // Weak pointers are only modified through the weak entry points
3308 // (and arbitrary calls, which could call the weak entry points).
3309 break;
3310 default:
3311 // Anything else could modify the weak pointer.
3312 goto clobbered;
3313 }
3314 }
3315 clobbered:;
3316 }
3317
3318 // Then, for each destroyWeak with an alloca operand, check to see if
3319 // the alloca and all its users can be zapped.
3320 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3321 Instruction *Inst = &*I++;
3322 InstructionClass Class = GetBasicInstructionClass(Inst);
3323 if (Class != IC_DestroyWeak)
3324 continue;
3325
3326 CallInst *Call = cast<CallInst>(Inst);
3327 Value *Arg = Call->getArgOperand(0);
3328 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
3329 for (Value::use_iterator UI = Alloca->use_begin(),
3330 UE = Alloca->use_end(); UI != UE; ++UI) {
3331 Instruction *UserInst = cast<Instruction>(*UI);
3332 switch (GetBasicInstructionClass(UserInst)) {
3333 case IC_InitWeak:
3334 case IC_StoreWeak:
3335 case IC_DestroyWeak:
3336 continue;
3337 default:
3338 goto done;
3339 }
3340 }
3341 Changed = true;
3342 for (Value::use_iterator UI = Alloca->use_begin(),
3343 UE = Alloca->use_end(); UI != UE; ) {
3344 CallInst *UserInst = cast<CallInst>(*UI++);
3345 if (!UserInst->use_empty())
Dan Gohman8a9eebe2011-12-12 18:19:12 +00003346 UserInst->replaceAllUsesWith(UserInst->getArgOperand(0));
John McCall9fbd3182011-06-15 23:37:01 +00003347 UserInst->eraseFromParent();
3348 }
3349 Alloca->eraseFromParent();
3350 done:;
3351 }
3352 }
3353}
3354
3355/// OptimizeSequences - Identify program paths which execute sequences of
3356/// retains and releases which can be eliminated.
3357bool ObjCARCOpt::OptimizeSequences(Function &F) {
3358 /// Releases, Retains - These are used to store the results of the main flow
3359 /// analysis. These use Value* as the key instead of Instruction* so that the
3360 /// map stays valid when we get around to rewriting code and calls get
3361 /// replaced by arguments.
3362 DenseMap<Value *, RRInfo> Releases;
3363 MapVector<Value *, RRInfo> Retains;
3364
3365 /// BBStates, This is used during the traversal of the function to track the
3366 /// states for each identified object at each block.
3367 DenseMap<const BasicBlock *, BBState> BBStates;
3368
3369 // Analyze the CFG of the function, and all instructions.
3370 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
3371
3372 // Transform.
Dan Gohman44280692011-07-22 22:29:21 +00003373 return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) &&
3374 NestingDetected;
John McCall9fbd3182011-06-15 23:37:01 +00003375}
3376
3377/// OptimizeReturns - Look for this pattern:
3378///
3379/// %call = call i8* @something(...)
3380/// %2 = call i8* @objc_retain(i8* %call)
3381/// %3 = call i8* @objc_autorelease(i8* %2)
3382/// ret i8* %3
3383///
3384/// And delete the retain and autorelease.
3385///
3386/// Otherwise if it's just this:
3387///
3388/// %3 = call i8* @objc_autorelease(i8* %2)
3389/// ret i8* %3
3390///
3391/// convert the autorelease to autoreleaseRV.
3392void ObjCARCOpt::OptimizeReturns(Function &F) {
3393 if (!F.getReturnType()->isPointerTy())
3394 return;
3395
3396 SmallPtrSet<Instruction *, 4> DependingInstructions;
3397 SmallPtrSet<const BasicBlock *, 4> Visited;
3398 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3399 BasicBlock *BB = FI;
3400 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
3401 if (!Ret) continue;
3402
3403 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
3404 FindDependencies(NeedsPositiveRetainCount, Arg,
3405 BB, Ret, DependingInstructions, Visited, PA);
3406 if (DependingInstructions.size() != 1)
3407 goto next_block;
3408
3409 {
3410 CallInst *Autorelease =
3411 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3412 if (!Autorelease)
3413 goto next_block;
3414 InstructionClass AutoreleaseClass =
3415 GetBasicInstructionClass(Autorelease);
3416 if (!IsAutorelease(AutoreleaseClass))
3417 goto next_block;
3418 if (GetObjCArg(Autorelease) != Arg)
3419 goto next_block;
3420
3421 DependingInstructions.clear();
3422 Visited.clear();
3423
3424 // Check that there is nothing that can affect the reference
3425 // count between the autorelease and the retain.
3426 FindDependencies(CanChangeRetainCount, Arg,
3427 BB, Autorelease, DependingInstructions, Visited, PA);
3428 if (DependingInstructions.size() != 1)
3429 goto next_block;
3430
3431 {
3432 CallInst *Retain =
3433 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3434
3435 // Check that we found a retain with the same argument.
3436 if (!Retain ||
3437 !IsRetain(GetBasicInstructionClass(Retain)) ||
3438 GetObjCArg(Retain) != Arg)
3439 goto next_block;
3440
3441 DependingInstructions.clear();
3442 Visited.clear();
3443
3444 // Convert the autorelease to an autoreleaseRV, since it's
3445 // returning the value.
3446 if (AutoreleaseClass == IC_Autorelease) {
3447 Autorelease->setCalledFunction(getAutoreleaseRVCallee(F.getParent()));
3448 AutoreleaseClass = IC_AutoreleaseRV;
3449 }
3450
3451 // Check that there is nothing that can affect the reference
3452 // count between the retain and the call.
Dan Gohman27e06662011-09-29 22:27:34 +00003453 // Note that Retain need not be in BB.
3454 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
John McCall9fbd3182011-06-15 23:37:01 +00003455 DependingInstructions, Visited, PA);
3456 if (DependingInstructions.size() != 1)
3457 goto next_block;
3458
3459 {
3460 CallInst *Call =
3461 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3462
3463 // Check that the pointer is the return value of the call.
3464 if (!Call || Arg != Call)
3465 goto next_block;
3466
3467 // Check that the call is a regular call.
3468 InstructionClass Class = GetBasicInstructionClass(Call);
3469 if (Class != IC_CallOrUser && Class != IC_Call)
3470 goto next_block;
3471
3472 // If so, we can zap the retain and autorelease.
3473 Changed = true;
3474 ++NumRets;
3475 EraseInstruction(Retain);
3476 EraseInstruction(Autorelease);
3477 }
3478 }
3479 }
3480
3481 next_block:
3482 DependingInstructions.clear();
3483 Visited.clear();
3484 }
3485}
3486
3487bool ObjCARCOpt::doInitialization(Module &M) {
3488 if (!EnableARCOpts)
3489 return false;
3490
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003491 Run = ModuleHasARC(M);
3492 if (!Run)
3493 return false;
3494
John McCall9fbd3182011-06-15 23:37:01 +00003495 // Identify the imprecise release metadata kind.
3496 ImpreciseReleaseMDKind =
3497 M.getContext().getMDKindID("clang.imprecise_release");
Dan Gohmana974bea2011-10-17 22:53:25 +00003498 CopyOnEscapeMDKind =
3499 M.getContext().getMDKindID("clang.arc.copy_on_escape");
John McCall9fbd3182011-06-15 23:37:01 +00003500
John McCall9fbd3182011-06-15 23:37:01 +00003501 // Intuitively, objc_retain and others are nocapture, however in practice
3502 // they are not, because they return their argument value. And objc_release
3503 // calls finalizers.
3504
3505 // These are initialized lazily.
3506 RetainRVCallee = 0;
3507 AutoreleaseRVCallee = 0;
3508 ReleaseCallee = 0;
3509 RetainCallee = 0;
Dan Gohman44280692011-07-22 22:29:21 +00003510 RetainBlockCallee = 0;
John McCall9fbd3182011-06-15 23:37:01 +00003511 AutoreleaseCallee = 0;
3512
3513 return false;
3514}
3515
3516bool ObjCARCOpt::runOnFunction(Function &F) {
3517 if (!EnableARCOpts)
3518 return false;
3519
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003520 // If nothing in the Module uses ARC, don't do anything.
3521 if (!Run)
3522 return false;
3523
John McCall9fbd3182011-06-15 23:37:01 +00003524 Changed = false;
3525
3526 PA.setAA(&getAnalysis<AliasAnalysis>());
3527
3528 // This pass performs several distinct transformations. As a compile-time aid
3529 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3530 // library functions aren't declared.
3531
3532 // Preliminary optimizations. This also computs UsedInThisFunction.
3533 OptimizeIndividualCalls(F);
3534
3535 // Optimizations for weak pointers.
3536 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3537 (1 << IC_LoadWeakRetained) |
3538 (1 << IC_StoreWeak) |
3539 (1 << IC_InitWeak) |
3540 (1 << IC_CopyWeak) |
3541 (1 << IC_MoveWeak) |
3542 (1 << IC_DestroyWeak)))
3543 OptimizeWeakCalls(F);
3544
3545 // Optimizations for retain+release pairs.
3546 if (UsedInThisFunction & ((1 << IC_Retain) |
3547 (1 << IC_RetainRV) |
3548 (1 << IC_RetainBlock)))
3549 if (UsedInThisFunction & (1 << IC_Release))
3550 // Run OptimizeSequences until it either stops making changes or
3551 // no retain+release pair nesting is detected.
3552 while (OptimizeSequences(F)) {}
3553
3554 // Optimizations if objc_autorelease is used.
3555 if (UsedInThisFunction &
3556 ((1 << IC_Autorelease) | (1 << IC_AutoreleaseRV)))
3557 OptimizeReturns(F);
3558
3559 return Changed;
3560}
3561
3562void ObjCARCOpt::releaseMemory() {
3563 PA.clear();
3564}
3565
3566//===----------------------------------------------------------------------===//
3567// ARC contraction.
3568//===----------------------------------------------------------------------===//
3569
3570// TODO: ObjCARCContract could insert PHI nodes when uses aren't
3571// dominated by single calls.
3572
3573#include "llvm/Operator.h"
3574#include "llvm/InlineAsm.h"
3575#include "llvm/Analysis/Dominators.h"
3576
3577STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed");
3578
3579namespace {
3580 /// ObjCARCContract - Late ARC optimizations. These change the IR in a way
3581 /// that makes it difficult to be analyzed by ObjCARCOpt, so it's run late.
3582 class ObjCARCContract : public FunctionPass {
3583 bool Changed;
3584 AliasAnalysis *AA;
3585 DominatorTree *DT;
3586 ProvenanceAnalysis PA;
3587
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003588 /// Run - A flag indicating whether this optimization pass should run.
3589 bool Run;
3590
John McCall9fbd3182011-06-15 23:37:01 +00003591 /// StoreStrongCallee, etc. - Declarations for ObjC runtime
3592 /// functions, for use in creating calls to them. These are initialized
3593 /// lazily to avoid cluttering up the Module with unused declarations.
3594 Constant *StoreStrongCallee,
3595 *RetainAutoreleaseCallee, *RetainAutoreleaseRVCallee;
3596
3597 /// RetainRVMarker - The inline asm string to insert between calls and
3598 /// RetainRV calls to make the optimization work on targets which need it.
3599 const MDString *RetainRVMarker;
3600
Dan Gohman0cdece42012-01-19 19:14:36 +00003601 /// StoreStrongCalls - The set of inserted objc_storeStrong calls. If
3602 /// at the end of walking the function we have found no alloca
3603 /// instructions, these calls can be marked "tail".
3604 DenseSet<CallInst *> StoreStrongCalls;
3605
John McCall9fbd3182011-06-15 23:37:01 +00003606 Constant *getStoreStrongCallee(Module *M);
3607 Constant *getRetainAutoreleaseCallee(Module *M);
3608 Constant *getRetainAutoreleaseRVCallee(Module *M);
3609
3610 bool ContractAutorelease(Function &F, Instruction *Autorelease,
3611 InstructionClass Class,
3612 SmallPtrSet<Instruction *, 4>
3613 &DependingInstructions,
3614 SmallPtrSet<const BasicBlock *, 4>
3615 &Visited);
3616
3617 void ContractRelease(Instruction *Release,
3618 inst_iterator &Iter);
3619
3620 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
3621 virtual bool doInitialization(Module &M);
3622 virtual bool runOnFunction(Function &F);
3623
3624 public:
3625 static char ID;
3626 ObjCARCContract() : FunctionPass(ID) {
3627 initializeObjCARCContractPass(*PassRegistry::getPassRegistry());
3628 }
3629 };
3630}
3631
3632char ObjCARCContract::ID = 0;
3633INITIALIZE_PASS_BEGIN(ObjCARCContract,
3634 "objc-arc-contract", "ObjC ARC contraction", false, false)
3635INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3636INITIALIZE_PASS_DEPENDENCY(DominatorTree)
3637INITIALIZE_PASS_END(ObjCARCContract,
3638 "objc-arc-contract", "ObjC ARC contraction", false, false)
3639
3640Pass *llvm::createObjCARCContractPass() {
3641 return new ObjCARCContract();
3642}
3643
3644void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const {
3645 AU.addRequired<AliasAnalysis>();
3646 AU.addRequired<DominatorTree>();
3647 AU.setPreservesCFG();
3648}
3649
3650Constant *ObjCARCContract::getStoreStrongCallee(Module *M) {
3651 if (!StoreStrongCallee) {
3652 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00003653 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3654 Type *I8XX = PointerType::getUnqual(I8X);
3655 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00003656 Params.push_back(I8XX);
3657 Params.push_back(I8X);
3658
3659 AttrListPtr Attributes;
3660 Attributes.addAttr(~0u, Attribute::NoUnwind);
3661 Attributes.addAttr(1, Attribute::NoCapture);
3662
3663 StoreStrongCallee =
3664 M->getOrInsertFunction(
3665 "objc_storeStrong",
3666 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
3667 Attributes);
3668 }
3669 return StoreStrongCallee;
3670}
3671
3672Constant *ObjCARCContract::getRetainAutoreleaseCallee(Module *M) {
3673 if (!RetainAutoreleaseCallee) {
3674 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00003675 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3676 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00003677 Params.push_back(I8X);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003678 FunctionType *FTy =
John McCall9fbd3182011-06-15 23:37:01 +00003679 FunctionType::get(I8X, Params, /*isVarArg=*/false);
3680 AttrListPtr Attributes;
3681 Attributes.addAttr(~0u, Attribute::NoUnwind);
3682 RetainAutoreleaseCallee =
3683 M->getOrInsertFunction("objc_retainAutorelease", FTy, Attributes);
3684 }
3685 return RetainAutoreleaseCallee;
3686}
3687
3688Constant *ObjCARCContract::getRetainAutoreleaseRVCallee(Module *M) {
3689 if (!RetainAutoreleaseRVCallee) {
3690 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00003691 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3692 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00003693 Params.push_back(I8X);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003694 FunctionType *FTy =
John McCall9fbd3182011-06-15 23:37:01 +00003695 FunctionType::get(I8X, Params, /*isVarArg=*/false);
3696 AttrListPtr Attributes;
3697 Attributes.addAttr(~0u, Attribute::NoUnwind);
3698 RetainAutoreleaseRVCallee =
3699 M->getOrInsertFunction("objc_retainAutoreleaseReturnValue", FTy,
3700 Attributes);
3701 }
3702 return RetainAutoreleaseRVCallee;
3703}
3704
3705/// ContractAutorelease - Merge an autorelease with a retain into a fused
3706/// call.
3707bool
3708ObjCARCContract::ContractAutorelease(Function &F, Instruction *Autorelease,
3709 InstructionClass Class,
3710 SmallPtrSet<Instruction *, 4>
3711 &DependingInstructions,
3712 SmallPtrSet<const BasicBlock *, 4>
3713 &Visited) {
3714 const Value *Arg = GetObjCArg(Autorelease);
3715
3716 // Check that there are no instructions between the retain and the autorelease
3717 // (such as an autorelease_pop) which may change the count.
3718 CallInst *Retain = 0;
3719 if (Class == IC_AutoreleaseRV)
3720 FindDependencies(RetainAutoreleaseRVDep, Arg,
3721 Autorelease->getParent(), Autorelease,
3722 DependingInstructions, Visited, PA);
3723 else
3724 FindDependencies(RetainAutoreleaseDep, Arg,
3725 Autorelease->getParent(), Autorelease,
3726 DependingInstructions, Visited, PA);
3727
3728 Visited.clear();
3729 if (DependingInstructions.size() != 1) {
3730 DependingInstructions.clear();
3731 return false;
3732 }
3733
3734 Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3735 DependingInstructions.clear();
3736
3737 if (!Retain ||
3738 GetBasicInstructionClass(Retain) != IC_Retain ||
3739 GetObjCArg(Retain) != Arg)
3740 return false;
3741
3742 Changed = true;
3743 ++NumPeeps;
3744
3745 if (Class == IC_AutoreleaseRV)
3746 Retain->setCalledFunction(getRetainAutoreleaseRVCallee(F.getParent()));
3747 else
3748 Retain->setCalledFunction(getRetainAutoreleaseCallee(F.getParent()));
3749
3750 EraseInstruction(Autorelease);
3751 return true;
3752}
3753
3754/// ContractRelease - Attempt to merge an objc_release with a store, load, and
3755/// objc_retain to form an objc_storeStrong. This can be a little tricky because
3756/// the instructions don't always appear in order, and there may be unrelated
3757/// intervening instructions.
3758void ObjCARCContract::ContractRelease(Instruction *Release,
3759 inst_iterator &Iter) {
3760 LoadInst *Load = dyn_cast<LoadInst>(GetObjCArg(Release));
Eli Friedman2bc3d522011-09-12 20:23:13 +00003761 if (!Load || !Load->isSimple()) return;
John McCall9fbd3182011-06-15 23:37:01 +00003762
3763 // For now, require everything to be in one basic block.
3764 BasicBlock *BB = Release->getParent();
3765 if (Load->getParent() != BB) return;
3766
3767 // Walk down to find the store.
3768 BasicBlock::iterator I = Load, End = BB->end();
3769 ++I;
3770 AliasAnalysis::Location Loc = AA->getLocation(Load);
3771 while (I != End &&
3772 (&*I == Release ||
3773 IsRetain(GetBasicInstructionClass(I)) ||
3774 !(AA->getModRefInfo(I, Loc) & AliasAnalysis::Mod)))
3775 ++I;
3776 StoreInst *Store = dyn_cast<StoreInst>(I);
Eli Friedman2bc3d522011-09-12 20:23:13 +00003777 if (!Store || !Store->isSimple()) return;
John McCall9fbd3182011-06-15 23:37:01 +00003778 if (Store->getPointerOperand() != Loc.Ptr) return;
3779
3780 Value *New = StripPointerCastsAndObjCCalls(Store->getValueOperand());
3781
3782 // Walk up to find the retain.
3783 I = Store;
3784 BasicBlock::iterator Begin = BB->begin();
3785 while (I != Begin && GetBasicInstructionClass(I) != IC_Retain)
3786 --I;
3787 Instruction *Retain = I;
3788 if (GetBasicInstructionClass(Retain) != IC_Retain) return;
3789 if (GetObjCArg(Retain) != New) return;
3790
3791 Changed = true;
3792 ++NumStoreStrongs;
3793
3794 LLVMContext &C = Release->getContext();
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003795 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3796 Type *I8XX = PointerType::getUnqual(I8X);
John McCall9fbd3182011-06-15 23:37:01 +00003797
3798 Value *Args[] = { Load->getPointerOperand(), New };
3799 if (Args[0]->getType() != I8XX)
3800 Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
3801 if (Args[1]->getType() != I8X)
3802 Args[1] = new BitCastInst(Args[1], I8X, "", Store);
3803 CallInst *StoreStrong =
3804 CallInst::Create(getStoreStrongCallee(BB->getParent()->getParent()),
Jay Foada3efbb12011-07-15 08:37:34 +00003805 Args, "", Store);
John McCall9fbd3182011-06-15 23:37:01 +00003806 StoreStrong->setDoesNotThrow();
3807 StoreStrong->setDebugLoc(Store->getDebugLoc());
3808
Dan Gohman0cdece42012-01-19 19:14:36 +00003809 // We can't set the tail flag yet, because we haven't yet determined
3810 // whether there are any escaping allocas. Remember this call, so that
3811 // we can set the tail flag once we know it's safe.
3812 StoreStrongCalls.insert(StoreStrong);
3813
John McCall9fbd3182011-06-15 23:37:01 +00003814 if (&*Iter == Store) ++Iter;
3815 Store->eraseFromParent();
3816 Release->eraseFromParent();
3817 EraseInstruction(Retain);
3818 if (Load->use_empty())
3819 Load->eraseFromParent();
3820}
3821
3822bool ObjCARCContract::doInitialization(Module &M) {
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003823 Run = ModuleHasARC(M);
3824 if (!Run)
3825 return false;
3826
John McCall9fbd3182011-06-15 23:37:01 +00003827 // These are initialized lazily.
3828 StoreStrongCallee = 0;
3829 RetainAutoreleaseCallee = 0;
3830 RetainAutoreleaseRVCallee = 0;
3831
3832 // Initialize RetainRVMarker.
3833 RetainRVMarker = 0;
3834 if (NamedMDNode *NMD =
3835 M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker"))
3836 if (NMD->getNumOperands() == 1) {
3837 const MDNode *N = NMD->getOperand(0);
3838 if (N->getNumOperands() == 1)
3839 if (const MDString *S = dyn_cast<MDString>(N->getOperand(0)))
3840 RetainRVMarker = S;
3841 }
3842
3843 return false;
3844}
3845
3846bool ObjCARCContract::runOnFunction(Function &F) {
3847 if (!EnableARCOpts)
3848 return false;
3849
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003850 // If nothing in the Module uses ARC, don't do anything.
3851 if (!Run)
3852 return false;
3853
John McCall9fbd3182011-06-15 23:37:01 +00003854 Changed = false;
3855 AA = &getAnalysis<AliasAnalysis>();
3856 DT = &getAnalysis<DominatorTree>();
3857
3858 PA.setAA(&getAnalysis<AliasAnalysis>());
3859
Dan Gohman0cdece42012-01-19 19:14:36 +00003860 // Track whether it's ok to mark objc_storeStrong calls with the "tail"
3861 // keyword. Be conservative if the function has variadic arguments.
3862 // It seems that functions which "return twice" are also unsafe for the
3863 // "tail" argument, because they are setjmp, which could need to
3864 // return to an earlier stack state.
3865 bool TailOkForStoreStrongs = !F.isVarArg() && !F.callsFunctionThatReturnsTwice();
3866
John McCall9fbd3182011-06-15 23:37:01 +00003867 // For ObjC library calls which return their argument, replace uses of the
3868 // argument with uses of the call return value, if it dominates the use. This
3869 // reduces register pressure.
3870 SmallPtrSet<Instruction *, 4> DependingInstructions;
3871 SmallPtrSet<const BasicBlock *, 4> Visited;
3872 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3873 Instruction *Inst = &*I++;
3874
3875 // Only these library routines return their argument. In particular,
3876 // objc_retainBlock does not necessarily return its argument.
3877 InstructionClass Class = GetBasicInstructionClass(Inst);
3878 switch (Class) {
3879 case IC_Retain:
3880 case IC_FusedRetainAutorelease:
3881 case IC_FusedRetainAutoreleaseRV:
3882 break;
3883 case IC_Autorelease:
3884 case IC_AutoreleaseRV:
3885 if (ContractAutorelease(F, Inst, Class, DependingInstructions, Visited))
3886 continue;
3887 break;
3888 case IC_RetainRV: {
3889 // If we're compiling for a target which needs a special inline-asm
3890 // marker to do the retainAutoreleasedReturnValue optimization,
3891 // insert it now.
3892 if (!RetainRVMarker)
3893 break;
3894 BasicBlock::iterator BBI = Inst;
3895 --BBI;
3896 while (isNoopInstruction(BBI)) --BBI;
3897 if (&*BBI == GetObjCArg(Inst)) {
3898 InlineAsm *IA =
3899 InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()),
3900 /*isVarArg=*/false),
3901 RetainRVMarker->getString(),
3902 /*Constraints=*/"", /*hasSideEffects=*/true);
3903 CallInst::Create(IA, "", Inst);
3904 }
3905 break;
3906 }
3907 case IC_InitWeak: {
3908 // objc_initWeak(p, null) => *p = null
3909 CallInst *CI = cast<CallInst>(Inst);
3910 if (isNullOrUndef(CI->getArgOperand(1))) {
3911 Value *Null =
3912 ConstantPointerNull::get(cast<PointerType>(CI->getType()));
3913 Changed = true;
3914 new StoreInst(Null, CI->getArgOperand(0), CI);
3915 CI->replaceAllUsesWith(Null);
3916 CI->eraseFromParent();
3917 }
3918 continue;
3919 }
3920 case IC_Release:
3921 ContractRelease(Inst, I);
3922 continue;
Dan Gohman0cdece42012-01-19 19:14:36 +00003923 case IC_User:
3924 // Be conservative if the function has any alloca instructions.
3925 // Technically we only care about escaping alloca instructions,
3926 // but this is sufficient to handle some interesting cases.
3927 if (isa<AllocaInst>(Inst))
3928 TailOkForStoreStrongs = false;
3929 continue;
John McCall9fbd3182011-06-15 23:37:01 +00003930 default:
3931 continue;
3932 }
3933
3934 // Don't use GetObjCArg because we don't want to look through bitcasts
3935 // and such; to do the replacement, the argument must have type i8*.
3936 const Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
3937 for (;;) {
3938 // If we're compiling bugpointed code, don't get in trouble.
3939 if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
3940 break;
3941 // Look through the uses of the pointer.
3942 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
3943 UI != UE; ) {
3944 Use &U = UI.getUse();
3945 unsigned OperandNo = UI.getOperandNo();
3946 ++UI; // Increment UI now, because we may unlink its element.
3947 if (Instruction *UserInst = dyn_cast<Instruction>(U.getUser()))
3948 if (Inst != UserInst && DT->dominates(Inst, UserInst)) {
3949 Changed = true;
3950 Instruction *Replacement = Inst;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003951 Type *UseTy = U.get()->getType();
John McCall9fbd3182011-06-15 23:37:01 +00003952 if (PHINode *PHI = dyn_cast<PHINode>(UserInst)) {
3953 // For PHI nodes, insert the bitcast in the predecessor block.
3954 unsigned ValNo =
3955 PHINode::getIncomingValueNumForOperand(OperandNo);
3956 BasicBlock *BB =
3957 PHI->getIncomingBlock(ValNo);
3958 if (Replacement->getType() != UseTy)
3959 Replacement = new BitCastInst(Replacement, UseTy, "",
3960 &BB->back());
3961 for (unsigned i = 0, e = PHI->getNumIncomingValues();
3962 i != e; ++i)
3963 if (PHI->getIncomingBlock(i) == BB) {
3964 // Keep the UI iterator valid.
3965 if (&PHI->getOperandUse(
3966 PHINode::getOperandNumForIncomingValue(i)) ==
3967 &UI.getUse())
3968 ++UI;
3969 PHI->setIncomingValue(i, Replacement);
3970 }
3971 } else {
3972 if (Replacement->getType() != UseTy)
3973 Replacement = new BitCastInst(Replacement, UseTy, "", UserInst);
3974 U.set(Replacement);
3975 }
3976 }
3977 }
3978
3979 // If Arg is a no-op casted pointer, strip one level of casts and
3980 // iterate.
3981 if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
3982 Arg = BI->getOperand(0);
3983 else if (isa<GEPOperator>(Arg) &&
3984 cast<GEPOperator>(Arg)->hasAllZeroIndices())
3985 Arg = cast<GEPOperator>(Arg)->getPointerOperand();
3986 else if (isa<GlobalAlias>(Arg) &&
3987 !cast<GlobalAlias>(Arg)->mayBeOverridden())
3988 Arg = cast<GlobalAlias>(Arg)->getAliasee();
3989 else
3990 break;
3991 }
3992 }
3993
Dan Gohman0cdece42012-01-19 19:14:36 +00003994 // If this function has no escaping allocas or suspicious vararg usage,
3995 // objc_storeStrong calls can be marked with the "tail" keyword.
3996 if (TailOkForStoreStrongs)
3997 for (DenseSet<CallInst *>::iterator I = StoreStrongCalls.begin(),
3998 E = StoreStrongCalls.end(); I != E; ++I)
3999 (*I)->setTailCall();
4000 StoreStrongCalls.clear();
4001
John McCall9fbd3182011-06-15 23:37:01 +00004002 return Changed;
4003}