[objc-arc] Move initialization of ARCMDKindCache into the class itself. I also made...
[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, and numerous minor simplifications.
17 ///
18 /// WARNING: This file knows about certain library functions. It recognizes them
19 /// by name, and hardwires knowledge of their semantics.
20 ///
21 /// WARNING: This file knows about how certain Objective-C library functions are
22 /// used. Naive LLVM IR transformations which would otherwise be
23 /// behavior-preserving may break these assumptions.
24 ///
25 //===----------------------------------------------------------------------===//
26
27 #include "ObjCARC.h"
28 #include "ARCRuntimeEntryPoints.h"
29 #include "DependencyAnalysis.h"
30 #include "ObjCARCAliasAnalysis.h"
31 #include "ProvenanceAnalysis.h"
32 #include "BlotMapVector.h"
33 #include "PtrState.h"
34 #include "llvm/ADT/DenseMap.h"
35 #include "llvm/ADT/DenseSet.h"
36 #include "llvm/ADT/STLExtras.h"
37 #include "llvm/ADT/SmallPtrSet.h"
38 #include "llvm/ADT/Statistic.h"
39 #include "llvm/IR/CFG.h"
40 #include "llvm/IR/IRBuilder.h"
41 #include "llvm/IR/LLVMContext.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/Support/raw_ostream.h"
44
45 using namespace llvm;
46 using namespace llvm::objcarc;
47
48 #define DEBUG_TYPE "objc-arc-opts"
49
50 /// \defgroup ARCUtilities Utility declarations/definitions specific to ARC.
51 /// @{
52
53 /// \brief This is similar to GetRCIdentityRoot but it stops as soon
54 /// as it finds a value with multiple uses.
55 static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
56   if (Arg->hasOneUse()) {
57     if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
58       return FindSingleUseIdentifiedObject(BC->getOperand(0));
59     if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
60       if (GEP->hasAllZeroIndices())
61         return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
62     if (IsForwarding(GetBasicARCInstKind(Arg)))
63       return FindSingleUseIdentifiedObject(
64                cast<CallInst>(Arg)->getArgOperand(0));
65     if (!IsObjCIdentifiedObject(Arg))
66       return nullptr;
67     return Arg;
68   }
69
70   // If we found an identifiable object but it has multiple uses, but they are
71   // trivial uses, we can still consider this to be a single-use value.
72   if (IsObjCIdentifiedObject(Arg)) {
73     for (const User *U : Arg->users())
74       if (!U->use_empty() || GetRCIdentityRoot(U) != Arg)
75          return nullptr;
76
77     return Arg;
78   }
79
80   return nullptr;
81 }
82
83 /// This is a wrapper around getUnderlyingObjCPtr along the lines of
84 /// GetUnderlyingObjects except that it returns early when it sees the first
85 /// alloca.
86 static inline bool AreAnyUnderlyingObjectsAnAlloca(const Value *V,
87                                                    const DataLayout &DL) {
88   SmallPtrSet<const Value *, 4> Visited;
89   SmallVector<const Value *, 4> Worklist;
90   Worklist.push_back(V);
91   do {
92     const Value *P = Worklist.pop_back_val();
93     P = GetUnderlyingObjCPtr(P, DL);
94
95     if (isa<AllocaInst>(P))
96       return true;
97
98     if (!Visited.insert(P).second)
99       continue;
100
101     if (const SelectInst *SI = dyn_cast<const SelectInst>(P)) {
102       Worklist.push_back(SI->getTrueValue());
103       Worklist.push_back(SI->getFalseValue());
104       continue;
105     }
106
107     if (const PHINode *PN = dyn_cast<const PHINode>(P)) {
108       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
109         Worklist.push_back(PN->getIncomingValue(i));
110       continue;
111     }
112   } while (!Worklist.empty());
113
114   return false;
115 }
116
117
118 /// @}
119 ///
120 /// \defgroup ARCOpt ARC Optimization.
121 /// @{
122
123 // TODO: On code like this:
124 //
125 // objc_retain(%x)
126 // stuff_that_cannot_release()
127 // objc_autorelease(%x)
128 // stuff_that_cannot_release()
129 // objc_retain(%x)
130 // stuff_that_cannot_release()
131 // objc_autorelease(%x)
132 //
133 // The second retain and autorelease can be deleted.
134
135 // TODO: It should be possible to delete
136 // objc_autoreleasePoolPush and objc_autoreleasePoolPop
137 // pairs if nothing is actually autoreleased between them. Also, autorelease
138 // calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
139 // after inlining) can be turned into plain release calls.
140
141 // TODO: Critical-edge splitting. If the optimial insertion point is
142 // a critical edge, the current algorithm has to fail, because it doesn't
143 // know how to split edges. It should be possible to make the optimizer
144 // think in terms of edges, rather than blocks, and then split critical
145 // edges on demand.
146
147 // TODO: OptimizeSequences could generalized to be Interprocedural.
148
149 // TODO: Recognize that a bunch of other objc runtime calls have
150 // non-escaping arguments and non-releasing arguments, and may be
151 // non-autoreleasing.
152
153 // TODO: Sink autorelease calls as far as possible. Unfortunately we
154 // usually can't sink them past other calls, which would be the main
155 // case where it would be useful.
156
157 // TODO: The pointer returned from objc_loadWeakRetained is retained.
158
159 // TODO: Delete release+retain pairs (rare).
160
161 STATISTIC(NumNoops,       "Number of no-op objc calls eliminated");
162 STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
163 STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
164 STATISTIC(NumRets,        "Number of return value forwarding "
165                           "retain+autoreleases eliminated");
166 STATISTIC(NumRRs,         "Number of retain+release paths eliminated");
167 STATISTIC(NumPeeps,       "Number of calls peephole-optimized");
168 #ifndef NDEBUG
169 STATISTIC(NumRetainsBeforeOpt,
170           "Number of retains before optimization");
171 STATISTIC(NumReleasesBeforeOpt,
172           "Number of releases before optimization");
173 STATISTIC(NumRetainsAfterOpt,
174           "Number of retains after optimization");
175 STATISTIC(NumReleasesAfterOpt,
176           "Number of releases after optimization");
177 #endif
178
179 namespace {
180   /// \brief Per-BasicBlock state.
181   class BBState {
182     /// The number of unique control paths from the entry which can reach this
183     /// block.
184     unsigned TopDownPathCount;
185
186     /// The number of unique control paths to exits from this block.
187     unsigned BottomUpPathCount;
188
189     /// The top-down traversal uses this to record information known about a
190     /// pointer at the bottom of each block.
191     BlotMapVector<const Value *, TopDownPtrState> PerPtrTopDown;
192
193     /// The bottom-up traversal uses this to record information known about a
194     /// pointer at the top of each block.
195     BlotMapVector<const Value *, BottomUpPtrState> PerPtrBottomUp;
196
197     /// Effective predecessors of the current block ignoring ignorable edges and
198     /// ignored backedges.
199     SmallVector<BasicBlock *, 2> Preds;
200
201     /// Effective successors of the current block ignoring ignorable edges and
202     /// ignored backedges.
203     SmallVector<BasicBlock *, 2> Succs;
204
205   public:
206     static const unsigned OverflowOccurredValue;
207
208     BBState() : TopDownPathCount(0), BottomUpPathCount(0) { }
209
210     typedef decltype(PerPtrTopDown)::iterator top_down_ptr_iterator;
211     typedef decltype(PerPtrTopDown)::const_iterator const_top_down_ptr_iterator;
212
213     top_down_ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
214     top_down_ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
215     const_top_down_ptr_iterator top_down_ptr_begin() const {
216       return PerPtrTopDown.begin();
217     }
218     const_top_down_ptr_iterator top_down_ptr_end() const {
219       return PerPtrTopDown.end();
220     }
221
222     typedef decltype(PerPtrBottomUp)::iterator bottom_up_ptr_iterator;
223     typedef decltype(
224         PerPtrBottomUp)::const_iterator const_bottom_up_ptr_iterator;
225
226     bottom_up_ptr_iterator bottom_up_ptr_begin() {
227       return PerPtrBottomUp.begin();
228     }
229     bottom_up_ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
230     const_bottom_up_ptr_iterator bottom_up_ptr_begin() const {
231       return PerPtrBottomUp.begin();
232     }
233     const_bottom_up_ptr_iterator bottom_up_ptr_end() const {
234       return PerPtrBottomUp.end();
235     }
236
237     /// Mark this block as being an entry block, which has one path from the
238     /// entry by definition.
239     void SetAsEntry() { TopDownPathCount = 1; }
240
241     /// Mark this block as being an exit block, which has one path to an exit by
242     /// definition.
243     void SetAsExit()  { BottomUpPathCount = 1; }
244
245     /// Attempt to find the PtrState object describing the top down state for
246     /// pointer Arg. Return a new initialized PtrState describing the top down
247     /// state for Arg if we do not find one.
248     TopDownPtrState &getPtrTopDownState(const Value *Arg) {
249       return PerPtrTopDown[Arg];
250     }
251
252     /// Attempt to find the PtrState object describing the bottom up state for
253     /// pointer Arg. Return a new initialized PtrState describing the bottom up
254     /// state for Arg if we do not find one.
255     BottomUpPtrState &getPtrBottomUpState(const Value *Arg) {
256       return PerPtrBottomUp[Arg];
257     }
258
259     /// Attempt to find the PtrState object describing the bottom up state for
260     /// pointer Arg.
261     bottom_up_ptr_iterator findPtrBottomUpState(const Value *Arg) {
262       return PerPtrBottomUp.find(Arg);
263     }
264
265     void clearBottomUpPointers() {
266       PerPtrBottomUp.clear();
267     }
268
269     void clearTopDownPointers() {
270       PerPtrTopDown.clear();
271     }
272
273     void InitFromPred(const BBState &Other);
274     void InitFromSucc(const BBState &Other);
275     void MergePred(const BBState &Other);
276     void MergeSucc(const BBState &Other);
277
278     /// Compute the number of possible unique paths from an entry to an exit
279     /// which pass through this block. This is only valid after both the
280     /// top-down and bottom-up traversals are complete.
281     ///
282     /// Returns true if overflow occurred. Returns false if overflow did not
283     /// occur.
284     bool GetAllPathCountWithOverflow(unsigned &PathCount) const {
285       if (TopDownPathCount == OverflowOccurredValue ||
286           BottomUpPathCount == OverflowOccurredValue)
287         return true;
288       unsigned long long Product =
289         (unsigned long long)TopDownPathCount*BottomUpPathCount;
290       // Overflow occurred if any of the upper bits of Product are set or if all
291       // the lower bits of Product are all set.
292       return (Product >> 32) ||
293              ((PathCount = Product) == OverflowOccurredValue);
294     }
295
296     // Specialized CFG utilities.
297     typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
298     edge_iterator pred_begin() const { return Preds.begin(); }
299     edge_iterator pred_end() const { return Preds.end(); }
300     edge_iterator succ_begin() const { return Succs.begin(); }
301     edge_iterator succ_end() const { return Succs.end(); }
302
303     void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
304     void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
305
306     bool isExit() const { return Succs.empty(); }
307   };
308
309   const unsigned BBState::OverflowOccurredValue = 0xffffffff;
310 }
311
312 void BBState::InitFromPred(const BBState &Other) {
313   PerPtrTopDown = Other.PerPtrTopDown;
314   TopDownPathCount = Other.TopDownPathCount;
315 }
316
317 void BBState::InitFromSucc(const BBState &Other) {
318   PerPtrBottomUp = Other.PerPtrBottomUp;
319   BottomUpPathCount = Other.BottomUpPathCount;
320 }
321
322 /// The top-down traversal uses this to merge information about predecessors to
323 /// form the initial state for a new block.
324 void BBState::MergePred(const BBState &Other) {
325   if (TopDownPathCount == OverflowOccurredValue)
326     return;
327
328   // Other.TopDownPathCount can be 0, in which case it is either dead or a
329   // loop backedge. Loop backedges are special.
330   TopDownPathCount += Other.TopDownPathCount;
331
332   // In order to be consistent, we clear the top down pointers when by adding
333   // TopDownPathCount becomes OverflowOccurredValue even though "true" overflow
334   // has not occurred.
335   if (TopDownPathCount == OverflowOccurredValue) {
336     clearTopDownPointers();
337     return;
338   }
339
340   // Check for overflow. If we have overflow, fall back to conservative
341   // behavior.
342   if (TopDownPathCount < Other.TopDownPathCount) {
343     TopDownPathCount = OverflowOccurredValue;
344     clearTopDownPointers();
345     return;
346   }
347
348   // For each entry in the other set, if our set has an entry with the same key,
349   // merge the entries. Otherwise, copy the entry and merge it with an empty
350   // entry.
351   for (auto MI = Other.top_down_ptr_begin(), ME = Other.top_down_ptr_end();
352        MI != ME; ++MI) {
353     auto Pair = PerPtrTopDown.insert(*MI);
354     Pair.first->second.Merge(Pair.second ? TopDownPtrState() : MI->second,
355                              /*TopDown=*/true);
356   }
357
358   // For each entry in our set, if the other set doesn't have an entry with the
359   // same key, force it to merge with an empty entry.
360   for (auto MI = top_down_ptr_begin(), ME = top_down_ptr_end(); MI != ME; ++MI)
361     if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
362       MI->second.Merge(TopDownPtrState(), /*TopDown=*/true);
363 }
364
365 /// The bottom-up traversal uses this to merge information about successors to
366 /// form the initial state for a new block.
367 void BBState::MergeSucc(const BBState &Other) {
368   if (BottomUpPathCount == OverflowOccurredValue)
369     return;
370
371   // Other.BottomUpPathCount can be 0, in which case it is either dead or a
372   // loop backedge. Loop backedges are special.
373   BottomUpPathCount += Other.BottomUpPathCount;
374
375   // In order to be consistent, we clear the top down pointers when by adding
376   // BottomUpPathCount becomes OverflowOccurredValue even though "true" overflow
377   // has not occurred.
378   if (BottomUpPathCount == OverflowOccurredValue) {
379     clearBottomUpPointers();
380     return;
381   }
382
383   // Check for overflow. If we have overflow, fall back to conservative
384   // behavior.
385   if (BottomUpPathCount < Other.BottomUpPathCount) {
386     BottomUpPathCount = OverflowOccurredValue;
387     clearBottomUpPointers();
388     return;
389   }
390
391   // For each entry in the other set, if our set has an entry with the
392   // same key, merge the entries. Otherwise, copy the entry and merge
393   // it with an empty entry.
394   for (auto MI = Other.bottom_up_ptr_begin(), ME = Other.bottom_up_ptr_end();
395        MI != ME; ++MI) {
396     auto Pair = PerPtrBottomUp.insert(*MI);
397     Pair.first->second.Merge(Pair.second ? BottomUpPtrState() : MI->second,
398                              /*TopDown=*/false);
399   }
400
401   // For each entry in our set, if the other set doesn't have an entry
402   // with the same key, force it to merge with an empty entry.
403   for (auto MI = bottom_up_ptr_begin(), ME = bottom_up_ptr_end(); MI != ME;
404        ++MI)
405     if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
406       MI->second.Merge(BottomUpPtrState(), /*TopDown=*/false);
407 }
408
409 namespace {
410
411   /// \brief The main ARC optimization pass.
412   class ObjCARCOpt : public FunctionPass {
413     bool Changed;
414     ProvenanceAnalysis PA;
415
416     /// A cache of references to runtime entry point constants.
417     ARCRuntimeEntryPoints EP;
418
419     /// A cache of MDKinds that can be passed into other functions to propagate
420     /// MDKind identifiers.
421     ARCMDKindCache MDKindCache;
422
423     // This is used to track if a pointer is stored into an alloca.
424     DenseSet<const Value *> MultiOwnersSet;
425
426     /// A flag indicating whether this optimization pass should run.
427     bool Run;
428
429     /// Flags which determine whether each of the interesting runtine functions
430     /// is in fact used in the current function.
431     unsigned UsedInThisFunction;
432
433     bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
434     void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
435                                    ARCInstKind &Class);
436     void OptimizeIndividualCalls(Function &F);
437
438     void CheckForCFGHazards(const BasicBlock *BB,
439                             DenseMap<const BasicBlock *, BBState> &BBStates,
440                             BBState &MyStates) const;
441     bool VisitInstructionBottomUp(Instruction *Inst, BasicBlock *BB,
442                                   BlotMapVector<Value *, RRInfo> &Retains,
443                                   BBState &MyStates);
444     bool VisitBottomUp(BasicBlock *BB,
445                        DenseMap<const BasicBlock *, BBState> &BBStates,
446                        BlotMapVector<Value *, RRInfo> &Retains);
447     bool VisitInstructionTopDown(Instruction *Inst,
448                                  DenseMap<Value *, RRInfo> &Releases,
449                                  BBState &MyStates);
450     bool VisitTopDown(BasicBlock *BB,
451                       DenseMap<const BasicBlock *, BBState> &BBStates,
452                       DenseMap<Value *, RRInfo> &Releases);
453     bool Visit(Function &F, DenseMap<const BasicBlock *, BBState> &BBStates,
454                BlotMapVector<Value *, RRInfo> &Retains,
455                DenseMap<Value *, RRInfo> &Releases);
456
457     void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
458                    BlotMapVector<Value *, RRInfo> &Retains,
459                    DenseMap<Value *, RRInfo> &Releases,
460                    SmallVectorImpl<Instruction *> &DeadInsts, Module *M);
461
462     bool ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState> &BBStates,
463                                BlotMapVector<Value *, RRInfo> &Retains,
464                                DenseMap<Value *, RRInfo> &Releases, Module *M,
465                                SmallVectorImpl<Instruction *> &NewRetains,
466                                SmallVectorImpl<Instruction *> &NewReleases,
467                                SmallVectorImpl<Instruction *> &DeadInsts,
468                                RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
469                                Value *Arg, bool KnownSafe,
470                                bool &AnyPairsCompletelyEliminated);
471
472     bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
473                               BlotMapVector<Value *, RRInfo> &Retains,
474                               DenseMap<Value *, RRInfo> &Releases, Module *M);
475
476     void OptimizeWeakCalls(Function &F);
477
478     bool OptimizeSequences(Function &F);
479
480     void OptimizeReturns(Function &F);
481
482 #ifndef NDEBUG
483     void GatherStatistics(Function &F, bool AfterOptimization = false);
484 #endif
485
486     void getAnalysisUsage(AnalysisUsage &AU) const override;
487     bool doInitialization(Module &M) override;
488     bool runOnFunction(Function &F) override;
489     void releaseMemory() override;
490
491   public:
492     static char ID;
493     ObjCARCOpt() : FunctionPass(ID) {
494       initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
495     }
496   };
497 }
498
499 char ObjCARCOpt::ID = 0;
500 INITIALIZE_PASS_BEGIN(ObjCARCOpt,
501                       "objc-arc", "ObjC ARC optimization", false, false)
502 INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
503 INITIALIZE_PASS_END(ObjCARCOpt,
504                     "objc-arc", "ObjC ARC optimization", false, false)
505
506 Pass *llvm::createObjCARCOptPass() {
507   return new ObjCARCOpt();
508 }
509
510 void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
511   AU.addRequired<ObjCARCAliasAnalysis>();
512   AU.addRequired<AliasAnalysis>();
513   // ARC optimization doesn't currently split critical edges.
514   AU.setPreservesCFG();
515 }
516
517 /// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is
518 /// not a return value.  Or, if it can be paired with an
519 /// objc_autoreleaseReturnValue, delete the pair and return true.
520 bool
521 ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
522   // Check for the argument being from an immediately preceding call or invoke.
523   const Value *Arg = GetArgRCIdentityRoot(RetainRV);
524   ImmutableCallSite CS(Arg);
525   if (const Instruction *Call = CS.getInstruction()) {
526     if (Call->getParent() == RetainRV->getParent()) {
527       BasicBlock::const_iterator I = Call;
528       ++I;
529       while (IsNoopInstruction(I)) ++I;
530       if (&*I == RetainRV)
531         return false;
532     } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
533       BasicBlock *RetainRVParent = RetainRV->getParent();
534       if (II->getNormalDest() == RetainRVParent) {
535         BasicBlock::const_iterator I = RetainRVParent->begin();
536         while (IsNoopInstruction(I)) ++I;
537         if (&*I == RetainRV)
538           return false;
539       }
540     }
541   }
542
543   // Check for being preceded by an objc_autoreleaseReturnValue on the same
544   // pointer. In this case, we can delete the pair.
545   BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
546   if (I != Begin) {
547     do --I; while (I != Begin && IsNoopInstruction(I));
548     if (GetBasicARCInstKind(I) == ARCInstKind::AutoreleaseRV &&
549         GetArgRCIdentityRoot(I) == Arg) {
550       Changed = true;
551       ++NumPeeps;
552
553       DEBUG(dbgs() << "Erasing autoreleaseRV,retainRV pair: " << *I << "\n"
554                    << "Erasing " << *RetainRV << "\n");
555
556       EraseInstruction(I);
557       EraseInstruction(RetainRV);
558       return true;
559     }
560   }
561
562   // Turn it to a plain objc_retain.
563   Changed = true;
564   ++NumPeeps;
565
566   DEBUG(dbgs() << "Transforming objc_retainAutoreleasedReturnValue => "
567                   "objc_retain since the operand is not a return value.\n"
568                   "Old = " << *RetainRV << "\n");
569
570   Constant *NewDecl = EP.get(ARCRuntimeEntryPointKind::Retain);
571   cast<CallInst>(RetainRV)->setCalledFunction(NewDecl);
572
573   DEBUG(dbgs() << "New = " << *RetainRV << "\n");
574
575   return false;
576 }
577
578 /// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not
579 /// used as a return value.
580 void ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F,
581                                            Instruction *AutoreleaseRV,
582                                            ARCInstKind &Class) {
583   // Check for a return of the pointer value.
584   const Value *Ptr = GetArgRCIdentityRoot(AutoreleaseRV);
585   SmallVector<const Value *, 2> Users;
586   Users.push_back(Ptr);
587   do {
588     Ptr = Users.pop_back_val();
589     for (const User *U : Ptr->users()) {
590       if (isa<ReturnInst>(U) || GetBasicARCInstKind(U) == ARCInstKind::RetainRV)
591         return;
592       if (isa<BitCastInst>(U))
593         Users.push_back(U);
594     }
595   } while (!Users.empty());
596
597   Changed = true;
598   ++NumPeeps;
599
600   DEBUG(dbgs() << "Transforming objc_autoreleaseReturnValue => "
601                   "objc_autorelease since its operand is not used as a return "
602                   "value.\n"
603                   "Old = " << *AutoreleaseRV << "\n");
604
605   CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
606   Constant *NewDecl = EP.get(ARCRuntimeEntryPointKind::Autorelease);
607   AutoreleaseRVCI->setCalledFunction(NewDecl);
608   AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
609   Class = ARCInstKind::Autorelease;
610
611   DEBUG(dbgs() << "New: " << *AutoreleaseRV << "\n");
612
613 }
614
615 /// Visit each call, one at a time, and make simplifications without doing any
616 /// additional analysis.
617 void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
618   DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeIndividualCalls ==\n");
619   // Reset all the flags in preparation for recomputing them.
620   UsedInThisFunction = 0;
621
622   // Visit all objc_* calls in F.
623   for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
624     Instruction *Inst = &*I++;
625
626     ARCInstKind Class = GetBasicARCInstKind(Inst);
627
628     DEBUG(dbgs() << "Visiting: Class: " << Class << "; " << *Inst << "\n");
629
630     switch (Class) {
631     default: break;
632
633     // Delete no-op casts. These function calls have special semantics, but
634     // the semantics are entirely implemented via lowering in the front-end,
635     // so by the time they reach the optimizer, they are just no-op calls
636     // which return their argument.
637     //
638     // There are gray areas here, as the ability to cast reference-counted
639     // pointers to raw void* and back allows code to break ARC assumptions,
640     // however these are currently considered to be unimportant.
641     case ARCInstKind::NoopCast:
642       Changed = true;
643       ++NumNoops;
644       DEBUG(dbgs() << "Erasing no-op cast: " << *Inst << "\n");
645       EraseInstruction(Inst);
646       continue;
647
648     // If the pointer-to-weak-pointer is null, it's undefined behavior.
649     case ARCInstKind::StoreWeak:
650     case ARCInstKind::LoadWeak:
651     case ARCInstKind::LoadWeakRetained:
652     case ARCInstKind::InitWeak:
653     case ARCInstKind::DestroyWeak: {
654       CallInst *CI = cast<CallInst>(Inst);
655       if (IsNullOrUndef(CI->getArgOperand(0))) {
656         Changed = true;
657         Type *Ty = CI->getArgOperand(0)->getType();
658         new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
659                       Constant::getNullValue(Ty),
660                       CI);
661         llvm::Value *NewValue = UndefValue::get(CI->getType());
662         DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
663                        "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
664         CI->replaceAllUsesWith(NewValue);
665         CI->eraseFromParent();
666         continue;
667       }
668       break;
669     }
670     case ARCInstKind::CopyWeak:
671     case ARCInstKind::MoveWeak: {
672       CallInst *CI = cast<CallInst>(Inst);
673       if (IsNullOrUndef(CI->getArgOperand(0)) ||
674           IsNullOrUndef(CI->getArgOperand(1))) {
675         Changed = true;
676         Type *Ty = CI->getArgOperand(0)->getType();
677         new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
678                       Constant::getNullValue(Ty),
679                       CI);
680
681         llvm::Value *NewValue = UndefValue::get(CI->getType());
682         DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
683                         "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
684
685         CI->replaceAllUsesWith(NewValue);
686         CI->eraseFromParent();
687         continue;
688       }
689       break;
690     }
691     case ARCInstKind::RetainRV:
692       if (OptimizeRetainRVCall(F, Inst))
693         continue;
694       break;
695     case ARCInstKind::AutoreleaseRV:
696       OptimizeAutoreleaseRVCall(F, Inst, Class);
697       break;
698     }
699
700     // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
701     if (IsAutorelease(Class) && Inst->use_empty()) {
702       CallInst *Call = cast<CallInst>(Inst);
703       const Value *Arg = Call->getArgOperand(0);
704       Arg = FindSingleUseIdentifiedObject(Arg);
705       if (Arg) {
706         Changed = true;
707         ++NumAutoreleases;
708
709         // Create the declaration lazily.
710         LLVMContext &C = Inst->getContext();
711
712         Constant *Decl = EP.get(ARCRuntimeEntryPointKind::Release);
713         CallInst *NewCall = CallInst::Create(Decl, Call->getArgOperand(0), "",
714                                              Call);
715         NewCall->setMetadata(MDKindCache.get(ARCMDKindID::ImpreciseRelease),
716                              MDNode::get(C, None));
717
718         DEBUG(dbgs() << "Replacing autorelease{,RV}(x) with objc_release(x) "
719               "since x is otherwise unused.\nOld: " << *Call << "\nNew: "
720               << *NewCall << "\n");
721
722         EraseInstruction(Call);
723         Inst = NewCall;
724         Class = ARCInstKind::Release;
725       }
726     }
727
728     // For functions which can never be passed stack arguments, add
729     // a tail keyword.
730     if (IsAlwaysTail(Class)) {
731       Changed = true;
732       DEBUG(dbgs() << "Adding tail keyword to function since it can never be "
733                       "passed stack args: " << *Inst << "\n");
734       cast<CallInst>(Inst)->setTailCall();
735     }
736
737     // Ensure that functions that can never have a "tail" keyword due to the
738     // semantics of ARC truly do not do so.
739     if (IsNeverTail(Class)) {
740       Changed = true;
741       DEBUG(dbgs() << "Removing tail keyword from function: " << *Inst <<
742             "\n");
743       cast<CallInst>(Inst)->setTailCall(false);
744     }
745
746     // Set nounwind as needed.
747     if (IsNoThrow(Class)) {
748       Changed = true;
749       DEBUG(dbgs() << "Found no throw class. Setting nounwind on: " << *Inst
750                    << "\n");
751       cast<CallInst>(Inst)->setDoesNotThrow();
752     }
753
754     if (!IsNoopOnNull(Class)) {
755       UsedInThisFunction |= 1 << unsigned(Class);
756       continue;
757     }
758
759     const Value *Arg = GetArgRCIdentityRoot(Inst);
760
761     // ARC calls with null are no-ops. Delete them.
762     if (IsNullOrUndef(Arg)) {
763       Changed = true;
764       ++NumNoops;
765       DEBUG(dbgs() << "ARC calls with  null are no-ops. Erasing: " << *Inst
766             << "\n");
767       EraseInstruction(Inst);
768       continue;
769     }
770
771     // Keep track of which of retain, release, autorelease, and retain_block
772     // are actually present in this function.
773     UsedInThisFunction |= 1 << unsigned(Class);
774
775     // If Arg is a PHI, and one or more incoming values to the
776     // PHI are null, and the call is control-equivalent to the PHI, and there
777     // are no relevant side effects between the PHI and the call, the call
778     // could be pushed up to just those paths with non-null incoming values.
779     // For now, don't bother splitting critical edges for this.
780     SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
781     Worklist.push_back(std::make_pair(Inst, Arg));
782     do {
783       std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
784       Inst = Pair.first;
785       Arg = Pair.second;
786
787       const PHINode *PN = dyn_cast<PHINode>(Arg);
788       if (!PN) continue;
789
790       // Determine if the PHI has any null operands, or any incoming
791       // critical edges.
792       bool HasNull = false;
793       bool HasCriticalEdges = false;
794       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
795         Value *Incoming =
796           GetRCIdentityRoot(PN->getIncomingValue(i));
797         if (IsNullOrUndef(Incoming))
798           HasNull = true;
799         else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
800                    .getNumSuccessors() != 1) {
801           HasCriticalEdges = true;
802           break;
803         }
804       }
805       // If we have null operands and no critical edges, optimize.
806       if (!HasCriticalEdges && HasNull) {
807         SmallPtrSet<Instruction *, 4> DependingInstructions;
808         SmallPtrSet<const BasicBlock *, 4> Visited;
809
810         // Check that there is nothing that cares about the reference
811         // count between the call and the phi.
812         switch (Class) {
813         case ARCInstKind::Retain:
814         case ARCInstKind::RetainBlock:
815           // These can always be moved up.
816           break;
817         case ARCInstKind::Release:
818           // These can't be moved across things that care about the retain
819           // count.
820           FindDependencies(NeedsPositiveRetainCount, Arg,
821                            Inst->getParent(), Inst,
822                            DependingInstructions, Visited, PA);
823           break;
824         case ARCInstKind::Autorelease:
825           // These can't be moved across autorelease pool scope boundaries.
826           FindDependencies(AutoreleasePoolBoundary, Arg,
827                            Inst->getParent(), Inst,
828                            DependingInstructions, Visited, PA);
829           break;
830         case ARCInstKind::RetainRV:
831         case ARCInstKind::AutoreleaseRV:
832           // Don't move these; the RV optimization depends on the autoreleaseRV
833           // being tail called, and the retainRV being immediately after a call
834           // (which might still happen if we get lucky with codegen layout, but
835           // it's not worth taking the chance).
836           continue;
837         default:
838           llvm_unreachable("Invalid dependence flavor");
839         }
840
841         if (DependingInstructions.size() == 1 &&
842             *DependingInstructions.begin() == PN) {
843           Changed = true;
844           ++NumPartialNoops;
845           // Clone the call into each predecessor that has a non-null value.
846           CallInst *CInst = cast<CallInst>(Inst);
847           Type *ParamTy = CInst->getArgOperand(0)->getType();
848           for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
849             Value *Incoming =
850               GetRCIdentityRoot(PN->getIncomingValue(i));
851             if (!IsNullOrUndef(Incoming)) {
852               CallInst *Clone = cast<CallInst>(CInst->clone());
853               Value *Op = PN->getIncomingValue(i);
854               Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
855               if (Op->getType() != ParamTy)
856                 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
857               Clone->setArgOperand(0, Op);
858               Clone->insertBefore(InsertPos);
859
860               DEBUG(dbgs() << "Cloning "
861                            << *CInst << "\n"
862                            "And inserting clone at " << *InsertPos << "\n");
863               Worklist.push_back(std::make_pair(Clone, Incoming));
864             }
865           }
866           // Erase the original call.
867           DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
868           EraseInstruction(CInst);
869           continue;
870         }
871       }
872     } while (!Worklist.empty());
873   }
874 }
875
876 /// If we have a top down pointer in the S_Use state, make sure that there are
877 /// no CFG hazards by checking the states of various bottom up pointers.
878 static void CheckForUseCFGHazard(const Sequence SuccSSeq,
879                                  const bool SuccSRRIKnownSafe,
880                                  TopDownPtrState &S,
881                                  bool &SomeSuccHasSame,
882                                  bool &AllSuccsHaveSame,
883                                  bool &NotAllSeqEqualButKnownSafe,
884                                  bool &ShouldContinue) {
885   switch (SuccSSeq) {
886   case S_CanRelease: {
887     if (!S.IsKnownSafe() && !SuccSRRIKnownSafe) {
888       S.ClearSequenceProgress();
889       break;
890     }
891     S.SetCFGHazardAfflicted(true);
892     ShouldContinue = true;
893     break;
894   }
895   case S_Use:
896     SomeSuccHasSame = true;
897     break;
898   case S_Stop:
899   case S_Release:
900   case S_MovableRelease:
901     if (!S.IsKnownSafe() && !SuccSRRIKnownSafe)
902       AllSuccsHaveSame = false;
903     else
904       NotAllSeqEqualButKnownSafe = true;
905     break;
906   case S_Retain:
907     llvm_unreachable("bottom-up pointer in retain state!");
908   case S_None:
909     llvm_unreachable("This should have been handled earlier.");
910   }
911 }
912
913 /// If we have a Top Down pointer in the S_CanRelease state, make sure that
914 /// there are no CFG hazards by checking the states of various bottom up
915 /// pointers.
916 static void CheckForCanReleaseCFGHazard(const Sequence SuccSSeq,
917                                         const bool SuccSRRIKnownSafe,
918                                         TopDownPtrState &S,
919                                         bool &SomeSuccHasSame,
920                                         bool &AllSuccsHaveSame,
921                                         bool &NotAllSeqEqualButKnownSafe) {
922   switch (SuccSSeq) {
923   case S_CanRelease:
924     SomeSuccHasSame = true;
925     break;
926   case S_Stop:
927   case S_Release:
928   case S_MovableRelease:
929   case S_Use:
930     if (!S.IsKnownSafe() && !SuccSRRIKnownSafe)
931       AllSuccsHaveSame = false;
932     else
933       NotAllSeqEqualButKnownSafe = true;
934     break;
935   case S_Retain:
936     llvm_unreachable("bottom-up pointer in retain state!");
937   case S_None:
938     llvm_unreachable("This should have been handled earlier.");
939   }
940 }
941
942 /// Check for critical edges, loop boundaries, irreducible control flow, or
943 /// other CFG structures where moving code across the edge would result in it
944 /// being executed more.
945 void
946 ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
947                                DenseMap<const BasicBlock *, BBState> &BBStates,
948                                BBState &MyStates) const {
949   // If any top-down local-use or possible-dec has a succ which is earlier in
950   // the sequence, forget it.
951   for (auto I = MyStates.top_down_ptr_begin(), E = MyStates.top_down_ptr_end();
952        I != E; ++I) {
953     TopDownPtrState &S = I->second;
954     const Sequence Seq = I->second.GetSeq();
955
956     // We only care about S_Retain, S_CanRelease, and S_Use.
957     if (Seq == S_None)
958       continue;
959
960     // Make sure that if extra top down states are added in the future that this
961     // code is updated to handle it.
962     assert((Seq == S_Retain || Seq == S_CanRelease || Seq == S_Use) &&
963            "Unknown top down sequence state.");
964
965     const Value *Arg = I->first;
966     const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
967     bool SomeSuccHasSame = false;
968     bool AllSuccsHaveSame = true;
969     bool NotAllSeqEqualButKnownSafe = false;
970
971     succ_const_iterator SI(TI), SE(TI, false);
972
973     for (; SI != SE; ++SI) {
974       // If VisitBottomUp has pointer information for this successor, take
975       // what we know about it.
976       const DenseMap<const BasicBlock *, BBState>::iterator BBI =
977         BBStates.find(*SI);
978       assert(BBI != BBStates.end());
979       const BottomUpPtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
980       const Sequence SuccSSeq = SuccS.GetSeq();
981
982       // If bottom up, the pointer is in an S_None state, clear the sequence
983       // progress since the sequence in the bottom up state finished
984       // suggesting a mismatch in between retains/releases. This is true for
985       // all three cases that we are handling here: S_Retain, S_Use, and
986       // S_CanRelease.
987       if (SuccSSeq == S_None) {
988         S.ClearSequenceProgress();
989         continue;
990       }
991
992       // If we have S_Use or S_CanRelease, perform our check for cfg hazard
993       // checks.
994       const bool SuccSRRIKnownSafe = SuccS.IsKnownSafe();
995
996       // *NOTE* We do not use Seq from above here since we are allowing for
997       // S.GetSeq() to change while we are visiting basic blocks.
998       switch(S.GetSeq()) {
999       case S_Use: {
1000         bool ShouldContinue = false;
1001         CheckForUseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S, SomeSuccHasSame,
1002                              AllSuccsHaveSame, NotAllSeqEqualButKnownSafe,
1003                              ShouldContinue);
1004         if (ShouldContinue)
1005           continue;
1006         break;
1007       }
1008       case S_CanRelease: {
1009         CheckForCanReleaseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S,
1010                                     SomeSuccHasSame, AllSuccsHaveSame,
1011                                     NotAllSeqEqualButKnownSafe);
1012         break;
1013       }
1014       case S_Retain:
1015       case S_None:
1016       case S_Stop:
1017       case S_Release:
1018       case S_MovableRelease:
1019         break;
1020       }
1021     }
1022
1023     // If the state at the other end of any of the successor edges
1024     // matches the current state, require all edges to match. This
1025     // guards against loops in the middle of a sequence.
1026     if (SomeSuccHasSame && !AllSuccsHaveSame) {
1027       S.ClearSequenceProgress();
1028     } else if (NotAllSeqEqualButKnownSafe) {
1029       // If we would have cleared the state foregoing the fact that we are known
1030       // safe, stop code motion. This is because whether or not it is safe to
1031       // remove RR pairs via KnownSafe is an orthogonal concept to whether we
1032       // are allowed to perform code motion.
1033       S.SetCFGHazardAfflicted(true);
1034     }
1035   }
1036 }
1037
1038 bool ObjCARCOpt::VisitInstructionBottomUp(
1039     Instruction *Inst, BasicBlock *BB, BlotMapVector<Value *, RRInfo> &Retains,
1040     BBState &MyStates) {
1041   bool NestingDetected = false;
1042   ARCInstKind Class = GetARCInstKind(Inst);
1043   const Value *Arg = nullptr;
1044
1045   DEBUG(dbgs() << "Class: " << Class << "\n");
1046
1047   switch (Class) {
1048   case ARCInstKind::Release: {
1049     Arg = GetArgRCIdentityRoot(Inst);
1050
1051     BottomUpPtrState &S = MyStates.getPtrBottomUpState(Arg);
1052     NestingDetected |= S.InitBottomUp(MDKindCache, Inst);
1053     break;
1054   }
1055   case ARCInstKind::RetainBlock:
1056     // In OptimizeIndividualCalls, we have strength reduced all optimizable
1057     // objc_retainBlocks to objc_retains. Thus at this point any
1058     // objc_retainBlocks that we see are not optimizable.
1059     break;
1060   case ARCInstKind::Retain:
1061   case ARCInstKind::RetainRV: {
1062     Arg = GetArgRCIdentityRoot(Inst);
1063     BottomUpPtrState &S = MyStates.getPtrBottomUpState(Arg);
1064     if (S.MatchWithRetain()) {
1065       // Don't do retain+release tracking for ARCInstKind::RetainRV, because
1066       // it's better to let it remain as the first instruction after a call.
1067       if (Class != ARCInstKind::RetainRV)
1068         Retains[Inst] = S.GetRRInfo();
1069       S.ClearSequenceProgress();
1070     }
1071     // A retain moving bottom up can be a use.
1072     break;
1073   }
1074   case ARCInstKind::AutoreleasepoolPop:
1075     // Conservatively, clear MyStates for all known pointers.
1076     MyStates.clearBottomUpPointers();
1077     return NestingDetected;
1078   case ARCInstKind::AutoreleasepoolPush:
1079   case ARCInstKind::None:
1080     // These are irrelevant.
1081     return NestingDetected;
1082   case ARCInstKind::User:
1083     // If we have a store into an alloca of a pointer we are tracking, the
1084     // pointer has multiple owners implying that we must be more conservative.
1085     //
1086     // This comes up in the context of a pointer being ``KnownSafe''. In the
1087     // presence of a block being initialized, the frontend will emit the
1088     // objc_retain on the original pointer and the release on the pointer loaded
1089     // from the alloca. The optimizer will through the provenance analysis
1090     // realize that the two are related, but since we only require KnownSafe in
1091     // one direction, will match the inner retain on the original pointer with
1092     // the guard release on the original pointer. This is fixed by ensuring that
1093     // in the presence of allocas we only unconditionally remove pointers if
1094     // both our retain and our release are KnownSafe.
1095     if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1096       const DataLayout &DL = BB->getModule()->getDataLayout();
1097       if (AreAnyUnderlyingObjectsAnAlloca(SI->getPointerOperand(), DL)) {
1098         auto I = MyStates.findPtrBottomUpState(
1099             GetRCIdentityRoot(SI->getValueOperand()));
1100         if (I != MyStates.bottom_up_ptr_end())
1101           MultiOwnersSet.insert(I->first);
1102       }
1103     }
1104     break;
1105   default:
1106     break;
1107   }
1108
1109   // Consider any other possible effects of this instruction on each
1110   // pointer being tracked.
1111   for (auto MI = MyStates.bottom_up_ptr_begin(),
1112             ME = MyStates.bottom_up_ptr_end();
1113        MI != ME; ++MI) {
1114     const Value *Ptr = MI->first;
1115     if (Ptr == Arg)
1116       continue; // Handled above.
1117     BottomUpPtrState &S = MI->second;
1118
1119     if (S.HandlePotentialAlterRefCount(Inst, Ptr, PA, Class))
1120       continue;
1121
1122     S.HandlePotentialUse(BB, Inst, Ptr, PA, Class);
1123   }
1124
1125   return NestingDetected;
1126 }
1127
1128 bool ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
1129                                DenseMap<const BasicBlock *, BBState> &BBStates,
1130                                BlotMapVector<Value *, RRInfo> &Retains) {
1131
1132   DEBUG(dbgs() << "\n== ObjCARCOpt::VisitBottomUp ==\n");
1133
1134   bool NestingDetected = false;
1135   BBState &MyStates = BBStates[BB];
1136
1137   // Merge the states from each successor to compute the initial state
1138   // for the current block.
1139   BBState::edge_iterator SI(MyStates.succ_begin()),
1140                          SE(MyStates.succ_end());
1141   if (SI != SE) {
1142     const BasicBlock *Succ = *SI;
1143     DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
1144     assert(I != BBStates.end());
1145     MyStates.InitFromSucc(I->second);
1146     ++SI;
1147     for (; SI != SE; ++SI) {
1148       Succ = *SI;
1149       I = BBStates.find(Succ);
1150       assert(I != BBStates.end());
1151       MyStates.MergeSucc(I->second);
1152     }
1153   }
1154
1155   // Visit all the instructions, bottom-up.
1156   for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
1157     Instruction *Inst = std::prev(I);
1158
1159     // Invoke instructions are visited as part of their successors (below).
1160     if (isa<InvokeInst>(Inst))
1161       continue;
1162
1163     DEBUG(dbgs() << "Visiting " << *Inst << "\n");
1164
1165     NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
1166   }
1167
1168   // If there's a predecessor with an invoke, visit the invoke as if it were
1169   // part of this block, since we can't insert code after an invoke in its own
1170   // block, and we don't want to split critical edges.
1171   for (BBState::edge_iterator PI(MyStates.pred_begin()),
1172        PE(MyStates.pred_end()); PI != PE; ++PI) {
1173     BasicBlock *Pred = *PI;
1174     if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
1175       NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
1176   }
1177
1178   return NestingDetected;
1179 }
1180
1181 bool
1182 ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
1183                                     DenseMap<Value *, RRInfo> &Releases,
1184                                     BBState &MyStates) {
1185   bool NestingDetected = false;
1186   ARCInstKind Class = GetARCInstKind(Inst);
1187   const Value *Arg = nullptr;
1188
1189   switch (Class) {
1190   case ARCInstKind::RetainBlock:
1191     // In OptimizeIndividualCalls, we have strength reduced all optimizable
1192     // objc_retainBlocks to objc_retains. Thus at this point any
1193     // objc_retainBlocks that we see are not optimizable. We need to break since
1194     // a retain can be a potential use.
1195     break;
1196   case ARCInstKind::Retain:
1197   case ARCInstKind::RetainRV: {
1198     Arg = GetArgRCIdentityRoot(Inst);
1199     TopDownPtrState &S = MyStates.getPtrTopDownState(Arg);
1200     NestingDetected |= S.InitTopDown(Class, Inst);
1201     // A retain can be a potential use; procede to the generic checking
1202     // code below.
1203     break;
1204   }
1205   case ARCInstKind::Release: {
1206     Arg = GetArgRCIdentityRoot(Inst);
1207     TopDownPtrState &S = MyStates.getPtrTopDownState(Arg);
1208     // Try to form a tentative pair in between this release instruction and the
1209     // top down pointers that we are tracking.
1210     if (S.MatchWithRelease(MDKindCache, Inst)) {
1211       // If we succeed, copy S's RRInfo into the Release -> {Retain Set
1212       // Map}. Then we clear S.
1213       Releases[Inst] = S.GetRRInfo();
1214       S.ClearSequenceProgress();
1215     }
1216     break;
1217   }
1218   case ARCInstKind::AutoreleasepoolPop:
1219     // Conservatively, clear MyStates for all known pointers.
1220     MyStates.clearTopDownPointers();
1221     return false;
1222   case ARCInstKind::AutoreleasepoolPush:
1223   case ARCInstKind::None:
1224     // These can not be uses of
1225     return false;
1226   default:
1227     break;
1228   }
1229
1230   // Consider any other possible effects of this instruction on each
1231   // pointer being tracked.
1232   for (auto MI = MyStates.top_down_ptr_begin(),
1233             ME = MyStates.top_down_ptr_end();
1234        MI != ME; ++MI) {
1235     const Value *Ptr = MI->first;
1236     if (Ptr == Arg)
1237       continue; // Handled above.
1238     TopDownPtrState &S = MI->second;
1239     if (S.HandlePotentialAlterRefCount(Inst, Ptr, PA, Class))
1240       continue;
1241
1242     S.HandlePotentialUse(Inst, Ptr, PA, Class);
1243   }
1244
1245   return NestingDetected;
1246 }
1247
1248 bool
1249 ObjCARCOpt::VisitTopDown(BasicBlock *BB,
1250                          DenseMap<const BasicBlock *, BBState> &BBStates,
1251                          DenseMap<Value *, RRInfo> &Releases) {
1252   DEBUG(dbgs() << "\n== ObjCARCOpt::VisitTopDown ==\n");
1253   bool NestingDetected = false;
1254   BBState &MyStates = BBStates[BB];
1255
1256   // Merge the states from each predecessor to compute the initial state
1257   // for the current block.
1258   BBState::edge_iterator PI(MyStates.pred_begin()),
1259                          PE(MyStates.pred_end());
1260   if (PI != PE) {
1261     const BasicBlock *Pred = *PI;
1262     DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
1263     assert(I != BBStates.end());
1264     MyStates.InitFromPred(I->second);
1265     ++PI;
1266     for (; PI != PE; ++PI) {
1267       Pred = *PI;
1268       I = BBStates.find(Pred);
1269       assert(I != BBStates.end());
1270       MyStates.MergePred(I->second);
1271     }
1272   }
1273
1274   // Visit all the instructions, top-down.
1275   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1276     Instruction *Inst = I;
1277
1278     DEBUG(dbgs() << "Visiting " << *Inst << "\n");
1279
1280     NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
1281   }
1282
1283   CheckForCFGHazards(BB, BBStates, MyStates);
1284   return NestingDetected;
1285 }
1286
1287 static void
1288 ComputePostOrders(Function &F,
1289                   SmallVectorImpl<BasicBlock *> &PostOrder,
1290                   SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
1291                   unsigned NoObjCARCExceptionsMDKind,
1292                   DenseMap<const BasicBlock *, BBState> &BBStates) {
1293   /// The visited set, for doing DFS walks.
1294   SmallPtrSet<BasicBlock *, 16> Visited;
1295
1296   // Do DFS, computing the PostOrder.
1297   SmallPtrSet<BasicBlock *, 16> OnStack;
1298   SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
1299
1300   // Functions always have exactly one entry block, and we don't have
1301   // any other block that we treat like an entry block.
1302   BasicBlock *EntryBB = &F.getEntryBlock();
1303   BBState &MyStates = BBStates[EntryBB];
1304   MyStates.SetAsEntry();
1305   TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
1306   SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
1307   Visited.insert(EntryBB);
1308   OnStack.insert(EntryBB);
1309   do {
1310   dfs_next_succ:
1311     BasicBlock *CurrBB = SuccStack.back().first;
1312     TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
1313     succ_iterator SE(TI, false);
1314
1315     while (SuccStack.back().second != SE) {
1316       BasicBlock *SuccBB = *SuccStack.back().second++;
1317       if (Visited.insert(SuccBB).second) {
1318         TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
1319         SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
1320         BBStates[CurrBB].addSucc(SuccBB);
1321         BBState &SuccStates = BBStates[SuccBB];
1322         SuccStates.addPred(CurrBB);
1323         OnStack.insert(SuccBB);
1324         goto dfs_next_succ;
1325       }
1326
1327       if (!OnStack.count(SuccBB)) {
1328         BBStates[CurrBB].addSucc(SuccBB);
1329         BBStates[SuccBB].addPred(CurrBB);
1330       }
1331     }
1332     OnStack.erase(CurrBB);
1333     PostOrder.push_back(CurrBB);
1334     SuccStack.pop_back();
1335   } while (!SuccStack.empty());
1336
1337   Visited.clear();
1338
1339   // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
1340   // Functions may have many exits, and there also blocks which we treat
1341   // as exits due to ignored edges.
1342   SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
1343   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
1344     BasicBlock *ExitBB = I;
1345     BBState &MyStates = BBStates[ExitBB];
1346     if (!MyStates.isExit())
1347       continue;
1348
1349     MyStates.SetAsExit();
1350
1351     PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
1352     Visited.insert(ExitBB);
1353     while (!PredStack.empty()) {
1354     reverse_dfs_next_succ:
1355       BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
1356       while (PredStack.back().second != PE) {
1357         BasicBlock *BB = *PredStack.back().second++;
1358         if (Visited.insert(BB).second) {
1359           PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
1360           goto reverse_dfs_next_succ;
1361         }
1362       }
1363       ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
1364     }
1365   }
1366 }
1367
1368 // Visit the function both top-down and bottom-up.
1369 bool ObjCARCOpt::Visit(Function &F,
1370                        DenseMap<const BasicBlock *, BBState> &BBStates,
1371                        BlotMapVector<Value *, RRInfo> &Retains,
1372                        DenseMap<Value *, RRInfo> &Releases) {
1373
1374   // Use reverse-postorder traversals, because we magically know that loops
1375   // will be well behaved, i.e. they won't repeatedly call retain on a single
1376   // pointer without doing a release. We can't use the ReversePostOrderTraversal
1377   // class here because we want the reverse-CFG postorder to consider each
1378   // function exit point, and we want to ignore selected cycle edges.
1379   SmallVector<BasicBlock *, 16> PostOrder;
1380   SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
1381   ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
1382                     MDKindCache.get(ARCMDKindID::NoObjCARCExceptions),
1383                     BBStates);
1384
1385   // Use reverse-postorder on the reverse CFG for bottom-up.
1386   bool BottomUpNestingDetected = false;
1387   for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
1388        ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
1389        I != E; ++I)
1390     BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
1391
1392   // Use reverse-postorder for top-down.
1393   bool TopDownNestingDetected = false;
1394   for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
1395        PostOrder.rbegin(), E = PostOrder.rend();
1396        I != E; ++I)
1397     TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
1398
1399   return TopDownNestingDetected && BottomUpNestingDetected;
1400 }
1401
1402 /// Move the calls in RetainsToMove and ReleasesToMove.
1403 void ObjCARCOpt::MoveCalls(Value *Arg, RRInfo &RetainsToMove,
1404                            RRInfo &ReleasesToMove,
1405                            BlotMapVector<Value *, RRInfo> &Retains,
1406                            DenseMap<Value *, RRInfo> &Releases,
1407                            SmallVectorImpl<Instruction *> &DeadInsts,
1408                            Module *M) {
1409   Type *ArgTy = Arg->getType();
1410   Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
1411
1412   DEBUG(dbgs() << "== ObjCARCOpt::MoveCalls ==\n");
1413
1414   // Insert the new retain and release calls.
1415   for (Instruction *InsertPt : ReleasesToMove.ReverseInsertPts) {
1416     Value *MyArg = ArgTy == ParamTy ? Arg :
1417                    new BitCastInst(Arg, ParamTy, "", InsertPt);
1418     Constant *Decl = EP.get(ARCRuntimeEntryPointKind::Retain);
1419     CallInst *Call = CallInst::Create(Decl, MyArg, "", InsertPt);
1420     Call->setDoesNotThrow();
1421     Call->setTailCall();
1422
1423     DEBUG(dbgs() << "Inserting new Retain: " << *Call << "\n"
1424                     "At insertion point: " << *InsertPt << "\n");
1425   }
1426   for (Instruction *InsertPt : RetainsToMove.ReverseInsertPts) {
1427     Value *MyArg = ArgTy == ParamTy ? Arg :
1428                    new BitCastInst(Arg, ParamTy, "", InsertPt);
1429     Constant *Decl = EP.get(ARCRuntimeEntryPointKind::Release);
1430     CallInst *Call = CallInst::Create(Decl, MyArg, "", InsertPt);
1431     // Attach a clang.imprecise_release metadata tag, if appropriate.
1432     if (MDNode *M = ReleasesToMove.ReleaseMetadata)
1433       Call->setMetadata(MDKindCache.get(ARCMDKindID::ImpreciseRelease), M);
1434     Call->setDoesNotThrow();
1435     if (ReleasesToMove.IsTailCallRelease)
1436       Call->setTailCall();
1437
1438     DEBUG(dbgs() << "Inserting new Release: " << *Call << "\n"
1439                     "At insertion point: " << *InsertPt << "\n");
1440   }
1441
1442   // Delete the original retain and release calls.
1443   for (Instruction *OrigRetain : RetainsToMove.Calls) {
1444     Retains.blot(OrigRetain);
1445     DeadInsts.push_back(OrigRetain);
1446     DEBUG(dbgs() << "Deleting retain: " << *OrigRetain << "\n");
1447   }
1448   for (Instruction *OrigRelease : ReleasesToMove.Calls) {
1449     Releases.erase(OrigRelease);
1450     DeadInsts.push_back(OrigRelease);
1451     DEBUG(dbgs() << "Deleting release: " << *OrigRelease << "\n");
1452   }
1453
1454 }
1455
1456 bool ObjCARCOpt::ConnectTDBUTraversals(
1457     DenseMap<const BasicBlock *, BBState> &BBStates,
1458     BlotMapVector<Value *, RRInfo> &Retains,
1459     DenseMap<Value *, RRInfo> &Releases, Module *M,
1460     SmallVectorImpl<Instruction *> &NewRetains,
1461     SmallVectorImpl<Instruction *> &NewReleases,
1462     SmallVectorImpl<Instruction *> &DeadInsts, RRInfo &RetainsToMove,
1463     RRInfo &ReleasesToMove, Value *Arg, bool KnownSafe,
1464     bool &AnyPairsCompletelyEliminated) {
1465   // If a pair happens in a region where it is known that the reference count
1466   // is already incremented, we can similarly ignore possible decrements unless
1467   // we are dealing with a retainable object with multiple provenance sources.
1468   bool KnownSafeTD = true, KnownSafeBU = true;
1469   bool MultipleOwners = false;
1470   bool CFGHazardAfflicted = false;
1471
1472   // Connect the dots between the top-down-collected RetainsToMove and
1473   // bottom-up-collected ReleasesToMove to form sets of related calls.
1474   // This is an iterative process so that we connect multiple releases
1475   // to multiple retains if needed.
1476   unsigned OldDelta = 0;
1477   unsigned NewDelta = 0;
1478   unsigned OldCount = 0;
1479   unsigned NewCount = 0;
1480   bool FirstRelease = true;
1481   for (;;) {
1482     for (SmallVectorImpl<Instruction *>::const_iterator
1483            NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
1484       Instruction *NewRetain = *NI;
1485       auto It = Retains.find(NewRetain);
1486       assert(It != Retains.end());
1487       const RRInfo &NewRetainRRI = It->second;
1488       KnownSafeTD &= NewRetainRRI.KnownSafe;
1489       MultipleOwners =
1490         MultipleOwners || MultiOwnersSet.count(GetArgRCIdentityRoot(NewRetain));
1491       for (Instruction *NewRetainRelease : NewRetainRRI.Calls) {
1492         auto Jt = Releases.find(NewRetainRelease);
1493         if (Jt == Releases.end())
1494           return false;
1495         const RRInfo &NewRetainReleaseRRI = Jt->second;
1496
1497         // If the release does not have a reference to the retain as well,
1498         // something happened which is unaccounted for. Do not do anything.
1499         //
1500         // This can happen if we catch an additive overflow during path count
1501         // merging.
1502         if (!NewRetainReleaseRRI.Calls.count(NewRetain))
1503           return false;
1504
1505         if (ReleasesToMove.Calls.insert(NewRetainRelease).second) {
1506
1507           // If we overflow when we compute the path count, don't remove/move
1508           // anything.
1509           const BBState &NRRBBState = BBStates[NewRetainRelease->getParent()];
1510           unsigned PathCount = BBState::OverflowOccurredValue;
1511           if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
1512             return false;
1513           assert(PathCount != BBState::OverflowOccurredValue &&
1514                  "PathCount at this point can not be "
1515                  "OverflowOccurredValue.");
1516           OldDelta -= PathCount;
1517
1518           // Merge the ReleaseMetadata and IsTailCallRelease values.
1519           if (FirstRelease) {
1520             ReleasesToMove.ReleaseMetadata =
1521               NewRetainReleaseRRI.ReleaseMetadata;
1522             ReleasesToMove.IsTailCallRelease =
1523               NewRetainReleaseRRI.IsTailCallRelease;
1524             FirstRelease = false;
1525           } else {
1526             if (ReleasesToMove.ReleaseMetadata !=
1527                 NewRetainReleaseRRI.ReleaseMetadata)
1528               ReleasesToMove.ReleaseMetadata = nullptr;
1529             if (ReleasesToMove.IsTailCallRelease !=
1530                 NewRetainReleaseRRI.IsTailCallRelease)
1531               ReleasesToMove.IsTailCallRelease = false;
1532           }
1533
1534           // Collect the optimal insertion points.
1535           if (!KnownSafe)
1536             for (Instruction *RIP : NewRetainReleaseRRI.ReverseInsertPts) {
1537               if (ReleasesToMove.ReverseInsertPts.insert(RIP).second) {
1538                 // If we overflow when we compute the path count, don't
1539                 // remove/move anything.
1540                 const BBState &RIPBBState = BBStates[RIP->getParent()];
1541                 PathCount = BBState::OverflowOccurredValue;
1542                 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
1543                   return false;
1544                 assert(PathCount != BBState::OverflowOccurredValue &&
1545                        "PathCount at this point can not be "
1546                        "OverflowOccurredValue.");
1547                 NewDelta -= PathCount;
1548               }
1549             }
1550           NewReleases.push_back(NewRetainRelease);
1551         }
1552       }
1553     }
1554     NewRetains.clear();
1555     if (NewReleases.empty()) break;
1556
1557     // Back the other way.
1558     for (SmallVectorImpl<Instruction *>::const_iterator
1559            NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
1560       Instruction *NewRelease = *NI;
1561       auto It = Releases.find(NewRelease);
1562       assert(It != Releases.end());
1563       const RRInfo &NewReleaseRRI = It->second;
1564       KnownSafeBU &= NewReleaseRRI.KnownSafe;
1565       CFGHazardAfflicted |= NewReleaseRRI.CFGHazardAfflicted;
1566       for (Instruction *NewReleaseRetain : NewReleaseRRI.Calls) {
1567         auto Jt = Retains.find(NewReleaseRetain);
1568         if (Jt == Retains.end())
1569           return false;
1570         const RRInfo &NewReleaseRetainRRI = Jt->second;
1571
1572         // If the retain does not have a reference to the release as well,
1573         // something happened which is unaccounted for. Do not do anything.
1574         //
1575         // This can happen if we catch an additive overflow during path count
1576         // merging.
1577         if (!NewReleaseRetainRRI.Calls.count(NewRelease))
1578           return false;
1579
1580         if (RetainsToMove.Calls.insert(NewReleaseRetain).second) {
1581           // If we overflow when we compute the path count, don't remove/move
1582           // anything.
1583           const BBState &NRRBBState = BBStates[NewReleaseRetain->getParent()];
1584           unsigned PathCount = BBState::OverflowOccurredValue;
1585           if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
1586             return false;
1587           assert(PathCount != BBState::OverflowOccurredValue &&
1588                  "PathCount at this point can not be "
1589                  "OverflowOccurredValue.");
1590           OldDelta += PathCount;
1591           OldCount += PathCount;
1592
1593           // Collect the optimal insertion points.
1594           if (!KnownSafe)
1595             for (Instruction *RIP : NewReleaseRetainRRI.ReverseInsertPts) {
1596               if (RetainsToMove.ReverseInsertPts.insert(RIP).second) {
1597                 // If we overflow when we compute the path count, don't
1598                 // remove/move anything.
1599                 const BBState &RIPBBState = BBStates[RIP->getParent()];
1600
1601                 PathCount = BBState::OverflowOccurredValue;
1602                 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
1603                   return false;
1604                 assert(PathCount != BBState::OverflowOccurredValue &&
1605                        "PathCount at this point can not be "
1606                        "OverflowOccurredValue.");
1607                 NewDelta += PathCount;
1608                 NewCount += PathCount;
1609               }
1610             }
1611           NewRetains.push_back(NewReleaseRetain);
1612         }
1613       }
1614     }
1615     NewReleases.clear();
1616     if (NewRetains.empty()) break;
1617   }
1618
1619   // If the pointer is known incremented in 1 direction and we do not have
1620   // MultipleOwners, we can safely remove the retain/releases. Otherwise we need
1621   // to be known safe in both directions.
1622   bool UnconditionallySafe = (KnownSafeTD && KnownSafeBU) ||
1623     ((KnownSafeTD || KnownSafeBU) && !MultipleOwners);
1624   if (UnconditionallySafe) {
1625     RetainsToMove.ReverseInsertPts.clear();
1626     ReleasesToMove.ReverseInsertPts.clear();
1627     NewCount = 0;
1628   } else {
1629     // Determine whether the new insertion points we computed preserve the
1630     // balance of retain and release calls through the program.
1631     // TODO: If the fully aggressive solution isn't valid, try to find a
1632     // less aggressive solution which is.
1633     if (NewDelta != 0)
1634       return false;
1635
1636     // At this point, we are not going to remove any RR pairs, but we still are
1637     // able to move RR pairs. If one of our pointers is afflicted with
1638     // CFGHazards, we cannot perform such code motion so exit early.
1639     const bool WillPerformCodeMotion = RetainsToMove.ReverseInsertPts.size() ||
1640       ReleasesToMove.ReverseInsertPts.size();
1641     if (CFGHazardAfflicted && WillPerformCodeMotion)
1642       return false;
1643   }
1644
1645   // Determine whether the original call points are balanced in the retain and
1646   // release calls through the program. If not, conservatively don't touch
1647   // them.
1648   // TODO: It's theoretically possible to do code motion in this case, as
1649   // long as the existing imbalances are maintained.
1650   if (OldDelta != 0)
1651     return false;
1652
1653   Changed = true;
1654   assert(OldCount != 0 && "Unreachable code?");
1655   NumRRs += OldCount - NewCount;
1656   // Set to true if we completely removed any RR pairs.
1657   AnyPairsCompletelyEliminated = NewCount == 0;
1658
1659   // We can move calls!
1660   return true;
1661 }
1662
1663 /// Identify pairings between the retains and releases, and delete and/or move
1664 /// them.
1665 bool ObjCARCOpt::PerformCodePlacement(
1666     DenseMap<const BasicBlock *, BBState> &BBStates,
1667     BlotMapVector<Value *, RRInfo> &Retains,
1668     DenseMap<Value *, RRInfo> &Releases, Module *M) {
1669   DEBUG(dbgs() << "\n== ObjCARCOpt::PerformCodePlacement ==\n");
1670
1671   bool AnyPairsCompletelyEliminated = false;
1672   RRInfo RetainsToMove;
1673   RRInfo ReleasesToMove;
1674   SmallVector<Instruction *, 4> NewRetains;
1675   SmallVector<Instruction *, 4> NewReleases;
1676   SmallVector<Instruction *, 8> DeadInsts;
1677
1678   // Visit each retain.
1679   for (BlotMapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
1680                                                       E = Retains.end();
1681        I != E; ++I) {
1682     Value *V = I->first;
1683     if (!V) continue; // blotted
1684
1685     Instruction *Retain = cast<Instruction>(V);
1686
1687     DEBUG(dbgs() << "Visiting: " << *Retain << "\n");
1688
1689     Value *Arg = GetArgRCIdentityRoot(Retain);
1690
1691     // If the object being released is in static or stack storage, we know it's
1692     // not being managed by ObjC reference counting, so we can delete pairs
1693     // regardless of what possible decrements or uses lie between them.
1694     bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
1695
1696     // A constant pointer can't be pointing to an object on the heap. It may
1697     // be reference-counted, but it won't be deleted.
1698     if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
1699       if (const GlobalVariable *GV =
1700             dyn_cast<GlobalVariable>(
1701               GetRCIdentityRoot(LI->getPointerOperand())))
1702         if (GV->isConstant())
1703           KnownSafe = true;
1704
1705     // Connect the dots between the top-down-collected RetainsToMove and
1706     // bottom-up-collected ReleasesToMove to form sets of related calls.
1707     NewRetains.push_back(Retain);
1708     bool PerformMoveCalls =
1709       ConnectTDBUTraversals(BBStates, Retains, Releases, M, NewRetains,
1710                             NewReleases, DeadInsts, RetainsToMove,
1711                             ReleasesToMove, Arg, KnownSafe,
1712                             AnyPairsCompletelyEliminated);
1713
1714     if (PerformMoveCalls) {
1715       // Ok, everything checks out and we're all set. Let's move/delete some
1716       // code!
1717       MoveCalls(Arg, RetainsToMove, ReleasesToMove,
1718                 Retains, Releases, DeadInsts, M);
1719     }
1720
1721     // Clean up state for next retain.
1722     NewReleases.clear();
1723     NewRetains.clear();
1724     RetainsToMove.clear();
1725     ReleasesToMove.clear();
1726   }
1727
1728   // Now that we're done moving everything, we can delete the newly dead
1729   // instructions, as we no longer need them as insert points.
1730   while (!DeadInsts.empty())
1731     EraseInstruction(DeadInsts.pop_back_val());
1732
1733   return AnyPairsCompletelyEliminated;
1734 }
1735
1736 /// Weak pointer optimizations.
1737 void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
1738   DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeWeakCalls ==\n");
1739
1740   // First, do memdep-style RLE and S2L optimizations. We can't use memdep
1741   // itself because it uses AliasAnalysis and we need to do provenance
1742   // queries instead.
1743   for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
1744     Instruction *Inst = &*I++;
1745
1746     DEBUG(dbgs() << "Visiting: " << *Inst << "\n");
1747
1748     ARCInstKind Class = GetBasicARCInstKind(Inst);
1749     if (Class != ARCInstKind::LoadWeak &&
1750         Class != ARCInstKind::LoadWeakRetained)
1751       continue;
1752
1753     // Delete objc_loadWeak calls with no users.
1754     if (Class == ARCInstKind::LoadWeak && Inst->use_empty()) {
1755       Inst->eraseFromParent();
1756       continue;
1757     }
1758
1759     // TODO: For now, just look for an earlier available version of this value
1760     // within the same block. Theoretically, we could do memdep-style non-local
1761     // analysis too, but that would want caching. A better approach would be to
1762     // use the technique that EarlyCSE uses.
1763     inst_iterator Current = std::prev(I);
1764     BasicBlock *CurrentBB = Current.getBasicBlockIterator();
1765     for (BasicBlock::iterator B = CurrentBB->begin(),
1766                               J = Current.getInstructionIterator();
1767          J != B; --J) {
1768       Instruction *EarlierInst = &*std::prev(J);
1769       ARCInstKind EarlierClass = GetARCInstKind(EarlierInst);
1770       switch (EarlierClass) {
1771       case ARCInstKind::LoadWeak:
1772       case ARCInstKind::LoadWeakRetained: {
1773         // If this is loading from the same pointer, replace this load's value
1774         // with that one.
1775         CallInst *Call = cast<CallInst>(Inst);
1776         CallInst *EarlierCall = cast<CallInst>(EarlierInst);
1777         Value *Arg = Call->getArgOperand(0);
1778         Value *EarlierArg = EarlierCall->getArgOperand(0);
1779         switch (PA.getAA()->alias(Arg, EarlierArg)) {
1780         case AliasAnalysis::MustAlias:
1781           Changed = true;
1782           // If the load has a builtin retain, insert a plain retain for it.
1783           if (Class == ARCInstKind::LoadWeakRetained) {
1784             Constant *Decl = EP.get(ARCRuntimeEntryPointKind::Retain);
1785             CallInst *CI = CallInst::Create(Decl, EarlierCall, "", Call);
1786             CI->setTailCall();
1787           }
1788           // Zap the fully redundant load.
1789           Call->replaceAllUsesWith(EarlierCall);
1790           Call->eraseFromParent();
1791           goto clobbered;
1792         case AliasAnalysis::MayAlias:
1793         case AliasAnalysis::PartialAlias:
1794           goto clobbered;
1795         case AliasAnalysis::NoAlias:
1796           break;
1797         }
1798         break;
1799       }
1800       case ARCInstKind::StoreWeak:
1801       case ARCInstKind::InitWeak: {
1802         // If this is storing to the same pointer and has the same size etc.
1803         // replace this load's value with the stored value.
1804         CallInst *Call = cast<CallInst>(Inst);
1805         CallInst *EarlierCall = cast<CallInst>(EarlierInst);
1806         Value *Arg = Call->getArgOperand(0);
1807         Value *EarlierArg = EarlierCall->getArgOperand(0);
1808         switch (PA.getAA()->alias(Arg, EarlierArg)) {
1809         case AliasAnalysis::MustAlias:
1810           Changed = true;
1811           // If the load has a builtin retain, insert a plain retain for it.
1812           if (Class == ARCInstKind::LoadWeakRetained) {
1813             Constant *Decl = EP.get(ARCRuntimeEntryPointKind::Retain);
1814             CallInst *CI = CallInst::Create(Decl, EarlierCall, "", Call);
1815             CI->setTailCall();
1816           }
1817           // Zap the fully redundant load.
1818           Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
1819           Call->eraseFromParent();
1820           goto clobbered;
1821         case AliasAnalysis::MayAlias:
1822         case AliasAnalysis::PartialAlias:
1823           goto clobbered;
1824         case AliasAnalysis::NoAlias:
1825           break;
1826         }
1827         break;
1828       }
1829       case ARCInstKind::MoveWeak:
1830       case ARCInstKind::CopyWeak:
1831         // TOOD: Grab the copied value.
1832         goto clobbered;
1833       case ARCInstKind::AutoreleasepoolPush:
1834       case ARCInstKind::None:
1835       case ARCInstKind::IntrinsicUser:
1836       case ARCInstKind::User:
1837         // Weak pointers are only modified through the weak entry points
1838         // (and arbitrary calls, which could call the weak entry points).
1839         break;
1840       default:
1841         // Anything else could modify the weak pointer.
1842         goto clobbered;
1843       }
1844     }
1845   clobbered:;
1846   }
1847
1848   // Then, for each destroyWeak with an alloca operand, check to see if
1849   // the alloca and all its users can be zapped.
1850   for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
1851     Instruction *Inst = &*I++;
1852     ARCInstKind Class = GetBasicARCInstKind(Inst);
1853     if (Class != ARCInstKind::DestroyWeak)
1854       continue;
1855
1856     CallInst *Call = cast<CallInst>(Inst);
1857     Value *Arg = Call->getArgOperand(0);
1858     if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
1859       for (User *U : Alloca->users()) {
1860         const Instruction *UserInst = cast<Instruction>(U);
1861         switch (GetBasicARCInstKind(UserInst)) {
1862         case ARCInstKind::InitWeak:
1863         case ARCInstKind::StoreWeak:
1864         case ARCInstKind::DestroyWeak:
1865           continue;
1866         default:
1867           goto done;
1868         }
1869       }
1870       Changed = true;
1871       for (auto UI = Alloca->user_begin(), UE = Alloca->user_end(); UI != UE;) {
1872         CallInst *UserInst = cast<CallInst>(*UI++);
1873         switch (GetBasicARCInstKind(UserInst)) {
1874         case ARCInstKind::InitWeak:
1875         case ARCInstKind::StoreWeak:
1876           // These functions return their second argument.
1877           UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
1878           break;
1879         case ARCInstKind::DestroyWeak:
1880           // No return value.
1881           break;
1882         default:
1883           llvm_unreachable("alloca really is used!");
1884         }
1885         UserInst->eraseFromParent();
1886       }
1887       Alloca->eraseFromParent();
1888     done:;
1889     }
1890   }
1891 }
1892
1893 /// Identify program paths which execute sequences of retains and releases which
1894 /// can be eliminated.
1895 bool ObjCARCOpt::OptimizeSequences(Function &F) {
1896   // Releases, Retains - These are used to store the results of the main flow
1897   // analysis. These use Value* as the key instead of Instruction* so that the
1898   // map stays valid when we get around to rewriting code and calls get
1899   // replaced by arguments.
1900   DenseMap<Value *, RRInfo> Releases;
1901   BlotMapVector<Value *, RRInfo> Retains;
1902
1903   // This is used during the traversal of the function to track the
1904   // states for each identified object at each block.
1905   DenseMap<const BasicBlock *, BBState> BBStates;
1906
1907   // Analyze the CFG of the function, and all instructions.
1908   bool NestingDetected = Visit(F, BBStates, Retains, Releases);
1909
1910   // Transform.
1911   bool AnyPairsCompletelyEliminated = PerformCodePlacement(BBStates, Retains,
1912                                                            Releases,
1913                                                            F.getParent());
1914
1915   // Cleanup.
1916   MultiOwnersSet.clear();
1917
1918   return AnyPairsCompletelyEliminated && NestingDetected;
1919 }
1920
1921 /// Check if there is a dependent call earlier that does not have anything in
1922 /// between the Retain and the call that can affect the reference count of their
1923 /// shared pointer argument. Note that Retain need not be in BB.
1924 static bool
1925 HasSafePathToPredecessorCall(const Value *Arg, Instruction *Retain,
1926                              SmallPtrSetImpl<Instruction *> &DepInsts,
1927                              SmallPtrSetImpl<const BasicBlock *> &Visited,
1928                              ProvenanceAnalysis &PA) {
1929   FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
1930                    DepInsts, Visited, PA);
1931   if (DepInsts.size() != 1)
1932     return false;
1933
1934   auto *Call = dyn_cast_or_null<CallInst>(*DepInsts.begin());
1935
1936   // Check that the pointer is the return value of the call.
1937   if (!Call || Arg != Call)
1938     return false;
1939
1940   // Check that the call is a regular call.
1941   ARCInstKind Class = GetBasicARCInstKind(Call);
1942   if (Class != ARCInstKind::CallOrUser && Class != ARCInstKind::Call)
1943     return false;
1944
1945   return true;
1946 }
1947
1948 /// Find a dependent retain that precedes the given autorelease for which there
1949 /// is nothing in between the two instructions that can affect the ref count of
1950 /// Arg.
1951 static CallInst *
1952 FindPredecessorRetainWithSafePath(const Value *Arg, BasicBlock *BB,
1953                                   Instruction *Autorelease,
1954                                   SmallPtrSetImpl<Instruction *> &DepInsts,
1955                                   SmallPtrSetImpl<const BasicBlock *> &Visited,
1956                                   ProvenanceAnalysis &PA) {
1957   FindDependencies(CanChangeRetainCount, Arg,
1958                    BB, Autorelease, DepInsts, Visited, PA);
1959   if (DepInsts.size() != 1)
1960     return nullptr;
1961
1962   auto *Retain = dyn_cast_or_null<CallInst>(*DepInsts.begin());
1963
1964   // Check that we found a retain with the same argument.
1965   if (!Retain || !IsRetain(GetBasicARCInstKind(Retain)) ||
1966       GetArgRCIdentityRoot(Retain) != Arg) {
1967     return nullptr;
1968   }
1969
1970   return Retain;
1971 }
1972
1973 /// Look for an ``autorelease'' instruction dependent on Arg such that there are
1974 /// no instructions dependent on Arg that need a positive ref count in between
1975 /// the autorelease and the ret.
1976 static CallInst *
1977 FindPredecessorAutoreleaseWithSafePath(const Value *Arg, BasicBlock *BB,
1978                                        ReturnInst *Ret,
1979                                        SmallPtrSetImpl<Instruction *> &DepInsts,
1980                                        SmallPtrSetImpl<const BasicBlock *> &V,
1981                                        ProvenanceAnalysis &PA) {
1982   FindDependencies(NeedsPositiveRetainCount, Arg,
1983                    BB, Ret, DepInsts, V, PA);
1984   if (DepInsts.size() != 1)
1985     return nullptr;
1986
1987   auto *Autorelease = dyn_cast_or_null<CallInst>(*DepInsts.begin());
1988   if (!Autorelease)
1989     return nullptr;
1990   ARCInstKind AutoreleaseClass = GetBasicARCInstKind(Autorelease);
1991   if (!IsAutorelease(AutoreleaseClass))
1992     return nullptr;
1993   if (GetArgRCIdentityRoot(Autorelease) != Arg)
1994     return nullptr;
1995
1996   return Autorelease;
1997 }
1998
1999 /// Look for this pattern:
2000 /// \code
2001 ///    %call = call i8* @something(...)
2002 ///    %2 = call i8* @objc_retain(i8* %call)
2003 ///    %3 = call i8* @objc_autorelease(i8* %2)
2004 ///    ret i8* %3
2005 /// \endcode
2006 /// And delete the retain and autorelease.
2007 void ObjCARCOpt::OptimizeReturns(Function &F) {
2008   if (!F.getReturnType()->isPointerTy())
2009     return;
2010
2011   DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeReturns ==\n");
2012
2013   SmallPtrSet<Instruction *, 4> DependingInstructions;
2014   SmallPtrSet<const BasicBlock *, 4> Visited;
2015   for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
2016     BasicBlock *BB = FI;
2017     ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
2018
2019     DEBUG(dbgs() << "Visiting: " << *Ret << "\n");
2020
2021     if (!Ret)
2022       continue;
2023
2024     const Value *Arg = GetRCIdentityRoot(Ret->getOperand(0));
2025
2026     // Look for an ``autorelease'' instruction that is a predecessor of Ret and
2027     // dependent on Arg such that there are no instructions dependent on Arg
2028     // that need a positive ref count in between the autorelease and Ret.
2029     CallInst *Autorelease =
2030       FindPredecessorAutoreleaseWithSafePath(Arg, BB, Ret,
2031                                              DependingInstructions, Visited,
2032                                              PA);
2033     DependingInstructions.clear();
2034     Visited.clear();
2035
2036     if (!Autorelease)
2037       continue;
2038
2039     CallInst *Retain =
2040       FindPredecessorRetainWithSafePath(Arg, BB, Autorelease,
2041                                         DependingInstructions, Visited, PA);
2042     DependingInstructions.clear();
2043     Visited.clear();
2044
2045     if (!Retain)
2046       continue;
2047
2048     // Check that there is nothing that can affect the reference count
2049     // between the retain and the call.  Note that Retain need not be in BB.
2050     bool HasSafePathToCall = HasSafePathToPredecessorCall(Arg, Retain,
2051                                                           DependingInstructions,
2052                                                           Visited, PA);
2053     DependingInstructions.clear();
2054     Visited.clear();
2055
2056     if (!HasSafePathToCall)
2057       continue;
2058
2059     // If so, we can zap the retain and autorelease.
2060     Changed = true;
2061     ++NumRets;
2062     DEBUG(dbgs() << "Erasing: " << *Retain << "\nErasing: "
2063           << *Autorelease << "\n");
2064     EraseInstruction(Retain);
2065     EraseInstruction(Autorelease);
2066   }
2067 }
2068
2069 #ifndef NDEBUG
2070 void
2071 ObjCARCOpt::GatherStatistics(Function &F, bool AfterOptimization) {
2072   llvm::Statistic &NumRetains =
2073     AfterOptimization? NumRetainsAfterOpt : NumRetainsBeforeOpt;
2074   llvm::Statistic &NumReleases =
2075     AfterOptimization? NumReleasesAfterOpt : NumReleasesBeforeOpt;
2076
2077   for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2078     Instruction *Inst = &*I++;
2079     switch (GetBasicARCInstKind(Inst)) {
2080     default:
2081       break;
2082     case ARCInstKind::Retain:
2083       ++NumRetains;
2084       break;
2085     case ARCInstKind::Release:
2086       ++NumReleases;
2087       break;
2088     }
2089   }
2090 }
2091 #endif
2092
2093 bool ObjCARCOpt::doInitialization(Module &M) {
2094   if (!EnableARCOpts)
2095     return false;
2096
2097   // If nothing in the Module uses ARC, don't do anything.
2098   Run = ModuleHasARC(M);
2099   if (!Run)
2100     return false;
2101
2102   // Intuitively, objc_retain and others are nocapture, however in practice
2103   // they are not, because they return their argument value. And objc_release
2104   // calls finalizers which can have arbitrary side effects.
2105   MDKindCache.init(&M);
2106
2107   // Initialize our runtime entry point cache.
2108   EP.init(&M);
2109
2110   return false;
2111 }
2112
2113 bool ObjCARCOpt::runOnFunction(Function &F) {
2114   if (!EnableARCOpts)
2115     return false;
2116
2117   // If nothing in the Module uses ARC, don't do anything.
2118   if (!Run)
2119     return false;
2120
2121   Changed = false;
2122
2123   DEBUG(dbgs() << "<<< ObjCARCOpt: Visiting Function: " << F.getName() << " >>>"
2124         "\n");
2125
2126   PA.setAA(&getAnalysis<AliasAnalysis>());
2127
2128 #ifndef NDEBUG
2129   if (AreStatisticsEnabled()) {
2130     GatherStatistics(F, false);
2131   }
2132 #endif
2133
2134   // This pass performs several distinct transformations. As a compile-time aid
2135   // when compiling code that isn't ObjC, skip these if the relevant ObjC
2136   // library functions aren't declared.
2137
2138   // Preliminary optimizations. This also computes UsedInThisFunction.
2139   OptimizeIndividualCalls(F);
2140
2141   // Optimizations for weak pointers.
2142   if (UsedInThisFunction & ((1 << unsigned(ARCInstKind::LoadWeak)) |
2143                             (1 << unsigned(ARCInstKind::LoadWeakRetained)) |
2144                             (1 << unsigned(ARCInstKind::StoreWeak)) |
2145                             (1 << unsigned(ARCInstKind::InitWeak)) |
2146                             (1 << unsigned(ARCInstKind::CopyWeak)) |
2147                             (1 << unsigned(ARCInstKind::MoveWeak)) |
2148                             (1 << unsigned(ARCInstKind::DestroyWeak))))
2149     OptimizeWeakCalls(F);
2150
2151   // Optimizations for retain+release pairs.
2152   if (UsedInThisFunction & ((1 << unsigned(ARCInstKind::Retain)) |
2153                             (1 << unsigned(ARCInstKind::RetainRV)) |
2154                             (1 << unsigned(ARCInstKind::RetainBlock))))
2155     if (UsedInThisFunction & (1 << unsigned(ARCInstKind::Release)))
2156       // Run OptimizeSequences until it either stops making changes or
2157       // no retain+release pair nesting is detected.
2158       while (OptimizeSequences(F)) {}
2159
2160   // Optimizations if objc_autorelease is used.
2161   if (UsedInThisFunction & ((1 << unsigned(ARCInstKind::Autorelease)) |
2162                             (1 << unsigned(ARCInstKind::AutoreleaseRV))))
2163     OptimizeReturns(F);
2164
2165   // Gather statistics after optimization.
2166 #ifndef NDEBUG
2167   if (AreStatisticsEnabled()) {
2168     GatherStatistics(F, true);
2169   }
2170 #endif
2171
2172   DEBUG(dbgs() << "\n");
2173
2174   return Changed;
2175 }
2176
2177 void ObjCARCOpt::releaseMemory() {
2178   PA.clear();
2179 }
2180
2181 /// @}
2182 ///