blob: e6cd1a7ca9c8c8253c0f285148529421219a77c1 [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
16/// redundant weak pointer operations, pattern-matching and replacement of
17/// low-level operations into higher-level operations, and numerous minor
18/// simplifications.
19///
20/// This file also defines a simple ARC-aware AliasAnalysis.
21///
22/// WARNING: This file knows about certain library functions. It recognizes them
23/// by name, and hardwires knowledge of their semantics.
24///
25/// WARNING: This file knows about how certain Objective-C library functions are
26/// used. Naive LLVM IR transformations which would otherwise be
27/// behavior-preserving may break these assumptions.
28///
John McCalld935e9c2011-06-15 23:37:01 +000029//===----------------------------------------------------------------------===//
30
Michael Gottesman08904e32013-01-28 03:28:38 +000031#define DEBUG_TYPE "objc-arc-opts"
32#include "ObjCARC.h"
Michael Gottesman278266f2013-01-29 04:20:52 +000033#include "DependencyAnalysis.h"
Michael Gottesman294e7da2013-01-28 05:51:54 +000034#include "ObjCARCAliasAnalysis.h"
Michael Gottesman778138e2013-01-29 03:03:03 +000035#include "ProvenanceAnalysis.h"
John McCalld935e9c2011-06-15 23:37:01 +000036#include "llvm/ADT/DenseMap.h"
Michael Gottesmanfa0939f2013-01-28 04:12:07 +000037#include "llvm/ADT/STLExtras.h"
Michael Gottesman778138e2013-01-29 03:03:03 +000038#include "llvm/ADT/SmallPtrSet.h"
Michael Gottesman278266f2013-01-29 04:20:52 +000039#include "llvm/ADT/Statistic.h"
40#include "llvm/IR/LLVMContext.h"
Michael Gottesman778138e2013-01-29 03:03:03 +000041#include "llvm/Support/CFG.h"
Michael Gottesman13a5f1a2013-01-29 04:51:59 +000042#include "llvm/Support/Debug.h"
Timur Iskhodzhanov5d7ff002013-01-29 09:09:27 +000043#include "llvm/Support/raw_ostream.h"
Michael Gottesmanfa0939f2013-01-28 04:12:07 +000044
John McCalld935e9c2011-06-15 23:37:01 +000045using namespace llvm;
Michael Gottesman08904e32013-01-28 03:28:38 +000046using namespace llvm::objcarc;
John McCalld935e9c2011-06-15 23:37:01 +000047
Michael Gottesman97e3df02013-01-14 00:35:14 +000048/// \defgroup MiscUtils Miscellaneous utilities that are not ARC specific.
49/// @{
John McCalld935e9c2011-06-15 23:37:01 +000050
51namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +000052 /// \brief An associative container with fast insertion-order (deterministic)
53 /// iteration over its elements. Plus the special blot operation.
John McCalld935e9c2011-06-15 23:37:01 +000054 template<class KeyT, class ValueT>
55 class MapVector {
Michael Gottesman97e3df02013-01-14 00:35:14 +000056 /// Map keys to indices in Vector.
John McCalld935e9c2011-06-15 23:37:01 +000057 typedef DenseMap<KeyT, size_t> MapTy;
58 MapTy Map;
59
John McCalld935e9c2011-06-15 23:37:01 +000060 typedef std::vector<std::pair<KeyT, ValueT> > VectorTy;
Michael Gottesman97e3df02013-01-14 00:35:14 +000061 /// Keys and values.
John McCalld935e9c2011-06-15 23:37:01 +000062 VectorTy Vector;
63
64 public:
65 typedef typename VectorTy::iterator iterator;
66 typedef typename VectorTy::const_iterator const_iterator;
67 iterator begin() { return Vector.begin(); }
68 iterator end() { return Vector.end(); }
69 const_iterator begin() const { return Vector.begin(); }
70 const_iterator end() const { return Vector.end(); }
71
72#ifdef XDEBUG
73 ~MapVector() {
74 assert(Vector.size() >= Map.size()); // May differ due to blotting.
75 for (typename MapTy::const_iterator I = Map.begin(), E = Map.end();
76 I != E; ++I) {
77 assert(I->second < Vector.size());
78 assert(Vector[I->second].first == I->first);
79 }
80 for (typename VectorTy::const_iterator I = Vector.begin(),
81 E = Vector.end(); I != E; ++I)
82 assert(!I->first ||
83 (Map.count(I->first) &&
84 Map[I->first] == size_t(I - Vector.begin())));
85 }
86#endif
87
Dan Gohman55b06742012-03-02 01:13:53 +000088 ValueT &operator[](const KeyT &Arg) {
John McCalld935e9c2011-06-15 23:37:01 +000089 std::pair<typename MapTy::iterator, bool> Pair =
90 Map.insert(std::make_pair(Arg, size_t(0)));
91 if (Pair.second) {
Dan Gohman55b06742012-03-02 01:13:53 +000092 size_t Num = Vector.size();
93 Pair.first->second = Num;
John McCalld935e9c2011-06-15 23:37:01 +000094 Vector.push_back(std::make_pair(Arg, ValueT()));
Dan Gohman55b06742012-03-02 01:13:53 +000095 return Vector[Num].second;
John McCalld935e9c2011-06-15 23:37:01 +000096 }
97 return Vector[Pair.first->second].second;
98 }
99
100 std::pair<iterator, bool>
101 insert(const std::pair<KeyT, ValueT> &InsertPair) {
102 std::pair<typename MapTy::iterator, bool> Pair =
103 Map.insert(std::make_pair(InsertPair.first, size_t(0)));
104 if (Pair.second) {
Dan Gohman55b06742012-03-02 01:13:53 +0000105 size_t Num = Vector.size();
106 Pair.first->second = Num;
John McCalld935e9c2011-06-15 23:37:01 +0000107 Vector.push_back(InsertPair);
Dan Gohman55b06742012-03-02 01:13:53 +0000108 return std::make_pair(Vector.begin() + Num, true);
John McCalld935e9c2011-06-15 23:37:01 +0000109 }
110 return std::make_pair(Vector.begin() + Pair.first->second, false);
111 }
112
Dan Gohman55b06742012-03-02 01:13:53 +0000113 const_iterator find(const KeyT &Key) const {
John McCalld935e9c2011-06-15 23:37:01 +0000114 typename MapTy::const_iterator It = Map.find(Key);
115 if (It == Map.end()) return Vector.end();
116 return Vector.begin() + It->second;
117 }
118
Michael Gottesman97e3df02013-01-14 00:35:14 +0000119 /// This is similar to erase, but instead of removing the element from the
120 /// vector, it just zeros out the key in the vector. This leaves iterators
121 /// intact, but clients must be prepared for zeroed-out keys when iterating.
Dan Gohman55b06742012-03-02 01:13:53 +0000122 void blot(const KeyT &Key) {
John McCalld935e9c2011-06-15 23:37:01 +0000123 typename MapTy::iterator It = Map.find(Key);
124 if (It == Map.end()) return;
125 Vector[It->second].first = KeyT();
126 Map.erase(It);
127 }
128
129 void clear() {
130 Map.clear();
131 Vector.clear();
132 }
133 };
134}
135
Michael Gottesman97e3df02013-01-14 00:35:14 +0000136/// @}
137///
138/// \defgroup ARCUtilities Utility declarations/definitions specific to ARC.
139/// @{
John McCalld935e9c2011-06-15 23:37:01 +0000140
Michael Gottesman97e3df02013-01-14 00:35:14 +0000141/// \brief This is similar to StripPointerCastsAndObjCCalls but it stops as soon
142/// as it finds a value with multiple uses.
John McCalld935e9c2011-06-15 23:37:01 +0000143static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
144 if (Arg->hasOneUse()) {
145 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
146 return FindSingleUseIdentifiedObject(BC->getOperand(0));
147 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
148 if (GEP->hasAllZeroIndices())
149 return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
150 if (IsForwarding(GetBasicInstructionClass(Arg)))
151 return FindSingleUseIdentifiedObject(
152 cast<CallInst>(Arg)->getArgOperand(0));
153 if (!IsObjCIdentifiedObject(Arg))
154 return 0;
155 return Arg;
156 }
157
Dan Gohman41375a32012-05-08 23:39:44 +0000158 // If we found an identifiable object but it has multiple uses, but they are
159 // trivial uses, we can still consider this to be a single-use value.
John McCalld935e9c2011-06-15 23:37:01 +0000160 if (IsObjCIdentifiedObject(Arg)) {
161 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
162 UI != UE; ++UI) {
163 const User *U = *UI;
164 if (!U->use_empty() || StripPointerCastsAndObjCCalls(U) != Arg)
165 return 0;
166 }
167
168 return Arg;
169 }
170
171 return 0;
172}
173
Michael Gottesman774d2c02013-01-29 21:00:52 +0000174/// \brief Test whether the given retainable object pointer escapes.
Michael Gottesman97e3df02013-01-14 00:35:14 +0000175///
176/// This differs from regular escape analysis in that a use as an
177/// argument to a call is not considered an escape.
178///
Michael Gottesman774d2c02013-01-29 21:00:52 +0000179static bool DoesRetainableObjPtrEscape(const User *Ptr) {
Michael Gottesman774d2c02013-01-29 21:00:52 +0000180 DEBUG(dbgs() << "DoesRetainableObjPtrEscape: Target: " << *Ptr << "\n");
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000181
Dan Gohman728db492012-01-13 00:39:07 +0000182 // Walk the def-use chains.
183 SmallVector<const Value *, 4> Worklist;
Michael Gottesman774d2c02013-01-29 21:00:52 +0000184 Worklist.push_back(Ptr);
185 // If Ptr has any operands add them as well.
Michael Gottesman23cda0c2013-01-29 21:07:53 +0000186 for (User::const_op_iterator I = Ptr->op_begin(), E = Ptr->op_end(); I != E;
187 ++I) {
Michael Gottesman774d2c02013-01-29 21:00:52 +0000188 Worklist.push_back(*I);
189 }
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000190
191 // Ensure we do not visit any value twice.
Michael Gottesman774d2c02013-01-29 21:00:52 +0000192 SmallPtrSet<const Value *, 8> VisitedSet;
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000193
Dan Gohman728db492012-01-13 00:39:07 +0000194 do {
195 const Value *V = Worklist.pop_back_val();
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000196
Michael Gottesman774d2c02013-01-29 21:00:52 +0000197 DEBUG(dbgs() << "DoesRetainableObjPtrEscape: Visiting: " << *V << "\n");
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000198
Dan Gohman728db492012-01-13 00:39:07 +0000199 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
200 UI != UE; ++UI) {
201 const User *UUser = *UI;
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000202
Michael Gottesman774d2c02013-01-29 21:00:52 +0000203 DEBUG(dbgs() << "DoesRetainableObjPtrEscape: User: " << *UUser << "\n");
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000204
Dan Gohman728db492012-01-13 00:39:07 +0000205 // Special - Use by a call (callee or argument) is not considered
206 // to be an escape.
Dan Gohmane1e352a2012-04-13 18:28:58 +0000207 switch (GetBasicInstructionClass(UUser)) {
208 case IC_StoreWeak:
209 case IC_InitWeak:
210 case IC_StoreStrong:
211 case IC_Autorelease:
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000212 case IC_AutoreleaseRV: {
Michael Gottesman23cda0c2013-01-29 21:07:53 +0000213 DEBUG(dbgs() << "DoesRetainableObjPtrEscape: User copies pointer "
214 "arguments. Pointer Escapes!\n");
Dan Gohmane1e352a2012-04-13 18:28:58 +0000215 // These special functions make copies of their pointer arguments.
216 return true;
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000217 }
Dan Gohmane1e352a2012-04-13 18:28:58 +0000218 case IC_User:
219 case IC_None:
220 // Use by an instruction which copies the value is an escape if the
221 // result is an escape.
222 if (isa<BitCastInst>(UUser) || isa<GetElementPtrInst>(UUser) ||
223 isa<PHINode>(UUser) || isa<SelectInst>(UUser)) {
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000224
Michael Gottesmane9145d32013-01-14 19:18:39 +0000225 if (!VisitedSet.insert(UUser)) {
Michael Gottesman23cda0c2013-01-29 21:07:53 +0000226 DEBUG(dbgs() << "DoesRetainableObjPtrEscape: User copies value. "
227 "Ptr escapes if result escapes. Adding to list.\n");
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000228 Worklist.push_back(UUser);
229 } else {
Michael Gottesman23cda0c2013-01-29 21:07:53 +0000230 DEBUG(dbgs() << "DoesRetainableObjPtrEscape: Already visited node."
231 "\n");
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000232 }
Dan Gohmane1e352a2012-04-13 18:28:58 +0000233 continue;
234 }
235 // Use by a load is not an escape.
236 if (isa<LoadInst>(UUser))
237 continue;
238 // Use by a store is not an escape if the use is the address.
239 if (const StoreInst *SI = dyn_cast<StoreInst>(UUser))
240 if (V != SI->getValueOperand())
241 continue;
242 break;
243 default:
244 // Regular calls and other stuff are not considered escapes.
Dan Gohman728db492012-01-13 00:39:07 +0000245 continue;
246 }
Dan Gohmaneb6e0152012-02-13 22:57:02 +0000247 // Otherwise, conservatively assume an escape.
Michael Gottesman23cda0c2013-01-29 21:07:53 +0000248 DEBUG(dbgs() << "DoesRetainableObjPtrEscape: Assuming ptr escapes.\n");
Dan Gohman728db492012-01-13 00:39:07 +0000249 return true;
250 }
251 } while (!Worklist.empty());
252
253 // No escapes found.
Michael Gottesman23cda0c2013-01-29 21:07:53 +0000254 DEBUG(dbgs() << "DoesRetainableObjPtrEscape: Ptr does not escape.\n");
Dan Gohman728db492012-01-13 00:39:07 +0000255 return false;
256}
257
Michael Gottesman97e3df02013-01-14 00:35:14 +0000258/// @}
259///
Michael Gottesman97e3df02013-01-14 00:35:14 +0000260/// \defgroup ARCOpt ARC Optimization.
261/// @{
John McCalld935e9c2011-06-15 23:37:01 +0000262
263// TODO: On code like this:
264//
265// objc_retain(%x)
266// stuff_that_cannot_release()
267// objc_autorelease(%x)
268// stuff_that_cannot_release()
269// objc_retain(%x)
270// stuff_that_cannot_release()
271// objc_autorelease(%x)
272//
273// The second retain and autorelease can be deleted.
274
275// TODO: It should be possible to delete
276// objc_autoreleasePoolPush and objc_autoreleasePoolPop
277// pairs if nothing is actually autoreleased between them. Also, autorelease
278// calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
279// after inlining) can be turned into plain release calls.
280
281// TODO: Critical-edge splitting. If the optimial insertion point is
282// a critical edge, the current algorithm has to fail, because it doesn't
283// know how to split edges. It should be possible to make the optimizer
284// think in terms of edges, rather than blocks, and then split critical
285// edges on demand.
286
287// TODO: OptimizeSequences could generalized to be Interprocedural.
288
289// TODO: Recognize that a bunch of other objc runtime calls have
290// non-escaping arguments and non-releasing arguments, and may be
291// non-autoreleasing.
292
293// TODO: Sink autorelease calls as far as possible. Unfortunately we
294// usually can't sink them past other calls, which would be the main
295// case where it would be useful.
296
Dan Gohmanb3894012011-08-19 00:26:36 +0000297// TODO: The pointer returned from objc_loadWeakRetained is retained.
298
299// TODO: Delete release+retain pairs (rare).
Dan Gohmanceaac7c2011-06-20 23:20:43 +0000300
John McCalld935e9c2011-06-15 23:37:01 +0000301STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
302STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
303STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
304STATISTIC(NumRets, "Number of return value forwarding "
305 "retain+autoreleaes eliminated");
306STATISTIC(NumRRs, "Number of retain+release paths eliminated");
307STATISTIC(NumPeeps, "Number of calls peephole-optimized");
308
309namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000310 /// \enum Sequence
311 ///
312 /// \brief A sequence of states that a pointer may go through in which an
313 /// objc_retain and objc_release are actually needed.
John McCalld935e9c2011-06-15 23:37:01 +0000314 enum Sequence {
315 S_None,
Michael Gottesman53fd20b2013-01-29 21:07:51 +0000316 S_Retain, ///< objc_retain(x).
317 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement.
318 S_Use, ///< any use of x.
Michael Gottesman386241c2013-01-29 21:39:02 +0000319 S_Stop, ///< like S_Release, but code motion is stopped.
Michael Gottesman53fd20b2013-01-29 21:07:51 +0000320 S_Release, ///< objc_release(x).
Michael Gottesman9bdab2b2013-01-29 21:41:44 +0000321 S_MovableRelease ///< objc_release(x), !clang.imprecise_release.
John McCalld935e9c2011-06-15 23:37:01 +0000322 };
Michael Gottesman53fd20b2013-01-29 21:07:51 +0000323
324 raw_ostream &operator<<(raw_ostream &OS, const Sequence S)
325 LLVM_ATTRIBUTE_UNUSED;
326 raw_ostream &operator<<(raw_ostream &OS, const Sequence S) {
327 switch (S) {
328 case S_None:
329 return OS << "S_None";
330 case S_Retain:
331 return OS << "S_Retain";
332 case S_CanRelease:
333 return OS << "S_CanRelease";
334 case S_Use:
335 return OS << "S_Use";
336 case S_Release:
337 return OS << "S_Release";
338 case S_MovableRelease:
339 return OS << "S_MovableRelease";
340 case S_Stop:
341 return OS << "S_Stop";
342 }
343 llvm_unreachable("Unknown sequence type.");
344 }
John McCalld935e9c2011-06-15 23:37:01 +0000345}
346
347static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
348 // The easy cases.
349 if (A == B)
350 return A;
351 if (A == S_None || B == S_None)
352 return S_None;
353
John McCalld935e9c2011-06-15 23:37:01 +0000354 if (A > B) std::swap(A, B);
355 if (TopDown) {
356 // Choose the side which is further along in the sequence.
Dan Gohman12130272011-08-12 00:26:31 +0000357 if ((A == S_Retain || A == S_CanRelease) &&
358 (B == S_CanRelease || B == S_Use))
John McCalld935e9c2011-06-15 23:37:01 +0000359 return B;
360 } else {
361 // Choose the side which is further along in the sequence.
362 if ((A == S_Use || A == S_CanRelease) &&
Dan Gohman12130272011-08-12 00:26:31 +0000363 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
John McCalld935e9c2011-06-15 23:37:01 +0000364 return A;
365 // If both sides are releases, choose the more conservative one.
366 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
367 return A;
368 if (A == S_Release && B == S_MovableRelease)
369 return A;
370 }
371
372 return S_None;
373}
374
375namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000376 /// \brief Unidirectional information about either a
John McCalld935e9c2011-06-15 23:37:01 +0000377 /// retain-decrement-use-release sequence or release-use-decrement-retain
378 /// reverese sequence.
379 struct RRInfo {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000380 /// After an objc_retain, the reference count of the referenced
Dan Gohmanb3894012011-08-19 00:26:36 +0000381 /// object is known to be positive. Similarly, before an objc_release, the
382 /// reference count of the referenced object is known to be positive. If
383 /// there are retain-release pairs in code regions where the retain count
384 /// is known to be positive, they can be eliminated, regardless of any side
385 /// effects between them.
386 ///
387 /// Also, a retain+release pair nested within another retain+release
388 /// pair all on the known same pointer value can be eliminated, regardless
389 /// of any intervening side effects.
390 ///
391 /// KnownSafe is true when either of these conditions is satisfied.
392 bool KnownSafe;
John McCalld935e9c2011-06-15 23:37:01 +0000393
Michael Gottesman97e3df02013-01-14 00:35:14 +0000394 /// True if the Calls are objc_retainBlock calls (as opposed to objc_retain
395 /// calls).
John McCalld935e9c2011-06-15 23:37:01 +0000396 bool IsRetainBlock;
397
Michael Gottesman97e3df02013-01-14 00:35:14 +0000398 /// True of the objc_release calls are all marked with the "tail" keyword.
John McCalld935e9c2011-06-15 23:37:01 +0000399 bool IsTailCallRelease;
400
Michael Gottesman97e3df02013-01-14 00:35:14 +0000401 /// If the Calls are objc_release calls and they all have a
402 /// clang.imprecise_release tag, this is the metadata tag.
John McCalld935e9c2011-06-15 23:37:01 +0000403 MDNode *ReleaseMetadata;
404
Michael Gottesman97e3df02013-01-14 00:35:14 +0000405 /// For a top-down sequence, the set of objc_retains or
John McCalld935e9c2011-06-15 23:37:01 +0000406 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
407 SmallPtrSet<Instruction *, 2> Calls;
408
Michael Gottesman97e3df02013-01-14 00:35:14 +0000409 /// The set of optimal insert positions for moving calls in the opposite
410 /// sequence.
John McCalld935e9c2011-06-15 23:37:01 +0000411 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
412
413 RRInfo() :
Dan Gohman728db492012-01-13 00:39:07 +0000414 KnownSafe(false), IsRetainBlock(false),
Dan Gohman62079b42012-04-25 00:50:46 +0000415 IsTailCallRelease(false),
John McCalld935e9c2011-06-15 23:37:01 +0000416 ReleaseMetadata(0) {}
417
418 void clear();
419 };
420}
421
422void RRInfo::clear() {
Dan Gohmanb3894012011-08-19 00:26:36 +0000423 KnownSafe = false;
John McCalld935e9c2011-06-15 23:37:01 +0000424 IsRetainBlock = false;
425 IsTailCallRelease = false;
426 ReleaseMetadata = 0;
427 Calls.clear();
428 ReverseInsertPts.clear();
429}
430
431namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000432 /// \brief This class summarizes several per-pointer runtime properties which
433 /// are propogated through the flow graph.
John McCalld935e9c2011-06-15 23:37:01 +0000434 class PtrState {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000435 /// True if the reference count is known to be incremented.
Dan Gohman62079b42012-04-25 00:50:46 +0000436 bool KnownPositiveRefCount;
437
Michael Gottesman97e3df02013-01-14 00:35:14 +0000438 /// True of we've seen an opportunity for partial RR elimination, such as
439 /// pushing calls into a CFG triangle or into one side of a CFG diamond.
Dan Gohman62079b42012-04-25 00:50:46 +0000440 bool Partial;
John McCalld935e9c2011-06-15 23:37:01 +0000441
Michael Gottesman97e3df02013-01-14 00:35:14 +0000442 /// The current position in the sequence.
Dan Gohman41375a32012-05-08 23:39:44 +0000443 Sequence Seq : 8;
John McCalld935e9c2011-06-15 23:37:01 +0000444
445 public:
Michael Gottesman97e3df02013-01-14 00:35:14 +0000446 /// Unidirectional information about the current sequence.
447 ///
John McCalld935e9c2011-06-15 23:37:01 +0000448 /// TODO: Encapsulate this better.
449 RRInfo RRI;
450
Dan Gohmandf476e52012-09-04 23:16:20 +0000451 PtrState() : KnownPositiveRefCount(false), Partial(false),
Dan Gohman41375a32012-05-08 23:39:44 +0000452 Seq(S_None) {}
John McCalld935e9c2011-06-15 23:37:01 +0000453
Michael Gottesman415ddd72013-02-05 19:32:18 +0000454 void SetKnownPositiveRefCount() {
Dan Gohman62079b42012-04-25 00:50:46 +0000455 KnownPositiveRefCount = true;
Dan Gohman12130272011-08-12 00:26:31 +0000456 }
457
Michael Gottesman415ddd72013-02-05 19:32:18 +0000458 void ClearRefCount() {
Dan Gohman62079b42012-04-25 00:50:46 +0000459 KnownPositiveRefCount = false;
John McCalld935e9c2011-06-15 23:37:01 +0000460 }
461
Michael Gottesman415ddd72013-02-05 19:32:18 +0000462 bool IsKnownIncremented() const {
Dan Gohman62079b42012-04-25 00:50:46 +0000463 return KnownPositiveRefCount;
John McCalld935e9c2011-06-15 23:37:01 +0000464 }
465
Michael Gottesman415ddd72013-02-05 19:32:18 +0000466 void SetSeq(Sequence NewSeq) {
John McCalld935e9c2011-06-15 23:37:01 +0000467 Seq = NewSeq;
468 }
469
Michael Gottesman415ddd72013-02-05 19:32:18 +0000470 Sequence GetSeq() const {
John McCalld935e9c2011-06-15 23:37:01 +0000471 return Seq;
472 }
473
Michael Gottesman415ddd72013-02-05 19:32:18 +0000474 void ClearSequenceProgress() {
Dan Gohman62079b42012-04-25 00:50:46 +0000475 ResetSequenceProgress(S_None);
476 }
477
Michael Gottesman415ddd72013-02-05 19:32:18 +0000478 void ResetSequenceProgress(Sequence NewSeq) {
Dan Gohman62079b42012-04-25 00:50:46 +0000479 Seq = NewSeq;
480 Partial = false;
John McCalld935e9c2011-06-15 23:37:01 +0000481 RRI.clear();
482 }
483
484 void Merge(const PtrState &Other, bool TopDown);
485 };
486}
487
488void
489PtrState::Merge(const PtrState &Other, bool TopDown) {
490 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
Dan Gohman62079b42012-04-25 00:50:46 +0000491 KnownPositiveRefCount = KnownPositiveRefCount && Other.KnownPositiveRefCount;
John McCalld935e9c2011-06-15 23:37:01 +0000492
493 // We can't merge a plain objc_retain with an objc_retainBlock.
494 if (RRI.IsRetainBlock != Other.RRI.IsRetainBlock)
495 Seq = S_None;
496
Dan Gohman1736c142011-10-17 18:48:25 +0000497 // If we're not in a sequence (anymore), drop all associated state.
John McCalld935e9c2011-06-15 23:37:01 +0000498 if (Seq == S_None) {
Dan Gohman62079b42012-04-25 00:50:46 +0000499 Partial = false;
John McCalld935e9c2011-06-15 23:37:01 +0000500 RRI.clear();
Dan Gohman62079b42012-04-25 00:50:46 +0000501 } else if (Partial || Other.Partial) {
Dan Gohman1736c142011-10-17 18:48:25 +0000502 // If we're doing a merge on a path that's previously seen a partial
503 // merge, conservatively drop the sequence, to avoid doing partial
504 // RR elimination. If the branch predicates for the two merge differ,
505 // mixing them is unsafe.
Dan Gohman62079b42012-04-25 00:50:46 +0000506 ClearSequenceProgress();
John McCalld935e9c2011-06-15 23:37:01 +0000507 } else {
508 // Conservatively merge the ReleaseMetadata information.
509 if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
510 RRI.ReleaseMetadata = 0;
511
Dan Gohmanb3894012011-08-19 00:26:36 +0000512 RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
Dan Gohman41375a32012-05-08 23:39:44 +0000513 RRI.IsTailCallRelease = RRI.IsTailCallRelease &&
514 Other.RRI.IsTailCallRelease;
John McCalld935e9c2011-06-15 23:37:01 +0000515 RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
Dan Gohman1736c142011-10-17 18:48:25 +0000516
517 // Merge the insert point sets. If there are any differences,
518 // that makes this a partial merge.
Dan Gohman41375a32012-05-08 23:39:44 +0000519 Partial = RRI.ReverseInsertPts.size() != Other.RRI.ReverseInsertPts.size();
Dan Gohman1736c142011-10-17 18:48:25 +0000520 for (SmallPtrSet<Instruction *, 2>::const_iterator
521 I = Other.RRI.ReverseInsertPts.begin(),
522 E = Other.RRI.ReverseInsertPts.end(); I != E; ++I)
Dan Gohman62079b42012-04-25 00:50:46 +0000523 Partial |= RRI.ReverseInsertPts.insert(*I);
John McCalld935e9c2011-06-15 23:37:01 +0000524 }
525}
526
527namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000528 /// \brief Per-BasicBlock state.
John McCalld935e9c2011-06-15 23:37:01 +0000529 class BBState {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000530 /// The number of unique control paths from the entry which can reach this
531 /// block.
John McCalld935e9c2011-06-15 23:37:01 +0000532 unsigned TopDownPathCount;
533
Michael Gottesman97e3df02013-01-14 00:35:14 +0000534 /// The number of unique control paths to exits from this block.
John McCalld935e9c2011-06-15 23:37:01 +0000535 unsigned BottomUpPathCount;
536
Michael Gottesman97e3df02013-01-14 00:35:14 +0000537 /// A type for PerPtrTopDown and PerPtrBottomUp.
John McCalld935e9c2011-06-15 23:37:01 +0000538 typedef MapVector<const Value *, PtrState> MapTy;
539
Michael Gottesman97e3df02013-01-14 00:35:14 +0000540 /// The top-down traversal uses this to record information known about a
541 /// pointer at the bottom of each block.
John McCalld935e9c2011-06-15 23:37:01 +0000542 MapTy PerPtrTopDown;
543
Michael Gottesman97e3df02013-01-14 00:35:14 +0000544 /// The bottom-up traversal uses this to record information known about a
545 /// pointer at the top of each block.
John McCalld935e9c2011-06-15 23:37:01 +0000546 MapTy PerPtrBottomUp;
547
Michael Gottesman97e3df02013-01-14 00:35:14 +0000548 /// Effective predecessors of the current block ignoring ignorable edges and
549 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000550 SmallVector<BasicBlock *, 2> Preds;
Michael Gottesman97e3df02013-01-14 00:35:14 +0000551 /// Effective successors of the current block ignoring ignorable edges and
552 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000553 SmallVector<BasicBlock *, 2> Succs;
554
John McCalld935e9c2011-06-15 23:37:01 +0000555 public:
556 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
557
558 typedef MapTy::iterator ptr_iterator;
559 typedef MapTy::const_iterator ptr_const_iterator;
560
561 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
562 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
563 ptr_const_iterator top_down_ptr_begin() const {
564 return PerPtrTopDown.begin();
565 }
566 ptr_const_iterator top_down_ptr_end() const {
567 return PerPtrTopDown.end();
568 }
569
570 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
571 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
572 ptr_const_iterator bottom_up_ptr_begin() const {
573 return PerPtrBottomUp.begin();
574 }
575 ptr_const_iterator bottom_up_ptr_end() const {
576 return PerPtrBottomUp.end();
577 }
578
Michael Gottesman97e3df02013-01-14 00:35:14 +0000579 /// Mark this block as being an entry block, which has one path from the
580 /// entry by definition.
John McCalld935e9c2011-06-15 23:37:01 +0000581 void SetAsEntry() { TopDownPathCount = 1; }
582
Michael Gottesman97e3df02013-01-14 00:35:14 +0000583 /// Mark this block as being an exit block, which has one path to an exit by
584 /// definition.
John McCalld935e9c2011-06-15 23:37:01 +0000585 void SetAsExit() { BottomUpPathCount = 1; }
586
587 PtrState &getPtrTopDownState(const Value *Arg) {
588 return PerPtrTopDown[Arg];
589 }
590
591 PtrState &getPtrBottomUpState(const Value *Arg) {
592 return PerPtrBottomUp[Arg];
593 }
594
595 void clearBottomUpPointers() {
Evan Chenge4df6a22011-08-04 18:40:26 +0000596 PerPtrBottomUp.clear();
John McCalld935e9c2011-06-15 23:37:01 +0000597 }
598
599 void clearTopDownPointers() {
600 PerPtrTopDown.clear();
601 }
602
603 void InitFromPred(const BBState &Other);
604 void InitFromSucc(const BBState &Other);
605 void MergePred(const BBState &Other);
606 void MergeSucc(const BBState &Other);
607
Michael Gottesman97e3df02013-01-14 00:35:14 +0000608 /// Return the number of possible unique paths from an entry to an exit
609 /// which pass through this block. This is only valid after both the
610 /// top-down and bottom-up traversals are complete.
John McCalld935e9c2011-06-15 23:37:01 +0000611 unsigned GetAllPathCount() const {
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000612 assert(TopDownPathCount != 0);
613 assert(BottomUpPathCount != 0);
John McCalld935e9c2011-06-15 23:37:01 +0000614 return TopDownPathCount * BottomUpPathCount;
615 }
Dan Gohman12130272011-08-12 00:26:31 +0000616
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000617 // Specialized CFG utilities.
Dan Gohmandae33492012-04-27 18:56:31 +0000618 typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000619 edge_iterator pred_begin() { return Preds.begin(); }
620 edge_iterator pred_end() { return Preds.end(); }
621 edge_iterator succ_begin() { return Succs.begin(); }
622 edge_iterator succ_end() { return Succs.end(); }
623
624 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
625 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
626
627 bool isExit() const { return Succs.empty(); }
John McCalld935e9c2011-06-15 23:37:01 +0000628 };
629}
630
631void BBState::InitFromPred(const BBState &Other) {
632 PerPtrTopDown = Other.PerPtrTopDown;
633 TopDownPathCount = Other.TopDownPathCount;
634}
635
636void BBState::InitFromSucc(const BBState &Other) {
637 PerPtrBottomUp = Other.PerPtrBottomUp;
638 BottomUpPathCount = Other.BottomUpPathCount;
639}
640
Michael Gottesman97e3df02013-01-14 00:35:14 +0000641/// The top-down traversal uses this to merge information about predecessors to
642/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +0000643void BBState::MergePred(const BBState &Other) {
644 // Other.TopDownPathCount can be 0, in which case it is either dead or a
645 // loop backedge. Loop backedges are special.
646 TopDownPathCount += Other.TopDownPathCount;
647
Michael Gottesman4385edf2013-01-14 01:47:53 +0000648 // Check for overflow. If we have overflow, fall back to conservative
649 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +0000650 if (TopDownPathCount < Other.TopDownPathCount) {
651 clearTopDownPointers();
652 return;
653 }
654
John McCalld935e9c2011-06-15 23:37:01 +0000655 // For each entry in the other set, if our set has an entry with the same key,
656 // merge the entries. Otherwise, copy the entry and merge it with an empty
657 // entry.
658 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
659 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
660 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
661 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
662 /*TopDown=*/true);
663 }
664
Dan Gohman7e315fc32011-08-11 21:06:32 +0000665 // For each entry in our set, if the other set doesn't have an entry with the
John McCalld935e9c2011-06-15 23:37:01 +0000666 // same key, force it to merge with an empty entry.
667 for (ptr_iterator MI = top_down_ptr_begin(),
668 ME = top_down_ptr_end(); MI != ME; ++MI)
669 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
670 MI->second.Merge(PtrState(), /*TopDown=*/true);
671}
672
Michael Gottesman97e3df02013-01-14 00:35:14 +0000673/// The bottom-up traversal uses this to merge information about successors to
674/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +0000675void BBState::MergeSucc(const BBState &Other) {
676 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
677 // loop backedge. Loop backedges are special.
678 BottomUpPathCount += Other.BottomUpPathCount;
679
Michael Gottesman4385edf2013-01-14 01:47:53 +0000680 // Check for overflow. If we have overflow, fall back to conservative
681 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +0000682 if (BottomUpPathCount < Other.BottomUpPathCount) {
683 clearBottomUpPointers();
684 return;
685 }
686
John McCalld935e9c2011-06-15 23:37:01 +0000687 // For each entry in the other set, if our set has an entry with the
688 // same key, merge the entries. Otherwise, copy the entry and merge
689 // it with an empty entry.
690 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
691 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
692 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
693 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
694 /*TopDown=*/false);
695 }
696
Dan Gohman7e315fc32011-08-11 21:06:32 +0000697 // For each entry in our set, if the other set doesn't have an entry
John McCalld935e9c2011-06-15 23:37:01 +0000698 // with the same key, force it to merge with an empty entry.
699 for (ptr_iterator MI = bottom_up_ptr_begin(),
700 ME = bottom_up_ptr_end(); MI != ME; ++MI)
701 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
702 MI->second.Merge(PtrState(), /*TopDown=*/false);
703}
704
705namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000706 /// \brief The main ARC optimization pass.
John McCalld935e9c2011-06-15 23:37:01 +0000707 class ObjCARCOpt : public FunctionPass {
708 bool Changed;
709 ProvenanceAnalysis PA;
710
Michael Gottesman97e3df02013-01-14 00:35:14 +0000711 /// A flag indicating whether this optimization pass should run.
Dan Gohmanceaac7c2011-06-20 23:20:43 +0000712 bool Run;
713
Michael Gottesman97e3df02013-01-14 00:35:14 +0000714 /// Declarations for ObjC runtime functions, for use in creating calls to
715 /// them. These are initialized lazily to avoid cluttering up the Module
716 /// with unused declarations.
John McCalld935e9c2011-06-15 23:37:01 +0000717
Michael Gottesman97e3df02013-01-14 00:35:14 +0000718 /// Declaration for ObjC runtime function
719 /// objc_retainAutoreleasedReturnValue.
720 Constant *RetainRVCallee;
721 /// Declaration for ObjC runtime function objc_autoreleaseReturnValue.
722 Constant *AutoreleaseRVCallee;
723 /// Declaration for ObjC runtime function objc_release.
724 Constant *ReleaseCallee;
725 /// Declaration for ObjC runtime function objc_retain.
726 Constant *RetainCallee;
727 /// Declaration for ObjC runtime function objc_retainBlock.
728 Constant *RetainBlockCallee;
729 /// Declaration for ObjC runtime function objc_autorelease.
730 Constant *AutoreleaseCallee;
731
732 /// Flags which determine whether each of the interesting runtine functions
733 /// is in fact used in the current function.
John McCalld935e9c2011-06-15 23:37:01 +0000734 unsigned UsedInThisFunction;
735
Michael Gottesman97e3df02013-01-14 00:35:14 +0000736 /// The Metadata Kind for clang.imprecise_release metadata.
John McCalld935e9c2011-06-15 23:37:01 +0000737 unsigned ImpreciseReleaseMDKind;
738
Michael Gottesman97e3df02013-01-14 00:35:14 +0000739 /// The Metadata Kind for clang.arc.copy_on_escape metadata.
Dan Gohmana7107f92011-10-17 22:53:25 +0000740 unsigned CopyOnEscapeMDKind;
741
Michael Gottesman97e3df02013-01-14 00:35:14 +0000742 /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata.
Dan Gohman0155f302012-02-17 18:59:53 +0000743 unsigned NoObjCARCExceptionsMDKind;
744
John McCalld935e9c2011-06-15 23:37:01 +0000745 Constant *getRetainRVCallee(Module *M);
746 Constant *getAutoreleaseRVCallee(Module *M);
747 Constant *getReleaseCallee(Module *M);
748 Constant *getRetainCallee(Module *M);
Dan Gohman6320f522011-07-22 22:29:21 +0000749 Constant *getRetainBlockCallee(Module *M);
John McCalld935e9c2011-06-15 23:37:01 +0000750 Constant *getAutoreleaseCallee(Module *M);
751
Dan Gohman728db492012-01-13 00:39:07 +0000752 bool IsRetainBlockOptimizable(const Instruction *Inst);
753
John McCalld935e9c2011-06-15 23:37:01 +0000754 void OptimizeRetainCall(Function &F, Instruction *Retain);
755 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
Michael Gottesman556ff612013-01-12 01:25:19 +0000756 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
757 InstructionClass &Class);
John McCalld935e9c2011-06-15 23:37:01 +0000758 void OptimizeIndividualCalls(Function &F);
759
760 void CheckForCFGHazards(const BasicBlock *BB,
761 DenseMap<const BasicBlock *, BBState> &BBStates,
762 BBState &MyStates) const;
Dan Gohman817a7c62012-03-22 18:24:56 +0000763 bool VisitInstructionBottomUp(Instruction *Inst,
Dan Gohman5c70fad2012-03-23 17:47:54 +0000764 BasicBlock *BB,
Dan Gohman817a7c62012-03-22 18:24:56 +0000765 MapVector<Value *, RRInfo> &Retains,
766 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +0000767 bool VisitBottomUp(BasicBlock *BB,
768 DenseMap<const BasicBlock *, BBState> &BBStates,
769 MapVector<Value *, RRInfo> &Retains);
Dan Gohman817a7c62012-03-22 18:24:56 +0000770 bool VisitInstructionTopDown(Instruction *Inst,
771 DenseMap<Value *, RRInfo> &Releases,
772 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +0000773 bool VisitTopDown(BasicBlock *BB,
774 DenseMap<const BasicBlock *, BBState> &BBStates,
775 DenseMap<Value *, RRInfo> &Releases);
776 bool Visit(Function &F,
777 DenseMap<const BasicBlock *, BBState> &BBStates,
778 MapVector<Value *, RRInfo> &Retains,
779 DenseMap<Value *, RRInfo> &Releases);
780
781 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
782 MapVector<Value *, RRInfo> &Retains,
783 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman6320f522011-07-22 22:29:21 +0000784 SmallVectorImpl<Instruction *> &DeadInsts,
785 Module *M);
John McCalld935e9c2011-06-15 23:37:01 +0000786
Michael Gottesman9de6f962013-01-22 21:49:00 +0000787 bool ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState> &BBStates,
788 MapVector<Value *, RRInfo> &Retains,
789 DenseMap<Value *, RRInfo> &Releases,
790 Module *M,
791 SmallVector<Instruction *, 4> &NewRetains,
792 SmallVector<Instruction *, 4> &NewReleases,
793 SmallVector<Instruction *, 8> &DeadInsts,
794 RRInfo &RetainsToMove,
795 RRInfo &ReleasesToMove,
796 Value *Arg,
797 bool KnownSafe,
798 bool &AnyPairsCompletelyEliminated);
799
John McCalld935e9c2011-06-15 23:37:01 +0000800 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
801 MapVector<Value *, RRInfo> &Retains,
Dan Gohman6320f522011-07-22 22:29:21 +0000802 DenseMap<Value *, RRInfo> &Releases,
803 Module *M);
John McCalld935e9c2011-06-15 23:37:01 +0000804
805 void OptimizeWeakCalls(Function &F);
806
807 bool OptimizeSequences(Function &F);
808
809 void OptimizeReturns(Function &F);
810
811 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
812 virtual bool doInitialization(Module &M);
813 virtual bool runOnFunction(Function &F);
814 virtual void releaseMemory();
815
816 public:
817 static char ID;
818 ObjCARCOpt() : FunctionPass(ID) {
819 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
820 }
821 };
822}
823
824char ObjCARCOpt::ID = 0;
825INITIALIZE_PASS_BEGIN(ObjCARCOpt,
826 "objc-arc", "ObjC ARC optimization", false, false)
827INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
828INITIALIZE_PASS_END(ObjCARCOpt,
829 "objc-arc", "ObjC ARC optimization", false, false)
830
831Pass *llvm::createObjCARCOptPass() {
832 return new ObjCARCOpt();
833}
834
835void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
836 AU.addRequired<ObjCARCAliasAnalysis>();
837 AU.addRequired<AliasAnalysis>();
838 // ARC optimization doesn't currently split critical edges.
839 AU.setPreservesCFG();
840}
841
Dan Gohman728db492012-01-13 00:39:07 +0000842bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
843 // Without the magic metadata tag, we have to assume this might be an
844 // objc_retainBlock call inserted to convert a block pointer to an id,
845 // in which case it really is needed.
846 if (!Inst->getMetadata(CopyOnEscapeMDKind))
847 return false;
848
849 // If the pointer "escapes" (not including being used in a call),
850 // the copy may be needed.
Michael Gottesman774d2c02013-01-29 21:00:52 +0000851 if (DoesRetainableObjPtrEscape(Inst))
Dan Gohman728db492012-01-13 00:39:07 +0000852 return false;
853
854 // Otherwise, it's not needed.
855 return true;
856}
857
John McCalld935e9c2011-06-15 23:37:01 +0000858Constant *ObjCARCOpt::getRetainRVCallee(Module *M) {
859 if (!RetainRVCallee) {
860 LLVMContext &C = M->getContext();
Jay Foadb804a2b2011-07-12 14:06:48 +0000861 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman41375a32012-05-08 23:39:44 +0000862 Type *Params[] = { I8X };
863 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000864 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +0000865 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
866 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +0000867 RetainRVCallee =
868 M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy,
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000869 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +0000870 }
871 return RetainRVCallee;
872}
873
874Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
875 if (!AutoreleaseRVCallee) {
876 LLVMContext &C = M->getContext();
Jay Foadb804a2b2011-07-12 14:06:48 +0000877 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman41375a32012-05-08 23:39:44 +0000878 Type *Params[] = { I8X };
879 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000880 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +0000881 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
882 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +0000883 AutoreleaseRVCallee =
884 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000885 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +0000886 }
887 return AutoreleaseRVCallee;
888}
889
890Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
891 if (!ReleaseCallee) {
892 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +0000893 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000894 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +0000895 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
896 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +0000897 ReleaseCallee =
898 M->getOrInsertFunction(
899 "objc_release",
900 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000901 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +0000902 }
903 return ReleaseCallee;
904}
905
906Constant *ObjCARCOpt::getRetainCallee(Module *M) {
907 if (!RetainCallee) {
908 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +0000909 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000910 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +0000911 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
912 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +0000913 RetainCallee =
914 M->getOrInsertFunction(
915 "objc_retain",
916 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000917 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +0000918 }
919 return RetainCallee;
920}
921
Dan Gohman6320f522011-07-22 22:29:21 +0000922Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
923 if (!RetainBlockCallee) {
924 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +0000925 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Dan Gohmanfca43c22011-09-14 18:33:34 +0000926 // objc_retainBlock is not nounwind because it calls user copy constructors
927 // which could theoretically throw.
Dan Gohman6320f522011-07-22 22:29:21 +0000928 RetainBlockCallee =
929 M->getOrInsertFunction(
930 "objc_retainBlock",
931 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendlinge94d8432012-12-07 23:16:57 +0000932 AttributeSet());
Dan Gohman6320f522011-07-22 22:29:21 +0000933 }
934 return RetainBlockCallee;
935}
936
John McCalld935e9c2011-06-15 23:37:01 +0000937Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
938 if (!AutoreleaseCallee) {
939 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +0000940 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000941 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +0000942 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
943 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +0000944 AutoreleaseCallee =
945 M->getOrInsertFunction(
946 "objc_autorelease",
947 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000948 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +0000949 }
950 return AutoreleaseCallee;
951}
952
Michael Gottesman97e3df02013-01-14 00:35:14 +0000953/// Turn objc_retain into objc_retainAutoreleasedReturnValue if the operand is a
954/// return value.
John McCalld935e9c2011-06-15 23:37:01 +0000955void
956ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) {
Dan Gohmandae33492012-04-27 18:56:31 +0000957 ImmutableCallSite CS(GetObjCArg(Retain));
958 const Instruction *Call = CS.getInstruction();
John McCalld935e9c2011-06-15 23:37:01 +0000959 if (!Call) return;
960 if (Call->getParent() != Retain->getParent()) return;
961
962 // Check that the call is next to the retain.
Dan Gohmandae33492012-04-27 18:56:31 +0000963 BasicBlock::const_iterator I = Call;
John McCalld935e9c2011-06-15 23:37:01 +0000964 ++I;
965 while (isNoopInstruction(I)) ++I;
966 if (&*I != Retain)
967 return;
968
969 // Turn it to an objc_retainAutoreleasedReturnValue..
970 Changed = true;
971 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +0000972
Michael Gottesman1e00ac62013-01-04 21:30:38 +0000973 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainCall: Transforming "
Michael Gottesman9f1be682013-01-12 03:45:49 +0000974 "objc_retain => objc_retainAutoreleasedReturnValue"
975 " since the operand is a return value.\n"
Michael Gottesman1e00ac62013-01-04 21:30:38 +0000976 " Old: "
977 << *Retain << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +0000978
John McCalld935e9c2011-06-15 23:37:01 +0000979 cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent()));
Michael Gottesman1e00ac62013-01-04 21:30:38 +0000980
981 DEBUG(dbgs() << " New: "
982 << *Retain << "\n");
John McCalld935e9c2011-06-15 23:37:01 +0000983}
984
Michael Gottesman97e3df02013-01-14 00:35:14 +0000985/// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is
986/// not a return value. Or, if it can be paired with an
987/// objc_autoreleaseReturnValue, delete the pair and return true.
John McCalld935e9c2011-06-15 23:37:01 +0000988bool
989ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +0000990 // Check for the argument being from an immediately preceding call or invoke.
Dan Gohmandae33492012-04-27 18:56:31 +0000991 const Value *Arg = GetObjCArg(RetainRV);
992 ImmutableCallSite CS(Arg);
993 if (const Instruction *Call = CS.getInstruction()) {
John McCalld935e9c2011-06-15 23:37:01 +0000994 if (Call->getParent() == RetainRV->getParent()) {
Dan Gohmandae33492012-04-27 18:56:31 +0000995 BasicBlock::const_iterator I = Call;
John McCalld935e9c2011-06-15 23:37:01 +0000996 ++I;
997 while (isNoopInstruction(I)) ++I;
998 if (&*I == RetainRV)
999 return false;
Dan Gohmandae33492012-04-27 18:56:31 +00001000 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001001 BasicBlock *RetainRVParent = RetainRV->getParent();
1002 if (II->getNormalDest() == RetainRVParent) {
Dan Gohmandae33492012-04-27 18:56:31 +00001003 BasicBlock::const_iterator I = RetainRVParent->begin();
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001004 while (isNoopInstruction(I)) ++I;
1005 if (&*I == RetainRV)
1006 return false;
1007 }
John McCalld935e9c2011-06-15 23:37:01 +00001008 }
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001009 }
John McCalld935e9c2011-06-15 23:37:01 +00001010
1011 // Check for being preceded by an objc_autoreleaseReturnValue on the same
1012 // pointer. In this case, we can delete the pair.
1013 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
1014 if (I != Begin) {
1015 do --I; while (I != Begin && isNoopInstruction(I));
1016 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
1017 GetObjCArg(I) == Arg) {
1018 Changed = true;
1019 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00001020
Michael Gottesman5c32ce92013-01-05 17:55:35 +00001021 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainRVCall: Erasing " << *I << "\n"
1022 << " Erasing " << *RetainRV
1023 << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001024
John McCalld935e9c2011-06-15 23:37:01 +00001025 EraseInstruction(I);
1026 EraseInstruction(RetainRV);
1027 return true;
1028 }
1029 }
1030
1031 // Turn it to a plain objc_retain.
1032 Changed = true;
1033 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00001034
Michael Gottesmandef07bb2013-01-05 17:55:42 +00001035 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainRVCall: Transforming "
1036 "objc_retainAutoreleasedReturnValue => "
1037 "objc_retain since the operand is not a return value.\n"
1038 " Old: "
1039 << *RetainRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001040
John McCalld935e9c2011-06-15 23:37:01 +00001041 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
Michael Gottesmandef07bb2013-01-05 17:55:42 +00001042
1043 DEBUG(dbgs() << " New: "
1044 << *RetainRV << "\n");
1045
John McCalld935e9c2011-06-15 23:37:01 +00001046 return false;
1047}
1048
Michael Gottesman97e3df02013-01-14 00:35:14 +00001049/// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not
1050/// used as a return value.
John McCalld935e9c2011-06-15 23:37:01 +00001051void
Michael Gottesman556ff612013-01-12 01:25:19 +00001052ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1053 InstructionClass &Class) {
John McCalld935e9c2011-06-15 23:37:01 +00001054 // Check for a return of the pointer value.
1055 const Value *Ptr = GetObjCArg(AutoreleaseRV);
Dan Gohman10a18d52011-08-12 00:36:31 +00001056 SmallVector<const Value *, 2> Users;
1057 Users.push_back(Ptr);
1058 do {
1059 Ptr = Users.pop_back_val();
1060 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
1061 UI != UE; ++UI) {
1062 const User *I = *UI;
1063 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
1064 return;
1065 if (isa<BitCastInst>(I))
1066 Users.push_back(I);
1067 }
1068 } while (!Users.empty());
John McCalld935e9c2011-06-15 23:37:01 +00001069
1070 Changed = true;
1071 ++NumPeeps;
Michael Gottesman1bf69082013-01-06 21:07:11 +00001072
1073 DEBUG(dbgs() << "ObjCARCOpt::OptimizeAutoreleaseRVCall: Transforming "
1074 "objc_autoreleaseReturnValue => "
1075 "objc_autorelease since its operand is not used as a return "
1076 "value.\n"
1077 " Old: "
1078 << *AutoreleaseRV << "\n");
1079
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001080 CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
1081 AutoreleaseRVCI->
John McCalld935e9c2011-06-15 23:37:01 +00001082 setCalledFunction(getAutoreleaseCallee(F.getParent()));
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001083 AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
Michael Gottesman556ff612013-01-12 01:25:19 +00001084 Class = IC_Autorelease;
Michael Gottesman10426b52013-01-07 21:26:07 +00001085
Michael Gottesman1bf69082013-01-06 21:07:11 +00001086 DEBUG(dbgs() << " New: "
1087 << *AutoreleaseRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001088
John McCalld935e9c2011-06-15 23:37:01 +00001089}
1090
Michael Gottesman97e3df02013-01-14 00:35:14 +00001091/// Visit each call, one at a time, and make simplifications without doing any
1092/// additional analysis.
John McCalld935e9c2011-06-15 23:37:01 +00001093void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
1094 // Reset all the flags in preparation for recomputing them.
1095 UsedInThisFunction = 0;
1096
1097 // Visit all objc_* calls in F.
1098 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
1099 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +00001100
John McCalld935e9c2011-06-15 23:37:01 +00001101 InstructionClass Class = GetBasicInstructionClass(Inst);
1102
Michael Gottesmand359e062013-01-18 03:08:39 +00001103 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Visiting: Class: "
1104 << Class << "; " << *Inst << "\n");
Michael Gottesman782e3442013-01-17 18:32:34 +00001105
John McCalld935e9c2011-06-15 23:37:01 +00001106 switch (Class) {
1107 default: break;
1108
1109 // Delete no-op casts. These function calls have special semantics, but
1110 // the semantics are entirely implemented via lowering in the front-end,
1111 // so by the time they reach the optimizer, they are just no-op calls
1112 // which return their argument.
1113 //
1114 // There are gray areas here, as the ability to cast reference-counted
1115 // pointers to raw void* and back allows code to break ARC assumptions,
1116 // however these are currently considered to be unimportant.
1117 case IC_NoopCast:
1118 Changed = true;
1119 ++NumNoops;
Michael Gottesmandc042f02013-01-06 21:07:15 +00001120 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Erasing no-op cast:"
1121 " " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001122 EraseInstruction(Inst);
1123 continue;
1124
1125 // If the pointer-to-weak-pointer is null, it's undefined behavior.
1126 case IC_StoreWeak:
1127 case IC_LoadWeak:
1128 case IC_LoadWeakRetained:
1129 case IC_InitWeak:
1130 case IC_DestroyWeak: {
1131 CallInst *CI = cast<CallInst>(Inst);
1132 if (isNullOrUndef(CI->getArgOperand(0))) {
Dan Gohman670f9372012-04-13 18:57:48 +00001133 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +00001134 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001135 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1136 Constant::getNullValue(Ty),
1137 CI);
Michael Gottesman10426b52013-01-07 21:26:07 +00001138 llvm::Value *NewValue = UndefValue::get(CI->getType());
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001139 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: A null "
1140 "pointer-to-weak-pointer is undefined behavior.\n"
1141 " Old = " << *CI <<
1142 "\n New = " <<
Michael Gottesman10426b52013-01-07 21:26:07 +00001143 *NewValue << "\n");
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001144 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +00001145 CI->eraseFromParent();
1146 continue;
1147 }
1148 break;
1149 }
1150 case IC_CopyWeak:
1151 case IC_MoveWeak: {
1152 CallInst *CI = cast<CallInst>(Inst);
1153 if (isNullOrUndef(CI->getArgOperand(0)) ||
1154 isNullOrUndef(CI->getArgOperand(1))) {
Dan Gohman670f9372012-04-13 18:57:48 +00001155 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +00001156 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001157 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1158 Constant::getNullValue(Ty),
1159 CI);
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001160
1161 llvm::Value *NewValue = UndefValue::get(CI->getType());
1162 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: A null "
1163 "pointer-to-weak-pointer is undefined behavior.\n"
1164 " Old = " << *CI <<
1165 "\n New = " <<
1166 *NewValue << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001167
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001168 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +00001169 CI->eraseFromParent();
1170 continue;
1171 }
1172 break;
1173 }
1174 case IC_Retain:
1175 OptimizeRetainCall(F, Inst);
1176 break;
1177 case IC_RetainRV:
1178 if (OptimizeRetainRVCall(F, Inst))
1179 continue;
1180 break;
1181 case IC_AutoreleaseRV:
Michael Gottesman556ff612013-01-12 01:25:19 +00001182 OptimizeAutoreleaseRVCall(F, Inst, Class);
John McCalld935e9c2011-06-15 23:37:01 +00001183 break;
1184 }
1185
1186 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
1187 if (IsAutorelease(Class) && Inst->use_empty()) {
1188 CallInst *Call = cast<CallInst>(Inst);
1189 const Value *Arg = Call->getArgOperand(0);
1190 Arg = FindSingleUseIdentifiedObject(Arg);
1191 if (Arg) {
1192 Changed = true;
1193 ++NumAutoreleases;
1194
1195 // Create the declaration lazily.
1196 LLVMContext &C = Inst->getContext();
1197 CallInst *NewCall =
1198 CallInst::Create(getReleaseCallee(F.getParent()),
1199 Call->getArgOperand(0), "", Call);
1200 NewCall->setMetadata(ImpreciseReleaseMDKind,
1201 MDNode::get(C, ArrayRef<Value *>()));
Michael Gottesman10426b52013-01-07 21:26:07 +00001202
Michael Gottesmana6a1dad2013-01-06 22:56:50 +00001203 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Replacing "
1204 "objc_autorelease(x) with objc_release(x) since x is "
1205 "otherwise unused.\n"
Michael Gottesman4bf6e752013-01-06 22:56:54 +00001206 " Old: " << *Call <<
Michael Gottesmana6a1dad2013-01-06 22:56:50 +00001207 "\n New: " <<
1208 *NewCall << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001209
John McCalld935e9c2011-06-15 23:37:01 +00001210 EraseInstruction(Call);
1211 Inst = NewCall;
1212 Class = IC_Release;
1213 }
1214 }
1215
1216 // For functions which can never be passed stack arguments, add
1217 // a tail keyword.
1218 if (IsAlwaysTail(Class)) {
1219 Changed = true;
Michael Gottesman2d763312013-01-06 23:39:09 +00001220 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Adding tail keyword"
1221 " to function since it can never be passed stack args: " << *Inst <<
1222 "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001223 cast<CallInst>(Inst)->setTailCall();
1224 }
1225
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001226 // Ensure that functions that can never have a "tail" keyword due to the
1227 // semantics of ARC truly do not do so.
1228 if (IsNeverTail(Class)) {
1229 Changed = true;
Michael Gottesman4385edf2013-01-14 01:47:53 +00001230 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Removing tail "
1231 "keyword from function: " << *Inst <<
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001232 "\n");
1233 cast<CallInst>(Inst)->setTailCall(false);
1234 }
1235
John McCalld935e9c2011-06-15 23:37:01 +00001236 // Set nounwind as needed.
1237 if (IsNoThrow(Class)) {
1238 Changed = true;
Michael Gottesman8800a512013-01-06 23:39:13 +00001239 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Found no throw"
1240 " class. Setting nounwind on: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001241 cast<CallInst>(Inst)->setDoesNotThrow();
1242 }
1243
1244 if (!IsNoopOnNull(Class)) {
1245 UsedInThisFunction |= 1 << Class;
1246 continue;
1247 }
1248
1249 const Value *Arg = GetObjCArg(Inst);
1250
1251 // ARC calls with null are no-ops. Delete them.
1252 if (isNullOrUndef(Arg)) {
1253 Changed = true;
1254 ++NumNoops;
Michael Gottesman5b970e12013-01-07 00:04:52 +00001255 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: ARC calls with "
1256 " null are no-ops. Erasing: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001257 EraseInstruction(Inst);
1258 continue;
1259 }
1260
1261 // Keep track of which of retain, release, autorelease, and retain_block
1262 // are actually present in this function.
1263 UsedInThisFunction |= 1 << Class;
1264
1265 // If Arg is a PHI, and one or more incoming values to the
1266 // PHI are null, and the call is control-equivalent to the PHI, and there
1267 // are no relevant side effects between the PHI and the call, the call
1268 // could be pushed up to just those paths with non-null incoming values.
1269 // For now, don't bother splitting critical edges for this.
1270 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
1271 Worklist.push_back(std::make_pair(Inst, Arg));
1272 do {
1273 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
1274 Inst = Pair.first;
1275 Arg = Pair.second;
1276
1277 const PHINode *PN = dyn_cast<PHINode>(Arg);
1278 if (!PN) continue;
1279
1280 // Determine if the PHI has any null operands, or any incoming
1281 // critical edges.
1282 bool HasNull = false;
1283 bool HasCriticalEdges = false;
1284 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1285 Value *Incoming =
1286 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
1287 if (isNullOrUndef(Incoming))
1288 HasNull = true;
1289 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
1290 .getNumSuccessors() != 1) {
1291 HasCriticalEdges = true;
1292 break;
1293 }
1294 }
1295 // If we have null operands and no critical edges, optimize.
1296 if (!HasCriticalEdges && HasNull) {
1297 SmallPtrSet<Instruction *, 4> DependingInstructions;
1298 SmallPtrSet<const BasicBlock *, 4> Visited;
1299
1300 // Check that there is nothing that cares about the reference
1301 // count between the call and the phi.
Dan Gohman8478d762012-04-13 00:59:57 +00001302 switch (Class) {
1303 case IC_Retain:
1304 case IC_RetainBlock:
1305 // These can always be moved up.
1306 break;
1307 case IC_Release:
Dan Gohman41375a32012-05-08 23:39:44 +00001308 // These can't be moved across things that care about the retain
1309 // count.
Dan Gohman8478d762012-04-13 00:59:57 +00001310 FindDependencies(NeedsPositiveRetainCount, Arg,
1311 Inst->getParent(), Inst,
1312 DependingInstructions, Visited, PA);
1313 break;
1314 case IC_Autorelease:
1315 // These can't be moved across autorelease pool scope boundaries.
1316 FindDependencies(AutoreleasePoolBoundary, Arg,
1317 Inst->getParent(), Inst,
1318 DependingInstructions, Visited, PA);
1319 break;
1320 case IC_RetainRV:
1321 case IC_AutoreleaseRV:
1322 // Don't move these; the RV optimization depends on the autoreleaseRV
1323 // being tail called, and the retainRV being immediately after a call
1324 // (which might still happen if we get lucky with codegen layout, but
1325 // it's not worth taking the chance).
1326 continue;
1327 default:
1328 llvm_unreachable("Invalid dependence flavor");
1329 }
1330
John McCalld935e9c2011-06-15 23:37:01 +00001331 if (DependingInstructions.size() == 1 &&
1332 *DependingInstructions.begin() == PN) {
1333 Changed = true;
1334 ++NumPartialNoops;
1335 // Clone the call into each predecessor that has a non-null value.
1336 CallInst *CInst = cast<CallInst>(Inst);
Chris Lattner229907c2011-07-18 04:54:35 +00001337 Type *ParamTy = CInst->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001338 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1339 Value *Incoming =
1340 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
1341 if (!isNullOrUndef(Incoming)) {
1342 CallInst *Clone = cast<CallInst>(CInst->clone());
1343 Value *Op = PN->getIncomingValue(i);
1344 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
1345 if (Op->getType() != ParamTy)
1346 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
1347 Clone->setArgOperand(0, Op);
1348 Clone->insertBefore(InsertPos);
Michael Gottesmanc189a392013-01-09 19:23:24 +00001349
1350 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Cloning "
1351 << *CInst << "\n"
1352 " And inserting "
1353 "clone at " << *InsertPos << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001354 Worklist.push_back(std::make_pair(Clone, Incoming));
1355 }
1356 }
1357 // Erase the original call.
Michael Gottesmanc189a392013-01-09 19:23:24 +00001358 DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001359 EraseInstruction(CInst);
1360 continue;
1361 }
1362 }
1363 } while (!Worklist.empty());
1364 }
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00001365 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Finished List.\n");
John McCalld935e9c2011-06-15 23:37:01 +00001366}
1367
Michael Gottesman97e3df02013-01-14 00:35:14 +00001368/// Check for critical edges, loop boundaries, irreducible control flow, or
1369/// other CFG structures where moving code across the edge would result in it
1370/// being executed more.
John McCalld935e9c2011-06-15 23:37:01 +00001371void
1372ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
1373 DenseMap<const BasicBlock *, BBState> &BBStates,
1374 BBState &MyStates) const {
1375 // If any top-down local-use or possible-dec has a succ which is earlier in
1376 // the sequence, forget it.
Dan Gohman55b06742012-03-02 01:13:53 +00001377 for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
John McCalld935e9c2011-06-15 23:37:01 +00001378 E = MyStates.top_down_ptr_end(); I != E; ++I)
1379 switch (I->second.GetSeq()) {
1380 default: break;
1381 case S_Use: {
1382 const Value *Arg = I->first;
1383 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
1384 bool SomeSuccHasSame = false;
1385 bool AllSuccsHaveSame = true;
Dan Gohman55b06742012-03-02 01:13:53 +00001386 PtrState &S = I->second;
Dan Gohman0155f302012-02-17 18:59:53 +00001387 succ_const_iterator SI(TI), SE(TI, false);
1388
Dan Gohman0155f302012-02-17 18:59:53 +00001389 for (; SI != SE; ++SI) {
Dan Gohman362eb692012-03-02 01:26:46 +00001390 Sequence SuccSSeq = S_None;
1391 bool SuccSRRIKnownSafe = false;
Dan Gohman41375a32012-05-08 23:39:44 +00001392 // If VisitBottomUp has pointer information for this successor, take
1393 // what we know about it.
Dan Gohmandae33492012-04-27 18:56:31 +00001394 DenseMap<const BasicBlock *, BBState>::iterator BBI =
1395 BBStates.find(*SI);
1396 assert(BBI != BBStates.end());
1397 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
1398 SuccSSeq = SuccS.GetSeq();
1399 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
Dan Gohman362eb692012-03-02 01:26:46 +00001400 switch (SuccSSeq) {
John McCalld935e9c2011-06-15 23:37:01 +00001401 case S_None:
Dan Gohman12130272011-08-12 00:26:31 +00001402 case S_CanRelease: {
Dan Gohman362eb692012-03-02 01:26:46 +00001403 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
Dan Gohman12130272011-08-12 00:26:31 +00001404 S.ClearSequenceProgress();
Dan Gohman362eb692012-03-02 01:26:46 +00001405 break;
1406 }
Dan Gohman12130272011-08-12 00:26:31 +00001407 continue;
1408 }
John McCalld935e9c2011-06-15 23:37:01 +00001409 case S_Use:
1410 SomeSuccHasSame = true;
1411 break;
1412 case S_Stop:
1413 case S_Release:
1414 case S_MovableRelease:
Dan Gohman362eb692012-03-02 01:26:46 +00001415 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
Dan Gohman12130272011-08-12 00:26:31 +00001416 AllSuccsHaveSame = false;
John McCalld935e9c2011-06-15 23:37:01 +00001417 break;
1418 case S_Retain:
1419 llvm_unreachable("bottom-up pointer in retain state!");
1420 }
Dan Gohman12130272011-08-12 00:26:31 +00001421 }
John McCalld935e9c2011-06-15 23:37:01 +00001422 // If the state at the other end of any of the successor edges
1423 // matches the current state, require all edges to match. This
1424 // guards against loops in the middle of a sequence.
1425 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohman12130272011-08-12 00:26:31 +00001426 S.ClearSequenceProgress();
Dan Gohman044437062011-12-12 18:13:53 +00001427 break;
John McCalld935e9c2011-06-15 23:37:01 +00001428 }
1429 case S_CanRelease: {
1430 const Value *Arg = I->first;
1431 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
1432 bool SomeSuccHasSame = false;
1433 bool AllSuccsHaveSame = true;
Dan Gohman55b06742012-03-02 01:13:53 +00001434 PtrState &S = I->second;
Dan Gohman0155f302012-02-17 18:59:53 +00001435 succ_const_iterator SI(TI), SE(TI, false);
1436
Dan Gohman0155f302012-02-17 18:59:53 +00001437 for (; SI != SE; ++SI) {
Dan Gohman362eb692012-03-02 01:26:46 +00001438 Sequence SuccSSeq = S_None;
1439 bool SuccSRRIKnownSafe = false;
Dan Gohman41375a32012-05-08 23:39:44 +00001440 // If VisitBottomUp has pointer information for this successor, take
1441 // what we know about it.
Dan Gohmandae33492012-04-27 18:56:31 +00001442 DenseMap<const BasicBlock *, BBState>::iterator BBI =
1443 BBStates.find(*SI);
1444 assert(BBI != BBStates.end());
1445 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
1446 SuccSSeq = SuccS.GetSeq();
1447 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
Dan Gohman362eb692012-03-02 01:26:46 +00001448 switch (SuccSSeq) {
Dan Gohman12130272011-08-12 00:26:31 +00001449 case S_None: {
Dan Gohman362eb692012-03-02 01:26:46 +00001450 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
Dan Gohman12130272011-08-12 00:26:31 +00001451 S.ClearSequenceProgress();
Dan Gohman362eb692012-03-02 01:26:46 +00001452 break;
1453 }
Dan Gohman12130272011-08-12 00:26:31 +00001454 continue;
1455 }
John McCalld935e9c2011-06-15 23:37:01 +00001456 case S_CanRelease:
1457 SomeSuccHasSame = true;
1458 break;
1459 case S_Stop:
1460 case S_Release:
1461 case S_MovableRelease:
1462 case S_Use:
Dan Gohman362eb692012-03-02 01:26:46 +00001463 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
Dan Gohman12130272011-08-12 00:26:31 +00001464 AllSuccsHaveSame = false;
John McCalld935e9c2011-06-15 23:37:01 +00001465 break;
1466 case S_Retain:
1467 llvm_unreachable("bottom-up pointer in retain state!");
1468 }
Dan Gohman12130272011-08-12 00:26:31 +00001469 }
John McCalld935e9c2011-06-15 23:37:01 +00001470 // If the state at the other end of any of the successor edges
1471 // matches the current state, require all edges to match. This
1472 // guards against loops in the middle of a sequence.
1473 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohman12130272011-08-12 00:26:31 +00001474 S.ClearSequenceProgress();
Dan Gohman044437062011-12-12 18:13:53 +00001475 break;
John McCalld935e9c2011-06-15 23:37:01 +00001476 }
1477 }
1478}
1479
1480bool
Dan Gohman817a7c62012-03-22 18:24:56 +00001481ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
Dan Gohman5c70fad2012-03-23 17:47:54 +00001482 BasicBlock *BB,
Dan Gohman817a7c62012-03-22 18:24:56 +00001483 MapVector<Value *, RRInfo> &Retains,
1484 BBState &MyStates) {
1485 bool NestingDetected = false;
1486 InstructionClass Class = GetInstructionClass(Inst);
1487 const Value *Arg = 0;
1488
1489 switch (Class) {
1490 case IC_Release: {
1491 Arg = GetObjCArg(Inst);
1492
1493 PtrState &S = MyStates.getPtrBottomUpState(Arg);
1494
1495 // If we see two releases in a row on the same pointer. If so, make
1496 // a note, and we'll cicle back to revisit it after we've
1497 // hopefully eliminated the second release, which may allow us to
1498 // eliminate the first release too.
1499 // Theoretically we could implement removal of nested retain+release
1500 // pairs by making PtrState hold a stack of states, but this is
1501 // simple and avoids adding overhead for the non-nested case.
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001502 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease) {
1503 DEBUG(dbgs() << "ObjCARCOpt::VisitInstructionBottomUp: Found nested "
1504 "releases (i.e. a release pair)\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00001505 NestingDetected = true;
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001506 }
Dan Gohman817a7c62012-03-22 18:24:56 +00001507
Dan Gohman817a7c62012-03-22 18:24:56 +00001508 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
Dan Gohman62079b42012-04-25 00:50:46 +00001509 S.ResetSequenceProgress(ReleaseMetadata ? S_MovableRelease : S_Release);
Dan Gohman817a7c62012-03-22 18:24:56 +00001510 S.RRI.ReleaseMetadata = ReleaseMetadata;
Dan Gohmandf476e52012-09-04 23:16:20 +00001511 S.RRI.KnownSafe = S.IsKnownIncremented();
Dan Gohman817a7c62012-03-22 18:24:56 +00001512 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
1513 S.RRI.Calls.insert(Inst);
1514
Dan Gohmandf476e52012-09-04 23:16:20 +00001515 S.SetKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001516 break;
1517 }
1518 case IC_RetainBlock:
1519 // An objc_retainBlock call with just a use may need to be kept,
1520 // because it may be copying a block from the stack to the heap.
1521 if (!IsRetainBlockOptimizable(Inst))
1522 break;
1523 // FALLTHROUGH
1524 case IC_Retain:
1525 case IC_RetainRV: {
1526 Arg = GetObjCArg(Inst);
1527
1528 PtrState &S = MyStates.getPtrBottomUpState(Arg);
Dan Gohman62079b42012-04-25 00:50:46 +00001529 S.SetKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001530
1531 switch (S.GetSeq()) {
1532 case S_Stop:
1533 case S_Release:
1534 case S_MovableRelease:
1535 case S_Use:
1536 S.RRI.ReverseInsertPts.clear();
1537 // FALL THROUGH
1538 case S_CanRelease:
1539 // Don't do retain+release tracking for IC_RetainRV, because it's
1540 // better to let it remain as the first instruction after a call.
1541 if (Class != IC_RetainRV) {
1542 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
1543 Retains[Inst] = S.RRI;
1544 }
1545 S.ClearSequenceProgress();
1546 break;
1547 case S_None:
1548 break;
1549 case S_Retain:
1550 llvm_unreachable("bottom-up pointer in retain state!");
1551 }
1552 return NestingDetected;
1553 }
1554 case IC_AutoreleasepoolPop:
1555 // Conservatively, clear MyStates for all known pointers.
1556 MyStates.clearBottomUpPointers();
1557 return NestingDetected;
1558 case IC_AutoreleasepoolPush:
1559 case IC_None:
1560 // These are irrelevant.
1561 return NestingDetected;
1562 default:
1563 break;
1564 }
1565
1566 // Consider any other possible effects of this instruction on each
1567 // pointer being tracked.
1568 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
1569 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
1570 const Value *Ptr = MI->first;
1571 if (Ptr == Arg)
1572 continue; // Handled above.
1573 PtrState &S = MI->second;
1574 Sequence Seq = S.GetSeq();
1575
1576 // Check for possible releases.
1577 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Dan Gohman62079b42012-04-25 00:50:46 +00001578 S.ClearRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001579 switch (Seq) {
1580 case S_Use:
1581 S.SetSeq(S_CanRelease);
1582 continue;
1583 case S_CanRelease:
1584 case S_Release:
1585 case S_MovableRelease:
1586 case S_Stop:
1587 case S_None:
1588 break;
1589 case S_Retain:
1590 llvm_unreachable("bottom-up pointer in retain state!");
1591 }
1592 }
1593
1594 // Check for possible direct uses.
1595 switch (Seq) {
1596 case S_Release:
1597 case S_MovableRelease:
1598 if (CanUse(Inst, Ptr, PA, Class)) {
1599 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohman5c70fad2012-03-23 17:47:54 +00001600 // If this is an invoke instruction, we're scanning it as part of
1601 // one of its successor blocks, since we can't insert code after it
1602 // in its own block, and we don't want to split critical edges.
1603 if (isa<InvokeInst>(Inst))
1604 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
1605 else
Francois Pichet4b9ab742012-03-24 01:36:37 +00001606 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohman817a7c62012-03-22 18:24:56 +00001607 S.SetSeq(S_Use);
1608 } else if (Seq == S_Release &&
1609 (Class == IC_User || Class == IC_CallOrUser)) {
1610 // Non-movable releases depend on any possible objc pointer use.
1611 S.SetSeq(S_Stop);
1612 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohman5c70fad2012-03-23 17:47:54 +00001613 // As above; handle invoke specially.
1614 if (isa<InvokeInst>(Inst))
1615 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
1616 else
Francois Pichet4b9ab742012-03-24 01:36:37 +00001617 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohman817a7c62012-03-22 18:24:56 +00001618 }
1619 break;
1620 case S_Stop:
1621 if (CanUse(Inst, Ptr, PA, Class))
1622 S.SetSeq(S_Use);
1623 break;
1624 case S_CanRelease:
1625 case S_Use:
1626 case S_None:
1627 break;
1628 case S_Retain:
1629 llvm_unreachable("bottom-up pointer in retain state!");
1630 }
1631 }
1632
1633 return NestingDetected;
1634}
1635
1636bool
John McCalld935e9c2011-06-15 23:37:01 +00001637ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
1638 DenseMap<const BasicBlock *, BBState> &BBStates,
1639 MapVector<Value *, RRInfo> &Retains) {
1640 bool NestingDetected = false;
1641 BBState &MyStates = BBStates[BB];
1642
1643 // Merge the states from each successor to compute the initial state
1644 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00001645 BBState::edge_iterator SI(MyStates.succ_begin()),
1646 SE(MyStates.succ_end());
1647 if (SI != SE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001648 const BasicBlock *Succ = *SI;
1649 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
1650 assert(I != BBStates.end());
1651 MyStates.InitFromSucc(I->second);
1652 ++SI;
1653 for (; SI != SE; ++SI) {
1654 Succ = *SI;
1655 I = BBStates.find(Succ);
1656 assert(I != BBStates.end());
1657 MyStates.MergeSucc(I->second);
1658 }
Dan Gohman0155f302012-02-17 18:59:53 +00001659 }
John McCalld935e9c2011-06-15 23:37:01 +00001660
1661 // Visit all the instructions, bottom-up.
1662 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
1663 Instruction *Inst = llvm::prior(I);
Dan Gohman5c70fad2012-03-23 17:47:54 +00001664
1665 // Invoke instructions are visited as part of their successors (below).
1666 if (isa<InvokeInst>(Inst))
1667 continue;
1668
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001669 DEBUG(dbgs() << "ObjCARCOpt::VisitButtonUp: Visiting " << *Inst << "\n");
1670
Dan Gohman5c70fad2012-03-23 17:47:54 +00001671 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
1672 }
1673
Dan Gohmandae33492012-04-27 18:56:31 +00001674 // If there's a predecessor with an invoke, visit the invoke as if it were
1675 // part of this block, since we can't insert code after an invoke in its own
1676 // block, and we don't want to split critical edges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001677 for (BBState::edge_iterator PI(MyStates.pred_begin()),
1678 PE(MyStates.pred_end()); PI != PE; ++PI) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00001679 BasicBlock *Pred = *PI;
Dan Gohmandae33492012-04-27 18:56:31 +00001680 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
1681 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
Dan Gohman817a7c62012-03-22 18:24:56 +00001682 }
John McCalld935e9c2011-06-15 23:37:01 +00001683
Dan Gohman817a7c62012-03-22 18:24:56 +00001684 return NestingDetected;
1685}
John McCalld935e9c2011-06-15 23:37:01 +00001686
Dan Gohman817a7c62012-03-22 18:24:56 +00001687bool
1688ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
1689 DenseMap<Value *, RRInfo> &Releases,
1690 BBState &MyStates) {
1691 bool NestingDetected = false;
1692 InstructionClass Class = GetInstructionClass(Inst);
1693 const Value *Arg = 0;
John McCalld935e9c2011-06-15 23:37:01 +00001694
Dan Gohman817a7c62012-03-22 18:24:56 +00001695 switch (Class) {
1696 case IC_RetainBlock:
1697 // An objc_retainBlock call with just a use may need to be kept,
1698 // because it may be copying a block from the stack to the heap.
1699 if (!IsRetainBlockOptimizable(Inst))
1700 break;
1701 // FALLTHROUGH
1702 case IC_Retain:
1703 case IC_RetainRV: {
1704 Arg = GetObjCArg(Inst);
1705
1706 PtrState &S = MyStates.getPtrTopDownState(Arg);
1707
1708 // Don't do retain+release tracking for IC_RetainRV, because it's
1709 // better to let it remain as the first instruction after a call.
1710 if (Class != IC_RetainRV) {
1711 // If we see two retains in a row on the same pointer. If so, make
John McCalld935e9c2011-06-15 23:37:01 +00001712 // a note, and we'll cicle back to revisit it after we've
Dan Gohman817a7c62012-03-22 18:24:56 +00001713 // hopefully eliminated the second retain, which may allow us to
1714 // eliminate the first retain too.
John McCalld935e9c2011-06-15 23:37:01 +00001715 // Theoretically we could implement removal of nested retain+release
1716 // pairs by making PtrState hold a stack of states, but this is
1717 // simple and avoids adding overhead for the non-nested case.
Dan Gohman817a7c62012-03-22 18:24:56 +00001718 if (S.GetSeq() == S_Retain)
John McCalld935e9c2011-06-15 23:37:01 +00001719 NestingDetected = true;
1720
Dan Gohman62079b42012-04-25 00:50:46 +00001721 S.ResetSequenceProgress(S_Retain);
Dan Gohman817a7c62012-03-22 18:24:56 +00001722 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
Dan Gohmandf476e52012-09-04 23:16:20 +00001723 S.RRI.KnownSafe = S.IsKnownIncremented();
John McCalld935e9c2011-06-15 23:37:01 +00001724 S.RRI.Calls.insert(Inst);
John McCalld935e9c2011-06-15 23:37:01 +00001725 }
John McCalld935e9c2011-06-15 23:37:01 +00001726
Dan Gohmandf476e52012-09-04 23:16:20 +00001727 S.SetKnownPositiveRefCount();
Dan Gohmanf64ff8e2012-07-23 19:27:31 +00001728
1729 // A retain can be a potential use; procede to the generic checking
1730 // code below.
1731 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001732 }
1733 case IC_Release: {
1734 Arg = GetObjCArg(Inst);
1735
1736 PtrState &S = MyStates.getPtrTopDownState(Arg);
Dan Gohmandf476e52012-09-04 23:16:20 +00001737 S.ClearRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001738
1739 switch (S.GetSeq()) {
1740 case S_Retain:
1741 case S_CanRelease:
1742 S.RRI.ReverseInsertPts.clear();
1743 // FALL THROUGH
1744 case S_Use:
1745 S.RRI.ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
1746 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
1747 Releases[Inst] = S.RRI;
1748 S.ClearSequenceProgress();
1749 break;
1750 case S_None:
1751 break;
1752 case S_Stop:
1753 case S_Release:
1754 case S_MovableRelease:
1755 llvm_unreachable("top-down pointer in release state!");
1756 }
1757 break;
1758 }
1759 case IC_AutoreleasepoolPop:
1760 // Conservatively, clear MyStates for all known pointers.
1761 MyStates.clearTopDownPointers();
1762 return NestingDetected;
1763 case IC_AutoreleasepoolPush:
1764 case IC_None:
1765 // These are irrelevant.
1766 return NestingDetected;
1767 default:
1768 break;
1769 }
1770
1771 // Consider any other possible effects of this instruction on each
1772 // pointer being tracked.
1773 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
1774 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
1775 const Value *Ptr = MI->first;
1776 if (Ptr == Arg)
1777 continue; // Handled above.
1778 PtrState &S = MI->second;
1779 Sequence Seq = S.GetSeq();
1780
1781 // Check for possible releases.
1782 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Dan Gohman62079b42012-04-25 00:50:46 +00001783 S.ClearRefCount();
John McCalld935e9c2011-06-15 23:37:01 +00001784 switch (Seq) {
Dan Gohman817a7c62012-03-22 18:24:56 +00001785 case S_Retain:
1786 S.SetSeq(S_CanRelease);
1787 assert(S.RRI.ReverseInsertPts.empty());
1788 S.RRI.ReverseInsertPts.insert(Inst);
1789
1790 // One call can't cause a transition from S_Retain to S_CanRelease
1791 // and S_CanRelease to S_Use. If we've made the first transition,
1792 // we're done.
1793 continue;
John McCalld935e9c2011-06-15 23:37:01 +00001794 case S_Use:
Dan Gohman817a7c62012-03-22 18:24:56 +00001795 case S_CanRelease:
John McCalld935e9c2011-06-15 23:37:01 +00001796 case S_None:
1797 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001798 case S_Stop:
1799 case S_Release:
1800 case S_MovableRelease:
1801 llvm_unreachable("top-down pointer in release state!");
John McCalld935e9c2011-06-15 23:37:01 +00001802 }
1803 }
Dan Gohman817a7c62012-03-22 18:24:56 +00001804
1805 // Check for possible direct uses.
1806 switch (Seq) {
1807 case S_CanRelease:
1808 if (CanUse(Inst, Ptr, PA, Class))
1809 S.SetSeq(S_Use);
1810 break;
1811 case S_Retain:
1812 case S_Use:
1813 case S_None:
1814 break;
1815 case S_Stop:
1816 case S_Release:
1817 case S_MovableRelease:
1818 llvm_unreachable("top-down pointer in release state!");
1819 }
John McCalld935e9c2011-06-15 23:37:01 +00001820 }
1821
1822 return NestingDetected;
1823}
1824
1825bool
1826ObjCARCOpt::VisitTopDown(BasicBlock *BB,
1827 DenseMap<const BasicBlock *, BBState> &BBStates,
1828 DenseMap<Value *, RRInfo> &Releases) {
1829 bool NestingDetected = false;
1830 BBState &MyStates = BBStates[BB];
1831
1832 // Merge the states from each predecessor to compute the initial state
1833 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00001834 BBState::edge_iterator PI(MyStates.pred_begin()),
1835 PE(MyStates.pred_end());
1836 if (PI != PE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001837 const BasicBlock *Pred = *PI;
1838 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
1839 assert(I != BBStates.end());
1840 MyStates.InitFromPred(I->second);
1841 ++PI;
1842 for (; PI != PE; ++PI) {
1843 Pred = *PI;
1844 I = BBStates.find(Pred);
1845 assert(I != BBStates.end());
1846 MyStates.MergePred(I->second);
1847 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001848 }
John McCalld935e9c2011-06-15 23:37:01 +00001849
1850 // Visit all the instructions, top-down.
1851 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1852 Instruction *Inst = I;
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001853
1854 DEBUG(dbgs() << "ObjCARCOpt::VisitTopDown: Visiting " << *Inst << "\n");
1855
Dan Gohman817a7c62012-03-22 18:24:56 +00001856 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00001857 }
1858
1859 CheckForCFGHazards(BB, BBStates, MyStates);
1860 return NestingDetected;
1861}
1862
Dan Gohmana53a12c2011-12-12 19:42:25 +00001863static void
1864ComputePostOrders(Function &F,
1865 SmallVectorImpl<BasicBlock *> &PostOrder,
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001866 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
1867 unsigned NoObjCARCExceptionsMDKind,
1868 DenseMap<const BasicBlock *, BBState> &BBStates) {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001869 /// The visited set, for doing DFS walks.
Dan Gohmana53a12c2011-12-12 19:42:25 +00001870 SmallPtrSet<BasicBlock *, 16> Visited;
1871
1872 // Do DFS, computing the PostOrder.
1873 SmallPtrSet<BasicBlock *, 16> OnStack;
1874 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001875
1876 // Functions always have exactly one entry block, and we don't have
1877 // any other block that we treat like an entry block.
Dan Gohmana53a12c2011-12-12 19:42:25 +00001878 BasicBlock *EntryBB = &F.getEntryBlock();
Dan Gohman41375a32012-05-08 23:39:44 +00001879 BBState &MyStates = BBStates[EntryBB];
1880 MyStates.SetAsEntry();
1881 TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
1882 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
Dan Gohmana53a12c2011-12-12 19:42:25 +00001883 Visited.insert(EntryBB);
1884 OnStack.insert(EntryBB);
1885 do {
1886 dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001887 BasicBlock *CurrBB = SuccStack.back().first;
1888 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
1889 succ_iterator SE(TI, false);
Dan Gohman41375a32012-05-08 23:39:44 +00001890
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001891 while (SuccStack.back().second != SE) {
1892 BasicBlock *SuccBB = *SuccStack.back().second++;
1893 if (Visited.insert(SuccBB)) {
Dan Gohman41375a32012-05-08 23:39:44 +00001894 TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
1895 SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001896 BBStates[CurrBB].addSucc(SuccBB);
Dan Gohman41375a32012-05-08 23:39:44 +00001897 BBState &SuccStates = BBStates[SuccBB];
1898 SuccStates.addPred(CurrBB);
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001899 OnStack.insert(SuccBB);
Dan Gohmana53a12c2011-12-12 19:42:25 +00001900 goto dfs_next_succ;
1901 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001902
1903 if (!OnStack.count(SuccBB)) {
1904 BBStates[CurrBB].addSucc(SuccBB);
1905 BBStates[SuccBB].addPred(CurrBB);
1906 }
Dan Gohmana53a12c2011-12-12 19:42:25 +00001907 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001908 OnStack.erase(CurrBB);
1909 PostOrder.push_back(CurrBB);
1910 SuccStack.pop_back();
Dan Gohmana53a12c2011-12-12 19:42:25 +00001911 } while (!SuccStack.empty());
1912
1913 Visited.clear();
1914
Dan Gohmana53a12c2011-12-12 19:42:25 +00001915 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001916 // Functions may have many exits, and there also blocks which we treat
1917 // as exits due to ignored edges.
1918 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
1919 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
1920 BasicBlock *ExitBB = I;
1921 BBState &MyStates = BBStates[ExitBB];
1922 if (!MyStates.isExit())
1923 continue;
1924
Dan Gohmandae33492012-04-27 18:56:31 +00001925 MyStates.SetAsExit();
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001926
1927 PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00001928 Visited.insert(ExitBB);
1929 while (!PredStack.empty()) {
1930 reverse_dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001931 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
1932 while (PredStack.back().second != PE) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00001933 BasicBlock *BB = *PredStack.back().second++;
Dan Gohmana53a12c2011-12-12 19:42:25 +00001934 if (Visited.insert(BB)) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001935 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00001936 goto reverse_dfs_next_succ;
1937 }
1938 }
1939 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
1940 }
1941 }
1942}
1943
Michael Gottesman97e3df02013-01-14 00:35:14 +00001944// Visit the function both top-down and bottom-up.
John McCalld935e9c2011-06-15 23:37:01 +00001945bool
1946ObjCARCOpt::Visit(Function &F,
1947 DenseMap<const BasicBlock *, BBState> &BBStates,
1948 MapVector<Value *, RRInfo> &Retains,
1949 DenseMap<Value *, RRInfo> &Releases) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00001950
1951 // Use reverse-postorder traversals, because we magically know that loops
1952 // will be well behaved, i.e. they won't repeatedly call retain on a single
1953 // pointer without doing a release. We can't use the ReversePostOrderTraversal
1954 // class here because we want the reverse-CFG postorder to consider each
1955 // function exit point, and we want to ignore selected cycle edges.
1956 SmallVector<BasicBlock *, 16> PostOrder;
1957 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001958 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
1959 NoObjCARCExceptionsMDKind,
1960 BBStates);
Dan Gohmana53a12c2011-12-12 19:42:25 +00001961
1962 // Use reverse-postorder on the reverse CFG for bottom-up.
John McCalld935e9c2011-06-15 23:37:01 +00001963 bool BottomUpNestingDetected = false;
Dan Gohmanc57b58c2011-08-18 21:27:42 +00001964 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
Dan Gohmana53a12c2011-12-12 19:42:25 +00001965 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
1966 I != E; ++I)
1967 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
John McCalld935e9c2011-06-15 23:37:01 +00001968
Dan Gohmana53a12c2011-12-12 19:42:25 +00001969 // Use reverse-postorder for top-down.
John McCalld935e9c2011-06-15 23:37:01 +00001970 bool TopDownNestingDetected = false;
Dan Gohmana53a12c2011-12-12 19:42:25 +00001971 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
1972 PostOrder.rbegin(), E = PostOrder.rend();
1973 I != E; ++I)
1974 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
John McCalld935e9c2011-06-15 23:37:01 +00001975
1976 return TopDownNestingDetected && BottomUpNestingDetected;
1977}
1978
Michael Gottesman97e3df02013-01-14 00:35:14 +00001979/// Move the calls in RetainsToMove and ReleasesToMove.
John McCalld935e9c2011-06-15 23:37:01 +00001980void ObjCARCOpt::MoveCalls(Value *Arg,
1981 RRInfo &RetainsToMove,
1982 RRInfo &ReleasesToMove,
1983 MapVector<Value *, RRInfo> &Retains,
1984 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman6320f522011-07-22 22:29:21 +00001985 SmallVectorImpl<Instruction *> &DeadInsts,
1986 Module *M) {
Chris Lattner229907c2011-07-18 04:54:35 +00001987 Type *ArgTy = Arg->getType();
Dan Gohman6320f522011-07-22 22:29:21 +00001988 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
John McCalld935e9c2011-06-15 23:37:01 +00001989
1990 // Insert the new retain and release calls.
1991 for (SmallPtrSet<Instruction *, 2>::const_iterator
1992 PI = ReleasesToMove.ReverseInsertPts.begin(),
1993 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
1994 Instruction *InsertPt = *PI;
1995 Value *MyArg = ArgTy == ParamTy ? Arg :
1996 new BitCastInst(Arg, ParamTy, "", InsertPt);
1997 CallInst *Call =
1998 CallInst::Create(RetainsToMove.IsRetainBlock ?
Dan Gohman6320f522011-07-22 22:29:21 +00001999 getRetainBlockCallee(M) : getRetainCallee(M),
John McCalld935e9c2011-06-15 23:37:01 +00002000 MyArg, "", InsertPt);
2001 Call->setDoesNotThrow();
Dan Gohman728db492012-01-13 00:39:07 +00002002 if (RetainsToMove.IsRetainBlock)
Dan Gohmana7107f92011-10-17 22:53:25 +00002003 Call->setMetadata(CopyOnEscapeMDKind,
2004 MDNode::get(M->getContext(), ArrayRef<Value *>()));
Dan Gohman728db492012-01-13 00:39:07 +00002005 else
John McCalld935e9c2011-06-15 23:37:01 +00002006 Call->setTailCall();
Michael Gottesmanc189a392013-01-09 19:23:24 +00002007
2008 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Inserting new Release: " << *Call
2009 << "\n"
2010 " At insertion point: " << *InsertPt
2011 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002012 }
2013 for (SmallPtrSet<Instruction *, 2>::const_iterator
2014 PI = RetainsToMove.ReverseInsertPts.begin(),
2015 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00002016 Instruction *InsertPt = *PI;
2017 Value *MyArg = ArgTy == ParamTy ? Arg :
2018 new BitCastInst(Arg, ParamTy, "", InsertPt);
2019 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
2020 "", InsertPt);
2021 // Attach a clang.imprecise_release metadata tag, if appropriate.
2022 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
2023 Call->setMetadata(ImpreciseReleaseMDKind, M);
2024 Call->setDoesNotThrow();
2025 if (ReleasesToMove.IsTailCallRelease)
2026 Call->setTailCall();
Michael Gottesmanc189a392013-01-09 19:23:24 +00002027
2028 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Inserting new Retain: " << *Call
2029 << "\n"
2030 " At insertion point: " << *InsertPt
2031 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002032 }
2033
2034 // Delete the original retain and release calls.
2035 for (SmallPtrSet<Instruction *, 2>::const_iterator
2036 AI = RetainsToMove.Calls.begin(),
2037 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
2038 Instruction *OrigRetain = *AI;
2039 Retains.blot(OrigRetain);
2040 DeadInsts.push_back(OrigRetain);
Michael Gottesmanc189a392013-01-09 19:23:24 +00002041 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Deleting retain: " << *OrigRetain <<
2042 "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002043 }
2044 for (SmallPtrSet<Instruction *, 2>::const_iterator
2045 AI = ReleasesToMove.Calls.begin(),
2046 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
2047 Instruction *OrigRelease = *AI;
2048 Releases.erase(OrigRelease);
2049 DeadInsts.push_back(OrigRelease);
Michael Gottesmanc189a392013-01-09 19:23:24 +00002050 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Deleting release: " << *OrigRelease
2051 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002052 }
2053}
2054
Michael Gottesman9de6f962013-01-22 21:49:00 +00002055bool
2056ObjCARCOpt::ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState>
2057 &BBStates,
2058 MapVector<Value *, RRInfo> &Retains,
2059 DenseMap<Value *, RRInfo> &Releases,
2060 Module *M,
2061 SmallVector<Instruction *, 4> &NewRetains,
2062 SmallVector<Instruction *, 4> &NewReleases,
2063 SmallVector<Instruction *, 8> &DeadInsts,
2064 RRInfo &RetainsToMove,
2065 RRInfo &ReleasesToMove,
2066 Value *Arg,
2067 bool KnownSafe,
2068 bool &AnyPairsCompletelyEliminated) {
2069 // If a pair happens in a region where it is known that the reference count
2070 // is already incremented, we can similarly ignore possible decrements.
2071 bool KnownSafeTD = true, KnownSafeBU = true;
2072
2073 // Connect the dots between the top-down-collected RetainsToMove and
2074 // bottom-up-collected ReleasesToMove to form sets of related calls.
2075 // This is an iterative process so that we connect multiple releases
2076 // to multiple retains if needed.
2077 unsigned OldDelta = 0;
2078 unsigned NewDelta = 0;
2079 unsigned OldCount = 0;
2080 unsigned NewCount = 0;
2081 bool FirstRelease = true;
2082 bool FirstRetain = true;
2083 for (;;) {
2084 for (SmallVectorImpl<Instruction *>::const_iterator
2085 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
2086 Instruction *NewRetain = *NI;
2087 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
2088 assert(It != Retains.end());
2089 const RRInfo &NewRetainRRI = It->second;
2090 KnownSafeTD &= NewRetainRRI.KnownSafe;
2091 for (SmallPtrSet<Instruction *, 2>::const_iterator
2092 LI = NewRetainRRI.Calls.begin(),
2093 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
2094 Instruction *NewRetainRelease = *LI;
2095 DenseMap<Value *, RRInfo>::const_iterator Jt =
2096 Releases.find(NewRetainRelease);
2097 if (Jt == Releases.end())
2098 return false;
2099 const RRInfo &NewRetainReleaseRRI = Jt->second;
2100 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
2101 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
2102 OldDelta -=
2103 BBStates[NewRetainRelease->getParent()].GetAllPathCount();
2104
2105 // Merge the ReleaseMetadata and IsTailCallRelease values.
2106 if (FirstRelease) {
2107 ReleasesToMove.ReleaseMetadata =
2108 NewRetainReleaseRRI.ReleaseMetadata;
2109 ReleasesToMove.IsTailCallRelease =
2110 NewRetainReleaseRRI.IsTailCallRelease;
2111 FirstRelease = false;
2112 } else {
2113 if (ReleasesToMove.ReleaseMetadata !=
2114 NewRetainReleaseRRI.ReleaseMetadata)
2115 ReleasesToMove.ReleaseMetadata = 0;
2116 if (ReleasesToMove.IsTailCallRelease !=
2117 NewRetainReleaseRRI.IsTailCallRelease)
2118 ReleasesToMove.IsTailCallRelease = false;
2119 }
2120
2121 // Collect the optimal insertion points.
2122 if (!KnownSafe)
2123 for (SmallPtrSet<Instruction *, 2>::const_iterator
2124 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
2125 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
2126 RI != RE; ++RI) {
2127 Instruction *RIP = *RI;
2128 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
2129 NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
2130 }
2131 NewReleases.push_back(NewRetainRelease);
2132 }
2133 }
2134 }
2135 NewRetains.clear();
2136 if (NewReleases.empty()) break;
2137
2138 // Back the other way.
2139 for (SmallVectorImpl<Instruction *>::const_iterator
2140 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
2141 Instruction *NewRelease = *NI;
2142 DenseMap<Value *, RRInfo>::const_iterator It =
2143 Releases.find(NewRelease);
2144 assert(It != Releases.end());
2145 const RRInfo &NewReleaseRRI = It->second;
2146 KnownSafeBU &= NewReleaseRRI.KnownSafe;
2147 for (SmallPtrSet<Instruction *, 2>::const_iterator
2148 LI = NewReleaseRRI.Calls.begin(),
2149 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
2150 Instruction *NewReleaseRetain = *LI;
2151 MapVector<Value *, RRInfo>::const_iterator Jt =
2152 Retains.find(NewReleaseRetain);
2153 if (Jt == Retains.end())
2154 return false;
2155 const RRInfo &NewReleaseRetainRRI = Jt->second;
2156 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
2157 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
2158 unsigned PathCount =
2159 BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
2160 OldDelta += PathCount;
2161 OldCount += PathCount;
2162
2163 // Merge the IsRetainBlock values.
2164 if (FirstRetain) {
2165 RetainsToMove.IsRetainBlock = NewReleaseRetainRRI.IsRetainBlock;
2166 FirstRetain = false;
2167 } else if (ReleasesToMove.IsRetainBlock !=
2168 NewReleaseRetainRRI.IsRetainBlock)
2169 // It's not possible to merge the sequences if one uses
2170 // objc_retain and the other uses objc_retainBlock.
2171 return false;
2172
2173 // Collect the optimal insertion points.
2174 if (!KnownSafe)
2175 for (SmallPtrSet<Instruction *, 2>::const_iterator
2176 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
2177 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
2178 RI != RE; ++RI) {
2179 Instruction *RIP = *RI;
2180 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
2181 PathCount = BBStates[RIP->getParent()].GetAllPathCount();
2182 NewDelta += PathCount;
2183 NewCount += PathCount;
2184 }
2185 }
2186 NewRetains.push_back(NewReleaseRetain);
2187 }
2188 }
2189 }
2190 NewReleases.clear();
2191 if (NewRetains.empty()) break;
2192 }
2193
2194 // If the pointer is known incremented or nested, we can safely delete the
2195 // pair regardless of what's between them.
2196 if (KnownSafeTD || KnownSafeBU) {
2197 RetainsToMove.ReverseInsertPts.clear();
2198 ReleasesToMove.ReverseInsertPts.clear();
2199 NewCount = 0;
2200 } else {
2201 // Determine whether the new insertion points we computed preserve the
2202 // balance of retain and release calls through the program.
2203 // TODO: If the fully aggressive solution isn't valid, try to find a
2204 // less aggressive solution which is.
2205 if (NewDelta != 0)
2206 return false;
2207 }
2208
2209 // Determine whether the original call points are balanced in the retain and
2210 // release calls through the program. If not, conservatively don't touch
2211 // them.
2212 // TODO: It's theoretically possible to do code motion in this case, as
2213 // long as the existing imbalances are maintained.
2214 if (OldDelta != 0)
2215 return false;
2216
2217 Changed = true;
2218 assert(OldCount != 0 && "Unreachable code?");
2219 NumRRs += OldCount - NewCount;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002220 // Set to true if we completely removed any RR pairs.
Michael Gottesman8b5515f2013-01-22 21:53:43 +00002221 AnyPairsCompletelyEliminated = NewCount == 0;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002222
2223 // We can move calls!
2224 return true;
2225}
2226
Michael Gottesman97e3df02013-01-14 00:35:14 +00002227/// Identify pairings between the retains and releases, and delete and/or move
2228/// them.
John McCalld935e9c2011-06-15 23:37:01 +00002229bool
2230ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
2231 &BBStates,
2232 MapVector<Value *, RRInfo> &Retains,
Dan Gohman6320f522011-07-22 22:29:21 +00002233 DenseMap<Value *, RRInfo> &Releases,
2234 Module *M) {
John McCalld935e9c2011-06-15 23:37:01 +00002235 bool AnyPairsCompletelyEliminated = false;
2236 RRInfo RetainsToMove;
2237 RRInfo ReleasesToMove;
2238 SmallVector<Instruction *, 4> NewRetains;
2239 SmallVector<Instruction *, 4> NewReleases;
2240 SmallVector<Instruction *, 8> DeadInsts;
2241
Dan Gohman670f9372012-04-13 18:57:48 +00002242 // Visit each retain.
John McCalld935e9c2011-06-15 23:37:01 +00002243 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
Dan Gohman2053a5d2011-09-29 22:25:23 +00002244 E = Retains.end(); I != E; ++I) {
2245 Value *V = I->first;
John McCalld935e9c2011-06-15 23:37:01 +00002246 if (!V) continue; // blotted
2247
2248 Instruction *Retain = cast<Instruction>(V);
Michael Gottesmanc189a392013-01-09 19:23:24 +00002249
2250 DEBUG(dbgs() << "ObjCARCOpt::PerformCodePlacement: Visiting: " << *Retain
2251 << "\n");
2252
John McCalld935e9c2011-06-15 23:37:01 +00002253 Value *Arg = GetObjCArg(Retain);
2254
Dan Gohman728db492012-01-13 00:39:07 +00002255 // If the object being released is in static or stack storage, we know it's
John McCalld935e9c2011-06-15 23:37:01 +00002256 // not being managed by ObjC reference counting, so we can delete pairs
2257 // regardless of what possible decrements or uses lie between them.
Dan Gohman728db492012-01-13 00:39:07 +00002258 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
Dan Gohman41375a32012-05-08 23:39:44 +00002259
Dan Gohman56e1cef2011-08-22 17:29:11 +00002260 // A constant pointer can't be pointing to an object on the heap. It may
2261 // be reference-counted, but it won't be deleted.
2262 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
2263 if (const GlobalVariable *GV =
2264 dyn_cast<GlobalVariable>(
2265 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
2266 if (GV->isConstant())
2267 KnownSafe = true;
2268
John McCalld935e9c2011-06-15 23:37:01 +00002269 // Connect the dots between the top-down-collected RetainsToMove and
2270 // bottom-up-collected ReleasesToMove to form sets of related calls.
John McCalld935e9c2011-06-15 23:37:01 +00002271 NewRetains.push_back(Retain);
Michael Gottesman9de6f962013-01-22 21:49:00 +00002272 bool PerformMoveCalls =
2273 ConnectTDBUTraversals(BBStates, Retains, Releases, M, NewRetains,
2274 NewReleases, DeadInsts, RetainsToMove,
2275 ReleasesToMove, Arg, KnownSafe,
2276 AnyPairsCompletelyEliminated);
John McCalld935e9c2011-06-15 23:37:01 +00002277
Michael Gottesman9de6f962013-01-22 21:49:00 +00002278 if (PerformMoveCalls) {
2279 // Ok, everything checks out and we're all set. Let's move/delete some
2280 // code!
2281 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
2282 Retains, Releases, DeadInsts, M);
John McCalld935e9c2011-06-15 23:37:01 +00002283 }
2284
Michael Gottesman9de6f962013-01-22 21:49:00 +00002285 // Clean up state for next retain.
John McCalld935e9c2011-06-15 23:37:01 +00002286 NewReleases.clear();
2287 NewRetains.clear();
2288 RetainsToMove.clear();
2289 ReleasesToMove.clear();
2290 }
2291
2292 // Now that we're done moving everything, we can delete the newly dead
2293 // instructions, as we no longer need them as insert points.
2294 while (!DeadInsts.empty())
2295 EraseInstruction(DeadInsts.pop_back_val());
2296
2297 return AnyPairsCompletelyEliminated;
2298}
2299
Michael Gottesman97e3df02013-01-14 00:35:14 +00002300/// Weak pointer optimizations.
John McCalld935e9c2011-06-15 23:37:01 +00002301void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
2302 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
2303 // itself because it uses AliasAnalysis and we need to do provenance
2304 // queries instead.
2305 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2306 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +00002307
Michael Gottesman9f848ae2013-01-04 21:29:57 +00002308 DEBUG(dbgs() << "ObjCARCOpt::OptimizeWeakCalls: Visiting: " << *Inst <<
Michael Gottesman3f146e22013-01-01 16:05:48 +00002309 "\n");
2310
John McCalld935e9c2011-06-15 23:37:01 +00002311 InstructionClass Class = GetBasicInstructionClass(Inst);
2312 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
2313 continue;
2314
2315 // Delete objc_loadWeak calls with no users.
2316 if (Class == IC_LoadWeak && Inst->use_empty()) {
2317 Inst->eraseFromParent();
2318 continue;
2319 }
2320
2321 // TODO: For now, just look for an earlier available version of this value
2322 // within the same block. Theoretically, we could do memdep-style non-local
2323 // analysis too, but that would want caching. A better approach would be to
2324 // use the technique that EarlyCSE uses.
2325 inst_iterator Current = llvm::prior(I);
2326 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
2327 for (BasicBlock::iterator B = CurrentBB->begin(),
2328 J = Current.getInstructionIterator();
2329 J != B; --J) {
2330 Instruction *EarlierInst = &*llvm::prior(J);
2331 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
2332 switch (EarlierClass) {
2333 case IC_LoadWeak:
2334 case IC_LoadWeakRetained: {
2335 // If this is loading from the same pointer, replace this load's value
2336 // with that one.
2337 CallInst *Call = cast<CallInst>(Inst);
2338 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2339 Value *Arg = Call->getArgOperand(0);
2340 Value *EarlierArg = EarlierCall->getArgOperand(0);
2341 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2342 case AliasAnalysis::MustAlias:
2343 Changed = true;
2344 // If the load has a builtin retain, insert a plain retain for it.
2345 if (Class == IC_LoadWeakRetained) {
2346 CallInst *CI =
2347 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
2348 "", Call);
2349 CI->setTailCall();
2350 }
2351 // Zap the fully redundant load.
2352 Call->replaceAllUsesWith(EarlierCall);
2353 Call->eraseFromParent();
2354 goto clobbered;
2355 case AliasAnalysis::MayAlias:
2356 case AliasAnalysis::PartialAlias:
2357 goto clobbered;
2358 case AliasAnalysis::NoAlias:
2359 break;
2360 }
2361 break;
2362 }
2363 case IC_StoreWeak:
2364 case IC_InitWeak: {
2365 // If this is storing to the same pointer and has the same size etc.
2366 // replace this load's value with the stored value.
2367 CallInst *Call = cast<CallInst>(Inst);
2368 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2369 Value *Arg = Call->getArgOperand(0);
2370 Value *EarlierArg = EarlierCall->getArgOperand(0);
2371 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2372 case AliasAnalysis::MustAlias:
2373 Changed = true;
2374 // If the load has a builtin retain, insert a plain retain for it.
2375 if (Class == IC_LoadWeakRetained) {
2376 CallInst *CI =
2377 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
2378 "", Call);
2379 CI->setTailCall();
2380 }
2381 // Zap the fully redundant load.
2382 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
2383 Call->eraseFromParent();
2384 goto clobbered;
2385 case AliasAnalysis::MayAlias:
2386 case AliasAnalysis::PartialAlias:
2387 goto clobbered;
2388 case AliasAnalysis::NoAlias:
2389 break;
2390 }
2391 break;
2392 }
2393 case IC_MoveWeak:
2394 case IC_CopyWeak:
2395 // TOOD: Grab the copied value.
2396 goto clobbered;
2397 case IC_AutoreleasepoolPush:
2398 case IC_None:
2399 case IC_User:
2400 // Weak pointers are only modified through the weak entry points
2401 // (and arbitrary calls, which could call the weak entry points).
2402 break;
2403 default:
2404 // Anything else could modify the weak pointer.
2405 goto clobbered;
2406 }
2407 }
2408 clobbered:;
2409 }
2410
2411 // Then, for each destroyWeak with an alloca operand, check to see if
2412 // the alloca and all its users can be zapped.
2413 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2414 Instruction *Inst = &*I++;
2415 InstructionClass Class = GetBasicInstructionClass(Inst);
2416 if (Class != IC_DestroyWeak)
2417 continue;
2418
2419 CallInst *Call = cast<CallInst>(Inst);
2420 Value *Arg = Call->getArgOperand(0);
2421 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
2422 for (Value::use_iterator UI = Alloca->use_begin(),
2423 UE = Alloca->use_end(); UI != UE; ++UI) {
Dan Gohmandae33492012-04-27 18:56:31 +00002424 const Instruction *UserInst = cast<Instruction>(*UI);
John McCalld935e9c2011-06-15 23:37:01 +00002425 switch (GetBasicInstructionClass(UserInst)) {
2426 case IC_InitWeak:
2427 case IC_StoreWeak:
2428 case IC_DestroyWeak:
2429 continue;
2430 default:
2431 goto done;
2432 }
2433 }
2434 Changed = true;
2435 for (Value::use_iterator UI = Alloca->use_begin(),
2436 UE = Alloca->use_end(); UI != UE; ) {
2437 CallInst *UserInst = cast<CallInst>(*UI++);
Dan Gohman14862c32012-05-18 22:17:29 +00002438 switch (GetBasicInstructionClass(UserInst)) {
2439 case IC_InitWeak:
2440 case IC_StoreWeak:
2441 // These functions return their second argument.
2442 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
2443 break;
2444 case IC_DestroyWeak:
2445 // No return value.
2446 break;
2447 default:
Dan Gohman9c97eea02012-05-21 17:41:28 +00002448 llvm_unreachable("alloca really is used!");
Dan Gohman14862c32012-05-18 22:17:29 +00002449 }
John McCalld935e9c2011-06-15 23:37:01 +00002450 UserInst->eraseFromParent();
2451 }
2452 Alloca->eraseFromParent();
2453 done:;
2454 }
2455 }
Michael Gottesman10426b52013-01-07 21:26:07 +00002456
Michael Gottesman9f848ae2013-01-04 21:29:57 +00002457 DEBUG(dbgs() << "ObjCARCOpt::OptimizeWeakCalls: Finished List.\n\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00002458
John McCalld935e9c2011-06-15 23:37:01 +00002459}
2460
Michael Gottesman97e3df02013-01-14 00:35:14 +00002461/// Identify program paths which execute sequences of retains and releases which
2462/// can be eliminated.
John McCalld935e9c2011-06-15 23:37:01 +00002463bool ObjCARCOpt::OptimizeSequences(Function &F) {
2464 /// Releases, Retains - These are used to store the results of the main flow
2465 /// analysis. These use Value* as the key instead of Instruction* so that the
2466 /// map stays valid when we get around to rewriting code and calls get
2467 /// replaced by arguments.
2468 DenseMap<Value *, RRInfo> Releases;
2469 MapVector<Value *, RRInfo> Retains;
2470
Michael Gottesman97e3df02013-01-14 00:35:14 +00002471 /// This is used during the traversal of the function to track the
John McCalld935e9c2011-06-15 23:37:01 +00002472 /// states for each identified object at each block.
2473 DenseMap<const BasicBlock *, BBState> BBStates;
2474
2475 // Analyze the CFG of the function, and all instructions.
2476 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
2477
2478 // Transform.
Dan Gohman6320f522011-07-22 22:29:21 +00002479 return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) &&
2480 NestingDetected;
John McCalld935e9c2011-06-15 23:37:01 +00002481}
2482
Michael Gottesman97e3df02013-01-14 00:35:14 +00002483/// Look for this pattern:
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00002484/// \code
John McCalld935e9c2011-06-15 23:37:01 +00002485/// %call = call i8* @something(...)
2486/// %2 = call i8* @objc_retain(i8* %call)
2487/// %3 = call i8* @objc_autorelease(i8* %2)
2488/// ret i8* %3
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00002489/// \endcode
John McCalld935e9c2011-06-15 23:37:01 +00002490/// And delete the retain and autorelease.
2491///
2492/// Otherwise if it's just this:
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00002493/// \code
John McCalld935e9c2011-06-15 23:37:01 +00002494/// %3 = call i8* @objc_autorelease(i8* %2)
2495/// ret i8* %3
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00002496/// \endcode
John McCalld935e9c2011-06-15 23:37:01 +00002497/// convert the autorelease to autoreleaseRV.
2498void ObjCARCOpt::OptimizeReturns(Function &F) {
2499 if (!F.getReturnType()->isPointerTy())
2500 return;
2501
2502 SmallPtrSet<Instruction *, 4> DependingInstructions;
2503 SmallPtrSet<const BasicBlock *, 4> Visited;
2504 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
2505 BasicBlock *BB = FI;
2506 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
Michael Gottesman3f146e22013-01-01 16:05:48 +00002507
Michael Gottesman9f848ae2013-01-04 21:29:57 +00002508 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Visiting: " << *Ret << "\n");
Michael Gottesman3f146e22013-01-01 16:05:48 +00002509
John McCalld935e9c2011-06-15 23:37:01 +00002510 if (!Ret) continue;
2511
2512 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
2513 FindDependencies(NeedsPositiveRetainCount, Arg,
2514 BB, Ret, DependingInstructions, Visited, PA);
2515 if (DependingInstructions.size() != 1)
2516 goto next_block;
2517
2518 {
2519 CallInst *Autorelease =
2520 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
2521 if (!Autorelease)
2522 goto next_block;
Dan Gohman41375a32012-05-08 23:39:44 +00002523 InstructionClass AutoreleaseClass = GetBasicInstructionClass(Autorelease);
John McCalld935e9c2011-06-15 23:37:01 +00002524 if (!IsAutorelease(AutoreleaseClass))
2525 goto next_block;
2526 if (GetObjCArg(Autorelease) != Arg)
2527 goto next_block;
2528
2529 DependingInstructions.clear();
2530 Visited.clear();
2531
2532 // Check that there is nothing that can affect the reference
2533 // count between the autorelease and the retain.
2534 FindDependencies(CanChangeRetainCount, Arg,
2535 BB, Autorelease, DependingInstructions, Visited, PA);
2536 if (DependingInstructions.size() != 1)
2537 goto next_block;
2538
2539 {
2540 CallInst *Retain =
2541 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
2542
2543 // Check that we found a retain with the same argument.
2544 if (!Retain ||
2545 !IsRetain(GetBasicInstructionClass(Retain)) ||
2546 GetObjCArg(Retain) != Arg)
2547 goto next_block;
2548
2549 DependingInstructions.clear();
2550 Visited.clear();
2551
2552 // Convert the autorelease to an autoreleaseRV, since it's
2553 // returning the value.
2554 if (AutoreleaseClass == IC_Autorelease) {
Michael Gottesmana6cb0182013-01-10 02:03:50 +00002555 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Converting autorelease "
2556 "=> autoreleaseRV since it's returning a value.\n"
2557 " In: " << *Autorelease
2558 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002559 Autorelease->setCalledFunction(getAutoreleaseRVCallee(F.getParent()));
Michael Gottesmana6cb0182013-01-10 02:03:50 +00002560 DEBUG(dbgs() << " Out: " << *Autorelease
2561 << "\n");
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00002562 Autorelease->setTailCall(); // Always tail call autoreleaseRV.
John McCalld935e9c2011-06-15 23:37:01 +00002563 AutoreleaseClass = IC_AutoreleaseRV;
2564 }
2565
2566 // Check that there is nothing that can affect the reference
2567 // count between the retain and the call.
Dan Gohman4ac148d2011-09-29 22:27:34 +00002568 // Note that Retain need not be in BB.
2569 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
John McCalld935e9c2011-06-15 23:37:01 +00002570 DependingInstructions, Visited, PA);
2571 if (DependingInstructions.size() != 1)
2572 goto next_block;
2573
2574 {
2575 CallInst *Call =
2576 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
2577
2578 // Check that the pointer is the return value of the call.
2579 if (!Call || Arg != Call)
2580 goto next_block;
2581
2582 // Check that the call is a regular call.
2583 InstructionClass Class = GetBasicInstructionClass(Call);
2584 if (Class != IC_CallOrUser && Class != IC_Call)
2585 goto next_block;
2586
2587 // If so, we can zap the retain and autorelease.
2588 Changed = true;
2589 ++NumRets;
Michael Gottesmand61a3b22013-01-07 00:04:56 +00002590 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Erasing: " << *Retain
2591 << "\n Erasing: "
2592 << *Autorelease << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002593 EraseInstruction(Retain);
2594 EraseInstruction(Autorelease);
2595 }
2596 }
2597 }
2598
2599 next_block:
2600 DependingInstructions.clear();
2601 Visited.clear();
2602 }
Michael Gottesman10426b52013-01-07 21:26:07 +00002603
Michael Gottesman9f848ae2013-01-04 21:29:57 +00002604 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Finished List.\n\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00002605
John McCalld935e9c2011-06-15 23:37:01 +00002606}
2607
2608bool ObjCARCOpt::doInitialization(Module &M) {
2609 if (!EnableARCOpts)
2610 return false;
2611
Dan Gohman670f9372012-04-13 18:57:48 +00002612 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanceaac7c2011-06-20 23:20:43 +00002613 Run = ModuleHasARC(M);
2614 if (!Run)
2615 return false;
2616
John McCalld935e9c2011-06-15 23:37:01 +00002617 // Identify the imprecise release metadata kind.
2618 ImpreciseReleaseMDKind =
2619 M.getContext().getMDKindID("clang.imprecise_release");
Dan Gohmana7107f92011-10-17 22:53:25 +00002620 CopyOnEscapeMDKind =
2621 M.getContext().getMDKindID("clang.arc.copy_on_escape");
Dan Gohman0155f302012-02-17 18:59:53 +00002622 NoObjCARCExceptionsMDKind =
2623 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
John McCalld935e9c2011-06-15 23:37:01 +00002624
John McCalld935e9c2011-06-15 23:37:01 +00002625 // Intuitively, objc_retain and others are nocapture, however in practice
2626 // they are not, because they return their argument value. And objc_release
Dan Gohmandae33492012-04-27 18:56:31 +00002627 // calls finalizers which can have arbitrary side effects.
John McCalld935e9c2011-06-15 23:37:01 +00002628
2629 // These are initialized lazily.
2630 RetainRVCallee = 0;
2631 AutoreleaseRVCallee = 0;
2632 ReleaseCallee = 0;
2633 RetainCallee = 0;
Dan Gohman6320f522011-07-22 22:29:21 +00002634 RetainBlockCallee = 0;
John McCalld935e9c2011-06-15 23:37:01 +00002635 AutoreleaseCallee = 0;
2636
2637 return false;
2638}
2639
2640bool ObjCARCOpt::runOnFunction(Function &F) {
2641 if (!EnableARCOpts)
2642 return false;
2643
Dan Gohmanceaac7c2011-06-20 23:20:43 +00002644 // If nothing in the Module uses ARC, don't do anything.
2645 if (!Run)
2646 return false;
2647
John McCalld935e9c2011-06-15 23:37:01 +00002648 Changed = false;
2649
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00002650 DEBUG(dbgs() << "ObjCARCOpt: Visiting Function: " << F.getName() << "\n");
2651
John McCalld935e9c2011-06-15 23:37:01 +00002652 PA.setAA(&getAnalysis<AliasAnalysis>());
2653
2654 // This pass performs several distinct transformations. As a compile-time aid
2655 // when compiling code that isn't ObjC, skip these if the relevant ObjC
2656 // library functions aren't declared.
2657
2658 // Preliminary optimizations. This also computs UsedInThisFunction.
2659 OptimizeIndividualCalls(F);
2660
2661 // Optimizations for weak pointers.
2662 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
2663 (1 << IC_LoadWeakRetained) |
2664 (1 << IC_StoreWeak) |
2665 (1 << IC_InitWeak) |
2666 (1 << IC_CopyWeak) |
2667 (1 << IC_MoveWeak) |
2668 (1 << IC_DestroyWeak)))
2669 OptimizeWeakCalls(F);
2670
2671 // Optimizations for retain+release pairs.
2672 if (UsedInThisFunction & ((1 << IC_Retain) |
2673 (1 << IC_RetainRV) |
2674 (1 << IC_RetainBlock)))
2675 if (UsedInThisFunction & (1 << IC_Release))
2676 // Run OptimizeSequences until it either stops making changes or
2677 // no retain+release pair nesting is detected.
2678 while (OptimizeSequences(F)) {}
2679
2680 // Optimizations if objc_autorelease is used.
Dan Gohman41375a32012-05-08 23:39:44 +00002681 if (UsedInThisFunction & ((1 << IC_Autorelease) |
2682 (1 << IC_AutoreleaseRV)))
John McCalld935e9c2011-06-15 23:37:01 +00002683 OptimizeReturns(F);
2684
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00002685 DEBUG(dbgs() << "\n");
2686
John McCalld935e9c2011-06-15 23:37:01 +00002687 return Changed;
2688}
2689
2690void ObjCARCOpt::releaseMemory() {
2691 PA.clear();
2692}
2693
Michael Gottesman97e3df02013-01-14 00:35:14 +00002694/// @}
2695///