blob: e6e1ff95aabf5c7a064b05ab606edabf0b36ac63 [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 Gottesman5a91bbf2013-05-24 20:44:02 +000033#include "llvm/ADT/DenseSet.h"
Michael Gottesmanfa0939f2013-01-28 04:12:07 +000034#include "llvm/ADT/STLExtras.h"
Michael Gottesman778138e2013-01-29 03:03:03 +000035#include "llvm/ADT/SmallPtrSet.h"
Michael Gottesman278266f2013-01-29 04:20:52 +000036#include "llvm/ADT/Statistic.h"
Michael Gottesmancd4de0f2013-03-26 00:42:09 +000037#include "llvm/IR/IRBuilder.h"
Michael Gottesman278266f2013-01-29 04:20:52 +000038#include "llvm/IR/LLVMContext.h"
Michael Gottesman778138e2013-01-29 03:03:03 +000039#include "llvm/Support/CFG.h"
Michael Gottesman13a5f1a2013-01-29 04:51:59 +000040#include "llvm/Support/Debug.h"
Timur Iskhodzhanov5d7ff002013-01-29 09:09:27 +000041#include "llvm/Support/raw_ostream.h"
Michael Gottesmanfa0939f2013-01-28 04:12:07 +000042
John McCalld935e9c2011-06-15 23:37:01 +000043using namespace llvm;
Michael Gottesman08904e32013-01-28 03:28:38 +000044using namespace llvm::objcarc;
John McCalld935e9c2011-06-15 23:37:01 +000045
Michael Gottesman97e3df02013-01-14 00:35:14 +000046/// \defgroup MiscUtils Miscellaneous utilities that are not ARC specific.
47/// @{
John McCalld935e9c2011-06-15 23:37:01 +000048
49namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +000050 /// \brief An associative container with fast insertion-order (deterministic)
51 /// iteration over its elements. Plus the special blot operation.
John McCalld935e9c2011-06-15 23:37:01 +000052 template<class KeyT, class ValueT>
53 class MapVector {
Michael Gottesman97e3df02013-01-14 00:35:14 +000054 /// Map keys to indices in Vector.
John McCalld935e9c2011-06-15 23:37:01 +000055 typedef DenseMap<KeyT, size_t> MapTy;
56 MapTy Map;
57
John McCalld935e9c2011-06-15 23:37:01 +000058 typedef std::vector<std::pair<KeyT, ValueT> > VectorTy;
Michael Gottesman97e3df02013-01-14 00:35:14 +000059 /// Keys and values.
John McCalld935e9c2011-06-15 23:37:01 +000060 VectorTy Vector;
61
62 public:
63 typedef typename VectorTy::iterator iterator;
64 typedef typename VectorTy::const_iterator const_iterator;
65 iterator begin() { return Vector.begin(); }
66 iterator end() { return Vector.end(); }
67 const_iterator begin() const { return Vector.begin(); }
68 const_iterator end() const { return Vector.end(); }
69
70#ifdef XDEBUG
71 ~MapVector() {
72 assert(Vector.size() >= Map.size()); // May differ due to blotting.
73 for (typename MapTy::const_iterator I = Map.begin(), E = Map.end();
74 I != E; ++I) {
75 assert(I->second < Vector.size());
76 assert(Vector[I->second].first == I->first);
77 }
78 for (typename VectorTy::const_iterator I = Vector.begin(),
79 E = Vector.end(); I != E; ++I)
80 assert(!I->first ||
81 (Map.count(I->first) &&
82 Map[I->first] == size_t(I - Vector.begin())));
83 }
84#endif
85
Dan Gohman55b06742012-03-02 01:13:53 +000086 ValueT &operator[](const KeyT &Arg) {
John McCalld935e9c2011-06-15 23:37:01 +000087 std::pair<typename MapTy::iterator, bool> Pair =
88 Map.insert(std::make_pair(Arg, size_t(0)));
89 if (Pair.second) {
Dan Gohman55b06742012-03-02 01:13:53 +000090 size_t Num = Vector.size();
91 Pair.first->second = Num;
John McCalld935e9c2011-06-15 23:37:01 +000092 Vector.push_back(std::make_pair(Arg, ValueT()));
Dan Gohman55b06742012-03-02 01:13:53 +000093 return Vector[Num].second;
John McCalld935e9c2011-06-15 23:37:01 +000094 }
95 return Vector[Pair.first->second].second;
96 }
97
98 std::pair<iterator, bool>
99 insert(const std::pair<KeyT, ValueT> &InsertPair) {
100 std::pair<typename MapTy::iterator, bool> Pair =
101 Map.insert(std::make_pair(InsertPair.first, size_t(0)));
102 if (Pair.second) {
Dan Gohman55b06742012-03-02 01:13:53 +0000103 size_t Num = Vector.size();
104 Pair.first->second = Num;
John McCalld935e9c2011-06-15 23:37:01 +0000105 Vector.push_back(InsertPair);
Dan Gohman55b06742012-03-02 01:13:53 +0000106 return std::make_pair(Vector.begin() + Num, true);
John McCalld935e9c2011-06-15 23:37:01 +0000107 }
108 return std::make_pair(Vector.begin() + Pair.first->second, false);
109 }
110
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000111 iterator find(const KeyT &Key) {
112 typename MapTy::iterator It = Map.find(Key);
113 if (It == Map.end()) return Vector.end();
114 return Vector.begin() + It->second;
115 }
116
Dan Gohman55b06742012-03-02 01:13:53 +0000117 const_iterator find(const KeyT &Key) const {
John McCalld935e9c2011-06-15 23:37:01 +0000118 typename MapTy::const_iterator It = Map.find(Key);
119 if (It == Map.end()) return Vector.end();
120 return Vector.begin() + It->second;
121 }
122
Michael Gottesman97e3df02013-01-14 00:35:14 +0000123 /// This is similar to erase, but instead of removing the element from the
124 /// vector, it just zeros out the key in the vector. This leaves iterators
125 /// intact, but clients must be prepared for zeroed-out keys when iterating.
Dan Gohman55b06742012-03-02 01:13:53 +0000126 void blot(const KeyT &Key) {
John McCalld935e9c2011-06-15 23:37:01 +0000127 typename MapTy::iterator It = Map.find(Key);
128 if (It == Map.end()) return;
129 Vector[It->second].first = KeyT();
130 Map.erase(It);
131 }
132
133 void clear() {
134 Map.clear();
135 Vector.clear();
136 }
137 };
138}
139
Michael Gottesman97e3df02013-01-14 00:35:14 +0000140/// @}
141///
142/// \defgroup ARCUtilities Utility declarations/definitions specific to ARC.
143/// @{
John McCalld935e9c2011-06-15 23:37:01 +0000144
Michael Gottesman97e3df02013-01-14 00:35:14 +0000145/// \brief This is similar to StripPointerCastsAndObjCCalls but it stops as soon
146/// as it finds a value with multiple uses.
John McCalld935e9c2011-06-15 23:37:01 +0000147static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
148 if (Arg->hasOneUse()) {
149 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
150 return FindSingleUseIdentifiedObject(BC->getOperand(0));
151 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
152 if (GEP->hasAllZeroIndices())
153 return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
154 if (IsForwarding(GetBasicInstructionClass(Arg)))
155 return FindSingleUseIdentifiedObject(
156 cast<CallInst>(Arg)->getArgOperand(0));
157 if (!IsObjCIdentifiedObject(Arg))
158 return 0;
159 return Arg;
160 }
161
Dan Gohman41375a32012-05-08 23:39:44 +0000162 // If we found an identifiable object but it has multiple uses, but they are
163 // trivial uses, we can still consider this to be a single-use value.
John McCalld935e9c2011-06-15 23:37:01 +0000164 if (IsObjCIdentifiedObject(Arg)) {
165 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
166 UI != UE; ++UI) {
167 const User *U = *UI;
168 if (!U->use_empty() || StripPointerCastsAndObjCCalls(U) != Arg)
169 return 0;
170 }
171
172 return Arg;
173 }
174
175 return 0;
176}
177
Michael Gottesman774d2c02013-01-29 21:00:52 +0000178/// \brief Test whether the given retainable object pointer escapes.
Michael Gottesman97e3df02013-01-14 00:35:14 +0000179///
180/// This differs from regular escape analysis in that a use as an
181/// argument to a call is not considered an escape.
182///
Michael Gottesman774d2c02013-01-29 21:00:52 +0000183static bool DoesRetainableObjPtrEscape(const User *Ptr) {
Michael Gottesman774d2c02013-01-29 21:00:52 +0000184 DEBUG(dbgs() << "DoesRetainableObjPtrEscape: Target: " << *Ptr << "\n");
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000185
Dan Gohman728db492012-01-13 00:39:07 +0000186 // Walk the def-use chains.
187 SmallVector<const Value *, 4> Worklist;
Michael Gottesman774d2c02013-01-29 21:00:52 +0000188 Worklist.push_back(Ptr);
189 // If Ptr has any operands add them as well.
Michael Gottesman23cda0c2013-01-29 21:07:53 +0000190 for (User::const_op_iterator I = Ptr->op_begin(), E = Ptr->op_end(); I != E;
191 ++I) {
Michael Gottesman774d2c02013-01-29 21:00:52 +0000192 Worklist.push_back(*I);
193 }
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000194
195 // Ensure we do not visit any value twice.
Michael Gottesman774d2c02013-01-29 21:00:52 +0000196 SmallPtrSet<const Value *, 8> VisitedSet;
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000197
Dan Gohman728db492012-01-13 00:39:07 +0000198 do {
199 const Value *V = Worklist.pop_back_val();
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000200
Michael Gottesman89279f82013-04-05 18:10:41 +0000201 DEBUG(dbgs() << "Visiting: " << *V << "\n");
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000202
Dan Gohman728db492012-01-13 00:39:07 +0000203 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
204 UI != UE; ++UI) {
205 const User *UUser = *UI;
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000206
Michael Gottesman89279f82013-04-05 18:10:41 +0000207 DEBUG(dbgs() << "User: " << *UUser << "\n");
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000208
Dan Gohman728db492012-01-13 00:39:07 +0000209 // Special - Use by a call (callee or argument) is not considered
210 // to be an escape.
Dan Gohmane1e352a2012-04-13 18:28:58 +0000211 switch (GetBasicInstructionClass(UUser)) {
212 case IC_StoreWeak:
213 case IC_InitWeak:
214 case IC_StoreStrong:
215 case IC_Autorelease:
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000216 case IC_AutoreleaseRV: {
Michael Gottesman89279f82013-04-05 18:10:41 +0000217 DEBUG(dbgs() << "User copies pointer arguments. Pointer Escapes!\n");
Dan Gohmane1e352a2012-04-13 18:28:58 +0000218 // These special functions make copies of their pointer arguments.
219 return true;
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000220 }
John McCall20182ac2013-03-22 21:38:36 +0000221 case IC_IntrinsicUser:
222 // Use by the use intrinsic is not an escape.
223 continue;
Dan Gohmane1e352a2012-04-13 18:28:58 +0000224 case IC_User:
225 case IC_None:
226 // Use by an instruction which copies the value is an escape if the
227 // result is an escape.
228 if (isa<BitCastInst>(UUser) || isa<GetElementPtrInst>(UUser) ||
229 isa<PHINode>(UUser) || isa<SelectInst>(UUser)) {
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000230
Michael Gottesmanf4b77612013-02-23 00:31:32 +0000231 if (VisitedSet.insert(UUser)) {
Michael Gottesman89279f82013-04-05 18:10:41 +0000232 DEBUG(dbgs() << "User copies value. Ptr escapes if result escapes."
233 " Adding to list.\n");
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000234 Worklist.push_back(UUser);
235 } else {
Michael Gottesman89279f82013-04-05 18:10:41 +0000236 DEBUG(dbgs() << "Already visited node.\n");
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000237 }
Dan Gohmane1e352a2012-04-13 18:28:58 +0000238 continue;
239 }
240 // Use by a load is not an escape.
241 if (isa<LoadInst>(UUser))
242 continue;
243 // Use by a store is not an escape if the use is the address.
244 if (const StoreInst *SI = dyn_cast<StoreInst>(UUser))
245 if (V != SI->getValueOperand())
246 continue;
247 break;
248 default:
249 // Regular calls and other stuff are not considered escapes.
Dan Gohman728db492012-01-13 00:39:07 +0000250 continue;
251 }
Dan Gohmaneb6e0152012-02-13 22:57:02 +0000252 // Otherwise, conservatively assume an escape.
Michael Gottesman89279f82013-04-05 18:10:41 +0000253 DEBUG(dbgs() << "Assuming ptr escapes.\n");
Dan Gohman728db492012-01-13 00:39:07 +0000254 return true;
255 }
256 } while (!Worklist.empty());
257
258 // No escapes found.
Michael Gottesman89279f82013-04-05 18:10:41 +0000259 DEBUG(dbgs() << "Ptr does not escape.\n");
Dan Gohman728db492012-01-13 00:39:07 +0000260 return false;
261}
262
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000263/// This is a wrapper around getUnderlyingObjCPtr along the lines of
264/// GetUnderlyingObjects except that it returns early when it sees the first
265/// alloca.
266static inline bool AreAnyUnderlyingObjectsAnAlloca(const Value *V) {
267 SmallPtrSet<const Value *, 4> Visited;
268 SmallVector<const Value *, 4> Worklist;
269 Worklist.push_back(V);
270 do {
271 const Value *P = Worklist.pop_back_val();
272 P = GetUnderlyingObjCPtr(P);
Michael Gottesman0c8b5622013-05-14 06:40:10 +0000273
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000274 if (isa<AllocaInst>(P))
275 return true;
Michael Gottesman0c8b5622013-05-14 06:40:10 +0000276
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000277 if (!Visited.insert(P))
278 continue;
Michael Gottesman0c8b5622013-05-14 06:40:10 +0000279
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000280 if (const SelectInst *SI = dyn_cast<const SelectInst>(P)) {
281 Worklist.push_back(SI->getTrueValue());
282 Worklist.push_back(SI->getFalseValue());
283 continue;
284 }
Michael Gottesman0c8b5622013-05-14 06:40:10 +0000285
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000286 if (const PHINode *PN = dyn_cast<const PHINode>(P)) {
287 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
288 Worklist.push_back(PN->getIncomingValue(i));
289 continue;
290 }
291 } while (!Worklist.empty());
292
293 return false;
294}
295
296
Michael Gottesman97e3df02013-01-14 00:35:14 +0000297/// @}
298///
Michael Gottesman97e3df02013-01-14 00:35:14 +0000299/// \defgroup ARCOpt ARC Optimization.
300/// @{
John McCalld935e9c2011-06-15 23:37:01 +0000301
302// TODO: On code like this:
303//
304// objc_retain(%x)
305// stuff_that_cannot_release()
306// objc_autorelease(%x)
307// stuff_that_cannot_release()
308// objc_retain(%x)
309// stuff_that_cannot_release()
310// objc_autorelease(%x)
311//
312// The second retain and autorelease can be deleted.
313
314// TODO: It should be possible to delete
315// objc_autoreleasePoolPush and objc_autoreleasePoolPop
316// pairs if nothing is actually autoreleased between them. Also, autorelease
317// calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
318// after inlining) can be turned into plain release calls.
319
320// TODO: Critical-edge splitting. If the optimial insertion point is
321// a critical edge, the current algorithm has to fail, because it doesn't
322// know how to split edges. It should be possible to make the optimizer
323// think in terms of edges, rather than blocks, and then split critical
324// edges on demand.
325
326// TODO: OptimizeSequences could generalized to be Interprocedural.
327
328// TODO: Recognize that a bunch of other objc runtime calls have
329// non-escaping arguments and non-releasing arguments, and may be
330// non-autoreleasing.
331
332// TODO: Sink autorelease calls as far as possible. Unfortunately we
333// usually can't sink them past other calls, which would be the main
334// case where it would be useful.
335
Dan Gohmanb3894012011-08-19 00:26:36 +0000336// TODO: The pointer returned from objc_loadWeakRetained is retained.
337
338// TODO: Delete release+retain pairs (rare).
Dan Gohmanceaac7c2011-06-20 23:20:43 +0000339
John McCalld935e9c2011-06-15 23:37:01 +0000340STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
341STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
342STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
343STATISTIC(NumRets, "Number of return value forwarding "
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000344 "retain+autoreleases eliminated");
John McCalld935e9c2011-06-15 23:37:01 +0000345STATISTIC(NumRRs, "Number of retain+release paths eliminated");
346STATISTIC(NumPeeps, "Number of calls peephole-optimized");
Matt Beaumont-Gaye55d9492013-05-13 21:10:49 +0000347#ifndef NDEBUG
Michael Gottesman9c118152013-04-29 06:16:57 +0000348STATISTIC(NumRetainsBeforeOpt,
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000349 "Number of retains before optimization");
Michael Gottesman9c118152013-04-29 06:16:57 +0000350STATISTIC(NumReleasesBeforeOpt,
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000351 "Number of releases before optimization");
Michael Gottesman9c118152013-04-29 06:16:57 +0000352STATISTIC(NumRetainsAfterOpt,
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000353 "Number of retains after optimization");
Michael Gottesman9c118152013-04-29 06:16:57 +0000354STATISTIC(NumReleasesAfterOpt,
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000355 "Number of releases after optimization");
Michael Gottesman03cf3c82013-04-29 07:29:08 +0000356#endif
John McCalld935e9c2011-06-15 23:37:01 +0000357
358namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000359 /// \enum Sequence
360 ///
361 /// \brief A sequence of states that a pointer may go through in which an
362 /// objc_retain and objc_release are actually needed.
John McCalld935e9c2011-06-15 23:37:01 +0000363 enum Sequence {
364 S_None,
Michael Gottesman53fd20b2013-01-29 21:07:51 +0000365 S_Retain, ///< objc_retain(x).
366 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement.
367 S_Use, ///< any use of x.
Michael Gottesman386241c2013-01-29 21:39:02 +0000368 S_Stop, ///< like S_Release, but code motion is stopped.
Michael Gottesman53fd20b2013-01-29 21:07:51 +0000369 S_Release, ///< objc_release(x).
Michael Gottesman9bdab2b2013-01-29 21:41:44 +0000370 S_MovableRelease ///< objc_release(x), !clang.imprecise_release.
John McCalld935e9c2011-06-15 23:37:01 +0000371 };
Michael Gottesman53fd20b2013-01-29 21:07:51 +0000372
373 raw_ostream &operator<<(raw_ostream &OS, const Sequence S)
374 LLVM_ATTRIBUTE_UNUSED;
375 raw_ostream &operator<<(raw_ostream &OS, const Sequence S) {
376 switch (S) {
377 case S_None:
378 return OS << "S_None";
379 case S_Retain:
380 return OS << "S_Retain";
381 case S_CanRelease:
382 return OS << "S_CanRelease";
383 case S_Use:
384 return OS << "S_Use";
385 case S_Release:
386 return OS << "S_Release";
387 case S_MovableRelease:
388 return OS << "S_MovableRelease";
389 case S_Stop:
390 return OS << "S_Stop";
391 }
392 llvm_unreachable("Unknown sequence type.");
393 }
John McCalld935e9c2011-06-15 23:37:01 +0000394}
395
396static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
397 // The easy cases.
398 if (A == B)
399 return A;
400 if (A == S_None || B == S_None)
401 return S_None;
402
John McCalld935e9c2011-06-15 23:37:01 +0000403 if (A > B) std::swap(A, B);
404 if (TopDown) {
405 // Choose the side which is further along in the sequence.
Dan Gohman12130272011-08-12 00:26:31 +0000406 if ((A == S_Retain || A == S_CanRelease) &&
407 (B == S_CanRelease || B == S_Use))
John McCalld935e9c2011-06-15 23:37:01 +0000408 return B;
409 } else {
410 // Choose the side which is further along in the sequence.
411 if ((A == S_Use || A == S_CanRelease) &&
Dan Gohman12130272011-08-12 00:26:31 +0000412 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
John McCalld935e9c2011-06-15 23:37:01 +0000413 return A;
414 // If both sides are releases, choose the more conservative one.
415 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
416 return A;
417 if (A == S_Release && B == S_MovableRelease)
418 return A;
419 }
420
421 return S_None;
422}
423
424namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000425 /// \brief Unidirectional information about either a
John McCalld935e9c2011-06-15 23:37:01 +0000426 /// retain-decrement-use-release sequence or release-use-decrement-retain
Bob Wilson798a7702013-04-09 22:15:51 +0000427 /// reverse sequence.
John McCalld935e9c2011-06-15 23:37:01 +0000428 struct RRInfo {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000429 /// After an objc_retain, the reference count of the referenced
Dan Gohmanb3894012011-08-19 00:26:36 +0000430 /// object is known to be positive. Similarly, before an objc_release, the
431 /// reference count of the referenced object is known to be positive. If
432 /// there are retain-release pairs in code regions where the retain count
433 /// is known to be positive, they can be eliminated, regardless of any side
434 /// effects between them.
435 ///
436 /// Also, a retain+release pair nested within another retain+release
437 /// pair all on the known same pointer value can be eliminated, regardless
438 /// of any intervening side effects.
439 ///
440 /// KnownSafe is true when either of these conditions is satisfied.
441 bool KnownSafe;
John McCalld935e9c2011-06-15 23:37:01 +0000442
Michael Gottesman97e3df02013-01-14 00:35:14 +0000443 /// True of the objc_release calls are all marked with the "tail" keyword.
John McCalld935e9c2011-06-15 23:37:01 +0000444 bool IsTailCallRelease;
445
Michael Gottesman97e3df02013-01-14 00:35:14 +0000446 /// If the Calls are objc_release calls and they all have a
447 /// clang.imprecise_release tag, this is the metadata tag.
John McCalld935e9c2011-06-15 23:37:01 +0000448 MDNode *ReleaseMetadata;
449
Michael Gottesman97e3df02013-01-14 00:35:14 +0000450 /// For a top-down sequence, the set of objc_retains or
John McCalld935e9c2011-06-15 23:37:01 +0000451 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
452 SmallPtrSet<Instruction *, 2> Calls;
453
Michael Gottesman97e3df02013-01-14 00:35:14 +0000454 /// The set of optimal insert positions for moving calls in the opposite
455 /// sequence.
John McCalld935e9c2011-06-15 23:37:01 +0000456 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
457
Michael Gottesmane67f40c2013-05-24 20:44:05 +0000458 /// If this is true, we cannot perform code motion but can still remove
459 /// retain/release pairs.
460 bool CFGHazardAfflicted;
461
John McCalld935e9c2011-06-15 23:37:01 +0000462 RRInfo() :
Michael Gottesmane67f40c2013-05-24 20:44:05 +0000463 KnownSafe(false), IsTailCallRelease(false), ReleaseMetadata(0),
464 CFGHazardAfflicted(false) {}
John McCalld935e9c2011-06-15 23:37:01 +0000465
466 void clear();
Michael Gottesman79249972013-04-05 23:46:45 +0000467
Michael Gottesman1d8d2572013-04-05 22:54:28 +0000468 bool IsTrackingImpreciseReleases() {
469 return ReleaseMetadata != 0;
470 }
John McCalld935e9c2011-06-15 23:37:01 +0000471 };
472}
473
474void RRInfo::clear() {
Dan Gohmanb3894012011-08-19 00:26:36 +0000475 KnownSafe = false;
John McCalld935e9c2011-06-15 23:37:01 +0000476 IsTailCallRelease = false;
477 ReleaseMetadata = 0;
478 Calls.clear();
479 ReverseInsertPts.clear();
Michael Gottesmane67f40c2013-05-24 20:44:05 +0000480 CFGHazardAfflicted = false;
John McCalld935e9c2011-06-15 23:37:01 +0000481}
482
483namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000484 /// \brief This class summarizes several per-pointer runtime properties which
485 /// are propogated through the flow graph.
John McCalld935e9c2011-06-15 23:37:01 +0000486 class PtrState {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000487 /// True if the reference count is known to be incremented.
Dan Gohman62079b42012-04-25 00:50:46 +0000488 bool KnownPositiveRefCount;
489
Bob Wilson798a7702013-04-09 22:15:51 +0000490 /// True if we've seen an opportunity for partial RR elimination, such as
Michael Gottesman97e3df02013-01-14 00:35:14 +0000491 /// pushing calls into a CFG triangle or into one side of a CFG diamond.
Dan Gohman62079b42012-04-25 00:50:46 +0000492 bool Partial;
John McCalld935e9c2011-06-15 23:37:01 +0000493
Michael Gottesman97e3df02013-01-14 00:35:14 +0000494 /// The current position in the sequence.
Dan Gohman41375a32012-05-08 23:39:44 +0000495 Sequence Seq : 8;
John McCalld935e9c2011-06-15 23:37:01 +0000496
497 public:
Michael Gottesman97e3df02013-01-14 00:35:14 +0000498 /// Unidirectional information about the current sequence.
499 ///
John McCalld935e9c2011-06-15 23:37:01 +0000500 /// TODO: Encapsulate this better.
501 RRInfo RRI;
502
Dan Gohmandf476e52012-09-04 23:16:20 +0000503 PtrState() : KnownPositiveRefCount(false), Partial(false),
Dan Gohman41375a32012-05-08 23:39:44 +0000504 Seq(S_None) {}
John McCalld935e9c2011-06-15 23:37:01 +0000505
Michael Gottesman415ddd72013-02-05 19:32:18 +0000506 void SetKnownPositiveRefCount() {
Michael Gottesmanf3f9e3b2013-05-14 00:08:09 +0000507 DEBUG(dbgs() << "Setting Known Positive.\n");
Dan Gohman62079b42012-04-25 00:50:46 +0000508 KnownPositiveRefCount = true;
Dan Gohman12130272011-08-12 00:26:31 +0000509 }
510
Michael Gottesman764b1cf2013-03-23 05:46:19 +0000511 void ClearKnownPositiveRefCount() {
Michael Gottesmanf3f9e3b2013-05-14 00:08:09 +0000512 DEBUG(dbgs() << "Clearing Known Positive.\n");
Dan Gohman62079b42012-04-25 00:50:46 +0000513 KnownPositiveRefCount = false;
John McCalld935e9c2011-06-15 23:37:01 +0000514 }
515
Michael Gottesman07beea42013-03-23 05:31:01 +0000516 bool HasKnownPositiveRefCount() const {
Dan Gohman62079b42012-04-25 00:50:46 +0000517 return KnownPositiveRefCount;
John McCalld935e9c2011-06-15 23:37:01 +0000518 }
519
Michael Gottesman415ddd72013-02-05 19:32:18 +0000520 void SetSeq(Sequence NewSeq) {
Michael Gottesman89279f82013-04-05 18:10:41 +0000521 DEBUG(dbgs() << "Old: " << Seq << "; New: " << NewSeq << "\n");
Michael Gottesman79249972013-04-05 23:46:45 +0000522 Seq = NewSeq;
John McCalld935e9c2011-06-15 23:37:01 +0000523 }
524
Michael Gottesman415ddd72013-02-05 19:32:18 +0000525 Sequence GetSeq() const {
John McCalld935e9c2011-06-15 23:37:01 +0000526 return Seq;
527 }
528
Michael Gottesman415ddd72013-02-05 19:32:18 +0000529 void ClearSequenceProgress() {
Dan Gohman62079b42012-04-25 00:50:46 +0000530 ResetSequenceProgress(S_None);
531 }
532
Michael Gottesman415ddd72013-02-05 19:32:18 +0000533 void ResetSequenceProgress(Sequence NewSeq) {
Michael Gottesman01338a42013-04-20 23:36:57 +0000534 DEBUG(dbgs() << "Resetting sequence progress.\n");
Michael Gottesman89279f82013-04-05 18:10:41 +0000535 SetSeq(NewSeq);
Dan Gohman62079b42012-04-25 00:50:46 +0000536 Partial = false;
John McCalld935e9c2011-06-15 23:37:01 +0000537 RRI.clear();
538 }
539
540 void Merge(const PtrState &Other, bool TopDown);
541 };
542}
543
544void
545PtrState::Merge(const PtrState &Other, bool TopDown) {
546 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
Dan Gohman62079b42012-04-25 00:50:46 +0000547 KnownPositiveRefCount = KnownPositiveRefCount && Other.KnownPositiveRefCount;
Michael Gottesman60f6b282013-03-29 05:13:07 +0000548
Dan Gohman1736c142011-10-17 18:48:25 +0000549 // If we're not in a sequence (anymore), drop all associated state.
John McCalld935e9c2011-06-15 23:37:01 +0000550 if (Seq == S_None) {
Dan Gohman62079b42012-04-25 00:50:46 +0000551 Partial = false;
John McCalld935e9c2011-06-15 23:37:01 +0000552 RRI.clear();
Dan Gohman62079b42012-04-25 00:50:46 +0000553 } else if (Partial || Other.Partial) {
Dan Gohman1736c142011-10-17 18:48:25 +0000554 // If we're doing a merge on a path that's previously seen a partial
555 // merge, conservatively drop the sequence, to avoid doing partial
556 // RR elimination. If the branch predicates for the two merge differ,
557 // mixing them is unsafe.
Dan Gohman62079b42012-04-25 00:50:46 +0000558 ClearSequenceProgress();
John McCalld935e9c2011-06-15 23:37:01 +0000559 } else {
560 // Conservatively merge the ReleaseMetadata information.
561 if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
562 RRI.ReleaseMetadata = 0;
563
Dan Gohmanb3894012011-08-19 00:26:36 +0000564 RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
Dan Gohman41375a32012-05-08 23:39:44 +0000565 RRI.IsTailCallRelease = RRI.IsTailCallRelease &&
566 Other.RRI.IsTailCallRelease;
John McCalld935e9c2011-06-15 23:37:01 +0000567 RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
Michael Gottesmane67f40c2013-05-24 20:44:05 +0000568 RRI.CFGHazardAfflicted |= Other.RRI.CFGHazardAfflicted;
Dan Gohman1736c142011-10-17 18:48:25 +0000569
570 // Merge the insert point sets. If there are any differences,
571 // that makes this a partial merge.
Dan Gohman41375a32012-05-08 23:39:44 +0000572 Partial = RRI.ReverseInsertPts.size() != Other.RRI.ReverseInsertPts.size();
Dan Gohman1736c142011-10-17 18:48:25 +0000573 for (SmallPtrSet<Instruction *, 2>::const_iterator
574 I = Other.RRI.ReverseInsertPts.begin(),
575 E = Other.RRI.ReverseInsertPts.end(); I != E; ++I)
Dan Gohman62079b42012-04-25 00:50:46 +0000576 Partial |= RRI.ReverseInsertPts.insert(*I);
John McCalld935e9c2011-06-15 23:37:01 +0000577 }
578}
579
580namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000581 /// \brief Per-BasicBlock state.
John McCalld935e9c2011-06-15 23:37:01 +0000582 class BBState {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000583 /// The number of unique control paths from the entry which can reach this
584 /// block.
John McCalld935e9c2011-06-15 23:37:01 +0000585 unsigned TopDownPathCount;
586
Michael Gottesman97e3df02013-01-14 00:35:14 +0000587 /// The number of unique control paths to exits from this block.
John McCalld935e9c2011-06-15 23:37:01 +0000588 unsigned BottomUpPathCount;
589
Michael Gottesman97e3df02013-01-14 00:35:14 +0000590 /// A type for PerPtrTopDown and PerPtrBottomUp.
John McCalld935e9c2011-06-15 23:37:01 +0000591 typedef MapVector<const Value *, PtrState> MapTy;
592
Michael Gottesman97e3df02013-01-14 00:35:14 +0000593 /// The top-down traversal uses this to record information known about a
594 /// pointer at the bottom of each block.
John McCalld935e9c2011-06-15 23:37:01 +0000595 MapTy PerPtrTopDown;
596
Michael Gottesman97e3df02013-01-14 00:35:14 +0000597 /// The bottom-up traversal uses this to record information known about a
598 /// pointer at the top of each block.
John McCalld935e9c2011-06-15 23:37:01 +0000599 MapTy PerPtrBottomUp;
600
Michael Gottesman97e3df02013-01-14 00:35:14 +0000601 /// Effective predecessors of the current block ignoring ignorable edges and
602 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000603 SmallVector<BasicBlock *, 2> Preds;
Michael Gottesman97e3df02013-01-14 00:35:14 +0000604 /// Effective successors of the current block ignoring ignorable edges and
605 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000606 SmallVector<BasicBlock *, 2> Succs;
607
John McCalld935e9c2011-06-15 23:37:01 +0000608 public:
609 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
610
611 typedef MapTy::iterator ptr_iterator;
612 typedef MapTy::const_iterator ptr_const_iterator;
613
614 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
615 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
616 ptr_const_iterator top_down_ptr_begin() const {
617 return PerPtrTopDown.begin();
618 }
619 ptr_const_iterator top_down_ptr_end() const {
620 return PerPtrTopDown.end();
621 }
622
623 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
624 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
625 ptr_const_iterator bottom_up_ptr_begin() const {
626 return PerPtrBottomUp.begin();
627 }
628 ptr_const_iterator bottom_up_ptr_end() const {
629 return PerPtrBottomUp.end();
630 }
631
Michael Gottesman97e3df02013-01-14 00:35:14 +0000632 /// Mark this block as being an entry block, which has one path from the
633 /// entry by definition.
John McCalld935e9c2011-06-15 23:37:01 +0000634 void SetAsEntry() { TopDownPathCount = 1; }
635
Michael Gottesman97e3df02013-01-14 00:35:14 +0000636 /// Mark this block as being an exit block, which has one path to an exit by
637 /// definition.
John McCalld935e9c2011-06-15 23:37:01 +0000638 void SetAsExit() { BottomUpPathCount = 1; }
639
Michael Gottesman993fbf72013-05-13 19:40:39 +0000640 /// Attempt to find the PtrState object describing the top down state for
641 /// pointer Arg. Return a new initialized PtrState describing the top down
642 /// state for Arg if we do not find one.
John McCalld935e9c2011-06-15 23:37:01 +0000643 PtrState &getPtrTopDownState(const Value *Arg) {
644 return PerPtrTopDown[Arg];
645 }
646
Michael Gottesman993fbf72013-05-13 19:40:39 +0000647 /// Attempt to find the PtrState object describing the bottom up state for
648 /// pointer Arg. Return a new initialized PtrState describing the bottom up
649 /// state for Arg if we do not find one.
John McCalld935e9c2011-06-15 23:37:01 +0000650 PtrState &getPtrBottomUpState(const Value *Arg) {
651 return PerPtrBottomUp[Arg];
652 }
653
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000654 /// Attempt to find the PtrState object describing the bottom up state for
655 /// pointer Arg.
656 ptr_iterator findPtrBottomUpState(const Value *Arg) {
657 return PerPtrBottomUp.find(Arg);
658 }
659
John McCalld935e9c2011-06-15 23:37:01 +0000660 void clearBottomUpPointers() {
Evan Chenge4df6a22011-08-04 18:40:26 +0000661 PerPtrBottomUp.clear();
John McCalld935e9c2011-06-15 23:37:01 +0000662 }
663
664 void clearTopDownPointers() {
665 PerPtrTopDown.clear();
666 }
667
668 void InitFromPred(const BBState &Other);
669 void InitFromSucc(const BBState &Other);
670 void MergePred(const BBState &Other);
671 void MergeSucc(const BBState &Other);
672
Michael Gottesman97e3df02013-01-14 00:35:14 +0000673 /// Return the number of possible unique paths from an entry to an exit
674 /// which pass through this block. This is only valid after both the
675 /// top-down and bottom-up traversals are complete.
John McCalld935e9c2011-06-15 23:37:01 +0000676 unsigned GetAllPathCount() const {
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000677 assert(TopDownPathCount != 0);
678 assert(BottomUpPathCount != 0);
John McCalld935e9c2011-06-15 23:37:01 +0000679 return TopDownPathCount * BottomUpPathCount;
680 }
Dan Gohman12130272011-08-12 00:26:31 +0000681
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000682 // Specialized CFG utilities.
Dan Gohmandae33492012-04-27 18:56:31 +0000683 typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000684 edge_iterator pred_begin() { return Preds.begin(); }
685 edge_iterator pred_end() { return Preds.end(); }
686 edge_iterator succ_begin() { return Succs.begin(); }
687 edge_iterator succ_end() { return Succs.end(); }
688
689 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
690 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
691
692 bool isExit() const { return Succs.empty(); }
John McCalld935e9c2011-06-15 23:37:01 +0000693 };
694}
695
696void BBState::InitFromPred(const BBState &Other) {
697 PerPtrTopDown = Other.PerPtrTopDown;
698 TopDownPathCount = Other.TopDownPathCount;
699}
700
701void BBState::InitFromSucc(const BBState &Other) {
702 PerPtrBottomUp = Other.PerPtrBottomUp;
703 BottomUpPathCount = Other.BottomUpPathCount;
704}
705
Michael Gottesman97e3df02013-01-14 00:35:14 +0000706/// The top-down traversal uses this to merge information about predecessors to
707/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +0000708void BBState::MergePred(const BBState &Other) {
709 // Other.TopDownPathCount can be 0, in which case it is either dead or a
710 // loop backedge. Loop backedges are special.
711 TopDownPathCount += Other.TopDownPathCount;
712
Michael Gottesman4385edf2013-01-14 01:47:53 +0000713 // Check for overflow. If we have overflow, fall back to conservative
714 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +0000715 if (TopDownPathCount < Other.TopDownPathCount) {
716 clearTopDownPointers();
717 return;
718 }
719
John McCalld935e9c2011-06-15 23:37:01 +0000720 // For each entry in the other set, if our set has an entry with the same key,
721 // merge the entries. Otherwise, copy the entry and merge it with an empty
722 // entry.
723 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
724 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
725 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
726 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
727 /*TopDown=*/true);
728 }
729
Dan Gohman7e315fc32011-08-11 21:06:32 +0000730 // For each entry in our set, if the other set doesn't have an entry with the
John McCalld935e9c2011-06-15 23:37:01 +0000731 // same key, force it to merge with an empty entry.
732 for (ptr_iterator MI = top_down_ptr_begin(),
733 ME = top_down_ptr_end(); MI != ME; ++MI)
734 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
735 MI->second.Merge(PtrState(), /*TopDown=*/true);
736}
737
Michael Gottesman97e3df02013-01-14 00:35:14 +0000738/// The bottom-up traversal uses this to merge information about successors to
739/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +0000740void BBState::MergeSucc(const BBState &Other) {
741 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
742 // loop backedge. Loop backedges are special.
743 BottomUpPathCount += Other.BottomUpPathCount;
744
Michael Gottesman4385edf2013-01-14 01:47:53 +0000745 // Check for overflow. If we have overflow, fall back to conservative
746 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +0000747 if (BottomUpPathCount < Other.BottomUpPathCount) {
748 clearBottomUpPointers();
749 return;
750 }
751
John McCalld935e9c2011-06-15 23:37:01 +0000752 // For each entry in the other set, if our set has an entry with the
753 // same key, merge the entries. Otherwise, copy the entry and merge
754 // it with an empty entry.
755 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
756 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
757 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
758 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
759 /*TopDown=*/false);
760 }
761
Dan Gohman7e315fc32011-08-11 21:06:32 +0000762 // For each entry in our set, if the other set doesn't have an entry
John McCalld935e9c2011-06-15 23:37:01 +0000763 // with the same key, force it to merge with an empty entry.
764 for (ptr_iterator MI = bottom_up_ptr_begin(),
765 ME = bottom_up_ptr_end(); MI != ME; ++MI)
766 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
767 MI->second.Merge(PtrState(), /*TopDown=*/false);
768}
769
Michael Gottesman81b1d432013-03-26 00:42:04 +0000770// Only enable ARC Annotations if we are building a debug version of
771// libObjCARCOpts.
772#ifndef NDEBUG
773#define ARC_ANNOTATIONS
774#endif
775
776// Define some macros along the lines of DEBUG and some helper functions to make
777// it cleaner to create annotations in the source code and to no-op when not
778// building in debug mode.
779#ifdef ARC_ANNOTATIONS
780
781#include "llvm/Support/CommandLine.h"
782
783/// Enable/disable ARC sequence annotations.
784static cl::opt<bool>
Michael Gottesman6806b512013-04-17 20:48:03 +0000785EnableARCAnnotations("enable-objc-arc-annotations", cl::init(false),
786 cl::desc("Enable emission of arc data flow analysis "
787 "annotations"));
Michael Gottesmanffef24f2013-04-17 20:48:01 +0000788static cl::opt<bool>
Michael Gottesmanadb921a2013-04-17 21:03:53 +0000789DisableCheckForCFGHazards("disable-objc-arc-checkforcfghazards", cl::init(false),
790 cl::desc("Disable check for cfg hazards when "
791 "annotating"));
Michael Gottesman4e88ce62013-04-17 21:59:41 +0000792static cl::opt<std::string>
793ARCAnnotationTargetIdentifier("objc-arc-annotation-target-identifier",
794 cl::init(""),
795 cl::desc("filter out all data flow annotations "
796 "but those that apply to the given "
797 "target llvm identifier."));
Michael Gottesman81b1d432013-03-26 00:42:04 +0000798
799/// This function appends a unique ARCAnnotationProvenanceSourceMDKind id to an
800/// instruction so that we can track backwards when post processing via the llvm
801/// arc annotation processor tool. If the function is an
802static MDString *AppendMDNodeToSourcePtr(unsigned NodeId,
803 Value *Ptr) {
804 MDString *Hash = 0;
805
806 // If pointer is a result of an instruction and it does not have a source
807 // MDNode it, attach a new MDNode onto it. If pointer is a result of
808 // an instruction and does have a source MDNode attached to it, return a
809 // reference to said Node. Otherwise just return 0.
810 if (Instruction *Inst = dyn_cast<Instruction>(Ptr)) {
811 MDNode *Node;
812 if (!(Node = Inst->getMetadata(NodeId))) {
813 // We do not have any node. Generate and attatch the hash MDString to the
814 // instruction.
815
816 // We just use an MDString to ensure that this metadata gets written out
817 // of line at the module level and to provide a very simple format
818 // encoding the information herein. Both of these makes it simpler to
819 // parse the annotations by a simple external program.
820 std::string Str;
821 raw_string_ostream os(Str);
822 os << "(" << Inst->getParent()->getParent()->getName() << ",%"
823 << Inst->getName() << ")";
824
825 Hash = MDString::get(Inst->getContext(), os.str());
826 Inst->setMetadata(NodeId, MDNode::get(Inst->getContext(),Hash));
827 } else {
828 // We have a node. Grab its hash and return it.
829 assert(Node->getNumOperands() == 1 &&
830 "An ARCAnnotationProvenanceSourceMDKind can only have 1 operand.");
831 Hash = cast<MDString>(Node->getOperand(0));
832 }
833 } else if (Argument *Arg = dyn_cast<Argument>(Ptr)) {
834 std::string str;
835 raw_string_ostream os(str);
836 os << "(" << Arg->getParent()->getName() << ",%" << Arg->getName()
837 << ")";
838 Hash = MDString::get(Arg->getContext(), os.str());
839 }
840
841 return Hash;
842}
843
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000844static std::string SequenceToString(Sequence A) {
845 std::string str;
846 raw_string_ostream os(str);
847 os << A;
848 return os.str();
849}
850
Michael Gottesman81b1d432013-03-26 00:42:04 +0000851/// Helper function to change a Sequence into a String object using our overload
852/// for raw_ostream so we only have printing code in one location.
853static MDString *SequenceToMDString(LLVMContext &Context,
854 Sequence A) {
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000855 return MDString::get(Context, SequenceToString(A));
Michael Gottesman81b1d432013-03-26 00:42:04 +0000856}
857
858/// A simple function to generate a MDNode which describes the change in state
859/// for Value *Ptr caused by Instruction *Inst.
860static void AppendMDNodeToInstForPtr(unsigned NodeId,
861 Instruction *Inst,
862 Value *Ptr,
863 MDString *PtrSourceMDNodeID,
864 Sequence OldSeq,
865 Sequence NewSeq) {
866 MDNode *Node = 0;
867 Value *tmp[3] = {PtrSourceMDNodeID,
868 SequenceToMDString(Inst->getContext(),
869 OldSeq),
870 SequenceToMDString(Inst->getContext(),
871 NewSeq)};
872 Node = MDNode::get(Inst->getContext(),
873 ArrayRef<Value*>(tmp, 3));
874
875 Inst->setMetadata(NodeId, Node);
876}
877
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000878/// Add to the beginning of the basic block llvm.ptr.annotations which show the
879/// state of a pointer at the entrance to a basic block.
880static void GenerateARCBBEntranceAnnotation(const char *Name, BasicBlock *BB,
881 Value *Ptr, Sequence Seq) {
Michael Gottesman4e88ce62013-04-17 21:59:41 +0000882 // If we have a target identifier, make sure that we match it before
883 // continuing.
884 if(!ARCAnnotationTargetIdentifier.empty() &&
885 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
886 return;
Michael Gottesman9e518132013-04-18 04:34:11 +0000887
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000888 Module *M = BB->getParent()->getParent();
889 LLVMContext &C = M->getContext();
890 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
891 Type *I8XX = PointerType::getUnqual(I8X);
892 Type *Params[] = {I8XX, I8XX};
893 FunctionType *FTy = FunctionType::get(Type::getVoidTy(C),
894 ArrayRef<Type*>(Params, 2),
895 /*isVarArg=*/false);
896 Constant *Callee = M->getOrInsertFunction(Name, FTy);
Michael Gottesman60f6b282013-03-29 05:13:07 +0000897
898 IRBuilder<> Builder(BB, BB->getFirstInsertionPt());
899
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000900 Value *PtrName;
901 StringRef Tmp = Ptr->getName();
902 if (0 == (PtrName = M->getGlobalVariable(Tmp, true))) {
903 Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
904 Tmp + "_STR");
905 PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
Michael Gottesman60f6b282013-03-29 05:13:07 +0000906 cast<Constant>(ActualPtrName), Tmp);
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000907 }
908
909 Value *S;
910 std::string SeqStr = SequenceToString(Seq);
911 if (0 == (S = M->getGlobalVariable(SeqStr, true))) {
912 Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
913 SeqStr + "_STR");
914 S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
915 cast<Constant>(ActualPtrName), SeqStr);
916 }
917
918 Builder.CreateCall2(Callee, PtrName, S);
919}
920
921/// Add to the end of the basic block llvm.ptr.annotations which show the state
922/// of the pointer at the bottom of the basic block.
923static void GenerateARCBBTerminatorAnnotation(const char *Name, BasicBlock *BB,
924 Value *Ptr, Sequence Seq) {
Michael Gottesman4e88ce62013-04-17 21:59:41 +0000925 // If we have a target identifier, make sure that we match it before emitting
926 // an annotation.
927 if(!ARCAnnotationTargetIdentifier.empty() &&
928 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
929 return;
Michael Gottesman9e518132013-04-18 04:34:11 +0000930
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000931 Module *M = BB->getParent()->getParent();
932 LLVMContext &C = M->getContext();
933 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
934 Type *I8XX = PointerType::getUnqual(I8X);
935 Type *Params[] = {I8XX, I8XX};
936 FunctionType *FTy = FunctionType::get(Type::getVoidTy(C),
937 ArrayRef<Type*>(Params, 2),
938 /*isVarArg=*/false);
939 Constant *Callee = M->getOrInsertFunction(Name, FTy);
Michael Gottesman60f6b282013-03-29 05:13:07 +0000940
941 IRBuilder<> Builder(BB, llvm::prior(BB->end()));
942
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000943 Value *PtrName;
944 StringRef Tmp = Ptr->getName();
945 if (0 == (PtrName = M->getGlobalVariable(Tmp, true))) {
946 Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
947 Tmp + "_STR");
948 PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
Michael Gottesman60f6b282013-03-29 05:13:07 +0000949 cast<Constant>(ActualPtrName), Tmp);
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000950 }
951
952 Value *S;
953 std::string SeqStr = SequenceToString(Seq);
954 if (0 == (S = M->getGlobalVariable(SeqStr, true))) {
955 Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
956 SeqStr + "_STR");
957 S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
958 cast<Constant>(ActualPtrName), SeqStr);
959 }
Michael Gottesman60f6b282013-03-29 05:13:07 +0000960 Builder.CreateCall2(Callee, PtrName, S);
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000961}
962
Michael Gottesman81b1d432013-03-26 00:42:04 +0000963/// Adds a source annotation to pointer and a state change annotation to Inst
964/// referencing the source annotation and the old/new state of pointer.
965static void GenerateARCAnnotation(unsigned InstMDId,
966 unsigned PtrMDId,
967 Instruction *Inst,
968 Value *Ptr,
969 Sequence OldSeq,
970 Sequence NewSeq) {
971 if (EnableARCAnnotations) {
Michael Gottesman4e88ce62013-04-17 21:59:41 +0000972 // If we have a target identifier, make sure that we match it before
973 // emitting an annotation.
974 if(!ARCAnnotationTargetIdentifier.empty() &&
975 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
976 return;
Michael Gottesman9e518132013-04-18 04:34:11 +0000977
Michael Gottesman81b1d432013-03-26 00:42:04 +0000978 // First generate the source annotation on our pointer. This will return an
979 // MDString* if Ptr actually comes from an instruction implying we can put
980 // in a source annotation. If AppendMDNodeToSourcePtr returns 0 (i.e. NULL),
981 // then we know that our pointer is from an Argument so we put a reference
982 // to the argument number.
983 //
984 // The point of this is to make it easy for the
985 // llvm-arc-annotation-processor tool to cross reference where the source
986 // pointer is in the LLVM IR since the LLVM IR parser does not submit such
987 // information via debug info for backends to use (since why would anyone
988 // need such a thing from LLVM IR besides in non standard cases
989 // [i.e. this]).
990 MDString *SourcePtrMDNode =
991 AppendMDNodeToSourcePtr(PtrMDId, Ptr);
992 AppendMDNodeToInstForPtr(InstMDId, Inst, Ptr, SourcePtrMDNode, OldSeq,
993 NewSeq);
994 }
995}
996
997// The actual interface for accessing the above functionality is defined via
998// some simple macros which are defined below. We do this so that the user does
999// not need to pass in what metadata id is needed resulting in cleaner code and
1000// additionally since it provides an easy way to conditionally no-op all
1001// annotation support in a non-debug build.
1002
1003/// Use this macro to annotate a sequence state change when processing
1004/// instructions bottom up,
1005#define ANNOTATE_BOTTOMUP(inst, ptr, old, new) \
1006 GenerateARCAnnotation(ARCAnnotationBottomUpMDKind, \
1007 ARCAnnotationProvenanceSourceMDKind, (inst), \
1008 const_cast<Value*>(ptr), (old), (new))
1009/// Use this macro to annotate a sequence state change when processing
1010/// instructions top down.
1011#define ANNOTATE_TOPDOWN(inst, ptr, old, new) \
1012 GenerateARCAnnotation(ARCAnnotationTopDownMDKind, \
1013 ARCAnnotationProvenanceSourceMDKind, (inst), \
1014 const_cast<Value*>(ptr), (old), (new))
1015
Michael Gottesman43e7e002013-04-03 22:41:59 +00001016#define ANNOTATE_BB(_states, _bb, _name, _type, _direction) \
1017 do { \
Michael Gottesman89279f82013-04-05 18:10:41 +00001018 if (EnableARCAnnotations) { \
1019 for(BBState::ptr_const_iterator I = (_states)._direction##_ptr_begin(), \
Michael Gottesman43e7e002013-04-03 22:41:59 +00001020 E = (_states)._direction##_ptr_end(); I != E; ++I) { \
Michael Gottesman89279f82013-04-05 18:10:41 +00001021 Value *Ptr = const_cast<Value*>(I->first); \
1022 Sequence Seq = I->second.GetSeq(); \
1023 GenerateARCBB ## _type ## Annotation(_name, (_bb), Ptr, Seq); \
1024 } \
Michael Gottesman43e7e002013-04-03 22:41:59 +00001025 } \
Michael Gottesman89279f82013-04-05 18:10:41 +00001026 } while (0)
Michael Gottesman43e7e002013-04-03 22:41:59 +00001027
Michael Gottesman89279f82013-04-05 18:10:41 +00001028#define ANNOTATE_BOTTOMUP_BBSTART(_states, _basicblock) \
Michael Gottesman43e7e002013-04-03 22:41:59 +00001029 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbstart", \
1030 Entrance, bottom_up)
Michael Gottesman89279f82013-04-05 18:10:41 +00001031#define ANNOTATE_BOTTOMUP_BBEND(_states, _basicblock) \
1032 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbend", \
Michael Gottesman43e7e002013-04-03 22:41:59 +00001033 Terminator, bottom_up)
Michael Gottesman89279f82013-04-05 18:10:41 +00001034#define ANNOTATE_TOPDOWN_BBSTART(_states, _basicblock) \
1035 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbstart", \
Michael Gottesman43e7e002013-04-03 22:41:59 +00001036 Entrance, top_down)
Michael Gottesman89279f82013-04-05 18:10:41 +00001037#define ANNOTATE_TOPDOWN_BBEND(_states, _basicblock) \
1038 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbend", \
Michael Gottesman43e7e002013-04-03 22:41:59 +00001039 Terminator, top_down)
1040
Michael Gottesman81b1d432013-03-26 00:42:04 +00001041#else // !ARC_ANNOTATION
1042// If annotations are off, noop.
1043#define ANNOTATE_BOTTOMUP(inst, ptr, old, new)
1044#define ANNOTATE_TOPDOWN(inst, ptr, old, new)
Michael Gottesman43e7e002013-04-03 22:41:59 +00001045#define ANNOTATE_BOTTOMUP_BBSTART(states, basicblock)
1046#define ANNOTATE_BOTTOMUP_BBEND(states, basicblock)
1047#define ANNOTATE_TOPDOWN_BBSTART(states, basicblock)
1048#define ANNOTATE_TOPDOWN_BBEND(states, basicblock)
Michael Gottesman81b1d432013-03-26 00:42:04 +00001049#endif // !ARC_ANNOTATION
1050
John McCalld935e9c2011-06-15 23:37:01 +00001051namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001052 /// \brief The main ARC optimization pass.
John McCalld935e9c2011-06-15 23:37:01 +00001053 class ObjCARCOpt : public FunctionPass {
1054 bool Changed;
1055 ProvenanceAnalysis PA;
1056
Michael Gottesman5a91bbf2013-05-24 20:44:02 +00001057 // This is used to track if a pointer is stored into an alloca.
1058 DenseSet<const Value *> MultiOwnersSet;
1059
Michael Gottesman97e3df02013-01-14 00:35:14 +00001060 /// A flag indicating whether this optimization pass should run.
Dan Gohmanceaac7c2011-06-20 23:20:43 +00001061 bool Run;
1062
Michael Gottesman97e3df02013-01-14 00:35:14 +00001063 /// Declarations for ObjC runtime functions, for use in creating calls to
1064 /// them. These are initialized lazily to avoid cluttering up the Module
1065 /// with unused declarations.
John McCalld935e9c2011-06-15 23:37:01 +00001066
Michael Gottesman97e3df02013-01-14 00:35:14 +00001067 /// Declaration for ObjC runtime function objc_autoreleaseReturnValue.
1068 Constant *AutoreleaseRVCallee;
1069 /// Declaration for ObjC runtime function objc_release.
1070 Constant *ReleaseCallee;
1071 /// Declaration for ObjC runtime function objc_retain.
1072 Constant *RetainCallee;
1073 /// Declaration for ObjC runtime function objc_retainBlock.
1074 Constant *RetainBlockCallee;
1075 /// Declaration for ObjC runtime function objc_autorelease.
1076 Constant *AutoreleaseCallee;
1077
1078 /// Flags which determine whether each of the interesting runtine functions
1079 /// is in fact used in the current function.
John McCalld935e9c2011-06-15 23:37:01 +00001080 unsigned UsedInThisFunction;
1081
Michael Gottesman97e3df02013-01-14 00:35:14 +00001082 /// The Metadata Kind for clang.imprecise_release metadata.
John McCalld935e9c2011-06-15 23:37:01 +00001083 unsigned ImpreciseReleaseMDKind;
1084
Michael Gottesman97e3df02013-01-14 00:35:14 +00001085 /// The Metadata Kind for clang.arc.copy_on_escape metadata.
Dan Gohmana7107f92011-10-17 22:53:25 +00001086 unsigned CopyOnEscapeMDKind;
1087
Michael Gottesman97e3df02013-01-14 00:35:14 +00001088 /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata.
Dan Gohman0155f302012-02-17 18:59:53 +00001089 unsigned NoObjCARCExceptionsMDKind;
1090
Michael Gottesman81b1d432013-03-26 00:42:04 +00001091#ifdef ARC_ANNOTATIONS
1092 /// The Metadata Kind for llvm.arc.annotation.bottomup metadata.
1093 unsigned ARCAnnotationBottomUpMDKind;
1094 /// The Metadata Kind for llvm.arc.annotation.topdown metadata.
1095 unsigned ARCAnnotationTopDownMDKind;
1096 /// The Metadata Kind for llvm.arc.annotation.provenancesource metadata.
1097 unsigned ARCAnnotationProvenanceSourceMDKind;
1098#endif // ARC_ANNOATIONS
1099
John McCalld935e9c2011-06-15 23:37:01 +00001100 Constant *getAutoreleaseRVCallee(Module *M);
1101 Constant *getReleaseCallee(Module *M);
1102 Constant *getRetainCallee(Module *M);
Dan Gohman6320f522011-07-22 22:29:21 +00001103 Constant *getRetainBlockCallee(Module *M);
John McCalld935e9c2011-06-15 23:37:01 +00001104 Constant *getAutoreleaseCallee(Module *M);
1105
Dan Gohman728db492012-01-13 00:39:07 +00001106 bool IsRetainBlockOptimizable(const Instruction *Inst);
1107
John McCalld935e9c2011-06-15 23:37:01 +00001108 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
Michael Gottesman556ff612013-01-12 01:25:19 +00001109 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1110 InstructionClass &Class);
Michael Gottesman158fdf62013-03-28 20:11:19 +00001111 bool OptimizeRetainBlockCall(Function &F, Instruction *RetainBlock,
1112 InstructionClass &Class);
John McCalld935e9c2011-06-15 23:37:01 +00001113 void OptimizeIndividualCalls(Function &F);
1114
1115 void CheckForCFGHazards(const BasicBlock *BB,
1116 DenseMap<const BasicBlock *, BBState> &BBStates,
1117 BBState &MyStates) const;
Dan Gohman817a7c62012-03-22 18:24:56 +00001118 bool VisitInstructionBottomUp(Instruction *Inst,
Dan Gohman5c70fad2012-03-23 17:47:54 +00001119 BasicBlock *BB,
Dan Gohman817a7c62012-03-22 18:24:56 +00001120 MapVector<Value *, RRInfo> &Retains,
1121 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00001122 bool VisitBottomUp(BasicBlock *BB,
1123 DenseMap<const BasicBlock *, BBState> &BBStates,
1124 MapVector<Value *, RRInfo> &Retains);
Dan Gohman817a7c62012-03-22 18:24:56 +00001125 bool VisitInstructionTopDown(Instruction *Inst,
1126 DenseMap<Value *, RRInfo> &Releases,
1127 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00001128 bool VisitTopDown(BasicBlock *BB,
1129 DenseMap<const BasicBlock *, BBState> &BBStates,
1130 DenseMap<Value *, RRInfo> &Releases);
1131 bool Visit(Function &F,
1132 DenseMap<const BasicBlock *, BBState> &BBStates,
1133 MapVector<Value *, RRInfo> &Retains,
1134 DenseMap<Value *, RRInfo> &Releases);
1135
1136 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1137 MapVector<Value *, RRInfo> &Retains,
1138 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman6320f522011-07-22 22:29:21 +00001139 SmallVectorImpl<Instruction *> &DeadInsts,
1140 Module *M);
John McCalld935e9c2011-06-15 23:37:01 +00001141
Michael Gottesman9de6f962013-01-22 21:49:00 +00001142 bool ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState> &BBStates,
1143 MapVector<Value *, RRInfo> &Retains,
1144 DenseMap<Value *, RRInfo> &Releases,
1145 Module *M,
1146 SmallVector<Instruction *, 4> &NewRetains,
1147 SmallVector<Instruction *, 4> &NewReleases,
1148 SmallVector<Instruction *, 8> &DeadInsts,
1149 RRInfo &RetainsToMove,
1150 RRInfo &ReleasesToMove,
1151 Value *Arg,
1152 bool KnownSafe,
1153 bool &AnyPairsCompletelyEliminated);
1154
John McCalld935e9c2011-06-15 23:37:01 +00001155 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1156 MapVector<Value *, RRInfo> &Retains,
Dan Gohman6320f522011-07-22 22:29:21 +00001157 DenseMap<Value *, RRInfo> &Releases,
1158 Module *M);
John McCalld935e9c2011-06-15 23:37:01 +00001159
1160 void OptimizeWeakCalls(Function &F);
1161
1162 bool OptimizeSequences(Function &F);
1163
1164 void OptimizeReturns(Function &F);
1165
Michael Gottesman9c118152013-04-29 06:16:57 +00001166#ifndef NDEBUG
1167 void GatherStatistics(Function &F, bool AfterOptimization = false);
1168#endif
1169
John McCalld935e9c2011-06-15 23:37:01 +00001170 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1171 virtual bool doInitialization(Module &M);
1172 virtual bool runOnFunction(Function &F);
1173 virtual void releaseMemory();
1174
1175 public:
1176 static char ID;
1177 ObjCARCOpt() : FunctionPass(ID) {
1178 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1179 }
1180 };
1181}
1182
1183char ObjCARCOpt::ID = 0;
1184INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1185 "objc-arc", "ObjC ARC optimization", false, false)
1186INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1187INITIALIZE_PASS_END(ObjCARCOpt,
1188 "objc-arc", "ObjC ARC optimization", false, false)
1189
1190Pass *llvm::createObjCARCOptPass() {
1191 return new ObjCARCOpt();
1192}
1193
1194void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1195 AU.addRequired<ObjCARCAliasAnalysis>();
1196 AU.addRequired<AliasAnalysis>();
1197 // ARC optimization doesn't currently split critical edges.
1198 AU.setPreservesCFG();
1199}
1200
Dan Gohman728db492012-01-13 00:39:07 +00001201bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1202 // Without the magic metadata tag, we have to assume this might be an
1203 // objc_retainBlock call inserted to convert a block pointer to an id,
1204 // in which case it really is needed.
1205 if (!Inst->getMetadata(CopyOnEscapeMDKind))
1206 return false;
1207
1208 // If the pointer "escapes" (not including being used in a call),
1209 // the copy may be needed.
Michael Gottesman774d2c02013-01-29 21:00:52 +00001210 if (DoesRetainableObjPtrEscape(Inst))
Dan Gohman728db492012-01-13 00:39:07 +00001211 return false;
1212
1213 // Otherwise, it's not needed.
1214 return true;
1215}
1216
John McCalld935e9c2011-06-15 23:37:01 +00001217Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1218 if (!AutoreleaseRVCallee) {
1219 LLVMContext &C = M->getContext();
Jay Foadb804a2b2011-07-12 14:06:48 +00001220 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman41375a32012-05-08 23:39:44 +00001221 Type *Params[] = { I8X };
1222 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001223 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001224 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1225 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001226 AutoreleaseRVCallee =
1227 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001228 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001229 }
1230 return AutoreleaseRVCallee;
1231}
1232
1233Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1234 if (!ReleaseCallee) {
1235 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001236 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001237 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001238 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1239 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001240 ReleaseCallee =
1241 M->getOrInsertFunction(
1242 "objc_release",
1243 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001244 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001245 }
1246 return ReleaseCallee;
1247}
1248
1249Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1250 if (!RetainCallee) {
1251 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001252 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001253 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001254 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1255 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001256 RetainCallee =
1257 M->getOrInsertFunction(
1258 "objc_retain",
1259 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001260 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001261 }
1262 return RetainCallee;
1263}
1264
Dan Gohman6320f522011-07-22 22:29:21 +00001265Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1266 if (!RetainBlockCallee) {
1267 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001268 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Dan Gohmanfca43c22011-09-14 18:33:34 +00001269 // objc_retainBlock is not nounwind because it calls user copy constructors
1270 // which could theoretically throw.
Dan Gohman6320f522011-07-22 22:29:21 +00001271 RetainBlockCallee =
1272 M->getOrInsertFunction(
1273 "objc_retainBlock",
1274 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendlinge94d8432012-12-07 23:16:57 +00001275 AttributeSet());
Dan Gohman6320f522011-07-22 22:29:21 +00001276 }
1277 return RetainBlockCallee;
1278}
1279
John McCalld935e9c2011-06-15 23:37:01 +00001280Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1281 if (!AutoreleaseCallee) {
1282 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001283 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001284 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001285 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1286 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001287 AutoreleaseCallee =
1288 M->getOrInsertFunction(
1289 "objc_autorelease",
1290 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001291 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001292 }
1293 return AutoreleaseCallee;
1294}
1295
Michael Gottesman97e3df02013-01-14 00:35:14 +00001296/// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is
1297/// not a return value. Or, if it can be paired with an
1298/// objc_autoreleaseReturnValue, delete the pair and return true.
John McCalld935e9c2011-06-15 23:37:01 +00001299bool
1300ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001301 // Check for the argument being from an immediately preceding call or invoke.
Dan Gohmandae33492012-04-27 18:56:31 +00001302 const Value *Arg = GetObjCArg(RetainRV);
1303 ImmutableCallSite CS(Arg);
1304 if (const Instruction *Call = CS.getInstruction()) {
John McCalld935e9c2011-06-15 23:37:01 +00001305 if (Call->getParent() == RetainRV->getParent()) {
Dan Gohmandae33492012-04-27 18:56:31 +00001306 BasicBlock::const_iterator I = Call;
John McCalld935e9c2011-06-15 23:37:01 +00001307 ++I;
Michael Gottesman65c24812013-03-25 09:27:43 +00001308 while (IsNoopInstruction(I)) ++I;
John McCalld935e9c2011-06-15 23:37:01 +00001309 if (&*I == RetainRV)
1310 return false;
Dan Gohmandae33492012-04-27 18:56:31 +00001311 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001312 BasicBlock *RetainRVParent = RetainRV->getParent();
1313 if (II->getNormalDest() == RetainRVParent) {
Dan Gohmandae33492012-04-27 18:56:31 +00001314 BasicBlock::const_iterator I = RetainRVParent->begin();
Michael Gottesman65c24812013-03-25 09:27:43 +00001315 while (IsNoopInstruction(I)) ++I;
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001316 if (&*I == RetainRV)
1317 return false;
1318 }
John McCalld935e9c2011-06-15 23:37:01 +00001319 }
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001320 }
John McCalld935e9c2011-06-15 23:37:01 +00001321
1322 // Check for being preceded by an objc_autoreleaseReturnValue on the same
1323 // pointer. In this case, we can delete the pair.
1324 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
1325 if (I != Begin) {
Michael Gottesman65c24812013-03-25 09:27:43 +00001326 do --I; while (I != Begin && IsNoopInstruction(I));
John McCalld935e9c2011-06-15 23:37:01 +00001327 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
1328 GetObjCArg(I) == Arg) {
1329 Changed = true;
1330 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00001331
Michael Gottesman89279f82013-04-05 18:10:41 +00001332 DEBUG(dbgs() << "Erasing autoreleaseRV,retainRV pair: " << *I << "\n"
1333 << "Erasing " << *RetainRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001334
John McCalld935e9c2011-06-15 23:37:01 +00001335 EraseInstruction(I);
1336 EraseInstruction(RetainRV);
1337 return true;
1338 }
1339 }
1340
1341 // Turn it to a plain objc_retain.
1342 Changed = true;
1343 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00001344
Michael Gottesman89279f82013-04-05 18:10:41 +00001345 DEBUG(dbgs() << "Transforming objc_retainAutoreleasedReturnValue => "
Michael Gottesmandef07bb2013-01-05 17:55:42 +00001346 "objc_retain since the operand is not a return value.\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00001347 "Old = " << *RetainRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001348
John McCalld935e9c2011-06-15 23:37:01 +00001349 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
Michael Gottesmandef07bb2013-01-05 17:55:42 +00001350
Michael Gottesman89279f82013-04-05 18:10:41 +00001351 DEBUG(dbgs() << "New = " << *RetainRV << "\n");
Michael Gottesmandef07bb2013-01-05 17:55:42 +00001352
John McCalld935e9c2011-06-15 23:37:01 +00001353 return false;
1354}
1355
Michael Gottesman97e3df02013-01-14 00:35:14 +00001356/// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not
1357/// used as a return value.
John McCalld935e9c2011-06-15 23:37:01 +00001358void
Michael Gottesman556ff612013-01-12 01:25:19 +00001359ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1360 InstructionClass &Class) {
John McCalld935e9c2011-06-15 23:37:01 +00001361 // Check for a return of the pointer value.
1362 const Value *Ptr = GetObjCArg(AutoreleaseRV);
Dan Gohman10a18d52011-08-12 00:36:31 +00001363 SmallVector<const Value *, 2> Users;
1364 Users.push_back(Ptr);
1365 do {
1366 Ptr = Users.pop_back_val();
1367 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
1368 UI != UE; ++UI) {
1369 const User *I = *UI;
1370 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
1371 return;
1372 if (isa<BitCastInst>(I))
1373 Users.push_back(I);
1374 }
1375 } while (!Users.empty());
John McCalld935e9c2011-06-15 23:37:01 +00001376
1377 Changed = true;
1378 ++NumPeeps;
Michael Gottesman1bf69082013-01-06 21:07:11 +00001379
Michael Gottesman89279f82013-04-05 18:10:41 +00001380 DEBUG(dbgs() << "Transforming objc_autoreleaseReturnValue => "
Michael Gottesman1bf69082013-01-06 21:07:11 +00001381 "objc_autorelease since its operand is not used as a return "
1382 "value.\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00001383 "Old = " << *AutoreleaseRV << "\n");
Michael Gottesman1bf69082013-01-06 21:07:11 +00001384
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001385 CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
1386 AutoreleaseRVCI->
John McCalld935e9c2011-06-15 23:37:01 +00001387 setCalledFunction(getAutoreleaseCallee(F.getParent()));
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001388 AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
Michael Gottesman556ff612013-01-12 01:25:19 +00001389 Class = IC_Autorelease;
Michael Gottesman10426b52013-01-07 21:26:07 +00001390
Michael Gottesman89279f82013-04-05 18:10:41 +00001391 DEBUG(dbgs() << "New: " << *AutoreleaseRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001392
John McCalld935e9c2011-06-15 23:37:01 +00001393}
1394
Michael Gottesman158fdf62013-03-28 20:11:19 +00001395// \brief Attempt to strength reduce objc_retainBlock calls to objc_retain
1396// calls.
1397//
1398// Specifically: If an objc_retainBlock call has the copy_on_escape metadata and
1399// does not escape (following the rules of block escaping), strength reduce the
1400// objc_retainBlock to an objc_retain.
1401//
1402// TODO: If an objc_retainBlock call is dominated period by a previous
1403// objc_retainBlock call, strength reduce the objc_retainBlock to an
1404// objc_retain.
1405bool
1406ObjCARCOpt::OptimizeRetainBlockCall(Function &F, Instruction *Inst,
1407 InstructionClass &Class) {
1408 assert(GetBasicInstructionClass(Inst) == Class);
1409 assert(IC_RetainBlock == Class);
Michael Gottesman60f6b282013-03-29 05:13:07 +00001410
Michael Gottesman158fdf62013-03-28 20:11:19 +00001411 // If we can not optimize Inst, return false.
1412 if (!IsRetainBlockOptimizable(Inst))
1413 return false;
Michael Gottesman60f6b282013-03-29 05:13:07 +00001414
Michael Gottesman3eab2e42013-04-21 00:50:27 +00001415 Changed = true;
1416 ++NumPeeps;
1417
1418 DEBUG(dbgs() << "Strength reduced retainBlock => retain.\n");
1419 DEBUG(dbgs() << "Old: " << *Inst << "\n");
Michael Gottesman158fdf62013-03-28 20:11:19 +00001420 CallInst *RetainBlock = cast<CallInst>(Inst);
1421 RetainBlock->setCalledFunction(getRetainCallee(F.getParent()));
1422 // Remove copy_on_escape metadata.
1423 RetainBlock->setMetadata(CopyOnEscapeMDKind, 0);
1424 Class = IC_Retain;
Michael Gottesman3eab2e42013-04-21 00:50:27 +00001425 DEBUG(dbgs() << "New: " << *Inst << "\n");
Michael Gottesman158fdf62013-03-28 20:11:19 +00001426 return true;
1427}
1428
Michael Gottesman97e3df02013-01-14 00:35:14 +00001429/// Visit each call, one at a time, and make simplifications without doing any
1430/// additional analysis.
John McCalld935e9c2011-06-15 23:37:01 +00001431void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001432 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeIndividualCalls ==\n");
John McCalld935e9c2011-06-15 23:37:01 +00001433 // Reset all the flags in preparation for recomputing them.
1434 UsedInThisFunction = 0;
1435
1436 // Visit all objc_* calls in F.
1437 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
1438 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +00001439
John McCalld935e9c2011-06-15 23:37:01 +00001440 InstructionClass Class = GetBasicInstructionClass(Inst);
1441
Michael Gottesman89279f82013-04-05 18:10:41 +00001442 DEBUG(dbgs() << "Visiting: Class: " << Class << "; " << *Inst << "\n");
Michael Gottesman782e3442013-01-17 18:32:34 +00001443
John McCalld935e9c2011-06-15 23:37:01 +00001444 switch (Class) {
1445 default: break;
1446
1447 // Delete no-op casts. These function calls have special semantics, but
1448 // the semantics are entirely implemented via lowering in the front-end,
1449 // so by the time they reach the optimizer, they are just no-op calls
1450 // which return their argument.
1451 //
1452 // There are gray areas here, as the ability to cast reference-counted
1453 // pointers to raw void* and back allows code to break ARC assumptions,
1454 // however these are currently considered to be unimportant.
1455 case IC_NoopCast:
1456 Changed = true;
1457 ++NumNoops;
Michael Gottesman89279f82013-04-05 18:10:41 +00001458 DEBUG(dbgs() << "Erasing no-op cast: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001459 EraseInstruction(Inst);
1460 continue;
1461
1462 // If the pointer-to-weak-pointer is null, it's undefined behavior.
1463 case IC_StoreWeak:
1464 case IC_LoadWeak:
1465 case IC_LoadWeakRetained:
1466 case IC_InitWeak:
1467 case IC_DestroyWeak: {
1468 CallInst *CI = cast<CallInst>(Inst);
Michael Gottesman65c24812013-03-25 09:27:43 +00001469 if (IsNullOrUndef(CI->getArgOperand(0))) {
Dan Gohman670f9372012-04-13 18:57:48 +00001470 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +00001471 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001472 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1473 Constant::getNullValue(Ty),
1474 CI);
Michael Gottesman10426b52013-01-07 21:26:07 +00001475 llvm::Value *NewValue = UndefValue::get(CI->getType());
Michael Gottesman89279f82013-04-05 18:10:41 +00001476 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
1477 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001478 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +00001479 CI->eraseFromParent();
1480 continue;
1481 }
1482 break;
1483 }
1484 case IC_CopyWeak:
1485 case IC_MoveWeak: {
1486 CallInst *CI = cast<CallInst>(Inst);
Michael Gottesman65c24812013-03-25 09:27:43 +00001487 if (IsNullOrUndef(CI->getArgOperand(0)) ||
1488 IsNullOrUndef(CI->getArgOperand(1))) {
Dan Gohman670f9372012-04-13 18:57:48 +00001489 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +00001490 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001491 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1492 Constant::getNullValue(Ty),
1493 CI);
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001494
1495 llvm::Value *NewValue = UndefValue::get(CI->getType());
Michael Gottesman89279f82013-04-05 18:10:41 +00001496 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
1497 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001498
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001499 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +00001500 CI->eraseFromParent();
1501 continue;
1502 }
1503 break;
1504 }
Michael Gottesman158fdf62013-03-28 20:11:19 +00001505 case IC_RetainBlock:
Michael Gottesman1e430042013-04-21 00:44:46 +00001506 // If we strength reduce an objc_retainBlock to an objc_retain, continue
Michael Gottesman158fdf62013-03-28 20:11:19 +00001507 // onto the objc_retain peephole optimizations. Otherwise break.
Michael Gottesman9fc50b82013-05-13 18:29:07 +00001508 OptimizeRetainBlockCall(F, Inst, Class);
John McCalld935e9c2011-06-15 23:37:01 +00001509 break;
1510 case IC_RetainRV:
1511 if (OptimizeRetainRVCall(F, Inst))
1512 continue;
1513 break;
1514 case IC_AutoreleaseRV:
Michael Gottesman556ff612013-01-12 01:25:19 +00001515 OptimizeAutoreleaseRVCall(F, Inst, Class);
John McCalld935e9c2011-06-15 23:37:01 +00001516 break;
1517 }
1518
Michael Gottesmanb8c88362013-04-03 02:57:24 +00001519 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
John McCalld935e9c2011-06-15 23:37:01 +00001520 if (IsAutorelease(Class) && Inst->use_empty()) {
1521 CallInst *Call = cast<CallInst>(Inst);
1522 const Value *Arg = Call->getArgOperand(0);
1523 Arg = FindSingleUseIdentifiedObject(Arg);
1524 if (Arg) {
1525 Changed = true;
1526 ++NumAutoreleases;
1527
1528 // Create the declaration lazily.
1529 LLVMContext &C = Inst->getContext();
1530 CallInst *NewCall =
1531 CallInst::Create(getReleaseCallee(F.getParent()),
1532 Call->getArgOperand(0), "", Call);
Dmitri Gribenko3238fb72013-05-05 00:40:33 +00001533 NewCall->setMetadata(ImpreciseReleaseMDKind, MDNode::get(C, None));
Michael Gottesman10426b52013-01-07 21:26:07 +00001534
Michael Gottesman89279f82013-04-05 18:10:41 +00001535 DEBUG(dbgs() << "Replacing autorelease{,RV}(x) with objc_release(x) "
1536 "since x is otherwise unused.\nOld: " << *Call << "\nNew: "
1537 << *NewCall << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001538
John McCalld935e9c2011-06-15 23:37:01 +00001539 EraseInstruction(Call);
1540 Inst = NewCall;
1541 Class = IC_Release;
1542 }
1543 }
1544
1545 // For functions which can never be passed stack arguments, add
1546 // a tail keyword.
1547 if (IsAlwaysTail(Class)) {
1548 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +00001549 DEBUG(dbgs() << "Adding tail keyword to function since it can never be "
1550 "passed stack args: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001551 cast<CallInst>(Inst)->setTailCall();
1552 }
1553
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001554 // Ensure that functions that can never have a "tail" keyword due to the
1555 // semantics of ARC truly do not do so.
1556 if (IsNeverTail(Class)) {
1557 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +00001558 DEBUG(dbgs() << "Removing tail keyword from function: " << *Inst <<
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001559 "\n");
1560 cast<CallInst>(Inst)->setTailCall(false);
1561 }
1562
John McCalld935e9c2011-06-15 23:37:01 +00001563 // Set nounwind as needed.
1564 if (IsNoThrow(Class)) {
1565 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +00001566 DEBUG(dbgs() << "Found no throw class. Setting nounwind on: " << *Inst
1567 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001568 cast<CallInst>(Inst)->setDoesNotThrow();
1569 }
1570
1571 if (!IsNoopOnNull(Class)) {
1572 UsedInThisFunction |= 1 << Class;
1573 continue;
1574 }
1575
1576 const Value *Arg = GetObjCArg(Inst);
1577
1578 // ARC calls with null are no-ops. Delete them.
Michael Gottesman65c24812013-03-25 09:27:43 +00001579 if (IsNullOrUndef(Arg)) {
John McCalld935e9c2011-06-15 23:37:01 +00001580 Changed = true;
1581 ++NumNoops;
Michael Gottesman89279f82013-04-05 18:10:41 +00001582 DEBUG(dbgs() << "ARC calls with null are no-ops. Erasing: " << *Inst
1583 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001584 EraseInstruction(Inst);
1585 continue;
1586 }
1587
1588 // Keep track of which of retain, release, autorelease, and retain_block
1589 // are actually present in this function.
1590 UsedInThisFunction |= 1 << Class;
1591
1592 // If Arg is a PHI, and one or more incoming values to the
1593 // PHI are null, and the call is control-equivalent to the PHI, and there
1594 // are no relevant side effects between the PHI and the call, the call
1595 // could be pushed up to just those paths with non-null incoming values.
1596 // For now, don't bother splitting critical edges for this.
1597 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
1598 Worklist.push_back(std::make_pair(Inst, Arg));
1599 do {
1600 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
1601 Inst = Pair.first;
1602 Arg = Pair.second;
1603
1604 const PHINode *PN = dyn_cast<PHINode>(Arg);
1605 if (!PN) continue;
1606
1607 // Determine if the PHI has any null operands, or any incoming
1608 // critical edges.
1609 bool HasNull = false;
1610 bool HasCriticalEdges = false;
1611 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1612 Value *Incoming =
1613 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
Michael Gottesman65c24812013-03-25 09:27:43 +00001614 if (IsNullOrUndef(Incoming))
John McCalld935e9c2011-06-15 23:37:01 +00001615 HasNull = true;
1616 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
1617 .getNumSuccessors() != 1) {
1618 HasCriticalEdges = true;
1619 break;
1620 }
1621 }
1622 // If we have null operands and no critical edges, optimize.
1623 if (!HasCriticalEdges && HasNull) {
1624 SmallPtrSet<Instruction *, 4> DependingInstructions;
1625 SmallPtrSet<const BasicBlock *, 4> Visited;
1626
1627 // Check that there is nothing that cares about the reference
1628 // count between the call and the phi.
Dan Gohman8478d762012-04-13 00:59:57 +00001629 switch (Class) {
1630 case IC_Retain:
1631 case IC_RetainBlock:
1632 // These can always be moved up.
1633 break;
1634 case IC_Release:
Dan Gohman41375a32012-05-08 23:39:44 +00001635 // These can't be moved across things that care about the retain
1636 // count.
Dan Gohman8478d762012-04-13 00:59:57 +00001637 FindDependencies(NeedsPositiveRetainCount, Arg,
1638 Inst->getParent(), Inst,
1639 DependingInstructions, Visited, PA);
1640 break;
1641 case IC_Autorelease:
1642 // These can't be moved across autorelease pool scope boundaries.
1643 FindDependencies(AutoreleasePoolBoundary, Arg,
1644 Inst->getParent(), Inst,
1645 DependingInstructions, Visited, PA);
1646 break;
1647 case IC_RetainRV:
1648 case IC_AutoreleaseRV:
1649 // Don't move these; the RV optimization depends on the autoreleaseRV
1650 // being tail called, and the retainRV being immediately after a call
1651 // (which might still happen if we get lucky with codegen layout, but
1652 // it's not worth taking the chance).
1653 continue;
1654 default:
1655 llvm_unreachable("Invalid dependence flavor");
1656 }
1657
John McCalld935e9c2011-06-15 23:37:01 +00001658 if (DependingInstructions.size() == 1 &&
1659 *DependingInstructions.begin() == PN) {
1660 Changed = true;
1661 ++NumPartialNoops;
1662 // Clone the call into each predecessor that has a non-null value.
1663 CallInst *CInst = cast<CallInst>(Inst);
Chris Lattner229907c2011-07-18 04:54:35 +00001664 Type *ParamTy = CInst->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001665 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1666 Value *Incoming =
1667 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
Michael Gottesman65c24812013-03-25 09:27:43 +00001668 if (!IsNullOrUndef(Incoming)) {
John McCalld935e9c2011-06-15 23:37:01 +00001669 CallInst *Clone = cast<CallInst>(CInst->clone());
1670 Value *Op = PN->getIncomingValue(i);
1671 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
1672 if (Op->getType() != ParamTy)
1673 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
1674 Clone->setArgOperand(0, Op);
1675 Clone->insertBefore(InsertPos);
Michael Gottesmanc189a392013-01-09 19:23:24 +00001676
Michael Gottesman89279f82013-04-05 18:10:41 +00001677 DEBUG(dbgs() << "Cloning "
Michael Gottesmanc189a392013-01-09 19:23:24 +00001678 << *CInst << "\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00001679 "And inserting clone at " << *InsertPos << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001680 Worklist.push_back(std::make_pair(Clone, Incoming));
1681 }
1682 }
1683 // Erase the original call.
Michael Gottesmanc189a392013-01-09 19:23:24 +00001684 DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001685 EraseInstruction(CInst);
1686 continue;
1687 }
1688 }
1689 } while (!Worklist.empty());
1690 }
1691}
1692
Michael Gottesman323964c2013-04-18 05:39:45 +00001693/// If we have a top down pointer in the S_Use state, make sure that there are
1694/// no CFG hazards by checking the states of various bottom up pointers.
1695static void CheckForUseCFGHazard(const Sequence SuccSSeq,
1696 const bool SuccSRRIKnownSafe,
1697 PtrState &S,
1698 bool &SomeSuccHasSame,
1699 bool &AllSuccsHaveSame,
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001700 bool &NotAllSeqEqualButKnownSafe,
Michael Gottesman323964c2013-04-18 05:39:45 +00001701 bool &ShouldContinue) {
1702 switch (SuccSSeq) {
1703 case S_CanRelease: {
1704 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
1705 S.ClearSequenceProgress();
1706 break;
1707 }
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001708 S.RRI.CFGHazardAfflicted = true;
Michael Gottesman323964c2013-04-18 05:39:45 +00001709 ShouldContinue = true;
1710 break;
1711 }
1712 case S_Use:
1713 SomeSuccHasSame = true;
1714 break;
1715 case S_Stop:
1716 case S_Release:
1717 case S_MovableRelease:
1718 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
1719 AllSuccsHaveSame = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001720 else
1721 NotAllSeqEqualButKnownSafe = true;
Michael Gottesman323964c2013-04-18 05:39:45 +00001722 break;
1723 case S_Retain:
1724 llvm_unreachable("bottom-up pointer in retain state!");
1725 case S_None:
1726 llvm_unreachable("This should have been handled earlier.");
1727 }
1728}
1729
1730/// If we have a Top Down pointer in the S_CanRelease state, make sure that
1731/// there are no CFG hazards by checking the states of various bottom up
1732/// pointers.
1733static void CheckForCanReleaseCFGHazard(const Sequence SuccSSeq,
1734 const bool SuccSRRIKnownSafe,
1735 PtrState &S,
1736 bool &SomeSuccHasSame,
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001737 bool &AllSuccsHaveSame,
1738 bool &NotAllSeqEqualButKnownSafe) {
Michael Gottesman323964c2013-04-18 05:39:45 +00001739 switch (SuccSSeq) {
1740 case S_CanRelease:
1741 SomeSuccHasSame = true;
1742 break;
1743 case S_Stop:
1744 case S_Release:
1745 case S_MovableRelease:
1746 case S_Use:
1747 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
1748 AllSuccsHaveSame = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001749 else
1750 NotAllSeqEqualButKnownSafe = true;
Michael Gottesman323964c2013-04-18 05:39:45 +00001751 break;
1752 case S_Retain:
1753 llvm_unreachable("bottom-up pointer in retain state!");
1754 case S_None:
1755 llvm_unreachable("This should have been handled earlier.");
1756 }
1757}
1758
Michael Gottesman97e3df02013-01-14 00:35:14 +00001759/// Check for critical edges, loop boundaries, irreducible control flow, or
1760/// other CFG structures where moving code across the edge would result in it
1761/// being executed more.
John McCalld935e9c2011-06-15 23:37:01 +00001762void
1763ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
1764 DenseMap<const BasicBlock *, BBState> &BBStates,
1765 BBState &MyStates) const {
1766 // If any top-down local-use or possible-dec has a succ which is earlier in
1767 // the sequence, forget it.
Dan Gohman55b06742012-03-02 01:13:53 +00001768 for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
Michael Gottesman323964c2013-04-18 05:39:45 +00001769 E = MyStates.top_down_ptr_end(); I != E; ++I) {
1770 PtrState &S = I->second;
1771 const Sequence Seq = I->second.GetSeq();
Dan Gohman0155f302012-02-17 18:59:53 +00001772
Michael Gottesman323964c2013-04-18 05:39:45 +00001773 // We only care about S_Retain, S_CanRelease, and S_Use.
1774 if (Seq == S_None)
1775 continue;
Dan Gohman0155f302012-02-17 18:59:53 +00001776
Michael Gottesman323964c2013-04-18 05:39:45 +00001777 // Make sure that if extra top down states are added in the future that this
1778 // code is updated to handle it.
1779 assert((Seq == S_Retain || Seq == S_CanRelease || Seq == S_Use) &&
1780 "Unknown top down sequence state.");
1781
1782 const Value *Arg = I->first;
1783 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
1784 bool SomeSuccHasSame = false;
1785 bool AllSuccsHaveSame = true;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001786 bool NotAllSeqEqualButKnownSafe = false;
Michael Gottesman323964c2013-04-18 05:39:45 +00001787
1788 succ_const_iterator SI(TI), SE(TI, false);
1789
1790 for (; SI != SE; ++SI) {
1791 // If VisitBottomUp has pointer information for this successor, take
1792 // what we know about it.
1793 const DenseMap<const BasicBlock *, BBState>::iterator BBI =
1794 BBStates.find(*SI);
1795 assert(BBI != BBStates.end());
1796 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
1797 const Sequence SuccSSeq = SuccS.GetSeq();
1798
1799 // If bottom up, the pointer is in an S_None state, clear the sequence
1800 // progress since the sequence in the bottom up state finished
1801 // suggesting a mismatch in between retains/releases. This is true for
1802 // all three cases that we are handling here: S_Retain, S_Use, and
1803 // S_CanRelease.
1804 if (SuccSSeq == S_None) {
Dan Gohman12130272011-08-12 00:26:31 +00001805 S.ClearSequenceProgress();
Michael Gottesman323964c2013-04-18 05:39:45 +00001806 continue;
1807 }
1808
1809 // If we have S_Use or S_CanRelease, perform our check for cfg hazard
1810 // checks.
1811 const bool SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
1812
1813 // *NOTE* We do not use Seq from above here since we are allowing for
1814 // S.GetSeq() to change while we are visiting basic blocks.
1815 switch(S.GetSeq()) {
1816 case S_Use: {
1817 bool ShouldContinue = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001818 CheckForUseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S, SomeSuccHasSame,
1819 AllSuccsHaveSame, NotAllSeqEqualButKnownSafe,
Michael Gottesman323964c2013-04-18 05:39:45 +00001820 ShouldContinue);
1821 if (ShouldContinue)
1822 continue;
1823 break;
1824 }
1825 case S_CanRelease: {
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001826 CheckForCanReleaseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S,
1827 SomeSuccHasSame, AllSuccsHaveSame,
1828 NotAllSeqEqualButKnownSafe);
Michael Gottesman323964c2013-04-18 05:39:45 +00001829 break;
1830 }
1831 case S_Retain:
1832 case S_None:
1833 case S_Stop:
1834 case S_Release:
1835 case S_MovableRelease:
1836 break;
1837 }
John McCalld935e9c2011-06-15 23:37:01 +00001838 }
Michael Gottesman323964c2013-04-18 05:39:45 +00001839
1840 // If the state at the other end of any of the successor edges
1841 // matches the current state, require all edges to match. This
1842 // guards against loops in the middle of a sequence.
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001843 if (SomeSuccHasSame && !AllSuccsHaveSame) {
Michael Gottesman323964c2013-04-18 05:39:45 +00001844 S.ClearSequenceProgress();
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001845 } else if (NotAllSeqEqualButKnownSafe) {
1846 // If we would have cleared the state foregoing the fact that we are known
1847 // safe, stop code motion. This is because whether or not it is safe to
1848 // remove RR pairs via KnownSafe is an orthogonal concept to whether we
1849 // are allowed to perform code motion.
1850 S.RRI.CFGHazardAfflicted = true;
1851 }
Michael Gottesman323964c2013-04-18 05:39:45 +00001852 }
John McCalld935e9c2011-06-15 23:37:01 +00001853}
1854
1855bool
Dan Gohman817a7c62012-03-22 18:24:56 +00001856ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
Dan Gohman5c70fad2012-03-23 17:47:54 +00001857 BasicBlock *BB,
Dan Gohman817a7c62012-03-22 18:24:56 +00001858 MapVector<Value *, RRInfo> &Retains,
1859 BBState &MyStates) {
1860 bool NestingDetected = false;
1861 InstructionClass Class = GetInstructionClass(Inst);
1862 const Value *Arg = 0;
Michael Gottesman79249972013-04-05 23:46:45 +00001863
Michael Gottesman1d8d2572013-04-05 22:54:28 +00001864 DEBUG(dbgs() << "Class: " << Class << "\n");
Michael Gottesman79249972013-04-05 23:46:45 +00001865
Dan Gohman817a7c62012-03-22 18:24:56 +00001866 switch (Class) {
1867 case IC_Release: {
1868 Arg = GetObjCArg(Inst);
1869
1870 PtrState &S = MyStates.getPtrBottomUpState(Arg);
1871
1872 // If we see two releases in a row on the same pointer. If so, make
1873 // a note, and we'll cicle back to revisit it after we've
1874 // hopefully eliminated the second release, which may allow us to
1875 // eliminate the first release too.
1876 // Theoretically we could implement removal of nested retain+release
1877 // pairs by making PtrState hold a stack of states, but this is
1878 // simple and avoids adding overhead for the non-nested case.
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001879 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001880 DEBUG(dbgs() << "Found nested releases (i.e. a release pair)\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00001881 NestingDetected = true;
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001882 }
Dan Gohman817a7c62012-03-22 18:24:56 +00001883
Dan Gohman817a7c62012-03-22 18:24:56 +00001884 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001885 Sequence NewSeq = ReleaseMetadata ? S_MovableRelease : S_Release;
1886 ANNOTATE_BOTTOMUP(Inst, Arg, S.GetSeq(), NewSeq);
1887 S.ResetSequenceProgress(NewSeq);
Dan Gohman817a7c62012-03-22 18:24:56 +00001888 S.RRI.ReleaseMetadata = ReleaseMetadata;
Michael Gottesman07beea42013-03-23 05:31:01 +00001889 S.RRI.KnownSafe = S.HasKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001890 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
1891 S.RRI.Calls.insert(Inst);
Dan Gohmandf476e52012-09-04 23:16:20 +00001892 S.SetKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001893 break;
1894 }
1895 case IC_RetainBlock:
Michael Gottesman158fdf62013-03-28 20:11:19 +00001896 // In OptimizeIndividualCalls, we have strength reduced all optimizable
1897 // objc_retainBlocks to objc_retains. Thus at this point any
1898 // objc_retainBlocks that we see are not optimizable.
1899 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001900 case IC_Retain:
1901 case IC_RetainRV: {
1902 Arg = GetObjCArg(Inst);
1903
1904 PtrState &S = MyStates.getPtrBottomUpState(Arg);
Dan Gohman62079b42012-04-25 00:50:46 +00001905 S.SetKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001906
Michael Gottesman81b1d432013-03-26 00:42:04 +00001907 Sequence OldSeq = S.GetSeq();
1908 switch (OldSeq) {
Dan Gohman817a7c62012-03-22 18:24:56 +00001909 case S_Stop:
1910 case S_Release:
1911 case S_MovableRelease:
1912 case S_Use:
Michael Gottesman1d8d2572013-04-05 22:54:28 +00001913 // If OldSeq is not S_Use or OldSeq is S_Use and we are tracking an
1914 // imprecise release, clear our reverse insertion points.
1915 if (OldSeq != S_Use || S.RRI.IsTrackingImpreciseReleases())
1916 S.RRI.ReverseInsertPts.clear();
Dan Gohman817a7c62012-03-22 18:24:56 +00001917 // FALL THROUGH
1918 case S_CanRelease:
1919 // Don't do retain+release tracking for IC_RetainRV, because it's
1920 // better to let it remain as the first instruction after a call.
Michael Gottesmanba648592013-03-28 23:08:44 +00001921 if (Class != IC_RetainRV)
Dan Gohman817a7c62012-03-22 18:24:56 +00001922 Retains[Inst] = S.RRI;
Dan Gohman817a7c62012-03-22 18:24:56 +00001923 S.ClearSequenceProgress();
1924 break;
1925 case S_None:
1926 break;
1927 case S_Retain:
1928 llvm_unreachable("bottom-up pointer in retain state!");
1929 }
Michael Gottesman79249972013-04-05 23:46:45 +00001930 ANNOTATE_BOTTOMUP(Inst, Arg, OldSeq, S.GetSeq());
Michael Gottesman31ba23a2013-04-05 22:54:32 +00001931 // A retain moving bottom up can be a use.
1932 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001933 }
1934 case IC_AutoreleasepoolPop:
1935 // Conservatively, clear MyStates for all known pointers.
1936 MyStates.clearBottomUpPointers();
1937 return NestingDetected;
1938 case IC_AutoreleasepoolPush:
1939 case IC_None:
1940 // These are irrelevant.
1941 return NestingDetected;
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001942 case IC_User:
1943 // If we have a store into an alloca of a pointer we are tracking, the
1944 // pointer has multiple owners implying that we must be more conservative.
1945 //
1946 // This comes up in the context of a pointer being ``KnownSafe''. In the
1947 // presense of a block being initialized, the frontend will emit the
1948 // objc_retain on the original pointer and the release on the pointer loaded
1949 // from the alloca. The optimizer will through the provenance analysis
1950 // realize that the two are related, but since we only require KnownSafe in
1951 // one direction, will match the inner retain on the original pointer with
1952 // the guard release on the original pointer. This is fixed by ensuring that
1953 // in the presense of allocas we only unconditionally remove pointers if
1954 // both our retain and our release are KnownSafe.
1955 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1956 if (AreAnyUnderlyingObjectsAnAlloca(SI->getPointerOperand())) {
1957 BBState::ptr_iterator I = MyStates.findPtrBottomUpState(
1958 StripPointerCastsAndObjCCalls(SI->getValueOperand()));
1959 if (I != MyStates.bottom_up_ptr_end())
Michael Gottesman5a91bbf2013-05-24 20:44:02 +00001960 MultiOwnersSet.insert(I->first);
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001961 }
1962 }
1963 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001964 default:
1965 break;
1966 }
1967
1968 // Consider any other possible effects of this instruction on each
1969 // pointer being tracked.
1970 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
1971 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
1972 const Value *Ptr = MI->first;
1973 if (Ptr == Arg)
1974 continue; // Handled above.
1975 PtrState &S = MI->second;
1976 Sequence Seq = S.GetSeq();
1977
1978 // Check for possible releases.
1979 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001980 DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr
1981 << "\n");
Michael Gottesman764b1cf2013-03-23 05:46:19 +00001982 S.ClearKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001983 switch (Seq) {
1984 case S_Use:
1985 S.SetSeq(S_CanRelease);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001986 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S.GetSeq());
Dan Gohman817a7c62012-03-22 18:24:56 +00001987 continue;
1988 case S_CanRelease:
1989 case S_Release:
1990 case S_MovableRelease:
1991 case S_Stop:
1992 case S_None:
1993 break;
1994 case S_Retain:
1995 llvm_unreachable("bottom-up pointer in retain state!");
1996 }
1997 }
1998
1999 // Check for possible direct uses.
2000 switch (Seq) {
2001 case S_Release:
2002 case S_MovableRelease:
2003 if (CanUse(Inst, Ptr, PA, Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002004 DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr
2005 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00002006 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohman5c70fad2012-03-23 17:47:54 +00002007 // If this is an invoke instruction, we're scanning it as part of
2008 // one of its successor blocks, since we can't insert code after it
2009 // in its own block, and we don't want to split critical edges.
2010 if (isa<InvokeInst>(Inst))
2011 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2012 else
Francois Pichet4b9ab742012-03-24 01:36:37 +00002013 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohman817a7c62012-03-22 18:24:56 +00002014 S.SetSeq(S_Use);
Michael Gottesman81b1d432013-03-26 00:42:04 +00002015 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
John McCall20182ac2013-03-22 21:38:36 +00002016 } else if (Seq == S_Release && IsUser(Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002017 DEBUG(dbgs() << "PreciseReleaseUse: Seq: " << Seq << "; " << *Ptr
2018 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00002019 // Non-movable releases depend on any possible objc pointer use.
2020 S.SetSeq(S_Stop);
Michael Gottesman81b1d432013-03-26 00:42:04 +00002021 ANNOTATE_BOTTOMUP(Inst, Ptr, S_Release, S_Stop);
Dan Gohman817a7c62012-03-22 18:24:56 +00002022 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohman5c70fad2012-03-23 17:47:54 +00002023 // As above; handle invoke specially.
2024 if (isa<InvokeInst>(Inst))
2025 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2026 else
Francois Pichet4b9ab742012-03-24 01:36:37 +00002027 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohman817a7c62012-03-22 18:24:56 +00002028 }
2029 break;
2030 case S_Stop:
Michael Gottesman81b1d432013-03-26 00:42:04 +00002031 if (CanUse(Inst, Ptr, PA, Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002032 DEBUG(dbgs() << "PreciseStopUse: Seq: " << Seq << "; " << *Ptr
2033 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00002034 S.SetSeq(S_Use);
Michael Gottesman81b1d432013-03-26 00:42:04 +00002035 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
2036 }
Dan Gohman817a7c62012-03-22 18:24:56 +00002037 break;
2038 case S_CanRelease:
2039 case S_Use:
2040 case S_None:
2041 break;
2042 case S_Retain:
2043 llvm_unreachable("bottom-up pointer in retain state!");
2044 }
2045 }
2046
2047 return NestingDetected;
2048}
2049
2050bool
John McCalld935e9c2011-06-15 23:37:01 +00002051ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2052 DenseMap<const BasicBlock *, BBState> &BBStates,
2053 MapVector<Value *, RRInfo> &Retains) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002054
2055 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitBottomUp ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00002056
John McCalld935e9c2011-06-15 23:37:01 +00002057 bool NestingDetected = false;
2058 BBState &MyStates = BBStates[BB];
2059
2060 // Merge the states from each successor to compute the initial state
2061 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00002062 BBState::edge_iterator SI(MyStates.succ_begin()),
2063 SE(MyStates.succ_end());
2064 if (SI != SE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002065 const BasicBlock *Succ = *SI;
2066 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
2067 assert(I != BBStates.end());
2068 MyStates.InitFromSucc(I->second);
2069 ++SI;
2070 for (; SI != SE; ++SI) {
2071 Succ = *SI;
2072 I = BBStates.find(Succ);
2073 assert(I != BBStates.end());
2074 MyStates.MergeSucc(I->second);
2075 }
Michael Gottesman60f6b282013-03-29 05:13:07 +00002076 }
Michael Gottesmancd4de0f2013-03-26 00:42:09 +00002077
Michael Gottesman43e7e002013-04-03 22:41:59 +00002078 // If ARC Annotations are enabled, output the current state of pointers at the
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002079 // bottom of the basic block.
Michael Gottesman43e7e002013-04-03 22:41:59 +00002080 ANNOTATE_BOTTOMUP_BBEND(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002081
John McCalld935e9c2011-06-15 23:37:01 +00002082 // Visit all the instructions, bottom-up.
2083 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2084 Instruction *Inst = llvm::prior(I);
Dan Gohman5c70fad2012-03-23 17:47:54 +00002085
2086 // Invoke instructions are visited as part of their successors (below).
2087 if (isa<InvokeInst>(Inst))
2088 continue;
2089
Michael Gottesman89279f82013-04-05 18:10:41 +00002090 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00002091
Dan Gohman5c70fad2012-03-23 17:47:54 +00002092 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
2093 }
2094
Dan Gohmandae33492012-04-27 18:56:31 +00002095 // If there's a predecessor with an invoke, visit the invoke as if it were
2096 // part of this block, since we can't insert code after an invoke in its own
2097 // block, and we don't want to split critical edges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002098 for (BBState::edge_iterator PI(MyStates.pred_begin()),
2099 PE(MyStates.pred_end()); PI != PE; ++PI) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00002100 BasicBlock *Pred = *PI;
Dan Gohmandae33492012-04-27 18:56:31 +00002101 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
2102 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
Dan Gohman817a7c62012-03-22 18:24:56 +00002103 }
John McCalld935e9c2011-06-15 23:37:01 +00002104
Michael Gottesman43e7e002013-04-03 22:41:59 +00002105 // If ARC Annotations are enabled, output the current state of pointers at the
2106 // top of the basic block.
2107 ANNOTATE_BOTTOMUP_BBSTART(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002108
Dan Gohman817a7c62012-03-22 18:24:56 +00002109 return NestingDetected;
2110}
John McCalld935e9c2011-06-15 23:37:01 +00002111
Dan Gohman817a7c62012-03-22 18:24:56 +00002112bool
2113ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
2114 DenseMap<Value *, RRInfo> &Releases,
2115 BBState &MyStates) {
2116 bool NestingDetected = false;
2117 InstructionClass Class = GetInstructionClass(Inst);
2118 const Value *Arg = 0;
John McCalld935e9c2011-06-15 23:37:01 +00002119
Dan Gohman817a7c62012-03-22 18:24:56 +00002120 switch (Class) {
2121 case IC_RetainBlock:
Michael Gottesman158fdf62013-03-28 20:11:19 +00002122 // In OptimizeIndividualCalls, we have strength reduced all optimizable
2123 // objc_retainBlocks to objc_retains. Thus at this point any
2124 // objc_retainBlocks that we see are not optimizable.
2125 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00002126 case IC_Retain:
2127 case IC_RetainRV: {
2128 Arg = GetObjCArg(Inst);
2129
2130 PtrState &S = MyStates.getPtrTopDownState(Arg);
2131
2132 // Don't do retain+release tracking for IC_RetainRV, because it's
2133 // better to let it remain as the first instruction after a call.
2134 if (Class != IC_RetainRV) {
2135 // If we see two retains in a row on the same pointer. If so, make
John McCalld935e9c2011-06-15 23:37:01 +00002136 // a note, and we'll cicle back to revisit it after we've
Dan Gohman817a7c62012-03-22 18:24:56 +00002137 // hopefully eliminated the second retain, which may allow us to
2138 // eliminate the first retain too.
John McCalld935e9c2011-06-15 23:37:01 +00002139 // Theoretically we could implement removal of nested retain+release
2140 // pairs by making PtrState hold a stack of states, but this is
2141 // simple and avoids adding overhead for the non-nested case.
Dan Gohman817a7c62012-03-22 18:24:56 +00002142 if (S.GetSeq() == S_Retain)
John McCalld935e9c2011-06-15 23:37:01 +00002143 NestingDetected = true;
2144
Michael Gottesman81b1d432013-03-26 00:42:04 +00002145 ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_Retain);
Dan Gohman62079b42012-04-25 00:50:46 +00002146 S.ResetSequenceProgress(S_Retain);
Michael Gottesman07beea42013-03-23 05:31:01 +00002147 S.RRI.KnownSafe = S.HasKnownPositiveRefCount();
John McCalld935e9c2011-06-15 23:37:01 +00002148 S.RRI.Calls.insert(Inst);
John McCalld935e9c2011-06-15 23:37:01 +00002149 }
John McCalld935e9c2011-06-15 23:37:01 +00002150
Dan Gohmandf476e52012-09-04 23:16:20 +00002151 S.SetKnownPositiveRefCount();
Dan Gohmanf64ff8e2012-07-23 19:27:31 +00002152
2153 // A retain can be a potential use; procede to the generic checking
2154 // code below.
2155 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00002156 }
2157 case IC_Release: {
2158 Arg = GetObjCArg(Inst);
2159
2160 PtrState &S = MyStates.getPtrTopDownState(Arg);
Michael Gottesman764b1cf2013-03-23 05:46:19 +00002161 S.ClearKnownPositiveRefCount();
Michael Gottesman79249972013-04-05 23:46:45 +00002162
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002163 Sequence OldSeq = S.GetSeq();
Michael Gottesman79249972013-04-05 23:46:45 +00002164
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002165 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
Michael Gottesman79249972013-04-05 23:46:45 +00002166
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002167 switch (OldSeq) {
Dan Gohman817a7c62012-03-22 18:24:56 +00002168 case S_Retain:
2169 case S_CanRelease:
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002170 if (OldSeq == S_Retain || ReleaseMetadata != 0)
2171 S.RRI.ReverseInsertPts.clear();
Dan Gohman817a7c62012-03-22 18:24:56 +00002172 // FALL THROUGH
2173 case S_Use:
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002174 S.RRI.ReleaseMetadata = ReleaseMetadata;
Dan Gohman817a7c62012-03-22 18:24:56 +00002175 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2176 Releases[Inst] = S.RRI;
Michael Gottesman81b1d432013-03-26 00:42:04 +00002177 ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_None);
Dan Gohman817a7c62012-03-22 18:24:56 +00002178 S.ClearSequenceProgress();
2179 break;
2180 case S_None:
2181 break;
2182 case S_Stop:
2183 case S_Release:
2184 case S_MovableRelease:
2185 llvm_unreachable("top-down pointer in release state!");
2186 }
2187 break;
2188 }
2189 case IC_AutoreleasepoolPop:
2190 // Conservatively, clear MyStates for all known pointers.
2191 MyStates.clearTopDownPointers();
2192 return NestingDetected;
2193 case IC_AutoreleasepoolPush:
2194 case IC_None:
2195 // These are irrelevant.
2196 return NestingDetected;
2197 default:
2198 break;
2199 }
2200
2201 // Consider any other possible effects of this instruction on each
2202 // pointer being tracked.
2203 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
2204 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
2205 const Value *Ptr = MI->first;
2206 if (Ptr == Arg)
2207 continue; // Handled above.
2208 PtrState &S = MI->second;
2209 Sequence Seq = S.GetSeq();
2210
2211 // Check for possible releases.
2212 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Michael Gottesmanbab49e972013-04-05 18:26:08 +00002213 DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr
Michael Gottesman79249972013-04-05 23:46:45 +00002214 << "\n");
Michael Gottesman764b1cf2013-03-23 05:46:19 +00002215 S.ClearKnownPositiveRefCount();
John McCalld935e9c2011-06-15 23:37:01 +00002216 switch (Seq) {
Dan Gohman817a7c62012-03-22 18:24:56 +00002217 case S_Retain:
2218 S.SetSeq(S_CanRelease);
Michael Gottesman81b1d432013-03-26 00:42:04 +00002219 ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_CanRelease);
Dan Gohman817a7c62012-03-22 18:24:56 +00002220 assert(S.RRI.ReverseInsertPts.empty());
2221 S.RRI.ReverseInsertPts.insert(Inst);
2222
2223 // One call can't cause a transition from S_Retain to S_CanRelease
2224 // and S_CanRelease to S_Use. If we've made the first transition,
2225 // we're done.
2226 continue;
John McCalld935e9c2011-06-15 23:37:01 +00002227 case S_Use:
Dan Gohman817a7c62012-03-22 18:24:56 +00002228 case S_CanRelease:
John McCalld935e9c2011-06-15 23:37:01 +00002229 case S_None:
2230 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00002231 case S_Stop:
2232 case S_Release:
2233 case S_MovableRelease:
2234 llvm_unreachable("top-down pointer in release state!");
John McCalld935e9c2011-06-15 23:37:01 +00002235 }
2236 }
Dan Gohman817a7c62012-03-22 18:24:56 +00002237
2238 // Check for possible direct uses.
2239 switch (Seq) {
2240 case S_CanRelease:
Michael Gottesman81b1d432013-03-26 00:42:04 +00002241 if (CanUse(Inst, Ptr, PA, Class)) {
Michael Gottesmanbab49e972013-04-05 18:26:08 +00002242 DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr
2243 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00002244 S.SetSeq(S_Use);
Michael Gottesman81b1d432013-03-26 00:42:04 +00002245 ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_Use);
2246 }
Dan Gohman817a7c62012-03-22 18:24:56 +00002247 break;
2248 case S_Retain:
2249 case S_Use:
2250 case S_None:
2251 break;
2252 case S_Stop:
2253 case S_Release:
2254 case S_MovableRelease:
2255 llvm_unreachable("top-down pointer in release state!");
2256 }
John McCalld935e9c2011-06-15 23:37:01 +00002257 }
2258
2259 return NestingDetected;
2260}
2261
2262bool
2263ObjCARCOpt::VisitTopDown(BasicBlock *BB,
2264 DenseMap<const BasicBlock *, BBState> &BBStates,
2265 DenseMap<Value *, RRInfo> &Releases) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002266 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitTopDown ==\n");
John McCalld935e9c2011-06-15 23:37:01 +00002267 bool NestingDetected = false;
2268 BBState &MyStates = BBStates[BB];
2269
2270 // Merge the states from each predecessor to compute the initial state
2271 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00002272 BBState::edge_iterator PI(MyStates.pred_begin()),
2273 PE(MyStates.pred_end());
2274 if (PI != PE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002275 const BasicBlock *Pred = *PI;
2276 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
2277 assert(I != BBStates.end());
2278 MyStates.InitFromPred(I->second);
2279 ++PI;
2280 for (; PI != PE; ++PI) {
2281 Pred = *PI;
2282 I = BBStates.find(Pred);
2283 assert(I != BBStates.end());
2284 MyStates.MergePred(I->second);
2285 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002286 }
John McCalld935e9c2011-06-15 23:37:01 +00002287
Michael Gottesman43e7e002013-04-03 22:41:59 +00002288 // If ARC Annotations are enabled, output the current state of pointers at the
2289 // top of the basic block.
2290 ANNOTATE_TOPDOWN_BBSTART(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002291
John McCalld935e9c2011-06-15 23:37:01 +00002292 // Visit all the instructions, top-down.
2293 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2294 Instruction *Inst = I;
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00002295
Michael Gottesman89279f82013-04-05 18:10:41 +00002296 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00002297
Dan Gohman817a7c62012-03-22 18:24:56 +00002298 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00002299 }
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002300
Michael Gottesman43e7e002013-04-03 22:41:59 +00002301 // If ARC Annotations are enabled, output the current state of pointers at the
2302 // bottom of the basic block.
2303 ANNOTATE_TOPDOWN_BBEND(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002304
Michael Gottesmanffef24f2013-04-17 20:48:01 +00002305#ifdef ARC_ANNOTATIONS
Michael Gottesmanadb921a2013-04-17 21:03:53 +00002306 if (!(EnableARCAnnotations && DisableCheckForCFGHazards))
Michael Gottesmanffef24f2013-04-17 20:48:01 +00002307#endif
John McCalld935e9c2011-06-15 23:37:01 +00002308 CheckForCFGHazards(BB, BBStates, MyStates);
2309 return NestingDetected;
2310}
2311
Dan Gohmana53a12c2011-12-12 19:42:25 +00002312static void
2313ComputePostOrders(Function &F,
2314 SmallVectorImpl<BasicBlock *> &PostOrder,
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002315 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
2316 unsigned NoObjCARCExceptionsMDKind,
2317 DenseMap<const BasicBlock *, BBState> &BBStates) {
Michael Gottesman97e3df02013-01-14 00:35:14 +00002318 /// The visited set, for doing DFS walks.
Dan Gohmana53a12c2011-12-12 19:42:25 +00002319 SmallPtrSet<BasicBlock *, 16> Visited;
2320
2321 // Do DFS, computing the PostOrder.
2322 SmallPtrSet<BasicBlock *, 16> OnStack;
2323 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002324
2325 // Functions always have exactly one entry block, and we don't have
2326 // any other block that we treat like an entry block.
Dan Gohmana53a12c2011-12-12 19:42:25 +00002327 BasicBlock *EntryBB = &F.getEntryBlock();
Dan Gohman41375a32012-05-08 23:39:44 +00002328 BBState &MyStates = BBStates[EntryBB];
2329 MyStates.SetAsEntry();
2330 TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
2331 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
Dan Gohmana53a12c2011-12-12 19:42:25 +00002332 Visited.insert(EntryBB);
2333 OnStack.insert(EntryBB);
2334 do {
2335 dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002336 BasicBlock *CurrBB = SuccStack.back().first;
2337 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
2338 succ_iterator SE(TI, false);
Dan Gohman41375a32012-05-08 23:39:44 +00002339
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002340 while (SuccStack.back().second != SE) {
2341 BasicBlock *SuccBB = *SuccStack.back().second++;
2342 if (Visited.insert(SuccBB)) {
Dan Gohman41375a32012-05-08 23:39:44 +00002343 TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
2344 SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002345 BBStates[CurrBB].addSucc(SuccBB);
Dan Gohman41375a32012-05-08 23:39:44 +00002346 BBState &SuccStates = BBStates[SuccBB];
2347 SuccStates.addPred(CurrBB);
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002348 OnStack.insert(SuccBB);
Dan Gohmana53a12c2011-12-12 19:42:25 +00002349 goto dfs_next_succ;
2350 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002351
2352 if (!OnStack.count(SuccBB)) {
2353 BBStates[CurrBB].addSucc(SuccBB);
2354 BBStates[SuccBB].addPred(CurrBB);
2355 }
Dan Gohmana53a12c2011-12-12 19:42:25 +00002356 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002357 OnStack.erase(CurrBB);
2358 PostOrder.push_back(CurrBB);
2359 SuccStack.pop_back();
Dan Gohmana53a12c2011-12-12 19:42:25 +00002360 } while (!SuccStack.empty());
2361
2362 Visited.clear();
2363
Dan Gohmana53a12c2011-12-12 19:42:25 +00002364 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002365 // Functions may have many exits, and there also blocks which we treat
2366 // as exits due to ignored edges.
2367 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
2368 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
2369 BasicBlock *ExitBB = I;
2370 BBState &MyStates = BBStates[ExitBB];
2371 if (!MyStates.isExit())
2372 continue;
2373
Dan Gohmandae33492012-04-27 18:56:31 +00002374 MyStates.SetAsExit();
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002375
2376 PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00002377 Visited.insert(ExitBB);
2378 while (!PredStack.empty()) {
2379 reverse_dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002380 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
2381 while (PredStack.back().second != PE) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00002382 BasicBlock *BB = *PredStack.back().second++;
Dan Gohmana53a12c2011-12-12 19:42:25 +00002383 if (Visited.insert(BB)) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002384 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00002385 goto reverse_dfs_next_succ;
2386 }
2387 }
2388 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
2389 }
2390 }
2391}
2392
Michael Gottesman97e3df02013-01-14 00:35:14 +00002393// Visit the function both top-down and bottom-up.
John McCalld935e9c2011-06-15 23:37:01 +00002394bool
2395ObjCARCOpt::Visit(Function &F,
2396 DenseMap<const BasicBlock *, BBState> &BBStates,
2397 MapVector<Value *, RRInfo> &Retains,
2398 DenseMap<Value *, RRInfo> &Releases) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00002399
2400 // Use reverse-postorder traversals, because we magically know that loops
2401 // will be well behaved, i.e. they won't repeatedly call retain on a single
2402 // pointer without doing a release. We can't use the ReversePostOrderTraversal
2403 // class here because we want the reverse-CFG postorder to consider each
2404 // function exit point, and we want to ignore selected cycle edges.
2405 SmallVector<BasicBlock *, 16> PostOrder;
2406 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002407 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
2408 NoObjCARCExceptionsMDKind,
2409 BBStates);
Dan Gohmana53a12c2011-12-12 19:42:25 +00002410
2411 // Use reverse-postorder on the reverse CFG for bottom-up.
John McCalld935e9c2011-06-15 23:37:01 +00002412 bool BottomUpNestingDetected = false;
Dan Gohmanc57b58c2011-08-18 21:27:42 +00002413 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
Dan Gohmana53a12c2011-12-12 19:42:25 +00002414 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
2415 I != E; ++I)
2416 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
John McCalld935e9c2011-06-15 23:37:01 +00002417
Dan Gohmana53a12c2011-12-12 19:42:25 +00002418 // Use reverse-postorder for top-down.
John McCalld935e9c2011-06-15 23:37:01 +00002419 bool TopDownNestingDetected = false;
Dan Gohmana53a12c2011-12-12 19:42:25 +00002420 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2421 PostOrder.rbegin(), E = PostOrder.rend();
2422 I != E; ++I)
2423 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
John McCalld935e9c2011-06-15 23:37:01 +00002424
2425 return TopDownNestingDetected && BottomUpNestingDetected;
2426}
2427
Michael Gottesman97e3df02013-01-14 00:35:14 +00002428/// Move the calls in RetainsToMove and ReleasesToMove.
John McCalld935e9c2011-06-15 23:37:01 +00002429void ObjCARCOpt::MoveCalls(Value *Arg,
2430 RRInfo &RetainsToMove,
2431 RRInfo &ReleasesToMove,
2432 MapVector<Value *, RRInfo> &Retains,
2433 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman6320f522011-07-22 22:29:21 +00002434 SmallVectorImpl<Instruction *> &DeadInsts,
Michael Gottesman79249972013-04-05 23:46:45 +00002435 Module *M) {
Chris Lattner229907c2011-07-18 04:54:35 +00002436 Type *ArgTy = Arg->getType();
Dan Gohman6320f522011-07-22 22:29:21 +00002437 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
Michael Gottesman79249972013-04-05 23:46:45 +00002438
Michael Gottesman89279f82013-04-05 18:10:41 +00002439 DEBUG(dbgs() << "== ObjCARCOpt::MoveCalls ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00002440
John McCalld935e9c2011-06-15 23:37:01 +00002441 // Insert the new retain and release calls.
2442 for (SmallPtrSet<Instruction *, 2>::const_iterator
2443 PI = ReleasesToMove.ReverseInsertPts.begin(),
2444 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2445 Instruction *InsertPt = *PI;
2446 Value *MyArg = ArgTy == ParamTy ? Arg :
2447 new BitCastInst(Arg, ParamTy, "", InsertPt);
2448 CallInst *Call =
Michael Gottesmanba648592013-03-28 23:08:44 +00002449 CallInst::Create(getRetainCallee(M), MyArg, "", InsertPt);
John McCalld935e9c2011-06-15 23:37:01 +00002450 Call->setDoesNotThrow();
Michael Gottesmanba648592013-03-28 23:08:44 +00002451 Call->setTailCall();
Michael Gottesman60f6b282013-03-29 05:13:07 +00002452
Michael Gottesmandf110ac2013-04-21 00:30:50 +00002453 DEBUG(dbgs() << "Inserting new Retain: " << *Call << "\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00002454 "At insertion point: " << *InsertPt << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002455 }
2456 for (SmallPtrSet<Instruction *, 2>::const_iterator
2457 PI = RetainsToMove.ReverseInsertPts.begin(),
2458 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00002459 Instruction *InsertPt = *PI;
2460 Value *MyArg = ArgTy == ParamTy ? Arg :
2461 new BitCastInst(Arg, ParamTy, "", InsertPt);
2462 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
2463 "", InsertPt);
2464 // Attach a clang.imprecise_release metadata tag, if appropriate.
2465 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
2466 Call->setMetadata(ImpreciseReleaseMDKind, M);
2467 Call->setDoesNotThrow();
2468 if (ReleasesToMove.IsTailCallRelease)
2469 Call->setTailCall();
Michael Gottesmanc189a392013-01-09 19:23:24 +00002470
Michael Gottesman89279f82013-04-05 18:10:41 +00002471 DEBUG(dbgs() << "Inserting new Release: " << *Call << "\n"
2472 "At insertion point: " << *InsertPt << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002473 }
2474
2475 // Delete the original retain and release calls.
2476 for (SmallPtrSet<Instruction *, 2>::const_iterator
2477 AI = RetainsToMove.Calls.begin(),
2478 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
2479 Instruction *OrigRetain = *AI;
2480 Retains.blot(OrigRetain);
2481 DeadInsts.push_back(OrigRetain);
Michael Gottesman89279f82013-04-05 18:10:41 +00002482 DEBUG(dbgs() << "Deleting retain: " << *OrigRetain << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002483 }
2484 for (SmallPtrSet<Instruction *, 2>::const_iterator
2485 AI = ReleasesToMove.Calls.begin(),
2486 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
2487 Instruction *OrigRelease = *AI;
2488 Releases.erase(OrigRelease);
2489 DeadInsts.push_back(OrigRelease);
Michael Gottesman89279f82013-04-05 18:10:41 +00002490 DEBUG(dbgs() << "Deleting release: " << *OrigRelease << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002491 }
Michael Gottesman79249972013-04-05 23:46:45 +00002492
John McCalld935e9c2011-06-15 23:37:01 +00002493}
2494
Michael Gottesman9de6f962013-01-22 21:49:00 +00002495bool
2496ObjCARCOpt::ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState>
2497 &BBStates,
2498 MapVector<Value *, RRInfo> &Retains,
2499 DenseMap<Value *, RRInfo> &Releases,
2500 Module *M,
2501 SmallVector<Instruction *, 4> &NewRetains,
2502 SmallVector<Instruction *, 4> &NewReleases,
2503 SmallVector<Instruction *, 8> &DeadInsts,
2504 RRInfo &RetainsToMove,
2505 RRInfo &ReleasesToMove,
2506 Value *Arg,
2507 bool KnownSafe,
2508 bool &AnyPairsCompletelyEliminated) {
2509 // If a pair happens in a region where it is known that the reference count
Michael Gottesmana76143ee2013-05-13 23:49:42 +00002510 // is already incremented, we can similarly ignore possible decrements unless
2511 // we are dealing with a retainable object with multiple provenance sources.
Michael Gottesman9de6f962013-01-22 21:49:00 +00002512 bool KnownSafeTD = true, KnownSafeBU = true;
Michael Gottesmana76143ee2013-05-13 23:49:42 +00002513 bool MultipleOwners = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00002514 bool CFGHazardAfflicted = false;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002515
2516 // Connect the dots between the top-down-collected RetainsToMove and
2517 // bottom-up-collected ReleasesToMove to form sets of related calls.
2518 // This is an iterative process so that we connect multiple releases
2519 // to multiple retains if needed.
2520 unsigned OldDelta = 0;
2521 unsigned NewDelta = 0;
2522 unsigned OldCount = 0;
2523 unsigned NewCount = 0;
2524 bool FirstRelease = true;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002525 for (;;) {
2526 for (SmallVectorImpl<Instruction *>::const_iterator
2527 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
2528 Instruction *NewRetain = *NI;
2529 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
2530 assert(It != Retains.end());
2531 const RRInfo &NewRetainRRI = It->second;
2532 KnownSafeTD &= NewRetainRRI.KnownSafe;
Michael Gottesman5a91bbf2013-05-24 20:44:02 +00002533 MultipleOwners =
2534 MultipleOwners || MultiOwnersSet.count(GetObjCArg(NewRetain));
Michael Gottesman9de6f962013-01-22 21:49:00 +00002535 for (SmallPtrSet<Instruction *, 2>::const_iterator
2536 LI = NewRetainRRI.Calls.begin(),
2537 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
2538 Instruction *NewRetainRelease = *LI;
2539 DenseMap<Value *, RRInfo>::const_iterator Jt =
2540 Releases.find(NewRetainRelease);
2541 if (Jt == Releases.end())
2542 return false;
2543 const RRInfo &NewRetainReleaseRRI = Jt->second;
2544 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
2545 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
2546 OldDelta -=
2547 BBStates[NewRetainRelease->getParent()].GetAllPathCount();
2548
2549 // Merge the ReleaseMetadata and IsTailCallRelease values.
2550 if (FirstRelease) {
2551 ReleasesToMove.ReleaseMetadata =
2552 NewRetainReleaseRRI.ReleaseMetadata;
2553 ReleasesToMove.IsTailCallRelease =
2554 NewRetainReleaseRRI.IsTailCallRelease;
2555 FirstRelease = false;
2556 } else {
2557 if (ReleasesToMove.ReleaseMetadata !=
2558 NewRetainReleaseRRI.ReleaseMetadata)
2559 ReleasesToMove.ReleaseMetadata = 0;
2560 if (ReleasesToMove.IsTailCallRelease !=
2561 NewRetainReleaseRRI.IsTailCallRelease)
2562 ReleasesToMove.IsTailCallRelease = false;
2563 }
2564
2565 // Collect the optimal insertion points.
2566 if (!KnownSafe)
2567 for (SmallPtrSet<Instruction *, 2>::const_iterator
2568 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
2569 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
2570 RI != RE; ++RI) {
2571 Instruction *RIP = *RI;
2572 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
2573 NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
2574 }
2575 NewReleases.push_back(NewRetainRelease);
2576 }
2577 }
2578 }
2579 NewRetains.clear();
2580 if (NewReleases.empty()) break;
2581
2582 // Back the other way.
2583 for (SmallVectorImpl<Instruction *>::const_iterator
2584 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
2585 Instruction *NewRelease = *NI;
2586 DenseMap<Value *, RRInfo>::const_iterator It =
2587 Releases.find(NewRelease);
2588 assert(It != Releases.end());
2589 const RRInfo &NewReleaseRRI = It->second;
2590 KnownSafeBU &= NewReleaseRRI.KnownSafe;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00002591 CFGHazardAfflicted |= NewReleaseRRI.CFGHazardAfflicted;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002592 for (SmallPtrSet<Instruction *, 2>::const_iterator
2593 LI = NewReleaseRRI.Calls.begin(),
2594 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
2595 Instruction *NewReleaseRetain = *LI;
2596 MapVector<Value *, RRInfo>::const_iterator Jt =
2597 Retains.find(NewReleaseRetain);
2598 if (Jt == Retains.end())
2599 return false;
2600 const RRInfo &NewReleaseRetainRRI = Jt->second;
2601 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
2602 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
2603 unsigned PathCount =
2604 BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
2605 OldDelta += PathCount;
2606 OldCount += PathCount;
2607
Michael Gottesman9de6f962013-01-22 21:49:00 +00002608 // Collect the optimal insertion points.
2609 if (!KnownSafe)
2610 for (SmallPtrSet<Instruction *, 2>::const_iterator
2611 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
2612 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
2613 RI != RE; ++RI) {
2614 Instruction *RIP = *RI;
2615 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
2616 PathCount = BBStates[RIP->getParent()].GetAllPathCount();
2617 NewDelta += PathCount;
2618 NewCount += PathCount;
2619 }
2620 }
2621 NewRetains.push_back(NewReleaseRetain);
2622 }
2623 }
2624 }
2625 NewReleases.clear();
2626 if (NewRetains.empty()) break;
2627 }
2628
Michael Gottesmana76143ee2013-05-13 23:49:42 +00002629 // If the pointer is known incremented in 1 direction and we do not have
2630 // MultipleOwners, we can safely remove the retain/releases. Otherwise we need
2631 // to be known safe in both directions.
2632 bool UnconditionallySafe = (KnownSafeTD && KnownSafeBU) ||
2633 ((KnownSafeTD || KnownSafeBU) && !MultipleOwners);
2634 if (UnconditionallySafe) {
Michael Gottesman9de6f962013-01-22 21:49:00 +00002635 RetainsToMove.ReverseInsertPts.clear();
2636 ReleasesToMove.ReverseInsertPts.clear();
2637 NewCount = 0;
2638 } else {
2639 // Determine whether the new insertion points we computed preserve the
2640 // balance of retain and release calls through the program.
2641 // TODO: If the fully aggressive solution isn't valid, try to find a
2642 // less aggressive solution which is.
2643 if (NewDelta != 0)
2644 return false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00002645
2646 // At this point, we are not going to remove any RR pairs, but we still are
2647 // able to move RR pairs. If one of our pointers is afflicted with
2648 // CFGHazards, we cannot perform such code motion so exit early.
2649 const bool WillPerformCodeMotion = RetainsToMove.ReverseInsertPts.size() ||
2650 ReleasesToMove.ReverseInsertPts.size();
2651 if (CFGHazardAfflicted && WillPerformCodeMotion)
2652 return false;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002653 }
2654
2655 // Determine whether the original call points are balanced in the retain and
2656 // release calls through the program. If not, conservatively don't touch
2657 // them.
2658 // TODO: It's theoretically possible to do code motion in this case, as
2659 // long as the existing imbalances are maintained.
2660 if (OldDelta != 0)
2661 return false;
Michael Gottesman8005ad32013-04-29 06:16:55 +00002662
Michael Gottesmana87bb8f2013-04-29 05:13:13 +00002663#ifdef ARC_ANNOTATIONS
2664 // Do not move calls if ARC annotations are requested.
Michael Gottesman3e3977c2013-04-29 05:25:39 +00002665 if (EnableARCAnnotations)
2666 return false;
Michael Gottesmana87bb8f2013-04-29 05:13:13 +00002667#endif // ARC_ANNOTATIONS
Michael Gottesman9de6f962013-01-22 21:49:00 +00002668
2669 Changed = true;
2670 assert(OldCount != 0 && "Unreachable code?");
2671 NumRRs += OldCount - NewCount;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002672 // Set to true if we completely removed any RR pairs.
Michael Gottesman8b5515f2013-01-22 21:53:43 +00002673 AnyPairsCompletelyEliminated = NewCount == 0;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002674
2675 // We can move calls!
2676 return true;
2677}
2678
Michael Gottesman97e3df02013-01-14 00:35:14 +00002679/// Identify pairings between the retains and releases, and delete and/or move
2680/// them.
John McCalld935e9c2011-06-15 23:37:01 +00002681bool
2682ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
2683 &BBStates,
2684 MapVector<Value *, RRInfo> &Retains,
Dan Gohman6320f522011-07-22 22:29:21 +00002685 DenseMap<Value *, RRInfo> &Releases,
2686 Module *M) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002687 DEBUG(dbgs() << "\n== ObjCARCOpt::PerformCodePlacement ==\n");
2688
John McCalld935e9c2011-06-15 23:37:01 +00002689 bool AnyPairsCompletelyEliminated = false;
2690 RRInfo RetainsToMove;
2691 RRInfo ReleasesToMove;
2692 SmallVector<Instruction *, 4> NewRetains;
2693 SmallVector<Instruction *, 4> NewReleases;
2694 SmallVector<Instruction *, 8> DeadInsts;
2695
Dan Gohman670f9372012-04-13 18:57:48 +00002696 // Visit each retain.
John McCalld935e9c2011-06-15 23:37:01 +00002697 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
Dan Gohman2053a5d2011-09-29 22:25:23 +00002698 E = Retains.end(); I != E; ++I) {
2699 Value *V = I->first;
John McCalld935e9c2011-06-15 23:37:01 +00002700 if (!V) continue; // blotted
2701
2702 Instruction *Retain = cast<Instruction>(V);
Michael Gottesmanc189a392013-01-09 19:23:24 +00002703
Michael Gottesman89279f82013-04-05 18:10:41 +00002704 DEBUG(dbgs() << "Visiting: " << *Retain << "\n");
Michael Gottesmanc189a392013-01-09 19:23:24 +00002705
John McCalld935e9c2011-06-15 23:37:01 +00002706 Value *Arg = GetObjCArg(Retain);
2707
Dan Gohman728db492012-01-13 00:39:07 +00002708 // If the object being released is in static or stack storage, we know it's
John McCalld935e9c2011-06-15 23:37:01 +00002709 // not being managed by ObjC reference counting, so we can delete pairs
2710 // regardless of what possible decrements or uses lie between them.
Dan Gohman728db492012-01-13 00:39:07 +00002711 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
Dan Gohman41375a32012-05-08 23:39:44 +00002712
Dan Gohman56e1cef2011-08-22 17:29:11 +00002713 // A constant pointer can't be pointing to an object on the heap. It may
2714 // be reference-counted, but it won't be deleted.
2715 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
2716 if (const GlobalVariable *GV =
2717 dyn_cast<GlobalVariable>(
2718 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
2719 if (GV->isConstant())
2720 KnownSafe = true;
2721
John McCalld935e9c2011-06-15 23:37:01 +00002722 // Connect the dots between the top-down-collected RetainsToMove and
2723 // bottom-up-collected ReleasesToMove to form sets of related calls.
John McCalld935e9c2011-06-15 23:37:01 +00002724 NewRetains.push_back(Retain);
Michael Gottesman9de6f962013-01-22 21:49:00 +00002725 bool PerformMoveCalls =
2726 ConnectTDBUTraversals(BBStates, Retains, Releases, M, NewRetains,
2727 NewReleases, DeadInsts, RetainsToMove,
2728 ReleasesToMove, Arg, KnownSafe,
2729 AnyPairsCompletelyEliminated);
John McCalld935e9c2011-06-15 23:37:01 +00002730
Michael Gottesman9de6f962013-01-22 21:49:00 +00002731 if (PerformMoveCalls) {
2732 // Ok, everything checks out and we're all set. Let's move/delete some
2733 // code!
2734 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
2735 Retains, Releases, DeadInsts, M);
John McCalld935e9c2011-06-15 23:37:01 +00002736 }
2737
Michael Gottesman9de6f962013-01-22 21:49:00 +00002738 // Clean up state for next retain.
John McCalld935e9c2011-06-15 23:37:01 +00002739 NewReleases.clear();
2740 NewRetains.clear();
2741 RetainsToMove.clear();
2742 ReleasesToMove.clear();
2743 }
2744
2745 // Now that we're done moving everything, we can delete the newly dead
2746 // instructions, as we no longer need them as insert points.
2747 while (!DeadInsts.empty())
2748 EraseInstruction(DeadInsts.pop_back_val());
2749
2750 return AnyPairsCompletelyEliminated;
2751}
2752
Michael Gottesman97e3df02013-01-14 00:35:14 +00002753/// Weak pointer optimizations.
John McCalld935e9c2011-06-15 23:37:01 +00002754void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002755 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeWeakCalls ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00002756
John McCalld935e9c2011-06-15 23:37:01 +00002757 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
2758 // itself because it uses AliasAnalysis and we need to do provenance
2759 // queries instead.
2760 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2761 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +00002762
Michael Gottesman89279f82013-04-05 18:10:41 +00002763 DEBUG(dbgs() << "Visiting: " << *Inst << "\n");
Michael Gottesman3f146e22013-01-01 16:05:48 +00002764
John McCalld935e9c2011-06-15 23:37:01 +00002765 InstructionClass Class = GetBasicInstructionClass(Inst);
2766 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
2767 continue;
2768
2769 // Delete objc_loadWeak calls with no users.
2770 if (Class == IC_LoadWeak && Inst->use_empty()) {
2771 Inst->eraseFromParent();
2772 continue;
2773 }
2774
2775 // TODO: For now, just look for an earlier available version of this value
2776 // within the same block. Theoretically, we could do memdep-style non-local
2777 // analysis too, but that would want caching. A better approach would be to
2778 // use the technique that EarlyCSE uses.
2779 inst_iterator Current = llvm::prior(I);
2780 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
2781 for (BasicBlock::iterator B = CurrentBB->begin(),
2782 J = Current.getInstructionIterator();
2783 J != B; --J) {
2784 Instruction *EarlierInst = &*llvm::prior(J);
2785 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
2786 switch (EarlierClass) {
2787 case IC_LoadWeak:
2788 case IC_LoadWeakRetained: {
2789 // If this is loading from the same pointer, replace this load's value
2790 // with that one.
2791 CallInst *Call = cast<CallInst>(Inst);
2792 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2793 Value *Arg = Call->getArgOperand(0);
2794 Value *EarlierArg = EarlierCall->getArgOperand(0);
2795 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2796 case AliasAnalysis::MustAlias:
2797 Changed = true;
2798 // If the load has a builtin retain, insert a plain retain for it.
2799 if (Class == IC_LoadWeakRetained) {
2800 CallInst *CI =
2801 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
2802 "", Call);
2803 CI->setTailCall();
2804 }
2805 // Zap the fully redundant load.
2806 Call->replaceAllUsesWith(EarlierCall);
2807 Call->eraseFromParent();
2808 goto clobbered;
2809 case AliasAnalysis::MayAlias:
2810 case AliasAnalysis::PartialAlias:
2811 goto clobbered;
2812 case AliasAnalysis::NoAlias:
2813 break;
2814 }
2815 break;
2816 }
2817 case IC_StoreWeak:
2818 case IC_InitWeak: {
2819 // If this is storing to the same pointer and has the same size etc.
2820 // replace this load's value with the stored value.
2821 CallInst *Call = cast<CallInst>(Inst);
2822 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2823 Value *Arg = Call->getArgOperand(0);
2824 Value *EarlierArg = EarlierCall->getArgOperand(0);
2825 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2826 case AliasAnalysis::MustAlias:
2827 Changed = true;
2828 // If the load has a builtin retain, insert a plain retain for it.
2829 if (Class == IC_LoadWeakRetained) {
2830 CallInst *CI =
2831 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
2832 "", Call);
2833 CI->setTailCall();
2834 }
2835 // Zap the fully redundant load.
2836 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
2837 Call->eraseFromParent();
2838 goto clobbered;
2839 case AliasAnalysis::MayAlias:
2840 case AliasAnalysis::PartialAlias:
2841 goto clobbered;
2842 case AliasAnalysis::NoAlias:
2843 break;
2844 }
2845 break;
2846 }
2847 case IC_MoveWeak:
2848 case IC_CopyWeak:
2849 // TOOD: Grab the copied value.
2850 goto clobbered;
2851 case IC_AutoreleasepoolPush:
2852 case IC_None:
John McCall20182ac2013-03-22 21:38:36 +00002853 case IC_IntrinsicUser:
John McCalld935e9c2011-06-15 23:37:01 +00002854 case IC_User:
2855 // Weak pointers are only modified through the weak entry points
2856 // (and arbitrary calls, which could call the weak entry points).
2857 break;
2858 default:
2859 // Anything else could modify the weak pointer.
2860 goto clobbered;
2861 }
2862 }
2863 clobbered:;
2864 }
2865
2866 // Then, for each destroyWeak with an alloca operand, check to see if
2867 // the alloca and all its users can be zapped.
2868 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2869 Instruction *Inst = &*I++;
2870 InstructionClass Class = GetBasicInstructionClass(Inst);
2871 if (Class != IC_DestroyWeak)
2872 continue;
2873
2874 CallInst *Call = cast<CallInst>(Inst);
2875 Value *Arg = Call->getArgOperand(0);
2876 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
2877 for (Value::use_iterator UI = Alloca->use_begin(),
2878 UE = Alloca->use_end(); UI != UE; ++UI) {
Dan Gohmandae33492012-04-27 18:56:31 +00002879 const Instruction *UserInst = cast<Instruction>(*UI);
John McCalld935e9c2011-06-15 23:37:01 +00002880 switch (GetBasicInstructionClass(UserInst)) {
2881 case IC_InitWeak:
2882 case IC_StoreWeak:
2883 case IC_DestroyWeak:
2884 continue;
2885 default:
2886 goto done;
2887 }
2888 }
2889 Changed = true;
2890 for (Value::use_iterator UI = Alloca->use_begin(),
2891 UE = Alloca->use_end(); UI != UE; ) {
2892 CallInst *UserInst = cast<CallInst>(*UI++);
Dan Gohman14862c32012-05-18 22:17:29 +00002893 switch (GetBasicInstructionClass(UserInst)) {
2894 case IC_InitWeak:
2895 case IC_StoreWeak:
2896 // These functions return their second argument.
2897 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
2898 break;
2899 case IC_DestroyWeak:
2900 // No return value.
2901 break;
2902 default:
Dan Gohman9c97eea02012-05-21 17:41:28 +00002903 llvm_unreachable("alloca really is used!");
Dan Gohman14862c32012-05-18 22:17:29 +00002904 }
John McCalld935e9c2011-06-15 23:37:01 +00002905 UserInst->eraseFromParent();
2906 }
2907 Alloca->eraseFromParent();
2908 done:;
2909 }
2910 }
2911}
2912
Michael Gottesman97e3df02013-01-14 00:35:14 +00002913/// Identify program paths which execute sequences of retains and releases which
2914/// can be eliminated.
John McCalld935e9c2011-06-15 23:37:01 +00002915bool ObjCARCOpt::OptimizeSequences(Function &F) {
Michael Gottesman740db972013-05-23 02:35:21 +00002916 // Releases, Retains - These are used to store the results of the main flow
2917 // analysis. These use Value* as the key instead of Instruction* so that the
2918 // map stays valid when we get around to rewriting code and calls get
2919 // replaced by arguments.
John McCalld935e9c2011-06-15 23:37:01 +00002920 DenseMap<Value *, RRInfo> Releases;
2921 MapVector<Value *, RRInfo> Retains;
2922
Michael Gottesman740db972013-05-23 02:35:21 +00002923 // This is used during the traversal of the function to track the
2924 // states for each identified object at each block.
John McCalld935e9c2011-06-15 23:37:01 +00002925 DenseMap<const BasicBlock *, BBState> BBStates;
2926
2927 // Analyze the CFG of the function, and all instructions.
2928 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
2929
2930 // Transform.
Michael Gottesman5a91bbf2013-05-24 20:44:02 +00002931 bool AnyPairsCompletelyEliminated = PerformCodePlacement(BBStates, Retains,
2932 Releases,
2933 F.getParent());
2934
2935 // Cleanup.
2936 MultiOwnersSet.clear();
2937
2938 return AnyPairsCompletelyEliminated && NestingDetected;
John McCalld935e9c2011-06-15 23:37:01 +00002939}
2940
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002941/// Check if there is a dependent call earlier that does not have anything in
2942/// between the Retain and the call that can affect the reference count of their
2943/// shared pointer argument. Note that Retain need not be in BB.
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002944static bool
2945HasSafePathToPredecessorCall(const Value *Arg, Instruction *Retain,
2946 SmallPtrSet<Instruction *, 4> &DepInsts,
2947 SmallPtrSet<const BasicBlock *, 4> &Visited,
2948 ProvenanceAnalysis &PA) {
2949 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
2950 DepInsts, Visited, PA);
2951 if (DepInsts.size() != 1)
2952 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002953
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002954 CallInst *Call =
2955 dyn_cast_or_null<CallInst>(*DepInsts.begin());
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002956
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002957 // Check that the pointer is the return value of the call.
2958 if (!Call || Arg != Call)
2959 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002960
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002961 // Check that the call is a regular call.
2962 InstructionClass Class = GetBasicInstructionClass(Call);
2963 if (Class != IC_CallOrUser && Class != IC_Call)
2964 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002965
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002966 return true;
2967}
2968
Michael Gottesman6908db12013-04-03 23:16:05 +00002969/// Find a dependent retain that precedes the given autorelease for which there
2970/// is nothing in between the two instructions that can affect the ref count of
2971/// Arg.
2972static CallInst *
2973FindPredecessorRetainWithSafePath(const Value *Arg, BasicBlock *BB,
2974 Instruction *Autorelease,
2975 SmallPtrSet<Instruction *, 4> &DepInsts,
2976 SmallPtrSet<const BasicBlock *, 4> &Visited,
2977 ProvenanceAnalysis &PA) {
2978 FindDependencies(CanChangeRetainCount, Arg,
2979 BB, Autorelease, DepInsts, Visited, PA);
2980 if (DepInsts.size() != 1)
2981 return 0;
Michael Gottesman79249972013-04-05 23:46:45 +00002982
Michael Gottesman6908db12013-04-03 23:16:05 +00002983 CallInst *Retain =
2984 dyn_cast_or_null<CallInst>(*DepInsts.begin());
Michael Gottesman79249972013-04-05 23:46:45 +00002985
Michael Gottesman6908db12013-04-03 23:16:05 +00002986 // Check that we found a retain with the same argument.
2987 if (!Retain ||
2988 !IsRetain(GetBasicInstructionClass(Retain)) ||
2989 GetObjCArg(Retain) != Arg) {
2990 return 0;
2991 }
Michael Gottesman79249972013-04-05 23:46:45 +00002992
Michael Gottesman6908db12013-04-03 23:16:05 +00002993 return Retain;
2994}
2995
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002996/// Look for an ``autorelease'' instruction dependent on Arg such that there are
2997/// no instructions dependent on Arg that need a positive ref count in between
2998/// the autorelease and the ret.
2999static CallInst *
3000FindPredecessorAutoreleaseWithSafePath(const Value *Arg, BasicBlock *BB,
3001 ReturnInst *Ret,
3002 SmallPtrSet<Instruction *, 4> &DepInsts,
3003 SmallPtrSet<const BasicBlock *, 4> &V,
3004 ProvenanceAnalysis &PA) {
3005 FindDependencies(NeedsPositiveRetainCount, Arg,
3006 BB, Ret, DepInsts, V, PA);
3007 if (DepInsts.size() != 1)
3008 return 0;
Michael Gottesman79249972013-04-05 23:46:45 +00003009
Michael Gottesman21a4ed32013-04-03 23:39:14 +00003010 CallInst *Autorelease =
3011 dyn_cast_or_null<CallInst>(*DepInsts.begin());
3012 if (!Autorelease)
3013 return 0;
3014 InstructionClass AutoreleaseClass = GetBasicInstructionClass(Autorelease);
3015 if (!IsAutorelease(AutoreleaseClass))
3016 return 0;
3017 if (GetObjCArg(Autorelease) != Arg)
3018 return 0;
Michael Gottesman79249972013-04-05 23:46:45 +00003019
Michael Gottesman21a4ed32013-04-03 23:39:14 +00003020 return Autorelease;
3021}
3022
Michael Gottesman97e3df02013-01-14 00:35:14 +00003023/// Look for this pattern:
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00003024/// \code
John McCalld935e9c2011-06-15 23:37:01 +00003025/// %call = call i8* @something(...)
3026/// %2 = call i8* @objc_retain(i8* %call)
3027/// %3 = call i8* @objc_autorelease(i8* %2)
3028/// ret i8* %3
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00003029/// \endcode
John McCalld935e9c2011-06-15 23:37:01 +00003030/// And delete the retain and autorelease.
John McCalld935e9c2011-06-15 23:37:01 +00003031void ObjCARCOpt::OptimizeReturns(Function &F) {
3032 if (!F.getReturnType()->isPointerTy())
3033 return;
Michael Gottesman79249972013-04-05 23:46:45 +00003034
Michael Gottesman89279f82013-04-05 18:10:41 +00003035 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeReturns ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00003036
John McCalld935e9c2011-06-15 23:37:01 +00003037 SmallPtrSet<Instruction *, 4> DependingInstructions;
3038 SmallPtrSet<const BasicBlock *, 4> Visited;
3039 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3040 BasicBlock *BB = FI;
3041 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
Michael Gottesman3f146e22013-01-01 16:05:48 +00003042
Michael Gottesman89279f82013-04-05 18:10:41 +00003043 DEBUG(dbgs() << "Visiting: " << *Ret << "\n");
Michael Gottesman3f146e22013-01-01 16:05:48 +00003044
Michael Gottesman21a4ed32013-04-03 23:39:14 +00003045 if (!Ret)
3046 continue;
Michael Gottesman79249972013-04-05 23:46:45 +00003047
John McCalld935e9c2011-06-15 23:37:01 +00003048 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
Michael Gottesman79249972013-04-05 23:46:45 +00003049
Michael Gottesmancdb7c152013-04-21 00:25:04 +00003050 // Look for an ``autorelease'' instruction that is a predecessor of Ret and
Michael Gottesman21a4ed32013-04-03 23:39:14 +00003051 // dependent on Arg such that there are no instructions dependent on Arg
3052 // that need a positive ref count in between the autorelease and Ret.
3053 CallInst *Autorelease =
3054 FindPredecessorAutoreleaseWithSafePath(Arg, BB, Ret,
3055 DependingInstructions, Visited,
3056 PA);
John McCalld935e9c2011-06-15 23:37:01 +00003057 DependingInstructions.clear();
3058 Visited.clear();
Michael Gottesmanfb9ece92013-04-21 00:25:01 +00003059
3060 if (!Autorelease)
3061 continue;
3062
3063 CallInst *Retain =
3064 FindPredecessorRetainWithSafePath(Arg, BB, Autorelease,
3065 DependingInstructions, Visited, PA);
3066 DependingInstructions.clear();
3067 Visited.clear();
3068
3069 if (!Retain)
3070 continue;
3071
3072 // Check that there is nothing that can affect the reference count
3073 // between the retain and the call. Note that Retain need not be in BB.
3074 bool HasSafePathToCall = HasSafePathToPredecessorCall(Arg, Retain,
3075 DependingInstructions,
3076 Visited, PA);
3077 DependingInstructions.clear();
3078 Visited.clear();
3079
3080 if (!HasSafePathToCall)
3081 continue;
3082
3083 // If so, we can zap the retain and autorelease.
3084 Changed = true;
3085 ++NumRets;
3086 DEBUG(dbgs() << "Erasing: " << *Retain << "\nErasing: "
3087 << *Autorelease << "\n");
3088 EraseInstruction(Retain);
3089 EraseInstruction(Autorelease);
John McCalld935e9c2011-06-15 23:37:01 +00003090 }
3091}
3092
Michael Gottesman9c118152013-04-29 06:16:57 +00003093#ifndef NDEBUG
3094void
3095ObjCARCOpt::GatherStatistics(Function &F, bool AfterOptimization) {
3096 llvm::Statistic &NumRetains =
3097 AfterOptimization? NumRetainsAfterOpt : NumRetainsBeforeOpt;
3098 llvm::Statistic &NumReleases =
3099 AfterOptimization? NumReleasesAfterOpt : NumReleasesBeforeOpt;
3100
3101 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3102 Instruction *Inst = &*I++;
3103 switch (GetBasicInstructionClass(Inst)) {
3104 default:
3105 break;
3106 case IC_Retain:
3107 ++NumRetains;
3108 break;
3109 case IC_Release:
3110 ++NumReleases;
3111 break;
3112 }
3113 }
3114}
3115#endif
3116
John McCalld935e9c2011-06-15 23:37:01 +00003117bool ObjCARCOpt::doInitialization(Module &M) {
3118 if (!EnableARCOpts)
3119 return false;
3120
Dan Gohman670f9372012-04-13 18:57:48 +00003121 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanceaac7c2011-06-20 23:20:43 +00003122 Run = ModuleHasARC(M);
3123 if (!Run)
3124 return false;
3125
John McCalld935e9c2011-06-15 23:37:01 +00003126 // Identify the imprecise release metadata kind.
3127 ImpreciseReleaseMDKind =
3128 M.getContext().getMDKindID("clang.imprecise_release");
Dan Gohmana7107f92011-10-17 22:53:25 +00003129 CopyOnEscapeMDKind =
3130 M.getContext().getMDKindID("clang.arc.copy_on_escape");
Dan Gohman0155f302012-02-17 18:59:53 +00003131 NoObjCARCExceptionsMDKind =
3132 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
Michael Gottesman81b1d432013-03-26 00:42:04 +00003133#ifdef ARC_ANNOTATIONS
3134 ARCAnnotationBottomUpMDKind =
3135 M.getContext().getMDKindID("llvm.arc.annotation.bottomup");
3136 ARCAnnotationTopDownMDKind =
3137 M.getContext().getMDKindID("llvm.arc.annotation.topdown");
3138 ARCAnnotationProvenanceSourceMDKind =
3139 M.getContext().getMDKindID("llvm.arc.annotation.provenancesource");
3140#endif // ARC_ANNOTATIONS
John McCalld935e9c2011-06-15 23:37:01 +00003141
John McCalld935e9c2011-06-15 23:37:01 +00003142 // Intuitively, objc_retain and others are nocapture, however in practice
3143 // they are not, because they return their argument value. And objc_release
Dan Gohmandae33492012-04-27 18:56:31 +00003144 // calls finalizers which can have arbitrary side effects.
John McCalld935e9c2011-06-15 23:37:01 +00003145
3146 // These are initialized lazily.
John McCalld935e9c2011-06-15 23:37:01 +00003147 AutoreleaseRVCallee = 0;
3148 ReleaseCallee = 0;
3149 RetainCallee = 0;
Dan Gohman6320f522011-07-22 22:29:21 +00003150 RetainBlockCallee = 0;
John McCalld935e9c2011-06-15 23:37:01 +00003151 AutoreleaseCallee = 0;
3152
3153 return false;
3154}
3155
3156bool ObjCARCOpt::runOnFunction(Function &F) {
3157 if (!EnableARCOpts)
3158 return false;
3159
Dan Gohmanceaac7c2011-06-20 23:20:43 +00003160 // If nothing in the Module uses ARC, don't do anything.
3161 if (!Run)
3162 return false;
3163
John McCalld935e9c2011-06-15 23:37:01 +00003164 Changed = false;
3165
Michael Gottesman89279f82013-04-05 18:10:41 +00003166 DEBUG(dbgs() << "<<< ObjCARCOpt: Visiting Function: " << F.getName() << " >>>"
3167 "\n");
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00003168
John McCalld935e9c2011-06-15 23:37:01 +00003169 PA.setAA(&getAnalysis<AliasAnalysis>());
3170
Michael Gottesman9fc50b82013-05-13 18:29:07 +00003171#ifndef NDEBUG
3172 if (AreStatisticsEnabled()) {
3173 GatherStatistics(F, false);
3174 }
3175#endif
3176
John McCalld935e9c2011-06-15 23:37:01 +00003177 // This pass performs several distinct transformations. As a compile-time aid
3178 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3179 // library functions aren't declared.
3180
Michael Gottesmancd5b0272013-04-24 22:18:15 +00003181 // Preliminary optimizations. This also computes UsedInThisFunction.
John McCalld935e9c2011-06-15 23:37:01 +00003182 OptimizeIndividualCalls(F);
3183
3184 // Optimizations for weak pointers.
3185 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3186 (1 << IC_LoadWeakRetained) |
3187 (1 << IC_StoreWeak) |
3188 (1 << IC_InitWeak) |
3189 (1 << IC_CopyWeak) |
3190 (1 << IC_MoveWeak) |
3191 (1 << IC_DestroyWeak)))
3192 OptimizeWeakCalls(F);
3193
3194 // Optimizations for retain+release pairs.
3195 if (UsedInThisFunction & ((1 << IC_Retain) |
3196 (1 << IC_RetainRV) |
3197 (1 << IC_RetainBlock)))
3198 if (UsedInThisFunction & (1 << IC_Release))
3199 // Run OptimizeSequences until it either stops making changes or
3200 // no retain+release pair nesting is detected.
3201 while (OptimizeSequences(F)) {}
3202
3203 // Optimizations if objc_autorelease is used.
Dan Gohman41375a32012-05-08 23:39:44 +00003204 if (UsedInThisFunction & ((1 << IC_Autorelease) |
3205 (1 << IC_AutoreleaseRV)))
John McCalld935e9c2011-06-15 23:37:01 +00003206 OptimizeReturns(F);
3207
Michael Gottesman9c118152013-04-29 06:16:57 +00003208 // Gather statistics after optimization.
3209#ifndef NDEBUG
3210 if (AreStatisticsEnabled()) {
3211 GatherStatistics(F, true);
3212 }
3213#endif
3214
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00003215 DEBUG(dbgs() << "\n");
3216
John McCalld935e9c2011-06-15 23:37:01 +00003217 return Changed;
3218}
3219
3220void ObjCARCOpt::releaseMemory() {
3221 PA.clear();
3222}
3223
Michael Gottesman97e3df02013-01-14 00:35:14 +00003224/// @}
3225///