blob: 25caab2f2f524ddc75906b88bcc9813f056694e7 [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 Gottesman4773a102013-06-21 05:42:08 +0000468 /// Conservatively merge the two RRInfo. Returns true if a partial merge has
469 /// occured, false otherwise.
470 bool Merge(const RRInfo &Other);
471
John McCalld935e9c2011-06-15 23:37:01 +0000472 };
473}
474
475void RRInfo::clear() {
Dan Gohmanb3894012011-08-19 00:26:36 +0000476 KnownSafe = false;
John McCalld935e9c2011-06-15 23:37:01 +0000477 IsTailCallRelease = false;
478 ReleaseMetadata = 0;
479 Calls.clear();
480 ReverseInsertPts.clear();
Michael Gottesmane67f40c2013-05-24 20:44:05 +0000481 CFGHazardAfflicted = false;
John McCalld935e9c2011-06-15 23:37:01 +0000482}
483
Michael Gottesman4773a102013-06-21 05:42:08 +0000484bool RRInfo::Merge(const RRInfo &Other) {
485 // Conservatively merge the ReleaseMetadata information.
486 if (ReleaseMetadata != Other.ReleaseMetadata)
487 ReleaseMetadata = 0;
488
489 // Conservatively merge the boolean state.
490 KnownSafe &= Other.KnownSafe;
491 IsTailCallRelease &= Other.IsTailCallRelease;
492 CFGHazardAfflicted |= Other.CFGHazardAfflicted;
493
494 // Merge the call sets.
495 Calls.insert(Other.Calls.begin(), Other.Calls.end());
496
497 // Merge the insert point sets. If there are any differences,
498 // that makes this a partial merge.
499 bool Partial = ReverseInsertPts.size() != Other.ReverseInsertPts.size();
500 for (SmallPtrSet<Instruction *, 2>::const_iterator
501 I = Other.ReverseInsertPts.begin(),
502 E = Other.ReverseInsertPts.end(); I != E; ++I)
503 Partial |= ReverseInsertPts.insert(*I);
504 return Partial;
505}
506
John McCalld935e9c2011-06-15 23:37:01 +0000507namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000508 /// \brief This class summarizes several per-pointer runtime properties which
509 /// are propogated through the flow graph.
John McCalld935e9c2011-06-15 23:37:01 +0000510 class PtrState {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000511 /// True if the reference count is known to be incremented.
Dan Gohman62079b42012-04-25 00:50:46 +0000512 bool KnownPositiveRefCount;
513
Bob Wilson798a7702013-04-09 22:15:51 +0000514 /// True if we've seen an opportunity for partial RR elimination, such as
Michael Gottesman97e3df02013-01-14 00:35:14 +0000515 /// pushing calls into a CFG triangle or into one side of a CFG diamond.
Dan Gohman62079b42012-04-25 00:50:46 +0000516 bool Partial;
John McCalld935e9c2011-06-15 23:37:01 +0000517
Michael Gottesman97e3df02013-01-14 00:35:14 +0000518 /// The current position in the sequence.
Dan Gohman41375a32012-05-08 23:39:44 +0000519 Sequence Seq : 8;
John McCalld935e9c2011-06-15 23:37:01 +0000520
521 public:
Michael Gottesman97e3df02013-01-14 00:35:14 +0000522 /// Unidirectional information about the current sequence.
523 ///
John McCalld935e9c2011-06-15 23:37:01 +0000524 /// TODO: Encapsulate this better.
525 RRInfo RRI;
526
Dan Gohmandf476e52012-09-04 23:16:20 +0000527 PtrState() : KnownPositiveRefCount(false), Partial(false),
Dan Gohman41375a32012-05-08 23:39:44 +0000528 Seq(S_None) {}
John McCalld935e9c2011-06-15 23:37:01 +0000529
Michael Gottesman93132252013-06-21 06:59:02 +0000530
531 bool IsKnownSafe() const {
532 return RRI.KnownSafe;
533 }
534
535 void SetKnownSafe(const bool NewValue) {
536 RRI.KnownSafe = NewValue;
537 }
538
Michael Gottesmanb82a1792013-06-21 07:00:44 +0000539 bool IsTailCallRelease() const {
540 return RRI.IsTailCallRelease;
541 }
542
543 void SetTailCallRelease(const bool NewValue) {
544 RRI.IsTailCallRelease = NewValue;
545 }
546
Michael Gottesmanf0401182013-06-21 19:12:38 +0000547 bool IsTrackingImpreciseReleases() {
548 return RRI.ReleaseMetadata != 0;
549 }
550
Michael Gottesmanf701d3f2013-06-21 07:03:07 +0000551 const MDNode *GetReleaseMetadata() const {
552 return RRI.ReleaseMetadata;
553 }
554
555 void SetReleaseMetadata(MDNode *NewValue) {
556 RRI.ReleaseMetadata = NewValue;
557 }
558
Michael Gottesman2f294592013-06-21 19:12:36 +0000559 bool IsCFGHazardAfflicted() const {
560 return RRI.CFGHazardAfflicted;
561 }
562
563 void SetCFGHazardAfflicted(const bool NewValue) {
564 RRI.CFGHazardAfflicted = NewValue;
565 }
566
Michael Gottesman415ddd72013-02-05 19:32:18 +0000567 void SetKnownPositiveRefCount() {
Michael Gottesmanf3f9e3b2013-05-14 00:08:09 +0000568 DEBUG(dbgs() << "Setting Known Positive.\n");
Dan Gohman62079b42012-04-25 00:50:46 +0000569 KnownPositiveRefCount = true;
Dan Gohman12130272011-08-12 00:26:31 +0000570 }
571
Michael Gottesman764b1cf2013-03-23 05:46:19 +0000572 void ClearKnownPositiveRefCount() {
Michael Gottesmanf3f9e3b2013-05-14 00:08:09 +0000573 DEBUG(dbgs() << "Clearing Known Positive.\n");
Dan Gohman62079b42012-04-25 00:50:46 +0000574 KnownPositiveRefCount = false;
John McCalld935e9c2011-06-15 23:37:01 +0000575 }
576
Michael Gottesman07beea42013-03-23 05:31:01 +0000577 bool HasKnownPositiveRefCount() const {
Dan Gohman62079b42012-04-25 00:50:46 +0000578 return KnownPositiveRefCount;
John McCalld935e9c2011-06-15 23:37:01 +0000579 }
580
Michael Gottesman415ddd72013-02-05 19:32:18 +0000581 void SetSeq(Sequence NewSeq) {
Michael Gottesman89279f82013-04-05 18:10:41 +0000582 DEBUG(dbgs() << "Old: " << Seq << "; New: " << NewSeq << "\n");
Michael Gottesman79249972013-04-05 23:46:45 +0000583 Seq = NewSeq;
John McCalld935e9c2011-06-15 23:37:01 +0000584 }
585
Michael Gottesman415ddd72013-02-05 19:32:18 +0000586 Sequence GetSeq() const {
John McCalld935e9c2011-06-15 23:37:01 +0000587 return Seq;
588 }
589
Michael Gottesman415ddd72013-02-05 19:32:18 +0000590 void ClearSequenceProgress() {
Dan Gohman62079b42012-04-25 00:50:46 +0000591 ResetSequenceProgress(S_None);
592 }
593
Michael Gottesman415ddd72013-02-05 19:32:18 +0000594 void ResetSequenceProgress(Sequence NewSeq) {
Michael Gottesman01338a42013-04-20 23:36:57 +0000595 DEBUG(dbgs() << "Resetting sequence progress.\n");
Michael Gottesman89279f82013-04-05 18:10:41 +0000596 SetSeq(NewSeq);
Dan Gohman62079b42012-04-25 00:50:46 +0000597 Partial = false;
John McCalld935e9c2011-06-15 23:37:01 +0000598 RRI.clear();
599 }
600
601 void Merge(const PtrState &Other, bool TopDown);
Michael Gottesman4f6ef112013-06-21 19:44:27 +0000602
603 void InsertCall(Instruction *I) {
604 RRI.Calls.insert(I);
605 }
606
607 void InsertReverseInsertPt(Instruction *I) {
608 RRI.ReverseInsertPts.insert(I);
609 }
610
611 void ClearReverseInsertPts() {
612 RRI.ReverseInsertPts.clear();
613 }
614
615 bool HasReverseInsertPts() const {
616 return !RRI.ReverseInsertPts.empty();
617 }
John McCalld935e9c2011-06-15 23:37:01 +0000618 };
619}
620
621void
622PtrState::Merge(const PtrState &Other, bool TopDown) {
623 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
Michael Gottesmanb7deb4c2013-06-21 06:54:31 +0000624 KnownPositiveRefCount &= Other.KnownPositiveRefCount;
Michael Gottesman60f6b282013-03-29 05:13:07 +0000625
Dan Gohman1736c142011-10-17 18:48:25 +0000626 // If we're not in a sequence (anymore), drop all associated state.
John McCalld935e9c2011-06-15 23:37:01 +0000627 if (Seq == S_None) {
Dan Gohman62079b42012-04-25 00:50:46 +0000628 Partial = false;
John McCalld935e9c2011-06-15 23:37:01 +0000629 RRI.clear();
Dan Gohman62079b42012-04-25 00:50:46 +0000630 } else if (Partial || Other.Partial) {
Dan Gohman1736c142011-10-17 18:48:25 +0000631 // If we're doing a merge on a path that's previously seen a partial
632 // merge, conservatively drop the sequence, to avoid doing partial
633 // RR elimination. If the branch predicates for the two merge differ,
634 // mixing them is unsafe.
Dan Gohman62079b42012-04-25 00:50:46 +0000635 ClearSequenceProgress();
John McCalld935e9c2011-06-15 23:37:01 +0000636 } else {
Michael Gottesmanb7deb4c2013-06-21 06:54:31 +0000637 // Otherwise merge the other PtrState's RRInfo into our RRInfo. At this
638 // point, we know that currently we are not partial. Stash whether or not
639 // the merge operation caused us to undergo a partial merging of reverse
640 // insertion points.
Michael Gottesman4773a102013-06-21 05:42:08 +0000641 Partial = RRI.Merge(Other.RRI);
John McCalld935e9c2011-06-15 23:37:01 +0000642 }
643}
644
645namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000646 /// \brief Per-BasicBlock state.
John McCalld935e9c2011-06-15 23:37:01 +0000647 class BBState {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000648 /// The number of unique control paths from the entry which can reach this
649 /// block.
John McCalld935e9c2011-06-15 23:37:01 +0000650 unsigned TopDownPathCount;
651
Michael Gottesman97e3df02013-01-14 00:35:14 +0000652 /// The number of unique control paths to exits from this block.
John McCalld935e9c2011-06-15 23:37:01 +0000653 unsigned BottomUpPathCount;
654
Michael Gottesman97e3df02013-01-14 00:35:14 +0000655 /// A type for PerPtrTopDown and PerPtrBottomUp.
John McCalld935e9c2011-06-15 23:37:01 +0000656 typedef MapVector<const Value *, PtrState> MapTy;
657
Michael Gottesman97e3df02013-01-14 00:35:14 +0000658 /// The top-down traversal uses this to record information known about a
659 /// pointer at the bottom of each block.
John McCalld935e9c2011-06-15 23:37:01 +0000660 MapTy PerPtrTopDown;
661
Michael Gottesman97e3df02013-01-14 00:35:14 +0000662 /// The bottom-up traversal uses this to record information known about a
663 /// pointer at the top of each block.
John McCalld935e9c2011-06-15 23:37:01 +0000664 MapTy PerPtrBottomUp;
665
Michael Gottesman97e3df02013-01-14 00:35:14 +0000666 /// Effective predecessors of the current block ignoring ignorable edges and
667 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000668 SmallVector<BasicBlock *, 2> Preds;
Michael Gottesman97e3df02013-01-14 00:35:14 +0000669 /// Effective successors of the current block ignoring ignorable edges and
670 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000671 SmallVector<BasicBlock *, 2> Succs;
672
John McCalld935e9c2011-06-15 23:37:01 +0000673 public:
674 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
675
676 typedef MapTy::iterator ptr_iterator;
677 typedef MapTy::const_iterator ptr_const_iterator;
678
679 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
680 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
681 ptr_const_iterator top_down_ptr_begin() const {
682 return PerPtrTopDown.begin();
683 }
684 ptr_const_iterator top_down_ptr_end() const {
685 return PerPtrTopDown.end();
686 }
687
688 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
689 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
690 ptr_const_iterator bottom_up_ptr_begin() const {
691 return PerPtrBottomUp.begin();
692 }
693 ptr_const_iterator bottom_up_ptr_end() const {
694 return PerPtrBottomUp.end();
695 }
696
Michael Gottesman97e3df02013-01-14 00:35:14 +0000697 /// Mark this block as being an entry block, which has one path from the
698 /// entry by definition.
John McCalld935e9c2011-06-15 23:37:01 +0000699 void SetAsEntry() { TopDownPathCount = 1; }
700
Michael Gottesman97e3df02013-01-14 00:35:14 +0000701 /// Mark this block as being an exit block, which has one path to an exit by
702 /// definition.
John McCalld935e9c2011-06-15 23:37:01 +0000703 void SetAsExit() { BottomUpPathCount = 1; }
704
Michael Gottesman993fbf72013-05-13 19:40:39 +0000705 /// Attempt to find the PtrState object describing the top down state for
706 /// pointer Arg. Return a new initialized PtrState describing the top down
707 /// state for Arg if we do not find one.
John McCalld935e9c2011-06-15 23:37:01 +0000708 PtrState &getPtrTopDownState(const Value *Arg) {
709 return PerPtrTopDown[Arg];
710 }
711
Michael Gottesman993fbf72013-05-13 19:40:39 +0000712 /// Attempt to find the PtrState object describing the bottom up state for
713 /// pointer Arg. Return a new initialized PtrState describing the bottom up
714 /// state for Arg if we do not find one.
John McCalld935e9c2011-06-15 23:37:01 +0000715 PtrState &getPtrBottomUpState(const Value *Arg) {
716 return PerPtrBottomUp[Arg];
717 }
718
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000719 /// Attempt to find the PtrState object describing the bottom up state for
720 /// pointer Arg.
721 ptr_iterator findPtrBottomUpState(const Value *Arg) {
722 return PerPtrBottomUp.find(Arg);
723 }
724
John McCalld935e9c2011-06-15 23:37:01 +0000725 void clearBottomUpPointers() {
Evan Chenge4df6a22011-08-04 18:40:26 +0000726 PerPtrBottomUp.clear();
John McCalld935e9c2011-06-15 23:37:01 +0000727 }
728
729 void clearTopDownPointers() {
730 PerPtrTopDown.clear();
731 }
732
733 void InitFromPred(const BBState &Other);
734 void InitFromSucc(const BBState &Other);
735 void MergePred(const BBState &Other);
736 void MergeSucc(const BBState &Other);
737
Michael Gottesman9e7261c2013-06-07 06:16:49 +0000738 /// Compute the number of possible unique paths from an entry to an exit
Michael Gottesman97e3df02013-01-14 00:35:14 +0000739 /// which pass through this block. This is only valid after both the
740 /// top-down and bottom-up traversals are complete.
Michael Gottesman9e7261c2013-06-07 06:16:49 +0000741 ///
742 /// Returns true if overflow occured. Returns false if overflow did not
743 /// occur.
744 bool GetAllPathCountWithOverflow(unsigned &PathCount) const {
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000745 assert(TopDownPathCount != 0);
746 assert(BottomUpPathCount != 0);
Michael Gottesman9e7261c2013-06-07 06:16:49 +0000747 unsigned long long Product =
748 (unsigned long long)TopDownPathCount*BottomUpPathCount;
749 PathCount = Product;
750 // Overflow occured if any of the upper bits of Product are set.
751 return Product >> 32;
John McCalld935e9c2011-06-15 23:37:01 +0000752 }
Dan Gohman12130272011-08-12 00:26:31 +0000753
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000754 // Specialized CFG utilities.
Dan Gohmandae33492012-04-27 18:56:31 +0000755 typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000756 edge_iterator pred_begin() { return Preds.begin(); }
757 edge_iterator pred_end() { return Preds.end(); }
758 edge_iterator succ_begin() { return Succs.begin(); }
759 edge_iterator succ_end() { return Succs.end(); }
760
761 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
762 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
763
764 bool isExit() const { return Succs.empty(); }
John McCalld935e9c2011-06-15 23:37:01 +0000765 };
766}
767
768void BBState::InitFromPred(const BBState &Other) {
769 PerPtrTopDown = Other.PerPtrTopDown;
770 TopDownPathCount = Other.TopDownPathCount;
771}
772
773void BBState::InitFromSucc(const BBState &Other) {
774 PerPtrBottomUp = Other.PerPtrBottomUp;
775 BottomUpPathCount = Other.BottomUpPathCount;
776}
777
Michael Gottesman97e3df02013-01-14 00:35:14 +0000778/// The top-down traversal uses this to merge information about predecessors to
779/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +0000780void BBState::MergePred(const BBState &Other) {
781 // Other.TopDownPathCount can be 0, in which case it is either dead or a
782 // loop backedge. Loop backedges are special.
783 TopDownPathCount += Other.TopDownPathCount;
784
Michael Gottesman4385edf2013-01-14 01:47:53 +0000785 // Check for overflow. If we have overflow, fall back to conservative
786 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +0000787 if (TopDownPathCount < Other.TopDownPathCount) {
788 clearTopDownPointers();
789 return;
790 }
791
John McCalld935e9c2011-06-15 23:37:01 +0000792 // For each entry in the other set, if our set has an entry with the same key,
793 // merge the entries. Otherwise, copy the entry and merge it with an empty
794 // entry.
795 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
796 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
797 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
798 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
799 /*TopDown=*/true);
800 }
801
Dan Gohman7e315fc32011-08-11 21:06:32 +0000802 // For each entry in our set, if the other set doesn't have an entry with the
John McCalld935e9c2011-06-15 23:37:01 +0000803 // same key, force it to merge with an empty entry.
804 for (ptr_iterator MI = top_down_ptr_begin(),
805 ME = top_down_ptr_end(); MI != ME; ++MI)
806 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
807 MI->second.Merge(PtrState(), /*TopDown=*/true);
808}
809
Michael Gottesman97e3df02013-01-14 00:35:14 +0000810/// The bottom-up traversal uses this to merge information about successors to
811/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +0000812void BBState::MergeSucc(const BBState &Other) {
813 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
814 // loop backedge. Loop backedges are special.
815 BottomUpPathCount += Other.BottomUpPathCount;
816
Michael Gottesman4385edf2013-01-14 01:47:53 +0000817 // Check for overflow. If we have overflow, fall back to conservative
818 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +0000819 if (BottomUpPathCount < Other.BottomUpPathCount) {
820 clearBottomUpPointers();
821 return;
822 }
823
John McCalld935e9c2011-06-15 23:37:01 +0000824 // For each entry in the other set, if our set has an entry with the
825 // same key, merge the entries. Otherwise, copy the entry and merge
826 // it with an empty entry.
827 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
828 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
829 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
830 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
831 /*TopDown=*/false);
832 }
833
Dan Gohman7e315fc32011-08-11 21:06:32 +0000834 // For each entry in our set, if the other set doesn't have an entry
John McCalld935e9c2011-06-15 23:37:01 +0000835 // with the same key, force it to merge with an empty entry.
836 for (ptr_iterator MI = bottom_up_ptr_begin(),
837 ME = bottom_up_ptr_end(); MI != ME; ++MI)
838 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
839 MI->second.Merge(PtrState(), /*TopDown=*/false);
840}
841
Michael Gottesman81b1d432013-03-26 00:42:04 +0000842// Only enable ARC Annotations if we are building a debug version of
843// libObjCARCOpts.
844#ifndef NDEBUG
845#define ARC_ANNOTATIONS
846#endif
847
848// Define some macros along the lines of DEBUG and some helper functions to make
849// it cleaner to create annotations in the source code and to no-op when not
850// building in debug mode.
851#ifdef ARC_ANNOTATIONS
852
853#include "llvm/Support/CommandLine.h"
854
855/// Enable/disable ARC sequence annotations.
856static cl::opt<bool>
Michael Gottesman6806b512013-04-17 20:48:03 +0000857EnableARCAnnotations("enable-objc-arc-annotations", cl::init(false),
858 cl::desc("Enable emission of arc data flow analysis "
859 "annotations"));
Michael Gottesmanffef24f2013-04-17 20:48:01 +0000860static cl::opt<bool>
Michael Gottesmanadb921a2013-04-17 21:03:53 +0000861DisableCheckForCFGHazards("disable-objc-arc-checkforcfghazards", cl::init(false),
862 cl::desc("Disable check for cfg hazards when "
863 "annotating"));
Michael Gottesman4e88ce62013-04-17 21:59:41 +0000864static cl::opt<std::string>
865ARCAnnotationTargetIdentifier("objc-arc-annotation-target-identifier",
866 cl::init(""),
867 cl::desc("filter out all data flow annotations "
868 "but those that apply to the given "
869 "target llvm identifier."));
Michael Gottesman81b1d432013-03-26 00:42:04 +0000870
871/// This function appends a unique ARCAnnotationProvenanceSourceMDKind id to an
872/// instruction so that we can track backwards when post processing via the llvm
873/// arc annotation processor tool. If the function is an
874static MDString *AppendMDNodeToSourcePtr(unsigned NodeId,
875 Value *Ptr) {
876 MDString *Hash = 0;
877
878 // If pointer is a result of an instruction and it does not have a source
879 // MDNode it, attach a new MDNode onto it. If pointer is a result of
880 // an instruction and does have a source MDNode attached to it, return a
881 // reference to said Node. Otherwise just return 0.
882 if (Instruction *Inst = dyn_cast<Instruction>(Ptr)) {
883 MDNode *Node;
884 if (!(Node = Inst->getMetadata(NodeId))) {
885 // We do not have any node. Generate and attatch the hash MDString to the
886 // instruction.
887
888 // We just use an MDString to ensure that this metadata gets written out
889 // of line at the module level and to provide a very simple format
890 // encoding the information herein. Both of these makes it simpler to
891 // parse the annotations by a simple external program.
892 std::string Str;
893 raw_string_ostream os(Str);
894 os << "(" << Inst->getParent()->getParent()->getName() << ",%"
895 << Inst->getName() << ")";
896
897 Hash = MDString::get(Inst->getContext(), os.str());
898 Inst->setMetadata(NodeId, MDNode::get(Inst->getContext(),Hash));
899 } else {
900 // We have a node. Grab its hash and return it.
901 assert(Node->getNumOperands() == 1 &&
902 "An ARCAnnotationProvenanceSourceMDKind can only have 1 operand.");
903 Hash = cast<MDString>(Node->getOperand(0));
904 }
905 } else if (Argument *Arg = dyn_cast<Argument>(Ptr)) {
906 std::string str;
907 raw_string_ostream os(str);
908 os << "(" << Arg->getParent()->getName() << ",%" << Arg->getName()
909 << ")";
910 Hash = MDString::get(Arg->getContext(), os.str());
911 }
912
913 return Hash;
914}
915
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000916static std::string SequenceToString(Sequence A) {
917 std::string str;
918 raw_string_ostream os(str);
919 os << A;
920 return os.str();
921}
922
Michael Gottesman81b1d432013-03-26 00:42:04 +0000923/// Helper function to change a Sequence into a String object using our overload
924/// for raw_ostream so we only have printing code in one location.
925static MDString *SequenceToMDString(LLVMContext &Context,
926 Sequence A) {
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000927 return MDString::get(Context, SequenceToString(A));
Michael Gottesman81b1d432013-03-26 00:42:04 +0000928}
929
930/// A simple function to generate a MDNode which describes the change in state
931/// for Value *Ptr caused by Instruction *Inst.
932static void AppendMDNodeToInstForPtr(unsigned NodeId,
933 Instruction *Inst,
934 Value *Ptr,
935 MDString *PtrSourceMDNodeID,
936 Sequence OldSeq,
937 Sequence NewSeq) {
938 MDNode *Node = 0;
939 Value *tmp[3] = {PtrSourceMDNodeID,
940 SequenceToMDString(Inst->getContext(),
941 OldSeq),
942 SequenceToMDString(Inst->getContext(),
943 NewSeq)};
944 Node = MDNode::get(Inst->getContext(),
945 ArrayRef<Value*>(tmp, 3));
946
947 Inst->setMetadata(NodeId, Node);
948}
949
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000950/// Add to the beginning of the basic block llvm.ptr.annotations which show the
951/// state of a pointer at the entrance to a basic block.
952static void GenerateARCBBEntranceAnnotation(const char *Name, BasicBlock *BB,
953 Value *Ptr, Sequence Seq) {
Michael Gottesman4e88ce62013-04-17 21:59:41 +0000954 // If we have a target identifier, make sure that we match it before
955 // continuing.
956 if(!ARCAnnotationTargetIdentifier.empty() &&
957 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
958 return;
Michael Gottesman9e518132013-04-18 04:34:11 +0000959
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000960 Module *M = BB->getParent()->getParent();
961 LLVMContext &C = M->getContext();
962 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
963 Type *I8XX = PointerType::getUnqual(I8X);
964 Type *Params[] = {I8XX, I8XX};
965 FunctionType *FTy = FunctionType::get(Type::getVoidTy(C),
966 ArrayRef<Type*>(Params, 2),
967 /*isVarArg=*/false);
968 Constant *Callee = M->getOrInsertFunction(Name, FTy);
Michael Gottesman60f6b282013-03-29 05:13:07 +0000969
970 IRBuilder<> Builder(BB, BB->getFirstInsertionPt());
971
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000972 Value *PtrName;
973 StringRef Tmp = Ptr->getName();
974 if (0 == (PtrName = M->getGlobalVariable(Tmp, true))) {
975 Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
976 Tmp + "_STR");
977 PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
Michael Gottesman60f6b282013-03-29 05:13:07 +0000978 cast<Constant>(ActualPtrName), Tmp);
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000979 }
980
981 Value *S;
982 std::string SeqStr = SequenceToString(Seq);
983 if (0 == (S = M->getGlobalVariable(SeqStr, true))) {
984 Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
985 SeqStr + "_STR");
986 S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
987 cast<Constant>(ActualPtrName), SeqStr);
988 }
989
990 Builder.CreateCall2(Callee, PtrName, S);
991}
992
993/// Add to the end of the basic block llvm.ptr.annotations which show the state
994/// of the pointer at the bottom of the basic block.
995static void GenerateARCBBTerminatorAnnotation(const char *Name, BasicBlock *BB,
996 Value *Ptr, Sequence Seq) {
Michael Gottesman4e88ce62013-04-17 21:59:41 +0000997 // If we have a target identifier, make sure that we match it before emitting
998 // an annotation.
999 if(!ARCAnnotationTargetIdentifier.empty() &&
1000 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
1001 return;
Michael Gottesman9e518132013-04-18 04:34:11 +00001002
Michael Gottesmancd4de0f2013-03-26 00:42:09 +00001003 Module *M = BB->getParent()->getParent();
1004 LLVMContext &C = M->getContext();
1005 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1006 Type *I8XX = PointerType::getUnqual(I8X);
1007 Type *Params[] = {I8XX, I8XX};
1008 FunctionType *FTy = FunctionType::get(Type::getVoidTy(C),
1009 ArrayRef<Type*>(Params, 2),
1010 /*isVarArg=*/false);
1011 Constant *Callee = M->getOrInsertFunction(Name, FTy);
Michael Gottesman60f6b282013-03-29 05:13:07 +00001012
1013 IRBuilder<> Builder(BB, llvm::prior(BB->end()));
1014
Michael Gottesmancd4de0f2013-03-26 00:42:09 +00001015 Value *PtrName;
1016 StringRef Tmp = Ptr->getName();
1017 if (0 == (PtrName = M->getGlobalVariable(Tmp, true))) {
1018 Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
1019 Tmp + "_STR");
1020 PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
Michael Gottesman60f6b282013-03-29 05:13:07 +00001021 cast<Constant>(ActualPtrName), Tmp);
Michael Gottesmancd4de0f2013-03-26 00:42:09 +00001022 }
1023
1024 Value *S;
1025 std::string SeqStr = SequenceToString(Seq);
1026 if (0 == (S = M->getGlobalVariable(SeqStr, true))) {
1027 Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
1028 SeqStr + "_STR");
1029 S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
1030 cast<Constant>(ActualPtrName), SeqStr);
1031 }
Michael Gottesman60f6b282013-03-29 05:13:07 +00001032 Builder.CreateCall2(Callee, PtrName, S);
Michael Gottesmancd4de0f2013-03-26 00:42:09 +00001033}
1034
Michael Gottesman81b1d432013-03-26 00:42:04 +00001035/// Adds a source annotation to pointer and a state change annotation to Inst
1036/// referencing the source annotation and the old/new state of pointer.
1037static void GenerateARCAnnotation(unsigned InstMDId,
1038 unsigned PtrMDId,
1039 Instruction *Inst,
1040 Value *Ptr,
1041 Sequence OldSeq,
1042 Sequence NewSeq) {
1043 if (EnableARCAnnotations) {
Michael Gottesman4e88ce62013-04-17 21:59:41 +00001044 // If we have a target identifier, make sure that we match it before
1045 // emitting an annotation.
1046 if(!ARCAnnotationTargetIdentifier.empty() &&
1047 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
1048 return;
Michael Gottesman9e518132013-04-18 04:34:11 +00001049
Michael Gottesman81b1d432013-03-26 00:42:04 +00001050 // First generate the source annotation on our pointer. This will return an
1051 // MDString* if Ptr actually comes from an instruction implying we can put
1052 // in a source annotation. If AppendMDNodeToSourcePtr returns 0 (i.e. NULL),
1053 // then we know that our pointer is from an Argument so we put a reference
1054 // to the argument number.
1055 //
1056 // The point of this is to make it easy for the
1057 // llvm-arc-annotation-processor tool to cross reference where the source
1058 // pointer is in the LLVM IR since the LLVM IR parser does not submit such
1059 // information via debug info for backends to use (since why would anyone
1060 // need such a thing from LLVM IR besides in non standard cases
1061 // [i.e. this]).
1062 MDString *SourcePtrMDNode =
1063 AppendMDNodeToSourcePtr(PtrMDId, Ptr);
1064 AppendMDNodeToInstForPtr(InstMDId, Inst, Ptr, SourcePtrMDNode, OldSeq,
1065 NewSeq);
1066 }
1067}
1068
1069// The actual interface for accessing the above functionality is defined via
1070// some simple macros which are defined below. We do this so that the user does
1071// not need to pass in what metadata id is needed resulting in cleaner code and
1072// additionally since it provides an easy way to conditionally no-op all
1073// annotation support in a non-debug build.
1074
1075/// Use this macro to annotate a sequence state change when processing
1076/// instructions bottom up,
1077#define ANNOTATE_BOTTOMUP(inst, ptr, old, new) \
1078 GenerateARCAnnotation(ARCAnnotationBottomUpMDKind, \
1079 ARCAnnotationProvenanceSourceMDKind, (inst), \
1080 const_cast<Value*>(ptr), (old), (new))
1081/// Use this macro to annotate a sequence state change when processing
1082/// instructions top down.
1083#define ANNOTATE_TOPDOWN(inst, ptr, old, new) \
1084 GenerateARCAnnotation(ARCAnnotationTopDownMDKind, \
1085 ARCAnnotationProvenanceSourceMDKind, (inst), \
1086 const_cast<Value*>(ptr), (old), (new))
1087
Michael Gottesman43e7e002013-04-03 22:41:59 +00001088#define ANNOTATE_BB(_states, _bb, _name, _type, _direction) \
1089 do { \
Michael Gottesman89279f82013-04-05 18:10:41 +00001090 if (EnableARCAnnotations) { \
1091 for(BBState::ptr_const_iterator I = (_states)._direction##_ptr_begin(), \
Michael Gottesman43e7e002013-04-03 22:41:59 +00001092 E = (_states)._direction##_ptr_end(); I != E; ++I) { \
Michael Gottesman89279f82013-04-05 18:10:41 +00001093 Value *Ptr = const_cast<Value*>(I->first); \
1094 Sequence Seq = I->second.GetSeq(); \
1095 GenerateARCBB ## _type ## Annotation(_name, (_bb), Ptr, Seq); \
1096 } \
Michael Gottesman43e7e002013-04-03 22:41:59 +00001097 } \
Michael Gottesman89279f82013-04-05 18:10:41 +00001098 } while (0)
Michael Gottesman43e7e002013-04-03 22:41:59 +00001099
Michael Gottesman89279f82013-04-05 18:10:41 +00001100#define ANNOTATE_BOTTOMUP_BBSTART(_states, _basicblock) \
Michael Gottesman43e7e002013-04-03 22:41:59 +00001101 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbstart", \
1102 Entrance, bottom_up)
Michael Gottesman89279f82013-04-05 18:10:41 +00001103#define ANNOTATE_BOTTOMUP_BBEND(_states, _basicblock) \
1104 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbend", \
Michael Gottesman43e7e002013-04-03 22:41:59 +00001105 Terminator, bottom_up)
Michael Gottesman89279f82013-04-05 18:10:41 +00001106#define ANNOTATE_TOPDOWN_BBSTART(_states, _basicblock) \
1107 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbstart", \
Michael Gottesman43e7e002013-04-03 22:41:59 +00001108 Entrance, top_down)
Michael Gottesman89279f82013-04-05 18:10:41 +00001109#define ANNOTATE_TOPDOWN_BBEND(_states, _basicblock) \
1110 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbend", \
Michael Gottesman43e7e002013-04-03 22:41:59 +00001111 Terminator, top_down)
1112
Michael Gottesman81b1d432013-03-26 00:42:04 +00001113#else // !ARC_ANNOTATION
1114// If annotations are off, noop.
1115#define ANNOTATE_BOTTOMUP(inst, ptr, old, new)
1116#define ANNOTATE_TOPDOWN(inst, ptr, old, new)
Michael Gottesman43e7e002013-04-03 22:41:59 +00001117#define ANNOTATE_BOTTOMUP_BBSTART(states, basicblock)
1118#define ANNOTATE_BOTTOMUP_BBEND(states, basicblock)
1119#define ANNOTATE_TOPDOWN_BBSTART(states, basicblock)
1120#define ANNOTATE_TOPDOWN_BBEND(states, basicblock)
Michael Gottesman81b1d432013-03-26 00:42:04 +00001121#endif // !ARC_ANNOTATION
1122
John McCalld935e9c2011-06-15 23:37:01 +00001123namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001124 /// \brief The main ARC optimization pass.
John McCalld935e9c2011-06-15 23:37:01 +00001125 class ObjCARCOpt : public FunctionPass {
1126 bool Changed;
1127 ProvenanceAnalysis PA;
1128
Michael Gottesman5a91bbf2013-05-24 20:44:02 +00001129 // This is used to track if a pointer is stored into an alloca.
1130 DenseSet<const Value *> MultiOwnersSet;
1131
Michael Gottesman97e3df02013-01-14 00:35:14 +00001132 /// A flag indicating whether this optimization pass should run.
Dan Gohmanceaac7c2011-06-20 23:20:43 +00001133 bool Run;
1134
Michael Gottesman97e3df02013-01-14 00:35:14 +00001135 /// Declarations for ObjC runtime functions, for use in creating calls to
1136 /// them. These are initialized lazily to avoid cluttering up the Module
1137 /// with unused declarations.
John McCalld935e9c2011-06-15 23:37:01 +00001138
Michael Gottesman97e3df02013-01-14 00:35:14 +00001139 /// Declaration for ObjC runtime function objc_autoreleaseReturnValue.
1140 Constant *AutoreleaseRVCallee;
1141 /// Declaration for ObjC runtime function objc_release.
1142 Constant *ReleaseCallee;
1143 /// Declaration for ObjC runtime function objc_retain.
1144 Constant *RetainCallee;
1145 /// Declaration for ObjC runtime function objc_retainBlock.
1146 Constant *RetainBlockCallee;
1147 /// Declaration for ObjC runtime function objc_autorelease.
1148 Constant *AutoreleaseCallee;
1149
1150 /// Flags which determine whether each of the interesting runtine functions
1151 /// is in fact used in the current function.
John McCalld935e9c2011-06-15 23:37:01 +00001152 unsigned UsedInThisFunction;
1153
Michael Gottesman97e3df02013-01-14 00:35:14 +00001154 /// The Metadata Kind for clang.imprecise_release metadata.
John McCalld935e9c2011-06-15 23:37:01 +00001155 unsigned ImpreciseReleaseMDKind;
1156
Michael Gottesman97e3df02013-01-14 00:35:14 +00001157 /// The Metadata Kind for clang.arc.copy_on_escape metadata.
Dan Gohmana7107f92011-10-17 22:53:25 +00001158 unsigned CopyOnEscapeMDKind;
1159
Michael Gottesman97e3df02013-01-14 00:35:14 +00001160 /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata.
Dan Gohman0155f302012-02-17 18:59:53 +00001161 unsigned NoObjCARCExceptionsMDKind;
1162
Michael Gottesman81b1d432013-03-26 00:42:04 +00001163#ifdef ARC_ANNOTATIONS
1164 /// The Metadata Kind for llvm.arc.annotation.bottomup metadata.
1165 unsigned ARCAnnotationBottomUpMDKind;
1166 /// The Metadata Kind for llvm.arc.annotation.topdown metadata.
1167 unsigned ARCAnnotationTopDownMDKind;
1168 /// The Metadata Kind for llvm.arc.annotation.provenancesource metadata.
1169 unsigned ARCAnnotationProvenanceSourceMDKind;
1170#endif // ARC_ANNOATIONS
1171
John McCalld935e9c2011-06-15 23:37:01 +00001172 Constant *getAutoreleaseRVCallee(Module *M);
1173 Constant *getReleaseCallee(Module *M);
1174 Constant *getRetainCallee(Module *M);
Dan Gohman6320f522011-07-22 22:29:21 +00001175 Constant *getRetainBlockCallee(Module *M);
John McCalld935e9c2011-06-15 23:37:01 +00001176 Constant *getAutoreleaseCallee(Module *M);
1177
Dan Gohman728db492012-01-13 00:39:07 +00001178 bool IsRetainBlockOptimizable(const Instruction *Inst);
1179
John McCalld935e9c2011-06-15 23:37:01 +00001180 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
Michael Gottesman556ff612013-01-12 01:25:19 +00001181 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1182 InstructionClass &Class);
Michael Gottesman158fdf62013-03-28 20:11:19 +00001183 bool OptimizeRetainBlockCall(Function &F, Instruction *RetainBlock,
1184 InstructionClass &Class);
John McCalld935e9c2011-06-15 23:37:01 +00001185 void OptimizeIndividualCalls(Function &F);
1186
1187 void CheckForCFGHazards(const BasicBlock *BB,
1188 DenseMap<const BasicBlock *, BBState> &BBStates,
1189 BBState &MyStates) const;
Dan Gohman817a7c62012-03-22 18:24:56 +00001190 bool VisitInstructionBottomUp(Instruction *Inst,
Dan Gohman5c70fad2012-03-23 17:47:54 +00001191 BasicBlock *BB,
Dan Gohman817a7c62012-03-22 18:24:56 +00001192 MapVector<Value *, RRInfo> &Retains,
1193 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00001194 bool VisitBottomUp(BasicBlock *BB,
1195 DenseMap<const BasicBlock *, BBState> &BBStates,
1196 MapVector<Value *, RRInfo> &Retains);
Dan Gohman817a7c62012-03-22 18:24:56 +00001197 bool VisitInstructionTopDown(Instruction *Inst,
1198 DenseMap<Value *, RRInfo> &Releases,
1199 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00001200 bool VisitTopDown(BasicBlock *BB,
1201 DenseMap<const BasicBlock *, BBState> &BBStates,
1202 DenseMap<Value *, RRInfo> &Releases);
1203 bool Visit(Function &F,
1204 DenseMap<const BasicBlock *, BBState> &BBStates,
1205 MapVector<Value *, RRInfo> &Retains,
1206 DenseMap<Value *, RRInfo> &Releases);
1207
1208 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1209 MapVector<Value *, RRInfo> &Retains,
1210 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman6320f522011-07-22 22:29:21 +00001211 SmallVectorImpl<Instruction *> &DeadInsts,
1212 Module *M);
John McCalld935e9c2011-06-15 23:37:01 +00001213
Michael Gottesman9de6f962013-01-22 21:49:00 +00001214 bool ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState> &BBStates,
1215 MapVector<Value *, RRInfo> &Retains,
1216 DenseMap<Value *, RRInfo> &Releases,
1217 Module *M,
1218 SmallVector<Instruction *, 4> &NewRetains,
1219 SmallVector<Instruction *, 4> &NewReleases,
1220 SmallVector<Instruction *, 8> &DeadInsts,
1221 RRInfo &RetainsToMove,
1222 RRInfo &ReleasesToMove,
1223 Value *Arg,
1224 bool KnownSafe,
1225 bool &AnyPairsCompletelyEliminated);
1226
John McCalld935e9c2011-06-15 23:37:01 +00001227 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1228 MapVector<Value *, RRInfo> &Retains,
Dan Gohman6320f522011-07-22 22:29:21 +00001229 DenseMap<Value *, RRInfo> &Releases,
1230 Module *M);
John McCalld935e9c2011-06-15 23:37:01 +00001231
1232 void OptimizeWeakCalls(Function &F);
1233
1234 bool OptimizeSequences(Function &F);
1235
1236 void OptimizeReturns(Function &F);
1237
Michael Gottesman9c118152013-04-29 06:16:57 +00001238#ifndef NDEBUG
1239 void GatherStatistics(Function &F, bool AfterOptimization = false);
1240#endif
1241
John McCalld935e9c2011-06-15 23:37:01 +00001242 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1243 virtual bool doInitialization(Module &M);
1244 virtual bool runOnFunction(Function &F);
1245 virtual void releaseMemory();
1246
1247 public:
1248 static char ID;
1249 ObjCARCOpt() : FunctionPass(ID) {
1250 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1251 }
1252 };
1253}
1254
1255char ObjCARCOpt::ID = 0;
1256INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1257 "objc-arc", "ObjC ARC optimization", false, false)
1258INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1259INITIALIZE_PASS_END(ObjCARCOpt,
1260 "objc-arc", "ObjC ARC optimization", false, false)
1261
1262Pass *llvm::createObjCARCOptPass() {
1263 return new ObjCARCOpt();
1264}
1265
1266void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1267 AU.addRequired<ObjCARCAliasAnalysis>();
1268 AU.addRequired<AliasAnalysis>();
1269 // ARC optimization doesn't currently split critical edges.
1270 AU.setPreservesCFG();
1271}
1272
Dan Gohman728db492012-01-13 00:39:07 +00001273bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1274 // Without the magic metadata tag, we have to assume this might be an
1275 // objc_retainBlock call inserted to convert a block pointer to an id,
1276 // in which case it really is needed.
1277 if (!Inst->getMetadata(CopyOnEscapeMDKind))
1278 return false;
1279
1280 // If the pointer "escapes" (not including being used in a call),
1281 // the copy may be needed.
Michael Gottesman774d2c02013-01-29 21:00:52 +00001282 if (DoesRetainableObjPtrEscape(Inst))
Dan Gohman728db492012-01-13 00:39:07 +00001283 return false;
1284
1285 // Otherwise, it's not needed.
1286 return true;
1287}
1288
John McCalld935e9c2011-06-15 23:37:01 +00001289Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1290 if (!AutoreleaseRVCallee) {
1291 LLVMContext &C = M->getContext();
Jay Foadb804a2b2011-07-12 14:06:48 +00001292 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman41375a32012-05-08 23:39:44 +00001293 Type *Params[] = { I8X };
1294 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001295 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001296 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1297 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001298 AutoreleaseRVCallee =
1299 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001300 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001301 }
1302 return AutoreleaseRVCallee;
1303}
1304
1305Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1306 if (!ReleaseCallee) {
1307 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001308 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001309 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001310 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1311 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001312 ReleaseCallee =
1313 M->getOrInsertFunction(
1314 "objc_release",
1315 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001316 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001317 }
1318 return ReleaseCallee;
1319}
1320
1321Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1322 if (!RetainCallee) {
1323 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001324 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001325 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001326 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1327 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001328 RetainCallee =
1329 M->getOrInsertFunction(
1330 "objc_retain",
1331 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001332 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001333 }
1334 return RetainCallee;
1335}
1336
Dan Gohman6320f522011-07-22 22:29:21 +00001337Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1338 if (!RetainBlockCallee) {
1339 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001340 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Dan Gohmanfca43c22011-09-14 18:33:34 +00001341 // objc_retainBlock is not nounwind because it calls user copy constructors
1342 // which could theoretically throw.
Dan Gohman6320f522011-07-22 22:29:21 +00001343 RetainBlockCallee =
1344 M->getOrInsertFunction(
1345 "objc_retainBlock",
1346 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendlinge94d8432012-12-07 23:16:57 +00001347 AttributeSet());
Dan Gohman6320f522011-07-22 22:29:21 +00001348 }
1349 return RetainBlockCallee;
1350}
1351
John McCalld935e9c2011-06-15 23:37:01 +00001352Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1353 if (!AutoreleaseCallee) {
1354 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001355 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001356 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001357 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1358 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001359 AutoreleaseCallee =
1360 M->getOrInsertFunction(
1361 "objc_autorelease",
1362 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001363 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001364 }
1365 return AutoreleaseCallee;
1366}
1367
Michael Gottesman97e3df02013-01-14 00:35:14 +00001368/// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is
1369/// not a return value. Or, if it can be paired with an
1370/// objc_autoreleaseReturnValue, delete the pair and return true.
John McCalld935e9c2011-06-15 23:37:01 +00001371bool
1372ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001373 // Check for the argument being from an immediately preceding call or invoke.
Dan Gohmandae33492012-04-27 18:56:31 +00001374 const Value *Arg = GetObjCArg(RetainRV);
1375 ImmutableCallSite CS(Arg);
1376 if (const Instruction *Call = CS.getInstruction()) {
John McCalld935e9c2011-06-15 23:37:01 +00001377 if (Call->getParent() == RetainRV->getParent()) {
Dan Gohmandae33492012-04-27 18:56:31 +00001378 BasicBlock::const_iterator I = Call;
John McCalld935e9c2011-06-15 23:37:01 +00001379 ++I;
Michael Gottesman65c24812013-03-25 09:27:43 +00001380 while (IsNoopInstruction(I)) ++I;
John McCalld935e9c2011-06-15 23:37:01 +00001381 if (&*I == RetainRV)
1382 return false;
Dan Gohmandae33492012-04-27 18:56:31 +00001383 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001384 BasicBlock *RetainRVParent = RetainRV->getParent();
1385 if (II->getNormalDest() == RetainRVParent) {
Dan Gohmandae33492012-04-27 18:56:31 +00001386 BasicBlock::const_iterator I = RetainRVParent->begin();
Michael Gottesman65c24812013-03-25 09:27:43 +00001387 while (IsNoopInstruction(I)) ++I;
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001388 if (&*I == RetainRV)
1389 return false;
1390 }
John McCalld935e9c2011-06-15 23:37:01 +00001391 }
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001392 }
John McCalld935e9c2011-06-15 23:37:01 +00001393
1394 // Check for being preceded by an objc_autoreleaseReturnValue on the same
1395 // pointer. In this case, we can delete the pair.
1396 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
1397 if (I != Begin) {
Michael Gottesman65c24812013-03-25 09:27:43 +00001398 do --I; while (I != Begin && IsNoopInstruction(I));
John McCalld935e9c2011-06-15 23:37:01 +00001399 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
1400 GetObjCArg(I) == Arg) {
1401 Changed = true;
1402 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00001403
Michael Gottesman89279f82013-04-05 18:10:41 +00001404 DEBUG(dbgs() << "Erasing autoreleaseRV,retainRV pair: " << *I << "\n"
1405 << "Erasing " << *RetainRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001406
John McCalld935e9c2011-06-15 23:37:01 +00001407 EraseInstruction(I);
1408 EraseInstruction(RetainRV);
1409 return true;
1410 }
1411 }
1412
1413 // Turn it to a plain objc_retain.
1414 Changed = true;
1415 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00001416
Michael Gottesman89279f82013-04-05 18:10:41 +00001417 DEBUG(dbgs() << "Transforming objc_retainAutoreleasedReturnValue => "
Michael Gottesmandef07bb2013-01-05 17:55:42 +00001418 "objc_retain since the operand is not a return value.\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00001419 "Old = " << *RetainRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001420
John McCalld935e9c2011-06-15 23:37:01 +00001421 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
Michael Gottesmandef07bb2013-01-05 17:55:42 +00001422
Michael Gottesman89279f82013-04-05 18:10:41 +00001423 DEBUG(dbgs() << "New = " << *RetainRV << "\n");
Michael Gottesmandef07bb2013-01-05 17:55:42 +00001424
John McCalld935e9c2011-06-15 23:37:01 +00001425 return false;
1426}
1427
Michael Gottesman97e3df02013-01-14 00:35:14 +00001428/// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not
1429/// used as a return value.
John McCalld935e9c2011-06-15 23:37:01 +00001430void
Michael Gottesman556ff612013-01-12 01:25:19 +00001431ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1432 InstructionClass &Class) {
John McCalld935e9c2011-06-15 23:37:01 +00001433 // Check for a return of the pointer value.
1434 const Value *Ptr = GetObjCArg(AutoreleaseRV);
Dan Gohman10a18d52011-08-12 00:36:31 +00001435 SmallVector<const Value *, 2> Users;
1436 Users.push_back(Ptr);
1437 do {
1438 Ptr = Users.pop_back_val();
1439 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
1440 UI != UE; ++UI) {
1441 const User *I = *UI;
1442 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
1443 return;
1444 if (isa<BitCastInst>(I))
1445 Users.push_back(I);
1446 }
1447 } while (!Users.empty());
John McCalld935e9c2011-06-15 23:37:01 +00001448
1449 Changed = true;
1450 ++NumPeeps;
Michael Gottesman1bf69082013-01-06 21:07:11 +00001451
Michael Gottesman89279f82013-04-05 18:10:41 +00001452 DEBUG(dbgs() << "Transforming objc_autoreleaseReturnValue => "
Michael Gottesman1bf69082013-01-06 21:07:11 +00001453 "objc_autorelease since its operand is not used as a return "
1454 "value.\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00001455 "Old = " << *AutoreleaseRV << "\n");
Michael Gottesman1bf69082013-01-06 21:07:11 +00001456
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001457 CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
1458 AutoreleaseRVCI->
John McCalld935e9c2011-06-15 23:37:01 +00001459 setCalledFunction(getAutoreleaseCallee(F.getParent()));
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001460 AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
Michael Gottesman556ff612013-01-12 01:25:19 +00001461 Class = IC_Autorelease;
Michael Gottesman10426b52013-01-07 21:26:07 +00001462
Michael Gottesman89279f82013-04-05 18:10:41 +00001463 DEBUG(dbgs() << "New: " << *AutoreleaseRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001464
John McCalld935e9c2011-06-15 23:37:01 +00001465}
1466
Michael Gottesman158fdf62013-03-28 20:11:19 +00001467// \brief Attempt to strength reduce objc_retainBlock calls to objc_retain
1468// calls.
1469//
1470// Specifically: If an objc_retainBlock call has the copy_on_escape metadata and
1471// does not escape (following the rules of block escaping), strength reduce the
1472// objc_retainBlock to an objc_retain.
1473//
1474// TODO: If an objc_retainBlock call is dominated period by a previous
1475// objc_retainBlock call, strength reduce the objc_retainBlock to an
1476// objc_retain.
1477bool
1478ObjCARCOpt::OptimizeRetainBlockCall(Function &F, Instruction *Inst,
1479 InstructionClass &Class) {
1480 assert(GetBasicInstructionClass(Inst) == Class);
1481 assert(IC_RetainBlock == Class);
Michael Gottesman60f6b282013-03-29 05:13:07 +00001482
Michael Gottesman158fdf62013-03-28 20:11:19 +00001483 // If we can not optimize Inst, return false.
1484 if (!IsRetainBlockOptimizable(Inst))
1485 return false;
Michael Gottesman60f6b282013-03-29 05:13:07 +00001486
Michael Gottesman3eab2e42013-04-21 00:50:27 +00001487 Changed = true;
1488 ++NumPeeps;
1489
1490 DEBUG(dbgs() << "Strength reduced retainBlock => retain.\n");
1491 DEBUG(dbgs() << "Old: " << *Inst << "\n");
Michael Gottesman158fdf62013-03-28 20:11:19 +00001492 CallInst *RetainBlock = cast<CallInst>(Inst);
1493 RetainBlock->setCalledFunction(getRetainCallee(F.getParent()));
1494 // Remove copy_on_escape metadata.
1495 RetainBlock->setMetadata(CopyOnEscapeMDKind, 0);
1496 Class = IC_Retain;
Michael Gottesman3eab2e42013-04-21 00:50:27 +00001497 DEBUG(dbgs() << "New: " << *Inst << "\n");
Michael Gottesman158fdf62013-03-28 20:11:19 +00001498 return true;
1499}
1500
Michael Gottesman97e3df02013-01-14 00:35:14 +00001501/// Visit each call, one at a time, and make simplifications without doing any
1502/// additional analysis.
John McCalld935e9c2011-06-15 23:37:01 +00001503void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001504 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeIndividualCalls ==\n");
John McCalld935e9c2011-06-15 23:37:01 +00001505 // Reset all the flags in preparation for recomputing them.
1506 UsedInThisFunction = 0;
1507
1508 // Visit all objc_* calls in F.
1509 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
1510 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +00001511
John McCalld935e9c2011-06-15 23:37:01 +00001512 InstructionClass Class = GetBasicInstructionClass(Inst);
1513
Michael Gottesman89279f82013-04-05 18:10:41 +00001514 DEBUG(dbgs() << "Visiting: Class: " << Class << "; " << *Inst << "\n");
Michael Gottesman782e3442013-01-17 18:32:34 +00001515
John McCalld935e9c2011-06-15 23:37:01 +00001516 switch (Class) {
1517 default: break;
1518
1519 // Delete no-op casts. These function calls have special semantics, but
1520 // the semantics are entirely implemented via lowering in the front-end,
1521 // so by the time they reach the optimizer, they are just no-op calls
1522 // which return their argument.
1523 //
1524 // There are gray areas here, as the ability to cast reference-counted
1525 // pointers to raw void* and back allows code to break ARC assumptions,
1526 // however these are currently considered to be unimportant.
1527 case IC_NoopCast:
1528 Changed = true;
1529 ++NumNoops;
Michael Gottesman89279f82013-04-05 18:10:41 +00001530 DEBUG(dbgs() << "Erasing no-op cast: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001531 EraseInstruction(Inst);
1532 continue;
1533
1534 // If the pointer-to-weak-pointer is null, it's undefined behavior.
1535 case IC_StoreWeak:
1536 case IC_LoadWeak:
1537 case IC_LoadWeakRetained:
1538 case IC_InitWeak:
1539 case IC_DestroyWeak: {
1540 CallInst *CI = cast<CallInst>(Inst);
Michael Gottesman65c24812013-03-25 09:27:43 +00001541 if (IsNullOrUndef(CI->getArgOperand(0))) {
Dan Gohman670f9372012-04-13 18:57:48 +00001542 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +00001543 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001544 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1545 Constant::getNullValue(Ty),
1546 CI);
Michael Gottesman10426b52013-01-07 21:26:07 +00001547 llvm::Value *NewValue = UndefValue::get(CI->getType());
Michael Gottesman89279f82013-04-05 18:10:41 +00001548 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
1549 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001550 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +00001551 CI->eraseFromParent();
1552 continue;
1553 }
1554 break;
1555 }
1556 case IC_CopyWeak:
1557 case IC_MoveWeak: {
1558 CallInst *CI = cast<CallInst>(Inst);
Michael Gottesman65c24812013-03-25 09:27:43 +00001559 if (IsNullOrUndef(CI->getArgOperand(0)) ||
1560 IsNullOrUndef(CI->getArgOperand(1))) {
Dan Gohman670f9372012-04-13 18:57:48 +00001561 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +00001562 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001563 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1564 Constant::getNullValue(Ty),
1565 CI);
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001566
1567 llvm::Value *NewValue = UndefValue::get(CI->getType());
Michael Gottesman89279f82013-04-05 18:10:41 +00001568 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
1569 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001570
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001571 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +00001572 CI->eraseFromParent();
1573 continue;
1574 }
1575 break;
1576 }
Michael Gottesman158fdf62013-03-28 20:11:19 +00001577 case IC_RetainBlock:
Michael Gottesman1e430042013-04-21 00:44:46 +00001578 // If we strength reduce an objc_retainBlock to an objc_retain, continue
Michael Gottesman158fdf62013-03-28 20:11:19 +00001579 // onto the objc_retain peephole optimizations. Otherwise break.
Michael Gottesman9fc50b82013-05-13 18:29:07 +00001580 OptimizeRetainBlockCall(F, Inst, Class);
John McCalld935e9c2011-06-15 23:37:01 +00001581 break;
1582 case IC_RetainRV:
1583 if (OptimizeRetainRVCall(F, Inst))
1584 continue;
1585 break;
1586 case IC_AutoreleaseRV:
Michael Gottesman556ff612013-01-12 01:25:19 +00001587 OptimizeAutoreleaseRVCall(F, Inst, Class);
John McCalld935e9c2011-06-15 23:37:01 +00001588 break;
1589 }
1590
Michael Gottesmanb8c88362013-04-03 02:57:24 +00001591 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
John McCalld935e9c2011-06-15 23:37:01 +00001592 if (IsAutorelease(Class) && Inst->use_empty()) {
1593 CallInst *Call = cast<CallInst>(Inst);
1594 const Value *Arg = Call->getArgOperand(0);
1595 Arg = FindSingleUseIdentifiedObject(Arg);
1596 if (Arg) {
1597 Changed = true;
1598 ++NumAutoreleases;
1599
1600 // Create the declaration lazily.
1601 LLVMContext &C = Inst->getContext();
1602 CallInst *NewCall =
1603 CallInst::Create(getReleaseCallee(F.getParent()),
1604 Call->getArgOperand(0), "", Call);
Dmitri Gribenko3238fb72013-05-05 00:40:33 +00001605 NewCall->setMetadata(ImpreciseReleaseMDKind, MDNode::get(C, None));
Michael Gottesman10426b52013-01-07 21:26:07 +00001606
Michael Gottesman89279f82013-04-05 18:10:41 +00001607 DEBUG(dbgs() << "Replacing autorelease{,RV}(x) with objc_release(x) "
1608 "since x is otherwise unused.\nOld: " << *Call << "\nNew: "
1609 << *NewCall << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001610
John McCalld935e9c2011-06-15 23:37:01 +00001611 EraseInstruction(Call);
1612 Inst = NewCall;
1613 Class = IC_Release;
1614 }
1615 }
1616
1617 // For functions which can never be passed stack arguments, add
1618 // a tail keyword.
1619 if (IsAlwaysTail(Class)) {
1620 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +00001621 DEBUG(dbgs() << "Adding tail keyword to function since it can never be "
1622 "passed stack args: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001623 cast<CallInst>(Inst)->setTailCall();
1624 }
1625
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001626 // Ensure that functions that can never have a "tail" keyword due to the
1627 // semantics of ARC truly do not do so.
1628 if (IsNeverTail(Class)) {
1629 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +00001630 DEBUG(dbgs() << "Removing tail keyword from function: " << *Inst <<
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001631 "\n");
1632 cast<CallInst>(Inst)->setTailCall(false);
1633 }
1634
John McCalld935e9c2011-06-15 23:37:01 +00001635 // Set nounwind as needed.
1636 if (IsNoThrow(Class)) {
1637 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +00001638 DEBUG(dbgs() << "Found no throw class. Setting nounwind on: " << *Inst
1639 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001640 cast<CallInst>(Inst)->setDoesNotThrow();
1641 }
1642
1643 if (!IsNoopOnNull(Class)) {
1644 UsedInThisFunction |= 1 << Class;
1645 continue;
1646 }
1647
1648 const Value *Arg = GetObjCArg(Inst);
1649
1650 // ARC calls with null are no-ops. Delete them.
Michael Gottesman65c24812013-03-25 09:27:43 +00001651 if (IsNullOrUndef(Arg)) {
John McCalld935e9c2011-06-15 23:37:01 +00001652 Changed = true;
1653 ++NumNoops;
Michael Gottesman89279f82013-04-05 18:10:41 +00001654 DEBUG(dbgs() << "ARC calls with null are no-ops. Erasing: " << *Inst
1655 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001656 EraseInstruction(Inst);
1657 continue;
1658 }
1659
1660 // Keep track of which of retain, release, autorelease, and retain_block
1661 // are actually present in this function.
1662 UsedInThisFunction |= 1 << Class;
1663
1664 // If Arg is a PHI, and one or more incoming values to the
1665 // PHI are null, and the call is control-equivalent to the PHI, and there
1666 // are no relevant side effects between the PHI and the call, the call
1667 // could be pushed up to just those paths with non-null incoming values.
1668 // For now, don't bother splitting critical edges for this.
1669 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
1670 Worklist.push_back(std::make_pair(Inst, Arg));
1671 do {
1672 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
1673 Inst = Pair.first;
1674 Arg = Pair.second;
1675
1676 const PHINode *PN = dyn_cast<PHINode>(Arg);
1677 if (!PN) continue;
1678
1679 // Determine if the PHI has any null operands, or any incoming
1680 // critical edges.
1681 bool HasNull = false;
1682 bool HasCriticalEdges = false;
1683 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1684 Value *Incoming =
1685 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
Michael Gottesman65c24812013-03-25 09:27:43 +00001686 if (IsNullOrUndef(Incoming))
John McCalld935e9c2011-06-15 23:37:01 +00001687 HasNull = true;
1688 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
1689 .getNumSuccessors() != 1) {
1690 HasCriticalEdges = true;
1691 break;
1692 }
1693 }
1694 // If we have null operands and no critical edges, optimize.
1695 if (!HasCriticalEdges && HasNull) {
1696 SmallPtrSet<Instruction *, 4> DependingInstructions;
1697 SmallPtrSet<const BasicBlock *, 4> Visited;
1698
1699 // Check that there is nothing that cares about the reference
1700 // count between the call and the phi.
Dan Gohman8478d762012-04-13 00:59:57 +00001701 switch (Class) {
1702 case IC_Retain:
1703 case IC_RetainBlock:
1704 // These can always be moved up.
1705 break;
1706 case IC_Release:
Dan Gohman41375a32012-05-08 23:39:44 +00001707 // These can't be moved across things that care about the retain
1708 // count.
Dan Gohman8478d762012-04-13 00:59:57 +00001709 FindDependencies(NeedsPositiveRetainCount, Arg,
1710 Inst->getParent(), Inst,
1711 DependingInstructions, Visited, PA);
1712 break;
1713 case IC_Autorelease:
1714 // These can't be moved across autorelease pool scope boundaries.
1715 FindDependencies(AutoreleasePoolBoundary, Arg,
1716 Inst->getParent(), Inst,
1717 DependingInstructions, Visited, PA);
1718 break;
1719 case IC_RetainRV:
1720 case IC_AutoreleaseRV:
1721 // Don't move these; the RV optimization depends on the autoreleaseRV
1722 // being tail called, and the retainRV being immediately after a call
1723 // (which might still happen if we get lucky with codegen layout, but
1724 // it's not worth taking the chance).
1725 continue;
1726 default:
1727 llvm_unreachable("Invalid dependence flavor");
1728 }
1729
John McCalld935e9c2011-06-15 23:37:01 +00001730 if (DependingInstructions.size() == 1 &&
1731 *DependingInstructions.begin() == PN) {
1732 Changed = true;
1733 ++NumPartialNoops;
1734 // Clone the call into each predecessor that has a non-null value.
1735 CallInst *CInst = cast<CallInst>(Inst);
Chris Lattner229907c2011-07-18 04:54:35 +00001736 Type *ParamTy = CInst->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001737 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1738 Value *Incoming =
1739 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
Michael Gottesman65c24812013-03-25 09:27:43 +00001740 if (!IsNullOrUndef(Incoming)) {
John McCalld935e9c2011-06-15 23:37:01 +00001741 CallInst *Clone = cast<CallInst>(CInst->clone());
1742 Value *Op = PN->getIncomingValue(i);
1743 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
1744 if (Op->getType() != ParamTy)
1745 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
1746 Clone->setArgOperand(0, Op);
1747 Clone->insertBefore(InsertPos);
Michael Gottesmanc189a392013-01-09 19:23:24 +00001748
Michael Gottesman89279f82013-04-05 18:10:41 +00001749 DEBUG(dbgs() << "Cloning "
Michael Gottesmanc189a392013-01-09 19:23:24 +00001750 << *CInst << "\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00001751 "And inserting clone at " << *InsertPos << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001752 Worklist.push_back(std::make_pair(Clone, Incoming));
1753 }
1754 }
1755 // Erase the original call.
Michael Gottesmanc189a392013-01-09 19:23:24 +00001756 DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001757 EraseInstruction(CInst);
1758 continue;
1759 }
1760 }
1761 } while (!Worklist.empty());
1762 }
1763}
1764
Michael Gottesman323964c2013-04-18 05:39:45 +00001765/// If we have a top down pointer in the S_Use state, make sure that there are
1766/// no CFG hazards by checking the states of various bottom up pointers.
1767static void CheckForUseCFGHazard(const Sequence SuccSSeq,
1768 const bool SuccSRRIKnownSafe,
1769 PtrState &S,
1770 bool &SomeSuccHasSame,
1771 bool &AllSuccsHaveSame,
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001772 bool &NotAllSeqEqualButKnownSafe,
Michael Gottesman323964c2013-04-18 05:39:45 +00001773 bool &ShouldContinue) {
1774 switch (SuccSSeq) {
1775 case S_CanRelease: {
Michael Gottesman93132252013-06-21 06:59:02 +00001776 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe) {
Michael Gottesman323964c2013-04-18 05:39:45 +00001777 S.ClearSequenceProgress();
1778 break;
1779 }
Michael Gottesman2f294592013-06-21 19:12:36 +00001780 S.SetCFGHazardAfflicted(true);
Michael Gottesman323964c2013-04-18 05:39:45 +00001781 ShouldContinue = true;
1782 break;
1783 }
1784 case S_Use:
1785 SomeSuccHasSame = true;
1786 break;
1787 case S_Stop:
1788 case S_Release:
1789 case S_MovableRelease:
Michael Gottesman93132252013-06-21 06:59:02 +00001790 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe)
Michael Gottesman323964c2013-04-18 05:39:45 +00001791 AllSuccsHaveSame = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001792 else
1793 NotAllSeqEqualButKnownSafe = true;
Michael Gottesman323964c2013-04-18 05:39:45 +00001794 break;
1795 case S_Retain:
1796 llvm_unreachable("bottom-up pointer in retain state!");
1797 case S_None:
1798 llvm_unreachable("This should have been handled earlier.");
1799 }
1800}
1801
1802/// If we have a Top Down pointer in the S_CanRelease state, make sure that
1803/// there are no CFG hazards by checking the states of various bottom up
1804/// pointers.
1805static void CheckForCanReleaseCFGHazard(const Sequence SuccSSeq,
1806 const bool SuccSRRIKnownSafe,
1807 PtrState &S,
1808 bool &SomeSuccHasSame,
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001809 bool &AllSuccsHaveSame,
1810 bool &NotAllSeqEqualButKnownSafe) {
Michael Gottesman323964c2013-04-18 05:39:45 +00001811 switch (SuccSSeq) {
1812 case S_CanRelease:
1813 SomeSuccHasSame = true;
1814 break;
1815 case S_Stop:
1816 case S_Release:
1817 case S_MovableRelease:
1818 case S_Use:
Michael Gottesman93132252013-06-21 06:59:02 +00001819 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe)
Michael Gottesman323964c2013-04-18 05:39:45 +00001820 AllSuccsHaveSame = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001821 else
1822 NotAllSeqEqualButKnownSafe = true;
Michael Gottesman323964c2013-04-18 05:39:45 +00001823 break;
1824 case S_Retain:
1825 llvm_unreachable("bottom-up pointer in retain state!");
1826 case S_None:
1827 llvm_unreachable("This should have been handled earlier.");
1828 }
1829}
1830
Michael Gottesman97e3df02013-01-14 00:35:14 +00001831/// Check for critical edges, loop boundaries, irreducible control flow, or
1832/// other CFG structures where moving code across the edge would result in it
1833/// being executed more.
John McCalld935e9c2011-06-15 23:37:01 +00001834void
1835ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
1836 DenseMap<const BasicBlock *, BBState> &BBStates,
1837 BBState &MyStates) const {
1838 // If any top-down local-use or possible-dec has a succ which is earlier in
1839 // the sequence, forget it.
Dan Gohman55b06742012-03-02 01:13:53 +00001840 for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
Michael Gottesman323964c2013-04-18 05:39:45 +00001841 E = MyStates.top_down_ptr_end(); I != E; ++I) {
1842 PtrState &S = I->second;
1843 const Sequence Seq = I->second.GetSeq();
Dan Gohman0155f302012-02-17 18:59:53 +00001844
Michael Gottesman323964c2013-04-18 05:39:45 +00001845 // We only care about S_Retain, S_CanRelease, and S_Use.
1846 if (Seq == S_None)
1847 continue;
Dan Gohman0155f302012-02-17 18:59:53 +00001848
Michael Gottesman323964c2013-04-18 05:39:45 +00001849 // Make sure that if extra top down states are added in the future that this
1850 // code is updated to handle it.
1851 assert((Seq == S_Retain || Seq == S_CanRelease || Seq == S_Use) &&
1852 "Unknown top down sequence state.");
1853
1854 const Value *Arg = I->first;
1855 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
1856 bool SomeSuccHasSame = false;
1857 bool AllSuccsHaveSame = true;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001858 bool NotAllSeqEqualButKnownSafe = false;
Michael Gottesman323964c2013-04-18 05:39:45 +00001859
1860 succ_const_iterator SI(TI), SE(TI, false);
1861
1862 for (; SI != SE; ++SI) {
1863 // If VisitBottomUp has pointer information for this successor, take
1864 // what we know about it.
1865 const DenseMap<const BasicBlock *, BBState>::iterator BBI =
1866 BBStates.find(*SI);
1867 assert(BBI != BBStates.end());
1868 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
1869 const Sequence SuccSSeq = SuccS.GetSeq();
1870
1871 // If bottom up, the pointer is in an S_None state, clear the sequence
1872 // progress since the sequence in the bottom up state finished
1873 // suggesting a mismatch in between retains/releases. This is true for
1874 // all three cases that we are handling here: S_Retain, S_Use, and
1875 // S_CanRelease.
1876 if (SuccSSeq == S_None) {
Dan Gohman12130272011-08-12 00:26:31 +00001877 S.ClearSequenceProgress();
Michael Gottesman323964c2013-04-18 05:39:45 +00001878 continue;
1879 }
1880
1881 // If we have S_Use or S_CanRelease, perform our check for cfg hazard
1882 // checks.
Michael Gottesman93132252013-06-21 06:59:02 +00001883 const bool SuccSRRIKnownSafe = SuccS.IsKnownSafe();
Michael Gottesman323964c2013-04-18 05:39:45 +00001884
1885 // *NOTE* We do not use Seq from above here since we are allowing for
1886 // S.GetSeq() to change while we are visiting basic blocks.
1887 switch(S.GetSeq()) {
1888 case S_Use: {
1889 bool ShouldContinue = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001890 CheckForUseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S, SomeSuccHasSame,
1891 AllSuccsHaveSame, NotAllSeqEqualButKnownSafe,
Michael Gottesman323964c2013-04-18 05:39:45 +00001892 ShouldContinue);
1893 if (ShouldContinue)
1894 continue;
1895 break;
1896 }
1897 case S_CanRelease: {
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001898 CheckForCanReleaseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S,
1899 SomeSuccHasSame, AllSuccsHaveSame,
1900 NotAllSeqEqualButKnownSafe);
Michael Gottesman323964c2013-04-18 05:39:45 +00001901 break;
1902 }
1903 case S_Retain:
1904 case S_None:
1905 case S_Stop:
1906 case S_Release:
1907 case S_MovableRelease:
1908 break;
1909 }
John McCalld935e9c2011-06-15 23:37:01 +00001910 }
Michael Gottesman323964c2013-04-18 05:39:45 +00001911
1912 // If the state at the other end of any of the successor edges
1913 // matches the current state, require all edges to match. This
1914 // guards against loops in the middle of a sequence.
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001915 if (SomeSuccHasSame && !AllSuccsHaveSame) {
Michael Gottesman323964c2013-04-18 05:39:45 +00001916 S.ClearSequenceProgress();
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001917 } else if (NotAllSeqEqualButKnownSafe) {
1918 // If we would have cleared the state foregoing the fact that we are known
1919 // safe, stop code motion. This is because whether or not it is safe to
1920 // remove RR pairs via KnownSafe is an orthogonal concept to whether we
1921 // are allowed to perform code motion.
Michael Gottesman2f294592013-06-21 19:12:36 +00001922 S.SetCFGHazardAfflicted(true);
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001923 }
Michael Gottesman323964c2013-04-18 05:39:45 +00001924 }
John McCalld935e9c2011-06-15 23:37:01 +00001925}
1926
1927bool
Dan Gohman817a7c62012-03-22 18:24:56 +00001928ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
Dan Gohman5c70fad2012-03-23 17:47:54 +00001929 BasicBlock *BB,
Dan Gohman817a7c62012-03-22 18:24:56 +00001930 MapVector<Value *, RRInfo> &Retains,
1931 BBState &MyStates) {
1932 bool NestingDetected = false;
1933 InstructionClass Class = GetInstructionClass(Inst);
1934 const Value *Arg = 0;
Michael Gottesman79249972013-04-05 23:46:45 +00001935
Michael Gottesman1d8d2572013-04-05 22:54:28 +00001936 DEBUG(dbgs() << "Class: " << Class << "\n");
Michael Gottesman79249972013-04-05 23:46:45 +00001937
Dan Gohman817a7c62012-03-22 18:24:56 +00001938 switch (Class) {
1939 case IC_Release: {
1940 Arg = GetObjCArg(Inst);
1941
1942 PtrState &S = MyStates.getPtrBottomUpState(Arg);
1943
1944 // If we see two releases in a row on the same pointer. If so, make
1945 // a note, and we'll cicle back to revisit it after we've
1946 // hopefully eliminated the second release, which may allow us to
1947 // eliminate the first release too.
1948 // Theoretically we could implement removal of nested retain+release
1949 // pairs by making PtrState hold a stack of states, but this is
1950 // simple and avoids adding overhead for the non-nested case.
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001951 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001952 DEBUG(dbgs() << "Found nested releases (i.e. a release pair)\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00001953 NestingDetected = true;
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001954 }
Dan Gohman817a7c62012-03-22 18:24:56 +00001955
Dan Gohman817a7c62012-03-22 18:24:56 +00001956 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001957 Sequence NewSeq = ReleaseMetadata ? S_MovableRelease : S_Release;
1958 ANNOTATE_BOTTOMUP(Inst, Arg, S.GetSeq(), NewSeq);
1959 S.ResetSequenceProgress(NewSeq);
Michael Gottesmanf701d3f2013-06-21 07:03:07 +00001960 S.SetReleaseMetadata(ReleaseMetadata);
Michael Gottesman93132252013-06-21 06:59:02 +00001961 S.SetKnownSafe(S.HasKnownPositiveRefCount());
Michael Gottesmanb82a1792013-06-21 07:00:44 +00001962 S.SetTailCallRelease(cast<CallInst>(Inst)->isTailCall());
Michael Gottesman4f6ef112013-06-21 19:44:27 +00001963 S.InsertCall(Inst);
Dan Gohmandf476e52012-09-04 23:16:20 +00001964 S.SetKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001965 break;
1966 }
1967 case IC_RetainBlock:
Michael Gottesman158fdf62013-03-28 20:11:19 +00001968 // In OptimizeIndividualCalls, we have strength reduced all optimizable
1969 // objc_retainBlocks to objc_retains. Thus at this point any
1970 // objc_retainBlocks that we see are not optimizable.
1971 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001972 case IC_Retain:
1973 case IC_RetainRV: {
1974 Arg = GetObjCArg(Inst);
1975
1976 PtrState &S = MyStates.getPtrBottomUpState(Arg);
Dan Gohman62079b42012-04-25 00:50:46 +00001977 S.SetKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001978
Michael Gottesman81b1d432013-03-26 00:42:04 +00001979 Sequence OldSeq = S.GetSeq();
1980 switch (OldSeq) {
Dan Gohman817a7c62012-03-22 18:24:56 +00001981 case S_Stop:
1982 case S_Release:
1983 case S_MovableRelease:
1984 case S_Use:
Michael Gottesman1d8d2572013-04-05 22:54:28 +00001985 // If OldSeq is not S_Use or OldSeq is S_Use and we are tracking an
1986 // imprecise release, clear our reverse insertion points.
Michael Gottesmanf0401182013-06-21 19:12:38 +00001987 if (OldSeq != S_Use || S.IsTrackingImpreciseReleases())
Michael Gottesman4f6ef112013-06-21 19:44:27 +00001988 S.ClearReverseInsertPts();
Dan Gohman817a7c62012-03-22 18:24:56 +00001989 // FALL THROUGH
1990 case S_CanRelease:
1991 // Don't do retain+release tracking for IC_RetainRV, because it's
1992 // better to let it remain as the first instruction after a call.
Michael Gottesmanba648592013-03-28 23:08:44 +00001993 if (Class != IC_RetainRV)
Dan Gohman817a7c62012-03-22 18:24:56 +00001994 Retains[Inst] = S.RRI;
Dan Gohman817a7c62012-03-22 18:24:56 +00001995 S.ClearSequenceProgress();
1996 break;
1997 case S_None:
1998 break;
1999 case S_Retain:
2000 llvm_unreachable("bottom-up pointer in retain state!");
2001 }
Michael Gottesman79249972013-04-05 23:46:45 +00002002 ANNOTATE_BOTTOMUP(Inst, Arg, OldSeq, S.GetSeq());
Michael Gottesman31ba23a2013-04-05 22:54:32 +00002003 // A retain moving bottom up can be a use.
2004 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00002005 }
2006 case IC_AutoreleasepoolPop:
2007 // Conservatively, clear MyStates for all known pointers.
2008 MyStates.clearBottomUpPointers();
2009 return NestingDetected;
2010 case IC_AutoreleasepoolPush:
2011 case IC_None:
2012 // These are irrelevant.
2013 return NestingDetected;
Michael Gottesmana76143ee2013-05-13 23:49:42 +00002014 case IC_User:
2015 // If we have a store into an alloca of a pointer we are tracking, the
2016 // pointer has multiple owners implying that we must be more conservative.
2017 //
2018 // This comes up in the context of a pointer being ``KnownSafe''. In the
2019 // presense of a block being initialized, the frontend will emit the
2020 // objc_retain on the original pointer and the release on the pointer loaded
2021 // from the alloca. The optimizer will through the provenance analysis
2022 // realize that the two are related, but since we only require KnownSafe in
2023 // one direction, will match the inner retain on the original pointer with
2024 // the guard release on the original pointer. This is fixed by ensuring that
2025 // in the presense of allocas we only unconditionally remove pointers if
2026 // both our retain and our release are KnownSafe.
2027 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
2028 if (AreAnyUnderlyingObjectsAnAlloca(SI->getPointerOperand())) {
2029 BBState::ptr_iterator I = MyStates.findPtrBottomUpState(
2030 StripPointerCastsAndObjCCalls(SI->getValueOperand()));
2031 if (I != MyStates.bottom_up_ptr_end())
Michael Gottesman5a91bbf2013-05-24 20:44:02 +00002032 MultiOwnersSet.insert(I->first);
Michael Gottesmana76143ee2013-05-13 23:49:42 +00002033 }
2034 }
2035 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00002036 default:
2037 break;
2038 }
2039
2040 // Consider any other possible effects of this instruction on each
2041 // pointer being tracked.
2042 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
2043 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
2044 const Value *Ptr = MI->first;
2045 if (Ptr == Arg)
2046 continue; // Handled above.
2047 PtrState &S = MI->second;
2048 Sequence Seq = S.GetSeq();
2049
2050 // Check for possible releases.
2051 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002052 DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr
2053 << "\n");
Michael Gottesman764b1cf2013-03-23 05:46:19 +00002054 S.ClearKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00002055 switch (Seq) {
2056 case S_Use:
2057 S.SetSeq(S_CanRelease);
Michael Gottesman81b1d432013-03-26 00:42:04 +00002058 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S.GetSeq());
Dan Gohman817a7c62012-03-22 18:24:56 +00002059 continue;
2060 case S_CanRelease:
2061 case S_Release:
2062 case S_MovableRelease:
2063 case S_Stop:
2064 case S_None:
2065 break;
2066 case S_Retain:
2067 llvm_unreachable("bottom-up pointer in retain state!");
2068 }
2069 }
2070
2071 // Check for possible direct uses.
2072 switch (Seq) {
2073 case S_Release:
2074 case S_MovableRelease:
2075 if (CanUse(Inst, Ptr, PA, Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002076 DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr
2077 << "\n");
Michael Gottesman4f6ef112013-06-21 19:44:27 +00002078 assert(!S.HasReverseInsertPts());
Dan Gohman5c70fad2012-03-23 17:47:54 +00002079 // If this is an invoke instruction, we're scanning it as part of
2080 // one of its successor blocks, since we can't insert code after it
2081 // in its own block, and we don't want to split critical edges.
2082 if (isa<InvokeInst>(Inst))
Michael Gottesman4f6ef112013-06-21 19:44:27 +00002083 S.InsertReverseInsertPt(BB->getFirstInsertionPt());
Dan Gohman5c70fad2012-03-23 17:47:54 +00002084 else
Michael Gottesman4f6ef112013-06-21 19:44:27 +00002085 S.InsertReverseInsertPt(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohman817a7c62012-03-22 18:24:56 +00002086 S.SetSeq(S_Use);
Michael Gottesman81b1d432013-03-26 00:42:04 +00002087 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
John McCall20182ac2013-03-22 21:38:36 +00002088 } else if (Seq == S_Release && IsUser(Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002089 DEBUG(dbgs() << "PreciseReleaseUse: Seq: " << Seq << "; " << *Ptr
2090 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00002091 // Non-movable releases depend on any possible objc pointer use.
2092 S.SetSeq(S_Stop);
Michael Gottesman81b1d432013-03-26 00:42:04 +00002093 ANNOTATE_BOTTOMUP(Inst, Ptr, S_Release, S_Stop);
Michael Gottesman4f6ef112013-06-21 19:44:27 +00002094 assert(!S.HasReverseInsertPts());
Dan Gohman5c70fad2012-03-23 17:47:54 +00002095 // As above; handle invoke specially.
2096 if (isa<InvokeInst>(Inst))
Michael Gottesman4f6ef112013-06-21 19:44:27 +00002097 S.InsertReverseInsertPt(BB->getFirstInsertionPt());
Dan Gohman5c70fad2012-03-23 17:47:54 +00002098 else
Michael Gottesman4f6ef112013-06-21 19:44:27 +00002099 S.InsertReverseInsertPt(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohman817a7c62012-03-22 18:24:56 +00002100 }
2101 break;
2102 case S_Stop:
Michael Gottesman81b1d432013-03-26 00:42:04 +00002103 if (CanUse(Inst, Ptr, PA, Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002104 DEBUG(dbgs() << "PreciseStopUse: Seq: " << Seq << "; " << *Ptr
2105 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00002106 S.SetSeq(S_Use);
Michael Gottesman81b1d432013-03-26 00:42:04 +00002107 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
2108 }
Dan Gohman817a7c62012-03-22 18:24:56 +00002109 break;
2110 case S_CanRelease:
2111 case S_Use:
2112 case S_None:
2113 break;
2114 case S_Retain:
2115 llvm_unreachable("bottom-up pointer in retain state!");
2116 }
2117 }
2118
2119 return NestingDetected;
2120}
2121
2122bool
John McCalld935e9c2011-06-15 23:37:01 +00002123ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2124 DenseMap<const BasicBlock *, BBState> &BBStates,
2125 MapVector<Value *, RRInfo> &Retains) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002126
2127 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitBottomUp ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00002128
John McCalld935e9c2011-06-15 23:37:01 +00002129 bool NestingDetected = false;
2130 BBState &MyStates = BBStates[BB];
2131
2132 // Merge the states from each successor to compute the initial state
2133 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00002134 BBState::edge_iterator SI(MyStates.succ_begin()),
2135 SE(MyStates.succ_end());
2136 if (SI != SE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002137 const BasicBlock *Succ = *SI;
2138 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
2139 assert(I != BBStates.end());
2140 MyStates.InitFromSucc(I->second);
2141 ++SI;
2142 for (; SI != SE; ++SI) {
2143 Succ = *SI;
2144 I = BBStates.find(Succ);
2145 assert(I != BBStates.end());
2146 MyStates.MergeSucc(I->second);
2147 }
Michael Gottesman60f6b282013-03-29 05:13:07 +00002148 }
Michael Gottesmancd4de0f2013-03-26 00:42:09 +00002149
Michael Gottesman43e7e002013-04-03 22:41:59 +00002150 // If ARC Annotations are enabled, output the current state of pointers at the
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002151 // bottom of the basic block.
Michael Gottesman43e7e002013-04-03 22:41:59 +00002152 ANNOTATE_BOTTOMUP_BBEND(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002153
John McCalld935e9c2011-06-15 23:37:01 +00002154 // Visit all the instructions, bottom-up.
2155 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2156 Instruction *Inst = llvm::prior(I);
Dan Gohman5c70fad2012-03-23 17:47:54 +00002157
2158 // Invoke instructions are visited as part of their successors (below).
2159 if (isa<InvokeInst>(Inst))
2160 continue;
2161
Michael Gottesman89279f82013-04-05 18:10:41 +00002162 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00002163
Dan Gohman5c70fad2012-03-23 17:47:54 +00002164 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
2165 }
2166
Dan Gohmandae33492012-04-27 18:56:31 +00002167 // If there's a predecessor with an invoke, visit the invoke as if it were
2168 // part of this block, since we can't insert code after an invoke in its own
2169 // block, and we don't want to split critical edges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002170 for (BBState::edge_iterator PI(MyStates.pred_begin()),
2171 PE(MyStates.pred_end()); PI != PE; ++PI) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00002172 BasicBlock *Pred = *PI;
Dan Gohmandae33492012-04-27 18:56:31 +00002173 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
2174 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
Dan Gohman817a7c62012-03-22 18:24:56 +00002175 }
John McCalld935e9c2011-06-15 23:37:01 +00002176
Michael Gottesman43e7e002013-04-03 22:41:59 +00002177 // If ARC Annotations are enabled, output the current state of pointers at the
2178 // top of the basic block.
2179 ANNOTATE_BOTTOMUP_BBSTART(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002180
Dan Gohman817a7c62012-03-22 18:24:56 +00002181 return NestingDetected;
2182}
John McCalld935e9c2011-06-15 23:37:01 +00002183
Dan Gohman817a7c62012-03-22 18:24:56 +00002184bool
2185ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
2186 DenseMap<Value *, RRInfo> &Releases,
2187 BBState &MyStates) {
2188 bool NestingDetected = false;
2189 InstructionClass Class = GetInstructionClass(Inst);
2190 const Value *Arg = 0;
John McCalld935e9c2011-06-15 23:37:01 +00002191
Dan Gohman817a7c62012-03-22 18:24:56 +00002192 switch (Class) {
2193 case IC_RetainBlock:
Michael Gottesman158fdf62013-03-28 20:11:19 +00002194 // In OptimizeIndividualCalls, we have strength reduced all optimizable
2195 // objc_retainBlocks to objc_retains. Thus at this point any
2196 // objc_retainBlocks that we see are not optimizable.
2197 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00002198 case IC_Retain:
2199 case IC_RetainRV: {
2200 Arg = GetObjCArg(Inst);
2201
2202 PtrState &S = MyStates.getPtrTopDownState(Arg);
2203
2204 // Don't do retain+release tracking for IC_RetainRV, because it's
2205 // better to let it remain as the first instruction after a call.
2206 if (Class != IC_RetainRV) {
2207 // If we see two retains in a row on the same pointer. If so, make
John McCalld935e9c2011-06-15 23:37:01 +00002208 // a note, and we'll cicle back to revisit it after we've
Dan Gohman817a7c62012-03-22 18:24:56 +00002209 // hopefully eliminated the second retain, which may allow us to
2210 // eliminate the first retain too.
John McCalld935e9c2011-06-15 23:37:01 +00002211 // Theoretically we could implement removal of nested retain+release
2212 // pairs by making PtrState hold a stack of states, but this is
2213 // simple and avoids adding overhead for the non-nested case.
Dan Gohman817a7c62012-03-22 18:24:56 +00002214 if (S.GetSeq() == S_Retain)
John McCalld935e9c2011-06-15 23:37:01 +00002215 NestingDetected = true;
2216
Michael Gottesman81b1d432013-03-26 00:42:04 +00002217 ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_Retain);
Dan Gohman62079b42012-04-25 00:50:46 +00002218 S.ResetSequenceProgress(S_Retain);
Michael Gottesman93132252013-06-21 06:59:02 +00002219 S.SetKnownSafe(S.HasKnownPositiveRefCount());
Michael Gottesman4f6ef112013-06-21 19:44:27 +00002220 S.InsertCall(Inst);
John McCalld935e9c2011-06-15 23:37:01 +00002221 }
John McCalld935e9c2011-06-15 23:37:01 +00002222
Dan Gohmandf476e52012-09-04 23:16:20 +00002223 S.SetKnownPositiveRefCount();
Dan Gohmanf64ff8e2012-07-23 19:27:31 +00002224
2225 // A retain can be a potential use; procede to the generic checking
2226 // code below.
2227 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00002228 }
2229 case IC_Release: {
2230 Arg = GetObjCArg(Inst);
2231
2232 PtrState &S = MyStates.getPtrTopDownState(Arg);
Michael Gottesman764b1cf2013-03-23 05:46:19 +00002233 S.ClearKnownPositiveRefCount();
Michael Gottesman79249972013-04-05 23:46:45 +00002234
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002235 Sequence OldSeq = S.GetSeq();
Michael Gottesman79249972013-04-05 23:46:45 +00002236
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002237 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
Michael Gottesman79249972013-04-05 23:46:45 +00002238
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002239 switch (OldSeq) {
Dan Gohman817a7c62012-03-22 18:24:56 +00002240 case S_Retain:
2241 case S_CanRelease:
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002242 if (OldSeq == S_Retain || ReleaseMetadata != 0)
Michael Gottesman4f6ef112013-06-21 19:44:27 +00002243 S.ClearReverseInsertPts();
Dan Gohman817a7c62012-03-22 18:24:56 +00002244 // FALL THROUGH
2245 case S_Use:
Michael Gottesmanf701d3f2013-06-21 07:03:07 +00002246 S.SetReleaseMetadata(ReleaseMetadata);
Michael Gottesmanb82a1792013-06-21 07:00:44 +00002247 S.SetTailCallRelease(cast<CallInst>(Inst)->isTailCall());
Dan Gohman817a7c62012-03-22 18:24:56 +00002248 Releases[Inst] = S.RRI;
Michael Gottesman81b1d432013-03-26 00:42:04 +00002249 ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_None);
Dan Gohman817a7c62012-03-22 18:24:56 +00002250 S.ClearSequenceProgress();
2251 break;
2252 case S_None:
2253 break;
2254 case S_Stop:
2255 case S_Release:
2256 case S_MovableRelease:
2257 llvm_unreachable("top-down pointer in release state!");
2258 }
2259 break;
2260 }
2261 case IC_AutoreleasepoolPop:
2262 // Conservatively, clear MyStates for all known pointers.
2263 MyStates.clearTopDownPointers();
2264 return NestingDetected;
2265 case IC_AutoreleasepoolPush:
2266 case IC_None:
2267 // These are irrelevant.
2268 return NestingDetected;
2269 default:
2270 break;
2271 }
2272
2273 // Consider any other possible effects of this instruction on each
2274 // pointer being tracked.
2275 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
2276 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
2277 const Value *Ptr = MI->first;
2278 if (Ptr == Arg)
2279 continue; // Handled above.
2280 PtrState &S = MI->second;
2281 Sequence Seq = S.GetSeq();
2282
2283 // Check for possible releases.
2284 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Michael Gottesmanbab49e972013-04-05 18:26:08 +00002285 DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr
Michael Gottesman79249972013-04-05 23:46:45 +00002286 << "\n");
Michael Gottesman764b1cf2013-03-23 05:46:19 +00002287 S.ClearKnownPositiveRefCount();
John McCalld935e9c2011-06-15 23:37:01 +00002288 switch (Seq) {
Dan Gohman817a7c62012-03-22 18:24:56 +00002289 case S_Retain:
2290 S.SetSeq(S_CanRelease);
Michael Gottesman81b1d432013-03-26 00:42:04 +00002291 ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_CanRelease);
Michael Gottesman4f6ef112013-06-21 19:44:27 +00002292 assert(!S.HasReverseInsertPts());
2293 S.InsertReverseInsertPt(Inst);
Dan Gohman817a7c62012-03-22 18:24:56 +00002294
2295 // One call can't cause a transition from S_Retain to S_CanRelease
2296 // and S_CanRelease to S_Use. If we've made the first transition,
2297 // we're done.
2298 continue;
John McCalld935e9c2011-06-15 23:37:01 +00002299 case S_Use:
Dan Gohman817a7c62012-03-22 18:24:56 +00002300 case S_CanRelease:
John McCalld935e9c2011-06-15 23:37:01 +00002301 case S_None:
2302 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00002303 case S_Stop:
2304 case S_Release:
2305 case S_MovableRelease:
2306 llvm_unreachable("top-down pointer in release state!");
John McCalld935e9c2011-06-15 23:37:01 +00002307 }
2308 }
Dan Gohman817a7c62012-03-22 18:24:56 +00002309
2310 // Check for possible direct uses.
2311 switch (Seq) {
2312 case S_CanRelease:
Michael Gottesman81b1d432013-03-26 00:42:04 +00002313 if (CanUse(Inst, Ptr, PA, Class)) {
Michael Gottesmanbab49e972013-04-05 18:26:08 +00002314 DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr
2315 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00002316 S.SetSeq(S_Use);
Michael Gottesman81b1d432013-03-26 00:42:04 +00002317 ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_Use);
2318 }
Dan Gohman817a7c62012-03-22 18:24:56 +00002319 break;
2320 case S_Retain:
2321 case S_Use:
2322 case S_None:
2323 break;
2324 case S_Stop:
2325 case S_Release:
2326 case S_MovableRelease:
2327 llvm_unreachable("top-down pointer in release state!");
2328 }
John McCalld935e9c2011-06-15 23:37:01 +00002329 }
2330
2331 return NestingDetected;
2332}
2333
2334bool
2335ObjCARCOpt::VisitTopDown(BasicBlock *BB,
2336 DenseMap<const BasicBlock *, BBState> &BBStates,
2337 DenseMap<Value *, RRInfo> &Releases) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002338 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitTopDown ==\n");
John McCalld935e9c2011-06-15 23:37:01 +00002339 bool NestingDetected = false;
2340 BBState &MyStates = BBStates[BB];
2341
2342 // Merge the states from each predecessor to compute the initial state
2343 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00002344 BBState::edge_iterator PI(MyStates.pred_begin()),
2345 PE(MyStates.pred_end());
2346 if (PI != PE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002347 const BasicBlock *Pred = *PI;
2348 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
2349 assert(I != BBStates.end());
2350 MyStates.InitFromPred(I->second);
2351 ++PI;
2352 for (; PI != PE; ++PI) {
2353 Pred = *PI;
2354 I = BBStates.find(Pred);
2355 assert(I != BBStates.end());
2356 MyStates.MergePred(I->second);
2357 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002358 }
John McCalld935e9c2011-06-15 23:37:01 +00002359
Michael Gottesman43e7e002013-04-03 22:41:59 +00002360 // If ARC Annotations are enabled, output the current state of pointers at the
2361 // top of the basic block.
2362 ANNOTATE_TOPDOWN_BBSTART(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002363
John McCalld935e9c2011-06-15 23:37:01 +00002364 // Visit all the instructions, top-down.
2365 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2366 Instruction *Inst = I;
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00002367
Michael Gottesman89279f82013-04-05 18:10:41 +00002368 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00002369
Dan Gohman817a7c62012-03-22 18:24:56 +00002370 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00002371 }
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002372
Michael Gottesman43e7e002013-04-03 22:41:59 +00002373 // If ARC Annotations are enabled, output the current state of pointers at the
2374 // bottom of the basic block.
2375 ANNOTATE_TOPDOWN_BBEND(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002376
Michael Gottesmanffef24f2013-04-17 20:48:01 +00002377#ifdef ARC_ANNOTATIONS
Michael Gottesmanadb921a2013-04-17 21:03:53 +00002378 if (!(EnableARCAnnotations && DisableCheckForCFGHazards))
Michael Gottesmanffef24f2013-04-17 20:48:01 +00002379#endif
John McCalld935e9c2011-06-15 23:37:01 +00002380 CheckForCFGHazards(BB, BBStates, MyStates);
2381 return NestingDetected;
2382}
2383
Dan Gohmana53a12c2011-12-12 19:42:25 +00002384static void
2385ComputePostOrders(Function &F,
2386 SmallVectorImpl<BasicBlock *> &PostOrder,
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002387 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
2388 unsigned NoObjCARCExceptionsMDKind,
2389 DenseMap<const BasicBlock *, BBState> &BBStates) {
Michael Gottesman97e3df02013-01-14 00:35:14 +00002390 /// The visited set, for doing DFS walks.
Dan Gohmana53a12c2011-12-12 19:42:25 +00002391 SmallPtrSet<BasicBlock *, 16> Visited;
2392
2393 // Do DFS, computing the PostOrder.
2394 SmallPtrSet<BasicBlock *, 16> OnStack;
2395 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002396
2397 // Functions always have exactly one entry block, and we don't have
2398 // any other block that we treat like an entry block.
Dan Gohmana53a12c2011-12-12 19:42:25 +00002399 BasicBlock *EntryBB = &F.getEntryBlock();
Dan Gohman41375a32012-05-08 23:39:44 +00002400 BBState &MyStates = BBStates[EntryBB];
2401 MyStates.SetAsEntry();
2402 TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
2403 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
Dan Gohmana53a12c2011-12-12 19:42:25 +00002404 Visited.insert(EntryBB);
2405 OnStack.insert(EntryBB);
2406 do {
2407 dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002408 BasicBlock *CurrBB = SuccStack.back().first;
2409 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
2410 succ_iterator SE(TI, false);
Dan Gohman41375a32012-05-08 23:39:44 +00002411
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002412 while (SuccStack.back().second != SE) {
2413 BasicBlock *SuccBB = *SuccStack.back().second++;
2414 if (Visited.insert(SuccBB)) {
Dan Gohman41375a32012-05-08 23:39:44 +00002415 TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
2416 SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002417 BBStates[CurrBB].addSucc(SuccBB);
Dan Gohman41375a32012-05-08 23:39:44 +00002418 BBState &SuccStates = BBStates[SuccBB];
2419 SuccStates.addPred(CurrBB);
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002420 OnStack.insert(SuccBB);
Dan Gohmana53a12c2011-12-12 19:42:25 +00002421 goto dfs_next_succ;
2422 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002423
2424 if (!OnStack.count(SuccBB)) {
2425 BBStates[CurrBB].addSucc(SuccBB);
2426 BBStates[SuccBB].addPred(CurrBB);
2427 }
Dan Gohmana53a12c2011-12-12 19:42:25 +00002428 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002429 OnStack.erase(CurrBB);
2430 PostOrder.push_back(CurrBB);
2431 SuccStack.pop_back();
Dan Gohmana53a12c2011-12-12 19:42:25 +00002432 } while (!SuccStack.empty());
2433
2434 Visited.clear();
2435
Dan Gohmana53a12c2011-12-12 19:42:25 +00002436 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002437 // Functions may have many exits, and there also blocks which we treat
2438 // as exits due to ignored edges.
2439 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
2440 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
2441 BasicBlock *ExitBB = I;
2442 BBState &MyStates = BBStates[ExitBB];
2443 if (!MyStates.isExit())
2444 continue;
2445
Dan Gohmandae33492012-04-27 18:56:31 +00002446 MyStates.SetAsExit();
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002447
2448 PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00002449 Visited.insert(ExitBB);
2450 while (!PredStack.empty()) {
2451 reverse_dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002452 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
2453 while (PredStack.back().second != PE) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00002454 BasicBlock *BB = *PredStack.back().second++;
Dan Gohmana53a12c2011-12-12 19:42:25 +00002455 if (Visited.insert(BB)) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002456 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00002457 goto reverse_dfs_next_succ;
2458 }
2459 }
2460 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
2461 }
2462 }
2463}
2464
Michael Gottesman97e3df02013-01-14 00:35:14 +00002465// Visit the function both top-down and bottom-up.
John McCalld935e9c2011-06-15 23:37:01 +00002466bool
2467ObjCARCOpt::Visit(Function &F,
2468 DenseMap<const BasicBlock *, BBState> &BBStates,
2469 MapVector<Value *, RRInfo> &Retains,
2470 DenseMap<Value *, RRInfo> &Releases) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00002471
2472 // Use reverse-postorder traversals, because we magically know that loops
2473 // will be well behaved, i.e. they won't repeatedly call retain on a single
2474 // pointer without doing a release. We can't use the ReversePostOrderTraversal
2475 // class here because we want the reverse-CFG postorder to consider each
2476 // function exit point, and we want to ignore selected cycle edges.
2477 SmallVector<BasicBlock *, 16> PostOrder;
2478 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002479 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
2480 NoObjCARCExceptionsMDKind,
2481 BBStates);
Dan Gohmana53a12c2011-12-12 19:42:25 +00002482
2483 // Use reverse-postorder on the reverse CFG for bottom-up.
John McCalld935e9c2011-06-15 23:37:01 +00002484 bool BottomUpNestingDetected = false;
Dan Gohmanc57b58c2011-08-18 21:27:42 +00002485 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
Dan Gohmana53a12c2011-12-12 19:42:25 +00002486 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
2487 I != E; ++I)
2488 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
John McCalld935e9c2011-06-15 23:37:01 +00002489
Dan Gohmana53a12c2011-12-12 19:42:25 +00002490 // Use reverse-postorder for top-down.
John McCalld935e9c2011-06-15 23:37:01 +00002491 bool TopDownNestingDetected = false;
Dan Gohmana53a12c2011-12-12 19:42:25 +00002492 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2493 PostOrder.rbegin(), E = PostOrder.rend();
2494 I != E; ++I)
2495 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
John McCalld935e9c2011-06-15 23:37:01 +00002496
2497 return TopDownNestingDetected && BottomUpNestingDetected;
2498}
2499
Michael Gottesman97e3df02013-01-14 00:35:14 +00002500/// Move the calls in RetainsToMove and ReleasesToMove.
John McCalld935e9c2011-06-15 23:37:01 +00002501void ObjCARCOpt::MoveCalls(Value *Arg,
2502 RRInfo &RetainsToMove,
2503 RRInfo &ReleasesToMove,
2504 MapVector<Value *, RRInfo> &Retains,
2505 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman6320f522011-07-22 22:29:21 +00002506 SmallVectorImpl<Instruction *> &DeadInsts,
Michael Gottesman79249972013-04-05 23:46:45 +00002507 Module *M) {
Chris Lattner229907c2011-07-18 04:54:35 +00002508 Type *ArgTy = Arg->getType();
Dan Gohman6320f522011-07-22 22:29:21 +00002509 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
Michael Gottesman79249972013-04-05 23:46:45 +00002510
Michael Gottesman89279f82013-04-05 18:10:41 +00002511 DEBUG(dbgs() << "== ObjCARCOpt::MoveCalls ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00002512
John McCalld935e9c2011-06-15 23:37:01 +00002513 // Insert the new retain and release calls.
2514 for (SmallPtrSet<Instruction *, 2>::const_iterator
2515 PI = ReleasesToMove.ReverseInsertPts.begin(),
2516 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2517 Instruction *InsertPt = *PI;
2518 Value *MyArg = ArgTy == ParamTy ? Arg :
2519 new BitCastInst(Arg, ParamTy, "", InsertPt);
2520 CallInst *Call =
Michael Gottesmanba648592013-03-28 23:08:44 +00002521 CallInst::Create(getRetainCallee(M), MyArg, "", InsertPt);
John McCalld935e9c2011-06-15 23:37:01 +00002522 Call->setDoesNotThrow();
Michael Gottesmanba648592013-03-28 23:08:44 +00002523 Call->setTailCall();
Michael Gottesman60f6b282013-03-29 05:13:07 +00002524
Michael Gottesmandf110ac2013-04-21 00:30:50 +00002525 DEBUG(dbgs() << "Inserting new Retain: " << *Call << "\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00002526 "At insertion point: " << *InsertPt << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002527 }
2528 for (SmallPtrSet<Instruction *, 2>::const_iterator
2529 PI = RetainsToMove.ReverseInsertPts.begin(),
2530 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00002531 Instruction *InsertPt = *PI;
2532 Value *MyArg = ArgTy == ParamTy ? Arg :
2533 new BitCastInst(Arg, ParamTy, "", InsertPt);
2534 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
2535 "", InsertPt);
2536 // Attach a clang.imprecise_release metadata tag, if appropriate.
2537 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
2538 Call->setMetadata(ImpreciseReleaseMDKind, M);
2539 Call->setDoesNotThrow();
2540 if (ReleasesToMove.IsTailCallRelease)
2541 Call->setTailCall();
Michael Gottesmanc189a392013-01-09 19:23:24 +00002542
Michael Gottesman89279f82013-04-05 18:10:41 +00002543 DEBUG(dbgs() << "Inserting new Release: " << *Call << "\n"
2544 "At insertion point: " << *InsertPt << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002545 }
2546
2547 // Delete the original retain and release calls.
2548 for (SmallPtrSet<Instruction *, 2>::const_iterator
2549 AI = RetainsToMove.Calls.begin(),
2550 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
2551 Instruction *OrigRetain = *AI;
2552 Retains.blot(OrigRetain);
2553 DeadInsts.push_back(OrigRetain);
Michael Gottesman89279f82013-04-05 18:10:41 +00002554 DEBUG(dbgs() << "Deleting retain: " << *OrigRetain << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002555 }
2556 for (SmallPtrSet<Instruction *, 2>::const_iterator
2557 AI = ReleasesToMove.Calls.begin(),
2558 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
2559 Instruction *OrigRelease = *AI;
2560 Releases.erase(OrigRelease);
2561 DeadInsts.push_back(OrigRelease);
Michael Gottesman89279f82013-04-05 18:10:41 +00002562 DEBUG(dbgs() << "Deleting release: " << *OrigRelease << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002563 }
Michael Gottesman79249972013-04-05 23:46:45 +00002564
John McCalld935e9c2011-06-15 23:37:01 +00002565}
2566
Michael Gottesman9de6f962013-01-22 21:49:00 +00002567bool
2568ObjCARCOpt::ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState>
2569 &BBStates,
2570 MapVector<Value *, RRInfo> &Retains,
2571 DenseMap<Value *, RRInfo> &Releases,
2572 Module *M,
2573 SmallVector<Instruction *, 4> &NewRetains,
2574 SmallVector<Instruction *, 4> &NewReleases,
2575 SmallVector<Instruction *, 8> &DeadInsts,
2576 RRInfo &RetainsToMove,
2577 RRInfo &ReleasesToMove,
2578 Value *Arg,
2579 bool KnownSafe,
2580 bool &AnyPairsCompletelyEliminated) {
2581 // If a pair happens in a region where it is known that the reference count
Michael Gottesmana76143ee2013-05-13 23:49:42 +00002582 // is already incremented, we can similarly ignore possible decrements unless
2583 // we are dealing with a retainable object with multiple provenance sources.
Michael Gottesman9de6f962013-01-22 21:49:00 +00002584 bool KnownSafeTD = true, KnownSafeBU = true;
Michael Gottesmana76143ee2013-05-13 23:49:42 +00002585 bool MultipleOwners = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00002586 bool CFGHazardAfflicted = false;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002587
2588 // Connect the dots between the top-down-collected RetainsToMove and
2589 // bottom-up-collected ReleasesToMove to form sets of related calls.
2590 // This is an iterative process so that we connect multiple releases
2591 // to multiple retains if needed.
2592 unsigned OldDelta = 0;
2593 unsigned NewDelta = 0;
2594 unsigned OldCount = 0;
2595 unsigned NewCount = 0;
2596 bool FirstRelease = true;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002597 for (;;) {
2598 for (SmallVectorImpl<Instruction *>::const_iterator
2599 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
2600 Instruction *NewRetain = *NI;
2601 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
2602 assert(It != Retains.end());
2603 const RRInfo &NewRetainRRI = It->second;
2604 KnownSafeTD &= NewRetainRRI.KnownSafe;
Michael Gottesman5a91bbf2013-05-24 20:44:02 +00002605 MultipleOwners =
2606 MultipleOwners || MultiOwnersSet.count(GetObjCArg(NewRetain));
Michael Gottesman9de6f962013-01-22 21:49:00 +00002607 for (SmallPtrSet<Instruction *, 2>::const_iterator
2608 LI = NewRetainRRI.Calls.begin(),
2609 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
2610 Instruction *NewRetainRelease = *LI;
2611 DenseMap<Value *, RRInfo>::const_iterator Jt =
2612 Releases.find(NewRetainRelease);
2613 if (Jt == Releases.end())
2614 return false;
2615 const RRInfo &NewRetainReleaseRRI = Jt->second;
2616 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
2617 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002618
2619 // If we overflow when we compute the path count, don't remove/move
2620 // anything.
2621 const BBState &NRRBBState = BBStates[NewRetainRelease->getParent()];
2622 unsigned PathCount;
2623 if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
2624 return false;
2625 OldDelta -= PathCount;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002626
2627 // Merge the ReleaseMetadata and IsTailCallRelease values.
2628 if (FirstRelease) {
2629 ReleasesToMove.ReleaseMetadata =
2630 NewRetainReleaseRRI.ReleaseMetadata;
2631 ReleasesToMove.IsTailCallRelease =
2632 NewRetainReleaseRRI.IsTailCallRelease;
2633 FirstRelease = false;
2634 } else {
2635 if (ReleasesToMove.ReleaseMetadata !=
2636 NewRetainReleaseRRI.ReleaseMetadata)
2637 ReleasesToMove.ReleaseMetadata = 0;
2638 if (ReleasesToMove.IsTailCallRelease !=
2639 NewRetainReleaseRRI.IsTailCallRelease)
2640 ReleasesToMove.IsTailCallRelease = false;
2641 }
2642
2643 // Collect the optimal insertion points.
2644 if (!KnownSafe)
2645 for (SmallPtrSet<Instruction *, 2>::const_iterator
2646 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
2647 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
2648 RI != RE; ++RI) {
2649 Instruction *RIP = *RI;
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002650 if (ReleasesToMove.ReverseInsertPts.insert(RIP)) {
2651 // If we overflow when we compute the path count, don't
2652 // remove/move anything.
2653 const BBState &RIPBBState = BBStates[RIP->getParent()];
2654 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
2655 return false;
2656 NewDelta -= PathCount;
2657 }
Michael Gottesman9de6f962013-01-22 21:49:00 +00002658 }
2659 NewReleases.push_back(NewRetainRelease);
2660 }
2661 }
2662 }
2663 NewRetains.clear();
2664 if (NewReleases.empty()) break;
2665
2666 // Back the other way.
2667 for (SmallVectorImpl<Instruction *>::const_iterator
2668 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
2669 Instruction *NewRelease = *NI;
2670 DenseMap<Value *, RRInfo>::const_iterator It =
2671 Releases.find(NewRelease);
2672 assert(It != Releases.end());
2673 const RRInfo &NewReleaseRRI = It->second;
2674 KnownSafeBU &= NewReleaseRRI.KnownSafe;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00002675 CFGHazardAfflicted |= NewReleaseRRI.CFGHazardAfflicted;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002676 for (SmallPtrSet<Instruction *, 2>::const_iterator
2677 LI = NewReleaseRRI.Calls.begin(),
2678 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
2679 Instruction *NewReleaseRetain = *LI;
2680 MapVector<Value *, RRInfo>::const_iterator Jt =
2681 Retains.find(NewReleaseRetain);
2682 if (Jt == Retains.end())
2683 return false;
2684 const RRInfo &NewReleaseRetainRRI = Jt->second;
2685 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
2686 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002687
2688 // If we overflow when we compute the path count, don't remove/move
2689 // anything.
2690 const BBState &NRRBBState = BBStates[NewReleaseRetain->getParent()];
2691 unsigned PathCount;
2692 if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
2693 return false;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002694 OldDelta += PathCount;
2695 OldCount += PathCount;
2696
Michael Gottesman9de6f962013-01-22 21:49:00 +00002697 // Collect the optimal insertion points.
2698 if (!KnownSafe)
2699 for (SmallPtrSet<Instruction *, 2>::const_iterator
2700 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
2701 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
2702 RI != RE; ++RI) {
2703 Instruction *RIP = *RI;
2704 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002705 // If we overflow when we compute the path count, don't
2706 // remove/move anything.
2707 const BBState &RIPBBState = BBStates[RIP->getParent()];
2708 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
2709 return false;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002710 NewDelta += PathCount;
2711 NewCount += PathCount;
2712 }
2713 }
2714 NewRetains.push_back(NewReleaseRetain);
2715 }
2716 }
2717 }
2718 NewReleases.clear();
2719 if (NewRetains.empty()) break;
2720 }
2721
Michael Gottesmana76143ee2013-05-13 23:49:42 +00002722 // If the pointer is known incremented in 1 direction and we do not have
2723 // MultipleOwners, we can safely remove the retain/releases. Otherwise we need
2724 // to be known safe in both directions.
2725 bool UnconditionallySafe = (KnownSafeTD && KnownSafeBU) ||
2726 ((KnownSafeTD || KnownSafeBU) && !MultipleOwners);
2727 if (UnconditionallySafe) {
Michael Gottesman9de6f962013-01-22 21:49:00 +00002728 RetainsToMove.ReverseInsertPts.clear();
2729 ReleasesToMove.ReverseInsertPts.clear();
2730 NewCount = 0;
2731 } else {
2732 // Determine whether the new insertion points we computed preserve the
2733 // balance of retain and release calls through the program.
2734 // TODO: If the fully aggressive solution isn't valid, try to find a
2735 // less aggressive solution which is.
2736 if (NewDelta != 0)
2737 return false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00002738
2739 // At this point, we are not going to remove any RR pairs, but we still are
2740 // able to move RR pairs. If one of our pointers is afflicted with
2741 // CFGHazards, we cannot perform such code motion so exit early.
2742 const bool WillPerformCodeMotion = RetainsToMove.ReverseInsertPts.size() ||
2743 ReleasesToMove.ReverseInsertPts.size();
2744 if (CFGHazardAfflicted && WillPerformCodeMotion)
2745 return false;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002746 }
2747
2748 // Determine whether the original call points are balanced in the retain and
2749 // release calls through the program. If not, conservatively don't touch
2750 // them.
2751 // TODO: It's theoretically possible to do code motion in this case, as
2752 // long as the existing imbalances are maintained.
2753 if (OldDelta != 0)
2754 return false;
Michael Gottesman8005ad32013-04-29 06:16:55 +00002755
Michael Gottesmana87bb8f2013-04-29 05:13:13 +00002756#ifdef ARC_ANNOTATIONS
2757 // Do not move calls if ARC annotations are requested.
Michael Gottesman3e3977c2013-04-29 05:25:39 +00002758 if (EnableARCAnnotations)
2759 return false;
Michael Gottesmana87bb8f2013-04-29 05:13:13 +00002760#endif // ARC_ANNOTATIONS
Michael Gottesman9de6f962013-01-22 21:49:00 +00002761
2762 Changed = true;
2763 assert(OldCount != 0 && "Unreachable code?");
2764 NumRRs += OldCount - NewCount;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002765 // Set to true if we completely removed any RR pairs.
Michael Gottesman8b5515f2013-01-22 21:53:43 +00002766 AnyPairsCompletelyEliminated = NewCount == 0;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002767
2768 // We can move calls!
2769 return true;
2770}
2771
Michael Gottesman97e3df02013-01-14 00:35:14 +00002772/// Identify pairings between the retains and releases, and delete and/or move
2773/// them.
John McCalld935e9c2011-06-15 23:37:01 +00002774bool
2775ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
2776 &BBStates,
2777 MapVector<Value *, RRInfo> &Retains,
Dan Gohman6320f522011-07-22 22:29:21 +00002778 DenseMap<Value *, RRInfo> &Releases,
2779 Module *M) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002780 DEBUG(dbgs() << "\n== ObjCARCOpt::PerformCodePlacement ==\n");
2781
John McCalld935e9c2011-06-15 23:37:01 +00002782 bool AnyPairsCompletelyEliminated = false;
2783 RRInfo RetainsToMove;
2784 RRInfo ReleasesToMove;
2785 SmallVector<Instruction *, 4> NewRetains;
2786 SmallVector<Instruction *, 4> NewReleases;
2787 SmallVector<Instruction *, 8> DeadInsts;
2788
Dan Gohman670f9372012-04-13 18:57:48 +00002789 // Visit each retain.
John McCalld935e9c2011-06-15 23:37:01 +00002790 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
Dan Gohman2053a5d2011-09-29 22:25:23 +00002791 E = Retains.end(); I != E; ++I) {
2792 Value *V = I->first;
John McCalld935e9c2011-06-15 23:37:01 +00002793 if (!V) continue; // blotted
2794
2795 Instruction *Retain = cast<Instruction>(V);
Michael Gottesmanc189a392013-01-09 19:23:24 +00002796
Michael Gottesman89279f82013-04-05 18:10:41 +00002797 DEBUG(dbgs() << "Visiting: " << *Retain << "\n");
Michael Gottesmanc189a392013-01-09 19:23:24 +00002798
John McCalld935e9c2011-06-15 23:37:01 +00002799 Value *Arg = GetObjCArg(Retain);
2800
Dan Gohman728db492012-01-13 00:39:07 +00002801 // If the object being released is in static or stack storage, we know it's
John McCalld935e9c2011-06-15 23:37:01 +00002802 // not being managed by ObjC reference counting, so we can delete pairs
2803 // regardless of what possible decrements or uses lie between them.
Dan Gohman728db492012-01-13 00:39:07 +00002804 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
Dan Gohman41375a32012-05-08 23:39:44 +00002805
Dan Gohman56e1cef2011-08-22 17:29:11 +00002806 // A constant pointer can't be pointing to an object on the heap. It may
2807 // be reference-counted, but it won't be deleted.
2808 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
2809 if (const GlobalVariable *GV =
2810 dyn_cast<GlobalVariable>(
2811 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
2812 if (GV->isConstant())
2813 KnownSafe = true;
2814
John McCalld935e9c2011-06-15 23:37:01 +00002815 // Connect the dots between the top-down-collected RetainsToMove and
2816 // bottom-up-collected ReleasesToMove to form sets of related calls.
John McCalld935e9c2011-06-15 23:37:01 +00002817 NewRetains.push_back(Retain);
Michael Gottesman9de6f962013-01-22 21:49:00 +00002818 bool PerformMoveCalls =
2819 ConnectTDBUTraversals(BBStates, Retains, Releases, M, NewRetains,
2820 NewReleases, DeadInsts, RetainsToMove,
2821 ReleasesToMove, Arg, KnownSafe,
2822 AnyPairsCompletelyEliminated);
John McCalld935e9c2011-06-15 23:37:01 +00002823
Michael Gottesman9de6f962013-01-22 21:49:00 +00002824 if (PerformMoveCalls) {
2825 // Ok, everything checks out and we're all set. Let's move/delete some
2826 // code!
2827 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
2828 Retains, Releases, DeadInsts, M);
John McCalld935e9c2011-06-15 23:37:01 +00002829 }
2830
Michael Gottesman9de6f962013-01-22 21:49:00 +00002831 // Clean up state for next retain.
John McCalld935e9c2011-06-15 23:37:01 +00002832 NewReleases.clear();
2833 NewRetains.clear();
2834 RetainsToMove.clear();
2835 ReleasesToMove.clear();
2836 }
2837
2838 // Now that we're done moving everything, we can delete the newly dead
2839 // instructions, as we no longer need them as insert points.
2840 while (!DeadInsts.empty())
2841 EraseInstruction(DeadInsts.pop_back_val());
2842
2843 return AnyPairsCompletelyEliminated;
2844}
2845
Michael Gottesman97e3df02013-01-14 00:35:14 +00002846/// Weak pointer optimizations.
John McCalld935e9c2011-06-15 23:37:01 +00002847void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002848 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeWeakCalls ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00002849
John McCalld935e9c2011-06-15 23:37:01 +00002850 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
2851 // itself because it uses AliasAnalysis and we need to do provenance
2852 // queries instead.
2853 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2854 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +00002855
Michael Gottesman89279f82013-04-05 18:10:41 +00002856 DEBUG(dbgs() << "Visiting: " << *Inst << "\n");
Michael Gottesman3f146e22013-01-01 16:05:48 +00002857
John McCalld935e9c2011-06-15 23:37:01 +00002858 InstructionClass Class = GetBasicInstructionClass(Inst);
2859 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
2860 continue;
2861
2862 // Delete objc_loadWeak calls with no users.
2863 if (Class == IC_LoadWeak && Inst->use_empty()) {
2864 Inst->eraseFromParent();
2865 continue;
2866 }
2867
2868 // TODO: For now, just look for an earlier available version of this value
2869 // within the same block. Theoretically, we could do memdep-style non-local
2870 // analysis too, but that would want caching. A better approach would be to
2871 // use the technique that EarlyCSE uses.
2872 inst_iterator Current = llvm::prior(I);
2873 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
2874 for (BasicBlock::iterator B = CurrentBB->begin(),
2875 J = Current.getInstructionIterator();
2876 J != B; --J) {
2877 Instruction *EarlierInst = &*llvm::prior(J);
2878 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
2879 switch (EarlierClass) {
2880 case IC_LoadWeak:
2881 case IC_LoadWeakRetained: {
2882 // If this is loading from the same pointer, replace this load's value
2883 // with that one.
2884 CallInst *Call = cast<CallInst>(Inst);
2885 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2886 Value *Arg = Call->getArgOperand(0);
2887 Value *EarlierArg = EarlierCall->getArgOperand(0);
2888 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2889 case AliasAnalysis::MustAlias:
2890 Changed = true;
2891 // If the load has a builtin retain, insert a plain retain for it.
2892 if (Class == IC_LoadWeakRetained) {
2893 CallInst *CI =
2894 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
2895 "", Call);
2896 CI->setTailCall();
2897 }
2898 // Zap the fully redundant load.
2899 Call->replaceAllUsesWith(EarlierCall);
2900 Call->eraseFromParent();
2901 goto clobbered;
2902 case AliasAnalysis::MayAlias:
2903 case AliasAnalysis::PartialAlias:
2904 goto clobbered;
2905 case AliasAnalysis::NoAlias:
2906 break;
2907 }
2908 break;
2909 }
2910 case IC_StoreWeak:
2911 case IC_InitWeak: {
2912 // If this is storing to the same pointer and has the same size etc.
2913 // replace this load's value with the stored value.
2914 CallInst *Call = cast<CallInst>(Inst);
2915 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2916 Value *Arg = Call->getArgOperand(0);
2917 Value *EarlierArg = EarlierCall->getArgOperand(0);
2918 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2919 case AliasAnalysis::MustAlias:
2920 Changed = true;
2921 // If the load has a builtin retain, insert a plain retain for it.
2922 if (Class == IC_LoadWeakRetained) {
2923 CallInst *CI =
2924 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
2925 "", Call);
2926 CI->setTailCall();
2927 }
2928 // Zap the fully redundant load.
2929 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
2930 Call->eraseFromParent();
2931 goto clobbered;
2932 case AliasAnalysis::MayAlias:
2933 case AliasAnalysis::PartialAlias:
2934 goto clobbered;
2935 case AliasAnalysis::NoAlias:
2936 break;
2937 }
2938 break;
2939 }
2940 case IC_MoveWeak:
2941 case IC_CopyWeak:
2942 // TOOD: Grab the copied value.
2943 goto clobbered;
2944 case IC_AutoreleasepoolPush:
2945 case IC_None:
John McCall20182ac2013-03-22 21:38:36 +00002946 case IC_IntrinsicUser:
John McCalld935e9c2011-06-15 23:37:01 +00002947 case IC_User:
2948 // Weak pointers are only modified through the weak entry points
2949 // (and arbitrary calls, which could call the weak entry points).
2950 break;
2951 default:
2952 // Anything else could modify the weak pointer.
2953 goto clobbered;
2954 }
2955 }
2956 clobbered:;
2957 }
2958
2959 // Then, for each destroyWeak with an alloca operand, check to see if
2960 // the alloca and all its users can be zapped.
2961 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2962 Instruction *Inst = &*I++;
2963 InstructionClass Class = GetBasicInstructionClass(Inst);
2964 if (Class != IC_DestroyWeak)
2965 continue;
2966
2967 CallInst *Call = cast<CallInst>(Inst);
2968 Value *Arg = Call->getArgOperand(0);
2969 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
2970 for (Value::use_iterator UI = Alloca->use_begin(),
2971 UE = Alloca->use_end(); UI != UE; ++UI) {
Dan Gohmandae33492012-04-27 18:56:31 +00002972 const Instruction *UserInst = cast<Instruction>(*UI);
John McCalld935e9c2011-06-15 23:37:01 +00002973 switch (GetBasicInstructionClass(UserInst)) {
2974 case IC_InitWeak:
2975 case IC_StoreWeak:
2976 case IC_DestroyWeak:
2977 continue;
2978 default:
2979 goto done;
2980 }
2981 }
2982 Changed = true;
2983 for (Value::use_iterator UI = Alloca->use_begin(),
2984 UE = Alloca->use_end(); UI != UE; ) {
2985 CallInst *UserInst = cast<CallInst>(*UI++);
Dan Gohman14862c32012-05-18 22:17:29 +00002986 switch (GetBasicInstructionClass(UserInst)) {
2987 case IC_InitWeak:
2988 case IC_StoreWeak:
2989 // These functions return their second argument.
2990 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
2991 break;
2992 case IC_DestroyWeak:
2993 // No return value.
2994 break;
2995 default:
Dan Gohman9c97eea02012-05-21 17:41:28 +00002996 llvm_unreachable("alloca really is used!");
Dan Gohman14862c32012-05-18 22:17:29 +00002997 }
John McCalld935e9c2011-06-15 23:37:01 +00002998 UserInst->eraseFromParent();
2999 }
3000 Alloca->eraseFromParent();
3001 done:;
3002 }
3003 }
3004}
3005
Michael Gottesman97e3df02013-01-14 00:35:14 +00003006/// Identify program paths which execute sequences of retains and releases which
3007/// can be eliminated.
John McCalld935e9c2011-06-15 23:37:01 +00003008bool ObjCARCOpt::OptimizeSequences(Function &F) {
Michael Gottesman740db972013-05-23 02:35:21 +00003009 // Releases, Retains - These are used to store the results of the main flow
3010 // analysis. These use Value* as the key instead of Instruction* so that the
3011 // map stays valid when we get around to rewriting code and calls get
3012 // replaced by arguments.
John McCalld935e9c2011-06-15 23:37:01 +00003013 DenseMap<Value *, RRInfo> Releases;
3014 MapVector<Value *, RRInfo> Retains;
3015
Michael Gottesman740db972013-05-23 02:35:21 +00003016 // This is used during the traversal of the function to track the
3017 // states for each identified object at each block.
John McCalld935e9c2011-06-15 23:37:01 +00003018 DenseMap<const BasicBlock *, BBState> BBStates;
3019
3020 // Analyze the CFG of the function, and all instructions.
3021 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
3022
3023 // Transform.
Michael Gottesman5a91bbf2013-05-24 20:44:02 +00003024 bool AnyPairsCompletelyEliminated = PerformCodePlacement(BBStates, Retains,
3025 Releases,
3026 F.getParent());
3027
3028 // Cleanup.
3029 MultiOwnersSet.clear();
3030
3031 return AnyPairsCompletelyEliminated && NestingDetected;
John McCalld935e9c2011-06-15 23:37:01 +00003032}
3033
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00003034/// Check if there is a dependent call earlier that does not have anything in
3035/// between the Retain and the call that can affect the reference count of their
3036/// shared pointer argument. Note that Retain need not be in BB.
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00003037static bool
3038HasSafePathToPredecessorCall(const Value *Arg, Instruction *Retain,
3039 SmallPtrSet<Instruction *, 4> &DepInsts,
3040 SmallPtrSet<const BasicBlock *, 4> &Visited,
3041 ProvenanceAnalysis &PA) {
3042 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
3043 DepInsts, Visited, PA);
3044 if (DepInsts.size() != 1)
3045 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00003046
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00003047 CallInst *Call =
3048 dyn_cast_or_null<CallInst>(*DepInsts.begin());
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00003049
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00003050 // Check that the pointer is the return value of the call.
3051 if (!Call || Arg != Call)
3052 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00003053
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00003054 // Check that the call is a regular call.
3055 InstructionClass Class = GetBasicInstructionClass(Call);
3056 if (Class != IC_CallOrUser && Class != IC_Call)
3057 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00003058
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00003059 return true;
3060}
3061
Michael Gottesman6908db12013-04-03 23:16:05 +00003062/// Find a dependent retain that precedes the given autorelease for which there
3063/// is nothing in between the two instructions that can affect the ref count of
3064/// Arg.
3065static CallInst *
3066FindPredecessorRetainWithSafePath(const Value *Arg, BasicBlock *BB,
3067 Instruction *Autorelease,
3068 SmallPtrSet<Instruction *, 4> &DepInsts,
3069 SmallPtrSet<const BasicBlock *, 4> &Visited,
3070 ProvenanceAnalysis &PA) {
3071 FindDependencies(CanChangeRetainCount, Arg,
3072 BB, Autorelease, DepInsts, Visited, PA);
3073 if (DepInsts.size() != 1)
3074 return 0;
Michael Gottesman79249972013-04-05 23:46:45 +00003075
Michael Gottesman6908db12013-04-03 23:16:05 +00003076 CallInst *Retain =
3077 dyn_cast_or_null<CallInst>(*DepInsts.begin());
Michael Gottesman79249972013-04-05 23:46:45 +00003078
Michael Gottesman6908db12013-04-03 23:16:05 +00003079 // Check that we found a retain with the same argument.
3080 if (!Retain ||
3081 !IsRetain(GetBasicInstructionClass(Retain)) ||
3082 GetObjCArg(Retain) != Arg) {
3083 return 0;
3084 }
Michael Gottesman79249972013-04-05 23:46:45 +00003085
Michael Gottesman6908db12013-04-03 23:16:05 +00003086 return Retain;
3087}
3088
Michael Gottesman21a4ed32013-04-03 23:39:14 +00003089/// Look for an ``autorelease'' instruction dependent on Arg such that there are
3090/// no instructions dependent on Arg that need a positive ref count in between
3091/// the autorelease and the ret.
3092static CallInst *
3093FindPredecessorAutoreleaseWithSafePath(const Value *Arg, BasicBlock *BB,
3094 ReturnInst *Ret,
3095 SmallPtrSet<Instruction *, 4> &DepInsts,
3096 SmallPtrSet<const BasicBlock *, 4> &V,
3097 ProvenanceAnalysis &PA) {
3098 FindDependencies(NeedsPositiveRetainCount, Arg,
3099 BB, Ret, DepInsts, V, PA);
3100 if (DepInsts.size() != 1)
3101 return 0;
Michael Gottesman79249972013-04-05 23:46:45 +00003102
Michael Gottesman21a4ed32013-04-03 23:39:14 +00003103 CallInst *Autorelease =
3104 dyn_cast_or_null<CallInst>(*DepInsts.begin());
3105 if (!Autorelease)
3106 return 0;
3107 InstructionClass AutoreleaseClass = GetBasicInstructionClass(Autorelease);
3108 if (!IsAutorelease(AutoreleaseClass))
3109 return 0;
3110 if (GetObjCArg(Autorelease) != Arg)
3111 return 0;
Michael Gottesman79249972013-04-05 23:46:45 +00003112
Michael Gottesman21a4ed32013-04-03 23:39:14 +00003113 return Autorelease;
3114}
3115
Michael Gottesman97e3df02013-01-14 00:35:14 +00003116/// Look for this pattern:
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00003117/// \code
John McCalld935e9c2011-06-15 23:37:01 +00003118/// %call = call i8* @something(...)
3119/// %2 = call i8* @objc_retain(i8* %call)
3120/// %3 = call i8* @objc_autorelease(i8* %2)
3121/// ret i8* %3
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00003122/// \endcode
John McCalld935e9c2011-06-15 23:37:01 +00003123/// And delete the retain and autorelease.
John McCalld935e9c2011-06-15 23:37:01 +00003124void ObjCARCOpt::OptimizeReturns(Function &F) {
3125 if (!F.getReturnType()->isPointerTy())
3126 return;
Michael Gottesman79249972013-04-05 23:46:45 +00003127
Michael Gottesman89279f82013-04-05 18:10:41 +00003128 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeReturns ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00003129
John McCalld935e9c2011-06-15 23:37:01 +00003130 SmallPtrSet<Instruction *, 4> DependingInstructions;
3131 SmallPtrSet<const BasicBlock *, 4> Visited;
3132 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3133 BasicBlock *BB = FI;
3134 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
Michael Gottesman3f146e22013-01-01 16:05:48 +00003135
Michael Gottesman89279f82013-04-05 18:10:41 +00003136 DEBUG(dbgs() << "Visiting: " << *Ret << "\n");
Michael Gottesman3f146e22013-01-01 16:05:48 +00003137
Michael Gottesman21a4ed32013-04-03 23:39:14 +00003138 if (!Ret)
3139 continue;
Michael Gottesman79249972013-04-05 23:46:45 +00003140
John McCalld935e9c2011-06-15 23:37:01 +00003141 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
Michael Gottesman79249972013-04-05 23:46:45 +00003142
Michael Gottesmancdb7c152013-04-21 00:25:04 +00003143 // Look for an ``autorelease'' instruction that is a predecessor of Ret and
Michael Gottesman21a4ed32013-04-03 23:39:14 +00003144 // dependent on Arg such that there are no instructions dependent on Arg
3145 // that need a positive ref count in between the autorelease and Ret.
3146 CallInst *Autorelease =
3147 FindPredecessorAutoreleaseWithSafePath(Arg, BB, Ret,
3148 DependingInstructions, Visited,
3149 PA);
John McCalld935e9c2011-06-15 23:37:01 +00003150 DependingInstructions.clear();
3151 Visited.clear();
Michael Gottesmanfb9ece92013-04-21 00:25:01 +00003152
3153 if (!Autorelease)
3154 continue;
3155
3156 CallInst *Retain =
3157 FindPredecessorRetainWithSafePath(Arg, BB, Autorelease,
3158 DependingInstructions, Visited, PA);
3159 DependingInstructions.clear();
3160 Visited.clear();
3161
3162 if (!Retain)
3163 continue;
3164
3165 // Check that there is nothing that can affect the reference count
3166 // between the retain and the call. Note that Retain need not be in BB.
3167 bool HasSafePathToCall = HasSafePathToPredecessorCall(Arg, Retain,
3168 DependingInstructions,
3169 Visited, PA);
3170 DependingInstructions.clear();
3171 Visited.clear();
3172
3173 if (!HasSafePathToCall)
3174 continue;
3175
3176 // If so, we can zap the retain and autorelease.
3177 Changed = true;
3178 ++NumRets;
3179 DEBUG(dbgs() << "Erasing: " << *Retain << "\nErasing: "
3180 << *Autorelease << "\n");
3181 EraseInstruction(Retain);
3182 EraseInstruction(Autorelease);
John McCalld935e9c2011-06-15 23:37:01 +00003183 }
3184}
3185
Michael Gottesman9c118152013-04-29 06:16:57 +00003186#ifndef NDEBUG
3187void
3188ObjCARCOpt::GatherStatistics(Function &F, bool AfterOptimization) {
3189 llvm::Statistic &NumRetains =
3190 AfterOptimization? NumRetainsAfterOpt : NumRetainsBeforeOpt;
3191 llvm::Statistic &NumReleases =
3192 AfterOptimization? NumReleasesAfterOpt : NumReleasesBeforeOpt;
3193
3194 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3195 Instruction *Inst = &*I++;
3196 switch (GetBasicInstructionClass(Inst)) {
3197 default:
3198 break;
3199 case IC_Retain:
3200 ++NumRetains;
3201 break;
3202 case IC_Release:
3203 ++NumReleases;
3204 break;
3205 }
3206 }
3207}
3208#endif
3209
John McCalld935e9c2011-06-15 23:37:01 +00003210bool ObjCARCOpt::doInitialization(Module &M) {
3211 if (!EnableARCOpts)
3212 return false;
3213
Dan Gohman670f9372012-04-13 18:57:48 +00003214 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanceaac7c2011-06-20 23:20:43 +00003215 Run = ModuleHasARC(M);
3216 if (!Run)
3217 return false;
3218
John McCalld935e9c2011-06-15 23:37:01 +00003219 // Identify the imprecise release metadata kind.
3220 ImpreciseReleaseMDKind =
3221 M.getContext().getMDKindID("clang.imprecise_release");
Dan Gohmana7107f92011-10-17 22:53:25 +00003222 CopyOnEscapeMDKind =
3223 M.getContext().getMDKindID("clang.arc.copy_on_escape");
Dan Gohman0155f302012-02-17 18:59:53 +00003224 NoObjCARCExceptionsMDKind =
3225 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
Michael Gottesman81b1d432013-03-26 00:42:04 +00003226#ifdef ARC_ANNOTATIONS
3227 ARCAnnotationBottomUpMDKind =
3228 M.getContext().getMDKindID("llvm.arc.annotation.bottomup");
3229 ARCAnnotationTopDownMDKind =
3230 M.getContext().getMDKindID("llvm.arc.annotation.topdown");
3231 ARCAnnotationProvenanceSourceMDKind =
3232 M.getContext().getMDKindID("llvm.arc.annotation.provenancesource");
3233#endif // ARC_ANNOTATIONS
John McCalld935e9c2011-06-15 23:37:01 +00003234
John McCalld935e9c2011-06-15 23:37:01 +00003235 // Intuitively, objc_retain and others are nocapture, however in practice
3236 // they are not, because they return their argument value. And objc_release
Dan Gohmandae33492012-04-27 18:56:31 +00003237 // calls finalizers which can have arbitrary side effects.
John McCalld935e9c2011-06-15 23:37:01 +00003238
3239 // These are initialized lazily.
John McCalld935e9c2011-06-15 23:37:01 +00003240 AutoreleaseRVCallee = 0;
3241 ReleaseCallee = 0;
3242 RetainCallee = 0;
Dan Gohman6320f522011-07-22 22:29:21 +00003243 RetainBlockCallee = 0;
John McCalld935e9c2011-06-15 23:37:01 +00003244 AutoreleaseCallee = 0;
3245
3246 return false;
3247}
3248
3249bool ObjCARCOpt::runOnFunction(Function &F) {
3250 if (!EnableARCOpts)
3251 return false;
3252
Dan Gohmanceaac7c2011-06-20 23:20:43 +00003253 // If nothing in the Module uses ARC, don't do anything.
3254 if (!Run)
3255 return false;
3256
John McCalld935e9c2011-06-15 23:37:01 +00003257 Changed = false;
3258
Michael Gottesman89279f82013-04-05 18:10:41 +00003259 DEBUG(dbgs() << "<<< ObjCARCOpt: Visiting Function: " << F.getName() << " >>>"
3260 "\n");
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00003261
John McCalld935e9c2011-06-15 23:37:01 +00003262 PA.setAA(&getAnalysis<AliasAnalysis>());
3263
Michael Gottesman9fc50b82013-05-13 18:29:07 +00003264#ifndef NDEBUG
3265 if (AreStatisticsEnabled()) {
3266 GatherStatistics(F, false);
3267 }
3268#endif
3269
John McCalld935e9c2011-06-15 23:37:01 +00003270 // This pass performs several distinct transformations. As a compile-time aid
3271 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3272 // library functions aren't declared.
3273
Michael Gottesmancd5b0272013-04-24 22:18:15 +00003274 // Preliminary optimizations. This also computes UsedInThisFunction.
John McCalld935e9c2011-06-15 23:37:01 +00003275 OptimizeIndividualCalls(F);
3276
3277 // Optimizations for weak pointers.
3278 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3279 (1 << IC_LoadWeakRetained) |
3280 (1 << IC_StoreWeak) |
3281 (1 << IC_InitWeak) |
3282 (1 << IC_CopyWeak) |
3283 (1 << IC_MoveWeak) |
3284 (1 << IC_DestroyWeak)))
3285 OptimizeWeakCalls(F);
3286
3287 // Optimizations for retain+release pairs.
3288 if (UsedInThisFunction & ((1 << IC_Retain) |
3289 (1 << IC_RetainRV) |
3290 (1 << IC_RetainBlock)))
3291 if (UsedInThisFunction & (1 << IC_Release))
3292 // Run OptimizeSequences until it either stops making changes or
3293 // no retain+release pair nesting is detected.
3294 while (OptimizeSequences(F)) {}
3295
3296 // Optimizations if objc_autorelease is used.
Dan Gohman41375a32012-05-08 23:39:44 +00003297 if (UsedInThisFunction & ((1 << IC_Autorelease) |
3298 (1 << IC_AutoreleaseRV)))
John McCalld935e9c2011-06-15 23:37:01 +00003299 OptimizeReturns(F);
3300
Michael Gottesman9c118152013-04-29 06:16:57 +00003301 // Gather statistics after optimization.
3302#ifndef NDEBUG
3303 if (AreStatisticsEnabled()) {
3304 GatherStatistics(F, true);
3305 }
3306#endif
3307
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00003308 DEBUG(dbgs() << "\n");
3309
John McCalld935e9c2011-06-15 23:37:01 +00003310 return Changed;
3311}
3312
3313void ObjCARCOpt::releaseMemory() {
3314 PA.clear();
3315}
3316
Michael Gottesman97e3df02013-01-14 00:35:14 +00003317/// @}
3318///