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