blob: acc32d5eb31b79ea26d25587d2ce70fbeee8247f [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");
306
307namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000308 /// \enum Sequence
309 ///
310 /// \brief A sequence of states that a pointer may go through in which an
311 /// objc_retain and objc_release are actually needed.
John McCalld935e9c2011-06-15 23:37:01 +0000312 enum Sequence {
313 S_None,
Michael Gottesman53fd20b2013-01-29 21:07:51 +0000314 S_Retain, ///< objc_retain(x).
315 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement.
316 S_Use, ///< any use of x.
Michael Gottesman386241c2013-01-29 21:39:02 +0000317 S_Stop, ///< like S_Release, but code motion is stopped.
Michael Gottesman53fd20b2013-01-29 21:07:51 +0000318 S_Release, ///< objc_release(x).
Michael Gottesman9bdab2b2013-01-29 21:41:44 +0000319 S_MovableRelease ///< objc_release(x), !clang.imprecise_release.
John McCalld935e9c2011-06-15 23:37:01 +0000320 };
Michael Gottesman53fd20b2013-01-29 21:07:51 +0000321
322 raw_ostream &operator<<(raw_ostream &OS, const Sequence S)
323 LLVM_ATTRIBUTE_UNUSED;
324 raw_ostream &operator<<(raw_ostream &OS, const Sequence S) {
325 switch (S) {
326 case S_None:
327 return OS << "S_None";
328 case S_Retain:
329 return OS << "S_Retain";
330 case S_CanRelease:
331 return OS << "S_CanRelease";
332 case S_Use:
333 return OS << "S_Use";
334 case S_Release:
335 return OS << "S_Release";
336 case S_MovableRelease:
337 return OS << "S_MovableRelease";
338 case S_Stop:
339 return OS << "S_Stop";
340 }
341 llvm_unreachable("Unknown sequence type.");
342 }
John McCalld935e9c2011-06-15 23:37:01 +0000343}
344
345static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
346 // The easy cases.
347 if (A == B)
348 return A;
349 if (A == S_None || B == S_None)
350 return S_None;
351
John McCalld935e9c2011-06-15 23:37:01 +0000352 if (A > B) std::swap(A, B);
353 if (TopDown) {
354 // Choose the side which is further along in the sequence.
Dan Gohman12130272011-08-12 00:26:31 +0000355 if ((A == S_Retain || A == S_CanRelease) &&
356 (B == S_CanRelease || B == S_Use))
John McCalld935e9c2011-06-15 23:37:01 +0000357 return B;
358 } else {
359 // Choose the side which is further along in the sequence.
360 if ((A == S_Use || A == S_CanRelease) &&
Dan Gohman12130272011-08-12 00:26:31 +0000361 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
John McCalld935e9c2011-06-15 23:37:01 +0000362 return A;
363 // If both sides are releases, choose the more conservative one.
364 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
365 return A;
366 if (A == S_Release && B == S_MovableRelease)
367 return A;
368 }
369
370 return S_None;
371}
372
373namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000374 /// \brief Unidirectional information about either a
John McCalld935e9c2011-06-15 23:37:01 +0000375 /// retain-decrement-use-release sequence or release-use-decrement-retain
376 /// reverese sequence.
377 struct RRInfo {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000378 /// After an objc_retain, the reference count of the referenced
Dan Gohmanb3894012011-08-19 00:26:36 +0000379 /// object is known to be positive. Similarly, before an objc_release, the
380 /// reference count of the referenced object is known to be positive. If
381 /// there are retain-release pairs in code regions where the retain count
382 /// is known to be positive, they can be eliminated, regardless of any side
383 /// effects between them.
384 ///
385 /// Also, a retain+release pair nested within another retain+release
386 /// pair all on the known same pointer value can be eliminated, regardless
387 /// of any intervening side effects.
388 ///
389 /// KnownSafe is true when either of these conditions is satisfied.
390 bool KnownSafe;
John McCalld935e9c2011-06-15 23:37:01 +0000391
Michael Gottesman97e3df02013-01-14 00:35:14 +0000392 /// True of the objc_release calls are all marked with the "tail" keyword.
John McCalld935e9c2011-06-15 23:37:01 +0000393 bool IsTailCallRelease;
394
Michael Gottesman97e3df02013-01-14 00:35:14 +0000395 /// If the Calls are objc_release calls and they all have a
396 /// clang.imprecise_release tag, this is the metadata tag.
John McCalld935e9c2011-06-15 23:37:01 +0000397 MDNode *ReleaseMetadata;
398
Michael Gottesman97e3df02013-01-14 00:35:14 +0000399 /// For a top-down sequence, the set of objc_retains or
John McCalld935e9c2011-06-15 23:37:01 +0000400 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
401 SmallPtrSet<Instruction *, 2> Calls;
402
Michael Gottesman97e3df02013-01-14 00:35:14 +0000403 /// The set of optimal insert positions for moving calls in the opposite
404 /// sequence.
John McCalld935e9c2011-06-15 23:37:01 +0000405 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
406
407 RRInfo() :
Michael Gottesmanba648592013-03-28 23:08:44 +0000408 KnownSafe(false), IsTailCallRelease(false), ReleaseMetadata(0) {}
John McCalld935e9c2011-06-15 23:37:01 +0000409
410 void clear();
Michael Gottesman1d8d2572013-04-05 22:54:28 +0000411
412 bool IsTrackingImpreciseReleases() {
413 return ReleaseMetadata != 0;
414 }
John McCalld935e9c2011-06-15 23:37:01 +0000415 };
416}
417
418void RRInfo::clear() {
Dan Gohmanb3894012011-08-19 00:26:36 +0000419 KnownSafe = false;
John McCalld935e9c2011-06-15 23:37:01 +0000420 IsTailCallRelease = false;
421 ReleaseMetadata = 0;
422 Calls.clear();
423 ReverseInsertPts.clear();
424}
425
426namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000427 /// \brief This class summarizes several per-pointer runtime properties which
428 /// are propogated through the flow graph.
John McCalld935e9c2011-06-15 23:37:01 +0000429 class PtrState {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000430 /// True if the reference count is known to be incremented.
Dan Gohman62079b42012-04-25 00:50:46 +0000431 bool KnownPositiveRefCount;
432
Michael Gottesman97e3df02013-01-14 00:35:14 +0000433 /// True of we've seen an opportunity for partial RR elimination, such as
434 /// pushing calls into a CFG triangle or into one side of a CFG diamond.
Dan Gohman62079b42012-04-25 00:50:46 +0000435 bool Partial;
John McCalld935e9c2011-06-15 23:37:01 +0000436
Michael Gottesman97e3df02013-01-14 00:35:14 +0000437 /// The current position in the sequence.
Dan Gohman41375a32012-05-08 23:39:44 +0000438 Sequence Seq : 8;
John McCalld935e9c2011-06-15 23:37:01 +0000439
440 public:
Michael Gottesman97e3df02013-01-14 00:35:14 +0000441 /// Unidirectional information about the current sequence.
442 ///
John McCalld935e9c2011-06-15 23:37:01 +0000443 /// TODO: Encapsulate this better.
444 RRInfo RRI;
445
Dan Gohmandf476e52012-09-04 23:16:20 +0000446 PtrState() : KnownPositiveRefCount(false), Partial(false),
Dan Gohman41375a32012-05-08 23:39:44 +0000447 Seq(S_None) {}
John McCalld935e9c2011-06-15 23:37:01 +0000448
Michael Gottesman415ddd72013-02-05 19:32:18 +0000449 void SetKnownPositiveRefCount() {
Dan Gohman62079b42012-04-25 00:50:46 +0000450 KnownPositiveRefCount = true;
Dan Gohman12130272011-08-12 00:26:31 +0000451 }
452
Michael Gottesman764b1cf2013-03-23 05:46:19 +0000453 void ClearKnownPositiveRefCount() {
Dan Gohman62079b42012-04-25 00:50:46 +0000454 KnownPositiveRefCount = false;
John McCalld935e9c2011-06-15 23:37:01 +0000455 }
456
Michael Gottesman07beea42013-03-23 05:31:01 +0000457 bool HasKnownPositiveRefCount() const {
Dan Gohman62079b42012-04-25 00:50:46 +0000458 return KnownPositiveRefCount;
John McCalld935e9c2011-06-15 23:37:01 +0000459 }
460
Michael Gottesman415ddd72013-02-05 19:32:18 +0000461 void SetSeq(Sequence NewSeq) {
Michael Gottesman89279f82013-04-05 18:10:41 +0000462 DEBUG(dbgs() << "Old: " << Seq << "; New: " << NewSeq << "\n");
463 Seq = NewSeq;
John McCalld935e9c2011-06-15 23:37:01 +0000464 }
465
Michael Gottesman415ddd72013-02-05 19:32:18 +0000466 Sequence GetSeq() const {
John McCalld935e9c2011-06-15 23:37:01 +0000467 return Seq;
468 }
469
Michael Gottesman415ddd72013-02-05 19:32:18 +0000470 void ClearSequenceProgress() {
Dan Gohman62079b42012-04-25 00:50:46 +0000471 ResetSequenceProgress(S_None);
472 }
473
Michael Gottesman415ddd72013-02-05 19:32:18 +0000474 void ResetSequenceProgress(Sequence NewSeq) {
Michael Gottesman89279f82013-04-05 18:10:41 +0000475 SetSeq(NewSeq);
Dan Gohman62079b42012-04-25 00:50:46 +0000476 Partial = false;
John McCalld935e9c2011-06-15 23:37:01 +0000477 RRI.clear();
478 }
479
480 void Merge(const PtrState &Other, bool TopDown);
481 };
482}
483
484void
485PtrState::Merge(const PtrState &Other, bool TopDown) {
486 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
Dan Gohman62079b42012-04-25 00:50:46 +0000487 KnownPositiveRefCount = KnownPositiveRefCount && Other.KnownPositiveRefCount;
Michael Gottesman60f6b282013-03-29 05:13:07 +0000488
Dan Gohman1736c142011-10-17 18:48:25 +0000489 // If we're not in a sequence (anymore), drop all associated state.
John McCalld935e9c2011-06-15 23:37:01 +0000490 if (Seq == S_None) {
Dan Gohman62079b42012-04-25 00:50:46 +0000491 Partial = false;
John McCalld935e9c2011-06-15 23:37:01 +0000492 RRI.clear();
Dan Gohman62079b42012-04-25 00:50:46 +0000493 } else if (Partial || Other.Partial) {
Dan Gohman1736c142011-10-17 18:48:25 +0000494 // If we're doing a merge on a path that's previously seen a partial
495 // merge, conservatively drop the sequence, to avoid doing partial
496 // RR elimination. If the branch predicates for the two merge differ,
497 // mixing them is unsafe.
Dan Gohman62079b42012-04-25 00:50:46 +0000498 ClearSequenceProgress();
John McCalld935e9c2011-06-15 23:37:01 +0000499 } else {
500 // Conservatively merge the ReleaseMetadata information.
501 if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
502 RRI.ReleaseMetadata = 0;
503
Dan Gohmanb3894012011-08-19 00:26:36 +0000504 RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
Dan Gohman41375a32012-05-08 23:39:44 +0000505 RRI.IsTailCallRelease = RRI.IsTailCallRelease &&
506 Other.RRI.IsTailCallRelease;
John McCalld935e9c2011-06-15 23:37:01 +0000507 RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
Dan Gohman1736c142011-10-17 18:48:25 +0000508
509 // Merge the insert point sets. If there are any differences,
510 // that makes this a partial merge.
Dan Gohman41375a32012-05-08 23:39:44 +0000511 Partial = RRI.ReverseInsertPts.size() != Other.RRI.ReverseInsertPts.size();
Dan Gohman1736c142011-10-17 18:48:25 +0000512 for (SmallPtrSet<Instruction *, 2>::const_iterator
513 I = Other.RRI.ReverseInsertPts.begin(),
514 E = Other.RRI.ReverseInsertPts.end(); I != E; ++I)
Dan Gohman62079b42012-04-25 00:50:46 +0000515 Partial |= RRI.ReverseInsertPts.insert(*I);
John McCalld935e9c2011-06-15 23:37:01 +0000516 }
517}
518
519namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000520 /// \brief Per-BasicBlock state.
John McCalld935e9c2011-06-15 23:37:01 +0000521 class BBState {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000522 /// The number of unique control paths from the entry which can reach this
523 /// block.
John McCalld935e9c2011-06-15 23:37:01 +0000524 unsigned TopDownPathCount;
525
Michael Gottesman97e3df02013-01-14 00:35:14 +0000526 /// The number of unique control paths to exits from this block.
John McCalld935e9c2011-06-15 23:37:01 +0000527 unsigned BottomUpPathCount;
528
Michael Gottesman97e3df02013-01-14 00:35:14 +0000529 /// A type for PerPtrTopDown and PerPtrBottomUp.
John McCalld935e9c2011-06-15 23:37:01 +0000530 typedef MapVector<const Value *, PtrState> MapTy;
531
Michael Gottesman97e3df02013-01-14 00:35:14 +0000532 /// The top-down traversal uses this to record information known about a
533 /// pointer at the bottom of each block.
John McCalld935e9c2011-06-15 23:37:01 +0000534 MapTy PerPtrTopDown;
535
Michael Gottesman97e3df02013-01-14 00:35:14 +0000536 /// The bottom-up traversal uses this to record information known about a
537 /// pointer at the top of each block.
John McCalld935e9c2011-06-15 23:37:01 +0000538 MapTy PerPtrBottomUp;
539
Michael Gottesman97e3df02013-01-14 00:35:14 +0000540 /// Effective predecessors of the current block ignoring ignorable edges and
541 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000542 SmallVector<BasicBlock *, 2> Preds;
Michael Gottesman97e3df02013-01-14 00:35:14 +0000543 /// Effective successors of the current block ignoring ignorable edges and
544 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000545 SmallVector<BasicBlock *, 2> Succs;
546
John McCalld935e9c2011-06-15 23:37:01 +0000547 public:
548 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
549
550 typedef MapTy::iterator ptr_iterator;
551 typedef MapTy::const_iterator ptr_const_iterator;
552
553 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
554 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
555 ptr_const_iterator top_down_ptr_begin() const {
556 return PerPtrTopDown.begin();
557 }
558 ptr_const_iterator top_down_ptr_end() const {
559 return PerPtrTopDown.end();
560 }
561
562 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
563 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
564 ptr_const_iterator bottom_up_ptr_begin() const {
565 return PerPtrBottomUp.begin();
566 }
567 ptr_const_iterator bottom_up_ptr_end() const {
568 return PerPtrBottomUp.end();
569 }
570
Michael Gottesman97e3df02013-01-14 00:35:14 +0000571 /// Mark this block as being an entry block, which has one path from the
572 /// entry by definition.
John McCalld935e9c2011-06-15 23:37:01 +0000573 void SetAsEntry() { TopDownPathCount = 1; }
574
Michael Gottesman97e3df02013-01-14 00:35:14 +0000575 /// Mark this block as being an exit block, which has one path to an exit by
576 /// definition.
John McCalld935e9c2011-06-15 23:37:01 +0000577 void SetAsExit() { BottomUpPathCount = 1; }
578
579 PtrState &getPtrTopDownState(const Value *Arg) {
580 return PerPtrTopDown[Arg];
581 }
582
583 PtrState &getPtrBottomUpState(const Value *Arg) {
584 return PerPtrBottomUp[Arg];
585 }
586
587 void clearBottomUpPointers() {
Evan Chenge4df6a22011-08-04 18:40:26 +0000588 PerPtrBottomUp.clear();
John McCalld935e9c2011-06-15 23:37:01 +0000589 }
590
591 void clearTopDownPointers() {
592 PerPtrTopDown.clear();
593 }
594
595 void InitFromPred(const BBState &Other);
596 void InitFromSucc(const BBState &Other);
597 void MergePred(const BBState &Other);
598 void MergeSucc(const BBState &Other);
599
Michael Gottesman97e3df02013-01-14 00:35:14 +0000600 /// Return the number of possible unique paths from an entry to an exit
601 /// which pass through this block. This is only valid after both the
602 /// top-down and bottom-up traversals are complete.
John McCalld935e9c2011-06-15 23:37:01 +0000603 unsigned GetAllPathCount() const {
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000604 assert(TopDownPathCount != 0);
605 assert(BottomUpPathCount != 0);
John McCalld935e9c2011-06-15 23:37:01 +0000606 return TopDownPathCount * BottomUpPathCount;
607 }
Dan Gohman12130272011-08-12 00:26:31 +0000608
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000609 // Specialized CFG utilities.
Dan Gohmandae33492012-04-27 18:56:31 +0000610 typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000611 edge_iterator pred_begin() { return Preds.begin(); }
612 edge_iterator pred_end() { return Preds.end(); }
613 edge_iterator succ_begin() { return Succs.begin(); }
614 edge_iterator succ_end() { return Succs.end(); }
615
616 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
617 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
618
619 bool isExit() const { return Succs.empty(); }
John McCalld935e9c2011-06-15 23:37:01 +0000620 };
621}
622
623void BBState::InitFromPred(const BBState &Other) {
624 PerPtrTopDown = Other.PerPtrTopDown;
625 TopDownPathCount = Other.TopDownPathCount;
626}
627
628void BBState::InitFromSucc(const BBState &Other) {
629 PerPtrBottomUp = Other.PerPtrBottomUp;
630 BottomUpPathCount = Other.BottomUpPathCount;
631}
632
Michael Gottesman97e3df02013-01-14 00:35:14 +0000633/// The top-down traversal uses this to merge information about predecessors to
634/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +0000635void BBState::MergePred(const BBState &Other) {
636 // Other.TopDownPathCount can be 0, in which case it is either dead or a
637 // loop backedge. Loop backedges are special.
638 TopDownPathCount += Other.TopDownPathCount;
639
Michael Gottesman4385edf2013-01-14 01:47:53 +0000640 // Check for overflow. If we have overflow, fall back to conservative
641 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +0000642 if (TopDownPathCount < Other.TopDownPathCount) {
643 clearTopDownPointers();
644 return;
645 }
646
John McCalld935e9c2011-06-15 23:37:01 +0000647 // For each entry in the other set, if our set has an entry with the same key,
648 // merge the entries. Otherwise, copy the entry and merge it with an empty
649 // entry.
650 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
651 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
652 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
653 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
654 /*TopDown=*/true);
655 }
656
Dan Gohman7e315fc32011-08-11 21:06:32 +0000657 // For each entry in our set, if the other set doesn't have an entry with the
John McCalld935e9c2011-06-15 23:37:01 +0000658 // same key, force it to merge with an empty entry.
659 for (ptr_iterator MI = top_down_ptr_begin(),
660 ME = top_down_ptr_end(); MI != ME; ++MI)
661 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
662 MI->second.Merge(PtrState(), /*TopDown=*/true);
663}
664
Michael Gottesman97e3df02013-01-14 00:35:14 +0000665/// The bottom-up traversal uses this to merge information about successors to
666/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +0000667void BBState::MergeSucc(const BBState &Other) {
668 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
669 // loop backedge. Loop backedges are special.
670 BottomUpPathCount += Other.BottomUpPathCount;
671
Michael Gottesman4385edf2013-01-14 01:47:53 +0000672 // Check for overflow. If we have overflow, fall back to conservative
673 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +0000674 if (BottomUpPathCount < Other.BottomUpPathCount) {
675 clearBottomUpPointers();
676 return;
677 }
678
John McCalld935e9c2011-06-15 23:37:01 +0000679 // For each entry in the other set, if our set has an entry with the
680 // same key, merge the entries. Otherwise, copy the entry and merge
681 // it with an empty entry.
682 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
683 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
684 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
685 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
686 /*TopDown=*/false);
687 }
688
Dan Gohman7e315fc32011-08-11 21:06:32 +0000689 // For each entry in our set, if the other set doesn't have an entry
John McCalld935e9c2011-06-15 23:37:01 +0000690 // with the same key, force it to merge with an empty entry.
691 for (ptr_iterator MI = bottom_up_ptr_begin(),
692 ME = bottom_up_ptr_end(); MI != ME; ++MI)
693 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
694 MI->second.Merge(PtrState(), /*TopDown=*/false);
695}
696
Michael Gottesman81b1d432013-03-26 00:42:04 +0000697// Only enable ARC Annotations if we are building a debug version of
698// libObjCARCOpts.
699#ifndef NDEBUG
700#define ARC_ANNOTATIONS
701#endif
702
703// Define some macros along the lines of DEBUG and some helper functions to make
704// it cleaner to create annotations in the source code and to no-op when not
705// building in debug mode.
706#ifdef ARC_ANNOTATIONS
707
708#include "llvm/Support/CommandLine.h"
709
710/// Enable/disable ARC sequence annotations.
711static cl::opt<bool>
712EnableARCAnnotations("enable-objc-arc-annotations", cl::init(false));
713
714/// This function appends a unique ARCAnnotationProvenanceSourceMDKind id to an
715/// instruction so that we can track backwards when post processing via the llvm
716/// arc annotation processor tool. If the function is an
717static MDString *AppendMDNodeToSourcePtr(unsigned NodeId,
718 Value *Ptr) {
719 MDString *Hash = 0;
720
721 // If pointer is a result of an instruction and it does not have a source
722 // MDNode it, attach a new MDNode onto it. If pointer is a result of
723 // an instruction and does have a source MDNode attached to it, return a
724 // reference to said Node. Otherwise just return 0.
725 if (Instruction *Inst = dyn_cast<Instruction>(Ptr)) {
726 MDNode *Node;
727 if (!(Node = Inst->getMetadata(NodeId))) {
728 // We do not have any node. Generate and attatch the hash MDString to the
729 // instruction.
730
731 // We just use an MDString to ensure that this metadata gets written out
732 // of line at the module level and to provide a very simple format
733 // encoding the information herein. Both of these makes it simpler to
734 // parse the annotations by a simple external program.
735 std::string Str;
736 raw_string_ostream os(Str);
737 os << "(" << Inst->getParent()->getParent()->getName() << ",%"
738 << Inst->getName() << ")";
739
740 Hash = MDString::get(Inst->getContext(), os.str());
741 Inst->setMetadata(NodeId, MDNode::get(Inst->getContext(),Hash));
742 } else {
743 // We have a node. Grab its hash and return it.
744 assert(Node->getNumOperands() == 1 &&
745 "An ARCAnnotationProvenanceSourceMDKind can only have 1 operand.");
746 Hash = cast<MDString>(Node->getOperand(0));
747 }
748 } else if (Argument *Arg = dyn_cast<Argument>(Ptr)) {
749 std::string str;
750 raw_string_ostream os(str);
751 os << "(" << Arg->getParent()->getName() << ",%" << Arg->getName()
752 << ")";
753 Hash = MDString::get(Arg->getContext(), os.str());
754 }
755
756 return Hash;
757}
758
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000759static std::string SequenceToString(Sequence A) {
760 std::string str;
761 raw_string_ostream os(str);
762 os << A;
763 return os.str();
764}
765
Michael Gottesman81b1d432013-03-26 00:42:04 +0000766/// Helper function to change a Sequence into a String object using our overload
767/// for raw_ostream so we only have printing code in one location.
768static MDString *SequenceToMDString(LLVMContext &Context,
769 Sequence A) {
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000770 return MDString::get(Context, SequenceToString(A));
Michael Gottesman81b1d432013-03-26 00:42:04 +0000771}
772
773/// A simple function to generate a MDNode which describes the change in state
774/// for Value *Ptr caused by Instruction *Inst.
775static void AppendMDNodeToInstForPtr(unsigned NodeId,
776 Instruction *Inst,
777 Value *Ptr,
778 MDString *PtrSourceMDNodeID,
779 Sequence OldSeq,
780 Sequence NewSeq) {
781 MDNode *Node = 0;
782 Value *tmp[3] = {PtrSourceMDNodeID,
783 SequenceToMDString(Inst->getContext(),
784 OldSeq),
785 SequenceToMDString(Inst->getContext(),
786 NewSeq)};
787 Node = MDNode::get(Inst->getContext(),
788 ArrayRef<Value*>(tmp, 3));
789
790 Inst->setMetadata(NodeId, Node);
791}
792
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000793/// Add to the beginning of the basic block llvm.ptr.annotations which show the
794/// state of a pointer at the entrance to a basic block.
795static void GenerateARCBBEntranceAnnotation(const char *Name, BasicBlock *BB,
796 Value *Ptr, Sequence Seq) {
797 Module *M = BB->getParent()->getParent();
798 LLVMContext &C = M->getContext();
799 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
800 Type *I8XX = PointerType::getUnqual(I8X);
801 Type *Params[] = {I8XX, I8XX};
802 FunctionType *FTy = FunctionType::get(Type::getVoidTy(C),
803 ArrayRef<Type*>(Params, 2),
804 /*isVarArg=*/false);
805 Constant *Callee = M->getOrInsertFunction(Name, FTy);
Michael Gottesman60f6b282013-03-29 05:13:07 +0000806
807 IRBuilder<> Builder(BB, BB->getFirstInsertionPt());
808
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000809 Value *PtrName;
810 StringRef Tmp = Ptr->getName();
811 if (0 == (PtrName = M->getGlobalVariable(Tmp, true))) {
812 Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
813 Tmp + "_STR");
814 PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
Michael Gottesman60f6b282013-03-29 05:13:07 +0000815 cast<Constant>(ActualPtrName), Tmp);
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000816 }
817
818 Value *S;
819 std::string SeqStr = SequenceToString(Seq);
820 if (0 == (S = M->getGlobalVariable(SeqStr, true))) {
821 Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
822 SeqStr + "_STR");
823 S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
824 cast<Constant>(ActualPtrName), SeqStr);
825 }
826
827 Builder.CreateCall2(Callee, PtrName, S);
828}
829
830/// Add to the end of the basic block llvm.ptr.annotations which show the state
831/// of the pointer at the bottom of the basic block.
832static void GenerateARCBBTerminatorAnnotation(const char *Name, BasicBlock *BB,
833 Value *Ptr, Sequence Seq) {
834 Module *M = BB->getParent()->getParent();
835 LLVMContext &C = M->getContext();
836 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
837 Type *I8XX = PointerType::getUnqual(I8X);
838 Type *Params[] = {I8XX, I8XX};
839 FunctionType *FTy = FunctionType::get(Type::getVoidTy(C),
840 ArrayRef<Type*>(Params, 2),
841 /*isVarArg=*/false);
842 Constant *Callee = M->getOrInsertFunction(Name, FTy);
Michael Gottesman60f6b282013-03-29 05:13:07 +0000843
844 IRBuilder<> Builder(BB, llvm::prior(BB->end()));
845
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000846 Value *PtrName;
847 StringRef Tmp = Ptr->getName();
848 if (0 == (PtrName = M->getGlobalVariable(Tmp, true))) {
849 Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
850 Tmp + "_STR");
851 PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
Michael Gottesman60f6b282013-03-29 05:13:07 +0000852 cast<Constant>(ActualPtrName), Tmp);
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000853 }
854
855 Value *S;
856 std::string SeqStr = SequenceToString(Seq);
857 if (0 == (S = M->getGlobalVariable(SeqStr, true))) {
858 Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
859 SeqStr + "_STR");
860 S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
861 cast<Constant>(ActualPtrName), SeqStr);
862 }
Michael Gottesman60f6b282013-03-29 05:13:07 +0000863 Builder.CreateCall2(Callee, PtrName, S);
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000864}
865
Michael Gottesman81b1d432013-03-26 00:42:04 +0000866/// Adds a source annotation to pointer and a state change annotation to Inst
867/// referencing the source annotation and the old/new state of pointer.
868static void GenerateARCAnnotation(unsigned InstMDId,
869 unsigned PtrMDId,
870 Instruction *Inst,
871 Value *Ptr,
872 Sequence OldSeq,
873 Sequence NewSeq) {
874 if (EnableARCAnnotations) {
875 // First generate the source annotation on our pointer. This will return an
876 // MDString* if Ptr actually comes from an instruction implying we can put
877 // in a source annotation. If AppendMDNodeToSourcePtr returns 0 (i.e. NULL),
878 // then we know that our pointer is from an Argument so we put a reference
879 // to the argument number.
880 //
881 // The point of this is to make it easy for the
882 // llvm-arc-annotation-processor tool to cross reference where the source
883 // pointer is in the LLVM IR since the LLVM IR parser does not submit such
884 // information via debug info for backends to use (since why would anyone
885 // need such a thing from LLVM IR besides in non standard cases
886 // [i.e. this]).
887 MDString *SourcePtrMDNode =
888 AppendMDNodeToSourcePtr(PtrMDId, Ptr);
889 AppendMDNodeToInstForPtr(InstMDId, Inst, Ptr, SourcePtrMDNode, OldSeq,
890 NewSeq);
891 }
892}
893
894// The actual interface for accessing the above functionality is defined via
895// some simple macros which are defined below. We do this so that the user does
896// not need to pass in what metadata id is needed resulting in cleaner code and
897// additionally since it provides an easy way to conditionally no-op all
898// annotation support in a non-debug build.
899
900/// Use this macro to annotate a sequence state change when processing
901/// instructions bottom up,
902#define ANNOTATE_BOTTOMUP(inst, ptr, old, new) \
903 GenerateARCAnnotation(ARCAnnotationBottomUpMDKind, \
904 ARCAnnotationProvenanceSourceMDKind, (inst), \
905 const_cast<Value*>(ptr), (old), (new))
906/// Use this macro to annotate a sequence state change when processing
907/// instructions top down.
908#define ANNOTATE_TOPDOWN(inst, ptr, old, new) \
909 GenerateARCAnnotation(ARCAnnotationTopDownMDKind, \
910 ARCAnnotationProvenanceSourceMDKind, (inst), \
911 const_cast<Value*>(ptr), (old), (new))
912
Michael Gottesman43e7e002013-04-03 22:41:59 +0000913#define ANNOTATE_BB(_states, _bb, _name, _type, _direction) \
914 do { \
Michael Gottesman89279f82013-04-05 18:10:41 +0000915 if (EnableARCAnnotations) { \
916 for(BBState::ptr_const_iterator I = (_states)._direction##_ptr_begin(), \
Michael Gottesman43e7e002013-04-03 22:41:59 +0000917 E = (_states)._direction##_ptr_end(); I != E; ++I) { \
Michael Gottesman89279f82013-04-05 18:10:41 +0000918 Value *Ptr = const_cast<Value*>(I->first); \
919 Sequence Seq = I->second.GetSeq(); \
920 GenerateARCBB ## _type ## Annotation(_name, (_bb), Ptr, Seq); \
921 } \
Michael Gottesman43e7e002013-04-03 22:41:59 +0000922 } \
Michael Gottesman89279f82013-04-05 18:10:41 +0000923 } while (0)
Michael Gottesman43e7e002013-04-03 22:41:59 +0000924
Michael Gottesman89279f82013-04-05 18:10:41 +0000925#define ANNOTATE_BOTTOMUP_BBSTART(_states, _basicblock) \
Michael Gottesman43e7e002013-04-03 22:41:59 +0000926 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbstart", \
927 Entrance, bottom_up)
Michael Gottesman89279f82013-04-05 18:10:41 +0000928#define ANNOTATE_BOTTOMUP_BBEND(_states, _basicblock) \
929 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbend", \
Michael Gottesman43e7e002013-04-03 22:41:59 +0000930 Terminator, bottom_up)
Michael Gottesman89279f82013-04-05 18:10:41 +0000931#define ANNOTATE_TOPDOWN_BBSTART(_states, _basicblock) \
932 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbstart", \
Michael Gottesman43e7e002013-04-03 22:41:59 +0000933 Entrance, top_down)
Michael Gottesman89279f82013-04-05 18:10:41 +0000934#define ANNOTATE_TOPDOWN_BBEND(_states, _basicblock) \
935 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbend", \
Michael Gottesman43e7e002013-04-03 22:41:59 +0000936 Terminator, top_down)
937
Michael Gottesman81b1d432013-03-26 00:42:04 +0000938#else // !ARC_ANNOTATION
939// If annotations are off, noop.
940#define ANNOTATE_BOTTOMUP(inst, ptr, old, new)
941#define ANNOTATE_TOPDOWN(inst, ptr, old, new)
Michael Gottesman43e7e002013-04-03 22:41:59 +0000942#define ANNOTATE_BOTTOMUP_BBSTART(states, basicblock)
943#define ANNOTATE_BOTTOMUP_BBEND(states, basicblock)
944#define ANNOTATE_TOPDOWN_BBSTART(states, basicblock)
945#define ANNOTATE_TOPDOWN_BBEND(states, basicblock)
Michael Gottesman81b1d432013-03-26 00:42:04 +0000946#endif // !ARC_ANNOTATION
947
John McCalld935e9c2011-06-15 23:37:01 +0000948namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000949 /// \brief The main ARC optimization pass.
John McCalld935e9c2011-06-15 23:37:01 +0000950 class ObjCARCOpt : public FunctionPass {
951 bool Changed;
952 ProvenanceAnalysis PA;
953
Michael Gottesman97e3df02013-01-14 00:35:14 +0000954 /// A flag indicating whether this optimization pass should run.
Dan Gohmanceaac7c2011-06-20 23:20:43 +0000955 bool Run;
956
Michael Gottesman97e3df02013-01-14 00:35:14 +0000957 /// Declarations for ObjC runtime functions, for use in creating calls to
958 /// them. These are initialized lazily to avoid cluttering up the Module
959 /// with unused declarations.
John McCalld935e9c2011-06-15 23:37:01 +0000960
Michael Gottesman97e3df02013-01-14 00:35:14 +0000961 /// Declaration for ObjC runtime function
962 /// objc_retainAutoreleasedReturnValue.
963 Constant *RetainRVCallee;
964 /// Declaration for ObjC runtime function objc_autoreleaseReturnValue.
965 Constant *AutoreleaseRVCallee;
966 /// Declaration for ObjC runtime function objc_release.
967 Constant *ReleaseCallee;
968 /// Declaration for ObjC runtime function objc_retain.
969 Constant *RetainCallee;
970 /// Declaration for ObjC runtime function objc_retainBlock.
971 Constant *RetainBlockCallee;
972 /// Declaration for ObjC runtime function objc_autorelease.
973 Constant *AutoreleaseCallee;
974
975 /// Flags which determine whether each of the interesting runtine functions
976 /// is in fact used in the current function.
John McCalld935e9c2011-06-15 23:37:01 +0000977 unsigned UsedInThisFunction;
978
Michael Gottesman97e3df02013-01-14 00:35:14 +0000979 /// The Metadata Kind for clang.imprecise_release metadata.
John McCalld935e9c2011-06-15 23:37:01 +0000980 unsigned ImpreciseReleaseMDKind;
981
Michael Gottesman97e3df02013-01-14 00:35:14 +0000982 /// The Metadata Kind for clang.arc.copy_on_escape metadata.
Dan Gohmana7107f92011-10-17 22:53:25 +0000983 unsigned CopyOnEscapeMDKind;
984
Michael Gottesman97e3df02013-01-14 00:35:14 +0000985 /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata.
Dan Gohman0155f302012-02-17 18:59:53 +0000986 unsigned NoObjCARCExceptionsMDKind;
987
Michael Gottesman81b1d432013-03-26 00:42:04 +0000988#ifdef ARC_ANNOTATIONS
989 /// The Metadata Kind for llvm.arc.annotation.bottomup metadata.
990 unsigned ARCAnnotationBottomUpMDKind;
991 /// The Metadata Kind for llvm.arc.annotation.topdown metadata.
992 unsigned ARCAnnotationTopDownMDKind;
993 /// The Metadata Kind for llvm.arc.annotation.provenancesource metadata.
994 unsigned ARCAnnotationProvenanceSourceMDKind;
995#endif // ARC_ANNOATIONS
996
John McCalld935e9c2011-06-15 23:37:01 +0000997 Constant *getRetainRVCallee(Module *M);
998 Constant *getAutoreleaseRVCallee(Module *M);
999 Constant *getReleaseCallee(Module *M);
1000 Constant *getRetainCallee(Module *M);
Dan Gohman6320f522011-07-22 22:29:21 +00001001 Constant *getRetainBlockCallee(Module *M);
John McCalld935e9c2011-06-15 23:37:01 +00001002 Constant *getAutoreleaseCallee(Module *M);
1003
Dan Gohman728db492012-01-13 00:39:07 +00001004 bool IsRetainBlockOptimizable(const Instruction *Inst);
1005
John McCalld935e9c2011-06-15 23:37:01 +00001006 void OptimizeRetainCall(Function &F, Instruction *Retain);
1007 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
Michael Gottesman556ff612013-01-12 01:25:19 +00001008 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1009 InstructionClass &Class);
Michael Gottesman158fdf62013-03-28 20:11:19 +00001010 bool OptimizeRetainBlockCall(Function &F, Instruction *RetainBlock,
1011 InstructionClass &Class);
John McCalld935e9c2011-06-15 23:37:01 +00001012 void OptimizeIndividualCalls(Function &F);
1013
1014 void CheckForCFGHazards(const BasicBlock *BB,
1015 DenseMap<const BasicBlock *, BBState> &BBStates,
1016 BBState &MyStates) const;
Dan Gohman817a7c62012-03-22 18:24:56 +00001017 bool VisitInstructionBottomUp(Instruction *Inst,
Dan Gohman5c70fad2012-03-23 17:47:54 +00001018 BasicBlock *BB,
Dan Gohman817a7c62012-03-22 18:24:56 +00001019 MapVector<Value *, RRInfo> &Retains,
1020 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00001021 bool VisitBottomUp(BasicBlock *BB,
1022 DenseMap<const BasicBlock *, BBState> &BBStates,
1023 MapVector<Value *, RRInfo> &Retains);
Dan Gohman817a7c62012-03-22 18:24:56 +00001024 bool VisitInstructionTopDown(Instruction *Inst,
1025 DenseMap<Value *, RRInfo> &Releases,
1026 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00001027 bool VisitTopDown(BasicBlock *BB,
1028 DenseMap<const BasicBlock *, BBState> &BBStates,
1029 DenseMap<Value *, RRInfo> &Releases);
1030 bool Visit(Function &F,
1031 DenseMap<const BasicBlock *, BBState> &BBStates,
1032 MapVector<Value *, RRInfo> &Retains,
1033 DenseMap<Value *, RRInfo> &Releases);
1034
1035 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1036 MapVector<Value *, RRInfo> &Retains,
1037 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman6320f522011-07-22 22:29:21 +00001038 SmallVectorImpl<Instruction *> &DeadInsts,
1039 Module *M);
John McCalld935e9c2011-06-15 23:37:01 +00001040
Michael Gottesman9de6f962013-01-22 21:49:00 +00001041 bool ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState> &BBStates,
1042 MapVector<Value *, RRInfo> &Retains,
1043 DenseMap<Value *, RRInfo> &Releases,
1044 Module *M,
1045 SmallVector<Instruction *, 4> &NewRetains,
1046 SmallVector<Instruction *, 4> &NewReleases,
1047 SmallVector<Instruction *, 8> &DeadInsts,
1048 RRInfo &RetainsToMove,
1049 RRInfo &ReleasesToMove,
1050 Value *Arg,
1051 bool KnownSafe,
1052 bool &AnyPairsCompletelyEliminated);
1053
John McCalld935e9c2011-06-15 23:37:01 +00001054 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1055 MapVector<Value *, RRInfo> &Retains,
Dan Gohman6320f522011-07-22 22:29:21 +00001056 DenseMap<Value *, RRInfo> &Releases,
1057 Module *M);
John McCalld935e9c2011-06-15 23:37:01 +00001058
1059 void OptimizeWeakCalls(Function &F);
1060
1061 bool OptimizeSequences(Function &F);
1062
1063 void OptimizeReturns(Function &F);
1064
1065 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1066 virtual bool doInitialization(Module &M);
1067 virtual bool runOnFunction(Function &F);
1068 virtual void releaseMemory();
1069
1070 public:
1071 static char ID;
1072 ObjCARCOpt() : FunctionPass(ID) {
1073 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1074 }
1075 };
1076}
1077
1078char ObjCARCOpt::ID = 0;
1079INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1080 "objc-arc", "ObjC ARC optimization", false, false)
1081INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1082INITIALIZE_PASS_END(ObjCARCOpt,
1083 "objc-arc", "ObjC ARC optimization", false, false)
1084
1085Pass *llvm::createObjCARCOptPass() {
1086 return new ObjCARCOpt();
1087}
1088
1089void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1090 AU.addRequired<ObjCARCAliasAnalysis>();
1091 AU.addRequired<AliasAnalysis>();
1092 // ARC optimization doesn't currently split critical edges.
1093 AU.setPreservesCFG();
1094}
1095
Dan Gohman728db492012-01-13 00:39:07 +00001096bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1097 // Without the magic metadata tag, we have to assume this might be an
1098 // objc_retainBlock call inserted to convert a block pointer to an id,
1099 // in which case it really is needed.
1100 if (!Inst->getMetadata(CopyOnEscapeMDKind))
1101 return false;
1102
1103 // If the pointer "escapes" (not including being used in a call),
1104 // the copy may be needed.
Michael Gottesman774d2c02013-01-29 21:00:52 +00001105 if (DoesRetainableObjPtrEscape(Inst))
Dan Gohman728db492012-01-13 00:39:07 +00001106 return false;
1107
1108 // Otherwise, it's not needed.
1109 return true;
1110}
1111
John McCalld935e9c2011-06-15 23:37:01 +00001112Constant *ObjCARCOpt::getRetainRVCallee(Module *M) {
1113 if (!RetainRVCallee) {
1114 LLVMContext &C = M->getContext();
Jay Foadb804a2b2011-07-12 14:06:48 +00001115 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman41375a32012-05-08 23:39:44 +00001116 Type *Params[] = { I8X };
1117 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001118 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001119 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1120 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001121 RetainRVCallee =
1122 M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy,
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001123 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001124 }
1125 return RetainRVCallee;
1126}
1127
1128Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1129 if (!AutoreleaseRVCallee) {
1130 LLVMContext &C = M->getContext();
Jay Foadb804a2b2011-07-12 14:06:48 +00001131 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman41375a32012-05-08 23:39:44 +00001132 Type *Params[] = { I8X };
1133 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001134 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001135 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1136 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001137 AutoreleaseRVCallee =
1138 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001139 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001140 }
1141 return AutoreleaseRVCallee;
1142}
1143
1144Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1145 if (!ReleaseCallee) {
1146 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001147 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001148 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001149 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1150 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001151 ReleaseCallee =
1152 M->getOrInsertFunction(
1153 "objc_release",
1154 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001155 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001156 }
1157 return ReleaseCallee;
1158}
1159
1160Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1161 if (!RetainCallee) {
1162 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001163 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
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 RetainCallee =
1168 M->getOrInsertFunction(
1169 "objc_retain",
1170 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001171 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001172 }
1173 return RetainCallee;
1174}
1175
Dan Gohman6320f522011-07-22 22:29:21 +00001176Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1177 if (!RetainBlockCallee) {
1178 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001179 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Dan Gohmanfca43c22011-09-14 18:33:34 +00001180 // objc_retainBlock is not nounwind because it calls user copy constructors
1181 // which could theoretically throw.
Dan Gohman6320f522011-07-22 22:29:21 +00001182 RetainBlockCallee =
1183 M->getOrInsertFunction(
1184 "objc_retainBlock",
1185 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendlinge94d8432012-12-07 23:16:57 +00001186 AttributeSet());
Dan Gohman6320f522011-07-22 22:29:21 +00001187 }
1188 return RetainBlockCallee;
1189}
1190
John McCalld935e9c2011-06-15 23:37:01 +00001191Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1192 if (!AutoreleaseCallee) {
1193 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001194 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001195 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001196 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1197 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001198 AutoreleaseCallee =
1199 M->getOrInsertFunction(
1200 "objc_autorelease",
1201 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001202 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001203 }
1204 return AutoreleaseCallee;
1205}
1206
Michael Gottesman97e3df02013-01-14 00:35:14 +00001207/// Turn objc_retain into objc_retainAutoreleasedReturnValue if the operand is a
1208/// return value.
John McCalld935e9c2011-06-15 23:37:01 +00001209void
1210ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) {
Dan Gohmandae33492012-04-27 18:56:31 +00001211 ImmutableCallSite CS(GetObjCArg(Retain));
1212 const Instruction *Call = CS.getInstruction();
John McCalld935e9c2011-06-15 23:37:01 +00001213 if (!Call) return;
1214 if (Call->getParent() != Retain->getParent()) return;
1215
1216 // Check that the call is next to the retain.
Dan Gohmandae33492012-04-27 18:56:31 +00001217 BasicBlock::const_iterator I = Call;
John McCalld935e9c2011-06-15 23:37:01 +00001218 ++I;
Michael Gottesman65c24812013-03-25 09:27:43 +00001219 while (IsNoopInstruction(I)) ++I;
John McCalld935e9c2011-06-15 23:37:01 +00001220 if (&*I != Retain)
1221 return;
1222
1223 // Turn it to an objc_retainAutoreleasedReturnValue..
1224 Changed = true;
1225 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00001226
Michael Gottesman89279f82013-04-05 18:10:41 +00001227 DEBUG(dbgs() << "Transforming objc_retain => "
1228 "objc_retainAutoreleasedReturnValue since the operand is a "
1229 "return value.\nOld: "<< *Retain << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001230
John McCalld935e9c2011-06-15 23:37:01 +00001231 cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent()));
Michael Gottesman1e00ac62013-01-04 21:30:38 +00001232
Michael Gottesman89279f82013-04-05 18:10:41 +00001233 DEBUG(dbgs() << "New: " << *Retain << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001234}
1235
Michael Gottesman97e3df02013-01-14 00:35:14 +00001236/// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is
1237/// not a return value. Or, if it can be paired with an
1238/// objc_autoreleaseReturnValue, delete the pair and return true.
John McCalld935e9c2011-06-15 23:37:01 +00001239bool
1240ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001241 // Check for the argument being from an immediately preceding call or invoke.
Dan Gohmandae33492012-04-27 18:56:31 +00001242 const Value *Arg = GetObjCArg(RetainRV);
1243 ImmutableCallSite CS(Arg);
1244 if (const Instruction *Call = CS.getInstruction()) {
John McCalld935e9c2011-06-15 23:37:01 +00001245 if (Call->getParent() == RetainRV->getParent()) {
Dan Gohmandae33492012-04-27 18:56:31 +00001246 BasicBlock::const_iterator I = Call;
John McCalld935e9c2011-06-15 23:37:01 +00001247 ++I;
Michael Gottesman65c24812013-03-25 09:27:43 +00001248 while (IsNoopInstruction(I)) ++I;
John McCalld935e9c2011-06-15 23:37:01 +00001249 if (&*I == RetainRV)
1250 return false;
Dan Gohmandae33492012-04-27 18:56:31 +00001251 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001252 BasicBlock *RetainRVParent = RetainRV->getParent();
1253 if (II->getNormalDest() == RetainRVParent) {
Dan Gohmandae33492012-04-27 18:56:31 +00001254 BasicBlock::const_iterator I = RetainRVParent->begin();
Michael Gottesman65c24812013-03-25 09:27:43 +00001255 while (IsNoopInstruction(I)) ++I;
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001256 if (&*I == RetainRV)
1257 return false;
1258 }
John McCalld935e9c2011-06-15 23:37:01 +00001259 }
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001260 }
John McCalld935e9c2011-06-15 23:37:01 +00001261
1262 // Check for being preceded by an objc_autoreleaseReturnValue on the same
1263 // pointer. In this case, we can delete the pair.
1264 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
1265 if (I != Begin) {
Michael Gottesman65c24812013-03-25 09:27:43 +00001266 do --I; while (I != Begin && IsNoopInstruction(I));
John McCalld935e9c2011-06-15 23:37:01 +00001267 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
1268 GetObjCArg(I) == Arg) {
1269 Changed = true;
1270 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00001271
Michael Gottesman89279f82013-04-05 18:10:41 +00001272 DEBUG(dbgs() << "Erasing autoreleaseRV,retainRV pair: " << *I << "\n"
1273 << "Erasing " << *RetainRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001274
John McCalld935e9c2011-06-15 23:37:01 +00001275 EraseInstruction(I);
1276 EraseInstruction(RetainRV);
1277 return true;
1278 }
1279 }
1280
1281 // Turn it to a plain objc_retain.
1282 Changed = true;
1283 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00001284
Michael Gottesman89279f82013-04-05 18:10:41 +00001285 DEBUG(dbgs() << "Transforming objc_retainAutoreleasedReturnValue => "
Michael Gottesmandef07bb2013-01-05 17:55:42 +00001286 "objc_retain since the operand is not a return value.\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00001287 "Old = " << *RetainRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001288
John McCalld935e9c2011-06-15 23:37:01 +00001289 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
Michael Gottesmandef07bb2013-01-05 17:55:42 +00001290
Michael Gottesman89279f82013-04-05 18:10:41 +00001291 DEBUG(dbgs() << "New = " << *RetainRV << "\n");
Michael Gottesmandef07bb2013-01-05 17:55:42 +00001292
John McCalld935e9c2011-06-15 23:37:01 +00001293 return false;
1294}
1295
Michael Gottesman97e3df02013-01-14 00:35:14 +00001296/// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not
1297/// used as a return value.
John McCalld935e9c2011-06-15 23:37:01 +00001298void
Michael Gottesman556ff612013-01-12 01:25:19 +00001299ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1300 InstructionClass &Class) {
John McCalld935e9c2011-06-15 23:37:01 +00001301 // Check for a return of the pointer value.
1302 const Value *Ptr = GetObjCArg(AutoreleaseRV);
Dan Gohman10a18d52011-08-12 00:36:31 +00001303 SmallVector<const Value *, 2> Users;
1304 Users.push_back(Ptr);
1305 do {
1306 Ptr = Users.pop_back_val();
1307 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
1308 UI != UE; ++UI) {
1309 const User *I = *UI;
1310 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
1311 return;
1312 if (isa<BitCastInst>(I))
1313 Users.push_back(I);
1314 }
1315 } while (!Users.empty());
John McCalld935e9c2011-06-15 23:37:01 +00001316
1317 Changed = true;
1318 ++NumPeeps;
Michael Gottesman1bf69082013-01-06 21:07:11 +00001319
Michael Gottesman89279f82013-04-05 18:10:41 +00001320 DEBUG(dbgs() << "Transforming objc_autoreleaseReturnValue => "
Michael Gottesman1bf69082013-01-06 21:07:11 +00001321 "objc_autorelease since its operand is not used as a return "
1322 "value.\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00001323 "Old = " << *AutoreleaseRV << "\n");
Michael Gottesman1bf69082013-01-06 21:07:11 +00001324
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001325 CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
1326 AutoreleaseRVCI->
John McCalld935e9c2011-06-15 23:37:01 +00001327 setCalledFunction(getAutoreleaseCallee(F.getParent()));
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001328 AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
Michael Gottesman556ff612013-01-12 01:25:19 +00001329 Class = IC_Autorelease;
Michael Gottesman10426b52013-01-07 21:26:07 +00001330
Michael Gottesman89279f82013-04-05 18:10:41 +00001331 DEBUG(dbgs() << "New: " << *AutoreleaseRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001332
John McCalld935e9c2011-06-15 23:37:01 +00001333}
1334
Michael Gottesman158fdf62013-03-28 20:11:19 +00001335// \brief Attempt to strength reduce objc_retainBlock calls to objc_retain
1336// calls.
1337//
1338// Specifically: If an objc_retainBlock call has the copy_on_escape metadata and
1339// does not escape (following the rules of block escaping), strength reduce the
1340// objc_retainBlock to an objc_retain.
1341//
1342// TODO: If an objc_retainBlock call is dominated period by a previous
1343// objc_retainBlock call, strength reduce the objc_retainBlock to an
1344// objc_retain.
1345bool
1346ObjCARCOpt::OptimizeRetainBlockCall(Function &F, Instruction *Inst,
1347 InstructionClass &Class) {
1348 assert(GetBasicInstructionClass(Inst) == Class);
1349 assert(IC_RetainBlock == Class);
Michael Gottesman60f6b282013-03-29 05:13:07 +00001350
Michael Gottesman158fdf62013-03-28 20:11:19 +00001351 // If we can not optimize Inst, return false.
1352 if (!IsRetainBlockOptimizable(Inst))
1353 return false;
Michael Gottesman60f6b282013-03-29 05:13:07 +00001354
Michael Gottesman158fdf62013-03-28 20:11:19 +00001355 CallInst *RetainBlock = cast<CallInst>(Inst);
1356 RetainBlock->setCalledFunction(getRetainCallee(F.getParent()));
1357 // Remove copy_on_escape metadata.
1358 RetainBlock->setMetadata(CopyOnEscapeMDKind, 0);
1359 Class = IC_Retain;
Michael Gottesman60f6b282013-03-29 05:13:07 +00001360
Michael Gottesman158fdf62013-03-28 20:11:19 +00001361 return true;
1362}
1363
Michael Gottesman97e3df02013-01-14 00:35:14 +00001364/// Visit each call, one at a time, and make simplifications without doing any
1365/// additional analysis.
John McCalld935e9c2011-06-15 23:37:01 +00001366void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001367 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeIndividualCalls ==\n");
John McCalld935e9c2011-06-15 23:37:01 +00001368 // Reset all the flags in preparation for recomputing them.
1369 UsedInThisFunction = 0;
1370
1371 // Visit all objc_* calls in F.
1372 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
1373 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +00001374
John McCalld935e9c2011-06-15 23:37:01 +00001375 InstructionClass Class = GetBasicInstructionClass(Inst);
1376
Michael Gottesman89279f82013-04-05 18:10:41 +00001377 DEBUG(dbgs() << "Visiting: Class: " << Class << "; " << *Inst << "\n");
Michael Gottesman782e3442013-01-17 18:32:34 +00001378
John McCalld935e9c2011-06-15 23:37:01 +00001379 switch (Class) {
1380 default: break;
1381
1382 // Delete no-op casts. These function calls have special semantics, but
1383 // the semantics are entirely implemented via lowering in the front-end,
1384 // so by the time they reach the optimizer, they are just no-op calls
1385 // which return their argument.
1386 //
1387 // There are gray areas here, as the ability to cast reference-counted
1388 // pointers to raw void* and back allows code to break ARC assumptions,
1389 // however these are currently considered to be unimportant.
1390 case IC_NoopCast:
1391 Changed = true;
1392 ++NumNoops;
Michael Gottesman89279f82013-04-05 18:10:41 +00001393 DEBUG(dbgs() << "Erasing no-op cast: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001394 EraseInstruction(Inst);
1395 continue;
1396
1397 // If the pointer-to-weak-pointer is null, it's undefined behavior.
1398 case IC_StoreWeak:
1399 case IC_LoadWeak:
1400 case IC_LoadWeakRetained:
1401 case IC_InitWeak:
1402 case IC_DestroyWeak: {
1403 CallInst *CI = cast<CallInst>(Inst);
Michael Gottesman65c24812013-03-25 09:27:43 +00001404 if (IsNullOrUndef(CI->getArgOperand(0))) {
Dan Gohman670f9372012-04-13 18:57:48 +00001405 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +00001406 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001407 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1408 Constant::getNullValue(Ty),
1409 CI);
Michael Gottesman10426b52013-01-07 21:26:07 +00001410 llvm::Value *NewValue = UndefValue::get(CI->getType());
Michael Gottesman89279f82013-04-05 18:10:41 +00001411 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
1412 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001413 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +00001414 CI->eraseFromParent();
1415 continue;
1416 }
1417 break;
1418 }
1419 case IC_CopyWeak:
1420 case IC_MoveWeak: {
1421 CallInst *CI = cast<CallInst>(Inst);
Michael Gottesman65c24812013-03-25 09:27:43 +00001422 if (IsNullOrUndef(CI->getArgOperand(0)) ||
1423 IsNullOrUndef(CI->getArgOperand(1))) {
Dan Gohman670f9372012-04-13 18:57:48 +00001424 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +00001425 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001426 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1427 Constant::getNullValue(Ty),
1428 CI);
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001429
1430 llvm::Value *NewValue = UndefValue::get(CI->getType());
Michael Gottesman89279f82013-04-05 18:10:41 +00001431 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
1432 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001433
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001434 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +00001435 CI->eraseFromParent();
1436 continue;
1437 }
1438 break;
1439 }
Michael Gottesman158fdf62013-03-28 20:11:19 +00001440 case IC_RetainBlock:
1441 // If we strength reduce an objc_retainBlock to amn objc_retain, continue
1442 // onto the objc_retain peephole optimizations. Otherwise break.
1443 if (!OptimizeRetainBlockCall(F, Inst, Class))
1444 break;
1445 // FALLTHROUGH
John McCalld935e9c2011-06-15 23:37:01 +00001446 case IC_Retain:
1447 OptimizeRetainCall(F, Inst);
1448 break;
1449 case IC_RetainRV:
1450 if (OptimizeRetainRVCall(F, Inst))
1451 continue;
1452 break;
1453 case IC_AutoreleaseRV:
Michael Gottesman556ff612013-01-12 01:25:19 +00001454 OptimizeAutoreleaseRVCall(F, Inst, Class);
John McCalld935e9c2011-06-15 23:37:01 +00001455 break;
1456 }
1457
Michael Gottesmanb8c88362013-04-03 02:57:24 +00001458 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
John McCalld935e9c2011-06-15 23:37:01 +00001459 if (IsAutorelease(Class) && Inst->use_empty()) {
1460 CallInst *Call = cast<CallInst>(Inst);
1461 const Value *Arg = Call->getArgOperand(0);
1462 Arg = FindSingleUseIdentifiedObject(Arg);
1463 if (Arg) {
1464 Changed = true;
1465 ++NumAutoreleases;
1466
1467 // Create the declaration lazily.
1468 LLVMContext &C = Inst->getContext();
1469 CallInst *NewCall =
1470 CallInst::Create(getReleaseCallee(F.getParent()),
1471 Call->getArgOperand(0), "", Call);
1472 NewCall->setMetadata(ImpreciseReleaseMDKind,
1473 MDNode::get(C, ArrayRef<Value *>()));
Michael Gottesman10426b52013-01-07 21:26:07 +00001474
Michael Gottesman89279f82013-04-05 18:10:41 +00001475 DEBUG(dbgs() << "Replacing autorelease{,RV}(x) with objc_release(x) "
1476 "since x is otherwise unused.\nOld: " << *Call << "\nNew: "
1477 << *NewCall << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001478
John McCalld935e9c2011-06-15 23:37:01 +00001479 EraseInstruction(Call);
1480 Inst = NewCall;
1481 Class = IC_Release;
1482 }
1483 }
1484
1485 // For functions which can never be passed stack arguments, add
1486 // a tail keyword.
1487 if (IsAlwaysTail(Class)) {
1488 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +00001489 DEBUG(dbgs() << "Adding tail keyword to function since it can never be "
1490 "passed stack args: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001491 cast<CallInst>(Inst)->setTailCall();
1492 }
1493
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001494 // Ensure that functions that can never have a "tail" keyword due to the
1495 // semantics of ARC truly do not do so.
1496 if (IsNeverTail(Class)) {
1497 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +00001498 DEBUG(dbgs() << "Removing tail keyword from function: " << *Inst <<
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001499 "\n");
1500 cast<CallInst>(Inst)->setTailCall(false);
1501 }
1502
John McCalld935e9c2011-06-15 23:37:01 +00001503 // Set nounwind as needed.
1504 if (IsNoThrow(Class)) {
1505 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +00001506 DEBUG(dbgs() << "Found no throw class. Setting nounwind on: " << *Inst
1507 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001508 cast<CallInst>(Inst)->setDoesNotThrow();
1509 }
1510
1511 if (!IsNoopOnNull(Class)) {
1512 UsedInThisFunction |= 1 << Class;
1513 continue;
1514 }
1515
1516 const Value *Arg = GetObjCArg(Inst);
1517
1518 // ARC calls with null are no-ops. Delete them.
Michael Gottesman65c24812013-03-25 09:27:43 +00001519 if (IsNullOrUndef(Arg)) {
John McCalld935e9c2011-06-15 23:37:01 +00001520 Changed = true;
1521 ++NumNoops;
Michael Gottesman89279f82013-04-05 18:10:41 +00001522 DEBUG(dbgs() << "ARC calls with null are no-ops. Erasing: " << *Inst
1523 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001524 EraseInstruction(Inst);
1525 continue;
1526 }
1527
1528 // Keep track of which of retain, release, autorelease, and retain_block
1529 // are actually present in this function.
1530 UsedInThisFunction |= 1 << Class;
1531
1532 // If Arg is a PHI, and one or more incoming values to the
1533 // PHI are null, and the call is control-equivalent to the PHI, and there
1534 // are no relevant side effects between the PHI and the call, the call
1535 // could be pushed up to just those paths with non-null incoming values.
1536 // For now, don't bother splitting critical edges for this.
1537 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
1538 Worklist.push_back(std::make_pair(Inst, Arg));
1539 do {
1540 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
1541 Inst = Pair.first;
1542 Arg = Pair.second;
1543
1544 const PHINode *PN = dyn_cast<PHINode>(Arg);
1545 if (!PN) continue;
1546
1547 // Determine if the PHI has any null operands, or any incoming
1548 // critical edges.
1549 bool HasNull = false;
1550 bool HasCriticalEdges = false;
1551 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1552 Value *Incoming =
1553 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
Michael Gottesman65c24812013-03-25 09:27:43 +00001554 if (IsNullOrUndef(Incoming))
John McCalld935e9c2011-06-15 23:37:01 +00001555 HasNull = true;
1556 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
1557 .getNumSuccessors() != 1) {
1558 HasCriticalEdges = true;
1559 break;
1560 }
1561 }
1562 // If we have null operands and no critical edges, optimize.
1563 if (!HasCriticalEdges && HasNull) {
1564 SmallPtrSet<Instruction *, 4> DependingInstructions;
1565 SmallPtrSet<const BasicBlock *, 4> Visited;
1566
1567 // Check that there is nothing that cares about the reference
1568 // count between the call and the phi.
Dan Gohman8478d762012-04-13 00:59:57 +00001569 switch (Class) {
1570 case IC_Retain:
1571 case IC_RetainBlock:
1572 // These can always be moved up.
1573 break;
1574 case IC_Release:
Dan Gohman41375a32012-05-08 23:39:44 +00001575 // These can't be moved across things that care about the retain
1576 // count.
Dan Gohman8478d762012-04-13 00:59:57 +00001577 FindDependencies(NeedsPositiveRetainCount, Arg,
1578 Inst->getParent(), Inst,
1579 DependingInstructions, Visited, PA);
1580 break;
1581 case IC_Autorelease:
1582 // These can't be moved across autorelease pool scope boundaries.
1583 FindDependencies(AutoreleasePoolBoundary, Arg,
1584 Inst->getParent(), Inst,
1585 DependingInstructions, Visited, PA);
1586 break;
1587 case IC_RetainRV:
1588 case IC_AutoreleaseRV:
1589 // Don't move these; the RV optimization depends on the autoreleaseRV
1590 // being tail called, and the retainRV being immediately after a call
1591 // (which might still happen if we get lucky with codegen layout, but
1592 // it's not worth taking the chance).
1593 continue;
1594 default:
1595 llvm_unreachable("Invalid dependence flavor");
1596 }
1597
John McCalld935e9c2011-06-15 23:37:01 +00001598 if (DependingInstructions.size() == 1 &&
1599 *DependingInstructions.begin() == PN) {
1600 Changed = true;
1601 ++NumPartialNoops;
1602 // Clone the call into each predecessor that has a non-null value.
1603 CallInst *CInst = cast<CallInst>(Inst);
Chris Lattner229907c2011-07-18 04:54:35 +00001604 Type *ParamTy = CInst->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001605 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1606 Value *Incoming =
1607 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
Michael Gottesman65c24812013-03-25 09:27:43 +00001608 if (!IsNullOrUndef(Incoming)) {
John McCalld935e9c2011-06-15 23:37:01 +00001609 CallInst *Clone = cast<CallInst>(CInst->clone());
1610 Value *Op = PN->getIncomingValue(i);
1611 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
1612 if (Op->getType() != ParamTy)
1613 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
1614 Clone->setArgOperand(0, Op);
1615 Clone->insertBefore(InsertPos);
Michael Gottesmanc189a392013-01-09 19:23:24 +00001616
Michael Gottesman89279f82013-04-05 18:10:41 +00001617 DEBUG(dbgs() << "Cloning "
Michael Gottesmanc189a392013-01-09 19:23:24 +00001618 << *CInst << "\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00001619 "And inserting clone at " << *InsertPos << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001620 Worklist.push_back(std::make_pair(Clone, Incoming));
1621 }
1622 }
1623 // Erase the original call.
Michael Gottesmanc189a392013-01-09 19:23:24 +00001624 DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001625 EraseInstruction(CInst);
1626 continue;
1627 }
1628 }
1629 } while (!Worklist.empty());
1630 }
1631}
1632
Michael Gottesman97e3df02013-01-14 00:35:14 +00001633/// Check for critical edges, loop boundaries, irreducible control flow, or
1634/// other CFG structures where moving code across the edge would result in it
1635/// being executed more.
John McCalld935e9c2011-06-15 23:37:01 +00001636void
1637ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
1638 DenseMap<const BasicBlock *, BBState> &BBStates,
1639 BBState &MyStates) const {
1640 // If any top-down local-use or possible-dec has a succ which is earlier in
1641 // the sequence, forget it.
Dan Gohman55b06742012-03-02 01:13:53 +00001642 for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
John McCalld935e9c2011-06-15 23:37:01 +00001643 E = MyStates.top_down_ptr_end(); I != E; ++I)
1644 switch (I->second.GetSeq()) {
1645 default: break;
1646 case S_Use: {
1647 const Value *Arg = I->first;
1648 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
1649 bool SomeSuccHasSame = false;
1650 bool AllSuccsHaveSame = true;
Dan Gohman55b06742012-03-02 01:13:53 +00001651 PtrState &S = I->second;
Dan Gohman0155f302012-02-17 18:59:53 +00001652 succ_const_iterator SI(TI), SE(TI, false);
1653
Dan Gohman0155f302012-02-17 18:59:53 +00001654 for (; SI != SE; ++SI) {
Dan Gohman362eb692012-03-02 01:26:46 +00001655 Sequence SuccSSeq = S_None;
1656 bool SuccSRRIKnownSafe = false;
Dan Gohman41375a32012-05-08 23:39:44 +00001657 // If VisitBottomUp has pointer information for this successor, take
1658 // what we know about it.
Dan Gohmandae33492012-04-27 18:56:31 +00001659 DenseMap<const BasicBlock *, BBState>::iterator BBI =
1660 BBStates.find(*SI);
1661 assert(BBI != BBStates.end());
1662 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
1663 SuccSSeq = SuccS.GetSeq();
1664 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
Dan Gohman362eb692012-03-02 01:26:46 +00001665 switch (SuccSSeq) {
John McCalld935e9c2011-06-15 23:37:01 +00001666 case S_None:
Dan Gohman12130272011-08-12 00:26:31 +00001667 case S_CanRelease: {
Dan Gohman362eb692012-03-02 01:26:46 +00001668 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
Dan Gohman12130272011-08-12 00:26:31 +00001669 S.ClearSequenceProgress();
Dan Gohman362eb692012-03-02 01:26:46 +00001670 break;
1671 }
Dan Gohman12130272011-08-12 00:26:31 +00001672 continue;
1673 }
John McCalld935e9c2011-06-15 23:37:01 +00001674 case S_Use:
1675 SomeSuccHasSame = true;
1676 break;
1677 case S_Stop:
1678 case S_Release:
1679 case S_MovableRelease:
Dan Gohman362eb692012-03-02 01:26:46 +00001680 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
Dan Gohman12130272011-08-12 00:26:31 +00001681 AllSuccsHaveSame = false;
John McCalld935e9c2011-06-15 23:37:01 +00001682 break;
1683 case S_Retain:
1684 llvm_unreachable("bottom-up pointer in retain state!");
1685 }
Dan Gohman12130272011-08-12 00:26:31 +00001686 }
John McCalld935e9c2011-06-15 23:37:01 +00001687 // If the state at the other end of any of the successor edges
1688 // matches the current state, require all edges to match. This
1689 // guards against loops in the middle of a sequence.
1690 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohman12130272011-08-12 00:26:31 +00001691 S.ClearSequenceProgress();
Dan Gohman044437062011-12-12 18:13:53 +00001692 break;
John McCalld935e9c2011-06-15 23:37:01 +00001693 }
1694 case S_CanRelease: {
1695 const Value *Arg = I->first;
1696 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
1697 bool SomeSuccHasSame = false;
1698 bool AllSuccsHaveSame = true;
Dan Gohman55b06742012-03-02 01:13:53 +00001699 PtrState &S = I->second;
Dan Gohman0155f302012-02-17 18:59:53 +00001700 succ_const_iterator SI(TI), SE(TI, false);
1701
Dan Gohman0155f302012-02-17 18:59:53 +00001702 for (; SI != SE; ++SI) {
Dan Gohman362eb692012-03-02 01:26:46 +00001703 Sequence SuccSSeq = S_None;
1704 bool SuccSRRIKnownSafe = false;
Dan Gohman41375a32012-05-08 23:39:44 +00001705 // If VisitBottomUp has pointer information for this successor, take
1706 // what we know about it.
Dan Gohmandae33492012-04-27 18:56:31 +00001707 DenseMap<const BasicBlock *, BBState>::iterator BBI =
1708 BBStates.find(*SI);
1709 assert(BBI != BBStates.end());
1710 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
1711 SuccSSeq = SuccS.GetSeq();
1712 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
Dan Gohman362eb692012-03-02 01:26:46 +00001713 switch (SuccSSeq) {
Dan Gohman12130272011-08-12 00:26:31 +00001714 case S_None: {
Dan Gohman362eb692012-03-02 01:26:46 +00001715 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
Dan Gohman12130272011-08-12 00:26:31 +00001716 S.ClearSequenceProgress();
Dan Gohman362eb692012-03-02 01:26:46 +00001717 break;
1718 }
Dan Gohman12130272011-08-12 00:26:31 +00001719 continue;
1720 }
John McCalld935e9c2011-06-15 23:37:01 +00001721 case S_CanRelease:
1722 SomeSuccHasSame = true;
1723 break;
1724 case S_Stop:
1725 case S_Release:
1726 case S_MovableRelease:
1727 case S_Use:
Dan Gohman362eb692012-03-02 01:26:46 +00001728 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
Dan Gohman12130272011-08-12 00:26:31 +00001729 AllSuccsHaveSame = false;
John McCalld935e9c2011-06-15 23:37:01 +00001730 break;
1731 case S_Retain:
1732 llvm_unreachable("bottom-up pointer in retain state!");
1733 }
Dan Gohman12130272011-08-12 00:26:31 +00001734 }
John McCalld935e9c2011-06-15 23:37:01 +00001735 // If the state at the other end of any of the successor edges
1736 // matches the current state, require all edges to match. This
1737 // guards against loops in the middle of a sequence.
1738 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohman12130272011-08-12 00:26:31 +00001739 S.ClearSequenceProgress();
Dan Gohman044437062011-12-12 18:13:53 +00001740 break;
John McCalld935e9c2011-06-15 23:37:01 +00001741 }
1742 }
1743}
1744
1745bool
Dan Gohman817a7c62012-03-22 18:24:56 +00001746ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
Dan Gohman5c70fad2012-03-23 17:47:54 +00001747 BasicBlock *BB,
Dan Gohman817a7c62012-03-22 18:24:56 +00001748 MapVector<Value *, RRInfo> &Retains,
1749 BBState &MyStates) {
1750 bool NestingDetected = false;
1751 InstructionClass Class = GetInstructionClass(Inst);
1752 const Value *Arg = 0;
Michael Gottesman1d8d2572013-04-05 22:54:28 +00001753
1754 DEBUG(dbgs() << "Class: " << Class << "\n");
1755
Dan Gohman817a7c62012-03-22 18:24:56 +00001756 switch (Class) {
1757 case IC_Release: {
1758 Arg = GetObjCArg(Inst);
1759
1760 PtrState &S = MyStates.getPtrBottomUpState(Arg);
1761
1762 // If we see two releases in a row on the same pointer. If so, make
1763 // a note, and we'll cicle back to revisit it after we've
1764 // hopefully eliminated the second release, which may allow us to
1765 // eliminate the first release too.
1766 // Theoretically we could implement removal of nested retain+release
1767 // pairs by making PtrState hold a stack of states, but this is
1768 // simple and avoids adding overhead for the non-nested case.
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001769 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001770 DEBUG(dbgs() << "Found nested releases (i.e. a release pair)\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00001771 NestingDetected = true;
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001772 }
Dan Gohman817a7c62012-03-22 18:24:56 +00001773
Dan Gohman817a7c62012-03-22 18:24:56 +00001774 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001775 Sequence NewSeq = ReleaseMetadata ? S_MovableRelease : S_Release;
1776 ANNOTATE_BOTTOMUP(Inst, Arg, S.GetSeq(), NewSeq);
1777 S.ResetSequenceProgress(NewSeq);
Dan Gohman817a7c62012-03-22 18:24:56 +00001778 S.RRI.ReleaseMetadata = ReleaseMetadata;
Michael Gottesman07beea42013-03-23 05:31:01 +00001779 S.RRI.KnownSafe = S.HasKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001780 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
1781 S.RRI.Calls.insert(Inst);
Dan Gohmandf476e52012-09-04 23:16:20 +00001782 S.SetKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001783 break;
1784 }
1785 case IC_RetainBlock:
Michael Gottesman158fdf62013-03-28 20:11:19 +00001786 // In OptimizeIndividualCalls, we have strength reduced all optimizable
1787 // objc_retainBlocks to objc_retains. Thus at this point any
1788 // objc_retainBlocks that we see are not optimizable.
1789 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001790 case IC_Retain:
1791 case IC_RetainRV: {
1792 Arg = GetObjCArg(Inst);
1793
1794 PtrState &S = MyStates.getPtrBottomUpState(Arg);
Dan Gohman62079b42012-04-25 00:50:46 +00001795 S.SetKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001796
Michael Gottesman81b1d432013-03-26 00:42:04 +00001797 Sequence OldSeq = S.GetSeq();
1798 switch (OldSeq) {
Dan Gohman817a7c62012-03-22 18:24:56 +00001799 case S_Stop:
1800 case S_Release:
1801 case S_MovableRelease:
1802 case S_Use:
Michael Gottesman1d8d2572013-04-05 22:54:28 +00001803 // If OldSeq is not S_Use or OldSeq is S_Use and we are tracking an
1804 // imprecise release, clear our reverse insertion points.
1805 if (OldSeq != S_Use || S.RRI.IsTrackingImpreciseReleases())
1806 S.RRI.ReverseInsertPts.clear();
Dan Gohman817a7c62012-03-22 18:24:56 +00001807 // FALL THROUGH
1808 case S_CanRelease:
1809 // Don't do retain+release tracking for IC_RetainRV, because it's
1810 // better to let it remain as the first instruction after a call.
Michael Gottesmanba648592013-03-28 23:08:44 +00001811 if (Class != IC_RetainRV)
Dan Gohman817a7c62012-03-22 18:24:56 +00001812 Retains[Inst] = S.RRI;
Dan Gohman817a7c62012-03-22 18:24:56 +00001813 S.ClearSequenceProgress();
1814 break;
1815 case S_None:
1816 break;
1817 case S_Retain:
1818 llvm_unreachable("bottom-up pointer in retain state!");
1819 }
Michael Gottesman31ba23a2013-04-05 22:54:32 +00001820 ANNOTATE_BOTTOMUP(Inst, Arg, OldSeq, S.GetSeq());
1821 // A retain moving bottom up can be a use.
1822 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001823 }
1824 case IC_AutoreleasepoolPop:
1825 // Conservatively, clear MyStates for all known pointers.
1826 MyStates.clearBottomUpPointers();
1827 return NestingDetected;
1828 case IC_AutoreleasepoolPush:
1829 case IC_None:
1830 // These are irrelevant.
1831 return NestingDetected;
1832 default:
1833 break;
1834 }
1835
1836 // Consider any other possible effects of this instruction on each
1837 // pointer being tracked.
1838 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
1839 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
1840 const Value *Ptr = MI->first;
1841 if (Ptr == Arg)
1842 continue; // Handled above.
1843 PtrState &S = MI->second;
1844 Sequence Seq = S.GetSeq();
1845
1846 // Check for possible releases.
1847 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001848 DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr
1849 << "\n");
Michael Gottesman764b1cf2013-03-23 05:46:19 +00001850 S.ClearKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001851 switch (Seq) {
1852 case S_Use:
1853 S.SetSeq(S_CanRelease);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001854 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S.GetSeq());
Dan Gohman817a7c62012-03-22 18:24:56 +00001855 continue;
1856 case S_CanRelease:
1857 case S_Release:
1858 case S_MovableRelease:
1859 case S_Stop:
1860 case S_None:
1861 break;
1862 case S_Retain:
1863 llvm_unreachable("bottom-up pointer in retain state!");
1864 }
1865 }
1866
1867 // Check for possible direct uses.
1868 switch (Seq) {
1869 case S_Release:
1870 case S_MovableRelease:
1871 if (CanUse(Inst, Ptr, PA, Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001872 DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr
1873 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00001874 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohman5c70fad2012-03-23 17:47:54 +00001875 // If this is an invoke instruction, we're scanning it as part of
1876 // one of its successor blocks, since we can't insert code after it
1877 // in its own block, and we don't want to split critical edges.
1878 if (isa<InvokeInst>(Inst))
1879 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
1880 else
Francois Pichet4b9ab742012-03-24 01:36:37 +00001881 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohman817a7c62012-03-22 18:24:56 +00001882 S.SetSeq(S_Use);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001883 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
John McCall20182ac2013-03-22 21:38:36 +00001884 } else if (Seq == S_Release && IsUser(Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001885 DEBUG(dbgs() << "PreciseReleaseUse: Seq: " << Seq << "; " << *Ptr
1886 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00001887 // Non-movable releases depend on any possible objc pointer use.
1888 S.SetSeq(S_Stop);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001889 ANNOTATE_BOTTOMUP(Inst, Ptr, S_Release, S_Stop);
Dan Gohman817a7c62012-03-22 18:24:56 +00001890 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohman5c70fad2012-03-23 17:47:54 +00001891 // As above; handle invoke specially.
1892 if (isa<InvokeInst>(Inst))
1893 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
1894 else
Francois Pichet4b9ab742012-03-24 01:36:37 +00001895 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohman817a7c62012-03-22 18:24:56 +00001896 }
1897 break;
1898 case S_Stop:
Michael Gottesman81b1d432013-03-26 00:42:04 +00001899 if (CanUse(Inst, Ptr, PA, Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001900 DEBUG(dbgs() << "PreciseStopUse: Seq: " << Seq << "; " << *Ptr
1901 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00001902 S.SetSeq(S_Use);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001903 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
1904 }
Dan Gohman817a7c62012-03-22 18:24:56 +00001905 break;
1906 case S_CanRelease:
1907 case S_Use:
1908 case S_None:
1909 break;
1910 case S_Retain:
1911 llvm_unreachable("bottom-up pointer in retain state!");
1912 }
1913 }
1914
1915 return NestingDetected;
1916}
1917
1918bool
John McCalld935e9c2011-06-15 23:37:01 +00001919ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
1920 DenseMap<const BasicBlock *, BBState> &BBStates,
1921 MapVector<Value *, RRInfo> &Retains) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001922
1923 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitBottomUp ==\n");
1924
John McCalld935e9c2011-06-15 23:37:01 +00001925 bool NestingDetected = false;
1926 BBState &MyStates = BBStates[BB];
1927
1928 // Merge the states from each successor to compute the initial state
1929 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00001930 BBState::edge_iterator SI(MyStates.succ_begin()),
1931 SE(MyStates.succ_end());
1932 if (SI != SE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001933 const BasicBlock *Succ = *SI;
1934 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
1935 assert(I != BBStates.end());
1936 MyStates.InitFromSucc(I->second);
1937 ++SI;
1938 for (; SI != SE; ++SI) {
1939 Succ = *SI;
1940 I = BBStates.find(Succ);
1941 assert(I != BBStates.end());
1942 MyStates.MergeSucc(I->second);
1943 }
Michael Gottesman60f6b282013-03-29 05:13:07 +00001944 }
Michael Gottesmancd4de0f2013-03-26 00:42:09 +00001945
Michael Gottesman43e7e002013-04-03 22:41:59 +00001946 // If ARC Annotations are enabled, output the current state of pointers at the
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00001947 // bottom of the basic block.
Michael Gottesman43e7e002013-04-03 22:41:59 +00001948 ANNOTATE_BOTTOMUP_BBEND(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00001949
John McCalld935e9c2011-06-15 23:37:01 +00001950 // Visit all the instructions, bottom-up.
1951 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
1952 Instruction *Inst = llvm::prior(I);
Dan Gohman5c70fad2012-03-23 17:47:54 +00001953
1954 // Invoke instructions are visited as part of their successors (below).
1955 if (isa<InvokeInst>(Inst))
1956 continue;
1957
Michael Gottesman89279f82013-04-05 18:10:41 +00001958 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001959
Dan Gohman5c70fad2012-03-23 17:47:54 +00001960 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
1961 }
1962
Dan Gohmandae33492012-04-27 18:56:31 +00001963 // If there's a predecessor with an invoke, visit the invoke as if it were
1964 // part of this block, since we can't insert code after an invoke in its own
1965 // block, and we don't want to split critical edges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001966 for (BBState::edge_iterator PI(MyStates.pred_begin()),
1967 PE(MyStates.pred_end()); PI != PE; ++PI) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00001968 BasicBlock *Pred = *PI;
Dan Gohmandae33492012-04-27 18:56:31 +00001969 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
1970 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
Dan Gohman817a7c62012-03-22 18:24:56 +00001971 }
John McCalld935e9c2011-06-15 23:37:01 +00001972
Michael Gottesman43e7e002013-04-03 22:41:59 +00001973 // If ARC Annotations are enabled, output the current state of pointers at the
1974 // top of the basic block.
1975 ANNOTATE_BOTTOMUP_BBSTART(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00001976
Dan Gohman817a7c62012-03-22 18:24:56 +00001977 return NestingDetected;
1978}
John McCalld935e9c2011-06-15 23:37:01 +00001979
Dan Gohman817a7c62012-03-22 18:24:56 +00001980bool
1981ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
1982 DenseMap<Value *, RRInfo> &Releases,
1983 BBState &MyStates) {
1984 bool NestingDetected = false;
1985 InstructionClass Class = GetInstructionClass(Inst);
1986 const Value *Arg = 0;
John McCalld935e9c2011-06-15 23:37:01 +00001987
Dan Gohman817a7c62012-03-22 18:24:56 +00001988 switch (Class) {
1989 case IC_RetainBlock:
Michael Gottesman158fdf62013-03-28 20:11:19 +00001990 // In OptimizeIndividualCalls, we have strength reduced all optimizable
1991 // objc_retainBlocks to objc_retains. Thus at this point any
1992 // objc_retainBlocks that we see are not optimizable.
1993 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001994 case IC_Retain:
1995 case IC_RetainRV: {
1996 Arg = GetObjCArg(Inst);
1997
1998 PtrState &S = MyStates.getPtrTopDownState(Arg);
1999
2000 // Don't do retain+release tracking for IC_RetainRV, because it's
2001 // better to let it remain as the first instruction after a call.
2002 if (Class != IC_RetainRV) {
2003 // If we see two retains in a row on the same pointer. If so, make
John McCalld935e9c2011-06-15 23:37:01 +00002004 // a note, and we'll cicle back to revisit it after we've
Dan Gohman817a7c62012-03-22 18:24:56 +00002005 // hopefully eliminated the second retain, which may allow us to
2006 // eliminate the first retain too.
John McCalld935e9c2011-06-15 23:37:01 +00002007 // Theoretically we could implement removal of nested retain+release
2008 // pairs by making PtrState hold a stack of states, but this is
2009 // simple and avoids adding overhead for the non-nested case.
Dan Gohman817a7c62012-03-22 18:24:56 +00002010 if (S.GetSeq() == S_Retain)
John McCalld935e9c2011-06-15 23:37:01 +00002011 NestingDetected = true;
2012
Michael Gottesman81b1d432013-03-26 00:42:04 +00002013 ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_Retain);
Dan Gohman62079b42012-04-25 00:50:46 +00002014 S.ResetSequenceProgress(S_Retain);
Michael Gottesman07beea42013-03-23 05:31:01 +00002015 S.RRI.KnownSafe = S.HasKnownPositiveRefCount();
John McCalld935e9c2011-06-15 23:37:01 +00002016 S.RRI.Calls.insert(Inst);
John McCalld935e9c2011-06-15 23:37:01 +00002017 }
John McCalld935e9c2011-06-15 23:37:01 +00002018
Dan Gohmandf476e52012-09-04 23:16:20 +00002019 S.SetKnownPositiveRefCount();
Dan Gohmanf64ff8e2012-07-23 19:27:31 +00002020
2021 // A retain can be a potential use; procede to the generic checking
2022 // code below.
2023 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00002024 }
2025 case IC_Release: {
2026 Arg = GetObjCArg(Inst);
2027
2028 PtrState &S = MyStates.getPtrTopDownState(Arg);
Michael Gottesman764b1cf2013-03-23 05:46:19 +00002029 S.ClearKnownPositiveRefCount();
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002030
2031 Sequence OldSeq = S.GetSeq();
2032
2033 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2034
2035 switch (OldSeq) {
Dan Gohman817a7c62012-03-22 18:24:56 +00002036 case S_Retain:
2037 case S_CanRelease:
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002038 if (OldSeq == S_Retain || ReleaseMetadata != 0)
2039 S.RRI.ReverseInsertPts.clear();
Dan Gohman817a7c62012-03-22 18:24:56 +00002040 // FALL THROUGH
2041 case S_Use:
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002042 S.RRI.ReleaseMetadata = ReleaseMetadata;
Dan Gohman817a7c62012-03-22 18:24:56 +00002043 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2044 Releases[Inst] = S.RRI;
Michael Gottesman81b1d432013-03-26 00:42:04 +00002045 ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_None);
Dan Gohman817a7c62012-03-22 18:24:56 +00002046 S.ClearSequenceProgress();
2047 break;
2048 case S_None:
2049 break;
2050 case S_Stop:
2051 case S_Release:
2052 case S_MovableRelease:
2053 llvm_unreachable("top-down pointer in release state!");
2054 }
2055 break;
2056 }
2057 case IC_AutoreleasepoolPop:
2058 // Conservatively, clear MyStates for all known pointers.
2059 MyStates.clearTopDownPointers();
2060 return NestingDetected;
2061 case IC_AutoreleasepoolPush:
2062 case IC_None:
2063 // These are irrelevant.
2064 return NestingDetected;
2065 default:
2066 break;
2067 }
2068
2069 // Consider any other possible effects of this instruction on each
2070 // pointer being tracked.
2071 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
2072 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
2073 const Value *Ptr = MI->first;
2074 if (Ptr == Arg)
2075 continue; // Handled above.
2076 PtrState &S = MI->second;
2077 Sequence Seq = S.GetSeq();
2078
2079 // Check for possible releases.
2080 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Michael Gottesmanbab49e972013-04-05 18:26:08 +00002081 DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr
2082 << "\n");
Michael Gottesman764b1cf2013-03-23 05:46:19 +00002083 S.ClearKnownPositiveRefCount();
John McCalld935e9c2011-06-15 23:37:01 +00002084 switch (Seq) {
Dan Gohman817a7c62012-03-22 18:24:56 +00002085 case S_Retain:
2086 S.SetSeq(S_CanRelease);
Michael Gottesman81b1d432013-03-26 00:42:04 +00002087 ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_CanRelease);
Dan Gohman817a7c62012-03-22 18:24:56 +00002088 assert(S.RRI.ReverseInsertPts.empty());
2089 S.RRI.ReverseInsertPts.insert(Inst);
2090
2091 // One call can't cause a transition from S_Retain to S_CanRelease
2092 // and S_CanRelease to S_Use. If we've made the first transition,
2093 // we're done.
2094 continue;
John McCalld935e9c2011-06-15 23:37:01 +00002095 case S_Use:
Dan Gohman817a7c62012-03-22 18:24:56 +00002096 case S_CanRelease:
John McCalld935e9c2011-06-15 23:37:01 +00002097 case S_None:
2098 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00002099 case S_Stop:
2100 case S_Release:
2101 case S_MovableRelease:
2102 llvm_unreachable("top-down pointer in release state!");
John McCalld935e9c2011-06-15 23:37:01 +00002103 }
2104 }
Dan Gohman817a7c62012-03-22 18:24:56 +00002105
2106 // Check for possible direct uses.
2107 switch (Seq) {
2108 case S_CanRelease:
Michael Gottesman81b1d432013-03-26 00:42:04 +00002109 if (CanUse(Inst, Ptr, PA, Class)) {
Michael Gottesmanbab49e972013-04-05 18:26:08 +00002110 DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr
2111 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00002112 S.SetSeq(S_Use);
Michael Gottesman81b1d432013-03-26 00:42:04 +00002113 ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_Use);
2114 }
Dan Gohman817a7c62012-03-22 18:24:56 +00002115 break;
2116 case S_Retain:
2117 case S_Use:
2118 case S_None:
2119 break;
2120 case S_Stop:
2121 case S_Release:
2122 case S_MovableRelease:
2123 llvm_unreachable("top-down pointer in release state!");
2124 }
John McCalld935e9c2011-06-15 23:37:01 +00002125 }
2126
2127 return NestingDetected;
2128}
2129
2130bool
2131ObjCARCOpt::VisitTopDown(BasicBlock *BB,
2132 DenseMap<const BasicBlock *, BBState> &BBStates,
2133 DenseMap<Value *, RRInfo> &Releases) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002134 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitTopDown ==\n");
John McCalld935e9c2011-06-15 23:37:01 +00002135 bool NestingDetected = false;
2136 BBState &MyStates = BBStates[BB];
2137
2138 // Merge the states from each predecessor to compute the initial state
2139 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00002140 BBState::edge_iterator PI(MyStates.pred_begin()),
2141 PE(MyStates.pred_end());
2142 if (PI != PE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002143 const BasicBlock *Pred = *PI;
2144 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
2145 assert(I != BBStates.end());
2146 MyStates.InitFromPred(I->second);
2147 ++PI;
2148 for (; PI != PE; ++PI) {
2149 Pred = *PI;
2150 I = BBStates.find(Pred);
2151 assert(I != BBStates.end());
2152 MyStates.MergePred(I->second);
2153 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002154 }
John McCalld935e9c2011-06-15 23:37:01 +00002155
Michael Gottesman43e7e002013-04-03 22:41:59 +00002156 // If ARC Annotations are enabled, output the current state of pointers at the
2157 // top of the basic block.
2158 ANNOTATE_TOPDOWN_BBSTART(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002159
John McCalld935e9c2011-06-15 23:37:01 +00002160 // Visit all the instructions, top-down.
2161 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2162 Instruction *Inst = I;
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00002163
Michael Gottesman89279f82013-04-05 18:10:41 +00002164 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00002165
Dan Gohman817a7c62012-03-22 18:24:56 +00002166 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00002167 }
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002168
Michael Gottesman43e7e002013-04-03 22:41:59 +00002169 // If ARC Annotations are enabled, output the current state of pointers at the
2170 // bottom of the basic block.
2171 ANNOTATE_TOPDOWN_BBEND(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002172
John McCalld935e9c2011-06-15 23:37:01 +00002173 CheckForCFGHazards(BB, BBStates, MyStates);
2174 return NestingDetected;
2175}
2176
Dan Gohmana53a12c2011-12-12 19:42:25 +00002177static void
2178ComputePostOrders(Function &F,
2179 SmallVectorImpl<BasicBlock *> &PostOrder,
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002180 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
2181 unsigned NoObjCARCExceptionsMDKind,
2182 DenseMap<const BasicBlock *, BBState> &BBStates) {
Michael Gottesman97e3df02013-01-14 00:35:14 +00002183 /// The visited set, for doing DFS walks.
Dan Gohmana53a12c2011-12-12 19:42:25 +00002184 SmallPtrSet<BasicBlock *, 16> Visited;
2185
2186 // Do DFS, computing the PostOrder.
2187 SmallPtrSet<BasicBlock *, 16> OnStack;
2188 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002189
2190 // Functions always have exactly one entry block, and we don't have
2191 // any other block that we treat like an entry block.
Dan Gohmana53a12c2011-12-12 19:42:25 +00002192 BasicBlock *EntryBB = &F.getEntryBlock();
Dan Gohman41375a32012-05-08 23:39:44 +00002193 BBState &MyStates = BBStates[EntryBB];
2194 MyStates.SetAsEntry();
2195 TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
2196 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
Dan Gohmana53a12c2011-12-12 19:42:25 +00002197 Visited.insert(EntryBB);
2198 OnStack.insert(EntryBB);
2199 do {
2200 dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002201 BasicBlock *CurrBB = SuccStack.back().first;
2202 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
2203 succ_iterator SE(TI, false);
Dan Gohman41375a32012-05-08 23:39:44 +00002204
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002205 while (SuccStack.back().second != SE) {
2206 BasicBlock *SuccBB = *SuccStack.back().second++;
2207 if (Visited.insert(SuccBB)) {
Dan Gohman41375a32012-05-08 23:39:44 +00002208 TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
2209 SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002210 BBStates[CurrBB].addSucc(SuccBB);
Dan Gohman41375a32012-05-08 23:39:44 +00002211 BBState &SuccStates = BBStates[SuccBB];
2212 SuccStates.addPred(CurrBB);
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002213 OnStack.insert(SuccBB);
Dan Gohmana53a12c2011-12-12 19:42:25 +00002214 goto dfs_next_succ;
2215 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002216
2217 if (!OnStack.count(SuccBB)) {
2218 BBStates[CurrBB].addSucc(SuccBB);
2219 BBStates[SuccBB].addPred(CurrBB);
2220 }
Dan Gohmana53a12c2011-12-12 19:42:25 +00002221 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002222 OnStack.erase(CurrBB);
2223 PostOrder.push_back(CurrBB);
2224 SuccStack.pop_back();
Dan Gohmana53a12c2011-12-12 19:42:25 +00002225 } while (!SuccStack.empty());
2226
2227 Visited.clear();
2228
Dan Gohmana53a12c2011-12-12 19:42:25 +00002229 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002230 // Functions may have many exits, and there also blocks which we treat
2231 // as exits due to ignored edges.
2232 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
2233 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
2234 BasicBlock *ExitBB = I;
2235 BBState &MyStates = BBStates[ExitBB];
2236 if (!MyStates.isExit())
2237 continue;
2238
Dan Gohmandae33492012-04-27 18:56:31 +00002239 MyStates.SetAsExit();
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002240
2241 PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00002242 Visited.insert(ExitBB);
2243 while (!PredStack.empty()) {
2244 reverse_dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002245 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
2246 while (PredStack.back().second != PE) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00002247 BasicBlock *BB = *PredStack.back().second++;
Dan Gohmana53a12c2011-12-12 19:42:25 +00002248 if (Visited.insert(BB)) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002249 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00002250 goto reverse_dfs_next_succ;
2251 }
2252 }
2253 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
2254 }
2255 }
2256}
2257
Michael Gottesman97e3df02013-01-14 00:35:14 +00002258// Visit the function both top-down and bottom-up.
John McCalld935e9c2011-06-15 23:37:01 +00002259bool
2260ObjCARCOpt::Visit(Function &F,
2261 DenseMap<const BasicBlock *, BBState> &BBStates,
2262 MapVector<Value *, RRInfo> &Retains,
2263 DenseMap<Value *, RRInfo> &Releases) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00002264
2265 // Use reverse-postorder traversals, because we magically know that loops
2266 // will be well behaved, i.e. they won't repeatedly call retain on a single
2267 // pointer without doing a release. We can't use the ReversePostOrderTraversal
2268 // class here because we want the reverse-CFG postorder to consider each
2269 // function exit point, and we want to ignore selected cycle edges.
2270 SmallVector<BasicBlock *, 16> PostOrder;
2271 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002272 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
2273 NoObjCARCExceptionsMDKind,
2274 BBStates);
Dan Gohmana53a12c2011-12-12 19:42:25 +00002275
2276 // Use reverse-postorder on the reverse CFG for bottom-up.
John McCalld935e9c2011-06-15 23:37:01 +00002277 bool BottomUpNestingDetected = false;
Dan Gohmanc57b58c2011-08-18 21:27:42 +00002278 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
Dan Gohmana53a12c2011-12-12 19:42:25 +00002279 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
2280 I != E; ++I)
2281 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
John McCalld935e9c2011-06-15 23:37:01 +00002282
Dan Gohmana53a12c2011-12-12 19:42:25 +00002283 // Use reverse-postorder for top-down.
John McCalld935e9c2011-06-15 23:37:01 +00002284 bool TopDownNestingDetected = false;
Dan Gohmana53a12c2011-12-12 19:42:25 +00002285 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2286 PostOrder.rbegin(), E = PostOrder.rend();
2287 I != E; ++I)
2288 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
John McCalld935e9c2011-06-15 23:37:01 +00002289
2290 return TopDownNestingDetected && BottomUpNestingDetected;
2291}
2292
Michael Gottesman97e3df02013-01-14 00:35:14 +00002293/// Move the calls in RetainsToMove and ReleasesToMove.
John McCalld935e9c2011-06-15 23:37:01 +00002294void ObjCARCOpt::MoveCalls(Value *Arg,
2295 RRInfo &RetainsToMove,
2296 RRInfo &ReleasesToMove,
2297 MapVector<Value *, RRInfo> &Retains,
2298 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman6320f522011-07-22 22:29:21 +00002299 SmallVectorImpl<Instruction *> &DeadInsts,
Michael Gottesman89279f82013-04-05 18:10:41 +00002300 Module *M) {
Chris Lattner229907c2011-07-18 04:54:35 +00002301 Type *ArgTy = Arg->getType();
Dan Gohman6320f522011-07-22 22:29:21 +00002302 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
Michael Gottesman89279f82013-04-05 18:10:41 +00002303
2304 DEBUG(dbgs() << "== ObjCARCOpt::MoveCalls ==\n");
2305
John McCalld935e9c2011-06-15 23:37:01 +00002306 // Insert the new retain and release calls.
2307 for (SmallPtrSet<Instruction *, 2>::const_iterator
2308 PI = ReleasesToMove.ReverseInsertPts.begin(),
2309 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2310 Instruction *InsertPt = *PI;
2311 Value *MyArg = ArgTy == ParamTy ? Arg :
2312 new BitCastInst(Arg, ParamTy, "", InsertPt);
2313 CallInst *Call =
Michael Gottesmanba648592013-03-28 23:08:44 +00002314 CallInst::Create(getRetainCallee(M), MyArg, "", InsertPt);
John McCalld935e9c2011-06-15 23:37:01 +00002315 Call->setDoesNotThrow();
Michael Gottesmanba648592013-03-28 23:08:44 +00002316 Call->setTailCall();
Michael Gottesman60f6b282013-03-29 05:13:07 +00002317
Michael Gottesman89279f82013-04-05 18:10:41 +00002318 DEBUG(dbgs() << "Inserting new Release: " << *Call << "\n"
2319 "At insertion point: " << *InsertPt << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002320 }
2321 for (SmallPtrSet<Instruction *, 2>::const_iterator
2322 PI = RetainsToMove.ReverseInsertPts.begin(),
2323 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00002324 Instruction *InsertPt = *PI;
2325 Value *MyArg = ArgTy == ParamTy ? Arg :
2326 new BitCastInst(Arg, ParamTy, "", InsertPt);
2327 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
2328 "", InsertPt);
2329 // Attach a clang.imprecise_release metadata tag, if appropriate.
2330 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
2331 Call->setMetadata(ImpreciseReleaseMDKind, M);
2332 Call->setDoesNotThrow();
2333 if (ReleasesToMove.IsTailCallRelease)
2334 Call->setTailCall();
Michael Gottesmanc189a392013-01-09 19:23:24 +00002335
Michael Gottesman89279f82013-04-05 18:10:41 +00002336 DEBUG(dbgs() << "Inserting new Release: " << *Call << "\n"
2337 "At insertion point: " << *InsertPt << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002338 }
2339
2340 // Delete the original retain and release calls.
2341 for (SmallPtrSet<Instruction *, 2>::const_iterator
2342 AI = RetainsToMove.Calls.begin(),
2343 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
2344 Instruction *OrigRetain = *AI;
2345 Retains.blot(OrigRetain);
2346 DeadInsts.push_back(OrigRetain);
Michael Gottesman89279f82013-04-05 18:10:41 +00002347 DEBUG(dbgs() << "Deleting retain: " << *OrigRetain << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002348 }
2349 for (SmallPtrSet<Instruction *, 2>::const_iterator
2350 AI = ReleasesToMove.Calls.begin(),
2351 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
2352 Instruction *OrigRelease = *AI;
2353 Releases.erase(OrigRelease);
2354 DeadInsts.push_back(OrigRelease);
Michael Gottesman89279f82013-04-05 18:10:41 +00002355 DEBUG(dbgs() << "Deleting release: " << *OrigRelease << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002356 }
Michael Gottesman89279f82013-04-05 18:10:41 +00002357
John McCalld935e9c2011-06-15 23:37:01 +00002358}
2359
Michael Gottesman9de6f962013-01-22 21:49:00 +00002360bool
2361ObjCARCOpt::ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState>
2362 &BBStates,
2363 MapVector<Value *, RRInfo> &Retains,
2364 DenseMap<Value *, RRInfo> &Releases,
2365 Module *M,
2366 SmallVector<Instruction *, 4> &NewRetains,
2367 SmallVector<Instruction *, 4> &NewReleases,
2368 SmallVector<Instruction *, 8> &DeadInsts,
2369 RRInfo &RetainsToMove,
2370 RRInfo &ReleasesToMove,
2371 Value *Arg,
2372 bool KnownSafe,
2373 bool &AnyPairsCompletelyEliminated) {
2374 // If a pair happens in a region where it is known that the reference count
2375 // is already incremented, we can similarly ignore possible decrements.
2376 bool KnownSafeTD = true, KnownSafeBU = true;
2377
2378 // Connect the dots between the top-down-collected RetainsToMove and
2379 // bottom-up-collected ReleasesToMove to form sets of related calls.
2380 // This is an iterative process so that we connect multiple releases
2381 // to multiple retains if needed.
2382 unsigned OldDelta = 0;
2383 unsigned NewDelta = 0;
2384 unsigned OldCount = 0;
2385 unsigned NewCount = 0;
2386 bool FirstRelease = true;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002387 for (;;) {
2388 for (SmallVectorImpl<Instruction *>::const_iterator
2389 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
2390 Instruction *NewRetain = *NI;
2391 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
2392 assert(It != Retains.end());
2393 const RRInfo &NewRetainRRI = It->second;
2394 KnownSafeTD &= NewRetainRRI.KnownSafe;
2395 for (SmallPtrSet<Instruction *, 2>::const_iterator
2396 LI = NewRetainRRI.Calls.begin(),
2397 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
2398 Instruction *NewRetainRelease = *LI;
2399 DenseMap<Value *, RRInfo>::const_iterator Jt =
2400 Releases.find(NewRetainRelease);
2401 if (Jt == Releases.end())
2402 return false;
2403 const RRInfo &NewRetainReleaseRRI = Jt->second;
2404 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
2405 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
2406 OldDelta -=
2407 BBStates[NewRetainRelease->getParent()].GetAllPathCount();
2408
2409 // Merge the ReleaseMetadata and IsTailCallRelease values.
2410 if (FirstRelease) {
2411 ReleasesToMove.ReleaseMetadata =
2412 NewRetainReleaseRRI.ReleaseMetadata;
2413 ReleasesToMove.IsTailCallRelease =
2414 NewRetainReleaseRRI.IsTailCallRelease;
2415 FirstRelease = false;
2416 } else {
2417 if (ReleasesToMove.ReleaseMetadata !=
2418 NewRetainReleaseRRI.ReleaseMetadata)
2419 ReleasesToMove.ReleaseMetadata = 0;
2420 if (ReleasesToMove.IsTailCallRelease !=
2421 NewRetainReleaseRRI.IsTailCallRelease)
2422 ReleasesToMove.IsTailCallRelease = false;
2423 }
2424
2425 // Collect the optimal insertion points.
2426 if (!KnownSafe)
2427 for (SmallPtrSet<Instruction *, 2>::const_iterator
2428 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
2429 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
2430 RI != RE; ++RI) {
2431 Instruction *RIP = *RI;
2432 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
2433 NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
2434 }
2435 NewReleases.push_back(NewRetainRelease);
2436 }
2437 }
2438 }
2439 NewRetains.clear();
2440 if (NewReleases.empty()) break;
2441
2442 // Back the other way.
2443 for (SmallVectorImpl<Instruction *>::const_iterator
2444 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
2445 Instruction *NewRelease = *NI;
2446 DenseMap<Value *, RRInfo>::const_iterator It =
2447 Releases.find(NewRelease);
2448 assert(It != Releases.end());
2449 const RRInfo &NewReleaseRRI = It->second;
2450 KnownSafeBU &= NewReleaseRRI.KnownSafe;
2451 for (SmallPtrSet<Instruction *, 2>::const_iterator
2452 LI = NewReleaseRRI.Calls.begin(),
2453 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
2454 Instruction *NewReleaseRetain = *LI;
2455 MapVector<Value *, RRInfo>::const_iterator Jt =
2456 Retains.find(NewReleaseRetain);
2457 if (Jt == Retains.end())
2458 return false;
2459 const RRInfo &NewReleaseRetainRRI = Jt->second;
2460 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
2461 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
2462 unsigned PathCount =
2463 BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
2464 OldDelta += PathCount;
2465 OldCount += PathCount;
2466
Michael Gottesman9de6f962013-01-22 21:49:00 +00002467 // Collect the optimal insertion points.
2468 if (!KnownSafe)
2469 for (SmallPtrSet<Instruction *, 2>::const_iterator
2470 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
2471 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
2472 RI != RE; ++RI) {
2473 Instruction *RIP = *RI;
2474 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
2475 PathCount = BBStates[RIP->getParent()].GetAllPathCount();
2476 NewDelta += PathCount;
2477 NewCount += PathCount;
2478 }
2479 }
2480 NewRetains.push_back(NewReleaseRetain);
2481 }
2482 }
2483 }
2484 NewReleases.clear();
2485 if (NewRetains.empty()) break;
2486 }
2487
2488 // If the pointer is known incremented or nested, we can safely delete the
2489 // pair regardless of what's between them.
2490 if (KnownSafeTD || KnownSafeBU) {
2491 RetainsToMove.ReverseInsertPts.clear();
2492 ReleasesToMove.ReverseInsertPts.clear();
2493 NewCount = 0;
2494 } else {
2495 // Determine whether the new insertion points we computed preserve the
2496 // balance of retain and release calls through the program.
2497 // TODO: If the fully aggressive solution isn't valid, try to find a
2498 // less aggressive solution which is.
2499 if (NewDelta != 0)
2500 return false;
2501 }
2502
2503 // Determine whether the original call points are balanced in the retain and
2504 // release calls through the program. If not, conservatively don't touch
2505 // them.
2506 // TODO: It's theoretically possible to do code motion in this case, as
2507 // long as the existing imbalances are maintained.
2508 if (OldDelta != 0)
2509 return false;
2510
2511 Changed = true;
2512 assert(OldCount != 0 && "Unreachable code?");
2513 NumRRs += OldCount - NewCount;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002514 // Set to true if we completely removed any RR pairs.
Michael Gottesman8b5515f2013-01-22 21:53:43 +00002515 AnyPairsCompletelyEliminated = NewCount == 0;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002516
2517 // We can move calls!
2518 return true;
2519}
2520
Michael Gottesman97e3df02013-01-14 00:35:14 +00002521/// Identify pairings between the retains and releases, and delete and/or move
2522/// them.
John McCalld935e9c2011-06-15 23:37:01 +00002523bool
2524ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
2525 &BBStates,
2526 MapVector<Value *, RRInfo> &Retains,
Dan Gohman6320f522011-07-22 22:29:21 +00002527 DenseMap<Value *, RRInfo> &Releases,
2528 Module *M) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002529 DEBUG(dbgs() << "\n== ObjCARCOpt::PerformCodePlacement ==\n");
2530
John McCalld935e9c2011-06-15 23:37:01 +00002531 bool AnyPairsCompletelyEliminated = false;
2532 RRInfo RetainsToMove;
2533 RRInfo ReleasesToMove;
2534 SmallVector<Instruction *, 4> NewRetains;
2535 SmallVector<Instruction *, 4> NewReleases;
2536 SmallVector<Instruction *, 8> DeadInsts;
2537
Dan Gohman670f9372012-04-13 18:57:48 +00002538 // Visit each retain.
John McCalld935e9c2011-06-15 23:37:01 +00002539 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
Dan Gohman2053a5d2011-09-29 22:25:23 +00002540 E = Retains.end(); I != E; ++I) {
2541 Value *V = I->first;
John McCalld935e9c2011-06-15 23:37:01 +00002542 if (!V) continue; // blotted
2543
2544 Instruction *Retain = cast<Instruction>(V);
Michael Gottesmanc189a392013-01-09 19:23:24 +00002545
Michael Gottesman89279f82013-04-05 18:10:41 +00002546 DEBUG(dbgs() << "Visiting: " << *Retain << "\n");
Michael Gottesmanc189a392013-01-09 19:23:24 +00002547
John McCalld935e9c2011-06-15 23:37:01 +00002548 Value *Arg = GetObjCArg(Retain);
2549
Dan Gohman728db492012-01-13 00:39:07 +00002550 // If the object being released is in static or stack storage, we know it's
John McCalld935e9c2011-06-15 23:37:01 +00002551 // not being managed by ObjC reference counting, so we can delete pairs
2552 // regardless of what possible decrements or uses lie between them.
Dan Gohman728db492012-01-13 00:39:07 +00002553 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
Dan Gohman41375a32012-05-08 23:39:44 +00002554
Dan Gohman56e1cef2011-08-22 17:29:11 +00002555 // A constant pointer can't be pointing to an object on the heap. It may
2556 // be reference-counted, but it won't be deleted.
2557 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
2558 if (const GlobalVariable *GV =
2559 dyn_cast<GlobalVariable>(
2560 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
2561 if (GV->isConstant())
2562 KnownSafe = true;
2563
John McCalld935e9c2011-06-15 23:37:01 +00002564 // Connect the dots between the top-down-collected RetainsToMove and
2565 // bottom-up-collected ReleasesToMove to form sets of related calls.
John McCalld935e9c2011-06-15 23:37:01 +00002566 NewRetains.push_back(Retain);
Michael Gottesman9de6f962013-01-22 21:49:00 +00002567 bool PerformMoveCalls =
2568 ConnectTDBUTraversals(BBStates, Retains, Releases, M, NewRetains,
2569 NewReleases, DeadInsts, RetainsToMove,
2570 ReleasesToMove, Arg, KnownSafe,
2571 AnyPairsCompletelyEliminated);
John McCalld935e9c2011-06-15 23:37:01 +00002572
Michael Gottesman81b1d432013-03-26 00:42:04 +00002573#ifdef ARC_ANNOTATIONS
2574 // Do not move calls if ARC annotations are requested. If we were to move
2575 // calls in this case, we would not be able
2576 PerformMoveCalls = PerformMoveCalls && !EnableARCAnnotations;
2577#endif // ARC_ANNOTATIONS
2578
Michael Gottesman9de6f962013-01-22 21:49:00 +00002579 if (PerformMoveCalls) {
2580 // Ok, everything checks out and we're all set. Let's move/delete some
2581 // code!
2582 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
2583 Retains, Releases, DeadInsts, M);
John McCalld935e9c2011-06-15 23:37:01 +00002584 }
2585
Michael Gottesman9de6f962013-01-22 21:49:00 +00002586 // Clean up state for next retain.
John McCalld935e9c2011-06-15 23:37:01 +00002587 NewReleases.clear();
2588 NewRetains.clear();
2589 RetainsToMove.clear();
2590 ReleasesToMove.clear();
2591 }
2592
2593 // Now that we're done moving everything, we can delete the newly dead
2594 // instructions, as we no longer need them as insert points.
2595 while (!DeadInsts.empty())
2596 EraseInstruction(DeadInsts.pop_back_val());
2597
2598 return AnyPairsCompletelyEliminated;
2599}
2600
Michael Gottesman97e3df02013-01-14 00:35:14 +00002601/// Weak pointer optimizations.
John McCalld935e9c2011-06-15 23:37:01 +00002602void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002603 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeWeakCalls ==\n");
2604
John McCalld935e9c2011-06-15 23:37:01 +00002605 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
2606 // itself because it uses AliasAnalysis and we need to do provenance
2607 // queries instead.
2608 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2609 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +00002610
Michael Gottesman89279f82013-04-05 18:10:41 +00002611 DEBUG(dbgs() << "Visiting: " << *Inst << "\n");
Michael Gottesman3f146e22013-01-01 16:05:48 +00002612
John McCalld935e9c2011-06-15 23:37:01 +00002613 InstructionClass Class = GetBasicInstructionClass(Inst);
2614 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
2615 continue;
2616
2617 // Delete objc_loadWeak calls with no users.
2618 if (Class == IC_LoadWeak && Inst->use_empty()) {
2619 Inst->eraseFromParent();
2620 continue;
2621 }
2622
2623 // TODO: For now, just look for an earlier available version of this value
2624 // within the same block. Theoretically, we could do memdep-style non-local
2625 // analysis too, but that would want caching. A better approach would be to
2626 // use the technique that EarlyCSE uses.
2627 inst_iterator Current = llvm::prior(I);
2628 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
2629 for (BasicBlock::iterator B = CurrentBB->begin(),
2630 J = Current.getInstructionIterator();
2631 J != B; --J) {
2632 Instruction *EarlierInst = &*llvm::prior(J);
2633 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
2634 switch (EarlierClass) {
2635 case IC_LoadWeak:
2636 case IC_LoadWeakRetained: {
2637 // If this is loading from the same pointer, replace this load's value
2638 // with that one.
2639 CallInst *Call = cast<CallInst>(Inst);
2640 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2641 Value *Arg = Call->getArgOperand(0);
2642 Value *EarlierArg = EarlierCall->getArgOperand(0);
2643 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2644 case AliasAnalysis::MustAlias:
2645 Changed = true;
2646 // If the load has a builtin retain, insert a plain retain for it.
2647 if (Class == IC_LoadWeakRetained) {
2648 CallInst *CI =
2649 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
2650 "", Call);
2651 CI->setTailCall();
2652 }
2653 // Zap the fully redundant load.
2654 Call->replaceAllUsesWith(EarlierCall);
2655 Call->eraseFromParent();
2656 goto clobbered;
2657 case AliasAnalysis::MayAlias:
2658 case AliasAnalysis::PartialAlias:
2659 goto clobbered;
2660 case AliasAnalysis::NoAlias:
2661 break;
2662 }
2663 break;
2664 }
2665 case IC_StoreWeak:
2666 case IC_InitWeak: {
2667 // If this is storing to the same pointer and has the same size etc.
2668 // replace this load's value with the stored value.
2669 CallInst *Call = cast<CallInst>(Inst);
2670 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2671 Value *Arg = Call->getArgOperand(0);
2672 Value *EarlierArg = EarlierCall->getArgOperand(0);
2673 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2674 case AliasAnalysis::MustAlias:
2675 Changed = true;
2676 // If the load has a builtin retain, insert a plain retain for it.
2677 if (Class == IC_LoadWeakRetained) {
2678 CallInst *CI =
2679 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
2680 "", Call);
2681 CI->setTailCall();
2682 }
2683 // Zap the fully redundant load.
2684 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
2685 Call->eraseFromParent();
2686 goto clobbered;
2687 case AliasAnalysis::MayAlias:
2688 case AliasAnalysis::PartialAlias:
2689 goto clobbered;
2690 case AliasAnalysis::NoAlias:
2691 break;
2692 }
2693 break;
2694 }
2695 case IC_MoveWeak:
2696 case IC_CopyWeak:
2697 // TOOD: Grab the copied value.
2698 goto clobbered;
2699 case IC_AutoreleasepoolPush:
2700 case IC_None:
John McCall20182ac2013-03-22 21:38:36 +00002701 case IC_IntrinsicUser:
John McCalld935e9c2011-06-15 23:37:01 +00002702 case IC_User:
2703 // Weak pointers are only modified through the weak entry points
2704 // (and arbitrary calls, which could call the weak entry points).
2705 break;
2706 default:
2707 // Anything else could modify the weak pointer.
2708 goto clobbered;
2709 }
2710 }
2711 clobbered:;
2712 }
2713
2714 // Then, for each destroyWeak with an alloca operand, check to see if
2715 // the alloca and all its users can be zapped.
2716 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2717 Instruction *Inst = &*I++;
2718 InstructionClass Class = GetBasicInstructionClass(Inst);
2719 if (Class != IC_DestroyWeak)
2720 continue;
2721
2722 CallInst *Call = cast<CallInst>(Inst);
2723 Value *Arg = Call->getArgOperand(0);
2724 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
2725 for (Value::use_iterator UI = Alloca->use_begin(),
2726 UE = Alloca->use_end(); UI != UE; ++UI) {
Dan Gohmandae33492012-04-27 18:56:31 +00002727 const Instruction *UserInst = cast<Instruction>(*UI);
John McCalld935e9c2011-06-15 23:37:01 +00002728 switch (GetBasicInstructionClass(UserInst)) {
2729 case IC_InitWeak:
2730 case IC_StoreWeak:
2731 case IC_DestroyWeak:
2732 continue;
2733 default:
2734 goto done;
2735 }
2736 }
2737 Changed = true;
2738 for (Value::use_iterator UI = Alloca->use_begin(),
2739 UE = Alloca->use_end(); UI != UE; ) {
2740 CallInst *UserInst = cast<CallInst>(*UI++);
Dan Gohman14862c32012-05-18 22:17:29 +00002741 switch (GetBasicInstructionClass(UserInst)) {
2742 case IC_InitWeak:
2743 case IC_StoreWeak:
2744 // These functions return their second argument.
2745 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
2746 break;
2747 case IC_DestroyWeak:
2748 // No return value.
2749 break;
2750 default:
Dan Gohman9c97eea02012-05-21 17:41:28 +00002751 llvm_unreachable("alloca really is used!");
Dan Gohman14862c32012-05-18 22:17:29 +00002752 }
John McCalld935e9c2011-06-15 23:37:01 +00002753 UserInst->eraseFromParent();
2754 }
2755 Alloca->eraseFromParent();
2756 done:;
2757 }
2758 }
2759}
2760
Michael Gottesman97e3df02013-01-14 00:35:14 +00002761/// Identify program paths which execute sequences of retains and releases which
2762/// can be eliminated.
John McCalld935e9c2011-06-15 23:37:01 +00002763bool ObjCARCOpt::OptimizeSequences(Function &F) {
2764 /// Releases, Retains - These are used to store the results of the main flow
2765 /// analysis. These use Value* as the key instead of Instruction* so that the
2766 /// map stays valid when we get around to rewriting code and calls get
2767 /// replaced by arguments.
2768 DenseMap<Value *, RRInfo> Releases;
2769 MapVector<Value *, RRInfo> Retains;
2770
Michael Gottesman97e3df02013-01-14 00:35:14 +00002771 /// This is used during the traversal of the function to track the
John McCalld935e9c2011-06-15 23:37:01 +00002772 /// states for each identified object at each block.
2773 DenseMap<const BasicBlock *, BBState> BBStates;
2774
2775 // Analyze the CFG of the function, and all instructions.
2776 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
2777
2778 // Transform.
Dan Gohman6320f522011-07-22 22:29:21 +00002779 return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) &&
2780 NestingDetected;
John McCalld935e9c2011-06-15 23:37:01 +00002781}
2782
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002783/// Check if there is a dependent call earlier that does not have anything in
2784/// between the Retain and the call that can affect the reference count of their
2785/// shared pointer argument. Note that Retain need not be in BB.
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002786static bool
2787HasSafePathToPredecessorCall(const Value *Arg, Instruction *Retain,
2788 SmallPtrSet<Instruction *, 4> &DepInsts,
2789 SmallPtrSet<const BasicBlock *, 4> &Visited,
2790 ProvenanceAnalysis &PA) {
2791 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
2792 DepInsts, Visited, PA);
2793 if (DepInsts.size() != 1)
2794 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002795
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002796 CallInst *Call =
2797 dyn_cast_or_null<CallInst>(*DepInsts.begin());
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002798
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002799 // Check that the pointer is the return value of the call.
2800 if (!Call || Arg != Call)
2801 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002802
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002803 // Check that the call is a regular call.
2804 InstructionClass Class = GetBasicInstructionClass(Call);
2805 if (Class != IC_CallOrUser && Class != IC_Call)
2806 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002807
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002808 return true;
2809}
2810
Michael Gottesman6908db12013-04-03 23:16:05 +00002811/// Find a dependent retain that precedes the given autorelease for which there
2812/// is nothing in between the two instructions that can affect the ref count of
2813/// Arg.
2814static CallInst *
2815FindPredecessorRetainWithSafePath(const Value *Arg, BasicBlock *BB,
2816 Instruction *Autorelease,
2817 SmallPtrSet<Instruction *, 4> &DepInsts,
2818 SmallPtrSet<const BasicBlock *, 4> &Visited,
2819 ProvenanceAnalysis &PA) {
2820 FindDependencies(CanChangeRetainCount, Arg,
2821 BB, Autorelease, DepInsts, Visited, PA);
2822 if (DepInsts.size() != 1)
2823 return 0;
2824
2825 CallInst *Retain =
2826 dyn_cast_or_null<CallInst>(*DepInsts.begin());
2827
2828 // Check that we found a retain with the same argument.
2829 if (!Retain ||
2830 !IsRetain(GetBasicInstructionClass(Retain)) ||
2831 GetObjCArg(Retain) != Arg) {
2832 return 0;
2833 }
2834
2835 return Retain;
2836}
2837
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002838/// Look for an ``autorelease'' instruction dependent on Arg such that there are
2839/// no instructions dependent on Arg that need a positive ref count in between
2840/// the autorelease and the ret.
2841static CallInst *
2842FindPredecessorAutoreleaseWithSafePath(const Value *Arg, BasicBlock *BB,
2843 ReturnInst *Ret,
2844 SmallPtrSet<Instruction *, 4> &DepInsts,
2845 SmallPtrSet<const BasicBlock *, 4> &V,
2846 ProvenanceAnalysis &PA) {
2847 FindDependencies(NeedsPositiveRetainCount, Arg,
2848 BB, Ret, DepInsts, V, PA);
2849 if (DepInsts.size() != 1)
2850 return 0;
2851
2852 CallInst *Autorelease =
2853 dyn_cast_or_null<CallInst>(*DepInsts.begin());
2854 if (!Autorelease)
2855 return 0;
2856 InstructionClass AutoreleaseClass = GetBasicInstructionClass(Autorelease);
2857 if (!IsAutorelease(AutoreleaseClass))
2858 return 0;
2859 if (GetObjCArg(Autorelease) != Arg)
2860 return 0;
2861
2862 return Autorelease;
2863}
2864
Michael Gottesman97e3df02013-01-14 00:35:14 +00002865/// Look for this pattern:
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00002866/// \code
John McCalld935e9c2011-06-15 23:37:01 +00002867/// %call = call i8* @something(...)
2868/// %2 = call i8* @objc_retain(i8* %call)
2869/// %3 = call i8* @objc_autorelease(i8* %2)
2870/// ret i8* %3
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00002871/// \endcode
John McCalld935e9c2011-06-15 23:37:01 +00002872/// And delete the retain and autorelease.
John McCalld935e9c2011-06-15 23:37:01 +00002873void ObjCARCOpt::OptimizeReturns(Function &F) {
2874 if (!F.getReturnType()->isPointerTy())
2875 return;
Michael Gottesman89279f82013-04-05 18:10:41 +00002876
2877 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeReturns ==\n");
2878
John McCalld935e9c2011-06-15 23:37:01 +00002879 SmallPtrSet<Instruction *, 4> DependingInstructions;
2880 SmallPtrSet<const BasicBlock *, 4> Visited;
2881 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
2882 BasicBlock *BB = FI;
2883 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
Michael Gottesman3f146e22013-01-01 16:05:48 +00002884
Michael Gottesman89279f82013-04-05 18:10:41 +00002885 DEBUG(dbgs() << "Visiting: " << *Ret << "\n");
Michael Gottesman3f146e22013-01-01 16:05:48 +00002886
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002887 if (!Ret)
2888 continue;
2889
John McCalld935e9c2011-06-15 23:37:01 +00002890 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002891
2892 // Look for an ``autorelease'' instruction that is a predecssor of Ret and
2893 // dependent on Arg such that there are no instructions dependent on Arg
2894 // that need a positive ref count in between the autorelease and Ret.
2895 CallInst *Autorelease =
2896 FindPredecessorAutoreleaseWithSafePath(Arg, BB, Ret,
2897 DependingInstructions, Visited,
2898 PA);
2899 if (Autorelease) {
John McCalld935e9c2011-06-15 23:37:01 +00002900 DependingInstructions.clear();
2901 Visited.clear();
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002902
2903 CallInst *Retain =
2904 FindPredecessorRetainWithSafePath(Arg, BB, Autorelease,
2905 DependingInstructions, Visited, PA);
2906 if (Retain) {
John McCalld935e9c2011-06-15 23:37:01 +00002907 DependingInstructions.clear();
2908 Visited.clear();
Michael Gottesman6908db12013-04-03 23:16:05 +00002909
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002910 // Check that there is nothing that can affect the reference count
2911 // between the retain and the call. Note that Retain need not be in BB.
2912 if (HasSafePathToPredecessorCall(Arg, Retain, DependingInstructions,
2913 Visited, PA)) {
John McCalld935e9c2011-06-15 23:37:01 +00002914 // If so, we can zap the retain and autorelease.
2915 Changed = true;
2916 ++NumRets;
Michael Gottesman89279f82013-04-05 18:10:41 +00002917 DEBUG(dbgs() << "Erasing: " << *Retain << "\nErasing: "
Michael Gottesmand61a3b22013-01-07 00:04:56 +00002918 << *Autorelease << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002919 EraseInstruction(Retain);
2920 EraseInstruction(Autorelease);
2921 }
2922 }
2923 }
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002924
John McCalld935e9c2011-06-15 23:37:01 +00002925 DependingInstructions.clear();
2926 Visited.clear();
2927 }
2928}
2929
2930bool ObjCARCOpt::doInitialization(Module &M) {
2931 if (!EnableARCOpts)
2932 return false;
2933
Dan Gohman670f9372012-04-13 18:57:48 +00002934 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanceaac7c2011-06-20 23:20:43 +00002935 Run = ModuleHasARC(M);
2936 if (!Run)
2937 return false;
2938
John McCalld935e9c2011-06-15 23:37:01 +00002939 // Identify the imprecise release metadata kind.
2940 ImpreciseReleaseMDKind =
2941 M.getContext().getMDKindID("clang.imprecise_release");
Dan Gohmana7107f92011-10-17 22:53:25 +00002942 CopyOnEscapeMDKind =
2943 M.getContext().getMDKindID("clang.arc.copy_on_escape");
Dan Gohman0155f302012-02-17 18:59:53 +00002944 NoObjCARCExceptionsMDKind =
2945 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
Michael Gottesman81b1d432013-03-26 00:42:04 +00002946#ifdef ARC_ANNOTATIONS
2947 ARCAnnotationBottomUpMDKind =
2948 M.getContext().getMDKindID("llvm.arc.annotation.bottomup");
2949 ARCAnnotationTopDownMDKind =
2950 M.getContext().getMDKindID("llvm.arc.annotation.topdown");
2951 ARCAnnotationProvenanceSourceMDKind =
2952 M.getContext().getMDKindID("llvm.arc.annotation.provenancesource");
2953#endif // ARC_ANNOTATIONS
John McCalld935e9c2011-06-15 23:37:01 +00002954
John McCalld935e9c2011-06-15 23:37:01 +00002955 // Intuitively, objc_retain and others are nocapture, however in practice
2956 // they are not, because they return their argument value. And objc_release
Dan Gohmandae33492012-04-27 18:56:31 +00002957 // calls finalizers which can have arbitrary side effects.
John McCalld935e9c2011-06-15 23:37:01 +00002958
2959 // These are initialized lazily.
2960 RetainRVCallee = 0;
2961 AutoreleaseRVCallee = 0;
2962 ReleaseCallee = 0;
2963 RetainCallee = 0;
Dan Gohman6320f522011-07-22 22:29:21 +00002964 RetainBlockCallee = 0;
John McCalld935e9c2011-06-15 23:37:01 +00002965 AutoreleaseCallee = 0;
2966
2967 return false;
2968}
2969
2970bool ObjCARCOpt::runOnFunction(Function &F) {
2971 if (!EnableARCOpts)
2972 return false;
2973
Dan Gohmanceaac7c2011-06-20 23:20:43 +00002974 // If nothing in the Module uses ARC, don't do anything.
2975 if (!Run)
2976 return false;
2977
John McCalld935e9c2011-06-15 23:37:01 +00002978 Changed = false;
2979
Michael Gottesman89279f82013-04-05 18:10:41 +00002980 DEBUG(dbgs() << "<<< ObjCARCOpt: Visiting Function: " << F.getName() << " >>>"
2981 "\n");
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00002982
John McCalld935e9c2011-06-15 23:37:01 +00002983 PA.setAA(&getAnalysis<AliasAnalysis>());
2984
2985 // This pass performs several distinct transformations. As a compile-time aid
2986 // when compiling code that isn't ObjC, skip these if the relevant ObjC
2987 // library functions aren't declared.
2988
2989 // Preliminary optimizations. This also computs UsedInThisFunction.
2990 OptimizeIndividualCalls(F);
2991
2992 // Optimizations for weak pointers.
2993 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
2994 (1 << IC_LoadWeakRetained) |
2995 (1 << IC_StoreWeak) |
2996 (1 << IC_InitWeak) |
2997 (1 << IC_CopyWeak) |
2998 (1 << IC_MoveWeak) |
2999 (1 << IC_DestroyWeak)))
3000 OptimizeWeakCalls(F);
3001
3002 // Optimizations for retain+release pairs.
3003 if (UsedInThisFunction & ((1 << IC_Retain) |
3004 (1 << IC_RetainRV) |
3005 (1 << IC_RetainBlock)))
3006 if (UsedInThisFunction & (1 << IC_Release))
3007 // Run OptimizeSequences until it either stops making changes or
3008 // no retain+release pair nesting is detected.
3009 while (OptimizeSequences(F)) {}
3010
3011 // Optimizations if objc_autorelease is used.
Dan Gohman41375a32012-05-08 23:39:44 +00003012 if (UsedInThisFunction & ((1 << IC_Autorelease) |
3013 (1 << IC_AutoreleaseRV)))
John McCalld935e9c2011-06-15 23:37:01 +00003014 OptimizeReturns(F);
3015
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00003016 DEBUG(dbgs() << "\n");
3017
John McCalld935e9c2011-06-15 23:37:01 +00003018 return Changed;
3019}
3020
3021void ObjCARCOpt::releaseMemory() {
3022 PA.clear();
3023}
3024
Michael Gottesman97e3df02013-01-14 00:35:14 +00003025/// @}
3026///