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