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.
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 if (isa<BitCastInst>(UUser) || isa<GetElementPtrInst>(UUser) ||
622 isa<PHINode>(UUser) || isa<SelectInst>(UUser)) {
623 Worklist.push_back(UUser);
628 } while (!Worklist.empty());
634 //===----------------------------------------------------------------------===//
635 // ARC AliasAnalysis.
636 //===----------------------------------------------------------------------===//
638 #include "llvm/Pass.h"
639 #include "llvm/Analysis/AliasAnalysis.h"
640 #include "llvm/Analysis/Passes.h"
643 /// ObjCARCAliasAnalysis - This is a simple alias analysis
644 /// implementation that uses knowledge of ARC constructs to answer queries.
646 /// TODO: This class could be generalized to know about other ObjC-specific
647 /// tricks. Such as knowing that ivars in the non-fragile ABI are non-aliasing
648 /// even though their offsets are dynamic.
649 class ObjCARCAliasAnalysis : public ImmutablePass,
650 public AliasAnalysis {
652 static char ID; // Class identification, replacement for typeinfo
653 ObjCARCAliasAnalysis() : ImmutablePass(ID) {
654 initializeObjCARCAliasAnalysisPass(*PassRegistry::getPassRegistry());
658 virtual void initializePass() {
659 InitializeAliasAnalysis(this);
662 /// getAdjustedAnalysisPointer - This method is used when a pass implements
663 /// an analysis interface through multiple inheritance. If needed, it
664 /// should override this to adjust the this pointer as needed for the
665 /// specified pass info.
666 virtual void *getAdjustedAnalysisPointer(const void *PI) {
667 if (PI == &AliasAnalysis::ID)
668 return (AliasAnalysis*)this;
672 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
673 virtual AliasResult alias(const Location &LocA, const Location &LocB);
674 virtual bool pointsToConstantMemory(const Location &Loc, bool OrLocal);
675 virtual ModRefBehavior getModRefBehavior(ImmutableCallSite CS);
676 virtual ModRefBehavior getModRefBehavior(const Function *F);
677 virtual ModRefResult getModRefInfo(ImmutableCallSite CS,
678 const Location &Loc);
679 virtual ModRefResult getModRefInfo(ImmutableCallSite CS1,
680 ImmutableCallSite CS2);
682 } // End of anonymous namespace
684 // Register this pass...
685 char ObjCARCAliasAnalysis::ID = 0;
686 INITIALIZE_AG_PASS(ObjCARCAliasAnalysis, AliasAnalysis, "objc-arc-aa",
687 "ObjC-ARC-Based Alias Analysis", false, true, false)
689 ImmutablePass *llvm::createObjCARCAliasAnalysisPass() {
690 return new ObjCARCAliasAnalysis();
694 ObjCARCAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
695 AU.setPreservesAll();
696 AliasAnalysis::getAnalysisUsage(AU);
699 AliasAnalysis::AliasResult
700 ObjCARCAliasAnalysis::alias(const Location &LocA, const Location &LocB) {
702 return AliasAnalysis::alias(LocA, LocB);
704 // First, strip off no-ops, including ObjC-specific no-ops, and try making a
705 // precise alias query.
706 const Value *SA = StripPointerCastsAndObjCCalls(LocA.Ptr);
707 const Value *SB = StripPointerCastsAndObjCCalls(LocB.Ptr);
709 AliasAnalysis::alias(Location(SA, LocA.Size, LocA.TBAATag),
710 Location(SB, LocB.Size, LocB.TBAATag));
711 if (Result != MayAlias)
714 // If that failed, climb to the underlying object, including climbing through
715 // ObjC-specific no-ops, and try making an imprecise alias query.
716 const Value *UA = GetUnderlyingObjCPtr(SA);
717 const Value *UB = GetUnderlyingObjCPtr(SB);
718 if (UA != SA || UB != SB) {
719 Result = AliasAnalysis::alias(Location(UA), Location(UB));
720 // We can't use MustAlias or PartialAlias results here because
721 // GetUnderlyingObjCPtr may return an offsetted pointer value.
722 if (Result == NoAlias)
726 // If that failed, fail. We don't need to chain here, since that's covered
727 // by the earlier precise query.
732 ObjCARCAliasAnalysis::pointsToConstantMemory(const Location &Loc,
735 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
737 // First, strip off no-ops, including ObjC-specific no-ops, and try making
738 // a precise alias query.
739 const Value *S = StripPointerCastsAndObjCCalls(Loc.Ptr);
740 if (AliasAnalysis::pointsToConstantMemory(Location(S, Loc.Size, Loc.TBAATag),
744 // If that failed, climb to the underlying object, including climbing through
745 // ObjC-specific no-ops, and try making an imprecise alias query.
746 const Value *U = GetUnderlyingObjCPtr(S);
748 return AliasAnalysis::pointsToConstantMemory(Location(U), OrLocal);
750 // If that failed, fail. We don't need to chain here, since that's covered
751 // by the earlier precise query.
755 AliasAnalysis::ModRefBehavior
756 ObjCARCAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
757 // We have nothing to do. Just chain to the next AliasAnalysis.
758 return AliasAnalysis::getModRefBehavior(CS);
761 AliasAnalysis::ModRefBehavior
762 ObjCARCAliasAnalysis::getModRefBehavior(const Function *F) {
764 return AliasAnalysis::getModRefBehavior(F);
766 switch (GetFunctionClass(F)) {
768 return DoesNotAccessMemory;
773 return AliasAnalysis::getModRefBehavior(F);
776 AliasAnalysis::ModRefResult
777 ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS, const Location &Loc) {
779 return AliasAnalysis::getModRefInfo(CS, Loc);
781 switch (GetBasicInstructionClass(CS.getInstruction())) {
785 case IC_AutoreleaseRV:
787 case IC_AutoreleasepoolPush:
788 case IC_FusedRetainAutorelease:
789 case IC_FusedRetainAutoreleaseRV:
790 // These functions don't access any memory visible to the compiler.
791 // Note that this doesn't include objc_retainBlock, becuase it updates
792 // pointers when it copies block data.
798 return AliasAnalysis::getModRefInfo(CS, Loc);
801 AliasAnalysis::ModRefResult
802 ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
803 ImmutableCallSite CS2) {
804 // TODO: Theoretically we could check for dependencies between objc_* calls
805 // and OnlyAccessesArgumentPointees calls or other well-behaved calls.
806 return AliasAnalysis::getModRefInfo(CS1, CS2);
809 //===----------------------------------------------------------------------===//
811 //===----------------------------------------------------------------------===//
813 #include "llvm/Support/InstIterator.h"
814 #include "llvm/Transforms/Scalar.h"
817 /// ObjCARCExpand - Early ARC transformations.
818 class ObjCARCExpand : public FunctionPass {
819 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
820 virtual bool doInitialization(Module &M);
821 virtual bool runOnFunction(Function &F);
823 /// Run - A flag indicating whether this optimization pass should run.
828 ObjCARCExpand() : FunctionPass(ID) {
829 initializeObjCARCExpandPass(*PassRegistry::getPassRegistry());
834 char ObjCARCExpand::ID = 0;
835 INITIALIZE_PASS(ObjCARCExpand,
836 "objc-arc-expand", "ObjC ARC expansion", false, false)
838 Pass *llvm::createObjCARCExpandPass() {
839 return new ObjCARCExpand();
842 void ObjCARCExpand::getAnalysisUsage(AnalysisUsage &AU) const {
843 AU.setPreservesCFG();
846 bool ObjCARCExpand::doInitialization(Module &M) {
847 Run = ModuleHasARC(M);
851 bool ObjCARCExpand::runOnFunction(Function &F) {
855 // If nothing in the Module uses ARC, don't do anything.
859 bool Changed = false;
861 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
862 Instruction *Inst = &*I;
864 switch (GetBasicInstructionClass(Inst)) {
868 case IC_AutoreleaseRV:
869 case IC_FusedRetainAutorelease:
870 case IC_FusedRetainAutoreleaseRV:
871 // These calls return their argument verbatim, as a low-level
872 // optimization. However, this makes high-level optimizations
873 // harder. Undo any uses of this optimization that the front-end
874 // emitted here. We'll redo them in a later pass.
876 Inst->replaceAllUsesWith(cast<CallInst>(Inst)->getArgOperand(0));
886 //===----------------------------------------------------------------------===//
888 //===----------------------------------------------------------------------===//
890 // TODO: On code like this:
893 // stuff_that_cannot_release()
894 // objc_autorelease(%x)
895 // stuff_that_cannot_release()
897 // stuff_that_cannot_release()
898 // objc_autorelease(%x)
900 // The second retain and autorelease can be deleted.
902 // TODO: It should be possible to delete
903 // objc_autoreleasePoolPush and objc_autoreleasePoolPop
904 // pairs if nothing is actually autoreleased between them. Also, autorelease
905 // calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
906 // after inlining) can be turned into plain release calls.
908 // TODO: Critical-edge splitting. If the optimial insertion point is
909 // a critical edge, the current algorithm has to fail, because it doesn't
910 // know how to split edges. It should be possible to make the optimizer
911 // think in terms of edges, rather than blocks, and then split critical
914 // TODO: OptimizeSequences could generalized to be Interprocedural.
916 // TODO: Recognize that a bunch of other objc runtime calls have
917 // non-escaping arguments and non-releasing arguments, and may be
918 // non-autoreleasing.
920 // TODO: Sink autorelease calls as far as possible. Unfortunately we
921 // usually can't sink them past other calls, which would be the main
922 // case where it would be useful.
924 // TODO: The pointer returned from objc_loadWeakRetained is retained.
926 // TODO: Delete release+retain pairs (rare).
928 #include "llvm/GlobalAlias.h"
929 #include "llvm/Constants.h"
930 #include "llvm/LLVMContext.h"
931 #include "llvm/Support/ErrorHandling.h"
932 #include "llvm/Support/CFG.h"
933 #include "llvm/ADT/Statistic.h"
934 #include "llvm/ADT/SmallPtrSet.h"
935 #include "llvm/ADT/DenseSet.h"
937 STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
938 STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
939 STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
940 STATISTIC(NumRets, "Number of return value forwarding "
941 "retain+autoreleaes eliminated");
942 STATISTIC(NumRRs, "Number of retain+release paths eliminated");
943 STATISTIC(NumPeeps, "Number of calls peephole-optimized");
946 /// ProvenanceAnalysis - This is similar to BasicAliasAnalysis, and it
947 /// uses many of the same techniques, except it uses special ObjC-specific
948 /// reasoning about pointer relationships.
949 class ProvenanceAnalysis {
952 typedef std::pair<const Value *, const Value *> ValuePairTy;
953 typedef DenseMap<ValuePairTy, bool> CachedResultsTy;
954 CachedResultsTy CachedResults;
956 bool relatedCheck(const Value *A, const Value *B);
957 bool relatedSelect(const SelectInst *A, const Value *B);
958 bool relatedPHI(const PHINode *A, const Value *B);
961 void operator=(const ProvenanceAnalysis &);
962 ProvenanceAnalysis(const ProvenanceAnalysis &);
965 ProvenanceAnalysis() {}
967 void setAA(AliasAnalysis *aa) { AA = aa; }
969 AliasAnalysis *getAA() const { return AA; }
971 bool related(const Value *A, const Value *B);
974 CachedResults.clear();
979 bool ProvenanceAnalysis::relatedSelect(const SelectInst *A, const Value *B) {
980 // If the values are Selects with the same condition, we can do a more precise
981 // check: just check for relations between the values on corresponding arms.
982 if (const SelectInst *SB = dyn_cast<SelectInst>(B))
983 if (A->getCondition() == SB->getCondition()) {
984 if (related(A->getTrueValue(), SB->getTrueValue()))
986 if (related(A->getFalseValue(), SB->getFalseValue()))
991 // Check both arms of the Select node individually.
992 if (related(A->getTrueValue(), B))
994 if (related(A->getFalseValue(), B))
997 // The arms both checked out.
1001 bool ProvenanceAnalysis::relatedPHI(const PHINode *A, const Value *B) {
1002 // If the values are PHIs in the same block, we can do a more precise as well
1003 // as efficient check: just check for relations between the values on
1004 // corresponding edges.
1005 if (const PHINode *PNB = dyn_cast<PHINode>(B))
1006 if (PNB->getParent() == A->getParent()) {
1007 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i)
1008 if (related(A->getIncomingValue(i),
1009 PNB->getIncomingValueForBlock(A->getIncomingBlock(i))))
1014 // Check each unique source of the PHI node against B.
1015 SmallPtrSet<const Value *, 4> UniqueSrc;
1016 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i) {
1017 const Value *PV1 = A->getIncomingValue(i);
1018 if (UniqueSrc.insert(PV1) && related(PV1, B))
1022 // All of the arms checked out.
1026 /// isStoredObjCPointer - Test if the value of P, or any value covered by its
1027 /// provenance, is ever stored within the function (not counting callees).
1028 static bool isStoredObjCPointer(const Value *P) {
1029 SmallPtrSet<const Value *, 8> Visited;
1030 SmallVector<const Value *, 8> Worklist;
1031 Worklist.push_back(P);
1034 P = Worklist.pop_back_val();
1035 for (Value::const_use_iterator UI = P->use_begin(), UE = P->use_end();
1037 const User *Ur = *UI;
1038 if (isa<StoreInst>(Ur)) {
1039 if (UI.getOperandNo() == 0)
1040 // The pointer is stored.
1042 // The pointed is stored through.
1045 if (isa<CallInst>(Ur))
1046 // The pointer is passed as an argument, ignore this.
1048 if (isa<PtrToIntInst>(P))
1049 // Assume the worst.
1051 if (Visited.insert(Ur))
1052 Worklist.push_back(Ur);
1054 } while (!Worklist.empty());
1056 // Everything checked out.
1060 bool ProvenanceAnalysis::relatedCheck(const Value *A, const Value *B) {
1061 // Skip past provenance pass-throughs.
1062 A = GetUnderlyingObjCPtr(A);
1063 B = GetUnderlyingObjCPtr(B);
1069 // Ask regular AliasAnalysis, for a first approximation.
1070 switch (AA->alias(A, B)) {
1071 case AliasAnalysis::NoAlias:
1073 case AliasAnalysis::MustAlias:
1074 case AliasAnalysis::PartialAlias:
1076 case AliasAnalysis::MayAlias:
1080 bool AIsIdentified = IsObjCIdentifiedObject(A);
1081 bool BIsIdentified = IsObjCIdentifiedObject(B);
1083 // An ObjC-Identified object can't alias a load if it is never locally stored.
1084 if (AIsIdentified) {
1085 if (BIsIdentified) {
1086 // If both pointers have provenance, they can be directly compared.
1090 if (isa<LoadInst>(B))
1091 return isStoredObjCPointer(A);
1094 if (BIsIdentified && isa<LoadInst>(A))
1095 return isStoredObjCPointer(B);
1098 // Special handling for PHI and Select.
1099 if (const PHINode *PN = dyn_cast<PHINode>(A))
1100 return relatedPHI(PN, B);
1101 if (const PHINode *PN = dyn_cast<PHINode>(B))
1102 return relatedPHI(PN, A);
1103 if (const SelectInst *S = dyn_cast<SelectInst>(A))
1104 return relatedSelect(S, B);
1105 if (const SelectInst *S = dyn_cast<SelectInst>(B))
1106 return relatedSelect(S, A);
1112 bool ProvenanceAnalysis::related(const Value *A, const Value *B) {
1113 // Begin by inserting a conservative value into the map. If the insertion
1114 // fails, we have the answer already. If it succeeds, leave it there until we
1115 // compute the real answer to guard against recursive queries.
1116 if (A > B) std::swap(A, B);
1117 std::pair<CachedResultsTy::iterator, bool> Pair =
1118 CachedResults.insert(std::make_pair(ValuePairTy(A, B), true));
1120 return Pair.first->second;
1122 bool Result = relatedCheck(A, B);
1123 CachedResults[ValuePairTy(A, B)] = Result;
1128 // Sequence - A sequence of states that a pointer may go through in which an
1129 // objc_retain and objc_release are actually needed.
1132 S_Retain, ///< objc_retain(x)
1133 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement
1134 S_Use, ///< any use of x
1135 S_Stop, ///< like S_Release, but code motion is stopped
1136 S_Release, ///< objc_release(x)
1137 S_MovableRelease ///< objc_release(x), !clang.imprecise_release
1141 static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
1145 if (A == S_None || B == S_None)
1148 if (A > B) std::swap(A, B);
1150 // Choose the side which is further along in the sequence.
1151 if ((A == S_Retain || A == S_CanRelease) &&
1152 (B == S_CanRelease || B == S_Use))
1155 // Choose the side which is further along in the sequence.
1156 if ((A == S_Use || A == S_CanRelease) &&
1157 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
1159 // If both sides are releases, choose the more conservative one.
1160 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
1162 if (A == S_Release && B == S_MovableRelease)
1170 /// RRInfo - Unidirectional information about either a
1171 /// retain-decrement-use-release sequence or release-use-decrement-retain
1172 /// reverese sequence.
1174 /// KnownSafe - After an objc_retain, the reference count of the referenced
1175 /// object is known to be positive. Similarly, before an objc_release, the
1176 /// reference count of the referenced object is known to be positive. If
1177 /// there are retain-release pairs in code regions where the retain count
1178 /// is known to be positive, they can be eliminated, regardless of any side
1179 /// effects between them.
1181 /// Also, a retain+release pair nested within another retain+release
1182 /// pair all on the known same pointer value can be eliminated, regardless
1183 /// of any intervening side effects.
1185 /// KnownSafe is true when either of these conditions is satisfied.
1188 /// IsRetainBlock - True if the Calls are objc_retainBlock calls (as
1189 /// opposed to objc_retain calls).
1192 /// IsTailCallRelease - True of the objc_release calls are all marked
1193 /// with the "tail" keyword.
1194 bool IsTailCallRelease;
1196 /// Partial - True of we've seen an opportunity for partial RR elimination,
1197 /// such as pushing calls into a CFG triangle or into one side of a
1199 /// TODO: Consider moving this to PtrState.
1202 /// ReleaseMetadata - If the Calls are objc_release calls and they all have
1203 /// a clang.imprecise_release tag, this is the metadata tag.
1204 MDNode *ReleaseMetadata;
1206 /// Calls - For a top-down sequence, the set of objc_retains or
1207 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
1208 SmallPtrSet<Instruction *, 2> Calls;
1210 /// ReverseInsertPts - The set of optimal insert positions for
1211 /// moving calls in the opposite sequence.
1212 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
1215 KnownSafe(false), IsRetainBlock(false),
1216 IsTailCallRelease(false), Partial(false),
1217 ReleaseMetadata(0) {}
1223 void RRInfo::clear() {
1225 IsRetainBlock = false;
1226 IsTailCallRelease = false;
1228 ReleaseMetadata = 0;
1230 ReverseInsertPts.clear();
1234 /// PtrState - This class summarizes several per-pointer runtime properties
1235 /// which are propogated through the flow graph.
1237 /// RefCount - The known minimum number of reference count increments.
1240 /// NestCount - The known minimum level of retain+release nesting.
1243 /// Seq - The current position in the sequence.
1247 /// RRI - Unidirectional information about the current sequence.
1248 /// TODO: Encapsulate this better.
1251 PtrState() : RefCount(0), NestCount(0), Seq(S_None) {}
1253 void SetAtLeastOneRefCount() {
1254 if (RefCount == 0) RefCount = 1;
1257 void IncrementRefCount() {
1258 if (RefCount != UINT_MAX) ++RefCount;
1261 void DecrementRefCount() {
1262 if (RefCount != 0) --RefCount;
1265 bool IsKnownIncremented() const {
1266 return RefCount > 0;
1269 void IncrementNestCount() {
1270 if (NestCount != UINT_MAX) ++NestCount;
1273 void DecrementNestCount() {
1274 if (NestCount != 0) --NestCount;
1277 bool IsKnownNested() const {
1278 return NestCount > 0;
1281 void SetSeq(Sequence NewSeq) {
1285 Sequence GetSeq() const {
1289 void ClearSequenceProgress() {
1294 void Merge(const PtrState &Other, bool TopDown);
1299 PtrState::Merge(const PtrState &Other, bool TopDown) {
1300 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
1301 RefCount = std::min(RefCount, Other.RefCount);
1302 NestCount = std::min(NestCount, Other.NestCount);
1304 // We can't merge a plain objc_retain with an objc_retainBlock.
1305 if (RRI.IsRetainBlock != Other.RRI.IsRetainBlock)
1308 // If we're not in a sequence (anymore), drop all associated state.
1309 if (Seq == S_None) {
1311 } else if (RRI.Partial || Other.RRI.Partial) {
1312 // If we're doing a merge on a path that's previously seen a partial
1313 // merge, conservatively drop the sequence, to avoid doing partial
1314 // RR elimination. If the branch predicates for the two merge differ,
1315 // mixing them is unsafe.
1319 // Conservatively merge the ReleaseMetadata information.
1320 if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
1321 RRI.ReleaseMetadata = 0;
1323 RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
1324 RRI.IsTailCallRelease = RRI.IsTailCallRelease && Other.RRI.IsTailCallRelease;
1325 RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
1327 // Merge the insert point sets. If there are any differences,
1328 // that makes this a partial merge.
1329 RRI.Partial = RRI.ReverseInsertPts.size() !=
1330 Other.RRI.ReverseInsertPts.size();
1331 for (SmallPtrSet<Instruction *, 2>::const_iterator
1332 I = Other.RRI.ReverseInsertPts.begin(),
1333 E = Other.RRI.ReverseInsertPts.end(); I != E; ++I)
1334 RRI.Partial |= RRI.ReverseInsertPts.insert(*I);
1339 /// BBState - Per-BasicBlock state.
1341 /// TopDownPathCount - The number of unique control paths from the entry
1342 /// which can reach this block.
1343 unsigned TopDownPathCount;
1345 /// BottomUpPathCount - The number of unique control paths to exits
1346 /// from this block.
1347 unsigned BottomUpPathCount;
1349 /// MapTy - A type for PerPtrTopDown and PerPtrBottomUp.
1350 typedef MapVector<const Value *, PtrState> MapTy;
1352 /// PerPtrTopDown - The top-down traversal uses this to record information
1353 /// known about a pointer at the bottom of each block.
1354 MapTy PerPtrTopDown;
1356 /// PerPtrBottomUp - The bottom-up traversal uses this to record information
1357 /// known about a pointer at the top of each block.
1358 MapTy PerPtrBottomUp;
1361 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
1363 typedef MapTy::iterator ptr_iterator;
1364 typedef MapTy::const_iterator ptr_const_iterator;
1366 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
1367 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
1368 ptr_const_iterator top_down_ptr_begin() const {
1369 return PerPtrTopDown.begin();
1371 ptr_const_iterator top_down_ptr_end() const {
1372 return PerPtrTopDown.end();
1375 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
1376 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
1377 ptr_const_iterator bottom_up_ptr_begin() const {
1378 return PerPtrBottomUp.begin();
1380 ptr_const_iterator bottom_up_ptr_end() const {
1381 return PerPtrBottomUp.end();
1384 /// SetAsEntry - Mark this block as being an entry block, which has one
1385 /// path from the entry by definition.
1386 void SetAsEntry() { TopDownPathCount = 1; }
1388 /// SetAsExit - Mark this block as being an exit block, which has one
1389 /// path to an exit by definition.
1390 void SetAsExit() { BottomUpPathCount = 1; }
1392 PtrState &getPtrTopDownState(const Value *Arg) {
1393 return PerPtrTopDown[Arg];
1396 PtrState &getPtrBottomUpState(const Value *Arg) {
1397 return PerPtrBottomUp[Arg];
1400 void clearBottomUpPointers() {
1401 PerPtrBottomUp.clear();
1404 void clearTopDownPointers() {
1405 PerPtrTopDown.clear();
1408 void InitFromPred(const BBState &Other);
1409 void InitFromSucc(const BBState &Other);
1410 void MergePred(const BBState &Other);
1411 void MergeSucc(const BBState &Other);
1413 /// GetAllPathCount - Return the number of possible unique paths from an
1414 /// entry to an exit which pass through this block. This is only valid
1415 /// after both the top-down and bottom-up traversals are complete.
1416 unsigned GetAllPathCount() const {
1417 return TopDownPathCount * BottomUpPathCount;
1420 /// IsVisitedTopDown - Test whether the block for this BBState has been
1421 /// visited by the top-down portion of the algorithm.
1422 bool isVisitedTopDown() const {
1423 return TopDownPathCount != 0;
1428 void BBState::InitFromPred(const BBState &Other) {
1429 PerPtrTopDown = Other.PerPtrTopDown;
1430 TopDownPathCount = Other.TopDownPathCount;
1433 void BBState::InitFromSucc(const BBState &Other) {
1434 PerPtrBottomUp = Other.PerPtrBottomUp;
1435 BottomUpPathCount = Other.BottomUpPathCount;
1438 /// MergePred - The top-down traversal uses this to merge information about
1439 /// predecessors to form the initial state for a new block.
1440 void BBState::MergePred(const BBState &Other) {
1441 // Other.TopDownPathCount can be 0, in which case it is either dead or a
1442 // loop backedge. Loop backedges are special.
1443 TopDownPathCount += Other.TopDownPathCount;
1445 // For each entry in the other set, if our set has an entry with the same key,
1446 // merge the entries. Otherwise, copy the entry and merge it with an empty
1448 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
1449 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
1450 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
1451 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1455 // For each entry in our set, if the other set doesn't have an entry with the
1456 // same key, force it to merge with an empty entry.
1457 for (ptr_iterator MI = top_down_ptr_begin(),
1458 ME = top_down_ptr_end(); MI != ME; ++MI)
1459 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
1460 MI->second.Merge(PtrState(), /*TopDown=*/true);
1463 /// MergeSucc - The bottom-up traversal uses this to merge information about
1464 /// successors to form the initial state for a new block.
1465 void BBState::MergeSucc(const BBState &Other) {
1466 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
1467 // loop backedge. Loop backedges are special.
1468 BottomUpPathCount += Other.BottomUpPathCount;
1470 // For each entry in the other set, if our set has an entry with the
1471 // same key, merge the entries. Otherwise, copy the entry and merge
1472 // it with an empty entry.
1473 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
1474 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
1475 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
1476 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1480 // For each entry in our set, if the other set doesn't have an entry
1481 // with the same key, force it to merge with an empty entry.
1482 for (ptr_iterator MI = bottom_up_ptr_begin(),
1483 ME = bottom_up_ptr_end(); MI != ME; ++MI)
1484 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
1485 MI->second.Merge(PtrState(), /*TopDown=*/false);
1489 /// ObjCARCOpt - The main ARC optimization pass.
1490 class ObjCARCOpt : public FunctionPass {
1492 ProvenanceAnalysis PA;
1494 /// Run - A flag indicating whether this optimization pass should run.
1497 /// RetainRVCallee, etc. - Declarations for ObjC runtime
1498 /// functions, for use in creating calls to them. These are initialized
1499 /// lazily to avoid cluttering up the Module with unused declarations.
1500 Constant *RetainRVCallee, *AutoreleaseRVCallee, *ReleaseCallee,
1501 *RetainCallee, *RetainBlockCallee, *AutoreleaseCallee;
1503 /// UsedInThisFunciton - Flags which determine whether each of the
1504 /// interesting runtine functions is in fact used in the current function.
1505 unsigned UsedInThisFunction;
1507 /// ImpreciseReleaseMDKind - The Metadata Kind for clang.imprecise_release
1509 unsigned ImpreciseReleaseMDKind;
1511 /// CopyOnEscapeMDKind - The Metadata Kind for clang.arc.copy_on_escape
1513 unsigned CopyOnEscapeMDKind;
1515 Constant *getRetainRVCallee(Module *M);
1516 Constant *getAutoreleaseRVCallee(Module *M);
1517 Constant *getReleaseCallee(Module *M);
1518 Constant *getRetainCallee(Module *M);
1519 Constant *getRetainBlockCallee(Module *M);
1520 Constant *getAutoreleaseCallee(Module *M);
1522 bool IsRetainBlockOptimizable(const Instruction *Inst);
1524 void OptimizeRetainCall(Function &F, Instruction *Retain);
1525 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
1526 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV);
1527 void OptimizeIndividualCalls(Function &F);
1529 void CheckForCFGHazards(const BasicBlock *BB,
1530 DenseMap<const BasicBlock *, BBState> &BBStates,
1531 BBState &MyStates) const;
1532 bool VisitBottomUp(BasicBlock *BB,
1533 DenseMap<const BasicBlock *, BBState> &BBStates,
1534 MapVector<Value *, RRInfo> &Retains);
1535 bool VisitTopDown(BasicBlock *BB,
1536 DenseMap<const BasicBlock *, BBState> &BBStates,
1537 DenseMap<Value *, RRInfo> &Releases);
1538 bool Visit(Function &F,
1539 DenseMap<const BasicBlock *, BBState> &BBStates,
1540 MapVector<Value *, RRInfo> &Retains,
1541 DenseMap<Value *, RRInfo> &Releases);
1543 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1544 MapVector<Value *, RRInfo> &Retains,
1545 DenseMap<Value *, RRInfo> &Releases,
1546 SmallVectorImpl<Instruction *> &DeadInsts,
1549 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1550 MapVector<Value *, RRInfo> &Retains,
1551 DenseMap<Value *, RRInfo> &Releases,
1554 void OptimizeWeakCalls(Function &F);
1556 bool OptimizeSequences(Function &F);
1558 void OptimizeReturns(Function &F);
1560 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1561 virtual bool doInitialization(Module &M);
1562 virtual bool runOnFunction(Function &F);
1563 virtual void releaseMemory();
1567 ObjCARCOpt() : FunctionPass(ID) {
1568 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1573 char ObjCARCOpt::ID = 0;
1574 INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1575 "objc-arc", "ObjC ARC optimization", false, false)
1576 INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1577 INITIALIZE_PASS_END(ObjCARCOpt,
1578 "objc-arc", "ObjC ARC optimization", false, false)
1580 Pass *llvm::createObjCARCOptPass() {
1581 return new ObjCARCOpt();
1584 void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1585 AU.addRequired<ObjCARCAliasAnalysis>();
1586 AU.addRequired<AliasAnalysis>();
1587 // ARC optimization doesn't currently split critical edges.
1588 AU.setPreservesCFG();
1591 bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1592 // Without the magic metadata tag, we have to assume this might be an
1593 // objc_retainBlock call inserted to convert a block pointer to an id,
1594 // in which case it really is needed.
1595 if (!Inst->getMetadata(CopyOnEscapeMDKind))
1598 // If the pointer "escapes" (not including being used in a call),
1599 // the copy may be needed.
1600 if (DoesObjCBlockEscape(Inst))
1603 // Otherwise, it's not needed.
1607 Constant *ObjCARCOpt::getRetainRVCallee(Module *M) {
1608 if (!RetainRVCallee) {
1609 LLVMContext &C = M->getContext();
1610 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1611 std::vector<Type *> Params;
1612 Params.push_back(I8X);
1614 FunctionType::get(I8X, Params, /*isVarArg=*/false);
1615 AttrListPtr Attributes;
1616 Attributes.addAttr(~0u, Attribute::NoUnwind);
1618 M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy,
1621 return RetainRVCallee;
1624 Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1625 if (!AutoreleaseRVCallee) {
1626 LLVMContext &C = M->getContext();
1627 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1628 std::vector<Type *> Params;
1629 Params.push_back(I8X);
1631 FunctionType::get(I8X, Params, /*isVarArg=*/false);
1632 AttrListPtr Attributes;
1633 Attributes.addAttr(~0u, Attribute::NoUnwind);
1634 AutoreleaseRVCallee =
1635 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
1638 return AutoreleaseRVCallee;
1641 Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1642 if (!ReleaseCallee) {
1643 LLVMContext &C = M->getContext();
1644 std::vector<Type *> Params;
1645 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1646 AttrListPtr Attributes;
1647 Attributes.addAttr(~0u, Attribute::NoUnwind);
1649 M->getOrInsertFunction(
1651 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
1654 return ReleaseCallee;
1657 Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1658 if (!RetainCallee) {
1659 LLVMContext &C = M->getContext();
1660 std::vector<Type *> Params;
1661 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1662 AttrListPtr Attributes;
1663 Attributes.addAttr(~0u, Attribute::NoUnwind);
1665 M->getOrInsertFunction(
1667 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1670 return RetainCallee;
1673 Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1674 if (!RetainBlockCallee) {
1675 LLVMContext &C = M->getContext();
1676 std::vector<Type *> Params;
1677 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1678 AttrListPtr Attributes;
1679 // objc_retainBlock is not nounwind because it calls user copy constructors
1680 // which could theoretically throw.
1682 M->getOrInsertFunction(
1684 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1687 return RetainBlockCallee;
1690 Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1691 if (!AutoreleaseCallee) {
1692 LLVMContext &C = M->getContext();
1693 std::vector<Type *> Params;
1694 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1695 AttrListPtr Attributes;
1696 Attributes.addAttr(~0u, Attribute::NoUnwind);
1698 M->getOrInsertFunction(
1700 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1703 return AutoreleaseCallee;
1706 /// CanAlterRefCount - Test whether the given instruction can result in a
1707 /// reference count modification (positive or negative) for the pointer's
1710 CanAlterRefCount(const Instruction *Inst, const Value *Ptr,
1711 ProvenanceAnalysis &PA, InstructionClass Class) {
1713 case IC_Autorelease:
1714 case IC_AutoreleaseRV:
1716 // These operations never directly modify a reference count.
1721 ImmutableCallSite CS = static_cast<const Value *>(Inst);
1722 assert(CS && "Only calls can alter reference counts!");
1724 // See if AliasAnalysis can help us with the call.
1725 AliasAnalysis::ModRefBehavior MRB = PA.getAA()->getModRefBehavior(CS);
1726 if (AliasAnalysis::onlyReadsMemory(MRB))
1728 if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
1729 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1731 const Value *Op = *I;
1732 if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1738 // Assume the worst.
1742 /// CanUse - Test whether the given instruction can "use" the given pointer's
1743 /// object in a way that requires the reference count to be positive.
1745 CanUse(const Instruction *Inst, const Value *Ptr, ProvenanceAnalysis &PA,
1746 InstructionClass Class) {
1747 // IC_Call operations (as opposed to IC_CallOrUser) never "use" objc pointers.
1748 if (Class == IC_Call)
1751 // Consider various instructions which may have pointer arguments which are
1753 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(Inst)) {
1754 // Comparing a pointer with null, or any other constant, isn't really a use,
1755 // because we don't care what the pointer points to, or about the values
1756 // of any other dynamic reference-counted pointers.
1757 if (!IsPotentialUse(ICI->getOperand(1)))
1759 } else if (ImmutableCallSite CS = static_cast<const Value *>(Inst)) {
1760 // For calls, just check the arguments (and not the callee operand).
1761 for (ImmutableCallSite::arg_iterator OI = CS.arg_begin(),
1762 OE = CS.arg_end(); OI != OE; ++OI) {
1763 const Value *Op = *OI;
1764 if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1768 } else if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1769 // Special-case stores, because we don't care about the stored value, just
1770 // the store address.
1771 const Value *Op = GetUnderlyingObjCPtr(SI->getPointerOperand());
1772 // If we can't tell what the underlying object was, assume there is a
1774 return IsPotentialUse(Op) && PA.related(Op, Ptr);
1777 // Check each operand for a match.
1778 for (User::const_op_iterator OI = Inst->op_begin(), OE = Inst->op_end();
1780 const Value *Op = *OI;
1781 if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1787 /// CanInterruptRV - Test whether the given instruction can autorelease
1788 /// any pointer or cause an autoreleasepool pop.
1790 CanInterruptRV(InstructionClass Class) {
1792 case IC_AutoreleasepoolPop:
1795 case IC_Autorelease:
1796 case IC_AutoreleaseRV:
1797 case IC_FusedRetainAutorelease:
1798 case IC_FusedRetainAutoreleaseRV:
1806 /// DependenceKind - There are several kinds of dependence-like concepts in
1808 enum DependenceKind {
1809 NeedsPositiveRetainCount,
1810 CanChangeRetainCount,
1811 RetainAutoreleaseDep, ///< Blocks objc_retainAutorelease.
1812 RetainAutoreleaseRVDep, ///< Blocks objc_retainAutoreleaseReturnValue.
1813 RetainRVDep ///< Blocks objc_retainAutoreleasedReturnValue.
1817 /// Depends - Test if there can be dependencies on Inst through Arg. This
1818 /// function only tests dependencies relevant for removing pairs of calls.
1820 Depends(DependenceKind Flavor, Instruction *Inst, const Value *Arg,
1821 ProvenanceAnalysis &PA) {
1822 // If we've reached the definition of Arg, stop.
1827 case NeedsPositiveRetainCount: {
1828 InstructionClass Class = GetInstructionClass(Inst);
1830 case IC_AutoreleasepoolPop:
1831 case IC_AutoreleasepoolPush:
1835 return CanUse(Inst, Arg, PA, Class);
1839 case CanChangeRetainCount: {
1840 InstructionClass Class = GetInstructionClass(Inst);
1842 case IC_AutoreleasepoolPop:
1843 // Conservatively assume this can decrement any count.
1845 case IC_AutoreleasepoolPush:
1849 return CanAlterRefCount(Inst, Arg, PA, Class);
1853 case RetainAutoreleaseDep:
1854 switch (GetBasicInstructionClass(Inst)) {
1855 case IC_AutoreleasepoolPop:
1856 // Don't merge an objc_autorelease with an objc_retain inside a different
1857 // autoreleasepool scope.
1861 // Check for a retain of the same pointer for merging.
1862 return GetObjCArg(Inst) == Arg;
1864 // Nothing else matters for objc_retainAutorelease formation.
1869 case RetainAutoreleaseRVDep: {
1870 InstructionClass Class = GetBasicInstructionClass(Inst);
1874 // Check for a retain of the same pointer for merging.
1875 return GetObjCArg(Inst) == Arg;
1877 // Anything that can autorelease interrupts
1878 // retainAutoreleaseReturnValue formation.
1879 return CanInterruptRV(Class);
1885 return CanInterruptRV(GetBasicInstructionClass(Inst));
1888 llvm_unreachable("Invalid dependence flavor");
1891 /// FindDependencies - Walk up the CFG from StartPos (which is in StartBB) and
1892 /// find local and non-local dependencies on Arg.
1893 /// TODO: Cache results?
1895 FindDependencies(DependenceKind Flavor,
1897 BasicBlock *StartBB, Instruction *StartInst,
1898 SmallPtrSet<Instruction *, 4> &DependingInstructions,
1899 SmallPtrSet<const BasicBlock *, 4> &Visited,
1900 ProvenanceAnalysis &PA) {
1901 BasicBlock::iterator StartPos = StartInst;
1903 SmallVector<std::pair<BasicBlock *, BasicBlock::iterator>, 4> Worklist;
1904 Worklist.push_back(std::make_pair(StartBB, StartPos));
1906 std::pair<BasicBlock *, BasicBlock::iterator> Pair =
1907 Worklist.pop_back_val();
1908 BasicBlock *LocalStartBB = Pair.first;
1909 BasicBlock::iterator LocalStartPos = Pair.second;
1910 BasicBlock::iterator StartBBBegin = LocalStartBB->begin();
1912 if (LocalStartPos == StartBBBegin) {
1913 pred_iterator PI(LocalStartBB), PE(LocalStartBB, false);
1915 // If we've reached the function entry, produce a null dependence.
1916 DependingInstructions.insert(0);
1918 // Add the predecessors to the worklist.
1920 BasicBlock *PredBB = *PI;
1921 if (Visited.insert(PredBB))
1922 Worklist.push_back(std::make_pair(PredBB, PredBB->end()));
1923 } while (++PI != PE);
1927 Instruction *Inst = --LocalStartPos;
1928 if (Depends(Flavor, Inst, Arg, PA)) {
1929 DependingInstructions.insert(Inst);
1933 } while (!Worklist.empty());
1935 // Determine whether the original StartBB post-dominates all of the blocks we
1936 // visited. If not, insert a sentinal indicating that most optimizations are
1938 for (SmallPtrSet<const BasicBlock *, 4>::const_iterator I = Visited.begin(),
1939 E = Visited.end(); I != E; ++I) {
1940 const BasicBlock *BB = *I;
1943 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
1944 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
1945 const BasicBlock *Succ = *SI;
1946 if (Succ != StartBB && !Visited.count(Succ)) {
1947 DependingInstructions.insert(reinterpret_cast<Instruction *>(-1));
1954 static bool isNullOrUndef(const Value *V) {
1955 return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
1958 static bool isNoopInstruction(const Instruction *I) {
1959 return isa<BitCastInst>(I) ||
1960 (isa<GetElementPtrInst>(I) &&
1961 cast<GetElementPtrInst>(I)->hasAllZeroIndices());
1964 /// OptimizeRetainCall - Turn objc_retain into
1965 /// objc_retainAutoreleasedReturnValue if the operand is a return value.
1967 ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) {
1968 CallSite CS(GetObjCArg(Retain));
1969 Instruction *Call = CS.getInstruction();
1971 if (Call->getParent() != Retain->getParent()) return;
1973 // Check that the call is next to the retain.
1974 BasicBlock::iterator I = Call;
1976 while (isNoopInstruction(I)) ++I;
1980 // Turn it to an objc_retainAutoreleasedReturnValue..
1983 cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent()));
1986 /// OptimizeRetainRVCall - Turn objc_retainAutoreleasedReturnValue into
1987 /// objc_retain if the operand is not a return value. Or, if it can be
1988 /// paired with an objc_autoreleaseReturnValue, delete the pair and
1991 ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
1992 // Check for the argument being from an immediately preceding call.
1993 Value *Arg = GetObjCArg(RetainRV);
1995 if (Instruction *Call = CS.getInstruction())
1996 if (Call->getParent() == RetainRV->getParent()) {
1997 BasicBlock::iterator I = Call;
1999 while (isNoopInstruction(I)) ++I;
2000 if (&*I == RetainRV)
2004 // Check for being preceded by an objc_autoreleaseReturnValue on the same
2005 // pointer. In this case, we can delete the pair.
2006 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
2008 do --I; while (I != Begin && isNoopInstruction(I));
2009 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
2010 GetObjCArg(I) == Arg) {
2013 EraseInstruction(I);
2014 EraseInstruction(RetainRV);
2019 // Turn it to a plain objc_retain.
2022 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
2026 /// OptimizeAutoreleaseRVCall - Turn objc_autoreleaseReturnValue into
2027 /// objc_autorelease if the result is not used as a return value.
2029 ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV) {
2030 // Check for a return of the pointer value.
2031 const Value *Ptr = GetObjCArg(AutoreleaseRV);
2032 SmallVector<const Value *, 2> Users;
2033 Users.push_back(Ptr);
2035 Ptr = Users.pop_back_val();
2036 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
2038 const User *I = *UI;
2039 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
2041 if (isa<BitCastInst>(I))
2044 } while (!Users.empty());
2048 cast<CallInst>(AutoreleaseRV)->
2049 setCalledFunction(getAutoreleaseCallee(F.getParent()));
2052 /// OptimizeIndividualCalls - Visit each call, one at a time, and make
2053 /// simplifications without doing any additional analysis.
2054 void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
2055 // Reset all the flags in preparation for recomputing them.
2056 UsedInThisFunction = 0;
2058 // Visit all objc_* calls in F.
2059 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2060 Instruction *Inst = &*I++;
2061 InstructionClass Class = GetBasicInstructionClass(Inst);
2066 // Delete no-op casts. These function calls have special semantics, but
2067 // the semantics are entirely implemented via lowering in the front-end,
2068 // so by the time they reach the optimizer, they are just no-op calls
2069 // which return their argument.
2071 // There are gray areas here, as the ability to cast reference-counted
2072 // pointers to raw void* and back allows code to break ARC assumptions,
2073 // however these are currently considered to be unimportant.
2077 EraseInstruction(Inst);
2080 // If the pointer-to-weak-pointer is null, it's undefined behavior.
2083 case IC_LoadWeakRetained:
2085 case IC_DestroyWeak: {
2086 CallInst *CI = cast<CallInst>(Inst);
2087 if (isNullOrUndef(CI->getArgOperand(0))) {
2088 Type *Ty = CI->getArgOperand(0)->getType();
2089 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2090 Constant::getNullValue(Ty),
2092 CI->replaceAllUsesWith(UndefValue::get(CI->getType()));
2093 CI->eraseFromParent();
2100 CallInst *CI = cast<CallInst>(Inst);
2101 if (isNullOrUndef(CI->getArgOperand(0)) ||
2102 isNullOrUndef(CI->getArgOperand(1))) {
2103 Type *Ty = CI->getArgOperand(0)->getType();
2104 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2105 Constant::getNullValue(Ty),
2107 CI->replaceAllUsesWith(UndefValue::get(CI->getType()));
2108 CI->eraseFromParent();
2114 OptimizeRetainCall(F, Inst);
2117 if (OptimizeRetainRVCall(F, Inst))
2120 case IC_AutoreleaseRV:
2121 OptimizeAutoreleaseRVCall(F, Inst);
2125 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
2126 if (IsAutorelease(Class) && Inst->use_empty()) {
2127 CallInst *Call = cast<CallInst>(Inst);
2128 const Value *Arg = Call->getArgOperand(0);
2129 Arg = FindSingleUseIdentifiedObject(Arg);
2134 // Create the declaration lazily.
2135 LLVMContext &C = Inst->getContext();
2137 CallInst::Create(getReleaseCallee(F.getParent()),
2138 Call->getArgOperand(0), "", Call);
2139 NewCall->setMetadata(ImpreciseReleaseMDKind,
2140 MDNode::get(C, ArrayRef<Value *>()));
2141 EraseInstruction(Call);
2147 // For functions which can never be passed stack arguments, add
2149 if (IsAlwaysTail(Class)) {
2151 cast<CallInst>(Inst)->setTailCall();
2154 // Set nounwind as needed.
2155 if (IsNoThrow(Class)) {
2157 cast<CallInst>(Inst)->setDoesNotThrow();
2160 if (!IsNoopOnNull(Class)) {
2161 UsedInThisFunction |= 1 << Class;
2165 const Value *Arg = GetObjCArg(Inst);
2167 // ARC calls with null are no-ops. Delete them.
2168 if (isNullOrUndef(Arg)) {
2171 EraseInstruction(Inst);
2175 // Keep track of which of retain, release, autorelease, and retain_block
2176 // are actually present in this function.
2177 UsedInThisFunction |= 1 << Class;
2179 // If Arg is a PHI, and one or more incoming values to the
2180 // PHI are null, and the call is control-equivalent to the PHI, and there
2181 // are no relevant side effects between the PHI and the call, the call
2182 // could be pushed up to just those paths with non-null incoming values.
2183 // For now, don't bother splitting critical edges for this.
2184 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
2185 Worklist.push_back(std::make_pair(Inst, Arg));
2187 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
2191 const PHINode *PN = dyn_cast<PHINode>(Arg);
2194 // Determine if the PHI has any null operands, or any incoming
2196 bool HasNull = false;
2197 bool HasCriticalEdges = false;
2198 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2200 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2201 if (isNullOrUndef(Incoming))
2203 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
2204 .getNumSuccessors() != 1) {
2205 HasCriticalEdges = true;
2209 // If we have null operands and no critical edges, optimize.
2210 if (!HasCriticalEdges && HasNull) {
2211 SmallPtrSet<Instruction *, 4> DependingInstructions;
2212 SmallPtrSet<const BasicBlock *, 4> Visited;
2214 // Check that there is nothing that cares about the reference
2215 // count between the call and the phi.
2216 FindDependencies(NeedsPositiveRetainCount, Arg,
2217 Inst->getParent(), Inst,
2218 DependingInstructions, Visited, PA);
2219 if (DependingInstructions.size() == 1 &&
2220 *DependingInstructions.begin() == PN) {
2223 // Clone the call into each predecessor that has a non-null value.
2224 CallInst *CInst = cast<CallInst>(Inst);
2225 Type *ParamTy = CInst->getArgOperand(0)->getType();
2226 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2228 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2229 if (!isNullOrUndef(Incoming)) {
2230 CallInst *Clone = cast<CallInst>(CInst->clone());
2231 Value *Op = PN->getIncomingValue(i);
2232 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
2233 if (Op->getType() != ParamTy)
2234 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
2235 Clone->setArgOperand(0, Op);
2236 Clone->insertBefore(InsertPos);
2237 Worklist.push_back(std::make_pair(Clone, Incoming));
2240 // Erase the original call.
2241 EraseInstruction(CInst);
2245 } while (!Worklist.empty());
2249 /// CheckForCFGHazards - Check for critical edges, loop boundaries, irreducible
2250 /// control flow, or other CFG structures where moving code across the edge
2251 /// would result in it being executed more.
2253 ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
2254 DenseMap<const BasicBlock *, BBState> &BBStates,
2255 BBState &MyStates) const {
2256 // If any top-down local-use or possible-dec has a succ which is earlier in
2257 // the sequence, forget it.
2258 for (BBState::ptr_const_iterator I = MyStates.top_down_ptr_begin(),
2259 E = MyStates.top_down_ptr_end(); I != E; ++I)
2260 switch (I->second.GetSeq()) {
2263 const Value *Arg = I->first;
2264 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2265 bool SomeSuccHasSame = false;
2266 bool AllSuccsHaveSame = true;
2267 PtrState &S = MyStates.getPtrTopDownState(Arg);
2268 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2269 PtrState &SuccS = BBStates[*SI].getPtrBottomUpState(Arg);
2270 switch (SuccS.GetSeq()) {
2272 case S_CanRelease: {
2273 if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
2274 S.ClearSequenceProgress();
2278 SomeSuccHasSame = true;
2282 case S_MovableRelease:
2283 if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
2284 AllSuccsHaveSame = false;
2287 llvm_unreachable("bottom-up pointer in retain state!");
2290 // If the state at the other end of any of the successor edges
2291 // matches the current state, require all edges to match. This
2292 // guards against loops in the middle of a sequence.
2293 if (SomeSuccHasSame && !AllSuccsHaveSame)
2294 S.ClearSequenceProgress();
2297 case S_CanRelease: {
2298 const Value *Arg = I->first;
2299 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2300 bool SomeSuccHasSame = false;
2301 bool AllSuccsHaveSame = true;
2302 PtrState &S = MyStates.getPtrTopDownState(Arg);
2303 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2304 PtrState &SuccS = BBStates[*SI].getPtrBottomUpState(Arg);
2305 switch (SuccS.GetSeq()) {
2307 if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
2308 S.ClearSequenceProgress();
2312 SomeSuccHasSame = true;
2316 case S_MovableRelease:
2318 if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
2319 AllSuccsHaveSame = false;
2322 llvm_unreachable("bottom-up pointer in retain state!");
2325 // If the state at the other end of any of the successor edges
2326 // matches the current state, require all edges to match. This
2327 // guards against loops in the middle of a sequence.
2328 if (SomeSuccHasSame && !AllSuccsHaveSame)
2329 S.ClearSequenceProgress();
2336 ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2337 DenseMap<const BasicBlock *, BBState> &BBStates,
2338 MapVector<Value *, RRInfo> &Retains) {
2339 bool NestingDetected = false;
2340 BBState &MyStates = BBStates[BB];
2342 // Merge the states from each successor to compute the initial state
2343 // for the current block.
2344 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2345 succ_const_iterator SI(TI), SE(TI, false);
2347 MyStates.SetAsExit();
2350 const BasicBlock *Succ = *SI++;
2353 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
2354 // If we haven't seen this node yet, then we've found a CFG cycle.
2355 // Be optimistic here; it's CheckForCFGHazards' job detect trouble.
2356 if (I == BBStates.end())
2358 MyStates.InitFromSucc(I->second);
2362 I = BBStates.find(Succ);
2363 if (I != BBStates.end())
2364 MyStates.MergeSucc(I->second);
2370 // Visit all the instructions, bottom-up.
2371 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2372 Instruction *Inst = llvm::prior(I);
2373 InstructionClass Class = GetInstructionClass(Inst);
2374 const Value *Arg = 0;
2378 Arg = GetObjCArg(Inst);
2380 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2382 // If we see two releases in a row on the same pointer. If so, make
2383 // a note, and we'll cicle back to revisit it after we've
2384 // hopefully eliminated the second release, which may allow us to
2385 // eliminate the first release too.
2386 // Theoretically we could implement removal of nested retain+release
2387 // pairs by making PtrState hold a stack of states, but this is
2388 // simple and avoids adding overhead for the non-nested case.
2389 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease)
2390 NestingDetected = true;
2394 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2395 S.SetSeq(ReleaseMetadata ? S_MovableRelease : S_Release);
2396 S.RRI.ReleaseMetadata = ReleaseMetadata;
2397 S.RRI.KnownSafe = S.IsKnownNested() || S.IsKnownIncremented();
2398 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2399 S.RRI.Calls.insert(Inst);
2401 S.IncrementRefCount();
2402 S.IncrementNestCount();
2405 case IC_RetainBlock:
2406 // An objc_retainBlock call with just a use may need to be kept,
2407 // because it may be copying a block from the stack to the heap.
2408 if (!IsRetainBlockOptimizable(Inst))
2413 Arg = GetObjCArg(Inst);
2415 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2416 S.DecrementRefCount();
2417 S.SetAtLeastOneRefCount();
2418 S.DecrementNestCount();
2420 switch (S.GetSeq()) {
2423 case S_MovableRelease:
2425 S.RRI.ReverseInsertPts.clear();
2428 // Don't do retain+release tracking for IC_RetainRV, because it's
2429 // better to let it remain as the first instruction after a call.
2430 if (Class != IC_RetainRV) {
2431 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2432 Retains[Inst] = S.RRI;
2434 S.ClearSequenceProgress();
2439 llvm_unreachable("bottom-up pointer in retain state!");
2443 case IC_AutoreleasepoolPop:
2444 // Conservatively, clear MyStates for all known pointers.
2445 MyStates.clearBottomUpPointers();
2447 case IC_AutoreleasepoolPush:
2449 // These are irrelevant.
2455 // Consider any other possible effects of this instruction on each
2456 // pointer being tracked.
2457 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
2458 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
2459 const Value *Ptr = MI->first;
2461 continue; // Handled above.
2462 PtrState &S = MI->second;
2463 Sequence Seq = S.GetSeq();
2465 // Check for possible releases.
2466 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2467 S.DecrementRefCount();
2470 S.SetSeq(S_CanRelease);
2474 case S_MovableRelease:
2479 llvm_unreachable("bottom-up pointer in retain state!");
2483 // Check for possible direct uses.
2486 case S_MovableRelease:
2487 if (CanUse(Inst, Ptr, PA, Class)) {
2488 assert(S.RRI.ReverseInsertPts.empty());
2489 S.RRI.ReverseInsertPts.insert(Inst);
2491 } else if (Seq == S_Release &&
2492 (Class == IC_User || Class == IC_CallOrUser)) {
2493 // Non-movable releases depend on any possible objc pointer use.
2495 assert(S.RRI.ReverseInsertPts.empty());
2496 S.RRI.ReverseInsertPts.insert(Inst);
2500 if (CanUse(Inst, Ptr, PA, Class))
2508 llvm_unreachable("bottom-up pointer in retain state!");
2513 return NestingDetected;
2517 ObjCARCOpt::VisitTopDown(BasicBlock *BB,
2518 DenseMap<const BasicBlock *, BBState> &BBStates,
2519 DenseMap<Value *, RRInfo> &Releases) {
2520 bool NestingDetected = false;
2521 BBState &MyStates = BBStates[BB];
2523 // Merge the states from each predecessor to compute the initial state
2524 // for the current block.
2525 const_pred_iterator PI(BB), PE(BB, false);
2527 MyStates.SetAsEntry();
2530 const BasicBlock *Pred = *PI++;
2533 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
2534 // If we haven't seen this node yet, then we've found a CFG cycle.
2535 // Be optimistic here; it's CheckForCFGHazards' job detect trouble.
2536 if (I == BBStates.end() || !I->second.isVisitedTopDown())
2538 MyStates.InitFromPred(I->second);
2542 I = BBStates.find(Pred);
2543 if (I != BBStates.end() && I->second.isVisitedTopDown())
2544 MyStates.MergePred(I->second);
2550 // Visit all the instructions, top-down.
2551 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2552 Instruction *Inst = I;
2553 InstructionClass Class = GetInstructionClass(Inst);
2554 const Value *Arg = 0;
2557 case IC_RetainBlock:
2558 // An objc_retainBlock call with just a use may need to be kept,
2559 // because it may be copying a block from the stack to the heap.
2560 if (!IsRetainBlockOptimizable(Inst))
2565 Arg = GetObjCArg(Inst);
2567 PtrState &S = MyStates.getPtrTopDownState(Arg);
2569 // Don't do retain+release tracking for IC_RetainRV, because it's
2570 // better to let it remain as the first instruction after a call.
2571 if (Class != IC_RetainRV) {
2572 // If we see two retains in a row on the same pointer. If so, make
2573 // a note, and we'll cicle back to revisit it after we've
2574 // hopefully eliminated the second retain, which may allow us to
2575 // eliminate the first retain too.
2576 // Theoretically we could implement removal of nested retain+release
2577 // pairs by making PtrState hold a stack of states, but this is
2578 // simple and avoids adding overhead for the non-nested case.
2579 if (S.GetSeq() == S_Retain)
2580 NestingDetected = true;
2584 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2585 // Don't check S.IsKnownIncremented() here because it's not
2587 S.RRI.KnownSafe = S.IsKnownNested();
2588 S.RRI.Calls.insert(Inst);
2591 S.SetAtLeastOneRefCount();
2592 S.IncrementRefCount();
2593 S.IncrementNestCount();
2597 Arg = GetObjCArg(Inst);
2599 PtrState &S = MyStates.getPtrTopDownState(Arg);
2600 S.DecrementRefCount();
2601 S.DecrementNestCount();
2603 switch (S.GetSeq()) {
2606 S.RRI.ReverseInsertPts.clear();
2609 S.RRI.ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2610 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2611 Releases[Inst] = S.RRI;
2612 S.ClearSequenceProgress();
2618 case S_MovableRelease:
2619 llvm_unreachable("top-down pointer in release state!");
2623 case IC_AutoreleasepoolPop:
2624 // Conservatively, clear MyStates for all known pointers.
2625 MyStates.clearTopDownPointers();
2627 case IC_AutoreleasepoolPush:
2629 // These are irrelevant.
2635 // Consider any other possible effects of this instruction on each
2636 // pointer being tracked.
2637 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
2638 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
2639 const Value *Ptr = MI->first;
2641 continue; // Handled above.
2642 PtrState &S = MI->second;
2643 Sequence Seq = S.GetSeq();
2645 // Check for possible releases.
2646 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2647 S.DecrementRefCount();
2650 S.SetSeq(S_CanRelease);
2651 assert(S.RRI.ReverseInsertPts.empty());
2652 S.RRI.ReverseInsertPts.insert(Inst);
2654 // One call can't cause a transition from S_Retain to S_CanRelease
2655 // and S_CanRelease to S_Use. If we've made the first transition,
2664 case S_MovableRelease:
2665 llvm_unreachable("top-down pointer in release state!");
2669 // Check for possible direct uses.
2672 if (CanUse(Inst, Ptr, PA, Class))
2681 case S_MovableRelease:
2682 llvm_unreachable("top-down pointer in release state!");
2687 CheckForCFGHazards(BB, BBStates, MyStates);
2688 return NestingDetected;
2692 ComputePostOrders(Function &F,
2693 SmallVectorImpl<BasicBlock *> &PostOrder,
2694 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder) {
2695 /// Backedges - Backedges detected in the DFS. These edges will be
2696 /// ignored in the reverse-CFG DFS, so that loops with multiple exits will be
2697 /// traversed in the desired order.
2698 DenseSet<std::pair<BasicBlock *, BasicBlock *> > Backedges;
2700 /// Visited - The visited set, for doing DFS walks.
2701 SmallPtrSet<BasicBlock *, 16> Visited;
2703 // Do DFS, computing the PostOrder.
2704 SmallPtrSet<BasicBlock *, 16> OnStack;
2705 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
2706 BasicBlock *EntryBB = &F.getEntryBlock();
2707 SuccStack.push_back(std::make_pair(EntryBB, succ_begin(EntryBB)));
2708 Visited.insert(EntryBB);
2709 OnStack.insert(EntryBB);
2712 succ_iterator End = succ_end(SuccStack.back().first);
2713 while (SuccStack.back().second != End) {
2714 BasicBlock *BB = *SuccStack.back().second++;
2715 if (Visited.insert(BB)) {
2716 SuccStack.push_back(std::make_pair(BB, succ_begin(BB)));
2720 if (OnStack.count(BB))
2721 Backedges.insert(std::make_pair(SuccStack.back().first, BB));
2723 OnStack.erase(SuccStack.back().first);
2724 PostOrder.push_back(SuccStack.pop_back_val().first);
2725 } while (!SuccStack.empty());
2729 // Compute the exits, which are the starting points for reverse-CFG DFS.
2730 SmallVector<BasicBlock *, 4> Exits;
2731 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
2733 if (BB->getTerminator()->getNumSuccessors() == 0)
2734 Exits.push_back(BB);
2737 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
2738 SmallVector<std::pair<BasicBlock *, pred_iterator>, 16> PredStack;
2739 for (SmallVectorImpl<BasicBlock *>::iterator I = Exits.begin(), E = Exits.end();
2741 BasicBlock *ExitBB = *I;
2742 PredStack.push_back(std::make_pair(ExitBB, pred_begin(ExitBB)));
2743 Visited.insert(ExitBB);
2744 while (!PredStack.empty()) {
2745 reverse_dfs_next_succ:
2746 pred_iterator End = pred_end(PredStack.back().first);
2747 while (PredStack.back().second != End) {
2748 BasicBlock *BB = *PredStack.back().second++;
2749 // Skip backedges detected in the forward-CFG DFS.
2750 if (Backedges.count(std::make_pair(BB, PredStack.back().first)))
2752 if (Visited.insert(BB)) {
2753 PredStack.push_back(std::make_pair(BB, pred_begin(BB)));
2754 goto reverse_dfs_next_succ;
2757 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
2762 // Visit - Visit the function both top-down and bottom-up.
2764 ObjCARCOpt::Visit(Function &F,
2765 DenseMap<const BasicBlock *, BBState> &BBStates,
2766 MapVector<Value *, RRInfo> &Retains,
2767 DenseMap<Value *, RRInfo> &Releases) {
2769 // Use reverse-postorder traversals, because we magically know that loops
2770 // will be well behaved, i.e. they won't repeatedly call retain on a single
2771 // pointer without doing a release. We can't use the ReversePostOrderTraversal
2772 // class here because we want the reverse-CFG postorder to consider each
2773 // function exit point, and we want to ignore selected cycle edges.
2774 SmallVector<BasicBlock *, 16> PostOrder;
2775 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
2776 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder);
2778 // Use reverse-postorder on the reverse CFG for bottom-up.
2779 bool BottomUpNestingDetected = false;
2780 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2781 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
2783 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
2785 // Use reverse-postorder for top-down.
2786 bool TopDownNestingDetected = false;
2787 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2788 PostOrder.rbegin(), E = PostOrder.rend();
2790 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
2792 return TopDownNestingDetected && BottomUpNestingDetected;
2795 /// MoveCalls - Move the calls in RetainsToMove and ReleasesToMove.
2796 void ObjCARCOpt::MoveCalls(Value *Arg,
2797 RRInfo &RetainsToMove,
2798 RRInfo &ReleasesToMove,
2799 MapVector<Value *, RRInfo> &Retains,
2800 DenseMap<Value *, RRInfo> &Releases,
2801 SmallVectorImpl<Instruction *> &DeadInsts,
2803 Type *ArgTy = Arg->getType();
2804 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
2806 // Insert the new retain and release calls.
2807 for (SmallPtrSet<Instruction *, 2>::const_iterator
2808 PI = ReleasesToMove.ReverseInsertPts.begin(),
2809 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2810 Instruction *InsertPt = *PI;
2811 Value *MyArg = ArgTy == ParamTy ? Arg :
2812 new BitCastInst(Arg, ParamTy, "", InsertPt);
2814 CallInst::Create(RetainsToMove.IsRetainBlock ?
2815 getRetainBlockCallee(M) : getRetainCallee(M),
2816 MyArg, "", InsertPt);
2817 Call->setDoesNotThrow();
2818 if (RetainsToMove.IsRetainBlock)
2819 Call->setMetadata(CopyOnEscapeMDKind,
2820 MDNode::get(M->getContext(), ArrayRef<Value *>()));
2822 Call->setTailCall();
2824 for (SmallPtrSet<Instruction *, 2>::const_iterator
2825 PI = RetainsToMove.ReverseInsertPts.begin(),
2826 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2827 Instruction *LastUse = *PI;
2828 Instruction *InsertPts[] = { 0, 0, 0 };
2829 if (InvokeInst *II = dyn_cast<InvokeInst>(LastUse)) {
2830 // We can't insert code immediately after an invoke instruction, so
2831 // insert code at the beginning of both successor blocks instead.
2832 // The invoke's return value isn't available in the unwind block,
2833 // but our releases will never depend on it, because they must be
2834 // paired with retains from before the invoke.
2835 InsertPts[0] = II->getNormalDest()->getFirstInsertionPt();
2836 InsertPts[1] = II->getUnwindDest()->getFirstInsertionPt();
2838 // Insert code immediately after the last use.
2839 InsertPts[0] = llvm::next(BasicBlock::iterator(LastUse));
2842 for (Instruction **I = InsertPts; *I; ++I) {
2843 Instruction *InsertPt = *I;
2844 Value *MyArg = ArgTy == ParamTy ? Arg :
2845 new BitCastInst(Arg, ParamTy, "", InsertPt);
2846 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
2848 // Attach a clang.imprecise_release metadata tag, if appropriate.
2849 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
2850 Call->setMetadata(ImpreciseReleaseMDKind, M);
2851 Call->setDoesNotThrow();
2852 if (ReleasesToMove.IsTailCallRelease)
2853 Call->setTailCall();
2857 // Delete the original retain and release calls.
2858 for (SmallPtrSet<Instruction *, 2>::const_iterator
2859 AI = RetainsToMove.Calls.begin(),
2860 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
2861 Instruction *OrigRetain = *AI;
2862 Retains.blot(OrigRetain);
2863 DeadInsts.push_back(OrigRetain);
2865 for (SmallPtrSet<Instruction *, 2>::const_iterator
2866 AI = ReleasesToMove.Calls.begin(),
2867 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
2868 Instruction *OrigRelease = *AI;
2869 Releases.erase(OrigRelease);
2870 DeadInsts.push_back(OrigRelease);
2875 ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
2877 MapVector<Value *, RRInfo> &Retains,
2878 DenseMap<Value *, RRInfo> &Releases,
2880 bool AnyPairsCompletelyEliminated = false;
2881 RRInfo RetainsToMove;
2882 RRInfo ReleasesToMove;
2883 SmallVector<Instruction *, 4> NewRetains;
2884 SmallVector<Instruction *, 4> NewReleases;
2885 SmallVector<Instruction *, 8> DeadInsts;
2887 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
2888 E = Retains.end(); I != E; ++I) {
2889 Value *V = I->first;
2890 if (!V) continue; // blotted
2892 Instruction *Retain = cast<Instruction>(V);
2893 Value *Arg = GetObjCArg(Retain);
2895 // If the object being released is in static or stack storage, we know it's
2896 // not being managed by ObjC reference counting, so we can delete pairs
2897 // regardless of what possible decrements or uses lie between them.
2898 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
2900 // A constant pointer can't be pointing to an object on the heap. It may
2901 // be reference-counted, but it won't be deleted.
2902 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
2903 if (const GlobalVariable *GV =
2904 dyn_cast<GlobalVariable>(
2905 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
2906 if (GV->isConstant())
2909 // If a pair happens in a region where it is known that the reference count
2910 // is already incremented, we can similarly ignore possible decrements.
2911 bool KnownSafeTD = true, KnownSafeBU = true;
2913 // Connect the dots between the top-down-collected RetainsToMove and
2914 // bottom-up-collected ReleasesToMove to form sets of related calls.
2915 // This is an iterative process so that we connect multiple releases
2916 // to multiple retains if needed.
2917 unsigned OldDelta = 0;
2918 unsigned NewDelta = 0;
2919 unsigned OldCount = 0;
2920 unsigned NewCount = 0;
2921 bool FirstRelease = true;
2922 bool FirstRetain = true;
2923 NewRetains.push_back(Retain);
2925 for (SmallVectorImpl<Instruction *>::const_iterator
2926 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
2927 Instruction *NewRetain = *NI;
2928 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
2929 assert(It != Retains.end());
2930 const RRInfo &NewRetainRRI = It->second;
2931 KnownSafeTD &= NewRetainRRI.KnownSafe;
2932 for (SmallPtrSet<Instruction *, 2>::const_iterator
2933 LI = NewRetainRRI.Calls.begin(),
2934 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
2935 Instruction *NewRetainRelease = *LI;
2936 DenseMap<Value *, RRInfo>::const_iterator Jt =
2937 Releases.find(NewRetainRelease);
2938 if (Jt == Releases.end())
2940 const RRInfo &NewRetainReleaseRRI = Jt->second;
2941 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
2942 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
2944 BBStates[NewRetainRelease->getParent()].GetAllPathCount();
2946 // Merge the ReleaseMetadata and IsTailCallRelease values.
2948 ReleasesToMove.ReleaseMetadata =
2949 NewRetainReleaseRRI.ReleaseMetadata;
2950 ReleasesToMove.IsTailCallRelease =
2951 NewRetainReleaseRRI.IsTailCallRelease;
2952 FirstRelease = false;
2954 if (ReleasesToMove.ReleaseMetadata !=
2955 NewRetainReleaseRRI.ReleaseMetadata)
2956 ReleasesToMove.ReleaseMetadata = 0;
2957 if (ReleasesToMove.IsTailCallRelease !=
2958 NewRetainReleaseRRI.IsTailCallRelease)
2959 ReleasesToMove.IsTailCallRelease = false;
2962 // Collect the optimal insertion points.
2964 for (SmallPtrSet<Instruction *, 2>::const_iterator
2965 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
2966 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
2968 Instruction *RIP = *RI;
2969 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
2970 NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
2972 NewReleases.push_back(NewRetainRelease);
2977 if (NewReleases.empty()) break;
2979 // Back the other way.
2980 for (SmallVectorImpl<Instruction *>::const_iterator
2981 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
2982 Instruction *NewRelease = *NI;
2983 DenseMap<Value *, RRInfo>::const_iterator It =
2984 Releases.find(NewRelease);
2985 assert(It != Releases.end());
2986 const RRInfo &NewReleaseRRI = It->second;
2987 KnownSafeBU &= NewReleaseRRI.KnownSafe;
2988 for (SmallPtrSet<Instruction *, 2>::const_iterator
2989 LI = NewReleaseRRI.Calls.begin(),
2990 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
2991 Instruction *NewReleaseRetain = *LI;
2992 MapVector<Value *, RRInfo>::const_iterator Jt =
2993 Retains.find(NewReleaseRetain);
2994 if (Jt == Retains.end())
2996 const RRInfo &NewReleaseRetainRRI = Jt->second;
2997 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
2998 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
2999 unsigned PathCount =
3000 BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
3001 OldDelta += PathCount;
3002 OldCount += PathCount;
3004 // Merge the IsRetainBlock values.
3006 RetainsToMove.IsRetainBlock = NewReleaseRetainRRI.IsRetainBlock;
3007 FirstRetain = false;
3008 } else if (ReleasesToMove.IsRetainBlock !=
3009 NewReleaseRetainRRI.IsRetainBlock)
3010 // It's not possible to merge the sequences if one uses
3011 // objc_retain and the other uses objc_retainBlock.
3014 // Collect the optimal insertion points.
3016 for (SmallPtrSet<Instruction *, 2>::const_iterator
3017 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
3018 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
3020 Instruction *RIP = *RI;
3021 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
3022 PathCount = BBStates[RIP->getParent()].GetAllPathCount();
3023 NewDelta += PathCount;
3024 NewCount += PathCount;
3027 NewRetains.push_back(NewReleaseRetain);
3031 NewReleases.clear();
3032 if (NewRetains.empty()) break;
3035 // If the pointer is known incremented or nested, we can safely delete the
3036 // pair regardless of what's between them.
3037 if (KnownSafeTD || KnownSafeBU) {
3038 RetainsToMove.ReverseInsertPts.clear();
3039 ReleasesToMove.ReverseInsertPts.clear();
3042 // Determine whether the new insertion points we computed preserve the
3043 // balance of retain and release calls through the program.
3044 // TODO: If the fully aggressive solution isn't valid, try to find a
3045 // less aggressive solution which is.
3050 // Determine whether the original call points are balanced in the retain and
3051 // release calls through the program. If not, conservatively don't touch
3053 // TODO: It's theoretically possible to do code motion in this case, as
3054 // long as the existing imbalances are maintained.
3058 // Ok, everything checks out and we're all set. Let's move some code!
3060 AnyPairsCompletelyEliminated = NewCount == 0;
3061 NumRRs += OldCount - NewCount;
3062 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
3063 Retains, Releases, DeadInsts, M);
3066 NewReleases.clear();
3068 RetainsToMove.clear();
3069 ReleasesToMove.clear();
3072 // Now that we're done moving everything, we can delete the newly dead
3073 // instructions, as we no longer need them as insert points.
3074 while (!DeadInsts.empty())
3075 EraseInstruction(DeadInsts.pop_back_val());
3077 return AnyPairsCompletelyEliminated;
3080 /// OptimizeWeakCalls - Weak pointer optimizations.
3081 void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
3082 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
3083 // itself because it uses AliasAnalysis and we need to do provenance
3085 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3086 Instruction *Inst = &*I++;
3087 InstructionClass Class = GetBasicInstructionClass(Inst);
3088 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
3091 // Delete objc_loadWeak calls with no users.
3092 if (Class == IC_LoadWeak && Inst->use_empty()) {
3093 Inst->eraseFromParent();
3097 // TODO: For now, just look for an earlier available version of this value
3098 // within the same block. Theoretically, we could do memdep-style non-local
3099 // analysis too, but that would want caching. A better approach would be to
3100 // use the technique that EarlyCSE uses.
3101 inst_iterator Current = llvm::prior(I);
3102 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
3103 for (BasicBlock::iterator B = CurrentBB->begin(),
3104 J = Current.getInstructionIterator();
3106 Instruction *EarlierInst = &*llvm::prior(J);
3107 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
3108 switch (EarlierClass) {
3110 case IC_LoadWeakRetained: {
3111 // If this is loading from the same pointer, replace this load's value
3113 CallInst *Call = cast<CallInst>(Inst);
3114 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3115 Value *Arg = Call->getArgOperand(0);
3116 Value *EarlierArg = EarlierCall->getArgOperand(0);
3117 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3118 case AliasAnalysis::MustAlias:
3120 // If the load has a builtin retain, insert a plain retain for it.
3121 if (Class == IC_LoadWeakRetained) {
3123 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3127 // Zap the fully redundant load.
3128 Call->replaceAllUsesWith(EarlierCall);
3129 Call->eraseFromParent();
3131 case AliasAnalysis::MayAlias:
3132 case AliasAnalysis::PartialAlias:
3134 case AliasAnalysis::NoAlias:
3141 // If this is storing to the same pointer and has the same size etc.
3142 // replace this load's value with the stored value.
3143 CallInst *Call = cast<CallInst>(Inst);
3144 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3145 Value *Arg = Call->getArgOperand(0);
3146 Value *EarlierArg = EarlierCall->getArgOperand(0);
3147 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3148 case AliasAnalysis::MustAlias:
3150 // If the load has a builtin retain, insert a plain retain for it.
3151 if (Class == IC_LoadWeakRetained) {
3153 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3157 // Zap the fully redundant load.
3158 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
3159 Call->eraseFromParent();
3161 case AliasAnalysis::MayAlias:
3162 case AliasAnalysis::PartialAlias:
3164 case AliasAnalysis::NoAlias:
3171 // TOOD: Grab the copied value.
3173 case IC_AutoreleasepoolPush:
3176 // Weak pointers are only modified through the weak entry points
3177 // (and arbitrary calls, which could call the weak entry points).
3180 // Anything else could modify the weak pointer.
3187 // Then, for each destroyWeak with an alloca operand, check to see if
3188 // the alloca and all its users can be zapped.
3189 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3190 Instruction *Inst = &*I++;
3191 InstructionClass Class = GetBasicInstructionClass(Inst);
3192 if (Class != IC_DestroyWeak)
3195 CallInst *Call = cast<CallInst>(Inst);
3196 Value *Arg = Call->getArgOperand(0);
3197 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
3198 for (Value::use_iterator UI = Alloca->use_begin(),
3199 UE = Alloca->use_end(); UI != UE; ++UI) {
3200 Instruction *UserInst = cast<Instruction>(*UI);
3201 switch (GetBasicInstructionClass(UserInst)) {
3204 case IC_DestroyWeak:
3211 for (Value::use_iterator UI = Alloca->use_begin(),
3212 UE = Alloca->use_end(); UI != UE; ) {
3213 CallInst *UserInst = cast<CallInst>(*UI++);
3214 if (!UserInst->use_empty())
3215 UserInst->replaceAllUsesWith(UserInst->getArgOperand(0));
3216 UserInst->eraseFromParent();
3218 Alloca->eraseFromParent();
3224 /// OptimizeSequences - Identify program paths which execute sequences of
3225 /// retains and releases which can be eliminated.
3226 bool ObjCARCOpt::OptimizeSequences(Function &F) {
3227 /// Releases, Retains - These are used to store the results of the main flow
3228 /// analysis. These use Value* as the key instead of Instruction* so that the
3229 /// map stays valid when we get around to rewriting code and calls get
3230 /// replaced by arguments.
3231 DenseMap<Value *, RRInfo> Releases;
3232 MapVector<Value *, RRInfo> Retains;
3234 /// BBStates, This is used during the traversal of the function to track the
3235 /// states for each identified object at each block.
3236 DenseMap<const BasicBlock *, BBState> BBStates;
3238 // Analyze the CFG of the function, and all instructions.
3239 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
3242 return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) &&
3246 /// OptimizeReturns - Look for this pattern:
3248 /// %call = call i8* @something(...)
3249 /// %2 = call i8* @objc_retain(i8* %call)
3250 /// %3 = call i8* @objc_autorelease(i8* %2)
3253 /// And delete the retain and autorelease.
3255 /// Otherwise if it's just this:
3257 /// %3 = call i8* @objc_autorelease(i8* %2)
3260 /// convert the autorelease to autoreleaseRV.
3261 void ObjCARCOpt::OptimizeReturns(Function &F) {
3262 if (!F.getReturnType()->isPointerTy())
3265 SmallPtrSet<Instruction *, 4> DependingInstructions;
3266 SmallPtrSet<const BasicBlock *, 4> Visited;
3267 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3268 BasicBlock *BB = FI;
3269 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
3272 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
3273 FindDependencies(NeedsPositiveRetainCount, Arg,
3274 BB, Ret, DependingInstructions, Visited, PA);
3275 if (DependingInstructions.size() != 1)
3279 CallInst *Autorelease =
3280 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3283 InstructionClass AutoreleaseClass =
3284 GetBasicInstructionClass(Autorelease);
3285 if (!IsAutorelease(AutoreleaseClass))
3287 if (GetObjCArg(Autorelease) != Arg)
3290 DependingInstructions.clear();
3293 // Check that there is nothing that can affect the reference
3294 // count between the autorelease and the retain.
3295 FindDependencies(CanChangeRetainCount, Arg,
3296 BB, Autorelease, DependingInstructions, Visited, PA);
3297 if (DependingInstructions.size() != 1)
3302 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3304 // Check that we found a retain with the same argument.
3306 !IsRetain(GetBasicInstructionClass(Retain)) ||
3307 GetObjCArg(Retain) != Arg)
3310 DependingInstructions.clear();
3313 // Convert the autorelease to an autoreleaseRV, since it's
3314 // returning the value.
3315 if (AutoreleaseClass == IC_Autorelease) {
3316 Autorelease->setCalledFunction(getAutoreleaseRVCallee(F.getParent()));
3317 AutoreleaseClass = IC_AutoreleaseRV;
3320 // Check that there is nothing that can affect the reference
3321 // count between the retain and the call.
3322 // Note that Retain need not be in BB.
3323 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
3324 DependingInstructions, Visited, PA);
3325 if (DependingInstructions.size() != 1)
3330 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3332 // Check that the pointer is the return value of the call.
3333 if (!Call || Arg != Call)
3336 // Check that the call is a regular call.
3337 InstructionClass Class = GetBasicInstructionClass(Call);
3338 if (Class != IC_CallOrUser && Class != IC_Call)
3341 // If so, we can zap the retain and autorelease.
3344 EraseInstruction(Retain);
3345 EraseInstruction(Autorelease);
3351 DependingInstructions.clear();
3356 bool ObjCARCOpt::doInitialization(Module &M) {
3360 Run = ModuleHasARC(M);
3364 // Identify the imprecise release metadata kind.
3365 ImpreciseReleaseMDKind =
3366 M.getContext().getMDKindID("clang.imprecise_release");
3367 CopyOnEscapeMDKind =
3368 M.getContext().getMDKindID("clang.arc.copy_on_escape");
3370 // Intuitively, objc_retain and others are nocapture, however in practice
3371 // they are not, because they return their argument value. And objc_release
3372 // calls finalizers.
3374 // These are initialized lazily.
3376 AutoreleaseRVCallee = 0;
3379 RetainBlockCallee = 0;
3380 AutoreleaseCallee = 0;
3385 bool ObjCARCOpt::runOnFunction(Function &F) {
3389 // If nothing in the Module uses ARC, don't do anything.
3395 PA.setAA(&getAnalysis<AliasAnalysis>());
3397 // This pass performs several distinct transformations. As a compile-time aid
3398 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3399 // library functions aren't declared.
3401 // Preliminary optimizations. This also computs UsedInThisFunction.
3402 OptimizeIndividualCalls(F);
3404 // Optimizations for weak pointers.
3405 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3406 (1 << IC_LoadWeakRetained) |
3407 (1 << IC_StoreWeak) |
3408 (1 << IC_InitWeak) |
3409 (1 << IC_CopyWeak) |
3410 (1 << IC_MoveWeak) |
3411 (1 << IC_DestroyWeak)))
3412 OptimizeWeakCalls(F);
3414 // Optimizations for retain+release pairs.
3415 if (UsedInThisFunction & ((1 << IC_Retain) |
3416 (1 << IC_RetainRV) |
3417 (1 << IC_RetainBlock)))
3418 if (UsedInThisFunction & (1 << IC_Release))
3419 // Run OptimizeSequences until it either stops making changes or
3420 // no retain+release pair nesting is detected.
3421 while (OptimizeSequences(F)) {}
3423 // Optimizations if objc_autorelease is used.
3424 if (UsedInThisFunction &
3425 ((1 << IC_Autorelease) | (1 << IC_AutoreleaseRV)))
3431 void ObjCARCOpt::releaseMemory() {
3435 //===----------------------------------------------------------------------===//
3437 //===----------------------------------------------------------------------===//
3439 // TODO: ObjCARCContract could insert PHI nodes when uses aren't
3440 // dominated by single calls.
3442 #include "llvm/Operator.h"
3443 #include "llvm/InlineAsm.h"
3444 #include "llvm/Analysis/Dominators.h"
3446 STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed");
3449 /// ObjCARCContract - Late ARC optimizations. These change the IR in a way
3450 /// that makes it difficult to be analyzed by ObjCARCOpt, so it's run late.
3451 class ObjCARCContract : public FunctionPass {
3455 ProvenanceAnalysis PA;
3457 /// Run - A flag indicating whether this optimization pass should run.
3460 /// StoreStrongCallee, etc. - Declarations for ObjC runtime
3461 /// functions, for use in creating calls to them. These are initialized
3462 /// lazily to avoid cluttering up the Module with unused declarations.
3463 Constant *StoreStrongCallee,
3464 *RetainAutoreleaseCallee, *RetainAutoreleaseRVCallee;
3466 /// RetainRVMarker - The inline asm string to insert between calls and
3467 /// RetainRV calls to make the optimization work on targets which need it.
3468 const MDString *RetainRVMarker;
3470 Constant *getStoreStrongCallee(Module *M);
3471 Constant *getRetainAutoreleaseCallee(Module *M);
3472 Constant *getRetainAutoreleaseRVCallee(Module *M);
3474 bool ContractAutorelease(Function &F, Instruction *Autorelease,
3475 InstructionClass Class,
3476 SmallPtrSet<Instruction *, 4>
3477 &DependingInstructions,
3478 SmallPtrSet<const BasicBlock *, 4>
3481 void ContractRelease(Instruction *Release,
3482 inst_iterator &Iter);
3484 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
3485 virtual bool doInitialization(Module &M);
3486 virtual bool runOnFunction(Function &F);
3490 ObjCARCContract() : FunctionPass(ID) {
3491 initializeObjCARCContractPass(*PassRegistry::getPassRegistry());
3496 char ObjCARCContract::ID = 0;
3497 INITIALIZE_PASS_BEGIN(ObjCARCContract,
3498 "objc-arc-contract", "ObjC ARC contraction", false, false)
3499 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3500 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
3501 INITIALIZE_PASS_END(ObjCARCContract,
3502 "objc-arc-contract", "ObjC ARC contraction", false, false)
3504 Pass *llvm::createObjCARCContractPass() {
3505 return new ObjCARCContract();
3508 void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const {
3509 AU.addRequired<AliasAnalysis>();
3510 AU.addRequired<DominatorTree>();
3511 AU.setPreservesCFG();
3514 Constant *ObjCARCContract::getStoreStrongCallee(Module *M) {
3515 if (!StoreStrongCallee) {
3516 LLVMContext &C = M->getContext();
3517 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3518 Type *I8XX = PointerType::getUnqual(I8X);
3519 std::vector<Type *> Params;
3520 Params.push_back(I8XX);
3521 Params.push_back(I8X);
3523 AttrListPtr Attributes;
3524 Attributes.addAttr(~0u, Attribute::NoUnwind);
3525 Attributes.addAttr(1, Attribute::NoCapture);
3528 M->getOrInsertFunction(
3530 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
3533 return StoreStrongCallee;
3536 Constant *ObjCARCContract::getRetainAutoreleaseCallee(Module *M) {
3537 if (!RetainAutoreleaseCallee) {
3538 LLVMContext &C = M->getContext();
3539 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3540 std::vector<Type *> Params;
3541 Params.push_back(I8X);
3543 FunctionType::get(I8X, Params, /*isVarArg=*/false);
3544 AttrListPtr Attributes;
3545 Attributes.addAttr(~0u, Attribute::NoUnwind);
3546 RetainAutoreleaseCallee =
3547 M->getOrInsertFunction("objc_retainAutorelease", FTy, Attributes);
3549 return RetainAutoreleaseCallee;
3552 Constant *ObjCARCContract::getRetainAutoreleaseRVCallee(Module *M) {
3553 if (!RetainAutoreleaseRVCallee) {
3554 LLVMContext &C = M->getContext();
3555 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3556 std::vector<Type *> Params;
3557 Params.push_back(I8X);
3559 FunctionType::get(I8X, Params, /*isVarArg=*/false);
3560 AttrListPtr Attributes;
3561 Attributes.addAttr(~0u, Attribute::NoUnwind);
3562 RetainAutoreleaseRVCallee =
3563 M->getOrInsertFunction("objc_retainAutoreleaseReturnValue", FTy,
3566 return RetainAutoreleaseRVCallee;
3569 /// ContractAutorelease - Merge an autorelease with a retain into a fused
3572 ObjCARCContract::ContractAutorelease(Function &F, Instruction *Autorelease,
3573 InstructionClass Class,
3574 SmallPtrSet<Instruction *, 4>
3575 &DependingInstructions,
3576 SmallPtrSet<const BasicBlock *, 4>
3578 const Value *Arg = GetObjCArg(Autorelease);
3580 // Check that there are no instructions between the retain and the autorelease
3581 // (such as an autorelease_pop) which may change the count.
3582 CallInst *Retain = 0;
3583 if (Class == IC_AutoreleaseRV)
3584 FindDependencies(RetainAutoreleaseRVDep, Arg,
3585 Autorelease->getParent(), Autorelease,
3586 DependingInstructions, Visited, PA);
3588 FindDependencies(RetainAutoreleaseDep, Arg,
3589 Autorelease->getParent(), Autorelease,
3590 DependingInstructions, Visited, PA);
3593 if (DependingInstructions.size() != 1) {
3594 DependingInstructions.clear();
3598 Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3599 DependingInstructions.clear();
3602 GetBasicInstructionClass(Retain) != IC_Retain ||
3603 GetObjCArg(Retain) != Arg)
3609 if (Class == IC_AutoreleaseRV)
3610 Retain->setCalledFunction(getRetainAutoreleaseRVCallee(F.getParent()));
3612 Retain->setCalledFunction(getRetainAutoreleaseCallee(F.getParent()));
3614 EraseInstruction(Autorelease);
3618 /// ContractRelease - Attempt to merge an objc_release with a store, load, and
3619 /// objc_retain to form an objc_storeStrong. This can be a little tricky because
3620 /// the instructions don't always appear in order, and there may be unrelated
3621 /// intervening instructions.
3622 void ObjCARCContract::ContractRelease(Instruction *Release,
3623 inst_iterator &Iter) {
3624 LoadInst *Load = dyn_cast<LoadInst>(GetObjCArg(Release));
3625 if (!Load || !Load->isSimple()) return;
3627 // For now, require everything to be in one basic block.
3628 BasicBlock *BB = Release->getParent();
3629 if (Load->getParent() != BB) return;
3631 // Walk down to find the store.
3632 BasicBlock::iterator I = Load, End = BB->end();
3634 AliasAnalysis::Location Loc = AA->getLocation(Load);
3637 IsRetain(GetBasicInstructionClass(I)) ||
3638 !(AA->getModRefInfo(I, Loc) & AliasAnalysis::Mod)))
3640 StoreInst *Store = dyn_cast<StoreInst>(I);
3641 if (!Store || !Store->isSimple()) return;
3642 if (Store->getPointerOperand() != Loc.Ptr) return;
3644 Value *New = StripPointerCastsAndObjCCalls(Store->getValueOperand());
3646 // Walk up to find the retain.
3648 BasicBlock::iterator Begin = BB->begin();
3649 while (I != Begin && GetBasicInstructionClass(I) != IC_Retain)
3651 Instruction *Retain = I;
3652 if (GetBasicInstructionClass(Retain) != IC_Retain) return;
3653 if (GetObjCArg(Retain) != New) return;
3658 LLVMContext &C = Release->getContext();
3659 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3660 Type *I8XX = PointerType::getUnqual(I8X);
3662 Value *Args[] = { Load->getPointerOperand(), New };
3663 if (Args[0]->getType() != I8XX)
3664 Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
3665 if (Args[1]->getType() != I8X)
3666 Args[1] = new BitCastInst(Args[1], I8X, "", Store);
3667 CallInst *StoreStrong =
3668 CallInst::Create(getStoreStrongCallee(BB->getParent()->getParent()),
3670 StoreStrong->setDoesNotThrow();
3671 StoreStrong->setDebugLoc(Store->getDebugLoc());
3673 if (&*Iter == Store) ++Iter;
3674 Store->eraseFromParent();
3675 Release->eraseFromParent();
3676 EraseInstruction(Retain);
3677 if (Load->use_empty())
3678 Load->eraseFromParent();
3681 bool ObjCARCContract::doInitialization(Module &M) {
3682 Run = ModuleHasARC(M);
3686 // These are initialized lazily.
3687 StoreStrongCallee = 0;
3688 RetainAutoreleaseCallee = 0;
3689 RetainAutoreleaseRVCallee = 0;
3691 // Initialize RetainRVMarker.
3693 if (NamedMDNode *NMD =
3694 M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker"))
3695 if (NMD->getNumOperands() == 1) {
3696 const MDNode *N = NMD->getOperand(0);
3697 if (N->getNumOperands() == 1)
3698 if (const MDString *S = dyn_cast<MDString>(N->getOperand(0)))
3705 bool ObjCARCContract::runOnFunction(Function &F) {
3709 // If nothing in the Module uses ARC, don't do anything.
3714 AA = &getAnalysis<AliasAnalysis>();
3715 DT = &getAnalysis<DominatorTree>();
3717 PA.setAA(&getAnalysis<AliasAnalysis>());
3719 // For ObjC library calls which return their argument, replace uses of the
3720 // argument with uses of the call return value, if it dominates the use. This
3721 // reduces register pressure.
3722 SmallPtrSet<Instruction *, 4> DependingInstructions;
3723 SmallPtrSet<const BasicBlock *, 4> Visited;
3724 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3725 Instruction *Inst = &*I++;
3727 // Only these library routines return their argument. In particular,
3728 // objc_retainBlock does not necessarily return its argument.
3729 InstructionClass Class = GetBasicInstructionClass(Inst);
3732 case IC_FusedRetainAutorelease:
3733 case IC_FusedRetainAutoreleaseRV:
3735 case IC_Autorelease:
3736 case IC_AutoreleaseRV:
3737 if (ContractAutorelease(F, Inst, Class, DependingInstructions, Visited))
3741 // If we're compiling for a target which needs a special inline-asm
3742 // marker to do the retainAutoreleasedReturnValue optimization,
3744 if (!RetainRVMarker)
3746 BasicBlock::iterator BBI = Inst;
3748 while (isNoopInstruction(BBI)) --BBI;
3749 if (&*BBI == GetObjCArg(Inst)) {
3751 InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()),
3752 /*isVarArg=*/false),
3753 RetainRVMarker->getString(),
3754 /*Constraints=*/"", /*hasSideEffects=*/true);
3755 CallInst::Create(IA, "", Inst);
3760 // objc_initWeak(p, null) => *p = null
3761 CallInst *CI = cast<CallInst>(Inst);
3762 if (isNullOrUndef(CI->getArgOperand(1))) {
3764 ConstantPointerNull::get(cast<PointerType>(CI->getType()));
3766 new StoreInst(Null, CI->getArgOperand(0), CI);
3767 CI->replaceAllUsesWith(Null);
3768 CI->eraseFromParent();
3773 ContractRelease(Inst, I);
3779 // Don't use GetObjCArg because we don't want to look through bitcasts
3780 // and such; to do the replacement, the argument must have type i8*.
3781 const Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
3783 // If we're compiling bugpointed code, don't get in trouble.
3784 if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
3786 // Look through the uses of the pointer.
3787 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
3789 Use &U = UI.getUse();
3790 unsigned OperandNo = UI.getOperandNo();
3791 ++UI; // Increment UI now, because we may unlink its element.
3792 if (Instruction *UserInst = dyn_cast<Instruction>(U.getUser()))
3793 if (Inst != UserInst && DT->dominates(Inst, UserInst)) {
3795 Instruction *Replacement = Inst;
3796 Type *UseTy = U.get()->getType();
3797 if (PHINode *PHI = dyn_cast<PHINode>(UserInst)) {
3798 // For PHI nodes, insert the bitcast in the predecessor block.
3800 PHINode::getIncomingValueNumForOperand(OperandNo);
3802 PHI->getIncomingBlock(ValNo);
3803 if (Replacement->getType() != UseTy)
3804 Replacement = new BitCastInst(Replacement, UseTy, "",
3806 for (unsigned i = 0, e = PHI->getNumIncomingValues();
3808 if (PHI->getIncomingBlock(i) == BB) {
3809 // Keep the UI iterator valid.
3810 if (&PHI->getOperandUse(
3811 PHINode::getOperandNumForIncomingValue(i)) ==
3814 PHI->setIncomingValue(i, Replacement);
3817 if (Replacement->getType() != UseTy)
3818 Replacement = new BitCastInst(Replacement, UseTy, "", UserInst);
3824 // If Arg is a no-op casted pointer, strip one level of casts and
3826 if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
3827 Arg = BI->getOperand(0);
3828 else if (isa<GEPOperator>(Arg) &&
3829 cast<GEPOperator>(Arg)->hasAllZeroIndices())
3830 Arg = cast<GEPOperator>(Arg)->getPointerOperand();
3831 else if (isa<GlobalAlias>(Arg) &&
3832 !cast<GlobalAlias>(Arg)->mayBeOverridden())
3833 Arg = cast<GlobalAlias>(Arg)->getAliasee();