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