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 //===----------------------------------------------------------------------===//
605 // ARC AliasAnalysis.
606 //===----------------------------------------------------------------------===//
608 #include "llvm/Pass.h"
609 #include "llvm/Analysis/AliasAnalysis.h"
610 #include "llvm/Analysis/Passes.h"
613 /// ObjCARCAliasAnalysis - This is a simple alias analysis
614 /// implementation that uses knowledge of ARC constructs to answer queries.
616 /// TODO: This class could be generalized to know about other ObjC-specific
617 /// tricks. Such as knowing that ivars in the non-fragile ABI are non-aliasing
618 /// even though their offsets are dynamic.
619 class ObjCARCAliasAnalysis : public ImmutablePass,
620 public AliasAnalysis {
622 static char ID; // Class identification, replacement for typeinfo
623 ObjCARCAliasAnalysis() : ImmutablePass(ID) {
624 initializeObjCARCAliasAnalysisPass(*PassRegistry::getPassRegistry());
628 virtual void initializePass() {
629 InitializeAliasAnalysis(this);
632 /// getAdjustedAnalysisPointer - This method is used when a pass implements
633 /// an analysis interface through multiple inheritance. If needed, it
634 /// should override this to adjust the this pointer as needed for the
635 /// specified pass info.
636 virtual void *getAdjustedAnalysisPointer(const void *PI) {
637 if (PI == &AliasAnalysis::ID)
638 return (AliasAnalysis*)this;
642 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
643 virtual AliasResult alias(const Location &LocA, const Location &LocB);
644 virtual bool pointsToConstantMemory(const Location &Loc, bool OrLocal);
645 virtual ModRefBehavior getModRefBehavior(ImmutableCallSite CS);
646 virtual ModRefBehavior getModRefBehavior(const Function *F);
647 virtual ModRefResult getModRefInfo(ImmutableCallSite CS,
648 const Location &Loc);
649 virtual ModRefResult getModRefInfo(ImmutableCallSite CS1,
650 ImmutableCallSite CS2);
652 } // End of anonymous namespace
654 // Register this pass...
655 char ObjCARCAliasAnalysis::ID = 0;
656 INITIALIZE_AG_PASS(ObjCARCAliasAnalysis, AliasAnalysis, "objc-arc-aa",
657 "ObjC-ARC-Based Alias Analysis", false, true, false)
659 ImmutablePass *llvm::createObjCARCAliasAnalysisPass() {
660 return new ObjCARCAliasAnalysis();
664 ObjCARCAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
665 AU.setPreservesAll();
666 AliasAnalysis::getAnalysisUsage(AU);
669 AliasAnalysis::AliasResult
670 ObjCARCAliasAnalysis::alias(const Location &LocA, const Location &LocB) {
672 return AliasAnalysis::alias(LocA, LocB);
674 // First, strip off no-ops, including ObjC-specific no-ops, and try making a
675 // precise alias query.
676 const Value *SA = StripPointerCastsAndObjCCalls(LocA.Ptr);
677 const Value *SB = StripPointerCastsAndObjCCalls(LocB.Ptr);
679 AliasAnalysis::alias(Location(SA, LocA.Size, LocA.TBAATag),
680 Location(SB, LocB.Size, LocB.TBAATag));
681 if (Result != MayAlias)
684 // If that failed, climb to the underlying object, including climbing through
685 // ObjC-specific no-ops, and try making an imprecise alias query.
686 const Value *UA = GetUnderlyingObjCPtr(SA);
687 const Value *UB = GetUnderlyingObjCPtr(SB);
688 if (UA != SA || UB != SB) {
689 Result = AliasAnalysis::alias(Location(UA), Location(UB));
690 // We can't use MustAlias or PartialAlias results here because
691 // GetUnderlyingObjCPtr may return an offsetted pointer value.
692 if (Result == NoAlias)
696 // If that failed, fail. We don't need to chain here, since that's covered
697 // by the earlier precise query.
702 ObjCARCAliasAnalysis::pointsToConstantMemory(const Location &Loc,
705 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
707 // First, strip off no-ops, including ObjC-specific no-ops, and try making
708 // a precise alias query.
709 const Value *S = StripPointerCastsAndObjCCalls(Loc.Ptr);
710 if (AliasAnalysis::pointsToConstantMemory(Location(S, Loc.Size, Loc.TBAATag),
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 *U = GetUnderlyingObjCPtr(S);
718 return AliasAnalysis::pointsToConstantMemory(Location(U), OrLocal);
720 // If that failed, fail. We don't need to chain here, since that's covered
721 // by the earlier precise query.
725 AliasAnalysis::ModRefBehavior
726 ObjCARCAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
727 // We have nothing to do. Just chain to the next AliasAnalysis.
728 return AliasAnalysis::getModRefBehavior(CS);
731 AliasAnalysis::ModRefBehavior
732 ObjCARCAliasAnalysis::getModRefBehavior(const Function *F) {
734 return AliasAnalysis::getModRefBehavior(F);
736 switch (GetFunctionClass(F)) {
738 return DoesNotAccessMemory;
743 return AliasAnalysis::getModRefBehavior(F);
746 AliasAnalysis::ModRefResult
747 ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS, const Location &Loc) {
749 return AliasAnalysis::getModRefInfo(CS, Loc);
751 switch (GetBasicInstructionClass(CS.getInstruction())) {
755 case IC_AutoreleaseRV:
757 case IC_AutoreleasepoolPush:
758 case IC_FusedRetainAutorelease:
759 case IC_FusedRetainAutoreleaseRV:
760 // These functions don't access any memory visible to the compiler.
761 // Note that this doesn't include objc_retainBlock, becuase it updates
762 // pointers when it copies block data.
768 return AliasAnalysis::getModRefInfo(CS, Loc);
771 AliasAnalysis::ModRefResult
772 ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
773 ImmutableCallSite CS2) {
774 // TODO: Theoretically we could check for dependencies between objc_* calls
775 // and OnlyAccessesArgumentPointees calls or other well-behaved calls.
776 return AliasAnalysis::getModRefInfo(CS1, CS2);
779 //===----------------------------------------------------------------------===//
781 //===----------------------------------------------------------------------===//
783 #include "llvm/Support/InstIterator.h"
784 #include "llvm/Transforms/Scalar.h"
787 /// ObjCARCExpand - Early ARC transformations.
788 class ObjCARCExpand : public FunctionPass {
789 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
790 virtual bool doInitialization(Module &M);
791 virtual bool runOnFunction(Function &F);
793 /// Run - A flag indicating whether this optimization pass should run.
798 ObjCARCExpand() : FunctionPass(ID) {
799 initializeObjCARCExpandPass(*PassRegistry::getPassRegistry());
804 char ObjCARCExpand::ID = 0;
805 INITIALIZE_PASS(ObjCARCExpand,
806 "objc-arc-expand", "ObjC ARC expansion", false, false)
808 Pass *llvm::createObjCARCExpandPass() {
809 return new ObjCARCExpand();
812 void ObjCARCExpand::getAnalysisUsage(AnalysisUsage &AU) const {
813 AU.setPreservesCFG();
816 bool ObjCARCExpand::doInitialization(Module &M) {
817 Run = ModuleHasARC(M);
821 bool ObjCARCExpand::runOnFunction(Function &F) {
825 // If nothing in the Module uses ARC, don't do anything.
829 bool Changed = false;
831 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
832 Instruction *Inst = &*I;
834 switch (GetBasicInstructionClass(Inst)) {
838 case IC_AutoreleaseRV:
839 case IC_FusedRetainAutorelease:
840 case IC_FusedRetainAutoreleaseRV:
841 // These calls return their argument verbatim, as a low-level
842 // optimization. However, this makes high-level optimizations
843 // harder. Undo any uses of this optimization that the front-end
844 // emitted here. We'll redo them in a later pass.
846 Inst->replaceAllUsesWith(cast<CallInst>(Inst)->getArgOperand(0));
856 //===----------------------------------------------------------------------===//
858 //===----------------------------------------------------------------------===//
860 // TODO: On code like this:
863 // stuff_that_cannot_release()
864 // objc_autorelease(%x)
865 // stuff_that_cannot_release()
867 // stuff_that_cannot_release()
868 // objc_autorelease(%x)
870 // The second retain and autorelease can be deleted.
872 // TODO: It should be possible to delete
873 // objc_autoreleasePoolPush and objc_autoreleasePoolPop
874 // pairs if nothing is actually autoreleased between them. Also, autorelease
875 // calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
876 // after inlining) can be turned into plain release calls.
878 // TODO: Critical-edge splitting. If the optimial insertion point is
879 // a critical edge, the current algorithm has to fail, because it doesn't
880 // know how to split edges. It should be possible to make the optimizer
881 // think in terms of edges, rather than blocks, and then split critical
884 // TODO: OptimizeSequences could generalized to be Interprocedural.
886 // TODO: Recognize that a bunch of other objc runtime calls have
887 // non-escaping arguments and non-releasing arguments, and may be
888 // non-autoreleasing.
890 // TODO: Sink autorelease calls as far as possible. Unfortunately we
891 // usually can't sink them past other calls, which would be the main
892 // case where it would be useful.
894 // TODO: The pointer returned from objc_loadWeakRetained is retained.
896 // TODO: Delete release+retain pairs (rare).
898 #include "llvm/GlobalAlias.h"
899 #include "llvm/Constants.h"
900 #include "llvm/LLVMContext.h"
901 #include "llvm/Support/ErrorHandling.h"
902 #include "llvm/Support/CFG.h"
903 #include "llvm/ADT/Statistic.h"
904 #include "llvm/ADT/SmallPtrSet.h"
905 #include "llvm/ADT/DenseSet.h"
907 STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
908 STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
909 STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
910 STATISTIC(NumRets, "Number of return value forwarding "
911 "retain+autoreleaes eliminated");
912 STATISTIC(NumRRs, "Number of retain+release paths eliminated");
913 STATISTIC(NumPeeps, "Number of calls peephole-optimized");
916 /// ProvenanceAnalysis - This is similar to BasicAliasAnalysis, and it
917 /// uses many of the same techniques, except it uses special ObjC-specific
918 /// reasoning about pointer relationships.
919 class ProvenanceAnalysis {
922 typedef std::pair<const Value *, const Value *> ValuePairTy;
923 typedef DenseMap<ValuePairTy, bool> CachedResultsTy;
924 CachedResultsTy CachedResults;
926 bool relatedCheck(const Value *A, const Value *B);
927 bool relatedSelect(const SelectInst *A, const Value *B);
928 bool relatedPHI(const PHINode *A, const Value *B);
931 void operator=(const ProvenanceAnalysis &);
932 ProvenanceAnalysis(const ProvenanceAnalysis &);
935 ProvenanceAnalysis() {}
937 void setAA(AliasAnalysis *aa) { AA = aa; }
939 AliasAnalysis *getAA() const { return AA; }
941 bool related(const Value *A, const Value *B);
944 CachedResults.clear();
949 bool ProvenanceAnalysis::relatedSelect(const SelectInst *A, const Value *B) {
950 // If the values are Selects with the same condition, we can do a more precise
951 // check: just check for relations between the values on corresponding arms.
952 if (const SelectInst *SB = dyn_cast<SelectInst>(B))
953 if (A->getCondition() == SB->getCondition()) {
954 if (related(A->getTrueValue(), SB->getTrueValue()))
956 if (related(A->getFalseValue(), SB->getFalseValue()))
961 // Check both arms of the Select node individually.
962 if (related(A->getTrueValue(), B))
964 if (related(A->getFalseValue(), B))
967 // The arms both checked out.
971 bool ProvenanceAnalysis::relatedPHI(const PHINode *A, const Value *B) {
972 // If the values are PHIs in the same block, we can do a more precise as well
973 // as efficient check: just check for relations between the values on
974 // corresponding edges.
975 if (const PHINode *PNB = dyn_cast<PHINode>(B))
976 if (PNB->getParent() == A->getParent()) {
977 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i)
978 if (related(A->getIncomingValue(i),
979 PNB->getIncomingValueForBlock(A->getIncomingBlock(i))))
984 // Check each unique source of the PHI node against B.
985 SmallPtrSet<const Value *, 4> UniqueSrc;
986 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i) {
987 const Value *PV1 = A->getIncomingValue(i);
988 if (UniqueSrc.insert(PV1) && related(PV1, B))
992 // All of the arms checked out.
996 /// isStoredObjCPointer - Test if the value of P, or any value covered by its
997 /// provenance, is ever stored within the function (not counting callees).
998 static bool isStoredObjCPointer(const Value *P) {
999 SmallPtrSet<const Value *, 8> Visited;
1000 SmallVector<const Value *, 8> Worklist;
1001 Worklist.push_back(P);
1004 P = Worklist.pop_back_val();
1005 for (Value::const_use_iterator UI = P->use_begin(), UE = P->use_end();
1007 const User *Ur = *UI;
1008 if (isa<StoreInst>(Ur)) {
1009 if (UI.getOperandNo() == 0)
1010 // The pointer is stored.
1012 // The pointed is stored through.
1015 if (isa<CallInst>(Ur))
1016 // The pointer is passed as an argument, ignore this.
1018 if (isa<PtrToIntInst>(P))
1019 // Assume the worst.
1021 if (Visited.insert(Ur))
1022 Worklist.push_back(Ur);
1024 } while (!Worklist.empty());
1026 // Everything checked out.
1030 bool ProvenanceAnalysis::relatedCheck(const Value *A, const Value *B) {
1031 // Skip past provenance pass-throughs.
1032 A = GetUnderlyingObjCPtr(A);
1033 B = GetUnderlyingObjCPtr(B);
1039 // Ask regular AliasAnalysis, for a first approximation.
1040 switch (AA->alias(A, B)) {
1041 case AliasAnalysis::NoAlias:
1043 case AliasAnalysis::MustAlias:
1044 case AliasAnalysis::PartialAlias:
1046 case AliasAnalysis::MayAlias:
1050 bool AIsIdentified = IsObjCIdentifiedObject(A);
1051 bool BIsIdentified = IsObjCIdentifiedObject(B);
1053 // An ObjC-Identified object can't alias a load if it is never locally stored.
1054 if (AIsIdentified) {
1055 if (BIsIdentified) {
1056 // If both pointers have provenance, they can be directly compared.
1060 if (isa<LoadInst>(B))
1061 return isStoredObjCPointer(A);
1064 if (BIsIdentified && isa<LoadInst>(A))
1065 return isStoredObjCPointer(B);
1068 // Special handling for PHI and Select.
1069 if (const PHINode *PN = dyn_cast<PHINode>(A))
1070 return relatedPHI(PN, B);
1071 if (const PHINode *PN = dyn_cast<PHINode>(B))
1072 return relatedPHI(PN, A);
1073 if (const SelectInst *S = dyn_cast<SelectInst>(A))
1074 return relatedSelect(S, B);
1075 if (const SelectInst *S = dyn_cast<SelectInst>(B))
1076 return relatedSelect(S, A);
1082 bool ProvenanceAnalysis::related(const Value *A, const Value *B) {
1083 // Begin by inserting a conservative value into the map. If the insertion
1084 // fails, we have the answer already. If it succeeds, leave it there until we
1085 // compute the real answer to guard against recursive queries.
1086 if (A > B) std::swap(A, B);
1087 std::pair<CachedResultsTy::iterator, bool> Pair =
1088 CachedResults.insert(std::make_pair(ValuePairTy(A, B), true));
1090 return Pair.first->second;
1092 bool Result = relatedCheck(A, B);
1093 CachedResults[ValuePairTy(A, B)] = Result;
1098 // Sequence - A sequence of states that a pointer may go through in which an
1099 // objc_retain and objc_release are actually needed.
1102 S_Retain, ///< objc_retain(x)
1103 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement
1104 S_Use, ///< any use of x
1105 S_Stop, ///< like S_Release, but code motion is stopped
1106 S_Release, ///< objc_release(x)
1107 S_MovableRelease ///< objc_release(x), !clang.imprecise_release
1111 static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
1115 if (A == S_None || B == S_None)
1118 if (A > B) std::swap(A, B);
1120 // Choose the side which is further along in the sequence.
1121 if ((A == S_Retain || A == S_CanRelease) &&
1122 (B == S_CanRelease || B == S_Use))
1125 // Choose the side which is further along in the sequence.
1126 if ((A == S_Use || A == S_CanRelease) &&
1127 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
1129 // If both sides are releases, choose the more conservative one.
1130 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
1132 if (A == S_Release && B == S_MovableRelease)
1140 /// RRInfo - Unidirectional information about either a
1141 /// retain-decrement-use-release sequence or release-use-decrement-retain
1142 /// reverese sequence.
1144 /// KnownSafe - After an objc_retain, the reference count of the referenced
1145 /// object is known to be positive. Similarly, before an objc_release, the
1146 /// reference count of the referenced object is known to be positive. If
1147 /// there are retain-release pairs in code regions where the retain count
1148 /// is known to be positive, they can be eliminated, regardless of any side
1149 /// effects between them.
1151 /// Also, a retain+release pair nested within another retain+release
1152 /// pair all on the known same pointer value can be eliminated, regardless
1153 /// of any intervening side effects.
1155 /// KnownSafe is true when either of these conditions is satisfied.
1158 /// IsRetainBlock - True if the Calls are objc_retainBlock calls (as
1159 /// opposed to objc_retain calls).
1162 /// CopyOnEscape - True if this the Calls are objc_retainBlock calls
1163 /// which all have the !clang.arc.copy_on_escape metadata.
1166 /// IsTailCallRelease - True of the objc_release calls are all marked
1167 /// with the "tail" keyword.
1168 bool IsTailCallRelease;
1170 /// Partial - True of we've seen an opportunity for partial RR elimination,
1171 /// such as pushing calls into a CFG triangle or into one side of a
1173 /// TODO: Consider moving this to PtrState.
1176 /// ReleaseMetadata - If the Calls are objc_release calls and they all have
1177 /// a clang.imprecise_release tag, this is the metadata tag.
1178 MDNode *ReleaseMetadata;
1180 /// Calls - For a top-down sequence, the set of objc_retains or
1181 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
1182 SmallPtrSet<Instruction *, 2> Calls;
1184 /// ReverseInsertPts - The set of optimal insert positions for
1185 /// moving calls in the opposite sequence.
1186 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
1189 KnownSafe(false), IsRetainBlock(false), CopyOnEscape(false),
1190 IsTailCallRelease(false), Partial(false),
1191 ReleaseMetadata(0) {}
1197 void RRInfo::clear() {
1199 IsRetainBlock = false;
1200 CopyOnEscape = false;
1201 IsTailCallRelease = false;
1203 ReleaseMetadata = 0;
1205 ReverseInsertPts.clear();
1209 /// PtrState - This class summarizes several per-pointer runtime properties
1210 /// which are propogated through the flow graph.
1212 /// RefCount - The known minimum number of reference count increments.
1215 /// NestCount - The known minimum level of retain+release nesting.
1218 /// Seq - The current position in the sequence.
1222 /// RRI - Unidirectional information about the current sequence.
1223 /// TODO: Encapsulate this better.
1226 PtrState() : RefCount(0), NestCount(0), Seq(S_None) {}
1228 void SetAtLeastOneRefCount() {
1229 if (RefCount == 0) RefCount = 1;
1232 void IncrementRefCount() {
1233 if (RefCount != UINT_MAX) ++RefCount;
1236 void DecrementRefCount() {
1237 if (RefCount != 0) --RefCount;
1240 bool IsKnownIncremented() const {
1241 return RefCount > 0;
1244 void IncrementNestCount() {
1245 if (NestCount != UINT_MAX) ++NestCount;
1248 void DecrementNestCount() {
1249 if (NestCount != 0) --NestCount;
1252 bool IsKnownNested() const {
1253 return NestCount > 0;
1256 void SetSeq(Sequence NewSeq) {
1260 Sequence GetSeq() const {
1264 void ClearSequenceProgress() {
1269 void Merge(const PtrState &Other, bool TopDown);
1274 PtrState::Merge(const PtrState &Other, bool TopDown) {
1275 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
1276 RefCount = std::min(RefCount, Other.RefCount);
1277 NestCount = std::min(NestCount, Other.NestCount);
1279 // We can't merge a plain objc_retain with an objc_retainBlock.
1280 if (RRI.IsRetainBlock != Other.RRI.IsRetainBlock)
1283 // If we're not in a sequence (anymore), drop all associated state.
1284 if (Seq == S_None) {
1286 } else if (RRI.Partial || Other.RRI.Partial) {
1287 // If we're doing a merge on a path that's previously seen a partial
1288 // merge, conservatively drop the sequence, to avoid doing partial
1289 // RR elimination. If the branch predicates for the two merge differ,
1290 // mixing them is unsafe.
1294 // Conservatively merge the ReleaseMetadata information.
1295 if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
1296 RRI.ReleaseMetadata = 0;
1298 RRI.CopyOnEscape = RRI.CopyOnEscape && Other.RRI.CopyOnEscape;
1299 RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
1300 RRI.IsTailCallRelease = RRI.IsTailCallRelease && Other.RRI.IsTailCallRelease;
1301 RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
1303 // Merge the insert point sets. If there are any differences,
1304 // that makes this a partial merge.
1305 RRI.Partial = RRI.ReverseInsertPts.size() !=
1306 Other.RRI.ReverseInsertPts.size();
1307 for (SmallPtrSet<Instruction *, 2>::const_iterator
1308 I = Other.RRI.ReverseInsertPts.begin(),
1309 E = Other.RRI.ReverseInsertPts.end(); I != E; ++I)
1310 RRI.Partial |= RRI.ReverseInsertPts.insert(*I);
1315 /// BBState - Per-BasicBlock state.
1317 /// TopDownPathCount - The number of unique control paths from the entry
1318 /// which can reach this block.
1319 unsigned TopDownPathCount;
1321 /// BottomUpPathCount - The number of unique control paths to exits
1322 /// from this block.
1323 unsigned BottomUpPathCount;
1325 /// MapTy - A type for PerPtrTopDown and PerPtrBottomUp.
1326 typedef MapVector<const Value *, PtrState> MapTy;
1328 /// PerPtrTopDown - The top-down traversal uses this to record information
1329 /// known about a pointer at the bottom of each block.
1330 MapTy PerPtrTopDown;
1332 /// PerPtrBottomUp - The bottom-up traversal uses this to record information
1333 /// known about a pointer at the top of each block.
1334 MapTy PerPtrBottomUp;
1337 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
1339 typedef MapTy::iterator ptr_iterator;
1340 typedef MapTy::const_iterator ptr_const_iterator;
1342 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
1343 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
1344 ptr_const_iterator top_down_ptr_begin() const {
1345 return PerPtrTopDown.begin();
1347 ptr_const_iterator top_down_ptr_end() const {
1348 return PerPtrTopDown.end();
1351 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
1352 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
1353 ptr_const_iterator bottom_up_ptr_begin() const {
1354 return PerPtrBottomUp.begin();
1356 ptr_const_iterator bottom_up_ptr_end() const {
1357 return PerPtrBottomUp.end();
1360 /// SetAsEntry - Mark this block as being an entry block, which has one
1361 /// path from the entry by definition.
1362 void SetAsEntry() { TopDownPathCount = 1; }
1364 /// SetAsExit - Mark this block as being an exit block, which has one
1365 /// path to an exit by definition.
1366 void SetAsExit() { BottomUpPathCount = 1; }
1368 PtrState &getPtrTopDownState(const Value *Arg) {
1369 return PerPtrTopDown[Arg];
1372 PtrState &getPtrBottomUpState(const Value *Arg) {
1373 return PerPtrBottomUp[Arg];
1376 void clearBottomUpPointers() {
1377 PerPtrBottomUp.clear();
1380 void clearTopDownPointers() {
1381 PerPtrTopDown.clear();
1384 void InitFromPred(const BBState &Other);
1385 void InitFromSucc(const BBState &Other);
1386 void MergePred(const BBState &Other);
1387 void MergeSucc(const BBState &Other);
1389 /// GetAllPathCount - Return the number of possible unique paths from an
1390 /// entry to an exit which pass through this block. This is only valid
1391 /// after both the top-down and bottom-up traversals are complete.
1392 unsigned GetAllPathCount() const {
1393 return TopDownPathCount * BottomUpPathCount;
1396 /// IsVisitedTopDown - Test whether the block for this BBState has been
1397 /// visited by the top-down portion of the algorithm.
1398 bool isVisitedTopDown() const {
1399 return TopDownPathCount != 0;
1404 void BBState::InitFromPred(const BBState &Other) {
1405 PerPtrTopDown = Other.PerPtrTopDown;
1406 TopDownPathCount = Other.TopDownPathCount;
1409 void BBState::InitFromSucc(const BBState &Other) {
1410 PerPtrBottomUp = Other.PerPtrBottomUp;
1411 BottomUpPathCount = Other.BottomUpPathCount;
1414 /// MergePred - The top-down traversal uses this to merge information about
1415 /// predecessors to form the initial state for a new block.
1416 void BBState::MergePred(const BBState &Other) {
1417 // Other.TopDownPathCount can be 0, in which case it is either dead or a
1418 // loop backedge. Loop backedges are special.
1419 TopDownPathCount += Other.TopDownPathCount;
1421 // For each entry in the other set, if our set has an entry with the same key,
1422 // merge the entries. Otherwise, copy the entry and merge it with an empty
1424 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
1425 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
1426 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
1427 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1431 // For each entry in our set, if the other set doesn't have an entry with the
1432 // same key, force it to merge with an empty entry.
1433 for (ptr_iterator MI = top_down_ptr_begin(),
1434 ME = top_down_ptr_end(); MI != ME; ++MI)
1435 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
1436 MI->second.Merge(PtrState(), /*TopDown=*/true);
1439 /// MergeSucc - The bottom-up traversal uses this to merge information about
1440 /// successors to form the initial state for a new block.
1441 void BBState::MergeSucc(const BBState &Other) {
1442 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
1443 // loop backedge. Loop backedges are special.
1444 BottomUpPathCount += Other.BottomUpPathCount;
1446 // For each entry in the other set, if our set has an entry with the
1447 // same key, merge the entries. Otherwise, copy the entry and merge
1448 // it with an empty entry.
1449 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
1450 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
1451 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
1452 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1456 // For each entry in our set, if the other set doesn't have an entry
1457 // with the same key, force it to merge with an empty entry.
1458 for (ptr_iterator MI = bottom_up_ptr_begin(),
1459 ME = bottom_up_ptr_end(); MI != ME; ++MI)
1460 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
1461 MI->second.Merge(PtrState(), /*TopDown=*/false);
1465 /// ObjCARCOpt - The main ARC optimization pass.
1466 class ObjCARCOpt : public FunctionPass {
1468 ProvenanceAnalysis PA;
1470 /// Run - A flag indicating whether this optimization pass should run.
1473 /// RetainRVCallee, etc. - Declarations for ObjC runtime
1474 /// functions, for use in creating calls to them. These are initialized
1475 /// lazily to avoid cluttering up the Module with unused declarations.
1476 Constant *RetainRVCallee, *AutoreleaseRVCallee, *ReleaseCallee,
1477 *RetainCallee, *RetainBlockCallee, *AutoreleaseCallee;
1479 /// UsedInThisFunciton - Flags which determine whether each of the
1480 /// interesting runtine functions is in fact used in the current function.
1481 unsigned UsedInThisFunction;
1483 /// ImpreciseReleaseMDKind - The Metadata Kind for clang.imprecise_release
1485 unsigned ImpreciseReleaseMDKind;
1487 /// CopyOnEscapeMDKind - The Metadata Kind for clang.arc.copy_on_escape
1489 unsigned CopyOnEscapeMDKind;
1491 Constant *getRetainRVCallee(Module *M);
1492 Constant *getAutoreleaseRVCallee(Module *M);
1493 Constant *getReleaseCallee(Module *M);
1494 Constant *getRetainCallee(Module *M);
1495 Constant *getRetainBlockCallee(Module *M);
1496 Constant *getAutoreleaseCallee(Module *M);
1498 void OptimizeRetainCall(Function &F, Instruction *Retain);
1499 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
1500 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV);
1501 void OptimizeIndividualCalls(Function &F);
1503 void CheckForCFGHazards(const BasicBlock *BB,
1504 DenseMap<const BasicBlock *, BBState> &BBStates,
1505 BBState &MyStates) const;
1506 bool VisitBottomUp(BasicBlock *BB,
1507 DenseMap<const BasicBlock *, BBState> &BBStates,
1508 MapVector<Value *, RRInfo> &Retains);
1509 bool VisitTopDown(BasicBlock *BB,
1510 DenseMap<const BasicBlock *, BBState> &BBStates,
1511 DenseMap<Value *, RRInfo> &Releases);
1512 bool Visit(Function &F,
1513 DenseMap<const BasicBlock *, BBState> &BBStates,
1514 MapVector<Value *, RRInfo> &Retains,
1515 DenseMap<Value *, RRInfo> &Releases);
1517 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1518 MapVector<Value *, RRInfo> &Retains,
1519 DenseMap<Value *, RRInfo> &Releases,
1520 SmallVectorImpl<Instruction *> &DeadInsts,
1523 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1524 MapVector<Value *, RRInfo> &Retains,
1525 DenseMap<Value *, RRInfo> &Releases,
1528 void OptimizeWeakCalls(Function &F);
1530 bool OptimizeSequences(Function &F);
1532 void OptimizeReturns(Function &F);
1534 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1535 virtual bool doInitialization(Module &M);
1536 virtual bool runOnFunction(Function &F);
1537 virtual void releaseMemory();
1541 ObjCARCOpt() : FunctionPass(ID) {
1542 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1547 char ObjCARCOpt::ID = 0;
1548 INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1549 "objc-arc", "ObjC ARC optimization", false, false)
1550 INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1551 INITIALIZE_PASS_END(ObjCARCOpt,
1552 "objc-arc", "ObjC ARC optimization", false, false)
1554 Pass *llvm::createObjCARCOptPass() {
1555 return new ObjCARCOpt();
1558 void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1559 AU.addRequired<ObjCARCAliasAnalysis>();
1560 AU.addRequired<AliasAnalysis>();
1561 // ARC optimization doesn't currently split critical edges.
1562 AU.setPreservesCFG();
1565 Constant *ObjCARCOpt::getRetainRVCallee(Module *M) {
1566 if (!RetainRVCallee) {
1567 LLVMContext &C = M->getContext();
1568 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1569 std::vector<Type *> Params;
1570 Params.push_back(I8X);
1572 FunctionType::get(I8X, Params, /*isVarArg=*/false);
1573 AttrListPtr Attributes;
1574 Attributes.addAttr(~0u, Attribute::NoUnwind);
1576 M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy,
1579 return RetainRVCallee;
1582 Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1583 if (!AutoreleaseRVCallee) {
1584 LLVMContext &C = M->getContext();
1585 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1586 std::vector<Type *> Params;
1587 Params.push_back(I8X);
1589 FunctionType::get(I8X, Params, /*isVarArg=*/false);
1590 AttrListPtr Attributes;
1591 Attributes.addAttr(~0u, Attribute::NoUnwind);
1592 AutoreleaseRVCallee =
1593 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
1596 return AutoreleaseRVCallee;
1599 Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1600 if (!ReleaseCallee) {
1601 LLVMContext &C = M->getContext();
1602 std::vector<Type *> Params;
1603 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1604 AttrListPtr Attributes;
1605 Attributes.addAttr(~0u, Attribute::NoUnwind);
1607 M->getOrInsertFunction(
1609 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
1612 return ReleaseCallee;
1615 Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1616 if (!RetainCallee) {
1617 LLVMContext &C = M->getContext();
1618 std::vector<Type *> Params;
1619 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1620 AttrListPtr Attributes;
1621 Attributes.addAttr(~0u, Attribute::NoUnwind);
1623 M->getOrInsertFunction(
1625 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1628 return RetainCallee;
1631 Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1632 if (!RetainBlockCallee) {
1633 LLVMContext &C = M->getContext();
1634 std::vector<Type *> Params;
1635 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1636 AttrListPtr Attributes;
1637 // objc_retainBlock is not nounwind because it calls user copy constructors
1638 // which could theoretically throw.
1640 M->getOrInsertFunction(
1642 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1645 return RetainBlockCallee;
1648 Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1649 if (!AutoreleaseCallee) {
1650 LLVMContext &C = M->getContext();
1651 std::vector<Type *> Params;
1652 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1653 AttrListPtr Attributes;
1654 Attributes.addAttr(~0u, Attribute::NoUnwind);
1656 M->getOrInsertFunction(
1658 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1661 return AutoreleaseCallee;
1664 /// CanAlterRefCount - Test whether the given instruction can result in a
1665 /// reference count modification (positive or negative) for the pointer's
1668 CanAlterRefCount(const Instruction *Inst, const Value *Ptr,
1669 ProvenanceAnalysis &PA, InstructionClass Class) {
1671 case IC_Autorelease:
1672 case IC_AutoreleaseRV:
1674 // These operations never directly modify a reference count.
1679 ImmutableCallSite CS = static_cast<const Value *>(Inst);
1680 assert(CS && "Only calls can alter reference counts!");
1682 // See if AliasAnalysis can help us with the call.
1683 AliasAnalysis::ModRefBehavior MRB = PA.getAA()->getModRefBehavior(CS);
1684 if (AliasAnalysis::onlyReadsMemory(MRB))
1686 if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
1687 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1689 const Value *Op = *I;
1690 if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1696 // Assume the worst.
1700 /// CanUse - Test whether the given instruction can "use" the given pointer's
1701 /// object in a way that requires the reference count to be positive.
1703 CanUse(const Instruction *Inst, const Value *Ptr, ProvenanceAnalysis &PA,
1704 InstructionClass Class) {
1705 // IC_Call operations (as opposed to IC_CallOrUser) never "use" objc pointers.
1706 if (Class == IC_Call)
1709 // Consider various instructions which may have pointer arguments which are
1711 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(Inst)) {
1712 // Comparing a pointer with null, or any other constant, isn't really a use,
1713 // because we don't care what the pointer points to, or about the values
1714 // of any other dynamic reference-counted pointers.
1715 if (!IsPotentialUse(ICI->getOperand(1)))
1717 } else if (ImmutableCallSite CS = static_cast<const Value *>(Inst)) {
1718 // For calls, just check the arguments (and not the callee operand).
1719 for (ImmutableCallSite::arg_iterator OI = CS.arg_begin(),
1720 OE = CS.arg_end(); OI != OE; ++OI) {
1721 const Value *Op = *OI;
1722 if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1726 } else if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1727 // Special-case stores, because we don't care about the stored value, just
1728 // the store address.
1729 const Value *Op = GetUnderlyingObjCPtr(SI->getPointerOperand());
1730 // If we can't tell what the underlying object was, assume there is a
1732 return IsPotentialUse(Op) && PA.related(Op, Ptr);
1735 // Check each operand for a match.
1736 for (User::const_op_iterator OI = Inst->op_begin(), OE = Inst->op_end();
1738 const Value *Op = *OI;
1739 if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1745 /// CanInterruptRV - Test whether the given instruction can autorelease
1746 /// any pointer or cause an autoreleasepool pop.
1748 CanInterruptRV(InstructionClass Class) {
1750 case IC_AutoreleasepoolPop:
1753 case IC_Autorelease:
1754 case IC_AutoreleaseRV:
1755 case IC_FusedRetainAutorelease:
1756 case IC_FusedRetainAutoreleaseRV:
1764 /// DependenceKind - There are several kinds of dependence-like concepts in
1766 enum DependenceKind {
1767 NeedsPositiveRetainCount,
1768 CanChangeRetainCount,
1769 RetainAutoreleaseDep, ///< Blocks objc_retainAutorelease.
1770 RetainAutoreleaseRVDep, ///< Blocks objc_retainAutoreleaseReturnValue.
1771 RetainRVDep ///< Blocks objc_retainAutoreleasedReturnValue.
1775 /// Depends - Test if there can be dependencies on Inst through Arg. This
1776 /// function only tests dependencies relevant for removing pairs of calls.
1778 Depends(DependenceKind Flavor, Instruction *Inst, const Value *Arg,
1779 ProvenanceAnalysis &PA) {
1780 // If we've reached the definition of Arg, stop.
1785 case NeedsPositiveRetainCount: {
1786 InstructionClass Class = GetInstructionClass(Inst);
1788 case IC_AutoreleasepoolPop:
1789 case IC_AutoreleasepoolPush:
1793 return CanUse(Inst, Arg, PA, Class);
1797 case CanChangeRetainCount: {
1798 InstructionClass Class = GetInstructionClass(Inst);
1800 case IC_AutoreleasepoolPop:
1801 // Conservatively assume this can decrement any count.
1803 case IC_AutoreleasepoolPush:
1807 return CanAlterRefCount(Inst, Arg, PA, Class);
1811 case RetainAutoreleaseDep:
1812 switch (GetBasicInstructionClass(Inst)) {
1813 case IC_AutoreleasepoolPop:
1814 // Don't merge an objc_autorelease with an objc_retain inside a different
1815 // autoreleasepool scope.
1819 // Check for a retain of the same pointer for merging.
1820 return GetObjCArg(Inst) == Arg;
1822 // Nothing else matters for objc_retainAutorelease formation.
1827 case RetainAutoreleaseRVDep: {
1828 InstructionClass Class = GetBasicInstructionClass(Inst);
1832 // Check for a retain of the same pointer for merging.
1833 return GetObjCArg(Inst) == Arg;
1835 // Anything that can autorelease interrupts
1836 // retainAutoreleaseReturnValue formation.
1837 return CanInterruptRV(Class);
1843 return CanInterruptRV(GetBasicInstructionClass(Inst));
1846 llvm_unreachable("Invalid dependence flavor");
1850 /// FindDependencies - Walk up the CFG from StartPos (which is in StartBB) and
1851 /// find local and non-local dependencies on Arg.
1852 /// TODO: Cache results?
1854 FindDependencies(DependenceKind Flavor,
1856 BasicBlock *StartBB, Instruction *StartInst,
1857 SmallPtrSet<Instruction *, 4> &DependingInstructions,
1858 SmallPtrSet<const BasicBlock *, 4> &Visited,
1859 ProvenanceAnalysis &PA) {
1860 BasicBlock::iterator StartPos = StartInst;
1862 SmallVector<std::pair<BasicBlock *, BasicBlock::iterator>, 4> Worklist;
1863 Worklist.push_back(std::make_pair(StartBB, StartPos));
1865 std::pair<BasicBlock *, BasicBlock::iterator> Pair =
1866 Worklist.pop_back_val();
1867 BasicBlock *LocalStartBB = Pair.first;
1868 BasicBlock::iterator LocalStartPos = Pair.second;
1869 BasicBlock::iterator StartBBBegin = LocalStartBB->begin();
1871 if (LocalStartPos == StartBBBegin) {
1872 pred_iterator PI(LocalStartBB), PE(LocalStartBB, false);
1874 // If we've reached the function entry, produce a null dependence.
1875 DependingInstructions.insert(0);
1877 // Add the predecessors to the worklist.
1879 BasicBlock *PredBB = *PI;
1880 if (Visited.insert(PredBB))
1881 Worklist.push_back(std::make_pair(PredBB, PredBB->end()));
1882 } while (++PI != PE);
1886 Instruction *Inst = --LocalStartPos;
1887 if (Depends(Flavor, Inst, Arg, PA)) {
1888 DependingInstructions.insert(Inst);
1892 } while (!Worklist.empty());
1894 // Determine whether the original StartBB post-dominates all of the blocks we
1895 // visited. If not, insert a sentinal indicating that most optimizations are
1897 for (SmallPtrSet<const BasicBlock *, 4>::const_iterator I = Visited.begin(),
1898 E = Visited.end(); I != E; ++I) {
1899 const BasicBlock *BB = *I;
1902 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
1903 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
1904 const BasicBlock *Succ = *SI;
1905 if (Succ != StartBB && !Visited.count(Succ)) {
1906 DependingInstructions.insert(reinterpret_cast<Instruction *>(-1));
1913 static bool isNullOrUndef(const Value *V) {
1914 return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
1917 static bool isNoopInstruction(const Instruction *I) {
1918 return isa<BitCastInst>(I) ||
1919 (isa<GetElementPtrInst>(I) &&
1920 cast<GetElementPtrInst>(I)->hasAllZeroIndices());
1923 /// OptimizeRetainCall - Turn objc_retain into
1924 /// objc_retainAutoreleasedReturnValue if the operand is a return value.
1926 ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) {
1927 CallSite CS(GetObjCArg(Retain));
1928 Instruction *Call = CS.getInstruction();
1930 if (Call->getParent() != Retain->getParent()) return;
1932 // Check that the call is next to the retain.
1933 BasicBlock::iterator I = Call;
1935 while (isNoopInstruction(I)) ++I;
1939 // Turn it to an objc_retainAutoreleasedReturnValue..
1942 cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent()));
1945 /// OptimizeRetainRVCall - Turn objc_retainAutoreleasedReturnValue into
1946 /// objc_retain if the operand is not a return value. Or, if it can be
1947 /// paired with an objc_autoreleaseReturnValue, delete the pair and
1950 ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
1951 // Check for the argument being from an immediately preceding call.
1952 Value *Arg = GetObjCArg(RetainRV);
1954 if (Instruction *Call = CS.getInstruction())
1955 if (Call->getParent() == RetainRV->getParent()) {
1956 BasicBlock::iterator I = Call;
1958 while (isNoopInstruction(I)) ++I;
1959 if (&*I == RetainRV)
1963 // Check for being preceded by an objc_autoreleaseReturnValue on the same
1964 // pointer. In this case, we can delete the pair.
1965 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
1967 do --I; while (I != Begin && isNoopInstruction(I));
1968 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
1969 GetObjCArg(I) == Arg) {
1972 EraseInstruction(I);
1973 EraseInstruction(RetainRV);
1978 // Turn it to a plain objc_retain.
1981 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
1985 /// OptimizeAutoreleaseRVCall - Turn objc_autoreleaseReturnValue into
1986 /// objc_autorelease if the result is not used as a return value.
1988 ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV) {
1989 // Check for a return of the pointer value.
1990 const Value *Ptr = GetObjCArg(AutoreleaseRV);
1991 SmallVector<const Value *, 2> Users;
1992 Users.push_back(Ptr);
1994 Ptr = Users.pop_back_val();
1995 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
1997 const User *I = *UI;
1998 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
2000 if (isa<BitCastInst>(I))
2003 } while (!Users.empty());
2007 cast<CallInst>(AutoreleaseRV)->
2008 setCalledFunction(getAutoreleaseCallee(F.getParent()));
2011 /// OptimizeIndividualCalls - Visit each call, one at a time, and make
2012 /// simplifications without doing any additional analysis.
2013 void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
2014 // Reset all the flags in preparation for recomputing them.
2015 UsedInThisFunction = 0;
2017 // Visit all objc_* calls in F.
2018 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2019 Instruction *Inst = &*I++;
2020 InstructionClass Class = GetBasicInstructionClass(Inst);
2025 // Delete no-op casts. These function calls have special semantics, but
2026 // the semantics are entirely implemented via lowering in the front-end,
2027 // so by the time they reach the optimizer, they are just no-op calls
2028 // which return their argument.
2030 // There are gray areas here, as the ability to cast reference-counted
2031 // pointers to raw void* and back allows code to break ARC assumptions,
2032 // however these are currently considered to be unimportant.
2036 EraseInstruction(Inst);
2039 // If the pointer-to-weak-pointer is null, it's undefined behavior.
2042 case IC_LoadWeakRetained:
2044 case IC_DestroyWeak: {
2045 CallInst *CI = cast<CallInst>(Inst);
2046 if (isNullOrUndef(CI->getArgOperand(0))) {
2047 Type *Ty = CI->getArgOperand(0)->getType();
2048 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2049 Constant::getNullValue(Ty),
2051 CI->replaceAllUsesWith(UndefValue::get(CI->getType()));
2052 CI->eraseFromParent();
2059 CallInst *CI = cast<CallInst>(Inst);
2060 if (isNullOrUndef(CI->getArgOperand(0)) ||
2061 isNullOrUndef(CI->getArgOperand(1))) {
2062 Type *Ty = CI->getArgOperand(0)->getType();
2063 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2064 Constant::getNullValue(Ty),
2066 CI->replaceAllUsesWith(UndefValue::get(CI->getType()));
2067 CI->eraseFromParent();
2073 OptimizeRetainCall(F, Inst);
2076 if (OptimizeRetainRVCall(F, Inst))
2079 case IC_AutoreleaseRV:
2080 OptimizeAutoreleaseRVCall(F, Inst);
2084 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
2085 if (IsAutorelease(Class) && Inst->use_empty()) {
2086 CallInst *Call = cast<CallInst>(Inst);
2087 const Value *Arg = Call->getArgOperand(0);
2088 Arg = FindSingleUseIdentifiedObject(Arg);
2093 // Create the declaration lazily.
2094 LLVMContext &C = Inst->getContext();
2096 CallInst::Create(getReleaseCallee(F.getParent()),
2097 Call->getArgOperand(0), "", Call);
2098 NewCall->setMetadata(ImpreciseReleaseMDKind,
2099 MDNode::get(C, ArrayRef<Value *>()));
2100 EraseInstruction(Call);
2106 // For functions which can never be passed stack arguments, add
2108 if (IsAlwaysTail(Class)) {
2110 cast<CallInst>(Inst)->setTailCall();
2113 // Set nounwind as needed.
2114 if (IsNoThrow(Class)) {
2116 cast<CallInst>(Inst)->setDoesNotThrow();
2119 if (!IsNoopOnNull(Class)) {
2120 UsedInThisFunction |= 1 << Class;
2124 const Value *Arg = GetObjCArg(Inst);
2126 // ARC calls with null are no-ops. Delete them.
2127 if (isNullOrUndef(Arg)) {
2130 EraseInstruction(Inst);
2134 // Keep track of which of retain, release, autorelease, and retain_block
2135 // are actually present in this function.
2136 UsedInThisFunction |= 1 << Class;
2138 // If Arg is a PHI, and one or more incoming values to the
2139 // PHI are null, and the call is control-equivalent to the PHI, and there
2140 // are no relevant side effects between the PHI and the call, the call
2141 // could be pushed up to just those paths with non-null incoming values.
2142 // For now, don't bother splitting critical edges for this.
2143 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
2144 Worklist.push_back(std::make_pair(Inst, Arg));
2146 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
2150 const PHINode *PN = dyn_cast<PHINode>(Arg);
2153 // Determine if the PHI has any null operands, or any incoming
2155 bool HasNull = false;
2156 bool HasCriticalEdges = false;
2157 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2159 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2160 if (isNullOrUndef(Incoming))
2162 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
2163 .getNumSuccessors() != 1) {
2164 HasCriticalEdges = true;
2168 // If we have null operands and no critical edges, optimize.
2169 if (!HasCriticalEdges && HasNull) {
2170 SmallPtrSet<Instruction *, 4> DependingInstructions;
2171 SmallPtrSet<const BasicBlock *, 4> Visited;
2173 // Check that there is nothing that cares about the reference
2174 // count between the call and the phi.
2175 FindDependencies(NeedsPositiveRetainCount, Arg,
2176 Inst->getParent(), Inst,
2177 DependingInstructions, Visited, PA);
2178 if (DependingInstructions.size() == 1 &&
2179 *DependingInstructions.begin() == PN) {
2182 // Clone the call into each predecessor that has a non-null value.
2183 CallInst *CInst = cast<CallInst>(Inst);
2184 Type *ParamTy = CInst->getArgOperand(0)->getType();
2185 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2187 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2188 if (!isNullOrUndef(Incoming)) {
2189 CallInst *Clone = cast<CallInst>(CInst->clone());
2190 Value *Op = PN->getIncomingValue(i);
2191 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
2192 if (Op->getType() != ParamTy)
2193 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
2194 Clone->setArgOperand(0, Op);
2195 Clone->insertBefore(InsertPos);
2196 Worklist.push_back(std::make_pair(Clone, Incoming));
2199 // Erase the original call.
2200 EraseInstruction(CInst);
2204 } while (!Worklist.empty());
2208 /// CheckForCFGHazards - Check for critical edges, loop boundaries, irreducible
2209 /// control flow, or other CFG structures where moving code across the edge
2210 /// would result in it being executed more.
2212 ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
2213 DenseMap<const BasicBlock *, BBState> &BBStates,
2214 BBState &MyStates) const {
2215 // If any top-down local-use or possible-dec has a succ which is earlier in
2216 // the sequence, forget it.
2217 for (BBState::ptr_const_iterator I = MyStates.top_down_ptr_begin(),
2218 E = MyStates.top_down_ptr_end(); I != E; ++I)
2219 switch (I->second.GetSeq()) {
2222 const Value *Arg = I->first;
2223 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2224 bool SomeSuccHasSame = false;
2225 bool AllSuccsHaveSame = true;
2226 PtrState &S = MyStates.getPtrTopDownState(Arg);
2227 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2228 PtrState &SuccS = BBStates[*SI].getPtrBottomUpState(Arg);
2229 switch (SuccS.GetSeq()) {
2231 case S_CanRelease: {
2232 if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
2233 S.ClearSequenceProgress();
2237 SomeSuccHasSame = true;
2241 case S_MovableRelease:
2242 if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
2243 AllSuccsHaveSame = false;
2246 llvm_unreachable("bottom-up pointer in retain state!");
2249 // If the state at the other end of any of the successor edges
2250 // matches the current state, require all edges to match. This
2251 // guards against loops in the middle of a sequence.
2252 if (SomeSuccHasSame && !AllSuccsHaveSame)
2253 S.ClearSequenceProgress();
2256 case S_CanRelease: {
2257 const Value *Arg = I->first;
2258 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2259 bool SomeSuccHasSame = false;
2260 bool AllSuccsHaveSame = true;
2261 PtrState &S = MyStates.getPtrTopDownState(Arg);
2262 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2263 PtrState &SuccS = BBStates[*SI].getPtrBottomUpState(Arg);
2264 switch (SuccS.GetSeq()) {
2266 if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
2267 S.ClearSequenceProgress();
2271 SomeSuccHasSame = true;
2275 case S_MovableRelease:
2277 if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
2278 AllSuccsHaveSame = false;
2281 llvm_unreachable("bottom-up pointer in retain state!");
2284 // If the state at the other end of any of the successor edges
2285 // matches the current state, require all edges to match. This
2286 // guards against loops in the middle of a sequence.
2287 if (SomeSuccHasSame && !AllSuccsHaveSame)
2288 S.ClearSequenceProgress();
2295 ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2296 DenseMap<const BasicBlock *, BBState> &BBStates,
2297 MapVector<Value *, RRInfo> &Retains) {
2298 bool NestingDetected = false;
2299 BBState &MyStates = BBStates[BB];
2301 // Merge the states from each successor to compute the initial state
2302 // for the current block.
2303 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2304 succ_const_iterator SI(TI), SE(TI, false);
2306 MyStates.SetAsExit();
2309 const BasicBlock *Succ = *SI++;
2312 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
2313 // If we haven't seen this node yet, then we've found a CFG cycle.
2314 // Be optimistic here; it's CheckForCFGHazards' job detect trouble.
2315 if (I == BBStates.end())
2317 MyStates.InitFromSucc(I->second);
2321 I = BBStates.find(Succ);
2322 if (I != BBStates.end())
2323 MyStates.MergeSucc(I->second);
2329 // Visit all the instructions, bottom-up.
2330 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2331 Instruction *Inst = llvm::prior(I);
2332 InstructionClass Class = GetInstructionClass(Inst);
2333 const Value *Arg = 0;
2337 Arg = GetObjCArg(Inst);
2339 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2341 // If we see two releases in a row on the same pointer. If so, make
2342 // a note, and we'll cicle back to revisit it after we've
2343 // hopefully eliminated the second release, which may allow us to
2344 // eliminate the first release too.
2345 // Theoretically we could implement removal of nested retain+release
2346 // pairs by making PtrState hold a stack of states, but this is
2347 // simple and avoids adding overhead for the non-nested case.
2348 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease)
2349 NestingDetected = true;
2353 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2354 S.SetSeq(ReleaseMetadata ? S_MovableRelease : S_Release);
2355 S.RRI.ReleaseMetadata = ReleaseMetadata;
2356 S.RRI.KnownSafe = S.IsKnownNested() || S.IsKnownIncremented();
2357 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2358 S.RRI.Calls.insert(Inst);
2360 S.IncrementRefCount();
2361 S.IncrementNestCount();
2364 case IC_RetainBlock:
2367 Arg = GetObjCArg(Inst);
2369 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2370 S.DecrementRefCount();
2371 S.SetAtLeastOneRefCount();
2372 S.DecrementNestCount();
2374 // An non-copy-on-escape objc_retainBlock call with just a use still
2375 // needs to be kept, because it may be copying a block from the stack
2377 if (Class == IC_RetainBlock &&
2378 !Inst->getMetadata(CopyOnEscapeMDKind) &&
2379 S.GetSeq() == S_Use)
2380 S.SetSeq(S_CanRelease);
2382 switch (S.GetSeq()) {
2385 case S_MovableRelease:
2387 S.RRI.ReverseInsertPts.clear();
2390 // Don't do retain+release tracking for IC_RetainRV, because it's
2391 // better to let it remain as the first instruction after a call.
2392 if (Class != IC_RetainRV) {
2393 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2394 if (S.RRI.IsRetainBlock)
2395 S.RRI.CopyOnEscape = !!Inst->getMetadata(CopyOnEscapeMDKind);
2396 Retains[Inst] = S.RRI;
2398 S.ClearSequenceProgress();
2403 llvm_unreachable("bottom-up pointer in retain state!");
2407 case IC_AutoreleasepoolPop:
2408 // Conservatively, clear MyStates for all known pointers.
2409 MyStates.clearBottomUpPointers();
2411 case IC_AutoreleasepoolPush:
2413 // These are irrelevant.
2419 // Consider any other possible effects of this instruction on each
2420 // pointer being tracked.
2421 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
2422 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
2423 const Value *Ptr = MI->first;
2425 continue; // Handled above.
2426 PtrState &S = MI->second;
2427 Sequence Seq = S.GetSeq();
2429 // Check for possible releases.
2430 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2431 S.DecrementRefCount();
2434 S.SetSeq(S_CanRelease);
2438 case S_MovableRelease:
2443 llvm_unreachable("bottom-up pointer in retain state!");
2447 // Check for possible direct uses.
2450 case S_MovableRelease:
2451 if (CanUse(Inst, Ptr, PA, Class)) {
2452 assert(S.RRI.ReverseInsertPts.empty());
2453 S.RRI.ReverseInsertPts.insert(Inst);
2455 } else if (Seq == S_Release &&
2456 (Class == IC_User || Class == IC_CallOrUser)) {
2457 // Non-movable releases depend on any possible objc pointer use.
2459 assert(S.RRI.ReverseInsertPts.empty());
2460 S.RRI.ReverseInsertPts.insert(Inst);
2464 if (CanUse(Inst, Ptr, PA, Class))
2472 llvm_unreachable("bottom-up pointer in retain state!");
2477 return NestingDetected;
2481 ObjCARCOpt::VisitTopDown(BasicBlock *BB,
2482 DenseMap<const BasicBlock *, BBState> &BBStates,
2483 DenseMap<Value *, RRInfo> &Releases) {
2484 bool NestingDetected = false;
2485 BBState &MyStates = BBStates[BB];
2487 // Merge the states from each predecessor to compute the initial state
2488 // for the current block.
2489 const_pred_iterator PI(BB), PE(BB, false);
2491 MyStates.SetAsEntry();
2494 const BasicBlock *Pred = *PI++;
2497 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
2498 // If we haven't seen this node yet, then we've found a CFG cycle.
2499 // Be optimistic here; it's CheckForCFGHazards' job detect trouble.
2500 if (I == BBStates.end() || !I->second.isVisitedTopDown())
2502 MyStates.InitFromPred(I->second);
2506 I = BBStates.find(Pred);
2507 if (I == BBStates.end() || I->second.isVisitedTopDown())
2508 MyStates.MergePred(I->second);
2514 // Visit all the instructions, top-down.
2515 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2516 Instruction *Inst = I;
2517 InstructionClass Class = GetInstructionClass(Inst);
2518 const Value *Arg = 0;
2521 case IC_RetainBlock:
2524 Arg = GetObjCArg(Inst);
2526 PtrState &S = MyStates.getPtrTopDownState(Arg);
2528 // Don't do retain+release tracking for IC_RetainRV, because it's
2529 // better to let it remain as the first instruction after a call.
2530 if (Class != IC_RetainRV) {
2531 // If we see two retains in a row on the same pointer. If so, make
2532 // a note, and we'll cicle back to revisit it after we've
2533 // hopefully eliminated the second retain, which may allow us to
2534 // eliminate the first retain too.
2535 // Theoretically we could implement removal of nested retain+release
2536 // pairs by making PtrState hold a stack of states, but this is
2537 // simple and avoids adding overhead for the non-nested case.
2538 if (S.GetSeq() == S_Retain)
2539 NestingDetected = true;
2543 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2544 if (S.RRI.IsRetainBlock)
2545 S.RRI.CopyOnEscape = !!Inst->getMetadata(CopyOnEscapeMDKind);
2546 // Don't check S.IsKnownIncremented() here because it's not
2548 S.RRI.KnownSafe = S.IsKnownNested();
2549 S.RRI.Calls.insert(Inst);
2552 S.SetAtLeastOneRefCount();
2553 S.IncrementRefCount();
2554 S.IncrementNestCount();
2558 Arg = GetObjCArg(Inst);
2560 PtrState &S = MyStates.getPtrTopDownState(Arg);
2561 S.DecrementRefCount();
2562 S.DecrementNestCount();
2564 switch (S.GetSeq()) {
2567 S.RRI.ReverseInsertPts.clear();
2570 S.RRI.ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2571 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2572 Releases[Inst] = S.RRI;
2573 S.ClearSequenceProgress();
2579 case S_MovableRelease:
2580 llvm_unreachable("top-down pointer in release state!");
2584 case IC_AutoreleasepoolPop:
2585 // Conservatively, clear MyStates for all known pointers.
2586 MyStates.clearTopDownPointers();
2588 case IC_AutoreleasepoolPush:
2590 // These are irrelevant.
2596 // Consider any other possible effects of this instruction on each
2597 // pointer being tracked.
2598 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
2599 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
2600 const Value *Ptr = MI->first;
2602 continue; // Handled above.
2603 PtrState &S = MI->second;
2604 Sequence Seq = S.GetSeq();
2606 // Check for possible releases.
2607 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2608 S.DecrementRefCount();
2611 S.SetSeq(S_CanRelease);
2612 assert(S.RRI.ReverseInsertPts.empty());
2613 S.RRI.ReverseInsertPts.insert(Inst);
2615 // One call can't cause a transition from S_Retain to S_CanRelease
2616 // and S_CanRelease to S_Use. If we've made the first transition,
2625 case S_MovableRelease:
2626 llvm_unreachable("top-down pointer in release state!");
2630 // Check for possible direct uses.
2633 if (CanUse(Inst, Ptr, PA, Class))
2637 // A non-copy-on-scape objc_retainBlock call may be responsible for
2638 // copying the block data from the stack to the heap. Model this by
2639 // moving it straight from S_Retain to S_Use.
2640 if (S.RRI.IsRetainBlock &&
2641 !S.RRI.CopyOnEscape &&
2642 CanUse(Inst, Ptr, PA, Class)) {
2643 assert(S.RRI.ReverseInsertPts.empty());
2644 S.RRI.ReverseInsertPts.insert(Inst);
2653 case S_MovableRelease:
2654 llvm_unreachable("top-down pointer in release state!");
2659 CheckForCFGHazards(BB, BBStates, MyStates);
2660 return NestingDetected;
2664 ComputePostOrders(Function &F,
2665 SmallVectorImpl<BasicBlock *> &PostOrder,
2666 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder) {
2667 /// Backedges - Backedges detected in the DFS. These edges will be
2668 /// ignored in the reverse-CFG DFS, so that loops with multiple exits will be
2669 /// traversed in the desired order.
2670 DenseSet<std::pair<BasicBlock *, BasicBlock *> > Backedges;
2672 /// Visited - The visited set, for doing DFS walks.
2673 SmallPtrSet<BasicBlock *, 16> Visited;
2675 // Do DFS, computing the PostOrder.
2676 SmallPtrSet<BasicBlock *, 16> OnStack;
2677 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
2678 BasicBlock *EntryBB = &F.getEntryBlock();
2679 SuccStack.push_back(std::make_pair(EntryBB, succ_begin(EntryBB)));
2680 Visited.insert(EntryBB);
2681 OnStack.insert(EntryBB);
2684 succ_iterator End = succ_end(SuccStack.back().first);
2685 while (SuccStack.back().second != End) {
2686 BasicBlock *BB = *SuccStack.back().second++;
2687 if (Visited.insert(BB)) {
2688 SuccStack.push_back(std::make_pair(BB, succ_begin(BB)));
2692 if (OnStack.count(BB))
2693 Backedges.insert(std::make_pair(SuccStack.back().first, BB));
2695 OnStack.erase(SuccStack.back().first);
2696 PostOrder.push_back(SuccStack.pop_back_val().first);
2697 } while (!SuccStack.empty());
2701 // Compute the exits, which are the starting points for reverse-CFG DFS.
2702 SmallVector<BasicBlock *, 4> Exits;
2703 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
2705 if (BB->getTerminator()->getNumSuccessors() == 0)
2706 Exits.push_back(BB);
2709 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
2710 SmallVector<std::pair<BasicBlock *, pred_iterator>, 16> PredStack;
2711 for (SmallVectorImpl<BasicBlock *>::iterator I = Exits.begin(), E = Exits.end();
2713 BasicBlock *ExitBB = *I;
2714 PredStack.push_back(std::make_pair(ExitBB, pred_begin(ExitBB)));
2715 Visited.insert(ExitBB);
2716 while (!PredStack.empty()) {
2717 reverse_dfs_next_succ:
2718 pred_iterator End = pred_end(PredStack.back().first);
2719 while (PredStack.back().second != End) {
2720 BasicBlock *BB = *PredStack.back().second++;
2721 // Skip backedges detected in the forward-CFG DFS.
2722 if (Backedges.count(std::make_pair(BB, PredStack.back().first)))
2724 if (Visited.insert(BB)) {
2725 PredStack.push_back(std::make_pair(BB, pred_begin(BB)));
2726 goto reverse_dfs_next_succ;
2729 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
2734 // Visit - Visit the function both top-down and bottom-up.
2736 ObjCARCOpt::Visit(Function &F,
2737 DenseMap<const BasicBlock *, BBState> &BBStates,
2738 MapVector<Value *, RRInfo> &Retains,
2739 DenseMap<Value *, RRInfo> &Releases) {
2741 // Use reverse-postorder traversals, because we magically know that loops
2742 // will be well behaved, i.e. they won't repeatedly call retain on a single
2743 // pointer without doing a release. We can't use the ReversePostOrderTraversal
2744 // class here because we want the reverse-CFG postorder to consider each
2745 // function exit point, and we want to ignore selected cycle edges.
2746 SmallVector<BasicBlock *, 16> PostOrder;
2747 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
2748 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder);
2750 // Use reverse-postorder on the reverse CFG for bottom-up.
2751 bool BottomUpNestingDetected = false;
2752 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2753 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
2755 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
2757 // Use reverse-postorder for top-down.
2758 bool TopDownNestingDetected = false;
2759 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2760 PostOrder.rbegin(), E = PostOrder.rend();
2762 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
2764 return TopDownNestingDetected && BottomUpNestingDetected;
2767 /// MoveCalls - Move the calls in RetainsToMove and ReleasesToMove.
2768 void ObjCARCOpt::MoveCalls(Value *Arg,
2769 RRInfo &RetainsToMove,
2770 RRInfo &ReleasesToMove,
2771 MapVector<Value *, RRInfo> &Retains,
2772 DenseMap<Value *, RRInfo> &Releases,
2773 SmallVectorImpl<Instruction *> &DeadInsts,
2775 Type *ArgTy = Arg->getType();
2776 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
2778 // Insert the new retain and release calls.
2779 for (SmallPtrSet<Instruction *, 2>::const_iterator
2780 PI = ReleasesToMove.ReverseInsertPts.begin(),
2781 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2782 Instruction *InsertPt = *PI;
2783 Value *MyArg = ArgTy == ParamTy ? Arg :
2784 new BitCastInst(Arg, ParamTy, "", InsertPt);
2786 CallInst::Create(RetainsToMove.IsRetainBlock ?
2787 getRetainBlockCallee(M) : getRetainCallee(M),
2788 MyArg, "", InsertPt);
2789 Call->setDoesNotThrow();
2790 if (RetainsToMove.CopyOnEscape)
2791 Call->setMetadata(CopyOnEscapeMDKind,
2792 MDNode::get(M->getContext(), ArrayRef<Value *>()));
2793 if (!RetainsToMove.IsRetainBlock)
2794 Call->setTailCall();
2796 for (SmallPtrSet<Instruction *, 2>::const_iterator
2797 PI = RetainsToMove.ReverseInsertPts.begin(),
2798 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2799 Instruction *LastUse = *PI;
2800 Instruction *InsertPts[] = { 0, 0, 0 };
2801 if (InvokeInst *II = dyn_cast<InvokeInst>(LastUse)) {
2802 // We can't insert code immediately after an invoke instruction, so
2803 // insert code at the beginning of both successor blocks instead.
2804 // The invoke's return value isn't available in the unwind block,
2805 // but our releases will never depend on it, because they must be
2806 // paired with retains from before the invoke.
2807 InsertPts[0] = II->getNormalDest()->getFirstInsertionPt();
2808 InsertPts[1] = II->getUnwindDest()->getFirstInsertionPt();
2810 // Insert code immediately after the last use.
2811 InsertPts[0] = llvm::next(BasicBlock::iterator(LastUse));
2814 for (Instruction **I = InsertPts; *I; ++I) {
2815 Instruction *InsertPt = *I;
2816 Value *MyArg = ArgTy == ParamTy ? Arg :
2817 new BitCastInst(Arg, ParamTy, "", InsertPt);
2818 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
2820 // Attach a clang.imprecise_release metadata tag, if appropriate.
2821 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
2822 Call->setMetadata(ImpreciseReleaseMDKind, M);
2823 Call->setDoesNotThrow();
2824 if (ReleasesToMove.IsTailCallRelease)
2825 Call->setTailCall();
2829 // Delete the original retain and release calls.
2830 for (SmallPtrSet<Instruction *, 2>::const_iterator
2831 AI = RetainsToMove.Calls.begin(),
2832 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
2833 Instruction *OrigRetain = *AI;
2834 Retains.blot(OrigRetain);
2835 DeadInsts.push_back(OrigRetain);
2837 for (SmallPtrSet<Instruction *, 2>::const_iterator
2838 AI = ReleasesToMove.Calls.begin(),
2839 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
2840 Instruction *OrigRelease = *AI;
2841 Releases.erase(OrigRelease);
2842 DeadInsts.push_back(OrigRelease);
2847 ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
2849 MapVector<Value *, RRInfo> &Retains,
2850 DenseMap<Value *, RRInfo> &Releases,
2852 bool AnyPairsCompletelyEliminated = false;
2853 RRInfo RetainsToMove;
2854 RRInfo ReleasesToMove;
2855 SmallVector<Instruction *, 4> NewRetains;
2856 SmallVector<Instruction *, 4> NewReleases;
2857 SmallVector<Instruction *, 8> DeadInsts;
2859 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
2860 E = Retains.end(); I != E; ++I) {
2861 Value *V = I->first;
2862 if (!V) continue; // blotted
2864 Instruction *Retain = cast<Instruction>(V);
2865 Value *Arg = GetObjCArg(Retain);
2867 // If the object being released is in static storage, we know it's
2868 // not being managed by ObjC reference counting, so we can delete pairs
2869 // regardless of what possible decrements or uses lie between them.
2870 bool KnownSafe = isa<Constant>(Arg);
2872 // Same for stack storage, unless this is a non-copy-on-escape
2873 // objc_retainBlock call, which is responsible for copying the block data
2874 // from the stack to the heap.
2875 if ((!I->second.IsRetainBlock || I->second.CopyOnEscape) &&
2876 isa<AllocaInst>(Arg))
2879 // A constant pointer can't be pointing to an object on the heap. It may
2880 // be reference-counted, but it won't be deleted.
2881 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
2882 if (const GlobalVariable *GV =
2883 dyn_cast<GlobalVariable>(
2884 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
2885 if (GV->isConstant())
2888 // If a pair happens in a region where it is known that the reference count
2889 // is already incremented, we can similarly ignore possible decrements.
2890 bool KnownSafeTD = true, KnownSafeBU = true;
2892 // Connect the dots between the top-down-collected RetainsToMove and
2893 // bottom-up-collected ReleasesToMove to form sets of related calls.
2894 // This is an iterative process so that we connect multiple releases
2895 // to multiple retains if needed.
2896 unsigned OldDelta = 0;
2897 unsigned NewDelta = 0;
2898 unsigned OldCount = 0;
2899 unsigned NewCount = 0;
2900 bool FirstRelease = true;
2901 bool FirstRetain = true;
2902 NewRetains.push_back(Retain);
2904 for (SmallVectorImpl<Instruction *>::const_iterator
2905 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
2906 Instruction *NewRetain = *NI;
2907 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
2908 assert(It != Retains.end());
2909 const RRInfo &NewRetainRRI = It->second;
2910 KnownSafeTD &= NewRetainRRI.KnownSafe;
2911 for (SmallPtrSet<Instruction *, 2>::const_iterator
2912 LI = NewRetainRRI.Calls.begin(),
2913 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
2914 Instruction *NewRetainRelease = *LI;
2915 DenseMap<Value *, RRInfo>::const_iterator Jt =
2916 Releases.find(NewRetainRelease);
2917 if (Jt == Releases.end())
2919 const RRInfo &NewRetainReleaseRRI = Jt->second;
2920 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
2921 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
2923 BBStates[NewRetainRelease->getParent()].GetAllPathCount();
2925 // Merge the ReleaseMetadata and IsTailCallRelease values.
2927 ReleasesToMove.ReleaseMetadata =
2928 NewRetainReleaseRRI.ReleaseMetadata;
2929 ReleasesToMove.IsTailCallRelease =
2930 NewRetainReleaseRRI.IsTailCallRelease;
2931 FirstRelease = false;
2933 if (ReleasesToMove.ReleaseMetadata !=
2934 NewRetainReleaseRRI.ReleaseMetadata)
2935 ReleasesToMove.ReleaseMetadata = 0;
2936 if (ReleasesToMove.IsTailCallRelease !=
2937 NewRetainReleaseRRI.IsTailCallRelease)
2938 ReleasesToMove.IsTailCallRelease = false;
2941 // Collect the optimal insertion points.
2943 for (SmallPtrSet<Instruction *, 2>::const_iterator
2944 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
2945 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
2947 Instruction *RIP = *RI;
2948 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
2949 NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
2951 NewReleases.push_back(NewRetainRelease);
2956 if (NewReleases.empty()) break;
2958 // Back the other way.
2959 for (SmallVectorImpl<Instruction *>::const_iterator
2960 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
2961 Instruction *NewRelease = *NI;
2962 DenseMap<Value *, RRInfo>::const_iterator It =
2963 Releases.find(NewRelease);
2964 assert(It != Releases.end());
2965 const RRInfo &NewReleaseRRI = It->second;
2966 KnownSafeBU &= NewReleaseRRI.KnownSafe;
2967 for (SmallPtrSet<Instruction *, 2>::const_iterator
2968 LI = NewReleaseRRI.Calls.begin(),
2969 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
2970 Instruction *NewReleaseRetain = *LI;
2971 MapVector<Value *, RRInfo>::const_iterator Jt =
2972 Retains.find(NewReleaseRetain);
2973 if (Jt == Retains.end())
2975 const RRInfo &NewReleaseRetainRRI = Jt->second;
2976 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
2977 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
2978 unsigned PathCount =
2979 BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
2980 OldDelta += PathCount;
2981 OldCount += PathCount;
2983 // Merge the IsRetainBlock values.
2985 RetainsToMove.IsRetainBlock = NewReleaseRetainRRI.IsRetainBlock;
2986 RetainsToMove.CopyOnEscape = NewReleaseRetainRRI.CopyOnEscape;
2987 FirstRetain = false;
2988 } else if (ReleasesToMove.IsRetainBlock !=
2989 NewReleaseRetainRRI.IsRetainBlock)
2990 // It's not possible to merge the sequences if one uses
2991 // objc_retain and the other uses objc_retainBlock.
2994 // Merge the CopyOnEscape values.
2995 RetainsToMove.CopyOnEscape &= NewReleaseRetainRRI.CopyOnEscape;
2997 // Collect the optimal insertion points.
2999 for (SmallPtrSet<Instruction *, 2>::const_iterator
3000 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
3001 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
3003 Instruction *RIP = *RI;
3004 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
3005 PathCount = BBStates[RIP->getParent()].GetAllPathCount();
3006 NewDelta += PathCount;
3007 NewCount += PathCount;
3010 NewRetains.push_back(NewReleaseRetain);
3014 NewReleases.clear();
3015 if (NewRetains.empty()) break;
3018 // If the pointer is known incremented or nested, we can safely delete the
3019 // pair regardless of what's between them.
3020 if (KnownSafeTD || KnownSafeBU) {
3021 RetainsToMove.ReverseInsertPts.clear();
3022 ReleasesToMove.ReverseInsertPts.clear();
3025 // Determine whether the new insertion points we computed preserve the
3026 // balance of retain and release calls through the program.
3027 // TODO: If the fully aggressive solution isn't valid, try to find a
3028 // less aggressive solution which is.
3033 // Determine whether the original call points are balanced in the retain and
3034 // release calls through the program. If not, conservatively don't touch
3036 // TODO: It's theoretically possible to do code motion in this case, as
3037 // long as the existing imbalances are maintained.
3041 // Ok, everything checks out and we're all set. Let's move some code!
3043 AnyPairsCompletelyEliminated = NewCount == 0;
3044 NumRRs += OldCount - NewCount;
3045 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
3046 Retains, Releases, DeadInsts, M);
3049 NewReleases.clear();
3051 RetainsToMove.clear();
3052 ReleasesToMove.clear();
3055 // Now that we're done moving everything, we can delete the newly dead
3056 // instructions, as we no longer need them as insert points.
3057 while (!DeadInsts.empty())
3058 EraseInstruction(DeadInsts.pop_back_val());
3060 return AnyPairsCompletelyEliminated;
3063 /// OptimizeWeakCalls - Weak pointer optimizations.
3064 void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
3065 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
3066 // itself because it uses AliasAnalysis and we need to do provenance
3068 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3069 Instruction *Inst = &*I++;
3070 InstructionClass Class = GetBasicInstructionClass(Inst);
3071 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
3074 // Delete objc_loadWeak calls with no users.
3075 if (Class == IC_LoadWeak && Inst->use_empty()) {
3076 Inst->eraseFromParent();
3080 // TODO: For now, just look for an earlier available version of this value
3081 // within the same block. Theoretically, we could do memdep-style non-local
3082 // analysis too, but that would want caching. A better approach would be to
3083 // use the technique that EarlyCSE uses.
3084 inst_iterator Current = llvm::prior(I);
3085 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
3086 for (BasicBlock::iterator B = CurrentBB->begin(),
3087 J = Current.getInstructionIterator();
3089 Instruction *EarlierInst = &*llvm::prior(J);
3090 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
3091 switch (EarlierClass) {
3093 case IC_LoadWeakRetained: {
3094 // If this is loading from the same pointer, replace this load's value
3096 CallInst *Call = cast<CallInst>(Inst);
3097 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3098 Value *Arg = Call->getArgOperand(0);
3099 Value *EarlierArg = EarlierCall->getArgOperand(0);
3100 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3101 case AliasAnalysis::MustAlias:
3103 // If the load has a builtin retain, insert a plain retain for it.
3104 if (Class == IC_LoadWeakRetained) {
3106 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3110 // Zap the fully redundant load.
3111 Call->replaceAllUsesWith(EarlierCall);
3112 Call->eraseFromParent();
3114 case AliasAnalysis::MayAlias:
3115 case AliasAnalysis::PartialAlias:
3117 case AliasAnalysis::NoAlias:
3124 // If this is storing to the same pointer and has the same size etc.
3125 // replace this load's value with the stored value.
3126 CallInst *Call = cast<CallInst>(Inst);
3127 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3128 Value *Arg = Call->getArgOperand(0);
3129 Value *EarlierArg = EarlierCall->getArgOperand(0);
3130 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3131 case AliasAnalysis::MustAlias:
3133 // If the load has a builtin retain, insert a plain retain for it.
3134 if (Class == IC_LoadWeakRetained) {
3136 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3140 // Zap the fully redundant load.
3141 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
3142 Call->eraseFromParent();
3144 case AliasAnalysis::MayAlias:
3145 case AliasAnalysis::PartialAlias:
3147 case AliasAnalysis::NoAlias:
3154 // TOOD: Grab the copied value.
3156 case IC_AutoreleasepoolPush:
3159 // Weak pointers are only modified through the weak entry points
3160 // (and arbitrary calls, which could call the weak entry points).
3163 // Anything else could modify the weak pointer.
3170 // Then, for each destroyWeak with an alloca operand, check to see if
3171 // the alloca and all its users can be zapped.
3172 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3173 Instruction *Inst = &*I++;
3174 InstructionClass Class = GetBasicInstructionClass(Inst);
3175 if (Class != IC_DestroyWeak)
3178 CallInst *Call = cast<CallInst>(Inst);
3179 Value *Arg = Call->getArgOperand(0);
3180 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
3181 for (Value::use_iterator UI = Alloca->use_begin(),
3182 UE = Alloca->use_end(); UI != UE; ++UI) {
3183 Instruction *UserInst = cast<Instruction>(*UI);
3184 switch (GetBasicInstructionClass(UserInst)) {
3187 case IC_DestroyWeak:
3194 for (Value::use_iterator UI = Alloca->use_begin(),
3195 UE = Alloca->use_end(); UI != UE; ) {
3196 CallInst *UserInst = cast<CallInst>(*UI++);
3197 if (!UserInst->use_empty())
3198 UserInst->replaceAllUsesWith(UserInst->getArgOperand(0));
3199 UserInst->eraseFromParent();
3201 Alloca->eraseFromParent();
3207 /// OptimizeSequences - Identify program paths which execute sequences of
3208 /// retains and releases which can be eliminated.
3209 bool ObjCARCOpt::OptimizeSequences(Function &F) {
3210 /// Releases, Retains - These are used to store the results of the main flow
3211 /// analysis. These use Value* as the key instead of Instruction* so that the
3212 /// map stays valid when we get around to rewriting code and calls get
3213 /// replaced by arguments.
3214 DenseMap<Value *, RRInfo> Releases;
3215 MapVector<Value *, RRInfo> Retains;
3217 /// BBStates, This is used during the traversal of the function to track the
3218 /// states for each identified object at each block.
3219 DenseMap<const BasicBlock *, BBState> BBStates;
3221 // Analyze the CFG of the function, and all instructions.
3222 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
3225 return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) &&
3229 /// OptimizeReturns - Look for this pattern:
3231 /// %call = call i8* @something(...)
3232 /// %2 = call i8* @objc_retain(i8* %call)
3233 /// %3 = call i8* @objc_autorelease(i8* %2)
3236 /// And delete the retain and autorelease.
3238 /// Otherwise if it's just this:
3240 /// %3 = call i8* @objc_autorelease(i8* %2)
3243 /// convert the autorelease to autoreleaseRV.
3244 void ObjCARCOpt::OptimizeReturns(Function &F) {
3245 if (!F.getReturnType()->isPointerTy())
3248 SmallPtrSet<Instruction *, 4> DependingInstructions;
3249 SmallPtrSet<const BasicBlock *, 4> Visited;
3250 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3251 BasicBlock *BB = FI;
3252 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
3255 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
3256 FindDependencies(NeedsPositiveRetainCount, Arg,
3257 BB, Ret, DependingInstructions, Visited, PA);
3258 if (DependingInstructions.size() != 1)
3262 CallInst *Autorelease =
3263 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3266 InstructionClass AutoreleaseClass =
3267 GetBasicInstructionClass(Autorelease);
3268 if (!IsAutorelease(AutoreleaseClass))
3270 if (GetObjCArg(Autorelease) != Arg)
3273 DependingInstructions.clear();
3276 // Check that there is nothing that can affect the reference
3277 // count between the autorelease and the retain.
3278 FindDependencies(CanChangeRetainCount, Arg,
3279 BB, Autorelease, DependingInstructions, Visited, PA);
3280 if (DependingInstructions.size() != 1)
3285 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3287 // Check that we found a retain with the same argument.
3289 !IsRetain(GetBasicInstructionClass(Retain)) ||
3290 GetObjCArg(Retain) != Arg)
3293 DependingInstructions.clear();
3296 // Convert the autorelease to an autoreleaseRV, since it's
3297 // returning the value.
3298 if (AutoreleaseClass == IC_Autorelease) {
3299 Autorelease->setCalledFunction(getAutoreleaseRVCallee(F.getParent()));
3300 AutoreleaseClass = IC_AutoreleaseRV;
3303 // Check that there is nothing that can affect the reference
3304 // count between the retain and the call.
3305 // Note that Retain need not be in BB.
3306 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
3307 DependingInstructions, Visited, PA);
3308 if (DependingInstructions.size() != 1)
3313 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3315 // Check that the pointer is the return value of the call.
3316 if (!Call || Arg != Call)
3319 // Check that the call is a regular call.
3320 InstructionClass Class = GetBasicInstructionClass(Call);
3321 if (Class != IC_CallOrUser && Class != IC_Call)
3324 // If so, we can zap the retain and autorelease.
3327 EraseInstruction(Retain);
3328 EraseInstruction(Autorelease);
3334 DependingInstructions.clear();
3339 bool ObjCARCOpt::doInitialization(Module &M) {
3343 Run = ModuleHasARC(M);
3347 // Identify the imprecise release metadata kind.
3348 ImpreciseReleaseMDKind =
3349 M.getContext().getMDKindID("clang.imprecise_release");
3350 CopyOnEscapeMDKind =
3351 M.getContext().getMDKindID("clang.arc.copy_on_escape");
3353 // Intuitively, objc_retain and others are nocapture, however in practice
3354 // they are not, because they return their argument value. And objc_release
3355 // calls finalizers.
3357 // These are initialized lazily.
3359 AutoreleaseRVCallee = 0;
3362 RetainBlockCallee = 0;
3363 AutoreleaseCallee = 0;
3368 bool ObjCARCOpt::runOnFunction(Function &F) {
3372 // If nothing in the Module uses ARC, don't do anything.
3378 PA.setAA(&getAnalysis<AliasAnalysis>());
3380 // This pass performs several distinct transformations. As a compile-time aid
3381 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3382 // library functions aren't declared.
3384 // Preliminary optimizations. This also computs UsedInThisFunction.
3385 OptimizeIndividualCalls(F);
3387 // Optimizations for weak pointers.
3388 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3389 (1 << IC_LoadWeakRetained) |
3390 (1 << IC_StoreWeak) |
3391 (1 << IC_InitWeak) |
3392 (1 << IC_CopyWeak) |
3393 (1 << IC_MoveWeak) |
3394 (1 << IC_DestroyWeak)))
3395 OptimizeWeakCalls(F);
3397 // Optimizations for retain+release pairs.
3398 if (UsedInThisFunction & ((1 << IC_Retain) |
3399 (1 << IC_RetainRV) |
3400 (1 << IC_RetainBlock)))
3401 if (UsedInThisFunction & (1 << IC_Release))
3402 // Run OptimizeSequences until it either stops making changes or
3403 // no retain+release pair nesting is detected.
3404 while (OptimizeSequences(F)) {}
3406 // Optimizations if objc_autorelease is used.
3407 if (UsedInThisFunction &
3408 ((1 << IC_Autorelease) | (1 << IC_AutoreleaseRV)))
3414 void ObjCARCOpt::releaseMemory() {
3418 //===----------------------------------------------------------------------===//
3420 //===----------------------------------------------------------------------===//
3422 // TODO: ObjCARCContract could insert PHI nodes when uses aren't
3423 // dominated by single calls.
3425 #include "llvm/Operator.h"
3426 #include "llvm/InlineAsm.h"
3427 #include "llvm/Analysis/Dominators.h"
3429 STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed");
3432 /// ObjCARCContract - Late ARC optimizations. These change the IR in a way
3433 /// that makes it difficult to be analyzed by ObjCARCOpt, so it's run late.
3434 class ObjCARCContract : public FunctionPass {
3438 ProvenanceAnalysis PA;
3440 /// Run - A flag indicating whether this optimization pass should run.
3443 /// StoreStrongCallee, etc. - Declarations for ObjC runtime
3444 /// functions, for use in creating calls to them. These are initialized
3445 /// lazily to avoid cluttering up the Module with unused declarations.
3446 Constant *StoreStrongCallee,
3447 *RetainAutoreleaseCallee, *RetainAutoreleaseRVCallee;
3449 /// RetainRVMarker - The inline asm string to insert between calls and
3450 /// RetainRV calls to make the optimization work on targets which need it.
3451 const MDString *RetainRVMarker;
3453 Constant *getStoreStrongCallee(Module *M);
3454 Constant *getRetainAutoreleaseCallee(Module *M);
3455 Constant *getRetainAutoreleaseRVCallee(Module *M);
3457 bool ContractAutorelease(Function &F, Instruction *Autorelease,
3458 InstructionClass Class,
3459 SmallPtrSet<Instruction *, 4>
3460 &DependingInstructions,
3461 SmallPtrSet<const BasicBlock *, 4>
3464 void ContractRelease(Instruction *Release,
3465 inst_iterator &Iter);
3467 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
3468 virtual bool doInitialization(Module &M);
3469 virtual bool runOnFunction(Function &F);
3473 ObjCARCContract() : FunctionPass(ID) {
3474 initializeObjCARCContractPass(*PassRegistry::getPassRegistry());
3479 char ObjCARCContract::ID = 0;
3480 INITIALIZE_PASS_BEGIN(ObjCARCContract,
3481 "objc-arc-contract", "ObjC ARC contraction", false, false)
3482 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3483 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
3484 INITIALIZE_PASS_END(ObjCARCContract,
3485 "objc-arc-contract", "ObjC ARC contraction", false, false)
3487 Pass *llvm::createObjCARCContractPass() {
3488 return new ObjCARCContract();
3491 void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const {
3492 AU.addRequired<AliasAnalysis>();
3493 AU.addRequired<DominatorTree>();
3494 AU.setPreservesCFG();
3497 Constant *ObjCARCContract::getStoreStrongCallee(Module *M) {
3498 if (!StoreStrongCallee) {
3499 LLVMContext &C = M->getContext();
3500 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3501 Type *I8XX = PointerType::getUnqual(I8X);
3502 std::vector<Type *> Params;
3503 Params.push_back(I8XX);
3504 Params.push_back(I8X);
3506 AttrListPtr Attributes;
3507 Attributes.addAttr(~0u, Attribute::NoUnwind);
3508 Attributes.addAttr(1, Attribute::NoCapture);
3511 M->getOrInsertFunction(
3513 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
3516 return StoreStrongCallee;
3519 Constant *ObjCARCContract::getRetainAutoreleaseCallee(Module *M) {
3520 if (!RetainAutoreleaseCallee) {
3521 LLVMContext &C = M->getContext();
3522 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3523 std::vector<Type *> Params;
3524 Params.push_back(I8X);
3526 FunctionType::get(I8X, Params, /*isVarArg=*/false);
3527 AttrListPtr Attributes;
3528 Attributes.addAttr(~0u, Attribute::NoUnwind);
3529 RetainAutoreleaseCallee =
3530 M->getOrInsertFunction("objc_retainAutorelease", FTy, Attributes);
3532 return RetainAutoreleaseCallee;
3535 Constant *ObjCARCContract::getRetainAutoreleaseRVCallee(Module *M) {
3536 if (!RetainAutoreleaseRVCallee) {
3537 LLVMContext &C = M->getContext();
3538 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3539 std::vector<Type *> Params;
3540 Params.push_back(I8X);
3542 FunctionType::get(I8X, Params, /*isVarArg=*/false);
3543 AttrListPtr Attributes;
3544 Attributes.addAttr(~0u, Attribute::NoUnwind);
3545 RetainAutoreleaseRVCallee =
3546 M->getOrInsertFunction("objc_retainAutoreleaseReturnValue", FTy,
3549 return RetainAutoreleaseRVCallee;
3552 /// ContractAutorelease - Merge an autorelease with a retain into a fused
3555 ObjCARCContract::ContractAutorelease(Function &F, Instruction *Autorelease,
3556 InstructionClass Class,
3557 SmallPtrSet<Instruction *, 4>
3558 &DependingInstructions,
3559 SmallPtrSet<const BasicBlock *, 4>
3561 const Value *Arg = GetObjCArg(Autorelease);
3563 // Check that there are no instructions between the retain and the autorelease
3564 // (such as an autorelease_pop) which may change the count.
3565 CallInst *Retain = 0;
3566 if (Class == IC_AutoreleaseRV)
3567 FindDependencies(RetainAutoreleaseRVDep, Arg,
3568 Autorelease->getParent(), Autorelease,
3569 DependingInstructions, Visited, PA);
3571 FindDependencies(RetainAutoreleaseDep, Arg,
3572 Autorelease->getParent(), Autorelease,
3573 DependingInstructions, Visited, PA);
3576 if (DependingInstructions.size() != 1) {
3577 DependingInstructions.clear();
3581 Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3582 DependingInstructions.clear();
3585 GetBasicInstructionClass(Retain) != IC_Retain ||
3586 GetObjCArg(Retain) != Arg)
3592 if (Class == IC_AutoreleaseRV)
3593 Retain->setCalledFunction(getRetainAutoreleaseRVCallee(F.getParent()));
3595 Retain->setCalledFunction(getRetainAutoreleaseCallee(F.getParent()));
3597 EraseInstruction(Autorelease);
3601 /// ContractRelease - Attempt to merge an objc_release with a store, load, and
3602 /// objc_retain to form an objc_storeStrong. This can be a little tricky because
3603 /// the instructions don't always appear in order, and there may be unrelated
3604 /// intervening instructions.
3605 void ObjCARCContract::ContractRelease(Instruction *Release,
3606 inst_iterator &Iter) {
3607 LoadInst *Load = dyn_cast<LoadInst>(GetObjCArg(Release));
3608 if (!Load || !Load->isSimple()) return;
3610 // For now, require everything to be in one basic block.
3611 BasicBlock *BB = Release->getParent();
3612 if (Load->getParent() != BB) return;
3614 // Walk down to find the store.
3615 BasicBlock::iterator I = Load, End = BB->end();
3617 AliasAnalysis::Location Loc = AA->getLocation(Load);
3620 IsRetain(GetBasicInstructionClass(I)) ||
3621 !(AA->getModRefInfo(I, Loc) & AliasAnalysis::Mod)))
3623 StoreInst *Store = dyn_cast<StoreInst>(I);
3624 if (!Store || !Store->isSimple()) return;
3625 if (Store->getPointerOperand() != Loc.Ptr) return;
3627 Value *New = StripPointerCastsAndObjCCalls(Store->getValueOperand());
3629 // Walk up to find the retain.
3631 BasicBlock::iterator Begin = BB->begin();
3632 while (I != Begin && GetBasicInstructionClass(I) != IC_Retain)
3634 Instruction *Retain = I;
3635 if (GetBasicInstructionClass(Retain) != IC_Retain) return;
3636 if (GetObjCArg(Retain) != New) return;
3641 LLVMContext &C = Release->getContext();
3642 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3643 Type *I8XX = PointerType::getUnqual(I8X);
3645 Value *Args[] = { Load->getPointerOperand(), New };
3646 if (Args[0]->getType() != I8XX)
3647 Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
3648 if (Args[1]->getType() != I8X)
3649 Args[1] = new BitCastInst(Args[1], I8X, "", Store);
3650 CallInst *StoreStrong =
3651 CallInst::Create(getStoreStrongCallee(BB->getParent()->getParent()),
3653 StoreStrong->setDoesNotThrow();
3654 StoreStrong->setDebugLoc(Store->getDebugLoc());
3656 if (&*Iter == Store) ++Iter;
3657 Store->eraseFromParent();
3658 Release->eraseFromParent();
3659 EraseInstruction(Retain);
3660 if (Load->use_empty())
3661 Load->eraseFromParent();
3664 bool ObjCARCContract::doInitialization(Module &M) {
3665 Run = ModuleHasARC(M);
3669 // These are initialized lazily.
3670 StoreStrongCallee = 0;
3671 RetainAutoreleaseCallee = 0;
3672 RetainAutoreleaseRVCallee = 0;
3674 // Initialize RetainRVMarker.
3676 if (NamedMDNode *NMD =
3677 M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker"))
3678 if (NMD->getNumOperands() == 1) {
3679 const MDNode *N = NMD->getOperand(0);
3680 if (N->getNumOperands() == 1)
3681 if (const MDString *S = dyn_cast<MDString>(N->getOperand(0)))
3688 bool ObjCARCContract::runOnFunction(Function &F) {
3692 // If nothing in the Module uses ARC, don't do anything.
3697 AA = &getAnalysis<AliasAnalysis>();
3698 DT = &getAnalysis<DominatorTree>();
3700 PA.setAA(&getAnalysis<AliasAnalysis>());
3702 // For ObjC library calls which return their argument, replace uses of the
3703 // argument with uses of the call return value, if it dominates the use. This
3704 // reduces register pressure.
3705 SmallPtrSet<Instruction *, 4> DependingInstructions;
3706 SmallPtrSet<const BasicBlock *, 4> Visited;
3707 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3708 Instruction *Inst = &*I++;
3710 // Only these library routines return their argument. In particular,
3711 // objc_retainBlock does not necessarily return its argument.
3712 InstructionClass Class = GetBasicInstructionClass(Inst);
3715 case IC_FusedRetainAutorelease:
3716 case IC_FusedRetainAutoreleaseRV:
3718 case IC_Autorelease:
3719 case IC_AutoreleaseRV:
3720 if (ContractAutorelease(F, Inst, Class, DependingInstructions, Visited))
3724 // If we're compiling for a target which needs a special inline-asm
3725 // marker to do the retainAutoreleasedReturnValue optimization,
3727 if (!RetainRVMarker)
3729 BasicBlock::iterator BBI = Inst;
3731 while (isNoopInstruction(BBI)) --BBI;
3732 if (&*BBI == GetObjCArg(Inst)) {
3734 InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()),
3735 /*isVarArg=*/false),
3736 RetainRVMarker->getString(),
3737 /*Constraints=*/"", /*hasSideEffects=*/true);
3738 CallInst::Create(IA, "", Inst);
3743 // objc_initWeak(p, null) => *p = null
3744 CallInst *CI = cast<CallInst>(Inst);
3745 if (isNullOrUndef(CI->getArgOperand(1))) {
3747 ConstantPointerNull::get(cast<PointerType>(CI->getType()));
3749 new StoreInst(Null, CI->getArgOperand(0), CI);
3750 CI->replaceAllUsesWith(Null);
3751 CI->eraseFromParent();
3756 ContractRelease(Inst, I);
3762 // Don't use GetObjCArg because we don't want to look through bitcasts
3763 // and such; to do the replacement, the argument must have type i8*.
3764 const Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
3766 // If we're compiling bugpointed code, don't get in trouble.
3767 if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
3769 // Look through the uses of the pointer.
3770 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
3772 Use &U = UI.getUse();
3773 unsigned OperandNo = UI.getOperandNo();
3774 ++UI; // Increment UI now, because we may unlink its element.
3775 if (Instruction *UserInst = dyn_cast<Instruction>(U.getUser()))
3776 if (Inst != UserInst && DT->dominates(Inst, UserInst)) {
3778 Instruction *Replacement = Inst;
3779 Type *UseTy = U.get()->getType();
3780 if (PHINode *PHI = dyn_cast<PHINode>(UserInst)) {
3781 // For PHI nodes, insert the bitcast in the predecessor block.
3783 PHINode::getIncomingValueNumForOperand(OperandNo);
3785 PHI->getIncomingBlock(ValNo);
3786 if (Replacement->getType() != UseTy)
3787 Replacement = new BitCastInst(Replacement, UseTy, "",
3789 for (unsigned i = 0, e = PHI->getNumIncomingValues();
3791 if (PHI->getIncomingBlock(i) == BB) {
3792 // Keep the UI iterator valid.
3793 if (&PHI->getOperandUse(
3794 PHINode::getOperandNumForIncomingValue(i)) ==
3797 PHI->setIncomingValue(i, Replacement);
3800 if (Replacement->getType() != UseTy)
3801 Replacement = new BitCastInst(Replacement, UseTy, "", UserInst);
3807 // If Arg is a no-op casted pointer, strip one level of casts and
3809 if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
3810 Arg = BI->getOperand(0);
3811 else if (isa<GEPOperator>(Arg) &&
3812 cast<GEPOperator>(Arg)->hasAllZeroIndices())
3813 Arg = cast<GEPOperator>(Arg)->getPointerOperand();
3814 else if (isa<GlobalAlias>(Arg) &&
3815 !cast<GlobalAlias>(Arg)->mayBeOverridden())
3816 Arg = cast<GlobalAlias>(Arg)->getAliasee();