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, and not function pointers.
183 PointerType *Ty = dyn_cast<PointerType>(Op->getType());
184 if (!Ty || isa<FunctionType>(Ty->getElementType()))
186 // Conservatively assume anything else is a potential use.
190 /// GetCallSiteClass - Helper for GetInstructionClass. Determines what kind
191 /// of construct CS is.
192 static InstructionClass GetCallSiteClass(ImmutableCallSite CS) {
193 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
195 if (IsPotentialUse(*I))
196 return CS.onlyReadsMemory() ? IC_User : IC_CallOrUser;
198 return CS.onlyReadsMemory() ? IC_None : IC_Call;
201 /// GetFunctionClass - Determine if F is one of the special known Functions.
202 /// If it isn't, return IC_CallOrUser.
203 static InstructionClass GetFunctionClass(const Function *F) {
204 Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
208 return StringSwitch<InstructionClass>(F->getName())
209 .Case("objc_autoreleasePoolPush", IC_AutoreleasepoolPush)
210 .Default(IC_CallOrUser);
213 const Argument *A0 = AI++;
215 // Argument is a pointer.
216 if (PointerType *PTy = dyn_cast<PointerType>(A0->getType())) {
217 Type *ETy = PTy->getElementType();
219 if (ETy->isIntegerTy(8))
220 return StringSwitch<InstructionClass>(F->getName())
221 .Case("objc_retain", IC_Retain)
222 .Case("objc_retainAutoreleasedReturnValue", IC_RetainRV)
223 .Case("objc_retainBlock", IC_RetainBlock)
224 .Case("objc_release", IC_Release)
225 .Case("objc_autorelease", IC_Autorelease)
226 .Case("objc_autoreleaseReturnValue", IC_AutoreleaseRV)
227 .Case("objc_autoreleasePoolPop", IC_AutoreleasepoolPop)
228 .Case("objc_retainedObject", IC_NoopCast)
229 .Case("objc_unretainedObject", IC_NoopCast)
230 .Case("objc_unretainedPointer", IC_NoopCast)
231 .Case("objc_retain_autorelease", IC_FusedRetainAutorelease)
232 .Case("objc_retainAutorelease", IC_FusedRetainAutorelease)
233 .Case("objc_retainAutoreleaseReturnValue",IC_FusedRetainAutoreleaseRV)
234 .Default(IC_CallOrUser);
237 if (PointerType *Pte = dyn_cast<PointerType>(ETy))
238 if (Pte->getElementType()->isIntegerTy(8))
239 return StringSwitch<InstructionClass>(F->getName())
240 .Case("objc_loadWeakRetained", IC_LoadWeakRetained)
241 .Case("objc_loadWeak", IC_LoadWeak)
242 .Case("objc_destroyWeak", IC_DestroyWeak)
243 .Default(IC_CallOrUser);
246 // Two arguments, first is i8**.
247 const Argument *A1 = AI++;
249 if (PointerType *PTy = dyn_cast<PointerType>(A0->getType()))
250 if (PointerType *Pte = dyn_cast<PointerType>(PTy->getElementType()))
251 if (Pte->getElementType()->isIntegerTy(8))
252 if (PointerType *PTy1 = dyn_cast<PointerType>(A1->getType())) {
253 Type *ETy1 = PTy1->getElementType();
254 // Second argument is i8*
255 if (ETy1->isIntegerTy(8))
256 return StringSwitch<InstructionClass>(F->getName())
257 .Case("objc_storeWeak", IC_StoreWeak)
258 .Case("objc_initWeak", IC_InitWeak)
259 .Default(IC_CallOrUser);
260 // Second argument is i8**.
261 if (PointerType *Pte1 = dyn_cast<PointerType>(ETy1))
262 if (Pte1->getElementType()->isIntegerTy(8))
263 return StringSwitch<InstructionClass>(F->getName())
264 .Case("objc_moveWeak", IC_MoveWeak)
265 .Case("objc_copyWeak", IC_CopyWeak)
266 .Default(IC_CallOrUser);
270 return IC_CallOrUser;
273 /// GetInstructionClass - Determine what kind of construct V is.
274 static InstructionClass GetInstructionClass(const Value *V) {
275 if (const Instruction *I = dyn_cast<Instruction>(V)) {
276 // Any instruction other than bitcast and gep with a pointer operand have a
277 // use of an objc pointer. Bitcasts, GEPs, Selects, PHIs transfer a pointer
278 // to a subsequent use, rather than using it themselves, in this sense.
279 // As a short cut, several other opcodes are known to have no pointer
280 // operands of interest. And ret is never followed by a release, so it's
281 // not interesting to examine.
282 switch (I->getOpcode()) {
283 case Instruction::Call: {
284 const CallInst *CI = cast<CallInst>(I);
285 // Check for calls to special functions.
286 if (const Function *F = CI->getCalledFunction()) {
287 InstructionClass Class = GetFunctionClass(F);
288 if (Class != IC_CallOrUser)
291 // None of the intrinsic functions do objc_release. For intrinsics, the
292 // only question is whether or not they may be users.
293 switch (F->getIntrinsicID()) {
295 case Intrinsic::bswap: case Intrinsic::ctpop:
296 case Intrinsic::ctlz: case Intrinsic::cttz:
297 case Intrinsic::returnaddress: case Intrinsic::frameaddress:
298 case Intrinsic::stacksave: case Intrinsic::stackrestore:
299 case Intrinsic::vastart: case Intrinsic::vacopy: case Intrinsic::vaend:
300 // Don't let dbg info affect our results.
301 case Intrinsic::dbg_declare: case Intrinsic::dbg_value:
302 // Short cut: Some intrinsics obviously don't use ObjC pointers.
305 for (Function::const_arg_iterator AI = F->arg_begin(),
306 AE = F->arg_end(); AI != AE; ++AI)
307 if (IsPotentialUse(AI))
312 return GetCallSiteClass(CI);
314 case Instruction::Invoke:
315 return GetCallSiteClass(cast<InvokeInst>(I));
316 case Instruction::BitCast:
317 case Instruction::GetElementPtr:
318 case Instruction::Select: case Instruction::PHI:
319 case Instruction::Ret: case Instruction::Br:
320 case Instruction::Switch: case Instruction::IndirectBr:
321 case Instruction::Alloca: case Instruction::VAArg:
322 case Instruction::Add: case Instruction::FAdd:
323 case Instruction::Sub: case Instruction::FSub:
324 case Instruction::Mul: case Instruction::FMul:
325 case Instruction::SDiv: case Instruction::UDiv: case Instruction::FDiv:
326 case Instruction::SRem: case Instruction::URem: case Instruction::FRem:
327 case Instruction::Shl: case Instruction::LShr: case Instruction::AShr:
328 case Instruction::And: case Instruction::Or: case Instruction::Xor:
329 case Instruction::SExt: case Instruction::ZExt: case Instruction::Trunc:
330 case Instruction::IntToPtr: case Instruction::FCmp:
331 case Instruction::FPTrunc: case Instruction::FPExt:
332 case Instruction::FPToUI: case Instruction::FPToSI:
333 case Instruction::UIToFP: case Instruction::SIToFP:
334 case Instruction::InsertElement: case Instruction::ExtractElement:
335 case Instruction::ShuffleVector:
336 case Instruction::ExtractValue:
338 case Instruction::ICmp:
339 // Comparing a pointer with null, or any other constant, isn't an
340 // interesting use, because we don't care what the pointer points to, or
341 // about the values of any other dynamic reference-counted pointers.
342 if (IsPotentialUse(I->getOperand(1)))
346 // For anything else, check all the operands.
347 // Note that this includes both operands of a Store: while the first
348 // operand isn't actually being dereferenced, it is being stored to
349 // memory where we can no longer track who might read it and dereference
350 // it, so we have to consider it potentially used.
351 for (User::const_op_iterator OI = I->op_begin(), OE = I->op_end();
353 if (IsPotentialUse(*OI))
358 // Otherwise, it's totally inert for ARC purposes.
362 /// GetBasicInstructionClass - Determine what kind of construct V is. This is
363 /// similar to GetInstructionClass except that it only detects objc runtine
364 /// calls. This allows it to be faster.
365 static InstructionClass GetBasicInstructionClass(const Value *V) {
366 if (const CallInst *CI = dyn_cast<CallInst>(V)) {
367 if (const Function *F = CI->getCalledFunction())
368 return GetFunctionClass(F);
369 // Otherwise, be conservative.
370 return IC_CallOrUser;
373 // Otherwise, be conservative.
377 /// IsRetain - Test if the the given class is objc_retain or
379 static bool IsRetain(InstructionClass Class) {
380 return Class == IC_Retain ||
381 Class == IC_RetainRV;
384 /// IsAutorelease - Test if the the given class is objc_autorelease or
386 static bool IsAutorelease(InstructionClass Class) {
387 return Class == IC_Autorelease ||
388 Class == IC_AutoreleaseRV;
391 /// IsForwarding - Test if the given class represents instructions which return
392 /// their argument verbatim.
393 static bool IsForwarding(InstructionClass Class) {
394 // objc_retainBlock technically doesn't always return its argument
395 // verbatim, but it doesn't matter for our purposes here.
396 return Class == IC_Retain ||
397 Class == IC_RetainRV ||
398 Class == IC_Autorelease ||
399 Class == IC_AutoreleaseRV ||
400 Class == IC_RetainBlock ||
401 Class == IC_NoopCast;
404 /// IsNoopOnNull - Test if the given class represents instructions which do
405 /// nothing if passed a null pointer.
406 static bool IsNoopOnNull(InstructionClass Class) {
407 return Class == IC_Retain ||
408 Class == IC_RetainRV ||
409 Class == IC_Release ||
410 Class == IC_Autorelease ||
411 Class == IC_AutoreleaseRV ||
412 Class == IC_RetainBlock;
415 /// IsAlwaysTail - Test if the given class represents instructions which are
416 /// always safe to mark with the "tail" keyword.
417 static bool IsAlwaysTail(InstructionClass Class) {
418 // IC_RetainBlock may be given a stack argument.
419 return Class == IC_Retain ||
420 Class == IC_RetainRV ||
421 Class == IC_Autorelease ||
422 Class == IC_AutoreleaseRV;
425 /// IsNoThrow - Test if the given class represents instructions which are always
426 /// safe to mark with the nounwind attribute..
427 static bool IsNoThrow(InstructionClass Class) {
428 // objc_retainBlock is not nounwind because it calls user copy constructors
429 // which could theoretically throw.
430 return Class == IC_Retain ||
431 Class == IC_RetainRV ||
432 Class == IC_Release ||
433 Class == IC_Autorelease ||
434 Class == IC_AutoreleaseRV ||
435 Class == IC_AutoreleasepoolPush ||
436 Class == IC_AutoreleasepoolPop;
439 /// EraseInstruction - Erase the given instruction. ObjC calls return their
440 /// argument verbatim, so if it's such a call and the return value has users,
441 /// replace them with the argument value.
442 static void EraseInstruction(Instruction *CI) {
443 Value *OldArg = cast<CallInst>(CI)->getArgOperand(0);
445 bool Unused = CI->use_empty();
448 // Replace the return value with the argument.
449 assert(IsForwarding(GetBasicInstructionClass(CI)) &&
450 "Can't delete non-forwarding instruction with users!");
451 CI->replaceAllUsesWith(OldArg);
454 CI->eraseFromParent();
457 RecursivelyDeleteTriviallyDeadInstructions(OldArg);
460 /// GetUnderlyingObjCPtr - This is a wrapper around getUnderlyingObject which
461 /// also knows how to look through objc_retain and objc_autorelease calls, which
462 /// we know to return their argument verbatim.
463 static const Value *GetUnderlyingObjCPtr(const Value *V) {
465 V = GetUnderlyingObject(V);
466 if (!IsForwarding(GetBasicInstructionClass(V)))
468 V = cast<CallInst>(V)->getArgOperand(0);
474 /// StripPointerCastsAndObjCCalls - This is a wrapper around
475 /// Value::stripPointerCasts which also knows how to look through objc_retain
476 /// and objc_autorelease calls, which we know to return their argument verbatim.
477 static const Value *StripPointerCastsAndObjCCalls(const Value *V) {
479 V = V->stripPointerCasts();
480 if (!IsForwarding(GetBasicInstructionClass(V)))
482 V = cast<CallInst>(V)->getArgOperand(0);
487 /// StripPointerCastsAndObjCCalls - This is a wrapper around
488 /// Value::stripPointerCasts which also knows how to look through objc_retain
489 /// and objc_autorelease calls, which we know to return their argument verbatim.
490 static Value *StripPointerCastsAndObjCCalls(Value *V) {
492 V = V->stripPointerCasts();
493 if (!IsForwarding(GetBasicInstructionClass(V)))
495 V = cast<CallInst>(V)->getArgOperand(0);
500 /// GetObjCArg - Assuming the given instruction is one of the special calls such
501 /// as objc_retain or objc_release, return the argument value, stripped of no-op
502 /// casts and forwarding calls.
503 static Value *GetObjCArg(Value *Inst) {
504 return StripPointerCastsAndObjCCalls(cast<CallInst>(Inst)->getArgOperand(0));
507 /// IsObjCIdentifiedObject - This is similar to AliasAnalysis'
508 /// isObjCIdentifiedObject, except that it uses special knowledge of
509 /// ObjC conventions...
510 static bool IsObjCIdentifiedObject(const Value *V) {
511 // Assume that call results and arguments have their own "provenance".
512 // Constants (including GlobalVariables) and Allocas are never
513 // reference-counted.
514 if (isa<CallInst>(V) || isa<InvokeInst>(V) ||
515 isa<Argument>(V) || isa<Constant>(V) ||
519 if (const LoadInst *LI = dyn_cast<LoadInst>(V)) {
520 const Value *Pointer =
521 StripPointerCastsAndObjCCalls(LI->getPointerOperand());
522 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Pointer)) {
523 // A constant pointer can't be pointing to an object on the heap. It may
524 // be reference-counted, but it won't be deleted.
525 if (GV->isConstant())
527 StringRef Name = GV->getName();
528 // These special variables are known to hold values which are not
529 // reference-counted pointers.
530 if (Name.startswith("\01L_OBJC_SELECTOR_REFERENCES_") ||
531 Name.startswith("\01L_OBJC_CLASSLIST_REFERENCES_") ||
532 Name.startswith("\01L_OBJC_CLASSLIST_SUP_REFS_$_") ||
533 Name.startswith("\01L_OBJC_METH_VAR_NAME_") ||
534 Name.startswith("\01l_objc_msgSend_fixup_"))
542 /// FindSingleUseIdentifiedObject - This is similar to
543 /// StripPointerCastsAndObjCCalls but it stops as soon as it finds a value
544 /// with multiple uses.
545 static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
546 if (Arg->hasOneUse()) {
547 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
548 return FindSingleUseIdentifiedObject(BC->getOperand(0));
549 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
550 if (GEP->hasAllZeroIndices())
551 return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
552 if (IsForwarding(GetBasicInstructionClass(Arg)))
553 return FindSingleUseIdentifiedObject(
554 cast<CallInst>(Arg)->getArgOperand(0));
555 if (!IsObjCIdentifiedObject(Arg))
560 // If we found an identifiable object but it has multiple uses, but they
561 // are trivial uses, we can still consider this to be a single-use
563 if (IsObjCIdentifiedObject(Arg)) {
564 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
567 if (!U->use_empty() || StripPointerCastsAndObjCCalls(U) != Arg)
577 /// ModuleHasARC - Test if the given module looks interesting to run ARC
579 static bool ModuleHasARC(const Module &M) {
581 M.getNamedValue("objc_retain") ||
582 M.getNamedValue("objc_release") ||
583 M.getNamedValue("objc_autorelease") ||
584 M.getNamedValue("objc_retainAutoreleasedReturnValue") ||
585 M.getNamedValue("objc_retainBlock") ||
586 M.getNamedValue("objc_autoreleaseReturnValue") ||
587 M.getNamedValue("objc_autoreleasePoolPush") ||
588 M.getNamedValue("objc_loadWeakRetained") ||
589 M.getNamedValue("objc_loadWeak") ||
590 M.getNamedValue("objc_destroyWeak") ||
591 M.getNamedValue("objc_storeWeak") ||
592 M.getNamedValue("objc_initWeak") ||
593 M.getNamedValue("objc_moveWeak") ||
594 M.getNamedValue("objc_copyWeak") ||
595 M.getNamedValue("objc_retainedObject") ||
596 M.getNamedValue("objc_unretainedObject") ||
597 M.getNamedValue("objc_unretainedPointer");
600 //===----------------------------------------------------------------------===//
601 // ARC AliasAnalysis.
602 //===----------------------------------------------------------------------===//
604 #include "llvm/Pass.h"
605 #include "llvm/Analysis/AliasAnalysis.h"
606 #include "llvm/Analysis/Passes.h"
609 /// ObjCARCAliasAnalysis - This is a simple alias analysis
610 /// implementation that uses knowledge of ARC constructs to answer queries.
612 /// TODO: This class could be generalized to know about other ObjC-specific
613 /// tricks. Such as knowing that ivars in the non-fragile ABI are non-aliasing
614 /// even though their offsets are dynamic.
615 class ObjCARCAliasAnalysis : public ImmutablePass,
616 public AliasAnalysis {
618 static char ID; // Class identification, replacement for typeinfo
619 ObjCARCAliasAnalysis() : ImmutablePass(ID) {
620 initializeObjCARCAliasAnalysisPass(*PassRegistry::getPassRegistry());
624 virtual void initializePass() {
625 InitializeAliasAnalysis(this);
628 /// getAdjustedAnalysisPointer - This method is used when a pass implements
629 /// an analysis interface through multiple inheritance. If needed, it
630 /// should override this to adjust the this pointer as needed for the
631 /// specified pass info.
632 virtual void *getAdjustedAnalysisPointer(const void *PI) {
633 if (PI == &AliasAnalysis::ID)
634 return (AliasAnalysis*)this;
638 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
639 virtual AliasResult alias(const Location &LocA, const Location &LocB);
640 virtual bool pointsToConstantMemory(const Location &Loc, bool OrLocal);
641 virtual ModRefBehavior getModRefBehavior(ImmutableCallSite CS);
642 virtual ModRefBehavior getModRefBehavior(const Function *F);
643 virtual ModRefResult getModRefInfo(ImmutableCallSite CS,
644 const Location &Loc);
645 virtual ModRefResult getModRefInfo(ImmutableCallSite CS1,
646 ImmutableCallSite CS2);
648 } // End of anonymous namespace
650 // Register this pass...
651 char ObjCARCAliasAnalysis::ID = 0;
652 INITIALIZE_AG_PASS(ObjCARCAliasAnalysis, AliasAnalysis, "objc-arc-aa",
653 "ObjC-ARC-Based Alias Analysis", false, true, false)
655 ImmutablePass *llvm::createObjCARCAliasAnalysisPass() {
656 return new ObjCARCAliasAnalysis();
660 ObjCARCAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
661 AU.setPreservesAll();
662 AliasAnalysis::getAnalysisUsage(AU);
665 AliasAnalysis::AliasResult
666 ObjCARCAliasAnalysis::alias(const Location &LocA, const Location &LocB) {
668 return AliasAnalysis::alias(LocA, LocB);
670 // First, strip off no-ops, including ObjC-specific no-ops, and try making a
671 // precise alias query.
672 const Value *SA = StripPointerCastsAndObjCCalls(LocA.Ptr);
673 const Value *SB = StripPointerCastsAndObjCCalls(LocB.Ptr);
675 AliasAnalysis::alias(Location(SA, LocA.Size, LocA.TBAATag),
676 Location(SB, LocB.Size, LocB.TBAATag));
677 if (Result != MayAlias)
680 // If that failed, climb to the underlying object, including climbing through
681 // ObjC-specific no-ops, and try making an imprecise alias query.
682 const Value *UA = GetUnderlyingObjCPtr(SA);
683 const Value *UB = GetUnderlyingObjCPtr(SB);
684 if (UA != SA || UB != SB) {
685 Result = AliasAnalysis::alias(Location(UA), Location(UB));
686 // We can't use MustAlias or PartialAlias results here because
687 // GetUnderlyingObjCPtr may return an offsetted pointer value.
688 if (Result == NoAlias)
692 // If that failed, fail. We don't need to chain here, since that's covered
693 // by the earlier precise query.
698 ObjCARCAliasAnalysis::pointsToConstantMemory(const Location &Loc,
701 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
703 // First, strip off no-ops, including ObjC-specific no-ops, and try making
704 // a precise alias query.
705 const Value *S = StripPointerCastsAndObjCCalls(Loc.Ptr);
706 if (AliasAnalysis::pointsToConstantMemory(Location(S, Loc.Size, Loc.TBAATag),
710 // If that failed, climb to the underlying object, including climbing through
711 // ObjC-specific no-ops, and try making an imprecise alias query.
712 const Value *U = GetUnderlyingObjCPtr(S);
714 return AliasAnalysis::pointsToConstantMemory(Location(U), OrLocal);
716 // If that failed, fail. We don't need to chain here, since that's covered
717 // by the earlier precise query.
721 AliasAnalysis::ModRefBehavior
722 ObjCARCAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
723 // We have nothing to do. Just chain to the next AliasAnalysis.
724 return AliasAnalysis::getModRefBehavior(CS);
727 AliasAnalysis::ModRefBehavior
728 ObjCARCAliasAnalysis::getModRefBehavior(const Function *F) {
730 return AliasAnalysis::getModRefBehavior(F);
732 switch (GetFunctionClass(F)) {
734 return DoesNotAccessMemory;
739 return AliasAnalysis::getModRefBehavior(F);
742 AliasAnalysis::ModRefResult
743 ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS, const Location &Loc) {
745 return AliasAnalysis::getModRefInfo(CS, Loc);
747 switch (GetBasicInstructionClass(CS.getInstruction())) {
751 case IC_AutoreleaseRV:
753 case IC_AutoreleasepoolPush:
754 case IC_FusedRetainAutorelease:
755 case IC_FusedRetainAutoreleaseRV:
756 // These functions don't access any memory visible to the compiler.
757 // Note that this doesn't include objc_retainBlock, becuase it updates
758 // pointers when it copies block data.
764 return AliasAnalysis::getModRefInfo(CS, Loc);
767 AliasAnalysis::ModRefResult
768 ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
769 ImmutableCallSite CS2) {
770 // TODO: Theoretically we could check for dependencies between objc_* calls
771 // and OnlyAccessesArgumentPointees calls or other well-behaved calls.
772 return AliasAnalysis::getModRefInfo(CS1, CS2);
775 //===----------------------------------------------------------------------===//
777 //===----------------------------------------------------------------------===//
779 #include "llvm/Support/InstIterator.h"
780 #include "llvm/Transforms/Scalar.h"
783 /// ObjCARCExpand - Early ARC transformations.
784 class ObjCARCExpand : public FunctionPass {
785 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
786 virtual bool doInitialization(Module &M);
787 virtual bool runOnFunction(Function &F);
789 /// Run - A flag indicating whether this optimization pass should run.
794 ObjCARCExpand() : FunctionPass(ID) {
795 initializeObjCARCExpandPass(*PassRegistry::getPassRegistry());
800 char ObjCARCExpand::ID = 0;
801 INITIALIZE_PASS(ObjCARCExpand,
802 "objc-arc-expand", "ObjC ARC expansion", false, false)
804 Pass *llvm::createObjCARCExpandPass() {
805 return new ObjCARCExpand();
808 void ObjCARCExpand::getAnalysisUsage(AnalysisUsage &AU) const {
809 AU.setPreservesCFG();
812 bool ObjCARCExpand::doInitialization(Module &M) {
813 Run = ModuleHasARC(M);
817 bool ObjCARCExpand::runOnFunction(Function &F) {
821 // If nothing in the Module uses ARC, don't do anything.
825 bool Changed = false;
827 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
828 Instruction *Inst = &*I;
830 switch (GetBasicInstructionClass(Inst)) {
834 case IC_AutoreleaseRV:
835 case IC_FusedRetainAutorelease:
836 case IC_FusedRetainAutoreleaseRV:
837 // These calls return their argument verbatim, as a low-level
838 // optimization. However, this makes high-level optimizations
839 // harder. Undo any uses of this optimization that the front-end
840 // emitted here. We'll redo them in a later pass.
842 Inst->replaceAllUsesWith(cast<CallInst>(Inst)->getArgOperand(0));
852 //===----------------------------------------------------------------------===//
854 //===----------------------------------------------------------------------===//
856 // TODO: On code like this:
859 // stuff_that_cannot_release()
860 // objc_autorelease(%x)
861 // stuff_that_cannot_release()
863 // stuff_that_cannot_release()
864 // objc_autorelease(%x)
866 // The second retain and autorelease can be deleted.
868 // TODO: It should be possible to delete
869 // objc_autoreleasePoolPush and objc_autoreleasePoolPop
870 // pairs if nothing is actually autoreleased between them. Also, autorelease
871 // calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
872 // after inlining) can be turned into plain release calls.
874 // TODO: Critical-edge splitting. If the optimial insertion point is
875 // a critical edge, the current algorithm has to fail, because it doesn't
876 // know how to split edges. It should be possible to make the optimizer
877 // think in terms of edges, rather than blocks, and then split critical
880 // TODO: OptimizeSequences could generalized to be Interprocedural.
882 // TODO: Recognize that a bunch of other objc runtime calls have
883 // non-escaping arguments and non-releasing arguments, and may be
884 // non-autoreleasing.
886 // TODO: Sink autorelease calls as far as possible. Unfortunately we
887 // usually can't sink them past other calls, which would be the main
888 // case where it would be useful.
890 // TODO: The pointer returned from objc_loadWeakRetained is retained.
892 // TODO: Delete release+retain pairs (rare).
894 #include "llvm/GlobalAlias.h"
895 #include "llvm/Constants.h"
896 #include "llvm/LLVMContext.h"
897 #include "llvm/Support/ErrorHandling.h"
898 #include "llvm/Support/CFG.h"
899 #include "llvm/ADT/PostOrderIterator.h"
900 #include "llvm/ADT/Statistic.h"
902 STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
903 STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
904 STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
905 STATISTIC(NumRets, "Number of return value forwarding "
906 "retain+autoreleaes eliminated");
907 STATISTIC(NumRRs, "Number of retain+release paths eliminated");
908 STATISTIC(NumPeeps, "Number of calls peephole-optimized");
911 /// ProvenanceAnalysis - This is similar to BasicAliasAnalysis, and it
912 /// uses many of the same techniques, except it uses special ObjC-specific
913 /// reasoning about pointer relationships.
914 class ProvenanceAnalysis {
917 typedef std::pair<const Value *, const Value *> ValuePairTy;
918 typedef DenseMap<ValuePairTy, bool> CachedResultsTy;
919 CachedResultsTy CachedResults;
921 bool relatedCheck(const Value *A, const Value *B);
922 bool relatedSelect(const SelectInst *A, const Value *B);
923 bool relatedPHI(const PHINode *A, const Value *B);
926 void operator=(const ProvenanceAnalysis &);
927 ProvenanceAnalysis(const ProvenanceAnalysis &);
930 ProvenanceAnalysis() {}
932 void setAA(AliasAnalysis *aa) { AA = aa; }
934 AliasAnalysis *getAA() const { return AA; }
936 bool related(const Value *A, const Value *B);
939 CachedResults.clear();
944 bool ProvenanceAnalysis::relatedSelect(const SelectInst *A, const Value *B) {
945 // If the values are Selects with the same condition, we can do a more precise
946 // check: just check for relations between the values on corresponding arms.
947 if (const SelectInst *SB = dyn_cast<SelectInst>(B))
948 if (A->getCondition() == SB->getCondition()) {
949 if (related(A->getTrueValue(), SB->getTrueValue()))
951 if (related(A->getFalseValue(), SB->getFalseValue()))
956 // Check both arms of the Select node individually.
957 if (related(A->getTrueValue(), B))
959 if (related(A->getFalseValue(), B))
962 // The arms both checked out.
966 bool ProvenanceAnalysis::relatedPHI(const PHINode *A, const Value *B) {
967 // If the values are PHIs in the same block, we can do a more precise as well
968 // as efficient check: just check for relations between the values on
969 // corresponding edges.
970 if (const PHINode *PNB = dyn_cast<PHINode>(B))
971 if (PNB->getParent() == A->getParent()) {
972 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i)
973 if (related(A->getIncomingValue(i),
974 PNB->getIncomingValueForBlock(A->getIncomingBlock(i))))
979 // Check each unique source of the PHI node against B.
980 SmallPtrSet<const Value *, 4> UniqueSrc;
981 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i) {
982 const Value *PV1 = A->getIncomingValue(i);
983 if (UniqueSrc.insert(PV1) && related(PV1, B))
987 // All of the arms checked out.
991 /// isStoredObjCPointer - Test if the value of P, or any value covered by its
992 /// provenance, is ever stored within the function (not counting callees).
993 static bool isStoredObjCPointer(const Value *P) {
994 SmallPtrSet<const Value *, 8> Visited;
995 SmallVector<const Value *, 8> Worklist;
996 Worklist.push_back(P);
999 P = Worklist.pop_back_val();
1000 for (Value::const_use_iterator UI = P->use_begin(), UE = P->use_end();
1002 const User *Ur = *UI;
1003 if (isa<StoreInst>(Ur)) {
1004 if (UI.getOperandNo() == 0)
1005 // The pointer is stored.
1007 // The pointed is stored through.
1010 if (isa<CallInst>(Ur))
1011 // The pointer is passed as an argument, ignore this.
1013 if (isa<PtrToIntInst>(P))
1014 // Assume the worst.
1016 if (Visited.insert(Ur))
1017 Worklist.push_back(Ur);
1019 } while (!Worklist.empty());
1021 // Everything checked out.
1025 bool ProvenanceAnalysis::relatedCheck(const Value *A, const Value *B) {
1026 // Skip past provenance pass-throughs.
1027 A = GetUnderlyingObjCPtr(A);
1028 B = GetUnderlyingObjCPtr(B);
1034 // Ask regular AliasAnalysis, for a first approximation.
1035 switch (AA->alias(A, B)) {
1036 case AliasAnalysis::NoAlias:
1038 case AliasAnalysis::MustAlias:
1039 case AliasAnalysis::PartialAlias:
1041 case AliasAnalysis::MayAlias:
1045 bool AIsIdentified = IsObjCIdentifiedObject(A);
1046 bool BIsIdentified = IsObjCIdentifiedObject(B);
1048 // An ObjC-Identified object can't alias a load if it is never locally stored.
1049 if (AIsIdentified) {
1050 if (BIsIdentified) {
1051 // If both pointers have provenance, they can be directly compared.
1055 if (isa<LoadInst>(B))
1056 return isStoredObjCPointer(A);
1059 if (BIsIdentified && isa<LoadInst>(A))
1060 return isStoredObjCPointer(B);
1063 // Special handling for PHI and Select.
1064 if (const PHINode *PN = dyn_cast<PHINode>(A))
1065 return relatedPHI(PN, B);
1066 if (const PHINode *PN = dyn_cast<PHINode>(B))
1067 return relatedPHI(PN, A);
1068 if (const SelectInst *S = dyn_cast<SelectInst>(A))
1069 return relatedSelect(S, B);
1070 if (const SelectInst *S = dyn_cast<SelectInst>(B))
1071 return relatedSelect(S, A);
1077 bool ProvenanceAnalysis::related(const Value *A, const Value *B) {
1078 // Begin by inserting a conservative value into the map. If the insertion
1079 // fails, we have the answer already. If it succeeds, leave it there until we
1080 // compute the real answer to guard against recursive queries.
1081 if (A > B) std::swap(A, B);
1082 std::pair<CachedResultsTy::iterator, bool> Pair =
1083 CachedResults.insert(std::make_pair(ValuePairTy(A, B), true));
1085 return Pair.first->second;
1087 bool Result = relatedCheck(A, B);
1088 CachedResults[ValuePairTy(A, B)] = Result;
1093 // Sequence - A sequence of states that a pointer may go through in which an
1094 // objc_retain and objc_release are actually needed.
1097 S_Retain, ///< objc_retain(x)
1098 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement
1099 S_Use, ///< any use of x
1100 S_Stop, ///< like S_Release, but code motion is stopped
1101 S_Release, ///< objc_release(x)
1102 S_MovableRelease ///< objc_release(x), !clang.imprecise_release
1106 static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
1110 if (A == S_None || B == S_None)
1113 if (A > B) std::swap(A, B);
1115 // Choose the side which is further along in the sequence.
1116 if ((A == S_Retain || A == S_CanRelease) &&
1117 (B == S_CanRelease || B == S_Use))
1120 // Choose the side which is further along in the sequence.
1121 if ((A == S_Use || A == S_CanRelease) &&
1122 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
1124 // If both sides are releases, choose the more conservative one.
1125 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
1127 if (A == S_Release && B == S_MovableRelease)
1135 /// RRInfo - Unidirectional information about either a
1136 /// retain-decrement-use-release sequence or release-use-decrement-retain
1137 /// reverese sequence.
1139 /// KnownSafe - After an objc_retain, the reference count of the referenced
1140 /// object is known to be positive. Similarly, before an objc_release, the
1141 /// reference count of the referenced object is known to be positive. If
1142 /// there are retain-release pairs in code regions where the retain count
1143 /// is known to be positive, they can be eliminated, regardless of any side
1144 /// effects between them.
1146 /// Also, a retain+release pair nested within another retain+release
1147 /// pair all on the known same pointer value can be eliminated, regardless
1148 /// of any intervening side effects.
1150 /// KnownSafe is true when either of these conditions is satisfied.
1153 /// IsRetainBlock - True if the Calls are objc_retainBlock calls (as
1154 /// opposed to objc_retain calls).
1157 /// CopyOnEscape - True if this the Calls are objc_retainBlock calls
1158 /// which all have the !clang.arc.copy_on_escape metadata.
1161 /// IsTailCallRelease - True of the objc_release calls are all marked
1162 /// with the "tail" keyword.
1163 bool IsTailCallRelease;
1165 /// Partial - True of we've seen an opportunity for partial RR elimination,
1166 /// such as pushing calls into a CFG triangle or into one side of a
1170 /// ReleaseMetadata - If the Calls are objc_release calls and they all have
1171 /// a clang.imprecise_release tag, this is the metadata tag.
1172 MDNode *ReleaseMetadata;
1174 /// Calls - For a top-down sequence, the set of objc_retains or
1175 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
1176 SmallPtrSet<Instruction *, 2> Calls;
1178 /// ReverseInsertPts - The set of optimal insert positions for
1179 /// moving calls in the opposite sequence.
1180 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
1183 KnownSafe(false), IsRetainBlock(false), CopyOnEscape(false),
1184 IsTailCallRelease(false), Partial(false),
1185 ReleaseMetadata(0) {}
1191 void RRInfo::clear() {
1193 IsRetainBlock = false;
1194 CopyOnEscape = false;
1195 IsTailCallRelease = false;
1197 ReleaseMetadata = 0;
1199 ReverseInsertPts.clear();
1203 /// PtrState - This class summarizes several per-pointer runtime properties
1204 /// which are propogated through the flow graph.
1206 /// RefCount - The known minimum number of reference count increments.
1209 /// NestCount - The known minimum level of retain+release nesting.
1212 /// Seq - The current position in the sequence.
1216 /// RRI - Unidirectional information about the current sequence.
1217 /// TODO: Encapsulate this better.
1220 PtrState() : RefCount(0), NestCount(0), Seq(S_None) {}
1222 void SetAtLeastOneRefCount() {
1223 if (RefCount == 0) RefCount = 1;
1226 void IncrementRefCount() {
1227 if (RefCount != UINT_MAX) ++RefCount;
1230 void DecrementRefCount() {
1231 if (RefCount != 0) --RefCount;
1234 bool IsKnownIncremented() const {
1235 return RefCount > 0;
1238 void IncrementNestCount() {
1239 if (NestCount != UINT_MAX) ++NestCount;
1242 void DecrementNestCount() {
1243 if (NestCount != 0) --NestCount;
1246 bool IsKnownNested() const {
1247 return NestCount > 0;
1250 void SetSeq(Sequence NewSeq) {
1254 Sequence GetSeq() const {
1258 void ClearSequenceProgress() {
1263 void Merge(const PtrState &Other, bool TopDown);
1268 PtrState::Merge(const PtrState &Other, bool TopDown) {
1269 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
1270 RefCount = std::min(RefCount, Other.RefCount);
1271 NestCount = std::min(NestCount, Other.NestCount);
1273 // We can't merge a plain objc_retain with an objc_retainBlock.
1274 if (RRI.IsRetainBlock != Other.RRI.IsRetainBlock)
1277 // If we're not in a sequence (anymore), drop all associated state.
1278 if (Seq == S_None) {
1280 } else if (RRI.Partial || Other.RRI.Partial) {
1281 // If we're doing a merge on a path that's previously seen a partial
1282 // merge, conservatively drop the sequence, to avoid doing partial
1283 // RR elimination. If the branch predicates for the two merge differ,
1284 // mixing them is unsafe.
1288 // Conservatively merge the ReleaseMetadata information.
1289 if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
1290 RRI.ReleaseMetadata = 0;
1292 RRI.CopyOnEscape = RRI.CopyOnEscape && Other.RRI.CopyOnEscape;
1293 RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
1294 RRI.IsTailCallRelease = RRI.IsTailCallRelease && Other.RRI.IsTailCallRelease;
1295 RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
1297 // Merge the insert point sets. If there are any differences,
1298 // that makes this a partial merge.
1299 RRI.Partial = RRI.ReverseInsertPts.size() !=
1300 Other.RRI.ReverseInsertPts.size();
1301 for (SmallPtrSet<Instruction *, 2>::const_iterator
1302 I = Other.RRI.ReverseInsertPts.begin(),
1303 E = Other.RRI.ReverseInsertPts.end(); I != E; ++I)
1304 RRI.Partial |= RRI.ReverseInsertPts.insert(*I);
1309 /// BBState - Per-BasicBlock state.
1311 /// TopDownPathCount - The number of unique control paths from the entry
1312 /// which can reach this block.
1313 unsigned TopDownPathCount;
1315 /// BottomUpPathCount - The number of unique control paths to exits
1316 /// from this block.
1317 unsigned BottomUpPathCount;
1319 /// MapTy - A type for PerPtrTopDown and PerPtrBottomUp.
1320 typedef MapVector<const Value *, PtrState> MapTy;
1322 /// PerPtrTopDown - The top-down traversal uses this to record information
1323 /// known about a pointer at the bottom of each block.
1324 MapTy PerPtrTopDown;
1326 /// PerPtrBottomUp - The bottom-up traversal uses this to record information
1327 /// known about a pointer at the top of each block.
1328 MapTy PerPtrBottomUp;
1331 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
1333 typedef MapTy::iterator ptr_iterator;
1334 typedef MapTy::const_iterator ptr_const_iterator;
1336 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
1337 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
1338 ptr_const_iterator top_down_ptr_begin() const {
1339 return PerPtrTopDown.begin();
1341 ptr_const_iterator top_down_ptr_end() const {
1342 return PerPtrTopDown.end();
1345 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
1346 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
1347 ptr_const_iterator bottom_up_ptr_begin() const {
1348 return PerPtrBottomUp.begin();
1350 ptr_const_iterator bottom_up_ptr_end() const {
1351 return PerPtrBottomUp.end();
1354 /// SetAsEntry - Mark this block as being an entry block, which has one
1355 /// path from the entry by definition.
1356 void SetAsEntry() { TopDownPathCount = 1; }
1358 /// SetAsExit - Mark this block as being an exit block, which has one
1359 /// path to an exit by definition.
1360 void SetAsExit() { BottomUpPathCount = 1; }
1362 PtrState &getPtrTopDownState(const Value *Arg) {
1363 return PerPtrTopDown[Arg];
1366 PtrState &getPtrBottomUpState(const Value *Arg) {
1367 return PerPtrBottomUp[Arg];
1370 void clearBottomUpPointers() {
1371 PerPtrBottomUp.clear();
1374 void clearTopDownPointers() {
1375 PerPtrTopDown.clear();
1378 void InitFromPred(const BBState &Other);
1379 void InitFromSucc(const BBState &Other);
1380 void MergePred(const BBState &Other);
1381 void MergeSucc(const BBState &Other);
1383 /// GetAllPathCount - Return the number of possible unique paths from an
1384 /// entry to an exit which pass through this block. This is only valid
1385 /// after both the top-down and bottom-up traversals are complete.
1386 unsigned GetAllPathCount() const {
1387 return TopDownPathCount * BottomUpPathCount;
1390 /// IsVisitedTopDown - Test whether the block for this BBState has been
1391 /// visited by the top-down portion of the algorithm.
1392 bool isVisitedTopDown() const {
1393 return TopDownPathCount != 0;
1398 void BBState::InitFromPred(const BBState &Other) {
1399 PerPtrTopDown = Other.PerPtrTopDown;
1400 TopDownPathCount = Other.TopDownPathCount;
1403 void BBState::InitFromSucc(const BBState &Other) {
1404 PerPtrBottomUp = Other.PerPtrBottomUp;
1405 BottomUpPathCount = Other.BottomUpPathCount;
1408 /// MergePred - The top-down traversal uses this to merge information about
1409 /// predecessors to form the initial state for a new block.
1410 void BBState::MergePred(const BBState &Other) {
1411 // Other.TopDownPathCount can be 0, in which case it is either dead or a
1412 // loop backedge. Loop backedges are special.
1413 TopDownPathCount += Other.TopDownPathCount;
1415 // For each entry in the other set, if our set has an entry with the same key,
1416 // merge the entries. Otherwise, copy the entry and merge it with an empty
1418 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
1419 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
1420 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
1421 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1425 // For each entry in our set, if the other set doesn't have an entry with the
1426 // same key, force it to merge with an empty entry.
1427 for (ptr_iterator MI = top_down_ptr_begin(),
1428 ME = top_down_ptr_end(); MI != ME; ++MI)
1429 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
1430 MI->second.Merge(PtrState(), /*TopDown=*/true);
1433 /// MergeSucc - The bottom-up traversal uses this to merge information about
1434 /// successors to form the initial state for a new block.
1435 void BBState::MergeSucc(const BBState &Other) {
1436 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
1437 // loop backedge. Loop backedges are special.
1438 BottomUpPathCount += Other.BottomUpPathCount;
1440 // For each entry in the other set, if our set has an entry with the
1441 // same key, merge the entries. Otherwise, copy the entry and merge
1442 // it with an empty entry.
1443 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
1444 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
1445 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
1446 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1450 // For each entry in our set, if the other set doesn't have an entry
1451 // with the same key, force it to merge with an empty entry.
1452 for (ptr_iterator MI = bottom_up_ptr_begin(),
1453 ME = bottom_up_ptr_end(); MI != ME; ++MI)
1454 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
1455 MI->second.Merge(PtrState(), /*TopDown=*/false);
1459 /// ObjCARCOpt - The main ARC optimization pass.
1460 class ObjCARCOpt : public FunctionPass {
1462 ProvenanceAnalysis PA;
1464 /// Run - A flag indicating whether this optimization pass should run.
1467 /// RetainRVCallee, etc. - Declarations for ObjC runtime
1468 /// functions, for use in creating calls to them. These are initialized
1469 /// lazily to avoid cluttering up the Module with unused declarations.
1470 Constant *RetainRVCallee, *AutoreleaseRVCallee, *ReleaseCallee,
1471 *RetainCallee, *RetainBlockCallee, *AutoreleaseCallee;
1473 /// UsedInThisFunciton - Flags which determine whether each of the
1474 /// interesting runtine functions is in fact used in the current function.
1475 unsigned UsedInThisFunction;
1477 /// ImpreciseReleaseMDKind - The Metadata Kind for clang.imprecise_release
1479 unsigned ImpreciseReleaseMDKind;
1481 /// CopyOnEscape - The Metadata Kind for clang.arc.copy_on_escape
1483 unsigned CopyOnEscapeMDKind;
1485 Constant *getRetainRVCallee(Module *M);
1486 Constant *getAutoreleaseRVCallee(Module *M);
1487 Constant *getReleaseCallee(Module *M);
1488 Constant *getRetainCallee(Module *M);
1489 Constant *getRetainBlockCallee(Module *M);
1490 Constant *getAutoreleaseCallee(Module *M);
1492 void OptimizeRetainCall(Function &F, Instruction *Retain);
1493 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
1494 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV);
1495 void OptimizeIndividualCalls(Function &F);
1497 void CheckForCFGHazards(const BasicBlock *BB,
1498 DenseMap<const BasicBlock *, BBState> &BBStates,
1499 BBState &MyStates) const;
1500 bool VisitBottomUp(BasicBlock *BB,
1501 DenseMap<const BasicBlock *, BBState> &BBStates,
1502 MapVector<Value *, RRInfo> &Retains);
1503 bool VisitTopDown(BasicBlock *BB,
1504 DenseMap<const BasicBlock *, BBState> &BBStates,
1505 DenseMap<Value *, RRInfo> &Releases);
1506 bool Visit(Function &F,
1507 DenseMap<const BasicBlock *, BBState> &BBStates,
1508 MapVector<Value *, RRInfo> &Retains,
1509 DenseMap<Value *, RRInfo> &Releases);
1511 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1512 MapVector<Value *, RRInfo> &Retains,
1513 DenseMap<Value *, RRInfo> &Releases,
1514 SmallVectorImpl<Instruction *> &DeadInsts,
1517 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1518 MapVector<Value *, RRInfo> &Retains,
1519 DenseMap<Value *, RRInfo> &Releases,
1522 void OptimizeWeakCalls(Function &F);
1524 bool OptimizeSequences(Function &F);
1526 void OptimizeReturns(Function &F);
1528 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1529 virtual bool doInitialization(Module &M);
1530 virtual bool runOnFunction(Function &F);
1531 virtual void releaseMemory();
1535 ObjCARCOpt() : FunctionPass(ID) {
1536 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1541 char ObjCARCOpt::ID = 0;
1542 INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1543 "objc-arc", "ObjC ARC optimization", false, false)
1544 INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1545 INITIALIZE_PASS_END(ObjCARCOpt,
1546 "objc-arc", "ObjC ARC optimization", false, false)
1548 Pass *llvm::createObjCARCOptPass() {
1549 return new ObjCARCOpt();
1552 void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1553 AU.addRequired<ObjCARCAliasAnalysis>();
1554 AU.addRequired<AliasAnalysis>();
1555 // ARC optimization doesn't currently split critical edges.
1556 AU.setPreservesCFG();
1559 Constant *ObjCARCOpt::getRetainRVCallee(Module *M) {
1560 if (!RetainRVCallee) {
1561 LLVMContext &C = M->getContext();
1562 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1563 std::vector<Type *> Params;
1564 Params.push_back(I8X);
1566 FunctionType::get(I8X, Params, /*isVarArg=*/false);
1567 AttrListPtr Attributes;
1568 Attributes.addAttr(~0u, Attribute::NoUnwind);
1570 M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy,
1573 return RetainRVCallee;
1576 Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1577 if (!AutoreleaseRVCallee) {
1578 LLVMContext &C = M->getContext();
1579 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1580 std::vector<Type *> Params;
1581 Params.push_back(I8X);
1583 FunctionType::get(I8X, Params, /*isVarArg=*/false);
1584 AttrListPtr Attributes;
1585 Attributes.addAttr(~0u, Attribute::NoUnwind);
1586 AutoreleaseRVCallee =
1587 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
1590 return AutoreleaseRVCallee;
1593 Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1594 if (!ReleaseCallee) {
1595 LLVMContext &C = M->getContext();
1596 std::vector<Type *> Params;
1597 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1598 AttrListPtr Attributes;
1599 Attributes.addAttr(~0u, Attribute::NoUnwind);
1601 M->getOrInsertFunction(
1603 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
1606 return ReleaseCallee;
1609 Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1610 if (!RetainCallee) {
1611 LLVMContext &C = M->getContext();
1612 std::vector<Type *> Params;
1613 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1614 AttrListPtr Attributes;
1615 Attributes.addAttr(~0u, Attribute::NoUnwind);
1617 M->getOrInsertFunction(
1619 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1622 return RetainCallee;
1625 Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1626 if (!RetainBlockCallee) {
1627 LLVMContext &C = M->getContext();
1628 std::vector<Type *> Params;
1629 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1630 AttrListPtr Attributes;
1631 // objc_retainBlock is not nounwind because it calls user copy constructors
1632 // which could theoretically throw.
1634 M->getOrInsertFunction(
1636 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1639 return RetainBlockCallee;
1642 Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1643 if (!AutoreleaseCallee) {
1644 LLVMContext &C = M->getContext();
1645 std::vector<Type *> Params;
1646 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1647 AttrListPtr Attributes;
1648 Attributes.addAttr(~0u, Attribute::NoUnwind);
1650 M->getOrInsertFunction(
1652 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1655 return AutoreleaseCallee;
1658 /// CanAlterRefCount - Test whether the given instruction can result in a
1659 /// reference count modification (positive or negative) for the pointer's
1662 CanAlterRefCount(const Instruction *Inst, const Value *Ptr,
1663 ProvenanceAnalysis &PA, InstructionClass Class) {
1665 case IC_Autorelease:
1666 case IC_AutoreleaseRV:
1668 // These operations never directly modify a reference count.
1673 ImmutableCallSite CS = static_cast<const Value *>(Inst);
1674 assert(CS && "Only calls can alter reference counts!");
1676 // See if AliasAnalysis can help us with the call.
1677 AliasAnalysis::ModRefBehavior MRB = PA.getAA()->getModRefBehavior(CS);
1678 if (AliasAnalysis::onlyReadsMemory(MRB))
1680 if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
1681 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1683 const Value *Op = *I;
1684 if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1690 // Assume the worst.
1694 /// CanUse - Test whether the given instruction can "use" the given pointer's
1695 /// object in a way that requires the reference count to be positive.
1697 CanUse(const Instruction *Inst, const Value *Ptr, ProvenanceAnalysis &PA,
1698 InstructionClass Class) {
1699 // IC_Call operations (as opposed to IC_CallOrUser) never "use" objc pointers.
1700 if (Class == IC_Call)
1703 // Consider various instructions which may have pointer arguments which are
1705 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(Inst)) {
1706 // Comparing a pointer with null, or any other constant, isn't really a use,
1707 // because we don't care what the pointer points to, or about the values
1708 // of any other dynamic reference-counted pointers.
1709 if (!IsPotentialUse(ICI->getOperand(1)))
1711 } else if (ImmutableCallSite CS = static_cast<const Value *>(Inst)) {
1712 // For calls, just check the arguments (and not the callee operand).
1713 for (ImmutableCallSite::arg_iterator OI = CS.arg_begin(),
1714 OE = CS.arg_end(); OI != OE; ++OI) {
1715 const Value *Op = *OI;
1716 if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1720 } else if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1721 // Special-case stores, because we don't care about the stored value, just
1722 // the store address.
1723 const Value *Op = GetUnderlyingObjCPtr(SI->getPointerOperand());
1724 // If we can't tell what the underlying object was, assume there is a
1726 return IsPotentialUse(Op) && PA.related(Op, Ptr);
1729 // Check each operand for a match.
1730 for (User::const_op_iterator OI = Inst->op_begin(), OE = Inst->op_end();
1732 const Value *Op = *OI;
1733 if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1739 /// CanInterruptRV - Test whether the given instruction can autorelease
1740 /// any pointer or cause an autoreleasepool pop.
1742 CanInterruptRV(InstructionClass Class) {
1744 case IC_AutoreleasepoolPop:
1747 case IC_Autorelease:
1748 case IC_AutoreleaseRV:
1749 case IC_FusedRetainAutorelease:
1750 case IC_FusedRetainAutoreleaseRV:
1758 /// DependenceKind - There are several kinds of dependence-like concepts in
1760 enum DependenceKind {
1761 NeedsPositiveRetainCount,
1762 CanChangeRetainCount,
1763 RetainAutoreleaseDep, ///< Blocks objc_retainAutorelease.
1764 RetainAutoreleaseRVDep, ///< Blocks objc_retainAutoreleaseReturnValue.
1765 RetainRVDep ///< Blocks objc_retainAutoreleasedReturnValue.
1769 /// Depends - Test if there can be dependencies on Inst through Arg. This
1770 /// function only tests dependencies relevant for removing pairs of calls.
1772 Depends(DependenceKind Flavor, Instruction *Inst, const Value *Arg,
1773 ProvenanceAnalysis &PA) {
1774 // If we've reached the definition of Arg, stop.
1779 case NeedsPositiveRetainCount: {
1780 InstructionClass Class = GetInstructionClass(Inst);
1782 case IC_AutoreleasepoolPop:
1783 case IC_AutoreleasepoolPush:
1787 return CanUse(Inst, Arg, PA, Class);
1791 case CanChangeRetainCount: {
1792 InstructionClass Class = GetInstructionClass(Inst);
1794 case IC_AutoreleasepoolPop:
1795 // Conservatively assume this can decrement any count.
1797 case IC_AutoreleasepoolPush:
1801 return CanAlterRefCount(Inst, Arg, PA, Class);
1805 case RetainAutoreleaseDep:
1806 switch (GetBasicInstructionClass(Inst)) {
1807 case IC_AutoreleasepoolPop:
1808 // Don't merge an objc_autorelease with an objc_retain inside a different
1809 // autoreleasepool scope.
1813 // Check for a retain of the same pointer for merging.
1814 return GetObjCArg(Inst) == Arg;
1816 // Nothing else matters for objc_retainAutorelease formation.
1821 case RetainAutoreleaseRVDep: {
1822 InstructionClass Class = GetBasicInstructionClass(Inst);
1826 // Check for a retain of the same pointer for merging.
1827 return GetObjCArg(Inst) == Arg;
1829 // Anything that can autorelease interrupts
1830 // retainAutoreleaseReturnValue formation.
1831 return CanInterruptRV(Class);
1837 return CanInterruptRV(GetBasicInstructionClass(Inst));
1840 llvm_unreachable("Invalid dependence flavor");
1844 /// FindDependencies - Walk up the CFG from StartPos (which is in StartBB) and
1845 /// find local and non-local dependencies on Arg.
1846 /// TODO: Cache results?
1848 FindDependencies(DependenceKind Flavor,
1850 BasicBlock *StartBB, Instruction *StartInst,
1851 SmallPtrSet<Instruction *, 4> &DependingInstructions,
1852 SmallPtrSet<const BasicBlock *, 4> &Visited,
1853 ProvenanceAnalysis &PA) {
1854 BasicBlock::iterator StartPos = StartInst;
1856 SmallVector<std::pair<BasicBlock *, BasicBlock::iterator>, 4> Worklist;
1857 Worklist.push_back(std::make_pair(StartBB, StartPos));
1859 std::pair<BasicBlock *, BasicBlock::iterator> Pair =
1860 Worklist.pop_back_val();
1861 BasicBlock *LocalStartBB = Pair.first;
1862 BasicBlock::iterator LocalStartPos = Pair.second;
1863 BasicBlock::iterator StartBBBegin = LocalStartBB->begin();
1865 if (LocalStartPos == StartBBBegin) {
1866 pred_iterator PI(LocalStartBB), PE(LocalStartBB, false);
1868 // If we've reached the function entry, produce a null dependence.
1869 DependingInstructions.insert(0);
1871 // Add the predecessors to the worklist.
1873 BasicBlock *PredBB = *PI;
1874 if (Visited.insert(PredBB))
1875 Worklist.push_back(std::make_pair(PredBB, PredBB->end()));
1876 } while (++PI != PE);
1880 Instruction *Inst = --LocalStartPos;
1881 if (Depends(Flavor, Inst, Arg, PA)) {
1882 DependingInstructions.insert(Inst);
1886 } while (!Worklist.empty());
1888 // Determine whether the original StartBB post-dominates all of the blocks we
1889 // visited. If not, insert a sentinal indicating that most optimizations are
1891 for (SmallPtrSet<const BasicBlock *, 4>::const_iterator I = Visited.begin(),
1892 E = Visited.end(); I != E; ++I) {
1893 const BasicBlock *BB = *I;
1896 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
1897 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
1898 const BasicBlock *Succ = *SI;
1899 if (Succ != StartBB && !Visited.count(Succ)) {
1900 DependingInstructions.insert(reinterpret_cast<Instruction *>(-1));
1907 static bool isNullOrUndef(const Value *V) {
1908 return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
1911 static bool isNoopInstruction(const Instruction *I) {
1912 return isa<BitCastInst>(I) ||
1913 (isa<GetElementPtrInst>(I) &&
1914 cast<GetElementPtrInst>(I)->hasAllZeroIndices());
1917 /// OptimizeRetainCall - Turn objc_retain into
1918 /// objc_retainAutoreleasedReturnValue if the operand is a return value.
1920 ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) {
1921 CallSite CS(GetObjCArg(Retain));
1922 Instruction *Call = CS.getInstruction();
1924 if (Call->getParent() != Retain->getParent()) return;
1926 // Check that the call is next to the retain.
1927 BasicBlock::iterator I = Call;
1929 while (isNoopInstruction(I)) ++I;
1933 // Turn it to an objc_retainAutoreleasedReturnValue..
1936 cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent()));
1939 /// OptimizeRetainRVCall - Turn objc_retainAutoreleasedReturnValue into
1940 /// objc_retain if the operand is not a return value. Or, if it can be
1941 /// paired with an objc_autoreleaseReturnValue, delete the pair and
1944 ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
1945 // Check for the argument being from an immediately preceding call.
1946 Value *Arg = GetObjCArg(RetainRV);
1948 if (Instruction *Call = CS.getInstruction())
1949 if (Call->getParent() == RetainRV->getParent()) {
1950 BasicBlock::iterator I = Call;
1952 while (isNoopInstruction(I)) ++I;
1953 if (&*I == RetainRV)
1957 // Check for being preceded by an objc_autoreleaseReturnValue on the same
1958 // pointer. In this case, we can delete the pair.
1959 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
1961 do --I; while (I != Begin && isNoopInstruction(I));
1962 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
1963 GetObjCArg(I) == Arg) {
1966 EraseInstruction(I);
1967 EraseInstruction(RetainRV);
1972 // Turn it to a plain objc_retain.
1975 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
1979 /// OptimizeAutoreleaseRVCall - Turn objc_autoreleaseReturnValue into
1980 /// objc_autorelease if the result is not used as a return value.
1982 ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV) {
1983 // Check for a return of the pointer value.
1984 const Value *Ptr = GetObjCArg(AutoreleaseRV);
1985 SmallVector<const Value *, 2> Users;
1986 Users.push_back(Ptr);
1988 Ptr = Users.pop_back_val();
1989 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
1991 const User *I = *UI;
1992 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
1994 if (isa<BitCastInst>(I))
1997 } while (!Users.empty());
2001 cast<CallInst>(AutoreleaseRV)->
2002 setCalledFunction(getAutoreleaseCallee(F.getParent()));
2005 /// OptimizeIndividualCalls - Visit each call, one at a time, and make
2006 /// simplifications without doing any additional analysis.
2007 void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
2008 // Reset all the flags in preparation for recomputing them.
2009 UsedInThisFunction = 0;
2011 // Visit all objc_* calls in F.
2012 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2013 Instruction *Inst = &*I++;
2014 InstructionClass Class = GetBasicInstructionClass(Inst);
2019 // Delete no-op casts. These function calls have special semantics, but
2020 // the semantics are entirely implemented via lowering in the front-end,
2021 // so by the time they reach the optimizer, they are just no-op calls
2022 // which return their argument.
2024 // There are gray areas here, as the ability to cast reference-counted
2025 // pointers to raw void* and back allows code to break ARC assumptions,
2026 // however these are currently considered to be unimportant.
2030 EraseInstruction(Inst);
2033 // If the pointer-to-weak-pointer is null, it's undefined behavior.
2036 case IC_LoadWeakRetained:
2038 case IC_DestroyWeak: {
2039 CallInst *CI = cast<CallInst>(Inst);
2040 if (isNullOrUndef(CI->getArgOperand(0))) {
2041 Type *Ty = CI->getArgOperand(0)->getType();
2042 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2043 Constant::getNullValue(Ty),
2045 CI->replaceAllUsesWith(UndefValue::get(CI->getType()));
2046 CI->eraseFromParent();
2053 CallInst *CI = cast<CallInst>(Inst);
2054 if (isNullOrUndef(CI->getArgOperand(0)) ||
2055 isNullOrUndef(CI->getArgOperand(1))) {
2056 Type *Ty = CI->getArgOperand(0)->getType();
2057 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2058 Constant::getNullValue(Ty),
2060 CI->replaceAllUsesWith(UndefValue::get(CI->getType()));
2061 CI->eraseFromParent();
2067 OptimizeRetainCall(F, Inst);
2070 if (OptimizeRetainRVCall(F, Inst))
2073 case IC_AutoreleaseRV:
2074 OptimizeAutoreleaseRVCall(F, Inst);
2078 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
2079 if (IsAutorelease(Class) && Inst->use_empty()) {
2080 CallInst *Call = cast<CallInst>(Inst);
2081 const Value *Arg = Call->getArgOperand(0);
2082 Arg = FindSingleUseIdentifiedObject(Arg);
2087 // Create the declaration lazily.
2088 LLVMContext &C = Inst->getContext();
2090 CallInst::Create(getReleaseCallee(F.getParent()),
2091 Call->getArgOperand(0), "", Call);
2092 NewCall->setMetadata(ImpreciseReleaseMDKind,
2093 MDNode::get(C, ArrayRef<Value *>()));
2094 EraseInstruction(Call);
2100 // For functions which can never be passed stack arguments, add
2102 if (IsAlwaysTail(Class)) {
2104 cast<CallInst>(Inst)->setTailCall();
2107 // Set nounwind as needed.
2108 if (IsNoThrow(Class)) {
2110 cast<CallInst>(Inst)->setDoesNotThrow();
2113 if (!IsNoopOnNull(Class)) {
2114 UsedInThisFunction |= 1 << Class;
2118 const Value *Arg = GetObjCArg(Inst);
2120 // ARC calls with null are no-ops. Delete them.
2121 if (isNullOrUndef(Arg)) {
2124 EraseInstruction(Inst);
2128 // Keep track of which of retain, release, autorelease, and retain_block
2129 // are actually present in this function.
2130 UsedInThisFunction |= 1 << Class;
2132 // If Arg is a PHI, and one or more incoming values to the
2133 // PHI are null, and the call is control-equivalent to the PHI, and there
2134 // are no relevant side effects between the PHI and the call, the call
2135 // could be pushed up to just those paths with non-null incoming values.
2136 // For now, don't bother splitting critical edges for this.
2137 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
2138 Worklist.push_back(std::make_pair(Inst, Arg));
2140 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
2144 const PHINode *PN = dyn_cast<PHINode>(Arg);
2147 // Determine if the PHI has any null operands, or any incoming
2149 bool HasNull = false;
2150 bool HasCriticalEdges = false;
2151 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2153 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2154 if (isNullOrUndef(Incoming))
2156 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
2157 .getNumSuccessors() != 1) {
2158 HasCriticalEdges = true;
2162 // If we have null operands and no critical edges, optimize.
2163 if (!HasCriticalEdges && HasNull) {
2164 SmallPtrSet<Instruction *, 4> DependingInstructions;
2165 SmallPtrSet<const BasicBlock *, 4> Visited;
2167 // Check that there is nothing that cares about the reference
2168 // count between the call and the phi.
2169 FindDependencies(NeedsPositiveRetainCount, Arg,
2170 Inst->getParent(), Inst,
2171 DependingInstructions, Visited, PA);
2172 if (DependingInstructions.size() == 1 &&
2173 *DependingInstructions.begin() == PN) {
2176 // Clone the call into each predecessor that has a non-null value.
2177 CallInst *CInst = cast<CallInst>(Inst);
2178 Type *ParamTy = CInst->getArgOperand(0)->getType();
2179 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2181 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2182 if (!isNullOrUndef(Incoming)) {
2183 CallInst *Clone = cast<CallInst>(CInst->clone());
2184 Value *Op = PN->getIncomingValue(i);
2185 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
2186 if (Op->getType() != ParamTy)
2187 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
2188 Clone->setArgOperand(0, Op);
2189 Clone->insertBefore(InsertPos);
2190 Worklist.push_back(std::make_pair(Clone, Incoming));
2193 // Erase the original call.
2194 EraseInstruction(CInst);
2198 } while (!Worklist.empty());
2202 /// CheckForCFGHazards - Check for critical edges, loop boundaries, irreducible
2203 /// control flow, or other CFG structures where moving code across the edge
2204 /// would result in it being executed more.
2206 ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
2207 DenseMap<const BasicBlock *, BBState> &BBStates,
2208 BBState &MyStates) const {
2209 // If any top-down local-use or possible-dec has a succ which is earlier in
2210 // the sequence, forget it.
2211 for (BBState::ptr_const_iterator I = MyStates.top_down_ptr_begin(),
2212 E = MyStates.top_down_ptr_end(); I != E; ++I)
2213 switch (I->second.GetSeq()) {
2216 const Value *Arg = I->first;
2217 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2218 bool SomeSuccHasSame = false;
2219 bool AllSuccsHaveSame = true;
2220 PtrState &S = MyStates.getPtrTopDownState(Arg);
2221 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2222 PtrState &SuccS = BBStates[*SI].getPtrBottomUpState(Arg);
2223 switch (SuccS.GetSeq()) {
2225 case S_CanRelease: {
2226 if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
2227 S.ClearSequenceProgress();
2231 SomeSuccHasSame = true;
2235 case S_MovableRelease:
2236 if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
2237 AllSuccsHaveSame = false;
2240 llvm_unreachable("bottom-up pointer in retain state!");
2243 // If the state at the other end of any of the successor edges
2244 // matches the current state, require all edges to match. This
2245 // guards against loops in the middle of a sequence.
2246 if (SomeSuccHasSame && !AllSuccsHaveSame)
2247 S.ClearSequenceProgress();
2250 case S_CanRelease: {
2251 const Value *Arg = I->first;
2252 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2253 bool SomeSuccHasSame = false;
2254 bool AllSuccsHaveSame = true;
2255 PtrState &S = MyStates.getPtrTopDownState(Arg);
2256 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2257 PtrState &SuccS = BBStates[*SI].getPtrBottomUpState(Arg);
2258 switch (SuccS.GetSeq()) {
2260 if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
2261 S.ClearSequenceProgress();
2265 SomeSuccHasSame = true;
2269 case S_MovableRelease:
2271 if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
2272 AllSuccsHaveSame = false;
2275 llvm_unreachable("bottom-up pointer in retain state!");
2278 // If the state at the other end of any of the successor edges
2279 // matches the current state, require all edges to match. This
2280 // guards against loops in the middle of a sequence.
2281 if (SomeSuccHasSame && !AllSuccsHaveSame)
2282 S.ClearSequenceProgress();
2289 ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2290 DenseMap<const BasicBlock *, BBState> &BBStates,
2291 MapVector<Value *, RRInfo> &Retains) {
2292 bool NestingDetected = false;
2293 BBState &MyStates = BBStates[BB];
2295 // Merge the states from each successor to compute the initial state
2296 // for the current block.
2297 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2298 succ_const_iterator SI(TI), SE(TI, false);
2300 MyStates.SetAsExit();
2303 const BasicBlock *Succ = *SI++;
2306 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
2307 // If we haven't seen this node yet, then we've found a CFG cycle.
2308 // Be optimistic here; it's CheckForCFGHazards' job detect trouble.
2309 if (I == BBStates.end())
2311 MyStates.InitFromSucc(I->second);
2315 I = BBStates.find(Succ);
2316 if (I != BBStates.end())
2317 MyStates.MergeSucc(I->second);
2323 // Visit all the instructions, bottom-up.
2324 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2325 Instruction *Inst = llvm::prior(I);
2326 InstructionClass Class = GetInstructionClass(Inst);
2327 const Value *Arg = 0;
2331 Arg = GetObjCArg(Inst);
2333 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2335 // If we see two releases in a row on the same pointer. If so, make
2336 // a note, and we'll cicle back to revisit it after we've
2337 // hopefully eliminated the second release, which may allow us to
2338 // eliminate the first release too.
2339 // Theoretically we could implement removal of nested retain+release
2340 // pairs by making PtrState hold a stack of states, but this is
2341 // simple and avoids adding overhead for the non-nested case.
2342 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease)
2343 NestingDetected = true;
2347 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2348 S.SetSeq(ReleaseMetadata ? S_MovableRelease : S_Release);
2349 S.RRI.ReleaseMetadata = ReleaseMetadata;
2350 S.RRI.KnownSafe = S.IsKnownNested() || S.IsKnownIncremented();
2351 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2352 S.RRI.Calls.insert(Inst);
2354 S.IncrementRefCount();
2355 S.IncrementNestCount();
2358 case IC_RetainBlock:
2361 Arg = GetObjCArg(Inst);
2363 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2364 S.DecrementRefCount();
2365 S.SetAtLeastOneRefCount();
2366 S.DecrementNestCount();
2368 // An non-copy-on-escape objc_retainBlock call with just a use still
2369 // needs to be kept, because it may be copying a block from the stack
2371 if (Class == IC_RetainBlock &&
2372 !Inst->getMetadata(CopyOnEscapeMDKind) &&
2373 S.GetSeq() == S_Use)
2374 S.SetSeq(S_CanRelease);
2376 switch (S.GetSeq()) {
2379 case S_MovableRelease:
2381 S.RRI.ReverseInsertPts.clear();
2384 // Don't do retain+release tracking for IC_RetainRV, because it's
2385 // better to let it remain as the first instruction after a call.
2386 if (Class != IC_RetainRV) {
2387 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2388 if (S.RRI.IsRetainBlock)
2389 S.RRI.CopyOnEscape = !!Inst->getMetadata(CopyOnEscapeMDKind);
2390 Retains[Inst] = S.RRI;
2392 S.ClearSequenceProgress();
2397 llvm_unreachable("bottom-up pointer in retain state!");
2401 case IC_AutoreleasepoolPop:
2402 // Conservatively, clear MyStates for all known pointers.
2403 MyStates.clearBottomUpPointers();
2405 case IC_AutoreleasepoolPush:
2407 // These are irrelevant.
2413 // Consider any other possible effects of this instruction on each
2414 // pointer being tracked.
2415 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
2416 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
2417 const Value *Ptr = MI->first;
2419 continue; // Handled above.
2420 PtrState &S = MI->second;
2421 Sequence Seq = S.GetSeq();
2423 // Check for possible releases.
2424 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2425 S.DecrementRefCount();
2428 S.SetSeq(S_CanRelease);
2432 case S_MovableRelease:
2437 llvm_unreachable("bottom-up pointer in retain state!");
2441 // Check for possible direct uses.
2444 case S_MovableRelease:
2445 if (CanUse(Inst, Ptr, PA, Class)) {
2446 assert(S.RRI.ReverseInsertPts.empty());
2447 S.RRI.ReverseInsertPts.insert(Inst);
2449 } else if (Seq == S_Release &&
2450 (Class == IC_User || Class == IC_CallOrUser)) {
2451 // Non-movable releases depend on any possible objc pointer use.
2453 assert(S.RRI.ReverseInsertPts.empty());
2454 S.RRI.ReverseInsertPts.insert(Inst);
2458 if (CanUse(Inst, Ptr, PA, Class))
2466 llvm_unreachable("bottom-up pointer in retain state!");
2471 return NestingDetected;
2475 ObjCARCOpt::VisitTopDown(BasicBlock *BB,
2476 DenseMap<const BasicBlock *, BBState> &BBStates,
2477 DenseMap<Value *, RRInfo> &Releases) {
2478 bool NestingDetected = false;
2479 BBState &MyStates = BBStates[BB];
2481 // Merge the states from each predecessor to compute the initial state
2482 // for the current block.
2483 const_pred_iterator PI(BB), PE(BB, false);
2485 MyStates.SetAsEntry();
2488 const BasicBlock *Pred = *PI++;
2491 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
2492 assert(I != BBStates.end());
2493 // If we haven't seen this node yet, then we've found a CFG cycle.
2494 // Be optimistic here; it's CheckForCFGHazards' job detect trouble.
2495 if (!I->second.isVisitedTopDown())
2497 MyStates.InitFromPred(I->second);
2501 I = BBStates.find(Pred);
2502 assert(I != BBStates.end());
2503 if (I->second.isVisitedTopDown())
2504 MyStates.MergePred(I->second);
2510 // Visit all the instructions, top-down.
2511 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2512 Instruction *Inst = I;
2513 InstructionClass Class = GetInstructionClass(Inst);
2514 const Value *Arg = 0;
2517 case IC_RetainBlock:
2520 Arg = GetObjCArg(Inst);
2522 PtrState &S = MyStates.getPtrTopDownState(Arg);
2524 // Don't do retain+release tracking for IC_RetainRV, because it's
2525 // better to let it remain as the first instruction after a call.
2526 if (Class != IC_RetainRV) {
2527 // If we see two retains in a row on the same pointer. If so, make
2528 // a note, and we'll cicle back to revisit it after we've
2529 // hopefully eliminated the second retain, which may allow us to
2530 // eliminate the first retain too.
2531 // Theoretically we could implement removal of nested retain+release
2532 // pairs by making PtrState hold a stack of states, but this is
2533 // simple and avoids adding overhead for the non-nested case.
2534 if (S.GetSeq() == S_Retain)
2535 NestingDetected = true;
2539 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2540 if (S.RRI.IsRetainBlock)
2541 S.RRI.CopyOnEscape = !!Inst->getMetadata(CopyOnEscapeMDKind);
2542 // Don't check S.IsKnownIncremented() here because it's not
2544 S.RRI.KnownSafe = S.IsKnownNested();
2545 S.RRI.Calls.insert(Inst);
2548 S.SetAtLeastOneRefCount();
2549 S.IncrementRefCount();
2550 S.IncrementNestCount();
2554 Arg = GetObjCArg(Inst);
2556 PtrState &S = MyStates.getPtrTopDownState(Arg);
2557 S.DecrementRefCount();
2558 S.DecrementNestCount();
2560 switch (S.GetSeq()) {
2563 S.RRI.ReverseInsertPts.clear();
2566 S.RRI.ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2567 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2568 Releases[Inst] = S.RRI;
2569 S.ClearSequenceProgress();
2575 case S_MovableRelease:
2576 llvm_unreachable("top-down pointer in release state!");
2580 case IC_AutoreleasepoolPop:
2581 // Conservatively, clear MyStates for all known pointers.
2582 MyStates.clearTopDownPointers();
2584 case IC_AutoreleasepoolPush:
2586 // These are irrelevant.
2592 // Consider any other possible effects of this instruction on each
2593 // pointer being tracked.
2594 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
2595 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
2596 const Value *Ptr = MI->first;
2598 continue; // Handled above.
2599 PtrState &S = MI->second;
2600 Sequence Seq = S.GetSeq();
2602 // Check for possible releases.
2603 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2604 S.DecrementRefCount();
2607 S.SetSeq(S_CanRelease);
2608 assert(S.RRI.ReverseInsertPts.empty());
2609 S.RRI.ReverseInsertPts.insert(Inst);
2611 // One call can't cause a transition from S_Retain to S_CanRelease
2612 // and S_CanRelease to S_Use. If we've made the first transition,
2621 case S_MovableRelease:
2622 llvm_unreachable("top-down pointer in release state!");
2626 // Check for possible direct uses.
2629 if (CanUse(Inst, Ptr, PA, Class))
2633 // A non-copy-on-scape objc_retainBlock call may be responsible for
2634 // copying the block data from the stack to the heap. Model this by
2635 // moving it straight from S_Retain to S_Use.
2636 if (S.RRI.IsRetainBlock &&
2637 !S.RRI.CopyOnEscape &&
2638 CanUse(Inst, Ptr, PA, Class)) {
2639 assert(S.RRI.ReverseInsertPts.empty());
2640 S.RRI.ReverseInsertPts.insert(Inst);
2649 case S_MovableRelease:
2650 llvm_unreachable("top-down pointer in release state!");
2655 CheckForCFGHazards(BB, BBStates, MyStates);
2656 return NestingDetected;
2659 // Visit - Visit the function both top-down and bottom-up.
2661 ObjCARCOpt::Visit(Function &F,
2662 DenseMap<const BasicBlock *, BBState> &BBStates,
2663 MapVector<Value *, RRInfo> &Retains,
2664 DenseMap<Value *, RRInfo> &Releases) {
2665 // Use reverse-postorder on the reverse CFG for bottom-up, because we
2666 // magically know that loops will be well behaved, i.e. they won't repeatedly
2667 // call retain on a single pointer without doing a release. We can't use
2668 // ReversePostOrderTraversal here because we want to walk up from each
2669 // function exit point.
2670 SmallPtrSet<BasicBlock *, 16> Visited;
2671 SmallVector<std::pair<BasicBlock *, pred_iterator>, 16> Stack;
2672 SmallVector<BasicBlock *, 16> Order;
2673 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
2675 if (BB->getTerminator()->getNumSuccessors() == 0)
2676 Stack.push_back(std::make_pair(BB, pred_begin(BB)));
2678 while (!Stack.empty()) {
2679 pred_iterator End = pred_end(Stack.back().first);
2680 while (Stack.back().second != End) {
2681 BasicBlock *BB = *Stack.back().second++;
2682 if (Visited.insert(BB))
2683 Stack.push_back(std::make_pair(BB, pred_begin(BB)));
2685 Order.push_back(Stack.pop_back_val().first);
2687 bool BottomUpNestingDetected = false;
2688 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2689 Order.rbegin(), E = Order.rend(); I != E; ++I) {
2690 BasicBlock *BB = *I;
2691 BottomUpNestingDetected |= VisitBottomUp(BB, BBStates, Retains);
2694 // Use regular reverse-postorder for top-down.
2695 bool TopDownNestingDetected = false;
2696 typedef ReversePostOrderTraversal<Function *> RPOTType;
2698 for (RPOTType::rpo_iterator I = RPOT.begin(), E = RPOT.end(); I != E; ++I) {
2699 BasicBlock *BB = *I;
2700 TopDownNestingDetected |= VisitTopDown(BB, BBStates, Releases);
2703 return TopDownNestingDetected && BottomUpNestingDetected;
2706 /// MoveCalls - Move the calls in RetainsToMove and ReleasesToMove.
2707 void ObjCARCOpt::MoveCalls(Value *Arg,
2708 RRInfo &RetainsToMove,
2709 RRInfo &ReleasesToMove,
2710 MapVector<Value *, RRInfo> &Retains,
2711 DenseMap<Value *, RRInfo> &Releases,
2712 SmallVectorImpl<Instruction *> &DeadInsts,
2714 Type *ArgTy = Arg->getType();
2715 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
2717 // Insert the new retain and release calls.
2718 for (SmallPtrSet<Instruction *, 2>::const_iterator
2719 PI = ReleasesToMove.ReverseInsertPts.begin(),
2720 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2721 Instruction *InsertPt = *PI;
2722 Value *MyArg = ArgTy == ParamTy ? Arg :
2723 new BitCastInst(Arg, ParamTy, "", InsertPt);
2725 CallInst::Create(RetainsToMove.IsRetainBlock ?
2726 getRetainBlockCallee(M) : getRetainCallee(M),
2727 MyArg, "", InsertPt);
2728 Call->setDoesNotThrow();
2729 if (RetainsToMove.CopyOnEscape)
2730 Call->setMetadata(CopyOnEscapeMDKind,
2731 MDNode::get(M->getContext(), ArrayRef<Value *>()));
2732 if (!RetainsToMove.IsRetainBlock)
2733 Call->setTailCall();
2735 for (SmallPtrSet<Instruction *, 2>::const_iterator
2736 PI = RetainsToMove.ReverseInsertPts.begin(),
2737 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2738 Instruction *LastUse = *PI;
2739 Instruction *InsertPts[] = { 0, 0, 0 };
2740 if (InvokeInst *II = dyn_cast<InvokeInst>(LastUse)) {
2741 // We can't insert code immediately after an invoke instruction, so
2742 // insert code at the beginning of both successor blocks instead.
2743 // The invoke's return value isn't available in the unwind block,
2744 // but our releases will never depend on it, because they must be
2745 // paired with retains from before the invoke.
2746 InsertPts[0] = II->getNormalDest()->getFirstInsertionPt();
2747 InsertPts[1] = II->getUnwindDest()->getFirstInsertionPt();
2749 // Insert code immediately after the last use.
2750 InsertPts[0] = llvm::next(BasicBlock::iterator(LastUse));
2753 for (Instruction **I = InsertPts; *I; ++I) {
2754 Instruction *InsertPt = *I;
2755 Value *MyArg = ArgTy == ParamTy ? Arg :
2756 new BitCastInst(Arg, ParamTy, "", InsertPt);
2757 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
2759 // Attach a clang.imprecise_release metadata tag, if appropriate.
2760 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
2761 Call->setMetadata(ImpreciseReleaseMDKind, M);
2762 Call->setDoesNotThrow();
2763 if (ReleasesToMove.IsTailCallRelease)
2764 Call->setTailCall();
2768 // Delete the original retain and release calls.
2769 for (SmallPtrSet<Instruction *, 2>::const_iterator
2770 AI = RetainsToMove.Calls.begin(),
2771 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
2772 Instruction *OrigRetain = *AI;
2773 Retains.blot(OrigRetain);
2774 DeadInsts.push_back(OrigRetain);
2776 for (SmallPtrSet<Instruction *, 2>::const_iterator
2777 AI = ReleasesToMove.Calls.begin(),
2778 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
2779 Instruction *OrigRelease = *AI;
2780 Releases.erase(OrigRelease);
2781 DeadInsts.push_back(OrigRelease);
2786 ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
2788 MapVector<Value *, RRInfo> &Retains,
2789 DenseMap<Value *, RRInfo> &Releases,
2791 bool AnyPairsCompletelyEliminated = false;
2792 RRInfo RetainsToMove;
2793 RRInfo ReleasesToMove;
2794 SmallVector<Instruction *, 4> NewRetains;
2795 SmallVector<Instruction *, 4> NewReleases;
2796 SmallVector<Instruction *, 8> DeadInsts;
2798 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
2799 E = Retains.end(); I != E; ++I) {
2800 Value *V = I->first;
2801 if (!V) continue; // blotted
2803 Instruction *Retain = cast<Instruction>(V);
2804 Value *Arg = GetObjCArg(Retain);
2806 // If the object being released is in static storage, we know it's
2807 // not being managed by ObjC reference counting, so we can delete pairs
2808 // regardless of what possible decrements or uses lie between them.
2809 bool KnownSafe = isa<Constant>(Arg);
2811 // Same for stack storage, unless this is a non-copy-on-escape
2812 // objc_retainBlock call, which is responsible for copying the block data
2813 // from the stack to the heap.
2814 if ((!I->second.IsRetainBlock || I->second.CopyOnEscape) &&
2815 isa<AllocaInst>(Arg))
2818 // A constant pointer can't be pointing to an object on the heap. It may
2819 // be reference-counted, but it won't be deleted.
2820 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
2821 if (const GlobalVariable *GV =
2822 dyn_cast<GlobalVariable>(
2823 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
2824 if (GV->isConstant())
2827 // If a pair happens in a region where it is known that the reference count
2828 // is already incremented, we can similarly ignore possible decrements.
2829 bool KnownSafeTD = true, KnownSafeBU = true;
2831 // Connect the dots between the top-down-collected RetainsToMove and
2832 // bottom-up-collected ReleasesToMove to form sets of related calls.
2833 // This is an iterative process so that we connect multiple releases
2834 // to multiple retains if needed.
2835 unsigned OldDelta = 0;
2836 unsigned NewDelta = 0;
2837 unsigned OldCount = 0;
2838 unsigned NewCount = 0;
2839 bool FirstRelease = true;
2840 bool FirstRetain = true;
2841 NewRetains.push_back(Retain);
2843 for (SmallVectorImpl<Instruction *>::const_iterator
2844 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
2845 Instruction *NewRetain = *NI;
2846 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
2847 assert(It != Retains.end());
2848 const RRInfo &NewRetainRRI = It->second;
2849 KnownSafeTD &= NewRetainRRI.KnownSafe;
2850 for (SmallPtrSet<Instruction *, 2>::const_iterator
2851 LI = NewRetainRRI.Calls.begin(),
2852 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
2853 Instruction *NewRetainRelease = *LI;
2854 DenseMap<Value *, RRInfo>::const_iterator Jt =
2855 Releases.find(NewRetainRelease);
2856 if (Jt == Releases.end())
2858 const RRInfo &NewRetainReleaseRRI = Jt->second;
2859 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
2860 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
2862 BBStates[NewRetainRelease->getParent()].GetAllPathCount();
2864 // Merge the ReleaseMetadata and IsTailCallRelease values.
2866 ReleasesToMove.ReleaseMetadata =
2867 NewRetainReleaseRRI.ReleaseMetadata;
2868 ReleasesToMove.IsTailCallRelease =
2869 NewRetainReleaseRRI.IsTailCallRelease;
2870 FirstRelease = false;
2872 if (ReleasesToMove.ReleaseMetadata !=
2873 NewRetainReleaseRRI.ReleaseMetadata)
2874 ReleasesToMove.ReleaseMetadata = 0;
2875 if (ReleasesToMove.IsTailCallRelease !=
2876 NewRetainReleaseRRI.IsTailCallRelease)
2877 ReleasesToMove.IsTailCallRelease = false;
2880 // Collect the optimal insertion points.
2882 for (SmallPtrSet<Instruction *, 2>::const_iterator
2883 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
2884 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
2886 Instruction *RIP = *RI;
2887 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
2888 NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
2890 NewReleases.push_back(NewRetainRelease);
2895 if (NewReleases.empty()) break;
2897 // Back the other way.
2898 for (SmallVectorImpl<Instruction *>::const_iterator
2899 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
2900 Instruction *NewRelease = *NI;
2901 DenseMap<Value *, RRInfo>::const_iterator It =
2902 Releases.find(NewRelease);
2903 assert(It != Releases.end());
2904 const RRInfo &NewReleaseRRI = It->second;
2905 KnownSafeBU &= NewReleaseRRI.KnownSafe;
2906 for (SmallPtrSet<Instruction *, 2>::const_iterator
2907 LI = NewReleaseRRI.Calls.begin(),
2908 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
2909 Instruction *NewReleaseRetain = *LI;
2910 MapVector<Value *, RRInfo>::const_iterator Jt =
2911 Retains.find(NewReleaseRetain);
2912 if (Jt == Retains.end())
2914 const RRInfo &NewReleaseRetainRRI = Jt->second;
2915 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
2916 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
2917 unsigned PathCount =
2918 BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
2919 OldDelta += PathCount;
2920 OldCount += PathCount;
2922 // Merge the IsRetainBlock values.
2924 RetainsToMove.IsRetainBlock = NewReleaseRetainRRI.IsRetainBlock;
2925 RetainsToMove.CopyOnEscape = NewReleaseRetainRRI.CopyOnEscape;
2926 FirstRetain = false;
2927 } else if (ReleasesToMove.IsRetainBlock !=
2928 NewReleaseRetainRRI.IsRetainBlock)
2929 // It's not possible to merge the sequences if one uses
2930 // objc_retain and the other uses objc_retainBlock.
2933 // Merge the CopyOnEscape values.
2934 RetainsToMove.CopyOnEscape &= NewReleaseRetainRRI.CopyOnEscape;
2936 // Collect the optimal insertion points.
2938 for (SmallPtrSet<Instruction *, 2>::const_iterator
2939 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
2940 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
2942 Instruction *RIP = *RI;
2943 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
2944 PathCount = BBStates[RIP->getParent()].GetAllPathCount();
2945 NewDelta += PathCount;
2946 NewCount += PathCount;
2949 NewRetains.push_back(NewReleaseRetain);
2953 NewReleases.clear();
2954 if (NewRetains.empty()) break;
2957 // If the pointer is known incremented or nested, we can safely delete the
2958 // pair regardless of what's between them.
2959 if (KnownSafeTD || KnownSafeBU) {
2960 RetainsToMove.ReverseInsertPts.clear();
2961 ReleasesToMove.ReverseInsertPts.clear();
2964 // Determine whether the new insertion points we computed preserve the
2965 // balance of retain and release calls through the program.
2966 // TODO: If the fully aggressive solution isn't valid, try to find a
2967 // less aggressive solution which is.
2972 // Determine whether the original call points are balanced in the retain and
2973 // release calls through the program. If not, conservatively don't touch
2975 // TODO: It's theoretically possible to do code motion in this case, as
2976 // long as the existing imbalances are maintained.
2980 // Ok, everything checks out and we're all set. Let's move some code!
2982 AnyPairsCompletelyEliminated = NewCount == 0;
2983 NumRRs += OldCount - NewCount;
2984 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
2985 Retains, Releases, DeadInsts, M);
2988 NewReleases.clear();
2990 RetainsToMove.clear();
2991 ReleasesToMove.clear();
2994 // Now that we're done moving everything, we can delete the newly dead
2995 // instructions, as we no longer need them as insert points.
2996 while (!DeadInsts.empty())
2997 EraseInstruction(DeadInsts.pop_back_val());
2999 return AnyPairsCompletelyEliminated;
3002 /// OptimizeWeakCalls - Weak pointer optimizations.
3003 void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
3004 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
3005 // itself because it uses AliasAnalysis and we need to do provenance
3007 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3008 Instruction *Inst = &*I++;
3009 InstructionClass Class = GetBasicInstructionClass(Inst);
3010 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
3013 // Delete objc_loadWeak calls with no users.
3014 if (Class == IC_LoadWeak && Inst->use_empty()) {
3015 Inst->eraseFromParent();
3019 // TODO: For now, just look for an earlier available version of this value
3020 // within the same block. Theoretically, we could do memdep-style non-local
3021 // analysis too, but that would want caching. A better approach would be to
3022 // use the technique that EarlyCSE uses.
3023 inst_iterator Current = llvm::prior(I);
3024 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
3025 for (BasicBlock::iterator B = CurrentBB->begin(),
3026 J = Current.getInstructionIterator();
3028 Instruction *EarlierInst = &*llvm::prior(J);
3029 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
3030 switch (EarlierClass) {
3032 case IC_LoadWeakRetained: {
3033 // If this is loading from the same pointer, replace this load's value
3035 CallInst *Call = cast<CallInst>(Inst);
3036 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3037 Value *Arg = Call->getArgOperand(0);
3038 Value *EarlierArg = EarlierCall->getArgOperand(0);
3039 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3040 case AliasAnalysis::MustAlias:
3042 // If the load has a builtin retain, insert a plain retain for it.
3043 if (Class == IC_LoadWeakRetained) {
3045 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3049 // Zap the fully redundant load.
3050 Call->replaceAllUsesWith(EarlierCall);
3051 Call->eraseFromParent();
3053 case AliasAnalysis::MayAlias:
3054 case AliasAnalysis::PartialAlias:
3056 case AliasAnalysis::NoAlias:
3063 // If this is storing to the same pointer and has the same size etc.
3064 // replace this load's value with the stored value.
3065 CallInst *Call = cast<CallInst>(Inst);
3066 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3067 Value *Arg = Call->getArgOperand(0);
3068 Value *EarlierArg = EarlierCall->getArgOperand(0);
3069 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3070 case AliasAnalysis::MustAlias:
3072 // If the load has a builtin retain, insert a plain retain for it.
3073 if (Class == IC_LoadWeakRetained) {
3075 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3079 // Zap the fully redundant load.
3080 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
3081 Call->eraseFromParent();
3083 case AliasAnalysis::MayAlias:
3084 case AliasAnalysis::PartialAlias:
3086 case AliasAnalysis::NoAlias:
3093 // TOOD: Grab the copied value.
3095 case IC_AutoreleasepoolPush:
3098 // Weak pointers are only modified through the weak entry points
3099 // (and arbitrary calls, which could call the weak entry points).
3102 // Anything else could modify the weak pointer.
3109 // Then, for each destroyWeak with an alloca operand, check to see if
3110 // the alloca and all its users can be zapped.
3111 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3112 Instruction *Inst = &*I++;
3113 InstructionClass Class = GetBasicInstructionClass(Inst);
3114 if (Class != IC_DestroyWeak)
3117 CallInst *Call = cast<CallInst>(Inst);
3118 Value *Arg = Call->getArgOperand(0);
3119 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
3120 for (Value::use_iterator UI = Alloca->use_begin(),
3121 UE = Alloca->use_end(); UI != UE; ++UI) {
3122 Instruction *UserInst = cast<Instruction>(*UI);
3123 switch (GetBasicInstructionClass(UserInst)) {
3126 case IC_DestroyWeak:
3133 for (Value::use_iterator UI = Alloca->use_begin(),
3134 UE = Alloca->use_end(); UI != UE; ) {
3135 CallInst *UserInst = cast<CallInst>(*UI++);
3136 if (!UserInst->use_empty())
3137 UserInst->replaceAllUsesWith(UserInst->getOperand(1));
3138 UserInst->eraseFromParent();
3140 Alloca->eraseFromParent();
3146 /// OptimizeSequences - Identify program paths which execute sequences of
3147 /// retains and releases which can be eliminated.
3148 bool ObjCARCOpt::OptimizeSequences(Function &F) {
3149 /// Releases, Retains - These are used to store the results of the main flow
3150 /// analysis. These use Value* as the key instead of Instruction* so that the
3151 /// map stays valid when we get around to rewriting code and calls get
3152 /// replaced by arguments.
3153 DenseMap<Value *, RRInfo> Releases;
3154 MapVector<Value *, RRInfo> Retains;
3156 /// BBStates, This is used during the traversal of the function to track the
3157 /// states for each identified object at each block.
3158 DenseMap<const BasicBlock *, BBState> BBStates;
3160 // Analyze the CFG of the function, and all instructions.
3161 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
3164 return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) &&
3168 /// OptimizeReturns - Look for this pattern:
3170 /// %call = call i8* @something(...)
3171 /// %2 = call i8* @objc_retain(i8* %call)
3172 /// %3 = call i8* @objc_autorelease(i8* %2)
3175 /// And delete the retain and autorelease.
3177 /// Otherwise if it's just this:
3179 /// %3 = call i8* @objc_autorelease(i8* %2)
3182 /// convert the autorelease to autoreleaseRV.
3183 void ObjCARCOpt::OptimizeReturns(Function &F) {
3184 if (!F.getReturnType()->isPointerTy())
3187 SmallPtrSet<Instruction *, 4> DependingInstructions;
3188 SmallPtrSet<const BasicBlock *, 4> Visited;
3189 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3190 BasicBlock *BB = FI;
3191 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
3194 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
3195 FindDependencies(NeedsPositiveRetainCount, Arg,
3196 BB, Ret, DependingInstructions, Visited, PA);
3197 if (DependingInstructions.size() != 1)
3201 CallInst *Autorelease =
3202 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3205 InstructionClass AutoreleaseClass =
3206 GetBasicInstructionClass(Autorelease);
3207 if (!IsAutorelease(AutoreleaseClass))
3209 if (GetObjCArg(Autorelease) != Arg)
3212 DependingInstructions.clear();
3215 // Check that there is nothing that can affect the reference
3216 // count between the autorelease and the retain.
3217 FindDependencies(CanChangeRetainCount, Arg,
3218 BB, Autorelease, DependingInstructions, Visited, PA);
3219 if (DependingInstructions.size() != 1)
3224 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3226 // Check that we found a retain with the same argument.
3228 !IsRetain(GetBasicInstructionClass(Retain)) ||
3229 GetObjCArg(Retain) != Arg)
3232 DependingInstructions.clear();
3235 // Convert the autorelease to an autoreleaseRV, since it's
3236 // returning the value.
3237 if (AutoreleaseClass == IC_Autorelease) {
3238 Autorelease->setCalledFunction(getAutoreleaseRVCallee(F.getParent()));
3239 AutoreleaseClass = IC_AutoreleaseRV;
3242 // Check that there is nothing that can affect the reference
3243 // count between the retain and the call.
3244 // Note that Retain need not be in BB.
3245 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
3246 DependingInstructions, Visited, PA);
3247 if (DependingInstructions.size() != 1)
3252 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3254 // Check that the pointer is the return value of the call.
3255 if (!Call || Arg != Call)
3258 // Check that the call is a regular call.
3259 InstructionClass Class = GetBasicInstructionClass(Call);
3260 if (Class != IC_CallOrUser && Class != IC_Call)
3263 // If so, we can zap the retain and autorelease.
3266 EraseInstruction(Retain);
3267 EraseInstruction(Autorelease);
3273 DependingInstructions.clear();
3278 bool ObjCARCOpt::doInitialization(Module &M) {
3282 Run = ModuleHasARC(M);
3286 // Identify the imprecise release metadata kind.
3287 ImpreciseReleaseMDKind =
3288 M.getContext().getMDKindID("clang.imprecise_release");
3289 CopyOnEscapeMDKind =
3290 M.getContext().getMDKindID("clang.arc.copy_on_escape");
3292 // Intuitively, objc_retain and others are nocapture, however in practice
3293 // they are not, because they return their argument value. And objc_release
3294 // calls finalizers.
3296 // These are initialized lazily.
3298 AutoreleaseRVCallee = 0;
3301 RetainBlockCallee = 0;
3302 AutoreleaseCallee = 0;
3307 bool ObjCARCOpt::runOnFunction(Function &F) {
3311 // If nothing in the Module uses ARC, don't do anything.
3317 PA.setAA(&getAnalysis<AliasAnalysis>());
3319 // This pass performs several distinct transformations. As a compile-time aid
3320 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3321 // library functions aren't declared.
3323 // Preliminary optimizations. This also computs UsedInThisFunction.
3324 OptimizeIndividualCalls(F);
3326 // Optimizations for weak pointers.
3327 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3328 (1 << IC_LoadWeakRetained) |
3329 (1 << IC_StoreWeak) |
3330 (1 << IC_InitWeak) |
3331 (1 << IC_CopyWeak) |
3332 (1 << IC_MoveWeak) |
3333 (1 << IC_DestroyWeak)))
3334 OptimizeWeakCalls(F);
3336 // Optimizations for retain+release pairs.
3337 if (UsedInThisFunction & ((1 << IC_Retain) |
3338 (1 << IC_RetainRV) |
3339 (1 << IC_RetainBlock)))
3340 if (UsedInThisFunction & (1 << IC_Release))
3341 // Run OptimizeSequences until it either stops making changes or
3342 // no retain+release pair nesting is detected.
3343 while (OptimizeSequences(F)) {}
3345 // Optimizations if objc_autorelease is used.
3346 if (UsedInThisFunction &
3347 ((1 << IC_Autorelease) | (1 << IC_AutoreleaseRV)))
3353 void ObjCARCOpt::releaseMemory() {
3357 //===----------------------------------------------------------------------===//
3359 //===----------------------------------------------------------------------===//
3361 // TODO: ObjCARCContract could insert PHI nodes when uses aren't
3362 // dominated by single calls.
3364 #include "llvm/Operator.h"
3365 #include "llvm/InlineAsm.h"
3366 #include "llvm/Analysis/Dominators.h"
3368 STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed");
3371 /// ObjCARCContract - Late ARC optimizations. These change the IR in a way
3372 /// that makes it difficult to be analyzed by ObjCARCOpt, so it's run late.
3373 class ObjCARCContract : public FunctionPass {
3377 ProvenanceAnalysis PA;
3379 /// Run - A flag indicating whether this optimization pass should run.
3382 /// StoreStrongCallee, etc. - Declarations for ObjC runtime
3383 /// functions, for use in creating calls to them. These are initialized
3384 /// lazily to avoid cluttering up the Module with unused declarations.
3385 Constant *StoreStrongCallee,
3386 *RetainAutoreleaseCallee, *RetainAutoreleaseRVCallee;
3388 /// RetainRVMarker - The inline asm string to insert between calls and
3389 /// RetainRV calls to make the optimization work on targets which need it.
3390 const MDString *RetainRVMarker;
3392 Constant *getStoreStrongCallee(Module *M);
3393 Constant *getRetainAutoreleaseCallee(Module *M);
3394 Constant *getRetainAutoreleaseRVCallee(Module *M);
3396 bool ContractAutorelease(Function &F, Instruction *Autorelease,
3397 InstructionClass Class,
3398 SmallPtrSet<Instruction *, 4>
3399 &DependingInstructions,
3400 SmallPtrSet<const BasicBlock *, 4>
3403 void ContractRelease(Instruction *Release,
3404 inst_iterator &Iter);
3406 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
3407 virtual bool doInitialization(Module &M);
3408 virtual bool runOnFunction(Function &F);
3412 ObjCARCContract() : FunctionPass(ID) {
3413 initializeObjCARCContractPass(*PassRegistry::getPassRegistry());
3418 char ObjCARCContract::ID = 0;
3419 INITIALIZE_PASS_BEGIN(ObjCARCContract,
3420 "objc-arc-contract", "ObjC ARC contraction", false, false)
3421 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3422 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
3423 INITIALIZE_PASS_END(ObjCARCContract,
3424 "objc-arc-contract", "ObjC ARC contraction", false, false)
3426 Pass *llvm::createObjCARCContractPass() {
3427 return new ObjCARCContract();
3430 void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const {
3431 AU.addRequired<AliasAnalysis>();
3432 AU.addRequired<DominatorTree>();
3433 AU.setPreservesCFG();
3436 Constant *ObjCARCContract::getStoreStrongCallee(Module *M) {
3437 if (!StoreStrongCallee) {
3438 LLVMContext &C = M->getContext();
3439 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3440 Type *I8XX = PointerType::getUnqual(I8X);
3441 std::vector<Type *> Params;
3442 Params.push_back(I8XX);
3443 Params.push_back(I8X);
3445 AttrListPtr Attributes;
3446 Attributes.addAttr(~0u, Attribute::NoUnwind);
3447 Attributes.addAttr(1, Attribute::NoCapture);
3450 M->getOrInsertFunction(
3452 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
3455 return StoreStrongCallee;
3458 Constant *ObjCARCContract::getRetainAutoreleaseCallee(Module *M) {
3459 if (!RetainAutoreleaseCallee) {
3460 LLVMContext &C = M->getContext();
3461 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3462 std::vector<Type *> Params;
3463 Params.push_back(I8X);
3465 FunctionType::get(I8X, Params, /*isVarArg=*/false);
3466 AttrListPtr Attributes;
3467 Attributes.addAttr(~0u, Attribute::NoUnwind);
3468 RetainAutoreleaseCallee =
3469 M->getOrInsertFunction("objc_retainAutorelease", FTy, Attributes);
3471 return RetainAutoreleaseCallee;
3474 Constant *ObjCARCContract::getRetainAutoreleaseRVCallee(Module *M) {
3475 if (!RetainAutoreleaseRVCallee) {
3476 LLVMContext &C = M->getContext();
3477 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3478 std::vector<Type *> Params;
3479 Params.push_back(I8X);
3481 FunctionType::get(I8X, Params, /*isVarArg=*/false);
3482 AttrListPtr Attributes;
3483 Attributes.addAttr(~0u, Attribute::NoUnwind);
3484 RetainAutoreleaseRVCallee =
3485 M->getOrInsertFunction("objc_retainAutoreleaseReturnValue", FTy,
3488 return RetainAutoreleaseRVCallee;
3491 /// ContractAutorelease - Merge an autorelease with a retain into a fused
3494 ObjCARCContract::ContractAutorelease(Function &F, Instruction *Autorelease,
3495 InstructionClass Class,
3496 SmallPtrSet<Instruction *, 4>
3497 &DependingInstructions,
3498 SmallPtrSet<const BasicBlock *, 4>
3500 const Value *Arg = GetObjCArg(Autorelease);
3502 // Check that there are no instructions between the retain and the autorelease
3503 // (such as an autorelease_pop) which may change the count.
3504 CallInst *Retain = 0;
3505 if (Class == IC_AutoreleaseRV)
3506 FindDependencies(RetainAutoreleaseRVDep, Arg,
3507 Autorelease->getParent(), Autorelease,
3508 DependingInstructions, Visited, PA);
3510 FindDependencies(RetainAutoreleaseDep, Arg,
3511 Autorelease->getParent(), Autorelease,
3512 DependingInstructions, Visited, PA);
3515 if (DependingInstructions.size() != 1) {
3516 DependingInstructions.clear();
3520 Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3521 DependingInstructions.clear();
3524 GetBasicInstructionClass(Retain) != IC_Retain ||
3525 GetObjCArg(Retain) != Arg)
3531 if (Class == IC_AutoreleaseRV)
3532 Retain->setCalledFunction(getRetainAutoreleaseRVCallee(F.getParent()));
3534 Retain->setCalledFunction(getRetainAutoreleaseCallee(F.getParent()));
3536 EraseInstruction(Autorelease);
3540 /// ContractRelease - Attempt to merge an objc_release with a store, load, and
3541 /// objc_retain to form an objc_storeStrong. This can be a little tricky because
3542 /// the instructions don't always appear in order, and there may be unrelated
3543 /// intervening instructions.
3544 void ObjCARCContract::ContractRelease(Instruction *Release,
3545 inst_iterator &Iter) {
3546 LoadInst *Load = dyn_cast<LoadInst>(GetObjCArg(Release));
3547 if (!Load || !Load->isSimple()) return;
3549 // For now, require everything to be in one basic block.
3550 BasicBlock *BB = Release->getParent();
3551 if (Load->getParent() != BB) return;
3553 // Walk down to find the store.
3554 BasicBlock::iterator I = Load, End = BB->end();
3556 AliasAnalysis::Location Loc = AA->getLocation(Load);
3559 IsRetain(GetBasicInstructionClass(I)) ||
3560 !(AA->getModRefInfo(I, Loc) & AliasAnalysis::Mod)))
3562 StoreInst *Store = dyn_cast<StoreInst>(I);
3563 if (!Store || !Store->isSimple()) return;
3564 if (Store->getPointerOperand() != Loc.Ptr) return;
3566 Value *New = StripPointerCastsAndObjCCalls(Store->getValueOperand());
3568 // Walk up to find the retain.
3570 BasicBlock::iterator Begin = BB->begin();
3571 while (I != Begin && GetBasicInstructionClass(I) != IC_Retain)
3573 Instruction *Retain = I;
3574 if (GetBasicInstructionClass(Retain) != IC_Retain) return;
3575 if (GetObjCArg(Retain) != New) return;
3580 LLVMContext &C = Release->getContext();
3581 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3582 Type *I8XX = PointerType::getUnqual(I8X);
3584 Value *Args[] = { Load->getPointerOperand(), New };
3585 if (Args[0]->getType() != I8XX)
3586 Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
3587 if (Args[1]->getType() != I8X)
3588 Args[1] = new BitCastInst(Args[1], I8X, "", Store);
3589 CallInst *StoreStrong =
3590 CallInst::Create(getStoreStrongCallee(BB->getParent()->getParent()),
3592 StoreStrong->setDoesNotThrow();
3593 StoreStrong->setDebugLoc(Store->getDebugLoc());
3595 if (&*Iter == Store) ++Iter;
3596 Store->eraseFromParent();
3597 Release->eraseFromParent();
3598 EraseInstruction(Retain);
3599 if (Load->use_empty())
3600 Load->eraseFromParent();
3603 bool ObjCARCContract::doInitialization(Module &M) {
3604 Run = ModuleHasARC(M);
3608 // These are initialized lazily.
3609 StoreStrongCallee = 0;
3610 RetainAutoreleaseCallee = 0;
3611 RetainAutoreleaseRVCallee = 0;
3613 // Initialize RetainRVMarker.
3615 if (NamedMDNode *NMD =
3616 M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker"))
3617 if (NMD->getNumOperands() == 1) {
3618 const MDNode *N = NMD->getOperand(0);
3619 if (N->getNumOperands() == 1)
3620 if (const MDString *S = dyn_cast<MDString>(N->getOperand(0)))
3627 bool ObjCARCContract::runOnFunction(Function &F) {
3631 // If nothing in the Module uses ARC, don't do anything.
3636 AA = &getAnalysis<AliasAnalysis>();
3637 DT = &getAnalysis<DominatorTree>();
3639 PA.setAA(&getAnalysis<AliasAnalysis>());
3641 // For ObjC library calls which return their argument, replace uses of the
3642 // argument with uses of the call return value, if it dominates the use. This
3643 // reduces register pressure.
3644 SmallPtrSet<Instruction *, 4> DependingInstructions;
3645 SmallPtrSet<const BasicBlock *, 4> Visited;
3646 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3647 Instruction *Inst = &*I++;
3649 // Only these library routines return their argument. In particular,
3650 // objc_retainBlock does not necessarily return its argument.
3651 InstructionClass Class = GetBasicInstructionClass(Inst);
3654 case IC_FusedRetainAutorelease:
3655 case IC_FusedRetainAutoreleaseRV:
3657 case IC_Autorelease:
3658 case IC_AutoreleaseRV:
3659 if (ContractAutorelease(F, Inst, Class, DependingInstructions, Visited))
3663 // If we're compiling for a target which needs a special inline-asm
3664 // marker to do the retainAutoreleasedReturnValue optimization,
3666 if (!RetainRVMarker)
3668 BasicBlock::iterator BBI = Inst;
3670 while (isNoopInstruction(BBI)) --BBI;
3671 if (&*BBI == GetObjCArg(Inst)) {
3673 InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()),
3674 /*isVarArg=*/false),
3675 RetainRVMarker->getString(),
3676 /*Constraints=*/"", /*hasSideEffects=*/true);
3677 CallInst::Create(IA, "", Inst);
3682 // objc_initWeak(p, null) => *p = null
3683 CallInst *CI = cast<CallInst>(Inst);
3684 if (isNullOrUndef(CI->getArgOperand(1))) {
3686 ConstantPointerNull::get(cast<PointerType>(CI->getType()));
3688 new StoreInst(Null, CI->getArgOperand(0), CI);
3689 CI->replaceAllUsesWith(Null);
3690 CI->eraseFromParent();
3695 ContractRelease(Inst, I);
3701 // Don't use GetObjCArg because we don't want to look through bitcasts
3702 // and such; to do the replacement, the argument must have type i8*.
3703 const Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
3705 // If we're compiling bugpointed code, don't get in trouble.
3706 if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
3708 // Look through the uses of the pointer.
3709 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
3711 Use &U = UI.getUse();
3712 unsigned OperandNo = UI.getOperandNo();
3713 ++UI; // Increment UI now, because we may unlink its element.
3714 if (Instruction *UserInst = dyn_cast<Instruction>(U.getUser()))
3715 if (Inst != UserInst && DT->dominates(Inst, UserInst)) {
3717 Instruction *Replacement = Inst;
3718 Type *UseTy = U.get()->getType();
3719 if (PHINode *PHI = dyn_cast<PHINode>(UserInst)) {
3720 // For PHI nodes, insert the bitcast in the predecessor block.
3722 PHINode::getIncomingValueNumForOperand(OperandNo);
3724 PHI->getIncomingBlock(ValNo);
3725 if (Replacement->getType() != UseTy)
3726 Replacement = new BitCastInst(Replacement, UseTy, "",
3728 for (unsigned i = 0, e = PHI->getNumIncomingValues();
3730 if (PHI->getIncomingBlock(i) == BB) {
3731 // Keep the UI iterator valid.
3732 if (&PHI->getOperandUse(
3733 PHINode::getOperandNumForIncomingValue(i)) ==
3736 PHI->setIncomingValue(i, Replacement);
3739 if (Replacement->getType() != UseTy)
3740 Replacement = new BitCastInst(Replacement, UseTy, "", UserInst);
3746 // If Arg is a no-op casted pointer, strip one level of casts and
3748 if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
3749 Arg = BI->getOperand(0);
3750 else if (isa<GEPOperator>(Arg) &&
3751 cast<GEPOperator>(Arg)->hasAllZeroIndices())
3752 Arg = cast<GEPOperator>(Arg)->getPointerOperand();
3753 else if (isa<GlobalAlias>(Arg) &&
3754 !cast<GlobalAlias>(Arg)->mayBeOverridden())
3755 Arg = cast<GlobalAlias>(Arg)->getAliasee();