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