blob: 48fe7c1440395f3fd4dec3c27b062f104a82c9ec [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
Michael Gottesman97e3df02013-01-14 00:35:14 +0000521 /// Unidirectional information about the current sequence.
John McCalld935e9c2011-06-15 23:37:01 +0000522 RRInfo RRI;
523
Michael Gottesmane3943d02013-06-21 19:44:30 +0000524 public:
Dan Gohmandf476e52012-09-04 23:16:20 +0000525 PtrState() : KnownPositiveRefCount(false), Partial(false),
Dan Gohman41375a32012-05-08 23:39:44 +0000526 Seq(S_None) {}
John McCalld935e9c2011-06-15 23:37:01 +0000527
Michael Gottesman93132252013-06-21 06:59:02 +0000528
529 bool IsKnownSafe() const {
530 return RRI.KnownSafe;
531 }
532
533 void SetKnownSafe(const bool NewValue) {
534 RRI.KnownSafe = NewValue;
535 }
536
Michael Gottesmanb82a1792013-06-21 07:00:44 +0000537 bool IsTailCallRelease() const {
538 return RRI.IsTailCallRelease;
539 }
540
541 void SetTailCallRelease(const bool NewValue) {
542 RRI.IsTailCallRelease = NewValue;
543 }
544
Michael Gottesman9799cf72013-06-21 20:52:49 +0000545 bool IsTrackingImpreciseReleases() const {
Michael Gottesmanf0401182013-06-21 19:12:38 +0000546 return RRI.ReleaseMetadata != 0;
547 }
548
Michael Gottesmanf701d3f2013-06-21 07:03:07 +0000549 const MDNode *GetReleaseMetadata() const {
550 return RRI.ReleaseMetadata;
551 }
552
553 void SetReleaseMetadata(MDNode *NewValue) {
554 RRI.ReleaseMetadata = NewValue;
555 }
556
Michael Gottesman2f294592013-06-21 19:12:36 +0000557 bool IsCFGHazardAfflicted() const {
558 return RRI.CFGHazardAfflicted;
559 }
560
561 void SetCFGHazardAfflicted(const bool NewValue) {
562 RRI.CFGHazardAfflicted = NewValue;
563 }
564
Michael Gottesman415ddd72013-02-05 19:32:18 +0000565 void SetKnownPositiveRefCount() {
Michael Gottesmanf3f9e3b2013-05-14 00:08:09 +0000566 DEBUG(dbgs() << "Setting Known Positive.\n");
Dan Gohman62079b42012-04-25 00:50:46 +0000567 KnownPositiveRefCount = true;
Dan Gohman12130272011-08-12 00:26:31 +0000568 }
569
Michael Gottesman764b1cf2013-03-23 05:46:19 +0000570 void ClearKnownPositiveRefCount() {
Michael Gottesmanf3f9e3b2013-05-14 00:08:09 +0000571 DEBUG(dbgs() << "Clearing Known Positive.\n");
Dan Gohman62079b42012-04-25 00:50:46 +0000572 KnownPositiveRefCount = false;
John McCalld935e9c2011-06-15 23:37:01 +0000573 }
574
Michael Gottesman07beea42013-03-23 05:31:01 +0000575 bool HasKnownPositiveRefCount() const {
Dan Gohman62079b42012-04-25 00:50:46 +0000576 return KnownPositiveRefCount;
John McCalld935e9c2011-06-15 23:37:01 +0000577 }
578
Michael Gottesman415ddd72013-02-05 19:32:18 +0000579 void SetSeq(Sequence NewSeq) {
Michael Gottesman89279f82013-04-05 18:10:41 +0000580 DEBUG(dbgs() << "Old: " << Seq << "; New: " << NewSeq << "\n");
Michael Gottesman79249972013-04-05 23:46:45 +0000581 Seq = NewSeq;
John McCalld935e9c2011-06-15 23:37:01 +0000582 }
583
Michael Gottesman415ddd72013-02-05 19:32:18 +0000584 Sequence GetSeq() const {
John McCalld935e9c2011-06-15 23:37:01 +0000585 return Seq;
586 }
587
Michael Gottesman415ddd72013-02-05 19:32:18 +0000588 void ClearSequenceProgress() {
Dan Gohman62079b42012-04-25 00:50:46 +0000589 ResetSequenceProgress(S_None);
590 }
591
Michael Gottesman415ddd72013-02-05 19:32:18 +0000592 void ResetSequenceProgress(Sequence NewSeq) {
Michael Gottesman01338a42013-04-20 23:36:57 +0000593 DEBUG(dbgs() << "Resetting sequence progress.\n");
Michael Gottesman89279f82013-04-05 18:10:41 +0000594 SetSeq(NewSeq);
Dan Gohman62079b42012-04-25 00:50:46 +0000595 Partial = false;
John McCalld935e9c2011-06-15 23:37:01 +0000596 RRI.clear();
597 }
598
599 void Merge(const PtrState &Other, bool TopDown);
Michael Gottesman4f6ef112013-06-21 19:44:27 +0000600
601 void InsertCall(Instruction *I) {
602 RRI.Calls.insert(I);
603 }
604
605 void InsertReverseInsertPt(Instruction *I) {
606 RRI.ReverseInsertPts.insert(I);
607 }
608
609 void ClearReverseInsertPts() {
610 RRI.ReverseInsertPts.clear();
611 }
612
613 bool HasReverseInsertPts() const {
614 return !RRI.ReverseInsertPts.empty();
615 }
Michael Gottesmane3943d02013-06-21 19:44:30 +0000616
617 const RRInfo &GetRRInfo() const {
618 return RRI;
619 }
John McCalld935e9c2011-06-15 23:37:01 +0000620 };
621}
622
623void
624PtrState::Merge(const PtrState &Other, bool TopDown) {
625 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
Michael Gottesmanb7deb4c2013-06-21 06:54:31 +0000626 KnownPositiveRefCount &= Other.KnownPositiveRefCount;
Michael Gottesman60f6b282013-03-29 05:13:07 +0000627
Dan Gohman1736c142011-10-17 18:48:25 +0000628 // If we're not in a sequence (anymore), drop all associated state.
John McCalld935e9c2011-06-15 23:37:01 +0000629 if (Seq == S_None) {
Dan Gohman62079b42012-04-25 00:50:46 +0000630 Partial = false;
John McCalld935e9c2011-06-15 23:37:01 +0000631 RRI.clear();
Dan Gohman62079b42012-04-25 00:50:46 +0000632 } else if (Partial || Other.Partial) {
Dan Gohman1736c142011-10-17 18:48:25 +0000633 // If we're doing a merge on a path that's previously seen a partial
634 // merge, conservatively drop the sequence, to avoid doing partial
635 // RR elimination. If the branch predicates for the two merge differ,
636 // mixing them is unsafe.
Dan Gohman62079b42012-04-25 00:50:46 +0000637 ClearSequenceProgress();
John McCalld935e9c2011-06-15 23:37:01 +0000638 } else {
Michael Gottesmanb7deb4c2013-06-21 06:54:31 +0000639 // Otherwise merge the other PtrState's RRInfo into our RRInfo. At this
640 // point, we know that currently we are not partial. Stash whether or not
641 // the merge operation caused us to undergo a partial merging of reverse
642 // insertion points.
Michael Gottesman4773a102013-06-21 05:42:08 +0000643 Partial = RRI.Merge(Other.RRI);
John McCalld935e9c2011-06-15 23:37:01 +0000644 }
645}
646
647namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000648 /// \brief Per-BasicBlock state.
John McCalld935e9c2011-06-15 23:37:01 +0000649 class BBState {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000650 /// The number of unique control paths from the entry which can reach this
651 /// block.
John McCalld935e9c2011-06-15 23:37:01 +0000652 unsigned TopDownPathCount;
653
Michael Gottesman97e3df02013-01-14 00:35:14 +0000654 /// The number of unique control paths to exits from this block.
John McCalld935e9c2011-06-15 23:37:01 +0000655 unsigned BottomUpPathCount;
656
Michael Gottesman97e3df02013-01-14 00:35:14 +0000657 /// A type for PerPtrTopDown and PerPtrBottomUp.
John McCalld935e9c2011-06-15 23:37:01 +0000658 typedef MapVector<const Value *, PtrState> MapTy;
659
Michael Gottesman97e3df02013-01-14 00:35:14 +0000660 /// The top-down traversal uses this to record information known about a
661 /// pointer at the bottom of each block.
John McCalld935e9c2011-06-15 23:37:01 +0000662 MapTy PerPtrTopDown;
663
Michael Gottesman97e3df02013-01-14 00:35:14 +0000664 /// The bottom-up traversal uses this to record information known about a
665 /// pointer at the top of each block.
John McCalld935e9c2011-06-15 23:37:01 +0000666 MapTy PerPtrBottomUp;
667
Michael Gottesman97e3df02013-01-14 00:35:14 +0000668 /// Effective predecessors of the current block ignoring ignorable edges and
669 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000670 SmallVector<BasicBlock *, 2> Preds;
Michael Gottesman97e3df02013-01-14 00:35:14 +0000671 /// Effective successors of the current block ignoring ignorable edges and
672 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000673 SmallVector<BasicBlock *, 2> Succs;
674
John McCalld935e9c2011-06-15 23:37:01 +0000675 public:
676 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
677
678 typedef MapTy::iterator ptr_iterator;
679 typedef MapTy::const_iterator ptr_const_iterator;
680
681 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
682 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
683 ptr_const_iterator top_down_ptr_begin() const {
684 return PerPtrTopDown.begin();
685 }
686 ptr_const_iterator top_down_ptr_end() const {
687 return PerPtrTopDown.end();
688 }
689
690 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
691 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
692 ptr_const_iterator bottom_up_ptr_begin() const {
693 return PerPtrBottomUp.begin();
694 }
695 ptr_const_iterator bottom_up_ptr_end() const {
696 return PerPtrBottomUp.end();
697 }
698
Michael Gottesman97e3df02013-01-14 00:35:14 +0000699 /// Mark this block as being an entry block, which has one path from the
700 /// entry by definition.
John McCalld935e9c2011-06-15 23:37:01 +0000701 void SetAsEntry() { TopDownPathCount = 1; }
702
Michael Gottesman97e3df02013-01-14 00:35:14 +0000703 /// Mark this block as being an exit block, which has one path to an exit by
704 /// definition.
John McCalld935e9c2011-06-15 23:37:01 +0000705 void SetAsExit() { BottomUpPathCount = 1; }
706
Michael Gottesman993fbf72013-05-13 19:40:39 +0000707 /// Attempt to find the PtrState object describing the top down state for
708 /// pointer Arg. Return a new initialized PtrState describing the top down
709 /// state for Arg if we do not find one.
John McCalld935e9c2011-06-15 23:37:01 +0000710 PtrState &getPtrTopDownState(const Value *Arg) {
711 return PerPtrTopDown[Arg];
712 }
713
Michael Gottesman993fbf72013-05-13 19:40:39 +0000714 /// Attempt to find the PtrState object describing the bottom up state for
715 /// pointer Arg. Return a new initialized PtrState describing the bottom up
716 /// state for Arg if we do not find one.
John McCalld935e9c2011-06-15 23:37:01 +0000717 PtrState &getPtrBottomUpState(const Value *Arg) {
718 return PerPtrBottomUp[Arg];
719 }
720
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000721 /// Attempt to find the PtrState object describing the bottom up state for
722 /// pointer Arg.
723 ptr_iterator findPtrBottomUpState(const Value *Arg) {
724 return PerPtrBottomUp.find(Arg);
725 }
726
John McCalld935e9c2011-06-15 23:37:01 +0000727 void clearBottomUpPointers() {
Evan Chenge4df6a22011-08-04 18:40:26 +0000728 PerPtrBottomUp.clear();
John McCalld935e9c2011-06-15 23:37:01 +0000729 }
730
731 void clearTopDownPointers() {
732 PerPtrTopDown.clear();
733 }
734
735 void InitFromPred(const BBState &Other);
736 void InitFromSucc(const BBState &Other);
737 void MergePred(const BBState &Other);
738 void MergeSucc(const BBState &Other);
739
Michael Gottesman9e7261c2013-06-07 06:16:49 +0000740 /// Compute the number of possible unique paths from an entry to an exit
Michael Gottesman97e3df02013-01-14 00:35:14 +0000741 /// which pass through this block. This is only valid after both the
742 /// top-down and bottom-up traversals are complete.
Michael Gottesman9e7261c2013-06-07 06:16:49 +0000743 ///
744 /// Returns true if overflow occured. Returns false if overflow did not
745 /// occur.
746 bool GetAllPathCountWithOverflow(unsigned &PathCount) const {
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000747 assert(TopDownPathCount != 0);
748 assert(BottomUpPathCount != 0);
Michael Gottesman9e7261c2013-06-07 06:16:49 +0000749 unsigned long long Product =
750 (unsigned long long)TopDownPathCount*BottomUpPathCount;
751 PathCount = Product;
752 // Overflow occured if any of the upper bits of Product are set.
753 return Product >> 32;
John McCalld935e9c2011-06-15 23:37:01 +0000754 }
Dan Gohman12130272011-08-12 00:26:31 +0000755
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000756 // Specialized CFG utilities.
Dan Gohmandae33492012-04-27 18:56:31 +0000757 typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000758 edge_iterator pred_begin() { return Preds.begin(); }
759 edge_iterator pred_end() { return Preds.end(); }
760 edge_iterator succ_begin() { return Succs.begin(); }
761 edge_iterator succ_end() { return Succs.end(); }
762
763 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
764 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
765
766 bool isExit() const { return Succs.empty(); }
John McCalld935e9c2011-06-15 23:37:01 +0000767 };
768}
769
770void BBState::InitFromPred(const BBState &Other) {
771 PerPtrTopDown = Other.PerPtrTopDown;
772 TopDownPathCount = Other.TopDownPathCount;
773}
774
775void BBState::InitFromSucc(const BBState &Other) {
776 PerPtrBottomUp = Other.PerPtrBottomUp;
777 BottomUpPathCount = Other.BottomUpPathCount;
778}
779
Michael Gottesman97e3df02013-01-14 00:35:14 +0000780/// The top-down traversal uses this to merge information about predecessors to
781/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +0000782void BBState::MergePred(const BBState &Other) {
783 // Other.TopDownPathCount can be 0, in which case it is either dead or a
784 // loop backedge. Loop backedges are special.
785 TopDownPathCount += Other.TopDownPathCount;
786
Michael Gottesman4385edf2013-01-14 01:47:53 +0000787 // Check for overflow. If we have overflow, fall back to conservative
788 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +0000789 if (TopDownPathCount < Other.TopDownPathCount) {
790 clearTopDownPointers();
791 return;
792 }
793
John McCalld935e9c2011-06-15 23:37:01 +0000794 // For each entry in the other set, if our set has an entry with the same key,
795 // merge the entries. Otherwise, copy the entry and merge it with an empty
796 // entry.
797 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
798 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
799 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
800 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
801 /*TopDown=*/true);
802 }
803
Dan Gohman7e315fc32011-08-11 21:06:32 +0000804 // For each entry in our set, if the other set doesn't have an entry with the
John McCalld935e9c2011-06-15 23:37:01 +0000805 // same key, force it to merge with an empty entry.
806 for (ptr_iterator MI = top_down_ptr_begin(),
807 ME = top_down_ptr_end(); MI != ME; ++MI)
808 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
809 MI->second.Merge(PtrState(), /*TopDown=*/true);
810}
811
Michael Gottesman97e3df02013-01-14 00:35:14 +0000812/// The bottom-up traversal uses this to merge information about successors to
813/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +0000814void BBState::MergeSucc(const BBState &Other) {
815 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
816 // loop backedge. Loop backedges are special.
817 BottomUpPathCount += Other.BottomUpPathCount;
818
Michael Gottesman4385edf2013-01-14 01:47:53 +0000819 // Check for overflow. If we have overflow, fall back to conservative
820 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +0000821 if (BottomUpPathCount < Other.BottomUpPathCount) {
822 clearBottomUpPointers();
823 return;
824 }
825
John McCalld935e9c2011-06-15 23:37:01 +0000826 // For each entry in the other set, if our set has an entry with the
827 // same key, merge the entries. Otherwise, copy the entry and merge
828 // it with an empty entry.
829 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
830 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
831 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
832 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
833 /*TopDown=*/false);
834 }
835
Dan Gohman7e315fc32011-08-11 21:06:32 +0000836 // For each entry in our set, if the other set doesn't have an entry
John McCalld935e9c2011-06-15 23:37:01 +0000837 // with the same key, force it to merge with an empty entry.
838 for (ptr_iterator MI = bottom_up_ptr_begin(),
839 ME = bottom_up_ptr_end(); MI != ME; ++MI)
840 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
841 MI->second.Merge(PtrState(), /*TopDown=*/false);
842}
843
Michael Gottesman81b1d432013-03-26 00:42:04 +0000844// Only enable ARC Annotations if we are building a debug version of
845// libObjCARCOpts.
846#ifndef NDEBUG
847#define ARC_ANNOTATIONS
848#endif
849
850// Define some macros along the lines of DEBUG and some helper functions to make
851// it cleaner to create annotations in the source code and to no-op when not
852// building in debug mode.
853#ifdef ARC_ANNOTATIONS
854
855#include "llvm/Support/CommandLine.h"
856
857/// Enable/disable ARC sequence annotations.
858static cl::opt<bool>
Michael Gottesman6806b512013-04-17 20:48:03 +0000859EnableARCAnnotations("enable-objc-arc-annotations", cl::init(false),
860 cl::desc("Enable emission of arc data flow analysis "
861 "annotations"));
Michael Gottesmanffef24f2013-04-17 20:48:01 +0000862static cl::opt<bool>
Michael Gottesmanadb921a2013-04-17 21:03:53 +0000863DisableCheckForCFGHazards("disable-objc-arc-checkforcfghazards", cl::init(false),
864 cl::desc("Disable check for cfg hazards when "
865 "annotating"));
Michael Gottesman4e88ce62013-04-17 21:59:41 +0000866static cl::opt<std::string>
867ARCAnnotationTargetIdentifier("objc-arc-annotation-target-identifier",
868 cl::init(""),
869 cl::desc("filter out all data flow annotations "
870 "but those that apply to the given "
871 "target llvm identifier."));
Michael Gottesman81b1d432013-03-26 00:42:04 +0000872
873/// This function appends a unique ARCAnnotationProvenanceSourceMDKind id to an
874/// instruction so that we can track backwards when post processing via the llvm
875/// arc annotation processor tool. If the function is an
876static MDString *AppendMDNodeToSourcePtr(unsigned NodeId,
877 Value *Ptr) {
878 MDString *Hash = 0;
879
880 // If pointer is a result of an instruction and it does not have a source
881 // MDNode it, attach a new MDNode onto it. If pointer is a result of
882 // an instruction and does have a source MDNode attached to it, return a
883 // reference to said Node. Otherwise just return 0.
884 if (Instruction *Inst = dyn_cast<Instruction>(Ptr)) {
885 MDNode *Node;
886 if (!(Node = Inst->getMetadata(NodeId))) {
887 // We do not have any node. Generate and attatch the hash MDString to the
888 // instruction.
889
890 // We just use an MDString to ensure that this metadata gets written out
891 // of line at the module level and to provide a very simple format
892 // encoding the information herein. Both of these makes it simpler to
893 // parse the annotations by a simple external program.
894 std::string Str;
895 raw_string_ostream os(Str);
896 os << "(" << Inst->getParent()->getParent()->getName() << ",%"
897 << Inst->getName() << ")";
898
899 Hash = MDString::get(Inst->getContext(), os.str());
900 Inst->setMetadata(NodeId, MDNode::get(Inst->getContext(),Hash));
901 } else {
902 // We have a node. Grab its hash and return it.
903 assert(Node->getNumOperands() == 1 &&
904 "An ARCAnnotationProvenanceSourceMDKind can only have 1 operand.");
905 Hash = cast<MDString>(Node->getOperand(0));
906 }
907 } else if (Argument *Arg = dyn_cast<Argument>(Ptr)) {
908 std::string str;
909 raw_string_ostream os(str);
910 os << "(" << Arg->getParent()->getName() << ",%" << Arg->getName()
911 << ")";
912 Hash = MDString::get(Arg->getContext(), os.str());
913 }
914
915 return Hash;
916}
917
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000918static std::string SequenceToString(Sequence A) {
919 std::string str;
920 raw_string_ostream os(str);
921 os << A;
922 return os.str();
923}
924
Michael Gottesman81b1d432013-03-26 00:42:04 +0000925/// Helper function to change a Sequence into a String object using our overload
926/// for raw_ostream so we only have printing code in one location.
927static MDString *SequenceToMDString(LLVMContext &Context,
928 Sequence A) {
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000929 return MDString::get(Context, SequenceToString(A));
Michael Gottesman81b1d432013-03-26 00:42:04 +0000930}
931
932/// A simple function to generate a MDNode which describes the change in state
933/// for Value *Ptr caused by Instruction *Inst.
934static void AppendMDNodeToInstForPtr(unsigned NodeId,
935 Instruction *Inst,
936 Value *Ptr,
937 MDString *PtrSourceMDNodeID,
938 Sequence OldSeq,
939 Sequence NewSeq) {
940 MDNode *Node = 0;
941 Value *tmp[3] = {PtrSourceMDNodeID,
942 SequenceToMDString(Inst->getContext(),
943 OldSeq),
944 SequenceToMDString(Inst->getContext(),
945 NewSeq)};
946 Node = MDNode::get(Inst->getContext(),
947 ArrayRef<Value*>(tmp, 3));
948
949 Inst->setMetadata(NodeId, Node);
950}
951
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000952/// Add to the beginning of the basic block llvm.ptr.annotations which show the
953/// state of a pointer at the entrance to a basic block.
954static void GenerateARCBBEntranceAnnotation(const char *Name, BasicBlock *BB,
955 Value *Ptr, Sequence Seq) {
Michael Gottesman4e88ce62013-04-17 21:59:41 +0000956 // If we have a target identifier, make sure that we match it before
957 // continuing.
958 if(!ARCAnnotationTargetIdentifier.empty() &&
959 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
960 return;
Michael Gottesman9e518132013-04-18 04:34:11 +0000961
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000962 Module *M = BB->getParent()->getParent();
963 LLVMContext &C = M->getContext();
964 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
965 Type *I8XX = PointerType::getUnqual(I8X);
966 Type *Params[] = {I8XX, I8XX};
967 FunctionType *FTy = FunctionType::get(Type::getVoidTy(C),
968 ArrayRef<Type*>(Params, 2),
969 /*isVarArg=*/false);
970 Constant *Callee = M->getOrInsertFunction(Name, FTy);
Michael Gottesman60f6b282013-03-29 05:13:07 +0000971
972 IRBuilder<> Builder(BB, BB->getFirstInsertionPt());
973
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000974 Value *PtrName;
975 StringRef Tmp = Ptr->getName();
976 if (0 == (PtrName = M->getGlobalVariable(Tmp, true))) {
977 Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
978 Tmp + "_STR");
979 PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
Michael Gottesman60f6b282013-03-29 05:13:07 +0000980 cast<Constant>(ActualPtrName), Tmp);
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000981 }
982
983 Value *S;
984 std::string SeqStr = SequenceToString(Seq);
985 if (0 == (S = M->getGlobalVariable(SeqStr, true))) {
986 Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
987 SeqStr + "_STR");
988 S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
989 cast<Constant>(ActualPtrName), SeqStr);
990 }
991
992 Builder.CreateCall2(Callee, PtrName, S);
993}
994
995/// Add to the end of the basic block llvm.ptr.annotations which show the state
996/// of the pointer at the bottom of the basic block.
997static void GenerateARCBBTerminatorAnnotation(const char *Name, BasicBlock *BB,
998 Value *Ptr, Sequence Seq) {
Michael Gottesman4e88ce62013-04-17 21:59:41 +0000999 // If we have a target identifier, make sure that we match it before emitting
1000 // an annotation.
1001 if(!ARCAnnotationTargetIdentifier.empty() &&
1002 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
1003 return;
Michael Gottesman9e518132013-04-18 04:34:11 +00001004
Michael Gottesmancd4de0f2013-03-26 00:42:09 +00001005 Module *M = BB->getParent()->getParent();
1006 LLVMContext &C = M->getContext();
1007 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1008 Type *I8XX = PointerType::getUnqual(I8X);
1009 Type *Params[] = {I8XX, I8XX};
1010 FunctionType *FTy = FunctionType::get(Type::getVoidTy(C),
1011 ArrayRef<Type*>(Params, 2),
1012 /*isVarArg=*/false);
1013 Constant *Callee = M->getOrInsertFunction(Name, FTy);
Michael Gottesman60f6b282013-03-29 05:13:07 +00001014
1015 IRBuilder<> Builder(BB, llvm::prior(BB->end()));
1016
Michael Gottesmancd4de0f2013-03-26 00:42:09 +00001017 Value *PtrName;
1018 StringRef Tmp = Ptr->getName();
1019 if (0 == (PtrName = M->getGlobalVariable(Tmp, true))) {
1020 Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
1021 Tmp + "_STR");
1022 PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
Michael Gottesman60f6b282013-03-29 05:13:07 +00001023 cast<Constant>(ActualPtrName), Tmp);
Michael Gottesmancd4de0f2013-03-26 00:42:09 +00001024 }
1025
1026 Value *S;
1027 std::string SeqStr = SequenceToString(Seq);
1028 if (0 == (S = M->getGlobalVariable(SeqStr, true))) {
1029 Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
1030 SeqStr + "_STR");
1031 S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
1032 cast<Constant>(ActualPtrName), SeqStr);
1033 }
Michael Gottesman60f6b282013-03-29 05:13:07 +00001034 Builder.CreateCall2(Callee, PtrName, S);
Michael Gottesmancd4de0f2013-03-26 00:42:09 +00001035}
1036
Michael Gottesman81b1d432013-03-26 00:42:04 +00001037/// Adds a source annotation to pointer and a state change annotation to Inst
1038/// referencing the source annotation and the old/new state of pointer.
1039static void GenerateARCAnnotation(unsigned InstMDId,
1040 unsigned PtrMDId,
1041 Instruction *Inst,
1042 Value *Ptr,
1043 Sequence OldSeq,
1044 Sequence NewSeq) {
1045 if (EnableARCAnnotations) {
Michael Gottesman4e88ce62013-04-17 21:59:41 +00001046 // If we have a target identifier, make sure that we match it before
1047 // emitting an annotation.
1048 if(!ARCAnnotationTargetIdentifier.empty() &&
1049 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
1050 return;
Michael Gottesman9e518132013-04-18 04:34:11 +00001051
Michael Gottesman81b1d432013-03-26 00:42:04 +00001052 // First generate the source annotation on our pointer. This will return an
1053 // MDString* if Ptr actually comes from an instruction implying we can put
1054 // in a source annotation. If AppendMDNodeToSourcePtr returns 0 (i.e. NULL),
1055 // then we know that our pointer is from an Argument so we put a reference
1056 // to the argument number.
1057 //
1058 // The point of this is to make it easy for the
1059 // llvm-arc-annotation-processor tool to cross reference where the source
1060 // pointer is in the LLVM IR since the LLVM IR parser does not submit such
1061 // information via debug info for backends to use (since why would anyone
1062 // need such a thing from LLVM IR besides in non standard cases
1063 // [i.e. this]).
1064 MDString *SourcePtrMDNode =
1065 AppendMDNodeToSourcePtr(PtrMDId, Ptr);
1066 AppendMDNodeToInstForPtr(InstMDId, Inst, Ptr, SourcePtrMDNode, OldSeq,
1067 NewSeq);
1068 }
1069}
1070
1071// The actual interface for accessing the above functionality is defined via
1072// some simple macros which are defined below. We do this so that the user does
1073// not need to pass in what metadata id is needed resulting in cleaner code and
1074// additionally since it provides an easy way to conditionally no-op all
1075// annotation support in a non-debug build.
1076
1077/// Use this macro to annotate a sequence state change when processing
1078/// instructions bottom up,
1079#define ANNOTATE_BOTTOMUP(inst, ptr, old, new) \
1080 GenerateARCAnnotation(ARCAnnotationBottomUpMDKind, \
1081 ARCAnnotationProvenanceSourceMDKind, (inst), \
1082 const_cast<Value*>(ptr), (old), (new))
1083/// Use this macro to annotate a sequence state change when processing
1084/// instructions top down.
1085#define ANNOTATE_TOPDOWN(inst, ptr, old, new) \
1086 GenerateARCAnnotation(ARCAnnotationTopDownMDKind, \
1087 ARCAnnotationProvenanceSourceMDKind, (inst), \
1088 const_cast<Value*>(ptr), (old), (new))
1089
Michael Gottesman43e7e002013-04-03 22:41:59 +00001090#define ANNOTATE_BB(_states, _bb, _name, _type, _direction) \
1091 do { \
Michael Gottesman89279f82013-04-05 18:10:41 +00001092 if (EnableARCAnnotations) { \
1093 for(BBState::ptr_const_iterator I = (_states)._direction##_ptr_begin(), \
Michael Gottesman43e7e002013-04-03 22:41:59 +00001094 E = (_states)._direction##_ptr_end(); I != E; ++I) { \
Michael Gottesman89279f82013-04-05 18:10:41 +00001095 Value *Ptr = const_cast<Value*>(I->first); \
1096 Sequence Seq = I->second.GetSeq(); \
1097 GenerateARCBB ## _type ## Annotation(_name, (_bb), Ptr, Seq); \
1098 } \
Michael Gottesman43e7e002013-04-03 22:41:59 +00001099 } \
Michael Gottesman89279f82013-04-05 18:10:41 +00001100 } while (0)
Michael Gottesman43e7e002013-04-03 22:41:59 +00001101
Michael Gottesman89279f82013-04-05 18:10:41 +00001102#define ANNOTATE_BOTTOMUP_BBSTART(_states, _basicblock) \
Michael Gottesman43e7e002013-04-03 22:41:59 +00001103 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbstart", \
1104 Entrance, bottom_up)
Michael Gottesman89279f82013-04-05 18:10:41 +00001105#define ANNOTATE_BOTTOMUP_BBEND(_states, _basicblock) \
1106 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbend", \
Michael Gottesman43e7e002013-04-03 22:41:59 +00001107 Terminator, bottom_up)
Michael Gottesman89279f82013-04-05 18:10:41 +00001108#define ANNOTATE_TOPDOWN_BBSTART(_states, _basicblock) \
1109 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbstart", \
Michael Gottesman43e7e002013-04-03 22:41:59 +00001110 Entrance, top_down)
Michael Gottesman89279f82013-04-05 18:10:41 +00001111#define ANNOTATE_TOPDOWN_BBEND(_states, _basicblock) \
1112 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbend", \
Michael Gottesman43e7e002013-04-03 22:41:59 +00001113 Terminator, top_down)
1114
Michael Gottesman81b1d432013-03-26 00:42:04 +00001115#else // !ARC_ANNOTATION
1116// If annotations are off, noop.
1117#define ANNOTATE_BOTTOMUP(inst, ptr, old, new)
1118#define ANNOTATE_TOPDOWN(inst, ptr, old, new)
Michael Gottesman43e7e002013-04-03 22:41:59 +00001119#define ANNOTATE_BOTTOMUP_BBSTART(states, basicblock)
1120#define ANNOTATE_BOTTOMUP_BBEND(states, basicblock)
1121#define ANNOTATE_TOPDOWN_BBSTART(states, basicblock)
1122#define ANNOTATE_TOPDOWN_BBEND(states, basicblock)
Michael Gottesman81b1d432013-03-26 00:42:04 +00001123#endif // !ARC_ANNOTATION
1124
John McCalld935e9c2011-06-15 23:37:01 +00001125namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001126 /// \brief The main ARC optimization pass.
John McCalld935e9c2011-06-15 23:37:01 +00001127 class ObjCARCOpt : public FunctionPass {
1128 bool Changed;
1129 ProvenanceAnalysis PA;
1130
Michael Gottesman5a91bbf2013-05-24 20:44:02 +00001131 // This is used to track if a pointer is stored into an alloca.
1132 DenseSet<const Value *> MultiOwnersSet;
1133
Michael Gottesman97e3df02013-01-14 00:35:14 +00001134 /// A flag indicating whether this optimization pass should run.
Dan Gohmanceaac7c2011-06-20 23:20:43 +00001135 bool Run;
1136
Michael Gottesman97e3df02013-01-14 00:35:14 +00001137 /// Declarations for ObjC runtime functions, for use in creating calls to
1138 /// them. These are initialized lazily to avoid cluttering up the Module
1139 /// with unused declarations.
John McCalld935e9c2011-06-15 23:37:01 +00001140
Michael Gottesman97e3df02013-01-14 00:35:14 +00001141 /// Declaration for ObjC runtime function objc_autoreleaseReturnValue.
1142 Constant *AutoreleaseRVCallee;
1143 /// Declaration for ObjC runtime function objc_release.
1144 Constant *ReleaseCallee;
1145 /// Declaration for ObjC runtime function objc_retain.
1146 Constant *RetainCallee;
1147 /// Declaration for ObjC runtime function objc_retainBlock.
1148 Constant *RetainBlockCallee;
1149 /// Declaration for ObjC runtime function objc_autorelease.
1150 Constant *AutoreleaseCallee;
1151
1152 /// Flags which determine whether each of the interesting runtine functions
1153 /// is in fact used in the current function.
John McCalld935e9c2011-06-15 23:37:01 +00001154 unsigned UsedInThisFunction;
1155
Michael Gottesman97e3df02013-01-14 00:35:14 +00001156 /// The Metadata Kind for clang.imprecise_release metadata.
John McCalld935e9c2011-06-15 23:37:01 +00001157 unsigned ImpreciseReleaseMDKind;
1158
Michael Gottesman97e3df02013-01-14 00:35:14 +00001159 /// The Metadata Kind for clang.arc.copy_on_escape metadata.
Dan Gohmana7107f92011-10-17 22:53:25 +00001160 unsigned CopyOnEscapeMDKind;
1161
Michael Gottesman97e3df02013-01-14 00:35:14 +00001162 /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata.
Dan Gohman0155f302012-02-17 18:59:53 +00001163 unsigned NoObjCARCExceptionsMDKind;
1164
Michael Gottesman81b1d432013-03-26 00:42:04 +00001165#ifdef ARC_ANNOTATIONS
1166 /// The Metadata Kind for llvm.arc.annotation.bottomup metadata.
1167 unsigned ARCAnnotationBottomUpMDKind;
1168 /// The Metadata Kind for llvm.arc.annotation.topdown metadata.
1169 unsigned ARCAnnotationTopDownMDKind;
1170 /// The Metadata Kind for llvm.arc.annotation.provenancesource metadata.
1171 unsigned ARCAnnotationProvenanceSourceMDKind;
1172#endif // ARC_ANNOATIONS
1173
John McCalld935e9c2011-06-15 23:37:01 +00001174 Constant *getAutoreleaseRVCallee(Module *M);
1175 Constant *getReleaseCallee(Module *M);
1176 Constant *getRetainCallee(Module *M);
Dan Gohman6320f522011-07-22 22:29:21 +00001177 Constant *getRetainBlockCallee(Module *M);
John McCalld935e9c2011-06-15 23:37:01 +00001178 Constant *getAutoreleaseCallee(Module *M);
1179
Dan Gohman728db492012-01-13 00:39:07 +00001180 bool IsRetainBlockOptimizable(const Instruction *Inst);
1181
John McCalld935e9c2011-06-15 23:37:01 +00001182 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
Michael Gottesman556ff612013-01-12 01:25:19 +00001183 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1184 InstructionClass &Class);
Michael Gottesman158fdf62013-03-28 20:11:19 +00001185 bool OptimizeRetainBlockCall(Function &F, Instruction *RetainBlock,
1186 InstructionClass &Class);
John McCalld935e9c2011-06-15 23:37:01 +00001187 void OptimizeIndividualCalls(Function &F);
1188
1189 void CheckForCFGHazards(const BasicBlock *BB,
1190 DenseMap<const BasicBlock *, BBState> &BBStates,
1191 BBState &MyStates) const;
Dan Gohman817a7c62012-03-22 18:24:56 +00001192 bool VisitInstructionBottomUp(Instruction *Inst,
Dan Gohman5c70fad2012-03-23 17:47:54 +00001193 BasicBlock *BB,
Dan Gohman817a7c62012-03-22 18:24:56 +00001194 MapVector<Value *, RRInfo> &Retains,
1195 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00001196 bool VisitBottomUp(BasicBlock *BB,
1197 DenseMap<const BasicBlock *, BBState> &BBStates,
1198 MapVector<Value *, RRInfo> &Retains);
Dan Gohman817a7c62012-03-22 18:24:56 +00001199 bool VisitInstructionTopDown(Instruction *Inst,
1200 DenseMap<Value *, RRInfo> &Releases,
1201 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00001202 bool VisitTopDown(BasicBlock *BB,
1203 DenseMap<const BasicBlock *, BBState> &BBStates,
1204 DenseMap<Value *, RRInfo> &Releases);
1205 bool Visit(Function &F,
1206 DenseMap<const BasicBlock *, BBState> &BBStates,
1207 MapVector<Value *, RRInfo> &Retains,
1208 DenseMap<Value *, RRInfo> &Releases);
1209
1210 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1211 MapVector<Value *, RRInfo> &Retains,
1212 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman6320f522011-07-22 22:29:21 +00001213 SmallVectorImpl<Instruction *> &DeadInsts,
1214 Module *M);
John McCalld935e9c2011-06-15 23:37:01 +00001215
Michael Gottesman9de6f962013-01-22 21:49:00 +00001216 bool ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState> &BBStates,
1217 MapVector<Value *, RRInfo> &Retains,
1218 DenseMap<Value *, RRInfo> &Releases,
1219 Module *M,
1220 SmallVector<Instruction *, 4> &NewRetains,
1221 SmallVector<Instruction *, 4> &NewReleases,
1222 SmallVector<Instruction *, 8> &DeadInsts,
1223 RRInfo &RetainsToMove,
1224 RRInfo &ReleasesToMove,
1225 Value *Arg,
1226 bool KnownSafe,
1227 bool &AnyPairsCompletelyEliminated);
1228
John McCalld935e9c2011-06-15 23:37:01 +00001229 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1230 MapVector<Value *, RRInfo> &Retains,
Dan Gohman6320f522011-07-22 22:29:21 +00001231 DenseMap<Value *, RRInfo> &Releases,
1232 Module *M);
John McCalld935e9c2011-06-15 23:37:01 +00001233
1234 void OptimizeWeakCalls(Function &F);
1235
1236 bool OptimizeSequences(Function &F);
1237
1238 void OptimizeReturns(Function &F);
1239
Michael Gottesman9c118152013-04-29 06:16:57 +00001240#ifndef NDEBUG
1241 void GatherStatistics(Function &F, bool AfterOptimization = false);
1242#endif
1243
John McCalld935e9c2011-06-15 23:37:01 +00001244 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1245 virtual bool doInitialization(Module &M);
1246 virtual bool runOnFunction(Function &F);
1247 virtual void releaseMemory();
1248
1249 public:
1250 static char ID;
1251 ObjCARCOpt() : FunctionPass(ID) {
1252 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1253 }
1254 };
1255}
1256
1257char ObjCARCOpt::ID = 0;
1258INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1259 "objc-arc", "ObjC ARC optimization", false, false)
1260INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1261INITIALIZE_PASS_END(ObjCARCOpt,
1262 "objc-arc", "ObjC ARC optimization", false, false)
1263
1264Pass *llvm::createObjCARCOptPass() {
1265 return new ObjCARCOpt();
1266}
1267
1268void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1269 AU.addRequired<ObjCARCAliasAnalysis>();
1270 AU.addRequired<AliasAnalysis>();
1271 // ARC optimization doesn't currently split critical edges.
1272 AU.setPreservesCFG();
1273}
1274
Dan Gohman728db492012-01-13 00:39:07 +00001275bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1276 // Without the magic metadata tag, we have to assume this might be an
1277 // objc_retainBlock call inserted to convert a block pointer to an id,
1278 // in which case it really is needed.
1279 if (!Inst->getMetadata(CopyOnEscapeMDKind))
1280 return false;
1281
1282 // If the pointer "escapes" (not including being used in a call),
1283 // the copy may be needed.
Michael Gottesman774d2c02013-01-29 21:00:52 +00001284 if (DoesRetainableObjPtrEscape(Inst))
Dan Gohman728db492012-01-13 00:39:07 +00001285 return false;
1286
1287 // Otherwise, it's not needed.
1288 return true;
1289}
1290
John McCalld935e9c2011-06-15 23:37:01 +00001291Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1292 if (!AutoreleaseRVCallee) {
1293 LLVMContext &C = M->getContext();
Jay Foadb804a2b2011-07-12 14:06:48 +00001294 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman41375a32012-05-08 23:39:44 +00001295 Type *Params[] = { I8X };
1296 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001297 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001298 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1299 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001300 AutoreleaseRVCallee =
1301 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001302 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001303 }
1304 return AutoreleaseRVCallee;
1305}
1306
1307Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1308 if (!ReleaseCallee) {
1309 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001310 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001311 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001312 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1313 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001314 ReleaseCallee =
1315 M->getOrInsertFunction(
1316 "objc_release",
1317 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001318 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001319 }
1320 return ReleaseCallee;
1321}
1322
1323Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1324 if (!RetainCallee) {
1325 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001326 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001327 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001328 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1329 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001330 RetainCallee =
1331 M->getOrInsertFunction(
1332 "objc_retain",
1333 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001334 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001335 }
1336 return RetainCallee;
1337}
1338
Dan Gohman6320f522011-07-22 22:29:21 +00001339Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1340 if (!RetainBlockCallee) {
1341 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001342 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Dan Gohmanfca43c22011-09-14 18:33:34 +00001343 // objc_retainBlock is not nounwind because it calls user copy constructors
1344 // which could theoretically throw.
Dan Gohman6320f522011-07-22 22:29:21 +00001345 RetainBlockCallee =
1346 M->getOrInsertFunction(
1347 "objc_retainBlock",
1348 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendlinge94d8432012-12-07 23:16:57 +00001349 AttributeSet());
Dan Gohman6320f522011-07-22 22:29:21 +00001350 }
1351 return RetainBlockCallee;
1352}
1353
John McCalld935e9c2011-06-15 23:37:01 +00001354Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1355 if (!AutoreleaseCallee) {
1356 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001357 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001358 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001359 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1360 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001361 AutoreleaseCallee =
1362 M->getOrInsertFunction(
1363 "objc_autorelease",
1364 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001365 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001366 }
1367 return AutoreleaseCallee;
1368}
1369
Michael Gottesman97e3df02013-01-14 00:35:14 +00001370/// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is
1371/// not a return value. Or, if it can be paired with an
1372/// objc_autoreleaseReturnValue, delete the pair and return true.
John McCalld935e9c2011-06-15 23:37:01 +00001373bool
1374ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001375 // Check for the argument being from an immediately preceding call or invoke.
Dan Gohmandae33492012-04-27 18:56:31 +00001376 const Value *Arg = GetObjCArg(RetainRV);
1377 ImmutableCallSite CS(Arg);
1378 if (const Instruction *Call = CS.getInstruction()) {
John McCalld935e9c2011-06-15 23:37:01 +00001379 if (Call->getParent() == RetainRV->getParent()) {
Dan Gohmandae33492012-04-27 18:56:31 +00001380 BasicBlock::const_iterator I = Call;
John McCalld935e9c2011-06-15 23:37:01 +00001381 ++I;
Michael Gottesman65c24812013-03-25 09:27:43 +00001382 while (IsNoopInstruction(I)) ++I;
John McCalld935e9c2011-06-15 23:37:01 +00001383 if (&*I == RetainRV)
1384 return false;
Dan Gohmandae33492012-04-27 18:56:31 +00001385 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001386 BasicBlock *RetainRVParent = RetainRV->getParent();
1387 if (II->getNormalDest() == RetainRVParent) {
Dan Gohmandae33492012-04-27 18:56:31 +00001388 BasicBlock::const_iterator I = RetainRVParent->begin();
Michael Gottesman65c24812013-03-25 09:27:43 +00001389 while (IsNoopInstruction(I)) ++I;
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001390 if (&*I == RetainRV)
1391 return false;
1392 }
John McCalld935e9c2011-06-15 23:37:01 +00001393 }
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001394 }
John McCalld935e9c2011-06-15 23:37:01 +00001395
1396 // Check for being preceded by an objc_autoreleaseReturnValue on the same
1397 // pointer. In this case, we can delete the pair.
1398 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
1399 if (I != Begin) {
Michael Gottesman65c24812013-03-25 09:27:43 +00001400 do --I; while (I != Begin && IsNoopInstruction(I));
John McCalld935e9c2011-06-15 23:37:01 +00001401 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
1402 GetObjCArg(I) == Arg) {
1403 Changed = true;
1404 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00001405
Michael Gottesman89279f82013-04-05 18:10:41 +00001406 DEBUG(dbgs() << "Erasing autoreleaseRV,retainRV pair: " << *I << "\n"
1407 << "Erasing " << *RetainRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001408
John McCalld935e9c2011-06-15 23:37:01 +00001409 EraseInstruction(I);
1410 EraseInstruction(RetainRV);
1411 return true;
1412 }
1413 }
1414
1415 // Turn it to a plain objc_retain.
1416 Changed = true;
1417 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00001418
Michael Gottesman89279f82013-04-05 18:10:41 +00001419 DEBUG(dbgs() << "Transforming objc_retainAutoreleasedReturnValue => "
Michael Gottesmandef07bb2013-01-05 17:55:42 +00001420 "objc_retain since the operand is not a return value.\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00001421 "Old = " << *RetainRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001422
John McCalld935e9c2011-06-15 23:37:01 +00001423 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
Michael Gottesmandef07bb2013-01-05 17:55:42 +00001424
Michael Gottesman89279f82013-04-05 18:10:41 +00001425 DEBUG(dbgs() << "New = " << *RetainRV << "\n");
Michael Gottesmandef07bb2013-01-05 17:55:42 +00001426
John McCalld935e9c2011-06-15 23:37:01 +00001427 return false;
1428}
1429
Michael Gottesman97e3df02013-01-14 00:35:14 +00001430/// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not
1431/// used as a return value.
John McCalld935e9c2011-06-15 23:37:01 +00001432void
Michael Gottesman556ff612013-01-12 01:25:19 +00001433ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1434 InstructionClass &Class) {
John McCalld935e9c2011-06-15 23:37:01 +00001435 // Check for a return of the pointer value.
1436 const Value *Ptr = GetObjCArg(AutoreleaseRV);
Dan Gohman10a18d52011-08-12 00:36:31 +00001437 SmallVector<const Value *, 2> Users;
1438 Users.push_back(Ptr);
1439 do {
1440 Ptr = Users.pop_back_val();
1441 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
1442 UI != UE; ++UI) {
1443 const User *I = *UI;
1444 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
1445 return;
1446 if (isa<BitCastInst>(I))
1447 Users.push_back(I);
1448 }
1449 } while (!Users.empty());
John McCalld935e9c2011-06-15 23:37:01 +00001450
1451 Changed = true;
1452 ++NumPeeps;
Michael Gottesman1bf69082013-01-06 21:07:11 +00001453
Michael Gottesman89279f82013-04-05 18:10:41 +00001454 DEBUG(dbgs() << "Transforming objc_autoreleaseReturnValue => "
Michael Gottesman1bf69082013-01-06 21:07:11 +00001455 "objc_autorelease since its operand is not used as a return "
1456 "value.\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00001457 "Old = " << *AutoreleaseRV << "\n");
Michael Gottesman1bf69082013-01-06 21:07:11 +00001458
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001459 CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
1460 AutoreleaseRVCI->
John McCalld935e9c2011-06-15 23:37:01 +00001461 setCalledFunction(getAutoreleaseCallee(F.getParent()));
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001462 AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
Michael Gottesman556ff612013-01-12 01:25:19 +00001463 Class = IC_Autorelease;
Michael Gottesman10426b52013-01-07 21:26:07 +00001464
Michael Gottesman89279f82013-04-05 18:10:41 +00001465 DEBUG(dbgs() << "New: " << *AutoreleaseRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001466
John McCalld935e9c2011-06-15 23:37:01 +00001467}
1468
Michael Gottesman158fdf62013-03-28 20:11:19 +00001469// \brief Attempt to strength reduce objc_retainBlock calls to objc_retain
1470// calls.
1471//
1472// Specifically: If an objc_retainBlock call has the copy_on_escape metadata and
1473// does not escape (following the rules of block escaping), strength reduce the
1474// objc_retainBlock to an objc_retain.
1475//
1476// TODO: If an objc_retainBlock call is dominated period by a previous
1477// objc_retainBlock call, strength reduce the objc_retainBlock to an
1478// objc_retain.
1479bool
1480ObjCARCOpt::OptimizeRetainBlockCall(Function &F, Instruction *Inst,
1481 InstructionClass &Class) {
1482 assert(GetBasicInstructionClass(Inst) == Class);
1483 assert(IC_RetainBlock == Class);
Michael Gottesman60f6b282013-03-29 05:13:07 +00001484
Michael Gottesman158fdf62013-03-28 20:11:19 +00001485 // If we can not optimize Inst, return false.
1486 if (!IsRetainBlockOptimizable(Inst))
1487 return false;
Michael Gottesman60f6b282013-03-29 05:13:07 +00001488
Michael Gottesman3eab2e42013-04-21 00:50:27 +00001489 Changed = true;
1490 ++NumPeeps;
1491
1492 DEBUG(dbgs() << "Strength reduced retainBlock => retain.\n");
1493 DEBUG(dbgs() << "Old: " << *Inst << "\n");
Michael Gottesman158fdf62013-03-28 20:11:19 +00001494 CallInst *RetainBlock = cast<CallInst>(Inst);
1495 RetainBlock->setCalledFunction(getRetainCallee(F.getParent()));
1496 // Remove copy_on_escape metadata.
1497 RetainBlock->setMetadata(CopyOnEscapeMDKind, 0);
1498 Class = IC_Retain;
Michael Gottesman3eab2e42013-04-21 00:50:27 +00001499 DEBUG(dbgs() << "New: " << *Inst << "\n");
Michael Gottesman158fdf62013-03-28 20:11:19 +00001500 return true;
1501}
1502
Michael Gottesman97e3df02013-01-14 00:35:14 +00001503/// Visit each call, one at a time, and make simplifications without doing any
1504/// additional analysis.
John McCalld935e9c2011-06-15 23:37:01 +00001505void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001506 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeIndividualCalls ==\n");
John McCalld935e9c2011-06-15 23:37:01 +00001507 // Reset all the flags in preparation for recomputing them.
1508 UsedInThisFunction = 0;
1509
1510 // Visit all objc_* calls in F.
1511 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
1512 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +00001513
John McCalld935e9c2011-06-15 23:37:01 +00001514 InstructionClass Class = GetBasicInstructionClass(Inst);
1515
Michael Gottesman89279f82013-04-05 18:10:41 +00001516 DEBUG(dbgs() << "Visiting: Class: " << Class << "; " << *Inst << "\n");
Michael Gottesman782e3442013-01-17 18:32:34 +00001517
John McCalld935e9c2011-06-15 23:37:01 +00001518 switch (Class) {
1519 default: break;
1520
1521 // Delete no-op casts. These function calls have special semantics, but
1522 // the semantics are entirely implemented via lowering in the front-end,
1523 // so by the time they reach the optimizer, they are just no-op calls
1524 // which return their argument.
1525 //
1526 // There are gray areas here, as the ability to cast reference-counted
1527 // pointers to raw void* and back allows code to break ARC assumptions,
1528 // however these are currently considered to be unimportant.
1529 case IC_NoopCast:
1530 Changed = true;
1531 ++NumNoops;
Michael Gottesman89279f82013-04-05 18:10:41 +00001532 DEBUG(dbgs() << "Erasing no-op cast: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001533 EraseInstruction(Inst);
1534 continue;
1535
1536 // If the pointer-to-weak-pointer is null, it's undefined behavior.
1537 case IC_StoreWeak:
1538 case IC_LoadWeak:
1539 case IC_LoadWeakRetained:
1540 case IC_InitWeak:
1541 case IC_DestroyWeak: {
1542 CallInst *CI = cast<CallInst>(Inst);
Michael Gottesman65c24812013-03-25 09:27:43 +00001543 if (IsNullOrUndef(CI->getArgOperand(0))) {
Dan Gohman670f9372012-04-13 18:57:48 +00001544 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +00001545 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001546 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1547 Constant::getNullValue(Ty),
1548 CI);
Michael Gottesman10426b52013-01-07 21:26:07 +00001549 llvm::Value *NewValue = UndefValue::get(CI->getType());
Michael Gottesman89279f82013-04-05 18:10:41 +00001550 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
1551 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001552 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +00001553 CI->eraseFromParent();
1554 continue;
1555 }
1556 break;
1557 }
1558 case IC_CopyWeak:
1559 case IC_MoveWeak: {
1560 CallInst *CI = cast<CallInst>(Inst);
Michael Gottesman65c24812013-03-25 09:27:43 +00001561 if (IsNullOrUndef(CI->getArgOperand(0)) ||
1562 IsNullOrUndef(CI->getArgOperand(1))) {
Dan Gohman670f9372012-04-13 18:57:48 +00001563 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +00001564 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001565 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1566 Constant::getNullValue(Ty),
1567 CI);
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001568
1569 llvm::Value *NewValue = UndefValue::get(CI->getType());
Michael Gottesman89279f82013-04-05 18:10:41 +00001570 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
1571 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001572
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001573 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +00001574 CI->eraseFromParent();
1575 continue;
1576 }
1577 break;
1578 }
Michael Gottesman158fdf62013-03-28 20:11:19 +00001579 case IC_RetainBlock:
Michael Gottesman1e430042013-04-21 00:44:46 +00001580 // If we strength reduce an objc_retainBlock to an objc_retain, continue
Michael Gottesman158fdf62013-03-28 20:11:19 +00001581 // onto the objc_retain peephole optimizations. Otherwise break.
Michael Gottesman9fc50b82013-05-13 18:29:07 +00001582 OptimizeRetainBlockCall(F, Inst, Class);
John McCalld935e9c2011-06-15 23:37:01 +00001583 break;
1584 case IC_RetainRV:
1585 if (OptimizeRetainRVCall(F, Inst))
1586 continue;
1587 break;
1588 case IC_AutoreleaseRV:
Michael Gottesman556ff612013-01-12 01:25:19 +00001589 OptimizeAutoreleaseRVCall(F, Inst, Class);
John McCalld935e9c2011-06-15 23:37:01 +00001590 break;
1591 }
1592
Michael Gottesmanb8c88362013-04-03 02:57:24 +00001593 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
John McCalld935e9c2011-06-15 23:37:01 +00001594 if (IsAutorelease(Class) && Inst->use_empty()) {
1595 CallInst *Call = cast<CallInst>(Inst);
1596 const Value *Arg = Call->getArgOperand(0);
1597 Arg = FindSingleUseIdentifiedObject(Arg);
1598 if (Arg) {
1599 Changed = true;
1600 ++NumAutoreleases;
1601
1602 // Create the declaration lazily.
1603 LLVMContext &C = Inst->getContext();
1604 CallInst *NewCall =
1605 CallInst::Create(getReleaseCallee(F.getParent()),
1606 Call->getArgOperand(0), "", Call);
Dmitri Gribenko3238fb72013-05-05 00:40:33 +00001607 NewCall->setMetadata(ImpreciseReleaseMDKind, MDNode::get(C, None));
Michael Gottesman10426b52013-01-07 21:26:07 +00001608
Michael Gottesman89279f82013-04-05 18:10:41 +00001609 DEBUG(dbgs() << "Replacing autorelease{,RV}(x) with objc_release(x) "
1610 "since x is otherwise unused.\nOld: " << *Call << "\nNew: "
1611 << *NewCall << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001612
John McCalld935e9c2011-06-15 23:37:01 +00001613 EraseInstruction(Call);
1614 Inst = NewCall;
1615 Class = IC_Release;
1616 }
1617 }
1618
1619 // For functions which can never be passed stack arguments, add
1620 // a tail keyword.
1621 if (IsAlwaysTail(Class)) {
1622 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +00001623 DEBUG(dbgs() << "Adding tail keyword to function since it can never be "
1624 "passed stack args: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001625 cast<CallInst>(Inst)->setTailCall();
1626 }
1627
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001628 // Ensure that functions that can never have a "tail" keyword due to the
1629 // semantics of ARC truly do not do so.
1630 if (IsNeverTail(Class)) {
1631 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +00001632 DEBUG(dbgs() << "Removing tail keyword from function: " << *Inst <<
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001633 "\n");
1634 cast<CallInst>(Inst)->setTailCall(false);
1635 }
1636
John McCalld935e9c2011-06-15 23:37:01 +00001637 // Set nounwind as needed.
1638 if (IsNoThrow(Class)) {
1639 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +00001640 DEBUG(dbgs() << "Found no throw class. Setting nounwind on: " << *Inst
1641 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001642 cast<CallInst>(Inst)->setDoesNotThrow();
1643 }
1644
1645 if (!IsNoopOnNull(Class)) {
1646 UsedInThisFunction |= 1 << Class;
1647 continue;
1648 }
1649
1650 const Value *Arg = GetObjCArg(Inst);
1651
1652 // ARC calls with null are no-ops. Delete them.
Michael Gottesman65c24812013-03-25 09:27:43 +00001653 if (IsNullOrUndef(Arg)) {
John McCalld935e9c2011-06-15 23:37:01 +00001654 Changed = true;
1655 ++NumNoops;
Michael Gottesman89279f82013-04-05 18:10:41 +00001656 DEBUG(dbgs() << "ARC calls with null are no-ops. Erasing: " << *Inst
1657 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001658 EraseInstruction(Inst);
1659 continue;
1660 }
1661
1662 // Keep track of which of retain, release, autorelease, and retain_block
1663 // are actually present in this function.
1664 UsedInThisFunction |= 1 << Class;
1665
1666 // If Arg is a PHI, and one or more incoming values to the
1667 // PHI are null, and the call is control-equivalent to the PHI, and there
1668 // are no relevant side effects between the PHI and the call, the call
1669 // could be pushed up to just those paths with non-null incoming values.
1670 // For now, don't bother splitting critical edges for this.
1671 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
1672 Worklist.push_back(std::make_pair(Inst, Arg));
1673 do {
1674 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
1675 Inst = Pair.first;
1676 Arg = Pair.second;
1677
1678 const PHINode *PN = dyn_cast<PHINode>(Arg);
1679 if (!PN) continue;
1680
1681 // Determine if the PHI has any null operands, or any incoming
1682 // critical edges.
1683 bool HasNull = false;
1684 bool HasCriticalEdges = false;
1685 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1686 Value *Incoming =
1687 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
Michael Gottesman65c24812013-03-25 09:27:43 +00001688 if (IsNullOrUndef(Incoming))
John McCalld935e9c2011-06-15 23:37:01 +00001689 HasNull = true;
1690 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
1691 .getNumSuccessors() != 1) {
1692 HasCriticalEdges = true;
1693 break;
1694 }
1695 }
1696 // If we have null operands and no critical edges, optimize.
1697 if (!HasCriticalEdges && HasNull) {
1698 SmallPtrSet<Instruction *, 4> DependingInstructions;
1699 SmallPtrSet<const BasicBlock *, 4> Visited;
1700
1701 // Check that there is nothing that cares about the reference
1702 // count between the call and the phi.
Dan Gohman8478d762012-04-13 00:59:57 +00001703 switch (Class) {
1704 case IC_Retain:
1705 case IC_RetainBlock:
1706 // These can always be moved up.
1707 break;
1708 case IC_Release:
Dan Gohman41375a32012-05-08 23:39:44 +00001709 // These can't be moved across things that care about the retain
1710 // count.
Dan Gohman8478d762012-04-13 00:59:57 +00001711 FindDependencies(NeedsPositiveRetainCount, Arg,
1712 Inst->getParent(), Inst,
1713 DependingInstructions, Visited, PA);
1714 break;
1715 case IC_Autorelease:
1716 // These can't be moved across autorelease pool scope boundaries.
1717 FindDependencies(AutoreleasePoolBoundary, Arg,
1718 Inst->getParent(), Inst,
1719 DependingInstructions, Visited, PA);
1720 break;
1721 case IC_RetainRV:
1722 case IC_AutoreleaseRV:
1723 // Don't move these; the RV optimization depends on the autoreleaseRV
1724 // being tail called, and the retainRV being immediately after a call
1725 // (which might still happen if we get lucky with codegen layout, but
1726 // it's not worth taking the chance).
1727 continue;
1728 default:
1729 llvm_unreachable("Invalid dependence flavor");
1730 }
1731
John McCalld935e9c2011-06-15 23:37:01 +00001732 if (DependingInstructions.size() == 1 &&
1733 *DependingInstructions.begin() == PN) {
1734 Changed = true;
1735 ++NumPartialNoops;
1736 // Clone the call into each predecessor that has a non-null value.
1737 CallInst *CInst = cast<CallInst>(Inst);
Chris Lattner229907c2011-07-18 04:54:35 +00001738 Type *ParamTy = CInst->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001739 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1740 Value *Incoming =
1741 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
Michael Gottesman65c24812013-03-25 09:27:43 +00001742 if (!IsNullOrUndef(Incoming)) {
John McCalld935e9c2011-06-15 23:37:01 +00001743 CallInst *Clone = cast<CallInst>(CInst->clone());
1744 Value *Op = PN->getIncomingValue(i);
1745 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
1746 if (Op->getType() != ParamTy)
1747 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
1748 Clone->setArgOperand(0, Op);
1749 Clone->insertBefore(InsertPos);
Michael Gottesmanc189a392013-01-09 19:23:24 +00001750
Michael Gottesman89279f82013-04-05 18:10:41 +00001751 DEBUG(dbgs() << "Cloning "
Michael Gottesmanc189a392013-01-09 19:23:24 +00001752 << *CInst << "\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00001753 "And inserting clone at " << *InsertPos << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001754 Worklist.push_back(std::make_pair(Clone, Incoming));
1755 }
1756 }
1757 // Erase the original call.
Michael Gottesmanc189a392013-01-09 19:23:24 +00001758 DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001759 EraseInstruction(CInst);
1760 continue;
1761 }
1762 }
1763 } while (!Worklist.empty());
1764 }
1765}
1766
Michael Gottesman323964c2013-04-18 05:39:45 +00001767/// If we have a top down pointer in the S_Use state, make sure that there are
1768/// no CFG hazards by checking the states of various bottom up pointers.
1769static void CheckForUseCFGHazard(const Sequence SuccSSeq,
1770 const bool SuccSRRIKnownSafe,
1771 PtrState &S,
1772 bool &SomeSuccHasSame,
1773 bool &AllSuccsHaveSame,
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001774 bool &NotAllSeqEqualButKnownSafe,
Michael Gottesman323964c2013-04-18 05:39:45 +00001775 bool &ShouldContinue) {
1776 switch (SuccSSeq) {
1777 case S_CanRelease: {
Michael Gottesman93132252013-06-21 06:59:02 +00001778 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe) {
Michael Gottesman323964c2013-04-18 05:39:45 +00001779 S.ClearSequenceProgress();
1780 break;
1781 }
Michael Gottesman2f294592013-06-21 19:12:36 +00001782 S.SetCFGHazardAfflicted(true);
Michael Gottesman323964c2013-04-18 05:39:45 +00001783 ShouldContinue = true;
1784 break;
1785 }
1786 case S_Use:
1787 SomeSuccHasSame = true;
1788 break;
1789 case S_Stop:
1790 case S_Release:
1791 case S_MovableRelease:
Michael Gottesman93132252013-06-21 06:59:02 +00001792 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe)
Michael Gottesman323964c2013-04-18 05:39:45 +00001793 AllSuccsHaveSame = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001794 else
1795 NotAllSeqEqualButKnownSafe = true;
Michael Gottesman323964c2013-04-18 05:39:45 +00001796 break;
1797 case S_Retain:
1798 llvm_unreachable("bottom-up pointer in retain state!");
1799 case S_None:
1800 llvm_unreachable("This should have been handled earlier.");
1801 }
1802}
1803
1804/// If we have a Top Down pointer in the S_CanRelease state, make sure that
1805/// there are no CFG hazards by checking the states of various bottom up
1806/// pointers.
1807static void CheckForCanReleaseCFGHazard(const Sequence SuccSSeq,
1808 const bool SuccSRRIKnownSafe,
1809 PtrState &S,
1810 bool &SomeSuccHasSame,
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001811 bool &AllSuccsHaveSame,
1812 bool &NotAllSeqEqualButKnownSafe) {
Michael Gottesman323964c2013-04-18 05:39:45 +00001813 switch (SuccSSeq) {
1814 case S_CanRelease:
1815 SomeSuccHasSame = true;
1816 break;
1817 case S_Stop:
1818 case S_Release:
1819 case S_MovableRelease:
1820 case S_Use:
Michael Gottesman93132252013-06-21 06:59:02 +00001821 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe)
Michael Gottesman323964c2013-04-18 05:39:45 +00001822 AllSuccsHaveSame = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001823 else
1824 NotAllSeqEqualButKnownSafe = true;
Michael Gottesman323964c2013-04-18 05:39:45 +00001825 break;
1826 case S_Retain:
1827 llvm_unreachable("bottom-up pointer in retain state!");
1828 case S_None:
1829 llvm_unreachable("This should have been handled earlier.");
1830 }
1831}
1832
Michael Gottesman97e3df02013-01-14 00:35:14 +00001833/// Check for critical edges, loop boundaries, irreducible control flow, or
1834/// other CFG structures where moving code across the edge would result in it
1835/// being executed more.
John McCalld935e9c2011-06-15 23:37:01 +00001836void
1837ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
1838 DenseMap<const BasicBlock *, BBState> &BBStates,
1839 BBState &MyStates) const {
1840 // If any top-down local-use or possible-dec has a succ which is earlier in
1841 // the sequence, forget it.
Dan Gohman55b06742012-03-02 01:13:53 +00001842 for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
Michael Gottesman323964c2013-04-18 05:39:45 +00001843 E = MyStates.top_down_ptr_end(); I != E; ++I) {
1844 PtrState &S = I->second;
1845 const Sequence Seq = I->second.GetSeq();
Dan Gohman0155f302012-02-17 18:59:53 +00001846
Michael Gottesman323964c2013-04-18 05:39:45 +00001847 // We only care about S_Retain, S_CanRelease, and S_Use.
1848 if (Seq == S_None)
1849 continue;
Dan Gohman0155f302012-02-17 18:59:53 +00001850
Michael Gottesman323964c2013-04-18 05:39:45 +00001851 // Make sure that if extra top down states are added in the future that this
1852 // code is updated to handle it.
1853 assert((Seq == S_Retain || Seq == S_CanRelease || Seq == S_Use) &&
1854 "Unknown top down sequence state.");
1855
1856 const Value *Arg = I->first;
1857 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
1858 bool SomeSuccHasSame = false;
1859 bool AllSuccsHaveSame = true;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001860 bool NotAllSeqEqualButKnownSafe = false;
Michael Gottesman323964c2013-04-18 05:39:45 +00001861
1862 succ_const_iterator SI(TI), SE(TI, false);
1863
1864 for (; SI != SE; ++SI) {
1865 // If VisitBottomUp has pointer information for this successor, take
1866 // what we know about it.
1867 const DenseMap<const BasicBlock *, BBState>::iterator BBI =
1868 BBStates.find(*SI);
1869 assert(BBI != BBStates.end());
1870 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
1871 const Sequence SuccSSeq = SuccS.GetSeq();
1872
1873 // If bottom up, the pointer is in an S_None state, clear the sequence
1874 // progress since the sequence in the bottom up state finished
1875 // suggesting a mismatch in between retains/releases. This is true for
1876 // all three cases that we are handling here: S_Retain, S_Use, and
1877 // S_CanRelease.
1878 if (SuccSSeq == S_None) {
Dan Gohman12130272011-08-12 00:26:31 +00001879 S.ClearSequenceProgress();
Michael Gottesman323964c2013-04-18 05:39:45 +00001880 continue;
1881 }
1882
1883 // If we have S_Use or S_CanRelease, perform our check for cfg hazard
1884 // checks.
Michael Gottesman93132252013-06-21 06:59:02 +00001885 const bool SuccSRRIKnownSafe = SuccS.IsKnownSafe();
Michael Gottesman323964c2013-04-18 05:39:45 +00001886
1887 // *NOTE* We do not use Seq from above here since we are allowing for
1888 // S.GetSeq() to change while we are visiting basic blocks.
1889 switch(S.GetSeq()) {
1890 case S_Use: {
1891 bool ShouldContinue = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001892 CheckForUseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S, SomeSuccHasSame,
1893 AllSuccsHaveSame, NotAllSeqEqualButKnownSafe,
Michael Gottesman323964c2013-04-18 05:39:45 +00001894 ShouldContinue);
1895 if (ShouldContinue)
1896 continue;
1897 break;
1898 }
1899 case S_CanRelease: {
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001900 CheckForCanReleaseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S,
1901 SomeSuccHasSame, AllSuccsHaveSame,
1902 NotAllSeqEqualButKnownSafe);
Michael Gottesman323964c2013-04-18 05:39:45 +00001903 break;
1904 }
1905 case S_Retain:
1906 case S_None:
1907 case S_Stop:
1908 case S_Release:
1909 case S_MovableRelease:
1910 break;
1911 }
John McCalld935e9c2011-06-15 23:37:01 +00001912 }
Michael Gottesman323964c2013-04-18 05:39:45 +00001913
1914 // If the state at the other end of any of the successor edges
1915 // matches the current state, require all edges to match. This
1916 // guards against loops in the middle of a sequence.
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001917 if (SomeSuccHasSame && !AllSuccsHaveSame) {
Michael Gottesman323964c2013-04-18 05:39:45 +00001918 S.ClearSequenceProgress();
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001919 } else if (NotAllSeqEqualButKnownSafe) {
1920 // If we would have cleared the state foregoing the fact that we are known
1921 // safe, stop code motion. This is because whether or not it is safe to
1922 // remove RR pairs via KnownSafe is an orthogonal concept to whether we
1923 // are allowed to perform code motion.
Michael Gottesman2f294592013-06-21 19:12:36 +00001924 S.SetCFGHazardAfflicted(true);
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001925 }
Michael Gottesman323964c2013-04-18 05:39:45 +00001926 }
John McCalld935e9c2011-06-15 23:37:01 +00001927}
1928
1929bool
Dan Gohman817a7c62012-03-22 18:24:56 +00001930ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
Dan Gohman5c70fad2012-03-23 17:47:54 +00001931 BasicBlock *BB,
Dan Gohman817a7c62012-03-22 18:24:56 +00001932 MapVector<Value *, RRInfo> &Retains,
1933 BBState &MyStates) {
1934 bool NestingDetected = false;
1935 InstructionClass Class = GetInstructionClass(Inst);
1936 const Value *Arg = 0;
Michael Gottesman79249972013-04-05 23:46:45 +00001937
Michael Gottesman1d8d2572013-04-05 22:54:28 +00001938 DEBUG(dbgs() << "Class: " << Class << "\n");
Michael Gottesman79249972013-04-05 23:46:45 +00001939
Dan Gohman817a7c62012-03-22 18:24:56 +00001940 switch (Class) {
1941 case IC_Release: {
1942 Arg = GetObjCArg(Inst);
1943
1944 PtrState &S = MyStates.getPtrBottomUpState(Arg);
1945
1946 // If we see two releases in a row on the same pointer. If so, make
1947 // a note, and we'll cicle back to revisit it after we've
1948 // hopefully eliminated the second release, which may allow us to
1949 // eliminate the first release too.
1950 // Theoretically we could implement removal of nested retain+release
1951 // pairs by making PtrState hold a stack of states, but this is
1952 // simple and avoids adding overhead for the non-nested case.
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001953 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001954 DEBUG(dbgs() << "Found nested releases (i.e. a release pair)\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00001955 NestingDetected = true;
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001956 }
Dan Gohman817a7c62012-03-22 18:24:56 +00001957
Dan Gohman817a7c62012-03-22 18:24:56 +00001958 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001959 Sequence NewSeq = ReleaseMetadata ? S_MovableRelease : S_Release;
1960 ANNOTATE_BOTTOMUP(Inst, Arg, S.GetSeq(), NewSeq);
1961 S.ResetSequenceProgress(NewSeq);
Michael Gottesmanf701d3f2013-06-21 07:03:07 +00001962 S.SetReleaseMetadata(ReleaseMetadata);
Michael Gottesman93132252013-06-21 06:59:02 +00001963 S.SetKnownSafe(S.HasKnownPositiveRefCount());
Michael Gottesmanb82a1792013-06-21 07:00:44 +00001964 S.SetTailCallRelease(cast<CallInst>(Inst)->isTailCall());
Michael Gottesman4f6ef112013-06-21 19:44:27 +00001965 S.InsertCall(Inst);
Dan Gohmandf476e52012-09-04 23:16:20 +00001966 S.SetKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001967 break;
1968 }
1969 case IC_RetainBlock:
Michael Gottesman158fdf62013-03-28 20:11:19 +00001970 // In OptimizeIndividualCalls, we have strength reduced all optimizable
1971 // objc_retainBlocks to objc_retains. Thus at this point any
1972 // objc_retainBlocks that we see are not optimizable.
1973 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001974 case IC_Retain:
1975 case IC_RetainRV: {
1976 Arg = GetObjCArg(Inst);
1977
1978 PtrState &S = MyStates.getPtrBottomUpState(Arg);
Dan Gohman62079b42012-04-25 00:50:46 +00001979 S.SetKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001980
Michael Gottesman81b1d432013-03-26 00:42:04 +00001981 Sequence OldSeq = S.GetSeq();
1982 switch (OldSeq) {
Dan Gohman817a7c62012-03-22 18:24:56 +00001983 case S_Stop:
1984 case S_Release:
1985 case S_MovableRelease:
1986 case S_Use:
Michael Gottesman1d8d2572013-04-05 22:54:28 +00001987 // If OldSeq is not S_Use or OldSeq is S_Use and we are tracking an
1988 // imprecise release, clear our reverse insertion points.
Michael Gottesmanf0401182013-06-21 19:12:38 +00001989 if (OldSeq != S_Use || S.IsTrackingImpreciseReleases())
Michael Gottesman4f6ef112013-06-21 19:44:27 +00001990 S.ClearReverseInsertPts();
Dan Gohman817a7c62012-03-22 18:24:56 +00001991 // FALL THROUGH
1992 case S_CanRelease:
1993 // Don't do retain+release tracking for IC_RetainRV, because it's
1994 // better to let it remain as the first instruction after a call.
Michael Gottesmanba648592013-03-28 23:08:44 +00001995 if (Class != IC_RetainRV)
Michael Gottesmane3943d02013-06-21 19:44:30 +00001996 Retains[Inst] = S.GetRRInfo();
Dan Gohman817a7c62012-03-22 18:24:56 +00001997 S.ClearSequenceProgress();
1998 break;
1999 case S_None:
2000 break;
2001 case S_Retain:
2002 llvm_unreachable("bottom-up pointer in retain state!");
2003 }
Michael Gottesman79249972013-04-05 23:46:45 +00002004 ANNOTATE_BOTTOMUP(Inst, Arg, OldSeq, S.GetSeq());
Michael Gottesman31ba23a2013-04-05 22:54:32 +00002005 // A retain moving bottom up can be a use.
2006 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00002007 }
2008 case IC_AutoreleasepoolPop:
2009 // Conservatively, clear MyStates for all known pointers.
2010 MyStates.clearBottomUpPointers();
2011 return NestingDetected;
2012 case IC_AutoreleasepoolPush:
2013 case IC_None:
2014 // These are irrelevant.
2015 return NestingDetected;
Michael Gottesmana76143ee2013-05-13 23:49:42 +00002016 case IC_User:
2017 // If we have a store into an alloca of a pointer we are tracking, the
2018 // pointer has multiple owners implying that we must be more conservative.
2019 //
2020 // This comes up in the context of a pointer being ``KnownSafe''. In the
2021 // presense of a block being initialized, the frontend will emit the
2022 // objc_retain on the original pointer and the release on the pointer loaded
2023 // from the alloca. The optimizer will through the provenance analysis
2024 // realize that the two are related, but since we only require KnownSafe in
2025 // one direction, will match the inner retain on the original pointer with
2026 // the guard release on the original pointer. This is fixed by ensuring that
2027 // in the presense of allocas we only unconditionally remove pointers if
2028 // both our retain and our release are KnownSafe.
2029 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
2030 if (AreAnyUnderlyingObjectsAnAlloca(SI->getPointerOperand())) {
2031 BBState::ptr_iterator I = MyStates.findPtrBottomUpState(
2032 StripPointerCastsAndObjCCalls(SI->getValueOperand()));
2033 if (I != MyStates.bottom_up_ptr_end())
Michael Gottesman5a91bbf2013-05-24 20:44:02 +00002034 MultiOwnersSet.insert(I->first);
Michael Gottesmana76143ee2013-05-13 23:49:42 +00002035 }
2036 }
2037 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00002038 default:
2039 break;
2040 }
2041
2042 // Consider any other possible effects of this instruction on each
2043 // pointer being tracked.
2044 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
2045 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
2046 const Value *Ptr = MI->first;
2047 if (Ptr == Arg)
2048 continue; // Handled above.
2049 PtrState &S = MI->second;
2050 Sequence Seq = S.GetSeq();
2051
2052 // Check for possible releases.
2053 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002054 DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr
2055 << "\n");
Michael Gottesman764b1cf2013-03-23 05:46:19 +00002056 S.ClearKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00002057 switch (Seq) {
2058 case S_Use:
2059 S.SetSeq(S_CanRelease);
Michael Gottesman81b1d432013-03-26 00:42:04 +00002060 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S.GetSeq());
Dan Gohman817a7c62012-03-22 18:24:56 +00002061 continue;
2062 case S_CanRelease:
2063 case S_Release:
2064 case S_MovableRelease:
2065 case S_Stop:
2066 case S_None:
2067 break;
2068 case S_Retain:
2069 llvm_unreachable("bottom-up pointer in retain state!");
2070 }
2071 }
2072
2073 // Check for possible direct uses.
2074 switch (Seq) {
2075 case S_Release:
2076 case S_MovableRelease:
2077 if (CanUse(Inst, Ptr, PA, Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002078 DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr
2079 << "\n");
Michael Gottesman4f6ef112013-06-21 19:44:27 +00002080 assert(!S.HasReverseInsertPts());
Dan Gohman5c70fad2012-03-23 17:47:54 +00002081 // If this is an invoke instruction, we're scanning it as part of
2082 // one of its successor blocks, since we can't insert code after it
2083 // in its own block, and we don't want to split critical edges.
2084 if (isa<InvokeInst>(Inst))
Michael Gottesman4f6ef112013-06-21 19:44:27 +00002085 S.InsertReverseInsertPt(BB->getFirstInsertionPt());
Dan Gohman5c70fad2012-03-23 17:47:54 +00002086 else
Michael Gottesman4f6ef112013-06-21 19:44:27 +00002087 S.InsertReverseInsertPt(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohman817a7c62012-03-22 18:24:56 +00002088 S.SetSeq(S_Use);
Michael Gottesman81b1d432013-03-26 00:42:04 +00002089 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
John McCall20182ac2013-03-22 21:38:36 +00002090 } else if (Seq == S_Release && IsUser(Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002091 DEBUG(dbgs() << "PreciseReleaseUse: Seq: " << Seq << "; " << *Ptr
2092 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00002093 // Non-movable releases depend on any possible objc pointer use.
2094 S.SetSeq(S_Stop);
Michael Gottesman81b1d432013-03-26 00:42:04 +00002095 ANNOTATE_BOTTOMUP(Inst, Ptr, S_Release, S_Stop);
Michael Gottesman4f6ef112013-06-21 19:44:27 +00002096 assert(!S.HasReverseInsertPts());
Dan Gohman5c70fad2012-03-23 17:47:54 +00002097 // As above; handle invoke specially.
2098 if (isa<InvokeInst>(Inst))
Michael Gottesman4f6ef112013-06-21 19:44:27 +00002099 S.InsertReverseInsertPt(BB->getFirstInsertionPt());
Dan Gohman5c70fad2012-03-23 17:47:54 +00002100 else
Michael Gottesman4f6ef112013-06-21 19:44:27 +00002101 S.InsertReverseInsertPt(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohman817a7c62012-03-22 18:24:56 +00002102 }
2103 break;
2104 case S_Stop:
Michael Gottesman81b1d432013-03-26 00:42:04 +00002105 if (CanUse(Inst, Ptr, PA, Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002106 DEBUG(dbgs() << "PreciseStopUse: Seq: " << Seq << "; " << *Ptr
2107 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00002108 S.SetSeq(S_Use);
Michael Gottesman81b1d432013-03-26 00:42:04 +00002109 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
2110 }
Dan Gohman817a7c62012-03-22 18:24:56 +00002111 break;
2112 case S_CanRelease:
2113 case S_Use:
2114 case S_None:
2115 break;
2116 case S_Retain:
2117 llvm_unreachable("bottom-up pointer in retain state!");
2118 }
2119 }
2120
2121 return NestingDetected;
2122}
2123
2124bool
John McCalld935e9c2011-06-15 23:37:01 +00002125ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2126 DenseMap<const BasicBlock *, BBState> &BBStates,
2127 MapVector<Value *, RRInfo> &Retains) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002128
2129 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitBottomUp ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00002130
John McCalld935e9c2011-06-15 23:37:01 +00002131 bool NestingDetected = false;
2132 BBState &MyStates = BBStates[BB];
2133
2134 // Merge the states from each successor to compute the initial state
2135 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00002136 BBState::edge_iterator SI(MyStates.succ_begin()),
2137 SE(MyStates.succ_end());
2138 if (SI != SE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002139 const BasicBlock *Succ = *SI;
2140 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
2141 assert(I != BBStates.end());
2142 MyStates.InitFromSucc(I->second);
2143 ++SI;
2144 for (; SI != SE; ++SI) {
2145 Succ = *SI;
2146 I = BBStates.find(Succ);
2147 assert(I != BBStates.end());
2148 MyStates.MergeSucc(I->second);
2149 }
Michael Gottesman60f6b282013-03-29 05:13:07 +00002150 }
Michael Gottesmancd4de0f2013-03-26 00:42:09 +00002151
Michael Gottesman43e7e002013-04-03 22:41:59 +00002152 // If ARC Annotations are enabled, output the current state of pointers at the
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002153 // bottom of the basic block.
Michael Gottesman43e7e002013-04-03 22:41:59 +00002154 ANNOTATE_BOTTOMUP_BBEND(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002155
John McCalld935e9c2011-06-15 23:37:01 +00002156 // Visit all the instructions, bottom-up.
2157 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2158 Instruction *Inst = llvm::prior(I);
Dan Gohman5c70fad2012-03-23 17:47:54 +00002159
2160 // Invoke instructions are visited as part of their successors (below).
2161 if (isa<InvokeInst>(Inst))
2162 continue;
2163
Michael Gottesman89279f82013-04-05 18:10:41 +00002164 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00002165
Dan Gohman5c70fad2012-03-23 17:47:54 +00002166 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
2167 }
2168
Dan Gohmandae33492012-04-27 18:56:31 +00002169 // If there's a predecessor with an invoke, visit the invoke as if it were
2170 // part of this block, since we can't insert code after an invoke in its own
2171 // block, and we don't want to split critical edges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002172 for (BBState::edge_iterator PI(MyStates.pred_begin()),
2173 PE(MyStates.pred_end()); PI != PE; ++PI) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00002174 BasicBlock *Pred = *PI;
Dan Gohmandae33492012-04-27 18:56:31 +00002175 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
2176 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
Dan Gohman817a7c62012-03-22 18:24:56 +00002177 }
John McCalld935e9c2011-06-15 23:37:01 +00002178
Michael Gottesman43e7e002013-04-03 22:41:59 +00002179 // If ARC Annotations are enabled, output the current state of pointers at the
2180 // top of the basic block.
2181 ANNOTATE_BOTTOMUP_BBSTART(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002182
Dan Gohman817a7c62012-03-22 18:24:56 +00002183 return NestingDetected;
2184}
John McCalld935e9c2011-06-15 23:37:01 +00002185
Dan Gohman817a7c62012-03-22 18:24:56 +00002186bool
2187ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
2188 DenseMap<Value *, RRInfo> &Releases,
2189 BBState &MyStates) {
2190 bool NestingDetected = false;
2191 InstructionClass Class = GetInstructionClass(Inst);
2192 const Value *Arg = 0;
John McCalld935e9c2011-06-15 23:37:01 +00002193
Dan Gohman817a7c62012-03-22 18:24:56 +00002194 switch (Class) {
2195 case IC_RetainBlock:
Michael Gottesman158fdf62013-03-28 20:11:19 +00002196 // In OptimizeIndividualCalls, we have strength reduced all optimizable
2197 // objc_retainBlocks to objc_retains. Thus at this point any
2198 // objc_retainBlocks that we see are not optimizable.
2199 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00002200 case IC_Retain:
2201 case IC_RetainRV: {
2202 Arg = GetObjCArg(Inst);
2203
2204 PtrState &S = MyStates.getPtrTopDownState(Arg);
2205
2206 // Don't do retain+release tracking for IC_RetainRV, because it's
2207 // better to let it remain as the first instruction after a call.
2208 if (Class != IC_RetainRV) {
2209 // If we see two retains in a row on the same pointer. If so, make
John McCalld935e9c2011-06-15 23:37:01 +00002210 // a note, and we'll cicle back to revisit it after we've
Dan Gohman817a7c62012-03-22 18:24:56 +00002211 // hopefully eliminated the second retain, which may allow us to
2212 // eliminate the first retain too.
John McCalld935e9c2011-06-15 23:37:01 +00002213 // Theoretically we could implement removal of nested retain+release
2214 // pairs by making PtrState hold a stack of states, but this is
2215 // simple and avoids adding overhead for the non-nested case.
Dan Gohman817a7c62012-03-22 18:24:56 +00002216 if (S.GetSeq() == S_Retain)
John McCalld935e9c2011-06-15 23:37:01 +00002217 NestingDetected = true;
2218
Michael Gottesman81b1d432013-03-26 00:42:04 +00002219 ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_Retain);
Dan Gohman62079b42012-04-25 00:50:46 +00002220 S.ResetSequenceProgress(S_Retain);
Michael Gottesman93132252013-06-21 06:59:02 +00002221 S.SetKnownSafe(S.HasKnownPositiveRefCount());
Michael Gottesman4f6ef112013-06-21 19:44:27 +00002222 S.InsertCall(Inst);
John McCalld935e9c2011-06-15 23:37:01 +00002223 }
John McCalld935e9c2011-06-15 23:37:01 +00002224
Dan Gohmandf476e52012-09-04 23:16:20 +00002225 S.SetKnownPositiveRefCount();
Dan Gohmanf64ff8e2012-07-23 19:27:31 +00002226
2227 // A retain can be a potential use; procede to the generic checking
2228 // code below.
2229 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00002230 }
2231 case IC_Release: {
2232 Arg = GetObjCArg(Inst);
2233
2234 PtrState &S = MyStates.getPtrTopDownState(Arg);
Michael Gottesman764b1cf2013-03-23 05:46:19 +00002235 S.ClearKnownPositiveRefCount();
Michael Gottesman79249972013-04-05 23:46:45 +00002236
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002237 Sequence OldSeq = S.GetSeq();
Michael Gottesman79249972013-04-05 23:46:45 +00002238
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002239 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
Michael Gottesman79249972013-04-05 23:46:45 +00002240
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002241 switch (OldSeq) {
Dan Gohman817a7c62012-03-22 18:24:56 +00002242 case S_Retain:
2243 case S_CanRelease:
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002244 if (OldSeq == S_Retain || ReleaseMetadata != 0)
Michael Gottesman4f6ef112013-06-21 19:44:27 +00002245 S.ClearReverseInsertPts();
Dan Gohman817a7c62012-03-22 18:24:56 +00002246 // FALL THROUGH
2247 case S_Use:
Michael Gottesmanf701d3f2013-06-21 07:03:07 +00002248 S.SetReleaseMetadata(ReleaseMetadata);
Michael Gottesmanb82a1792013-06-21 07:00:44 +00002249 S.SetTailCallRelease(cast<CallInst>(Inst)->isTailCall());
Michael Gottesmane3943d02013-06-21 19:44:30 +00002250 Releases[Inst] = S.GetRRInfo();
Michael Gottesman81b1d432013-03-26 00:42:04 +00002251 ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_None);
Dan Gohman817a7c62012-03-22 18:24:56 +00002252 S.ClearSequenceProgress();
2253 break;
2254 case S_None:
2255 break;
2256 case S_Stop:
2257 case S_Release:
2258 case S_MovableRelease:
2259 llvm_unreachable("top-down pointer in release state!");
2260 }
2261 break;
2262 }
2263 case IC_AutoreleasepoolPop:
2264 // Conservatively, clear MyStates for all known pointers.
2265 MyStates.clearTopDownPointers();
2266 return NestingDetected;
2267 case IC_AutoreleasepoolPush:
2268 case IC_None:
2269 // These are irrelevant.
2270 return NestingDetected;
2271 default:
2272 break;
2273 }
2274
2275 // Consider any other possible effects of this instruction on each
2276 // pointer being tracked.
2277 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
2278 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
2279 const Value *Ptr = MI->first;
2280 if (Ptr == Arg)
2281 continue; // Handled above.
2282 PtrState &S = MI->second;
2283 Sequence Seq = S.GetSeq();
2284
2285 // Check for possible releases.
2286 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Michael Gottesmanbab49e972013-04-05 18:26:08 +00002287 DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr
Michael Gottesman79249972013-04-05 23:46:45 +00002288 << "\n");
Michael Gottesman764b1cf2013-03-23 05:46:19 +00002289 S.ClearKnownPositiveRefCount();
John McCalld935e9c2011-06-15 23:37:01 +00002290 switch (Seq) {
Dan Gohman817a7c62012-03-22 18:24:56 +00002291 case S_Retain:
2292 S.SetSeq(S_CanRelease);
Michael Gottesman81b1d432013-03-26 00:42:04 +00002293 ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_CanRelease);
Michael Gottesman4f6ef112013-06-21 19:44:27 +00002294 assert(!S.HasReverseInsertPts());
2295 S.InsertReverseInsertPt(Inst);
Dan Gohman817a7c62012-03-22 18:24:56 +00002296
2297 // One call can't cause a transition from S_Retain to S_CanRelease
2298 // and S_CanRelease to S_Use. If we've made the first transition,
2299 // we're done.
2300 continue;
John McCalld935e9c2011-06-15 23:37:01 +00002301 case S_Use:
Dan Gohman817a7c62012-03-22 18:24:56 +00002302 case S_CanRelease:
John McCalld935e9c2011-06-15 23:37:01 +00002303 case S_None:
2304 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00002305 case S_Stop:
2306 case S_Release:
2307 case S_MovableRelease:
2308 llvm_unreachable("top-down pointer in release state!");
John McCalld935e9c2011-06-15 23:37:01 +00002309 }
2310 }
Dan Gohman817a7c62012-03-22 18:24:56 +00002311
2312 // Check for possible direct uses.
2313 switch (Seq) {
2314 case S_CanRelease:
Michael Gottesman81b1d432013-03-26 00:42:04 +00002315 if (CanUse(Inst, Ptr, PA, Class)) {
Michael Gottesmanbab49e972013-04-05 18:26:08 +00002316 DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr
2317 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00002318 S.SetSeq(S_Use);
Michael Gottesman81b1d432013-03-26 00:42:04 +00002319 ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_Use);
2320 }
Dan Gohman817a7c62012-03-22 18:24:56 +00002321 break;
2322 case S_Retain:
2323 case S_Use:
2324 case S_None:
2325 break;
2326 case S_Stop:
2327 case S_Release:
2328 case S_MovableRelease:
2329 llvm_unreachable("top-down pointer in release state!");
2330 }
John McCalld935e9c2011-06-15 23:37:01 +00002331 }
2332
2333 return NestingDetected;
2334}
2335
2336bool
2337ObjCARCOpt::VisitTopDown(BasicBlock *BB,
2338 DenseMap<const BasicBlock *, BBState> &BBStates,
2339 DenseMap<Value *, RRInfo> &Releases) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002340 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitTopDown ==\n");
John McCalld935e9c2011-06-15 23:37:01 +00002341 bool NestingDetected = false;
2342 BBState &MyStates = BBStates[BB];
2343
2344 // Merge the states from each predecessor to compute the initial state
2345 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00002346 BBState::edge_iterator PI(MyStates.pred_begin()),
2347 PE(MyStates.pred_end());
2348 if (PI != PE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002349 const BasicBlock *Pred = *PI;
2350 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
2351 assert(I != BBStates.end());
2352 MyStates.InitFromPred(I->second);
2353 ++PI;
2354 for (; PI != PE; ++PI) {
2355 Pred = *PI;
2356 I = BBStates.find(Pred);
2357 assert(I != BBStates.end());
2358 MyStates.MergePred(I->second);
2359 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002360 }
John McCalld935e9c2011-06-15 23:37:01 +00002361
Michael Gottesman43e7e002013-04-03 22:41:59 +00002362 // If ARC Annotations are enabled, output the current state of pointers at the
2363 // top of the basic block.
2364 ANNOTATE_TOPDOWN_BBSTART(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002365
John McCalld935e9c2011-06-15 23:37:01 +00002366 // Visit all the instructions, top-down.
2367 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2368 Instruction *Inst = I;
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00002369
Michael Gottesman89279f82013-04-05 18:10:41 +00002370 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00002371
Dan Gohman817a7c62012-03-22 18:24:56 +00002372 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00002373 }
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002374
Michael Gottesman43e7e002013-04-03 22:41:59 +00002375 // If ARC Annotations are enabled, output the current state of pointers at the
2376 // bottom of the basic block.
2377 ANNOTATE_TOPDOWN_BBEND(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002378
Michael Gottesmanffef24f2013-04-17 20:48:01 +00002379#ifdef ARC_ANNOTATIONS
Michael Gottesmanadb921a2013-04-17 21:03:53 +00002380 if (!(EnableARCAnnotations && DisableCheckForCFGHazards))
Michael Gottesmanffef24f2013-04-17 20:48:01 +00002381#endif
John McCalld935e9c2011-06-15 23:37:01 +00002382 CheckForCFGHazards(BB, BBStates, MyStates);
2383 return NestingDetected;
2384}
2385
Dan Gohmana53a12c2011-12-12 19:42:25 +00002386static void
2387ComputePostOrders(Function &F,
2388 SmallVectorImpl<BasicBlock *> &PostOrder,
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002389 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
2390 unsigned NoObjCARCExceptionsMDKind,
2391 DenseMap<const BasicBlock *, BBState> &BBStates) {
Michael Gottesman97e3df02013-01-14 00:35:14 +00002392 /// The visited set, for doing DFS walks.
Dan Gohmana53a12c2011-12-12 19:42:25 +00002393 SmallPtrSet<BasicBlock *, 16> Visited;
2394
2395 // Do DFS, computing the PostOrder.
2396 SmallPtrSet<BasicBlock *, 16> OnStack;
2397 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002398
2399 // Functions always have exactly one entry block, and we don't have
2400 // any other block that we treat like an entry block.
Dan Gohmana53a12c2011-12-12 19:42:25 +00002401 BasicBlock *EntryBB = &F.getEntryBlock();
Dan Gohman41375a32012-05-08 23:39:44 +00002402 BBState &MyStates = BBStates[EntryBB];
2403 MyStates.SetAsEntry();
2404 TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
2405 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
Dan Gohmana53a12c2011-12-12 19:42:25 +00002406 Visited.insert(EntryBB);
2407 OnStack.insert(EntryBB);
2408 do {
2409 dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002410 BasicBlock *CurrBB = SuccStack.back().first;
2411 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
2412 succ_iterator SE(TI, false);
Dan Gohman41375a32012-05-08 23:39:44 +00002413
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002414 while (SuccStack.back().second != SE) {
2415 BasicBlock *SuccBB = *SuccStack.back().second++;
2416 if (Visited.insert(SuccBB)) {
Dan Gohman41375a32012-05-08 23:39:44 +00002417 TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
2418 SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002419 BBStates[CurrBB].addSucc(SuccBB);
Dan Gohman41375a32012-05-08 23:39:44 +00002420 BBState &SuccStates = BBStates[SuccBB];
2421 SuccStates.addPred(CurrBB);
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002422 OnStack.insert(SuccBB);
Dan Gohmana53a12c2011-12-12 19:42:25 +00002423 goto dfs_next_succ;
2424 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002425
2426 if (!OnStack.count(SuccBB)) {
2427 BBStates[CurrBB].addSucc(SuccBB);
2428 BBStates[SuccBB].addPred(CurrBB);
2429 }
Dan Gohmana53a12c2011-12-12 19:42:25 +00002430 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002431 OnStack.erase(CurrBB);
2432 PostOrder.push_back(CurrBB);
2433 SuccStack.pop_back();
Dan Gohmana53a12c2011-12-12 19:42:25 +00002434 } while (!SuccStack.empty());
2435
2436 Visited.clear();
2437
Dan Gohmana53a12c2011-12-12 19:42:25 +00002438 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002439 // Functions may have many exits, and there also blocks which we treat
2440 // as exits due to ignored edges.
2441 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
2442 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
2443 BasicBlock *ExitBB = I;
2444 BBState &MyStates = BBStates[ExitBB];
2445 if (!MyStates.isExit())
2446 continue;
2447
Dan Gohmandae33492012-04-27 18:56:31 +00002448 MyStates.SetAsExit();
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002449
2450 PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00002451 Visited.insert(ExitBB);
2452 while (!PredStack.empty()) {
2453 reverse_dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002454 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
2455 while (PredStack.back().second != PE) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00002456 BasicBlock *BB = *PredStack.back().second++;
Dan Gohmana53a12c2011-12-12 19:42:25 +00002457 if (Visited.insert(BB)) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002458 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00002459 goto reverse_dfs_next_succ;
2460 }
2461 }
2462 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
2463 }
2464 }
2465}
2466
Michael Gottesman97e3df02013-01-14 00:35:14 +00002467// Visit the function both top-down and bottom-up.
John McCalld935e9c2011-06-15 23:37:01 +00002468bool
2469ObjCARCOpt::Visit(Function &F,
2470 DenseMap<const BasicBlock *, BBState> &BBStates,
2471 MapVector<Value *, RRInfo> &Retains,
2472 DenseMap<Value *, RRInfo> &Releases) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00002473
2474 // Use reverse-postorder traversals, because we magically know that loops
2475 // will be well behaved, i.e. they won't repeatedly call retain on a single
2476 // pointer without doing a release. We can't use the ReversePostOrderTraversal
2477 // class here because we want the reverse-CFG postorder to consider each
2478 // function exit point, and we want to ignore selected cycle edges.
2479 SmallVector<BasicBlock *, 16> PostOrder;
2480 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002481 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
2482 NoObjCARCExceptionsMDKind,
2483 BBStates);
Dan Gohmana53a12c2011-12-12 19:42:25 +00002484
2485 // Use reverse-postorder on the reverse CFG for bottom-up.
John McCalld935e9c2011-06-15 23:37:01 +00002486 bool BottomUpNestingDetected = false;
Dan Gohmanc57b58c2011-08-18 21:27:42 +00002487 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
Dan Gohmana53a12c2011-12-12 19:42:25 +00002488 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
2489 I != E; ++I)
2490 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
John McCalld935e9c2011-06-15 23:37:01 +00002491
Dan Gohmana53a12c2011-12-12 19:42:25 +00002492 // Use reverse-postorder for top-down.
John McCalld935e9c2011-06-15 23:37:01 +00002493 bool TopDownNestingDetected = false;
Dan Gohmana53a12c2011-12-12 19:42:25 +00002494 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2495 PostOrder.rbegin(), E = PostOrder.rend();
2496 I != E; ++I)
2497 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
John McCalld935e9c2011-06-15 23:37:01 +00002498
2499 return TopDownNestingDetected && BottomUpNestingDetected;
2500}
2501
Michael Gottesman97e3df02013-01-14 00:35:14 +00002502/// Move the calls in RetainsToMove and ReleasesToMove.
John McCalld935e9c2011-06-15 23:37:01 +00002503void ObjCARCOpt::MoveCalls(Value *Arg,
2504 RRInfo &RetainsToMove,
2505 RRInfo &ReleasesToMove,
2506 MapVector<Value *, RRInfo> &Retains,
2507 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman6320f522011-07-22 22:29:21 +00002508 SmallVectorImpl<Instruction *> &DeadInsts,
Michael Gottesman79249972013-04-05 23:46:45 +00002509 Module *M) {
Chris Lattner229907c2011-07-18 04:54:35 +00002510 Type *ArgTy = Arg->getType();
Dan Gohman6320f522011-07-22 22:29:21 +00002511 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
Michael Gottesman79249972013-04-05 23:46:45 +00002512
Michael Gottesman89279f82013-04-05 18:10:41 +00002513 DEBUG(dbgs() << "== ObjCARCOpt::MoveCalls ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00002514
John McCalld935e9c2011-06-15 23:37:01 +00002515 // Insert the new retain and release calls.
2516 for (SmallPtrSet<Instruction *, 2>::const_iterator
2517 PI = ReleasesToMove.ReverseInsertPts.begin(),
2518 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2519 Instruction *InsertPt = *PI;
2520 Value *MyArg = ArgTy == ParamTy ? Arg :
2521 new BitCastInst(Arg, ParamTy, "", InsertPt);
2522 CallInst *Call =
Michael Gottesmanba648592013-03-28 23:08:44 +00002523 CallInst::Create(getRetainCallee(M), MyArg, "", InsertPt);
John McCalld935e9c2011-06-15 23:37:01 +00002524 Call->setDoesNotThrow();
Michael Gottesmanba648592013-03-28 23:08:44 +00002525 Call->setTailCall();
Michael Gottesman60f6b282013-03-29 05:13:07 +00002526
Michael Gottesmandf110ac2013-04-21 00:30:50 +00002527 DEBUG(dbgs() << "Inserting new Retain: " << *Call << "\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00002528 "At insertion point: " << *InsertPt << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002529 }
2530 for (SmallPtrSet<Instruction *, 2>::const_iterator
2531 PI = RetainsToMove.ReverseInsertPts.begin(),
2532 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00002533 Instruction *InsertPt = *PI;
2534 Value *MyArg = ArgTy == ParamTy ? Arg :
2535 new BitCastInst(Arg, ParamTy, "", InsertPt);
2536 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
2537 "", InsertPt);
2538 // Attach a clang.imprecise_release metadata tag, if appropriate.
2539 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
2540 Call->setMetadata(ImpreciseReleaseMDKind, M);
2541 Call->setDoesNotThrow();
2542 if (ReleasesToMove.IsTailCallRelease)
2543 Call->setTailCall();
Michael Gottesmanc189a392013-01-09 19:23:24 +00002544
Michael Gottesman89279f82013-04-05 18:10:41 +00002545 DEBUG(dbgs() << "Inserting new Release: " << *Call << "\n"
2546 "At insertion point: " << *InsertPt << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002547 }
2548
2549 // Delete the original retain and release calls.
2550 for (SmallPtrSet<Instruction *, 2>::const_iterator
2551 AI = RetainsToMove.Calls.begin(),
2552 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
2553 Instruction *OrigRetain = *AI;
2554 Retains.blot(OrigRetain);
2555 DeadInsts.push_back(OrigRetain);
Michael Gottesman89279f82013-04-05 18:10:41 +00002556 DEBUG(dbgs() << "Deleting retain: " << *OrigRetain << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002557 }
2558 for (SmallPtrSet<Instruction *, 2>::const_iterator
2559 AI = ReleasesToMove.Calls.begin(),
2560 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
2561 Instruction *OrigRelease = *AI;
2562 Releases.erase(OrigRelease);
2563 DeadInsts.push_back(OrigRelease);
Michael Gottesman89279f82013-04-05 18:10:41 +00002564 DEBUG(dbgs() << "Deleting release: " << *OrigRelease << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002565 }
Michael Gottesman79249972013-04-05 23:46:45 +00002566
John McCalld935e9c2011-06-15 23:37:01 +00002567}
2568
Michael Gottesman9de6f962013-01-22 21:49:00 +00002569bool
2570ObjCARCOpt::ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState>
2571 &BBStates,
2572 MapVector<Value *, RRInfo> &Retains,
2573 DenseMap<Value *, RRInfo> &Releases,
2574 Module *M,
2575 SmallVector<Instruction *, 4> &NewRetains,
2576 SmallVector<Instruction *, 4> &NewReleases,
2577 SmallVector<Instruction *, 8> &DeadInsts,
2578 RRInfo &RetainsToMove,
2579 RRInfo &ReleasesToMove,
2580 Value *Arg,
2581 bool KnownSafe,
2582 bool &AnyPairsCompletelyEliminated) {
2583 // If a pair happens in a region where it is known that the reference count
Michael Gottesmana76143ee2013-05-13 23:49:42 +00002584 // is already incremented, we can similarly ignore possible decrements unless
2585 // we are dealing with a retainable object with multiple provenance sources.
Michael Gottesman9de6f962013-01-22 21:49:00 +00002586 bool KnownSafeTD = true, KnownSafeBU = true;
Michael Gottesmana76143ee2013-05-13 23:49:42 +00002587 bool MultipleOwners = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00002588 bool CFGHazardAfflicted = false;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002589
2590 // Connect the dots between the top-down-collected RetainsToMove and
2591 // bottom-up-collected ReleasesToMove to form sets of related calls.
2592 // This is an iterative process so that we connect multiple releases
2593 // to multiple retains if needed.
2594 unsigned OldDelta = 0;
2595 unsigned NewDelta = 0;
2596 unsigned OldCount = 0;
2597 unsigned NewCount = 0;
2598 bool FirstRelease = true;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002599 for (;;) {
2600 for (SmallVectorImpl<Instruction *>::const_iterator
2601 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
2602 Instruction *NewRetain = *NI;
2603 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
2604 assert(It != Retains.end());
2605 const RRInfo &NewRetainRRI = It->second;
2606 KnownSafeTD &= NewRetainRRI.KnownSafe;
Michael Gottesman5a91bbf2013-05-24 20:44:02 +00002607 MultipleOwners =
2608 MultipleOwners || MultiOwnersSet.count(GetObjCArg(NewRetain));
Michael Gottesman9de6f962013-01-22 21:49:00 +00002609 for (SmallPtrSet<Instruction *, 2>::const_iterator
2610 LI = NewRetainRRI.Calls.begin(),
2611 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
2612 Instruction *NewRetainRelease = *LI;
2613 DenseMap<Value *, RRInfo>::const_iterator Jt =
2614 Releases.find(NewRetainRelease);
2615 if (Jt == Releases.end())
2616 return false;
2617 const RRInfo &NewRetainReleaseRRI = Jt->second;
2618 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
2619 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002620
2621 // If we overflow when we compute the path count, don't remove/move
2622 // anything.
2623 const BBState &NRRBBState = BBStates[NewRetainRelease->getParent()];
2624 unsigned PathCount;
2625 if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
2626 return false;
2627 OldDelta -= PathCount;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002628
2629 // Merge the ReleaseMetadata and IsTailCallRelease values.
2630 if (FirstRelease) {
2631 ReleasesToMove.ReleaseMetadata =
2632 NewRetainReleaseRRI.ReleaseMetadata;
2633 ReleasesToMove.IsTailCallRelease =
2634 NewRetainReleaseRRI.IsTailCallRelease;
2635 FirstRelease = false;
2636 } else {
2637 if (ReleasesToMove.ReleaseMetadata !=
2638 NewRetainReleaseRRI.ReleaseMetadata)
2639 ReleasesToMove.ReleaseMetadata = 0;
2640 if (ReleasesToMove.IsTailCallRelease !=
2641 NewRetainReleaseRRI.IsTailCallRelease)
2642 ReleasesToMove.IsTailCallRelease = false;
2643 }
2644
2645 // Collect the optimal insertion points.
2646 if (!KnownSafe)
2647 for (SmallPtrSet<Instruction *, 2>::const_iterator
2648 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
2649 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
2650 RI != RE; ++RI) {
2651 Instruction *RIP = *RI;
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002652 if (ReleasesToMove.ReverseInsertPts.insert(RIP)) {
2653 // If we overflow when we compute the path count, don't
2654 // remove/move anything.
2655 const BBState &RIPBBState = BBStates[RIP->getParent()];
2656 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
2657 return false;
2658 NewDelta -= PathCount;
2659 }
Michael Gottesman9de6f962013-01-22 21:49:00 +00002660 }
2661 NewReleases.push_back(NewRetainRelease);
2662 }
2663 }
2664 }
2665 NewRetains.clear();
2666 if (NewReleases.empty()) break;
2667
2668 // Back the other way.
2669 for (SmallVectorImpl<Instruction *>::const_iterator
2670 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
2671 Instruction *NewRelease = *NI;
2672 DenseMap<Value *, RRInfo>::const_iterator It =
2673 Releases.find(NewRelease);
2674 assert(It != Releases.end());
2675 const RRInfo &NewReleaseRRI = It->second;
2676 KnownSafeBU &= NewReleaseRRI.KnownSafe;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00002677 CFGHazardAfflicted |= NewReleaseRRI.CFGHazardAfflicted;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002678 for (SmallPtrSet<Instruction *, 2>::const_iterator
2679 LI = NewReleaseRRI.Calls.begin(),
2680 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
2681 Instruction *NewReleaseRetain = *LI;
2682 MapVector<Value *, RRInfo>::const_iterator Jt =
2683 Retains.find(NewReleaseRetain);
2684 if (Jt == Retains.end())
2685 return false;
2686 const RRInfo &NewReleaseRetainRRI = Jt->second;
2687 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
2688 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002689
2690 // If we overflow when we compute the path count, don't remove/move
2691 // anything.
2692 const BBState &NRRBBState = BBStates[NewReleaseRetain->getParent()];
2693 unsigned PathCount;
2694 if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
2695 return false;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002696 OldDelta += PathCount;
2697 OldCount += PathCount;
2698
Michael Gottesman9de6f962013-01-22 21:49:00 +00002699 // Collect the optimal insertion points.
2700 if (!KnownSafe)
2701 for (SmallPtrSet<Instruction *, 2>::const_iterator
2702 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
2703 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
2704 RI != RE; ++RI) {
2705 Instruction *RIP = *RI;
2706 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002707 // If we overflow when we compute the path count, don't
2708 // remove/move anything.
2709 const BBState &RIPBBState = BBStates[RIP->getParent()];
2710 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
2711 return false;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002712 NewDelta += PathCount;
2713 NewCount += PathCount;
2714 }
2715 }
2716 NewRetains.push_back(NewReleaseRetain);
2717 }
2718 }
2719 }
2720 NewReleases.clear();
2721 if (NewRetains.empty()) break;
2722 }
2723
Michael Gottesmana76143ee2013-05-13 23:49:42 +00002724 // If the pointer is known incremented in 1 direction and we do not have
2725 // MultipleOwners, we can safely remove the retain/releases. Otherwise we need
2726 // to be known safe in both directions.
2727 bool UnconditionallySafe = (KnownSafeTD && KnownSafeBU) ||
2728 ((KnownSafeTD || KnownSafeBU) && !MultipleOwners);
2729 if (UnconditionallySafe) {
Michael Gottesman9de6f962013-01-22 21:49:00 +00002730 RetainsToMove.ReverseInsertPts.clear();
2731 ReleasesToMove.ReverseInsertPts.clear();
2732 NewCount = 0;
2733 } else {
2734 // Determine whether the new insertion points we computed preserve the
2735 // balance of retain and release calls through the program.
2736 // TODO: If the fully aggressive solution isn't valid, try to find a
2737 // less aggressive solution which is.
2738 if (NewDelta != 0)
2739 return false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00002740
2741 // At this point, we are not going to remove any RR pairs, but we still are
2742 // able to move RR pairs. If one of our pointers is afflicted with
2743 // CFGHazards, we cannot perform such code motion so exit early.
2744 const bool WillPerformCodeMotion = RetainsToMove.ReverseInsertPts.size() ||
2745 ReleasesToMove.ReverseInsertPts.size();
2746 if (CFGHazardAfflicted && WillPerformCodeMotion)
2747 return false;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002748 }
2749
2750 // Determine whether the original call points are balanced in the retain and
2751 // release calls through the program. If not, conservatively don't touch
2752 // them.
2753 // TODO: It's theoretically possible to do code motion in this case, as
2754 // long as the existing imbalances are maintained.
2755 if (OldDelta != 0)
2756 return false;
Michael Gottesman8005ad32013-04-29 06:16:55 +00002757
Michael Gottesmana87bb8f2013-04-29 05:13:13 +00002758#ifdef ARC_ANNOTATIONS
2759 // Do not move calls if ARC annotations are requested.
Michael Gottesman3e3977c2013-04-29 05:25:39 +00002760 if (EnableARCAnnotations)
2761 return false;
Michael Gottesmana87bb8f2013-04-29 05:13:13 +00002762#endif // ARC_ANNOTATIONS
Michael Gottesman9de6f962013-01-22 21:49:00 +00002763
2764 Changed = true;
2765 assert(OldCount != 0 && "Unreachable code?");
2766 NumRRs += OldCount - NewCount;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002767 // Set to true if we completely removed any RR pairs.
Michael Gottesman8b5515f2013-01-22 21:53:43 +00002768 AnyPairsCompletelyEliminated = NewCount == 0;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002769
2770 // We can move calls!
2771 return true;
2772}
2773
Michael Gottesman97e3df02013-01-14 00:35:14 +00002774/// Identify pairings between the retains and releases, and delete and/or move
2775/// them.
John McCalld935e9c2011-06-15 23:37:01 +00002776bool
2777ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
2778 &BBStates,
2779 MapVector<Value *, RRInfo> &Retains,
Dan Gohman6320f522011-07-22 22:29:21 +00002780 DenseMap<Value *, RRInfo> &Releases,
2781 Module *M) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002782 DEBUG(dbgs() << "\n== ObjCARCOpt::PerformCodePlacement ==\n");
2783
John McCalld935e9c2011-06-15 23:37:01 +00002784 bool AnyPairsCompletelyEliminated = false;
2785 RRInfo RetainsToMove;
2786 RRInfo ReleasesToMove;
2787 SmallVector<Instruction *, 4> NewRetains;
2788 SmallVector<Instruction *, 4> NewReleases;
2789 SmallVector<Instruction *, 8> DeadInsts;
2790
Dan Gohman670f9372012-04-13 18:57:48 +00002791 // Visit each retain.
John McCalld935e9c2011-06-15 23:37:01 +00002792 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
Dan Gohman2053a5d2011-09-29 22:25:23 +00002793 E = Retains.end(); I != E; ++I) {
2794 Value *V = I->first;
John McCalld935e9c2011-06-15 23:37:01 +00002795 if (!V) continue; // blotted
2796
2797 Instruction *Retain = cast<Instruction>(V);
Michael Gottesmanc189a392013-01-09 19:23:24 +00002798
Michael Gottesman89279f82013-04-05 18:10:41 +00002799 DEBUG(dbgs() << "Visiting: " << *Retain << "\n");
Michael Gottesmanc189a392013-01-09 19:23:24 +00002800
John McCalld935e9c2011-06-15 23:37:01 +00002801 Value *Arg = GetObjCArg(Retain);
2802
Dan Gohman728db492012-01-13 00:39:07 +00002803 // If the object being released is in static or stack storage, we know it's
John McCalld935e9c2011-06-15 23:37:01 +00002804 // not being managed by ObjC reference counting, so we can delete pairs
2805 // regardless of what possible decrements or uses lie between them.
Dan Gohman728db492012-01-13 00:39:07 +00002806 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
Dan Gohman41375a32012-05-08 23:39:44 +00002807
Dan Gohman56e1cef2011-08-22 17:29:11 +00002808 // A constant pointer can't be pointing to an object on the heap. It may
2809 // be reference-counted, but it won't be deleted.
2810 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
2811 if (const GlobalVariable *GV =
2812 dyn_cast<GlobalVariable>(
2813 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
2814 if (GV->isConstant())
2815 KnownSafe = true;
2816
John McCalld935e9c2011-06-15 23:37:01 +00002817 // Connect the dots between the top-down-collected RetainsToMove and
2818 // bottom-up-collected ReleasesToMove to form sets of related calls.
John McCalld935e9c2011-06-15 23:37:01 +00002819 NewRetains.push_back(Retain);
Michael Gottesman9de6f962013-01-22 21:49:00 +00002820 bool PerformMoveCalls =
2821 ConnectTDBUTraversals(BBStates, Retains, Releases, M, NewRetains,
2822 NewReleases, DeadInsts, RetainsToMove,
2823 ReleasesToMove, Arg, KnownSafe,
2824 AnyPairsCompletelyEliminated);
John McCalld935e9c2011-06-15 23:37:01 +00002825
Michael Gottesman9de6f962013-01-22 21:49:00 +00002826 if (PerformMoveCalls) {
2827 // Ok, everything checks out and we're all set. Let's move/delete some
2828 // code!
2829 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
2830 Retains, Releases, DeadInsts, M);
John McCalld935e9c2011-06-15 23:37:01 +00002831 }
2832
Michael Gottesman9de6f962013-01-22 21:49:00 +00002833 // Clean up state for next retain.
John McCalld935e9c2011-06-15 23:37:01 +00002834 NewReleases.clear();
2835 NewRetains.clear();
2836 RetainsToMove.clear();
2837 ReleasesToMove.clear();
2838 }
2839
2840 // Now that we're done moving everything, we can delete the newly dead
2841 // instructions, as we no longer need them as insert points.
2842 while (!DeadInsts.empty())
2843 EraseInstruction(DeadInsts.pop_back_val());
2844
2845 return AnyPairsCompletelyEliminated;
2846}
2847
Michael Gottesman97e3df02013-01-14 00:35:14 +00002848/// Weak pointer optimizations.
John McCalld935e9c2011-06-15 23:37:01 +00002849void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002850 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeWeakCalls ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00002851
John McCalld935e9c2011-06-15 23:37:01 +00002852 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
2853 // itself because it uses AliasAnalysis and we need to do provenance
2854 // queries instead.
2855 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2856 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +00002857
Michael Gottesman89279f82013-04-05 18:10:41 +00002858 DEBUG(dbgs() << "Visiting: " << *Inst << "\n");
Michael Gottesman3f146e22013-01-01 16:05:48 +00002859
John McCalld935e9c2011-06-15 23:37:01 +00002860 InstructionClass Class = GetBasicInstructionClass(Inst);
2861 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
2862 continue;
2863
2864 // Delete objc_loadWeak calls with no users.
2865 if (Class == IC_LoadWeak && Inst->use_empty()) {
2866 Inst->eraseFromParent();
2867 continue;
2868 }
2869
2870 // TODO: For now, just look for an earlier available version of this value
2871 // within the same block. Theoretically, we could do memdep-style non-local
2872 // analysis too, but that would want caching. A better approach would be to
2873 // use the technique that EarlyCSE uses.
2874 inst_iterator Current = llvm::prior(I);
2875 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
2876 for (BasicBlock::iterator B = CurrentBB->begin(),
2877 J = Current.getInstructionIterator();
2878 J != B; --J) {
2879 Instruction *EarlierInst = &*llvm::prior(J);
2880 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
2881 switch (EarlierClass) {
2882 case IC_LoadWeak:
2883 case IC_LoadWeakRetained: {
2884 // If this is loading from the same pointer, replace this load's value
2885 // with that one.
2886 CallInst *Call = cast<CallInst>(Inst);
2887 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2888 Value *Arg = Call->getArgOperand(0);
2889 Value *EarlierArg = EarlierCall->getArgOperand(0);
2890 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2891 case AliasAnalysis::MustAlias:
2892 Changed = true;
2893 // If the load has a builtin retain, insert a plain retain for it.
2894 if (Class == IC_LoadWeakRetained) {
2895 CallInst *CI =
2896 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
2897 "", Call);
2898 CI->setTailCall();
2899 }
2900 // Zap the fully redundant load.
2901 Call->replaceAllUsesWith(EarlierCall);
2902 Call->eraseFromParent();
2903 goto clobbered;
2904 case AliasAnalysis::MayAlias:
2905 case AliasAnalysis::PartialAlias:
2906 goto clobbered;
2907 case AliasAnalysis::NoAlias:
2908 break;
2909 }
2910 break;
2911 }
2912 case IC_StoreWeak:
2913 case IC_InitWeak: {
2914 // If this is storing to the same pointer and has the same size etc.
2915 // replace this load's value with the stored value.
2916 CallInst *Call = cast<CallInst>(Inst);
2917 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2918 Value *Arg = Call->getArgOperand(0);
2919 Value *EarlierArg = EarlierCall->getArgOperand(0);
2920 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2921 case AliasAnalysis::MustAlias:
2922 Changed = true;
2923 // If the load has a builtin retain, insert a plain retain for it.
2924 if (Class == IC_LoadWeakRetained) {
2925 CallInst *CI =
2926 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
2927 "", Call);
2928 CI->setTailCall();
2929 }
2930 // Zap the fully redundant load.
2931 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
2932 Call->eraseFromParent();
2933 goto clobbered;
2934 case AliasAnalysis::MayAlias:
2935 case AliasAnalysis::PartialAlias:
2936 goto clobbered;
2937 case AliasAnalysis::NoAlias:
2938 break;
2939 }
2940 break;
2941 }
2942 case IC_MoveWeak:
2943 case IC_CopyWeak:
2944 // TOOD: Grab the copied value.
2945 goto clobbered;
2946 case IC_AutoreleasepoolPush:
2947 case IC_None:
John McCall20182ac2013-03-22 21:38:36 +00002948 case IC_IntrinsicUser:
John McCalld935e9c2011-06-15 23:37:01 +00002949 case IC_User:
2950 // Weak pointers are only modified through the weak entry points
2951 // (and arbitrary calls, which could call the weak entry points).
2952 break;
2953 default:
2954 // Anything else could modify the weak pointer.
2955 goto clobbered;
2956 }
2957 }
2958 clobbered:;
2959 }
2960
2961 // Then, for each destroyWeak with an alloca operand, check to see if
2962 // the alloca and all its users can be zapped.
2963 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2964 Instruction *Inst = &*I++;
2965 InstructionClass Class = GetBasicInstructionClass(Inst);
2966 if (Class != IC_DestroyWeak)
2967 continue;
2968
2969 CallInst *Call = cast<CallInst>(Inst);
2970 Value *Arg = Call->getArgOperand(0);
2971 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
2972 for (Value::use_iterator UI = Alloca->use_begin(),
2973 UE = Alloca->use_end(); UI != UE; ++UI) {
Dan Gohmandae33492012-04-27 18:56:31 +00002974 const Instruction *UserInst = cast<Instruction>(*UI);
John McCalld935e9c2011-06-15 23:37:01 +00002975 switch (GetBasicInstructionClass(UserInst)) {
2976 case IC_InitWeak:
2977 case IC_StoreWeak:
2978 case IC_DestroyWeak:
2979 continue;
2980 default:
2981 goto done;
2982 }
2983 }
2984 Changed = true;
2985 for (Value::use_iterator UI = Alloca->use_begin(),
2986 UE = Alloca->use_end(); UI != UE; ) {
2987 CallInst *UserInst = cast<CallInst>(*UI++);
Dan Gohman14862c32012-05-18 22:17:29 +00002988 switch (GetBasicInstructionClass(UserInst)) {
2989 case IC_InitWeak:
2990 case IC_StoreWeak:
2991 // These functions return their second argument.
2992 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
2993 break;
2994 case IC_DestroyWeak:
2995 // No return value.
2996 break;
2997 default:
Dan Gohman9c97eea02012-05-21 17:41:28 +00002998 llvm_unreachable("alloca really is used!");
Dan Gohman14862c32012-05-18 22:17:29 +00002999 }
John McCalld935e9c2011-06-15 23:37:01 +00003000 UserInst->eraseFromParent();
3001 }
3002 Alloca->eraseFromParent();
3003 done:;
3004 }
3005 }
3006}
3007
Michael Gottesman97e3df02013-01-14 00:35:14 +00003008/// Identify program paths which execute sequences of retains and releases which
3009/// can be eliminated.
John McCalld935e9c2011-06-15 23:37:01 +00003010bool ObjCARCOpt::OptimizeSequences(Function &F) {
Michael Gottesman740db972013-05-23 02:35:21 +00003011 // Releases, Retains - These are used to store the results of the main flow
3012 // analysis. These use Value* as the key instead of Instruction* so that the
3013 // map stays valid when we get around to rewriting code and calls get
3014 // replaced by arguments.
John McCalld935e9c2011-06-15 23:37:01 +00003015 DenseMap<Value *, RRInfo> Releases;
3016 MapVector<Value *, RRInfo> Retains;
3017
Michael Gottesman740db972013-05-23 02:35:21 +00003018 // This is used during the traversal of the function to track the
3019 // states for each identified object at each block.
John McCalld935e9c2011-06-15 23:37:01 +00003020 DenseMap<const BasicBlock *, BBState> BBStates;
3021
3022 // Analyze the CFG of the function, and all instructions.
3023 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
3024
3025 // Transform.
Michael Gottesman5a91bbf2013-05-24 20:44:02 +00003026 bool AnyPairsCompletelyEliminated = PerformCodePlacement(BBStates, Retains,
3027 Releases,
3028 F.getParent());
3029
3030 // Cleanup.
3031 MultiOwnersSet.clear();
3032
3033 return AnyPairsCompletelyEliminated && NestingDetected;
John McCalld935e9c2011-06-15 23:37:01 +00003034}
3035
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00003036/// Check if there is a dependent call earlier that does not have anything in
3037/// between the Retain and the call that can affect the reference count of their
3038/// shared pointer argument. Note that Retain need not be in BB.
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00003039static bool
3040HasSafePathToPredecessorCall(const Value *Arg, Instruction *Retain,
3041 SmallPtrSet<Instruction *, 4> &DepInsts,
3042 SmallPtrSet<const BasicBlock *, 4> &Visited,
3043 ProvenanceAnalysis &PA) {
3044 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
3045 DepInsts, Visited, PA);
3046 if (DepInsts.size() != 1)
3047 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00003048
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00003049 CallInst *Call =
3050 dyn_cast_or_null<CallInst>(*DepInsts.begin());
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00003051
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00003052 // Check that the pointer is the return value of the call.
3053 if (!Call || Arg != Call)
3054 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00003055
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00003056 // Check that the call is a regular call.
3057 InstructionClass Class = GetBasicInstructionClass(Call);
3058 if (Class != IC_CallOrUser && Class != IC_Call)
3059 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00003060
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00003061 return true;
3062}
3063
Michael Gottesman6908db12013-04-03 23:16:05 +00003064/// Find a dependent retain that precedes the given autorelease for which there
3065/// is nothing in between the two instructions that can affect the ref count of
3066/// Arg.
3067static CallInst *
3068FindPredecessorRetainWithSafePath(const Value *Arg, BasicBlock *BB,
3069 Instruction *Autorelease,
3070 SmallPtrSet<Instruction *, 4> &DepInsts,
3071 SmallPtrSet<const BasicBlock *, 4> &Visited,
3072 ProvenanceAnalysis &PA) {
3073 FindDependencies(CanChangeRetainCount, Arg,
3074 BB, Autorelease, DepInsts, Visited, PA);
3075 if (DepInsts.size() != 1)
3076 return 0;
Michael Gottesman79249972013-04-05 23:46:45 +00003077
Michael Gottesman6908db12013-04-03 23:16:05 +00003078 CallInst *Retain =
3079 dyn_cast_or_null<CallInst>(*DepInsts.begin());
Michael Gottesman79249972013-04-05 23:46:45 +00003080
Michael Gottesman6908db12013-04-03 23:16:05 +00003081 // Check that we found a retain with the same argument.
3082 if (!Retain ||
3083 !IsRetain(GetBasicInstructionClass(Retain)) ||
3084 GetObjCArg(Retain) != Arg) {
3085 return 0;
3086 }
Michael Gottesman79249972013-04-05 23:46:45 +00003087
Michael Gottesman6908db12013-04-03 23:16:05 +00003088 return Retain;
3089}
3090
Michael Gottesman21a4ed32013-04-03 23:39:14 +00003091/// Look for an ``autorelease'' instruction dependent on Arg such that there are
3092/// no instructions dependent on Arg that need a positive ref count in between
3093/// the autorelease and the ret.
3094static CallInst *
3095FindPredecessorAutoreleaseWithSafePath(const Value *Arg, BasicBlock *BB,
3096 ReturnInst *Ret,
3097 SmallPtrSet<Instruction *, 4> &DepInsts,
3098 SmallPtrSet<const BasicBlock *, 4> &V,
3099 ProvenanceAnalysis &PA) {
3100 FindDependencies(NeedsPositiveRetainCount, Arg,
3101 BB, Ret, DepInsts, V, PA);
3102 if (DepInsts.size() != 1)
3103 return 0;
Michael Gottesman79249972013-04-05 23:46:45 +00003104
Michael Gottesman21a4ed32013-04-03 23:39:14 +00003105 CallInst *Autorelease =
3106 dyn_cast_or_null<CallInst>(*DepInsts.begin());
3107 if (!Autorelease)
3108 return 0;
3109 InstructionClass AutoreleaseClass = GetBasicInstructionClass(Autorelease);
3110 if (!IsAutorelease(AutoreleaseClass))
3111 return 0;
3112 if (GetObjCArg(Autorelease) != Arg)
3113 return 0;
Michael Gottesman79249972013-04-05 23:46:45 +00003114
Michael Gottesman21a4ed32013-04-03 23:39:14 +00003115 return Autorelease;
3116}
3117
Michael Gottesman97e3df02013-01-14 00:35:14 +00003118/// Look for this pattern:
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00003119/// \code
John McCalld935e9c2011-06-15 23:37:01 +00003120/// %call = call i8* @something(...)
3121/// %2 = call i8* @objc_retain(i8* %call)
3122/// %3 = call i8* @objc_autorelease(i8* %2)
3123/// ret i8* %3
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00003124/// \endcode
John McCalld935e9c2011-06-15 23:37:01 +00003125/// And delete the retain and autorelease.
John McCalld935e9c2011-06-15 23:37:01 +00003126void ObjCARCOpt::OptimizeReturns(Function &F) {
3127 if (!F.getReturnType()->isPointerTy())
3128 return;
Michael Gottesman79249972013-04-05 23:46:45 +00003129
Michael Gottesman89279f82013-04-05 18:10:41 +00003130 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeReturns ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00003131
John McCalld935e9c2011-06-15 23:37:01 +00003132 SmallPtrSet<Instruction *, 4> DependingInstructions;
3133 SmallPtrSet<const BasicBlock *, 4> Visited;
3134 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3135 BasicBlock *BB = FI;
3136 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
Michael Gottesman3f146e22013-01-01 16:05:48 +00003137
Michael Gottesman89279f82013-04-05 18:10:41 +00003138 DEBUG(dbgs() << "Visiting: " << *Ret << "\n");
Michael Gottesman3f146e22013-01-01 16:05:48 +00003139
Michael Gottesman21a4ed32013-04-03 23:39:14 +00003140 if (!Ret)
3141 continue;
Michael Gottesman79249972013-04-05 23:46:45 +00003142
John McCalld935e9c2011-06-15 23:37:01 +00003143 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
Michael Gottesman79249972013-04-05 23:46:45 +00003144
Michael Gottesmancdb7c152013-04-21 00:25:04 +00003145 // Look for an ``autorelease'' instruction that is a predecessor of Ret and
Michael Gottesman21a4ed32013-04-03 23:39:14 +00003146 // dependent on Arg such that there are no instructions dependent on Arg
3147 // that need a positive ref count in between the autorelease and Ret.
3148 CallInst *Autorelease =
3149 FindPredecessorAutoreleaseWithSafePath(Arg, BB, Ret,
3150 DependingInstructions, Visited,
3151 PA);
John McCalld935e9c2011-06-15 23:37:01 +00003152 DependingInstructions.clear();
3153 Visited.clear();
Michael Gottesmanfb9ece92013-04-21 00:25:01 +00003154
3155 if (!Autorelease)
3156 continue;
3157
3158 CallInst *Retain =
3159 FindPredecessorRetainWithSafePath(Arg, BB, Autorelease,
3160 DependingInstructions, Visited, PA);
3161 DependingInstructions.clear();
3162 Visited.clear();
3163
3164 if (!Retain)
3165 continue;
3166
3167 // Check that there is nothing that can affect the reference count
3168 // between the retain and the call. Note that Retain need not be in BB.
3169 bool HasSafePathToCall = HasSafePathToPredecessorCall(Arg, Retain,
3170 DependingInstructions,
3171 Visited, PA);
3172 DependingInstructions.clear();
3173 Visited.clear();
3174
3175 if (!HasSafePathToCall)
3176 continue;
3177
3178 // If so, we can zap the retain and autorelease.
3179 Changed = true;
3180 ++NumRets;
3181 DEBUG(dbgs() << "Erasing: " << *Retain << "\nErasing: "
3182 << *Autorelease << "\n");
3183 EraseInstruction(Retain);
3184 EraseInstruction(Autorelease);
John McCalld935e9c2011-06-15 23:37:01 +00003185 }
3186}
3187
Michael Gottesman9c118152013-04-29 06:16:57 +00003188#ifndef NDEBUG
3189void
3190ObjCARCOpt::GatherStatistics(Function &F, bool AfterOptimization) {
3191 llvm::Statistic &NumRetains =
3192 AfterOptimization? NumRetainsAfterOpt : NumRetainsBeforeOpt;
3193 llvm::Statistic &NumReleases =
3194 AfterOptimization? NumReleasesAfterOpt : NumReleasesBeforeOpt;
3195
3196 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3197 Instruction *Inst = &*I++;
3198 switch (GetBasicInstructionClass(Inst)) {
3199 default:
3200 break;
3201 case IC_Retain:
3202 ++NumRetains;
3203 break;
3204 case IC_Release:
3205 ++NumReleases;
3206 break;
3207 }
3208 }
3209}
3210#endif
3211
John McCalld935e9c2011-06-15 23:37:01 +00003212bool ObjCARCOpt::doInitialization(Module &M) {
3213 if (!EnableARCOpts)
3214 return false;
3215
Dan Gohman670f9372012-04-13 18:57:48 +00003216 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanceaac7c2011-06-20 23:20:43 +00003217 Run = ModuleHasARC(M);
3218 if (!Run)
3219 return false;
3220
John McCalld935e9c2011-06-15 23:37:01 +00003221 // Identify the imprecise release metadata kind.
3222 ImpreciseReleaseMDKind =
3223 M.getContext().getMDKindID("clang.imprecise_release");
Dan Gohmana7107f92011-10-17 22:53:25 +00003224 CopyOnEscapeMDKind =
3225 M.getContext().getMDKindID("clang.arc.copy_on_escape");
Dan Gohman0155f302012-02-17 18:59:53 +00003226 NoObjCARCExceptionsMDKind =
3227 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
Michael Gottesman81b1d432013-03-26 00:42:04 +00003228#ifdef ARC_ANNOTATIONS
3229 ARCAnnotationBottomUpMDKind =
3230 M.getContext().getMDKindID("llvm.arc.annotation.bottomup");
3231 ARCAnnotationTopDownMDKind =
3232 M.getContext().getMDKindID("llvm.arc.annotation.topdown");
3233 ARCAnnotationProvenanceSourceMDKind =
3234 M.getContext().getMDKindID("llvm.arc.annotation.provenancesource");
3235#endif // ARC_ANNOTATIONS
John McCalld935e9c2011-06-15 23:37:01 +00003236
John McCalld935e9c2011-06-15 23:37:01 +00003237 // Intuitively, objc_retain and others are nocapture, however in practice
3238 // they are not, because they return their argument value. And objc_release
Dan Gohmandae33492012-04-27 18:56:31 +00003239 // calls finalizers which can have arbitrary side effects.
John McCalld935e9c2011-06-15 23:37:01 +00003240
3241 // These are initialized lazily.
John McCalld935e9c2011-06-15 23:37:01 +00003242 AutoreleaseRVCallee = 0;
3243 ReleaseCallee = 0;
3244 RetainCallee = 0;
Dan Gohman6320f522011-07-22 22:29:21 +00003245 RetainBlockCallee = 0;
John McCalld935e9c2011-06-15 23:37:01 +00003246 AutoreleaseCallee = 0;
3247
3248 return false;
3249}
3250
3251bool ObjCARCOpt::runOnFunction(Function &F) {
3252 if (!EnableARCOpts)
3253 return false;
3254
Dan Gohmanceaac7c2011-06-20 23:20:43 +00003255 // If nothing in the Module uses ARC, don't do anything.
3256 if (!Run)
3257 return false;
3258
John McCalld935e9c2011-06-15 23:37:01 +00003259 Changed = false;
3260
Michael Gottesman89279f82013-04-05 18:10:41 +00003261 DEBUG(dbgs() << "<<< ObjCARCOpt: Visiting Function: " << F.getName() << " >>>"
3262 "\n");
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00003263
John McCalld935e9c2011-06-15 23:37:01 +00003264 PA.setAA(&getAnalysis<AliasAnalysis>());
3265
Michael Gottesman9fc50b82013-05-13 18:29:07 +00003266#ifndef NDEBUG
3267 if (AreStatisticsEnabled()) {
3268 GatherStatistics(F, false);
3269 }
3270#endif
3271
John McCalld935e9c2011-06-15 23:37:01 +00003272 // This pass performs several distinct transformations. As a compile-time aid
3273 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3274 // library functions aren't declared.
3275
Michael Gottesmancd5b0272013-04-24 22:18:15 +00003276 // Preliminary optimizations. This also computes UsedInThisFunction.
John McCalld935e9c2011-06-15 23:37:01 +00003277 OptimizeIndividualCalls(F);
3278
3279 // Optimizations for weak pointers.
3280 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3281 (1 << IC_LoadWeakRetained) |
3282 (1 << IC_StoreWeak) |
3283 (1 << IC_InitWeak) |
3284 (1 << IC_CopyWeak) |
3285 (1 << IC_MoveWeak) |
3286 (1 << IC_DestroyWeak)))
3287 OptimizeWeakCalls(F);
3288
3289 // Optimizations for retain+release pairs.
3290 if (UsedInThisFunction & ((1 << IC_Retain) |
3291 (1 << IC_RetainRV) |
3292 (1 << IC_RetainBlock)))
3293 if (UsedInThisFunction & (1 << IC_Release))
3294 // Run OptimizeSequences until it either stops making changes or
3295 // no retain+release pair nesting is detected.
3296 while (OptimizeSequences(F)) {}
3297
3298 // Optimizations if objc_autorelease is used.
Dan Gohman41375a32012-05-08 23:39:44 +00003299 if (UsedInThisFunction & ((1 << IC_Autorelease) |
3300 (1 << IC_AutoreleaseRV)))
John McCalld935e9c2011-06-15 23:37:01 +00003301 OptimizeReturns(F);
3302
Michael Gottesman9c118152013-04-29 06:16:57 +00003303 // Gather statistics after optimization.
3304#ifndef NDEBUG
3305 if (AreStatisticsEnabled()) {
3306 GatherStatistics(F, true);
3307 }
3308#endif
3309
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00003310 DEBUG(dbgs() << "\n");
3311
John McCalld935e9c2011-06-15 23:37:01 +00003312 return Changed;
3313}
3314
3315void ObjCARCOpt::releaseMemory() {
3316 PA.clear();
3317}
3318
Michael Gottesman97e3df02013-01-14 00:35:14 +00003319/// @}
3320///