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