blob: d2d8325d1fcf1013ceecbad2e92c3ac8eee6ff8b [file] [log] [blame]
Michael Gottesman79d8d812013-01-28 01:35:51 +00001//===- ObjCARCOpts.cpp - ObjC ARC Optimization ----------------------------===//
John McCalld935e9c2011-06-15 23:37:01 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Michael Gottesman97e3df02013-01-14 00:35:14 +00009/// \file
10/// This file defines ObjC ARC optimizations. ARC stands for Automatic
11/// Reference Counting and is a system for managing reference counts for objects
12/// in Objective C.
13///
14/// The optimizations performed include elimination of redundant, partially
15/// redundant, and inconsequential reference count operations, elimination of
Michael Gottesman697d8b92013-02-07 04:12:57 +000016/// redundant weak pointer operations, and numerous minor simplifications.
Michael Gottesman97e3df02013-01-14 00:35:14 +000017///
18/// WARNING: This file knows about certain library functions. It recognizes them
19/// by name, and hardwires knowledge of their semantics.
20///
21/// WARNING: This file knows about how certain Objective-C library functions are
22/// used. Naive LLVM IR transformations which would otherwise be
23/// behavior-preserving may break these assumptions.
24///
John McCalld935e9c2011-06-15 23:37:01 +000025//===----------------------------------------------------------------------===//
26
Michael Gottesman08904e32013-01-28 03:28:38 +000027#define DEBUG_TYPE "objc-arc-opts"
28#include "ObjCARC.h"
Michael Gottesman278266f2013-01-29 04:20:52 +000029#include "DependencyAnalysis.h"
Michael Gottesman294e7da2013-01-28 05:51:54 +000030#include "ObjCARCAliasAnalysis.h"
Michael Gottesman778138e2013-01-29 03:03:03 +000031#include "ProvenanceAnalysis.h"
John McCalld935e9c2011-06-15 23:37:01 +000032#include "llvm/ADT/DenseMap.h"
Michael Gottesmanfa0939f2013-01-28 04:12:07 +000033#include "llvm/ADT/STLExtras.h"
Michael Gottesman778138e2013-01-29 03:03:03 +000034#include "llvm/ADT/SmallPtrSet.h"
Michael Gottesman278266f2013-01-29 04:20:52 +000035#include "llvm/ADT/Statistic.h"
Michael Gottesmancd4de0f2013-03-26 00:42:09 +000036#include "llvm/IR/IRBuilder.h"
Michael Gottesman278266f2013-01-29 04:20:52 +000037#include "llvm/IR/LLVMContext.h"
Michael Gottesman778138e2013-01-29 03:03:03 +000038#include "llvm/Support/CFG.h"
Michael Gottesman13a5f1a2013-01-29 04:51:59 +000039#include "llvm/Support/Debug.h"
Timur Iskhodzhanov5d7ff002013-01-29 09:09:27 +000040#include "llvm/Support/raw_ostream.h"
Michael Gottesmanfa0939f2013-01-28 04:12:07 +000041
John McCalld935e9c2011-06-15 23:37:01 +000042using namespace llvm;
Michael Gottesman08904e32013-01-28 03:28:38 +000043using namespace llvm::objcarc;
John McCalld935e9c2011-06-15 23:37:01 +000044
Michael Gottesman97e3df02013-01-14 00:35:14 +000045/// \defgroup MiscUtils Miscellaneous utilities that are not ARC specific.
46/// @{
John McCalld935e9c2011-06-15 23:37:01 +000047
48namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +000049 /// \brief An associative container with fast insertion-order (deterministic)
50 /// iteration over its elements. Plus the special blot operation.
John McCalld935e9c2011-06-15 23:37:01 +000051 template<class KeyT, class ValueT>
52 class MapVector {
Michael Gottesman97e3df02013-01-14 00:35:14 +000053 /// Map keys to indices in Vector.
John McCalld935e9c2011-06-15 23:37:01 +000054 typedef DenseMap<KeyT, size_t> MapTy;
55 MapTy Map;
56
John McCalld935e9c2011-06-15 23:37:01 +000057 typedef std::vector<std::pair<KeyT, ValueT> > VectorTy;
Michael Gottesman97e3df02013-01-14 00:35:14 +000058 /// Keys and values.
John McCalld935e9c2011-06-15 23:37:01 +000059 VectorTy Vector;
60
61 public:
62 typedef typename VectorTy::iterator iterator;
63 typedef typename VectorTy::const_iterator const_iterator;
64 iterator begin() { return Vector.begin(); }
65 iterator end() { return Vector.end(); }
66 const_iterator begin() const { return Vector.begin(); }
67 const_iterator end() const { return Vector.end(); }
68
69#ifdef XDEBUG
70 ~MapVector() {
71 assert(Vector.size() >= Map.size()); // May differ due to blotting.
72 for (typename MapTy::const_iterator I = Map.begin(), E = Map.end();
73 I != E; ++I) {
74 assert(I->second < Vector.size());
75 assert(Vector[I->second].first == I->first);
76 }
77 for (typename VectorTy::const_iterator I = Vector.begin(),
78 E = Vector.end(); I != E; ++I)
79 assert(!I->first ||
80 (Map.count(I->first) &&
81 Map[I->first] == size_t(I - Vector.begin())));
82 }
83#endif
84
Dan Gohman55b06742012-03-02 01:13:53 +000085 ValueT &operator[](const KeyT &Arg) {
John McCalld935e9c2011-06-15 23:37:01 +000086 std::pair<typename MapTy::iterator, bool> Pair =
87 Map.insert(std::make_pair(Arg, size_t(0)));
88 if (Pair.second) {
Dan Gohman55b06742012-03-02 01:13:53 +000089 size_t Num = Vector.size();
90 Pair.first->second = Num;
John McCalld935e9c2011-06-15 23:37:01 +000091 Vector.push_back(std::make_pair(Arg, ValueT()));
Dan Gohman55b06742012-03-02 01:13:53 +000092 return Vector[Num].second;
John McCalld935e9c2011-06-15 23:37:01 +000093 }
94 return Vector[Pair.first->second].second;
95 }
96
97 std::pair<iterator, bool>
98 insert(const std::pair<KeyT, ValueT> &InsertPair) {
99 std::pair<typename MapTy::iterator, bool> Pair =
100 Map.insert(std::make_pair(InsertPair.first, size_t(0)));
101 if (Pair.second) {
Dan Gohman55b06742012-03-02 01:13:53 +0000102 size_t Num = Vector.size();
103 Pair.first->second = Num;
John McCalld935e9c2011-06-15 23:37:01 +0000104 Vector.push_back(InsertPair);
Dan Gohman55b06742012-03-02 01:13:53 +0000105 return std::make_pair(Vector.begin() + Num, true);
John McCalld935e9c2011-06-15 23:37:01 +0000106 }
107 return std::make_pair(Vector.begin() + Pair.first->second, false);
108 }
109
Dan Gohman55b06742012-03-02 01:13:53 +0000110 const_iterator find(const KeyT &Key) const {
John McCalld935e9c2011-06-15 23:37:01 +0000111 typename MapTy::const_iterator It = Map.find(Key);
112 if (It == Map.end()) return Vector.end();
113 return Vector.begin() + It->second;
114 }
115
Michael Gottesman97e3df02013-01-14 00:35:14 +0000116 /// This is similar to erase, but instead of removing the element from the
117 /// vector, it just zeros out the key in the vector. This leaves iterators
118 /// intact, but clients must be prepared for zeroed-out keys when iterating.
Dan Gohman55b06742012-03-02 01:13:53 +0000119 void blot(const KeyT &Key) {
John McCalld935e9c2011-06-15 23:37:01 +0000120 typename MapTy::iterator It = Map.find(Key);
121 if (It == Map.end()) return;
122 Vector[It->second].first = KeyT();
123 Map.erase(It);
124 }
125
126 void clear() {
127 Map.clear();
128 Vector.clear();
129 }
130 };
131}
132
Michael Gottesman97e3df02013-01-14 00:35:14 +0000133/// @}
134///
135/// \defgroup ARCUtilities Utility declarations/definitions specific to ARC.
136/// @{
John McCalld935e9c2011-06-15 23:37:01 +0000137
Michael Gottesman97e3df02013-01-14 00:35:14 +0000138/// \brief This is similar to StripPointerCastsAndObjCCalls but it stops as soon
139/// as it finds a value with multiple uses.
John McCalld935e9c2011-06-15 23:37:01 +0000140static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
141 if (Arg->hasOneUse()) {
142 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
143 return FindSingleUseIdentifiedObject(BC->getOperand(0));
144 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
145 if (GEP->hasAllZeroIndices())
146 return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
147 if (IsForwarding(GetBasicInstructionClass(Arg)))
148 return FindSingleUseIdentifiedObject(
149 cast<CallInst>(Arg)->getArgOperand(0));
150 if (!IsObjCIdentifiedObject(Arg))
151 return 0;
152 return Arg;
153 }
154
Dan Gohman41375a32012-05-08 23:39:44 +0000155 // If we found an identifiable object but it has multiple uses, but they are
156 // trivial uses, we can still consider this to be a single-use value.
John McCalld935e9c2011-06-15 23:37:01 +0000157 if (IsObjCIdentifiedObject(Arg)) {
158 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
159 UI != UE; ++UI) {
160 const User *U = *UI;
161 if (!U->use_empty() || StripPointerCastsAndObjCCalls(U) != Arg)
162 return 0;
163 }
164
165 return Arg;
166 }
167
168 return 0;
169}
170
Michael Gottesman774d2c02013-01-29 21:00:52 +0000171/// \brief Test whether the given retainable object pointer escapes.
Michael Gottesman97e3df02013-01-14 00:35:14 +0000172///
173/// This differs from regular escape analysis in that a use as an
174/// argument to a call is not considered an escape.
175///
Michael Gottesman774d2c02013-01-29 21:00:52 +0000176static bool DoesRetainableObjPtrEscape(const User *Ptr) {
Michael Gottesman774d2c02013-01-29 21:00:52 +0000177 DEBUG(dbgs() << "DoesRetainableObjPtrEscape: Target: " << *Ptr << "\n");
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000178
Dan Gohman728db492012-01-13 00:39:07 +0000179 // Walk the def-use chains.
180 SmallVector<const Value *, 4> Worklist;
Michael Gottesman774d2c02013-01-29 21:00:52 +0000181 Worklist.push_back(Ptr);
182 // If Ptr has any operands add them as well.
Michael Gottesman23cda0c2013-01-29 21:07:53 +0000183 for (User::const_op_iterator I = Ptr->op_begin(), E = Ptr->op_end(); I != E;
184 ++I) {
Michael Gottesman774d2c02013-01-29 21:00:52 +0000185 Worklist.push_back(*I);
186 }
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000187
188 // Ensure we do not visit any value twice.
Michael Gottesman774d2c02013-01-29 21:00:52 +0000189 SmallPtrSet<const Value *, 8> VisitedSet;
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000190
Dan Gohman728db492012-01-13 00:39:07 +0000191 do {
192 const Value *V = Worklist.pop_back_val();
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000193
Michael Gottesman89279f82013-04-05 18:10:41 +0000194 DEBUG(dbgs() << "Visiting: " << *V << "\n");
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000195
Dan Gohman728db492012-01-13 00:39:07 +0000196 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
197 UI != UE; ++UI) {
198 const User *UUser = *UI;
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000199
Michael Gottesman89279f82013-04-05 18:10:41 +0000200 DEBUG(dbgs() << "User: " << *UUser << "\n");
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000201
Dan Gohman728db492012-01-13 00:39:07 +0000202 // Special - Use by a call (callee or argument) is not considered
203 // to be an escape.
Dan Gohmane1e352a2012-04-13 18:28:58 +0000204 switch (GetBasicInstructionClass(UUser)) {
205 case IC_StoreWeak:
206 case IC_InitWeak:
207 case IC_StoreStrong:
208 case IC_Autorelease:
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000209 case IC_AutoreleaseRV: {
Michael Gottesman89279f82013-04-05 18:10:41 +0000210 DEBUG(dbgs() << "User copies pointer arguments. Pointer Escapes!\n");
Dan Gohmane1e352a2012-04-13 18:28:58 +0000211 // These special functions make copies of their pointer arguments.
212 return true;
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000213 }
John McCall20182ac2013-03-22 21:38:36 +0000214 case IC_IntrinsicUser:
215 // Use by the use intrinsic is not an escape.
216 continue;
Dan Gohmane1e352a2012-04-13 18:28:58 +0000217 case IC_User:
218 case IC_None:
219 // Use by an instruction which copies the value is an escape if the
220 // result is an escape.
221 if (isa<BitCastInst>(UUser) || isa<GetElementPtrInst>(UUser) ||
222 isa<PHINode>(UUser) || isa<SelectInst>(UUser)) {
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000223
Michael Gottesmanf4b77612013-02-23 00:31:32 +0000224 if (VisitedSet.insert(UUser)) {
Michael Gottesman89279f82013-04-05 18:10:41 +0000225 DEBUG(dbgs() << "User copies value. Ptr escapes if result escapes."
226 " Adding to list.\n");
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000227 Worklist.push_back(UUser);
228 } else {
Michael Gottesman89279f82013-04-05 18:10:41 +0000229 DEBUG(dbgs() << "Already visited node.\n");
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000230 }
Dan Gohmane1e352a2012-04-13 18:28:58 +0000231 continue;
232 }
233 // Use by a load is not an escape.
234 if (isa<LoadInst>(UUser))
235 continue;
236 // Use by a store is not an escape if the use is the address.
237 if (const StoreInst *SI = dyn_cast<StoreInst>(UUser))
238 if (V != SI->getValueOperand())
239 continue;
240 break;
241 default:
242 // Regular calls and other stuff are not considered escapes.
Dan Gohman728db492012-01-13 00:39:07 +0000243 continue;
244 }
Dan Gohmaneb6e0152012-02-13 22:57:02 +0000245 // Otherwise, conservatively assume an escape.
Michael Gottesman89279f82013-04-05 18:10:41 +0000246 DEBUG(dbgs() << "Assuming ptr escapes.\n");
Dan Gohman728db492012-01-13 00:39:07 +0000247 return true;
248 }
249 } while (!Worklist.empty());
250
251 // No escapes found.
Michael Gottesman89279f82013-04-05 18:10:41 +0000252 DEBUG(dbgs() << "Ptr does not escape.\n");
Dan Gohman728db492012-01-13 00:39:07 +0000253 return false;
254}
255
Michael Gottesman97e3df02013-01-14 00:35:14 +0000256/// @}
257///
Michael Gottesman97e3df02013-01-14 00:35:14 +0000258/// \defgroup ARCOpt ARC Optimization.
259/// @{
John McCalld935e9c2011-06-15 23:37:01 +0000260
261// TODO: On code like this:
262//
263// objc_retain(%x)
264// stuff_that_cannot_release()
265// objc_autorelease(%x)
266// stuff_that_cannot_release()
267// objc_retain(%x)
268// stuff_that_cannot_release()
269// objc_autorelease(%x)
270//
271// The second retain and autorelease can be deleted.
272
273// TODO: It should be possible to delete
274// objc_autoreleasePoolPush and objc_autoreleasePoolPop
275// pairs if nothing is actually autoreleased between them. Also, autorelease
276// calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
277// after inlining) can be turned into plain release calls.
278
279// TODO: Critical-edge splitting. If the optimial insertion point is
280// a critical edge, the current algorithm has to fail, because it doesn't
281// know how to split edges. It should be possible to make the optimizer
282// think in terms of edges, rather than blocks, and then split critical
283// edges on demand.
284
285// TODO: OptimizeSequences could generalized to be Interprocedural.
286
287// TODO: Recognize that a bunch of other objc runtime calls have
288// non-escaping arguments and non-releasing arguments, and may be
289// non-autoreleasing.
290
291// TODO: Sink autorelease calls as far as possible. Unfortunately we
292// usually can't sink them past other calls, which would be the main
293// case where it would be useful.
294
Dan Gohmanb3894012011-08-19 00:26:36 +0000295// TODO: The pointer returned from objc_loadWeakRetained is retained.
296
297// TODO: Delete release+retain pairs (rare).
Dan Gohmanceaac7c2011-06-20 23:20:43 +0000298
John McCalld935e9c2011-06-15 23:37:01 +0000299STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
300STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
301STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
302STATISTIC(NumRets, "Number of return value forwarding "
303 "retain+autoreleaes eliminated");
304STATISTIC(NumRRs, "Number of retain+release paths eliminated");
305STATISTIC(NumPeeps, "Number of calls peephole-optimized");
Michael Gottesman9c118152013-04-29 06:16:57 +0000306STATISTIC(NumRetainsBeforeOpt,
307 "Number of retains before optimization.");
308STATISTIC(NumReleasesBeforeOpt,
309 "Number of releases before optimization.");
Michael Gottesman03cf3c82013-04-29 07:29:08 +0000310#ifndef NDEBUG
Michael Gottesman9c118152013-04-29 06:16:57 +0000311STATISTIC(NumRetainsAfterOpt,
312 "Number of retains after optimization.");
313STATISTIC(NumReleasesAfterOpt,
314 "Number of releases after optimization.");
Michael Gottesman03cf3c82013-04-29 07:29:08 +0000315#endif
John McCalld935e9c2011-06-15 23:37:01 +0000316
317namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000318 /// \enum Sequence
319 ///
320 /// \brief A sequence of states that a pointer may go through in which an
321 /// objc_retain and objc_release are actually needed.
John McCalld935e9c2011-06-15 23:37:01 +0000322 enum Sequence {
323 S_None,
Michael Gottesman53fd20b2013-01-29 21:07:51 +0000324 S_Retain, ///< objc_retain(x).
325 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement.
326 S_Use, ///< any use of x.
Michael Gottesman386241c2013-01-29 21:39:02 +0000327 S_Stop, ///< like S_Release, but code motion is stopped.
Michael Gottesman53fd20b2013-01-29 21:07:51 +0000328 S_Release, ///< objc_release(x).
Michael Gottesman9bdab2b2013-01-29 21:41:44 +0000329 S_MovableRelease ///< objc_release(x), !clang.imprecise_release.
John McCalld935e9c2011-06-15 23:37:01 +0000330 };
Michael Gottesman53fd20b2013-01-29 21:07:51 +0000331
332 raw_ostream &operator<<(raw_ostream &OS, const Sequence S)
333 LLVM_ATTRIBUTE_UNUSED;
334 raw_ostream &operator<<(raw_ostream &OS, const Sequence S) {
335 switch (S) {
336 case S_None:
337 return OS << "S_None";
338 case S_Retain:
339 return OS << "S_Retain";
340 case S_CanRelease:
341 return OS << "S_CanRelease";
342 case S_Use:
343 return OS << "S_Use";
344 case S_Release:
345 return OS << "S_Release";
346 case S_MovableRelease:
347 return OS << "S_MovableRelease";
348 case S_Stop:
349 return OS << "S_Stop";
350 }
351 llvm_unreachable("Unknown sequence type.");
352 }
John McCalld935e9c2011-06-15 23:37:01 +0000353}
354
355static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
356 // The easy cases.
357 if (A == B)
358 return A;
359 if (A == S_None || B == S_None)
360 return S_None;
361
John McCalld935e9c2011-06-15 23:37:01 +0000362 if (A > B) std::swap(A, B);
363 if (TopDown) {
364 // Choose the side which is further along in the sequence.
Dan Gohman12130272011-08-12 00:26:31 +0000365 if ((A == S_Retain || A == S_CanRelease) &&
366 (B == S_CanRelease || B == S_Use))
John McCalld935e9c2011-06-15 23:37:01 +0000367 return B;
368 } else {
369 // Choose the side which is further along in the sequence.
370 if ((A == S_Use || A == S_CanRelease) &&
Dan Gohman12130272011-08-12 00:26:31 +0000371 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
John McCalld935e9c2011-06-15 23:37:01 +0000372 return A;
373 // If both sides are releases, choose the more conservative one.
374 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
375 return A;
376 if (A == S_Release && B == S_MovableRelease)
377 return A;
378 }
379
380 return S_None;
381}
382
383namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000384 /// \brief Unidirectional information about either a
John McCalld935e9c2011-06-15 23:37:01 +0000385 /// retain-decrement-use-release sequence or release-use-decrement-retain
Bob Wilson798a7702013-04-09 22:15:51 +0000386 /// reverse sequence.
John McCalld935e9c2011-06-15 23:37:01 +0000387 struct RRInfo {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000388 /// After an objc_retain, the reference count of the referenced
Dan Gohmanb3894012011-08-19 00:26:36 +0000389 /// object is known to be positive. Similarly, before an objc_release, the
390 /// reference count of the referenced object is known to be positive. If
391 /// there are retain-release pairs in code regions where the retain count
392 /// is known to be positive, they can be eliminated, regardless of any side
393 /// effects between them.
394 ///
395 /// Also, a retain+release pair nested within another retain+release
396 /// pair all on the known same pointer value can be eliminated, regardless
397 /// of any intervening side effects.
398 ///
399 /// KnownSafe is true when either of these conditions is satisfied.
400 bool KnownSafe;
John McCalld935e9c2011-06-15 23:37:01 +0000401
Michael Gottesman97e3df02013-01-14 00:35:14 +0000402 /// True of the objc_release calls are all marked with the "tail" keyword.
John McCalld935e9c2011-06-15 23:37:01 +0000403 bool IsTailCallRelease;
404
Michael Gottesman97e3df02013-01-14 00:35:14 +0000405 /// If the Calls are objc_release calls and they all have a
406 /// clang.imprecise_release tag, this is the metadata tag.
John McCalld935e9c2011-06-15 23:37:01 +0000407 MDNode *ReleaseMetadata;
408
Michael Gottesman97e3df02013-01-14 00:35:14 +0000409 /// For a top-down sequence, the set of objc_retains or
John McCalld935e9c2011-06-15 23:37:01 +0000410 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
411 SmallPtrSet<Instruction *, 2> Calls;
412
Michael Gottesman97e3df02013-01-14 00:35:14 +0000413 /// The set of optimal insert positions for moving calls in the opposite
414 /// sequence.
John McCalld935e9c2011-06-15 23:37:01 +0000415 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
416
417 RRInfo() :
Michael Gottesmanba648592013-03-28 23:08:44 +0000418 KnownSafe(false), IsTailCallRelease(false), ReleaseMetadata(0) {}
John McCalld935e9c2011-06-15 23:37:01 +0000419
420 void clear();
Michael Gottesman79249972013-04-05 23:46:45 +0000421
Michael Gottesman1d8d2572013-04-05 22:54:28 +0000422 bool IsTrackingImpreciseReleases() {
423 return ReleaseMetadata != 0;
424 }
John McCalld935e9c2011-06-15 23:37:01 +0000425 };
426}
427
428void RRInfo::clear() {
Dan Gohmanb3894012011-08-19 00:26:36 +0000429 KnownSafe = false;
John McCalld935e9c2011-06-15 23:37:01 +0000430 IsTailCallRelease = false;
431 ReleaseMetadata = 0;
432 Calls.clear();
433 ReverseInsertPts.clear();
434}
435
436namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000437 /// \brief This class summarizes several per-pointer runtime properties which
438 /// are propogated through the flow graph.
John McCalld935e9c2011-06-15 23:37:01 +0000439 class PtrState {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000440 /// True if the reference count is known to be incremented.
Dan Gohman62079b42012-04-25 00:50:46 +0000441 bool KnownPositiveRefCount;
442
Bob Wilson798a7702013-04-09 22:15:51 +0000443 /// True if we've seen an opportunity for partial RR elimination, such as
Michael Gottesman97e3df02013-01-14 00:35:14 +0000444 /// pushing calls into a CFG triangle or into one side of a CFG diamond.
Dan Gohman62079b42012-04-25 00:50:46 +0000445 bool Partial;
John McCalld935e9c2011-06-15 23:37:01 +0000446
Michael Gottesman97e3df02013-01-14 00:35:14 +0000447 /// The current position in the sequence.
Dan Gohman41375a32012-05-08 23:39:44 +0000448 Sequence Seq : 8;
John McCalld935e9c2011-06-15 23:37:01 +0000449
450 public:
Michael Gottesman97e3df02013-01-14 00:35:14 +0000451 /// Unidirectional information about the current sequence.
452 ///
John McCalld935e9c2011-06-15 23:37:01 +0000453 /// TODO: Encapsulate this better.
454 RRInfo RRI;
455
Dan Gohmandf476e52012-09-04 23:16:20 +0000456 PtrState() : KnownPositiveRefCount(false), Partial(false),
Dan Gohman41375a32012-05-08 23:39:44 +0000457 Seq(S_None) {}
John McCalld935e9c2011-06-15 23:37:01 +0000458
Michael Gottesman415ddd72013-02-05 19:32:18 +0000459 void SetKnownPositiveRefCount() {
Dan Gohman62079b42012-04-25 00:50:46 +0000460 KnownPositiveRefCount = true;
Dan Gohman12130272011-08-12 00:26:31 +0000461 }
462
Michael Gottesman764b1cf2013-03-23 05:46:19 +0000463 void ClearKnownPositiveRefCount() {
Dan Gohman62079b42012-04-25 00:50:46 +0000464 KnownPositiveRefCount = false;
John McCalld935e9c2011-06-15 23:37:01 +0000465 }
466
Michael Gottesman07beea42013-03-23 05:31:01 +0000467 bool HasKnownPositiveRefCount() const {
Dan Gohman62079b42012-04-25 00:50:46 +0000468 return KnownPositiveRefCount;
John McCalld935e9c2011-06-15 23:37:01 +0000469 }
470
Michael Gottesman415ddd72013-02-05 19:32:18 +0000471 void SetSeq(Sequence NewSeq) {
Michael Gottesman89279f82013-04-05 18:10:41 +0000472 DEBUG(dbgs() << "Old: " << Seq << "; New: " << NewSeq << "\n");
Michael Gottesman79249972013-04-05 23:46:45 +0000473 Seq = NewSeq;
John McCalld935e9c2011-06-15 23:37:01 +0000474 }
475
Michael Gottesman415ddd72013-02-05 19:32:18 +0000476 Sequence GetSeq() const {
John McCalld935e9c2011-06-15 23:37:01 +0000477 return Seq;
478 }
479
Michael Gottesman415ddd72013-02-05 19:32:18 +0000480 void ClearSequenceProgress() {
Dan Gohman62079b42012-04-25 00:50:46 +0000481 ResetSequenceProgress(S_None);
482 }
483
Michael Gottesman415ddd72013-02-05 19:32:18 +0000484 void ResetSequenceProgress(Sequence NewSeq) {
Michael Gottesman01338a42013-04-20 23:36:57 +0000485 DEBUG(dbgs() << "Resetting sequence progress.\n");
Michael Gottesman89279f82013-04-05 18:10:41 +0000486 SetSeq(NewSeq);
Dan Gohman62079b42012-04-25 00:50:46 +0000487 Partial = false;
John McCalld935e9c2011-06-15 23:37:01 +0000488 RRI.clear();
489 }
490
491 void Merge(const PtrState &Other, bool TopDown);
492 };
493}
494
495void
496PtrState::Merge(const PtrState &Other, bool TopDown) {
497 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
Dan Gohman62079b42012-04-25 00:50:46 +0000498 KnownPositiveRefCount = KnownPositiveRefCount && Other.KnownPositiveRefCount;
Michael Gottesman60f6b282013-03-29 05:13:07 +0000499
Dan Gohman1736c142011-10-17 18:48:25 +0000500 // If we're not in a sequence (anymore), drop all associated state.
John McCalld935e9c2011-06-15 23:37:01 +0000501 if (Seq == S_None) {
Dan Gohman62079b42012-04-25 00:50:46 +0000502 Partial = false;
John McCalld935e9c2011-06-15 23:37:01 +0000503 RRI.clear();
Dan Gohman62079b42012-04-25 00:50:46 +0000504 } else if (Partial || Other.Partial) {
Dan Gohman1736c142011-10-17 18:48:25 +0000505 // If we're doing a merge on a path that's previously seen a partial
506 // merge, conservatively drop the sequence, to avoid doing partial
507 // RR elimination. If the branch predicates for the two merge differ,
508 // mixing them is unsafe.
Dan Gohman62079b42012-04-25 00:50:46 +0000509 ClearSequenceProgress();
John McCalld935e9c2011-06-15 23:37:01 +0000510 } else {
511 // Conservatively merge the ReleaseMetadata information.
512 if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
513 RRI.ReleaseMetadata = 0;
514
Dan Gohmanb3894012011-08-19 00:26:36 +0000515 RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
Dan Gohman41375a32012-05-08 23:39:44 +0000516 RRI.IsTailCallRelease = RRI.IsTailCallRelease &&
517 Other.RRI.IsTailCallRelease;
John McCalld935e9c2011-06-15 23:37:01 +0000518 RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
Dan Gohman1736c142011-10-17 18:48:25 +0000519
520 // Merge the insert point sets. If there are any differences,
521 // that makes this a partial merge.
Dan Gohman41375a32012-05-08 23:39:44 +0000522 Partial = RRI.ReverseInsertPts.size() != Other.RRI.ReverseInsertPts.size();
Dan Gohman1736c142011-10-17 18:48:25 +0000523 for (SmallPtrSet<Instruction *, 2>::const_iterator
524 I = Other.RRI.ReverseInsertPts.begin(),
525 E = Other.RRI.ReverseInsertPts.end(); I != E; ++I)
Dan Gohman62079b42012-04-25 00:50:46 +0000526 Partial |= RRI.ReverseInsertPts.insert(*I);
John McCalld935e9c2011-06-15 23:37:01 +0000527 }
528}
529
530namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000531 /// \brief Per-BasicBlock state.
John McCalld935e9c2011-06-15 23:37:01 +0000532 class BBState {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000533 /// The number of unique control paths from the entry which can reach this
534 /// block.
John McCalld935e9c2011-06-15 23:37:01 +0000535 unsigned TopDownPathCount;
536
Michael Gottesman97e3df02013-01-14 00:35:14 +0000537 /// The number of unique control paths to exits from this block.
John McCalld935e9c2011-06-15 23:37:01 +0000538 unsigned BottomUpPathCount;
539
Michael Gottesman97e3df02013-01-14 00:35:14 +0000540 /// A type for PerPtrTopDown and PerPtrBottomUp.
John McCalld935e9c2011-06-15 23:37:01 +0000541 typedef MapVector<const Value *, PtrState> MapTy;
542
Michael Gottesman97e3df02013-01-14 00:35:14 +0000543 /// The top-down traversal uses this to record information known about a
544 /// pointer at the bottom of each block.
John McCalld935e9c2011-06-15 23:37:01 +0000545 MapTy PerPtrTopDown;
546
Michael Gottesman97e3df02013-01-14 00:35:14 +0000547 /// The bottom-up traversal uses this to record information known about a
548 /// pointer at the top of each block.
John McCalld935e9c2011-06-15 23:37:01 +0000549 MapTy PerPtrBottomUp;
550
Michael Gottesman97e3df02013-01-14 00:35:14 +0000551 /// Effective predecessors of the current block ignoring ignorable edges and
552 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000553 SmallVector<BasicBlock *, 2> Preds;
Michael Gottesman97e3df02013-01-14 00:35:14 +0000554 /// Effective successors of the current block ignoring ignorable edges and
555 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000556 SmallVector<BasicBlock *, 2> Succs;
557
John McCalld935e9c2011-06-15 23:37:01 +0000558 public:
559 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
560
561 typedef MapTy::iterator ptr_iterator;
562 typedef MapTy::const_iterator ptr_const_iterator;
563
564 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
565 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
566 ptr_const_iterator top_down_ptr_begin() const {
567 return PerPtrTopDown.begin();
568 }
569 ptr_const_iterator top_down_ptr_end() const {
570 return PerPtrTopDown.end();
571 }
572
573 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
574 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
575 ptr_const_iterator bottom_up_ptr_begin() const {
576 return PerPtrBottomUp.begin();
577 }
578 ptr_const_iterator bottom_up_ptr_end() const {
579 return PerPtrBottomUp.end();
580 }
581
Michael Gottesman97e3df02013-01-14 00:35:14 +0000582 /// Mark this block as being an entry block, which has one path from the
583 /// entry by definition.
John McCalld935e9c2011-06-15 23:37:01 +0000584 void SetAsEntry() { TopDownPathCount = 1; }
585
Michael Gottesman97e3df02013-01-14 00:35:14 +0000586 /// Mark this block as being an exit block, which has one path to an exit by
587 /// definition.
John McCalld935e9c2011-06-15 23:37:01 +0000588 void SetAsExit() { BottomUpPathCount = 1; }
589
Michael Gottesman993fbf72013-05-13 19:40:39 +0000590 /// Attempt to find the PtrState object describing the top down state for
591 /// pointer Arg. Return a new initialized PtrState describing the top down
592 /// state for Arg if we do not find one.
John McCalld935e9c2011-06-15 23:37:01 +0000593 PtrState &getPtrTopDownState(const Value *Arg) {
594 return PerPtrTopDown[Arg];
595 }
596
Michael Gottesman993fbf72013-05-13 19:40:39 +0000597 /// Attempt to find the PtrState object describing the bottom up state for
598 /// pointer Arg. Return a new initialized PtrState describing the bottom up
599 /// state for Arg if we do not find one.
John McCalld935e9c2011-06-15 23:37:01 +0000600 PtrState &getPtrBottomUpState(const Value *Arg) {
601 return PerPtrBottomUp[Arg];
602 }
603
604 void clearBottomUpPointers() {
Evan Chenge4df6a22011-08-04 18:40:26 +0000605 PerPtrBottomUp.clear();
John McCalld935e9c2011-06-15 23:37:01 +0000606 }
607
608 void clearTopDownPointers() {
609 PerPtrTopDown.clear();
610 }
611
612 void InitFromPred(const BBState &Other);
613 void InitFromSucc(const BBState &Other);
614 void MergePred(const BBState &Other);
615 void MergeSucc(const BBState &Other);
616
Michael Gottesman97e3df02013-01-14 00:35:14 +0000617 /// Return the number of possible unique paths from an entry to an exit
618 /// which pass through this block. This is only valid after both the
619 /// top-down and bottom-up traversals are complete.
John McCalld935e9c2011-06-15 23:37:01 +0000620 unsigned GetAllPathCount() const {
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000621 assert(TopDownPathCount != 0);
622 assert(BottomUpPathCount != 0);
John McCalld935e9c2011-06-15 23:37:01 +0000623 return TopDownPathCount * BottomUpPathCount;
624 }
Dan Gohman12130272011-08-12 00:26:31 +0000625
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000626 // Specialized CFG utilities.
Dan Gohmandae33492012-04-27 18:56:31 +0000627 typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000628 edge_iterator pred_begin() { return Preds.begin(); }
629 edge_iterator pred_end() { return Preds.end(); }
630 edge_iterator succ_begin() { return Succs.begin(); }
631 edge_iterator succ_end() { return Succs.end(); }
632
633 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
634 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
635
636 bool isExit() const { return Succs.empty(); }
John McCalld935e9c2011-06-15 23:37:01 +0000637 };
638}
639
640void BBState::InitFromPred(const BBState &Other) {
641 PerPtrTopDown = Other.PerPtrTopDown;
642 TopDownPathCount = Other.TopDownPathCount;
643}
644
645void BBState::InitFromSucc(const BBState &Other) {
646 PerPtrBottomUp = Other.PerPtrBottomUp;
647 BottomUpPathCount = Other.BottomUpPathCount;
648}
649
Michael Gottesman97e3df02013-01-14 00:35:14 +0000650/// The top-down traversal uses this to merge information about predecessors to
651/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +0000652void BBState::MergePred(const BBState &Other) {
653 // Other.TopDownPathCount can be 0, in which case it is either dead or a
654 // loop backedge. Loop backedges are special.
655 TopDownPathCount += Other.TopDownPathCount;
656
Michael Gottesman4385edf2013-01-14 01:47:53 +0000657 // Check for overflow. If we have overflow, fall back to conservative
658 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +0000659 if (TopDownPathCount < Other.TopDownPathCount) {
660 clearTopDownPointers();
661 return;
662 }
663
John McCalld935e9c2011-06-15 23:37:01 +0000664 // For each entry in the other set, if our set has an entry with the same key,
665 // merge the entries. Otherwise, copy the entry and merge it with an empty
666 // entry.
667 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
668 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
669 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
670 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
671 /*TopDown=*/true);
672 }
673
Dan Gohman7e315fc32011-08-11 21:06:32 +0000674 // For each entry in our set, if the other set doesn't have an entry with the
John McCalld935e9c2011-06-15 23:37:01 +0000675 // same key, force it to merge with an empty entry.
676 for (ptr_iterator MI = top_down_ptr_begin(),
677 ME = top_down_ptr_end(); MI != ME; ++MI)
678 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
679 MI->second.Merge(PtrState(), /*TopDown=*/true);
680}
681
Michael Gottesman97e3df02013-01-14 00:35:14 +0000682/// The bottom-up traversal uses this to merge information about successors to
683/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +0000684void BBState::MergeSucc(const BBState &Other) {
685 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
686 // loop backedge. Loop backedges are special.
687 BottomUpPathCount += Other.BottomUpPathCount;
688
Michael Gottesman4385edf2013-01-14 01:47:53 +0000689 // Check for overflow. If we have overflow, fall back to conservative
690 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +0000691 if (BottomUpPathCount < Other.BottomUpPathCount) {
692 clearBottomUpPointers();
693 return;
694 }
695
John McCalld935e9c2011-06-15 23:37:01 +0000696 // For each entry in the other set, if our set has an entry with the
697 // same key, merge the entries. Otherwise, copy the entry and merge
698 // it with an empty entry.
699 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
700 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
701 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
702 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
703 /*TopDown=*/false);
704 }
705
Dan Gohman7e315fc32011-08-11 21:06:32 +0000706 // For each entry in our set, if the other set doesn't have an entry
John McCalld935e9c2011-06-15 23:37:01 +0000707 // with the same key, force it to merge with an empty entry.
708 for (ptr_iterator MI = bottom_up_ptr_begin(),
709 ME = bottom_up_ptr_end(); MI != ME; ++MI)
710 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
711 MI->second.Merge(PtrState(), /*TopDown=*/false);
712}
713
Michael Gottesman81b1d432013-03-26 00:42:04 +0000714// Only enable ARC Annotations if we are building a debug version of
715// libObjCARCOpts.
716#ifndef NDEBUG
717#define ARC_ANNOTATIONS
718#endif
719
720// Define some macros along the lines of DEBUG and some helper functions to make
721// it cleaner to create annotations in the source code and to no-op when not
722// building in debug mode.
723#ifdef ARC_ANNOTATIONS
724
725#include "llvm/Support/CommandLine.h"
726
727/// Enable/disable ARC sequence annotations.
728static cl::opt<bool>
Michael Gottesman6806b512013-04-17 20:48:03 +0000729EnableARCAnnotations("enable-objc-arc-annotations", cl::init(false),
730 cl::desc("Enable emission of arc data flow analysis "
731 "annotations"));
Michael Gottesmanffef24f2013-04-17 20:48:01 +0000732static cl::opt<bool>
Michael Gottesmanadb921a2013-04-17 21:03:53 +0000733DisableCheckForCFGHazards("disable-objc-arc-checkforcfghazards", cl::init(false),
734 cl::desc("Disable check for cfg hazards when "
735 "annotating"));
Michael Gottesman4e88ce62013-04-17 21:59:41 +0000736static cl::opt<std::string>
737ARCAnnotationTargetIdentifier("objc-arc-annotation-target-identifier",
738 cl::init(""),
739 cl::desc("filter out all data flow annotations "
740 "but those that apply to the given "
741 "target llvm identifier."));
Michael Gottesman81b1d432013-03-26 00:42:04 +0000742
743/// This function appends a unique ARCAnnotationProvenanceSourceMDKind id to an
744/// instruction so that we can track backwards when post processing via the llvm
745/// arc annotation processor tool. If the function is an
746static MDString *AppendMDNodeToSourcePtr(unsigned NodeId,
747 Value *Ptr) {
748 MDString *Hash = 0;
749
750 // If pointer is a result of an instruction and it does not have a source
751 // MDNode it, attach a new MDNode onto it. If pointer is a result of
752 // an instruction and does have a source MDNode attached to it, return a
753 // reference to said Node. Otherwise just return 0.
754 if (Instruction *Inst = dyn_cast<Instruction>(Ptr)) {
755 MDNode *Node;
756 if (!(Node = Inst->getMetadata(NodeId))) {
757 // We do not have any node. Generate and attatch the hash MDString to the
758 // instruction.
759
760 // We just use an MDString to ensure that this metadata gets written out
761 // of line at the module level and to provide a very simple format
762 // encoding the information herein. Both of these makes it simpler to
763 // parse the annotations by a simple external program.
764 std::string Str;
765 raw_string_ostream os(Str);
766 os << "(" << Inst->getParent()->getParent()->getName() << ",%"
767 << Inst->getName() << ")";
768
769 Hash = MDString::get(Inst->getContext(), os.str());
770 Inst->setMetadata(NodeId, MDNode::get(Inst->getContext(),Hash));
771 } else {
772 // We have a node. Grab its hash and return it.
773 assert(Node->getNumOperands() == 1 &&
774 "An ARCAnnotationProvenanceSourceMDKind can only have 1 operand.");
775 Hash = cast<MDString>(Node->getOperand(0));
776 }
777 } else if (Argument *Arg = dyn_cast<Argument>(Ptr)) {
778 std::string str;
779 raw_string_ostream os(str);
780 os << "(" << Arg->getParent()->getName() << ",%" << Arg->getName()
781 << ")";
782 Hash = MDString::get(Arg->getContext(), os.str());
783 }
784
785 return Hash;
786}
787
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000788static std::string SequenceToString(Sequence A) {
789 std::string str;
790 raw_string_ostream os(str);
791 os << A;
792 return os.str();
793}
794
Michael Gottesman81b1d432013-03-26 00:42:04 +0000795/// Helper function to change a Sequence into a String object using our overload
796/// for raw_ostream so we only have printing code in one location.
797static MDString *SequenceToMDString(LLVMContext &Context,
798 Sequence A) {
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000799 return MDString::get(Context, SequenceToString(A));
Michael Gottesman81b1d432013-03-26 00:42:04 +0000800}
801
802/// A simple function to generate a MDNode which describes the change in state
803/// for Value *Ptr caused by Instruction *Inst.
804static void AppendMDNodeToInstForPtr(unsigned NodeId,
805 Instruction *Inst,
806 Value *Ptr,
807 MDString *PtrSourceMDNodeID,
808 Sequence OldSeq,
809 Sequence NewSeq) {
810 MDNode *Node = 0;
811 Value *tmp[3] = {PtrSourceMDNodeID,
812 SequenceToMDString(Inst->getContext(),
813 OldSeq),
814 SequenceToMDString(Inst->getContext(),
815 NewSeq)};
816 Node = MDNode::get(Inst->getContext(),
817 ArrayRef<Value*>(tmp, 3));
818
819 Inst->setMetadata(NodeId, Node);
820}
821
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000822/// Add to the beginning of the basic block llvm.ptr.annotations which show the
823/// state of a pointer at the entrance to a basic block.
824static void GenerateARCBBEntranceAnnotation(const char *Name, BasicBlock *BB,
825 Value *Ptr, Sequence Seq) {
Michael Gottesman4e88ce62013-04-17 21:59:41 +0000826 // If we have a target identifier, make sure that we match it before
827 // continuing.
828 if(!ARCAnnotationTargetIdentifier.empty() &&
829 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
830 return;
Michael Gottesman9e518132013-04-18 04:34:11 +0000831
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000832 Module *M = BB->getParent()->getParent();
833 LLVMContext &C = M->getContext();
834 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
835 Type *I8XX = PointerType::getUnqual(I8X);
836 Type *Params[] = {I8XX, I8XX};
837 FunctionType *FTy = FunctionType::get(Type::getVoidTy(C),
838 ArrayRef<Type*>(Params, 2),
839 /*isVarArg=*/false);
840 Constant *Callee = M->getOrInsertFunction(Name, FTy);
Michael Gottesman60f6b282013-03-29 05:13:07 +0000841
842 IRBuilder<> Builder(BB, BB->getFirstInsertionPt());
843
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000844 Value *PtrName;
845 StringRef Tmp = Ptr->getName();
846 if (0 == (PtrName = M->getGlobalVariable(Tmp, true))) {
847 Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
848 Tmp + "_STR");
849 PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
Michael Gottesman60f6b282013-03-29 05:13:07 +0000850 cast<Constant>(ActualPtrName), Tmp);
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000851 }
852
853 Value *S;
854 std::string SeqStr = SequenceToString(Seq);
855 if (0 == (S = M->getGlobalVariable(SeqStr, true))) {
856 Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
857 SeqStr + "_STR");
858 S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
859 cast<Constant>(ActualPtrName), SeqStr);
860 }
861
862 Builder.CreateCall2(Callee, PtrName, S);
863}
864
865/// Add to the end of the basic block llvm.ptr.annotations which show the state
866/// of the pointer at the bottom of the basic block.
867static void GenerateARCBBTerminatorAnnotation(const char *Name, BasicBlock *BB,
868 Value *Ptr, Sequence Seq) {
Michael Gottesman4e88ce62013-04-17 21:59:41 +0000869 // If we have a target identifier, make sure that we match it before emitting
870 // an annotation.
871 if(!ARCAnnotationTargetIdentifier.empty() &&
872 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
873 return;
Michael Gottesman9e518132013-04-18 04:34:11 +0000874
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000875 Module *M = BB->getParent()->getParent();
876 LLVMContext &C = M->getContext();
877 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
878 Type *I8XX = PointerType::getUnqual(I8X);
879 Type *Params[] = {I8XX, I8XX};
880 FunctionType *FTy = FunctionType::get(Type::getVoidTy(C),
881 ArrayRef<Type*>(Params, 2),
882 /*isVarArg=*/false);
883 Constant *Callee = M->getOrInsertFunction(Name, FTy);
Michael Gottesman60f6b282013-03-29 05:13:07 +0000884
885 IRBuilder<> Builder(BB, llvm::prior(BB->end()));
886
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000887 Value *PtrName;
888 StringRef Tmp = Ptr->getName();
889 if (0 == (PtrName = M->getGlobalVariable(Tmp, true))) {
890 Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
891 Tmp + "_STR");
892 PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
Michael Gottesman60f6b282013-03-29 05:13:07 +0000893 cast<Constant>(ActualPtrName), Tmp);
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000894 }
895
896 Value *S;
897 std::string SeqStr = SequenceToString(Seq);
898 if (0 == (S = M->getGlobalVariable(SeqStr, true))) {
899 Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
900 SeqStr + "_STR");
901 S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
902 cast<Constant>(ActualPtrName), SeqStr);
903 }
Michael Gottesman60f6b282013-03-29 05:13:07 +0000904 Builder.CreateCall2(Callee, PtrName, S);
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000905}
906
Michael Gottesman81b1d432013-03-26 00:42:04 +0000907/// Adds a source annotation to pointer and a state change annotation to Inst
908/// referencing the source annotation and the old/new state of pointer.
909static void GenerateARCAnnotation(unsigned InstMDId,
910 unsigned PtrMDId,
911 Instruction *Inst,
912 Value *Ptr,
913 Sequence OldSeq,
914 Sequence NewSeq) {
915 if (EnableARCAnnotations) {
Michael Gottesman4e88ce62013-04-17 21:59:41 +0000916 // If we have a target identifier, make sure that we match it before
917 // emitting an annotation.
918 if(!ARCAnnotationTargetIdentifier.empty() &&
919 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
920 return;
Michael Gottesman9e518132013-04-18 04:34:11 +0000921
Michael Gottesman81b1d432013-03-26 00:42:04 +0000922 // First generate the source annotation on our pointer. This will return an
923 // MDString* if Ptr actually comes from an instruction implying we can put
924 // in a source annotation. If AppendMDNodeToSourcePtr returns 0 (i.e. NULL),
925 // then we know that our pointer is from an Argument so we put a reference
926 // to the argument number.
927 //
928 // The point of this is to make it easy for the
929 // llvm-arc-annotation-processor tool to cross reference where the source
930 // pointer is in the LLVM IR since the LLVM IR parser does not submit such
931 // information via debug info for backends to use (since why would anyone
932 // need such a thing from LLVM IR besides in non standard cases
933 // [i.e. this]).
934 MDString *SourcePtrMDNode =
935 AppendMDNodeToSourcePtr(PtrMDId, Ptr);
936 AppendMDNodeToInstForPtr(InstMDId, Inst, Ptr, SourcePtrMDNode, OldSeq,
937 NewSeq);
938 }
939}
940
941// The actual interface for accessing the above functionality is defined via
942// some simple macros which are defined below. We do this so that the user does
943// not need to pass in what metadata id is needed resulting in cleaner code and
944// additionally since it provides an easy way to conditionally no-op all
945// annotation support in a non-debug build.
946
947/// Use this macro to annotate a sequence state change when processing
948/// instructions bottom up,
949#define ANNOTATE_BOTTOMUP(inst, ptr, old, new) \
950 GenerateARCAnnotation(ARCAnnotationBottomUpMDKind, \
951 ARCAnnotationProvenanceSourceMDKind, (inst), \
952 const_cast<Value*>(ptr), (old), (new))
953/// Use this macro to annotate a sequence state change when processing
954/// instructions top down.
955#define ANNOTATE_TOPDOWN(inst, ptr, old, new) \
956 GenerateARCAnnotation(ARCAnnotationTopDownMDKind, \
957 ARCAnnotationProvenanceSourceMDKind, (inst), \
958 const_cast<Value*>(ptr), (old), (new))
959
Michael Gottesman43e7e002013-04-03 22:41:59 +0000960#define ANNOTATE_BB(_states, _bb, _name, _type, _direction) \
961 do { \
Michael Gottesman89279f82013-04-05 18:10:41 +0000962 if (EnableARCAnnotations) { \
963 for(BBState::ptr_const_iterator I = (_states)._direction##_ptr_begin(), \
Michael Gottesman43e7e002013-04-03 22:41:59 +0000964 E = (_states)._direction##_ptr_end(); I != E; ++I) { \
Michael Gottesman89279f82013-04-05 18:10:41 +0000965 Value *Ptr = const_cast<Value*>(I->first); \
966 Sequence Seq = I->second.GetSeq(); \
967 GenerateARCBB ## _type ## Annotation(_name, (_bb), Ptr, Seq); \
968 } \
Michael Gottesman43e7e002013-04-03 22:41:59 +0000969 } \
Michael Gottesman89279f82013-04-05 18:10:41 +0000970 } while (0)
Michael Gottesman43e7e002013-04-03 22:41:59 +0000971
Michael Gottesman89279f82013-04-05 18:10:41 +0000972#define ANNOTATE_BOTTOMUP_BBSTART(_states, _basicblock) \
Michael Gottesman43e7e002013-04-03 22:41:59 +0000973 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbstart", \
974 Entrance, bottom_up)
Michael Gottesman89279f82013-04-05 18:10:41 +0000975#define ANNOTATE_BOTTOMUP_BBEND(_states, _basicblock) \
976 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbend", \
Michael Gottesman43e7e002013-04-03 22:41:59 +0000977 Terminator, bottom_up)
Michael Gottesman89279f82013-04-05 18:10:41 +0000978#define ANNOTATE_TOPDOWN_BBSTART(_states, _basicblock) \
979 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbstart", \
Michael Gottesman43e7e002013-04-03 22:41:59 +0000980 Entrance, top_down)
Michael Gottesman89279f82013-04-05 18:10:41 +0000981#define ANNOTATE_TOPDOWN_BBEND(_states, _basicblock) \
982 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbend", \
Michael Gottesman43e7e002013-04-03 22:41:59 +0000983 Terminator, top_down)
984
Michael Gottesman81b1d432013-03-26 00:42:04 +0000985#else // !ARC_ANNOTATION
986// If annotations are off, noop.
987#define ANNOTATE_BOTTOMUP(inst, ptr, old, new)
988#define ANNOTATE_TOPDOWN(inst, ptr, old, new)
Michael Gottesman43e7e002013-04-03 22:41:59 +0000989#define ANNOTATE_BOTTOMUP_BBSTART(states, basicblock)
990#define ANNOTATE_BOTTOMUP_BBEND(states, basicblock)
991#define ANNOTATE_TOPDOWN_BBSTART(states, basicblock)
992#define ANNOTATE_TOPDOWN_BBEND(states, basicblock)
Michael Gottesman81b1d432013-03-26 00:42:04 +0000993#endif // !ARC_ANNOTATION
994
John McCalld935e9c2011-06-15 23:37:01 +0000995namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000996 /// \brief The main ARC optimization pass.
John McCalld935e9c2011-06-15 23:37:01 +0000997 class ObjCARCOpt : public FunctionPass {
998 bool Changed;
999 ProvenanceAnalysis PA;
1000
Michael Gottesman97e3df02013-01-14 00:35:14 +00001001 /// A flag indicating whether this optimization pass should run.
Dan Gohmanceaac7c2011-06-20 23:20:43 +00001002 bool Run;
1003
Michael Gottesman97e3df02013-01-14 00:35:14 +00001004 /// Declarations for ObjC runtime functions, for use in creating calls to
1005 /// them. These are initialized lazily to avoid cluttering up the Module
1006 /// with unused declarations.
John McCalld935e9c2011-06-15 23:37:01 +00001007
Michael Gottesman97e3df02013-01-14 00:35:14 +00001008 /// Declaration for ObjC runtime function objc_autoreleaseReturnValue.
1009 Constant *AutoreleaseRVCallee;
1010 /// Declaration for ObjC runtime function objc_release.
1011 Constant *ReleaseCallee;
1012 /// Declaration for ObjC runtime function objc_retain.
1013 Constant *RetainCallee;
1014 /// Declaration for ObjC runtime function objc_retainBlock.
1015 Constant *RetainBlockCallee;
1016 /// Declaration for ObjC runtime function objc_autorelease.
1017 Constant *AutoreleaseCallee;
1018
1019 /// Flags which determine whether each of the interesting runtine functions
1020 /// is in fact used in the current function.
John McCalld935e9c2011-06-15 23:37:01 +00001021 unsigned UsedInThisFunction;
1022
Michael Gottesman97e3df02013-01-14 00:35:14 +00001023 /// The Metadata Kind for clang.imprecise_release metadata.
John McCalld935e9c2011-06-15 23:37:01 +00001024 unsigned ImpreciseReleaseMDKind;
1025
Michael Gottesman97e3df02013-01-14 00:35:14 +00001026 /// The Metadata Kind for clang.arc.copy_on_escape metadata.
Dan Gohmana7107f92011-10-17 22:53:25 +00001027 unsigned CopyOnEscapeMDKind;
1028
Michael Gottesman97e3df02013-01-14 00:35:14 +00001029 /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata.
Dan Gohman0155f302012-02-17 18:59:53 +00001030 unsigned NoObjCARCExceptionsMDKind;
1031
Michael Gottesman81b1d432013-03-26 00:42:04 +00001032#ifdef ARC_ANNOTATIONS
1033 /// The Metadata Kind for llvm.arc.annotation.bottomup metadata.
1034 unsigned ARCAnnotationBottomUpMDKind;
1035 /// The Metadata Kind for llvm.arc.annotation.topdown metadata.
1036 unsigned ARCAnnotationTopDownMDKind;
1037 /// The Metadata Kind for llvm.arc.annotation.provenancesource metadata.
1038 unsigned ARCAnnotationProvenanceSourceMDKind;
1039#endif // ARC_ANNOATIONS
1040
John McCalld935e9c2011-06-15 23:37:01 +00001041 Constant *getAutoreleaseRVCallee(Module *M);
1042 Constant *getReleaseCallee(Module *M);
1043 Constant *getRetainCallee(Module *M);
Dan Gohman6320f522011-07-22 22:29:21 +00001044 Constant *getRetainBlockCallee(Module *M);
John McCalld935e9c2011-06-15 23:37:01 +00001045 Constant *getAutoreleaseCallee(Module *M);
1046
Dan Gohman728db492012-01-13 00:39:07 +00001047 bool IsRetainBlockOptimizable(const Instruction *Inst);
1048
John McCalld935e9c2011-06-15 23:37:01 +00001049 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
Michael Gottesman556ff612013-01-12 01:25:19 +00001050 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1051 InstructionClass &Class);
Michael Gottesman158fdf62013-03-28 20:11:19 +00001052 bool OptimizeRetainBlockCall(Function &F, Instruction *RetainBlock,
1053 InstructionClass &Class);
John McCalld935e9c2011-06-15 23:37:01 +00001054 void OptimizeIndividualCalls(Function &F);
1055
1056 void CheckForCFGHazards(const BasicBlock *BB,
1057 DenseMap<const BasicBlock *, BBState> &BBStates,
1058 BBState &MyStates) const;
Dan Gohman817a7c62012-03-22 18:24:56 +00001059 bool VisitInstructionBottomUp(Instruction *Inst,
Dan Gohman5c70fad2012-03-23 17:47:54 +00001060 BasicBlock *BB,
Dan Gohman817a7c62012-03-22 18:24:56 +00001061 MapVector<Value *, RRInfo> &Retains,
1062 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00001063 bool VisitBottomUp(BasicBlock *BB,
1064 DenseMap<const BasicBlock *, BBState> &BBStates,
1065 MapVector<Value *, RRInfo> &Retains);
Dan Gohman817a7c62012-03-22 18:24:56 +00001066 bool VisitInstructionTopDown(Instruction *Inst,
1067 DenseMap<Value *, RRInfo> &Releases,
1068 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00001069 bool VisitTopDown(BasicBlock *BB,
1070 DenseMap<const BasicBlock *, BBState> &BBStates,
1071 DenseMap<Value *, RRInfo> &Releases);
1072 bool Visit(Function &F,
1073 DenseMap<const BasicBlock *, BBState> &BBStates,
1074 MapVector<Value *, RRInfo> &Retains,
1075 DenseMap<Value *, RRInfo> &Releases);
1076
1077 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1078 MapVector<Value *, RRInfo> &Retains,
1079 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman6320f522011-07-22 22:29:21 +00001080 SmallVectorImpl<Instruction *> &DeadInsts,
1081 Module *M);
John McCalld935e9c2011-06-15 23:37:01 +00001082
Michael Gottesman9de6f962013-01-22 21:49:00 +00001083 bool ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState> &BBStates,
1084 MapVector<Value *, RRInfo> &Retains,
1085 DenseMap<Value *, RRInfo> &Releases,
1086 Module *M,
1087 SmallVector<Instruction *, 4> &NewRetains,
1088 SmallVector<Instruction *, 4> &NewReleases,
1089 SmallVector<Instruction *, 8> &DeadInsts,
1090 RRInfo &RetainsToMove,
1091 RRInfo &ReleasesToMove,
1092 Value *Arg,
1093 bool KnownSafe,
1094 bool &AnyPairsCompletelyEliminated);
1095
John McCalld935e9c2011-06-15 23:37:01 +00001096 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1097 MapVector<Value *, RRInfo> &Retains,
Dan Gohman6320f522011-07-22 22:29:21 +00001098 DenseMap<Value *, RRInfo> &Releases,
1099 Module *M);
John McCalld935e9c2011-06-15 23:37:01 +00001100
1101 void OptimizeWeakCalls(Function &F);
1102
1103 bool OptimizeSequences(Function &F);
1104
1105 void OptimizeReturns(Function &F);
1106
Michael Gottesman9c118152013-04-29 06:16:57 +00001107#ifndef NDEBUG
1108 void GatherStatistics(Function &F, bool AfterOptimization = false);
1109#endif
1110
John McCalld935e9c2011-06-15 23:37:01 +00001111 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1112 virtual bool doInitialization(Module &M);
1113 virtual bool runOnFunction(Function &F);
1114 virtual void releaseMemory();
1115
1116 public:
1117 static char ID;
1118 ObjCARCOpt() : FunctionPass(ID) {
1119 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1120 }
1121 };
1122}
1123
1124char ObjCARCOpt::ID = 0;
1125INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1126 "objc-arc", "ObjC ARC optimization", false, false)
1127INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1128INITIALIZE_PASS_END(ObjCARCOpt,
1129 "objc-arc", "ObjC ARC optimization", false, false)
1130
1131Pass *llvm::createObjCARCOptPass() {
1132 return new ObjCARCOpt();
1133}
1134
1135void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1136 AU.addRequired<ObjCARCAliasAnalysis>();
1137 AU.addRequired<AliasAnalysis>();
1138 // ARC optimization doesn't currently split critical edges.
1139 AU.setPreservesCFG();
1140}
1141
Dan Gohman728db492012-01-13 00:39:07 +00001142bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1143 // Without the magic metadata tag, we have to assume this might be an
1144 // objc_retainBlock call inserted to convert a block pointer to an id,
1145 // in which case it really is needed.
1146 if (!Inst->getMetadata(CopyOnEscapeMDKind))
1147 return false;
1148
1149 // If the pointer "escapes" (not including being used in a call),
1150 // the copy may be needed.
Michael Gottesman774d2c02013-01-29 21:00:52 +00001151 if (DoesRetainableObjPtrEscape(Inst))
Dan Gohman728db492012-01-13 00:39:07 +00001152 return false;
1153
1154 // Otherwise, it's not needed.
1155 return true;
1156}
1157
John McCalld935e9c2011-06-15 23:37:01 +00001158Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1159 if (!AutoreleaseRVCallee) {
1160 LLVMContext &C = M->getContext();
Jay Foadb804a2b2011-07-12 14:06:48 +00001161 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman41375a32012-05-08 23:39:44 +00001162 Type *Params[] = { I8X };
1163 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001164 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001165 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1166 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001167 AutoreleaseRVCallee =
1168 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001169 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001170 }
1171 return AutoreleaseRVCallee;
1172}
1173
1174Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1175 if (!ReleaseCallee) {
1176 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001177 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001178 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001179 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1180 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001181 ReleaseCallee =
1182 M->getOrInsertFunction(
1183 "objc_release",
1184 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001185 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001186 }
1187 return ReleaseCallee;
1188}
1189
1190Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1191 if (!RetainCallee) {
1192 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001193 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001194 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001195 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1196 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001197 RetainCallee =
1198 M->getOrInsertFunction(
1199 "objc_retain",
1200 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001201 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001202 }
1203 return RetainCallee;
1204}
1205
Dan Gohman6320f522011-07-22 22:29:21 +00001206Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1207 if (!RetainBlockCallee) {
1208 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001209 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Dan Gohmanfca43c22011-09-14 18:33:34 +00001210 // objc_retainBlock is not nounwind because it calls user copy constructors
1211 // which could theoretically throw.
Dan Gohman6320f522011-07-22 22:29:21 +00001212 RetainBlockCallee =
1213 M->getOrInsertFunction(
1214 "objc_retainBlock",
1215 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendlinge94d8432012-12-07 23:16:57 +00001216 AttributeSet());
Dan Gohman6320f522011-07-22 22:29:21 +00001217 }
1218 return RetainBlockCallee;
1219}
1220
John McCalld935e9c2011-06-15 23:37:01 +00001221Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1222 if (!AutoreleaseCallee) {
1223 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001224 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001225 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001226 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1227 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001228 AutoreleaseCallee =
1229 M->getOrInsertFunction(
1230 "objc_autorelease",
1231 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001232 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001233 }
1234 return AutoreleaseCallee;
1235}
1236
Michael Gottesman97e3df02013-01-14 00:35:14 +00001237/// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is
1238/// not a return value. Or, if it can be paired with an
1239/// objc_autoreleaseReturnValue, delete the pair and return true.
John McCalld935e9c2011-06-15 23:37:01 +00001240bool
1241ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001242 // Check for the argument being from an immediately preceding call or invoke.
Dan Gohmandae33492012-04-27 18:56:31 +00001243 const Value *Arg = GetObjCArg(RetainRV);
1244 ImmutableCallSite CS(Arg);
1245 if (const Instruction *Call = CS.getInstruction()) {
John McCalld935e9c2011-06-15 23:37:01 +00001246 if (Call->getParent() == RetainRV->getParent()) {
Dan Gohmandae33492012-04-27 18:56:31 +00001247 BasicBlock::const_iterator I = Call;
John McCalld935e9c2011-06-15 23:37:01 +00001248 ++I;
Michael Gottesman65c24812013-03-25 09:27:43 +00001249 while (IsNoopInstruction(I)) ++I;
John McCalld935e9c2011-06-15 23:37:01 +00001250 if (&*I == RetainRV)
1251 return false;
Dan Gohmandae33492012-04-27 18:56:31 +00001252 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001253 BasicBlock *RetainRVParent = RetainRV->getParent();
1254 if (II->getNormalDest() == RetainRVParent) {
Dan Gohmandae33492012-04-27 18:56:31 +00001255 BasicBlock::const_iterator I = RetainRVParent->begin();
Michael Gottesman65c24812013-03-25 09:27:43 +00001256 while (IsNoopInstruction(I)) ++I;
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001257 if (&*I == RetainRV)
1258 return false;
1259 }
John McCalld935e9c2011-06-15 23:37:01 +00001260 }
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001261 }
John McCalld935e9c2011-06-15 23:37:01 +00001262
1263 // Check for being preceded by an objc_autoreleaseReturnValue on the same
1264 // pointer. In this case, we can delete the pair.
1265 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
1266 if (I != Begin) {
Michael Gottesman65c24812013-03-25 09:27:43 +00001267 do --I; while (I != Begin && IsNoopInstruction(I));
John McCalld935e9c2011-06-15 23:37:01 +00001268 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
1269 GetObjCArg(I) == Arg) {
1270 Changed = true;
1271 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00001272
Michael Gottesman89279f82013-04-05 18:10:41 +00001273 DEBUG(dbgs() << "Erasing autoreleaseRV,retainRV pair: " << *I << "\n"
1274 << "Erasing " << *RetainRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001275
John McCalld935e9c2011-06-15 23:37:01 +00001276 EraseInstruction(I);
1277 EraseInstruction(RetainRV);
1278 return true;
1279 }
1280 }
1281
1282 // Turn it to a plain objc_retain.
1283 Changed = true;
1284 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00001285
Michael Gottesman89279f82013-04-05 18:10:41 +00001286 DEBUG(dbgs() << "Transforming objc_retainAutoreleasedReturnValue => "
Michael Gottesmandef07bb2013-01-05 17:55:42 +00001287 "objc_retain since the operand is not a return value.\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00001288 "Old = " << *RetainRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001289
John McCalld935e9c2011-06-15 23:37:01 +00001290 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
Michael Gottesmandef07bb2013-01-05 17:55:42 +00001291
Michael Gottesman89279f82013-04-05 18:10:41 +00001292 DEBUG(dbgs() << "New = " << *RetainRV << "\n");
Michael Gottesmandef07bb2013-01-05 17:55:42 +00001293
John McCalld935e9c2011-06-15 23:37:01 +00001294 return false;
1295}
1296
Michael Gottesman97e3df02013-01-14 00:35:14 +00001297/// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not
1298/// used as a return value.
John McCalld935e9c2011-06-15 23:37:01 +00001299void
Michael Gottesman556ff612013-01-12 01:25:19 +00001300ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1301 InstructionClass &Class) {
John McCalld935e9c2011-06-15 23:37:01 +00001302 // Check for a return of the pointer value.
1303 const Value *Ptr = GetObjCArg(AutoreleaseRV);
Dan Gohman10a18d52011-08-12 00:36:31 +00001304 SmallVector<const Value *, 2> Users;
1305 Users.push_back(Ptr);
1306 do {
1307 Ptr = Users.pop_back_val();
1308 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
1309 UI != UE; ++UI) {
1310 const User *I = *UI;
1311 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
1312 return;
1313 if (isa<BitCastInst>(I))
1314 Users.push_back(I);
1315 }
1316 } while (!Users.empty());
John McCalld935e9c2011-06-15 23:37:01 +00001317
1318 Changed = true;
1319 ++NumPeeps;
Michael Gottesman1bf69082013-01-06 21:07:11 +00001320
Michael Gottesman89279f82013-04-05 18:10:41 +00001321 DEBUG(dbgs() << "Transforming objc_autoreleaseReturnValue => "
Michael Gottesman1bf69082013-01-06 21:07:11 +00001322 "objc_autorelease since its operand is not used as a return "
1323 "value.\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00001324 "Old = " << *AutoreleaseRV << "\n");
Michael Gottesman1bf69082013-01-06 21:07:11 +00001325
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001326 CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
1327 AutoreleaseRVCI->
John McCalld935e9c2011-06-15 23:37:01 +00001328 setCalledFunction(getAutoreleaseCallee(F.getParent()));
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001329 AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
Michael Gottesman556ff612013-01-12 01:25:19 +00001330 Class = IC_Autorelease;
Michael Gottesman10426b52013-01-07 21:26:07 +00001331
Michael Gottesman89279f82013-04-05 18:10:41 +00001332 DEBUG(dbgs() << "New: " << *AutoreleaseRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001333
John McCalld935e9c2011-06-15 23:37:01 +00001334}
1335
Michael Gottesman158fdf62013-03-28 20:11:19 +00001336// \brief Attempt to strength reduce objc_retainBlock calls to objc_retain
1337// calls.
1338//
1339// Specifically: If an objc_retainBlock call has the copy_on_escape metadata and
1340// does not escape (following the rules of block escaping), strength reduce the
1341// objc_retainBlock to an objc_retain.
1342//
1343// TODO: If an objc_retainBlock call is dominated period by a previous
1344// objc_retainBlock call, strength reduce the objc_retainBlock to an
1345// objc_retain.
1346bool
1347ObjCARCOpt::OptimizeRetainBlockCall(Function &F, Instruction *Inst,
1348 InstructionClass &Class) {
1349 assert(GetBasicInstructionClass(Inst) == Class);
1350 assert(IC_RetainBlock == Class);
Michael Gottesman60f6b282013-03-29 05:13:07 +00001351
Michael Gottesman158fdf62013-03-28 20:11:19 +00001352 // If we can not optimize Inst, return false.
1353 if (!IsRetainBlockOptimizable(Inst))
1354 return false;
Michael Gottesman60f6b282013-03-29 05:13:07 +00001355
Michael Gottesman3eab2e42013-04-21 00:50:27 +00001356 Changed = true;
1357 ++NumPeeps;
1358
1359 DEBUG(dbgs() << "Strength reduced retainBlock => retain.\n");
1360 DEBUG(dbgs() << "Old: " << *Inst << "\n");
Michael Gottesman158fdf62013-03-28 20:11:19 +00001361 CallInst *RetainBlock = cast<CallInst>(Inst);
1362 RetainBlock->setCalledFunction(getRetainCallee(F.getParent()));
1363 // Remove copy_on_escape metadata.
1364 RetainBlock->setMetadata(CopyOnEscapeMDKind, 0);
1365 Class = IC_Retain;
Michael Gottesman3eab2e42013-04-21 00:50:27 +00001366 DEBUG(dbgs() << "New: " << *Inst << "\n");
Michael Gottesman158fdf62013-03-28 20:11:19 +00001367 return true;
1368}
1369
Michael Gottesman97e3df02013-01-14 00:35:14 +00001370/// Visit each call, one at a time, and make simplifications without doing any
1371/// additional analysis.
John McCalld935e9c2011-06-15 23:37:01 +00001372void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001373 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeIndividualCalls ==\n");
John McCalld935e9c2011-06-15 23:37:01 +00001374 // Reset all the flags in preparation for recomputing them.
1375 UsedInThisFunction = 0;
1376
1377 // Visit all objc_* calls in F.
1378 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
1379 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +00001380
John McCalld935e9c2011-06-15 23:37:01 +00001381 InstructionClass Class = GetBasicInstructionClass(Inst);
1382
Michael Gottesman89279f82013-04-05 18:10:41 +00001383 DEBUG(dbgs() << "Visiting: Class: " << Class << "; " << *Inst << "\n");
Michael Gottesman782e3442013-01-17 18:32:34 +00001384
John McCalld935e9c2011-06-15 23:37:01 +00001385 switch (Class) {
1386 default: break;
1387
1388 // Delete no-op casts. These function calls have special semantics, but
1389 // the semantics are entirely implemented via lowering in the front-end,
1390 // so by the time they reach the optimizer, they are just no-op calls
1391 // which return their argument.
1392 //
1393 // There are gray areas here, as the ability to cast reference-counted
1394 // pointers to raw void* and back allows code to break ARC assumptions,
1395 // however these are currently considered to be unimportant.
1396 case IC_NoopCast:
1397 Changed = true;
1398 ++NumNoops;
Michael Gottesman89279f82013-04-05 18:10:41 +00001399 DEBUG(dbgs() << "Erasing no-op cast: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001400 EraseInstruction(Inst);
1401 continue;
1402
1403 // If the pointer-to-weak-pointer is null, it's undefined behavior.
1404 case IC_StoreWeak:
1405 case IC_LoadWeak:
1406 case IC_LoadWeakRetained:
1407 case IC_InitWeak:
1408 case IC_DestroyWeak: {
1409 CallInst *CI = cast<CallInst>(Inst);
Michael Gottesman65c24812013-03-25 09:27:43 +00001410 if (IsNullOrUndef(CI->getArgOperand(0))) {
Dan Gohman670f9372012-04-13 18:57:48 +00001411 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +00001412 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001413 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1414 Constant::getNullValue(Ty),
1415 CI);
Michael Gottesman10426b52013-01-07 21:26:07 +00001416 llvm::Value *NewValue = UndefValue::get(CI->getType());
Michael Gottesman89279f82013-04-05 18:10:41 +00001417 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
1418 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001419 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +00001420 CI->eraseFromParent();
1421 continue;
1422 }
1423 break;
1424 }
1425 case IC_CopyWeak:
1426 case IC_MoveWeak: {
1427 CallInst *CI = cast<CallInst>(Inst);
Michael Gottesman65c24812013-03-25 09:27:43 +00001428 if (IsNullOrUndef(CI->getArgOperand(0)) ||
1429 IsNullOrUndef(CI->getArgOperand(1))) {
Dan Gohman670f9372012-04-13 18:57:48 +00001430 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +00001431 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001432 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1433 Constant::getNullValue(Ty),
1434 CI);
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001435
1436 llvm::Value *NewValue = UndefValue::get(CI->getType());
Michael Gottesman89279f82013-04-05 18:10:41 +00001437 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
1438 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001439
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001440 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +00001441 CI->eraseFromParent();
1442 continue;
1443 }
1444 break;
1445 }
Michael Gottesman158fdf62013-03-28 20:11:19 +00001446 case IC_RetainBlock:
Michael Gottesman1e430042013-04-21 00:44:46 +00001447 // If we strength reduce an objc_retainBlock to an objc_retain, continue
Michael Gottesman158fdf62013-03-28 20:11:19 +00001448 // onto the objc_retain peephole optimizations. Otherwise break.
Michael Gottesman9fc50b82013-05-13 18:29:07 +00001449 OptimizeRetainBlockCall(F, Inst, Class);
John McCalld935e9c2011-06-15 23:37:01 +00001450 break;
1451 case IC_RetainRV:
1452 if (OptimizeRetainRVCall(F, Inst))
1453 continue;
1454 break;
1455 case IC_AutoreleaseRV:
Michael Gottesman556ff612013-01-12 01:25:19 +00001456 OptimizeAutoreleaseRVCall(F, Inst, Class);
John McCalld935e9c2011-06-15 23:37:01 +00001457 break;
1458 }
1459
Michael Gottesmanb8c88362013-04-03 02:57:24 +00001460 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
John McCalld935e9c2011-06-15 23:37:01 +00001461 if (IsAutorelease(Class) && Inst->use_empty()) {
1462 CallInst *Call = cast<CallInst>(Inst);
1463 const Value *Arg = Call->getArgOperand(0);
1464 Arg = FindSingleUseIdentifiedObject(Arg);
1465 if (Arg) {
1466 Changed = true;
1467 ++NumAutoreleases;
1468
1469 // Create the declaration lazily.
1470 LLVMContext &C = Inst->getContext();
1471 CallInst *NewCall =
1472 CallInst::Create(getReleaseCallee(F.getParent()),
1473 Call->getArgOperand(0), "", Call);
Dmitri Gribenko3238fb72013-05-05 00:40:33 +00001474 NewCall->setMetadata(ImpreciseReleaseMDKind, MDNode::get(C, None));
Michael Gottesman10426b52013-01-07 21:26:07 +00001475
Michael Gottesman89279f82013-04-05 18:10:41 +00001476 DEBUG(dbgs() << "Replacing autorelease{,RV}(x) with objc_release(x) "
1477 "since x is otherwise unused.\nOld: " << *Call << "\nNew: "
1478 << *NewCall << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001479
John McCalld935e9c2011-06-15 23:37:01 +00001480 EraseInstruction(Call);
1481 Inst = NewCall;
1482 Class = IC_Release;
1483 }
1484 }
1485
1486 // For functions which can never be passed stack arguments, add
1487 // a tail keyword.
1488 if (IsAlwaysTail(Class)) {
1489 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +00001490 DEBUG(dbgs() << "Adding tail keyword to function since it can never be "
1491 "passed stack args: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001492 cast<CallInst>(Inst)->setTailCall();
1493 }
1494
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001495 // Ensure that functions that can never have a "tail" keyword due to the
1496 // semantics of ARC truly do not do so.
1497 if (IsNeverTail(Class)) {
1498 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +00001499 DEBUG(dbgs() << "Removing tail keyword from function: " << *Inst <<
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001500 "\n");
1501 cast<CallInst>(Inst)->setTailCall(false);
1502 }
1503
John McCalld935e9c2011-06-15 23:37:01 +00001504 // Set nounwind as needed.
1505 if (IsNoThrow(Class)) {
1506 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +00001507 DEBUG(dbgs() << "Found no throw class. Setting nounwind on: " << *Inst
1508 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001509 cast<CallInst>(Inst)->setDoesNotThrow();
1510 }
1511
1512 if (!IsNoopOnNull(Class)) {
1513 UsedInThisFunction |= 1 << Class;
1514 continue;
1515 }
1516
1517 const Value *Arg = GetObjCArg(Inst);
1518
1519 // ARC calls with null are no-ops. Delete them.
Michael Gottesman65c24812013-03-25 09:27:43 +00001520 if (IsNullOrUndef(Arg)) {
John McCalld935e9c2011-06-15 23:37:01 +00001521 Changed = true;
1522 ++NumNoops;
Michael Gottesman89279f82013-04-05 18:10:41 +00001523 DEBUG(dbgs() << "ARC calls with null are no-ops. Erasing: " << *Inst
1524 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001525 EraseInstruction(Inst);
1526 continue;
1527 }
1528
1529 // Keep track of which of retain, release, autorelease, and retain_block
1530 // are actually present in this function.
1531 UsedInThisFunction |= 1 << Class;
1532
1533 // If Arg is a PHI, and one or more incoming values to the
1534 // PHI are null, and the call is control-equivalent to the PHI, and there
1535 // are no relevant side effects between the PHI and the call, the call
1536 // could be pushed up to just those paths with non-null incoming values.
1537 // For now, don't bother splitting critical edges for this.
1538 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
1539 Worklist.push_back(std::make_pair(Inst, Arg));
1540 do {
1541 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
1542 Inst = Pair.first;
1543 Arg = Pair.second;
1544
1545 const PHINode *PN = dyn_cast<PHINode>(Arg);
1546 if (!PN) continue;
1547
1548 // Determine if the PHI has any null operands, or any incoming
1549 // critical edges.
1550 bool HasNull = false;
1551 bool HasCriticalEdges = false;
1552 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1553 Value *Incoming =
1554 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
Michael Gottesman65c24812013-03-25 09:27:43 +00001555 if (IsNullOrUndef(Incoming))
John McCalld935e9c2011-06-15 23:37:01 +00001556 HasNull = true;
1557 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
1558 .getNumSuccessors() != 1) {
1559 HasCriticalEdges = true;
1560 break;
1561 }
1562 }
1563 // If we have null operands and no critical edges, optimize.
1564 if (!HasCriticalEdges && HasNull) {
1565 SmallPtrSet<Instruction *, 4> DependingInstructions;
1566 SmallPtrSet<const BasicBlock *, 4> Visited;
1567
1568 // Check that there is nothing that cares about the reference
1569 // count between the call and the phi.
Dan Gohman8478d762012-04-13 00:59:57 +00001570 switch (Class) {
1571 case IC_Retain:
1572 case IC_RetainBlock:
1573 // These can always be moved up.
1574 break;
1575 case IC_Release:
Dan Gohman41375a32012-05-08 23:39:44 +00001576 // These can't be moved across things that care about the retain
1577 // count.
Dan Gohman8478d762012-04-13 00:59:57 +00001578 FindDependencies(NeedsPositiveRetainCount, Arg,
1579 Inst->getParent(), Inst,
1580 DependingInstructions, Visited, PA);
1581 break;
1582 case IC_Autorelease:
1583 // These can't be moved across autorelease pool scope boundaries.
1584 FindDependencies(AutoreleasePoolBoundary, Arg,
1585 Inst->getParent(), Inst,
1586 DependingInstructions, Visited, PA);
1587 break;
1588 case IC_RetainRV:
1589 case IC_AutoreleaseRV:
1590 // Don't move these; the RV optimization depends on the autoreleaseRV
1591 // being tail called, and the retainRV being immediately after a call
1592 // (which might still happen if we get lucky with codegen layout, but
1593 // it's not worth taking the chance).
1594 continue;
1595 default:
1596 llvm_unreachable("Invalid dependence flavor");
1597 }
1598
John McCalld935e9c2011-06-15 23:37:01 +00001599 if (DependingInstructions.size() == 1 &&
1600 *DependingInstructions.begin() == PN) {
1601 Changed = true;
1602 ++NumPartialNoops;
1603 // Clone the call into each predecessor that has a non-null value.
1604 CallInst *CInst = cast<CallInst>(Inst);
Chris Lattner229907c2011-07-18 04:54:35 +00001605 Type *ParamTy = CInst->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001606 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1607 Value *Incoming =
1608 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
Michael Gottesman65c24812013-03-25 09:27:43 +00001609 if (!IsNullOrUndef(Incoming)) {
John McCalld935e9c2011-06-15 23:37:01 +00001610 CallInst *Clone = cast<CallInst>(CInst->clone());
1611 Value *Op = PN->getIncomingValue(i);
1612 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
1613 if (Op->getType() != ParamTy)
1614 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
1615 Clone->setArgOperand(0, Op);
1616 Clone->insertBefore(InsertPos);
Michael Gottesmanc189a392013-01-09 19:23:24 +00001617
Michael Gottesman89279f82013-04-05 18:10:41 +00001618 DEBUG(dbgs() << "Cloning "
Michael Gottesmanc189a392013-01-09 19:23:24 +00001619 << *CInst << "\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00001620 "And inserting clone at " << *InsertPos << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001621 Worklist.push_back(std::make_pair(Clone, Incoming));
1622 }
1623 }
1624 // Erase the original call.
Michael Gottesmanc189a392013-01-09 19:23:24 +00001625 DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001626 EraseInstruction(CInst);
1627 continue;
1628 }
1629 }
1630 } while (!Worklist.empty());
1631 }
1632}
1633
Michael Gottesman323964c2013-04-18 05:39:45 +00001634/// If we have a top down pointer in the S_Use state, make sure that there are
1635/// no CFG hazards by checking the states of various bottom up pointers.
1636static void CheckForUseCFGHazard(const Sequence SuccSSeq,
1637 const bool SuccSRRIKnownSafe,
1638 PtrState &S,
1639 bool &SomeSuccHasSame,
1640 bool &AllSuccsHaveSame,
1641 bool &ShouldContinue) {
1642 switch (SuccSSeq) {
1643 case S_CanRelease: {
1644 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
1645 S.ClearSequenceProgress();
1646 break;
1647 }
1648 ShouldContinue = true;
1649 break;
1650 }
1651 case S_Use:
1652 SomeSuccHasSame = true;
1653 break;
1654 case S_Stop:
1655 case S_Release:
1656 case S_MovableRelease:
1657 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
1658 AllSuccsHaveSame = false;
1659 break;
1660 case S_Retain:
1661 llvm_unreachable("bottom-up pointer in retain state!");
1662 case S_None:
1663 llvm_unreachable("This should have been handled earlier.");
1664 }
1665}
1666
1667/// If we have a Top Down pointer in the S_CanRelease state, make sure that
1668/// there are no CFG hazards by checking the states of various bottom up
1669/// pointers.
1670static void CheckForCanReleaseCFGHazard(const Sequence SuccSSeq,
1671 const bool SuccSRRIKnownSafe,
1672 PtrState &S,
1673 bool &SomeSuccHasSame,
1674 bool &AllSuccsHaveSame) {
1675 switch (SuccSSeq) {
1676 case S_CanRelease:
1677 SomeSuccHasSame = true;
1678 break;
1679 case S_Stop:
1680 case S_Release:
1681 case S_MovableRelease:
1682 case S_Use:
1683 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
1684 AllSuccsHaveSame = false;
1685 break;
1686 case S_Retain:
1687 llvm_unreachable("bottom-up pointer in retain state!");
1688 case S_None:
1689 llvm_unreachable("This should have been handled earlier.");
1690 }
1691}
1692
Michael Gottesman97e3df02013-01-14 00:35:14 +00001693/// Check for critical edges, loop boundaries, irreducible control flow, or
1694/// other CFG structures where moving code across the edge would result in it
1695/// being executed more.
John McCalld935e9c2011-06-15 23:37:01 +00001696void
1697ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
1698 DenseMap<const BasicBlock *, BBState> &BBStates,
1699 BBState &MyStates) const {
1700 // If any top-down local-use or possible-dec has a succ which is earlier in
1701 // the sequence, forget it.
Dan Gohman55b06742012-03-02 01:13:53 +00001702 for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
Michael Gottesman323964c2013-04-18 05:39:45 +00001703 E = MyStates.top_down_ptr_end(); I != E; ++I) {
1704 PtrState &S = I->second;
1705 const Sequence Seq = I->second.GetSeq();
Dan Gohman0155f302012-02-17 18:59:53 +00001706
Michael Gottesman323964c2013-04-18 05:39:45 +00001707 // We only care about S_Retain, S_CanRelease, and S_Use.
1708 if (Seq == S_None)
1709 continue;
Dan Gohman0155f302012-02-17 18:59:53 +00001710
Michael Gottesman323964c2013-04-18 05:39:45 +00001711 // Make sure that if extra top down states are added in the future that this
1712 // code is updated to handle it.
1713 assert((Seq == S_Retain || Seq == S_CanRelease || Seq == S_Use) &&
1714 "Unknown top down sequence state.");
1715
1716 const Value *Arg = I->first;
1717 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
1718 bool SomeSuccHasSame = false;
1719 bool AllSuccsHaveSame = true;
1720
1721 succ_const_iterator SI(TI), SE(TI, false);
1722
1723 for (; SI != SE; ++SI) {
1724 // If VisitBottomUp has pointer information for this successor, take
1725 // what we know about it.
1726 const DenseMap<const BasicBlock *, BBState>::iterator BBI =
1727 BBStates.find(*SI);
1728 assert(BBI != BBStates.end());
1729 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
1730 const Sequence SuccSSeq = SuccS.GetSeq();
1731
1732 // If bottom up, the pointer is in an S_None state, clear the sequence
1733 // progress since the sequence in the bottom up state finished
1734 // suggesting a mismatch in between retains/releases. This is true for
1735 // all three cases that we are handling here: S_Retain, S_Use, and
1736 // S_CanRelease.
1737 if (SuccSSeq == S_None) {
Dan Gohman12130272011-08-12 00:26:31 +00001738 S.ClearSequenceProgress();
Michael Gottesman323964c2013-04-18 05:39:45 +00001739 continue;
1740 }
1741
1742 // If we have S_Use or S_CanRelease, perform our check for cfg hazard
1743 // checks.
1744 const bool SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
1745
1746 // *NOTE* We do not use Seq from above here since we are allowing for
1747 // S.GetSeq() to change while we are visiting basic blocks.
1748 switch(S.GetSeq()) {
1749 case S_Use: {
1750 bool ShouldContinue = false;
1751 CheckForUseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S,
1752 SomeSuccHasSame, AllSuccsHaveSame,
1753 ShouldContinue);
1754 if (ShouldContinue)
1755 continue;
1756 break;
1757 }
1758 case S_CanRelease: {
1759 CheckForCanReleaseCFGHazard(SuccSSeq, SuccSRRIKnownSafe,
1760 S, SomeSuccHasSame,
1761 AllSuccsHaveSame);
1762 break;
1763 }
1764 case S_Retain:
1765 case S_None:
1766 case S_Stop:
1767 case S_Release:
1768 case S_MovableRelease:
1769 break;
1770 }
John McCalld935e9c2011-06-15 23:37:01 +00001771 }
Michael Gottesman323964c2013-04-18 05:39:45 +00001772
1773 // If the state at the other end of any of the successor edges
1774 // matches the current state, require all edges to match. This
1775 // guards against loops in the middle of a sequence.
1776 if (SomeSuccHasSame && !AllSuccsHaveSame)
1777 S.ClearSequenceProgress();
1778 }
John McCalld935e9c2011-06-15 23:37:01 +00001779}
1780
1781bool
Dan Gohman817a7c62012-03-22 18:24:56 +00001782ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
Dan Gohman5c70fad2012-03-23 17:47:54 +00001783 BasicBlock *BB,
Dan Gohman817a7c62012-03-22 18:24:56 +00001784 MapVector<Value *, RRInfo> &Retains,
1785 BBState &MyStates) {
1786 bool NestingDetected = false;
1787 InstructionClass Class = GetInstructionClass(Inst);
1788 const Value *Arg = 0;
Michael Gottesman79249972013-04-05 23:46:45 +00001789
Michael Gottesman1d8d2572013-04-05 22:54:28 +00001790 DEBUG(dbgs() << "Class: " << Class << "\n");
Michael Gottesman79249972013-04-05 23:46:45 +00001791
Dan Gohman817a7c62012-03-22 18:24:56 +00001792 switch (Class) {
1793 case IC_Release: {
1794 Arg = GetObjCArg(Inst);
1795
1796 PtrState &S = MyStates.getPtrBottomUpState(Arg);
1797
1798 // If we see two releases in a row on the same pointer. If so, make
1799 // a note, and we'll cicle back to revisit it after we've
1800 // hopefully eliminated the second release, which may allow us to
1801 // eliminate the first release too.
1802 // Theoretically we could implement removal of nested retain+release
1803 // pairs by making PtrState hold a stack of states, but this is
1804 // simple and avoids adding overhead for the non-nested case.
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001805 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001806 DEBUG(dbgs() << "Found nested releases (i.e. a release pair)\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00001807 NestingDetected = true;
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001808 }
Dan Gohman817a7c62012-03-22 18:24:56 +00001809
Dan Gohman817a7c62012-03-22 18:24:56 +00001810 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001811 Sequence NewSeq = ReleaseMetadata ? S_MovableRelease : S_Release;
1812 ANNOTATE_BOTTOMUP(Inst, Arg, S.GetSeq(), NewSeq);
1813 S.ResetSequenceProgress(NewSeq);
Dan Gohman817a7c62012-03-22 18:24:56 +00001814 S.RRI.ReleaseMetadata = ReleaseMetadata;
Michael Gottesman07beea42013-03-23 05:31:01 +00001815 S.RRI.KnownSafe = S.HasKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001816 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
1817 S.RRI.Calls.insert(Inst);
Dan Gohmandf476e52012-09-04 23:16:20 +00001818 S.SetKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001819 break;
1820 }
1821 case IC_RetainBlock:
Michael Gottesman158fdf62013-03-28 20:11:19 +00001822 // In OptimizeIndividualCalls, we have strength reduced all optimizable
1823 // objc_retainBlocks to objc_retains. Thus at this point any
1824 // objc_retainBlocks that we see are not optimizable.
1825 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001826 case IC_Retain:
1827 case IC_RetainRV: {
1828 Arg = GetObjCArg(Inst);
1829
1830 PtrState &S = MyStates.getPtrBottomUpState(Arg);
Dan Gohman62079b42012-04-25 00:50:46 +00001831 S.SetKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001832
Michael Gottesman81b1d432013-03-26 00:42:04 +00001833 Sequence OldSeq = S.GetSeq();
1834 switch (OldSeq) {
Dan Gohman817a7c62012-03-22 18:24:56 +00001835 case S_Stop:
1836 case S_Release:
1837 case S_MovableRelease:
1838 case S_Use:
Michael Gottesman1d8d2572013-04-05 22:54:28 +00001839 // If OldSeq is not S_Use or OldSeq is S_Use and we are tracking an
1840 // imprecise release, clear our reverse insertion points.
1841 if (OldSeq != S_Use || S.RRI.IsTrackingImpreciseReleases())
1842 S.RRI.ReverseInsertPts.clear();
Dan Gohman817a7c62012-03-22 18:24:56 +00001843 // FALL THROUGH
1844 case S_CanRelease:
1845 // Don't do retain+release tracking for IC_RetainRV, because it's
1846 // better to let it remain as the first instruction after a call.
Michael Gottesmanba648592013-03-28 23:08:44 +00001847 if (Class != IC_RetainRV)
Dan Gohman817a7c62012-03-22 18:24:56 +00001848 Retains[Inst] = S.RRI;
Dan Gohman817a7c62012-03-22 18:24:56 +00001849 S.ClearSequenceProgress();
1850 break;
1851 case S_None:
1852 break;
1853 case S_Retain:
1854 llvm_unreachable("bottom-up pointer in retain state!");
1855 }
Michael Gottesman79249972013-04-05 23:46:45 +00001856 ANNOTATE_BOTTOMUP(Inst, Arg, OldSeq, S.GetSeq());
Michael Gottesman31ba23a2013-04-05 22:54:32 +00001857 // A retain moving bottom up can be a use.
1858 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001859 }
1860 case IC_AutoreleasepoolPop:
1861 // Conservatively, clear MyStates for all known pointers.
1862 MyStates.clearBottomUpPointers();
1863 return NestingDetected;
1864 case IC_AutoreleasepoolPush:
1865 case IC_None:
1866 // These are irrelevant.
1867 return NestingDetected;
1868 default:
1869 break;
1870 }
1871
1872 // Consider any other possible effects of this instruction on each
1873 // pointer being tracked.
1874 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
1875 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
1876 const Value *Ptr = MI->first;
1877 if (Ptr == Arg)
1878 continue; // Handled above.
1879 PtrState &S = MI->second;
1880 Sequence Seq = S.GetSeq();
1881
1882 // Check for possible releases.
1883 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001884 DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr
1885 << "\n");
Michael Gottesman764b1cf2013-03-23 05:46:19 +00001886 S.ClearKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001887 switch (Seq) {
1888 case S_Use:
1889 S.SetSeq(S_CanRelease);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001890 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S.GetSeq());
Dan Gohman817a7c62012-03-22 18:24:56 +00001891 continue;
1892 case S_CanRelease:
1893 case S_Release:
1894 case S_MovableRelease:
1895 case S_Stop:
1896 case S_None:
1897 break;
1898 case S_Retain:
1899 llvm_unreachable("bottom-up pointer in retain state!");
1900 }
1901 }
1902
1903 // Check for possible direct uses.
1904 switch (Seq) {
1905 case S_Release:
1906 case S_MovableRelease:
1907 if (CanUse(Inst, Ptr, PA, Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001908 DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr
1909 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00001910 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohman5c70fad2012-03-23 17:47:54 +00001911 // If this is an invoke instruction, we're scanning it as part of
1912 // one of its successor blocks, since we can't insert code after it
1913 // in its own block, and we don't want to split critical edges.
1914 if (isa<InvokeInst>(Inst))
1915 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
1916 else
Francois Pichet4b9ab742012-03-24 01:36:37 +00001917 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohman817a7c62012-03-22 18:24:56 +00001918 S.SetSeq(S_Use);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001919 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
John McCall20182ac2013-03-22 21:38:36 +00001920 } else if (Seq == S_Release && IsUser(Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001921 DEBUG(dbgs() << "PreciseReleaseUse: Seq: " << Seq << "; " << *Ptr
1922 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00001923 // Non-movable releases depend on any possible objc pointer use.
1924 S.SetSeq(S_Stop);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001925 ANNOTATE_BOTTOMUP(Inst, Ptr, S_Release, S_Stop);
Dan Gohman817a7c62012-03-22 18:24:56 +00001926 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohman5c70fad2012-03-23 17:47:54 +00001927 // As above; handle invoke specially.
1928 if (isa<InvokeInst>(Inst))
1929 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
1930 else
Francois Pichet4b9ab742012-03-24 01:36:37 +00001931 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohman817a7c62012-03-22 18:24:56 +00001932 }
1933 break;
1934 case S_Stop:
Michael Gottesman81b1d432013-03-26 00:42:04 +00001935 if (CanUse(Inst, Ptr, PA, Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001936 DEBUG(dbgs() << "PreciseStopUse: Seq: " << Seq << "; " << *Ptr
1937 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00001938 S.SetSeq(S_Use);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001939 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
1940 }
Dan Gohman817a7c62012-03-22 18:24:56 +00001941 break;
1942 case S_CanRelease:
1943 case S_Use:
1944 case S_None:
1945 break;
1946 case S_Retain:
1947 llvm_unreachable("bottom-up pointer in retain state!");
1948 }
1949 }
1950
1951 return NestingDetected;
1952}
1953
1954bool
John McCalld935e9c2011-06-15 23:37:01 +00001955ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
1956 DenseMap<const BasicBlock *, BBState> &BBStates,
1957 MapVector<Value *, RRInfo> &Retains) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001958
1959 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitBottomUp ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00001960
John McCalld935e9c2011-06-15 23:37:01 +00001961 bool NestingDetected = false;
1962 BBState &MyStates = BBStates[BB];
1963
1964 // Merge the states from each successor to compute the initial state
1965 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00001966 BBState::edge_iterator SI(MyStates.succ_begin()),
1967 SE(MyStates.succ_end());
1968 if (SI != SE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001969 const BasicBlock *Succ = *SI;
1970 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
1971 assert(I != BBStates.end());
1972 MyStates.InitFromSucc(I->second);
1973 ++SI;
1974 for (; SI != SE; ++SI) {
1975 Succ = *SI;
1976 I = BBStates.find(Succ);
1977 assert(I != BBStates.end());
1978 MyStates.MergeSucc(I->second);
1979 }
Michael Gottesman60f6b282013-03-29 05:13:07 +00001980 }
Michael Gottesmancd4de0f2013-03-26 00:42:09 +00001981
Michael Gottesman43e7e002013-04-03 22:41:59 +00001982 // If ARC Annotations are enabled, output the current state of pointers at the
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00001983 // bottom of the basic block.
Michael Gottesman43e7e002013-04-03 22:41:59 +00001984 ANNOTATE_BOTTOMUP_BBEND(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00001985
John McCalld935e9c2011-06-15 23:37:01 +00001986 // Visit all the instructions, bottom-up.
1987 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
1988 Instruction *Inst = llvm::prior(I);
Dan Gohman5c70fad2012-03-23 17:47:54 +00001989
1990 // Invoke instructions are visited as part of their successors (below).
1991 if (isa<InvokeInst>(Inst))
1992 continue;
1993
Michael Gottesman89279f82013-04-05 18:10:41 +00001994 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001995
Dan Gohman5c70fad2012-03-23 17:47:54 +00001996 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
1997 }
1998
Dan Gohmandae33492012-04-27 18:56:31 +00001999 // If there's a predecessor with an invoke, visit the invoke as if it were
2000 // part of this block, since we can't insert code after an invoke in its own
2001 // block, and we don't want to split critical edges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002002 for (BBState::edge_iterator PI(MyStates.pred_begin()),
2003 PE(MyStates.pred_end()); PI != PE; ++PI) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00002004 BasicBlock *Pred = *PI;
Dan Gohmandae33492012-04-27 18:56:31 +00002005 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
2006 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
Dan Gohman817a7c62012-03-22 18:24:56 +00002007 }
John McCalld935e9c2011-06-15 23:37:01 +00002008
Michael Gottesman43e7e002013-04-03 22:41:59 +00002009 // If ARC Annotations are enabled, output the current state of pointers at the
2010 // top of the basic block.
2011 ANNOTATE_BOTTOMUP_BBSTART(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002012
Dan Gohman817a7c62012-03-22 18:24:56 +00002013 return NestingDetected;
2014}
John McCalld935e9c2011-06-15 23:37:01 +00002015
Dan Gohman817a7c62012-03-22 18:24:56 +00002016bool
2017ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
2018 DenseMap<Value *, RRInfo> &Releases,
2019 BBState &MyStates) {
2020 bool NestingDetected = false;
2021 InstructionClass Class = GetInstructionClass(Inst);
2022 const Value *Arg = 0;
John McCalld935e9c2011-06-15 23:37:01 +00002023
Dan Gohman817a7c62012-03-22 18:24:56 +00002024 switch (Class) {
2025 case IC_RetainBlock:
Michael Gottesman158fdf62013-03-28 20:11:19 +00002026 // In OptimizeIndividualCalls, we have strength reduced all optimizable
2027 // objc_retainBlocks to objc_retains. Thus at this point any
2028 // objc_retainBlocks that we see are not optimizable.
2029 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00002030 case IC_Retain:
2031 case IC_RetainRV: {
2032 Arg = GetObjCArg(Inst);
2033
2034 PtrState &S = MyStates.getPtrTopDownState(Arg);
2035
2036 // Don't do retain+release tracking for IC_RetainRV, because it's
2037 // better to let it remain as the first instruction after a call.
2038 if (Class != IC_RetainRV) {
2039 // If we see two retains in a row on the same pointer. If so, make
John McCalld935e9c2011-06-15 23:37:01 +00002040 // a note, and we'll cicle back to revisit it after we've
Dan Gohman817a7c62012-03-22 18:24:56 +00002041 // hopefully eliminated the second retain, which may allow us to
2042 // eliminate the first retain too.
John McCalld935e9c2011-06-15 23:37:01 +00002043 // Theoretically we could implement removal of nested retain+release
2044 // pairs by making PtrState hold a stack of states, but this is
2045 // simple and avoids adding overhead for the non-nested case.
Dan Gohman817a7c62012-03-22 18:24:56 +00002046 if (S.GetSeq() == S_Retain)
John McCalld935e9c2011-06-15 23:37:01 +00002047 NestingDetected = true;
2048
Michael Gottesman81b1d432013-03-26 00:42:04 +00002049 ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_Retain);
Dan Gohman62079b42012-04-25 00:50:46 +00002050 S.ResetSequenceProgress(S_Retain);
Michael Gottesman07beea42013-03-23 05:31:01 +00002051 S.RRI.KnownSafe = S.HasKnownPositiveRefCount();
John McCalld935e9c2011-06-15 23:37:01 +00002052 S.RRI.Calls.insert(Inst);
John McCalld935e9c2011-06-15 23:37:01 +00002053 }
John McCalld935e9c2011-06-15 23:37:01 +00002054
Dan Gohmandf476e52012-09-04 23:16:20 +00002055 S.SetKnownPositiveRefCount();
Dan Gohmanf64ff8e2012-07-23 19:27:31 +00002056
2057 // A retain can be a potential use; procede to the generic checking
2058 // code below.
2059 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00002060 }
2061 case IC_Release: {
2062 Arg = GetObjCArg(Inst);
2063
2064 PtrState &S = MyStates.getPtrTopDownState(Arg);
Michael Gottesman764b1cf2013-03-23 05:46:19 +00002065 S.ClearKnownPositiveRefCount();
Michael Gottesman79249972013-04-05 23:46:45 +00002066
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002067 Sequence OldSeq = S.GetSeq();
Michael Gottesman79249972013-04-05 23:46:45 +00002068
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002069 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
Michael Gottesman79249972013-04-05 23:46:45 +00002070
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002071 switch (OldSeq) {
Dan Gohman817a7c62012-03-22 18:24:56 +00002072 case S_Retain:
2073 case S_CanRelease:
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002074 if (OldSeq == S_Retain || ReleaseMetadata != 0)
2075 S.RRI.ReverseInsertPts.clear();
Dan Gohman817a7c62012-03-22 18:24:56 +00002076 // FALL THROUGH
2077 case S_Use:
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002078 S.RRI.ReleaseMetadata = ReleaseMetadata;
Dan Gohman817a7c62012-03-22 18:24:56 +00002079 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2080 Releases[Inst] = S.RRI;
Michael Gottesman81b1d432013-03-26 00:42:04 +00002081 ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_None);
Dan Gohman817a7c62012-03-22 18:24:56 +00002082 S.ClearSequenceProgress();
2083 break;
2084 case S_None:
2085 break;
2086 case S_Stop:
2087 case S_Release:
2088 case S_MovableRelease:
2089 llvm_unreachable("top-down pointer in release state!");
2090 }
2091 break;
2092 }
2093 case IC_AutoreleasepoolPop:
2094 // Conservatively, clear MyStates for all known pointers.
2095 MyStates.clearTopDownPointers();
2096 return NestingDetected;
2097 case IC_AutoreleasepoolPush:
2098 case IC_None:
2099 // These are irrelevant.
2100 return NestingDetected;
2101 default:
2102 break;
2103 }
2104
2105 // Consider any other possible effects of this instruction on each
2106 // pointer being tracked.
2107 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
2108 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
2109 const Value *Ptr = MI->first;
2110 if (Ptr == Arg)
2111 continue; // Handled above.
2112 PtrState &S = MI->second;
2113 Sequence Seq = S.GetSeq();
2114
2115 // Check for possible releases.
2116 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Michael Gottesmanbab49e972013-04-05 18:26:08 +00002117 DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr
Michael Gottesman79249972013-04-05 23:46:45 +00002118 << "\n");
Michael Gottesman764b1cf2013-03-23 05:46:19 +00002119 S.ClearKnownPositiveRefCount();
John McCalld935e9c2011-06-15 23:37:01 +00002120 switch (Seq) {
Dan Gohman817a7c62012-03-22 18:24:56 +00002121 case S_Retain:
2122 S.SetSeq(S_CanRelease);
Michael Gottesman81b1d432013-03-26 00:42:04 +00002123 ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_CanRelease);
Dan Gohman817a7c62012-03-22 18:24:56 +00002124 assert(S.RRI.ReverseInsertPts.empty());
2125 S.RRI.ReverseInsertPts.insert(Inst);
2126
2127 // One call can't cause a transition from S_Retain to S_CanRelease
2128 // and S_CanRelease to S_Use. If we've made the first transition,
2129 // we're done.
2130 continue;
John McCalld935e9c2011-06-15 23:37:01 +00002131 case S_Use:
Dan Gohman817a7c62012-03-22 18:24:56 +00002132 case S_CanRelease:
John McCalld935e9c2011-06-15 23:37:01 +00002133 case S_None:
2134 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00002135 case S_Stop:
2136 case S_Release:
2137 case S_MovableRelease:
2138 llvm_unreachable("top-down pointer in release state!");
John McCalld935e9c2011-06-15 23:37:01 +00002139 }
2140 }
Dan Gohman817a7c62012-03-22 18:24:56 +00002141
2142 // Check for possible direct uses.
2143 switch (Seq) {
2144 case S_CanRelease:
Michael Gottesman81b1d432013-03-26 00:42:04 +00002145 if (CanUse(Inst, Ptr, PA, Class)) {
Michael Gottesmanbab49e972013-04-05 18:26:08 +00002146 DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr
2147 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00002148 S.SetSeq(S_Use);
Michael Gottesman81b1d432013-03-26 00:42:04 +00002149 ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_Use);
2150 }
Dan Gohman817a7c62012-03-22 18:24:56 +00002151 break;
2152 case S_Retain:
2153 case S_Use:
2154 case S_None:
2155 break;
2156 case S_Stop:
2157 case S_Release:
2158 case S_MovableRelease:
2159 llvm_unreachable("top-down pointer in release state!");
2160 }
John McCalld935e9c2011-06-15 23:37:01 +00002161 }
2162
2163 return NestingDetected;
2164}
2165
2166bool
2167ObjCARCOpt::VisitTopDown(BasicBlock *BB,
2168 DenseMap<const BasicBlock *, BBState> &BBStates,
2169 DenseMap<Value *, RRInfo> &Releases) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002170 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitTopDown ==\n");
John McCalld935e9c2011-06-15 23:37:01 +00002171 bool NestingDetected = false;
2172 BBState &MyStates = BBStates[BB];
2173
2174 // Merge the states from each predecessor to compute the initial state
2175 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00002176 BBState::edge_iterator PI(MyStates.pred_begin()),
2177 PE(MyStates.pred_end());
2178 if (PI != PE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002179 const BasicBlock *Pred = *PI;
2180 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
2181 assert(I != BBStates.end());
2182 MyStates.InitFromPred(I->second);
2183 ++PI;
2184 for (; PI != PE; ++PI) {
2185 Pred = *PI;
2186 I = BBStates.find(Pred);
2187 assert(I != BBStates.end());
2188 MyStates.MergePred(I->second);
2189 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002190 }
John McCalld935e9c2011-06-15 23:37:01 +00002191
Michael Gottesman43e7e002013-04-03 22:41:59 +00002192 // If ARC Annotations are enabled, output the current state of pointers at the
2193 // top of the basic block.
2194 ANNOTATE_TOPDOWN_BBSTART(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002195
John McCalld935e9c2011-06-15 23:37:01 +00002196 // Visit all the instructions, top-down.
2197 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2198 Instruction *Inst = I;
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00002199
Michael Gottesman89279f82013-04-05 18:10:41 +00002200 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00002201
Dan Gohman817a7c62012-03-22 18:24:56 +00002202 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00002203 }
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002204
Michael Gottesman43e7e002013-04-03 22:41:59 +00002205 // If ARC Annotations are enabled, output the current state of pointers at the
2206 // bottom of the basic block.
2207 ANNOTATE_TOPDOWN_BBEND(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002208
Michael Gottesmanffef24f2013-04-17 20:48:01 +00002209#ifdef ARC_ANNOTATIONS
Michael Gottesmanadb921a2013-04-17 21:03:53 +00002210 if (!(EnableARCAnnotations && DisableCheckForCFGHazards))
Michael Gottesmanffef24f2013-04-17 20:48:01 +00002211#endif
John McCalld935e9c2011-06-15 23:37:01 +00002212 CheckForCFGHazards(BB, BBStates, MyStates);
2213 return NestingDetected;
2214}
2215
Dan Gohmana53a12c2011-12-12 19:42:25 +00002216static void
2217ComputePostOrders(Function &F,
2218 SmallVectorImpl<BasicBlock *> &PostOrder,
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002219 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
2220 unsigned NoObjCARCExceptionsMDKind,
2221 DenseMap<const BasicBlock *, BBState> &BBStates) {
Michael Gottesman97e3df02013-01-14 00:35:14 +00002222 /// The visited set, for doing DFS walks.
Dan Gohmana53a12c2011-12-12 19:42:25 +00002223 SmallPtrSet<BasicBlock *, 16> Visited;
2224
2225 // Do DFS, computing the PostOrder.
2226 SmallPtrSet<BasicBlock *, 16> OnStack;
2227 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002228
2229 // Functions always have exactly one entry block, and we don't have
2230 // any other block that we treat like an entry block.
Dan Gohmana53a12c2011-12-12 19:42:25 +00002231 BasicBlock *EntryBB = &F.getEntryBlock();
Dan Gohman41375a32012-05-08 23:39:44 +00002232 BBState &MyStates = BBStates[EntryBB];
2233 MyStates.SetAsEntry();
2234 TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
2235 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
Dan Gohmana53a12c2011-12-12 19:42:25 +00002236 Visited.insert(EntryBB);
2237 OnStack.insert(EntryBB);
2238 do {
2239 dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002240 BasicBlock *CurrBB = SuccStack.back().first;
2241 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
2242 succ_iterator SE(TI, false);
Dan Gohman41375a32012-05-08 23:39:44 +00002243
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002244 while (SuccStack.back().second != SE) {
2245 BasicBlock *SuccBB = *SuccStack.back().second++;
2246 if (Visited.insert(SuccBB)) {
Dan Gohman41375a32012-05-08 23:39:44 +00002247 TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
2248 SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002249 BBStates[CurrBB].addSucc(SuccBB);
Dan Gohman41375a32012-05-08 23:39:44 +00002250 BBState &SuccStates = BBStates[SuccBB];
2251 SuccStates.addPred(CurrBB);
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002252 OnStack.insert(SuccBB);
Dan Gohmana53a12c2011-12-12 19:42:25 +00002253 goto dfs_next_succ;
2254 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002255
2256 if (!OnStack.count(SuccBB)) {
2257 BBStates[CurrBB].addSucc(SuccBB);
2258 BBStates[SuccBB].addPred(CurrBB);
2259 }
Dan Gohmana53a12c2011-12-12 19:42:25 +00002260 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002261 OnStack.erase(CurrBB);
2262 PostOrder.push_back(CurrBB);
2263 SuccStack.pop_back();
Dan Gohmana53a12c2011-12-12 19:42:25 +00002264 } while (!SuccStack.empty());
2265
2266 Visited.clear();
2267
Dan Gohmana53a12c2011-12-12 19:42:25 +00002268 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002269 // Functions may have many exits, and there also blocks which we treat
2270 // as exits due to ignored edges.
2271 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
2272 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
2273 BasicBlock *ExitBB = I;
2274 BBState &MyStates = BBStates[ExitBB];
2275 if (!MyStates.isExit())
2276 continue;
2277
Dan Gohmandae33492012-04-27 18:56:31 +00002278 MyStates.SetAsExit();
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002279
2280 PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00002281 Visited.insert(ExitBB);
2282 while (!PredStack.empty()) {
2283 reverse_dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002284 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
2285 while (PredStack.back().second != PE) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00002286 BasicBlock *BB = *PredStack.back().second++;
Dan Gohmana53a12c2011-12-12 19:42:25 +00002287 if (Visited.insert(BB)) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002288 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00002289 goto reverse_dfs_next_succ;
2290 }
2291 }
2292 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
2293 }
2294 }
2295}
2296
Michael Gottesman97e3df02013-01-14 00:35:14 +00002297// Visit the function both top-down and bottom-up.
John McCalld935e9c2011-06-15 23:37:01 +00002298bool
2299ObjCARCOpt::Visit(Function &F,
2300 DenseMap<const BasicBlock *, BBState> &BBStates,
2301 MapVector<Value *, RRInfo> &Retains,
2302 DenseMap<Value *, RRInfo> &Releases) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00002303
2304 // Use reverse-postorder traversals, because we magically know that loops
2305 // will be well behaved, i.e. they won't repeatedly call retain on a single
2306 // pointer without doing a release. We can't use the ReversePostOrderTraversal
2307 // class here because we want the reverse-CFG postorder to consider each
2308 // function exit point, and we want to ignore selected cycle edges.
2309 SmallVector<BasicBlock *, 16> PostOrder;
2310 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002311 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
2312 NoObjCARCExceptionsMDKind,
2313 BBStates);
Dan Gohmana53a12c2011-12-12 19:42:25 +00002314
2315 // Use reverse-postorder on the reverse CFG for bottom-up.
John McCalld935e9c2011-06-15 23:37:01 +00002316 bool BottomUpNestingDetected = false;
Dan Gohmanc57b58c2011-08-18 21:27:42 +00002317 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
Dan Gohmana53a12c2011-12-12 19:42:25 +00002318 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
2319 I != E; ++I)
2320 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
John McCalld935e9c2011-06-15 23:37:01 +00002321
Dan Gohmana53a12c2011-12-12 19:42:25 +00002322 // Use reverse-postorder for top-down.
John McCalld935e9c2011-06-15 23:37:01 +00002323 bool TopDownNestingDetected = false;
Dan Gohmana53a12c2011-12-12 19:42:25 +00002324 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2325 PostOrder.rbegin(), E = PostOrder.rend();
2326 I != E; ++I)
2327 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
John McCalld935e9c2011-06-15 23:37:01 +00002328
2329 return TopDownNestingDetected && BottomUpNestingDetected;
2330}
2331
Michael Gottesman97e3df02013-01-14 00:35:14 +00002332/// Move the calls in RetainsToMove and ReleasesToMove.
John McCalld935e9c2011-06-15 23:37:01 +00002333void ObjCARCOpt::MoveCalls(Value *Arg,
2334 RRInfo &RetainsToMove,
2335 RRInfo &ReleasesToMove,
2336 MapVector<Value *, RRInfo> &Retains,
2337 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman6320f522011-07-22 22:29:21 +00002338 SmallVectorImpl<Instruction *> &DeadInsts,
Michael Gottesman79249972013-04-05 23:46:45 +00002339 Module *M) {
Chris Lattner229907c2011-07-18 04:54:35 +00002340 Type *ArgTy = Arg->getType();
Dan Gohman6320f522011-07-22 22:29:21 +00002341 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
Michael Gottesman79249972013-04-05 23:46:45 +00002342
Michael Gottesman89279f82013-04-05 18:10:41 +00002343 DEBUG(dbgs() << "== ObjCARCOpt::MoveCalls ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00002344
John McCalld935e9c2011-06-15 23:37:01 +00002345 // Insert the new retain and release calls.
2346 for (SmallPtrSet<Instruction *, 2>::const_iterator
2347 PI = ReleasesToMove.ReverseInsertPts.begin(),
2348 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2349 Instruction *InsertPt = *PI;
2350 Value *MyArg = ArgTy == ParamTy ? Arg :
2351 new BitCastInst(Arg, ParamTy, "", InsertPt);
2352 CallInst *Call =
Michael Gottesmanba648592013-03-28 23:08:44 +00002353 CallInst::Create(getRetainCallee(M), MyArg, "", InsertPt);
John McCalld935e9c2011-06-15 23:37:01 +00002354 Call->setDoesNotThrow();
Michael Gottesmanba648592013-03-28 23:08:44 +00002355 Call->setTailCall();
Michael Gottesman60f6b282013-03-29 05:13:07 +00002356
Michael Gottesmandf110ac2013-04-21 00:30:50 +00002357 DEBUG(dbgs() << "Inserting new Retain: " << *Call << "\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00002358 "At insertion point: " << *InsertPt << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002359 }
2360 for (SmallPtrSet<Instruction *, 2>::const_iterator
2361 PI = RetainsToMove.ReverseInsertPts.begin(),
2362 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00002363 Instruction *InsertPt = *PI;
2364 Value *MyArg = ArgTy == ParamTy ? Arg :
2365 new BitCastInst(Arg, ParamTy, "", InsertPt);
2366 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
2367 "", InsertPt);
2368 // Attach a clang.imprecise_release metadata tag, if appropriate.
2369 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
2370 Call->setMetadata(ImpreciseReleaseMDKind, M);
2371 Call->setDoesNotThrow();
2372 if (ReleasesToMove.IsTailCallRelease)
2373 Call->setTailCall();
Michael Gottesmanc189a392013-01-09 19:23:24 +00002374
Michael Gottesman89279f82013-04-05 18:10:41 +00002375 DEBUG(dbgs() << "Inserting new Release: " << *Call << "\n"
2376 "At insertion point: " << *InsertPt << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002377 }
2378
2379 // Delete the original retain and release calls.
2380 for (SmallPtrSet<Instruction *, 2>::const_iterator
2381 AI = RetainsToMove.Calls.begin(),
2382 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
2383 Instruction *OrigRetain = *AI;
2384 Retains.blot(OrigRetain);
2385 DeadInsts.push_back(OrigRetain);
Michael Gottesman89279f82013-04-05 18:10:41 +00002386 DEBUG(dbgs() << "Deleting retain: " << *OrigRetain << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002387 }
2388 for (SmallPtrSet<Instruction *, 2>::const_iterator
2389 AI = ReleasesToMove.Calls.begin(),
2390 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
2391 Instruction *OrigRelease = *AI;
2392 Releases.erase(OrigRelease);
2393 DeadInsts.push_back(OrigRelease);
Michael Gottesman89279f82013-04-05 18:10:41 +00002394 DEBUG(dbgs() << "Deleting release: " << *OrigRelease << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002395 }
Michael Gottesman79249972013-04-05 23:46:45 +00002396
John McCalld935e9c2011-06-15 23:37:01 +00002397}
2398
Michael Gottesman9de6f962013-01-22 21:49:00 +00002399bool
2400ObjCARCOpt::ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState>
2401 &BBStates,
2402 MapVector<Value *, RRInfo> &Retains,
2403 DenseMap<Value *, RRInfo> &Releases,
2404 Module *M,
2405 SmallVector<Instruction *, 4> &NewRetains,
2406 SmallVector<Instruction *, 4> &NewReleases,
2407 SmallVector<Instruction *, 8> &DeadInsts,
2408 RRInfo &RetainsToMove,
2409 RRInfo &ReleasesToMove,
2410 Value *Arg,
2411 bool KnownSafe,
2412 bool &AnyPairsCompletelyEliminated) {
2413 // If a pair happens in a region where it is known that the reference count
2414 // is already incremented, we can similarly ignore possible decrements.
2415 bool KnownSafeTD = true, KnownSafeBU = true;
2416
2417 // Connect the dots between the top-down-collected RetainsToMove and
2418 // bottom-up-collected ReleasesToMove to form sets of related calls.
2419 // This is an iterative process so that we connect multiple releases
2420 // to multiple retains if needed.
2421 unsigned OldDelta = 0;
2422 unsigned NewDelta = 0;
2423 unsigned OldCount = 0;
2424 unsigned NewCount = 0;
2425 bool FirstRelease = true;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002426 for (;;) {
2427 for (SmallVectorImpl<Instruction *>::const_iterator
2428 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
2429 Instruction *NewRetain = *NI;
2430 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
2431 assert(It != Retains.end());
2432 const RRInfo &NewRetainRRI = It->second;
2433 KnownSafeTD &= NewRetainRRI.KnownSafe;
2434 for (SmallPtrSet<Instruction *, 2>::const_iterator
2435 LI = NewRetainRRI.Calls.begin(),
2436 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
2437 Instruction *NewRetainRelease = *LI;
2438 DenseMap<Value *, RRInfo>::const_iterator Jt =
2439 Releases.find(NewRetainRelease);
2440 if (Jt == Releases.end())
2441 return false;
2442 const RRInfo &NewRetainReleaseRRI = Jt->second;
2443 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
2444 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
2445 OldDelta -=
2446 BBStates[NewRetainRelease->getParent()].GetAllPathCount();
2447
2448 // Merge the ReleaseMetadata and IsTailCallRelease values.
2449 if (FirstRelease) {
2450 ReleasesToMove.ReleaseMetadata =
2451 NewRetainReleaseRRI.ReleaseMetadata;
2452 ReleasesToMove.IsTailCallRelease =
2453 NewRetainReleaseRRI.IsTailCallRelease;
2454 FirstRelease = false;
2455 } else {
2456 if (ReleasesToMove.ReleaseMetadata !=
2457 NewRetainReleaseRRI.ReleaseMetadata)
2458 ReleasesToMove.ReleaseMetadata = 0;
2459 if (ReleasesToMove.IsTailCallRelease !=
2460 NewRetainReleaseRRI.IsTailCallRelease)
2461 ReleasesToMove.IsTailCallRelease = false;
2462 }
2463
2464 // Collect the optimal insertion points.
2465 if (!KnownSafe)
2466 for (SmallPtrSet<Instruction *, 2>::const_iterator
2467 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
2468 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
2469 RI != RE; ++RI) {
2470 Instruction *RIP = *RI;
2471 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
2472 NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
2473 }
2474 NewReleases.push_back(NewRetainRelease);
2475 }
2476 }
2477 }
2478 NewRetains.clear();
2479 if (NewReleases.empty()) break;
2480
2481 // Back the other way.
2482 for (SmallVectorImpl<Instruction *>::const_iterator
2483 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
2484 Instruction *NewRelease = *NI;
2485 DenseMap<Value *, RRInfo>::const_iterator It =
2486 Releases.find(NewRelease);
2487 assert(It != Releases.end());
2488 const RRInfo &NewReleaseRRI = It->second;
2489 KnownSafeBU &= NewReleaseRRI.KnownSafe;
2490 for (SmallPtrSet<Instruction *, 2>::const_iterator
2491 LI = NewReleaseRRI.Calls.begin(),
2492 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
2493 Instruction *NewReleaseRetain = *LI;
2494 MapVector<Value *, RRInfo>::const_iterator Jt =
2495 Retains.find(NewReleaseRetain);
2496 if (Jt == Retains.end())
2497 return false;
2498 const RRInfo &NewReleaseRetainRRI = Jt->second;
2499 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
2500 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
2501 unsigned PathCount =
2502 BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
2503 OldDelta += PathCount;
2504 OldCount += PathCount;
2505
Michael Gottesman9de6f962013-01-22 21:49:00 +00002506 // Collect the optimal insertion points.
2507 if (!KnownSafe)
2508 for (SmallPtrSet<Instruction *, 2>::const_iterator
2509 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
2510 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
2511 RI != RE; ++RI) {
2512 Instruction *RIP = *RI;
2513 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
2514 PathCount = BBStates[RIP->getParent()].GetAllPathCount();
2515 NewDelta += PathCount;
2516 NewCount += PathCount;
2517 }
2518 }
2519 NewRetains.push_back(NewReleaseRetain);
2520 }
2521 }
2522 }
2523 NewReleases.clear();
2524 if (NewRetains.empty()) break;
2525 }
2526
2527 // If the pointer is known incremented or nested, we can safely delete the
2528 // pair regardless of what's between them.
2529 if (KnownSafeTD || KnownSafeBU) {
2530 RetainsToMove.ReverseInsertPts.clear();
2531 ReleasesToMove.ReverseInsertPts.clear();
2532 NewCount = 0;
2533 } else {
2534 // Determine whether the new insertion points we computed preserve the
2535 // balance of retain and release calls through the program.
2536 // TODO: If the fully aggressive solution isn't valid, try to find a
2537 // less aggressive solution which is.
2538 if (NewDelta != 0)
2539 return false;
2540 }
2541
2542 // Determine whether the original call points are balanced in the retain and
2543 // release calls through the program. If not, conservatively don't touch
2544 // them.
2545 // TODO: It's theoretically possible to do code motion in this case, as
2546 // long as the existing imbalances are maintained.
2547 if (OldDelta != 0)
2548 return false;
Michael Gottesman8005ad32013-04-29 06:16:55 +00002549
Michael Gottesmana87bb8f2013-04-29 05:13:13 +00002550#ifdef ARC_ANNOTATIONS
2551 // Do not move calls if ARC annotations are requested.
Michael Gottesman3e3977c2013-04-29 05:25:39 +00002552 if (EnableARCAnnotations)
2553 return false;
Michael Gottesmana87bb8f2013-04-29 05:13:13 +00002554#endif // ARC_ANNOTATIONS
Michael Gottesman9de6f962013-01-22 21:49:00 +00002555
2556 Changed = true;
2557 assert(OldCount != 0 && "Unreachable code?");
2558 NumRRs += OldCount - NewCount;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002559 // Set to true if we completely removed any RR pairs.
Michael Gottesman8b5515f2013-01-22 21:53:43 +00002560 AnyPairsCompletelyEliminated = NewCount == 0;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002561
2562 // We can move calls!
2563 return true;
2564}
2565
Michael Gottesman97e3df02013-01-14 00:35:14 +00002566/// Identify pairings between the retains and releases, and delete and/or move
2567/// them.
John McCalld935e9c2011-06-15 23:37:01 +00002568bool
2569ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
2570 &BBStates,
2571 MapVector<Value *, RRInfo> &Retains,
Dan Gohman6320f522011-07-22 22:29:21 +00002572 DenseMap<Value *, RRInfo> &Releases,
2573 Module *M) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002574 DEBUG(dbgs() << "\n== ObjCARCOpt::PerformCodePlacement ==\n");
2575
John McCalld935e9c2011-06-15 23:37:01 +00002576 bool AnyPairsCompletelyEliminated = false;
2577 RRInfo RetainsToMove;
2578 RRInfo ReleasesToMove;
2579 SmallVector<Instruction *, 4> NewRetains;
2580 SmallVector<Instruction *, 4> NewReleases;
2581 SmallVector<Instruction *, 8> DeadInsts;
2582
Dan Gohman670f9372012-04-13 18:57:48 +00002583 // Visit each retain.
John McCalld935e9c2011-06-15 23:37:01 +00002584 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
Dan Gohman2053a5d2011-09-29 22:25:23 +00002585 E = Retains.end(); I != E; ++I) {
2586 Value *V = I->first;
John McCalld935e9c2011-06-15 23:37:01 +00002587 if (!V) continue; // blotted
2588
2589 Instruction *Retain = cast<Instruction>(V);
Michael Gottesmanc189a392013-01-09 19:23:24 +00002590
Michael Gottesman89279f82013-04-05 18:10:41 +00002591 DEBUG(dbgs() << "Visiting: " << *Retain << "\n");
Michael Gottesmanc189a392013-01-09 19:23:24 +00002592
John McCalld935e9c2011-06-15 23:37:01 +00002593 Value *Arg = GetObjCArg(Retain);
2594
Dan Gohman728db492012-01-13 00:39:07 +00002595 // If the object being released is in static or stack storage, we know it's
John McCalld935e9c2011-06-15 23:37:01 +00002596 // not being managed by ObjC reference counting, so we can delete pairs
2597 // regardless of what possible decrements or uses lie between them.
Dan Gohman728db492012-01-13 00:39:07 +00002598 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
Dan Gohman41375a32012-05-08 23:39:44 +00002599
Dan Gohman56e1cef2011-08-22 17:29:11 +00002600 // A constant pointer can't be pointing to an object on the heap. It may
2601 // be reference-counted, but it won't be deleted.
2602 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
2603 if (const GlobalVariable *GV =
2604 dyn_cast<GlobalVariable>(
2605 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
2606 if (GV->isConstant())
2607 KnownSafe = true;
2608
John McCalld935e9c2011-06-15 23:37:01 +00002609 // Connect the dots between the top-down-collected RetainsToMove and
2610 // bottom-up-collected ReleasesToMove to form sets of related calls.
John McCalld935e9c2011-06-15 23:37:01 +00002611 NewRetains.push_back(Retain);
Michael Gottesman9de6f962013-01-22 21:49:00 +00002612 bool PerformMoveCalls =
2613 ConnectTDBUTraversals(BBStates, Retains, Releases, M, NewRetains,
2614 NewReleases, DeadInsts, RetainsToMove,
2615 ReleasesToMove, Arg, KnownSafe,
2616 AnyPairsCompletelyEliminated);
John McCalld935e9c2011-06-15 23:37:01 +00002617
Michael Gottesman9de6f962013-01-22 21:49:00 +00002618 if (PerformMoveCalls) {
2619 // Ok, everything checks out and we're all set. Let's move/delete some
2620 // code!
2621 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
2622 Retains, Releases, DeadInsts, M);
John McCalld935e9c2011-06-15 23:37:01 +00002623 }
2624
Michael Gottesman9de6f962013-01-22 21:49:00 +00002625 // Clean up state for next retain.
John McCalld935e9c2011-06-15 23:37:01 +00002626 NewReleases.clear();
2627 NewRetains.clear();
2628 RetainsToMove.clear();
2629 ReleasesToMove.clear();
2630 }
2631
2632 // Now that we're done moving everything, we can delete the newly dead
2633 // instructions, as we no longer need them as insert points.
2634 while (!DeadInsts.empty())
2635 EraseInstruction(DeadInsts.pop_back_val());
2636
2637 return AnyPairsCompletelyEliminated;
2638}
2639
Michael Gottesman97e3df02013-01-14 00:35:14 +00002640/// Weak pointer optimizations.
John McCalld935e9c2011-06-15 23:37:01 +00002641void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002642 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeWeakCalls ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00002643
John McCalld935e9c2011-06-15 23:37:01 +00002644 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
2645 // itself because it uses AliasAnalysis and we need to do provenance
2646 // queries instead.
2647 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2648 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +00002649
Michael Gottesman89279f82013-04-05 18:10:41 +00002650 DEBUG(dbgs() << "Visiting: " << *Inst << "\n");
Michael Gottesman3f146e22013-01-01 16:05:48 +00002651
John McCalld935e9c2011-06-15 23:37:01 +00002652 InstructionClass Class = GetBasicInstructionClass(Inst);
2653 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
2654 continue;
2655
2656 // Delete objc_loadWeak calls with no users.
2657 if (Class == IC_LoadWeak && Inst->use_empty()) {
2658 Inst->eraseFromParent();
2659 continue;
2660 }
2661
2662 // TODO: For now, just look for an earlier available version of this value
2663 // within the same block. Theoretically, we could do memdep-style non-local
2664 // analysis too, but that would want caching. A better approach would be to
2665 // use the technique that EarlyCSE uses.
2666 inst_iterator Current = llvm::prior(I);
2667 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
2668 for (BasicBlock::iterator B = CurrentBB->begin(),
2669 J = Current.getInstructionIterator();
2670 J != B; --J) {
2671 Instruction *EarlierInst = &*llvm::prior(J);
2672 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
2673 switch (EarlierClass) {
2674 case IC_LoadWeak:
2675 case IC_LoadWeakRetained: {
2676 // If this is loading from the same pointer, replace this load's value
2677 // with that one.
2678 CallInst *Call = cast<CallInst>(Inst);
2679 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2680 Value *Arg = Call->getArgOperand(0);
2681 Value *EarlierArg = EarlierCall->getArgOperand(0);
2682 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2683 case AliasAnalysis::MustAlias:
2684 Changed = true;
2685 // If the load has a builtin retain, insert a plain retain for it.
2686 if (Class == IC_LoadWeakRetained) {
2687 CallInst *CI =
2688 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
2689 "", Call);
2690 CI->setTailCall();
2691 }
2692 // Zap the fully redundant load.
2693 Call->replaceAllUsesWith(EarlierCall);
2694 Call->eraseFromParent();
2695 goto clobbered;
2696 case AliasAnalysis::MayAlias:
2697 case AliasAnalysis::PartialAlias:
2698 goto clobbered;
2699 case AliasAnalysis::NoAlias:
2700 break;
2701 }
2702 break;
2703 }
2704 case IC_StoreWeak:
2705 case IC_InitWeak: {
2706 // If this is storing to the same pointer and has the same size etc.
2707 // replace this load's value with the stored value.
2708 CallInst *Call = cast<CallInst>(Inst);
2709 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2710 Value *Arg = Call->getArgOperand(0);
2711 Value *EarlierArg = EarlierCall->getArgOperand(0);
2712 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2713 case AliasAnalysis::MustAlias:
2714 Changed = true;
2715 // If the load has a builtin retain, insert a plain retain for it.
2716 if (Class == IC_LoadWeakRetained) {
2717 CallInst *CI =
2718 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
2719 "", Call);
2720 CI->setTailCall();
2721 }
2722 // Zap the fully redundant load.
2723 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
2724 Call->eraseFromParent();
2725 goto clobbered;
2726 case AliasAnalysis::MayAlias:
2727 case AliasAnalysis::PartialAlias:
2728 goto clobbered;
2729 case AliasAnalysis::NoAlias:
2730 break;
2731 }
2732 break;
2733 }
2734 case IC_MoveWeak:
2735 case IC_CopyWeak:
2736 // TOOD: Grab the copied value.
2737 goto clobbered;
2738 case IC_AutoreleasepoolPush:
2739 case IC_None:
John McCall20182ac2013-03-22 21:38:36 +00002740 case IC_IntrinsicUser:
John McCalld935e9c2011-06-15 23:37:01 +00002741 case IC_User:
2742 // Weak pointers are only modified through the weak entry points
2743 // (and arbitrary calls, which could call the weak entry points).
2744 break;
2745 default:
2746 // Anything else could modify the weak pointer.
2747 goto clobbered;
2748 }
2749 }
2750 clobbered:;
2751 }
2752
2753 // Then, for each destroyWeak with an alloca operand, check to see if
2754 // the alloca and all its users can be zapped.
2755 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2756 Instruction *Inst = &*I++;
2757 InstructionClass Class = GetBasicInstructionClass(Inst);
2758 if (Class != IC_DestroyWeak)
2759 continue;
2760
2761 CallInst *Call = cast<CallInst>(Inst);
2762 Value *Arg = Call->getArgOperand(0);
2763 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
2764 for (Value::use_iterator UI = Alloca->use_begin(),
2765 UE = Alloca->use_end(); UI != UE; ++UI) {
Dan Gohmandae33492012-04-27 18:56:31 +00002766 const Instruction *UserInst = cast<Instruction>(*UI);
John McCalld935e9c2011-06-15 23:37:01 +00002767 switch (GetBasicInstructionClass(UserInst)) {
2768 case IC_InitWeak:
2769 case IC_StoreWeak:
2770 case IC_DestroyWeak:
2771 continue;
2772 default:
2773 goto done;
2774 }
2775 }
2776 Changed = true;
2777 for (Value::use_iterator UI = Alloca->use_begin(),
2778 UE = Alloca->use_end(); UI != UE; ) {
2779 CallInst *UserInst = cast<CallInst>(*UI++);
Dan Gohman14862c32012-05-18 22:17:29 +00002780 switch (GetBasicInstructionClass(UserInst)) {
2781 case IC_InitWeak:
2782 case IC_StoreWeak:
2783 // These functions return their second argument.
2784 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
2785 break;
2786 case IC_DestroyWeak:
2787 // No return value.
2788 break;
2789 default:
Dan Gohman9c97eea02012-05-21 17:41:28 +00002790 llvm_unreachable("alloca really is used!");
Dan Gohman14862c32012-05-18 22:17:29 +00002791 }
John McCalld935e9c2011-06-15 23:37:01 +00002792 UserInst->eraseFromParent();
2793 }
2794 Alloca->eraseFromParent();
2795 done:;
2796 }
2797 }
2798}
2799
Michael Gottesman97e3df02013-01-14 00:35:14 +00002800/// Identify program paths which execute sequences of retains and releases which
2801/// can be eliminated.
John McCalld935e9c2011-06-15 23:37:01 +00002802bool ObjCARCOpt::OptimizeSequences(Function &F) {
2803 /// Releases, Retains - These are used to store the results of the main flow
2804 /// analysis. These use Value* as the key instead of Instruction* so that the
2805 /// map stays valid when we get around to rewriting code and calls get
2806 /// replaced by arguments.
2807 DenseMap<Value *, RRInfo> Releases;
2808 MapVector<Value *, RRInfo> Retains;
2809
Michael Gottesman97e3df02013-01-14 00:35:14 +00002810 /// This is used during the traversal of the function to track the
John McCalld935e9c2011-06-15 23:37:01 +00002811 /// states for each identified object at each block.
2812 DenseMap<const BasicBlock *, BBState> BBStates;
2813
2814 // Analyze the CFG of the function, and all instructions.
2815 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
2816
2817 // Transform.
Dan Gohman6320f522011-07-22 22:29:21 +00002818 return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) &&
2819 NestingDetected;
John McCalld935e9c2011-06-15 23:37:01 +00002820}
2821
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002822/// Check if there is a dependent call earlier that does not have anything in
2823/// between the Retain and the call that can affect the reference count of their
2824/// shared pointer argument. Note that Retain need not be in BB.
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002825static bool
2826HasSafePathToPredecessorCall(const Value *Arg, Instruction *Retain,
2827 SmallPtrSet<Instruction *, 4> &DepInsts,
2828 SmallPtrSet<const BasicBlock *, 4> &Visited,
2829 ProvenanceAnalysis &PA) {
2830 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
2831 DepInsts, Visited, PA);
2832 if (DepInsts.size() != 1)
2833 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002834
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002835 CallInst *Call =
2836 dyn_cast_or_null<CallInst>(*DepInsts.begin());
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002837
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002838 // Check that the pointer is the return value of the call.
2839 if (!Call || Arg != Call)
2840 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002841
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002842 // Check that the call is a regular call.
2843 InstructionClass Class = GetBasicInstructionClass(Call);
2844 if (Class != IC_CallOrUser && Class != IC_Call)
2845 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002846
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002847 return true;
2848}
2849
Michael Gottesman6908db12013-04-03 23:16:05 +00002850/// Find a dependent retain that precedes the given autorelease for which there
2851/// is nothing in between the two instructions that can affect the ref count of
2852/// Arg.
2853static CallInst *
2854FindPredecessorRetainWithSafePath(const Value *Arg, BasicBlock *BB,
2855 Instruction *Autorelease,
2856 SmallPtrSet<Instruction *, 4> &DepInsts,
2857 SmallPtrSet<const BasicBlock *, 4> &Visited,
2858 ProvenanceAnalysis &PA) {
2859 FindDependencies(CanChangeRetainCount, Arg,
2860 BB, Autorelease, DepInsts, Visited, PA);
2861 if (DepInsts.size() != 1)
2862 return 0;
Michael Gottesman79249972013-04-05 23:46:45 +00002863
Michael Gottesman6908db12013-04-03 23:16:05 +00002864 CallInst *Retain =
2865 dyn_cast_or_null<CallInst>(*DepInsts.begin());
Michael Gottesman79249972013-04-05 23:46:45 +00002866
Michael Gottesman6908db12013-04-03 23:16:05 +00002867 // Check that we found a retain with the same argument.
2868 if (!Retain ||
2869 !IsRetain(GetBasicInstructionClass(Retain)) ||
2870 GetObjCArg(Retain) != Arg) {
2871 return 0;
2872 }
Michael Gottesman79249972013-04-05 23:46:45 +00002873
Michael Gottesman6908db12013-04-03 23:16:05 +00002874 return Retain;
2875}
2876
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002877/// Look for an ``autorelease'' instruction dependent on Arg such that there are
2878/// no instructions dependent on Arg that need a positive ref count in between
2879/// the autorelease and the ret.
2880static CallInst *
2881FindPredecessorAutoreleaseWithSafePath(const Value *Arg, BasicBlock *BB,
2882 ReturnInst *Ret,
2883 SmallPtrSet<Instruction *, 4> &DepInsts,
2884 SmallPtrSet<const BasicBlock *, 4> &V,
2885 ProvenanceAnalysis &PA) {
2886 FindDependencies(NeedsPositiveRetainCount, Arg,
2887 BB, Ret, DepInsts, V, PA);
2888 if (DepInsts.size() != 1)
2889 return 0;
Michael Gottesman79249972013-04-05 23:46:45 +00002890
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002891 CallInst *Autorelease =
2892 dyn_cast_or_null<CallInst>(*DepInsts.begin());
2893 if (!Autorelease)
2894 return 0;
2895 InstructionClass AutoreleaseClass = GetBasicInstructionClass(Autorelease);
2896 if (!IsAutorelease(AutoreleaseClass))
2897 return 0;
2898 if (GetObjCArg(Autorelease) != Arg)
2899 return 0;
Michael Gottesman79249972013-04-05 23:46:45 +00002900
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002901 return Autorelease;
2902}
2903
Michael Gottesman97e3df02013-01-14 00:35:14 +00002904/// Look for this pattern:
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00002905/// \code
John McCalld935e9c2011-06-15 23:37:01 +00002906/// %call = call i8* @something(...)
2907/// %2 = call i8* @objc_retain(i8* %call)
2908/// %3 = call i8* @objc_autorelease(i8* %2)
2909/// ret i8* %3
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00002910/// \endcode
John McCalld935e9c2011-06-15 23:37:01 +00002911/// And delete the retain and autorelease.
John McCalld935e9c2011-06-15 23:37:01 +00002912void ObjCARCOpt::OptimizeReturns(Function &F) {
2913 if (!F.getReturnType()->isPointerTy())
2914 return;
Michael Gottesman79249972013-04-05 23:46:45 +00002915
Michael Gottesman89279f82013-04-05 18:10:41 +00002916 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeReturns ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00002917
John McCalld935e9c2011-06-15 23:37:01 +00002918 SmallPtrSet<Instruction *, 4> DependingInstructions;
2919 SmallPtrSet<const BasicBlock *, 4> Visited;
2920 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
2921 BasicBlock *BB = FI;
2922 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
Michael Gottesman3f146e22013-01-01 16:05:48 +00002923
Michael Gottesman89279f82013-04-05 18:10:41 +00002924 DEBUG(dbgs() << "Visiting: " << *Ret << "\n");
Michael Gottesman3f146e22013-01-01 16:05:48 +00002925
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002926 if (!Ret)
2927 continue;
Michael Gottesman79249972013-04-05 23:46:45 +00002928
John McCalld935e9c2011-06-15 23:37:01 +00002929 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
Michael Gottesman79249972013-04-05 23:46:45 +00002930
Michael Gottesmancdb7c152013-04-21 00:25:04 +00002931 // Look for an ``autorelease'' instruction that is a predecessor of Ret and
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002932 // dependent on Arg such that there are no instructions dependent on Arg
2933 // that need a positive ref count in between the autorelease and Ret.
2934 CallInst *Autorelease =
2935 FindPredecessorAutoreleaseWithSafePath(Arg, BB, Ret,
2936 DependingInstructions, Visited,
2937 PA);
John McCalld935e9c2011-06-15 23:37:01 +00002938 DependingInstructions.clear();
2939 Visited.clear();
Michael Gottesmanfb9ece92013-04-21 00:25:01 +00002940
2941 if (!Autorelease)
2942 continue;
2943
2944 CallInst *Retain =
2945 FindPredecessorRetainWithSafePath(Arg, BB, Autorelease,
2946 DependingInstructions, Visited, PA);
2947 DependingInstructions.clear();
2948 Visited.clear();
2949
2950 if (!Retain)
2951 continue;
2952
2953 // Check that there is nothing that can affect the reference count
2954 // between the retain and the call. Note that Retain need not be in BB.
2955 bool HasSafePathToCall = HasSafePathToPredecessorCall(Arg, Retain,
2956 DependingInstructions,
2957 Visited, PA);
2958 DependingInstructions.clear();
2959 Visited.clear();
2960
2961 if (!HasSafePathToCall)
2962 continue;
2963
2964 // If so, we can zap the retain and autorelease.
2965 Changed = true;
2966 ++NumRets;
2967 DEBUG(dbgs() << "Erasing: " << *Retain << "\nErasing: "
2968 << *Autorelease << "\n");
2969 EraseInstruction(Retain);
2970 EraseInstruction(Autorelease);
John McCalld935e9c2011-06-15 23:37:01 +00002971 }
2972}
2973
Michael Gottesman9c118152013-04-29 06:16:57 +00002974#ifndef NDEBUG
2975void
2976ObjCARCOpt::GatherStatistics(Function &F, bool AfterOptimization) {
2977 llvm::Statistic &NumRetains =
2978 AfterOptimization? NumRetainsAfterOpt : NumRetainsBeforeOpt;
2979 llvm::Statistic &NumReleases =
2980 AfterOptimization? NumReleasesAfterOpt : NumReleasesBeforeOpt;
2981
2982 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2983 Instruction *Inst = &*I++;
2984 switch (GetBasicInstructionClass(Inst)) {
2985 default:
2986 break;
2987 case IC_Retain:
2988 ++NumRetains;
2989 break;
2990 case IC_Release:
2991 ++NumReleases;
2992 break;
2993 }
2994 }
2995}
2996#endif
2997
John McCalld935e9c2011-06-15 23:37:01 +00002998bool ObjCARCOpt::doInitialization(Module &M) {
2999 if (!EnableARCOpts)
3000 return false;
3001
Dan Gohman670f9372012-04-13 18:57:48 +00003002 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanceaac7c2011-06-20 23:20:43 +00003003 Run = ModuleHasARC(M);
3004 if (!Run)
3005 return false;
3006
John McCalld935e9c2011-06-15 23:37:01 +00003007 // Identify the imprecise release metadata kind.
3008 ImpreciseReleaseMDKind =
3009 M.getContext().getMDKindID("clang.imprecise_release");
Dan Gohmana7107f92011-10-17 22:53:25 +00003010 CopyOnEscapeMDKind =
3011 M.getContext().getMDKindID("clang.arc.copy_on_escape");
Dan Gohman0155f302012-02-17 18:59:53 +00003012 NoObjCARCExceptionsMDKind =
3013 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
Michael Gottesman81b1d432013-03-26 00:42:04 +00003014#ifdef ARC_ANNOTATIONS
3015 ARCAnnotationBottomUpMDKind =
3016 M.getContext().getMDKindID("llvm.arc.annotation.bottomup");
3017 ARCAnnotationTopDownMDKind =
3018 M.getContext().getMDKindID("llvm.arc.annotation.topdown");
3019 ARCAnnotationProvenanceSourceMDKind =
3020 M.getContext().getMDKindID("llvm.arc.annotation.provenancesource");
3021#endif // ARC_ANNOTATIONS
John McCalld935e9c2011-06-15 23:37:01 +00003022
John McCalld935e9c2011-06-15 23:37:01 +00003023 // Intuitively, objc_retain and others are nocapture, however in practice
3024 // they are not, because they return their argument value. And objc_release
Dan Gohmandae33492012-04-27 18:56:31 +00003025 // calls finalizers which can have arbitrary side effects.
John McCalld935e9c2011-06-15 23:37:01 +00003026
3027 // These are initialized lazily.
John McCalld935e9c2011-06-15 23:37:01 +00003028 AutoreleaseRVCallee = 0;
3029 ReleaseCallee = 0;
3030 RetainCallee = 0;
Dan Gohman6320f522011-07-22 22:29:21 +00003031 RetainBlockCallee = 0;
John McCalld935e9c2011-06-15 23:37:01 +00003032 AutoreleaseCallee = 0;
3033
3034 return false;
3035}
3036
3037bool ObjCARCOpt::runOnFunction(Function &F) {
3038 if (!EnableARCOpts)
3039 return false;
3040
Dan Gohmanceaac7c2011-06-20 23:20:43 +00003041 // If nothing in the Module uses ARC, don't do anything.
3042 if (!Run)
3043 return false;
3044
John McCalld935e9c2011-06-15 23:37:01 +00003045 Changed = false;
3046
Michael Gottesman89279f82013-04-05 18:10:41 +00003047 DEBUG(dbgs() << "<<< ObjCARCOpt: Visiting Function: " << F.getName() << " >>>"
3048 "\n");
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00003049
John McCalld935e9c2011-06-15 23:37:01 +00003050 PA.setAA(&getAnalysis<AliasAnalysis>());
3051
Michael Gottesman9fc50b82013-05-13 18:29:07 +00003052#ifndef NDEBUG
3053 if (AreStatisticsEnabled()) {
3054 GatherStatistics(F, false);
3055 }
3056#endif
3057
John McCalld935e9c2011-06-15 23:37:01 +00003058 // This pass performs several distinct transformations. As a compile-time aid
3059 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3060 // library functions aren't declared.
3061
Michael Gottesmancd5b0272013-04-24 22:18:15 +00003062 // Preliminary optimizations. This also computes UsedInThisFunction.
John McCalld935e9c2011-06-15 23:37:01 +00003063 OptimizeIndividualCalls(F);
3064
3065 // Optimizations for weak pointers.
3066 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3067 (1 << IC_LoadWeakRetained) |
3068 (1 << IC_StoreWeak) |
3069 (1 << IC_InitWeak) |
3070 (1 << IC_CopyWeak) |
3071 (1 << IC_MoveWeak) |
3072 (1 << IC_DestroyWeak)))
3073 OptimizeWeakCalls(F);
3074
3075 // Optimizations for retain+release pairs.
3076 if (UsedInThisFunction & ((1 << IC_Retain) |
3077 (1 << IC_RetainRV) |
3078 (1 << IC_RetainBlock)))
3079 if (UsedInThisFunction & (1 << IC_Release))
3080 // Run OptimizeSequences until it either stops making changes or
3081 // no retain+release pair nesting is detected.
3082 while (OptimizeSequences(F)) {}
3083
3084 // Optimizations if objc_autorelease is used.
Dan Gohman41375a32012-05-08 23:39:44 +00003085 if (UsedInThisFunction & ((1 << IC_Autorelease) |
3086 (1 << IC_AutoreleaseRV)))
John McCalld935e9c2011-06-15 23:37:01 +00003087 OptimizeReturns(F);
3088
Michael Gottesman9c118152013-04-29 06:16:57 +00003089 // Gather statistics after optimization.
3090#ifndef NDEBUG
3091 if (AreStatisticsEnabled()) {
3092 GatherStatistics(F, true);
3093 }
3094#endif
3095
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00003096 DEBUG(dbgs() << "\n");
3097
John McCalld935e9c2011-06-15 23:37:01 +00003098 return Changed;
3099}
3100
3101void ObjCARCOpt::releaseMemory() {
3102 PA.clear();
3103}
3104
Michael Gottesman97e3df02013-01-14 00:35:14 +00003105/// @}
3106///