blob: 9654b1ecd306eb7550a36877d4b7310b7c73181f [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.
347 for (User::const_op_iterator OI = I->op_begin(), OE = I->op_end();
348 OI != OE; ++OI)
349 if (IsPotentialUse(*OI))
350 return IC_User;
351 }
352 }
353
354 // Otherwise, it's totally inert for ARC purposes.
355 return IC_None;
356}
357
358/// GetBasicInstructionClass - Determine what kind of construct V is. This is
359/// similar to GetInstructionClass except that it only detects objc runtine
360/// calls. This allows it to be faster.
361static InstructionClass GetBasicInstructionClass(const Value *V) {
362 if (const CallInst *CI = dyn_cast<CallInst>(V)) {
363 if (const Function *F = CI->getCalledFunction())
364 return GetFunctionClass(F);
365 // Otherwise, be conservative.
366 return IC_CallOrUser;
367 }
368
369 // Otherwise, be conservative.
370 return IC_User;
371}
372
373/// IsRetain - Test if the the given class is objc_retain or
374/// equivalent.
375static bool IsRetain(InstructionClass Class) {
376 return Class == IC_Retain ||
377 Class == IC_RetainRV;
378}
379
380/// IsAutorelease - Test if the the given class is objc_autorelease or
381/// equivalent.
382static bool IsAutorelease(InstructionClass Class) {
383 return Class == IC_Autorelease ||
384 Class == IC_AutoreleaseRV;
385}
386
387/// IsForwarding - Test if the given class represents instructions which return
388/// their argument verbatim.
389static bool IsForwarding(InstructionClass Class) {
390 // objc_retainBlock technically doesn't always return its argument
391 // verbatim, but it doesn't matter for our purposes here.
392 return Class == IC_Retain ||
393 Class == IC_RetainRV ||
394 Class == IC_Autorelease ||
395 Class == IC_AutoreleaseRV ||
396 Class == IC_RetainBlock ||
397 Class == IC_NoopCast;
398}
399
400/// IsNoopOnNull - Test if the given class represents instructions which do
401/// nothing if passed a null pointer.
402static bool IsNoopOnNull(InstructionClass Class) {
403 return Class == IC_Retain ||
404 Class == IC_RetainRV ||
405 Class == IC_Release ||
406 Class == IC_Autorelease ||
407 Class == IC_AutoreleaseRV ||
408 Class == IC_RetainBlock;
409}
410
411/// IsAlwaysTail - Test if the given class represents instructions which are
412/// always safe to mark with the "tail" keyword.
413static bool IsAlwaysTail(InstructionClass Class) {
414 // IC_RetainBlock may be given a stack argument.
415 return Class == IC_Retain ||
416 Class == IC_RetainRV ||
417 Class == IC_Autorelease ||
418 Class == IC_AutoreleaseRV;
419}
420
421/// IsNoThrow - Test if the given class represents instructions which are always
422/// safe to mark with the nounwind attribute..
423static bool IsNoThrow(InstructionClass Class) {
424 return Class == IC_Retain ||
425 Class == IC_RetainRV ||
426 Class == IC_RetainBlock ||
427 Class == IC_Release ||
428 Class == IC_Autorelease ||
429 Class == IC_AutoreleaseRV ||
430 Class == IC_AutoreleasepoolPush ||
431 Class == IC_AutoreleasepoolPop;
432}
433
434/// EraseInstruction - Erase the given instruction. ObjC calls return their
435/// argument verbatim, so if it's such a call and the return value has users,
436/// replace them with the argument value.
437static void EraseInstruction(Instruction *CI) {
438 Value *OldArg = cast<CallInst>(CI)->getArgOperand(0);
439
440 bool Unused = CI->use_empty();
441
442 if (!Unused) {
443 // Replace the return value with the argument.
444 assert(IsForwarding(GetBasicInstructionClass(CI)) &&
445 "Can't delete non-forwarding instruction with users!");
446 CI->replaceAllUsesWith(OldArg);
447 }
448
449 CI->eraseFromParent();
450
451 if (Unused)
452 RecursivelyDeleteTriviallyDeadInstructions(OldArg);
453}
454
455/// GetUnderlyingObjCPtr - This is a wrapper around getUnderlyingObject which
456/// also knows how to look through objc_retain and objc_autorelease calls, which
457/// we know to return their argument verbatim.
458static const Value *GetUnderlyingObjCPtr(const Value *V) {
459 for (;;) {
460 V = GetUnderlyingObject(V);
461 if (!IsForwarding(GetBasicInstructionClass(V)))
462 break;
463 V = cast<CallInst>(V)->getArgOperand(0);
464 }
465
466 return V;
467}
468
469/// StripPointerCastsAndObjCCalls - This is a wrapper around
470/// Value::stripPointerCasts which also knows how to look through objc_retain
471/// and objc_autorelease calls, which we know to return their argument verbatim.
472static const Value *StripPointerCastsAndObjCCalls(const Value *V) {
473 for (;;) {
474 V = V->stripPointerCasts();
475 if (!IsForwarding(GetBasicInstructionClass(V)))
476 break;
477 V = cast<CallInst>(V)->getArgOperand(0);
478 }
479 return V;
480}
481
482/// StripPointerCastsAndObjCCalls - This is a wrapper around
483/// Value::stripPointerCasts which also knows how to look through objc_retain
484/// and objc_autorelease calls, which we know to return their argument verbatim.
485static Value *StripPointerCastsAndObjCCalls(Value *V) {
486 for (;;) {
487 V = V->stripPointerCasts();
488 if (!IsForwarding(GetBasicInstructionClass(V)))
489 break;
490 V = cast<CallInst>(V)->getArgOperand(0);
491 }
492 return V;
493}
494
495/// GetObjCArg - Assuming the given instruction is one of the special calls such
496/// as objc_retain or objc_release, return the argument value, stripped of no-op
497/// casts and forwarding calls.
498static Value *GetObjCArg(Value *Inst) {
499 return StripPointerCastsAndObjCCalls(cast<CallInst>(Inst)->getArgOperand(0));
500}
501
502/// IsObjCIdentifiedObject - This is similar to AliasAnalysis'
503/// isObjCIdentifiedObject, except that it uses special knowledge of
504/// ObjC conventions...
505static bool IsObjCIdentifiedObject(const Value *V) {
506 // Assume that call results and arguments have their own "provenance".
507 // Constants (including GlobalVariables) and Allocas are never
508 // reference-counted.
509 if (isa<CallInst>(V) || isa<InvokeInst>(V) ||
510 isa<Argument>(V) || isa<Constant>(V) ||
511 isa<AllocaInst>(V))
512 return true;
513
514 if (const LoadInst *LI = dyn_cast<LoadInst>(V)) {
515 const Value *Pointer =
516 StripPointerCastsAndObjCCalls(LI->getPointerOperand());
517 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Pointer)) {
Dan Gohman1b31ea82011-08-22 17:29:11 +0000518 // A constant pointer can't be pointing to an object on the heap. It may
519 // be reference-counted, but it won't be deleted.
520 if (GV->isConstant())
521 return true;
John McCall9fbd3182011-06-15 23:37:01 +0000522 StringRef Name = GV->getName();
523 // These special variables are known to hold values which are not
524 // reference-counted pointers.
525 if (Name.startswith("\01L_OBJC_SELECTOR_REFERENCES_") ||
526 Name.startswith("\01L_OBJC_CLASSLIST_REFERENCES_") ||
527 Name.startswith("\01L_OBJC_CLASSLIST_SUP_REFS_$_") ||
528 Name.startswith("\01L_OBJC_METH_VAR_NAME_") ||
529 Name.startswith("\01l_objc_msgSend_fixup_"))
530 return true;
531 }
532 }
533
534 return false;
535}
536
537/// FindSingleUseIdentifiedObject - This is similar to
538/// StripPointerCastsAndObjCCalls but it stops as soon as it finds a value
539/// with multiple uses.
540static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
541 if (Arg->hasOneUse()) {
542 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
543 return FindSingleUseIdentifiedObject(BC->getOperand(0));
544 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
545 if (GEP->hasAllZeroIndices())
546 return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
547 if (IsForwarding(GetBasicInstructionClass(Arg)))
548 return FindSingleUseIdentifiedObject(
549 cast<CallInst>(Arg)->getArgOperand(0));
550 if (!IsObjCIdentifiedObject(Arg))
551 return 0;
552 return Arg;
553 }
554
555 // If we found an identifiable object but it has multiple uses, but they
556 // are trivial uses, we can still consider this to be a single-use
557 // value.
558 if (IsObjCIdentifiedObject(Arg)) {
559 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
560 UI != UE; ++UI) {
561 const User *U = *UI;
562 if (!U->use_empty() || StripPointerCastsAndObjCCalls(U) != Arg)
563 return 0;
564 }
565
566 return Arg;
567 }
568
569 return 0;
570}
571
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000572/// ModuleHasARC - Test if the given module looks interesting to run ARC
573/// optimization on.
574static bool ModuleHasARC(const Module &M) {
575 return
576 M.getNamedValue("objc_retain") ||
577 M.getNamedValue("objc_release") ||
578 M.getNamedValue("objc_autorelease") ||
579 M.getNamedValue("objc_retainAutoreleasedReturnValue") ||
580 M.getNamedValue("objc_retainBlock") ||
581 M.getNamedValue("objc_autoreleaseReturnValue") ||
582 M.getNamedValue("objc_autoreleasePoolPush") ||
583 M.getNamedValue("objc_loadWeakRetained") ||
584 M.getNamedValue("objc_loadWeak") ||
585 M.getNamedValue("objc_destroyWeak") ||
586 M.getNamedValue("objc_storeWeak") ||
587 M.getNamedValue("objc_initWeak") ||
588 M.getNamedValue("objc_moveWeak") ||
589 M.getNamedValue("objc_copyWeak") ||
590 M.getNamedValue("objc_retainedObject") ||
591 M.getNamedValue("objc_unretainedObject") ||
592 M.getNamedValue("objc_unretainedPointer");
593}
594
John McCall9fbd3182011-06-15 23:37:01 +0000595//===----------------------------------------------------------------------===//
596// ARC AliasAnalysis.
597//===----------------------------------------------------------------------===//
598
599#include "llvm/Pass.h"
600#include "llvm/Analysis/AliasAnalysis.h"
601#include "llvm/Analysis/Passes.h"
602
603namespace {
604 /// ObjCARCAliasAnalysis - This is a simple alias analysis
605 /// implementation that uses knowledge of ARC constructs to answer queries.
606 ///
607 /// TODO: This class could be generalized to know about other ObjC-specific
608 /// tricks. Such as knowing that ivars in the non-fragile ABI are non-aliasing
609 /// even though their offsets are dynamic.
610 class ObjCARCAliasAnalysis : public ImmutablePass,
611 public AliasAnalysis {
612 public:
613 static char ID; // Class identification, replacement for typeinfo
614 ObjCARCAliasAnalysis() : ImmutablePass(ID) {
615 initializeObjCARCAliasAnalysisPass(*PassRegistry::getPassRegistry());
616 }
617
618 private:
619 virtual void initializePass() {
620 InitializeAliasAnalysis(this);
621 }
622
623 /// getAdjustedAnalysisPointer - This method is used when a pass implements
624 /// an analysis interface through multiple inheritance. If needed, it
625 /// should override this to adjust the this pointer as needed for the
626 /// specified pass info.
627 virtual void *getAdjustedAnalysisPointer(const void *PI) {
628 if (PI == &AliasAnalysis::ID)
629 return (AliasAnalysis*)this;
630 return this;
631 }
632
633 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
634 virtual AliasResult alias(const Location &LocA, const Location &LocB);
635 virtual bool pointsToConstantMemory(const Location &Loc, bool OrLocal);
636 virtual ModRefBehavior getModRefBehavior(ImmutableCallSite CS);
637 virtual ModRefBehavior getModRefBehavior(const Function *F);
638 virtual ModRefResult getModRefInfo(ImmutableCallSite CS,
639 const Location &Loc);
640 virtual ModRefResult getModRefInfo(ImmutableCallSite CS1,
641 ImmutableCallSite CS2);
642 };
643} // End of anonymous namespace
644
645// Register this pass...
646char ObjCARCAliasAnalysis::ID = 0;
647INITIALIZE_AG_PASS(ObjCARCAliasAnalysis, AliasAnalysis, "objc-arc-aa",
648 "ObjC-ARC-Based Alias Analysis", false, true, false)
649
650ImmutablePass *llvm::createObjCARCAliasAnalysisPass() {
651 return new ObjCARCAliasAnalysis();
652}
653
654void
655ObjCARCAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
656 AU.setPreservesAll();
657 AliasAnalysis::getAnalysisUsage(AU);
658}
659
660AliasAnalysis::AliasResult
661ObjCARCAliasAnalysis::alias(const Location &LocA, const Location &LocB) {
662 if (!EnableARCOpts)
663 return AliasAnalysis::alias(LocA, LocB);
664
665 // First, strip off no-ops, including ObjC-specific no-ops, and try making a
666 // precise alias query.
667 const Value *SA = StripPointerCastsAndObjCCalls(LocA.Ptr);
668 const Value *SB = StripPointerCastsAndObjCCalls(LocB.Ptr);
669 AliasResult Result =
670 AliasAnalysis::alias(Location(SA, LocA.Size, LocA.TBAATag),
671 Location(SB, LocB.Size, LocB.TBAATag));
672 if (Result != MayAlias)
673 return Result;
674
675 // If that failed, climb to the underlying object, including climbing through
676 // ObjC-specific no-ops, and try making an imprecise alias query.
677 const Value *UA = GetUnderlyingObjCPtr(SA);
678 const Value *UB = GetUnderlyingObjCPtr(SB);
679 if (UA != SA || UB != SB) {
680 Result = AliasAnalysis::alias(Location(UA), Location(UB));
681 // We can't use MustAlias or PartialAlias results here because
682 // GetUnderlyingObjCPtr may return an offsetted pointer value.
683 if (Result == NoAlias)
684 return NoAlias;
685 }
686
687 // If that failed, fail. We don't need to chain here, since that's covered
688 // by the earlier precise query.
689 return MayAlias;
690}
691
692bool
693ObjCARCAliasAnalysis::pointsToConstantMemory(const Location &Loc,
694 bool OrLocal) {
695 if (!EnableARCOpts)
696 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
697
698 // First, strip off no-ops, including ObjC-specific no-ops, and try making
699 // a precise alias query.
700 const Value *S = StripPointerCastsAndObjCCalls(Loc.Ptr);
701 if (AliasAnalysis::pointsToConstantMemory(Location(S, Loc.Size, Loc.TBAATag),
702 OrLocal))
703 return true;
704
705 // If that failed, climb to the underlying object, including climbing through
706 // ObjC-specific no-ops, and try making an imprecise alias query.
707 const Value *U = GetUnderlyingObjCPtr(S);
708 if (U != S)
709 return AliasAnalysis::pointsToConstantMemory(Location(U), OrLocal);
710
711 // If that failed, fail. We don't need to chain here, since that's covered
712 // by the earlier precise query.
713 return false;
714}
715
716AliasAnalysis::ModRefBehavior
717ObjCARCAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
718 // We have nothing to do. Just chain to the next AliasAnalysis.
719 return AliasAnalysis::getModRefBehavior(CS);
720}
721
722AliasAnalysis::ModRefBehavior
723ObjCARCAliasAnalysis::getModRefBehavior(const Function *F) {
724 if (!EnableARCOpts)
725 return AliasAnalysis::getModRefBehavior(F);
726
727 switch (GetFunctionClass(F)) {
728 case IC_NoopCast:
729 return DoesNotAccessMemory;
730 default:
731 break;
732 }
733
734 return AliasAnalysis::getModRefBehavior(F);
735}
736
737AliasAnalysis::ModRefResult
738ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS, const Location &Loc) {
739 if (!EnableARCOpts)
740 return AliasAnalysis::getModRefInfo(CS, Loc);
741
742 switch (GetBasicInstructionClass(CS.getInstruction())) {
743 case IC_Retain:
744 case IC_RetainRV:
745 case IC_RetainBlock:
746 case IC_Autorelease:
747 case IC_AutoreleaseRV:
748 case IC_NoopCast:
749 case IC_AutoreleasepoolPush:
750 case IC_FusedRetainAutorelease:
751 case IC_FusedRetainAutoreleaseRV:
752 // These functions don't access any memory visible to the compiler.
753 return NoModRef;
754 default:
755 break;
756 }
757
758 return AliasAnalysis::getModRefInfo(CS, Loc);
759}
760
761AliasAnalysis::ModRefResult
762ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
763 ImmutableCallSite CS2) {
764 // TODO: Theoretically we could check for dependencies between objc_* calls
765 // and OnlyAccessesArgumentPointees calls or other well-behaved calls.
766 return AliasAnalysis::getModRefInfo(CS1, CS2);
767}
768
769//===----------------------------------------------------------------------===//
770// ARC expansion.
771//===----------------------------------------------------------------------===//
772
773#include "llvm/Support/InstIterator.h"
774#include "llvm/Transforms/Scalar.h"
775
776namespace {
777 /// ObjCARCExpand - Early ARC transformations.
778 class ObjCARCExpand : public FunctionPass {
779 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000780 virtual bool doInitialization(Module &M);
John McCall9fbd3182011-06-15 23:37:01 +0000781 virtual bool runOnFunction(Function &F);
782
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000783 /// Run - A flag indicating whether this optimization pass should run.
784 bool Run;
785
John McCall9fbd3182011-06-15 23:37:01 +0000786 public:
787 static char ID;
788 ObjCARCExpand() : FunctionPass(ID) {
789 initializeObjCARCExpandPass(*PassRegistry::getPassRegistry());
790 }
791 };
792}
793
794char ObjCARCExpand::ID = 0;
795INITIALIZE_PASS(ObjCARCExpand,
796 "objc-arc-expand", "ObjC ARC expansion", false, false)
797
798Pass *llvm::createObjCARCExpandPass() {
799 return new ObjCARCExpand();
800}
801
802void ObjCARCExpand::getAnalysisUsage(AnalysisUsage &AU) const {
803 AU.setPreservesCFG();
804}
805
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000806bool ObjCARCExpand::doInitialization(Module &M) {
807 Run = ModuleHasARC(M);
808 return false;
809}
810
John McCall9fbd3182011-06-15 23:37:01 +0000811bool ObjCARCExpand::runOnFunction(Function &F) {
812 if (!EnableARCOpts)
813 return false;
814
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000815 // If nothing in the Module uses ARC, don't do anything.
816 if (!Run)
817 return false;
818
John McCall9fbd3182011-06-15 23:37:01 +0000819 bool Changed = false;
820
821 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
822 Instruction *Inst = &*I;
823
824 switch (GetBasicInstructionClass(Inst)) {
825 case IC_Retain:
826 case IC_RetainRV:
827 case IC_Autorelease:
828 case IC_AutoreleaseRV:
829 case IC_FusedRetainAutorelease:
830 case IC_FusedRetainAutoreleaseRV:
831 // These calls return their argument verbatim, as a low-level
832 // optimization. However, this makes high-level optimizations
833 // harder. Undo any uses of this optimization that the front-end
834 // emitted here. We'll redo them in a later pass.
835 Changed = true;
836 Inst->replaceAllUsesWith(cast<CallInst>(Inst)->getArgOperand(0));
837 break;
838 default:
839 break;
840 }
841 }
842
843 return Changed;
844}
845
846//===----------------------------------------------------------------------===//
847// ARC optimization.
848//===----------------------------------------------------------------------===//
849
850// TODO: On code like this:
851//
852// objc_retain(%x)
853// stuff_that_cannot_release()
854// objc_autorelease(%x)
855// stuff_that_cannot_release()
856// objc_retain(%x)
857// stuff_that_cannot_release()
858// objc_autorelease(%x)
859//
860// The second retain and autorelease can be deleted.
861
862// TODO: It should be possible to delete
863// objc_autoreleasePoolPush and objc_autoreleasePoolPop
864// pairs if nothing is actually autoreleased between them. Also, autorelease
865// calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
866// after inlining) can be turned into plain release calls.
867
868// TODO: Critical-edge splitting. If the optimial insertion point is
869// a critical edge, the current algorithm has to fail, because it doesn't
870// know how to split edges. It should be possible to make the optimizer
871// think in terms of edges, rather than blocks, and then split critical
872// edges on demand.
873
874// TODO: OptimizeSequences could generalized to be Interprocedural.
875
876// TODO: Recognize that a bunch of other objc runtime calls have
877// non-escaping arguments and non-releasing arguments, and may be
878// non-autoreleasing.
879
880// TODO: Sink autorelease calls as far as possible. Unfortunately we
881// usually can't sink them past other calls, which would be the main
882// case where it would be useful.
883
Dan Gohmane6d5e882011-08-19 00:26:36 +0000884// TODO: The pointer returned from objc_loadWeakRetained is retained.
885
886// TODO: Delete release+retain pairs (rare).
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000887
John McCall9fbd3182011-06-15 23:37:01 +0000888#include "llvm/GlobalAlias.h"
John McCall9fbd3182011-06-15 23:37:01 +0000889#include "llvm/Constants.h"
890#include "llvm/LLVMContext.h"
891#include "llvm/Support/ErrorHandling.h"
892#include "llvm/Support/CFG.h"
893#include "llvm/ADT/PostOrderIterator.h"
894#include "llvm/ADT/Statistic.h"
895
896STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
897STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
898STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
899STATISTIC(NumRets, "Number of return value forwarding "
900 "retain+autoreleaes eliminated");
901STATISTIC(NumRRs, "Number of retain+release paths eliminated");
902STATISTIC(NumPeeps, "Number of calls peephole-optimized");
903
904namespace {
905 /// ProvenanceAnalysis - This is similar to BasicAliasAnalysis, and it
906 /// uses many of the same techniques, except it uses special ObjC-specific
907 /// reasoning about pointer relationships.
908 class ProvenanceAnalysis {
909 AliasAnalysis *AA;
910
911 typedef std::pair<const Value *, const Value *> ValuePairTy;
912 typedef DenseMap<ValuePairTy, bool> CachedResultsTy;
913 CachedResultsTy CachedResults;
914
915 bool relatedCheck(const Value *A, const Value *B);
916 bool relatedSelect(const SelectInst *A, const Value *B);
917 bool relatedPHI(const PHINode *A, const Value *B);
918
919 // Do not implement.
920 void operator=(const ProvenanceAnalysis &);
921 ProvenanceAnalysis(const ProvenanceAnalysis &);
922
923 public:
924 ProvenanceAnalysis() {}
925
926 void setAA(AliasAnalysis *aa) { AA = aa; }
927
928 AliasAnalysis *getAA() const { return AA; }
929
930 bool related(const Value *A, const Value *B);
931
932 void clear() {
933 CachedResults.clear();
934 }
935 };
936}
937
938bool ProvenanceAnalysis::relatedSelect(const SelectInst *A, const Value *B) {
939 // If the values are Selects with the same condition, we can do a more precise
940 // check: just check for relations between the values on corresponding arms.
941 if (const SelectInst *SB = dyn_cast<SelectInst>(B))
942 if (A->getCondition() == SB->getCondition()) {
943 if (related(A->getTrueValue(), SB->getTrueValue()))
944 return true;
945 if (related(A->getFalseValue(), SB->getFalseValue()))
946 return true;
947 return false;
948 }
949
950 // Check both arms of the Select node individually.
951 if (related(A->getTrueValue(), B))
952 return true;
953 if (related(A->getFalseValue(), B))
954 return true;
955
956 // The arms both checked out.
957 return false;
958}
959
960bool ProvenanceAnalysis::relatedPHI(const PHINode *A, const Value *B) {
961 // If the values are PHIs in the same block, we can do a more precise as well
962 // as efficient check: just check for relations between the values on
963 // corresponding edges.
964 if (const PHINode *PNB = dyn_cast<PHINode>(B))
965 if (PNB->getParent() == A->getParent()) {
966 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i)
967 if (related(A->getIncomingValue(i),
968 PNB->getIncomingValueForBlock(A->getIncomingBlock(i))))
969 return true;
970 return false;
971 }
972
973 // Check each unique source of the PHI node against B.
974 SmallPtrSet<const Value *, 4> UniqueSrc;
975 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i) {
976 const Value *PV1 = A->getIncomingValue(i);
977 if (UniqueSrc.insert(PV1) && related(PV1, B))
978 return true;
979 }
980
981 // All of the arms checked out.
982 return false;
983}
984
985/// isStoredObjCPointer - Test if the value of P, or any value covered by its
986/// provenance, is ever stored within the function (not counting callees).
987static bool isStoredObjCPointer(const Value *P) {
988 SmallPtrSet<const Value *, 8> Visited;
989 SmallVector<const Value *, 8> Worklist;
990 Worklist.push_back(P);
991 Visited.insert(P);
992 do {
993 P = Worklist.pop_back_val();
994 for (Value::const_use_iterator UI = P->use_begin(), UE = P->use_end();
995 UI != UE; ++UI) {
996 const User *Ur = *UI;
997 if (isa<StoreInst>(Ur)) {
998 if (UI.getOperandNo() == 0)
999 // The pointer is stored.
1000 return true;
1001 // The pointed is stored through.
1002 continue;
1003 }
1004 if (isa<CallInst>(Ur))
1005 // The pointer is passed as an argument, ignore this.
1006 continue;
1007 if (isa<PtrToIntInst>(P))
1008 // Assume the worst.
1009 return true;
1010 if (Visited.insert(Ur))
1011 Worklist.push_back(Ur);
1012 }
1013 } while (!Worklist.empty());
1014
1015 // Everything checked out.
1016 return false;
1017}
1018
1019bool ProvenanceAnalysis::relatedCheck(const Value *A, const Value *B) {
1020 // Skip past provenance pass-throughs.
1021 A = GetUnderlyingObjCPtr(A);
1022 B = GetUnderlyingObjCPtr(B);
1023
1024 // Quick check.
1025 if (A == B)
1026 return true;
1027
1028 // Ask regular AliasAnalysis, for a first approximation.
1029 switch (AA->alias(A, B)) {
1030 case AliasAnalysis::NoAlias:
1031 return false;
1032 case AliasAnalysis::MustAlias:
1033 case AliasAnalysis::PartialAlias:
1034 return true;
1035 case AliasAnalysis::MayAlias:
1036 break;
1037 }
1038
1039 bool AIsIdentified = IsObjCIdentifiedObject(A);
1040 bool BIsIdentified = IsObjCIdentifiedObject(B);
1041
1042 // An ObjC-Identified object can't alias a load if it is never locally stored.
1043 if (AIsIdentified) {
1044 if (BIsIdentified) {
1045 // If both pointers have provenance, they can be directly compared.
1046 if (A != B)
1047 return false;
1048 } else {
1049 if (isa<LoadInst>(B))
1050 return isStoredObjCPointer(A);
1051 }
1052 } else {
1053 if (BIsIdentified && isa<LoadInst>(A))
1054 return isStoredObjCPointer(B);
1055 }
1056
1057 // Special handling for PHI and Select.
1058 if (const PHINode *PN = dyn_cast<PHINode>(A))
1059 return relatedPHI(PN, B);
1060 if (const PHINode *PN = dyn_cast<PHINode>(B))
1061 return relatedPHI(PN, A);
1062 if (const SelectInst *S = dyn_cast<SelectInst>(A))
1063 return relatedSelect(S, B);
1064 if (const SelectInst *S = dyn_cast<SelectInst>(B))
1065 return relatedSelect(S, A);
1066
1067 // Conservative.
1068 return true;
1069}
1070
1071bool ProvenanceAnalysis::related(const Value *A, const Value *B) {
1072 // Begin by inserting a conservative value into the map. If the insertion
1073 // fails, we have the answer already. If it succeeds, leave it there until we
1074 // compute the real answer to guard against recursive queries.
1075 if (A > B) std::swap(A, B);
1076 std::pair<CachedResultsTy::iterator, bool> Pair =
1077 CachedResults.insert(std::make_pair(ValuePairTy(A, B), true));
1078 if (!Pair.second)
1079 return Pair.first->second;
1080
1081 bool Result = relatedCheck(A, B);
1082 CachedResults[ValuePairTy(A, B)] = Result;
1083 return Result;
1084}
1085
1086namespace {
1087 // Sequence - A sequence of states that a pointer may go through in which an
1088 // objc_retain and objc_release are actually needed.
1089 enum Sequence {
1090 S_None,
1091 S_Retain, ///< objc_retain(x)
1092 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement
1093 S_Use, ///< any use of x
1094 S_Stop, ///< like S_Release, but code motion is stopped
1095 S_Release, ///< objc_release(x)
1096 S_MovableRelease ///< objc_release(x), !clang.imprecise_release
1097 };
1098}
1099
1100static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
1101 // The easy cases.
1102 if (A == B)
1103 return A;
1104 if (A == S_None || B == S_None)
1105 return S_None;
1106
John McCall9fbd3182011-06-15 23:37:01 +00001107 if (A > B) std::swap(A, B);
1108 if (TopDown) {
1109 // Choose the side which is further along in the sequence.
Dan Gohmana7f7db22011-08-12 00:26:31 +00001110 if ((A == S_Retain || A == S_CanRelease) &&
1111 (B == S_CanRelease || B == S_Use))
John McCall9fbd3182011-06-15 23:37:01 +00001112 return B;
1113 } else {
1114 // Choose the side which is further along in the sequence.
1115 if ((A == S_Use || A == S_CanRelease) &&
Dan Gohmana7f7db22011-08-12 00:26:31 +00001116 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
John McCall9fbd3182011-06-15 23:37:01 +00001117 return A;
1118 // If both sides are releases, choose the more conservative one.
1119 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
1120 return A;
1121 if (A == S_Release && B == S_MovableRelease)
1122 return A;
1123 }
1124
1125 return S_None;
1126}
1127
1128namespace {
1129 /// RRInfo - Unidirectional information about either a
1130 /// retain-decrement-use-release sequence or release-use-decrement-retain
1131 /// reverese sequence.
1132 struct RRInfo {
Dan Gohmane6d5e882011-08-19 00:26:36 +00001133 /// KnownSafe - After an objc_retain, the reference count of the referenced
1134 /// object is known to be positive. Similarly, before an objc_release, the
1135 /// reference count of the referenced object is known to be positive. If
1136 /// there are retain-release pairs in code regions where the retain count
1137 /// is known to be positive, they can be eliminated, regardless of any side
1138 /// effects between them.
1139 ///
1140 /// Also, a retain+release pair nested within another retain+release
1141 /// pair all on the known same pointer value can be eliminated, regardless
1142 /// of any intervening side effects.
1143 ///
1144 /// KnownSafe is true when either of these conditions is satisfied.
1145 bool KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00001146
1147 /// IsRetainBlock - True if the Calls are objc_retainBlock calls (as
1148 /// opposed to objc_retain calls).
1149 bool IsRetainBlock;
1150
1151 /// IsTailCallRelease - True of the objc_release calls are all marked
1152 /// with the "tail" keyword.
1153 bool IsTailCallRelease;
1154
1155 /// ReleaseMetadata - If the Calls are objc_release calls and they all have
1156 /// a clang.imprecise_release tag, this is the metadata tag.
1157 MDNode *ReleaseMetadata;
1158
1159 /// Calls - For a top-down sequence, the set of objc_retains or
1160 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
1161 SmallPtrSet<Instruction *, 2> Calls;
1162
1163 /// ReverseInsertPts - The set of optimal insert positions for
1164 /// moving calls in the opposite sequence.
1165 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
1166
1167 RRInfo() :
Dan Gohmane6d5e882011-08-19 00:26:36 +00001168 KnownSafe(false), IsRetainBlock(false), IsTailCallRelease(false),
John McCall9fbd3182011-06-15 23:37:01 +00001169 ReleaseMetadata(0) {}
1170
1171 void clear();
1172 };
1173}
1174
1175void RRInfo::clear() {
Dan Gohmane6d5e882011-08-19 00:26:36 +00001176 KnownSafe = false;
John McCall9fbd3182011-06-15 23:37:01 +00001177 IsRetainBlock = false;
1178 IsTailCallRelease = false;
1179 ReleaseMetadata = 0;
1180 Calls.clear();
1181 ReverseInsertPts.clear();
1182}
1183
1184namespace {
1185 /// PtrState - This class summarizes several per-pointer runtime properties
1186 /// which are propogated through the flow graph.
1187 class PtrState {
1188 /// RefCount - The known minimum number of reference count increments.
1189 unsigned RefCount;
1190
Dan Gohmane6d5e882011-08-19 00:26:36 +00001191 /// NestCount - The known minimum level of retain+release nesting.
1192 unsigned NestCount;
1193
John McCall9fbd3182011-06-15 23:37:01 +00001194 /// Seq - The current position in the sequence.
1195 Sequence Seq;
1196
1197 public:
1198 /// RRI - Unidirectional information about the current sequence.
1199 /// TODO: Encapsulate this better.
1200 RRInfo RRI;
1201
Dan Gohmane6d5e882011-08-19 00:26:36 +00001202 PtrState() : RefCount(0), NestCount(0), Seq(S_None) {}
John McCall9fbd3182011-06-15 23:37:01 +00001203
Dan Gohmana7f7db22011-08-12 00:26:31 +00001204 void SetAtLeastOneRefCount() {
1205 if (RefCount == 0) RefCount = 1;
1206 }
1207
John McCall9fbd3182011-06-15 23:37:01 +00001208 void IncrementRefCount() {
1209 if (RefCount != UINT_MAX) ++RefCount;
1210 }
1211
1212 void DecrementRefCount() {
1213 if (RefCount != 0) --RefCount;
1214 }
1215
John McCall9fbd3182011-06-15 23:37:01 +00001216 bool IsKnownIncremented() const {
1217 return RefCount > 0;
1218 }
1219
Dan Gohmane6d5e882011-08-19 00:26:36 +00001220 void IncrementNestCount() {
1221 if (NestCount != UINT_MAX) ++NestCount;
1222 }
1223
1224 void DecrementNestCount() {
1225 if (NestCount != 0) --NestCount;
1226 }
1227
1228 bool IsKnownNested() const {
1229 return NestCount > 0;
1230 }
1231
John McCall9fbd3182011-06-15 23:37:01 +00001232 void SetSeq(Sequence NewSeq) {
1233 Seq = NewSeq;
1234 }
1235
1236 void SetSeqToRelease(MDNode *M) {
1237 if (Seq == S_None || Seq == S_Use) {
1238 Seq = M ? S_MovableRelease : S_Release;
1239 RRI.ReleaseMetadata = M;
1240 } else if (Seq != S_MovableRelease || RRI.ReleaseMetadata != M) {
1241 Seq = S_Release;
1242 RRI.ReleaseMetadata = 0;
1243 }
1244 }
1245
1246 Sequence GetSeq() const {
1247 return Seq;
1248 }
1249
1250 void ClearSequenceProgress() {
1251 Seq = S_None;
1252 RRI.clear();
1253 }
1254
1255 void Merge(const PtrState &Other, bool TopDown);
1256 };
1257}
1258
1259void
1260PtrState::Merge(const PtrState &Other, bool TopDown) {
1261 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
1262 RefCount = std::min(RefCount, Other.RefCount);
Dan Gohmane6d5e882011-08-19 00:26:36 +00001263 NestCount = std::min(NestCount, Other.NestCount);
John McCall9fbd3182011-06-15 23:37:01 +00001264
1265 // We can't merge a plain objc_retain with an objc_retainBlock.
1266 if (RRI.IsRetainBlock != Other.RRI.IsRetainBlock)
1267 Seq = S_None;
1268
1269 if (Seq == S_None) {
1270 RRI.clear();
1271 } else {
1272 // Conservatively merge the ReleaseMetadata information.
1273 if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
1274 RRI.ReleaseMetadata = 0;
1275
Dan Gohmane6d5e882011-08-19 00:26:36 +00001276 RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00001277 RRI.IsTailCallRelease = RRI.IsTailCallRelease && Other.RRI.IsTailCallRelease;
1278 RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
1279 RRI.ReverseInsertPts.insert(Other.RRI.ReverseInsertPts.begin(),
1280 Other.RRI.ReverseInsertPts.end());
1281 }
1282}
1283
1284namespace {
1285 /// BBState - Per-BasicBlock state.
1286 class BBState {
1287 /// TopDownPathCount - The number of unique control paths from the entry
1288 /// which can reach this block.
1289 unsigned TopDownPathCount;
1290
1291 /// BottomUpPathCount - The number of unique control paths to exits
1292 /// from this block.
1293 unsigned BottomUpPathCount;
1294
1295 /// MapTy - A type for PerPtrTopDown and PerPtrBottomUp.
1296 typedef MapVector<const Value *, PtrState> MapTy;
1297
1298 /// PerPtrTopDown - The top-down traversal uses this to record information
1299 /// known about a pointer at the bottom of each block.
1300 MapTy PerPtrTopDown;
1301
1302 /// PerPtrBottomUp - The bottom-up traversal uses this to record information
1303 /// known about a pointer at the top of each block.
1304 MapTy PerPtrBottomUp;
1305
1306 public:
1307 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
1308
1309 typedef MapTy::iterator ptr_iterator;
1310 typedef MapTy::const_iterator ptr_const_iterator;
1311
1312 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
1313 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
1314 ptr_const_iterator top_down_ptr_begin() const {
1315 return PerPtrTopDown.begin();
1316 }
1317 ptr_const_iterator top_down_ptr_end() const {
1318 return PerPtrTopDown.end();
1319 }
1320
1321 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
1322 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
1323 ptr_const_iterator bottom_up_ptr_begin() const {
1324 return PerPtrBottomUp.begin();
1325 }
1326 ptr_const_iterator bottom_up_ptr_end() const {
1327 return PerPtrBottomUp.end();
1328 }
1329
1330 /// SetAsEntry - Mark this block as being an entry block, which has one
1331 /// path from the entry by definition.
1332 void SetAsEntry() { TopDownPathCount = 1; }
1333
1334 /// SetAsExit - Mark this block as being an exit block, which has one
1335 /// path to an exit by definition.
1336 void SetAsExit() { BottomUpPathCount = 1; }
1337
1338 PtrState &getPtrTopDownState(const Value *Arg) {
1339 return PerPtrTopDown[Arg];
1340 }
1341
1342 PtrState &getPtrBottomUpState(const Value *Arg) {
1343 return PerPtrBottomUp[Arg];
1344 }
1345
1346 void clearBottomUpPointers() {
Evan Chenga81388f2011-08-04 18:40:26 +00001347 PerPtrBottomUp.clear();
John McCall9fbd3182011-06-15 23:37:01 +00001348 }
1349
1350 void clearTopDownPointers() {
1351 PerPtrTopDown.clear();
1352 }
1353
1354 void InitFromPred(const BBState &Other);
1355 void InitFromSucc(const BBState &Other);
1356 void MergePred(const BBState &Other);
1357 void MergeSucc(const BBState &Other);
1358
1359 /// GetAllPathCount - Return the number of possible unique paths from an
1360 /// entry to an exit which pass through this block. This is only valid
1361 /// after both the top-down and bottom-up traversals are complete.
1362 unsigned GetAllPathCount() const {
1363 return TopDownPathCount * BottomUpPathCount;
1364 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00001365
1366 /// IsVisitedTopDown - Test whether the block for this BBState has been
1367 /// visited by the top-down portion of the algorithm.
1368 bool isVisitedTopDown() const {
1369 return TopDownPathCount != 0;
1370 }
John McCall9fbd3182011-06-15 23:37:01 +00001371 };
1372}
1373
1374void BBState::InitFromPred(const BBState &Other) {
1375 PerPtrTopDown = Other.PerPtrTopDown;
1376 TopDownPathCount = Other.TopDownPathCount;
1377}
1378
1379void BBState::InitFromSucc(const BBState &Other) {
1380 PerPtrBottomUp = Other.PerPtrBottomUp;
1381 BottomUpPathCount = Other.BottomUpPathCount;
1382}
1383
1384/// MergePred - The top-down traversal uses this to merge information about
1385/// predecessors to form the initial state for a new block.
1386void BBState::MergePred(const BBState &Other) {
1387 // Other.TopDownPathCount can be 0, in which case it is either dead or a
1388 // loop backedge. Loop backedges are special.
1389 TopDownPathCount += Other.TopDownPathCount;
1390
1391 // For each entry in the other set, if our set has an entry with the same key,
1392 // merge the entries. Otherwise, copy the entry and merge it with an empty
1393 // entry.
1394 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
1395 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
1396 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
1397 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1398 /*TopDown=*/true);
1399 }
1400
Dan Gohmanfa7eed12011-08-11 21:06:32 +00001401 // For each entry in our set, if the other set doesn't have an entry with the
John McCall9fbd3182011-06-15 23:37:01 +00001402 // same key, force it to merge with an empty entry.
1403 for (ptr_iterator MI = top_down_ptr_begin(),
1404 ME = top_down_ptr_end(); MI != ME; ++MI)
1405 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
1406 MI->second.Merge(PtrState(), /*TopDown=*/true);
1407}
1408
1409/// MergeSucc - The bottom-up traversal uses this to merge information about
1410/// successors to form the initial state for a new block.
1411void BBState::MergeSucc(const BBState &Other) {
1412 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
1413 // loop backedge. Loop backedges are special.
1414 BottomUpPathCount += Other.BottomUpPathCount;
1415
1416 // For each entry in the other set, if our set has an entry with the
1417 // same key, merge the entries. Otherwise, copy the entry and merge
1418 // it with an empty entry.
1419 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
1420 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
1421 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
1422 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1423 /*TopDown=*/false);
1424 }
1425
Dan Gohmanfa7eed12011-08-11 21:06:32 +00001426 // For each entry in our set, if the other set doesn't have an entry
John McCall9fbd3182011-06-15 23:37:01 +00001427 // with the same key, force it to merge with an empty entry.
1428 for (ptr_iterator MI = bottom_up_ptr_begin(),
1429 ME = bottom_up_ptr_end(); MI != ME; ++MI)
1430 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
1431 MI->second.Merge(PtrState(), /*TopDown=*/false);
1432}
1433
1434namespace {
1435 /// ObjCARCOpt - The main ARC optimization pass.
1436 class ObjCARCOpt : public FunctionPass {
1437 bool Changed;
1438 ProvenanceAnalysis PA;
1439
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00001440 /// Run - A flag indicating whether this optimization pass should run.
1441 bool Run;
1442
John McCall9fbd3182011-06-15 23:37:01 +00001443 /// RetainRVCallee, etc. - Declarations for ObjC runtime
1444 /// functions, for use in creating calls to them. These are initialized
1445 /// lazily to avoid cluttering up the Module with unused declarations.
1446 Constant *RetainRVCallee, *AutoreleaseRVCallee, *ReleaseCallee,
Dan Gohman44280692011-07-22 22:29:21 +00001447 *RetainCallee, *RetainBlockCallee, *AutoreleaseCallee;
John McCall9fbd3182011-06-15 23:37:01 +00001448
1449 /// UsedInThisFunciton - Flags which determine whether each of the
1450 /// interesting runtine functions is in fact used in the current function.
1451 unsigned UsedInThisFunction;
1452
1453 /// ImpreciseReleaseMDKind - The Metadata Kind for clang.imprecise_release
1454 /// metadata.
1455 unsigned ImpreciseReleaseMDKind;
1456
1457 Constant *getRetainRVCallee(Module *M);
1458 Constant *getAutoreleaseRVCallee(Module *M);
1459 Constant *getReleaseCallee(Module *M);
1460 Constant *getRetainCallee(Module *M);
Dan Gohman44280692011-07-22 22:29:21 +00001461 Constant *getRetainBlockCallee(Module *M);
John McCall9fbd3182011-06-15 23:37:01 +00001462 Constant *getAutoreleaseCallee(Module *M);
1463
1464 void OptimizeRetainCall(Function &F, Instruction *Retain);
1465 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
1466 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV);
1467 void OptimizeIndividualCalls(Function &F);
1468
1469 void CheckForCFGHazards(const BasicBlock *BB,
1470 DenseMap<const BasicBlock *, BBState> &BBStates,
1471 BBState &MyStates) const;
1472 bool VisitBottomUp(BasicBlock *BB,
1473 DenseMap<const BasicBlock *, BBState> &BBStates,
1474 MapVector<Value *, RRInfo> &Retains);
1475 bool VisitTopDown(BasicBlock *BB,
1476 DenseMap<const BasicBlock *, BBState> &BBStates,
1477 DenseMap<Value *, RRInfo> &Releases);
1478 bool Visit(Function &F,
1479 DenseMap<const BasicBlock *, BBState> &BBStates,
1480 MapVector<Value *, RRInfo> &Retains,
1481 DenseMap<Value *, RRInfo> &Releases);
1482
1483 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1484 MapVector<Value *, RRInfo> &Retains,
1485 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman44280692011-07-22 22:29:21 +00001486 SmallVectorImpl<Instruction *> &DeadInsts,
1487 Module *M);
John McCall9fbd3182011-06-15 23:37:01 +00001488
1489 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1490 MapVector<Value *, RRInfo> &Retains,
Dan Gohman44280692011-07-22 22:29:21 +00001491 DenseMap<Value *, RRInfo> &Releases,
1492 Module *M);
John McCall9fbd3182011-06-15 23:37:01 +00001493
1494 void OptimizeWeakCalls(Function &F);
1495
1496 bool OptimizeSequences(Function &F);
1497
1498 void OptimizeReturns(Function &F);
1499
1500 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1501 virtual bool doInitialization(Module &M);
1502 virtual bool runOnFunction(Function &F);
1503 virtual void releaseMemory();
1504
1505 public:
1506 static char ID;
1507 ObjCARCOpt() : FunctionPass(ID) {
1508 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1509 }
1510 };
1511}
1512
1513char ObjCARCOpt::ID = 0;
1514INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1515 "objc-arc", "ObjC ARC optimization", false, false)
1516INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1517INITIALIZE_PASS_END(ObjCARCOpt,
1518 "objc-arc", "ObjC ARC optimization", false, false)
1519
1520Pass *llvm::createObjCARCOptPass() {
1521 return new ObjCARCOpt();
1522}
1523
1524void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1525 AU.addRequired<ObjCARCAliasAnalysis>();
1526 AU.addRequired<AliasAnalysis>();
1527 // ARC optimization doesn't currently split critical edges.
1528 AU.setPreservesCFG();
1529}
1530
1531Constant *ObjCARCOpt::getRetainRVCallee(Module *M) {
1532 if (!RetainRVCallee) {
1533 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001534 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1535 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00001536 Params.push_back(I8X);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001537 FunctionType *FTy =
John McCall9fbd3182011-06-15 23:37:01 +00001538 FunctionType::get(I8X, Params, /*isVarArg=*/false);
1539 AttrListPtr Attributes;
1540 Attributes.addAttr(~0u, Attribute::NoUnwind);
1541 RetainRVCallee =
1542 M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy,
1543 Attributes);
1544 }
1545 return RetainRVCallee;
1546}
1547
1548Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1549 if (!AutoreleaseRVCallee) {
1550 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001551 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1552 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00001553 Params.push_back(I8X);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001554 FunctionType *FTy =
John McCall9fbd3182011-06-15 23:37:01 +00001555 FunctionType::get(I8X, Params, /*isVarArg=*/false);
1556 AttrListPtr Attributes;
1557 Attributes.addAttr(~0u, Attribute::NoUnwind);
1558 AutoreleaseRVCallee =
1559 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
1560 Attributes);
1561 }
1562 return AutoreleaseRVCallee;
1563}
1564
1565Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1566 if (!ReleaseCallee) {
1567 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001568 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00001569 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1570 AttrListPtr Attributes;
1571 Attributes.addAttr(~0u, Attribute::NoUnwind);
1572 ReleaseCallee =
1573 M->getOrInsertFunction(
1574 "objc_release",
1575 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
1576 Attributes);
1577 }
1578 return ReleaseCallee;
1579}
1580
1581Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1582 if (!RetainCallee) {
1583 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001584 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00001585 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1586 AttrListPtr Attributes;
1587 Attributes.addAttr(~0u, Attribute::NoUnwind);
1588 RetainCallee =
1589 M->getOrInsertFunction(
1590 "objc_retain",
1591 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1592 Attributes);
1593 }
1594 return RetainCallee;
1595}
1596
Dan Gohman44280692011-07-22 22:29:21 +00001597Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1598 if (!RetainBlockCallee) {
1599 LLVMContext &C = M->getContext();
1600 std::vector<Type *> Params;
1601 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1602 AttrListPtr Attributes;
1603 Attributes.addAttr(~0u, Attribute::NoUnwind);
1604 RetainBlockCallee =
1605 M->getOrInsertFunction(
1606 "objc_retainBlock",
1607 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1608 Attributes);
1609 }
1610 return RetainBlockCallee;
1611}
1612
John McCall9fbd3182011-06-15 23:37:01 +00001613Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1614 if (!AutoreleaseCallee) {
1615 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001616 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00001617 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1618 AttrListPtr Attributes;
1619 Attributes.addAttr(~0u, Attribute::NoUnwind);
1620 AutoreleaseCallee =
1621 M->getOrInsertFunction(
1622 "objc_autorelease",
1623 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1624 Attributes);
1625 }
1626 return AutoreleaseCallee;
1627}
1628
1629/// CanAlterRefCount - Test whether the given instruction can result in a
1630/// reference count modification (positive or negative) for the pointer's
1631/// object.
1632static bool
1633CanAlterRefCount(const Instruction *Inst, const Value *Ptr,
1634 ProvenanceAnalysis &PA, InstructionClass Class) {
1635 switch (Class) {
1636 case IC_Autorelease:
1637 case IC_AutoreleaseRV:
1638 case IC_User:
1639 // These operations never directly modify a reference count.
1640 return false;
1641 default: break;
1642 }
1643
1644 ImmutableCallSite CS = static_cast<const Value *>(Inst);
1645 assert(CS && "Only calls can alter reference counts!");
1646
1647 // See if AliasAnalysis can help us with the call.
1648 AliasAnalysis::ModRefBehavior MRB = PA.getAA()->getModRefBehavior(CS);
1649 if (AliasAnalysis::onlyReadsMemory(MRB))
1650 return false;
1651 if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
1652 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1653 I != E; ++I) {
1654 const Value *Op = *I;
1655 if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1656 return true;
1657 }
1658 return false;
1659 }
1660
1661 // Assume the worst.
1662 return true;
1663}
1664
1665/// CanUse - Test whether the given instruction can "use" the given pointer's
1666/// object in a way that requires the reference count to be positive.
1667static bool
1668CanUse(const Instruction *Inst, const Value *Ptr, ProvenanceAnalysis &PA,
1669 InstructionClass Class) {
1670 // IC_Call operations (as opposed to IC_CallOrUser) never "use" objc pointers.
1671 if (Class == IC_Call)
1672 return false;
1673
1674 // Consider various instructions which may have pointer arguments which are
1675 // not "uses".
1676 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(Inst)) {
1677 // Comparing a pointer with null, or any other constant, isn't really a use,
1678 // because we don't care what the pointer points to, or about the values
1679 // of any other dynamic reference-counted pointers.
1680 if (!IsPotentialUse(ICI->getOperand(1)))
1681 return false;
1682 } else if (ImmutableCallSite CS = static_cast<const Value *>(Inst)) {
1683 // For calls, just check the arguments (and not the callee operand).
1684 for (ImmutableCallSite::arg_iterator OI = CS.arg_begin(),
1685 OE = CS.arg_end(); OI != OE; ++OI) {
1686 const Value *Op = *OI;
1687 if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1688 return true;
1689 }
1690 return false;
1691 } else if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1692 // Special-case stores, because we don't care about the stored value, just
1693 // the store address.
1694 const Value *Op = GetUnderlyingObjCPtr(SI->getPointerOperand());
1695 // If we can't tell what the underlying object was, assume there is a
1696 // dependence.
1697 return IsPotentialUse(Op) && PA.related(Op, Ptr);
1698 }
1699
1700 // Check each operand for a match.
1701 for (User::const_op_iterator OI = Inst->op_begin(), OE = Inst->op_end();
1702 OI != OE; ++OI) {
1703 const Value *Op = *OI;
1704 if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1705 return true;
1706 }
1707 return false;
1708}
1709
1710/// CanInterruptRV - Test whether the given instruction can autorelease
1711/// any pointer or cause an autoreleasepool pop.
1712static bool
1713CanInterruptRV(InstructionClass Class) {
1714 switch (Class) {
1715 case IC_AutoreleasepoolPop:
1716 case IC_CallOrUser:
1717 case IC_Call:
1718 case IC_Autorelease:
1719 case IC_AutoreleaseRV:
1720 case IC_FusedRetainAutorelease:
1721 case IC_FusedRetainAutoreleaseRV:
1722 return true;
1723 default:
1724 return false;
1725 }
1726}
1727
1728namespace {
1729 /// DependenceKind - There are several kinds of dependence-like concepts in
1730 /// use here.
1731 enum DependenceKind {
1732 NeedsPositiveRetainCount,
1733 CanChangeRetainCount,
1734 RetainAutoreleaseDep, ///< Blocks objc_retainAutorelease.
1735 RetainAutoreleaseRVDep, ///< Blocks objc_retainAutoreleaseReturnValue.
1736 RetainRVDep ///< Blocks objc_retainAutoreleasedReturnValue.
1737 };
1738}
1739
1740/// Depends - Test if there can be dependencies on Inst through Arg. This
1741/// function only tests dependencies relevant for removing pairs of calls.
1742static bool
1743Depends(DependenceKind Flavor, Instruction *Inst, const Value *Arg,
1744 ProvenanceAnalysis &PA) {
1745 // If we've reached the definition of Arg, stop.
1746 if (Inst == Arg)
1747 return true;
1748
1749 switch (Flavor) {
1750 case NeedsPositiveRetainCount: {
1751 InstructionClass Class = GetInstructionClass(Inst);
1752 switch (Class) {
1753 case IC_AutoreleasepoolPop:
1754 case IC_AutoreleasepoolPush:
1755 case IC_None:
1756 return false;
1757 default:
1758 return CanUse(Inst, Arg, PA, Class);
1759 }
1760 }
1761
1762 case CanChangeRetainCount: {
1763 InstructionClass Class = GetInstructionClass(Inst);
1764 switch (Class) {
1765 case IC_AutoreleasepoolPop:
1766 // Conservatively assume this can decrement any count.
1767 return true;
1768 case IC_AutoreleasepoolPush:
1769 case IC_None:
1770 return false;
1771 default:
1772 return CanAlterRefCount(Inst, Arg, PA, Class);
1773 }
1774 }
1775
1776 case RetainAutoreleaseDep:
1777 switch (GetBasicInstructionClass(Inst)) {
1778 case IC_AutoreleasepoolPop:
1779 // Don't merge an objc_autorelease with an objc_retain inside a different
1780 // autoreleasepool scope.
1781 return true;
1782 case IC_Retain:
1783 case IC_RetainRV:
1784 // Check for a retain of the same pointer for merging.
1785 return GetObjCArg(Inst) == Arg;
1786 default:
1787 // Nothing else matters for objc_retainAutorelease formation.
1788 return false;
1789 }
1790 break;
1791
1792 case RetainAutoreleaseRVDep: {
1793 InstructionClass Class = GetBasicInstructionClass(Inst);
1794 switch (Class) {
1795 case IC_Retain:
1796 case IC_RetainRV:
1797 // Check for a retain of the same pointer for merging.
1798 return GetObjCArg(Inst) == Arg;
1799 default:
1800 // Anything that can autorelease interrupts
1801 // retainAutoreleaseReturnValue formation.
1802 return CanInterruptRV(Class);
1803 }
1804 break;
1805 }
1806
1807 case RetainRVDep:
1808 return CanInterruptRV(GetBasicInstructionClass(Inst));
1809 }
1810
1811 llvm_unreachable("Invalid dependence flavor");
1812 return true;
1813}
1814
1815/// FindDependencies - Walk up the CFG from StartPos (which is in StartBB) and
1816/// find local and non-local dependencies on Arg.
1817/// TODO: Cache results?
1818static void
1819FindDependencies(DependenceKind Flavor,
1820 const Value *Arg,
1821 BasicBlock *StartBB, Instruction *StartInst,
1822 SmallPtrSet<Instruction *, 4> &DependingInstructions,
1823 SmallPtrSet<const BasicBlock *, 4> &Visited,
1824 ProvenanceAnalysis &PA) {
1825 BasicBlock::iterator StartPos = StartInst;
1826
1827 SmallVector<std::pair<BasicBlock *, BasicBlock::iterator>, 4> Worklist;
1828 Worklist.push_back(std::make_pair(StartBB, StartPos));
1829 do {
1830 std::pair<BasicBlock *, BasicBlock::iterator> Pair =
1831 Worklist.pop_back_val();
1832 BasicBlock *LocalStartBB = Pair.first;
1833 BasicBlock::iterator LocalStartPos = Pair.second;
1834 BasicBlock::iterator StartBBBegin = LocalStartBB->begin();
1835 for (;;) {
1836 if (LocalStartPos == StartBBBegin) {
1837 pred_iterator PI(LocalStartBB), PE(LocalStartBB, false);
1838 if (PI == PE)
1839 // If we've reached the function entry, produce a null dependence.
1840 DependingInstructions.insert(0);
1841 else
1842 // Add the predecessors to the worklist.
1843 do {
1844 BasicBlock *PredBB = *PI;
1845 if (Visited.insert(PredBB))
1846 Worklist.push_back(std::make_pair(PredBB, PredBB->end()));
1847 } while (++PI != PE);
1848 break;
1849 }
1850
1851 Instruction *Inst = --LocalStartPos;
1852 if (Depends(Flavor, Inst, Arg, PA)) {
1853 DependingInstructions.insert(Inst);
1854 break;
1855 }
1856 }
1857 } while (!Worklist.empty());
1858
1859 // Determine whether the original StartBB post-dominates all of the blocks we
1860 // visited. If not, insert a sentinal indicating that most optimizations are
1861 // not safe.
1862 for (SmallPtrSet<const BasicBlock *, 4>::const_iterator I = Visited.begin(),
1863 E = Visited.end(); I != E; ++I) {
1864 const BasicBlock *BB = *I;
1865 if (BB == StartBB)
1866 continue;
1867 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
1868 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
1869 const BasicBlock *Succ = *SI;
1870 if (Succ != StartBB && !Visited.count(Succ)) {
1871 DependingInstructions.insert(reinterpret_cast<Instruction *>(-1));
1872 return;
1873 }
1874 }
1875 }
1876}
1877
1878static bool isNullOrUndef(const Value *V) {
1879 return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
1880}
1881
1882static bool isNoopInstruction(const Instruction *I) {
1883 return isa<BitCastInst>(I) ||
1884 (isa<GetElementPtrInst>(I) &&
1885 cast<GetElementPtrInst>(I)->hasAllZeroIndices());
1886}
1887
1888/// OptimizeRetainCall - Turn objc_retain into
1889/// objc_retainAutoreleasedReturnValue if the operand is a return value.
1890void
1891ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) {
1892 CallSite CS(GetObjCArg(Retain));
1893 Instruction *Call = CS.getInstruction();
1894 if (!Call) return;
1895 if (Call->getParent() != Retain->getParent()) return;
1896
1897 // Check that the call is next to the retain.
1898 BasicBlock::iterator I = Call;
1899 ++I;
1900 while (isNoopInstruction(I)) ++I;
1901 if (&*I != Retain)
1902 return;
1903
1904 // Turn it to an objc_retainAutoreleasedReturnValue..
1905 Changed = true;
1906 ++NumPeeps;
1907 cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent()));
1908}
1909
1910/// OptimizeRetainRVCall - Turn objc_retainAutoreleasedReturnValue into
1911/// objc_retain if the operand is not a return value. Or, if it can be
1912/// paired with an objc_autoreleaseReturnValue, delete the pair and
1913/// return true.
1914bool
1915ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
1916 // Check for the argument being from an immediately preceding call.
1917 Value *Arg = GetObjCArg(RetainRV);
1918 CallSite CS(Arg);
1919 if (Instruction *Call = CS.getInstruction())
1920 if (Call->getParent() == RetainRV->getParent()) {
1921 BasicBlock::iterator I = Call;
1922 ++I;
1923 while (isNoopInstruction(I)) ++I;
1924 if (&*I == RetainRV)
1925 return false;
1926 }
1927
1928 // Check for being preceded by an objc_autoreleaseReturnValue on the same
1929 // pointer. In this case, we can delete the pair.
1930 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
1931 if (I != Begin) {
1932 do --I; while (I != Begin && isNoopInstruction(I));
1933 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
1934 GetObjCArg(I) == Arg) {
1935 Changed = true;
1936 ++NumPeeps;
1937 EraseInstruction(I);
1938 EraseInstruction(RetainRV);
1939 return true;
1940 }
1941 }
1942
1943 // Turn it to a plain objc_retain.
1944 Changed = true;
1945 ++NumPeeps;
1946 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
1947 return false;
1948}
1949
1950/// OptimizeAutoreleaseRVCall - Turn objc_autoreleaseReturnValue into
1951/// objc_autorelease if the result is not used as a return value.
1952void
1953ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV) {
1954 // Check for a return of the pointer value.
1955 const Value *Ptr = GetObjCArg(AutoreleaseRV);
Dan Gohman126a54f2011-08-12 00:36:31 +00001956 SmallVector<const Value *, 2> Users;
1957 Users.push_back(Ptr);
1958 do {
1959 Ptr = Users.pop_back_val();
1960 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
1961 UI != UE; ++UI) {
1962 const User *I = *UI;
1963 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
1964 return;
1965 if (isa<BitCastInst>(I))
1966 Users.push_back(I);
1967 }
1968 } while (!Users.empty());
John McCall9fbd3182011-06-15 23:37:01 +00001969
1970 Changed = true;
1971 ++NumPeeps;
1972 cast<CallInst>(AutoreleaseRV)->
1973 setCalledFunction(getAutoreleaseCallee(F.getParent()));
1974}
1975
1976/// OptimizeIndividualCalls - Visit each call, one at a time, and make
1977/// simplifications without doing any additional analysis.
1978void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
1979 // Reset all the flags in preparation for recomputing them.
1980 UsedInThisFunction = 0;
1981
1982 // Visit all objc_* calls in F.
1983 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
1984 Instruction *Inst = &*I++;
1985 InstructionClass Class = GetBasicInstructionClass(Inst);
1986
1987 switch (Class) {
1988 default: break;
1989
1990 // Delete no-op casts. These function calls have special semantics, but
1991 // the semantics are entirely implemented via lowering in the front-end,
1992 // so by the time they reach the optimizer, they are just no-op calls
1993 // which return their argument.
1994 //
1995 // There are gray areas here, as the ability to cast reference-counted
1996 // pointers to raw void* and back allows code to break ARC assumptions,
1997 // however these are currently considered to be unimportant.
1998 case IC_NoopCast:
1999 Changed = true;
2000 ++NumNoops;
2001 EraseInstruction(Inst);
2002 continue;
2003
2004 // If the pointer-to-weak-pointer is null, it's undefined behavior.
2005 case IC_StoreWeak:
2006 case IC_LoadWeak:
2007 case IC_LoadWeakRetained:
2008 case IC_InitWeak:
2009 case IC_DestroyWeak: {
2010 CallInst *CI = cast<CallInst>(Inst);
2011 if (isNullOrUndef(CI->getArgOperand(0))) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002012 Type *Ty = CI->getArgOperand(0)->getType();
John McCall9fbd3182011-06-15 23:37:01 +00002013 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2014 Constant::getNullValue(Ty),
2015 CI);
2016 CI->replaceAllUsesWith(UndefValue::get(CI->getType()));
2017 CI->eraseFromParent();
2018 continue;
2019 }
2020 break;
2021 }
2022 case IC_CopyWeak:
2023 case IC_MoveWeak: {
2024 CallInst *CI = cast<CallInst>(Inst);
2025 if (isNullOrUndef(CI->getArgOperand(0)) ||
2026 isNullOrUndef(CI->getArgOperand(1))) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002027 Type *Ty = CI->getArgOperand(0)->getType();
John McCall9fbd3182011-06-15 23:37:01 +00002028 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2029 Constant::getNullValue(Ty),
2030 CI);
2031 CI->replaceAllUsesWith(UndefValue::get(CI->getType()));
2032 CI->eraseFromParent();
2033 continue;
2034 }
2035 break;
2036 }
2037 case IC_Retain:
2038 OptimizeRetainCall(F, Inst);
2039 break;
2040 case IC_RetainRV:
2041 if (OptimizeRetainRVCall(F, Inst))
2042 continue;
2043 break;
2044 case IC_AutoreleaseRV:
2045 OptimizeAutoreleaseRVCall(F, Inst);
2046 break;
2047 }
2048
2049 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
2050 if (IsAutorelease(Class) && Inst->use_empty()) {
2051 CallInst *Call = cast<CallInst>(Inst);
2052 const Value *Arg = Call->getArgOperand(0);
2053 Arg = FindSingleUseIdentifiedObject(Arg);
2054 if (Arg) {
2055 Changed = true;
2056 ++NumAutoreleases;
2057
2058 // Create the declaration lazily.
2059 LLVMContext &C = Inst->getContext();
2060 CallInst *NewCall =
2061 CallInst::Create(getReleaseCallee(F.getParent()),
2062 Call->getArgOperand(0), "", Call);
2063 NewCall->setMetadata(ImpreciseReleaseMDKind,
2064 MDNode::get(C, ArrayRef<Value *>()));
2065 EraseInstruction(Call);
2066 Inst = NewCall;
2067 Class = IC_Release;
2068 }
2069 }
2070
2071 // For functions which can never be passed stack arguments, add
2072 // a tail keyword.
2073 if (IsAlwaysTail(Class)) {
2074 Changed = true;
2075 cast<CallInst>(Inst)->setTailCall();
2076 }
2077
2078 // Set nounwind as needed.
2079 if (IsNoThrow(Class)) {
2080 Changed = true;
2081 cast<CallInst>(Inst)->setDoesNotThrow();
2082 }
2083
2084 if (!IsNoopOnNull(Class)) {
2085 UsedInThisFunction |= 1 << Class;
2086 continue;
2087 }
2088
2089 const Value *Arg = GetObjCArg(Inst);
2090
2091 // ARC calls with null are no-ops. Delete them.
2092 if (isNullOrUndef(Arg)) {
2093 Changed = true;
2094 ++NumNoops;
2095 EraseInstruction(Inst);
2096 continue;
2097 }
2098
2099 // Keep track of which of retain, release, autorelease, and retain_block
2100 // are actually present in this function.
2101 UsedInThisFunction |= 1 << Class;
2102
2103 // If Arg is a PHI, and one or more incoming values to the
2104 // PHI are null, and the call is control-equivalent to the PHI, and there
2105 // are no relevant side effects between the PHI and the call, the call
2106 // could be pushed up to just those paths with non-null incoming values.
2107 // For now, don't bother splitting critical edges for this.
2108 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
2109 Worklist.push_back(std::make_pair(Inst, Arg));
2110 do {
2111 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
2112 Inst = Pair.first;
2113 Arg = Pair.second;
2114
2115 const PHINode *PN = dyn_cast<PHINode>(Arg);
2116 if (!PN) continue;
2117
2118 // Determine if the PHI has any null operands, or any incoming
2119 // critical edges.
2120 bool HasNull = false;
2121 bool HasCriticalEdges = false;
2122 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2123 Value *Incoming =
2124 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2125 if (isNullOrUndef(Incoming))
2126 HasNull = true;
2127 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
2128 .getNumSuccessors() != 1) {
2129 HasCriticalEdges = true;
2130 break;
2131 }
2132 }
2133 // If we have null operands and no critical edges, optimize.
2134 if (!HasCriticalEdges && HasNull) {
2135 SmallPtrSet<Instruction *, 4> DependingInstructions;
2136 SmallPtrSet<const BasicBlock *, 4> Visited;
2137
2138 // Check that there is nothing that cares about the reference
2139 // count between the call and the phi.
2140 FindDependencies(NeedsPositiveRetainCount, Arg,
2141 Inst->getParent(), Inst,
2142 DependingInstructions, Visited, PA);
2143 if (DependingInstructions.size() == 1 &&
2144 *DependingInstructions.begin() == PN) {
2145 Changed = true;
2146 ++NumPartialNoops;
2147 // Clone the call into each predecessor that has a non-null value.
2148 CallInst *CInst = cast<CallInst>(Inst);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002149 Type *ParamTy = CInst->getArgOperand(0)->getType();
John McCall9fbd3182011-06-15 23:37:01 +00002150 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2151 Value *Incoming =
2152 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2153 if (!isNullOrUndef(Incoming)) {
2154 CallInst *Clone = cast<CallInst>(CInst->clone());
2155 Value *Op = PN->getIncomingValue(i);
2156 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
2157 if (Op->getType() != ParamTy)
2158 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
2159 Clone->setArgOperand(0, Op);
2160 Clone->insertBefore(InsertPos);
2161 Worklist.push_back(std::make_pair(Clone, Incoming));
2162 }
2163 }
2164 // Erase the original call.
2165 EraseInstruction(CInst);
2166 continue;
2167 }
2168 }
2169 } while (!Worklist.empty());
2170 }
2171}
2172
2173/// CheckForCFGHazards - Check for critical edges, loop boundaries, irreducible
2174/// control flow, or other CFG structures where moving code across the edge
2175/// would result in it being executed more.
2176void
2177ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
2178 DenseMap<const BasicBlock *, BBState> &BBStates,
2179 BBState &MyStates) const {
2180 // If any top-down local-use or possible-dec has a succ which is earlier in
2181 // the sequence, forget it.
2182 for (BBState::ptr_const_iterator I = MyStates.top_down_ptr_begin(),
2183 E = MyStates.top_down_ptr_end(); I != E; ++I)
2184 switch (I->second.GetSeq()) {
2185 default: break;
2186 case S_Use: {
2187 const Value *Arg = I->first;
2188 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2189 bool SomeSuccHasSame = false;
2190 bool AllSuccsHaveSame = true;
Dan Gohmana7f7db22011-08-12 00:26:31 +00002191 PtrState &S = MyStates.getPtrTopDownState(Arg);
2192 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2193 PtrState &SuccS = BBStates[*SI].getPtrBottomUpState(Arg);
2194 switch (SuccS.GetSeq()) {
John McCall9fbd3182011-06-15 23:37:01 +00002195 case S_None:
Dan Gohmana7f7db22011-08-12 00:26:31 +00002196 case S_CanRelease: {
Dan Gohmane6d5e882011-08-19 00:26:36 +00002197 if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002198 S.ClearSequenceProgress();
2199 continue;
2200 }
John McCall9fbd3182011-06-15 23:37:01 +00002201 case S_Use:
2202 SomeSuccHasSame = true;
2203 break;
2204 case S_Stop:
2205 case S_Release:
2206 case S_MovableRelease:
Dan Gohmane6d5e882011-08-19 00:26:36 +00002207 if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002208 AllSuccsHaveSame = false;
John McCall9fbd3182011-06-15 23:37:01 +00002209 break;
2210 case S_Retain:
2211 llvm_unreachable("bottom-up pointer in retain state!");
2212 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002213 }
John McCall9fbd3182011-06-15 23:37:01 +00002214 // If the state at the other end of any of the successor edges
2215 // matches the current state, require all edges to match. This
2216 // guards against loops in the middle of a sequence.
2217 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002218 S.ClearSequenceProgress();
John McCall9fbd3182011-06-15 23:37:01 +00002219 }
2220 case S_CanRelease: {
2221 const Value *Arg = I->first;
2222 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2223 bool SomeSuccHasSame = false;
2224 bool AllSuccsHaveSame = true;
Dan Gohmana7f7db22011-08-12 00:26:31 +00002225 PtrState &S = MyStates.getPtrTopDownState(Arg);
2226 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2227 PtrState &SuccS = BBStates[*SI].getPtrBottomUpState(Arg);
2228 switch (SuccS.GetSeq()) {
2229 case S_None: {
Dan Gohmane6d5e882011-08-19 00:26:36 +00002230 if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002231 S.ClearSequenceProgress();
2232 continue;
2233 }
John McCall9fbd3182011-06-15 23:37:01 +00002234 case S_CanRelease:
2235 SomeSuccHasSame = true;
2236 break;
2237 case S_Stop:
2238 case S_Release:
2239 case S_MovableRelease:
2240 case S_Use:
Dan Gohmane6d5e882011-08-19 00:26:36 +00002241 if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002242 AllSuccsHaveSame = false;
John McCall9fbd3182011-06-15 23:37:01 +00002243 break;
2244 case S_Retain:
2245 llvm_unreachable("bottom-up pointer in retain state!");
2246 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002247 }
John McCall9fbd3182011-06-15 23:37:01 +00002248 // If the state at the other end of any of the successor edges
2249 // matches the current state, require all edges to match. This
2250 // guards against loops in the middle of a sequence.
2251 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002252 S.ClearSequenceProgress();
John McCall9fbd3182011-06-15 23:37:01 +00002253 }
2254 }
2255}
2256
2257bool
2258ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2259 DenseMap<const BasicBlock *, BBState> &BBStates,
2260 MapVector<Value *, RRInfo> &Retains) {
2261 bool NestingDetected = false;
2262 BBState &MyStates = BBStates[BB];
2263
2264 // Merge the states from each successor to compute the initial state
2265 // for the current block.
2266 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2267 succ_const_iterator SI(TI), SE(TI, false);
2268 if (SI == SE)
2269 MyStates.SetAsExit();
2270 else
2271 do {
2272 const BasicBlock *Succ = *SI++;
2273 if (Succ == BB)
2274 continue;
2275 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
Dan Gohmana7f7db22011-08-12 00:26:31 +00002276 // If we haven't seen this node yet, then we've found a CFG cycle.
2277 // Be optimistic here; it's CheckForCFGHazards' job detect trouble.
John McCall9fbd3182011-06-15 23:37:01 +00002278 if (I == BBStates.end())
2279 continue;
2280 MyStates.InitFromSucc(I->second);
2281 while (SI != SE) {
2282 Succ = *SI++;
2283 if (Succ != BB) {
2284 I = BBStates.find(Succ);
2285 if (I != BBStates.end())
2286 MyStates.MergeSucc(I->second);
2287 }
2288 }
2289 break;
2290 } while (SI != SE);
2291
2292 // Visit all the instructions, bottom-up.
2293 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2294 Instruction *Inst = llvm::prior(I);
2295 InstructionClass Class = GetInstructionClass(Inst);
2296 const Value *Arg = 0;
2297
2298 switch (Class) {
2299 case IC_Release: {
2300 Arg = GetObjCArg(Inst);
2301
2302 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2303
2304 // If we see two releases in a row on the same pointer. If so, make
2305 // a note, and we'll cicle back to revisit it after we've
2306 // hopefully eliminated the second release, which may allow us to
2307 // eliminate the first release too.
2308 // Theoretically we could implement removal of nested retain+release
2309 // pairs by making PtrState hold a stack of states, but this is
2310 // simple and avoids adding overhead for the non-nested case.
2311 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease)
2312 NestingDetected = true;
2313
2314 S.SetSeqToRelease(Inst->getMetadata(ImpreciseReleaseMDKind));
2315 S.RRI.clear();
Dan Gohmane6d5e882011-08-19 00:26:36 +00002316 S.RRI.KnownSafe = S.IsKnownNested() || S.IsKnownIncremented();
John McCall9fbd3182011-06-15 23:37:01 +00002317 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2318 S.RRI.Calls.insert(Inst);
2319
2320 S.IncrementRefCount();
Dan Gohmane6d5e882011-08-19 00:26:36 +00002321 S.IncrementNestCount();
John McCall9fbd3182011-06-15 23:37:01 +00002322 break;
2323 }
2324 case IC_RetainBlock:
2325 case IC_Retain:
2326 case IC_RetainRV: {
2327 Arg = GetObjCArg(Inst);
2328
2329 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2330 S.DecrementRefCount();
Dan Gohmana7f7db22011-08-12 00:26:31 +00002331 S.SetAtLeastOneRefCount();
Dan Gohmane6d5e882011-08-19 00:26:36 +00002332 S.DecrementNestCount();
John McCall9fbd3182011-06-15 23:37:01 +00002333
2334 switch (S.GetSeq()) {
2335 case S_Stop:
2336 case S_Release:
2337 case S_MovableRelease:
2338 case S_Use:
2339 S.RRI.ReverseInsertPts.clear();
2340 // FALL THROUGH
2341 case S_CanRelease:
2342 // Don't do retain+release tracking for IC_RetainRV, because it's
2343 // better to let it remain as the first instruction after a call.
2344 if (Class != IC_RetainRV) {
2345 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2346 Retains[Inst] = S.RRI;
2347 }
2348 S.ClearSequenceProgress();
2349 break;
2350 case S_None:
2351 break;
2352 case S_Retain:
2353 llvm_unreachable("bottom-up pointer in retain state!");
2354 }
Dan Gohmane6d5e882011-08-19 00:26:36 +00002355 continue;
John McCall9fbd3182011-06-15 23:37:01 +00002356 }
2357 case IC_AutoreleasepoolPop:
2358 // Conservatively, clear MyStates for all known pointers.
2359 MyStates.clearBottomUpPointers();
2360 continue;
2361 case IC_AutoreleasepoolPush:
2362 case IC_None:
2363 // These are irrelevant.
2364 continue;
2365 default:
2366 break;
2367 }
2368
2369 // Consider any other possible effects of this instruction on each
2370 // pointer being tracked.
2371 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
2372 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
2373 const Value *Ptr = MI->first;
2374 if (Ptr == Arg)
2375 continue; // Handled above.
2376 PtrState &S = MI->second;
2377 Sequence Seq = S.GetSeq();
2378
Dan Gohmane6d5e882011-08-19 00:26:36 +00002379 // Check for possible releases.
2380 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2381 S.DecrementRefCount();
Dan Gohmana7f7db22011-08-12 00:26:31 +00002382 switch (Seq) {
2383 case S_Use:
2384 S.SetSeq(S_CanRelease);
2385 continue;
2386 case S_CanRelease:
2387 case S_Release:
2388 case S_MovableRelease:
2389 case S_Stop:
2390 case S_None:
2391 break;
2392 case S_Retain:
2393 llvm_unreachable("bottom-up pointer in retain state!");
2394 }
Dan Gohmane6d5e882011-08-19 00:26:36 +00002395 }
John McCall9fbd3182011-06-15 23:37:01 +00002396
2397 // Check for possible direct uses.
2398 switch (Seq) {
2399 case S_Release:
2400 case S_MovableRelease:
2401 if (CanUse(Inst, Ptr, PA, Class)) {
2402 S.RRI.ReverseInsertPts.clear();
2403 S.RRI.ReverseInsertPts.insert(Inst);
2404 S.SetSeq(S_Use);
2405 } else if (Seq == S_Release &&
2406 (Class == IC_User || Class == IC_CallOrUser)) {
2407 // Non-movable releases depend on any possible objc pointer use.
2408 S.SetSeq(S_Stop);
2409 S.RRI.ReverseInsertPts.clear();
2410 S.RRI.ReverseInsertPts.insert(Inst);
2411 }
2412 break;
2413 case S_Stop:
2414 if (CanUse(Inst, Ptr, PA, Class))
2415 S.SetSeq(S_Use);
2416 break;
2417 case S_CanRelease:
2418 case S_Use:
2419 case S_None:
2420 break;
2421 case S_Retain:
2422 llvm_unreachable("bottom-up pointer in retain state!");
2423 }
2424 }
2425 }
2426
2427 return NestingDetected;
2428}
2429
2430bool
2431ObjCARCOpt::VisitTopDown(BasicBlock *BB,
2432 DenseMap<const BasicBlock *, BBState> &BBStates,
2433 DenseMap<Value *, RRInfo> &Releases) {
2434 bool NestingDetected = false;
2435 BBState &MyStates = BBStates[BB];
2436
2437 // Merge the states from each predecessor to compute the initial state
2438 // for the current block.
2439 const_pred_iterator PI(BB), PE(BB, false);
2440 if (PI == PE)
2441 MyStates.SetAsEntry();
2442 else
2443 do {
2444 const BasicBlock *Pred = *PI++;
2445 if (Pred == BB)
2446 continue;
2447 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
Dan Gohmana7f7db22011-08-12 00:26:31 +00002448 assert(I != BBStates.end());
2449 // If we haven't seen this node yet, then we've found a CFG cycle.
2450 // Be optimistic here; it's CheckForCFGHazards' job detect trouble.
2451 if (!I->second.isVisitedTopDown())
John McCall9fbd3182011-06-15 23:37:01 +00002452 continue;
2453 MyStates.InitFromPred(I->second);
2454 while (PI != PE) {
2455 Pred = *PI++;
2456 if (Pred != BB) {
2457 I = BBStates.find(Pred);
Dan Gohmana7f7db22011-08-12 00:26:31 +00002458 assert(I != BBStates.end());
2459 if (I->second.isVisitedTopDown())
John McCall9fbd3182011-06-15 23:37:01 +00002460 MyStates.MergePred(I->second);
2461 }
2462 }
2463 break;
2464 } while (PI != PE);
2465
2466 // Visit all the instructions, top-down.
2467 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2468 Instruction *Inst = I;
2469 InstructionClass Class = GetInstructionClass(Inst);
2470 const Value *Arg = 0;
2471
2472 switch (Class) {
2473 case IC_RetainBlock:
2474 case IC_Retain:
2475 case IC_RetainRV: {
2476 Arg = GetObjCArg(Inst);
2477
2478 PtrState &S = MyStates.getPtrTopDownState(Arg);
2479
2480 // Don't do retain+release tracking for IC_RetainRV, because it's
2481 // better to let it remain as the first instruction after a call.
2482 if (Class != IC_RetainRV) {
2483 // If we see two retains in a row on the same pointer. If so, make
2484 // a note, and we'll cicle back to revisit it after we've
2485 // hopefully eliminated the second retain, which may allow us to
2486 // eliminate the first retain too.
2487 // Theoretically we could implement removal of nested retain+release
2488 // pairs by making PtrState hold a stack of states, but this is
2489 // simple and avoids adding overhead for the non-nested case.
2490 if (S.GetSeq() == S_Retain)
2491 NestingDetected = true;
2492
2493 S.SetSeq(S_Retain);
2494 S.RRI.clear();
2495 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
Dan Gohmane6d5e882011-08-19 00:26:36 +00002496 // Don't check S.IsKnownIncremented() here because it's not
2497 // sufficient.
2498 S.RRI.KnownSafe = S.IsKnownNested();
John McCall9fbd3182011-06-15 23:37:01 +00002499 S.RRI.Calls.insert(Inst);
2500 }
2501
Dan Gohmana7f7db22011-08-12 00:26:31 +00002502 S.SetAtLeastOneRefCount();
John McCall9fbd3182011-06-15 23:37:01 +00002503 S.IncrementRefCount();
Dan Gohmane6d5e882011-08-19 00:26:36 +00002504 S.IncrementNestCount();
2505 continue;
John McCall9fbd3182011-06-15 23:37:01 +00002506 }
2507 case IC_Release: {
2508 Arg = GetObjCArg(Inst);
2509
2510 PtrState &S = MyStates.getPtrTopDownState(Arg);
2511 S.DecrementRefCount();
Dan Gohmane6d5e882011-08-19 00:26:36 +00002512 S.DecrementNestCount();
John McCall9fbd3182011-06-15 23:37:01 +00002513
2514 switch (S.GetSeq()) {
2515 case S_Retain:
2516 case S_CanRelease:
2517 S.RRI.ReverseInsertPts.clear();
2518 // FALL THROUGH
2519 case S_Use:
2520 S.RRI.ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2521 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2522 Releases[Inst] = S.RRI;
2523 S.ClearSequenceProgress();
2524 break;
2525 case S_None:
2526 break;
2527 case S_Stop:
2528 case S_Release:
2529 case S_MovableRelease:
2530 llvm_unreachable("top-down pointer in release state!");
2531 }
2532 break;
2533 }
2534 case IC_AutoreleasepoolPop:
2535 // Conservatively, clear MyStates for all known pointers.
2536 MyStates.clearTopDownPointers();
2537 continue;
2538 case IC_AutoreleasepoolPush:
2539 case IC_None:
2540 // These are irrelevant.
2541 continue;
2542 default:
2543 break;
2544 }
2545
2546 // Consider any other possible effects of this instruction on each
2547 // pointer being tracked.
2548 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
2549 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
2550 const Value *Ptr = MI->first;
2551 if (Ptr == Arg)
2552 continue; // Handled above.
2553 PtrState &S = MI->second;
2554 Sequence Seq = S.GetSeq();
2555
Dan Gohmane6d5e882011-08-19 00:26:36 +00002556 // Check for possible releases.
2557 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2558 S.DecrementRefCount();
John McCall9fbd3182011-06-15 23:37:01 +00002559 switch (Seq) {
2560 case S_Retain:
2561 S.SetSeq(S_CanRelease);
2562 S.RRI.ReverseInsertPts.clear();
2563 S.RRI.ReverseInsertPts.insert(Inst);
2564
2565 // One call can't cause a transition from S_Retain to S_CanRelease
2566 // and S_CanRelease to S_Use. If we've made the first transition,
2567 // we're done.
2568 continue;
2569 case S_Use:
2570 case S_CanRelease:
2571 case S_None:
2572 break;
2573 case S_Stop:
2574 case S_Release:
2575 case S_MovableRelease:
2576 llvm_unreachable("top-down pointer in release state!");
2577 }
Dan Gohmane6d5e882011-08-19 00:26:36 +00002578 }
John McCall9fbd3182011-06-15 23:37:01 +00002579
2580 // Check for possible direct uses.
2581 switch (Seq) {
2582 case S_CanRelease:
2583 if (CanUse(Inst, Ptr, PA, Class))
2584 S.SetSeq(S_Use);
2585 break;
2586 case S_Use:
2587 case S_Retain:
2588 case S_None:
2589 break;
2590 case S_Stop:
2591 case S_Release:
2592 case S_MovableRelease:
2593 llvm_unreachable("top-down pointer in release state!");
2594 }
2595 }
2596 }
2597
2598 CheckForCFGHazards(BB, BBStates, MyStates);
2599 return NestingDetected;
2600}
2601
2602// Visit - Visit the function both top-down and bottom-up.
2603bool
2604ObjCARCOpt::Visit(Function &F,
2605 DenseMap<const BasicBlock *, BBState> &BBStates,
2606 MapVector<Value *, RRInfo> &Retains,
2607 DenseMap<Value *, RRInfo> &Releases) {
Dan Gohmand8e48c42011-08-12 00:24:29 +00002608 // Use reverse-postorder on the reverse CFG for bottom-up, because we
John McCall9fbd3182011-06-15 23:37:01 +00002609 // magically know that loops will be well behaved, i.e. they won't repeatedly
Dan Gohmand8e48c42011-08-12 00:24:29 +00002610 // call retain on a single pointer without doing a release. We can't use
2611 // ReversePostOrderTraversal here because we want to walk up from each
2612 // function exit point.
2613 SmallPtrSet<BasicBlock *, 16> Visited;
2614 SmallVector<std::pair<BasicBlock *, pred_iterator>, 16> Stack;
2615 SmallVector<BasicBlock *, 16> Order;
2616 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
2617 BasicBlock *BB = I;
2618 if (BB->getTerminator()->getNumSuccessors() == 0)
2619 Stack.push_back(std::make_pair(BB, pred_begin(BB)));
2620 }
2621 while (!Stack.empty()) {
2622 pred_iterator End = pred_end(Stack.back().first);
2623 while (Stack.back().second != End) {
2624 BasicBlock *BB = *Stack.back().second++;
2625 if (Visited.insert(BB))
2626 Stack.push_back(std::make_pair(BB, pred_begin(BB)));
2627 }
2628 Order.push_back(Stack.pop_back_val().first);
2629 }
John McCall9fbd3182011-06-15 23:37:01 +00002630 bool BottomUpNestingDetected = false;
Dan Gohmanb48ef3a2011-08-18 21:27:42 +00002631 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2632 Order.rbegin(), E = Order.rend(); I != E; ++I) {
2633 BasicBlock *BB = *I;
John McCall9fbd3182011-06-15 23:37:01 +00002634 BottomUpNestingDetected |= VisitBottomUp(BB, BBStates, Retains);
2635 }
2636
Dan Gohmand8e48c42011-08-12 00:24:29 +00002637 // Use regular reverse-postorder for top-down.
John McCall9fbd3182011-06-15 23:37:01 +00002638 bool TopDownNestingDetected = false;
Dan Gohmand8e48c42011-08-12 00:24:29 +00002639 typedef ReversePostOrderTraversal<Function *> RPOTType;
2640 RPOTType RPOT(&F);
2641 for (RPOTType::rpo_iterator I = RPOT.begin(), E = RPOT.end(); I != E; ++I) {
2642 BasicBlock *BB = *I;
2643 TopDownNestingDetected |= VisitTopDown(BB, BBStates, Releases);
2644 }
John McCall9fbd3182011-06-15 23:37:01 +00002645
2646 return TopDownNestingDetected && BottomUpNestingDetected;
2647}
2648
2649/// MoveCalls - Move the calls in RetainsToMove and ReleasesToMove.
2650void ObjCARCOpt::MoveCalls(Value *Arg,
2651 RRInfo &RetainsToMove,
2652 RRInfo &ReleasesToMove,
2653 MapVector<Value *, RRInfo> &Retains,
2654 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman44280692011-07-22 22:29:21 +00002655 SmallVectorImpl<Instruction *> &DeadInsts,
2656 Module *M) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002657 Type *ArgTy = Arg->getType();
Dan Gohman44280692011-07-22 22:29:21 +00002658 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
John McCall9fbd3182011-06-15 23:37:01 +00002659
2660 // Insert the new retain and release calls.
2661 for (SmallPtrSet<Instruction *, 2>::const_iterator
2662 PI = ReleasesToMove.ReverseInsertPts.begin(),
2663 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2664 Instruction *InsertPt = *PI;
2665 Value *MyArg = ArgTy == ParamTy ? Arg :
2666 new BitCastInst(Arg, ParamTy, "", InsertPt);
2667 CallInst *Call =
2668 CallInst::Create(RetainsToMove.IsRetainBlock ?
Dan Gohman44280692011-07-22 22:29:21 +00002669 getRetainBlockCallee(M) : getRetainCallee(M),
John McCall9fbd3182011-06-15 23:37:01 +00002670 MyArg, "", InsertPt);
2671 Call->setDoesNotThrow();
2672 if (!RetainsToMove.IsRetainBlock)
2673 Call->setTailCall();
2674 }
2675 for (SmallPtrSet<Instruction *, 2>::const_iterator
2676 PI = RetainsToMove.ReverseInsertPts.begin(),
2677 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
Dan Gohman0860d0b2011-06-16 20:57:14 +00002678 Instruction *LastUse = *PI;
2679 Instruction *InsertPts[] = { 0, 0, 0 };
2680 if (InvokeInst *II = dyn_cast<InvokeInst>(LastUse)) {
2681 // We can't insert code immediately after an invoke instruction, so
2682 // insert code at the beginning of both successor blocks instead.
2683 // The invoke's return value isn't available in the unwind block,
2684 // but our releases will never depend on it, because they must be
2685 // paired with retains from before the invoke.
2686 InsertPts[0] = II->getNormalDest()->getFirstNonPHI();
2687 InsertPts[1] = II->getUnwindDest()->getFirstNonPHI();
2688 } else {
2689 // Insert code immediately after the last use.
2690 InsertPts[0] = llvm::next(BasicBlock::iterator(LastUse));
2691 }
2692
2693 for (Instruction **I = InsertPts; *I; ++I) {
2694 Instruction *InsertPt = *I;
2695 Value *MyArg = ArgTy == ParamTy ? Arg :
2696 new BitCastInst(Arg, ParamTy, "", InsertPt);
Dan Gohman44280692011-07-22 22:29:21 +00002697 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
2698 "", InsertPt);
Dan Gohman0860d0b2011-06-16 20:57:14 +00002699 // Attach a clang.imprecise_release metadata tag, if appropriate.
2700 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
2701 Call->setMetadata(ImpreciseReleaseMDKind, M);
2702 Call->setDoesNotThrow();
2703 if (ReleasesToMove.IsTailCallRelease)
2704 Call->setTailCall();
2705 }
John McCall9fbd3182011-06-15 23:37:01 +00002706 }
2707
2708 // Delete the original retain and release calls.
2709 for (SmallPtrSet<Instruction *, 2>::const_iterator
2710 AI = RetainsToMove.Calls.begin(),
2711 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
2712 Instruction *OrigRetain = *AI;
2713 Retains.blot(OrigRetain);
2714 DeadInsts.push_back(OrigRetain);
2715 }
2716 for (SmallPtrSet<Instruction *, 2>::const_iterator
2717 AI = ReleasesToMove.Calls.begin(),
2718 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
2719 Instruction *OrigRelease = *AI;
2720 Releases.erase(OrigRelease);
2721 DeadInsts.push_back(OrigRelease);
2722 }
2723}
2724
2725bool
2726ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
2727 &BBStates,
2728 MapVector<Value *, RRInfo> &Retains,
Dan Gohman44280692011-07-22 22:29:21 +00002729 DenseMap<Value *, RRInfo> &Releases,
2730 Module *M) {
John McCall9fbd3182011-06-15 23:37:01 +00002731 bool AnyPairsCompletelyEliminated = false;
2732 RRInfo RetainsToMove;
2733 RRInfo ReleasesToMove;
2734 SmallVector<Instruction *, 4> NewRetains;
2735 SmallVector<Instruction *, 4> NewReleases;
2736 SmallVector<Instruction *, 8> DeadInsts;
2737
2738 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
2739 E = Retains.end(); I != E; ) {
2740 Value *V = (I++)->first;
2741 if (!V) continue; // blotted
2742
2743 Instruction *Retain = cast<Instruction>(V);
2744 Value *Arg = GetObjCArg(Retain);
2745
2746 // If the object being released is in static or stack storage, we know it's
2747 // not being managed by ObjC reference counting, so we can delete pairs
2748 // regardless of what possible decrements or uses lie between them.
2749 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
2750
Dan Gohman1b31ea82011-08-22 17:29:11 +00002751 // A constant pointer can't be pointing to an object on the heap. It may
2752 // be reference-counted, but it won't be deleted.
2753 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
2754 if (const GlobalVariable *GV =
2755 dyn_cast<GlobalVariable>(
2756 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
2757 if (GV->isConstant())
2758 KnownSafe = true;
2759
John McCall9fbd3182011-06-15 23:37:01 +00002760 // If a pair happens in a region where it is known that the reference count
2761 // is already incremented, we can similarly ignore possible decrements.
Dan Gohmane6d5e882011-08-19 00:26:36 +00002762 bool KnownSafeTD = true, KnownSafeBU = true;
John McCall9fbd3182011-06-15 23:37:01 +00002763
2764 // Connect the dots between the top-down-collected RetainsToMove and
2765 // bottom-up-collected ReleasesToMove to form sets of related calls.
2766 // This is an iterative process so that we connect multiple releases
2767 // to multiple retains if needed.
2768 unsigned OldDelta = 0;
2769 unsigned NewDelta = 0;
2770 unsigned OldCount = 0;
2771 unsigned NewCount = 0;
2772 bool FirstRelease = true;
2773 bool FirstRetain = true;
2774 NewRetains.push_back(Retain);
2775 for (;;) {
2776 for (SmallVectorImpl<Instruction *>::const_iterator
2777 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
2778 Instruction *NewRetain = *NI;
2779 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
2780 assert(It != Retains.end());
2781 const RRInfo &NewRetainRRI = It->second;
Dan Gohmane6d5e882011-08-19 00:26:36 +00002782 KnownSafeTD &= NewRetainRRI.KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00002783 for (SmallPtrSet<Instruction *, 2>::const_iterator
2784 LI = NewRetainRRI.Calls.begin(),
2785 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
2786 Instruction *NewRetainRelease = *LI;
2787 DenseMap<Value *, RRInfo>::const_iterator Jt =
2788 Releases.find(NewRetainRelease);
2789 if (Jt == Releases.end())
2790 goto next_retain;
2791 const RRInfo &NewRetainReleaseRRI = Jt->second;
2792 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
2793 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
2794 OldDelta -=
2795 BBStates[NewRetainRelease->getParent()].GetAllPathCount();
2796
2797 // Merge the ReleaseMetadata and IsTailCallRelease values.
2798 if (FirstRelease) {
2799 ReleasesToMove.ReleaseMetadata =
2800 NewRetainReleaseRRI.ReleaseMetadata;
2801 ReleasesToMove.IsTailCallRelease =
2802 NewRetainReleaseRRI.IsTailCallRelease;
2803 FirstRelease = false;
2804 } else {
2805 if (ReleasesToMove.ReleaseMetadata !=
2806 NewRetainReleaseRRI.ReleaseMetadata)
2807 ReleasesToMove.ReleaseMetadata = 0;
2808 if (ReleasesToMove.IsTailCallRelease !=
2809 NewRetainReleaseRRI.IsTailCallRelease)
2810 ReleasesToMove.IsTailCallRelease = false;
2811 }
2812
2813 // Collect the optimal insertion points.
2814 if (!KnownSafe)
2815 for (SmallPtrSet<Instruction *, 2>::const_iterator
2816 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
2817 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
2818 RI != RE; ++RI) {
2819 Instruction *RIP = *RI;
2820 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
2821 NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
2822 }
2823 NewReleases.push_back(NewRetainRelease);
2824 }
2825 }
2826 }
2827 NewRetains.clear();
2828 if (NewReleases.empty()) break;
2829
2830 // Back the other way.
2831 for (SmallVectorImpl<Instruction *>::const_iterator
2832 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
2833 Instruction *NewRelease = *NI;
2834 DenseMap<Value *, RRInfo>::const_iterator It =
2835 Releases.find(NewRelease);
2836 assert(It != Releases.end());
2837 const RRInfo &NewReleaseRRI = It->second;
Dan Gohmane6d5e882011-08-19 00:26:36 +00002838 KnownSafeBU &= NewReleaseRRI.KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00002839 for (SmallPtrSet<Instruction *, 2>::const_iterator
2840 LI = NewReleaseRRI.Calls.begin(),
2841 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
2842 Instruction *NewReleaseRetain = *LI;
2843 MapVector<Value *, RRInfo>::const_iterator Jt =
2844 Retains.find(NewReleaseRetain);
2845 if (Jt == Retains.end())
2846 goto next_retain;
2847 const RRInfo &NewReleaseRetainRRI = Jt->second;
2848 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
2849 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
2850 unsigned PathCount =
2851 BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
2852 OldDelta += PathCount;
2853 OldCount += PathCount;
2854
2855 // Merge the IsRetainBlock values.
2856 if (FirstRetain) {
2857 RetainsToMove.IsRetainBlock = NewReleaseRetainRRI.IsRetainBlock;
2858 FirstRetain = false;
2859 } else if (ReleasesToMove.IsRetainBlock !=
2860 NewReleaseRetainRRI.IsRetainBlock)
2861 // It's not possible to merge the sequences if one uses
2862 // objc_retain and the other uses objc_retainBlock.
2863 goto next_retain;
2864
2865 // Collect the optimal insertion points.
2866 if (!KnownSafe)
2867 for (SmallPtrSet<Instruction *, 2>::const_iterator
2868 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
2869 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
2870 RI != RE; ++RI) {
2871 Instruction *RIP = *RI;
2872 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
2873 PathCount = BBStates[RIP->getParent()].GetAllPathCount();
2874 NewDelta += PathCount;
2875 NewCount += PathCount;
2876 }
2877 }
2878 NewRetains.push_back(NewReleaseRetain);
2879 }
2880 }
2881 }
2882 NewReleases.clear();
2883 if (NewRetains.empty()) break;
2884 }
2885
Dan Gohmane6d5e882011-08-19 00:26:36 +00002886 // If the pointer is known incremented or nested, we can safely delete the
2887 // pair regardless of what's between them.
2888 if (KnownSafeTD || KnownSafeBU) {
John McCall9fbd3182011-06-15 23:37:01 +00002889 RetainsToMove.ReverseInsertPts.clear();
2890 ReleasesToMove.ReverseInsertPts.clear();
2891 NewCount = 0;
Dan Gohmana7f7db22011-08-12 00:26:31 +00002892 } else {
2893 // Determine whether the new insertion points we computed preserve the
2894 // balance of retain and release calls through the program.
2895 // TODO: If the fully aggressive solution isn't valid, try to find a
2896 // less aggressive solution which is.
2897 if (NewDelta != 0)
2898 goto next_retain;
John McCall9fbd3182011-06-15 23:37:01 +00002899 }
2900
2901 // Determine whether the original call points are balanced in the retain and
2902 // release calls through the program. If not, conservatively don't touch
2903 // them.
2904 // TODO: It's theoretically possible to do code motion in this case, as
2905 // long as the existing imbalances are maintained.
2906 if (OldDelta != 0)
2907 goto next_retain;
2908
John McCall9fbd3182011-06-15 23:37:01 +00002909 // Ok, everything checks out and we're all set. Let's move some code!
2910 Changed = true;
2911 AnyPairsCompletelyEliminated = NewCount == 0;
2912 NumRRs += OldCount - NewCount;
Dan Gohman44280692011-07-22 22:29:21 +00002913 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
2914 Retains, Releases, DeadInsts, M);
John McCall9fbd3182011-06-15 23:37:01 +00002915
2916 next_retain:
2917 NewReleases.clear();
2918 NewRetains.clear();
2919 RetainsToMove.clear();
2920 ReleasesToMove.clear();
2921 }
2922
2923 // Now that we're done moving everything, we can delete the newly dead
2924 // instructions, as we no longer need them as insert points.
2925 while (!DeadInsts.empty())
2926 EraseInstruction(DeadInsts.pop_back_val());
2927
2928 return AnyPairsCompletelyEliminated;
2929}
2930
2931/// OptimizeWeakCalls - Weak pointer optimizations.
2932void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
2933 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
2934 // itself because it uses AliasAnalysis and we need to do provenance
2935 // queries instead.
2936 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2937 Instruction *Inst = &*I++;
2938 InstructionClass Class = GetBasicInstructionClass(Inst);
2939 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
2940 continue;
2941
2942 // Delete objc_loadWeak calls with no users.
2943 if (Class == IC_LoadWeak && Inst->use_empty()) {
2944 Inst->eraseFromParent();
2945 continue;
2946 }
2947
2948 // TODO: For now, just look for an earlier available version of this value
2949 // within the same block. Theoretically, we could do memdep-style non-local
2950 // analysis too, but that would want caching. A better approach would be to
2951 // use the technique that EarlyCSE uses.
2952 inst_iterator Current = llvm::prior(I);
2953 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
2954 for (BasicBlock::iterator B = CurrentBB->begin(),
2955 J = Current.getInstructionIterator();
2956 J != B; --J) {
2957 Instruction *EarlierInst = &*llvm::prior(J);
2958 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
2959 switch (EarlierClass) {
2960 case IC_LoadWeak:
2961 case IC_LoadWeakRetained: {
2962 // If this is loading from the same pointer, replace this load's value
2963 // with that one.
2964 CallInst *Call = cast<CallInst>(Inst);
2965 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2966 Value *Arg = Call->getArgOperand(0);
2967 Value *EarlierArg = EarlierCall->getArgOperand(0);
2968 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2969 case AliasAnalysis::MustAlias:
2970 Changed = true;
2971 // If the load has a builtin retain, insert a plain retain for it.
2972 if (Class == IC_LoadWeakRetained) {
2973 CallInst *CI =
2974 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
2975 "", Call);
2976 CI->setTailCall();
2977 }
2978 // Zap the fully redundant load.
2979 Call->replaceAllUsesWith(EarlierCall);
2980 Call->eraseFromParent();
2981 goto clobbered;
2982 case AliasAnalysis::MayAlias:
2983 case AliasAnalysis::PartialAlias:
2984 goto clobbered;
2985 case AliasAnalysis::NoAlias:
2986 break;
2987 }
2988 break;
2989 }
2990 case IC_StoreWeak:
2991 case IC_InitWeak: {
2992 // If this is storing to the same pointer and has the same size etc.
2993 // replace this load's value with the stored value.
2994 CallInst *Call = cast<CallInst>(Inst);
2995 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2996 Value *Arg = Call->getArgOperand(0);
2997 Value *EarlierArg = EarlierCall->getArgOperand(0);
2998 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2999 case AliasAnalysis::MustAlias:
3000 Changed = true;
3001 // If the load has a builtin retain, insert a plain retain for it.
3002 if (Class == IC_LoadWeakRetained) {
3003 CallInst *CI =
3004 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3005 "", Call);
3006 CI->setTailCall();
3007 }
3008 // Zap the fully redundant load.
3009 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
3010 Call->eraseFromParent();
3011 goto clobbered;
3012 case AliasAnalysis::MayAlias:
3013 case AliasAnalysis::PartialAlias:
3014 goto clobbered;
3015 case AliasAnalysis::NoAlias:
3016 break;
3017 }
3018 break;
3019 }
3020 case IC_MoveWeak:
3021 case IC_CopyWeak:
3022 // TOOD: Grab the copied value.
3023 goto clobbered;
3024 case IC_AutoreleasepoolPush:
3025 case IC_None:
3026 case IC_User:
3027 // Weak pointers are only modified through the weak entry points
3028 // (and arbitrary calls, which could call the weak entry points).
3029 break;
3030 default:
3031 // Anything else could modify the weak pointer.
3032 goto clobbered;
3033 }
3034 }
3035 clobbered:;
3036 }
3037
3038 // Then, for each destroyWeak with an alloca operand, check to see if
3039 // the alloca and all its users can be zapped.
3040 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3041 Instruction *Inst = &*I++;
3042 InstructionClass Class = GetBasicInstructionClass(Inst);
3043 if (Class != IC_DestroyWeak)
3044 continue;
3045
3046 CallInst *Call = cast<CallInst>(Inst);
3047 Value *Arg = Call->getArgOperand(0);
3048 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
3049 for (Value::use_iterator UI = Alloca->use_begin(),
3050 UE = Alloca->use_end(); UI != UE; ++UI) {
3051 Instruction *UserInst = cast<Instruction>(*UI);
3052 switch (GetBasicInstructionClass(UserInst)) {
3053 case IC_InitWeak:
3054 case IC_StoreWeak:
3055 case IC_DestroyWeak:
3056 continue;
3057 default:
3058 goto done;
3059 }
3060 }
3061 Changed = true;
3062 for (Value::use_iterator UI = Alloca->use_begin(),
3063 UE = Alloca->use_end(); UI != UE; ) {
3064 CallInst *UserInst = cast<CallInst>(*UI++);
3065 if (!UserInst->use_empty())
3066 UserInst->replaceAllUsesWith(UserInst->getOperand(1));
3067 UserInst->eraseFromParent();
3068 }
3069 Alloca->eraseFromParent();
3070 done:;
3071 }
3072 }
3073}
3074
3075/// OptimizeSequences - Identify program paths which execute sequences of
3076/// retains and releases which can be eliminated.
3077bool ObjCARCOpt::OptimizeSequences(Function &F) {
3078 /// Releases, Retains - These are used to store the results of the main flow
3079 /// analysis. These use Value* as the key instead of Instruction* so that the
3080 /// map stays valid when we get around to rewriting code and calls get
3081 /// replaced by arguments.
3082 DenseMap<Value *, RRInfo> Releases;
3083 MapVector<Value *, RRInfo> Retains;
3084
3085 /// BBStates, This is used during the traversal of the function to track the
3086 /// states for each identified object at each block.
3087 DenseMap<const BasicBlock *, BBState> BBStates;
3088
3089 // Analyze the CFG of the function, and all instructions.
3090 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
3091
3092 // Transform.
Dan Gohman44280692011-07-22 22:29:21 +00003093 return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) &&
3094 NestingDetected;
John McCall9fbd3182011-06-15 23:37:01 +00003095}
3096
3097/// OptimizeReturns - Look for this pattern:
3098///
3099/// %call = call i8* @something(...)
3100/// %2 = call i8* @objc_retain(i8* %call)
3101/// %3 = call i8* @objc_autorelease(i8* %2)
3102/// ret i8* %3
3103///
3104/// And delete the retain and autorelease.
3105///
3106/// Otherwise if it's just this:
3107///
3108/// %3 = call i8* @objc_autorelease(i8* %2)
3109/// ret i8* %3
3110///
3111/// convert the autorelease to autoreleaseRV.
3112void ObjCARCOpt::OptimizeReturns(Function &F) {
3113 if (!F.getReturnType()->isPointerTy())
3114 return;
3115
3116 SmallPtrSet<Instruction *, 4> DependingInstructions;
3117 SmallPtrSet<const BasicBlock *, 4> Visited;
3118 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3119 BasicBlock *BB = FI;
3120 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
3121 if (!Ret) continue;
3122
3123 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
3124 FindDependencies(NeedsPositiveRetainCount, Arg,
3125 BB, Ret, DependingInstructions, Visited, PA);
3126 if (DependingInstructions.size() != 1)
3127 goto next_block;
3128
3129 {
3130 CallInst *Autorelease =
3131 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3132 if (!Autorelease)
3133 goto next_block;
3134 InstructionClass AutoreleaseClass =
3135 GetBasicInstructionClass(Autorelease);
3136 if (!IsAutorelease(AutoreleaseClass))
3137 goto next_block;
3138 if (GetObjCArg(Autorelease) != Arg)
3139 goto next_block;
3140
3141 DependingInstructions.clear();
3142 Visited.clear();
3143
3144 // Check that there is nothing that can affect the reference
3145 // count between the autorelease and the retain.
3146 FindDependencies(CanChangeRetainCount, Arg,
3147 BB, Autorelease, DependingInstructions, Visited, PA);
3148 if (DependingInstructions.size() != 1)
3149 goto next_block;
3150
3151 {
3152 CallInst *Retain =
3153 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3154
3155 // Check that we found a retain with the same argument.
3156 if (!Retain ||
3157 !IsRetain(GetBasicInstructionClass(Retain)) ||
3158 GetObjCArg(Retain) != Arg)
3159 goto next_block;
3160
3161 DependingInstructions.clear();
3162 Visited.clear();
3163
3164 // Convert the autorelease to an autoreleaseRV, since it's
3165 // returning the value.
3166 if (AutoreleaseClass == IC_Autorelease) {
3167 Autorelease->setCalledFunction(getAutoreleaseRVCallee(F.getParent()));
3168 AutoreleaseClass = IC_AutoreleaseRV;
3169 }
3170
3171 // Check that there is nothing that can affect the reference
3172 // count between the retain and the call.
3173 FindDependencies(CanChangeRetainCount, Arg, BB, Retain,
3174 DependingInstructions, Visited, PA);
3175 if (DependingInstructions.size() != 1)
3176 goto next_block;
3177
3178 {
3179 CallInst *Call =
3180 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3181
3182 // Check that the pointer is the return value of the call.
3183 if (!Call || Arg != Call)
3184 goto next_block;
3185
3186 // Check that the call is a regular call.
3187 InstructionClass Class = GetBasicInstructionClass(Call);
3188 if (Class != IC_CallOrUser && Class != IC_Call)
3189 goto next_block;
3190
3191 // If so, we can zap the retain and autorelease.
3192 Changed = true;
3193 ++NumRets;
3194 EraseInstruction(Retain);
3195 EraseInstruction(Autorelease);
3196 }
3197 }
3198 }
3199
3200 next_block:
3201 DependingInstructions.clear();
3202 Visited.clear();
3203 }
3204}
3205
3206bool ObjCARCOpt::doInitialization(Module &M) {
3207 if (!EnableARCOpts)
3208 return false;
3209
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003210 Run = ModuleHasARC(M);
3211 if (!Run)
3212 return false;
3213
John McCall9fbd3182011-06-15 23:37:01 +00003214 // Identify the imprecise release metadata kind.
3215 ImpreciseReleaseMDKind =
3216 M.getContext().getMDKindID("clang.imprecise_release");
3217
John McCall9fbd3182011-06-15 23:37:01 +00003218 // Intuitively, objc_retain and others are nocapture, however in practice
3219 // they are not, because they return their argument value. And objc_release
3220 // calls finalizers.
3221
3222 // These are initialized lazily.
3223 RetainRVCallee = 0;
3224 AutoreleaseRVCallee = 0;
3225 ReleaseCallee = 0;
3226 RetainCallee = 0;
Dan Gohman44280692011-07-22 22:29:21 +00003227 RetainBlockCallee = 0;
John McCall9fbd3182011-06-15 23:37:01 +00003228 AutoreleaseCallee = 0;
3229
3230 return false;
3231}
3232
3233bool ObjCARCOpt::runOnFunction(Function &F) {
3234 if (!EnableARCOpts)
3235 return false;
3236
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003237 // If nothing in the Module uses ARC, don't do anything.
3238 if (!Run)
3239 return false;
3240
John McCall9fbd3182011-06-15 23:37:01 +00003241 Changed = false;
3242
3243 PA.setAA(&getAnalysis<AliasAnalysis>());
3244
3245 // This pass performs several distinct transformations. As a compile-time aid
3246 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3247 // library functions aren't declared.
3248
3249 // Preliminary optimizations. This also computs UsedInThisFunction.
3250 OptimizeIndividualCalls(F);
3251
3252 // Optimizations for weak pointers.
3253 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3254 (1 << IC_LoadWeakRetained) |
3255 (1 << IC_StoreWeak) |
3256 (1 << IC_InitWeak) |
3257 (1 << IC_CopyWeak) |
3258 (1 << IC_MoveWeak) |
3259 (1 << IC_DestroyWeak)))
3260 OptimizeWeakCalls(F);
3261
3262 // Optimizations for retain+release pairs.
3263 if (UsedInThisFunction & ((1 << IC_Retain) |
3264 (1 << IC_RetainRV) |
3265 (1 << IC_RetainBlock)))
3266 if (UsedInThisFunction & (1 << IC_Release))
3267 // Run OptimizeSequences until it either stops making changes or
3268 // no retain+release pair nesting is detected.
3269 while (OptimizeSequences(F)) {}
3270
3271 // Optimizations if objc_autorelease is used.
3272 if (UsedInThisFunction &
3273 ((1 << IC_Autorelease) | (1 << IC_AutoreleaseRV)))
3274 OptimizeReturns(F);
3275
3276 return Changed;
3277}
3278
3279void ObjCARCOpt::releaseMemory() {
3280 PA.clear();
3281}
3282
3283//===----------------------------------------------------------------------===//
3284// ARC contraction.
3285//===----------------------------------------------------------------------===//
3286
3287// TODO: ObjCARCContract could insert PHI nodes when uses aren't
3288// dominated by single calls.
3289
3290#include "llvm/Operator.h"
3291#include "llvm/InlineAsm.h"
3292#include "llvm/Analysis/Dominators.h"
3293
3294STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed");
3295
3296namespace {
3297 /// ObjCARCContract - Late ARC optimizations. These change the IR in a way
3298 /// that makes it difficult to be analyzed by ObjCARCOpt, so it's run late.
3299 class ObjCARCContract : public FunctionPass {
3300 bool Changed;
3301 AliasAnalysis *AA;
3302 DominatorTree *DT;
3303 ProvenanceAnalysis PA;
3304
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003305 /// Run - A flag indicating whether this optimization pass should run.
3306 bool Run;
3307
John McCall9fbd3182011-06-15 23:37:01 +00003308 /// StoreStrongCallee, etc. - Declarations for ObjC runtime
3309 /// functions, for use in creating calls to them. These are initialized
3310 /// lazily to avoid cluttering up the Module with unused declarations.
3311 Constant *StoreStrongCallee,
3312 *RetainAutoreleaseCallee, *RetainAutoreleaseRVCallee;
3313
3314 /// RetainRVMarker - The inline asm string to insert between calls and
3315 /// RetainRV calls to make the optimization work on targets which need it.
3316 const MDString *RetainRVMarker;
3317
3318 Constant *getStoreStrongCallee(Module *M);
3319 Constant *getRetainAutoreleaseCallee(Module *M);
3320 Constant *getRetainAutoreleaseRVCallee(Module *M);
3321
3322 bool ContractAutorelease(Function &F, Instruction *Autorelease,
3323 InstructionClass Class,
3324 SmallPtrSet<Instruction *, 4>
3325 &DependingInstructions,
3326 SmallPtrSet<const BasicBlock *, 4>
3327 &Visited);
3328
3329 void ContractRelease(Instruction *Release,
3330 inst_iterator &Iter);
3331
3332 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
3333 virtual bool doInitialization(Module &M);
3334 virtual bool runOnFunction(Function &F);
3335
3336 public:
3337 static char ID;
3338 ObjCARCContract() : FunctionPass(ID) {
3339 initializeObjCARCContractPass(*PassRegistry::getPassRegistry());
3340 }
3341 };
3342}
3343
3344char ObjCARCContract::ID = 0;
3345INITIALIZE_PASS_BEGIN(ObjCARCContract,
3346 "objc-arc-contract", "ObjC ARC contraction", false, false)
3347INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3348INITIALIZE_PASS_DEPENDENCY(DominatorTree)
3349INITIALIZE_PASS_END(ObjCARCContract,
3350 "objc-arc-contract", "ObjC ARC contraction", false, false)
3351
3352Pass *llvm::createObjCARCContractPass() {
3353 return new ObjCARCContract();
3354}
3355
3356void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const {
3357 AU.addRequired<AliasAnalysis>();
3358 AU.addRequired<DominatorTree>();
3359 AU.setPreservesCFG();
3360}
3361
3362Constant *ObjCARCContract::getStoreStrongCallee(Module *M) {
3363 if (!StoreStrongCallee) {
3364 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00003365 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3366 Type *I8XX = PointerType::getUnqual(I8X);
3367 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00003368 Params.push_back(I8XX);
3369 Params.push_back(I8X);
3370
3371 AttrListPtr Attributes;
3372 Attributes.addAttr(~0u, Attribute::NoUnwind);
3373 Attributes.addAttr(1, Attribute::NoCapture);
3374
3375 StoreStrongCallee =
3376 M->getOrInsertFunction(
3377 "objc_storeStrong",
3378 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
3379 Attributes);
3380 }
3381 return StoreStrongCallee;
3382}
3383
3384Constant *ObjCARCContract::getRetainAutoreleaseCallee(Module *M) {
3385 if (!RetainAutoreleaseCallee) {
3386 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00003387 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3388 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00003389 Params.push_back(I8X);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003390 FunctionType *FTy =
John McCall9fbd3182011-06-15 23:37:01 +00003391 FunctionType::get(I8X, Params, /*isVarArg=*/false);
3392 AttrListPtr Attributes;
3393 Attributes.addAttr(~0u, Attribute::NoUnwind);
3394 RetainAutoreleaseCallee =
3395 M->getOrInsertFunction("objc_retainAutorelease", FTy, Attributes);
3396 }
3397 return RetainAutoreleaseCallee;
3398}
3399
3400Constant *ObjCARCContract::getRetainAutoreleaseRVCallee(Module *M) {
3401 if (!RetainAutoreleaseRVCallee) {
3402 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00003403 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3404 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00003405 Params.push_back(I8X);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003406 FunctionType *FTy =
John McCall9fbd3182011-06-15 23:37:01 +00003407 FunctionType::get(I8X, Params, /*isVarArg=*/false);
3408 AttrListPtr Attributes;
3409 Attributes.addAttr(~0u, Attribute::NoUnwind);
3410 RetainAutoreleaseRVCallee =
3411 M->getOrInsertFunction("objc_retainAutoreleaseReturnValue", FTy,
3412 Attributes);
3413 }
3414 return RetainAutoreleaseRVCallee;
3415}
3416
3417/// ContractAutorelease - Merge an autorelease with a retain into a fused
3418/// call.
3419bool
3420ObjCARCContract::ContractAutorelease(Function &F, Instruction *Autorelease,
3421 InstructionClass Class,
3422 SmallPtrSet<Instruction *, 4>
3423 &DependingInstructions,
3424 SmallPtrSet<const BasicBlock *, 4>
3425 &Visited) {
3426 const Value *Arg = GetObjCArg(Autorelease);
3427
3428 // Check that there are no instructions between the retain and the autorelease
3429 // (such as an autorelease_pop) which may change the count.
3430 CallInst *Retain = 0;
3431 if (Class == IC_AutoreleaseRV)
3432 FindDependencies(RetainAutoreleaseRVDep, Arg,
3433 Autorelease->getParent(), Autorelease,
3434 DependingInstructions, Visited, PA);
3435 else
3436 FindDependencies(RetainAutoreleaseDep, Arg,
3437 Autorelease->getParent(), Autorelease,
3438 DependingInstructions, Visited, PA);
3439
3440 Visited.clear();
3441 if (DependingInstructions.size() != 1) {
3442 DependingInstructions.clear();
3443 return false;
3444 }
3445
3446 Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3447 DependingInstructions.clear();
3448
3449 if (!Retain ||
3450 GetBasicInstructionClass(Retain) != IC_Retain ||
3451 GetObjCArg(Retain) != Arg)
3452 return false;
3453
3454 Changed = true;
3455 ++NumPeeps;
3456
3457 if (Class == IC_AutoreleaseRV)
3458 Retain->setCalledFunction(getRetainAutoreleaseRVCallee(F.getParent()));
3459 else
3460 Retain->setCalledFunction(getRetainAutoreleaseCallee(F.getParent()));
3461
3462 EraseInstruction(Autorelease);
3463 return true;
3464}
3465
3466/// ContractRelease - Attempt to merge an objc_release with a store, load, and
3467/// objc_retain to form an objc_storeStrong. This can be a little tricky because
3468/// the instructions don't always appear in order, and there may be unrelated
3469/// intervening instructions.
3470void ObjCARCContract::ContractRelease(Instruction *Release,
3471 inst_iterator &Iter) {
3472 LoadInst *Load = dyn_cast<LoadInst>(GetObjCArg(Release));
3473 if (!Load || Load->isVolatile()) return;
3474
3475 // For now, require everything to be in one basic block.
3476 BasicBlock *BB = Release->getParent();
3477 if (Load->getParent() != BB) return;
3478
3479 // Walk down to find the store.
3480 BasicBlock::iterator I = Load, End = BB->end();
3481 ++I;
3482 AliasAnalysis::Location Loc = AA->getLocation(Load);
3483 while (I != End &&
3484 (&*I == Release ||
3485 IsRetain(GetBasicInstructionClass(I)) ||
3486 !(AA->getModRefInfo(I, Loc) & AliasAnalysis::Mod)))
3487 ++I;
3488 StoreInst *Store = dyn_cast<StoreInst>(I);
3489 if (!Store || Store->isVolatile()) return;
3490 if (Store->getPointerOperand() != Loc.Ptr) return;
3491
3492 Value *New = StripPointerCastsAndObjCCalls(Store->getValueOperand());
3493
3494 // Walk up to find the retain.
3495 I = Store;
3496 BasicBlock::iterator Begin = BB->begin();
3497 while (I != Begin && GetBasicInstructionClass(I) != IC_Retain)
3498 --I;
3499 Instruction *Retain = I;
3500 if (GetBasicInstructionClass(Retain) != IC_Retain) return;
3501 if (GetObjCArg(Retain) != New) return;
3502
3503 Changed = true;
3504 ++NumStoreStrongs;
3505
3506 LLVMContext &C = Release->getContext();
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003507 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3508 Type *I8XX = PointerType::getUnqual(I8X);
John McCall9fbd3182011-06-15 23:37:01 +00003509
3510 Value *Args[] = { Load->getPointerOperand(), New };
3511 if (Args[0]->getType() != I8XX)
3512 Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
3513 if (Args[1]->getType() != I8X)
3514 Args[1] = new BitCastInst(Args[1], I8X, "", Store);
3515 CallInst *StoreStrong =
3516 CallInst::Create(getStoreStrongCallee(BB->getParent()->getParent()),
Jay Foada3efbb12011-07-15 08:37:34 +00003517 Args, "", Store);
John McCall9fbd3182011-06-15 23:37:01 +00003518 StoreStrong->setDoesNotThrow();
3519 StoreStrong->setDebugLoc(Store->getDebugLoc());
3520
3521 if (&*Iter == Store) ++Iter;
3522 Store->eraseFromParent();
3523 Release->eraseFromParent();
3524 EraseInstruction(Retain);
3525 if (Load->use_empty())
3526 Load->eraseFromParent();
3527}
3528
3529bool ObjCARCContract::doInitialization(Module &M) {
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003530 Run = ModuleHasARC(M);
3531 if (!Run)
3532 return false;
3533
John McCall9fbd3182011-06-15 23:37:01 +00003534 // These are initialized lazily.
3535 StoreStrongCallee = 0;
3536 RetainAutoreleaseCallee = 0;
3537 RetainAutoreleaseRVCallee = 0;
3538
3539 // Initialize RetainRVMarker.
3540 RetainRVMarker = 0;
3541 if (NamedMDNode *NMD =
3542 M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker"))
3543 if (NMD->getNumOperands() == 1) {
3544 const MDNode *N = NMD->getOperand(0);
3545 if (N->getNumOperands() == 1)
3546 if (const MDString *S = dyn_cast<MDString>(N->getOperand(0)))
3547 RetainRVMarker = S;
3548 }
3549
3550 return false;
3551}
3552
3553bool ObjCARCContract::runOnFunction(Function &F) {
3554 if (!EnableARCOpts)
3555 return false;
3556
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003557 // If nothing in the Module uses ARC, don't do anything.
3558 if (!Run)
3559 return false;
3560
John McCall9fbd3182011-06-15 23:37:01 +00003561 Changed = false;
3562 AA = &getAnalysis<AliasAnalysis>();
3563 DT = &getAnalysis<DominatorTree>();
3564
3565 PA.setAA(&getAnalysis<AliasAnalysis>());
3566
3567 // For ObjC library calls which return their argument, replace uses of the
3568 // argument with uses of the call return value, if it dominates the use. This
3569 // reduces register pressure.
3570 SmallPtrSet<Instruction *, 4> DependingInstructions;
3571 SmallPtrSet<const BasicBlock *, 4> Visited;
3572 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3573 Instruction *Inst = &*I++;
3574
3575 // Only these library routines return their argument. In particular,
3576 // objc_retainBlock does not necessarily return its argument.
3577 InstructionClass Class = GetBasicInstructionClass(Inst);
3578 switch (Class) {
3579 case IC_Retain:
3580 case IC_FusedRetainAutorelease:
3581 case IC_FusedRetainAutoreleaseRV:
3582 break;
3583 case IC_Autorelease:
3584 case IC_AutoreleaseRV:
3585 if (ContractAutorelease(F, Inst, Class, DependingInstructions, Visited))
3586 continue;
3587 break;
3588 case IC_RetainRV: {
3589 // If we're compiling for a target which needs a special inline-asm
3590 // marker to do the retainAutoreleasedReturnValue optimization,
3591 // insert it now.
3592 if (!RetainRVMarker)
3593 break;
3594 BasicBlock::iterator BBI = Inst;
3595 --BBI;
3596 while (isNoopInstruction(BBI)) --BBI;
3597 if (&*BBI == GetObjCArg(Inst)) {
3598 InlineAsm *IA =
3599 InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()),
3600 /*isVarArg=*/false),
3601 RetainRVMarker->getString(),
3602 /*Constraints=*/"", /*hasSideEffects=*/true);
3603 CallInst::Create(IA, "", Inst);
3604 }
3605 break;
3606 }
3607 case IC_InitWeak: {
3608 // objc_initWeak(p, null) => *p = null
3609 CallInst *CI = cast<CallInst>(Inst);
3610 if (isNullOrUndef(CI->getArgOperand(1))) {
3611 Value *Null =
3612 ConstantPointerNull::get(cast<PointerType>(CI->getType()));
3613 Changed = true;
3614 new StoreInst(Null, CI->getArgOperand(0), CI);
3615 CI->replaceAllUsesWith(Null);
3616 CI->eraseFromParent();
3617 }
3618 continue;
3619 }
3620 case IC_Release:
3621 ContractRelease(Inst, I);
3622 continue;
3623 default:
3624 continue;
3625 }
3626
3627 // Don't use GetObjCArg because we don't want to look through bitcasts
3628 // and such; to do the replacement, the argument must have type i8*.
3629 const Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
3630 for (;;) {
3631 // If we're compiling bugpointed code, don't get in trouble.
3632 if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
3633 break;
3634 // Look through the uses of the pointer.
3635 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
3636 UI != UE; ) {
3637 Use &U = UI.getUse();
3638 unsigned OperandNo = UI.getOperandNo();
3639 ++UI; // Increment UI now, because we may unlink its element.
3640 if (Instruction *UserInst = dyn_cast<Instruction>(U.getUser()))
3641 if (Inst != UserInst && DT->dominates(Inst, UserInst)) {
3642 Changed = true;
3643 Instruction *Replacement = Inst;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003644 Type *UseTy = U.get()->getType();
John McCall9fbd3182011-06-15 23:37:01 +00003645 if (PHINode *PHI = dyn_cast<PHINode>(UserInst)) {
3646 // For PHI nodes, insert the bitcast in the predecessor block.
3647 unsigned ValNo =
3648 PHINode::getIncomingValueNumForOperand(OperandNo);
3649 BasicBlock *BB =
3650 PHI->getIncomingBlock(ValNo);
3651 if (Replacement->getType() != UseTy)
3652 Replacement = new BitCastInst(Replacement, UseTy, "",
3653 &BB->back());
3654 for (unsigned i = 0, e = PHI->getNumIncomingValues();
3655 i != e; ++i)
3656 if (PHI->getIncomingBlock(i) == BB) {
3657 // Keep the UI iterator valid.
3658 if (&PHI->getOperandUse(
3659 PHINode::getOperandNumForIncomingValue(i)) ==
3660 &UI.getUse())
3661 ++UI;
3662 PHI->setIncomingValue(i, Replacement);
3663 }
3664 } else {
3665 if (Replacement->getType() != UseTy)
3666 Replacement = new BitCastInst(Replacement, UseTy, "", UserInst);
3667 U.set(Replacement);
3668 }
3669 }
3670 }
3671
3672 // If Arg is a no-op casted pointer, strip one level of casts and
3673 // iterate.
3674 if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
3675 Arg = BI->getOperand(0);
3676 else if (isa<GEPOperator>(Arg) &&
3677 cast<GEPOperator>(Arg)->hasAllZeroIndices())
3678 Arg = cast<GEPOperator>(Arg)->getPointerOperand();
3679 else if (isa<GlobalAlias>(Arg) &&
3680 !cast<GlobalAlias>(Arg)->mayBeOverridden())
3681 Arg = cast<GlobalAlias>(Arg)->getAliasee();
3682 else
3683 break;
3684 }
3685 }
3686
3687 return Changed;
3688}