blob: 4bf25facc68f31b5c83f501463ff930ee2d37938 [file] [log] [blame]
Michael Gottesman79d8d812013-01-28 01:35:51 +00001//===- ObjCARCOpts.cpp - ObjC ARC Optimization ----------------------------===//
John McCalld935e9c2011-06-15 23:37:01 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Michael Gottesman97e3df02013-01-14 00:35:14 +00009/// \file
10/// This file defines ObjC ARC optimizations. ARC stands for Automatic
11/// Reference Counting and is a system for managing reference counts for objects
12/// in Objective C.
13///
14/// The optimizations performed include elimination of redundant, partially
15/// redundant, and inconsequential reference count operations, elimination of
Michael Gottesman697d8b92013-02-07 04:12:57 +000016/// redundant weak pointer operations, and numerous minor simplifications.
Michael Gottesman97e3df02013-01-14 00:35:14 +000017///
18/// WARNING: This file knows about certain library functions. It recognizes them
19/// by name, and hardwires knowledge of their semantics.
20///
21/// WARNING: This file knows about how certain Objective-C library functions are
22/// used. Naive LLVM IR transformations which would otherwise be
23/// behavior-preserving may break these assumptions.
24///
John McCalld935e9c2011-06-15 23:37:01 +000025//===----------------------------------------------------------------------===//
26
Michael Gottesman08904e32013-01-28 03:28:38 +000027#define DEBUG_TYPE "objc-arc-opts"
28#include "ObjCARC.h"
Michael Gottesman278266f2013-01-29 04:20:52 +000029#include "DependencyAnalysis.h"
Michael Gottesman294e7da2013-01-28 05:51:54 +000030#include "ObjCARCAliasAnalysis.h"
Michael Gottesman778138e2013-01-29 03:03:03 +000031#include "ProvenanceAnalysis.h"
John McCalld935e9c2011-06-15 23:37:01 +000032#include "llvm/ADT/DenseMap.h"
Michael Gottesmanfa0939f2013-01-28 04:12:07 +000033#include "llvm/ADT/STLExtras.h"
Michael Gottesman778138e2013-01-29 03:03:03 +000034#include "llvm/ADT/SmallPtrSet.h"
Michael Gottesman278266f2013-01-29 04:20:52 +000035#include "llvm/ADT/Statistic.h"
Michael Gottesmancd4de0f2013-03-26 00:42:09 +000036#include "llvm/IR/IRBuilder.h"
Michael Gottesman278266f2013-01-29 04:20:52 +000037#include "llvm/IR/LLVMContext.h"
Michael Gottesman778138e2013-01-29 03:03:03 +000038#include "llvm/Support/CFG.h"
Michael Gottesman13a5f1a2013-01-29 04:51:59 +000039#include "llvm/Support/Debug.h"
Timur Iskhodzhanov5d7ff002013-01-29 09:09:27 +000040#include "llvm/Support/raw_ostream.h"
Michael Gottesmanfa0939f2013-01-28 04:12:07 +000041
John McCalld935e9c2011-06-15 23:37:01 +000042using namespace llvm;
Michael Gottesman08904e32013-01-28 03:28:38 +000043using namespace llvm::objcarc;
John McCalld935e9c2011-06-15 23:37:01 +000044
Michael Gottesman97e3df02013-01-14 00:35:14 +000045/// \defgroup MiscUtils Miscellaneous utilities that are not ARC specific.
46/// @{
John McCalld935e9c2011-06-15 23:37:01 +000047
48namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +000049 /// \brief An associative container with fast insertion-order (deterministic)
50 /// iteration over its elements. Plus the special blot operation.
John McCalld935e9c2011-06-15 23:37:01 +000051 template<class KeyT, class ValueT>
52 class MapVector {
Michael Gottesman97e3df02013-01-14 00:35:14 +000053 /// Map keys to indices in Vector.
John McCalld935e9c2011-06-15 23:37:01 +000054 typedef DenseMap<KeyT, size_t> MapTy;
55 MapTy Map;
56
John McCalld935e9c2011-06-15 23:37:01 +000057 typedef std::vector<std::pair<KeyT, ValueT> > VectorTy;
Michael Gottesman97e3df02013-01-14 00:35:14 +000058 /// Keys and values.
John McCalld935e9c2011-06-15 23:37:01 +000059 VectorTy Vector;
60
61 public:
62 typedef typename VectorTy::iterator iterator;
63 typedef typename VectorTy::const_iterator const_iterator;
64 iterator begin() { return Vector.begin(); }
65 iterator end() { return Vector.end(); }
66 const_iterator begin() const { return Vector.begin(); }
67 const_iterator end() const { return Vector.end(); }
68
69#ifdef XDEBUG
70 ~MapVector() {
71 assert(Vector.size() >= Map.size()); // May differ due to blotting.
72 for (typename MapTy::const_iterator I = Map.begin(), E = Map.end();
73 I != E; ++I) {
74 assert(I->second < Vector.size());
75 assert(Vector[I->second].first == I->first);
76 }
77 for (typename VectorTy::const_iterator I = Vector.begin(),
78 E = Vector.end(); I != E; ++I)
79 assert(!I->first ||
80 (Map.count(I->first) &&
81 Map[I->first] == size_t(I - Vector.begin())));
82 }
83#endif
84
Dan Gohman55b06742012-03-02 01:13:53 +000085 ValueT &operator[](const KeyT &Arg) {
John McCalld935e9c2011-06-15 23:37:01 +000086 std::pair<typename MapTy::iterator, bool> Pair =
87 Map.insert(std::make_pair(Arg, size_t(0)));
88 if (Pair.second) {
Dan Gohman55b06742012-03-02 01:13:53 +000089 size_t Num = Vector.size();
90 Pair.first->second = Num;
John McCalld935e9c2011-06-15 23:37:01 +000091 Vector.push_back(std::make_pair(Arg, ValueT()));
Dan Gohman55b06742012-03-02 01:13:53 +000092 return Vector[Num].second;
John McCalld935e9c2011-06-15 23:37:01 +000093 }
94 return Vector[Pair.first->second].second;
95 }
96
97 std::pair<iterator, bool>
98 insert(const std::pair<KeyT, ValueT> &InsertPair) {
99 std::pair<typename MapTy::iterator, bool> Pair =
100 Map.insert(std::make_pair(InsertPair.first, size_t(0)));
101 if (Pair.second) {
Dan Gohman55b06742012-03-02 01:13:53 +0000102 size_t Num = Vector.size();
103 Pair.first->second = Num;
John McCalld935e9c2011-06-15 23:37:01 +0000104 Vector.push_back(InsertPair);
Dan Gohman55b06742012-03-02 01:13:53 +0000105 return std::make_pair(Vector.begin() + Num, true);
John McCalld935e9c2011-06-15 23:37:01 +0000106 }
107 return std::make_pair(Vector.begin() + Pair.first->second, false);
108 }
109
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000110 iterator find(const KeyT &Key) {
111 typename MapTy::iterator It = Map.find(Key);
112 if (It == Map.end()) return Vector.end();
113 return Vector.begin() + It->second;
114 }
115
Dan Gohman55b06742012-03-02 01:13:53 +0000116 const_iterator find(const KeyT &Key) const {
John McCalld935e9c2011-06-15 23:37:01 +0000117 typename MapTy::const_iterator It = Map.find(Key);
118 if (It == Map.end()) return Vector.end();
119 return Vector.begin() + It->second;
120 }
121
Michael Gottesman97e3df02013-01-14 00:35:14 +0000122 /// This is similar to erase, but instead of removing the element from the
123 /// vector, it just zeros out the key in the vector. This leaves iterators
124 /// intact, but clients must be prepared for zeroed-out keys when iterating.
Dan Gohman55b06742012-03-02 01:13:53 +0000125 void blot(const KeyT &Key) {
John McCalld935e9c2011-06-15 23:37:01 +0000126 typename MapTy::iterator It = Map.find(Key);
127 if (It == Map.end()) return;
128 Vector[It->second].first = KeyT();
129 Map.erase(It);
130 }
131
132 void clear() {
133 Map.clear();
134 Vector.clear();
135 }
136 };
137}
138
Michael Gottesman97e3df02013-01-14 00:35:14 +0000139/// @}
140///
141/// \defgroup ARCUtilities Utility declarations/definitions specific to ARC.
142/// @{
John McCalld935e9c2011-06-15 23:37:01 +0000143
Michael Gottesman97e3df02013-01-14 00:35:14 +0000144/// \brief This is similar to StripPointerCastsAndObjCCalls but it stops as soon
145/// as it finds a value with multiple uses.
John McCalld935e9c2011-06-15 23:37:01 +0000146static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
147 if (Arg->hasOneUse()) {
148 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
149 return FindSingleUseIdentifiedObject(BC->getOperand(0));
150 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
151 if (GEP->hasAllZeroIndices())
152 return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
153 if (IsForwarding(GetBasicInstructionClass(Arg)))
154 return FindSingleUseIdentifiedObject(
155 cast<CallInst>(Arg)->getArgOperand(0));
156 if (!IsObjCIdentifiedObject(Arg))
157 return 0;
158 return Arg;
159 }
160
Dan Gohman41375a32012-05-08 23:39:44 +0000161 // If we found an identifiable object but it has multiple uses, but they are
162 // trivial uses, we can still consider this to be a single-use value.
John McCalld935e9c2011-06-15 23:37:01 +0000163 if (IsObjCIdentifiedObject(Arg)) {
164 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
165 UI != UE; ++UI) {
166 const User *U = *UI;
167 if (!U->use_empty() || StripPointerCastsAndObjCCalls(U) != Arg)
168 return 0;
169 }
170
171 return Arg;
172 }
173
174 return 0;
175}
176
Michael Gottesman774d2c02013-01-29 21:00:52 +0000177/// \brief Test whether the given retainable object pointer escapes.
Michael Gottesman97e3df02013-01-14 00:35:14 +0000178///
179/// This differs from regular escape analysis in that a use as an
180/// argument to a call is not considered an escape.
181///
Michael Gottesman774d2c02013-01-29 21:00:52 +0000182static bool DoesRetainableObjPtrEscape(const User *Ptr) {
Michael Gottesman774d2c02013-01-29 21:00:52 +0000183 DEBUG(dbgs() << "DoesRetainableObjPtrEscape: Target: " << *Ptr << "\n");
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000184
Dan Gohman728db492012-01-13 00:39:07 +0000185 // Walk the def-use chains.
186 SmallVector<const Value *, 4> Worklist;
Michael Gottesman774d2c02013-01-29 21:00:52 +0000187 Worklist.push_back(Ptr);
188 // If Ptr has any operands add them as well.
Michael Gottesman23cda0c2013-01-29 21:07:53 +0000189 for (User::const_op_iterator I = Ptr->op_begin(), E = Ptr->op_end(); I != E;
190 ++I) {
Michael Gottesman774d2c02013-01-29 21:00:52 +0000191 Worklist.push_back(*I);
192 }
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000193
194 // Ensure we do not visit any value twice.
Michael Gottesman774d2c02013-01-29 21:00:52 +0000195 SmallPtrSet<const Value *, 8> VisitedSet;
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000196
Dan Gohman728db492012-01-13 00:39:07 +0000197 do {
198 const Value *V = Worklist.pop_back_val();
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000199
Michael Gottesman89279f82013-04-05 18:10:41 +0000200 DEBUG(dbgs() << "Visiting: " << *V << "\n");
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000201
Dan Gohman728db492012-01-13 00:39:07 +0000202 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
203 UI != UE; ++UI) {
204 const User *UUser = *UI;
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000205
Michael Gottesman89279f82013-04-05 18:10:41 +0000206 DEBUG(dbgs() << "User: " << *UUser << "\n");
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000207
Dan Gohman728db492012-01-13 00:39:07 +0000208 // Special - Use by a call (callee or argument) is not considered
209 // to be an escape.
Dan Gohmane1e352a2012-04-13 18:28:58 +0000210 switch (GetBasicInstructionClass(UUser)) {
211 case IC_StoreWeak:
212 case IC_InitWeak:
213 case IC_StoreStrong:
214 case IC_Autorelease:
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000215 case IC_AutoreleaseRV: {
Michael Gottesman89279f82013-04-05 18:10:41 +0000216 DEBUG(dbgs() << "User copies pointer arguments. Pointer Escapes!\n");
Dan Gohmane1e352a2012-04-13 18:28:58 +0000217 // These special functions make copies of their pointer arguments.
218 return true;
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000219 }
John McCall20182ac2013-03-22 21:38:36 +0000220 case IC_IntrinsicUser:
221 // Use by the use intrinsic is not an escape.
222 continue;
Dan Gohmane1e352a2012-04-13 18:28:58 +0000223 case IC_User:
224 case IC_None:
225 // Use by an instruction which copies the value is an escape if the
226 // result is an escape.
227 if (isa<BitCastInst>(UUser) || isa<GetElementPtrInst>(UUser) ||
228 isa<PHINode>(UUser) || isa<SelectInst>(UUser)) {
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000229
Michael Gottesmanf4b77612013-02-23 00:31:32 +0000230 if (VisitedSet.insert(UUser)) {
Michael Gottesman89279f82013-04-05 18:10:41 +0000231 DEBUG(dbgs() << "User copies value. Ptr escapes if result escapes."
232 " Adding to list.\n");
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000233 Worklist.push_back(UUser);
234 } else {
Michael Gottesman89279f82013-04-05 18:10:41 +0000235 DEBUG(dbgs() << "Already visited node.\n");
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000236 }
Dan Gohmane1e352a2012-04-13 18:28:58 +0000237 continue;
238 }
239 // Use by a load is not an escape.
240 if (isa<LoadInst>(UUser))
241 continue;
242 // Use by a store is not an escape if the use is the address.
243 if (const StoreInst *SI = dyn_cast<StoreInst>(UUser))
244 if (V != SI->getValueOperand())
245 continue;
246 break;
247 default:
248 // Regular calls and other stuff are not considered escapes.
Dan Gohman728db492012-01-13 00:39:07 +0000249 continue;
250 }
Dan Gohmaneb6e0152012-02-13 22:57:02 +0000251 // Otherwise, conservatively assume an escape.
Michael Gottesman89279f82013-04-05 18:10:41 +0000252 DEBUG(dbgs() << "Assuming ptr escapes.\n");
Dan Gohman728db492012-01-13 00:39:07 +0000253 return true;
254 }
255 } while (!Worklist.empty());
256
257 // No escapes found.
Michael Gottesman89279f82013-04-05 18:10:41 +0000258 DEBUG(dbgs() << "Ptr does not escape.\n");
Dan Gohman728db492012-01-13 00:39:07 +0000259 return false;
260}
261
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000262/// This is a wrapper around getUnderlyingObjCPtr along the lines of
263/// GetUnderlyingObjects except that it returns early when it sees the first
264/// alloca.
265static inline bool AreAnyUnderlyingObjectsAnAlloca(const Value *V) {
266 SmallPtrSet<const Value *, 4> Visited;
267 SmallVector<const Value *, 4> Worklist;
268 Worklist.push_back(V);
269 do {
270 const Value *P = Worklist.pop_back_val();
271 P = GetUnderlyingObjCPtr(P);
Michael Gottesman0c8b5622013-05-14 06:40:10 +0000272
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000273 if (isa<AllocaInst>(P))
274 return true;
Michael Gottesman0c8b5622013-05-14 06:40:10 +0000275
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000276 if (!Visited.insert(P))
277 continue;
Michael Gottesman0c8b5622013-05-14 06:40:10 +0000278
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000279 if (const SelectInst *SI = dyn_cast<const SelectInst>(P)) {
280 Worklist.push_back(SI->getTrueValue());
281 Worklist.push_back(SI->getFalseValue());
282 continue;
283 }
Michael Gottesman0c8b5622013-05-14 06:40:10 +0000284
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000285 if (const PHINode *PN = dyn_cast<const PHINode>(P)) {
286 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
287 Worklist.push_back(PN->getIncomingValue(i));
288 continue;
289 }
290 } while (!Worklist.empty());
291
292 return false;
293}
294
295
Michael Gottesman97e3df02013-01-14 00:35:14 +0000296/// @}
297///
Michael Gottesman97e3df02013-01-14 00:35:14 +0000298/// \defgroup ARCOpt ARC Optimization.
299/// @{
John McCalld935e9c2011-06-15 23:37:01 +0000300
301// TODO: On code like this:
302//
303// objc_retain(%x)
304// stuff_that_cannot_release()
305// objc_autorelease(%x)
306// stuff_that_cannot_release()
307// objc_retain(%x)
308// stuff_that_cannot_release()
309// objc_autorelease(%x)
310//
311// The second retain and autorelease can be deleted.
312
313// TODO: It should be possible to delete
314// objc_autoreleasePoolPush and objc_autoreleasePoolPop
315// pairs if nothing is actually autoreleased between them. Also, autorelease
316// calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
317// after inlining) can be turned into plain release calls.
318
319// TODO: Critical-edge splitting. If the optimial insertion point is
320// a critical edge, the current algorithm has to fail, because it doesn't
321// know how to split edges. It should be possible to make the optimizer
322// think in terms of edges, rather than blocks, and then split critical
323// edges on demand.
324
325// TODO: OptimizeSequences could generalized to be Interprocedural.
326
327// TODO: Recognize that a bunch of other objc runtime calls have
328// non-escaping arguments and non-releasing arguments, and may be
329// non-autoreleasing.
330
331// TODO: Sink autorelease calls as far as possible. Unfortunately we
332// usually can't sink them past other calls, which would be the main
333// case where it would be useful.
334
Dan Gohmanb3894012011-08-19 00:26:36 +0000335// TODO: The pointer returned from objc_loadWeakRetained is retained.
336
337// TODO: Delete release+retain pairs (rare).
Dan Gohmanceaac7c2011-06-20 23:20:43 +0000338
John McCalld935e9c2011-06-15 23:37:01 +0000339STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
340STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
341STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
342STATISTIC(NumRets, "Number of return value forwarding "
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000343 "retain+autoreleases eliminated");
John McCalld935e9c2011-06-15 23:37:01 +0000344STATISTIC(NumRRs, "Number of retain+release paths eliminated");
345STATISTIC(NumPeeps, "Number of calls peephole-optimized");
Matt Beaumont-Gaye55d9492013-05-13 21:10:49 +0000346#ifndef NDEBUG
Michael Gottesman9c118152013-04-29 06:16:57 +0000347STATISTIC(NumRetainsBeforeOpt,
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000348 "Number of retains before optimization");
Michael Gottesman9c118152013-04-29 06:16:57 +0000349STATISTIC(NumReleasesBeforeOpt,
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000350 "Number of releases before optimization");
Michael Gottesman9c118152013-04-29 06:16:57 +0000351STATISTIC(NumRetainsAfterOpt,
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000352 "Number of retains after optimization");
Michael Gottesman9c118152013-04-29 06:16:57 +0000353STATISTIC(NumReleasesAfterOpt,
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000354 "Number of releases after optimization");
Michael Gottesman03cf3c82013-04-29 07:29:08 +0000355#endif
John McCalld935e9c2011-06-15 23:37:01 +0000356
357namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000358 /// \enum Sequence
359 ///
360 /// \brief A sequence of states that a pointer may go through in which an
361 /// objc_retain and objc_release are actually needed.
John McCalld935e9c2011-06-15 23:37:01 +0000362 enum Sequence {
363 S_None,
Michael Gottesman53fd20b2013-01-29 21:07:51 +0000364 S_Retain, ///< objc_retain(x).
365 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement.
366 S_Use, ///< any use of x.
Michael Gottesman386241c2013-01-29 21:39:02 +0000367 S_Stop, ///< like S_Release, but code motion is stopped.
Michael Gottesman53fd20b2013-01-29 21:07:51 +0000368 S_Release, ///< objc_release(x).
Michael Gottesman9bdab2b2013-01-29 21:41:44 +0000369 S_MovableRelease ///< objc_release(x), !clang.imprecise_release.
John McCalld935e9c2011-06-15 23:37:01 +0000370 };
Michael Gottesman53fd20b2013-01-29 21:07:51 +0000371
372 raw_ostream &operator<<(raw_ostream &OS, const Sequence S)
373 LLVM_ATTRIBUTE_UNUSED;
374 raw_ostream &operator<<(raw_ostream &OS, const Sequence S) {
375 switch (S) {
376 case S_None:
377 return OS << "S_None";
378 case S_Retain:
379 return OS << "S_Retain";
380 case S_CanRelease:
381 return OS << "S_CanRelease";
382 case S_Use:
383 return OS << "S_Use";
384 case S_Release:
385 return OS << "S_Release";
386 case S_MovableRelease:
387 return OS << "S_MovableRelease";
388 case S_Stop:
389 return OS << "S_Stop";
390 }
391 llvm_unreachable("Unknown sequence type.");
392 }
John McCalld935e9c2011-06-15 23:37:01 +0000393}
394
395static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
396 // The easy cases.
397 if (A == B)
398 return A;
399 if (A == S_None || B == S_None)
400 return S_None;
401
John McCalld935e9c2011-06-15 23:37:01 +0000402 if (A > B) std::swap(A, B);
403 if (TopDown) {
404 // Choose the side which is further along in the sequence.
Dan Gohman12130272011-08-12 00:26:31 +0000405 if ((A == S_Retain || A == S_CanRelease) &&
406 (B == S_CanRelease || B == S_Use))
John McCalld935e9c2011-06-15 23:37:01 +0000407 return B;
408 } else {
409 // Choose the side which is further along in the sequence.
410 if ((A == S_Use || A == S_CanRelease) &&
Dan Gohman12130272011-08-12 00:26:31 +0000411 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
John McCalld935e9c2011-06-15 23:37:01 +0000412 return A;
413 // If both sides are releases, choose the more conservative one.
414 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
415 return A;
416 if (A == S_Release && B == S_MovableRelease)
417 return A;
418 }
419
420 return S_None;
421}
422
423namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000424 /// \brief Unidirectional information about either a
John McCalld935e9c2011-06-15 23:37:01 +0000425 /// retain-decrement-use-release sequence or release-use-decrement-retain
Bob Wilson798a7702013-04-09 22:15:51 +0000426 /// reverse sequence.
John McCalld935e9c2011-06-15 23:37:01 +0000427 struct RRInfo {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000428 /// After an objc_retain, the reference count of the referenced
Dan Gohmanb3894012011-08-19 00:26:36 +0000429 /// object is known to be positive. Similarly, before an objc_release, the
430 /// reference count of the referenced object is known to be positive. If
431 /// there are retain-release pairs in code regions where the retain count
432 /// is known to be positive, they can be eliminated, regardless of any side
433 /// effects between them.
434 ///
435 /// Also, a retain+release pair nested within another retain+release
436 /// pair all on the known same pointer value can be eliminated, regardless
437 /// of any intervening side effects.
438 ///
439 /// KnownSafe is true when either of these conditions is satisfied.
440 bool KnownSafe;
John McCalld935e9c2011-06-15 23:37:01 +0000441
Michael Gottesman97e3df02013-01-14 00:35:14 +0000442 /// True of the objc_release calls are all marked with the "tail" keyword.
John McCalld935e9c2011-06-15 23:37:01 +0000443 bool IsTailCallRelease;
444
Michael Gottesman97e3df02013-01-14 00:35:14 +0000445 /// If the Calls are objc_release calls and they all have a
446 /// clang.imprecise_release tag, this is the metadata tag.
John McCalld935e9c2011-06-15 23:37:01 +0000447 MDNode *ReleaseMetadata;
448
Michael Gottesman97e3df02013-01-14 00:35:14 +0000449 /// For a top-down sequence, the set of objc_retains or
John McCalld935e9c2011-06-15 23:37:01 +0000450 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
451 SmallPtrSet<Instruction *, 2> Calls;
452
Michael Gottesman97e3df02013-01-14 00:35:14 +0000453 /// The set of optimal insert positions for moving calls in the opposite
454 /// sequence.
John McCalld935e9c2011-06-15 23:37:01 +0000455 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
456
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000457 /// Does this pointer have multiple owners?
458 ///
459 /// In the presence of multiple owners with the same provenance caused by
460 /// allocas, we can not assume that the frontend will emit balanced code
461 /// since it could put the release on the pointer loaded from the
462 /// alloca. This confuses the optimizer so we must be more conservative in
463 /// that case.
464 bool MultipleOwners;
465
John McCalld935e9c2011-06-15 23:37:01 +0000466 RRInfo() :
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000467 KnownSafe(false), IsTailCallRelease(false), ReleaseMetadata(0),
468 MultipleOwners(false) {}
John McCalld935e9c2011-06-15 23:37:01 +0000469
470 void clear();
Michael Gottesman79249972013-04-05 23:46:45 +0000471
Michael Gottesman1d8d2572013-04-05 22:54:28 +0000472 bool IsTrackingImpreciseReleases() {
473 return ReleaseMetadata != 0;
474 }
John McCalld935e9c2011-06-15 23:37:01 +0000475 };
476}
477
478void RRInfo::clear() {
Dan Gohmanb3894012011-08-19 00:26:36 +0000479 KnownSafe = false;
John McCalld935e9c2011-06-15 23:37:01 +0000480 IsTailCallRelease = false;
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000481 MultipleOwners = false;
John McCalld935e9c2011-06-15 23:37:01 +0000482 ReleaseMetadata = 0;
483 Calls.clear();
484 ReverseInsertPts.clear();
485}
486
487namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000488 /// \brief This class summarizes several per-pointer runtime properties which
489 /// are propogated through the flow graph.
John McCalld935e9c2011-06-15 23:37:01 +0000490 class PtrState {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000491 /// True if the reference count is known to be incremented.
Dan Gohman62079b42012-04-25 00:50:46 +0000492 bool KnownPositiveRefCount;
493
Bob Wilson798a7702013-04-09 22:15:51 +0000494 /// True if we've seen an opportunity for partial RR elimination, such as
Michael Gottesman97e3df02013-01-14 00:35:14 +0000495 /// pushing calls into a CFG triangle or into one side of a CFG diamond.
Dan Gohman62079b42012-04-25 00:50:46 +0000496 bool Partial;
John McCalld935e9c2011-06-15 23:37:01 +0000497
Michael Gottesman97e3df02013-01-14 00:35:14 +0000498 /// The current position in the sequence.
Dan Gohman41375a32012-05-08 23:39:44 +0000499 Sequence Seq : 8;
John McCalld935e9c2011-06-15 23:37:01 +0000500
501 public:
Michael Gottesman97e3df02013-01-14 00:35:14 +0000502 /// Unidirectional information about the current sequence.
503 ///
John McCalld935e9c2011-06-15 23:37:01 +0000504 /// TODO: Encapsulate this better.
505 RRInfo RRI;
506
Dan Gohmandf476e52012-09-04 23:16:20 +0000507 PtrState() : KnownPositiveRefCount(false), Partial(false),
Dan Gohman41375a32012-05-08 23:39:44 +0000508 Seq(S_None) {}
John McCalld935e9c2011-06-15 23:37:01 +0000509
Michael Gottesman415ddd72013-02-05 19:32:18 +0000510 void SetKnownPositiveRefCount() {
Michael Gottesmanf3f9e3b2013-05-14 00:08:09 +0000511 DEBUG(dbgs() << "Setting Known Positive.\n");
Dan Gohman62079b42012-04-25 00:50:46 +0000512 KnownPositiveRefCount = true;
Dan Gohman12130272011-08-12 00:26:31 +0000513 }
514
Michael Gottesman764b1cf2013-03-23 05:46:19 +0000515 void ClearKnownPositiveRefCount() {
Michael Gottesmanf3f9e3b2013-05-14 00:08:09 +0000516 DEBUG(dbgs() << "Clearing Known Positive.\n");
Dan Gohman62079b42012-04-25 00:50:46 +0000517 KnownPositiveRefCount = false;
John McCalld935e9c2011-06-15 23:37:01 +0000518 }
519
Michael Gottesman07beea42013-03-23 05:31:01 +0000520 bool HasKnownPositiveRefCount() const {
Dan Gohman62079b42012-04-25 00:50:46 +0000521 return KnownPositiveRefCount;
John McCalld935e9c2011-06-15 23:37:01 +0000522 }
523
Michael Gottesman415ddd72013-02-05 19:32:18 +0000524 void SetSeq(Sequence NewSeq) {
Michael Gottesman89279f82013-04-05 18:10:41 +0000525 DEBUG(dbgs() << "Old: " << Seq << "; New: " << NewSeq << "\n");
Michael Gottesman79249972013-04-05 23:46:45 +0000526 Seq = NewSeq;
John McCalld935e9c2011-06-15 23:37:01 +0000527 }
528
Michael Gottesman415ddd72013-02-05 19:32:18 +0000529 Sequence GetSeq() const {
John McCalld935e9c2011-06-15 23:37:01 +0000530 return Seq;
531 }
532
Michael Gottesman415ddd72013-02-05 19:32:18 +0000533 void ClearSequenceProgress() {
Dan Gohman62079b42012-04-25 00:50:46 +0000534 ResetSequenceProgress(S_None);
535 }
536
Michael Gottesman415ddd72013-02-05 19:32:18 +0000537 void ResetSequenceProgress(Sequence NewSeq) {
Michael Gottesman01338a42013-04-20 23:36:57 +0000538 DEBUG(dbgs() << "Resetting sequence progress.\n");
Michael Gottesman89279f82013-04-05 18:10:41 +0000539 SetSeq(NewSeq);
Dan Gohman62079b42012-04-25 00:50:46 +0000540 Partial = false;
John McCalld935e9c2011-06-15 23:37:01 +0000541 RRI.clear();
542 }
543
544 void Merge(const PtrState &Other, bool TopDown);
545 };
546}
547
548void
549PtrState::Merge(const PtrState &Other, bool TopDown) {
550 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
Dan Gohman62079b42012-04-25 00:50:46 +0000551 KnownPositiveRefCount = KnownPositiveRefCount && Other.KnownPositiveRefCount;
Michael Gottesman60f6b282013-03-29 05:13:07 +0000552
Dan Gohman1736c142011-10-17 18:48:25 +0000553 // If we're not in a sequence (anymore), drop all associated state.
John McCalld935e9c2011-06-15 23:37:01 +0000554 if (Seq == S_None) {
Dan Gohman62079b42012-04-25 00:50:46 +0000555 Partial = false;
John McCalld935e9c2011-06-15 23:37:01 +0000556 RRI.clear();
Dan Gohman62079b42012-04-25 00:50:46 +0000557 } else if (Partial || Other.Partial) {
Dan Gohman1736c142011-10-17 18:48:25 +0000558 // If we're doing a merge on a path that's previously seen a partial
559 // merge, conservatively drop the sequence, to avoid doing partial
560 // RR elimination. If the branch predicates for the two merge differ,
561 // mixing them is unsafe.
Dan Gohman62079b42012-04-25 00:50:46 +0000562 ClearSequenceProgress();
John McCalld935e9c2011-06-15 23:37:01 +0000563 } else {
564 // Conservatively merge the ReleaseMetadata information.
565 if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
566 RRI.ReleaseMetadata = 0;
567
Dan Gohmanb3894012011-08-19 00:26:36 +0000568 RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
Dan Gohman41375a32012-05-08 23:39:44 +0000569 RRI.IsTailCallRelease = RRI.IsTailCallRelease &&
570 Other.RRI.IsTailCallRelease;
John McCalld935e9c2011-06-15 23:37:01 +0000571 RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000572 RRI.MultipleOwners |= Other.RRI.MultipleOwners;
Dan Gohman1736c142011-10-17 18:48:25 +0000573
574 // Merge the insert point sets. If there are any differences,
575 // that makes this a partial merge.
Dan Gohman41375a32012-05-08 23:39:44 +0000576 Partial = RRI.ReverseInsertPts.size() != Other.RRI.ReverseInsertPts.size();
Dan Gohman1736c142011-10-17 18:48:25 +0000577 for (SmallPtrSet<Instruction *, 2>::const_iterator
578 I = Other.RRI.ReverseInsertPts.begin(),
579 E = Other.RRI.ReverseInsertPts.end(); I != E; ++I)
Dan Gohman62079b42012-04-25 00:50:46 +0000580 Partial |= RRI.ReverseInsertPts.insert(*I);
John McCalld935e9c2011-06-15 23:37:01 +0000581 }
582}
583
584namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000585 /// \brief Per-BasicBlock state.
John McCalld935e9c2011-06-15 23:37:01 +0000586 class BBState {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000587 /// The number of unique control paths from the entry which can reach this
588 /// block.
John McCalld935e9c2011-06-15 23:37:01 +0000589 unsigned TopDownPathCount;
590
Michael Gottesman97e3df02013-01-14 00:35:14 +0000591 /// The number of unique control paths to exits from this block.
John McCalld935e9c2011-06-15 23:37:01 +0000592 unsigned BottomUpPathCount;
593
Michael Gottesman97e3df02013-01-14 00:35:14 +0000594 /// A type for PerPtrTopDown and PerPtrBottomUp.
John McCalld935e9c2011-06-15 23:37:01 +0000595 typedef MapVector<const Value *, PtrState> MapTy;
596
Michael Gottesman97e3df02013-01-14 00:35:14 +0000597 /// The top-down traversal uses this to record information known about a
598 /// pointer at the bottom of each block.
John McCalld935e9c2011-06-15 23:37:01 +0000599 MapTy PerPtrTopDown;
600
Michael Gottesman97e3df02013-01-14 00:35:14 +0000601 /// The bottom-up traversal uses this to record information known about a
602 /// pointer at the top of each block.
John McCalld935e9c2011-06-15 23:37:01 +0000603 MapTy PerPtrBottomUp;
604
Michael Gottesman97e3df02013-01-14 00:35:14 +0000605 /// Effective predecessors of the current block ignoring ignorable edges and
606 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000607 SmallVector<BasicBlock *, 2> Preds;
Michael Gottesman97e3df02013-01-14 00:35:14 +0000608 /// Effective successors of the current block ignoring ignorable edges and
609 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000610 SmallVector<BasicBlock *, 2> Succs;
611
John McCalld935e9c2011-06-15 23:37:01 +0000612 public:
613 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
614
615 typedef MapTy::iterator ptr_iterator;
616 typedef MapTy::const_iterator ptr_const_iterator;
617
618 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
619 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
620 ptr_const_iterator top_down_ptr_begin() const {
621 return PerPtrTopDown.begin();
622 }
623 ptr_const_iterator top_down_ptr_end() const {
624 return PerPtrTopDown.end();
625 }
626
627 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
628 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
629 ptr_const_iterator bottom_up_ptr_begin() const {
630 return PerPtrBottomUp.begin();
631 }
632 ptr_const_iterator bottom_up_ptr_end() const {
633 return PerPtrBottomUp.end();
634 }
635
Michael Gottesman97e3df02013-01-14 00:35:14 +0000636 /// Mark this block as being an entry block, which has one path from the
637 /// entry by definition.
John McCalld935e9c2011-06-15 23:37:01 +0000638 void SetAsEntry() { TopDownPathCount = 1; }
639
Michael Gottesman97e3df02013-01-14 00:35:14 +0000640 /// Mark this block as being an exit block, which has one path to an exit by
641 /// definition.
John McCalld935e9c2011-06-15 23:37:01 +0000642 void SetAsExit() { BottomUpPathCount = 1; }
643
Michael Gottesman993fbf72013-05-13 19:40:39 +0000644 /// Attempt to find the PtrState object describing the top down state for
645 /// pointer Arg. Return a new initialized PtrState describing the top down
646 /// state for Arg if we do not find one.
John McCalld935e9c2011-06-15 23:37:01 +0000647 PtrState &getPtrTopDownState(const Value *Arg) {
648 return PerPtrTopDown[Arg];
649 }
650
Michael Gottesman993fbf72013-05-13 19:40:39 +0000651 /// Attempt to find the PtrState object describing the bottom up state for
652 /// pointer Arg. Return a new initialized PtrState describing the bottom up
653 /// state for Arg if we do not find one.
John McCalld935e9c2011-06-15 23:37:01 +0000654 PtrState &getPtrBottomUpState(const Value *Arg) {
655 return PerPtrBottomUp[Arg];
656 }
657
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000658 /// Attempt to find the PtrState object describing the bottom up state for
659 /// pointer Arg.
660 ptr_iterator findPtrBottomUpState(const Value *Arg) {
661 return PerPtrBottomUp.find(Arg);
662 }
663
John McCalld935e9c2011-06-15 23:37:01 +0000664 void clearBottomUpPointers() {
Evan Chenge4df6a22011-08-04 18:40:26 +0000665 PerPtrBottomUp.clear();
John McCalld935e9c2011-06-15 23:37:01 +0000666 }
667
668 void clearTopDownPointers() {
669 PerPtrTopDown.clear();
670 }
671
672 void InitFromPred(const BBState &Other);
673 void InitFromSucc(const BBState &Other);
674 void MergePred(const BBState &Other);
675 void MergeSucc(const BBState &Other);
676
Michael Gottesman97e3df02013-01-14 00:35:14 +0000677 /// Return the number of possible unique paths from an entry to an exit
678 /// which pass through this block. This is only valid after both the
679 /// top-down and bottom-up traversals are complete.
John McCalld935e9c2011-06-15 23:37:01 +0000680 unsigned GetAllPathCount() const {
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000681 assert(TopDownPathCount != 0);
682 assert(BottomUpPathCount != 0);
John McCalld935e9c2011-06-15 23:37:01 +0000683 return TopDownPathCount * BottomUpPathCount;
684 }
Dan Gohman12130272011-08-12 00:26:31 +0000685
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000686 // Specialized CFG utilities.
Dan Gohmandae33492012-04-27 18:56:31 +0000687 typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000688 edge_iterator pred_begin() { return Preds.begin(); }
689 edge_iterator pred_end() { return Preds.end(); }
690 edge_iterator succ_begin() { return Succs.begin(); }
691 edge_iterator succ_end() { return Succs.end(); }
692
693 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
694 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
695
696 bool isExit() const { return Succs.empty(); }
John McCalld935e9c2011-06-15 23:37:01 +0000697 };
698}
699
700void BBState::InitFromPred(const BBState &Other) {
701 PerPtrTopDown = Other.PerPtrTopDown;
702 TopDownPathCount = Other.TopDownPathCount;
703}
704
705void BBState::InitFromSucc(const BBState &Other) {
706 PerPtrBottomUp = Other.PerPtrBottomUp;
707 BottomUpPathCount = Other.BottomUpPathCount;
708}
709
Michael Gottesman97e3df02013-01-14 00:35:14 +0000710/// The top-down traversal uses this to merge information about predecessors to
711/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +0000712void BBState::MergePred(const BBState &Other) {
713 // Other.TopDownPathCount can be 0, in which case it is either dead or a
714 // loop backedge. Loop backedges are special.
715 TopDownPathCount += Other.TopDownPathCount;
716
Michael Gottesman4385edf2013-01-14 01:47:53 +0000717 // Check for overflow. If we have overflow, fall back to conservative
718 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +0000719 if (TopDownPathCount < Other.TopDownPathCount) {
720 clearTopDownPointers();
721 return;
722 }
723
John McCalld935e9c2011-06-15 23:37:01 +0000724 // For each entry in the other set, if our set has an entry with the same key,
725 // merge the entries. Otherwise, copy the entry and merge it with an empty
726 // entry.
727 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
728 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
729 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
730 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
731 /*TopDown=*/true);
732 }
733
Dan Gohman7e315fc32011-08-11 21:06:32 +0000734 // For each entry in our set, if the other set doesn't have an entry with the
John McCalld935e9c2011-06-15 23:37:01 +0000735 // same key, force it to merge with an empty entry.
736 for (ptr_iterator MI = top_down_ptr_begin(),
737 ME = top_down_ptr_end(); MI != ME; ++MI)
738 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
739 MI->second.Merge(PtrState(), /*TopDown=*/true);
740}
741
Michael Gottesman97e3df02013-01-14 00:35:14 +0000742/// The bottom-up traversal uses this to merge information about successors to
743/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +0000744void BBState::MergeSucc(const BBState &Other) {
745 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
746 // loop backedge. Loop backedges are special.
747 BottomUpPathCount += Other.BottomUpPathCount;
748
Michael Gottesman4385edf2013-01-14 01:47:53 +0000749 // Check for overflow. If we have overflow, fall back to conservative
750 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +0000751 if (BottomUpPathCount < Other.BottomUpPathCount) {
752 clearBottomUpPointers();
753 return;
754 }
755
John McCalld935e9c2011-06-15 23:37:01 +0000756 // For each entry in the other set, if our set has an entry with the
757 // same key, merge the entries. Otherwise, copy the entry and merge
758 // it with an empty entry.
759 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
760 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
761 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
762 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
763 /*TopDown=*/false);
764 }
765
Dan Gohman7e315fc32011-08-11 21:06:32 +0000766 // For each entry in our set, if the other set doesn't have an entry
John McCalld935e9c2011-06-15 23:37:01 +0000767 // with the same key, force it to merge with an empty entry.
768 for (ptr_iterator MI = bottom_up_ptr_begin(),
769 ME = bottom_up_ptr_end(); MI != ME; ++MI)
770 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
771 MI->second.Merge(PtrState(), /*TopDown=*/false);
772}
773
Michael Gottesman81b1d432013-03-26 00:42:04 +0000774// Only enable ARC Annotations if we are building a debug version of
775// libObjCARCOpts.
776#ifndef NDEBUG
777#define ARC_ANNOTATIONS
778#endif
779
780// Define some macros along the lines of DEBUG and some helper functions to make
781// it cleaner to create annotations in the source code and to no-op when not
782// building in debug mode.
783#ifdef ARC_ANNOTATIONS
784
785#include "llvm/Support/CommandLine.h"
786
787/// Enable/disable ARC sequence annotations.
788static cl::opt<bool>
Michael Gottesman6806b512013-04-17 20:48:03 +0000789EnableARCAnnotations("enable-objc-arc-annotations", cl::init(false),
790 cl::desc("Enable emission of arc data flow analysis "
791 "annotations"));
Michael Gottesmanffef24f2013-04-17 20:48:01 +0000792static cl::opt<bool>
Michael Gottesmanadb921a2013-04-17 21:03:53 +0000793DisableCheckForCFGHazards("disable-objc-arc-checkforcfghazards", cl::init(false),
794 cl::desc("Disable check for cfg hazards when "
795 "annotating"));
Michael Gottesman4e88ce62013-04-17 21:59:41 +0000796static cl::opt<std::string>
797ARCAnnotationTargetIdentifier("objc-arc-annotation-target-identifier",
798 cl::init(""),
799 cl::desc("filter out all data flow annotations "
800 "but those that apply to the given "
801 "target llvm identifier."));
Michael Gottesman81b1d432013-03-26 00:42:04 +0000802
803/// This function appends a unique ARCAnnotationProvenanceSourceMDKind id to an
804/// instruction so that we can track backwards when post processing via the llvm
805/// arc annotation processor tool. If the function is an
806static MDString *AppendMDNodeToSourcePtr(unsigned NodeId,
807 Value *Ptr) {
808 MDString *Hash = 0;
809
810 // If pointer is a result of an instruction and it does not have a source
811 // MDNode it, attach a new MDNode onto it. If pointer is a result of
812 // an instruction and does have a source MDNode attached to it, return a
813 // reference to said Node. Otherwise just return 0.
814 if (Instruction *Inst = dyn_cast<Instruction>(Ptr)) {
815 MDNode *Node;
816 if (!(Node = Inst->getMetadata(NodeId))) {
817 // We do not have any node. Generate and attatch the hash MDString to the
818 // instruction.
819
820 // We just use an MDString to ensure that this metadata gets written out
821 // of line at the module level and to provide a very simple format
822 // encoding the information herein. Both of these makes it simpler to
823 // parse the annotations by a simple external program.
824 std::string Str;
825 raw_string_ostream os(Str);
826 os << "(" << Inst->getParent()->getParent()->getName() << ",%"
827 << Inst->getName() << ")";
828
829 Hash = MDString::get(Inst->getContext(), os.str());
830 Inst->setMetadata(NodeId, MDNode::get(Inst->getContext(),Hash));
831 } else {
832 // We have a node. Grab its hash and return it.
833 assert(Node->getNumOperands() == 1 &&
834 "An ARCAnnotationProvenanceSourceMDKind can only have 1 operand.");
835 Hash = cast<MDString>(Node->getOperand(0));
836 }
837 } else if (Argument *Arg = dyn_cast<Argument>(Ptr)) {
838 std::string str;
839 raw_string_ostream os(str);
840 os << "(" << Arg->getParent()->getName() << ",%" << Arg->getName()
841 << ")";
842 Hash = MDString::get(Arg->getContext(), os.str());
843 }
844
845 return Hash;
846}
847
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000848static std::string SequenceToString(Sequence A) {
849 std::string str;
850 raw_string_ostream os(str);
851 os << A;
852 return os.str();
853}
854
Michael Gottesman81b1d432013-03-26 00:42:04 +0000855/// Helper function to change a Sequence into a String object using our overload
856/// for raw_ostream so we only have printing code in one location.
857static MDString *SequenceToMDString(LLVMContext &Context,
858 Sequence A) {
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000859 return MDString::get(Context, SequenceToString(A));
Michael Gottesman81b1d432013-03-26 00:42:04 +0000860}
861
862/// A simple function to generate a MDNode which describes the change in state
863/// for Value *Ptr caused by Instruction *Inst.
864static void AppendMDNodeToInstForPtr(unsigned NodeId,
865 Instruction *Inst,
866 Value *Ptr,
867 MDString *PtrSourceMDNodeID,
868 Sequence OldSeq,
869 Sequence NewSeq) {
870 MDNode *Node = 0;
871 Value *tmp[3] = {PtrSourceMDNodeID,
872 SequenceToMDString(Inst->getContext(),
873 OldSeq),
874 SequenceToMDString(Inst->getContext(),
875 NewSeq)};
876 Node = MDNode::get(Inst->getContext(),
877 ArrayRef<Value*>(tmp, 3));
878
879 Inst->setMetadata(NodeId, Node);
880}
881
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000882/// Add to the beginning of the basic block llvm.ptr.annotations which show the
883/// state of a pointer at the entrance to a basic block.
884static void GenerateARCBBEntranceAnnotation(const char *Name, BasicBlock *BB,
885 Value *Ptr, Sequence Seq) {
Michael Gottesman4e88ce62013-04-17 21:59:41 +0000886 // If we have a target identifier, make sure that we match it before
887 // continuing.
888 if(!ARCAnnotationTargetIdentifier.empty() &&
889 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
890 return;
Michael Gottesman9e518132013-04-18 04:34:11 +0000891
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000892 Module *M = BB->getParent()->getParent();
893 LLVMContext &C = M->getContext();
894 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
895 Type *I8XX = PointerType::getUnqual(I8X);
896 Type *Params[] = {I8XX, I8XX};
897 FunctionType *FTy = FunctionType::get(Type::getVoidTy(C),
898 ArrayRef<Type*>(Params, 2),
899 /*isVarArg=*/false);
900 Constant *Callee = M->getOrInsertFunction(Name, FTy);
Michael Gottesman60f6b282013-03-29 05:13:07 +0000901
902 IRBuilder<> Builder(BB, BB->getFirstInsertionPt());
903
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000904 Value *PtrName;
905 StringRef Tmp = Ptr->getName();
906 if (0 == (PtrName = M->getGlobalVariable(Tmp, true))) {
907 Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
908 Tmp + "_STR");
909 PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
Michael Gottesman60f6b282013-03-29 05:13:07 +0000910 cast<Constant>(ActualPtrName), Tmp);
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000911 }
912
913 Value *S;
914 std::string SeqStr = SequenceToString(Seq);
915 if (0 == (S = M->getGlobalVariable(SeqStr, true))) {
916 Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
917 SeqStr + "_STR");
918 S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
919 cast<Constant>(ActualPtrName), SeqStr);
920 }
921
922 Builder.CreateCall2(Callee, PtrName, S);
923}
924
925/// Add to the end of the basic block llvm.ptr.annotations which show the state
926/// of the pointer at the bottom of the basic block.
927static void GenerateARCBBTerminatorAnnotation(const char *Name, BasicBlock *BB,
928 Value *Ptr, Sequence Seq) {
Michael Gottesman4e88ce62013-04-17 21:59:41 +0000929 // If we have a target identifier, make sure that we match it before emitting
930 // an annotation.
931 if(!ARCAnnotationTargetIdentifier.empty() &&
932 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
933 return;
Michael Gottesman9e518132013-04-18 04:34:11 +0000934
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000935 Module *M = BB->getParent()->getParent();
936 LLVMContext &C = M->getContext();
937 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
938 Type *I8XX = PointerType::getUnqual(I8X);
939 Type *Params[] = {I8XX, I8XX};
940 FunctionType *FTy = FunctionType::get(Type::getVoidTy(C),
941 ArrayRef<Type*>(Params, 2),
942 /*isVarArg=*/false);
943 Constant *Callee = M->getOrInsertFunction(Name, FTy);
Michael Gottesman60f6b282013-03-29 05:13:07 +0000944
945 IRBuilder<> Builder(BB, llvm::prior(BB->end()));
946
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000947 Value *PtrName;
948 StringRef Tmp = Ptr->getName();
949 if (0 == (PtrName = M->getGlobalVariable(Tmp, true))) {
950 Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
951 Tmp + "_STR");
952 PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
Michael Gottesman60f6b282013-03-29 05:13:07 +0000953 cast<Constant>(ActualPtrName), Tmp);
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000954 }
955
956 Value *S;
957 std::string SeqStr = SequenceToString(Seq);
958 if (0 == (S = M->getGlobalVariable(SeqStr, true))) {
959 Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
960 SeqStr + "_STR");
961 S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
962 cast<Constant>(ActualPtrName), SeqStr);
963 }
Michael Gottesman60f6b282013-03-29 05:13:07 +0000964 Builder.CreateCall2(Callee, PtrName, S);
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000965}
966
Michael Gottesman81b1d432013-03-26 00:42:04 +0000967/// Adds a source annotation to pointer and a state change annotation to Inst
968/// referencing the source annotation and the old/new state of pointer.
969static void GenerateARCAnnotation(unsigned InstMDId,
970 unsigned PtrMDId,
971 Instruction *Inst,
972 Value *Ptr,
973 Sequence OldSeq,
974 Sequence NewSeq) {
975 if (EnableARCAnnotations) {
Michael Gottesman4e88ce62013-04-17 21:59:41 +0000976 // If we have a target identifier, make sure that we match it before
977 // emitting an annotation.
978 if(!ARCAnnotationTargetIdentifier.empty() &&
979 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
980 return;
Michael Gottesman9e518132013-04-18 04:34:11 +0000981
Michael Gottesman81b1d432013-03-26 00:42:04 +0000982 // First generate the source annotation on our pointer. This will return an
983 // MDString* if Ptr actually comes from an instruction implying we can put
984 // in a source annotation. If AppendMDNodeToSourcePtr returns 0 (i.e. NULL),
985 // then we know that our pointer is from an Argument so we put a reference
986 // to the argument number.
987 //
988 // The point of this is to make it easy for the
989 // llvm-arc-annotation-processor tool to cross reference where the source
990 // pointer is in the LLVM IR since the LLVM IR parser does not submit such
991 // information via debug info for backends to use (since why would anyone
992 // need such a thing from LLVM IR besides in non standard cases
993 // [i.e. this]).
994 MDString *SourcePtrMDNode =
995 AppendMDNodeToSourcePtr(PtrMDId, Ptr);
996 AppendMDNodeToInstForPtr(InstMDId, Inst, Ptr, SourcePtrMDNode, OldSeq,
997 NewSeq);
998 }
999}
1000
1001// The actual interface for accessing the above functionality is defined via
1002// some simple macros which are defined below. We do this so that the user does
1003// not need to pass in what metadata id is needed resulting in cleaner code and
1004// additionally since it provides an easy way to conditionally no-op all
1005// annotation support in a non-debug build.
1006
1007/// Use this macro to annotate a sequence state change when processing
1008/// instructions bottom up,
1009#define ANNOTATE_BOTTOMUP(inst, ptr, old, new) \
1010 GenerateARCAnnotation(ARCAnnotationBottomUpMDKind, \
1011 ARCAnnotationProvenanceSourceMDKind, (inst), \
1012 const_cast<Value*>(ptr), (old), (new))
1013/// Use this macro to annotate a sequence state change when processing
1014/// instructions top down.
1015#define ANNOTATE_TOPDOWN(inst, ptr, old, new) \
1016 GenerateARCAnnotation(ARCAnnotationTopDownMDKind, \
1017 ARCAnnotationProvenanceSourceMDKind, (inst), \
1018 const_cast<Value*>(ptr), (old), (new))
1019
Michael Gottesman43e7e002013-04-03 22:41:59 +00001020#define ANNOTATE_BB(_states, _bb, _name, _type, _direction) \
1021 do { \
Michael Gottesman89279f82013-04-05 18:10:41 +00001022 if (EnableARCAnnotations) { \
1023 for(BBState::ptr_const_iterator I = (_states)._direction##_ptr_begin(), \
Michael Gottesman43e7e002013-04-03 22:41:59 +00001024 E = (_states)._direction##_ptr_end(); I != E; ++I) { \
Michael Gottesman89279f82013-04-05 18:10:41 +00001025 Value *Ptr = const_cast<Value*>(I->first); \
1026 Sequence Seq = I->second.GetSeq(); \
1027 GenerateARCBB ## _type ## Annotation(_name, (_bb), Ptr, Seq); \
1028 } \
Michael Gottesman43e7e002013-04-03 22:41:59 +00001029 } \
Michael Gottesman89279f82013-04-05 18:10:41 +00001030 } while (0)
Michael Gottesman43e7e002013-04-03 22:41:59 +00001031
Michael Gottesman89279f82013-04-05 18:10:41 +00001032#define ANNOTATE_BOTTOMUP_BBSTART(_states, _basicblock) \
Michael Gottesman43e7e002013-04-03 22:41:59 +00001033 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbstart", \
1034 Entrance, bottom_up)
Michael Gottesman89279f82013-04-05 18:10:41 +00001035#define ANNOTATE_BOTTOMUP_BBEND(_states, _basicblock) \
1036 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbend", \
Michael Gottesman43e7e002013-04-03 22:41:59 +00001037 Terminator, bottom_up)
Michael Gottesman89279f82013-04-05 18:10:41 +00001038#define ANNOTATE_TOPDOWN_BBSTART(_states, _basicblock) \
1039 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbstart", \
Michael Gottesman43e7e002013-04-03 22:41:59 +00001040 Entrance, top_down)
Michael Gottesman89279f82013-04-05 18:10:41 +00001041#define ANNOTATE_TOPDOWN_BBEND(_states, _basicblock) \
1042 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbend", \
Michael Gottesman43e7e002013-04-03 22:41:59 +00001043 Terminator, top_down)
1044
Michael Gottesman81b1d432013-03-26 00:42:04 +00001045#else // !ARC_ANNOTATION
1046// If annotations are off, noop.
1047#define ANNOTATE_BOTTOMUP(inst, ptr, old, new)
1048#define ANNOTATE_TOPDOWN(inst, ptr, old, new)
Michael Gottesman43e7e002013-04-03 22:41:59 +00001049#define ANNOTATE_BOTTOMUP_BBSTART(states, basicblock)
1050#define ANNOTATE_BOTTOMUP_BBEND(states, basicblock)
1051#define ANNOTATE_TOPDOWN_BBSTART(states, basicblock)
1052#define ANNOTATE_TOPDOWN_BBEND(states, basicblock)
Michael Gottesman81b1d432013-03-26 00:42:04 +00001053#endif // !ARC_ANNOTATION
1054
John McCalld935e9c2011-06-15 23:37:01 +00001055namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001056 /// \brief The main ARC optimization pass.
John McCalld935e9c2011-06-15 23:37:01 +00001057 class ObjCARCOpt : public FunctionPass {
1058 bool Changed;
1059 ProvenanceAnalysis PA;
1060
Michael Gottesman97e3df02013-01-14 00:35:14 +00001061 /// A flag indicating whether this optimization pass should run.
Dan Gohmanceaac7c2011-06-20 23:20:43 +00001062 bool Run;
1063
Michael Gottesman97e3df02013-01-14 00:35:14 +00001064 /// Declarations for ObjC runtime functions, for use in creating calls to
1065 /// them. These are initialized lazily to avoid cluttering up the Module
1066 /// with unused declarations.
John McCalld935e9c2011-06-15 23:37:01 +00001067
Michael Gottesman97e3df02013-01-14 00:35:14 +00001068 /// Declaration for ObjC runtime function objc_autoreleaseReturnValue.
1069 Constant *AutoreleaseRVCallee;
1070 /// Declaration for ObjC runtime function objc_release.
1071 Constant *ReleaseCallee;
1072 /// Declaration for ObjC runtime function objc_retain.
1073 Constant *RetainCallee;
1074 /// Declaration for ObjC runtime function objc_retainBlock.
1075 Constant *RetainBlockCallee;
1076 /// Declaration for ObjC runtime function objc_autorelease.
1077 Constant *AutoreleaseCallee;
1078
1079 /// Flags which determine whether each of the interesting runtine functions
1080 /// is in fact used in the current function.
John McCalld935e9c2011-06-15 23:37:01 +00001081 unsigned UsedInThisFunction;
1082
Michael Gottesman97e3df02013-01-14 00:35:14 +00001083 /// The Metadata Kind for clang.imprecise_release metadata.
John McCalld935e9c2011-06-15 23:37:01 +00001084 unsigned ImpreciseReleaseMDKind;
1085
Michael Gottesman97e3df02013-01-14 00:35:14 +00001086 /// The Metadata Kind for clang.arc.copy_on_escape metadata.
Dan Gohmana7107f92011-10-17 22:53:25 +00001087 unsigned CopyOnEscapeMDKind;
1088
Michael Gottesman97e3df02013-01-14 00:35:14 +00001089 /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata.
Dan Gohman0155f302012-02-17 18:59:53 +00001090 unsigned NoObjCARCExceptionsMDKind;
1091
Michael Gottesman81b1d432013-03-26 00:42:04 +00001092#ifdef ARC_ANNOTATIONS
1093 /// The Metadata Kind for llvm.arc.annotation.bottomup metadata.
1094 unsigned ARCAnnotationBottomUpMDKind;
1095 /// The Metadata Kind for llvm.arc.annotation.topdown metadata.
1096 unsigned ARCAnnotationTopDownMDKind;
1097 /// The Metadata Kind for llvm.arc.annotation.provenancesource metadata.
1098 unsigned ARCAnnotationProvenanceSourceMDKind;
1099#endif // ARC_ANNOATIONS
1100
John McCalld935e9c2011-06-15 23:37:01 +00001101 Constant *getAutoreleaseRVCallee(Module *M);
1102 Constant *getReleaseCallee(Module *M);
1103 Constant *getRetainCallee(Module *M);
Dan Gohman6320f522011-07-22 22:29:21 +00001104 Constant *getRetainBlockCallee(Module *M);
John McCalld935e9c2011-06-15 23:37:01 +00001105 Constant *getAutoreleaseCallee(Module *M);
1106
Dan Gohman728db492012-01-13 00:39:07 +00001107 bool IsRetainBlockOptimizable(const Instruction *Inst);
1108
John McCalld935e9c2011-06-15 23:37:01 +00001109 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
Michael Gottesman556ff612013-01-12 01:25:19 +00001110 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1111 InstructionClass &Class);
Michael Gottesman158fdf62013-03-28 20:11:19 +00001112 bool OptimizeRetainBlockCall(Function &F, Instruction *RetainBlock,
1113 InstructionClass &Class);
John McCalld935e9c2011-06-15 23:37:01 +00001114 void OptimizeIndividualCalls(Function &F);
1115
1116 void CheckForCFGHazards(const BasicBlock *BB,
1117 DenseMap<const BasicBlock *, BBState> &BBStates,
1118 BBState &MyStates) const;
Dan Gohman817a7c62012-03-22 18:24:56 +00001119 bool VisitInstructionBottomUp(Instruction *Inst,
Dan Gohman5c70fad2012-03-23 17:47:54 +00001120 BasicBlock *BB,
Dan Gohman817a7c62012-03-22 18:24:56 +00001121 MapVector<Value *, RRInfo> &Retains,
1122 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00001123 bool VisitBottomUp(BasicBlock *BB,
1124 DenseMap<const BasicBlock *, BBState> &BBStates,
1125 MapVector<Value *, RRInfo> &Retains);
Dan Gohman817a7c62012-03-22 18:24:56 +00001126 bool VisitInstructionTopDown(Instruction *Inst,
1127 DenseMap<Value *, RRInfo> &Releases,
1128 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00001129 bool VisitTopDown(BasicBlock *BB,
1130 DenseMap<const BasicBlock *, BBState> &BBStates,
1131 DenseMap<Value *, RRInfo> &Releases);
1132 bool Visit(Function &F,
1133 DenseMap<const BasicBlock *, BBState> &BBStates,
1134 MapVector<Value *, RRInfo> &Retains,
1135 DenseMap<Value *, RRInfo> &Releases);
1136
1137 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1138 MapVector<Value *, RRInfo> &Retains,
1139 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman6320f522011-07-22 22:29:21 +00001140 SmallVectorImpl<Instruction *> &DeadInsts,
1141 Module *M);
John McCalld935e9c2011-06-15 23:37:01 +00001142
Michael Gottesman9de6f962013-01-22 21:49:00 +00001143 bool ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState> &BBStates,
1144 MapVector<Value *, RRInfo> &Retains,
1145 DenseMap<Value *, RRInfo> &Releases,
1146 Module *M,
1147 SmallVector<Instruction *, 4> &NewRetains,
1148 SmallVector<Instruction *, 4> &NewReleases,
1149 SmallVector<Instruction *, 8> &DeadInsts,
1150 RRInfo &RetainsToMove,
1151 RRInfo &ReleasesToMove,
1152 Value *Arg,
1153 bool KnownSafe,
1154 bool &AnyPairsCompletelyEliminated);
1155
John McCalld935e9c2011-06-15 23:37:01 +00001156 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1157 MapVector<Value *, RRInfo> &Retains,
Dan Gohman6320f522011-07-22 22:29:21 +00001158 DenseMap<Value *, RRInfo> &Releases,
1159 Module *M);
John McCalld935e9c2011-06-15 23:37:01 +00001160
1161 void OptimizeWeakCalls(Function &F);
1162
1163 bool OptimizeSequences(Function &F);
1164
1165 void OptimizeReturns(Function &F);
1166
Michael Gottesman9c118152013-04-29 06:16:57 +00001167#ifndef NDEBUG
1168 void GatherStatistics(Function &F, bool AfterOptimization = false);
1169#endif
1170
John McCalld935e9c2011-06-15 23:37:01 +00001171 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1172 virtual bool doInitialization(Module &M);
1173 virtual bool runOnFunction(Function &F);
1174 virtual void releaseMemory();
1175
1176 public:
1177 static char ID;
1178 ObjCARCOpt() : FunctionPass(ID) {
1179 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1180 }
1181 };
1182}
1183
1184char ObjCARCOpt::ID = 0;
1185INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1186 "objc-arc", "ObjC ARC optimization", false, false)
1187INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1188INITIALIZE_PASS_END(ObjCARCOpt,
1189 "objc-arc", "ObjC ARC optimization", false, false)
1190
1191Pass *llvm::createObjCARCOptPass() {
1192 return new ObjCARCOpt();
1193}
1194
1195void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1196 AU.addRequired<ObjCARCAliasAnalysis>();
1197 AU.addRequired<AliasAnalysis>();
1198 // ARC optimization doesn't currently split critical edges.
1199 AU.setPreservesCFG();
1200}
1201
Dan Gohman728db492012-01-13 00:39:07 +00001202bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1203 // Without the magic metadata tag, we have to assume this might be an
1204 // objc_retainBlock call inserted to convert a block pointer to an id,
1205 // in which case it really is needed.
1206 if (!Inst->getMetadata(CopyOnEscapeMDKind))
1207 return false;
1208
1209 // If the pointer "escapes" (not including being used in a call),
1210 // the copy may be needed.
Michael Gottesman774d2c02013-01-29 21:00:52 +00001211 if (DoesRetainableObjPtrEscape(Inst))
Dan Gohman728db492012-01-13 00:39:07 +00001212 return false;
1213
1214 // Otherwise, it's not needed.
1215 return true;
1216}
1217
John McCalld935e9c2011-06-15 23:37:01 +00001218Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1219 if (!AutoreleaseRVCallee) {
1220 LLVMContext &C = M->getContext();
Jay Foadb804a2b2011-07-12 14:06:48 +00001221 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman41375a32012-05-08 23:39:44 +00001222 Type *Params[] = { I8X };
1223 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001224 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001225 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1226 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001227 AutoreleaseRVCallee =
1228 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001229 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001230 }
1231 return AutoreleaseRVCallee;
1232}
1233
1234Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1235 if (!ReleaseCallee) {
1236 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001237 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001238 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001239 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1240 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001241 ReleaseCallee =
1242 M->getOrInsertFunction(
1243 "objc_release",
1244 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001245 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001246 }
1247 return ReleaseCallee;
1248}
1249
1250Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1251 if (!RetainCallee) {
1252 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001253 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001254 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001255 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1256 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001257 RetainCallee =
1258 M->getOrInsertFunction(
1259 "objc_retain",
1260 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001261 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001262 }
1263 return RetainCallee;
1264}
1265
Dan Gohman6320f522011-07-22 22:29:21 +00001266Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1267 if (!RetainBlockCallee) {
1268 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001269 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Dan Gohmanfca43c22011-09-14 18:33:34 +00001270 // objc_retainBlock is not nounwind because it calls user copy constructors
1271 // which could theoretically throw.
Dan Gohman6320f522011-07-22 22:29:21 +00001272 RetainBlockCallee =
1273 M->getOrInsertFunction(
1274 "objc_retainBlock",
1275 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendlinge94d8432012-12-07 23:16:57 +00001276 AttributeSet());
Dan Gohman6320f522011-07-22 22:29:21 +00001277 }
1278 return RetainBlockCallee;
1279}
1280
John McCalld935e9c2011-06-15 23:37:01 +00001281Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1282 if (!AutoreleaseCallee) {
1283 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001284 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001285 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001286 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1287 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001288 AutoreleaseCallee =
1289 M->getOrInsertFunction(
1290 "objc_autorelease",
1291 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001292 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001293 }
1294 return AutoreleaseCallee;
1295}
1296
Michael Gottesman97e3df02013-01-14 00:35:14 +00001297/// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is
1298/// not a return value. Or, if it can be paired with an
1299/// objc_autoreleaseReturnValue, delete the pair and return true.
John McCalld935e9c2011-06-15 23:37:01 +00001300bool
1301ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001302 // Check for the argument being from an immediately preceding call or invoke.
Dan Gohmandae33492012-04-27 18:56:31 +00001303 const Value *Arg = GetObjCArg(RetainRV);
1304 ImmutableCallSite CS(Arg);
1305 if (const Instruction *Call = CS.getInstruction()) {
John McCalld935e9c2011-06-15 23:37:01 +00001306 if (Call->getParent() == RetainRV->getParent()) {
Dan Gohmandae33492012-04-27 18:56:31 +00001307 BasicBlock::const_iterator I = Call;
John McCalld935e9c2011-06-15 23:37:01 +00001308 ++I;
Michael Gottesman65c24812013-03-25 09:27:43 +00001309 while (IsNoopInstruction(I)) ++I;
John McCalld935e9c2011-06-15 23:37:01 +00001310 if (&*I == RetainRV)
1311 return false;
Dan Gohmandae33492012-04-27 18:56:31 +00001312 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001313 BasicBlock *RetainRVParent = RetainRV->getParent();
1314 if (II->getNormalDest() == RetainRVParent) {
Dan Gohmandae33492012-04-27 18:56:31 +00001315 BasicBlock::const_iterator I = RetainRVParent->begin();
Michael Gottesman65c24812013-03-25 09:27:43 +00001316 while (IsNoopInstruction(I)) ++I;
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001317 if (&*I == RetainRV)
1318 return false;
1319 }
John McCalld935e9c2011-06-15 23:37:01 +00001320 }
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001321 }
John McCalld935e9c2011-06-15 23:37:01 +00001322
1323 // Check for being preceded by an objc_autoreleaseReturnValue on the same
1324 // pointer. In this case, we can delete the pair.
1325 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
1326 if (I != Begin) {
Michael Gottesman65c24812013-03-25 09:27:43 +00001327 do --I; while (I != Begin && IsNoopInstruction(I));
John McCalld935e9c2011-06-15 23:37:01 +00001328 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
1329 GetObjCArg(I) == Arg) {
1330 Changed = true;
1331 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00001332
Michael Gottesman89279f82013-04-05 18:10:41 +00001333 DEBUG(dbgs() << "Erasing autoreleaseRV,retainRV pair: " << *I << "\n"
1334 << "Erasing " << *RetainRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001335
John McCalld935e9c2011-06-15 23:37:01 +00001336 EraseInstruction(I);
1337 EraseInstruction(RetainRV);
1338 return true;
1339 }
1340 }
1341
1342 // Turn it to a plain objc_retain.
1343 Changed = true;
1344 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00001345
Michael Gottesman89279f82013-04-05 18:10:41 +00001346 DEBUG(dbgs() << "Transforming objc_retainAutoreleasedReturnValue => "
Michael Gottesmandef07bb2013-01-05 17:55:42 +00001347 "objc_retain since the operand is not a return value.\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00001348 "Old = " << *RetainRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001349
John McCalld935e9c2011-06-15 23:37:01 +00001350 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
Michael Gottesmandef07bb2013-01-05 17:55:42 +00001351
Michael Gottesman89279f82013-04-05 18:10:41 +00001352 DEBUG(dbgs() << "New = " << *RetainRV << "\n");
Michael Gottesmandef07bb2013-01-05 17:55:42 +00001353
John McCalld935e9c2011-06-15 23:37:01 +00001354 return false;
1355}
1356
Michael Gottesman97e3df02013-01-14 00:35:14 +00001357/// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not
1358/// used as a return value.
John McCalld935e9c2011-06-15 23:37:01 +00001359void
Michael Gottesman556ff612013-01-12 01:25:19 +00001360ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1361 InstructionClass &Class) {
John McCalld935e9c2011-06-15 23:37:01 +00001362 // Check for a return of the pointer value.
1363 const Value *Ptr = GetObjCArg(AutoreleaseRV);
Dan Gohman10a18d52011-08-12 00:36:31 +00001364 SmallVector<const Value *, 2> Users;
1365 Users.push_back(Ptr);
1366 do {
1367 Ptr = Users.pop_back_val();
1368 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
1369 UI != UE; ++UI) {
1370 const User *I = *UI;
1371 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
1372 return;
1373 if (isa<BitCastInst>(I))
1374 Users.push_back(I);
1375 }
1376 } while (!Users.empty());
John McCalld935e9c2011-06-15 23:37:01 +00001377
1378 Changed = true;
1379 ++NumPeeps;
Michael Gottesman1bf69082013-01-06 21:07:11 +00001380
Michael Gottesman89279f82013-04-05 18:10:41 +00001381 DEBUG(dbgs() << "Transforming objc_autoreleaseReturnValue => "
Michael Gottesman1bf69082013-01-06 21:07:11 +00001382 "objc_autorelease since its operand is not used as a return "
1383 "value.\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00001384 "Old = " << *AutoreleaseRV << "\n");
Michael Gottesman1bf69082013-01-06 21:07:11 +00001385
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001386 CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
1387 AutoreleaseRVCI->
John McCalld935e9c2011-06-15 23:37:01 +00001388 setCalledFunction(getAutoreleaseCallee(F.getParent()));
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001389 AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
Michael Gottesman556ff612013-01-12 01:25:19 +00001390 Class = IC_Autorelease;
Michael Gottesman10426b52013-01-07 21:26:07 +00001391
Michael Gottesman89279f82013-04-05 18:10:41 +00001392 DEBUG(dbgs() << "New: " << *AutoreleaseRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001393
John McCalld935e9c2011-06-15 23:37:01 +00001394}
1395
Michael Gottesman158fdf62013-03-28 20:11:19 +00001396// \brief Attempt to strength reduce objc_retainBlock calls to objc_retain
1397// calls.
1398//
1399// Specifically: If an objc_retainBlock call has the copy_on_escape metadata and
1400// does not escape (following the rules of block escaping), strength reduce the
1401// objc_retainBlock to an objc_retain.
1402//
1403// TODO: If an objc_retainBlock call is dominated period by a previous
1404// objc_retainBlock call, strength reduce the objc_retainBlock to an
1405// objc_retain.
1406bool
1407ObjCARCOpt::OptimizeRetainBlockCall(Function &F, Instruction *Inst,
1408 InstructionClass &Class) {
1409 assert(GetBasicInstructionClass(Inst) == Class);
1410 assert(IC_RetainBlock == Class);
Michael Gottesman60f6b282013-03-29 05:13:07 +00001411
Michael Gottesman158fdf62013-03-28 20:11:19 +00001412 // If we can not optimize Inst, return false.
1413 if (!IsRetainBlockOptimizable(Inst))
1414 return false;
Michael Gottesman60f6b282013-03-29 05:13:07 +00001415
Michael Gottesman3eab2e42013-04-21 00:50:27 +00001416 Changed = true;
1417 ++NumPeeps;
1418
1419 DEBUG(dbgs() << "Strength reduced retainBlock => retain.\n");
1420 DEBUG(dbgs() << "Old: " << *Inst << "\n");
Michael Gottesman158fdf62013-03-28 20:11:19 +00001421 CallInst *RetainBlock = cast<CallInst>(Inst);
1422 RetainBlock->setCalledFunction(getRetainCallee(F.getParent()));
1423 // Remove copy_on_escape metadata.
1424 RetainBlock->setMetadata(CopyOnEscapeMDKind, 0);
1425 Class = IC_Retain;
Michael Gottesman3eab2e42013-04-21 00:50:27 +00001426 DEBUG(dbgs() << "New: " << *Inst << "\n");
Michael Gottesman158fdf62013-03-28 20:11:19 +00001427 return true;
1428}
1429
Michael Gottesman97e3df02013-01-14 00:35:14 +00001430/// Visit each call, one at a time, and make simplifications without doing any
1431/// additional analysis.
John McCalld935e9c2011-06-15 23:37:01 +00001432void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001433 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeIndividualCalls ==\n");
John McCalld935e9c2011-06-15 23:37:01 +00001434 // Reset all the flags in preparation for recomputing them.
1435 UsedInThisFunction = 0;
1436
1437 // Visit all objc_* calls in F.
1438 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
1439 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +00001440
John McCalld935e9c2011-06-15 23:37:01 +00001441 InstructionClass Class = GetBasicInstructionClass(Inst);
1442
Michael Gottesman89279f82013-04-05 18:10:41 +00001443 DEBUG(dbgs() << "Visiting: Class: " << Class << "; " << *Inst << "\n");
Michael Gottesman782e3442013-01-17 18:32:34 +00001444
John McCalld935e9c2011-06-15 23:37:01 +00001445 switch (Class) {
1446 default: break;
1447
1448 // Delete no-op casts. These function calls have special semantics, but
1449 // the semantics are entirely implemented via lowering in the front-end,
1450 // so by the time they reach the optimizer, they are just no-op calls
1451 // which return their argument.
1452 //
1453 // There are gray areas here, as the ability to cast reference-counted
1454 // pointers to raw void* and back allows code to break ARC assumptions,
1455 // however these are currently considered to be unimportant.
1456 case IC_NoopCast:
1457 Changed = true;
1458 ++NumNoops;
Michael Gottesman89279f82013-04-05 18:10:41 +00001459 DEBUG(dbgs() << "Erasing no-op cast: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001460 EraseInstruction(Inst);
1461 continue;
1462
1463 // If the pointer-to-weak-pointer is null, it's undefined behavior.
1464 case IC_StoreWeak:
1465 case IC_LoadWeak:
1466 case IC_LoadWeakRetained:
1467 case IC_InitWeak:
1468 case IC_DestroyWeak: {
1469 CallInst *CI = cast<CallInst>(Inst);
Michael Gottesman65c24812013-03-25 09:27:43 +00001470 if (IsNullOrUndef(CI->getArgOperand(0))) {
Dan Gohman670f9372012-04-13 18:57:48 +00001471 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +00001472 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001473 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1474 Constant::getNullValue(Ty),
1475 CI);
Michael Gottesman10426b52013-01-07 21:26:07 +00001476 llvm::Value *NewValue = UndefValue::get(CI->getType());
Michael Gottesman89279f82013-04-05 18:10:41 +00001477 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
1478 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001479 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +00001480 CI->eraseFromParent();
1481 continue;
1482 }
1483 break;
1484 }
1485 case IC_CopyWeak:
1486 case IC_MoveWeak: {
1487 CallInst *CI = cast<CallInst>(Inst);
Michael Gottesman65c24812013-03-25 09:27:43 +00001488 if (IsNullOrUndef(CI->getArgOperand(0)) ||
1489 IsNullOrUndef(CI->getArgOperand(1))) {
Dan Gohman670f9372012-04-13 18:57:48 +00001490 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +00001491 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001492 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1493 Constant::getNullValue(Ty),
1494 CI);
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001495
1496 llvm::Value *NewValue = UndefValue::get(CI->getType());
Michael Gottesman89279f82013-04-05 18:10:41 +00001497 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
1498 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001499
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001500 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +00001501 CI->eraseFromParent();
1502 continue;
1503 }
1504 break;
1505 }
Michael Gottesman158fdf62013-03-28 20:11:19 +00001506 case IC_RetainBlock:
Michael Gottesman1e430042013-04-21 00:44:46 +00001507 // If we strength reduce an objc_retainBlock to an objc_retain, continue
Michael Gottesman158fdf62013-03-28 20:11:19 +00001508 // onto the objc_retain peephole optimizations. Otherwise break.
Michael Gottesman9fc50b82013-05-13 18:29:07 +00001509 OptimizeRetainBlockCall(F, Inst, Class);
John McCalld935e9c2011-06-15 23:37:01 +00001510 break;
1511 case IC_RetainRV:
1512 if (OptimizeRetainRVCall(F, Inst))
1513 continue;
1514 break;
1515 case IC_AutoreleaseRV:
Michael Gottesman556ff612013-01-12 01:25:19 +00001516 OptimizeAutoreleaseRVCall(F, Inst, Class);
John McCalld935e9c2011-06-15 23:37:01 +00001517 break;
1518 }
1519
Michael Gottesmanb8c88362013-04-03 02:57:24 +00001520 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
John McCalld935e9c2011-06-15 23:37:01 +00001521 if (IsAutorelease(Class) && Inst->use_empty()) {
1522 CallInst *Call = cast<CallInst>(Inst);
1523 const Value *Arg = Call->getArgOperand(0);
1524 Arg = FindSingleUseIdentifiedObject(Arg);
1525 if (Arg) {
1526 Changed = true;
1527 ++NumAutoreleases;
1528
1529 // Create the declaration lazily.
1530 LLVMContext &C = Inst->getContext();
1531 CallInst *NewCall =
1532 CallInst::Create(getReleaseCallee(F.getParent()),
1533 Call->getArgOperand(0), "", Call);
Dmitri Gribenko3238fb72013-05-05 00:40:33 +00001534 NewCall->setMetadata(ImpreciseReleaseMDKind, MDNode::get(C, None));
Michael Gottesman10426b52013-01-07 21:26:07 +00001535
Michael Gottesman89279f82013-04-05 18:10:41 +00001536 DEBUG(dbgs() << "Replacing autorelease{,RV}(x) with objc_release(x) "
1537 "since x is otherwise unused.\nOld: " << *Call << "\nNew: "
1538 << *NewCall << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001539
John McCalld935e9c2011-06-15 23:37:01 +00001540 EraseInstruction(Call);
1541 Inst = NewCall;
1542 Class = IC_Release;
1543 }
1544 }
1545
1546 // For functions which can never be passed stack arguments, add
1547 // a tail keyword.
1548 if (IsAlwaysTail(Class)) {
1549 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +00001550 DEBUG(dbgs() << "Adding tail keyword to function since it can never be "
1551 "passed stack args: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001552 cast<CallInst>(Inst)->setTailCall();
1553 }
1554
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001555 // Ensure that functions that can never have a "tail" keyword due to the
1556 // semantics of ARC truly do not do so.
1557 if (IsNeverTail(Class)) {
1558 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +00001559 DEBUG(dbgs() << "Removing tail keyword from function: " << *Inst <<
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001560 "\n");
1561 cast<CallInst>(Inst)->setTailCall(false);
1562 }
1563
John McCalld935e9c2011-06-15 23:37:01 +00001564 // Set nounwind as needed.
1565 if (IsNoThrow(Class)) {
1566 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +00001567 DEBUG(dbgs() << "Found no throw class. Setting nounwind on: " << *Inst
1568 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001569 cast<CallInst>(Inst)->setDoesNotThrow();
1570 }
1571
1572 if (!IsNoopOnNull(Class)) {
1573 UsedInThisFunction |= 1 << Class;
1574 continue;
1575 }
1576
1577 const Value *Arg = GetObjCArg(Inst);
1578
1579 // ARC calls with null are no-ops. Delete them.
Michael Gottesman65c24812013-03-25 09:27:43 +00001580 if (IsNullOrUndef(Arg)) {
John McCalld935e9c2011-06-15 23:37:01 +00001581 Changed = true;
1582 ++NumNoops;
Michael Gottesman89279f82013-04-05 18:10:41 +00001583 DEBUG(dbgs() << "ARC calls with null are no-ops. Erasing: " << *Inst
1584 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001585 EraseInstruction(Inst);
1586 continue;
1587 }
1588
1589 // Keep track of which of retain, release, autorelease, and retain_block
1590 // are actually present in this function.
1591 UsedInThisFunction |= 1 << Class;
1592
1593 // If Arg is a PHI, and one or more incoming values to the
1594 // PHI are null, and the call is control-equivalent to the PHI, and there
1595 // are no relevant side effects between the PHI and the call, the call
1596 // could be pushed up to just those paths with non-null incoming values.
1597 // For now, don't bother splitting critical edges for this.
1598 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
1599 Worklist.push_back(std::make_pair(Inst, Arg));
1600 do {
1601 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
1602 Inst = Pair.first;
1603 Arg = Pair.second;
1604
1605 const PHINode *PN = dyn_cast<PHINode>(Arg);
1606 if (!PN) continue;
1607
1608 // Determine if the PHI has any null operands, or any incoming
1609 // critical edges.
1610 bool HasNull = false;
1611 bool HasCriticalEdges = false;
1612 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1613 Value *Incoming =
1614 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
Michael Gottesman65c24812013-03-25 09:27:43 +00001615 if (IsNullOrUndef(Incoming))
John McCalld935e9c2011-06-15 23:37:01 +00001616 HasNull = true;
1617 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
1618 .getNumSuccessors() != 1) {
1619 HasCriticalEdges = true;
1620 break;
1621 }
1622 }
1623 // If we have null operands and no critical edges, optimize.
1624 if (!HasCriticalEdges && HasNull) {
1625 SmallPtrSet<Instruction *, 4> DependingInstructions;
1626 SmallPtrSet<const BasicBlock *, 4> Visited;
1627
1628 // Check that there is nothing that cares about the reference
1629 // count between the call and the phi.
Dan Gohman8478d762012-04-13 00:59:57 +00001630 switch (Class) {
1631 case IC_Retain:
1632 case IC_RetainBlock:
1633 // These can always be moved up.
1634 break;
1635 case IC_Release:
Dan Gohman41375a32012-05-08 23:39:44 +00001636 // These can't be moved across things that care about the retain
1637 // count.
Dan Gohman8478d762012-04-13 00:59:57 +00001638 FindDependencies(NeedsPositiveRetainCount, Arg,
1639 Inst->getParent(), Inst,
1640 DependingInstructions, Visited, PA);
1641 break;
1642 case IC_Autorelease:
1643 // These can't be moved across autorelease pool scope boundaries.
1644 FindDependencies(AutoreleasePoolBoundary, Arg,
1645 Inst->getParent(), Inst,
1646 DependingInstructions, Visited, PA);
1647 break;
1648 case IC_RetainRV:
1649 case IC_AutoreleaseRV:
1650 // Don't move these; the RV optimization depends on the autoreleaseRV
1651 // being tail called, and the retainRV being immediately after a call
1652 // (which might still happen if we get lucky with codegen layout, but
1653 // it's not worth taking the chance).
1654 continue;
1655 default:
1656 llvm_unreachable("Invalid dependence flavor");
1657 }
1658
John McCalld935e9c2011-06-15 23:37:01 +00001659 if (DependingInstructions.size() == 1 &&
1660 *DependingInstructions.begin() == PN) {
1661 Changed = true;
1662 ++NumPartialNoops;
1663 // Clone the call into each predecessor that has a non-null value.
1664 CallInst *CInst = cast<CallInst>(Inst);
Chris Lattner229907c2011-07-18 04:54:35 +00001665 Type *ParamTy = CInst->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001666 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1667 Value *Incoming =
1668 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
Michael Gottesman65c24812013-03-25 09:27:43 +00001669 if (!IsNullOrUndef(Incoming)) {
John McCalld935e9c2011-06-15 23:37:01 +00001670 CallInst *Clone = cast<CallInst>(CInst->clone());
1671 Value *Op = PN->getIncomingValue(i);
1672 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
1673 if (Op->getType() != ParamTy)
1674 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
1675 Clone->setArgOperand(0, Op);
1676 Clone->insertBefore(InsertPos);
Michael Gottesmanc189a392013-01-09 19:23:24 +00001677
Michael Gottesman89279f82013-04-05 18:10:41 +00001678 DEBUG(dbgs() << "Cloning "
Michael Gottesmanc189a392013-01-09 19:23:24 +00001679 << *CInst << "\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00001680 "And inserting clone at " << *InsertPos << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001681 Worklist.push_back(std::make_pair(Clone, Incoming));
1682 }
1683 }
1684 // Erase the original call.
Michael Gottesmanc189a392013-01-09 19:23:24 +00001685 DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001686 EraseInstruction(CInst);
1687 continue;
1688 }
1689 }
1690 } while (!Worklist.empty());
1691 }
1692}
1693
Michael Gottesman323964c2013-04-18 05:39:45 +00001694/// If we have a top down pointer in the S_Use state, make sure that there are
1695/// no CFG hazards by checking the states of various bottom up pointers.
1696static void CheckForUseCFGHazard(const Sequence SuccSSeq,
1697 const bool SuccSRRIKnownSafe,
1698 PtrState &S,
1699 bool &SomeSuccHasSame,
1700 bool &AllSuccsHaveSame,
1701 bool &ShouldContinue) {
1702 switch (SuccSSeq) {
1703 case S_CanRelease: {
1704 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
1705 S.ClearSequenceProgress();
1706 break;
1707 }
1708 ShouldContinue = true;
1709 break;
1710 }
1711 case S_Use:
1712 SomeSuccHasSame = true;
1713 break;
1714 case S_Stop:
1715 case S_Release:
1716 case S_MovableRelease:
1717 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
1718 AllSuccsHaveSame = false;
1719 break;
1720 case S_Retain:
1721 llvm_unreachable("bottom-up pointer in retain state!");
1722 case S_None:
1723 llvm_unreachable("This should have been handled earlier.");
1724 }
1725}
1726
1727/// If we have a Top Down pointer in the S_CanRelease state, make sure that
1728/// there are no CFG hazards by checking the states of various bottom up
1729/// pointers.
1730static void CheckForCanReleaseCFGHazard(const Sequence SuccSSeq,
1731 const bool SuccSRRIKnownSafe,
1732 PtrState &S,
1733 bool &SomeSuccHasSame,
1734 bool &AllSuccsHaveSame) {
1735 switch (SuccSSeq) {
1736 case S_CanRelease:
1737 SomeSuccHasSame = true;
1738 break;
1739 case S_Stop:
1740 case S_Release:
1741 case S_MovableRelease:
1742 case S_Use:
1743 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
1744 AllSuccsHaveSame = false;
1745 break;
1746 case S_Retain:
1747 llvm_unreachable("bottom-up pointer in retain state!");
1748 case S_None:
1749 llvm_unreachable("This should have been handled earlier.");
1750 }
1751}
1752
Michael Gottesman97e3df02013-01-14 00:35:14 +00001753/// Check for critical edges, loop boundaries, irreducible control flow, or
1754/// other CFG structures where moving code across the edge would result in it
1755/// being executed more.
John McCalld935e9c2011-06-15 23:37:01 +00001756void
1757ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
1758 DenseMap<const BasicBlock *, BBState> &BBStates,
1759 BBState &MyStates) const {
1760 // If any top-down local-use or possible-dec has a succ which is earlier in
1761 // the sequence, forget it.
Dan Gohman55b06742012-03-02 01:13:53 +00001762 for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
Michael Gottesman323964c2013-04-18 05:39:45 +00001763 E = MyStates.top_down_ptr_end(); I != E; ++I) {
1764 PtrState &S = I->second;
1765 const Sequence Seq = I->second.GetSeq();
Dan Gohman0155f302012-02-17 18:59:53 +00001766
Michael Gottesman323964c2013-04-18 05:39:45 +00001767 // We only care about S_Retain, S_CanRelease, and S_Use.
1768 if (Seq == S_None)
1769 continue;
Dan Gohman0155f302012-02-17 18:59:53 +00001770
Michael Gottesman323964c2013-04-18 05:39:45 +00001771 // Make sure that if extra top down states are added in the future that this
1772 // code is updated to handle it.
1773 assert((Seq == S_Retain || Seq == S_CanRelease || Seq == S_Use) &&
1774 "Unknown top down sequence state.");
1775
1776 const Value *Arg = I->first;
1777 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
1778 bool SomeSuccHasSame = false;
1779 bool AllSuccsHaveSame = true;
1780
1781 succ_const_iterator SI(TI), SE(TI, false);
1782
1783 for (; SI != SE; ++SI) {
1784 // If VisitBottomUp has pointer information for this successor, take
1785 // what we know about it.
1786 const DenseMap<const BasicBlock *, BBState>::iterator BBI =
1787 BBStates.find(*SI);
1788 assert(BBI != BBStates.end());
1789 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
1790 const Sequence SuccSSeq = SuccS.GetSeq();
1791
1792 // If bottom up, the pointer is in an S_None state, clear the sequence
1793 // progress since the sequence in the bottom up state finished
1794 // suggesting a mismatch in between retains/releases. This is true for
1795 // all three cases that we are handling here: S_Retain, S_Use, and
1796 // S_CanRelease.
1797 if (SuccSSeq == S_None) {
Dan Gohman12130272011-08-12 00:26:31 +00001798 S.ClearSequenceProgress();
Michael Gottesman323964c2013-04-18 05:39:45 +00001799 continue;
1800 }
1801
1802 // If we have S_Use or S_CanRelease, perform our check for cfg hazard
1803 // checks.
1804 const bool SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
1805
1806 // *NOTE* We do not use Seq from above here since we are allowing for
1807 // S.GetSeq() to change while we are visiting basic blocks.
1808 switch(S.GetSeq()) {
1809 case S_Use: {
1810 bool ShouldContinue = false;
1811 CheckForUseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S,
1812 SomeSuccHasSame, AllSuccsHaveSame,
1813 ShouldContinue);
1814 if (ShouldContinue)
1815 continue;
1816 break;
1817 }
1818 case S_CanRelease: {
1819 CheckForCanReleaseCFGHazard(SuccSSeq, SuccSRRIKnownSafe,
1820 S, SomeSuccHasSame,
1821 AllSuccsHaveSame);
1822 break;
1823 }
1824 case S_Retain:
1825 case S_None:
1826 case S_Stop:
1827 case S_Release:
1828 case S_MovableRelease:
1829 break;
1830 }
John McCalld935e9c2011-06-15 23:37:01 +00001831 }
Michael Gottesman323964c2013-04-18 05:39:45 +00001832
1833 // If the state at the other end of any of the successor edges
1834 // matches the current state, require all edges to match. This
1835 // guards against loops in the middle of a sequence.
1836 if (SomeSuccHasSame && !AllSuccsHaveSame)
1837 S.ClearSequenceProgress();
1838 }
John McCalld935e9c2011-06-15 23:37:01 +00001839}
1840
1841bool
Dan Gohman817a7c62012-03-22 18:24:56 +00001842ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
Dan Gohman5c70fad2012-03-23 17:47:54 +00001843 BasicBlock *BB,
Dan Gohman817a7c62012-03-22 18:24:56 +00001844 MapVector<Value *, RRInfo> &Retains,
1845 BBState &MyStates) {
1846 bool NestingDetected = false;
1847 InstructionClass Class = GetInstructionClass(Inst);
1848 const Value *Arg = 0;
Michael Gottesman79249972013-04-05 23:46:45 +00001849
Michael Gottesman1d8d2572013-04-05 22:54:28 +00001850 DEBUG(dbgs() << "Class: " << Class << "\n");
Michael Gottesman79249972013-04-05 23:46:45 +00001851
Dan Gohman817a7c62012-03-22 18:24:56 +00001852 switch (Class) {
1853 case IC_Release: {
1854 Arg = GetObjCArg(Inst);
1855
1856 PtrState &S = MyStates.getPtrBottomUpState(Arg);
1857
1858 // If we see two releases in a row on the same pointer. If so, make
1859 // a note, and we'll cicle back to revisit it after we've
1860 // hopefully eliminated the second release, which may allow us to
1861 // eliminate the first release too.
1862 // Theoretically we could implement removal of nested retain+release
1863 // pairs by making PtrState hold a stack of states, but this is
1864 // simple and avoids adding overhead for the non-nested case.
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001865 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001866 DEBUG(dbgs() << "Found nested releases (i.e. a release pair)\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00001867 NestingDetected = true;
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001868 }
Dan Gohman817a7c62012-03-22 18:24:56 +00001869
Dan Gohman817a7c62012-03-22 18:24:56 +00001870 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001871 Sequence NewSeq = ReleaseMetadata ? S_MovableRelease : S_Release;
1872 ANNOTATE_BOTTOMUP(Inst, Arg, S.GetSeq(), NewSeq);
1873 S.ResetSequenceProgress(NewSeq);
Dan Gohman817a7c62012-03-22 18:24:56 +00001874 S.RRI.ReleaseMetadata = ReleaseMetadata;
Michael Gottesman07beea42013-03-23 05:31:01 +00001875 S.RRI.KnownSafe = S.HasKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001876 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
1877 S.RRI.Calls.insert(Inst);
Dan Gohmandf476e52012-09-04 23:16:20 +00001878 S.SetKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001879 break;
1880 }
1881 case IC_RetainBlock:
Michael Gottesman158fdf62013-03-28 20:11:19 +00001882 // In OptimizeIndividualCalls, we have strength reduced all optimizable
1883 // objc_retainBlocks to objc_retains. Thus at this point any
1884 // objc_retainBlocks that we see are not optimizable.
1885 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001886 case IC_Retain:
1887 case IC_RetainRV: {
1888 Arg = GetObjCArg(Inst);
1889
1890 PtrState &S = MyStates.getPtrBottomUpState(Arg);
Dan Gohman62079b42012-04-25 00:50:46 +00001891 S.SetKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001892
Michael Gottesman81b1d432013-03-26 00:42:04 +00001893 Sequence OldSeq = S.GetSeq();
1894 switch (OldSeq) {
Dan Gohman817a7c62012-03-22 18:24:56 +00001895 case S_Stop:
1896 case S_Release:
1897 case S_MovableRelease:
1898 case S_Use:
Michael Gottesman1d8d2572013-04-05 22:54:28 +00001899 // If OldSeq is not S_Use or OldSeq is S_Use and we are tracking an
1900 // imprecise release, clear our reverse insertion points.
1901 if (OldSeq != S_Use || S.RRI.IsTrackingImpreciseReleases())
1902 S.RRI.ReverseInsertPts.clear();
Dan Gohman817a7c62012-03-22 18:24:56 +00001903 // FALL THROUGH
1904 case S_CanRelease:
1905 // Don't do retain+release tracking for IC_RetainRV, because it's
1906 // better to let it remain as the first instruction after a call.
Michael Gottesmanba648592013-03-28 23:08:44 +00001907 if (Class != IC_RetainRV)
Dan Gohman817a7c62012-03-22 18:24:56 +00001908 Retains[Inst] = S.RRI;
Dan Gohman817a7c62012-03-22 18:24:56 +00001909 S.ClearSequenceProgress();
1910 break;
1911 case S_None:
1912 break;
1913 case S_Retain:
1914 llvm_unreachable("bottom-up pointer in retain state!");
1915 }
Michael Gottesman79249972013-04-05 23:46:45 +00001916 ANNOTATE_BOTTOMUP(Inst, Arg, OldSeq, S.GetSeq());
Michael Gottesman31ba23a2013-04-05 22:54:32 +00001917 // A retain moving bottom up can be a use.
1918 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001919 }
1920 case IC_AutoreleasepoolPop:
1921 // Conservatively, clear MyStates for all known pointers.
1922 MyStates.clearBottomUpPointers();
1923 return NestingDetected;
1924 case IC_AutoreleasepoolPush:
1925 case IC_None:
1926 // These are irrelevant.
1927 return NestingDetected;
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001928 case IC_User:
1929 // If we have a store into an alloca of a pointer we are tracking, the
1930 // pointer has multiple owners implying that we must be more conservative.
1931 //
1932 // This comes up in the context of a pointer being ``KnownSafe''. In the
1933 // presense of a block being initialized, the frontend will emit the
1934 // objc_retain on the original pointer and the release on the pointer loaded
1935 // from the alloca. The optimizer will through the provenance analysis
1936 // realize that the two are related, but since we only require KnownSafe in
1937 // one direction, will match the inner retain on the original pointer with
1938 // the guard release on the original pointer. This is fixed by ensuring that
1939 // in the presense of allocas we only unconditionally remove pointers if
1940 // both our retain and our release are KnownSafe.
1941 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1942 if (AreAnyUnderlyingObjectsAnAlloca(SI->getPointerOperand())) {
1943 BBState::ptr_iterator I = MyStates.findPtrBottomUpState(
1944 StripPointerCastsAndObjCCalls(SI->getValueOperand()));
1945 if (I != MyStates.bottom_up_ptr_end())
1946 I->second.RRI.MultipleOwners = true;
1947 }
1948 }
1949 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001950 default:
1951 break;
1952 }
1953
1954 // Consider any other possible effects of this instruction on each
1955 // pointer being tracked.
1956 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
1957 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
1958 const Value *Ptr = MI->first;
1959 if (Ptr == Arg)
1960 continue; // Handled above.
1961 PtrState &S = MI->second;
1962 Sequence Seq = S.GetSeq();
1963
1964 // Check for possible releases.
1965 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001966 DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr
1967 << "\n");
Michael Gottesman764b1cf2013-03-23 05:46:19 +00001968 S.ClearKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001969 switch (Seq) {
1970 case S_Use:
1971 S.SetSeq(S_CanRelease);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001972 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S.GetSeq());
Dan Gohman817a7c62012-03-22 18:24:56 +00001973 continue;
1974 case S_CanRelease:
1975 case S_Release:
1976 case S_MovableRelease:
1977 case S_Stop:
1978 case S_None:
1979 break;
1980 case S_Retain:
1981 llvm_unreachable("bottom-up pointer in retain state!");
1982 }
1983 }
1984
1985 // Check for possible direct uses.
1986 switch (Seq) {
1987 case S_Release:
1988 case S_MovableRelease:
1989 if (CanUse(Inst, Ptr, PA, Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001990 DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr
1991 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00001992 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohman5c70fad2012-03-23 17:47:54 +00001993 // If this is an invoke instruction, we're scanning it as part of
1994 // one of its successor blocks, since we can't insert code after it
1995 // in its own block, and we don't want to split critical edges.
1996 if (isa<InvokeInst>(Inst))
1997 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
1998 else
Francois Pichet4b9ab742012-03-24 01:36:37 +00001999 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohman817a7c62012-03-22 18:24:56 +00002000 S.SetSeq(S_Use);
Michael Gottesman81b1d432013-03-26 00:42:04 +00002001 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
John McCall20182ac2013-03-22 21:38:36 +00002002 } else if (Seq == S_Release && IsUser(Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002003 DEBUG(dbgs() << "PreciseReleaseUse: Seq: " << Seq << "; " << *Ptr
2004 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00002005 // Non-movable releases depend on any possible objc pointer use.
2006 S.SetSeq(S_Stop);
Michael Gottesman81b1d432013-03-26 00:42:04 +00002007 ANNOTATE_BOTTOMUP(Inst, Ptr, S_Release, S_Stop);
Dan Gohman817a7c62012-03-22 18:24:56 +00002008 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohman5c70fad2012-03-23 17:47:54 +00002009 // As above; handle invoke specially.
2010 if (isa<InvokeInst>(Inst))
2011 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2012 else
Francois Pichet4b9ab742012-03-24 01:36:37 +00002013 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohman817a7c62012-03-22 18:24:56 +00002014 }
2015 break;
2016 case S_Stop:
Michael Gottesman81b1d432013-03-26 00:42:04 +00002017 if (CanUse(Inst, Ptr, PA, Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002018 DEBUG(dbgs() << "PreciseStopUse: Seq: " << Seq << "; " << *Ptr
2019 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00002020 S.SetSeq(S_Use);
Michael Gottesman81b1d432013-03-26 00:42:04 +00002021 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
2022 }
Dan Gohman817a7c62012-03-22 18:24:56 +00002023 break;
2024 case S_CanRelease:
2025 case S_Use:
2026 case S_None:
2027 break;
2028 case S_Retain:
2029 llvm_unreachable("bottom-up pointer in retain state!");
2030 }
2031 }
2032
2033 return NestingDetected;
2034}
2035
2036bool
John McCalld935e9c2011-06-15 23:37:01 +00002037ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2038 DenseMap<const BasicBlock *, BBState> &BBStates,
2039 MapVector<Value *, RRInfo> &Retains) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002040
2041 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitBottomUp ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00002042
John McCalld935e9c2011-06-15 23:37:01 +00002043 bool NestingDetected = false;
2044 BBState &MyStates = BBStates[BB];
2045
2046 // Merge the states from each successor to compute the initial state
2047 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00002048 BBState::edge_iterator SI(MyStates.succ_begin()),
2049 SE(MyStates.succ_end());
2050 if (SI != SE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002051 const BasicBlock *Succ = *SI;
2052 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
2053 assert(I != BBStates.end());
2054 MyStates.InitFromSucc(I->second);
2055 ++SI;
2056 for (; SI != SE; ++SI) {
2057 Succ = *SI;
2058 I = BBStates.find(Succ);
2059 assert(I != BBStates.end());
2060 MyStates.MergeSucc(I->second);
2061 }
Michael Gottesman60f6b282013-03-29 05:13:07 +00002062 }
Michael Gottesmancd4de0f2013-03-26 00:42:09 +00002063
Michael Gottesman43e7e002013-04-03 22:41:59 +00002064 // If ARC Annotations are enabled, output the current state of pointers at the
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002065 // bottom of the basic block.
Michael Gottesman43e7e002013-04-03 22:41:59 +00002066 ANNOTATE_BOTTOMUP_BBEND(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002067
John McCalld935e9c2011-06-15 23:37:01 +00002068 // Visit all the instructions, bottom-up.
2069 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2070 Instruction *Inst = llvm::prior(I);
Dan Gohman5c70fad2012-03-23 17:47:54 +00002071
2072 // Invoke instructions are visited as part of their successors (below).
2073 if (isa<InvokeInst>(Inst))
2074 continue;
2075
Michael Gottesman89279f82013-04-05 18:10:41 +00002076 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00002077
Dan Gohman5c70fad2012-03-23 17:47:54 +00002078 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
2079 }
2080
Dan Gohmandae33492012-04-27 18:56:31 +00002081 // If there's a predecessor with an invoke, visit the invoke as if it were
2082 // part of this block, since we can't insert code after an invoke in its own
2083 // block, and we don't want to split critical edges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002084 for (BBState::edge_iterator PI(MyStates.pred_begin()),
2085 PE(MyStates.pred_end()); PI != PE; ++PI) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00002086 BasicBlock *Pred = *PI;
Dan Gohmandae33492012-04-27 18:56:31 +00002087 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
2088 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
Dan Gohman817a7c62012-03-22 18:24:56 +00002089 }
John McCalld935e9c2011-06-15 23:37:01 +00002090
Michael Gottesman43e7e002013-04-03 22:41:59 +00002091 // If ARC Annotations are enabled, output the current state of pointers at the
2092 // top of the basic block.
2093 ANNOTATE_BOTTOMUP_BBSTART(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002094
Dan Gohman817a7c62012-03-22 18:24:56 +00002095 return NestingDetected;
2096}
John McCalld935e9c2011-06-15 23:37:01 +00002097
Dan Gohman817a7c62012-03-22 18:24:56 +00002098bool
2099ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
2100 DenseMap<Value *, RRInfo> &Releases,
2101 BBState &MyStates) {
2102 bool NestingDetected = false;
2103 InstructionClass Class = GetInstructionClass(Inst);
2104 const Value *Arg = 0;
John McCalld935e9c2011-06-15 23:37:01 +00002105
Dan Gohman817a7c62012-03-22 18:24:56 +00002106 switch (Class) {
2107 case IC_RetainBlock:
Michael Gottesman158fdf62013-03-28 20:11:19 +00002108 // In OptimizeIndividualCalls, we have strength reduced all optimizable
2109 // objc_retainBlocks to objc_retains. Thus at this point any
2110 // objc_retainBlocks that we see are not optimizable.
2111 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00002112 case IC_Retain:
2113 case IC_RetainRV: {
2114 Arg = GetObjCArg(Inst);
2115
2116 PtrState &S = MyStates.getPtrTopDownState(Arg);
2117
2118 // Don't do retain+release tracking for IC_RetainRV, because it's
2119 // better to let it remain as the first instruction after a call.
2120 if (Class != IC_RetainRV) {
2121 // If we see two retains in a row on the same pointer. If so, make
John McCalld935e9c2011-06-15 23:37:01 +00002122 // a note, and we'll cicle back to revisit it after we've
Dan Gohman817a7c62012-03-22 18:24:56 +00002123 // hopefully eliminated the second retain, which may allow us to
2124 // eliminate the first retain too.
John McCalld935e9c2011-06-15 23:37:01 +00002125 // Theoretically we could implement removal of nested retain+release
2126 // pairs by making PtrState hold a stack of states, but this is
2127 // simple and avoids adding overhead for the non-nested case.
Dan Gohman817a7c62012-03-22 18:24:56 +00002128 if (S.GetSeq() == S_Retain)
John McCalld935e9c2011-06-15 23:37:01 +00002129 NestingDetected = true;
2130
Michael Gottesman81b1d432013-03-26 00:42:04 +00002131 ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_Retain);
Dan Gohman62079b42012-04-25 00:50:46 +00002132 S.ResetSequenceProgress(S_Retain);
Michael Gottesman07beea42013-03-23 05:31:01 +00002133 S.RRI.KnownSafe = S.HasKnownPositiveRefCount();
John McCalld935e9c2011-06-15 23:37:01 +00002134 S.RRI.Calls.insert(Inst);
John McCalld935e9c2011-06-15 23:37:01 +00002135 }
John McCalld935e9c2011-06-15 23:37:01 +00002136
Dan Gohmandf476e52012-09-04 23:16:20 +00002137 S.SetKnownPositiveRefCount();
Dan Gohmanf64ff8e2012-07-23 19:27:31 +00002138
2139 // A retain can be a potential use; procede to the generic checking
2140 // code below.
2141 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00002142 }
2143 case IC_Release: {
2144 Arg = GetObjCArg(Inst);
2145
2146 PtrState &S = MyStates.getPtrTopDownState(Arg);
Michael Gottesman764b1cf2013-03-23 05:46:19 +00002147 S.ClearKnownPositiveRefCount();
Michael Gottesman79249972013-04-05 23:46:45 +00002148
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002149 Sequence OldSeq = S.GetSeq();
Michael Gottesman79249972013-04-05 23:46:45 +00002150
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002151 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
Michael Gottesman79249972013-04-05 23:46:45 +00002152
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002153 switch (OldSeq) {
Dan Gohman817a7c62012-03-22 18:24:56 +00002154 case S_Retain:
2155 case S_CanRelease:
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002156 if (OldSeq == S_Retain || ReleaseMetadata != 0)
2157 S.RRI.ReverseInsertPts.clear();
Dan Gohman817a7c62012-03-22 18:24:56 +00002158 // FALL THROUGH
2159 case S_Use:
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002160 S.RRI.ReleaseMetadata = ReleaseMetadata;
Dan Gohman817a7c62012-03-22 18:24:56 +00002161 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2162 Releases[Inst] = S.RRI;
Michael Gottesman81b1d432013-03-26 00:42:04 +00002163 ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_None);
Dan Gohman817a7c62012-03-22 18:24:56 +00002164 S.ClearSequenceProgress();
2165 break;
2166 case S_None:
2167 break;
2168 case S_Stop:
2169 case S_Release:
2170 case S_MovableRelease:
2171 llvm_unreachable("top-down pointer in release state!");
2172 }
2173 break;
2174 }
2175 case IC_AutoreleasepoolPop:
2176 // Conservatively, clear MyStates for all known pointers.
2177 MyStates.clearTopDownPointers();
2178 return NestingDetected;
2179 case IC_AutoreleasepoolPush:
2180 case IC_None:
2181 // These are irrelevant.
2182 return NestingDetected;
2183 default:
2184 break;
2185 }
2186
2187 // Consider any other possible effects of this instruction on each
2188 // pointer being tracked.
2189 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
2190 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
2191 const Value *Ptr = MI->first;
2192 if (Ptr == Arg)
2193 continue; // Handled above.
2194 PtrState &S = MI->second;
2195 Sequence Seq = S.GetSeq();
2196
2197 // Check for possible releases.
2198 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Michael Gottesmanbab49e972013-04-05 18:26:08 +00002199 DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr
Michael Gottesman79249972013-04-05 23:46:45 +00002200 << "\n");
Michael Gottesman764b1cf2013-03-23 05:46:19 +00002201 S.ClearKnownPositiveRefCount();
John McCalld935e9c2011-06-15 23:37:01 +00002202 switch (Seq) {
Dan Gohman817a7c62012-03-22 18:24:56 +00002203 case S_Retain:
2204 S.SetSeq(S_CanRelease);
Michael Gottesman81b1d432013-03-26 00:42:04 +00002205 ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_CanRelease);
Dan Gohman817a7c62012-03-22 18:24:56 +00002206 assert(S.RRI.ReverseInsertPts.empty());
2207 S.RRI.ReverseInsertPts.insert(Inst);
2208
2209 // One call can't cause a transition from S_Retain to S_CanRelease
2210 // and S_CanRelease to S_Use. If we've made the first transition,
2211 // we're done.
2212 continue;
John McCalld935e9c2011-06-15 23:37:01 +00002213 case S_Use:
Dan Gohman817a7c62012-03-22 18:24:56 +00002214 case S_CanRelease:
John McCalld935e9c2011-06-15 23:37:01 +00002215 case S_None:
2216 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00002217 case S_Stop:
2218 case S_Release:
2219 case S_MovableRelease:
2220 llvm_unreachable("top-down pointer in release state!");
John McCalld935e9c2011-06-15 23:37:01 +00002221 }
2222 }
Dan Gohman817a7c62012-03-22 18:24:56 +00002223
2224 // Check for possible direct uses.
2225 switch (Seq) {
2226 case S_CanRelease:
Michael Gottesman81b1d432013-03-26 00:42:04 +00002227 if (CanUse(Inst, Ptr, PA, Class)) {
Michael Gottesmanbab49e972013-04-05 18:26:08 +00002228 DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr
2229 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00002230 S.SetSeq(S_Use);
Michael Gottesman81b1d432013-03-26 00:42:04 +00002231 ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_Use);
2232 }
Dan Gohman817a7c62012-03-22 18:24:56 +00002233 break;
2234 case S_Retain:
2235 case S_Use:
2236 case S_None:
2237 break;
2238 case S_Stop:
2239 case S_Release:
2240 case S_MovableRelease:
2241 llvm_unreachable("top-down pointer in release state!");
2242 }
John McCalld935e9c2011-06-15 23:37:01 +00002243 }
2244
2245 return NestingDetected;
2246}
2247
2248bool
2249ObjCARCOpt::VisitTopDown(BasicBlock *BB,
2250 DenseMap<const BasicBlock *, BBState> &BBStates,
2251 DenseMap<Value *, RRInfo> &Releases) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002252 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitTopDown ==\n");
John McCalld935e9c2011-06-15 23:37:01 +00002253 bool NestingDetected = false;
2254 BBState &MyStates = BBStates[BB];
2255
2256 // Merge the states from each predecessor to compute the initial state
2257 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00002258 BBState::edge_iterator PI(MyStates.pred_begin()),
2259 PE(MyStates.pred_end());
2260 if (PI != PE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002261 const BasicBlock *Pred = *PI;
2262 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
2263 assert(I != BBStates.end());
2264 MyStates.InitFromPred(I->second);
2265 ++PI;
2266 for (; PI != PE; ++PI) {
2267 Pred = *PI;
2268 I = BBStates.find(Pred);
2269 assert(I != BBStates.end());
2270 MyStates.MergePred(I->second);
2271 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002272 }
John McCalld935e9c2011-06-15 23:37:01 +00002273
Michael Gottesman43e7e002013-04-03 22:41:59 +00002274 // If ARC Annotations are enabled, output the current state of pointers at the
2275 // top of the basic block.
2276 ANNOTATE_TOPDOWN_BBSTART(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002277
John McCalld935e9c2011-06-15 23:37:01 +00002278 // Visit all the instructions, top-down.
2279 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2280 Instruction *Inst = I;
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00002281
Michael Gottesman89279f82013-04-05 18:10:41 +00002282 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00002283
Dan Gohman817a7c62012-03-22 18:24:56 +00002284 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00002285 }
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002286
Michael Gottesman43e7e002013-04-03 22:41:59 +00002287 // If ARC Annotations are enabled, output the current state of pointers at the
2288 // bottom of the basic block.
2289 ANNOTATE_TOPDOWN_BBEND(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002290
Michael Gottesmanffef24f2013-04-17 20:48:01 +00002291#ifdef ARC_ANNOTATIONS
Michael Gottesmanadb921a2013-04-17 21:03:53 +00002292 if (!(EnableARCAnnotations && DisableCheckForCFGHazards))
Michael Gottesmanffef24f2013-04-17 20:48:01 +00002293#endif
John McCalld935e9c2011-06-15 23:37:01 +00002294 CheckForCFGHazards(BB, BBStates, MyStates);
2295 return NestingDetected;
2296}
2297
Dan Gohmana53a12c2011-12-12 19:42:25 +00002298static void
2299ComputePostOrders(Function &F,
2300 SmallVectorImpl<BasicBlock *> &PostOrder,
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002301 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
2302 unsigned NoObjCARCExceptionsMDKind,
2303 DenseMap<const BasicBlock *, BBState> &BBStates) {
Michael Gottesman97e3df02013-01-14 00:35:14 +00002304 /// The visited set, for doing DFS walks.
Dan Gohmana53a12c2011-12-12 19:42:25 +00002305 SmallPtrSet<BasicBlock *, 16> Visited;
2306
2307 // Do DFS, computing the PostOrder.
2308 SmallPtrSet<BasicBlock *, 16> OnStack;
2309 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002310
2311 // Functions always have exactly one entry block, and we don't have
2312 // any other block that we treat like an entry block.
Dan Gohmana53a12c2011-12-12 19:42:25 +00002313 BasicBlock *EntryBB = &F.getEntryBlock();
Dan Gohman41375a32012-05-08 23:39:44 +00002314 BBState &MyStates = BBStates[EntryBB];
2315 MyStates.SetAsEntry();
2316 TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
2317 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
Dan Gohmana53a12c2011-12-12 19:42:25 +00002318 Visited.insert(EntryBB);
2319 OnStack.insert(EntryBB);
2320 do {
2321 dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002322 BasicBlock *CurrBB = SuccStack.back().first;
2323 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
2324 succ_iterator SE(TI, false);
Dan Gohman41375a32012-05-08 23:39:44 +00002325
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002326 while (SuccStack.back().second != SE) {
2327 BasicBlock *SuccBB = *SuccStack.back().second++;
2328 if (Visited.insert(SuccBB)) {
Dan Gohman41375a32012-05-08 23:39:44 +00002329 TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
2330 SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002331 BBStates[CurrBB].addSucc(SuccBB);
Dan Gohman41375a32012-05-08 23:39:44 +00002332 BBState &SuccStates = BBStates[SuccBB];
2333 SuccStates.addPred(CurrBB);
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002334 OnStack.insert(SuccBB);
Dan Gohmana53a12c2011-12-12 19:42:25 +00002335 goto dfs_next_succ;
2336 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002337
2338 if (!OnStack.count(SuccBB)) {
2339 BBStates[CurrBB].addSucc(SuccBB);
2340 BBStates[SuccBB].addPred(CurrBB);
2341 }
Dan Gohmana53a12c2011-12-12 19:42:25 +00002342 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002343 OnStack.erase(CurrBB);
2344 PostOrder.push_back(CurrBB);
2345 SuccStack.pop_back();
Dan Gohmana53a12c2011-12-12 19:42:25 +00002346 } while (!SuccStack.empty());
2347
2348 Visited.clear();
2349
Dan Gohmana53a12c2011-12-12 19:42:25 +00002350 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002351 // Functions may have many exits, and there also blocks which we treat
2352 // as exits due to ignored edges.
2353 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
2354 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
2355 BasicBlock *ExitBB = I;
2356 BBState &MyStates = BBStates[ExitBB];
2357 if (!MyStates.isExit())
2358 continue;
2359
Dan Gohmandae33492012-04-27 18:56:31 +00002360 MyStates.SetAsExit();
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002361
2362 PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00002363 Visited.insert(ExitBB);
2364 while (!PredStack.empty()) {
2365 reverse_dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002366 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
2367 while (PredStack.back().second != PE) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00002368 BasicBlock *BB = *PredStack.back().second++;
Dan Gohmana53a12c2011-12-12 19:42:25 +00002369 if (Visited.insert(BB)) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002370 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00002371 goto reverse_dfs_next_succ;
2372 }
2373 }
2374 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
2375 }
2376 }
2377}
2378
Michael Gottesman97e3df02013-01-14 00:35:14 +00002379// Visit the function both top-down and bottom-up.
John McCalld935e9c2011-06-15 23:37:01 +00002380bool
2381ObjCARCOpt::Visit(Function &F,
2382 DenseMap<const BasicBlock *, BBState> &BBStates,
2383 MapVector<Value *, RRInfo> &Retains,
2384 DenseMap<Value *, RRInfo> &Releases) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00002385
2386 // Use reverse-postorder traversals, because we magically know that loops
2387 // will be well behaved, i.e. they won't repeatedly call retain on a single
2388 // pointer without doing a release. We can't use the ReversePostOrderTraversal
2389 // class here because we want the reverse-CFG postorder to consider each
2390 // function exit point, and we want to ignore selected cycle edges.
2391 SmallVector<BasicBlock *, 16> PostOrder;
2392 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002393 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
2394 NoObjCARCExceptionsMDKind,
2395 BBStates);
Dan Gohmana53a12c2011-12-12 19:42:25 +00002396
2397 // Use reverse-postorder on the reverse CFG for bottom-up.
John McCalld935e9c2011-06-15 23:37:01 +00002398 bool BottomUpNestingDetected = false;
Dan Gohmanc57b58c2011-08-18 21:27:42 +00002399 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
Dan Gohmana53a12c2011-12-12 19:42:25 +00002400 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
2401 I != E; ++I)
2402 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
John McCalld935e9c2011-06-15 23:37:01 +00002403
Dan Gohmana53a12c2011-12-12 19:42:25 +00002404 // Use reverse-postorder for top-down.
John McCalld935e9c2011-06-15 23:37:01 +00002405 bool TopDownNestingDetected = false;
Dan Gohmana53a12c2011-12-12 19:42:25 +00002406 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2407 PostOrder.rbegin(), E = PostOrder.rend();
2408 I != E; ++I)
2409 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
John McCalld935e9c2011-06-15 23:37:01 +00002410
2411 return TopDownNestingDetected && BottomUpNestingDetected;
2412}
2413
Michael Gottesman97e3df02013-01-14 00:35:14 +00002414/// Move the calls in RetainsToMove and ReleasesToMove.
John McCalld935e9c2011-06-15 23:37:01 +00002415void ObjCARCOpt::MoveCalls(Value *Arg,
2416 RRInfo &RetainsToMove,
2417 RRInfo &ReleasesToMove,
2418 MapVector<Value *, RRInfo> &Retains,
2419 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman6320f522011-07-22 22:29:21 +00002420 SmallVectorImpl<Instruction *> &DeadInsts,
Michael Gottesman79249972013-04-05 23:46:45 +00002421 Module *M) {
Chris Lattner229907c2011-07-18 04:54:35 +00002422 Type *ArgTy = Arg->getType();
Dan Gohman6320f522011-07-22 22:29:21 +00002423 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
Michael Gottesman79249972013-04-05 23:46:45 +00002424
Michael Gottesman89279f82013-04-05 18:10:41 +00002425 DEBUG(dbgs() << "== ObjCARCOpt::MoveCalls ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00002426
John McCalld935e9c2011-06-15 23:37:01 +00002427 // Insert the new retain and release calls.
2428 for (SmallPtrSet<Instruction *, 2>::const_iterator
2429 PI = ReleasesToMove.ReverseInsertPts.begin(),
2430 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2431 Instruction *InsertPt = *PI;
2432 Value *MyArg = ArgTy == ParamTy ? Arg :
2433 new BitCastInst(Arg, ParamTy, "", InsertPt);
2434 CallInst *Call =
Michael Gottesmanba648592013-03-28 23:08:44 +00002435 CallInst::Create(getRetainCallee(M), MyArg, "", InsertPt);
John McCalld935e9c2011-06-15 23:37:01 +00002436 Call->setDoesNotThrow();
Michael Gottesmanba648592013-03-28 23:08:44 +00002437 Call->setTailCall();
Michael Gottesman60f6b282013-03-29 05:13:07 +00002438
Michael Gottesmandf110ac2013-04-21 00:30:50 +00002439 DEBUG(dbgs() << "Inserting new Retain: " << *Call << "\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00002440 "At insertion point: " << *InsertPt << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002441 }
2442 for (SmallPtrSet<Instruction *, 2>::const_iterator
2443 PI = RetainsToMove.ReverseInsertPts.begin(),
2444 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00002445 Instruction *InsertPt = *PI;
2446 Value *MyArg = ArgTy == ParamTy ? Arg :
2447 new BitCastInst(Arg, ParamTy, "", InsertPt);
2448 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
2449 "", InsertPt);
2450 // Attach a clang.imprecise_release metadata tag, if appropriate.
2451 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
2452 Call->setMetadata(ImpreciseReleaseMDKind, M);
2453 Call->setDoesNotThrow();
2454 if (ReleasesToMove.IsTailCallRelease)
2455 Call->setTailCall();
Michael Gottesmanc189a392013-01-09 19:23:24 +00002456
Michael Gottesman89279f82013-04-05 18:10:41 +00002457 DEBUG(dbgs() << "Inserting new Release: " << *Call << "\n"
2458 "At insertion point: " << *InsertPt << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002459 }
2460
2461 // Delete the original retain and release calls.
2462 for (SmallPtrSet<Instruction *, 2>::const_iterator
2463 AI = RetainsToMove.Calls.begin(),
2464 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
2465 Instruction *OrigRetain = *AI;
2466 Retains.blot(OrigRetain);
2467 DeadInsts.push_back(OrigRetain);
Michael Gottesman89279f82013-04-05 18:10:41 +00002468 DEBUG(dbgs() << "Deleting retain: " << *OrigRetain << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002469 }
2470 for (SmallPtrSet<Instruction *, 2>::const_iterator
2471 AI = ReleasesToMove.Calls.begin(),
2472 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
2473 Instruction *OrigRelease = *AI;
2474 Releases.erase(OrigRelease);
2475 DeadInsts.push_back(OrigRelease);
Michael Gottesman89279f82013-04-05 18:10:41 +00002476 DEBUG(dbgs() << "Deleting release: " << *OrigRelease << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002477 }
Michael Gottesman79249972013-04-05 23:46:45 +00002478
John McCalld935e9c2011-06-15 23:37:01 +00002479}
2480
Michael Gottesman9de6f962013-01-22 21:49:00 +00002481bool
2482ObjCARCOpt::ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState>
2483 &BBStates,
2484 MapVector<Value *, RRInfo> &Retains,
2485 DenseMap<Value *, RRInfo> &Releases,
2486 Module *M,
2487 SmallVector<Instruction *, 4> &NewRetains,
2488 SmallVector<Instruction *, 4> &NewReleases,
2489 SmallVector<Instruction *, 8> &DeadInsts,
2490 RRInfo &RetainsToMove,
2491 RRInfo &ReleasesToMove,
2492 Value *Arg,
2493 bool KnownSafe,
2494 bool &AnyPairsCompletelyEliminated) {
2495 // If a pair happens in a region where it is known that the reference count
Michael Gottesmana76143ee2013-05-13 23:49:42 +00002496 // is already incremented, we can similarly ignore possible decrements unless
2497 // we are dealing with a retainable object with multiple provenance sources.
Michael Gottesman9de6f962013-01-22 21:49:00 +00002498 bool KnownSafeTD = true, KnownSafeBU = true;
Michael Gottesmana76143ee2013-05-13 23:49:42 +00002499 bool MultipleOwners = false;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002500
2501 // Connect the dots between the top-down-collected RetainsToMove and
2502 // bottom-up-collected ReleasesToMove to form sets of related calls.
2503 // This is an iterative process so that we connect multiple releases
2504 // to multiple retains if needed.
2505 unsigned OldDelta = 0;
2506 unsigned NewDelta = 0;
2507 unsigned OldCount = 0;
2508 unsigned NewCount = 0;
2509 bool FirstRelease = true;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002510 for (;;) {
2511 for (SmallVectorImpl<Instruction *>::const_iterator
2512 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
2513 Instruction *NewRetain = *NI;
2514 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
2515 assert(It != Retains.end());
2516 const RRInfo &NewRetainRRI = It->second;
2517 KnownSafeTD &= NewRetainRRI.KnownSafe;
Michael Gottesmana76143ee2013-05-13 23:49:42 +00002518 MultipleOwners |= NewRetainRRI.MultipleOwners;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002519 for (SmallPtrSet<Instruction *, 2>::const_iterator
2520 LI = NewRetainRRI.Calls.begin(),
2521 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
2522 Instruction *NewRetainRelease = *LI;
2523 DenseMap<Value *, RRInfo>::const_iterator Jt =
2524 Releases.find(NewRetainRelease);
2525 if (Jt == Releases.end())
2526 return false;
2527 const RRInfo &NewRetainReleaseRRI = Jt->second;
2528 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
2529 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
2530 OldDelta -=
2531 BBStates[NewRetainRelease->getParent()].GetAllPathCount();
2532
2533 // Merge the ReleaseMetadata and IsTailCallRelease values.
2534 if (FirstRelease) {
2535 ReleasesToMove.ReleaseMetadata =
2536 NewRetainReleaseRRI.ReleaseMetadata;
2537 ReleasesToMove.IsTailCallRelease =
2538 NewRetainReleaseRRI.IsTailCallRelease;
2539 FirstRelease = false;
2540 } else {
2541 if (ReleasesToMove.ReleaseMetadata !=
2542 NewRetainReleaseRRI.ReleaseMetadata)
2543 ReleasesToMove.ReleaseMetadata = 0;
2544 if (ReleasesToMove.IsTailCallRelease !=
2545 NewRetainReleaseRRI.IsTailCallRelease)
2546 ReleasesToMove.IsTailCallRelease = false;
2547 }
2548
2549 // Collect the optimal insertion points.
2550 if (!KnownSafe)
2551 for (SmallPtrSet<Instruction *, 2>::const_iterator
2552 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
2553 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
2554 RI != RE; ++RI) {
2555 Instruction *RIP = *RI;
2556 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
2557 NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
2558 }
2559 NewReleases.push_back(NewRetainRelease);
2560 }
2561 }
2562 }
2563 NewRetains.clear();
2564 if (NewReleases.empty()) break;
2565
2566 // Back the other way.
2567 for (SmallVectorImpl<Instruction *>::const_iterator
2568 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
2569 Instruction *NewRelease = *NI;
2570 DenseMap<Value *, RRInfo>::const_iterator It =
2571 Releases.find(NewRelease);
2572 assert(It != Releases.end());
2573 const RRInfo &NewReleaseRRI = It->second;
2574 KnownSafeBU &= NewReleaseRRI.KnownSafe;
2575 for (SmallPtrSet<Instruction *, 2>::const_iterator
2576 LI = NewReleaseRRI.Calls.begin(),
2577 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
2578 Instruction *NewReleaseRetain = *LI;
2579 MapVector<Value *, RRInfo>::const_iterator Jt =
2580 Retains.find(NewReleaseRetain);
2581 if (Jt == Retains.end())
2582 return false;
2583 const RRInfo &NewReleaseRetainRRI = Jt->second;
2584 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
2585 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
2586 unsigned PathCount =
2587 BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
2588 OldDelta += PathCount;
2589 OldCount += PathCount;
2590
Michael Gottesman9de6f962013-01-22 21:49:00 +00002591 // Collect the optimal insertion points.
2592 if (!KnownSafe)
2593 for (SmallPtrSet<Instruction *, 2>::const_iterator
2594 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
2595 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
2596 RI != RE; ++RI) {
2597 Instruction *RIP = *RI;
2598 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
2599 PathCount = BBStates[RIP->getParent()].GetAllPathCount();
2600 NewDelta += PathCount;
2601 NewCount += PathCount;
2602 }
2603 }
2604 NewRetains.push_back(NewReleaseRetain);
2605 }
2606 }
2607 }
2608 NewReleases.clear();
2609 if (NewRetains.empty()) break;
2610 }
2611
Michael Gottesmana76143ee2013-05-13 23:49:42 +00002612 // If the pointer is known incremented in 1 direction and we do not have
2613 // MultipleOwners, we can safely remove the retain/releases. Otherwise we need
2614 // to be known safe in both directions.
2615 bool UnconditionallySafe = (KnownSafeTD && KnownSafeBU) ||
2616 ((KnownSafeTD || KnownSafeBU) && !MultipleOwners);
2617 if (UnconditionallySafe) {
Michael Gottesman9de6f962013-01-22 21:49:00 +00002618 RetainsToMove.ReverseInsertPts.clear();
2619 ReleasesToMove.ReverseInsertPts.clear();
2620 NewCount = 0;
2621 } else {
2622 // Determine whether the new insertion points we computed preserve the
2623 // balance of retain and release calls through the program.
2624 // TODO: If the fully aggressive solution isn't valid, try to find a
2625 // less aggressive solution which is.
2626 if (NewDelta != 0)
2627 return false;
2628 }
2629
2630 // Determine whether the original call points are balanced in the retain and
2631 // release calls through the program. If not, conservatively don't touch
2632 // them.
2633 // TODO: It's theoretically possible to do code motion in this case, as
2634 // long as the existing imbalances are maintained.
2635 if (OldDelta != 0)
2636 return false;
Michael Gottesman8005ad32013-04-29 06:16:55 +00002637
Michael Gottesmana87bb8f2013-04-29 05:13:13 +00002638#ifdef ARC_ANNOTATIONS
2639 // Do not move calls if ARC annotations are requested.
Michael Gottesman3e3977c2013-04-29 05:25:39 +00002640 if (EnableARCAnnotations)
2641 return false;
Michael Gottesmana87bb8f2013-04-29 05:13:13 +00002642#endif // ARC_ANNOTATIONS
Michael Gottesman9de6f962013-01-22 21:49:00 +00002643
2644 Changed = true;
2645 assert(OldCount != 0 && "Unreachable code?");
2646 NumRRs += OldCount - NewCount;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002647 // Set to true if we completely removed any RR pairs.
Michael Gottesman8b5515f2013-01-22 21:53:43 +00002648 AnyPairsCompletelyEliminated = NewCount == 0;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002649
2650 // We can move calls!
2651 return true;
2652}
2653
Michael Gottesman97e3df02013-01-14 00:35:14 +00002654/// Identify pairings between the retains and releases, and delete and/or move
2655/// them.
John McCalld935e9c2011-06-15 23:37:01 +00002656bool
2657ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
2658 &BBStates,
2659 MapVector<Value *, RRInfo> &Retains,
Dan Gohman6320f522011-07-22 22:29:21 +00002660 DenseMap<Value *, RRInfo> &Releases,
2661 Module *M) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002662 DEBUG(dbgs() << "\n== ObjCARCOpt::PerformCodePlacement ==\n");
2663
John McCalld935e9c2011-06-15 23:37:01 +00002664 bool AnyPairsCompletelyEliminated = false;
2665 RRInfo RetainsToMove;
2666 RRInfo ReleasesToMove;
2667 SmallVector<Instruction *, 4> NewRetains;
2668 SmallVector<Instruction *, 4> NewReleases;
2669 SmallVector<Instruction *, 8> DeadInsts;
2670
Dan Gohman670f9372012-04-13 18:57:48 +00002671 // Visit each retain.
John McCalld935e9c2011-06-15 23:37:01 +00002672 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
Dan Gohman2053a5d2011-09-29 22:25:23 +00002673 E = Retains.end(); I != E; ++I) {
2674 Value *V = I->first;
John McCalld935e9c2011-06-15 23:37:01 +00002675 if (!V) continue; // blotted
2676
2677 Instruction *Retain = cast<Instruction>(V);
Michael Gottesmanc189a392013-01-09 19:23:24 +00002678
Michael Gottesman89279f82013-04-05 18:10:41 +00002679 DEBUG(dbgs() << "Visiting: " << *Retain << "\n");
Michael Gottesmanc189a392013-01-09 19:23:24 +00002680
John McCalld935e9c2011-06-15 23:37:01 +00002681 Value *Arg = GetObjCArg(Retain);
2682
Dan Gohman728db492012-01-13 00:39:07 +00002683 // If the object being released is in static or stack storage, we know it's
John McCalld935e9c2011-06-15 23:37:01 +00002684 // not being managed by ObjC reference counting, so we can delete pairs
2685 // regardless of what possible decrements or uses lie between them.
Dan Gohman728db492012-01-13 00:39:07 +00002686 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
Dan Gohman41375a32012-05-08 23:39:44 +00002687
Dan Gohman56e1cef2011-08-22 17:29:11 +00002688 // A constant pointer can't be pointing to an object on the heap. It may
2689 // be reference-counted, but it won't be deleted.
2690 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
2691 if (const GlobalVariable *GV =
2692 dyn_cast<GlobalVariable>(
2693 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
2694 if (GV->isConstant())
2695 KnownSafe = true;
2696
John McCalld935e9c2011-06-15 23:37:01 +00002697 // Connect the dots between the top-down-collected RetainsToMove and
2698 // bottom-up-collected ReleasesToMove to form sets of related calls.
John McCalld935e9c2011-06-15 23:37:01 +00002699 NewRetains.push_back(Retain);
Michael Gottesman9de6f962013-01-22 21:49:00 +00002700 bool PerformMoveCalls =
2701 ConnectTDBUTraversals(BBStates, Retains, Releases, M, NewRetains,
2702 NewReleases, DeadInsts, RetainsToMove,
2703 ReleasesToMove, Arg, KnownSafe,
2704 AnyPairsCompletelyEliminated);
John McCalld935e9c2011-06-15 23:37:01 +00002705
Michael Gottesman9de6f962013-01-22 21:49:00 +00002706 if (PerformMoveCalls) {
2707 // Ok, everything checks out and we're all set. Let's move/delete some
2708 // code!
2709 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
2710 Retains, Releases, DeadInsts, M);
John McCalld935e9c2011-06-15 23:37:01 +00002711 }
2712
Michael Gottesman9de6f962013-01-22 21:49:00 +00002713 // Clean up state for next retain.
John McCalld935e9c2011-06-15 23:37:01 +00002714 NewReleases.clear();
2715 NewRetains.clear();
2716 RetainsToMove.clear();
2717 ReleasesToMove.clear();
2718 }
2719
2720 // Now that we're done moving everything, we can delete the newly dead
2721 // instructions, as we no longer need them as insert points.
2722 while (!DeadInsts.empty())
2723 EraseInstruction(DeadInsts.pop_back_val());
2724
2725 return AnyPairsCompletelyEliminated;
2726}
2727
Michael Gottesman97e3df02013-01-14 00:35:14 +00002728/// Weak pointer optimizations.
John McCalld935e9c2011-06-15 23:37:01 +00002729void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002730 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeWeakCalls ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00002731
John McCalld935e9c2011-06-15 23:37:01 +00002732 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
2733 // itself because it uses AliasAnalysis and we need to do provenance
2734 // queries instead.
2735 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2736 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +00002737
Michael Gottesman89279f82013-04-05 18:10:41 +00002738 DEBUG(dbgs() << "Visiting: " << *Inst << "\n");
Michael Gottesman3f146e22013-01-01 16:05:48 +00002739
John McCalld935e9c2011-06-15 23:37:01 +00002740 InstructionClass Class = GetBasicInstructionClass(Inst);
2741 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
2742 continue;
2743
2744 // Delete objc_loadWeak calls with no users.
2745 if (Class == IC_LoadWeak && Inst->use_empty()) {
2746 Inst->eraseFromParent();
2747 continue;
2748 }
2749
2750 // TODO: For now, just look for an earlier available version of this value
2751 // within the same block. Theoretically, we could do memdep-style non-local
2752 // analysis too, but that would want caching. A better approach would be to
2753 // use the technique that EarlyCSE uses.
2754 inst_iterator Current = llvm::prior(I);
2755 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
2756 for (BasicBlock::iterator B = CurrentBB->begin(),
2757 J = Current.getInstructionIterator();
2758 J != B; --J) {
2759 Instruction *EarlierInst = &*llvm::prior(J);
2760 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
2761 switch (EarlierClass) {
2762 case IC_LoadWeak:
2763 case IC_LoadWeakRetained: {
2764 // If this is loading from the same pointer, replace this load's value
2765 // with that one.
2766 CallInst *Call = cast<CallInst>(Inst);
2767 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2768 Value *Arg = Call->getArgOperand(0);
2769 Value *EarlierArg = EarlierCall->getArgOperand(0);
2770 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2771 case AliasAnalysis::MustAlias:
2772 Changed = true;
2773 // If the load has a builtin retain, insert a plain retain for it.
2774 if (Class == IC_LoadWeakRetained) {
2775 CallInst *CI =
2776 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
2777 "", Call);
2778 CI->setTailCall();
2779 }
2780 // Zap the fully redundant load.
2781 Call->replaceAllUsesWith(EarlierCall);
2782 Call->eraseFromParent();
2783 goto clobbered;
2784 case AliasAnalysis::MayAlias:
2785 case AliasAnalysis::PartialAlias:
2786 goto clobbered;
2787 case AliasAnalysis::NoAlias:
2788 break;
2789 }
2790 break;
2791 }
2792 case IC_StoreWeak:
2793 case IC_InitWeak: {
2794 // If this is storing to the same pointer and has the same size etc.
2795 // replace this load's value with the stored value.
2796 CallInst *Call = cast<CallInst>(Inst);
2797 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2798 Value *Arg = Call->getArgOperand(0);
2799 Value *EarlierArg = EarlierCall->getArgOperand(0);
2800 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2801 case AliasAnalysis::MustAlias:
2802 Changed = true;
2803 // If the load has a builtin retain, insert a plain retain for it.
2804 if (Class == IC_LoadWeakRetained) {
2805 CallInst *CI =
2806 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
2807 "", Call);
2808 CI->setTailCall();
2809 }
2810 // Zap the fully redundant load.
2811 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
2812 Call->eraseFromParent();
2813 goto clobbered;
2814 case AliasAnalysis::MayAlias:
2815 case AliasAnalysis::PartialAlias:
2816 goto clobbered;
2817 case AliasAnalysis::NoAlias:
2818 break;
2819 }
2820 break;
2821 }
2822 case IC_MoveWeak:
2823 case IC_CopyWeak:
2824 // TOOD: Grab the copied value.
2825 goto clobbered;
2826 case IC_AutoreleasepoolPush:
2827 case IC_None:
John McCall20182ac2013-03-22 21:38:36 +00002828 case IC_IntrinsicUser:
John McCalld935e9c2011-06-15 23:37:01 +00002829 case IC_User:
2830 // Weak pointers are only modified through the weak entry points
2831 // (and arbitrary calls, which could call the weak entry points).
2832 break;
2833 default:
2834 // Anything else could modify the weak pointer.
2835 goto clobbered;
2836 }
2837 }
2838 clobbered:;
2839 }
2840
2841 // Then, for each destroyWeak with an alloca operand, check to see if
2842 // the alloca and all its users can be zapped.
2843 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2844 Instruction *Inst = &*I++;
2845 InstructionClass Class = GetBasicInstructionClass(Inst);
2846 if (Class != IC_DestroyWeak)
2847 continue;
2848
2849 CallInst *Call = cast<CallInst>(Inst);
2850 Value *Arg = Call->getArgOperand(0);
2851 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
2852 for (Value::use_iterator UI = Alloca->use_begin(),
2853 UE = Alloca->use_end(); UI != UE; ++UI) {
Dan Gohmandae33492012-04-27 18:56:31 +00002854 const Instruction *UserInst = cast<Instruction>(*UI);
John McCalld935e9c2011-06-15 23:37:01 +00002855 switch (GetBasicInstructionClass(UserInst)) {
2856 case IC_InitWeak:
2857 case IC_StoreWeak:
2858 case IC_DestroyWeak:
2859 continue;
2860 default:
2861 goto done;
2862 }
2863 }
2864 Changed = true;
2865 for (Value::use_iterator UI = Alloca->use_begin(),
2866 UE = Alloca->use_end(); UI != UE; ) {
2867 CallInst *UserInst = cast<CallInst>(*UI++);
Dan Gohman14862c32012-05-18 22:17:29 +00002868 switch (GetBasicInstructionClass(UserInst)) {
2869 case IC_InitWeak:
2870 case IC_StoreWeak:
2871 // These functions return their second argument.
2872 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
2873 break;
2874 case IC_DestroyWeak:
2875 // No return value.
2876 break;
2877 default:
Dan Gohman9c97eea02012-05-21 17:41:28 +00002878 llvm_unreachable("alloca really is used!");
Dan Gohman14862c32012-05-18 22:17:29 +00002879 }
John McCalld935e9c2011-06-15 23:37:01 +00002880 UserInst->eraseFromParent();
2881 }
2882 Alloca->eraseFromParent();
2883 done:;
2884 }
2885 }
2886}
2887
Michael Gottesman97e3df02013-01-14 00:35:14 +00002888/// Identify program paths which execute sequences of retains and releases which
2889/// can be eliminated.
John McCalld935e9c2011-06-15 23:37:01 +00002890bool ObjCARCOpt::OptimizeSequences(Function &F) {
2891 /// Releases, Retains - These are used to store the results of the main flow
2892 /// analysis. These use Value* as the key instead of Instruction* so that the
2893 /// map stays valid when we get around to rewriting code and calls get
2894 /// replaced by arguments.
2895 DenseMap<Value *, RRInfo> Releases;
2896 MapVector<Value *, RRInfo> Retains;
2897
Michael Gottesman97e3df02013-01-14 00:35:14 +00002898 /// This is used during the traversal of the function to track the
John McCalld935e9c2011-06-15 23:37:01 +00002899 /// states for each identified object at each block.
2900 DenseMap<const BasicBlock *, BBState> BBStates;
2901
2902 // Analyze the CFG of the function, and all instructions.
2903 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
2904
2905 // Transform.
Dan Gohman6320f522011-07-22 22:29:21 +00002906 return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) &&
2907 NestingDetected;
John McCalld935e9c2011-06-15 23:37:01 +00002908}
2909
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002910/// Check if there is a dependent call earlier that does not have anything in
2911/// between the Retain and the call that can affect the reference count of their
2912/// shared pointer argument. Note that Retain need not be in BB.
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002913static bool
2914HasSafePathToPredecessorCall(const Value *Arg, Instruction *Retain,
2915 SmallPtrSet<Instruction *, 4> &DepInsts,
2916 SmallPtrSet<const BasicBlock *, 4> &Visited,
2917 ProvenanceAnalysis &PA) {
2918 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
2919 DepInsts, Visited, PA);
2920 if (DepInsts.size() != 1)
2921 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002922
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002923 CallInst *Call =
2924 dyn_cast_or_null<CallInst>(*DepInsts.begin());
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002925
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002926 // Check that the pointer is the return value of the call.
2927 if (!Call || Arg != Call)
2928 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002929
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002930 // Check that the call is a regular call.
2931 InstructionClass Class = GetBasicInstructionClass(Call);
2932 if (Class != IC_CallOrUser && Class != IC_Call)
2933 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002934
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002935 return true;
2936}
2937
Michael Gottesman6908db12013-04-03 23:16:05 +00002938/// Find a dependent retain that precedes the given autorelease for which there
2939/// is nothing in between the two instructions that can affect the ref count of
2940/// Arg.
2941static CallInst *
2942FindPredecessorRetainWithSafePath(const Value *Arg, BasicBlock *BB,
2943 Instruction *Autorelease,
2944 SmallPtrSet<Instruction *, 4> &DepInsts,
2945 SmallPtrSet<const BasicBlock *, 4> &Visited,
2946 ProvenanceAnalysis &PA) {
2947 FindDependencies(CanChangeRetainCount, Arg,
2948 BB, Autorelease, DepInsts, Visited, PA);
2949 if (DepInsts.size() != 1)
2950 return 0;
Michael Gottesman79249972013-04-05 23:46:45 +00002951
Michael Gottesman6908db12013-04-03 23:16:05 +00002952 CallInst *Retain =
2953 dyn_cast_or_null<CallInst>(*DepInsts.begin());
Michael Gottesman79249972013-04-05 23:46:45 +00002954
Michael Gottesman6908db12013-04-03 23:16:05 +00002955 // Check that we found a retain with the same argument.
2956 if (!Retain ||
2957 !IsRetain(GetBasicInstructionClass(Retain)) ||
2958 GetObjCArg(Retain) != Arg) {
2959 return 0;
2960 }
Michael Gottesman79249972013-04-05 23:46:45 +00002961
Michael Gottesman6908db12013-04-03 23:16:05 +00002962 return Retain;
2963}
2964
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002965/// Look for an ``autorelease'' instruction dependent on Arg such that there are
2966/// no instructions dependent on Arg that need a positive ref count in between
2967/// the autorelease and the ret.
2968static CallInst *
2969FindPredecessorAutoreleaseWithSafePath(const Value *Arg, BasicBlock *BB,
2970 ReturnInst *Ret,
2971 SmallPtrSet<Instruction *, 4> &DepInsts,
2972 SmallPtrSet<const BasicBlock *, 4> &V,
2973 ProvenanceAnalysis &PA) {
2974 FindDependencies(NeedsPositiveRetainCount, Arg,
2975 BB, Ret, DepInsts, V, PA);
2976 if (DepInsts.size() != 1)
2977 return 0;
Michael Gottesman79249972013-04-05 23:46:45 +00002978
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002979 CallInst *Autorelease =
2980 dyn_cast_or_null<CallInst>(*DepInsts.begin());
2981 if (!Autorelease)
2982 return 0;
2983 InstructionClass AutoreleaseClass = GetBasicInstructionClass(Autorelease);
2984 if (!IsAutorelease(AutoreleaseClass))
2985 return 0;
2986 if (GetObjCArg(Autorelease) != Arg)
2987 return 0;
Michael Gottesman79249972013-04-05 23:46:45 +00002988
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002989 return Autorelease;
2990}
2991
Michael Gottesman97e3df02013-01-14 00:35:14 +00002992/// Look for this pattern:
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00002993/// \code
John McCalld935e9c2011-06-15 23:37:01 +00002994/// %call = call i8* @something(...)
2995/// %2 = call i8* @objc_retain(i8* %call)
2996/// %3 = call i8* @objc_autorelease(i8* %2)
2997/// ret i8* %3
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00002998/// \endcode
John McCalld935e9c2011-06-15 23:37:01 +00002999/// And delete the retain and autorelease.
John McCalld935e9c2011-06-15 23:37:01 +00003000void ObjCARCOpt::OptimizeReturns(Function &F) {
3001 if (!F.getReturnType()->isPointerTy())
3002 return;
Michael Gottesman79249972013-04-05 23:46:45 +00003003
Michael Gottesman89279f82013-04-05 18:10:41 +00003004 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeReturns ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00003005
John McCalld935e9c2011-06-15 23:37:01 +00003006 SmallPtrSet<Instruction *, 4> DependingInstructions;
3007 SmallPtrSet<const BasicBlock *, 4> Visited;
3008 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3009 BasicBlock *BB = FI;
3010 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
Michael Gottesman3f146e22013-01-01 16:05:48 +00003011
Michael Gottesman89279f82013-04-05 18:10:41 +00003012 DEBUG(dbgs() << "Visiting: " << *Ret << "\n");
Michael Gottesman3f146e22013-01-01 16:05:48 +00003013
Michael Gottesman21a4ed32013-04-03 23:39:14 +00003014 if (!Ret)
3015 continue;
Michael Gottesman79249972013-04-05 23:46:45 +00003016
John McCalld935e9c2011-06-15 23:37:01 +00003017 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
Michael Gottesman79249972013-04-05 23:46:45 +00003018
Michael Gottesmancdb7c152013-04-21 00:25:04 +00003019 // Look for an ``autorelease'' instruction that is a predecessor of Ret and
Michael Gottesman21a4ed32013-04-03 23:39:14 +00003020 // dependent on Arg such that there are no instructions dependent on Arg
3021 // that need a positive ref count in between the autorelease and Ret.
3022 CallInst *Autorelease =
3023 FindPredecessorAutoreleaseWithSafePath(Arg, BB, Ret,
3024 DependingInstructions, Visited,
3025 PA);
John McCalld935e9c2011-06-15 23:37:01 +00003026 DependingInstructions.clear();
3027 Visited.clear();
Michael Gottesmanfb9ece92013-04-21 00:25:01 +00003028
3029 if (!Autorelease)
3030 continue;
3031
3032 CallInst *Retain =
3033 FindPredecessorRetainWithSafePath(Arg, BB, Autorelease,
3034 DependingInstructions, Visited, PA);
3035 DependingInstructions.clear();
3036 Visited.clear();
3037
3038 if (!Retain)
3039 continue;
3040
3041 // Check that there is nothing that can affect the reference count
3042 // between the retain and the call. Note that Retain need not be in BB.
3043 bool HasSafePathToCall = HasSafePathToPredecessorCall(Arg, Retain,
3044 DependingInstructions,
3045 Visited, PA);
3046 DependingInstructions.clear();
3047 Visited.clear();
3048
3049 if (!HasSafePathToCall)
3050 continue;
3051
3052 // If so, we can zap the retain and autorelease.
3053 Changed = true;
3054 ++NumRets;
3055 DEBUG(dbgs() << "Erasing: " << *Retain << "\nErasing: "
3056 << *Autorelease << "\n");
3057 EraseInstruction(Retain);
3058 EraseInstruction(Autorelease);
John McCalld935e9c2011-06-15 23:37:01 +00003059 }
3060}
3061
Michael Gottesman9c118152013-04-29 06:16:57 +00003062#ifndef NDEBUG
3063void
3064ObjCARCOpt::GatherStatistics(Function &F, bool AfterOptimization) {
3065 llvm::Statistic &NumRetains =
3066 AfterOptimization? NumRetainsAfterOpt : NumRetainsBeforeOpt;
3067 llvm::Statistic &NumReleases =
3068 AfterOptimization? NumReleasesAfterOpt : NumReleasesBeforeOpt;
3069
3070 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3071 Instruction *Inst = &*I++;
3072 switch (GetBasicInstructionClass(Inst)) {
3073 default:
3074 break;
3075 case IC_Retain:
3076 ++NumRetains;
3077 break;
3078 case IC_Release:
3079 ++NumReleases;
3080 break;
3081 }
3082 }
3083}
3084#endif
3085
John McCalld935e9c2011-06-15 23:37:01 +00003086bool ObjCARCOpt::doInitialization(Module &M) {
3087 if (!EnableARCOpts)
3088 return false;
3089
Dan Gohman670f9372012-04-13 18:57:48 +00003090 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanceaac7c2011-06-20 23:20:43 +00003091 Run = ModuleHasARC(M);
3092 if (!Run)
3093 return false;
3094
John McCalld935e9c2011-06-15 23:37:01 +00003095 // Identify the imprecise release metadata kind.
3096 ImpreciseReleaseMDKind =
3097 M.getContext().getMDKindID("clang.imprecise_release");
Dan Gohmana7107f92011-10-17 22:53:25 +00003098 CopyOnEscapeMDKind =
3099 M.getContext().getMDKindID("clang.arc.copy_on_escape");
Dan Gohman0155f302012-02-17 18:59:53 +00003100 NoObjCARCExceptionsMDKind =
3101 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
Michael Gottesman81b1d432013-03-26 00:42:04 +00003102#ifdef ARC_ANNOTATIONS
3103 ARCAnnotationBottomUpMDKind =
3104 M.getContext().getMDKindID("llvm.arc.annotation.bottomup");
3105 ARCAnnotationTopDownMDKind =
3106 M.getContext().getMDKindID("llvm.arc.annotation.topdown");
3107 ARCAnnotationProvenanceSourceMDKind =
3108 M.getContext().getMDKindID("llvm.arc.annotation.provenancesource");
3109#endif // ARC_ANNOTATIONS
John McCalld935e9c2011-06-15 23:37:01 +00003110
John McCalld935e9c2011-06-15 23:37:01 +00003111 // Intuitively, objc_retain and others are nocapture, however in practice
3112 // they are not, because they return their argument value. And objc_release
Dan Gohmandae33492012-04-27 18:56:31 +00003113 // calls finalizers which can have arbitrary side effects.
John McCalld935e9c2011-06-15 23:37:01 +00003114
3115 // These are initialized lazily.
John McCalld935e9c2011-06-15 23:37:01 +00003116 AutoreleaseRVCallee = 0;
3117 ReleaseCallee = 0;
3118 RetainCallee = 0;
Dan Gohman6320f522011-07-22 22:29:21 +00003119 RetainBlockCallee = 0;
John McCalld935e9c2011-06-15 23:37:01 +00003120 AutoreleaseCallee = 0;
3121
3122 return false;
3123}
3124
3125bool ObjCARCOpt::runOnFunction(Function &F) {
3126 if (!EnableARCOpts)
3127 return false;
3128
Dan Gohmanceaac7c2011-06-20 23:20:43 +00003129 // If nothing in the Module uses ARC, don't do anything.
3130 if (!Run)
3131 return false;
3132
John McCalld935e9c2011-06-15 23:37:01 +00003133 Changed = false;
3134
Michael Gottesman89279f82013-04-05 18:10:41 +00003135 DEBUG(dbgs() << "<<< ObjCARCOpt: Visiting Function: " << F.getName() << " >>>"
3136 "\n");
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00003137
John McCalld935e9c2011-06-15 23:37:01 +00003138 PA.setAA(&getAnalysis<AliasAnalysis>());
3139
Michael Gottesman9fc50b82013-05-13 18:29:07 +00003140#ifndef NDEBUG
3141 if (AreStatisticsEnabled()) {
3142 GatherStatistics(F, false);
3143 }
3144#endif
3145
John McCalld935e9c2011-06-15 23:37:01 +00003146 // This pass performs several distinct transformations. As a compile-time aid
3147 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3148 // library functions aren't declared.
3149
Michael Gottesmancd5b0272013-04-24 22:18:15 +00003150 // Preliminary optimizations. This also computes UsedInThisFunction.
John McCalld935e9c2011-06-15 23:37:01 +00003151 OptimizeIndividualCalls(F);
3152
3153 // Optimizations for weak pointers.
3154 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3155 (1 << IC_LoadWeakRetained) |
3156 (1 << IC_StoreWeak) |
3157 (1 << IC_InitWeak) |
3158 (1 << IC_CopyWeak) |
3159 (1 << IC_MoveWeak) |
3160 (1 << IC_DestroyWeak)))
3161 OptimizeWeakCalls(F);
3162
3163 // Optimizations for retain+release pairs.
3164 if (UsedInThisFunction & ((1 << IC_Retain) |
3165 (1 << IC_RetainRV) |
3166 (1 << IC_RetainBlock)))
3167 if (UsedInThisFunction & (1 << IC_Release))
3168 // Run OptimizeSequences until it either stops making changes or
3169 // no retain+release pair nesting is detected.
3170 while (OptimizeSequences(F)) {}
3171
3172 // Optimizations if objc_autorelease is used.
Dan Gohman41375a32012-05-08 23:39:44 +00003173 if (UsedInThisFunction & ((1 << IC_Autorelease) |
3174 (1 << IC_AutoreleaseRV)))
John McCalld935e9c2011-06-15 23:37:01 +00003175 OptimizeReturns(F);
3176
Michael Gottesman9c118152013-04-29 06:16:57 +00003177 // Gather statistics after optimization.
3178#ifndef NDEBUG
3179 if (AreStatisticsEnabled()) {
3180 GatherStatistics(F, true);
3181 }
3182#endif
3183
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00003184 DEBUG(dbgs() << "\n");
3185
John McCalld935e9c2011-06-15 23:37:01 +00003186 return Changed;
3187}
3188
3189void ObjCARCOpt::releaseMemory() {
3190 PA.clear();
3191}
3192
Michael Gottesman97e3df02013-01-14 00:35:14 +00003193/// @}
3194///