blob: dd4dd50f0ba597c9b279ff7df7905572cc862a03 [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#include "ObjCARC.h"
Michael Gottesman14acfac2013-07-06 01:39:23 +000028#include "ARCRuntimeEntryPoints.h"
Michael Gottesman278266f2013-01-29 04:20:52 +000029#include "DependencyAnalysis.h"
Michael Gottesman294e7da2013-01-28 05:51:54 +000030#include "ObjCARCAliasAnalysis.h"
Michael Gottesman778138e2013-01-29 03:03:03 +000031#include "ProvenanceAnalysis.h"
John McCalld935e9c2011-06-15 23:37:01 +000032#include "llvm/ADT/DenseMap.h"
Michael Gottesman5a91bbf2013-05-24 20:44:02 +000033#include "llvm/ADT/DenseSet.h"
Michael Gottesmanfa0939f2013-01-28 04:12:07 +000034#include "llvm/ADT/STLExtras.h"
Michael Gottesman778138e2013-01-29 03:03:03 +000035#include "llvm/ADT/SmallPtrSet.h"
Michael Gottesman278266f2013-01-29 04:20:52 +000036#include "llvm/ADT/Statistic.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000037#include "llvm/IR/CFG.h"
Michael Gottesmancd4de0f2013-03-26 00:42:09 +000038#include "llvm/IR/IRBuilder.h"
Michael Gottesman278266f2013-01-29 04:20:52 +000039#include "llvm/IR/LLVMContext.h"
Michael Gottesman13a5f1a2013-01-29 04:51:59 +000040#include "llvm/Support/Debug.h"
Timur Iskhodzhanov5d7ff002013-01-29 09:09:27 +000041#include "llvm/Support/raw_ostream.h"
Michael Gottesmanfa0939f2013-01-28 04:12:07 +000042
John McCalld935e9c2011-06-15 23:37:01 +000043using namespace llvm;
Michael Gottesman08904e32013-01-28 03:28:38 +000044using namespace llvm::objcarc;
John McCalld935e9c2011-06-15 23:37:01 +000045
Chandler Carruth964daaa2014-04-22 02:55:47 +000046#define DEBUG_TYPE "objc-arc-opts"
47
Michael Gottesman97e3df02013-01-14 00:35:14 +000048/// \defgroup MiscUtils Miscellaneous utilities that are not ARC specific.
49/// @{
John McCalld935e9c2011-06-15 23:37:01 +000050
51namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +000052 /// \brief An associative container with fast insertion-order (deterministic)
53 /// iteration over its elements. Plus the special blot operation.
John McCalld935e9c2011-06-15 23:37:01 +000054 template<class KeyT, class ValueT>
55 class MapVector {
Michael Gottesman97e3df02013-01-14 00:35:14 +000056 /// Map keys to indices in Vector.
John McCalld935e9c2011-06-15 23:37:01 +000057 typedef DenseMap<KeyT, size_t> MapTy;
58 MapTy Map;
59
John McCalld935e9c2011-06-15 23:37:01 +000060 typedef std::vector<std::pair<KeyT, ValueT> > VectorTy;
Michael Gottesman97e3df02013-01-14 00:35:14 +000061 /// Keys and values.
John McCalld935e9c2011-06-15 23:37:01 +000062 VectorTy Vector;
63
64 public:
65 typedef typename VectorTy::iterator iterator;
66 typedef typename VectorTy::const_iterator const_iterator;
67 iterator begin() { return Vector.begin(); }
68 iterator end() { return Vector.end(); }
69 const_iterator begin() const { return Vector.begin(); }
70 const_iterator end() const { return Vector.end(); }
71
72#ifdef XDEBUG
73 ~MapVector() {
74 assert(Vector.size() >= Map.size()); // May differ due to blotting.
75 for (typename MapTy::const_iterator I = Map.begin(), E = Map.end();
76 I != E; ++I) {
77 assert(I->second < Vector.size());
78 assert(Vector[I->second].first == I->first);
79 }
80 for (typename VectorTy::const_iterator I = Vector.begin(),
81 E = Vector.end(); I != E; ++I)
82 assert(!I->first ||
83 (Map.count(I->first) &&
84 Map[I->first] == size_t(I - Vector.begin())));
85 }
86#endif
87
Dan Gohman55b06742012-03-02 01:13:53 +000088 ValueT &operator[](const KeyT &Arg) {
John McCalld935e9c2011-06-15 23:37:01 +000089 std::pair<typename MapTy::iterator, bool> Pair =
90 Map.insert(std::make_pair(Arg, size_t(0)));
91 if (Pair.second) {
Dan Gohman55b06742012-03-02 01:13:53 +000092 size_t Num = Vector.size();
93 Pair.first->second = Num;
John McCalld935e9c2011-06-15 23:37:01 +000094 Vector.push_back(std::make_pair(Arg, ValueT()));
Dan Gohman55b06742012-03-02 01:13:53 +000095 return Vector[Num].second;
John McCalld935e9c2011-06-15 23:37:01 +000096 }
97 return Vector[Pair.first->second].second;
98 }
99
100 std::pair<iterator, bool>
101 insert(const std::pair<KeyT, ValueT> &InsertPair) {
102 std::pair<typename MapTy::iterator, bool> Pair =
103 Map.insert(std::make_pair(InsertPair.first, size_t(0)));
104 if (Pair.second) {
Dan Gohman55b06742012-03-02 01:13:53 +0000105 size_t Num = Vector.size();
106 Pair.first->second = Num;
John McCalld935e9c2011-06-15 23:37:01 +0000107 Vector.push_back(InsertPair);
Dan Gohman55b06742012-03-02 01:13:53 +0000108 return std::make_pair(Vector.begin() + Num, true);
John McCalld935e9c2011-06-15 23:37:01 +0000109 }
110 return std::make_pair(Vector.begin() + Pair.first->second, false);
111 }
112
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000113 iterator find(const KeyT &Key) {
114 typename MapTy::iterator It = Map.find(Key);
115 if (It == Map.end()) return Vector.end();
116 return Vector.begin() + It->second;
117 }
118
Dan Gohman55b06742012-03-02 01:13:53 +0000119 const_iterator find(const KeyT &Key) const {
John McCalld935e9c2011-06-15 23:37:01 +0000120 typename MapTy::const_iterator It = Map.find(Key);
121 if (It == Map.end()) return Vector.end();
122 return Vector.begin() + It->second;
123 }
124
Michael Gottesman97e3df02013-01-14 00:35:14 +0000125 /// This is similar to erase, but instead of removing the element from the
126 /// vector, it just zeros out the key in the vector. This leaves iterators
127 /// intact, but clients must be prepared for zeroed-out keys when iterating.
Dan Gohman55b06742012-03-02 01:13:53 +0000128 void blot(const KeyT &Key) {
John McCalld935e9c2011-06-15 23:37:01 +0000129 typename MapTy::iterator It = Map.find(Key);
130 if (It == Map.end()) return;
131 Vector[It->second].first = KeyT();
132 Map.erase(It);
133 }
134
135 void clear() {
136 Map.clear();
137 Vector.clear();
138 }
139 };
140}
141
Michael Gottesman97e3df02013-01-14 00:35:14 +0000142/// @}
143///
144/// \defgroup ARCUtilities Utility declarations/definitions specific to ARC.
145/// @{
John McCalld935e9c2011-06-15 23:37:01 +0000146
Michael Gottesman97e3df02013-01-14 00:35:14 +0000147/// \brief This is similar to StripPointerCastsAndObjCCalls but it stops as soon
148/// as it finds a value with multiple uses.
John McCalld935e9c2011-06-15 23:37:01 +0000149static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
150 if (Arg->hasOneUse()) {
151 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
152 return FindSingleUseIdentifiedObject(BC->getOperand(0));
153 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
154 if (GEP->hasAllZeroIndices())
155 return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
156 if (IsForwarding(GetBasicInstructionClass(Arg)))
157 return FindSingleUseIdentifiedObject(
158 cast<CallInst>(Arg)->getArgOperand(0));
159 if (!IsObjCIdentifiedObject(Arg))
Craig Topperf40110f2014-04-25 05:29:35 +0000160 return nullptr;
John McCalld935e9c2011-06-15 23:37:01 +0000161 return Arg;
162 }
163
Dan Gohman41375a32012-05-08 23:39:44 +0000164 // If we found an identifiable object but it has multiple uses, but they are
165 // trivial uses, we can still consider this to be a single-use value.
John McCalld935e9c2011-06-15 23:37:01 +0000166 if (IsObjCIdentifiedObject(Arg)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000167 for (const User *U : Arg->users())
John McCalld935e9c2011-06-15 23:37:01 +0000168 if (!U->use_empty() || StripPointerCastsAndObjCCalls(U) != Arg)
Craig Topperf40110f2014-04-25 05:29:35 +0000169 return nullptr;
John McCalld935e9c2011-06-15 23:37:01 +0000170
171 return Arg;
172 }
173
Craig Topperf40110f2014-04-25 05:29:35 +0000174 return nullptr;
John McCalld935e9c2011-06-15 23:37:01 +0000175}
176
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000177/// This is a wrapper around getUnderlyingObjCPtr along the lines of
178/// GetUnderlyingObjects except that it returns early when it sees the first
179/// alloca.
180static inline bool AreAnyUnderlyingObjectsAnAlloca(const Value *V) {
181 SmallPtrSet<const Value *, 4> Visited;
182 SmallVector<const Value *, 4> Worklist;
183 Worklist.push_back(V);
184 do {
185 const Value *P = Worklist.pop_back_val();
186 P = GetUnderlyingObjCPtr(P);
Michael Gottesman0c8b5622013-05-14 06:40:10 +0000187
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000188 if (isa<AllocaInst>(P))
189 return true;
Michael Gottesman0c8b5622013-05-14 06:40:10 +0000190
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000191 if (!Visited.insert(P))
192 continue;
Michael Gottesman0c8b5622013-05-14 06:40:10 +0000193
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000194 if (const SelectInst *SI = dyn_cast<const SelectInst>(P)) {
195 Worklist.push_back(SI->getTrueValue());
196 Worklist.push_back(SI->getFalseValue());
197 continue;
198 }
Michael Gottesman0c8b5622013-05-14 06:40:10 +0000199
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000200 if (const PHINode *PN = dyn_cast<const PHINode>(P)) {
201 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
202 Worklist.push_back(PN->getIncomingValue(i));
203 continue;
204 }
205 } while (!Worklist.empty());
206
207 return false;
208}
209
210
Michael Gottesman97e3df02013-01-14 00:35:14 +0000211/// @}
212///
Michael Gottesman97e3df02013-01-14 00:35:14 +0000213/// \defgroup ARCOpt ARC Optimization.
214/// @{
John McCalld935e9c2011-06-15 23:37:01 +0000215
216// TODO: On code like this:
217//
218// objc_retain(%x)
219// stuff_that_cannot_release()
220// objc_autorelease(%x)
221// stuff_that_cannot_release()
222// objc_retain(%x)
223// stuff_that_cannot_release()
224// objc_autorelease(%x)
225//
226// The second retain and autorelease can be deleted.
227
228// TODO: It should be possible to delete
229// objc_autoreleasePoolPush and objc_autoreleasePoolPop
230// pairs if nothing is actually autoreleased between them. Also, autorelease
231// calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
232// after inlining) can be turned into plain release calls.
233
234// TODO: Critical-edge splitting. If the optimial insertion point is
235// a critical edge, the current algorithm has to fail, because it doesn't
236// know how to split edges. It should be possible to make the optimizer
237// think in terms of edges, rather than blocks, and then split critical
238// edges on demand.
239
240// TODO: OptimizeSequences could generalized to be Interprocedural.
241
242// TODO: Recognize that a bunch of other objc runtime calls have
243// non-escaping arguments and non-releasing arguments, and may be
244// non-autoreleasing.
245
246// TODO: Sink autorelease calls as far as possible. Unfortunately we
247// usually can't sink them past other calls, which would be the main
248// case where it would be useful.
249
Dan Gohmanb3894012011-08-19 00:26:36 +0000250// TODO: The pointer returned from objc_loadWeakRetained is retained.
251
252// TODO: Delete release+retain pairs (rare).
Dan Gohmanceaac7c2011-06-20 23:20:43 +0000253
John McCalld935e9c2011-06-15 23:37:01 +0000254STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
255STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
256STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
257STATISTIC(NumRets, "Number of return value forwarding "
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000258 "retain+autoreleases eliminated");
John McCalld935e9c2011-06-15 23:37:01 +0000259STATISTIC(NumRRs, "Number of retain+release paths eliminated");
260STATISTIC(NumPeeps, "Number of calls peephole-optimized");
Matt Beaumont-Gaye55d9492013-05-13 21:10:49 +0000261#ifndef NDEBUG
Michael Gottesman9c118152013-04-29 06:16:57 +0000262STATISTIC(NumRetainsBeforeOpt,
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000263 "Number of retains before optimization");
Michael Gottesman9c118152013-04-29 06:16:57 +0000264STATISTIC(NumReleasesBeforeOpt,
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000265 "Number of releases before optimization");
Michael Gottesman9c118152013-04-29 06:16:57 +0000266STATISTIC(NumRetainsAfterOpt,
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000267 "Number of retains after optimization");
Michael Gottesman9c118152013-04-29 06:16:57 +0000268STATISTIC(NumReleasesAfterOpt,
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000269 "Number of releases after optimization");
Michael Gottesman03cf3c82013-04-29 07:29:08 +0000270#endif
John McCalld935e9c2011-06-15 23:37:01 +0000271
272namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000273 /// \enum Sequence
274 ///
275 /// \brief A sequence of states that a pointer may go through in which an
276 /// objc_retain and objc_release are actually needed.
John McCalld935e9c2011-06-15 23:37:01 +0000277 enum Sequence {
278 S_None,
Michael Gottesman53fd20b2013-01-29 21:07:51 +0000279 S_Retain, ///< objc_retain(x).
280 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement.
281 S_Use, ///< any use of x.
Michael Gottesman386241c2013-01-29 21:39:02 +0000282 S_Stop, ///< like S_Release, but code motion is stopped.
Michael Gottesman53fd20b2013-01-29 21:07:51 +0000283 S_Release, ///< objc_release(x).
Michael Gottesman9bdab2b2013-01-29 21:41:44 +0000284 S_MovableRelease ///< objc_release(x), !clang.imprecise_release.
John McCalld935e9c2011-06-15 23:37:01 +0000285 };
Michael Gottesman53fd20b2013-01-29 21:07:51 +0000286
287 raw_ostream &operator<<(raw_ostream &OS, const Sequence S)
288 LLVM_ATTRIBUTE_UNUSED;
289 raw_ostream &operator<<(raw_ostream &OS, const Sequence S) {
290 switch (S) {
291 case S_None:
292 return OS << "S_None";
293 case S_Retain:
294 return OS << "S_Retain";
295 case S_CanRelease:
296 return OS << "S_CanRelease";
297 case S_Use:
298 return OS << "S_Use";
299 case S_Release:
300 return OS << "S_Release";
301 case S_MovableRelease:
302 return OS << "S_MovableRelease";
303 case S_Stop:
304 return OS << "S_Stop";
305 }
306 llvm_unreachable("Unknown sequence type.");
307 }
John McCalld935e9c2011-06-15 23:37:01 +0000308}
309
310static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
311 // The easy cases.
312 if (A == B)
313 return A;
314 if (A == S_None || B == S_None)
315 return S_None;
316
John McCalld935e9c2011-06-15 23:37:01 +0000317 if (A > B) std::swap(A, B);
318 if (TopDown) {
319 // Choose the side which is further along in the sequence.
Dan Gohman12130272011-08-12 00:26:31 +0000320 if ((A == S_Retain || A == S_CanRelease) &&
321 (B == S_CanRelease || B == S_Use))
John McCalld935e9c2011-06-15 23:37:01 +0000322 return B;
323 } else {
324 // Choose the side which is further along in the sequence.
325 if ((A == S_Use || A == S_CanRelease) &&
Dan Gohman12130272011-08-12 00:26:31 +0000326 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
John McCalld935e9c2011-06-15 23:37:01 +0000327 return A;
328 // If both sides are releases, choose the more conservative one.
329 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
330 return A;
331 if (A == S_Release && B == S_MovableRelease)
332 return A;
333 }
334
335 return S_None;
336}
337
338namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000339 /// \brief Unidirectional information about either a
John McCalld935e9c2011-06-15 23:37:01 +0000340 /// retain-decrement-use-release sequence or release-use-decrement-retain
Bob Wilson798a7702013-04-09 22:15:51 +0000341 /// reverse sequence.
John McCalld935e9c2011-06-15 23:37:01 +0000342 struct RRInfo {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000343 /// After an objc_retain, the reference count of the referenced
Dan Gohmanb3894012011-08-19 00:26:36 +0000344 /// object is known to be positive. Similarly, before an objc_release, the
345 /// reference count of the referenced object is known to be positive. If
346 /// there are retain-release pairs in code regions where the retain count
347 /// is known to be positive, they can be eliminated, regardless of any side
348 /// effects between them.
349 ///
350 /// Also, a retain+release pair nested within another retain+release
351 /// pair all on the known same pointer value can be eliminated, regardless
352 /// of any intervening side effects.
353 ///
354 /// KnownSafe is true when either of these conditions is satisfied.
355 bool KnownSafe;
John McCalld935e9c2011-06-15 23:37:01 +0000356
Michael Gottesman97e3df02013-01-14 00:35:14 +0000357 /// True of the objc_release calls are all marked with the "tail" keyword.
John McCalld935e9c2011-06-15 23:37:01 +0000358 bool IsTailCallRelease;
359
Michael Gottesman97e3df02013-01-14 00:35:14 +0000360 /// If the Calls are objc_release calls and they all have a
361 /// clang.imprecise_release tag, this is the metadata tag.
John McCalld935e9c2011-06-15 23:37:01 +0000362 MDNode *ReleaseMetadata;
363
Michael Gottesman97e3df02013-01-14 00:35:14 +0000364 /// For a top-down sequence, the set of objc_retains or
John McCalld935e9c2011-06-15 23:37:01 +0000365 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
366 SmallPtrSet<Instruction *, 2> Calls;
367
Michael Gottesman97e3df02013-01-14 00:35:14 +0000368 /// The set of optimal insert positions for moving calls in the opposite
369 /// sequence.
John McCalld935e9c2011-06-15 23:37:01 +0000370 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
371
Michael Gottesmane67f40c2013-05-24 20:44:05 +0000372 /// If this is true, we cannot perform code motion but can still remove
373 /// retain/release pairs.
374 bool CFGHazardAfflicted;
375
John McCalld935e9c2011-06-15 23:37:01 +0000376 RRInfo() :
Craig Topperf40110f2014-04-25 05:29:35 +0000377 KnownSafe(false), IsTailCallRelease(false), ReleaseMetadata(nullptr),
Michael Gottesmane67f40c2013-05-24 20:44:05 +0000378 CFGHazardAfflicted(false) {}
John McCalld935e9c2011-06-15 23:37:01 +0000379
380 void clear();
Michael Gottesman79249972013-04-05 23:46:45 +0000381
Michael Gottesman4773a102013-06-21 05:42:08 +0000382 /// Conservatively merge the two RRInfo. Returns true if a partial merge has
Alp Tokercb402912014-01-24 17:20:08 +0000383 /// occurred, false otherwise.
Michael Gottesman4773a102013-06-21 05:42:08 +0000384 bool Merge(const RRInfo &Other);
385
John McCalld935e9c2011-06-15 23:37:01 +0000386 };
387}
388
389void RRInfo::clear() {
Dan Gohmanb3894012011-08-19 00:26:36 +0000390 KnownSafe = false;
John McCalld935e9c2011-06-15 23:37:01 +0000391 IsTailCallRelease = false;
Craig Topperf40110f2014-04-25 05:29:35 +0000392 ReleaseMetadata = nullptr;
John McCalld935e9c2011-06-15 23:37:01 +0000393 Calls.clear();
394 ReverseInsertPts.clear();
Michael Gottesmane67f40c2013-05-24 20:44:05 +0000395 CFGHazardAfflicted = false;
John McCalld935e9c2011-06-15 23:37:01 +0000396}
397
Michael Gottesman4773a102013-06-21 05:42:08 +0000398bool RRInfo::Merge(const RRInfo &Other) {
399 // Conservatively merge the ReleaseMetadata information.
400 if (ReleaseMetadata != Other.ReleaseMetadata)
Craig Topperf40110f2014-04-25 05:29:35 +0000401 ReleaseMetadata = nullptr;
Michael Gottesman4773a102013-06-21 05:42:08 +0000402
403 // Conservatively merge the boolean state.
404 KnownSafe &= Other.KnownSafe;
405 IsTailCallRelease &= Other.IsTailCallRelease;
406 CFGHazardAfflicted |= Other.CFGHazardAfflicted;
407
408 // Merge the call sets.
409 Calls.insert(Other.Calls.begin(), Other.Calls.end());
410
411 // Merge the insert point sets. If there are any differences,
412 // that makes this a partial merge.
413 bool Partial = ReverseInsertPts.size() != Other.ReverseInsertPts.size();
414 for (SmallPtrSet<Instruction *, 2>::const_iterator
415 I = Other.ReverseInsertPts.begin(),
416 E = Other.ReverseInsertPts.end(); I != E; ++I)
417 Partial |= ReverseInsertPts.insert(*I);
418 return Partial;
419}
420
John McCalld935e9c2011-06-15 23:37:01 +0000421namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000422 /// \brief This class summarizes several per-pointer runtime properties which
423 /// are propogated through the flow graph.
John McCalld935e9c2011-06-15 23:37:01 +0000424 class PtrState {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000425 /// True if the reference count is known to be incremented.
Dan Gohman62079b42012-04-25 00:50:46 +0000426 bool KnownPositiveRefCount;
427
Bob Wilson798a7702013-04-09 22:15:51 +0000428 /// True if we've seen an opportunity for partial RR elimination, such as
Michael Gottesman97e3df02013-01-14 00:35:14 +0000429 /// pushing calls into a CFG triangle or into one side of a CFG diamond.
Dan Gohman62079b42012-04-25 00:50:46 +0000430 bool Partial;
John McCalld935e9c2011-06-15 23:37:01 +0000431
Michael Gottesman97e3df02013-01-14 00:35:14 +0000432 /// The current position in the sequence.
Bill Wendling2798f1e2013-12-01 03:36:07 +0000433 unsigned char Seq : 8;
John McCalld935e9c2011-06-15 23:37:01 +0000434
Michael Gottesman97e3df02013-01-14 00:35:14 +0000435 /// Unidirectional information about the current sequence.
John McCalld935e9c2011-06-15 23:37:01 +0000436 RRInfo RRI;
437
Michael Gottesmane3943d02013-06-21 19:44:30 +0000438 public:
Dan Gohmandf476e52012-09-04 23:16:20 +0000439 PtrState() : KnownPositiveRefCount(false), Partial(false),
Dan Gohman41375a32012-05-08 23:39:44 +0000440 Seq(S_None) {}
John McCalld935e9c2011-06-15 23:37:01 +0000441
Michael Gottesman93132252013-06-21 06:59:02 +0000442
443 bool IsKnownSafe() const {
Michael Gottesman01df4502013-07-06 01:41:35 +0000444 return RRI.KnownSafe;
Michael Gottesman93132252013-06-21 06:59:02 +0000445 }
446
447 void SetKnownSafe(const bool NewValue) {
448 RRI.KnownSafe = NewValue;
449 }
450
Michael Gottesmanb82a1792013-06-21 07:00:44 +0000451 bool IsTailCallRelease() const {
452 return RRI.IsTailCallRelease;
453 }
454
455 void SetTailCallRelease(const bool NewValue) {
456 RRI.IsTailCallRelease = NewValue;
457 }
458
Michael Gottesman9799cf72013-06-21 20:52:49 +0000459 bool IsTrackingImpreciseReleases() const {
Craig Topperf40110f2014-04-25 05:29:35 +0000460 return RRI.ReleaseMetadata != nullptr;
Michael Gottesmanf0401182013-06-21 19:12:38 +0000461 }
462
Michael Gottesmanf701d3f2013-06-21 07:03:07 +0000463 const MDNode *GetReleaseMetadata() const {
464 return RRI.ReleaseMetadata;
465 }
466
467 void SetReleaseMetadata(MDNode *NewValue) {
468 RRI.ReleaseMetadata = NewValue;
469 }
470
Michael Gottesman2f294592013-06-21 19:12:36 +0000471 bool IsCFGHazardAfflicted() const {
472 return RRI.CFGHazardAfflicted;
473 }
474
475 void SetCFGHazardAfflicted(const bool NewValue) {
476 RRI.CFGHazardAfflicted = NewValue;
477 }
478
Michael Gottesman415ddd72013-02-05 19:32:18 +0000479 void SetKnownPositiveRefCount() {
Michael Gottesmanf3f9e3b2013-05-14 00:08:09 +0000480 DEBUG(dbgs() << "Setting Known Positive.\n");
Dan Gohman62079b42012-04-25 00:50:46 +0000481 KnownPositiveRefCount = true;
Dan Gohman12130272011-08-12 00:26:31 +0000482 }
483
Michael Gottesman764b1cf2013-03-23 05:46:19 +0000484 void ClearKnownPositiveRefCount() {
Michael Gottesmanf3f9e3b2013-05-14 00:08:09 +0000485 DEBUG(dbgs() << "Clearing Known Positive.\n");
Dan Gohman62079b42012-04-25 00:50:46 +0000486 KnownPositiveRefCount = false;
John McCalld935e9c2011-06-15 23:37:01 +0000487 }
488
Michael Gottesman07beea42013-03-23 05:31:01 +0000489 bool HasKnownPositiveRefCount() const {
Dan Gohman62079b42012-04-25 00:50:46 +0000490 return KnownPositiveRefCount;
John McCalld935e9c2011-06-15 23:37:01 +0000491 }
492
Michael Gottesman415ddd72013-02-05 19:32:18 +0000493 void SetSeq(Sequence NewSeq) {
Michael Gottesman89279f82013-04-05 18:10:41 +0000494 DEBUG(dbgs() << "Old: " << Seq << "; New: " << NewSeq << "\n");
Michael Gottesman79249972013-04-05 23:46:45 +0000495 Seq = NewSeq;
John McCalld935e9c2011-06-15 23:37:01 +0000496 }
497
Michael Gottesman415ddd72013-02-05 19:32:18 +0000498 Sequence GetSeq() const {
Bill Wendling2798f1e2013-12-01 03:36:07 +0000499 return static_cast<Sequence>(Seq);
John McCalld935e9c2011-06-15 23:37:01 +0000500 }
501
Michael Gottesman415ddd72013-02-05 19:32:18 +0000502 void ClearSequenceProgress() {
Dan Gohman62079b42012-04-25 00:50:46 +0000503 ResetSequenceProgress(S_None);
504 }
505
Michael Gottesman415ddd72013-02-05 19:32:18 +0000506 void ResetSequenceProgress(Sequence NewSeq) {
Michael Gottesman01338a42013-04-20 23:36:57 +0000507 DEBUG(dbgs() << "Resetting sequence progress.\n");
Michael Gottesman89279f82013-04-05 18:10:41 +0000508 SetSeq(NewSeq);
Dan Gohman62079b42012-04-25 00:50:46 +0000509 Partial = false;
John McCalld935e9c2011-06-15 23:37:01 +0000510 RRI.clear();
511 }
512
513 void Merge(const PtrState &Other, bool TopDown);
Michael Gottesman4f6ef112013-06-21 19:44:27 +0000514
515 void InsertCall(Instruction *I) {
516 RRI.Calls.insert(I);
517 }
518
519 void InsertReverseInsertPt(Instruction *I) {
520 RRI.ReverseInsertPts.insert(I);
521 }
522
523 void ClearReverseInsertPts() {
524 RRI.ReverseInsertPts.clear();
525 }
526
527 bool HasReverseInsertPts() const {
528 return !RRI.ReverseInsertPts.empty();
529 }
Michael Gottesmane3943d02013-06-21 19:44:30 +0000530
531 const RRInfo &GetRRInfo() const {
532 return RRI;
533 }
John McCalld935e9c2011-06-15 23:37:01 +0000534 };
535}
536
537void
538PtrState::Merge(const PtrState &Other, bool TopDown) {
Bill Wendlingcbcb02c2013-12-01 03:40:42 +0000539 Seq = MergeSeqs(GetSeq(), Other.GetSeq(), TopDown);
Michael Gottesmanb7deb4c2013-06-21 06:54:31 +0000540 KnownPositiveRefCount &= Other.KnownPositiveRefCount;
Michael Gottesman60f6b282013-03-29 05:13:07 +0000541
Dan Gohman1736c142011-10-17 18:48:25 +0000542 // If we're not in a sequence (anymore), drop all associated state.
John McCalld935e9c2011-06-15 23:37:01 +0000543 if (Seq == S_None) {
Dan Gohman62079b42012-04-25 00:50:46 +0000544 Partial = false;
John McCalld935e9c2011-06-15 23:37:01 +0000545 RRI.clear();
Dan Gohman62079b42012-04-25 00:50:46 +0000546 } else if (Partial || Other.Partial) {
Dan Gohman1736c142011-10-17 18:48:25 +0000547 // If we're doing a merge on a path that's previously seen a partial
548 // merge, conservatively drop the sequence, to avoid doing partial
549 // RR elimination. If the branch predicates for the two merge differ,
550 // mixing them is unsafe.
Dan Gohman62079b42012-04-25 00:50:46 +0000551 ClearSequenceProgress();
John McCalld935e9c2011-06-15 23:37:01 +0000552 } else {
Michael Gottesmanb7deb4c2013-06-21 06:54:31 +0000553 // Otherwise merge the other PtrState's RRInfo into our RRInfo. At this
554 // point, we know that currently we are not partial. Stash whether or not
555 // the merge operation caused us to undergo a partial merging of reverse
556 // insertion points.
Michael Gottesman4773a102013-06-21 05:42:08 +0000557 Partial = RRI.Merge(Other.RRI);
John McCalld935e9c2011-06-15 23:37:01 +0000558 }
559}
560
561namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000562 /// \brief Per-BasicBlock state.
John McCalld935e9c2011-06-15 23:37:01 +0000563 class BBState {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000564 /// The number of unique control paths from the entry which can reach this
565 /// block.
John McCalld935e9c2011-06-15 23:37:01 +0000566 unsigned TopDownPathCount;
567
Michael Gottesman97e3df02013-01-14 00:35:14 +0000568 /// The number of unique control paths to exits from this block.
John McCalld935e9c2011-06-15 23:37:01 +0000569 unsigned BottomUpPathCount;
570
Michael Gottesman97e3df02013-01-14 00:35:14 +0000571 /// A type for PerPtrTopDown and PerPtrBottomUp.
John McCalld935e9c2011-06-15 23:37:01 +0000572 typedef MapVector<const Value *, PtrState> MapTy;
573
Michael Gottesman97e3df02013-01-14 00:35:14 +0000574 /// The top-down traversal uses this to record information known about a
575 /// pointer at the bottom of each block.
John McCalld935e9c2011-06-15 23:37:01 +0000576 MapTy PerPtrTopDown;
577
Michael Gottesman97e3df02013-01-14 00:35:14 +0000578 /// The bottom-up traversal uses this to record information known about a
579 /// pointer at the top of each block.
John McCalld935e9c2011-06-15 23:37:01 +0000580 MapTy PerPtrBottomUp;
581
Michael Gottesman97e3df02013-01-14 00:35:14 +0000582 /// Effective predecessors of the current block ignoring ignorable edges and
583 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000584 SmallVector<BasicBlock *, 2> Preds;
Michael Gottesman97e3df02013-01-14 00:35:14 +0000585 /// Effective successors of the current block ignoring ignorable edges and
586 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000587 SmallVector<BasicBlock *, 2> Succs;
588
John McCalld935e9c2011-06-15 23:37:01 +0000589 public:
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000590 static const unsigned OverflowOccurredValue;
591
592 BBState() : TopDownPathCount(0), BottomUpPathCount(0) { }
John McCalld935e9c2011-06-15 23:37:01 +0000593
594 typedef MapTy::iterator ptr_iterator;
595 typedef MapTy::const_iterator ptr_const_iterator;
596
597 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
598 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
599 ptr_const_iterator top_down_ptr_begin() const {
600 return PerPtrTopDown.begin();
601 }
602 ptr_const_iterator top_down_ptr_end() const {
603 return PerPtrTopDown.end();
604 }
605
606 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
607 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
608 ptr_const_iterator bottom_up_ptr_begin() const {
609 return PerPtrBottomUp.begin();
610 }
611 ptr_const_iterator bottom_up_ptr_end() const {
612 return PerPtrBottomUp.end();
613 }
614
Michael Gottesman97e3df02013-01-14 00:35:14 +0000615 /// Mark this block as being an entry block, which has one path from the
616 /// entry by definition.
John McCalld935e9c2011-06-15 23:37:01 +0000617 void SetAsEntry() { TopDownPathCount = 1; }
618
Michael Gottesman97e3df02013-01-14 00:35:14 +0000619 /// Mark this block as being an exit block, which has one path to an exit by
620 /// definition.
John McCalld935e9c2011-06-15 23:37:01 +0000621 void SetAsExit() { BottomUpPathCount = 1; }
622
Michael Gottesman993fbf72013-05-13 19:40:39 +0000623 /// Attempt to find the PtrState object describing the top down state for
624 /// pointer Arg. Return a new initialized PtrState describing the top down
625 /// state for Arg if we do not find one.
John McCalld935e9c2011-06-15 23:37:01 +0000626 PtrState &getPtrTopDownState(const Value *Arg) {
627 return PerPtrTopDown[Arg];
628 }
629
Michael Gottesman993fbf72013-05-13 19:40:39 +0000630 /// Attempt to find the PtrState object describing the bottom up state for
631 /// pointer Arg. Return a new initialized PtrState describing the bottom up
632 /// state for Arg if we do not find one.
John McCalld935e9c2011-06-15 23:37:01 +0000633 PtrState &getPtrBottomUpState(const Value *Arg) {
634 return PerPtrBottomUp[Arg];
635 }
636
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000637 /// Attempt to find the PtrState object describing the bottom up state for
638 /// pointer Arg.
639 ptr_iterator findPtrBottomUpState(const Value *Arg) {
640 return PerPtrBottomUp.find(Arg);
641 }
642
John McCalld935e9c2011-06-15 23:37:01 +0000643 void clearBottomUpPointers() {
Evan Chenge4df6a22011-08-04 18:40:26 +0000644 PerPtrBottomUp.clear();
John McCalld935e9c2011-06-15 23:37:01 +0000645 }
646
647 void clearTopDownPointers() {
648 PerPtrTopDown.clear();
649 }
650
651 void InitFromPred(const BBState &Other);
652 void InitFromSucc(const BBState &Other);
653 void MergePred(const BBState &Other);
654 void MergeSucc(const BBState &Other);
655
Michael Gottesman9e7261c2013-06-07 06:16:49 +0000656 /// Compute the number of possible unique paths from an entry to an exit
Michael Gottesman97e3df02013-01-14 00:35:14 +0000657 /// which pass through this block. This is only valid after both the
658 /// top-down and bottom-up traversals are complete.
Michael Gottesman9e7261c2013-06-07 06:16:49 +0000659 ///
Alp Tokercb402912014-01-24 17:20:08 +0000660 /// Returns true if overflow occurred. Returns false if overflow did not
Michael Gottesman9e7261c2013-06-07 06:16:49 +0000661 /// occur.
662 bool GetAllPathCountWithOverflow(unsigned &PathCount) const {
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000663 if (TopDownPathCount == OverflowOccurredValue ||
664 BottomUpPathCount == OverflowOccurredValue)
665 return true;
Michael Gottesman9e7261c2013-06-07 06:16:49 +0000666 unsigned long long Product =
667 (unsigned long long)TopDownPathCount*BottomUpPathCount;
Alp Tokercb402912014-01-24 17:20:08 +0000668 // Overflow occurred if any of the upper bits of Product are set or if all
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000669 // the lower bits of Product are all set.
670 return (Product >> 32) ||
671 ((PathCount = Product) == OverflowOccurredValue);
John McCalld935e9c2011-06-15 23:37:01 +0000672 }
Dan Gohman12130272011-08-12 00:26:31 +0000673
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000674 // Specialized CFG utilities.
Dan Gohmandae33492012-04-27 18:56:31 +0000675 typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
Michael Gottesman0fecf982013-08-07 23:56:34 +0000676 edge_iterator pred_begin() const { return Preds.begin(); }
677 edge_iterator pred_end() const { return Preds.end(); }
678 edge_iterator succ_begin() const { return Succs.begin(); }
679 edge_iterator succ_end() const { return Succs.end(); }
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000680
681 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
682 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
683
684 bool isExit() const { return Succs.empty(); }
John McCalld935e9c2011-06-15 23:37:01 +0000685 };
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000686
687 const unsigned BBState::OverflowOccurredValue = 0xffffffff;
John McCalld935e9c2011-06-15 23:37:01 +0000688}
689
690void BBState::InitFromPred(const BBState &Other) {
691 PerPtrTopDown = Other.PerPtrTopDown;
692 TopDownPathCount = Other.TopDownPathCount;
693}
694
695void BBState::InitFromSucc(const BBState &Other) {
696 PerPtrBottomUp = Other.PerPtrBottomUp;
697 BottomUpPathCount = Other.BottomUpPathCount;
698}
699
Michael Gottesman97e3df02013-01-14 00:35:14 +0000700/// The top-down traversal uses this to merge information about predecessors to
701/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +0000702void BBState::MergePred(const BBState &Other) {
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000703 if (TopDownPathCount == OverflowOccurredValue)
704 return;
705
John McCalld935e9c2011-06-15 23:37:01 +0000706 // Other.TopDownPathCount can be 0, in which case it is either dead or a
707 // loop backedge. Loop backedges are special.
708 TopDownPathCount += Other.TopDownPathCount;
709
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000710 // In order to be consistent, we clear the top down pointers when by adding
711 // TopDownPathCount becomes OverflowOccurredValue even though "true" overflow
Alp Tokercb402912014-01-24 17:20:08 +0000712 // has not occurred.
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000713 if (TopDownPathCount == OverflowOccurredValue) {
714 clearTopDownPointers();
715 return;
716 }
717
Michael Gottesman4385edf2013-01-14 01:47:53 +0000718 // Check for overflow. If we have overflow, fall back to conservative
719 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +0000720 if (TopDownPathCount < Other.TopDownPathCount) {
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000721 TopDownPathCount = OverflowOccurredValue;
Dan Gohman7c84dad2012-09-12 20:45:17 +0000722 clearTopDownPointers();
723 return;
724 }
725
John McCalld935e9c2011-06-15 23:37:01 +0000726 // For each entry in the other set, if our set has an entry with the same key,
727 // merge the entries. Otherwise, copy the entry and merge it with an empty
728 // entry.
729 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
730 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
731 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
732 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
733 /*TopDown=*/true);
734 }
735
Dan Gohman7e315fc32011-08-11 21:06:32 +0000736 // For each entry in our set, if the other set doesn't have an entry with the
John McCalld935e9c2011-06-15 23:37:01 +0000737 // same key, force it to merge with an empty entry.
738 for (ptr_iterator MI = top_down_ptr_begin(),
739 ME = top_down_ptr_end(); MI != ME; ++MI)
740 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
741 MI->second.Merge(PtrState(), /*TopDown=*/true);
742}
743
Michael Gottesman97e3df02013-01-14 00:35:14 +0000744/// The bottom-up traversal uses this to merge information about successors to
745/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +0000746void BBState::MergeSucc(const BBState &Other) {
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000747 if (BottomUpPathCount == OverflowOccurredValue)
748 return;
749
John McCalld935e9c2011-06-15 23:37:01 +0000750 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
751 // loop backedge. Loop backedges are special.
752 BottomUpPathCount += Other.BottomUpPathCount;
753
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000754 // In order to be consistent, we clear the top down pointers when by adding
755 // BottomUpPathCount becomes OverflowOccurredValue even though "true" overflow
Alp Tokercb402912014-01-24 17:20:08 +0000756 // has not occurred.
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000757 if (BottomUpPathCount == OverflowOccurredValue) {
758 clearBottomUpPointers();
759 return;
760 }
761
Michael Gottesman4385edf2013-01-14 01:47:53 +0000762 // Check for overflow. If we have overflow, fall back to conservative
763 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +0000764 if (BottomUpPathCount < Other.BottomUpPathCount) {
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000765 BottomUpPathCount = OverflowOccurredValue;
Dan Gohman7c84dad2012-09-12 20:45:17 +0000766 clearBottomUpPointers();
767 return;
768 }
769
John McCalld935e9c2011-06-15 23:37:01 +0000770 // For each entry in the other set, if our set has an entry with the
771 // same key, merge the entries. Otherwise, copy the entry and merge
772 // it with an empty entry.
773 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
774 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
775 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
776 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
777 /*TopDown=*/false);
778 }
779
Dan Gohman7e315fc32011-08-11 21:06:32 +0000780 // For each entry in our set, if the other set doesn't have an entry
John McCalld935e9c2011-06-15 23:37:01 +0000781 // with the same key, force it to merge with an empty entry.
782 for (ptr_iterator MI = bottom_up_ptr_begin(),
783 ME = bottom_up_ptr_end(); MI != ME; ++MI)
784 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
785 MI->second.Merge(PtrState(), /*TopDown=*/false);
786}
787
Michael Gottesman81b1d432013-03-26 00:42:04 +0000788// Only enable ARC Annotations if we are building a debug version of
789// libObjCARCOpts.
790#ifndef NDEBUG
791#define ARC_ANNOTATIONS
792#endif
793
794// Define some macros along the lines of DEBUG and some helper functions to make
795// it cleaner to create annotations in the source code and to no-op when not
796// building in debug mode.
797#ifdef ARC_ANNOTATIONS
798
799#include "llvm/Support/CommandLine.h"
800
801/// Enable/disable ARC sequence annotations.
802static cl::opt<bool>
Michael Gottesman6806b512013-04-17 20:48:03 +0000803EnableARCAnnotations("enable-objc-arc-annotations", cl::init(false),
804 cl::desc("Enable emission of arc data flow analysis "
805 "annotations"));
Michael Gottesmanffef24f2013-04-17 20:48:01 +0000806static cl::opt<bool>
Michael Gottesmanadb921a2013-04-17 21:03:53 +0000807DisableCheckForCFGHazards("disable-objc-arc-checkforcfghazards", cl::init(false),
808 cl::desc("Disable check for cfg hazards when "
809 "annotating"));
Michael Gottesman4e88ce62013-04-17 21:59:41 +0000810static cl::opt<std::string>
811ARCAnnotationTargetIdentifier("objc-arc-annotation-target-identifier",
812 cl::init(""),
813 cl::desc("filter out all data flow annotations "
814 "but those that apply to the given "
815 "target llvm identifier."));
Michael Gottesman81b1d432013-03-26 00:42:04 +0000816
817/// This function appends a unique ARCAnnotationProvenanceSourceMDKind id to an
818/// instruction so that we can track backwards when post processing via the llvm
819/// arc annotation processor tool. If the function is an
820static MDString *AppendMDNodeToSourcePtr(unsigned NodeId,
821 Value *Ptr) {
Craig Toppere73658d2014-04-28 04:05:08 +0000822 MDString *Hash = nullptr;
Michael Gottesman81b1d432013-03-26 00:42:04 +0000823
824 // If pointer is a result of an instruction and it does not have a source
825 // MDNode it, attach a new MDNode onto it. If pointer is a result of
826 // an instruction and does have a source MDNode attached to it, return a
827 // reference to said Node. Otherwise just return 0.
828 if (Instruction *Inst = dyn_cast<Instruction>(Ptr)) {
829 MDNode *Node;
830 if (!(Node = Inst->getMetadata(NodeId))) {
831 // We do not have any node. Generate and attatch the hash MDString to the
832 // instruction.
833
834 // We just use an MDString to ensure that this metadata gets written out
835 // of line at the module level and to provide a very simple format
836 // encoding the information herein. Both of these makes it simpler to
837 // parse the annotations by a simple external program.
838 std::string Str;
839 raw_string_ostream os(Str);
840 os << "(" << Inst->getParent()->getParent()->getName() << ",%"
841 << Inst->getName() << ")";
842
843 Hash = MDString::get(Inst->getContext(), os.str());
844 Inst->setMetadata(NodeId, MDNode::get(Inst->getContext(),Hash));
845 } else {
846 // We have a node. Grab its hash and return it.
847 assert(Node->getNumOperands() == 1 &&
848 "An ARCAnnotationProvenanceSourceMDKind can only have 1 operand.");
849 Hash = cast<MDString>(Node->getOperand(0));
850 }
851 } else if (Argument *Arg = dyn_cast<Argument>(Ptr)) {
852 std::string str;
853 raw_string_ostream os(str);
854 os << "(" << Arg->getParent()->getName() << ",%" << Arg->getName()
855 << ")";
856 Hash = MDString::get(Arg->getContext(), os.str());
857 }
858
859 return Hash;
860}
861
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000862static std::string SequenceToString(Sequence A) {
863 std::string str;
864 raw_string_ostream os(str);
865 os << A;
866 return os.str();
867}
868
Michael Gottesman81b1d432013-03-26 00:42:04 +0000869/// Helper function to change a Sequence into a String object using our overload
870/// for raw_ostream so we only have printing code in one location.
871static MDString *SequenceToMDString(LLVMContext &Context,
872 Sequence A) {
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000873 return MDString::get(Context, SequenceToString(A));
Michael Gottesman81b1d432013-03-26 00:42:04 +0000874}
875
876/// A simple function to generate a MDNode which describes the change in state
877/// for Value *Ptr caused by Instruction *Inst.
878static void AppendMDNodeToInstForPtr(unsigned NodeId,
879 Instruction *Inst,
880 Value *Ptr,
881 MDString *PtrSourceMDNodeID,
882 Sequence OldSeq,
883 Sequence NewSeq) {
Craig Toppere73658d2014-04-28 04:05:08 +0000884 MDNode *Node = nullptr;
Michael Gottesman81b1d432013-03-26 00:42:04 +0000885 Value *tmp[3] = {PtrSourceMDNodeID,
886 SequenceToMDString(Inst->getContext(),
887 OldSeq),
888 SequenceToMDString(Inst->getContext(),
889 NewSeq)};
890 Node = MDNode::get(Inst->getContext(),
891 ArrayRef<Value*>(tmp, 3));
892
893 Inst->setMetadata(NodeId, Node);
894}
895
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000896/// Add to the beginning of the basic block llvm.ptr.annotations which show the
897/// state of a pointer at the entrance to a basic block.
898static void GenerateARCBBEntranceAnnotation(const char *Name, BasicBlock *BB,
899 Value *Ptr, Sequence Seq) {
Michael Gottesman4e88ce62013-04-17 21:59:41 +0000900 // If we have a target identifier, make sure that we match it before
901 // continuing.
902 if(!ARCAnnotationTargetIdentifier.empty() &&
903 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
904 return;
Michael Gottesman9e518132013-04-18 04:34:11 +0000905
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000906 Module *M = BB->getParent()->getParent();
907 LLVMContext &C = M->getContext();
908 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
909 Type *I8XX = PointerType::getUnqual(I8X);
910 Type *Params[] = {I8XX, I8XX};
911 FunctionType *FTy = FunctionType::get(Type::getVoidTy(C),
912 ArrayRef<Type*>(Params, 2),
913 /*isVarArg=*/false);
914 Constant *Callee = M->getOrInsertFunction(Name, FTy);
Michael Gottesman60f6b282013-03-29 05:13:07 +0000915
916 IRBuilder<> Builder(BB, BB->getFirstInsertionPt());
917
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000918 Value *PtrName;
919 StringRef Tmp = Ptr->getName();
Craig Toppere73658d2014-04-28 04:05:08 +0000920 if (nullptr == (PtrName = M->getGlobalVariable(Tmp, true))) {
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000921 Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
922 Tmp + "_STR");
923 PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
Michael Gottesman60f6b282013-03-29 05:13:07 +0000924 cast<Constant>(ActualPtrName), Tmp);
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000925 }
926
927 Value *S;
928 std::string SeqStr = SequenceToString(Seq);
Craig Toppere73658d2014-04-28 04:05:08 +0000929 if (nullptr == (S = M->getGlobalVariable(SeqStr, true))) {
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000930 Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
931 SeqStr + "_STR");
932 S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
933 cast<Constant>(ActualPtrName), SeqStr);
934 }
935
936 Builder.CreateCall2(Callee, PtrName, S);
937}
938
939/// Add to the end of the basic block llvm.ptr.annotations which show the state
940/// of the pointer at the bottom of the basic block.
941static void GenerateARCBBTerminatorAnnotation(const char *Name, BasicBlock *BB,
942 Value *Ptr, Sequence Seq) {
Michael Gottesman4e88ce62013-04-17 21:59:41 +0000943 // If we have a target identifier, make sure that we match it before emitting
944 // an annotation.
945 if(!ARCAnnotationTargetIdentifier.empty() &&
946 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
947 return;
Michael Gottesman9e518132013-04-18 04:34:11 +0000948
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000949 Module *M = BB->getParent()->getParent();
950 LLVMContext &C = M->getContext();
951 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
952 Type *I8XX = PointerType::getUnqual(I8X);
953 Type *Params[] = {I8XX, I8XX};
954 FunctionType *FTy = FunctionType::get(Type::getVoidTy(C),
955 ArrayRef<Type*>(Params, 2),
956 /*isVarArg=*/false);
957 Constant *Callee = M->getOrInsertFunction(Name, FTy);
Michael Gottesman60f6b282013-03-29 05:13:07 +0000958
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000959 IRBuilder<> Builder(BB, std::prev(BB->end()));
Michael Gottesman60f6b282013-03-29 05:13:07 +0000960
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000961 Value *PtrName;
962 StringRef Tmp = Ptr->getName();
Craig Toppere73658d2014-04-28 04:05:08 +0000963 if (nullptr == (PtrName = M->getGlobalVariable(Tmp, true))) {
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000964 Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
965 Tmp + "_STR");
966 PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
Michael Gottesman60f6b282013-03-29 05:13:07 +0000967 cast<Constant>(ActualPtrName), Tmp);
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000968 }
969
970 Value *S;
971 std::string SeqStr = SequenceToString(Seq);
Craig Toppere73658d2014-04-28 04:05:08 +0000972 if (nullptr == (S = M->getGlobalVariable(SeqStr, true))) {
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000973 Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
974 SeqStr + "_STR");
975 S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
976 cast<Constant>(ActualPtrName), SeqStr);
977 }
Michael Gottesman60f6b282013-03-29 05:13:07 +0000978 Builder.CreateCall2(Callee, PtrName, S);
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000979}
980
Michael Gottesman81b1d432013-03-26 00:42:04 +0000981/// Adds a source annotation to pointer and a state change annotation to Inst
982/// referencing the source annotation and the old/new state of pointer.
983static void GenerateARCAnnotation(unsigned InstMDId,
984 unsigned PtrMDId,
985 Instruction *Inst,
986 Value *Ptr,
987 Sequence OldSeq,
988 Sequence NewSeq) {
989 if (EnableARCAnnotations) {
Michael Gottesman4e88ce62013-04-17 21:59:41 +0000990 // If we have a target identifier, make sure that we match it before
991 // emitting an annotation.
992 if(!ARCAnnotationTargetIdentifier.empty() &&
993 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
994 return;
Michael Gottesman9e518132013-04-18 04:34:11 +0000995
Michael Gottesman81b1d432013-03-26 00:42:04 +0000996 // First generate the source annotation on our pointer. This will return an
997 // MDString* if Ptr actually comes from an instruction implying we can put
998 // in a source annotation. If AppendMDNodeToSourcePtr returns 0 (i.e. NULL),
999 // then we know that our pointer is from an Argument so we put a reference
1000 // to the argument number.
1001 //
1002 // The point of this is to make it easy for the
1003 // llvm-arc-annotation-processor tool to cross reference where the source
1004 // pointer is in the LLVM IR since the LLVM IR parser does not submit such
1005 // information via debug info for backends to use (since why would anyone
Alp Tokerf907b892013-12-05 05:44:44 +00001006 // need such a thing from LLVM IR besides in non-standard cases
Michael Gottesman81b1d432013-03-26 00:42:04 +00001007 // [i.e. this]).
1008 MDString *SourcePtrMDNode =
1009 AppendMDNodeToSourcePtr(PtrMDId, Ptr);
1010 AppendMDNodeToInstForPtr(InstMDId, Inst, Ptr, SourcePtrMDNode, OldSeq,
1011 NewSeq);
1012 }
1013}
1014
1015// The actual interface for accessing the above functionality is defined via
1016// some simple macros which are defined below. We do this so that the user does
1017// not need to pass in what metadata id is needed resulting in cleaner code and
1018// additionally since it provides an easy way to conditionally no-op all
1019// annotation support in a non-debug build.
1020
1021/// Use this macro to annotate a sequence state change when processing
1022/// instructions bottom up,
1023#define ANNOTATE_BOTTOMUP(inst, ptr, old, new) \
1024 GenerateARCAnnotation(ARCAnnotationBottomUpMDKind, \
1025 ARCAnnotationProvenanceSourceMDKind, (inst), \
1026 const_cast<Value*>(ptr), (old), (new))
1027/// Use this macro to annotate a sequence state change when processing
1028/// instructions top down.
1029#define ANNOTATE_TOPDOWN(inst, ptr, old, new) \
1030 GenerateARCAnnotation(ARCAnnotationTopDownMDKind, \
1031 ARCAnnotationProvenanceSourceMDKind, (inst), \
1032 const_cast<Value*>(ptr), (old), (new))
1033
Michael Gottesman43e7e002013-04-03 22:41:59 +00001034#define ANNOTATE_BB(_states, _bb, _name, _type, _direction) \
1035 do { \
Michael Gottesman89279f82013-04-05 18:10:41 +00001036 if (EnableARCAnnotations) { \
1037 for(BBState::ptr_const_iterator I = (_states)._direction##_ptr_begin(), \
Michael Gottesman43e7e002013-04-03 22:41:59 +00001038 E = (_states)._direction##_ptr_end(); I != E; ++I) { \
Michael Gottesman89279f82013-04-05 18:10:41 +00001039 Value *Ptr = const_cast<Value*>(I->first); \
1040 Sequence Seq = I->second.GetSeq(); \
1041 GenerateARCBB ## _type ## Annotation(_name, (_bb), Ptr, Seq); \
1042 } \
Michael Gottesman43e7e002013-04-03 22:41:59 +00001043 } \
Michael Gottesman89279f82013-04-05 18:10:41 +00001044 } while (0)
Michael Gottesman43e7e002013-04-03 22:41:59 +00001045
Michael Gottesman89279f82013-04-05 18:10:41 +00001046#define ANNOTATE_BOTTOMUP_BBSTART(_states, _basicblock) \
Michael Gottesman43e7e002013-04-03 22:41:59 +00001047 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbstart", \
1048 Entrance, bottom_up)
Michael Gottesman89279f82013-04-05 18:10:41 +00001049#define ANNOTATE_BOTTOMUP_BBEND(_states, _basicblock) \
1050 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbend", \
Michael Gottesman43e7e002013-04-03 22:41:59 +00001051 Terminator, bottom_up)
Michael Gottesman89279f82013-04-05 18:10:41 +00001052#define ANNOTATE_TOPDOWN_BBSTART(_states, _basicblock) \
1053 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbstart", \
Michael Gottesman43e7e002013-04-03 22:41:59 +00001054 Entrance, top_down)
Michael Gottesman89279f82013-04-05 18:10:41 +00001055#define ANNOTATE_TOPDOWN_BBEND(_states, _basicblock) \
1056 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbend", \
Michael Gottesman43e7e002013-04-03 22:41:59 +00001057 Terminator, top_down)
1058
Michael Gottesman81b1d432013-03-26 00:42:04 +00001059#else // !ARC_ANNOTATION
1060// If annotations are off, noop.
1061#define ANNOTATE_BOTTOMUP(inst, ptr, old, new)
1062#define ANNOTATE_TOPDOWN(inst, ptr, old, new)
Michael Gottesman43e7e002013-04-03 22:41:59 +00001063#define ANNOTATE_BOTTOMUP_BBSTART(states, basicblock)
1064#define ANNOTATE_BOTTOMUP_BBEND(states, basicblock)
1065#define ANNOTATE_TOPDOWN_BBSTART(states, basicblock)
1066#define ANNOTATE_TOPDOWN_BBEND(states, basicblock)
Michael Gottesman81b1d432013-03-26 00:42:04 +00001067#endif // !ARC_ANNOTATION
1068
John McCalld935e9c2011-06-15 23:37:01 +00001069namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001070 /// \brief The main ARC optimization pass.
John McCalld935e9c2011-06-15 23:37:01 +00001071 class ObjCARCOpt : public FunctionPass {
1072 bool Changed;
1073 ProvenanceAnalysis PA;
Michael Gottesman14acfac2013-07-06 01:39:23 +00001074 ARCRuntimeEntryPoints EP;
John McCalld935e9c2011-06-15 23:37:01 +00001075
Michael Gottesman5a91bbf2013-05-24 20:44:02 +00001076 // This is used to track if a pointer is stored into an alloca.
1077 DenseSet<const Value *> MultiOwnersSet;
1078
Michael Gottesman97e3df02013-01-14 00:35:14 +00001079 /// A flag indicating whether this optimization pass should run.
Dan Gohmanceaac7c2011-06-20 23:20:43 +00001080 bool Run;
1081
Michael Gottesman97e3df02013-01-14 00:35:14 +00001082 /// Flags which determine whether each of the interesting runtine functions
1083 /// is in fact used in the current function.
John McCalld935e9c2011-06-15 23:37:01 +00001084 unsigned UsedInThisFunction;
1085
Michael Gottesman97e3df02013-01-14 00:35:14 +00001086 /// The Metadata Kind for clang.imprecise_release metadata.
John McCalld935e9c2011-06-15 23:37:01 +00001087 unsigned ImpreciseReleaseMDKind;
1088
Michael Gottesman97e3df02013-01-14 00:35:14 +00001089 /// The Metadata Kind for clang.arc.copy_on_escape metadata.
Dan Gohmana7107f92011-10-17 22:53:25 +00001090 unsigned CopyOnEscapeMDKind;
1091
Michael Gottesman97e3df02013-01-14 00:35:14 +00001092 /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata.
Dan Gohman0155f302012-02-17 18:59:53 +00001093 unsigned NoObjCARCExceptionsMDKind;
1094
Michael Gottesman81b1d432013-03-26 00:42:04 +00001095#ifdef ARC_ANNOTATIONS
1096 /// The Metadata Kind for llvm.arc.annotation.bottomup metadata.
1097 unsigned ARCAnnotationBottomUpMDKind;
1098 /// The Metadata Kind for llvm.arc.annotation.topdown metadata.
1099 unsigned ARCAnnotationTopDownMDKind;
1100 /// The Metadata Kind for llvm.arc.annotation.provenancesource metadata.
1101 unsigned ARCAnnotationProvenanceSourceMDKind;
1102#endif // ARC_ANNOATIONS
1103
John McCalld935e9c2011-06-15 23:37:01 +00001104 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
Michael Gottesman556ff612013-01-12 01:25:19 +00001105 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1106 InstructionClass &Class);
John McCalld935e9c2011-06-15 23:37:01 +00001107 void OptimizeIndividualCalls(Function &F);
1108
1109 void CheckForCFGHazards(const BasicBlock *BB,
1110 DenseMap<const BasicBlock *, BBState> &BBStates,
1111 BBState &MyStates) const;
Dan Gohman817a7c62012-03-22 18:24:56 +00001112 bool VisitInstructionBottomUp(Instruction *Inst,
Dan Gohman5c70fad2012-03-23 17:47:54 +00001113 BasicBlock *BB,
Dan Gohman817a7c62012-03-22 18:24:56 +00001114 MapVector<Value *, RRInfo> &Retains,
1115 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00001116 bool VisitBottomUp(BasicBlock *BB,
1117 DenseMap<const BasicBlock *, BBState> &BBStates,
1118 MapVector<Value *, RRInfo> &Retains);
Dan Gohman817a7c62012-03-22 18:24:56 +00001119 bool VisitInstructionTopDown(Instruction *Inst,
1120 DenseMap<Value *, RRInfo> &Releases,
1121 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00001122 bool VisitTopDown(BasicBlock *BB,
1123 DenseMap<const BasicBlock *, BBState> &BBStates,
1124 DenseMap<Value *, RRInfo> &Releases);
1125 bool Visit(Function &F,
1126 DenseMap<const BasicBlock *, BBState> &BBStates,
1127 MapVector<Value *, RRInfo> &Retains,
1128 DenseMap<Value *, RRInfo> &Releases);
1129
1130 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1131 MapVector<Value *, RRInfo> &Retains,
1132 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman6320f522011-07-22 22:29:21 +00001133 SmallVectorImpl<Instruction *> &DeadInsts,
1134 Module *M);
John McCalld935e9c2011-06-15 23:37:01 +00001135
Michael Gottesman9de6f962013-01-22 21:49:00 +00001136 bool ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState> &BBStates,
1137 MapVector<Value *, RRInfo> &Retains,
1138 DenseMap<Value *, RRInfo> &Releases,
1139 Module *M,
Craig Topperb94011f2013-07-14 04:42:23 +00001140 SmallVectorImpl<Instruction *> &NewRetains,
1141 SmallVectorImpl<Instruction *> &NewReleases,
1142 SmallVectorImpl<Instruction *> &DeadInsts,
Michael Gottesman9de6f962013-01-22 21:49:00 +00001143 RRInfo &RetainsToMove,
1144 RRInfo &ReleasesToMove,
1145 Value *Arg,
1146 bool KnownSafe,
1147 bool &AnyPairsCompletelyEliminated);
1148
John McCalld935e9c2011-06-15 23:37:01 +00001149 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1150 MapVector<Value *, RRInfo> &Retains,
Dan Gohman6320f522011-07-22 22:29:21 +00001151 DenseMap<Value *, RRInfo> &Releases,
1152 Module *M);
John McCalld935e9c2011-06-15 23:37:01 +00001153
1154 void OptimizeWeakCalls(Function &F);
1155
1156 bool OptimizeSequences(Function &F);
1157
1158 void OptimizeReturns(Function &F);
1159
Michael Gottesman9c118152013-04-29 06:16:57 +00001160#ifndef NDEBUG
1161 void GatherStatistics(Function &F, bool AfterOptimization = false);
1162#endif
1163
Craig Topper3e4c6972014-03-05 09:10:37 +00001164 void getAnalysisUsage(AnalysisUsage &AU) const override;
1165 bool doInitialization(Module &M) override;
1166 bool runOnFunction(Function &F) override;
1167 void releaseMemory() override;
John McCalld935e9c2011-06-15 23:37:01 +00001168
1169 public:
1170 static char ID;
1171 ObjCARCOpt() : FunctionPass(ID) {
1172 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1173 }
1174 };
1175}
1176
1177char ObjCARCOpt::ID = 0;
1178INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1179 "objc-arc", "ObjC ARC optimization", false, false)
1180INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1181INITIALIZE_PASS_END(ObjCARCOpt,
1182 "objc-arc", "ObjC ARC optimization", false, false)
1183
1184Pass *llvm::createObjCARCOptPass() {
1185 return new ObjCARCOpt();
1186}
1187
1188void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1189 AU.addRequired<ObjCARCAliasAnalysis>();
1190 AU.addRequired<AliasAnalysis>();
1191 // ARC optimization doesn't currently split critical edges.
1192 AU.setPreservesCFG();
1193}
1194
Michael Gottesman97e3df02013-01-14 00:35:14 +00001195/// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is
1196/// not a return value. Or, if it can be paired with an
1197/// objc_autoreleaseReturnValue, delete the pair and return true.
John McCalld935e9c2011-06-15 23:37:01 +00001198bool
1199ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001200 // Check for the argument being from an immediately preceding call or invoke.
Dan Gohmandae33492012-04-27 18:56:31 +00001201 const Value *Arg = GetObjCArg(RetainRV);
1202 ImmutableCallSite CS(Arg);
1203 if (const Instruction *Call = CS.getInstruction()) {
John McCalld935e9c2011-06-15 23:37:01 +00001204 if (Call->getParent() == RetainRV->getParent()) {
Dan Gohmandae33492012-04-27 18:56:31 +00001205 BasicBlock::const_iterator I = Call;
John McCalld935e9c2011-06-15 23:37:01 +00001206 ++I;
Michael Gottesman65c24812013-03-25 09:27:43 +00001207 while (IsNoopInstruction(I)) ++I;
John McCalld935e9c2011-06-15 23:37:01 +00001208 if (&*I == RetainRV)
1209 return false;
Dan Gohmandae33492012-04-27 18:56:31 +00001210 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001211 BasicBlock *RetainRVParent = RetainRV->getParent();
1212 if (II->getNormalDest() == RetainRVParent) {
Dan Gohmandae33492012-04-27 18:56:31 +00001213 BasicBlock::const_iterator I = RetainRVParent->begin();
Michael Gottesman65c24812013-03-25 09:27:43 +00001214 while (IsNoopInstruction(I)) ++I;
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001215 if (&*I == RetainRV)
1216 return false;
1217 }
John McCalld935e9c2011-06-15 23:37:01 +00001218 }
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001219 }
John McCalld935e9c2011-06-15 23:37:01 +00001220
1221 // Check for being preceded by an objc_autoreleaseReturnValue on the same
1222 // pointer. In this case, we can delete the pair.
1223 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
1224 if (I != Begin) {
Michael Gottesman65c24812013-03-25 09:27:43 +00001225 do --I; while (I != Begin && IsNoopInstruction(I));
John McCalld935e9c2011-06-15 23:37:01 +00001226 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
1227 GetObjCArg(I) == Arg) {
1228 Changed = true;
1229 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00001230
Michael Gottesman89279f82013-04-05 18:10:41 +00001231 DEBUG(dbgs() << "Erasing autoreleaseRV,retainRV pair: " << *I << "\n"
1232 << "Erasing " << *RetainRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001233
John McCalld935e9c2011-06-15 23:37:01 +00001234 EraseInstruction(I);
1235 EraseInstruction(RetainRV);
1236 return true;
1237 }
1238 }
1239
1240 // Turn it to a plain objc_retain.
1241 Changed = true;
1242 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00001243
Michael Gottesman89279f82013-04-05 18:10:41 +00001244 DEBUG(dbgs() << "Transforming objc_retainAutoreleasedReturnValue => "
Michael Gottesmandef07bb2013-01-05 17:55:42 +00001245 "objc_retain since the operand is not a return value.\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00001246 "Old = " << *RetainRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001247
Michael Gottesman14acfac2013-07-06 01:39:23 +00001248 Constant *NewDecl = EP.get(ARCRuntimeEntryPoints::EPT_Retain);
1249 cast<CallInst>(RetainRV)->setCalledFunction(NewDecl);
Michael Gottesmandef07bb2013-01-05 17:55:42 +00001250
Michael Gottesman89279f82013-04-05 18:10:41 +00001251 DEBUG(dbgs() << "New = " << *RetainRV << "\n");
Michael Gottesmandef07bb2013-01-05 17:55:42 +00001252
John McCalld935e9c2011-06-15 23:37:01 +00001253 return false;
1254}
1255
Michael Gottesman97e3df02013-01-14 00:35:14 +00001256/// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not
1257/// used as a return value.
John McCalld935e9c2011-06-15 23:37:01 +00001258void
Michael Gottesman556ff612013-01-12 01:25:19 +00001259ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1260 InstructionClass &Class) {
John McCalld935e9c2011-06-15 23:37:01 +00001261 // Check for a return of the pointer value.
1262 const Value *Ptr = GetObjCArg(AutoreleaseRV);
Dan Gohman10a18d52011-08-12 00:36:31 +00001263 SmallVector<const Value *, 2> Users;
1264 Users.push_back(Ptr);
1265 do {
1266 Ptr = Users.pop_back_val();
Chandler Carruthcdf47882014-03-09 03:16:01 +00001267 for (const User *U : Ptr->users()) {
1268 if (isa<ReturnInst>(U) || GetBasicInstructionClass(U) == IC_RetainRV)
Dan Gohman10a18d52011-08-12 00:36:31 +00001269 return;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001270 if (isa<BitCastInst>(U))
1271 Users.push_back(U);
Dan Gohman10a18d52011-08-12 00:36:31 +00001272 }
1273 } while (!Users.empty());
John McCalld935e9c2011-06-15 23:37:01 +00001274
1275 Changed = true;
1276 ++NumPeeps;
Michael Gottesman1bf69082013-01-06 21:07:11 +00001277
Michael Gottesman89279f82013-04-05 18:10:41 +00001278 DEBUG(dbgs() << "Transforming objc_autoreleaseReturnValue => "
Michael Gottesman1bf69082013-01-06 21:07:11 +00001279 "objc_autorelease since its operand is not used as a return "
1280 "value.\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00001281 "Old = " << *AutoreleaseRV << "\n");
Michael Gottesman1bf69082013-01-06 21:07:11 +00001282
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001283 CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
Michael Gottesman14acfac2013-07-06 01:39:23 +00001284 Constant *NewDecl = EP.get(ARCRuntimeEntryPoints::EPT_Autorelease);
1285 AutoreleaseRVCI->setCalledFunction(NewDecl);
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001286 AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
Michael Gottesman556ff612013-01-12 01:25:19 +00001287 Class = IC_Autorelease;
Michael Gottesman10426b52013-01-07 21:26:07 +00001288
Michael Gottesman89279f82013-04-05 18:10:41 +00001289 DEBUG(dbgs() << "New: " << *AutoreleaseRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001290
John McCalld935e9c2011-06-15 23:37:01 +00001291}
1292
Michael Gottesman97e3df02013-01-14 00:35:14 +00001293/// Visit each call, one at a time, and make simplifications without doing any
1294/// additional analysis.
John McCalld935e9c2011-06-15 23:37:01 +00001295void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001296 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeIndividualCalls ==\n");
John McCalld935e9c2011-06-15 23:37:01 +00001297 // Reset all the flags in preparation for recomputing them.
1298 UsedInThisFunction = 0;
1299
1300 // Visit all objc_* calls in F.
1301 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
1302 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +00001303
John McCalld935e9c2011-06-15 23:37:01 +00001304 InstructionClass Class = GetBasicInstructionClass(Inst);
1305
Michael Gottesman89279f82013-04-05 18:10:41 +00001306 DEBUG(dbgs() << "Visiting: Class: " << Class << "; " << *Inst << "\n");
Michael Gottesman782e3442013-01-17 18:32:34 +00001307
John McCalld935e9c2011-06-15 23:37:01 +00001308 switch (Class) {
1309 default: break;
1310
1311 // Delete no-op casts. These function calls have special semantics, but
1312 // the semantics are entirely implemented via lowering in the front-end,
1313 // so by the time they reach the optimizer, they are just no-op calls
1314 // which return their argument.
1315 //
1316 // There are gray areas here, as the ability to cast reference-counted
1317 // pointers to raw void* and back allows code to break ARC assumptions,
1318 // however these are currently considered to be unimportant.
1319 case IC_NoopCast:
1320 Changed = true;
1321 ++NumNoops;
Michael Gottesman89279f82013-04-05 18:10:41 +00001322 DEBUG(dbgs() << "Erasing no-op cast: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001323 EraseInstruction(Inst);
1324 continue;
1325
1326 // If the pointer-to-weak-pointer is null, it's undefined behavior.
1327 case IC_StoreWeak:
1328 case IC_LoadWeak:
1329 case IC_LoadWeakRetained:
1330 case IC_InitWeak:
1331 case IC_DestroyWeak: {
1332 CallInst *CI = cast<CallInst>(Inst);
Michael Gottesman65c24812013-03-25 09:27:43 +00001333 if (IsNullOrUndef(CI->getArgOperand(0))) {
Dan Gohman670f9372012-04-13 18:57:48 +00001334 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +00001335 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001336 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1337 Constant::getNullValue(Ty),
1338 CI);
Michael Gottesman10426b52013-01-07 21:26:07 +00001339 llvm::Value *NewValue = UndefValue::get(CI->getType());
Michael Gottesman89279f82013-04-05 18:10:41 +00001340 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
1341 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001342 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +00001343 CI->eraseFromParent();
1344 continue;
1345 }
1346 break;
1347 }
1348 case IC_CopyWeak:
1349 case IC_MoveWeak: {
1350 CallInst *CI = cast<CallInst>(Inst);
Michael Gottesman65c24812013-03-25 09:27:43 +00001351 if (IsNullOrUndef(CI->getArgOperand(0)) ||
1352 IsNullOrUndef(CI->getArgOperand(1))) {
Dan Gohman670f9372012-04-13 18:57:48 +00001353 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +00001354 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001355 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1356 Constant::getNullValue(Ty),
1357 CI);
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001358
1359 llvm::Value *NewValue = UndefValue::get(CI->getType());
Michael Gottesman89279f82013-04-05 18:10:41 +00001360 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
1361 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001362
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001363 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +00001364 CI->eraseFromParent();
1365 continue;
1366 }
1367 break;
1368 }
John McCalld935e9c2011-06-15 23:37:01 +00001369 case IC_RetainRV:
1370 if (OptimizeRetainRVCall(F, Inst))
1371 continue;
1372 break;
1373 case IC_AutoreleaseRV:
Michael Gottesman556ff612013-01-12 01:25:19 +00001374 OptimizeAutoreleaseRVCall(F, Inst, Class);
John McCalld935e9c2011-06-15 23:37:01 +00001375 break;
1376 }
1377
Michael Gottesmanb8c88362013-04-03 02:57:24 +00001378 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
John McCalld935e9c2011-06-15 23:37:01 +00001379 if (IsAutorelease(Class) && Inst->use_empty()) {
1380 CallInst *Call = cast<CallInst>(Inst);
1381 const Value *Arg = Call->getArgOperand(0);
1382 Arg = FindSingleUseIdentifiedObject(Arg);
1383 if (Arg) {
1384 Changed = true;
1385 ++NumAutoreleases;
1386
1387 // Create the declaration lazily.
1388 LLVMContext &C = Inst->getContext();
Michael Gottesman01df4502013-07-06 01:41:35 +00001389
Michael Gottesman14acfac2013-07-06 01:39:23 +00001390 Constant *Decl = EP.get(ARCRuntimeEntryPoints::EPT_Release);
1391 CallInst *NewCall = CallInst::Create(Decl, Call->getArgOperand(0), "",
1392 Call);
Dmitri Gribenko3238fb72013-05-05 00:40:33 +00001393 NewCall->setMetadata(ImpreciseReleaseMDKind, MDNode::get(C, None));
Michael Gottesman10426b52013-01-07 21:26:07 +00001394
Michael Gottesman89279f82013-04-05 18:10:41 +00001395 DEBUG(dbgs() << "Replacing autorelease{,RV}(x) with objc_release(x) "
1396 "since x is otherwise unused.\nOld: " << *Call << "\nNew: "
1397 << *NewCall << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001398
John McCalld935e9c2011-06-15 23:37:01 +00001399 EraseInstruction(Call);
1400 Inst = NewCall;
1401 Class = IC_Release;
1402 }
1403 }
1404
1405 // For functions which can never be passed stack arguments, add
1406 // a tail keyword.
1407 if (IsAlwaysTail(Class)) {
1408 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +00001409 DEBUG(dbgs() << "Adding tail keyword to function since it can never be "
1410 "passed stack args: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001411 cast<CallInst>(Inst)->setTailCall();
1412 }
1413
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001414 // Ensure that functions that can never have a "tail" keyword due to the
1415 // semantics of ARC truly do not do so.
1416 if (IsNeverTail(Class)) {
1417 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +00001418 DEBUG(dbgs() << "Removing tail keyword from function: " << *Inst <<
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001419 "\n");
1420 cast<CallInst>(Inst)->setTailCall(false);
1421 }
1422
John McCalld935e9c2011-06-15 23:37:01 +00001423 // Set nounwind as needed.
1424 if (IsNoThrow(Class)) {
1425 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +00001426 DEBUG(dbgs() << "Found no throw class. Setting nounwind on: " << *Inst
1427 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001428 cast<CallInst>(Inst)->setDoesNotThrow();
1429 }
1430
1431 if (!IsNoopOnNull(Class)) {
1432 UsedInThisFunction |= 1 << Class;
1433 continue;
1434 }
1435
1436 const Value *Arg = GetObjCArg(Inst);
1437
1438 // ARC calls with null are no-ops. Delete them.
Michael Gottesman65c24812013-03-25 09:27:43 +00001439 if (IsNullOrUndef(Arg)) {
John McCalld935e9c2011-06-15 23:37:01 +00001440 Changed = true;
1441 ++NumNoops;
Michael Gottesman89279f82013-04-05 18:10:41 +00001442 DEBUG(dbgs() << "ARC calls with null are no-ops. Erasing: " << *Inst
1443 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001444 EraseInstruction(Inst);
1445 continue;
1446 }
1447
1448 // Keep track of which of retain, release, autorelease, and retain_block
1449 // are actually present in this function.
1450 UsedInThisFunction |= 1 << Class;
1451
1452 // If Arg is a PHI, and one or more incoming values to the
1453 // PHI are null, and the call is control-equivalent to the PHI, and there
1454 // are no relevant side effects between the PHI and the call, the call
1455 // could be pushed up to just those paths with non-null incoming values.
1456 // For now, don't bother splitting critical edges for this.
1457 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
1458 Worklist.push_back(std::make_pair(Inst, Arg));
1459 do {
1460 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
1461 Inst = Pair.first;
1462 Arg = Pair.second;
1463
1464 const PHINode *PN = dyn_cast<PHINode>(Arg);
1465 if (!PN) continue;
1466
1467 // Determine if the PHI has any null operands, or any incoming
1468 // critical edges.
1469 bool HasNull = false;
1470 bool HasCriticalEdges = false;
1471 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1472 Value *Incoming =
1473 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
Michael Gottesman65c24812013-03-25 09:27:43 +00001474 if (IsNullOrUndef(Incoming))
John McCalld935e9c2011-06-15 23:37:01 +00001475 HasNull = true;
1476 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
1477 .getNumSuccessors() != 1) {
1478 HasCriticalEdges = true;
1479 break;
1480 }
1481 }
1482 // If we have null operands and no critical edges, optimize.
1483 if (!HasCriticalEdges && HasNull) {
1484 SmallPtrSet<Instruction *, 4> DependingInstructions;
1485 SmallPtrSet<const BasicBlock *, 4> Visited;
1486
1487 // Check that there is nothing that cares about the reference
1488 // count between the call and the phi.
Dan Gohman8478d762012-04-13 00:59:57 +00001489 switch (Class) {
1490 case IC_Retain:
1491 case IC_RetainBlock:
1492 // These can always be moved up.
1493 break;
1494 case IC_Release:
Dan Gohman41375a32012-05-08 23:39:44 +00001495 // These can't be moved across things that care about the retain
1496 // count.
Dan Gohman8478d762012-04-13 00:59:57 +00001497 FindDependencies(NeedsPositiveRetainCount, Arg,
1498 Inst->getParent(), Inst,
1499 DependingInstructions, Visited, PA);
1500 break;
1501 case IC_Autorelease:
1502 // These can't be moved across autorelease pool scope boundaries.
1503 FindDependencies(AutoreleasePoolBoundary, Arg,
1504 Inst->getParent(), Inst,
1505 DependingInstructions, Visited, PA);
1506 break;
1507 case IC_RetainRV:
1508 case IC_AutoreleaseRV:
1509 // Don't move these; the RV optimization depends on the autoreleaseRV
1510 // being tail called, and the retainRV being immediately after a call
1511 // (which might still happen if we get lucky with codegen layout, but
1512 // it's not worth taking the chance).
1513 continue;
1514 default:
1515 llvm_unreachable("Invalid dependence flavor");
1516 }
1517
John McCalld935e9c2011-06-15 23:37:01 +00001518 if (DependingInstructions.size() == 1 &&
1519 *DependingInstructions.begin() == PN) {
1520 Changed = true;
1521 ++NumPartialNoops;
1522 // Clone the call into each predecessor that has a non-null value.
1523 CallInst *CInst = cast<CallInst>(Inst);
Chris Lattner229907c2011-07-18 04:54:35 +00001524 Type *ParamTy = CInst->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001525 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1526 Value *Incoming =
1527 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
Michael Gottesman65c24812013-03-25 09:27:43 +00001528 if (!IsNullOrUndef(Incoming)) {
John McCalld935e9c2011-06-15 23:37:01 +00001529 CallInst *Clone = cast<CallInst>(CInst->clone());
1530 Value *Op = PN->getIncomingValue(i);
1531 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
1532 if (Op->getType() != ParamTy)
1533 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
1534 Clone->setArgOperand(0, Op);
1535 Clone->insertBefore(InsertPos);
Michael Gottesmanc189a392013-01-09 19:23:24 +00001536
Michael Gottesman89279f82013-04-05 18:10:41 +00001537 DEBUG(dbgs() << "Cloning "
Michael Gottesmanc189a392013-01-09 19:23:24 +00001538 << *CInst << "\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00001539 "And inserting clone at " << *InsertPos << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001540 Worklist.push_back(std::make_pair(Clone, Incoming));
1541 }
1542 }
1543 // Erase the original call.
Michael Gottesmanc189a392013-01-09 19:23:24 +00001544 DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001545 EraseInstruction(CInst);
1546 continue;
1547 }
1548 }
1549 } while (!Worklist.empty());
1550 }
1551}
1552
Michael Gottesman323964c2013-04-18 05:39:45 +00001553/// If we have a top down pointer in the S_Use state, make sure that there are
1554/// no CFG hazards by checking the states of various bottom up pointers.
1555static void CheckForUseCFGHazard(const Sequence SuccSSeq,
1556 const bool SuccSRRIKnownSafe,
1557 PtrState &S,
1558 bool &SomeSuccHasSame,
1559 bool &AllSuccsHaveSame,
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001560 bool &NotAllSeqEqualButKnownSafe,
Michael Gottesman323964c2013-04-18 05:39:45 +00001561 bool &ShouldContinue) {
1562 switch (SuccSSeq) {
1563 case S_CanRelease: {
Michael Gottesman93132252013-06-21 06:59:02 +00001564 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe) {
Michael Gottesman323964c2013-04-18 05:39:45 +00001565 S.ClearSequenceProgress();
1566 break;
1567 }
Michael Gottesman2f294592013-06-21 19:12:36 +00001568 S.SetCFGHazardAfflicted(true);
Michael Gottesman323964c2013-04-18 05:39:45 +00001569 ShouldContinue = true;
1570 break;
1571 }
1572 case S_Use:
1573 SomeSuccHasSame = true;
1574 break;
1575 case S_Stop:
1576 case S_Release:
1577 case S_MovableRelease:
Michael Gottesman93132252013-06-21 06:59:02 +00001578 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe)
Michael Gottesman323964c2013-04-18 05:39:45 +00001579 AllSuccsHaveSame = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001580 else
1581 NotAllSeqEqualButKnownSafe = true;
Michael Gottesman323964c2013-04-18 05:39:45 +00001582 break;
1583 case S_Retain:
1584 llvm_unreachable("bottom-up pointer in retain state!");
1585 case S_None:
1586 llvm_unreachable("This should have been handled earlier.");
1587 }
1588}
1589
1590/// If we have a Top Down pointer in the S_CanRelease state, make sure that
1591/// there are no CFG hazards by checking the states of various bottom up
1592/// pointers.
1593static void CheckForCanReleaseCFGHazard(const Sequence SuccSSeq,
1594 const bool SuccSRRIKnownSafe,
1595 PtrState &S,
1596 bool &SomeSuccHasSame,
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001597 bool &AllSuccsHaveSame,
1598 bool &NotAllSeqEqualButKnownSafe) {
Michael Gottesman323964c2013-04-18 05:39:45 +00001599 switch (SuccSSeq) {
1600 case S_CanRelease:
1601 SomeSuccHasSame = true;
1602 break;
1603 case S_Stop:
1604 case S_Release:
1605 case S_MovableRelease:
1606 case S_Use:
Michael Gottesman93132252013-06-21 06:59:02 +00001607 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe)
Michael Gottesman323964c2013-04-18 05:39:45 +00001608 AllSuccsHaveSame = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001609 else
1610 NotAllSeqEqualButKnownSafe = true;
Michael Gottesman323964c2013-04-18 05:39:45 +00001611 break;
1612 case S_Retain:
1613 llvm_unreachable("bottom-up pointer in retain state!");
1614 case S_None:
1615 llvm_unreachable("This should have been handled earlier.");
1616 }
1617}
1618
Michael Gottesman97e3df02013-01-14 00:35:14 +00001619/// Check for critical edges, loop boundaries, irreducible control flow, or
1620/// other CFG structures where moving code across the edge would result in it
1621/// being executed more.
John McCalld935e9c2011-06-15 23:37:01 +00001622void
1623ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
1624 DenseMap<const BasicBlock *, BBState> &BBStates,
1625 BBState &MyStates) const {
1626 // If any top-down local-use or possible-dec has a succ which is earlier in
1627 // the sequence, forget it.
Dan Gohman55b06742012-03-02 01:13:53 +00001628 for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
Michael Gottesman323964c2013-04-18 05:39:45 +00001629 E = MyStates.top_down_ptr_end(); I != E; ++I) {
1630 PtrState &S = I->second;
1631 const Sequence Seq = I->second.GetSeq();
Dan Gohman0155f302012-02-17 18:59:53 +00001632
Michael Gottesman323964c2013-04-18 05:39:45 +00001633 // We only care about S_Retain, S_CanRelease, and S_Use.
1634 if (Seq == S_None)
1635 continue;
Dan Gohman0155f302012-02-17 18:59:53 +00001636
Michael Gottesman323964c2013-04-18 05:39:45 +00001637 // Make sure that if extra top down states are added in the future that this
1638 // code is updated to handle it.
1639 assert((Seq == S_Retain || Seq == S_CanRelease || Seq == S_Use) &&
1640 "Unknown top down sequence state.");
1641
1642 const Value *Arg = I->first;
1643 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
1644 bool SomeSuccHasSame = false;
1645 bool AllSuccsHaveSame = true;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001646 bool NotAllSeqEqualButKnownSafe = false;
Michael Gottesman323964c2013-04-18 05:39:45 +00001647
1648 succ_const_iterator SI(TI), SE(TI, false);
1649
1650 for (; SI != SE; ++SI) {
1651 // If VisitBottomUp has pointer information for this successor, take
1652 // what we know about it.
1653 const DenseMap<const BasicBlock *, BBState>::iterator BBI =
1654 BBStates.find(*SI);
1655 assert(BBI != BBStates.end());
1656 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
1657 const Sequence SuccSSeq = SuccS.GetSeq();
1658
1659 // If bottom up, the pointer is in an S_None state, clear the sequence
1660 // progress since the sequence in the bottom up state finished
1661 // suggesting a mismatch in between retains/releases. This is true for
1662 // all three cases that we are handling here: S_Retain, S_Use, and
1663 // S_CanRelease.
1664 if (SuccSSeq == S_None) {
Dan Gohman12130272011-08-12 00:26:31 +00001665 S.ClearSequenceProgress();
Michael Gottesman323964c2013-04-18 05:39:45 +00001666 continue;
1667 }
1668
1669 // If we have S_Use or S_CanRelease, perform our check for cfg hazard
1670 // checks.
Michael Gottesman93132252013-06-21 06:59:02 +00001671 const bool SuccSRRIKnownSafe = SuccS.IsKnownSafe();
Michael Gottesman323964c2013-04-18 05:39:45 +00001672
1673 // *NOTE* We do not use Seq from above here since we are allowing for
1674 // S.GetSeq() to change while we are visiting basic blocks.
1675 switch(S.GetSeq()) {
1676 case S_Use: {
1677 bool ShouldContinue = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001678 CheckForUseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S, SomeSuccHasSame,
1679 AllSuccsHaveSame, NotAllSeqEqualButKnownSafe,
Michael Gottesman323964c2013-04-18 05:39:45 +00001680 ShouldContinue);
1681 if (ShouldContinue)
1682 continue;
1683 break;
1684 }
1685 case S_CanRelease: {
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001686 CheckForCanReleaseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S,
1687 SomeSuccHasSame, AllSuccsHaveSame,
1688 NotAllSeqEqualButKnownSafe);
Michael Gottesman323964c2013-04-18 05:39:45 +00001689 break;
1690 }
1691 case S_Retain:
1692 case S_None:
1693 case S_Stop:
1694 case S_Release:
1695 case S_MovableRelease:
1696 break;
1697 }
John McCalld935e9c2011-06-15 23:37:01 +00001698 }
Michael Gottesman323964c2013-04-18 05:39:45 +00001699
1700 // If the state at the other end of any of the successor edges
1701 // matches the current state, require all edges to match. This
1702 // guards against loops in the middle of a sequence.
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001703 if (SomeSuccHasSame && !AllSuccsHaveSame) {
Michael Gottesman323964c2013-04-18 05:39:45 +00001704 S.ClearSequenceProgress();
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001705 } else if (NotAllSeqEqualButKnownSafe) {
1706 // If we would have cleared the state foregoing the fact that we are known
1707 // safe, stop code motion. This is because whether or not it is safe to
1708 // remove RR pairs via KnownSafe is an orthogonal concept to whether we
1709 // are allowed to perform code motion.
Michael Gottesman2f294592013-06-21 19:12:36 +00001710 S.SetCFGHazardAfflicted(true);
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001711 }
Michael Gottesman323964c2013-04-18 05:39:45 +00001712 }
John McCalld935e9c2011-06-15 23:37:01 +00001713}
1714
1715bool
Dan Gohman817a7c62012-03-22 18:24:56 +00001716ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
Dan Gohman5c70fad2012-03-23 17:47:54 +00001717 BasicBlock *BB,
Dan Gohman817a7c62012-03-22 18:24:56 +00001718 MapVector<Value *, RRInfo> &Retains,
1719 BBState &MyStates) {
1720 bool NestingDetected = false;
1721 InstructionClass Class = GetInstructionClass(Inst);
Craig Topperf40110f2014-04-25 05:29:35 +00001722 const Value *Arg = nullptr;
Michael Gottesman79249972013-04-05 23:46:45 +00001723
Michael Gottesman1d8d2572013-04-05 22:54:28 +00001724 DEBUG(dbgs() << "Class: " << Class << "\n");
Michael Gottesman79249972013-04-05 23:46:45 +00001725
Dan Gohman817a7c62012-03-22 18:24:56 +00001726 switch (Class) {
1727 case IC_Release: {
1728 Arg = GetObjCArg(Inst);
1729
1730 PtrState &S = MyStates.getPtrBottomUpState(Arg);
1731
1732 // If we see two releases in a row on the same pointer. If so, make
1733 // a note, and we'll cicle back to revisit it after we've
1734 // hopefully eliminated the second release, which may allow us to
1735 // eliminate the first release too.
1736 // Theoretically we could implement removal of nested retain+release
1737 // pairs by making PtrState hold a stack of states, but this is
1738 // simple and avoids adding overhead for the non-nested case.
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001739 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001740 DEBUG(dbgs() << "Found nested releases (i.e. a release pair)\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00001741 NestingDetected = true;
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001742 }
Dan Gohman817a7c62012-03-22 18:24:56 +00001743
Dan Gohman817a7c62012-03-22 18:24:56 +00001744 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001745 Sequence NewSeq = ReleaseMetadata ? S_MovableRelease : S_Release;
1746 ANNOTATE_BOTTOMUP(Inst, Arg, S.GetSeq(), NewSeq);
1747 S.ResetSequenceProgress(NewSeq);
Michael Gottesmanf701d3f2013-06-21 07:03:07 +00001748 S.SetReleaseMetadata(ReleaseMetadata);
Michael Gottesman93132252013-06-21 06:59:02 +00001749 S.SetKnownSafe(S.HasKnownPositiveRefCount());
Michael Gottesmanb82a1792013-06-21 07:00:44 +00001750 S.SetTailCallRelease(cast<CallInst>(Inst)->isTailCall());
Michael Gottesman4f6ef112013-06-21 19:44:27 +00001751 S.InsertCall(Inst);
Dan Gohmandf476e52012-09-04 23:16:20 +00001752 S.SetKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001753 break;
1754 }
1755 case IC_RetainBlock:
Michael Gottesman158fdf62013-03-28 20:11:19 +00001756 // In OptimizeIndividualCalls, we have strength reduced all optimizable
1757 // objc_retainBlocks to objc_retains. Thus at this point any
1758 // objc_retainBlocks that we see are not optimizable.
1759 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001760 case IC_Retain:
1761 case IC_RetainRV: {
1762 Arg = GetObjCArg(Inst);
1763
1764 PtrState &S = MyStates.getPtrBottomUpState(Arg);
Dan Gohman62079b42012-04-25 00:50:46 +00001765 S.SetKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001766
Michael Gottesman81b1d432013-03-26 00:42:04 +00001767 Sequence OldSeq = S.GetSeq();
1768 switch (OldSeq) {
Dan Gohman817a7c62012-03-22 18:24:56 +00001769 case S_Stop:
1770 case S_Release:
1771 case S_MovableRelease:
1772 case S_Use:
Michael Gottesman1d8d2572013-04-05 22:54:28 +00001773 // If OldSeq is not S_Use or OldSeq is S_Use and we are tracking an
1774 // imprecise release, clear our reverse insertion points.
Michael Gottesmanf0401182013-06-21 19:12:38 +00001775 if (OldSeq != S_Use || S.IsTrackingImpreciseReleases())
Michael Gottesman4f6ef112013-06-21 19:44:27 +00001776 S.ClearReverseInsertPts();
Dan Gohman817a7c62012-03-22 18:24:56 +00001777 // FALL THROUGH
1778 case S_CanRelease:
1779 // Don't do retain+release tracking for IC_RetainRV, because it's
1780 // better to let it remain as the first instruction after a call.
Michael Gottesmanba648592013-03-28 23:08:44 +00001781 if (Class != IC_RetainRV)
Michael Gottesmane3943d02013-06-21 19:44:30 +00001782 Retains[Inst] = S.GetRRInfo();
Dan Gohman817a7c62012-03-22 18:24:56 +00001783 S.ClearSequenceProgress();
1784 break;
1785 case S_None:
1786 break;
1787 case S_Retain:
1788 llvm_unreachable("bottom-up pointer in retain state!");
1789 }
Michael Gottesman79249972013-04-05 23:46:45 +00001790 ANNOTATE_BOTTOMUP(Inst, Arg, OldSeq, S.GetSeq());
Michael Gottesman31ba23a2013-04-05 22:54:32 +00001791 // A retain moving bottom up can be a use.
1792 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001793 }
1794 case IC_AutoreleasepoolPop:
1795 // Conservatively, clear MyStates for all known pointers.
1796 MyStates.clearBottomUpPointers();
1797 return NestingDetected;
1798 case IC_AutoreleasepoolPush:
1799 case IC_None:
1800 // These are irrelevant.
1801 return NestingDetected;
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001802 case IC_User:
1803 // If we have a store into an alloca of a pointer we are tracking, the
1804 // pointer has multiple owners implying that we must be more conservative.
1805 //
1806 // This comes up in the context of a pointer being ``KnownSafe''. In the
Alp Tokercb402912014-01-24 17:20:08 +00001807 // presence of a block being initialized, the frontend will emit the
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001808 // objc_retain on the original pointer and the release on the pointer loaded
1809 // from the alloca. The optimizer will through the provenance analysis
1810 // realize that the two are related, but since we only require KnownSafe in
1811 // one direction, will match the inner retain on the original pointer with
1812 // the guard release on the original pointer. This is fixed by ensuring that
Alp Tokercb402912014-01-24 17:20:08 +00001813 // in the presence of allocas we only unconditionally remove pointers if
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001814 // both our retain and our release are KnownSafe.
1815 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1816 if (AreAnyUnderlyingObjectsAnAlloca(SI->getPointerOperand())) {
1817 BBState::ptr_iterator I = MyStates.findPtrBottomUpState(
1818 StripPointerCastsAndObjCCalls(SI->getValueOperand()));
1819 if (I != MyStates.bottom_up_ptr_end())
Michael Gottesman5a91bbf2013-05-24 20:44:02 +00001820 MultiOwnersSet.insert(I->first);
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001821 }
1822 }
1823 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001824 default:
1825 break;
1826 }
1827
1828 // Consider any other possible effects of this instruction on each
1829 // pointer being tracked.
1830 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
1831 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
1832 const Value *Ptr = MI->first;
1833 if (Ptr == Arg)
1834 continue; // Handled above.
1835 PtrState &S = MI->second;
1836 Sequence Seq = S.GetSeq();
1837
1838 // Check for possible releases.
1839 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001840 DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr
1841 << "\n");
Michael Gottesman764b1cf2013-03-23 05:46:19 +00001842 S.ClearKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001843 switch (Seq) {
1844 case S_Use:
1845 S.SetSeq(S_CanRelease);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001846 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S.GetSeq());
Dan Gohman817a7c62012-03-22 18:24:56 +00001847 continue;
1848 case S_CanRelease:
1849 case S_Release:
1850 case S_MovableRelease:
1851 case S_Stop:
1852 case S_None:
1853 break;
1854 case S_Retain:
1855 llvm_unreachable("bottom-up pointer in retain state!");
1856 }
1857 }
1858
1859 // Check for possible direct uses.
1860 switch (Seq) {
1861 case S_Release:
1862 case S_MovableRelease:
1863 if (CanUse(Inst, Ptr, PA, Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001864 DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr
1865 << "\n");
Michael Gottesman4f6ef112013-06-21 19:44:27 +00001866 assert(!S.HasReverseInsertPts());
Dan Gohman5c70fad2012-03-23 17:47:54 +00001867 // If this is an invoke instruction, we're scanning it as part of
1868 // one of its successor blocks, since we can't insert code after it
1869 // in its own block, and we don't want to split critical edges.
1870 if (isa<InvokeInst>(Inst))
Michael Gottesman4f6ef112013-06-21 19:44:27 +00001871 S.InsertReverseInsertPt(BB->getFirstInsertionPt());
Dan Gohman5c70fad2012-03-23 17:47:54 +00001872 else
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001873 S.InsertReverseInsertPt(std::next(BasicBlock::iterator(Inst)));
Dan Gohman817a7c62012-03-22 18:24:56 +00001874 S.SetSeq(S_Use);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001875 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
John McCall20182ac2013-03-22 21:38:36 +00001876 } else if (Seq == S_Release && IsUser(Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001877 DEBUG(dbgs() << "PreciseReleaseUse: Seq: " << Seq << "; " << *Ptr
1878 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00001879 // Non-movable releases depend on any possible objc pointer use.
1880 S.SetSeq(S_Stop);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001881 ANNOTATE_BOTTOMUP(Inst, Ptr, S_Release, S_Stop);
Michael Gottesman4f6ef112013-06-21 19:44:27 +00001882 assert(!S.HasReverseInsertPts());
Dan Gohman5c70fad2012-03-23 17:47:54 +00001883 // As above; handle invoke specially.
1884 if (isa<InvokeInst>(Inst))
Michael Gottesman4f6ef112013-06-21 19:44:27 +00001885 S.InsertReverseInsertPt(BB->getFirstInsertionPt());
Dan Gohman5c70fad2012-03-23 17:47:54 +00001886 else
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001887 S.InsertReverseInsertPt(std::next(BasicBlock::iterator(Inst)));
Dan Gohman817a7c62012-03-22 18:24:56 +00001888 }
1889 break;
1890 case S_Stop:
Michael Gottesman81b1d432013-03-26 00:42:04 +00001891 if (CanUse(Inst, Ptr, PA, Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001892 DEBUG(dbgs() << "PreciseStopUse: Seq: " << Seq << "; " << *Ptr
1893 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00001894 S.SetSeq(S_Use);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001895 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
1896 }
Dan Gohman817a7c62012-03-22 18:24:56 +00001897 break;
1898 case S_CanRelease:
1899 case S_Use:
1900 case S_None:
1901 break;
1902 case S_Retain:
1903 llvm_unreachable("bottom-up pointer in retain state!");
1904 }
1905 }
1906
1907 return NestingDetected;
1908}
1909
1910bool
John McCalld935e9c2011-06-15 23:37:01 +00001911ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
1912 DenseMap<const BasicBlock *, BBState> &BBStates,
1913 MapVector<Value *, RRInfo> &Retains) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001914
1915 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitBottomUp ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00001916
John McCalld935e9c2011-06-15 23:37:01 +00001917 bool NestingDetected = false;
1918 BBState &MyStates = BBStates[BB];
1919
1920 // Merge the states from each successor to compute the initial state
1921 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00001922 BBState::edge_iterator SI(MyStates.succ_begin()),
1923 SE(MyStates.succ_end());
1924 if (SI != SE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001925 const BasicBlock *Succ = *SI;
1926 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
1927 assert(I != BBStates.end());
1928 MyStates.InitFromSucc(I->second);
1929 ++SI;
1930 for (; SI != SE; ++SI) {
1931 Succ = *SI;
1932 I = BBStates.find(Succ);
1933 assert(I != BBStates.end());
1934 MyStates.MergeSucc(I->second);
1935 }
Michael Gottesman60f6b282013-03-29 05:13:07 +00001936 }
Michael Gottesmancd4de0f2013-03-26 00:42:09 +00001937
Michael Gottesman43e7e002013-04-03 22:41:59 +00001938 // If ARC Annotations are enabled, output the current state of pointers at the
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00001939 // bottom of the basic block.
Michael Gottesman43e7e002013-04-03 22:41:59 +00001940 ANNOTATE_BOTTOMUP_BBEND(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00001941
John McCalld935e9c2011-06-15 23:37:01 +00001942 // Visit all the instructions, bottom-up.
1943 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001944 Instruction *Inst = std::prev(I);
Dan Gohman5c70fad2012-03-23 17:47:54 +00001945
1946 // Invoke instructions are visited as part of their successors (below).
1947 if (isa<InvokeInst>(Inst))
1948 continue;
1949
Michael Gottesman89279f82013-04-05 18:10:41 +00001950 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001951
Dan Gohman5c70fad2012-03-23 17:47:54 +00001952 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
1953 }
1954
Dan Gohmandae33492012-04-27 18:56:31 +00001955 // If there's a predecessor with an invoke, visit the invoke as if it were
1956 // part of this block, since we can't insert code after an invoke in its own
1957 // block, and we don't want to split critical edges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001958 for (BBState::edge_iterator PI(MyStates.pred_begin()),
1959 PE(MyStates.pred_end()); PI != PE; ++PI) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00001960 BasicBlock *Pred = *PI;
Dan Gohmandae33492012-04-27 18:56:31 +00001961 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
1962 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
Dan Gohman817a7c62012-03-22 18:24:56 +00001963 }
John McCalld935e9c2011-06-15 23:37:01 +00001964
Michael Gottesman43e7e002013-04-03 22:41:59 +00001965 // If ARC Annotations are enabled, output the current state of pointers at the
1966 // top of the basic block.
1967 ANNOTATE_BOTTOMUP_BBSTART(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00001968
Dan Gohman817a7c62012-03-22 18:24:56 +00001969 return NestingDetected;
1970}
John McCalld935e9c2011-06-15 23:37:01 +00001971
Dan Gohman817a7c62012-03-22 18:24:56 +00001972bool
1973ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
1974 DenseMap<Value *, RRInfo> &Releases,
1975 BBState &MyStates) {
1976 bool NestingDetected = false;
1977 InstructionClass Class = GetInstructionClass(Inst);
Craig Topperf40110f2014-04-25 05:29:35 +00001978 const Value *Arg = nullptr;
John McCalld935e9c2011-06-15 23:37:01 +00001979
Dan Gohman817a7c62012-03-22 18:24:56 +00001980 switch (Class) {
1981 case IC_RetainBlock:
Michael Gottesman158fdf62013-03-28 20:11:19 +00001982 // In OptimizeIndividualCalls, we have strength reduced all optimizable
1983 // objc_retainBlocks to objc_retains. Thus at this point any
1984 // objc_retainBlocks that we see are not optimizable.
1985 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001986 case IC_Retain:
1987 case IC_RetainRV: {
1988 Arg = GetObjCArg(Inst);
1989
1990 PtrState &S = MyStates.getPtrTopDownState(Arg);
1991
1992 // Don't do retain+release tracking for IC_RetainRV, because it's
1993 // better to let it remain as the first instruction after a call.
1994 if (Class != IC_RetainRV) {
1995 // If we see two retains in a row on the same pointer. If so, make
John McCalld935e9c2011-06-15 23:37:01 +00001996 // a note, and we'll cicle back to revisit it after we've
Dan Gohman817a7c62012-03-22 18:24:56 +00001997 // hopefully eliminated the second retain, which may allow us to
1998 // eliminate the first retain too.
John McCalld935e9c2011-06-15 23:37:01 +00001999 // Theoretically we could implement removal of nested retain+release
2000 // pairs by making PtrState hold a stack of states, but this is
2001 // simple and avoids adding overhead for the non-nested case.
Dan Gohman817a7c62012-03-22 18:24:56 +00002002 if (S.GetSeq() == S_Retain)
John McCalld935e9c2011-06-15 23:37:01 +00002003 NestingDetected = true;
2004
Michael Gottesman81b1d432013-03-26 00:42:04 +00002005 ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_Retain);
Dan Gohman62079b42012-04-25 00:50:46 +00002006 S.ResetSequenceProgress(S_Retain);
Michael Gottesman93132252013-06-21 06:59:02 +00002007 S.SetKnownSafe(S.HasKnownPositiveRefCount());
Michael Gottesman4f6ef112013-06-21 19:44:27 +00002008 S.InsertCall(Inst);
John McCalld935e9c2011-06-15 23:37:01 +00002009 }
John McCalld935e9c2011-06-15 23:37:01 +00002010
Dan Gohmandf476e52012-09-04 23:16:20 +00002011 S.SetKnownPositiveRefCount();
Dan Gohmanf64ff8e2012-07-23 19:27:31 +00002012
2013 // A retain can be a potential use; procede to the generic checking
2014 // code below.
2015 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00002016 }
2017 case IC_Release: {
2018 Arg = GetObjCArg(Inst);
2019
2020 PtrState &S = MyStates.getPtrTopDownState(Arg);
Michael Gottesman764b1cf2013-03-23 05:46:19 +00002021 S.ClearKnownPositiveRefCount();
Michael Gottesman79249972013-04-05 23:46:45 +00002022
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002023 Sequence OldSeq = S.GetSeq();
Michael Gottesman79249972013-04-05 23:46:45 +00002024
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002025 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
Michael Gottesman79249972013-04-05 23:46:45 +00002026
Michael Gottesman1d8d2572013-04-05 22:54:28 +00002027 switch (OldSeq) {
Dan Gohman817a7c62012-03-22 18:24:56 +00002028 case S_Retain:
2029 case S_CanRelease:
Craig Topperf40110f2014-04-25 05:29:35 +00002030 if (OldSeq == S_Retain || ReleaseMetadata != nullptr)
Michael Gottesman4f6ef112013-06-21 19:44:27 +00002031 S.ClearReverseInsertPts();
Dan Gohman817a7c62012-03-22 18:24:56 +00002032 // FALL THROUGH
2033 case S_Use:
Michael Gottesmanf701d3f2013-06-21 07:03:07 +00002034 S.SetReleaseMetadata(ReleaseMetadata);
Michael Gottesmanb82a1792013-06-21 07:00:44 +00002035 S.SetTailCallRelease(cast<CallInst>(Inst)->isTailCall());
Michael Gottesmane3943d02013-06-21 19:44:30 +00002036 Releases[Inst] = S.GetRRInfo();
Michael Gottesman81b1d432013-03-26 00:42:04 +00002037 ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_None);
Dan Gohman817a7c62012-03-22 18:24:56 +00002038 S.ClearSequenceProgress();
2039 break;
2040 case S_None:
2041 break;
2042 case S_Stop:
2043 case S_Release:
2044 case S_MovableRelease:
2045 llvm_unreachable("top-down pointer in release state!");
2046 }
2047 break;
2048 }
2049 case IC_AutoreleasepoolPop:
2050 // Conservatively, clear MyStates for all known pointers.
2051 MyStates.clearTopDownPointers();
2052 return NestingDetected;
2053 case IC_AutoreleasepoolPush:
2054 case IC_None:
2055 // These are irrelevant.
2056 return NestingDetected;
2057 default:
2058 break;
2059 }
2060
2061 // Consider any other possible effects of this instruction on each
2062 // pointer being tracked.
2063 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
2064 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
2065 const Value *Ptr = MI->first;
2066 if (Ptr == Arg)
2067 continue; // Handled above.
2068 PtrState &S = MI->second;
2069 Sequence Seq = S.GetSeq();
2070
2071 // Check for possible releases.
2072 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Michael Gottesmanbab49e972013-04-05 18:26:08 +00002073 DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr
Michael Gottesman79249972013-04-05 23:46:45 +00002074 << "\n");
Michael Gottesman764b1cf2013-03-23 05:46:19 +00002075 S.ClearKnownPositiveRefCount();
John McCalld935e9c2011-06-15 23:37:01 +00002076 switch (Seq) {
Dan Gohman817a7c62012-03-22 18:24:56 +00002077 case S_Retain:
2078 S.SetSeq(S_CanRelease);
Michael Gottesman81b1d432013-03-26 00:42:04 +00002079 ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_CanRelease);
Michael Gottesman4f6ef112013-06-21 19:44:27 +00002080 assert(!S.HasReverseInsertPts());
2081 S.InsertReverseInsertPt(Inst);
Dan Gohman817a7c62012-03-22 18:24:56 +00002082
2083 // One call can't cause a transition from S_Retain to S_CanRelease
2084 // and S_CanRelease to S_Use. If we've made the first transition,
2085 // we're done.
2086 continue;
John McCalld935e9c2011-06-15 23:37:01 +00002087 case S_Use:
Dan Gohman817a7c62012-03-22 18:24:56 +00002088 case S_CanRelease:
John McCalld935e9c2011-06-15 23:37:01 +00002089 case S_None:
2090 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00002091 case S_Stop:
2092 case S_Release:
2093 case S_MovableRelease:
2094 llvm_unreachable("top-down pointer in release state!");
John McCalld935e9c2011-06-15 23:37:01 +00002095 }
2096 }
Dan Gohman817a7c62012-03-22 18:24:56 +00002097
2098 // Check for possible direct uses.
2099 switch (Seq) {
2100 case S_CanRelease:
Michael Gottesman81b1d432013-03-26 00:42:04 +00002101 if (CanUse(Inst, Ptr, PA, Class)) {
Michael Gottesmanbab49e972013-04-05 18:26:08 +00002102 DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr
2103 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00002104 S.SetSeq(S_Use);
Michael Gottesman81b1d432013-03-26 00:42:04 +00002105 ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_Use);
2106 }
Dan Gohman817a7c62012-03-22 18:24:56 +00002107 break;
2108 case S_Retain:
2109 case S_Use:
2110 case S_None:
2111 break;
2112 case S_Stop:
2113 case S_Release:
2114 case S_MovableRelease:
2115 llvm_unreachable("top-down pointer in release state!");
2116 }
John McCalld935e9c2011-06-15 23:37:01 +00002117 }
2118
2119 return NestingDetected;
2120}
2121
2122bool
2123ObjCARCOpt::VisitTopDown(BasicBlock *BB,
2124 DenseMap<const BasicBlock *, BBState> &BBStates,
2125 DenseMap<Value *, RRInfo> &Releases) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002126 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitTopDown ==\n");
John McCalld935e9c2011-06-15 23:37:01 +00002127 bool NestingDetected = false;
2128 BBState &MyStates = BBStates[BB];
2129
2130 // Merge the states from each predecessor to compute the initial state
2131 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00002132 BBState::edge_iterator PI(MyStates.pred_begin()),
2133 PE(MyStates.pred_end());
2134 if (PI != PE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002135 const BasicBlock *Pred = *PI;
2136 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
2137 assert(I != BBStates.end());
2138 MyStates.InitFromPred(I->second);
2139 ++PI;
2140 for (; PI != PE; ++PI) {
2141 Pred = *PI;
2142 I = BBStates.find(Pred);
2143 assert(I != BBStates.end());
2144 MyStates.MergePred(I->second);
2145 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002146 }
John McCalld935e9c2011-06-15 23:37:01 +00002147
Michael Gottesman43e7e002013-04-03 22:41:59 +00002148 // If ARC Annotations are enabled, output the current state of pointers at the
2149 // top of the basic block.
2150 ANNOTATE_TOPDOWN_BBSTART(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002151
John McCalld935e9c2011-06-15 23:37:01 +00002152 // Visit all the instructions, top-down.
2153 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2154 Instruction *Inst = I;
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00002155
Michael Gottesman89279f82013-04-05 18:10:41 +00002156 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00002157
Dan Gohman817a7c62012-03-22 18:24:56 +00002158 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00002159 }
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002160
Michael Gottesman43e7e002013-04-03 22:41:59 +00002161 // If ARC Annotations are enabled, output the current state of pointers at the
2162 // bottom of the basic block.
2163 ANNOTATE_TOPDOWN_BBEND(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002164
Michael Gottesmanffef24f2013-04-17 20:48:01 +00002165#ifdef ARC_ANNOTATIONS
Michael Gottesmanadb921a2013-04-17 21:03:53 +00002166 if (!(EnableARCAnnotations && DisableCheckForCFGHazards))
Michael Gottesmanffef24f2013-04-17 20:48:01 +00002167#endif
John McCalld935e9c2011-06-15 23:37:01 +00002168 CheckForCFGHazards(BB, BBStates, MyStates);
2169 return NestingDetected;
2170}
2171
Dan Gohmana53a12c2011-12-12 19:42:25 +00002172static void
2173ComputePostOrders(Function &F,
2174 SmallVectorImpl<BasicBlock *> &PostOrder,
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002175 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
2176 unsigned NoObjCARCExceptionsMDKind,
2177 DenseMap<const BasicBlock *, BBState> &BBStates) {
Michael Gottesman97e3df02013-01-14 00:35:14 +00002178 /// The visited set, for doing DFS walks.
Dan Gohmana53a12c2011-12-12 19:42:25 +00002179 SmallPtrSet<BasicBlock *, 16> Visited;
2180
2181 // Do DFS, computing the PostOrder.
2182 SmallPtrSet<BasicBlock *, 16> OnStack;
2183 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002184
2185 // Functions always have exactly one entry block, and we don't have
2186 // any other block that we treat like an entry block.
Dan Gohmana53a12c2011-12-12 19:42:25 +00002187 BasicBlock *EntryBB = &F.getEntryBlock();
Dan Gohman41375a32012-05-08 23:39:44 +00002188 BBState &MyStates = BBStates[EntryBB];
2189 MyStates.SetAsEntry();
2190 TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
2191 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
Dan Gohmana53a12c2011-12-12 19:42:25 +00002192 Visited.insert(EntryBB);
2193 OnStack.insert(EntryBB);
2194 do {
2195 dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002196 BasicBlock *CurrBB = SuccStack.back().first;
2197 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
2198 succ_iterator SE(TI, false);
Dan Gohman41375a32012-05-08 23:39:44 +00002199
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002200 while (SuccStack.back().second != SE) {
2201 BasicBlock *SuccBB = *SuccStack.back().second++;
2202 if (Visited.insert(SuccBB)) {
Dan Gohman41375a32012-05-08 23:39:44 +00002203 TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
2204 SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002205 BBStates[CurrBB].addSucc(SuccBB);
Dan Gohman41375a32012-05-08 23:39:44 +00002206 BBState &SuccStates = BBStates[SuccBB];
2207 SuccStates.addPred(CurrBB);
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002208 OnStack.insert(SuccBB);
Dan Gohmana53a12c2011-12-12 19:42:25 +00002209 goto dfs_next_succ;
2210 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002211
2212 if (!OnStack.count(SuccBB)) {
2213 BBStates[CurrBB].addSucc(SuccBB);
2214 BBStates[SuccBB].addPred(CurrBB);
2215 }
Dan Gohmana53a12c2011-12-12 19:42:25 +00002216 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002217 OnStack.erase(CurrBB);
2218 PostOrder.push_back(CurrBB);
2219 SuccStack.pop_back();
Dan Gohmana53a12c2011-12-12 19:42:25 +00002220 } while (!SuccStack.empty());
2221
2222 Visited.clear();
2223
Dan Gohmana53a12c2011-12-12 19:42:25 +00002224 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002225 // Functions may have many exits, and there also blocks which we treat
2226 // as exits due to ignored edges.
2227 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
2228 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
2229 BasicBlock *ExitBB = I;
2230 BBState &MyStates = BBStates[ExitBB];
2231 if (!MyStates.isExit())
2232 continue;
2233
Dan Gohmandae33492012-04-27 18:56:31 +00002234 MyStates.SetAsExit();
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002235
2236 PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00002237 Visited.insert(ExitBB);
2238 while (!PredStack.empty()) {
2239 reverse_dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002240 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
2241 while (PredStack.back().second != PE) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00002242 BasicBlock *BB = *PredStack.back().second++;
Dan Gohmana53a12c2011-12-12 19:42:25 +00002243 if (Visited.insert(BB)) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002244 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00002245 goto reverse_dfs_next_succ;
2246 }
2247 }
2248 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
2249 }
2250 }
2251}
2252
Michael Gottesman97e3df02013-01-14 00:35:14 +00002253// Visit the function both top-down and bottom-up.
John McCalld935e9c2011-06-15 23:37:01 +00002254bool
2255ObjCARCOpt::Visit(Function &F,
2256 DenseMap<const BasicBlock *, BBState> &BBStates,
2257 MapVector<Value *, RRInfo> &Retains,
2258 DenseMap<Value *, RRInfo> &Releases) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00002259
2260 // Use reverse-postorder traversals, because we magically know that loops
2261 // will be well behaved, i.e. they won't repeatedly call retain on a single
2262 // pointer without doing a release. We can't use the ReversePostOrderTraversal
2263 // class here because we want the reverse-CFG postorder to consider each
2264 // function exit point, and we want to ignore selected cycle edges.
2265 SmallVector<BasicBlock *, 16> PostOrder;
2266 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002267 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
2268 NoObjCARCExceptionsMDKind,
2269 BBStates);
Dan Gohmana53a12c2011-12-12 19:42:25 +00002270
2271 // Use reverse-postorder on the reverse CFG for bottom-up.
John McCalld935e9c2011-06-15 23:37:01 +00002272 bool BottomUpNestingDetected = false;
Dan Gohmanc57b58c2011-08-18 21:27:42 +00002273 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
Dan Gohmana53a12c2011-12-12 19:42:25 +00002274 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
2275 I != E; ++I)
2276 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
John McCalld935e9c2011-06-15 23:37:01 +00002277
Dan Gohmana53a12c2011-12-12 19:42:25 +00002278 // Use reverse-postorder for top-down.
John McCalld935e9c2011-06-15 23:37:01 +00002279 bool TopDownNestingDetected = false;
Dan Gohmana53a12c2011-12-12 19:42:25 +00002280 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2281 PostOrder.rbegin(), E = PostOrder.rend();
2282 I != E; ++I)
2283 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
John McCalld935e9c2011-06-15 23:37:01 +00002284
2285 return TopDownNestingDetected && BottomUpNestingDetected;
2286}
2287
Michael Gottesman97e3df02013-01-14 00:35:14 +00002288/// Move the calls in RetainsToMove and ReleasesToMove.
John McCalld935e9c2011-06-15 23:37:01 +00002289void ObjCARCOpt::MoveCalls(Value *Arg,
2290 RRInfo &RetainsToMove,
2291 RRInfo &ReleasesToMove,
2292 MapVector<Value *, RRInfo> &Retains,
2293 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman6320f522011-07-22 22:29:21 +00002294 SmallVectorImpl<Instruction *> &DeadInsts,
Michael Gottesman79249972013-04-05 23:46:45 +00002295 Module *M) {
Chris Lattner229907c2011-07-18 04:54:35 +00002296 Type *ArgTy = Arg->getType();
Dan Gohman6320f522011-07-22 22:29:21 +00002297 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
Michael Gottesman79249972013-04-05 23:46:45 +00002298
Michael Gottesman89279f82013-04-05 18:10:41 +00002299 DEBUG(dbgs() << "== ObjCARCOpt::MoveCalls ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00002300
John McCalld935e9c2011-06-15 23:37:01 +00002301 // Insert the new retain and release calls.
2302 for (SmallPtrSet<Instruction *, 2>::const_iterator
2303 PI = ReleasesToMove.ReverseInsertPts.begin(),
2304 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2305 Instruction *InsertPt = *PI;
2306 Value *MyArg = ArgTy == ParamTy ? Arg :
2307 new BitCastInst(Arg, ParamTy, "", InsertPt);
Michael Gottesman14acfac2013-07-06 01:39:23 +00002308 Constant *Decl = EP.get(ARCRuntimeEntryPoints::EPT_Retain);
2309 CallInst *Call = CallInst::Create(Decl, MyArg, "", InsertPt);
John McCalld935e9c2011-06-15 23:37:01 +00002310 Call->setDoesNotThrow();
Michael Gottesmanba648592013-03-28 23:08:44 +00002311 Call->setTailCall();
Michael Gottesman60f6b282013-03-29 05:13:07 +00002312
Michael Gottesmandf110ac2013-04-21 00:30:50 +00002313 DEBUG(dbgs() << "Inserting new Retain: " << *Call << "\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00002314 "At insertion point: " << *InsertPt << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002315 }
2316 for (SmallPtrSet<Instruction *, 2>::const_iterator
2317 PI = RetainsToMove.ReverseInsertPts.begin(),
2318 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00002319 Instruction *InsertPt = *PI;
2320 Value *MyArg = ArgTy == ParamTy ? Arg :
2321 new BitCastInst(Arg, ParamTy, "", InsertPt);
Michael Gottesman14acfac2013-07-06 01:39:23 +00002322 Constant *Decl = EP.get(ARCRuntimeEntryPoints::EPT_Release);
2323 CallInst *Call = CallInst::Create(Decl, MyArg, "", InsertPt);
Dan Gohman5c70fad2012-03-23 17:47:54 +00002324 // Attach a clang.imprecise_release metadata tag, if appropriate.
2325 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
2326 Call->setMetadata(ImpreciseReleaseMDKind, M);
2327 Call->setDoesNotThrow();
2328 if (ReleasesToMove.IsTailCallRelease)
2329 Call->setTailCall();
Michael Gottesmanc189a392013-01-09 19:23:24 +00002330
Michael Gottesman89279f82013-04-05 18:10:41 +00002331 DEBUG(dbgs() << "Inserting new Release: " << *Call << "\n"
2332 "At insertion point: " << *InsertPt << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002333 }
2334
2335 // Delete the original retain and release calls.
2336 for (SmallPtrSet<Instruction *, 2>::const_iterator
2337 AI = RetainsToMove.Calls.begin(),
2338 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
2339 Instruction *OrigRetain = *AI;
2340 Retains.blot(OrigRetain);
2341 DeadInsts.push_back(OrigRetain);
Michael Gottesman89279f82013-04-05 18:10:41 +00002342 DEBUG(dbgs() << "Deleting retain: " << *OrigRetain << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002343 }
2344 for (SmallPtrSet<Instruction *, 2>::const_iterator
2345 AI = ReleasesToMove.Calls.begin(),
2346 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
2347 Instruction *OrigRelease = *AI;
2348 Releases.erase(OrigRelease);
2349 DeadInsts.push_back(OrigRelease);
Michael Gottesman89279f82013-04-05 18:10:41 +00002350 DEBUG(dbgs() << "Deleting release: " << *OrigRelease << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002351 }
Michael Gottesman79249972013-04-05 23:46:45 +00002352
John McCalld935e9c2011-06-15 23:37:01 +00002353}
2354
Michael Gottesman9de6f962013-01-22 21:49:00 +00002355bool
2356ObjCARCOpt::ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState>
2357 &BBStates,
2358 MapVector<Value *, RRInfo> &Retains,
2359 DenseMap<Value *, RRInfo> &Releases,
2360 Module *M,
Craig Topperb94011f2013-07-14 04:42:23 +00002361 SmallVectorImpl<Instruction *> &NewRetains,
2362 SmallVectorImpl<Instruction *> &NewReleases,
2363 SmallVectorImpl<Instruction *> &DeadInsts,
Michael Gottesman9de6f962013-01-22 21:49:00 +00002364 RRInfo &RetainsToMove,
2365 RRInfo &ReleasesToMove,
2366 Value *Arg,
2367 bool KnownSafe,
2368 bool &AnyPairsCompletelyEliminated) {
2369 // If a pair happens in a region where it is known that the reference count
Michael Gottesmana76143ee2013-05-13 23:49:42 +00002370 // is already incremented, we can similarly ignore possible decrements unless
2371 // we are dealing with a retainable object with multiple provenance sources.
Michael Gottesman9de6f962013-01-22 21:49:00 +00002372 bool KnownSafeTD = true, KnownSafeBU = true;
Michael Gottesmana76143ee2013-05-13 23:49:42 +00002373 bool MultipleOwners = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00002374 bool CFGHazardAfflicted = false;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002375
2376 // Connect the dots between the top-down-collected RetainsToMove and
2377 // bottom-up-collected ReleasesToMove to form sets of related calls.
2378 // This is an iterative process so that we connect multiple releases
2379 // to multiple retains if needed.
2380 unsigned OldDelta = 0;
2381 unsigned NewDelta = 0;
2382 unsigned OldCount = 0;
2383 unsigned NewCount = 0;
2384 bool FirstRelease = true;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002385 for (;;) {
2386 for (SmallVectorImpl<Instruction *>::const_iterator
2387 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
2388 Instruction *NewRetain = *NI;
2389 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
2390 assert(It != Retains.end());
2391 const RRInfo &NewRetainRRI = It->second;
2392 KnownSafeTD &= NewRetainRRI.KnownSafe;
Michael Gottesman5a91bbf2013-05-24 20:44:02 +00002393 MultipleOwners =
2394 MultipleOwners || MultiOwnersSet.count(GetObjCArg(NewRetain));
Michael Gottesman9de6f962013-01-22 21:49:00 +00002395 for (SmallPtrSet<Instruction *, 2>::const_iterator
2396 LI = NewRetainRRI.Calls.begin(),
2397 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
2398 Instruction *NewRetainRelease = *LI;
2399 DenseMap<Value *, RRInfo>::const_iterator Jt =
2400 Releases.find(NewRetainRelease);
2401 if (Jt == Releases.end())
2402 return false;
2403 const RRInfo &NewRetainReleaseRRI = Jt->second;
Michael Gottesman24b2f6f2013-11-05 16:02:40 +00002404
2405 // If the release does not have a reference to the retain as well,
2406 // something happened which is unaccounted for. Do not do anything.
2407 //
2408 // This can happen if we catch an additive overflow during path count
2409 // merging.
2410 if (!NewRetainReleaseRRI.Calls.count(NewRetain))
2411 return false;
2412
Michael Gottesman9de6f962013-01-22 21:49:00 +00002413 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002414
2415 // If we overflow when we compute the path count, don't remove/move
2416 // anything.
2417 const BBState &NRRBBState = BBStates[NewRetainRelease->getParent()];
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00002418 unsigned PathCount = BBState::OverflowOccurredValue;
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002419 if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
2420 return false;
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00002421 assert(PathCount != BBState::OverflowOccurredValue &&
2422 "PathCount at this point can not be "
2423 "OverflowOccurredValue.");
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002424 OldDelta -= PathCount;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002425
2426 // Merge the ReleaseMetadata and IsTailCallRelease values.
2427 if (FirstRelease) {
2428 ReleasesToMove.ReleaseMetadata =
2429 NewRetainReleaseRRI.ReleaseMetadata;
2430 ReleasesToMove.IsTailCallRelease =
2431 NewRetainReleaseRRI.IsTailCallRelease;
2432 FirstRelease = false;
2433 } else {
2434 if (ReleasesToMove.ReleaseMetadata !=
2435 NewRetainReleaseRRI.ReleaseMetadata)
Craig Topperf40110f2014-04-25 05:29:35 +00002436 ReleasesToMove.ReleaseMetadata = nullptr;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002437 if (ReleasesToMove.IsTailCallRelease !=
2438 NewRetainReleaseRRI.IsTailCallRelease)
2439 ReleasesToMove.IsTailCallRelease = false;
2440 }
2441
2442 // Collect the optimal insertion points.
2443 if (!KnownSafe)
2444 for (SmallPtrSet<Instruction *, 2>::const_iterator
2445 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
2446 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
2447 RI != RE; ++RI) {
2448 Instruction *RIP = *RI;
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002449 if (ReleasesToMove.ReverseInsertPts.insert(RIP)) {
2450 // If we overflow when we compute the path count, don't
2451 // remove/move anything.
2452 const BBState &RIPBBState = BBStates[RIP->getParent()];
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00002453 PathCount = BBState::OverflowOccurredValue;
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002454 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
2455 return false;
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00002456 assert(PathCount != BBState::OverflowOccurredValue &&
2457 "PathCount at this point can not be "
2458 "OverflowOccurredValue.");
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002459 NewDelta -= PathCount;
2460 }
Michael Gottesman9de6f962013-01-22 21:49:00 +00002461 }
2462 NewReleases.push_back(NewRetainRelease);
2463 }
2464 }
2465 }
2466 NewRetains.clear();
2467 if (NewReleases.empty()) break;
2468
2469 // Back the other way.
2470 for (SmallVectorImpl<Instruction *>::const_iterator
2471 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
2472 Instruction *NewRelease = *NI;
2473 DenseMap<Value *, RRInfo>::const_iterator It =
2474 Releases.find(NewRelease);
2475 assert(It != Releases.end());
2476 const RRInfo &NewReleaseRRI = It->second;
2477 KnownSafeBU &= NewReleaseRRI.KnownSafe;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00002478 CFGHazardAfflicted |= NewReleaseRRI.CFGHazardAfflicted;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002479 for (SmallPtrSet<Instruction *, 2>::const_iterator
2480 LI = NewReleaseRRI.Calls.begin(),
2481 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
2482 Instruction *NewReleaseRetain = *LI;
2483 MapVector<Value *, RRInfo>::const_iterator Jt =
2484 Retains.find(NewReleaseRetain);
2485 if (Jt == Retains.end())
2486 return false;
2487 const RRInfo &NewReleaseRetainRRI = Jt->second;
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002488
Michael Gottesman24b2f6f2013-11-05 16:02:40 +00002489 // If the retain does not have a reference to the release as well,
2490 // something happened which is unaccounted for. Do not do anything.
2491 //
2492 // This can happen if we catch an additive overflow during path count
2493 // merging.
2494 if (!NewReleaseRetainRRI.Calls.count(NewRelease))
2495 return false;
2496
2497 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002498 // If we overflow when we compute the path count, don't remove/move
2499 // anything.
2500 const BBState &NRRBBState = BBStates[NewReleaseRetain->getParent()];
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00002501 unsigned PathCount = BBState::OverflowOccurredValue;
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002502 if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
2503 return false;
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00002504 assert(PathCount != BBState::OverflowOccurredValue &&
2505 "PathCount at this point can not be "
2506 "OverflowOccurredValue.");
Michael Gottesman9de6f962013-01-22 21:49:00 +00002507 OldDelta += PathCount;
2508 OldCount += PathCount;
2509
Michael Gottesman9de6f962013-01-22 21:49:00 +00002510 // Collect the optimal insertion points.
2511 if (!KnownSafe)
2512 for (SmallPtrSet<Instruction *, 2>::const_iterator
2513 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
2514 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
2515 RI != RE; ++RI) {
2516 Instruction *RIP = *RI;
2517 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002518 // If we overflow when we compute the path count, don't
2519 // remove/move anything.
2520 const BBState &RIPBBState = BBStates[RIP->getParent()];
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00002521
2522 PathCount = BBState::OverflowOccurredValue;
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002523 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
2524 return false;
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00002525 assert(PathCount != BBState::OverflowOccurredValue &&
2526 "PathCount at this point can not be "
2527 "OverflowOccurredValue.");
Michael Gottesman9de6f962013-01-22 21:49:00 +00002528 NewDelta += PathCount;
2529 NewCount += PathCount;
2530 }
2531 }
2532 NewRetains.push_back(NewReleaseRetain);
2533 }
2534 }
2535 }
2536 NewReleases.clear();
2537 if (NewRetains.empty()) break;
2538 }
2539
Michael Gottesmana76143ee2013-05-13 23:49:42 +00002540 // If the pointer is known incremented in 1 direction and we do not have
2541 // MultipleOwners, we can safely remove the retain/releases. Otherwise we need
2542 // to be known safe in both directions.
2543 bool UnconditionallySafe = (KnownSafeTD && KnownSafeBU) ||
2544 ((KnownSafeTD || KnownSafeBU) && !MultipleOwners);
2545 if (UnconditionallySafe) {
Michael Gottesman9de6f962013-01-22 21:49:00 +00002546 RetainsToMove.ReverseInsertPts.clear();
2547 ReleasesToMove.ReverseInsertPts.clear();
2548 NewCount = 0;
2549 } else {
2550 // Determine whether the new insertion points we computed preserve the
2551 // balance of retain and release calls through the program.
2552 // TODO: If the fully aggressive solution isn't valid, try to find a
2553 // less aggressive solution which is.
2554 if (NewDelta != 0)
2555 return false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00002556
2557 // At this point, we are not going to remove any RR pairs, but we still are
2558 // able to move RR pairs. If one of our pointers is afflicted with
2559 // CFGHazards, we cannot perform such code motion so exit early.
2560 const bool WillPerformCodeMotion = RetainsToMove.ReverseInsertPts.size() ||
2561 ReleasesToMove.ReverseInsertPts.size();
2562 if (CFGHazardAfflicted && WillPerformCodeMotion)
2563 return false;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002564 }
2565
2566 // Determine whether the original call points are balanced in the retain and
2567 // release calls through the program. If not, conservatively don't touch
2568 // them.
2569 // TODO: It's theoretically possible to do code motion in this case, as
2570 // long as the existing imbalances are maintained.
2571 if (OldDelta != 0)
2572 return false;
Michael Gottesman8005ad32013-04-29 06:16:55 +00002573
Michael Gottesmana87bb8f2013-04-29 05:13:13 +00002574#ifdef ARC_ANNOTATIONS
2575 // Do not move calls if ARC annotations are requested.
Michael Gottesman3e3977c2013-04-29 05:25:39 +00002576 if (EnableARCAnnotations)
2577 return false;
Michael Gottesmana87bb8f2013-04-29 05:13:13 +00002578#endif // ARC_ANNOTATIONS
Michael Gottesman9de6f962013-01-22 21:49:00 +00002579
2580 Changed = true;
2581 assert(OldCount != 0 && "Unreachable code?");
2582 NumRRs += OldCount - NewCount;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002583 // Set to true if we completely removed any RR pairs.
Michael Gottesman8b5515f2013-01-22 21:53:43 +00002584 AnyPairsCompletelyEliminated = NewCount == 0;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002585
2586 // We can move calls!
2587 return true;
2588}
2589
Michael Gottesman97e3df02013-01-14 00:35:14 +00002590/// Identify pairings between the retains and releases, and delete and/or move
2591/// them.
John McCalld935e9c2011-06-15 23:37:01 +00002592bool
2593ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
2594 &BBStates,
2595 MapVector<Value *, RRInfo> &Retains,
Dan Gohman6320f522011-07-22 22:29:21 +00002596 DenseMap<Value *, RRInfo> &Releases,
2597 Module *M) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002598 DEBUG(dbgs() << "\n== ObjCARCOpt::PerformCodePlacement ==\n");
2599
John McCalld935e9c2011-06-15 23:37:01 +00002600 bool AnyPairsCompletelyEliminated = false;
2601 RRInfo RetainsToMove;
2602 RRInfo ReleasesToMove;
2603 SmallVector<Instruction *, 4> NewRetains;
2604 SmallVector<Instruction *, 4> NewReleases;
2605 SmallVector<Instruction *, 8> DeadInsts;
2606
Dan Gohman670f9372012-04-13 18:57:48 +00002607 // Visit each retain.
John McCalld935e9c2011-06-15 23:37:01 +00002608 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
Dan Gohman2053a5d2011-09-29 22:25:23 +00002609 E = Retains.end(); I != E; ++I) {
2610 Value *V = I->first;
John McCalld935e9c2011-06-15 23:37:01 +00002611 if (!V) continue; // blotted
2612
2613 Instruction *Retain = cast<Instruction>(V);
Michael Gottesmanc189a392013-01-09 19:23:24 +00002614
Michael Gottesman89279f82013-04-05 18:10:41 +00002615 DEBUG(dbgs() << "Visiting: " << *Retain << "\n");
Michael Gottesmanc189a392013-01-09 19:23:24 +00002616
John McCalld935e9c2011-06-15 23:37:01 +00002617 Value *Arg = GetObjCArg(Retain);
2618
Dan Gohman728db492012-01-13 00:39:07 +00002619 // If the object being released is in static or stack storage, we know it's
John McCalld935e9c2011-06-15 23:37:01 +00002620 // not being managed by ObjC reference counting, so we can delete pairs
2621 // regardless of what possible decrements or uses lie between them.
Dan Gohman728db492012-01-13 00:39:07 +00002622 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
Dan Gohman41375a32012-05-08 23:39:44 +00002623
Dan Gohman56e1cef2011-08-22 17:29:11 +00002624 // A constant pointer can't be pointing to an object on the heap. It may
2625 // be reference-counted, but it won't be deleted.
2626 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
2627 if (const GlobalVariable *GV =
2628 dyn_cast<GlobalVariable>(
2629 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
2630 if (GV->isConstant())
2631 KnownSafe = true;
2632
John McCalld935e9c2011-06-15 23:37:01 +00002633 // Connect the dots between the top-down-collected RetainsToMove and
2634 // bottom-up-collected ReleasesToMove to form sets of related calls.
John McCalld935e9c2011-06-15 23:37:01 +00002635 NewRetains.push_back(Retain);
Michael Gottesman9de6f962013-01-22 21:49:00 +00002636 bool PerformMoveCalls =
2637 ConnectTDBUTraversals(BBStates, Retains, Releases, M, NewRetains,
2638 NewReleases, DeadInsts, RetainsToMove,
2639 ReleasesToMove, Arg, KnownSafe,
2640 AnyPairsCompletelyEliminated);
John McCalld935e9c2011-06-15 23:37:01 +00002641
Michael Gottesman9de6f962013-01-22 21:49:00 +00002642 if (PerformMoveCalls) {
2643 // Ok, everything checks out and we're all set. Let's move/delete some
2644 // code!
2645 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
2646 Retains, Releases, DeadInsts, M);
John McCalld935e9c2011-06-15 23:37:01 +00002647 }
2648
Michael Gottesman9de6f962013-01-22 21:49:00 +00002649 // Clean up state for next retain.
John McCalld935e9c2011-06-15 23:37:01 +00002650 NewReleases.clear();
2651 NewRetains.clear();
2652 RetainsToMove.clear();
2653 ReleasesToMove.clear();
2654 }
2655
2656 // Now that we're done moving everything, we can delete the newly dead
2657 // instructions, as we no longer need them as insert points.
2658 while (!DeadInsts.empty())
2659 EraseInstruction(DeadInsts.pop_back_val());
2660
2661 return AnyPairsCompletelyEliminated;
2662}
2663
Michael Gottesman97e3df02013-01-14 00:35:14 +00002664/// Weak pointer optimizations.
John McCalld935e9c2011-06-15 23:37:01 +00002665void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002666 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeWeakCalls ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00002667
John McCalld935e9c2011-06-15 23:37:01 +00002668 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
2669 // itself because it uses AliasAnalysis and we need to do provenance
2670 // queries instead.
2671 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2672 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +00002673
Michael Gottesman89279f82013-04-05 18:10:41 +00002674 DEBUG(dbgs() << "Visiting: " << *Inst << "\n");
Michael Gottesman3f146e22013-01-01 16:05:48 +00002675
John McCalld935e9c2011-06-15 23:37:01 +00002676 InstructionClass Class = GetBasicInstructionClass(Inst);
2677 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
2678 continue;
2679
2680 // Delete objc_loadWeak calls with no users.
2681 if (Class == IC_LoadWeak && Inst->use_empty()) {
2682 Inst->eraseFromParent();
2683 continue;
2684 }
2685
2686 // TODO: For now, just look for an earlier available version of this value
2687 // within the same block. Theoretically, we could do memdep-style non-local
2688 // analysis too, but that would want caching. A better approach would be to
2689 // use the technique that EarlyCSE uses.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00002690 inst_iterator Current = std::prev(I);
John McCalld935e9c2011-06-15 23:37:01 +00002691 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
2692 for (BasicBlock::iterator B = CurrentBB->begin(),
2693 J = Current.getInstructionIterator();
2694 J != B; --J) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00002695 Instruction *EarlierInst = &*std::prev(J);
John McCalld935e9c2011-06-15 23:37:01 +00002696 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
2697 switch (EarlierClass) {
2698 case IC_LoadWeak:
2699 case IC_LoadWeakRetained: {
2700 // If this is loading from the same pointer, replace this load's value
2701 // with that one.
2702 CallInst *Call = cast<CallInst>(Inst);
2703 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2704 Value *Arg = Call->getArgOperand(0);
2705 Value *EarlierArg = EarlierCall->getArgOperand(0);
2706 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2707 case AliasAnalysis::MustAlias:
2708 Changed = true;
2709 // If the load has a builtin retain, insert a plain retain for it.
2710 if (Class == IC_LoadWeakRetained) {
Michael Gottesman14acfac2013-07-06 01:39:23 +00002711 Constant *Decl = EP.get(ARCRuntimeEntryPoints::EPT_Retain);
2712 CallInst *CI = CallInst::Create(Decl, EarlierCall, "", Call);
John McCalld935e9c2011-06-15 23:37:01 +00002713 CI->setTailCall();
2714 }
2715 // Zap the fully redundant load.
2716 Call->replaceAllUsesWith(EarlierCall);
2717 Call->eraseFromParent();
2718 goto clobbered;
2719 case AliasAnalysis::MayAlias:
2720 case AliasAnalysis::PartialAlias:
2721 goto clobbered;
2722 case AliasAnalysis::NoAlias:
2723 break;
2724 }
2725 break;
2726 }
2727 case IC_StoreWeak:
2728 case IC_InitWeak: {
2729 // If this is storing to the same pointer and has the same size etc.
2730 // replace this load's value with the stored value.
2731 CallInst *Call = cast<CallInst>(Inst);
2732 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2733 Value *Arg = Call->getArgOperand(0);
2734 Value *EarlierArg = EarlierCall->getArgOperand(0);
2735 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2736 case AliasAnalysis::MustAlias:
2737 Changed = true;
2738 // If the load has a builtin retain, insert a plain retain for it.
2739 if (Class == IC_LoadWeakRetained) {
Michael Gottesman14acfac2013-07-06 01:39:23 +00002740 Constant *Decl = EP.get(ARCRuntimeEntryPoints::EPT_Retain);
2741 CallInst *CI = CallInst::Create(Decl, EarlierCall, "", Call);
John McCalld935e9c2011-06-15 23:37:01 +00002742 CI->setTailCall();
2743 }
2744 // Zap the fully redundant load.
2745 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
2746 Call->eraseFromParent();
2747 goto clobbered;
2748 case AliasAnalysis::MayAlias:
2749 case AliasAnalysis::PartialAlias:
2750 goto clobbered;
2751 case AliasAnalysis::NoAlias:
2752 break;
2753 }
2754 break;
2755 }
2756 case IC_MoveWeak:
2757 case IC_CopyWeak:
2758 // TOOD: Grab the copied value.
2759 goto clobbered;
2760 case IC_AutoreleasepoolPush:
2761 case IC_None:
John McCall20182ac2013-03-22 21:38:36 +00002762 case IC_IntrinsicUser:
John McCalld935e9c2011-06-15 23:37:01 +00002763 case IC_User:
2764 // Weak pointers are only modified through the weak entry points
2765 // (and arbitrary calls, which could call the weak entry points).
2766 break;
2767 default:
2768 // Anything else could modify the weak pointer.
2769 goto clobbered;
2770 }
2771 }
2772 clobbered:;
2773 }
2774
2775 // Then, for each destroyWeak with an alloca operand, check to see if
2776 // the alloca and all its users can be zapped.
2777 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2778 Instruction *Inst = &*I++;
2779 InstructionClass Class = GetBasicInstructionClass(Inst);
2780 if (Class != IC_DestroyWeak)
2781 continue;
2782
2783 CallInst *Call = cast<CallInst>(Inst);
2784 Value *Arg = Call->getArgOperand(0);
2785 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00002786 for (User *U : Alloca->users()) {
2787 const Instruction *UserInst = cast<Instruction>(U);
John McCalld935e9c2011-06-15 23:37:01 +00002788 switch (GetBasicInstructionClass(UserInst)) {
2789 case IC_InitWeak:
2790 case IC_StoreWeak:
2791 case IC_DestroyWeak:
2792 continue;
2793 default:
2794 goto done;
2795 }
2796 }
2797 Changed = true;
Chandler Carruthcdf47882014-03-09 03:16:01 +00002798 for (auto UI = Alloca->user_begin(), UE = Alloca->user_end(); UI != UE;) {
John McCalld935e9c2011-06-15 23:37:01 +00002799 CallInst *UserInst = cast<CallInst>(*UI++);
Dan Gohman14862c32012-05-18 22:17:29 +00002800 switch (GetBasicInstructionClass(UserInst)) {
2801 case IC_InitWeak:
2802 case IC_StoreWeak:
2803 // These functions return their second argument.
2804 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
2805 break;
2806 case IC_DestroyWeak:
2807 // No return value.
2808 break;
2809 default:
Dan Gohman9c97eea02012-05-21 17:41:28 +00002810 llvm_unreachable("alloca really is used!");
Dan Gohman14862c32012-05-18 22:17:29 +00002811 }
John McCalld935e9c2011-06-15 23:37:01 +00002812 UserInst->eraseFromParent();
2813 }
2814 Alloca->eraseFromParent();
2815 done:;
2816 }
2817 }
2818}
2819
Michael Gottesman97e3df02013-01-14 00:35:14 +00002820/// Identify program paths which execute sequences of retains and releases which
2821/// can be eliminated.
John McCalld935e9c2011-06-15 23:37:01 +00002822bool ObjCARCOpt::OptimizeSequences(Function &F) {
Michael Gottesman740db972013-05-23 02:35:21 +00002823 // Releases, Retains - These are used to store the results of the main flow
2824 // analysis. These use Value* as the key instead of Instruction* so that the
2825 // map stays valid when we get around to rewriting code and calls get
2826 // replaced by arguments.
John McCalld935e9c2011-06-15 23:37:01 +00002827 DenseMap<Value *, RRInfo> Releases;
2828 MapVector<Value *, RRInfo> Retains;
2829
Michael Gottesman740db972013-05-23 02:35:21 +00002830 // This is used during the traversal of the function to track the
2831 // states for each identified object at each block.
John McCalld935e9c2011-06-15 23:37:01 +00002832 DenseMap<const BasicBlock *, BBState> BBStates;
2833
2834 // Analyze the CFG of the function, and all instructions.
2835 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
2836
2837 // Transform.
Michael Gottesman5a91bbf2013-05-24 20:44:02 +00002838 bool AnyPairsCompletelyEliminated = PerformCodePlacement(BBStates, Retains,
2839 Releases,
2840 F.getParent());
2841
2842 // Cleanup.
2843 MultiOwnersSet.clear();
2844
2845 return AnyPairsCompletelyEliminated && NestingDetected;
John McCalld935e9c2011-06-15 23:37:01 +00002846}
2847
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002848/// Check if there is a dependent call earlier that does not have anything in
2849/// between the Retain and the call that can affect the reference count of their
2850/// shared pointer argument. Note that Retain need not be in BB.
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002851static bool
2852HasSafePathToPredecessorCall(const Value *Arg, Instruction *Retain,
2853 SmallPtrSet<Instruction *, 4> &DepInsts,
2854 SmallPtrSet<const BasicBlock *, 4> &Visited,
2855 ProvenanceAnalysis &PA) {
2856 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
2857 DepInsts, Visited, PA);
2858 if (DepInsts.size() != 1)
2859 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002860
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002861 CallInst *Call =
2862 dyn_cast_or_null<CallInst>(*DepInsts.begin());
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002863
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002864 // Check that the pointer is the return value of the call.
2865 if (!Call || Arg != Call)
2866 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002867
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002868 // Check that the call is a regular call.
2869 InstructionClass Class = GetBasicInstructionClass(Call);
2870 if (Class != IC_CallOrUser && Class != IC_Call)
2871 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002872
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002873 return true;
2874}
2875
Michael Gottesman6908db12013-04-03 23:16:05 +00002876/// Find a dependent retain that precedes the given autorelease for which there
2877/// is nothing in between the two instructions that can affect the ref count of
2878/// Arg.
2879static CallInst *
2880FindPredecessorRetainWithSafePath(const Value *Arg, BasicBlock *BB,
2881 Instruction *Autorelease,
2882 SmallPtrSet<Instruction *, 4> &DepInsts,
2883 SmallPtrSet<const BasicBlock *, 4> &Visited,
2884 ProvenanceAnalysis &PA) {
2885 FindDependencies(CanChangeRetainCount, Arg,
2886 BB, Autorelease, DepInsts, Visited, PA);
2887 if (DepInsts.size() != 1)
Craig Topperf40110f2014-04-25 05:29:35 +00002888 return nullptr;
Michael Gottesman79249972013-04-05 23:46:45 +00002889
Michael Gottesman6908db12013-04-03 23:16:05 +00002890 CallInst *Retain =
2891 dyn_cast_or_null<CallInst>(*DepInsts.begin());
Michael Gottesman79249972013-04-05 23:46:45 +00002892
Michael Gottesman6908db12013-04-03 23:16:05 +00002893 // Check that we found a retain with the same argument.
2894 if (!Retain ||
2895 !IsRetain(GetBasicInstructionClass(Retain)) ||
2896 GetObjCArg(Retain) != Arg) {
Craig Topperf40110f2014-04-25 05:29:35 +00002897 return nullptr;
Michael Gottesman6908db12013-04-03 23:16:05 +00002898 }
Michael Gottesman79249972013-04-05 23:46:45 +00002899
Michael Gottesman6908db12013-04-03 23:16:05 +00002900 return Retain;
2901}
2902
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002903/// Look for an ``autorelease'' instruction dependent on Arg such that there are
2904/// no instructions dependent on Arg that need a positive ref count in between
2905/// the autorelease and the ret.
2906static CallInst *
2907FindPredecessorAutoreleaseWithSafePath(const Value *Arg, BasicBlock *BB,
2908 ReturnInst *Ret,
2909 SmallPtrSet<Instruction *, 4> &DepInsts,
2910 SmallPtrSet<const BasicBlock *, 4> &V,
2911 ProvenanceAnalysis &PA) {
2912 FindDependencies(NeedsPositiveRetainCount, Arg,
2913 BB, Ret, DepInsts, V, PA);
2914 if (DepInsts.size() != 1)
Craig Topperf40110f2014-04-25 05:29:35 +00002915 return nullptr;
Michael Gottesman79249972013-04-05 23:46:45 +00002916
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002917 CallInst *Autorelease =
2918 dyn_cast_or_null<CallInst>(*DepInsts.begin());
2919 if (!Autorelease)
Craig Topperf40110f2014-04-25 05:29:35 +00002920 return nullptr;
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002921 InstructionClass AutoreleaseClass = GetBasicInstructionClass(Autorelease);
2922 if (!IsAutorelease(AutoreleaseClass))
Craig Topperf40110f2014-04-25 05:29:35 +00002923 return nullptr;
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002924 if (GetObjCArg(Autorelease) != Arg)
Craig Topperf40110f2014-04-25 05:29:35 +00002925 return nullptr;
Michael Gottesman79249972013-04-05 23:46:45 +00002926
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002927 return Autorelease;
2928}
2929
Michael Gottesman97e3df02013-01-14 00:35:14 +00002930/// Look for this pattern:
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00002931/// \code
John McCalld935e9c2011-06-15 23:37:01 +00002932/// %call = call i8* @something(...)
2933/// %2 = call i8* @objc_retain(i8* %call)
2934/// %3 = call i8* @objc_autorelease(i8* %2)
2935/// ret i8* %3
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00002936/// \endcode
John McCalld935e9c2011-06-15 23:37:01 +00002937/// And delete the retain and autorelease.
John McCalld935e9c2011-06-15 23:37:01 +00002938void ObjCARCOpt::OptimizeReturns(Function &F) {
2939 if (!F.getReturnType()->isPointerTy())
2940 return;
Michael Gottesman79249972013-04-05 23:46:45 +00002941
Michael Gottesman89279f82013-04-05 18:10:41 +00002942 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeReturns ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00002943
John McCalld935e9c2011-06-15 23:37:01 +00002944 SmallPtrSet<Instruction *, 4> DependingInstructions;
2945 SmallPtrSet<const BasicBlock *, 4> Visited;
2946 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
2947 BasicBlock *BB = FI;
2948 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
Michael Gottesman3f146e22013-01-01 16:05:48 +00002949
Michael Gottesman89279f82013-04-05 18:10:41 +00002950 DEBUG(dbgs() << "Visiting: " << *Ret << "\n");
Michael Gottesman3f146e22013-01-01 16:05:48 +00002951
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002952 if (!Ret)
2953 continue;
Michael Gottesman79249972013-04-05 23:46:45 +00002954
John McCalld935e9c2011-06-15 23:37:01 +00002955 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
Michael Gottesman79249972013-04-05 23:46:45 +00002956
Michael Gottesmancdb7c152013-04-21 00:25:04 +00002957 // Look for an ``autorelease'' instruction that is a predecessor of Ret and
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002958 // dependent on Arg such that there are no instructions dependent on Arg
2959 // that need a positive ref count in between the autorelease and Ret.
2960 CallInst *Autorelease =
2961 FindPredecessorAutoreleaseWithSafePath(Arg, BB, Ret,
2962 DependingInstructions, Visited,
2963 PA);
John McCalld935e9c2011-06-15 23:37:01 +00002964 DependingInstructions.clear();
2965 Visited.clear();
Michael Gottesmanfb9ece92013-04-21 00:25:01 +00002966
2967 if (!Autorelease)
2968 continue;
2969
2970 CallInst *Retain =
2971 FindPredecessorRetainWithSafePath(Arg, BB, Autorelease,
2972 DependingInstructions, Visited, PA);
2973 DependingInstructions.clear();
2974 Visited.clear();
2975
2976 if (!Retain)
2977 continue;
2978
2979 // Check that there is nothing that can affect the reference count
2980 // between the retain and the call. Note that Retain need not be in BB.
2981 bool HasSafePathToCall = HasSafePathToPredecessorCall(Arg, Retain,
2982 DependingInstructions,
2983 Visited, PA);
2984 DependingInstructions.clear();
2985 Visited.clear();
2986
2987 if (!HasSafePathToCall)
2988 continue;
2989
2990 // If so, we can zap the retain and autorelease.
2991 Changed = true;
2992 ++NumRets;
2993 DEBUG(dbgs() << "Erasing: " << *Retain << "\nErasing: "
2994 << *Autorelease << "\n");
2995 EraseInstruction(Retain);
2996 EraseInstruction(Autorelease);
John McCalld935e9c2011-06-15 23:37:01 +00002997 }
2998}
2999
Michael Gottesman9c118152013-04-29 06:16:57 +00003000#ifndef NDEBUG
3001void
3002ObjCARCOpt::GatherStatistics(Function &F, bool AfterOptimization) {
3003 llvm::Statistic &NumRetains =
3004 AfterOptimization? NumRetainsAfterOpt : NumRetainsBeforeOpt;
3005 llvm::Statistic &NumReleases =
3006 AfterOptimization? NumReleasesAfterOpt : NumReleasesBeforeOpt;
3007
3008 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3009 Instruction *Inst = &*I++;
3010 switch (GetBasicInstructionClass(Inst)) {
3011 default:
3012 break;
3013 case IC_Retain:
3014 ++NumRetains;
3015 break;
3016 case IC_Release:
3017 ++NumReleases;
3018 break;
3019 }
3020 }
3021}
3022#endif
3023
John McCalld935e9c2011-06-15 23:37:01 +00003024bool ObjCARCOpt::doInitialization(Module &M) {
3025 if (!EnableARCOpts)
3026 return false;
3027
Dan Gohman670f9372012-04-13 18:57:48 +00003028 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanceaac7c2011-06-20 23:20:43 +00003029 Run = ModuleHasARC(M);
3030 if (!Run)
3031 return false;
3032
John McCalld935e9c2011-06-15 23:37:01 +00003033 // Identify the imprecise release metadata kind.
3034 ImpreciseReleaseMDKind =
3035 M.getContext().getMDKindID("clang.imprecise_release");
Dan Gohmana7107f92011-10-17 22:53:25 +00003036 CopyOnEscapeMDKind =
3037 M.getContext().getMDKindID("clang.arc.copy_on_escape");
Dan Gohman0155f302012-02-17 18:59:53 +00003038 NoObjCARCExceptionsMDKind =
3039 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
Michael Gottesman81b1d432013-03-26 00:42:04 +00003040#ifdef ARC_ANNOTATIONS
3041 ARCAnnotationBottomUpMDKind =
3042 M.getContext().getMDKindID("llvm.arc.annotation.bottomup");
3043 ARCAnnotationTopDownMDKind =
3044 M.getContext().getMDKindID("llvm.arc.annotation.topdown");
3045 ARCAnnotationProvenanceSourceMDKind =
3046 M.getContext().getMDKindID("llvm.arc.annotation.provenancesource");
3047#endif // ARC_ANNOTATIONS
John McCalld935e9c2011-06-15 23:37:01 +00003048
John McCalld935e9c2011-06-15 23:37:01 +00003049 // Intuitively, objc_retain and others are nocapture, however in practice
3050 // they are not, because they return their argument value. And objc_release
Dan Gohmandae33492012-04-27 18:56:31 +00003051 // calls finalizers which can have arbitrary side effects.
John McCalld935e9c2011-06-15 23:37:01 +00003052
Michael Gottesman14acfac2013-07-06 01:39:23 +00003053 // Initialize our runtime entry point cache.
3054 EP.Initialize(&M);
John McCalld935e9c2011-06-15 23:37:01 +00003055
3056 return false;
3057}
3058
3059bool ObjCARCOpt::runOnFunction(Function &F) {
3060 if (!EnableARCOpts)
3061 return false;
3062
Dan Gohmanceaac7c2011-06-20 23:20:43 +00003063 // If nothing in the Module uses ARC, don't do anything.
3064 if (!Run)
3065 return false;
3066
John McCalld935e9c2011-06-15 23:37:01 +00003067 Changed = false;
3068
Michael Gottesman89279f82013-04-05 18:10:41 +00003069 DEBUG(dbgs() << "<<< ObjCARCOpt: Visiting Function: " << F.getName() << " >>>"
3070 "\n");
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00003071
John McCalld935e9c2011-06-15 23:37:01 +00003072 PA.setAA(&getAnalysis<AliasAnalysis>());
3073
Michael Gottesman9fc50b82013-05-13 18:29:07 +00003074#ifndef NDEBUG
3075 if (AreStatisticsEnabled()) {
3076 GatherStatistics(F, false);
3077 }
3078#endif
3079
John McCalld935e9c2011-06-15 23:37:01 +00003080 // This pass performs several distinct transformations. As a compile-time aid
3081 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3082 // library functions aren't declared.
3083
Michael Gottesmancd5b0272013-04-24 22:18:15 +00003084 // Preliminary optimizations. This also computes UsedInThisFunction.
John McCalld935e9c2011-06-15 23:37:01 +00003085 OptimizeIndividualCalls(F);
3086
3087 // Optimizations for weak pointers.
3088 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3089 (1 << IC_LoadWeakRetained) |
3090 (1 << IC_StoreWeak) |
3091 (1 << IC_InitWeak) |
3092 (1 << IC_CopyWeak) |
3093 (1 << IC_MoveWeak) |
3094 (1 << IC_DestroyWeak)))
3095 OptimizeWeakCalls(F);
3096
3097 // Optimizations for retain+release pairs.
3098 if (UsedInThisFunction & ((1 << IC_Retain) |
3099 (1 << IC_RetainRV) |
3100 (1 << IC_RetainBlock)))
3101 if (UsedInThisFunction & (1 << IC_Release))
3102 // Run OptimizeSequences until it either stops making changes or
3103 // no retain+release pair nesting is detected.
3104 while (OptimizeSequences(F)) {}
3105
3106 // Optimizations if objc_autorelease is used.
Dan Gohman41375a32012-05-08 23:39:44 +00003107 if (UsedInThisFunction & ((1 << IC_Autorelease) |
3108 (1 << IC_AutoreleaseRV)))
John McCalld935e9c2011-06-15 23:37:01 +00003109 OptimizeReturns(F);
3110
Michael Gottesman9c118152013-04-29 06:16:57 +00003111 // Gather statistics after optimization.
3112#ifndef NDEBUG
3113 if (AreStatisticsEnabled()) {
3114 GatherStatistics(F, true);
3115 }
3116#endif
3117
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00003118 DEBUG(dbgs() << "\n");
3119
John McCalld935e9c2011-06-15 23:37:01 +00003120 return Changed;
3121}
3122
3123void ObjCARCOpt::releaseMemory() {
3124 PA.clear();
3125}
3126
Michael Gottesman97e3df02013-01-14 00:35:14 +00003127/// @}
3128///