Changed SmallPtrSet.count guard + SmallPtrSet.insert to just SmallPtrSet.insert.
[oota-llvm.git] / lib / Transforms / Scalar / ObjCARC.cpp
1 //===- ObjCARC.cpp - ObjC ARC Optimization --------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 /// \file
10 /// This file defines ObjC ARC optimizations. ARC stands for Automatic
11 /// Reference Counting and is a system for managing reference counts for objects
12 /// in Objective C.
13 ///
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
18 /// simplifications.
19 ///
20 /// This file also defines a simple ARC-aware AliasAnalysis.
21 ///
22 /// WARNING: This file knows about certain library functions. It recognizes them
23 /// by name, and hardwires knowledge of their semantics.
24 ///
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.
28 ///
29 //===----------------------------------------------------------------------===//
30
31 #define DEBUG_TYPE "objc-arc"
32 #include "llvm/ADT/DenseMap.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/raw_ostream.h"
37 using namespace llvm;
38
39 /// \brief A handy option to enable/disable all optimizations in this file.
40 static cl::opt<bool> EnableARCOpts("enable-objc-arc-opts", cl::init(true));
41
42 /// \defgroup MiscUtils Miscellaneous utilities that are not ARC specific.
43 /// @{
44
45 namespace {
46   /// \brief An associative container with fast insertion-order (deterministic)
47   /// iteration over its elements. Plus the special blot operation.
48   template<class KeyT, class ValueT>
49   class MapVector {
50     /// Map keys to indices in Vector.
51     typedef DenseMap<KeyT, size_t> MapTy;
52     MapTy Map;
53
54     typedef std::vector<std::pair<KeyT, ValueT> > VectorTy;
55     /// Keys and values.
56     VectorTy Vector;
57
58   public:
59     typedef typename VectorTy::iterator iterator;
60     typedef typename VectorTy::const_iterator const_iterator;
61     iterator begin() { return Vector.begin(); }
62     iterator end() { return Vector.end(); }
63     const_iterator begin() const { return Vector.begin(); }
64     const_iterator end() const { return Vector.end(); }
65
66 #ifdef XDEBUG
67     ~MapVector() {
68       assert(Vector.size() >= Map.size()); // May differ due to blotting.
69       for (typename MapTy::const_iterator I = Map.begin(), E = Map.end();
70            I != E; ++I) {
71         assert(I->second < Vector.size());
72         assert(Vector[I->second].first == I->first);
73       }
74       for (typename VectorTy::const_iterator I = Vector.begin(),
75            E = Vector.end(); I != E; ++I)
76         assert(!I->first ||
77                (Map.count(I->first) &&
78                 Map[I->first] == size_t(I - Vector.begin())));
79     }
80 #endif
81
82     ValueT &operator[](const KeyT &Arg) {
83       std::pair<typename MapTy::iterator, bool> Pair =
84         Map.insert(std::make_pair(Arg, size_t(0)));
85       if (Pair.second) {
86         size_t Num = Vector.size();
87         Pair.first->second = Num;
88         Vector.push_back(std::make_pair(Arg, ValueT()));
89         return Vector[Num].second;
90       }
91       return Vector[Pair.first->second].second;
92     }
93
94     std::pair<iterator, bool>
95     insert(const std::pair<KeyT, ValueT> &InsertPair) {
96       std::pair<typename MapTy::iterator, bool> Pair =
97         Map.insert(std::make_pair(InsertPair.first, size_t(0)));
98       if (Pair.second) {
99         size_t Num = Vector.size();
100         Pair.first->second = Num;
101         Vector.push_back(InsertPair);
102         return std::make_pair(Vector.begin() + Num, true);
103       }
104       return std::make_pair(Vector.begin() + Pair.first->second, false);
105     }
106
107     const_iterator find(const KeyT &Key) const {
108       typename MapTy::const_iterator It = Map.find(Key);
109       if (It == Map.end()) return Vector.end();
110       return Vector.begin() + It->second;
111     }
112
113     /// This is similar to erase, but instead of removing the element from the
114     /// vector, it just zeros out the key in the vector. This leaves iterators
115     /// intact, but clients must be prepared for zeroed-out keys when iterating.
116     void blot(const KeyT &Key) {
117       typename MapTy::iterator It = Map.find(Key);
118       if (It == Map.end()) return;
119       Vector[It->second].first = KeyT();
120       Map.erase(It);
121     }
122
123     void clear() {
124       Map.clear();
125       Vector.clear();
126     }
127   };
128 }
129
130 /// @}
131 ///
132 /// \defgroup ARCUtilities Utility declarations/definitions specific to ARC.
133 /// @{
134
135 #include "llvm/ADT/StringSwitch.h"
136 #include "llvm/Analysis/ValueTracking.h"
137 #include "llvm/IR/Intrinsics.h"
138 #include "llvm/IR/Module.h"
139 #include "llvm/Support/CallSite.h"
140 #include "llvm/Transforms/Utils/Local.h"
141
142 namespace {
143   /// \enum InstructionClass
144   /// \brief A simple classification for instructions.
145   enum InstructionClass {
146     IC_Retain,              ///< objc_retain
147     IC_RetainRV,            ///< objc_retainAutoreleasedReturnValue
148     IC_RetainBlock,         ///< objc_retainBlock
149     IC_Release,             ///< objc_release
150     IC_Autorelease,         ///< objc_autorelease
151     IC_AutoreleaseRV,       ///< objc_autoreleaseReturnValue
152     IC_AutoreleasepoolPush, ///< objc_autoreleasePoolPush
153     IC_AutoreleasepoolPop,  ///< objc_autoreleasePoolPop
154     IC_NoopCast,            ///< objc_retainedObject, etc.
155     IC_FusedRetainAutorelease, ///< objc_retainAutorelease
156     IC_FusedRetainAutoreleaseRV, ///< objc_retainAutoreleaseReturnValue
157     IC_LoadWeakRetained,    ///< objc_loadWeakRetained (primitive)
158     IC_StoreWeak,           ///< objc_storeWeak (primitive)
159     IC_InitWeak,            ///< objc_initWeak (derived)
160     IC_LoadWeak,            ///< objc_loadWeak (derived)
161     IC_MoveWeak,            ///< objc_moveWeak (derived)
162     IC_CopyWeak,            ///< objc_copyWeak (derived)
163     IC_DestroyWeak,         ///< objc_destroyWeak (derived)
164     IC_StoreStrong,         ///< objc_storeStrong (derived)
165     IC_CallOrUser,          ///< could call objc_release and/or "use" pointers
166     IC_Call,                ///< could call objc_release
167     IC_User,                ///< could "use" a pointer
168     IC_None                 ///< anything else
169   };
170 }
171
172 /// \brief Test whether the given value is possible a reference-counted pointer.
173 static bool IsPotentialUse(const Value *Op) {
174   // Pointers to static or stack storage are not reference-counted pointers.
175   if (isa<Constant>(Op) || isa<AllocaInst>(Op))
176     return false;
177   // Special arguments are not reference-counted.
178   if (const Argument *Arg = dyn_cast<Argument>(Op))
179     if (Arg->hasByValAttr() ||
180         Arg->hasNestAttr() ||
181         Arg->hasStructRetAttr())
182       return false;
183   // Only consider values with pointer types.
184   // It seemes intuitive to exclude function pointer types as well, since
185   // functions are never reference-counted, however clang occasionally
186   // bitcasts reference-counted pointers to function-pointer type
187   // temporarily.
188   PointerType *Ty = dyn_cast<PointerType>(Op->getType());
189   if (!Ty)
190     return false;
191   // Conservatively assume anything else is a potential use.
192   return true;
193 }
194
195 /// \brief Helper for GetInstructionClass. Determines what kind of construct CS
196 /// is.
197 static InstructionClass GetCallSiteClass(ImmutableCallSite CS) {
198   for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
199        I != E; ++I)
200     if (IsPotentialUse(*I))
201       return CS.onlyReadsMemory() ? IC_User : IC_CallOrUser;
202
203   return CS.onlyReadsMemory() ? IC_None : IC_Call;
204 }
205
206 /// \brief Determine if F is one of the special known Functions.  If it isn't,
207 /// return IC_CallOrUser.
208 static InstructionClass GetFunctionClass(const Function *F) {
209   Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
210
211   // No arguments.
212   if (AI == AE)
213     return StringSwitch<InstructionClass>(F->getName())
214       .Case("objc_autoreleasePoolPush",  IC_AutoreleasepoolPush)
215       .Default(IC_CallOrUser);
216
217   // One argument.
218   const Argument *A0 = AI++;
219   if (AI == AE)
220     // Argument is a pointer.
221     if (PointerType *PTy = dyn_cast<PointerType>(A0->getType())) {
222       Type *ETy = PTy->getElementType();
223       // Argument is i8*.
224       if (ETy->isIntegerTy(8))
225         return StringSwitch<InstructionClass>(F->getName())
226           .Case("objc_retain",                IC_Retain)
227           .Case("objc_retainAutoreleasedReturnValue", IC_RetainRV)
228           .Case("objc_retainBlock",           IC_RetainBlock)
229           .Case("objc_release",               IC_Release)
230           .Case("objc_autorelease",           IC_Autorelease)
231           .Case("objc_autoreleaseReturnValue", IC_AutoreleaseRV)
232           .Case("objc_autoreleasePoolPop",    IC_AutoreleasepoolPop)
233           .Case("objc_retainedObject",        IC_NoopCast)
234           .Case("objc_unretainedObject",      IC_NoopCast)
235           .Case("objc_unretainedPointer",     IC_NoopCast)
236           .Case("objc_retain_autorelease",    IC_FusedRetainAutorelease)
237           .Case("objc_retainAutorelease",     IC_FusedRetainAutorelease)
238           .Case("objc_retainAutoreleaseReturnValue",IC_FusedRetainAutoreleaseRV)
239           .Default(IC_CallOrUser);
240
241       // Argument is i8**
242       if (PointerType *Pte = dyn_cast<PointerType>(ETy))
243         if (Pte->getElementType()->isIntegerTy(8))
244           return StringSwitch<InstructionClass>(F->getName())
245             .Case("objc_loadWeakRetained",      IC_LoadWeakRetained)
246             .Case("objc_loadWeak",              IC_LoadWeak)
247             .Case("objc_destroyWeak",           IC_DestroyWeak)
248             .Default(IC_CallOrUser);
249     }
250
251   // Two arguments, first is i8**.
252   const Argument *A1 = AI++;
253   if (AI == AE)
254     if (PointerType *PTy = dyn_cast<PointerType>(A0->getType()))
255       if (PointerType *Pte = dyn_cast<PointerType>(PTy->getElementType()))
256         if (Pte->getElementType()->isIntegerTy(8))
257           if (PointerType *PTy1 = dyn_cast<PointerType>(A1->getType())) {
258             Type *ETy1 = PTy1->getElementType();
259             // Second argument is i8*
260             if (ETy1->isIntegerTy(8))
261               return StringSwitch<InstructionClass>(F->getName())
262                      .Case("objc_storeWeak",             IC_StoreWeak)
263                      .Case("objc_initWeak",              IC_InitWeak)
264                      .Case("objc_storeStrong",           IC_StoreStrong)
265                      .Default(IC_CallOrUser);
266             // Second argument is i8**.
267             if (PointerType *Pte1 = dyn_cast<PointerType>(ETy1))
268               if (Pte1->getElementType()->isIntegerTy(8))
269                 return StringSwitch<InstructionClass>(F->getName())
270                        .Case("objc_moveWeak",              IC_MoveWeak)
271                        .Case("objc_copyWeak",              IC_CopyWeak)
272                        .Default(IC_CallOrUser);
273           }
274
275   // Anything else.
276   return IC_CallOrUser;
277 }
278
279 /// \brief Determine what kind of construct V is.
280 static InstructionClass GetInstructionClass(const Value *V) {
281   if (const Instruction *I = dyn_cast<Instruction>(V)) {
282     // Any instruction other than bitcast and gep with a pointer operand have a
283     // use of an objc pointer. Bitcasts, GEPs, Selects, PHIs transfer a pointer
284     // to a subsequent use, rather than using it themselves, in this sense.
285     // As a short cut, several other opcodes are known to have no pointer
286     // operands of interest. And ret is never followed by a release, so it's
287     // not interesting to examine.
288     switch (I->getOpcode()) {
289     case Instruction::Call: {
290       const CallInst *CI = cast<CallInst>(I);
291       // Check for calls to special functions.
292       if (const Function *F = CI->getCalledFunction()) {
293         InstructionClass Class = GetFunctionClass(F);
294         if (Class != IC_CallOrUser)
295           return Class;
296
297         // None of the intrinsic functions do objc_release. For intrinsics, the
298         // only question is whether or not they may be users.
299         switch (F->getIntrinsicID()) {
300         case Intrinsic::returnaddress: case Intrinsic::frameaddress:
301         case Intrinsic::stacksave: case Intrinsic::stackrestore:
302         case Intrinsic::vastart: case Intrinsic::vacopy: case Intrinsic::vaend:
303         case Intrinsic::objectsize: case Intrinsic::prefetch:
304         case Intrinsic::stackprotector:
305         case Intrinsic::eh_return_i32: case Intrinsic::eh_return_i64:
306         case Intrinsic::eh_typeid_for: case Intrinsic::eh_dwarf_cfa:
307         case Intrinsic::eh_sjlj_lsda: case Intrinsic::eh_sjlj_functioncontext:
308         case Intrinsic::init_trampoline: case Intrinsic::adjust_trampoline:
309         case Intrinsic::lifetime_start: case Intrinsic::lifetime_end:
310         case Intrinsic::invariant_start: case Intrinsic::invariant_end:
311         // Don't let dbg info affect our results.
312         case Intrinsic::dbg_declare: case Intrinsic::dbg_value:
313           // Short cut: Some intrinsics obviously don't use ObjC pointers.
314           return IC_None;
315         default:
316           break;
317         }
318       }
319       return GetCallSiteClass(CI);
320     }
321     case Instruction::Invoke:
322       return GetCallSiteClass(cast<InvokeInst>(I));
323     case Instruction::BitCast:
324     case Instruction::GetElementPtr:
325     case Instruction::Select: case Instruction::PHI:
326     case Instruction::Ret: case Instruction::Br:
327     case Instruction::Switch: case Instruction::IndirectBr:
328     case Instruction::Alloca: case Instruction::VAArg:
329     case Instruction::Add: case Instruction::FAdd:
330     case Instruction::Sub: case Instruction::FSub:
331     case Instruction::Mul: case Instruction::FMul:
332     case Instruction::SDiv: case Instruction::UDiv: case Instruction::FDiv:
333     case Instruction::SRem: case Instruction::URem: case Instruction::FRem:
334     case Instruction::Shl: case Instruction::LShr: case Instruction::AShr:
335     case Instruction::And: case Instruction::Or: case Instruction::Xor:
336     case Instruction::SExt: case Instruction::ZExt: case Instruction::Trunc:
337     case Instruction::IntToPtr: case Instruction::FCmp:
338     case Instruction::FPTrunc: case Instruction::FPExt:
339     case Instruction::FPToUI: case Instruction::FPToSI:
340     case Instruction::UIToFP: case Instruction::SIToFP:
341     case Instruction::InsertElement: case Instruction::ExtractElement:
342     case Instruction::ShuffleVector:
343     case Instruction::ExtractValue:
344       break;
345     case Instruction::ICmp:
346       // Comparing a pointer with null, or any other constant, isn't an
347       // interesting use, because we don't care what the pointer points to, or
348       // about the values of any other dynamic reference-counted pointers.
349       if (IsPotentialUse(I->getOperand(1)))
350         return IC_User;
351       break;
352     default:
353       // For anything else, check all the operands.
354       // Note that this includes both operands of a Store: while the first
355       // operand isn't actually being dereferenced, it is being stored to
356       // memory where we can no longer track who might read it and dereference
357       // it, so we have to consider it potentially used.
358       for (User::const_op_iterator OI = I->op_begin(), OE = I->op_end();
359            OI != OE; ++OI)
360         if (IsPotentialUse(*OI))
361           return IC_User;
362     }
363   }
364
365   // Otherwise, it's totally inert for ARC purposes.
366   return IC_None;
367 }
368
369 /// \brief Determine which objc runtime call instruction class V belongs to.
370 ///
371 /// This is similar to GetInstructionClass except that it only detects objc
372 /// runtime calls. This allows it to be faster.
373 ///
374 static InstructionClass GetBasicInstructionClass(const Value *V) {
375   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
376     if (const Function *F = CI->getCalledFunction())
377       return GetFunctionClass(F);
378     // Otherwise, be conservative.
379     return IC_CallOrUser;
380   }
381
382   // Otherwise, be conservative.
383   return isa<InvokeInst>(V) ? IC_CallOrUser : IC_User;
384 }
385
386 /// \brief Test if the given class is objc_retain or equivalent.
387 static bool IsRetain(InstructionClass Class) {
388   return Class == IC_Retain ||
389          Class == IC_RetainRV;
390 }
391
392 /// \brief Test if the given class is objc_autorelease or equivalent.
393 static bool IsAutorelease(InstructionClass Class) {
394   return Class == IC_Autorelease ||
395          Class == IC_AutoreleaseRV;
396 }
397
398 /// \brief Test if the given class represents instructions which return their
399 /// argument verbatim.
400 static bool IsForwarding(InstructionClass Class) {
401   // objc_retainBlock technically doesn't always return its argument
402   // verbatim, but it doesn't matter for our purposes here.
403   return Class == IC_Retain ||
404          Class == IC_RetainRV ||
405          Class == IC_Autorelease ||
406          Class == IC_AutoreleaseRV ||
407          Class == IC_RetainBlock ||
408          Class == IC_NoopCast;
409 }
410
411 /// \brief Test if the given class represents instructions which do nothing if
412 /// passed a null pointer.
413 static bool IsNoopOnNull(InstructionClass Class) {
414   return Class == IC_Retain ||
415          Class == IC_RetainRV ||
416          Class == IC_Release ||
417          Class == IC_Autorelease ||
418          Class == IC_AutoreleaseRV ||
419          Class == IC_RetainBlock;
420 }
421
422 /// \brief Test if the given class represents instructions which are always safe
423 /// to mark with the "tail" keyword.
424 static bool IsAlwaysTail(InstructionClass Class) {
425   // IC_RetainBlock may be given a stack argument.
426   return Class == IC_Retain ||
427          Class == IC_RetainRV ||
428          Class == IC_AutoreleaseRV;
429 }
430
431 /// \brief Test if the given class represents instructions which are never safe
432 /// to mark with the "tail" keyword.
433 static bool IsNeverTail(InstructionClass Class) {
434   /// It is never safe to tail call objc_autorelease since by tail calling
435   /// objc_autorelease, we also tail call -[NSObject autorelease] which supports
436   /// fast autoreleasing causing our object to be potentially reclaimed from the
437   /// autorelease pool which violates the semantics of __autoreleasing types in
438   /// ARC.
439   return Class == IC_Autorelease;
440 }
441
442 /// \brief Test if the given class represents instructions which are always safe
443 /// to mark with the nounwind attribute.
444 static bool IsNoThrow(InstructionClass Class) {
445   // objc_retainBlock is not nounwind because it calls user copy constructors
446   // which could theoretically throw.
447   return Class == IC_Retain ||
448          Class == IC_RetainRV ||
449          Class == IC_Release ||
450          Class == IC_Autorelease ||
451          Class == IC_AutoreleaseRV ||
452          Class == IC_AutoreleasepoolPush ||
453          Class == IC_AutoreleasepoolPop;
454 }
455
456 /// \brief Erase the given instruction.
457 ///
458 /// Many ObjC calls return their argument verbatim,
459 /// so if it's such a call and the return value has users, replace them with the
460 /// argument value.
461 ///
462 static void EraseInstruction(Instruction *CI) {
463   Value *OldArg = cast<CallInst>(CI)->getArgOperand(0);
464
465   bool Unused = CI->use_empty();
466
467   if (!Unused) {
468     // Replace the return value with the argument.
469     assert(IsForwarding(GetBasicInstructionClass(CI)) &&
470            "Can't delete non-forwarding instruction with users!");
471     CI->replaceAllUsesWith(OldArg);
472   }
473
474   CI->eraseFromParent();
475
476   if (Unused)
477     RecursivelyDeleteTriviallyDeadInstructions(OldArg);
478 }
479
480 /// \brief This is a wrapper around getUnderlyingObject which also knows how to
481 /// look through objc_retain and objc_autorelease calls, which we know to return
482 /// their argument verbatim.
483 static const Value *GetUnderlyingObjCPtr(const Value *V) {
484   for (;;) {
485     V = GetUnderlyingObject(V);
486     if (!IsForwarding(GetBasicInstructionClass(V)))
487       break;
488     V = cast<CallInst>(V)->getArgOperand(0);
489   }
490
491   return V;
492 }
493
494 /// \brief This is a wrapper around Value::stripPointerCasts which also knows
495 /// how to look through objc_retain and objc_autorelease calls, which we know to
496 /// return their argument verbatim.
497 static const Value *StripPointerCastsAndObjCCalls(const Value *V) {
498   for (;;) {
499     V = V->stripPointerCasts();
500     if (!IsForwarding(GetBasicInstructionClass(V)))
501       break;
502     V = cast<CallInst>(V)->getArgOperand(0);
503   }
504   return V;
505 }
506
507 /// \brief This is a wrapper around Value::stripPointerCasts which also knows
508 /// how to look through objc_retain and objc_autorelease calls, which we know to
509 /// return their argument verbatim.
510 static Value *StripPointerCastsAndObjCCalls(Value *V) {
511   for (;;) {
512     V = V->stripPointerCasts();
513     if (!IsForwarding(GetBasicInstructionClass(V)))
514       break;
515     V = cast<CallInst>(V)->getArgOperand(0);
516   }
517   return V;
518 }
519
520 /// \brief Assuming the given instruction is one of the special calls such as
521 /// objc_retain or objc_release, return the argument value, stripped of no-op
522 /// casts and forwarding calls.
523 static Value *GetObjCArg(Value *Inst) {
524   return StripPointerCastsAndObjCCalls(cast<CallInst>(Inst)->getArgOperand(0));
525 }
526
527 /// \brief This is similar to AliasAnalysis's isObjCIdentifiedObject, except
528 /// that it uses special knowledge of ObjC conventions.
529 static bool IsObjCIdentifiedObject(const Value *V) {
530   // Assume that call results and arguments have their own "provenance".
531   // Constants (including GlobalVariables) and Allocas are never
532   // reference-counted.
533   if (isa<CallInst>(V) || isa<InvokeInst>(V) ||
534       isa<Argument>(V) || isa<Constant>(V) ||
535       isa<AllocaInst>(V))
536     return true;
537
538   if (const LoadInst *LI = dyn_cast<LoadInst>(V)) {
539     const Value *Pointer =
540       StripPointerCastsAndObjCCalls(LI->getPointerOperand());
541     if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Pointer)) {
542       // A constant pointer can't be pointing to an object on the heap. It may
543       // be reference-counted, but it won't be deleted.
544       if (GV->isConstant())
545         return true;
546       StringRef Name = GV->getName();
547       // These special variables are known to hold values which are not
548       // reference-counted pointers.
549       if (Name.startswith("\01L_OBJC_SELECTOR_REFERENCES_") ||
550           Name.startswith("\01L_OBJC_CLASSLIST_REFERENCES_") ||
551           Name.startswith("\01L_OBJC_CLASSLIST_SUP_REFS_$_") ||
552           Name.startswith("\01L_OBJC_METH_VAR_NAME_") ||
553           Name.startswith("\01l_objc_msgSend_fixup_"))
554         return true;
555     }
556   }
557
558   return false;
559 }
560
561 /// \brief This is similar to StripPointerCastsAndObjCCalls but it stops as soon
562 /// as it finds a value with multiple uses.
563 static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
564   if (Arg->hasOneUse()) {
565     if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
566       return FindSingleUseIdentifiedObject(BC->getOperand(0));
567     if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
568       if (GEP->hasAllZeroIndices())
569         return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
570     if (IsForwarding(GetBasicInstructionClass(Arg)))
571       return FindSingleUseIdentifiedObject(
572                cast<CallInst>(Arg)->getArgOperand(0));
573     if (!IsObjCIdentifiedObject(Arg))
574       return 0;
575     return Arg;
576   }
577
578   // If we found an identifiable object but it has multiple uses, but they are
579   // trivial uses, we can still consider this to be a single-use value.
580   if (IsObjCIdentifiedObject(Arg)) {
581     for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
582          UI != UE; ++UI) {
583       const User *U = *UI;
584       if (!U->use_empty() || StripPointerCastsAndObjCCalls(U) != Arg)
585          return 0;
586     }
587
588     return Arg;
589   }
590
591   return 0;
592 }
593
594 /// \brief Test if the given module looks interesting to run ARC optimization
595 /// on.
596 static bool ModuleHasARC(const Module &M) {
597   return
598     M.getNamedValue("objc_retain") ||
599     M.getNamedValue("objc_release") ||
600     M.getNamedValue("objc_autorelease") ||
601     M.getNamedValue("objc_retainAutoreleasedReturnValue") ||
602     M.getNamedValue("objc_retainBlock") ||
603     M.getNamedValue("objc_autoreleaseReturnValue") ||
604     M.getNamedValue("objc_autoreleasePoolPush") ||
605     M.getNamedValue("objc_loadWeakRetained") ||
606     M.getNamedValue("objc_loadWeak") ||
607     M.getNamedValue("objc_destroyWeak") ||
608     M.getNamedValue("objc_storeWeak") ||
609     M.getNamedValue("objc_initWeak") ||
610     M.getNamedValue("objc_moveWeak") ||
611     M.getNamedValue("objc_copyWeak") ||
612     M.getNamedValue("objc_retainedObject") ||
613     M.getNamedValue("objc_unretainedObject") ||
614     M.getNamedValue("objc_unretainedPointer");
615 }
616
617 /// \brief Test whether the given pointer, which is an Objective C block
618 /// pointer, does not "escape".
619 ///
620 /// This differs from regular escape analysis in that a use as an
621 /// argument to a call is not considered an escape.
622 ///
623 static bool DoesObjCBlockEscape(const Value *BlockPtr) {
624
625   DEBUG(dbgs() << "DoesObjCBlockEscape: Target: " << *BlockPtr << "\n");
626
627   // Walk the def-use chains.
628   SmallVector<const Value *, 4> Worklist;
629   Worklist.push_back(BlockPtr);
630
631   // Ensure we do not visit any value twice.
632   SmallPtrSet<const Value *, 4> VisitedSet;
633
634   do {
635     const Value *V = Worklist.pop_back_val();
636
637     DEBUG(dbgs() << "DoesObjCBlockEscape: Visiting: " << *V << "\n");
638
639     for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
640          UI != UE; ++UI) {
641       const User *UUser = *UI;
642
643       DEBUG(dbgs() << "DoesObjCBlockEscape: User: " << *UUser << "\n");
644
645       // Special - Use by a call (callee or argument) is not considered
646       // to be an escape.
647       switch (GetBasicInstructionClass(UUser)) {
648       case IC_StoreWeak:
649       case IC_InitWeak:
650       case IC_StoreStrong:
651       case IC_Autorelease:
652       case IC_AutoreleaseRV: {
653         DEBUG(dbgs() << "DoesObjCBlockEscape: User copies pointer arguments. "
654                         "Block Escapes!\n");
655         // These special functions make copies of their pointer arguments.
656         return true;
657       }
658       case IC_User:
659       case IC_None:
660         // Use by an instruction which copies the value is an escape if the
661         // result is an escape.
662         if (isa<BitCastInst>(UUser) || isa<GetElementPtrInst>(UUser) ||
663             isa<PHINode>(UUser) || isa<SelectInst>(UUser)) {
664
665           if (!VisitedSet.insert(UUser)) {
666             DEBUG(dbgs() << "DoesObjCBlockEscape: User copies value. Escapes "
667                             "if result escapes. Adding to list.\n");
668             Worklist.push_back(UUser);
669           } else {
670             DEBUG(dbgs() << "DoesObjCBlockEscape: Already visited node.\n");
671           }
672           continue;
673         }
674         // Use by a load is not an escape.
675         if (isa<LoadInst>(UUser))
676           continue;
677         // Use by a store is not an escape if the use is the address.
678         if (const StoreInst *SI = dyn_cast<StoreInst>(UUser))
679           if (V != SI->getValueOperand())
680             continue;
681         break;
682       default:
683         // Regular calls and other stuff are not considered escapes.
684         continue;
685       }
686       // Otherwise, conservatively assume an escape.
687       DEBUG(dbgs() << "DoesObjCBlockEscape: Assuming block escapes.\n");
688       return true;
689     }
690   } while (!Worklist.empty());
691
692   // No escapes found.
693   DEBUG(dbgs() << "DoesObjCBlockEscape: Block does not escape.\n");
694   return false;
695 }
696
697 /// @}
698 ///
699 /// \defgroup ARCAA Extends alias analysis using ObjC specific knowledge.
700 /// @{
701
702 #include "llvm/Analysis/AliasAnalysis.h"
703 #include "llvm/Analysis/Passes.h"
704 #include "llvm/Pass.h"
705
706 namespace {
707   /// \brief This is a simple alias analysis implementation that uses knowledge
708   /// of ARC constructs to answer queries.
709   ///
710   /// TODO: This class could be generalized to know about other ObjC-specific
711   /// tricks. Such as knowing that ivars in the non-fragile ABI are non-aliasing
712   /// even though their offsets are dynamic.
713   class ObjCARCAliasAnalysis : public ImmutablePass,
714                                public AliasAnalysis {
715   public:
716     static char ID; // Class identification, replacement for typeinfo
717     ObjCARCAliasAnalysis() : ImmutablePass(ID) {
718       initializeObjCARCAliasAnalysisPass(*PassRegistry::getPassRegistry());
719     }
720
721   private:
722     virtual void initializePass() {
723       InitializeAliasAnalysis(this);
724     }
725
726     /// This method is used when a pass implements an analysis interface through
727     /// multiple inheritance.  If needed, it should override this to adjust the
728     /// this pointer as needed for the specified pass info.
729     virtual void *getAdjustedAnalysisPointer(const void *PI) {
730       if (PI == &AliasAnalysis::ID)
731         return static_cast<AliasAnalysis *>(this);
732       return this;
733     }
734
735     virtual void getAnalysisUsage(AnalysisUsage &AU) const;
736     virtual AliasResult alias(const Location &LocA, const Location &LocB);
737     virtual bool pointsToConstantMemory(const Location &Loc, bool OrLocal);
738     virtual ModRefBehavior getModRefBehavior(ImmutableCallSite CS);
739     virtual ModRefBehavior getModRefBehavior(const Function *F);
740     virtual ModRefResult getModRefInfo(ImmutableCallSite CS,
741                                        const Location &Loc);
742     virtual ModRefResult getModRefInfo(ImmutableCallSite CS1,
743                                        ImmutableCallSite CS2);
744   };
745 }  // End of anonymous namespace
746
747 // Register this pass...
748 char ObjCARCAliasAnalysis::ID = 0;
749 INITIALIZE_AG_PASS(ObjCARCAliasAnalysis, AliasAnalysis, "objc-arc-aa",
750                    "ObjC-ARC-Based Alias Analysis", false, true, false)
751
752 ImmutablePass *llvm::createObjCARCAliasAnalysisPass() {
753   return new ObjCARCAliasAnalysis();
754 }
755
756 void
757 ObjCARCAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
758   AU.setPreservesAll();
759   AliasAnalysis::getAnalysisUsage(AU);
760 }
761
762 AliasAnalysis::AliasResult
763 ObjCARCAliasAnalysis::alias(const Location &LocA, const Location &LocB) {
764   if (!EnableARCOpts)
765     return AliasAnalysis::alias(LocA, LocB);
766
767   // First, strip off no-ops, including ObjC-specific no-ops, and try making a
768   // precise alias query.
769   const Value *SA = StripPointerCastsAndObjCCalls(LocA.Ptr);
770   const Value *SB = StripPointerCastsAndObjCCalls(LocB.Ptr);
771   AliasResult Result =
772     AliasAnalysis::alias(Location(SA, LocA.Size, LocA.TBAATag),
773                          Location(SB, LocB.Size, LocB.TBAATag));
774   if (Result != MayAlias)
775     return Result;
776
777   // If that failed, climb to the underlying object, including climbing through
778   // ObjC-specific no-ops, and try making an imprecise alias query.
779   const Value *UA = GetUnderlyingObjCPtr(SA);
780   const Value *UB = GetUnderlyingObjCPtr(SB);
781   if (UA != SA || UB != SB) {
782     Result = AliasAnalysis::alias(Location(UA), Location(UB));
783     // We can't use MustAlias or PartialAlias results here because
784     // GetUnderlyingObjCPtr may return an offsetted pointer value.
785     if (Result == NoAlias)
786       return NoAlias;
787   }
788
789   // If that failed, fail. We don't need to chain here, since that's covered
790   // by the earlier precise query.
791   return MayAlias;
792 }
793
794 bool
795 ObjCARCAliasAnalysis::pointsToConstantMemory(const Location &Loc,
796                                              bool OrLocal) {
797   if (!EnableARCOpts)
798     return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
799
800   // First, strip off no-ops, including ObjC-specific no-ops, and try making
801   // a precise alias query.
802   const Value *S = StripPointerCastsAndObjCCalls(Loc.Ptr);
803   if (AliasAnalysis::pointsToConstantMemory(Location(S, Loc.Size, Loc.TBAATag),
804                                             OrLocal))
805     return true;
806
807   // If that failed, climb to the underlying object, including climbing through
808   // ObjC-specific no-ops, and try making an imprecise alias query.
809   const Value *U = GetUnderlyingObjCPtr(S);
810   if (U != S)
811     return AliasAnalysis::pointsToConstantMemory(Location(U), OrLocal);
812
813   // If that failed, fail. We don't need to chain here, since that's covered
814   // by the earlier precise query.
815   return false;
816 }
817
818 AliasAnalysis::ModRefBehavior
819 ObjCARCAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
820   // We have nothing to do. Just chain to the next AliasAnalysis.
821   return AliasAnalysis::getModRefBehavior(CS);
822 }
823
824 AliasAnalysis::ModRefBehavior
825 ObjCARCAliasAnalysis::getModRefBehavior(const Function *F) {
826   if (!EnableARCOpts)
827     return AliasAnalysis::getModRefBehavior(F);
828
829   switch (GetFunctionClass(F)) {
830   case IC_NoopCast:
831     return DoesNotAccessMemory;
832   default:
833     break;
834   }
835
836   return AliasAnalysis::getModRefBehavior(F);
837 }
838
839 AliasAnalysis::ModRefResult
840 ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS, const Location &Loc) {
841   if (!EnableARCOpts)
842     return AliasAnalysis::getModRefInfo(CS, Loc);
843
844   switch (GetBasicInstructionClass(CS.getInstruction())) {
845   case IC_Retain:
846   case IC_RetainRV:
847   case IC_Autorelease:
848   case IC_AutoreleaseRV:
849   case IC_NoopCast:
850   case IC_AutoreleasepoolPush:
851   case IC_FusedRetainAutorelease:
852   case IC_FusedRetainAutoreleaseRV:
853     // These functions don't access any memory visible to the compiler.
854     // Note that this doesn't include objc_retainBlock, because it updates
855     // pointers when it copies block data.
856     return NoModRef;
857   default:
858     break;
859   }
860
861   return AliasAnalysis::getModRefInfo(CS, Loc);
862 }
863
864 AliasAnalysis::ModRefResult
865 ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
866                                     ImmutableCallSite CS2) {
867   // TODO: Theoretically we could check for dependencies between objc_* calls
868   // and OnlyAccessesArgumentPointees calls or other well-behaved calls.
869   return AliasAnalysis::getModRefInfo(CS1, CS2);
870 }
871
872 /// @}
873 ///
874 /// \defgroup ARCExpansion Early ARC Optimizations.
875 /// @{
876
877 #include "llvm/Support/InstIterator.h"
878 #include "llvm/Transforms/Scalar.h"
879
880 namespace {
881   /// \brief Early ARC transformations.
882   class ObjCARCExpand : public FunctionPass {
883     virtual void getAnalysisUsage(AnalysisUsage &AU) const;
884     virtual bool doInitialization(Module &M);
885     virtual bool runOnFunction(Function &F);
886
887     /// A flag indicating whether this optimization pass should run.
888     bool Run;
889
890   public:
891     static char ID;
892     ObjCARCExpand() : FunctionPass(ID) {
893       initializeObjCARCExpandPass(*PassRegistry::getPassRegistry());
894     }
895   };
896 }
897
898 char ObjCARCExpand::ID = 0;
899 INITIALIZE_PASS(ObjCARCExpand,
900                 "objc-arc-expand", "ObjC ARC expansion", false, false)
901
902 Pass *llvm::createObjCARCExpandPass() {
903   return new ObjCARCExpand();
904 }
905
906 void ObjCARCExpand::getAnalysisUsage(AnalysisUsage &AU) const {
907   AU.setPreservesCFG();
908 }
909
910 bool ObjCARCExpand::doInitialization(Module &M) {
911   Run = ModuleHasARC(M);
912   return false;
913 }
914
915 bool ObjCARCExpand::runOnFunction(Function &F) {
916   if (!EnableARCOpts)
917     return false;
918
919   // If nothing in the Module uses ARC, don't do anything.
920   if (!Run)
921     return false;
922
923   bool Changed = false;
924
925   DEBUG(dbgs() << "ObjCARCExpand: Visiting Function: " << F.getName() << "\n");
926
927   for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
928     Instruction *Inst = &*I;
929
930     DEBUG(dbgs() << "ObjCARCExpand: Visiting: " << *Inst << "\n");
931
932     switch (GetBasicInstructionClass(Inst)) {
933     case IC_Retain:
934     case IC_RetainRV:
935     case IC_Autorelease:
936     case IC_AutoreleaseRV:
937     case IC_FusedRetainAutorelease:
938     case IC_FusedRetainAutoreleaseRV: {
939       // These calls return their argument verbatim, as a low-level
940       // optimization. However, this makes high-level optimizations
941       // harder. Undo any uses of this optimization that the front-end
942       // emitted here. We'll redo them in the contract pass.
943       Changed = true;
944       Value *Value = cast<CallInst>(Inst)->getArgOperand(0);
945       DEBUG(dbgs() << "ObjCARCExpand: Old = " << *Inst << "\n"
946                       "               New = " << *Value << "\n");
947       Inst->replaceAllUsesWith(Value);
948       break;
949     }
950     default:
951       break;
952     }
953   }
954
955   DEBUG(dbgs() << "ObjCARCExpand: Finished List.\n\n");
956
957   return Changed;
958 }
959
960 /// @}
961 ///
962 /// \defgroup ARCAPElim ARC Autorelease Pool Elimination.
963 /// @{
964
965 #include "llvm/ADT/STLExtras.h"
966 #include "llvm/IR/Constants.h"
967
968 namespace {
969   /// \brief Autorelease pool elimination.
970   class ObjCARCAPElim : public ModulePass {
971     virtual void getAnalysisUsage(AnalysisUsage &AU) const;
972     virtual bool runOnModule(Module &M);
973
974     static bool MayAutorelease(ImmutableCallSite CS, unsigned Depth = 0);
975     static bool OptimizeBB(BasicBlock *BB);
976
977   public:
978     static char ID;
979     ObjCARCAPElim() : ModulePass(ID) {
980       initializeObjCARCAPElimPass(*PassRegistry::getPassRegistry());
981     }
982   };
983 }
984
985 char ObjCARCAPElim::ID = 0;
986 INITIALIZE_PASS(ObjCARCAPElim,
987                 "objc-arc-apelim",
988                 "ObjC ARC autorelease pool elimination",
989                 false, false)
990
991 Pass *llvm::createObjCARCAPElimPass() {
992   return new ObjCARCAPElim();
993 }
994
995 void ObjCARCAPElim::getAnalysisUsage(AnalysisUsage &AU) const {
996   AU.setPreservesCFG();
997 }
998
999 /// Interprocedurally determine if calls made by the given call site can
1000 /// possibly produce autoreleases.
1001 bool ObjCARCAPElim::MayAutorelease(ImmutableCallSite CS, unsigned Depth) {
1002   if (const Function *Callee = CS.getCalledFunction()) {
1003     if (Callee->isDeclaration() || Callee->mayBeOverridden())
1004       return true;
1005     for (Function::const_iterator I = Callee->begin(), E = Callee->end();
1006          I != E; ++I) {
1007       const BasicBlock *BB = I;
1008       for (BasicBlock::const_iterator J = BB->begin(), F = BB->end();
1009            J != F; ++J)
1010         if (ImmutableCallSite JCS = ImmutableCallSite(J))
1011           // This recursion depth limit is arbitrary. It's just great
1012           // enough to cover known interesting testcases.
1013           if (Depth < 3 &&
1014               !JCS.onlyReadsMemory() &&
1015               MayAutorelease(JCS, Depth + 1))
1016             return true;
1017     }
1018     return false;
1019   }
1020
1021   return true;
1022 }
1023
1024 bool ObjCARCAPElim::OptimizeBB(BasicBlock *BB) {
1025   bool Changed = false;
1026
1027   Instruction *Push = 0;
1028   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1029     Instruction *Inst = I++;
1030     switch (GetBasicInstructionClass(Inst)) {
1031     case IC_AutoreleasepoolPush:
1032       Push = Inst;
1033       break;
1034     case IC_AutoreleasepoolPop:
1035       // If this pop matches a push and nothing in between can autorelease,
1036       // zap the pair.
1037       if (Push && cast<CallInst>(Inst)->getArgOperand(0) == Push) {
1038         Changed = true;
1039         DEBUG(dbgs() << "ObjCARCAPElim::OptimizeBB: Zapping push pop "
1040                         "autorelease pair:\n"
1041                         "                           Pop: " << *Inst << "\n"
1042                      << "                           Push: " << *Push << "\n");
1043         Inst->eraseFromParent();
1044         Push->eraseFromParent();
1045       }
1046       Push = 0;
1047       break;
1048     case IC_CallOrUser:
1049       if (MayAutorelease(ImmutableCallSite(Inst)))
1050         Push = 0;
1051       break;
1052     default:
1053       break;
1054     }
1055   }
1056
1057   return Changed;
1058 }
1059
1060 bool ObjCARCAPElim::runOnModule(Module &M) {
1061   if (!EnableARCOpts)
1062     return false;
1063
1064   // If nothing in the Module uses ARC, don't do anything.
1065   if (!ModuleHasARC(M))
1066     return false;
1067
1068   // Find the llvm.global_ctors variable, as the first step in
1069   // identifying the global constructors. In theory, unnecessary autorelease
1070   // pools could occur anywhere, but in practice it's pretty rare. Global
1071   // ctors are a place where autorelease pools get inserted automatically,
1072   // so it's pretty common for them to be unnecessary, and it's pretty
1073   // profitable to eliminate them.
1074   GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1075   if (!GV)
1076     return false;
1077
1078   assert(GV->hasDefinitiveInitializer() &&
1079          "llvm.global_ctors is uncooperative!");
1080
1081   bool Changed = false;
1082
1083   // Dig the constructor functions out of GV's initializer.
1084   ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
1085   for (User::op_iterator OI = Init->op_begin(), OE = Init->op_end();
1086        OI != OE; ++OI) {
1087     Value *Op = *OI;
1088     // llvm.global_ctors is an array of pairs where the second members
1089     // are constructor functions.
1090     Function *F = dyn_cast<Function>(cast<ConstantStruct>(Op)->getOperand(1));
1091     // If the user used a constructor function with the wrong signature and
1092     // it got bitcasted or whatever, look the other way.
1093     if (!F)
1094       continue;
1095     // Only look at function definitions.
1096     if (F->isDeclaration())
1097       continue;
1098     // Only look at functions with one basic block.
1099     if (llvm::next(F->begin()) != F->end())
1100       continue;
1101     // Ok, a single-block constructor function definition. Try to optimize it.
1102     Changed |= OptimizeBB(F->begin());
1103   }
1104
1105   return Changed;
1106 }
1107
1108 /// @}
1109 ///
1110 /// \defgroup ARCOpt ARC Optimization.
1111 /// @{
1112
1113 // TODO: On code like this:
1114 //
1115 // objc_retain(%x)
1116 // stuff_that_cannot_release()
1117 // objc_autorelease(%x)
1118 // stuff_that_cannot_release()
1119 // objc_retain(%x)
1120 // stuff_that_cannot_release()
1121 // objc_autorelease(%x)
1122 //
1123 // The second retain and autorelease can be deleted.
1124
1125 // TODO: It should be possible to delete
1126 // objc_autoreleasePoolPush and objc_autoreleasePoolPop
1127 // pairs if nothing is actually autoreleased between them. Also, autorelease
1128 // calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
1129 // after inlining) can be turned into plain release calls.
1130
1131 // TODO: Critical-edge splitting. If the optimial insertion point is
1132 // a critical edge, the current algorithm has to fail, because it doesn't
1133 // know how to split edges. It should be possible to make the optimizer
1134 // think in terms of edges, rather than blocks, and then split critical
1135 // edges on demand.
1136
1137 // TODO: OptimizeSequences could generalized to be Interprocedural.
1138
1139 // TODO: Recognize that a bunch of other objc runtime calls have
1140 // non-escaping arguments and non-releasing arguments, and may be
1141 // non-autoreleasing.
1142
1143 // TODO: Sink autorelease calls as far as possible. Unfortunately we
1144 // usually can't sink them past other calls, which would be the main
1145 // case where it would be useful.
1146
1147 // TODO: The pointer returned from objc_loadWeakRetained is retained.
1148
1149 // TODO: Delete release+retain pairs (rare).
1150
1151 #include "llvm/ADT/SmallPtrSet.h"
1152 #include "llvm/ADT/Statistic.h"
1153 #include "llvm/IR/LLVMContext.h"
1154 #include "llvm/Support/CFG.h"
1155
1156 STATISTIC(NumNoops,       "Number of no-op objc calls eliminated");
1157 STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
1158 STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
1159 STATISTIC(NumRets,        "Number of return value forwarding "
1160                           "retain+autoreleaes eliminated");
1161 STATISTIC(NumRRs,         "Number of retain+release paths eliminated");
1162 STATISTIC(NumPeeps,       "Number of calls peephole-optimized");
1163
1164 namespace {
1165   /// \brief This is similar to BasicAliasAnalysis, and it uses many of the same
1166   /// techniques, except it uses special ObjC-specific reasoning about pointer
1167   /// relationships.
1168   class ProvenanceAnalysis {
1169     AliasAnalysis *AA;
1170
1171     typedef std::pair<const Value *, const Value *> ValuePairTy;
1172     typedef DenseMap<ValuePairTy, bool> CachedResultsTy;
1173     CachedResultsTy CachedResults;
1174
1175     bool relatedCheck(const Value *A, const Value *B);
1176     bool relatedSelect(const SelectInst *A, const Value *B);
1177     bool relatedPHI(const PHINode *A, const Value *B);
1178
1179     void operator=(const ProvenanceAnalysis &) LLVM_DELETED_FUNCTION;
1180     ProvenanceAnalysis(const ProvenanceAnalysis &) LLVM_DELETED_FUNCTION;
1181
1182   public:
1183     ProvenanceAnalysis() {}
1184
1185     void setAA(AliasAnalysis *aa) { AA = aa; }
1186
1187     AliasAnalysis *getAA() const { return AA; }
1188
1189     bool related(const Value *A, const Value *B);
1190
1191     void clear() {
1192       CachedResults.clear();
1193     }
1194   };
1195 }
1196
1197 bool ProvenanceAnalysis::relatedSelect(const SelectInst *A, const Value *B) {
1198   // If the values are Selects with the same condition, we can do a more precise
1199   // check: just check for relations between the values on corresponding arms.
1200   if (const SelectInst *SB = dyn_cast<SelectInst>(B))
1201     if (A->getCondition() == SB->getCondition())
1202       return related(A->getTrueValue(), SB->getTrueValue()) ||
1203              related(A->getFalseValue(), SB->getFalseValue());
1204
1205   // Check both arms of the Select node individually.
1206   return related(A->getTrueValue(), B) ||
1207          related(A->getFalseValue(), B);
1208 }
1209
1210 bool ProvenanceAnalysis::relatedPHI(const PHINode *A, const Value *B) {
1211   // If the values are PHIs in the same block, we can do a more precise as well
1212   // as efficient check: just check for relations between the values on
1213   // corresponding edges.
1214   if (const PHINode *PNB = dyn_cast<PHINode>(B))
1215     if (PNB->getParent() == A->getParent()) {
1216       for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i)
1217         if (related(A->getIncomingValue(i),
1218                     PNB->getIncomingValueForBlock(A->getIncomingBlock(i))))
1219           return true;
1220       return false;
1221     }
1222
1223   // Check each unique source of the PHI node against B.
1224   SmallPtrSet<const Value *, 4> UniqueSrc;
1225   for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i) {
1226     const Value *PV1 = A->getIncomingValue(i);
1227     if (UniqueSrc.insert(PV1) && related(PV1, B))
1228       return true;
1229   }
1230
1231   // All of the arms checked out.
1232   return false;
1233 }
1234
1235 /// Test if the value of P, or any value covered by its provenance, is ever
1236 /// stored within the function (not counting callees).
1237 static bool isStoredObjCPointer(const Value *P) {
1238   SmallPtrSet<const Value *, 8> Visited;
1239   SmallVector<const Value *, 8> Worklist;
1240   Worklist.push_back(P);
1241   Visited.insert(P);
1242   do {
1243     P = Worklist.pop_back_val();
1244     for (Value::const_use_iterator UI = P->use_begin(), UE = P->use_end();
1245          UI != UE; ++UI) {
1246       const User *Ur = *UI;
1247       if (isa<StoreInst>(Ur)) {
1248         if (UI.getOperandNo() == 0)
1249           // The pointer is stored.
1250           return true;
1251         // The pointed is stored through.
1252         continue;
1253       }
1254       if (isa<CallInst>(Ur))
1255         // The pointer is passed as an argument, ignore this.
1256         continue;
1257       if (isa<PtrToIntInst>(P))
1258         // Assume the worst.
1259         return true;
1260       if (Visited.insert(Ur))
1261         Worklist.push_back(Ur);
1262     }
1263   } while (!Worklist.empty());
1264
1265   // Everything checked out.
1266   return false;
1267 }
1268
1269 bool ProvenanceAnalysis::relatedCheck(const Value *A, const Value *B) {
1270   // Skip past provenance pass-throughs.
1271   A = GetUnderlyingObjCPtr(A);
1272   B = GetUnderlyingObjCPtr(B);
1273
1274   // Quick check.
1275   if (A == B)
1276     return true;
1277
1278   // Ask regular AliasAnalysis, for a first approximation.
1279   switch (AA->alias(A, B)) {
1280   case AliasAnalysis::NoAlias:
1281     return false;
1282   case AliasAnalysis::MustAlias:
1283   case AliasAnalysis::PartialAlias:
1284     return true;
1285   case AliasAnalysis::MayAlias:
1286     break;
1287   }
1288
1289   bool AIsIdentified = IsObjCIdentifiedObject(A);
1290   bool BIsIdentified = IsObjCIdentifiedObject(B);
1291
1292   // An ObjC-Identified object can't alias a load if it is never locally stored.
1293   if (AIsIdentified) {
1294     // Check for an obvious escape.
1295     if (isa<LoadInst>(B))
1296       return isStoredObjCPointer(A);
1297     if (BIsIdentified) {
1298       // Check for an obvious escape.
1299       if (isa<LoadInst>(A))
1300         return isStoredObjCPointer(B);
1301       // Both pointers are identified and escapes aren't an evident problem.
1302       return false;
1303     }
1304   } else if (BIsIdentified) {
1305     // Check for an obvious escape.
1306     if (isa<LoadInst>(A))
1307       return isStoredObjCPointer(B);
1308   }
1309
1310    // Special handling for PHI and Select.
1311   if (const PHINode *PN = dyn_cast<PHINode>(A))
1312     return relatedPHI(PN, B);
1313   if (const PHINode *PN = dyn_cast<PHINode>(B))
1314     return relatedPHI(PN, A);
1315   if (const SelectInst *S = dyn_cast<SelectInst>(A))
1316     return relatedSelect(S, B);
1317   if (const SelectInst *S = dyn_cast<SelectInst>(B))
1318     return relatedSelect(S, A);
1319
1320   // Conservative.
1321   return true;
1322 }
1323
1324 bool ProvenanceAnalysis::related(const Value *A, const Value *B) {
1325   // Begin by inserting a conservative value into the map. If the insertion
1326   // fails, we have the answer already. If it succeeds, leave it there until we
1327   // compute the real answer to guard against recursive queries.
1328   if (A > B) std::swap(A, B);
1329   std::pair<CachedResultsTy::iterator, bool> Pair =
1330     CachedResults.insert(std::make_pair(ValuePairTy(A, B), true));
1331   if (!Pair.second)
1332     return Pair.first->second;
1333
1334   bool Result = relatedCheck(A, B);
1335   CachedResults[ValuePairTy(A, B)] = Result;
1336   return Result;
1337 }
1338
1339 namespace {
1340   /// \enum Sequence
1341   ///
1342   /// \brief A sequence of states that a pointer may go through in which an
1343   /// objc_retain and objc_release are actually needed.
1344   enum Sequence {
1345     S_None,
1346     S_Retain,         ///< objc_retain(x)
1347     S_CanRelease,     ///< foo(x) -- x could possibly see a ref count decrement
1348     S_Use,            ///< any use of x
1349     S_Stop,           ///< like S_Release, but code motion is stopped
1350     S_Release,        ///< objc_release(x)
1351     S_MovableRelease  ///< objc_release(x), !clang.imprecise_release
1352   };
1353 }
1354
1355 static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
1356   // The easy cases.
1357   if (A == B)
1358     return A;
1359   if (A == S_None || B == S_None)
1360     return S_None;
1361
1362   if (A > B) std::swap(A, B);
1363   if (TopDown) {
1364     // Choose the side which is further along in the sequence.
1365     if ((A == S_Retain || A == S_CanRelease) &&
1366         (B == S_CanRelease || B == S_Use))
1367       return B;
1368   } else {
1369     // Choose the side which is further along in the sequence.
1370     if ((A == S_Use || A == S_CanRelease) &&
1371         (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
1372       return A;
1373     // If both sides are releases, choose the more conservative one.
1374     if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
1375       return A;
1376     if (A == S_Release && B == S_MovableRelease)
1377       return A;
1378   }
1379
1380   return S_None;
1381 }
1382
1383 namespace {
1384   /// \brief Unidirectional information about either a
1385   /// retain-decrement-use-release sequence or release-use-decrement-retain
1386   /// reverese sequence.
1387   struct RRInfo {
1388     /// After an objc_retain, the reference count of the referenced
1389     /// object is known to be positive. Similarly, before an objc_release, the
1390     /// reference count of the referenced object is known to be positive. If
1391     /// there are retain-release pairs in code regions where the retain count
1392     /// is known to be positive, they can be eliminated, regardless of any side
1393     /// effects between them.
1394     ///
1395     /// Also, a retain+release pair nested within another retain+release
1396     /// pair all on the known same pointer value can be eliminated, regardless
1397     /// of any intervening side effects.
1398     ///
1399     /// KnownSafe is true when either of these conditions is satisfied.
1400     bool KnownSafe;
1401
1402     /// True if the Calls are objc_retainBlock calls (as opposed to objc_retain
1403     /// calls).
1404     bool IsRetainBlock;
1405
1406     /// True of the objc_release calls are all marked with the "tail" keyword.
1407     bool IsTailCallRelease;
1408
1409     /// If the Calls are objc_release calls and they all have a
1410     /// clang.imprecise_release tag, this is the metadata tag.
1411     MDNode *ReleaseMetadata;
1412
1413     /// For a top-down sequence, the set of objc_retains or
1414     /// objc_retainBlocks. For bottom-up, the set of objc_releases.
1415     SmallPtrSet<Instruction *, 2> Calls;
1416
1417     /// The set of optimal insert positions for moving calls in the opposite
1418     /// sequence.
1419     SmallPtrSet<Instruction *, 2> ReverseInsertPts;
1420
1421     RRInfo() :
1422       KnownSafe(false), IsRetainBlock(false),
1423       IsTailCallRelease(false),
1424       ReleaseMetadata(0) {}
1425
1426     void clear();
1427   };
1428 }
1429
1430 void RRInfo::clear() {
1431   KnownSafe = false;
1432   IsRetainBlock = false;
1433   IsTailCallRelease = false;
1434   ReleaseMetadata = 0;
1435   Calls.clear();
1436   ReverseInsertPts.clear();
1437 }
1438
1439 namespace {
1440   /// \brief This class summarizes several per-pointer runtime properties which
1441   /// are propogated through the flow graph.
1442   class PtrState {
1443     /// True if the reference count is known to be incremented.
1444     bool KnownPositiveRefCount;
1445
1446     /// True of we've seen an opportunity for partial RR elimination, such as
1447     /// pushing calls into a CFG triangle or into one side of a CFG diamond.
1448     bool Partial;
1449
1450     /// The current position in the sequence.
1451     Sequence Seq : 8;
1452
1453   public:
1454     /// Unidirectional information about the current sequence.
1455     ///
1456     /// TODO: Encapsulate this better.
1457     RRInfo RRI;
1458
1459     PtrState() : KnownPositiveRefCount(false), Partial(false),
1460                  Seq(S_None) {}
1461
1462     void SetKnownPositiveRefCount() {
1463       KnownPositiveRefCount = true;
1464     }
1465
1466     void ClearRefCount() {
1467       KnownPositiveRefCount = false;
1468     }
1469
1470     bool IsKnownIncremented() const {
1471       return KnownPositiveRefCount;
1472     }
1473
1474     void SetSeq(Sequence NewSeq) {
1475       Seq = NewSeq;
1476     }
1477
1478     Sequence GetSeq() const {
1479       return Seq;
1480     }
1481
1482     void ClearSequenceProgress() {
1483       ResetSequenceProgress(S_None);
1484     }
1485
1486     void ResetSequenceProgress(Sequence NewSeq) {
1487       Seq = NewSeq;
1488       Partial = false;
1489       RRI.clear();
1490     }
1491
1492     void Merge(const PtrState &Other, bool TopDown);
1493   };
1494 }
1495
1496 void
1497 PtrState::Merge(const PtrState &Other, bool TopDown) {
1498   Seq = MergeSeqs(Seq, Other.Seq, TopDown);
1499   KnownPositiveRefCount = KnownPositiveRefCount && Other.KnownPositiveRefCount;
1500
1501   // We can't merge a plain objc_retain with an objc_retainBlock.
1502   if (RRI.IsRetainBlock != Other.RRI.IsRetainBlock)
1503     Seq = S_None;
1504
1505   // If we're not in a sequence (anymore), drop all associated state.
1506   if (Seq == S_None) {
1507     Partial = false;
1508     RRI.clear();
1509   } else if (Partial || Other.Partial) {
1510     // If we're doing a merge on a path that's previously seen a partial
1511     // merge, conservatively drop the sequence, to avoid doing partial
1512     // RR elimination. If the branch predicates for the two merge differ,
1513     // mixing them is unsafe.
1514     ClearSequenceProgress();
1515   } else {
1516     // Conservatively merge the ReleaseMetadata information.
1517     if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
1518       RRI.ReleaseMetadata = 0;
1519
1520     RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
1521     RRI.IsTailCallRelease = RRI.IsTailCallRelease &&
1522                             Other.RRI.IsTailCallRelease;
1523     RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
1524
1525     // Merge the insert point sets. If there are any differences,
1526     // that makes this a partial merge.
1527     Partial = RRI.ReverseInsertPts.size() != Other.RRI.ReverseInsertPts.size();
1528     for (SmallPtrSet<Instruction *, 2>::const_iterator
1529          I = Other.RRI.ReverseInsertPts.begin(),
1530          E = Other.RRI.ReverseInsertPts.end(); I != E; ++I)
1531       Partial |= RRI.ReverseInsertPts.insert(*I);
1532   }
1533 }
1534
1535 namespace {
1536   /// \brief Per-BasicBlock state.
1537   class BBState {
1538     /// The number of unique control paths from the entry which can reach this
1539     /// block.
1540     unsigned TopDownPathCount;
1541
1542     /// The number of unique control paths to exits from this block.
1543     unsigned BottomUpPathCount;
1544
1545     /// A type for PerPtrTopDown and PerPtrBottomUp.
1546     typedef MapVector<const Value *, PtrState> MapTy;
1547
1548     /// The top-down traversal uses this to record information known about a
1549     /// pointer at the bottom of each block.
1550     MapTy PerPtrTopDown;
1551
1552     /// The bottom-up traversal uses this to record information known about a
1553     /// pointer at the top of each block.
1554     MapTy PerPtrBottomUp;
1555
1556     /// Effective predecessors of the current block ignoring ignorable edges and
1557     /// ignored backedges.
1558     SmallVector<BasicBlock *, 2> Preds;
1559     /// Effective successors of the current block ignoring ignorable edges and
1560     /// ignored backedges.
1561     SmallVector<BasicBlock *, 2> Succs;
1562
1563   public:
1564     BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
1565
1566     typedef MapTy::iterator ptr_iterator;
1567     typedef MapTy::const_iterator ptr_const_iterator;
1568
1569     ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
1570     ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
1571     ptr_const_iterator top_down_ptr_begin() const {
1572       return PerPtrTopDown.begin();
1573     }
1574     ptr_const_iterator top_down_ptr_end() const {
1575       return PerPtrTopDown.end();
1576     }
1577
1578     ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
1579     ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
1580     ptr_const_iterator bottom_up_ptr_begin() const {
1581       return PerPtrBottomUp.begin();
1582     }
1583     ptr_const_iterator bottom_up_ptr_end() const {
1584       return PerPtrBottomUp.end();
1585     }
1586
1587     /// Mark this block as being an entry block, which has one path from the
1588     /// entry by definition.
1589     void SetAsEntry() { TopDownPathCount = 1; }
1590
1591     /// Mark this block as being an exit block, which has one path to an exit by
1592     /// definition.
1593     void SetAsExit()  { BottomUpPathCount = 1; }
1594
1595     PtrState &getPtrTopDownState(const Value *Arg) {
1596       return PerPtrTopDown[Arg];
1597     }
1598
1599     PtrState &getPtrBottomUpState(const Value *Arg) {
1600       return PerPtrBottomUp[Arg];
1601     }
1602
1603     void clearBottomUpPointers() {
1604       PerPtrBottomUp.clear();
1605     }
1606
1607     void clearTopDownPointers() {
1608       PerPtrTopDown.clear();
1609     }
1610
1611     void InitFromPred(const BBState &Other);
1612     void InitFromSucc(const BBState &Other);
1613     void MergePred(const BBState &Other);
1614     void MergeSucc(const BBState &Other);
1615
1616     /// Return the number of possible unique paths from an entry to an exit
1617     /// which pass through this block. This is only valid after both the
1618     /// top-down and bottom-up traversals are complete.
1619     unsigned GetAllPathCount() const {
1620       assert(TopDownPathCount != 0);
1621       assert(BottomUpPathCount != 0);
1622       return TopDownPathCount * BottomUpPathCount;
1623     }
1624
1625     // Specialized CFG utilities.
1626     typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
1627     edge_iterator pred_begin() { return Preds.begin(); }
1628     edge_iterator pred_end() { return Preds.end(); }
1629     edge_iterator succ_begin() { return Succs.begin(); }
1630     edge_iterator succ_end() { return Succs.end(); }
1631
1632     void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
1633     void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
1634
1635     bool isExit() const { return Succs.empty(); }
1636   };
1637 }
1638
1639 void BBState::InitFromPred(const BBState &Other) {
1640   PerPtrTopDown = Other.PerPtrTopDown;
1641   TopDownPathCount = Other.TopDownPathCount;
1642 }
1643
1644 void BBState::InitFromSucc(const BBState &Other) {
1645   PerPtrBottomUp = Other.PerPtrBottomUp;
1646   BottomUpPathCount = Other.BottomUpPathCount;
1647 }
1648
1649 /// The top-down traversal uses this to merge information about predecessors to
1650 /// form the initial state for a new block.
1651 void BBState::MergePred(const BBState &Other) {
1652   // Other.TopDownPathCount can be 0, in which case it is either dead or a
1653   // loop backedge. Loop backedges are special.
1654   TopDownPathCount += Other.TopDownPathCount;
1655
1656   // Check for overflow. If we have overflow, fall back to conservative
1657   // behavior.
1658   if (TopDownPathCount < Other.TopDownPathCount) {
1659     clearTopDownPointers();
1660     return;
1661   }
1662
1663   // For each entry in the other set, if our set has an entry with the same key,
1664   // merge the entries. Otherwise, copy the entry and merge it with an empty
1665   // entry.
1666   for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
1667        ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
1668     std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
1669     Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1670                              /*TopDown=*/true);
1671   }
1672
1673   // For each entry in our set, if the other set doesn't have an entry with the
1674   // same key, force it to merge with an empty entry.
1675   for (ptr_iterator MI = top_down_ptr_begin(),
1676        ME = top_down_ptr_end(); MI != ME; ++MI)
1677     if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
1678       MI->second.Merge(PtrState(), /*TopDown=*/true);
1679 }
1680
1681 /// The bottom-up traversal uses this to merge information about successors to
1682 /// form the initial state for a new block.
1683 void BBState::MergeSucc(const BBState &Other) {
1684   // Other.BottomUpPathCount can be 0, in which case it is either dead or a
1685   // loop backedge. Loop backedges are special.
1686   BottomUpPathCount += Other.BottomUpPathCount;
1687
1688   // Check for overflow. If we have overflow, fall back to conservative
1689   // behavior.
1690   if (BottomUpPathCount < Other.BottomUpPathCount) {
1691     clearBottomUpPointers();
1692     return;
1693   }
1694
1695   // For each entry in the other set, if our set has an entry with the
1696   // same key, merge the entries. Otherwise, copy the entry and merge
1697   // it with an empty entry.
1698   for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
1699        ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
1700     std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
1701     Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1702                              /*TopDown=*/false);
1703   }
1704
1705   // For each entry in our set, if the other set doesn't have an entry
1706   // with the same key, force it to merge with an empty entry.
1707   for (ptr_iterator MI = bottom_up_ptr_begin(),
1708        ME = bottom_up_ptr_end(); MI != ME; ++MI)
1709     if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
1710       MI->second.Merge(PtrState(), /*TopDown=*/false);
1711 }
1712
1713 namespace {
1714   /// \brief The main ARC optimization pass.
1715   class ObjCARCOpt : public FunctionPass {
1716     bool Changed;
1717     ProvenanceAnalysis PA;
1718
1719     /// A flag indicating whether this optimization pass should run.
1720     bool Run;
1721
1722     /// Declarations for ObjC runtime functions, for use in creating calls to
1723     /// them. These are initialized lazily to avoid cluttering up the Module
1724     /// with unused declarations.
1725
1726     /// Declaration for ObjC runtime function
1727     /// objc_retainAutoreleasedReturnValue.
1728     Constant *RetainRVCallee;
1729     /// Declaration for ObjC runtime function objc_autoreleaseReturnValue.
1730     Constant *AutoreleaseRVCallee;
1731     /// Declaration for ObjC runtime function objc_release.
1732     Constant *ReleaseCallee;
1733     /// Declaration for ObjC runtime function objc_retain.
1734     Constant *RetainCallee;
1735     /// Declaration for ObjC runtime function objc_retainBlock.
1736     Constant *RetainBlockCallee;
1737     /// Declaration for ObjC runtime function objc_autorelease.
1738     Constant *AutoreleaseCallee;
1739
1740     /// Flags which determine whether each of the interesting runtine functions
1741     /// is in fact used in the current function.
1742     unsigned UsedInThisFunction;
1743
1744     /// The Metadata Kind for clang.imprecise_release metadata.
1745     unsigned ImpreciseReleaseMDKind;
1746
1747     /// The Metadata Kind for clang.arc.copy_on_escape metadata.
1748     unsigned CopyOnEscapeMDKind;
1749
1750     /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata.
1751     unsigned NoObjCARCExceptionsMDKind;
1752
1753     Constant *getRetainRVCallee(Module *M);
1754     Constant *getAutoreleaseRVCallee(Module *M);
1755     Constant *getReleaseCallee(Module *M);
1756     Constant *getRetainCallee(Module *M);
1757     Constant *getRetainBlockCallee(Module *M);
1758     Constant *getAutoreleaseCallee(Module *M);
1759
1760     bool IsRetainBlockOptimizable(const Instruction *Inst);
1761
1762     void OptimizeRetainCall(Function &F, Instruction *Retain);
1763     bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
1764     void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1765                                    InstructionClass &Class);
1766     void OptimizeIndividualCalls(Function &F);
1767
1768     void CheckForCFGHazards(const BasicBlock *BB,
1769                             DenseMap<const BasicBlock *, BBState> &BBStates,
1770                             BBState &MyStates) const;
1771     bool VisitInstructionBottomUp(Instruction *Inst,
1772                                   BasicBlock *BB,
1773                                   MapVector<Value *, RRInfo> &Retains,
1774                                   BBState &MyStates);
1775     bool VisitBottomUp(BasicBlock *BB,
1776                        DenseMap<const BasicBlock *, BBState> &BBStates,
1777                        MapVector<Value *, RRInfo> &Retains);
1778     bool VisitInstructionTopDown(Instruction *Inst,
1779                                  DenseMap<Value *, RRInfo> &Releases,
1780                                  BBState &MyStates);
1781     bool VisitTopDown(BasicBlock *BB,
1782                       DenseMap<const BasicBlock *, BBState> &BBStates,
1783                       DenseMap<Value *, RRInfo> &Releases);
1784     bool Visit(Function &F,
1785                DenseMap<const BasicBlock *, BBState> &BBStates,
1786                MapVector<Value *, RRInfo> &Retains,
1787                DenseMap<Value *, RRInfo> &Releases);
1788
1789     void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1790                    MapVector<Value *, RRInfo> &Retains,
1791                    DenseMap<Value *, RRInfo> &Releases,
1792                    SmallVectorImpl<Instruction *> &DeadInsts,
1793                    Module *M);
1794
1795     bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1796                               MapVector<Value *, RRInfo> &Retains,
1797                               DenseMap<Value *, RRInfo> &Releases,
1798                               Module *M);
1799
1800     void OptimizeWeakCalls(Function &F);
1801
1802     bool OptimizeSequences(Function &F);
1803
1804     void OptimizeReturns(Function &F);
1805
1806     virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1807     virtual bool doInitialization(Module &M);
1808     virtual bool runOnFunction(Function &F);
1809     virtual void releaseMemory();
1810
1811   public:
1812     static char ID;
1813     ObjCARCOpt() : FunctionPass(ID) {
1814       initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1815     }
1816   };
1817 }
1818
1819 char ObjCARCOpt::ID = 0;
1820 INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1821                       "objc-arc", "ObjC ARC optimization", false, false)
1822 INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1823 INITIALIZE_PASS_END(ObjCARCOpt,
1824                     "objc-arc", "ObjC ARC optimization", false, false)
1825
1826 Pass *llvm::createObjCARCOptPass() {
1827   return new ObjCARCOpt();
1828 }
1829
1830 void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1831   AU.addRequired<ObjCARCAliasAnalysis>();
1832   AU.addRequired<AliasAnalysis>();
1833   // ARC optimization doesn't currently split critical edges.
1834   AU.setPreservesCFG();
1835 }
1836
1837 bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1838   // Without the magic metadata tag, we have to assume this might be an
1839   // objc_retainBlock call inserted to convert a block pointer to an id,
1840   // in which case it really is needed.
1841   if (!Inst->getMetadata(CopyOnEscapeMDKind))
1842     return false;
1843
1844   // If the pointer "escapes" (not including being used in a call),
1845   // the copy may be needed.
1846   if (DoesObjCBlockEscape(Inst))
1847     return false;
1848
1849   // Otherwise, it's not needed.
1850   return true;
1851 }
1852
1853 Constant *ObjCARCOpt::getRetainRVCallee(Module *M) {
1854   if (!RetainRVCallee) {
1855     LLVMContext &C = M->getContext();
1856     Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1857     Type *Params[] = { I8X };
1858     FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
1859     AttributeSet Attribute =
1860       AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
1861                             Attribute::get(C, Attribute::NoUnwind));
1862     RetainRVCallee =
1863       M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy,
1864                              Attribute);
1865   }
1866   return RetainRVCallee;
1867 }
1868
1869 Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1870   if (!AutoreleaseRVCallee) {
1871     LLVMContext &C = M->getContext();
1872     Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1873     Type *Params[] = { I8X };
1874     FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
1875     AttributeSet Attribute =
1876       AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
1877                             Attribute::get(C, Attribute::NoUnwind));
1878     AutoreleaseRVCallee =
1879       M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
1880                              Attribute);
1881   }
1882   return AutoreleaseRVCallee;
1883 }
1884
1885 Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1886   if (!ReleaseCallee) {
1887     LLVMContext &C = M->getContext();
1888     Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1889     AttributeSet Attribute =
1890       AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
1891                             Attribute::get(C, Attribute::NoUnwind));
1892     ReleaseCallee =
1893       M->getOrInsertFunction(
1894         "objc_release",
1895         FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
1896         Attribute);
1897   }
1898   return ReleaseCallee;
1899 }
1900
1901 Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1902   if (!RetainCallee) {
1903     LLVMContext &C = M->getContext();
1904     Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1905     AttributeSet Attribute =
1906       AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
1907                             Attribute::get(C, Attribute::NoUnwind));
1908     RetainCallee =
1909       M->getOrInsertFunction(
1910         "objc_retain",
1911         FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1912         Attribute);
1913   }
1914   return RetainCallee;
1915 }
1916
1917 Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1918   if (!RetainBlockCallee) {
1919     LLVMContext &C = M->getContext();
1920     Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1921     // objc_retainBlock is not nounwind because it calls user copy constructors
1922     // which could theoretically throw.
1923     RetainBlockCallee =
1924       M->getOrInsertFunction(
1925         "objc_retainBlock",
1926         FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1927         AttributeSet());
1928   }
1929   return RetainBlockCallee;
1930 }
1931
1932 Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1933   if (!AutoreleaseCallee) {
1934     LLVMContext &C = M->getContext();
1935     Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1936     AttributeSet Attribute =
1937       AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
1938                             Attribute::get(C, Attribute::NoUnwind));
1939     AutoreleaseCallee =
1940       M->getOrInsertFunction(
1941         "objc_autorelease",
1942         FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1943         Attribute);
1944   }
1945   return AutoreleaseCallee;
1946 }
1947
1948 /// Test whether the given value is possible a reference-counted pointer,
1949 /// including tests which utilize AliasAnalysis.
1950 static bool IsPotentialUse(const Value *Op, AliasAnalysis &AA) {
1951   // First make the rudimentary check.
1952   if (!IsPotentialUse(Op))
1953     return false;
1954
1955   // Objects in constant memory are not reference-counted.
1956   if (AA.pointsToConstantMemory(Op))
1957     return false;
1958
1959   // Pointers in constant memory are not pointing to reference-counted objects.
1960   if (const LoadInst *LI = dyn_cast<LoadInst>(Op))
1961     if (AA.pointsToConstantMemory(LI->getPointerOperand()))
1962       return false;
1963
1964   // Otherwise assume the worst.
1965   return true;
1966 }
1967
1968 /// Test whether the given instruction can result in a reference count
1969 /// modification (positive or negative) for the pointer's object.
1970 static bool
1971 CanAlterRefCount(const Instruction *Inst, const Value *Ptr,
1972                  ProvenanceAnalysis &PA, InstructionClass Class) {
1973   switch (Class) {
1974   case IC_Autorelease:
1975   case IC_AutoreleaseRV:
1976   case IC_User:
1977     // These operations never directly modify a reference count.
1978     return false;
1979   default: break;
1980   }
1981
1982   ImmutableCallSite CS = static_cast<const Value *>(Inst);
1983   assert(CS && "Only calls can alter reference counts!");
1984
1985   // See if AliasAnalysis can help us with the call.
1986   AliasAnalysis::ModRefBehavior MRB = PA.getAA()->getModRefBehavior(CS);
1987   if (AliasAnalysis::onlyReadsMemory(MRB))
1988     return false;
1989   if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
1990     for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1991          I != E; ++I) {
1992       const Value *Op = *I;
1993       if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
1994         return true;
1995     }
1996     return false;
1997   }
1998
1999   // Assume the worst.
2000   return true;
2001 }
2002
2003 /// Test whether the given instruction can "use" the given pointer's object in a
2004 /// way that requires the reference count to be positive.
2005 static bool
2006 CanUse(const Instruction *Inst, const Value *Ptr, ProvenanceAnalysis &PA,
2007        InstructionClass Class) {
2008   // IC_Call operations (as opposed to IC_CallOrUser) never "use" objc pointers.
2009   if (Class == IC_Call)
2010     return false;
2011
2012   // Consider various instructions which may have pointer arguments which are
2013   // not "uses".
2014   if (const ICmpInst *ICI = dyn_cast<ICmpInst>(Inst)) {
2015     // Comparing a pointer with null, or any other constant, isn't really a use,
2016     // because we don't care what the pointer points to, or about the values
2017     // of any other dynamic reference-counted pointers.
2018     if (!IsPotentialUse(ICI->getOperand(1), *PA.getAA()))
2019       return false;
2020   } else if (ImmutableCallSite CS = static_cast<const Value *>(Inst)) {
2021     // For calls, just check the arguments (and not the callee operand).
2022     for (ImmutableCallSite::arg_iterator OI = CS.arg_begin(),
2023          OE = CS.arg_end(); OI != OE; ++OI) {
2024       const Value *Op = *OI;
2025       if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
2026         return true;
2027     }
2028     return false;
2029   } else if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
2030     // Special-case stores, because we don't care about the stored value, just
2031     // the store address.
2032     const Value *Op = GetUnderlyingObjCPtr(SI->getPointerOperand());
2033     // If we can't tell what the underlying object was, assume there is a
2034     // dependence.
2035     return IsPotentialUse(Op, *PA.getAA()) && PA.related(Op, Ptr);
2036   }
2037
2038   // Check each operand for a match.
2039   for (User::const_op_iterator OI = Inst->op_begin(), OE = Inst->op_end();
2040        OI != OE; ++OI) {
2041     const Value *Op = *OI;
2042     if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
2043       return true;
2044   }
2045   return false;
2046 }
2047
2048 /// Test whether the given instruction can autorelease any pointer or cause an
2049 /// autoreleasepool pop.
2050 static bool
2051 CanInterruptRV(InstructionClass Class) {
2052   switch (Class) {
2053   case IC_AutoreleasepoolPop:
2054   case IC_CallOrUser:
2055   case IC_Call:
2056   case IC_Autorelease:
2057   case IC_AutoreleaseRV:
2058   case IC_FusedRetainAutorelease:
2059   case IC_FusedRetainAutoreleaseRV:
2060     return true;
2061   default:
2062     return false;
2063   }
2064 }
2065
2066 namespace {
2067   /// \enum DependenceKind
2068   /// \brief Defines different dependence kinds among various ARC constructs.
2069   ///
2070   /// There are several kinds of dependence-like concepts in use here.
2071   ///
2072   enum DependenceKind {
2073     NeedsPositiveRetainCount,
2074     AutoreleasePoolBoundary,
2075     CanChangeRetainCount,
2076     RetainAutoreleaseDep,       ///< Blocks objc_retainAutorelease.
2077     RetainAutoreleaseRVDep,     ///< Blocks objc_retainAutoreleaseReturnValue.
2078     RetainRVDep                 ///< Blocks objc_retainAutoreleasedReturnValue.
2079   };
2080 }
2081
2082 /// Test if there can be dependencies on Inst through Arg. This function only
2083 /// tests dependencies relevant for removing pairs of calls.
2084 static bool
2085 Depends(DependenceKind Flavor, Instruction *Inst, const Value *Arg,
2086         ProvenanceAnalysis &PA) {
2087   // If we've reached the definition of Arg, stop.
2088   if (Inst == Arg)
2089     return true;
2090
2091   switch (Flavor) {
2092   case NeedsPositiveRetainCount: {
2093     InstructionClass Class = GetInstructionClass(Inst);
2094     switch (Class) {
2095     case IC_AutoreleasepoolPop:
2096     case IC_AutoreleasepoolPush:
2097     case IC_None:
2098       return false;
2099     default:
2100       return CanUse(Inst, Arg, PA, Class);
2101     }
2102   }
2103
2104   case AutoreleasePoolBoundary: {
2105     InstructionClass Class = GetInstructionClass(Inst);
2106     switch (Class) {
2107     case IC_AutoreleasepoolPop:
2108     case IC_AutoreleasepoolPush:
2109       // These mark the end and begin of an autorelease pool scope.
2110       return true;
2111     default:
2112       // Nothing else does this.
2113       return false;
2114     }
2115   }
2116
2117   case CanChangeRetainCount: {
2118     InstructionClass Class = GetInstructionClass(Inst);
2119     switch (Class) {
2120     case IC_AutoreleasepoolPop:
2121       // Conservatively assume this can decrement any count.
2122       return true;
2123     case IC_AutoreleasepoolPush:
2124     case IC_None:
2125       return false;
2126     default:
2127       return CanAlterRefCount(Inst, Arg, PA, Class);
2128     }
2129   }
2130
2131   case RetainAutoreleaseDep:
2132     switch (GetBasicInstructionClass(Inst)) {
2133     case IC_AutoreleasepoolPop:
2134     case IC_AutoreleasepoolPush:
2135       // Don't merge an objc_autorelease with an objc_retain inside a different
2136       // autoreleasepool scope.
2137       return true;
2138     case IC_Retain:
2139     case IC_RetainRV:
2140       // Check for a retain of the same pointer for merging.
2141       return GetObjCArg(Inst) == Arg;
2142     default:
2143       // Nothing else matters for objc_retainAutorelease formation.
2144       return false;
2145     }
2146
2147   case RetainAutoreleaseRVDep: {
2148     InstructionClass Class = GetBasicInstructionClass(Inst);
2149     switch (Class) {
2150     case IC_Retain:
2151     case IC_RetainRV:
2152       // Check for a retain of the same pointer for merging.
2153       return GetObjCArg(Inst) == Arg;
2154     default:
2155       // Anything that can autorelease interrupts
2156       // retainAutoreleaseReturnValue formation.
2157       return CanInterruptRV(Class);
2158     }
2159   }
2160
2161   case RetainRVDep:
2162     return CanInterruptRV(GetBasicInstructionClass(Inst));
2163   }
2164
2165   llvm_unreachable("Invalid dependence flavor");
2166 }
2167
2168 /// Walk up the CFG from StartPos (which is in StartBB) and find local and
2169 /// non-local dependencies on Arg.
2170 ///
2171 /// TODO: Cache results?
2172 static void
2173 FindDependencies(DependenceKind Flavor,
2174                  const Value *Arg,
2175                  BasicBlock *StartBB, Instruction *StartInst,
2176                  SmallPtrSet<Instruction *, 4> &DependingInstructions,
2177                  SmallPtrSet<const BasicBlock *, 4> &Visited,
2178                  ProvenanceAnalysis &PA) {
2179   BasicBlock::iterator StartPos = StartInst;
2180
2181   SmallVector<std::pair<BasicBlock *, BasicBlock::iterator>, 4> Worklist;
2182   Worklist.push_back(std::make_pair(StartBB, StartPos));
2183   do {
2184     std::pair<BasicBlock *, BasicBlock::iterator> Pair =
2185       Worklist.pop_back_val();
2186     BasicBlock *LocalStartBB = Pair.first;
2187     BasicBlock::iterator LocalStartPos = Pair.second;
2188     BasicBlock::iterator StartBBBegin = LocalStartBB->begin();
2189     for (;;) {
2190       if (LocalStartPos == StartBBBegin) {
2191         pred_iterator PI(LocalStartBB), PE(LocalStartBB, false);
2192         if (PI == PE)
2193           // If we've reached the function entry, produce a null dependence.
2194           DependingInstructions.insert(0);
2195         else
2196           // Add the predecessors to the worklist.
2197           do {
2198             BasicBlock *PredBB = *PI;
2199             if (Visited.insert(PredBB))
2200               Worklist.push_back(std::make_pair(PredBB, PredBB->end()));
2201           } while (++PI != PE);
2202         break;
2203       }
2204
2205       Instruction *Inst = --LocalStartPos;
2206       if (Depends(Flavor, Inst, Arg, PA)) {
2207         DependingInstructions.insert(Inst);
2208         break;
2209       }
2210     }
2211   } while (!Worklist.empty());
2212
2213   // Determine whether the original StartBB post-dominates all of the blocks we
2214   // visited. If not, insert a sentinal indicating that most optimizations are
2215   // not safe.
2216   for (SmallPtrSet<const BasicBlock *, 4>::const_iterator I = Visited.begin(),
2217        E = Visited.end(); I != E; ++I) {
2218     const BasicBlock *BB = *I;
2219     if (BB == StartBB)
2220       continue;
2221     const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2222     for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2223       const BasicBlock *Succ = *SI;
2224       if (Succ != StartBB && !Visited.count(Succ)) {
2225         DependingInstructions.insert(reinterpret_cast<Instruction *>(-1));
2226         return;
2227       }
2228     }
2229   }
2230 }
2231
2232 static bool isNullOrUndef(const Value *V) {
2233   return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
2234 }
2235
2236 static bool isNoopInstruction(const Instruction *I) {
2237   return isa<BitCastInst>(I) ||
2238          (isa<GetElementPtrInst>(I) &&
2239           cast<GetElementPtrInst>(I)->hasAllZeroIndices());
2240 }
2241
2242 /// Turn objc_retain into objc_retainAutoreleasedReturnValue if the operand is a
2243 /// return value.
2244 void
2245 ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) {
2246   ImmutableCallSite CS(GetObjCArg(Retain));
2247   const Instruction *Call = CS.getInstruction();
2248   if (!Call) return;
2249   if (Call->getParent() != Retain->getParent()) return;
2250
2251   // Check that the call is next to the retain.
2252   BasicBlock::const_iterator I = Call;
2253   ++I;
2254   while (isNoopInstruction(I)) ++I;
2255   if (&*I != Retain)
2256     return;
2257
2258   // Turn it to an objc_retainAutoreleasedReturnValue..
2259   Changed = true;
2260   ++NumPeeps;
2261
2262   DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainCall: Transforming "
2263                   "objc_retain => objc_retainAutoreleasedReturnValue"
2264                   " since the operand is a return value.\n"
2265                   "                                Old: "
2266                << *Retain << "\n");
2267
2268   cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent()));
2269
2270   DEBUG(dbgs() << "                                New: "
2271                << *Retain << "\n");
2272 }
2273
2274 /// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is
2275 /// not a return value.  Or, if it can be paired with an
2276 /// objc_autoreleaseReturnValue, delete the pair and return true.
2277 bool
2278 ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
2279   // Check for the argument being from an immediately preceding call or invoke.
2280   const Value *Arg = GetObjCArg(RetainRV);
2281   ImmutableCallSite CS(Arg);
2282   if (const Instruction *Call = CS.getInstruction()) {
2283     if (Call->getParent() == RetainRV->getParent()) {
2284       BasicBlock::const_iterator I = Call;
2285       ++I;
2286       while (isNoopInstruction(I)) ++I;
2287       if (&*I == RetainRV)
2288         return false;
2289     } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
2290       BasicBlock *RetainRVParent = RetainRV->getParent();
2291       if (II->getNormalDest() == RetainRVParent) {
2292         BasicBlock::const_iterator I = RetainRVParent->begin();
2293         while (isNoopInstruction(I)) ++I;
2294         if (&*I == RetainRV)
2295           return false;
2296       }
2297     }
2298   }
2299
2300   // Check for being preceded by an objc_autoreleaseReturnValue on the same
2301   // pointer. In this case, we can delete the pair.
2302   BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
2303   if (I != Begin) {
2304     do --I; while (I != Begin && isNoopInstruction(I));
2305     if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
2306         GetObjCArg(I) == Arg) {
2307       Changed = true;
2308       ++NumPeeps;
2309
2310       DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainRVCall: Erasing " << *I << "\n"
2311                    << "                                  Erasing " << *RetainRV
2312                    << "\n");
2313
2314       EraseInstruction(I);
2315       EraseInstruction(RetainRV);
2316       return true;
2317     }
2318   }
2319
2320   // Turn it to a plain objc_retain.
2321   Changed = true;
2322   ++NumPeeps;
2323
2324   DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainRVCall: Transforming "
2325                   "objc_retainAutoreleasedReturnValue => "
2326                   "objc_retain since the operand is not a return value.\n"
2327                   "                                  Old: "
2328                << *RetainRV << "\n");
2329
2330   cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
2331
2332   DEBUG(dbgs() << "                                  New: "
2333                << *RetainRV << "\n");
2334
2335   return false;
2336 }
2337
2338 /// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not
2339 /// used as a return value.
2340 void
2341 ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
2342                                       InstructionClass &Class) {
2343   // Check for a return of the pointer value.
2344   const Value *Ptr = GetObjCArg(AutoreleaseRV);
2345   SmallVector<const Value *, 2> Users;
2346   Users.push_back(Ptr);
2347   do {
2348     Ptr = Users.pop_back_val();
2349     for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
2350          UI != UE; ++UI) {
2351       const User *I = *UI;
2352       if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
2353         return;
2354       if (isa<BitCastInst>(I))
2355         Users.push_back(I);
2356     }
2357   } while (!Users.empty());
2358
2359   Changed = true;
2360   ++NumPeeps;
2361
2362   DEBUG(dbgs() << "ObjCARCOpt::OptimizeAutoreleaseRVCall: Transforming "
2363                   "objc_autoreleaseReturnValue => "
2364                   "objc_autorelease since its operand is not used as a return "
2365                   "value.\n"
2366                   "                                       Old: "
2367                << *AutoreleaseRV << "\n");
2368
2369   CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
2370   AutoreleaseRVCI->
2371     setCalledFunction(getAutoreleaseCallee(F.getParent()));
2372   AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
2373   Class = IC_Autorelease;
2374
2375   DEBUG(dbgs() << "                                       New: "
2376                << *AutoreleaseRV << "\n");
2377
2378 }
2379
2380 /// Visit each call, one at a time, and make simplifications without doing any
2381 /// additional analysis.
2382 void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
2383   // Reset all the flags in preparation for recomputing them.
2384   UsedInThisFunction = 0;
2385
2386   // Visit all objc_* calls in F.
2387   for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2388     Instruction *Inst = &*I++;
2389
2390     DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Visiting: " <<
2391           *Inst << "\n");
2392
2393     InstructionClass Class = GetBasicInstructionClass(Inst);
2394
2395     switch (Class) {
2396     default: break;
2397
2398     // Delete no-op casts. These function calls have special semantics, but
2399     // the semantics are entirely implemented via lowering in the front-end,
2400     // so by the time they reach the optimizer, they are just no-op calls
2401     // which return their argument.
2402     //
2403     // There are gray areas here, as the ability to cast reference-counted
2404     // pointers to raw void* and back allows code to break ARC assumptions,
2405     // however these are currently considered to be unimportant.
2406     case IC_NoopCast:
2407       Changed = true;
2408       ++NumNoops;
2409       DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Erasing no-op cast:"
2410                    " " << *Inst << "\n");
2411       EraseInstruction(Inst);
2412       continue;
2413
2414     // If the pointer-to-weak-pointer is null, it's undefined behavior.
2415     case IC_StoreWeak:
2416     case IC_LoadWeak:
2417     case IC_LoadWeakRetained:
2418     case IC_InitWeak:
2419     case IC_DestroyWeak: {
2420       CallInst *CI = cast<CallInst>(Inst);
2421       if (isNullOrUndef(CI->getArgOperand(0))) {
2422         Changed = true;
2423         Type *Ty = CI->getArgOperand(0)->getType();
2424         new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2425                       Constant::getNullValue(Ty),
2426                       CI);
2427         llvm::Value *NewValue = UndefValue::get(CI->getType());
2428         DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: A null "
2429                         "pointer-to-weak-pointer is undefined behavior.\n"
2430                         "                                     Old = " << *CI <<
2431                         "\n                                     New = " <<
2432                         *NewValue << "\n");
2433         CI->replaceAllUsesWith(NewValue);
2434         CI->eraseFromParent();
2435         continue;
2436       }
2437       break;
2438     }
2439     case IC_CopyWeak:
2440     case IC_MoveWeak: {
2441       CallInst *CI = cast<CallInst>(Inst);
2442       if (isNullOrUndef(CI->getArgOperand(0)) ||
2443           isNullOrUndef(CI->getArgOperand(1))) {
2444         Changed = true;
2445         Type *Ty = CI->getArgOperand(0)->getType();
2446         new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2447                       Constant::getNullValue(Ty),
2448                       CI);
2449
2450         llvm::Value *NewValue = UndefValue::get(CI->getType());
2451         DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: A null "
2452                         "pointer-to-weak-pointer is undefined behavior.\n"
2453                         "                                     Old = " << *CI <<
2454                         "\n                                     New = " <<
2455                         *NewValue << "\n");
2456
2457         CI->replaceAllUsesWith(NewValue);
2458         CI->eraseFromParent();
2459         continue;
2460       }
2461       break;
2462     }
2463     case IC_Retain:
2464       OptimizeRetainCall(F, Inst);
2465       break;
2466     case IC_RetainRV:
2467       if (OptimizeRetainRVCall(F, Inst))
2468         continue;
2469       break;
2470     case IC_AutoreleaseRV:
2471       OptimizeAutoreleaseRVCall(F, Inst, Class);
2472       break;
2473     }
2474
2475     // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
2476     if (IsAutorelease(Class) && Inst->use_empty()) {
2477       CallInst *Call = cast<CallInst>(Inst);
2478       const Value *Arg = Call->getArgOperand(0);
2479       Arg = FindSingleUseIdentifiedObject(Arg);
2480       if (Arg) {
2481         Changed = true;
2482         ++NumAutoreleases;
2483
2484         // Create the declaration lazily.
2485         LLVMContext &C = Inst->getContext();
2486         CallInst *NewCall =
2487           CallInst::Create(getReleaseCallee(F.getParent()),
2488                            Call->getArgOperand(0), "", Call);
2489         NewCall->setMetadata(ImpreciseReleaseMDKind,
2490                              MDNode::get(C, ArrayRef<Value *>()));
2491
2492         DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Replacing "
2493                         "objc_autorelease(x) with objc_release(x) since x is "
2494                         "otherwise unused.\n"
2495                         "                                     Old: " << *Call <<
2496                         "\n                                     New: " <<
2497                         *NewCall << "\n");
2498
2499         EraseInstruction(Call);
2500         Inst = NewCall;
2501         Class = IC_Release;
2502       }
2503     }
2504
2505     // For functions which can never be passed stack arguments, add
2506     // a tail keyword.
2507     if (IsAlwaysTail(Class)) {
2508       Changed = true;
2509       DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Adding tail keyword"
2510             " to function since it can never be passed stack args: " << *Inst <<
2511             "\n");
2512       cast<CallInst>(Inst)->setTailCall();
2513     }
2514
2515     // Ensure that functions that can never have a "tail" keyword due to the
2516     // semantics of ARC truly do not do so.
2517     if (IsNeverTail(Class)) {
2518       Changed = true;
2519       DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Removing tail "
2520             "keyword from function: " << *Inst <<
2521             "\n");
2522       cast<CallInst>(Inst)->setTailCall(false);
2523     }
2524
2525     // Set nounwind as needed.
2526     if (IsNoThrow(Class)) {
2527       Changed = true;
2528       DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Found no throw"
2529             " class. Setting nounwind on: " << *Inst << "\n");
2530       cast<CallInst>(Inst)->setDoesNotThrow();
2531     }
2532
2533     if (!IsNoopOnNull(Class)) {
2534       UsedInThisFunction |= 1 << Class;
2535       continue;
2536     }
2537
2538     const Value *Arg = GetObjCArg(Inst);
2539
2540     // ARC calls with null are no-ops. Delete them.
2541     if (isNullOrUndef(Arg)) {
2542       Changed = true;
2543       ++NumNoops;
2544       DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: ARC calls with "
2545             " null are no-ops. Erasing: " << *Inst << "\n");
2546       EraseInstruction(Inst);
2547       continue;
2548     }
2549
2550     // Keep track of which of retain, release, autorelease, and retain_block
2551     // are actually present in this function.
2552     UsedInThisFunction |= 1 << Class;
2553
2554     // If Arg is a PHI, and one or more incoming values to the
2555     // PHI are null, and the call is control-equivalent to the PHI, and there
2556     // are no relevant side effects between the PHI and the call, the call
2557     // could be pushed up to just those paths with non-null incoming values.
2558     // For now, don't bother splitting critical edges for this.
2559     SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
2560     Worklist.push_back(std::make_pair(Inst, Arg));
2561     do {
2562       std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
2563       Inst = Pair.first;
2564       Arg = Pair.second;
2565
2566       const PHINode *PN = dyn_cast<PHINode>(Arg);
2567       if (!PN) continue;
2568
2569       // Determine if the PHI has any null operands, or any incoming
2570       // critical edges.
2571       bool HasNull = false;
2572       bool HasCriticalEdges = false;
2573       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2574         Value *Incoming =
2575           StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2576         if (isNullOrUndef(Incoming))
2577           HasNull = true;
2578         else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
2579                    .getNumSuccessors() != 1) {
2580           HasCriticalEdges = true;
2581           break;
2582         }
2583       }
2584       // If we have null operands and no critical edges, optimize.
2585       if (!HasCriticalEdges && HasNull) {
2586         SmallPtrSet<Instruction *, 4> DependingInstructions;
2587         SmallPtrSet<const BasicBlock *, 4> Visited;
2588
2589         // Check that there is nothing that cares about the reference
2590         // count between the call and the phi.
2591         switch (Class) {
2592         case IC_Retain:
2593         case IC_RetainBlock:
2594           // These can always be moved up.
2595           break;
2596         case IC_Release:
2597           // These can't be moved across things that care about the retain
2598           // count.
2599           FindDependencies(NeedsPositiveRetainCount, Arg,
2600                            Inst->getParent(), Inst,
2601                            DependingInstructions, Visited, PA);
2602           break;
2603         case IC_Autorelease:
2604           // These can't be moved across autorelease pool scope boundaries.
2605           FindDependencies(AutoreleasePoolBoundary, Arg,
2606                            Inst->getParent(), Inst,
2607                            DependingInstructions, Visited, PA);
2608           break;
2609         case IC_RetainRV:
2610         case IC_AutoreleaseRV:
2611           // Don't move these; the RV optimization depends on the autoreleaseRV
2612           // being tail called, and the retainRV being immediately after a call
2613           // (which might still happen if we get lucky with codegen layout, but
2614           // it's not worth taking the chance).
2615           continue;
2616         default:
2617           llvm_unreachable("Invalid dependence flavor");
2618         }
2619
2620         if (DependingInstructions.size() == 1 &&
2621             *DependingInstructions.begin() == PN) {
2622           Changed = true;
2623           ++NumPartialNoops;
2624           // Clone the call into each predecessor that has a non-null value.
2625           CallInst *CInst = cast<CallInst>(Inst);
2626           Type *ParamTy = CInst->getArgOperand(0)->getType();
2627           for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2628             Value *Incoming =
2629               StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2630             if (!isNullOrUndef(Incoming)) {
2631               CallInst *Clone = cast<CallInst>(CInst->clone());
2632               Value *Op = PN->getIncomingValue(i);
2633               Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
2634               if (Op->getType() != ParamTy)
2635                 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
2636               Clone->setArgOperand(0, Op);
2637               Clone->insertBefore(InsertPos);
2638
2639               DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Cloning "
2640                            << *CInst << "\n"
2641                            "                                     And inserting "
2642                            "clone at " << *InsertPos << "\n");
2643               Worklist.push_back(std::make_pair(Clone, Incoming));
2644             }
2645           }
2646           // Erase the original call.
2647           DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
2648           EraseInstruction(CInst);
2649           continue;
2650         }
2651       }
2652     } while (!Worklist.empty());
2653   }
2654   DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Finished List.\n");
2655 }
2656
2657 /// Check for critical edges, loop boundaries, irreducible control flow, or
2658 /// other CFG structures where moving code across the edge would result in it
2659 /// being executed more.
2660 void
2661 ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
2662                                DenseMap<const BasicBlock *, BBState> &BBStates,
2663                                BBState &MyStates) const {
2664   // If any top-down local-use or possible-dec has a succ which is earlier in
2665   // the sequence, forget it.
2666   for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
2667        E = MyStates.top_down_ptr_end(); I != E; ++I)
2668     switch (I->second.GetSeq()) {
2669     default: break;
2670     case S_Use: {
2671       const Value *Arg = I->first;
2672       const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2673       bool SomeSuccHasSame = false;
2674       bool AllSuccsHaveSame = true;
2675       PtrState &S = I->second;
2676       succ_const_iterator SI(TI), SE(TI, false);
2677
2678       // If the terminator is an invoke marked with the
2679       // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
2680       // ignored, for ARC purposes.
2681       if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind)) {
2682         DEBUG(dbgs() << "ObjCARCOpt::CheckForCFGHazards: Found an invoke "
2683                         "terminator marked with "
2684                         "clang.arc.no_objc_arc_exceptions. Ignoring unwind "
2685                         "edge.\n");
2686         --SE;
2687       }
2688
2689       for (; SI != SE; ++SI) {
2690         Sequence SuccSSeq = S_None;
2691         bool SuccSRRIKnownSafe = false;
2692         // If VisitBottomUp has pointer information for this successor, take
2693         // what we know about it.
2694         DenseMap<const BasicBlock *, BBState>::iterator BBI =
2695           BBStates.find(*SI);
2696         assert(BBI != BBStates.end());
2697         const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2698         SuccSSeq = SuccS.GetSeq();
2699         SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
2700         switch (SuccSSeq) {
2701         case S_None:
2702         case S_CanRelease: {
2703           if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
2704             S.ClearSequenceProgress();
2705             break;
2706           }
2707           continue;
2708         }
2709         case S_Use:
2710           SomeSuccHasSame = true;
2711           break;
2712         case S_Stop:
2713         case S_Release:
2714         case S_MovableRelease:
2715           if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
2716             AllSuccsHaveSame = false;
2717           break;
2718         case S_Retain:
2719           llvm_unreachable("bottom-up pointer in retain state!");
2720         }
2721       }
2722       // If the state at the other end of any of the successor edges
2723       // matches the current state, require all edges to match. This
2724       // guards against loops in the middle of a sequence.
2725       if (SomeSuccHasSame && !AllSuccsHaveSame)
2726         S.ClearSequenceProgress();
2727       break;
2728     }
2729     case S_CanRelease: {
2730       const Value *Arg = I->first;
2731       const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2732       bool SomeSuccHasSame = false;
2733       bool AllSuccsHaveSame = true;
2734       PtrState &S = I->second;
2735       succ_const_iterator SI(TI), SE(TI, false);
2736
2737       // If the terminator is an invoke marked with the
2738       // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
2739       // ignored, for ARC purposes.
2740       if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind)) {
2741         DEBUG(dbgs() << "ObjCARCOpt::CheckForCFGHazards: Found an invoke "
2742                         "terminator marked with "
2743                         "clang.arc.no_objc_arc_exceptions. Ignoring unwind "
2744                         "edge.\n");
2745         --SE;
2746       }
2747
2748       for (; SI != SE; ++SI) {
2749         Sequence SuccSSeq = S_None;
2750         bool SuccSRRIKnownSafe = false;
2751         // If VisitBottomUp has pointer information for this successor, take
2752         // what we know about it.
2753         DenseMap<const BasicBlock *, BBState>::iterator BBI =
2754           BBStates.find(*SI);
2755         assert(BBI != BBStates.end());
2756         const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2757         SuccSSeq = SuccS.GetSeq();
2758         SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
2759         switch (SuccSSeq) {
2760         case S_None: {
2761           if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
2762             S.ClearSequenceProgress();
2763             break;
2764           }
2765           continue;
2766         }
2767         case S_CanRelease:
2768           SomeSuccHasSame = true;
2769           break;
2770         case S_Stop:
2771         case S_Release:
2772         case S_MovableRelease:
2773         case S_Use:
2774           if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
2775             AllSuccsHaveSame = false;
2776           break;
2777         case S_Retain:
2778           llvm_unreachable("bottom-up pointer in retain state!");
2779         }
2780       }
2781       // If the state at the other end of any of the successor edges
2782       // matches the current state, require all edges to match. This
2783       // guards against loops in the middle of a sequence.
2784       if (SomeSuccHasSame && !AllSuccsHaveSame)
2785         S.ClearSequenceProgress();
2786       break;
2787     }
2788     }
2789 }
2790
2791 bool
2792 ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
2793                                      BasicBlock *BB,
2794                                      MapVector<Value *, RRInfo> &Retains,
2795                                      BBState &MyStates) {
2796   bool NestingDetected = false;
2797   InstructionClass Class = GetInstructionClass(Inst);
2798   const Value *Arg = 0;
2799
2800   switch (Class) {
2801   case IC_Release: {
2802     Arg = GetObjCArg(Inst);
2803
2804     PtrState &S = MyStates.getPtrBottomUpState(Arg);
2805
2806     // If we see two releases in a row on the same pointer. If so, make
2807     // a note, and we'll cicle back to revisit it after we've
2808     // hopefully eliminated the second release, which may allow us to
2809     // eliminate the first release too.
2810     // Theoretically we could implement removal of nested retain+release
2811     // pairs by making PtrState hold a stack of states, but this is
2812     // simple and avoids adding overhead for the non-nested case.
2813     if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease) {
2814       DEBUG(dbgs() << "ObjCARCOpt::VisitInstructionBottomUp: Found nested "
2815                       "releases (i.e. a release pair)\n");
2816       NestingDetected = true;
2817     }
2818
2819     MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2820     S.ResetSequenceProgress(ReleaseMetadata ? S_MovableRelease : S_Release);
2821     S.RRI.ReleaseMetadata = ReleaseMetadata;
2822     S.RRI.KnownSafe = S.IsKnownIncremented();
2823     S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2824     S.RRI.Calls.insert(Inst);
2825
2826     S.SetKnownPositiveRefCount();
2827     break;
2828   }
2829   case IC_RetainBlock:
2830     // An objc_retainBlock call with just a use may need to be kept,
2831     // because it may be copying a block from the stack to the heap.
2832     if (!IsRetainBlockOptimizable(Inst))
2833       break;
2834     // FALLTHROUGH
2835   case IC_Retain:
2836   case IC_RetainRV: {
2837     Arg = GetObjCArg(Inst);
2838
2839     PtrState &S = MyStates.getPtrBottomUpState(Arg);
2840     S.SetKnownPositiveRefCount();
2841
2842     switch (S.GetSeq()) {
2843     case S_Stop:
2844     case S_Release:
2845     case S_MovableRelease:
2846     case S_Use:
2847       S.RRI.ReverseInsertPts.clear();
2848       // FALL THROUGH
2849     case S_CanRelease:
2850       // Don't do retain+release tracking for IC_RetainRV, because it's
2851       // better to let it remain as the first instruction after a call.
2852       if (Class != IC_RetainRV) {
2853         S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2854         Retains[Inst] = S.RRI;
2855       }
2856       S.ClearSequenceProgress();
2857       break;
2858     case S_None:
2859       break;
2860     case S_Retain:
2861       llvm_unreachable("bottom-up pointer in retain state!");
2862     }
2863     return NestingDetected;
2864   }
2865   case IC_AutoreleasepoolPop:
2866     // Conservatively, clear MyStates for all known pointers.
2867     MyStates.clearBottomUpPointers();
2868     return NestingDetected;
2869   case IC_AutoreleasepoolPush:
2870   case IC_None:
2871     // These are irrelevant.
2872     return NestingDetected;
2873   default:
2874     break;
2875   }
2876
2877   // Consider any other possible effects of this instruction on each
2878   // pointer being tracked.
2879   for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
2880        ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
2881     const Value *Ptr = MI->first;
2882     if (Ptr == Arg)
2883       continue; // Handled above.
2884     PtrState &S = MI->second;
2885     Sequence Seq = S.GetSeq();
2886
2887     // Check for possible releases.
2888     if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2889       S.ClearRefCount();
2890       switch (Seq) {
2891       case S_Use:
2892         S.SetSeq(S_CanRelease);
2893         continue;
2894       case S_CanRelease:
2895       case S_Release:
2896       case S_MovableRelease:
2897       case S_Stop:
2898       case S_None:
2899         break;
2900       case S_Retain:
2901         llvm_unreachable("bottom-up pointer in retain state!");
2902       }
2903     }
2904
2905     // Check for possible direct uses.
2906     switch (Seq) {
2907     case S_Release:
2908     case S_MovableRelease:
2909       if (CanUse(Inst, Ptr, PA, Class)) {
2910         assert(S.RRI.ReverseInsertPts.empty());
2911         // If this is an invoke instruction, we're scanning it as part of
2912         // one of its successor blocks, since we can't insert code after it
2913         // in its own block, and we don't want to split critical edges.
2914         if (isa<InvokeInst>(Inst))
2915           S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2916         else
2917           S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
2918         S.SetSeq(S_Use);
2919       } else if (Seq == S_Release &&
2920                  (Class == IC_User || Class == IC_CallOrUser)) {
2921         // Non-movable releases depend on any possible objc pointer use.
2922         S.SetSeq(S_Stop);
2923         assert(S.RRI.ReverseInsertPts.empty());
2924         // As above; handle invoke specially.
2925         if (isa<InvokeInst>(Inst))
2926           S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2927         else
2928           S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
2929       }
2930       break;
2931     case S_Stop:
2932       if (CanUse(Inst, Ptr, PA, Class))
2933         S.SetSeq(S_Use);
2934       break;
2935     case S_CanRelease:
2936     case S_Use:
2937     case S_None:
2938       break;
2939     case S_Retain:
2940       llvm_unreachable("bottom-up pointer in retain state!");
2941     }
2942   }
2943
2944   return NestingDetected;
2945 }
2946
2947 bool
2948 ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2949                           DenseMap<const BasicBlock *, BBState> &BBStates,
2950                           MapVector<Value *, RRInfo> &Retains) {
2951   bool NestingDetected = false;
2952   BBState &MyStates = BBStates[BB];
2953
2954   // Merge the states from each successor to compute the initial state
2955   // for the current block.
2956   BBState::edge_iterator SI(MyStates.succ_begin()),
2957                          SE(MyStates.succ_end());
2958   if (SI != SE) {
2959     const BasicBlock *Succ = *SI;
2960     DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
2961     assert(I != BBStates.end());
2962     MyStates.InitFromSucc(I->second);
2963     ++SI;
2964     for (; SI != SE; ++SI) {
2965       Succ = *SI;
2966       I = BBStates.find(Succ);
2967       assert(I != BBStates.end());
2968       MyStates.MergeSucc(I->second);
2969     }
2970   }
2971
2972   // Visit all the instructions, bottom-up.
2973   for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2974     Instruction *Inst = llvm::prior(I);
2975
2976     // Invoke instructions are visited as part of their successors (below).
2977     if (isa<InvokeInst>(Inst))
2978       continue;
2979
2980     DEBUG(dbgs() << "ObjCARCOpt::VisitButtonUp: Visiting " << *Inst << "\n");
2981
2982     NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
2983   }
2984
2985   // If there's a predecessor with an invoke, visit the invoke as if it were
2986   // part of this block, since we can't insert code after an invoke in its own
2987   // block, and we don't want to split critical edges.
2988   for (BBState::edge_iterator PI(MyStates.pred_begin()),
2989        PE(MyStates.pred_end()); PI != PE; ++PI) {
2990     BasicBlock *Pred = *PI;
2991     if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
2992       NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
2993   }
2994
2995   return NestingDetected;
2996 }
2997
2998 bool
2999 ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
3000                                     DenseMap<Value *, RRInfo> &Releases,
3001                                     BBState &MyStates) {
3002   bool NestingDetected = false;
3003   InstructionClass Class = GetInstructionClass(Inst);
3004   const Value *Arg = 0;
3005
3006   switch (Class) {
3007   case IC_RetainBlock:
3008     // An objc_retainBlock call with just a use may need to be kept,
3009     // because it may be copying a block from the stack to the heap.
3010     if (!IsRetainBlockOptimizable(Inst))
3011       break;
3012     // FALLTHROUGH
3013   case IC_Retain:
3014   case IC_RetainRV: {
3015     Arg = GetObjCArg(Inst);
3016
3017     PtrState &S = MyStates.getPtrTopDownState(Arg);
3018
3019     // Don't do retain+release tracking for IC_RetainRV, because it's
3020     // better to let it remain as the first instruction after a call.
3021     if (Class != IC_RetainRV) {
3022       // If we see two retains in a row on the same pointer. If so, make
3023       // a note, and we'll cicle back to revisit it after we've
3024       // hopefully eliminated the second retain, which may allow us to
3025       // eliminate the first retain too.
3026       // Theoretically we could implement removal of nested retain+release
3027       // pairs by making PtrState hold a stack of states, but this is
3028       // simple and avoids adding overhead for the non-nested case.
3029       if (S.GetSeq() == S_Retain)
3030         NestingDetected = true;
3031
3032       S.ResetSequenceProgress(S_Retain);
3033       S.RRI.IsRetainBlock = Class == IC_RetainBlock;
3034       S.RRI.KnownSafe = S.IsKnownIncremented();
3035       S.RRI.Calls.insert(Inst);
3036     }
3037
3038     S.SetKnownPositiveRefCount();
3039
3040     // A retain can be a potential use; procede to the generic checking
3041     // code below.
3042     break;
3043   }
3044   case IC_Release: {
3045     Arg = GetObjCArg(Inst);
3046
3047     PtrState &S = MyStates.getPtrTopDownState(Arg);
3048     S.ClearRefCount();
3049
3050     switch (S.GetSeq()) {
3051     case S_Retain:
3052     case S_CanRelease:
3053       S.RRI.ReverseInsertPts.clear();
3054       // FALL THROUGH
3055     case S_Use:
3056       S.RRI.ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
3057       S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
3058       Releases[Inst] = S.RRI;
3059       S.ClearSequenceProgress();
3060       break;
3061     case S_None:
3062       break;
3063     case S_Stop:
3064     case S_Release:
3065     case S_MovableRelease:
3066       llvm_unreachable("top-down pointer in release state!");
3067     }
3068     break;
3069   }
3070   case IC_AutoreleasepoolPop:
3071     // Conservatively, clear MyStates for all known pointers.
3072     MyStates.clearTopDownPointers();
3073     return NestingDetected;
3074   case IC_AutoreleasepoolPush:
3075   case IC_None:
3076     // These are irrelevant.
3077     return NestingDetected;
3078   default:
3079     break;
3080   }
3081
3082   // Consider any other possible effects of this instruction on each
3083   // pointer being tracked.
3084   for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
3085        ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
3086     const Value *Ptr = MI->first;
3087     if (Ptr == Arg)
3088       continue; // Handled above.
3089     PtrState &S = MI->second;
3090     Sequence Seq = S.GetSeq();
3091
3092     // Check for possible releases.
3093     if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
3094       S.ClearRefCount();
3095       switch (Seq) {
3096       case S_Retain:
3097         S.SetSeq(S_CanRelease);
3098         assert(S.RRI.ReverseInsertPts.empty());
3099         S.RRI.ReverseInsertPts.insert(Inst);
3100
3101         // One call can't cause a transition from S_Retain to S_CanRelease
3102         // and S_CanRelease to S_Use. If we've made the first transition,
3103         // we're done.
3104         continue;
3105       case S_Use:
3106       case S_CanRelease:
3107       case S_None:
3108         break;
3109       case S_Stop:
3110       case S_Release:
3111       case S_MovableRelease:
3112         llvm_unreachable("top-down pointer in release state!");
3113       }
3114     }
3115
3116     // Check for possible direct uses.
3117     switch (Seq) {
3118     case S_CanRelease:
3119       if (CanUse(Inst, Ptr, PA, Class))
3120         S.SetSeq(S_Use);
3121       break;
3122     case S_Retain:
3123     case S_Use:
3124     case S_None:
3125       break;
3126     case S_Stop:
3127     case S_Release:
3128     case S_MovableRelease:
3129       llvm_unreachable("top-down pointer in release state!");
3130     }
3131   }
3132
3133   return NestingDetected;
3134 }
3135
3136 bool
3137 ObjCARCOpt::VisitTopDown(BasicBlock *BB,
3138                          DenseMap<const BasicBlock *, BBState> &BBStates,
3139                          DenseMap<Value *, RRInfo> &Releases) {
3140   bool NestingDetected = false;
3141   BBState &MyStates = BBStates[BB];
3142
3143   // Merge the states from each predecessor to compute the initial state
3144   // for the current block.
3145   BBState::edge_iterator PI(MyStates.pred_begin()),
3146                          PE(MyStates.pred_end());
3147   if (PI != PE) {
3148     const BasicBlock *Pred = *PI;
3149     DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
3150     assert(I != BBStates.end());
3151     MyStates.InitFromPred(I->second);
3152     ++PI;
3153     for (; PI != PE; ++PI) {
3154       Pred = *PI;
3155       I = BBStates.find(Pred);
3156       assert(I != BBStates.end());
3157       MyStates.MergePred(I->second);
3158     }
3159   }
3160
3161   // Visit all the instructions, top-down.
3162   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3163     Instruction *Inst = I;
3164
3165     DEBUG(dbgs() << "ObjCARCOpt::VisitTopDown: Visiting " << *Inst << "\n");
3166
3167     NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
3168   }
3169
3170   CheckForCFGHazards(BB, BBStates, MyStates);
3171   return NestingDetected;
3172 }
3173
3174 static void
3175 ComputePostOrders(Function &F,
3176                   SmallVectorImpl<BasicBlock *> &PostOrder,
3177                   SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
3178                   unsigned NoObjCARCExceptionsMDKind,
3179                   DenseMap<const BasicBlock *, BBState> &BBStates) {
3180   /// The visited set, for doing DFS walks.
3181   SmallPtrSet<BasicBlock *, 16> Visited;
3182
3183   // Do DFS, computing the PostOrder.
3184   SmallPtrSet<BasicBlock *, 16> OnStack;
3185   SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
3186
3187   // Functions always have exactly one entry block, and we don't have
3188   // any other block that we treat like an entry block.
3189   BasicBlock *EntryBB = &F.getEntryBlock();
3190   BBState &MyStates = BBStates[EntryBB];
3191   MyStates.SetAsEntry();
3192   TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
3193   SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
3194   Visited.insert(EntryBB);
3195   OnStack.insert(EntryBB);
3196   do {
3197   dfs_next_succ:
3198     BasicBlock *CurrBB = SuccStack.back().first;
3199     TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
3200     succ_iterator SE(TI, false);
3201
3202     // If the terminator is an invoke marked with the
3203     // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
3204     // ignored, for ARC purposes.
3205     if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind)) {
3206         DEBUG(dbgs() << "ObjCARCOpt::ComputePostOrders: Found an invoke "
3207                         "terminator marked with "
3208                         "clang.arc.no_objc_arc_exceptions. Ignoring unwind "
3209                         "edge.\n");
3210       --SE;
3211     }
3212
3213     while (SuccStack.back().second != SE) {
3214       BasicBlock *SuccBB = *SuccStack.back().second++;
3215       if (Visited.insert(SuccBB)) {
3216         TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
3217         SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
3218         BBStates[CurrBB].addSucc(SuccBB);
3219         BBState &SuccStates = BBStates[SuccBB];
3220         SuccStates.addPred(CurrBB);
3221         OnStack.insert(SuccBB);
3222         goto dfs_next_succ;
3223       }
3224
3225       if (!OnStack.count(SuccBB)) {
3226         BBStates[CurrBB].addSucc(SuccBB);
3227         BBStates[SuccBB].addPred(CurrBB);
3228       }
3229     }
3230     OnStack.erase(CurrBB);
3231     PostOrder.push_back(CurrBB);
3232     SuccStack.pop_back();
3233   } while (!SuccStack.empty());
3234
3235   Visited.clear();
3236
3237   // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
3238   // Functions may have many exits, and there also blocks which we treat
3239   // as exits due to ignored edges.
3240   SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
3241   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
3242     BasicBlock *ExitBB = I;
3243     BBState &MyStates = BBStates[ExitBB];
3244     if (!MyStates.isExit())
3245       continue;
3246
3247     MyStates.SetAsExit();
3248
3249     PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
3250     Visited.insert(ExitBB);
3251     while (!PredStack.empty()) {
3252     reverse_dfs_next_succ:
3253       BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
3254       while (PredStack.back().second != PE) {
3255         BasicBlock *BB = *PredStack.back().second++;
3256         if (Visited.insert(BB)) {
3257           PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
3258           goto reverse_dfs_next_succ;
3259         }
3260       }
3261       ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
3262     }
3263   }
3264 }
3265
3266 // Visit the function both top-down and bottom-up.
3267 bool
3268 ObjCARCOpt::Visit(Function &F,
3269                   DenseMap<const BasicBlock *, BBState> &BBStates,
3270                   MapVector<Value *, RRInfo> &Retains,
3271                   DenseMap<Value *, RRInfo> &Releases) {
3272
3273   // Use reverse-postorder traversals, because we magically know that loops
3274   // will be well behaved, i.e. they won't repeatedly call retain on a single
3275   // pointer without doing a release. We can't use the ReversePostOrderTraversal
3276   // class here because we want the reverse-CFG postorder to consider each
3277   // function exit point, and we want to ignore selected cycle edges.
3278   SmallVector<BasicBlock *, 16> PostOrder;
3279   SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
3280   ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
3281                     NoObjCARCExceptionsMDKind,
3282                     BBStates);
3283
3284   // Use reverse-postorder on the reverse CFG for bottom-up.
3285   bool BottomUpNestingDetected = false;
3286   for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
3287        ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
3288        I != E; ++I)
3289     BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
3290
3291   // Use reverse-postorder for top-down.
3292   bool TopDownNestingDetected = false;
3293   for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
3294        PostOrder.rbegin(), E = PostOrder.rend();
3295        I != E; ++I)
3296     TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
3297
3298   return TopDownNestingDetected && BottomUpNestingDetected;
3299 }
3300
3301 /// Move the calls in RetainsToMove and ReleasesToMove.
3302 void ObjCARCOpt::MoveCalls(Value *Arg,
3303                            RRInfo &RetainsToMove,
3304                            RRInfo &ReleasesToMove,
3305                            MapVector<Value *, RRInfo> &Retains,
3306                            DenseMap<Value *, RRInfo> &Releases,
3307                            SmallVectorImpl<Instruction *> &DeadInsts,
3308                            Module *M) {
3309   Type *ArgTy = Arg->getType();
3310   Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
3311
3312   // Insert the new retain and release calls.
3313   for (SmallPtrSet<Instruction *, 2>::const_iterator
3314        PI = ReleasesToMove.ReverseInsertPts.begin(),
3315        PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
3316     Instruction *InsertPt = *PI;
3317     Value *MyArg = ArgTy == ParamTy ? Arg :
3318                    new BitCastInst(Arg, ParamTy, "", InsertPt);
3319     CallInst *Call =
3320       CallInst::Create(RetainsToMove.IsRetainBlock ?
3321                          getRetainBlockCallee(M) : getRetainCallee(M),
3322                        MyArg, "", InsertPt);
3323     Call->setDoesNotThrow();
3324     if (RetainsToMove.IsRetainBlock)
3325       Call->setMetadata(CopyOnEscapeMDKind,
3326                         MDNode::get(M->getContext(), ArrayRef<Value *>()));
3327     else
3328       Call->setTailCall();
3329
3330     DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Inserting new Release: " << *Call
3331                  << "\n"
3332                     "                       At insertion point: " << *InsertPt
3333                  << "\n");
3334   }
3335   for (SmallPtrSet<Instruction *, 2>::const_iterator
3336        PI = RetainsToMove.ReverseInsertPts.begin(),
3337        PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
3338     Instruction *InsertPt = *PI;
3339     Value *MyArg = ArgTy == ParamTy ? Arg :
3340                    new BitCastInst(Arg, ParamTy, "", InsertPt);
3341     CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
3342                                       "", InsertPt);
3343     // Attach a clang.imprecise_release metadata tag, if appropriate.
3344     if (MDNode *M = ReleasesToMove.ReleaseMetadata)
3345       Call->setMetadata(ImpreciseReleaseMDKind, M);
3346     Call->setDoesNotThrow();
3347     if (ReleasesToMove.IsTailCallRelease)
3348       Call->setTailCall();
3349
3350     DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Inserting new Retain: " << *Call
3351                  << "\n"
3352                     "                       At insertion point: " << *InsertPt
3353                  << "\n");
3354   }
3355
3356   // Delete the original retain and release calls.
3357   for (SmallPtrSet<Instruction *, 2>::const_iterator
3358        AI = RetainsToMove.Calls.begin(),
3359        AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
3360     Instruction *OrigRetain = *AI;
3361     Retains.blot(OrigRetain);
3362     DeadInsts.push_back(OrigRetain);
3363     DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Deleting retain: " << *OrigRetain <<
3364                     "\n");
3365   }
3366   for (SmallPtrSet<Instruction *, 2>::const_iterator
3367        AI = ReleasesToMove.Calls.begin(),
3368        AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
3369     Instruction *OrigRelease = *AI;
3370     Releases.erase(OrigRelease);
3371     DeadInsts.push_back(OrigRelease);
3372     DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Deleting release: " << *OrigRelease
3373                  << "\n");
3374   }
3375 }
3376
3377 /// Identify pairings between the retains and releases, and delete and/or move
3378 /// them.
3379 bool
3380 ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
3381                                    &BBStates,
3382                                  MapVector<Value *, RRInfo> &Retains,
3383                                  DenseMap<Value *, RRInfo> &Releases,
3384                                  Module *M) {
3385   bool AnyPairsCompletelyEliminated = false;
3386   RRInfo RetainsToMove;
3387   RRInfo ReleasesToMove;
3388   SmallVector<Instruction *, 4> NewRetains;
3389   SmallVector<Instruction *, 4> NewReleases;
3390   SmallVector<Instruction *, 8> DeadInsts;
3391
3392   // Visit each retain.
3393   for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
3394        E = Retains.end(); I != E; ++I) {
3395     Value *V = I->first;
3396     if (!V) continue; // blotted
3397
3398     Instruction *Retain = cast<Instruction>(V);
3399
3400     DEBUG(dbgs() << "ObjCARCOpt::PerformCodePlacement: Visiting: " << *Retain
3401           << "\n");
3402
3403     Value *Arg = GetObjCArg(Retain);
3404
3405     // If the object being released is in static or stack storage, we know it's
3406     // not being managed by ObjC reference counting, so we can delete pairs
3407     // regardless of what possible decrements or uses lie between them.
3408     bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
3409
3410     // A constant pointer can't be pointing to an object on the heap. It may
3411     // be reference-counted, but it won't be deleted.
3412     if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
3413       if (const GlobalVariable *GV =
3414             dyn_cast<GlobalVariable>(
3415               StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
3416         if (GV->isConstant())
3417           KnownSafe = true;
3418
3419     // If a pair happens in a region where it is known that the reference count
3420     // is already incremented, we can similarly ignore possible decrements.
3421     bool KnownSafeTD = true, KnownSafeBU = true;
3422
3423     // Connect the dots between the top-down-collected RetainsToMove and
3424     // bottom-up-collected ReleasesToMove to form sets of related calls.
3425     // This is an iterative process so that we connect multiple releases
3426     // to multiple retains if needed.
3427     unsigned OldDelta = 0;
3428     unsigned NewDelta = 0;
3429     unsigned OldCount = 0;
3430     unsigned NewCount = 0;
3431     bool FirstRelease = true;
3432     bool FirstRetain = true;
3433     NewRetains.push_back(Retain);
3434     for (;;) {
3435       for (SmallVectorImpl<Instruction *>::const_iterator
3436            NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
3437         Instruction *NewRetain = *NI;
3438         MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
3439         assert(It != Retains.end());
3440         const RRInfo &NewRetainRRI = It->second;
3441         KnownSafeTD &= NewRetainRRI.KnownSafe;
3442         for (SmallPtrSet<Instruction *, 2>::const_iterator
3443              LI = NewRetainRRI.Calls.begin(),
3444              LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
3445           Instruction *NewRetainRelease = *LI;
3446           DenseMap<Value *, RRInfo>::const_iterator Jt =
3447             Releases.find(NewRetainRelease);
3448           if (Jt == Releases.end())
3449             goto next_retain;
3450           const RRInfo &NewRetainReleaseRRI = Jt->second;
3451           assert(NewRetainReleaseRRI.Calls.count(NewRetain));
3452           if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
3453             OldDelta -=
3454               BBStates[NewRetainRelease->getParent()].GetAllPathCount();
3455
3456             // Merge the ReleaseMetadata and IsTailCallRelease values.
3457             if (FirstRelease) {
3458               ReleasesToMove.ReleaseMetadata =
3459                 NewRetainReleaseRRI.ReleaseMetadata;
3460               ReleasesToMove.IsTailCallRelease =
3461                 NewRetainReleaseRRI.IsTailCallRelease;
3462               FirstRelease = false;
3463             } else {
3464               if (ReleasesToMove.ReleaseMetadata !=
3465                     NewRetainReleaseRRI.ReleaseMetadata)
3466                 ReleasesToMove.ReleaseMetadata = 0;
3467               if (ReleasesToMove.IsTailCallRelease !=
3468                     NewRetainReleaseRRI.IsTailCallRelease)
3469                 ReleasesToMove.IsTailCallRelease = false;
3470             }
3471
3472             // Collect the optimal insertion points.
3473             if (!KnownSafe)
3474               for (SmallPtrSet<Instruction *, 2>::const_iterator
3475                    RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
3476                    RE = NewRetainReleaseRRI.ReverseInsertPts.end();
3477                    RI != RE; ++RI) {
3478                 Instruction *RIP = *RI;
3479                 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
3480                   NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
3481               }
3482             NewReleases.push_back(NewRetainRelease);
3483           }
3484         }
3485       }
3486       NewRetains.clear();
3487       if (NewReleases.empty()) break;
3488
3489       // Back the other way.
3490       for (SmallVectorImpl<Instruction *>::const_iterator
3491            NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
3492         Instruction *NewRelease = *NI;
3493         DenseMap<Value *, RRInfo>::const_iterator It =
3494           Releases.find(NewRelease);
3495         assert(It != Releases.end());
3496         const RRInfo &NewReleaseRRI = It->second;
3497         KnownSafeBU &= NewReleaseRRI.KnownSafe;
3498         for (SmallPtrSet<Instruction *, 2>::const_iterator
3499              LI = NewReleaseRRI.Calls.begin(),
3500              LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
3501           Instruction *NewReleaseRetain = *LI;
3502           MapVector<Value *, RRInfo>::const_iterator Jt =
3503             Retains.find(NewReleaseRetain);
3504           if (Jt == Retains.end())
3505             goto next_retain;
3506           const RRInfo &NewReleaseRetainRRI = Jt->second;
3507           assert(NewReleaseRetainRRI.Calls.count(NewRelease));
3508           if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
3509             unsigned PathCount =
3510               BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
3511             OldDelta += PathCount;
3512             OldCount += PathCount;
3513
3514             // Merge the IsRetainBlock values.
3515             if (FirstRetain) {
3516               RetainsToMove.IsRetainBlock = NewReleaseRetainRRI.IsRetainBlock;
3517               FirstRetain = false;
3518             } else if (ReleasesToMove.IsRetainBlock !=
3519                        NewReleaseRetainRRI.IsRetainBlock)
3520               // It's not possible to merge the sequences if one uses
3521               // objc_retain and the other uses objc_retainBlock.
3522               goto next_retain;
3523
3524             // Collect the optimal insertion points.
3525             if (!KnownSafe)
3526               for (SmallPtrSet<Instruction *, 2>::const_iterator
3527                    RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
3528                    RE = NewReleaseRetainRRI.ReverseInsertPts.end();
3529                    RI != RE; ++RI) {
3530                 Instruction *RIP = *RI;
3531                 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
3532                   PathCount = BBStates[RIP->getParent()].GetAllPathCount();
3533                   NewDelta += PathCount;
3534                   NewCount += PathCount;
3535                 }
3536               }
3537             NewRetains.push_back(NewReleaseRetain);
3538           }
3539         }
3540       }
3541       NewReleases.clear();
3542       if (NewRetains.empty()) break;
3543     }
3544
3545     // If the pointer is known incremented or nested, we can safely delete the
3546     // pair regardless of what's between them.
3547     if (KnownSafeTD || KnownSafeBU) {
3548       RetainsToMove.ReverseInsertPts.clear();
3549       ReleasesToMove.ReverseInsertPts.clear();
3550       NewCount = 0;
3551     } else {
3552       // Determine whether the new insertion points we computed preserve the
3553       // balance of retain and release calls through the program.
3554       // TODO: If the fully aggressive solution isn't valid, try to find a
3555       // less aggressive solution which is.
3556       if (NewDelta != 0)
3557         goto next_retain;
3558     }
3559
3560     // Determine whether the original call points are balanced in the retain and
3561     // release calls through the program. If not, conservatively don't touch
3562     // them.
3563     // TODO: It's theoretically possible to do code motion in this case, as
3564     // long as the existing imbalances are maintained.
3565     if (OldDelta != 0)
3566       goto next_retain;
3567
3568     // Ok, everything checks out and we're all set. Let's move some code!
3569     Changed = true;
3570     assert(OldCount != 0 && "Unreachable code?");
3571     AnyPairsCompletelyEliminated = NewCount == 0;
3572     NumRRs += OldCount - NewCount;
3573     MoveCalls(Arg, RetainsToMove, ReleasesToMove,
3574               Retains, Releases, DeadInsts, M);
3575
3576   next_retain:
3577     NewReleases.clear();
3578     NewRetains.clear();
3579     RetainsToMove.clear();
3580     ReleasesToMove.clear();
3581   }
3582
3583   // Now that we're done moving everything, we can delete the newly dead
3584   // instructions, as we no longer need them as insert points.
3585   while (!DeadInsts.empty())
3586     EraseInstruction(DeadInsts.pop_back_val());
3587
3588   return AnyPairsCompletelyEliminated;
3589 }
3590
3591 /// Weak pointer optimizations.
3592 void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
3593   // First, do memdep-style RLE and S2L optimizations. We can't use memdep
3594   // itself because it uses AliasAnalysis and we need to do provenance
3595   // queries instead.
3596   for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3597     Instruction *Inst = &*I++;
3598
3599     DEBUG(dbgs() << "ObjCARCOpt::OptimizeWeakCalls: Visiting: " << *Inst <<
3600           "\n");
3601
3602     InstructionClass Class = GetBasicInstructionClass(Inst);
3603     if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
3604       continue;
3605
3606     // Delete objc_loadWeak calls with no users.
3607     if (Class == IC_LoadWeak && Inst->use_empty()) {
3608       Inst->eraseFromParent();
3609       continue;
3610     }
3611
3612     // TODO: For now, just look for an earlier available version of this value
3613     // within the same block. Theoretically, we could do memdep-style non-local
3614     // analysis too, but that would want caching. A better approach would be to
3615     // use the technique that EarlyCSE uses.
3616     inst_iterator Current = llvm::prior(I);
3617     BasicBlock *CurrentBB = Current.getBasicBlockIterator();
3618     for (BasicBlock::iterator B = CurrentBB->begin(),
3619                               J = Current.getInstructionIterator();
3620          J != B; --J) {
3621       Instruction *EarlierInst = &*llvm::prior(J);
3622       InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
3623       switch (EarlierClass) {
3624       case IC_LoadWeak:
3625       case IC_LoadWeakRetained: {
3626         // If this is loading from the same pointer, replace this load's value
3627         // with that one.
3628         CallInst *Call = cast<CallInst>(Inst);
3629         CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3630         Value *Arg = Call->getArgOperand(0);
3631         Value *EarlierArg = EarlierCall->getArgOperand(0);
3632         switch (PA.getAA()->alias(Arg, EarlierArg)) {
3633         case AliasAnalysis::MustAlias:
3634           Changed = true;
3635           // If the load has a builtin retain, insert a plain retain for it.
3636           if (Class == IC_LoadWeakRetained) {
3637             CallInst *CI =
3638               CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3639                                "", Call);
3640             CI->setTailCall();
3641           }
3642           // Zap the fully redundant load.
3643           Call->replaceAllUsesWith(EarlierCall);
3644           Call->eraseFromParent();
3645           goto clobbered;
3646         case AliasAnalysis::MayAlias:
3647         case AliasAnalysis::PartialAlias:
3648           goto clobbered;
3649         case AliasAnalysis::NoAlias:
3650           break;
3651         }
3652         break;
3653       }
3654       case IC_StoreWeak:
3655       case IC_InitWeak: {
3656         // If this is storing to the same pointer and has the same size etc.
3657         // replace this load's value with the stored value.
3658         CallInst *Call = cast<CallInst>(Inst);
3659         CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3660         Value *Arg = Call->getArgOperand(0);
3661         Value *EarlierArg = EarlierCall->getArgOperand(0);
3662         switch (PA.getAA()->alias(Arg, EarlierArg)) {
3663         case AliasAnalysis::MustAlias:
3664           Changed = true;
3665           // If the load has a builtin retain, insert a plain retain for it.
3666           if (Class == IC_LoadWeakRetained) {
3667             CallInst *CI =
3668               CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3669                                "", Call);
3670             CI->setTailCall();
3671           }
3672           // Zap the fully redundant load.
3673           Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
3674           Call->eraseFromParent();
3675           goto clobbered;
3676         case AliasAnalysis::MayAlias:
3677         case AliasAnalysis::PartialAlias:
3678           goto clobbered;
3679         case AliasAnalysis::NoAlias:
3680           break;
3681         }
3682         break;
3683       }
3684       case IC_MoveWeak:
3685       case IC_CopyWeak:
3686         // TOOD: Grab the copied value.
3687         goto clobbered;
3688       case IC_AutoreleasepoolPush:
3689       case IC_None:
3690       case IC_User:
3691         // Weak pointers are only modified through the weak entry points
3692         // (and arbitrary calls, which could call the weak entry points).
3693         break;
3694       default:
3695         // Anything else could modify the weak pointer.
3696         goto clobbered;
3697       }
3698     }
3699   clobbered:;
3700   }
3701
3702   // Then, for each destroyWeak with an alloca operand, check to see if
3703   // the alloca and all its users can be zapped.
3704   for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3705     Instruction *Inst = &*I++;
3706     InstructionClass Class = GetBasicInstructionClass(Inst);
3707     if (Class != IC_DestroyWeak)
3708       continue;
3709
3710     CallInst *Call = cast<CallInst>(Inst);
3711     Value *Arg = Call->getArgOperand(0);
3712     if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
3713       for (Value::use_iterator UI = Alloca->use_begin(),
3714            UE = Alloca->use_end(); UI != UE; ++UI) {
3715         const Instruction *UserInst = cast<Instruction>(*UI);
3716         switch (GetBasicInstructionClass(UserInst)) {
3717         case IC_InitWeak:
3718         case IC_StoreWeak:
3719         case IC_DestroyWeak:
3720           continue;
3721         default:
3722           goto done;
3723         }
3724       }
3725       Changed = true;
3726       for (Value::use_iterator UI = Alloca->use_begin(),
3727            UE = Alloca->use_end(); UI != UE; ) {
3728         CallInst *UserInst = cast<CallInst>(*UI++);
3729         switch (GetBasicInstructionClass(UserInst)) {
3730         case IC_InitWeak:
3731         case IC_StoreWeak:
3732           // These functions return their second argument.
3733           UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
3734           break;
3735         case IC_DestroyWeak:
3736           // No return value.
3737           break;
3738         default:
3739           llvm_unreachable("alloca really is used!");
3740         }
3741         UserInst->eraseFromParent();
3742       }
3743       Alloca->eraseFromParent();
3744     done:;
3745     }
3746   }
3747
3748   DEBUG(dbgs() << "ObjCARCOpt::OptimizeWeakCalls: Finished List.\n\n");
3749
3750 }
3751
3752 /// Identify program paths which execute sequences of retains and releases which
3753 /// can be eliminated.
3754 bool ObjCARCOpt::OptimizeSequences(Function &F) {
3755   /// Releases, Retains - These are used to store the results of the main flow
3756   /// analysis. These use Value* as the key instead of Instruction* so that the
3757   /// map stays valid when we get around to rewriting code and calls get
3758   /// replaced by arguments.
3759   DenseMap<Value *, RRInfo> Releases;
3760   MapVector<Value *, RRInfo> Retains;
3761
3762   /// This is used during the traversal of the function to track the
3763   /// states for each identified object at each block.
3764   DenseMap<const BasicBlock *, BBState> BBStates;
3765
3766   // Analyze the CFG of the function, and all instructions.
3767   bool NestingDetected = Visit(F, BBStates, Retains, Releases);
3768
3769   // Transform.
3770   return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) &&
3771          NestingDetected;
3772 }
3773
3774 /// Look for this pattern:
3775 /// \code
3776 ///    %call = call i8* @something(...)
3777 ///    %2 = call i8* @objc_retain(i8* %call)
3778 ///    %3 = call i8* @objc_autorelease(i8* %2)
3779 ///    ret i8* %3
3780 /// \endcode
3781 /// And delete the retain and autorelease.
3782 ///
3783 /// Otherwise if it's just this:
3784 /// \code
3785 ///    %3 = call i8* @objc_autorelease(i8* %2)
3786 ///    ret i8* %3
3787 /// \endcode
3788 /// convert the autorelease to autoreleaseRV.
3789 void ObjCARCOpt::OptimizeReturns(Function &F) {
3790   if (!F.getReturnType()->isPointerTy())
3791     return;
3792
3793   SmallPtrSet<Instruction *, 4> DependingInstructions;
3794   SmallPtrSet<const BasicBlock *, 4> Visited;
3795   for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3796     BasicBlock *BB = FI;
3797     ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
3798
3799     DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Visiting: " << *Ret << "\n");
3800
3801     if (!Ret) continue;
3802
3803     const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
3804     FindDependencies(NeedsPositiveRetainCount, Arg,
3805                      BB, Ret, DependingInstructions, Visited, PA);
3806     if (DependingInstructions.size() != 1)
3807       goto next_block;
3808
3809     {
3810       CallInst *Autorelease =
3811         dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3812       if (!Autorelease)
3813         goto next_block;
3814       InstructionClass AutoreleaseClass = GetBasicInstructionClass(Autorelease);
3815       if (!IsAutorelease(AutoreleaseClass))
3816         goto next_block;
3817       if (GetObjCArg(Autorelease) != Arg)
3818         goto next_block;
3819
3820       DependingInstructions.clear();
3821       Visited.clear();
3822
3823       // Check that there is nothing that can affect the reference
3824       // count between the autorelease and the retain.
3825       FindDependencies(CanChangeRetainCount, Arg,
3826                        BB, Autorelease, DependingInstructions, Visited, PA);
3827       if (DependingInstructions.size() != 1)
3828         goto next_block;
3829
3830       {
3831         CallInst *Retain =
3832           dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3833
3834         // Check that we found a retain with the same argument.
3835         if (!Retain ||
3836             !IsRetain(GetBasicInstructionClass(Retain)) ||
3837             GetObjCArg(Retain) != Arg)
3838           goto next_block;
3839
3840         DependingInstructions.clear();
3841         Visited.clear();
3842
3843         // Convert the autorelease to an autoreleaseRV, since it's
3844         // returning the value.
3845         if (AutoreleaseClass == IC_Autorelease) {
3846           DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Converting autorelease "
3847                           "=> autoreleaseRV since it's returning a value.\n"
3848                           "                             In: " << *Autorelease
3849                        << "\n");
3850           Autorelease->setCalledFunction(getAutoreleaseRVCallee(F.getParent()));
3851           DEBUG(dbgs() << "                             Out: " << *Autorelease
3852                        << "\n");
3853           Autorelease->setTailCall(); // Always tail call autoreleaseRV.
3854           AutoreleaseClass = IC_AutoreleaseRV;
3855         }
3856
3857         // Check that there is nothing that can affect the reference
3858         // count between the retain and the call.
3859         // Note that Retain need not be in BB.
3860         FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
3861                          DependingInstructions, Visited, PA);
3862         if (DependingInstructions.size() != 1)
3863           goto next_block;
3864
3865         {
3866           CallInst *Call =
3867             dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3868
3869           // Check that the pointer is the return value of the call.
3870           if (!Call || Arg != Call)
3871             goto next_block;
3872
3873           // Check that the call is a regular call.
3874           InstructionClass Class = GetBasicInstructionClass(Call);
3875           if (Class != IC_CallOrUser && Class != IC_Call)
3876             goto next_block;
3877
3878           // If so, we can zap the retain and autorelease.
3879           Changed = true;
3880           ++NumRets;
3881           DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Erasing: " << *Retain
3882                        << "\n                             Erasing: "
3883                        << *Autorelease << "\n");
3884           EraseInstruction(Retain);
3885           EraseInstruction(Autorelease);
3886         }
3887       }
3888     }
3889
3890   next_block:
3891     DependingInstructions.clear();
3892     Visited.clear();
3893   }
3894
3895   DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Finished List.\n\n");
3896
3897 }
3898
3899 bool ObjCARCOpt::doInitialization(Module &M) {
3900   if (!EnableARCOpts)
3901     return false;
3902
3903   // If nothing in the Module uses ARC, don't do anything.
3904   Run = ModuleHasARC(M);
3905   if (!Run)
3906     return false;
3907
3908   // Identify the imprecise release metadata kind.
3909   ImpreciseReleaseMDKind =
3910     M.getContext().getMDKindID("clang.imprecise_release");
3911   CopyOnEscapeMDKind =
3912     M.getContext().getMDKindID("clang.arc.copy_on_escape");
3913   NoObjCARCExceptionsMDKind =
3914     M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
3915
3916   // Intuitively, objc_retain and others are nocapture, however in practice
3917   // they are not, because they return their argument value. And objc_release
3918   // calls finalizers which can have arbitrary side effects.
3919
3920   // These are initialized lazily.
3921   RetainRVCallee = 0;
3922   AutoreleaseRVCallee = 0;
3923   ReleaseCallee = 0;
3924   RetainCallee = 0;
3925   RetainBlockCallee = 0;
3926   AutoreleaseCallee = 0;
3927
3928   return false;
3929 }
3930
3931 bool ObjCARCOpt::runOnFunction(Function &F) {
3932   if (!EnableARCOpts)
3933     return false;
3934
3935   // If nothing in the Module uses ARC, don't do anything.
3936   if (!Run)
3937     return false;
3938
3939   Changed = false;
3940
3941   DEBUG(dbgs() << "ObjCARCOpt: Visiting Function: " << F.getName() << "\n");
3942
3943   PA.setAA(&getAnalysis<AliasAnalysis>());
3944
3945   // This pass performs several distinct transformations. As a compile-time aid
3946   // when compiling code that isn't ObjC, skip these if the relevant ObjC
3947   // library functions aren't declared.
3948
3949   // Preliminary optimizations. This also computs UsedInThisFunction.
3950   OptimizeIndividualCalls(F);
3951
3952   // Optimizations for weak pointers.
3953   if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3954                             (1 << IC_LoadWeakRetained) |
3955                             (1 << IC_StoreWeak) |
3956                             (1 << IC_InitWeak) |
3957                             (1 << IC_CopyWeak) |
3958                             (1 << IC_MoveWeak) |
3959                             (1 << IC_DestroyWeak)))
3960     OptimizeWeakCalls(F);
3961
3962   // Optimizations for retain+release pairs.
3963   if (UsedInThisFunction & ((1 << IC_Retain) |
3964                             (1 << IC_RetainRV) |
3965                             (1 << IC_RetainBlock)))
3966     if (UsedInThisFunction & (1 << IC_Release))
3967       // Run OptimizeSequences until it either stops making changes or
3968       // no retain+release pair nesting is detected.
3969       while (OptimizeSequences(F)) {}
3970
3971   // Optimizations if objc_autorelease is used.
3972   if (UsedInThisFunction & ((1 << IC_Autorelease) |
3973                             (1 << IC_AutoreleaseRV)))
3974     OptimizeReturns(F);
3975
3976   DEBUG(dbgs() << "\n");
3977
3978   return Changed;
3979 }
3980
3981 void ObjCARCOpt::releaseMemory() {
3982   PA.clear();
3983 }
3984
3985 /// @}
3986 ///
3987 /// \defgroup ARCContract ARC Contraction.
3988 /// @{
3989
3990 // TODO: ObjCARCContract could insert PHI nodes when uses aren't
3991 // dominated by single calls.
3992
3993 #include "llvm/Analysis/Dominators.h"
3994 #include "llvm/IR/InlineAsm.h"
3995 #include "llvm/IR/Operator.h"
3996
3997 STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed");
3998
3999 namespace {
4000   /// \brief Late ARC optimizations
4001   ///
4002   /// These change the IR in a way that makes it difficult to be analyzed by
4003   /// ObjCARCOpt, so it's run late.
4004   class ObjCARCContract : public FunctionPass {
4005     bool Changed;
4006     AliasAnalysis *AA;
4007     DominatorTree *DT;
4008     ProvenanceAnalysis PA;
4009
4010     /// A flag indicating whether this optimization pass should run.
4011     bool Run;
4012
4013     /// Declarations for ObjC runtime functions, for use in creating calls to
4014     /// them. These are initialized lazily to avoid cluttering up the Module
4015     /// with unused declarations.
4016
4017     /// Declaration for objc_storeStrong().
4018     Constant *StoreStrongCallee;
4019     /// Declaration for objc_retainAutorelease().
4020     Constant *RetainAutoreleaseCallee;
4021     /// Declaration for objc_retainAutoreleaseReturnValue().
4022     Constant *RetainAutoreleaseRVCallee;
4023
4024     /// The inline asm string to insert between calls and RetainRV calls to make
4025     /// the optimization work on targets which need it.
4026     const MDString *RetainRVMarker;
4027
4028     /// The set of inserted objc_storeStrong calls. If at the end of walking the
4029     /// function we have found no alloca instructions, these calls can be marked
4030     /// "tail".
4031     SmallPtrSet<CallInst *, 8> StoreStrongCalls;
4032
4033     Constant *getStoreStrongCallee(Module *M);
4034     Constant *getRetainAutoreleaseCallee(Module *M);
4035     Constant *getRetainAutoreleaseRVCallee(Module *M);
4036
4037     bool ContractAutorelease(Function &F, Instruction *Autorelease,
4038                              InstructionClass Class,
4039                              SmallPtrSet<Instruction *, 4>
4040                                &DependingInstructions,
4041                              SmallPtrSet<const BasicBlock *, 4>
4042                                &Visited);
4043
4044     void ContractRelease(Instruction *Release,
4045                          inst_iterator &Iter);
4046
4047     virtual void getAnalysisUsage(AnalysisUsage &AU) const;
4048     virtual bool doInitialization(Module &M);
4049     virtual bool runOnFunction(Function &F);
4050
4051   public:
4052     static char ID;
4053     ObjCARCContract() : FunctionPass(ID) {
4054       initializeObjCARCContractPass(*PassRegistry::getPassRegistry());
4055     }
4056   };
4057 }
4058
4059 char ObjCARCContract::ID = 0;
4060 INITIALIZE_PASS_BEGIN(ObjCARCContract,
4061                       "objc-arc-contract", "ObjC ARC contraction", false, false)
4062 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
4063 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
4064 INITIALIZE_PASS_END(ObjCARCContract,
4065                     "objc-arc-contract", "ObjC ARC contraction", false, false)
4066
4067 Pass *llvm::createObjCARCContractPass() {
4068   return new ObjCARCContract();
4069 }
4070
4071 void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const {
4072   AU.addRequired<AliasAnalysis>();
4073   AU.addRequired<DominatorTree>();
4074   AU.setPreservesCFG();
4075 }
4076
4077 Constant *ObjCARCContract::getStoreStrongCallee(Module *M) {
4078   if (!StoreStrongCallee) {
4079     LLVMContext &C = M->getContext();
4080     Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
4081     Type *I8XX = PointerType::getUnqual(I8X);
4082     Type *Params[] = { I8XX, I8X };
4083
4084     AttributeSet Attribute = AttributeSet()
4085       .addAttr(M->getContext(), AttributeSet::FunctionIndex,
4086                Attribute::get(C, Attribute::NoUnwind))
4087       .addAttr(M->getContext(), 1, Attribute::get(C, Attribute::NoCapture));
4088
4089     StoreStrongCallee =
4090       M->getOrInsertFunction(
4091         "objc_storeStrong",
4092         FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
4093         Attribute);
4094   }
4095   return StoreStrongCallee;
4096 }
4097
4098 Constant *ObjCARCContract::getRetainAutoreleaseCallee(Module *M) {
4099   if (!RetainAutoreleaseCallee) {
4100     LLVMContext &C = M->getContext();
4101     Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
4102     Type *Params[] = { I8X };
4103     FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
4104     AttributeSet Attribute =
4105       AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
4106                             Attribute::get(C, Attribute::NoUnwind));
4107     RetainAutoreleaseCallee =
4108       M->getOrInsertFunction("objc_retainAutorelease", FTy, Attribute);
4109   }
4110   return RetainAutoreleaseCallee;
4111 }
4112
4113 Constant *ObjCARCContract::getRetainAutoreleaseRVCallee(Module *M) {
4114   if (!RetainAutoreleaseRVCallee) {
4115     LLVMContext &C = M->getContext();
4116     Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
4117     Type *Params[] = { I8X };
4118     FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
4119     AttributeSet Attribute =
4120       AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
4121                             Attribute::get(C, Attribute::NoUnwind));
4122     RetainAutoreleaseRVCallee =
4123       M->getOrInsertFunction("objc_retainAutoreleaseReturnValue", FTy,
4124                              Attribute);
4125   }
4126   return RetainAutoreleaseRVCallee;
4127 }
4128
4129 /// Merge an autorelease with a retain into a fused call.
4130 bool
4131 ObjCARCContract::ContractAutorelease(Function &F, Instruction *Autorelease,
4132                                      InstructionClass Class,
4133                                      SmallPtrSet<Instruction *, 4>
4134                                        &DependingInstructions,
4135                                      SmallPtrSet<const BasicBlock *, 4>
4136                                        &Visited) {
4137   const Value *Arg = GetObjCArg(Autorelease);
4138
4139   // Check that there are no instructions between the retain and the autorelease
4140   // (such as an autorelease_pop) which may change the count.
4141   CallInst *Retain = 0;
4142   if (Class == IC_AutoreleaseRV)
4143     FindDependencies(RetainAutoreleaseRVDep, Arg,
4144                      Autorelease->getParent(), Autorelease,
4145                      DependingInstructions, Visited, PA);
4146   else
4147     FindDependencies(RetainAutoreleaseDep, Arg,
4148                      Autorelease->getParent(), Autorelease,
4149                      DependingInstructions, Visited, PA);
4150
4151   Visited.clear();
4152   if (DependingInstructions.size() != 1) {
4153     DependingInstructions.clear();
4154     return false;
4155   }
4156
4157   Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
4158   DependingInstructions.clear();
4159
4160   if (!Retain ||
4161       GetBasicInstructionClass(Retain) != IC_Retain ||
4162       GetObjCArg(Retain) != Arg)
4163     return false;
4164
4165   Changed = true;
4166   ++NumPeeps;
4167
4168   DEBUG(dbgs() << "ObjCARCContract::ContractAutorelease: Fusing "
4169                   "retain/autorelease. Erasing: " << *Autorelease << "\n"
4170                   "                                      Old Retain: "
4171                << *Retain << "\n");
4172
4173   if (Class == IC_AutoreleaseRV)
4174     Retain->setCalledFunction(getRetainAutoreleaseRVCallee(F.getParent()));
4175   else
4176     Retain->setCalledFunction(getRetainAutoreleaseCallee(F.getParent()));
4177
4178   DEBUG(dbgs() << "                                      New Retain: "
4179                << *Retain << "\n");
4180
4181   EraseInstruction(Autorelease);
4182   return true;
4183 }
4184
4185 /// Attempt to merge an objc_release with a store, load, and objc_retain to form
4186 /// an objc_storeStrong. This can be a little tricky because the instructions
4187 /// don't always appear in order, and there may be unrelated intervening
4188 /// instructions.
4189 void ObjCARCContract::ContractRelease(Instruction *Release,
4190                                       inst_iterator &Iter) {
4191   LoadInst *Load = dyn_cast<LoadInst>(GetObjCArg(Release));
4192   if (!Load || !Load->isSimple()) return;
4193
4194   // For now, require everything to be in one basic block.
4195   BasicBlock *BB = Release->getParent();
4196   if (Load->getParent() != BB) return;
4197
4198   // Walk down to find the store and the release, which may be in either order.
4199   BasicBlock::iterator I = Load, End = BB->end();
4200   ++I;
4201   AliasAnalysis::Location Loc = AA->getLocation(Load);
4202   StoreInst *Store = 0;
4203   bool SawRelease = false;
4204   for (; !Store || !SawRelease; ++I) {
4205     if (I == End)
4206       return;
4207
4208     Instruction *Inst = I;
4209     if (Inst == Release) {
4210       SawRelease = true;
4211       continue;
4212     }
4213
4214     InstructionClass Class = GetBasicInstructionClass(Inst);
4215
4216     // Unrelated retains are harmless.
4217     if (IsRetain(Class))
4218       continue;
4219
4220     if (Store) {
4221       // The store is the point where we're going to put the objc_storeStrong,
4222       // so make sure there are no uses after it.
4223       if (CanUse(Inst, Load, PA, Class))
4224         return;
4225     } else if (AA->getModRefInfo(Inst, Loc) & AliasAnalysis::Mod) {
4226       // We are moving the load down to the store, so check for anything
4227       // else which writes to the memory between the load and the store.
4228       Store = dyn_cast<StoreInst>(Inst);
4229       if (!Store || !Store->isSimple()) return;
4230       if (Store->getPointerOperand() != Loc.Ptr) return;
4231     }
4232   }
4233
4234   Value *New = StripPointerCastsAndObjCCalls(Store->getValueOperand());
4235
4236   // Walk up to find the retain.
4237   I = Store;
4238   BasicBlock::iterator Begin = BB->begin();
4239   while (I != Begin && GetBasicInstructionClass(I) != IC_Retain)
4240     --I;
4241   Instruction *Retain = I;
4242   if (GetBasicInstructionClass(Retain) != IC_Retain) return;
4243   if (GetObjCArg(Retain) != New) return;
4244
4245   Changed = true;
4246   ++NumStoreStrongs;
4247
4248   LLVMContext &C = Release->getContext();
4249   Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
4250   Type *I8XX = PointerType::getUnqual(I8X);
4251
4252   Value *Args[] = { Load->getPointerOperand(), New };
4253   if (Args[0]->getType() != I8XX)
4254     Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
4255   if (Args[1]->getType() != I8X)
4256     Args[1] = new BitCastInst(Args[1], I8X, "", Store);
4257   CallInst *StoreStrong =
4258     CallInst::Create(getStoreStrongCallee(BB->getParent()->getParent()),
4259                      Args, "", Store);
4260   StoreStrong->setDoesNotThrow();
4261   StoreStrong->setDebugLoc(Store->getDebugLoc());
4262
4263   // We can't set the tail flag yet, because we haven't yet determined
4264   // whether there are any escaping allocas. Remember this call, so that
4265   // we can set the tail flag once we know it's safe.
4266   StoreStrongCalls.insert(StoreStrong);
4267
4268   if (&*Iter == Store) ++Iter;
4269   Store->eraseFromParent();
4270   Release->eraseFromParent();
4271   EraseInstruction(Retain);
4272   if (Load->use_empty())
4273     Load->eraseFromParent();
4274 }
4275
4276 bool ObjCARCContract::doInitialization(Module &M) {
4277   // If nothing in the Module uses ARC, don't do anything.
4278   Run = ModuleHasARC(M);
4279   if (!Run)
4280     return false;
4281
4282   // These are initialized lazily.
4283   StoreStrongCallee = 0;
4284   RetainAutoreleaseCallee = 0;
4285   RetainAutoreleaseRVCallee = 0;
4286
4287   // Initialize RetainRVMarker.
4288   RetainRVMarker = 0;
4289   if (NamedMDNode *NMD =
4290         M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker"))
4291     if (NMD->getNumOperands() == 1) {
4292       const MDNode *N = NMD->getOperand(0);
4293       if (N->getNumOperands() == 1)
4294         if (const MDString *S = dyn_cast<MDString>(N->getOperand(0)))
4295           RetainRVMarker = S;
4296     }
4297
4298   return false;
4299 }
4300
4301 bool ObjCARCContract::runOnFunction(Function &F) {
4302   if (!EnableARCOpts)
4303     return false;
4304
4305   // If nothing in the Module uses ARC, don't do anything.
4306   if (!Run)
4307     return false;
4308
4309   Changed = false;
4310   AA = &getAnalysis<AliasAnalysis>();
4311   DT = &getAnalysis<DominatorTree>();
4312
4313   PA.setAA(&getAnalysis<AliasAnalysis>());
4314
4315   // Track whether it's ok to mark objc_storeStrong calls with the "tail"
4316   // keyword. Be conservative if the function has variadic arguments.
4317   // It seems that functions which "return twice" are also unsafe for the
4318   // "tail" argument, because they are setjmp, which could need to
4319   // return to an earlier stack state.
4320   bool TailOkForStoreStrongs = !F.isVarArg() &&
4321                                !F.callsFunctionThatReturnsTwice();
4322
4323   // For ObjC library calls which return their argument, replace uses of the
4324   // argument with uses of the call return value, if it dominates the use. This
4325   // reduces register pressure.
4326   SmallPtrSet<Instruction *, 4> DependingInstructions;
4327   SmallPtrSet<const BasicBlock *, 4> Visited;
4328   for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
4329     Instruction *Inst = &*I++;
4330
4331     DEBUG(dbgs() << "ObjCARCContract: Visiting: " << *Inst << "\n");
4332
4333     // Only these library routines return their argument. In particular,
4334     // objc_retainBlock does not necessarily return its argument.
4335     InstructionClass Class = GetBasicInstructionClass(Inst);
4336     switch (Class) {
4337     case IC_Retain:
4338     case IC_FusedRetainAutorelease:
4339     case IC_FusedRetainAutoreleaseRV:
4340       break;
4341     case IC_Autorelease:
4342     case IC_AutoreleaseRV:
4343       if (ContractAutorelease(F, Inst, Class, DependingInstructions, Visited))
4344         continue;
4345       break;
4346     case IC_RetainRV: {
4347       // If we're compiling for a target which needs a special inline-asm
4348       // marker to do the retainAutoreleasedReturnValue optimization,
4349       // insert it now.
4350       if (!RetainRVMarker)
4351         break;
4352       BasicBlock::iterator BBI = Inst;
4353       BasicBlock *InstParent = Inst->getParent();
4354
4355       // Step up to see if the call immediately precedes the RetainRV call.
4356       // If it's an invoke, we have to cross a block boundary. And we have
4357       // to carefully dodge no-op instructions.
4358       do {
4359         if (&*BBI == InstParent->begin()) {
4360           BasicBlock *Pred = InstParent->getSinglePredecessor();
4361           if (!Pred)
4362             goto decline_rv_optimization;
4363           BBI = Pred->getTerminator();
4364           break;
4365         }
4366         --BBI;
4367       } while (isNoopInstruction(BBI));
4368
4369       if (&*BBI == GetObjCArg(Inst)) {
4370         DEBUG(dbgs() << "ObjCARCContract: Adding inline asm marker for "
4371                         "retainAutoreleasedReturnValue optimization.\n");
4372         Changed = true;
4373         InlineAsm *IA =
4374           InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()),
4375                                            /*isVarArg=*/false),
4376                          RetainRVMarker->getString(),
4377                          /*Constraints=*/"", /*hasSideEffects=*/true);
4378         CallInst::Create(IA, "", Inst);
4379       }
4380     decline_rv_optimization:
4381       break;
4382     }
4383     case IC_InitWeak: {
4384       // objc_initWeak(p, null) => *p = null
4385       CallInst *CI = cast<CallInst>(Inst);
4386       if (isNullOrUndef(CI->getArgOperand(1))) {
4387         Value *Null =
4388           ConstantPointerNull::get(cast<PointerType>(CI->getType()));
4389         Changed = true;
4390         new StoreInst(Null, CI->getArgOperand(0), CI);
4391
4392         DEBUG(dbgs() << "OBJCARCContract: Old = " << *CI << "\n"
4393                      << "                 New = " << *Null << "\n");
4394
4395         CI->replaceAllUsesWith(Null);
4396         CI->eraseFromParent();
4397       }
4398       continue;
4399     }
4400     case IC_Release:
4401       ContractRelease(Inst, I);
4402       continue;
4403     case IC_User:
4404       // Be conservative if the function has any alloca instructions.
4405       // Technically we only care about escaping alloca instructions,
4406       // but this is sufficient to handle some interesting cases.
4407       if (isa<AllocaInst>(Inst))
4408         TailOkForStoreStrongs = false;
4409       continue;
4410     default:
4411       continue;
4412     }
4413
4414     DEBUG(dbgs() << "ObjCARCContract: Finished List.\n\n");
4415
4416     // Don't use GetObjCArg because we don't want to look through bitcasts
4417     // and such; to do the replacement, the argument must have type i8*.
4418     const Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
4419     for (;;) {
4420       // If we're compiling bugpointed code, don't get in trouble.
4421       if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
4422         break;
4423       // Look through the uses of the pointer.
4424       for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
4425            UI != UE; ) {
4426         Use &U = UI.getUse();
4427         unsigned OperandNo = UI.getOperandNo();
4428         ++UI; // Increment UI now, because we may unlink its element.
4429
4430         // If the call's return value dominates a use of the call's argument
4431         // value, rewrite the use to use the return value. We check for
4432         // reachability here because an unreachable call is considered to
4433         // trivially dominate itself, which would lead us to rewriting its
4434         // argument in terms of its return value, which would lead to
4435         // infinite loops in GetObjCArg.
4436         if (DT->isReachableFromEntry(U) && DT->dominates(Inst, U)) {
4437           Changed = true;
4438           Instruction *Replacement = Inst;
4439           Type *UseTy = U.get()->getType();
4440           if (PHINode *PHI = dyn_cast<PHINode>(U.getUser())) {
4441             // For PHI nodes, insert the bitcast in the predecessor block.
4442             unsigned ValNo = PHINode::getIncomingValueNumForOperand(OperandNo);
4443             BasicBlock *BB = PHI->getIncomingBlock(ValNo);
4444             if (Replacement->getType() != UseTy)
4445               Replacement = new BitCastInst(Replacement, UseTy, "",
4446                                             &BB->back());
4447             // While we're here, rewrite all edges for this PHI, rather
4448             // than just one use at a time, to minimize the number of
4449             // bitcasts we emit.
4450             for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
4451               if (PHI->getIncomingBlock(i) == BB) {
4452                 // Keep the UI iterator valid.
4453                 if (&PHI->getOperandUse(
4454                       PHINode::getOperandNumForIncomingValue(i)) ==
4455                     &UI.getUse())
4456                   ++UI;
4457                 PHI->setIncomingValue(i, Replacement);
4458               }
4459           } else {
4460             if (Replacement->getType() != UseTy)
4461               Replacement = new BitCastInst(Replacement, UseTy, "",
4462                                             cast<Instruction>(U.getUser()));
4463             U.set(Replacement);
4464           }
4465         }
4466       }
4467
4468       // If Arg is a no-op casted pointer, strip one level of casts and iterate.
4469       if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
4470         Arg = BI->getOperand(0);
4471       else if (isa<GEPOperator>(Arg) &&
4472                cast<GEPOperator>(Arg)->hasAllZeroIndices())
4473         Arg = cast<GEPOperator>(Arg)->getPointerOperand();
4474       else if (isa<GlobalAlias>(Arg) &&
4475                !cast<GlobalAlias>(Arg)->mayBeOverridden())
4476         Arg = cast<GlobalAlias>(Arg)->getAliasee();
4477       else
4478         break;
4479     }
4480   }
4481
4482   // If this function has no escaping allocas or suspicious vararg usage,
4483   // objc_storeStrong calls can be marked with the "tail" keyword.
4484   if (TailOkForStoreStrongs)
4485     for (SmallPtrSet<CallInst *, 8>::iterator I = StoreStrongCalls.begin(),
4486          E = StoreStrongCalls.end(); I != E; ++I)
4487       (*I)->setTailCall();
4488   StoreStrongCalls.clear();
4489
4490   return Changed;
4491 }
4492
4493 /// @}
4494 ///