blob: 4e068d51c8e887bb1601772f7d998d69f12f3643 [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;
182 // Only consider values with pointer types, and not function pointers.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000183 PointerType *Ty = dyn_cast<PointerType>(Op->getType());
John McCall9fbd3182011-06-15 23:37:01 +0000184 if (!Ty || isa<FunctionType>(Ty->getElementType()))
185 return false;
186 // Conservatively assume anything else is a potential use.
187 return true;
188}
189
190/// GetCallSiteClass - Helper for GetInstructionClass. Determines what kind
191/// of construct CS is.
192static InstructionClass GetCallSiteClass(ImmutableCallSite CS) {
193 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
194 I != E; ++I)
195 if (IsPotentialUse(*I))
196 return CS.onlyReadsMemory() ? IC_User : IC_CallOrUser;
197
198 return CS.onlyReadsMemory() ? IC_None : IC_Call;
199}
200
201/// GetFunctionClass - Determine if F is one of the special known Functions.
202/// If it isn't, return IC_CallOrUser.
203static InstructionClass GetFunctionClass(const Function *F) {
204 Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
205
206 // No arguments.
207 if (AI == AE)
208 return StringSwitch<InstructionClass>(F->getName())
209 .Case("objc_autoreleasePoolPush", IC_AutoreleasepoolPush)
210 .Default(IC_CallOrUser);
211
212 // One argument.
213 const Argument *A0 = AI++;
214 if (AI == AE)
215 // Argument is a pointer.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000216 if (PointerType *PTy = dyn_cast<PointerType>(A0->getType())) {
217 Type *ETy = PTy->getElementType();
John McCall9fbd3182011-06-15 23:37:01 +0000218 // Argument is i8*.
219 if (ETy->isIntegerTy(8))
220 return StringSwitch<InstructionClass>(F->getName())
221 .Case("objc_retain", IC_Retain)
222 .Case("objc_retainAutoreleasedReturnValue", IC_RetainRV)
223 .Case("objc_retainBlock", IC_RetainBlock)
224 .Case("objc_release", IC_Release)
225 .Case("objc_autorelease", IC_Autorelease)
226 .Case("objc_autoreleaseReturnValue", IC_AutoreleaseRV)
227 .Case("objc_autoreleasePoolPop", IC_AutoreleasepoolPop)
228 .Case("objc_retainedObject", IC_NoopCast)
229 .Case("objc_unretainedObject", IC_NoopCast)
230 .Case("objc_unretainedPointer", IC_NoopCast)
231 .Case("objc_retain_autorelease", IC_FusedRetainAutorelease)
232 .Case("objc_retainAutorelease", IC_FusedRetainAutorelease)
233 .Case("objc_retainAutoreleaseReturnValue",IC_FusedRetainAutoreleaseRV)
234 .Default(IC_CallOrUser);
235
236 // Argument is i8**
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000237 if (PointerType *Pte = dyn_cast<PointerType>(ETy))
John McCall9fbd3182011-06-15 23:37:01 +0000238 if (Pte->getElementType()->isIntegerTy(8))
239 return StringSwitch<InstructionClass>(F->getName())
240 .Case("objc_loadWeakRetained", IC_LoadWeakRetained)
241 .Case("objc_loadWeak", IC_LoadWeak)
242 .Case("objc_destroyWeak", IC_DestroyWeak)
243 .Default(IC_CallOrUser);
244 }
245
246 // Two arguments, first is i8**.
247 const Argument *A1 = AI++;
248 if (AI == AE)
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000249 if (PointerType *PTy = dyn_cast<PointerType>(A0->getType()))
250 if (PointerType *Pte = dyn_cast<PointerType>(PTy->getElementType()))
John McCall9fbd3182011-06-15 23:37:01 +0000251 if (Pte->getElementType()->isIntegerTy(8))
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000252 if (PointerType *PTy1 = dyn_cast<PointerType>(A1->getType())) {
253 Type *ETy1 = PTy1->getElementType();
John McCall9fbd3182011-06-15 23:37:01 +0000254 // Second argument is i8*
255 if (ETy1->isIntegerTy(8))
256 return StringSwitch<InstructionClass>(F->getName())
257 .Case("objc_storeWeak", IC_StoreWeak)
258 .Case("objc_initWeak", IC_InitWeak)
259 .Default(IC_CallOrUser);
260 // Second argument is i8**.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000261 if (PointerType *Pte1 = dyn_cast<PointerType>(ETy1))
John McCall9fbd3182011-06-15 23:37:01 +0000262 if (Pte1->getElementType()->isIntegerTy(8))
263 return StringSwitch<InstructionClass>(F->getName())
264 .Case("objc_moveWeak", IC_MoveWeak)
265 .Case("objc_copyWeak", IC_CopyWeak)
266 .Default(IC_CallOrUser);
267 }
268
269 // Anything else.
270 return IC_CallOrUser;
271}
272
273/// GetInstructionClass - Determine what kind of construct V is.
274static InstructionClass GetInstructionClass(const Value *V) {
275 if (const Instruction *I = dyn_cast<Instruction>(V)) {
276 // Any instruction other than bitcast and gep with a pointer operand have a
277 // use of an objc pointer. Bitcasts, GEPs, Selects, PHIs transfer a pointer
278 // to a subsequent use, rather than using it themselves, in this sense.
279 // As a short cut, several other opcodes are known to have no pointer
280 // operands of interest. And ret is never followed by a release, so it's
281 // not interesting to examine.
282 switch (I->getOpcode()) {
283 case Instruction::Call: {
284 const CallInst *CI = cast<CallInst>(I);
285 // Check for calls to special functions.
286 if (const Function *F = CI->getCalledFunction()) {
287 InstructionClass Class = GetFunctionClass(F);
288 if (Class != IC_CallOrUser)
289 return Class;
290
291 // None of the intrinsic functions do objc_release. For intrinsics, the
292 // only question is whether or not they may be users.
293 switch (F->getIntrinsicID()) {
294 case 0: break;
295 case Intrinsic::bswap: case Intrinsic::ctpop:
296 case Intrinsic::ctlz: case Intrinsic::cttz:
297 case Intrinsic::returnaddress: case Intrinsic::frameaddress:
298 case Intrinsic::stacksave: case Intrinsic::stackrestore:
299 case Intrinsic::vastart: case Intrinsic::vacopy: case Intrinsic::vaend:
300 // Don't let dbg info affect our results.
301 case Intrinsic::dbg_declare: case Intrinsic::dbg_value:
302 // Short cut: Some intrinsics obviously don't use ObjC pointers.
303 return IC_None;
304 default:
305 for (Function::const_arg_iterator AI = F->arg_begin(),
306 AE = F->arg_end(); AI != AE; ++AI)
307 if (IsPotentialUse(AI))
308 return IC_User;
309 return IC_None;
310 }
311 }
312 return GetCallSiteClass(CI);
313 }
314 case Instruction::Invoke:
315 return GetCallSiteClass(cast<InvokeInst>(I));
316 case Instruction::BitCast:
317 case Instruction::GetElementPtr:
318 case Instruction::Select: case Instruction::PHI:
319 case Instruction::Ret: case Instruction::Br:
320 case Instruction::Switch: case Instruction::IndirectBr:
321 case Instruction::Alloca: case Instruction::VAArg:
322 case Instruction::Add: case Instruction::FAdd:
323 case Instruction::Sub: case Instruction::FSub:
324 case Instruction::Mul: case Instruction::FMul:
325 case Instruction::SDiv: case Instruction::UDiv: case Instruction::FDiv:
326 case Instruction::SRem: case Instruction::URem: case Instruction::FRem:
327 case Instruction::Shl: case Instruction::LShr: case Instruction::AShr:
328 case Instruction::And: case Instruction::Or: case Instruction::Xor:
329 case Instruction::SExt: case Instruction::ZExt: case Instruction::Trunc:
330 case Instruction::IntToPtr: case Instruction::FCmp:
331 case Instruction::FPTrunc: case Instruction::FPExt:
332 case Instruction::FPToUI: case Instruction::FPToSI:
333 case Instruction::UIToFP: case Instruction::SIToFP:
334 case Instruction::InsertElement: case Instruction::ExtractElement:
335 case Instruction::ShuffleVector:
336 case Instruction::ExtractValue:
337 break;
338 case Instruction::ICmp:
339 // Comparing a pointer with null, or any other constant, isn't an
340 // interesting use, because we don't care what the pointer points to, or
341 // about the values of any other dynamic reference-counted pointers.
342 if (IsPotentialUse(I->getOperand(1)))
343 return IC_User;
344 break;
345 default:
346 // For anything else, check all the operands.
Dan Gohmand4464602011-08-22 17:29:37 +0000347 // Note that this includes both operands of a Store: while the first
348 // operand isn't actually being dereferenced, it is being stored to
349 // memory where we can no longer track who might read it and dereference
350 // it, so we have to consider it potentially used.
John McCall9fbd3182011-06-15 23:37:01 +0000351 for (User::const_op_iterator OI = I->op_begin(), OE = I->op_end();
352 OI != OE; ++OI)
353 if (IsPotentialUse(*OI))
354 return IC_User;
355 }
356 }
357
358 // Otherwise, it's totally inert for ARC purposes.
359 return IC_None;
360}
361
362/// GetBasicInstructionClass - Determine what kind of construct V is. This is
363/// similar to GetInstructionClass except that it only detects objc runtine
364/// calls. This allows it to be faster.
365static InstructionClass GetBasicInstructionClass(const Value *V) {
366 if (const CallInst *CI = dyn_cast<CallInst>(V)) {
367 if (const Function *F = CI->getCalledFunction())
368 return GetFunctionClass(F);
369 // Otherwise, be conservative.
370 return IC_CallOrUser;
371 }
372
373 // Otherwise, be conservative.
374 return IC_User;
375}
376
377/// IsRetain - Test if the the given class is objc_retain or
378/// equivalent.
379static bool IsRetain(InstructionClass Class) {
380 return Class == IC_Retain ||
381 Class == IC_RetainRV;
382}
383
384/// IsAutorelease - Test if the the given class is objc_autorelease or
385/// equivalent.
386static bool IsAutorelease(InstructionClass Class) {
387 return Class == IC_Autorelease ||
388 Class == IC_AutoreleaseRV;
389}
390
391/// IsForwarding - Test if the given class represents instructions which return
392/// their argument verbatim.
393static bool IsForwarding(InstructionClass Class) {
394 // objc_retainBlock technically doesn't always return its argument
395 // verbatim, but it doesn't matter for our purposes here.
396 return Class == IC_Retain ||
397 Class == IC_RetainRV ||
398 Class == IC_Autorelease ||
399 Class == IC_AutoreleaseRV ||
400 Class == IC_RetainBlock ||
401 Class == IC_NoopCast;
402}
403
404/// IsNoopOnNull - Test if the given class represents instructions which do
405/// nothing if passed a null pointer.
406static bool IsNoopOnNull(InstructionClass Class) {
407 return Class == IC_Retain ||
408 Class == IC_RetainRV ||
409 Class == IC_Release ||
410 Class == IC_Autorelease ||
411 Class == IC_AutoreleaseRV ||
412 Class == IC_RetainBlock;
413}
414
415/// IsAlwaysTail - Test if the given class represents instructions which are
416/// always safe to mark with the "tail" keyword.
417static bool IsAlwaysTail(InstructionClass Class) {
418 // IC_RetainBlock may be given a stack argument.
419 return Class == IC_Retain ||
420 Class == IC_RetainRV ||
421 Class == IC_Autorelease ||
422 Class == IC_AutoreleaseRV;
423}
424
425/// IsNoThrow - Test if the given class represents instructions which are always
426/// safe to mark with the nounwind attribute..
427static bool IsNoThrow(InstructionClass Class) {
Dan Gohman1d2fd752011-09-14 18:33:34 +0000428 // objc_retainBlock is not nounwind because it calls user copy constructors
429 // which could theoretically throw.
John McCall9fbd3182011-06-15 23:37:01 +0000430 return Class == IC_Retain ||
431 Class == IC_RetainRV ||
John McCall9fbd3182011-06-15 23:37:01 +0000432 Class == IC_Release ||
433 Class == IC_Autorelease ||
434 Class == IC_AutoreleaseRV ||
435 Class == IC_AutoreleasepoolPush ||
436 Class == IC_AutoreleasepoolPop;
437}
438
439/// EraseInstruction - Erase the given instruction. ObjC calls return their
440/// argument verbatim, so if it's such a call and the return value has users,
441/// replace them with the argument value.
442static void EraseInstruction(Instruction *CI) {
443 Value *OldArg = cast<CallInst>(CI)->getArgOperand(0);
444
445 bool Unused = CI->use_empty();
446
447 if (!Unused) {
448 // Replace the return value with the argument.
449 assert(IsForwarding(GetBasicInstructionClass(CI)) &&
450 "Can't delete non-forwarding instruction with users!");
451 CI->replaceAllUsesWith(OldArg);
452 }
453
454 CI->eraseFromParent();
455
456 if (Unused)
457 RecursivelyDeleteTriviallyDeadInstructions(OldArg);
458}
459
460/// GetUnderlyingObjCPtr - This is a wrapper around getUnderlyingObject which
461/// also knows how to look through objc_retain and objc_autorelease calls, which
462/// we know to return their argument verbatim.
463static const Value *GetUnderlyingObjCPtr(const Value *V) {
464 for (;;) {
465 V = GetUnderlyingObject(V);
466 if (!IsForwarding(GetBasicInstructionClass(V)))
467 break;
468 V = cast<CallInst>(V)->getArgOperand(0);
469 }
470
471 return V;
472}
473
474/// StripPointerCastsAndObjCCalls - This is a wrapper around
475/// Value::stripPointerCasts which also knows how to look through objc_retain
476/// and objc_autorelease calls, which we know to return their argument verbatim.
477static const Value *StripPointerCastsAndObjCCalls(const Value *V) {
478 for (;;) {
479 V = V->stripPointerCasts();
480 if (!IsForwarding(GetBasicInstructionClass(V)))
481 break;
482 V = cast<CallInst>(V)->getArgOperand(0);
483 }
484 return V;
485}
486
487/// StripPointerCastsAndObjCCalls - This is a wrapper around
488/// Value::stripPointerCasts which also knows how to look through objc_retain
489/// and objc_autorelease calls, which we know to return their argument verbatim.
490static Value *StripPointerCastsAndObjCCalls(Value *V) {
491 for (;;) {
492 V = V->stripPointerCasts();
493 if (!IsForwarding(GetBasicInstructionClass(V)))
494 break;
495 V = cast<CallInst>(V)->getArgOperand(0);
496 }
497 return V;
498}
499
500/// GetObjCArg - Assuming the given instruction is one of the special calls such
501/// as objc_retain or objc_release, return the argument value, stripped of no-op
502/// casts and forwarding calls.
503static Value *GetObjCArg(Value *Inst) {
504 return StripPointerCastsAndObjCCalls(cast<CallInst>(Inst)->getArgOperand(0));
505}
506
507/// IsObjCIdentifiedObject - This is similar to AliasAnalysis'
508/// isObjCIdentifiedObject, except that it uses special knowledge of
509/// ObjC conventions...
510static bool IsObjCIdentifiedObject(const Value *V) {
511 // Assume that call results and arguments have their own "provenance".
512 // Constants (including GlobalVariables) and Allocas are never
513 // reference-counted.
514 if (isa<CallInst>(V) || isa<InvokeInst>(V) ||
515 isa<Argument>(V) || isa<Constant>(V) ||
516 isa<AllocaInst>(V))
517 return true;
518
519 if (const LoadInst *LI = dyn_cast<LoadInst>(V)) {
520 const Value *Pointer =
521 StripPointerCastsAndObjCCalls(LI->getPointerOperand());
522 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Pointer)) {
Dan Gohman1b31ea82011-08-22 17:29:11 +0000523 // A constant pointer can't be pointing to an object on the heap. It may
524 // be reference-counted, but it won't be deleted.
525 if (GV->isConstant())
526 return true;
John McCall9fbd3182011-06-15 23:37:01 +0000527 StringRef Name = GV->getName();
528 // These special variables are known to hold values which are not
529 // reference-counted pointers.
530 if (Name.startswith("\01L_OBJC_SELECTOR_REFERENCES_") ||
531 Name.startswith("\01L_OBJC_CLASSLIST_REFERENCES_") ||
532 Name.startswith("\01L_OBJC_CLASSLIST_SUP_REFS_$_") ||
533 Name.startswith("\01L_OBJC_METH_VAR_NAME_") ||
534 Name.startswith("\01l_objc_msgSend_fixup_"))
535 return true;
536 }
537 }
538
539 return false;
540}
541
542/// FindSingleUseIdentifiedObject - This is similar to
543/// StripPointerCastsAndObjCCalls but it stops as soon as it finds a value
544/// with multiple uses.
545static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
546 if (Arg->hasOneUse()) {
547 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
548 return FindSingleUseIdentifiedObject(BC->getOperand(0));
549 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
550 if (GEP->hasAllZeroIndices())
551 return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
552 if (IsForwarding(GetBasicInstructionClass(Arg)))
553 return FindSingleUseIdentifiedObject(
554 cast<CallInst>(Arg)->getArgOperand(0));
555 if (!IsObjCIdentifiedObject(Arg))
556 return 0;
557 return Arg;
558 }
559
560 // If we found an identifiable object but it has multiple uses, but they
561 // are trivial uses, we can still consider this to be a single-use
562 // value.
563 if (IsObjCIdentifiedObject(Arg)) {
564 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
565 UI != UE; ++UI) {
566 const User *U = *UI;
567 if (!U->use_empty() || StripPointerCastsAndObjCCalls(U) != Arg)
568 return 0;
569 }
570
571 return Arg;
572 }
573
574 return 0;
575}
576
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000577/// ModuleHasARC - Test if the given module looks interesting to run ARC
578/// optimization on.
579static bool ModuleHasARC(const Module &M) {
580 return
581 M.getNamedValue("objc_retain") ||
582 M.getNamedValue("objc_release") ||
583 M.getNamedValue("objc_autorelease") ||
584 M.getNamedValue("objc_retainAutoreleasedReturnValue") ||
585 M.getNamedValue("objc_retainBlock") ||
586 M.getNamedValue("objc_autoreleaseReturnValue") ||
587 M.getNamedValue("objc_autoreleasePoolPush") ||
588 M.getNamedValue("objc_loadWeakRetained") ||
589 M.getNamedValue("objc_loadWeak") ||
590 M.getNamedValue("objc_destroyWeak") ||
591 M.getNamedValue("objc_storeWeak") ||
592 M.getNamedValue("objc_initWeak") ||
593 M.getNamedValue("objc_moveWeak") ||
594 M.getNamedValue("objc_copyWeak") ||
595 M.getNamedValue("objc_retainedObject") ||
596 M.getNamedValue("objc_unretainedObject") ||
597 M.getNamedValue("objc_unretainedPointer");
598}
599
John McCall9fbd3182011-06-15 23:37:01 +0000600//===----------------------------------------------------------------------===//
601// ARC AliasAnalysis.
602//===----------------------------------------------------------------------===//
603
604#include "llvm/Pass.h"
605#include "llvm/Analysis/AliasAnalysis.h"
606#include "llvm/Analysis/Passes.h"
607
608namespace {
609 /// ObjCARCAliasAnalysis - This is a simple alias analysis
610 /// implementation that uses knowledge of ARC constructs to answer queries.
611 ///
612 /// TODO: This class could be generalized to know about other ObjC-specific
613 /// tricks. Such as knowing that ivars in the non-fragile ABI are non-aliasing
614 /// even though their offsets are dynamic.
615 class ObjCARCAliasAnalysis : public ImmutablePass,
616 public AliasAnalysis {
617 public:
618 static char ID; // Class identification, replacement for typeinfo
619 ObjCARCAliasAnalysis() : ImmutablePass(ID) {
620 initializeObjCARCAliasAnalysisPass(*PassRegistry::getPassRegistry());
621 }
622
623 private:
624 virtual void initializePass() {
625 InitializeAliasAnalysis(this);
626 }
627
628 /// getAdjustedAnalysisPointer - This method is used when a pass implements
629 /// an analysis interface through multiple inheritance. If needed, it
630 /// should override this to adjust the this pointer as needed for the
631 /// specified pass info.
632 virtual void *getAdjustedAnalysisPointer(const void *PI) {
633 if (PI == &AliasAnalysis::ID)
634 return (AliasAnalysis*)this;
635 return this;
636 }
637
638 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
639 virtual AliasResult alias(const Location &LocA, const Location &LocB);
640 virtual bool pointsToConstantMemory(const Location &Loc, bool OrLocal);
641 virtual ModRefBehavior getModRefBehavior(ImmutableCallSite CS);
642 virtual ModRefBehavior getModRefBehavior(const Function *F);
643 virtual ModRefResult getModRefInfo(ImmutableCallSite CS,
644 const Location &Loc);
645 virtual ModRefResult getModRefInfo(ImmutableCallSite CS1,
646 ImmutableCallSite CS2);
647 };
648} // End of anonymous namespace
649
650// Register this pass...
651char ObjCARCAliasAnalysis::ID = 0;
652INITIALIZE_AG_PASS(ObjCARCAliasAnalysis, AliasAnalysis, "objc-arc-aa",
653 "ObjC-ARC-Based Alias Analysis", false, true, false)
654
655ImmutablePass *llvm::createObjCARCAliasAnalysisPass() {
656 return new ObjCARCAliasAnalysis();
657}
658
659void
660ObjCARCAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
661 AU.setPreservesAll();
662 AliasAnalysis::getAnalysisUsage(AU);
663}
664
665AliasAnalysis::AliasResult
666ObjCARCAliasAnalysis::alias(const Location &LocA, const Location &LocB) {
667 if (!EnableARCOpts)
668 return AliasAnalysis::alias(LocA, LocB);
669
670 // First, strip off no-ops, including ObjC-specific no-ops, and try making a
671 // precise alias query.
672 const Value *SA = StripPointerCastsAndObjCCalls(LocA.Ptr);
673 const Value *SB = StripPointerCastsAndObjCCalls(LocB.Ptr);
674 AliasResult Result =
675 AliasAnalysis::alias(Location(SA, LocA.Size, LocA.TBAATag),
676 Location(SB, LocB.Size, LocB.TBAATag));
677 if (Result != MayAlias)
678 return Result;
679
680 // If that failed, climb to the underlying object, including climbing through
681 // ObjC-specific no-ops, and try making an imprecise alias query.
682 const Value *UA = GetUnderlyingObjCPtr(SA);
683 const Value *UB = GetUnderlyingObjCPtr(SB);
684 if (UA != SA || UB != SB) {
685 Result = AliasAnalysis::alias(Location(UA), Location(UB));
686 // We can't use MustAlias or PartialAlias results here because
687 // GetUnderlyingObjCPtr may return an offsetted pointer value.
688 if (Result == NoAlias)
689 return NoAlias;
690 }
691
692 // If that failed, fail. We don't need to chain here, since that's covered
693 // by the earlier precise query.
694 return MayAlias;
695}
696
697bool
698ObjCARCAliasAnalysis::pointsToConstantMemory(const Location &Loc,
699 bool OrLocal) {
700 if (!EnableARCOpts)
701 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
702
703 // First, strip off no-ops, including ObjC-specific no-ops, and try making
704 // a precise alias query.
705 const Value *S = StripPointerCastsAndObjCCalls(Loc.Ptr);
706 if (AliasAnalysis::pointsToConstantMemory(Location(S, Loc.Size, Loc.TBAATag),
707 OrLocal))
708 return true;
709
710 // If that failed, climb to the underlying object, including climbing through
711 // ObjC-specific no-ops, and try making an imprecise alias query.
712 const Value *U = GetUnderlyingObjCPtr(S);
713 if (U != S)
714 return AliasAnalysis::pointsToConstantMemory(Location(U), OrLocal);
715
716 // If that failed, fail. We don't need to chain here, since that's covered
717 // by the earlier precise query.
718 return false;
719}
720
721AliasAnalysis::ModRefBehavior
722ObjCARCAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
723 // We have nothing to do. Just chain to the next AliasAnalysis.
724 return AliasAnalysis::getModRefBehavior(CS);
725}
726
727AliasAnalysis::ModRefBehavior
728ObjCARCAliasAnalysis::getModRefBehavior(const Function *F) {
729 if (!EnableARCOpts)
730 return AliasAnalysis::getModRefBehavior(F);
731
732 switch (GetFunctionClass(F)) {
733 case IC_NoopCast:
734 return DoesNotAccessMemory;
735 default:
736 break;
737 }
738
739 return AliasAnalysis::getModRefBehavior(F);
740}
741
742AliasAnalysis::ModRefResult
743ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS, const Location &Loc) {
744 if (!EnableARCOpts)
745 return AliasAnalysis::getModRefInfo(CS, Loc);
746
747 switch (GetBasicInstructionClass(CS.getInstruction())) {
748 case IC_Retain:
749 case IC_RetainRV:
John McCall9fbd3182011-06-15 23:37:01 +0000750 case IC_Autorelease:
751 case IC_AutoreleaseRV:
752 case IC_NoopCast:
753 case IC_AutoreleasepoolPush:
754 case IC_FusedRetainAutorelease:
755 case IC_FusedRetainAutoreleaseRV:
756 // These functions don't access any memory visible to the compiler.
Dan Gohman21104822011-09-14 18:13:00 +0000757 // Note that this doesn't include objc_retainBlock, becuase it updates
758 // pointers when it copies block data.
John McCall9fbd3182011-06-15 23:37:01 +0000759 return NoModRef;
760 default:
761 break;
762 }
763
764 return AliasAnalysis::getModRefInfo(CS, Loc);
765}
766
767AliasAnalysis::ModRefResult
768ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
769 ImmutableCallSite CS2) {
770 // TODO: Theoretically we could check for dependencies between objc_* calls
771 // and OnlyAccessesArgumentPointees calls or other well-behaved calls.
772 return AliasAnalysis::getModRefInfo(CS1, CS2);
773}
774
775//===----------------------------------------------------------------------===//
776// ARC expansion.
777//===----------------------------------------------------------------------===//
778
779#include "llvm/Support/InstIterator.h"
780#include "llvm/Transforms/Scalar.h"
781
782namespace {
783 /// ObjCARCExpand - Early ARC transformations.
784 class ObjCARCExpand : public FunctionPass {
785 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000786 virtual bool doInitialization(Module &M);
John McCall9fbd3182011-06-15 23:37:01 +0000787 virtual bool runOnFunction(Function &F);
788
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000789 /// Run - A flag indicating whether this optimization pass should run.
790 bool Run;
791
John McCall9fbd3182011-06-15 23:37:01 +0000792 public:
793 static char ID;
794 ObjCARCExpand() : FunctionPass(ID) {
795 initializeObjCARCExpandPass(*PassRegistry::getPassRegistry());
796 }
797 };
798}
799
800char ObjCARCExpand::ID = 0;
801INITIALIZE_PASS(ObjCARCExpand,
802 "objc-arc-expand", "ObjC ARC expansion", false, false)
803
804Pass *llvm::createObjCARCExpandPass() {
805 return new ObjCARCExpand();
806}
807
808void ObjCARCExpand::getAnalysisUsage(AnalysisUsage &AU) const {
809 AU.setPreservesCFG();
810}
811
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000812bool ObjCARCExpand::doInitialization(Module &M) {
813 Run = ModuleHasARC(M);
814 return false;
815}
816
John McCall9fbd3182011-06-15 23:37:01 +0000817bool ObjCARCExpand::runOnFunction(Function &F) {
818 if (!EnableARCOpts)
819 return false;
820
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000821 // If nothing in the Module uses ARC, don't do anything.
822 if (!Run)
823 return false;
824
John McCall9fbd3182011-06-15 23:37:01 +0000825 bool Changed = false;
826
827 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
828 Instruction *Inst = &*I;
829
830 switch (GetBasicInstructionClass(Inst)) {
831 case IC_Retain:
832 case IC_RetainRV:
833 case IC_Autorelease:
834 case IC_AutoreleaseRV:
835 case IC_FusedRetainAutorelease:
836 case IC_FusedRetainAutoreleaseRV:
837 // These calls return their argument verbatim, as a low-level
838 // optimization. However, this makes high-level optimizations
839 // harder. Undo any uses of this optimization that the front-end
840 // emitted here. We'll redo them in a later pass.
841 Changed = true;
842 Inst->replaceAllUsesWith(cast<CallInst>(Inst)->getArgOperand(0));
843 break;
844 default:
845 break;
846 }
847 }
848
849 return Changed;
850}
851
852//===----------------------------------------------------------------------===//
853// ARC optimization.
854//===----------------------------------------------------------------------===//
855
856// TODO: On code like this:
857//
858// objc_retain(%x)
859// stuff_that_cannot_release()
860// objc_autorelease(%x)
861// stuff_that_cannot_release()
862// objc_retain(%x)
863// stuff_that_cannot_release()
864// objc_autorelease(%x)
865//
866// The second retain and autorelease can be deleted.
867
868// TODO: It should be possible to delete
869// objc_autoreleasePoolPush and objc_autoreleasePoolPop
870// pairs if nothing is actually autoreleased between them. Also, autorelease
871// calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
872// after inlining) can be turned into plain release calls.
873
874// TODO: Critical-edge splitting. If the optimial insertion point is
875// a critical edge, the current algorithm has to fail, because it doesn't
876// know how to split edges. It should be possible to make the optimizer
877// think in terms of edges, rather than blocks, and then split critical
878// edges on demand.
879
880// TODO: OptimizeSequences could generalized to be Interprocedural.
881
882// TODO: Recognize that a bunch of other objc runtime calls have
883// non-escaping arguments and non-releasing arguments, and may be
884// non-autoreleasing.
885
886// TODO: Sink autorelease calls as far as possible. Unfortunately we
887// usually can't sink them past other calls, which would be the main
888// case where it would be useful.
889
Dan Gohmane6d5e882011-08-19 00:26:36 +0000890// TODO: The pointer returned from objc_loadWeakRetained is retained.
891
892// TODO: Delete release+retain pairs (rare).
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000893
John McCall9fbd3182011-06-15 23:37:01 +0000894#include "llvm/GlobalAlias.h"
John McCall9fbd3182011-06-15 23:37:01 +0000895#include "llvm/Constants.h"
896#include "llvm/LLVMContext.h"
897#include "llvm/Support/ErrorHandling.h"
898#include "llvm/Support/CFG.h"
899#include "llvm/ADT/PostOrderIterator.h"
900#include "llvm/ADT/Statistic.h"
901
902STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
903STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
904STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
905STATISTIC(NumRets, "Number of return value forwarding "
906 "retain+autoreleaes eliminated");
907STATISTIC(NumRRs, "Number of retain+release paths eliminated");
908STATISTIC(NumPeeps, "Number of calls peephole-optimized");
909
910namespace {
911 /// ProvenanceAnalysis - This is similar to BasicAliasAnalysis, and it
912 /// uses many of the same techniques, except it uses special ObjC-specific
913 /// reasoning about pointer relationships.
914 class ProvenanceAnalysis {
915 AliasAnalysis *AA;
916
917 typedef std::pair<const Value *, const Value *> ValuePairTy;
918 typedef DenseMap<ValuePairTy, bool> CachedResultsTy;
919 CachedResultsTy CachedResults;
920
921 bool relatedCheck(const Value *A, const Value *B);
922 bool relatedSelect(const SelectInst *A, const Value *B);
923 bool relatedPHI(const PHINode *A, const Value *B);
924
925 // Do not implement.
926 void operator=(const ProvenanceAnalysis &);
927 ProvenanceAnalysis(const ProvenanceAnalysis &);
928
929 public:
930 ProvenanceAnalysis() {}
931
932 void setAA(AliasAnalysis *aa) { AA = aa; }
933
934 AliasAnalysis *getAA() const { return AA; }
935
936 bool related(const Value *A, const Value *B);
937
938 void clear() {
939 CachedResults.clear();
940 }
941 };
942}
943
944bool ProvenanceAnalysis::relatedSelect(const SelectInst *A, const Value *B) {
945 // If the values are Selects with the same condition, we can do a more precise
946 // check: just check for relations between the values on corresponding arms.
947 if (const SelectInst *SB = dyn_cast<SelectInst>(B))
948 if (A->getCondition() == SB->getCondition()) {
949 if (related(A->getTrueValue(), SB->getTrueValue()))
950 return true;
951 if (related(A->getFalseValue(), SB->getFalseValue()))
952 return true;
953 return false;
954 }
955
956 // Check both arms of the Select node individually.
957 if (related(A->getTrueValue(), B))
958 return true;
959 if (related(A->getFalseValue(), B))
960 return true;
961
962 // The arms both checked out.
963 return false;
964}
965
966bool ProvenanceAnalysis::relatedPHI(const PHINode *A, const Value *B) {
967 // If the values are PHIs in the same block, we can do a more precise as well
968 // as efficient check: just check for relations between the values on
969 // corresponding edges.
970 if (const PHINode *PNB = dyn_cast<PHINode>(B))
971 if (PNB->getParent() == A->getParent()) {
972 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i)
973 if (related(A->getIncomingValue(i),
974 PNB->getIncomingValueForBlock(A->getIncomingBlock(i))))
975 return true;
976 return false;
977 }
978
979 // Check each unique source of the PHI node against B.
980 SmallPtrSet<const Value *, 4> UniqueSrc;
981 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i) {
982 const Value *PV1 = A->getIncomingValue(i);
983 if (UniqueSrc.insert(PV1) && related(PV1, B))
984 return true;
985 }
986
987 // All of the arms checked out.
988 return false;
989}
990
991/// isStoredObjCPointer - Test if the value of P, or any value covered by its
992/// provenance, is ever stored within the function (not counting callees).
993static bool isStoredObjCPointer(const Value *P) {
994 SmallPtrSet<const Value *, 8> Visited;
995 SmallVector<const Value *, 8> Worklist;
996 Worklist.push_back(P);
997 Visited.insert(P);
998 do {
999 P = Worklist.pop_back_val();
1000 for (Value::const_use_iterator UI = P->use_begin(), UE = P->use_end();
1001 UI != UE; ++UI) {
1002 const User *Ur = *UI;
1003 if (isa<StoreInst>(Ur)) {
1004 if (UI.getOperandNo() == 0)
1005 // The pointer is stored.
1006 return true;
1007 // The pointed is stored through.
1008 continue;
1009 }
1010 if (isa<CallInst>(Ur))
1011 // The pointer is passed as an argument, ignore this.
1012 continue;
1013 if (isa<PtrToIntInst>(P))
1014 // Assume the worst.
1015 return true;
1016 if (Visited.insert(Ur))
1017 Worklist.push_back(Ur);
1018 }
1019 } while (!Worklist.empty());
1020
1021 // Everything checked out.
1022 return false;
1023}
1024
1025bool ProvenanceAnalysis::relatedCheck(const Value *A, const Value *B) {
1026 // Skip past provenance pass-throughs.
1027 A = GetUnderlyingObjCPtr(A);
1028 B = GetUnderlyingObjCPtr(B);
1029
1030 // Quick check.
1031 if (A == B)
1032 return true;
1033
1034 // Ask regular AliasAnalysis, for a first approximation.
1035 switch (AA->alias(A, B)) {
1036 case AliasAnalysis::NoAlias:
1037 return false;
1038 case AliasAnalysis::MustAlias:
1039 case AliasAnalysis::PartialAlias:
1040 return true;
1041 case AliasAnalysis::MayAlias:
1042 break;
1043 }
1044
1045 bool AIsIdentified = IsObjCIdentifiedObject(A);
1046 bool BIsIdentified = IsObjCIdentifiedObject(B);
1047
1048 // An ObjC-Identified object can't alias a load if it is never locally stored.
1049 if (AIsIdentified) {
1050 if (BIsIdentified) {
1051 // If both pointers have provenance, they can be directly compared.
1052 if (A != B)
1053 return false;
1054 } else {
1055 if (isa<LoadInst>(B))
1056 return isStoredObjCPointer(A);
1057 }
1058 } else {
1059 if (BIsIdentified && isa<LoadInst>(A))
1060 return isStoredObjCPointer(B);
1061 }
1062
1063 // Special handling for PHI and Select.
1064 if (const PHINode *PN = dyn_cast<PHINode>(A))
1065 return relatedPHI(PN, B);
1066 if (const PHINode *PN = dyn_cast<PHINode>(B))
1067 return relatedPHI(PN, A);
1068 if (const SelectInst *S = dyn_cast<SelectInst>(A))
1069 return relatedSelect(S, B);
1070 if (const SelectInst *S = dyn_cast<SelectInst>(B))
1071 return relatedSelect(S, A);
1072
1073 // Conservative.
1074 return true;
1075}
1076
1077bool ProvenanceAnalysis::related(const Value *A, const Value *B) {
1078 // Begin by inserting a conservative value into the map. If the insertion
1079 // fails, we have the answer already. If it succeeds, leave it there until we
1080 // compute the real answer to guard against recursive queries.
1081 if (A > B) std::swap(A, B);
1082 std::pair<CachedResultsTy::iterator, bool> Pair =
1083 CachedResults.insert(std::make_pair(ValuePairTy(A, B), true));
1084 if (!Pair.second)
1085 return Pair.first->second;
1086
1087 bool Result = relatedCheck(A, B);
1088 CachedResults[ValuePairTy(A, B)] = Result;
1089 return Result;
1090}
1091
1092namespace {
1093 // Sequence - A sequence of states that a pointer may go through in which an
1094 // objc_retain and objc_release are actually needed.
1095 enum Sequence {
1096 S_None,
1097 S_Retain, ///< objc_retain(x)
1098 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement
1099 S_Use, ///< any use of x
1100 S_Stop, ///< like S_Release, but code motion is stopped
1101 S_Release, ///< objc_release(x)
1102 S_MovableRelease ///< objc_release(x), !clang.imprecise_release
1103 };
1104}
1105
1106static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
1107 // The easy cases.
1108 if (A == B)
1109 return A;
1110 if (A == S_None || B == S_None)
1111 return S_None;
1112
John McCall9fbd3182011-06-15 23:37:01 +00001113 if (A > B) std::swap(A, B);
1114 if (TopDown) {
1115 // Choose the side which is further along in the sequence.
Dan Gohmana7f7db22011-08-12 00:26:31 +00001116 if ((A == S_Retain || A == S_CanRelease) &&
1117 (B == S_CanRelease || B == S_Use))
John McCall9fbd3182011-06-15 23:37:01 +00001118 return B;
1119 } else {
1120 // Choose the side which is further along in the sequence.
1121 if ((A == S_Use || A == S_CanRelease) &&
Dan Gohmana7f7db22011-08-12 00:26:31 +00001122 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
John McCall9fbd3182011-06-15 23:37:01 +00001123 return A;
1124 // If both sides are releases, choose the more conservative one.
1125 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
1126 return A;
1127 if (A == S_Release && B == S_MovableRelease)
1128 return A;
1129 }
1130
1131 return S_None;
1132}
1133
1134namespace {
1135 /// RRInfo - Unidirectional information about either a
1136 /// retain-decrement-use-release sequence or release-use-decrement-retain
1137 /// reverese sequence.
1138 struct RRInfo {
Dan Gohmane6d5e882011-08-19 00:26:36 +00001139 /// KnownSafe - After an objc_retain, the reference count of the referenced
1140 /// object is known to be positive. Similarly, before an objc_release, the
1141 /// reference count of the referenced object is known to be positive. If
1142 /// there are retain-release pairs in code regions where the retain count
1143 /// is known to be positive, they can be eliminated, regardless of any side
1144 /// effects between them.
1145 ///
1146 /// Also, a retain+release pair nested within another retain+release
1147 /// pair all on the known same pointer value can be eliminated, regardless
1148 /// of any intervening side effects.
1149 ///
1150 /// KnownSafe is true when either of these conditions is satisfied.
1151 bool KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00001152
1153 /// IsRetainBlock - True if the Calls are objc_retainBlock calls (as
1154 /// opposed to objc_retain calls).
1155 bool IsRetainBlock;
1156
1157 /// IsTailCallRelease - True of the objc_release calls are all marked
1158 /// with the "tail" keyword.
1159 bool IsTailCallRelease;
1160
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001161 /// Partial - True of we've seen an opportunity for partial RR elimination,
1162 /// such as pushing calls into a CFG triangle or into one side of a
1163 /// CFG diamond.
1164 bool Partial;
1165
John McCall9fbd3182011-06-15 23:37:01 +00001166 /// ReleaseMetadata - If the Calls are objc_release calls and they all have
1167 /// a clang.imprecise_release tag, this is the metadata tag.
1168 MDNode *ReleaseMetadata;
1169
1170 /// Calls - For a top-down sequence, the set of objc_retains or
1171 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
1172 SmallPtrSet<Instruction *, 2> Calls;
1173
1174 /// ReverseInsertPts - The set of optimal insert positions for
1175 /// moving calls in the opposite sequence.
1176 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
1177
1178 RRInfo() :
Dan Gohmane6d5e882011-08-19 00:26:36 +00001179 KnownSafe(false), IsRetainBlock(false), IsTailCallRelease(false),
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001180 Partial(false),
John McCall9fbd3182011-06-15 23:37:01 +00001181 ReleaseMetadata(0) {}
1182
1183 void clear();
1184 };
1185}
1186
1187void RRInfo::clear() {
Dan Gohmane6d5e882011-08-19 00:26:36 +00001188 KnownSafe = false;
John McCall9fbd3182011-06-15 23:37:01 +00001189 IsRetainBlock = false;
1190 IsTailCallRelease = false;
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001191 Partial = false;
John McCall9fbd3182011-06-15 23:37:01 +00001192 ReleaseMetadata = 0;
1193 Calls.clear();
1194 ReverseInsertPts.clear();
1195}
1196
1197namespace {
1198 /// PtrState - This class summarizes several per-pointer runtime properties
1199 /// which are propogated through the flow graph.
1200 class PtrState {
1201 /// RefCount - The known minimum number of reference count increments.
1202 unsigned RefCount;
1203
Dan Gohmane6d5e882011-08-19 00:26:36 +00001204 /// NestCount - The known minimum level of retain+release nesting.
1205 unsigned NestCount;
1206
John McCall9fbd3182011-06-15 23:37:01 +00001207 /// Seq - The current position in the sequence.
1208 Sequence Seq;
1209
1210 public:
1211 /// RRI - Unidirectional information about the current sequence.
1212 /// TODO: Encapsulate this better.
1213 RRInfo RRI;
1214
Dan Gohmane6d5e882011-08-19 00:26:36 +00001215 PtrState() : RefCount(0), NestCount(0), Seq(S_None) {}
John McCall9fbd3182011-06-15 23:37:01 +00001216
Dan Gohmana7f7db22011-08-12 00:26:31 +00001217 void SetAtLeastOneRefCount() {
1218 if (RefCount == 0) RefCount = 1;
1219 }
1220
John McCall9fbd3182011-06-15 23:37:01 +00001221 void IncrementRefCount() {
1222 if (RefCount != UINT_MAX) ++RefCount;
1223 }
1224
1225 void DecrementRefCount() {
1226 if (RefCount != 0) --RefCount;
1227 }
1228
John McCall9fbd3182011-06-15 23:37:01 +00001229 bool IsKnownIncremented() const {
1230 return RefCount > 0;
1231 }
1232
Dan Gohmane6d5e882011-08-19 00:26:36 +00001233 void IncrementNestCount() {
1234 if (NestCount != UINT_MAX) ++NestCount;
1235 }
1236
1237 void DecrementNestCount() {
1238 if (NestCount != 0) --NestCount;
1239 }
1240
1241 bool IsKnownNested() const {
1242 return NestCount > 0;
1243 }
1244
John McCall9fbd3182011-06-15 23:37:01 +00001245 void SetSeq(Sequence NewSeq) {
1246 Seq = NewSeq;
1247 }
1248
1249 void SetSeqToRelease(MDNode *M) {
1250 if (Seq == S_None || Seq == S_Use) {
1251 Seq = M ? S_MovableRelease : S_Release;
1252 RRI.ReleaseMetadata = M;
1253 } else if (Seq != S_MovableRelease || RRI.ReleaseMetadata != M) {
1254 Seq = S_Release;
1255 RRI.ReleaseMetadata = 0;
1256 }
1257 }
1258
1259 Sequence GetSeq() const {
1260 return Seq;
1261 }
1262
1263 void ClearSequenceProgress() {
1264 Seq = S_None;
1265 RRI.clear();
1266 }
1267
1268 void Merge(const PtrState &Other, bool TopDown);
1269 };
1270}
1271
1272void
1273PtrState::Merge(const PtrState &Other, bool TopDown) {
1274 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
1275 RefCount = std::min(RefCount, Other.RefCount);
Dan Gohmane6d5e882011-08-19 00:26:36 +00001276 NestCount = std::min(NestCount, Other.NestCount);
John McCall9fbd3182011-06-15 23:37:01 +00001277
1278 // We can't merge a plain objc_retain with an objc_retainBlock.
1279 if (RRI.IsRetainBlock != Other.RRI.IsRetainBlock)
1280 Seq = S_None;
1281
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001282 // If we're not in a sequence (anymore), drop all associated state.
John McCall9fbd3182011-06-15 23:37:01 +00001283 if (Seq == S_None) {
1284 RRI.clear();
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001285 } else if (RRI.Partial || Other.RRI.Partial) {
1286 // If we're doing a merge on a path that's previously seen a partial
1287 // merge, conservatively drop the sequence, to avoid doing partial
1288 // RR elimination. If the branch predicates for the two merge differ,
1289 // mixing them is unsafe.
1290 Seq = S_None;
1291 RRI.clear();
John McCall9fbd3182011-06-15 23:37:01 +00001292 } else {
1293 // Conservatively merge the ReleaseMetadata information.
1294 if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
1295 RRI.ReleaseMetadata = 0;
1296
Dan Gohmane6d5e882011-08-19 00:26:36 +00001297 RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00001298 RRI.IsTailCallRelease = RRI.IsTailCallRelease && Other.RRI.IsTailCallRelease;
1299 RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001300
1301 // Merge the insert point sets. If there are any differences,
1302 // that makes this a partial merge.
1303 RRI.Partial = RRI.ReverseInsertPts.size() !=
1304 Other.RRI.ReverseInsertPts.size();
1305 for (SmallPtrSet<Instruction *, 2>::const_iterator
1306 I = Other.RRI.ReverseInsertPts.begin(),
1307 E = Other.RRI.ReverseInsertPts.end(); I != E; ++I)
1308 RRI.Partial |= RRI.ReverseInsertPts.insert(*I);
John McCall9fbd3182011-06-15 23:37:01 +00001309 }
1310}
1311
1312namespace {
1313 /// BBState - Per-BasicBlock state.
1314 class BBState {
1315 /// TopDownPathCount - The number of unique control paths from the entry
1316 /// which can reach this block.
1317 unsigned TopDownPathCount;
1318
1319 /// BottomUpPathCount - The number of unique control paths to exits
1320 /// from this block.
1321 unsigned BottomUpPathCount;
1322
1323 /// MapTy - A type for PerPtrTopDown and PerPtrBottomUp.
1324 typedef MapVector<const Value *, PtrState> MapTy;
1325
1326 /// PerPtrTopDown - The top-down traversal uses this to record information
1327 /// known about a pointer at the bottom of each block.
1328 MapTy PerPtrTopDown;
1329
1330 /// PerPtrBottomUp - The bottom-up traversal uses this to record information
1331 /// known about a pointer at the top of each block.
1332 MapTy PerPtrBottomUp;
1333
1334 public:
1335 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
1336
1337 typedef MapTy::iterator ptr_iterator;
1338 typedef MapTy::const_iterator ptr_const_iterator;
1339
1340 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
1341 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
1342 ptr_const_iterator top_down_ptr_begin() const {
1343 return PerPtrTopDown.begin();
1344 }
1345 ptr_const_iterator top_down_ptr_end() const {
1346 return PerPtrTopDown.end();
1347 }
1348
1349 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
1350 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
1351 ptr_const_iterator bottom_up_ptr_begin() const {
1352 return PerPtrBottomUp.begin();
1353 }
1354 ptr_const_iterator bottom_up_ptr_end() const {
1355 return PerPtrBottomUp.end();
1356 }
1357
1358 /// SetAsEntry - Mark this block as being an entry block, which has one
1359 /// path from the entry by definition.
1360 void SetAsEntry() { TopDownPathCount = 1; }
1361
1362 /// SetAsExit - Mark this block as being an exit block, which has one
1363 /// path to an exit by definition.
1364 void SetAsExit() { BottomUpPathCount = 1; }
1365
1366 PtrState &getPtrTopDownState(const Value *Arg) {
1367 return PerPtrTopDown[Arg];
1368 }
1369
1370 PtrState &getPtrBottomUpState(const Value *Arg) {
1371 return PerPtrBottomUp[Arg];
1372 }
1373
1374 void clearBottomUpPointers() {
Evan Chenga81388f2011-08-04 18:40:26 +00001375 PerPtrBottomUp.clear();
John McCall9fbd3182011-06-15 23:37:01 +00001376 }
1377
1378 void clearTopDownPointers() {
1379 PerPtrTopDown.clear();
1380 }
1381
1382 void InitFromPred(const BBState &Other);
1383 void InitFromSucc(const BBState &Other);
1384 void MergePred(const BBState &Other);
1385 void MergeSucc(const BBState &Other);
1386
1387 /// GetAllPathCount - Return the number of possible unique paths from an
1388 /// entry to an exit which pass through this block. This is only valid
1389 /// after both the top-down and bottom-up traversals are complete.
1390 unsigned GetAllPathCount() const {
1391 return TopDownPathCount * BottomUpPathCount;
1392 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00001393
1394 /// IsVisitedTopDown - Test whether the block for this BBState has been
1395 /// visited by the top-down portion of the algorithm.
1396 bool isVisitedTopDown() const {
1397 return TopDownPathCount != 0;
1398 }
John McCall9fbd3182011-06-15 23:37:01 +00001399 };
1400}
1401
1402void BBState::InitFromPred(const BBState &Other) {
1403 PerPtrTopDown = Other.PerPtrTopDown;
1404 TopDownPathCount = Other.TopDownPathCount;
1405}
1406
1407void BBState::InitFromSucc(const BBState &Other) {
1408 PerPtrBottomUp = Other.PerPtrBottomUp;
1409 BottomUpPathCount = Other.BottomUpPathCount;
1410}
1411
1412/// MergePred - The top-down traversal uses this to merge information about
1413/// predecessors to form the initial state for a new block.
1414void BBState::MergePred(const BBState &Other) {
1415 // Other.TopDownPathCount can be 0, in which case it is either dead or a
1416 // loop backedge. Loop backedges are special.
1417 TopDownPathCount += Other.TopDownPathCount;
1418
1419 // For each entry in the other set, if our set has an entry with the same key,
1420 // merge the entries. Otherwise, copy the entry and merge it with an empty
1421 // entry.
1422 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
1423 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
1424 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
1425 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1426 /*TopDown=*/true);
1427 }
1428
Dan Gohmanfa7eed12011-08-11 21:06:32 +00001429 // For each entry in our set, if the other set doesn't have an entry with the
John McCall9fbd3182011-06-15 23:37:01 +00001430 // same key, force it to merge with an empty entry.
1431 for (ptr_iterator MI = top_down_ptr_begin(),
1432 ME = top_down_ptr_end(); MI != ME; ++MI)
1433 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
1434 MI->second.Merge(PtrState(), /*TopDown=*/true);
1435}
1436
1437/// MergeSucc - The bottom-up traversal uses this to merge information about
1438/// successors to form the initial state for a new block.
1439void BBState::MergeSucc(const BBState &Other) {
1440 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
1441 // loop backedge. Loop backedges are special.
1442 BottomUpPathCount += Other.BottomUpPathCount;
1443
1444 // For each entry in the other set, if our set has an entry with the
1445 // same key, merge the entries. Otherwise, copy the entry and merge
1446 // it with an empty entry.
1447 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
1448 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
1449 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
1450 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1451 /*TopDown=*/false);
1452 }
1453
Dan Gohmanfa7eed12011-08-11 21:06:32 +00001454 // For each entry in our set, if the other set doesn't have an entry
John McCall9fbd3182011-06-15 23:37:01 +00001455 // with the same key, force it to merge with an empty entry.
1456 for (ptr_iterator MI = bottom_up_ptr_begin(),
1457 ME = bottom_up_ptr_end(); MI != ME; ++MI)
1458 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
1459 MI->second.Merge(PtrState(), /*TopDown=*/false);
1460}
1461
1462namespace {
1463 /// ObjCARCOpt - The main ARC optimization pass.
1464 class ObjCARCOpt : public FunctionPass {
1465 bool Changed;
1466 ProvenanceAnalysis PA;
1467
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00001468 /// Run - A flag indicating whether this optimization pass should run.
1469 bool Run;
1470
John McCall9fbd3182011-06-15 23:37:01 +00001471 /// RetainRVCallee, etc. - Declarations for ObjC runtime
1472 /// functions, for use in creating calls to them. These are initialized
1473 /// lazily to avoid cluttering up the Module with unused declarations.
1474 Constant *RetainRVCallee, *AutoreleaseRVCallee, *ReleaseCallee,
Dan Gohman44280692011-07-22 22:29:21 +00001475 *RetainCallee, *RetainBlockCallee, *AutoreleaseCallee;
John McCall9fbd3182011-06-15 23:37:01 +00001476
1477 /// UsedInThisFunciton - Flags which determine whether each of the
1478 /// interesting runtine functions is in fact used in the current function.
1479 unsigned UsedInThisFunction;
1480
1481 /// ImpreciseReleaseMDKind - The Metadata Kind for clang.imprecise_release
1482 /// metadata.
1483 unsigned ImpreciseReleaseMDKind;
1484
1485 Constant *getRetainRVCallee(Module *M);
1486 Constant *getAutoreleaseRVCallee(Module *M);
1487 Constant *getReleaseCallee(Module *M);
1488 Constant *getRetainCallee(Module *M);
Dan Gohman44280692011-07-22 22:29:21 +00001489 Constant *getRetainBlockCallee(Module *M);
John McCall9fbd3182011-06-15 23:37:01 +00001490 Constant *getAutoreleaseCallee(Module *M);
1491
1492 void OptimizeRetainCall(Function &F, Instruction *Retain);
1493 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
1494 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV);
1495 void OptimizeIndividualCalls(Function &F);
1496
1497 void CheckForCFGHazards(const BasicBlock *BB,
1498 DenseMap<const BasicBlock *, BBState> &BBStates,
1499 BBState &MyStates) const;
1500 bool VisitBottomUp(BasicBlock *BB,
1501 DenseMap<const BasicBlock *, BBState> &BBStates,
1502 MapVector<Value *, RRInfo> &Retains);
1503 bool VisitTopDown(BasicBlock *BB,
1504 DenseMap<const BasicBlock *, BBState> &BBStates,
1505 DenseMap<Value *, RRInfo> &Releases);
1506 bool Visit(Function &F,
1507 DenseMap<const BasicBlock *, BBState> &BBStates,
1508 MapVector<Value *, RRInfo> &Retains,
1509 DenseMap<Value *, RRInfo> &Releases);
1510
1511 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1512 MapVector<Value *, RRInfo> &Retains,
1513 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman44280692011-07-22 22:29:21 +00001514 SmallVectorImpl<Instruction *> &DeadInsts,
1515 Module *M);
John McCall9fbd3182011-06-15 23:37:01 +00001516
1517 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1518 MapVector<Value *, RRInfo> &Retains,
Dan Gohman44280692011-07-22 22:29:21 +00001519 DenseMap<Value *, RRInfo> &Releases,
1520 Module *M);
John McCall9fbd3182011-06-15 23:37:01 +00001521
1522 void OptimizeWeakCalls(Function &F);
1523
1524 bool OptimizeSequences(Function &F);
1525
1526 void OptimizeReturns(Function &F);
1527
1528 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1529 virtual bool doInitialization(Module &M);
1530 virtual bool runOnFunction(Function &F);
1531 virtual void releaseMemory();
1532
1533 public:
1534 static char ID;
1535 ObjCARCOpt() : FunctionPass(ID) {
1536 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1537 }
1538 };
1539}
1540
1541char ObjCARCOpt::ID = 0;
1542INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1543 "objc-arc", "ObjC ARC optimization", false, false)
1544INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1545INITIALIZE_PASS_END(ObjCARCOpt,
1546 "objc-arc", "ObjC ARC optimization", false, false)
1547
1548Pass *llvm::createObjCARCOptPass() {
1549 return new ObjCARCOpt();
1550}
1551
1552void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1553 AU.addRequired<ObjCARCAliasAnalysis>();
1554 AU.addRequired<AliasAnalysis>();
1555 // ARC optimization doesn't currently split critical edges.
1556 AU.setPreservesCFG();
1557}
1558
1559Constant *ObjCARCOpt::getRetainRVCallee(Module *M) {
1560 if (!RetainRVCallee) {
1561 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001562 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1563 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00001564 Params.push_back(I8X);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001565 FunctionType *FTy =
John McCall9fbd3182011-06-15 23:37:01 +00001566 FunctionType::get(I8X, Params, /*isVarArg=*/false);
1567 AttrListPtr Attributes;
1568 Attributes.addAttr(~0u, Attribute::NoUnwind);
1569 RetainRVCallee =
1570 M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy,
1571 Attributes);
1572 }
1573 return RetainRVCallee;
1574}
1575
1576Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1577 if (!AutoreleaseRVCallee) {
1578 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001579 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1580 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00001581 Params.push_back(I8X);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001582 FunctionType *FTy =
John McCall9fbd3182011-06-15 23:37:01 +00001583 FunctionType::get(I8X, Params, /*isVarArg=*/false);
1584 AttrListPtr Attributes;
1585 Attributes.addAttr(~0u, Attribute::NoUnwind);
1586 AutoreleaseRVCallee =
1587 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
1588 Attributes);
1589 }
1590 return AutoreleaseRVCallee;
1591}
1592
1593Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1594 if (!ReleaseCallee) {
1595 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001596 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00001597 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1598 AttrListPtr Attributes;
1599 Attributes.addAttr(~0u, Attribute::NoUnwind);
1600 ReleaseCallee =
1601 M->getOrInsertFunction(
1602 "objc_release",
1603 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
1604 Attributes);
1605 }
1606 return ReleaseCallee;
1607}
1608
1609Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1610 if (!RetainCallee) {
1611 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001612 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00001613 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1614 AttrListPtr Attributes;
1615 Attributes.addAttr(~0u, Attribute::NoUnwind);
1616 RetainCallee =
1617 M->getOrInsertFunction(
1618 "objc_retain",
1619 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1620 Attributes);
1621 }
1622 return RetainCallee;
1623}
1624
Dan Gohman44280692011-07-22 22:29:21 +00001625Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1626 if (!RetainBlockCallee) {
1627 LLVMContext &C = M->getContext();
1628 std::vector<Type *> Params;
1629 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1630 AttrListPtr Attributes;
Dan Gohman1d2fd752011-09-14 18:33:34 +00001631 // objc_retainBlock is not nounwind because it calls user copy constructors
1632 // which could theoretically throw.
Dan Gohman44280692011-07-22 22:29:21 +00001633 RetainBlockCallee =
1634 M->getOrInsertFunction(
1635 "objc_retainBlock",
1636 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1637 Attributes);
1638 }
1639 return RetainBlockCallee;
1640}
1641
John McCall9fbd3182011-06-15 23:37:01 +00001642Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1643 if (!AutoreleaseCallee) {
1644 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001645 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00001646 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1647 AttrListPtr Attributes;
1648 Attributes.addAttr(~0u, Attribute::NoUnwind);
1649 AutoreleaseCallee =
1650 M->getOrInsertFunction(
1651 "objc_autorelease",
1652 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1653 Attributes);
1654 }
1655 return AutoreleaseCallee;
1656}
1657
1658/// CanAlterRefCount - Test whether the given instruction can result in a
1659/// reference count modification (positive or negative) for the pointer's
1660/// object.
1661static bool
1662CanAlterRefCount(const Instruction *Inst, const Value *Ptr,
1663 ProvenanceAnalysis &PA, InstructionClass Class) {
1664 switch (Class) {
1665 case IC_Autorelease:
1666 case IC_AutoreleaseRV:
1667 case IC_User:
1668 // These operations never directly modify a reference count.
1669 return false;
1670 default: break;
1671 }
1672
1673 ImmutableCallSite CS = static_cast<const Value *>(Inst);
1674 assert(CS && "Only calls can alter reference counts!");
1675
1676 // See if AliasAnalysis can help us with the call.
1677 AliasAnalysis::ModRefBehavior MRB = PA.getAA()->getModRefBehavior(CS);
1678 if (AliasAnalysis::onlyReadsMemory(MRB))
1679 return false;
1680 if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
1681 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1682 I != E; ++I) {
1683 const Value *Op = *I;
1684 if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1685 return true;
1686 }
1687 return false;
1688 }
1689
1690 // Assume the worst.
1691 return true;
1692}
1693
1694/// CanUse - Test whether the given instruction can "use" the given pointer's
1695/// object in a way that requires the reference count to be positive.
1696static bool
1697CanUse(const Instruction *Inst, const Value *Ptr, ProvenanceAnalysis &PA,
1698 InstructionClass Class) {
1699 // IC_Call operations (as opposed to IC_CallOrUser) never "use" objc pointers.
1700 if (Class == IC_Call)
1701 return false;
1702
1703 // Consider various instructions which may have pointer arguments which are
1704 // not "uses".
1705 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(Inst)) {
1706 // Comparing a pointer with null, or any other constant, isn't really a use,
1707 // because we don't care what the pointer points to, or about the values
1708 // of any other dynamic reference-counted pointers.
1709 if (!IsPotentialUse(ICI->getOperand(1)))
1710 return false;
1711 } else if (ImmutableCallSite CS = static_cast<const Value *>(Inst)) {
1712 // For calls, just check the arguments (and not the callee operand).
1713 for (ImmutableCallSite::arg_iterator OI = CS.arg_begin(),
1714 OE = CS.arg_end(); OI != OE; ++OI) {
1715 const Value *Op = *OI;
1716 if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1717 return true;
1718 }
1719 return false;
1720 } else if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1721 // Special-case stores, because we don't care about the stored value, just
1722 // the store address.
1723 const Value *Op = GetUnderlyingObjCPtr(SI->getPointerOperand());
1724 // If we can't tell what the underlying object was, assume there is a
1725 // dependence.
1726 return IsPotentialUse(Op) && PA.related(Op, Ptr);
1727 }
1728
1729 // Check each operand for a match.
1730 for (User::const_op_iterator OI = Inst->op_begin(), OE = Inst->op_end();
1731 OI != OE; ++OI) {
1732 const Value *Op = *OI;
1733 if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1734 return true;
1735 }
1736 return false;
1737}
1738
1739/// CanInterruptRV - Test whether the given instruction can autorelease
1740/// any pointer or cause an autoreleasepool pop.
1741static bool
1742CanInterruptRV(InstructionClass Class) {
1743 switch (Class) {
1744 case IC_AutoreleasepoolPop:
1745 case IC_CallOrUser:
1746 case IC_Call:
1747 case IC_Autorelease:
1748 case IC_AutoreleaseRV:
1749 case IC_FusedRetainAutorelease:
1750 case IC_FusedRetainAutoreleaseRV:
1751 return true;
1752 default:
1753 return false;
1754 }
1755}
1756
1757namespace {
1758 /// DependenceKind - There are several kinds of dependence-like concepts in
1759 /// use here.
1760 enum DependenceKind {
1761 NeedsPositiveRetainCount,
1762 CanChangeRetainCount,
1763 RetainAutoreleaseDep, ///< Blocks objc_retainAutorelease.
1764 RetainAutoreleaseRVDep, ///< Blocks objc_retainAutoreleaseReturnValue.
1765 RetainRVDep ///< Blocks objc_retainAutoreleasedReturnValue.
1766 };
1767}
1768
1769/// Depends - Test if there can be dependencies on Inst through Arg. This
1770/// function only tests dependencies relevant for removing pairs of calls.
1771static bool
1772Depends(DependenceKind Flavor, Instruction *Inst, const Value *Arg,
1773 ProvenanceAnalysis &PA) {
1774 // If we've reached the definition of Arg, stop.
1775 if (Inst == Arg)
1776 return true;
1777
1778 switch (Flavor) {
1779 case NeedsPositiveRetainCount: {
1780 InstructionClass Class = GetInstructionClass(Inst);
1781 switch (Class) {
1782 case IC_AutoreleasepoolPop:
1783 case IC_AutoreleasepoolPush:
1784 case IC_None:
1785 return false;
1786 default:
1787 return CanUse(Inst, Arg, PA, Class);
1788 }
1789 }
1790
1791 case CanChangeRetainCount: {
1792 InstructionClass Class = GetInstructionClass(Inst);
1793 switch (Class) {
1794 case IC_AutoreleasepoolPop:
1795 // Conservatively assume this can decrement any count.
1796 return true;
1797 case IC_AutoreleasepoolPush:
1798 case IC_None:
1799 return false;
1800 default:
1801 return CanAlterRefCount(Inst, Arg, PA, Class);
1802 }
1803 }
1804
1805 case RetainAutoreleaseDep:
1806 switch (GetBasicInstructionClass(Inst)) {
1807 case IC_AutoreleasepoolPop:
1808 // Don't merge an objc_autorelease with an objc_retain inside a different
1809 // autoreleasepool scope.
1810 return true;
1811 case IC_Retain:
1812 case IC_RetainRV:
1813 // Check for a retain of the same pointer for merging.
1814 return GetObjCArg(Inst) == Arg;
1815 default:
1816 // Nothing else matters for objc_retainAutorelease formation.
1817 return false;
1818 }
1819 break;
1820
1821 case RetainAutoreleaseRVDep: {
1822 InstructionClass Class = GetBasicInstructionClass(Inst);
1823 switch (Class) {
1824 case IC_Retain:
1825 case IC_RetainRV:
1826 // Check for a retain of the same pointer for merging.
1827 return GetObjCArg(Inst) == Arg;
1828 default:
1829 // Anything that can autorelease interrupts
1830 // retainAutoreleaseReturnValue formation.
1831 return CanInterruptRV(Class);
1832 }
1833 break;
1834 }
1835
1836 case RetainRVDep:
1837 return CanInterruptRV(GetBasicInstructionClass(Inst));
1838 }
1839
1840 llvm_unreachable("Invalid dependence flavor");
1841 return true;
1842}
1843
1844/// FindDependencies - Walk up the CFG from StartPos (which is in StartBB) and
1845/// find local and non-local dependencies on Arg.
1846/// TODO: Cache results?
1847static void
1848FindDependencies(DependenceKind Flavor,
1849 const Value *Arg,
1850 BasicBlock *StartBB, Instruction *StartInst,
1851 SmallPtrSet<Instruction *, 4> &DependingInstructions,
1852 SmallPtrSet<const BasicBlock *, 4> &Visited,
1853 ProvenanceAnalysis &PA) {
1854 BasicBlock::iterator StartPos = StartInst;
1855
1856 SmallVector<std::pair<BasicBlock *, BasicBlock::iterator>, 4> Worklist;
1857 Worklist.push_back(std::make_pair(StartBB, StartPos));
1858 do {
1859 std::pair<BasicBlock *, BasicBlock::iterator> Pair =
1860 Worklist.pop_back_val();
1861 BasicBlock *LocalStartBB = Pair.first;
1862 BasicBlock::iterator LocalStartPos = Pair.second;
1863 BasicBlock::iterator StartBBBegin = LocalStartBB->begin();
1864 for (;;) {
1865 if (LocalStartPos == StartBBBegin) {
1866 pred_iterator PI(LocalStartBB), PE(LocalStartBB, false);
1867 if (PI == PE)
1868 // If we've reached the function entry, produce a null dependence.
1869 DependingInstructions.insert(0);
1870 else
1871 // Add the predecessors to the worklist.
1872 do {
1873 BasicBlock *PredBB = *PI;
1874 if (Visited.insert(PredBB))
1875 Worklist.push_back(std::make_pair(PredBB, PredBB->end()));
1876 } while (++PI != PE);
1877 break;
1878 }
1879
1880 Instruction *Inst = --LocalStartPos;
1881 if (Depends(Flavor, Inst, Arg, PA)) {
1882 DependingInstructions.insert(Inst);
1883 break;
1884 }
1885 }
1886 } while (!Worklist.empty());
1887
1888 // Determine whether the original StartBB post-dominates all of the blocks we
1889 // visited. If not, insert a sentinal indicating that most optimizations are
1890 // not safe.
1891 for (SmallPtrSet<const BasicBlock *, 4>::const_iterator I = Visited.begin(),
1892 E = Visited.end(); I != E; ++I) {
1893 const BasicBlock *BB = *I;
1894 if (BB == StartBB)
1895 continue;
1896 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
1897 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
1898 const BasicBlock *Succ = *SI;
1899 if (Succ != StartBB && !Visited.count(Succ)) {
1900 DependingInstructions.insert(reinterpret_cast<Instruction *>(-1));
1901 return;
1902 }
1903 }
1904 }
1905}
1906
1907static bool isNullOrUndef(const Value *V) {
1908 return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
1909}
1910
1911static bool isNoopInstruction(const Instruction *I) {
1912 return isa<BitCastInst>(I) ||
1913 (isa<GetElementPtrInst>(I) &&
1914 cast<GetElementPtrInst>(I)->hasAllZeroIndices());
1915}
1916
1917/// OptimizeRetainCall - Turn objc_retain into
1918/// objc_retainAutoreleasedReturnValue if the operand is a return value.
1919void
1920ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) {
1921 CallSite CS(GetObjCArg(Retain));
1922 Instruction *Call = CS.getInstruction();
1923 if (!Call) return;
1924 if (Call->getParent() != Retain->getParent()) return;
1925
1926 // Check that the call is next to the retain.
1927 BasicBlock::iterator I = Call;
1928 ++I;
1929 while (isNoopInstruction(I)) ++I;
1930 if (&*I != Retain)
1931 return;
1932
1933 // Turn it to an objc_retainAutoreleasedReturnValue..
1934 Changed = true;
1935 ++NumPeeps;
1936 cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent()));
1937}
1938
1939/// OptimizeRetainRVCall - Turn objc_retainAutoreleasedReturnValue into
1940/// objc_retain if the operand is not a return value. Or, if it can be
1941/// paired with an objc_autoreleaseReturnValue, delete the pair and
1942/// return true.
1943bool
1944ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
1945 // Check for the argument being from an immediately preceding call.
1946 Value *Arg = GetObjCArg(RetainRV);
1947 CallSite CS(Arg);
1948 if (Instruction *Call = CS.getInstruction())
1949 if (Call->getParent() == RetainRV->getParent()) {
1950 BasicBlock::iterator I = Call;
1951 ++I;
1952 while (isNoopInstruction(I)) ++I;
1953 if (&*I == RetainRV)
1954 return false;
1955 }
1956
1957 // Check for being preceded by an objc_autoreleaseReturnValue on the same
1958 // pointer. In this case, we can delete the pair.
1959 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
1960 if (I != Begin) {
1961 do --I; while (I != Begin && isNoopInstruction(I));
1962 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
1963 GetObjCArg(I) == Arg) {
1964 Changed = true;
1965 ++NumPeeps;
1966 EraseInstruction(I);
1967 EraseInstruction(RetainRV);
1968 return true;
1969 }
1970 }
1971
1972 // Turn it to a plain objc_retain.
1973 Changed = true;
1974 ++NumPeeps;
1975 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
1976 return false;
1977}
1978
1979/// OptimizeAutoreleaseRVCall - Turn objc_autoreleaseReturnValue into
1980/// objc_autorelease if the result is not used as a return value.
1981void
1982ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV) {
1983 // Check for a return of the pointer value.
1984 const Value *Ptr = GetObjCArg(AutoreleaseRV);
Dan Gohman126a54f2011-08-12 00:36:31 +00001985 SmallVector<const Value *, 2> Users;
1986 Users.push_back(Ptr);
1987 do {
1988 Ptr = Users.pop_back_val();
1989 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
1990 UI != UE; ++UI) {
1991 const User *I = *UI;
1992 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
1993 return;
1994 if (isa<BitCastInst>(I))
1995 Users.push_back(I);
1996 }
1997 } while (!Users.empty());
John McCall9fbd3182011-06-15 23:37:01 +00001998
1999 Changed = true;
2000 ++NumPeeps;
2001 cast<CallInst>(AutoreleaseRV)->
2002 setCalledFunction(getAutoreleaseCallee(F.getParent()));
2003}
2004
2005/// OptimizeIndividualCalls - Visit each call, one at a time, and make
2006/// simplifications without doing any additional analysis.
2007void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
2008 // Reset all the flags in preparation for recomputing them.
2009 UsedInThisFunction = 0;
2010
2011 // Visit all objc_* calls in F.
2012 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2013 Instruction *Inst = &*I++;
2014 InstructionClass Class = GetBasicInstructionClass(Inst);
2015
2016 switch (Class) {
2017 default: break;
2018
2019 // Delete no-op casts. These function calls have special semantics, but
2020 // the semantics are entirely implemented via lowering in the front-end,
2021 // so by the time they reach the optimizer, they are just no-op calls
2022 // which return their argument.
2023 //
2024 // There are gray areas here, as the ability to cast reference-counted
2025 // pointers to raw void* and back allows code to break ARC assumptions,
2026 // however these are currently considered to be unimportant.
2027 case IC_NoopCast:
2028 Changed = true;
2029 ++NumNoops;
2030 EraseInstruction(Inst);
2031 continue;
2032
2033 // If the pointer-to-weak-pointer is null, it's undefined behavior.
2034 case IC_StoreWeak:
2035 case IC_LoadWeak:
2036 case IC_LoadWeakRetained:
2037 case IC_InitWeak:
2038 case IC_DestroyWeak: {
2039 CallInst *CI = cast<CallInst>(Inst);
2040 if (isNullOrUndef(CI->getArgOperand(0))) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002041 Type *Ty = CI->getArgOperand(0)->getType();
John McCall9fbd3182011-06-15 23:37:01 +00002042 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2043 Constant::getNullValue(Ty),
2044 CI);
2045 CI->replaceAllUsesWith(UndefValue::get(CI->getType()));
2046 CI->eraseFromParent();
2047 continue;
2048 }
2049 break;
2050 }
2051 case IC_CopyWeak:
2052 case IC_MoveWeak: {
2053 CallInst *CI = cast<CallInst>(Inst);
2054 if (isNullOrUndef(CI->getArgOperand(0)) ||
2055 isNullOrUndef(CI->getArgOperand(1))) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002056 Type *Ty = CI->getArgOperand(0)->getType();
John McCall9fbd3182011-06-15 23:37:01 +00002057 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2058 Constant::getNullValue(Ty),
2059 CI);
2060 CI->replaceAllUsesWith(UndefValue::get(CI->getType()));
2061 CI->eraseFromParent();
2062 continue;
2063 }
2064 break;
2065 }
2066 case IC_Retain:
2067 OptimizeRetainCall(F, Inst);
2068 break;
2069 case IC_RetainRV:
2070 if (OptimizeRetainRVCall(F, Inst))
2071 continue;
2072 break;
2073 case IC_AutoreleaseRV:
2074 OptimizeAutoreleaseRVCall(F, Inst);
2075 break;
2076 }
2077
2078 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
2079 if (IsAutorelease(Class) && Inst->use_empty()) {
2080 CallInst *Call = cast<CallInst>(Inst);
2081 const Value *Arg = Call->getArgOperand(0);
2082 Arg = FindSingleUseIdentifiedObject(Arg);
2083 if (Arg) {
2084 Changed = true;
2085 ++NumAutoreleases;
2086
2087 // Create the declaration lazily.
2088 LLVMContext &C = Inst->getContext();
2089 CallInst *NewCall =
2090 CallInst::Create(getReleaseCallee(F.getParent()),
2091 Call->getArgOperand(0), "", Call);
2092 NewCall->setMetadata(ImpreciseReleaseMDKind,
2093 MDNode::get(C, ArrayRef<Value *>()));
2094 EraseInstruction(Call);
2095 Inst = NewCall;
2096 Class = IC_Release;
2097 }
2098 }
2099
2100 // For functions which can never be passed stack arguments, add
2101 // a tail keyword.
2102 if (IsAlwaysTail(Class)) {
2103 Changed = true;
2104 cast<CallInst>(Inst)->setTailCall();
2105 }
2106
2107 // Set nounwind as needed.
2108 if (IsNoThrow(Class)) {
2109 Changed = true;
2110 cast<CallInst>(Inst)->setDoesNotThrow();
2111 }
2112
2113 if (!IsNoopOnNull(Class)) {
2114 UsedInThisFunction |= 1 << Class;
2115 continue;
2116 }
2117
2118 const Value *Arg = GetObjCArg(Inst);
2119
2120 // ARC calls with null are no-ops. Delete them.
2121 if (isNullOrUndef(Arg)) {
2122 Changed = true;
2123 ++NumNoops;
2124 EraseInstruction(Inst);
2125 continue;
2126 }
2127
2128 // Keep track of which of retain, release, autorelease, and retain_block
2129 // are actually present in this function.
2130 UsedInThisFunction |= 1 << Class;
2131
2132 // If Arg is a PHI, and one or more incoming values to the
2133 // PHI are null, and the call is control-equivalent to the PHI, and there
2134 // are no relevant side effects between the PHI and the call, the call
2135 // could be pushed up to just those paths with non-null incoming values.
2136 // For now, don't bother splitting critical edges for this.
2137 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
2138 Worklist.push_back(std::make_pair(Inst, Arg));
2139 do {
2140 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
2141 Inst = Pair.first;
2142 Arg = Pair.second;
2143
2144 const PHINode *PN = dyn_cast<PHINode>(Arg);
2145 if (!PN) continue;
2146
2147 // Determine if the PHI has any null operands, or any incoming
2148 // critical edges.
2149 bool HasNull = false;
2150 bool HasCriticalEdges = false;
2151 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2152 Value *Incoming =
2153 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2154 if (isNullOrUndef(Incoming))
2155 HasNull = true;
2156 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
2157 .getNumSuccessors() != 1) {
2158 HasCriticalEdges = true;
2159 break;
2160 }
2161 }
2162 // If we have null operands and no critical edges, optimize.
2163 if (!HasCriticalEdges && HasNull) {
2164 SmallPtrSet<Instruction *, 4> DependingInstructions;
2165 SmallPtrSet<const BasicBlock *, 4> Visited;
2166
2167 // Check that there is nothing that cares about the reference
2168 // count between the call and the phi.
2169 FindDependencies(NeedsPositiveRetainCount, Arg,
2170 Inst->getParent(), Inst,
2171 DependingInstructions, Visited, PA);
2172 if (DependingInstructions.size() == 1 &&
2173 *DependingInstructions.begin() == PN) {
2174 Changed = true;
2175 ++NumPartialNoops;
2176 // Clone the call into each predecessor that has a non-null value.
2177 CallInst *CInst = cast<CallInst>(Inst);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002178 Type *ParamTy = CInst->getArgOperand(0)->getType();
John McCall9fbd3182011-06-15 23:37:01 +00002179 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2180 Value *Incoming =
2181 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2182 if (!isNullOrUndef(Incoming)) {
2183 CallInst *Clone = cast<CallInst>(CInst->clone());
2184 Value *Op = PN->getIncomingValue(i);
2185 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
2186 if (Op->getType() != ParamTy)
2187 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
2188 Clone->setArgOperand(0, Op);
2189 Clone->insertBefore(InsertPos);
2190 Worklist.push_back(std::make_pair(Clone, Incoming));
2191 }
2192 }
2193 // Erase the original call.
2194 EraseInstruction(CInst);
2195 continue;
2196 }
2197 }
2198 } while (!Worklist.empty());
2199 }
2200}
2201
2202/// CheckForCFGHazards - Check for critical edges, loop boundaries, irreducible
2203/// control flow, or other CFG structures where moving code across the edge
2204/// would result in it being executed more.
2205void
2206ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
2207 DenseMap<const BasicBlock *, BBState> &BBStates,
2208 BBState &MyStates) const {
2209 // If any top-down local-use or possible-dec has a succ which is earlier in
2210 // the sequence, forget it.
2211 for (BBState::ptr_const_iterator I = MyStates.top_down_ptr_begin(),
2212 E = MyStates.top_down_ptr_end(); I != E; ++I)
2213 switch (I->second.GetSeq()) {
2214 default: break;
2215 case S_Use: {
2216 const Value *Arg = I->first;
2217 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2218 bool SomeSuccHasSame = false;
2219 bool AllSuccsHaveSame = true;
Dan Gohmana7f7db22011-08-12 00:26:31 +00002220 PtrState &S = MyStates.getPtrTopDownState(Arg);
2221 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2222 PtrState &SuccS = BBStates[*SI].getPtrBottomUpState(Arg);
2223 switch (SuccS.GetSeq()) {
John McCall9fbd3182011-06-15 23:37:01 +00002224 case S_None:
Dan Gohmana7f7db22011-08-12 00:26:31 +00002225 case S_CanRelease: {
Dan Gohmane6d5e882011-08-19 00:26:36 +00002226 if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002227 S.ClearSequenceProgress();
2228 continue;
2229 }
John McCall9fbd3182011-06-15 23:37:01 +00002230 case S_Use:
2231 SomeSuccHasSame = true;
2232 break;
2233 case S_Stop:
2234 case S_Release:
2235 case S_MovableRelease:
Dan Gohmane6d5e882011-08-19 00:26:36 +00002236 if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002237 AllSuccsHaveSame = false;
John McCall9fbd3182011-06-15 23:37:01 +00002238 break;
2239 case S_Retain:
2240 llvm_unreachable("bottom-up pointer in retain state!");
2241 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002242 }
John McCall9fbd3182011-06-15 23:37:01 +00002243 // If the state at the other end of any of the successor edges
2244 // matches the current state, require all edges to match. This
2245 // guards against loops in the middle of a sequence.
2246 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002247 S.ClearSequenceProgress();
John McCall9fbd3182011-06-15 23:37:01 +00002248 }
2249 case S_CanRelease: {
2250 const Value *Arg = I->first;
2251 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2252 bool SomeSuccHasSame = false;
2253 bool AllSuccsHaveSame = true;
Dan Gohmana7f7db22011-08-12 00:26:31 +00002254 PtrState &S = MyStates.getPtrTopDownState(Arg);
2255 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2256 PtrState &SuccS = BBStates[*SI].getPtrBottomUpState(Arg);
2257 switch (SuccS.GetSeq()) {
2258 case S_None: {
Dan Gohmane6d5e882011-08-19 00:26:36 +00002259 if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002260 S.ClearSequenceProgress();
2261 continue;
2262 }
John McCall9fbd3182011-06-15 23:37:01 +00002263 case S_CanRelease:
2264 SomeSuccHasSame = true;
2265 break;
2266 case S_Stop:
2267 case S_Release:
2268 case S_MovableRelease:
2269 case S_Use:
Dan Gohmane6d5e882011-08-19 00:26:36 +00002270 if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002271 AllSuccsHaveSame = false;
John McCall9fbd3182011-06-15 23:37:01 +00002272 break;
2273 case S_Retain:
2274 llvm_unreachable("bottom-up pointer in retain state!");
2275 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002276 }
John McCall9fbd3182011-06-15 23:37:01 +00002277 // If the state at the other end of any of the successor edges
2278 // matches the current state, require all edges to match. This
2279 // guards against loops in the middle of a sequence.
2280 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002281 S.ClearSequenceProgress();
John McCall9fbd3182011-06-15 23:37:01 +00002282 }
2283 }
2284}
2285
2286bool
2287ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2288 DenseMap<const BasicBlock *, BBState> &BBStates,
2289 MapVector<Value *, RRInfo> &Retains) {
2290 bool NestingDetected = false;
2291 BBState &MyStates = BBStates[BB];
2292
2293 // Merge the states from each successor to compute the initial state
2294 // for the current block.
2295 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2296 succ_const_iterator SI(TI), SE(TI, false);
2297 if (SI == SE)
2298 MyStates.SetAsExit();
2299 else
2300 do {
2301 const BasicBlock *Succ = *SI++;
2302 if (Succ == BB)
2303 continue;
2304 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
Dan Gohmana7f7db22011-08-12 00:26:31 +00002305 // If we haven't seen this node yet, then we've found a CFG cycle.
2306 // Be optimistic here; it's CheckForCFGHazards' job detect trouble.
John McCall9fbd3182011-06-15 23:37:01 +00002307 if (I == BBStates.end())
2308 continue;
2309 MyStates.InitFromSucc(I->second);
2310 while (SI != SE) {
2311 Succ = *SI++;
2312 if (Succ != BB) {
2313 I = BBStates.find(Succ);
2314 if (I != BBStates.end())
2315 MyStates.MergeSucc(I->second);
2316 }
2317 }
2318 break;
2319 } while (SI != SE);
2320
2321 // Visit all the instructions, bottom-up.
2322 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2323 Instruction *Inst = llvm::prior(I);
2324 InstructionClass Class = GetInstructionClass(Inst);
2325 const Value *Arg = 0;
2326
2327 switch (Class) {
2328 case IC_Release: {
2329 Arg = GetObjCArg(Inst);
2330
2331 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2332
2333 // If we see two releases in a row on the same pointer. If so, make
2334 // a note, and we'll cicle back to revisit it after we've
2335 // hopefully eliminated the second release, which may allow us to
2336 // eliminate the first release too.
2337 // Theoretically we could implement removal of nested retain+release
2338 // pairs by making PtrState hold a stack of states, but this is
2339 // simple and avoids adding overhead for the non-nested case.
2340 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease)
2341 NestingDetected = true;
2342
2343 S.SetSeqToRelease(Inst->getMetadata(ImpreciseReleaseMDKind));
2344 S.RRI.clear();
Dan Gohmane6d5e882011-08-19 00:26:36 +00002345 S.RRI.KnownSafe = S.IsKnownNested() || S.IsKnownIncremented();
John McCall9fbd3182011-06-15 23:37:01 +00002346 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2347 S.RRI.Calls.insert(Inst);
2348
2349 S.IncrementRefCount();
Dan Gohmane6d5e882011-08-19 00:26:36 +00002350 S.IncrementNestCount();
John McCall9fbd3182011-06-15 23:37:01 +00002351 break;
2352 }
2353 case IC_RetainBlock:
2354 case IC_Retain:
2355 case IC_RetainRV: {
2356 Arg = GetObjCArg(Inst);
2357
2358 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2359 S.DecrementRefCount();
Dan Gohmana7f7db22011-08-12 00:26:31 +00002360 S.SetAtLeastOneRefCount();
Dan Gohmane6d5e882011-08-19 00:26:36 +00002361 S.DecrementNestCount();
John McCall9fbd3182011-06-15 23:37:01 +00002362
Dan Gohman597fece2011-09-29 22:25:23 +00002363 // An objc_retainBlock call with just a use still needs to be kept,
2364 // because it may be copying a block from the stack to the heap.
2365 if (Class == IC_RetainBlock && S.GetSeq() == S_Use)
2366 S.SetSeq(S_CanRelease);
2367
John McCall9fbd3182011-06-15 23:37:01 +00002368 switch (S.GetSeq()) {
2369 case S_Stop:
2370 case S_Release:
2371 case S_MovableRelease:
2372 case S_Use:
2373 S.RRI.ReverseInsertPts.clear();
2374 // FALL THROUGH
2375 case S_CanRelease:
2376 // Don't do retain+release tracking for IC_RetainRV, because it's
2377 // better to let it remain as the first instruction after a call.
2378 if (Class != IC_RetainRV) {
2379 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2380 Retains[Inst] = S.RRI;
2381 }
2382 S.ClearSequenceProgress();
2383 break;
2384 case S_None:
2385 break;
2386 case S_Retain:
2387 llvm_unreachable("bottom-up pointer in retain state!");
2388 }
Dan Gohmane6d5e882011-08-19 00:26:36 +00002389 continue;
John McCall9fbd3182011-06-15 23:37:01 +00002390 }
2391 case IC_AutoreleasepoolPop:
2392 // Conservatively, clear MyStates for all known pointers.
2393 MyStates.clearBottomUpPointers();
2394 continue;
2395 case IC_AutoreleasepoolPush:
2396 case IC_None:
2397 // These are irrelevant.
2398 continue;
2399 default:
2400 break;
2401 }
2402
2403 // Consider any other possible effects of this instruction on each
2404 // pointer being tracked.
2405 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
2406 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
2407 const Value *Ptr = MI->first;
2408 if (Ptr == Arg)
2409 continue; // Handled above.
2410 PtrState &S = MI->second;
2411 Sequence Seq = S.GetSeq();
2412
Dan Gohmane6d5e882011-08-19 00:26:36 +00002413 // Check for possible releases.
2414 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2415 S.DecrementRefCount();
Dan Gohmana7f7db22011-08-12 00:26:31 +00002416 switch (Seq) {
2417 case S_Use:
2418 S.SetSeq(S_CanRelease);
2419 continue;
2420 case S_CanRelease:
2421 case S_Release:
2422 case S_MovableRelease:
2423 case S_Stop:
2424 case S_None:
2425 break;
2426 case S_Retain:
2427 llvm_unreachable("bottom-up pointer in retain state!");
2428 }
Dan Gohmane6d5e882011-08-19 00:26:36 +00002429 }
John McCall9fbd3182011-06-15 23:37:01 +00002430
2431 // Check for possible direct uses.
2432 switch (Seq) {
2433 case S_Release:
2434 case S_MovableRelease:
2435 if (CanUse(Inst, Ptr, PA, Class)) {
Dan Gohman597fece2011-09-29 22:25:23 +00002436 assert(S.RRI.ReverseInsertPts.empty());
John McCall9fbd3182011-06-15 23:37:01 +00002437 S.RRI.ReverseInsertPts.insert(Inst);
2438 S.SetSeq(S_Use);
2439 } else if (Seq == S_Release &&
2440 (Class == IC_User || Class == IC_CallOrUser)) {
2441 // Non-movable releases depend on any possible objc pointer use.
2442 S.SetSeq(S_Stop);
Dan Gohman597fece2011-09-29 22:25:23 +00002443 assert(S.RRI.ReverseInsertPts.empty());
John McCall9fbd3182011-06-15 23:37:01 +00002444 S.RRI.ReverseInsertPts.insert(Inst);
2445 }
2446 break;
2447 case S_Stop:
2448 if (CanUse(Inst, Ptr, PA, Class))
2449 S.SetSeq(S_Use);
2450 break;
2451 case S_CanRelease:
2452 case S_Use:
2453 case S_None:
2454 break;
2455 case S_Retain:
2456 llvm_unreachable("bottom-up pointer in retain state!");
2457 }
2458 }
2459 }
2460
2461 return NestingDetected;
2462}
2463
2464bool
2465ObjCARCOpt::VisitTopDown(BasicBlock *BB,
2466 DenseMap<const BasicBlock *, BBState> &BBStates,
2467 DenseMap<Value *, RRInfo> &Releases) {
2468 bool NestingDetected = false;
2469 BBState &MyStates = BBStates[BB];
2470
2471 // Merge the states from each predecessor to compute the initial state
2472 // for the current block.
2473 const_pred_iterator PI(BB), PE(BB, false);
2474 if (PI == PE)
2475 MyStates.SetAsEntry();
2476 else
2477 do {
2478 const BasicBlock *Pred = *PI++;
2479 if (Pred == BB)
2480 continue;
2481 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
Dan Gohmana7f7db22011-08-12 00:26:31 +00002482 assert(I != BBStates.end());
2483 // If we haven't seen this node yet, then we've found a CFG cycle.
2484 // Be optimistic here; it's CheckForCFGHazards' job detect trouble.
2485 if (!I->second.isVisitedTopDown())
John McCall9fbd3182011-06-15 23:37:01 +00002486 continue;
2487 MyStates.InitFromPred(I->second);
2488 while (PI != PE) {
2489 Pred = *PI++;
2490 if (Pred != BB) {
2491 I = BBStates.find(Pred);
Dan Gohmana7f7db22011-08-12 00:26:31 +00002492 assert(I != BBStates.end());
2493 if (I->second.isVisitedTopDown())
John McCall9fbd3182011-06-15 23:37:01 +00002494 MyStates.MergePred(I->second);
2495 }
2496 }
2497 break;
2498 } while (PI != PE);
2499
2500 // Visit all the instructions, top-down.
2501 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2502 Instruction *Inst = I;
2503 InstructionClass Class = GetInstructionClass(Inst);
2504 const Value *Arg = 0;
2505
2506 switch (Class) {
2507 case IC_RetainBlock:
2508 case IC_Retain:
2509 case IC_RetainRV: {
2510 Arg = GetObjCArg(Inst);
2511
2512 PtrState &S = MyStates.getPtrTopDownState(Arg);
2513
2514 // Don't do retain+release tracking for IC_RetainRV, because it's
2515 // better to let it remain as the first instruction after a call.
2516 if (Class != IC_RetainRV) {
2517 // If we see two retains in a row on the same pointer. If so, make
2518 // a note, and we'll cicle back to revisit it after we've
2519 // hopefully eliminated the second retain, which may allow us to
2520 // eliminate the first retain too.
2521 // Theoretically we could implement removal of nested retain+release
2522 // pairs by making PtrState hold a stack of states, but this is
2523 // simple and avoids adding overhead for the non-nested case.
2524 if (S.GetSeq() == S_Retain)
2525 NestingDetected = true;
2526
2527 S.SetSeq(S_Retain);
2528 S.RRI.clear();
2529 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
Dan Gohmane6d5e882011-08-19 00:26:36 +00002530 // Don't check S.IsKnownIncremented() here because it's not
2531 // sufficient.
2532 S.RRI.KnownSafe = S.IsKnownNested();
John McCall9fbd3182011-06-15 23:37:01 +00002533 S.RRI.Calls.insert(Inst);
2534 }
2535
Dan Gohmana7f7db22011-08-12 00:26:31 +00002536 S.SetAtLeastOneRefCount();
John McCall9fbd3182011-06-15 23:37:01 +00002537 S.IncrementRefCount();
Dan Gohmane6d5e882011-08-19 00:26:36 +00002538 S.IncrementNestCount();
2539 continue;
John McCall9fbd3182011-06-15 23:37:01 +00002540 }
2541 case IC_Release: {
2542 Arg = GetObjCArg(Inst);
2543
2544 PtrState &S = MyStates.getPtrTopDownState(Arg);
2545 S.DecrementRefCount();
Dan Gohmane6d5e882011-08-19 00:26:36 +00002546 S.DecrementNestCount();
John McCall9fbd3182011-06-15 23:37:01 +00002547
2548 switch (S.GetSeq()) {
2549 case S_Retain:
2550 case S_CanRelease:
2551 S.RRI.ReverseInsertPts.clear();
2552 // FALL THROUGH
2553 case S_Use:
2554 S.RRI.ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2555 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2556 Releases[Inst] = S.RRI;
2557 S.ClearSequenceProgress();
2558 break;
2559 case S_None:
2560 break;
2561 case S_Stop:
2562 case S_Release:
2563 case S_MovableRelease:
2564 llvm_unreachable("top-down pointer in release state!");
2565 }
2566 break;
2567 }
2568 case IC_AutoreleasepoolPop:
2569 // Conservatively, clear MyStates for all known pointers.
2570 MyStates.clearTopDownPointers();
2571 continue;
2572 case IC_AutoreleasepoolPush:
2573 case IC_None:
2574 // These are irrelevant.
2575 continue;
2576 default:
2577 break;
2578 }
2579
2580 // Consider any other possible effects of this instruction on each
2581 // pointer being tracked.
2582 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
2583 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
2584 const Value *Ptr = MI->first;
2585 if (Ptr == Arg)
2586 continue; // Handled above.
2587 PtrState &S = MI->second;
2588 Sequence Seq = S.GetSeq();
2589
Dan Gohmane6d5e882011-08-19 00:26:36 +00002590 // Check for possible releases.
2591 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2592 S.DecrementRefCount();
John McCall9fbd3182011-06-15 23:37:01 +00002593 switch (Seq) {
2594 case S_Retain:
2595 S.SetSeq(S_CanRelease);
Dan Gohman597fece2011-09-29 22:25:23 +00002596 assert(S.RRI.ReverseInsertPts.empty());
John McCall9fbd3182011-06-15 23:37:01 +00002597 S.RRI.ReverseInsertPts.insert(Inst);
2598
2599 // One call can't cause a transition from S_Retain to S_CanRelease
2600 // and S_CanRelease to S_Use. If we've made the first transition,
2601 // we're done.
2602 continue;
2603 case S_Use:
2604 case S_CanRelease:
2605 case S_None:
2606 break;
2607 case S_Stop:
2608 case S_Release:
2609 case S_MovableRelease:
2610 llvm_unreachable("top-down pointer in release 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_CanRelease:
2617 if (CanUse(Inst, Ptr, PA, Class))
2618 S.SetSeq(S_Use);
2619 break;
John McCall9fbd3182011-06-15 23:37:01 +00002620 case S_Retain:
Dan Gohman597fece2011-09-29 22:25:23 +00002621 // An objc_retainBlock call may be responsible for copying the block
2622 // data from the stack to the heap. Model this by moving it straight
2623 // from S_Retain to S_Use.
2624 if (S.RRI.IsRetainBlock &&
2625 CanUse(Inst, Ptr, PA, Class)) {
2626 assert(S.RRI.ReverseInsertPts.empty());
2627 S.RRI.ReverseInsertPts.insert(Inst);
2628 S.SetSeq(S_Use);
2629 }
2630 break;
2631 case S_Use:
John McCall9fbd3182011-06-15 23:37:01 +00002632 case S_None:
2633 break;
2634 case S_Stop:
2635 case S_Release:
2636 case S_MovableRelease:
2637 llvm_unreachable("top-down pointer in release state!");
2638 }
2639 }
2640 }
2641
2642 CheckForCFGHazards(BB, BBStates, MyStates);
2643 return NestingDetected;
2644}
2645
2646// Visit - Visit the function both top-down and bottom-up.
2647bool
2648ObjCARCOpt::Visit(Function &F,
2649 DenseMap<const BasicBlock *, BBState> &BBStates,
2650 MapVector<Value *, RRInfo> &Retains,
2651 DenseMap<Value *, RRInfo> &Releases) {
Dan Gohmand8e48c42011-08-12 00:24:29 +00002652 // Use reverse-postorder on the reverse CFG for bottom-up, because we
John McCall9fbd3182011-06-15 23:37:01 +00002653 // magically know that loops will be well behaved, i.e. they won't repeatedly
Dan Gohmand8e48c42011-08-12 00:24:29 +00002654 // call retain on a single pointer without doing a release. We can't use
2655 // ReversePostOrderTraversal here because we want to walk up from each
2656 // function exit point.
2657 SmallPtrSet<BasicBlock *, 16> Visited;
2658 SmallVector<std::pair<BasicBlock *, pred_iterator>, 16> Stack;
2659 SmallVector<BasicBlock *, 16> Order;
2660 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
2661 BasicBlock *BB = I;
2662 if (BB->getTerminator()->getNumSuccessors() == 0)
2663 Stack.push_back(std::make_pair(BB, pred_begin(BB)));
2664 }
2665 while (!Stack.empty()) {
2666 pred_iterator End = pred_end(Stack.back().first);
2667 while (Stack.back().second != End) {
2668 BasicBlock *BB = *Stack.back().second++;
2669 if (Visited.insert(BB))
2670 Stack.push_back(std::make_pair(BB, pred_begin(BB)));
2671 }
2672 Order.push_back(Stack.pop_back_val().first);
2673 }
John McCall9fbd3182011-06-15 23:37:01 +00002674 bool BottomUpNestingDetected = false;
Dan Gohmanb48ef3a2011-08-18 21:27:42 +00002675 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2676 Order.rbegin(), E = Order.rend(); I != E; ++I) {
2677 BasicBlock *BB = *I;
John McCall9fbd3182011-06-15 23:37:01 +00002678 BottomUpNestingDetected |= VisitBottomUp(BB, BBStates, Retains);
2679 }
2680
Dan Gohmand8e48c42011-08-12 00:24:29 +00002681 // Use regular reverse-postorder for top-down.
John McCall9fbd3182011-06-15 23:37:01 +00002682 bool TopDownNestingDetected = false;
Dan Gohmand8e48c42011-08-12 00:24:29 +00002683 typedef ReversePostOrderTraversal<Function *> RPOTType;
2684 RPOTType RPOT(&F);
2685 for (RPOTType::rpo_iterator I = RPOT.begin(), E = RPOT.end(); I != E; ++I) {
2686 BasicBlock *BB = *I;
2687 TopDownNestingDetected |= VisitTopDown(BB, BBStates, Releases);
2688 }
John McCall9fbd3182011-06-15 23:37:01 +00002689
2690 return TopDownNestingDetected && BottomUpNestingDetected;
2691}
2692
2693/// MoveCalls - Move the calls in RetainsToMove and ReleasesToMove.
2694void ObjCARCOpt::MoveCalls(Value *Arg,
2695 RRInfo &RetainsToMove,
2696 RRInfo &ReleasesToMove,
2697 MapVector<Value *, RRInfo> &Retains,
2698 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman44280692011-07-22 22:29:21 +00002699 SmallVectorImpl<Instruction *> &DeadInsts,
2700 Module *M) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002701 Type *ArgTy = Arg->getType();
Dan Gohman44280692011-07-22 22:29:21 +00002702 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
John McCall9fbd3182011-06-15 23:37:01 +00002703
2704 // Insert the new retain and release calls.
2705 for (SmallPtrSet<Instruction *, 2>::const_iterator
2706 PI = ReleasesToMove.ReverseInsertPts.begin(),
2707 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2708 Instruction *InsertPt = *PI;
2709 Value *MyArg = ArgTy == ParamTy ? Arg :
2710 new BitCastInst(Arg, ParamTy, "", InsertPt);
2711 CallInst *Call =
2712 CallInst::Create(RetainsToMove.IsRetainBlock ?
Dan Gohman44280692011-07-22 22:29:21 +00002713 getRetainBlockCallee(M) : getRetainCallee(M),
John McCall9fbd3182011-06-15 23:37:01 +00002714 MyArg, "", InsertPt);
2715 Call->setDoesNotThrow();
2716 if (!RetainsToMove.IsRetainBlock)
2717 Call->setTailCall();
2718 }
2719 for (SmallPtrSet<Instruction *, 2>::const_iterator
2720 PI = RetainsToMove.ReverseInsertPts.begin(),
2721 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
Dan Gohman0860d0b2011-06-16 20:57:14 +00002722 Instruction *LastUse = *PI;
2723 Instruction *InsertPts[] = { 0, 0, 0 };
2724 if (InvokeInst *II = dyn_cast<InvokeInst>(LastUse)) {
2725 // We can't insert code immediately after an invoke instruction, so
2726 // insert code at the beginning of both successor blocks instead.
2727 // The invoke's return value isn't available in the unwind block,
2728 // but our releases will never depend on it, because they must be
2729 // paired with retains from before the invoke.
Bill Wendling89d44112011-08-25 01:08:34 +00002730 InsertPts[0] = II->getNormalDest()->getFirstInsertionPt();
2731 InsertPts[1] = II->getUnwindDest()->getFirstInsertionPt();
Dan Gohman0860d0b2011-06-16 20:57:14 +00002732 } else {
2733 // Insert code immediately after the last use.
2734 InsertPts[0] = llvm::next(BasicBlock::iterator(LastUse));
2735 }
2736
2737 for (Instruction **I = InsertPts; *I; ++I) {
2738 Instruction *InsertPt = *I;
2739 Value *MyArg = ArgTy == ParamTy ? Arg :
2740 new BitCastInst(Arg, ParamTy, "", InsertPt);
Dan Gohman44280692011-07-22 22:29:21 +00002741 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
2742 "", InsertPt);
Dan Gohman0860d0b2011-06-16 20:57:14 +00002743 // Attach a clang.imprecise_release metadata tag, if appropriate.
2744 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
2745 Call->setMetadata(ImpreciseReleaseMDKind, M);
2746 Call->setDoesNotThrow();
2747 if (ReleasesToMove.IsTailCallRelease)
2748 Call->setTailCall();
2749 }
John McCall9fbd3182011-06-15 23:37:01 +00002750 }
2751
2752 // Delete the original retain and release calls.
2753 for (SmallPtrSet<Instruction *, 2>::const_iterator
2754 AI = RetainsToMove.Calls.begin(),
2755 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
2756 Instruction *OrigRetain = *AI;
2757 Retains.blot(OrigRetain);
2758 DeadInsts.push_back(OrigRetain);
2759 }
2760 for (SmallPtrSet<Instruction *, 2>::const_iterator
2761 AI = ReleasesToMove.Calls.begin(),
2762 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
2763 Instruction *OrigRelease = *AI;
2764 Releases.erase(OrigRelease);
2765 DeadInsts.push_back(OrigRelease);
2766 }
2767}
2768
2769bool
2770ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
2771 &BBStates,
2772 MapVector<Value *, RRInfo> &Retains,
Dan Gohman44280692011-07-22 22:29:21 +00002773 DenseMap<Value *, RRInfo> &Releases,
2774 Module *M) {
John McCall9fbd3182011-06-15 23:37:01 +00002775 bool AnyPairsCompletelyEliminated = false;
2776 RRInfo RetainsToMove;
2777 RRInfo ReleasesToMove;
2778 SmallVector<Instruction *, 4> NewRetains;
2779 SmallVector<Instruction *, 4> NewReleases;
2780 SmallVector<Instruction *, 8> DeadInsts;
2781
2782 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
Dan Gohman597fece2011-09-29 22:25:23 +00002783 E = Retains.end(); I != E; ++I) {
2784 Value *V = I->first;
John McCall9fbd3182011-06-15 23:37:01 +00002785 if (!V) continue; // blotted
2786
2787 Instruction *Retain = cast<Instruction>(V);
2788 Value *Arg = GetObjCArg(Retain);
2789
Dan Gohman597fece2011-09-29 22:25:23 +00002790 // If the object being released is in static storage, we know it's
John McCall9fbd3182011-06-15 23:37:01 +00002791 // not being managed by ObjC reference counting, so we can delete pairs
2792 // regardless of what possible decrements or uses lie between them.
Dan Gohman597fece2011-09-29 22:25:23 +00002793 bool KnownSafe = isa<Constant>(Arg);
2794
2795 // Same for stack storage, unless this is an objc_retainBlock call,
2796 // which is responsible for copying the block data from the stack to
2797 // the heap.
2798 if (!I->second.IsRetainBlock && isa<AllocaInst>(Arg))
2799 KnownSafe = true;
John McCall9fbd3182011-06-15 23:37:01 +00002800
Dan Gohman1b31ea82011-08-22 17:29:11 +00002801 // A constant pointer can't be pointing to an object on the heap. It may
2802 // be reference-counted, but it won't be deleted.
2803 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
2804 if (const GlobalVariable *GV =
2805 dyn_cast<GlobalVariable>(
2806 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
2807 if (GV->isConstant())
2808 KnownSafe = true;
2809
John McCall9fbd3182011-06-15 23:37:01 +00002810 // If a pair happens in a region where it is known that the reference count
2811 // is already incremented, we can similarly ignore possible decrements.
Dan Gohmane6d5e882011-08-19 00:26:36 +00002812 bool KnownSafeTD = true, KnownSafeBU = true;
John McCall9fbd3182011-06-15 23:37:01 +00002813
2814 // Connect the dots between the top-down-collected RetainsToMove and
2815 // bottom-up-collected ReleasesToMove to form sets of related calls.
2816 // This is an iterative process so that we connect multiple releases
2817 // to multiple retains if needed.
2818 unsigned OldDelta = 0;
2819 unsigned NewDelta = 0;
2820 unsigned OldCount = 0;
2821 unsigned NewCount = 0;
2822 bool FirstRelease = true;
2823 bool FirstRetain = true;
2824 NewRetains.push_back(Retain);
2825 for (;;) {
2826 for (SmallVectorImpl<Instruction *>::const_iterator
2827 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
2828 Instruction *NewRetain = *NI;
2829 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
2830 assert(It != Retains.end());
2831 const RRInfo &NewRetainRRI = It->second;
Dan Gohmane6d5e882011-08-19 00:26:36 +00002832 KnownSafeTD &= NewRetainRRI.KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00002833 for (SmallPtrSet<Instruction *, 2>::const_iterator
2834 LI = NewRetainRRI.Calls.begin(),
2835 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
2836 Instruction *NewRetainRelease = *LI;
2837 DenseMap<Value *, RRInfo>::const_iterator Jt =
2838 Releases.find(NewRetainRelease);
2839 if (Jt == Releases.end())
2840 goto next_retain;
2841 const RRInfo &NewRetainReleaseRRI = Jt->second;
2842 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
2843 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
2844 OldDelta -=
2845 BBStates[NewRetainRelease->getParent()].GetAllPathCount();
2846
2847 // Merge the ReleaseMetadata and IsTailCallRelease values.
2848 if (FirstRelease) {
2849 ReleasesToMove.ReleaseMetadata =
2850 NewRetainReleaseRRI.ReleaseMetadata;
2851 ReleasesToMove.IsTailCallRelease =
2852 NewRetainReleaseRRI.IsTailCallRelease;
2853 FirstRelease = false;
2854 } else {
2855 if (ReleasesToMove.ReleaseMetadata !=
2856 NewRetainReleaseRRI.ReleaseMetadata)
2857 ReleasesToMove.ReleaseMetadata = 0;
2858 if (ReleasesToMove.IsTailCallRelease !=
2859 NewRetainReleaseRRI.IsTailCallRelease)
2860 ReleasesToMove.IsTailCallRelease = false;
2861 }
2862
2863 // Collect the optimal insertion points.
2864 if (!KnownSafe)
2865 for (SmallPtrSet<Instruction *, 2>::const_iterator
2866 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
2867 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
2868 RI != RE; ++RI) {
2869 Instruction *RIP = *RI;
2870 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
2871 NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
2872 }
2873 NewReleases.push_back(NewRetainRelease);
2874 }
2875 }
2876 }
2877 NewRetains.clear();
2878 if (NewReleases.empty()) break;
2879
2880 // Back the other way.
2881 for (SmallVectorImpl<Instruction *>::const_iterator
2882 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
2883 Instruction *NewRelease = *NI;
2884 DenseMap<Value *, RRInfo>::const_iterator It =
2885 Releases.find(NewRelease);
2886 assert(It != Releases.end());
2887 const RRInfo &NewReleaseRRI = It->second;
Dan Gohmane6d5e882011-08-19 00:26:36 +00002888 KnownSafeBU &= NewReleaseRRI.KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00002889 for (SmallPtrSet<Instruction *, 2>::const_iterator
2890 LI = NewReleaseRRI.Calls.begin(),
2891 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
2892 Instruction *NewReleaseRetain = *LI;
2893 MapVector<Value *, RRInfo>::const_iterator Jt =
2894 Retains.find(NewReleaseRetain);
2895 if (Jt == Retains.end())
2896 goto next_retain;
2897 const RRInfo &NewReleaseRetainRRI = Jt->second;
2898 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
2899 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
2900 unsigned PathCount =
2901 BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
2902 OldDelta += PathCount;
2903 OldCount += PathCount;
2904
2905 // Merge the IsRetainBlock values.
2906 if (FirstRetain) {
2907 RetainsToMove.IsRetainBlock = NewReleaseRetainRRI.IsRetainBlock;
2908 FirstRetain = false;
2909 } else if (ReleasesToMove.IsRetainBlock !=
2910 NewReleaseRetainRRI.IsRetainBlock)
2911 // It's not possible to merge the sequences if one uses
2912 // objc_retain and the other uses objc_retainBlock.
2913 goto next_retain;
2914
2915 // Collect the optimal insertion points.
2916 if (!KnownSafe)
2917 for (SmallPtrSet<Instruction *, 2>::const_iterator
2918 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
2919 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
2920 RI != RE; ++RI) {
2921 Instruction *RIP = *RI;
2922 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
2923 PathCount = BBStates[RIP->getParent()].GetAllPathCount();
2924 NewDelta += PathCount;
2925 NewCount += PathCount;
2926 }
2927 }
2928 NewRetains.push_back(NewReleaseRetain);
2929 }
2930 }
2931 }
2932 NewReleases.clear();
2933 if (NewRetains.empty()) break;
2934 }
2935
Dan Gohmane6d5e882011-08-19 00:26:36 +00002936 // If the pointer is known incremented or nested, we can safely delete the
2937 // pair regardless of what's between them.
2938 if (KnownSafeTD || KnownSafeBU) {
John McCall9fbd3182011-06-15 23:37:01 +00002939 RetainsToMove.ReverseInsertPts.clear();
2940 ReleasesToMove.ReverseInsertPts.clear();
2941 NewCount = 0;
Dan Gohmana7f7db22011-08-12 00:26:31 +00002942 } else {
2943 // Determine whether the new insertion points we computed preserve the
2944 // balance of retain and release calls through the program.
2945 // TODO: If the fully aggressive solution isn't valid, try to find a
2946 // less aggressive solution which is.
2947 if (NewDelta != 0)
2948 goto next_retain;
John McCall9fbd3182011-06-15 23:37:01 +00002949 }
2950
2951 // Determine whether the original call points are balanced in the retain and
2952 // release calls through the program. If not, conservatively don't touch
2953 // them.
2954 // TODO: It's theoretically possible to do code motion in this case, as
2955 // long as the existing imbalances are maintained.
2956 if (OldDelta != 0)
2957 goto next_retain;
2958
John McCall9fbd3182011-06-15 23:37:01 +00002959 // Ok, everything checks out and we're all set. Let's move some code!
2960 Changed = true;
2961 AnyPairsCompletelyEliminated = NewCount == 0;
2962 NumRRs += OldCount - NewCount;
Dan Gohman44280692011-07-22 22:29:21 +00002963 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
2964 Retains, Releases, DeadInsts, M);
John McCall9fbd3182011-06-15 23:37:01 +00002965
2966 next_retain:
2967 NewReleases.clear();
2968 NewRetains.clear();
2969 RetainsToMove.clear();
2970 ReleasesToMove.clear();
2971 }
2972
2973 // Now that we're done moving everything, we can delete the newly dead
2974 // instructions, as we no longer need them as insert points.
2975 while (!DeadInsts.empty())
2976 EraseInstruction(DeadInsts.pop_back_val());
2977
2978 return AnyPairsCompletelyEliminated;
2979}
2980
2981/// OptimizeWeakCalls - Weak pointer optimizations.
2982void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
2983 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
2984 // itself because it uses AliasAnalysis and we need to do provenance
2985 // queries instead.
2986 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2987 Instruction *Inst = &*I++;
2988 InstructionClass Class = GetBasicInstructionClass(Inst);
2989 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
2990 continue;
2991
2992 // Delete objc_loadWeak calls with no users.
2993 if (Class == IC_LoadWeak && Inst->use_empty()) {
2994 Inst->eraseFromParent();
2995 continue;
2996 }
2997
2998 // TODO: For now, just look for an earlier available version of this value
2999 // within the same block. Theoretically, we could do memdep-style non-local
3000 // analysis too, but that would want caching. A better approach would be to
3001 // use the technique that EarlyCSE uses.
3002 inst_iterator Current = llvm::prior(I);
3003 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
3004 for (BasicBlock::iterator B = CurrentBB->begin(),
3005 J = Current.getInstructionIterator();
3006 J != B; --J) {
3007 Instruction *EarlierInst = &*llvm::prior(J);
3008 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
3009 switch (EarlierClass) {
3010 case IC_LoadWeak:
3011 case IC_LoadWeakRetained: {
3012 // If this is loading from the same pointer, replace this load's value
3013 // with that one.
3014 CallInst *Call = cast<CallInst>(Inst);
3015 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3016 Value *Arg = Call->getArgOperand(0);
3017 Value *EarlierArg = EarlierCall->getArgOperand(0);
3018 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3019 case AliasAnalysis::MustAlias:
3020 Changed = true;
3021 // If the load has a builtin retain, insert a plain retain for it.
3022 if (Class == IC_LoadWeakRetained) {
3023 CallInst *CI =
3024 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3025 "", Call);
3026 CI->setTailCall();
3027 }
3028 // Zap the fully redundant load.
3029 Call->replaceAllUsesWith(EarlierCall);
3030 Call->eraseFromParent();
3031 goto clobbered;
3032 case AliasAnalysis::MayAlias:
3033 case AliasAnalysis::PartialAlias:
3034 goto clobbered;
3035 case AliasAnalysis::NoAlias:
3036 break;
3037 }
3038 break;
3039 }
3040 case IC_StoreWeak:
3041 case IC_InitWeak: {
3042 // If this is storing to the same pointer and has the same size etc.
3043 // replace this load's value with the stored value.
3044 CallInst *Call = cast<CallInst>(Inst);
3045 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3046 Value *Arg = Call->getArgOperand(0);
3047 Value *EarlierArg = EarlierCall->getArgOperand(0);
3048 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3049 case AliasAnalysis::MustAlias:
3050 Changed = true;
3051 // If the load has a builtin retain, insert a plain retain for it.
3052 if (Class == IC_LoadWeakRetained) {
3053 CallInst *CI =
3054 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3055 "", Call);
3056 CI->setTailCall();
3057 }
3058 // Zap the fully redundant load.
3059 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
3060 Call->eraseFromParent();
3061 goto clobbered;
3062 case AliasAnalysis::MayAlias:
3063 case AliasAnalysis::PartialAlias:
3064 goto clobbered;
3065 case AliasAnalysis::NoAlias:
3066 break;
3067 }
3068 break;
3069 }
3070 case IC_MoveWeak:
3071 case IC_CopyWeak:
3072 // TOOD: Grab the copied value.
3073 goto clobbered;
3074 case IC_AutoreleasepoolPush:
3075 case IC_None:
3076 case IC_User:
3077 // Weak pointers are only modified through the weak entry points
3078 // (and arbitrary calls, which could call the weak entry points).
3079 break;
3080 default:
3081 // Anything else could modify the weak pointer.
3082 goto clobbered;
3083 }
3084 }
3085 clobbered:;
3086 }
3087
3088 // Then, for each destroyWeak with an alloca operand, check to see if
3089 // the alloca and all its users can be zapped.
3090 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3091 Instruction *Inst = &*I++;
3092 InstructionClass Class = GetBasicInstructionClass(Inst);
3093 if (Class != IC_DestroyWeak)
3094 continue;
3095
3096 CallInst *Call = cast<CallInst>(Inst);
3097 Value *Arg = Call->getArgOperand(0);
3098 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
3099 for (Value::use_iterator UI = Alloca->use_begin(),
3100 UE = Alloca->use_end(); UI != UE; ++UI) {
3101 Instruction *UserInst = cast<Instruction>(*UI);
3102 switch (GetBasicInstructionClass(UserInst)) {
3103 case IC_InitWeak:
3104 case IC_StoreWeak:
3105 case IC_DestroyWeak:
3106 continue;
3107 default:
3108 goto done;
3109 }
3110 }
3111 Changed = true;
3112 for (Value::use_iterator UI = Alloca->use_begin(),
3113 UE = Alloca->use_end(); UI != UE; ) {
3114 CallInst *UserInst = cast<CallInst>(*UI++);
3115 if (!UserInst->use_empty())
3116 UserInst->replaceAllUsesWith(UserInst->getOperand(1));
3117 UserInst->eraseFromParent();
3118 }
3119 Alloca->eraseFromParent();
3120 done:;
3121 }
3122 }
3123}
3124
3125/// OptimizeSequences - Identify program paths which execute sequences of
3126/// retains and releases which can be eliminated.
3127bool ObjCARCOpt::OptimizeSequences(Function &F) {
3128 /// Releases, Retains - These are used to store the results of the main flow
3129 /// analysis. These use Value* as the key instead of Instruction* so that the
3130 /// map stays valid when we get around to rewriting code and calls get
3131 /// replaced by arguments.
3132 DenseMap<Value *, RRInfo> Releases;
3133 MapVector<Value *, RRInfo> Retains;
3134
3135 /// BBStates, This is used during the traversal of the function to track the
3136 /// states for each identified object at each block.
3137 DenseMap<const BasicBlock *, BBState> BBStates;
3138
3139 // Analyze the CFG of the function, and all instructions.
3140 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
3141
3142 // Transform.
Dan Gohman44280692011-07-22 22:29:21 +00003143 return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) &&
3144 NestingDetected;
John McCall9fbd3182011-06-15 23:37:01 +00003145}
3146
3147/// OptimizeReturns - Look for this pattern:
3148///
3149/// %call = call i8* @something(...)
3150/// %2 = call i8* @objc_retain(i8* %call)
3151/// %3 = call i8* @objc_autorelease(i8* %2)
3152/// ret i8* %3
3153///
3154/// And delete the retain and autorelease.
3155///
3156/// Otherwise if it's just this:
3157///
3158/// %3 = call i8* @objc_autorelease(i8* %2)
3159/// ret i8* %3
3160///
3161/// convert the autorelease to autoreleaseRV.
3162void ObjCARCOpt::OptimizeReturns(Function &F) {
3163 if (!F.getReturnType()->isPointerTy())
3164 return;
3165
3166 SmallPtrSet<Instruction *, 4> DependingInstructions;
3167 SmallPtrSet<const BasicBlock *, 4> Visited;
3168 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3169 BasicBlock *BB = FI;
3170 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
3171 if (!Ret) continue;
3172
3173 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
3174 FindDependencies(NeedsPositiveRetainCount, Arg,
3175 BB, Ret, DependingInstructions, Visited, PA);
3176 if (DependingInstructions.size() != 1)
3177 goto next_block;
3178
3179 {
3180 CallInst *Autorelease =
3181 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3182 if (!Autorelease)
3183 goto next_block;
3184 InstructionClass AutoreleaseClass =
3185 GetBasicInstructionClass(Autorelease);
3186 if (!IsAutorelease(AutoreleaseClass))
3187 goto next_block;
3188 if (GetObjCArg(Autorelease) != Arg)
3189 goto next_block;
3190
3191 DependingInstructions.clear();
3192 Visited.clear();
3193
3194 // Check that there is nothing that can affect the reference
3195 // count between the autorelease and the retain.
3196 FindDependencies(CanChangeRetainCount, Arg,
3197 BB, Autorelease, DependingInstructions, Visited, PA);
3198 if (DependingInstructions.size() != 1)
3199 goto next_block;
3200
3201 {
3202 CallInst *Retain =
3203 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3204
3205 // Check that we found a retain with the same argument.
3206 if (!Retain ||
3207 !IsRetain(GetBasicInstructionClass(Retain)) ||
3208 GetObjCArg(Retain) != Arg)
3209 goto next_block;
3210
3211 DependingInstructions.clear();
3212 Visited.clear();
3213
3214 // Convert the autorelease to an autoreleaseRV, since it's
3215 // returning the value.
3216 if (AutoreleaseClass == IC_Autorelease) {
3217 Autorelease->setCalledFunction(getAutoreleaseRVCallee(F.getParent()));
3218 AutoreleaseClass = IC_AutoreleaseRV;
3219 }
3220
3221 // Check that there is nothing that can affect the reference
3222 // count between the retain and the call.
Dan Gohman27e06662011-09-29 22:27:34 +00003223 // Note that Retain need not be in BB.
3224 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
John McCall9fbd3182011-06-15 23:37:01 +00003225 DependingInstructions, Visited, PA);
3226 if (DependingInstructions.size() != 1)
3227 goto next_block;
3228
3229 {
3230 CallInst *Call =
3231 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3232
3233 // Check that the pointer is the return value of the call.
3234 if (!Call || Arg != Call)
3235 goto next_block;
3236
3237 // Check that the call is a regular call.
3238 InstructionClass Class = GetBasicInstructionClass(Call);
3239 if (Class != IC_CallOrUser && Class != IC_Call)
3240 goto next_block;
3241
3242 // If so, we can zap the retain and autorelease.
3243 Changed = true;
3244 ++NumRets;
3245 EraseInstruction(Retain);
3246 EraseInstruction(Autorelease);
3247 }
3248 }
3249 }
3250
3251 next_block:
3252 DependingInstructions.clear();
3253 Visited.clear();
3254 }
3255}
3256
3257bool ObjCARCOpt::doInitialization(Module &M) {
3258 if (!EnableARCOpts)
3259 return false;
3260
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003261 Run = ModuleHasARC(M);
3262 if (!Run)
3263 return false;
3264
John McCall9fbd3182011-06-15 23:37:01 +00003265 // Identify the imprecise release metadata kind.
3266 ImpreciseReleaseMDKind =
3267 M.getContext().getMDKindID("clang.imprecise_release");
3268
John McCall9fbd3182011-06-15 23:37:01 +00003269 // Intuitively, objc_retain and others are nocapture, however in practice
3270 // they are not, because they return their argument value. And objc_release
3271 // calls finalizers.
3272
3273 // These are initialized lazily.
3274 RetainRVCallee = 0;
3275 AutoreleaseRVCallee = 0;
3276 ReleaseCallee = 0;
3277 RetainCallee = 0;
Dan Gohman44280692011-07-22 22:29:21 +00003278 RetainBlockCallee = 0;
John McCall9fbd3182011-06-15 23:37:01 +00003279 AutoreleaseCallee = 0;
3280
3281 return false;
3282}
3283
3284bool ObjCARCOpt::runOnFunction(Function &F) {
3285 if (!EnableARCOpts)
3286 return false;
3287
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003288 // If nothing in the Module uses ARC, don't do anything.
3289 if (!Run)
3290 return false;
3291
John McCall9fbd3182011-06-15 23:37:01 +00003292 Changed = false;
3293
3294 PA.setAA(&getAnalysis<AliasAnalysis>());
3295
3296 // This pass performs several distinct transformations. As a compile-time aid
3297 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3298 // library functions aren't declared.
3299
3300 // Preliminary optimizations. This also computs UsedInThisFunction.
3301 OptimizeIndividualCalls(F);
3302
3303 // Optimizations for weak pointers.
3304 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3305 (1 << IC_LoadWeakRetained) |
3306 (1 << IC_StoreWeak) |
3307 (1 << IC_InitWeak) |
3308 (1 << IC_CopyWeak) |
3309 (1 << IC_MoveWeak) |
3310 (1 << IC_DestroyWeak)))
3311 OptimizeWeakCalls(F);
3312
3313 // Optimizations for retain+release pairs.
3314 if (UsedInThisFunction & ((1 << IC_Retain) |
3315 (1 << IC_RetainRV) |
3316 (1 << IC_RetainBlock)))
3317 if (UsedInThisFunction & (1 << IC_Release))
3318 // Run OptimizeSequences until it either stops making changes or
3319 // no retain+release pair nesting is detected.
3320 while (OptimizeSequences(F)) {}
3321
3322 // Optimizations if objc_autorelease is used.
3323 if (UsedInThisFunction &
3324 ((1 << IC_Autorelease) | (1 << IC_AutoreleaseRV)))
3325 OptimizeReturns(F);
3326
3327 return Changed;
3328}
3329
3330void ObjCARCOpt::releaseMemory() {
3331 PA.clear();
3332}
3333
3334//===----------------------------------------------------------------------===//
3335// ARC contraction.
3336//===----------------------------------------------------------------------===//
3337
3338// TODO: ObjCARCContract could insert PHI nodes when uses aren't
3339// dominated by single calls.
3340
3341#include "llvm/Operator.h"
3342#include "llvm/InlineAsm.h"
3343#include "llvm/Analysis/Dominators.h"
3344
3345STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed");
3346
3347namespace {
3348 /// ObjCARCContract - Late ARC optimizations. These change the IR in a way
3349 /// that makes it difficult to be analyzed by ObjCARCOpt, so it's run late.
3350 class ObjCARCContract : public FunctionPass {
3351 bool Changed;
3352 AliasAnalysis *AA;
3353 DominatorTree *DT;
3354 ProvenanceAnalysis PA;
3355
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003356 /// Run - A flag indicating whether this optimization pass should run.
3357 bool Run;
3358
John McCall9fbd3182011-06-15 23:37:01 +00003359 /// StoreStrongCallee, etc. - Declarations for ObjC runtime
3360 /// functions, for use in creating calls to them. These are initialized
3361 /// lazily to avoid cluttering up the Module with unused declarations.
3362 Constant *StoreStrongCallee,
3363 *RetainAutoreleaseCallee, *RetainAutoreleaseRVCallee;
3364
3365 /// RetainRVMarker - The inline asm string to insert between calls and
3366 /// RetainRV calls to make the optimization work on targets which need it.
3367 const MDString *RetainRVMarker;
3368
3369 Constant *getStoreStrongCallee(Module *M);
3370 Constant *getRetainAutoreleaseCallee(Module *M);
3371 Constant *getRetainAutoreleaseRVCallee(Module *M);
3372
3373 bool ContractAutorelease(Function &F, Instruction *Autorelease,
3374 InstructionClass Class,
3375 SmallPtrSet<Instruction *, 4>
3376 &DependingInstructions,
3377 SmallPtrSet<const BasicBlock *, 4>
3378 &Visited);
3379
3380 void ContractRelease(Instruction *Release,
3381 inst_iterator &Iter);
3382
3383 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
3384 virtual bool doInitialization(Module &M);
3385 virtual bool runOnFunction(Function &F);
3386
3387 public:
3388 static char ID;
3389 ObjCARCContract() : FunctionPass(ID) {
3390 initializeObjCARCContractPass(*PassRegistry::getPassRegistry());
3391 }
3392 };
3393}
3394
3395char ObjCARCContract::ID = 0;
3396INITIALIZE_PASS_BEGIN(ObjCARCContract,
3397 "objc-arc-contract", "ObjC ARC contraction", false, false)
3398INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3399INITIALIZE_PASS_DEPENDENCY(DominatorTree)
3400INITIALIZE_PASS_END(ObjCARCContract,
3401 "objc-arc-contract", "ObjC ARC contraction", false, false)
3402
3403Pass *llvm::createObjCARCContractPass() {
3404 return new ObjCARCContract();
3405}
3406
3407void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const {
3408 AU.addRequired<AliasAnalysis>();
3409 AU.addRequired<DominatorTree>();
3410 AU.setPreservesCFG();
3411}
3412
3413Constant *ObjCARCContract::getStoreStrongCallee(Module *M) {
3414 if (!StoreStrongCallee) {
3415 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00003416 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3417 Type *I8XX = PointerType::getUnqual(I8X);
3418 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00003419 Params.push_back(I8XX);
3420 Params.push_back(I8X);
3421
3422 AttrListPtr Attributes;
3423 Attributes.addAttr(~0u, Attribute::NoUnwind);
3424 Attributes.addAttr(1, Attribute::NoCapture);
3425
3426 StoreStrongCallee =
3427 M->getOrInsertFunction(
3428 "objc_storeStrong",
3429 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
3430 Attributes);
3431 }
3432 return StoreStrongCallee;
3433}
3434
3435Constant *ObjCARCContract::getRetainAutoreleaseCallee(Module *M) {
3436 if (!RetainAutoreleaseCallee) {
3437 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00003438 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3439 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00003440 Params.push_back(I8X);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003441 FunctionType *FTy =
John McCall9fbd3182011-06-15 23:37:01 +00003442 FunctionType::get(I8X, Params, /*isVarArg=*/false);
3443 AttrListPtr Attributes;
3444 Attributes.addAttr(~0u, Attribute::NoUnwind);
3445 RetainAutoreleaseCallee =
3446 M->getOrInsertFunction("objc_retainAutorelease", FTy, Attributes);
3447 }
3448 return RetainAutoreleaseCallee;
3449}
3450
3451Constant *ObjCARCContract::getRetainAutoreleaseRVCallee(Module *M) {
3452 if (!RetainAutoreleaseRVCallee) {
3453 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00003454 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3455 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00003456 Params.push_back(I8X);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003457 FunctionType *FTy =
John McCall9fbd3182011-06-15 23:37:01 +00003458 FunctionType::get(I8X, Params, /*isVarArg=*/false);
3459 AttrListPtr Attributes;
3460 Attributes.addAttr(~0u, Attribute::NoUnwind);
3461 RetainAutoreleaseRVCallee =
3462 M->getOrInsertFunction("objc_retainAutoreleaseReturnValue", FTy,
3463 Attributes);
3464 }
3465 return RetainAutoreleaseRVCallee;
3466}
3467
3468/// ContractAutorelease - Merge an autorelease with a retain into a fused
3469/// call.
3470bool
3471ObjCARCContract::ContractAutorelease(Function &F, Instruction *Autorelease,
3472 InstructionClass Class,
3473 SmallPtrSet<Instruction *, 4>
3474 &DependingInstructions,
3475 SmallPtrSet<const BasicBlock *, 4>
3476 &Visited) {
3477 const Value *Arg = GetObjCArg(Autorelease);
3478
3479 // Check that there are no instructions between the retain and the autorelease
3480 // (such as an autorelease_pop) which may change the count.
3481 CallInst *Retain = 0;
3482 if (Class == IC_AutoreleaseRV)
3483 FindDependencies(RetainAutoreleaseRVDep, Arg,
3484 Autorelease->getParent(), Autorelease,
3485 DependingInstructions, Visited, PA);
3486 else
3487 FindDependencies(RetainAutoreleaseDep, Arg,
3488 Autorelease->getParent(), Autorelease,
3489 DependingInstructions, Visited, PA);
3490
3491 Visited.clear();
3492 if (DependingInstructions.size() != 1) {
3493 DependingInstructions.clear();
3494 return false;
3495 }
3496
3497 Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3498 DependingInstructions.clear();
3499
3500 if (!Retain ||
3501 GetBasicInstructionClass(Retain) != IC_Retain ||
3502 GetObjCArg(Retain) != Arg)
3503 return false;
3504
3505 Changed = true;
3506 ++NumPeeps;
3507
3508 if (Class == IC_AutoreleaseRV)
3509 Retain->setCalledFunction(getRetainAutoreleaseRVCallee(F.getParent()));
3510 else
3511 Retain->setCalledFunction(getRetainAutoreleaseCallee(F.getParent()));
3512
3513 EraseInstruction(Autorelease);
3514 return true;
3515}
3516
3517/// ContractRelease - Attempt to merge an objc_release with a store, load, and
3518/// objc_retain to form an objc_storeStrong. This can be a little tricky because
3519/// the instructions don't always appear in order, and there may be unrelated
3520/// intervening instructions.
3521void ObjCARCContract::ContractRelease(Instruction *Release,
3522 inst_iterator &Iter) {
3523 LoadInst *Load = dyn_cast<LoadInst>(GetObjCArg(Release));
Eli Friedman2bc3d522011-09-12 20:23:13 +00003524 if (!Load || !Load->isSimple()) return;
John McCall9fbd3182011-06-15 23:37:01 +00003525
3526 // For now, require everything to be in one basic block.
3527 BasicBlock *BB = Release->getParent();
3528 if (Load->getParent() != BB) return;
3529
3530 // Walk down to find the store.
3531 BasicBlock::iterator I = Load, End = BB->end();
3532 ++I;
3533 AliasAnalysis::Location Loc = AA->getLocation(Load);
3534 while (I != End &&
3535 (&*I == Release ||
3536 IsRetain(GetBasicInstructionClass(I)) ||
3537 !(AA->getModRefInfo(I, Loc) & AliasAnalysis::Mod)))
3538 ++I;
3539 StoreInst *Store = dyn_cast<StoreInst>(I);
Eli Friedman2bc3d522011-09-12 20:23:13 +00003540 if (!Store || !Store->isSimple()) return;
John McCall9fbd3182011-06-15 23:37:01 +00003541 if (Store->getPointerOperand() != Loc.Ptr) return;
3542
3543 Value *New = StripPointerCastsAndObjCCalls(Store->getValueOperand());
3544
3545 // Walk up to find the retain.
3546 I = Store;
3547 BasicBlock::iterator Begin = BB->begin();
3548 while (I != Begin && GetBasicInstructionClass(I) != IC_Retain)
3549 --I;
3550 Instruction *Retain = I;
3551 if (GetBasicInstructionClass(Retain) != IC_Retain) return;
3552 if (GetObjCArg(Retain) != New) return;
3553
3554 Changed = true;
3555 ++NumStoreStrongs;
3556
3557 LLVMContext &C = Release->getContext();
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003558 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3559 Type *I8XX = PointerType::getUnqual(I8X);
John McCall9fbd3182011-06-15 23:37:01 +00003560
3561 Value *Args[] = { Load->getPointerOperand(), New };
3562 if (Args[0]->getType() != I8XX)
3563 Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
3564 if (Args[1]->getType() != I8X)
3565 Args[1] = new BitCastInst(Args[1], I8X, "", Store);
3566 CallInst *StoreStrong =
3567 CallInst::Create(getStoreStrongCallee(BB->getParent()->getParent()),
Jay Foada3efbb12011-07-15 08:37:34 +00003568 Args, "", Store);
John McCall9fbd3182011-06-15 23:37:01 +00003569 StoreStrong->setDoesNotThrow();
3570 StoreStrong->setDebugLoc(Store->getDebugLoc());
3571
3572 if (&*Iter == Store) ++Iter;
3573 Store->eraseFromParent();
3574 Release->eraseFromParent();
3575 EraseInstruction(Retain);
3576 if (Load->use_empty())
3577 Load->eraseFromParent();
3578}
3579
3580bool ObjCARCContract::doInitialization(Module &M) {
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003581 Run = ModuleHasARC(M);
3582 if (!Run)
3583 return false;
3584
John McCall9fbd3182011-06-15 23:37:01 +00003585 // These are initialized lazily.
3586 StoreStrongCallee = 0;
3587 RetainAutoreleaseCallee = 0;
3588 RetainAutoreleaseRVCallee = 0;
3589
3590 // Initialize RetainRVMarker.
3591 RetainRVMarker = 0;
3592 if (NamedMDNode *NMD =
3593 M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker"))
3594 if (NMD->getNumOperands() == 1) {
3595 const MDNode *N = NMD->getOperand(0);
3596 if (N->getNumOperands() == 1)
3597 if (const MDString *S = dyn_cast<MDString>(N->getOperand(0)))
3598 RetainRVMarker = S;
3599 }
3600
3601 return false;
3602}
3603
3604bool ObjCARCContract::runOnFunction(Function &F) {
3605 if (!EnableARCOpts)
3606 return false;
3607
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003608 // If nothing in the Module uses ARC, don't do anything.
3609 if (!Run)
3610 return false;
3611
John McCall9fbd3182011-06-15 23:37:01 +00003612 Changed = false;
3613 AA = &getAnalysis<AliasAnalysis>();
3614 DT = &getAnalysis<DominatorTree>();
3615
3616 PA.setAA(&getAnalysis<AliasAnalysis>());
3617
3618 // For ObjC library calls which return their argument, replace uses of the
3619 // argument with uses of the call return value, if it dominates the use. This
3620 // reduces register pressure.
3621 SmallPtrSet<Instruction *, 4> DependingInstructions;
3622 SmallPtrSet<const BasicBlock *, 4> Visited;
3623 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3624 Instruction *Inst = &*I++;
3625
3626 // Only these library routines return their argument. In particular,
3627 // objc_retainBlock does not necessarily return its argument.
3628 InstructionClass Class = GetBasicInstructionClass(Inst);
3629 switch (Class) {
3630 case IC_Retain:
3631 case IC_FusedRetainAutorelease:
3632 case IC_FusedRetainAutoreleaseRV:
3633 break;
3634 case IC_Autorelease:
3635 case IC_AutoreleaseRV:
3636 if (ContractAutorelease(F, Inst, Class, DependingInstructions, Visited))
3637 continue;
3638 break;
3639 case IC_RetainRV: {
3640 // If we're compiling for a target which needs a special inline-asm
3641 // marker to do the retainAutoreleasedReturnValue optimization,
3642 // insert it now.
3643 if (!RetainRVMarker)
3644 break;
3645 BasicBlock::iterator BBI = Inst;
3646 --BBI;
3647 while (isNoopInstruction(BBI)) --BBI;
3648 if (&*BBI == GetObjCArg(Inst)) {
3649 InlineAsm *IA =
3650 InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()),
3651 /*isVarArg=*/false),
3652 RetainRVMarker->getString(),
3653 /*Constraints=*/"", /*hasSideEffects=*/true);
3654 CallInst::Create(IA, "", Inst);
3655 }
3656 break;
3657 }
3658 case IC_InitWeak: {
3659 // objc_initWeak(p, null) => *p = null
3660 CallInst *CI = cast<CallInst>(Inst);
3661 if (isNullOrUndef(CI->getArgOperand(1))) {
3662 Value *Null =
3663 ConstantPointerNull::get(cast<PointerType>(CI->getType()));
3664 Changed = true;
3665 new StoreInst(Null, CI->getArgOperand(0), CI);
3666 CI->replaceAllUsesWith(Null);
3667 CI->eraseFromParent();
3668 }
3669 continue;
3670 }
3671 case IC_Release:
3672 ContractRelease(Inst, I);
3673 continue;
3674 default:
3675 continue;
3676 }
3677
3678 // Don't use GetObjCArg because we don't want to look through bitcasts
3679 // and such; to do the replacement, the argument must have type i8*.
3680 const Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
3681 for (;;) {
3682 // If we're compiling bugpointed code, don't get in trouble.
3683 if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
3684 break;
3685 // Look through the uses of the pointer.
3686 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
3687 UI != UE; ) {
3688 Use &U = UI.getUse();
3689 unsigned OperandNo = UI.getOperandNo();
3690 ++UI; // Increment UI now, because we may unlink its element.
3691 if (Instruction *UserInst = dyn_cast<Instruction>(U.getUser()))
3692 if (Inst != UserInst && DT->dominates(Inst, UserInst)) {
3693 Changed = true;
3694 Instruction *Replacement = Inst;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003695 Type *UseTy = U.get()->getType();
John McCall9fbd3182011-06-15 23:37:01 +00003696 if (PHINode *PHI = dyn_cast<PHINode>(UserInst)) {
3697 // For PHI nodes, insert the bitcast in the predecessor block.
3698 unsigned ValNo =
3699 PHINode::getIncomingValueNumForOperand(OperandNo);
3700 BasicBlock *BB =
3701 PHI->getIncomingBlock(ValNo);
3702 if (Replacement->getType() != UseTy)
3703 Replacement = new BitCastInst(Replacement, UseTy, "",
3704 &BB->back());
3705 for (unsigned i = 0, e = PHI->getNumIncomingValues();
3706 i != e; ++i)
3707 if (PHI->getIncomingBlock(i) == BB) {
3708 // Keep the UI iterator valid.
3709 if (&PHI->getOperandUse(
3710 PHINode::getOperandNumForIncomingValue(i)) ==
3711 &UI.getUse())
3712 ++UI;
3713 PHI->setIncomingValue(i, Replacement);
3714 }
3715 } else {
3716 if (Replacement->getType() != UseTy)
3717 Replacement = new BitCastInst(Replacement, UseTy, "", UserInst);
3718 U.set(Replacement);
3719 }
3720 }
3721 }
3722
3723 // If Arg is a no-op casted pointer, strip one level of casts and
3724 // iterate.
3725 if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
3726 Arg = BI->getOperand(0);
3727 else if (isa<GEPOperator>(Arg) &&
3728 cast<GEPOperator>(Arg)->hasAllZeroIndices())
3729 Arg = cast<GEPOperator>(Arg)->getPointerOperand();
3730 else if (isa<GlobalAlias>(Arg) &&
3731 !cast<GlobalAlias>(Arg)->mayBeOverridden())
3732 Arg = cast<GlobalAlias>(Arg)->getAliasee();
3733 else
3734 break;
3735 }
3736 }
3737
3738 return Changed;
3739}