blob: fc5cf4e8646d46cc6999c09a35c47e486fcc05b7 [file] [log] [blame]
Michael Gottesman79d8d812013-01-28 01:35:51 +00001//===- ObjCARCOpts.cpp - ObjC ARC Optimization ----------------------------===//
John McCalld935e9c2011-06-15 23:37:01 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Michael Gottesman97e3df02013-01-14 00:35:14 +00009/// \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
Michael Gottesman697d8b92013-02-07 04:12:57 +000016/// redundant weak pointer operations, and numerous minor simplifications.
Michael Gottesman97e3df02013-01-14 00:35:14 +000017///
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///
John McCalld935e9c2011-06-15 23:37:01 +000025//===----------------------------------------------------------------------===//
26
Michael Gottesman08904e32013-01-28 03:28:38 +000027#define DEBUG_TYPE "objc-arc-opts"
28#include "ObjCARC.h"
Michael Gottesman278266f2013-01-29 04:20:52 +000029#include "DependencyAnalysis.h"
Michael Gottesman294e7da2013-01-28 05:51:54 +000030#include "ObjCARCAliasAnalysis.h"
Michael Gottesman778138e2013-01-29 03:03:03 +000031#include "ProvenanceAnalysis.h"
John McCalld935e9c2011-06-15 23:37:01 +000032#include "llvm/ADT/DenseMap.h"
Michael Gottesman5a91bbf2013-05-24 20:44:02 +000033#include "llvm/ADT/DenseSet.h"
Michael Gottesmanfa0939f2013-01-28 04:12:07 +000034#include "llvm/ADT/STLExtras.h"
Michael Gottesman778138e2013-01-29 03:03:03 +000035#include "llvm/ADT/SmallPtrSet.h"
Michael Gottesman278266f2013-01-29 04:20:52 +000036#include "llvm/ADT/Statistic.h"
Michael Gottesmancd4de0f2013-03-26 00:42:09 +000037#include "llvm/IR/IRBuilder.h"
Michael Gottesman278266f2013-01-29 04:20:52 +000038#include "llvm/IR/LLVMContext.h"
Michael Gottesman778138e2013-01-29 03:03:03 +000039#include "llvm/Support/CFG.h"
Michael Gottesman13a5f1a2013-01-29 04:51:59 +000040#include "llvm/Support/Debug.h"
Timur Iskhodzhanov5d7ff002013-01-29 09:09:27 +000041#include "llvm/Support/raw_ostream.h"
Michael Gottesmanfa0939f2013-01-28 04:12:07 +000042
John McCalld935e9c2011-06-15 23:37:01 +000043using namespace llvm;
Michael Gottesman08904e32013-01-28 03:28:38 +000044using namespace llvm::objcarc;
John McCalld935e9c2011-06-15 23:37:01 +000045
Michael Gottesman97e3df02013-01-14 00:35:14 +000046/// \defgroup MiscUtils Miscellaneous utilities that are not ARC specific.
47/// @{
John McCalld935e9c2011-06-15 23:37:01 +000048
49namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +000050 /// \brief An associative container with fast insertion-order (deterministic)
51 /// iteration over its elements. Plus the special blot operation.
John McCalld935e9c2011-06-15 23:37:01 +000052 template<class KeyT, class ValueT>
53 class MapVector {
Michael Gottesman97e3df02013-01-14 00:35:14 +000054 /// Map keys to indices in Vector.
John McCalld935e9c2011-06-15 23:37:01 +000055 typedef DenseMap<KeyT, size_t> MapTy;
56 MapTy Map;
57
John McCalld935e9c2011-06-15 23:37:01 +000058 typedef std::vector<std::pair<KeyT, ValueT> > VectorTy;
Michael Gottesman97e3df02013-01-14 00:35:14 +000059 /// Keys and values.
John McCalld935e9c2011-06-15 23:37:01 +000060 VectorTy Vector;
61
62 public:
63 typedef typename VectorTy::iterator iterator;
64 typedef typename VectorTy::const_iterator const_iterator;
65 iterator begin() { return Vector.begin(); }
66 iterator end() { return Vector.end(); }
67 const_iterator begin() const { return Vector.begin(); }
68 const_iterator end() const { return Vector.end(); }
69
70#ifdef XDEBUG
71 ~MapVector() {
72 assert(Vector.size() >= Map.size()); // May differ due to blotting.
73 for (typename MapTy::const_iterator I = Map.begin(), E = Map.end();
74 I != E; ++I) {
75 assert(I->second < Vector.size());
76 assert(Vector[I->second].first == I->first);
77 }
78 for (typename VectorTy::const_iterator I = Vector.begin(),
79 E = Vector.end(); I != E; ++I)
80 assert(!I->first ||
81 (Map.count(I->first) &&
82 Map[I->first] == size_t(I - Vector.begin())));
83 }
84#endif
85
Dan Gohman55b06742012-03-02 01:13:53 +000086 ValueT &operator[](const KeyT &Arg) {
John McCalld935e9c2011-06-15 23:37:01 +000087 std::pair<typename MapTy::iterator, bool> Pair =
88 Map.insert(std::make_pair(Arg, size_t(0)));
89 if (Pair.second) {
Dan Gohman55b06742012-03-02 01:13:53 +000090 size_t Num = Vector.size();
91 Pair.first->second = Num;
John McCalld935e9c2011-06-15 23:37:01 +000092 Vector.push_back(std::make_pair(Arg, ValueT()));
Dan Gohman55b06742012-03-02 01:13:53 +000093 return Vector[Num].second;
John McCalld935e9c2011-06-15 23:37:01 +000094 }
95 return Vector[Pair.first->second].second;
96 }
97
98 std::pair<iterator, bool>
99 insert(const std::pair<KeyT, ValueT> &InsertPair) {
100 std::pair<typename MapTy::iterator, bool> Pair =
101 Map.insert(std::make_pair(InsertPair.first, size_t(0)));
102 if (Pair.second) {
Dan Gohman55b06742012-03-02 01:13:53 +0000103 size_t Num = Vector.size();
104 Pair.first->second = Num;
John McCalld935e9c2011-06-15 23:37:01 +0000105 Vector.push_back(InsertPair);
Dan Gohman55b06742012-03-02 01:13:53 +0000106 return std::make_pair(Vector.begin() + Num, true);
John McCalld935e9c2011-06-15 23:37:01 +0000107 }
108 return std::make_pair(Vector.begin() + Pair.first->second, false);
109 }
110
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000111 iterator find(const KeyT &Key) {
112 typename MapTy::iterator It = Map.find(Key);
113 if (It == Map.end()) return Vector.end();
114 return Vector.begin() + It->second;
115 }
116
Dan Gohman55b06742012-03-02 01:13:53 +0000117 const_iterator find(const KeyT &Key) const {
John McCalld935e9c2011-06-15 23:37:01 +0000118 typename MapTy::const_iterator It = Map.find(Key);
119 if (It == Map.end()) return Vector.end();
120 return Vector.begin() + It->second;
121 }
122
Michael Gottesman97e3df02013-01-14 00:35:14 +0000123 /// This is similar to erase, but instead of removing the element from the
124 /// vector, it just zeros out the key in the vector. This leaves iterators
125 /// intact, but clients must be prepared for zeroed-out keys when iterating.
Dan Gohman55b06742012-03-02 01:13:53 +0000126 void blot(const KeyT &Key) {
John McCalld935e9c2011-06-15 23:37:01 +0000127 typename MapTy::iterator It = Map.find(Key);
128 if (It == Map.end()) return;
129 Vector[It->second].first = KeyT();
130 Map.erase(It);
131 }
132
133 void clear() {
134 Map.clear();
135 Vector.clear();
136 }
137 };
138}
139
Michael Gottesman97e3df02013-01-14 00:35:14 +0000140/// @}
141///
142/// \defgroup ARCUtilities Utility declarations/definitions specific to ARC.
143/// @{
John McCalld935e9c2011-06-15 23:37:01 +0000144
Michael Gottesman97e3df02013-01-14 00:35:14 +0000145/// \brief This is similar to StripPointerCastsAndObjCCalls but it stops as soon
146/// as it finds a value with multiple uses.
John McCalld935e9c2011-06-15 23:37:01 +0000147static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
148 if (Arg->hasOneUse()) {
149 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
150 return FindSingleUseIdentifiedObject(BC->getOperand(0));
151 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
152 if (GEP->hasAllZeroIndices())
153 return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
154 if (IsForwarding(GetBasicInstructionClass(Arg)))
155 return FindSingleUseIdentifiedObject(
156 cast<CallInst>(Arg)->getArgOperand(0));
157 if (!IsObjCIdentifiedObject(Arg))
158 return 0;
159 return Arg;
160 }
161
Dan Gohman41375a32012-05-08 23:39:44 +0000162 // If we found an identifiable object but it has multiple uses, but they are
163 // trivial uses, we can still consider this to be a single-use value.
John McCalld935e9c2011-06-15 23:37:01 +0000164 if (IsObjCIdentifiedObject(Arg)) {
165 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
166 UI != UE; ++UI) {
167 const User *U = *UI;
168 if (!U->use_empty() || StripPointerCastsAndObjCCalls(U) != Arg)
169 return 0;
170 }
171
172 return Arg;
173 }
174
175 return 0;
176}
177
Michael Gottesman774d2c02013-01-29 21:00:52 +0000178/// \brief Test whether the given retainable object pointer escapes.
Michael Gottesman97e3df02013-01-14 00:35:14 +0000179///
180/// This differs from regular escape analysis in that a use as an
181/// argument to a call is not considered an escape.
182///
Michael Gottesman774d2c02013-01-29 21:00:52 +0000183static bool DoesRetainableObjPtrEscape(const User *Ptr) {
Michael Gottesman774d2c02013-01-29 21:00:52 +0000184 DEBUG(dbgs() << "DoesRetainableObjPtrEscape: Target: " << *Ptr << "\n");
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000185
Dan Gohman728db492012-01-13 00:39:07 +0000186 // Walk the def-use chains.
187 SmallVector<const Value *, 4> Worklist;
Michael Gottesman774d2c02013-01-29 21:00:52 +0000188 Worklist.push_back(Ptr);
189 // If Ptr has any operands add them as well.
Michael Gottesman23cda0c2013-01-29 21:07:53 +0000190 for (User::const_op_iterator I = Ptr->op_begin(), E = Ptr->op_end(); I != E;
191 ++I) {
Michael Gottesman774d2c02013-01-29 21:00:52 +0000192 Worklist.push_back(*I);
193 }
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000194
195 // Ensure we do not visit any value twice.
Michael Gottesman774d2c02013-01-29 21:00:52 +0000196 SmallPtrSet<const Value *, 8> VisitedSet;
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000197
Dan Gohman728db492012-01-13 00:39:07 +0000198 do {
199 const Value *V = Worklist.pop_back_val();
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000200
Michael Gottesman89279f82013-04-05 18:10:41 +0000201 DEBUG(dbgs() << "Visiting: " << *V << "\n");
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000202
Dan Gohman728db492012-01-13 00:39:07 +0000203 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
204 UI != UE; ++UI) {
205 const User *UUser = *UI;
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000206
Michael Gottesman89279f82013-04-05 18:10:41 +0000207 DEBUG(dbgs() << "User: " << *UUser << "\n");
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000208
Dan Gohman728db492012-01-13 00:39:07 +0000209 // Special - Use by a call (callee or argument) is not considered
210 // to be an escape.
Dan Gohmane1e352a2012-04-13 18:28:58 +0000211 switch (GetBasicInstructionClass(UUser)) {
212 case IC_StoreWeak:
213 case IC_InitWeak:
214 case IC_StoreStrong:
215 case IC_Autorelease:
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000216 case IC_AutoreleaseRV: {
Michael Gottesman89279f82013-04-05 18:10:41 +0000217 DEBUG(dbgs() << "User copies pointer arguments. Pointer Escapes!\n");
Dan Gohmane1e352a2012-04-13 18:28:58 +0000218 // These special functions make copies of their pointer arguments.
219 return true;
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000220 }
John McCall20182ac2013-03-22 21:38:36 +0000221 case IC_IntrinsicUser:
222 // Use by the use intrinsic is not an escape.
223 continue;
Dan Gohmane1e352a2012-04-13 18:28:58 +0000224 case IC_User:
225 case IC_None:
226 // Use by an instruction which copies the value is an escape if the
227 // result is an escape.
228 if (isa<BitCastInst>(UUser) || isa<GetElementPtrInst>(UUser) ||
229 isa<PHINode>(UUser) || isa<SelectInst>(UUser)) {
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000230
Michael Gottesmanf4b77612013-02-23 00:31:32 +0000231 if (VisitedSet.insert(UUser)) {
Michael Gottesman89279f82013-04-05 18:10:41 +0000232 DEBUG(dbgs() << "User copies value. Ptr escapes if result escapes."
233 " Adding to list.\n");
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000234 Worklist.push_back(UUser);
235 } else {
Michael Gottesman89279f82013-04-05 18:10:41 +0000236 DEBUG(dbgs() << "Already visited node.\n");
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000237 }
Dan Gohmane1e352a2012-04-13 18:28:58 +0000238 continue;
239 }
240 // Use by a load is not an escape.
241 if (isa<LoadInst>(UUser))
242 continue;
243 // Use by a store is not an escape if the use is the address.
244 if (const StoreInst *SI = dyn_cast<StoreInst>(UUser))
245 if (V != SI->getValueOperand())
246 continue;
247 break;
248 default:
249 // Regular calls and other stuff are not considered escapes.
Dan Gohman728db492012-01-13 00:39:07 +0000250 continue;
251 }
Dan Gohmaneb6e0152012-02-13 22:57:02 +0000252 // Otherwise, conservatively assume an escape.
Michael Gottesman89279f82013-04-05 18:10:41 +0000253 DEBUG(dbgs() << "Assuming ptr escapes.\n");
Dan Gohman728db492012-01-13 00:39:07 +0000254 return true;
255 }
256 } while (!Worklist.empty());
257
258 // No escapes found.
Michael Gottesman89279f82013-04-05 18:10:41 +0000259 DEBUG(dbgs() << "Ptr does not escape.\n");
Dan Gohman728db492012-01-13 00:39:07 +0000260 return false;
261}
262
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000263/// This is a wrapper around getUnderlyingObjCPtr along the lines of
264/// GetUnderlyingObjects except that it returns early when it sees the first
265/// alloca.
266static inline bool AreAnyUnderlyingObjectsAnAlloca(const Value *V) {
267 SmallPtrSet<const Value *, 4> Visited;
268 SmallVector<const Value *, 4> Worklist;
269 Worklist.push_back(V);
270 do {
271 const Value *P = Worklist.pop_back_val();
272 P = GetUnderlyingObjCPtr(P);
Michael Gottesman0c8b5622013-05-14 06:40:10 +0000273
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000274 if (isa<AllocaInst>(P))
275 return true;
Michael Gottesman0c8b5622013-05-14 06:40:10 +0000276
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000277 if (!Visited.insert(P))
278 continue;
Michael Gottesman0c8b5622013-05-14 06:40:10 +0000279
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000280 if (const SelectInst *SI = dyn_cast<const SelectInst>(P)) {
281 Worklist.push_back(SI->getTrueValue());
282 Worklist.push_back(SI->getFalseValue());
283 continue;
284 }
Michael Gottesman0c8b5622013-05-14 06:40:10 +0000285
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000286 if (const PHINode *PN = dyn_cast<const PHINode>(P)) {
287 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
288 Worklist.push_back(PN->getIncomingValue(i));
289 continue;
290 }
291 } while (!Worklist.empty());
292
293 return false;
294}
295
296
Michael Gottesman97e3df02013-01-14 00:35:14 +0000297/// @}
298///
Michael Gottesman97e3df02013-01-14 00:35:14 +0000299/// \defgroup ARCOpt ARC Optimization.
300/// @{
John McCalld935e9c2011-06-15 23:37:01 +0000301
302// TODO: On code like this:
303//
304// objc_retain(%x)
305// stuff_that_cannot_release()
306// objc_autorelease(%x)
307// stuff_that_cannot_release()
308// objc_retain(%x)
309// stuff_that_cannot_release()
310// objc_autorelease(%x)
311//
312// The second retain and autorelease can be deleted.
313
314// TODO: It should be possible to delete
315// objc_autoreleasePoolPush and objc_autoreleasePoolPop
316// pairs if nothing is actually autoreleased between them. Also, autorelease
317// calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
318// after inlining) can be turned into plain release calls.
319
320// TODO: Critical-edge splitting. If the optimial insertion point is
321// a critical edge, the current algorithm has to fail, because it doesn't
322// know how to split edges. It should be possible to make the optimizer
323// think in terms of edges, rather than blocks, and then split critical
324// edges on demand.
325
326// TODO: OptimizeSequences could generalized to be Interprocedural.
327
328// TODO: Recognize that a bunch of other objc runtime calls have
329// non-escaping arguments and non-releasing arguments, and may be
330// non-autoreleasing.
331
332// TODO: Sink autorelease calls as far as possible. Unfortunately we
333// usually can't sink them past other calls, which would be the main
334// case where it would be useful.
335
Dan Gohmanb3894012011-08-19 00:26:36 +0000336// TODO: The pointer returned from objc_loadWeakRetained is retained.
337
338// TODO: Delete release+retain pairs (rare).
Dan Gohmanceaac7c2011-06-20 23:20:43 +0000339
John McCalld935e9c2011-06-15 23:37:01 +0000340STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
341STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
342STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
343STATISTIC(NumRets, "Number of return value forwarding "
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000344 "retain+autoreleases eliminated");
John McCalld935e9c2011-06-15 23:37:01 +0000345STATISTIC(NumRRs, "Number of retain+release paths eliminated");
346STATISTIC(NumPeeps, "Number of calls peephole-optimized");
Matt Beaumont-Gaye55d9492013-05-13 21:10:49 +0000347#ifndef NDEBUG
Michael Gottesman9c118152013-04-29 06:16:57 +0000348STATISTIC(NumRetainsBeforeOpt,
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000349 "Number of retains before optimization");
Michael Gottesman9c118152013-04-29 06:16:57 +0000350STATISTIC(NumReleasesBeforeOpt,
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000351 "Number of releases before optimization");
Michael Gottesman9c118152013-04-29 06:16:57 +0000352STATISTIC(NumRetainsAfterOpt,
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000353 "Number of retains after optimization");
Michael Gottesman9c118152013-04-29 06:16:57 +0000354STATISTIC(NumReleasesAfterOpt,
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000355 "Number of releases after optimization");
Michael Gottesman03cf3c82013-04-29 07:29:08 +0000356#endif
John McCalld935e9c2011-06-15 23:37:01 +0000357
358namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000359 /// \enum Sequence
360 ///
361 /// \brief A sequence of states that a pointer may go through in which an
362 /// objc_retain and objc_release are actually needed.
John McCalld935e9c2011-06-15 23:37:01 +0000363 enum Sequence {
364 S_None,
Michael Gottesman53fd20b2013-01-29 21:07:51 +0000365 S_Retain, ///< objc_retain(x).
366 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement.
367 S_Use, ///< any use of x.
Michael Gottesman386241c2013-01-29 21:39:02 +0000368 S_Stop, ///< like S_Release, but code motion is stopped.
Michael Gottesman53fd20b2013-01-29 21:07:51 +0000369 S_Release, ///< objc_release(x).
Michael Gottesman9bdab2b2013-01-29 21:41:44 +0000370 S_MovableRelease ///< objc_release(x), !clang.imprecise_release.
John McCalld935e9c2011-06-15 23:37:01 +0000371 };
Michael Gottesman53fd20b2013-01-29 21:07:51 +0000372
373 raw_ostream &operator<<(raw_ostream &OS, const Sequence S)
374 LLVM_ATTRIBUTE_UNUSED;
375 raw_ostream &operator<<(raw_ostream &OS, const Sequence S) {
376 switch (S) {
377 case S_None:
378 return OS << "S_None";
379 case S_Retain:
380 return OS << "S_Retain";
381 case S_CanRelease:
382 return OS << "S_CanRelease";
383 case S_Use:
384 return OS << "S_Use";
385 case S_Release:
386 return OS << "S_Release";
387 case S_MovableRelease:
388 return OS << "S_MovableRelease";
389 case S_Stop:
390 return OS << "S_Stop";
391 }
392 llvm_unreachable("Unknown sequence type.");
393 }
John McCalld935e9c2011-06-15 23:37:01 +0000394}
395
396static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
397 // The easy cases.
398 if (A == B)
399 return A;
400 if (A == S_None || B == S_None)
401 return S_None;
402
John McCalld935e9c2011-06-15 23:37:01 +0000403 if (A > B) std::swap(A, B);
404 if (TopDown) {
405 // Choose the side which is further along in the sequence.
Dan Gohman12130272011-08-12 00:26:31 +0000406 if ((A == S_Retain || A == S_CanRelease) &&
407 (B == S_CanRelease || B == S_Use))
John McCalld935e9c2011-06-15 23:37:01 +0000408 return B;
409 } else {
410 // Choose the side which is further along in the sequence.
411 if ((A == S_Use || A == S_CanRelease) &&
Dan Gohman12130272011-08-12 00:26:31 +0000412 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
John McCalld935e9c2011-06-15 23:37:01 +0000413 return A;
414 // If both sides are releases, choose the more conservative one.
415 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
416 return A;
417 if (A == S_Release && B == S_MovableRelease)
418 return A;
419 }
420
421 return S_None;
422}
423
424namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000425 /// \brief Unidirectional information about either a
John McCalld935e9c2011-06-15 23:37:01 +0000426 /// retain-decrement-use-release sequence or release-use-decrement-retain
Bob Wilson798a7702013-04-09 22:15:51 +0000427 /// reverse sequence.
John McCalld935e9c2011-06-15 23:37:01 +0000428 struct RRInfo {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000429 /// After an objc_retain, the reference count of the referenced
Dan Gohmanb3894012011-08-19 00:26:36 +0000430 /// object is known to be positive. Similarly, before an objc_release, the
431 /// reference count of the referenced object is known to be positive. If
432 /// there are retain-release pairs in code regions where the retain count
433 /// is known to be positive, they can be eliminated, regardless of any side
434 /// effects between them.
435 ///
436 /// Also, a retain+release pair nested within another retain+release
437 /// pair all on the known same pointer value can be eliminated, regardless
438 /// of any intervening side effects.
439 ///
440 /// KnownSafe is true when either of these conditions is satisfied.
441 bool KnownSafe;
John McCalld935e9c2011-06-15 23:37:01 +0000442
Michael Gottesman97e3df02013-01-14 00:35:14 +0000443 /// True of the objc_release calls are all marked with the "tail" keyword.
John McCalld935e9c2011-06-15 23:37:01 +0000444 bool IsTailCallRelease;
445
Michael Gottesman97e3df02013-01-14 00:35:14 +0000446 /// If the Calls are objc_release calls and they all have a
447 /// clang.imprecise_release tag, this is the metadata tag.
John McCalld935e9c2011-06-15 23:37:01 +0000448 MDNode *ReleaseMetadata;
449
Michael Gottesman97e3df02013-01-14 00:35:14 +0000450 /// For a top-down sequence, the set of objc_retains or
John McCalld935e9c2011-06-15 23:37:01 +0000451 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
452 SmallPtrSet<Instruction *, 2> Calls;
453
Michael Gottesman97e3df02013-01-14 00:35:14 +0000454 /// The set of optimal insert positions for moving calls in the opposite
455 /// sequence.
John McCalld935e9c2011-06-15 23:37:01 +0000456 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
457
Michael Gottesmane67f40c2013-05-24 20:44:05 +0000458 /// If this is true, we cannot perform code motion but can still remove
459 /// retain/release pairs.
460 bool CFGHazardAfflicted;
461
John McCalld935e9c2011-06-15 23:37:01 +0000462 RRInfo() :
Michael Gottesmane67f40c2013-05-24 20:44:05 +0000463 KnownSafe(false), IsTailCallRelease(false), ReleaseMetadata(0),
464 CFGHazardAfflicted(false) {}
John McCalld935e9c2011-06-15 23:37:01 +0000465
466 void clear();
Michael Gottesman79249972013-04-05 23:46:45 +0000467
Michael Gottesman1d8d2572013-04-05 22:54:28 +0000468 bool IsTrackingImpreciseReleases() {
469 return ReleaseMetadata != 0;
470 }
John McCalld935e9c2011-06-15 23:37:01 +0000471 };
472}
473
474void RRInfo::clear() {
Dan Gohmanb3894012011-08-19 00:26:36 +0000475 KnownSafe = false;
John McCalld935e9c2011-06-15 23:37:01 +0000476 IsTailCallRelease = false;
477 ReleaseMetadata = 0;
478 Calls.clear();
479 ReverseInsertPts.clear();
Michael Gottesmane67f40c2013-05-24 20:44:05 +0000480 CFGHazardAfflicted = false;
John McCalld935e9c2011-06-15 23:37:01 +0000481}
482
483namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000484 /// \brief This class summarizes several per-pointer runtime properties which
485 /// are propogated through the flow graph.
John McCalld935e9c2011-06-15 23:37:01 +0000486 class PtrState {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000487 /// True if the reference count is known to be incremented.
Dan Gohman62079b42012-04-25 00:50:46 +0000488 bool KnownPositiveRefCount;
489
Bob Wilson798a7702013-04-09 22:15:51 +0000490 /// True if we've seen an opportunity for partial RR elimination, such as
Michael Gottesman97e3df02013-01-14 00:35:14 +0000491 /// pushing calls into a CFG triangle or into one side of a CFG diamond.
Dan Gohman62079b42012-04-25 00:50:46 +0000492 bool Partial;
John McCalld935e9c2011-06-15 23:37:01 +0000493
Michael Gottesman97e3df02013-01-14 00:35:14 +0000494 /// The current position in the sequence.
Dan Gohman41375a32012-05-08 23:39:44 +0000495 Sequence Seq : 8;
John McCalld935e9c2011-06-15 23:37:01 +0000496
497 public:
Michael Gottesman97e3df02013-01-14 00:35:14 +0000498 /// Unidirectional information about the current sequence.
499 ///
John McCalld935e9c2011-06-15 23:37:01 +0000500 /// TODO: Encapsulate this better.
501 RRInfo RRI;
502
Dan Gohmandf476e52012-09-04 23:16:20 +0000503 PtrState() : KnownPositiveRefCount(false), Partial(false),
Dan Gohman41375a32012-05-08 23:39:44 +0000504 Seq(S_None) {}
John McCalld935e9c2011-06-15 23:37:01 +0000505
Michael Gottesman415ddd72013-02-05 19:32:18 +0000506 void SetKnownPositiveRefCount() {
Michael Gottesmanf3f9e3b2013-05-14 00:08:09 +0000507 DEBUG(dbgs() << "Setting Known Positive.\n");
Dan Gohman62079b42012-04-25 00:50:46 +0000508 KnownPositiveRefCount = true;
Dan Gohman12130272011-08-12 00:26:31 +0000509 }
510
Michael Gottesman764b1cf2013-03-23 05:46:19 +0000511 void ClearKnownPositiveRefCount() {
Michael Gottesmanf3f9e3b2013-05-14 00:08:09 +0000512 DEBUG(dbgs() << "Clearing Known Positive.\n");
Dan Gohman62079b42012-04-25 00:50:46 +0000513 KnownPositiveRefCount = false;
John McCalld935e9c2011-06-15 23:37:01 +0000514 }
515
Michael Gottesman07beea42013-03-23 05:31:01 +0000516 bool HasKnownPositiveRefCount() const {
Dan Gohman62079b42012-04-25 00:50:46 +0000517 return KnownPositiveRefCount;
John McCalld935e9c2011-06-15 23:37:01 +0000518 }
519
Michael Gottesman415ddd72013-02-05 19:32:18 +0000520 void SetSeq(Sequence NewSeq) {
Michael Gottesman89279f82013-04-05 18:10:41 +0000521 DEBUG(dbgs() << "Old: " << Seq << "; New: " << NewSeq << "\n");
Michael Gottesman79249972013-04-05 23:46:45 +0000522 Seq = NewSeq;
John McCalld935e9c2011-06-15 23:37:01 +0000523 }
524
Michael Gottesman415ddd72013-02-05 19:32:18 +0000525 Sequence GetSeq() const {
John McCalld935e9c2011-06-15 23:37:01 +0000526 return Seq;
527 }
528
Michael Gottesman415ddd72013-02-05 19:32:18 +0000529 void ClearSequenceProgress() {
Dan Gohman62079b42012-04-25 00:50:46 +0000530 ResetSequenceProgress(S_None);
531 }
532
Michael Gottesman415ddd72013-02-05 19:32:18 +0000533 void ResetSequenceProgress(Sequence NewSeq) {
Michael Gottesman01338a42013-04-20 23:36:57 +0000534 DEBUG(dbgs() << "Resetting sequence progress.\n");
Michael Gottesman89279f82013-04-05 18:10:41 +0000535 SetSeq(NewSeq);
Dan Gohman62079b42012-04-25 00:50:46 +0000536 Partial = false;
John McCalld935e9c2011-06-15 23:37:01 +0000537 RRI.clear();
538 }
539
540 void Merge(const PtrState &Other, bool TopDown);
541 };
542}
543
544void
545PtrState::Merge(const PtrState &Other, bool TopDown) {
546 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
Dan Gohman62079b42012-04-25 00:50:46 +0000547 KnownPositiveRefCount = KnownPositiveRefCount && Other.KnownPositiveRefCount;
Michael Gottesman60f6b282013-03-29 05:13:07 +0000548
Dan Gohman1736c142011-10-17 18:48:25 +0000549 // If we're not in a sequence (anymore), drop all associated state.
John McCalld935e9c2011-06-15 23:37:01 +0000550 if (Seq == S_None) {
Dan Gohman62079b42012-04-25 00:50:46 +0000551 Partial = false;
John McCalld935e9c2011-06-15 23:37:01 +0000552 RRI.clear();
Dan Gohman62079b42012-04-25 00:50:46 +0000553 } else if (Partial || Other.Partial) {
Dan Gohman1736c142011-10-17 18:48:25 +0000554 // If we're doing a merge on a path that's previously seen a partial
555 // merge, conservatively drop the sequence, to avoid doing partial
556 // RR elimination. If the branch predicates for the two merge differ,
557 // mixing them is unsafe.
Dan Gohman62079b42012-04-25 00:50:46 +0000558 ClearSequenceProgress();
John McCalld935e9c2011-06-15 23:37:01 +0000559 } else {
560 // Conservatively merge the ReleaseMetadata information.
561 if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
562 RRI.ReleaseMetadata = 0;
563
Dan Gohmanb3894012011-08-19 00:26:36 +0000564 RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
Dan Gohman41375a32012-05-08 23:39:44 +0000565 RRI.IsTailCallRelease = RRI.IsTailCallRelease &&
566 Other.RRI.IsTailCallRelease;
John McCalld935e9c2011-06-15 23:37:01 +0000567 RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
Michael Gottesmane67f40c2013-05-24 20:44:05 +0000568 RRI.CFGHazardAfflicted |= Other.RRI.CFGHazardAfflicted;
Dan Gohman1736c142011-10-17 18:48:25 +0000569
570 // Merge the insert point sets. If there are any differences,
571 // that makes this a partial merge.
Dan Gohman41375a32012-05-08 23:39:44 +0000572 Partial = RRI.ReverseInsertPts.size() != Other.RRI.ReverseInsertPts.size();
Dan Gohman1736c142011-10-17 18:48:25 +0000573 for (SmallPtrSet<Instruction *, 2>::const_iterator
574 I = Other.RRI.ReverseInsertPts.begin(),
575 E = Other.RRI.ReverseInsertPts.end(); I != E; ++I)
Dan Gohman62079b42012-04-25 00:50:46 +0000576 Partial |= RRI.ReverseInsertPts.insert(*I);
John McCalld935e9c2011-06-15 23:37:01 +0000577 }
578}
579
580namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000581 /// \brief Per-BasicBlock state.
John McCalld935e9c2011-06-15 23:37:01 +0000582 class BBState {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000583 /// The number of unique control paths from the entry which can reach this
584 /// block.
John McCalld935e9c2011-06-15 23:37:01 +0000585 unsigned TopDownPathCount;
586
Michael Gottesman97e3df02013-01-14 00:35:14 +0000587 /// The number of unique control paths to exits from this block.
John McCalld935e9c2011-06-15 23:37:01 +0000588 unsigned BottomUpPathCount;
589
Michael Gottesman97e3df02013-01-14 00:35:14 +0000590 /// A type for PerPtrTopDown and PerPtrBottomUp.
John McCalld935e9c2011-06-15 23:37:01 +0000591 typedef MapVector<const Value *, PtrState> MapTy;
592
Michael Gottesman97e3df02013-01-14 00:35:14 +0000593 /// The top-down traversal uses this to record information known about a
594 /// pointer at the bottom of each block.
John McCalld935e9c2011-06-15 23:37:01 +0000595 MapTy PerPtrTopDown;
596
Michael Gottesman97e3df02013-01-14 00:35:14 +0000597 /// The bottom-up traversal uses this to record information known about a
598 /// pointer at the top of each block.
John McCalld935e9c2011-06-15 23:37:01 +0000599 MapTy PerPtrBottomUp;
600
Michael Gottesman97e3df02013-01-14 00:35:14 +0000601 /// Effective predecessors of the current block ignoring ignorable edges and
602 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000603 SmallVector<BasicBlock *, 2> Preds;
Michael Gottesman97e3df02013-01-14 00:35:14 +0000604 /// Effective successors of the current block ignoring ignorable edges and
605 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000606 SmallVector<BasicBlock *, 2> Succs;
607
John McCalld935e9c2011-06-15 23:37:01 +0000608 public:
609 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
610
611 typedef MapTy::iterator ptr_iterator;
612 typedef MapTy::const_iterator ptr_const_iterator;
613
614 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
615 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
616 ptr_const_iterator top_down_ptr_begin() const {
617 return PerPtrTopDown.begin();
618 }
619 ptr_const_iterator top_down_ptr_end() const {
620 return PerPtrTopDown.end();
621 }
622
623 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
624 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
625 ptr_const_iterator bottom_up_ptr_begin() const {
626 return PerPtrBottomUp.begin();
627 }
628 ptr_const_iterator bottom_up_ptr_end() const {
629 return PerPtrBottomUp.end();
630 }
631
Michael Gottesman97e3df02013-01-14 00:35:14 +0000632 /// Mark this block as being an entry block, which has one path from the
633 /// entry by definition.
John McCalld935e9c2011-06-15 23:37:01 +0000634 void SetAsEntry() { TopDownPathCount = 1; }
635
Michael Gottesman97e3df02013-01-14 00:35:14 +0000636 /// Mark this block as being an exit block, which has one path to an exit by
637 /// definition.
John McCalld935e9c2011-06-15 23:37:01 +0000638 void SetAsExit() { BottomUpPathCount = 1; }
639
Michael Gottesman993fbf72013-05-13 19:40:39 +0000640 /// Attempt to find the PtrState object describing the top down state for
641 /// pointer Arg. Return a new initialized PtrState describing the top down
642 /// state for Arg if we do not find one.
John McCalld935e9c2011-06-15 23:37:01 +0000643 PtrState &getPtrTopDownState(const Value *Arg) {
644 return PerPtrTopDown[Arg];
645 }
646
Michael Gottesman993fbf72013-05-13 19:40:39 +0000647 /// Attempt to find the PtrState object describing the bottom up state for
648 /// pointer Arg. Return a new initialized PtrState describing the bottom up
649 /// state for Arg if we do not find one.
John McCalld935e9c2011-06-15 23:37:01 +0000650 PtrState &getPtrBottomUpState(const Value *Arg) {
651 return PerPtrBottomUp[Arg];
652 }
653
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000654 /// Attempt to find the PtrState object describing the bottom up state for
655 /// pointer Arg.
656 ptr_iterator findPtrBottomUpState(const Value *Arg) {
657 return PerPtrBottomUp.find(Arg);
658 }
659
John McCalld935e9c2011-06-15 23:37:01 +0000660 void clearBottomUpPointers() {
Evan Chenge4df6a22011-08-04 18:40:26 +0000661 PerPtrBottomUp.clear();
John McCalld935e9c2011-06-15 23:37:01 +0000662 }
663
664 void clearTopDownPointers() {
665 PerPtrTopDown.clear();
666 }
667
668 void InitFromPred(const BBState &Other);
669 void InitFromSucc(const BBState &Other);
670 void MergePred(const BBState &Other);
671 void MergeSucc(const BBState &Other);
672
Michael Gottesman9e7261c2013-06-07 06:16:49 +0000673 /// Compute the number of possible unique paths from an entry to an exit
Michael Gottesman97e3df02013-01-14 00:35:14 +0000674 /// which pass through this block. This is only valid after both the
675 /// top-down and bottom-up traversals are complete.
Michael Gottesman9e7261c2013-06-07 06:16:49 +0000676 ///
677 /// Returns true if overflow occured. Returns false if overflow did not
678 /// occur.
679 bool GetAllPathCountWithOverflow(unsigned &PathCount) const {
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000680 assert(TopDownPathCount != 0);
681 assert(BottomUpPathCount != 0);
Michael Gottesman9e7261c2013-06-07 06:16:49 +0000682 unsigned long long Product =
683 (unsigned long long)TopDownPathCount*BottomUpPathCount;
684 PathCount = Product;
685 // Overflow occured if any of the upper bits of Product are set.
686 return Product >> 32;
John McCalld935e9c2011-06-15 23:37:01 +0000687 }
Dan Gohman12130272011-08-12 00:26:31 +0000688
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000689 // Specialized CFG utilities.
Dan Gohmandae33492012-04-27 18:56:31 +0000690 typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000691 edge_iterator pred_begin() { return Preds.begin(); }
692 edge_iterator pred_end() { return Preds.end(); }
693 edge_iterator succ_begin() { return Succs.begin(); }
694 edge_iterator succ_end() { return Succs.end(); }
695
696 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
697 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
698
699 bool isExit() const { return Succs.empty(); }
John McCalld935e9c2011-06-15 23:37:01 +0000700 };
701}
702
703void BBState::InitFromPred(const BBState &Other) {
704 PerPtrTopDown = Other.PerPtrTopDown;
705 TopDownPathCount = Other.TopDownPathCount;
706}
707
708void BBState::InitFromSucc(const BBState &Other) {
709 PerPtrBottomUp = Other.PerPtrBottomUp;
710 BottomUpPathCount = Other.BottomUpPathCount;
711}
712
Michael Gottesman97e3df02013-01-14 00:35:14 +0000713/// The top-down traversal uses this to merge information about predecessors to
714/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +0000715void BBState::MergePred(const BBState &Other) {
716 // Other.TopDownPathCount can be 0, in which case it is either dead or a
717 // loop backedge. Loop backedges are special.
718 TopDownPathCount += Other.TopDownPathCount;
719
Michael Gottesman4385edf2013-01-14 01:47:53 +0000720 // Check for overflow. If we have overflow, fall back to conservative
721 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +0000722 if (TopDownPathCount < Other.TopDownPathCount) {
723 clearTopDownPointers();
724 return;
725 }
726
John McCalld935e9c2011-06-15 23:37:01 +0000727 // For each entry in the other set, if our set has an entry with the same key,
728 // merge the entries. Otherwise, copy the entry and merge it with an empty
729 // entry.
730 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
731 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
732 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
733 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
734 /*TopDown=*/true);
735 }
736
Dan Gohman7e315fc32011-08-11 21:06:32 +0000737 // For each entry in our set, if the other set doesn't have an entry with the
John McCalld935e9c2011-06-15 23:37:01 +0000738 // same key, force it to merge with an empty entry.
739 for (ptr_iterator MI = top_down_ptr_begin(),
740 ME = top_down_ptr_end(); MI != ME; ++MI)
741 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
742 MI->second.Merge(PtrState(), /*TopDown=*/true);
743}
744
Michael Gottesman97e3df02013-01-14 00:35:14 +0000745/// The bottom-up traversal uses this to merge information about successors to
746/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +0000747void BBState::MergeSucc(const BBState &Other) {
748 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
749 // loop backedge. Loop backedges are special.
750 BottomUpPathCount += Other.BottomUpPathCount;
751
Michael Gottesman4385edf2013-01-14 01:47:53 +0000752 // Check for overflow. If we have overflow, fall back to conservative
753 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +0000754 if (BottomUpPathCount < Other.BottomUpPathCount) {
755 clearBottomUpPointers();
756 return;
757 }
758
John McCalld935e9c2011-06-15 23:37:01 +0000759 // For each entry in the other set, if our set has an entry with the
760 // same key, merge the entries. Otherwise, copy the entry and merge
761 // it with an empty entry.
762 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
763 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
764 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
765 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
766 /*TopDown=*/false);
767 }
768
Dan Gohman7e315fc32011-08-11 21:06:32 +0000769 // For each entry in our set, if the other set doesn't have an entry
John McCalld935e9c2011-06-15 23:37:01 +0000770 // with the same key, force it to merge with an empty entry.
771 for (ptr_iterator MI = bottom_up_ptr_begin(),
772 ME = bottom_up_ptr_end(); MI != ME; ++MI)
773 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
774 MI->second.Merge(PtrState(), /*TopDown=*/false);
775}
776
Michael Gottesman81b1d432013-03-26 00:42:04 +0000777// Only enable ARC Annotations if we are building a debug version of
778// libObjCARCOpts.
779#ifndef NDEBUG
780#define ARC_ANNOTATIONS
781#endif
782
783// Define some macros along the lines of DEBUG and some helper functions to make
784// it cleaner to create annotations in the source code and to no-op when not
785// building in debug mode.
786#ifdef ARC_ANNOTATIONS
787
788#include "llvm/Support/CommandLine.h"
789
790/// Enable/disable ARC sequence annotations.
791static cl::opt<bool>
Michael Gottesman6806b512013-04-17 20:48:03 +0000792EnableARCAnnotations("enable-objc-arc-annotations", cl::init(false),
793 cl::desc("Enable emission of arc data flow analysis "
794 "annotations"));
Michael Gottesmanffef24f2013-04-17 20:48:01 +0000795static cl::opt<bool>
Michael Gottesmanadb921a2013-04-17 21:03:53 +0000796DisableCheckForCFGHazards("disable-objc-arc-checkforcfghazards", cl::init(false),
797 cl::desc("Disable check for cfg hazards when "
798 "annotating"));
Michael Gottesman4e88ce62013-04-17 21:59:41 +0000799static cl::opt<std::string>
800ARCAnnotationTargetIdentifier("objc-arc-annotation-target-identifier",
801 cl::init(""),
802 cl::desc("filter out all data flow annotations "
803 "but those that apply to the given "
804 "target llvm identifier."));
Michael Gottesman81b1d432013-03-26 00:42:04 +0000805
806/// This function appends a unique ARCAnnotationProvenanceSourceMDKind id to an
807/// instruction so that we can track backwards when post processing via the llvm
808/// arc annotation processor tool. If the function is an
809static MDString *AppendMDNodeToSourcePtr(unsigned NodeId,
810 Value *Ptr) {
811 MDString *Hash = 0;
812
813 // If pointer is a result of an instruction and it does not have a source
814 // MDNode it, attach a new MDNode onto it. If pointer is a result of
815 // an instruction and does have a source MDNode attached to it, return a
816 // reference to said Node. Otherwise just return 0.
817 if (Instruction *Inst = dyn_cast<Instruction>(Ptr)) {
818 MDNode *Node;
819 if (!(Node = Inst->getMetadata(NodeId))) {
820 // We do not have any node. Generate and attatch the hash MDString to the
821 // instruction.
822
823 // We just use an MDString to ensure that this metadata gets written out
824 // of line at the module level and to provide a very simple format
825 // encoding the information herein. Both of these makes it simpler to
826 // parse the annotations by a simple external program.
827 std::string Str;
828 raw_string_ostream os(Str);
829 os << "(" << Inst->getParent()->getParent()->getName() << ",%"
830 << Inst->getName() << ")";
831
832 Hash = MDString::get(Inst->getContext(), os.str());
833 Inst->setMetadata(NodeId, MDNode::get(Inst->getContext(),Hash));
834 } else {
835 // We have a node. Grab its hash and return it.
836 assert(Node->getNumOperands() == 1 &&
837 "An ARCAnnotationProvenanceSourceMDKind can only have 1 operand.");
838 Hash = cast<MDString>(Node->getOperand(0));
839 }
840 } else if (Argument *Arg = dyn_cast<Argument>(Ptr)) {
841 std::string str;
842 raw_string_ostream os(str);
843 os << "(" << Arg->getParent()->getName() << ",%" << Arg->getName()
844 << ")";
845 Hash = MDString::get(Arg->getContext(), os.str());
846 }
847
848 return Hash;
849}
850
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000851static std::string SequenceToString(Sequence A) {
852 std::string str;
853 raw_string_ostream os(str);
854 os << A;
855 return os.str();
856}
857
Michael Gottesman81b1d432013-03-26 00:42:04 +0000858/// Helper function to change a Sequence into a String object using our overload
859/// for raw_ostream so we only have printing code in one location.
860static MDString *SequenceToMDString(LLVMContext &Context,
861 Sequence A) {
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000862 return MDString::get(Context, SequenceToString(A));
Michael Gottesman81b1d432013-03-26 00:42:04 +0000863}
864
865/// A simple function to generate a MDNode which describes the change in state
866/// for Value *Ptr caused by Instruction *Inst.
867static void AppendMDNodeToInstForPtr(unsigned NodeId,
868 Instruction *Inst,
869 Value *Ptr,
870 MDString *PtrSourceMDNodeID,
871 Sequence OldSeq,
872 Sequence NewSeq) {
873 MDNode *Node = 0;
874 Value *tmp[3] = {PtrSourceMDNodeID,
875 SequenceToMDString(Inst->getContext(),
876 OldSeq),
877 SequenceToMDString(Inst->getContext(),
878 NewSeq)};
879 Node = MDNode::get(Inst->getContext(),
880 ArrayRef<Value*>(tmp, 3));
881
882 Inst->setMetadata(NodeId, Node);
883}
884
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000885/// Add to the beginning of the basic block llvm.ptr.annotations which show the
886/// state of a pointer at the entrance to a basic block.
887static void GenerateARCBBEntranceAnnotation(const char *Name, BasicBlock *BB,
888 Value *Ptr, Sequence Seq) {
Michael Gottesman4e88ce62013-04-17 21:59:41 +0000889 // If we have a target identifier, make sure that we match it before
890 // continuing.
891 if(!ARCAnnotationTargetIdentifier.empty() &&
892 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
893 return;
Michael Gottesman9e518132013-04-18 04:34:11 +0000894
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000895 Module *M = BB->getParent()->getParent();
896 LLVMContext &C = M->getContext();
897 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
898 Type *I8XX = PointerType::getUnqual(I8X);
899 Type *Params[] = {I8XX, I8XX};
900 FunctionType *FTy = FunctionType::get(Type::getVoidTy(C),
901 ArrayRef<Type*>(Params, 2),
902 /*isVarArg=*/false);
903 Constant *Callee = M->getOrInsertFunction(Name, FTy);
Michael Gottesman60f6b282013-03-29 05:13:07 +0000904
905 IRBuilder<> Builder(BB, BB->getFirstInsertionPt());
906
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000907 Value *PtrName;
908 StringRef Tmp = Ptr->getName();
909 if (0 == (PtrName = M->getGlobalVariable(Tmp, true))) {
910 Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
911 Tmp + "_STR");
912 PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
Michael Gottesman60f6b282013-03-29 05:13:07 +0000913 cast<Constant>(ActualPtrName), Tmp);
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000914 }
915
916 Value *S;
917 std::string SeqStr = SequenceToString(Seq);
918 if (0 == (S = M->getGlobalVariable(SeqStr, true))) {
919 Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
920 SeqStr + "_STR");
921 S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
922 cast<Constant>(ActualPtrName), SeqStr);
923 }
924
925 Builder.CreateCall2(Callee, PtrName, S);
926}
927
928/// Add to the end of the basic block llvm.ptr.annotations which show the state
929/// of the pointer at the bottom of the basic block.
930static void GenerateARCBBTerminatorAnnotation(const char *Name, BasicBlock *BB,
931 Value *Ptr, Sequence Seq) {
Michael Gottesman4e88ce62013-04-17 21:59:41 +0000932 // If we have a target identifier, make sure that we match it before emitting
933 // an annotation.
934 if(!ARCAnnotationTargetIdentifier.empty() &&
935 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
936 return;
Michael Gottesman9e518132013-04-18 04:34:11 +0000937
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000938 Module *M = BB->getParent()->getParent();
939 LLVMContext &C = M->getContext();
940 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
941 Type *I8XX = PointerType::getUnqual(I8X);
942 Type *Params[] = {I8XX, I8XX};
943 FunctionType *FTy = FunctionType::get(Type::getVoidTy(C),
944 ArrayRef<Type*>(Params, 2),
945 /*isVarArg=*/false);
946 Constant *Callee = M->getOrInsertFunction(Name, FTy);
Michael Gottesman60f6b282013-03-29 05:13:07 +0000947
948 IRBuilder<> Builder(BB, llvm::prior(BB->end()));
949
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000950 Value *PtrName;
951 StringRef Tmp = Ptr->getName();
952 if (0 == (PtrName = M->getGlobalVariable(Tmp, true))) {
953 Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
954 Tmp + "_STR");
955 PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
Michael Gottesman60f6b282013-03-29 05:13:07 +0000956 cast<Constant>(ActualPtrName), Tmp);
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000957 }
958
959 Value *S;
960 std::string SeqStr = SequenceToString(Seq);
961 if (0 == (S = M->getGlobalVariable(SeqStr, true))) {
962 Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
963 SeqStr + "_STR");
964 S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
965 cast<Constant>(ActualPtrName), SeqStr);
966 }
Michael Gottesman60f6b282013-03-29 05:13:07 +0000967 Builder.CreateCall2(Callee, PtrName, S);
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000968}
969
Michael Gottesman81b1d432013-03-26 00:42:04 +0000970/// Adds a source annotation to pointer and a state change annotation to Inst
971/// referencing the source annotation and the old/new state of pointer.
972static void GenerateARCAnnotation(unsigned InstMDId,
973 unsigned PtrMDId,
974 Instruction *Inst,
975 Value *Ptr,
976 Sequence OldSeq,
977 Sequence NewSeq) {
978 if (EnableARCAnnotations) {
Michael Gottesman4e88ce62013-04-17 21:59:41 +0000979 // If we have a target identifier, make sure that we match it before
980 // emitting an annotation.
981 if(!ARCAnnotationTargetIdentifier.empty() &&
982 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
983 return;
Michael Gottesman9e518132013-04-18 04:34:11 +0000984
Michael Gottesman81b1d432013-03-26 00:42:04 +0000985 // First generate the source annotation on our pointer. This will return an
986 // MDString* if Ptr actually comes from an instruction implying we can put
987 // in a source annotation. If AppendMDNodeToSourcePtr returns 0 (i.e. NULL),
988 // then we know that our pointer is from an Argument so we put a reference
989 // to the argument number.
990 //
991 // The point of this is to make it easy for the
992 // llvm-arc-annotation-processor tool to cross reference where the source
993 // pointer is in the LLVM IR since the LLVM IR parser does not submit such
994 // information via debug info for backends to use (since why would anyone
995 // need such a thing from LLVM IR besides in non standard cases
996 // [i.e. this]).
997 MDString *SourcePtrMDNode =
998 AppendMDNodeToSourcePtr(PtrMDId, Ptr);
999 AppendMDNodeToInstForPtr(InstMDId, Inst, Ptr, SourcePtrMDNode, OldSeq,
1000 NewSeq);
1001 }
1002}
1003
1004// The actual interface for accessing the above functionality is defined via
1005// some simple macros which are defined below. We do this so that the user does
1006// not need to pass in what metadata id is needed resulting in cleaner code and
1007// additionally since it provides an easy way to conditionally no-op all
1008// annotation support in a non-debug build.
1009
1010/// Use this macro to annotate a sequence state change when processing
1011/// instructions bottom up,
1012#define ANNOTATE_BOTTOMUP(inst, ptr, old, new) \
1013 GenerateARCAnnotation(ARCAnnotationBottomUpMDKind, \
1014 ARCAnnotationProvenanceSourceMDKind, (inst), \
1015 const_cast<Value*>(ptr), (old), (new))
1016/// Use this macro to annotate a sequence state change when processing
1017/// instructions top down.
1018#define ANNOTATE_TOPDOWN(inst, ptr, old, new) \
1019 GenerateARCAnnotation(ARCAnnotationTopDownMDKind, \
1020 ARCAnnotationProvenanceSourceMDKind, (inst), \
1021 const_cast<Value*>(ptr), (old), (new))
1022
Michael Gottesman43e7e002013-04-03 22:41:59 +00001023#define ANNOTATE_BB(_states, _bb, _name, _type, _direction) \
1024 do { \
Michael Gottesman89279f82013-04-05 18:10:41 +00001025 if (EnableARCAnnotations) { \
1026 for(BBState::ptr_const_iterator I = (_states)._direction##_ptr_begin(), \
Michael Gottesman43e7e002013-04-03 22:41:59 +00001027 E = (_states)._direction##_ptr_end(); I != E; ++I) { \
Michael Gottesman89279f82013-04-05 18:10:41 +00001028 Value *Ptr = const_cast<Value*>(I->first); \
1029 Sequence Seq = I->second.GetSeq(); \
1030 GenerateARCBB ## _type ## Annotation(_name, (_bb), Ptr, Seq); \
1031 } \
Michael Gottesman43e7e002013-04-03 22:41:59 +00001032 } \
Michael Gottesman89279f82013-04-05 18:10:41 +00001033 } while (0)
Michael Gottesman43e7e002013-04-03 22:41:59 +00001034
Michael Gottesman89279f82013-04-05 18:10:41 +00001035#define ANNOTATE_BOTTOMUP_BBSTART(_states, _basicblock) \
Michael Gottesman43e7e002013-04-03 22:41:59 +00001036 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbstart", \
1037 Entrance, bottom_up)
Michael Gottesman89279f82013-04-05 18:10:41 +00001038#define ANNOTATE_BOTTOMUP_BBEND(_states, _basicblock) \
1039 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbend", \
Michael Gottesman43e7e002013-04-03 22:41:59 +00001040 Terminator, bottom_up)
Michael Gottesman89279f82013-04-05 18:10:41 +00001041#define ANNOTATE_TOPDOWN_BBSTART(_states, _basicblock) \
1042 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbstart", \
Michael Gottesman43e7e002013-04-03 22:41:59 +00001043 Entrance, top_down)
Michael Gottesman89279f82013-04-05 18:10:41 +00001044#define ANNOTATE_TOPDOWN_BBEND(_states, _basicblock) \
1045 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbend", \
Michael Gottesman43e7e002013-04-03 22:41:59 +00001046 Terminator, top_down)
1047
Michael Gottesman81b1d432013-03-26 00:42:04 +00001048#else // !ARC_ANNOTATION
1049// If annotations are off, noop.
1050#define ANNOTATE_BOTTOMUP(inst, ptr, old, new)
1051#define ANNOTATE_TOPDOWN(inst, ptr, old, new)
Michael Gottesman43e7e002013-04-03 22:41:59 +00001052#define ANNOTATE_BOTTOMUP_BBSTART(states, basicblock)
1053#define ANNOTATE_BOTTOMUP_BBEND(states, basicblock)
1054#define ANNOTATE_TOPDOWN_BBSTART(states, basicblock)
1055#define ANNOTATE_TOPDOWN_BBEND(states, basicblock)
Michael Gottesman81b1d432013-03-26 00:42:04 +00001056#endif // !ARC_ANNOTATION
1057
John McCalld935e9c2011-06-15 23:37:01 +00001058namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001059 /// \brief The main ARC optimization pass.
John McCalld935e9c2011-06-15 23:37:01 +00001060 class ObjCARCOpt : public FunctionPass {
1061 bool Changed;
1062 ProvenanceAnalysis PA;
1063
Michael Gottesman5a91bbf2013-05-24 20:44:02 +00001064 // This is used to track if a pointer is stored into an alloca.
1065 DenseSet<const Value *> MultiOwnersSet;
1066
Michael Gottesman97e3df02013-01-14 00:35:14 +00001067 /// A flag indicating whether this optimization pass should run.
Dan Gohmanceaac7c2011-06-20 23:20:43 +00001068 bool Run;
1069
Michael Gottesman97e3df02013-01-14 00:35:14 +00001070 /// Declarations for ObjC runtime functions, for use in creating calls to
1071 /// them. These are initialized lazily to avoid cluttering up the Module
1072 /// with unused declarations.
John McCalld935e9c2011-06-15 23:37:01 +00001073
Michael Gottesman97e3df02013-01-14 00:35:14 +00001074 /// Declaration for ObjC runtime function objc_autoreleaseReturnValue.
1075 Constant *AutoreleaseRVCallee;
1076 /// Declaration for ObjC runtime function objc_release.
1077 Constant *ReleaseCallee;
1078 /// Declaration for ObjC runtime function objc_retain.
1079 Constant *RetainCallee;
1080 /// Declaration for ObjC runtime function objc_retainBlock.
1081 Constant *RetainBlockCallee;
1082 /// Declaration for ObjC runtime function objc_autorelease.
1083 Constant *AutoreleaseCallee;
1084
1085 /// Flags which determine whether each of the interesting runtine functions
1086 /// is in fact used in the current function.
John McCalld935e9c2011-06-15 23:37:01 +00001087 unsigned UsedInThisFunction;
1088
Michael Gottesman97e3df02013-01-14 00:35:14 +00001089 /// The Metadata Kind for clang.imprecise_release metadata.
John McCalld935e9c2011-06-15 23:37:01 +00001090 unsigned ImpreciseReleaseMDKind;
1091
Michael Gottesman97e3df02013-01-14 00:35:14 +00001092 /// The Metadata Kind for clang.arc.copy_on_escape metadata.
Dan Gohmana7107f92011-10-17 22:53:25 +00001093 unsigned CopyOnEscapeMDKind;
1094
Michael Gottesman97e3df02013-01-14 00:35:14 +00001095 /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata.
Dan Gohman0155f302012-02-17 18:59:53 +00001096 unsigned NoObjCARCExceptionsMDKind;
1097
Michael Gottesman81b1d432013-03-26 00:42:04 +00001098#ifdef ARC_ANNOTATIONS
1099 /// The Metadata Kind for llvm.arc.annotation.bottomup metadata.
1100 unsigned ARCAnnotationBottomUpMDKind;
1101 /// The Metadata Kind for llvm.arc.annotation.topdown metadata.
1102 unsigned ARCAnnotationTopDownMDKind;
1103 /// The Metadata Kind for llvm.arc.annotation.provenancesource metadata.
1104 unsigned ARCAnnotationProvenanceSourceMDKind;
1105#endif // ARC_ANNOATIONS
1106
John McCalld935e9c2011-06-15 23:37:01 +00001107 Constant *getAutoreleaseRVCallee(Module *M);
1108 Constant *getReleaseCallee(Module *M);
1109 Constant *getRetainCallee(Module *M);
Dan Gohman6320f522011-07-22 22:29:21 +00001110 Constant *getRetainBlockCallee(Module *M);
John McCalld935e9c2011-06-15 23:37:01 +00001111 Constant *getAutoreleaseCallee(Module *M);
1112
Dan Gohman728db492012-01-13 00:39:07 +00001113 bool IsRetainBlockOptimizable(const Instruction *Inst);
1114
John McCalld935e9c2011-06-15 23:37:01 +00001115 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
Michael Gottesman556ff612013-01-12 01:25:19 +00001116 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1117 InstructionClass &Class);
Michael Gottesman158fdf62013-03-28 20:11:19 +00001118 bool OptimizeRetainBlockCall(Function &F, Instruction *RetainBlock,
1119 InstructionClass &Class);
John McCalld935e9c2011-06-15 23:37:01 +00001120 void OptimizeIndividualCalls(Function &F);
1121
1122 void CheckForCFGHazards(const BasicBlock *BB,
1123 DenseMap<const BasicBlock *, BBState> &BBStates,
1124 BBState &MyStates) const;
Dan Gohman817a7c62012-03-22 18:24:56 +00001125 bool VisitInstructionBottomUp(Instruction *Inst,
Dan Gohman5c70fad2012-03-23 17:47:54 +00001126 BasicBlock *BB,
Dan Gohman817a7c62012-03-22 18:24:56 +00001127 MapVector<Value *, RRInfo> &Retains,
1128 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00001129 bool VisitBottomUp(BasicBlock *BB,
1130 DenseMap<const BasicBlock *, BBState> &BBStates,
1131 MapVector<Value *, RRInfo> &Retains);
Dan Gohman817a7c62012-03-22 18:24:56 +00001132 bool VisitInstructionTopDown(Instruction *Inst,
1133 DenseMap<Value *, RRInfo> &Releases,
1134 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00001135 bool VisitTopDown(BasicBlock *BB,
1136 DenseMap<const BasicBlock *, BBState> &BBStates,
1137 DenseMap<Value *, RRInfo> &Releases);
1138 bool Visit(Function &F,
1139 DenseMap<const BasicBlock *, BBState> &BBStates,
1140 MapVector<Value *, RRInfo> &Retains,
1141 DenseMap<Value *, RRInfo> &Releases);
1142
1143 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1144 MapVector<Value *, RRInfo> &Retains,
1145 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman6320f522011-07-22 22:29:21 +00001146 SmallVectorImpl<Instruction *> &DeadInsts,
1147 Module *M);
John McCalld935e9c2011-06-15 23:37:01 +00001148
Michael Gottesman9de6f962013-01-22 21:49:00 +00001149 bool ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState> &BBStates,
1150 MapVector<Value *, RRInfo> &Retains,
1151 DenseMap<Value *, RRInfo> &Releases,
1152 Module *M,
1153 SmallVector<Instruction *, 4> &NewRetains,
1154 SmallVector<Instruction *, 4> &NewReleases,
1155 SmallVector<Instruction *, 8> &DeadInsts,
1156 RRInfo &RetainsToMove,
1157 RRInfo &ReleasesToMove,
1158 Value *Arg,
1159 bool KnownSafe,
1160 bool &AnyPairsCompletelyEliminated);
1161
John McCalld935e9c2011-06-15 23:37:01 +00001162 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1163 MapVector<Value *, RRInfo> &Retains,
Dan Gohman6320f522011-07-22 22:29:21 +00001164 DenseMap<Value *, RRInfo> &Releases,
1165 Module *M);
John McCalld935e9c2011-06-15 23:37:01 +00001166
1167 void OptimizeWeakCalls(Function &F);
1168
1169 bool OptimizeSequences(Function &F);
1170
1171 void OptimizeReturns(Function &F);
1172
Michael Gottesman9c118152013-04-29 06:16:57 +00001173#ifndef NDEBUG
1174 void GatherStatistics(Function &F, bool AfterOptimization = false);
1175#endif
1176
John McCalld935e9c2011-06-15 23:37:01 +00001177 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1178 virtual bool doInitialization(Module &M);
1179 virtual bool runOnFunction(Function &F);
1180 virtual void releaseMemory();
1181
1182 public:
1183 static char ID;
1184 ObjCARCOpt() : FunctionPass(ID) {
1185 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1186 }
1187 };
1188}
1189
1190char ObjCARCOpt::ID = 0;
1191INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1192 "objc-arc", "ObjC ARC optimization", false, false)
1193INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1194INITIALIZE_PASS_END(ObjCARCOpt,
1195 "objc-arc", "ObjC ARC optimization", false, false)
1196
1197Pass *llvm::createObjCARCOptPass() {
1198 return new ObjCARCOpt();
1199}
1200
1201void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1202 AU.addRequired<ObjCARCAliasAnalysis>();
1203 AU.addRequired<AliasAnalysis>();
1204 // ARC optimization doesn't currently split critical edges.
1205 AU.setPreservesCFG();
1206}
1207
Dan Gohman728db492012-01-13 00:39:07 +00001208bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1209 // Without the magic metadata tag, we have to assume this might be an
1210 // objc_retainBlock call inserted to convert a block pointer to an id,
1211 // in which case it really is needed.
1212 if (!Inst->getMetadata(CopyOnEscapeMDKind))
1213 return false;
1214
1215 // If the pointer "escapes" (not including being used in a call),
1216 // the copy may be needed.
Michael Gottesman774d2c02013-01-29 21:00:52 +00001217 if (DoesRetainableObjPtrEscape(Inst))
Dan Gohman728db492012-01-13 00:39:07 +00001218 return false;
1219
1220 // Otherwise, it's not needed.
1221 return true;
1222}
1223
John McCalld935e9c2011-06-15 23:37:01 +00001224Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1225 if (!AutoreleaseRVCallee) {
1226 LLVMContext &C = M->getContext();
Jay Foadb804a2b2011-07-12 14:06:48 +00001227 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman41375a32012-05-08 23:39:44 +00001228 Type *Params[] = { I8X };
1229 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001230 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001231 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1232 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001233 AutoreleaseRVCallee =
1234 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001235 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001236 }
1237 return AutoreleaseRVCallee;
1238}
1239
1240Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1241 if (!ReleaseCallee) {
1242 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001243 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001244 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001245 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1246 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001247 ReleaseCallee =
1248 M->getOrInsertFunction(
1249 "objc_release",
1250 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001251 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001252 }
1253 return ReleaseCallee;
1254}
1255
1256Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1257 if (!RetainCallee) {
1258 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001259 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001260 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001261 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1262 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001263 RetainCallee =
1264 M->getOrInsertFunction(
1265 "objc_retain",
1266 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001267 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001268 }
1269 return RetainCallee;
1270}
1271
Dan Gohman6320f522011-07-22 22:29:21 +00001272Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1273 if (!RetainBlockCallee) {
1274 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001275 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Dan Gohmanfca43c22011-09-14 18:33:34 +00001276 // objc_retainBlock is not nounwind because it calls user copy constructors
1277 // which could theoretically throw.
Dan Gohman6320f522011-07-22 22:29:21 +00001278 RetainBlockCallee =
1279 M->getOrInsertFunction(
1280 "objc_retainBlock",
1281 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendlinge94d8432012-12-07 23:16:57 +00001282 AttributeSet());
Dan Gohman6320f522011-07-22 22:29:21 +00001283 }
1284 return RetainBlockCallee;
1285}
1286
John McCalld935e9c2011-06-15 23:37:01 +00001287Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1288 if (!AutoreleaseCallee) {
1289 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001290 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001291 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001292 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1293 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001294 AutoreleaseCallee =
1295 M->getOrInsertFunction(
1296 "objc_autorelease",
1297 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001298 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001299 }
1300 return AutoreleaseCallee;
1301}
1302
Michael Gottesman97e3df02013-01-14 00:35:14 +00001303/// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is
1304/// not a return value. Or, if it can be paired with an
1305/// objc_autoreleaseReturnValue, delete the pair and return true.
John McCalld935e9c2011-06-15 23:37:01 +00001306bool
1307ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001308 // Check for the argument being from an immediately preceding call or invoke.
Dan Gohmandae33492012-04-27 18:56:31 +00001309 const Value *Arg = GetObjCArg(RetainRV);
1310 ImmutableCallSite CS(Arg);
1311 if (const Instruction *Call = CS.getInstruction()) {
John McCalld935e9c2011-06-15 23:37:01 +00001312 if (Call->getParent() == RetainRV->getParent()) {
Dan Gohmandae33492012-04-27 18:56:31 +00001313 BasicBlock::const_iterator I = Call;
John McCalld935e9c2011-06-15 23:37:01 +00001314 ++I;
Michael Gottesman65c24812013-03-25 09:27:43 +00001315 while (IsNoopInstruction(I)) ++I;
John McCalld935e9c2011-06-15 23:37:01 +00001316 if (&*I == RetainRV)
1317 return false;
Dan Gohmandae33492012-04-27 18:56:31 +00001318 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001319 BasicBlock *RetainRVParent = RetainRV->getParent();
1320 if (II->getNormalDest() == RetainRVParent) {
Dan Gohmandae33492012-04-27 18:56:31 +00001321 BasicBlock::const_iterator I = RetainRVParent->begin();
Michael Gottesman65c24812013-03-25 09:27:43 +00001322 while (IsNoopInstruction(I)) ++I;
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001323 if (&*I == RetainRV)
1324 return false;
1325 }
John McCalld935e9c2011-06-15 23:37:01 +00001326 }
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001327 }
John McCalld935e9c2011-06-15 23:37:01 +00001328
1329 // Check for being preceded by an objc_autoreleaseReturnValue on the same
1330 // pointer. In this case, we can delete the pair.
1331 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
1332 if (I != Begin) {
Michael Gottesman65c24812013-03-25 09:27:43 +00001333 do --I; while (I != Begin && IsNoopInstruction(I));
John McCalld935e9c2011-06-15 23:37:01 +00001334 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
1335 GetObjCArg(I) == Arg) {
1336 Changed = true;
1337 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00001338
Michael Gottesman89279f82013-04-05 18:10:41 +00001339 DEBUG(dbgs() << "Erasing autoreleaseRV,retainRV pair: " << *I << "\n"
1340 << "Erasing " << *RetainRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001341
John McCalld935e9c2011-06-15 23:37:01 +00001342 EraseInstruction(I);
1343 EraseInstruction(RetainRV);
1344 return true;
1345 }
1346 }
1347
1348 // Turn it to a plain objc_retain.
1349 Changed = true;
1350 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00001351
Michael Gottesman89279f82013-04-05 18:10:41 +00001352 DEBUG(dbgs() << "Transforming objc_retainAutoreleasedReturnValue => "
Michael Gottesmandef07bb2013-01-05 17:55:42 +00001353 "objc_retain since the operand is not a return value.\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00001354 "Old = " << *RetainRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001355
John McCalld935e9c2011-06-15 23:37:01 +00001356 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
Michael Gottesmandef07bb2013-01-05 17:55:42 +00001357
Michael Gottesman89279f82013-04-05 18:10:41 +00001358 DEBUG(dbgs() << "New = " << *RetainRV << "\n");
Michael Gottesmandef07bb2013-01-05 17:55:42 +00001359
John McCalld935e9c2011-06-15 23:37:01 +00001360 return false;
1361}
1362
Michael Gottesman97e3df02013-01-14 00:35:14 +00001363/// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not
1364/// used as a return value.
John McCalld935e9c2011-06-15 23:37:01 +00001365void
Michael Gottesman556ff612013-01-12 01:25:19 +00001366ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1367 InstructionClass &Class) {
John McCalld935e9c2011-06-15 23:37:01 +00001368 // Check for a return of the pointer value.
1369 const Value *Ptr = GetObjCArg(AutoreleaseRV);
Dan Gohman10a18d52011-08-12 00:36:31 +00001370 SmallVector<const Value *, 2> Users;
1371 Users.push_back(Ptr);
1372 do {
1373 Ptr = Users.pop_back_val();
1374 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
1375 UI != UE; ++UI) {
1376 const User *I = *UI;
1377 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
1378 return;
1379 if (isa<BitCastInst>(I))
1380 Users.push_back(I);
1381 }
1382 } while (!Users.empty());
John McCalld935e9c2011-06-15 23:37:01 +00001383
1384 Changed = true;
1385 ++NumPeeps;
Michael Gottesman1bf69082013-01-06 21:07:11 +00001386
Michael Gottesman89279f82013-04-05 18:10:41 +00001387 DEBUG(dbgs() << "Transforming objc_autoreleaseReturnValue => "
Michael Gottesman1bf69082013-01-06 21:07:11 +00001388 "objc_autorelease since its operand is not used as a return "
1389 "value.\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00001390 "Old = " << *AutoreleaseRV << "\n");
Michael Gottesman1bf69082013-01-06 21:07:11 +00001391
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001392 CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
1393 AutoreleaseRVCI->
John McCalld935e9c2011-06-15 23:37:01 +00001394 setCalledFunction(getAutoreleaseCallee(F.getParent()));
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001395 AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
Michael Gottesman556ff612013-01-12 01:25:19 +00001396 Class = IC_Autorelease;
Michael Gottesman10426b52013-01-07 21:26:07 +00001397
Michael Gottesman89279f82013-04-05 18:10:41 +00001398 DEBUG(dbgs() << "New: " << *AutoreleaseRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001399
John McCalld935e9c2011-06-15 23:37:01 +00001400}
1401
Michael Gottesman158fdf62013-03-28 20:11:19 +00001402// \brief Attempt to strength reduce objc_retainBlock calls to objc_retain
1403// calls.
1404//
1405// Specifically: If an objc_retainBlock call has the copy_on_escape metadata and
1406// does not escape (following the rules of block escaping), strength reduce the
1407// objc_retainBlock to an objc_retain.
1408//
1409// TODO: If an objc_retainBlock call is dominated period by a previous
1410// objc_retainBlock call, strength reduce the objc_retainBlock to an
1411// objc_retain.
1412bool
1413ObjCARCOpt::OptimizeRetainBlockCall(Function &F, Instruction *Inst,
1414 InstructionClass &Class) {
1415 assert(GetBasicInstructionClass(Inst) == Class);
1416 assert(IC_RetainBlock == Class);
Michael Gottesman60f6b282013-03-29 05:13:07 +00001417
Michael Gottesman158fdf62013-03-28 20:11:19 +00001418 // If we can not optimize Inst, return false.
1419 if (!IsRetainBlockOptimizable(Inst))
1420 return false;
Michael Gottesman60f6b282013-03-29 05:13:07 +00001421
Michael Gottesman3eab2e42013-04-21 00:50:27 +00001422 Changed = true;
1423 ++NumPeeps;
1424
1425 DEBUG(dbgs() << "Strength reduced retainBlock => retain.\n");
1426 DEBUG(dbgs() << "Old: " << *Inst << "\n");
Michael Gottesman158fdf62013-03-28 20:11:19 +00001427 CallInst *RetainBlock = cast<CallInst>(Inst);
1428 RetainBlock->setCalledFunction(getRetainCallee(F.getParent()));
1429 // Remove copy_on_escape metadata.
1430 RetainBlock->setMetadata(CopyOnEscapeMDKind, 0);
1431 Class = IC_Retain;
Michael Gottesman3eab2e42013-04-21 00:50:27 +00001432 DEBUG(dbgs() << "New: " << *Inst << "\n");
Michael Gottesman158fdf62013-03-28 20:11:19 +00001433 return true;
1434}
1435
Michael Gottesman97e3df02013-01-14 00:35:14 +00001436/// Visit each call, one at a time, and make simplifications without doing any
1437/// additional analysis.
John McCalld935e9c2011-06-15 23:37:01 +00001438void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001439 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeIndividualCalls ==\n");
John McCalld935e9c2011-06-15 23:37:01 +00001440 // Reset all the flags in preparation for recomputing them.
1441 UsedInThisFunction = 0;
1442
1443 // Visit all objc_* calls in F.
1444 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
1445 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +00001446
John McCalld935e9c2011-06-15 23:37:01 +00001447 InstructionClass Class = GetBasicInstructionClass(Inst);
1448
Michael Gottesman89279f82013-04-05 18:10:41 +00001449 DEBUG(dbgs() << "Visiting: Class: " << Class << "; " << *Inst << "\n");
Michael Gottesman782e3442013-01-17 18:32:34 +00001450
John McCalld935e9c2011-06-15 23:37:01 +00001451 switch (Class) {
1452 default: break;
1453
1454 // Delete no-op casts. These function calls have special semantics, but
1455 // the semantics are entirely implemented via lowering in the front-end,
1456 // so by the time they reach the optimizer, they are just no-op calls
1457 // which return their argument.
1458 //
1459 // There are gray areas here, as the ability to cast reference-counted
1460 // pointers to raw void* and back allows code to break ARC assumptions,
1461 // however these are currently considered to be unimportant.
1462 case IC_NoopCast:
1463 Changed = true;
1464 ++NumNoops;
Michael Gottesman89279f82013-04-05 18:10:41 +00001465 DEBUG(dbgs() << "Erasing no-op cast: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001466 EraseInstruction(Inst);
1467 continue;
1468
1469 // If the pointer-to-weak-pointer is null, it's undefined behavior.
1470 case IC_StoreWeak:
1471 case IC_LoadWeak:
1472 case IC_LoadWeakRetained:
1473 case IC_InitWeak:
1474 case IC_DestroyWeak: {
1475 CallInst *CI = cast<CallInst>(Inst);
Michael Gottesman65c24812013-03-25 09:27:43 +00001476 if (IsNullOrUndef(CI->getArgOperand(0))) {
Dan Gohman670f9372012-04-13 18:57:48 +00001477 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +00001478 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001479 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1480 Constant::getNullValue(Ty),
1481 CI);
Michael Gottesman10426b52013-01-07 21:26:07 +00001482 llvm::Value *NewValue = UndefValue::get(CI->getType());
Michael Gottesman89279f82013-04-05 18:10:41 +00001483 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
1484 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001485 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +00001486 CI->eraseFromParent();
1487 continue;
1488 }
1489 break;
1490 }
1491 case IC_CopyWeak:
1492 case IC_MoveWeak: {
1493 CallInst *CI = cast<CallInst>(Inst);
Michael Gottesman65c24812013-03-25 09:27:43 +00001494 if (IsNullOrUndef(CI->getArgOperand(0)) ||
1495 IsNullOrUndef(CI->getArgOperand(1))) {
Dan Gohman670f9372012-04-13 18:57:48 +00001496 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +00001497 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001498 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1499 Constant::getNullValue(Ty),
1500 CI);
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001501
1502 llvm::Value *NewValue = UndefValue::get(CI->getType());
Michael Gottesman89279f82013-04-05 18:10:41 +00001503 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
1504 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001505
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001506 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +00001507 CI->eraseFromParent();
1508 continue;
1509 }
1510 break;
1511 }
Michael Gottesman158fdf62013-03-28 20:11:19 +00001512 case IC_RetainBlock:
Michael Gottesman1e430042013-04-21 00:44:46 +00001513 // If we strength reduce an objc_retainBlock to an objc_retain, continue
Michael Gottesman158fdf62013-03-28 20:11:19 +00001514 // onto the objc_retain peephole optimizations. Otherwise break.
Michael Gottesman9fc50b82013-05-13 18:29:07 +00001515 OptimizeRetainBlockCall(F, Inst, Class);
John McCalld935e9c2011-06-15 23:37:01 +00001516 break;
1517 case IC_RetainRV:
1518 if (OptimizeRetainRVCall(F, Inst))
1519 continue;
1520 break;
1521 case IC_AutoreleaseRV:
Michael Gottesman556ff612013-01-12 01:25:19 +00001522 OptimizeAutoreleaseRVCall(F, Inst, Class);
John McCalld935e9c2011-06-15 23:37:01 +00001523 break;
1524 }
1525
Michael Gottesmanb8c88362013-04-03 02:57:24 +00001526 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
John McCalld935e9c2011-06-15 23:37:01 +00001527 if (IsAutorelease(Class) && Inst->use_empty()) {
1528 CallInst *Call = cast<CallInst>(Inst);
1529 const Value *Arg = Call->getArgOperand(0);
1530 Arg = FindSingleUseIdentifiedObject(Arg);
1531 if (Arg) {
1532 Changed = true;
1533 ++NumAutoreleases;
1534
1535 // Create the declaration lazily.
1536 LLVMContext &C = Inst->getContext();
1537 CallInst *NewCall =
1538 CallInst::Create(getReleaseCallee(F.getParent()),
1539 Call->getArgOperand(0), "", Call);
Dmitri Gribenko3238fb72013-05-05 00:40:33 +00001540 NewCall->setMetadata(ImpreciseReleaseMDKind, MDNode::get(C, None));
Michael Gottesman10426b52013-01-07 21:26:07 +00001541
Michael Gottesman89279f82013-04-05 18:10:41 +00001542 DEBUG(dbgs() << "Replacing autorelease{,RV}(x) with objc_release(x) "
1543 "since x is otherwise unused.\nOld: " << *Call << "\nNew: "
1544 << *NewCall << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001545
John McCalld935e9c2011-06-15 23:37:01 +00001546 EraseInstruction(Call);
1547 Inst = NewCall;
1548 Class = IC_Release;
1549 }
1550 }
1551
1552 // For functions which can never be passed stack arguments, add
1553 // a tail keyword.
1554 if (IsAlwaysTail(Class)) {
1555 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +00001556 DEBUG(dbgs() << "Adding tail keyword to function since it can never be "
1557 "passed stack args: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001558 cast<CallInst>(Inst)->setTailCall();
1559 }
1560
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001561 // Ensure that functions that can never have a "tail" keyword due to the
1562 // semantics of ARC truly do not do so.
1563 if (IsNeverTail(Class)) {
1564 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +00001565 DEBUG(dbgs() << "Removing tail keyword from function: " << *Inst <<
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001566 "\n");
1567 cast<CallInst>(Inst)->setTailCall(false);
1568 }
1569
John McCalld935e9c2011-06-15 23:37:01 +00001570 // Set nounwind as needed.
1571 if (IsNoThrow(Class)) {
1572 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +00001573 DEBUG(dbgs() << "Found no throw class. Setting nounwind on: " << *Inst
1574 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001575 cast<CallInst>(Inst)->setDoesNotThrow();
1576 }
1577
1578 if (!IsNoopOnNull(Class)) {
1579 UsedInThisFunction |= 1 << Class;
1580 continue;
1581 }
1582
1583 const Value *Arg = GetObjCArg(Inst);
1584
1585 // ARC calls with null are no-ops. Delete them.
Michael Gottesman65c24812013-03-25 09:27:43 +00001586 if (IsNullOrUndef(Arg)) {
John McCalld935e9c2011-06-15 23:37:01 +00001587 Changed = true;
1588 ++NumNoops;
Michael Gottesman89279f82013-04-05 18:10:41 +00001589 DEBUG(dbgs() << "ARC calls with null are no-ops. Erasing: " << *Inst
1590 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001591 EraseInstruction(Inst);
1592 continue;
1593 }
1594
1595 // Keep track of which of retain, release, autorelease, and retain_block
1596 // are actually present in this function.
1597 UsedInThisFunction |= 1 << Class;
1598
1599 // If Arg is a PHI, and one or more incoming values to the
1600 // PHI are null, and the call is control-equivalent to the PHI, and there
1601 // are no relevant side effects between the PHI and the call, the call
1602 // could be pushed up to just those paths with non-null incoming values.
1603 // For now, don't bother splitting critical edges for this.
1604 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
1605 Worklist.push_back(std::make_pair(Inst, Arg));
1606 do {
1607 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
1608 Inst = Pair.first;
1609 Arg = Pair.second;
1610
1611 const PHINode *PN = dyn_cast<PHINode>(Arg);
1612 if (!PN) continue;
1613
1614 // Determine if the PHI has any null operands, or any incoming
1615 // critical edges.
1616 bool HasNull = false;
1617 bool HasCriticalEdges = false;
1618 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1619 Value *Incoming =
1620 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
Michael Gottesman65c24812013-03-25 09:27:43 +00001621 if (IsNullOrUndef(Incoming))
John McCalld935e9c2011-06-15 23:37:01 +00001622 HasNull = true;
1623 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
1624 .getNumSuccessors() != 1) {
1625 HasCriticalEdges = true;
1626 break;
1627 }
1628 }
1629 // If we have null operands and no critical edges, optimize.
1630 if (!HasCriticalEdges && HasNull) {
1631 SmallPtrSet<Instruction *, 4> DependingInstructions;
1632 SmallPtrSet<const BasicBlock *, 4> Visited;
1633
1634 // Check that there is nothing that cares about the reference
1635 // count between the call and the phi.
Dan Gohman8478d762012-04-13 00:59:57 +00001636 switch (Class) {
1637 case IC_Retain:
1638 case IC_RetainBlock:
1639 // These can always be moved up.
1640 break;
1641 case IC_Release:
Dan Gohman41375a32012-05-08 23:39:44 +00001642 // These can't be moved across things that care about the retain
1643 // count.
Dan Gohman8478d762012-04-13 00:59:57 +00001644 FindDependencies(NeedsPositiveRetainCount, Arg,
1645 Inst->getParent(), Inst,
1646 DependingInstructions, Visited, PA);
1647 break;
1648 case IC_Autorelease:
1649 // These can't be moved across autorelease pool scope boundaries.
1650 FindDependencies(AutoreleasePoolBoundary, Arg,
1651 Inst->getParent(), Inst,
1652 DependingInstructions, Visited, PA);
1653 break;
1654 case IC_RetainRV:
1655 case IC_AutoreleaseRV:
1656 // Don't move these; the RV optimization depends on the autoreleaseRV
1657 // being tail called, and the retainRV being immediately after a call
1658 // (which might still happen if we get lucky with codegen layout, but
1659 // it's not worth taking the chance).
1660 continue;
1661 default:
1662 llvm_unreachable("Invalid dependence flavor");
1663 }
1664
John McCalld935e9c2011-06-15 23:37:01 +00001665 if (DependingInstructions.size() == 1 &&
1666 *DependingInstructions.begin() == PN) {
1667 Changed = true;
1668 ++NumPartialNoops;
1669 // Clone the call into each predecessor that has a non-null value.
1670 CallInst *CInst = cast<CallInst>(Inst);
Chris Lattner229907c2011-07-18 04:54:35 +00001671 Type *ParamTy = CInst->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001672 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1673 Value *Incoming =
1674 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
Michael Gottesman65c24812013-03-25 09:27:43 +00001675 if (!IsNullOrUndef(Incoming)) {
John McCalld935e9c2011-06-15 23:37:01 +00001676 CallInst *Clone = cast<CallInst>(CInst->clone());
1677 Value *Op = PN->getIncomingValue(i);
1678 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
1679 if (Op->getType() != ParamTy)
1680 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
1681 Clone->setArgOperand(0, Op);
1682 Clone->insertBefore(InsertPos);
Michael Gottesmanc189a392013-01-09 19:23:24 +00001683
Michael Gottesman89279f82013-04-05 18:10:41 +00001684 DEBUG(dbgs() << "Cloning "
Michael Gottesmanc189a392013-01-09 19:23:24 +00001685 << *CInst << "\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00001686 "And inserting clone at " << *InsertPos << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001687 Worklist.push_back(std::make_pair(Clone, Incoming));
1688 }
1689 }
1690 // Erase the original call.
Michael Gottesmanc189a392013-01-09 19:23:24 +00001691 DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001692 EraseInstruction(CInst);
1693 continue;
1694 }
1695 }
1696 } while (!Worklist.empty());
1697 }
1698}
1699
Michael Gottesman323964c2013-04-18 05:39:45 +00001700/// If we have a top down pointer in the S_Use state, make sure that there are
1701/// no CFG hazards by checking the states of various bottom up pointers.
1702static void CheckForUseCFGHazard(const Sequence SuccSSeq,
1703 const bool SuccSRRIKnownSafe,
1704 PtrState &S,
1705 bool &SomeSuccHasSame,
1706 bool &AllSuccsHaveSame,
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001707 bool &NotAllSeqEqualButKnownSafe,
Michael Gottesman323964c2013-04-18 05:39:45 +00001708 bool &ShouldContinue) {
1709 switch (SuccSSeq) {
1710 case S_CanRelease: {
1711 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
1712 S.ClearSequenceProgress();
1713 break;
1714 }
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001715 S.RRI.CFGHazardAfflicted = true;
Michael Gottesman323964c2013-04-18 05:39:45 +00001716 ShouldContinue = true;
1717 break;
1718 }
1719 case S_Use:
1720 SomeSuccHasSame = true;
1721 break;
1722 case S_Stop:
1723 case S_Release:
1724 case S_MovableRelease:
1725 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
1726 AllSuccsHaveSame = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001727 else
1728 NotAllSeqEqualButKnownSafe = true;
Michael Gottesman323964c2013-04-18 05:39:45 +00001729 break;
1730 case S_Retain:
1731 llvm_unreachable("bottom-up pointer in retain state!");
1732 case S_None:
1733 llvm_unreachable("This should have been handled earlier.");
1734 }
1735}
1736
1737/// If we have a Top Down pointer in the S_CanRelease state, make sure that
1738/// there are no CFG hazards by checking the states of various bottom up
1739/// pointers.
1740static void CheckForCanReleaseCFGHazard(const Sequence SuccSSeq,
1741 const bool SuccSRRIKnownSafe,
1742 PtrState &S,
1743 bool &SomeSuccHasSame,
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001744 bool &AllSuccsHaveSame,
1745 bool &NotAllSeqEqualButKnownSafe) {
Michael Gottesman323964c2013-04-18 05:39:45 +00001746 switch (SuccSSeq) {
1747 case S_CanRelease:
1748 SomeSuccHasSame = true;
1749 break;
1750 case S_Stop:
1751 case S_Release:
1752 case S_MovableRelease:
1753 case S_Use:
1754 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
1755 AllSuccsHaveSame = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001756 else
1757 NotAllSeqEqualButKnownSafe = true;
Michael Gottesman323964c2013-04-18 05:39:45 +00001758 break;
1759 case S_Retain:
1760 llvm_unreachable("bottom-up pointer in retain state!");
1761 case S_None:
1762 llvm_unreachable("This should have been handled earlier.");
1763 }
1764}
1765
Michael Gottesman97e3df02013-01-14 00:35:14 +00001766/// Check for critical edges, loop boundaries, irreducible control flow, or
1767/// other CFG structures where moving code across the edge would result in it
1768/// being executed more.
John McCalld935e9c2011-06-15 23:37:01 +00001769void
1770ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
1771 DenseMap<const BasicBlock *, BBState> &BBStates,
1772 BBState &MyStates) const {
1773 // If any top-down local-use or possible-dec has a succ which is earlier in
1774 // the sequence, forget it.
Dan Gohman55b06742012-03-02 01:13:53 +00001775 for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
Michael Gottesman323964c2013-04-18 05:39:45 +00001776 E = MyStates.top_down_ptr_end(); I != E; ++I) {
1777 PtrState &S = I->second;
1778 const Sequence Seq = I->second.GetSeq();
Dan Gohman0155f302012-02-17 18:59:53 +00001779
Michael Gottesman323964c2013-04-18 05:39:45 +00001780 // We only care about S_Retain, S_CanRelease, and S_Use.
1781 if (Seq == S_None)
1782 continue;
Dan Gohman0155f302012-02-17 18:59:53 +00001783
Michael Gottesman323964c2013-04-18 05:39:45 +00001784 // Make sure that if extra top down states are added in the future that this
1785 // code is updated to handle it.
1786 assert((Seq == S_Retain || Seq == S_CanRelease || Seq == S_Use) &&
1787 "Unknown top down sequence state.");
1788
1789 const Value *Arg = I->first;
1790 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
1791 bool SomeSuccHasSame = false;
1792 bool AllSuccsHaveSame = true;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001793 bool NotAllSeqEqualButKnownSafe = false;
Michael Gottesman323964c2013-04-18 05:39:45 +00001794
1795 succ_const_iterator SI(TI), SE(TI, false);
1796
1797 for (; SI != SE; ++SI) {
1798 // If VisitBottomUp has pointer information for this successor, take
1799 // what we know about it.
1800 const DenseMap<const BasicBlock *, BBState>::iterator BBI =
1801 BBStates.find(*SI);
1802 assert(BBI != BBStates.end());
1803 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
1804 const Sequence SuccSSeq = SuccS.GetSeq();
1805
1806 // If bottom up, the pointer is in an S_None state, clear the sequence
1807 // progress since the sequence in the bottom up state finished
1808 // suggesting a mismatch in between retains/releases. This is true for
1809 // all three cases that we are handling here: S_Retain, S_Use, and
1810 // S_CanRelease.
1811 if (SuccSSeq == S_None) {
Dan Gohman12130272011-08-12 00:26:31 +00001812 S.ClearSequenceProgress();
Michael Gottesman323964c2013-04-18 05:39:45 +00001813 continue;
1814 }
1815
1816 // If we have S_Use or S_CanRelease, perform our check for cfg hazard
1817 // checks.
1818 const bool SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
1819
1820 // *NOTE* We do not use Seq from above here since we are allowing for
1821 // S.GetSeq() to change while we are visiting basic blocks.
1822 switch(S.GetSeq()) {
1823 case S_Use: {
1824 bool ShouldContinue = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001825 CheckForUseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S, SomeSuccHasSame,
1826 AllSuccsHaveSame, NotAllSeqEqualButKnownSafe,
Michael Gottesman323964c2013-04-18 05:39:45 +00001827 ShouldContinue);
1828 if (ShouldContinue)
1829 continue;
1830 break;
1831 }
1832 case S_CanRelease: {
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001833 CheckForCanReleaseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S,
1834 SomeSuccHasSame, AllSuccsHaveSame,
1835 NotAllSeqEqualButKnownSafe);
Michael Gottesman323964c2013-04-18 05:39:45 +00001836 break;
1837 }
1838 case S_Retain:
1839 case S_None:
1840 case S_Stop:
1841 case S_Release:
1842 case S_MovableRelease:
1843 break;
1844 }
John McCalld935e9c2011-06-15 23:37:01 +00001845 }
Michael Gottesman323964c2013-04-18 05:39:45 +00001846
1847 // If the state at the other end of any of the successor edges
1848 // matches the current state, require all edges to match. This
1849 // guards against loops in the middle of a sequence.
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001850 if (SomeSuccHasSame && !AllSuccsHaveSame) {
Michael Gottesman323964c2013-04-18 05:39:45 +00001851 S.ClearSequenceProgress();
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001852 } else if (NotAllSeqEqualButKnownSafe) {
1853 // If we would have cleared the state foregoing the fact that we are known
1854 // safe, stop code motion. This is because whether or not it is safe to
1855 // remove RR pairs via KnownSafe is an orthogonal concept to whether we
1856 // are allowed to perform code motion.
1857 S.RRI.CFGHazardAfflicted = true;
1858 }
Michael Gottesman323964c2013-04-18 05:39:45 +00001859 }
John McCalld935e9c2011-06-15 23:37:01 +00001860}
1861
1862bool
Dan Gohman817a7c62012-03-22 18:24:56 +00001863ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
Dan Gohman5c70fad2012-03-23 17:47:54 +00001864 BasicBlock *BB,
Dan Gohman817a7c62012-03-22 18:24:56 +00001865 MapVector<Value *, RRInfo> &Retains,
1866 BBState &MyStates) {
1867 bool NestingDetected = false;
1868 InstructionClass Class = GetInstructionClass(Inst);
1869 const Value *Arg = 0;
Michael Gottesman79249972013-04-05 23:46:45 +00001870
Michael Gottesman1d8d2572013-04-05 22:54:28 +00001871 DEBUG(dbgs() << "Class: " << Class << "\n");
Michael Gottesman79249972013-04-05 23:46:45 +00001872
Dan Gohman817a7c62012-03-22 18:24:56 +00001873 switch (Class) {
1874 case IC_Release: {
1875 Arg = GetObjCArg(Inst);
1876
1877 PtrState &S = MyStates.getPtrBottomUpState(Arg);
1878
1879 // If we see two releases in a row on the same pointer. If so, make
1880 // a note, and we'll cicle back to revisit it after we've
1881 // hopefully eliminated the second release, which may allow us to
1882 // eliminate the first release too.
1883 // Theoretically we could implement removal of nested retain+release
1884 // pairs by making PtrState hold a stack of states, but this is
1885 // simple and avoids adding overhead for the non-nested case.
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001886 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001887 DEBUG(dbgs() << "Found nested releases (i.e. a release pair)\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00001888 NestingDetected = true;
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001889 }
Dan Gohman817a7c62012-03-22 18:24:56 +00001890
Dan Gohman817a7c62012-03-22 18:24:56 +00001891 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001892 Sequence NewSeq = ReleaseMetadata ? S_MovableRelease : S_Release;
1893 ANNOTATE_BOTTOMUP(Inst, Arg, S.GetSeq(), NewSeq);
1894 S.ResetSequenceProgress(NewSeq);
Dan Gohman817a7c62012-03-22 18:24:56 +00001895 S.RRI.ReleaseMetadata = ReleaseMetadata;
Michael Gottesman07beea42013-03-23 05:31:01 +00001896 S.RRI.KnownSafe = S.HasKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001897 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
1898 S.RRI.Calls.insert(Inst);
Dan Gohmandf476e52012-09-04 23:16:20 +00001899 S.SetKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001900 break;
1901 }
1902 case IC_RetainBlock:
Michael Gottesman158fdf62013-03-28 20:11:19 +00001903 // In OptimizeIndividualCalls, we have strength reduced all optimizable
1904 // objc_retainBlocks to objc_retains. Thus at this point any
1905 // objc_retainBlocks that we see are not optimizable.
1906 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001907 case IC_Retain:
1908 case IC_RetainRV: {
1909 Arg = GetObjCArg(Inst);
1910
1911 PtrState &S = MyStates.getPtrBottomUpState(Arg);
Dan Gohman62079b42012-04-25 00:50:46 +00001912 S.SetKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001913
Michael Gottesman81b1d432013-03-26 00:42:04 +00001914 Sequence OldSeq = S.GetSeq();
1915 switch (OldSeq) {
Dan Gohman817a7c62012-03-22 18:24:56 +00001916 case S_Stop:
1917 case S_Release:
1918 case S_MovableRelease:
1919 case S_Use:
Michael Gottesman1d8d2572013-04-05 22:54:28 +00001920 // If OldSeq is not S_Use or OldSeq is S_Use and we are tracking an
1921 // imprecise release, clear our reverse insertion points.
1922 if (OldSeq != S_Use || S.RRI.IsTrackingImpreciseReleases())
1923 S.RRI.ReverseInsertPts.clear();
Dan Gohman817a7c62012-03-22 18:24:56 +00001924 // FALL THROUGH
1925 case S_CanRelease:
1926 // Don't do retain+release tracking for IC_RetainRV, because it's
1927 // better to let it remain as the first instruction after a call.
Michael Gottesmanba648592013-03-28 23:08:44 +00001928 if (Class != IC_RetainRV)
Dan Gohman817a7c62012-03-22 18:24:56 +00001929 Retains[Inst] = S.RRI;
Dan Gohman817a7c62012-03-22 18:24:56 +00001930 S.ClearSequenceProgress();
1931 break;
1932 case S_None:
1933 break;
1934 case S_Retain:
1935 llvm_unreachable("bottom-up pointer in retain state!");
1936 }
Michael Gottesman79249972013-04-05 23:46:45 +00001937 ANNOTATE_BOTTOMUP(Inst, Arg, OldSeq, S.GetSeq());
Michael Gottesman31ba23a2013-04-05 22:54:32 +00001938 // A retain moving bottom up can be a use.
1939 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001940 }
1941 case IC_AutoreleasepoolPop:
1942 // Conservatively, clear MyStates for all known pointers.
1943 MyStates.clearBottomUpPointers();
1944 return NestingDetected;
1945 case IC_AutoreleasepoolPush:
1946 case IC_None:
1947 // These are irrelevant.
1948 return NestingDetected;
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001949 case IC_User:
1950 // If we have a store into an alloca of a pointer we are tracking, the
1951 // pointer has multiple owners implying that we must be more conservative.
1952 //
1953 // This comes up in the context of a pointer being ``KnownSafe''. In the
1954 // presense of a block being initialized, the frontend will emit the
1955 // objc_retain on the original pointer and the release on the pointer loaded
1956 // from the alloca. The optimizer will through the provenance analysis
1957 // realize that the two are related, but since we only require KnownSafe in
1958 // one direction, will match the inner retain on the original pointer with
1959 // the guard release on the original pointer. This is fixed by ensuring that
1960 // in the presense of allocas we only unconditionally remove pointers if
1961 // both our retain and our release are KnownSafe.
1962 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1963 if (AreAnyUnderlyingObjectsAnAlloca(SI->getPointerOperand())) {
1964 BBState::ptr_iterator I = MyStates.findPtrBottomUpState(
1965 StripPointerCastsAndObjCCalls(SI->getValueOperand()));
1966 if (I != MyStates.bottom_up_ptr_end())
Michael Gottesman5a91bbf2013-05-24 20:44:02 +00001967 MultiOwnersSet.insert(I->first);
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001968 }
1969 }
1970 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001971 default:
1972 break;
1973 }
1974
1975 // Consider any other possible effects of this instruction on each
1976 // pointer being tracked.
1977 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
1978 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
1979 const Value *Ptr = MI->first;
1980 if (Ptr == Arg)
1981 continue; // Handled above.
1982 PtrState &S = MI->second;
1983 Sequence Seq = S.GetSeq();
1984
1985 // Check for possible releases.
1986 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001987 DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr
1988 << "\n");
Michael Gottesman764b1cf2013-03-23 05:46:19 +00001989 S.ClearKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001990 switch (Seq) {
1991 case S_Use:
1992 S.SetSeq(S_CanRelease);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001993 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S.GetSeq());
Dan Gohman817a7c62012-03-22 18:24:56 +00001994 continue;
1995 case S_CanRelease:
1996 case S_Release:
1997 case S_MovableRelease:
1998 case S_Stop:
1999 case S_None:
2000 break;
2001 case S_Retain:
2002 llvm_unreachable("bottom-up pointer in retain state!");
2003 }
2004 }
2005
2006 // Check for possible direct uses.
2007 switch (Seq) {
2008 case S_Release:
2009 case S_MovableRelease:
2010 if (CanUse(Inst, Ptr, PA, Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002011 DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr
2012 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00002013 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohman5c70fad2012-03-23 17:47:54 +00002014 // If this is an invoke instruction, we're scanning it as part of
2015 // one of its successor blocks, since we can't insert code after it
2016 // in its own block, and we don't want to split critical edges.
2017 if (isa<InvokeInst>(Inst))
2018 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2019 else
Francois Pichet4b9ab742012-03-24 01:36:37 +00002020 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohman817a7c62012-03-22 18:24:56 +00002021 S.SetSeq(S_Use);
Michael Gottesman81b1d432013-03-26 00:42:04 +00002022 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
John McCall20182ac2013-03-22 21:38:36 +00002023 } else if (Seq == S_Release && IsUser(Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002024 DEBUG(dbgs() << "PreciseReleaseUse: Seq: " << Seq << "; " << *Ptr
2025 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00002026 // Non-movable releases depend on any possible objc pointer use.
2027 S.SetSeq(S_Stop);
Michael Gottesman81b1d432013-03-26 00:42:04 +00002028 ANNOTATE_BOTTOMUP(Inst, Ptr, S_Release, S_Stop);
Dan Gohman817a7c62012-03-22 18:24:56 +00002029 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohman5c70fad2012-03-23 17:47:54 +00002030 // As above; handle invoke specially.
2031 if (isa<InvokeInst>(Inst))
2032 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2033 else
Francois Pichet4b9ab742012-03-24 01:36:37 +00002034 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohman817a7c62012-03-22 18:24:56 +00002035 }
2036 break;
2037 case S_Stop:
Michael Gottesman81b1d432013-03-26 00:42:04 +00002038 if (CanUse(Inst, Ptr, PA, Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002039 DEBUG(dbgs() << "PreciseStopUse: Seq: " << Seq << "; " << *Ptr
2040 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00002041 S.SetSeq(S_Use);
Michael Gottesman81b1d432013-03-26 00:42:04 +00002042 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
2043 }
Dan Gohman817a7c62012-03-22 18:24:56 +00002044 break;
2045 case S_CanRelease:
2046 case S_Use:
2047 case S_None:
2048 break;
2049 case S_Retain:
2050 llvm_unreachable("bottom-up pointer in retain state!");
2051 }
2052 }
2053
2054 return NestingDetected;
2055}
2056
2057bool
John McCalld935e9c2011-06-15 23:37:01 +00002058ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2059 DenseMap<const BasicBlock *, BBState> &BBStates,
2060 MapVector<Value *, RRInfo> &Retains) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002061
2062 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitBottomUp ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00002063
John McCalld935e9c2011-06-15 23:37:01 +00002064 bool NestingDetected = false;
2065 BBState &MyStates = BBStates[BB];
2066
2067 // Merge the states from each successor to compute the initial state
2068 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00002069 BBState::edge_iterator SI(MyStates.succ_begin()),
2070 SE(MyStates.succ_end());
2071 if (SI != SE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002072 const BasicBlock *Succ = *SI;
2073 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
2074 assert(I != BBStates.end());
2075 MyStates.InitFromSucc(I->second);
2076 ++SI;
2077 for (; SI != SE; ++SI) {
2078 Succ = *SI;
2079 I = BBStates.find(Succ);
2080 assert(I != BBStates.end());
2081 MyStates.MergeSucc(I->second);
2082 }
Michael Gottesman60f6b282013-03-29 05:13:07 +00002083 }
Michael Gottesmancd4de0f2013-03-26 00:42:09 +00002084
Michael Gottesman43e7e002013-04-03 22:41:59 +00002085 // If ARC Annotations are enabled, output the current state of pointers at the
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002086 // bottom of the basic block.
Michael Gottesman43e7e002013-04-03 22:41:59 +00002087 ANNOTATE_BOTTOMUP_BBEND(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002088
John McCalld935e9c2011-06-15 23:37:01 +00002089 // Visit all the instructions, bottom-up.
2090 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2091 Instruction *Inst = llvm::prior(I);
Dan Gohman5c70fad2012-03-23 17:47:54 +00002092
2093 // Invoke instructions are visited as part of their successors (below).
2094 if (isa<InvokeInst>(Inst))
2095 continue;
2096
Michael Gottesman89279f82013-04-05 18:10:41 +00002097 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00002098
Dan Gohman5c70fad2012-03-23 17:47:54 +00002099 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
2100 }
2101
Dan Gohmandae33492012-04-27 18:56:31 +00002102 // If there's a predecessor with an invoke, visit the invoke as if it were
2103 // part of this block, since we can't insert code after an invoke in its own
2104 // block, and we don't want to split critical edges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002105 for (BBState::edge_iterator PI(MyStates.pred_begin()),
2106 PE(MyStates.pred_end()); PI != PE; ++PI) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00002107 BasicBlock *Pred = *PI;
Dan Gohmandae33492012-04-27 18:56:31 +00002108 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
2109 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
Dan Gohman817a7c62012-03-22 18:24:56 +00002110 }
John McCalld935e9c2011-06-15 23:37:01 +00002111
Michael Gottesman43e7e002013-04-03 22:41:59 +00002112 // If ARC Annotations are enabled, output the current state of pointers at the
2113 // top of the basic block.
2114 ANNOTATE_BOTTOMUP_BBSTART(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002115
Dan Gohman817a7c62012-03-22 18:24:56 +00002116 return NestingDetected;
2117}
John McCalld935e9c2011-06-15 23:37:01 +00002118
Dan Gohman817a7c62012-03-22 18:24:56 +00002119bool
2120ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
2121 DenseMap<Value *, RRInfo> &Releases,
2122 BBState &MyStates) {
2123 bool NestingDetected = false;
2124 InstructionClass Class = GetInstructionClass(Inst);
2125 const Value *Arg = 0;
John McCalld935e9c2011-06-15 23:37:01 +00002126
Dan Gohman817a7c62012-03-22 18:24:56 +00002127 switch (Class) {
2128 case IC_RetainBlock:
Michael Gottesman158fdf62013-03-28 20:11:19 +00002129 // In OptimizeIndividualCalls, we have strength reduced all optimizable
2130 // objc_retainBlocks to objc_retains. Thus at this point any
2131 // objc_retainBlocks that we see are not optimizable.
2132 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00002133 case IC_Retain:
2134 case IC_RetainRV: {
2135 Arg = GetObjCArg(Inst);
2136
2137 PtrState &S = MyStates.getPtrTopDownState(Arg);
2138
2139 // Don't do retain+release tracking for IC_RetainRV, because it's
2140 // better to let it remain as the first instruction after a call.
2141 if (Class != IC_RetainRV) {
2142 // If we see two retains in a row on the same pointer. If so, make
John McCalld935e9c2011-06-15 23:37:01 +00002143 // a note, and we'll cicle back to revisit it after we've
Dan Gohman817a7c62012-03-22 18:24:56 +00002144 // hopefully eliminated the second retain, which may allow us to
2145 // eliminate the first retain too.
John McCalld935e9c2011-06-15 23:37:01 +00002146 // Theoretically we could implement removal of nested retain+release
2147 // pairs by making PtrState hold a stack of states, but this is
2148 // simple and avoids adding overhead for the non-nested case.
Dan Gohman817a7c62012-03-22 18:24:56 +00002149 if (S.GetSeq() == S_Retain)
John McCalld935e9c2011-06-15 23:37:01 +00002150 NestingDetected = true;
2151
Michael Gottesman81b1d432013-03-26 00:42:04 +00002152 ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_Retain);
Dan Gohman62079b42012-04-25 00:50:46 +00002153 S.ResetSequenceProgress(S_Retain);
Michael Gottesman07beea42013-03-23 05:31:01 +00002154 S.RRI.KnownSafe = S.HasKnownPositiveRefCount();
John McCalld935e9c2011-06-15 23:37:01 +00002155 S.RRI.Calls.insert(Inst);
John McCalld935e9c2011-06-15 23:37:01 +00002156 }
John McCalld935e9c2011-06-15 23:37:01 +00002157
Dan Gohmandf476e52012-09-04 23:16:20 +00002158 S.SetKnownPositiveRefCount();
Dan Gohmanf64ff8e2012-07-23 19:27:31 +00002159
2160 // A retain can be a potential use; procede to the generic checking
2161 // code below.
2162 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00002163 }
2164 case IC_Release: {
2165 Arg = GetObjCArg(Inst);
2166
2167 PtrState &S = MyStates.getPtrTopDownState(Arg);
Michael Gottesman764b1cf2013-03-23 05:46:19 +00002168 S.ClearKnownPositiveRefCount();
Michael Gottesman79249972013-04-05 23:46:45 +00002169
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002170 Sequence OldSeq = S.GetSeq();
Michael Gottesman79249972013-04-05 23:46:45 +00002171
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002172 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
Michael Gottesman79249972013-04-05 23:46:45 +00002173
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002174 switch (OldSeq) {
Dan Gohman817a7c62012-03-22 18:24:56 +00002175 case S_Retain:
2176 case S_CanRelease:
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002177 if (OldSeq == S_Retain || ReleaseMetadata != 0)
2178 S.RRI.ReverseInsertPts.clear();
Dan Gohman817a7c62012-03-22 18:24:56 +00002179 // FALL THROUGH
2180 case S_Use:
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002181 S.RRI.ReleaseMetadata = ReleaseMetadata;
Dan Gohman817a7c62012-03-22 18:24:56 +00002182 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2183 Releases[Inst] = S.RRI;
Michael Gottesman81b1d432013-03-26 00:42:04 +00002184 ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_None);
Dan Gohman817a7c62012-03-22 18:24:56 +00002185 S.ClearSequenceProgress();
2186 break;
2187 case S_None:
2188 break;
2189 case S_Stop:
2190 case S_Release:
2191 case S_MovableRelease:
2192 llvm_unreachable("top-down pointer in release state!");
2193 }
2194 break;
2195 }
2196 case IC_AutoreleasepoolPop:
2197 // Conservatively, clear MyStates for all known pointers.
2198 MyStates.clearTopDownPointers();
2199 return NestingDetected;
2200 case IC_AutoreleasepoolPush:
2201 case IC_None:
2202 // These are irrelevant.
2203 return NestingDetected;
2204 default:
2205 break;
2206 }
2207
2208 // Consider any other possible effects of this instruction on each
2209 // pointer being tracked.
2210 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
2211 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
2212 const Value *Ptr = MI->first;
2213 if (Ptr == Arg)
2214 continue; // Handled above.
2215 PtrState &S = MI->second;
2216 Sequence Seq = S.GetSeq();
2217
2218 // Check for possible releases.
2219 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Michael Gottesmanbab49e972013-04-05 18:26:08 +00002220 DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr
Michael Gottesman79249972013-04-05 23:46:45 +00002221 << "\n");
Michael Gottesman764b1cf2013-03-23 05:46:19 +00002222 S.ClearKnownPositiveRefCount();
John McCalld935e9c2011-06-15 23:37:01 +00002223 switch (Seq) {
Dan Gohman817a7c62012-03-22 18:24:56 +00002224 case S_Retain:
2225 S.SetSeq(S_CanRelease);
Michael Gottesman81b1d432013-03-26 00:42:04 +00002226 ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_CanRelease);
Dan Gohman817a7c62012-03-22 18:24:56 +00002227 assert(S.RRI.ReverseInsertPts.empty());
2228 S.RRI.ReverseInsertPts.insert(Inst);
2229
2230 // One call can't cause a transition from S_Retain to S_CanRelease
2231 // and S_CanRelease to S_Use. If we've made the first transition,
2232 // we're done.
2233 continue;
John McCalld935e9c2011-06-15 23:37:01 +00002234 case S_Use:
Dan Gohman817a7c62012-03-22 18:24:56 +00002235 case S_CanRelease:
John McCalld935e9c2011-06-15 23:37:01 +00002236 case S_None:
2237 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00002238 case S_Stop:
2239 case S_Release:
2240 case S_MovableRelease:
2241 llvm_unreachable("top-down pointer in release state!");
John McCalld935e9c2011-06-15 23:37:01 +00002242 }
2243 }
Dan Gohman817a7c62012-03-22 18:24:56 +00002244
2245 // Check for possible direct uses.
2246 switch (Seq) {
2247 case S_CanRelease:
Michael Gottesman81b1d432013-03-26 00:42:04 +00002248 if (CanUse(Inst, Ptr, PA, Class)) {
Michael Gottesmanbab49e972013-04-05 18:26:08 +00002249 DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr
2250 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00002251 S.SetSeq(S_Use);
Michael Gottesman81b1d432013-03-26 00:42:04 +00002252 ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_Use);
2253 }
Dan Gohman817a7c62012-03-22 18:24:56 +00002254 break;
2255 case S_Retain:
2256 case S_Use:
2257 case S_None:
2258 break;
2259 case S_Stop:
2260 case S_Release:
2261 case S_MovableRelease:
2262 llvm_unreachable("top-down pointer in release state!");
2263 }
John McCalld935e9c2011-06-15 23:37:01 +00002264 }
2265
2266 return NestingDetected;
2267}
2268
2269bool
2270ObjCARCOpt::VisitTopDown(BasicBlock *BB,
2271 DenseMap<const BasicBlock *, BBState> &BBStates,
2272 DenseMap<Value *, RRInfo> &Releases) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002273 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitTopDown ==\n");
John McCalld935e9c2011-06-15 23:37:01 +00002274 bool NestingDetected = false;
2275 BBState &MyStates = BBStates[BB];
2276
2277 // Merge the states from each predecessor to compute the initial state
2278 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00002279 BBState::edge_iterator PI(MyStates.pred_begin()),
2280 PE(MyStates.pred_end());
2281 if (PI != PE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002282 const BasicBlock *Pred = *PI;
2283 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
2284 assert(I != BBStates.end());
2285 MyStates.InitFromPred(I->second);
2286 ++PI;
2287 for (; PI != PE; ++PI) {
2288 Pred = *PI;
2289 I = BBStates.find(Pred);
2290 assert(I != BBStates.end());
2291 MyStates.MergePred(I->second);
2292 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002293 }
John McCalld935e9c2011-06-15 23:37:01 +00002294
Michael Gottesman43e7e002013-04-03 22:41:59 +00002295 // If ARC Annotations are enabled, output the current state of pointers at the
2296 // top of the basic block.
2297 ANNOTATE_TOPDOWN_BBSTART(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002298
John McCalld935e9c2011-06-15 23:37:01 +00002299 // Visit all the instructions, top-down.
2300 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2301 Instruction *Inst = I;
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00002302
Michael Gottesman89279f82013-04-05 18:10:41 +00002303 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00002304
Dan Gohman817a7c62012-03-22 18:24:56 +00002305 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00002306 }
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002307
Michael Gottesman43e7e002013-04-03 22:41:59 +00002308 // If ARC Annotations are enabled, output the current state of pointers at the
2309 // bottom of the basic block.
2310 ANNOTATE_TOPDOWN_BBEND(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002311
Michael Gottesmanffef24f2013-04-17 20:48:01 +00002312#ifdef ARC_ANNOTATIONS
Michael Gottesmanadb921a2013-04-17 21:03:53 +00002313 if (!(EnableARCAnnotations && DisableCheckForCFGHazards))
Michael Gottesmanffef24f2013-04-17 20:48:01 +00002314#endif
John McCalld935e9c2011-06-15 23:37:01 +00002315 CheckForCFGHazards(BB, BBStates, MyStates);
2316 return NestingDetected;
2317}
2318
Dan Gohmana53a12c2011-12-12 19:42:25 +00002319static void
2320ComputePostOrders(Function &F,
2321 SmallVectorImpl<BasicBlock *> &PostOrder,
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002322 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
2323 unsigned NoObjCARCExceptionsMDKind,
2324 DenseMap<const BasicBlock *, BBState> &BBStates) {
Michael Gottesman97e3df02013-01-14 00:35:14 +00002325 /// The visited set, for doing DFS walks.
Dan Gohmana53a12c2011-12-12 19:42:25 +00002326 SmallPtrSet<BasicBlock *, 16> Visited;
2327
2328 // Do DFS, computing the PostOrder.
2329 SmallPtrSet<BasicBlock *, 16> OnStack;
2330 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002331
2332 // Functions always have exactly one entry block, and we don't have
2333 // any other block that we treat like an entry block.
Dan Gohmana53a12c2011-12-12 19:42:25 +00002334 BasicBlock *EntryBB = &F.getEntryBlock();
Dan Gohman41375a32012-05-08 23:39:44 +00002335 BBState &MyStates = BBStates[EntryBB];
2336 MyStates.SetAsEntry();
2337 TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
2338 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
Dan Gohmana53a12c2011-12-12 19:42:25 +00002339 Visited.insert(EntryBB);
2340 OnStack.insert(EntryBB);
2341 do {
2342 dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002343 BasicBlock *CurrBB = SuccStack.back().first;
2344 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
2345 succ_iterator SE(TI, false);
Dan Gohman41375a32012-05-08 23:39:44 +00002346
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002347 while (SuccStack.back().second != SE) {
2348 BasicBlock *SuccBB = *SuccStack.back().second++;
2349 if (Visited.insert(SuccBB)) {
Dan Gohman41375a32012-05-08 23:39:44 +00002350 TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
2351 SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002352 BBStates[CurrBB].addSucc(SuccBB);
Dan Gohman41375a32012-05-08 23:39:44 +00002353 BBState &SuccStates = BBStates[SuccBB];
2354 SuccStates.addPred(CurrBB);
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002355 OnStack.insert(SuccBB);
Dan Gohmana53a12c2011-12-12 19:42:25 +00002356 goto dfs_next_succ;
2357 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002358
2359 if (!OnStack.count(SuccBB)) {
2360 BBStates[CurrBB].addSucc(SuccBB);
2361 BBStates[SuccBB].addPred(CurrBB);
2362 }
Dan Gohmana53a12c2011-12-12 19:42:25 +00002363 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002364 OnStack.erase(CurrBB);
2365 PostOrder.push_back(CurrBB);
2366 SuccStack.pop_back();
Dan Gohmana53a12c2011-12-12 19:42:25 +00002367 } while (!SuccStack.empty());
2368
2369 Visited.clear();
2370
Dan Gohmana53a12c2011-12-12 19:42:25 +00002371 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002372 // Functions may have many exits, and there also blocks which we treat
2373 // as exits due to ignored edges.
2374 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
2375 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
2376 BasicBlock *ExitBB = I;
2377 BBState &MyStates = BBStates[ExitBB];
2378 if (!MyStates.isExit())
2379 continue;
2380
Dan Gohmandae33492012-04-27 18:56:31 +00002381 MyStates.SetAsExit();
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002382
2383 PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00002384 Visited.insert(ExitBB);
2385 while (!PredStack.empty()) {
2386 reverse_dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002387 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
2388 while (PredStack.back().second != PE) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00002389 BasicBlock *BB = *PredStack.back().second++;
Dan Gohmana53a12c2011-12-12 19:42:25 +00002390 if (Visited.insert(BB)) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002391 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00002392 goto reverse_dfs_next_succ;
2393 }
2394 }
2395 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
2396 }
2397 }
2398}
2399
Michael Gottesman97e3df02013-01-14 00:35:14 +00002400// Visit the function both top-down and bottom-up.
John McCalld935e9c2011-06-15 23:37:01 +00002401bool
2402ObjCARCOpt::Visit(Function &F,
2403 DenseMap<const BasicBlock *, BBState> &BBStates,
2404 MapVector<Value *, RRInfo> &Retains,
2405 DenseMap<Value *, RRInfo> &Releases) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00002406
2407 // Use reverse-postorder traversals, because we magically know that loops
2408 // will be well behaved, i.e. they won't repeatedly call retain on a single
2409 // pointer without doing a release. We can't use the ReversePostOrderTraversal
2410 // class here because we want the reverse-CFG postorder to consider each
2411 // function exit point, and we want to ignore selected cycle edges.
2412 SmallVector<BasicBlock *, 16> PostOrder;
2413 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002414 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
2415 NoObjCARCExceptionsMDKind,
2416 BBStates);
Dan Gohmana53a12c2011-12-12 19:42:25 +00002417
2418 // Use reverse-postorder on the reverse CFG for bottom-up.
John McCalld935e9c2011-06-15 23:37:01 +00002419 bool BottomUpNestingDetected = false;
Dan Gohmanc57b58c2011-08-18 21:27:42 +00002420 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
Dan Gohmana53a12c2011-12-12 19:42:25 +00002421 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
2422 I != E; ++I)
2423 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
John McCalld935e9c2011-06-15 23:37:01 +00002424
Dan Gohmana53a12c2011-12-12 19:42:25 +00002425 // Use reverse-postorder for top-down.
John McCalld935e9c2011-06-15 23:37:01 +00002426 bool TopDownNestingDetected = false;
Dan Gohmana53a12c2011-12-12 19:42:25 +00002427 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2428 PostOrder.rbegin(), E = PostOrder.rend();
2429 I != E; ++I)
2430 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
John McCalld935e9c2011-06-15 23:37:01 +00002431
2432 return TopDownNestingDetected && BottomUpNestingDetected;
2433}
2434
Michael Gottesman97e3df02013-01-14 00:35:14 +00002435/// Move the calls in RetainsToMove and ReleasesToMove.
John McCalld935e9c2011-06-15 23:37:01 +00002436void ObjCARCOpt::MoveCalls(Value *Arg,
2437 RRInfo &RetainsToMove,
2438 RRInfo &ReleasesToMove,
2439 MapVector<Value *, RRInfo> &Retains,
2440 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman6320f522011-07-22 22:29:21 +00002441 SmallVectorImpl<Instruction *> &DeadInsts,
Michael Gottesman79249972013-04-05 23:46:45 +00002442 Module *M) {
Chris Lattner229907c2011-07-18 04:54:35 +00002443 Type *ArgTy = Arg->getType();
Dan Gohman6320f522011-07-22 22:29:21 +00002444 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
Michael Gottesman79249972013-04-05 23:46:45 +00002445
Michael Gottesman89279f82013-04-05 18:10:41 +00002446 DEBUG(dbgs() << "== ObjCARCOpt::MoveCalls ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00002447
John McCalld935e9c2011-06-15 23:37:01 +00002448 // Insert the new retain and release calls.
2449 for (SmallPtrSet<Instruction *, 2>::const_iterator
2450 PI = ReleasesToMove.ReverseInsertPts.begin(),
2451 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2452 Instruction *InsertPt = *PI;
2453 Value *MyArg = ArgTy == ParamTy ? Arg :
2454 new BitCastInst(Arg, ParamTy, "", InsertPt);
2455 CallInst *Call =
Michael Gottesmanba648592013-03-28 23:08:44 +00002456 CallInst::Create(getRetainCallee(M), MyArg, "", InsertPt);
John McCalld935e9c2011-06-15 23:37:01 +00002457 Call->setDoesNotThrow();
Michael Gottesmanba648592013-03-28 23:08:44 +00002458 Call->setTailCall();
Michael Gottesman60f6b282013-03-29 05:13:07 +00002459
Michael Gottesmandf110ac2013-04-21 00:30:50 +00002460 DEBUG(dbgs() << "Inserting new Retain: " << *Call << "\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00002461 "At insertion point: " << *InsertPt << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002462 }
2463 for (SmallPtrSet<Instruction *, 2>::const_iterator
2464 PI = RetainsToMove.ReverseInsertPts.begin(),
2465 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00002466 Instruction *InsertPt = *PI;
2467 Value *MyArg = ArgTy == ParamTy ? Arg :
2468 new BitCastInst(Arg, ParamTy, "", InsertPt);
2469 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
2470 "", InsertPt);
2471 // Attach a clang.imprecise_release metadata tag, if appropriate.
2472 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
2473 Call->setMetadata(ImpreciseReleaseMDKind, M);
2474 Call->setDoesNotThrow();
2475 if (ReleasesToMove.IsTailCallRelease)
2476 Call->setTailCall();
Michael Gottesmanc189a392013-01-09 19:23:24 +00002477
Michael Gottesman89279f82013-04-05 18:10:41 +00002478 DEBUG(dbgs() << "Inserting new Release: " << *Call << "\n"
2479 "At insertion point: " << *InsertPt << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002480 }
2481
2482 // Delete the original retain and release calls.
2483 for (SmallPtrSet<Instruction *, 2>::const_iterator
2484 AI = RetainsToMove.Calls.begin(),
2485 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
2486 Instruction *OrigRetain = *AI;
2487 Retains.blot(OrigRetain);
2488 DeadInsts.push_back(OrigRetain);
Michael Gottesman89279f82013-04-05 18:10:41 +00002489 DEBUG(dbgs() << "Deleting retain: " << *OrigRetain << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002490 }
2491 for (SmallPtrSet<Instruction *, 2>::const_iterator
2492 AI = ReleasesToMove.Calls.begin(),
2493 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
2494 Instruction *OrigRelease = *AI;
2495 Releases.erase(OrigRelease);
2496 DeadInsts.push_back(OrigRelease);
Michael Gottesman89279f82013-04-05 18:10:41 +00002497 DEBUG(dbgs() << "Deleting release: " << *OrigRelease << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002498 }
Michael Gottesman79249972013-04-05 23:46:45 +00002499
John McCalld935e9c2011-06-15 23:37:01 +00002500}
2501
Michael Gottesman9de6f962013-01-22 21:49:00 +00002502bool
2503ObjCARCOpt::ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState>
2504 &BBStates,
2505 MapVector<Value *, RRInfo> &Retains,
2506 DenseMap<Value *, RRInfo> &Releases,
2507 Module *M,
2508 SmallVector<Instruction *, 4> &NewRetains,
2509 SmallVector<Instruction *, 4> &NewReleases,
2510 SmallVector<Instruction *, 8> &DeadInsts,
2511 RRInfo &RetainsToMove,
2512 RRInfo &ReleasesToMove,
2513 Value *Arg,
2514 bool KnownSafe,
2515 bool &AnyPairsCompletelyEliminated) {
2516 // If a pair happens in a region where it is known that the reference count
Michael Gottesmana76143ee2013-05-13 23:49:42 +00002517 // is already incremented, we can similarly ignore possible decrements unless
2518 // we are dealing with a retainable object with multiple provenance sources.
Michael Gottesman9de6f962013-01-22 21:49:00 +00002519 bool KnownSafeTD = true, KnownSafeBU = true;
Michael Gottesmana76143ee2013-05-13 23:49:42 +00002520 bool MultipleOwners = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00002521 bool CFGHazardAfflicted = false;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002522
2523 // Connect the dots between the top-down-collected RetainsToMove and
2524 // bottom-up-collected ReleasesToMove to form sets of related calls.
2525 // This is an iterative process so that we connect multiple releases
2526 // to multiple retains if needed.
2527 unsigned OldDelta = 0;
2528 unsigned NewDelta = 0;
2529 unsigned OldCount = 0;
2530 unsigned NewCount = 0;
2531 bool FirstRelease = true;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002532 for (;;) {
2533 for (SmallVectorImpl<Instruction *>::const_iterator
2534 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
2535 Instruction *NewRetain = *NI;
2536 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
2537 assert(It != Retains.end());
2538 const RRInfo &NewRetainRRI = It->second;
2539 KnownSafeTD &= NewRetainRRI.KnownSafe;
Michael Gottesman5a91bbf2013-05-24 20:44:02 +00002540 MultipleOwners =
2541 MultipleOwners || MultiOwnersSet.count(GetObjCArg(NewRetain));
Michael Gottesman9de6f962013-01-22 21:49:00 +00002542 for (SmallPtrSet<Instruction *, 2>::const_iterator
2543 LI = NewRetainRRI.Calls.begin(),
2544 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
2545 Instruction *NewRetainRelease = *LI;
2546 DenseMap<Value *, RRInfo>::const_iterator Jt =
2547 Releases.find(NewRetainRelease);
2548 if (Jt == Releases.end())
2549 return false;
2550 const RRInfo &NewRetainReleaseRRI = Jt->second;
2551 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
2552 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002553
2554 // If we overflow when we compute the path count, don't remove/move
2555 // anything.
2556 const BBState &NRRBBState = BBStates[NewRetainRelease->getParent()];
2557 unsigned PathCount;
2558 if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
2559 return false;
2560 OldDelta -= PathCount;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002561
2562 // Merge the ReleaseMetadata and IsTailCallRelease values.
2563 if (FirstRelease) {
2564 ReleasesToMove.ReleaseMetadata =
2565 NewRetainReleaseRRI.ReleaseMetadata;
2566 ReleasesToMove.IsTailCallRelease =
2567 NewRetainReleaseRRI.IsTailCallRelease;
2568 FirstRelease = false;
2569 } else {
2570 if (ReleasesToMove.ReleaseMetadata !=
2571 NewRetainReleaseRRI.ReleaseMetadata)
2572 ReleasesToMove.ReleaseMetadata = 0;
2573 if (ReleasesToMove.IsTailCallRelease !=
2574 NewRetainReleaseRRI.IsTailCallRelease)
2575 ReleasesToMove.IsTailCallRelease = false;
2576 }
2577
2578 // Collect the optimal insertion points.
2579 if (!KnownSafe)
2580 for (SmallPtrSet<Instruction *, 2>::const_iterator
2581 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
2582 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
2583 RI != RE; ++RI) {
2584 Instruction *RIP = *RI;
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002585 if (ReleasesToMove.ReverseInsertPts.insert(RIP)) {
2586 // If we overflow when we compute the path count, don't
2587 // remove/move anything.
2588 const BBState &RIPBBState = BBStates[RIP->getParent()];
2589 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
2590 return false;
2591 NewDelta -= PathCount;
2592 }
Michael Gottesman9de6f962013-01-22 21:49:00 +00002593 }
2594 NewReleases.push_back(NewRetainRelease);
2595 }
2596 }
2597 }
2598 NewRetains.clear();
2599 if (NewReleases.empty()) break;
2600
2601 // Back the other way.
2602 for (SmallVectorImpl<Instruction *>::const_iterator
2603 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
2604 Instruction *NewRelease = *NI;
2605 DenseMap<Value *, RRInfo>::const_iterator It =
2606 Releases.find(NewRelease);
2607 assert(It != Releases.end());
2608 const RRInfo &NewReleaseRRI = It->second;
2609 KnownSafeBU &= NewReleaseRRI.KnownSafe;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00002610 CFGHazardAfflicted |= NewReleaseRRI.CFGHazardAfflicted;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002611 for (SmallPtrSet<Instruction *, 2>::const_iterator
2612 LI = NewReleaseRRI.Calls.begin(),
2613 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
2614 Instruction *NewReleaseRetain = *LI;
2615 MapVector<Value *, RRInfo>::const_iterator Jt =
2616 Retains.find(NewReleaseRetain);
2617 if (Jt == Retains.end())
2618 return false;
2619 const RRInfo &NewReleaseRetainRRI = Jt->second;
2620 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
2621 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002622
2623 // If we overflow when we compute the path count, don't remove/move
2624 // anything.
2625 const BBState &NRRBBState = BBStates[NewReleaseRetain->getParent()];
2626 unsigned PathCount;
2627 if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
2628 return false;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002629 OldDelta += PathCount;
2630 OldCount += PathCount;
2631
Michael Gottesman9de6f962013-01-22 21:49:00 +00002632 // Collect the optimal insertion points.
2633 if (!KnownSafe)
2634 for (SmallPtrSet<Instruction *, 2>::const_iterator
2635 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
2636 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
2637 RI != RE; ++RI) {
2638 Instruction *RIP = *RI;
2639 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002640 // If we overflow when we compute the path count, don't
2641 // remove/move anything.
2642 const BBState &RIPBBState = BBStates[RIP->getParent()];
2643 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
2644 return false;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002645 NewDelta += PathCount;
2646 NewCount += PathCount;
2647 }
2648 }
2649 NewRetains.push_back(NewReleaseRetain);
2650 }
2651 }
2652 }
2653 NewReleases.clear();
2654 if (NewRetains.empty()) break;
2655 }
2656
Michael Gottesmana76143ee2013-05-13 23:49:42 +00002657 // If the pointer is known incremented in 1 direction and we do not have
2658 // MultipleOwners, we can safely remove the retain/releases. Otherwise we need
2659 // to be known safe in both directions.
2660 bool UnconditionallySafe = (KnownSafeTD && KnownSafeBU) ||
2661 ((KnownSafeTD || KnownSafeBU) && !MultipleOwners);
2662 if (UnconditionallySafe) {
Michael Gottesman9de6f962013-01-22 21:49:00 +00002663 RetainsToMove.ReverseInsertPts.clear();
2664 ReleasesToMove.ReverseInsertPts.clear();
2665 NewCount = 0;
2666 } else {
2667 // Determine whether the new insertion points we computed preserve the
2668 // balance of retain and release calls through the program.
2669 // TODO: If the fully aggressive solution isn't valid, try to find a
2670 // less aggressive solution which is.
2671 if (NewDelta != 0)
2672 return false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00002673
2674 // At this point, we are not going to remove any RR pairs, but we still are
2675 // able to move RR pairs. If one of our pointers is afflicted with
2676 // CFGHazards, we cannot perform such code motion so exit early.
2677 const bool WillPerformCodeMotion = RetainsToMove.ReverseInsertPts.size() ||
2678 ReleasesToMove.ReverseInsertPts.size();
2679 if (CFGHazardAfflicted && WillPerformCodeMotion)
2680 return false;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002681 }
2682
2683 // Determine whether the original call points are balanced in the retain and
2684 // release calls through the program. If not, conservatively don't touch
2685 // them.
2686 // TODO: It's theoretically possible to do code motion in this case, as
2687 // long as the existing imbalances are maintained.
2688 if (OldDelta != 0)
2689 return false;
Michael Gottesman8005ad32013-04-29 06:16:55 +00002690
Michael Gottesmana87bb8f2013-04-29 05:13:13 +00002691#ifdef ARC_ANNOTATIONS
2692 // Do not move calls if ARC annotations are requested.
Michael Gottesman3e3977c2013-04-29 05:25:39 +00002693 if (EnableARCAnnotations)
2694 return false;
Michael Gottesmana87bb8f2013-04-29 05:13:13 +00002695#endif // ARC_ANNOTATIONS
Michael Gottesman9de6f962013-01-22 21:49:00 +00002696
2697 Changed = true;
2698 assert(OldCount != 0 && "Unreachable code?");
2699 NumRRs += OldCount - NewCount;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002700 // Set to true if we completely removed any RR pairs.
Michael Gottesman8b5515f2013-01-22 21:53:43 +00002701 AnyPairsCompletelyEliminated = NewCount == 0;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002702
2703 // We can move calls!
2704 return true;
2705}
2706
Michael Gottesman97e3df02013-01-14 00:35:14 +00002707/// Identify pairings between the retains and releases, and delete and/or move
2708/// them.
John McCalld935e9c2011-06-15 23:37:01 +00002709bool
2710ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
2711 &BBStates,
2712 MapVector<Value *, RRInfo> &Retains,
Dan Gohman6320f522011-07-22 22:29:21 +00002713 DenseMap<Value *, RRInfo> &Releases,
2714 Module *M) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002715 DEBUG(dbgs() << "\n== ObjCARCOpt::PerformCodePlacement ==\n");
2716
John McCalld935e9c2011-06-15 23:37:01 +00002717 bool AnyPairsCompletelyEliminated = false;
2718 RRInfo RetainsToMove;
2719 RRInfo ReleasesToMove;
2720 SmallVector<Instruction *, 4> NewRetains;
2721 SmallVector<Instruction *, 4> NewReleases;
2722 SmallVector<Instruction *, 8> DeadInsts;
2723
Dan Gohman670f9372012-04-13 18:57:48 +00002724 // Visit each retain.
John McCalld935e9c2011-06-15 23:37:01 +00002725 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
Dan Gohman2053a5d2011-09-29 22:25:23 +00002726 E = Retains.end(); I != E; ++I) {
2727 Value *V = I->first;
John McCalld935e9c2011-06-15 23:37:01 +00002728 if (!V) continue; // blotted
2729
2730 Instruction *Retain = cast<Instruction>(V);
Michael Gottesmanc189a392013-01-09 19:23:24 +00002731
Michael Gottesman89279f82013-04-05 18:10:41 +00002732 DEBUG(dbgs() << "Visiting: " << *Retain << "\n");
Michael Gottesmanc189a392013-01-09 19:23:24 +00002733
John McCalld935e9c2011-06-15 23:37:01 +00002734 Value *Arg = GetObjCArg(Retain);
2735
Dan Gohman728db492012-01-13 00:39:07 +00002736 // If the object being released is in static or stack storage, we know it's
John McCalld935e9c2011-06-15 23:37:01 +00002737 // not being managed by ObjC reference counting, so we can delete pairs
2738 // regardless of what possible decrements or uses lie between them.
Dan Gohman728db492012-01-13 00:39:07 +00002739 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
Dan Gohman41375a32012-05-08 23:39:44 +00002740
Dan Gohman56e1cef2011-08-22 17:29:11 +00002741 // A constant pointer can't be pointing to an object on the heap. It may
2742 // be reference-counted, but it won't be deleted.
2743 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
2744 if (const GlobalVariable *GV =
2745 dyn_cast<GlobalVariable>(
2746 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
2747 if (GV->isConstant())
2748 KnownSafe = true;
2749
John McCalld935e9c2011-06-15 23:37:01 +00002750 // Connect the dots between the top-down-collected RetainsToMove and
2751 // bottom-up-collected ReleasesToMove to form sets of related calls.
John McCalld935e9c2011-06-15 23:37:01 +00002752 NewRetains.push_back(Retain);
Michael Gottesman9de6f962013-01-22 21:49:00 +00002753 bool PerformMoveCalls =
2754 ConnectTDBUTraversals(BBStates, Retains, Releases, M, NewRetains,
2755 NewReleases, DeadInsts, RetainsToMove,
2756 ReleasesToMove, Arg, KnownSafe,
2757 AnyPairsCompletelyEliminated);
John McCalld935e9c2011-06-15 23:37:01 +00002758
Michael Gottesman9de6f962013-01-22 21:49:00 +00002759 if (PerformMoveCalls) {
2760 // Ok, everything checks out and we're all set. Let's move/delete some
2761 // code!
2762 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
2763 Retains, Releases, DeadInsts, M);
John McCalld935e9c2011-06-15 23:37:01 +00002764 }
2765
Michael Gottesman9de6f962013-01-22 21:49:00 +00002766 // Clean up state for next retain.
John McCalld935e9c2011-06-15 23:37:01 +00002767 NewReleases.clear();
2768 NewRetains.clear();
2769 RetainsToMove.clear();
2770 ReleasesToMove.clear();
2771 }
2772
2773 // Now that we're done moving everything, we can delete the newly dead
2774 // instructions, as we no longer need them as insert points.
2775 while (!DeadInsts.empty())
2776 EraseInstruction(DeadInsts.pop_back_val());
2777
2778 return AnyPairsCompletelyEliminated;
2779}
2780
Michael Gottesman97e3df02013-01-14 00:35:14 +00002781/// Weak pointer optimizations.
John McCalld935e9c2011-06-15 23:37:01 +00002782void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002783 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeWeakCalls ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00002784
John McCalld935e9c2011-06-15 23:37:01 +00002785 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
2786 // itself because it uses AliasAnalysis and we need to do provenance
2787 // queries instead.
2788 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2789 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +00002790
Michael Gottesman89279f82013-04-05 18:10:41 +00002791 DEBUG(dbgs() << "Visiting: " << *Inst << "\n");
Michael Gottesman3f146e22013-01-01 16:05:48 +00002792
John McCalld935e9c2011-06-15 23:37:01 +00002793 InstructionClass Class = GetBasicInstructionClass(Inst);
2794 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
2795 continue;
2796
2797 // Delete objc_loadWeak calls with no users.
2798 if (Class == IC_LoadWeak && Inst->use_empty()) {
2799 Inst->eraseFromParent();
2800 continue;
2801 }
2802
2803 // TODO: For now, just look for an earlier available version of this value
2804 // within the same block. Theoretically, we could do memdep-style non-local
2805 // analysis too, but that would want caching. A better approach would be to
2806 // use the technique that EarlyCSE uses.
2807 inst_iterator Current = llvm::prior(I);
2808 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
2809 for (BasicBlock::iterator B = CurrentBB->begin(),
2810 J = Current.getInstructionIterator();
2811 J != B; --J) {
2812 Instruction *EarlierInst = &*llvm::prior(J);
2813 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
2814 switch (EarlierClass) {
2815 case IC_LoadWeak:
2816 case IC_LoadWeakRetained: {
2817 // If this is loading from the same pointer, replace this load's value
2818 // with that one.
2819 CallInst *Call = cast<CallInst>(Inst);
2820 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2821 Value *Arg = Call->getArgOperand(0);
2822 Value *EarlierArg = EarlierCall->getArgOperand(0);
2823 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2824 case AliasAnalysis::MustAlias:
2825 Changed = true;
2826 // If the load has a builtin retain, insert a plain retain for it.
2827 if (Class == IC_LoadWeakRetained) {
2828 CallInst *CI =
2829 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
2830 "", Call);
2831 CI->setTailCall();
2832 }
2833 // Zap the fully redundant load.
2834 Call->replaceAllUsesWith(EarlierCall);
2835 Call->eraseFromParent();
2836 goto clobbered;
2837 case AliasAnalysis::MayAlias:
2838 case AliasAnalysis::PartialAlias:
2839 goto clobbered;
2840 case AliasAnalysis::NoAlias:
2841 break;
2842 }
2843 break;
2844 }
2845 case IC_StoreWeak:
2846 case IC_InitWeak: {
2847 // If this is storing to the same pointer and has the same size etc.
2848 // replace this load's value with the stored value.
2849 CallInst *Call = cast<CallInst>(Inst);
2850 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2851 Value *Arg = Call->getArgOperand(0);
2852 Value *EarlierArg = EarlierCall->getArgOperand(0);
2853 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2854 case AliasAnalysis::MustAlias:
2855 Changed = true;
2856 // If the load has a builtin retain, insert a plain retain for it.
2857 if (Class == IC_LoadWeakRetained) {
2858 CallInst *CI =
2859 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
2860 "", Call);
2861 CI->setTailCall();
2862 }
2863 // Zap the fully redundant load.
2864 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
2865 Call->eraseFromParent();
2866 goto clobbered;
2867 case AliasAnalysis::MayAlias:
2868 case AliasAnalysis::PartialAlias:
2869 goto clobbered;
2870 case AliasAnalysis::NoAlias:
2871 break;
2872 }
2873 break;
2874 }
2875 case IC_MoveWeak:
2876 case IC_CopyWeak:
2877 // TOOD: Grab the copied value.
2878 goto clobbered;
2879 case IC_AutoreleasepoolPush:
2880 case IC_None:
John McCall20182ac2013-03-22 21:38:36 +00002881 case IC_IntrinsicUser:
John McCalld935e9c2011-06-15 23:37:01 +00002882 case IC_User:
2883 // Weak pointers are only modified through the weak entry points
2884 // (and arbitrary calls, which could call the weak entry points).
2885 break;
2886 default:
2887 // Anything else could modify the weak pointer.
2888 goto clobbered;
2889 }
2890 }
2891 clobbered:;
2892 }
2893
2894 // Then, for each destroyWeak with an alloca operand, check to see if
2895 // the alloca and all its users can be zapped.
2896 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2897 Instruction *Inst = &*I++;
2898 InstructionClass Class = GetBasicInstructionClass(Inst);
2899 if (Class != IC_DestroyWeak)
2900 continue;
2901
2902 CallInst *Call = cast<CallInst>(Inst);
2903 Value *Arg = Call->getArgOperand(0);
2904 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
2905 for (Value::use_iterator UI = Alloca->use_begin(),
2906 UE = Alloca->use_end(); UI != UE; ++UI) {
Dan Gohmandae33492012-04-27 18:56:31 +00002907 const Instruction *UserInst = cast<Instruction>(*UI);
John McCalld935e9c2011-06-15 23:37:01 +00002908 switch (GetBasicInstructionClass(UserInst)) {
2909 case IC_InitWeak:
2910 case IC_StoreWeak:
2911 case IC_DestroyWeak:
2912 continue;
2913 default:
2914 goto done;
2915 }
2916 }
2917 Changed = true;
2918 for (Value::use_iterator UI = Alloca->use_begin(),
2919 UE = Alloca->use_end(); UI != UE; ) {
2920 CallInst *UserInst = cast<CallInst>(*UI++);
Dan Gohman14862c32012-05-18 22:17:29 +00002921 switch (GetBasicInstructionClass(UserInst)) {
2922 case IC_InitWeak:
2923 case IC_StoreWeak:
2924 // These functions return their second argument.
2925 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
2926 break;
2927 case IC_DestroyWeak:
2928 // No return value.
2929 break;
2930 default:
Dan Gohman9c97eea02012-05-21 17:41:28 +00002931 llvm_unreachable("alloca really is used!");
Dan Gohman14862c32012-05-18 22:17:29 +00002932 }
John McCalld935e9c2011-06-15 23:37:01 +00002933 UserInst->eraseFromParent();
2934 }
2935 Alloca->eraseFromParent();
2936 done:;
2937 }
2938 }
2939}
2940
Michael Gottesman97e3df02013-01-14 00:35:14 +00002941/// Identify program paths which execute sequences of retains and releases which
2942/// can be eliminated.
John McCalld935e9c2011-06-15 23:37:01 +00002943bool ObjCARCOpt::OptimizeSequences(Function &F) {
Michael Gottesman740db972013-05-23 02:35:21 +00002944 // Releases, Retains - These are used to store the results of the main flow
2945 // analysis. These use Value* as the key instead of Instruction* so that the
2946 // map stays valid when we get around to rewriting code and calls get
2947 // replaced by arguments.
John McCalld935e9c2011-06-15 23:37:01 +00002948 DenseMap<Value *, RRInfo> Releases;
2949 MapVector<Value *, RRInfo> Retains;
2950
Michael Gottesman740db972013-05-23 02:35:21 +00002951 // This is used during the traversal of the function to track the
2952 // states for each identified object at each block.
John McCalld935e9c2011-06-15 23:37:01 +00002953 DenseMap<const BasicBlock *, BBState> BBStates;
2954
2955 // Analyze the CFG of the function, and all instructions.
2956 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
2957
2958 // Transform.
Michael Gottesman5a91bbf2013-05-24 20:44:02 +00002959 bool AnyPairsCompletelyEliminated = PerformCodePlacement(BBStates, Retains,
2960 Releases,
2961 F.getParent());
2962
2963 // Cleanup.
2964 MultiOwnersSet.clear();
2965
2966 return AnyPairsCompletelyEliminated && NestingDetected;
John McCalld935e9c2011-06-15 23:37:01 +00002967}
2968
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002969/// Check if there is a dependent call earlier that does not have anything in
2970/// between the Retain and the call that can affect the reference count of their
2971/// shared pointer argument. Note that Retain need not be in BB.
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002972static bool
2973HasSafePathToPredecessorCall(const Value *Arg, Instruction *Retain,
2974 SmallPtrSet<Instruction *, 4> &DepInsts,
2975 SmallPtrSet<const BasicBlock *, 4> &Visited,
2976 ProvenanceAnalysis &PA) {
2977 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
2978 DepInsts, Visited, PA);
2979 if (DepInsts.size() != 1)
2980 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002981
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002982 CallInst *Call =
2983 dyn_cast_or_null<CallInst>(*DepInsts.begin());
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002984
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002985 // Check that the pointer is the return value of the call.
2986 if (!Call || Arg != Call)
2987 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002988
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002989 // Check that the call is a regular call.
2990 InstructionClass Class = GetBasicInstructionClass(Call);
2991 if (Class != IC_CallOrUser && Class != IC_Call)
2992 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002993
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002994 return true;
2995}
2996
Michael Gottesman6908db12013-04-03 23:16:05 +00002997/// Find a dependent retain that precedes the given autorelease for which there
2998/// is nothing in between the two instructions that can affect the ref count of
2999/// Arg.
3000static CallInst *
3001FindPredecessorRetainWithSafePath(const Value *Arg, BasicBlock *BB,
3002 Instruction *Autorelease,
3003 SmallPtrSet<Instruction *, 4> &DepInsts,
3004 SmallPtrSet<const BasicBlock *, 4> &Visited,
3005 ProvenanceAnalysis &PA) {
3006 FindDependencies(CanChangeRetainCount, Arg,
3007 BB, Autorelease, DepInsts, Visited, PA);
3008 if (DepInsts.size() != 1)
3009 return 0;
Michael Gottesman79249972013-04-05 23:46:45 +00003010
Michael Gottesman6908db12013-04-03 23:16:05 +00003011 CallInst *Retain =
3012 dyn_cast_or_null<CallInst>(*DepInsts.begin());
Michael Gottesman79249972013-04-05 23:46:45 +00003013
Michael Gottesman6908db12013-04-03 23:16:05 +00003014 // Check that we found a retain with the same argument.
3015 if (!Retain ||
3016 !IsRetain(GetBasicInstructionClass(Retain)) ||
3017 GetObjCArg(Retain) != Arg) {
3018 return 0;
3019 }
Michael Gottesman79249972013-04-05 23:46:45 +00003020
Michael Gottesman6908db12013-04-03 23:16:05 +00003021 return Retain;
3022}
3023
Michael Gottesman21a4ed32013-04-03 23:39:14 +00003024/// Look for an ``autorelease'' instruction dependent on Arg such that there are
3025/// no instructions dependent on Arg that need a positive ref count in between
3026/// the autorelease and the ret.
3027static CallInst *
3028FindPredecessorAutoreleaseWithSafePath(const Value *Arg, BasicBlock *BB,
3029 ReturnInst *Ret,
3030 SmallPtrSet<Instruction *, 4> &DepInsts,
3031 SmallPtrSet<const BasicBlock *, 4> &V,
3032 ProvenanceAnalysis &PA) {
3033 FindDependencies(NeedsPositiveRetainCount, Arg,
3034 BB, Ret, DepInsts, V, PA);
3035 if (DepInsts.size() != 1)
3036 return 0;
Michael Gottesman79249972013-04-05 23:46:45 +00003037
Michael Gottesman21a4ed32013-04-03 23:39:14 +00003038 CallInst *Autorelease =
3039 dyn_cast_or_null<CallInst>(*DepInsts.begin());
3040 if (!Autorelease)
3041 return 0;
3042 InstructionClass AutoreleaseClass = GetBasicInstructionClass(Autorelease);
3043 if (!IsAutorelease(AutoreleaseClass))
3044 return 0;
3045 if (GetObjCArg(Autorelease) != Arg)
3046 return 0;
Michael Gottesman79249972013-04-05 23:46:45 +00003047
Michael Gottesman21a4ed32013-04-03 23:39:14 +00003048 return Autorelease;
3049}
3050
Michael Gottesman97e3df02013-01-14 00:35:14 +00003051/// Look for this pattern:
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00003052/// \code
John McCalld935e9c2011-06-15 23:37:01 +00003053/// %call = call i8* @something(...)
3054/// %2 = call i8* @objc_retain(i8* %call)
3055/// %3 = call i8* @objc_autorelease(i8* %2)
3056/// ret i8* %3
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00003057/// \endcode
John McCalld935e9c2011-06-15 23:37:01 +00003058/// And delete the retain and autorelease.
John McCalld935e9c2011-06-15 23:37:01 +00003059void ObjCARCOpt::OptimizeReturns(Function &F) {
3060 if (!F.getReturnType()->isPointerTy())
3061 return;
Michael Gottesman79249972013-04-05 23:46:45 +00003062
Michael Gottesman89279f82013-04-05 18:10:41 +00003063 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeReturns ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00003064
John McCalld935e9c2011-06-15 23:37:01 +00003065 SmallPtrSet<Instruction *, 4> DependingInstructions;
3066 SmallPtrSet<const BasicBlock *, 4> Visited;
3067 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3068 BasicBlock *BB = FI;
3069 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
Michael Gottesman3f146e22013-01-01 16:05:48 +00003070
Michael Gottesman89279f82013-04-05 18:10:41 +00003071 DEBUG(dbgs() << "Visiting: " << *Ret << "\n");
Michael Gottesman3f146e22013-01-01 16:05:48 +00003072
Michael Gottesman21a4ed32013-04-03 23:39:14 +00003073 if (!Ret)
3074 continue;
Michael Gottesman79249972013-04-05 23:46:45 +00003075
John McCalld935e9c2011-06-15 23:37:01 +00003076 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
Michael Gottesman79249972013-04-05 23:46:45 +00003077
Michael Gottesmancdb7c152013-04-21 00:25:04 +00003078 // Look for an ``autorelease'' instruction that is a predecessor of Ret and
Michael Gottesman21a4ed32013-04-03 23:39:14 +00003079 // dependent on Arg such that there are no instructions dependent on Arg
3080 // that need a positive ref count in between the autorelease and Ret.
3081 CallInst *Autorelease =
3082 FindPredecessorAutoreleaseWithSafePath(Arg, BB, Ret,
3083 DependingInstructions, Visited,
3084 PA);
John McCalld935e9c2011-06-15 23:37:01 +00003085 DependingInstructions.clear();
3086 Visited.clear();
Michael Gottesmanfb9ece92013-04-21 00:25:01 +00003087
3088 if (!Autorelease)
3089 continue;
3090
3091 CallInst *Retain =
3092 FindPredecessorRetainWithSafePath(Arg, BB, Autorelease,
3093 DependingInstructions, Visited, PA);
3094 DependingInstructions.clear();
3095 Visited.clear();
3096
3097 if (!Retain)
3098 continue;
3099
3100 // Check that there is nothing that can affect the reference count
3101 // between the retain and the call. Note that Retain need not be in BB.
3102 bool HasSafePathToCall = HasSafePathToPredecessorCall(Arg, Retain,
3103 DependingInstructions,
3104 Visited, PA);
3105 DependingInstructions.clear();
3106 Visited.clear();
3107
3108 if (!HasSafePathToCall)
3109 continue;
3110
3111 // If so, we can zap the retain and autorelease.
3112 Changed = true;
3113 ++NumRets;
3114 DEBUG(dbgs() << "Erasing: " << *Retain << "\nErasing: "
3115 << *Autorelease << "\n");
3116 EraseInstruction(Retain);
3117 EraseInstruction(Autorelease);
John McCalld935e9c2011-06-15 23:37:01 +00003118 }
3119}
3120
Michael Gottesman9c118152013-04-29 06:16:57 +00003121#ifndef NDEBUG
3122void
3123ObjCARCOpt::GatherStatistics(Function &F, bool AfterOptimization) {
3124 llvm::Statistic &NumRetains =
3125 AfterOptimization? NumRetainsAfterOpt : NumRetainsBeforeOpt;
3126 llvm::Statistic &NumReleases =
3127 AfterOptimization? NumReleasesAfterOpt : NumReleasesBeforeOpt;
3128
3129 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3130 Instruction *Inst = &*I++;
3131 switch (GetBasicInstructionClass(Inst)) {
3132 default:
3133 break;
3134 case IC_Retain:
3135 ++NumRetains;
3136 break;
3137 case IC_Release:
3138 ++NumReleases;
3139 break;
3140 }
3141 }
3142}
3143#endif
3144
John McCalld935e9c2011-06-15 23:37:01 +00003145bool ObjCARCOpt::doInitialization(Module &M) {
3146 if (!EnableARCOpts)
3147 return false;
3148
Dan Gohman670f9372012-04-13 18:57:48 +00003149 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanceaac7c2011-06-20 23:20:43 +00003150 Run = ModuleHasARC(M);
3151 if (!Run)
3152 return false;
3153
John McCalld935e9c2011-06-15 23:37:01 +00003154 // Identify the imprecise release metadata kind.
3155 ImpreciseReleaseMDKind =
3156 M.getContext().getMDKindID("clang.imprecise_release");
Dan Gohmana7107f92011-10-17 22:53:25 +00003157 CopyOnEscapeMDKind =
3158 M.getContext().getMDKindID("clang.arc.copy_on_escape");
Dan Gohman0155f302012-02-17 18:59:53 +00003159 NoObjCARCExceptionsMDKind =
3160 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
Michael Gottesman81b1d432013-03-26 00:42:04 +00003161#ifdef ARC_ANNOTATIONS
3162 ARCAnnotationBottomUpMDKind =
3163 M.getContext().getMDKindID("llvm.arc.annotation.bottomup");
3164 ARCAnnotationTopDownMDKind =
3165 M.getContext().getMDKindID("llvm.arc.annotation.topdown");
3166 ARCAnnotationProvenanceSourceMDKind =
3167 M.getContext().getMDKindID("llvm.arc.annotation.provenancesource");
3168#endif // ARC_ANNOTATIONS
John McCalld935e9c2011-06-15 23:37:01 +00003169
John McCalld935e9c2011-06-15 23:37:01 +00003170 // Intuitively, objc_retain and others are nocapture, however in practice
3171 // they are not, because they return their argument value. And objc_release
Dan Gohmandae33492012-04-27 18:56:31 +00003172 // calls finalizers which can have arbitrary side effects.
John McCalld935e9c2011-06-15 23:37:01 +00003173
3174 // These are initialized lazily.
John McCalld935e9c2011-06-15 23:37:01 +00003175 AutoreleaseRVCallee = 0;
3176 ReleaseCallee = 0;
3177 RetainCallee = 0;
Dan Gohman6320f522011-07-22 22:29:21 +00003178 RetainBlockCallee = 0;
John McCalld935e9c2011-06-15 23:37:01 +00003179 AutoreleaseCallee = 0;
3180
3181 return false;
3182}
3183
3184bool ObjCARCOpt::runOnFunction(Function &F) {
3185 if (!EnableARCOpts)
3186 return false;
3187
Dan Gohmanceaac7c2011-06-20 23:20:43 +00003188 // If nothing in the Module uses ARC, don't do anything.
3189 if (!Run)
3190 return false;
3191
John McCalld935e9c2011-06-15 23:37:01 +00003192 Changed = false;
3193
Michael Gottesman89279f82013-04-05 18:10:41 +00003194 DEBUG(dbgs() << "<<< ObjCARCOpt: Visiting Function: " << F.getName() << " >>>"
3195 "\n");
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00003196
John McCalld935e9c2011-06-15 23:37:01 +00003197 PA.setAA(&getAnalysis<AliasAnalysis>());
3198
Michael Gottesman9fc50b82013-05-13 18:29:07 +00003199#ifndef NDEBUG
3200 if (AreStatisticsEnabled()) {
3201 GatherStatistics(F, false);
3202 }
3203#endif
3204
John McCalld935e9c2011-06-15 23:37:01 +00003205 // This pass performs several distinct transformations. As a compile-time aid
3206 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3207 // library functions aren't declared.
3208
Michael Gottesmancd5b0272013-04-24 22:18:15 +00003209 // Preliminary optimizations. This also computes UsedInThisFunction.
John McCalld935e9c2011-06-15 23:37:01 +00003210 OptimizeIndividualCalls(F);
3211
3212 // Optimizations for weak pointers.
3213 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3214 (1 << IC_LoadWeakRetained) |
3215 (1 << IC_StoreWeak) |
3216 (1 << IC_InitWeak) |
3217 (1 << IC_CopyWeak) |
3218 (1 << IC_MoveWeak) |
3219 (1 << IC_DestroyWeak)))
3220 OptimizeWeakCalls(F);
3221
3222 // Optimizations for retain+release pairs.
3223 if (UsedInThisFunction & ((1 << IC_Retain) |
3224 (1 << IC_RetainRV) |
3225 (1 << IC_RetainBlock)))
3226 if (UsedInThisFunction & (1 << IC_Release))
3227 // Run OptimizeSequences until it either stops making changes or
3228 // no retain+release pair nesting is detected.
3229 while (OptimizeSequences(F)) {}
3230
3231 // Optimizations if objc_autorelease is used.
Dan Gohman41375a32012-05-08 23:39:44 +00003232 if (UsedInThisFunction & ((1 << IC_Autorelease) |
3233 (1 << IC_AutoreleaseRV)))
John McCalld935e9c2011-06-15 23:37:01 +00003234 OptimizeReturns(F);
3235
Michael Gottesman9c118152013-04-29 06:16:57 +00003236 // Gather statistics after optimization.
3237#ifndef NDEBUG
3238 if (AreStatisticsEnabled()) {
3239 GatherStatistics(F, true);
3240 }
3241#endif
3242
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00003243 DEBUG(dbgs() << "\n");
3244
John McCalld935e9c2011-06-15 23:37:01 +00003245 return Changed;
3246}
3247
3248void ObjCARCOpt::releaseMemory() {
3249 PA.clear();
3250}
3251
Michael Gottesman97e3df02013-01-14 00:35:14 +00003252/// @}
3253///