1 //===- ObjCARC.cpp - ObjC ARC Optimization --------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
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
20 // This file also defines a simple ARC-aware AliasAnalysis.
22 // WARNING: This file knows about certain library functions. It recognizes them
23 // by name, and hardwires knowedge of their semantics.
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.
29 //===----------------------------------------------------------------------===//
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"
36 #include "llvm/Module.h"
37 #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"
46 // A handy option to enable/disable all optimizations in this file.
47 static cl::opt<bool> EnableARCOpts("enable-objc-arc-opts", cl::init(true));
49 //===----------------------------------------------------------------------===//
51 //===----------------------------------------------------------------------===//
54 /// MapVector - An associative container with fast insertion-order
55 /// (deterministic) iteration over its elements. Plus the special
57 template<class KeyT, class ValueT>
59 /// Map - Map keys to indices in Vector.
60 typedef DenseMap<KeyT, size_t> MapTy;
63 /// Vector - Keys and values.
64 typedef std::vector<std::pair<KeyT, ValueT> > VectorTy;
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(); }
77 assert(Vector.size() >= Map.size()); // May differ due to blotting.
78 for (typename MapTy::const_iterator I = Map.begin(), E = Map.end();
80 assert(I->second < Vector.size());
81 assert(Vector[I->second].first == I->first);
83 for (typename VectorTy::const_iterator I = Vector.begin(),
84 E = Vector.end(); I != E; ++I)
86 (Map.count(I->first) &&
87 Map[I->first] == size_t(I - Vector.begin())));
91 ValueT &operator[](KeyT Arg) {
92 std::pair<typename MapTy::iterator, bool> Pair =
93 Map.insert(std::make_pair(Arg, size_t(0)));
95 Pair.first->second = Vector.size();
96 Vector.push_back(std::make_pair(Arg, ValueT()));
97 return Vector.back().second;
99 return Vector[Pair.first->second].second;
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)));
107 Pair.first->second = Vector.size();
108 Vector.push_back(InsertPair);
109 return std::make_pair(llvm::prior(Vector.end()), true);
111 return std::make_pair(Vector.begin() + Pair.first->second, false);
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;
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
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();
138 //===----------------------------------------------------------------------===//
140 //===----------------------------------------------------------------------===//
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
170 /// IsPotentialUse - Test whether the given value is possible a
171 /// reference-counted pointer.
172 static 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))
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())
182 // Only consider values with pointer types.
183 // It seemes intuitive to exclude function pointer types as well, since
184 // functions are never reference-counted, however clang occasionally
185 // bitcasts reference-counted pointers to function-pointer type
187 PointerType *Ty = dyn_cast<PointerType>(Op->getType());
190 // Conservatively assume anything else is a potential use.
194 /// GetCallSiteClass - Helper for GetInstructionClass. Determines what kind
195 /// of construct CS is.
196 static InstructionClass GetCallSiteClass(ImmutableCallSite CS) {
197 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
199 if (IsPotentialUse(*I))
200 return CS.onlyReadsMemory() ? IC_User : IC_CallOrUser;
202 return CS.onlyReadsMemory() ? IC_None : IC_Call;
205 /// GetFunctionClass - Determine if F is one of the special known Functions.
206 /// If it isn't, return IC_CallOrUser.
207 static InstructionClass GetFunctionClass(const Function *F) {
208 Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
212 return StringSwitch<InstructionClass>(F->getName())
213 .Case("objc_autoreleasePoolPush", IC_AutoreleasepoolPush)
214 .Default(IC_CallOrUser);
217 const Argument *A0 = AI++;
219 // Argument is a pointer.
220 if (PointerType *PTy = dyn_cast<PointerType>(A0->getType())) {
221 Type *ETy = PTy->getElementType();
223 if (ETy->isIntegerTy(8))
224 return StringSwitch<InstructionClass>(F->getName())
225 .Case("objc_retain", IC_Retain)
226 .Case("objc_retainAutoreleasedReturnValue", IC_RetainRV)
227 .Case("objc_retainBlock", IC_RetainBlock)
228 .Case("objc_release", IC_Release)
229 .Case("objc_autorelease", IC_Autorelease)
230 .Case("objc_autoreleaseReturnValue", IC_AutoreleaseRV)
231 .Case("objc_autoreleasePoolPop", IC_AutoreleasepoolPop)
232 .Case("objc_retainedObject", IC_NoopCast)
233 .Case("objc_unretainedObject", IC_NoopCast)
234 .Case("objc_unretainedPointer", IC_NoopCast)
235 .Case("objc_retain_autorelease", IC_FusedRetainAutorelease)
236 .Case("objc_retainAutorelease", IC_FusedRetainAutorelease)
237 .Case("objc_retainAutoreleaseReturnValue",IC_FusedRetainAutoreleaseRV)
238 .Default(IC_CallOrUser);
241 if (PointerType *Pte = dyn_cast<PointerType>(ETy))
242 if (Pte->getElementType()->isIntegerTy(8))
243 return StringSwitch<InstructionClass>(F->getName())
244 .Case("objc_loadWeakRetained", IC_LoadWeakRetained)
245 .Case("objc_loadWeak", IC_LoadWeak)
246 .Case("objc_destroyWeak", IC_DestroyWeak)
247 .Default(IC_CallOrUser);
250 // Two arguments, first is i8**.
251 const Argument *A1 = AI++;
253 if (PointerType *PTy = dyn_cast<PointerType>(A0->getType()))
254 if (PointerType *Pte = dyn_cast<PointerType>(PTy->getElementType()))
255 if (Pte->getElementType()->isIntegerTy(8))
256 if (PointerType *PTy1 = dyn_cast<PointerType>(A1->getType())) {
257 Type *ETy1 = PTy1->getElementType();
258 // Second argument is i8*
259 if (ETy1->isIntegerTy(8))
260 return StringSwitch<InstructionClass>(F->getName())
261 .Case("objc_storeWeak", IC_StoreWeak)
262 .Case("objc_initWeak", IC_InitWeak)
263 .Default(IC_CallOrUser);
264 // Second argument is i8**.
265 if (PointerType *Pte1 = dyn_cast<PointerType>(ETy1))
266 if (Pte1->getElementType()->isIntegerTy(8))
267 return StringSwitch<InstructionClass>(F->getName())
268 .Case("objc_moveWeak", IC_MoveWeak)
269 .Case("objc_copyWeak", IC_CopyWeak)
270 .Default(IC_CallOrUser);
274 return IC_CallOrUser;
277 /// GetInstructionClass - Determine what kind of construct V is.
278 static InstructionClass GetInstructionClass(const Value *V) {
279 if (const Instruction *I = dyn_cast<Instruction>(V)) {
280 // Any instruction other than bitcast and gep with a pointer operand have a
281 // use of an objc pointer. Bitcasts, GEPs, Selects, PHIs transfer a pointer
282 // to a subsequent use, rather than using it themselves, in this sense.
283 // As a short cut, several other opcodes are known to have no pointer
284 // operands of interest. And ret is never followed by a release, so it's
285 // not interesting to examine.
286 switch (I->getOpcode()) {
287 case Instruction::Call: {
288 const CallInst *CI = cast<CallInst>(I);
289 // Check for calls to special functions.
290 if (const Function *F = CI->getCalledFunction()) {
291 InstructionClass Class = GetFunctionClass(F);
292 if (Class != IC_CallOrUser)
295 // None of the intrinsic functions do objc_release. For intrinsics, the
296 // only question is whether or not they may be users.
297 switch (F->getIntrinsicID()) {
299 case Intrinsic::bswap: case Intrinsic::ctpop:
300 case Intrinsic::ctlz: case Intrinsic::cttz:
301 case Intrinsic::returnaddress: case Intrinsic::frameaddress:
302 case Intrinsic::stacksave: case Intrinsic::stackrestore:
303 case Intrinsic::vastart: case Intrinsic::vacopy: case Intrinsic::vaend:
304 // Don't let dbg info affect our results.
305 case Intrinsic::dbg_declare: case Intrinsic::dbg_value:
306 // Short cut: Some intrinsics obviously don't use ObjC pointers.
309 for (Function::const_arg_iterator AI = F->arg_begin(),
310 AE = F->arg_end(); AI != AE; ++AI)
311 if (IsPotentialUse(AI))
316 return GetCallSiteClass(CI);
318 case Instruction::Invoke:
319 return GetCallSiteClass(cast<InvokeInst>(I));
320 case Instruction::BitCast:
321 case Instruction::GetElementPtr:
322 case Instruction::Select: case Instruction::PHI:
323 case Instruction::Ret: case Instruction::Br:
324 case Instruction::Switch: case Instruction::IndirectBr:
325 case Instruction::Alloca: case Instruction::VAArg:
326 case Instruction::Add: case Instruction::FAdd:
327 case Instruction::Sub: case Instruction::FSub:
328 case Instruction::Mul: case Instruction::FMul:
329 case Instruction::SDiv: case Instruction::UDiv: case Instruction::FDiv:
330 case Instruction::SRem: case Instruction::URem: case Instruction::FRem:
331 case Instruction::Shl: case Instruction::LShr: case Instruction::AShr:
332 case Instruction::And: case Instruction::Or: case Instruction::Xor:
333 case Instruction::SExt: case Instruction::ZExt: case Instruction::Trunc:
334 case Instruction::IntToPtr: case Instruction::FCmp:
335 case Instruction::FPTrunc: case Instruction::FPExt:
336 case Instruction::FPToUI: case Instruction::FPToSI:
337 case Instruction::UIToFP: case Instruction::SIToFP:
338 case Instruction::InsertElement: case Instruction::ExtractElement:
339 case Instruction::ShuffleVector:
340 case Instruction::ExtractValue:
342 case Instruction::ICmp:
343 // Comparing a pointer with null, or any other constant, isn't an
344 // interesting use, because we don't care what the pointer points to, or
345 // about the values of any other dynamic reference-counted pointers.
346 if (IsPotentialUse(I->getOperand(1)))
350 // For anything else, check all the operands.
351 // Note that this includes both operands of a Store: while the first
352 // operand isn't actually being dereferenced, it is being stored to
353 // memory where we can no longer track who might read it and dereference
354 // it, so we have to consider it potentially used.
355 for (User::const_op_iterator OI = I->op_begin(), OE = I->op_end();
357 if (IsPotentialUse(*OI))
362 // Otherwise, it's totally inert for ARC purposes.
366 /// GetBasicInstructionClass - Determine what kind of construct V is. This is
367 /// similar to GetInstructionClass except that it only detects objc runtine
368 /// calls. This allows it to be faster.
369 static InstructionClass GetBasicInstructionClass(const Value *V) {
370 if (const CallInst *CI = dyn_cast<CallInst>(V)) {
371 if (const Function *F = CI->getCalledFunction())
372 return GetFunctionClass(F);
373 // Otherwise, be conservative.
374 return IC_CallOrUser;
377 // Otherwise, be conservative.
378 return isa<InvokeInst>(V) ? IC_CallOrUser : IC_User;
381 /// IsRetain - Test if the the given class is objc_retain or
383 static bool IsRetain(InstructionClass Class) {
384 return Class == IC_Retain ||
385 Class == IC_RetainRV;
388 /// IsAutorelease - Test if the the given class is objc_autorelease or
390 static bool IsAutorelease(InstructionClass Class) {
391 return Class == IC_Autorelease ||
392 Class == IC_AutoreleaseRV;
395 /// IsForwarding - Test if the given class represents instructions which return
396 /// their argument verbatim.
397 static bool IsForwarding(InstructionClass Class) {
398 // objc_retainBlock technically doesn't always return its argument
399 // verbatim, but it doesn't matter for our purposes here.
400 return Class == IC_Retain ||
401 Class == IC_RetainRV ||
402 Class == IC_Autorelease ||
403 Class == IC_AutoreleaseRV ||
404 Class == IC_RetainBlock ||
405 Class == IC_NoopCast;
408 /// IsNoopOnNull - Test if the given class represents instructions which do
409 /// nothing if passed a null pointer.
410 static bool IsNoopOnNull(InstructionClass Class) {
411 return Class == IC_Retain ||
412 Class == IC_RetainRV ||
413 Class == IC_Release ||
414 Class == IC_Autorelease ||
415 Class == IC_AutoreleaseRV ||
416 Class == IC_RetainBlock;
419 /// IsAlwaysTail - Test if the given class represents instructions which are
420 /// always safe to mark with the "tail" keyword.
421 static bool IsAlwaysTail(InstructionClass Class) {
422 // IC_RetainBlock may be given a stack argument.
423 return Class == IC_Retain ||
424 Class == IC_RetainRV ||
425 Class == IC_Autorelease ||
426 Class == IC_AutoreleaseRV;
429 /// IsNoThrow - Test if the given class represents instructions which are always
430 /// safe to mark with the nounwind attribute..
431 static bool IsNoThrow(InstructionClass Class) {
432 // objc_retainBlock is not nounwind because it calls user copy constructors
433 // which could theoretically throw.
434 return Class == IC_Retain ||
435 Class == IC_RetainRV ||
436 Class == IC_Release ||
437 Class == IC_Autorelease ||
438 Class == IC_AutoreleaseRV ||
439 Class == IC_AutoreleasepoolPush ||
440 Class == IC_AutoreleasepoolPop;
443 /// EraseInstruction - Erase the given instruction. ObjC calls return their
444 /// argument verbatim, so if it's such a call and the return value has users,
445 /// replace them with the argument value.
446 static void EraseInstruction(Instruction *CI) {
447 Value *OldArg = cast<CallInst>(CI)->getArgOperand(0);
449 bool Unused = CI->use_empty();
452 // Replace the return value with the argument.
453 assert(IsForwarding(GetBasicInstructionClass(CI)) &&
454 "Can't delete non-forwarding instruction with users!");
455 CI->replaceAllUsesWith(OldArg);
458 CI->eraseFromParent();
461 RecursivelyDeleteTriviallyDeadInstructions(OldArg);
464 /// GetUnderlyingObjCPtr - This is a wrapper around getUnderlyingObject which
465 /// also knows how to look through objc_retain and objc_autorelease calls, which
466 /// we know to return their argument verbatim.
467 static const Value *GetUnderlyingObjCPtr(const Value *V) {
469 V = GetUnderlyingObject(V);
470 if (!IsForwarding(GetBasicInstructionClass(V)))
472 V = cast<CallInst>(V)->getArgOperand(0);
478 /// StripPointerCastsAndObjCCalls - This is a wrapper around
479 /// Value::stripPointerCasts which also knows how to look through objc_retain
480 /// and objc_autorelease calls, which we know to return their argument verbatim.
481 static const Value *StripPointerCastsAndObjCCalls(const Value *V) {
483 V = V->stripPointerCasts();
484 if (!IsForwarding(GetBasicInstructionClass(V)))
486 V = cast<CallInst>(V)->getArgOperand(0);
491 /// StripPointerCastsAndObjCCalls - This is a wrapper around
492 /// Value::stripPointerCasts which also knows how to look through objc_retain
493 /// and objc_autorelease calls, which we know to return their argument verbatim.
494 static Value *StripPointerCastsAndObjCCalls(Value *V) {
496 V = V->stripPointerCasts();
497 if (!IsForwarding(GetBasicInstructionClass(V)))
499 V = cast<CallInst>(V)->getArgOperand(0);
504 /// GetObjCArg - Assuming the given instruction is one of the special calls such
505 /// as objc_retain or objc_release, return the argument value, stripped of no-op
506 /// casts and forwarding calls.
507 static Value *GetObjCArg(Value *Inst) {
508 return StripPointerCastsAndObjCCalls(cast<CallInst>(Inst)->getArgOperand(0));
511 /// IsObjCIdentifiedObject - This is similar to AliasAnalysis'
512 /// isObjCIdentifiedObject, except that it uses special knowledge of
513 /// ObjC conventions...
514 static bool IsObjCIdentifiedObject(const Value *V) {
515 // Assume that call results and arguments have their own "provenance".
516 // Constants (including GlobalVariables) and Allocas are never
517 // reference-counted.
518 if (isa<CallInst>(V) || isa<InvokeInst>(V) ||
519 isa<Argument>(V) || isa<Constant>(V) ||
523 if (const LoadInst *LI = dyn_cast<LoadInst>(V)) {
524 const Value *Pointer =
525 StripPointerCastsAndObjCCalls(LI->getPointerOperand());
526 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Pointer)) {
527 // A constant pointer can't be pointing to an object on the heap. It may
528 // be reference-counted, but it won't be deleted.
529 if (GV->isConstant())
531 StringRef Name = GV->getName();
532 // These special variables are known to hold values which are not
533 // reference-counted pointers.
534 if (Name.startswith("\01L_OBJC_SELECTOR_REFERENCES_") ||
535 Name.startswith("\01L_OBJC_CLASSLIST_REFERENCES_") ||
536 Name.startswith("\01L_OBJC_CLASSLIST_SUP_REFS_$_") ||
537 Name.startswith("\01L_OBJC_METH_VAR_NAME_") ||
538 Name.startswith("\01l_objc_msgSend_fixup_"))
546 /// FindSingleUseIdentifiedObject - This is similar to
547 /// StripPointerCastsAndObjCCalls but it stops as soon as it finds a value
548 /// with multiple uses.
549 static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
550 if (Arg->hasOneUse()) {
551 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
552 return FindSingleUseIdentifiedObject(BC->getOperand(0));
553 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
554 if (GEP->hasAllZeroIndices())
555 return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
556 if (IsForwarding(GetBasicInstructionClass(Arg)))
557 return FindSingleUseIdentifiedObject(
558 cast<CallInst>(Arg)->getArgOperand(0));
559 if (!IsObjCIdentifiedObject(Arg))
564 // If we found an identifiable object but it has multiple uses, but they
565 // are trivial uses, we can still consider this to be a single-use
567 if (IsObjCIdentifiedObject(Arg)) {
568 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
571 if (!U->use_empty() || StripPointerCastsAndObjCCalls(U) != Arg)
581 /// ModuleHasARC - Test if the given module looks interesting to run ARC
583 static bool ModuleHasARC(const Module &M) {
585 M.getNamedValue("objc_retain") ||
586 M.getNamedValue("objc_release") ||
587 M.getNamedValue("objc_autorelease") ||
588 M.getNamedValue("objc_retainAutoreleasedReturnValue") ||
589 M.getNamedValue("objc_retainBlock") ||
590 M.getNamedValue("objc_autoreleaseReturnValue") ||
591 M.getNamedValue("objc_autoreleasePoolPush") ||
592 M.getNamedValue("objc_loadWeakRetained") ||
593 M.getNamedValue("objc_loadWeak") ||
594 M.getNamedValue("objc_destroyWeak") ||
595 M.getNamedValue("objc_storeWeak") ||
596 M.getNamedValue("objc_initWeak") ||
597 M.getNamedValue("objc_moveWeak") ||
598 M.getNamedValue("objc_copyWeak") ||
599 M.getNamedValue("objc_retainedObject") ||
600 M.getNamedValue("objc_unretainedObject") ||
601 M.getNamedValue("objc_unretainedPointer");
604 /// DoesObjCBlockEscape - Test whether the given pointer, which is an
605 /// Objective C block pointer, does not "escape". This differs from regular
606 /// escape analysis in that a use as an argument to a call is not considered
608 static bool DoesObjCBlockEscape(const Value *BlockPtr) {
609 // Walk the def-use chains.
610 SmallVector<const Value *, 4> Worklist;
611 Worklist.push_back(BlockPtr);
613 const Value *V = Worklist.pop_back_val();
614 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
616 const User *UUser = *UI;
617 // Special - Use by a call (callee or argument) is not considered
619 if (isa<CallInst>(UUser) || isa<InvokeInst>(UUser))
621 // Use by an instruction which copies the value is an escape if the
622 // result is an escape.
623 if (isa<BitCastInst>(UUser) || isa<GetElementPtrInst>(UUser) ||
624 isa<PHINode>(UUser) || isa<SelectInst>(UUser)) {
625 Worklist.push_back(UUser);
628 // Use by a load is not an escape.
629 if (isa<LoadInst>(UUser))
631 // Use by a store is not an escape if the use is the address.
632 if (const StoreInst *SI = dyn_cast<StoreInst>(UUser))
633 if (V != SI->getValueOperand())
635 // Otherwise, conservatively assume an escape.
638 } while (!Worklist.empty());
644 //===----------------------------------------------------------------------===//
645 // ARC AliasAnalysis.
646 //===----------------------------------------------------------------------===//
648 #include "llvm/Pass.h"
649 #include "llvm/Analysis/AliasAnalysis.h"
650 #include "llvm/Analysis/Passes.h"
653 /// ObjCARCAliasAnalysis - This is a simple alias analysis
654 /// implementation that uses knowledge of ARC constructs to answer queries.
656 /// TODO: This class could be generalized to know about other ObjC-specific
657 /// tricks. Such as knowing that ivars in the non-fragile ABI are non-aliasing
658 /// even though their offsets are dynamic.
659 class ObjCARCAliasAnalysis : public ImmutablePass,
660 public AliasAnalysis {
662 static char ID; // Class identification, replacement for typeinfo
663 ObjCARCAliasAnalysis() : ImmutablePass(ID) {
664 initializeObjCARCAliasAnalysisPass(*PassRegistry::getPassRegistry());
668 virtual void initializePass() {
669 InitializeAliasAnalysis(this);
672 /// getAdjustedAnalysisPointer - This method is used when a pass implements
673 /// an analysis interface through multiple inheritance. If needed, it
674 /// should override this to adjust the this pointer as needed for the
675 /// specified pass info.
676 virtual void *getAdjustedAnalysisPointer(const void *PI) {
677 if (PI == &AliasAnalysis::ID)
678 return (AliasAnalysis*)this;
682 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
683 virtual AliasResult alias(const Location &LocA, const Location &LocB);
684 virtual bool pointsToConstantMemory(const Location &Loc, bool OrLocal);
685 virtual ModRefBehavior getModRefBehavior(ImmutableCallSite CS);
686 virtual ModRefBehavior getModRefBehavior(const Function *F);
687 virtual ModRefResult getModRefInfo(ImmutableCallSite CS,
688 const Location &Loc);
689 virtual ModRefResult getModRefInfo(ImmutableCallSite CS1,
690 ImmutableCallSite CS2);
692 } // End of anonymous namespace
694 // Register this pass...
695 char ObjCARCAliasAnalysis::ID = 0;
696 INITIALIZE_AG_PASS(ObjCARCAliasAnalysis, AliasAnalysis, "objc-arc-aa",
697 "ObjC-ARC-Based Alias Analysis", false, true, false)
699 ImmutablePass *llvm::createObjCARCAliasAnalysisPass() {
700 return new ObjCARCAliasAnalysis();
704 ObjCARCAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
705 AU.setPreservesAll();
706 AliasAnalysis::getAnalysisUsage(AU);
709 AliasAnalysis::AliasResult
710 ObjCARCAliasAnalysis::alias(const Location &LocA, const Location &LocB) {
712 return AliasAnalysis::alias(LocA, LocB);
714 // First, strip off no-ops, including ObjC-specific no-ops, and try making a
715 // precise alias query.
716 const Value *SA = StripPointerCastsAndObjCCalls(LocA.Ptr);
717 const Value *SB = StripPointerCastsAndObjCCalls(LocB.Ptr);
719 AliasAnalysis::alias(Location(SA, LocA.Size, LocA.TBAATag),
720 Location(SB, LocB.Size, LocB.TBAATag));
721 if (Result != MayAlias)
724 // If that failed, climb to the underlying object, including climbing through
725 // ObjC-specific no-ops, and try making an imprecise alias query.
726 const Value *UA = GetUnderlyingObjCPtr(SA);
727 const Value *UB = GetUnderlyingObjCPtr(SB);
728 if (UA != SA || UB != SB) {
729 Result = AliasAnalysis::alias(Location(UA), Location(UB));
730 // We can't use MustAlias or PartialAlias results here because
731 // GetUnderlyingObjCPtr may return an offsetted pointer value.
732 if (Result == NoAlias)
736 // If that failed, fail. We don't need to chain here, since that's covered
737 // by the earlier precise query.
742 ObjCARCAliasAnalysis::pointsToConstantMemory(const Location &Loc,
745 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
747 // First, strip off no-ops, including ObjC-specific no-ops, and try making
748 // a precise alias query.
749 const Value *S = StripPointerCastsAndObjCCalls(Loc.Ptr);
750 if (AliasAnalysis::pointsToConstantMemory(Location(S, Loc.Size, Loc.TBAATag),
754 // If that failed, climb to the underlying object, including climbing through
755 // ObjC-specific no-ops, and try making an imprecise alias query.
756 const Value *U = GetUnderlyingObjCPtr(S);
758 return AliasAnalysis::pointsToConstantMemory(Location(U), OrLocal);
760 // If that failed, fail. We don't need to chain here, since that's covered
761 // by the earlier precise query.
765 AliasAnalysis::ModRefBehavior
766 ObjCARCAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
767 // We have nothing to do. Just chain to the next AliasAnalysis.
768 return AliasAnalysis::getModRefBehavior(CS);
771 AliasAnalysis::ModRefBehavior
772 ObjCARCAliasAnalysis::getModRefBehavior(const Function *F) {
774 return AliasAnalysis::getModRefBehavior(F);
776 switch (GetFunctionClass(F)) {
778 return DoesNotAccessMemory;
783 return AliasAnalysis::getModRefBehavior(F);
786 AliasAnalysis::ModRefResult
787 ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS, const Location &Loc) {
789 return AliasAnalysis::getModRefInfo(CS, Loc);
791 switch (GetBasicInstructionClass(CS.getInstruction())) {
795 case IC_AutoreleaseRV:
797 case IC_AutoreleasepoolPush:
798 case IC_FusedRetainAutorelease:
799 case IC_FusedRetainAutoreleaseRV:
800 // These functions don't access any memory visible to the compiler.
801 // Note that this doesn't include objc_retainBlock, becuase it updates
802 // pointers when it copies block data.
808 return AliasAnalysis::getModRefInfo(CS, Loc);
811 AliasAnalysis::ModRefResult
812 ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
813 ImmutableCallSite CS2) {
814 // TODO: Theoretically we could check for dependencies between objc_* calls
815 // and OnlyAccessesArgumentPointees calls or other well-behaved calls.
816 return AliasAnalysis::getModRefInfo(CS1, CS2);
819 //===----------------------------------------------------------------------===//
821 //===----------------------------------------------------------------------===//
823 #include "llvm/Support/InstIterator.h"
824 #include "llvm/Transforms/Scalar.h"
827 /// ObjCARCExpand - Early ARC transformations.
828 class ObjCARCExpand : public FunctionPass {
829 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
830 virtual bool doInitialization(Module &M);
831 virtual bool runOnFunction(Function &F);
833 /// Run - A flag indicating whether this optimization pass should run.
838 ObjCARCExpand() : FunctionPass(ID) {
839 initializeObjCARCExpandPass(*PassRegistry::getPassRegistry());
844 char ObjCARCExpand::ID = 0;
845 INITIALIZE_PASS(ObjCARCExpand,
846 "objc-arc-expand", "ObjC ARC expansion", false, false)
848 Pass *llvm::createObjCARCExpandPass() {
849 return new ObjCARCExpand();
852 void ObjCARCExpand::getAnalysisUsage(AnalysisUsage &AU) const {
853 AU.setPreservesCFG();
856 bool ObjCARCExpand::doInitialization(Module &M) {
857 Run = ModuleHasARC(M);
861 bool ObjCARCExpand::runOnFunction(Function &F) {
865 // If nothing in the Module uses ARC, don't do anything.
869 bool Changed = false;
871 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
872 Instruction *Inst = &*I;
874 switch (GetBasicInstructionClass(Inst)) {
878 case IC_AutoreleaseRV:
879 case IC_FusedRetainAutorelease:
880 case IC_FusedRetainAutoreleaseRV:
881 // These calls return their argument verbatim, as a low-level
882 // optimization. However, this makes high-level optimizations
883 // harder. Undo any uses of this optimization that the front-end
884 // emitted here. We'll redo them in a later pass.
886 Inst->replaceAllUsesWith(cast<CallInst>(Inst)->getArgOperand(0));
896 //===----------------------------------------------------------------------===//
897 // ARC autorelease pool elimination.
898 //===----------------------------------------------------------------------===//
900 #include "llvm/Constants.h"
903 /// ObjCARCAPElim - Autorelease pool elimination.
904 class ObjCARCAPElim : public ModulePass {
905 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
906 virtual bool runOnModule(Module &M);
908 bool MayAutorelease(CallSite CS, unsigned Depth = 0);
909 bool OptimizeBB(BasicBlock *BB);
913 ObjCARCAPElim() : ModulePass(ID) {
914 initializeObjCARCAPElimPass(*PassRegistry::getPassRegistry());
919 char ObjCARCAPElim::ID = 0;
920 INITIALIZE_PASS(ObjCARCAPElim,
922 "ObjC ARC autorelease pool elimination",
925 Pass *llvm::createObjCARCAPElimPass() {
926 return new ObjCARCAPElim();
929 void ObjCARCAPElim::getAnalysisUsage(AnalysisUsage &AU) const {
930 AU.setPreservesCFG();
933 /// MayAutorelease - Interprocedurally determine if calls made by the
934 /// given call site can possibly produce autoreleases.
935 bool ObjCARCAPElim::MayAutorelease(CallSite CS, unsigned Depth) {
936 if (Function *Callee = CS.getCalledFunction()) {
937 if (Callee->isDeclaration() || Callee->mayBeOverridden())
939 for (Function::iterator I = Callee->begin(), E = Callee->end();
942 for (BasicBlock::iterator J = BB->begin(), F = BB->end(); J != F; ++J)
943 if (CallSite JCS = CallSite(J))
944 // This recursion depth limit is arbitrary. It's just great
945 // enough to cover known interesting testcases.
947 !JCS.onlyReadsMemory() &&
948 MayAutorelease(JCS, Depth + 1))
957 bool ObjCARCAPElim::OptimizeBB(BasicBlock *BB) {
958 bool Changed = false;
960 Instruction *Push = 0;
961 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
962 Instruction *Inst = I++;
963 switch (GetBasicInstructionClass(Inst)) {
964 case IC_AutoreleasepoolPush:
967 case IC_AutoreleasepoolPop:
968 // If this pop matches a push and nothing in between can autorelease,
970 if (Push && cast<CallInst>(Inst)->getArgOperand(0) == Push) {
972 Inst->eraseFromParent();
973 Push->eraseFromParent();
978 if (MayAutorelease(CallSite(Inst)))
989 bool ObjCARCAPElim::runOnModule(Module &M) {
993 // If nothing in the Module uses ARC, don't do anything.
994 if (!ModuleHasARC(M))
997 // Find the llvm.global_ctors variable, as the first step in
998 // identifying the global constructors.
999 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1003 assert(GV->hasDefinitiveInitializer() &&
1004 "llvm.global_ctors is uncooperative!");
1006 bool Changed = false;
1008 // Dig the constructor functions out of GV's initializer.
1009 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
1010 for (User::op_iterator OI = Init->op_begin(), OE = Init->op_end();
1013 // llvm.global_ctors is an array of pairs where the second members
1014 // are constructor functions.
1015 Function *F = cast<Function>(cast<ConstantStruct>(Op)->getOperand(1));
1016 // Only look at function definitions.
1017 if (F->isDeclaration())
1019 // Only look at functions with one basic block.
1020 if (llvm::next(F->begin()) != F->end())
1022 // Ok, a single-block constructor function definition. Try to optimize it.
1023 Changed |= OptimizeBB(F->begin());
1029 //===----------------------------------------------------------------------===//
1030 // ARC optimization.
1031 //===----------------------------------------------------------------------===//
1033 // TODO: On code like this:
1036 // stuff_that_cannot_release()
1037 // objc_autorelease(%x)
1038 // stuff_that_cannot_release()
1040 // stuff_that_cannot_release()
1041 // objc_autorelease(%x)
1043 // The second retain and autorelease can be deleted.
1045 // TODO: It should be possible to delete
1046 // objc_autoreleasePoolPush and objc_autoreleasePoolPop
1047 // pairs if nothing is actually autoreleased between them. Also, autorelease
1048 // calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
1049 // after inlining) can be turned into plain release calls.
1051 // TODO: Critical-edge splitting. If the optimial insertion point is
1052 // a critical edge, the current algorithm has to fail, because it doesn't
1053 // know how to split edges. It should be possible to make the optimizer
1054 // think in terms of edges, rather than blocks, and then split critical
1057 // TODO: OptimizeSequences could generalized to be Interprocedural.
1059 // TODO: Recognize that a bunch of other objc runtime calls have
1060 // non-escaping arguments and non-releasing arguments, and may be
1061 // non-autoreleasing.
1063 // TODO: Sink autorelease calls as far as possible. Unfortunately we
1064 // usually can't sink them past other calls, which would be the main
1065 // case where it would be useful.
1067 // TODO: The pointer returned from objc_loadWeakRetained is retained.
1069 // TODO: Delete release+retain pairs (rare).
1071 #include "llvm/GlobalAlias.h"
1072 #include "llvm/Constants.h"
1073 #include "llvm/LLVMContext.h"
1074 #include "llvm/Support/ErrorHandling.h"
1075 #include "llvm/Support/CFG.h"
1076 #include "llvm/ADT/Statistic.h"
1077 #include "llvm/ADT/SmallPtrSet.h"
1078 #include "llvm/ADT/DenseSet.h"
1080 STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
1081 STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
1082 STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
1083 STATISTIC(NumRets, "Number of return value forwarding "
1084 "retain+autoreleaes eliminated");
1085 STATISTIC(NumRRs, "Number of retain+release paths eliminated");
1086 STATISTIC(NumPeeps, "Number of calls peephole-optimized");
1089 /// ProvenanceAnalysis - This is similar to BasicAliasAnalysis, and it
1090 /// uses many of the same techniques, except it uses special ObjC-specific
1091 /// reasoning about pointer relationships.
1092 class ProvenanceAnalysis {
1095 typedef std::pair<const Value *, const Value *> ValuePairTy;
1096 typedef DenseMap<ValuePairTy, bool> CachedResultsTy;
1097 CachedResultsTy CachedResults;
1099 bool relatedCheck(const Value *A, const Value *B);
1100 bool relatedSelect(const SelectInst *A, const Value *B);
1101 bool relatedPHI(const PHINode *A, const Value *B);
1103 // Do not implement.
1104 void operator=(const ProvenanceAnalysis &);
1105 ProvenanceAnalysis(const ProvenanceAnalysis &);
1108 ProvenanceAnalysis() {}
1110 void setAA(AliasAnalysis *aa) { AA = aa; }
1112 AliasAnalysis *getAA() const { return AA; }
1114 bool related(const Value *A, const Value *B);
1117 CachedResults.clear();
1122 bool ProvenanceAnalysis::relatedSelect(const SelectInst *A, const Value *B) {
1123 // If the values are Selects with the same condition, we can do a more precise
1124 // check: just check for relations between the values on corresponding arms.
1125 if (const SelectInst *SB = dyn_cast<SelectInst>(B))
1126 if (A->getCondition() == SB->getCondition()) {
1127 if (related(A->getTrueValue(), SB->getTrueValue()))
1129 if (related(A->getFalseValue(), SB->getFalseValue()))
1134 // Check both arms of the Select node individually.
1135 if (related(A->getTrueValue(), B))
1137 if (related(A->getFalseValue(), B))
1140 // The arms both checked out.
1144 bool ProvenanceAnalysis::relatedPHI(const PHINode *A, const Value *B) {
1145 // If the values are PHIs in the same block, we can do a more precise as well
1146 // as efficient check: just check for relations between the values on
1147 // corresponding edges.
1148 if (const PHINode *PNB = dyn_cast<PHINode>(B))
1149 if (PNB->getParent() == A->getParent()) {
1150 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i)
1151 if (related(A->getIncomingValue(i),
1152 PNB->getIncomingValueForBlock(A->getIncomingBlock(i))))
1157 // Check each unique source of the PHI node against B.
1158 SmallPtrSet<const Value *, 4> UniqueSrc;
1159 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i) {
1160 const Value *PV1 = A->getIncomingValue(i);
1161 if (UniqueSrc.insert(PV1) && related(PV1, B))
1165 // All of the arms checked out.
1169 /// isStoredObjCPointer - Test if the value of P, or any value covered by its
1170 /// provenance, is ever stored within the function (not counting callees).
1171 static bool isStoredObjCPointer(const Value *P) {
1172 SmallPtrSet<const Value *, 8> Visited;
1173 SmallVector<const Value *, 8> Worklist;
1174 Worklist.push_back(P);
1177 P = Worklist.pop_back_val();
1178 for (Value::const_use_iterator UI = P->use_begin(), UE = P->use_end();
1180 const User *Ur = *UI;
1181 if (isa<StoreInst>(Ur)) {
1182 if (UI.getOperandNo() == 0)
1183 // The pointer is stored.
1185 // The pointed is stored through.
1188 if (isa<CallInst>(Ur))
1189 // The pointer is passed as an argument, ignore this.
1191 if (isa<PtrToIntInst>(P))
1192 // Assume the worst.
1194 if (Visited.insert(Ur))
1195 Worklist.push_back(Ur);
1197 } while (!Worklist.empty());
1199 // Everything checked out.
1203 bool ProvenanceAnalysis::relatedCheck(const Value *A, const Value *B) {
1204 // Skip past provenance pass-throughs.
1205 A = GetUnderlyingObjCPtr(A);
1206 B = GetUnderlyingObjCPtr(B);
1212 // Ask regular AliasAnalysis, for a first approximation.
1213 switch (AA->alias(A, B)) {
1214 case AliasAnalysis::NoAlias:
1216 case AliasAnalysis::MustAlias:
1217 case AliasAnalysis::PartialAlias:
1219 case AliasAnalysis::MayAlias:
1223 bool AIsIdentified = IsObjCIdentifiedObject(A);
1224 bool BIsIdentified = IsObjCIdentifiedObject(B);
1226 // An ObjC-Identified object can't alias a load if it is never locally stored.
1227 if (AIsIdentified) {
1228 if (BIsIdentified) {
1229 // If both pointers have provenance, they can be directly compared.
1233 if (isa<LoadInst>(B))
1234 return isStoredObjCPointer(A);
1237 if (BIsIdentified && isa<LoadInst>(A))
1238 return isStoredObjCPointer(B);
1241 // Special handling for PHI and Select.
1242 if (const PHINode *PN = dyn_cast<PHINode>(A))
1243 return relatedPHI(PN, B);
1244 if (const PHINode *PN = dyn_cast<PHINode>(B))
1245 return relatedPHI(PN, A);
1246 if (const SelectInst *S = dyn_cast<SelectInst>(A))
1247 return relatedSelect(S, B);
1248 if (const SelectInst *S = dyn_cast<SelectInst>(B))
1249 return relatedSelect(S, A);
1255 bool ProvenanceAnalysis::related(const Value *A, const Value *B) {
1256 // Begin by inserting a conservative value into the map. If the insertion
1257 // fails, we have the answer already. If it succeeds, leave it there until we
1258 // compute the real answer to guard against recursive queries.
1259 if (A > B) std::swap(A, B);
1260 std::pair<CachedResultsTy::iterator, bool> Pair =
1261 CachedResults.insert(std::make_pair(ValuePairTy(A, B), true));
1263 return Pair.first->second;
1265 bool Result = relatedCheck(A, B);
1266 CachedResults[ValuePairTy(A, B)] = Result;
1271 // Sequence - A sequence of states that a pointer may go through in which an
1272 // objc_retain and objc_release are actually needed.
1275 S_Retain, ///< objc_retain(x)
1276 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement
1277 S_Use, ///< any use of x
1278 S_Stop, ///< like S_Release, but code motion is stopped
1279 S_Release, ///< objc_release(x)
1280 S_MovableRelease ///< objc_release(x), !clang.imprecise_release
1284 static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
1288 if (A == S_None || B == S_None)
1291 if (A > B) std::swap(A, B);
1293 // Choose the side which is further along in the sequence.
1294 if ((A == S_Retain || A == S_CanRelease) &&
1295 (B == S_CanRelease || B == S_Use))
1298 // Choose the side which is further along in the sequence.
1299 if ((A == S_Use || A == S_CanRelease) &&
1300 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
1302 // If both sides are releases, choose the more conservative one.
1303 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
1305 if (A == S_Release && B == S_MovableRelease)
1313 /// RRInfo - Unidirectional information about either a
1314 /// retain-decrement-use-release sequence or release-use-decrement-retain
1315 /// reverese sequence.
1317 /// KnownSafe - After an objc_retain, the reference count of the referenced
1318 /// object is known to be positive. Similarly, before an objc_release, the
1319 /// reference count of the referenced object is known to be positive. If
1320 /// there are retain-release pairs in code regions where the retain count
1321 /// is known to be positive, they can be eliminated, regardless of any side
1322 /// effects between them.
1324 /// Also, a retain+release pair nested within another retain+release
1325 /// pair all on the known same pointer value can be eliminated, regardless
1326 /// of any intervening side effects.
1328 /// KnownSafe is true when either of these conditions is satisfied.
1331 /// IsRetainBlock - True if the Calls are objc_retainBlock calls (as
1332 /// opposed to objc_retain calls).
1335 /// IsTailCallRelease - True of the objc_release calls are all marked
1336 /// with the "tail" keyword.
1337 bool IsTailCallRelease;
1339 /// Partial - True of we've seen an opportunity for partial RR elimination,
1340 /// such as pushing calls into a CFG triangle or into one side of a
1342 /// TODO: Consider moving this to PtrState.
1345 /// ReleaseMetadata - If the Calls are objc_release calls and they all have
1346 /// a clang.imprecise_release tag, this is the metadata tag.
1347 MDNode *ReleaseMetadata;
1349 /// Calls - For a top-down sequence, the set of objc_retains or
1350 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
1351 SmallPtrSet<Instruction *, 2> Calls;
1353 /// ReverseInsertPts - The set of optimal insert positions for
1354 /// moving calls in the opposite sequence.
1355 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
1358 KnownSafe(false), IsRetainBlock(false),
1359 IsTailCallRelease(false), Partial(false),
1360 ReleaseMetadata(0) {}
1366 void RRInfo::clear() {
1368 IsRetainBlock = false;
1369 IsTailCallRelease = false;
1371 ReleaseMetadata = 0;
1373 ReverseInsertPts.clear();
1377 /// PtrState - This class summarizes several per-pointer runtime properties
1378 /// which are propogated through the flow graph.
1380 /// RefCount - The known minimum number of reference count increments.
1383 /// NestCount - The known minimum level of retain+release nesting.
1386 /// Seq - The current position in the sequence.
1390 /// RRI - Unidirectional information about the current sequence.
1391 /// TODO: Encapsulate this better.
1394 PtrState() : RefCount(0), NestCount(0), Seq(S_None) {}
1396 void SetAtLeastOneRefCount() {
1397 if (RefCount == 0) RefCount = 1;
1400 void IncrementRefCount() {
1401 if (RefCount != UINT_MAX) ++RefCount;
1404 void DecrementRefCount() {
1405 if (RefCount != 0) --RefCount;
1408 bool IsKnownIncremented() const {
1409 return RefCount > 0;
1412 void IncrementNestCount() {
1413 if (NestCount != UINT_MAX) ++NestCount;
1416 void DecrementNestCount() {
1417 if (NestCount != 0) --NestCount;
1420 bool IsKnownNested() const {
1421 return NestCount > 0;
1424 void SetSeq(Sequence NewSeq) {
1428 Sequence GetSeq() const {
1432 void ClearSequenceProgress() {
1437 void Merge(const PtrState &Other, bool TopDown);
1442 PtrState::Merge(const PtrState &Other, bool TopDown) {
1443 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
1444 RefCount = std::min(RefCount, Other.RefCount);
1445 NestCount = std::min(NestCount, Other.NestCount);
1447 // We can't merge a plain objc_retain with an objc_retainBlock.
1448 if (RRI.IsRetainBlock != Other.RRI.IsRetainBlock)
1451 // If we're not in a sequence (anymore), drop all associated state.
1452 if (Seq == S_None) {
1454 } else if (RRI.Partial || Other.RRI.Partial) {
1455 // If we're doing a merge on a path that's previously seen a partial
1456 // merge, conservatively drop the sequence, to avoid doing partial
1457 // RR elimination. If the branch predicates for the two merge differ,
1458 // mixing them is unsafe.
1462 // Conservatively merge the ReleaseMetadata information.
1463 if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
1464 RRI.ReleaseMetadata = 0;
1466 RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
1467 RRI.IsTailCallRelease = RRI.IsTailCallRelease && Other.RRI.IsTailCallRelease;
1468 RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
1470 // Merge the insert point sets. If there are any differences,
1471 // that makes this a partial merge.
1472 RRI.Partial = RRI.ReverseInsertPts.size() !=
1473 Other.RRI.ReverseInsertPts.size();
1474 for (SmallPtrSet<Instruction *, 2>::const_iterator
1475 I = Other.RRI.ReverseInsertPts.begin(),
1476 E = Other.RRI.ReverseInsertPts.end(); I != E; ++I)
1477 RRI.Partial |= RRI.ReverseInsertPts.insert(*I);
1482 /// BBState - Per-BasicBlock state.
1484 /// TopDownPathCount - The number of unique control paths from the entry
1485 /// which can reach this block.
1486 unsigned TopDownPathCount;
1488 /// BottomUpPathCount - The number of unique control paths to exits
1489 /// from this block.
1490 unsigned BottomUpPathCount;
1492 /// MapTy - A type for PerPtrTopDown and PerPtrBottomUp.
1493 typedef MapVector<const Value *, PtrState> MapTy;
1495 /// PerPtrTopDown - The top-down traversal uses this to record information
1496 /// known about a pointer at the bottom of each block.
1497 MapTy PerPtrTopDown;
1499 /// PerPtrBottomUp - The bottom-up traversal uses this to record information
1500 /// known about a pointer at the top of each block.
1501 MapTy PerPtrBottomUp;
1504 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
1506 typedef MapTy::iterator ptr_iterator;
1507 typedef MapTy::const_iterator ptr_const_iterator;
1509 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
1510 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
1511 ptr_const_iterator top_down_ptr_begin() const {
1512 return PerPtrTopDown.begin();
1514 ptr_const_iterator top_down_ptr_end() const {
1515 return PerPtrTopDown.end();
1518 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
1519 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
1520 ptr_const_iterator bottom_up_ptr_begin() const {
1521 return PerPtrBottomUp.begin();
1523 ptr_const_iterator bottom_up_ptr_end() const {
1524 return PerPtrBottomUp.end();
1527 /// SetAsEntry - Mark this block as being an entry block, which has one
1528 /// path from the entry by definition.
1529 void SetAsEntry() { TopDownPathCount = 1; }
1531 /// SetAsExit - Mark this block as being an exit block, which has one
1532 /// path to an exit by definition.
1533 void SetAsExit() { BottomUpPathCount = 1; }
1535 PtrState &getPtrTopDownState(const Value *Arg) {
1536 return PerPtrTopDown[Arg];
1539 PtrState &getPtrBottomUpState(const Value *Arg) {
1540 return PerPtrBottomUp[Arg];
1543 void clearBottomUpPointers() {
1544 PerPtrBottomUp.clear();
1547 void clearTopDownPointers() {
1548 PerPtrTopDown.clear();
1551 void InitFromPred(const BBState &Other);
1552 void InitFromSucc(const BBState &Other);
1553 void MergePred(const BBState &Other);
1554 void MergeSucc(const BBState &Other);
1556 /// GetAllPathCount - Return the number of possible unique paths from an
1557 /// entry to an exit which pass through this block. This is only valid
1558 /// after both the top-down and bottom-up traversals are complete.
1559 unsigned GetAllPathCount() const {
1560 return TopDownPathCount * BottomUpPathCount;
1563 /// IsVisitedTopDown - Test whether the block for this BBState has been
1564 /// visited by the top-down portion of the algorithm.
1565 bool isVisitedTopDown() const {
1566 return TopDownPathCount != 0;
1571 void BBState::InitFromPred(const BBState &Other) {
1572 PerPtrTopDown = Other.PerPtrTopDown;
1573 TopDownPathCount = Other.TopDownPathCount;
1576 void BBState::InitFromSucc(const BBState &Other) {
1577 PerPtrBottomUp = Other.PerPtrBottomUp;
1578 BottomUpPathCount = Other.BottomUpPathCount;
1581 /// MergePred - The top-down traversal uses this to merge information about
1582 /// predecessors to form the initial state for a new block.
1583 void BBState::MergePred(const BBState &Other) {
1584 // Other.TopDownPathCount can be 0, in which case it is either dead or a
1585 // loop backedge. Loop backedges are special.
1586 TopDownPathCount += Other.TopDownPathCount;
1588 // For each entry in the other set, if our set has an entry with the same key,
1589 // merge the entries. Otherwise, copy the entry and merge it with an empty
1591 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
1592 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
1593 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
1594 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1598 // For each entry in our set, if the other set doesn't have an entry with the
1599 // same key, force it to merge with an empty entry.
1600 for (ptr_iterator MI = top_down_ptr_begin(),
1601 ME = top_down_ptr_end(); MI != ME; ++MI)
1602 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
1603 MI->second.Merge(PtrState(), /*TopDown=*/true);
1606 /// MergeSucc - The bottom-up traversal uses this to merge information about
1607 /// successors to form the initial state for a new block.
1608 void BBState::MergeSucc(const BBState &Other) {
1609 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
1610 // loop backedge. Loop backedges are special.
1611 BottomUpPathCount += Other.BottomUpPathCount;
1613 // For each entry in the other set, if our set has an entry with the
1614 // same key, merge the entries. Otherwise, copy the entry and merge
1615 // it with an empty entry.
1616 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
1617 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
1618 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
1619 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1623 // For each entry in our set, if the other set doesn't have an entry
1624 // with the same key, force it to merge with an empty entry.
1625 for (ptr_iterator MI = bottom_up_ptr_begin(),
1626 ME = bottom_up_ptr_end(); MI != ME; ++MI)
1627 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
1628 MI->second.Merge(PtrState(), /*TopDown=*/false);
1632 /// ObjCARCOpt - The main ARC optimization pass.
1633 class ObjCARCOpt : public FunctionPass {
1635 ProvenanceAnalysis PA;
1637 /// Run - A flag indicating whether this optimization pass should run.
1640 /// RetainRVCallee, etc. - Declarations for ObjC runtime
1641 /// functions, for use in creating calls to them. These are initialized
1642 /// lazily to avoid cluttering up the Module with unused declarations.
1643 Constant *RetainRVCallee, *AutoreleaseRVCallee, *ReleaseCallee,
1644 *RetainCallee, *RetainBlockCallee, *AutoreleaseCallee;
1646 /// UsedInThisFunciton - Flags which determine whether each of the
1647 /// interesting runtine functions is in fact used in the current function.
1648 unsigned UsedInThisFunction;
1650 /// ImpreciseReleaseMDKind - The Metadata Kind for clang.imprecise_release
1652 unsigned ImpreciseReleaseMDKind;
1654 /// CopyOnEscapeMDKind - The Metadata Kind for clang.arc.copy_on_escape
1656 unsigned CopyOnEscapeMDKind;
1658 /// NoObjCARCExceptionsMDKind - The Metadata Kind for
1659 /// clang.arc.no_objc_arc_exceptions metadata.
1660 unsigned NoObjCARCExceptionsMDKind;
1662 Constant *getRetainRVCallee(Module *M);
1663 Constant *getAutoreleaseRVCallee(Module *M);
1664 Constant *getReleaseCallee(Module *M);
1665 Constant *getRetainCallee(Module *M);
1666 Constant *getRetainBlockCallee(Module *M);
1667 Constant *getAutoreleaseCallee(Module *M);
1669 bool IsRetainBlockOptimizable(const Instruction *Inst);
1671 void OptimizeRetainCall(Function &F, Instruction *Retain);
1672 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
1673 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV);
1674 void OptimizeIndividualCalls(Function &F);
1676 void CheckForCFGHazards(const BasicBlock *BB,
1677 DenseMap<const BasicBlock *, BBState> &BBStates,
1678 BBState &MyStates) const;
1679 bool VisitBottomUp(BasicBlock *BB,
1680 DenseMap<const BasicBlock *, BBState> &BBStates,
1681 MapVector<Value *, RRInfo> &Retains);
1682 bool VisitTopDown(BasicBlock *BB,
1683 DenseMap<const BasicBlock *, BBState> &BBStates,
1684 DenseMap<Value *, RRInfo> &Releases);
1685 bool Visit(Function &F,
1686 DenseMap<const BasicBlock *, BBState> &BBStates,
1687 MapVector<Value *, RRInfo> &Retains,
1688 DenseMap<Value *, RRInfo> &Releases);
1690 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1691 MapVector<Value *, RRInfo> &Retains,
1692 DenseMap<Value *, RRInfo> &Releases,
1693 SmallVectorImpl<Instruction *> &DeadInsts,
1696 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1697 MapVector<Value *, RRInfo> &Retains,
1698 DenseMap<Value *, RRInfo> &Releases,
1701 void OptimizeWeakCalls(Function &F);
1703 bool OptimizeSequences(Function &F);
1705 void OptimizeReturns(Function &F);
1707 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1708 virtual bool doInitialization(Module &M);
1709 virtual bool runOnFunction(Function &F);
1710 virtual void releaseMemory();
1714 ObjCARCOpt() : FunctionPass(ID) {
1715 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1720 char ObjCARCOpt::ID = 0;
1721 INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1722 "objc-arc", "ObjC ARC optimization", false, false)
1723 INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1724 INITIALIZE_PASS_END(ObjCARCOpt,
1725 "objc-arc", "ObjC ARC optimization", false, false)
1727 Pass *llvm::createObjCARCOptPass() {
1728 return new ObjCARCOpt();
1731 void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1732 AU.addRequired<ObjCARCAliasAnalysis>();
1733 AU.addRequired<AliasAnalysis>();
1734 // ARC optimization doesn't currently split critical edges.
1735 AU.setPreservesCFG();
1738 bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1739 // Without the magic metadata tag, we have to assume this might be an
1740 // objc_retainBlock call inserted to convert a block pointer to an id,
1741 // in which case it really is needed.
1742 if (!Inst->getMetadata(CopyOnEscapeMDKind))
1745 // If the pointer "escapes" (not including being used in a call),
1746 // the copy may be needed.
1747 if (DoesObjCBlockEscape(Inst))
1750 // Otherwise, it's not needed.
1754 Constant *ObjCARCOpt::getRetainRVCallee(Module *M) {
1755 if (!RetainRVCallee) {
1756 LLVMContext &C = M->getContext();
1757 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1758 std::vector<Type *> Params;
1759 Params.push_back(I8X);
1761 FunctionType::get(I8X, Params, /*isVarArg=*/false);
1762 AttrListPtr Attributes;
1763 Attributes.addAttr(~0u, Attribute::NoUnwind);
1765 M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy,
1768 return RetainRVCallee;
1771 Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1772 if (!AutoreleaseRVCallee) {
1773 LLVMContext &C = M->getContext();
1774 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1775 std::vector<Type *> Params;
1776 Params.push_back(I8X);
1778 FunctionType::get(I8X, Params, /*isVarArg=*/false);
1779 AttrListPtr Attributes;
1780 Attributes.addAttr(~0u, Attribute::NoUnwind);
1781 AutoreleaseRVCallee =
1782 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
1785 return AutoreleaseRVCallee;
1788 Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1789 if (!ReleaseCallee) {
1790 LLVMContext &C = M->getContext();
1791 std::vector<Type *> Params;
1792 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1793 AttrListPtr Attributes;
1794 Attributes.addAttr(~0u, Attribute::NoUnwind);
1796 M->getOrInsertFunction(
1798 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
1801 return ReleaseCallee;
1804 Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1805 if (!RetainCallee) {
1806 LLVMContext &C = M->getContext();
1807 std::vector<Type *> Params;
1808 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1809 AttrListPtr Attributes;
1810 Attributes.addAttr(~0u, Attribute::NoUnwind);
1812 M->getOrInsertFunction(
1814 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1817 return RetainCallee;
1820 Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1821 if (!RetainBlockCallee) {
1822 LLVMContext &C = M->getContext();
1823 std::vector<Type *> Params;
1824 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1825 AttrListPtr Attributes;
1826 // objc_retainBlock is not nounwind because it calls user copy constructors
1827 // which could theoretically throw.
1829 M->getOrInsertFunction(
1831 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1834 return RetainBlockCallee;
1837 Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1838 if (!AutoreleaseCallee) {
1839 LLVMContext &C = M->getContext();
1840 std::vector<Type *> Params;
1841 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1842 AttrListPtr Attributes;
1843 Attributes.addAttr(~0u, Attribute::NoUnwind);
1845 M->getOrInsertFunction(
1847 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1850 return AutoreleaseCallee;
1853 /// CanAlterRefCount - Test whether the given instruction can result in a
1854 /// reference count modification (positive or negative) for the pointer's
1857 CanAlterRefCount(const Instruction *Inst, const Value *Ptr,
1858 ProvenanceAnalysis &PA, InstructionClass Class) {
1860 case IC_Autorelease:
1861 case IC_AutoreleaseRV:
1863 // These operations never directly modify a reference count.
1868 ImmutableCallSite CS = static_cast<const Value *>(Inst);
1869 assert(CS && "Only calls can alter reference counts!");
1871 // See if AliasAnalysis can help us with the call.
1872 AliasAnalysis::ModRefBehavior MRB = PA.getAA()->getModRefBehavior(CS);
1873 if (AliasAnalysis::onlyReadsMemory(MRB))
1875 if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
1876 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1878 const Value *Op = *I;
1879 if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1885 // Assume the worst.
1889 /// CanUse - Test whether the given instruction can "use" the given pointer's
1890 /// object in a way that requires the reference count to be positive.
1892 CanUse(const Instruction *Inst, const Value *Ptr, ProvenanceAnalysis &PA,
1893 InstructionClass Class) {
1894 // IC_Call operations (as opposed to IC_CallOrUser) never "use" objc pointers.
1895 if (Class == IC_Call)
1898 // Consider various instructions which may have pointer arguments which are
1900 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(Inst)) {
1901 // Comparing a pointer with null, or any other constant, isn't really a use,
1902 // because we don't care what the pointer points to, or about the values
1903 // of any other dynamic reference-counted pointers.
1904 if (!IsPotentialUse(ICI->getOperand(1)))
1906 } else if (ImmutableCallSite CS = static_cast<const Value *>(Inst)) {
1907 // For calls, just check the arguments (and not the callee operand).
1908 for (ImmutableCallSite::arg_iterator OI = CS.arg_begin(),
1909 OE = CS.arg_end(); OI != OE; ++OI) {
1910 const Value *Op = *OI;
1911 if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1915 } else if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1916 // Special-case stores, because we don't care about the stored value, just
1917 // the store address.
1918 const Value *Op = GetUnderlyingObjCPtr(SI->getPointerOperand());
1919 // If we can't tell what the underlying object was, assume there is a
1921 return IsPotentialUse(Op) && PA.related(Op, Ptr);
1924 // Check each operand for a match.
1925 for (User::const_op_iterator OI = Inst->op_begin(), OE = Inst->op_end();
1927 const Value *Op = *OI;
1928 if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1934 /// CanInterruptRV - Test whether the given instruction can autorelease
1935 /// any pointer or cause an autoreleasepool pop.
1937 CanInterruptRV(InstructionClass Class) {
1939 case IC_AutoreleasepoolPop:
1942 case IC_Autorelease:
1943 case IC_AutoreleaseRV:
1944 case IC_FusedRetainAutorelease:
1945 case IC_FusedRetainAutoreleaseRV:
1953 /// DependenceKind - There are several kinds of dependence-like concepts in
1955 enum DependenceKind {
1956 NeedsPositiveRetainCount,
1957 CanChangeRetainCount,
1958 RetainAutoreleaseDep, ///< Blocks objc_retainAutorelease.
1959 RetainAutoreleaseRVDep, ///< Blocks objc_retainAutoreleaseReturnValue.
1960 RetainRVDep ///< Blocks objc_retainAutoreleasedReturnValue.
1964 /// Depends - Test if there can be dependencies on Inst through Arg. This
1965 /// function only tests dependencies relevant for removing pairs of calls.
1967 Depends(DependenceKind Flavor, Instruction *Inst, const Value *Arg,
1968 ProvenanceAnalysis &PA) {
1969 // If we've reached the definition of Arg, stop.
1974 case NeedsPositiveRetainCount: {
1975 InstructionClass Class = GetInstructionClass(Inst);
1977 case IC_AutoreleasepoolPop:
1978 case IC_AutoreleasepoolPush:
1982 return CanUse(Inst, Arg, PA, Class);
1986 case CanChangeRetainCount: {
1987 InstructionClass Class = GetInstructionClass(Inst);
1989 case IC_AutoreleasepoolPop:
1990 // Conservatively assume this can decrement any count.
1992 case IC_AutoreleasepoolPush:
1996 return CanAlterRefCount(Inst, Arg, PA, Class);
2000 case RetainAutoreleaseDep:
2001 switch (GetBasicInstructionClass(Inst)) {
2002 case IC_AutoreleasepoolPop:
2003 // Don't merge an objc_autorelease with an objc_retain inside a different
2004 // autoreleasepool scope.
2008 // Check for a retain of the same pointer for merging.
2009 return GetObjCArg(Inst) == Arg;
2011 // Nothing else matters for objc_retainAutorelease formation.
2015 case RetainAutoreleaseRVDep: {
2016 InstructionClass Class = GetBasicInstructionClass(Inst);
2020 // Check for a retain of the same pointer for merging.
2021 return GetObjCArg(Inst) == Arg;
2023 // Anything that can autorelease interrupts
2024 // retainAutoreleaseReturnValue formation.
2025 return CanInterruptRV(Class);
2030 return CanInterruptRV(GetBasicInstructionClass(Inst));
2033 llvm_unreachable("Invalid dependence flavor");
2036 /// FindDependencies - Walk up the CFG from StartPos (which is in StartBB) and
2037 /// find local and non-local dependencies on Arg.
2038 /// TODO: Cache results?
2040 FindDependencies(DependenceKind Flavor,
2042 BasicBlock *StartBB, Instruction *StartInst,
2043 SmallPtrSet<Instruction *, 4> &DependingInstructions,
2044 SmallPtrSet<const BasicBlock *, 4> &Visited,
2045 ProvenanceAnalysis &PA) {
2046 BasicBlock::iterator StartPos = StartInst;
2048 SmallVector<std::pair<BasicBlock *, BasicBlock::iterator>, 4> Worklist;
2049 Worklist.push_back(std::make_pair(StartBB, StartPos));
2051 std::pair<BasicBlock *, BasicBlock::iterator> Pair =
2052 Worklist.pop_back_val();
2053 BasicBlock *LocalStartBB = Pair.first;
2054 BasicBlock::iterator LocalStartPos = Pair.second;
2055 BasicBlock::iterator StartBBBegin = LocalStartBB->begin();
2057 if (LocalStartPos == StartBBBegin) {
2058 pred_iterator PI(LocalStartBB), PE(LocalStartBB, false);
2060 // If we've reached the function entry, produce a null dependence.
2061 DependingInstructions.insert(0);
2063 // Add the predecessors to the worklist.
2065 BasicBlock *PredBB = *PI;
2066 if (Visited.insert(PredBB))
2067 Worklist.push_back(std::make_pair(PredBB, PredBB->end()));
2068 } while (++PI != PE);
2072 Instruction *Inst = --LocalStartPos;
2073 if (Depends(Flavor, Inst, Arg, PA)) {
2074 DependingInstructions.insert(Inst);
2078 } while (!Worklist.empty());
2080 // Determine whether the original StartBB post-dominates all of the blocks we
2081 // visited. If not, insert a sentinal indicating that most optimizations are
2083 for (SmallPtrSet<const BasicBlock *, 4>::const_iterator I = Visited.begin(),
2084 E = Visited.end(); I != E; ++I) {
2085 const BasicBlock *BB = *I;
2088 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2089 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2090 const BasicBlock *Succ = *SI;
2091 if (Succ != StartBB && !Visited.count(Succ)) {
2092 DependingInstructions.insert(reinterpret_cast<Instruction *>(-1));
2099 static bool isNullOrUndef(const Value *V) {
2100 return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
2103 static bool isNoopInstruction(const Instruction *I) {
2104 return isa<BitCastInst>(I) ||
2105 (isa<GetElementPtrInst>(I) &&
2106 cast<GetElementPtrInst>(I)->hasAllZeroIndices());
2109 /// OptimizeRetainCall - Turn objc_retain into
2110 /// objc_retainAutoreleasedReturnValue if the operand is a return value.
2112 ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) {
2113 CallSite CS(GetObjCArg(Retain));
2114 Instruction *Call = CS.getInstruction();
2116 if (Call->getParent() != Retain->getParent()) return;
2118 // Check that the call is next to the retain.
2119 BasicBlock::iterator I = Call;
2121 while (isNoopInstruction(I)) ++I;
2125 // Turn it to an objc_retainAutoreleasedReturnValue..
2128 cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent()));
2131 /// OptimizeRetainRVCall - Turn objc_retainAutoreleasedReturnValue into
2132 /// objc_retain if the operand is not a return value. Or, if it can be
2133 /// paired with an objc_autoreleaseReturnValue, delete the pair and
2136 ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
2137 // Check for the argument being from an immediately preceding call.
2138 Value *Arg = GetObjCArg(RetainRV);
2140 if (Instruction *Call = CS.getInstruction())
2141 if (Call->getParent() == RetainRV->getParent()) {
2142 BasicBlock::iterator I = Call;
2144 while (isNoopInstruction(I)) ++I;
2145 if (&*I == RetainRV)
2149 // Check for being preceded by an objc_autoreleaseReturnValue on the same
2150 // pointer. In this case, we can delete the pair.
2151 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
2153 do --I; while (I != Begin && isNoopInstruction(I));
2154 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
2155 GetObjCArg(I) == Arg) {
2158 EraseInstruction(I);
2159 EraseInstruction(RetainRV);
2164 // Turn it to a plain objc_retain.
2167 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
2171 /// OptimizeAutoreleaseRVCall - Turn objc_autoreleaseReturnValue into
2172 /// objc_autorelease if the result is not used as a return value.
2174 ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV) {
2175 // Check for a return of the pointer value.
2176 const Value *Ptr = GetObjCArg(AutoreleaseRV);
2177 SmallVector<const Value *, 2> Users;
2178 Users.push_back(Ptr);
2180 Ptr = Users.pop_back_val();
2181 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
2183 const User *I = *UI;
2184 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
2186 if (isa<BitCastInst>(I))
2189 } while (!Users.empty());
2193 cast<CallInst>(AutoreleaseRV)->
2194 setCalledFunction(getAutoreleaseCallee(F.getParent()));
2197 /// OptimizeIndividualCalls - Visit each call, one at a time, and make
2198 /// simplifications without doing any additional analysis.
2199 void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
2200 // Reset all the flags in preparation for recomputing them.
2201 UsedInThisFunction = 0;
2203 // Visit all objc_* calls in F.
2204 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2205 Instruction *Inst = &*I++;
2206 InstructionClass Class = GetBasicInstructionClass(Inst);
2211 // Delete no-op casts. These function calls have special semantics, but
2212 // the semantics are entirely implemented via lowering in the front-end,
2213 // so by the time they reach the optimizer, they are just no-op calls
2214 // which return their argument.
2216 // There are gray areas here, as the ability to cast reference-counted
2217 // pointers to raw void* and back allows code to break ARC assumptions,
2218 // however these are currently considered to be unimportant.
2222 EraseInstruction(Inst);
2225 // If the pointer-to-weak-pointer is null, it's undefined behavior.
2228 case IC_LoadWeakRetained:
2230 case IC_DestroyWeak: {
2231 CallInst *CI = cast<CallInst>(Inst);
2232 if (isNullOrUndef(CI->getArgOperand(0))) {
2233 Type *Ty = CI->getArgOperand(0)->getType();
2234 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2235 Constant::getNullValue(Ty),
2237 CI->replaceAllUsesWith(UndefValue::get(CI->getType()));
2238 CI->eraseFromParent();
2245 CallInst *CI = cast<CallInst>(Inst);
2246 if (isNullOrUndef(CI->getArgOperand(0)) ||
2247 isNullOrUndef(CI->getArgOperand(1))) {
2248 Type *Ty = CI->getArgOperand(0)->getType();
2249 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2250 Constant::getNullValue(Ty),
2252 CI->replaceAllUsesWith(UndefValue::get(CI->getType()));
2253 CI->eraseFromParent();
2259 OptimizeRetainCall(F, Inst);
2262 if (OptimizeRetainRVCall(F, Inst))
2265 case IC_AutoreleaseRV:
2266 OptimizeAutoreleaseRVCall(F, Inst);
2270 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
2271 if (IsAutorelease(Class) && Inst->use_empty()) {
2272 CallInst *Call = cast<CallInst>(Inst);
2273 const Value *Arg = Call->getArgOperand(0);
2274 Arg = FindSingleUseIdentifiedObject(Arg);
2279 // Create the declaration lazily.
2280 LLVMContext &C = Inst->getContext();
2282 CallInst::Create(getReleaseCallee(F.getParent()),
2283 Call->getArgOperand(0), "", Call);
2284 NewCall->setMetadata(ImpreciseReleaseMDKind,
2285 MDNode::get(C, ArrayRef<Value *>()));
2286 EraseInstruction(Call);
2292 // For functions which can never be passed stack arguments, add
2294 if (IsAlwaysTail(Class)) {
2296 cast<CallInst>(Inst)->setTailCall();
2299 // Set nounwind as needed.
2300 if (IsNoThrow(Class)) {
2302 cast<CallInst>(Inst)->setDoesNotThrow();
2305 if (!IsNoopOnNull(Class)) {
2306 UsedInThisFunction |= 1 << Class;
2310 const Value *Arg = GetObjCArg(Inst);
2312 // ARC calls with null are no-ops. Delete them.
2313 if (isNullOrUndef(Arg)) {
2316 EraseInstruction(Inst);
2320 // Keep track of which of retain, release, autorelease, and retain_block
2321 // are actually present in this function.
2322 UsedInThisFunction |= 1 << Class;
2324 // If Arg is a PHI, and one or more incoming values to the
2325 // PHI are null, and the call is control-equivalent to the PHI, and there
2326 // are no relevant side effects between the PHI and the call, the call
2327 // could be pushed up to just those paths with non-null incoming values.
2328 // For now, don't bother splitting critical edges for this.
2329 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
2330 Worklist.push_back(std::make_pair(Inst, Arg));
2332 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
2336 const PHINode *PN = dyn_cast<PHINode>(Arg);
2339 // Determine if the PHI has any null operands, or any incoming
2341 bool HasNull = false;
2342 bool HasCriticalEdges = false;
2343 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2345 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2346 if (isNullOrUndef(Incoming))
2348 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
2349 .getNumSuccessors() != 1) {
2350 HasCriticalEdges = true;
2354 // If we have null operands and no critical edges, optimize.
2355 if (!HasCriticalEdges && HasNull) {
2356 SmallPtrSet<Instruction *, 4> DependingInstructions;
2357 SmallPtrSet<const BasicBlock *, 4> Visited;
2359 // Check that there is nothing that cares about the reference
2360 // count between the call and the phi.
2361 FindDependencies(NeedsPositiveRetainCount, Arg,
2362 Inst->getParent(), Inst,
2363 DependingInstructions, Visited, PA);
2364 if (DependingInstructions.size() == 1 &&
2365 *DependingInstructions.begin() == PN) {
2368 // Clone the call into each predecessor that has a non-null value.
2369 CallInst *CInst = cast<CallInst>(Inst);
2370 Type *ParamTy = CInst->getArgOperand(0)->getType();
2371 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2373 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2374 if (!isNullOrUndef(Incoming)) {
2375 CallInst *Clone = cast<CallInst>(CInst->clone());
2376 Value *Op = PN->getIncomingValue(i);
2377 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
2378 if (Op->getType() != ParamTy)
2379 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
2380 Clone->setArgOperand(0, Op);
2381 Clone->insertBefore(InsertPos);
2382 Worklist.push_back(std::make_pair(Clone, Incoming));
2385 // Erase the original call.
2386 EraseInstruction(CInst);
2390 } while (!Worklist.empty());
2394 /// CheckForCFGHazards - Check for critical edges, loop boundaries, irreducible
2395 /// control flow, or other CFG structures where moving code across the edge
2396 /// would result in it being executed more.
2398 ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
2399 DenseMap<const BasicBlock *, BBState> &BBStates,
2400 BBState &MyStates) const {
2401 // If any top-down local-use or possible-dec has a succ which is earlier in
2402 // the sequence, forget it.
2403 for (BBState::ptr_const_iterator I = MyStates.top_down_ptr_begin(),
2404 E = MyStates.top_down_ptr_end(); I != E; ++I)
2405 switch (I->second.GetSeq()) {
2408 const Value *Arg = I->first;
2409 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2410 bool SomeSuccHasSame = false;
2411 bool AllSuccsHaveSame = true;
2412 PtrState &S = MyStates.getPtrTopDownState(Arg);
2413 succ_const_iterator SI(TI), SE(TI, false);
2415 // If the terminator is an invoke marked with the
2416 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
2417 // ignored, for ARC purposes.
2418 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind))
2421 for (; SI != SE; ++SI) {
2422 PtrState &SuccS = BBStates[*SI].getPtrBottomUpState(Arg);
2423 switch (SuccS.GetSeq()) {
2425 case S_CanRelease: {
2426 if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
2427 S.ClearSequenceProgress();
2431 SomeSuccHasSame = true;
2435 case S_MovableRelease:
2436 if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
2437 AllSuccsHaveSame = false;
2440 llvm_unreachable("bottom-up pointer in retain state!");
2443 // If the state at the other end of any of the successor edges
2444 // matches the current state, require all edges to match. This
2445 // guards against loops in the middle of a sequence.
2446 if (SomeSuccHasSame && !AllSuccsHaveSame)
2447 S.ClearSequenceProgress();
2450 case S_CanRelease: {
2451 const Value *Arg = I->first;
2452 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2453 bool SomeSuccHasSame = false;
2454 bool AllSuccsHaveSame = true;
2455 PtrState &S = MyStates.getPtrTopDownState(Arg);
2456 succ_const_iterator SI(TI), SE(TI, false);
2458 // If the terminator is an invoke marked with the
2459 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
2460 // ignored, for ARC purposes.
2461 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind))
2464 for (; SI != SE; ++SI) {
2465 PtrState &SuccS = BBStates[*SI].getPtrBottomUpState(Arg);
2466 switch (SuccS.GetSeq()) {
2468 if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
2469 S.ClearSequenceProgress();
2473 SomeSuccHasSame = true;
2477 case S_MovableRelease:
2479 if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
2480 AllSuccsHaveSame = false;
2483 llvm_unreachable("bottom-up pointer in retain state!");
2486 // If the state at the other end of any of the successor edges
2487 // matches the current state, require all edges to match. This
2488 // guards against loops in the middle of a sequence.
2489 if (SomeSuccHasSame && !AllSuccsHaveSame)
2490 S.ClearSequenceProgress();
2497 ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2498 DenseMap<const BasicBlock *, BBState> &BBStates,
2499 MapVector<Value *, RRInfo> &Retains) {
2500 bool NestingDetected = false;
2501 BBState &MyStates = BBStates[BB];
2503 // Merge the states from each successor to compute the initial state
2504 // for the current block.
2505 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2506 succ_const_iterator SI(TI), SE(TI, false);
2508 MyStates.SetAsExit();
2510 // If the terminator is an invoke marked with the
2511 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
2512 // ignored, for ARC purposes.
2513 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind))
2517 const BasicBlock *Succ = *SI++;
2520 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
2521 // If we haven't seen this node yet, then we've found a CFG cycle.
2522 // Be optimistic here; it's CheckForCFGHazards' job detect trouble.
2523 if (I == BBStates.end())
2525 MyStates.InitFromSucc(I->second);
2529 I = BBStates.find(Succ);
2530 if (I != BBStates.end())
2531 MyStates.MergeSucc(I->second);
2538 // Visit all the instructions, bottom-up.
2539 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2540 Instruction *Inst = llvm::prior(I);
2541 InstructionClass Class = GetInstructionClass(Inst);
2542 const Value *Arg = 0;
2546 Arg = GetObjCArg(Inst);
2548 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2550 // If we see two releases in a row on the same pointer. If so, make
2551 // a note, and we'll cicle back to revisit it after we've
2552 // hopefully eliminated the second release, which may allow us to
2553 // eliminate the first release too.
2554 // Theoretically we could implement removal of nested retain+release
2555 // pairs by making PtrState hold a stack of states, but this is
2556 // simple and avoids adding overhead for the non-nested case.
2557 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease)
2558 NestingDetected = true;
2562 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2563 S.SetSeq(ReleaseMetadata ? S_MovableRelease : S_Release);
2564 S.RRI.ReleaseMetadata = ReleaseMetadata;
2565 S.RRI.KnownSafe = S.IsKnownNested() || S.IsKnownIncremented();
2566 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2567 S.RRI.Calls.insert(Inst);
2569 S.IncrementRefCount();
2570 S.IncrementNestCount();
2573 case IC_RetainBlock:
2574 // An objc_retainBlock call with just a use may need to be kept,
2575 // because it may be copying a block from the stack to the heap.
2576 if (!IsRetainBlockOptimizable(Inst))
2581 Arg = GetObjCArg(Inst);
2583 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2584 S.DecrementRefCount();
2585 S.SetAtLeastOneRefCount();
2586 S.DecrementNestCount();
2588 switch (S.GetSeq()) {
2591 case S_MovableRelease:
2593 S.RRI.ReverseInsertPts.clear();
2596 // Don't do retain+release tracking for IC_RetainRV, because it's
2597 // better to let it remain as the first instruction after a call.
2598 if (Class != IC_RetainRV) {
2599 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2600 Retains[Inst] = S.RRI;
2602 S.ClearSequenceProgress();
2607 llvm_unreachable("bottom-up pointer in retain state!");
2611 case IC_AutoreleasepoolPop:
2612 // Conservatively, clear MyStates for all known pointers.
2613 MyStates.clearBottomUpPointers();
2615 case IC_AutoreleasepoolPush:
2617 // These are irrelevant.
2623 // Consider any other possible effects of this instruction on each
2624 // pointer being tracked.
2625 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
2626 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
2627 const Value *Ptr = MI->first;
2629 continue; // Handled above.
2630 PtrState &S = MI->second;
2631 Sequence Seq = S.GetSeq();
2633 // Check for possible releases.
2634 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2635 S.DecrementRefCount();
2638 S.SetSeq(S_CanRelease);
2642 case S_MovableRelease:
2647 llvm_unreachable("bottom-up pointer in retain state!");
2651 // Check for possible direct uses.
2654 case S_MovableRelease:
2655 if (CanUse(Inst, Ptr, PA, Class)) {
2656 assert(S.RRI.ReverseInsertPts.empty());
2657 S.RRI.ReverseInsertPts.insert(Inst);
2659 } else if (Seq == S_Release &&
2660 (Class == IC_User || Class == IC_CallOrUser)) {
2661 // Non-movable releases depend on any possible objc pointer use.
2663 assert(S.RRI.ReverseInsertPts.empty());
2664 S.RRI.ReverseInsertPts.insert(Inst);
2668 if (CanUse(Inst, Ptr, PA, Class))
2676 llvm_unreachable("bottom-up pointer in retain state!");
2681 return NestingDetected;
2685 ObjCARCOpt::VisitTopDown(BasicBlock *BB,
2686 DenseMap<const BasicBlock *, BBState> &BBStates,
2687 DenseMap<Value *, RRInfo> &Releases) {
2688 bool NestingDetected = false;
2689 BBState &MyStates = BBStates[BB];
2691 // Merge the states from each predecessor to compute the initial state
2692 // for the current block.
2693 const_pred_iterator PI(BB), PE(BB, false);
2695 MyStates.SetAsEntry();
2698 unsigned OperandNo = PI.getOperandNo();
2699 const Use &Us = PI.getUse();
2702 // Skip invoke unwind edges on invoke instructions marked with
2703 // clang.arc.no_objc_arc_exceptions.
2704 if (const InvokeInst *II = dyn_cast<InvokeInst>(Us.getUser()))
2705 if (OperandNo == II->getNumArgOperands() + 2 &&
2706 II->getMetadata(NoObjCARCExceptionsMDKind))
2709 const BasicBlock *Pred = cast<TerminatorInst>(Us.getUser())->getParent();
2712 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
2713 // If we haven't seen this node yet, then we've found a CFG cycle.
2714 // Be optimistic here; it's CheckForCFGHazards' job detect trouble.
2715 if (I == BBStates.end() || !I->second.isVisitedTopDown())
2717 MyStates.InitFromPred(I->second);
2721 I = BBStates.find(Pred);
2722 if (I != BBStates.end() && I->second.isVisitedTopDown())
2723 MyStates.MergePred(I->second);
2729 // Visit all the instructions, top-down.
2730 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2731 Instruction *Inst = I;
2732 InstructionClass Class = GetInstructionClass(Inst);
2733 const Value *Arg = 0;
2736 case IC_RetainBlock:
2737 // An objc_retainBlock call with just a use may need to be kept,
2738 // because it may be copying a block from the stack to the heap.
2739 if (!IsRetainBlockOptimizable(Inst))
2744 Arg = GetObjCArg(Inst);
2746 PtrState &S = MyStates.getPtrTopDownState(Arg);
2748 // Don't do retain+release tracking for IC_RetainRV, because it's
2749 // better to let it remain as the first instruction after a call.
2750 if (Class != IC_RetainRV) {
2751 // If we see two retains in a row on the same pointer. If so, make
2752 // a note, and we'll cicle back to revisit it after we've
2753 // hopefully eliminated the second retain, which may allow us to
2754 // eliminate the first retain too.
2755 // Theoretically we could implement removal of nested retain+release
2756 // pairs by making PtrState hold a stack of states, but this is
2757 // simple and avoids adding overhead for the non-nested case.
2758 if (S.GetSeq() == S_Retain)
2759 NestingDetected = true;
2763 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2764 // Don't check S.IsKnownIncremented() here because it's not
2766 S.RRI.KnownSafe = S.IsKnownNested();
2767 S.RRI.Calls.insert(Inst);
2770 S.SetAtLeastOneRefCount();
2771 S.IncrementRefCount();
2772 S.IncrementNestCount();
2776 Arg = GetObjCArg(Inst);
2778 PtrState &S = MyStates.getPtrTopDownState(Arg);
2779 S.DecrementRefCount();
2780 S.DecrementNestCount();
2782 switch (S.GetSeq()) {
2785 S.RRI.ReverseInsertPts.clear();
2788 S.RRI.ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2789 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2790 Releases[Inst] = S.RRI;
2791 S.ClearSequenceProgress();
2797 case S_MovableRelease:
2798 llvm_unreachable("top-down pointer in release state!");
2802 case IC_AutoreleasepoolPop:
2803 // Conservatively, clear MyStates for all known pointers.
2804 MyStates.clearTopDownPointers();
2806 case IC_AutoreleasepoolPush:
2808 // These are irrelevant.
2814 // Consider any other possible effects of this instruction on each
2815 // pointer being tracked.
2816 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
2817 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
2818 const Value *Ptr = MI->first;
2820 continue; // Handled above.
2821 PtrState &S = MI->second;
2822 Sequence Seq = S.GetSeq();
2824 // Check for possible releases.
2825 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2826 S.DecrementRefCount();
2829 S.SetSeq(S_CanRelease);
2830 assert(S.RRI.ReverseInsertPts.empty());
2831 S.RRI.ReverseInsertPts.insert(Inst);
2833 // One call can't cause a transition from S_Retain to S_CanRelease
2834 // and S_CanRelease to S_Use. If we've made the first transition,
2843 case S_MovableRelease:
2844 llvm_unreachable("top-down pointer in release state!");
2848 // Check for possible direct uses.
2851 if (CanUse(Inst, Ptr, PA, Class))
2860 case S_MovableRelease:
2861 llvm_unreachable("top-down pointer in release state!");
2866 CheckForCFGHazards(BB, BBStates, MyStates);
2867 return NestingDetected;
2871 ComputePostOrders(Function &F,
2872 SmallVectorImpl<BasicBlock *> &PostOrder,
2873 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder) {
2874 /// Backedges - Backedges detected in the DFS. These edges will be
2875 /// ignored in the reverse-CFG DFS, so that loops with multiple exits will be
2876 /// traversed in the desired order.
2877 DenseSet<std::pair<BasicBlock *, BasicBlock *> > Backedges;
2879 /// Visited - The visited set, for doing DFS walks.
2880 SmallPtrSet<BasicBlock *, 16> Visited;
2882 // Do DFS, computing the PostOrder.
2883 SmallPtrSet<BasicBlock *, 16> OnStack;
2884 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
2885 BasicBlock *EntryBB = &F.getEntryBlock();
2886 SuccStack.push_back(std::make_pair(EntryBB, succ_begin(EntryBB)));
2887 Visited.insert(EntryBB);
2888 OnStack.insert(EntryBB);
2891 TerminatorInst *TI = cast<TerminatorInst>(&SuccStack.back().first->back());
2892 succ_iterator End = succ_iterator(TI, true);
2893 while (SuccStack.back().second != End) {
2894 BasicBlock *BB = *SuccStack.back().second++;
2895 if (Visited.insert(BB)) {
2896 SuccStack.push_back(std::make_pair(BB, succ_begin(BB)));
2900 if (OnStack.count(BB))
2901 Backedges.insert(std::make_pair(SuccStack.back().first, BB));
2903 OnStack.erase(SuccStack.back().first);
2904 PostOrder.push_back(SuccStack.pop_back_val().first);
2905 } while (!SuccStack.empty());
2909 // Compute the exits, which are the starting points for reverse-CFG DFS.
2910 SmallVector<BasicBlock *, 4> Exits;
2911 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
2913 if (cast<TerminatorInst>(&BB->back())->getNumSuccessors() == 0)
2914 Exits.push_back(BB);
2917 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
2918 SmallVector<std::pair<BasicBlock *, pred_iterator>, 16> PredStack;
2919 for (SmallVectorImpl<BasicBlock *>::iterator I = Exits.begin(), E = Exits.end();
2921 BasicBlock *ExitBB = *I;
2922 PredStack.push_back(std::make_pair(ExitBB, pred_begin(ExitBB)));
2923 Visited.insert(ExitBB);
2924 while (!PredStack.empty()) {
2925 reverse_dfs_next_succ:
2926 pred_iterator End = pred_end(PredStack.back().first);
2927 while (PredStack.back().second != End) {
2928 BasicBlock *BB = *PredStack.back().second++;
2929 // Skip backedges detected in the forward-CFG DFS.
2930 if (Backedges.count(std::make_pair(BB, PredStack.back().first)))
2932 if (Visited.insert(BB)) {
2933 PredStack.push_back(std::make_pair(BB, pred_begin(BB)));
2934 goto reverse_dfs_next_succ;
2937 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
2942 // Visit - Visit the function both top-down and bottom-up.
2944 ObjCARCOpt::Visit(Function &F,
2945 DenseMap<const BasicBlock *, BBState> &BBStates,
2946 MapVector<Value *, RRInfo> &Retains,
2947 DenseMap<Value *, RRInfo> &Releases) {
2949 // Use reverse-postorder traversals, because we magically know that loops
2950 // will be well behaved, i.e. they won't repeatedly call retain on a single
2951 // pointer without doing a release. We can't use the ReversePostOrderTraversal
2952 // class here because we want the reverse-CFG postorder to consider each
2953 // function exit point, and we want to ignore selected cycle edges.
2954 SmallVector<BasicBlock *, 16> PostOrder;
2955 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
2956 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder);
2958 // Use reverse-postorder on the reverse CFG for bottom-up.
2959 bool BottomUpNestingDetected = false;
2960 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2961 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
2963 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
2965 // Use reverse-postorder for top-down.
2966 bool TopDownNestingDetected = false;
2967 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2968 PostOrder.rbegin(), E = PostOrder.rend();
2970 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
2972 return TopDownNestingDetected && BottomUpNestingDetected;
2975 /// MoveCalls - Move the calls in RetainsToMove and ReleasesToMove.
2976 void ObjCARCOpt::MoveCalls(Value *Arg,
2977 RRInfo &RetainsToMove,
2978 RRInfo &ReleasesToMove,
2979 MapVector<Value *, RRInfo> &Retains,
2980 DenseMap<Value *, RRInfo> &Releases,
2981 SmallVectorImpl<Instruction *> &DeadInsts,
2983 Type *ArgTy = Arg->getType();
2984 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
2986 // Insert the new retain and release calls.
2987 for (SmallPtrSet<Instruction *, 2>::const_iterator
2988 PI = ReleasesToMove.ReverseInsertPts.begin(),
2989 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2990 Instruction *InsertPt = *PI;
2991 Value *MyArg = ArgTy == ParamTy ? Arg :
2992 new BitCastInst(Arg, ParamTy, "", InsertPt);
2994 CallInst::Create(RetainsToMove.IsRetainBlock ?
2995 getRetainBlockCallee(M) : getRetainCallee(M),
2996 MyArg, "", InsertPt);
2997 Call->setDoesNotThrow();
2998 if (RetainsToMove.IsRetainBlock)
2999 Call->setMetadata(CopyOnEscapeMDKind,
3000 MDNode::get(M->getContext(), ArrayRef<Value *>()));
3002 Call->setTailCall();
3004 for (SmallPtrSet<Instruction *, 2>::const_iterator
3005 PI = RetainsToMove.ReverseInsertPts.begin(),
3006 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
3007 Instruction *LastUse = *PI;
3008 Instruction *InsertPts[] = { 0, 0, 0 };
3009 if (InvokeInst *II = dyn_cast<InvokeInst>(LastUse)) {
3010 // We can't insert code immediately after an invoke instruction, so
3011 // insert code at the beginning of both successor blocks instead.
3012 // The invoke's return value isn't available in the unwind block,
3013 // but our releases will never depend on it, because they must be
3014 // paired with retains from before the invoke.
3015 InsertPts[0] = II->getNormalDest()->getFirstInsertionPt();
3016 InsertPts[1] = II->getUnwindDest()->getFirstInsertionPt();
3018 // Insert code immediately after the last use.
3019 InsertPts[0] = llvm::next(BasicBlock::iterator(LastUse));
3022 for (Instruction **I = InsertPts; *I; ++I) {
3023 Instruction *InsertPt = *I;
3024 Value *MyArg = ArgTy == ParamTy ? Arg :
3025 new BitCastInst(Arg, ParamTy, "", InsertPt);
3026 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
3028 // Attach a clang.imprecise_release metadata tag, if appropriate.
3029 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
3030 Call->setMetadata(ImpreciseReleaseMDKind, M);
3031 Call->setDoesNotThrow();
3032 if (ReleasesToMove.IsTailCallRelease)
3033 Call->setTailCall();
3037 // Delete the original retain and release calls.
3038 for (SmallPtrSet<Instruction *, 2>::const_iterator
3039 AI = RetainsToMove.Calls.begin(),
3040 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
3041 Instruction *OrigRetain = *AI;
3042 Retains.blot(OrigRetain);
3043 DeadInsts.push_back(OrigRetain);
3045 for (SmallPtrSet<Instruction *, 2>::const_iterator
3046 AI = ReleasesToMove.Calls.begin(),
3047 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
3048 Instruction *OrigRelease = *AI;
3049 Releases.erase(OrigRelease);
3050 DeadInsts.push_back(OrigRelease);
3055 ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
3057 MapVector<Value *, RRInfo> &Retains,
3058 DenseMap<Value *, RRInfo> &Releases,
3060 bool AnyPairsCompletelyEliminated = false;
3061 RRInfo RetainsToMove;
3062 RRInfo ReleasesToMove;
3063 SmallVector<Instruction *, 4> NewRetains;
3064 SmallVector<Instruction *, 4> NewReleases;
3065 SmallVector<Instruction *, 8> DeadInsts;
3067 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
3068 E = Retains.end(); I != E; ++I) {
3069 Value *V = I->first;
3070 if (!V) continue; // blotted
3072 Instruction *Retain = cast<Instruction>(V);
3073 Value *Arg = GetObjCArg(Retain);
3075 // If the object being released is in static or stack storage, we know it's
3076 // not being managed by ObjC reference counting, so we can delete pairs
3077 // regardless of what possible decrements or uses lie between them.
3078 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
3080 // A constant pointer can't be pointing to an object on the heap. It may
3081 // be reference-counted, but it won't be deleted.
3082 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
3083 if (const GlobalVariable *GV =
3084 dyn_cast<GlobalVariable>(
3085 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
3086 if (GV->isConstant())
3089 // If a pair happens in a region where it is known that the reference count
3090 // is already incremented, we can similarly ignore possible decrements.
3091 bool KnownSafeTD = true, KnownSafeBU = true;
3093 // Connect the dots between the top-down-collected RetainsToMove and
3094 // bottom-up-collected ReleasesToMove to form sets of related calls.
3095 // This is an iterative process so that we connect multiple releases
3096 // to multiple retains if needed.
3097 unsigned OldDelta = 0;
3098 unsigned NewDelta = 0;
3099 unsigned OldCount = 0;
3100 unsigned NewCount = 0;
3101 bool FirstRelease = true;
3102 bool FirstRetain = true;
3103 NewRetains.push_back(Retain);
3105 for (SmallVectorImpl<Instruction *>::const_iterator
3106 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
3107 Instruction *NewRetain = *NI;
3108 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
3109 assert(It != Retains.end());
3110 const RRInfo &NewRetainRRI = It->second;
3111 KnownSafeTD &= NewRetainRRI.KnownSafe;
3112 for (SmallPtrSet<Instruction *, 2>::const_iterator
3113 LI = NewRetainRRI.Calls.begin(),
3114 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
3115 Instruction *NewRetainRelease = *LI;
3116 DenseMap<Value *, RRInfo>::const_iterator Jt =
3117 Releases.find(NewRetainRelease);
3118 if (Jt == Releases.end())
3120 const RRInfo &NewRetainReleaseRRI = Jt->second;
3121 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
3122 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
3124 BBStates[NewRetainRelease->getParent()].GetAllPathCount();
3126 // Merge the ReleaseMetadata and IsTailCallRelease values.
3128 ReleasesToMove.ReleaseMetadata =
3129 NewRetainReleaseRRI.ReleaseMetadata;
3130 ReleasesToMove.IsTailCallRelease =
3131 NewRetainReleaseRRI.IsTailCallRelease;
3132 FirstRelease = false;
3134 if (ReleasesToMove.ReleaseMetadata !=
3135 NewRetainReleaseRRI.ReleaseMetadata)
3136 ReleasesToMove.ReleaseMetadata = 0;
3137 if (ReleasesToMove.IsTailCallRelease !=
3138 NewRetainReleaseRRI.IsTailCallRelease)
3139 ReleasesToMove.IsTailCallRelease = false;
3142 // Collect the optimal insertion points.
3144 for (SmallPtrSet<Instruction *, 2>::const_iterator
3145 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
3146 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
3148 Instruction *RIP = *RI;
3149 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
3150 NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
3152 NewReleases.push_back(NewRetainRelease);
3157 if (NewReleases.empty()) break;
3159 // Back the other way.
3160 for (SmallVectorImpl<Instruction *>::const_iterator
3161 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
3162 Instruction *NewRelease = *NI;
3163 DenseMap<Value *, RRInfo>::const_iterator It =
3164 Releases.find(NewRelease);
3165 assert(It != Releases.end());
3166 const RRInfo &NewReleaseRRI = It->second;
3167 KnownSafeBU &= NewReleaseRRI.KnownSafe;
3168 for (SmallPtrSet<Instruction *, 2>::const_iterator
3169 LI = NewReleaseRRI.Calls.begin(),
3170 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
3171 Instruction *NewReleaseRetain = *LI;
3172 MapVector<Value *, RRInfo>::const_iterator Jt =
3173 Retains.find(NewReleaseRetain);
3174 if (Jt == Retains.end())
3176 const RRInfo &NewReleaseRetainRRI = Jt->second;
3177 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
3178 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
3179 unsigned PathCount =
3180 BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
3181 OldDelta += PathCount;
3182 OldCount += PathCount;
3184 // Merge the IsRetainBlock values.
3186 RetainsToMove.IsRetainBlock = NewReleaseRetainRRI.IsRetainBlock;
3187 FirstRetain = false;
3188 } else if (ReleasesToMove.IsRetainBlock !=
3189 NewReleaseRetainRRI.IsRetainBlock)
3190 // It's not possible to merge the sequences if one uses
3191 // objc_retain and the other uses objc_retainBlock.
3194 // Collect the optimal insertion points.
3196 for (SmallPtrSet<Instruction *, 2>::const_iterator
3197 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
3198 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
3200 Instruction *RIP = *RI;
3201 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
3202 PathCount = BBStates[RIP->getParent()].GetAllPathCount();
3203 NewDelta += PathCount;
3204 NewCount += PathCount;
3207 NewRetains.push_back(NewReleaseRetain);
3211 NewReleases.clear();
3212 if (NewRetains.empty()) break;
3215 // If the pointer is known incremented or nested, we can safely delete the
3216 // pair regardless of what's between them.
3217 if (KnownSafeTD || KnownSafeBU) {
3218 RetainsToMove.ReverseInsertPts.clear();
3219 ReleasesToMove.ReverseInsertPts.clear();
3222 // Determine whether the new insertion points we computed preserve the
3223 // balance of retain and release calls through the program.
3224 // TODO: If the fully aggressive solution isn't valid, try to find a
3225 // less aggressive solution which is.
3230 // Determine whether the original call points are balanced in the retain and
3231 // release calls through the program. If not, conservatively don't touch
3233 // TODO: It's theoretically possible to do code motion in this case, as
3234 // long as the existing imbalances are maintained.
3238 // Ok, everything checks out and we're all set. Let's move some code!
3240 AnyPairsCompletelyEliminated = NewCount == 0;
3241 NumRRs += OldCount - NewCount;
3242 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
3243 Retains, Releases, DeadInsts, M);
3246 NewReleases.clear();
3248 RetainsToMove.clear();
3249 ReleasesToMove.clear();
3252 // Now that we're done moving everything, we can delete the newly dead
3253 // instructions, as we no longer need them as insert points.
3254 while (!DeadInsts.empty())
3255 EraseInstruction(DeadInsts.pop_back_val());
3257 return AnyPairsCompletelyEliminated;
3260 /// OptimizeWeakCalls - Weak pointer optimizations.
3261 void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
3262 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
3263 // itself because it uses AliasAnalysis and we need to do provenance
3265 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3266 Instruction *Inst = &*I++;
3267 InstructionClass Class = GetBasicInstructionClass(Inst);
3268 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
3271 // Delete objc_loadWeak calls with no users.
3272 if (Class == IC_LoadWeak && Inst->use_empty()) {
3273 Inst->eraseFromParent();
3277 // TODO: For now, just look for an earlier available version of this value
3278 // within the same block. Theoretically, we could do memdep-style non-local
3279 // analysis too, but that would want caching. A better approach would be to
3280 // use the technique that EarlyCSE uses.
3281 inst_iterator Current = llvm::prior(I);
3282 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
3283 for (BasicBlock::iterator B = CurrentBB->begin(),
3284 J = Current.getInstructionIterator();
3286 Instruction *EarlierInst = &*llvm::prior(J);
3287 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
3288 switch (EarlierClass) {
3290 case IC_LoadWeakRetained: {
3291 // If this is loading from the same pointer, replace this load's value
3293 CallInst *Call = cast<CallInst>(Inst);
3294 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3295 Value *Arg = Call->getArgOperand(0);
3296 Value *EarlierArg = EarlierCall->getArgOperand(0);
3297 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3298 case AliasAnalysis::MustAlias:
3300 // If the load has a builtin retain, insert a plain retain for it.
3301 if (Class == IC_LoadWeakRetained) {
3303 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3307 // Zap the fully redundant load.
3308 Call->replaceAllUsesWith(EarlierCall);
3309 Call->eraseFromParent();
3311 case AliasAnalysis::MayAlias:
3312 case AliasAnalysis::PartialAlias:
3314 case AliasAnalysis::NoAlias:
3321 // If this is storing to the same pointer and has the same size etc.
3322 // replace this load's value with the stored value.
3323 CallInst *Call = cast<CallInst>(Inst);
3324 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3325 Value *Arg = Call->getArgOperand(0);
3326 Value *EarlierArg = EarlierCall->getArgOperand(0);
3327 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3328 case AliasAnalysis::MustAlias:
3330 // If the load has a builtin retain, insert a plain retain for it.
3331 if (Class == IC_LoadWeakRetained) {
3333 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3337 // Zap the fully redundant load.
3338 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
3339 Call->eraseFromParent();
3341 case AliasAnalysis::MayAlias:
3342 case AliasAnalysis::PartialAlias:
3344 case AliasAnalysis::NoAlias:
3351 // TOOD: Grab the copied value.
3353 case IC_AutoreleasepoolPush:
3356 // Weak pointers are only modified through the weak entry points
3357 // (and arbitrary calls, which could call the weak entry points).
3360 // Anything else could modify the weak pointer.
3367 // Then, for each destroyWeak with an alloca operand, check to see if
3368 // the alloca and all its users can be zapped.
3369 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3370 Instruction *Inst = &*I++;
3371 InstructionClass Class = GetBasicInstructionClass(Inst);
3372 if (Class != IC_DestroyWeak)
3375 CallInst *Call = cast<CallInst>(Inst);
3376 Value *Arg = Call->getArgOperand(0);
3377 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
3378 for (Value::use_iterator UI = Alloca->use_begin(),
3379 UE = Alloca->use_end(); UI != UE; ++UI) {
3380 Instruction *UserInst = cast<Instruction>(*UI);
3381 switch (GetBasicInstructionClass(UserInst)) {
3384 case IC_DestroyWeak:
3391 for (Value::use_iterator UI = Alloca->use_begin(),
3392 UE = Alloca->use_end(); UI != UE; ) {
3393 CallInst *UserInst = cast<CallInst>(*UI++);
3394 if (!UserInst->use_empty())
3395 UserInst->replaceAllUsesWith(UserInst->getArgOperand(0));
3396 UserInst->eraseFromParent();
3398 Alloca->eraseFromParent();
3404 /// OptimizeSequences - Identify program paths which execute sequences of
3405 /// retains and releases which can be eliminated.
3406 bool ObjCARCOpt::OptimizeSequences(Function &F) {
3407 /// Releases, Retains - These are used to store the results of the main flow
3408 /// analysis. These use Value* as the key instead of Instruction* so that the
3409 /// map stays valid when we get around to rewriting code and calls get
3410 /// replaced by arguments.
3411 DenseMap<Value *, RRInfo> Releases;
3412 MapVector<Value *, RRInfo> Retains;
3414 /// BBStates, This is used during the traversal of the function to track the
3415 /// states for each identified object at each block.
3416 DenseMap<const BasicBlock *, BBState> BBStates;
3418 // Analyze the CFG of the function, and all instructions.
3419 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
3422 return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) &&
3426 /// OptimizeReturns - Look for this pattern:
3428 /// %call = call i8* @something(...)
3429 /// %2 = call i8* @objc_retain(i8* %call)
3430 /// %3 = call i8* @objc_autorelease(i8* %2)
3433 /// And delete the retain and autorelease.
3435 /// Otherwise if it's just this:
3437 /// %3 = call i8* @objc_autorelease(i8* %2)
3440 /// convert the autorelease to autoreleaseRV.
3441 void ObjCARCOpt::OptimizeReturns(Function &F) {
3442 if (!F.getReturnType()->isPointerTy())
3445 SmallPtrSet<Instruction *, 4> DependingInstructions;
3446 SmallPtrSet<const BasicBlock *, 4> Visited;
3447 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3448 BasicBlock *BB = FI;
3449 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
3452 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
3453 FindDependencies(NeedsPositiveRetainCount, Arg,
3454 BB, Ret, DependingInstructions, Visited, PA);
3455 if (DependingInstructions.size() != 1)
3459 CallInst *Autorelease =
3460 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3463 InstructionClass AutoreleaseClass =
3464 GetBasicInstructionClass(Autorelease);
3465 if (!IsAutorelease(AutoreleaseClass))
3467 if (GetObjCArg(Autorelease) != Arg)
3470 DependingInstructions.clear();
3473 // Check that there is nothing that can affect the reference
3474 // count between the autorelease and the retain.
3475 FindDependencies(CanChangeRetainCount, Arg,
3476 BB, Autorelease, DependingInstructions, Visited, PA);
3477 if (DependingInstructions.size() != 1)
3482 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3484 // Check that we found a retain with the same argument.
3486 !IsRetain(GetBasicInstructionClass(Retain)) ||
3487 GetObjCArg(Retain) != Arg)
3490 DependingInstructions.clear();
3493 // Convert the autorelease to an autoreleaseRV, since it's
3494 // returning the value.
3495 if (AutoreleaseClass == IC_Autorelease) {
3496 Autorelease->setCalledFunction(getAutoreleaseRVCallee(F.getParent()));
3497 AutoreleaseClass = IC_AutoreleaseRV;
3500 // Check that there is nothing that can affect the reference
3501 // count between the retain and the call.
3502 // Note that Retain need not be in BB.
3503 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
3504 DependingInstructions, Visited, PA);
3505 if (DependingInstructions.size() != 1)
3510 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3512 // Check that the pointer is the return value of the call.
3513 if (!Call || Arg != Call)
3516 // Check that the call is a regular call.
3517 InstructionClass Class = GetBasicInstructionClass(Call);
3518 if (Class != IC_CallOrUser && Class != IC_Call)
3521 // If so, we can zap the retain and autorelease.
3524 EraseInstruction(Retain);
3525 EraseInstruction(Autorelease);
3531 DependingInstructions.clear();
3536 bool ObjCARCOpt::doInitialization(Module &M) {
3540 Run = ModuleHasARC(M);
3544 // Identify the imprecise release metadata kind.
3545 ImpreciseReleaseMDKind =
3546 M.getContext().getMDKindID("clang.imprecise_release");
3547 CopyOnEscapeMDKind =
3548 M.getContext().getMDKindID("clang.arc.copy_on_escape");
3549 NoObjCARCExceptionsMDKind =
3550 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
3552 // Intuitively, objc_retain and others are nocapture, however in practice
3553 // they are not, because they return their argument value. And objc_release
3554 // calls finalizers.
3556 // These are initialized lazily.
3558 AutoreleaseRVCallee = 0;
3561 RetainBlockCallee = 0;
3562 AutoreleaseCallee = 0;
3567 bool ObjCARCOpt::runOnFunction(Function &F) {
3571 // If nothing in the Module uses ARC, don't do anything.
3577 PA.setAA(&getAnalysis<AliasAnalysis>());
3579 // This pass performs several distinct transformations. As a compile-time aid
3580 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3581 // library functions aren't declared.
3583 // Preliminary optimizations. This also computs UsedInThisFunction.
3584 OptimizeIndividualCalls(F);
3586 // Optimizations for weak pointers.
3587 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3588 (1 << IC_LoadWeakRetained) |
3589 (1 << IC_StoreWeak) |
3590 (1 << IC_InitWeak) |
3591 (1 << IC_CopyWeak) |
3592 (1 << IC_MoveWeak) |
3593 (1 << IC_DestroyWeak)))
3594 OptimizeWeakCalls(F);
3596 // Optimizations for retain+release pairs.
3597 if (UsedInThisFunction & ((1 << IC_Retain) |
3598 (1 << IC_RetainRV) |
3599 (1 << IC_RetainBlock)))
3600 if (UsedInThisFunction & (1 << IC_Release))
3601 // Run OptimizeSequences until it either stops making changes or
3602 // no retain+release pair nesting is detected.
3603 while (OptimizeSequences(F)) {}
3605 // Optimizations if objc_autorelease is used.
3606 if (UsedInThisFunction &
3607 ((1 << IC_Autorelease) | (1 << IC_AutoreleaseRV)))
3613 void ObjCARCOpt::releaseMemory() {
3617 //===----------------------------------------------------------------------===//
3619 //===----------------------------------------------------------------------===//
3621 // TODO: ObjCARCContract could insert PHI nodes when uses aren't
3622 // dominated by single calls.
3624 #include "llvm/Operator.h"
3625 #include "llvm/InlineAsm.h"
3626 #include "llvm/Analysis/Dominators.h"
3628 STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed");
3631 /// ObjCARCContract - Late ARC optimizations. These change the IR in a way
3632 /// that makes it difficult to be analyzed by ObjCARCOpt, so it's run late.
3633 class ObjCARCContract : public FunctionPass {
3637 ProvenanceAnalysis PA;
3639 /// Run - A flag indicating whether this optimization pass should run.
3642 /// StoreStrongCallee, etc. - Declarations for ObjC runtime
3643 /// functions, for use in creating calls to them. These are initialized
3644 /// lazily to avoid cluttering up the Module with unused declarations.
3645 Constant *StoreStrongCallee,
3646 *RetainAutoreleaseCallee, *RetainAutoreleaseRVCallee;
3648 /// RetainRVMarker - The inline asm string to insert between calls and
3649 /// RetainRV calls to make the optimization work on targets which need it.
3650 const MDString *RetainRVMarker;
3652 /// StoreStrongCalls - The set of inserted objc_storeStrong calls. If
3653 /// at the end of walking the function we have found no alloca
3654 /// instructions, these calls can be marked "tail".
3655 DenseSet<CallInst *> StoreStrongCalls;
3657 Constant *getStoreStrongCallee(Module *M);
3658 Constant *getRetainAutoreleaseCallee(Module *M);
3659 Constant *getRetainAutoreleaseRVCallee(Module *M);
3661 bool ContractAutorelease(Function &F, Instruction *Autorelease,
3662 InstructionClass Class,
3663 SmallPtrSet<Instruction *, 4>
3664 &DependingInstructions,
3665 SmallPtrSet<const BasicBlock *, 4>
3668 void ContractRelease(Instruction *Release,
3669 inst_iterator &Iter);
3671 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
3672 virtual bool doInitialization(Module &M);
3673 virtual bool runOnFunction(Function &F);
3677 ObjCARCContract() : FunctionPass(ID) {
3678 initializeObjCARCContractPass(*PassRegistry::getPassRegistry());
3683 char ObjCARCContract::ID = 0;
3684 INITIALIZE_PASS_BEGIN(ObjCARCContract,
3685 "objc-arc-contract", "ObjC ARC contraction", false, false)
3686 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3687 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
3688 INITIALIZE_PASS_END(ObjCARCContract,
3689 "objc-arc-contract", "ObjC ARC contraction", false, false)
3691 Pass *llvm::createObjCARCContractPass() {
3692 return new ObjCARCContract();
3695 void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const {
3696 AU.addRequired<AliasAnalysis>();
3697 AU.addRequired<DominatorTree>();
3698 AU.setPreservesCFG();
3701 Constant *ObjCARCContract::getStoreStrongCallee(Module *M) {
3702 if (!StoreStrongCallee) {
3703 LLVMContext &C = M->getContext();
3704 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3705 Type *I8XX = PointerType::getUnqual(I8X);
3706 std::vector<Type *> Params;
3707 Params.push_back(I8XX);
3708 Params.push_back(I8X);
3710 AttrListPtr Attributes;
3711 Attributes.addAttr(~0u, Attribute::NoUnwind);
3712 Attributes.addAttr(1, Attribute::NoCapture);
3715 M->getOrInsertFunction(
3717 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
3720 return StoreStrongCallee;
3723 Constant *ObjCARCContract::getRetainAutoreleaseCallee(Module *M) {
3724 if (!RetainAutoreleaseCallee) {
3725 LLVMContext &C = M->getContext();
3726 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3727 std::vector<Type *> Params;
3728 Params.push_back(I8X);
3730 FunctionType::get(I8X, Params, /*isVarArg=*/false);
3731 AttrListPtr Attributes;
3732 Attributes.addAttr(~0u, Attribute::NoUnwind);
3733 RetainAutoreleaseCallee =
3734 M->getOrInsertFunction("objc_retainAutorelease", FTy, Attributes);
3736 return RetainAutoreleaseCallee;
3739 Constant *ObjCARCContract::getRetainAutoreleaseRVCallee(Module *M) {
3740 if (!RetainAutoreleaseRVCallee) {
3741 LLVMContext &C = M->getContext();
3742 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3743 std::vector<Type *> Params;
3744 Params.push_back(I8X);
3746 FunctionType::get(I8X, Params, /*isVarArg=*/false);
3747 AttrListPtr Attributes;
3748 Attributes.addAttr(~0u, Attribute::NoUnwind);
3749 RetainAutoreleaseRVCallee =
3750 M->getOrInsertFunction("objc_retainAutoreleaseReturnValue", FTy,
3753 return RetainAutoreleaseRVCallee;
3756 /// ContractAutorelease - Merge an autorelease with a retain into a fused
3759 ObjCARCContract::ContractAutorelease(Function &F, Instruction *Autorelease,
3760 InstructionClass Class,
3761 SmallPtrSet<Instruction *, 4>
3762 &DependingInstructions,
3763 SmallPtrSet<const BasicBlock *, 4>
3765 const Value *Arg = GetObjCArg(Autorelease);
3767 // Check that there are no instructions between the retain and the autorelease
3768 // (such as an autorelease_pop) which may change the count.
3769 CallInst *Retain = 0;
3770 if (Class == IC_AutoreleaseRV)
3771 FindDependencies(RetainAutoreleaseRVDep, Arg,
3772 Autorelease->getParent(), Autorelease,
3773 DependingInstructions, Visited, PA);
3775 FindDependencies(RetainAutoreleaseDep, Arg,
3776 Autorelease->getParent(), Autorelease,
3777 DependingInstructions, Visited, PA);
3780 if (DependingInstructions.size() != 1) {
3781 DependingInstructions.clear();
3785 Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3786 DependingInstructions.clear();
3789 GetBasicInstructionClass(Retain) != IC_Retain ||
3790 GetObjCArg(Retain) != Arg)
3796 if (Class == IC_AutoreleaseRV)
3797 Retain->setCalledFunction(getRetainAutoreleaseRVCallee(F.getParent()));
3799 Retain->setCalledFunction(getRetainAutoreleaseCallee(F.getParent()));
3801 EraseInstruction(Autorelease);
3805 /// ContractRelease - Attempt to merge an objc_release with a store, load, and
3806 /// objc_retain to form an objc_storeStrong. This can be a little tricky because
3807 /// the instructions don't always appear in order, and there may be unrelated
3808 /// intervening instructions.
3809 void ObjCARCContract::ContractRelease(Instruction *Release,
3810 inst_iterator &Iter) {
3811 LoadInst *Load = dyn_cast<LoadInst>(GetObjCArg(Release));
3812 if (!Load || !Load->isSimple()) return;
3814 // For now, require everything to be in one basic block.
3815 BasicBlock *BB = Release->getParent();
3816 if (Load->getParent() != BB) return;
3818 // Walk down to find the store.
3819 BasicBlock::iterator I = Load, End = BB->end();
3821 AliasAnalysis::Location Loc = AA->getLocation(Load);
3824 IsRetain(GetBasicInstructionClass(I)) ||
3825 !(AA->getModRefInfo(I, Loc) & AliasAnalysis::Mod)))
3827 StoreInst *Store = dyn_cast<StoreInst>(I);
3828 if (!Store || !Store->isSimple()) return;
3829 if (Store->getPointerOperand() != Loc.Ptr) return;
3831 Value *New = StripPointerCastsAndObjCCalls(Store->getValueOperand());
3833 // Walk up to find the retain.
3835 BasicBlock::iterator Begin = BB->begin();
3836 while (I != Begin && GetBasicInstructionClass(I) != IC_Retain)
3838 Instruction *Retain = I;
3839 if (GetBasicInstructionClass(Retain) != IC_Retain) return;
3840 if (GetObjCArg(Retain) != New) return;
3845 LLVMContext &C = Release->getContext();
3846 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3847 Type *I8XX = PointerType::getUnqual(I8X);
3849 Value *Args[] = { Load->getPointerOperand(), New };
3850 if (Args[0]->getType() != I8XX)
3851 Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
3852 if (Args[1]->getType() != I8X)
3853 Args[1] = new BitCastInst(Args[1], I8X, "", Store);
3854 CallInst *StoreStrong =
3855 CallInst::Create(getStoreStrongCallee(BB->getParent()->getParent()),
3857 StoreStrong->setDoesNotThrow();
3858 StoreStrong->setDebugLoc(Store->getDebugLoc());
3860 // We can't set the tail flag yet, because we haven't yet determined
3861 // whether there are any escaping allocas. Remember this call, so that
3862 // we can set the tail flag once we know it's safe.
3863 StoreStrongCalls.insert(StoreStrong);
3865 if (&*Iter == Store) ++Iter;
3866 Store->eraseFromParent();
3867 Release->eraseFromParent();
3868 EraseInstruction(Retain);
3869 if (Load->use_empty())
3870 Load->eraseFromParent();
3873 bool ObjCARCContract::doInitialization(Module &M) {
3874 Run = ModuleHasARC(M);
3878 // These are initialized lazily.
3879 StoreStrongCallee = 0;
3880 RetainAutoreleaseCallee = 0;
3881 RetainAutoreleaseRVCallee = 0;
3883 // Initialize RetainRVMarker.
3885 if (NamedMDNode *NMD =
3886 M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker"))
3887 if (NMD->getNumOperands() == 1) {
3888 const MDNode *N = NMD->getOperand(0);
3889 if (N->getNumOperands() == 1)
3890 if (const MDString *S = dyn_cast<MDString>(N->getOperand(0)))
3897 bool ObjCARCContract::runOnFunction(Function &F) {
3901 // If nothing in the Module uses ARC, don't do anything.
3906 AA = &getAnalysis<AliasAnalysis>();
3907 DT = &getAnalysis<DominatorTree>();
3909 PA.setAA(&getAnalysis<AliasAnalysis>());
3911 // Track whether it's ok to mark objc_storeStrong calls with the "tail"
3912 // keyword. Be conservative if the function has variadic arguments.
3913 // It seems that functions which "return twice" are also unsafe for the
3914 // "tail" argument, because they are setjmp, which could need to
3915 // return to an earlier stack state.
3916 bool TailOkForStoreStrongs = !F.isVarArg() && !F.callsFunctionThatReturnsTwice();
3918 // For ObjC library calls which return their argument, replace uses of the
3919 // argument with uses of the call return value, if it dominates the use. This
3920 // reduces register pressure.
3921 SmallPtrSet<Instruction *, 4> DependingInstructions;
3922 SmallPtrSet<const BasicBlock *, 4> Visited;
3923 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3924 Instruction *Inst = &*I++;
3926 // Only these library routines return their argument. In particular,
3927 // objc_retainBlock does not necessarily return its argument.
3928 InstructionClass Class = GetBasicInstructionClass(Inst);
3931 case IC_FusedRetainAutorelease:
3932 case IC_FusedRetainAutoreleaseRV:
3934 case IC_Autorelease:
3935 case IC_AutoreleaseRV:
3936 if (ContractAutorelease(F, Inst, Class, DependingInstructions, Visited))
3940 // If we're compiling for a target which needs a special inline-asm
3941 // marker to do the retainAutoreleasedReturnValue optimization,
3943 if (!RetainRVMarker)
3945 BasicBlock::iterator BBI = Inst;
3947 while (isNoopInstruction(BBI)) --BBI;
3948 if (&*BBI == GetObjCArg(Inst)) {
3950 InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()),
3951 /*isVarArg=*/false),
3952 RetainRVMarker->getString(),
3953 /*Constraints=*/"", /*hasSideEffects=*/true);
3954 CallInst::Create(IA, "", Inst);
3959 // objc_initWeak(p, null) => *p = null
3960 CallInst *CI = cast<CallInst>(Inst);
3961 if (isNullOrUndef(CI->getArgOperand(1))) {
3963 ConstantPointerNull::get(cast<PointerType>(CI->getType()));
3965 new StoreInst(Null, CI->getArgOperand(0), CI);
3966 CI->replaceAllUsesWith(Null);
3967 CI->eraseFromParent();
3972 ContractRelease(Inst, I);
3975 // Be conservative if the function has any alloca instructions.
3976 // Technically we only care about escaping alloca instructions,
3977 // but this is sufficient to handle some interesting cases.
3978 if (isa<AllocaInst>(Inst))
3979 TailOkForStoreStrongs = false;
3985 // Don't use GetObjCArg because we don't want to look through bitcasts
3986 // and such; to do the replacement, the argument must have type i8*.
3987 const Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
3989 // If we're compiling bugpointed code, don't get in trouble.
3990 if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
3992 // Look through the uses of the pointer.
3993 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
3995 Use &U = UI.getUse();
3996 unsigned OperandNo = UI.getOperandNo();
3997 ++UI; // Increment UI now, because we may unlink its element.
3998 if (Instruction *UserInst = dyn_cast<Instruction>(U.getUser()))
3999 if (Inst != UserInst && DT->dominates(Inst, UserInst)) {
4001 Instruction *Replacement = Inst;
4002 Type *UseTy = U.get()->getType();
4003 if (PHINode *PHI = dyn_cast<PHINode>(UserInst)) {
4004 // For PHI nodes, insert the bitcast in the predecessor block.
4006 PHINode::getIncomingValueNumForOperand(OperandNo);
4008 PHI->getIncomingBlock(ValNo);
4009 if (Replacement->getType() != UseTy)
4010 Replacement = new BitCastInst(Replacement, UseTy, "",
4012 for (unsigned i = 0, e = PHI->getNumIncomingValues();
4014 if (PHI->getIncomingBlock(i) == BB) {
4015 // Keep the UI iterator valid.
4016 if (&PHI->getOperandUse(
4017 PHINode::getOperandNumForIncomingValue(i)) ==
4020 PHI->setIncomingValue(i, Replacement);
4023 if (Replacement->getType() != UseTy)
4024 Replacement = new BitCastInst(Replacement, UseTy, "", UserInst);
4030 // If Arg is a no-op casted pointer, strip one level of casts and
4032 if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
4033 Arg = BI->getOperand(0);
4034 else if (isa<GEPOperator>(Arg) &&
4035 cast<GEPOperator>(Arg)->hasAllZeroIndices())
4036 Arg = cast<GEPOperator>(Arg)->getPointerOperand();
4037 else if (isa<GlobalAlias>(Arg) &&
4038 !cast<GlobalAlias>(Arg)->mayBeOverridden())
4039 Arg = cast<GlobalAlias>(Arg)->getAliasee();
4045 // If this function has no escaping allocas or suspicious vararg usage,
4046 // objc_storeStrong calls can be marked with the "tail" keyword.
4047 if (TailOkForStoreStrongs)
4048 for (DenseSet<CallInst *>::iterator I = StoreStrongCalls.begin(),
4049 E = StoreStrongCalls.end(); I != E; ++I)
4050 (*I)->setTailCall();
4051 StoreStrongCalls.clear();