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