blob: 0385de5095e9c96ad021c7b85e680da7d5a66379 [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 Gottesman14acfac2013-07-06 01:39:23 +000029#include "ARCRuntimeEntryPoints.h"
Michael Gottesman278266f2013-01-29 04:20:52 +000030#include "DependencyAnalysis.h"
Michael Gottesman294e7da2013-01-28 05:51:54 +000031#include "ObjCARCAliasAnalysis.h"
Michael Gottesman778138e2013-01-29 03:03:03 +000032#include "ProvenanceAnalysis.h"
John McCalld935e9c2011-06-15 23:37:01 +000033#include "llvm/ADT/DenseMap.h"
Michael Gottesman5a91bbf2013-05-24 20:44:02 +000034#include "llvm/ADT/DenseSet.h"
Michael Gottesmanfa0939f2013-01-28 04:12:07 +000035#include "llvm/ADT/STLExtras.h"
Michael Gottesman778138e2013-01-29 03:03:03 +000036#include "llvm/ADT/SmallPtrSet.h"
Michael Gottesman278266f2013-01-29 04:20:52 +000037#include "llvm/ADT/Statistic.h"
Michael Gottesmancd4de0f2013-03-26 00:42:09 +000038#include "llvm/IR/IRBuilder.h"
Michael Gottesman278266f2013-01-29 04:20:52 +000039#include "llvm/IR/LLVMContext.h"
Michael Gottesman778138e2013-01-29 03:03:03 +000040#include "llvm/Support/CFG.h"
Michael Gottesman13a5f1a2013-01-29 04:51:59 +000041#include "llvm/Support/Debug.h"
Timur Iskhodzhanov5d7ff002013-01-29 09:09:27 +000042#include "llvm/Support/raw_ostream.h"
Michael Gottesmanfa0939f2013-01-28 04:12:07 +000043
John McCalld935e9c2011-06-15 23:37:01 +000044using namespace llvm;
Michael Gottesman08904e32013-01-28 03:28:38 +000045using namespace llvm::objcarc;
John McCalld935e9c2011-06-15 23:37:01 +000046
Michael Gottesman97e3df02013-01-14 00:35:14 +000047/// \defgroup MiscUtils Miscellaneous utilities that are not ARC specific.
48/// @{
John McCalld935e9c2011-06-15 23:37:01 +000049
50namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +000051 /// \brief An associative container with fast insertion-order (deterministic)
52 /// iteration over its elements. Plus the special blot operation.
John McCalld935e9c2011-06-15 23:37:01 +000053 template<class KeyT, class ValueT>
54 class MapVector {
Michael Gottesman97e3df02013-01-14 00:35:14 +000055 /// Map keys to indices in Vector.
John McCalld935e9c2011-06-15 23:37:01 +000056 typedef DenseMap<KeyT, size_t> MapTy;
57 MapTy Map;
58
John McCalld935e9c2011-06-15 23:37:01 +000059 typedef std::vector<std::pair<KeyT, ValueT> > VectorTy;
Michael Gottesman97e3df02013-01-14 00:35:14 +000060 /// Keys and values.
John McCalld935e9c2011-06-15 23:37:01 +000061 VectorTy Vector;
62
63 public:
64 typedef typename VectorTy::iterator iterator;
65 typedef typename VectorTy::const_iterator const_iterator;
66 iterator begin() { return Vector.begin(); }
67 iterator end() { return Vector.end(); }
68 const_iterator begin() const { return Vector.begin(); }
69 const_iterator end() const { return Vector.end(); }
70
71#ifdef XDEBUG
72 ~MapVector() {
73 assert(Vector.size() >= Map.size()); // May differ due to blotting.
74 for (typename MapTy::const_iterator I = Map.begin(), E = Map.end();
75 I != E; ++I) {
76 assert(I->second < Vector.size());
77 assert(Vector[I->second].first == I->first);
78 }
79 for (typename VectorTy::const_iterator I = Vector.begin(),
80 E = Vector.end(); I != E; ++I)
81 assert(!I->first ||
82 (Map.count(I->first) &&
83 Map[I->first] == size_t(I - Vector.begin())));
84 }
85#endif
86
Dan Gohman55b06742012-03-02 01:13:53 +000087 ValueT &operator[](const KeyT &Arg) {
John McCalld935e9c2011-06-15 23:37:01 +000088 std::pair<typename MapTy::iterator, bool> Pair =
89 Map.insert(std::make_pair(Arg, size_t(0)));
90 if (Pair.second) {
Dan Gohman55b06742012-03-02 01:13:53 +000091 size_t Num = Vector.size();
92 Pair.first->second = Num;
John McCalld935e9c2011-06-15 23:37:01 +000093 Vector.push_back(std::make_pair(Arg, ValueT()));
Dan Gohman55b06742012-03-02 01:13:53 +000094 return Vector[Num].second;
John McCalld935e9c2011-06-15 23:37:01 +000095 }
96 return Vector[Pair.first->second].second;
97 }
98
99 std::pair<iterator, bool>
100 insert(const std::pair<KeyT, ValueT> &InsertPair) {
101 std::pair<typename MapTy::iterator, bool> Pair =
102 Map.insert(std::make_pair(InsertPair.first, size_t(0)));
103 if (Pair.second) {
Dan Gohman55b06742012-03-02 01:13:53 +0000104 size_t Num = Vector.size();
105 Pair.first->second = Num;
John McCalld935e9c2011-06-15 23:37:01 +0000106 Vector.push_back(InsertPair);
Dan Gohman55b06742012-03-02 01:13:53 +0000107 return std::make_pair(Vector.begin() + Num, true);
John McCalld935e9c2011-06-15 23:37:01 +0000108 }
109 return std::make_pair(Vector.begin() + Pair.first->second, false);
110 }
111
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000112 iterator find(const KeyT &Key) {
113 typename MapTy::iterator It = Map.find(Key);
114 if (It == Map.end()) return Vector.end();
115 return Vector.begin() + It->second;
116 }
117
Dan Gohman55b06742012-03-02 01:13:53 +0000118 const_iterator find(const KeyT &Key) const {
John McCalld935e9c2011-06-15 23:37:01 +0000119 typename MapTy::const_iterator It = Map.find(Key);
120 if (It == Map.end()) return Vector.end();
121 return Vector.begin() + It->second;
122 }
123
Michael Gottesman97e3df02013-01-14 00:35:14 +0000124 /// This is similar to erase, but instead of removing the element from the
125 /// vector, it just zeros out the key in the vector. This leaves iterators
126 /// intact, but clients must be prepared for zeroed-out keys when iterating.
Dan Gohman55b06742012-03-02 01:13:53 +0000127 void blot(const KeyT &Key) {
John McCalld935e9c2011-06-15 23:37:01 +0000128 typename MapTy::iterator It = Map.find(Key);
129 if (It == Map.end()) return;
130 Vector[It->second].first = KeyT();
131 Map.erase(It);
132 }
133
134 void clear() {
135 Map.clear();
136 Vector.clear();
137 }
138 };
139}
140
Michael Gottesman97e3df02013-01-14 00:35:14 +0000141/// @}
142///
143/// \defgroup ARCUtilities Utility declarations/definitions specific to ARC.
144/// @{
John McCalld935e9c2011-06-15 23:37:01 +0000145
Michael Gottesman97e3df02013-01-14 00:35:14 +0000146/// \brief This is similar to StripPointerCastsAndObjCCalls but it stops as soon
147/// as it finds a value with multiple uses.
John McCalld935e9c2011-06-15 23:37:01 +0000148static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
149 if (Arg->hasOneUse()) {
150 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
151 return FindSingleUseIdentifiedObject(BC->getOperand(0));
152 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
153 if (GEP->hasAllZeroIndices())
154 return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
155 if (IsForwarding(GetBasicInstructionClass(Arg)))
156 return FindSingleUseIdentifiedObject(
157 cast<CallInst>(Arg)->getArgOperand(0));
158 if (!IsObjCIdentifiedObject(Arg))
159 return 0;
160 return Arg;
161 }
162
Dan Gohman41375a32012-05-08 23:39:44 +0000163 // If we found an identifiable object but it has multiple uses, but they are
164 // trivial uses, we can still consider this to be a single-use value.
John McCalld935e9c2011-06-15 23:37:01 +0000165 if (IsObjCIdentifiedObject(Arg)) {
166 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
167 UI != UE; ++UI) {
168 const User *U = *UI;
169 if (!U->use_empty() || StripPointerCastsAndObjCCalls(U) != Arg)
170 return 0;
171 }
172
173 return Arg;
174 }
175
176 return 0;
177}
178
Michael Gottesman774d2c02013-01-29 21:00:52 +0000179/// \brief Test whether the given retainable object pointer escapes.
Michael Gottesman97e3df02013-01-14 00:35:14 +0000180///
181/// This differs from regular escape analysis in that a use as an
182/// argument to a call is not considered an escape.
183///
Michael Gottesman774d2c02013-01-29 21:00:52 +0000184static bool DoesRetainableObjPtrEscape(const User *Ptr) {
Michael Gottesman774d2c02013-01-29 21:00:52 +0000185 DEBUG(dbgs() << "DoesRetainableObjPtrEscape: Target: " << *Ptr << "\n");
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000186
Dan Gohman728db492012-01-13 00:39:07 +0000187 // Walk the def-use chains.
188 SmallVector<const Value *, 4> Worklist;
Michael Gottesman774d2c02013-01-29 21:00:52 +0000189 Worklist.push_back(Ptr);
190 // If Ptr has any operands add them as well.
Michael Gottesman23cda0c2013-01-29 21:07:53 +0000191 for (User::const_op_iterator I = Ptr->op_begin(), E = Ptr->op_end(); I != E;
192 ++I) {
Michael Gottesman774d2c02013-01-29 21:00:52 +0000193 Worklist.push_back(*I);
194 }
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000195
196 // Ensure we do not visit any value twice.
Michael Gottesman774d2c02013-01-29 21:00:52 +0000197 SmallPtrSet<const Value *, 8> VisitedSet;
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000198
Dan Gohman728db492012-01-13 00:39:07 +0000199 do {
200 const Value *V = Worklist.pop_back_val();
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000201
Michael Gottesman89279f82013-04-05 18:10:41 +0000202 DEBUG(dbgs() << "Visiting: " << *V << "\n");
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000203
Dan Gohman728db492012-01-13 00:39:07 +0000204 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
205 UI != UE; ++UI) {
206 const User *UUser = *UI;
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000207
Michael Gottesman89279f82013-04-05 18:10:41 +0000208 DEBUG(dbgs() << "User: " << *UUser << "\n");
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000209
Dan Gohman728db492012-01-13 00:39:07 +0000210 // Special - Use by a call (callee or argument) is not considered
211 // to be an escape.
Dan Gohmane1e352a2012-04-13 18:28:58 +0000212 switch (GetBasicInstructionClass(UUser)) {
213 case IC_StoreWeak:
214 case IC_InitWeak:
215 case IC_StoreStrong:
216 case IC_Autorelease:
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000217 case IC_AutoreleaseRV: {
Michael Gottesman89279f82013-04-05 18:10:41 +0000218 DEBUG(dbgs() << "User copies pointer arguments. Pointer Escapes!\n");
Dan Gohmane1e352a2012-04-13 18:28:58 +0000219 // These special functions make copies of their pointer arguments.
220 return true;
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000221 }
John McCall20182ac2013-03-22 21:38:36 +0000222 case IC_IntrinsicUser:
223 // Use by the use intrinsic is not an escape.
224 continue;
Dan Gohmane1e352a2012-04-13 18:28:58 +0000225 case IC_User:
226 case IC_None:
227 // Use by an instruction which copies the value is an escape if the
228 // result is an escape.
229 if (isa<BitCastInst>(UUser) || isa<GetElementPtrInst>(UUser) ||
230 isa<PHINode>(UUser) || isa<SelectInst>(UUser)) {
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000231
Michael Gottesmanf4b77612013-02-23 00:31:32 +0000232 if (VisitedSet.insert(UUser)) {
Michael Gottesman89279f82013-04-05 18:10:41 +0000233 DEBUG(dbgs() << "User copies value. Ptr escapes if result escapes."
234 " Adding to list.\n");
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000235 Worklist.push_back(UUser);
236 } else {
Michael Gottesman89279f82013-04-05 18:10:41 +0000237 DEBUG(dbgs() << "Already visited node.\n");
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000238 }
Dan Gohmane1e352a2012-04-13 18:28:58 +0000239 continue;
240 }
241 // Use by a load is not an escape.
242 if (isa<LoadInst>(UUser))
243 continue;
244 // Use by a store is not an escape if the use is the address.
245 if (const StoreInst *SI = dyn_cast<StoreInst>(UUser))
246 if (V != SI->getValueOperand())
247 continue;
248 break;
249 default:
250 // Regular calls and other stuff are not considered escapes.
Dan Gohman728db492012-01-13 00:39:07 +0000251 continue;
252 }
Dan Gohmaneb6e0152012-02-13 22:57:02 +0000253 // Otherwise, conservatively assume an escape.
Michael Gottesman89279f82013-04-05 18:10:41 +0000254 DEBUG(dbgs() << "Assuming ptr escapes.\n");
Dan Gohman728db492012-01-13 00:39:07 +0000255 return true;
256 }
257 } while (!Worklist.empty());
258
259 // No escapes found.
Michael Gottesman89279f82013-04-05 18:10:41 +0000260 DEBUG(dbgs() << "Ptr does not escape.\n");
Dan Gohman728db492012-01-13 00:39:07 +0000261 return false;
262}
263
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000264/// This is a wrapper around getUnderlyingObjCPtr along the lines of
265/// GetUnderlyingObjects except that it returns early when it sees the first
266/// alloca.
267static inline bool AreAnyUnderlyingObjectsAnAlloca(const Value *V) {
268 SmallPtrSet<const Value *, 4> Visited;
269 SmallVector<const Value *, 4> Worklist;
270 Worklist.push_back(V);
271 do {
272 const Value *P = Worklist.pop_back_val();
273 P = GetUnderlyingObjCPtr(P);
Michael Gottesman0c8b5622013-05-14 06:40:10 +0000274
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000275 if (isa<AllocaInst>(P))
276 return true;
Michael Gottesman0c8b5622013-05-14 06:40:10 +0000277
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000278 if (!Visited.insert(P))
279 continue;
Michael Gottesman0c8b5622013-05-14 06:40:10 +0000280
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000281 if (const SelectInst *SI = dyn_cast<const SelectInst>(P)) {
282 Worklist.push_back(SI->getTrueValue());
283 Worklist.push_back(SI->getFalseValue());
284 continue;
285 }
Michael Gottesman0c8b5622013-05-14 06:40:10 +0000286
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000287 if (const PHINode *PN = dyn_cast<const PHINode>(P)) {
288 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
289 Worklist.push_back(PN->getIncomingValue(i));
290 continue;
291 }
292 } while (!Worklist.empty());
293
294 return false;
295}
296
297
Michael Gottesman97e3df02013-01-14 00:35:14 +0000298/// @}
299///
Michael Gottesman97e3df02013-01-14 00:35:14 +0000300/// \defgroup ARCOpt ARC Optimization.
301/// @{
John McCalld935e9c2011-06-15 23:37:01 +0000302
303// TODO: On code like this:
304//
305// objc_retain(%x)
306// stuff_that_cannot_release()
307// objc_autorelease(%x)
308// stuff_that_cannot_release()
309// objc_retain(%x)
310// stuff_that_cannot_release()
311// objc_autorelease(%x)
312//
313// The second retain and autorelease can be deleted.
314
315// TODO: It should be possible to delete
316// objc_autoreleasePoolPush and objc_autoreleasePoolPop
317// pairs if nothing is actually autoreleased between them. Also, autorelease
318// calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
319// after inlining) can be turned into plain release calls.
320
321// TODO: Critical-edge splitting. If the optimial insertion point is
322// a critical edge, the current algorithm has to fail, because it doesn't
323// know how to split edges. It should be possible to make the optimizer
324// think in terms of edges, rather than blocks, and then split critical
325// edges on demand.
326
327// TODO: OptimizeSequences could generalized to be Interprocedural.
328
329// TODO: Recognize that a bunch of other objc runtime calls have
330// non-escaping arguments and non-releasing arguments, and may be
331// non-autoreleasing.
332
333// TODO: Sink autorelease calls as far as possible. Unfortunately we
334// usually can't sink them past other calls, which would be the main
335// case where it would be useful.
336
Dan Gohmanb3894012011-08-19 00:26:36 +0000337// TODO: The pointer returned from objc_loadWeakRetained is retained.
338
339// TODO: Delete release+retain pairs (rare).
Dan Gohmanceaac7c2011-06-20 23:20:43 +0000340
John McCalld935e9c2011-06-15 23:37:01 +0000341STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
342STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
343STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
344STATISTIC(NumRets, "Number of return value forwarding "
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000345 "retain+autoreleases eliminated");
John McCalld935e9c2011-06-15 23:37:01 +0000346STATISTIC(NumRRs, "Number of retain+release paths eliminated");
347STATISTIC(NumPeeps, "Number of calls peephole-optimized");
Matt Beaumont-Gaye55d9492013-05-13 21:10:49 +0000348#ifndef NDEBUG
Michael Gottesman9c118152013-04-29 06:16:57 +0000349STATISTIC(NumRetainsBeforeOpt,
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000350 "Number of retains before optimization");
Michael Gottesman9c118152013-04-29 06:16:57 +0000351STATISTIC(NumReleasesBeforeOpt,
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000352 "Number of releases before optimization");
Michael Gottesman9c118152013-04-29 06:16:57 +0000353STATISTIC(NumRetainsAfterOpt,
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000354 "Number of retains after optimization");
Michael Gottesman9c118152013-04-29 06:16:57 +0000355STATISTIC(NumReleasesAfterOpt,
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000356 "Number of releases after optimization");
Michael Gottesman03cf3c82013-04-29 07:29:08 +0000357#endif
John McCalld935e9c2011-06-15 23:37:01 +0000358
359namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000360 /// \enum Sequence
361 ///
362 /// \brief A sequence of states that a pointer may go through in which an
363 /// objc_retain and objc_release are actually needed.
John McCalld935e9c2011-06-15 23:37:01 +0000364 enum Sequence {
365 S_None,
Michael Gottesman53fd20b2013-01-29 21:07:51 +0000366 S_Retain, ///< objc_retain(x).
367 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement.
368 S_Use, ///< any use of x.
Michael Gottesman386241c2013-01-29 21:39:02 +0000369 S_Stop, ///< like S_Release, but code motion is stopped.
Michael Gottesman53fd20b2013-01-29 21:07:51 +0000370 S_Release, ///< objc_release(x).
Michael Gottesman9bdab2b2013-01-29 21:41:44 +0000371 S_MovableRelease ///< objc_release(x), !clang.imprecise_release.
John McCalld935e9c2011-06-15 23:37:01 +0000372 };
Michael Gottesman53fd20b2013-01-29 21:07:51 +0000373
374 raw_ostream &operator<<(raw_ostream &OS, const Sequence S)
375 LLVM_ATTRIBUTE_UNUSED;
376 raw_ostream &operator<<(raw_ostream &OS, const Sequence S) {
377 switch (S) {
378 case S_None:
379 return OS << "S_None";
380 case S_Retain:
381 return OS << "S_Retain";
382 case S_CanRelease:
383 return OS << "S_CanRelease";
384 case S_Use:
385 return OS << "S_Use";
386 case S_Release:
387 return OS << "S_Release";
388 case S_MovableRelease:
389 return OS << "S_MovableRelease";
390 case S_Stop:
391 return OS << "S_Stop";
392 }
393 llvm_unreachable("Unknown sequence type.");
394 }
John McCalld935e9c2011-06-15 23:37:01 +0000395}
396
397static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
398 // The easy cases.
399 if (A == B)
400 return A;
401 if (A == S_None || B == S_None)
402 return S_None;
403
John McCalld935e9c2011-06-15 23:37:01 +0000404 if (A > B) std::swap(A, B);
405 if (TopDown) {
406 // Choose the side which is further along in the sequence.
Dan Gohman12130272011-08-12 00:26:31 +0000407 if ((A == S_Retain || A == S_CanRelease) &&
408 (B == S_CanRelease || B == S_Use))
John McCalld935e9c2011-06-15 23:37:01 +0000409 return B;
410 } else {
411 // Choose the side which is further along in the sequence.
412 if ((A == S_Use || A == S_CanRelease) &&
Dan Gohman12130272011-08-12 00:26:31 +0000413 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
John McCalld935e9c2011-06-15 23:37:01 +0000414 return A;
415 // If both sides are releases, choose the more conservative one.
416 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
417 return A;
418 if (A == S_Release && B == S_MovableRelease)
419 return A;
420 }
421
422 return S_None;
423}
424
425namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000426 /// \brief Unidirectional information about either a
John McCalld935e9c2011-06-15 23:37:01 +0000427 /// retain-decrement-use-release sequence or release-use-decrement-retain
Bob Wilson798a7702013-04-09 22:15:51 +0000428 /// reverse sequence.
John McCalld935e9c2011-06-15 23:37:01 +0000429 struct RRInfo {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000430 /// After an objc_retain, the reference count of the referenced
Dan Gohmanb3894012011-08-19 00:26:36 +0000431 /// object is known to be positive. Similarly, before an objc_release, the
432 /// reference count of the referenced object is known to be positive. If
433 /// there are retain-release pairs in code regions where the retain count
434 /// is known to be positive, they can be eliminated, regardless of any side
435 /// effects between them.
436 ///
437 /// Also, a retain+release pair nested within another retain+release
438 /// pair all on the known same pointer value can be eliminated, regardless
439 /// of any intervening side effects.
440 ///
441 /// KnownSafe is true when either of these conditions is satisfied.
442 bool KnownSafe;
John McCalld935e9c2011-06-15 23:37:01 +0000443
Michael Gottesman97e3df02013-01-14 00:35:14 +0000444 /// True of the objc_release calls are all marked with the "tail" keyword.
John McCalld935e9c2011-06-15 23:37:01 +0000445 bool IsTailCallRelease;
446
Michael Gottesman97e3df02013-01-14 00:35:14 +0000447 /// If the Calls are objc_release calls and they all have a
448 /// clang.imprecise_release tag, this is the metadata tag.
John McCalld935e9c2011-06-15 23:37:01 +0000449 MDNode *ReleaseMetadata;
450
Michael Gottesman97e3df02013-01-14 00:35:14 +0000451 /// For a top-down sequence, the set of objc_retains or
John McCalld935e9c2011-06-15 23:37:01 +0000452 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
453 SmallPtrSet<Instruction *, 2> Calls;
454
Michael Gottesman97e3df02013-01-14 00:35:14 +0000455 /// The set of optimal insert positions for moving calls in the opposite
456 /// sequence.
John McCalld935e9c2011-06-15 23:37:01 +0000457 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
458
Michael Gottesmane67f40c2013-05-24 20:44:05 +0000459 /// If this is true, we cannot perform code motion but can still remove
460 /// retain/release pairs.
461 bool CFGHazardAfflicted;
462
John McCalld935e9c2011-06-15 23:37:01 +0000463 RRInfo() :
Michael Gottesmane67f40c2013-05-24 20:44:05 +0000464 KnownSafe(false), IsTailCallRelease(false), ReleaseMetadata(0),
465 CFGHazardAfflicted(false) {}
John McCalld935e9c2011-06-15 23:37:01 +0000466
467 void clear();
Michael Gottesman79249972013-04-05 23:46:45 +0000468
Michael Gottesman4773a102013-06-21 05:42:08 +0000469 /// Conservatively merge the two RRInfo. Returns true if a partial merge has
470 /// occured, false otherwise.
471 bool Merge(const RRInfo &Other);
472
John McCalld935e9c2011-06-15 23:37:01 +0000473 };
474}
475
476void RRInfo::clear() {
Dan Gohmanb3894012011-08-19 00:26:36 +0000477 KnownSafe = false;
John McCalld935e9c2011-06-15 23:37:01 +0000478 IsTailCallRelease = false;
479 ReleaseMetadata = 0;
480 Calls.clear();
481 ReverseInsertPts.clear();
Michael Gottesmane67f40c2013-05-24 20:44:05 +0000482 CFGHazardAfflicted = false;
John McCalld935e9c2011-06-15 23:37:01 +0000483}
484
Michael Gottesman4773a102013-06-21 05:42:08 +0000485bool RRInfo::Merge(const RRInfo &Other) {
486 // Conservatively merge the ReleaseMetadata information.
487 if (ReleaseMetadata != Other.ReleaseMetadata)
488 ReleaseMetadata = 0;
489
490 // Conservatively merge the boolean state.
491 KnownSafe &= Other.KnownSafe;
492 IsTailCallRelease &= Other.IsTailCallRelease;
493 CFGHazardAfflicted |= Other.CFGHazardAfflicted;
494
495 // Merge the call sets.
496 Calls.insert(Other.Calls.begin(), Other.Calls.end());
497
498 // Merge the insert point sets. If there are any differences,
499 // that makes this a partial merge.
500 bool Partial = ReverseInsertPts.size() != Other.ReverseInsertPts.size();
501 for (SmallPtrSet<Instruction *, 2>::const_iterator
502 I = Other.ReverseInsertPts.begin(),
503 E = Other.ReverseInsertPts.end(); I != E; ++I)
504 Partial |= ReverseInsertPts.insert(*I);
505 return Partial;
506}
507
John McCalld935e9c2011-06-15 23:37:01 +0000508namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000509 /// \brief This class summarizes several per-pointer runtime properties which
510 /// are propogated through the flow graph.
John McCalld935e9c2011-06-15 23:37:01 +0000511 class PtrState {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000512 /// True if the reference count is known to be incremented.
Dan Gohman62079b42012-04-25 00:50:46 +0000513 bool KnownPositiveRefCount;
514
Bob Wilson798a7702013-04-09 22:15:51 +0000515 /// True if we've seen an opportunity for partial RR elimination, such as
Michael Gottesman97e3df02013-01-14 00:35:14 +0000516 /// pushing calls into a CFG triangle or into one side of a CFG diamond.
Dan Gohman62079b42012-04-25 00:50:46 +0000517 bool Partial;
John McCalld935e9c2011-06-15 23:37:01 +0000518
Michael Gottesman97e3df02013-01-14 00:35:14 +0000519 /// The current position in the sequence.
Dan Gohman41375a32012-05-08 23:39:44 +0000520 Sequence Seq : 8;
John McCalld935e9c2011-06-15 23:37:01 +0000521
Michael Gottesman97e3df02013-01-14 00:35:14 +0000522 /// Unidirectional information about the current sequence.
John McCalld935e9c2011-06-15 23:37:01 +0000523 RRInfo RRI;
524
Michael Gottesmane3943d02013-06-21 19:44:30 +0000525 public:
Dan Gohmandf476e52012-09-04 23:16:20 +0000526 PtrState() : KnownPositiveRefCount(false), Partial(false),
Dan Gohman41375a32012-05-08 23:39:44 +0000527 Seq(S_None) {}
John McCalld935e9c2011-06-15 23:37:01 +0000528
Michael Gottesman93132252013-06-21 06:59:02 +0000529
530 bool IsKnownSafe() const {
Michael Gottesman01df4502013-07-06 01:41:35 +0000531 return RRI.KnownSafe;
Michael Gottesman93132252013-06-21 06:59:02 +0000532 }
533
534 void SetKnownSafe(const bool NewValue) {
535 RRI.KnownSafe = NewValue;
536 }
537
Michael Gottesmanb82a1792013-06-21 07:00:44 +0000538 bool IsTailCallRelease() const {
539 return RRI.IsTailCallRelease;
540 }
541
542 void SetTailCallRelease(const bool NewValue) {
543 RRI.IsTailCallRelease = NewValue;
544 }
545
Michael Gottesman9799cf72013-06-21 20:52:49 +0000546 bool IsTrackingImpreciseReleases() const {
Michael Gottesmanf0401182013-06-21 19:12:38 +0000547 return RRI.ReleaseMetadata != 0;
548 }
549
Michael Gottesmanf701d3f2013-06-21 07:03:07 +0000550 const MDNode *GetReleaseMetadata() const {
551 return RRI.ReleaseMetadata;
552 }
553
554 void SetReleaseMetadata(MDNode *NewValue) {
555 RRI.ReleaseMetadata = NewValue;
556 }
557
Michael Gottesman2f294592013-06-21 19:12:36 +0000558 bool IsCFGHazardAfflicted() const {
559 return RRI.CFGHazardAfflicted;
560 }
561
562 void SetCFGHazardAfflicted(const bool NewValue) {
563 RRI.CFGHazardAfflicted = NewValue;
564 }
565
Michael Gottesman415ddd72013-02-05 19:32:18 +0000566 void SetKnownPositiveRefCount() {
Michael Gottesmanf3f9e3b2013-05-14 00:08:09 +0000567 DEBUG(dbgs() << "Setting Known Positive.\n");
Dan Gohman62079b42012-04-25 00:50:46 +0000568 KnownPositiveRefCount = true;
Dan Gohman12130272011-08-12 00:26:31 +0000569 }
570
Michael Gottesman764b1cf2013-03-23 05:46:19 +0000571 void ClearKnownPositiveRefCount() {
Michael Gottesmanf3f9e3b2013-05-14 00:08:09 +0000572 DEBUG(dbgs() << "Clearing Known Positive.\n");
Dan Gohman62079b42012-04-25 00:50:46 +0000573 KnownPositiveRefCount = false;
John McCalld935e9c2011-06-15 23:37:01 +0000574 }
575
Michael Gottesman07beea42013-03-23 05:31:01 +0000576 bool HasKnownPositiveRefCount() const {
Dan Gohman62079b42012-04-25 00:50:46 +0000577 return KnownPositiveRefCount;
John McCalld935e9c2011-06-15 23:37:01 +0000578 }
579
Michael Gottesman415ddd72013-02-05 19:32:18 +0000580 void SetSeq(Sequence NewSeq) {
Michael Gottesman89279f82013-04-05 18:10:41 +0000581 DEBUG(dbgs() << "Old: " << Seq << "; New: " << NewSeq << "\n");
Michael Gottesman79249972013-04-05 23:46:45 +0000582 Seq = NewSeq;
John McCalld935e9c2011-06-15 23:37:01 +0000583 }
584
Michael Gottesman415ddd72013-02-05 19:32:18 +0000585 Sequence GetSeq() const {
John McCalld935e9c2011-06-15 23:37:01 +0000586 return Seq;
587 }
588
Michael Gottesman415ddd72013-02-05 19:32:18 +0000589 void ClearSequenceProgress() {
Dan Gohman62079b42012-04-25 00:50:46 +0000590 ResetSequenceProgress(S_None);
591 }
592
Michael Gottesman415ddd72013-02-05 19:32:18 +0000593 void ResetSequenceProgress(Sequence NewSeq) {
Michael Gottesman01338a42013-04-20 23:36:57 +0000594 DEBUG(dbgs() << "Resetting sequence progress.\n");
Michael Gottesman89279f82013-04-05 18:10:41 +0000595 SetSeq(NewSeq);
Dan Gohman62079b42012-04-25 00:50:46 +0000596 Partial = false;
John McCalld935e9c2011-06-15 23:37:01 +0000597 RRI.clear();
598 }
599
600 void Merge(const PtrState &Other, bool TopDown);
Michael Gottesman4f6ef112013-06-21 19:44:27 +0000601
602 void InsertCall(Instruction *I) {
603 RRI.Calls.insert(I);
604 }
605
606 void InsertReverseInsertPt(Instruction *I) {
607 RRI.ReverseInsertPts.insert(I);
608 }
609
610 void ClearReverseInsertPts() {
611 RRI.ReverseInsertPts.clear();
612 }
613
614 bool HasReverseInsertPts() const {
615 return !RRI.ReverseInsertPts.empty();
616 }
Michael Gottesmane3943d02013-06-21 19:44:30 +0000617
618 const RRInfo &GetRRInfo() const {
619 return RRI;
620 }
John McCalld935e9c2011-06-15 23:37:01 +0000621 };
622}
623
624void
625PtrState::Merge(const PtrState &Other, bool TopDown) {
626 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
Michael Gottesmanb7deb4c2013-06-21 06:54:31 +0000627 KnownPositiveRefCount &= Other.KnownPositiveRefCount;
Michael Gottesman60f6b282013-03-29 05:13:07 +0000628
Dan Gohman1736c142011-10-17 18:48:25 +0000629 // If we're not in a sequence (anymore), drop all associated state.
John McCalld935e9c2011-06-15 23:37:01 +0000630 if (Seq == S_None) {
Dan Gohman62079b42012-04-25 00:50:46 +0000631 Partial = false;
John McCalld935e9c2011-06-15 23:37:01 +0000632 RRI.clear();
Dan Gohman62079b42012-04-25 00:50:46 +0000633 } else if (Partial || Other.Partial) {
Dan Gohman1736c142011-10-17 18:48:25 +0000634 // If we're doing a merge on a path that's previously seen a partial
635 // merge, conservatively drop the sequence, to avoid doing partial
636 // RR elimination. If the branch predicates for the two merge differ,
637 // mixing them is unsafe.
Dan Gohman62079b42012-04-25 00:50:46 +0000638 ClearSequenceProgress();
John McCalld935e9c2011-06-15 23:37:01 +0000639 } else {
Michael Gottesmanb7deb4c2013-06-21 06:54:31 +0000640 // Otherwise merge the other PtrState's RRInfo into our RRInfo. At this
641 // point, we know that currently we are not partial. Stash whether or not
642 // the merge operation caused us to undergo a partial merging of reverse
643 // insertion points.
Michael Gottesman4773a102013-06-21 05:42:08 +0000644 Partial = RRI.Merge(Other.RRI);
John McCalld935e9c2011-06-15 23:37:01 +0000645 }
646}
647
648namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000649 /// \brief Per-BasicBlock state.
John McCalld935e9c2011-06-15 23:37:01 +0000650 class BBState {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000651 /// The number of unique control paths from the entry which can reach this
652 /// block.
John McCalld935e9c2011-06-15 23:37:01 +0000653 unsigned TopDownPathCount;
654
Michael Gottesman97e3df02013-01-14 00:35:14 +0000655 /// The number of unique control paths to exits from this block.
John McCalld935e9c2011-06-15 23:37:01 +0000656 unsigned BottomUpPathCount;
657
Michael Gottesman97e3df02013-01-14 00:35:14 +0000658 /// A type for PerPtrTopDown and PerPtrBottomUp.
John McCalld935e9c2011-06-15 23:37:01 +0000659 typedef MapVector<const Value *, PtrState> MapTy;
660
Michael Gottesman97e3df02013-01-14 00:35:14 +0000661 /// The top-down traversal uses this to record information known about a
662 /// pointer at the bottom of each block.
John McCalld935e9c2011-06-15 23:37:01 +0000663 MapTy PerPtrTopDown;
664
Michael Gottesman97e3df02013-01-14 00:35:14 +0000665 /// The bottom-up traversal uses this to record information known about a
666 /// pointer at the top of each block.
John McCalld935e9c2011-06-15 23:37:01 +0000667 MapTy PerPtrBottomUp;
668
Michael Gottesman97e3df02013-01-14 00:35:14 +0000669 /// Effective predecessors of the current block ignoring ignorable edges and
670 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000671 SmallVector<BasicBlock *, 2> Preds;
Michael Gottesman97e3df02013-01-14 00:35:14 +0000672 /// Effective successors of the current block ignoring ignorable edges and
673 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000674 SmallVector<BasicBlock *, 2> Succs;
675
John McCalld935e9c2011-06-15 23:37:01 +0000676 public:
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000677 static const unsigned OverflowOccurredValue;
678
679 BBState() : TopDownPathCount(0), BottomUpPathCount(0) { }
John McCalld935e9c2011-06-15 23:37:01 +0000680
681 typedef MapTy::iterator ptr_iterator;
682 typedef MapTy::const_iterator ptr_const_iterator;
683
684 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
685 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
686 ptr_const_iterator top_down_ptr_begin() const {
687 return PerPtrTopDown.begin();
688 }
689 ptr_const_iterator top_down_ptr_end() const {
690 return PerPtrTopDown.end();
691 }
692
693 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
694 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
695 ptr_const_iterator bottom_up_ptr_begin() const {
696 return PerPtrBottomUp.begin();
697 }
698 ptr_const_iterator bottom_up_ptr_end() const {
699 return PerPtrBottomUp.end();
700 }
701
Michael Gottesman97e3df02013-01-14 00:35:14 +0000702 /// Mark this block as being an entry block, which has one path from the
703 /// entry by definition.
John McCalld935e9c2011-06-15 23:37:01 +0000704 void SetAsEntry() { TopDownPathCount = 1; }
705
Michael Gottesman97e3df02013-01-14 00:35:14 +0000706 /// Mark this block as being an exit block, which has one path to an exit by
707 /// definition.
John McCalld935e9c2011-06-15 23:37:01 +0000708 void SetAsExit() { BottomUpPathCount = 1; }
709
Michael Gottesman993fbf72013-05-13 19:40:39 +0000710 /// Attempt to find the PtrState object describing the top down state for
711 /// pointer Arg. Return a new initialized PtrState describing the top down
712 /// state for Arg if we do not find one.
John McCalld935e9c2011-06-15 23:37:01 +0000713 PtrState &getPtrTopDownState(const Value *Arg) {
714 return PerPtrTopDown[Arg];
715 }
716
Michael Gottesman993fbf72013-05-13 19:40:39 +0000717 /// Attempt to find the PtrState object describing the bottom up state for
718 /// pointer Arg. Return a new initialized PtrState describing the bottom up
719 /// state for Arg if we do not find one.
John McCalld935e9c2011-06-15 23:37:01 +0000720 PtrState &getPtrBottomUpState(const Value *Arg) {
721 return PerPtrBottomUp[Arg];
722 }
723
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000724 /// Attempt to find the PtrState object describing the bottom up state for
725 /// pointer Arg.
726 ptr_iterator findPtrBottomUpState(const Value *Arg) {
727 return PerPtrBottomUp.find(Arg);
728 }
729
John McCalld935e9c2011-06-15 23:37:01 +0000730 void clearBottomUpPointers() {
Evan Chenge4df6a22011-08-04 18:40:26 +0000731 PerPtrBottomUp.clear();
John McCalld935e9c2011-06-15 23:37:01 +0000732 }
733
734 void clearTopDownPointers() {
735 PerPtrTopDown.clear();
736 }
737
738 void InitFromPred(const BBState &Other);
739 void InitFromSucc(const BBState &Other);
740 void MergePred(const BBState &Other);
741 void MergeSucc(const BBState &Other);
742
Michael Gottesman9e7261c2013-06-07 06:16:49 +0000743 /// Compute the number of possible unique paths from an entry to an exit
Michael Gottesman97e3df02013-01-14 00:35:14 +0000744 /// which pass through this block. This is only valid after both the
745 /// top-down and bottom-up traversals are complete.
Michael Gottesman9e7261c2013-06-07 06:16:49 +0000746 ///
747 /// Returns true if overflow occured. Returns false if overflow did not
748 /// occur.
749 bool GetAllPathCountWithOverflow(unsigned &PathCount) const {
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000750 if (TopDownPathCount == OverflowOccurredValue ||
751 BottomUpPathCount == OverflowOccurredValue)
752 return true;
Michael Gottesman9e7261c2013-06-07 06:16:49 +0000753 unsigned long long Product =
754 (unsigned long long)TopDownPathCount*BottomUpPathCount;
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000755 // Overflow occured if any of the upper bits of Product are set or if all
756 // the lower bits of Product are all set.
757 return (Product >> 32) ||
758 ((PathCount = Product) == OverflowOccurredValue);
John McCalld935e9c2011-06-15 23:37:01 +0000759 }
Dan Gohman12130272011-08-12 00:26:31 +0000760
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000761 // Specialized CFG utilities.
Dan Gohmandae33492012-04-27 18:56:31 +0000762 typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
Michael Gottesman0fecf982013-08-07 23:56:34 +0000763 edge_iterator pred_begin() const { return Preds.begin(); }
764 edge_iterator pred_end() const { return Preds.end(); }
765 edge_iterator succ_begin() const { return Succs.begin(); }
766 edge_iterator succ_end() const { return Succs.end(); }
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000767
768 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
769 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
770
771 bool isExit() const { return Succs.empty(); }
John McCalld935e9c2011-06-15 23:37:01 +0000772 };
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000773
774 const unsigned BBState::OverflowOccurredValue = 0xffffffff;
John McCalld935e9c2011-06-15 23:37:01 +0000775}
776
777void BBState::InitFromPred(const BBState &Other) {
778 PerPtrTopDown = Other.PerPtrTopDown;
779 TopDownPathCount = Other.TopDownPathCount;
780}
781
782void BBState::InitFromSucc(const BBState &Other) {
783 PerPtrBottomUp = Other.PerPtrBottomUp;
784 BottomUpPathCount = Other.BottomUpPathCount;
785}
786
Michael Gottesman97e3df02013-01-14 00:35:14 +0000787/// The top-down traversal uses this to merge information about predecessors to
788/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +0000789void BBState::MergePred(const BBState &Other) {
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000790 if (TopDownPathCount == OverflowOccurredValue)
791 return;
792
John McCalld935e9c2011-06-15 23:37:01 +0000793 // Other.TopDownPathCount can be 0, in which case it is either dead or a
794 // loop backedge. Loop backedges are special.
795 TopDownPathCount += Other.TopDownPathCount;
796
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000797 // In order to be consistent, we clear the top down pointers when by adding
798 // TopDownPathCount becomes OverflowOccurredValue even though "true" overflow
799 // has not occured.
800 if (TopDownPathCount == OverflowOccurredValue) {
801 clearTopDownPointers();
802 return;
803 }
804
Michael Gottesman4385edf2013-01-14 01:47:53 +0000805 // Check for overflow. If we have overflow, fall back to conservative
806 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +0000807 if (TopDownPathCount < Other.TopDownPathCount) {
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000808 TopDownPathCount = OverflowOccurredValue;
Dan Gohman7c84dad2012-09-12 20:45:17 +0000809 clearTopDownPointers();
810 return;
811 }
812
John McCalld935e9c2011-06-15 23:37:01 +0000813 // For each entry in the other set, if our set has an entry with the same key,
814 // merge the entries. Otherwise, copy the entry and merge it with an empty
815 // entry.
816 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
817 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
818 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
819 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
820 /*TopDown=*/true);
821 }
822
Dan Gohman7e315fc32011-08-11 21:06:32 +0000823 // For each entry in our set, if the other set doesn't have an entry with the
John McCalld935e9c2011-06-15 23:37:01 +0000824 // same key, force it to merge with an empty entry.
825 for (ptr_iterator MI = top_down_ptr_begin(),
826 ME = top_down_ptr_end(); MI != ME; ++MI)
827 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
828 MI->second.Merge(PtrState(), /*TopDown=*/true);
829}
830
Michael Gottesman97e3df02013-01-14 00:35:14 +0000831/// The bottom-up traversal uses this to merge information about successors to
832/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +0000833void BBState::MergeSucc(const BBState &Other) {
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000834 if (BottomUpPathCount == OverflowOccurredValue)
835 return;
836
John McCalld935e9c2011-06-15 23:37:01 +0000837 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
838 // loop backedge. Loop backedges are special.
839 BottomUpPathCount += Other.BottomUpPathCount;
840
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000841 // In order to be consistent, we clear the top down pointers when by adding
842 // BottomUpPathCount becomes OverflowOccurredValue even though "true" overflow
843 // has not occured.
844 if (BottomUpPathCount == OverflowOccurredValue) {
845 clearBottomUpPointers();
846 return;
847 }
848
Michael Gottesman4385edf2013-01-14 01:47:53 +0000849 // Check for overflow. If we have overflow, fall back to conservative
850 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +0000851 if (BottomUpPathCount < Other.BottomUpPathCount) {
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000852 BottomUpPathCount = OverflowOccurredValue;
Dan Gohman7c84dad2012-09-12 20:45:17 +0000853 clearBottomUpPointers();
854 return;
855 }
856
John McCalld935e9c2011-06-15 23:37:01 +0000857 // For each entry in the other set, if our set has an entry with the
858 // same key, merge the entries. Otherwise, copy the entry and merge
859 // it with an empty entry.
860 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
861 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
862 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
863 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
864 /*TopDown=*/false);
865 }
866
Dan Gohman7e315fc32011-08-11 21:06:32 +0000867 // For each entry in our set, if the other set doesn't have an entry
John McCalld935e9c2011-06-15 23:37:01 +0000868 // with the same key, force it to merge with an empty entry.
869 for (ptr_iterator MI = bottom_up_ptr_begin(),
870 ME = bottom_up_ptr_end(); MI != ME; ++MI)
871 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
872 MI->second.Merge(PtrState(), /*TopDown=*/false);
873}
874
Michael Gottesman81b1d432013-03-26 00:42:04 +0000875// Only enable ARC Annotations if we are building a debug version of
876// libObjCARCOpts.
877#ifndef NDEBUG
878#define ARC_ANNOTATIONS
879#endif
880
881// Define some macros along the lines of DEBUG and some helper functions to make
882// it cleaner to create annotations in the source code and to no-op when not
883// building in debug mode.
884#ifdef ARC_ANNOTATIONS
885
886#include "llvm/Support/CommandLine.h"
887
888/// Enable/disable ARC sequence annotations.
889static cl::opt<bool>
Michael Gottesman6806b512013-04-17 20:48:03 +0000890EnableARCAnnotations("enable-objc-arc-annotations", cl::init(false),
891 cl::desc("Enable emission of arc data flow analysis "
892 "annotations"));
Michael Gottesmanffef24f2013-04-17 20:48:01 +0000893static cl::opt<bool>
Michael Gottesmanadb921a2013-04-17 21:03:53 +0000894DisableCheckForCFGHazards("disable-objc-arc-checkforcfghazards", cl::init(false),
895 cl::desc("Disable check for cfg hazards when "
896 "annotating"));
Michael Gottesman4e88ce62013-04-17 21:59:41 +0000897static cl::opt<std::string>
898ARCAnnotationTargetIdentifier("objc-arc-annotation-target-identifier",
899 cl::init(""),
900 cl::desc("filter out all data flow annotations "
901 "but those that apply to the given "
902 "target llvm identifier."));
Michael Gottesman81b1d432013-03-26 00:42:04 +0000903
904/// This function appends a unique ARCAnnotationProvenanceSourceMDKind id to an
905/// instruction so that we can track backwards when post processing via the llvm
906/// arc annotation processor tool. If the function is an
907static MDString *AppendMDNodeToSourcePtr(unsigned NodeId,
908 Value *Ptr) {
909 MDString *Hash = 0;
910
911 // If pointer is a result of an instruction and it does not have a source
912 // MDNode it, attach a new MDNode onto it. If pointer is a result of
913 // an instruction and does have a source MDNode attached to it, return a
914 // reference to said Node. Otherwise just return 0.
915 if (Instruction *Inst = dyn_cast<Instruction>(Ptr)) {
916 MDNode *Node;
917 if (!(Node = Inst->getMetadata(NodeId))) {
918 // We do not have any node. Generate and attatch the hash MDString to the
919 // instruction.
920
921 // We just use an MDString to ensure that this metadata gets written out
922 // of line at the module level and to provide a very simple format
923 // encoding the information herein. Both of these makes it simpler to
924 // parse the annotations by a simple external program.
925 std::string Str;
926 raw_string_ostream os(Str);
927 os << "(" << Inst->getParent()->getParent()->getName() << ",%"
928 << Inst->getName() << ")";
929
930 Hash = MDString::get(Inst->getContext(), os.str());
931 Inst->setMetadata(NodeId, MDNode::get(Inst->getContext(),Hash));
932 } else {
933 // We have a node. Grab its hash and return it.
934 assert(Node->getNumOperands() == 1 &&
935 "An ARCAnnotationProvenanceSourceMDKind can only have 1 operand.");
936 Hash = cast<MDString>(Node->getOperand(0));
937 }
938 } else if (Argument *Arg = dyn_cast<Argument>(Ptr)) {
939 std::string str;
940 raw_string_ostream os(str);
941 os << "(" << Arg->getParent()->getName() << ",%" << Arg->getName()
942 << ")";
943 Hash = MDString::get(Arg->getContext(), os.str());
944 }
945
946 return Hash;
947}
948
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000949static std::string SequenceToString(Sequence A) {
950 std::string str;
951 raw_string_ostream os(str);
952 os << A;
953 return os.str();
954}
955
Michael Gottesman81b1d432013-03-26 00:42:04 +0000956/// Helper function to change a Sequence into a String object using our overload
957/// for raw_ostream so we only have printing code in one location.
958static MDString *SequenceToMDString(LLVMContext &Context,
959 Sequence A) {
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000960 return MDString::get(Context, SequenceToString(A));
Michael Gottesman81b1d432013-03-26 00:42:04 +0000961}
962
963/// A simple function to generate a MDNode which describes the change in state
964/// for Value *Ptr caused by Instruction *Inst.
965static void AppendMDNodeToInstForPtr(unsigned NodeId,
966 Instruction *Inst,
967 Value *Ptr,
968 MDString *PtrSourceMDNodeID,
969 Sequence OldSeq,
970 Sequence NewSeq) {
971 MDNode *Node = 0;
972 Value *tmp[3] = {PtrSourceMDNodeID,
973 SequenceToMDString(Inst->getContext(),
974 OldSeq),
975 SequenceToMDString(Inst->getContext(),
976 NewSeq)};
977 Node = MDNode::get(Inst->getContext(),
978 ArrayRef<Value*>(tmp, 3));
979
980 Inst->setMetadata(NodeId, Node);
981}
982
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000983/// Add to the beginning of the basic block llvm.ptr.annotations which show the
984/// state of a pointer at the entrance to a basic block.
985static void GenerateARCBBEntranceAnnotation(const char *Name, BasicBlock *BB,
986 Value *Ptr, Sequence Seq) {
Michael Gottesman4e88ce62013-04-17 21:59:41 +0000987 // If we have a target identifier, make sure that we match it before
988 // continuing.
989 if(!ARCAnnotationTargetIdentifier.empty() &&
990 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
991 return;
Michael Gottesman9e518132013-04-18 04:34:11 +0000992
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000993 Module *M = BB->getParent()->getParent();
994 LLVMContext &C = M->getContext();
995 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
996 Type *I8XX = PointerType::getUnqual(I8X);
997 Type *Params[] = {I8XX, I8XX};
998 FunctionType *FTy = FunctionType::get(Type::getVoidTy(C),
999 ArrayRef<Type*>(Params, 2),
1000 /*isVarArg=*/false);
1001 Constant *Callee = M->getOrInsertFunction(Name, FTy);
Michael Gottesman60f6b282013-03-29 05:13:07 +00001002
1003 IRBuilder<> Builder(BB, BB->getFirstInsertionPt());
1004
Michael Gottesmancd4de0f2013-03-26 00:42:09 +00001005 Value *PtrName;
1006 StringRef Tmp = Ptr->getName();
1007 if (0 == (PtrName = M->getGlobalVariable(Tmp, true))) {
1008 Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
1009 Tmp + "_STR");
1010 PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
Michael Gottesman60f6b282013-03-29 05:13:07 +00001011 cast<Constant>(ActualPtrName), Tmp);
Michael Gottesmancd4de0f2013-03-26 00:42:09 +00001012 }
1013
1014 Value *S;
1015 std::string SeqStr = SequenceToString(Seq);
1016 if (0 == (S = M->getGlobalVariable(SeqStr, true))) {
1017 Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
1018 SeqStr + "_STR");
1019 S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
1020 cast<Constant>(ActualPtrName), SeqStr);
1021 }
1022
1023 Builder.CreateCall2(Callee, PtrName, S);
1024}
1025
1026/// Add to the end of the basic block llvm.ptr.annotations which show the state
1027/// of the pointer at the bottom of the basic block.
1028static void GenerateARCBBTerminatorAnnotation(const char *Name, BasicBlock *BB,
1029 Value *Ptr, Sequence Seq) {
Michael Gottesman4e88ce62013-04-17 21:59:41 +00001030 // If we have a target identifier, make sure that we match it before emitting
1031 // an annotation.
1032 if(!ARCAnnotationTargetIdentifier.empty() &&
1033 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
1034 return;
Michael Gottesman9e518132013-04-18 04:34:11 +00001035
Michael Gottesmancd4de0f2013-03-26 00:42:09 +00001036 Module *M = BB->getParent()->getParent();
1037 LLVMContext &C = M->getContext();
1038 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1039 Type *I8XX = PointerType::getUnqual(I8X);
1040 Type *Params[] = {I8XX, I8XX};
1041 FunctionType *FTy = FunctionType::get(Type::getVoidTy(C),
1042 ArrayRef<Type*>(Params, 2),
1043 /*isVarArg=*/false);
1044 Constant *Callee = M->getOrInsertFunction(Name, FTy);
Michael Gottesman60f6b282013-03-29 05:13:07 +00001045
1046 IRBuilder<> Builder(BB, llvm::prior(BB->end()));
1047
Michael Gottesmancd4de0f2013-03-26 00:42:09 +00001048 Value *PtrName;
1049 StringRef Tmp = Ptr->getName();
1050 if (0 == (PtrName = M->getGlobalVariable(Tmp, true))) {
1051 Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
1052 Tmp + "_STR");
1053 PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
Michael Gottesman60f6b282013-03-29 05:13:07 +00001054 cast<Constant>(ActualPtrName), Tmp);
Michael Gottesmancd4de0f2013-03-26 00:42:09 +00001055 }
1056
1057 Value *S;
1058 std::string SeqStr = SequenceToString(Seq);
1059 if (0 == (S = M->getGlobalVariable(SeqStr, true))) {
1060 Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
1061 SeqStr + "_STR");
1062 S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
1063 cast<Constant>(ActualPtrName), SeqStr);
1064 }
Michael Gottesman60f6b282013-03-29 05:13:07 +00001065 Builder.CreateCall2(Callee, PtrName, S);
Michael Gottesmancd4de0f2013-03-26 00:42:09 +00001066}
1067
Michael Gottesman81b1d432013-03-26 00:42:04 +00001068/// Adds a source annotation to pointer and a state change annotation to Inst
1069/// referencing the source annotation and the old/new state of pointer.
1070static void GenerateARCAnnotation(unsigned InstMDId,
1071 unsigned PtrMDId,
1072 Instruction *Inst,
1073 Value *Ptr,
1074 Sequence OldSeq,
1075 Sequence NewSeq) {
1076 if (EnableARCAnnotations) {
Michael Gottesman4e88ce62013-04-17 21:59:41 +00001077 // If we have a target identifier, make sure that we match it before
1078 // emitting an annotation.
1079 if(!ARCAnnotationTargetIdentifier.empty() &&
1080 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
1081 return;
Michael Gottesman9e518132013-04-18 04:34:11 +00001082
Michael Gottesman81b1d432013-03-26 00:42:04 +00001083 // First generate the source annotation on our pointer. This will return an
1084 // MDString* if Ptr actually comes from an instruction implying we can put
1085 // in a source annotation. If AppendMDNodeToSourcePtr returns 0 (i.e. NULL),
1086 // then we know that our pointer is from an Argument so we put a reference
1087 // to the argument number.
1088 //
1089 // The point of this is to make it easy for the
1090 // llvm-arc-annotation-processor tool to cross reference where the source
1091 // pointer is in the LLVM IR since the LLVM IR parser does not submit such
1092 // information via debug info for backends to use (since why would anyone
1093 // need such a thing from LLVM IR besides in non standard cases
1094 // [i.e. this]).
1095 MDString *SourcePtrMDNode =
1096 AppendMDNodeToSourcePtr(PtrMDId, Ptr);
1097 AppendMDNodeToInstForPtr(InstMDId, Inst, Ptr, SourcePtrMDNode, OldSeq,
1098 NewSeq);
1099 }
1100}
1101
1102// The actual interface for accessing the above functionality is defined via
1103// some simple macros which are defined below. We do this so that the user does
1104// not need to pass in what metadata id is needed resulting in cleaner code and
1105// additionally since it provides an easy way to conditionally no-op all
1106// annotation support in a non-debug build.
1107
1108/// Use this macro to annotate a sequence state change when processing
1109/// instructions bottom up,
1110#define ANNOTATE_BOTTOMUP(inst, ptr, old, new) \
1111 GenerateARCAnnotation(ARCAnnotationBottomUpMDKind, \
1112 ARCAnnotationProvenanceSourceMDKind, (inst), \
1113 const_cast<Value*>(ptr), (old), (new))
1114/// Use this macro to annotate a sequence state change when processing
1115/// instructions top down.
1116#define ANNOTATE_TOPDOWN(inst, ptr, old, new) \
1117 GenerateARCAnnotation(ARCAnnotationTopDownMDKind, \
1118 ARCAnnotationProvenanceSourceMDKind, (inst), \
1119 const_cast<Value*>(ptr), (old), (new))
1120
Michael Gottesman43e7e002013-04-03 22:41:59 +00001121#define ANNOTATE_BB(_states, _bb, _name, _type, _direction) \
1122 do { \
Michael Gottesman89279f82013-04-05 18:10:41 +00001123 if (EnableARCAnnotations) { \
1124 for(BBState::ptr_const_iterator I = (_states)._direction##_ptr_begin(), \
Michael Gottesman43e7e002013-04-03 22:41:59 +00001125 E = (_states)._direction##_ptr_end(); I != E; ++I) { \
Michael Gottesman89279f82013-04-05 18:10:41 +00001126 Value *Ptr = const_cast<Value*>(I->first); \
1127 Sequence Seq = I->second.GetSeq(); \
1128 GenerateARCBB ## _type ## Annotation(_name, (_bb), Ptr, Seq); \
1129 } \
Michael Gottesman43e7e002013-04-03 22:41:59 +00001130 } \
Michael Gottesman89279f82013-04-05 18:10:41 +00001131 } while (0)
Michael Gottesman43e7e002013-04-03 22:41:59 +00001132
Michael Gottesman89279f82013-04-05 18:10:41 +00001133#define ANNOTATE_BOTTOMUP_BBSTART(_states, _basicblock) \
Michael Gottesman43e7e002013-04-03 22:41:59 +00001134 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbstart", \
1135 Entrance, bottom_up)
Michael Gottesman89279f82013-04-05 18:10:41 +00001136#define ANNOTATE_BOTTOMUP_BBEND(_states, _basicblock) \
1137 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbend", \
Michael Gottesman43e7e002013-04-03 22:41:59 +00001138 Terminator, bottom_up)
Michael Gottesman89279f82013-04-05 18:10:41 +00001139#define ANNOTATE_TOPDOWN_BBSTART(_states, _basicblock) \
1140 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbstart", \
Michael Gottesman43e7e002013-04-03 22:41:59 +00001141 Entrance, top_down)
Michael Gottesman89279f82013-04-05 18:10:41 +00001142#define ANNOTATE_TOPDOWN_BBEND(_states, _basicblock) \
1143 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbend", \
Michael Gottesman43e7e002013-04-03 22:41:59 +00001144 Terminator, top_down)
1145
Michael Gottesman81b1d432013-03-26 00:42:04 +00001146#else // !ARC_ANNOTATION
1147// If annotations are off, noop.
1148#define ANNOTATE_BOTTOMUP(inst, ptr, old, new)
1149#define ANNOTATE_TOPDOWN(inst, ptr, old, new)
Michael Gottesman43e7e002013-04-03 22:41:59 +00001150#define ANNOTATE_BOTTOMUP_BBSTART(states, basicblock)
1151#define ANNOTATE_BOTTOMUP_BBEND(states, basicblock)
1152#define ANNOTATE_TOPDOWN_BBSTART(states, basicblock)
1153#define ANNOTATE_TOPDOWN_BBEND(states, basicblock)
Michael Gottesman81b1d432013-03-26 00:42:04 +00001154#endif // !ARC_ANNOTATION
1155
John McCalld935e9c2011-06-15 23:37:01 +00001156namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001157 /// \brief The main ARC optimization pass.
John McCalld935e9c2011-06-15 23:37:01 +00001158 class ObjCARCOpt : public FunctionPass {
1159 bool Changed;
1160 ProvenanceAnalysis PA;
Michael Gottesman14acfac2013-07-06 01:39:23 +00001161 ARCRuntimeEntryPoints EP;
John McCalld935e9c2011-06-15 23:37:01 +00001162
Michael Gottesman5a91bbf2013-05-24 20:44:02 +00001163 // This is used to track if a pointer is stored into an alloca.
1164 DenseSet<const Value *> MultiOwnersSet;
1165
Michael Gottesman97e3df02013-01-14 00:35:14 +00001166 /// A flag indicating whether this optimization pass should run.
Dan Gohmanceaac7c2011-06-20 23:20:43 +00001167 bool Run;
1168
Michael Gottesman97e3df02013-01-14 00:35:14 +00001169 /// Flags which determine whether each of the interesting runtine functions
1170 /// is in fact used in the current function.
John McCalld935e9c2011-06-15 23:37:01 +00001171 unsigned UsedInThisFunction;
1172
Michael Gottesman97e3df02013-01-14 00:35:14 +00001173 /// The Metadata Kind for clang.imprecise_release metadata.
John McCalld935e9c2011-06-15 23:37:01 +00001174 unsigned ImpreciseReleaseMDKind;
1175
Michael Gottesman97e3df02013-01-14 00:35:14 +00001176 /// The Metadata Kind for clang.arc.copy_on_escape metadata.
Dan Gohmana7107f92011-10-17 22:53:25 +00001177 unsigned CopyOnEscapeMDKind;
1178
Michael Gottesman97e3df02013-01-14 00:35:14 +00001179 /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata.
Dan Gohman0155f302012-02-17 18:59:53 +00001180 unsigned NoObjCARCExceptionsMDKind;
1181
Michael Gottesman81b1d432013-03-26 00:42:04 +00001182#ifdef ARC_ANNOTATIONS
1183 /// The Metadata Kind for llvm.arc.annotation.bottomup metadata.
1184 unsigned ARCAnnotationBottomUpMDKind;
1185 /// The Metadata Kind for llvm.arc.annotation.topdown metadata.
1186 unsigned ARCAnnotationTopDownMDKind;
1187 /// The Metadata Kind for llvm.arc.annotation.provenancesource metadata.
1188 unsigned ARCAnnotationProvenanceSourceMDKind;
1189#endif // ARC_ANNOATIONS
1190
Dan Gohman728db492012-01-13 00:39:07 +00001191 bool IsRetainBlockOptimizable(const Instruction *Inst);
1192
John McCalld935e9c2011-06-15 23:37:01 +00001193 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
Michael Gottesman556ff612013-01-12 01:25:19 +00001194 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1195 InstructionClass &Class);
Michael Gottesman158fdf62013-03-28 20:11:19 +00001196 bool OptimizeRetainBlockCall(Function &F, Instruction *RetainBlock,
1197 InstructionClass &Class);
John McCalld935e9c2011-06-15 23:37:01 +00001198 void OptimizeIndividualCalls(Function &F);
1199
1200 void CheckForCFGHazards(const BasicBlock *BB,
1201 DenseMap<const BasicBlock *, BBState> &BBStates,
1202 BBState &MyStates) const;
Dan Gohman817a7c62012-03-22 18:24:56 +00001203 bool VisitInstructionBottomUp(Instruction *Inst,
Dan Gohman5c70fad2012-03-23 17:47:54 +00001204 BasicBlock *BB,
Dan Gohman817a7c62012-03-22 18:24:56 +00001205 MapVector<Value *, RRInfo> &Retains,
1206 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00001207 bool VisitBottomUp(BasicBlock *BB,
1208 DenseMap<const BasicBlock *, BBState> &BBStates,
1209 MapVector<Value *, RRInfo> &Retains);
Dan Gohman817a7c62012-03-22 18:24:56 +00001210 bool VisitInstructionTopDown(Instruction *Inst,
1211 DenseMap<Value *, RRInfo> &Releases,
1212 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00001213 bool VisitTopDown(BasicBlock *BB,
1214 DenseMap<const BasicBlock *, BBState> &BBStates,
1215 DenseMap<Value *, RRInfo> &Releases);
1216 bool Visit(Function &F,
1217 DenseMap<const BasicBlock *, BBState> &BBStates,
1218 MapVector<Value *, RRInfo> &Retains,
1219 DenseMap<Value *, RRInfo> &Releases);
1220
1221 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1222 MapVector<Value *, RRInfo> &Retains,
1223 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman6320f522011-07-22 22:29:21 +00001224 SmallVectorImpl<Instruction *> &DeadInsts,
1225 Module *M);
John McCalld935e9c2011-06-15 23:37:01 +00001226
Michael Gottesman9de6f962013-01-22 21:49:00 +00001227 bool ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState> &BBStates,
1228 MapVector<Value *, RRInfo> &Retains,
1229 DenseMap<Value *, RRInfo> &Releases,
1230 Module *M,
Craig Topperb94011f2013-07-14 04:42:23 +00001231 SmallVectorImpl<Instruction *> &NewRetains,
1232 SmallVectorImpl<Instruction *> &NewReleases,
1233 SmallVectorImpl<Instruction *> &DeadInsts,
Michael Gottesman9de6f962013-01-22 21:49:00 +00001234 RRInfo &RetainsToMove,
1235 RRInfo &ReleasesToMove,
1236 Value *Arg,
1237 bool KnownSafe,
1238 bool &AnyPairsCompletelyEliminated);
1239
John McCalld935e9c2011-06-15 23:37:01 +00001240 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1241 MapVector<Value *, RRInfo> &Retains,
Dan Gohman6320f522011-07-22 22:29:21 +00001242 DenseMap<Value *, RRInfo> &Releases,
1243 Module *M);
John McCalld935e9c2011-06-15 23:37:01 +00001244
1245 void OptimizeWeakCalls(Function &F);
1246
1247 bool OptimizeSequences(Function &F);
1248
1249 void OptimizeReturns(Function &F);
1250
Michael Gottesman9c118152013-04-29 06:16:57 +00001251#ifndef NDEBUG
1252 void GatherStatistics(Function &F, bool AfterOptimization = false);
1253#endif
1254
John McCalld935e9c2011-06-15 23:37:01 +00001255 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1256 virtual bool doInitialization(Module &M);
1257 virtual bool runOnFunction(Function &F);
1258 virtual void releaseMemory();
1259
1260 public:
1261 static char ID;
1262 ObjCARCOpt() : FunctionPass(ID) {
1263 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1264 }
1265 };
1266}
1267
1268char ObjCARCOpt::ID = 0;
1269INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1270 "objc-arc", "ObjC ARC optimization", false, false)
1271INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1272INITIALIZE_PASS_END(ObjCARCOpt,
1273 "objc-arc", "ObjC ARC optimization", false, false)
1274
1275Pass *llvm::createObjCARCOptPass() {
1276 return new ObjCARCOpt();
1277}
1278
1279void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1280 AU.addRequired<ObjCARCAliasAnalysis>();
1281 AU.addRequired<AliasAnalysis>();
1282 // ARC optimization doesn't currently split critical edges.
1283 AU.setPreservesCFG();
1284}
1285
Dan Gohman728db492012-01-13 00:39:07 +00001286bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1287 // Without the magic metadata tag, we have to assume this might be an
1288 // objc_retainBlock call inserted to convert a block pointer to an id,
1289 // in which case it really is needed.
1290 if (!Inst->getMetadata(CopyOnEscapeMDKind))
1291 return false;
1292
1293 // If the pointer "escapes" (not including being used in a call),
1294 // the copy may be needed.
Michael Gottesman774d2c02013-01-29 21:00:52 +00001295 if (DoesRetainableObjPtrEscape(Inst))
Dan Gohman728db492012-01-13 00:39:07 +00001296 return false;
1297
1298 // Otherwise, it's not needed.
1299 return true;
1300}
1301
Michael Gottesman97e3df02013-01-14 00:35:14 +00001302/// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is
1303/// not a return value. Or, if it can be paired with an
1304/// objc_autoreleaseReturnValue, delete the pair and return true.
John McCalld935e9c2011-06-15 23:37:01 +00001305bool
1306ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001307 // Check for the argument being from an immediately preceding call or invoke.
Dan Gohmandae33492012-04-27 18:56:31 +00001308 const Value *Arg = GetObjCArg(RetainRV);
1309 ImmutableCallSite CS(Arg);
1310 if (const Instruction *Call = CS.getInstruction()) {
John McCalld935e9c2011-06-15 23:37:01 +00001311 if (Call->getParent() == RetainRV->getParent()) {
Dan Gohmandae33492012-04-27 18:56:31 +00001312 BasicBlock::const_iterator I = Call;
John McCalld935e9c2011-06-15 23:37:01 +00001313 ++I;
Michael Gottesman65c24812013-03-25 09:27:43 +00001314 while (IsNoopInstruction(I)) ++I;
John McCalld935e9c2011-06-15 23:37:01 +00001315 if (&*I == RetainRV)
1316 return false;
Dan Gohmandae33492012-04-27 18:56:31 +00001317 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001318 BasicBlock *RetainRVParent = RetainRV->getParent();
1319 if (II->getNormalDest() == RetainRVParent) {
Dan Gohmandae33492012-04-27 18:56:31 +00001320 BasicBlock::const_iterator I = RetainRVParent->begin();
Michael Gottesman65c24812013-03-25 09:27:43 +00001321 while (IsNoopInstruction(I)) ++I;
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001322 if (&*I == RetainRV)
1323 return false;
1324 }
John McCalld935e9c2011-06-15 23:37:01 +00001325 }
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001326 }
John McCalld935e9c2011-06-15 23:37:01 +00001327
1328 // Check for being preceded by an objc_autoreleaseReturnValue on the same
1329 // pointer. In this case, we can delete the pair.
1330 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
1331 if (I != Begin) {
Michael Gottesman65c24812013-03-25 09:27:43 +00001332 do --I; while (I != Begin && IsNoopInstruction(I));
John McCalld935e9c2011-06-15 23:37:01 +00001333 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
1334 GetObjCArg(I) == Arg) {
1335 Changed = true;
1336 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00001337
Michael Gottesman89279f82013-04-05 18:10:41 +00001338 DEBUG(dbgs() << "Erasing autoreleaseRV,retainRV pair: " << *I << "\n"
1339 << "Erasing " << *RetainRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001340
John McCalld935e9c2011-06-15 23:37:01 +00001341 EraseInstruction(I);
1342 EraseInstruction(RetainRV);
1343 return true;
1344 }
1345 }
1346
1347 // Turn it to a plain objc_retain.
1348 Changed = true;
1349 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00001350
Michael Gottesman89279f82013-04-05 18:10:41 +00001351 DEBUG(dbgs() << "Transforming objc_retainAutoreleasedReturnValue => "
Michael Gottesmandef07bb2013-01-05 17:55:42 +00001352 "objc_retain since the operand is not a return value.\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00001353 "Old = " << *RetainRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001354
Michael Gottesman14acfac2013-07-06 01:39:23 +00001355 Constant *NewDecl = EP.get(ARCRuntimeEntryPoints::EPT_Retain);
1356 cast<CallInst>(RetainRV)->setCalledFunction(NewDecl);
Michael Gottesmandef07bb2013-01-05 17:55:42 +00001357
Michael Gottesman89279f82013-04-05 18:10:41 +00001358 DEBUG(dbgs() << "New = " << *RetainRV << "\n");
Michael Gottesmandef07bb2013-01-05 17:55:42 +00001359
John McCalld935e9c2011-06-15 23:37:01 +00001360 return false;
1361}
1362
Michael Gottesman97e3df02013-01-14 00:35:14 +00001363/// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not
1364/// used as a return value.
John McCalld935e9c2011-06-15 23:37:01 +00001365void
Michael Gottesman556ff612013-01-12 01:25:19 +00001366ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1367 InstructionClass &Class) {
John McCalld935e9c2011-06-15 23:37:01 +00001368 // Check for a return of the pointer value.
1369 const Value *Ptr = GetObjCArg(AutoreleaseRV);
Dan Gohman10a18d52011-08-12 00:36:31 +00001370 SmallVector<const Value *, 2> Users;
1371 Users.push_back(Ptr);
1372 do {
1373 Ptr = Users.pop_back_val();
1374 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
1375 UI != UE; ++UI) {
1376 const User *I = *UI;
1377 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
1378 return;
1379 if (isa<BitCastInst>(I))
1380 Users.push_back(I);
1381 }
1382 } while (!Users.empty());
John McCalld935e9c2011-06-15 23:37:01 +00001383
1384 Changed = true;
1385 ++NumPeeps;
Michael Gottesman1bf69082013-01-06 21:07:11 +00001386
Michael Gottesman89279f82013-04-05 18:10:41 +00001387 DEBUG(dbgs() << "Transforming objc_autoreleaseReturnValue => "
Michael Gottesman1bf69082013-01-06 21:07:11 +00001388 "objc_autorelease since its operand is not used as a return "
1389 "value.\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00001390 "Old = " << *AutoreleaseRV << "\n");
Michael Gottesman1bf69082013-01-06 21:07:11 +00001391
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001392 CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
Michael Gottesman14acfac2013-07-06 01:39:23 +00001393 Constant *NewDecl = EP.get(ARCRuntimeEntryPoints::EPT_Autorelease);
1394 AutoreleaseRVCI->setCalledFunction(NewDecl);
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001395 AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
Michael Gottesman556ff612013-01-12 01:25:19 +00001396 Class = IC_Autorelease;
Michael Gottesman10426b52013-01-07 21:26:07 +00001397
Michael Gottesman89279f82013-04-05 18:10:41 +00001398 DEBUG(dbgs() << "New: " << *AutoreleaseRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001399
John McCalld935e9c2011-06-15 23:37:01 +00001400}
1401
Michael Gottesman158fdf62013-03-28 20:11:19 +00001402// \brief Attempt to strength reduce objc_retainBlock calls to objc_retain
1403// calls.
1404//
1405// Specifically: If an objc_retainBlock call has the copy_on_escape metadata and
1406// does not escape (following the rules of block escaping), strength reduce the
1407// objc_retainBlock to an objc_retain.
1408//
1409// TODO: If an objc_retainBlock call is dominated period by a previous
1410// objc_retainBlock call, strength reduce the objc_retainBlock to an
1411// objc_retain.
1412bool
1413ObjCARCOpt::OptimizeRetainBlockCall(Function &F, Instruction *Inst,
1414 InstructionClass &Class) {
1415 assert(GetBasicInstructionClass(Inst) == Class);
1416 assert(IC_RetainBlock == Class);
Michael Gottesman60f6b282013-03-29 05:13:07 +00001417
Michael Gottesman158fdf62013-03-28 20:11:19 +00001418 // If we can not optimize Inst, return false.
1419 if (!IsRetainBlockOptimizable(Inst))
1420 return false;
Michael Gottesman60f6b282013-03-29 05:13:07 +00001421
Michael Gottesman3eab2e42013-04-21 00:50:27 +00001422 Changed = true;
1423 ++NumPeeps;
1424
1425 DEBUG(dbgs() << "Strength reduced retainBlock => retain.\n");
1426 DEBUG(dbgs() << "Old: " << *Inst << "\n");
Michael Gottesman158fdf62013-03-28 20:11:19 +00001427 CallInst *RetainBlock = cast<CallInst>(Inst);
Michael Gottesman14acfac2013-07-06 01:39:23 +00001428 Constant *NewDecl = EP.get(ARCRuntimeEntryPoints::EPT_Retain);
1429 RetainBlock->setCalledFunction(NewDecl);
Michael Gottesman158fdf62013-03-28 20:11:19 +00001430 // Remove copy_on_escape metadata.
1431 RetainBlock->setMetadata(CopyOnEscapeMDKind, 0);
1432 Class = IC_Retain;
Michael Gottesman3eab2e42013-04-21 00:50:27 +00001433 DEBUG(dbgs() << "New: " << *Inst << "\n");
Michael Gottesman158fdf62013-03-28 20:11:19 +00001434 return true;
1435}
1436
Michael Gottesman97e3df02013-01-14 00:35:14 +00001437/// Visit each call, one at a time, and make simplifications without doing any
1438/// additional analysis.
John McCalld935e9c2011-06-15 23:37:01 +00001439void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001440 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeIndividualCalls ==\n");
John McCalld935e9c2011-06-15 23:37:01 +00001441 // Reset all the flags in preparation for recomputing them.
1442 UsedInThisFunction = 0;
1443
1444 // Visit all objc_* calls in F.
1445 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
1446 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +00001447
John McCalld935e9c2011-06-15 23:37:01 +00001448 InstructionClass Class = GetBasicInstructionClass(Inst);
1449
Michael Gottesman89279f82013-04-05 18:10:41 +00001450 DEBUG(dbgs() << "Visiting: Class: " << Class << "; " << *Inst << "\n");
Michael Gottesman782e3442013-01-17 18:32:34 +00001451
John McCalld935e9c2011-06-15 23:37:01 +00001452 switch (Class) {
1453 default: break;
1454
1455 // Delete no-op casts. These function calls have special semantics, but
1456 // the semantics are entirely implemented via lowering in the front-end,
1457 // so by the time they reach the optimizer, they are just no-op calls
1458 // which return their argument.
1459 //
1460 // There are gray areas here, as the ability to cast reference-counted
1461 // pointers to raw void* and back allows code to break ARC assumptions,
1462 // however these are currently considered to be unimportant.
1463 case IC_NoopCast:
1464 Changed = true;
1465 ++NumNoops;
Michael Gottesman89279f82013-04-05 18:10:41 +00001466 DEBUG(dbgs() << "Erasing no-op cast: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001467 EraseInstruction(Inst);
1468 continue;
1469
1470 // If the pointer-to-weak-pointer is null, it's undefined behavior.
1471 case IC_StoreWeak:
1472 case IC_LoadWeak:
1473 case IC_LoadWeakRetained:
1474 case IC_InitWeak:
1475 case IC_DestroyWeak: {
1476 CallInst *CI = cast<CallInst>(Inst);
Michael Gottesman65c24812013-03-25 09:27:43 +00001477 if (IsNullOrUndef(CI->getArgOperand(0))) {
Dan Gohman670f9372012-04-13 18:57:48 +00001478 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +00001479 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001480 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1481 Constant::getNullValue(Ty),
1482 CI);
Michael Gottesman10426b52013-01-07 21:26:07 +00001483 llvm::Value *NewValue = UndefValue::get(CI->getType());
Michael Gottesman89279f82013-04-05 18:10:41 +00001484 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
1485 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001486 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +00001487 CI->eraseFromParent();
1488 continue;
1489 }
1490 break;
1491 }
1492 case IC_CopyWeak:
1493 case IC_MoveWeak: {
1494 CallInst *CI = cast<CallInst>(Inst);
Michael Gottesman65c24812013-03-25 09:27:43 +00001495 if (IsNullOrUndef(CI->getArgOperand(0)) ||
1496 IsNullOrUndef(CI->getArgOperand(1))) {
Dan Gohman670f9372012-04-13 18:57:48 +00001497 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +00001498 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001499 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1500 Constant::getNullValue(Ty),
1501 CI);
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001502
1503 llvm::Value *NewValue = UndefValue::get(CI->getType());
Michael Gottesman89279f82013-04-05 18:10:41 +00001504 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
1505 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001506
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001507 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +00001508 CI->eraseFromParent();
1509 continue;
1510 }
1511 break;
1512 }
Michael Gottesman158fdf62013-03-28 20:11:19 +00001513 case IC_RetainBlock:
Michael Gottesman1e430042013-04-21 00:44:46 +00001514 // If we strength reduce an objc_retainBlock to an objc_retain, continue
Michael Gottesman158fdf62013-03-28 20:11:19 +00001515 // onto the objc_retain peephole optimizations. Otherwise break.
Michael Gottesman9fc50b82013-05-13 18:29:07 +00001516 OptimizeRetainBlockCall(F, Inst, Class);
John McCalld935e9c2011-06-15 23:37:01 +00001517 break;
1518 case IC_RetainRV:
1519 if (OptimizeRetainRVCall(F, Inst))
1520 continue;
1521 break;
1522 case IC_AutoreleaseRV:
Michael Gottesman556ff612013-01-12 01:25:19 +00001523 OptimizeAutoreleaseRVCall(F, Inst, Class);
John McCalld935e9c2011-06-15 23:37:01 +00001524 break;
1525 }
1526
Michael Gottesmanb8c88362013-04-03 02:57:24 +00001527 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
John McCalld935e9c2011-06-15 23:37:01 +00001528 if (IsAutorelease(Class) && Inst->use_empty()) {
1529 CallInst *Call = cast<CallInst>(Inst);
1530 const Value *Arg = Call->getArgOperand(0);
1531 Arg = FindSingleUseIdentifiedObject(Arg);
1532 if (Arg) {
1533 Changed = true;
1534 ++NumAutoreleases;
1535
1536 // Create the declaration lazily.
1537 LLVMContext &C = Inst->getContext();
Michael Gottesman01df4502013-07-06 01:41:35 +00001538
Michael Gottesman14acfac2013-07-06 01:39:23 +00001539 Constant *Decl = EP.get(ARCRuntimeEntryPoints::EPT_Release);
1540 CallInst *NewCall = CallInst::Create(Decl, Call->getArgOperand(0), "",
1541 Call);
Dmitri Gribenko3238fb72013-05-05 00:40:33 +00001542 NewCall->setMetadata(ImpreciseReleaseMDKind, MDNode::get(C, None));
Michael Gottesman10426b52013-01-07 21:26:07 +00001543
Michael Gottesman89279f82013-04-05 18:10:41 +00001544 DEBUG(dbgs() << "Replacing autorelease{,RV}(x) with objc_release(x) "
1545 "since x is otherwise unused.\nOld: " << *Call << "\nNew: "
1546 << *NewCall << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001547
John McCalld935e9c2011-06-15 23:37:01 +00001548 EraseInstruction(Call);
1549 Inst = NewCall;
1550 Class = IC_Release;
1551 }
1552 }
1553
1554 // For functions which can never be passed stack arguments, add
1555 // a tail keyword.
1556 if (IsAlwaysTail(Class)) {
1557 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +00001558 DEBUG(dbgs() << "Adding tail keyword to function since it can never be "
1559 "passed stack args: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001560 cast<CallInst>(Inst)->setTailCall();
1561 }
1562
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001563 // Ensure that functions that can never have a "tail" keyword due to the
1564 // semantics of ARC truly do not do so.
1565 if (IsNeverTail(Class)) {
1566 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +00001567 DEBUG(dbgs() << "Removing tail keyword from function: " << *Inst <<
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001568 "\n");
1569 cast<CallInst>(Inst)->setTailCall(false);
1570 }
1571
John McCalld935e9c2011-06-15 23:37:01 +00001572 // Set nounwind as needed.
1573 if (IsNoThrow(Class)) {
1574 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +00001575 DEBUG(dbgs() << "Found no throw class. Setting nounwind on: " << *Inst
1576 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001577 cast<CallInst>(Inst)->setDoesNotThrow();
1578 }
1579
1580 if (!IsNoopOnNull(Class)) {
1581 UsedInThisFunction |= 1 << Class;
1582 continue;
1583 }
1584
1585 const Value *Arg = GetObjCArg(Inst);
1586
1587 // ARC calls with null are no-ops. Delete them.
Michael Gottesman65c24812013-03-25 09:27:43 +00001588 if (IsNullOrUndef(Arg)) {
John McCalld935e9c2011-06-15 23:37:01 +00001589 Changed = true;
1590 ++NumNoops;
Michael Gottesman89279f82013-04-05 18:10:41 +00001591 DEBUG(dbgs() << "ARC calls with null are no-ops. Erasing: " << *Inst
1592 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001593 EraseInstruction(Inst);
1594 continue;
1595 }
1596
1597 // Keep track of which of retain, release, autorelease, and retain_block
1598 // are actually present in this function.
1599 UsedInThisFunction |= 1 << Class;
1600
1601 // If Arg is a PHI, and one or more incoming values to the
1602 // PHI are null, and the call is control-equivalent to the PHI, and there
1603 // are no relevant side effects between the PHI and the call, the call
1604 // could be pushed up to just those paths with non-null incoming values.
1605 // For now, don't bother splitting critical edges for this.
1606 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
1607 Worklist.push_back(std::make_pair(Inst, Arg));
1608 do {
1609 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
1610 Inst = Pair.first;
1611 Arg = Pair.second;
1612
1613 const PHINode *PN = dyn_cast<PHINode>(Arg);
1614 if (!PN) continue;
1615
1616 // Determine if the PHI has any null operands, or any incoming
1617 // critical edges.
1618 bool HasNull = false;
1619 bool HasCriticalEdges = false;
1620 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1621 Value *Incoming =
1622 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
Michael Gottesman65c24812013-03-25 09:27:43 +00001623 if (IsNullOrUndef(Incoming))
John McCalld935e9c2011-06-15 23:37:01 +00001624 HasNull = true;
1625 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
1626 .getNumSuccessors() != 1) {
1627 HasCriticalEdges = true;
1628 break;
1629 }
1630 }
1631 // If we have null operands and no critical edges, optimize.
1632 if (!HasCriticalEdges && HasNull) {
1633 SmallPtrSet<Instruction *, 4> DependingInstructions;
1634 SmallPtrSet<const BasicBlock *, 4> Visited;
1635
1636 // Check that there is nothing that cares about the reference
1637 // count between the call and the phi.
Dan Gohman8478d762012-04-13 00:59:57 +00001638 switch (Class) {
1639 case IC_Retain:
1640 case IC_RetainBlock:
1641 // These can always be moved up.
1642 break;
1643 case IC_Release:
Dan Gohman41375a32012-05-08 23:39:44 +00001644 // These can't be moved across things that care about the retain
1645 // count.
Dan Gohman8478d762012-04-13 00:59:57 +00001646 FindDependencies(NeedsPositiveRetainCount, Arg,
1647 Inst->getParent(), Inst,
1648 DependingInstructions, Visited, PA);
1649 break;
1650 case IC_Autorelease:
1651 // These can't be moved across autorelease pool scope boundaries.
1652 FindDependencies(AutoreleasePoolBoundary, Arg,
1653 Inst->getParent(), Inst,
1654 DependingInstructions, Visited, PA);
1655 break;
1656 case IC_RetainRV:
1657 case IC_AutoreleaseRV:
1658 // Don't move these; the RV optimization depends on the autoreleaseRV
1659 // being tail called, and the retainRV being immediately after a call
1660 // (which might still happen if we get lucky with codegen layout, but
1661 // it's not worth taking the chance).
1662 continue;
1663 default:
1664 llvm_unreachable("Invalid dependence flavor");
1665 }
1666
John McCalld935e9c2011-06-15 23:37:01 +00001667 if (DependingInstructions.size() == 1 &&
1668 *DependingInstructions.begin() == PN) {
1669 Changed = true;
1670 ++NumPartialNoops;
1671 // Clone the call into each predecessor that has a non-null value.
1672 CallInst *CInst = cast<CallInst>(Inst);
Chris Lattner229907c2011-07-18 04:54:35 +00001673 Type *ParamTy = CInst->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001674 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1675 Value *Incoming =
1676 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
Michael Gottesman65c24812013-03-25 09:27:43 +00001677 if (!IsNullOrUndef(Incoming)) {
John McCalld935e9c2011-06-15 23:37:01 +00001678 CallInst *Clone = cast<CallInst>(CInst->clone());
1679 Value *Op = PN->getIncomingValue(i);
1680 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
1681 if (Op->getType() != ParamTy)
1682 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
1683 Clone->setArgOperand(0, Op);
1684 Clone->insertBefore(InsertPos);
Michael Gottesmanc189a392013-01-09 19:23:24 +00001685
Michael Gottesman89279f82013-04-05 18:10:41 +00001686 DEBUG(dbgs() << "Cloning "
Michael Gottesmanc189a392013-01-09 19:23:24 +00001687 << *CInst << "\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00001688 "And inserting clone at " << *InsertPos << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001689 Worklist.push_back(std::make_pair(Clone, Incoming));
1690 }
1691 }
1692 // Erase the original call.
Michael Gottesmanc189a392013-01-09 19:23:24 +00001693 DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001694 EraseInstruction(CInst);
1695 continue;
1696 }
1697 }
1698 } while (!Worklist.empty());
1699 }
1700}
1701
Michael Gottesman323964c2013-04-18 05:39:45 +00001702/// If we have a top down pointer in the S_Use state, make sure that there are
1703/// no CFG hazards by checking the states of various bottom up pointers.
1704static void CheckForUseCFGHazard(const Sequence SuccSSeq,
1705 const bool SuccSRRIKnownSafe,
1706 PtrState &S,
1707 bool &SomeSuccHasSame,
1708 bool &AllSuccsHaveSame,
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001709 bool &NotAllSeqEqualButKnownSafe,
Michael Gottesman323964c2013-04-18 05:39:45 +00001710 bool &ShouldContinue) {
1711 switch (SuccSSeq) {
1712 case S_CanRelease: {
Michael Gottesman93132252013-06-21 06:59:02 +00001713 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe) {
Michael Gottesman323964c2013-04-18 05:39:45 +00001714 S.ClearSequenceProgress();
1715 break;
1716 }
Michael Gottesman2f294592013-06-21 19:12:36 +00001717 S.SetCFGHazardAfflicted(true);
Michael Gottesman323964c2013-04-18 05:39:45 +00001718 ShouldContinue = true;
1719 break;
1720 }
1721 case S_Use:
1722 SomeSuccHasSame = true;
1723 break;
1724 case S_Stop:
1725 case S_Release:
1726 case S_MovableRelease:
Michael Gottesman93132252013-06-21 06:59:02 +00001727 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe)
Michael Gottesman323964c2013-04-18 05:39:45 +00001728 AllSuccsHaveSame = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001729 else
1730 NotAllSeqEqualButKnownSafe = true;
Michael Gottesman323964c2013-04-18 05:39:45 +00001731 break;
1732 case S_Retain:
1733 llvm_unreachable("bottom-up pointer in retain state!");
1734 case S_None:
1735 llvm_unreachable("This should have been handled earlier.");
1736 }
1737}
1738
1739/// If we have a Top Down pointer in the S_CanRelease state, make sure that
1740/// there are no CFG hazards by checking the states of various bottom up
1741/// pointers.
1742static void CheckForCanReleaseCFGHazard(const Sequence SuccSSeq,
1743 const bool SuccSRRIKnownSafe,
1744 PtrState &S,
1745 bool &SomeSuccHasSame,
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001746 bool &AllSuccsHaveSame,
1747 bool &NotAllSeqEqualButKnownSafe) {
Michael Gottesman323964c2013-04-18 05:39:45 +00001748 switch (SuccSSeq) {
1749 case S_CanRelease:
1750 SomeSuccHasSame = true;
1751 break;
1752 case S_Stop:
1753 case S_Release:
1754 case S_MovableRelease:
1755 case S_Use:
Michael Gottesman93132252013-06-21 06:59:02 +00001756 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe)
Michael Gottesman323964c2013-04-18 05:39:45 +00001757 AllSuccsHaveSame = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001758 else
1759 NotAllSeqEqualButKnownSafe = true;
Michael Gottesman323964c2013-04-18 05:39:45 +00001760 break;
1761 case S_Retain:
1762 llvm_unreachable("bottom-up pointer in retain state!");
1763 case S_None:
1764 llvm_unreachable("This should have been handled earlier.");
1765 }
1766}
1767
Michael Gottesman97e3df02013-01-14 00:35:14 +00001768/// Check for critical edges, loop boundaries, irreducible control flow, or
1769/// other CFG structures where moving code across the edge would result in it
1770/// being executed more.
John McCalld935e9c2011-06-15 23:37:01 +00001771void
1772ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
1773 DenseMap<const BasicBlock *, BBState> &BBStates,
1774 BBState &MyStates) const {
1775 // If any top-down local-use or possible-dec has a succ which is earlier in
1776 // the sequence, forget it.
Dan Gohman55b06742012-03-02 01:13:53 +00001777 for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
Michael Gottesman323964c2013-04-18 05:39:45 +00001778 E = MyStates.top_down_ptr_end(); I != E; ++I) {
1779 PtrState &S = I->second;
1780 const Sequence Seq = I->second.GetSeq();
Dan Gohman0155f302012-02-17 18:59:53 +00001781
Michael Gottesman323964c2013-04-18 05:39:45 +00001782 // We only care about S_Retain, S_CanRelease, and S_Use.
1783 if (Seq == S_None)
1784 continue;
Dan Gohman0155f302012-02-17 18:59:53 +00001785
Michael Gottesman323964c2013-04-18 05:39:45 +00001786 // Make sure that if extra top down states are added in the future that this
1787 // code is updated to handle it.
1788 assert((Seq == S_Retain || Seq == S_CanRelease || Seq == S_Use) &&
1789 "Unknown top down sequence state.");
1790
1791 const Value *Arg = I->first;
1792 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
1793 bool SomeSuccHasSame = false;
1794 bool AllSuccsHaveSame = true;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001795 bool NotAllSeqEqualButKnownSafe = false;
Michael Gottesman323964c2013-04-18 05:39:45 +00001796
1797 succ_const_iterator SI(TI), SE(TI, false);
1798
1799 for (; SI != SE; ++SI) {
1800 // If VisitBottomUp has pointer information for this successor, take
1801 // what we know about it.
1802 const DenseMap<const BasicBlock *, BBState>::iterator BBI =
1803 BBStates.find(*SI);
1804 assert(BBI != BBStates.end());
1805 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
1806 const Sequence SuccSSeq = SuccS.GetSeq();
1807
1808 // If bottom up, the pointer is in an S_None state, clear the sequence
1809 // progress since the sequence in the bottom up state finished
1810 // suggesting a mismatch in between retains/releases. This is true for
1811 // all three cases that we are handling here: S_Retain, S_Use, and
1812 // S_CanRelease.
1813 if (SuccSSeq == S_None) {
Dan Gohman12130272011-08-12 00:26:31 +00001814 S.ClearSequenceProgress();
Michael Gottesman323964c2013-04-18 05:39:45 +00001815 continue;
1816 }
1817
1818 // If we have S_Use or S_CanRelease, perform our check for cfg hazard
1819 // checks.
Michael Gottesman93132252013-06-21 06:59:02 +00001820 const bool SuccSRRIKnownSafe = SuccS.IsKnownSafe();
Michael Gottesman323964c2013-04-18 05:39:45 +00001821
1822 // *NOTE* We do not use Seq from above here since we are allowing for
1823 // S.GetSeq() to change while we are visiting basic blocks.
1824 switch(S.GetSeq()) {
1825 case S_Use: {
1826 bool ShouldContinue = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001827 CheckForUseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S, SomeSuccHasSame,
1828 AllSuccsHaveSame, NotAllSeqEqualButKnownSafe,
Michael Gottesman323964c2013-04-18 05:39:45 +00001829 ShouldContinue);
1830 if (ShouldContinue)
1831 continue;
1832 break;
1833 }
1834 case S_CanRelease: {
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001835 CheckForCanReleaseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S,
1836 SomeSuccHasSame, AllSuccsHaveSame,
1837 NotAllSeqEqualButKnownSafe);
Michael Gottesman323964c2013-04-18 05:39:45 +00001838 break;
1839 }
1840 case S_Retain:
1841 case S_None:
1842 case S_Stop:
1843 case S_Release:
1844 case S_MovableRelease:
1845 break;
1846 }
John McCalld935e9c2011-06-15 23:37:01 +00001847 }
Michael Gottesman323964c2013-04-18 05:39:45 +00001848
1849 // If the state at the other end of any of the successor edges
1850 // matches the current state, require all edges to match. This
1851 // guards against loops in the middle of a sequence.
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001852 if (SomeSuccHasSame && !AllSuccsHaveSame) {
Michael Gottesman323964c2013-04-18 05:39:45 +00001853 S.ClearSequenceProgress();
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001854 } else if (NotAllSeqEqualButKnownSafe) {
1855 // If we would have cleared the state foregoing the fact that we are known
1856 // safe, stop code motion. This is because whether or not it is safe to
1857 // remove RR pairs via KnownSafe is an orthogonal concept to whether we
1858 // are allowed to perform code motion.
Michael Gottesman2f294592013-06-21 19:12:36 +00001859 S.SetCFGHazardAfflicted(true);
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001860 }
Michael Gottesman323964c2013-04-18 05:39:45 +00001861 }
John McCalld935e9c2011-06-15 23:37:01 +00001862}
1863
1864bool
Dan Gohman817a7c62012-03-22 18:24:56 +00001865ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
Dan Gohman5c70fad2012-03-23 17:47:54 +00001866 BasicBlock *BB,
Dan Gohman817a7c62012-03-22 18:24:56 +00001867 MapVector<Value *, RRInfo> &Retains,
1868 BBState &MyStates) {
1869 bool NestingDetected = false;
1870 InstructionClass Class = GetInstructionClass(Inst);
1871 const Value *Arg = 0;
Michael Gottesman79249972013-04-05 23:46:45 +00001872
Michael Gottesman1d8d2572013-04-05 22:54:28 +00001873 DEBUG(dbgs() << "Class: " << Class << "\n");
Michael Gottesman79249972013-04-05 23:46:45 +00001874
Dan Gohman817a7c62012-03-22 18:24:56 +00001875 switch (Class) {
1876 case IC_Release: {
1877 Arg = GetObjCArg(Inst);
1878
1879 PtrState &S = MyStates.getPtrBottomUpState(Arg);
1880
1881 // If we see two releases in a row on the same pointer. If so, make
1882 // a note, and we'll cicle back to revisit it after we've
1883 // hopefully eliminated the second release, which may allow us to
1884 // eliminate the first release too.
1885 // Theoretically we could implement removal of nested retain+release
1886 // pairs by making PtrState hold a stack of states, but this is
1887 // simple and avoids adding overhead for the non-nested case.
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001888 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001889 DEBUG(dbgs() << "Found nested releases (i.e. a release pair)\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00001890 NestingDetected = true;
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001891 }
Dan Gohman817a7c62012-03-22 18:24:56 +00001892
Dan Gohman817a7c62012-03-22 18:24:56 +00001893 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001894 Sequence NewSeq = ReleaseMetadata ? S_MovableRelease : S_Release;
1895 ANNOTATE_BOTTOMUP(Inst, Arg, S.GetSeq(), NewSeq);
1896 S.ResetSequenceProgress(NewSeq);
Michael Gottesmanf701d3f2013-06-21 07:03:07 +00001897 S.SetReleaseMetadata(ReleaseMetadata);
Michael Gottesman93132252013-06-21 06:59:02 +00001898 S.SetKnownSafe(S.HasKnownPositiveRefCount());
Michael Gottesmanb82a1792013-06-21 07:00:44 +00001899 S.SetTailCallRelease(cast<CallInst>(Inst)->isTailCall());
Michael Gottesman4f6ef112013-06-21 19:44:27 +00001900 S.InsertCall(Inst);
Dan Gohmandf476e52012-09-04 23:16:20 +00001901 S.SetKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001902 break;
1903 }
1904 case IC_RetainBlock:
Michael Gottesman158fdf62013-03-28 20:11:19 +00001905 // In OptimizeIndividualCalls, we have strength reduced all optimizable
1906 // objc_retainBlocks to objc_retains. Thus at this point any
1907 // objc_retainBlocks that we see are not optimizable.
1908 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001909 case IC_Retain:
1910 case IC_RetainRV: {
1911 Arg = GetObjCArg(Inst);
1912
1913 PtrState &S = MyStates.getPtrBottomUpState(Arg);
Dan Gohman62079b42012-04-25 00:50:46 +00001914 S.SetKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001915
Michael Gottesman81b1d432013-03-26 00:42:04 +00001916 Sequence OldSeq = S.GetSeq();
1917 switch (OldSeq) {
Dan Gohman817a7c62012-03-22 18:24:56 +00001918 case S_Stop:
1919 case S_Release:
1920 case S_MovableRelease:
1921 case S_Use:
Michael Gottesman1d8d2572013-04-05 22:54:28 +00001922 // If OldSeq is not S_Use or OldSeq is S_Use and we are tracking an
1923 // imprecise release, clear our reverse insertion points.
Michael Gottesmanf0401182013-06-21 19:12:38 +00001924 if (OldSeq != S_Use || S.IsTrackingImpreciseReleases())
Michael Gottesman4f6ef112013-06-21 19:44:27 +00001925 S.ClearReverseInsertPts();
Dan Gohman817a7c62012-03-22 18:24:56 +00001926 // FALL THROUGH
1927 case S_CanRelease:
1928 // Don't do retain+release tracking for IC_RetainRV, because it's
1929 // better to let it remain as the first instruction after a call.
Michael Gottesmanba648592013-03-28 23:08:44 +00001930 if (Class != IC_RetainRV)
Michael Gottesmane3943d02013-06-21 19:44:30 +00001931 Retains[Inst] = S.GetRRInfo();
Dan Gohman817a7c62012-03-22 18:24:56 +00001932 S.ClearSequenceProgress();
1933 break;
1934 case S_None:
1935 break;
1936 case S_Retain:
1937 llvm_unreachable("bottom-up pointer in retain state!");
1938 }
Michael Gottesman79249972013-04-05 23:46:45 +00001939 ANNOTATE_BOTTOMUP(Inst, Arg, OldSeq, S.GetSeq());
Michael Gottesman31ba23a2013-04-05 22:54:32 +00001940 // A retain moving bottom up can be a use.
1941 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001942 }
1943 case IC_AutoreleasepoolPop:
1944 // Conservatively, clear MyStates for all known pointers.
1945 MyStates.clearBottomUpPointers();
1946 return NestingDetected;
1947 case IC_AutoreleasepoolPush:
1948 case IC_None:
1949 // These are irrelevant.
1950 return NestingDetected;
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001951 case IC_User:
1952 // If we have a store into an alloca of a pointer we are tracking, the
1953 // pointer has multiple owners implying that we must be more conservative.
1954 //
1955 // This comes up in the context of a pointer being ``KnownSafe''. In the
1956 // presense of a block being initialized, the frontend will emit the
1957 // objc_retain on the original pointer and the release on the pointer loaded
1958 // from the alloca. The optimizer will through the provenance analysis
1959 // realize that the two are related, but since we only require KnownSafe in
1960 // one direction, will match the inner retain on the original pointer with
1961 // the guard release on the original pointer. This is fixed by ensuring that
1962 // in the presense of allocas we only unconditionally remove pointers if
1963 // both our retain and our release are KnownSafe.
1964 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1965 if (AreAnyUnderlyingObjectsAnAlloca(SI->getPointerOperand())) {
1966 BBState::ptr_iterator I = MyStates.findPtrBottomUpState(
1967 StripPointerCastsAndObjCCalls(SI->getValueOperand()));
1968 if (I != MyStates.bottom_up_ptr_end())
Michael Gottesman5a91bbf2013-05-24 20:44:02 +00001969 MultiOwnersSet.insert(I->first);
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001970 }
1971 }
1972 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001973 default:
1974 break;
1975 }
1976
1977 // Consider any other possible effects of this instruction on each
1978 // pointer being tracked.
1979 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
1980 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
1981 const Value *Ptr = MI->first;
1982 if (Ptr == Arg)
1983 continue; // Handled above.
1984 PtrState &S = MI->second;
1985 Sequence Seq = S.GetSeq();
1986
1987 // Check for possible releases.
1988 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001989 DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr
1990 << "\n");
Michael Gottesman764b1cf2013-03-23 05:46:19 +00001991 S.ClearKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001992 switch (Seq) {
1993 case S_Use:
1994 S.SetSeq(S_CanRelease);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001995 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S.GetSeq());
Dan Gohman817a7c62012-03-22 18:24:56 +00001996 continue;
1997 case S_CanRelease:
1998 case S_Release:
1999 case S_MovableRelease:
2000 case S_Stop:
2001 case S_None:
2002 break;
2003 case S_Retain:
2004 llvm_unreachable("bottom-up pointer in retain state!");
2005 }
2006 }
2007
2008 // Check for possible direct uses.
2009 switch (Seq) {
2010 case S_Release:
2011 case S_MovableRelease:
2012 if (CanUse(Inst, Ptr, PA, Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002013 DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr
2014 << "\n");
Michael Gottesman4f6ef112013-06-21 19:44:27 +00002015 assert(!S.HasReverseInsertPts());
Dan Gohman5c70fad2012-03-23 17:47:54 +00002016 // If this is an invoke instruction, we're scanning it as part of
2017 // one of its successor blocks, since we can't insert code after it
2018 // in its own block, and we don't want to split critical edges.
2019 if (isa<InvokeInst>(Inst))
Michael Gottesman4f6ef112013-06-21 19:44:27 +00002020 S.InsertReverseInsertPt(BB->getFirstInsertionPt());
Dan Gohman5c70fad2012-03-23 17:47:54 +00002021 else
Michael Gottesman4f6ef112013-06-21 19:44:27 +00002022 S.InsertReverseInsertPt(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohman817a7c62012-03-22 18:24:56 +00002023 S.SetSeq(S_Use);
Michael Gottesman81b1d432013-03-26 00:42:04 +00002024 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
John McCall20182ac2013-03-22 21:38:36 +00002025 } else if (Seq == S_Release && IsUser(Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002026 DEBUG(dbgs() << "PreciseReleaseUse: Seq: " << Seq << "; " << *Ptr
2027 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00002028 // Non-movable releases depend on any possible objc pointer use.
2029 S.SetSeq(S_Stop);
Michael Gottesman81b1d432013-03-26 00:42:04 +00002030 ANNOTATE_BOTTOMUP(Inst, Ptr, S_Release, S_Stop);
Michael Gottesman4f6ef112013-06-21 19:44:27 +00002031 assert(!S.HasReverseInsertPts());
Dan Gohman5c70fad2012-03-23 17:47:54 +00002032 // As above; handle invoke specially.
2033 if (isa<InvokeInst>(Inst))
Michael Gottesman4f6ef112013-06-21 19:44:27 +00002034 S.InsertReverseInsertPt(BB->getFirstInsertionPt());
Dan Gohman5c70fad2012-03-23 17:47:54 +00002035 else
Michael Gottesman4f6ef112013-06-21 19:44:27 +00002036 S.InsertReverseInsertPt(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohman817a7c62012-03-22 18:24:56 +00002037 }
2038 break;
2039 case S_Stop:
Michael Gottesman81b1d432013-03-26 00:42:04 +00002040 if (CanUse(Inst, Ptr, PA, Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002041 DEBUG(dbgs() << "PreciseStopUse: Seq: " << Seq << "; " << *Ptr
2042 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00002043 S.SetSeq(S_Use);
Michael Gottesman81b1d432013-03-26 00:42:04 +00002044 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
2045 }
Dan Gohman817a7c62012-03-22 18:24:56 +00002046 break;
2047 case S_CanRelease:
2048 case S_Use:
2049 case S_None:
2050 break;
2051 case S_Retain:
2052 llvm_unreachable("bottom-up pointer in retain state!");
2053 }
2054 }
2055
2056 return NestingDetected;
2057}
2058
2059bool
John McCalld935e9c2011-06-15 23:37:01 +00002060ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2061 DenseMap<const BasicBlock *, BBState> &BBStates,
2062 MapVector<Value *, RRInfo> &Retains) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002063
2064 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitBottomUp ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00002065
John McCalld935e9c2011-06-15 23:37:01 +00002066 bool NestingDetected = false;
2067 BBState &MyStates = BBStates[BB];
2068
2069 // Merge the states from each successor to compute the initial state
2070 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00002071 BBState::edge_iterator SI(MyStates.succ_begin()),
2072 SE(MyStates.succ_end());
2073 if (SI != SE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002074 const BasicBlock *Succ = *SI;
2075 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
2076 assert(I != BBStates.end());
2077 MyStates.InitFromSucc(I->second);
2078 ++SI;
2079 for (; SI != SE; ++SI) {
2080 Succ = *SI;
2081 I = BBStates.find(Succ);
2082 assert(I != BBStates.end());
2083 MyStates.MergeSucc(I->second);
2084 }
Michael Gottesman60f6b282013-03-29 05:13:07 +00002085 }
Michael Gottesmancd4de0f2013-03-26 00:42:09 +00002086
Michael Gottesman43e7e002013-04-03 22:41:59 +00002087 // If ARC Annotations are enabled, output the current state of pointers at the
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002088 // bottom of the basic block.
Michael Gottesman43e7e002013-04-03 22:41:59 +00002089 ANNOTATE_BOTTOMUP_BBEND(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002090
John McCalld935e9c2011-06-15 23:37:01 +00002091 // Visit all the instructions, bottom-up.
2092 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2093 Instruction *Inst = llvm::prior(I);
Dan Gohman5c70fad2012-03-23 17:47:54 +00002094
2095 // Invoke instructions are visited as part of their successors (below).
2096 if (isa<InvokeInst>(Inst))
2097 continue;
2098
Michael Gottesman89279f82013-04-05 18:10:41 +00002099 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00002100
Dan Gohman5c70fad2012-03-23 17:47:54 +00002101 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
2102 }
2103
Dan Gohmandae33492012-04-27 18:56:31 +00002104 // If there's a predecessor with an invoke, visit the invoke as if it were
2105 // part of this block, since we can't insert code after an invoke in its own
2106 // block, and we don't want to split critical edges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002107 for (BBState::edge_iterator PI(MyStates.pred_begin()),
2108 PE(MyStates.pred_end()); PI != PE; ++PI) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00002109 BasicBlock *Pred = *PI;
Dan Gohmandae33492012-04-27 18:56:31 +00002110 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
2111 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
Dan Gohman817a7c62012-03-22 18:24:56 +00002112 }
John McCalld935e9c2011-06-15 23:37:01 +00002113
Michael Gottesman43e7e002013-04-03 22:41:59 +00002114 // If ARC Annotations are enabled, output the current state of pointers at the
2115 // top of the basic block.
2116 ANNOTATE_BOTTOMUP_BBSTART(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002117
Dan Gohman817a7c62012-03-22 18:24:56 +00002118 return NestingDetected;
2119}
John McCalld935e9c2011-06-15 23:37:01 +00002120
Dan Gohman817a7c62012-03-22 18:24:56 +00002121bool
2122ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
2123 DenseMap<Value *, RRInfo> &Releases,
2124 BBState &MyStates) {
2125 bool NestingDetected = false;
2126 InstructionClass Class = GetInstructionClass(Inst);
2127 const Value *Arg = 0;
John McCalld935e9c2011-06-15 23:37:01 +00002128
Dan Gohman817a7c62012-03-22 18:24:56 +00002129 switch (Class) {
2130 case IC_RetainBlock:
Michael Gottesman158fdf62013-03-28 20:11:19 +00002131 // In OptimizeIndividualCalls, we have strength reduced all optimizable
2132 // objc_retainBlocks to objc_retains. Thus at this point any
2133 // objc_retainBlocks that we see are not optimizable.
2134 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00002135 case IC_Retain:
2136 case IC_RetainRV: {
2137 Arg = GetObjCArg(Inst);
2138
2139 PtrState &S = MyStates.getPtrTopDownState(Arg);
2140
2141 // Don't do retain+release tracking for IC_RetainRV, because it's
2142 // better to let it remain as the first instruction after a call.
2143 if (Class != IC_RetainRV) {
2144 // If we see two retains in a row on the same pointer. If so, make
John McCalld935e9c2011-06-15 23:37:01 +00002145 // a note, and we'll cicle back to revisit it after we've
Dan Gohman817a7c62012-03-22 18:24:56 +00002146 // hopefully eliminated the second retain, which may allow us to
2147 // eliminate the first retain too.
John McCalld935e9c2011-06-15 23:37:01 +00002148 // Theoretically we could implement removal of nested retain+release
2149 // pairs by making PtrState hold a stack of states, but this is
2150 // simple and avoids adding overhead for the non-nested case.
Dan Gohman817a7c62012-03-22 18:24:56 +00002151 if (S.GetSeq() == S_Retain)
John McCalld935e9c2011-06-15 23:37:01 +00002152 NestingDetected = true;
2153
Michael Gottesman81b1d432013-03-26 00:42:04 +00002154 ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_Retain);
Dan Gohman62079b42012-04-25 00:50:46 +00002155 S.ResetSequenceProgress(S_Retain);
Michael Gottesman93132252013-06-21 06:59:02 +00002156 S.SetKnownSafe(S.HasKnownPositiveRefCount());
Michael Gottesman4f6ef112013-06-21 19:44:27 +00002157 S.InsertCall(Inst);
John McCalld935e9c2011-06-15 23:37:01 +00002158 }
John McCalld935e9c2011-06-15 23:37:01 +00002159
Dan Gohmandf476e52012-09-04 23:16:20 +00002160 S.SetKnownPositiveRefCount();
Dan Gohmanf64ff8e2012-07-23 19:27:31 +00002161
2162 // A retain can be a potential use; procede to the generic checking
2163 // code below.
2164 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00002165 }
2166 case IC_Release: {
2167 Arg = GetObjCArg(Inst);
2168
2169 PtrState &S = MyStates.getPtrTopDownState(Arg);
Michael Gottesman764b1cf2013-03-23 05:46:19 +00002170 S.ClearKnownPositiveRefCount();
Michael Gottesman79249972013-04-05 23:46:45 +00002171
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002172 Sequence OldSeq = S.GetSeq();
Michael Gottesman79249972013-04-05 23:46:45 +00002173
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002174 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
Michael Gottesman79249972013-04-05 23:46:45 +00002175
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002176 switch (OldSeq) {
Dan Gohman817a7c62012-03-22 18:24:56 +00002177 case S_Retain:
2178 case S_CanRelease:
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002179 if (OldSeq == S_Retain || ReleaseMetadata != 0)
Michael Gottesman4f6ef112013-06-21 19:44:27 +00002180 S.ClearReverseInsertPts();
Dan Gohman817a7c62012-03-22 18:24:56 +00002181 // FALL THROUGH
2182 case S_Use:
Michael Gottesmanf701d3f2013-06-21 07:03:07 +00002183 S.SetReleaseMetadata(ReleaseMetadata);
Michael Gottesmanb82a1792013-06-21 07:00:44 +00002184 S.SetTailCallRelease(cast<CallInst>(Inst)->isTailCall());
Michael Gottesmane3943d02013-06-21 19:44:30 +00002185 Releases[Inst] = S.GetRRInfo();
Michael Gottesman81b1d432013-03-26 00:42:04 +00002186 ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_None);
Dan Gohman817a7c62012-03-22 18:24:56 +00002187 S.ClearSequenceProgress();
2188 break;
2189 case S_None:
2190 break;
2191 case S_Stop:
2192 case S_Release:
2193 case S_MovableRelease:
2194 llvm_unreachable("top-down pointer in release state!");
2195 }
2196 break;
2197 }
2198 case IC_AutoreleasepoolPop:
2199 // Conservatively, clear MyStates for all known pointers.
2200 MyStates.clearTopDownPointers();
2201 return NestingDetected;
2202 case IC_AutoreleasepoolPush:
2203 case IC_None:
2204 // These are irrelevant.
2205 return NestingDetected;
2206 default:
2207 break;
2208 }
2209
2210 // Consider any other possible effects of this instruction on each
2211 // pointer being tracked.
2212 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
2213 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
2214 const Value *Ptr = MI->first;
2215 if (Ptr == Arg)
2216 continue; // Handled above.
2217 PtrState &S = MI->second;
2218 Sequence Seq = S.GetSeq();
2219
2220 // Check for possible releases.
2221 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Michael Gottesmanbab49e972013-04-05 18:26:08 +00002222 DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr
Michael Gottesman79249972013-04-05 23:46:45 +00002223 << "\n");
Michael Gottesman764b1cf2013-03-23 05:46:19 +00002224 S.ClearKnownPositiveRefCount();
John McCalld935e9c2011-06-15 23:37:01 +00002225 switch (Seq) {
Dan Gohman817a7c62012-03-22 18:24:56 +00002226 case S_Retain:
2227 S.SetSeq(S_CanRelease);
Michael Gottesman81b1d432013-03-26 00:42:04 +00002228 ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_CanRelease);
Michael Gottesman4f6ef112013-06-21 19:44:27 +00002229 assert(!S.HasReverseInsertPts());
2230 S.InsertReverseInsertPt(Inst);
Dan Gohman817a7c62012-03-22 18:24:56 +00002231
2232 // One call can't cause a transition from S_Retain to S_CanRelease
2233 // and S_CanRelease to S_Use. If we've made the first transition,
2234 // we're done.
2235 continue;
John McCalld935e9c2011-06-15 23:37:01 +00002236 case S_Use:
Dan Gohman817a7c62012-03-22 18:24:56 +00002237 case S_CanRelease:
John McCalld935e9c2011-06-15 23:37:01 +00002238 case S_None:
2239 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00002240 case S_Stop:
2241 case S_Release:
2242 case S_MovableRelease:
2243 llvm_unreachable("top-down pointer in release state!");
John McCalld935e9c2011-06-15 23:37:01 +00002244 }
2245 }
Dan Gohman817a7c62012-03-22 18:24:56 +00002246
2247 // Check for possible direct uses.
2248 switch (Seq) {
2249 case S_CanRelease:
Michael Gottesman81b1d432013-03-26 00:42:04 +00002250 if (CanUse(Inst, Ptr, PA, Class)) {
Michael Gottesmanbab49e972013-04-05 18:26:08 +00002251 DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr
2252 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00002253 S.SetSeq(S_Use);
Michael Gottesman81b1d432013-03-26 00:42:04 +00002254 ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_Use);
2255 }
Dan Gohman817a7c62012-03-22 18:24:56 +00002256 break;
2257 case S_Retain:
2258 case S_Use:
2259 case S_None:
2260 break;
2261 case S_Stop:
2262 case S_Release:
2263 case S_MovableRelease:
2264 llvm_unreachable("top-down pointer in release state!");
2265 }
John McCalld935e9c2011-06-15 23:37:01 +00002266 }
2267
2268 return NestingDetected;
2269}
2270
2271bool
2272ObjCARCOpt::VisitTopDown(BasicBlock *BB,
2273 DenseMap<const BasicBlock *, BBState> &BBStates,
2274 DenseMap<Value *, RRInfo> &Releases) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002275 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitTopDown ==\n");
John McCalld935e9c2011-06-15 23:37:01 +00002276 bool NestingDetected = false;
2277 BBState &MyStates = BBStates[BB];
2278
2279 // Merge the states from each predecessor to compute the initial state
2280 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00002281 BBState::edge_iterator PI(MyStates.pred_begin()),
2282 PE(MyStates.pred_end());
2283 if (PI != PE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002284 const BasicBlock *Pred = *PI;
2285 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
2286 assert(I != BBStates.end());
2287 MyStates.InitFromPred(I->second);
2288 ++PI;
2289 for (; PI != PE; ++PI) {
2290 Pred = *PI;
2291 I = BBStates.find(Pred);
2292 assert(I != BBStates.end());
2293 MyStates.MergePred(I->second);
2294 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002295 }
John McCalld935e9c2011-06-15 23:37:01 +00002296
Michael Gottesman43e7e002013-04-03 22:41:59 +00002297 // If ARC Annotations are enabled, output the current state of pointers at the
2298 // top of the basic block.
2299 ANNOTATE_TOPDOWN_BBSTART(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002300
John McCalld935e9c2011-06-15 23:37:01 +00002301 // Visit all the instructions, top-down.
2302 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2303 Instruction *Inst = I;
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00002304
Michael Gottesman89279f82013-04-05 18:10:41 +00002305 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00002306
Dan Gohman817a7c62012-03-22 18:24:56 +00002307 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00002308 }
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002309
Michael Gottesman43e7e002013-04-03 22:41:59 +00002310 // If ARC Annotations are enabled, output the current state of pointers at the
2311 // bottom of the basic block.
2312 ANNOTATE_TOPDOWN_BBEND(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002313
Michael Gottesmanffef24f2013-04-17 20:48:01 +00002314#ifdef ARC_ANNOTATIONS
Michael Gottesmanadb921a2013-04-17 21:03:53 +00002315 if (!(EnableARCAnnotations && DisableCheckForCFGHazards))
Michael Gottesmanffef24f2013-04-17 20:48:01 +00002316#endif
John McCalld935e9c2011-06-15 23:37:01 +00002317 CheckForCFGHazards(BB, BBStates, MyStates);
2318 return NestingDetected;
2319}
2320
Dan Gohmana53a12c2011-12-12 19:42:25 +00002321static void
2322ComputePostOrders(Function &F,
2323 SmallVectorImpl<BasicBlock *> &PostOrder,
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002324 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
2325 unsigned NoObjCARCExceptionsMDKind,
2326 DenseMap<const BasicBlock *, BBState> &BBStates) {
Michael Gottesman97e3df02013-01-14 00:35:14 +00002327 /// The visited set, for doing DFS walks.
Dan Gohmana53a12c2011-12-12 19:42:25 +00002328 SmallPtrSet<BasicBlock *, 16> Visited;
2329
2330 // Do DFS, computing the PostOrder.
2331 SmallPtrSet<BasicBlock *, 16> OnStack;
2332 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002333
2334 // Functions always have exactly one entry block, and we don't have
2335 // any other block that we treat like an entry block.
Dan Gohmana53a12c2011-12-12 19:42:25 +00002336 BasicBlock *EntryBB = &F.getEntryBlock();
Dan Gohman41375a32012-05-08 23:39:44 +00002337 BBState &MyStates = BBStates[EntryBB];
2338 MyStates.SetAsEntry();
2339 TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
2340 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
Dan Gohmana53a12c2011-12-12 19:42:25 +00002341 Visited.insert(EntryBB);
2342 OnStack.insert(EntryBB);
2343 do {
2344 dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002345 BasicBlock *CurrBB = SuccStack.back().first;
2346 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
2347 succ_iterator SE(TI, false);
Dan Gohman41375a32012-05-08 23:39:44 +00002348
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002349 while (SuccStack.back().second != SE) {
2350 BasicBlock *SuccBB = *SuccStack.back().second++;
2351 if (Visited.insert(SuccBB)) {
Dan Gohman41375a32012-05-08 23:39:44 +00002352 TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
2353 SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002354 BBStates[CurrBB].addSucc(SuccBB);
Dan Gohman41375a32012-05-08 23:39:44 +00002355 BBState &SuccStates = BBStates[SuccBB];
2356 SuccStates.addPred(CurrBB);
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002357 OnStack.insert(SuccBB);
Dan Gohmana53a12c2011-12-12 19:42:25 +00002358 goto dfs_next_succ;
2359 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002360
2361 if (!OnStack.count(SuccBB)) {
2362 BBStates[CurrBB].addSucc(SuccBB);
2363 BBStates[SuccBB].addPred(CurrBB);
2364 }
Dan Gohmana53a12c2011-12-12 19:42:25 +00002365 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002366 OnStack.erase(CurrBB);
2367 PostOrder.push_back(CurrBB);
2368 SuccStack.pop_back();
Dan Gohmana53a12c2011-12-12 19:42:25 +00002369 } while (!SuccStack.empty());
2370
2371 Visited.clear();
2372
Dan Gohmana53a12c2011-12-12 19:42:25 +00002373 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002374 // Functions may have many exits, and there also blocks which we treat
2375 // as exits due to ignored edges.
2376 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
2377 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
2378 BasicBlock *ExitBB = I;
2379 BBState &MyStates = BBStates[ExitBB];
2380 if (!MyStates.isExit())
2381 continue;
2382
Dan Gohmandae33492012-04-27 18:56:31 +00002383 MyStates.SetAsExit();
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002384
2385 PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00002386 Visited.insert(ExitBB);
2387 while (!PredStack.empty()) {
2388 reverse_dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002389 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
2390 while (PredStack.back().second != PE) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00002391 BasicBlock *BB = *PredStack.back().second++;
Dan Gohmana53a12c2011-12-12 19:42:25 +00002392 if (Visited.insert(BB)) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002393 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00002394 goto reverse_dfs_next_succ;
2395 }
2396 }
2397 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
2398 }
2399 }
2400}
2401
Michael Gottesman97e3df02013-01-14 00:35:14 +00002402// Visit the function both top-down and bottom-up.
John McCalld935e9c2011-06-15 23:37:01 +00002403bool
2404ObjCARCOpt::Visit(Function &F,
2405 DenseMap<const BasicBlock *, BBState> &BBStates,
2406 MapVector<Value *, RRInfo> &Retains,
2407 DenseMap<Value *, RRInfo> &Releases) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00002408
2409 // Use reverse-postorder traversals, because we magically know that loops
2410 // will be well behaved, i.e. they won't repeatedly call retain on a single
2411 // pointer without doing a release. We can't use the ReversePostOrderTraversal
2412 // class here because we want the reverse-CFG postorder to consider each
2413 // function exit point, and we want to ignore selected cycle edges.
2414 SmallVector<BasicBlock *, 16> PostOrder;
2415 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002416 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
2417 NoObjCARCExceptionsMDKind,
2418 BBStates);
Dan Gohmana53a12c2011-12-12 19:42:25 +00002419
2420 // Use reverse-postorder on the reverse CFG for bottom-up.
John McCalld935e9c2011-06-15 23:37:01 +00002421 bool BottomUpNestingDetected = false;
Dan Gohmanc57b58c2011-08-18 21:27:42 +00002422 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
Dan Gohmana53a12c2011-12-12 19:42:25 +00002423 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
2424 I != E; ++I)
2425 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
John McCalld935e9c2011-06-15 23:37:01 +00002426
Dan Gohmana53a12c2011-12-12 19:42:25 +00002427 // Use reverse-postorder for top-down.
John McCalld935e9c2011-06-15 23:37:01 +00002428 bool TopDownNestingDetected = false;
Dan Gohmana53a12c2011-12-12 19:42:25 +00002429 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2430 PostOrder.rbegin(), E = PostOrder.rend();
2431 I != E; ++I)
2432 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
John McCalld935e9c2011-06-15 23:37:01 +00002433
2434 return TopDownNestingDetected && BottomUpNestingDetected;
2435}
2436
Michael Gottesman97e3df02013-01-14 00:35:14 +00002437/// Move the calls in RetainsToMove and ReleasesToMove.
John McCalld935e9c2011-06-15 23:37:01 +00002438void ObjCARCOpt::MoveCalls(Value *Arg,
2439 RRInfo &RetainsToMove,
2440 RRInfo &ReleasesToMove,
2441 MapVector<Value *, RRInfo> &Retains,
2442 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman6320f522011-07-22 22:29:21 +00002443 SmallVectorImpl<Instruction *> &DeadInsts,
Michael Gottesman79249972013-04-05 23:46:45 +00002444 Module *M) {
Chris Lattner229907c2011-07-18 04:54:35 +00002445 Type *ArgTy = Arg->getType();
Dan Gohman6320f522011-07-22 22:29:21 +00002446 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
Michael Gottesman79249972013-04-05 23:46:45 +00002447
Michael Gottesman89279f82013-04-05 18:10:41 +00002448 DEBUG(dbgs() << "== ObjCARCOpt::MoveCalls ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00002449
John McCalld935e9c2011-06-15 23:37:01 +00002450 // Insert the new retain and release calls.
2451 for (SmallPtrSet<Instruction *, 2>::const_iterator
2452 PI = ReleasesToMove.ReverseInsertPts.begin(),
2453 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2454 Instruction *InsertPt = *PI;
2455 Value *MyArg = ArgTy == ParamTy ? Arg :
2456 new BitCastInst(Arg, ParamTy, "", InsertPt);
Michael Gottesman14acfac2013-07-06 01:39:23 +00002457 Constant *Decl = EP.get(ARCRuntimeEntryPoints::EPT_Retain);
2458 CallInst *Call = CallInst::Create(Decl, MyArg, "", InsertPt);
John McCalld935e9c2011-06-15 23:37:01 +00002459 Call->setDoesNotThrow();
Michael Gottesmanba648592013-03-28 23:08:44 +00002460 Call->setTailCall();
Michael Gottesman60f6b282013-03-29 05:13:07 +00002461
Michael Gottesmandf110ac2013-04-21 00:30:50 +00002462 DEBUG(dbgs() << "Inserting new Retain: " << *Call << "\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00002463 "At insertion point: " << *InsertPt << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002464 }
2465 for (SmallPtrSet<Instruction *, 2>::const_iterator
2466 PI = RetainsToMove.ReverseInsertPts.begin(),
2467 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00002468 Instruction *InsertPt = *PI;
2469 Value *MyArg = ArgTy == ParamTy ? Arg :
2470 new BitCastInst(Arg, ParamTy, "", InsertPt);
Michael Gottesman14acfac2013-07-06 01:39:23 +00002471 Constant *Decl = EP.get(ARCRuntimeEntryPoints::EPT_Release);
2472 CallInst *Call = CallInst::Create(Decl, MyArg, "", InsertPt);
Dan Gohman5c70fad2012-03-23 17:47:54 +00002473 // Attach a clang.imprecise_release metadata tag, if appropriate.
2474 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
2475 Call->setMetadata(ImpreciseReleaseMDKind, M);
2476 Call->setDoesNotThrow();
2477 if (ReleasesToMove.IsTailCallRelease)
2478 Call->setTailCall();
Michael Gottesmanc189a392013-01-09 19:23:24 +00002479
Michael Gottesman89279f82013-04-05 18:10:41 +00002480 DEBUG(dbgs() << "Inserting new Release: " << *Call << "\n"
2481 "At insertion point: " << *InsertPt << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002482 }
2483
2484 // Delete the original retain and release calls.
2485 for (SmallPtrSet<Instruction *, 2>::const_iterator
2486 AI = RetainsToMove.Calls.begin(),
2487 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
2488 Instruction *OrigRetain = *AI;
2489 Retains.blot(OrigRetain);
2490 DeadInsts.push_back(OrigRetain);
Michael Gottesman89279f82013-04-05 18:10:41 +00002491 DEBUG(dbgs() << "Deleting retain: " << *OrigRetain << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002492 }
2493 for (SmallPtrSet<Instruction *, 2>::const_iterator
2494 AI = ReleasesToMove.Calls.begin(),
2495 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
2496 Instruction *OrigRelease = *AI;
2497 Releases.erase(OrigRelease);
2498 DeadInsts.push_back(OrigRelease);
Michael Gottesman89279f82013-04-05 18:10:41 +00002499 DEBUG(dbgs() << "Deleting release: " << *OrigRelease << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002500 }
Michael Gottesman79249972013-04-05 23:46:45 +00002501
John McCalld935e9c2011-06-15 23:37:01 +00002502}
2503
Michael Gottesman9de6f962013-01-22 21:49:00 +00002504bool
2505ObjCARCOpt::ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState>
2506 &BBStates,
2507 MapVector<Value *, RRInfo> &Retains,
2508 DenseMap<Value *, RRInfo> &Releases,
2509 Module *M,
Craig Topperb94011f2013-07-14 04:42:23 +00002510 SmallVectorImpl<Instruction *> &NewRetains,
2511 SmallVectorImpl<Instruction *> &NewReleases,
2512 SmallVectorImpl<Instruction *> &DeadInsts,
Michael Gottesman9de6f962013-01-22 21:49:00 +00002513 RRInfo &RetainsToMove,
2514 RRInfo &ReleasesToMove,
2515 Value *Arg,
2516 bool KnownSafe,
2517 bool &AnyPairsCompletelyEliminated) {
2518 // If a pair happens in a region where it is known that the reference count
Michael Gottesmana76143ee2013-05-13 23:49:42 +00002519 // is already incremented, we can similarly ignore possible decrements unless
2520 // we are dealing with a retainable object with multiple provenance sources.
Michael Gottesman9de6f962013-01-22 21:49:00 +00002521 bool KnownSafeTD = true, KnownSafeBU = true;
Michael Gottesmana76143ee2013-05-13 23:49:42 +00002522 bool MultipleOwners = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00002523 bool CFGHazardAfflicted = false;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002524
2525 // Connect the dots between the top-down-collected RetainsToMove and
2526 // bottom-up-collected ReleasesToMove to form sets of related calls.
2527 // This is an iterative process so that we connect multiple releases
2528 // to multiple retains if needed.
2529 unsigned OldDelta = 0;
2530 unsigned NewDelta = 0;
2531 unsigned OldCount = 0;
2532 unsigned NewCount = 0;
2533 bool FirstRelease = true;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002534 for (;;) {
2535 for (SmallVectorImpl<Instruction *>::const_iterator
2536 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
2537 Instruction *NewRetain = *NI;
2538 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
2539 assert(It != Retains.end());
2540 const RRInfo &NewRetainRRI = It->second;
2541 KnownSafeTD &= NewRetainRRI.KnownSafe;
Michael Gottesman5a91bbf2013-05-24 20:44:02 +00002542 MultipleOwners =
2543 MultipleOwners || MultiOwnersSet.count(GetObjCArg(NewRetain));
Michael Gottesman9de6f962013-01-22 21:49:00 +00002544 for (SmallPtrSet<Instruction *, 2>::const_iterator
2545 LI = NewRetainRRI.Calls.begin(),
2546 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
2547 Instruction *NewRetainRelease = *LI;
2548 DenseMap<Value *, RRInfo>::const_iterator Jt =
2549 Releases.find(NewRetainRelease);
2550 if (Jt == Releases.end())
2551 return false;
2552 const RRInfo &NewRetainReleaseRRI = Jt->second;
2553 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
2554 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002555
2556 // If we overflow when we compute the path count, don't remove/move
2557 // anything.
2558 const BBState &NRRBBState = BBStates[NewRetainRelease->getParent()];
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00002559 unsigned PathCount = BBState::OverflowOccurredValue;
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002560 if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
2561 return false;
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00002562 assert(PathCount != BBState::OverflowOccurredValue &&
2563 "PathCount at this point can not be "
2564 "OverflowOccurredValue.");
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002565 OldDelta -= PathCount;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002566
2567 // Merge the ReleaseMetadata and IsTailCallRelease values.
2568 if (FirstRelease) {
2569 ReleasesToMove.ReleaseMetadata =
2570 NewRetainReleaseRRI.ReleaseMetadata;
2571 ReleasesToMove.IsTailCallRelease =
2572 NewRetainReleaseRRI.IsTailCallRelease;
2573 FirstRelease = false;
2574 } else {
2575 if (ReleasesToMove.ReleaseMetadata !=
2576 NewRetainReleaseRRI.ReleaseMetadata)
2577 ReleasesToMove.ReleaseMetadata = 0;
2578 if (ReleasesToMove.IsTailCallRelease !=
2579 NewRetainReleaseRRI.IsTailCallRelease)
2580 ReleasesToMove.IsTailCallRelease = false;
2581 }
2582
2583 // Collect the optimal insertion points.
2584 if (!KnownSafe)
2585 for (SmallPtrSet<Instruction *, 2>::const_iterator
2586 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
2587 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
2588 RI != RE; ++RI) {
2589 Instruction *RIP = *RI;
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002590 if (ReleasesToMove.ReverseInsertPts.insert(RIP)) {
2591 // If we overflow when we compute the path count, don't
2592 // remove/move anything.
2593 const BBState &RIPBBState = BBStates[RIP->getParent()];
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00002594 PathCount = BBState::OverflowOccurredValue;
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002595 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
2596 return false;
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00002597 assert(PathCount != BBState::OverflowOccurredValue &&
2598 "PathCount at this point can not be "
2599 "OverflowOccurredValue.");
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002600 NewDelta -= PathCount;
2601 }
Michael Gottesman9de6f962013-01-22 21:49:00 +00002602 }
2603 NewReleases.push_back(NewRetainRelease);
2604 }
2605 }
2606 }
2607 NewRetains.clear();
2608 if (NewReleases.empty()) break;
2609
2610 // Back the other way.
2611 for (SmallVectorImpl<Instruction *>::const_iterator
2612 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
2613 Instruction *NewRelease = *NI;
2614 DenseMap<Value *, RRInfo>::const_iterator It =
2615 Releases.find(NewRelease);
2616 assert(It != Releases.end());
2617 const RRInfo &NewReleaseRRI = It->second;
2618 KnownSafeBU &= NewReleaseRRI.KnownSafe;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00002619 CFGHazardAfflicted |= NewReleaseRRI.CFGHazardAfflicted;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002620 for (SmallPtrSet<Instruction *, 2>::const_iterator
2621 LI = NewReleaseRRI.Calls.begin(),
2622 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
2623 Instruction *NewReleaseRetain = *LI;
2624 MapVector<Value *, RRInfo>::const_iterator Jt =
2625 Retains.find(NewReleaseRetain);
2626 if (Jt == Retains.end())
2627 return false;
2628 const RRInfo &NewReleaseRetainRRI = Jt->second;
2629 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
2630 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002631
2632 // If we overflow when we compute the path count, don't remove/move
2633 // anything.
2634 const BBState &NRRBBState = BBStates[NewReleaseRetain->getParent()];
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00002635 unsigned PathCount = BBState::OverflowOccurredValue;
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002636 if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
2637 return false;
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00002638 assert(PathCount != BBState::OverflowOccurredValue &&
2639 "PathCount at this point can not be "
2640 "OverflowOccurredValue.");
Michael Gottesman9de6f962013-01-22 21:49:00 +00002641 OldDelta += PathCount;
2642 OldCount += PathCount;
2643
Michael Gottesman9de6f962013-01-22 21:49:00 +00002644 // Collect the optimal insertion points.
2645 if (!KnownSafe)
2646 for (SmallPtrSet<Instruction *, 2>::const_iterator
2647 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
2648 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
2649 RI != RE; ++RI) {
2650 Instruction *RIP = *RI;
2651 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002652 // If we overflow when we compute the path count, don't
2653 // remove/move anything.
2654 const BBState &RIPBBState = BBStates[RIP->getParent()];
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00002655
2656 PathCount = BBState::OverflowOccurredValue;
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002657 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
2658 return false;
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00002659 assert(PathCount != BBState::OverflowOccurredValue &&
2660 "PathCount at this point can not be "
2661 "OverflowOccurredValue.");
Michael Gottesman9de6f962013-01-22 21:49:00 +00002662 NewDelta += PathCount;
2663 NewCount += PathCount;
2664 }
2665 }
2666 NewRetains.push_back(NewReleaseRetain);
2667 }
2668 }
2669 }
2670 NewReleases.clear();
2671 if (NewRetains.empty()) break;
2672 }
2673
Michael Gottesmana76143ee2013-05-13 23:49:42 +00002674 // If the pointer is known incremented in 1 direction and we do not have
2675 // MultipleOwners, we can safely remove the retain/releases. Otherwise we need
2676 // to be known safe in both directions.
2677 bool UnconditionallySafe = (KnownSafeTD && KnownSafeBU) ||
2678 ((KnownSafeTD || KnownSafeBU) && !MultipleOwners);
2679 if (UnconditionallySafe) {
Michael Gottesman9de6f962013-01-22 21:49:00 +00002680 RetainsToMove.ReverseInsertPts.clear();
2681 ReleasesToMove.ReverseInsertPts.clear();
2682 NewCount = 0;
2683 } else {
2684 // Determine whether the new insertion points we computed preserve the
2685 // balance of retain and release calls through the program.
2686 // TODO: If the fully aggressive solution isn't valid, try to find a
2687 // less aggressive solution which is.
2688 if (NewDelta != 0)
2689 return false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00002690
2691 // At this point, we are not going to remove any RR pairs, but we still are
2692 // able to move RR pairs. If one of our pointers is afflicted with
2693 // CFGHazards, we cannot perform such code motion so exit early.
2694 const bool WillPerformCodeMotion = RetainsToMove.ReverseInsertPts.size() ||
2695 ReleasesToMove.ReverseInsertPts.size();
2696 if (CFGHazardAfflicted && WillPerformCodeMotion)
2697 return false;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002698 }
2699
2700 // Determine whether the original call points are balanced in the retain and
2701 // release calls through the program. If not, conservatively don't touch
2702 // them.
2703 // TODO: It's theoretically possible to do code motion in this case, as
2704 // long as the existing imbalances are maintained.
2705 if (OldDelta != 0)
2706 return false;
Michael Gottesman8005ad32013-04-29 06:16:55 +00002707
Michael Gottesmana87bb8f2013-04-29 05:13:13 +00002708#ifdef ARC_ANNOTATIONS
2709 // Do not move calls if ARC annotations are requested.
Michael Gottesman3e3977c2013-04-29 05:25:39 +00002710 if (EnableARCAnnotations)
2711 return false;
Michael Gottesmana87bb8f2013-04-29 05:13:13 +00002712#endif // ARC_ANNOTATIONS
Michael Gottesman9de6f962013-01-22 21:49:00 +00002713
2714 Changed = true;
2715 assert(OldCount != 0 && "Unreachable code?");
2716 NumRRs += OldCount - NewCount;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002717 // Set to true if we completely removed any RR pairs.
Michael Gottesman8b5515f2013-01-22 21:53:43 +00002718 AnyPairsCompletelyEliminated = NewCount == 0;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002719
2720 // We can move calls!
2721 return true;
2722}
2723
Michael Gottesman97e3df02013-01-14 00:35:14 +00002724/// Identify pairings between the retains and releases, and delete and/or move
2725/// them.
John McCalld935e9c2011-06-15 23:37:01 +00002726bool
2727ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
2728 &BBStates,
2729 MapVector<Value *, RRInfo> &Retains,
Dan Gohman6320f522011-07-22 22:29:21 +00002730 DenseMap<Value *, RRInfo> &Releases,
2731 Module *M) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002732 DEBUG(dbgs() << "\n== ObjCARCOpt::PerformCodePlacement ==\n");
2733
John McCalld935e9c2011-06-15 23:37:01 +00002734 bool AnyPairsCompletelyEliminated = false;
2735 RRInfo RetainsToMove;
2736 RRInfo ReleasesToMove;
2737 SmallVector<Instruction *, 4> NewRetains;
2738 SmallVector<Instruction *, 4> NewReleases;
2739 SmallVector<Instruction *, 8> DeadInsts;
2740
Dan Gohman670f9372012-04-13 18:57:48 +00002741 // Visit each retain.
John McCalld935e9c2011-06-15 23:37:01 +00002742 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
Dan Gohman2053a5d2011-09-29 22:25:23 +00002743 E = Retains.end(); I != E; ++I) {
2744 Value *V = I->first;
John McCalld935e9c2011-06-15 23:37:01 +00002745 if (!V) continue; // blotted
2746
2747 Instruction *Retain = cast<Instruction>(V);
Michael Gottesmanc189a392013-01-09 19:23:24 +00002748
Michael Gottesman89279f82013-04-05 18:10:41 +00002749 DEBUG(dbgs() << "Visiting: " << *Retain << "\n");
Michael Gottesmanc189a392013-01-09 19:23:24 +00002750
John McCalld935e9c2011-06-15 23:37:01 +00002751 Value *Arg = GetObjCArg(Retain);
2752
Dan Gohman728db492012-01-13 00:39:07 +00002753 // If the object being released is in static or stack storage, we know it's
John McCalld935e9c2011-06-15 23:37:01 +00002754 // not being managed by ObjC reference counting, so we can delete pairs
2755 // regardless of what possible decrements or uses lie between them.
Dan Gohman728db492012-01-13 00:39:07 +00002756 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
Dan Gohman41375a32012-05-08 23:39:44 +00002757
Dan Gohman56e1cef2011-08-22 17:29:11 +00002758 // A constant pointer can't be pointing to an object on the heap. It may
2759 // be reference-counted, but it won't be deleted.
2760 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
2761 if (const GlobalVariable *GV =
2762 dyn_cast<GlobalVariable>(
2763 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
2764 if (GV->isConstant())
2765 KnownSafe = true;
2766
John McCalld935e9c2011-06-15 23:37:01 +00002767 // Connect the dots between the top-down-collected RetainsToMove and
2768 // bottom-up-collected ReleasesToMove to form sets of related calls.
John McCalld935e9c2011-06-15 23:37:01 +00002769 NewRetains.push_back(Retain);
Michael Gottesman9de6f962013-01-22 21:49:00 +00002770 bool PerformMoveCalls =
2771 ConnectTDBUTraversals(BBStates, Retains, Releases, M, NewRetains,
2772 NewReleases, DeadInsts, RetainsToMove,
2773 ReleasesToMove, Arg, KnownSafe,
2774 AnyPairsCompletelyEliminated);
John McCalld935e9c2011-06-15 23:37:01 +00002775
Michael Gottesman9de6f962013-01-22 21:49:00 +00002776 if (PerformMoveCalls) {
2777 // Ok, everything checks out and we're all set. Let's move/delete some
2778 // code!
2779 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
2780 Retains, Releases, DeadInsts, M);
John McCalld935e9c2011-06-15 23:37:01 +00002781 }
2782
Michael Gottesman9de6f962013-01-22 21:49:00 +00002783 // Clean up state for next retain.
John McCalld935e9c2011-06-15 23:37:01 +00002784 NewReleases.clear();
2785 NewRetains.clear();
2786 RetainsToMove.clear();
2787 ReleasesToMove.clear();
2788 }
2789
2790 // Now that we're done moving everything, we can delete the newly dead
2791 // instructions, as we no longer need them as insert points.
2792 while (!DeadInsts.empty())
2793 EraseInstruction(DeadInsts.pop_back_val());
2794
2795 return AnyPairsCompletelyEliminated;
2796}
2797
Michael Gottesman97e3df02013-01-14 00:35:14 +00002798/// Weak pointer optimizations.
John McCalld935e9c2011-06-15 23:37:01 +00002799void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002800 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeWeakCalls ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00002801
John McCalld935e9c2011-06-15 23:37:01 +00002802 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
2803 // itself because it uses AliasAnalysis and we need to do provenance
2804 // queries instead.
2805 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2806 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +00002807
Michael Gottesman89279f82013-04-05 18:10:41 +00002808 DEBUG(dbgs() << "Visiting: " << *Inst << "\n");
Michael Gottesman3f146e22013-01-01 16:05:48 +00002809
John McCalld935e9c2011-06-15 23:37:01 +00002810 InstructionClass Class = GetBasicInstructionClass(Inst);
2811 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
2812 continue;
2813
2814 // Delete objc_loadWeak calls with no users.
2815 if (Class == IC_LoadWeak && Inst->use_empty()) {
2816 Inst->eraseFromParent();
2817 continue;
2818 }
2819
2820 // TODO: For now, just look for an earlier available version of this value
2821 // within the same block. Theoretically, we could do memdep-style non-local
2822 // analysis too, but that would want caching. A better approach would be to
2823 // use the technique that EarlyCSE uses.
2824 inst_iterator Current = llvm::prior(I);
2825 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
2826 for (BasicBlock::iterator B = CurrentBB->begin(),
2827 J = Current.getInstructionIterator();
2828 J != B; --J) {
2829 Instruction *EarlierInst = &*llvm::prior(J);
2830 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
2831 switch (EarlierClass) {
2832 case IC_LoadWeak:
2833 case IC_LoadWeakRetained: {
2834 // If this is loading from the same pointer, replace this load's value
2835 // with that one.
2836 CallInst *Call = cast<CallInst>(Inst);
2837 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2838 Value *Arg = Call->getArgOperand(0);
2839 Value *EarlierArg = EarlierCall->getArgOperand(0);
2840 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2841 case AliasAnalysis::MustAlias:
2842 Changed = true;
2843 // If the load has a builtin retain, insert a plain retain for it.
2844 if (Class == IC_LoadWeakRetained) {
Michael Gottesman14acfac2013-07-06 01:39:23 +00002845 Constant *Decl = EP.get(ARCRuntimeEntryPoints::EPT_Retain);
2846 CallInst *CI = CallInst::Create(Decl, EarlierCall, "", Call);
John McCalld935e9c2011-06-15 23:37:01 +00002847 CI->setTailCall();
2848 }
2849 // Zap the fully redundant load.
2850 Call->replaceAllUsesWith(EarlierCall);
2851 Call->eraseFromParent();
2852 goto clobbered;
2853 case AliasAnalysis::MayAlias:
2854 case AliasAnalysis::PartialAlias:
2855 goto clobbered;
2856 case AliasAnalysis::NoAlias:
2857 break;
2858 }
2859 break;
2860 }
2861 case IC_StoreWeak:
2862 case IC_InitWeak: {
2863 // If this is storing to the same pointer and has the same size etc.
2864 // replace this load's value with the stored value.
2865 CallInst *Call = cast<CallInst>(Inst);
2866 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2867 Value *Arg = Call->getArgOperand(0);
2868 Value *EarlierArg = EarlierCall->getArgOperand(0);
2869 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2870 case AliasAnalysis::MustAlias:
2871 Changed = true;
2872 // If the load has a builtin retain, insert a plain retain for it.
2873 if (Class == IC_LoadWeakRetained) {
Michael Gottesman14acfac2013-07-06 01:39:23 +00002874 Constant *Decl = EP.get(ARCRuntimeEntryPoints::EPT_Retain);
2875 CallInst *CI = CallInst::Create(Decl, EarlierCall, "", Call);
John McCalld935e9c2011-06-15 23:37:01 +00002876 CI->setTailCall();
2877 }
2878 // Zap the fully redundant load.
2879 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
2880 Call->eraseFromParent();
2881 goto clobbered;
2882 case AliasAnalysis::MayAlias:
2883 case AliasAnalysis::PartialAlias:
2884 goto clobbered;
2885 case AliasAnalysis::NoAlias:
2886 break;
2887 }
2888 break;
2889 }
2890 case IC_MoveWeak:
2891 case IC_CopyWeak:
2892 // TOOD: Grab the copied value.
2893 goto clobbered;
2894 case IC_AutoreleasepoolPush:
2895 case IC_None:
John McCall20182ac2013-03-22 21:38:36 +00002896 case IC_IntrinsicUser:
John McCalld935e9c2011-06-15 23:37:01 +00002897 case IC_User:
2898 // Weak pointers are only modified through the weak entry points
2899 // (and arbitrary calls, which could call the weak entry points).
2900 break;
2901 default:
2902 // Anything else could modify the weak pointer.
2903 goto clobbered;
2904 }
2905 }
2906 clobbered:;
2907 }
2908
2909 // Then, for each destroyWeak with an alloca operand, check to see if
2910 // the alloca and all its users can be zapped.
2911 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2912 Instruction *Inst = &*I++;
2913 InstructionClass Class = GetBasicInstructionClass(Inst);
2914 if (Class != IC_DestroyWeak)
2915 continue;
2916
2917 CallInst *Call = cast<CallInst>(Inst);
2918 Value *Arg = Call->getArgOperand(0);
2919 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
2920 for (Value::use_iterator UI = Alloca->use_begin(),
2921 UE = Alloca->use_end(); UI != UE; ++UI) {
Dan Gohmandae33492012-04-27 18:56:31 +00002922 const Instruction *UserInst = cast<Instruction>(*UI);
John McCalld935e9c2011-06-15 23:37:01 +00002923 switch (GetBasicInstructionClass(UserInst)) {
2924 case IC_InitWeak:
2925 case IC_StoreWeak:
2926 case IC_DestroyWeak:
2927 continue;
2928 default:
2929 goto done;
2930 }
2931 }
2932 Changed = true;
2933 for (Value::use_iterator UI = Alloca->use_begin(),
2934 UE = Alloca->use_end(); UI != UE; ) {
2935 CallInst *UserInst = cast<CallInst>(*UI++);
Dan Gohman14862c32012-05-18 22:17:29 +00002936 switch (GetBasicInstructionClass(UserInst)) {
2937 case IC_InitWeak:
2938 case IC_StoreWeak:
2939 // These functions return their second argument.
2940 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
2941 break;
2942 case IC_DestroyWeak:
2943 // No return value.
2944 break;
2945 default:
Dan Gohman9c97eea02012-05-21 17:41:28 +00002946 llvm_unreachable("alloca really is used!");
Dan Gohman14862c32012-05-18 22:17:29 +00002947 }
John McCalld935e9c2011-06-15 23:37:01 +00002948 UserInst->eraseFromParent();
2949 }
2950 Alloca->eraseFromParent();
2951 done:;
2952 }
2953 }
2954}
2955
Michael Gottesman97e3df02013-01-14 00:35:14 +00002956/// Identify program paths which execute sequences of retains and releases which
2957/// can be eliminated.
John McCalld935e9c2011-06-15 23:37:01 +00002958bool ObjCARCOpt::OptimizeSequences(Function &F) {
Michael Gottesman740db972013-05-23 02:35:21 +00002959 // Releases, Retains - These are used to store the results of the main flow
2960 // analysis. These use Value* as the key instead of Instruction* so that the
2961 // map stays valid when we get around to rewriting code and calls get
2962 // replaced by arguments.
John McCalld935e9c2011-06-15 23:37:01 +00002963 DenseMap<Value *, RRInfo> Releases;
2964 MapVector<Value *, RRInfo> Retains;
2965
Michael Gottesman740db972013-05-23 02:35:21 +00002966 // This is used during the traversal of the function to track the
2967 // states for each identified object at each block.
John McCalld935e9c2011-06-15 23:37:01 +00002968 DenseMap<const BasicBlock *, BBState> BBStates;
2969
2970 // Analyze the CFG of the function, and all instructions.
2971 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
2972
2973 // Transform.
Michael Gottesman5a91bbf2013-05-24 20:44:02 +00002974 bool AnyPairsCompletelyEliminated = PerformCodePlacement(BBStates, Retains,
2975 Releases,
2976 F.getParent());
2977
2978 // Cleanup.
2979 MultiOwnersSet.clear();
2980
2981 return AnyPairsCompletelyEliminated && NestingDetected;
John McCalld935e9c2011-06-15 23:37:01 +00002982}
2983
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002984/// Check if there is a dependent call earlier that does not have anything in
2985/// between the Retain and the call that can affect the reference count of their
2986/// shared pointer argument. Note that Retain need not be in BB.
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002987static bool
2988HasSafePathToPredecessorCall(const Value *Arg, Instruction *Retain,
2989 SmallPtrSet<Instruction *, 4> &DepInsts,
2990 SmallPtrSet<const BasicBlock *, 4> &Visited,
2991 ProvenanceAnalysis &PA) {
2992 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
2993 DepInsts, Visited, PA);
2994 if (DepInsts.size() != 1)
2995 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002996
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002997 CallInst *Call =
2998 dyn_cast_or_null<CallInst>(*DepInsts.begin());
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002999
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00003000 // Check that the pointer is the return value of the call.
3001 if (!Call || Arg != Call)
3002 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00003003
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00003004 // Check that the call is a regular call.
3005 InstructionClass Class = GetBasicInstructionClass(Call);
3006 if (Class != IC_CallOrUser && Class != IC_Call)
3007 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00003008
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00003009 return true;
3010}
3011
Michael Gottesman6908db12013-04-03 23:16:05 +00003012/// Find a dependent retain that precedes the given autorelease for which there
3013/// is nothing in between the two instructions that can affect the ref count of
3014/// Arg.
3015static CallInst *
3016FindPredecessorRetainWithSafePath(const Value *Arg, BasicBlock *BB,
3017 Instruction *Autorelease,
3018 SmallPtrSet<Instruction *, 4> &DepInsts,
3019 SmallPtrSet<const BasicBlock *, 4> &Visited,
3020 ProvenanceAnalysis &PA) {
3021 FindDependencies(CanChangeRetainCount, Arg,
3022 BB, Autorelease, DepInsts, Visited, PA);
3023 if (DepInsts.size() != 1)
3024 return 0;
Michael Gottesman79249972013-04-05 23:46:45 +00003025
Michael Gottesman6908db12013-04-03 23:16:05 +00003026 CallInst *Retain =
3027 dyn_cast_or_null<CallInst>(*DepInsts.begin());
Michael Gottesman79249972013-04-05 23:46:45 +00003028
Michael Gottesman6908db12013-04-03 23:16:05 +00003029 // Check that we found a retain with the same argument.
3030 if (!Retain ||
3031 !IsRetain(GetBasicInstructionClass(Retain)) ||
3032 GetObjCArg(Retain) != Arg) {
3033 return 0;
3034 }
Michael Gottesman79249972013-04-05 23:46:45 +00003035
Michael Gottesman6908db12013-04-03 23:16:05 +00003036 return Retain;
3037}
3038
Michael Gottesman21a4ed32013-04-03 23:39:14 +00003039/// Look for an ``autorelease'' instruction dependent on Arg such that there are
3040/// no instructions dependent on Arg that need a positive ref count in between
3041/// the autorelease and the ret.
3042static CallInst *
3043FindPredecessorAutoreleaseWithSafePath(const Value *Arg, BasicBlock *BB,
3044 ReturnInst *Ret,
3045 SmallPtrSet<Instruction *, 4> &DepInsts,
3046 SmallPtrSet<const BasicBlock *, 4> &V,
3047 ProvenanceAnalysis &PA) {
3048 FindDependencies(NeedsPositiveRetainCount, Arg,
3049 BB, Ret, DepInsts, V, PA);
3050 if (DepInsts.size() != 1)
3051 return 0;
Michael Gottesman79249972013-04-05 23:46:45 +00003052
Michael Gottesman21a4ed32013-04-03 23:39:14 +00003053 CallInst *Autorelease =
3054 dyn_cast_or_null<CallInst>(*DepInsts.begin());
3055 if (!Autorelease)
3056 return 0;
3057 InstructionClass AutoreleaseClass = GetBasicInstructionClass(Autorelease);
3058 if (!IsAutorelease(AutoreleaseClass))
3059 return 0;
3060 if (GetObjCArg(Autorelease) != Arg)
3061 return 0;
Michael Gottesman79249972013-04-05 23:46:45 +00003062
Michael Gottesman21a4ed32013-04-03 23:39:14 +00003063 return Autorelease;
3064}
3065
Michael Gottesman97e3df02013-01-14 00:35:14 +00003066/// Look for this pattern:
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00003067/// \code
John McCalld935e9c2011-06-15 23:37:01 +00003068/// %call = call i8* @something(...)
3069/// %2 = call i8* @objc_retain(i8* %call)
3070/// %3 = call i8* @objc_autorelease(i8* %2)
3071/// ret i8* %3
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00003072/// \endcode
John McCalld935e9c2011-06-15 23:37:01 +00003073/// And delete the retain and autorelease.
John McCalld935e9c2011-06-15 23:37:01 +00003074void ObjCARCOpt::OptimizeReturns(Function &F) {
3075 if (!F.getReturnType()->isPointerTy())
3076 return;
Michael Gottesman79249972013-04-05 23:46:45 +00003077
Michael Gottesman89279f82013-04-05 18:10:41 +00003078 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeReturns ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00003079
John McCalld935e9c2011-06-15 23:37:01 +00003080 SmallPtrSet<Instruction *, 4> DependingInstructions;
3081 SmallPtrSet<const BasicBlock *, 4> Visited;
3082 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3083 BasicBlock *BB = FI;
3084 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
Michael Gottesman3f146e22013-01-01 16:05:48 +00003085
Michael Gottesman89279f82013-04-05 18:10:41 +00003086 DEBUG(dbgs() << "Visiting: " << *Ret << "\n");
Michael Gottesman3f146e22013-01-01 16:05:48 +00003087
Michael Gottesman21a4ed32013-04-03 23:39:14 +00003088 if (!Ret)
3089 continue;
Michael Gottesman79249972013-04-05 23:46:45 +00003090
John McCalld935e9c2011-06-15 23:37:01 +00003091 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
Michael Gottesman79249972013-04-05 23:46:45 +00003092
Michael Gottesmancdb7c152013-04-21 00:25:04 +00003093 // Look for an ``autorelease'' instruction that is a predecessor of Ret and
Michael Gottesman21a4ed32013-04-03 23:39:14 +00003094 // dependent on Arg such that there are no instructions dependent on Arg
3095 // that need a positive ref count in between the autorelease and Ret.
3096 CallInst *Autorelease =
3097 FindPredecessorAutoreleaseWithSafePath(Arg, BB, Ret,
3098 DependingInstructions, Visited,
3099 PA);
John McCalld935e9c2011-06-15 23:37:01 +00003100 DependingInstructions.clear();
3101 Visited.clear();
Michael Gottesmanfb9ece92013-04-21 00:25:01 +00003102
3103 if (!Autorelease)
3104 continue;
3105
3106 CallInst *Retain =
3107 FindPredecessorRetainWithSafePath(Arg, BB, Autorelease,
3108 DependingInstructions, Visited, PA);
3109 DependingInstructions.clear();
3110 Visited.clear();
3111
3112 if (!Retain)
3113 continue;
3114
3115 // Check that there is nothing that can affect the reference count
3116 // between the retain and the call. Note that Retain need not be in BB.
3117 bool HasSafePathToCall = HasSafePathToPredecessorCall(Arg, Retain,
3118 DependingInstructions,
3119 Visited, PA);
3120 DependingInstructions.clear();
3121 Visited.clear();
3122
3123 if (!HasSafePathToCall)
3124 continue;
3125
3126 // If so, we can zap the retain and autorelease.
3127 Changed = true;
3128 ++NumRets;
3129 DEBUG(dbgs() << "Erasing: " << *Retain << "\nErasing: "
3130 << *Autorelease << "\n");
3131 EraseInstruction(Retain);
3132 EraseInstruction(Autorelease);
John McCalld935e9c2011-06-15 23:37:01 +00003133 }
3134}
3135
Michael Gottesman9c118152013-04-29 06:16:57 +00003136#ifndef NDEBUG
3137void
3138ObjCARCOpt::GatherStatistics(Function &F, bool AfterOptimization) {
3139 llvm::Statistic &NumRetains =
3140 AfterOptimization? NumRetainsAfterOpt : NumRetainsBeforeOpt;
3141 llvm::Statistic &NumReleases =
3142 AfterOptimization? NumReleasesAfterOpt : NumReleasesBeforeOpt;
3143
3144 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3145 Instruction *Inst = &*I++;
3146 switch (GetBasicInstructionClass(Inst)) {
3147 default:
3148 break;
3149 case IC_Retain:
3150 ++NumRetains;
3151 break;
3152 case IC_Release:
3153 ++NumReleases;
3154 break;
3155 }
3156 }
3157}
3158#endif
3159
John McCalld935e9c2011-06-15 23:37:01 +00003160bool ObjCARCOpt::doInitialization(Module &M) {
3161 if (!EnableARCOpts)
3162 return false;
3163
Dan Gohman670f9372012-04-13 18:57:48 +00003164 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanceaac7c2011-06-20 23:20:43 +00003165 Run = ModuleHasARC(M);
3166 if (!Run)
3167 return false;
3168
John McCalld935e9c2011-06-15 23:37:01 +00003169 // Identify the imprecise release metadata kind.
3170 ImpreciseReleaseMDKind =
3171 M.getContext().getMDKindID("clang.imprecise_release");
Dan Gohmana7107f92011-10-17 22:53:25 +00003172 CopyOnEscapeMDKind =
3173 M.getContext().getMDKindID("clang.arc.copy_on_escape");
Dan Gohman0155f302012-02-17 18:59:53 +00003174 NoObjCARCExceptionsMDKind =
3175 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
Michael Gottesman81b1d432013-03-26 00:42:04 +00003176#ifdef ARC_ANNOTATIONS
3177 ARCAnnotationBottomUpMDKind =
3178 M.getContext().getMDKindID("llvm.arc.annotation.bottomup");
3179 ARCAnnotationTopDownMDKind =
3180 M.getContext().getMDKindID("llvm.arc.annotation.topdown");
3181 ARCAnnotationProvenanceSourceMDKind =
3182 M.getContext().getMDKindID("llvm.arc.annotation.provenancesource");
3183#endif // ARC_ANNOTATIONS
John McCalld935e9c2011-06-15 23:37:01 +00003184
John McCalld935e9c2011-06-15 23:37:01 +00003185 // Intuitively, objc_retain and others are nocapture, however in practice
3186 // they are not, because they return their argument value. And objc_release
Dan Gohmandae33492012-04-27 18:56:31 +00003187 // calls finalizers which can have arbitrary side effects.
John McCalld935e9c2011-06-15 23:37:01 +00003188
Michael Gottesman14acfac2013-07-06 01:39:23 +00003189 // Initialize our runtime entry point cache.
3190 EP.Initialize(&M);
John McCalld935e9c2011-06-15 23:37:01 +00003191
3192 return false;
3193}
3194
3195bool ObjCARCOpt::runOnFunction(Function &F) {
3196 if (!EnableARCOpts)
3197 return false;
3198
Dan Gohmanceaac7c2011-06-20 23:20:43 +00003199 // If nothing in the Module uses ARC, don't do anything.
3200 if (!Run)
3201 return false;
3202
John McCalld935e9c2011-06-15 23:37:01 +00003203 Changed = false;
3204
Michael Gottesman89279f82013-04-05 18:10:41 +00003205 DEBUG(dbgs() << "<<< ObjCARCOpt: Visiting Function: " << F.getName() << " >>>"
3206 "\n");
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00003207
John McCalld935e9c2011-06-15 23:37:01 +00003208 PA.setAA(&getAnalysis<AliasAnalysis>());
3209
Michael Gottesman9fc50b82013-05-13 18:29:07 +00003210#ifndef NDEBUG
3211 if (AreStatisticsEnabled()) {
3212 GatherStatistics(F, false);
3213 }
3214#endif
3215
John McCalld935e9c2011-06-15 23:37:01 +00003216 // This pass performs several distinct transformations. As a compile-time aid
3217 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3218 // library functions aren't declared.
3219
Michael Gottesmancd5b0272013-04-24 22:18:15 +00003220 // Preliminary optimizations. This also computes UsedInThisFunction.
John McCalld935e9c2011-06-15 23:37:01 +00003221 OptimizeIndividualCalls(F);
3222
3223 // Optimizations for weak pointers.
3224 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3225 (1 << IC_LoadWeakRetained) |
3226 (1 << IC_StoreWeak) |
3227 (1 << IC_InitWeak) |
3228 (1 << IC_CopyWeak) |
3229 (1 << IC_MoveWeak) |
3230 (1 << IC_DestroyWeak)))
3231 OptimizeWeakCalls(F);
3232
3233 // Optimizations for retain+release pairs.
3234 if (UsedInThisFunction & ((1 << IC_Retain) |
3235 (1 << IC_RetainRV) |
3236 (1 << IC_RetainBlock)))
3237 if (UsedInThisFunction & (1 << IC_Release))
3238 // Run OptimizeSequences until it either stops making changes or
3239 // no retain+release pair nesting is detected.
3240 while (OptimizeSequences(F)) {}
3241
3242 // Optimizations if objc_autorelease is used.
Dan Gohman41375a32012-05-08 23:39:44 +00003243 if (UsedInThisFunction & ((1 << IC_Autorelease) |
3244 (1 << IC_AutoreleaseRV)))
John McCalld935e9c2011-06-15 23:37:01 +00003245 OptimizeReturns(F);
3246
Michael Gottesman9c118152013-04-29 06:16:57 +00003247 // Gather statistics after optimization.
3248#ifndef NDEBUG
3249 if (AreStatisticsEnabled()) {
3250 GatherStatistics(F, true);
3251 }
3252#endif
3253
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00003254 DEBUG(dbgs() << "\n");
3255
John McCalld935e9c2011-06-15 23:37:01 +00003256 return Changed;
3257}
3258
3259void ObjCARCOpt::releaseMemory() {
3260 PA.clear();
3261}
3262
Michael Gottesman97e3df02013-01-14 00:35:14 +00003263/// @}
3264///