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