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