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