blob: a045582d53257d8a8c5bd4f5ba262cb8d6391c3a [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
Bob Wilson798a7702013-04-09 22:15:51 +0000376 /// reverse sequence.
John McCalld935e9c2011-06-15 23:37:01 +0000377 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 Gottesman79249972013-04-05 23:46:45 +0000411
Michael Gottesman1d8d2572013-04-05 22:54:28 +0000412 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
Bob Wilson798a7702013-04-09 22:15:51 +0000433 /// True if we've seen an opportunity for partial RR elimination, such as
Michael Gottesman97e3df02013-01-14 00:35:14 +0000434 /// 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");
Michael Gottesman79249972013-04-05 23:46:45 +0000463 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 Gottesman01338a42013-04-20 23:36:57 +0000475 DEBUG(dbgs() << "Resetting sequence progress.\n");
Michael Gottesman89279f82013-04-05 18:10:41 +0000476 SetSeq(NewSeq);
Dan Gohman62079b42012-04-25 00:50:46 +0000477 Partial = false;
John McCalld935e9c2011-06-15 23:37:01 +0000478 RRI.clear();
479 }
480
481 void Merge(const PtrState &Other, bool TopDown);
482 };
483}
484
485void
486PtrState::Merge(const PtrState &Other, bool TopDown) {
487 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
Dan Gohman62079b42012-04-25 00:50:46 +0000488 KnownPositiveRefCount = KnownPositiveRefCount && Other.KnownPositiveRefCount;
Michael Gottesman60f6b282013-03-29 05:13:07 +0000489
Dan Gohman1736c142011-10-17 18:48:25 +0000490 // If we're not in a sequence (anymore), drop all associated state.
John McCalld935e9c2011-06-15 23:37:01 +0000491 if (Seq == S_None) {
Dan Gohman62079b42012-04-25 00:50:46 +0000492 Partial = false;
John McCalld935e9c2011-06-15 23:37:01 +0000493 RRI.clear();
Dan Gohman62079b42012-04-25 00:50:46 +0000494 } else if (Partial || Other.Partial) {
Dan Gohman1736c142011-10-17 18:48:25 +0000495 // If we're doing a merge on a path that's previously seen a partial
496 // merge, conservatively drop the sequence, to avoid doing partial
497 // RR elimination. If the branch predicates for the two merge differ,
498 // mixing them is unsafe.
Dan Gohman62079b42012-04-25 00:50:46 +0000499 ClearSequenceProgress();
John McCalld935e9c2011-06-15 23:37:01 +0000500 } else {
501 // Conservatively merge the ReleaseMetadata information.
502 if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
503 RRI.ReleaseMetadata = 0;
504
Dan Gohmanb3894012011-08-19 00:26:36 +0000505 RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
Dan Gohman41375a32012-05-08 23:39:44 +0000506 RRI.IsTailCallRelease = RRI.IsTailCallRelease &&
507 Other.RRI.IsTailCallRelease;
John McCalld935e9c2011-06-15 23:37:01 +0000508 RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
Dan Gohman1736c142011-10-17 18:48:25 +0000509
510 // Merge the insert point sets. If there are any differences,
511 // that makes this a partial merge.
Dan Gohman41375a32012-05-08 23:39:44 +0000512 Partial = RRI.ReverseInsertPts.size() != Other.RRI.ReverseInsertPts.size();
Dan Gohman1736c142011-10-17 18:48:25 +0000513 for (SmallPtrSet<Instruction *, 2>::const_iterator
514 I = Other.RRI.ReverseInsertPts.begin(),
515 E = Other.RRI.ReverseInsertPts.end(); I != E; ++I)
Dan Gohman62079b42012-04-25 00:50:46 +0000516 Partial |= RRI.ReverseInsertPts.insert(*I);
John McCalld935e9c2011-06-15 23:37:01 +0000517 }
518}
519
520namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000521 /// \brief Per-BasicBlock state.
John McCalld935e9c2011-06-15 23:37:01 +0000522 class BBState {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000523 /// The number of unique control paths from the entry which can reach this
524 /// block.
John McCalld935e9c2011-06-15 23:37:01 +0000525 unsigned TopDownPathCount;
526
Michael Gottesman97e3df02013-01-14 00:35:14 +0000527 /// The number of unique control paths to exits from this block.
John McCalld935e9c2011-06-15 23:37:01 +0000528 unsigned BottomUpPathCount;
529
Michael Gottesman97e3df02013-01-14 00:35:14 +0000530 /// A type for PerPtrTopDown and PerPtrBottomUp.
John McCalld935e9c2011-06-15 23:37:01 +0000531 typedef MapVector<const Value *, PtrState> MapTy;
532
Michael Gottesman97e3df02013-01-14 00:35:14 +0000533 /// The top-down traversal uses this to record information known about a
534 /// pointer at the bottom of each block.
John McCalld935e9c2011-06-15 23:37:01 +0000535 MapTy PerPtrTopDown;
536
Michael Gottesman97e3df02013-01-14 00:35:14 +0000537 /// The bottom-up traversal uses this to record information known about a
538 /// pointer at the top of each block.
John McCalld935e9c2011-06-15 23:37:01 +0000539 MapTy PerPtrBottomUp;
540
Michael Gottesman97e3df02013-01-14 00:35:14 +0000541 /// Effective predecessors of the current block ignoring ignorable edges and
542 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000543 SmallVector<BasicBlock *, 2> Preds;
Michael Gottesman97e3df02013-01-14 00:35:14 +0000544 /// Effective successors of the current block ignoring ignorable edges and
545 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000546 SmallVector<BasicBlock *, 2> Succs;
547
John McCalld935e9c2011-06-15 23:37:01 +0000548 public:
549 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
550
551 typedef MapTy::iterator ptr_iterator;
552 typedef MapTy::const_iterator ptr_const_iterator;
553
554 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
555 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
556 ptr_const_iterator top_down_ptr_begin() const {
557 return PerPtrTopDown.begin();
558 }
559 ptr_const_iterator top_down_ptr_end() const {
560 return PerPtrTopDown.end();
561 }
562
563 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
564 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
565 ptr_const_iterator bottom_up_ptr_begin() const {
566 return PerPtrBottomUp.begin();
567 }
568 ptr_const_iterator bottom_up_ptr_end() const {
569 return PerPtrBottomUp.end();
570 }
571
Michael Gottesman97e3df02013-01-14 00:35:14 +0000572 /// Mark this block as being an entry block, which has one path from the
573 /// entry by definition.
John McCalld935e9c2011-06-15 23:37:01 +0000574 void SetAsEntry() { TopDownPathCount = 1; }
575
Michael Gottesman97e3df02013-01-14 00:35:14 +0000576 /// Mark this block as being an exit block, which has one path to an exit by
577 /// definition.
John McCalld935e9c2011-06-15 23:37:01 +0000578 void SetAsExit() { BottomUpPathCount = 1; }
579
580 PtrState &getPtrTopDownState(const Value *Arg) {
581 return PerPtrTopDown[Arg];
582 }
583
584 PtrState &getPtrBottomUpState(const Value *Arg) {
585 return PerPtrBottomUp[Arg];
586 }
587
588 void clearBottomUpPointers() {
Evan Chenge4df6a22011-08-04 18:40:26 +0000589 PerPtrBottomUp.clear();
John McCalld935e9c2011-06-15 23:37:01 +0000590 }
591
592 void clearTopDownPointers() {
593 PerPtrTopDown.clear();
594 }
595
596 void InitFromPred(const BBState &Other);
597 void InitFromSucc(const BBState &Other);
598 void MergePred(const BBState &Other);
599 void MergeSucc(const BBState &Other);
600
Michael Gottesman97e3df02013-01-14 00:35:14 +0000601 /// Return the number of possible unique paths from an entry to an exit
602 /// which pass through this block. This is only valid after both the
603 /// top-down and bottom-up traversals are complete.
John McCalld935e9c2011-06-15 23:37:01 +0000604 unsigned GetAllPathCount() const {
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000605 assert(TopDownPathCount != 0);
606 assert(BottomUpPathCount != 0);
John McCalld935e9c2011-06-15 23:37:01 +0000607 return TopDownPathCount * BottomUpPathCount;
608 }
Dan Gohman12130272011-08-12 00:26:31 +0000609
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000610 // Specialized CFG utilities.
Dan Gohmandae33492012-04-27 18:56:31 +0000611 typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000612 edge_iterator pred_begin() { return Preds.begin(); }
613 edge_iterator pred_end() { return Preds.end(); }
614 edge_iterator succ_begin() { return Succs.begin(); }
615 edge_iterator succ_end() { return Succs.end(); }
616
617 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
618 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
619
620 bool isExit() const { return Succs.empty(); }
John McCalld935e9c2011-06-15 23:37:01 +0000621 };
622}
623
624void BBState::InitFromPred(const BBState &Other) {
625 PerPtrTopDown = Other.PerPtrTopDown;
626 TopDownPathCount = Other.TopDownPathCount;
627}
628
629void BBState::InitFromSucc(const BBState &Other) {
630 PerPtrBottomUp = Other.PerPtrBottomUp;
631 BottomUpPathCount = Other.BottomUpPathCount;
632}
633
Michael Gottesman97e3df02013-01-14 00:35:14 +0000634/// The top-down traversal uses this to merge information about predecessors to
635/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +0000636void BBState::MergePred(const BBState &Other) {
637 // Other.TopDownPathCount can be 0, in which case it is either dead or a
638 // loop backedge. Loop backedges are special.
639 TopDownPathCount += Other.TopDownPathCount;
640
Michael Gottesman4385edf2013-01-14 01:47:53 +0000641 // Check for overflow. If we have overflow, fall back to conservative
642 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +0000643 if (TopDownPathCount < Other.TopDownPathCount) {
644 clearTopDownPointers();
645 return;
646 }
647
John McCalld935e9c2011-06-15 23:37:01 +0000648 // For each entry in the other set, if our set has an entry with the same key,
649 // merge the entries. Otherwise, copy the entry and merge it with an empty
650 // entry.
651 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
652 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
653 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
654 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
655 /*TopDown=*/true);
656 }
657
Dan Gohman7e315fc32011-08-11 21:06:32 +0000658 // For each entry in our set, if the other set doesn't have an entry with the
John McCalld935e9c2011-06-15 23:37:01 +0000659 // same key, force it to merge with an empty entry.
660 for (ptr_iterator MI = top_down_ptr_begin(),
661 ME = top_down_ptr_end(); MI != ME; ++MI)
662 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
663 MI->second.Merge(PtrState(), /*TopDown=*/true);
664}
665
Michael Gottesman97e3df02013-01-14 00:35:14 +0000666/// The bottom-up traversal uses this to merge information about successors to
667/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +0000668void BBState::MergeSucc(const BBState &Other) {
669 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
670 // loop backedge. Loop backedges are special.
671 BottomUpPathCount += Other.BottomUpPathCount;
672
Michael Gottesman4385edf2013-01-14 01:47:53 +0000673 // Check for overflow. If we have overflow, fall back to conservative
674 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +0000675 if (BottomUpPathCount < Other.BottomUpPathCount) {
676 clearBottomUpPointers();
677 return;
678 }
679
John McCalld935e9c2011-06-15 23:37:01 +0000680 // For each entry in the other set, if our set has an entry with the
681 // same key, merge the entries. Otherwise, copy the entry and merge
682 // it with an empty entry.
683 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
684 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
685 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
686 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
687 /*TopDown=*/false);
688 }
689
Dan Gohman7e315fc32011-08-11 21:06:32 +0000690 // For each entry in our set, if the other set doesn't have an entry
John McCalld935e9c2011-06-15 23:37:01 +0000691 // with the same key, force it to merge with an empty entry.
692 for (ptr_iterator MI = bottom_up_ptr_begin(),
693 ME = bottom_up_ptr_end(); MI != ME; ++MI)
694 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
695 MI->second.Merge(PtrState(), /*TopDown=*/false);
696}
697
Michael Gottesman81b1d432013-03-26 00:42:04 +0000698// Only enable ARC Annotations if we are building a debug version of
699// libObjCARCOpts.
700#ifndef NDEBUG
701#define ARC_ANNOTATIONS
702#endif
703
704// Define some macros along the lines of DEBUG and some helper functions to make
705// it cleaner to create annotations in the source code and to no-op when not
706// building in debug mode.
707#ifdef ARC_ANNOTATIONS
708
709#include "llvm/Support/CommandLine.h"
710
711/// Enable/disable ARC sequence annotations.
712static cl::opt<bool>
Michael Gottesman6806b512013-04-17 20:48:03 +0000713EnableARCAnnotations("enable-objc-arc-annotations", cl::init(false),
714 cl::desc("Enable emission of arc data flow analysis "
715 "annotations"));
Michael Gottesmanffef24f2013-04-17 20:48:01 +0000716static cl::opt<bool>
Michael Gottesmanadb921a2013-04-17 21:03:53 +0000717DisableCheckForCFGHazards("disable-objc-arc-checkforcfghazards", cl::init(false),
718 cl::desc("Disable check for cfg hazards when "
719 "annotating"));
Michael Gottesman4e88ce62013-04-17 21:59:41 +0000720static cl::opt<std::string>
721ARCAnnotationTargetIdentifier("objc-arc-annotation-target-identifier",
722 cl::init(""),
723 cl::desc("filter out all data flow annotations "
724 "but those that apply to the given "
725 "target llvm identifier."));
Michael Gottesman81b1d432013-03-26 00:42:04 +0000726
727/// This function appends a unique ARCAnnotationProvenanceSourceMDKind id to an
728/// instruction so that we can track backwards when post processing via the llvm
729/// arc annotation processor tool. If the function is an
730static MDString *AppendMDNodeToSourcePtr(unsigned NodeId,
731 Value *Ptr) {
732 MDString *Hash = 0;
733
734 // If pointer is a result of an instruction and it does not have a source
735 // MDNode it, attach a new MDNode onto it. If pointer is a result of
736 // an instruction and does have a source MDNode attached to it, return a
737 // reference to said Node. Otherwise just return 0.
738 if (Instruction *Inst = dyn_cast<Instruction>(Ptr)) {
739 MDNode *Node;
740 if (!(Node = Inst->getMetadata(NodeId))) {
741 // We do not have any node. Generate and attatch the hash MDString to the
742 // instruction.
743
744 // We just use an MDString to ensure that this metadata gets written out
745 // of line at the module level and to provide a very simple format
746 // encoding the information herein. Both of these makes it simpler to
747 // parse the annotations by a simple external program.
748 std::string Str;
749 raw_string_ostream os(Str);
750 os << "(" << Inst->getParent()->getParent()->getName() << ",%"
751 << Inst->getName() << ")";
752
753 Hash = MDString::get(Inst->getContext(), os.str());
754 Inst->setMetadata(NodeId, MDNode::get(Inst->getContext(),Hash));
755 } else {
756 // We have a node. Grab its hash and return it.
757 assert(Node->getNumOperands() == 1 &&
758 "An ARCAnnotationProvenanceSourceMDKind can only have 1 operand.");
759 Hash = cast<MDString>(Node->getOperand(0));
760 }
761 } else if (Argument *Arg = dyn_cast<Argument>(Ptr)) {
762 std::string str;
763 raw_string_ostream os(str);
764 os << "(" << Arg->getParent()->getName() << ",%" << Arg->getName()
765 << ")";
766 Hash = MDString::get(Arg->getContext(), os.str());
767 }
768
769 return Hash;
770}
771
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000772static std::string SequenceToString(Sequence A) {
773 std::string str;
774 raw_string_ostream os(str);
775 os << A;
776 return os.str();
777}
778
Michael Gottesman81b1d432013-03-26 00:42:04 +0000779/// Helper function to change a Sequence into a String object using our overload
780/// for raw_ostream so we only have printing code in one location.
781static MDString *SequenceToMDString(LLVMContext &Context,
782 Sequence A) {
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000783 return MDString::get(Context, SequenceToString(A));
Michael Gottesman81b1d432013-03-26 00:42:04 +0000784}
785
786/// A simple function to generate a MDNode which describes the change in state
787/// for Value *Ptr caused by Instruction *Inst.
788static void AppendMDNodeToInstForPtr(unsigned NodeId,
789 Instruction *Inst,
790 Value *Ptr,
791 MDString *PtrSourceMDNodeID,
792 Sequence OldSeq,
793 Sequence NewSeq) {
794 MDNode *Node = 0;
795 Value *tmp[3] = {PtrSourceMDNodeID,
796 SequenceToMDString(Inst->getContext(),
797 OldSeq),
798 SequenceToMDString(Inst->getContext(),
799 NewSeq)};
800 Node = MDNode::get(Inst->getContext(),
801 ArrayRef<Value*>(tmp, 3));
802
803 Inst->setMetadata(NodeId, Node);
804}
805
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000806/// Add to the beginning of the basic block llvm.ptr.annotations which show the
807/// state of a pointer at the entrance to a basic block.
808static void GenerateARCBBEntranceAnnotation(const char *Name, BasicBlock *BB,
809 Value *Ptr, Sequence Seq) {
Michael Gottesman4e88ce62013-04-17 21:59:41 +0000810 // If we have a target identifier, make sure that we match it before
811 // continuing.
812 if(!ARCAnnotationTargetIdentifier.empty() &&
813 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
814 return;
Michael Gottesman9e518132013-04-18 04:34:11 +0000815
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000816 Module *M = BB->getParent()->getParent();
817 LLVMContext &C = M->getContext();
818 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
819 Type *I8XX = PointerType::getUnqual(I8X);
820 Type *Params[] = {I8XX, I8XX};
821 FunctionType *FTy = FunctionType::get(Type::getVoidTy(C),
822 ArrayRef<Type*>(Params, 2),
823 /*isVarArg=*/false);
824 Constant *Callee = M->getOrInsertFunction(Name, FTy);
Michael Gottesman60f6b282013-03-29 05:13:07 +0000825
826 IRBuilder<> Builder(BB, BB->getFirstInsertionPt());
827
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000828 Value *PtrName;
829 StringRef Tmp = Ptr->getName();
830 if (0 == (PtrName = M->getGlobalVariable(Tmp, true))) {
831 Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
832 Tmp + "_STR");
833 PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
Michael Gottesman60f6b282013-03-29 05:13:07 +0000834 cast<Constant>(ActualPtrName), Tmp);
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000835 }
836
837 Value *S;
838 std::string SeqStr = SequenceToString(Seq);
839 if (0 == (S = M->getGlobalVariable(SeqStr, true))) {
840 Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
841 SeqStr + "_STR");
842 S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
843 cast<Constant>(ActualPtrName), SeqStr);
844 }
845
846 Builder.CreateCall2(Callee, PtrName, S);
847}
848
849/// Add to the end of the basic block llvm.ptr.annotations which show the state
850/// of the pointer at the bottom of the basic block.
851static void GenerateARCBBTerminatorAnnotation(const char *Name, BasicBlock *BB,
852 Value *Ptr, Sequence Seq) {
Michael Gottesman4e88ce62013-04-17 21:59:41 +0000853 // If we have a target identifier, make sure that we match it before emitting
854 // an annotation.
855 if(!ARCAnnotationTargetIdentifier.empty() &&
856 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
857 return;
Michael Gottesman9e518132013-04-18 04:34:11 +0000858
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000859 Module *M = BB->getParent()->getParent();
860 LLVMContext &C = M->getContext();
861 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
862 Type *I8XX = PointerType::getUnqual(I8X);
863 Type *Params[] = {I8XX, I8XX};
864 FunctionType *FTy = FunctionType::get(Type::getVoidTy(C),
865 ArrayRef<Type*>(Params, 2),
866 /*isVarArg=*/false);
867 Constant *Callee = M->getOrInsertFunction(Name, FTy);
Michael Gottesman60f6b282013-03-29 05:13:07 +0000868
869 IRBuilder<> Builder(BB, llvm::prior(BB->end()));
870
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000871 Value *PtrName;
872 StringRef Tmp = Ptr->getName();
873 if (0 == (PtrName = M->getGlobalVariable(Tmp, true))) {
874 Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
875 Tmp + "_STR");
876 PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
Michael Gottesman60f6b282013-03-29 05:13:07 +0000877 cast<Constant>(ActualPtrName), Tmp);
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000878 }
879
880 Value *S;
881 std::string SeqStr = SequenceToString(Seq);
882 if (0 == (S = M->getGlobalVariable(SeqStr, true))) {
883 Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
884 SeqStr + "_STR");
885 S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
886 cast<Constant>(ActualPtrName), SeqStr);
887 }
Michael Gottesman60f6b282013-03-29 05:13:07 +0000888 Builder.CreateCall2(Callee, PtrName, S);
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000889}
890
Michael Gottesman81b1d432013-03-26 00:42:04 +0000891/// Adds a source annotation to pointer and a state change annotation to Inst
892/// referencing the source annotation and the old/new state of pointer.
893static void GenerateARCAnnotation(unsigned InstMDId,
894 unsigned PtrMDId,
895 Instruction *Inst,
896 Value *Ptr,
897 Sequence OldSeq,
898 Sequence NewSeq) {
899 if (EnableARCAnnotations) {
Michael Gottesman4e88ce62013-04-17 21:59:41 +0000900 // If we have a target identifier, make sure that we match it before
901 // emitting an annotation.
902 if(!ARCAnnotationTargetIdentifier.empty() &&
903 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
904 return;
Michael Gottesman9e518132013-04-18 04:34:11 +0000905
Michael Gottesman81b1d432013-03-26 00:42:04 +0000906 // First generate the source annotation on our pointer. This will return an
907 // MDString* if Ptr actually comes from an instruction implying we can put
908 // in a source annotation. If AppendMDNodeToSourcePtr returns 0 (i.e. NULL),
909 // then we know that our pointer is from an Argument so we put a reference
910 // to the argument number.
911 //
912 // The point of this is to make it easy for the
913 // llvm-arc-annotation-processor tool to cross reference where the source
914 // pointer is in the LLVM IR since the LLVM IR parser does not submit such
915 // information via debug info for backends to use (since why would anyone
916 // need such a thing from LLVM IR besides in non standard cases
917 // [i.e. this]).
918 MDString *SourcePtrMDNode =
919 AppendMDNodeToSourcePtr(PtrMDId, Ptr);
920 AppendMDNodeToInstForPtr(InstMDId, Inst, Ptr, SourcePtrMDNode, OldSeq,
921 NewSeq);
922 }
923}
924
925// The actual interface for accessing the above functionality is defined via
926// some simple macros which are defined below. We do this so that the user does
927// not need to pass in what metadata id is needed resulting in cleaner code and
928// additionally since it provides an easy way to conditionally no-op all
929// annotation support in a non-debug build.
930
931/// Use this macro to annotate a sequence state change when processing
932/// instructions bottom up,
933#define ANNOTATE_BOTTOMUP(inst, ptr, old, new) \
934 GenerateARCAnnotation(ARCAnnotationBottomUpMDKind, \
935 ARCAnnotationProvenanceSourceMDKind, (inst), \
936 const_cast<Value*>(ptr), (old), (new))
937/// Use this macro to annotate a sequence state change when processing
938/// instructions top down.
939#define ANNOTATE_TOPDOWN(inst, ptr, old, new) \
940 GenerateARCAnnotation(ARCAnnotationTopDownMDKind, \
941 ARCAnnotationProvenanceSourceMDKind, (inst), \
942 const_cast<Value*>(ptr), (old), (new))
943
Michael Gottesman43e7e002013-04-03 22:41:59 +0000944#define ANNOTATE_BB(_states, _bb, _name, _type, _direction) \
945 do { \
Michael Gottesman89279f82013-04-05 18:10:41 +0000946 if (EnableARCAnnotations) { \
947 for(BBState::ptr_const_iterator I = (_states)._direction##_ptr_begin(), \
Michael Gottesman43e7e002013-04-03 22:41:59 +0000948 E = (_states)._direction##_ptr_end(); I != E; ++I) { \
Michael Gottesman89279f82013-04-05 18:10:41 +0000949 Value *Ptr = const_cast<Value*>(I->first); \
950 Sequence Seq = I->second.GetSeq(); \
951 GenerateARCBB ## _type ## Annotation(_name, (_bb), Ptr, Seq); \
952 } \
Michael Gottesman43e7e002013-04-03 22:41:59 +0000953 } \
Michael Gottesman89279f82013-04-05 18:10:41 +0000954 } while (0)
Michael Gottesman43e7e002013-04-03 22:41:59 +0000955
Michael Gottesman89279f82013-04-05 18:10:41 +0000956#define ANNOTATE_BOTTOMUP_BBSTART(_states, _basicblock) \
Michael Gottesman43e7e002013-04-03 22:41:59 +0000957 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbstart", \
958 Entrance, bottom_up)
Michael Gottesman89279f82013-04-05 18:10:41 +0000959#define ANNOTATE_BOTTOMUP_BBEND(_states, _basicblock) \
960 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbend", \
Michael Gottesman43e7e002013-04-03 22:41:59 +0000961 Terminator, bottom_up)
Michael Gottesman89279f82013-04-05 18:10:41 +0000962#define ANNOTATE_TOPDOWN_BBSTART(_states, _basicblock) \
963 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbstart", \
Michael Gottesman43e7e002013-04-03 22:41:59 +0000964 Entrance, top_down)
Michael Gottesman89279f82013-04-05 18:10:41 +0000965#define ANNOTATE_TOPDOWN_BBEND(_states, _basicblock) \
966 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbend", \
Michael Gottesman43e7e002013-04-03 22:41:59 +0000967 Terminator, top_down)
968
Michael Gottesman81b1d432013-03-26 00:42:04 +0000969#else // !ARC_ANNOTATION
970// If annotations are off, noop.
971#define ANNOTATE_BOTTOMUP(inst, ptr, old, new)
972#define ANNOTATE_TOPDOWN(inst, ptr, old, new)
Michael Gottesman43e7e002013-04-03 22:41:59 +0000973#define ANNOTATE_BOTTOMUP_BBSTART(states, basicblock)
974#define ANNOTATE_BOTTOMUP_BBEND(states, basicblock)
975#define ANNOTATE_TOPDOWN_BBSTART(states, basicblock)
976#define ANNOTATE_TOPDOWN_BBEND(states, basicblock)
Michael Gottesman81b1d432013-03-26 00:42:04 +0000977#endif // !ARC_ANNOTATION
978
John McCalld935e9c2011-06-15 23:37:01 +0000979namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000980 /// \brief The main ARC optimization pass.
John McCalld935e9c2011-06-15 23:37:01 +0000981 class ObjCARCOpt : public FunctionPass {
982 bool Changed;
983 ProvenanceAnalysis PA;
984
Michael Gottesman97e3df02013-01-14 00:35:14 +0000985 /// A flag indicating whether this optimization pass should run.
Dan Gohmanceaac7c2011-06-20 23:20:43 +0000986 bool Run;
987
Michael Gottesman97e3df02013-01-14 00:35:14 +0000988 /// Declarations for ObjC runtime functions, for use in creating calls to
989 /// them. These are initialized lazily to avoid cluttering up the Module
990 /// with unused declarations.
John McCalld935e9c2011-06-15 23:37:01 +0000991
Michael Gottesman97e3df02013-01-14 00:35:14 +0000992 /// Declaration for ObjC runtime function
993 /// objc_retainAutoreleasedReturnValue.
994 Constant *RetainRVCallee;
995 /// Declaration for ObjC runtime function objc_autoreleaseReturnValue.
996 Constant *AutoreleaseRVCallee;
997 /// Declaration for ObjC runtime function objc_release.
998 Constant *ReleaseCallee;
999 /// Declaration for ObjC runtime function objc_retain.
1000 Constant *RetainCallee;
1001 /// Declaration for ObjC runtime function objc_retainBlock.
1002 Constant *RetainBlockCallee;
1003 /// Declaration for ObjC runtime function objc_autorelease.
1004 Constant *AutoreleaseCallee;
1005
1006 /// Flags which determine whether each of the interesting runtine functions
1007 /// is in fact used in the current function.
John McCalld935e9c2011-06-15 23:37:01 +00001008 unsigned UsedInThisFunction;
1009
Michael Gottesman97e3df02013-01-14 00:35:14 +00001010 /// The Metadata Kind for clang.imprecise_release metadata.
John McCalld935e9c2011-06-15 23:37:01 +00001011 unsigned ImpreciseReleaseMDKind;
1012
Michael Gottesman97e3df02013-01-14 00:35:14 +00001013 /// The Metadata Kind for clang.arc.copy_on_escape metadata.
Dan Gohmana7107f92011-10-17 22:53:25 +00001014 unsigned CopyOnEscapeMDKind;
1015
Michael Gottesman97e3df02013-01-14 00:35:14 +00001016 /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata.
Dan Gohman0155f302012-02-17 18:59:53 +00001017 unsigned NoObjCARCExceptionsMDKind;
1018
Michael Gottesman81b1d432013-03-26 00:42:04 +00001019#ifdef ARC_ANNOTATIONS
1020 /// The Metadata Kind for llvm.arc.annotation.bottomup metadata.
1021 unsigned ARCAnnotationBottomUpMDKind;
1022 /// The Metadata Kind for llvm.arc.annotation.topdown metadata.
1023 unsigned ARCAnnotationTopDownMDKind;
1024 /// The Metadata Kind for llvm.arc.annotation.provenancesource metadata.
1025 unsigned ARCAnnotationProvenanceSourceMDKind;
1026#endif // ARC_ANNOATIONS
1027
John McCalld935e9c2011-06-15 23:37:01 +00001028 Constant *getRetainRVCallee(Module *M);
1029 Constant *getAutoreleaseRVCallee(Module *M);
1030 Constant *getReleaseCallee(Module *M);
1031 Constant *getRetainCallee(Module *M);
Dan Gohman6320f522011-07-22 22:29:21 +00001032 Constant *getRetainBlockCallee(Module *M);
John McCalld935e9c2011-06-15 23:37:01 +00001033 Constant *getAutoreleaseCallee(Module *M);
1034
Dan Gohman728db492012-01-13 00:39:07 +00001035 bool IsRetainBlockOptimizable(const Instruction *Inst);
1036
John McCalld935e9c2011-06-15 23:37:01 +00001037 void OptimizeRetainCall(Function &F, Instruction *Retain);
1038 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
Michael Gottesman556ff612013-01-12 01:25:19 +00001039 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1040 InstructionClass &Class);
Michael Gottesman158fdf62013-03-28 20:11:19 +00001041 bool OptimizeRetainBlockCall(Function &F, Instruction *RetainBlock,
1042 InstructionClass &Class);
John McCalld935e9c2011-06-15 23:37:01 +00001043 void OptimizeIndividualCalls(Function &F);
1044
1045 void CheckForCFGHazards(const BasicBlock *BB,
1046 DenseMap<const BasicBlock *, BBState> &BBStates,
1047 BBState &MyStates) const;
Dan Gohman817a7c62012-03-22 18:24:56 +00001048 bool VisitInstructionBottomUp(Instruction *Inst,
Dan Gohman5c70fad2012-03-23 17:47:54 +00001049 BasicBlock *BB,
Dan Gohman817a7c62012-03-22 18:24:56 +00001050 MapVector<Value *, RRInfo> &Retains,
1051 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00001052 bool VisitBottomUp(BasicBlock *BB,
1053 DenseMap<const BasicBlock *, BBState> &BBStates,
1054 MapVector<Value *, RRInfo> &Retains);
Dan Gohman817a7c62012-03-22 18:24:56 +00001055 bool VisitInstructionTopDown(Instruction *Inst,
1056 DenseMap<Value *, RRInfo> &Releases,
1057 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00001058 bool VisitTopDown(BasicBlock *BB,
1059 DenseMap<const BasicBlock *, BBState> &BBStates,
1060 DenseMap<Value *, RRInfo> &Releases);
1061 bool Visit(Function &F,
1062 DenseMap<const BasicBlock *, BBState> &BBStates,
1063 MapVector<Value *, RRInfo> &Retains,
1064 DenseMap<Value *, RRInfo> &Releases);
1065
1066 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1067 MapVector<Value *, RRInfo> &Retains,
1068 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman6320f522011-07-22 22:29:21 +00001069 SmallVectorImpl<Instruction *> &DeadInsts,
1070 Module *M);
John McCalld935e9c2011-06-15 23:37:01 +00001071
Michael Gottesman9de6f962013-01-22 21:49:00 +00001072 bool ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState> &BBStates,
1073 MapVector<Value *, RRInfo> &Retains,
1074 DenseMap<Value *, RRInfo> &Releases,
1075 Module *M,
1076 SmallVector<Instruction *, 4> &NewRetains,
1077 SmallVector<Instruction *, 4> &NewReleases,
1078 SmallVector<Instruction *, 8> &DeadInsts,
1079 RRInfo &RetainsToMove,
1080 RRInfo &ReleasesToMove,
1081 Value *Arg,
1082 bool KnownSafe,
1083 bool &AnyPairsCompletelyEliminated);
1084
John McCalld935e9c2011-06-15 23:37:01 +00001085 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1086 MapVector<Value *, RRInfo> &Retains,
Dan Gohman6320f522011-07-22 22:29:21 +00001087 DenseMap<Value *, RRInfo> &Releases,
1088 Module *M);
John McCalld935e9c2011-06-15 23:37:01 +00001089
1090 void OptimizeWeakCalls(Function &F);
1091
1092 bool OptimizeSequences(Function &F);
1093
1094 void OptimizeReturns(Function &F);
1095
1096 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1097 virtual bool doInitialization(Module &M);
1098 virtual bool runOnFunction(Function &F);
1099 virtual void releaseMemory();
1100
1101 public:
1102 static char ID;
1103 ObjCARCOpt() : FunctionPass(ID) {
1104 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1105 }
1106 };
1107}
1108
1109char ObjCARCOpt::ID = 0;
1110INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1111 "objc-arc", "ObjC ARC optimization", false, false)
1112INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1113INITIALIZE_PASS_END(ObjCARCOpt,
1114 "objc-arc", "ObjC ARC optimization", false, false)
1115
1116Pass *llvm::createObjCARCOptPass() {
1117 return new ObjCARCOpt();
1118}
1119
1120void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1121 AU.addRequired<ObjCARCAliasAnalysis>();
1122 AU.addRequired<AliasAnalysis>();
1123 // ARC optimization doesn't currently split critical edges.
1124 AU.setPreservesCFG();
1125}
1126
Dan Gohman728db492012-01-13 00:39:07 +00001127bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1128 // Without the magic metadata tag, we have to assume this might be an
1129 // objc_retainBlock call inserted to convert a block pointer to an id,
1130 // in which case it really is needed.
1131 if (!Inst->getMetadata(CopyOnEscapeMDKind))
1132 return false;
1133
1134 // If the pointer "escapes" (not including being used in a call),
1135 // the copy may be needed.
Michael Gottesman774d2c02013-01-29 21:00:52 +00001136 if (DoesRetainableObjPtrEscape(Inst))
Dan Gohman728db492012-01-13 00:39:07 +00001137 return false;
1138
1139 // Otherwise, it's not needed.
1140 return true;
1141}
1142
John McCalld935e9c2011-06-15 23:37:01 +00001143Constant *ObjCARCOpt::getRetainRVCallee(Module *M) {
1144 if (!RetainRVCallee) {
1145 LLVMContext &C = M->getContext();
Jay Foadb804a2b2011-07-12 14:06:48 +00001146 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman41375a32012-05-08 23:39:44 +00001147 Type *Params[] = { I8X };
1148 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001149 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001150 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1151 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001152 RetainRVCallee =
1153 M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy,
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001154 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001155 }
1156 return RetainRVCallee;
1157}
1158
1159Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1160 if (!AutoreleaseRVCallee) {
1161 LLVMContext &C = M->getContext();
Jay Foadb804a2b2011-07-12 14:06:48 +00001162 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman41375a32012-05-08 23:39:44 +00001163 Type *Params[] = { I8X };
1164 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001165 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001166 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1167 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001168 AutoreleaseRVCallee =
1169 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001170 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001171 }
1172 return AutoreleaseRVCallee;
1173}
1174
1175Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1176 if (!ReleaseCallee) {
1177 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001178 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001179 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001180 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1181 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001182 ReleaseCallee =
1183 M->getOrInsertFunction(
1184 "objc_release",
1185 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001186 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001187 }
1188 return ReleaseCallee;
1189}
1190
1191Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1192 if (!RetainCallee) {
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 RetainCallee =
1199 M->getOrInsertFunction(
1200 "objc_retain",
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 RetainCallee;
1205}
1206
Dan Gohman6320f522011-07-22 22:29:21 +00001207Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1208 if (!RetainBlockCallee) {
1209 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001210 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Dan Gohmanfca43c22011-09-14 18:33:34 +00001211 // objc_retainBlock is not nounwind because it calls user copy constructors
1212 // which could theoretically throw.
Dan Gohman6320f522011-07-22 22:29:21 +00001213 RetainBlockCallee =
1214 M->getOrInsertFunction(
1215 "objc_retainBlock",
1216 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendlinge94d8432012-12-07 23:16:57 +00001217 AttributeSet());
Dan Gohman6320f522011-07-22 22:29:21 +00001218 }
1219 return RetainBlockCallee;
1220}
1221
John McCalld935e9c2011-06-15 23:37:01 +00001222Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1223 if (!AutoreleaseCallee) {
1224 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001225 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001226 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001227 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1228 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001229 AutoreleaseCallee =
1230 M->getOrInsertFunction(
1231 "objc_autorelease",
1232 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001233 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001234 }
1235 return AutoreleaseCallee;
1236}
1237
Michael Gottesman97e3df02013-01-14 00:35:14 +00001238/// Turn objc_retain into objc_retainAutoreleasedReturnValue if the operand is a
1239/// return value.
John McCalld935e9c2011-06-15 23:37:01 +00001240void
1241ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) {
Dan Gohmandae33492012-04-27 18:56:31 +00001242 ImmutableCallSite CS(GetObjCArg(Retain));
1243 const Instruction *Call = CS.getInstruction();
John McCalld935e9c2011-06-15 23:37:01 +00001244 if (!Call) return;
1245 if (Call->getParent() != Retain->getParent()) return;
1246
1247 // Check that the call is next to the retain.
Dan Gohmandae33492012-04-27 18:56:31 +00001248 BasicBlock::const_iterator I = Call;
John McCalld935e9c2011-06-15 23:37:01 +00001249 ++I;
Michael Gottesman65c24812013-03-25 09:27:43 +00001250 while (IsNoopInstruction(I)) ++I;
John McCalld935e9c2011-06-15 23:37:01 +00001251 if (&*I != Retain)
1252 return;
1253
1254 // Turn it to an objc_retainAutoreleasedReturnValue..
1255 Changed = true;
1256 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00001257
Michael Gottesman89279f82013-04-05 18:10:41 +00001258 DEBUG(dbgs() << "Transforming objc_retain => "
1259 "objc_retainAutoreleasedReturnValue since the operand is a "
1260 "return value.\nOld: "<< *Retain << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001261
John McCalld935e9c2011-06-15 23:37:01 +00001262 cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent()));
Michael Gottesman1e00ac62013-01-04 21:30:38 +00001263
Michael Gottesman89279f82013-04-05 18:10:41 +00001264 DEBUG(dbgs() << "New: " << *Retain << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001265}
1266
Michael Gottesman97e3df02013-01-14 00:35:14 +00001267/// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is
1268/// not a return value. Or, if it can be paired with an
1269/// objc_autoreleaseReturnValue, delete the pair and return true.
John McCalld935e9c2011-06-15 23:37:01 +00001270bool
1271ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001272 // Check for the argument being from an immediately preceding call or invoke.
Dan Gohmandae33492012-04-27 18:56:31 +00001273 const Value *Arg = GetObjCArg(RetainRV);
1274 ImmutableCallSite CS(Arg);
1275 if (const Instruction *Call = CS.getInstruction()) {
John McCalld935e9c2011-06-15 23:37:01 +00001276 if (Call->getParent() == RetainRV->getParent()) {
Dan Gohmandae33492012-04-27 18:56:31 +00001277 BasicBlock::const_iterator I = Call;
John McCalld935e9c2011-06-15 23:37:01 +00001278 ++I;
Michael Gottesman65c24812013-03-25 09:27:43 +00001279 while (IsNoopInstruction(I)) ++I;
John McCalld935e9c2011-06-15 23:37:01 +00001280 if (&*I == RetainRV)
1281 return false;
Dan Gohmandae33492012-04-27 18:56:31 +00001282 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001283 BasicBlock *RetainRVParent = RetainRV->getParent();
1284 if (II->getNormalDest() == RetainRVParent) {
Dan Gohmandae33492012-04-27 18:56:31 +00001285 BasicBlock::const_iterator I = RetainRVParent->begin();
Michael Gottesman65c24812013-03-25 09:27:43 +00001286 while (IsNoopInstruction(I)) ++I;
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001287 if (&*I == RetainRV)
1288 return false;
1289 }
John McCalld935e9c2011-06-15 23:37:01 +00001290 }
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001291 }
John McCalld935e9c2011-06-15 23:37:01 +00001292
1293 // Check for being preceded by an objc_autoreleaseReturnValue on the same
1294 // pointer. In this case, we can delete the pair.
1295 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
1296 if (I != Begin) {
Michael Gottesman65c24812013-03-25 09:27:43 +00001297 do --I; while (I != Begin && IsNoopInstruction(I));
John McCalld935e9c2011-06-15 23:37:01 +00001298 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
1299 GetObjCArg(I) == Arg) {
1300 Changed = true;
1301 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00001302
Michael Gottesman89279f82013-04-05 18:10:41 +00001303 DEBUG(dbgs() << "Erasing autoreleaseRV,retainRV pair: " << *I << "\n"
1304 << "Erasing " << *RetainRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001305
John McCalld935e9c2011-06-15 23:37:01 +00001306 EraseInstruction(I);
1307 EraseInstruction(RetainRV);
1308 return true;
1309 }
1310 }
1311
1312 // Turn it to a plain objc_retain.
1313 Changed = true;
1314 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00001315
Michael Gottesman89279f82013-04-05 18:10:41 +00001316 DEBUG(dbgs() << "Transforming objc_retainAutoreleasedReturnValue => "
Michael Gottesmandef07bb2013-01-05 17:55:42 +00001317 "objc_retain since the operand is not a return value.\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00001318 "Old = " << *RetainRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001319
John McCalld935e9c2011-06-15 23:37:01 +00001320 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
Michael Gottesmandef07bb2013-01-05 17:55:42 +00001321
Michael Gottesman89279f82013-04-05 18:10:41 +00001322 DEBUG(dbgs() << "New = " << *RetainRV << "\n");
Michael Gottesmandef07bb2013-01-05 17:55:42 +00001323
John McCalld935e9c2011-06-15 23:37:01 +00001324 return false;
1325}
1326
Michael Gottesman97e3df02013-01-14 00:35:14 +00001327/// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not
1328/// used as a return value.
John McCalld935e9c2011-06-15 23:37:01 +00001329void
Michael Gottesman556ff612013-01-12 01:25:19 +00001330ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1331 InstructionClass &Class) {
John McCalld935e9c2011-06-15 23:37:01 +00001332 // Check for a return of the pointer value.
1333 const Value *Ptr = GetObjCArg(AutoreleaseRV);
Dan Gohman10a18d52011-08-12 00:36:31 +00001334 SmallVector<const Value *, 2> Users;
1335 Users.push_back(Ptr);
1336 do {
1337 Ptr = Users.pop_back_val();
1338 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
1339 UI != UE; ++UI) {
1340 const User *I = *UI;
1341 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
1342 return;
1343 if (isa<BitCastInst>(I))
1344 Users.push_back(I);
1345 }
1346 } while (!Users.empty());
John McCalld935e9c2011-06-15 23:37:01 +00001347
1348 Changed = true;
1349 ++NumPeeps;
Michael Gottesman1bf69082013-01-06 21:07:11 +00001350
Michael Gottesman89279f82013-04-05 18:10:41 +00001351 DEBUG(dbgs() << "Transforming objc_autoreleaseReturnValue => "
Michael Gottesman1bf69082013-01-06 21:07:11 +00001352 "objc_autorelease since its operand is not used as a return "
1353 "value.\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00001354 "Old = " << *AutoreleaseRV << "\n");
Michael Gottesman1bf69082013-01-06 21:07:11 +00001355
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001356 CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
1357 AutoreleaseRVCI->
John McCalld935e9c2011-06-15 23:37:01 +00001358 setCalledFunction(getAutoreleaseCallee(F.getParent()));
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001359 AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
Michael Gottesman556ff612013-01-12 01:25:19 +00001360 Class = IC_Autorelease;
Michael Gottesman10426b52013-01-07 21:26:07 +00001361
Michael Gottesman89279f82013-04-05 18:10:41 +00001362 DEBUG(dbgs() << "New: " << *AutoreleaseRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001363
John McCalld935e9c2011-06-15 23:37:01 +00001364}
1365
Michael Gottesman158fdf62013-03-28 20:11:19 +00001366// \brief Attempt to strength reduce objc_retainBlock calls to objc_retain
1367// calls.
1368//
1369// Specifically: If an objc_retainBlock call has the copy_on_escape metadata and
1370// does not escape (following the rules of block escaping), strength reduce the
1371// objc_retainBlock to an objc_retain.
1372//
1373// TODO: If an objc_retainBlock call is dominated period by a previous
1374// objc_retainBlock call, strength reduce the objc_retainBlock to an
1375// objc_retain.
1376bool
1377ObjCARCOpt::OptimizeRetainBlockCall(Function &F, Instruction *Inst,
1378 InstructionClass &Class) {
1379 assert(GetBasicInstructionClass(Inst) == Class);
1380 assert(IC_RetainBlock == Class);
Michael Gottesman60f6b282013-03-29 05:13:07 +00001381
Michael Gottesman158fdf62013-03-28 20:11:19 +00001382 // If we can not optimize Inst, return false.
1383 if (!IsRetainBlockOptimizable(Inst))
1384 return false;
Michael Gottesman60f6b282013-03-29 05:13:07 +00001385
Michael Gottesman3eab2e42013-04-21 00:50:27 +00001386 Changed = true;
1387 ++NumPeeps;
1388
1389 DEBUG(dbgs() << "Strength reduced retainBlock => retain.\n");
1390 DEBUG(dbgs() << "Old: " << *Inst << "\n");
Michael Gottesman158fdf62013-03-28 20:11:19 +00001391 CallInst *RetainBlock = cast<CallInst>(Inst);
1392 RetainBlock->setCalledFunction(getRetainCallee(F.getParent()));
1393 // Remove copy_on_escape metadata.
1394 RetainBlock->setMetadata(CopyOnEscapeMDKind, 0);
1395 Class = IC_Retain;
Michael Gottesman3eab2e42013-04-21 00:50:27 +00001396 DEBUG(dbgs() << "New: " << *Inst << "\n");
Michael Gottesman158fdf62013-03-28 20:11:19 +00001397 return true;
1398}
1399
Michael Gottesman97e3df02013-01-14 00:35:14 +00001400/// Visit each call, one at a time, and make simplifications without doing any
1401/// additional analysis.
John McCalld935e9c2011-06-15 23:37:01 +00001402void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001403 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeIndividualCalls ==\n");
John McCalld935e9c2011-06-15 23:37:01 +00001404 // Reset all the flags in preparation for recomputing them.
1405 UsedInThisFunction = 0;
1406
1407 // Visit all objc_* calls in F.
1408 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
1409 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +00001410
John McCalld935e9c2011-06-15 23:37:01 +00001411 InstructionClass Class = GetBasicInstructionClass(Inst);
1412
Michael Gottesman89279f82013-04-05 18:10:41 +00001413 DEBUG(dbgs() << "Visiting: Class: " << Class << "; " << *Inst << "\n");
Michael Gottesman782e3442013-01-17 18:32:34 +00001414
John McCalld935e9c2011-06-15 23:37:01 +00001415 switch (Class) {
1416 default: break;
1417
1418 // Delete no-op casts. These function calls have special semantics, but
1419 // the semantics are entirely implemented via lowering in the front-end,
1420 // so by the time they reach the optimizer, they are just no-op calls
1421 // which return their argument.
1422 //
1423 // There are gray areas here, as the ability to cast reference-counted
1424 // pointers to raw void* and back allows code to break ARC assumptions,
1425 // however these are currently considered to be unimportant.
1426 case IC_NoopCast:
1427 Changed = true;
1428 ++NumNoops;
Michael Gottesman89279f82013-04-05 18:10:41 +00001429 DEBUG(dbgs() << "Erasing no-op cast: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001430 EraseInstruction(Inst);
1431 continue;
1432
1433 // If the pointer-to-weak-pointer is null, it's undefined behavior.
1434 case IC_StoreWeak:
1435 case IC_LoadWeak:
1436 case IC_LoadWeakRetained:
1437 case IC_InitWeak:
1438 case IC_DestroyWeak: {
1439 CallInst *CI = cast<CallInst>(Inst);
Michael Gottesman65c24812013-03-25 09:27:43 +00001440 if (IsNullOrUndef(CI->getArgOperand(0))) {
Dan Gohman670f9372012-04-13 18:57:48 +00001441 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +00001442 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001443 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1444 Constant::getNullValue(Ty),
1445 CI);
Michael Gottesman10426b52013-01-07 21:26:07 +00001446 llvm::Value *NewValue = UndefValue::get(CI->getType());
Michael Gottesman89279f82013-04-05 18:10:41 +00001447 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
1448 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001449 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +00001450 CI->eraseFromParent();
1451 continue;
1452 }
1453 break;
1454 }
1455 case IC_CopyWeak:
1456 case IC_MoveWeak: {
1457 CallInst *CI = cast<CallInst>(Inst);
Michael Gottesman65c24812013-03-25 09:27:43 +00001458 if (IsNullOrUndef(CI->getArgOperand(0)) ||
1459 IsNullOrUndef(CI->getArgOperand(1))) {
Dan Gohman670f9372012-04-13 18:57:48 +00001460 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +00001461 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001462 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1463 Constant::getNullValue(Ty),
1464 CI);
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001465
1466 llvm::Value *NewValue = UndefValue::get(CI->getType());
Michael Gottesman89279f82013-04-05 18:10:41 +00001467 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
1468 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001469
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001470 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +00001471 CI->eraseFromParent();
1472 continue;
1473 }
1474 break;
1475 }
Michael Gottesman158fdf62013-03-28 20:11:19 +00001476 case IC_RetainBlock:
Michael Gottesman1e430042013-04-21 00:44:46 +00001477 // If we strength reduce an objc_retainBlock to an objc_retain, continue
Michael Gottesman158fdf62013-03-28 20:11:19 +00001478 // onto the objc_retain peephole optimizations. Otherwise break.
1479 if (!OptimizeRetainBlockCall(F, Inst, Class))
1480 break;
1481 // FALLTHROUGH
John McCalld935e9c2011-06-15 23:37:01 +00001482 case IC_Retain:
1483 OptimizeRetainCall(F, Inst);
1484 break;
1485 case IC_RetainRV:
1486 if (OptimizeRetainRVCall(F, Inst))
1487 continue;
1488 break;
1489 case IC_AutoreleaseRV:
Michael Gottesman556ff612013-01-12 01:25:19 +00001490 OptimizeAutoreleaseRVCall(F, Inst, Class);
John McCalld935e9c2011-06-15 23:37:01 +00001491 break;
1492 }
1493
Michael Gottesmanb8c88362013-04-03 02:57:24 +00001494 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
John McCalld935e9c2011-06-15 23:37:01 +00001495 if (IsAutorelease(Class) && Inst->use_empty()) {
1496 CallInst *Call = cast<CallInst>(Inst);
1497 const Value *Arg = Call->getArgOperand(0);
1498 Arg = FindSingleUseIdentifiedObject(Arg);
1499 if (Arg) {
1500 Changed = true;
1501 ++NumAutoreleases;
1502
1503 // Create the declaration lazily.
1504 LLVMContext &C = Inst->getContext();
1505 CallInst *NewCall =
1506 CallInst::Create(getReleaseCallee(F.getParent()),
1507 Call->getArgOperand(0), "", Call);
1508 NewCall->setMetadata(ImpreciseReleaseMDKind,
1509 MDNode::get(C, ArrayRef<Value *>()));
Michael Gottesman10426b52013-01-07 21:26:07 +00001510
Michael Gottesman89279f82013-04-05 18:10:41 +00001511 DEBUG(dbgs() << "Replacing autorelease{,RV}(x) with objc_release(x) "
1512 "since x is otherwise unused.\nOld: " << *Call << "\nNew: "
1513 << *NewCall << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001514
John McCalld935e9c2011-06-15 23:37:01 +00001515 EraseInstruction(Call);
1516 Inst = NewCall;
1517 Class = IC_Release;
1518 }
1519 }
1520
1521 // For functions which can never be passed stack arguments, add
1522 // a tail keyword.
1523 if (IsAlwaysTail(Class)) {
1524 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +00001525 DEBUG(dbgs() << "Adding tail keyword to function since it can never be "
1526 "passed stack args: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001527 cast<CallInst>(Inst)->setTailCall();
1528 }
1529
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001530 // Ensure that functions that can never have a "tail" keyword due to the
1531 // semantics of ARC truly do not do so.
1532 if (IsNeverTail(Class)) {
1533 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +00001534 DEBUG(dbgs() << "Removing tail keyword from function: " << *Inst <<
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001535 "\n");
1536 cast<CallInst>(Inst)->setTailCall(false);
1537 }
1538
John McCalld935e9c2011-06-15 23:37:01 +00001539 // Set nounwind as needed.
1540 if (IsNoThrow(Class)) {
1541 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +00001542 DEBUG(dbgs() << "Found no throw class. Setting nounwind on: " << *Inst
1543 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001544 cast<CallInst>(Inst)->setDoesNotThrow();
1545 }
1546
1547 if (!IsNoopOnNull(Class)) {
1548 UsedInThisFunction |= 1 << Class;
1549 continue;
1550 }
1551
1552 const Value *Arg = GetObjCArg(Inst);
1553
1554 // ARC calls with null are no-ops. Delete them.
Michael Gottesman65c24812013-03-25 09:27:43 +00001555 if (IsNullOrUndef(Arg)) {
John McCalld935e9c2011-06-15 23:37:01 +00001556 Changed = true;
1557 ++NumNoops;
Michael Gottesman89279f82013-04-05 18:10:41 +00001558 DEBUG(dbgs() << "ARC calls with null are no-ops. Erasing: " << *Inst
1559 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001560 EraseInstruction(Inst);
1561 continue;
1562 }
1563
1564 // Keep track of which of retain, release, autorelease, and retain_block
1565 // are actually present in this function.
1566 UsedInThisFunction |= 1 << Class;
1567
1568 // If Arg is a PHI, and one or more incoming values to the
1569 // PHI are null, and the call is control-equivalent to the PHI, and there
1570 // are no relevant side effects between the PHI and the call, the call
1571 // could be pushed up to just those paths with non-null incoming values.
1572 // For now, don't bother splitting critical edges for this.
1573 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
1574 Worklist.push_back(std::make_pair(Inst, Arg));
1575 do {
1576 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
1577 Inst = Pair.first;
1578 Arg = Pair.second;
1579
1580 const PHINode *PN = dyn_cast<PHINode>(Arg);
1581 if (!PN) continue;
1582
1583 // Determine if the PHI has any null operands, or any incoming
1584 // critical edges.
1585 bool HasNull = false;
1586 bool HasCriticalEdges = false;
1587 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1588 Value *Incoming =
1589 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
Michael Gottesman65c24812013-03-25 09:27:43 +00001590 if (IsNullOrUndef(Incoming))
John McCalld935e9c2011-06-15 23:37:01 +00001591 HasNull = true;
1592 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
1593 .getNumSuccessors() != 1) {
1594 HasCriticalEdges = true;
1595 break;
1596 }
1597 }
1598 // If we have null operands and no critical edges, optimize.
1599 if (!HasCriticalEdges && HasNull) {
1600 SmallPtrSet<Instruction *, 4> DependingInstructions;
1601 SmallPtrSet<const BasicBlock *, 4> Visited;
1602
1603 // Check that there is nothing that cares about the reference
1604 // count between the call and the phi.
Dan Gohman8478d762012-04-13 00:59:57 +00001605 switch (Class) {
1606 case IC_Retain:
1607 case IC_RetainBlock:
1608 // These can always be moved up.
1609 break;
1610 case IC_Release:
Dan Gohman41375a32012-05-08 23:39:44 +00001611 // These can't be moved across things that care about the retain
1612 // count.
Dan Gohman8478d762012-04-13 00:59:57 +00001613 FindDependencies(NeedsPositiveRetainCount, Arg,
1614 Inst->getParent(), Inst,
1615 DependingInstructions, Visited, PA);
1616 break;
1617 case IC_Autorelease:
1618 // These can't be moved across autorelease pool scope boundaries.
1619 FindDependencies(AutoreleasePoolBoundary, Arg,
1620 Inst->getParent(), Inst,
1621 DependingInstructions, Visited, PA);
1622 break;
1623 case IC_RetainRV:
1624 case IC_AutoreleaseRV:
1625 // Don't move these; the RV optimization depends on the autoreleaseRV
1626 // being tail called, and the retainRV being immediately after a call
1627 // (which might still happen if we get lucky with codegen layout, but
1628 // it's not worth taking the chance).
1629 continue;
1630 default:
1631 llvm_unreachable("Invalid dependence flavor");
1632 }
1633
John McCalld935e9c2011-06-15 23:37:01 +00001634 if (DependingInstructions.size() == 1 &&
1635 *DependingInstructions.begin() == PN) {
1636 Changed = true;
1637 ++NumPartialNoops;
1638 // Clone the call into each predecessor that has a non-null value.
1639 CallInst *CInst = cast<CallInst>(Inst);
Chris Lattner229907c2011-07-18 04:54:35 +00001640 Type *ParamTy = CInst->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001641 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1642 Value *Incoming =
1643 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
Michael Gottesman65c24812013-03-25 09:27:43 +00001644 if (!IsNullOrUndef(Incoming)) {
John McCalld935e9c2011-06-15 23:37:01 +00001645 CallInst *Clone = cast<CallInst>(CInst->clone());
1646 Value *Op = PN->getIncomingValue(i);
1647 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
1648 if (Op->getType() != ParamTy)
1649 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
1650 Clone->setArgOperand(0, Op);
1651 Clone->insertBefore(InsertPos);
Michael Gottesmanc189a392013-01-09 19:23:24 +00001652
Michael Gottesman89279f82013-04-05 18:10:41 +00001653 DEBUG(dbgs() << "Cloning "
Michael Gottesmanc189a392013-01-09 19:23:24 +00001654 << *CInst << "\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00001655 "And inserting clone at " << *InsertPos << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001656 Worklist.push_back(std::make_pair(Clone, Incoming));
1657 }
1658 }
1659 // Erase the original call.
Michael Gottesmanc189a392013-01-09 19:23:24 +00001660 DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001661 EraseInstruction(CInst);
1662 continue;
1663 }
1664 }
1665 } while (!Worklist.empty());
1666 }
1667}
1668
Michael Gottesman323964c2013-04-18 05:39:45 +00001669/// If we have a top down pointer in the S_Use state, make sure that there are
1670/// no CFG hazards by checking the states of various bottom up pointers.
1671static void CheckForUseCFGHazard(const Sequence SuccSSeq,
1672 const bool SuccSRRIKnownSafe,
1673 PtrState &S,
1674 bool &SomeSuccHasSame,
1675 bool &AllSuccsHaveSame,
1676 bool &ShouldContinue) {
1677 switch (SuccSSeq) {
1678 case S_CanRelease: {
1679 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
1680 S.ClearSequenceProgress();
1681 break;
1682 }
1683 ShouldContinue = true;
1684 break;
1685 }
1686 case S_Use:
1687 SomeSuccHasSame = true;
1688 break;
1689 case S_Stop:
1690 case S_Release:
1691 case S_MovableRelease:
1692 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
1693 AllSuccsHaveSame = false;
1694 break;
1695 case S_Retain:
1696 llvm_unreachable("bottom-up pointer in retain state!");
1697 case S_None:
1698 llvm_unreachable("This should have been handled earlier.");
1699 }
1700}
1701
1702/// If we have a Top Down pointer in the S_CanRelease state, make sure that
1703/// there are no CFG hazards by checking the states of various bottom up
1704/// pointers.
1705static void CheckForCanReleaseCFGHazard(const Sequence SuccSSeq,
1706 const bool SuccSRRIKnownSafe,
1707 PtrState &S,
1708 bool &SomeSuccHasSame,
1709 bool &AllSuccsHaveSame) {
1710 switch (SuccSSeq) {
1711 case S_CanRelease:
1712 SomeSuccHasSame = true;
1713 break;
1714 case S_Stop:
1715 case S_Release:
1716 case S_MovableRelease:
1717 case S_Use:
1718 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
1719 AllSuccsHaveSame = false;
1720 break;
1721 case S_Retain:
1722 llvm_unreachable("bottom-up pointer in retain state!");
1723 case S_None:
1724 llvm_unreachable("This should have been handled earlier.");
1725 }
1726}
1727
Michael Gottesman97e3df02013-01-14 00:35:14 +00001728/// Check for critical edges, loop boundaries, irreducible control flow, or
1729/// other CFG structures where moving code across the edge would result in it
1730/// being executed more.
John McCalld935e9c2011-06-15 23:37:01 +00001731void
1732ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
1733 DenseMap<const BasicBlock *, BBState> &BBStates,
1734 BBState &MyStates) const {
1735 // If any top-down local-use or possible-dec has a succ which is earlier in
1736 // the sequence, forget it.
Dan Gohman55b06742012-03-02 01:13:53 +00001737 for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
Michael Gottesman323964c2013-04-18 05:39:45 +00001738 E = MyStates.top_down_ptr_end(); I != E; ++I) {
1739 PtrState &S = I->second;
1740 const Sequence Seq = I->second.GetSeq();
Dan Gohman0155f302012-02-17 18:59:53 +00001741
Michael Gottesman323964c2013-04-18 05:39:45 +00001742 // We only care about S_Retain, S_CanRelease, and S_Use.
1743 if (Seq == S_None)
1744 continue;
Dan Gohman0155f302012-02-17 18:59:53 +00001745
Michael Gottesman323964c2013-04-18 05:39:45 +00001746 // Make sure that if extra top down states are added in the future that this
1747 // code is updated to handle it.
1748 assert((Seq == S_Retain || Seq == S_CanRelease || Seq == S_Use) &&
1749 "Unknown top down sequence state.");
1750
1751 const Value *Arg = I->first;
1752 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
1753 bool SomeSuccHasSame = false;
1754 bool AllSuccsHaveSame = true;
1755
1756 succ_const_iterator SI(TI), SE(TI, false);
1757
1758 for (; SI != SE; ++SI) {
1759 // If VisitBottomUp has pointer information for this successor, take
1760 // what we know about it.
1761 const DenseMap<const BasicBlock *, BBState>::iterator BBI =
1762 BBStates.find(*SI);
1763 assert(BBI != BBStates.end());
1764 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
1765 const Sequence SuccSSeq = SuccS.GetSeq();
1766
1767 // If bottom up, the pointer is in an S_None state, clear the sequence
1768 // progress since the sequence in the bottom up state finished
1769 // suggesting a mismatch in between retains/releases. This is true for
1770 // all three cases that we are handling here: S_Retain, S_Use, and
1771 // S_CanRelease.
1772 if (SuccSSeq == S_None) {
Dan Gohman12130272011-08-12 00:26:31 +00001773 S.ClearSequenceProgress();
Michael Gottesman323964c2013-04-18 05:39:45 +00001774 continue;
1775 }
1776
1777 // If we have S_Use or S_CanRelease, perform our check for cfg hazard
1778 // checks.
1779 const bool SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
1780
1781 // *NOTE* We do not use Seq from above here since we are allowing for
1782 // S.GetSeq() to change while we are visiting basic blocks.
1783 switch(S.GetSeq()) {
1784 case S_Use: {
1785 bool ShouldContinue = false;
1786 CheckForUseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S,
1787 SomeSuccHasSame, AllSuccsHaveSame,
1788 ShouldContinue);
1789 if (ShouldContinue)
1790 continue;
1791 break;
1792 }
1793 case S_CanRelease: {
1794 CheckForCanReleaseCFGHazard(SuccSSeq, SuccSRRIKnownSafe,
1795 S, SomeSuccHasSame,
1796 AllSuccsHaveSame);
1797 break;
1798 }
1799 case S_Retain:
1800 case S_None:
1801 case S_Stop:
1802 case S_Release:
1803 case S_MovableRelease:
1804 break;
1805 }
John McCalld935e9c2011-06-15 23:37:01 +00001806 }
Michael Gottesman323964c2013-04-18 05:39:45 +00001807
1808 // If the state at the other end of any of the successor edges
1809 // matches the current state, require all edges to match. This
1810 // guards against loops in the middle of a sequence.
1811 if (SomeSuccHasSame && !AllSuccsHaveSame)
1812 S.ClearSequenceProgress();
1813 }
John McCalld935e9c2011-06-15 23:37:01 +00001814}
1815
1816bool
Dan Gohman817a7c62012-03-22 18:24:56 +00001817ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
Dan Gohman5c70fad2012-03-23 17:47:54 +00001818 BasicBlock *BB,
Dan Gohman817a7c62012-03-22 18:24:56 +00001819 MapVector<Value *, RRInfo> &Retains,
1820 BBState &MyStates) {
1821 bool NestingDetected = false;
1822 InstructionClass Class = GetInstructionClass(Inst);
1823 const Value *Arg = 0;
Michael Gottesman79249972013-04-05 23:46:45 +00001824
Michael Gottesman1d8d2572013-04-05 22:54:28 +00001825 DEBUG(dbgs() << "Class: " << Class << "\n");
Michael Gottesman79249972013-04-05 23:46:45 +00001826
Dan Gohman817a7c62012-03-22 18:24:56 +00001827 switch (Class) {
1828 case IC_Release: {
1829 Arg = GetObjCArg(Inst);
1830
1831 PtrState &S = MyStates.getPtrBottomUpState(Arg);
1832
1833 // If we see two releases in a row on the same pointer. If so, make
1834 // a note, and we'll cicle back to revisit it after we've
1835 // hopefully eliminated the second release, which may allow us to
1836 // eliminate the first release too.
1837 // Theoretically we could implement removal of nested retain+release
1838 // pairs by making PtrState hold a stack of states, but this is
1839 // simple and avoids adding overhead for the non-nested case.
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001840 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001841 DEBUG(dbgs() << "Found nested releases (i.e. a release pair)\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00001842 NestingDetected = true;
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001843 }
Dan Gohman817a7c62012-03-22 18:24:56 +00001844
Dan Gohman817a7c62012-03-22 18:24:56 +00001845 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001846 Sequence NewSeq = ReleaseMetadata ? S_MovableRelease : S_Release;
1847 ANNOTATE_BOTTOMUP(Inst, Arg, S.GetSeq(), NewSeq);
1848 S.ResetSequenceProgress(NewSeq);
Dan Gohman817a7c62012-03-22 18:24:56 +00001849 S.RRI.ReleaseMetadata = ReleaseMetadata;
Michael Gottesman07beea42013-03-23 05:31:01 +00001850 S.RRI.KnownSafe = S.HasKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001851 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
1852 S.RRI.Calls.insert(Inst);
Dan Gohmandf476e52012-09-04 23:16:20 +00001853 S.SetKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001854 break;
1855 }
1856 case IC_RetainBlock:
Michael Gottesman158fdf62013-03-28 20:11:19 +00001857 // In OptimizeIndividualCalls, we have strength reduced all optimizable
1858 // objc_retainBlocks to objc_retains. Thus at this point any
1859 // objc_retainBlocks that we see are not optimizable.
1860 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001861 case IC_Retain:
1862 case IC_RetainRV: {
1863 Arg = GetObjCArg(Inst);
1864
1865 PtrState &S = MyStates.getPtrBottomUpState(Arg);
Dan Gohman62079b42012-04-25 00:50:46 +00001866 S.SetKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001867
Michael Gottesman81b1d432013-03-26 00:42:04 +00001868 Sequence OldSeq = S.GetSeq();
1869 switch (OldSeq) {
Dan Gohman817a7c62012-03-22 18:24:56 +00001870 case S_Stop:
1871 case S_Release:
1872 case S_MovableRelease:
1873 case S_Use:
Michael Gottesman1d8d2572013-04-05 22:54:28 +00001874 // If OldSeq is not S_Use or OldSeq is S_Use and we are tracking an
1875 // imprecise release, clear our reverse insertion points.
1876 if (OldSeq != S_Use || S.RRI.IsTrackingImpreciseReleases())
1877 S.RRI.ReverseInsertPts.clear();
Dan Gohman817a7c62012-03-22 18:24:56 +00001878 // FALL THROUGH
1879 case S_CanRelease:
1880 // Don't do retain+release tracking for IC_RetainRV, because it's
1881 // better to let it remain as the first instruction after a call.
Michael Gottesmanba648592013-03-28 23:08:44 +00001882 if (Class != IC_RetainRV)
Dan Gohman817a7c62012-03-22 18:24:56 +00001883 Retains[Inst] = S.RRI;
Dan Gohman817a7c62012-03-22 18:24:56 +00001884 S.ClearSequenceProgress();
1885 break;
1886 case S_None:
1887 break;
1888 case S_Retain:
1889 llvm_unreachable("bottom-up pointer in retain state!");
1890 }
Michael Gottesman79249972013-04-05 23:46:45 +00001891 ANNOTATE_BOTTOMUP(Inst, Arg, OldSeq, S.GetSeq());
Michael Gottesman31ba23a2013-04-05 22:54:32 +00001892 // A retain moving bottom up can be a use.
1893 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001894 }
1895 case IC_AutoreleasepoolPop:
1896 // Conservatively, clear MyStates for all known pointers.
1897 MyStates.clearBottomUpPointers();
1898 return NestingDetected;
1899 case IC_AutoreleasepoolPush:
1900 case IC_None:
1901 // These are irrelevant.
1902 return NestingDetected;
1903 default:
1904 break;
1905 }
1906
1907 // Consider any other possible effects of this instruction on each
1908 // pointer being tracked.
1909 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
1910 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
1911 const Value *Ptr = MI->first;
1912 if (Ptr == Arg)
1913 continue; // Handled above.
1914 PtrState &S = MI->second;
1915 Sequence Seq = S.GetSeq();
1916
1917 // Check for possible releases.
1918 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001919 DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr
1920 << "\n");
Michael Gottesman764b1cf2013-03-23 05:46:19 +00001921 S.ClearKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001922 switch (Seq) {
1923 case S_Use:
1924 S.SetSeq(S_CanRelease);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001925 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S.GetSeq());
Dan Gohman817a7c62012-03-22 18:24:56 +00001926 continue;
1927 case S_CanRelease:
1928 case S_Release:
1929 case S_MovableRelease:
1930 case S_Stop:
1931 case S_None:
1932 break;
1933 case S_Retain:
1934 llvm_unreachable("bottom-up pointer in retain state!");
1935 }
1936 }
1937
1938 // Check for possible direct uses.
1939 switch (Seq) {
1940 case S_Release:
1941 case S_MovableRelease:
1942 if (CanUse(Inst, Ptr, PA, Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001943 DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr
1944 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00001945 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohman5c70fad2012-03-23 17:47:54 +00001946 // If this is an invoke instruction, we're scanning it as part of
1947 // one of its successor blocks, since we can't insert code after it
1948 // in its own block, and we don't want to split critical edges.
1949 if (isa<InvokeInst>(Inst))
1950 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
1951 else
Francois Pichet4b9ab742012-03-24 01:36:37 +00001952 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohman817a7c62012-03-22 18:24:56 +00001953 S.SetSeq(S_Use);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001954 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
John McCall20182ac2013-03-22 21:38:36 +00001955 } else if (Seq == S_Release && IsUser(Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001956 DEBUG(dbgs() << "PreciseReleaseUse: Seq: " << Seq << "; " << *Ptr
1957 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00001958 // Non-movable releases depend on any possible objc pointer use.
1959 S.SetSeq(S_Stop);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001960 ANNOTATE_BOTTOMUP(Inst, Ptr, S_Release, S_Stop);
Dan Gohman817a7c62012-03-22 18:24:56 +00001961 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohman5c70fad2012-03-23 17:47:54 +00001962 // As above; handle invoke specially.
1963 if (isa<InvokeInst>(Inst))
1964 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
1965 else
Francois Pichet4b9ab742012-03-24 01:36:37 +00001966 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohman817a7c62012-03-22 18:24:56 +00001967 }
1968 break;
1969 case S_Stop:
Michael Gottesman81b1d432013-03-26 00:42:04 +00001970 if (CanUse(Inst, Ptr, PA, Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001971 DEBUG(dbgs() << "PreciseStopUse: Seq: " << Seq << "; " << *Ptr
1972 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00001973 S.SetSeq(S_Use);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001974 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
1975 }
Dan Gohman817a7c62012-03-22 18:24:56 +00001976 break;
1977 case S_CanRelease:
1978 case S_Use:
1979 case S_None:
1980 break;
1981 case S_Retain:
1982 llvm_unreachable("bottom-up pointer in retain state!");
1983 }
1984 }
1985
1986 return NestingDetected;
1987}
1988
1989bool
John McCalld935e9c2011-06-15 23:37:01 +00001990ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
1991 DenseMap<const BasicBlock *, BBState> &BBStates,
1992 MapVector<Value *, RRInfo> &Retains) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001993
1994 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitBottomUp ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00001995
John McCalld935e9c2011-06-15 23:37:01 +00001996 bool NestingDetected = false;
1997 BBState &MyStates = BBStates[BB];
1998
1999 // Merge the states from each successor to compute the initial state
2000 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00002001 BBState::edge_iterator SI(MyStates.succ_begin()),
2002 SE(MyStates.succ_end());
2003 if (SI != SE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002004 const BasicBlock *Succ = *SI;
2005 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
2006 assert(I != BBStates.end());
2007 MyStates.InitFromSucc(I->second);
2008 ++SI;
2009 for (; SI != SE; ++SI) {
2010 Succ = *SI;
2011 I = BBStates.find(Succ);
2012 assert(I != BBStates.end());
2013 MyStates.MergeSucc(I->second);
2014 }
Michael Gottesman60f6b282013-03-29 05:13:07 +00002015 }
Michael Gottesmancd4de0f2013-03-26 00:42:09 +00002016
Michael Gottesman43e7e002013-04-03 22:41:59 +00002017 // If ARC Annotations are enabled, output the current state of pointers at the
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002018 // bottom of the basic block.
Michael Gottesman43e7e002013-04-03 22:41:59 +00002019 ANNOTATE_BOTTOMUP_BBEND(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002020
John McCalld935e9c2011-06-15 23:37:01 +00002021 // Visit all the instructions, bottom-up.
2022 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2023 Instruction *Inst = llvm::prior(I);
Dan Gohman5c70fad2012-03-23 17:47:54 +00002024
2025 // Invoke instructions are visited as part of their successors (below).
2026 if (isa<InvokeInst>(Inst))
2027 continue;
2028
Michael Gottesman89279f82013-04-05 18:10:41 +00002029 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00002030
Dan Gohman5c70fad2012-03-23 17:47:54 +00002031 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
2032 }
2033
Dan Gohmandae33492012-04-27 18:56:31 +00002034 // If there's a predecessor with an invoke, visit the invoke as if it were
2035 // part of this block, since we can't insert code after an invoke in its own
2036 // block, and we don't want to split critical edges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002037 for (BBState::edge_iterator PI(MyStates.pred_begin()),
2038 PE(MyStates.pred_end()); PI != PE; ++PI) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00002039 BasicBlock *Pred = *PI;
Dan Gohmandae33492012-04-27 18:56:31 +00002040 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
2041 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
Dan Gohman817a7c62012-03-22 18:24:56 +00002042 }
John McCalld935e9c2011-06-15 23:37:01 +00002043
Michael Gottesman43e7e002013-04-03 22:41:59 +00002044 // If ARC Annotations are enabled, output the current state of pointers at the
2045 // top of the basic block.
2046 ANNOTATE_BOTTOMUP_BBSTART(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002047
Dan Gohman817a7c62012-03-22 18:24:56 +00002048 return NestingDetected;
2049}
John McCalld935e9c2011-06-15 23:37:01 +00002050
Dan Gohman817a7c62012-03-22 18:24:56 +00002051bool
2052ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
2053 DenseMap<Value *, RRInfo> &Releases,
2054 BBState &MyStates) {
2055 bool NestingDetected = false;
2056 InstructionClass Class = GetInstructionClass(Inst);
2057 const Value *Arg = 0;
John McCalld935e9c2011-06-15 23:37:01 +00002058
Dan Gohman817a7c62012-03-22 18:24:56 +00002059 switch (Class) {
2060 case IC_RetainBlock:
Michael Gottesman158fdf62013-03-28 20:11:19 +00002061 // In OptimizeIndividualCalls, we have strength reduced all optimizable
2062 // objc_retainBlocks to objc_retains. Thus at this point any
2063 // objc_retainBlocks that we see are not optimizable.
2064 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00002065 case IC_Retain:
2066 case IC_RetainRV: {
2067 Arg = GetObjCArg(Inst);
2068
2069 PtrState &S = MyStates.getPtrTopDownState(Arg);
2070
2071 // Don't do retain+release tracking for IC_RetainRV, because it's
2072 // better to let it remain as the first instruction after a call.
2073 if (Class != IC_RetainRV) {
2074 // If we see two retains in a row on the same pointer. If so, make
John McCalld935e9c2011-06-15 23:37:01 +00002075 // a note, and we'll cicle back to revisit it after we've
Dan Gohman817a7c62012-03-22 18:24:56 +00002076 // hopefully eliminated the second retain, which may allow us to
2077 // eliminate the first retain too.
John McCalld935e9c2011-06-15 23:37:01 +00002078 // Theoretically we could implement removal of nested retain+release
2079 // pairs by making PtrState hold a stack of states, but this is
2080 // simple and avoids adding overhead for the non-nested case.
Dan Gohman817a7c62012-03-22 18:24:56 +00002081 if (S.GetSeq() == S_Retain)
John McCalld935e9c2011-06-15 23:37:01 +00002082 NestingDetected = true;
2083
Michael Gottesman81b1d432013-03-26 00:42:04 +00002084 ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_Retain);
Dan Gohman62079b42012-04-25 00:50:46 +00002085 S.ResetSequenceProgress(S_Retain);
Michael Gottesman07beea42013-03-23 05:31:01 +00002086 S.RRI.KnownSafe = S.HasKnownPositiveRefCount();
John McCalld935e9c2011-06-15 23:37:01 +00002087 S.RRI.Calls.insert(Inst);
John McCalld935e9c2011-06-15 23:37:01 +00002088 }
John McCalld935e9c2011-06-15 23:37:01 +00002089
Dan Gohmandf476e52012-09-04 23:16:20 +00002090 S.SetKnownPositiveRefCount();
Dan Gohmanf64ff8e2012-07-23 19:27:31 +00002091
2092 // A retain can be a potential use; procede to the generic checking
2093 // code below.
2094 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00002095 }
2096 case IC_Release: {
2097 Arg = GetObjCArg(Inst);
2098
2099 PtrState &S = MyStates.getPtrTopDownState(Arg);
Michael Gottesman764b1cf2013-03-23 05:46:19 +00002100 S.ClearKnownPositiveRefCount();
Michael Gottesman79249972013-04-05 23:46:45 +00002101
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002102 Sequence OldSeq = S.GetSeq();
Michael Gottesman79249972013-04-05 23:46:45 +00002103
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002104 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
Michael Gottesman79249972013-04-05 23:46:45 +00002105
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002106 switch (OldSeq) {
Dan Gohman817a7c62012-03-22 18:24:56 +00002107 case S_Retain:
2108 case S_CanRelease:
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002109 if (OldSeq == S_Retain || ReleaseMetadata != 0)
2110 S.RRI.ReverseInsertPts.clear();
Dan Gohman817a7c62012-03-22 18:24:56 +00002111 // FALL THROUGH
2112 case S_Use:
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002113 S.RRI.ReleaseMetadata = ReleaseMetadata;
Dan Gohman817a7c62012-03-22 18:24:56 +00002114 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2115 Releases[Inst] = S.RRI;
Michael Gottesman81b1d432013-03-26 00:42:04 +00002116 ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_None);
Dan Gohman817a7c62012-03-22 18:24:56 +00002117 S.ClearSequenceProgress();
2118 break;
2119 case S_None:
2120 break;
2121 case S_Stop:
2122 case S_Release:
2123 case S_MovableRelease:
2124 llvm_unreachable("top-down pointer in release state!");
2125 }
2126 break;
2127 }
2128 case IC_AutoreleasepoolPop:
2129 // Conservatively, clear MyStates for all known pointers.
2130 MyStates.clearTopDownPointers();
2131 return NestingDetected;
2132 case IC_AutoreleasepoolPush:
2133 case IC_None:
2134 // These are irrelevant.
2135 return NestingDetected;
2136 default:
2137 break;
2138 }
2139
2140 // Consider any other possible effects of this instruction on each
2141 // pointer being tracked.
2142 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
2143 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
2144 const Value *Ptr = MI->first;
2145 if (Ptr == Arg)
2146 continue; // Handled above.
2147 PtrState &S = MI->second;
2148 Sequence Seq = S.GetSeq();
2149
2150 // Check for possible releases.
2151 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Michael Gottesmanbab49e972013-04-05 18:26:08 +00002152 DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr
Michael Gottesman79249972013-04-05 23:46:45 +00002153 << "\n");
Michael Gottesman764b1cf2013-03-23 05:46:19 +00002154 S.ClearKnownPositiveRefCount();
John McCalld935e9c2011-06-15 23:37:01 +00002155 switch (Seq) {
Dan Gohman817a7c62012-03-22 18:24:56 +00002156 case S_Retain:
2157 S.SetSeq(S_CanRelease);
Michael Gottesman81b1d432013-03-26 00:42:04 +00002158 ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_CanRelease);
Dan Gohman817a7c62012-03-22 18:24:56 +00002159 assert(S.RRI.ReverseInsertPts.empty());
2160 S.RRI.ReverseInsertPts.insert(Inst);
2161
2162 // One call can't cause a transition from S_Retain to S_CanRelease
2163 // and S_CanRelease to S_Use. If we've made the first transition,
2164 // we're done.
2165 continue;
John McCalld935e9c2011-06-15 23:37:01 +00002166 case S_Use:
Dan Gohman817a7c62012-03-22 18:24:56 +00002167 case S_CanRelease:
John McCalld935e9c2011-06-15 23:37:01 +00002168 case S_None:
2169 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00002170 case S_Stop:
2171 case S_Release:
2172 case S_MovableRelease:
2173 llvm_unreachable("top-down pointer in release state!");
John McCalld935e9c2011-06-15 23:37:01 +00002174 }
2175 }
Dan Gohman817a7c62012-03-22 18:24:56 +00002176
2177 // Check for possible direct uses.
2178 switch (Seq) {
2179 case S_CanRelease:
Michael Gottesman81b1d432013-03-26 00:42:04 +00002180 if (CanUse(Inst, Ptr, PA, Class)) {
Michael Gottesmanbab49e972013-04-05 18:26:08 +00002181 DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr
2182 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00002183 S.SetSeq(S_Use);
Michael Gottesman81b1d432013-03-26 00:42:04 +00002184 ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_Use);
2185 }
Dan Gohman817a7c62012-03-22 18:24:56 +00002186 break;
2187 case S_Retain:
2188 case S_Use:
2189 case S_None:
2190 break;
2191 case S_Stop:
2192 case S_Release:
2193 case S_MovableRelease:
2194 llvm_unreachable("top-down pointer in release state!");
2195 }
John McCalld935e9c2011-06-15 23:37:01 +00002196 }
2197
2198 return NestingDetected;
2199}
2200
2201bool
2202ObjCARCOpt::VisitTopDown(BasicBlock *BB,
2203 DenseMap<const BasicBlock *, BBState> &BBStates,
2204 DenseMap<Value *, RRInfo> &Releases) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002205 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitTopDown ==\n");
John McCalld935e9c2011-06-15 23:37:01 +00002206 bool NestingDetected = false;
2207 BBState &MyStates = BBStates[BB];
2208
2209 // Merge the states from each predecessor to compute the initial state
2210 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00002211 BBState::edge_iterator PI(MyStates.pred_begin()),
2212 PE(MyStates.pred_end());
2213 if (PI != PE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002214 const BasicBlock *Pred = *PI;
2215 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
2216 assert(I != BBStates.end());
2217 MyStates.InitFromPred(I->second);
2218 ++PI;
2219 for (; PI != PE; ++PI) {
2220 Pred = *PI;
2221 I = BBStates.find(Pred);
2222 assert(I != BBStates.end());
2223 MyStates.MergePred(I->second);
2224 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002225 }
John McCalld935e9c2011-06-15 23:37:01 +00002226
Michael Gottesman43e7e002013-04-03 22:41:59 +00002227 // If ARC Annotations are enabled, output the current state of pointers at the
2228 // top of the basic block.
2229 ANNOTATE_TOPDOWN_BBSTART(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002230
John McCalld935e9c2011-06-15 23:37:01 +00002231 // Visit all the instructions, top-down.
2232 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2233 Instruction *Inst = I;
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00002234
Michael Gottesman89279f82013-04-05 18:10:41 +00002235 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00002236
Dan Gohman817a7c62012-03-22 18:24:56 +00002237 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00002238 }
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002239
Michael Gottesman43e7e002013-04-03 22:41:59 +00002240 // If ARC Annotations are enabled, output the current state of pointers at the
2241 // bottom of the basic block.
2242 ANNOTATE_TOPDOWN_BBEND(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002243
Michael Gottesmanffef24f2013-04-17 20:48:01 +00002244#ifdef ARC_ANNOTATIONS
Michael Gottesmanadb921a2013-04-17 21:03:53 +00002245 if (!(EnableARCAnnotations && DisableCheckForCFGHazards))
Michael Gottesmanffef24f2013-04-17 20:48:01 +00002246#endif
John McCalld935e9c2011-06-15 23:37:01 +00002247 CheckForCFGHazards(BB, BBStates, MyStates);
2248 return NestingDetected;
2249}
2250
Dan Gohmana53a12c2011-12-12 19:42:25 +00002251static void
2252ComputePostOrders(Function &F,
2253 SmallVectorImpl<BasicBlock *> &PostOrder,
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002254 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
2255 unsigned NoObjCARCExceptionsMDKind,
2256 DenseMap<const BasicBlock *, BBState> &BBStates) {
Michael Gottesman97e3df02013-01-14 00:35:14 +00002257 /// The visited set, for doing DFS walks.
Dan Gohmana53a12c2011-12-12 19:42:25 +00002258 SmallPtrSet<BasicBlock *, 16> Visited;
2259
2260 // Do DFS, computing the PostOrder.
2261 SmallPtrSet<BasicBlock *, 16> OnStack;
2262 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002263
2264 // Functions always have exactly one entry block, and we don't have
2265 // any other block that we treat like an entry block.
Dan Gohmana53a12c2011-12-12 19:42:25 +00002266 BasicBlock *EntryBB = &F.getEntryBlock();
Dan Gohman41375a32012-05-08 23:39:44 +00002267 BBState &MyStates = BBStates[EntryBB];
2268 MyStates.SetAsEntry();
2269 TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
2270 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
Dan Gohmana53a12c2011-12-12 19:42:25 +00002271 Visited.insert(EntryBB);
2272 OnStack.insert(EntryBB);
2273 do {
2274 dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002275 BasicBlock *CurrBB = SuccStack.back().first;
2276 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
2277 succ_iterator SE(TI, false);
Dan Gohman41375a32012-05-08 23:39:44 +00002278
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002279 while (SuccStack.back().second != SE) {
2280 BasicBlock *SuccBB = *SuccStack.back().second++;
2281 if (Visited.insert(SuccBB)) {
Dan Gohman41375a32012-05-08 23:39:44 +00002282 TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
2283 SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002284 BBStates[CurrBB].addSucc(SuccBB);
Dan Gohman41375a32012-05-08 23:39:44 +00002285 BBState &SuccStates = BBStates[SuccBB];
2286 SuccStates.addPred(CurrBB);
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002287 OnStack.insert(SuccBB);
Dan Gohmana53a12c2011-12-12 19:42:25 +00002288 goto dfs_next_succ;
2289 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002290
2291 if (!OnStack.count(SuccBB)) {
2292 BBStates[CurrBB].addSucc(SuccBB);
2293 BBStates[SuccBB].addPred(CurrBB);
2294 }
Dan Gohmana53a12c2011-12-12 19:42:25 +00002295 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002296 OnStack.erase(CurrBB);
2297 PostOrder.push_back(CurrBB);
2298 SuccStack.pop_back();
Dan Gohmana53a12c2011-12-12 19:42:25 +00002299 } while (!SuccStack.empty());
2300
2301 Visited.clear();
2302
Dan Gohmana53a12c2011-12-12 19:42:25 +00002303 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002304 // Functions may have many exits, and there also blocks which we treat
2305 // as exits due to ignored edges.
2306 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
2307 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
2308 BasicBlock *ExitBB = I;
2309 BBState &MyStates = BBStates[ExitBB];
2310 if (!MyStates.isExit())
2311 continue;
2312
Dan Gohmandae33492012-04-27 18:56:31 +00002313 MyStates.SetAsExit();
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002314
2315 PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00002316 Visited.insert(ExitBB);
2317 while (!PredStack.empty()) {
2318 reverse_dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002319 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
2320 while (PredStack.back().second != PE) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00002321 BasicBlock *BB = *PredStack.back().second++;
Dan Gohmana53a12c2011-12-12 19:42:25 +00002322 if (Visited.insert(BB)) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002323 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00002324 goto reverse_dfs_next_succ;
2325 }
2326 }
2327 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
2328 }
2329 }
2330}
2331
Michael Gottesman97e3df02013-01-14 00:35:14 +00002332// Visit the function both top-down and bottom-up.
John McCalld935e9c2011-06-15 23:37:01 +00002333bool
2334ObjCARCOpt::Visit(Function &F,
2335 DenseMap<const BasicBlock *, BBState> &BBStates,
2336 MapVector<Value *, RRInfo> &Retains,
2337 DenseMap<Value *, RRInfo> &Releases) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00002338
2339 // Use reverse-postorder traversals, because we magically know that loops
2340 // will be well behaved, i.e. they won't repeatedly call retain on a single
2341 // pointer without doing a release. We can't use the ReversePostOrderTraversal
2342 // class here because we want the reverse-CFG postorder to consider each
2343 // function exit point, and we want to ignore selected cycle edges.
2344 SmallVector<BasicBlock *, 16> PostOrder;
2345 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002346 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
2347 NoObjCARCExceptionsMDKind,
2348 BBStates);
Dan Gohmana53a12c2011-12-12 19:42:25 +00002349
2350 // Use reverse-postorder on the reverse CFG for bottom-up.
John McCalld935e9c2011-06-15 23:37:01 +00002351 bool BottomUpNestingDetected = false;
Dan Gohmanc57b58c2011-08-18 21:27:42 +00002352 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
Dan Gohmana53a12c2011-12-12 19:42:25 +00002353 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
2354 I != E; ++I)
2355 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
John McCalld935e9c2011-06-15 23:37:01 +00002356
Dan Gohmana53a12c2011-12-12 19:42:25 +00002357 // Use reverse-postorder for top-down.
John McCalld935e9c2011-06-15 23:37:01 +00002358 bool TopDownNestingDetected = false;
Dan Gohmana53a12c2011-12-12 19:42:25 +00002359 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2360 PostOrder.rbegin(), E = PostOrder.rend();
2361 I != E; ++I)
2362 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
John McCalld935e9c2011-06-15 23:37:01 +00002363
2364 return TopDownNestingDetected && BottomUpNestingDetected;
2365}
2366
Michael Gottesman97e3df02013-01-14 00:35:14 +00002367/// Move the calls in RetainsToMove and ReleasesToMove.
John McCalld935e9c2011-06-15 23:37:01 +00002368void ObjCARCOpt::MoveCalls(Value *Arg,
2369 RRInfo &RetainsToMove,
2370 RRInfo &ReleasesToMove,
2371 MapVector<Value *, RRInfo> &Retains,
2372 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman6320f522011-07-22 22:29:21 +00002373 SmallVectorImpl<Instruction *> &DeadInsts,
Michael Gottesman79249972013-04-05 23:46:45 +00002374 Module *M) {
Chris Lattner229907c2011-07-18 04:54:35 +00002375 Type *ArgTy = Arg->getType();
Dan Gohman6320f522011-07-22 22:29:21 +00002376 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
Michael Gottesman79249972013-04-05 23:46:45 +00002377
Michael Gottesman89279f82013-04-05 18:10:41 +00002378 DEBUG(dbgs() << "== ObjCARCOpt::MoveCalls ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00002379
John McCalld935e9c2011-06-15 23:37:01 +00002380 // Insert the new retain and release calls.
2381 for (SmallPtrSet<Instruction *, 2>::const_iterator
2382 PI = ReleasesToMove.ReverseInsertPts.begin(),
2383 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2384 Instruction *InsertPt = *PI;
2385 Value *MyArg = ArgTy == ParamTy ? Arg :
2386 new BitCastInst(Arg, ParamTy, "", InsertPt);
2387 CallInst *Call =
Michael Gottesmanba648592013-03-28 23:08:44 +00002388 CallInst::Create(getRetainCallee(M), MyArg, "", InsertPt);
John McCalld935e9c2011-06-15 23:37:01 +00002389 Call->setDoesNotThrow();
Michael Gottesmanba648592013-03-28 23:08:44 +00002390 Call->setTailCall();
Michael Gottesman60f6b282013-03-29 05:13:07 +00002391
Michael Gottesmandf110ac2013-04-21 00:30:50 +00002392 DEBUG(dbgs() << "Inserting new Retain: " << *Call << "\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00002393 "At insertion point: " << *InsertPt << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002394 }
2395 for (SmallPtrSet<Instruction *, 2>::const_iterator
2396 PI = RetainsToMove.ReverseInsertPts.begin(),
2397 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00002398 Instruction *InsertPt = *PI;
2399 Value *MyArg = ArgTy == ParamTy ? Arg :
2400 new BitCastInst(Arg, ParamTy, "", InsertPt);
2401 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
2402 "", InsertPt);
2403 // Attach a clang.imprecise_release metadata tag, if appropriate.
2404 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
2405 Call->setMetadata(ImpreciseReleaseMDKind, M);
2406 Call->setDoesNotThrow();
2407 if (ReleasesToMove.IsTailCallRelease)
2408 Call->setTailCall();
Michael Gottesmanc189a392013-01-09 19:23:24 +00002409
Michael Gottesman89279f82013-04-05 18:10:41 +00002410 DEBUG(dbgs() << "Inserting new Release: " << *Call << "\n"
2411 "At insertion point: " << *InsertPt << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002412 }
2413
2414 // Delete the original retain and release calls.
2415 for (SmallPtrSet<Instruction *, 2>::const_iterator
2416 AI = RetainsToMove.Calls.begin(),
2417 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
2418 Instruction *OrigRetain = *AI;
2419 Retains.blot(OrigRetain);
2420 DeadInsts.push_back(OrigRetain);
Michael Gottesman89279f82013-04-05 18:10:41 +00002421 DEBUG(dbgs() << "Deleting retain: " << *OrigRetain << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002422 }
2423 for (SmallPtrSet<Instruction *, 2>::const_iterator
2424 AI = ReleasesToMove.Calls.begin(),
2425 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
2426 Instruction *OrigRelease = *AI;
2427 Releases.erase(OrigRelease);
2428 DeadInsts.push_back(OrigRelease);
Michael Gottesman89279f82013-04-05 18:10:41 +00002429 DEBUG(dbgs() << "Deleting release: " << *OrigRelease << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002430 }
Michael Gottesman79249972013-04-05 23:46:45 +00002431
John McCalld935e9c2011-06-15 23:37:01 +00002432}
2433
Michael Gottesman9de6f962013-01-22 21:49:00 +00002434bool
2435ObjCARCOpt::ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState>
2436 &BBStates,
2437 MapVector<Value *, RRInfo> &Retains,
2438 DenseMap<Value *, RRInfo> &Releases,
2439 Module *M,
2440 SmallVector<Instruction *, 4> &NewRetains,
2441 SmallVector<Instruction *, 4> &NewReleases,
2442 SmallVector<Instruction *, 8> &DeadInsts,
2443 RRInfo &RetainsToMove,
2444 RRInfo &ReleasesToMove,
2445 Value *Arg,
2446 bool KnownSafe,
2447 bool &AnyPairsCompletelyEliminated) {
2448 // If a pair happens in a region where it is known that the reference count
2449 // is already incremented, we can similarly ignore possible decrements.
2450 bool KnownSafeTD = true, KnownSafeBU = true;
2451
2452 // Connect the dots between the top-down-collected RetainsToMove and
2453 // bottom-up-collected ReleasesToMove to form sets of related calls.
2454 // This is an iterative process so that we connect multiple releases
2455 // to multiple retains if needed.
2456 unsigned OldDelta = 0;
2457 unsigned NewDelta = 0;
2458 unsigned OldCount = 0;
2459 unsigned NewCount = 0;
2460 bool FirstRelease = true;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002461 for (;;) {
2462 for (SmallVectorImpl<Instruction *>::const_iterator
2463 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
2464 Instruction *NewRetain = *NI;
2465 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
2466 assert(It != Retains.end());
2467 const RRInfo &NewRetainRRI = It->second;
2468 KnownSafeTD &= NewRetainRRI.KnownSafe;
2469 for (SmallPtrSet<Instruction *, 2>::const_iterator
2470 LI = NewRetainRRI.Calls.begin(),
2471 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
2472 Instruction *NewRetainRelease = *LI;
2473 DenseMap<Value *, RRInfo>::const_iterator Jt =
2474 Releases.find(NewRetainRelease);
2475 if (Jt == Releases.end())
2476 return false;
2477 const RRInfo &NewRetainReleaseRRI = Jt->second;
2478 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
2479 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
2480 OldDelta -=
2481 BBStates[NewRetainRelease->getParent()].GetAllPathCount();
2482
2483 // Merge the ReleaseMetadata and IsTailCallRelease values.
2484 if (FirstRelease) {
2485 ReleasesToMove.ReleaseMetadata =
2486 NewRetainReleaseRRI.ReleaseMetadata;
2487 ReleasesToMove.IsTailCallRelease =
2488 NewRetainReleaseRRI.IsTailCallRelease;
2489 FirstRelease = false;
2490 } else {
2491 if (ReleasesToMove.ReleaseMetadata !=
2492 NewRetainReleaseRRI.ReleaseMetadata)
2493 ReleasesToMove.ReleaseMetadata = 0;
2494 if (ReleasesToMove.IsTailCallRelease !=
2495 NewRetainReleaseRRI.IsTailCallRelease)
2496 ReleasesToMove.IsTailCallRelease = false;
2497 }
2498
2499 // Collect the optimal insertion points.
2500 if (!KnownSafe)
2501 for (SmallPtrSet<Instruction *, 2>::const_iterator
2502 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
2503 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
2504 RI != RE; ++RI) {
2505 Instruction *RIP = *RI;
2506 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
2507 NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
2508 }
2509 NewReleases.push_back(NewRetainRelease);
2510 }
2511 }
2512 }
2513 NewRetains.clear();
2514 if (NewReleases.empty()) break;
2515
2516 // Back the other way.
2517 for (SmallVectorImpl<Instruction *>::const_iterator
2518 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
2519 Instruction *NewRelease = *NI;
2520 DenseMap<Value *, RRInfo>::const_iterator It =
2521 Releases.find(NewRelease);
2522 assert(It != Releases.end());
2523 const RRInfo &NewReleaseRRI = It->second;
2524 KnownSafeBU &= NewReleaseRRI.KnownSafe;
2525 for (SmallPtrSet<Instruction *, 2>::const_iterator
2526 LI = NewReleaseRRI.Calls.begin(),
2527 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
2528 Instruction *NewReleaseRetain = *LI;
2529 MapVector<Value *, RRInfo>::const_iterator Jt =
2530 Retains.find(NewReleaseRetain);
2531 if (Jt == Retains.end())
2532 return false;
2533 const RRInfo &NewReleaseRetainRRI = Jt->second;
2534 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
2535 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
2536 unsigned PathCount =
2537 BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
2538 OldDelta += PathCount;
2539 OldCount += PathCount;
2540
Michael Gottesman9de6f962013-01-22 21:49:00 +00002541 // Collect the optimal insertion points.
2542 if (!KnownSafe)
2543 for (SmallPtrSet<Instruction *, 2>::const_iterator
2544 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
2545 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
2546 RI != RE; ++RI) {
2547 Instruction *RIP = *RI;
2548 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
2549 PathCount = BBStates[RIP->getParent()].GetAllPathCount();
2550 NewDelta += PathCount;
2551 NewCount += PathCount;
2552 }
2553 }
2554 NewRetains.push_back(NewReleaseRetain);
2555 }
2556 }
2557 }
2558 NewReleases.clear();
2559 if (NewRetains.empty()) break;
2560 }
2561
2562 // If the pointer is known incremented or nested, we can safely delete the
2563 // pair regardless of what's between them.
2564 if (KnownSafeTD || KnownSafeBU) {
2565 RetainsToMove.ReverseInsertPts.clear();
2566 ReleasesToMove.ReverseInsertPts.clear();
2567 NewCount = 0;
2568 } else {
2569 // Determine whether the new insertion points we computed preserve the
2570 // balance of retain and release calls through the program.
2571 // TODO: If the fully aggressive solution isn't valid, try to find a
2572 // less aggressive solution which is.
2573 if (NewDelta != 0)
2574 return false;
2575 }
2576
2577 // Determine whether the original call points are balanced in the retain and
2578 // release calls through the program. If not, conservatively don't touch
2579 // them.
2580 // TODO: It's theoretically possible to do code motion in this case, as
2581 // long as the existing imbalances are maintained.
2582 if (OldDelta != 0)
2583 return false;
Michael Gottesmana87bb8f2013-04-29 05:13:13 +00002584
2585#ifdef ARC_ANNOTATIONS
2586 // Do not move calls if ARC annotations are requested.
2587 return false;
2588#endif // ARC_ANNOTATIONS
Michael Gottesman9de6f962013-01-22 21:49:00 +00002589
2590 Changed = true;
2591 assert(OldCount != 0 && "Unreachable code?");
2592 NumRRs += OldCount - NewCount;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002593 // Set to true if we completely removed any RR pairs.
Michael Gottesman8b5515f2013-01-22 21:53:43 +00002594 AnyPairsCompletelyEliminated = NewCount == 0;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002595
2596 // We can move calls!
2597 return true;
2598}
2599
Michael Gottesman97e3df02013-01-14 00:35:14 +00002600/// Identify pairings between the retains and releases, and delete and/or move
2601/// them.
John McCalld935e9c2011-06-15 23:37:01 +00002602bool
2603ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
2604 &BBStates,
2605 MapVector<Value *, RRInfo> &Retains,
Dan Gohman6320f522011-07-22 22:29:21 +00002606 DenseMap<Value *, RRInfo> &Releases,
2607 Module *M) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002608 DEBUG(dbgs() << "\n== ObjCARCOpt::PerformCodePlacement ==\n");
2609
John McCalld935e9c2011-06-15 23:37:01 +00002610 bool AnyPairsCompletelyEliminated = false;
2611 RRInfo RetainsToMove;
2612 RRInfo ReleasesToMove;
2613 SmallVector<Instruction *, 4> NewRetains;
2614 SmallVector<Instruction *, 4> NewReleases;
2615 SmallVector<Instruction *, 8> DeadInsts;
2616
Dan Gohman670f9372012-04-13 18:57:48 +00002617 // Visit each retain.
John McCalld935e9c2011-06-15 23:37:01 +00002618 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
Dan Gohman2053a5d2011-09-29 22:25:23 +00002619 E = Retains.end(); I != E; ++I) {
2620 Value *V = I->first;
John McCalld935e9c2011-06-15 23:37:01 +00002621 if (!V) continue; // blotted
2622
2623 Instruction *Retain = cast<Instruction>(V);
Michael Gottesmanc189a392013-01-09 19:23:24 +00002624
Michael Gottesman89279f82013-04-05 18:10:41 +00002625 DEBUG(dbgs() << "Visiting: " << *Retain << "\n");
Michael Gottesmanc189a392013-01-09 19:23:24 +00002626
John McCalld935e9c2011-06-15 23:37:01 +00002627 Value *Arg = GetObjCArg(Retain);
2628
Dan Gohman728db492012-01-13 00:39:07 +00002629 // If the object being released is in static or stack storage, we know it's
John McCalld935e9c2011-06-15 23:37:01 +00002630 // not being managed by ObjC reference counting, so we can delete pairs
2631 // regardless of what possible decrements or uses lie between them.
Dan Gohman728db492012-01-13 00:39:07 +00002632 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
Dan Gohman41375a32012-05-08 23:39:44 +00002633
Dan Gohman56e1cef2011-08-22 17:29:11 +00002634 // A constant pointer can't be pointing to an object on the heap. It may
2635 // be reference-counted, but it won't be deleted.
2636 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
2637 if (const GlobalVariable *GV =
2638 dyn_cast<GlobalVariable>(
2639 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
2640 if (GV->isConstant())
2641 KnownSafe = true;
2642
John McCalld935e9c2011-06-15 23:37:01 +00002643 // Connect the dots between the top-down-collected RetainsToMove and
2644 // bottom-up-collected ReleasesToMove to form sets of related calls.
John McCalld935e9c2011-06-15 23:37:01 +00002645 NewRetains.push_back(Retain);
Michael Gottesman9de6f962013-01-22 21:49:00 +00002646 bool PerformMoveCalls =
2647 ConnectTDBUTraversals(BBStates, Retains, Releases, M, NewRetains,
2648 NewReleases, DeadInsts, RetainsToMove,
2649 ReleasesToMove, Arg, KnownSafe,
2650 AnyPairsCompletelyEliminated);
John McCalld935e9c2011-06-15 23:37:01 +00002651
Michael Gottesman9de6f962013-01-22 21:49:00 +00002652 if (PerformMoveCalls) {
2653 // Ok, everything checks out and we're all set. Let's move/delete some
2654 // code!
2655 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
2656 Retains, Releases, DeadInsts, M);
John McCalld935e9c2011-06-15 23:37:01 +00002657 }
2658
Michael Gottesman9de6f962013-01-22 21:49:00 +00002659 // Clean up state for next retain.
John McCalld935e9c2011-06-15 23:37:01 +00002660 NewReleases.clear();
2661 NewRetains.clear();
2662 RetainsToMove.clear();
2663 ReleasesToMove.clear();
2664 }
2665
2666 // Now that we're done moving everything, we can delete the newly dead
2667 // instructions, as we no longer need them as insert points.
2668 while (!DeadInsts.empty())
2669 EraseInstruction(DeadInsts.pop_back_val());
2670
2671 return AnyPairsCompletelyEliminated;
2672}
2673
Michael Gottesman97e3df02013-01-14 00:35:14 +00002674/// Weak pointer optimizations.
John McCalld935e9c2011-06-15 23:37:01 +00002675void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002676 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeWeakCalls ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00002677
John McCalld935e9c2011-06-15 23:37:01 +00002678 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
2679 // itself because it uses AliasAnalysis and we need to do provenance
2680 // queries instead.
2681 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2682 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +00002683
Michael Gottesman89279f82013-04-05 18:10:41 +00002684 DEBUG(dbgs() << "Visiting: " << *Inst << "\n");
Michael Gottesman3f146e22013-01-01 16:05:48 +00002685
John McCalld935e9c2011-06-15 23:37:01 +00002686 InstructionClass Class = GetBasicInstructionClass(Inst);
2687 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
2688 continue;
2689
2690 // Delete objc_loadWeak calls with no users.
2691 if (Class == IC_LoadWeak && Inst->use_empty()) {
2692 Inst->eraseFromParent();
2693 continue;
2694 }
2695
2696 // TODO: For now, just look for an earlier available version of this value
2697 // within the same block. Theoretically, we could do memdep-style non-local
2698 // analysis too, but that would want caching. A better approach would be to
2699 // use the technique that EarlyCSE uses.
2700 inst_iterator Current = llvm::prior(I);
2701 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
2702 for (BasicBlock::iterator B = CurrentBB->begin(),
2703 J = Current.getInstructionIterator();
2704 J != B; --J) {
2705 Instruction *EarlierInst = &*llvm::prior(J);
2706 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
2707 switch (EarlierClass) {
2708 case IC_LoadWeak:
2709 case IC_LoadWeakRetained: {
2710 // If this is loading from the same pointer, replace this load's value
2711 // with that one.
2712 CallInst *Call = cast<CallInst>(Inst);
2713 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2714 Value *Arg = Call->getArgOperand(0);
2715 Value *EarlierArg = EarlierCall->getArgOperand(0);
2716 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2717 case AliasAnalysis::MustAlias:
2718 Changed = true;
2719 // If the load has a builtin retain, insert a plain retain for it.
2720 if (Class == IC_LoadWeakRetained) {
2721 CallInst *CI =
2722 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
2723 "", Call);
2724 CI->setTailCall();
2725 }
2726 // Zap the fully redundant load.
2727 Call->replaceAllUsesWith(EarlierCall);
2728 Call->eraseFromParent();
2729 goto clobbered;
2730 case AliasAnalysis::MayAlias:
2731 case AliasAnalysis::PartialAlias:
2732 goto clobbered;
2733 case AliasAnalysis::NoAlias:
2734 break;
2735 }
2736 break;
2737 }
2738 case IC_StoreWeak:
2739 case IC_InitWeak: {
2740 // If this is storing to the same pointer and has the same size etc.
2741 // replace this load's value with the stored value.
2742 CallInst *Call = cast<CallInst>(Inst);
2743 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2744 Value *Arg = Call->getArgOperand(0);
2745 Value *EarlierArg = EarlierCall->getArgOperand(0);
2746 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2747 case AliasAnalysis::MustAlias:
2748 Changed = true;
2749 // If the load has a builtin retain, insert a plain retain for it.
2750 if (Class == IC_LoadWeakRetained) {
2751 CallInst *CI =
2752 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
2753 "", Call);
2754 CI->setTailCall();
2755 }
2756 // Zap the fully redundant load.
2757 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
2758 Call->eraseFromParent();
2759 goto clobbered;
2760 case AliasAnalysis::MayAlias:
2761 case AliasAnalysis::PartialAlias:
2762 goto clobbered;
2763 case AliasAnalysis::NoAlias:
2764 break;
2765 }
2766 break;
2767 }
2768 case IC_MoveWeak:
2769 case IC_CopyWeak:
2770 // TOOD: Grab the copied value.
2771 goto clobbered;
2772 case IC_AutoreleasepoolPush:
2773 case IC_None:
John McCall20182ac2013-03-22 21:38:36 +00002774 case IC_IntrinsicUser:
John McCalld935e9c2011-06-15 23:37:01 +00002775 case IC_User:
2776 // Weak pointers are only modified through the weak entry points
2777 // (and arbitrary calls, which could call the weak entry points).
2778 break;
2779 default:
2780 // Anything else could modify the weak pointer.
2781 goto clobbered;
2782 }
2783 }
2784 clobbered:;
2785 }
2786
2787 // Then, for each destroyWeak with an alloca operand, check to see if
2788 // the alloca and all its users can be zapped.
2789 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2790 Instruction *Inst = &*I++;
2791 InstructionClass Class = GetBasicInstructionClass(Inst);
2792 if (Class != IC_DestroyWeak)
2793 continue;
2794
2795 CallInst *Call = cast<CallInst>(Inst);
2796 Value *Arg = Call->getArgOperand(0);
2797 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
2798 for (Value::use_iterator UI = Alloca->use_begin(),
2799 UE = Alloca->use_end(); UI != UE; ++UI) {
Dan Gohmandae33492012-04-27 18:56:31 +00002800 const Instruction *UserInst = cast<Instruction>(*UI);
John McCalld935e9c2011-06-15 23:37:01 +00002801 switch (GetBasicInstructionClass(UserInst)) {
2802 case IC_InitWeak:
2803 case IC_StoreWeak:
2804 case IC_DestroyWeak:
2805 continue;
2806 default:
2807 goto done;
2808 }
2809 }
2810 Changed = true;
2811 for (Value::use_iterator UI = Alloca->use_begin(),
2812 UE = Alloca->use_end(); UI != UE; ) {
2813 CallInst *UserInst = cast<CallInst>(*UI++);
Dan Gohman14862c32012-05-18 22:17:29 +00002814 switch (GetBasicInstructionClass(UserInst)) {
2815 case IC_InitWeak:
2816 case IC_StoreWeak:
2817 // These functions return their second argument.
2818 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
2819 break;
2820 case IC_DestroyWeak:
2821 // No return value.
2822 break;
2823 default:
Dan Gohman9c97eea02012-05-21 17:41:28 +00002824 llvm_unreachable("alloca really is used!");
Dan Gohman14862c32012-05-18 22:17:29 +00002825 }
John McCalld935e9c2011-06-15 23:37:01 +00002826 UserInst->eraseFromParent();
2827 }
2828 Alloca->eraseFromParent();
2829 done:;
2830 }
2831 }
2832}
2833
Michael Gottesman97e3df02013-01-14 00:35:14 +00002834/// Identify program paths which execute sequences of retains and releases which
2835/// can be eliminated.
John McCalld935e9c2011-06-15 23:37:01 +00002836bool ObjCARCOpt::OptimizeSequences(Function &F) {
2837 /// Releases, Retains - These are used to store the results of the main flow
2838 /// analysis. These use Value* as the key instead of Instruction* so that the
2839 /// map stays valid when we get around to rewriting code and calls get
2840 /// replaced by arguments.
2841 DenseMap<Value *, RRInfo> Releases;
2842 MapVector<Value *, RRInfo> Retains;
2843
Michael Gottesman97e3df02013-01-14 00:35:14 +00002844 /// This is used during the traversal of the function to track the
John McCalld935e9c2011-06-15 23:37:01 +00002845 /// states for each identified object at each block.
2846 DenseMap<const BasicBlock *, BBState> BBStates;
2847
2848 // Analyze the CFG of the function, and all instructions.
2849 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
2850
2851 // Transform.
Dan Gohman6320f522011-07-22 22:29:21 +00002852 return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) &&
2853 NestingDetected;
John McCalld935e9c2011-06-15 23:37:01 +00002854}
2855
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002856/// Check if there is a dependent call earlier that does not have anything in
2857/// between the Retain and the call that can affect the reference count of their
2858/// shared pointer argument. Note that Retain need not be in BB.
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002859static bool
2860HasSafePathToPredecessorCall(const Value *Arg, Instruction *Retain,
2861 SmallPtrSet<Instruction *, 4> &DepInsts,
2862 SmallPtrSet<const BasicBlock *, 4> &Visited,
2863 ProvenanceAnalysis &PA) {
2864 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
2865 DepInsts, Visited, PA);
2866 if (DepInsts.size() != 1)
2867 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002868
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002869 CallInst *Call =
2870 dyn_cast_or_null<CallInst>(*DepInsts.begin());
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002871
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002872 // Check that the pointer is the return value of the call.
2873 if (!Call || Arg != Call)
2874 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002875
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002876 // Check that the call is a regular call.
2877 InstructionClass Class = GetBasicInstructionClass(Call);
2878 if (Class != IC_CallOrUser && Class != IC_Call)
2879 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002880
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002881 return true;
2882}
2883
Michael Gottesman6908db12013-04-03 23:16:05 +00002884/// Find a dependent retain that precedes the given autorelease for which there
2885/// is nothing in between the two instructions that can affect the ref count of
2886/// Arg.
2887static CallInst *
2888FindPredecessorRetainWithSafePath(const Value *Arg, BasicBlock *BB,
2889 Instruction *Autorelease,
2890 SmallPtrSet<Instruction *, 4> &DepInsts,
2891 SmallPtrSet<const BasicBlock *, 4> &Visited,
2892 ProvenanceAnalysis &PA) {
2893 FindDependencies(CanChangeRetainCount, Arg,
2894 BB, Autorelease, DepInsts, Visited, PA);
2895 if (DepInsts.size() != 1)
2896 return 0;
Michael Gottesman79249972013-04-05 23:46:45 +00002897
Michael Gottesman6908db12013-04-03 23:16:05 +00002898 CallInst *Retain =
2899 dyn_cast_or_null<CallInst>(*DepInsts.begin());
Michael Gottesman79249972013-04-05 23:46:45 +00002900
Michael Gottesman6908db12013-04-03 23:16:05 +00002901 // Check that we found a retain with the same argument.
2902 if (!Retain ||
2903 !IsRetain(GetBasicInstructionClass(Retain)) ||
2904 GetObjCArg(Retain) != Arg) {
2905 return 0;
2906 }
Michael Gottesman79249972013-04-05 23:46:45 +00002907
Michael Gottesman6908db12013-04-03 23:16:05 +00002908 return Retain;
2909}
2910
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002911/// Look for an ``autorelease'' instruction dependent on Arg such that there are
2912/// no instructions dependent on Arg that need a positive ref count in between
2913/// the autorelease and the ret.
2914static CallInst *
2915FindPredecessorAutoreleaseWithSafePath(const Value *Arg, BasicBlock *BB,
2916 ReturnInst *Ret,
2917 SmallPtrSet<Instruction *, 4> &DepInsts,
2918 SmallPtrSet<const BasicBlock *, 4> &V,
2919 ProvenanceAnalysis &PA) {
2920 FindDependencies(NeedsPositiveRetainCount, Arg,
2921 BB, Ret, DepInsts, V, PA);
2922 if (DepInsts.size() != 1)
2923 return 0;
Michael Gottesman79249972013-04-05 23:46:45 +00002924
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002925 CallInst *Autorelease =
2926 dyn_cast_or_null<CallInst>(*DepInsts.begin());
2927 if (!Autorelease)
2928 return 0;
2929 InstructionClass AutoreleaseClass = GetBasicInstructionClass(Autorelease);
2930 if (!IsAutorelease(AutoreleaseClass))
2931 return 0;
2932 if (GetObjCArg(Autorelease) != Arg)
2933 return 0;
Michael Gottesman79249972013-04-05 23:46:45 +00002934
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002935 return Autorelease;
2936}
2937
Michael Gottesman97e3df02013-01-14 00:35:14 +00002938/// Look for this pattern:
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00002939/// \code
John McCalld935e9c2011-06-15 23:37:01 +00002940/// %call = call i8* @something(...)
2941/// %2 = call i8* @objc_retain(i8* %call)
2942/// %3 = call i8* @objc_autorelease(i8* %2)
2943/// ret i8* %3
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00002944/// \endcode
John McCalld935e9c2011-06-15 23:37:01 +00002945/// And delete the retain and autorelease.
John McCalld935e9c2011-06-15 23:37:01 +00002946void ObjCARCOpt::OptimizeReturns(Function &F) {
2947 if (!F.getReturnType()->isPointerTy())
2948 return;
Michael Gottesman79249972013-04-05 23:46:45 +00002949
Michael Gottesman89279f82013-04-05 18:10:41 +00002950 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeReturns ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00002951
John McCalld935e9c2011-06-15 23:37:01 +00002952 SmallPtrSet<Instruction *, 4> DependingInstructions;
2953 SmallPtrSet<const BasicBlock *, 4> Visited;
2954 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
2955 BasicBlock *BB = FI;
2956 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
Michael Gottesman3f146e22013-01-01 16:05:48 +00002957
Michael Gottesman89279f82013-04-05 18:10:41 +00002958 DEBUG(dbgs() << "Visiting: " << *Ret << "\n");
Michael Gottesman3f146e22013-01-01 16:05:48 +00002959
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002960 if (!Ret)
2961 continue;
Michael Gottesman79249972013-04-05 23:46:45 +00002962
John McCalld935e9c2011-06-15 23:37:01 +00002963 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
Michael Gottesman79249972013-04-05 23:46:45 +00002964
Michael Gottesmancdb7c152013-04-21 00:25:04 +00002965 // Look for an ``autorelease'' instruction that is a predecessor of Ret and
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002966 // dependent on Arg such that there are no instructions dependent on Arg
2967 // that need a positive ref count in between the autorelease and Ret.
2968 CallInst *Autorelease =
2969 FindPredecessorAutoreleaseWithSafePath(Arg, BB, Ret,
2970 DependingInstructions, Visited,
2971 PA);
John McCalld935e9c2011-06-15 23:37:01 +00002972 DependingInstructions.clear();
2973 Visited.clear();
Michael Gottesmanfb9ece92013-04-21 00:25:01 +00002974
2975 if (!Autorelease)
2976 continue;
2977
2978 CallInst *Retain =
2979 FindPredecessorRetainWithSafePath(Arg, BB, Autorelease,
2980 DependingInstructions, Visited, PA);
2981 DependingInstructions.clear();
2982 Visited.clear();
2983
2984 if (!Retain)
2985 continue;
2986
2987 // Check that there is nothing that can affect the reference count
2988 // between the retain and the call. Note that Retain need not be in BB.
2989 bool HasSafePathToCall = HasSafePathToPredecessorCall(Arg, Retain,
2990 DependingInstructions,
2991 Visited, PA);
2992 DependingInstructions.clear();
2993 Visited.clear();
2994
2995 if (!HasSafePathToCall)
2996 continue;
2997
2998 // If so, we can zap the retain and autorelease.
2999 Changed = true;
3000 ++NumRets;
3001 DEBUG(dbgs() << "Erasing: " << *Retain << "\nErasing: "
3002 << *Autorelease << "\n");
3003 EraseInstruction(Retain);
3004 EraseInstruction(Autorelease);
John McCalld935e9c2011-06-15 23:37:01 +00003005 }
3006}
3007
3008bool ObjCARCOpt::doInitialization(Module &M) {
3009 if (!EnableARCOpts)
3010 return false;
3011
Dan Gohman670f9372012-04-13 18:57:48 +00003012 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanceaac7c2011-06-20 23:20:43 +00003013 Run = ModuleHasARC(M);
3014 if (!Run)
3015 return false;
3016
John McCalld935e9c2011-06-15 23:37:01 +00003017 // Identify the imprecise release metadata kind.
3018 ImpreciseReleaseMDKind =
3019 M.getContext().getMDKindID("clang.imprecise_release");
Dan Gohmana7107f92011-10-17 22:53:25 +00003020 CopyOnEscapeMDKind =
3021 M.getContext().getMDKindID("clang.arc.copy_on_escape");
Dan Gohman0155f302012-02-17 18:59:53 +00003022 NoObjCARCExceptionsMDKind =
3023 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
Michael Gottesman81b1d432013-03-26 00:42:04 +00003024#ifdef ARC_ANNOTATIONS
3025 ARCAnnotationBottomUpMDKind =
3026 M.getContext().getMDKindID("llvm.arc.annotation.bottomup");
3027 ARCAnnotationTopDownMDKind =
3028 M.getContext().getMDKindID("llvm.arc.annotation.topdown");
3029 ARCAnnotationProvenanceSourceMDKind =
3030 M.getContext().getMDKindID("llvm.arc.annotation.provenancesource");
3031#endif // ARC_ANNOTATIONS
John McCalld935e9c2011-06-15 23:37:01 +00003032
John McCalld935e9c2011-06-15 23:37:01 +00003033 // Intuitively, objc_retain and others are nocapture, however in practice
3034 // they are not, because they return their argument value. And objc_release
Dan Gohmandae33492012-04-27 18:56:31 +00003035 // calls finalizers which can have arbitrary side effects.
John McCalld935e9c2011-06-15 23:37:01 +00003036
3037 // These are initialized lazily.
3038 RetainRVCallee = 0;
3039 AutoreleaseRVCallee = 0;
3040 ReleaseCallee = 0;
3041 RetainCallee = 0;
Dan Gohman6320f522011-07-22 22:29:21 +00003042 RetainBlockCallee = 0;
John McCalld935e9c2011-06-15 23:37:01 +00003043 AutoreleaseCallee = 0;
3044
3045 return false;
3046}
3047
3048bool ObjCARCOpt::runOnFunction(Function &F) {
3049 if (!EnableARCOpts)
3050 return false;
3051
Dan Gohmanceaac7c2011-06-20 23:20:43 +00003052 // If nothing in the Module uses ARC, don't do anything.
3053 if (!Run)
3054 return false;
3055
John McCalld935e9c2011-06-15 23:37:01 +00003056 Changed = false;
3057
Michael Gottesman89279f82013-04-05 18:10:41 +00003058 DEBUG(dbgs() << "<<< ObjCARCOpt: Visiting Function: " << F.getName() << " >>>"
3059 "\n");
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00003060
John McCalld935e9c2011-06-15 23:37:01 +00003061 PA.setAA(&getAnalysis<AliasAnalysis>());
3062
3063 // This pass performs several distinct transformations. As a compile-time aid
3064 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3065 // library functions aren't declared.
3066
Michael Gottesmancd5b0272013-04-24 22:18:15 +00003067 // Preliminary optimizations. This also computes UsedInThisFunction.
John McCalld935e9c2011-06-15 23:37:01 +00003068 OptimizeIndividualCalls(F);
3069
3070 // Optimizations for weak pointers.
3071 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3072 (1 << IC_LoadWeakRetained) |
3073 (1 << IC_StoreWeak) |
3074 (1 << IC_InitWeak) |
3075 (1 << IC_CopyWeak) |
3076 (1 << IC_MoveWeak) |
3077 (1 << IC_DestroyWeak)))
3078 OptimizeWeakCalls(F);
3079
3080 // Optimizations for retain+release pairs.
3081 if (UsedInThisFunction & ((1 << IC_Retain) |
3082 (1 << IC_RetainRV) |
3083 (1 << IC_RetainBlock)))
3084 if (UsedInThisFunction & (1 << IC_Release))
3085 // Run OptimizeSequences until it either stops making changes or
3086 // no retain+release pair nesting is detected.
3087 while (OptimizeSequences(F)) {}
3088
3089 // Optimizations if objc_autorelease is used.
Dan Gohman41375a32012-05-08 23:39:44 +00003090 if (UsedInThisFunction & ((1 << IC_Autorelease) |
3091 (1 << IC_AutoreleaseRV)))
John McCalld935e9c2011-06-15 23:37:01 +00003092 OptimizeReturns(F);
3093
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00003094 DEBUG(dbgs() << "\n");
3095
John McCalld935e9c2011-06-15 23:37:01 +00003096 return Changed;
3097}
3098
3099void ObjCARCOpt::releaseMemory() {
3100 PA.clear();
3101}
3102
Michael Gottesman97e3df02013-01-14 00:35:14 +00003103/// @}
3104///