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