Move all of the header files which are involved in modelling the LLVM IR
[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 Queue.\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         Inst->eraseFromParent();
999         Push->eraseFromParent();
1000       }
1001       Push = 0;
1002       break;
1003     case IC_CallOrUser:
1004       if (MayAutorelease(ImmutableCallSite(Inst)))
1005         Push = 0;
1006       break;
1007     default:
1008       break;
1009     }
1010   }
1011
1012   return Changed;
1013 }
1014
1015 bool ObjCARCAPElim::runOnModule(Module &M) {
1016   if (!EnableARCOpts)
1017     return false;
1018
1019   // If nothing in the Module uses ARC, don't do anything.
1020   if (!ModuleHasARC(M))
1021     return false;
1022
1023   // Find the llvm.global_ctors variable, as the first step in
1024   // identifying the global constructors. In theory, unnecessary autorelease
1025   // pools could occur anywhere, but in practice it's pretty rare. Global
1026   // ctors are a place where autorelease pools get inserted automatically,
1027   // so it's pretty common for them to be unnecessary, and it's pretty
1028   // profitable to eliminate them.
1029   GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1030   if (!GV)
1031     return false;
1032
1033   assert(GV->hasDefinitiveInitializer() &&
1034          "llvm.global_ctors is uncooperative!");
1035
1036   bool Changed = false;
1037
1038   // Dig the constructor functions out of GV's initializer.
1039   ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
1040   for (User::op_iterator OI = Init->op_begin(), OE = Init->op_end();
1041        OI != OE; ++OI) {
1042     Value *Op = *OI;
1043     // llvm.global_ctors is an array of pairs where the second members
1044     // are constructor functions.
1045     Function *F = dyn_cast<Function>(cast<ConstantStruct>(Op)->getOperand(1));
1046     // If the user used a constructor function with the wrong signature and
1047     // it got bitcasted or whatever, look the other way.
1048     if (!F)
1049       continue;
1050     // Only look at function definitions.
1051     if (F->isDeclaration())
1052       continue;
1053     // Only look at functions with one basic block.
1054     if (llvm::next(F->begin()) != F->end())
1055       continue;
1056     // Ok, a single-block constructor function definition. Try to optimize it.
1057     Changed |= OptimizeBB(F->begin());
1058   }
1059
1060   return Changed;
1061 }
1062
1063 //===----------------------------------------------------------------------===//
1064 // ARC optimization.
1065 //===----------------------------------------------------------------------===//
1066
1067 // TODO: On code like this:
1068 //
1069 // objc_retain(%x)
1070 // stuff_that_cannot_release()
1071 // objc_autorelease(%x)
1072 // stuff_that_cannot_release()
1073 // objc_retain(%x)
1074 // stuff_that_cannot_release()
1075 // objc_autorelease(%x)
1076 //
1077 // The second retain and autorelease can be deleted.
1078
1079 // TODO: It should be possible to delete
1080 // objc_autoreleasePoolPush and objc_autoreleasePoolPop
1081 // pairs if nothing is actually autoreleased between them. Also, autorelease
1082 // calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
1083 // after inlining) can be turned into plain release calls.
1084
1085 // TODO: Critical-edge splitting. If the optimial insertion point is
1086 // a critical edge, the current algorithm has to fail, because it doesn't
1087 // know how to split edges. It should be possible to make the optimizer
1088 // think in terms of edges, rather than blocks, and then split critical
1089 // edges on demand.
1090
1091 // TODO: OptimizeSequences could generalized to be Interprocedural.
1092
1093 // TODO: Recognize that a bunch of other objc runtime calls have
1094 // non-escaping arguments and non-releasing arguments, and may be
1095 // non-autoreleasing.
1096
1097 // TODO: Sink autorelease calls as far as possible. Unfortunately we
1098 // usually can't sink them past other calls, which would be the main
1099 // case where it would be useful.
1100
1101 // TODO: The pointer returned from objc_loadWeakRetained is retained.
1102
1103 // TODO: Delete release+retain pairs (rare).
1104
1105 #include "llvm/ADT/SmallPtrSet.h"
1106 #include "llvm/ADT/Statistic.h"
1107 #include "llvm/IR/LLVMContext.h"
1108 #include "llvm/Support/CFG.h"
1109
1110 STATISTIC(NumNoops,       "Number of no-op objc calls eliminated");
1111 STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
1112 STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
1113 STATISTIC(NumRets,        "Number of return value forwarding "
1114                           "retain+autoreleaes eliminated");
1115 STATISTIC(NumRRs,         "Number of retain+release paths eliminated");
1116 STATISTIC(NumPeeps,       "Number of calls peephole-optimized");
1117
1118 namespace {
1119   /// ProvenanceAnalysis - This is similar to BasicAliasAnalysis, and it
1120   /// uses many of the same techniques, except it uses special ObjC-specific
1121   /// reasoning about pointer relationships.
1122   class ProvenanceAnalysis {
1123     AliasAnalysis *AA;
1124
1125     typedef std::pair<const Value *, const Value *> ValuePairTy;
1126     typedef DenseMap<ValuePairTy, bool> CachedResultsTy;
1127     CachedResultsTy CachedResults;
1128
1129     bool relatedCheck(const Value *A, const Value *B);
1130     bool relatedSelect(const SelectInst *A, const Value *B);
1131     bool relatedPHI(const PHINode *A, const Value *B);
1132
1133     void operator=(const ProvenanceAnalysis &) LLVM_DELETED_FUNCTION;
1134     ProvenanceAnalysis(const ProvenanceAnalysis &) LLVM_DELETED_FUNCTION;
1135
1136   public:
1137     ProvenanceAnalysis() {}
1138
1139     void setAA(AliasAnalysis *aa) { AA = aa; }
1140
1141     AliasAnalysis *getAA() const { return AA; }
1142
1143     bool related(const Value *A, const Value *B);
1144
1145     void clear() {
1146       CachedResults.clear();
1147     }
1148   };
1149 }
1150
1151 bool ProvenanceAnalysis::relatedSelect(const SelectInst *A, const Value *B) {
1152   // If the values are Selects with the same condition, we can do a more precise
1153   // check: just check for relations between the values on corresponding arms.
1154   if (const SelectInst *SB = dyn_cast<SelectInst>(B))
1155     if (A->getCondition() == SB->getCondition())
1156       return related(A->getTrueValue(), SB->getTrueValue()) ||
1157              related(A->getFalseValue(), SB->getFalseValue());
1158
1159   // Check both arms of the Select node individually.
1160   return related(A->getTrueValue(), B) ||
1161          related(A->getFalseValue(), B);
1162 }
1163
1164 bool ProvenanceAnalysis::relatedPHI(const PHINode *A, const Value *B) {
1165   // If the values are PHIs in the same block, we can do a more precise as well
1166   // as efficient check: just check for relations between the values on
1167   // corresponding edges.
1168   if (const PHINode *PNB = dyn_cast<PHINode>(B))
1169     if (PNB->getParent() == A->getParent()) {
1170       for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i)
1171         if (related(A->getIncomingValue(i),
1172                     PNB->getIncomingValueForBlock(A->getIncomingBlock(i))))
1173           return true;
1174       return false;
1175     }
1176
1177   // Check each unique source of the PHI node against B.
1178   SmallPtrSet<const Value *, 4> UniqueSrc;
1179   for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i) {
1180     const Value *PV1 = A->getIncomingValue(i);
1181     if (UniqueSrc.insert(PV1) && related(PV1, B))
1182       return true;
1183   }
1184
1185   // All of the arms checked out.
1186   return false;
1187 }
1188
1189 /// isStoredObjCPointer - Test if the value of P, or any value covered by its
1190 /// provenance, is ever stored within the function (not counting callees).
1191 static bool isStoredObjCPointer(const Value *P) {
1192   SmallPtrSet<const Value *, 8> Visited;
1193   SmallVector<const Value *, 8> Worklist;
1194   Worklist.push_back(P);
1195   Visited.insert(P);
1196   do {
1197     P = Worklist.pop_back_val();
1198     for (Value::const_use_iterator UI = P->use_begin(), UE = P->use_end();
1199          UI != UE; ++UI) {
1200       const User *Ur = *UI;
1201       if (isa<StoreInst>(Ur)) {
1202         if (UI.getOperandNo() == 0)
1203           // The pointer is stored.
1204           return true;
1205         // The pointed is stored through.
1206         continue;
1207       }
1208       if (isa<CallInst>(Ur))
1209         // The pointer is passed as an argument, ignore this.
1210         continue;
1211       if (isa<PtrToIntInst>(P))
1212         // Assume the worst.
1213         return true;
1214       if (Visited.insert(Ur))
1215         Worklist.push_back(Ur);
1216     }
1217   } while (!Worklist.empty());
1218
1219   // Everything checked out.
1220   return false;
1221 }
1222
1223 bool ProvenanceAnalysis::relatedCheck(const Value *A, const Value *B) {
1224   // Skip past provenance pass-throughs.
1225   A = GetUnderlyingObjCPtr(A);
1226   B = GetUnderlyingObjCPtr(B);
1227
1228   // Quick check.
1229   if (A == B)
1230     return true;
1231
1232   // Ask regular AliasAnalysis, for a first approximation.
1233   switch (AA->alias(A, B)) {
1234   case AliasAnalysis::NoAlias:
1235     return false;
1236   case AliasAnalysis::MustAlias:
1237   case AliasAnalysis::PartialAlias:
1238     return true;
1239   case AliasAnalysis::MayAlias:
1240     break;
1241   }
1242
1243   bool AIsIdentified = IsObjCIdentifiedObject(A);
1244   bool BIsIdentified = IsObjCIdentifiedObject(B);
1245
1246   // An ObjC-Identified object can't alias a load if it is never locally stored.
1247   if (AIsIdentified) {
1248     // Check for an obvious escape.
1249     if (isa<LoadInst>(B))
1250       return isStoredObjCPointer(A);
1251     if (BIsIdentified) {
1252       // Check for an obvious escape.
1253       if (isa<LoadInst>(A))
1254         return isStoredObjCPointer(B);
1255       // Both pointers are identified and escapes aren't an evident problem.
1256       return false;
1257     }
1258   } else if (BIsIdentified) {
1259     // Check for an obvious escape.
1260     if (isa<LoadInst>(A))
1261       return isStoredObjCPointer(B);
1262   }
1263
1264    // Special handling for PHI and Select.
1265   if (const PHINode *PN = dyn_cast<PHINode>(A))
1266     return relatedPHI(PN, B);
1267   if (const PHINode *PN = dyn_cast<PHINode>(B))
1268     return relatedPHI(PN, A);
1269   if (const SelectInst *S = dyn_cast<SelectInst>(A))
1270     return relatedSelect(S, B);
1271   if (const SelectInst *S = dyn_cast<SelectInst>(B))
1272     return relatedSelect(S, A);
1273
1274   // Conservative.
1275   return true;
1276 }
1277
1278 bool ProvenanceAnalysis::related(const Value *A, const Value *B) {
1279   // Begin by inserting a conservative value into the map. If the insertion
1280   // fails, we have the answer already. If it succeeds, leave it there until we
1281   // compute the real answer to guard against recursive queries.
1282   if (A > B) std::swap(A, B);
1283   std::pair<CachedResultsTy::iterator, bool> Pair =
1284     CachedResults.insert(std::make_pair(ValuePairTy(A, B), true));
1285   if (!Pair.second)
1286     return Pair.first->second;
1287
1288   bool Result = relatedCheck(A, B);
1289   CachedResults[ValuePairTy(A, B)] = Result;
1290   return Result;
1291 }
1292
1293 namespace {
1294   // Sequence - A sequence of states that a pointer may go through in which an
1295   // objc_retain and objc_release are actually needed.
1296   enum Sequence {
1297     S_None,
1298     S_Retain,         ///< objc_retain(x)
1299     S_CanRelease,     ///< foo(x) -- x could possibly see a ref count decrement
1300     S_Use,            ///< any use of x
1301     S_Stop,           ///< like S_Release, but code motion is stopped
1302     S_Release,        ///< objc_release(x)
1303     S_MovableRelease  ///< objc_release(x), !clang.imprecise_release
1304   };
1305 }
1306
1307 static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
1308   // The easy cases.
1309   if (A == B)
1310     return A;
1311   if (A == S_None || B == S_None)
1312     return S_None;
1313
1314   if (A > B) std::swap(A, B);
1315   if (TopDown) {
1316     // Choose the side which is further along in the sequence.
1317     if ((A == S_Retain || A == S_CanRelease) &&
1318         (B == S_CanRelease || B == S_Use))
1319       return B;
1320   } else {
1321     // Choose the side which is further along in the sequence.
1322     if ((A == S_Use || A == S_CanRelease) &&
1323         (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
1324       return A;
1325     // If both sides are releases, choose the more conservative one.
1326     if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
1327       return A;
1328     if (A == S_Release && B == S_MovableRelease)
1329       return A;
1330   }
1331
1332   return S_None;
1333 }
1334
1335 namespace {
1336   /// RRInfo - Unidirectional information about either a
1337   /// retain-decrement-use-release sequence or release-use-decrement-retain
1338   /// reverese sequence.
1339   struct RRInfo {
1340     /// KnownSafe - After an objc_retain, the reference count of the referenced
1341     /// object is known to be positive. Similarly, before an objc_release, the
1342     /// reference count of the referenced object is known to be positive. If
1343     /// there are retain-release pairs in code regions where the retain count
1344     /// is known to be positive, they can be eliminated, regardless of any side
1345     /// effects between them.
1346     ///
1347     /// Also, a retain+release pair nested within another retain+release
1348     /// pair all on the known same pointer value can be eliminated, regardless
1349     /// of any intervening side effects.
1350     ///
1351     /// KnownSafe is true when either of these conditions is satisfied.
1352     bool KnownSafe;
1353
1354     /// IsRetainBlock - True if the Calls are objc_retainBlock calls (as
1355     /// opposed to objc_retain calls).
1356     bool IsRetainBlock;
1357
1358     /// IsTailCallRelease - True of the objc_release calls are all marked
1359     /// with the "tail" keyword.
1360     bool IsTailCallRelease;
1361
1362     /// ReleaseMetadata - If the Calls are objc_release calls and they all have
1363     /// a clang.imprecise_release tag, this is the metadata tag.
1364     MDNode *ReleaseMetadata;
1365
1366     /// Calls - For a top-down sequence, the set of objc_retains or
1367     /// objc_retainBlocks. For bottom-up, the set of objc_releases.
1368     SmallPtrSet<Instruction *, 2> Calls;
1369
1370     /// ReverseInsertPts - The set of optimal insert positions for
1371     /// moving calls in the opposite sequence.
1372     SmallPtrSet<Instruction *, 2> ReverseInsertPts;
1373
1374     RRInfo() :
1375       KnownSafe(false), IsRetainBlock(false),
1376       IsTailCallRelease(false),
1377       ReleaseMetadata(0) {}
1378
1379     void clear();
1380   };
1381 }
1382
1383 void RRInfo::clear() {
1384   KnownSafe = false;
1385   IsRetainBlock = false;
1386   IsTailCallRelease = false;
1387   ReleaseMetadata = 0;
1388   Calls.clear();
1389   ReverseInsertPts.clear();
1390 }
1391
1392 namespace {
1393   /// PtrState - This class summarizes several per-pointer runtime properties
1394   /// which are propogated through the flow graph.
1395   class PtrState {
1396     /// KnownPositiveRefCount - True if the reference count is known to
1397     /// be incremented.
1398     bool KnownPositiveRefCount;
1399
1400     /// Partial - True of we've seen an opportunity for partial RR elimination,
1401     /// such as pushing calls into a CFG triangle or into one side of a
1402     /// CFG diamond.
1403     bool Partial;
1404
1405     /// Seq - The current position in the sequence.
1406     Sequence Seq : 8;
1407
1408   public:
1409     /// RRI - Unidirectional information about the current sequence.
1410     /// TODO: Encapsulate this better.
1411     RRInfo RRI;
1412
1413     PtrState() : KnownPositiveRefCount(false), Partial(false),
1414                  Seq(S_None) {}
1415
1416     void SetKnownPositiveRefCount() {
1417       KnownPositiveRefCount = true;
1418     }
1419
1420     void ClearRefCount() {
1421       KnownPositiveRefCount = false;
1422     }
1423
1424     bool IsKnownIncremented() const {
1425       return KnownPositiveRefCount;
1426     }
1427
1428     void SetSeq(Sequence NewSeq) {
1429       Seq = NewSeq;
1430     }
1431
1432     Sequence GetSeq() const {
1433       return Seq;
1434     }
1435
1436     void ClearSequenceProgress() {
1437       ResetSequenceProgress(S_None);
1438     }
1439
1440     void ResetSequenceProgress(Sequence NewSeq) {
1441       Seq = NewSeq;
1442       Partial = false;
1443       RRI.clear();
1444     }
1445
1446     void Merge(const PtrState &Other, bool TopDown);
1447   };
1448 }
1449
1450 void
1451 PtrState::Merge(const PtrState &Other, bool TopDown) {
1452   Seq = MergeSeqs(Seq, Other.Seq, TopDown);
1453   KnownPositiveRefCount = KnownPositiveRefCount && Other.KnownPositiveRefCount;
1454
1455   // We can't merge a plain objc_retain with an objc_retainBlock.
1456   if (RRI.IsRetainBlock != Other.RRI.IsRetainBlock)
1457     Seq = S_None;
1458
1459   // If we're not in a sequence (anymore), drop all associated state.
1460   if (Seq == S_None) {
1461     Partial = false;
1462     RRI.clear();
1463   } else if (Partial || Other.Partial) {
1464     // If we're doing a merge on a path that's previously seen a partial
1465     // merge, conservatively drop the sequence, to avoid doing partial
1466     // RR elimination. If the branch predicates for the two merge differ,
1467     // mixing them is unsafe.
1468     ClearSequenceProgress();
1469   } else {
1470     // Conservatively merge the ReleaseMetadata information.
1471     if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
1472       RRI.ReleaseMetadata = 0;
1473
1474     RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
1475     RRI.IsTailCallRelease = RRI.IsTailCallRelease &&
1476                             Other.RRI.IsTailCallRelease;
1477     RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
1478
1479     // Merge the insert point sets. If there are any differences,
1480     // that makes this a partial merge.
1481     Partial = RRI.ReverseInsertPts.size() != Other.RRI.ReverseInsertPts.size();
1482     for (SmallPtrSet<Instruction *, 2>::const_iterator
1483          I = Other.RRI.ReverseInsertPts.begin(),
1484          E = Other.RRI.ReverseInsertPts.end(); I != E; ++I)
1485       Partial |= RRI.ReverseInsertPts.insert(*I);
1486   }
1487 }
1488
1489 namespace {
1490   /// BBState - Per-BasicBlock state.
1491   class BBState {
1492     /// TopDownPathCount - The number of unique control paths from the entry
1493     /// which can reach this block.
1494     unsigned TopDownPathCount;
1495
1496     /// BottomUpPathCount - The number of unique control paths to exits
1497     /// from this block.
1498     unsigned BottomUpPathCount;
1499
1500     /// MapTy - A type for PerPtrTopDown and PerPtrBottomUp.
1501     typedef MapVector<const Value *, PtrState> MapTy;
1502
1503     /// PerPtrTopDown - The top-down traversal uses this to record information
1504     /// known about a pointer at the bottom of each block.
1505     MapTy PerPtrTopDown;
1506
1507     /// PerPtrBottomUp - The bottom-up traversal uses this to record information
1508     /// known about a pointer at the top of each block.
1509     MapTy PerPtrBottomUp;
1510
1511     /// Preds, Succs - Effective successors and predecessors of the current
1512     /// block (this ignores ignorable edges and ignored backedges).
1513     SmallVector<BasicBlock *, 2> Preds;
1514     SmallVector<BasicBlock *, 2> Succs;
1515
1516   public:
1517     BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
1518
1519     typedef MapTy::iterator ptr_iterator;
1520     typedef MapTy::const_iterator ptr_const_iterator;
1521
1522     ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
1523     ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
1524     ptr_const_iterator top_down_ptr_begin() const {
1525       return PerPtrTopDown.begin();
1526     }
1527     ptr_const_iterator top_down_ptr_end() const {
1528       return PerPtrTopDown.end();
1529     }
1530
1531     ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
1532     ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
1533     ptr_const_iterator bottom_up_ptr_begin() const {
1534       return PerPtrBottomUp.begin();
1535     }
1536     ptr_const_iterator bottom_up_ptr_end() const {
1537       return PerPtrBottomUp.end();
1538     }
1539
1540     /// SetAsEntry - Mark this block as being an entry block, which has one
1541     /// path from the entry by definition.
1542     void SetAsEntry() { TopDownPathCount = 1; }
1543
1544     /// SetAsExit - Mark this block as being an exit block, which has one
1545     /// path to an exit by definition.
1546     void SetAsExit()  { BottomUpPathCount = 1; }
1547
1548     PtrState &getPtrTopDownState(const Value *Arg) {
1549       return PerPtrTopDown[Arg];
1550     }
1551
1552     PtrState &getPtrBottomUpState(const Value *Arg) {
1553       return PerPtrBottomUp[Arg];
1554     }
1555
1556     void clearBottomUpPointers() {
1557       PerPtrBottomUp.clear();
1558     }
1559
1560     void clearTopDownPointers() {
1561       PerPtrTopDown.clear();
1562     }
1563
1564     void InitFromPred(const BBState &Other);
1565     void InitFromSucc(const BBState &Other);
1566     void MergePred(const BBState &Other);
1567     void MergeSucc(const BBState &Other);
1568
1569     /// GetAllPathCount - Return the number of possible unique paths from an
1570     /// entry to an exit which pass through this block. This is only valid
1571     /// after both the top-down and bottom-up traversals are complete.
1572     unsigned GetAllPathCount() const {
1573       assert(TopDownPathCount != 0);
1574       assert(BottomUpPathCount != 0);
1575       return TopDownPathCount * BottomUpPathCount;
1576     }
1577
1578     // Specialized CFG utilities.
1579     typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
1580     edge_iterator pred_begin() { return Preds.begin(); }
1581     edge_iterator pred_end() { return Preds.end(); }
1582     edge_iterator succ_begin() { return Succs.begin(); }
1583     edge_iterator succ_end() { return Succs.end(); }
1584
1585     void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
1586     void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
1587
1588     bool isExit() const { return Succs.empty(); }
1589   };
1590 }
1591
1592 void BBState::InitFromPred(const BBState &Other) {
1593   PerPtrTopDown = Other.PerPtrTopDown;
1594   TopDownPathCount = Other.TopDownPathCount;
1595 }
1596
1597 void BBState::InitFromSucc(const BBState &Other) {
1598   PerPtrBottomUp = Other.PerPtrBottomUp;
1599   BottomUpPathCount = Other.BottomUpPathCount;
1600 }
1601
1602 /// MergePred - The top-down traversal uses this to merge information about
1603 /// predecessors to form the initial state for a new block.
1604 void BBState::MergePred(const BBState &Other) {
1605   // Other.TopDownPathCount can be 0, in which case it is either dead or a
1606   // loop backedge. Loop backedges are special.
1607   TopDownPathCount += Other.TopDownPathCount;
1608
1609   // Check for overflow. If we have overflow, fall back to conservative behavior.
1610   if (TopDownPathCount < Other.TopDownPathCount) {
1611     clearTopDownPointers();
1612     return;
1613   }
1614
1615   // For each entry in the other set, if our set has an entry with the same key,
1616   // merge the entries. Otherwise, copy the entry and merge it with an empty
1617   // entry.
1618   for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
1619        ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
1620     std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
1621     Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1622                              /*TopDown=*/true);
1623   }
1624
1625   // For each entry in our set, if the other set doesn't have an entry with the
1626   // same key, force it to merge with an empty entry.
1627   for (ptr_iterator MI = top_down_ptr_begin(),
1628        ME = top_down_ptr_end(); MI != ME; ++MI)
1629     if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
1630       MI->second.Merge(PtrState(), /*TopDown=*/true);
1631 }
1632
1633 /// MergeSucc - The bottom-up traversal uses this to merge information about
1634 /// successors to form the initial state for a new block.
1635 void BBState::MergeSucc(const BBState &Other) {
1636   // Other.BottomUpPathCount can be 0, in which case it is either dead or a
1637   // loop backedge. Loop backedges are special.
1638   BottomUpPathCount += Other.BottomUpPathCount;
1639
1640   // Check for overflow. If we have overflow, fall back to conservative behavior.
1641   if (BottomUpPathCount < Other.BottomUpPathCount) {
1642     clearBottomUpPointers();
1643     return;
1644   }
1645
1646   // For each entry in the other set, if our set has an entry with the
1647   // same key, merge the entries. Otherwise, copy the entry and merge
1648   // it with an empty entry.
1649   for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
1650        ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
1651     std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
1652     Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1653                              /*TopDown=*/false);
1654   }
1655
1656   // For each entry in our set, if the other set doesn't have an entry
1657   // with the same key, force it to merge with an empty entry.
1658   for (ptr_iterator MI = bottom_up_ptr_begin(),
1659        ME = bottom_up_ptr_end(); MI != ME; ++MI)
1660     if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
1661       MI->second.Merge(PtrState(), /*TopDown=*/false);
1662 }
1663
1664 namespace {
1665   /// ObjCARCOpt - The main ARC optimization pass.
1666   class ObjCARCOpt : public FunctionPass {
1667     bool Changed;
1668     ProvenanceAnalysis PA;
1669
1670     /// Run - A flag indicating whether this optimization pass should run.
1671     bool Run;
1672
1673     /// RetainRVCallee, etc. - Declarations for ObjC runtime
1674     /// functions, for use in creating calls to them. These are initialized
1675     /// lazily to avoid cluttering up the Module with unused declarations.
1676     Constant *RetainRVCallee, *AutoreleaseRVCallee, *ReleaseCallee,
1677              *RetainCallee, *RetainBlockCallee, *AutoreleaseCallee;
1678
1679     /// UsedInThisFunciton - Flags which determine whether each of the
1680     /// interesting runtine functions is in fact used in the current function.
1681     unsigned UsedInThisFunction;
1682
1683     /// ImpreciseReleaseMDKind - The Metadata Kind for clang.imprecise_release
1684     /// metadata.
1685     unsigned ImpreciseReleaseMDKind;
1686
1687     /// CopyOnEscapeMDKind - The Metadata Kind for clang.arc.copy_on_escape
1688     /// metadata.
1689     unsigned CopyOnEscapeMDKind;
1690
1691     /// NoObjCARCExceptionsMDKind - The Metadata Kind for
1692     /// clang.arc.no_objc_arc_exceptions metadata.
1693     unsigned NoObjCARCExceptionsMDKind;
1694
1695     Constant *getRetainRVCallee(Module *M);
1696     Constant *getAutoreleaseRVCallee(Module *M);
1697     Constant *getReleaseCallee(Module *M);
1698     Constant *getRetainCallee(Module *M);
1699     Constant *getRetainBlockCallee(Module *M);
1700     Constant *getAutoreleaseCallee(Module *M);
1701
1702     bool IsRetainBlockOptimizable(const Instruction *Inst);
1703
1704     void OptimizeRetainCall(Function &F, Instruction *Retain);
1705     bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
1706     void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV);
1707     void OptimizeIndividualCalls(Function &F);
1708
1709     void CheckForCFGHazards(const BasicBlock *BB,
1710                             DenseMap<const BasicBlock *, BBState> &BBStates,
1711                             BBState &MyStates) const;
1712     bool VisitInstructionBottomUp(Instruction *Inst,
1713                                   BasicBlock *BB,
1714                                   MapVector<Value *, RRInfo> &Retains,
1715                                   BBState &MyStates);
1716     bool VisitBottomUp(BasicBlock *BB,
1717                        DenseMap<const BasicBlock *, BBState> &BBStates,
1718                        MapVector<Value *, RRInfo> &Retains);
1719     bool VisitInstructionTopDown(Instruction *Inst,
1720                                  DenseMap<Value *, RRInfo> &Releases,
1721                                  BBState &MyStates);
1722     bool VisitTopDown(BasicBlock *BB,
1723                       DenseMap<const BasicBlock *, BBState> &BBStates,
1724                       DenseMap<Value *, RRInfo> &Releases);
1725     bool Visit(Function &F,
1726                DenseMap<const BasicBlock *, BBState> &BBStates,
1727                MapVector<Value *, RRInfo> &Retains,
1728                DenseMap<Value *, RRInfo> &Releases);
1729
1730     void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1731                    MapVector<Value *, RRInfo> &Retains,
1732                    DenseMap<Value *, RRInfo> &Releases,
1733                    SmallVectorImpl<Instruction *> &DeadInsts,
1734                    Module *M);
1735
1736     bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1737                               MapVector<Value *, RRInfo> &Retains,
1738                               DenseMap<Value *, RRInfo> &Releases,
1739                               Module *M);
1740
1741     void OptimizeWeakCalls(Function &F);
1742
1743     bool OptimizeSequences(Function &F);
1744
1745     void OptimizeReturns(Function &F);
1746
1747     virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1748     virtual bool doInitialization(Module &M);
1749     virtual bool runOnFunction(Function &F);
1750     virtual void releaseMemory();
1751
1752   public:
1753     static char ID;
1754     ObjCARCOpt() : FunctionPass(ID) {
1755       initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1756     }
1757   };
1758 }
1759
1760 char ObjCARCOpt::ID = 0;
1761 INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1762                       "objc-arc", "ObjC ARC optimization", false, false)
1763 INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1764 INITIALIZE_PASS_END(ObjCARCOpt,
1765                     "objc-arc", "ObjC ARC optimization", false, false)
1766
1767 Pass *llvm::createObjCARCOptPass() {
1768   return new ObjCARCOpt();
1769 }
1770
1771 void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1772   AU.addRequired<ObjCARCAliasAnalysis>();
1773   AU.addRequired<AliasAnalysis>();
1774   // ARC optimization doesn't currently split critical edges.
1775   AU.setPreservesCFG();
1776 }
1777
1778 bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1779   // Without the magic metadata tag, we have to assume this might be an
1780   // objc_retainBlock call inserted to convert a block pointer to an id,
1781   // in which case it really is needed.
1782   if (!Inst->getMetadata(CopyOnEscapeMDKind))
1783     return false;
1784
1785   // If the pointer "escapes" (not including being used in a call),
1786   // the copy may be needed.
1787   if (DoesObjCBlockEscape(Inst))
1788     return false;
1789
1790   // Otherwise, it's not needed.
1791   return true;
1792 }
1793
1794 Constant *ObjCARCOpt::getRetainRVCallee(Module *M) {
1795   if (!RetainRVCallee) {
1796     LLVMContext &C = M->getContext();
1797     Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1798     Type *Params[] = { I8X };
1799     FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
1800     AttributeSet Attribute =
1801       AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
1802                             Attribute::get(C, Attribute::NoUnwind));
1803     RetainRVCallee =
1804       M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy,
1805                              Attribute);
1806   }
1807   return RetainRVCallee;
1808 }
1809
1810 Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1811   if (!AutoreleaseRVCallee) {
1812     LLVMContext &C = M->getContext();
1813     Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1814     Type *Params[] = { I8X };
1815     FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
1816     AttributeSet Attribute =
1817       AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
1818                             Attribute::get(C, Attribute::NoUnwind));
1819     AutoreleaseRVCallee =
1820       M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
1821                              Attribute);
1822   }
1823   return AutoreleaseRVCallee;
1824 }
1825
1826 Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1827   if (!ReleaseCallee) {
1828     LLVMContext &C = M->getContext();
1829     Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1830     AttributeSet Attribute =
1831       AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
1832                             Attribute::get(C, Attribute::NoUnwind));
1833     ReleaseCallee =
1834       M->getOrInsertFunction(
1835         "objc_release",
1836         FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
1837         Attribute);
1838   }
1839   return ReleaseCallee;
1840 }
1841
1842 Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1843   if (!RetainCallee) {
1844     LLVMContext &C = M->getContext();
1845     Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1846     AttributeSet Attribute =
1847       AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
1848                             Attribute::get(C, Attribute::NoUnwind));
1849     RetainCallee =
1850       M->getOrInsertFunction(
1851         "objc_retain",
1852         FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1853         Attribute);
1854   }
1855   return RetainCallee;
1856 }
1857
1858 Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1859   if (!RetainBlockCallee) {
1860     LLVMContext &C = M->getContext();
1861     Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1862     // objc_retainBlock is not nounwind because it calls user copy constructors
1863     // which could theoretically throw.
1864     RetainBlockCallee =
1865       M->getOrInsertFunction(
1866         "objc_retainBlock",
1867         FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1868         AttributeSet());
1869   }
1870   return RetainBlockCallee;
1871 }
1872
1873 Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1874   if (!AutoreleaseCallee) {
1875     LLVMContext &C = M->getContext();
1876     Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1877     AttributeSet Attribute =
1878       AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
1879                             Attribute::get(C, Attribute::NoUnwind));
1880     AutoreleaseCallee =
1881       M->getOrInsertFunction(
1882         "objc_autorelease",
1883         FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1884         Attribute);
1885   }
1886   return AutoreleaseCallee;
1887 }
1888
1889 /// IsPotentialUse - Test whether the given value is possible a
1890 /// reference-counted pointer, including tests which utilize AliasAnalysis.
1891 static bool IsPotentialUse(const Value *Op, AliasAnalysis &AA) {
1892   // First make the rudimentary check.
1893   if (!IsPotentialUse(Op))
1894     return false;
1895
1896   // Objects in constant memory are not reference-counted.
1897   if (AA.pointsToConstantMemory(Op))
1898     return false;
1899
1900   // Pointers in constant memory are not pointing to reference-counted objects.
1901   if (const LoadInst *LI = dyn_cast<LoadInst>(Op))
1902     if (AA.pointsToConstantMemory(LI->getPointerOperand()))
1903       return false;
1904
1905   // Otherwise assume the worst.
1906   return true;
1907 }
1908
1909 /// CanAlterRefCount - Test whether the given instruction can result in a
1910 /// reference count modification (positive or negative) for the pointer's
1911 /// object.
1912 static bool
1913 CanAlterRefCount(const Instruction *Inst, const Value *Ptr,
1914                  ProvenanceAnalysis &PA, InstructionClass Class) {
1915   switch (Class) {
1916   case IC_Autorelease:
1917   case IC_AutoreleaseRV:
1918   case IC_User:
1919     // These operations never directly modify a reference count.
1920     return false;
1921   default: break;
1922   }
1923
1924   ImmutableCallSite CS = static_cast<const Value *>(Inst);
1925   assert(CS && "Only calls can alter reference counts!");
1926
1927   // See if AliasAnalysis can help us with the call.
1928   AliasAnalysis::ModRefBehavior MRB = PA.getAA()->getModRefBehavior(CS);
1929   if (AliasAnalysis::onlyReadsMemory(MRB))
1930     return false;
1931   if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
1932     for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1933          I != E; ++I) {
1934       const Value *Op = *I;
1935       if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
1936         return true;
1937     }
1938     return false;
1939   }
1940
1941   // Assume the worst.
1942   return true;
1943 }
1944
1945 /// CanUse - Test whether the given instruction can "use" the given pointer's
1946 /// object in a way that requires the reference count to be positive.
1947 static bool
1948 CanUse(const Instruction *Inst, const Value *Ptr, ProvenanceAnalysis &PA,
1949        InstructionClass Class) {
1950   // IC_Call operations (as opposed to IC_CallOrUser) never "use" objc pointers.
1951   if (Class == IC_Call)
1952     return false;
1953
1954   // Consider various instructions which may have pointer arguments which are
1955   // not "uses".
1956   if (const ICmpInst *ICI = dyn_cast<ICmpInst>(Inst)) {
1957     // Comparing a pointer with null, or any other constant, isn't really a use,
1958     // because we don't care what the pointer points to, or about the values
1959     // of any other dynamic reference-counted pointers.
1960     if (!IsPotentialUse(ICI->getOperand(1), *PA.getAA()))
1961       return false;
1962   } else if (ImmutableCallSite CS = static_cast<const Value *>(Inst)) {
1963     // For calls, just check the arguments (and not the callee operand).
1964     for (ImmutableCallSite::arg_iterator OI = CS.arg_begin(),
1965          OE = CS.arg_end(); OI != OE; ++OI) {
1966       const Value *Op = *OI;
1967       if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
1968         return true;
1969     }
1970     return false;
1971   } else if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1972     // Special-case stores, because we don't care about the stored value, just
1973     // the store address.
1974     const Value *Op = GetUnderlyingObjCPtr(SI->getPointerOperand());
1975     // If we can't tell what the underlying object was, assume there is a
1976     // dependence.
1977     return IsPotentialUse(Op, *PA.getAA()) && PA.related(Op, Ptr);
1978   }
1979
1980   // Check each operand for a match.
1981   for (User::const_op_iterator OI = Inst->op_begin(), OE = Inst->op_end();
1982        OI != OE; ++OI) {
1983     const Value *Op = *OI;
1984     if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
1985       return true;
1986   }
1987   return false;
1988 }
1989
1990 /// CanInterruptRV - Test whether the given instruction can autorelease
1991 /// any pointer or cause an autoreleasepool pop.
1992 static bool
1993 CanInterruptRV(InstructionClass Class) {
1994   switch (Class) {
1995   case IC_AutoreleasepoolPop:
1996   case IC_CallOrUser:
1997   case IC_Call:
1998   case IC_Autorelease:
1999   case IC_AutoreleaseRV:
2000   case IC_FusedRetainAutorelease:
2001   case IC_FusedRetainAutoreleaseRV:
2002     return true;
2003   default:
2004     return false;
2005   }
2006 }
2007
2008 namespace {
2009   /// DependenceKind - There are several kinds of dependence-like concepts in
2010   /// use here.
2011   enum DependenceKind {
2012     NeedsPositiveRetainCount,
2013     AutoreleasePoolBoundary,
2014     CanChangeRetainCount,
2015     RetainAutoreleaseDep,       ///< Blocks objc_retainAutorelease.
2016     RetainAutoreleaseRVDep,     ///< Blocks objc_retainAutoreleaseReturnValue.
2017     RetainRVDep                 ///< Blocks objc_retainAutoreleasedReturnValue.
2018   };
2019 }
2020
2021 /// Depends - Test if there can be dependencies on Inst through Arg. This
2022 /// function only tests dependencies relevant for removing pairs of calls.
2023 static bool
2024 Depends(DependenceKind Flavor, Instruction *Inst, const Value *Arg,
2025         ProvenanceAnalysis &PA) {
2026   // If we've reached the definition of Arg, stop.
2027   if (Inst == Arg)
2028     return true;
2029
2030   switch (Flavor) {
2031   case NeedsPositiveRetainCount: {
2032     InstructionClass Class = GetInstructionClass(Inst);
2033     switch (Class) {
2034     case IC_AutoreleasepoolPop:
2035     case IC_AutoreleasepoolPush:
2036     case IC_None:
2037       return false;
2038     default:
2039       return CanUse(Inst, Arg, PA, Class);
2040     }
2041   }
2042
2043   case AutoreleasePoolBoundary: {
2044     InstructionClass Class = GetInstructionClass(Inst);
2045     switch (Class) {
2046     case IC_AutoreleasepoolPop:
2047     case IC_AutoreleasepoolPush:
2048       // These mark the end and begin of an autorelease pool scope.
2049       return true;
2050     default:
2051       // Nothing else does this.
2052       return false;
2053     }
2054   }
2055
2056   case CanChangeRetainCount: {
2057     InstructionClass Class = GetInstructionClass(Inst);
2058     switch (Class) {
2059     case IC_AutoreleasepoolPop:
2060       // Conservatively assume this can decrement any count.
2061       return true;
2062     case IC_AutoreleasepoolPush:
2063     case IC_None:
2064       return false;
2065     default:
2066       return CanAlterRefCount(Inst, Arg, PA, Class);
2067     }
2068   }
2069
2070   case RetainAutoreleaseDep:
2071     switch (GetBasicInstructionClass(Inst)) {
2072     case IC_AutoreleasepoolPop:
2073     case IC_AutoreleasepoolPush:
2074       // Don't merge an objc_autorelease with an objc_retain inside a different
2075       // autoreleasepool scope.
2076       return true;
2077     case IC_Retain:
2078     case IC_RetainRV:
2079       // Check for a retain of the same pointer for merging.
2080       return GetObjCArg(Inst) == Arg;
2081     default:
2082       // Nothing else matters for objc_retainAutorelease formation.
2083       return false;
2084     }
2085
2086   case RetainAutoreleaseRVDep: {
2087     InstructionClass Class = GetBasicInstructionClass(Inst);
2088     switch (Class) {
2089     case IC_Retain:
2090     case IC_RetainRV:
2091       // Check for a retain of the same pointer for merging.
2092       return GetObjCArg(Inst) == Arg;
2093     default:
2094       // Anything that can autorelease interrupts
2095       // retainAutoreleaseReturnValue formation.
2096       return CanInterruptRV(Class);
2097     }
2098   }
2099
2100   case RetainRVDep:
2101     return CanInterruptRV(GetBasicInstructionClass(Inst));
2102   }
2103
2104   llvm_unreachable("Invalid dependence flavor");
2105 }
2106
2107 /// FindDependencies - Walk up the CFG from StartPos (which is in StartBB) and
2108 /// find local and non-local dependencies on Arg.
2109 /// TODO: Cache results?
2110 static void
2111 FindDependencies(DependenceKind Flavor,
2112                  const Value *Arg,
2113                  BasicBlock *StartBB, Instruction *StartInst,
2114                  SmallPtrSet<Instruction *, 4> &DependingInstructions,
2115                  SmallPtrSet<const BasicBlock *, 4> &Visited,
2116                  ProvenanceAnalysis &PA) {
2117   BasicBlock::iterator StartPos = StartInst;
2118
2119   SmallVector<std::pair<BasicBlock *, BasicBlock::iterator>, 4> Worklist;
2120   Worklist.push_back(std::make_pair(StartBB, StartPos));
2121   do {
2122     std::pair<BasicBlock *, BasicBlock::iterator> Pair =
2123       Worklist.pop_back_val();
2124     BasicBlock *LocalStartBB = Pair.first;
2125     BasicBlock::iterator LocalStartPos = Pair.second;
2126     BasicBlock::iterator StartBBBegin = LocalStartBB->begin();
2127     for (;;) {
2128       if (LocalStartPos == StartBBBegin) {
2129         pred_iterator PI(LocalStartBB), PE(LocalStartBB, false);
2130         if (PI == PE)
2131           // If we've reached the function entry, produce a null dependence.
2132           DependingInstructions.insert(0);
2133         else
2134           // Add the predecessors to the worklist.
2135           do {
2136             BasicBlock *PredBB = *PI;
2137             if (Visited.insert(PredBB))
2138               Worklist.push_back(std::make_pair(PredBB, PredBB->end()));
2139           } while (++PI != PE);
2140         break;
2141       }
2142
2143       Instruction *Inst = --LocalStartPos;
2144       if (Depends(Flavor, Inst, Arg, PA)) {
2145         DependingInstructions.insert(Inst);
2146         break;
2147       }
2148     }
2149   } while (!Worklist.empty());
2150
2151   // Determine whether the original StartBB post-dominates all of the blocks we
2152   // visited. If not, insert a sentinal indicating that most optimizations are
2153   // not safe.
2154   for (SmallPtrSet<const BasicBlock *, 4>::const_iterator I = Visited.begin(),
2155        E = Visited.end(); I != E; ++I) {
2156     const BasicBlock *BB = *I;
2157     if (BB == StartBB)
2158       continue;
2159     const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2160     for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2161       const BasicBlock *Succ = *SI;
2162       if (Succ != StartBB && !Visited.count(Succ)) {
2163         DependingInstructions.insert(reinterpret_cast<Instruction *>(-1));
2164         return;
2165       }
2166     }
2167   }
2168 }
2169
2170 static bool isNullOrUndef(const Value *V) {
2171   return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
2172 }
2173
2174 static bool isNoopInstruction(const Instruction *I) {
2175   return isa<BitCastInst>(I) ||
2176          (isa<GetElementPtrInst>(I) &&
2177           cast<GetElementPtrInst>(I)->hasAllZeroIndices());
2178 }
2179
2180 /// OptimizeRetainCall - Turn objc_retain into
2181 /// objc_retainAutoreleasedReturnValue if the operand is a return value.
2182 void
2183 ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) {
2184   ImmutableCallSite CS(GetObjCArg(Retain));
2185   const Instruction *Call = CS.getInstruction();
2186   if (!Call) return;
2187   if (Call->getParent() != Retain->getParent()) return;
2188
2189   // Check that the call is next to the retain.
2190   BasicBlock::const_iterator I = Call;
2191   ++I;
2192   while (isNoopInstruction(I)) ++I;
2193   if (&*I != Retain)
2194     return;
2195
2196   // Turn it to an objc_retainAutoreleasedReturnValue..
2197   Changed = true;
2198   ++NumPeeps;
2199   cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent()));
2200 }
2201
2202 /// OptimizeRetainRVCall - Turn objc_retainAutoreleasedReturnValue into
2203 /// objc_retain if the operand is not a return value.  Or, if it can be paired
2204 /// with an objc_autoreleaseReturnValue, delete the pair and return true.
2205 bool
2206 ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
2207   // Check for the argument being from an immediately preceding call or invoke.
2208   const Value *Arg = GetObjCArg(RetainRV);
2209   ImmutableCallSite CS(Arg);
2210   if (const Instruction *Call = CS.getInstruction()) {
2211     if (Call->getParent() == RetainRV->getParent()) {
2212       BasicBlock::const_iterator I = Call;
2213       ++I;
2214       while (isNoopInstruction(I)) ++I;
2215       if (&*I == RetainRV)
2216         return false;
2217     } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
2218       BasicBlock *RetainRVParent = RetainRV->getParent();
2219       if (II->getNormalDest() == RetainRVParent) {
2220         BasicBlock::const_iterator I = RetainRVParent->begin();
2221         while (isNoopInstruction(I)) ++I;
2222         if (&*I == RetainRV)
2223           return false;
2224       }
2225     }
2226   }
2227
2228   // Check for being preceded by an objc_autoreleaseReturnValue on the same
2229   // pointer. In this case, we can delete the pair.
2230   BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
2231   if (I != Begin) {
2232     do --I; while (I != Begin && isNoopInstruction(I));
2233     if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
2234         GetObjCArg(I) == Arg) {
2235       Changed = true;
2236       ++NumPeeps;
2237       EraseInstruction(I);
2238       EraseInstruction(RetainRV);
2239       return true;
2240     }
2241   }
2242
2243   // Turn it to a plain objc_retain.
2244   Changed = true;
2245   ++NumPeeps;
2246   cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
2247   return false;
2248 }
2249
2250 /// OptimizeAutoreleaseRVCall - Turn objc_autoreleaseReturnValue into
2251 /// objc_autorelease if the result is not used as a return value.
2252 void
2253 ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV) {
2254   // Check for a return of the pointer value.
2255   const Value *Ptr = GetObjCArg(AutoreleaseRV);
2256   SmallVector<const Value *, 2> Users;
2257   Users.push_back(Ptr);
2258   do {
2259     Ptr = Users.pop_back_val();
2260     for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
2261          UI != UE; ++UI) {
2262       const User *I = *UI;
2263       if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
2264         return;
2265       if (isa<BitCastInst>(I))
2266         Users.push_back(I);
2267     }
2268   } while (!Users.empty());
2269
2270   Changed = true;
2271   ++NumPeeps;
2272   cast<CallInst>(AutoreleaseRV)->
2273     setCalledFunction(getAutoreleaseCallee(F.getParent()));
2274 }
2275
2276 /// OptimizeIndividualCalls - Visit each call, one at a time, and make
2277 /// simplifications without doing any additional analysis.
2278 void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
2279   // Reset all the flags in preparation for recomputing them.
2280   UsedInThisFunction = 0;
2281
2282   // Visit all objc_* calls in F.
2283   for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2284     Instruction *Inst = &*I++;
2285
2286     DEBUG(dbgs() << "ObjCARCOpt: OptimizeIndividualCalls: Visiting: " <<
2287           *Inst << "\n");
2288
2289     InstructionClass Class = GetBasicInstructionClass(Inst);
2290
2291     switch (Class) {
2292     default: break;
2293
2294     // Delete no-op casts. These function calls have special semantics, but
2295     // the semantics are entirely implemented via lowering in the front-end,
2296     // so by the time they reach the optimizer, they are just no-op calls
2297     // which return their argument.
2298     //
2299     // There are gray areas here, as the ability to cast reference-counted
2300     // pointers to raw void* and back allows code to break ARC assumptions,
2301     // however these are currently considered to be unimportant.
2302     case IC_NoopCast:
2303       Changed = true;
2304       ++NumNoops;
2305       EraseInstruction(Inst);
2306       continue;
2307
2308     // If the pointer-to-weak-pointer is null, it's undefined behavior.
2309     case IC_StoreWeak:
2310     case IC_LoadWeak:
2311     case IC_LoadWeakRetained:
2312     case IC_InitWeak:
2313     case IC_DestroyWeak: {
2314       CallInst *CI = cast<CallInst>(Inst);
2315       if (isNullOrUndef(CI->getArgOperand(0))) {
2316         Changed = true;
2317         Type *Ty = CI->getArgOperand(0)->getType();
2318         new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2319                       Constant::getNullValue(Ty),
2320                       CI);
2321         CI->replaceAllUsesWith(UndefValue::get(CI->getType()));
2322         CI->eraseFromParent();
2323         continue;
2324       }
2325       break;
2326     }
2327     case IC_CopyWeak:
2328     case IC_MoveWeak: {
2329       CallInst *CI = cast<CallInst>(Inst);
2330       if (isNullOrUndef(CI->getArgOperand(0)) ||
2331           isNullOrUndef(CI->getArgOperand(1))) {
2332         Changed = true;
2333         Type *Ty = CI->getArgOperand(0)->getType();
2334         new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2335                       Constant::getNullValue(Ty),
2336                       CI);
2337         CI->replaceAllUsesWith(UndefValue::get(CI->getType()));
2338         CI->eraseFromParent();
2339         continue;
2340       }
2341       break;
2342     }
2343     case IC_Retain:
2344       OptimizeRetainCall(F, Inst);
2345       break;
2346     case IC_RetainRV:
2347       if (OptimizeRetainRVCall(F, Inst))
2348         continue;
2349       break;
2350     case IC_AutoreleaseRV:
2351       OptimizeAutoreleaseRVCall(F, Inst);
2352       break;
2353     }
2354
2355     // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
2356     if (IsAutorelease(Class) && Inst->use_empty()) {
2357       CallInst *Call = cast<CallInst>(Inst);
2358       const Value *Arg = Call->getArgOperand(0);
2359       Arg = FindSingleUseIdentifiedObject(Arg);
2360       if (Arg) {
2361         Changed = true;
2362         ++NumAutoreleases;
2363
2364         // Create the declaration lazily.
2365         LLVMContext &C = Inst->getContext();
2366         CallInst *NewCall =
2367           CallInst::Create(getReleaseCallee(F.getParent()),
2368                            Call->getArgOperand(0), "", Call);
2369         NewCall->setMetadata(ImpreciseReleaseMDKind,
2370                              MDNode::get(C, ArrayRef<Value *>()));
2371         EraseInstruction(Call);
2372         Inst = NewCall;
2373         Class = IC_Release;
2374       }
2375     }
2376
2377     // For functions which can never be passed stack arguments, add
2378     // a tail keyword.
2379     if (IsAlwaysTail(Class)) {
2380       Changed = true;
2381       cast<CallInst>(Inst)->setTailCall();
2382     }
2383
2384     // Set nounwind as needed.
2385     if (IsNoThrow(Class)) {
2386       Changed = true;
2387       cast<CallInst>(Inst)->setDoesNotThrow();
2388     }
2389
2390     if (!IsNoopOnNull(Class)) {
2391       UsedInThisFunction |= 1 << Class;
2392       continue;
2393     }
2394
2395     const Value *Arg = GetObjCArg(Inst);
2396
2397     // ARC calls with null are no-ops. Delete them.
2398     if (isNullOrUndef(Arg)) {
2399       Changed = true;
2400       ++NumNoops;
2401       EraseInstruction(Inst);
2402       continue;
2403     }
2404
2405     // Keep track of which of retain, release, autorelease, and retain_block
2406     // are actually present in this function.
2407     UsedInThisFunction |= 1 << Class;
2408
2409     // If Arg is a PHI, and one or more incoming values to the
2410     // PHI are null, and the call is control-equivalent to the PHI, and there
2411     // are no relevant side effects between the PHI and the call, the call
2412     // could be pushed up to just those paths with non-null incoming values.
2413     // For now, don't bother splitting critical edges for this.
2414     SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
2415     Worklist.push_back(std::make_pair(Inst, Arg));
2416     do {
2417       std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
2418       Inst = Pair.first;
2419       Arg = Pair.second;
2420
2421       const PHINode *PN = dyn_cast<PHINode>(Arg);
2422       if (!PN) continue;
2423
2424       // Determine if the PHI has any null operands, or any incoming
2425       // critical edges.
2426       bool HasNull = false;
2427       bool HasCriticalEdges = false;
2428       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2429         Value *Incoming =
2430           StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2431         if (isNullOrUndef(Incoming))
2432           HasNull = true;
2433         else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
2434                    .getNumSuccessors() != 1) {
2435           HasCriticalEdges = true;
2436           break;
2437         }
2438       }
2439       // If we have null operands and no critical edges, optimize.
2440       if (!HasCriticalEdges && HasNull) {
2441         SmallPtrSet<Instruction *, 4> DependingInstructions;
2442         SmallPtrSet<const BasicBlock *, 4> Visited;
2443
2444         // Check that there is nothing that cares about the reference
2445         // count between the call and the phi.
2446         switch (Class) {
2447         case IC_Retain:
2448         case IC_RetainBlock:
2449           // These can always be moved up.
2450           break;
2451         case IC_Release:
2452           // These can't be moved across things that care about the retain
2453           // count.
2454           FindDependencies(NeedsPositiveRetainCount, Arg,
2455                            Inst->getParent(), Inst,
2456                            DependingInstructions, Visited, PA);
2457           break;
2458         case IC_Autorelease:
2459           // These can't be moved across autorelease pool scope boundaries.
2460           FindDependencies(AutoreleasePoolBoundary, Arg,
2461                            Inst->getParent(), Inst,
2462                            DependingInstructions, Visited, PA);
2463           break;
2464         case IC_RetainRV:
2465         case IC_AutoreleaseRV:
2466           // Don't move these; the RV optimization depends on the autoreleaseRV
2467           // being tail called, and the retainRV being immediately after a call
2468           // (which might still happen if we get lucky with codegen layout, but
2469           // it's not worth taking the chance).
2470           continue;
2471         default:
2472           llvm_unreachable("Invalid dependence flavor");
2473         }
2474
2475         if (DependingInstructions.size() == 1 &&
2476             *DependingInstructions.begin() == PN) {
2477           Changed = true;
2478           ++NumPartialNoops;
2479           // Clone the call into each predecessor that has a non-null value.
2480           CallInst *CInst = cast<CallInst>(Inst);
2481           Type *ParamTy = CInst->getArgOperand(0)->getType();
2482           for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2483             Value *Incoming =
2484               StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2485             if (!isNullOrUndef(Incoming)) {
2486               CallInst *Clone = cast<CallInst>(CInst->clone());
2487               Value *Op = PN->getIncomingValue(i);
2488               Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
2489               if (Op->getType() != ParamTy)
2490                 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
2491               Clone->setArgOperand(0, Op);
2492               Clone->insertBefore(InsertPos);
2493               Worklist.push_back(std::make_pair(Clone, Incoming));
2494             }
2495           }
2496           // Erase the original call.
2497           EraseInstruction(CInst);
2498           continue;
2499         }
2500       }
2501     } while (!Worklist.empty());
2502
2503     DEBUG(dbgs() << "ObjCARCOpt: Finished Individual Call Queue.\n\n");
2504
2505   }
2506 }
2507
2508 /// CheckForCFGHazards - Check for critical edges, loop boundaries, irreducible
2509 /// control flow, or other CFG structures where moving code across the edge
2510 /// would result in it being executed more.
2511 void
2512 ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
2513                                DenseMap<const BasicBlock *, BBState> &BBStates,
2514                                BBState &MyStates) const {
2515   // If any top-down local-use or possible-dec has a succ which is earlier in
2516   // the sequence, forget it.
2517   for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
2518        E = MyStates.top_down_ptr_end(); I != E; ++I)
2519     switch (I->second.GetSeq()) {
2520     default: break;
2521     case S_Use: {
2522       const Value *Arg = I->first;
2523       const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2524       bool SomeSuccHasSame = false;
2525       bool AllSuccsHaveSame = true;
2526       PtrState &S = I->second;
2527       succ_const_iterator SI(TI), SE(TI, false);
2528
2529       // If the terminator is an invoke marked with the
2530       // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
2531       // ignored, for ARC purposes.
2532       if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind))
2533         --SE;
2534
2535       for (; SI != SE; ++SI) {
2536         Sequence SuccSSeq = S_None;
2537         bool SuccSRRIKnownSafe = false;
2538         // If VisitBottomUp has pointer information for this successor, take
2539         // what we know about it.
2540         DenseMap<const BasicBlock *, BBState>::iterator BBI =
2541           BBStates.find(*SI);
2542         assert(BBI != BBStates.end());
2543         const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2544         SuccSSeq = SuccS.GetSeq();
2545         SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
2546         switch (SuccSSeq) {
2547         case S_None:
2548         case S_CanRelease: {
2549           if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
2550             S.ClearSequenceProgress();
2551             break;
2552           }
2553           continue;
2554         }
2555         case S_Use:
2556           SomeSuccHasSame = true;
2557           break;
2558         case S_Stop:
2559         case S_Release:
2560         case S_MovableRelease:
2561           if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
2562             AllSuccsHaveSame = false;
2563           break;
2564         case S_Retain:
2565           llvm_unreachable("bottom-up pointer in retain state!");
2566         }
2567       }
2568       // If the state at the other end of any of the successor edges
2569       // matches the current state, require all edges to match. This
2570       // guards against loops in the middle of a sequence.
2571       if (SomeSuccHasSame && !AllSuccsHaveSame)
2572         S.ClearSequenceProgress();
2573       break;
2574     }
2575     case S_CanRelease: {
2576       const Value *Arg = I->first;
2577       const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2578       bool SomeSuccHasSame = false;
2579       bool AllSuccsHaveSame = true;
2580       PtrState &S = I->second;
2581       succ_const_iterator SI(TI), SE(TI, false);
2582
2583       // If the terminator is an invoke marked with the
2584       // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
2585       // ignored, for ARC purposes.
2586       if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind))
2587         --SE;
2588
2589       for (; SI != SE; ++SI) {
2590         Sequence SuccSSeq = S_None;
2591         bool SuccSRRIKnownSafe = false;
2592         // If VisitBottomUp has pointer information for this successor, take
2593         // what we know about it.
2594         DenseMap<const BasicBlock *, BBState>::iterator BBI =
2595           BBStates.find(*SI);
2596         assert(BBI != BBStates.end());
2597         const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2598         SuccSSeq = SuccS.GetSeq();
2599         SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
2600         switch (SuccSSeq) {
2601         case S_None: {
2602           if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
2603             S.ClearSequenceProgress();
2604             break;
2605           }
2606           continue;
2607         }
2608         case S_CanRelease:
2609           SomeSuccHasSame = true;
2610           break;
2611         case S_Stop:
2612         case S_Release:
2613         case S_MovableRelease:
2614         case S_Use:
2615           if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
2616             AllSuccsHaveSame = false;
2617           break;
2618         case S_Retain:
2619           llvm_unreachable("bottom-up pointer in retain state!");
2620         }
2621       }
2622       // If the state at the other end of any of the successor edges
2623       // matches the current state, require all edges to match. This
2624       // guards against loops in the middle of a sequence.
2625       if (SomeSuccHasSame && !AllSuccsHaveSame)
2626         S.ClearSequenceProgress();
2627       break;
2628     }
2629     }
2630 }
2631
2632 bool
2633 ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
2634                                      BasicBlock *BB,
2635                                      MapVector<Value *, RRInfo> &Retains,
2636                                      BBState &MyStates) {
2637   bool NestingDetected = false;
2638   InstructionClass Class = GetInstructionClass(Inst);
2639   const Value *Arg = 0;
2640
2641   switch (Class) {
2642   case IC_Release: {
2643     Arg = GetObjCArg(Inst);
2644
2645     PtrState &S = MyStates.getPtrBottomUpState(Arg);
2646
2647     // If we see two releases in a row on the same pointer. If so, make
2648     // a note, and we'll cicle back to revisit it after we've
2649     // hopefully eliminated the second release, which may allow us to
2650     // eliminate the first release too.
2651     // Theoretically we could implement removal of nested retain+release
2652     // pairs by making PtrState hold a stack of states, but this is
2653     // simple and avoids adding overhead for the non-nested case.
2654     if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease)
2655       NestingDetected = true;
2656
2657     MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2658     S.ResetSequenceProgress(ReleaseMetadata ? S_MovableRelease : S_Release);
2659     S.RRI.ReleaseMetadata = ReleaseMetadata;
2660     S.RRI.KnownSafe = S.IsKnownIncremented();
2661     S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2662     S.RRI.Calls.insert(Inst);
2663
2664     S.SetKnownPositiveRefCount();
2665     break;
2666   }
2667   case IC_RetainBlock:
2668     // An objc_retainBlock call with just a use may need to be kept,
2669     // because it may be copying a block from the stack to the heap.
2670     if (!IsRetainBlockOptimizable(Inst))
2671       break;
2672     // FALLTHROUGH
2673   case IC_Retain:
2674   case IC_RetainRV: {
2675     Arg = GetObjCArg(Inst);
2676
2677     PtrState &S = MyStates.getPtrBottomUpState(Arg);
2678     S.SetKnownPositiveRefCount();
2679
2680     switch (S.GetSeq()) {
2681     case S_Stop:
2682     case S_Release:
2683     case S_MovableRelease:
2684     case S_Use:
2685       S.RRI.ReverseInsertPts.clear();
2686       // FALL THROUGH
2687     case S_CanRelease:
2688       // Don't do retain+release tracking for IC_RetainRV, because it's
2689       // better to let it remain as the first instruction after a call.
2690       if (Class != IC_RetainRV) {
2691         S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2692         Retains[Inst] = S.RRI;
2693       }
2694       S.ClearSequenceProgress();
2695       break;
2696     case S_None:
2697       break;
2698     case S_Retain:
2699       llvm_unreachable("bottom-up pointer in retain state!");
2700     }
2701     return NestingDetected;
2702   }
2703   case IC_AutoreleasepoolPop:
2704     // Conservatively, clear MyStates for all known pointers.
2705     MyStates.clearBottomUpPointers();
2706     return NestingDetected;
2707   case IC_AutoreleasepoolPush:
2708   case IC_None:
2709     // These are irrelevant.
2710     return NestingDetected;
2711   default:
2712     break;
2713   }
2714
2715   // Consider any other possible effects of this instruction on each
2716   // pointer being tracked.
2717   for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
2718        ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
2719     const Value *Ptr = MI->first;
2720     if (Ptr == Arg)
2721       continue; // Handled above.
2722     PtrState &S = MI->second;
2723     Sequence Seq = S.GetSeq();
2724
2725     // Check for possible releases.
2726     if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2727       S.ClearRefCount();
2728       switch (Seq) {
2729       case S_Use:
2730         S.SetSeq(S_CanRelease);
2731         continue;
2732       case S_CanRelease:
2733       case S_Release:
2734       case S_MovableRelease:
2735       case S_Stop:
2736       case S_None:
2737         break;
2738       case S_Retain:
2739         llvm_unreachable("bottom-up pointer in retain state!");
2740       }
2741     }
2742
2743     // Check for possible direct uses.
2744     switch (Seq) {
2745     case S_Release:
2746     case S_MovableRelease:
2747       if (CanUse(Inst, Ptr, PA, Class)) {
2748         assert(S.RRI.ReverseInsertPts.empty());
2749         // If this is an invoke instruction, we're scanning it as part of
2750         // one of its successor blocks, since we can't insert code after it
2751         // in its own block, and we don't want to split critical edges.
2752         if (isa<InvokeInst>(Inst))
2753           S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2754         else
2755           S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
2756         S.SetSeq(S_Use);
2757       } else if (Seq == S_Release &&
2758                  (Class == IC_User || Class == IC_CallOrUser)) {
2759         // Non-movable releases depend on any possible objc pointer use.
2760         S.SetSeq(S_Stop);
2761         assert(S.RRI.ReverseInsertPts.empty());
2762         // As above; handle invoke specially.
2763         if (isa<InvokeInst>(Inst))
2764           S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2765         else
2766           S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
2767       }
2768       break;
2769     case S_Stop:
2770       if (CanUse(Inst, Ptr, PA, Class))
2771         S.SetSeq(S_Use);
2772       break;
2773     case S_CanRelease:
2774     case S_Use:
2775     case S_None:
2776       break;
2777     case S_Retain:
2778       llvm_unreachable("bottom-up pointer in retain state!");
2779     }
2780   }
2781
2782   return NestingDetected;
2783 }
2784
2785 bool
2786 ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2787                           DenseMap<const BasicBlock *, BBState> &BBStates,
2788                           MapVector<Value *, RRInfo> &Retains) {
2789   bool NestingDetected = false;
2790   BBState &MyStates = BBStates[BB];
2791
2792   // Merge the states from each successor to compute the initial state
2793   // for the current block.
2794   BBState::edge_iterator SI(MyStates.succ_begin()),
2795                          SE(MyStates.succ_end());
2796   if (SI != SE) {
2797     const BasicBlock *Succ = *SI;
2798     DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
2799     assert(I != BBStates.end());
2800     MyStates.InitFromSucc(I->second);
2801     ++SI;
2802     for (; SI != SE; ++SI) {
2803       Succ = *SI;
2804       I = BBStates.find(Succ);
2805       assert(I != BBStates.end());
2806       MyStates.MergeSucc(I->second);
2807     }
2808   }
2809
2810   // Visit all the instructions, bottom-up.
2811   for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2812     Instruction *Inst = llvm::prior(I);
2813
2814     // Invoke instructions are visited as part of their successors (below).
2815     if (isa<InvokeInst>(Inst))
2816       continue;
2817
2818     NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
2819   }
2820
2821   // If there's a predecessor with an invoke, visit the invoke as if it were
2822   // part of this block, since we can't insert code after an invoke in its own
2823   // block, and we don't want to split critical edges.
2824   for (BBState::edge_iterator PI(MyStates.pred_begin()),
2825        PE(MyStates.pred_end()); PI != PE; ++PI) {
2826     BasicBlock *Pred = *PI;
2827     if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
2828       NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
2829   }
2830
2831   return NestingDetected;
2832 }
2833
2834 bool
2835 ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
2836                                     DenseMap<Value *, RRInfo> &Releases,
2837                                     BBState &MyStates) {
2838   bool NestingDetected = false;
2839   InstructionClass Class = GetInstructionClass(Inst);
2840   const Value *Arg = 0;
2841
2842   switch (Class) {
2843   case IC_RetainBlock:
2844     // An objc_retainBlock call with just a use may need to be kept,
2845     // because it may be copying a block from the stack to the heap.
2846     if (!IsRetainBlockOptimizable(Inst))
2847       break;
2848     // FALLTHROUGH
2849   case IC_Retain:
2850   case IC_RetainRV: {
2851     Arg = GetObjCArg(Inst);
2852
2853     PtrState &S = MyStates.getPtrTopDownState(Arg);
2854
2855     // Don't do retain+release tracking for IC_RetainRV, because it's
2856     // better to let it remain as the first instruction after a call.
2857     if (Class != IC_RetainRV) {
2858       // If we see two retains in a row on the same pointer. If so, make
2859       // a note, and we'll cicle back to revisit it after we've
2860       // hopefully eliminated the second retain, which may allow us to
2861       // eliminate the first retain too.
2862       // Theoretically we could implement removal of nested retain+release
2863       // pairs by making PtrState hold a stack of states, but this is
2864       // simple and avoids adding overhead for the non-nested case.
2865       if (S.GetSeq() == S_Retain)
2866         NestingDetected = true;
2867
2868       S.ResetSequenceProgress(S_Retain);
2869       S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2870       S.RRI.KnownSafe = S.IsKnownIncremented();
2871       S.RRI.Calls.insert(Inst);
2872     }
2873
2874     S.SetKnownPositiveRefCount();
2875
2876     // A retain can be a potential use; procede to the generic checking
2877     // code below.
2878     break;
2879   }
2880   case IC_Release: {
2881     Arg = GetObjCArg(Inst);
2882
2883     PtrState &S = MyStates.getPtrTopDownState(Arg);
2884     S.ClearRefCount();
2885
2886     switch (S.GetSeq()) {
2887     case S_Retain:
2888     case S_CanRelease:
2889       S.RRI.ReverseInsertPts.clear();
2890       // FALL THROUGH
2891     case S_Use:
2892       S.RRI.ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2893       S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2894       Releases[Inst] = S.RRI;
2895       S.ClearSequenceProgress();
2896       break;
2897     case S_None:
2898       break;
2899     case S_Stop:
2900     case S_Release:
2901     case S_MovableRelease:
2902       llvm_unreachable("top-down pointer in release state!");
2903     }
2904     break;
2905   }
2906   case IC_AutoreleasepoolPop:
2907     // Conservatively, clear MyStates for all known pointers.
2908     MyStates.clearTopDownPointers();
2909     return NestingDetected;
2910   case IC_AutoreleasepoolPush:
2911   case IC_None:
2912     // These are irrelevant.
2913     return NestingDetected;
2914   default:
2915     break;
2916   }
2917
2918   // Consider any other possible effects of this instruction on each
2919   // pointer being tracked.
2920   for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
2921        ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
2922     const Value *Ptr = MI->first;
2923     if (Ptr == Arg)
2924       continue; // Handled above.
2925     PtrState &S = MI->second;
2926     Sequence Seq = S.GetSeq();
2927
2928     // Check for possible releases.
2929     if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2930       S.ClearRefCount();
2931       switch (Seq) {
2932       case S_Retain:
2933         S.SetSeq(S_CanRelease);
2934         assert(S.RRI.ReverseInsertPts.empty());
2935         S.RRI.ReverseInsertPts.insert(Inst);
2936
2937         // One call can't cause a transition from S_Retain to S_CanRelease
2938         // and S_CanRelease to S_Use. If we've made the first transition,
2939         // we're done.
2940         continue;
2941       case S_Use:
2942       case S_CanRelease:
2943       case S_None:
2944         break;
2945       case S_Stop:
2946       case S_Release:
2947       case S_MovableRelease:
2948         llvm_unreachable("top-down pointer in release state!");
2949       }
2950     }
2951
2952     // Check for possible direct uses.
2953     switch (Seq) {
2954     case S_CanRelease:
2955       if (CanUse(Inst, Ptr, PA, Class))
2956         S.SetSeq(S_Use);
2957       break;
2958     case S_Retain:
2959     case S_Use:
2960     case S_None:
2961       break;
2962     case S_Stop:
2963     case S_Release:
2964     case S_MovableRelease:
2965       llvm_unreachable("top-down pointer in release state!");
2966     }
2967   }
2968
2969   return NestingDetected;
2970 }
2971
2972 bool
2973 ObjCARCOpt::VisitTopDown(BasicBlock *BB,
2974                          DenseMap<const BasicBlock *, BBState> &BBStates,
2975                          DenseMap<Value *, RRInfo> &Releases) {
2976   bool NestingDetected = false;
2977   BBState &MyStates = BBStates[BB];
2978
2979   // Merge the states from each predecessor to compute the initial state
2980   // for the current block.
2981   BBState::edge_iterator PI(MyStates.pred_begin()),
2982                          PE(MyStates.pred_end());
2983   if (PI != PE) {
2984     const BasicBlock *Pred = *PI;
2985     DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
2986     assert(I != BBStates.end());
2987     MyStates.InitFromPred(I->second);
2988     ++PI;
2989     for (; PI != PE; ++PI) {
2990       Pred = *PI;
2991       I = BBStates.find(Pred);
2992       assert(I != BBStates.end());
2993       MyStates.MergePred(I->second);
2994     }
2995   }
2996
2997   // Visit all the instructions, top-down.
2998   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2999     Instruction *Inst = I;
3000     NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
3001   }
3002
3003   CheckForCFGHazards(BB, BBStates, MyStates);
3004   return NestingDetected;
3005 }
3006
3007 static void
3008 ComputePostOrders(Function &F,
3009                   SmallVectorImpl<BasicBlock *> &PostOrder,
3010                   SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
3011                   unsigned NoObjCARCExceptionsMDKind,
3012                   DenseMap<const BasicBlock *, BBState> &BBStates) {
3013   /// Visited - The visited set, for doing DFS walks.
3014   SmallPtrSet<BasicBlock *, 16> Visited;
3015
3016   // Do DFS, computing the PostOrder.
3017   SmallPtrSet<BasicBlock *, 16> OnStack;
3018   SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
3019
3020   // Functions always have exactly one entry block, and we don't have
3021   // any other block that we treat like an entry block.
3022   BasicBlock *EntryBB = &F.getEntryBlock();
3023   BBState &MyStates = BBStates[EntryBB];
3024   MyStates.SetAsEntry();
3025   TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
3026   SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
3027   Visited.insert(EntryBB);
3028   OnStack.insert(EntryBB);
3029   do {
3030   dfs_next_succ:
3031     BasicBlock *CurrBB = SuccStack.back().first;
3032     TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
3033     succ_iterator SE(TI, false);
3034
3035     // If the terminator is an invoke marked with the
3036     // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
3037     // ignored, for ARC purposes.
3038     if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind))
3039       --SE;
3040
3041     while (SuccStack.back().second != SE) {
3042       BasicBlock *SuccBB = *SuccStack.back().second++;
3043       if (Visited.insert(SuccBB)) {
3044         TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
3045         SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
3046         BBStates[CurrBB].addSucc(SuccBB);
3047         BBState &SuccStates = BBStates[SuccBB];
3048         SuccStates.addPred(CurrBB);
3049         OnStack.insert(SuccBB);
3050         goto dfs_next_succ;
3051       }
3052
3053       if (!OnStack.count(SuccBB)) {
3054         BBStates[CurrBB].addSucc(SuccBB);
3055         BBStates[SuccBB].addPred(CurrBB);
3056       }
3057     }
3058     OnStack.erase(CurrBB);
3059     PostOrder.push_back(CurrBB);
3060     SuccStack.pop_back();
3061   } while (!SuccStack.empty());
3062
3063   Visited.clear();
3064
3065   // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
3066   // Functions may have many exits, and there also blocks which we treat
3067   // as exits due to ignored edges.
3068   SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
3069   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
3070     BasicBlock *ExitBB = I;
3071     BBState &MyStates = BBStates[ExitBB];
3072     if (!MyStates.isExit())
3073       continue;
3074
3075     MyStates.SetAsExit();
3076
3077     PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
3078     Visited.insert(ExitBB);
3079     while (!PredStack.empty()) {
3080     reverse_dfs_next_succ:
3081       BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
3082       while (PredStack.back().second != PE) {
3083         BasicBlock *BB = *PredStack.back().second++;
3084         if (Visited.insert(BB)) {
3085           PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
3086           goto reverse_dfs_next_succ;
3087         }
3088       }
3089       ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
3090     }
3091   }
3092 }
3093
3094 // Visit - Visit the function both top-down and bottom-up.
3095 bool
3096 ObjCARCOpt::Visit(Function &F,
3097                   DenseMap<const BasicBlock *, BBState> &BBStates,
3098                   MapVector<Value *, RRInfo> &Retains,
3099                   DenseMap<Value *, RRInfo> &Releases) {
3100
3101   // Use reverse-postorder traversals, because we magically know that loops
3102   // will be well behaved, i.e. they won't repeatedly call retain on a single
3103   // pointer without doing a release. We can't use the ReversePostOrderTraversal
3104   // class here because we want the reverse-CFG postorder to consider each
3105   // function exit point, and we want to ignore selected cycle edges.
3106   SmallVector<BasicBlock *, 16> PostOrder;
3107   SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
3108   ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
3109                     NoObjCARCExceptionsMDKind,
3110                     BBStates);
3111
3112   // Use reverse-postorder on the reverse CFG for bottom-up.
3113   bool BottomUpNestingDetected = false;
3114   for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
3115        ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
3116        I != E; ++I)
3117     BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
3118
3119   // Use reverse-postorder for top-down.
3120   bool TopDownNestingDetected = false;
3121   for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
3122        PostOrder.rbegin(), E = PostOrder.rend();
3123        I != E; ++I)
3124     TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
3125
3126   return TopDownNestingDetected && BottomUpNestingDetected;
3127 }
3128
3129 /// MoveCalls - Move the calls in RetainsToMove and ReleasesToMove.
3130 void ObjCARCOpt::MoveCalls(Value *Arg,
3131                            RRInfo &RetainsToMove,
3132                            RRInfo &ReleasesToMove,
3133                            MapVector<Value *, RRInfo> &Retains,
3134                            DenseMap<Value *, RRInfo> &Releases,
3135                            SmallVectorImpl<Instruction *> &DeadInsts,
3136                            Module *M) {
3137   Type *ArgTy = Arg->getType();
3138   Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
3139
3140   // Insert the new retain and release calls.
3141   for (SmallPtrSet<Instruction *, 2>::const_iterator
3142        PI = ReleasesToMove.ReverseInsertPts.begin(),
3143        PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
3144     Instruction *InsertPt = *PI;
3145     Value *MyArg = ArgTy == ParamTy ? Arg :
3146                    new BitCastInst(Arg, ParamTy, "", InsertPt);
3147     CallInst *Call =
3148       CallInst::Create(RetainsToMove.IsRetainBlock ?
3149                          getRetainBlockCallee(M) : getRetainCallee(M),
3150                        MyArg, "", InsertPt);
3151     Call->setDoesNotThrow();
3152     if (RetainsToMove.IsRetainBlock)
3153       Call->setMetadata(CopyOnEscapeMDKind,
3154                         MDNode::get(M->getContext(), ArrayRef<Value *>()));
3155     else
3156       Call->setTailCall();
3157   }
3158   for (SmallPtrSet<Instruction *, 2>::const_iterator
3159        PI = RetainsToMove.ReverseInsertPts.begin(),
3160        PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
3161     Instruction *InsertPt = *PI;
3162     Value *MyArg = ArgTy == ParamTy ? Arg :
3163                    new BitCastInst(Arg, ParamTy, "", InsertPt);
3164     CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
3165                                       "", InsertPt);
3166     // Attach a clang.imprecise_release metadata tag, if appropriate.
3167     if (MDNode *M = ReleasesToMove.ReleaseMetadata)
3168       Call->setMetadata(ImpreciseReleaseMDKind, M);
3169     Call->setDoesNotThrow();
3170     if (ReleasesToMove.IsTailCallRelease)
3171       Call->setTailCall();
3172   }
3173
3174   // Delete the original retain and release calls.
3175   for (SmallPtrSet<Instruction *, 2>::const_iterator
3176        AI = RetainsToMove.Calls.begin(),
3177        AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
3178     Instruction *OrigRetain = *AI;
3179     Retains.blot(OrigRetain);
3180     DeadInsts.push_back(OrigRetain);
3181   }
3182   for (SmallPtrSet<Instruction *, 2>::const_iterator
3183        AI = ReleasesToMove.Calls.begin(),
3184        AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
3185     Instruction *OrigRelease = *AI;
3186     Releases.erase(OrigRelease);
3187     DeadInsts.push_back(OrigRelease);
3188   }
3189 }
3190
3191 /// PerformCodePlacement - Identify pairings between the retains and releases,
3192 /// and delete and/or move them.
3193 bool
3194 ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
3195                                    &BBStates,
3196                                  MapVector<Value *, RRInfo> &Retains,
3197                                  DenseMap<Value *, RRInfo> &Releases,
3198                                  Module *M) {
3199   bool AnyPairsCompletelyEliminated = false;
3200   RRInfo RetainsToMove;
3201   RRInfo ReleasesToMove;
3202   SmallVector<Instruction *, 4> NewRetains;
3203   SmallVector<Instruction *, 4> NewReleases;
3204   SmallVector<Instruction *, 8> DeadInsts;
3205
3206   // Visit each retain.
3207   for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
3208        E = Retains.end(); I != E; ++I) {
3209     Value *V = I->first;
3210     if (!V) continue; // blotted
3211
3212     Instruction *Retain = cast<Instruction>(V);
3213     Value *Arg = GetObjCArg(Retain);
3214
3215     // If the object being released is in static or stack storage, we know it's
3216     // not being managed by ObjC reference counting, so we can delete pairs
3217     // regardless of what possible decrements or uses lie between them.
3218     bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
3219
3220     // A constant pointer can't be pointing to an object on the heap. It may
3221     // be reference-counted, but it won't be deleted.
3222     if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
3223       if (const GlobalVariable *GV =
3224             dyn_cast<GlobalVariable>(
3225               StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
3226         if (GV->isConstant())
3227           KnownSafe = true;
3228
3229     // If a pair happens in a region where it is known that the reference count
3230     // is already incremented, we can similarly ignore possible decrements.
3231     bool KnownSafeTD = true, KnownSafeBU = true;
3232
3233     // Connect the dots between the top-down-collected RetainsToMove and
3234     // bottom-up-collected ReleasesToMove to form sets of related calls.
3235     // This is an iterative process so that we connect multiple releases
3236     // to multiple retains if needed.
3237     unsigned OldDelta = 0;
3238     unsigned NewDelta = 0;
3239     unsigned OldCount = 0;
3240     unsigned NewCount = 0;
3241     bool FirstRelease = true;
3242     bool FirstRetain = true;
3243     NewRetains.push_back(Retain);
3244     for (;;) {
3245       for (SmallVectorImpl<Instruction *>::const_iterator
3246            NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
3247         Instruction *NewRetain = *NI;
3248         MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
3249         assert(It != Retains.end());
3250         const RRInfo &NewRetainRRI = It->second;
3251         KnownSafeTD &= NewRetainRRI.KnownSafe;
3252         for (SmallPtrSet<Instruction *, 2>::const_iterator
3253              LI = NewRetainRRI.Calls.begin(),
3254              LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
3255           Instruction *NewRetainRelease = *LI;
3256           DenseMap<Value *, RRInfo>::const_iterator Jt =
3257             Releases.find(NewRetainRelease);
3258           if (Jt == Releases.end())
3259             goto next_retain;
3260           const RRInfo &NewRetainReleaseRRI = Jt->second;
3261           assert(NewRetainReleaseRRI.Calls.count(NewRetain));
3262           if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
3263             OldDelta -=
3264               BBStates[NewRetainRelease->getParent()].GetAllPathCount();
3265
3266             // Merge the ReleaseMetadata and IsTailCallRelease values.
3267             if (FirstRelease) {
3268               ReleasesToMove.ReleaseMetadata =
3269                 NewRetainReleaseRRI.ReleaseMetadata;
3270               ReleasesToMove.IsTailCallRelease =
3271                 NewRetainReleaseRRI.IsTailCallRelease;
3272               FirstRelease = false;
3273             } else {
3274               if (ReleasesToMove.ReleaseMetadata !=
3275                     NewRetainReleaseRRI.ReleaseMetadata)
3276                 ReleasesToMove.ReleaseMetadata = 0;
3277               if (ReleasesToMove.IsTailCallRelease !=
3278                     NewRetainReleaseRRI.IsTailCallRelease)
3279                 ReleasesToMove.IsTailCallRelease = false;
3280             }
3281
3282             // Collect the optimal insertion points.
3283             if (!KnownSafe)
3284               for (SmallPtrSet<Instruction *, 2>::const_iterator
3285                    RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
3286                    RE = NewRetainReleaseRRI.ReverseInsertPts.end();
3287                    RI != RE; ++RI) {
3288                 Instruction *RIP = *RI;
3289                 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
3290                   NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
3291               }
3292             NewReleases.push_back(NewRetainRelease);
3293           }
3294         }
3295       }
3296       NewRetains.clear();
3297       if (NewReleases.empty()) break;
3298
3299       // Back the other way.
3300       for (SmallVectorImpl<Instruction *>::const_iterator
3301            NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
3302         Instruction *NewRelease = *NI;
3303         DenseMap<Value *, RRInfo>::const_iterator It =
3304           Releases.find(NewRelease);
3305         assert(It != Releases.end());
3306         const RRInfo &NewReleaseRRI = It->second;
3307         KnownSafeBU &= NewReleaseRRI.KnownSafe;
3308         for (SmallPtrSet<Instruction *, 2>::const_iterator
3309              LI = NewReleaseRRI.Calls.begin(),
3310              LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
3311           Instruction *NewReleaseRetain = *LI;
3312           MapVector<Value *, RRInfo>::const_iterator Jt =
3313             Retains.find(NewReleaseRetain);
3314           if (Jt == Retains.end())
3315             goto next_retain;
3316           const RRInfo &NewReleaseRetainRRI = Jt->second;
3317           assert(NewReleaseRetainRRI.Calls.count(NewRelease));
3318           if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
3319             unsigned PathCount =
3320               BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
3321             OldDelta += PathCount;
3322             OldCount += PathCount;
3323
3324             // Merge the IsRetainBlock values.
3325             if (FirstRetain) {
3326               RetainsToMove.IsRetainBlock = NewReleaseRetainRRI.IsRetainBlock;
3327               FirstRetain = false;
3328             } else if (ReleasesToMove.IsRetainBlock !=
3329                        NewReleaseRetainRRI.IsRetainBlock)
3330               // It's not possible to merge the sequences if one uses
3331               // objc_retain and the other uses objc_retainBlock.
3332               goto next_retain;
3333
3334             // Collect the optimal insertion points.
3335             if (!KnownSafe)
3336               for (SmallPtrSet<Instruction *, 2>::const_iterator
3337                    RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
3338                    RE = NewReleaseRetainRRI.ReverseInsertPts.end();
3339                    RI != RE; ++RI) {
3340                 Instruction *RIP = *RI;
3341                 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
3342                   PathCount = BBStates[RIP->getParent()].GetAllPathCount();
3343                   NewDelta += PathCount;
3344                   NewCount += PathCount;
3345                 }
3346               }
3347             NewRetains.push_back(NewReleaseRetain);
3348           }
3349         }
3350       }
3351       NewReleases.clear();
3352       if (NewRetains.empty()) break;
3353     }
3354
3355     // If the pointer is known incremented or nested, we can safely delete the
3356     // pair regardless of what's between them.
3357     if (KnownSafeTD || KnownSafeBU) {
3358       RetainsToMove.ReverseInsertPts.clear();
3359       ReleasesToMove.ReverseInsertPts.clear();
3360       NewCount = 0;
3361     } else {
3362       // Determine whether the new insertion points we computed preserve the
3363       // balance of retain and release calls through the program.
3364       // TODO: If the fully aggressive solution isn't valid, try to find a
3365       // less aggressive solution which is.
3366       if (NewDelta != 0)
3367         goto next_retain;
3368     }
3369
3370     // Determine whether the original call points are balanced in the retain and
3371     // release calls through the program. If not, conservatively don't touch
3372     // them.
3373     // TODO: It's theoretically possible to do code motion in this case, as
3374     // long as the existing imbalances are maintained.
3375     if (OldDelta != 0)
3376       goto next_retain;
3377
3378     // Ok, everything checks out and we're all set. Let's move some code!
3379     Changed = true;
3380     assert(OldCount != 0 && "Unreachable code?");
3381     AnyPairsCompletelyEliminated = NewCount == 0;
3382     NumRRs += OldCount - NewCount;
3383     MoveCalls(Arg, RetainsToMove, ReleasesToMove,
3384               Retains, Releases, DeadInsts, M);
3385
3386   next_retain:
3387     NewReleases.clear();
3388     NewRetains.clear();
3389     RetainsToMove.clear();
3390     ReleasesToMove.clear();
3391   }
3392
3393   // Now that we're done moving everything, we can delete the newly dead
3394   // instructions, as we no longer need them as insert points.
3395   while (!DeadInsts.empty())
3396     EraseInstruction(DeadInsts.pop_back_val());
3397
3398   return AnyPairsCompletelyEliminated;
3399 }
3400
3401 /// OptimizeWeakCalls - Weak pointer optimizations.
3402 void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
3403   // First, do memdep-style RLE and S2L optimizations. We can't use memdep
3404   // itself because it uses AliasAnalysis and we need to do provenance
3405   // queries instead.
3406   for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3407     Instruction *Inst = &*I++;
3408
3409     DEBUG(dbgs() << "ObjCARCOpt: OptimizeWeakCalls: Visiting: " << *Inst <<
3410           "\n");
3411
3412     InstructionClass Class = GetBasicInstructionClass(Inst);
3413     if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
3414       continue;
3415
3416     // Delete objc_loadWeak calls with no users.
3417     if (Class == IC_LoadWeak && Inst->use_empty()) {
3418       Inst->eraseFromParent();
3419       continue;
3420     }
3421
3422     // TODO: For now, just look for an earlier available version of this value
3423     // within the same block. Theoretically, we could do memdep-style non-local
3424     // analysis too, but that would want caching. A better approach would be to
3425     // use the technique that EarlyCSE uses.
3426     inst_iterator Current = llvm::prior(I);
3427     BasicBlock *CurrentBB = Current.getBasicBlockIterator();
3428     for (BasicBlock::iterator B = CurrentBB->begin(),
3429                               J = Current.getInstructionIterator();
3430          J != B; --J) {
3431       Instruction *EarlierInst = &*llvm::prior(J);
3432       InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
3433       switch (EarlierClass) {
3434       case IC_LoadWeak:
3435       case IC_LoadWeakRetained: {
3436         // If this is loading from the same pointer, replace this load's value
3437         // with that one.
3438         CallInst *Call = cast<CallInst>(Inst);
3439         CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3440         Value *Arg = Call->getArgOperand(0);
3441         Value *EarlierArg = EarlierCall->getArgOperand(0);
3442         switch (PA.getAA()->alias(Arg, EarlierArg)) {
3443         case AliasAnalysis::MustAlias:
3444           Changed = true;
3445           // If the load has a builtin retain, insert a plain retain for it.
3446           if (Class == IC_LoadWeakRetained) {
3447             CallInst *CI =
3448               CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3449                                "", Call);
3450             CI->setTailCall();
3451           }
3452           // Zap the fully redundant load.
3453           Call->replaceAllUsesWith(EarlierCall);
3454           Call->eraseFromParent();
3455           goto clobbered;
3456         case AliasAnalysis::MayAlias:
3457         case AliasAnalysis::PartialAlias:
3458           goto clobbered;
3459         case AliasAnalysis::NoAlias:
3460           break;
3461         }
3462         break;
3463       }
3464       case IC_StoreWeak:
3465       case IC_InitWeak: {
3466         // If this is storing to the same pointer and has the same size etc.
3467         // replace this load's value with the stored value.
3468         CallInst *Call = cast<CallInst>(Inst);
3469         CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3470         Value *Arg = Call->getArgOperand(0);
3471         Value *EarlierArg = EarlierCall->getArgOperand(0);
3472         switch (PA.getAA()->alias(Arg, EarlierArg)) {
3473         case AliasAnalysis::MustAlias:
3474           Changed = true;
3475           // If the load has a builtin retain, insert a plain retain for it.
3476           if (Class == IC_LoadWeakRetained) {
3477             CallInst *CI =
3478               CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3479                                "", Call);
3480             CI->setTailCall();
3481           }
3482           // Zap the fully redundant load.
3483           Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
3484           Call->eraseFromParent();
3485           goto clobbered;
3486         case AliasAnalysis::MayAlias:
3487         case AliasAnalysis::PartialAlias:
3488           goto clobbered;
3489         case AliasAnalysis::NoAlias:
3490           break;
3491         }
3492         break;
3493       }
3494       case IC_MoveWeak:
3495       case IC_CopyWeak:
3496         // TOOD: Grab the copied value.
3497         goto clobbered;
3498       case IC_AutoreleasepoolPush:
3499       case IC_None:
3500       case IC_User:
3501         // Weak pointers are only modified through the weak entry points
3502         // (and arbitrary calls, which could call the weak entry points).
3503         break;
3504       default:
3505         // Anything else could modify the weak pointer.
3506         goto clobbered;
3507       }
3508     }
3509   clobbered:;
3510   }
3511
3512   // Then, for each destroyWeak with an alloca operand, check to see if
3513   // the alloca and all its users can be zapped.
3514   for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3515     Instruction *Inst = &*I++;
3516     InstructionClass Class = GetBasicInstructionClass(Inst);
3517     if (Class != IC_DestroyWeak)
3518       continue;
3519
3520     CallInst *Call = cast<CallInst>(Inst);
3521     Value *Arg = Call->getArgOperand(0);
3522     if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
3523       for (Value::use_iterator UI = Alloca->use_begin(),
3524            UE = Alloca->use_end(); UI != UE; ++UI) {
3525         const Instruction *UserInst = cast<Instruction>(*UI);
3526         switch (GetBasicInstructionClass(UserInst)) {
3527         case IC_InitWeak:
3528         case IC_StoreWeak:
3529         case IC_DestroyWeak:
3530           continue;
3531         default:
3532           goto done;
3533         }
3534       }
3535       Changed = true;
3536       for (Value::use_iterator UI = Alloca->use_begin(),
3537            UE = Alloca->use_end(); UI != UE; ) {
3538         CallInst *UserInst = cast<CallInst>(*UI++);
3539         switch (GetBasicInstructionClass(UserInst)) {
3540         case IC_InitWeak:
3541         case IC_StoreWeak:
3542           // These functions return their second argument.
3543           UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
3544           break;
3545         case IC_DestroyWeak:
3546           // No return value.
3547           break;
3548         default:
3549           llvm_unreachable("alloca really is used!");
3550         }
3551         UserInst->eraseFromParent();
3552       }
3553       Alloca->eraseFromParent();
3554     done:;
3555     }
3556   }
3557   
3558   DEBUG(dbgs() << "ObjCARCOpt: Finished visiting weak calls.\n\n");
3559   
3560 }
3561
3562 /// OptimizeSequences - Identify program paths which execute sequences of
3563 /// retains and releases which can be eliminated.
3564 bool ObjCARCOpt::OptimizeSequences(Function &F) {
3565   /// Releases, Retains - These are used to store the results of the main flow
3566   /// analysis. These use Value* as the key instead of Instruction* so that the
3567   /// map stays valid when we get around to rewriting code and calls get
3568   /// replaced by arguments.
3569   DenseMap<Value *, RRInfo> Releases;
3570   MapVector<Value *, RRInfo> Retains;
3571
3572   /// BBStates, This is used during the traversal of the function to track the
3573   /// states for each identified object at each block.
3574   DenseMap<const BasicBlock *, BBState> BBStates;
3575
3576   // Analyze the CFG of the function, and all instructions.
3577   bool NestingDetected = Visit(F, BBStates, Retains, Releases);
3578
3579   // Transform.
3580   return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) &&
3581          NestingDetected;
3582 }
3583
3584 /// OptimizeReturns - Look for this pattern:
3585 /// \code
3586 ///    %call = call i8* @something(...)
3587 ///    %2 = call i8* @objc_retain(i8* %call)
3588 ///    %3 = call i8* @objc_autorelease(i8* %2)
3589 ///    ret i8* %3
3590 /// \endcode
3591 /// And delete the retain and autorelease.
3592 ///
3593 /// Otherwise if it's just this:
3594 /// \code
3595 ///    %3 = call i8* @objc_autorelease(i8* %2)
3596 ///    ret i8* %3
3597 /// \endcode
3598 /// convert the autorelease to autoreleaseRV.
3599 void ObjCARCOpt::OptimizeReturns(Function &F) {
3600   if (!F.getReturnType()->isPointerTy())
3601     return;
3602
3603   SmallPtrSet<Instruction *, 4> DependingInstructions;
3604   SmallPtrSet<const BasicBlock *, 4> Visited;
3605   for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3606     BasicBlock *BB = FI;
3607     ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
3608
3609     DEBUG(dbgs() << "ObjCARCOpt: OptimizeReturns: Visiting: " << *Ret << "\n");
3610
3611     if (!Ret) continue;
3612
3613     const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
3614     FindDependencies(NeedsPositiveRetainCount, Arg,
3615                      BB, Ret, DependingInstructions, Visited, PA);
3616     if (DependingInstructions.size() != 1)
3617       goto next_block;
3618
3619     {
3620       CallInst *Autorelease =
3621         dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3622       if (!Autorelease)
3623         goto next_block;
3624       InstructionClass AutoreleaseClass = GetBasicInstructionClass(Autorelease);
3625       if (!IsAutorelease(AutoreleaseClass))
3626         goto next_block;
3627       if (GetObjCArg(Autorelease) != Arg)
3628         goto next_block;
3629
3630       DependingInstructions.clear();
3631       Visited.clear();
3632
3633       // Check that there is nothing that can affect the reference
3634       // count between the autorelease and the retain.
3635       FindDependencies(CanChangeRetainCount, Arg,
3636                        BB, Autorelease, DependingInstructions, Visited, PA);
3637       if (DependingInstructions.size() != 1)
3638         goto next_block;
3639
3640       {
3641         CallInst *Retain =
3642           dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3643
3644         // Check that we found a retain with the same argument.
3645         if (!Retain ||
3646             !IsRetain(GetBasicInstructionClass(Retain)) ||
3647             GetObjCArg(Retain) != Arg)
3648           goto next_block;
3649
3650         DependingInstructions.clear();
3651         Visited.clear();
3652
3653         // Convert the autorelease to an autoreleaseRV, since it's
3654         // returning the value.
3655         if (AutoreleaseClass == IC_Autorelease) {
3656           Autorelease->setCalledFunction(getAutoreleaseRVCallee(F.getParent()));
3657           AutoreleaseClass = IC_AutoreleaseRV;
3658         }
3659
3660         // Check that there is nothing that can affect the reference
3661         // count between the retain and the call.
3662         // Note that Retain need not be in BB.
3663         FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
3664                          DependingInstructions, Visited, PA);
3665         if (DependingInstructions.size() != 1)
3666           goto next_block;
3667
3668         {
3669           CallInst *Call =
3670             dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3671
3672           // Check that the pointer is the return value of the call.
3673           if (!Call || Arg != Call)
3674             goto next_block;
3675
3676           // Check that the call is a regular call.
3677           InstructionClass Class = GetBasicInstructionClass(Call);
3678           if (Class != IC_CallOrUser && Class != IC_Call)
3679             goto next_block;
3680
3681           // If so, we can zap the retain and autorelease.
3682           Changed = true;
3683           ++NumRets;
3684           EraseInstruction(Retain);
3685           EraseInstruction(Autorelease);
3686         }
3687       }
3688     }
3689
3690   next_block:
3691     DependingInstructions.clear();
3692     Visited.clear();
3693   }
3694   
3695   DEBUG(dbgs() << "ObjCARCOpt: OptimizeReturns: Finished visiting returns.\n\n");
3696   
3697 }
3698
3699 bool ObjCARCOpt::doInitialization(Module &M) {
3700   if (!EnableARCOpts)
3701     return false;
3702
3703   // If nothing in the Module uses ARC, don't do anything.
3704   Run = ModuleHasARC(M);
3705   if (!Run)
3706     return false;
3707
3708   // Identify the imprecise release metadata kind.
3709   ImpreciseReleaseMDKind =
3710     M.getContext().getMDKindID("clang.imprecise_release");
3711   CopyOnEscapeMDKind =
3712     M.getContext().getMDKindID("clang.arc.copy_on_escape");
3713   NoObjCARCExceptionsMDKind =
3714     M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
3715
3716   // Intuitively, objc_retain and others are nocapture, however in practice
3717   // they are not, because they return their argument value. And objc_release
3718   // calls finalizers which can have arbitrary side effects.
3719
3720   // These are initialized lazily.
3721   RetainRVCallee = 0;
3722   AutoreleaseRVCallee = 0;
3723   ReleaseCallee = 0;
3724   RetainCallee = 0;
3725   RetainBlockCallee = 0;
3726   AutoreleaseCallee = 0;
3727
3728   return false;
3729 }
3730
3731 bool ObjCARCOpt::runOnFunction(Function &F) {
3732   if (!EnableARCOpts)
3733     return false;
3734
3735   // If nothing in the Module uses ARC, don't do anything.
3736   if (!Run)
3737     return false;
3738
3739   Changed = false;
3740
3741   PA.setAA(&getAnalysis<AliasAnalysis>());
3742
3743   // This pass performs several distinct transformations. As a compile-time aid
3744   // when compiling code that isn't ObjC, skip these if the relevant ObjC
3745   // library functions aren't declared.
3746
3747   // Preliminary optimizations. This also computs UsedInThisFunction.
3748   OptimizeIndividualCalls(F);
3749
3750   // Optimizations for weak pointers.
3751   if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3752                             (1 << IC_LoadWeakRetained) |
3753                             (1 << IC_StoreWeak) |
3754                             (1 << IC_InitWeak) |
3755                             (1 << IC_CopyWeak) |
3756                             (1 << IC_MoveWeak) |
3757                             (1 << IC_DestroyWeak)))
3758     OptimizeWeakCalls(F);
3759
3760   // Optimizations for retain+release pairs.
3761   if (UsedInThisFunction & ((1 << IC_Retain) |
3762                             (1 << IC_RetainRV) |
3763                             (1 << IC_RetainBlock)))
3764     if (UsedInThisFunction & (1 << IC_Release))
3765       // Run OptimizeSequences until it either stops making changes or
3766       // no retain+release pair nesting is detected.
3767       while (OptimizeSequences(F)) {}
3768
3769   // Optimizations if objc_autorelease is used.
3770   if (UsedInThisFunction & ((1 << IC_Autorelease) |
3771                             (1 << IC_AutoreleaseRV)))
3772     OptimizeReturns(F);
3773
3774   return Changed;
3775 }
3776
3777 void ObjCARCOpt::releaseMemory() {
3778   PA.clear();
3779 }
3780
3781 //===----------------------------------------------------------------------===//
3782 // ARC contraction.
3783 //===----------------------------------------------------------------------===//
3784
3785 // TODO: ObjCARCContract could insert PHI nodes when uses aren't
3786 // dominated by single calls.
3787
3788 #include "llvm/Analysis/Dominators.h"
3789 #include "llvm/IR/InlineAsm.h"
3790 #include "llvm/IR/Operator.h"
3791
3792 STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed");
3793
3794 namespace {
3795   /// ObjCARCContract - Late ARC optimizations.  These change the IR in a way
3796   /// that makes it difficult to be analyzed by ObjCARCOpt, so it's run late.
3797   class ObjCARCContract : public FunctionPass {
3798     bool Changed;
3799     AliasAnalysis *AA;
3800     DominatorTree *DT;
3801     ProvenanceAnalysis PA;
3802
3803     /// Run - A flag indicating whether this optimization pass should run.
3804     bool Run;
3805
3806     /// StoreStrongCallee, etc. - Declarations for ObjC runtime
3807     /// functions, for use in creating calls to them. These are initialized
3808     /// lazily to avoid cluttering up the Module with unused declarations.
3809     Constant *StoreStrongCallee,
3810              *RetainAutoreleaseCallee, *RetainAutoreleaseRVCallee;
3811
3812     /// RetainRVMarker - The inline asm string to insert between calls and
3813     /// RetainRV calls to make the optimization work on targets which need it.
3814     const MDString *RetainRVMarker;
3815
3816     /// StoreStrongCalls - The set of inserted objc_storeStrong calls. If
3817     /// at the end of walking the function we have found no alloca
3818     /// instructions, these calls can be marked "tail".
3819     SmallPtrSet<CallInst *, 8> StoreStrongCalls;
3820
3821     Constant *getStoreStrongCallee(Module *M);
3822     Constant *getRetainAutoreleaseCallee(Module *M);
3823     Constant *getRetainAutoreleaseRVCallee(Module *M);
3824
3825     bool ContractAutorelease(Function &F, Instruction *Autorelease,
3826                              InstructionClass Class,
3827                              SmallPtrSet<Instruction *, 4>
3828                                &DependingInstructions,
3829                              SmallPtrSet<const BasicBlock *, 4>
3830                                &Visited);
3831
3832     void ContractRelease(Instruction *Release,
3833                          inst_iterator &Iter);
3834
3835     virtual void getAnalysisUsage(AnalysisUsage &AU) const;
3836     virtual bool doInitialization(Module &M);
3837     virtual bool runOnFunction(Function &F);
3838
3839   public:
3840     static char ID;
3841     ObjCARCContract() : FunctionPass(ID) {
3842       initializeObjCARCContractPass(*PassRegistry::getPassRegistry());
3843     }
3844   };
3845 }
3846
3847 char ObjCARCContract::ID = 0;
3848 INITIALIZE_PASS_BEGIN(ObjCARCContract,
3849                       "objc-arc-contract", "ObjC ARC contraction", false, false)
3850 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3851 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
3852 INITIALIZE_PASS_END(ObjCARCContract,
3853                     "objc-arc-contract", "ObjC ARC contraction", false, false)
3854
3855 Pass *llvm::createObjCARCContractPass() {
3856   return new ObjCARCContract();
3857 }
3858
3859 void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const {
3860   AU.addRequired<AliasAnalysis>();
3861   AU.addRequired<DominatorTree>();
3862   AU.setPreservesCFG();
3863 }
3864
3865 Constant *ObjCARCContract::getStoreStrongCallee(Module *M) {
3866   if (!StoreStrongCallee) {
3867     LLVMContext &C = M->getContext();
3868     Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3869     Type *I8XX = PointerType::getUnqual(I8X);
3870     Type *Params[] = { I8XX, I8X };
3871
3872     AttributeSet Attribute = AttributeSet()
3873       .addAttr(M->getContext(), AttributeSet::FunctionIndex,
3874                Attribute::get(C, Attribute::NoUnwind))
3875       .addAttr(M->getContext(), 1, Attribute::get(C, Attribute::NoCapture));
3876
3877     StoreStrongCallee =
3878       M->getOrInsertFunction(
3879         "objc_storeStrong",
3880         FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
3881         Attribute);
3882   }
3883   return StoreStrongCallee;
3884 }
3885
3886 Constant *ObjCARCContract::getRetainAutoreleaseCallee(Module *M) {
3887   if (!RetainAutoreleaseCallee) {
3888     LLVMContext &C = M->getContext();
3889     Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3890     Type *Params[] = { I8X };
3891     FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
3892     AttributeSet Attribute =
3893       AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
3894                             Attribute::get(C, Attribute::NoUnwind));
3895     RetainAutoreleaseCallee =
3896       M->getOrInsertFunction("objc_retainAutorelease", FTy, Attribute);
3897   }
3898   return RetainAutoreleaseCallee;
3899 }
3900
3901 Constant *ObjCARCContract::getRetainAutoreleaseRVCallee(Module *M) {
3902   if (!RetainAutoreleaseRVCallee) {
3903     LLVMContext &C = M->getContext();
3904     Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3905     Type *Params[] = { I8X };
3906     FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
3907     AttributeSet Attribute =
3908       AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
3909                             Attribute::get(C, Attribute::NoUnwind));
3910     RetainAutoreleaseRVCallee =
3911       M->getOrInsertFunction("objc_retainAutoreleaseReturnValue", FTy,
3912                              Attribute);
3913   }
3914   return RetainAutoreleaseRVCallee;
3915 }
3916
3917 /// ContractAutorelease - Merge an autorelease with a retain into a fused call.
3918 bool
3919 ObjCARCContract::ContractAutorelease(Function &F, Instruction *Autorelease,
3920                                      InstructionClass Class,
3921                                      SmallPtrSet<Instruction *, 4>
3922                                        &DependingInstructions,
3923                                      SmallPtrSet<const BasicBlock *, 4>
3924                                        &Visited) {
3925   const Value *Arg = GetObjCArg(Autorelease);
3926
3927   // Check that there are no instructions between the retain and the autorelease
3928   // (such as an autorelease_pop) which may change the count.
3929   CallInst *Retain = 0;
3930   if (Class == IC_AutoreleaseRV)
3931     FindDependencies(RetainAutoreleaseRVDep, Arg,
3932                      Autorelease->getParent(), Autorelease,
3933                      DependingInstructions, Visited, PA);
3934   else
3935     FindDependencies(RetainAutoreleaseDep, Arg,
3936                      Autorelease->getParent(), Autorelease,
3937                      DependingInstructions, Visited, PA);
3938
3939   Visited.clear();
3940   if (DependingInstructions.size() != 1) {
3941     DependingInstructions.clear();
3942     return false;
3943   }
3944
3945   Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3946   DependingInstructions.clear();
3947
3948   if (!Retain ||
3949       GetBasicInstructionClass(Retain) != IC_Retain ||
3950       GetObjCArg(Retain) != Arg)
3951     return false;
3952
3953   Changed = true;
3954   ++NumPeeps;
3955
3956   if (Class == IC_AutoreleaseRV)
3957     Retain->setCalledFunction(getRetainAutoreleaseRVCallee(F.getParent()));
3958   else
3959     Retain->setCalledFunction(getRetainAutoreleaseCallee(F.getParent()));
3960
3961   EraseInstruction(Autorelease);
3962   return true;
3963 }
3964
3965 /// ContractRelease - Attempt to merge an objc_release with a store, load, and
3966 /// objc_retain to form an objc_storeStrong. This can be a little tricky because
3967 /// the instructions don't always appear in order, and there may be unrelated
3968 /// intervening instructions.
3969 void ObjCARCContract::ContractRelease(Instruction *Release,
3970                                       inst_iterator &Iter) {
3971   LoadInst *Load = dyn_cast<LoadInst>(GetObjCArg(Release));
3972   if (!Load || !Load->isSimple()) return;
3973
3974   // For now, require everything to be in one basic block.
3975   BasicBlock *BB = Release->getParent();
3976   if (Load->getParent() != BB) return;
3977
3978   // Walk down to find the store and the release, which may be in either order.
3979   BasicBlock::iterator I = Load, End = BB->end();
3980   ++I;
3981   AliasAnalysis::Location Loc = AA->getLocation(Load);
3982   StoreInst *Store = 0;
3983   bool SawRelease = false;
3984   for (; !Store || !SawRelease; ++I) {
3985     if (I == End)
3986       return;
3987
3988     Instruction *Inst = I;
3989     if (Inst == Release) {
3990       SawRelease = true;
3991       continue;
3992     }
3993
3994     InstructionClass Class = GetBasicInstructionClass(Inst);
3995
3996     // Unrelated retains are harmless.
3997     if (IsRetain(Class))
3998       continue;
3999
4000     if (Store) {
4001       // The store is the point where we're going to put the objc_storeStrong,
4002       // so make sure there are no uses after it.
4003       if (CanUse(Inst, Load, PA, Class))
4004         return;
4005     } else if (AA->getModRefInfo(Inst, Loc) & AliasAnalysis::Mod) {
4006       // We are moving the load down to the store, so check for anything
4007       // else which writes to the memory between the load and the store.
4008       Store = dyn_cast<StoreInst>(Inst);
4009       if (!Store || !Store->isSimple()) return;
4010       if (Store->getPointerOperand() != Loc.Ptr) return;
4011     }
4012   }
4013
4014   Value *New = StripPointerCastsAndObjCCalls(Store->getValueOperand());
4015
4016   // Walk up to find the retain.
4017   I = Store;
4018   BasicBlock::iterator Begin = BB->begin();
4019   while (I != Begin && GetBasicInstructionClass(I) != IC_Retain)
4020     --I;
4021   Instruction *Retain = I;
4022   if (GetBasicInstructionClass(Retain) != IC_Retain) return;
4023   if (GetObjCArg(Retain) != New) return;
4024
4025   Changed = true;
4026   ++NumStoreStrongs;
4027
4028   LLVMContext &C = Release->getContext();
4029   Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
4030   Type *I8XX = PointerType::getUnqual(I8X);
4031
4032   Value *Args[] = { Load->getPointerOperand(), New };
4033   if (Args[0]->getType() != I8XX)
4034     Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
4035   if (Args[1]->getType() != I8X)
4036     Args[1] = new BitCastInst(Args[1], I8X, "", Store);
4037   CallInst *StoreStrong =
4038     CallInst::Create(getStoreStrongCallee(BB->getParent()->getParent()),
4039                      Args, "", Store);
4040   StoreStrong->setDoesNotThrow();
4041   StoreStrong->setDebugLoc(Store->getDebugLoc());
4042
4043   // We can't set the tail flag yet, because we haven't yet determined
4044   // whether there are any escaping allocas. Remember this call, so that
4045   // we can set the tail flag once we know it's safe.
4046   StoreStrongCalls.insert(StoreStrong);
4047
4048   if (&*Iter == Store) ++Iter;
4049   Store->eraseFromParent();
4050   Release->eraseFromParent();
4051   EraseInstruction(Retain);
4052   if (Load->use_empty())
4053     Load->eraseFromParent();
4054 }
4055
4056 bool ObjCARCContract::doInitialization(Module &M) {
4057   // If nothing in the Module uses ARC, don't do anything.
4058   Run = ModuleHasARC(M);
4059   if (!Run)
4060     return false;
4061
4062   // These are initialized lazily.
4063   StoreStrongCallee = 0;
4064   RetainAutoreleaseCallee = 0;
4065   RetainAutoreleaseRVCallee = 0;
4066
4067   // Initialize RetainRVMarker.
4068   RetainRVMarker = 0;
4069   if (NamedMDNode *NMD =
4070         M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker"))
4071     if (NMD->getNumOperands() == 1) {
4072       const MDNode *N = NMD->getOperand(0);
4073       if (N->getNumOperands() == 1)
4074         if (const MDString *S = dyn_cast<MDString>(N->getOperand(0)))
4075           RetainRVMarker = S;
4076     }
4077
4078   return false;
4079 }
4080
4081 bool ObjCARCContract::runOnFunction(Function &F) {
4082   if (!EnableARCOpts)
4083     return false;
4084
4085   // If nothing in the Module uses ARC, don't do anything.
4086   if (!Run)
4087     return false;
4088
4089   Changed = false;
4090   AA = &getAnalysis<AliasAnalysis>();
4091   DT = &getAnalysis<DominatorTree>();
4092
4093   PA.setAA(&getAnalysis<AliasAnalysis>());
4094
4095   // Track whether it's ok to mark objc_storeStrong calls with the "tail"
4096   // keyword. Be conservative if the function has variadic arguments.
4097   // It seems that functions which "return twice" are also unsafe for the
4098   // "tail" argument, because they are setjmp, which could need to
4099   // return to an earlier stack state.
4100   bool TailOkForStoreStrongs = !F.isVarArg() &&
4101                                !F.callsFunctionThatReturnsTwice();
4102
4103   // For ObjC library calls which return their argument, replace uses of the
4104   // argument with uses of the call return value, if it dominates the use. This
4105   // reduces register pressure.
4106   SmallPtrSet<Instruction *, 4> DependingInstructions;
4107   SmallPtrSet<const BasicBlock *, 4> Visited;
4108   for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
4109     Instruction *Inst = &*I++;
4110     
4111     DEBUG(dbgs() << "ObjCARCContract: Visiting: " << *Inst << "\n");
4112     
4113     // Only these library routines return their argument. In particular,
4114     // objc_retainBlock does not necessarily return its argument.
4115     InstructionClass Class = GetBasicInstructionClass(Inst);
4116     switch (Class) {
4117     case IC_Retain:
4118     case IC_FusedRetainAutorelease:
4119     case IC_FusedRetainAutoreleaseRV:
4120       break;
4121     case IC_Autorelease:
4122     case IC_AutoreleaseRV:
4123       if (ContractAutorelease(F, Inst, Class, DependingInstructions, Visited))
4124         continue;
4125       break;
4126     case IC_RetainRV: {
4127       // If we're compiling for a target which needs a special inline-asm
4128       // marker to do the retainAutoreleasedReturnValue optimization,
4129       // insert it now.
4130       if (!RetainRVMarker)
4131         break;
4132       BasicBlock::iterator BBI = Inst;
4133       BasicBlock *InstParent = Inst->getParent();
4134
4135       // Step up to see if the call immediately precedes the RetainRV call.
4136       // If it's an invoke, we have to cross a block boundary. And we have
4137       // to carefully dodge no-op instructions.
4138       do {
4139         if (&*BBI == InstParent->begin()) {
4140           BasicBlock *Pred = InstParent->getSinglePredecessor();
4141           if (!Pred)
4142             goto decline_rv_optimization;
4143           BBI = Pred->getTerminator();
4144           break;
4145         }
4146         --BBI;
4147       } while (isNoopInstruction(BBI));
4148
4149       if (&*BBI == GetObjCArg(Inst)) {
4150         Changed = true;
4151         InlineAsm *IA =
4152           InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()),
4153                                            /*isVarArg=*/false),
4154                          RetainRVMarker->getString(),
4155                          /*Constraints=*/"", /*hasSideEffects=*/true);
4156         CallInst::Create(IA, "", Inst);
4157       }
4158     decline_rv_optimization:
4159       break;
4160     }
4161     case IC_InitWeak: {
4162       // objc_initWeak(p, null) => *p = null
4163       CallInst *CI = cast<CallInst>(Inst);
4164       if (isNullOrUndef(CI->getArgOperand(1))) {
4165         Value *Null =
4166           ConstantPointerNull::get(cast<PointerType>(CI->getType()));
4167         Changed = true;
4168         new StoreInst(Null, CI->getArgOperand(0), CI);
4169         CI->replaceAllUsesWith(Null);
4170         CI->eraseFromParent();
4171       }
4172       continue;
4173     }
4174     case IC_Release:
4175       ContractRelease(Inst, I);
4176       continue;
4177     case IC_User:
4178       // Be conservative if the function has any alloca instructions.
4179       // Technically we only care about escaping alloca instructions,
4180       // but this is sufficient to handle some interesting cases.
4181       if (isa<AllocaInst>(Inst))
4182         TailOkForStoreStrongs = false;
4183       continue;
4184     default:
4185       continue;
4186     }
4187
4188     DEBUG(dbgs() << "ObjCARCContract: Finished Queue.\n\n");
4189
4190     // Don't use GetObjCArg because we don't want to look through bitcasts
4191     // and such; to do the replacement, the argument must have type i8*.
4192     const Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
4193     for (;;) {
4194       // If we're compiling bugpointed code, don't get in trouble.
4195       if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
4196         break;
4197       // Look through the uses of the pointer.
4198       for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
4199            UI != UE; ) {
4200         Use &U = UI.getUse();
4201         unsigned OperandNo = UI.getOperandNo();
4202         ++UI; // Increment UI now, because we may unlink its element.
4203
4204         // If the call's return value dominates a use of the call's argument
4205         // value, rewrite the use to use the return value. We check for
4206         // reachability here because an unreachable call is considered to
4207         // trivially dominate itself, which would lead us to rewriting its
4208         // argument in terms of its return value, which would lead to
4209         // infinite loops in GetObjCArg.
4210         if (DT->isReachableFromEntry(U) && DT->dominates(Inst, U)) {
4211           Changed = true;
4212           Instruction *Replacement = Inst;
4213           Type *UseTy = U.get()->getType();
4214           if (PHINode *PHI = dyn_cast<PHINode>(U.getUser())) {
4215             // For PHI nodes, insert the bitcast in the predecessor block.
4216             unsigned ValNo = PHINode::getIncomingValueNumForOperand(OperandNo);
4217             BasicBlock *BB = PHI->getIncomingBlock(ValNo);
4218             if (Replacement->getType() != UseTy)
4219               Replacement = new BitCastInst(Replacement, UseTy, "",
4220                                             &BB->back());
4221             // While we're here, rewrite all edges for this PHI, rather
4222             // than just one use at a time, to minimize the number of
4223             // bitcasts we emit.
4224             for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
4225               if (PHI->getIncomingBlock(i) == BB) {
4226                 // Keep the UI iterator valid.
4227                 if (&PHI->getOperandUse(
4228                       PHINode::getOperandNumForIncomingValue(i)) ==
4229                     &UI.getUse())
4230                   ++UI;
4231                 PHI->setIncomingValue(i, Replacement);
4232               }
4233           } else {
4234             if (Replacement->getType() != UseTy)
4235               Replacement = new BitCastInst(Replacement, UseTy, "",
4236                                             cast<Instruction>(U.getUser()));
4237             U.set(Replacement);
4238           }
4239         }
4240       }
4241
4242       // If Arg is a no-op casted pointer, strip one level of casts and iterate.
4243       if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
4244         Arg = BI->getOperand(0);
4245       else if (isa<GEPOperator>(Arg) &&
4246                cast<GEPOperator>(Arg)->hasAllZeroIndices())
4247         Arg = cast<GEPOperator>(Arg)->getPointerOperand();
4248       else if (isa<GlobalAlias>(Arg) &&
4249                !cast<GlobalAlias>(Arg)->mayBeOverridden())
4250         Arg = cast<GlobalAlias>(Arg)->getAliasee();
4251       else
4252         break;
4253     }
4254   }
4255
4256   // If this function has no escaping allocas or suspicious vararg usage,
4257   // objc_storeStrong calls can be marked with the "tail" keyword.
4258   if (TailOkForStoreStrongs)
4259     for (SmallPtrSet<CallInst *, 8>::iterator I = StoreStrongCalls.begin(),
4260          E = StoreStrongCalls.end(); I != E; ++I)
4261       (*I)->setTailCall();
4262   StoreStrongCalls.clear();
4263
4264   return Changed;
4265 }