blob: 1c1cec722ab5c4a31e54d083c5252c3ea6c7d4ab [file] [log] [blame]
Michael Gottesman79d8d812013-01-28 01:35:51 +00001//===- ObjCARCOpts.cpp - ObjC ARC Optimization ----------------------------===//
John McCalld935e9c2011-06-15 23:37:01 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Michael Gottesman97e3df02013-01-14 00:35:14 +00009/// \file
10/// This file defines ObjC ARC optimizations. ARC stands for Automatic
11/// Reference Counting and is a system for managing reference counts for objects
12/// in Objective C.
13///
14/// The optimizations performed include elimination of redundant, partially
15/// redundant, and inconsequential reference count operations, elimination of
Michael Gottesman697d8b92013-02-07 04:12:57 +000016/// redundant weak pointer operations, and numerous minor simplifications.
Michael Gottesman97e3df02013-01-14 00:35:14 +000017///
18/// WARNING: This file knows about certain library functions. It recognizes them
19/// by name, and hardwires knowledge of their semantics.
20///
21/// WARNING: This file knows about how certain Objective-C library functions are
22/// used. Naive LLVM IR transformations which would otherwise be
23/// behavior-preserving may break these assumptions.
24///
John McCalld935e9c2011-06-15 23:37:01 +000025//===----------------------------------------------------------------------===//
26
Michael Gottesman08904e32013-01-28 03:28:38 +000027#define DEBUG_TYPE "objc-arc-opts"
28#include "ObjCARC.h"
Michael Gottesman278266f2013-01-29 04:20:52 +000029#include "DependencyAnalysis.h"
Michael Gottesman294e7da2013-01-28 05:51:54 +000030#include "ObjCARCAliasAnalysis.h"
Michael Gottesman778138e2013-01-29 03:03:03 +000031#include "ProvenanceAnalysis.h"
John McCalld935e9c2011-06-15 23:37:01 +000032#include "llvm/ADT/DenseMap.h"
Michael Gottesmanfa0939f2013-01-28 04:12:07 +000033#include "llvm/ADT/STLExtras.h"
Michael Gottesman778138e2013-01-29 03:03:03 +000034#include "llvm/ADT/SmallPtrSet.h"
Michael Gottesman278266f2013-01-29 04:20:52 +000035#include "llvm/ADT/Statistic.h"
Michael Gottesmancd4de0f2013-03-26 00:42:09 +000036#include "llvm/IR/IRBuilder.h"
Michael Gottesman278266f2013-01-29 04:20:52 +000037#include "llvm/IR/LLVMContext.h"
Michael Gottesman778138e2013-01-29 03:03:03 +000038#include "llvm/Support/CFG.h"
Michael Gottesman13a5f1a2013-01-29 04:51:59 +000039#include "llvm/Support/Debug.h"
Timur Iskhodzhanov5d7ff002013-01-29 09:09:27 +000040#include "llvm/Support/raw_ostream.h"
Michael Gottesmanfa0939f2013-01-28 04:12:07 +000041
John McCalld935e9c2011-06-15 23:37:01 +000042using namespace llvm;
Michael Gottesman08904e32013-01-28 03:28:38 +000043using namespace llvm::objcarc;
John McCalld935e9c2011-06-15 23:37:01 +000044
Michael Gottesman97e3df02013-01-14 00:35:14 +000045/// \defgroup MiscUtils Miscellaneous utilities that are not ARC specific.
46/// @{
John McCalld935e9c2011-06-15 23:37:01 +000047
48namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +000049 /// \brief An associative container with fast insertion-order (deterministic)
50 /// iteration over its elements. Plus the special blot operation.
John McCalld935e9c2011-06-15 23:37:01 +000051 template<class KeyT, class ValueT>
52 class MapVector {
Michael Gottesman97e3df02013-01-14 00:35:14 +000053 /// Map keys to indices in Vector.
John McCalld935e9c2011-06-15 23:37:01 +000054 typedef DenseMap<KeyT, size_t> MapTy;
55 MapTy Map;
56
John McCalld935e9c2011-06-15 23:37:01 +000057 typedef std::vector<std::pair<KeyT, ValueT> > VectorTy;
Michael Gottesman97e3df02013-01-14 00:35:14 +000058 /// Keys and values.
John McCalld935e9c2011-06-15 23:37:01 +000059 VectorTy Vector;
60
61 public:
62 typedef typename VectorTy::iterator iterator;
63 typedef typename VectorTy::const_iterator const_iterator;
64 iterator begin() { return Vector.begin(); }
65 iterator end() { return Vector.end(); }
66 const_iterator begin() const { return Vector.begin(); }
67 const_iterator end() const { return Vector.end(); }
68
69#ifdef XDEBUG
70 ~MapVector() {
71 assert(Vector.size() >= Map.size()); // May differ due to blotting.
72 for (typename MapTy::const_iterator I = Map.begin(), E = Map.end();
73 I != E; ++I) {
74 assert(I->second < Vector.size());
75 assert(Vector[I->second].first == I->first);
76 }
77 for (typename VectorTy::const_iterator I = Vector.begin(),
78 E = Vector.end(); I != E; ++I)
79 assert(!I->first ||
80 (Map.count(I->first) &&
81 Map[I->first] == size_t(I - Vector.begin())));
82 }
83#endif
84
Dan Gohman55b06742012-03-02 01:13:53 +000085 ValueT &operator[](const KeyT &Arg) {
John McCalld935e9c2011-06-15 23:37:01 +000086 std::pair<typename MapTy::iterator, bool> Pair =
87 Map.insert(std::make_pair(Arg, size_t(0)));
88 if (Pair.second) {
Dan Gohman55b06742012-03-02 01:13:53 +000089 size_t Num = Vector.size();
90 Pair.first->second = Num;
John McCalld935e9c2011-06-15 23:37:01 +000091 Vector.push_back(std::make_pair(Arg, ValueT()));
Dan Gohman55b06742012-03-02 01:13:53 +000092 return Vector[Num].second;
John McCalld935e9c2011-06-15 23:37:01 +000093 }
94 return Vector[Pair.first->second].second;
95 }
96
97 std::pair<iterator, bool>
98 insert(const std::pair<KeyT, ValueT> &InsertPair) {
99 std::pair<typename MapTy::iterator, bool> Pair =
100 Map.insert(std::make_pair(InsertPair.first, size_t(0)));
101 if (Pair.second) {
Dan Gohman55b06742012-03-02 01:13:53 +0000102 size_t Num = Vector.size();
103 Pair.first->second = Num;
John McCalld935e9c2011-06-15 23:37:01 +0000104 Vector.push_back(InsertPair);
Dan Gohman55b06742012-03-02 01:13:53 +0000105 return std::make_pair(Vector.begin() + Num, true);
John McCalld935e9c2011-06-15 23:37:01 +0000106 }
107 return std::make_pair(Vector.begin() + Pair.first->second, false);
108 }
109
Dan Gohman55b06742012-03-02 01:13:53 +0000110 const_iterator find(const KeyT &Key) const {
John McCalld935e9c2011-06-15 23:37:01 +0000111 typename MapTy::const_iterator It = Map.find(Key);
112 if (It == Map.end()) return Vector.end();
113 return Vector.begin() + It->second;
114 }
115
Michael Gottesman97e3df02013-01-14 00:35:14 +0000116 /// This is similar to erase, but instead of removing the element from the
117 /// vector, it just zeros out the key in the vector. This leaves iterators
118 /// intact, but clients must be prepared for zeroed-out keys when iterating.
Dan Gohman55b06742012-03-02 01:13:53 +0000119 void blot(const KeyT &Key) {
John McCalld935e9c2011-06-15 23:37:01 +0000120 typename MapTy::iterator It = Map.find(Key);
121 if (It == Map.end()) return;
122 Vector[It->second].first = KeyT();
123 Map.erase(It);
124 }
125
126 void clear() {
127 Map.clear();
128 Vector.clear();
129 }
130 };
131}
132
Michael Gottesman97e3df02013-01-14 00:35:14 +0000133/// @}
134///
135/// \defgroup ARCUtilities Utility declarations/definitions specific to ARC.
136/// @{
John McCalld935e9c2011-06-15 23:37:01 +0000137
Michael Gottesman97e3df02013-01-14 00:35:14 +0000138/// \brief This is similar to StripPointerCastsAndObjCCalls but it stops as soon
139/// as it finds a value with multiple uses.
John McCalld935e9c2011-06-15 23:37:01 +0000140static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
141 if (Arg->hasOneUse()) {
142 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
143 return FindSingleUseIdentifiedObject(BC->getOperand(0));
144 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
145 if (GEP->hasAllZeroIndices())
146 return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
147 if (IsForwarding(GetBasicInstructionClass(Arg)))
148 return FindSingleUseIdentifiedObject(
149 cast<CallInst>(Arg)->getArgOperand(0));
150 if (!IsObjCIdentifiedObject(Arg))
151 return 0;
152 return Arg;
153 }
154
Dan Gohman41375a32012-05-08 23:39:44 +0000155 // If we found an identifiable object but it has multiple uses, but they are
156 // trivial uses, we can still consider this to be a single-use value.
John McCalld935e9c2011-06-15 23:37:01 +0000157 if (IsObjCIdentifiedObject(Arg)) {
158 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
159 UI != UE; ++UI) {
160 const User *U = *UI;
161 if (!U->use_empty() || StripPointerCastsAndObjCCalls(U) != Arg)
162 return 0;
163 }
164
165 return Arg;
166 }
167
168 return 0;
169}
170
Michael Gottesman774d2c02013-01-29 21:00:52 +0000171/// \brief Test whether the given retainable object pointer escapes.
Michael Gottesman97e3df02013-01-14 00:35:14 +0000172///
173/// This differs from regular escape analysis in that a use as an
174/// argument to a call is not considered an escape.
175///
Michael Gottesman774d2c02013-01-29 21:00:52 +0000176static bool DoesRetainableObjPtrEscape(const User *Ptr) {
Michael Gottesman774d2c02013-01-29 21:00:52 +0000177 DEBUG(dbgs() << "DoesRetainableObjPtrEscape: Target: " << *Ptr << "\n");
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000178
Dan Gohman728db492012-01-13 00:39:07 +0000179 // Walk the def-use chains.
180 SmallVector<const Value *, 4> Worklist;
Michael Gottesman774d2c02013-01-29 21:00:52 +0000181 Worklist.push_back(Ptr);
182 // If Ptr has any operands add them as well.
Michael Gottesman23cda0c2013-01-29 21:07:53 +0000183 for (User::const_op_iterator I = Ptr->op_begin(), E = Ptr->op_end(); I != E;
184 ++I) {
Michael Gottesman774d2c02013-01-29 21:00:52 +0000185 Worklist.push_back(*I);
186 }
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000187
188 // Ensure we do not visit any value twice.
Michael Gottesman774d2c02013-01-29 21:00:52 +0000189 SmallPtrSet<const Value *, 8> VisitedSet;
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000190
Dan Gohman728db492012-01-13 00:39:07 +0000191 do {
192 const Value *V = Worklist.pop_back_val();
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000193
Michael Gottesman89279f82013-04-05 18:10:41 +0000194 DEBUG(dbgs() << "Visiting: " << *V << "\n");
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000195
Dan Gohman728db492012-01-13 00:39:07 +0000196 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
197 UI != UE; ++UI) {
198 const User *UUser = *UI;
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000199
Michael Gottesman89279f82013-04-05 18:10:41 +0000200 DEBUG(dbgs() << "User: " << *UUser << "\n");
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000201
Dan Gohman728db492012-01-13 00:39:07 +0000202 // Special - Use by a call (callee or argument) is not considered
203 // to be an escape.
Dan Gohmane1e352a2012-04-13 18:28:58 +0000204 switch (GetBasicInstructionClass(UUser)) {
205 case IC_StoreWeak:
206 case IC_InitWeak:
207 case IC_StoreStrong:
208 case IC_Autorelease:
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000209 case IC_AutoreleaseRV: {
Michael Gottesman89279f82013-04-05 18:10:41 +0000210 DEBUG(dbgs() << "User copies pointer arguments. Pointer Escapes!\n");
Dan Gohmane1e352a2012-04-13 18:28:58 +0000211 // These special functions make copies of their pointer arguments.
212 return true;
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000213 }
John McCall20182ac2013-03-22 21:38:36 +0000214 case IC_IntrinsicUser:
215 // Use by the use intrinsic is not an escape.
216 continue;
Dan Gohmane1e352a2012-04-13 18:28:58 +0000217 case IC_User:
218 case IC_None:
219 // Use by an instruction which copies the value is an escape if the
220 // result is an escape.
221 if (isa<BitCastInst>(UUser) || isa<GetElementPtrInst>(UUser) ||
222 isa<PHINode>(UUser) || isa<SelectInst>(UUser)) {
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000223
Michael Gottesmanf4b77612013-02-23 00:31:32 +0000224 if (VisitedSet.insert(UUser)) {
Michael Gottesman89279f82013-04-05 18:10:41 +0000225 DEBUG(dbgs() << "User copies value. Ptr escapes if result escapes."
226 " Adding to list.\n");
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000227 Worklist.push_back(UUser);
228 } else {
Michael Gottesman89279f82013-04-05 18:10:41 +0000229 DEBUG(dbgs() << "Already visited node.\n");
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000230 }
Dan Gohmane1e352a2012-04-13 18:28:58 +0000231 continue;
232 }
233 // Use by a load is not an escape.
234 if (isa<LoadInst>(UUser))
235 continue;
236 // Use by a store is not an escape if the use is the address.
237 if (const StoreInst *SI = dyn_cast<StoreInst>(UUser))
238 if (V != SI->getValueOperand())
239 continue;
240 break;
241 default:
242 // Regular calls and other stuff are not considered escapes.
Dan Gohman728db492012-01-13 00:39:07 +0000243 continue;
244 }
Dan Gohmaneb6e0152012-02-13 22:57:02 +0000245 // Otherwise, conservatively assume an escape.
Michael Gottesman89279f82013-04-05 18:10:41 +0000246 DEBUG(dbgs() << "Assuming ptr escapes.\n");
Dan Gohman728db492012-01-13 00:39:07 +0000247 return true;
248 }
249 } while (!Worklist.empty());
250
251 // No escapes found.
Michael Gottesman89279f82013-04-05 18:10:41 +0000252 DEBUG(dbgs() << "Ptr does not escape.\n");
Dan Gohman728db492012-01-13 00:39:07 +0000253 return false;
254}
255
Michael Gottesman97e3df02013-01-14 00:35:14 +0000256/// @}
257///
Michael Gottesman97e3df02013-01-14 00:35:14 +0000258/// \defgroup ARCOpt ARC Optimization.
259/// @{
John McCalld935e9c2011-06-15 23:37:01 +0000260
261// TODO: On code like this:
262//
263// objc_retain(%x)
264// stuff_that_cannot_release()
265// objc_autorelease(%x)
266// stuff_that_cannot_release()
267// objc_retain(%x)
268// stuff_that_cannot_release()
269// objc_autorelease(%x)
270//
271// The second retain and autorelease can be deleted.
272
273// TODO: It should be possible to delete
274// objc_autoreleasePoolPush and objc_autoreleasePoolPop
275// pairs if nothing is actually autoreleased between them. Also, autorelease
276// calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
277// after inlining) can be turned into plain release calls.
278
279// TODO: Critical-edge splitting. If the optimial insertion point is
280// a critical edge, the current algorithm has to fail, because it doesn't
281// know how to split edges. It should be possible to make the optimizer
282// think in terms of edges, rather than blocks, and then split critical
283// edges on demand.
284
285// TODO: OptimizeSequences could generalized to be Interprocedural.
286
287// TODO: Recognize that a bunch of other objc runtime calls have
288// non-escaping arguments and non-releasing arguments, and may be
289// non-autoreleasing.
290
291// TODO: Sink autorelease calls as far as possible. Unfortunately we
292// usually can't sink them past other calls, which would be the main
293// case where it would be useful.
294
Dan Gohmanb3894012011-08-19 00:26:36 +0000295// TODO: The pointer returned from objc_loadWeakRetained is retained.
296
297// TODO: Delete release+retain pairs (rare).
Dan Gohmanceaac7c2011-06-20 23:20:43 +0000298
John McCalld935e9c2011-06-15 23:37:01 +0000299STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
300STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
301STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
302STATISTIC(NumRets, "Number of return value forwarding "
303 "retain+autoreleaes eliminated");
304STATISTIC(NumRRs, "Number of retain+release paths eliminated");
305STATISTIC(NumPeeps, "Number of calls peephole-optimized");
306
307namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000308 /// \enum Sequence
309 ///
310 /// \brief A sequence of states that a pointer may go through in which an
311 /// objc_retain and objc_release are actually needed.
John McCalld935e9c2011-06-15 23:37:01 +0000312 enum Sequence {
313 S_None,
Michael Gottesman53fd20b2013-01-29 21:07:51 +0000314 S_Retain, ///< objc_retain(x).
315 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement.
316 S_Use, ///< any use of x.
Michael Gottesman386241c2013-01-29 21:39:02 +0000317 S_Stop, ///< like S_Release, but code motion is stopped.
Michael Gottesman53fd20b2013-01-29 21:07:51 +0000318 S_Release, ///< objc_release(x).
Michael Gottesman9bdab2b2013-01-29 21:41:44 +0000319 S_MovableRelease ///< objc_release(x), !clang.imprecise_release.
John McCalld935e9c2011-06-15 23:37:01 +0000320 };
Michael Gottesman53fd20b2013-01-29 21:07:51 +0000321
322 raw_ostream &operator<<(raw_ostream &OS, const Sequence S)
323 LLVM_ATTRIBUTE_UNUSED;
324 raw_ostream &operator<<(raw_ostream &OS, const Sequence S) {
325 switch (S) {
326 case S_None:
327 return OS << "S_None";
328 case S_Retain:
329 return OS << "S_Retain";
330 case S_CanRelease:
331 return OS << "S_CanRelease";
332 case S_Use:
333 return OS << "S_Use";
334 case S_Release:
335 return OS << "S_Release";
336 case S_MovableRelease:
337 return OS << "S_MovableRelease";
338 case S_Stop:
339 return OS << "S_Stop";
340 }
341 llvm_unreachable("Unknown sequence type.");
342 }
John McCalld935e9c2011-06-15 23:37:01 +0000343}
344
345static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
346 // The easy cases.
347 if (A == B)
348 return A;
349 if (A == S_None || B == S_None)
350 return S_None;
351
John McCalld935e9c2011-06-15 23:37:01 +0000352 if (A > B) std::swap(A, B);
353 if (TopDown) {
354 // Choose the side which is further along in the sequence.
Dan Gohman12130272011-08-12 00:26:31 +0000355 if ((A == S_Retain || A == S_CanRelease) &&
356 (B == S_CanRelease || B == S_Use))
John McCalld935e9c2011-06-15 23:37:01 +0000357 return B;
358 } else {
359 // Choose the side which is further along in the sequence.
360 if ((A == S_Use || A == S_CanRelease) &&
Dan Gohman12130272011-08-12 00:26:31 +0000361 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
John McCalld935e9c2011-06-15 23:37:01 +0000362 return A;
363 // If both sides are releases, choose the more conservative one.
364 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
365 return A;
366 if (A == S_Release && B == S_MovableRelease)
367 return A;
368 }
369
370 return S_None;
371}
372
373namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000374 /// \brief Unidirectional information about either a
John McCalld935e9c2011-06-15 23:37:01 +0000375 /// retain-decrement-use-release sequence or release-use-decrement-retain
376 /// reverese sequence.
377 struct RRInfo {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000378 /// After an objc_retain, the reference count of the referenced
Dan Gohmanb3894012011-08-19 00:26:36 +0000379 /// object is known to be positive. Similarly, before an objc_release, the
380 /// reference count of the referenced object is known to be positive. If
381 /// there are retain-release pairs in code regions where the retain count
382 /// is known to be positive, they can be eliminated, regardless of any side
383 /// effects between them.
384 ///
385 /// Also, a retain+release pair nested within another retain+release
386 /// pair all on the known same pointer value can be eliminated, regardless
387 /// of any intervening side effects.
388 ///
389 /// KnownSafe is true when either of these conditions is satisfied.
390 bool KnownSafe;
John McCalld935e9c2011-06-15 23:37:01 +0000391
Michael Gottesman97e3df02013-01-14 00:35:14 +0000392 /// True of the objc_release calls are all marked with the "tail" keyword.
John McCalld935e9c2011-06-15 23:37:01 +0000393 bool IsTailCallRelease;
394
Michael Gottesman97e3df02013-01-14 00:35:14 +0000395 /// If the Calls are objc_release calls and they all have a
396 /// clang.imprecise_release tag, this is the metadata tag.
John McCalld935e9c2011-06-15 23:37:01 +0000397 MDNode *ReleaseMetadata;
398
Michael Gottesman97e3df02013-01-14 00:35:14 +0000399 /// For a top-down sequence, the set of objc_retains or
John McCalld935e9c2011-06-15 23:37:01 +0000400 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
401 SmallPtrSet<Instruction *, 2> Calls;
402
Michael Gottesman97e3df02013-01-14 00:35:14 +0000403 /// The set of optimal insert positions for moving calls in the opposite
404 /// sequence.
John McCalld935e9c2011-06-15 23:37:01 +0000405 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
406
407 RRInfo() :
Michael Gottesmanba648592013-03-28 23:08:44 +0000408 KnownSafe(false), IsTailCallRelease(false), ReleaseMetadata(0) {}
John McCalld935e9c2011-06-15 23:37:01 +0000409
410 void clear();
411 };
412}
413
414void RRInfo::clear() {
Dan Gohmanb3894012011-08-19 00:26:36 +0000415 KnownSafe = false;
John McCalld935e9c2011-06-15 23:37:01 +0000416 IsTailCallRelease = false;
417 ReleaseMetadata = 0;
418 Calls.clear();
419 ReverseInsertPts.clear();
420}
421
422namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000423 /// \brief This class summarizes several per-pointer runtime properties which
424 /// are propogated through the flow graph.
John McCalld935e9c2011-06-15 23:37:01 +0000425 class PtrState {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000426 /// True if the reference count is known to be incremented.
Dan Gohman62079b42012-04-25 00:50:46 +0000427 bool KnownPositiveRefCount;
428
Michael Gottesman97e3df02013-01-14 00:35:14 +0000429 /// True of we've seen an opportunity for partial RR elimination, such as
430 /// pushing calls into a CFG triangle or into one side of a CFG diamond.
Dan Gohman62079b42012-04-25 00:50:46 +0000431 bool Partial;
John McCalld935e9c2011-06-15 23:37:01 +0000432
Michael Gottesman97e3df02013-01-14 00:35:14 +0000433 /// The current position in the sequence.
Dan Gohman41375a32012-05-08 23:39:44 +0000434 Sequence Seq : 8;
John McCalld935e9c2011-06-15 23:37:01 +0000435
436 public:
Michael Gottesman97e3df02013-01-14 00:35:14 +0000437 /// Unidirectional information about the current sequence.
438 ///
John McCalld935e9c2011-06-15 23:37:01 +0000439 /// TODO: Encapsulate this better.
440 RRInfo RRI;
441
Dan Gohmandf476e52012-09-04 23:16:20 +0000442 PtrState() : KnownPositiveRefCount(false), Partial(false),
Dan Gohman41375a32012-05-08 23:39:44 +0000443 Seq(S_None) {}
John McCalld935e9c2011-06-15 23:37:01 +0000444
Michael Gottesman415ddd72013-02-05 19:32:18 +0000445 void SetKnownPositiveRefCount() {
Dan Gohman62079b42012-04-25 00:50:46 +0000446 KnownPositiveRefCount = true;
Dan Gohman12130272011-08-12 00:26:31 +0000447 }
448
Michael Gottesman764b1cf2013-03-23 05:46:19 +0000449 void ClearKnownPositiveRefCount() {
Dan Gohman62079b42012-04-25 00:50:46 +0000450 KnownPositiveRefCount = false;
John McCalld935e9c2011-06-15 23:37:01 +0000451 }
452
Michael Gottesman07beea42013-03-23 05:31:01 +0000453 bool HasKnownPositiveRefCount() const {
Dan Gohman62079b42012-04-25 00:50:46 +0000454 return KnownPositiveRefCount;
John McCalld935e9c2011-06-15 23:37:01 +0000455 }
456
Michael Gottesman415ddd72013-02-05 19:32:18 +0000457 void SetSeq(Sequence NewSeq) {
Michael Gottesman89279f82013-04-05 18:10:41 +0000458 DEBUG(dbgs() << "Old: " << Seq << "; New: " << NewSeq << "\n");
459 Seq = NewSeq;
John McCalld935e9c2011-06-15 23:37:01 +0000460 }
461
Michael Gottesman415ddd72013-02-05 19:32:18 +0000462 Sequence GetSeq() const {
John McCalld935e9c2011-06-15 23:37:01 +0000463 return Seq;
464 }
465
Michael Gottesman415ddd72013-02-05 19:32:18 +0000466 void ClearSequenceProgress() {
Dan Gohman62079b42012-04-25 00:50:46 +0000467 ResetSequenceProgress(S_None);
468 }
469
Michael Gottesman415ddd72013-02-05 19:32:18 +0000470 void ResetSequenceProgress(Sequence NewSeq) {
Michael Gottesman89279f82013-04-05 18:10:41 +0000471 SetSeq(NewSeq);
Dan Gohman62079b42012-04-25 00:50:46 +0000472 Partial = false;
John McCalld935e9c2011-06-15 23:37:01 +0000473 RRI.clear();
474 }
475
476 void Merge(const PtrState &Other, bool TopDown);
477 };
478}
479
480void
481PtrState::Merge(const PtrState &Other, bool TopDown) {
482 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
Dan Gohman62079b42012-04-25 00:50:46 +0000483 KnownPositiveRefCount = KnownPositiveRefCount && Other.KnownPositiveRefCount;
Michael Gottesman60f6b282013-03-29 05:13:07 +0000484
Dan Gohman1736c142011-10-17 18:48:25 +0000485 // If we're not in a sequence (anymore), drop all associated state.
John McCalld935e9c2011-06-15 23:37:01 +0000486 if (Seq == S_None) {
Dan Gohman62079b42012-04-25 00:50:46 +0000487 Partial = false;
John McCalld935e9c2011-06-15 23:37:01 +0000488 RRI.clear();
Dan Gohman62079b42012-04-25 00:50:46 +0000489 } else if (Partial || Other.Partial) {
Dan Gohman1736c142011-10-17 18:48:25 +0000490 // If we're doing a merge on a path that's previously seen a partial
491 // merge, conservatively drop the sequence, to avoid doing partial
492 // RR elimination. If the branch predicates for the two merge differ,
493 // mixing them is unsafe.
Dan Gohman62079b42012-04-25 00:50:46 +0000494 ClearSequenceProgress();
John McCalld935e9c2011-06-15 23:37:01 +0000495 } else {
496 // Conservatively merge the ReleaseMetadata information.
497 if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
498 RRI.ReleaseMetadata = 0;
499
Dan Gohmanb3894012011-08-19 00:26:36 +0000500 RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
Dan Gohman41375a32012-05-08 23:39:44 +0000501 RRI.IsTailCallRelease = RRI.IsTailCallRelease &&
502 Other.RRI.IsTailCallRelease;
John McCalld935e9c2011-06-15 23:37:01 +0000503 RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
Dan Gohman1736c142011-10-17 18:48:25 +0000504
505 // Merge the insert point sets. If there are any differences,
506 // that makes this a partial merge.
Dan Gohman41375a32012-05-08 23:39:44 +0000507 Partial = RRI.ReverseInsertPts.size() != Other.RRI.ReverseInsertPts.size();
Dan Gohman1736c142011-10-17 18:48:25 +0000508 for (SmallPtrSet<Instruction *, 2>::const_iterator
509 I = Other.RRI.ReverseInsertPts.begin(),
510 E = Other.RRI.ReverseInsertPts.end(); I != E; ++I)
Dan Gohman62079b42012-04-25 00:50:46 +0000511 Partial |= RRI.ReverseInsertPts.insert(*I);
John McCalld935e9c2011-06-15 23:37:01 +0000512 }
513}
514
515namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000516 /// \brief Per-BasicBlock state.
John McCalld935e9c2011-06-15 23:37:01 +0000517 class BBState {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000518 /// The number of unique control paths from the entry which can reach this
519 /// block.
John McCalld935e9c2011-06-15 23:37:01 +0000520 unsigned TopDownPathCount;
521
Michael Gottesman97e3df02013-01-14 00:35:14 +0000522 /// The number of unique control paths to exits from this block.
John McCalld935e9c2011-06-15 23:37:01 +0000523 unsigned BottomUpPathCount;
524
Michael Gottesman97e3df02013-01-14 00:35:14 +0000525 /// A type for PerPtrTopDown and PerPtrBottomUp.
John McCalld935e9c2011-06-15 23:37:01 +0000526 typedef MapVector<const Value *, PtrState> MapTy;
527
Michael Gottesman97e3df02013-01-14 00:35:14 +0000528 /// The top-down traversal uses this to record information known about a
529 /// pointer at the bottom of each block.
John McCalld935e9c2011-06-15 23:37:01 +0000530 MapTy PerPtrTopDown;
531
Michael Gottesman97e3df02013-01-14 00:35:14 +0000532 /// The bottom-up traversal uses this to record information known about a
533 /// pointer at the top of each block.
John McCalld935e9c2011-06-15 23:37:01 +0000534 MapTy PerPtrBottomUp;
535
Michael Gottesman97e3df02013-01-14 00:35:14 +0000536 /// Effective predecessors of the current block ignoring ignorable edges and
537 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000538 SmallVector<BasicBlock *, 2> Preds;
Michael Gottesman97e3df02013-01-14 00:35:14 +0000539 /// Effective successors of the current block ignoring ignorable edges and
540 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000541 SmallVector<BasicBlock *, 2> Succs;
542
John McCalld935e9c2011-06-15 23:37:01 +0000543 public:
544 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
545
546 typedef MapTy::iterator ptr_iterator;
547 typedef MapTy::const_iterator ptr_const_iterator;
548
549 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
550 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
551 ptr_const_iterator top_down_ptr_begin() const {
552 return PerPtrTopDown.begin();
553 }
554 ptr_const_iterator top_down_ptr_end() const {
555 return PerPtrTopDown.end();
556 }
557
558 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
559 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
560 ptr_const_iterator bottom_up_ptr_begin() const {
561 return PerPtrBottomUp.begin();
562 }
563 ptr_const_iterator bottom_up_ptr_end() const {
564 return PerPtrBottomUp.end();
565 }
566
Michael Gottesman97e3df02013-01-14 00:35:14 +0000567 /// Mark this block as being an entry block, which has one path from the
568 /// entry by definition.
John McCalld935e9c2011-06-15 23:37:01 +0000569 void SetAsEntry() { TopDownPathCount = 1; }
570
Michael Gottesman97e3df02013-01-14 00:35:14 +0000571 /// Mark this block as being an exit block, which has one path to an exit by
572 /// definition.
John McCalld935e9c2011-06-15 23:37:01 +0000573 void SetAsExit() { BottomUpPathCount = 1; }
574
575 PtrState &getPtrTopDownState(const Value *Arg) {
576 return PerPtrTopDown[Arg];
577 }
578
579 PtrState &getPtrBottomUpState(const Value *Arg) {
580 return PerPtrBottomUp[Arg];
581 }
582
583 void clearBottomUpPointers() {
Evan Chenge4df6a22011-08-04 18:40:26 +0000584 PerPtrBottomUp.clear();
John McCalld935e9c2011-06-15 23:37:01 +0000585 }
586
587 void clearTopDownPointers() {
588 PerPtrTopDown.clear();
589 }
590
591 void InitFromPred(const BBState &Other);
592 void InitFromSucc(const BBState &Other);
593 void MergePred(const BBState &Other);
594 void MergeSucc(const BBState &Other);
595
Michael Gottesman97e3df02013-01-14 00:35:14 +0000596 /// Return the number of possible unique paths from an entry to an exit
597 /// which pass through this block. This is only valid after both the
598 /// top-down and bottom-up traversals are complete.
John McCalld935e9c2011-06-15 23:37:01 +0000599 unsigned GetAllPathCount() const {
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000600 assert(TopDownPathCount != 0);
601 assert(BottomUpPathCount != 0);
John McCalld935e9c2011-06-15 23:37:01 +0000602 return TopDownPathCount * BottomUpPathCount;
603 }
Dan Gohman12130272011-08-12 00:26:31 +0000604
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000605 // Specialized CFG utilities.
Dan Gohmandae33492012-04-27 18:56:31 +0000606 typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000607 edge_iterator pred_begin() { return Preds.begin(); }
608 edge_iterator pred_end() { return Preds.end(); }
609 edge_iterator succ_begin() { return Succs.begin(); }
610 edge_iterator succ_end() { return Succs.end(); }
611
612 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
613 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
614
615 bool isExit() const { return Succs.empty(); }
John McCalld935e9c2011-06-15 23:37:01 +0000616 };
617}
618
619void BBState::InitFromPred(const BBState &Other) {
620 PerPtrTopDown = Other.PerPtrTopDown;
621 TopDownPathCount = Other.TopDownPathCount;
622}
623
624void BBState::InitFromSucc(const BBState &Other) {
625 PerPtrBottomUp = Other.PerPtrBottomUp;
626 BottomUpPathCount = Other.BottomUpPathCount;
627}
628
Michael Gottesman97e3df02013-01-14 00:35:14 +0000629/// The top-down traversal uses this to merge information about predecessors to
630/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +0000631void BBState::MergePred(const BBState &Other) {
632 // Other.TopDownPathCount can be 0, in which case it is either dead or a
633 // loop backedge. Loop backedges are special.
634 TopDownPathCount += Other.TopDownPathCount;
635
Michael Gottesman4385edf2013-01-14 01:47:53 +0000636 // Check for overflow. If we have overflow, fall back to conservative
637 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +0000638 if (TopDownPathCount < Other.TopDownPathCount) {
639 clearTopDownPointers();
640 return;
641 }
642
John McCalld935e9c2011-06-15 23:37:01 +0000643 // For each entry in the other set, if our set has an entry with the same key,
644 // merge the entries. Otherwise, copy the entry and merge it with an empty
645 // entry.
646 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
647 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
648 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
649 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
650 /*TopDown=*/true);
651 }
652
Dan Gohman7e315fc32011-08-11 21:06:32 +0000653 // For each entry in our set, if the other set doesn't have an entry with the
John McCalld935e9c2011-06-15 23:37:01 +0000654 // same key, force it to merge with an empty entry.
655 for (ptr_iterator MI = top_down_ptr_begin(),
656 ME = top_down_ptr_end(); MI != ME; ++MI)
657 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
658 MI->second.Merge(PtrState(), /*TopDown=*/true);
659}
660
Michael Gottesman97e3df02013-01-14 00:35:14 +0000661/// The bottom-up traversal uses this to merge information about successors to
662/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +0000663void BBState::MergeSucc(const BBState &Other) {
664 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
665 // loop backedge. Loop backedges are special.
666 BottomUpPathCount += Other.BottomUpPathCount;
667
Michael Gottesman4385edf2013-01-14 01:47:53 +0000668 // Check for overflow. If we have overflow, fall back to conservative
669 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +0000670 if (BottomUpPathCount < Other.BottomUpPathCount) {
671 clearBottomUpPointers();
672 return;
673 }
674
John McCalld935e9c2011-06-15 23:37:01 +0000675 // For each entry in the other set, if our set has an entry with the
676 // same key, merge the entries. Otherwise, copy the entry and merge
677 // it with an empty entry.
678 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
679 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
680 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
681 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
682 /*TopDown=*/false);
683 }
684
Dan Gohman7e315fc32011-08-11 21:06:32 +0000685 // For each entry in our set, if the other set doesn't have an entry
John McCalld935e9c2011-06-15 23:37:01 +0000686 // with the same key, force it to merge with an empty entry.
687 for (ptr_iterator MI = bottom_up_ptr_begin(),
688 ME = bottom_up_ptr_end(); MI != ME; ++MI)
689 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
690 MI->second.Merge(PtrState(), /*TopDown=*/false);
691}
692
Michael Gottesman81b1d432013-03-26 00:42:04 +0000693// Only enable ARC Annotations if we are building a debug version of
694// libObjCARCOpts.
695#ifndef NDEBUG
696#define ARC_ANNOTATIONS
697#endif
698
699// Define some macros along the lines of DEBUG and some helper functions to make
700// it cleaner to create annotations in the source code and to no-op when not
701// building in debug mode.
702#ifdef ARC_ANNOTATIONS
703
704#include "llvm/Support/CommandLine.h"
705
706/// Enable/disable ARC sequence annotations.
707static cl::opt<bool>
708EnableARCAnnotations("enable-objc-arc-annotations", cl::init(false));
709
710/// This function appends a unique ARCAnnotationProvenanceSourceMDKind id to an
711/// instruction so that we can track backwards when post processing via the llvm
712/// arc annotation processor tool. If the function is an
713static MDString *AppendMDNodeToSourcePtr(unsigned NodeId,
714 Value *Ptr) {
715 MDString *Hash = 0;
716
717 // If pointer is a result of an instruction and it does not have a source
718 // MDNode it, attach a new MDNode onto it. If pointer is a result of
719 // an instruction and does have a source MDNode attached to it, return a
720 // reference to said Node. Otherwise just return 0.
721 if (Instruction *Inst = dyn_cast<Instruction>(Ptr)) {
722 MDNode *Node;
723 if (!(Node = Inst->getMetadata(NodeId))) {
724 // We do not have any node. Generate and attatch the hash MDString to the
725 // instruction.
726
727 // We just use an MDString to ensure that this metadata gets written out
728 // of line at the module level and to provide a very simple format
729 // encoding the information herein. Both of these makes it simpler to
730 // parse the annotations by a simple external program.
731 std::string Str;
732 raw_string_ostream os(Str);
733 os << "(" << Inst->getParent()->getParent()->getName() << ",%"
734 << Inst->getName() << ")";
735
736 Hash = MDString::get(Inst->getContext(), os.str());
737 Inst->setMetadata(NodeId, MDNode::get(Inst->getContext(),Hash));
738 } else {
739 // We have a node. Grab its hash and return it.
740 assert(Node->getNumOperands() == 1 &&
741 "An ARCAnnotationProvenanceSourceMDKind can only have 1 operand.");
742 Hash = cast<MDString>(Node->getOperand(0));
743 }
744 } else if (Argument *Arg = dyn_cast<Argument>(Ptr)) {
745 std::string str;
746 raw_string_ostream os(str);
747 os << "(" << Arg->getParent()->getName() << ",%" << Arg->getName()
748 << ")";
749 Hash = MDString::get(Arg->getContext(), os.str());
750 }
751
752 return Hash;
753}
754
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000755static std::string SequenceToString(Sequence A) {
756 std::string str;
757 raw_string_ostream os(str);
758 os << A;
759 return os.str();
760}
761
Michael Gottesman81b1d432013-03-26 00:42:04 +0000762/// Helper function to change a Sequence into a String object using our overload
763/// for raw_ostream so we only have printing code in one location.
764static MDString *SequenceToMDString(LLVMContext &Context,
765 Sequence A) {
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000766 return MDString::get(Context, SequenceToString(A));
Michael Gottesman81b1d432013-03-26 00:42:04 +0000767}
768
769/// A simple function to generate a MDNode which describes the change in state
770/// for Value *Ptr caused by Instruction *Inst.
771static void AppendMDNodeToInstForPtr(unsigned NodeId,
772 Instruction *Inst,
773 Value *Ptr,
774 MDString *PtrSourceMDNodeID,
775 Sequence OldSeq,
776 Sequence NewSeq) {
777 MDNode *Node = 0;
778 Value *tmp[3] = {PtrSourceMDNodeID,
779 SequenceToMDString(Inst->getContext(),
780 OldSeq),
781 SequenceToMDString(Inst->getContext(),
782 NewSeq)};
783 Node = MDNode::get(Inst->getContext(),
784 ArrayRef<Value*>(tmp, 3));
785
786 Inst->setMetadata(NodeId, Node);
787}
788
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000789/// Add to the beginning of the basic block llvm.ptr.annotations which show the
790/// state of a pointer at the entrance to a basic block.
791static void GenerateARCBBEntranceAnnotation(const char *Name, BasicBlock *BB,
792 Value *Ptr, Sequence Seq) {
793 Module *M = BB->getParent()->getParent();
794 LLVMContext &C = M->getContext();
795 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
796 Type *I8XX = PointerType::getUnqual(I8X);
797 Type *Params[] = {I8XX, I8XX};
798 FunctionType *FTy = FunctionType::get(Type::getVoidTy(C),
799 ArrayRef<Type*>(Params, 2),
800 /*isVarArg=*/false);
801 Constant *Callee = M->getOrInsertFunction(Name, FTy);
Michael Gottesman60f6b282013-03-29 05:13:07 +0000802
803 IRBuilder<> Builder(BB, BB->getFirstInsertionPt());
804
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000805 Value *PtrName;
806 StringRef Tmp = Ptr->getName();
807 if (0 == (PtrName = M->getGlobalVariable(Tmp, true))) {
808 Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
809 Tmp + "_STR");
810 PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
Michael Gottesman60f6b282013-03-29 05:13:07 +0000811 cast<Constant>(ActualPtrName), Tmp);
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000812 }
813
814 Value *S;
815 std::string SeqStr = SequenceToString(Seq);
816 if (0 == (S = M->getGlobalVariable(SeqStr, true))) {
817 Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
818 SeqStr + "_STR");
819 S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
820 cast<Constant>(ActualPtrName), SeqStr);
821 }
822
823 Builder.CreateCall2(Callee, PtrName, S);
824}
825
826/// Add to the end of the basic block llvm.ptr.annotations which show the state
827/// of the pointer at the bottom of the basic block.
828static void GenerateARCBBTerminatorAnnotation(const char *Name, BasicBlock *BB,
829 Value *Ptr, Sequence Seq) {
830 Module *M = BB->getParent()->getParent();
831 LLVMContext &C = M->getContext();
832 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
833 Type *I8XX = PointerType::getUnqual(I8X);
834 Type *Params[] = {I8XX, I8XX};
835 FunctionType *FTy = FunctionType::get(Type::getVoidTy(C),
836 ArrayRef<Type*>(Params, 2),
837 /*isVarArg=*/false);
838 Constant *Callee = M->getOrInsertFunction(Name, FTy);
Michael Gottesman60f6b282013-03-29 05:13:07 +0000839
840 IRBuilder<> Builder(BB, llvm::prior(BB->end()));
841
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000842 Value *PtrName;
843 StringRef Tmp = Ptr->getName();
844 if (0 == (PtrName = M->getGlobalVariable(Tmp, true))) {
845 Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
846 Tmp + "_STR");
847 PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
Michael Gottesman60f6b282013-03-29 05:13:07 +0000848 cast<Constant>(ActualPtrName), Tmp);
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000849 }
850
851 Value *S;
852 std::string SeqStr = SequenceToString(Seq);
853 if (0 == (S = M->getGlobalVariable(SeqStr, true))) {
854 Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
855 SeqStr + "_STR");
856 S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
857 cast<Constant>(ActualPtrName), SeqStr);
858 }
Michael Gottesman60f6b282013-03-29 05:13:07 +0000859 Builder.CreateCall2(Callee, PtrName, S);
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000860}
861
Michael Gottesman81b1d432013-03-26 00:42:04 +0000862/// Adds a source annotation to pointer and a state change annotation to Inst
863/// referencing the source annotation and the old/new state of pointer.
864static void GenerateARCAnnotation(unsigned InstMDId,
865 unsigned PtrMDId,
866 Instruction *Inst,
867 Value *Ptr,
868 Sequence OldSeq,
869 Sequence NewSeq) {
870 if (EnableARCAnnotations) {
871 // First generate the source annotation on our pointer. This will return an
872 // MDString* if Ptr actually comes from an instruction implying we can put
873 // in a source annotation. If AppendMDNodeToSourcePtr returns 0 (i.e. NULL),
874 // then we know that our pointer is from an Argument so we put a reference
875 // to the argument number.
876 //
877 // The point of this is to make it easy for the
878 // llvm-arc-annotation-processor tool to cross reference where the source
879 // pointer is in the LLVM IR since the LLVM IR parser does not submit such
880 // information via debug info for backends to use (since why would anyone
881 // need such a thing from LLVM IR besides in non standard cases
882 // [i.e. this]).
883 MDString *SourcePtrMDNode =
884 AppendMDNodeToSourcePtr(PtrMDId, Ptr);
885 AppendMDNodeToInstForPtr(InstMDId, Inst, Ptr, SourcePtrMDNode, OldSeq,
886 NewSeq);
887 }
888}
889
890// The actual interface for accessing the above functionality is defined via
891// some simple macros which are defined below. We do this so that the user does
892// not need to pass in what metadata id is needed resulting in cleaner code and
893// additionally since it provides an easy way to conditionally no-op all
894// annotation support in a non-debug build.
895
896/// Use this macro to annotate a sequence state change when processing
897/// instructions bottom up,
898#define ANNOTATE_BOTTOMUP(inst, ptr, old, new) \
899 GenerateARCAnnotation(ARCAnnotationBottomUpMDKind, \
900 ARCAnnotationProvenanceSourceMDKind, (inst), \
901 const_cast<Value*>(ptr), (old), (new))
902/// Use this macro to annotate a sequence state change when processing
903/// instructions top down.
904#define ANNOTATE_TOPDOWN(inst, ptr, old, new) \
905 GenerateARCAnnotation(ARCAnnotationTopDownMDKind, \
906 ARCAnnotationProvenanceSourceMDKind, (inst), \
907 const_cast<Value*>(ptr), (old), (new))
908
Michael Gottesman43e7e002013-04-03 22:41:59 +0000909#define ANNOTATE_BB(_states, _bb, _name, _type, _direction) \
910 do { \
Michael Gottesman89279f82013-04-05 18:10:41 +0000911 if (EnableARCAnnotations) { \
912 for(BBState::ptr_const_iterator I = (_states)._direction##_ptr_begin(), \
Michael Gottesman43e7e002013-04-03 22:41:59 +0000913 E = (_states)._direction##_ptr_end(); I != E; ++I) { \
Michael Gottesman89279f82013-04-05 18:10:41 +0000914 Value *Ptr = const_cast<Value*>(I->first); \
915 Sequence Seq = I->second.GetSeq(); \
916 GenerateARCBB ## _type ## Annotation(_name, (_bb), Ptr, Seq); \
917 } \
Michael Gottesman43e7e002013-04-03 22:41:59 +0000918 } \
Michael Gottesman89279f82013-04-05 18:10:41 +0000919 } while (0)
Michael Gottesman43e7e002013-04-03 22:41:59 +0000920
Michael Gottesman89279f82013-04-05 18:10:41 +0000921#define ANNOTATE_BOTTOMUP_BBSTART(_states, _basicblock) \
Michael Gottesman43e7e002013-04-03 22:41:59 +0000922 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbstart", \
923 Entrance, bottom_up)
Michael Gottesman89279f82013-04-05 18:10:41 +0000924#define ANNOTATE_BOTTOMUP_BBEND(_states, _basicblock) \
925 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbend", \
Michael Gottesman43e7e002013-04-03 22:41:59 +0000926 Terminator, bottom_up)
Michael Gottesman89279f82013-04-05 18:10:41 +0000927#define ANNOTATE_TOPDOWN_BBSTART(_states, _basicblock) \
928 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbstart", \
Michael Gottesman43e7e002013-04-03 22:41:59 +0000929 Entrance, top_down)
Michael Gottesman89279f82013-04-05 18:10:41 +0000930#define ANNOTATE_TOPDOWN_BBEND(_states, _basicblock) \
931 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbend", \
Michael Gottesman43e7e002013-04-03 22:41:59 +0000932 Terminator, top_down)
933
Michael Gottesman81b1d432013-03-26 00:42:04 +0000934#else // !ARC_ANNOTATION
935// If annotations are off, noop.
936#define ANNOTATE_BOTTOMUP(inst, ptr, old, new)
937#define ANNOTATE_TOPDOWN(inst, ptr, old, new)
Michael Gottesman43e7e002013-04-03 22:41:59 +0000938#define ANNOTATE_BOTTOMUP_BBSTART(states, basicblock)
939#define ANNOTATE_BOTTOMUP_BBEND(states, basicblock)
940#define ANNOTATE_TOPDOWN_BBSTART(states, basicblock)
941#define ANNOTATE_TOPDOWN_BBEND(states, basicblock)
Michael Gottesman81b1d432013-03-26 00:42:04 +0000942#endif // !ARC_ANNOTATION
943
John McCalld935e9c2011-06-15 23:37:01 +0000944namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000945 /// \brief The main ARC optimization pass.
John McCalld935e9c2011-06-15 23:37:01 +0000946 class ObjCARCOpt : public FunctionPass {
947 bool Changed;
948 ProvenanceAnalysis PA;
949
Michael Gottesman97e3df02013-01-14 00:35:14 +0000950 /// A flag indicating whether this optimization pass should run.
Dan Gohmanceaac7c2011-06-20 23:20:43 +0000951 bool Run;
952
Michael Gottesman97e3df02013-01-14 00:35:14 +0000953 /// Declarations for ObjC runtime functions, for use in creating calls to
954 /// them. These are initialized lazily to avoid cluttering up the Module
955 /// with unused declarations.
John McCalld935e9c2011-06-15 23:37:01 +0000956
Michael Gottesman97e3df02013-01-14 00:35:14 +0000957 /// Declaration for ObjC runtime function
958 /// objc_retainAutoreleasedReturnValue.
959 Constant *RetainRVCallee;
960 /// Declaration for ObjC runtime function objc_autoreleaseReturnValue.
961 Constant *AutoreleaseRVCallee;
962 /// Declaration for ObjC runtime function objc_release.
963 Constant *ReleaseCallee;
964 /// Declaration for ObjC runtime function objc_retain.
965 Constant *RetainCallee;
966 /// Declaration for ObjC runtime function objc_retainBlock.
967 Constant *RetainBlockCallee;
968 /// Declaration for ObjC runtime function objc_autorelease.
969 Constant *AutoreleaseCallee;
970
971 /// Flags which determine whether each of the interesting runtine functions
972 /// is in fact used in the current function.
John McCalld935e9c2011-06-15 23:37:01 +0000973 unsigned UsedInThisFunction;
974
Michael Gottesman97e3df02013-01-14 00:35:14 +0000975 /// The Metadata Kind for clang.imprecise_release metadata.
John McCalld935e9c2011-06-15 23:37:01 +0000976 unsigned ImpreciseReleaseMDKind;
977
Michael Gottesman97e3df02013-01-14 00:35:14 +0000978 /// The Metadata Kind for clang.arc.copy_on_escape metadata.
Dan Gohmana7107f92011-10-17 22:53:25 +0000979 unsigned CopyOnEscapeMDKind;
980
Michael Gottesman97e3df02013-01-14 00:35:14 +0000981 /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata.
Dan Gohman0155f302012-02-17 18:59:53 +0000982 unsigned NoObjCARCExceptionsMDKind;
983
Michael Gottesman81b1d432013-03-26 00:42:04 +0000984#ifdef ARC_ANNOTATIONS
985 /// The Metadata Kind for llvm.arc.annotation.bottomup metadata.
986 unsigned ARCAnnotationBottomUpMDKind;
987 /// The Metadata Kind for llvm.arc.annotation.topdown metadata.
988 unsigned ARCAnnotationTopDownMDKind;
989 /// The Metadata Kind for llvm.arc.annotation.provenancesource metadata.
990 unsigned ARCAnnotationProvenanceSourceMDKind;
991#endif // ARC_ANNOATIONS
992
John McCalld935e9c2011-06-15 23:37:01 +0000993 Constant *getRetainRVCallee(Module *M);
994 Constant *getAutoreleaseRVCallee(Module *M);
995 Constant *getReleaseCallee(Module *M);
996 Constant *getRetainCallee(Module *M);
Dan Gohman6320f522011-07-22 22:29:21 +0000997 Constant *getRetainBlockCallee(Module *M);
John McCalld935e9c2011-06-15 23:37:01 +0000998 Constant *getAutoreleaseCallee(Module *M);
999
Dan Gohman728db492012-01-13 00:39:07 +00001000 bool IsRetainBlockOptimizable(const Instruction *Inst);
1001
John McCalld935e9c2011-06-15 23:37:01 +00001002 void OptimizeRetainCall(Function &F, Instruction *Retain);
1003 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
Michael Gottesman556ff612013-01-12 01:25:19 +00001004 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1005 InstructionClass &Class);
Michael Gottesman158fdf62013-03-28 20:11:19 +00001006 bool OptimizeRetainBlockCall(Function &F, Instruction *RetainBlock,
1007 InstructionClass &Class);
John McCalld935e9c2011-06-15 23:37:01 +00001008 void OptimizeIndividualCalls(Function &F);
1009
1010 void CheckForCFGHazards(const BasicBlock *BB,
1011 DenseMap<const BasicBlock *, BBState> &BBStates,
1012 BBState &MyStates) const;
Dan Gohman817a7c62012-03-22 18:24:56 +00001013 bool VisitInstructionBottomUp(Instruction *Inst,
Dan Gohman5c70fad2012-03-23 17:47:54 +00001014 BasicBlock *BB,
Dan Gohman817a7c62012-03-22 18:24:56 +00001015 MapVector<Value *, RRInfo> &Retains,
1016 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00001017 bool VisitBottomUp(BasicBlock *BB,
1018 DenseMap<const BasicBlock *, BBState> &BBStates,
1019 MapVector<Value *, RRInfo> &Retains);
Dan Gohman817a7c62012-03-22 18:24:56 +00001020 bool VisitInstructionTopDown(Instruction *Inst,
1021 DenseMap<Value *, RRInfo> &Releases,
1022 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00001023 bool VisitTopDown(BasicBlock *BB,
1024 DenseMap<const BasicBlock *, BBState> &BBStates,
1025 DenseMap<Value *, RRInfo> &Releases);
1026 bool Visit(Function &F,
1027 DenseMap<const BasicBlock *, BBState> &BBStates,
1028 MapVector<Value *, RRInfo> &Retains,
1029 DenseMap<Value *, RRInfo> &Releases);
1030
1031 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1032 MapVector<Value *, RRInfo> &Retains,
1033 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman6320f522011-07-22 22:29:21 +00001034 SmallVectorImpl<Instruction *> &DeadInsts,
1035 Module *M);
John McCalld935e9c2011-06-15 23:37:01 +00001036
Michael Gottesman9de6f962013-01-22 21:49:00 +00001037 bool ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState> &BBStates,
1038 MapVector<Value *, RRInfo> &Retains,
1039 DenseMap<Value *, RRInfo> &Releases,
1040 Module *M,
1041 SmallVector<Instruction *, 4> &NewRetains,
1042 SmallVector<Instruction *, 4> &NewReleases,
1043 SmallVector<Instruction *, 8> &DeadInsts,
1044 RRInfo &RetainsToMove,
1045 RRInfo &ReleasesToMove,
1046 Value *Arg,
1047 bool KnownSafe,
1048 bool &AnyPairsCompletelyEliminated);
1049
John McCalld935e9c2011-06-15 23:37:01 +00001050 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1051 MapVector<Value *, RRInfo> &Retains,
Dan Gohman6320f522011-07-22 22:29:21 +00001052 DenseMap<Value *, RRInfo> &Releases,
1053 Module *M);
John McCalld935e9c2011-06-15 23:37:01 +00001054
1055 void OptimizeWeakCalls(Function &F);
1056
1057 bool OptimizeSequences(Function &F);
1058
1059 void OptimizeReturns(Function &F);
1060
1061 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1062 virtual bool doInitialization(Module &M);
1063 virtual bool runOnFunction(Function &F);
1064 virtual void releaseMemory();
1065
1066 public:
1067 static char ID;
1068 ObjCARCOpt() : FunctionPass(ID) {
1069 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1070 }
1071 };
1072}
1073
1074char ObjCARCOpt::ID = 0;
1075INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1076 "objc-arc", "ObjC ARC optimization", false, false)
1077INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1078INITIALIZE_PASS_END(ObjCARCOpt,
1079 "objc-arc", "ObjC ARC optimization", false, false)
1080
1081Pass *llvm::createObjCARCOptPass() {
1082 return new ObjCARCOpt();
1083}
1084
1085void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1086 AU.addRequired<ObjCARCAliasAnalysis>();
1087 AU.addRequired<AliasAnalysis>();
1088 // ARC optimization doesn't currently split critical edges.
1089 AU.setPreservesCFG();
1090}
1091
Dan Gohman728db492012-01-13 00:39:07 +00001092bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1093 // Without the magic metadata tag, we have to assume this might be an
1094 // objc_retainBlock call inserted to convert a block pointer to an id,
1095 // in which case it really is needed.
1096 if (!Inst->getMetadata(CopyOnEscapeMDKind))
1097 return false;
1098
1099 // If the pointer "escapes" (not including being used in a call),
1100 // the copy may be needed.
Michael Gottesman774d2c02013-01-29 21:00:52 +00001101 if (DoesRetainableObjPtrEscape(Inst))
Dan Gohman728db492012-01-13 00:39:07 +00001102 return false;
1103
1104 // Otherwise, it's not needed.
1105 return true;
1106}
1107
John McCalld935e9c2011-06-15 23:37:01 +00001108Constant *ObjCARCOpt::getRetainRVCallee(Module *M) {
1109 if (!RetainRVCallee) {
1110 LLVMContext &C = M->getContext();
Jay Foadb804a2b2011-07-12 14:06:48 +00001111 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman41375a32012-05-08 23:39:44 +00001112 Type *Params[] = { I8X };
1113 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001114 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001115 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1116 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001117 RetainRVCallee =
1118 M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy,
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001119 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001120 }
1121 return RetainRVCallee;
1122}
1123
1124Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1125 if (!AutoreleaseRVCallee) {
1126 LLVMContext &C = M->getContext();
Jay Foadb804a2b2011-07-12 14:06:48 +00001127 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman41375a32012-05-08 23:39:44 +00001128 Type *Params[] = { I8X };
1129 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001130 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001131 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1132 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001133 AutoreleaseRVCallee =
1134 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001135 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001136 }
1137 return AutoreleaseRVCallee;
1138}
1139
1140Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1141 if (!ReleaseCallee) {
1142 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001143 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001144 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001145 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1146 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001147 ReleaseCallee =
1148 M->getOrInsertFunction(
1149 "objc_release",
1150 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001151 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001152 }
1153 return ReleaseCallee;
1154}
1155
1156Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1157 if (!RetainCallee) {
1158 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001159 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001160 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001161 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1162 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001163 RetainCallee =
1164 M->getOrInsertFunction(
1165 "objc_retain",
1166 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001167 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001168 }
1169 return RetainCallee;
1170}
1171
Dan Gohman6320f522011-07-22 22:29:21 +00001172Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1173 if (!RetainBlockCallee) {
1174 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001175 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Dan Gohmanfca43c22011-09-14 18:33:34 +00001176 // objc_retainBlock is not nounwind because it calls user copy constructors
1177 // which could theoretically throw.
Dan Gohman6320f522011-07-22 22:29:21 +00001178 RetainBlockCallee =
1179 M->getOrInsertFunction(
1180 "objc_retainBlock",
1181 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendlinge94d8432012-12-07 23:16:57 +00001182 AttributeSet());
Dan Gohman6320f522011-07-22 22:29:21 +00001183 }
1184 return RetainBlockCallee;
1185}
1186
John McCalld935e9c2011-06-15 23:37:01 +00001187Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1188 if (!AutoreleaseCallee) {
1189 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001190 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001191 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001192 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1193 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001194 AutoreleaseCallee =
1195 M->getOrInsertFunction(
1196 "objc_autorelease",
1197 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001198 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001199 }
1200 return AutoreleaseCallee;
1201}
1202
Michael Gottesman97e3df02013-01-14 00:35:14 +00001203/// Turn objc_retain into objc_retainAutoreleasedReturnValue if the operand is a
1204/// return value.
John McCalld935e9c2011-06-15 23:37:01 +00001205void
1206ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) {
Dan Gohmandae33492012-04-27 18:56:31 +00001207 ImmutableCallSite CS(GetObjCArg(Retain));
1208 const Instruction *Call = CS.getInstruction();
John McCalld935e9c2011-06-15 23:37:01 +00001209 if (!Call) return;
1210 if (Call->getParent() != Retain->getParent()) return;
1211
1212 // Check that the call is next to the retain.
Dan Gohmandae33492012-04-27 18:56:31 +00001213 BasicBlock::const_iterator I = Call;
John McCalld935e9c2011-06-15 23:37:01 +00001214 ++I;
Michael Gottesman65c24812013-03-25 09:27:43 +00001215 while (IsNoopInstruction(I)) ++I;
John McCalld935e9c2011-06-15 23:37:01 +00001216 if (&*I != Retain)
1217 return;
1218
1219 // Turn it to an objc_retainAutoreleasedReturnValue..
1220 Changed = true;
1221 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00001222
Michael Gottesman89279f82013-04-05 18:10:41 +00001223 DEBUG(dbgs() << "Transforming objc_retain => "
1224 "objc_retainAutoreleasedReturnValue since the operand is a "
1225 "return value.\nOld: "<< *Retain << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001226
John McCalld935e9c2011-06-15 23:37:01 +00001227 cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent()));
Michael Gottesman1e00ac62013-01-04 21:30:38 +00001228
Michael Gottesman89279f82013-04-05 18:10:41 +00001229 DEBUG(dbgs() << "New: " << *Retain << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001230}
1231
Michael Gottesman97e3df02013-01-14 00:35:14 +00001232/// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is
1233/// not a return value. Or, if it can be paired with an
1234/// objc_autoreleaseReturnValue, delete the pair and return true.
John McCalld935e9c2011-06-15 23:37:01 +00001235bool
1236ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001237 // Check for the argument being from an immediately preceding call or invoke.
Dan Gohmandae33492012-04-27 18:56:31 +00001238 const Value *Arg = GetObjCArg(RetainRV);
1239 ImmutableCallSite CS(Arg);
1240 if (const Instruction *Call = CS.getInstruction()) {
John McCalld935e9c2011-06-15 23:37:01 +00001241 if (Call->getParent() == RetainRV->getParent()) {
Dan Gohmandae33492012-04-27 18:56:31 +00001242 BasicBlock::const_iterator I = Call;
John McCalld935e9c2011-06-15 23:37:01 +00001243 ++I;
Michael Gottesman65c24812013-03-25 09:27:43 +00001244 while (IsNoopInstruction(I)) ++I;
John McCalld935e9c2011-06-15 23:37:01 +00001245 if (&*I == RetainRV)
1246 return false;
Dan Gohmandae33492012-04-27 18:56:31 +00001247 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001248 BasicBlock *RetainRVParent = RetainRV->getParent();
1249 if (II->getNormalDest() == RetainRVParent) {
Dan Gohmandae33492012-04-27 18:56:31 +00001250 BasicBlock::const_iterator I = RetainRVParent->begin();
Michael Gottesman65c24812013-03-25 09:27:43 +00001251 while (IsNoopInstruction(I)) ++I;
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001252 if (&*I == RetainRV)
1253 return false;
1254 }
John McCalld935e9c2011-06-15 23:37:01 +00001255 }
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001256 }
John McCalld935e9c2011-06-15 23:37:01 +00001257
1258 // Check for being preceded by an objc_autoreleaseReturnValue on the same
1259 // pointer. In this case, we can delete the pair.
1260 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
1261 if (I != Begin) {
Michael Gottesman65c24812013-03-25 09:27:43 +00001262 do --I; while (I != Begin && IsNoopInstruction(I));
John McCalld935e9c2011-06-15 23:37:01 +00001263 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
1264 GetObjCArg(I) == Arg) {
1265 Changed = true;
1266 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00001267
Michael Gottesman89279f82013-04-05 18:10:41 +00001268 DEBUG(dbgs() << "Erasing autoreleaseRV,retainRV pair: " << *I << "\n"
1269 << "Erasing " << *RetainRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001270
John McCalld935e9c2011-06-15 23:37:01 +00001271 EraseInstruction(I);
1272 EraseInstruction(RetainRV);
1273 return true;
1274 }
1275 }
1276
1277 // Turn it to a plain objc_retain.
1278 Changed = true;
1279 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00001280
Michael Gottesman89279f82013-04-05 18:10:41 +00001281 DEBUG(dbgs() << "Transforming objc_retainAutoreleasedReturnValue => "
Michael Gottesmandef07bb2013-01-05 17:55:42 +00001282 "objc_retain since the operand is not a return value.\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00001283 "Old = " << *RetainRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001284
John McCalld935e9c2011-06-15 23:37:01 +00001285 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
Michael Gottesmandef07bb2013-01-05 17:55:42 +00001286
Michael Gottesman89279f82013-04-05 18:10:41 +00001287 DEBUG(dbgs() << "New = " << *RetainRV << "\n");
Michael Gottesmandef07bb2013-01-05 17:55:42 +00001288
John McCalld935e9c2011-06-15 23:37:01 +00001289 return false;
1290}
1291
Michael Gottesman97e3df02013-01-14 00:35:14 +00001292/// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not
1293/// used as a return value.
John McCalld935e9c2011-06-15 23:37:01 +00001294void
Michael Gottesman556ff612013-01-12 01:25:19 +00001295ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1296 InstructionClass &Class) {
John McCalld935e9c2011-06-15 23:37:01 +00001297 // Check for a return of the pointer value.
1298 const Value *Ptr = GetObjCArg(AutoreleaseRV);
Dan Gohman10a18d52011-08-12 00:36:31 +00001299 SmallVector<const Value *, 2> Users;
1300 Users.push_back(Ptr);
1301 do {
1302 Ptr = Users.pop_back_val();
1303 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
1304 UI != UE; ++UI) {
1305 const User *I = *UI;
1306 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
1307 return;
1308 if (isa<BitCastInst>(I))
1309 Users.push_back(I);
1310 }
1311 } while (!Users.empty());
John McCalld935e9c2011-06-15 23:37:01 +00001312
1313 Changed = true;
1314 ++NumPeeps;
Michael Gottesman1bf69082013-01-06 21:07:11 +00001315
Michael Gottesman89279f82013-04-05 18:10:41 +00001316 DEBUG(dbgs() << "Transforming objc_autoreleaseReturnValue => "
Michael Gottesman1bf69082013-01-06 21:07:11 +00001317 "objc_autorelease since its operand is not used as a return "
1318 "value.\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00001319 "Old = " << *AutoreleaseRV << "\n");
Michael Gottesman1bf69082013-01-06 21:07:11 +00001320
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001321 CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
1322 AutoreleaseRVCI->
John McCalld935e9c2011-06-15 23:37:01 +00001323 setCalledFunction(getAutoreleaseCallee(F.getParent()));
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001324 AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
Michael Gottesman556ff612013-01-12 01:25:19 +00001325 Class = IC_Autorelease;
Michael Gottesman10426b52013-01-07 21:26:07 +00001326
Michael Gottesman89279f82013-04-05 18:10:41 +00001327 DEBUG(dbgs() << "New: " << *AutoreleaseRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001328
John McCalld935e9c2011-06-15 23:37:01 +00001329}
1330
Michael Gottesman158fdf62013-03-28 20:11:19 +00001331// \brief Attempt to strength reduce objc_retainBlock calls to objc_retain
1332// calls.
1333//
1334// Specifically: If an objc_retainBlock call has the copy_on_escape metadata and
1335// does not escape (following the rules of block escaping), strength reduce the
1336// objc_retainBlock to an objc_retain.
1337//
1338// TODO: If an objc_retainBlock call is dominated period by a previous
1339// objc_retainBlock call, strength reduce the objc_retainBlock to an
1340// objc_retain.
1341bool
1342ObjCARCOpt::OptimizeRetainBlockCall(Function &F, Instruction *Inst,
1343 InstructionClass &Class) {
1344 assert(GetBasicInstructionClass(Inst) == Class);
1345 assert(IC_RetainBlock == Class);
Michael Gottesman60f6b282013-03-29 05:13:07 +00001346
Michael Gottesman158fdf62013-03-28 20:11:19 +00001347 // If we can not optimize Inst, return false.
1348 if (!IsRetainBlockOptimizable(Inst))
1349 return false;
Michael Gottesman60f6b282013-03-29 05:13:07 +00001350
Michael Gottesman158fdf62013-03-28 20:11:19 +00001351 CallInst *RetainBlock = cast<CallInst>(Inst);
1352 RetainBlock->setCalledFunction(getRetainCallee(F.getParent()));
1353 // Remove copy_on_escape metadata.
1354 RetainBlock->setMetadata(CopyOnEscapeMDKind, 0);
1355 Class = IC_Retain;
Michael Gottesman60f6b282013-03-29 05:13:07 +00001356
Michael Gottesman158fdf62013-03-28 20:11:19 +00001357 return true;
1358}
1359
Michael Gottesman97e3df02013-01-14 00:35:14 +00001360/// Visit each call, one at a time, and make simplifications without doing any
1361/// additional analysis.
John McCalld935e9c2011-06-15 23:37:01 +00001362void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001363 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeIndividualCalls ==\n");
John McCalld935e9c2011-06-15 23:37:01 +00001364 // Reset all the flags in preparation for recomputing them.
1365 UsedInThisFunction = 0;
1366
1367 // Visit all objc_* calls in F.
1368 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
1369 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +00001370
John McCalld935e9c2011-06-15 23:37:01 +00001371 InstructionClass Class = GetBasicInstructionClass(Inst);
1372
Michael Gottesman89279f82013-04-05 18:10:41 +00001373 DEBUG(dbgs() << "Visiting: Class: " << Class << "; " << *Inst << "\n");
Michael Gottesman782e3442013-01-17 18:32:34 +00001374
John McCalld935e9c2011-06-15 23:37:01 +00001375 switch (Class) {
1376 default: break;
1377
1378 // Delete no-op casts. These function calls have special semantics, but
1379 // the semantics are entirely implemented via lowering in the front-end,
1380 // so by the time they reach the optimizer, they are just no-op calls
1381 // which return their argument.
1382 //
1383 // There are gray areas here, as the ability to cast reference-counted
1384 // pointers to raw void* and back allows code to break ARC assumptions,
1385 // however these are currently considered to be unimportant.
1386 case IC_NoopCast:
1387 Changed = true;
1388 ++NumNoops;
Michael Gottesman89279f82013-04-05 18:10:41 +00001389 DEBUG(dbgs() << "Erasing no-op cast: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001390 EraseInstruction(Inst);
1391 continue;
1392
1393 // If the pointer-to-weak-pointer is null, it's undefined behavior.
1394 case IC_StoreWeak:
1395 case IC_LoadWeak:
1396 case IC_LoadWeakRetained:
1397 case IC_InitWeak:
1398 case IC_DestroyWeak: {
1399 CallInst *CI = cast<CallInst>(Inst);
Michael Gottesman65c24812013-03-25 09:27:43 +00001400 if (IsNullOrUndef(CI->getArgOperand(0))) {
Dan Gohman670f9372012-04-13 18:57:48 +00001401 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +00001402 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001403 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1404 Constant::getNullValue(Ty),
1405 CI);
Michael Gottesman10426b52013-01-07 21:26:07 +00001406 llvm::Value *NewValue = UndefValue::get(CI->getType());
Michael Gottesman89279f82013-04-05 18:10:41 +00001407 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
1408 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001409 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +00001410 CI->eraseFromParent();
1411 continue;
1412 }
1413 break;
1414 }
1415 case IC_CopyWeak:
1416 case IC_MoveWeak: {
1417 CallInst *CI = cast<CallInst>(Inst);
Michael Gottesman65c24812013-03-25 09:27:43 +00001418 if (IsNullOrUndef(CI->getArgOperand(0)) ||
1419 IsNullOrUndef(CI->getArgOperand(1))) {
Dan Gohman670f9372012-04-13 18:57:48 +00001420 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +00001421 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001422 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1423 Constant::getNullValue(Ty),
1424 CI);
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001425
1426 llvm::Value *NewValue = UndefValue::get(CI->getType());
Michael Gottesman89279f82013-04-05 18:10:41 +00001427 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
1428 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001429
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001430 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +00001431 CI->eraseFromParent();
1432 continue;
1433 }
1434 break;
1435 }
Michael Gottesman158fdf62013-03-28 20:11:19 +00001436 case IC_RetainBlock:
1437 // If we strength reduce an objc_retainBlock to amn objc_retain, continue
1438 // onto the objc_retain peephole optimizations. Otherwise break.
1439 if (!OptimizeRetainBlockCall(F, Inst, Class))
1440 break;
1441 // FALLTHROUGH
John McCalld935e9c2011-06-15 23:37:01 +00001442 case IC_Retain:
1443 OptimizeRetainCall(F, Inst);
1444 break;
1445 case IC_RetainRV:
1446 if (OptimizeRetainRVCall(F, Inst))
1447 continue;
1448 break;
1449 case IC_AutoreleaseRV:
Michael Gottesman556ff612013-01-12 01:25:19 +00001450 OptimizeAutoreleaseRVCall(F, Inst, Class);
John McCalld935e9c2011-06-15 23:37:01 +00001451 break;
1452 }
1453
Michael Gottesmanb8c88362013-04-03 02:57:24 +00001454 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
John McCalld935e9c2011-06-15 23:37:01 +00001455 if (IsAutorelease(Class) && Inst->use_empty()) {
1456 CallInst *Call = cast<CallInst>(Inst);
1457 const Value *Arg = Call->getArgOperand(0);
1458 Arg = FindSingleUseIdentifiedObject(Arg);
1459 if (Arg) {
1460 Changed = true;
1461 ++NumAutoreleases;
1462
1463 // Create the declaration lazily.
1464 LLVMContext &C = Inst->getContext();
1465 CallInst *NewCall =
1466 CallInst::Create(getReleaseCallee(F.getParent()),
1467 Call->getArgOperand(0), "", Call);
1468 NewCall->setMetadata(ImpreciseReleaseMDKind,
1469 MDNode::get(C, ArrayRef<Value *>()));
Michael Gottesman10426b52013-01-07 21:26:07 +00001470
Michael Gottesman89279f82013-04-05 18:10:41 +00001471 DEBUG(dbgs() << "Replacing autorelease{,RV}(x) with objc_release(x) "
1472 "since x is otherwise unused.\nOld: " << *Call << "\nNew: "
1473 << *NewCall << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001474
John McCalld935e9c2011-06-15 23:37:01 +00001475 EraseInstruction(Call);
1476 Inst = NewCall;
1477 Class = IC_Release;
1478 }
1479 }
1480
1481 // For functions which can never be passed stack arguments, add
1482 // a tail keyword.
1483 if (IsAlwaysTail(Class)) {
1484 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +00001485 DEBUG(dbgs() << "Adding tail keyword to function since it can never be "
1486 "passed stack args: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001487 cast<CallInst>(Inst)->setTailCall();
1488 }
1489
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001490 // Ensure that functions that can never have a "tail" keyword due to the
1491 // semantics of ARC truly do not do so.
1492 if (IsNeverTail(Class)) {
1493 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +00001494 DEBUG(dbgs() << "Removing tail keyword from function: " << *Inst <<
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001495 "\n");
1496 cast<CallInst>(Inst)->setTailCall(false);
1497 }
1498
John McCalld935e9c2011-06-15 23:37:01 +00001499 // Set nounwind as needed.
1500 if (IsNoThrow(Class)) {
1501 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +00001502 DEBUG(dbgs() << "Found no throw class. Setting nounwind on: " << *Inst
1503 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001504 cast<CallInst>(Inst)->setDoesNotThrow();
1505 }
1506
1507 if (!IsNoopOnNull(Class)) {
1508 UsedInThisFunction |= 1 << Class;
1509 continue;
1510 }
1511
1512 const Value *Arg = GetObjCArg(Inst);
1513
1514 // ARC calls with null are no-ops. Delete them.
Michael Gottesman65c24812013-03-25 09:27:43 +00001515 if (IsNullOrUndef(Arg)) {
John McCalld935e9c2011-06-15 23:37:01 +00001516 Changed = true;
1517 ++NumNoops;
Michael Gottesman89279f82013-04-05 18:10:41 +00001518 DEBUG(dbgs() << "ARC calls with null are no-ops. Erasing: " << *Inst
1519 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001520 EraseInstruction(Inst);
1521 continue;
1522 }
1523
1524 // Keep track of which of retain, release, autorelease, and retain_block
1525 // are actually present in this function.
1526 UsedInThisFunction |= 1 << Class;
1527
1528 // If Arg is a PHI, and one or more incoming values to the
1529 // PHI are null, and the call is control-equivalent to the PHI, and there
1530 // are no relevant side effects between the PHI and the call, the call
1531 // could be pushed up to just those paths with non-null incoming values.
1532 // For now, don't bother splitting critical edges for this.
1533 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
1534 Worklist.push_back(std::make_pair(Inst, Arg));
1535 do {
1536 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
1537 Inst = Pair.first;
1538 Arg = Pair.second;
1539
1540 const PHINode *PN = dyn_cast<PHINode>(Arg);
1541 if (!PN) continue;
1542
1543 // Determine if the PHI has any null operands, or any incoming
1544 // critical edges.
1545 bool HasNull = false;
1546 bool HasCriticalEdges = false;
1547 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1548 Value *Incoming =
1549 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
Michael Gottesman65c24812013-03-25 09:27:43 +00001550 if (IsNullOrUndef(Incoming))
John McCalld935e9c2011-06-15 23:37:01 +00001551 HasNull = true;
1552 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
1553 .getNumSuccessors() != 1) {
1554 HasCriticalEdges = true;
1555 break;
1556 }
1557 }
1558 // If we have null operands and no critical edges, optimize.
1559 if (!HasCriticalEdges && HasNull) {
1560 SmallPtrSet<Instruction *, 4> DependingInstructions;
1561 SmallPtrSet<const BasicBlock *, 4> Visited;
1562
1563 // Check that there is nothing that cares about the reference
1564 // count between the call and the phi.
Dan Gohman8478d762012-04-13 00:59:57 +00001565 switch (Class) {
1566 case IC_Retain:
1567 case IC_RetainBlock:
1568 // These can always be moved up.
1569 break;
1570 case IC_Release:
Dan Gohman41375a32012-05-08 23:39:44 +00001571 // These can't be moved across things that care about the retain
1572 // count.
Dan Gohman8478d762012-04-13 00:59:57 +00001573 FindDependencies(NeedsPositiveRetainCount, Arg,
1574 Inst->getParent(), Inst,
1575 DependingInstructions, Visited, PA);
1576 break;
1577 case IC_Autorelease:
1578 // These can't be moved across autorelease pool scope boundaries.
1579 FindDependencies(AutoreleasePoolBoundary, Arg,
1580 Inst->getParent(), Inst,
1581 DependingInstructions, Visited, PA);
1582 break;
1583 case IC_RetainRV:
1584 case IC_AutoreleaseRV:
1585 // Don't move these; the RV optimization depends on the autoreleaseRV
1586 // being tail called, and the retainRV being immediately after a call
1587 // (which might still happen if we get lucky with codegen layout, but
1588 // it's not worth taking the chance).
1589 continue;
1590 default:
1591 llvm_unreachable("Invalid dependence flavor");
1592 }
1593
John McCalld935e9c2011-06-15 23:37:01 +00001594 if (DependingInstructions.size() == 1 &&
1595 *DependingInstructions.begin() == PN) {
1596 Changed = true;
1597 ++NumPartialNoops;
1598 // Clone the call into each predecessor that has a non-null value.
1599 CallInst *CInst = cast<CallInst>(Inst);
Chris Lattner229907c2011-07-18 04:54:35 +00001600 Type *ParamTy = CInst->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001601 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1602 Value *Incoming =
1603 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
Michael Gottesman65c24812013-03-25 09:27:43 +00001604 if (!IsNullOrUndef(Incoming)) {
John McCalld935e9c2011-06-15 23:37:01 +00001605 CallInst *Clone = cast<CallInst>(CInst->clone());
1606 Value *Op = PN->getIncomingValue(i);
1607 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
1608 if (Op->getType() != ParamTy)
1609 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
1610 Clone->setArgOperand(0, Op);
1611 Clone->insertBefore(InsertPos);
Michael Gottesmanc189a392013-01-09 19:23:24 +00001612
Michael Gottesman89279f82013-04-05 18:10:41 +00001613 DEBUG(dbgs() << "Cloning "
Michael Gottesmanc189a392013-01-09 19:23:24 +00001614 << *CInst << "\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00001615 "And inserting clone at " << *InsertPos << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001616 Worklist.push_back(std::make_pair(Clone, Incoming));
1617 }
1618 }
1619 // Erase the original call.
Michael Gottesmanc189a392013-01-09 19:23:24 +00001620 DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001621 EraseInstruction(CInst);
1622 continue;
1623 }
1624 }
1625 } while (!Worklist.empty());
1626 }
1627}
1628
Michael Gottesman97e3df02013-01-14 00:35:14 +00001629/// Check for critical edges, loop boundaries, irreducible control flow, or
1630/// other CFG structures where moving code across the edge would result in it
1631/// being executed more.
John McCalld935e9c2011-06-15 23:37:01 +00001632void
1633ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
1634 DenseMap<const BasicBlock *, BBState> &BBStates,
1635 BBState &MyStates) const {
1636 // If any top-down local-use or possible-dec has a succ which is earlier in
1637 // the sequence, forget it.
Dan Gohman55b06742012-03-02 01:13:53 +00001638 for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
John McCalld935e9c2011-06-15 23:37:01 +00001639 E = MyStates.top_down_ptr_end(); I != E; ++I)
1640 switch (I->second.GetSeq()) {
1641 default: break;
1642 case S_Use: {
1643 const Value *Arg = I->first;
1644 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
1645 bool SomeSuccHasSame = false;
1646 bool AllSuccsHaveSame = true;
Dan Gohman55b06742012-03-02 01:13:53 +00001647 PtrState &S = I->second;
Dan Gohman0155f302012-02-17 18:59:53 +00001648 succ_const_iterator SI(TI), SE(TI, false);
1649
Dan Gohman0155f302012-02-17 18:59:53 +00001650 for (; SI != SE; ++SI) {
Dan Gohman362eb692012-03-02 01:26:46 +00001651 Sequence SuccSSeq = S_None;
1652 bool SuccSRRIKnownSafe = false;
Dan Gohman41375a32012-05-08 23:39:44 +00001653 // If VisitBottomUp has pointer information for this successor, take
1654 // what we know about it.
Dan Gohmandae33492012-04-27 18:56:31 +00001655 DenseMap<const BasicBlock *, BBState>::iterator BBI =
1656 BBStates.find(*SI);
1657 assert(BBI != BBStates.end());
1658 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
1659 SuccSSeq = SuccS.GetSeq();
1660 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
Dan Gohman362eb692012-03-02 01:26:46 +00001661 switch (SuccSSeq) {
John McCalld935e9c2011-06-15 23:37:01 +00001662 case S_None:
Dan Gohman12130272011-08-12 00:26:31 +00001663 case S_CanRelease: {
Dan Gohman362eb692012-03-02 01:26:46 +00001664 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
Dan Gohman12130272011-08-12 00:26:31 +00001665 S.ClearSequenceProgress();
Dan Gohman362eb692012-03-02 01:26:46 +00001666 break;
1667 }
Dan Gohman12130272011-08-12 00:26:31 +00001668 continue;
1669 }
John McCalld935e9c2011-06-15 23:37:01 +00001670 case S_Use:
1671 SomeSuccHasSame = true;
1672 break;
1673 case S_Stop:
1674 case S_Release:
1675 case S_MovableRelease:
Dan Gohman362eb692012-03-02 01:26:46 +00001676 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
Dan Gohman12130272011-08-12 00:26:31 +00001677 AllSuccsHaveSame = false;
John McCalld935e9c2011-06-15 23:37:01 +00001678 break;
1679 case S_Retain:
1680 llvm_unreachable("bottom-up pointer in retain state!");
1681 }
Dan Gohman12130272011-08-12 00:26:31 +00001682 }
John McCalld935e9c2011-06-15 23:37:01 +00001683 // If the state at the other end of any of the successor edges
1684 // matches the current state, require all edges to match. This
1685 // guards against loops in the middle of a sequence.
1686 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohman12130272011-08-12 00:26:31 +00001687 S.ClearSequenceProgress();
Dan Gohman044437062011-12-12 18:13:53 +00001688 break;
John McCalld935e9c2011-06-15 23:37:01 +00001689 }
1690 case S_CanRelease: {
1691 const Value *Arg = I->first;
1692 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
1693 bool SomeSuccHasSame = false;
1694 bool AllSuccsHaveSame = true;
Dan Gohman55b06742012-03-02 01:13:53 +00001695 PtrState &S = I->second;
Dan Gohman0155f302012-02-17 18:59:53 +00001696 succ_const_iterator SI(TI), SE(TI, false);
1697
Dan Gohman0155f302012-02-17 18:59:53 +00001698 for (; SI != SE; ++SI) {
Dan Gohman362eb692012-03-02 01:26:46 +00001699 Sequence SuccSSeq = S_None;
1700 bool SuccSRRIKnownSafe = false;
Dan Gohman41375a32012-05-08 23:39:44 +00001701 // If VisitBottomUp has pointer information for this successor, take
1702 // what we know about it.
Dan Gohmandae33492012-04-27 18:56:31 +00001703 DenseMap<const BasicBlock *, BBState>::iterator BBI =
1704 BBStates.find(*SI);
1705 assert(BBI != BBStates.end());
1706 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
1707 SuccSSeq = SuccS.GetSeq();
1708 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
Dan Gohman362eb692012-03-02 01:26:46 +00001709 switch (SuccSSeq) {
Dan Gohman12130272011-08-12 00:26:31 +00001710 case S_None: {
Dan Gohman362eb692012-03-02 01:26:46 +00001711 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
Dan Gohman12130272011-08-12 00:26:31 +00001712 S.ClearSequenceProgress();
Dan Gohman362eb692012-03-02 01:26:46 +00001713 break;
1714 }
Dan Gohman12130272011-08-12 00:26:31 +00001715 continue;
1716 }
John McCalld935e9c2011-06-15 23:37:01 +00001717 case S_CanRelease:
1718 SomeSuccHasSame = true;
1719 break;
1720 case S_Stop:
1721 case S_Release:
1722 case S_MovableRelease:
1723 case S_Use:
Dan Gohman362eb692012-03-02 01:26:46 +00001724 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
Dan Gohman12130272011-08-12 00:26:31 +00001725 AllSuccsHaveSame = false;
John McCalld935e9c2011-06-15 23:37:01 +00001726 break;
1727 case S_Retain:
1728 llvm_unreachable("bottom-up pointer in retain state!");
1729 }
Dan Gohman12130272011-08-12 00:26:31 +00001730 }
John McCalld935e9c2011-06-15 23:37:01 +00001731 // If the state at the other end of any of the successor edges
1732 // matches the current state, require all edges to match. This
1733 // guards against loops in the middle of a sequence.
1734 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohman12130272011-08-12 00:26:31 +00001735 S.ClearSequenceProgress();
Dan Gohman044437062011-12-12 18:13:53 +00001736 break;
John McCalld935e9c2011-06-15 23:37:01 +00001737 }
1738 }
1739}
1740
1741bool
Dan Gohman817a7c62012-03-22 18:24:56 +00001742ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
Dan Gohman5c70fad2012-03-23 17:47:54 +00001743 BasicBlock *BB,
Dan Gohman817a7c62012-03-22 18:24:56 +00001744 MapVector<Value *, RRInfo> &Retains,
1745 BBState &MyStates) {
1746 bool NestingDetected = false;
1747 InstructionClass Class = GetInstructionClass(Inst);
1748 const Value *Arg = 0;
1749
1750 switch (Class) {
1751 case IC_Release: {
1752 Arg = GetObjCArg(Inst);
1753
1754 PtrState &S = MyStates.getPtrBottomUpState(Arg);
1755
1756 // If we see two releases in a row on the same pointer. If so, make
1757 // a note, and we'll cicle back to revisit it after we've
1758 // hopefully eliminated the second release, which may allow us to
1759 // eliminate the first release too.
1760 // Theoretically we could implement removal of nested retain+release
1761 // pairs by making PtrState hold a stack of states, but this is
1762 // simple and avoids adding overhead for the non-nested case.
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001763 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001764 DEBUG(dbgs() << "Found nested releases (i.e. a release pair)\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00001765 NestingDetected = true;
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001766 }
Dan Gohman817a7c62012-03-22 18:24:56 +00001767
Dan Gohman817a7c62012-03-22 18:24:56 +00001768 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001769 Sequence NewSeq = ReleaseMetadata ? S_MovableRelease : S_Release;
1770 ANNOTATE_BOTTOMUP(Inst, Arg, S.GetSeq(), NewSeq);
1771 S.ResetSequenceProgress(NewSeq);
Dan Gohman817a7c62012-03-22 18:24:56 +00001772 S.RRI.ReleaseMetadata = ReleaseMetadata;
Michael Gottesman07beea42013-03-23 05:31:01 +00001773 S.RRI.KnownSafe = S.HasKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001774 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
1775 S.RRI.Calls.insert(Inst);
Dan Gohmandf476e52012-09-04 23:16:20 +00001776 S.SetKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001777 break;
1778 }
1779 case IC_RetainBlock:
Michael Gottesman158fdf62013-03-28 20:11:19 +00001780 // In OptimizeIndividualCalls, we have strength reduced all optimizable
1781 // objc_retainBlocks to objc_retains. Thus at this point any
1782 // objc_retainBlocks that we see are not optimizable.
1783 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001784 case IC_Retain:
1785 case IC_RetainRV: {
1786 Arg = GetObjCArg(Inst);
1787
1788 PtrState &S = MyStates.getPtrBottomUpState(Arg);
Dan Gohman62079b42012-04-25 00:50:46 +00001789 S.SetKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001790
Michael Gottesman81b1d432013-03-26 00:42:04 +00001791 Sequence OldSeq = S.GetSeq();
1792 switch (OldSeq) {
Dan Gohman817a7c62012-03-22 18:24:56 +00001793 case S_Stop:
1794 case S_Release:
1795 case S_MovableRelease:
1796 case S_Use:
1797 S.RRI.ReverseInsertPts.clear();
1798 // FALL THROUGH
1799 case S_CanRelease:
1800 // Don't do retain+release tracking for IC_RetainRV, because it's
1801 // better to let it remain as the first instruction after a call.
Michael Gottesmanba648592013-03-28 23:08:44 +00001802 if (Class != IC_RetainRV)
Dan Gohman817a7c62012-03-22 18:24:56 +00001803 Retains[Inst] = S.RRI;
Dan Gohman817a7c62012-03-22 18:24:56 +00001804 S.ClearSequenceProgress();
1805 break;
1806 case S_None:
1807 break;
1808 case S_Retain:
1809 llvm_unreachable("bottom-up pointer in retain state!");
1810 }
Michael Gottesman81b1d432013-03-26 00:42:04 +00001811 ANNOTATE_BOTTOMUP(Inst, Arg, OldSeq, S.GetSeq());
Dan Gohman817a7c62012-03-22 18:24:56 +00001812 return NestingDetected;
1813 }
1814 case IC_AutoreleasepoolPop:
1815 // Conservatively, clear MyStates for all known pointers.
1816 MyStates.clearBottomUpPointers();
1817 return NestingDetected;
1818 case IC_AutoreleasepoolPush:
1819 case IC_None:
1820 // These are irrelevant.
1821 return NestingDetected;
1822 default:
1823 break;
1824 }
1825
1826 // Consider any other possible effects of this instruction on each
1827 // pointer being tracked.
1828 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
1829 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
1830 const Value *Ptr = MI->first;
1831 if (Ptr == Arg)
1832 continue; // Handled above.
1833 PtrState &S = MI->second;
1834 Sequence Seq = S.GetSeq();
1835
1836 // Check for possible releases.
1837 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001838 DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr
1839 << "\n");
Michael Gottesman764b1cf2013-03-23 05:46:19 +00001840 S.ClearKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001841 switch (Seq) {
1842 case S_Use:
1843 S.SetSeq(S_CanRelease);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001844 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S.GetSeq());
Dan Gohman817a7c62012-03-22 18:24:56 +00001845 continue;
1846 case S_CanRelease:
1847 case S_Release:
1848 case S_MovableRelease:
1849 case S_Stop:
1850 case S_None:
1851 break;
1852 case S_Retain:
1853 llvm_unreachable("bottom-up pointer in retain state!");
1854 }
1855 }
1856
1857 // Check for possible direct uses.
1858 switch (Seq) {
1859 case S_Release:
1860 case S_MovableRelease:
1861 if (CanUse(Inst, Ptr, PA, Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001862 DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr
1863 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00001864 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohman5c70fad2012-03-23 17:47:54 +00001865 // If this is an invoke instruction, we're scanning it as part of
1866 // one of its successor blocks, since we can't insert code after it
1867 // in its own block, and we don't want to split critical edges.
1868 if (isa<InvokeInst>(Inst))
1869 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
1870 else
Francois Pichet4b9ab742012-03-24 01:36:37 +00001871 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohman817a7c62012-03-22 18:24:56 +00001872 S.SetSeq(S_Use);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001873 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
John McCall20182ac2013-03-22 21:38:36 +00001874 } else if (Seq == S_Release && IsUser(Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001875 DEBUG(dbgs() << "PreciseReleaseUse: Seq: " << Seq << "; " << *Ptr
1876 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00001877 // Non-movable releases depend on any possible objc pointer use.
1878 S.SetSeq(S_Stop);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001879 ANNOTATE_BOTTOMUP(Inst, Ptr, S_Release, S_Stop);
Dan Gohman817a7c62012-03-22 18:24:56 +00001880 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohman5c70fad2012-03-23 17:47:54 +00001881 // As above; handle invoke specially.
1882 if (isa<InvokeInst>(Inst))
1883 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
1884 else
Francois Pichet4b9ab742012-03-24 01:36:37 +00001885 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohman817a7c62012-03-22 18:24:56 +00001886 }
1887 break;
1888 case S_Stop:
Michael Gottesman81b1d432013-03-26 00:42:04 +00001889 if (CanUse(Inst, Ptr, PA, Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001890 DEBUG(dbgs() << "PreciseStopUse: Seq: " << Seq << "; " << *Ptr
1891 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00001892 S.SetSeq(S_Use);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001893 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
1894 }
Dan Gohman817a7c62012-03-22 18:24:56 +00001895 break;
1896 case S_CanRelease:
1897 case S_Use:
1898 case S_None:
1899 break;
1900 case S_Retain:
1901 llvm_unreachable("bottom-up pointer in retain state!");
1902 }
1903 }
1904
1905 return NestingDetected;
1906}
1907
1908bool
John McCalld935e9c2011-06-15 23:37:01 +00001909ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
1910 DenseMap<const BasicBlock *, BBState> &BBStates,
1911 MapVector<Value *, RRInfo> &Retains) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001912
1913 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitBottomUp ==\n");
1914
John McCalld935e9c2011-06-15 23:37:01 +00001915 bool NestingDetected = false;
1916 BBState &MyStates = BBStates[BB];
1917
1918 // Merge the states from each successor to compute the initial state
1919 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00001920 BBState::edge_iterator SI(MyStates.succ_begin()),
1921 SE(MyStates.succ_end());
1922 if (SI != SE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001923 const BasicBlock *Succ = *SI;
1924 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
1925 assert(I != BBStates.end());
1926 MyStates.InitFromSucc(I->second);
1927 ++SI;
1928 for (; SI != SE; ++SI) {
1929 Succ = *SI;
1930 I = BBStates.find(Succ);
1931 assert(I != BBStates.end());
1932 MyStates.MergeSucc(I->second);
1933 }
Michael Gottesman60f6b282013-03-29 05:13:07 +00001934 }
Michael Gottesmancd4de0f2013-03-26 00:42:09 +00001935
Michael Gottesman43e7e002013-04-03 22:41:59 +00001936 // If ARC Annotations are enabled, output the current state of pointers at the
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00001937 // bottom of the basic block.
Michael Gottesman43e7e002013-04-03 22:41:59 +00001938 ANNOTATE_BOTTOMUP_BBEND(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00001939
John McCalld935e9c2011-06-15 23:37:01 +00001940 // Visit all the instructions, bottom-up.
1941 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
1942 Instruction *Inst = llvm::prior(I);
Dan Gohman5c70fad2012-03-23 17:47:54 +00001943
1944 // Invoke instructions are visited as part of their successors (below).
1945 if (isa<InvokeInst>(Inst))
1946 continue;
1947
Michael Gottesman89279f82013-04-05 18:10:41 +00001948 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001949
Dan Gohman5c70fad2012-03-23 17:47:54 +00001950 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
1951 }
1952
Dan Gohmandae33492012-04-27 18:56:31 +00001953 // If there's a predecessor with an invoke, visit the invoke as if it were
1954 // part of this block, since we can't insert code after an invoke in its own
1955 // block, and we don't want to split critical edges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001956 for (BBState::edge_iterator PI(MyStates.pred_begin()),
1957 PE(MyStates.pred_end()); PI != PE; ++PI) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00001958 BasicBlock *Pred = *PI;
Dan Gohmandae33492012-04-27 18:56:31 +00001959 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
1960 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
Dan Gohman817a7c62012-03-22 18:24:56 +00001961 }
John McCalld935e9c2011-06-15 23:37:01 +00001962
Michael Gottesman43e7e002013-04-03 22:41:59 +00001963 // If ARC Annotations are enabled, output the current state of pointers at the
1964 // top of the basic block.
1965 ANNOTATE_BOTTOMUP_BBSTART(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00001966
Dan Gohman817a7c62012-03-22 18:24:56 +00001967 return NestingDetected;
1968}
John McCalld935e9c2011-06-15 23:37:01 +00001969
Dan Gohman817a7c62012-03-22 18:24:56 +00001970bool
1971ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
1972 DenseMap<Value *, RRInfo> &Releases,
1973 BBState &MyStates) {
1974 bool NestingDetected = false;
1975 InstructionClass Class = GetInstructionClass(Inst);
1976 const Value *Arg = 0;
John McCalld935e9c2011-06-15 23:37:01 +00001977
Dan Gohman817a7c62012-03-22 18:24:56 +00001978 switch (Class) {
1979 case IC_RetainBlock:
Michael Gottesman158fdf62013-03-28 20:11:19 +00001980 // In OptimizeIndividualCalls, we have strength reduced all optimizable
1981 // objc_retainBlocks to objc_retains. Thus at this point any
1982 // objc_retainBlocks that we see are not optimizable.
1983 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001984 case IC_Retain:
1985 case IC_RetainRV: {
1986 Arg = GetObjCArg(Inst);
1987
1988 PtrState &S = MyStates.getPtrTopDownState(Arg);
1989
1990 // Don't do retain+release tracking for IC_RetainRV, because it's
1991 // better to let it remain as the first instruction after a call.
1992 if (Class != IC_RetainRV) {
1993 // If we see two retains in a row on the same pointer. If so, make
John McCalld935e9c2011-06-15 23:37:01 +00001994 // a note, and we'll cicle back to revisit it after we've
Dan Gohman817a7c62012-03-22 18:24:56 +00001995 // hopefully eliminated the second retain, which may allow us to
1996 // eliminate the first retain too.
John McCalld935e9c2011-06-15 23:37:01 +00001997 // Theoretically we could implement removal of nested retain+release
1998 // pairs by making PtrState hold a stack of states, but this is
1999 // simple and avoids adding overhead for the non-nested case.
Dan Gohman817a7c62012-03-22 18:24:56 +00002000 if (S.GetSeq() == S_Retain)
John McCalld935e9c2011-06-15 23:37:01 +00002001 NestingDetected = true;
2002
Michael Gottesman81b1d432013-03-26 00:42:04 +00002003 ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_Retain);
Dan Gohman62079b42012-04-25 00:50:46 +00002004 S.ResetSequenceProgress(S_Retain);
Michael Gottesman07beea42013-03-23 05:31:01 +00002005 S.RRI.KnownSafe = S.HasKnownPositiveRefCount();
John McCalld935e9c2011-06-15 23:37:01 +00002006 S.RRI.Calls.insert(Inst);
John McCalld935e9c2011-06-15 23:37:01 +00002007 }
John McCalld935e9c2011-06-15 23:37:01 +00002008
Dan Gohmandf476e52012-09-04 23:16:20 +00002009 S.SetKnownPositiveRefCount();
Dan Gohmanf64ff8e2012-07-23 19:27:31 +00002010
2011 // A retain can be a potential use; procede to the generic checking
2012 // code below.
2013 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00002014 }
2015 case IC_Release: {
2016 Arg = GetObjCArg(Inst);
2017
2018 PtrState &S = MyStates.getPtrTopDownState(Arg);
Michael Gottesman764b1cf2013-03-23 05:46:19 +00002019 S.ClearKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00002020
2021 switch (S.GetSeq()) {
2022 case S_Retain:
2023 case S_CanRelease:
2024 S.RRI.ReverseInsertPts.clear();
2025 // FALL THROUGH
2026 case S_Use:
2027 S.RRI.ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2028 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2029 Releases[Inst] = S.RRI;
Michael Gottesman81b1d432013-03-26 00:42:04 +00002030 ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_None);
Dan Gohman817a7c62012-03-22 18:24:56 +00002031 S.ClearSequenceProgress();
2032 break;
2033 case S_None:
2034 break;
2035 case S_Stop:
2036 case S_Release:
2037 case S_MovableRelease:
2038 llvm_unreachable("top-down pointer in release state!");
2039 }
2040 break;
2041 }
2042 case IC_AutoreleasepoolPop:
2043 // Conservatively, clear MyStates for all known pointers.
2044 MyStates.clearTopDownPointers();
2045 return NestingDetected;
2046 case IC_AutoreleasepoolPush:
2047 case IC_None:
2048 // These are irrelevant.
2049 return NestingDetected;
2050 default:
2051 break;
2052 }
2053
2054 // Consider any other possible effects of this instruction on each
2055 // pointer being tracked.
2056 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
2057 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
2058 const Value *Ptr = MI->first;
2059 if (Ptr == Arg)
2060 continue; // Handled above.
2061 PtrState &S = MI->second;
2062 Sequence Seq = S.GetSeq();
2063
2064 // Check for possible releases.
2065 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Michael Gottesman764b1cf2013-03-23 05:46:19 +00002066 S.ClearKnownPositiveRefCount();
John McCalld935e9c2011-06-15 23:37:01 +00002067 switch (Seq) {
Dan Gohman817a7c62012-03-22 18:24:56 +00002068 case S_Retain:
2069 S.SetSeq(S_CanRelease);
Michael Gottesman81b1d432013-03-26 00:42:04 +00002070 ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_CanRelease);
Dan Gohman817a7c62012-03-22 18:24:56 +00002071 assert(S.RRI.ReverseInsertPts.empty());
2072 S.RRI.ReverseInsertPts.insert(Inst);
2073
2074 // One call can't cause a transition from S_Retain to S_CanRelease
2075 // and S_CanRelease to S_Use. If we've made the first transition,
2076 // we're done.
2077 continue;
John McCalld935e9c2011-06-15 23:37:01 +00002078 case S_Use:
Dan Gohman817a7c62012-03-22 18:24:56 +00002079 case S_CanRelease:
John McCalld935e9c2011-06-15 23:37:01 +00002080 case S_None:
2081 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00002082 case S_Stop:
2083 case S_Release:
2084 case S_MovableRelease:
2085 llvm_unreachable("top-down pointer in release state!");
John McCalld935e9c2011-06-15 23:37:01 +00002086 }
2087 }
Dan Gohman817a7c62012-03-22 18:24:56 +00002088
2089 // Check for possible direct uses.
2090 switch (Seq) {
2091 case S_CanRelease:
Michael Gottesman81b1d432013-03-26 00:42:04 +00002092 if (CanUse(Inst, Ptr, PA, Class)) {
Dan Gohman817a7c62012-03-22 18:24:56 +00002093 S.SetSeq(S_Use);
Michael Gottesman81b1d432013-03-26 00:42:04 +00002094 ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_Use);
2095 }
Dan Gohman817a7c62012-03-22 18:24:56 +00002096 break;
2097 case S_Retain:
2098 case S_Use:
2099 case S_None:
2100 break;
2101 case S_Stop:
2102 case S_Release:
2103 case S_MovableRelease:
2104 llvm_unreachable("top-down pointer in release state!");
2105 }
John McCalld935e9c2011-06-15 23:37:01 +00002106 }
2107
2108 return NestingDetected;
2109}
2110
2111bool
2112ObjCARCOpt::VisitTopDown(BasicBlock *BB,
2113 DenseMap<const BasicBlock *, BBState> &BBStates,
2114 DenseMap<Value *, RRInfo> &Releases) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002115 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitTopDown ==\n");
John McCalld935e9c2011-06-15 23:37:01 +00002116 bool NestingDetected = false;
2117 BBState &MyStates = BBStates[BB];
2118
2119 // Merge the states from each predecessor to compute the initial state
2120 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00002121 BBState::edge_iterator PI(MyStates.pred_begin()),
2122 PE(MyStates.pred_end());
2123 if (PI != PE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002124 const BasicBlock *Pred = *PI;
2125 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
2126 assert(I != BBStates.end());
2127 MyStates.InitFromPred(I->second);
2128 ++PI;
2129 for (; PI != PE; ++PI) {
2130 Pred = *PI;
2131 I = BBStates.find(Pred);
2132 assert(I != BBStates.end());
2133 MyStates.MergePred(I->second);
2134 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002135 }
John McCalld935e9c2011-06-15 23:37:01 +00002136
Michael Gottesman43e7e002013-04-03 22:41:59 +00002137 // If ARC Annotations are enabled, output the current state of pointers at the
2138 // top of the basic block.
2139 ANNOTATE_TOPDOWN_BBSTART(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002140
John McCalld935e9c2011-06-15 23:37:01 +00002141 // Visit all the instructions, top-down.
2142 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2143 Instruction *Inst = I;
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00002144
Michael Gottesman89279f82013-04-05 18:10:41 +00002145 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00002146
Dan Gohman817a7c62012-03-22 18:24:56 +00002147 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00002148 }
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002149
Michael Gottesman43e7e002013-04-03 22:41:59 +00002150 // If ARC Annotations are enabled, output the current state of pointers at the
2151 // bottom of the basic block.
2152 ANNOTATE_TOPDOWN_BBEND(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002153
John McCalld935e9c2011-06-15 23:37:01 +00002154 CheckForCFGHazards(BB, BBStates, MyStates);
2155 return NestingDetected;
2156}
2157
Dan Gohmana53a12c2011-12-12 19:42:25 +00002158static void
2159ComputePostOrders(Function &F,
2160 SmallVectorImpl<BasicBlock *> &PostOrder,
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002161 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
2162 unsigned NoObjCARCExceptionsMDKind,
2163 DenseMap<const BasicBlock *, BBState> &BBStates) {
Michael Gottesman97e3df02013-01-14 00:35:14 +00002164 /// The visited set, for doing DFS walks.
Dan Gohmana53a12c2011-12-12 19:42:25 +00002165 SmallPtrSet<BasicBlock *, 16> Visited;
2166
2167 // Do DFS, computing the PostOrder.
2168 SmallPtrSet<BasicBlock *, 16> OnStack;
2169 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002170
2171 // Functions always have exactly one entry block, and we don't have
2172 // any other block that we treat like an entry block.
Dan Gohmana53a12c2011-12-12 19:42:25 +00002173 BasicBlock *EntryBB = &F.getEntryBlock();
Dan Gohman41375a32012-05-08 23:39:44 +00002174 BBState &MyStates = BBStates[EntryBB];
2175 MyStates.SetAsEntry();
2176 TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
2177 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
Dan Gohmana53a12c2011-12-12 19:42:25 +00002178 Visited.insert(EntryBB);
2179 OnStack.insert(EntryBB);
2180 do {
2181 dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002182 BasicBlock *CurrBB = SuccStack.back().first;
2183 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
2184 succ_iterator SE(TI, false);
Dan Gohman41375a32012-05-08 23:39:44 +00002185
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002186 while (SuccStack.back().second != SE) {
2187 BasicBlock *SuccBB = *SuccStack.back().second++;
2188 if (Visited.insert(SuccBB)) {
Dan Gohman41375a32012-05-08 23:39:44 +00002189 TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
2190 SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002191 BBStates[CurrBB].addSucc(SuccBB);
Dan Gohman41375a32012-05-08 23:39:44 +00002192 BBState &SuccStates = BBStates[SuccBB];
2193 SuccStates.addPred(CurrBB);
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002194 OnStack.insert(SuccBB);
Dan Gohmana53a12c2011-12-12 19:42:25 +00002195 goto dfs_next_succ;
2196 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002197
2198 if (!OnStack.count(SuccBB)) {
2199 BBStates[CurrBB].addSucc(SuccBB);
2200 BBStates[SuccBB].addPred(CurrBB);
2201 }
Dan Gohmana53a12c2011-12-12 19:42:25 +00002202 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002203 OnStack.erase(CurrBB);
2204 PostOrder.push_back(CurrBB);
2205 SuccStack.pop_back();
Dan Gohmana53a12c2011-12-12 19:42:25 +00002206 } while (!SuccStack.empty());
2207
2208 Visited.clear();
2209
Dan Gohmana53a12c2011-12-12 19:42:25 +00002210 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002211 // Functions may have many exits, and there also blocks which we treat
2212 // as exits due to ignored edges.
2213 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
2214 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
2215 BasicBlock *ExitBB = I;
2216 BBState &MyStates = BBStates[ExitBB];
2217 if (!MyStates.isExit())
2218 continue;
2219
Dan Gohmandae33492012-04-27 18:56:31 +00002220 MyStates.SetAsExit();
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002221
2222 PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00002223 Visited.insert(ExitBB);
2224 while (!PredStack.empty()) {
2225 reverse_dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002226 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
2227 while (PredStack.back().second != PE) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00002228 BasicBlock *BB = *PredStack.back().second++;
Dan Gohmana53a12c2011-12-12 19:42:25 +00002229 if (Visited.insert(BB)) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002230 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00002231 goto reverse_dfs_next_succ;
2232 }
2233 }
2234 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
2235 }
2236 }
2237}
2238
Michael Gottesman97e3df02013-01-14 00:35:14 +00002239// Visit the function both top-down and bottom-up.
John McCalld935e9c2011-06-15 23:37:01 +00002240bool
2241ObjCARCOpt::Visit(Function &F,
2242 DenseMap<const BasicBlock *, BBState> &BBStates,
2243 MapVector<Value *, RRInfo> &Retains,
2244 DenseMap<Value *, RRInfo> &Releases) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00002245
2246 // Use reverse-postorder traversals, because we magically know that loops
2247 // will be well behaved, i.e. they won't repeatedly call retain on a single
2248 // pointer without doing a release. We can't use the ReversePostOrderTraversal
2249 // class here because we want the reverse-CFG postorder to consider each
2250 // function exit point, and we want to ignore selected cycle edges.
2251 SmallVector<BasicBlock *, 16> PostOrder;
2252 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002253 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
2254 NoObjCARCExceptionsMDKind,
2255 BBStates);
Dan Gohmana53a12c2011-12-12 19:42:25 +00002256
2257 // Use reverse-postorder on the reverse CFG for bottom-up.
John McCalld935e9c2011-06-15 23:37:01 +00002258 bool BottomUpNestingDetected = false;
Dan Gohmanc57b58c2011-08-18 21:27:42 +00002259 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
Dan Gohmana53a12c2011-12-12 19:42:25 +00002260 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
2261 I != E; ++I)
2262 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
John McCalld935e9c2011-06-15 23:37:01 +00002263
Dan Gohmana53a12c2011-12-12 19:42:25 +00002264 // Use reverse-postorder for top-down.
John McCalld935e9c2011-06-15 23:37:01 +00002265 bool TopDownNestingDetected = false;
Dan Gohmana53a12c2011-12-12 19:42:25 +00002266 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2267 PostOrder.rbegin(), E = PostOrder.rend();
2268 I != E; ++I)
2269 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
John McCalld935e9c2011-06-15 23:37:01 +00002270
2271 return TopDownNestingDetected && BottomUpNestingDetected;
2272}
2273
Michael Gottesman97e3df02013-01-14 00:35:14 +00002274/// Move the calls in RetainsToMove and ReleasesToMove.
John McCalld935e9c2011-06-15 23:37:01 +00002275void ObjCARCOpt::MoveCalls(Value *Arg,
2276 RRInfo &RetainsToMove,
2277 RRInfo &ReleasesToMove,
2278 MapVector<Value *, RRInfo> &Retains,
2279 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman6320f522011-07-22 22:29:21 +00002280 SmallVectorImpl<Instruction *> &DeadInsts,
Michael Gottesman89279f82013-04-05 18:10:41 +00002281 Module *M) {
Chris Lattner229907c2011-07-18 04:54:35 +00002282 Type *ArgTy = Arg->getType();
Dan Gohman6320f522011-07-22 22:29:21 +00002283 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
Michael Gottesman89279f82013-04-05 18:10:41 +00002284
2285 DEBUG(dbgs() << "== ObjCARCOpt::MoveCalls ==\n");
2286
John McCalld935e9c2011-06-15 23:37:01 +00002287 // Insert the new retain and release calls.
2288 for (SmallPtrSet<Instruction *, 2>::const_iterator
2289 PI = ReleasesToMove.ReverseInsertPts.begin(),
2290 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2291 Instruction *InsertPt = *PI;
2292 Value *MyArg = ArgTy == ParamTy ? Arg :
2293 new BitCastInst(Arg, ParamTy, "", InsertPt);
2294 CallInst *Call =
Michael Gottesmanba648592013-03-28 23:08:44 +00002295 CallInst::Create(getRetainCallee(M), MyArg, "", InsertPt);
John McCalld935e9c2011-06-15 23:37:01 +00002296 Call->setDoesNotThrow();
Michael Gottesmanba648592013-03-28 23:08:44 +00002297 Call->setTailCall();
Michael Gottesman60f6b282013-03-29 05:13:07 +00002298
Michael Gottesman89279f82013-04-05 18:10:41 +00002299 DEBUG(dbgs() << "Inserting new Release: " << *Call << "\n"
2300 "At insertion point: " << *InsertPt << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002301 }
2302 for (SmallPtrSet<Instruction *, 2>::const_iterator
2303 PI = RetainsToMove.ReverseInsertPts.begin(),
2304 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00002305 Instruction *InsertPt = *PI;
2306 Value *MyArg = ArgTy == ParamTy ? Arg :
2307 new BitCastInst(Arg, ParamTy, "", InsertPt);
2308 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
2309 "", InsertPt);
2310 // Attach a clang.imprecise_release metadata tag, if appropriate.
2311 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
2312 Call->setMetadata(ImpreciseReleaseMDKind, M);
2313 Call->setDoesNotThrow();
2314 if (ReleasesToMove.IsTailCallRelease)
2315 Call->setTailCall();
Michael Gottesmanc189a392013-01-09 19:23:24 +00002316
Michael Gottesman89279f82013-04-05 18:10:41 +00002317 DEBUG(dbgs() << "Inserting new Release: " << *Call << "\n"
2318 "At insertion point: " << *InsertPt << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002319 }
2320
2321 // Delete the original retain and release calls.
2322 for (SmallPtrSet<Instruction *, 2>::const_iterator
2323 AI = RetainsToMove.Calls.begin(),
2324 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
2325 Instruction *OrigRetain = *AI;
2326 Retains.blot(OrigRetain);
2327 DeadInsts.push_back(OrigRetain);
Michael Gottesman89279f82013-04-05 18:10:41 +00002328 DEBUG(dbgs() << "Deleting retain: " << *OrigRetain << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002329 }
2330 for (SmallPtrSet<Instruction *, 2>::const_iterator
2331 AI = ReleasesToMove.Calls.begin(),
2332 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
2333 Instruction *OrigRelease = *AI;
2334 Releases.erase(OrigRelease);
2335 DeadInsts.push_back(OrigRelease);
Michael Gottesman89279f82013-04-05 18:10:41 +00002336 DEBUG(dbgs() << "Deleting release: " << *OrigRelease << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002337 }
Michael Gottesman89279f82013-04-05 18:10:41 +00002338
John McCalld935e9c2011-06-15 23:37:01 +00002339}
2340
Michael Gottesman9de6f962013-01-22 21:49:00 +00002341bool
2342ObjCARCOpt::ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState>
2343 &BBStates,
2344 MapVector<Value *, RRInfo> &Retains,
2345 DenseMap<Value *, RRInfo> &Releases,
2346 Module *M,
2347 SmallVector<Instruction *, 4> &NewRetains,
2348 SmallVector<Instruction *, 4> &NewReleases,
2349 SmallVector<Instruction *, 8> &DeadInsts,
2350 RRInfo &RetainsToMove,
2351 RRInfo &ReleasesToMove,
2352 Value *Arg,
2353 bool KnownSafe,
2354 bool &AnyPairsCompletelyEliminated) {
2355 // If a pair happens in a region where it is known that the reference count
2356 // is already incremented, we can similarly ignore possible decrements.
2357 bool KnownSafeTD = true, KnownSafeBU = true;
2358
2359 // Connect the dots between the top-down-collected RetainsToMove and
2360 // bottom-up-collected ReleasesToMove to form sets of related calls.
2361 // This is an iterative process so that we connect multiple releases
2362 // to multiple retains if needed.
2363 unsigned OldDelta = 0;
2364 unsigned NewDelta = 0;
2365 unsigned OldCount = 0;
2366 unsigned NewCount = 0;
2367 bool FirstRelease = true;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002368 for (;;) {
2369 for (SmallVectorImpl<Instruction *>::const_iterator
2370 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
2371 Instruction *NewRetain = *NI;
2372 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
2373 assert(It != Retains.end());
2374 const RRInfo &NewRetainRRI = It->second;
2375 KnownSafeTD &= NewRetainRRI.KnownSafe;
2376 for (SmallPtrSet<Instruction *, 2>::const_iterator
2377 LI = NewRetainRRI.Calls.begin(),
2378 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
2379 Instruction *NewRetainRelease = *LI;
2380 DenseMap<Value *, RRInfo>::const_iterator Jt =
2381 Releases.find(NewRetainRelease);
2382 if (Jt == Releases.end())
2383 return false;
2384 const RRInfo &NewRetainReleaseRRI = Jt->second;
2385 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
2386 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
2387 OldDelta -=
2388 BBStates[NewRetainRelease->getParent()].GetAllPathCount();
2389
2390 // Merge the ReleaseMetadata and IsTailCallRelease values.
2391 if (FirstRelease) {
2392 ReleasesToMove.ReleaseMetadata =
2393 NewRetainReleaseRRI.ReleaseMetadata;
2394 ReleasesToMove.IsTailCallRelease =
2395 NewRetainReleaseRRI.IsTailCallRelease;
2396 FirstRelease = false;
2397 } else {
2398 if (ReleasesToMove.ReleaseMetadata !=
2399 NewRetainReleaseRRI.ReleaseMetadata)
2400 ReleasesToMove.ReleaseMetadata = 0;
2401 if (ReleasesToMove.IsTailCallRelease !=
2402 NewRetainReleaseRRI.IsTailCallRelease)
2403 ReleasesToMove.IsTailCallRelease = false;
2404 }
2405
2406 // Collect the optimal insertion points.
2407 if (!KnownSafe)
2408 for (SmallPtrSet<Instruction *, 2>::const_iterator
2409 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
2410 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
2411 RI != RE; ++RI) {
2412 Instruction *RIP = *RI;
2413 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
2414 NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
2415 }
2416 NewReleases.push_back(NewRetainRelease);
2417 }
2418 }
2419 }
2420 NewRetains.clear();
2421 if (NewReleases.empty()) break;
2422
2423 // Back the other way.
2424 for (SmallVectorImpl<Instruction *>::const_iterator
2425 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
2426 Instruction *NewRelease = *NI;
2427 DenseMap<Value *, RRInfo>::const_iterator It =
2428 Releases.find(NewRelease);
2429 assert(It != Releases.end());
2430 const RRInfo &NewReleaseRRI = It->second;
2431 KnownSafeBU &= NewReleaseRRI.KnownSafe;
2432 for (SmallPtrSet<Instruction *, 2>::const_iterator
2433 LI = NewReleaseRRI.Calls.begin(),
2434 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
2435 Instruction *NewReleaseRetain = *LI;
2436 MapVector<Value *, RRInfo>::const_iterator Jt =
2437 Retains.find(NewReleaseRetain);
2438 if (Jt == Retains.end())
2439 return false;
2440 const RRInfo &NewReleaseRetainRRI = Jt->second;
2441 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
2442 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
2443 unsigned PathCount =
2444 BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
2445 OldDelta += PathCount;
2446 OldCount += PathCount;
2447
Michael Gottesman9de6f962013-01-22 21:49:00 +00002448 // Collect the optimal insertion points.
2449 if (!KnownSafe)
2450 for (SmallPtrSet<Instruction *, 2>::const_iterator
2451 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
2452 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
2453 RI != RE; ++RI) {
2454 Instruction *RIP = *RI;
2455 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
2456 PathCount = BBStates[RIP->getParent()].GetAllPathCount();
2457 NewDelta += PathCount;
2458 NewCount += PathCount;
2459 }
2460 }
2461 NewRetains.push_back(NewReleaseRetain);
2462 }
2463 }
2464 }
2465 NewReleases.clear();
2466 if (NewRetains.empty()) break;
2467 }
2468
2469 // If the pointer is known incremented or nested, we can safely delete the
2470 // pair regardless of what's between them.
2471 if (KnownSafeTD || KnownSafeBU) {
2472 RetainsToMove.ReverseInsertPts.clear();
2473 ReleasesToMove.ReverseInsertPts.clear();
2474 NewCount = 0;
2475 } else {
2476 // Determine whether the new insertion points we computed preserve the
2477 // balance of retain and release calls through the program.
2478 // TODO: If the fully aggressive solution isn't valid, try to find a
2479 // less aggressive solution which is.
2480 if (NewDelta != 0)
2481 return false;
2482 }
2483
2484 // Determine whether the original call points are balanced in the retain and
2485 // release calls through the program. If not, conservatively don't touch
2486 // them.
2487 // TODO: It's theoretically possible to do code motion in this case, as
2488 // long as the existing imbalances are maintained.
2489 if (OldDelta != 0)
2490 return false;
2491
2492 Changed = true;
2493 assert(OldCount != 0 && "Unreachable code?");
2494 NumRRs += OldCount - NewCount;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002495 // Set to true if we completely removed any RR pairs.
Michael Gottesman8b5515f2013-01-22 21:53:43 +00002496 AnyPairsCompletelyEliminated = NewCount == 0;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002497
2498 // We can move calls!
2499 return true;
2500}
2501
Michael Gottesman97e3df02013-01-14 00:35:14 +00002502/// Identify pairings between the retains and releases, and delete and/or move
2503/// them.
John McCalld935e9c2011-06-15 23:37:01 +00002504bool
2505ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
2506 &BBStates,
2507 MapVector<Value *, RRInfo> &Retains,
Dan Gohman6320f522011-07-22 22:29:21 +00002508 DenseMap<Value *, RRInfo> &Releases,
2509 Module *M) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002510 DEBUG(dbgs() << "\n== ObjCARCOpt::PerformCodePlacement ==\n");
2511
John McCalld935e9c2011-06-15 23:37:01 +00002512 bool AnyPairsCompletelyEliminated = false;
2513 RRInfo RetainsToMove;
2514 RRInfo ReleasesToMove;
2515 SmallVector<Instruction *, 4> NewRetains;
2516 SmallVector<Instruction *, 4> NewReleases;
2517 SmallVector<Instruction *, 8> DeadInsts;
2518
Dan Gohman670f9372012-04-13 18:57:48 +00002519 // Visit each retain.
John McCalld935e9c2011-06-15 23:37:01 +00002520 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
Dan Gohman2053a5d2011-09-29 22:25:23 +00002521 E = Retains.end(); I != E; ++I) {
2522 Value *V = I->first;
John McCalld935e9c2011-06-15 23:37:01 +00002523 if (!V) continue; // blotted
2524
2525 Instruction *Retain = cast<Instruction>(V);
Michael Gottesmanc189a392013-01-09 19:23:24 +00002526
Michael Gottesman89279f82013-04-05 18:10:41 +00002527 DEBUG(dbgs() << "Visiting: " << *Retain << "\n");
Michael Gottesmanc189a392013-01-09 19:23:24 +00002528
John McCalld935e9c2011-06-15 23:37:01 +00002529 Value *Arg = GetObjCArg(Retain);
2530
Dan Gohman728db492012-01-13 00:39:07 +00002531 // If the object being released is in static or stack storage, we know it's
John McCalld935e9c2011-06-15 23:37:01 +00002532 // not being managed by ObjC reference counting, so we can delete pairs
2533 // regardless of what possible decrements or uses lie between them.
Dan Gohman728db492012-01-13 00:39:07 +00002534 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
Dan Gohman41375a32012-05-08 23:39:44 +00002535
Dan Gohman56e1cef2011-08-22 17:29:11 +00002536 // A constant pointer can't be pointing to an object on the heap. It may
2537 // be reference-counted, but it won't be deleted.
2538 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
2539 if (const GlobalVariable *GV =
2540 dyn_cast<GlobalVariable>(
2541 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
2542 if (GV->isConstant())
2543 KnownSafe = true;
2544
John McCalld935e9c2011-06-15 23:37:01 +00002545 // Connect the dots between the top-down-collected RetainsToMove and
2546 // bottom-up-collected ReleasesToMove to form sets of related calls.
John McCalld935e9c2011-06-15 23:37:01 +00002547 NewRetains.push_back(Retain);
Michael Gottesman9de6f962013-01-22 21:49:00 +00002548 bool PerformMoveCalls =
2549 ConnectTDBUTraversals(BBStates, Retains, Releases, M, NewRetains,
2550 NewReleases, DeadInsts, RetainsToMove,
2551 ReleasesToMove, Arg, KnownSafe,
2552 AnyPairsCompletelyEliminated);
John McCalld935e9c2011-06-15 23:37:01 +00002553
Michael Gottesman81b1d432013-03-26 00:42:04 +00002554#ifdef ARC_ANNOTATIONS
2555 // Do not move calls if ARC annotations are requested. If we were to move
2556 // calls in this case, we would not be able
2557 PerformMoveCalls = PerformMoveCalls && !EnableARCAnnotations;
2558#endif // ARC_ANNOTATIONS
2559
Michael Gottesman9de6f962013-01-22 21:49:00 +00002560 if (PerformMoveCalls) {
2561 // Ok, everything checks out and we're all set. Let's move/delete some
2562 // code!
2563 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
2564 Retains, Releases, DeadInsts, M);
John McCalld935e9c2011-06-15 23:37:01 +00002565 }
2566
Michael Gottesman9de6f962013-01-22 21:49:00 +00002567 // Clean up state for next retain.
John McCalld935e9c2011-06-15 23:37:01 +00002568 NewReleases.clear();
2569 NewRetains.clear();
2570 RetainsToMove.clear();
2571 ReleasesToMove.clear();
2572 }
2573
2574 // Now that we're done moving everything, we can delete the newly dead
2575 // instructions, as we no longer need them as insert points.
2576 while (!DeadInsts.empty())
2577 EraseInstruction(DeadInsts.pop_back_val());
2578
2579 return AnyPairsCompletelyEliminated;
2580}
2581
Michael Gottesman97e3df02013-01-14 00:35:14 +00002582/// Weak pointer optimizations.
John McCalld935e9c2011-06-15 23:37:01 +00002583void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002584 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeWeakCalls ==\n");
2585
John McCalld935e9c2011-06-15 23:37:01 +00002586 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
2587 // itself because it uses AliasAnalysis and we need to do provenance
2588 // queries instead.
2589 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2590 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +00002591
Michael Gottesman89279f82013-04-05 18:10:41 +00002592 DEBUG(dbgs() << "Visiting: " << *Inst << "\n");
Michael Gottesman3f146e22013-01-01 16:05:48 +00002593
John McCalld935e9c2011-06-15 23:37:01 +00002594 InstructionClass Class = GetBasicInstructionClass(Inst);
2595 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
2596 continue;
2597
2598 // Delete objc_loadWeak calls with no users.
2599 if (Class == IC_LoadWeak && Inst->use_empty()) {
2600 Inst->eraseFromParent();
2601 continue;
2602 }
2603
2604 // TODO: For now, just look for an earlier available version of this value
2605 // within the same block. Theoretically, we could do memdep-style non-local
2606 // analysis too, but that would want caching. A better approach would be to
2607 // use the technique that EarlyCSE uses.
2608 inst_iterator Current = llvm::prior(I);
2609 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
2610 for (BasicBlock::iterator B = CurrentBB->begin(),
2611 J = Current.getInstructionIterator();
2612 J != B; --J) {
2613 Instruction *EarlierInst = &*llvm::prior(J);
2614 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
2615 switch (EarlierClass) {
2616 case IC_LoadWeak:
2617 case IC_LoadWeakRetained: {
2618 // If this is loading from the same pointer, replace this load's value
2619 // with that one.
2620 CallInst *Call = cast<CallInst>(Inst);
2621 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2622 Value *Arg = Call->getArgOperand(0);
2623 Value *EarlierArg = EarlierCall->getArgOperand(0);
2624 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2625 case AliasAnalysis::MustAlias:
2626 Changed = true;
2627 // If the load has a builtin retain, insert a plain retain for it.
2628 if (Class == IC_LoadWeakRetained) {
2629 CallInst *CI =
2630 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
2631 "", Call);
2632 CI->setTailCall();
2633 }
2634 // Zap the fully redundant load.
2635 Call->replaceAllUsesWith(EarlierCall);
2636 Call->eraseFromParent();
2637 goto clobbered;
2638 case AliasAnalysis::MayAlias:
2639 case AliasAnalysis::PartialAlias:
2640 goto clobbered;
2641 case AliasAnalysis::NoAlias:
2642 break;
2643 }
2644 break;
2645 }
2646 case IC_StoreWeak:
2647 case IC_InitWeak: {
2648 // If this is storing to the same pointer and has the same size etc.
2649 // replace this load's value with the stored value.
2650 CallInst *Call = cast<CallInst>(Inst);
2651 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2652 Value *Arg = Call->getArgOperand(0);
2653 Value *EarlierArg = EarlierCall->getArgOperand(0);
2654 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2655 case AliasAnalysis::MustAlias:
2656 Changed = true;
2657 // If the load has a builtin retain, insert a plain retain for it.
2658 if (Class == IC_LoadWeakRetained) {
2659 CallInst *CI =
2660 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
2661 "", Call);
2662 CI->setTailCall();
2663 }
2664 // Zap the fully redundant load.
2665 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
2666 Call->eraseFromParent();
2667 goto clobbered;
2668 case AliasAnalysis::MayAlias:
2669 case AliasAnalysis::PartialAlias:
2670 goto clobbered;
2671 case AliasAnalysis::NoAlias:
2672 break;
2673 }
2674 break;
2675 }
2676 case IC_MoveWeak:
2677 case IC_CopyWeak:
2678 // TOOD: Grab the copied value.
2679 goto clobbered;
2680 case IC_AutoreleasepoolPush:
2681 case IC_None:
John McCall20182ac2013-03-22 21:38:36 +00002682 case IC_IntrinsicUser:
John McCalld935e9c2011-06-15 23:37:01 +00002683 case IC_User:
2684 // Weak pointers are only modified through the weak entry points
2685 // (and arbitrary calls, which could call the weak entry points).
2686 break;
2687 default:
2688 // Anything else could modify the weak pointer.
2689 goto clobbered;
2690 }
2691 }
2692 clobbered:;
2693 }
2694
2695 // Then, for each destroyWeak with an alloca operand, check to see if
2696 // the alloca and all its users can be zapped.
2697 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2698 Instruction *Inst = &*I++;
2699 InstructionClass Class = GetBasicInstructionClass(Inst);
2700 if (Class != IC_DestroyWeak)
2701 continue;
2702
2703 CallInst *Call = cast<CallInst>(Inst);
2704 Value *Arg = Call->getArgOperand(0);
2705 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
2706 for (Value::use_iterator UI = Alloca->use_begin(),
2707 UE = Alloca->use_end(); UI != UE; ++UI) {
Dan Gohmandae33492012-04-27 18:56:31 +00002708 const Instruction *UserInst = cast<Instruction>(*UI);
John McCalld935e9c2011-06-15 23:37:01 +00002709 switch (GetBasicInstructionClass(UserInst)) {
2710 case IC_InitWeak:
2711 case IC_StoreWeak:
2712 case IC_DestroyWeak:
2713 continue;
2714 default:
2715 goto done;
2716 }
2717 }
2718 Changed = true;
2719 for (Value::use_iterator UI = Alloca->use_begin(),
2720 UE = Alloca->use_end(); UI != UE; ) {
2721 CallInst *UserInst = cast<CallInst>(*UI++);
Dan Gohman14862c32012-05-18 22:17:29 +00002722 switch (GetBasicInstructionClass(UserInst)) {
2723 case IC_InitWeak:
2724 case IC_StoreWeak:
2725 // These functions return their second argument.
2726 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
2727 break;
2728 case IC_DestroyWeak:
2729 // No return value.
2730 break;
2731 default:
Dan Gohman9c97eea02012-05-21 17:41:28 +00002732 llvm_unreachable("alloca really is used!");
Dan Gohman14862c32012-05-18 22:17:29 +00002733 }
John McCalld935e9c2011-06-15 23:37:01 +00002734 UserInst->eraseFromParent();
2735 }
2736 Alloca->eraseFromParent();
2737 done:;
2738 }
2739 }
2740}
2741
Michael Gottesman97e3df02013-01-14 00:35:14 +00002742/// Identify program paths which execute sequences of retains and releases which
2743/// can be eliminated.
John McCalld935e9c2011-06-15 23:37:01 +00002744bool ObjCARCOpt::OptimizeSequences(Function &F) {
2745 /// Releases, Retains - These are used to store the results of the main flow
2746 /// analysis. These use Value* as the key instead of Instruction* so that the
2747 /// map stays valid when we get around to rewriting code and calls get
2748 /// replaced by arguments.
2749 DenseMap<Value *, RRInfo> Releases;
2750 MapVector<Value *, RRInfo> Retains;
2751
Michael Gottesman97e3df02013-01-14 00:35:14 +00002752 /// This is used during the traversal of the function to track the
John McCalld935e9c2011-06-15 23:37:01 +00002753 /// states for each identified object at each block.
2754 DenseMap<const BasicBlock *, BBState> BBStates;
2755
2756 // Analyze the CFG of the function, and all instructions.
2757 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
2758
2759 // Transform.
Dan Gohman6320f522011-07-22 22:29:21 +00002760 return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) &&
2761 NestingDetected;
John McCalld935e9c2011-06-15 23:37:01 +00002762}
2763
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002764/// Check if there is a dependent call earlier that does not have anything in
2765/// between the Retain and the call that can affect the reference count of their
2766/// shared pointer argument. Note that Retain need not be in BB.
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002767static bool
2768HasSafePathToPredecessorCall(const Value *Arg, Instruction *Retain,
2769 SmallPtrSet<Instruction *, 4> &DepInsts,
2770 SmallPtrSet<const BasicBlock *, 4> &Visited,
2771 ProvenanceAnalysis &PA) {
2772 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
2773 DepInsts, Visited, PA);
2774 if (DepInsts.size() != 1)
2775 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002776
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002777 CallInst *Call =
2778 dyn_cast_or_null<CallInst>(*DepInsts.begin());
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002779
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002780 // Check that the pointer is the return value of the call.
2781 if (!Call || Arg != Call)
2782 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002783
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002784 // Check that the call is a regular call.
2785 InstructionClass Class = GetBasicInstructionClass(Call);
2786 if (Class != IC_CallOrUser && Class != IC_Call)
2787 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002788
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002789 return true;
2790}
2791
Michael Gottesman6908db12013-04-03 23:16:05 +00002792/// Find a dependent retain that precedes the given autorelease for which there
2793/// is nothing in between the two instructions that can affect the ref count of
2794/// Arg.
2795static CallInst *
2796FindPredecessorRetainWithSafePath(const Value *Arg, BasicBlock *BB,
2797 Instruction *Autorelease,
2798 SmallPtrSet<Instruction *, 4> &DepInsts,
2799 SmallPtrSet<const BasicBlock *, 4> &Visited,
2800 ProvenanceAnalysis &PA) {
2801 FindDependencies(CanChangeRetainCount, Arg,
2802 BB, Autorelease, DepInsts, Visited, PA);
2803 if (DepInsts.size() != 1)
2804 return 0;
2805
2806 CallInst *Retain =
2807 dyn_cast_or_null<CallInst>(*DepInsts.begin());
2808
2809 // Check that we found a retain with the same argument.
2810 if (!Retain ||
2811 !IsRetain(GetBasicInstructionClass(Retain)) ||
2812 GetObjCArg(Retain) != Arg) {
2813 return 0;
2814 }
2815
2816 return Retain;
2817}
2818
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002819/// Look for an ``autorelease'' instruction dependent on Arg such that there are
2820/// no instructions dependent on Arg that need a positive ref count in between
2821/// the autorelease and the ret.
2822static CallInst *
2823FindPredecessorAutoreleaseWithSafePath(const Value *Arg, BasicBlock *BB,
2824 ReturnInst *Ret,
2825 SmallPtrSet<Instruction *, 4> &DepInsts,
2826 SmallPtrSet<const BasicBlock *, 4> &V,
2827 ProvenanceAnalysis &PA) {
2828 FindDependencies(NeedsPositiveRetainCount, Arg,
2829 BB, Ret, DepInsts, V, PA);
2830 if (DepInsts.size() != 1)
2831 return 0;
2832
2833 CallInst *Autorelease =
2834 dyn_cast_or_null<CallInst>(*DepInsts.begin());
2835 if (!Autorelease)
2836 return 0;
2837 InstructionClass AutoreleaseClass = GetBasicInstructionClass(Autorelease);
2838 if (!IsAutorelease(AutoreleaseClass))
2839 return 0;
2840 if (GetObjCArg(Autorelease) != Arg)
2841 return 0;
2842
2843 return Autorelease;
2844}
2845
Michael Gottesman97e3df02013-01-14 00:35:14 +00002846/// Look for this pattern:
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00002847/// \code
John McCalld935e9c2011-06-15 23:37:01 +00002848/// %call = call i8* @something(...)
2849/// %2 = call i8* @objc_retain(i8* %call)
2850/// %3 = call i8* @objc_autorelease(i8* %2)
2851/// ret i8* %3
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00002852/// \endcode
John McCalld935e9c2011-06-15 23:37:01 +00002853/// And delete the retain and autorelease.
John McCalld935e9c2011-06-15 23:37:01 +00002854void ObjCARCOpt::OptimizeReturns(Function &F) {
2855 if (!F.getReturnType()->isPointerTy())
2856 return;
Michael Gottesman89279f82013-04-05 18:10:41 +00002857
2858 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeReturns ==\n");
2859
John McCalld935e9c2011-06-15 23:37:01 +00002860 SmallPtrSet<Instruction *, 4> DependingInstructions;
2861 SmallPtrSet<const BasicBlock *, 4> Visited;
2862 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
2863 BasicBlock *BB = FI;
2864 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
Michael Gottesman3f146e22013-01-01 16:05:48 +00002865
Michael Gottesman89279f82013-04-05 18:10:41 +00002866 DEBUG(dbgs() << "Visiting: " << *Ret << "\n");
Michael Gottesman3f146e22013-01-01 16:05:48 +00002867
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002868 if (!Ret)
2869 continue;
2870
John McCalld935e9c2011-06-15 23:37:01 +00002871 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002872
2873 // Look for an ``autorelease'' instruction that is a predecssor of Ret and
2874 // dependent on Arg such that there are no instructions dependent on Arg
2875 // that need a positive ref count in between the autorelease and Ret.
2876 CallInst *Autorelease =
2877 FindPredecessorAutoreleaseWithSafePath(Arg, BB, Ret,
2878 DependingInstructions, Visited,
2879 PA);
2880 if (Autorelease) {
John McCalld935e9c2011-06-15 23:37:01 +00002881 DependingInstructions.clear();
2882 Visited.clear();
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002883
2884 CallInst *Retain =
2885 FindPredecessorRetainWithSafePath(Arg, BB, Autorelease,
2886 DependingInstructions, Visited, PA);
2887 if (Retain) {
John McCalld935e9c2011-06-15 23:37:01 +00002888 DependingInstructions.clear();
2889 Visited.clear();
Michael Gottesman6908db12013-04-03 23:16:05 +00002890
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002891 // Check that there is nothing that can affect the reference count
2892 // between the retain and the call. Note that Retain need not be in BB.
2893 if (HasSafePathToPredecessorCall(Arg, Retain, DependingInstructions,
2894 Visited, PA)) {
John McCalld935e9c2011-06-15 23:37:01 +00002895 // If so, we can zap the retain and autorelease.
2896 Changed = true;
2897 ++NumRets;
Michael Gottesman89279f82013-04-05 18:10:41 +00002898 DEBUG(dbgs() << "Erasing: " << *Retain << "\nErasing: "
Michael Gottesmand61a3b22013-01-07 00:04:56 +00002899 << *Autorelease << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002900 EraseInstruction(Retain);
2901 EraseInstruction(Autorelease);
2902 }
2903 }
2904 }
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002905
John McCalld935e9c2011-06-15 23:37:01 +00002906 DependingInstructions.clear();
2907 Visited.clear();
2908 }
2909}
2910
2911bool ObjCARCOpt::doInitialization(Module &M) {
2912 if (!EnableARCOpts)
2913 return false;
2914
Dan Gohman670f9372012-04-13 18:57:48 +00002915 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanceaac7c2011-06-20 23:20:43 +00002916 Run = ModuleHasARC(M);
2917 if (!Run)
2918 return false;
2919
John McCalld935e9c2011-06-15 23:37:01 +00002920 // Identify the imprecise release metadata kind.
2921 ImpreciseReleaseMDKind =
2922 M.getContext().getMDKindID("clang.imprecise_release");
Dan Gohmana7107f92011-10-17 22:53:25 +00002923 CopyOnEscapeMDKind =
2924 M.getContext().getMDKindID("clang.arc.copy_on_escape");
Dan Gohman0155f302012-02-17 18:59:53 +00002925 NoObjCARCExceptionsMDKind =
2926 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
Michael Gottesman81b1d432013-03-26 00:42:04 +00002927#ifdef ARC_ANNOTATIONS
2928 ARCAnnotationBottomUpMDKind =
2929 M.getContext().getMDKindID("llvm.arc.annotation.bottomup");
2930 ARCAnnotationTopDownMDKind =
2931 M.getContext().getMDKindID("llvm.arc.annotation.topdown");
2932 ARCAnnotationProvenanceSourceMDKind =
2933 M.getContext().getMDKindID("llvm.arc.annotation.provenancesource");
2934#endif // ARC_ANNOTATIONS
John McCalld935e9c2011-06-15 23:37:01 +00002935
John McCalld935e9c2011-06-15 23:37:01 +00002936 // Intuitively, objc_retain and others are nocapture, however in practice
2937 // they are not, because they return their argument value. And objc_release
Dan Gohmandae33492012-04-27 18:56:31 +00002938 // calls finalizers which can have arbitrary side effects.
John McCalld935e9c2011-06-15 23:37:01 +00002939
2940 // These are initialized lazily.
2941 RetainRVCallee = 0;
2942 AutoreleaseRVCallee = 0;
2943 ReleaseCallee = 0;
2944 RetainCallee = 0;
Dan Gohman6320f522011-07-22 22:29:21 +00002945 RetainBlockCallee = 0;
John McCalld935e9c2011-06-15 23:37:01 +00002946 AutoreleaseCallee = 0;
2947
2948 return false;
2949}
2950
2951bool ObjCARCOpt::runOnFunction(Function &F) {
2952 if (!EnableARCOpts)
2953 return false;
2954
Dan Gohmanceaac7c2011-06-20 23:20:43 +00002955 // If nothing in the Module uses ARC, don't do anything.
2956 if (!Run)
2957 return false;
2958
John McCalld935e9c2011-06-15 23:37:01 +00002959 Changed = false;
2960
Michael Gottesman89279f82013-04-05 18:10:41 +00002961 DEBUG(dbgs() << "<<< ObjCARCOpt: Visiting Function: " << F.getName() << " >>>"
2962 "\n");
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00002963
John McCalld935e9c2011-06-15 23:37:01 +00002964 PA.setAA(&getAnalysis<AliasAnalysis>());
2965
2966 // This pass performs several distinct transformations. As a compile-time aid
2967 // when compiling code that isn't ObjC, skip these if the relevant ObjC
2968 // library functions aren't declared.
2969
2970 // Preliminary optimizations. This also computs UsedInThisFunction.
2971 OptimizeIndividualCalls(F);
2972
2973 // Optimizations for weak pointers.
2974 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
2975 (1 << IC_LoadWeakRetained) |
2976 (1 << IC_StoreWeak) |
2977 (1 << IC_InitWeak) |
2978 (1 << IC_CopyWeak) |
2979 (1 << IC_MoveWeak) |
2980 (1 << IC_DestroyWeak)))
2981 OptimizeWeakCalls(F);
2982
2983 // Optimizations for retain+release pairs.
2984 if (UsedInThisFunction & ((1 << IC_Retain) |
2985 (1 << IC_RetainRV) |
2986 (1 << IC_RetainBlock)))
2987 if (UsedInThisFunction & (1 << IC_Release))
2988 // Run OptimizeSequences until it either stops making changes or
2989 // no retain+release pair nesting is detected.
2990 while (OptimizeSequences(F)) {}
2991
2992 // Optimizations if objc_autorelease is used.
Dan Gohman41375a32012-05-08 23:39:44 +00002993 if (UsedInThisFunction & ((1 << IC_Autorelease) |
2994 (1 << IC_AutoreleaseRV)))
John McCalld935e9c2011-06-15 23:37:01 +00002995 OptimizeReturns(F);
2996
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00002997 DEBUG(dbgs() << "\n");
2998
John McCalld935e9c2011-06-15 23:37:01 +00002999 return Changed;
3000}
3001
3002void ObjCARCOpt::releaseMemory() {
3003 PA.clear();
3004}
3005
Michael Gottesman97e3df02013-01-14 00:35:14 +00003006/// @}
3007///