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 return Class == IC_Retain ||
429 Class == IC_RetainRV ||
430 Class == IC_RetainBlock ||
431 Class == IC_Release ||
432 Class == IC_Autorelease ||
433 Class == IC_AutoreleaseRV ||
434 Class == IC_AutoreleasepoolPush ||
435 Class == IC_AutoreleasepoolPop;
438 /// EraseInstruction - Erase the given instruction. ObjC calls return their
439 /// argument verbatim, so if it's such a call and the return value has users,
440 /// replace them with the argument value.
441 static void EraseInstruction(Instruction *CI) {
442 Value *OldArg = cast<CallInst>(CI)->getArgOperand(0);
444 bool Unused = CI->use_empty();
447 // Replace the return value with the argument.
448 assert(IsForwarding(GetBasicInstructionClass(CI)) &&
449 "Can't delete non-forwarding instruction with users!");
450 CI->replaceAllUsesWith(OldArg);
453 CI->eraseFromParent();
456 RecursivelyDeleteTriviallyDeadInstructions(OldArg);
459 /// GetUnderlyingObjCPtr - This is a wrapper around getUnderlyingObject which
460 /// also knows how to look through objc_retain and objc_autorelease calls, which
461 /// we know to return their argument verbatim.
462 static const Value *GetUnderlyingObjCPtr(const Value *V) {
464 V = GetUnderlyingObject(V);
465 if (!IsForwarding(GetBasicInstructionClass(V)))
467 V = cast<CallInst>(V)->getArgOperand(0);
473 /// StripPointerCastsAndObjCCalls - This is a wrapper around
474 /// Value::stripPointerCasts which also knows how to look through objc_retain
475 /// and objc_autorelease calls, which we know to return their argument verbatim.
476 static const Value *StripPointerCastsAndObjCCalls(const Value *V) {
478 V = V->stripPointerCasts();
479 if (!IsForwarding(GetBasicInstructionClass(V)))
481 V = cast<CallInst>(V)->getArgOperand(0);
486 /// StripPointerCastsAndObjCCalls - This is a wrapper around
487 /// Value::stripPointerCasts which also knows how to look through objc_retain
488 /// and objc_autorelease calls, which we know to return their argument verbatim.
489 static Value *StripPointerCastsAndObjCCalls(Value *V) {
491 V = V->stripPointerCasts();
492 if (!IsForwarding(GetBasicInstructionClass(V)))
494 V = cast<CallInst>(V)->getArgOperand(0);
499 /// GetObjCArg - Assuming the given instruction is one of the special calls such
500 /// as objc_retain or objc_release, return the argument value, stripped of no-op
501 /// casts and forwarding calls.
502 static Value *GetObjCArg(Value *Inst) {
503 return StripPointerCastsAndObjCCalls(cast<CallInst>(Inst)->getArgOperand(0));
506 /// IsObjCIdentifiedObject - This is similar to AliasAnalysis'
507 /// isObjCIdentifiedObject, except that it uses special knowledge of
508 /// ObjC conventions...
509 static bool IsObjCIdentifiedObject(const Value *V) {
510 // Assume that call results and arguments have their own "provenance".
511 // Constants (including GlobalVariables) and Allocas are never
512 // reference-counted.
513 if (isa<CallInst>(V) || isa<InvokeInst>(V) ||
514 isa<Argument>(V) || isa<Constant>(V) ||
518 if (const LoadInst *LI = dyn_cast<LoadInst>(V)) {
519 const Value *Pointer =
520 StripPointerCastsAndObjCCalls(LI->getPointerOperand());
521 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Pointer)) {
522 // A constant pointer can't be pointing to an object on the heap. It may
523 // be reference-counted, but it won't be deleted.
524 if (GV->isConstant())
526 StringRef Name = GV->getName();
527 // These special variables are known to hold values which are not
528 // reference-counted pointers.
529 if (Name.startswith("\01L_OBJC_SELECTOR_REFERENCES_") ||
530 Name.startswith("\01L_OBJC_CLASSLIST_REFERENCES_") ||
531 Name.startswith("\01L_OBJC_CLASSLIST_SUP_REFS_$_") ||
532 Name.startswith("\01L_OBJC_METH_VAR_NAME_") ||
533 Name.startswith("\01l_objc_msgSend_fixup_"))
541 /// FindSingleUseIdentifiedObject - This is similar to
542 /// StripPointerCastsAndObjCCalls but it stops as soon as it finds a value
543 /// with multiple uses.
544 static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
545 if (Arg->hasOneUse()) {
546 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
547 return FindSingleUseIdentifiedObject(BC->getOperand(0));
548 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
549 if (GEP->hasAllZeroIndices())
550 return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
551 if (IsForwarding(GetBasicInstructionClass(Arg)))
552 return FindSingleUseIdentifiedObject(
553 cast<CallInst>(Arg)->getArgOperand(0));
554 if (!IsObjCIdentifiedObject(Arg))
559 // If we found an identifiable object but it has multiple uses, but they
560 // are trivial uses, we can still consider this to be a single-use
562 if (IsObjCIdentifiedObject(Arg)) {
563 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
566 if (!U->use_empty() || StripPointerCastsAndObjCCalls(U) != Arg)
576 /// ModuleHasARC - Test if the given module looks interesting to run ARC
578 static bool ModuleHasARC(const Module &M) {
580 M.getNamedValue("objc_retain") ||
581 M.getNamedValue("objc_release") ||
582 M.getNamedValue("objc_autorelease") ||
583 M.getNamedValue("objc_retainAutoreleasedReturnValue") ||
584 M.getNamedValue("objc_retainBlock") ||
585 M.getNamedValue("objc_autoreleaseReturnValue") ||
586 M.getNamedValue("objc_autoreleasePoolPush") ||
587 M.getNamedValue("objc_loadWeakRetained") ||
588 M.getNamedValue("objc_loadWeak") ||
589 M.getNamedValue("objc_destroyWeak") ||
590 M.getNamedValue("objc_storeWeak") ||
591 M.getNamedValue("objc_initWeak") ||
592 M.getNamedValue("objc_moveWeak") ||
593 M.getNamedValue("objc_copyWeak") ||
594 M.getNamedValue("objc_retainedObject") ||
595 M.getNamedValue("objc_unretainedObject") ||
596 M.getNamedValue("objc_unretainedPointer");
599 //===----------------------------------------------------------------------===//
600 // ARC AliasAnalysis.
601 //===----------------------------------------------------------------------===//
603 #include "llvm/Pass.h"
604 #include "llvm/Analysis/AliasAnalysis.h"
605 #include "llvm/Analysis/Passes.h"
608 /// ObjCARCAliasAnalysis - This is a simple alias analysis
609 /// implementation that uses knowledge of ARC constructs to answer queries.
611 /// TODO: This class could be generalized to know about other ObjC-specific
612 /// tricks. Such as knowing that ivars in the non-fragile ABI are non-aliasing
613 /// even though their offsets are dynamic.
614 class ObjCARCAliasAnalysis : public ImmutablePass,
615 public AliasAnalysis {
617 static char ID; // Class identification, replacement for typeinfo
618 ObjCARCAliasAnalysis() : ImmutablePass(ID) {
619 initializeObjCARCAliasAnalysisPass(*PassRegistry::getPassRegistry());
623 virtual void initializePass() {
624 InitializeAliasAnalysis(this);
627 /// getAdjustedAnalysisPointer - This method is used when a pass implements
628 /// an analysis interface through multiple inheritance. If needed, it
629 /// should override this to adjust the this pointer as needed for the
630 /// specified pass info.
631 virtual void *getAdjustedAnalysisPointer(const void *PI) {
632 if (PI == &AliasAnalysis::ID)
633 return (AliasAnalysis*)this;
637 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
638 virtual AliasResult alias(const Location &LocA, const Location &LocB);
639 virtual bool pointsToConstantMemory(const Location &Loc, bool OrLocal);
640 virtual ModRefBehavior getModRefBehavior(ImmutableCallSite CS);
641 virtual ModRefBehavior getModRefBehavior(const Function *F);
642 virtual ModRefResult getModRefInfo(ImmutableCallSite CS,
643 const Location &Loc);
644 virtual ModRefResult getModRefInfo(ImmutableCallSite CS1,
645 ImmutableCallSite CS2);
647 } // End of anonymous namespace
649 // Register this pass...
650 char ObjCARCAliasAnalysis::ID = 0;
651 INITIALIZE_AG_PASS(ObjCARCAliasAnalysis, AliasAnalysis, "objc-arc-aa",
652 "ObjC-ARC-Based Alias Analysis", false, true, false)
654 ImmutablePass *llvm::createObjCARCAliasAnalysisPass() {
655 return new ObjCARCAliasAnalysis();
659 ObjCARCAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
660 AU.setPreservesAll();
661 AliasAnalysis::getAnalysisUsage(AU);
664 AliasAnalysis::AliasResult
665 ObjCARCAliasAnalysis::alias(const Location &LocA, const Location &LocB) {
667 return AliasAnalysis::alias(LocA, LocB);
669 // First, strip off no-ops, including ObjC-specific no-ops, and try making a
670 // precise alias query.
671 const Value *SA = StripPointerCastsAndObjCCalls(LocA.Ptr);
672 const Value *SB = StripPointerCastsAndObjCCalls(LocB.Ptr);
674 AliasAnalysis::alias(Location(SA, LocA.Size, LocA.TBAATag),
675 Location(SB, LocB.Size, LocB.TBAATag));
676 if (Result != MayAlias)
679 // If that failed, climb to the underlying object, including climbing through
680 // ObjC-specific no-ops, and try making an imprecise alias query.
681 const Value *UA = GetUnderlyingObjCPtr(SA);
682 const Value *UB = GetUnderlyingObjCPtr(SB);
683 if (UA != SA || UB != SB) {
684 Result = AliasAnalysis::alias(Location(UA), Location(UB));
685 // We can't use MustAlias or PartialAlias results here because
686 // GetUnderlyingObjCPtr may return an offsetted pointer value.
687 if (Result == NoAlias)
691 // If that failed, fail. We don't need to chain here, since that's covered
692 // by the earlier precise query.
697 ObjCARCAliasAnalysis::pointsToConstantMemory(const Location &Loc,
700 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
702 // First, strip off no-ops, including ObjC-specific no-ops, and try making
703 // a precise alias query.
704 const Value *S = StripPointerCastsAndObjCCalls(Loc.Ptr);
705 if (AliasAnalysis::pointsToConstantMemory(Location(S, Loc.Size, Loc.TBAATag),
709 // If that failed, climb to the underlying object, including climbing through
710 // ObjC-specific no-ops, and try making an imprecise alias query.
711 const Value *U = GetUnderlyingObjCPtr(S);
713 return AliasAnalysis::pointsToConstantMemory(Location(U), OrLocal);
715 // If that failed, fail. We don't need to chain here, since that's covered
716 // by the earlier precise query.
720 AliasAnalysis::ModRefBehavior
721 ObjCARCAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
722 // We have nothing to do. Just chain to the next AliasAnalysis.
723 return AliasAnalysis::getModRefBehavior(CS);
726 AliasAnalysis::ModRefBehavior
727 ObjCARCAliasAnalysis::getModRefBehavior(const Function *F) {
729 return AliasAnalysis::getModRefBehavior(F);
731 switch (GetFunctionClass(F)) {
733 return DoesNotAccessMemory;
738 return AliasAnalysis::getModRefBehavior(F);
741 AliasAnalysis::ModRefResult
742 ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS, const Location &Loc) {
744 return AliasAnalysis::getModRefInfo(CS, Loc);
746 switch (GetBasicInstructionClass(CS.getInstruction())) {
750 case IC_AutoreleaseRV:
752 case IC_AutoreleasepoolPush:
753 case IC_FusedRetainAutorelease:
754 case IC_FusedRetainAutoreleaseRV:
755 // These functions don't access any memory visible to the compiler.
756 // Note that this doesn't include objc_retainBlock, becuase it updates
757 // pointers when it copies block data.
763 return AliasAnalysis::getModRefInfo(CS, Loc);
766 AliasAnalysis::ModRefResult
767 ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
768 ImmutableCallSite CS2) {
769 // TODO: Theoretically we could check for dependencies between objc_* calls
770 // and OnlyAccessesArgumentPointees calls or other well-behaved calls.
771 return AliasAnalysis::getModRefInfo(CS1, CS2);
774 //===----------------------------------------------------------------------===//
776 //===----------------------------------------------------------------------===//
778 #include "llvm/Support/InstIterator.h"
779 #include "llvm/Transforms/Scalar.h"
782 /// ObjCARCExpand - Early ARC transformations.
783 class ObjCARCExpand : public FunctionPass {
784 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
785 virtual bool doInitialization(Module &M);
786 virtual bool runOnFunction(Function &F);
788 /// Run - A flag indicating whether this optimization pass should run.
793 ObjCARCExpand() : FunctionPass(ID) {
794 initializeObjCARCExpandPass(*PassRegistry::getPassRegistry());
799 char ObjCARCExpand::ID = 0;
800 INITIALIZE_PASS(ObjCARCExpand,
801 "objc-arc-expand", "ObjC ARC expansion", false, false)
803 Pass *llvm::createObjCARCExpandPass() {
804 return new ObjCARCExpand();
807 void ObjCARCExpand::getAnalysisUsage(AnalysisUsage &AU) const {
808 AU.setPreservesCFG();
811 bool ObjCARCExpand::doInitialization(Module &M) {
812 Run = ModuleHasARC(M);
816 bool ObjCARCExpand::runOnFunction(Function &F) {
820 // If nothing in the Module uses ARC, don't do anything.
824 bool Changed = false;
826 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
827 Instruction *Inst = &*I;
829 switch (GetBasicInstructionClass(Inst)) {
833 case IC_AutoreleaseRV:
834 case IC_FusedRetainAutorelease:
835 case IC_FusedRetainAutoreleaseRV:
836 // These calls return their argument verbatim, as a low-level
837 // optimization. However, this makes high-level optimizations
838 // harder. Undo any uses of this optimization that the front-end
839 // emitted here. We'll redo them in a later pass.
841 Inst->replaceAllUsesWith(cast<CallInst>(Inst)->getArgOperand(0));
851 //===----------------------------------------------------------------------===//
853 //===----------------------------------------------------------------------===//
855 // TODO: On code like this:
858 // stuff_that_cannot_release()
859 // objc_autorelease(%x)
860 // stuff_that_cannot_release()
862 // stuff_that_cannot_release()
863 // objc_autorelease(%x)
865 // The second retain and autorelease can be deleted.
867 // TODO: It should be possible to delete
868 // objc_autoreleasePoolPush and objc_autoreleasePoolPop
869 // pairs if nothing is actually autoreleased between them. Also, autorelease
870 // calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
871 // after inlining) can be turned into plain release calls.
873 // TODO: Critical-edge splitting. If the optimial insertion point is
874 // a critical edge, the current algorithm has to fail, because it doesn't
875 // know how to split edges. It should be possible to make the optimizer
876 // think in terms of edges, rather than blocks, and then split critical
879 // TODO: OptimizeSequences could generalized to be Interprocedural.
881 // TODO: Recognize that a bunch of other objc runtime calls have
882 // non-escaping arguments and non-releasing arguments, and may be
883 // non-autoreleasing.
885 // TODO: Sink autorelease calls as far as possible. Unfortunately we
886 // usually can't sink them past other calls, which would be the main
887 // case where it would be useful.
889 // TODO: The pointer returned from objc_loadWeakRetained is retained.
891 // TODO: Delete release+retain pairs (rare).
893 #include "llvm/GlobalAlias.h"
894 #include "llvm/Constants.h"
895 #include "llvm/LLVMContext.h"
896 #include "llvm/Support/ErrorHandling.h"
897 #include "llvm/Support/CFG.h"
898 #include "llvm/ADT/PostOrderIterator.h"
899 #include "llvm/ADT/Statistic.h"
901 STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
902 STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
903 STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
904 STATISTIC(NumRets, "Number of return value forwarding "
905 "retain+autoreleaes eliminated");
906 STATISTIC(NumRRs, "Number of retain+release paths eliminated");
907 STATISTIC(NumPeeps, "Number of calls peephole-optimized");
910 /// ProvenanceAnalysis - This is similar to BasicAliasAnalysis, and it
911 /// uses many of the same techniques, except it uses special ObjC-specific
912 /// reasoning about pointer relationships.
913 class ProvenanceAnalysis {
916 typedef std::pair<const Value *, const Value *> ValuePairTy;
917 typedef DenseMap<ValuePairTy, bool> CachedResultsTy;
918 CachedResultsTy CachedResults;
920 bool relatedCheck(const Value *A, const Value *B);
921 bool relatedSelect(const SelectInst *A, const Value *B);
922 bool relatedPHI(const PHINode *A, const Value *B);
925 void operator=(const ProvenanceAnalysis &);
926 ProvenanceAnalysis(const ProvenanceAnalysis &);
929 ProvenanceAnalysis() {}
931 void setAA(AliasAnalysis *aa) { AA = aa; }
933 AliasAnalysis *getAA() const { return AA; }
935 bool related(const Value *A, const Value *B);
938 CachedResults.clear();
943 bool ProvenanceAnalysis::relatedSelect(const SelectInst *A, const Value *B) {
944 // If the values are Selects with the same condition, we can do a more precise
945 // check: just check for relations between the values on corresponding arms.
946 if (const SelectInst *SB = dyn_cast<SelectInst>(B))
947 if (A->getCondition() == SB->getCondition()) {
948 if (related(A->getTrueValue(), SB->getTrueValue()))
950 if (related(A->getFalseValue(), SB->getFalseValue()))
955 // Check both arms of the Select node individually.
956 if (related(A->getTrueValue(), B))
958 if (related(A->getFalseValue(), B))
961 // The arms both checked out.
965 bool ProvenanceAnalysis::relatedPHI(const PHINode *A, const Value *B) {
966 // If the values are PHIs in the same block, we can do a more precise as well
967 // as efficient check: just check for relations between the values on
968 // corresponding edges.
969 if (const PHINode *PNB = dyn_cast<PHINode>(B))
970 if (PNB->getParent() == A->getParent()) {
971 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i)
972 if (related(A->getIncomingValue(i),
973 PNB->getIncomingValueForBlock(A->getIncomingBlock(i))))
978 // Check each unique source of the PHI node against B.
979 SmallPtrSet<const Value *, 4> UniqueSrc;
980 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i) {
981 const Value *PV1 = A->getIncomingValue(i);
982 if (UniqueSrc.insert(PV1) && related(PV1, B))
986 // All of the arms checked out.
990 /// isStoredObjCPointer - Test if the value of P, or any value covered by its
991 /// provenance, is ever stored within the function (not counting callees).
992 static bool isStoredObjCPointer(const Value *P) {
993 SmallPtrSet<const Value *, 8> Visited;
994 SmallVector<const Value *, 8> Worklist;
995 Worklist.push_back(P);
998 P = Worklist.pop_back_val();
999 for (Value::const_use_iterator UI = P->use_begin(), UE = P->use_end();
1001 const User *Ur = *UI;
1002 if (isa<StoreInst>(Ur)) {
1003 if (UI.getOperandNo() == 0)
1004 // The pointer is stored.
1006 // The pointed is stored through.
1009 if (isa<CallInst>(Ur))
1010 // The pointer is passed as an argument, ignore this.
1012 if (isa<PtrToIntInst>(P))
1013 // Assume the worst.
1015 if (Visited.insert(Ur))
1016 Worklist.push_back(Ur);
1018 } while (!Worklist.empty());
1020 // Everything checked out.
1024 bool ProvenanceAnalysis::relatedCheck(const Value *A, const Value *B) {
1025 // Skip past provenance pass-throughs.
1026 A = GetUnderlyingObjCPtr(A);
1027 B = GetUnderlyingObjCPtr(B);
1033 // Ask regular AliasAnalysis, for a first approximation.
1034 switch (AA->alias(A, B)) {
1035 case AliasAnalysis::NoAlias:
1037 case AliasAnalysis::MustAlias:
1038 case AliasAnalysis::PartialAlias:
1040 case AliasAnalysis::MayAlias:
1044 bool AIsIdentified = IsObjCIdentifiedObject(A);
1045 bool BIsIdentified = IsObjCIdentifiedObject(B);
1047 // An ObjC-Identified object can't alias a load if it is never locally stored.
1048 if (AIsIdentified) {
1049 if (BIsIdentified) {
1050 // If both pointers have provenance, they can be directly compared.
1054 if (isa<LoadInst>(B))
1055 return isStoredObjCPointer(A);
1058 if (BIsIdentified && isa<LoadInst>(A))
1059 return isStoredObjCPointer(B);
1062 // Special handling for PHI and Select.
1063 if (const PHINode *PN = dyn_cast<PHINode>(A))
1064 return relatedPHI(PN, B);
1065 if (const PHINode *PN = dyn_cast<PHINode>(B))
1066 return relatedPHI(PN, A);
1067 if (const SelectInst *S = dyn_cast<SelectInst>(A))
1068 return relatedSelect(S, B);
1069 if (const SelectInst *S = dyn_cast<SelectInst>(B))
1070 return relatedSelect(S, A);
1076 bool ProvenanceAnalysis::related(const Value *A, const Value *B) {
1077 // Begin by inserting a conservative value into the map. If the insertion
1078 // fails, we have the answer already. If it succeeds, leave it there until we
1079 // compute the real answer to guard against recursive queries.
1080 if (A > B) std::swap(A, B);
1081 std::pair<CachedResultsTy::iterator, bool> Pair =
1082 CachedResults.insert(std::make_pair(ValuePairTy(A, B), true));
1084 return Pair.first->second;
1086 bool Result = relatedCheck(A, B);
1087 CachedResults[ValuePairTy(A, B)] = Result;
1092 // Sequence - A sequence of states that a pointer may go through in which an
1093 // objc_retain and objc_release are actually needed.
1096 S_Retain, ///< objc_retain(x)
1097 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement
1098 S_Use, ///< any use of x
1099 S_Stop, ///< like S_Release, but code motion is stopped
1100 S_Release, ///< objc_release(x)
1101 S_MovableRelease ///< objc_release(x), !clang.imprecise_release
1105 static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
1109 if (A == S_None || B == S_None)
1112 if (A > B) std::swap(A, B);
1114 // Choose the side which is further along in the sequence.
1115 if ((A == S_Retain || A == S_CanRelease) &&
1116 (B == S_CanRelease || B == S_Use))
1119 // Choose the side which is further along in the sequence.
1120 if ((A == S_Use || A == S_CanRelease) &&
1121 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
1123 // If both sides are releases, choose the more conservative one.
1124 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
1126 if (A == S_Release && B == S_MovableRelease)
1134 /// RRInfo - Unidirectional information about either a
1135 /// retain-decrement-use-release sequence or release-use-decrement-retain
1136 /// reverese sequence.
1138 /// KnownSafe - After an objc_retain, the reference count of the referenced
1139 /// object is known to be positive. Similarly, before an objc_release, the
1140 /// reference count of the referenced object is known to be positive. If
1141 /// there are retain-release pairs in code regions where the retain count
1142 /// is known to be positive, they can be eliminated, regardless of any side
1143 /// effects between them.
1145 /// Also, a retain+release pair nested within another retain+release
1146 /// pair all on the known same pointer value can be eliminated, regardless
1147 /// of any intervening side effects.
1149 /// KnownSafe is true when either of these conditions is satisfied.
1152 /// IsRetainBlock - True if the Calls are objc_retainBlock calls (as
1153 /// opposed to objc_retain calls).
1156 /// IsTailCallRelease - True of the objc_release calls are all marked
1157 /// with the "tail" keyword.
1158 bool IsTailCallRelease;
1160 /// ReleaseMetadata - If the Calls are objc_release calls and they all have
1161 /// a clang.imprecise_release tag, this is the metadata tag.
1162 MDNode *ReleaseMetadata;
1164 /// Calls - For a top-down sequence, the set of objc_retains or
1165 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
1166 SmallPtrSet<Instruction *, 2> Calls;
1168 /// ReverseInsertPts - The set of optimal insert positions for
1169 /// moving calls in the opposite sequence.
1170 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
1173 KnownSafe(false), IsRetainBlock(false), IsTailCallRelease(false),
1174 ReleaseMetadata(0) {}
1180 void RRInfo::clear() {
1182 IsRetainBlock = false;
1183 IsTailCallRelease = false;
1184 ReleaseMetadata = 0;
1186 ReverseInsertPts.clear();
1190 /// PtrState - This class summarizes several per-pointer runtime properties
1191 /// which are propogated through the flow graph.
1193 /// RefCount - The known minimum number of reference count increments.
1196 /// NestCount - The known minimum level of retain+release nesting.
1199 /// Seq - The current position in the sequence.
1203 /// RRI - Unidirectional information about the current sequence.
1204 /// TODO: Encapsulate this better.
1207 PtrState() : RefCount(0), NestCount(0), Seq(S_None) {}
1209 void SetAtLeastOneRefCount() {
1210 if (RefCount == 0) RefCount = 1;
1213 void IncrementRefCount() {
1214 if (RefCount != UINT_MAX) ++RefCount;
1217 void DecrementRefCount() {
1218 if (RefCount != 0) --RefCount;
1221 bool IsKnownIncremented() const {
1222 return RefCount > 0;
1225 void IncrementNestCount() {
1226 if (NestCount != UINT_MAX) ++NestCount;
1229 void DecrementNestCount() {
1230 if (NestCount != 0) --NestCount;
1233 bool IsKnownNested() const {
1234 return NestCount > 0;
1237 void SetSeq(Sequence NewSeq) {
1241 void SetSeqToRelease(MDNode *M) {
1242 if (Seq == S_None || Seq == S_Use) {
1243 Seq = M ? S_MovableRelease : S_Release;
1244 RRI.ReleaseMetadata = M;
1245 } else if (Seq != S_MovableRelease || RRI.ReleaseMetadata != M) {
1247 RRI.ReleaseMetadata = 0;
1251 Sequence GetSeq() const {
1255 void ClearSequenceProgress() {
1260 void Merge(const PtrState &Other, bool TopDown);
1265 PtrState::Merge(const PtrState &Other, bool TopDown) {
1266 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
1267 RefCount = std::min(RefCount, Other.RefCount);
1268 NestCount = std::min(NestCount, Other.NestCount);
1270 // We can't merge a plain objc_retain with an objc_retainBlock.
1271 if (RRI.IsRetainBlock != Other.RRI.IsRetainBlock)
1274 if (Seq == S_None) {
1277 // Conservatively merge the ReleaseMetadata information.
1278 if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
1279 RRI.ReleaseMetadata = 0;
1281 RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
1282 RRI.IsTailCallRelease = RRI.IsTailCallRelease && Other.RRI.IsTailCallRelease;
1283 RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
1284 RRI.ReverseInsertPts.insert(Other.RRI.ReverseInsertPts.begin(),
1285 Other.RRI.ReverseInsertPts.end());
1290 /// BBState - Per-BasicBlock state.
1292 /// TopDownPathCount - The number of unique control paths from the entry
1293 /// which can reach this block.
1294 unsigned TopDownPathCount;
1296 /// BottomUpPathCount - The number of unique control paths to exits
1297 /// from this block.
1298 unsigned BottomUpPathCount;
1300 /// MapTy - A type for PerPtrTopDown and PerPtrBottomUp.
1301 typedef MapVector<const Value *, PtrState> MapTy;
1303 /// PerPtrTopDown - The top-down traversal uses this to record information
1304 /// known about a pointer at the bottom of each block.
1305 MapTy PerPtrTopDown;
1307 /// PerPtrBottomUp - The bottom-up traversal uses this to record information
1308 /// known about a pointer at the top of each block.
1309 MapTy PerPtrBottomUp;
1312 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
1314 typedef MapTy::iterator ptr_iterator;
1315 typedef MapTy::const_iterator ptr_const_iterator;
1317 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
1318 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
1319 ptr_const_iterator top_down_ptr_begin() const {
1320 return PerPtrTopDown.begin();
1322 ptr_const_iterator top_down_ptr_end() const {
1323 return PerPtrTopDown.end();
1326 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
1327 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
1328 ptr_const_iterator bottom_up_ptr_begin() const {
1329 return PerPtrBottomUp.begin();
1331 ptr_const_iterator bottom_up_ptr_end() const {
1332 return PerPtrBottomUp.end();
1335 /// SetAsEntry - Mark this block as being an entry block, which has one
1336 /// path from the entry by definition.
1337 void SetAsEntry() { TopDownPathCount = 1; }
1339 /// SetAsExit - Mark this block as being an exit block, which has one
1340 /// path to an exit by definition.
1341 void SetAsExit() { BottomUpPathCount = 1; }
1343 PtrState &getPtrTopDownState(const Value *Arg) {
1344 return PerPtrTopDown[Arg];
1347 PtrState &getPtrBottomUpState(const Value *Arg) {
1348 return PerPtrBottomUp[Arg];
1351 void clearBottomUpPointers() {
1352 PerPtrBottomUp.clear();
1355 void clearTopDownPointers() {
1356 PerPtrTopDown.clear();
1359 void InitFromPred(const BBState &Other);
1360 void InitFromSucc(const BBState &Other);
1361 void MergePred(const BBState &Other);
1362 void MergeSucc(const BBState &Other);
1364 /// GetAllPathCount - Return the number of possible unique paths from an
1365 /// entry to an exit which pass through this block. This is only valid
1366 /// after both the top-down and bottom-up traversals are complete.
1367 unsigned GetAllPathCount() const {
1368 return TopDownPathCount * BottomUpPathCount;
1371 /// IsVisitedTopDown - Test whether the block for this BBState has been
1372 /// visited by the top-down portion of the algorithm.
1373 bool isVisitedTopDown() const {
1374 return TopDownPathCount != 0;
1379 void BBState::InitFromPred(const BBState &Other) {
1380 PerPtrTopDown = Other.PerPtrTopDown;
1381 TopDownPathCount = Other.TopDownPathCount;
1384 void BBState::InitFromSucc(const BBState &Other) {
1385 PerPtrBottomUp = Other.PerPtrBottomUp;
1386 BottomUpPathCount = Other.BottomUpPathCount;
1389 /// MergePred - The top-down traversal uses this to merge information about
1390 /// predecessors to form the initial state for a new block.
1391 void BBState::MergePred(const BBState &Other) {
1392 // Other.TopDownPathCount can be 0, in which case it is either dead or a
1393 // loop backedge. Loop backedges are special.
1394 TopDownPathCount += Other.TopDownPathCount;
1396 // For each entry in the other set, if our set has an entry with the same key,
1397 // merge the entries. Otherwise, copy the entry and merge it with an empty
1399 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
1400 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
1401 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
1402 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1406 // For each entry in our set, if the other set doesn't have an entry with the
1407 // same key, force it to merge with an empty entry.
1408 for (ptr_iterator MI = top_down_ptr_begin(),
1409 ME = top_down_ptr_end(); MI != ME; ++MI)
1410 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
1411 MI->second.Merge(PtrState(), /*TopDown=*/true);
1414 /// MergeSucc - The bottom-up traversal uses this to merge information about
1415 /// successors to form the initial state for a new block.
1416 void BBState::MergeSucc(const BBState &Other) {
1417 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
1418 // loop backedge. Loop backedges are special.
1419 BottomUpPathCount += Other.BottomUpPathCount;
1421 // For each entry in the other set, if our set has an entry with the
1422 // same key, merge the entries. Otherwise, copy the entry and merge
1423 // it with an empty entry.
1424 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
1425 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
1426 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
1427 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1431 // For each entry in our set, if the other set doesn't have an entry
1432 // with the same key, force it to merge with an empty entry.
1433 for (ptr_iterator MI = bottom_up_ptr_begin(),
1434 ME = bottom_up_ptr_end(); MI != ME; ++MI)
1435 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
1436 MI->second.Merge(PtrState(), /*TopDown=*/false);
1440 /// ObjCARCOpt - The main ARC optimization pass.
1441 class ObjCARCOpt : public FunctionPass {
1443 ProvenanceAnalysis PA;
1445 /// Run - A flag indicating whether this optimization pass should run.
1448 /// RetainRVCallee, etc. - Declarations for ObjC runtime
1449 /// functions, for use in creating calls to them. These are initialized
1450 /// lazily to avoid cluttering up the Module with unused declarations.
1451 Constant *RetainRVCallee, *AutoreleaseRVCallee, *ReleaseCallee,
1452 *RetainCallee, *RetainBlockCallee, *AutoreleaseCallee;
1454 /// UsedInThisFunciton - Flags which determine whether each of the
1455 /// interesting runtine functions is in fact used in the current function.
1456 unsigned UsedInThisFunction;
1458 /// ImpreciseReleaseMDKind - The Metadata Kind for clang.imprecise_release
1460 unsigned ImpreciseReleaseMDKind;
1462 Constant *getRetainRVCallee(Module *M);
1463 Constant *getAutoreleaseRVCallee(Module *M);
1464 Constant *getReleaseCallee(Module *M);
1465 Constant *getRetainCallee(Module *M);
1466 Constant *getRetainBlockCallee(Module *M);
1467 Constant *getAutoreleaseCallee(Module *M);
1469 void OptimizeRetainCall(Function &F, Instruction *Retain);
1470 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
1471 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV);
1472 void OptimizeIndividualCalls(Function &F);
1474 void CheckForCFGHazards(const BasicBlock *BB,
1475 DenseMap<const BasicBlock *, BBState> &BBStates,
1476 BBState &MyStates) const;
1477 bool VisitBottomUp(BasicBlock *BB,
1478 DenseMap<const BasicBlock *, BBState> &BBStates,
1479 MapVector<Value *, RRInfo> &Retains);
1480 bool VisitTopDown(BasicBlock *BB,
1481 DenseMap<const BasicBlock *, BBState> &BBStates,
1482 DenseMap<Value *, RRInfo> &Releases);
1483 bool Visit(Function &F,
1484 DenseMap<const BasicBlock *, BBState> &BBStates,
1485 MapVector<Value *, RRInfo> &Retains,
1486 DenseMap<Value *, RRInfo> &Releases);
1488 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1489 MapVector<Value *, RRInfo> &Retains,
1490 DenseMap<Value *, RRInfo> &Releases,
1491 SmallVectorImpl<Instruction *> &DeadInsts,
1494 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1495 MapVector<Value *, RRInfo> &Retains,
1496 DenseMap<Value *, RRInfo> &Releases,
1499 void OptimizeWeakCalls(Function &F);
1501 bool OptimizeSequences(Function &F);
1503 void OptimizeReturns(Function &F);
1505 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1506 virtual bool doInitialization(Module &M);
1507 virtual bool runOnFunction(Function &F);
1508 virtual void releaseMemory();
1512 ObjCARCOpt() : FunctionPass(ID) {
1513 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1518 char ObjCARCOpt::ID = 0;
1519 INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1520 "objc-arc", "ObjC ARC optimization", false, false)
1521 INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1522 INITIALIZE_PASS_END(ObjCARCOpt,
1523 "objc-arc", "ObjC ARC optimization", false, false)
1525 Pass *llvm::createObjCARCOptPass() {
1526 return new ObjCARCOpt();
1529 void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1530 AU.addRequired<ObjCARCAliasAnalysis>();
1531 AU.addRequired<AliasAnalysis>();
1532 // ARC optimization doesn't currently split critical edges.
1533 AU.setPreservesCFG();
1536 Constant *ObjCARCOpt::getRetainRVCallee(Module *M) {
1537 if (!RetainRVCallee) {
1538 LLVMContext &C = M->getContext();
1539 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1540 std::vector<Type *> Params;
1541 Params.push_back(I8X);
1543 FunctionType::get(I8X, Params, /*isVarArg=*/false);
1544 AttrListPtr Attributes;
1545 Attributes.addAttr(~0u, Attribute::NoUnwind);
1547 M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy,
1550 return RetainRVCallee;
1553 Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1554 if (!AutoreleaseRVCallee) {
1555 LLVMContext &C = M->getContext();
1556 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1557 std::vector<Type *> Params;
1558 Params.push_back(I8X);
1560 FunctionType::get(I8X, Params, /*isVarArg=*/false);
1561 AttrListPtr Attributes;
1562 Attributes.addAttr(~0u, Attribute::NoUnwind);
1563 AutoreleaseRVCallee =
1564 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
1567 return AutoreleaseRVCallee;
1570 Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1571 if (!ReleaseCallee) {
1572 LLVMContext &C = M->getContext();
1573 std::vector<Type *> Params;
1574 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1575 AttrListPtr Attributes;
1576 Attributes.addAttr(~0u, Attribute::NoUnwind);
1578 M->getOrInsertFunction(
1580 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
1583 return ReleaseCallee;
1586 Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1587 if (!RetainCallee) {
1588 LLVMContext &C = M->getContext();
1589 std::vector<Type *> Params;
1590 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1591 AttrListPtr Attributes;
1592 Attributes.addAttr(~0u, Attribute::NoUnwind);
1594 M->getOrInsertFunction(
1596 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1599 return RetainCallee;
1602 Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1603 if (!RetainBlockCallee) {
1604 LLVMContext &C = M->getContext();
1605 std::vector<Type *> Params;
1606 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1607 AttrListPtr Attributes;
1608 Attributes.addAttr(~0u, Attribute::NoUnwind);
1610 M->getOrInsertFunction(
1612 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1615 return RetainBlockCallee;
1618 Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1619 if (!AutoreleaseCallee) {
1620 LLVMContext &C = M->getContext();
1621 std::vector<Type *> Params;
1622 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1623 AttrListPtr Attributes;
1624 Attributes.addAttr(~0u, Attribute::NoUnwind);
1626 M->getOrInsertFunction(
1628 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1631 return AutoreleaseCallee;
1634 /// CanAlterRefCount - Test whether the given instruction can result in a
1635 /// reference count modification (positive or negative) for the pointer's
1638 CanAlterRefCount(const Instruction *Inst, const Value *Ptr,
1639 ProvenanceAnalysis &PA, InstructionClass Class) {
1641 case IC_Autorelease:
1642 case IC_AutoreleaseRV:
1644 // These operations never directly modify a reference count.
1649 ImmutableCallSite CS = static_cast<const Value *>(Inst);
1650 assert(CS && "Only calls can alter reference counts!");
1652 // See if AliasAnalysis can help us with the call.
1653 AliasAnalysis::ModRefBehavior MRB = PA.getAA()->getModRefBehavior(CS);
1654 if (AliasAnalysis::onlyReadsMemory(MRB))
1656 if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
1657 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1659 const Value *Op = *I;
1660 if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1666 // Assume the worst.
1670 /// CanUse - Test whether the given instruction can "use" the given pointer's
1671 /// object in a way that requires the reference count to be positive.
1673 CanUse(const Instruction *Inst, const Value *Ptr, ProvenanceAnalysis &PA,
1674 InstructionClass Class) {
1675 // IC_Call operations (as opposed to IC_CallOrUser) never "use" objc pointers.
1676 if (Class == IC_Call)
1679 // Consider various instructions which may have pointer arguments which are
1681 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(Inst)) {
1682 // Comparing a pointer with null, or any other constant, isn't really a use,
1683 // because we don't care what the pointer points to, or about the values
1684 // of any other dynamic reference-counted pointers.
1685 if (!IsPotentialUse(ICI->getOperand(1)))
1687 } else if (ImmutableCallSite CS = static_cast<const Value *>(Inst)) {
1688 // For calls, just check the arguments (and not the callee operand).
1689 for (ImmutableCallSite::arg_iterator OI = CS.arg_begin(),
1690 OE = CS.arg_end(); OI != OE; ++OI) {
1691 const Value *Op = *OI;
1692 if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1696 } else if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1697 // Special-case stores, because we don't care about the stored value, just
1698 // the store address.
1699 const Value *Op = GetUnderlyingObjCPtr(SI->getPointerOperand());
1700 // If we can't tell what the underlying object was, assume there is a
1702 return IsPotentialUse(Op) && PA.related(Op, Ptr);
1705 // Check each operand for a match.
1706 for (User::const_op_iterator OI = Inst->op_begin(), OE = Inst->op_end();
1708 const Value *Op = *OI;
1709 if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1715 /// CanInterruptRV - Test whether the given instruction can autorelease
1716 /// any pointer or cause an autoreleasepool pop.
1718 CanInterruptRV(InstructionClass Class) {
1720 case IC_AutoreleasepoolPop:
1723 case IC_Autorelease:
1724 case IC_AutoreleaseRV:
1725 case IC_FusedRetainAutorelease:
1726 case IC_FusedRetainAutoreleaseRV:
1734 /// DependenceKind - There are several kinds of dependence-like concepts in
1736 enum DependenceKind {
1737 NeedsPositiveRetainCount,
1738 CanChangeRetainCount,
1739 RetainAutoreleaseDep, ///< Blocks objc_retainAutorelease.
1740 RetainAutoreleaseRVDep, ///< Blocks objc_retainAutoreleaseReturnValue.
1741 RetainRVDep ///< Blocks objc_retainAutoreleasedReturnValue.
1745 /// Depends - Test if there can be dependencies on Inst through Arg. This
1746 /// function only tests dependencies relevant for removing pairs of calls.
1748 Depends(DependenceKind Flavor, Instruction *Inst, const Value *Arg,
1749 ProvenanceAnalysis &PA) {
1750 // If we've reached the definition of Arg, stop.
1755 case NeedsPositiveRetainCount: {
1756 InstructionClass Class = GetInstructionClass(Inst);
1758 case IC_AutoreleasepoolPop:
1759 case IC_AutoreleasepoolPush:
1763 return CanUse(Inst, Arg, PA, Class);
1767 case CanChangeRetainCount: {
1768 InstructionClass Class = GetInstructionClass(Inst);
1770 case IC_AutoreleasepoolPop:
1771 // Conservatively assume this can decrement any count.
1773 case IC_AutoreleasepoolPush:
1777 return CanAlterRefCount(Inst, Arg, PA, Class);
1781 case RetainAutoreleaseDep:
1782 switch (GetBasicInstructionClass(Inst)) {
1783 case IC_AutoreleasepoolPop:
1784 // Don't merge an objc_autorelease with an objc_retain inside a different
1785 // autoreleasepool scope.
1789 // Check for a retain of the same pointer for merging.
1790 return GetObjCArg(Inst) == Arg;
1792 // Nothing else matters for objc_retainAutorelease formation.
1797 case RetainAutoreleaseRVDep: {
1798 InstructionClass Class = GetBasicInstructionClass(Inst);
1802 // Check for a retain of the same pointer for merging.
1803 return GetObjCArg(Inst) == Arg;
1805 // Anything that can autorelease interrupts
1806 // retainAutoreleaseReturnValue formation.
1807 return CanInterruptRV(Class);
1813 return CanInterruptRV(GetBasicInstructionClass(Inst));
1816 llvm_unreachable("Invalid dependence flavor");
1820 /// FindDependencies - Walk up the CFG from StartPos (which is in StartBB) and
1821 /// find local and non-local dependencies on Arg.
1822 /// TODO: Cache results?
1824 FindDependencies(DependenceKind Flavor,
1826 BasicBlock *StartBB, Instruction *StartInst,
1827 SmallPtrSet<Instruction *, 4> &DependingInstructions,
1828 SmallPtrSet<const BasicBlock *, 4> &Visited,
1829 ProvenanceAnalysis &PA) {
1830 BasicBlock::iterator StartPos = StartInst;
1832 SmallVector<std::pair<BasicBlock *, BasicBlock::iterator>, 4> Worklist;
1833 Worklist.push_back(std::make_pair(StartBB, StartPos));
1835 std::pair<BasicBlock *, BasicBlock::iterator> Pair =
1836 Worklist.pop_back_val();
1837 BasicBlock *LocalStartBB = Pair.first;
1838 BasicBlock::iterator LocalStartPos = Pair.second;
1839 BasicBlock::iterator StartBBBegin = LocalStartBB->begin();
1841 if (LocalStartPos == StartBBBegin) {
1842 pred_iterator PI(LocalStartBB), PE(LocalStartBB, false);
1844 // If we've reached the function entry, produce a null dependence.
1845 DependingInstructions.insert(0);
1847 // Add the predecessors to the worklist.
1849 BasicBlock *PredBB = *PI;
1850 if (Visited.insert(PredBB))
1851 Worklist.push_back(std::make_pair(PredBB, PredBB->end()));
1852 } while (++PI != PE);
1856 Instruction *Inst = --LocalStartPos;
1857 if (Depends(Flavor, Inst, Arg, PA)) {
1858 DependingInstructions.insert(Inst);
1862 } while (!Worklist.empty());
1864 // Determine whether the original StartBB post-dominates all of the blocks we
1865 // visited. If not, insert a sentinal indicating that most optimizations are
1867 for (SmallPtrSet<const BasicBlock *, 4>::const_iterator I = Visited.begin(),
1868 E = Visited.end(); I != E; ++I) {
1869 const BasicBlock *BB = *I;
1872 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
1873 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
1874 const BasicBlock *Succ = *SI;
1875 if (Succ != StartBB && !Visited.count(Succ)) {
1876 DependingInstructions.insert(reinterpret_cast<Instruction *>(-1));
1883 static bool isNullOrUndef(const Value *V) {
1884 return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
1887 static bool isNoopInstruction(const Instruction *I) {
1888 return isa<BitCastInst>(I) ||
1889 (isa<GetElementPtrInst>(I) &&
1890 cast<GetElementPtrInst>(I)->hasAllZeroIndices());
1893 /// OptimizeRetainCall - Turn objc_retain into
1894 /// objc_retainAutoreleasedReturnValue if the operand is a return value.
1896 ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) {
1897 CallSite CS(GetObjCArg(Retain));
1898 Instruction *Call = CS.getInstruction();
1900 if (Call->getParent() != Retain->getParent()) return;
1902 // Check that the call is next to the retain.
1903 BasicBlock::iterator I = Call;
1905 while (isNoopInstruction(I)) ++I;
1909 // Turn it to an objc_retainAutoreleasedReturnValue..
1912 cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent()));
1915 /// OptimizeRetainRVCall - Turn objc_retainAutoreleasedReturnValue into
1916 /// objc_retain if the operand is not a return value. Or, if it can be
1917 /// paired with an objc_autoreleaseReturnValue, delete the pair and
1920 ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
1921 // Check for the argument being from an immediately preceding call.
1922 Value *Arg = GetObjCArg(RetainRV);
1924 if (Instruction *Call = CS.getInstruction())
1925 if (Call->getParent() == RetainRV->getParent()) {
1926 BasicBlock::iterator I = Call;
1928 while (isNoopInstruction(I)) ++I;
1929 if (&*I == RetainRV)
1933 // Check for being preceded by an objc_autoreleaseReturnValue on the same
1934 // pointer. In this case, we can delete the pair.
1935 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
1937 do --I; while (I != Begin && isNoopInstruction(I));
1938 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
1939 GetObjCArg(I) == Arg) {
1942 EraseInstruction(I);
1943 EraseInstruction(RetainRV);
1948 // Turn it to a plain objc_retain.
1951 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
1955 /// OptimizeAutoreleaseRVCall - Turn objc_autoreleaseReturnValue into
1956 /// objc_autorelease if the result is not used as a return value.
1958 ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV) {
1959 // Check for a return of the pointer value.
1960 const Value *Ptr = GetObjCArg(AutoreleaseRV);
1961 SmallVector<const Value *, 2> Users;
1962 Users.push_back(Ptr);
1964 Ptr = Users.pop_back_val();
1965 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
1967 const User *I = *UI;
1968 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
1970 if (isa<BitCastInst>(I))
1973 } while (!Users.empty());
1977 cast<CallInst>(AutoreleaseRV)->
1978 setCalledFunction(getAutoreleaseCallee(F.getParent()));
1981 /// OptimizeIndividualCalls - Visit each call, one at a time, and make
1982 /// simplifications without doing any additional analysis.
1983 void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
1984 // Reset all the flags in preparation for recomputing them.
1985 UsedInThisFunction = 0;
1987 // Visit all objc_* calls in F.
1988 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
1989 Instruction *Inst = &*I++;
1990 InstructionClass Class = GetBasicInstructionClass(Inst);
1995 // Delete no-op casts. These function calls have special semantics, but
1996 // the semantics are entirely implemented via lowering in the front-end,
1997 // so by the time they reach the optimizer, they are just no-op calls
1998 // which return their argument.
2000 // There are gray areas here, as the ability to cast reference-counted
2001 // pointers to raw void* and back allows code to break ARC assumptions,
2002 // however these are currently considered to be unimportant.
2006 EraseInstruction(Inst);
2009 // If the pointer-to-weak-pointer is null, it's undefined behavior.
2012 case IC_LoadWeakRetained:
2014 case IC_DestroyWeak: {
2015 CallInst *CI = cast<CallInst>(Inst);
2016 if (isNullOrUndef(CI->getArgOperand(0))) {
2017 Type *Ty = CI->getArgOperand(0)->getType();
2018 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2019 Constant::getNullValue(Ty),
2021 CI->replaceAllUsesWith(UndefValue::get(CI->getType()));
2022 CI->eraseFromParent();
2029 CallInst *CI = cast<CallInst>(Inst);
2030 if (isNullOrUndef(CI->getArgOperand(0)) ||
2031 isNullOrUndef(CI->getArgOperand(1))) {
2032 Type *Ty = CI->getArgOperand(0)->getType();
2033 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2034 Constant::getNullValue(Ty),
2036 CI->replaceAllUsesWith(UndefValue::get(CI->getType()));
2037 CI->eraseFromParent();
2043 OptimizeRetainCall(F, Inst);
2046 if (OptimizeRetainRVCall(F, Inst))
2049 case IC_AutoreleaseRV:
2050 OptimizeAutoreleaseRVCall(F, Inst);
2054 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
2055 if (IsAutorelease(Class) && Inst->use_empty()) {
2056 CallInst *Call = cast<CallInst>(Inst);
2057 const Value *Arg = Call->getArgOperand(0);
2058 Arg = FindSingleUseIdentifiedObject(Arg);
2063 // Create the declaration lazily.
2064 LLVMContext &C = Inst->getContext();
2066 CallInst::Create(getReleaseCallee(F.getParent()),
2067 Call->getArgOperand(0), "", Call);
2068 NewCall->setMetadata(ImpreciseReleaseMDKind,
2069 MDNode::get(C, ArrayRef<Value *>()));
2070 EraseInstruction(Call);
2076 // For functions which can never be passed stack arguments, add
2078 if (IsAlwaysTail(Class)) {
2080 cast<CallInst>(Inst)->setTailCall();
2083 // Set nounwind as needed.
2084 if (IsNoThrow(Class)) {
2086 cast<CallInst>(Inst)->setDoesNotThrow();
2089 if (!IsNoopOnNull(Class)) {
2090 UsedInThisFunction |= 1 << Class;
2094 const Value *Arg = GetObjCArg(Inst);
2096 // ARC calls with null are no-ops. Delete them.
2097 if (isNullOrUndef(Arg)) {
2100 EraseInstruction(Inst);
2104 // Keep track of which of retain, release, autorelease, and retain_block
2105 // are actually present in this function.
2106 UsedInThisFunction |= 1 << Class;
2108 // If Arg is a PHI, and one or more incoming values to the
2109 // PHI are null, and the call is control-equivalent to the PHI, and there
2110 // are no relevant side effects between the PHI and the call, the call
2111 // could be pushed up to just those paths with non-null incoming values.
2112 // For now, don't bother splitting critical edges for this.
2113 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
2114 Worklist.push_back(std::make_pair(Inst, Arg));
2116 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
2120 const PHINode *PN = dyn_cast<PHINode>(Arg);
2123 // Determine if the PHI has any null operands, or any incoming
2125 bool HasNull = false;
2126 bool HasCriticalEdges = false;
2127 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2129 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2130 if (isNullOrUndef(Incoming))
2132 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
2133 .getNumSuccessors() != 1) {
2134 HasCriticalEdges = true;
2138 // If we have null operands and no critical edges, optimize.
2139 if (!HasCriticalEdges && HasNull) {
2140 SmallPtrSet<Instruction *, 4> DependingInstructions;
2141 SmallPtrSet<const BasicBlock *, 4> Visited;
2143 // Check that there is nothing that cares about the reference
2144 // count between the call and the phi.
2145 FindDependencies(NeedsPositiveRetainCount, Arg,
2146 Inst->getParent(), Inst,
2147 DependingInstructions, Visited, PA);
2148 if (DependingInstructions.size() == 1 &&
2149 *DependingInstructions.begin() == PN) {
2152 // Clone the call into each predecessor that has a non-null value.
2153 CallInst *CInst = cast<CallInst>(Inst);
2154 Type *ParamTy = CInst->getArgOperand(0)->getType();
2155 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2157 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2158 if (!isNullOrUndef(Incoming)) {
2159 CallInst *Clone = cast<CallInst>(CInst->clone());
2160 Value *Op = PN->getIncomingValue(i);
2161 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
2162 if (Op->getType() != ParamTy)
2163 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
2164 Clone->setArgOperand(0, Op);
2165 Clone->insertBefore(InsertPos);
2166 Worklist.push_back(std::make_pair(Clone, Incoming));
2169 // Erase the original call.
2170 EraseInstruction(CInst);
2174 } while (!Worklist.empty());
2178 /// CheckForCFGHazards - Check for critical edges, loop boundaries, irreducible
2179 /// control flow, or other CFG structures where moving code across the edge
2180 /// would result in it being executed more.
2182 ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
2183 DenseMap<const BasicBlock *, BBState> &BBStates,
2184 BBState &MyStates) const {
2185 // If any top-down local-use or possible-dec has a succ which is earlier in
2186 // the sequence, forget it.
2187 for (BBState::ptr_const_iterator I = MyStates.top_down_ptr_begin(),
2188 E = MyStates.top_down_ptr_end(); I != E; ++I)
2189 switch (I->second.GetSeq()) {
2192 const Value *Arg = I->first;
2193 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2194 bool SomeSuccHasSame = false;
2195 bool AllSuccsHaveSame = true;
2196 PtrState &S = MyStates.getPtrTopDownState(Arg);
2197 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2198 PtrState &SuccS = BBStates[*SI].getPtrBottomUpState(Arg);
2199 switch (SuccS.GetSeq()) {
2201 case S_CanRelease: {
2202 if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
2203 S.ClearSequenceProgress();
2207 SomeSuccHasSame = true;
2211 case S_MovableRelease:
2212 if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
2213 AllSuccsHaveSame = false;
2216 llvm_unreachable("bottom-up pointer in retain state!");
2219 // If the state at the other end of any of the successor edges
2220 // matches the current state, require all edges to match. This
2221 // guards against loops in the middle of a sequence.
2222 if (SomeSuccHasSame && !AllSuccsHaveSame)
2223 S.ClearSequenceProgress();
2225 case S_CanRelease: {
2226 const Value *Arg = I->first;
2227 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2228 bool SomeSuccHasSame = false;
2229 bool AllSuccsHaveSame = true;
2230 PtrState &S = MyStates.getPtrTopDownState(Arg);
2231 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2232 PtrState &SuccS = BBStates[*SI].getPtrBottomUpState(Arg);
2233 switch (SuccS.GetSeq()) {
2235 if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
2236 S.ClearSequenceProgress();
2240 SomeSuccHasSame = true;
2244 case S_MovableRelease:
2246 if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
2247 AllSuccsHaveSame = false;
2250 llvm_unreachable("bottom-up pointer in retain state!");
2253 // If the state at the other end of any of the successor edges
2254 // matches the current state, require all edges to match. This
2255 // guards against loops in the middle of a sequence.
2256 if (SomeSuccHasSame && !AllSuccsHaveSame)
2257 S.ClearSequenceProgress();
2263 ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2264 DenseMap<const BasicBlock *, BBState> &BBStates,
2265 MapVector<Value *, RRInfo> &Retains) {
2266 bool NestingDetected = false;
2267 BBState &MyStates = BBStates[BB];
2269 // Merge the states from each successor to compute the initial state
2270 // for the current block.
2271 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2272 succ_const_iterator SI(TI), SE(TI, false);
2274 MyStates.SetAsExit();
2277 const BasicBlock *Succ = *SI++;
2280 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
2281 // If we haven't seen this node yet, then we've found a CFG cycle.
2282 // Be optimistic here; it's CheckForCFGHazards' job detect trouble.
2283 if (I == BBStates.end())
2285 MyStates.InitFromSucc(I->second);
2289 I = BBStates.find(Succ);
2290 if (I != BBStates.end())
2291 MyStates.MergeSucc(I->second);
2297 // Visit all the instructions, bottom-up.
2298 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2299 Instruction *Inst = llvm::prior(I);
2300 InstructionClass Class = GetInstructionClass(Inst);
2301 const Value *Arg = 0;
2305 Arg = GetObjCArg(Inst);
2307 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2309 // If we see two releases in a row on the same pointer. If so, make
2310 // a note, and we'll cicle back to revisit it after we've
2311 // hopefully eliminated the second release, which may allow us to
2312 // eliminate the first release too.
2313 // Theoretically we could implement removal of nested retain+release
2314 // pairs by making PtrState hold a stack of states, but this is
2315 // simple and avoids adding overhead for the non-nested case.
2316 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease)
2317 NestingDetected = true;
2319 S.SetSeqToRelease(Inst->getMetadata(ImpreciseReleaseMDKind));
2321 S.RRI.KnownSafe = S.IsKnownNested() || S.IsKnownIncremented();
2322 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2323 S.RRI.Calls.insert(Inst);
2325 S.IncrementRefCount();
2326 S.IncrementNestCount();
2329 case IC_RetainBlock:
2332 Arg = GetObjCArg(Inst);
2334 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2335 S.DecrementRefCount();
2336 S.SetAtLeastOneRefCount();
2337 S.DecrementNestCount();
2339 switch (S.GetSeq()) {
2342 case S_MovableRelease:
2344 S.RRI.ReverseInsertPts.clear();
2347 // Don't do retain+release tracking for IC_RetainRV, because it's
2348 // better to let it remain as the first instruction after a call.
2349 if (Class != IC_RetainRV) {
2350 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2351 Retains[Inst] = S.RRI;
2353 S.ClearSequenceProgress();
2358 llvm_unreachable("bottom-up pointer in retain state!");
2362 case IC_AutoreleasepoolPop:
2363 // Conservatively, clear MyStates for all known pointers.
2364 MyStates.clearBottomUpPointers();
2366 case IC_AutoreleasepoolPush:
2368 // These are irrelevant.
2374 // Consider any other possible effects of this instruction on each
2375 // pointer being tracked.
2376 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
2377 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
2378 const Value *Ptr = MI->first;
2380 continue; // Handled above.
2381 PtrState &S = MI->second;
2382 Sequence Seq = S.GetSeq();
2384 // Check for possible releases.
2385 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2386 S.DecrementRefCount();
2389 S.SetSeq(S_CanRelease);
2393 case S_MovableRelease:
2398 llvm_unreachable("bottom-up pointer in retain state!");
2402 // Check for possible direct uses.
2405 case S_MovableRelease:
2406 if (CanUse(Inst, Ptr, PA, Class)) {
2407 S.RRI.ReverseInsertPts.clear();
2408 S.RRI.ReverseInsertPts.insert(Inst);
2410 } else if (Seq == S_Release &&
2411 (Class == IC_User || Class == IC_CallOrUser)) {
2412 // Non-movable releases depend on any possible objc pointer use.
2414 S.RRI.ReverseInsertPts.clear();
2415 S.RRI.ReverseInsertPts.insert(Inst);
2419 if (CanUse(Inst, Ptr, PA, Class))
2427 llvm_unreachable("bottom-up pointer in retain state!");
2432 return NestingDetected;
2436 ObjCARCOpt::VisitTopDown(BasicBlock *BB,
2437 DenseMap<const BasicBlock *, BBState> &BBStates,
2438 DenseMap<Value *, RRInfo> &Releases) {
2439 bool NestingDetected = false;
2440 BBState &MyStates = BBStates[BB];
2442 // Merge the states from each predecessor to compute the initial state
2443 // for the current block.
2444 const_pred_iterator PI(BB), PE(BB, false);
2446 MyStates.SetAsEntry();
2449 const BasicBlock *Pred = *PI++;
2452 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
2453 assert(I != BBStates.end());
2454 // If we haven't seen this node yet, then we've found a CFG cycle.
2455 // Be optimistic here; it's CheckForCFGHazards' job detect trouble.
2456 if (!I->second.isVisitedTopDown())
2458 MyStates.InitFromPred(I->second);
2462 I = BBStates.find(Pred);
2463 assert(I != BBStates.end());
2464 if (I->second.isVisitedTopDown())
2465 MyStates.MergePred(I->second);
2471 // Visit all the instructions, top-down.
2472 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2473 Instruction *Inst = I;
2474 InstructionClass Class = GetInstructionClass(Inst);
2475 const Value *Arg = 0;
2478 case IC_RetainBlock:
2481 Arg = GetObjCArg(Inst);
2483 PtrState &S = MyStates.getPtrTopDownState(Arg);
2485 // Don't do retain+release tracking for IC_RetainRV, because it's
2486 // better to let it remain as the first instruction after a call.
2487 if (Class != IC_RetainRV) {
2488 // If we see two retains in a row on the same pointer. If so, make
2489 // a note, and we'll cicle back to revisit it after we've
2490 // hopefully eliminated the second retain, which may allow us to
2491 // eliminate the first retain too.
2492 // Theoretically we could implement removal of nested retain+release
2493 // pairs by making PtrState hold a stack of states, but this is
2494 // simple and avoids adding overhead for the non-nested case.
2495 if (S.GetSeq() == S_Retain)
2496 NestingDetected = true;
2500 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2501 // Don't check S.IsKnownIncremented() here because it's not
2503 S.RRI.KnownSafe = S.IsKnownNested();
2504 S.RRI.Calls.insert(Inst);
2507 S.SetAtLeastOneRefCount();
2508 S.IncrementRefCount();
2509 S.IncrementNestCount();
2513 Arg = GetObjCArg(Inst);
2515 PtrState &S = MyStates.getPtrTopDownState(Arg);
2516 S.DecrementRefCount();
2517 S.DecrementNestCount();
2519 switch (S.GetSeq()) {
2522 S.RRI.ReverseInsertPts.clear();
2525 S.RRI.ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2526 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2527 Releases[Inst] = S.RRI;
2528 S.ClearSequenceProgress();
2534 case S_MovableRelease:
2535 llvm_unreachable("top-down pointer in release state!");
2539 case IC_AutoreleasepoolPop:
2540 // Conservatively, clear MyStates for all known pointers.
2541 MyStates.clearTopDownPointers();
2543 case IC_AutoreleasepoolPush:
2545 // These are irrelevant.
2551 // Consider any other possible effects of this instruction on each
2552 // pointer being tracked.
2553 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
2554 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
2555 const Value *Ptr = MI->first;
2557 continue; // Handled above.
2558 PtrState &S = MI->second;
2559 Sequence Seq = S.GetSeq();
2561 // Check for possible releases.
2562 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2563 S.DecrementRefCount();
2566 S.SetSeq(S_CanRelease);
2567 S.RRI.ReverseInsertPts.clear();
2568 S.RRI.ReverseInsertPts.insert(Inst);
2570 // One call can't cause a transition from S_Retain to S_CanRelease
2571 // and S_CanRelease to S_Use. If we've made the first transition,
2580 case S_MovableRelease:
2581 llvm_unreachable("top-down pointer in release state!");
2585 // Check for possible direct uses.
2588 if (CanUse(Inst, Ptr, PA, Class))
2597 case S_MovableRelease:
2598 llvm_unreachable("top-down pointer in release state!");
2603 CheckForCFGHazards(BB, BBStates, MyStates);
2604 return NestingDetected;
2607 // Visit - Visit the function both top-down and bottom-up.
2609 ObjCARCOpt::Visit(Function &F,
2610 DenseMap<const BasicBlock *, BBState> &BBStates,
2611 MapVector<Value *, RRInfo> &Retains,
2612 DenseMap<Value *, RRInfo> &Releases) {
2613 // Use reverse-postorder on the reverse CFG for bottom-up, because we
2614 // magically know that loops will be well behaved, i.e. they won't repeatedly
2615 // call retain on a single pointer without doing a release. We can't use
2616 // ReversePostOrderTraversal here because we want to walk up from each
2617 // function exit point.
2618 SmallPtrSet<BasicBlock *, 16> Visited;
2619 SmallVector<std::pair<BasicBlock *, pred_iterator>, 16> Stack;
2620 SmallVector<BasicBlock *, 16> Order;
2621 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
2623 if (BB->getTerminator()->getNumSuccessors() == 0)
2624 Stack.push_back(std::make_pair(BB, pred_begin(BB)));
2626 while (!Stack.empty()) {
2627 pred_iterator End = pred_end(Stack.back().first);
2628 while (Stack.back().second != End) {
2629 BasicBlock *BB = *Stack.back().second++;
2630 if (Visited.insert(BB))
2631 Stack.push_back(std::make_pair(BB, pred_begin(BB)));
2633 Order.push_back(Stack.pop_back_val().first);
2635 bool BottomUpNestingDetected = false;
2636 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2637 Order.rbegin(), E = Order.rend(); I != E; ++I) {
2638 BasicBlock *BB = *I;
2639 BottomUpNestingDetected |= VisitBottomUp(BB, BBStates, Retains);
2642 // Use regular reverse-postorder for top-down.
2643 bool TopDownNestingDetected = false;
2644 typedef ReversePostOrderTraversal<Function *> RPOTType;
2646 for (RPOTType::rpo_iterator I = RPOT.begin(), E = RPOT.end(); I != E; ++I) {
2647 BasicBlock *BB = *I;
2648 TopDownNestingDetected |= VisitTopDown(BB, BBStates, Releases);
2651 return TopDownNestingDetected && BottomUpNestingDetected;
2654 /// MoveCalls - Move the calls in RetainsToMove and ReleasesToMove.
2655 void ObjCARCOpt::MoveCalls(Value *Arg,
2656 RRInfo &RetainsToMove,
2657 RRInfo &ReleasesToMove,
2658 MapVector<Value *, RRInfo> &Retains,
2659 DenseMap<Value *, RRInfo> &Releases,
2660 SmallVectorImpl<Instruction *> &DeadInsts,
2662 Type *ArgTy = Arg->getType();
2663 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
2665 // Insert the new retain and release calls.
2666 for (SmallPtrSet<Instruction *, 2>::const_iterator
2667 PI = ReleasesToMove.ReverseInsertPts.begin(),
2668 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2669 Instruction *InsertPt = *PI;
2670 Value *MyArg = ArgTy == ParamTy ? Arg :
2671 new BitCastInst(Arg, ParamTy, "", InsertPt);
2673 CallInst::Create(RetainsToMove.IsRetainBlock ?
2674 getRetainBlockCallee(M) : getRetainCallee(M),
2675 MyArg, "", InsertPt);
2676 Call->setDoesNotThrow();
2677 if (!RetainsToMove.IsRetainBlock)
2678 Call->setTailCall();
2680 for (SmallPtrSet<Instruction *, 2>::const_iterator
2681 PI = RetainsToMove.ReverseInsertPts.begin(),
2682 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2683 Instruction *LastUse = *PI;
2684 Instruction *InsertPts[] = { 0, 0, 0 };
2685 if (InvokeInst *II = dyn_cast<InvokeInst>(LastUse)) {
2686 // We can't insert code immediately after an invoke instruction, so
2687 // insert code at the beginning of both successor blocks instead.
2688 // The invoke's return value isn't available in the unwind block,
2689 // but our releases will never depend on it, because they must be
2690 // paired with retains from before the invoke.
2691 InsertPts[0] = II->getNormalDest()->getFirstInsertionPt();
2692 InsertPts[1] = II->getUnwindDest()->getFirstInsertionPt();
2694 // Insert code immediately after the last use.
2695 InsertPts[0] = llvm::next(BasicBlock::iterator(LastUse));
2698 for (Instruction **I = InsertPts; *I; ++I) {
2699 Instruction *InsertPt = *I;
2700 Value *MyArg = ArgTy == ParamTy ? Arg :
2701 new BitCastInst(Arg, ParamTy, "", InsertPt);
2702 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
2704 // Attach a clang.imprecise_release metadata tag, if appropriate.
2705 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
2706 Call->setMetadata(ImpreciseReleaseMDKind, M);
2707 Call->setDoesNotThrow();
2708 if (ReleasesToMove.IsTailCallRelease)
2709 Call->setTailCall();
2713 // Delete the original retain and release calls.
2714 for (SmallPtrSet<Instruction *, 2>::const_iterator
2715 AI = RetainsToMove.Calls.begin(),
2716 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
2717 Instruction *OrigRetain = *AI;
2718 Retains.blot(OrigRetain);
2719 DeadInsts.push_back(OrigRetain);
2721 for (SmallPtrSet<Instruction *, 2>::const_iterator
2722 AI = ReleasesToMove.Calls.begin(),
2723 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
2724 Instruction *OrigRelease = *AI;
2725 Releases.erase(OrigRelease);
2726 DeadInsts.push_back(OrigRelease);
2731 ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
2733 MapVector<Value *, RRInfo> &Retains,
2734 DenseMap<Value *, RRInfo> &Releases,
2736 bool AnyPairsCompletelyEliminated = false;
2737 RRInfo RetainsToMove;
2738 RRInfo ReleasesToMove;
2739 SmallVector<Instruction *, 4> NewRetains;
2740 SmallVector<Instruction *, 4> NewReleases;
2741 SmallVector<Instruction *, 8> DeadInsts;
2743 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
2744 E = Retains.end(); I != E; ) {
2745 Value *V = (I++)->first;
2746 if (!V) continue; // blotted
2748 Instruction *Retain = cast<Instruction>(V);
2749 Value *Arg = GetObjCArg(Retain);
2751 // If the object being released is in static or stack storage, we know it's
2752 // not being managed by ObjC reference counting, so we can delete pairs
2753 // regardless of what possible decrements or uses lie between them.
2754 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
2756 // A constant pointer can't be pointing to an object on the heap. It may
2757 // be reference-counted, but it won't be deleted.
2758 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
2759 if (const GlobalVariable *GV =
2760 dyn_cast<GlobalVariable>(
2761 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
2762 if (GV->isConstant())
2765 // If a pair happens in a region where it is known that the reference count
2766 // is already incremented, we can similarly ignore possible decrements.
2767 bool KnownSafeTD = true, KnownSafeBU = true;
2769 // Connect the dots between the top-down-collected RetainsToMove and
2770 // bottom-up-collected ReleasesToMove to form sets of related calls.
2771 // This is an iterative process so that we connect multiple releases
2772 // to multiple retains if needed.
2773 unsigned OldDelta = 0;
2774 unsigned NewDelta = 0;
2775 unsigned OldCount = 0;
2776 unsigned NewCount = 0;
2777 bool FirstRelease = true;
2778 bool FirstRetain = true;
2779 NewRetains.push_back(Retain);
2781 for (SmallVectorImpl<Instruction *>::const_iterator
2782 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
2783 Instruction *NewRetain = *NI;
2784 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
2785 assert(It != Retains.end());
2786 const RRInfo &NewRetainRRI = It->second;
2787 KnownSafeTD &= NewRetainRRI.KnownSafe;
2788 for (SmallPtrSet<Instruction *, 2>::const_iterator
2789 LI = NewRetainRRI.Calls.begin(),
2790 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
2791 Instruction *NewRetainRelease = *LI;
2792 DenseMap<Value *, RRInfo>::const_iterator Jt =
2793 Releases.find(NewRetainRelease);
2794 if (Jt == Releases.end())
2796 const RRInfo &NewRetainReleaseRRI = Jt->second;
2797 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
2798 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
2800 BBStates[NewRetainRelease->getParent()].GetAllPathCount();
2802 // Merge the ReleaseMetadata and IsTailCallRelease values.
2804 ReleasesToMove.ReleaseMetadata =
2805 NewRetainReleaseRRI.ReleaseMetadata;
2806 ReleasesToMove.IsTailCallRelease =
2807 NewRetainReleaseRRI.IsTailCallRelease;
2808 FirstRelease = false;
2810 if (ReleasesToMove.ReleaseMetadata !=
2811 NewRetainReleaseRRI.ReleaseMetadata)
2812 ReleasesToMove.ReleaseMetadata = 0;
2813 if (ReleasesToMove.IsTailCallRelease !=
2814 NewRetainReleaseRRI.IsTailCallRelease)
2815 ReleasesToMove.IsTailCallRelease = false;
2818 // Collect the optimal insertion points.
2820 for (SmallPtrSet<Instruction *, 2>::const_iterator
2821 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
2822 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
2824 Instruction *RIP = *RI;
2825 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
2826 NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
2828 NewReleases.push_back(NewRetainRelease);
2833 if (NewReleases.empty()) break;
2835 // Back the other way.
2836 for (SmallVectorImpl<Instruction *>::const_iterator
2837 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
2838 Instruction *NewRelease = *NI;
2839 DenseMap<Value *, RRInfo>::const_iterator It =
2840 Releases.find(NewRelease);
2841 assert(It != Releases.end());
2842 const RRInfo &NewReleaseRRI = It->second;
2843 KnownSafeBU &= NewReleaseRRI.KnownSafe;
2844 for (SmallPtrSet<Instruction *, 2>::const_iterator
2845 LI = NewReleaseRRI.Calls.begin(),
2846 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
2847 Instruction *NewReleaseRetain = *LI;
2848 MapVector<Value *, RRInfo>::const_iterator Jt =
2849 Retains.find(NewReleaseRetain);
2850 if (Jt == Retains.end())
2852 const RRInfo &NewReleaseRetainRRI = Jt->second;
2853 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
2854 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
2855 unsigned PathCount =
2856 BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
2857 OldDelta += PathCount;
2858 OldCount += PathCount;
2860 // Merge the IsRetainBlock values.
2862 RetainsToMove.IsRetainBlock = NewReleaseRetainRRI.IsRetainBlock;
2863 FirstRetain = false;
2864 } else if (ReleasesToMove.IsRetainBlock !=
2865 NewReleaseRetainRRI.IsRetainBlock)
2866 // It's not possible to merge the sequences if one uses
2867 // objc_retain and the other uses objc_retainBlock.
2870 // Collect the optimal insertion points.
2872 for (SmallPtrSet<Instruction *, 2>::const_iterator
2873 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
2874 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
2876 Instruction *RIP = *RI;
2877 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
2878 PathCount = BBStates[RIP->getParent()].GetAllPathCount();
2879 NewDelta += PathCount;
2880 NewCount += PathCount;
2883 NewRetains.push_back(NewReleaseRetain);
2887 NewReleases.clear();
2888 if (NewRetains.empty()) break;
2891 // If the pointer is known incremented or nested, we can safely delete the
2892 // pair regardless of what's between them.
2893 if (KnownSafeTD || KnownSafeBU) {
2894 RetainsToMove.ReverseInsertPts.clear();
2895 ReleasesToMove.ReverseInsertPts.clear();
2898 // Determine whether the new insertion points we computed preserve the
2899 // balance of retain and release calls through the program.
2900 // TODO: If the fully aggressive solution isn't valid, try to find a
2901 // less aggressive solution which is.
2906 // Determine whether the original call points are balanced in the retain and
2907 // release calls through the program. If not, conservatively don't touch
2909 // TODO: It's theoretically possible to do code motion in this case, as
2910 // long as the existing imbalances are maintained.
2914 // Ok, everything checks out and we're all set. Let's move some code!
2916 AnyPairsCompletelyEliminated = NewCount == 0;
2917 NumRRs += OldCount - NewCount;
2918 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
2919 Retains, Releases, DeadInsts, M);
2922 NewReleases.clear();
2924 RetainsToMove.clear();
2925 ReleasesToMove.clear();
2928 // Now that we're done moving everything, we can delete the newly dead
2929 // instructions, as we no longer need them as insert points.
2930 while (!DeadInsts.empty())
2931 EraseInstruction(DeadInsts.pop_back_val());
2933 return AnyPairsCompletelyEliminated;
2936 /// OptimizeWeakCalls - Weak pointer optimizations.
2937 void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
2938 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
2939 // itself because it uses AliasAnalysis and we need to do provenance
2941 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2942 Instruction *Inst = &*I++;
2943 InstructionClass Class = GetBasicInstructionClass(Inst);
2944 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
2947 // Delete objc_loadWeak calls with no users.
2948 if (Class == IC_LoadWeak && Inst->use_empty()) {
2949 Inst->eraseFromParent();
2953 // TODO: For now, just look for an earlier available version of this value
2954 // within the same block. Theoretically, we could do memdep-style non-local
2955 // analysis too, but that would want caching. A better approach would be to
2956 // use the technique that EarlyCSE uses.
2957 inst_iterator Current = llvm::prior(I);
2958 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
2959 for (BasicBlock::iterator B = CurrentBB->begin(),
2960 J = Current.getInstructionIterator();
2962 Instruction *EarlierInst = &*llvm::prior(J);
2963 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
2964 switch (EarlierClass) {
2966 case IC_LoadWeakRetained: {
2967 // If this is loading from the same pointer, replace this load's value
2969 CallInst *Call = cast<CallInst>(Inst);
2970 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2971 Value *Arg = Call->getArgOperand(0);
2972 Value *EarlierArg = EarlierCall->getArgOperand(0);
2973 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2974 case AliasAnalysis::MustAlias:
2976 // If the load has a builtin retain, insert a plain retain for it.
2977 if (Class == IC_LoadWeakRetained) {
2979 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
2983 // Zap the fully redundant load.
2984 Call->replaceAllUsesWith(EarlierCall);
2985 Call->eraseFromParent();
2987 case AliasAnalysis::MayAlias:
2988 case AliasAnalysis::PartialAlias:
2990 case AliasAnalysis::NoAlias:
2997 // If this is storing to the same pointer and has the same size etc.
2998 // replace this load's value with the stored value.
2999 CallInst *Call = cast<CallInst>(Inst);
3000 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3001 Value *Arg = Call->getArgOperand(0);
3002 Value *EarlierArg = EarlierCall->getArgOperand(0);
3003 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3004 case AliasAnalysis::MustAlias:
3006 // If the load has a builtin retain, insert a plain retain for it.
3007 if (Class == IC_LoadWeakRetained) {
3009 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3013 // Zap the fully redundant load.
3014 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
3015 Call->eraseFromParent();
3017 case AliasAnalysis::MayAlias:
3018 case AliasAnalysis::PartialAlias:
3020 case AliasAnalysis::NoAlias:
3027 // TOOD: Grab the copied value.
3029 case IC_AutoreleasepoolPush:
3032 // Weak pointers are only modified through the weak entry points
3033 // (and arbitrary calls, which could call the weak entry points).
3036 // Anything else could modify the weak pointer.
3043 // Then, for each destroyWeak with an alloca operand, check to see if
3044 // the alloca and all its users can be zapped.
3045 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3046 Instruction *Inst = &*I++;
3047 InstructionClass Class = GetBasicInstructionClass(Inst);
3048 if (Class != IC_DestroyWeak)
3051 CallInst *Call = cast<CallInst>(Inst);
3052 Value *Arg = Call->getArgOperand(0);
3053 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
3054 for (Value::use_iterator UI = Alloca->use_begin(),
3055 UE = Alloca->use_end(); UI != UE; ++UI) {
3056 Instruction *UserInst = cast<Instruction>(*UI);
3057 switch (GetBasicInstructionClass(UserInst)) {
3060 case IC_DestroyWeak:
3067 for (Value::use_iterator UI = Alloca->use_begin(),
3068 UE = Alloca->use_end(); UI != UE; ) {
3069 CallInst *UserInst = cast<CallInst>(*UI++);
3070 if (!UserInst->use_empty())
3071 UserInst->replaceAllUsesWith(UserInst->getOperand(1));
3072 UserInst->eraseFromParent();
3074 Alloca->eraseFromParent();
3080 /// OptimizeSequences - Identify program paths which execute sequences of
3081 /// retains and releases which can be eliminated.
3082 bool ObjCARCOpt::OptimizeSequences(Function &F) {
3083 /// Releases, Retains - These are used to store the results of the main flow
3084 /// analysis. These use Value* as the key instead of Instruction* so that the
3085 /// map stays valid when we get around to rewriting code and calls get
3086 /// replaced by arguments.
3087 DenseMap<Value *, RRInfo> Releases;
3088 MapVector<Value *, RRInfo> Retains;
3090 /// BBStates, This is used during the traversal of the function to track the
3091 /// states for each identified object at each block.
3092 DenseMap<const BasicBlock *, BBState> BBStates;
3094 // Analyze the CFG of the function, and all instructions.
3095 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
3098 return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) &&
3102 /// OptimizeReturns - Look for this pattern:
3104 /// %call = call i8* @something(...)
3105 /// %2 = call i8* @objc_retain(i8* %call)
3106 /// %3 = call i8* @objc_autorelease(i8* %2)
3109 /// And delete the retain and autorelease.
3111 /// Otherwise if it's just this:
3113 /// %3 = call i8* @objc_autorelease(i8* %2)
3116 /// convert the autorelease to autoreleaseRV.
3117 void ObjCARCOpt::OptimizeReturns(Function &F) {
3118 if (!F.getReturnType()->isPointerTy())
3121 SmallPtrSet<Instruction *, 4> DependingInstructions;
3122 SmallPtrSet<const BasicBlock *, 4> Visited;
3123 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3124 BasicBlock *BB = FI;
3125 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
3128 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
3129 FindDependencies(NeedsPositiveRetainCount, Arg,
3130 BB, Ret, DependingInstructions, Visited, PA);
3131 if (DependingInstructions.size() != 1)
3135 CallInst *Autorelease =
3136 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3139 InstructionClass AutoreleaseClass =
3140 GetBasicInstructionClass(Autorelease);
3141 if (!IsAutorelease(AutoreleaseClass))
3143 if (GetObjCArg(Autorelease) != Arg)
3146 DependingInstructions.clear();
3149 // Check that there is nothing that can affect the reference
3150 // count between the autorelease and the retain.
3151 FindDependencies(CanChangeRetainCount, Arg,
3152 BB, Autorelease, DependingInstructions, Visited, PA);
3153 if (DependingInstructions.size() != 1)
3158 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3160 // Check that we found a retain with the same argument.
3162 !IsRetain(GetBasicInstructionClass(Retain)) ||
3163 GetObjCArg(Retain) != Arg)
3166 DependingInstructions.clear();
3169 // Convert the autorelease to an autoreleaseRV, since it's
3170 // returning the value.
3171 if (AutoreleaseClass == IC_Autorelease) {
3172 Autorelease->setCalledFunction(getAutoreleaseRVCallee(F.getParent()));
3173 AutoreleaseClass = IC_AutoreleaseRV;
3176 // Check that there is nothing that can affect the reference
3177 // count between the retain and the call.
3178 FindDependencies(CanChangeRetainCount, Arg, BB, Retain,
3179 DependingInstructions, Visited, PA);
3180 if (DependingInstructions.size() != 1)
3185 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3187 // Check that the pointer is the return value of the call.
3188 if (!Call || Arg != Call)
3191 // Check that the call is a regular call.
3192 InstructionClass Class = GetBasicInstructionClass(Call);
3193 if (Class != IC_CallOrUser && Class != IC_Call)
3196 // If so, we can zap the retain and autorelease.
3199 EraseInstruction(Retain);
3200 EraseInstruction(Autorelease);
3206 DependingInstructions.clear();
3211 bool ObjCARCOpt::doInitialization(Module &M) {
3215 Run = ModuleHasARC(M);
3219 // Identify the imprecise release metadata kind.
3220 ImpreciseReleaseMDKind =
3221 M.getContext().getMDKindID("clang.imprecise_release");
3223 // Intuitively, objc_retain and others are nocapture, however in practice
3224 // they are not, because they return their argument value. And objc_release
3225 // calls finalizers.
3227 // These are initialized lazily.
3229 AutoreleaseRVCallee = 0;
3232 RetainBlockCallee = 0;
3233 AutoreleaseCallee = 0;
3238 bool ObjCARCOpt::runOnFunction(Function &F) {
3242 // If nothing in the Module uses ARC, don't do anything.
3248 PA.setAA(&getAnalysis<AliasAnalysis>());
3250 // This pass performs several distinct transformations. As a compile-time aid
3251 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3252 // library functions aren't declared.
3254 // Preliminary optimizations. This also computs UsedInThisFunction.
3255 OptimizeIndividualCalls(F);
3257 // Optimizations for weak pointers.
3258 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3259 (1 << IC_LoadWeakRetained) |
3260 (1 << IC_StoreWeak) |
3261 (1 << IC_InitWeak) |
3262 (1 << IC_CopyWeak) |
3263 (1 << IC_MoveWeak) |
3264 (1 << IC_DestroyWeak)))
3265 OptimizeWeakCalls(F);
3267 // Optimizations for retain+release pairs.
3268 if (UsedInThisFunction & ((1 << IC_Retain) |
3269 (1 << IC_RetainRV) |
3270 (1 << IC_RetainBlock)))
3271 if (UsedInThisFunction & (1 << IC_Release))
3272 // Run OptimizeSequences until it either stops making changes or
3273 // no retain+release pair nesting is detected.
3274 while (OptimizeSequences(F)) {}
3276 // Optimizations if objc_autorelease is used.
3277 if (UsedInThisFunction &
3278 ((1 << IC_Autorelease) | (1 << IC_AutoreleaseRV)))
3284 void ObjCARCOpt::releaseMemory() {
3288 //===----------------------------------------------------------------------===//
3290 //===----------------------------------------------------------------------===//
3292 // TODO: ObjCARCContract could insert PHI nodes when uses aren't
3293 // dominated by single calls.
3295 #include "llvm/Operator.h"
3296 #include "llvm/InlineAsm.h"
3297 #include "llvm/Analysis/Dominators.h"
3299 STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed");
3302 /// ObjCARCContract - Late ARC optimizations. These change the IR in a way
3303 /// that makes it difficult to be analyzed by ObjCARCOpt, so it's run late.
3304 class ObjCARCContract : public FunctionPass {
3308 ProvenanceAnalysis PA;
3310 /// Run - A flag indicating whether this optimization pass should run.
3313 /// StoreStrongCallee, etc. - Declarations for ObjC runtime
3314 /// functions, for use in creating calls to them. These are initialized
3315 /// lazily to avoid cluttering up the Module with unused declarations.
3316 Constant *StoreStrongCallee,
3317 *RetainAutoreleaseCallee, *RetainAutoreleaseRVCallee;
3319 /// RetainRVMarker - The inline asm string to insert between calls and
3320 /// RetainRV calls to make the optimization work on targets which need it.
3321 const MDString *RetainRVMarker;
3323 Constant *getStoreStrongCallee(Module *M);
3324 Constant *getRetainAutoreleaseCallee(Module *M);
3325 Constant *getRetainAutoreleaseRVCallee(Module *M);
3327 bool ContractAutorelease(Function &F, Instruction *Autorelease,
3328 InstructionClass Class,
3329 SmallPtrSet<Instruction *, 4>
3330 &DependingInstructions,
3331 SmallPtrSet<const BasicBlock *, 4>
3334 void ContractRelease(Instruction *Release,
3335 inst_iterator &Iter);
3337 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
3338 virtual bool doInitialization(Module &M);
3339 virtual bool runOnFunction(Function &F);
3343 ObjCARCContract() : FunctionPass(ID) {
3344 initializeObjCARCContractPass(*PassRegistry::getPassRegistry());
3349 char ObjCARCContract::ID = 0;
3350 INITIALIZE_PASS_BEGIN(ObjCARCContract,
3351 "objc-arc-contract", "ObjC ARC contraction", false, false)
3352 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3353 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
3354 INITIALIZE_PASS_END(ObjCARCContract,
3355 "objc-arc-contract", "ObjC ARC contraction", false, false)
3357 Pass *llvm::createObjCARCContractPass() {
3358 return new ObjCARCContract();
3361 void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const {
3362 AU.addRequired<AliasAnalysis>();
3363 AU.addRequired<DominatorTree>();
3364 AU.setPreservesCFG();
3367 Constant *ObjCARCContract::getStoreStrongCallee(Module *M) {
3368 if (!StoreStrongCallee) {
3369 LLVMContext &C = M->getContext();
3370 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3371 Type *I8XX = PointerType::getUnqual(I8X);
3372 std::vector<Type *> Params;
3373 Params.push_back(I8XX);
3374 Params.push_back(I8X);
3376 AttrListPtr Attributes;
3377 Attributes.addAttr(~0u, Attribute::NoUnwind);
3378 Attributes.addAttr(1, Attribute::NoCapture);
3381 M->getOrInsertFunction(
3383 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
3386 return StoreStrongCallee;
3389 Constant *ObjCARCContract::getRetainAutoreleaseCallee(Module *M) {
3390 if (!RetainAutoreleaseCallee) {
3391 LLVMContext &C = M->getContext();
3392 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3393 std::vector<Type *> Params;
3394 Params.push_back(I8X);
3396 FunctionType::get(I8X, Params, /*isVarArg=*/false);
3397 AttrListPtr Attributes;
3398 Attributes.addAttr(~0u, Attribute::NoUnwind);
3399 RetainAutoreleaseCallee =
3400 M->getOrInsertFunction("objc_retainAutorelease", FTy, Attributes);
3402 return RetainAutoreleaseCallee;
3405 Constant *ObjCARCContract::getRetainAutoreleaseRVCallee(Module *M) {
3406 if (!RetainAutoreleaseRVCallee) {
3407 LLVMContext &C = M->getContext();
3408 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3409 std::vector<Type *> Params;
3410 Params.push_back(I8X);
3412 FunctionType::get(I8X, Params, /*isVarArg=*/false);
3413 AttrListPtr Attributes;
3414 Attributes.addAttr(~0u, Attribute::NoUnwind);
3415 RetainAutoreleaseRVCallee =
3416 M->getOrInsertFunction("objc_retainAutoreleaseReturnValue", FTy,
3419 return RetainAutoreleaseRVCallee;
3422 /// ContractAutorelease - Merge an autorelease with a retain into a fused
3425 ObjCARCContract::ContractAutorelease(Function &F, Instruction *Autorelease,
3426 InstructionClass Class,
3427 SmallPtrSet<Instruction *, 4>
3428 &DependingInstructions,
3429 SmallPtrSet<const BasicBlock *, 4>
3431 const Value *Arg = GetObjCArg(Autorelease);
3433 // Check that there are no instructions between the retain and the autorelease
3434 // (such as an autorelease_pop) which may change the count.
3435 CallInst *Retain = 0;
3436 if (Class == IC_AutoreleaseRV)
3437 FindDependencies(RetainAutoreleaseRVDep, Arg,
3438 Autorelease->getParent(), Autorelease,
3439 DependingInstructions, Visited, PA);
3441 FindDependencies(RetainAutoreleaseDep, Arg,
3442 Autorelease->getParent(), Autorelease,
3443 DependingInstructions, Visited, PA);
3446 if (DependingInstructions.size() != 1) {
3447 DependingInstructions.clear();
3451 Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3452 DependingInstructions.clear();
3455 GetBasicInstructionClass(Retain) != IC_Retain ||
3456 GetObjCArg(Retain) != Arg)
3462 if (Class == IC_AutoreleaseRV)
3463 Retain->setCalledFunction(getRetainAutoreleaseRVCallee(F.getParent()));
3465 Retain->setCalledFunction(getRetainAutoreleaseCallee(F.getParent()));
3467 EraseInstruction(Autorelease);
3471 /// ContractRelease - Attempt to merge an objc_release with a store, load, and
3472 /// objc_retain to form an objc_storeStrong. This can be a little tricky because
3473 /// the instructions don't always appear in order, and there may be unrelated
3474 /// intervening instructions.
3475 void ObjCARCContract::ContractRelease(Instruction *Release,
3476 inst_iterator &Iter) {
3477 LoadInst *Load = dyn_cast<LoadInst>(GetObjCArg(Release));
3478 if (!Load || !Load->isSimple()) return;
3480 // For now, require everything to be in one basic block.
3481 BasicBlock *BB = Release->getParent();
3482 if (Load->getParent() != BB) return;
3484 // Walk down to find the store.
3485 BasicBlock::iterator I = Load, End = BB->end();
3487 AliasAnalysis::Location Loc = AA->getLocation(Load);
3490 IsRetain(GetBasicInstructionClass(I)) ||
3491 !(AA->getModRefInfo(I, Loc) & AliasAnalysis::Mod)))
3493 StoreInst *Store = dyn_cast<StoreInst>(I);
3494 if (!Store || !Store->isSimple()) return;
3495 if (Store->getPointerOperand() != Loc.Ptr) return;
3497 Value *New = StripPointerCastsAndObjCCalls(Store->getValueOperand());
3499 // Walk up to find the retain.
3501 BasicBlock::iterator Begin = BB->begin();
3502 while (I != Begin && GetBasicInstructionClass(I) != IC_Retain)
3504 Instruction *Retain = I;
3505 if (GetBasicInstructionClass(Retain) != IC_Retain) return;
3506 if (GetObjCArg(Retain) != New) return;
3511 LLVMContext &C = Release->getContext();
3512 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3513 Type *I8XX = PointerType::getUnqual(I8X);
3515 Value *Args[] = { Load->getPointerOperand(), New };
3516 if (Args[0]->getType() != I8XX)
3517 Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
3518 if (Args[1]->getType() != I8X)
3519 Args[1] = new BitCastInst(Args[1], I8X, "", Store);
3520 CallInst *StoreStrong =
3521 CallInst::Create(getStoreStrongCallee(BB->getParent()->getParent()),
3523 StoreStrong->setDoesNotThrow();
3524 StoreStrong->setDebugLoc(Store->getDebugLoc());
3526 if (&*Iter == Store) ++Iter;
3527 Store->eraseFromParent();
3528 Release->eraseFromParent();
3529 EraseInstruction(Retain);
3530 if (Load->use_empty())
3531 Load->eraseFromParent();
3534 bool ObjCARCContract::doInitialization(Module &M) {
3535 Run = ModuleHasARC(M);
3539 // These are initialized lazily.
3540 StoreStrongCallee = 0;
3541 RetainAutoreleaseCallee = 0;
3542 RetainAutoreleaseRVCallee = 0;
3544 // Initialize RetainRVMarker.
3546 if (NamedMDNode *NMD =
3547 M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker"))
3548 if (NMD->getNumOperands() == 1) {
3549 const MDNode *N = NMD->getOperand(0);
3550 if (N->getNumOperands() == 1)
3551 if (const MDString *S = dyn_cast<MDString>(N->getOperand(0)))
3558 bool ObjCARCContract::runOnFunction(Function &F) {
3562 // If nothing in the Module uses ARC, don't do anything.
3567 AA = &getAnalysis<AliasAnalysis>();
3568 DT = &getAnalysis<DominatorTree>();
3570 PA.setAA(&getAnalysis<AliasAnalysis>());
3572 // For ObjC library calls which return their argument, replace uses of the
3573 // argument with uses of the call return value, if it dominates the use. This
3574 // reduces register pressure.
3575 SmallPtrSet<Instruction *, 4> DependingInstructions;
3576 SmallPtrSet<const BasicBlock *, 4> Visited;
3577 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3578 Instruction *Inst = &*I++;
3580 // Only these library routines return their argument. In particular,
3581 // objc_retainBlock does not necessarily return its argument.
3582 InstructionClass Class = GetBasicInstructionClass(Inst);
3585 case IC_FusedRetainAutorelease:
3586 case IC_FusedRetainAutoreleaseRV:
3588 case IC_Autorelease:
3589 case IC_AutoreleaseRV:
3590 if (ContractAutorelease(F, Inst, Class, DependingInstructions, Visited))
3594 // If we're compiling for a target which needs a special inline-asm
3595 // marker to do the retainAutoreleasedReturnValue optimization,
3597 if (!RetainRVMarker)
3599 BasicBlock::iterator BBI = Inst;
3601 while (isNoopInstruction(BBI)) --BBI;
3602 if (&*BBI == GetObjCArg(Inst)) {
3604 InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()),
3605 /*isVarArg=*/false),
3606 RetainRVMarker->getString(),
3607 /*Constraints=*/"", /*hasSideEffects=*/true);
3608 CallInst::Create(IA, "", Inst);
3613 // objc_initWeak(p, null) => *p = null
3614 CallInst *CI = cast<CallInst>(Inst);
3615 if (isNullOrUndef(CI->getArgOperand(1))) {
3617 ConstantPointerNull::get(cast<PointerType>(CI->getType()));
3619 new StoreInst(Null, CI->getArgOperand(0), CI);
3620 CI->replaceAllUsesWith(Null);
3621 CI->eraseFromParent();
3626 ContractRelease(Inst, I);
3632 // Don't use GetObjCArg because we don't want to look through bitcasts
3633 // and such; to do the replacement, the argument must have type i8*.
3634 const Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
3636 // If we're compiling bugpointed code, don't get in trouble.
3637 if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
3639 // Look through the uses of the pointer.
3640 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
3642 Use &U = UI.getUse();
3643 unsigned OperandNo = UI.getOperandNo();
3644 ++UI; // Increment UI now, because we may unlink its element.
3645 if (Instruction *UserInst = dyn_cast<Instruction>(U.getUser()))
3646 if (Inst != UserInst && DT->dominates(Inst, UserInst)) {
3648 Instruction *Replacement = Inst;
3649 Type *UseTy = U.get()->getType();
3650 if (PHINode *PHI = dyn_cast<PHINode>(UserInst)) {
3651 // For PHI nodes, insert the bitcast in the predecessor block.
3653 PHINode::getIncomingValueNumForOperand(OperandNo);
3655 PHI->getIncomingBlock(ValNo);
3656 if (Replacement->getType() != UseTy)
3657 Replacement = new BitCastInst(Replacement, UseTy, "",
3659 for (unsigned i = 0, e = PHI->getNumIncomingValues();
3661 if (PHI->getIncomingBlock(i) == BB) {
3662 // Keep the UI iterator valid.
3663 if (&PHI->getOperandUse(
3664 PHINode::getOperandNumForIncomingValue(i)) ==
3667 PHI->setIncomingValue(i, Replacement);
3670 if (Replacement->getType() != UseTy)
3671 Replacement = new BitCastInst(Replacement, UseTy, "", UserInst);
3677 // If Arg is a no-op casted pointer, strip one level of casts and
3679 if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
3680 Arg = BI->getOperand(0);
3681 else if (isa<GEPOperator>(Arg) &&
3682 cast<GEPOperator>(Arg)->hasAllZeroIndices())
3683 Arg = cast<GEPOperator>(Arg)->getPointerOperand();
3684 else if (isa<GlobalAlias>(Arg) &&
3685 !cast<GlobalAlias>(Arg)->mayBeOverridden())
3686 Arg = cast<GlobalAlias>(Arg)->getAliasee();