blob: 2b3498f40ac2a62c65fd59c99d9948e35c654fae [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"
Michael Gottesman0be69202015-03-05 23:28:58 +000032#include "BlotMapVector.h"
John McCalld935e9c2011-06-15 23:37:01 +000033#include "llvm/ADT/DenseMap.h"
Michael Gottesman5a91bbf2013-05-24 20:44:02 +000034#include "llvm/ADT/DenseSet.h"
Michael Gottesmanfa0939f2013-01-28 04:12:07 +000035#include "llvm/ADT/STLExtras.h"
Michael Gottesman778138e2013-01-29 03:03:03 +000036#include "llvm/ADT/SmallPtrSet.h"
Michael Gottesman278266f2013-01-29 04:20:52 +000037#include "llvm/ADT/Statistic.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000038#include "llvm/IR/CFG.h"
Michael Gottesmancd4de0f2013-03-26 00:42:09 +000039#include "llvm/IR/IRBuilder.h"
Michael Gottesman278266f2013-01-29 04:20:52 +000040#include "llvm/IR/LLVMContext.h"
Michael Gottesman13a5f1a2013-01-29 04:51:59 +000041#include "llvm/Support/Debug.h"
Timur Iskhodzhanov5d7ff002013-01-29 09:09:27 +000042#include "llvm/Support/raw_ostream.h"
Michael Gottesmanfa0939f2013-01-28 04:12:07 +000043
John McCalld935e9c2011-06-15 23:37:01 +000044using namespace llvm;
Michael Gottesman08904e32013-01-28 03:28:38 +000045using namespace llvm::objcarc;
John McCalld935e9c2011-06-15 23:37:01 +000046
Chandler Carruth964daaa2014-04-22 02:55:47 +000047#define DEBUG_TYPE "objc-arc-opts"
48
Michael Gottesman97e3df02013-01-14 00:35:14 +000049/// \defgroup ARCUtilities Utility declarations/definitions specific to ARC.
50/// @{
John McCalld935e9c2011-06-15 23:37:01 +000051
Michael Gottesmane5ad66f2015-02-19 00:42:38 +000052/// \brief This is similar to GetRCIdentityRoot but it stops as soon
Michael Gottesman97e3df02013-01-14 00:35:14 +000053/// as it finds a value with multiple uses.
John McCalld935e9c2011-06-15 23:37:01 +000054static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
55 if (Arg->hasOneUse()) {
56 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
57 return FindSingleUseIdentifiedObject(BC->getOperand(0));
58 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
59 if (GEP->hasAllZeroIndices())
60 return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
Michael Gottesman6f729fa2015-02-19 19:51:32 +000061 if (IsForwarding(GetBasicARCInstKind(Arg)))
John McCalld935e9c2011-06-15 23:37:01 +000062 return FindSingleUseIdentifiedObject(
63 cast<CallInst>(Arg)->getArgOperand(0));
64 if (!IsObjCIdentifiedObject(Arg))
Craig Topperf40110f2014-04-25 05:29:35 +000065 return nullptr;
John McCalld935e9c2011-06-15 23:37:01 +000066 return Arg;
67 }
68
Dan Gohman41375a32012-05-08 23:39:44 +000069 // If we found an identifiable object but it has multiple uses, but they are
70 // trivial uses, we can still consider this to be a single-use value.
John McCalld935e9c2011-06-15 23:37:01 +000071 if (IsObjCIdentifiedObject(Arg)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +000072 for (const User *U : Arg->users())
Michael Gottesmane5ad66f2015-02-19 00:42:38 +000073 if (!U->use_empty() || GetRCIdentityRoot(U) != Arg)
Craig Topperf40110f2014-04-25 05:29:35 +000074 return nullptr;
John McCalld935e9c2011-06-15 23:37:01 +000075
76 return Arg;
77 }
78
Craig Topperf40110f2014-04-25 05:29:35 +000079 return nullptr;
John McCalld935e9c2011-06-15 23:37:01 +000080}
81
Michael Gottesmana76143ee2013-05-13 23:49:42 +000082/// This is a wrapper around getUnderlyingObjCPtr along the lines of
83/// GetUnderlyingObjects except that it returns early when it sees the first
84/// alloca.
85static inline bool AreAnyUnderlyingObjectsAnAlloca(const Value *V) {
86 SmallPtrSet<const Value *, 4> Visited;
87 SmallVector<const Value *, 4> Worklist;
88 Worklist.push_back(V);
89 do {
90 const Value *P = Worklist.pop_back_val();
91 P = GetUnderlyingObjCPtr(P);
Michael Gottesman0c8b5622013-05-14 06:40:10 +000092
Michael Gottesmana76143ee2013-05-13 23:49:42 +000093 if (isa<AllocaInst>(P))
94 return true;
Michael Gottesman0c8b5622013-05-14 06:40:10 +000095
David Blaikie70573dc2014-11-19 07:49:26 +000096 if (!Visited.insert(P).second)
Michael Gottesmana76143ee2013-05-13 23:49:42 +000097 continue;
Michael Gottesman0c8b5622013-05-14 06:40:10 +000098
Michael Gottesmana76143ee2013-05-13 23:49:42 +000099 if (const SelectInst *SI = dyn_cast<const SelectInst>(P)) {
100 Worklist.push_back(SI->getTrueValue());
101 Worklist.push_back(SI->getFalseValue());
102 continue;
103 }
Michael Gottesman0c8b5622013-05-14 06:40:10 +0000104
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000105 if (const PHINode *PN = dyn_cast<const PHINode>(P)) {
106 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
107 Worklist.push_back(PN->getIncomingValue(i));
108 continue;
109 }
110 } while (!Worklist.empty());
111
112 return false;
113}
114
115
Michael Gottesman97e3df02013-01-14 00:35:14 +0000116/// @}
117///
Michael Gottesman97e3df02013-01-14 00:35:14 +0000118/// \defgroup ARCOpt ARC Optimization.
119/// @{
John McCalld935e9c2011-06-15 23:37:01 +0000120
121// TODO: On code like this:
122//
123// objc_retain(%x)
124// stuff_that_cannot_release()
125// objc_autorelease(%x)
126// stuff_that_cannot_release()
127// objc_retain(%x)
128// stuff_that_cannot_release()
129// objc_autorelease(%x)
130//
131// The second retain and autorelease can be deleted.
132
133// TODO: It should be possible to delete
134// objc_autoreleasePoolPush and objc_autoreleasePoolPop
135// pairs if nothing is actually autoreleased between them. Also, autorelease
136// calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
137// after inlining) can be turned into plain release calls.
138
139// TODO: Critical-edge splitting. If the optimial insertion point is
140// a critical edge, the current algorithm has to fail, because it doesn't
141// know how to split edges. It should be possible to make the optimizer
142// think in terms of edges, rather than blocks, and then split critical
143// edges on demand.
144
145// TODO: OptimizeSequences could generalized to be Interprocedural.
146
147// TODO: Recognize that a bunch of other objc runtime calls have
148// non-escaping arguments and non-releasing arguments, and may be
149// non-autoreleasing.
150
151// TODO: Sink autorelease calls as far as possible. Unfortunately we
152// usually can't sink them past other calls, which would be the main
153// case where it would be useful.
154
Dan Gohmanb3894012011-08-19 00:26:36 +0000155// TODO: The pointer returned from objc_loadWeakRetained is retained.
156
157// TODO: Delete release+retain pairs (rare).
Dan Gohmanceaac7c2011-06-20 23:20:43 +0000158
John McCalld935e9c2011-06-15 23:37:01 +0000159STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
160STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
161STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
162STATISTIC(NumRets, "Number of return value forwarding "
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000163 "retain+autoreleases eliminated");
John McCalld935e9c2011-06-15 23:37:01 +0000164STATISTIC(NumRRs, "Number of retain+release paths eliminated");
165STATISTIC(NumPeeps, "Number of calls peephole-optimized");
Matt Beaumont-Gaye55d9492013-05-13 21:10:49 +0000166#ifndef NDEBUG
Michael Gottesman9c118152013-04-29 06:16:57 +0000167STATISTIC(NumRetainsBeforeOpt,
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000168 "Number of retains before optimization");
Michael Gottesman9c118152013-04-29 06:16:57 +0000169STATISTIC(NumReleasesBeforeOpt,
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000170 "Number of releases before optimization");
Michael Gottesman9c118152013-04-29 06:16:57 +0000171STATISTIC(NumRetainsAfterOpt,
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000172 "Number of retains after optimization");
Michael Gottesman9c118152013-04-29 06:16:57 +0000173STATISTIC(NumReleasesAfterOpt,
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000174 "Number of releases after optimization");
Michael Gottesman03cf3c82013-04-29 07:29:08 +0000175#endif
John McCalld935e9c2011-06-15 23:37:01 +0000176
177namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000178 /// \enum Sequence
179 ///
180 /// \brief A sequence of states that a pointer may go through in which an
181 /// objc_retain and objc_release are actually needed.
John McCalld935e9c2011-06-15 23:37:01 +0000182 enum Sequence {
183 S_None,
Michael Gottesman53fd20b2013-01-29 21:07:51 +0000184 S_Retain, ///< objc_retain(x).
185 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement.
186 S_Use, ///< any use of x.
Michael Gottesman386241c2013-01-29 21:39:02 +0000187 S_Stop, ///< like S_Release, but code motion is stopped.
Michael Gottesman53fd20b2013-01-29 21:07:51 +0000188 S_Release, ///< objc_release(x).
Michael Gottesman9bdab2b2013-01-29 21:41:44 +0000189 S_MovableRelease ///< objc_release(x), !clang.imprecise_release.
John McCalld935e9c2011-06-15 23:37:01 +0000190 };
Michael Gottesman53fd20b2013-01-29 21:07:51 +0000191
192 raw_ostream &operator<<(raw_ostream &OS, const Sequence S)
193 LLVM_ATTRIBUTE_UNUSED;
194 raw_ostream &operator<<(raw_ostream &OS, const Sequence S) {
195 switch (S) {
196 case S_None:
197 return OS << "S_None";
198 case S_Retain:
199 return OS << "S_Retain";
200 case S_CanRelease:
201 return OS << "S_CanRelease";
202 case S_Use:
203 return OS << "S_Use";
204 case S_Release:
205 return OS << "S_Release";
206 case S_MovableRelease:
207 return OS << "S_MovableRelease";
208 case S_Stop:
209 return OS << "S_Stop";
210 }
211 llvm_unreachable("Unknown sequence type.");
212 }
John McCalld935e9c2011-06-15 23:37:01 +0000213}
214
215static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
216 // The easy cases.
217 if (A == B)
218 return A;
219 if (A == S_None || B == S_None)
220 return S_None;
221
John McCalld935e9c2011-06-15 23:37:01 +0000222 if (A > B) std::swap(A, B);
223 if (TopDown) {
224 // Choose the side which is further along in the sequence.
Dan Gohman12130272011-08-12 00:26:31 +0000225 if ((A == S_Retain || A == S_CanRelease) &&
226 (B == S_CanRelease || B == S_Use))
John McCalld935e9c2011-06-15 23:37:01 +0000227 return B;
228 } else {
229 // Choose the side which is further along in the sequence.
230 if ((A == S_Use || A == S_CanRelease) &&
Dan Gohman12130272011-08-12 00:26:31 +0000231 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
John McCalld935e9c2011-06-15 23:37:01 +0000232 return A;
233 // If both sides are releases, choose the more conservative one.
234 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
235 return A;
236 if (A == S_Release && B == S_MovableRelease)
237 return A;
238 }
239
240 return S_None;
241}
242
243namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000244 /// \brief Unidirectional information about either a
John McCalld935e9c2011-06-15 23:37:01 +0000245 /// retain-decrement-use-release sequence or release-use-decrement-retain
Bob Wilson798a7702013-04-09 22:15:51 +0000246 /// reverse sequence.
John McCalld935e9c2011-06-15 23:37:01 +0000247 struct RRInfo {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000248 /// After an objc_retain, the reference count of the referenced
Dan Gohmanb3894012011-08-19 00:26:36 +0000249 /// object is known to be positive. Similarly, before an objc_release, the
250 /// reference count of the referenced object is known to be positive. If
251 /// there are retain-release pairs in code regions where the retain count
252 /// is known to be positive, they can be eliminated, regardless of any side
253 /// effects between them.
254 ///
255 /// Also, a retain+release pair nested within another retain+release
256 /// pair all on the known same pointer value can be eliminated, regardless
257 /// of any intervening side effects.
258 ///
259 /// KnownSafe is true when either of these conditions is satisfied.
260 bool KnownSafe;
John McCalld935e9c2011-06-15 23:37:01 +0000261
Michael Gottesman97e3df02013-01-14 00:35:14 +0000262 /// True of the objc_release calls are all marked with the "tail" keyword.
John McCalld935e9c2011-06-15 23:37:01 +0000263 bool IsTailCallRelease;
264
Michael Gottesman97e3df02013-01-14 00:35:14 +0000265 /// If the Calls are objc_release calls and they all have a
266 /// clang.imprecise_release tag, this is the metadata tag.
John McCalld935e9c2011-06-15 23:37:01 +0000267 MDNode *ReleaseMetadata;
268
Michael Gottesman97e3df02013-01-14 00:35:14 +0000269 /// For a top-down sequence, the set of objc_retains or
John McCalld935e9c2011-06-15 23:37:01 +0000270 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
271 SmallPtrSet<Instruction *, 2> Calls;
272
Michael Gottesman97e3df02013-01-14 00:35:14 +0000273 /// The set of optimal insert positions for moving calls in the opposite
274 /// sequence.
John McCalld935e9c2011-06-15 23:37:01 +0000275 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
276
Michael Gottesmane67f40c2013-05-24 20:44:05 +0000277 /// If this is true, we cannot perform code motion but can still remove
278 /// retain/release pairs.
279 bool CFGHazardAfflicted;
280
John McCalld935e9c2011-06-15 23:37:01 +0000281 RRInfo() :
Craig Topperf40110f2014-04-25 05:29:35 +0000282 KnownSafe(false), IsTailCallRelease(false), ReleaseMetadata(nullptr),
Michael Gottesmane67f40c2013-05-24 20:44:05 +0000283 CFGHazardAfflicted(false) {}
John McCalld935e9c2011-06-15 23:37:01 +0000284
285 void clear();
Michael Gottesman79249972013-04-05 23:46:45 +0000286
Michael Gottesman4773a102013-06-21 05:42:08 +0000287 /// Conservatively merge the two RRInfo. Returns true if a partial merge has
Alp Tokercb402912014-01-24 17:20:08 +0000288 /// occurred, false otherwise.
Michael Gottesman4773a102013-06-21 05:42:08 +0000289 bool Merge(const RRInfo &Other);
290
John McCalld935e9c2011-06-15 23:37:01 +0000291 };
292}
293
294void RRInfo::clear() {
Dan Gohmanb3894012011-08-19 00:26:36 +0000295 KnownSafe = false;
John McCalld935e9c2011-06-15 23:37:01 +0000296 IsTailCallRelease = false;
Craig Topperf40110f2014-04-25 05:29:35 +0000297 ReleaseMetadata = nullptr;
John McCalld935e9c2011-06-15 23:37:01 +0000298 Calls.clear();
299 ReverseInsertPts.clear();
Michael Gottesmane67f40c2013-05-24 20:44:05 +0000300 CFGHazardAfflicted = false;
John McCalld935e9c2011-06-15 23:37:01 +0000301}
302
Michael Gottesman4773a102013-06-21 05:42:08 +0000303bool RRInfo::Merge(const RRInfo &Other) {
304 // Conservatively merge the ReleaseMetadata information.
305 if (ReleaseMetadata != Other.ReleaseMetadata)
Craig Topperf40110f2014-04-25 05:29:35 +0000306 ReleaseMetadata = nullptr;
Michael Gottesman4773a102013-06-21 05:42:08 +0000307
308 // Conservatively merge the boolean state.
309 KnownSafe &= Other.KnownSafe;
310 IsTailCallRelease &= Other.IsTailCallRelease;
311 CFGHazardAfflicted |= Other.CFGHazardAfflicted;
312
313 // Merge the call sets.
314 Calls.insert(Other.Calls.begin(), Other.Calls.end());
315
316 // Merge the insert point sets. If there are any differences,
317 // that makes this a partial merge.
318 bool Partial = ReverseInsertPts.size() != Other.ReverseInsertPts.size();
Craig Topper46276792014-08-24 23:23:06 +0000319 for (Instruction *Inst : Other.ReverseInsertPts)
David Blaikie70573dc2014-11-19 07:49:26 +0000320 Partial |= ReverseInsertPts.insert(Inst).second;
Michael Gottesman4773a102013-06-21 05:42:08 +0000321 return Partial;
322}
323
John McCalld935e9c2011-06-15 23:37:01 +0000324namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000325 /// \brief This class summarizes several per-pointer runtime properties which
326 /// are propogated through the flow graph.
John McCalld935e9c2011-06-15 23:37:01 +0000327 class PtrState {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000328 /// True if the reference count is known to be incremented.
Dan Gohman62079b42012-04-25 00:50:46 +0000329 bool KnownPositiveRefCount;
330
Bob Wilson798a7702013-04-09 22:15:51 +0000331 /// True if we've seen an opportunity for partial RR elimination, such as
Michael Gottesman97e3df02013-01-14 00:35:14 +0000332 /// pushing calls into a CFG triangle or into one side of a CFG diamond.
Dan Gohman62079b42012-04-25 00:50:46 +0000333 bool Partial;
John McCalld935e9c2011-06-15 23:37:01 +0000334
Michael Gottesman97e3df02013-01-14 00:35:14 +0000335 /// The current position in the sequence.
Bill Wendling2798f1e2013-12-01 03:36:07 +0000336 unsigned char Seq : 8;
John McCalld935e9c2011-06-15 23:37:01 +0000337
Michael Gottesman97e3df02013-01-14 00:35:14 +0000338 /// Unidirectional information about the current sequence.
John McCalld935e9c2011-06-15 23:37:01 +0000339 RRInfo RRI;
340
Michael Gottesmane3943d02013-06-21 19:44:30 +0000341 public:
Dan Gohmandf476e52012-09-04 23:16:20 +0000342 PtrState() : KnownPositiveRefCount(false), Partial(false),
Dan Gohman41375a32012-05-08 23:39:44 +0000343 Seq(S_None) {}
John McCalld935e9c2011-06-15 23:37:01 +0000344
Michael Gottesman93132252013-06-21 06:59:02 +0000345
346 bool IsKnownSafe() const {
Michael Gottesman01df4502013-07-06 01:41:35 +0000347 return RRI.KnownSafe;
Michael Gottesman93132252013-06-21 06:59:02 +0000348 }
349
350 void SetKnownSafe(const bool NewValue) {
351 RRI.KnownSafe = NewValue;
352 }
353
Michael Gottesmanb82a1792013-06-21 07:00:44 +0000354 bool IsTailCallRelease() const {
355 return RRI.IsTailCallRelease;
356 }
357
358 void SetTailCallRelease(const bool NewValue) {
359 RRI.IsTailCallRelease = NewValue;
360 }
361
Michael Gottesman9799cf72013-06-21 20:52:49 +0000362 bool IsTrackingImpreciseReleases() const {
Craig Topperf40110f2014-04-25 05:29:35 +0000363 return RRI.ReleaseMetadata != nullptr;
Michael Gottesmanf0401182013-06-21 19:12:38 +0000364 }
365
Michael Gottesmanf701d3f2013-06-21 07:03:07 +0000366 const MDNode *GetReleaseMetadata() const {
367 return RRI.ReleaseMetadata;
368 }
369
370 void SetReleaseMetadata(MDNode *NewValue) {
371 RRI.ReleaseMetadata = NewValue;
372 }
373
Michael Gottesman2f294592013-06-21 19:12:36 +0000374 bool IsCFGHazardAfflicted() const {
375 return RRI.CFGHazardAfflicted;
376 }
377
378 void SetCFGHazardAfflicted(const bool NewValue) {
379 RRI.CFGHazardAfflicted = NewValue;
380 }
381
Michael Gottesman415ddd72013-02-05 19:32:18 +0000382 void SetKnownPositiveRefCount() {
Michael Gottesmanf3f9e3b2013-05-14 00:08:09 +0000383 DEBUG(dbgs() << "Setting Known Positive.\n");
Dan Gohman62079b42012-04-25 00:50:46 +0000384 KnownPositiveRefCount = true;
Dan Gohman12130272011-08-12 00:26:31 +0000385 }
386
Michael Gottesman764b1cf2013-03-23 05:46:19 +0000387 void ClearKnownPositiveRefCount() {
Michael Gottesmanf3f9e3b2013-05-14 00:08:09 +0000388 DEBUG(dbgs() << "Clearing Known Positive.\n");
Dan Gohman62079b42012-04-25 00:50:46 +0000389 KnownPositiveRefCount = false;
John McCalld935e9c2011-06-15 23:37:01 +0000390 }
391
Michael Gottesman07beea42013-03-23 05:31:01 +0000392 bool HasKnownPositiveRefCount() const {
Dan Gohman62079b42012-04-25 00:50:46 +0000393 return KnownPositiveRefCount;
John McCalld935e9c2011-06-15 23:37:01 +0000394 }
395
Michael Gottesman415ddd72013-02-05 19:32:18 +0000396 void SetSeq(Sequence NewSeq) {
Michael Gottesman89279f82013-04-05 18:10:41 +0000397 DEBUG(dbgs() << "Old: " << Seq << "; New: " << NewSeq << "\n");
Michael Gottesman79249972013-04-05 23:46:45 +0000398 Seq = NewSeq;
John McCalld935e9c2011-06-15 23:37:01 +0000399 }
400
Michael Gottesman415ddd72013-02-05 19:32:18 +0000401 Sequence GetSeq() const {
Bill Wendling2798f1e2013-12-01 03:36:07 +0000402 return static_cast<Sequence>(Seq);
John McCalld935e9c2011-06-15 23:37:01 +0000403 }
404
Michael Gottesman415ddd72013-02-05 19:32:18 +0000405 void ClearSequenceProgress() {
Dan Gohman62079b42012-04-25 00:50:46 +0000406 ResetSequenceProgress(S_None);
407 }
408
Michael Gottesman415ddd72013-02-05 19:32:18 +0000409 void ResetSequenceProgress(Sequence NewSeq) {
Michael Gottesman01338a42013-04-20 23:36:57 +0000410 DEBUG(dbgs() << "Resetting sequence progress.\n");
Michael Gottesman89279f82013-04-05 18:10:41 +0000411 SetSeq(NewSeq);
Dan Gohman62079b42012-04-25 00:50:46 +0000412 Partial = false;
John McCalld935e9c2011-06-15 23:37:01 +0000413 RRI.clear();
414 }
415
416 void Merge(const PtrState &Other, bool TopDown);
Michael Gottesman4f6ef112013-06-21 19:44:27 +0000417
418 void InsertCall(Instruction *I) {
419 RRI.Calls.insert(I);
420 }
421
422 void InsertReverseInsertPt(Instruction *I) {
423 RRI.ReverseInsertPts.insert(I);
424 }
425
426 void ClearReverseInsertPts() {
427 RRI.ReverseInsertPts.clear();
428 }
429
430 bool HasReverseInsertPts() const {
431 return !RRI.ReverseInsertPts.empty();
432 }
Michael Gottesmane3943d02013-06-21 19:44:30 +0000433
434 const RRInfo &GetRRInfo() const {
435 return RRI;
436 }
John McCalld935e9c2011-06-15 23:37:01 +0000437 };
438}
439
440void
441PtrState::Merge(const PtrState &Other, bool TopDown) {
Bill Wendlingcbcb02c2013-12-01 03:40:42 +0000442 Seq = MergeSeqs(GetSeq(), Other.GetSeq(), TopDown);
Michael Gottesmanb7deb4c2013-06-21 06:54:31 +0000443 KnownPositiveRefCount &= Other.KnownPositiveRefCount;
Michael Gottesman60f6b282013-03-29 05:13:07 +0000444
Dan Gohman1736c142011-10-17 18:48:25 +0000445 // If we're not in a sequence (anymore), drop all associated state.
John McCalld935e9c2011-06-15 23:37:01 +0000446 if (Seq == S_None) {
Dan Gohman62079b42012-04-25 00:50:46 +0000447 Partial = false;
John McCalld935e9c2011-06-15 23:37:01 +0000448 RRI.clear();
Dan Gohman62079b42012-04-25 00:50:46 +0000449 } else if (Partial || Other.Partial) {
Dan Gohman1736c142011-10-17 18:48:25 +0000450 // If we're doing a merge on a path that's previously seen a partial
451 // merge, conservatively drop the sequence, to avoid doing partial
452 // RR elimination. If the branch predicates for the two merge differ,
453 // mixing them is unsafe.
Dan Gohman62079b42012-04-25 00:50:46 +0000454 ClearSequenceProgress();
John McCalld935e9c2011-06-15 23:37:01 +0000455 } else {
Michael Gottesmanb7deb4c2013-06-21 06:54:31 +0000456 // Otherwise merge the other PtrState's RRInfo into our RRInfo. At this
457 // point, we know that currently we are not partial. Stash whether or not
458 // the merge operation caused us to undergo a partial merging of reverse
459 // insertion points.
Michael Gottesman4773a102013-06-21 05:42:08 +0000460 Partial = RRI.Merge(Other.RRI);
John McCalld935e9c2011-06-15 23:37:01 +0000461 }
462}
463
464namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000465 /// \brief Per-BasicBlock state.
John McCalld935e9c2011-06-15 23:37:01 +0000466 class BBState {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000467 /// The number of unique control paths from the entry which can reach this
468 /// block.
John McCalld935e9c2011-06-15 23:37:01 +0000469 unsigned TopDownPathCount;
470
Michael Gottesman97e3df02013-01-14 00:35:14 +0000471 /// The number of unique control paths to exits from this block.
John McCalld935e9c2011-06-15 23:37:01 +0000472 unsigned BottomUpPathCount;
473
Michael Gottesman97e3df02013-01-14 00:35:14 +0000474 /// A type for PerPtrTopDown and PerPtrBottomUp.
Michael Gottesman0be69202015-03-05 23:28:58 +0000475 typedef BlotMapVector<const Value *, PtrState> MapTy;
John McCalld935e9c2011-06-15 23:37:01 +0000476
Michael Gottesman97e3df02013-01-14 00:35:14 +0000477 /// The top-down traversal uses this to record information known about a
478 /// pointer at the bottom of each block.
John McCalld935e9c2011-06-15 23:37:01 +0000479 MapTy PerPtrTopDown;
480
Michael Gottesman97e3df02013-01-14 00:35:14 +0000481 /// The bottom-up traversal uses this to record information known about a
482 /// pointer at the top of each block.
John McCalld935e9c2011-06-15 23:37:01 +0000483 MapTy PerPtrBottomUp;
484
Michael Gottesman97e3df02013-01-14 00:35:14 +0000485 /// Effective predecessors of the current block ignoring ignorable edges and
486 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000487 SmallVector<BasicBlock *, 2> Preds;
Michael Gottesman97e3df02013-01-14 00:35:14 +0000488 /// Effective successors of the current block ignoring ignorable edges and
489 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000490 SmallVector<BasicBlock *, 2> Succs;
491
John McCalld935e9c2011-06-15 23:37:01 +0000492 public:
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000493 static const unsigned OverflowOccurredValue;
494
495 BBState() : TopDownPathCount(0), BottomUpPathCount(0) { }
John McCalld935e9c2011-06-15 23:37:01 +0000496
497 typedef MapTy::iterator ptr_iterator;
498 typedef MapTy::const_iterator ptr_const_iterator;
499
500 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
501 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
502 ptr_const_iterator top_down_ptr_begin() const {
503 return PerPtrTopDown.begin();
504 }
505 ptr_const_iterator top_down_ptr_end() const {
506 return PerPtrTopDown.end();
507 }
508
509 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
510 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
511 ptr_const_iterator bottom_up_ptr_begin() const {
512 return PerPtrBottomUp.begin();
513 }
514 ptr_const_iterator bottom_up_ptr_end() const {
515 return PerPtrBottomUp.end();
516 }
517
Michael Gottesman97e3df02013-01-14 00:35:14 +0000518 /// Mark this block as being an entry block, which has one path from the
519 /// entry by definition.
John McCalld935e9c2011-06-15 23:37:01 +0000520 void SetAsEntry() { TopDownPathCount = 1; }
521
Michael Gottesman97e3df02013-01-14 00:35:14 +0000522 /// Mark this block as being an exit block, which has one path to an exit by
523 /// definition.
John McCalld935e9c2011-06-15 23:37:01 +0000524 void SetAsExit() { BottomUpPathCount = 1; }
525
Michael Gottesman993fbf72013-05-13 19:40:39 +0000526 /// Attempt to find the PtrState object describing the top down state for
527 /// pointer Arg. Return a new initialized PtrState describing the top down
528 /// state for Arg if we do not find one.
John McCalld935e9c2011-06-15 23:37:01 +0000529 PtrState &getPtrTopDownState(const Value *Arg) {
530 return PerPtrTopDown[Arg];
531 }
532
Michael Gottesman993fbf72013-05-13 19:40:39 +0000533 /// Attempt to find the PtrState object describing the bottom up state for
534 /// pointer Arg. Return a new initialized PtrState describing the bottom up
535 /// state for Arg if we do not find one.
John McCalld935e9c2011-06-15 23:37:01 +0000536 PtrState &getPtrBottomUpState(const Value *Arg) {
537 return PerPtrBottomUp[Arg];
538 }
539
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000540 /// Attempt to find the PtrState object describing the bottom up state for
541 /// pointer Arg.
542 ptr_iterator findPtrBottomUpState(const Value *Arg) {
543 return PerPtrBottomUp.find(Arg);
544 }
545
John McCalld935e9c2011-06-15 23:37:01 +0000546 void clearBottomUpPointers() {
Evan Chenge4df6a22011-08-04 18:40:26 +0000547 PerPtrBottomUp.clear();
John McCalld935e9c2011-06-15 23:37:01 +0000548 }
549
550 void clearTopDownPointers() {
551 PerPtrTopDown.clear();
552 }
553
554 void InitFromPred(const BBState &Other);
555 void InitFromSucc(const BBState &Other);
556 void MergePred(const BBState &Other);
557 void MergeSucc(const BBState &Other);
558
Michael Gottesman9e7261c2013-06-07 06:16:49 +0000559 /// Compute the number of possible unique paths from an entry to an exit
Michael Gottesman97e3df02013-01-14 00:35:14 +0000560 /// which pass through this block. This is only valid after both the
561 /// top-down and bottom-up traversals are complete.
Michael Gottesman9e7261c2013-06-07 06:16:49 +0000562 ///
Alp Tokercb402912014-01-24 17:20:08 +0000563 /// Returns true if overflow occurred. Returns false if overflow did not
Michael Gottesman9e7261c2013-06-07 06:16:49 +0000564 /// occur.
565 bool GetAllPathCountWithOverflow(unsigned &PathCount) const {
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000566 if (TopDownPathCount == OverflowOccurredValue ||
567 BottomUpPathCount == OverflowOccurredValue)
568 return true;
Michael Gottesman9e7261c2013-06-07 06:16:49 +0000569 unsigned long long Product =
570 (unsigned long long)TopDownPathCount*BottomUpPathCount;
Alp Tokercb402912014-01-24 17:20:08 +0000571 // Overflow occurred if any of the upper bits of Product are set or if all
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000572 // the lower bits of Product are all set.
573 return (Product >> 32) ||
574 ((PathCount = Product) == OverflowOccurredValue);
John McCalld935e9c2011-06-15 23:37:01 +0000575 }
Dan Gohman12130272011-08-12 00:26:31 +0000576
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000577 // Specialized CFG utilities.
Dan Gohmandae33492012-04-27 18:56:31 +0000578 typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
Michael Gottesman0fecf982013-08-07 23:56:34 +0000579 edge_iterator pred_begin() const { return Preds.begin(); }
580 edge_iterator pred_end() const { return Preds.end(); }
581 edge_iterator succ_begin() const { return Succs.begin(); }
582 edge_iterator succ_end() const { return Succs.end(); }
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000583
584 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
585 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
586
587 bool isExit() const { return Succs.empty(); }
John McCalld935e9c2011-06-15 23:37:01 +0000588 };
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000589
590 const unsigned BBState::OverflowOccurredValue = 0xffffffff;
John McCalld935e9c2011-06-15 23:37:01 +0000591}
592
593void BBState::InitFromPred(const BBState &Other) {
594 PerPtrTopDown = Other.PerPtrTopDown;
595 TopDownPathCount = Other.TopDownPathCount;
596}
597
598void BBState::InitFromSucc(const BBState &Other) {
599 PerPtrBottomUp = Other.PerPtrBottomUp;
600 BottomUpPathCount = Other.BottomUpPathCount;
601}
602
Michael Gottesman97e3df02013-01-14 00:35:14 +0000603/// The top-down traversal uses this to merge information about predecessors to
604/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +0000605void BBState::MergePred(const BBState &Other) {
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000606 if (TopDownPathCount == OverflowOccurredValue)
607 return;
608
John McCalld935e9c2011-06-15 23:37:01 +0000609 // Other.TopDownPathCount can be 0, in which case it is either dead or a
610 // loop backedge. Loop backedges are special.
611 TopDownPathCount += Other.TopDownPathCount;
612
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000613 // In order to be consistent, we clear the top down pointers when by adding
614 // TopDownPathCount becomes OverflowOccurredValue even though "true" overflow
Alp Tokercb402912014-01-24 17:20:08 +0000615 // has not occurred.
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000616 if (TopDownPathCount == OverflowOccurredValue) {
617 clearTopDownPointers();
618 return;
619 }
620
Michael Gottesman4385edf2013-01-14 01:47:53 +0000621 // Check for overflow. If we have overflow, fall back to conservative
622 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +0000623 if (TopDownPathCount < Other.TopDownPathCount) {
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000624 TopDownPathCount = OverflowOccurredValue;
Dan Gohman7c84dad2012-09-12 20:45:17 +0000625 clearTopDownPointers();
626 return;
627 }
628
John McCalld935e9c2011-06-15 23:37:01 +0000629 // For each entry in the other set, if our set has an entry with the same key,
630 // merge the entries. Otherwise, copy the entry and merge it with an empty
631 // entry.
632 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
633 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
634 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
635 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
636 /*TopDown=*/true);
637 }
638
Dan Gohman7e315fc32011-08-11 21:06:32 +0000639 // For each entry in our set, if the other set doesn't have an entry with the
John McCalld935e9c2011-06-15 23:37:01 +0000640 // same key, force it to merge with an empty entry.
641 for (ptr_iterator MI = top_down_ptr_begin(),
642 ME = top_down_ptr_end(); MI != ME; ++MI)
643 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
644 MI->second.Merge(PtrState(), /*TopDown=*/true);
645}
646
Michael Gottesman97e3df02013-01-14 00:35:14 +0000647/// The bottom-up traversal uses this to merge information about successors to
648/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +0000649void BBState::MergeSucc(const BBState &Other) {
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000650 if (BottomUpPathCount == OverflowOccurredValue)
651 return;
652
John McCalld935e9c2011-06-15 23:37:01 +0000653 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
654 // loop backedge. Loop backedges are special.
655 BottomUpPathCount += Other.BottomUpPathCount;
656
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000657 // In order to be consistent, we clear the top down pointers when by adding
658 // BottomUpPathCount becomes OverflowOccurredValue even though "true" overflow
Alp Tokercb402912014-01-24 17:20:08 +0000659 // has not occurred.
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000660 if (BottomUpPathCount == OverflowOccurredValue) {
661 clearBottomUpPointers();
662 return;
663 }
664
Michael Gottesman4385edf2013-01-14 01:47:53 +0000665 // Check for overflow. If we have overflow, fall back to conservative
666 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +0000667 if (BottomUpPathCount < Other.BottomUpPathCount) {
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000668 BottomUpPathCount = OverflowOccurredValue;
Dan Gohman7c84dad2012-09-12 20:45:17 +0000669 clearBottomUpPointers();
670 return;
671 }
672
John McCalld935e9c2011-06-15 23:37:01 +0000673 // For each entry in the other set, if our set has an entry with the
674 // same key, merge the entries. Otherwise, copy the entry and merge
675 // it with an empty entry.
676 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
677 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
678 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
679 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
680 /*TopDown=*/false);
681 }
682
Dan Gohman7e315fc32011-08-11 21:06:32 +0000683 // For each entry in our set, if the other set doesn't have an entry
John McCalld935e9c2011-06-15 23:37:01 +0000684 // with the same key, force it to merge with an empty entry.
685 for (ptr_iterator MI = bottom_up_ptr_begin(),
686 ME = bottom_up_ptr_end(); MI != ME; ++MI)
687 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
688 MI->second.Merge(PtrState(), /*TopDown=*/false);
689}
690
Michael Gottesman81b1d432013-03-26 00:42:04 +0000691// Only enable ARC Annotations if we are building a debug version of
692// libObjCARCOpts.
693#ifndef NDEBUG
694#define ARC_ANNOTATIONS
695#endif
696
697// Define some macros along the lines of DEBUG and some helper functions to make
698// it cleaner to create annotations in the source code and to no-op when not
699// building in debug mode.
700#ifdef ARC_ANNOTATIONS
701
702#include "llvm/Support/CommandLine.h"
703
704/// Enable/disable ARC sequence annotations.
705static cl::opt<bool>
Michael Gottesman6806b512013-04-17 20:48:03 +0000706EnableARCAnnotations("enable-objc-arc-annotations", cl::init(false),
707 cl::desc("Enable emission of arc data flow analysis "
708 "annotations"));
Michael Gottesmanffef24f2013-04-17 20:48:01 +0000709static cl::opt<bool>
Michael Gottesmanadb921a2013-04-17 21:03:53 +0000710DisableCheckForCFGHazards("disable-objc-arc-checkforcfghazards", cl::init(false),
711 cl::desc("Disable check for cfg hazards when "
712 "annotating"));
Michael Gottesman4e88ce62013-04-17 21:59:41 +0000713static cl::opt<std::string>
714ARCAnnotationTargetIdentifier("objc-arc-annotation-target-identifier",
715 cl::init(""),
716 cl::desc("filter out all data flow annotations "
717 "but those that apply to the given "
718 "target llvm identifier."));
Michael Gottesman81b1d432013-03-26 00:42:04 +0000719
720/// This function appends a unique ARCAnnotationProvenanceSourceMDKind id to an
721/// instruction so that we can track backwards when post processing via the llvm
722/// arc annotation processor tool. If the function is an
723static MDString *AppendMDNodeToSourcePtr(unsigned NodeId,
724 Value *Ptr) {
Craig Toppere73658d2014-04-28 04:05:08 +0000725 MDString *Hash = nullptr;
Michael Gottesman81b1d432013-03-26 00:42:04 +0000726
727 // If pointer is a result of an instruction and it does not have a source
728 // MDNode it, attach a new MDNode onto it. If pointer is a result of
729 // an instruction and does have a source MDNode attached to it, return a
730 // reference to said Node. Otherwise just return 0.
731 if (Instruction *Inst = dyn_cast<Instruction>(Ptr)) {
732 MDNode *Node;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000733 if (!(Node = Inst->getMetadata(NodeId))) {
Michael Gottesman81b1d432013-03-26 00:42:04 +0000734 // We do not have any node. Generate and attatch the hash MDString to the
735 // instruction.
736
737 // We just use an MDString to ensure that this metadata gets written out
738 // of line at the module level and to provide a very simple format
739 // encoding the information herein. Both of these makes it simpler to
740 // parse the annotations by a simple external program.
Alp Tokere69170a2014-06-26 22:52:05 +0000741 std::string Str;
742 raw_string_ostream os(Str);
Michael Gottesman81b1d432013-03-26 00:42:04 +0000743 os << "(" << Inst->getParent()->getParent()->getName() << ",%"
744 << Inst->getName() << ")";
745
746 Hash = MDString::get(Inst->getContext(), os.str());
747 Inst->setMetadata(NodeId, MDNode::get(Inst->getContext(),Hash));
748 } else {
749 // We have a node. Grab its hash and return it.
750 assert(Node->getNumOperands() == 1 &&
751 "An ARCAnnotationProvenanceSourceMDKind can only have 1 operand.");
752 Hash = cast<MDString>(Node->getOperand(0));
753 }
754 } else if (Argument *Arg = dyn_cast<Argument>(Ptr)) {
Alp Tokere69170a2014-06-26 22:52:05 +0000755 std::string str;
756 raw_string_ostream os(str);
Michael Gottesman81b1d432013-03-26 00:42:04 +0000757 os << "(" << Arg->getParent()->getName() << ",%" << Arg->getName()
758 << ")";
759 Hash = MDString::get(Arg->getContext(), os.str());
760 }
761
762 return Hash;
763}
764
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000765static std::string SequenceToString(Sequence A) {
Alp Tokere69170a2014-06-26 22:52:05 +0000766 std::string str;
767 raw_string_ostream os(str);
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000768 os << A;
769 return os.str();
770}
771
Michael Gottesman81b1d432013-03-26 00:42:04 +0000772/// Helper function to change a Sequence into a String object using our overload
773/// for raw_ostream so we only have printing code in one location.
774static MDString *SequenceToMDString(LLVMContext &Context,
775 Sequence A) {
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000776 return MDString::get(Context, SequenceToString(A));
Michael Gottesman81b1d432013-03-26 00:42:04 +0000777}
778
779/// A simple function to generate a MDNode which describes the change in state
780/// for Value *Ptr caused by Instruction *Inst.
781static void AppendMDNodeToInstForPtr(unsigned NodeId,
782 Instruction *Inst,
783 Value *Ptr,
784 MDString *PtrSourceMDNodeID,
785 Sequence OldSeq,
786 Sequence NewSeq) {
Craig Toppere73658d2014-04-28 04:05:08 +0000787 MDNode *Node = nullptr;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000788 Metadata *tmp[3] = {PtrSourceMDNodeID,
789 SequenceToMDString(Inst->getContext(), OldSeq),
790 SequenceToMDString(Inst->getContext(), NewSeq)};
Craig Toppere1d12942014-08-27 05:25:25 +0000791 Node = MDNode::get(Inst->getContext(), tmp);
Michael Gottesman81b1d432013-03-26 00:42:04 +0000792
793 Inst->setMetadata(NodeId, Node);
794}
795
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000796/// Add to the beginning of the basic block llvm.ptr.annotations which show the
797/// state of a pointer at the entrance to a basic block.
798static void GenerateARCBBEntranceAnnotation(const char *Name, BasicBlock *BB,
799 Value *Ptr, Sequence Seq) {
Michael Gottesman4e88ce62013-04-17 21:59:41 +0000800 // If we have a target identifier, make sure that we match it before
801 // continuing.
802 if(!ARCAnnotationTargetIdentifier.empty() &&
803 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
804 return;
Michael Gottesman9e518132013-04-18 04:34:11 +0000805
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000806 Module *M = BB->getParent()->getParent();
807 LLVMContext &C = M->getContext();
808 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
809 Type *I8XX = PointerType::getUnqual(I8X);
810 Type *Params[] = {I8XX, I8XX};
Craig Toppere1d12942014-08-27 05:25:25 +0000811 FunctionType *FTy = FunctionType::get(Type::getVoidTy(C), Params,
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000812 /*isVarArg=*/false);
813 Constant *Callee = M->getOrInsertFunction(Name, FTy);
Michael Gottesman60f6b282013-03-29 05:13:07 +0000814
815 IRBuilder<> Builder(BB, BB->getFirstInsertionPt());
816
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000817 Value *PtrName;
818 StringRef Tmp = Ptr->getName();
Craig Toppere73658d2014-04-28 04:05:08 +0000819 if (nullptr == (PtrName = M->getGlobalVariable(Tmp, true))) {
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000820 Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
821 Tmp + "_STR");
822 PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
Michael Gottesman60f6b282013-03-29 05:13:07 +0000823 cast<Constant>(ActualPtrName), Tmp);
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000824 }
825
826 Value *S;
827 std::string SeqStr = SequenceToString(Seq);
Craig Toppere73658d2014-04-28 04:05:08 +0000828 if (nullptr == (S = M->getGlobalVariable(SeqStr, true))) {
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000829 Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
830 SeqStr + "_STR");
831 S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
832 cast<Constant>(ActualPtrName), SeqStr);
833 }
834
835 Builder.CreateCall2(Callee, PtrName, S);
836}
837
838/// Add to the end of the basic block llvm.ptr.annotations which show the state
839/// of the pointer at the bottom of the basic block.
840static void GenerateARCBBTerminatorAnnotation(const char *Name, BasicBlock *BB,
841 Value *Ptr, Sequence Seq) {
Michael Gottesman4e88ce62013-04-17 21:59:41 +0000842 // If we have a target identifier, make sure that we match it before emitting
843 // an annotation.
844 if(!ARCAnnotationTargetIdentifier.empty() &&
845 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
846 return;
Michael Gottesman9e518132013-04-18 04:34:11 +0000847
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000848 Module *M = BB->getParent()->getParent();
849 LLVMContext &C = M->getContext();
850 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
851 Type *I8XX = PointerType::getUnqual(I8X);
852 Type *Params[] = {I8XX, I8XX};
Craig Toppere1d12942014-08-27 05:25:25 +0000853 FunctionType *FTy = FunctionType::get(Type::getVoidTy(C), Params,
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000854 /*isVarArg=*/false);
855 Constant *Callee = M->getOrInsertFunction(Name, FTy);
Michael Gottesman60f6b282013-03-29 05:13:07 +0000856
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000857 IRBuilder<> Builder(BB, std::prev(BB->end()));
Michael Gottesman60f6b282013-03-29 05:13:07 +0000858
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000859 Value *PtrName;
860 StringRef Tmp = Ptr->getName();
Craig Toppere73658d2014-04-28 04:05:08 +0000861 if (nullptr == (PtrName = M->getGlobalVariable(Tmp, true))) {
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000862 Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
863 Tmp + "_STR");
864 PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
Michael Gottesman60f6b282013-03-29 05:13:07 +0000865 cast<Constant>(ActualPtrName), Tmp);
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000866 }
867
868 Value *S;
869 std::string SeqStr = SequenceToString(Seq);
Craig Toppere73658d2014-04-28 04:05:08 +0000870 if (nullptr == (S = M->getGlobalVariable(SeqStr, true))) {
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000871 Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
872 SeqStr + "_STR");
873 S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
874 cast<Constant>(ActualPtrName), SeqStr);
875 }
Michael Gottesman60f6b282013-03-29 05:13:07 +0000876 Builder.CreateCall2(Callee, PtrName, S);
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000877}
878
Michael Gottesman81b1d432013-03-26 00:42:04 +0000879/// Adds a source annotation to pointer and a state change annotation to Inst
880/// referencing the source annotation and the old/new state of pointer.
881static void GenerateARCAnnotation(unsigned InstMDId,
882 unsigned PtrMDId,
883 Instruction *Inst,
884 Value *Ptr,
885 Sequence OldSeq,
886 Sequence NewSeq) {
887 if (EnableARCAnnotations) {
Michael Gottesman4e88ce62013-04-17 21:59:41 +0000888 // If we have a target identifier, make sure that we match it before
889 // emitting an annotation.
890 if(!ARCAnnotationTargetIdentifier.empty() &&
891 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
892 return;
Michael Gottesman9e518132013-04-18 04:34:11 +0000893
Michael Gottesman81b1d432013-03-26 00:42:04 +0000894 // First generate the source annotation on our pointer. This will return an
895 // MDString* if Ptr actually comes from an instruction implying we can put
896 // in a source annotation. If AppendMDNodeToSourcePtr returns 0 (i.e. NULL),
897 // then we know that our pointer is from an Argument so we put a reference
898 // to the argument number.
899 //
900 // The point of this is to make it easy for the
901 // llvm-arc-annotation-processor tool to cross reference where the source
902 // pointer is in the LLVM IR since the LLVM IR parser does not submit such
903 // information via debug info for backends to use (since why would anyone
Alp Tokerf907b892013-12-05 05:44:44 +0000904 // need such a thing from LLVM IR besides in non-standard cases
Michael Gottesman81b1d432013-03-26 00:42:04 +0000905 // [i.e. this]).
906 MDString *SourcePtrMDNode =
907 AppendMDNodeToSourcePtr(PtrMDId, Ptr);
908 AppendMDNodeToInstForPtr(InstMDId, Inst, Ptr, SourcePtrMDNode, OldSeq,
909 NewSeq);
910 }
911}
912
913// The actual interface for accessing the above functionality is defined via
914// some simple macros which are defined below. We do this so that the user does
915// not need to pass in what metadata id is needed resulting in cleaner code and
916// additionally since it provides an easy way to conditionally no-op all
917// annotation support in a non-debug build.
918
919/// Use this macro to annotate a sequence state change when processing
920/// instructions bottom up,
921#define ANNOTATE_BOTTOMUP(inst, ptr, old, new) \
922 GenerateARCAnnotation(ARCAnnotationBottomUpMDKind, \
923 ARCAnnotationProvenanceSourceMDKind, (inst), \
924 const_cast<Value*>(ptr), (old), (new))
925/// Use this macro to annotate a sequence state change when processing
926/// instructions top down.
927#define ANNOTATE_TOPDOWN(inst, ptr, old, new) \
928 GenerateARCAnnotation(ARCAnnotationTopDownMDKind, \
929 ARCAnnotationProvenanceSourceMDKind, (inst), \
930 const_cast<Value*>(ptr), (old), (new))
931
Michael Gottesman43e7e002013-04-03 22:41:59 +0000932#define ANNOTATE_BB(_states, _bb, _name, _type, _direction) \
933 do { \
Michael Gottesman89279f82013-04-05 18:10:41 +0000934 if (EnableARCAnnotations) { \
935 for(BBState::ptr_const_iterator I = (_states)._direction##_ptr_begin(), \
Michael Gottesman43e7e002013-04-03 22:41:59 +0000936 E = (_states)._direction##_ptr_end(); I != E; ++I) { \
Michael Gottesman89279f82013-04-05 18:10:41 +0000937 Value *Ptr = const_cast<Value*>(I->first); \
938 Sequence Seq = I->second.GetSeq(); \
939 GenerateARCBB ## _type ## Annotation(_name, (_bb), Ptr, Seq); \
940 } \
Michael Gottesman43e7e002013-04-03 22:41:59 +0000941 } \
Michael Gottesman89279f82013-04-05 18:10:41 +0000942 } while (0)
Michael Gottesman43e7e002013-04-03 22:41:59 +0000943
Michael Gottesman89279f82013-04-05 18:10:41 +0000944#define ANNOTATE_BOTTOMUP_BBSTART(_states, _basicblock) \
Michael Gottesman43e7e002013-04-03 22:41:59 +0000945 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbstart", \
946 Entrance, bottom_up)
Michael Gottesman89279f82013-04-05 18:10:41 +0000947#define ANNOTATE_BOTTOMUP_BBEND(_states, _basicblock) \
948 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbend", \
Michael Gottesman43e7e002013-04-03 22:41:59 +0000949 Terminator, bottom_up)
Michael Gottesman89279f82013-04-05 18:10:41 +0000950#define ANNOTATE_TOPDOWN_BBSTART(_states, _basicblock) \
951 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbstart", \
Michael Gottesman43e7e002013-04-03 22:41:59 +0000952 Entrance, top_down)
Michael Gottesman89279f82013-04-05 18:10:41 +0000953#define ANNOTATE_TOPDOWN_BBEND(_states, _basicblock) \
954 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbend", \
Michael Gottesman43e7e002013-04-03 22:41:59 +0000955 Terminator, top_down)
956
Michael Gottesman81b1d432013-03-26 00:42:04 +0000957#else // !ARC_ANNOTATION
958// If annotations are off, noop.
959#define ANNOTATE_BOTTOMUP(inst, ptr, old, new)
960#define ANNOTATE_TOPDOWN(inst, ptr, old, new)
Michael Gottesman43e7e002013-04-03 22:41:59 +0000961#define ANNOTATE_BOTTOMUP_BBSTART(states, basicblock)
962#define ANNOTATE_BOTTOMUP_BBEND(states, basicblock)
963#define ANNOTATE_TOPDOWN_BBSTART(states, basicblock)
964#define ANNOTATE_TOPDOWN_BBEND(states, basicblock)
Michael Gottesman81b1d432013-03-26 00:42:04 +0000965#endif // !ARC_ANNOTATION
966
John McCalld935e9c2011-06-15 23:37:01 +0000967namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000968 /// \brief The main ARC optimization pass.
John McCalld935e9c2011-06-15 23:37:01 +0000969 class ObjCARCOpt : public FunctionPass {
970 bool Changed;
971 ProvenanceAnalysis PA;
Michael Gottesman14acfac2013-07-06 01:39:23 +0000972 ARCRuntimeEntryPoints EP;
John McCalld935e9c2011-06-15 23:37:01 +0000973
Michael Gottesman5a91bbf2013-05-24 20:44:02 +0000974 // This is used to track if a pointer is stored into an alloca.
975 DenseSet<const Value *> MultiOwnersSet;
976
Michael Gottesman97e3df02013-01-14 00:35:14 +0000977 /// A flag indicating whether this optimization pass should run.
Dan Gohmanceaac7c2011-06-20 23:20:43 +0000978 bool Run;
979
Michael Gottesman97e3df02013-01-14 00:35:14 +0000980 /// Flags which determine whether each of the interesting runtine functions
981 /// is in fact used in the current function.
John McCalld935e9c2011-06-15 23:37:01 +0000982 unsigned UsedInThisFunction;
983
Michael Gottesman97e3df02013-01-14 00:35:14 +0000984 /// The Metadata Kind for clang.imprecise_release metadata.
John McCalld935e9c2011-06-15 23:37:01 +0000985 unsigned ImpreciseReleaseMDKind;
986
Michael Gottesman97e3df02013-01-14 00:35:14 +0000987 /// The Metadata Kind for clang.arc.copy_on_escape metadata.
Dan Gohmana7107f92011-10-17 22:53:25 +0000988 unsigned CopyOnEscapeMDKind;
989
Michael Gottesman97e3df02013-01-14 00:35:14 +0000990 /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata.
Dan Gohman0155f302012-02-17 18:59:53 +0000991 unsigned NoObjCARCExceptionsMDKind;
992
Michael Gottesman81b1d432013-03-26 00:42:04 +0000993#ifdef ARC_ANNOTATIONS
994 /// The Metadata Kind for llvm.arc.annotation.bottomup metadata.
995 unsigned ARCAnnotationBottomUpMDKind;
996 /// The Metadata Kind for llvm.arc.annotation.topdown metadata.
997 unsigned ARCAnnotationTopDownMDKind;
998 /// The Metadata Kind for llvm.arc.annotation.provenancesource metadata.
999 unsigned ARCAnnotationProvenanceSourceMDKind;
1000#endif // ARC_ANNOATIONS
1001
John McCalld935e9c2011-06-15 23:37:01 +00001002 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
Michael Gottesman556ff612013-01-12 01:25:19 +00001003 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001004 ARCInstKind &Class);
John McCalld935e9c2011-06-15 23:37:01 +00001005 void OptimizeIndividualCalls(Function &F);
1006
1007 void CheckForCFGHazards(const BasicBlock *BB,
1008 DenseMap<const BasicBlock *, BBState> &BBStates,
1009 BBState &MyStates) const;
Michael Gottesman0be69202015-03-05 23:28:58 +00001010 bool VisitInstructionBottomUp(Instruction *Inst, BasicBlock *BB,
1011 BlotMapVector<Value *, RRInfo> &Retains,
Dan Gohman817a7c62012-03-22 18:24:56 +00001012 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00001013 bool VisitBottomUp(BasicBlock *BB,
1014 DenseMap<const BasicBlock *, BBState> &BBStates,
Michael Gottesman0be69202015-03-05 23:28:58 +00001015 BlotMapVector<Value *, RRInfo> &Retains);
Dan Gohman817a7c62012-03-22 18:24:56 +00001016 bool VisitInstructionTopDown(Instruction *Inst,
1017 DenseMap<Value *, RRInfo> &Releases,
1018 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00001019 bool VisitTopDown(BasicBlock *BB,
1020 DenseMap<const BasicBlock *, BBState> &BBStates,
1021 DenseMap<Value *, RRInfo> &Releases);
Michael Gottesman0be69202015-03-05 23:28:58 +00001022 bool Visit(Function &F, DenseMap<const BasicBlock *, BBState> &BBStates,
1023 BlotMapVector<Value *, RRInfo> &Retains,
John McCalld935e9c2011-06-15 23:37:01 +00001024 DenseMap<Value *, RRInfo> &Releases);
1025
1026 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
Michael Gottesman0be69202015-03-05 23:28:58 +00001027 BlotMapVector<Value *, RRInfo> &Retains,
John McCalld935e9c2011-06-15 23:37:01 +00001028 DenseMap<Value *, RRInfo> &Releases,
Michael Gottesman0be69202015-03-05 23:28:58 +00001029 SmallVectorImpl<Instruction *> &DeadInsts, Module *M);
John McCalld935e9c2011-06-15 23:37:01 +00001030
Michael Gottesman9de6f962013-01-22 21:49:00 +00001031 bool ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState> &BBStates,
Michael Gottesman0be69202015-03-05 23:28:58 +00001032 BlotMapVector<Value *, RRInfo> &Retains,
1033 DenseMap<Value *, RRInfo> &Releases, Module *M,
Craig Topperb94011f2013-07-14 04:42:23 +00001034 SmallVectorImpl<Instruction *> &NewRetains,
1035 SmallVectorImpl<Instruction *> &NewReleases,
1036 SmallVectorImpl<Instruction *> &DeadInsts,
Michael Gottesman0be69202015-03-05 23:28:58 +00001037 RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1038 Value *Arg, bool KnownSafe,
Michael Gottesman9de6f962013-01-22 21:49:00 +00001039 bool &AnyPairsCompletelyEliminated);
1040
John McCalld935e9c2011-06-15 23:37:01 +00001041 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
Michael Gottesman0be69202015-03-05 23:28:58 +00001042 BlotMapVector<Value *, RRInfo> &Retains,
1043 DenseMap<Value *, RRInfo> &Releases, Module *M);
John McCalld935e9c2011-06-15 23:37:01 +00001044
1045 void OptimizeWeakCalls(Function &F);
1046
1047 bool OptimizeSequences(Function &F);
1048
1049 void OptimizeReturns(Function &F);
1050
Michael Gottesman9c118152013-04-29 06:16:57 +00001051#ifndef NDEBUG
1052 void GatherStatistics(Function &F, bool AfterOptimization = false);
1053#endif
1054
Craig Topper3e4c6972014-03-05 09:10:37 +00001055 void getAnalysisUsage(AnalysisUsage &AU) const override;
1056 bool doInitialization(Module &M) override;
1057 bool runOnFunction(Function &F) override;
1058 void releaseMemory() override;
John McCalld935e9c2011-06-15 23:37:01 +00001059
1060 public:
1061 static char ID;
1062 ObjCARCOpt() : FunctionPass(ID) {
1063 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1064 }
1065 };
1066}
1067
1068char ObjCARCOpt::ID = 0;
1069INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1070 "objc-arc", "ObjC ARC optimization", false, false)
1071INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1072INITIALIZE_PASS_END(ObjCARCOpt,
1073 "objc-arc", "ObjC ARC optimization", false, false)
1074
1075Pass *llvm::createObjCARCOptPass() {
1076 return new ObjCARCOpt();
1077}
1078
1079void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1080 AU.addRequired<ObjCARCAliasAnalysis>();
1081 AU.addRequired<AliasAnalysis>();
1082 // ARC optimization doesn't currently split critical edges.
1083 AU.setPreservesCFG();
1084}
1085
Michael Gottesman97e3df02013-01-14 00:35:14 +00001086/// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is
1087/// not a return value. Or, if it can be paired with an
1088/// objc_autoreleaseReturnValue, delete the pair and return true.
John McCalld935e9c2011-06-15 23:37:01 +00001089bool
1090ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001091 // Check for the argument being from an immediately preceding call or invoke.
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001092 const Value *Arg = GetArgRCIdentityRoot(RetainRV);
Dan Gohmandae33492012-04-27 18:56:31 +00001093 ImmutableCallSite CS(Arg);
1094 if (const Instruction *Call = CS.getInstruction()) {
John McCalld935e9c2011-06-15 23:37:01 +00001095 if (Call->getParent() == RetainRV->getParent()) {
Dan Gohmandae33492012-04-27 18:56:31 +00001096 BasicBlock::const_iterator I = Call;
John McCalld935e9c2011-06-15 23:37:01 +00001097 ++I;
Michael Gottesman65c24812013-03-25 09:27:43 +00001098 while (IsNoopInstruction(I)) ++I;
John McCalld935e9c2011-06-15 23:37:01 +00001099 if (&*I == RetainRV)
1100 return false;
Dan Gohmandae33492012-04-27 18:56:31 +00001101 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001102 BasicBlock *RetainRVParent = RetainRV->getParent();
1103 if (II->getNormalDest() == RetainRVParent) {
Dan Gohmandae33492012-04-27 18:56:31 +00001104 BasicBlock::const_iterator I = RetainRVParent->begin();
Michael Gottesman65c24812013-03-25 09:27:43 +00001105 while (IsNoopInstruction(I)) ++I;
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001106 if (&*I == RetainRV)
1107 return false;
1108 }
John McCalld935e9c2011-06-15 23:37:01 +00001109 }
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001110 }
John McCalld935e9c2011-06-15 23:37:01 +00001111
1112 // Check for being preceded by an objc_autoreleaseReturnValue on the same
1113 // pointer. In this case, we can delete the pair.
1114 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
1115 if (I != Begin) {
Michael Gottesman65c24812013-03-25 09:27:43 +00001116 do --I; while (I != Begin && IsNoopInstruction(I));
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001117 if (GetBasicARCInstKind(I) == ARCInstKind::AutoreleaseRV &&
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001118 GetArgRCIdentityRoot(I) == Arg) {
John McCalld935e9c2011-06-15 23:37:01 +00001119 Changed = true;
1120 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00001121
Michael Gottesman89279f82013-04-05 18:10:41 +00001122 DEBUG(dbgs() << "Erasing autoreleaseRV,retainRV pair: " << *I << "\n"
1123 << "Erasing " << *RetainRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001124
John McCalld935e9c2011-06-15 23:37:01 +00001125 EraseInstruction(I);
1126 EraseInstruction(RetainRV);
1127 return true;
1128 }
1129 }
1130
1131 // Turn it to a plain objc_retain.
1132 Changed = true;
1133 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00001134
Michael Gottesman89279f82013-04-05 18:10:41 +00001135 DEBUG(dbgs() << "Transforming objc_retainAutoreleasedReturnValue => "
Michael Gottesmandef07bb2013-01-05 17:55:42 +00001136 "objc_retain since the operand is not a return value.\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00001137 "Old = " << *RetainRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001138
Michael Gottesman14acfac2013-07-06 01:39:23 +00001139 Constant *NewDecl = EP.get(ARCRuntimeEntryPoints::EPT_Retain);
1140 cast<CallInst>(RetainRV)->setCalledFunction(NewDecl);
Michael Gottesmandef07bb2013-01-05 17:55:42 +00001141
Michael Gottesman89279f82013-04-05 18:10:41 +00001142 DEBUG(dbgs() << "New = " << *RetainRV << "\n");
Michael Gottesmandef07bb2013-01-05 17:55:42 +00001143
John McCalld935e9c2011-06-15 23:37:01 +00001144 return false;
1145}
1146
Michael Gottesman97e3df02013-01-14 00:35:14 +00001147/// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not
1148/// used as a return value.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001149void ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F,
1150 Instruction *AutoreleaseRV,
1151 ARCInstKind &Class) {
John McCalld935e9c2011-06-15 23:37:01 +00001152 // Check for a return of the pointer value.
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001153 const Value *Ptr = GetArgRCIdentityRoot(AutoreleaseRV);
Dan Gohman10a18d52011-08-12 00:36:31 +00001154 SmallVector<const Value *, 2> Users;
1155 Users.push_back(Ptr);
1156 do {
1157 Ptr = Users.pop_back_val();
Chandler Carruthcdf47882014-03-09 03:16:01 +00001158 for (const User *U : Ptr->users()) {
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001159 if (isa<ReturnInst>(U) || GetBasicARCInstKind(U) == ARCInstKind::RetainRV)
Dan Gohman10a18d52011-08-12 00:36:31 +00001160 return;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001161 if (isa<BitCastInst>(U))
1162 Users.push_back(U);
Dan Gohman10a18d52011-08-12 00:36:31 +00001163 }
1164 } while (!Users.empty());
John McCalld935e9c2011-06-15 23:37:01 +00001165
1166 Changed = true;
1167 ++NumPeeps;
Michael Gottesman1bf69082013-01-06 21:07:11 +00001168
Michael Gottesman89279f82013-04-05 18:10:41 +00001169 DEBUG(dbgs() << "Transforming objc_autoreleaseReturnValue => "
Michael Gottesman1bf69082013-01-06 21:07:11 +00001170 "objc_autorelease since its operand is not used as a return "
1171 "value.\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00001172 "Old = " << *AutoreleaseRV << "\n");
Michael Gottesman1bf69082013-01-06 21:07:11 +00001173
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001174 CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
Michael Gottesman14acfac2013-07-06 01:39:23 +00001175 Constant *NewDecl = EP.get(ARCRuntimeEntryPoints::EPT_Autorelease);
1176 AutoreleaseRVCI->setCalledFunction(NewDecl);
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001177 AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001178 Class = ARCInstKind::Autorelease;
Michael Gottesman10426b52013-01-07 21:26:07 +00001179
Michael Gottesman89279f82013-04-05 18:10:41 +00001180 DEBUG(dbgs() << "New: " << *AutoreleaseRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001181
John McCalld935e9c2011-06-15 23:37:01 +00001182}
1183
Michael Gottesman97e3df02013-01-14 00:35:14 +00001184/// Visit each call, one at a time, and make simplifications without doing any
1185/// additional analysis.
John McCalld935e9c2011-06-15 23:37:01 +00001186void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001187 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeIndividualCalls ==\n");
John McCalld935e9c2011-06-15 23:37:01 +00001188 // Reset all the flags in preparation for recomputing them.
1189 UsedInThisFunction = 0;
1190
1191 // Visit all objc_* calls in F.
1192 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
1193 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +00001194
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001195 ARCInstKind Class = GetBasicARCInstKind(Inst);
John McCalld935e9c2011-06-15 23:37:01 +00001196
Michael Gottesman89279f82013-04-05 18:10:41 +00001197 DEBUG(dbgs() << "Visiting: Class: " << Class << "; " << *Inst << "\n");
Michael Gottesman782e3442013-01-17 18:32:34 +00001198
John McCalld935e9c2011-06-15 23:37:01 +00001199 switch (Class) {
1200 default: break;
1201
1202 // Delete no-op casts. These function calls have special semantics, but
1203 // the semantics are entirely implemented via lowering in the front-end,
1204 // so by the time they reach the optimizer, they are just no-op calls
1205 // which return their argument.
1206 //
1207 // There are gray areas here, as the ability to cast reference-counted
1208 // pointers to raw void* and back allows code to break ARC assumptions,
1209 // however these are currently considered to be unimportant.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001210 case ARCInstKind::NoopCast:
John McCalld935e9c2011-06-15 23:37:01 +00001211 Changed = true;
1212 ++NumNoops;
Michael Gottesman89279f82013-04-05 18:10:41 +00001213 DEBUG(dbgs() << "Erasing no-op cast: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001214 EraseInstruction(Inst);
1215 continue;
1216
1217 // If the pointer-to-weak-pointer is null, it's undefined behavior.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001218 case ARCInstKind::StoreWeak:
1219 case ARCInstKind::LoadWeak:
1220 case ARCInstKind::LoadWeakRetained:
1221 case ARCInstKind::InitWeak:
1222 case ARCInstKind::DestroyWeak: {
John McCalld935e9c2011-06-15 23:37:01 +00001223 CallInst *CI = cast<CallInst>(Inst);
Michael Gottesman65c24812013-03-25 09:27:43 +00001224 if (IsNullOrUndef(CI->getArgOperand(0))) {
Dan Gohman670f9372012-04-13 18:57:48 +00001225 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +00001226 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001227 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1228 Constant::getNullValue(Ty),
1229 CI);
Michael Gottesman10426b52013-01-07 21:26:07 +00001230 llvm::Value *NewValue = UndefValue::get(CI->getType());
Michael Gottesman89279f82013-04-05 18:10:41 +00001231 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
1232 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001233 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +00001234 CI->eraseFromParent();
1235 continue;
1236 }
1237 break;
1238 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001239 case ARCInstKind::CopyWeak:
1240 case ARCInstKind::MoveWeak: {
John McCalld935e9c2011-06-15 23:37:01 +00001241 CallInst *CI = cast<CallInst>(Inst);
Michael Gottesman65c24812013-03-25 09:27:43 +00001242 if (IsNullOrUndef(CI->getArgOperand(0)) ||
1243 IsNullOrUndef(CI->getArgOperand(1))) {
Dan Gohman670f9372012-04-13 18:57:48 +00001244 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +00001245 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001246 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1247 Constant::getNullValue(Ty),
1248 CI);
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001249
1250 llvm::Value *NewValue = UndefValue::get(CI->getType());
Michael Gottesman89279f82013-04-05 18:10:41 +00001251 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
1252 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001253
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001254 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +00001255 CI->eraseFromParent();
1256 continue;
1257 }
1258 break;
1259 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001260 case ARCInstKind::RetainRV:
John McCalld935e9c2011-06-15 23:37:01 +00001261 if (OptimizeRetainRVCall(F, Inst))
1262 continue;
1263 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001264 case ARCInstKind::AutoreleaseRV:
Michael Gottesman556ff612013-01-12 01:25:19 +00001265 OptimizeAutoreleaseRVCall(F, Inst, Class);
John McCalld935e9c2011-06-15 23:37:01 +00001266 break;
1267 }
1268
Michael Gottesmanb8c88362013-04-03 02:57:24 +00001269 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
John McCalld935e9c2011-06-15 23:37:01 +00001270 if (IsAutorelease(Class) && Inst->use_empty()) {
1271 CallInst *Call = cast<CallInst>(Inst);
1272 const Value *Arg = Call->getArgOperand(0);
1273 Arg = FindSingleUseIdentifiedObject(Arg);
1274 if (Arg) {
1275 Changed = true;
1276 ++NumAutoreleases;
1277
1278 // Create the declaration lazily.
1279 LLVMContext &C = Inst->getContext();
Michael Gottesman01df4502013-07-06 01:41:35 +00001280
Michael Gottesman14acfac2013-07-06 01:39:23 +00001281 Constant *Decl = EP.get(ARCRuntimeEntryPoints::EPT_Release);
1282 CallInst *NewCall = CallInst::Create(Decl, Call->getArgOperand(0), "",
1283 Call);
Dmitri Gribenko3238fb72013-05-05 00:40:33 +00001284 NewCall->setMetadata(ImpreciseReleaseMDKind, MDNode::get(C, None));
Michael Gottesman10426b52013-01-07 21:26:07 +00001285
Michael Gottesman89279f82013-04-05 18:10:41 +00001286 DEBUG(dbgs() << "Replacing autorelease{,RV}(x) with objc_release(x) "
1287 "since x is otherwise unused.\nOld: " << *Call << "\nNew: "
1288 << *NewCall << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001289
John McCalld935e9c2011-06-15 23:37:01 +00001290 EraseInstruction(Call);
1291 Inst = NewCall;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001292 Class = ARCInstKind::Release;
John McCalld935e9c2011-06-15 23:37:01 +00001293 }
1294 }
1295
1296 // For functions which can never be passed stack arguments, add
1297 // a tail keyword.
1298 if (IsAlwaysTail(Class)) {
1299 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +00001300 DEBUG(dbgs() << "Adding tail keyword to function since it can never be "
1301 "passed stack args: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001302 cast<CallInst>(Inst)->setTailCall();
1303 }
1304
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001305 // Ensure that functions that can never have a "tail" keyword due to the
1306 // semantics of ARC truly do not do so.
1307 if (IsNeverTail(Class)) {
1308 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +00001309 DEBUG(dbgs() << "Removing tail keyword from function: " << *Inst <<
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001310 "\n");
1311 cast<CallInst>(Inst)->setTailCall(false);
1312 }
1313
John McCalld935e9c2011-06-15 23:37:01 +00001314 // Set nounwind as needed.
1315 if (IsNoThrow(Class)) {
1316 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +00001317 DEBUG(dbgs() << "Found no throw class. Setting nounwind on: " << *Inst
1318 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001319 cast<CallInst>(Inst)->setDoesNotThrow();
1320 }
1321
1322 if (!IsNoopOnNull(Class)) {
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001323 UsedInThisFunction |= 1 << unsigned(Class);
John McCalld935e9c2011-06-15 23:37:01 +00001324 continue;
1325 }
1326
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001327 const Value *Arg = GetArgRCIdentityRoot(Inst);
John McCalld935e9c2011-06-15 23:37:01 +00001328
1329 // ARC calls with null are no-ops. Delete them.
Michael Gottesman65c24812013-03-25 09:27:43 +00001330 if (IsNullOrUndef(Arg)) {
John McCalld935e9c2011-06-15 23:37:01 +00001331 Changed = true;
1332 ++NumNoops;
Michael Gottesman89279f82013-04-05 18:10:41 +00001333 DEBUG(dbgs() << "ARC calls with null are no-ops. Erasing: " << *Inst
1334 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001335 EraseInstruction(Inst);
1336 continue;
1337 }
1338
1339 // Keep track of which of retain, release, autorelease, and retain_block
1340 // are actually present in this function.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001341 UsedInThisFunction |= 1 << unsigned(Class);
John McCalld935e9c2011-06-15 23:37:01 +00001342
1343 // If Arg is a PHI, and one or more incoming values to the
1344 // PHI are null, and the call is control-equivalent to the PHI, and there
1345 // are no relevant side effects between the PHI and the call, the call
1346 // could be pushed up to just those paths with non-null incoming values.
1347 // For now, don't bother splitting critical edges for this.
1348 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
1349 Worklist.push_back(std::make_pair(Inst, Arg));
1350 do {
1351 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
1352 Inst = Pair.first;
1353 Arg = Pair.second;
1354
1355 const PHINode *PN = dyn_cast<PHINode>(Arg);
1356 if (!PN) continue;
1357
1358 // Determine if the PHI has any null operands, or any incoming
1359 // critical edges.
1360 bool HasNull = false;
1361 bool HasCriticalEdges = false;
1362 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1363 Value *Incoming =
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001364 GetRCIdentityRoot(PN->getIncomingValue(i));
Michael Gottesman65c24812013-03-25 09:27:43 +00001365 if (IsNullOrUndef(Incoming))
John McCalld935e9c2011-06-15 23:37:01 +00001366 HasNull = true;
1367 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
1368 .getNumSuccessors() != 1) {
1369 HasCriticalEdges = true;
1370 break;
1371 }
1372 }
1373 // If we have null operands and no critical edges, optimize.
1374 if (!HasCriticalEdges && HasNull) {
1375 SmallPtrSet<Instruction *, 4> DependingInstructions;
1376 SmallPtrSet<const BasicBlock *, 4> Visited;
1377
1378 // Check that there is nothing that cares about the reference
1379 // count between the call and the phi.
Dan Gohman8478d762012-04-13 00:59:57 +00001380 switch (Class) {
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001381 case ARCInstKind::Retain:
1382 case ARCInstKind::RetainBlock:
Dan Gohman8478d762012-04-13 00:59:57 +00001383 // These can always be moved up.
1384 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001385 case ARCInstKind::Release:
Dan Gohman41375a32012-05-08 23:39:44 +00001386 // These can't be moved across things that care about the retain
1387 // count.
Dan Gohman8478d762012-04-13 00:59:57 +00001388 FindDependencies(NeedsPositiveRetainCount, Arg,
1389 Inst->getParent(), Inst,
1390 DependingInstructions, Visited, PA);
1391 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001392 case ARCInstKind::Autorelease:
Dan Gohman8478d762012-04-13 00:59:57 +00001393 // These can't be moved across autorelease pool scope boundaries.
1394 FindDependencies(AutoreleasePoolBoundary, Arg,
1395 Inst->getParent(), Inst,
1396 DependingInstructions, Visited, PA);
1397 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001398 case ARCInstKind::RetainRV:
1399 case ARCInstKind::AutoreleaseRV:
Dan Gohman8478d762012-04-13 00:59:57 +00001400 // Don't move these; the RV optimization depends on the autoreleaseRV
1401 // being tail called, and the retainRV being immediately after a call
1402 // (which might still happen if we get lucky with codegen layout, but
1403 // it's not worth taking the chance).
1404 continue;
1405 default:
1406 llvm_unreachable("Invalid dependence flavor");
1407 }
1408
John McCalld935e9c2011-06-15 23:37:01 +00001409 if (DependingInstructions.size() == 1 &&
1410 *DependingInstructions.begin() == PN) {
1411 Changed = true;
1412 ++NumPartialNoops;
1413 // Clone the call into each predecessor that has a non-null value.
1414 CallInst *CInst = cast<CallInst>(Inst);
Chris Lattner229907c2011-07-18 04:54:35 +00001415 Type *ParamTy = CInst->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001416 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1417 Value *Incoming =
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001418 GetRCIdentityRoot(PN->getIncomingValue(i));
Michael Gottesman65c24812013-03-25 09:27:43 +00001419 if (!IsNullOrUndef(Incoming)) {
John McCalld935e9c2011-06-15 23:37:01 +00001420 CallInst *Clone = cast<CallInst>(CInst->clone());
1421 Value *Op = PN->getIncomingValue(i);
1422 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
1423 if (Op->getType() != ParamTy)
1424 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
1425 Clone->setArgOperand(0, Op);
1426 Clone->insertBefore(InsertPos);
Michael Gottesmanc189a392013-01-09 19:23:24 +00001427
Michael Gottesman89279f82013-04-05 18:10:41 +00001428 DEBUG(dbgs() << "Cloning "
Michael Gottesmanc189a392013-01-09 19:23:24 +00001429 << *CInst << "\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00001430 "And inserting clone at " << *InsertPos << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001431 Worklist.push_back(std::make_pair(Clone, Incoming));
1432 }
1433 }
1434 // Erase the original call.
Michael Gottesmanc189a392013-01-09 19:23:24 +00001435 DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001436 EraseInstruction(CInst);
1437 continue;
1438 }
1439 }
1440 } while (!Worklist.empty());
1441 }
1442}
1443
Michael Gottesman323964c2013-04-18 05:39:45 +00001444/// If we have a top down pointer in the S_Use state, make sure that there are
1445/// no CFG hazards by checking the states of various bottom up pointers.
1446static void CheckForUseCFGHazard(const Sequence SuccSSeq,
1447 const bool SuccSRRIKnownSafe,
1448 PtrState &S,
1449 bool &SomeSuccHasSame,
1450 bool &AllSuccsHaveSame,
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001451 bool &NotAllSeqEqualButKnownSafe,
Michael Gottesman323964c2013-04-18 05:39:45 +00001452 bool &ShouldContinue) {
1453 switch (SuccSSeq) {
1454 case S_CanRelease: {
Michael Gottesman93132252013-06-21 06:59:02 +00001455 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe) {
Michael Gottesman323964c2013-04-18 05:39:45 +00001456 S.ClearSequenceProgress();
1457 break;
1458 }
Michael Gottesman2f294592013-06-21 19:12:36 +00001459 S.SetCFGHazardAfflicted(true);
Michael Gottesman323964c2013-04-18 05:39:45 +00001460 ShouldContinue = true;
1461 break;
1462 }
1463 case S_Use:
1464 SomeSuccHasSame = true;
1465 break;
1466 case S_Stop:
1467 case S_Release:
1468 case S_MovableRelease:
Michael Gottesman93132252013-06-21 06:59:02 +00001469 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe)
Michael Gottesman323964c2013-04-18 05:39:45 +00001470 AllSuccsHaveSame = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001471 else
1472 NotAllSeqEqualButKnownSafe = true;
Michael Gottesman323964c2013-04-18 05:39:45 +00001473 break;
1474 case S_Retain:
1475 llvm_unreachable("bottom-up pointer in retain state!");
1476 case S_None:
1477 llvm_unreachable("This should have been handled earlier.");
1478 }
1479}
1480
1481/// If we have a Top Down pointer in the S_CanRelease state, make sure that
1482/// there are no CFG hazards by checking the states of various bottom up
1483/// pointers.
1484static void CheckForCanReleaseCFGHazard(const Sequence SuccSSeq,
1485 const bool SuccSRRIKnownSafe,
1486 PtrState &S,
1487 bool &SomeSuccHasSame,
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001488 bool &AllSuccsHaveSame,
1489 bool &NotAllSeqEqualButKnownSafe) {
Michael Gottesman323964c2013-04-18 05:39:45 +00001490 switch (SuccSSeq) {
1491 case S_CanRelease:
1492 SomeSuccHasSame = true;
1493 break;
1494 case S_Stop:
1495 case S_Release:
1496 case S_MovableRelease:
1497 case S_Use:
Michael Gottesman93132252013-06-21 06:59:02 +00001498 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe)
Michael Gottesman323964c2013-04-18 05:39:45 +00001499 AllSuccsHaveSame = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001500 else
1501 NotAllSeqEqualButKnownSafe = true;
Michael Gottesman323964c2013-04-18 05:39:45 +00001502 break;
1503 case S_Retain:
1504 llvm_unreachable("bottom-up pointer in retain state!");
1505 case S_None:
1506 llvm_unreachable("This should have been handled earlier.");
1507 }
1508}
1509
Michael Gottesman97e3df02013-01-14 00:35:14 +00001510/// Check for critical edges, loop boundaries, irreducible control flow, or
1511/// other CFG structures where moving code across the edge would result in it
1512/// being executed more.
John McCalld935e9c2011-06-15 23:37:01 +00001513void
1514ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
1515 DenseMap<const BasicBlock *, BBState> &BBStates,
1516 BBState &MyStates) const {
1517 // If any top-down local-use or possible-dec has a succ which is earlier in
1518 // the sequence, forget it.
Dan Gohman55b06742012-03-02 01:13:53 +00001519 for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
Michael Gottesman323964c2013-04-18 05:39:45 +00001520 E = MyStates.top_down_ptr_end(); I != E; ++I) {
1521 PtrState &S = I->second;
1522 const Sequence Seq = I->second.GetSeq();
Dan Gohman0155f302012-02-17 18:59:53 +00001523
Michael Gottesman323964c2013-04-18 05:39:45 +00001524 // We only care about S_Retain, S_CanRelease, and S_Use.
1525 if (Seq == S_None)
1526 continue;
Dan Gohman0155f302012-02-17 18:59:53 +00001527
Michael Gottesman323964c2013-04-18 05:39:45 +00001528 // Make sure that if extra top down states are added in the future that this
1529 // code is updated to handle it.
1530 assert((Seq == S_Retain || Seq == S_CanRelease || Seq == S_Use) &&
1531 "Unknown top down sequence state.");
1532
1533 const Value *Arg = I->first;
1534 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
1535 bool SomeSuccHasSame = false;
1536 bool AllSuccsHaveSame = true;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001537 bool NotAllSeqEqualButKnownSafe = false;
Michael Gottesman323964c2013-04-18 05:39:45 +00001538
1539 succ_const_iterator SI(TI), SE(TI, false);
1540
1541 for (; SI != SE; ++SI) {
1542 // If VisitBottomUp has pointer information for this successor, take
1543 // what we know about it.
1544 const DenseMap<const BasicBlock *, BBState>::iterator BBI =
1545 BBStates.find(*SI);
1546 assert(BBI != BBStates.end());
1547 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
1548 const Sequence SuccSSeq = SuccS.GetSeq();
1549
1550 // If bottom up, the pointer is in an S_None state, clear the sequence
1551 // progress since the sequence in the bottom up state finished
1552 // suggesting a mismatch in between retains/releases. This is true for
1553 // all three cases that we are handling here: S_Retain, S_Use, and
1554 // S_CanRelease.
1555 if (SuccSSeq == S_None) {
Dan Gohman12130272011-08-12 00:26:31 +00001556 S.ClearSequenceProgress();
Michael Gottesman323964c2013-04-18 05:39:45 +00001557 continue;
1558 }
1559
1560 // If we have S_Use or S_CanRelease, perform our check for cfg hazard
1561 // checks.
Michael Gottesman93132252013-06-21 06:59:02 +00001562 const bool SuccSRRIKnownSafe = SuccS.IsKnownSafe();
Michael Gottesman323964c2013-04-18 05:39:45 +00001563
1564 // *NOTE* We do not use Seq from above here since we are allowing for
1565 // S.GetSeq() to change while we are visiting basic blocks.
1566 switch(S.GetSeq()) {
1567 case S_Use: {
1568 bool ShouldContinue = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001569 CheckForUseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S, SomeSuccHasSame,
1570 AllSuccsHaveSame, NotAllSeqEqualButKnownSafe,
Michael Gottesman323964c2013-04-18 05:39:45 +00001571 ShouldContinue);
1572 if (ShouldContinue)
1573 continue;
1574 break;
1575 }
1576 case S_CanRelease: {
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001577 CheckForCanReleaseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S,
1578 SomeSuccHasSame, AllSuccsHaveSame,
1579 NotAllSeqEqualButKnownSafe);
Michael Gottesman323964c2013-04-18 05:39:45 +00001580 break;
1581 }
1582 case S_Retain:
1583 case S_None:
1584 case S_Stop:
1585 case S_Release:
1586 case S_MovableRelease:
1587 break;
1588 }
John McCalld935e9c2011-06-15 23:37:01 +00001589 }
Michael Gottesman323964c2013-04-18 05:39:45 +00001590
1591 // If the state at the other end of any of the successor edges
1592 // matches the current state, require all edges to match. This
1593 // guards against loops in the middle of a sequence.
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001594 if (SomeSuccHasSame && !AllSuccsHaveSame) {
Michael Gottesman323964c2013-04-18 05:39:45 +00001595 S.ClearSequenceProgress();
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001596 } else if (NotAllSeqEqualButKnownSafe) {
1597 // If we would have cleared the state foregoing the fact that we are known
1598 // safe, stop code motion. This is because whether or not it is safe to
1599 // remove RR pairs via KnownSafe is an orthogonal concept to whether we
1600 // are allowed to perform code motion.
Michael Gottesman2f294592013-06-21 19:12:36 +00001601 S.SetCFGHazardAfflicted(true);
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001602 }
Michael Gottesman323964c2013-04-18 05:39:45 +00001603 }
John McCalld935e9c2011-06-15 23:37:01 +00001604}
1605
Michael Gottesman0be69202015-03-05 23:28:58 +00001606bool ObjCARCOpt::VisitInstructionBottomUp(
1607 Instruction *Inst, BasicBlock *BB, BlotMapVector<Value *, RRInfo> &Retains,
1608 BBState &MyStates) {
Dan Gohman817a7c62012-03-22 18:24:56 +00001609 bool NestingDetected = false;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001610 ARCInstKind Class = GetARCInstKind(Inst);
Craig Topperf40110f2014-04-25 05:29:35 +00001611 const Value *Arg = nullptr;
Michael Gottesman79249972013-04-05 23:46:45 +00001612
Michael Gottesman1d8d2572013-04-05 22:54:28 +00001613 DEBUG(dbgs() << "Class: " << Class << "\n");
Michael Gottesman79249972013-04-05 23:46:45 +00001614
Dan Gohman817a7c62012-03-22 18:24:56 +00001615 switch (Class) {
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001616 case ARCInstKind::Release: {
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001617 Arg = GetArgRCIdentityRoot(Inst);
Dan Gohman817a7c62012-03-22 18:24:56 +00001618
1619 PtrState &S = MyStates.getPtrBottomUpState(Arg);
1620
1621 // If we see two releases in a row on the same pointer. If so, make
1622 // a note, and we'll cicle back to revisit it after we've
1623 // hopefully eliminated the second release, which may allow us to
1624 // eliminate the first release too.
1625 // Theoretically we could implement removal of nested retain+release
1626 // pairs by making PtrState hold a stack of states, but this is
1627 // simple and avoids adding overhead for the non-nested case.
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001628 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001629 DEBUG(dbgs() << "Found nested releases (i.e. a release pair)\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00001630 NestingDetected = true;
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001631 }
Dan Gohman817a7c62012-03-22 18:24:56 +00001632
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001633 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001634 Sequence NewSeq = ReleaseMetadata ? S_MovableRelease : S_Release;
1635 ANNOTATE_BOTTOMUP(Inst, Arg, S.GetSeq(), NewSeq);
1636 S.ResetSequenceProgress(NewSeq);
Michael Gottesmanf701d3f2013-06-21 07:03:07 +00001637 S.SetReleaseMetadata(ReleaseMetadata);
Michael Gottesman93132252013-06-21 06:59:02 +00001638 S.SetKnownSafe(S.HasKnownPositiveRefCount());
Michael Gottesmanb82a1792013-06-21 07:00:44 +00001639 S.SetTailCallRelease(cast<CallInst>(Inst)->isTailCall());
Michael Gottesman4f6ef112013-06-21 19:44:27 +00001640 S.InsertCall(Inst);
Dan Gohmandf476e52012-09-04 23:16:20 +00001641 S.SetKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001642 break;
1643 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001644 case ARCInstKind::RetainBlock:
Michael Gottesman158fdf62013-03-28 20:11:19 +00001645 // In OptimizeIndividualCalls, we have strength reduced all optimizable
1646 // objc_retainBlocks to objc_retains. Thus at this point any
1647 // objc_retainBlocks that we see are not optimizable.
1648 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001649 case ARCInstKind::Retain:
1650 case ARCInstKind::RetainRV: {
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001651 Arg = GetArgRCIdentityRoot(Inst);
Dan Gohman817a7c62012-03-22 18:24:56 +00001652
1653 PtrState &S = MyStates.getPtrBottomUpState(Arg);
Dan Gohman62079b42012-04-25 00:50:46 +00001654 S.SetKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001655
Michael Gottesman81b1d432013-03-26 00:42:04 +00001656 Sequence OldSeq = S.GetSeq();
1657 switch (OldSeq) {
Dan Gohman817a7c62012-03-22 18:24:56 +00001658 case S_Stop:
1659 case S_Release:
1660 case S_MovableRelease:
1661 case S_Use:
Michael Gottesman1d8d2572013-04-05 22:54:28 +00001662 // If OldSeq is not S_Use or OldSeq is S_Use and we are tracking an
1663 // imprecise release, clear our reverse insertion points.
Michael Gottesmanf0401182013-06-21 19:12:38 +00001664 if (OldSeq != S_Use || S.IsTrackingImpreciseReleases())
Michael Gottesman4f6ef112013-06-21 19:44:27 +00001665 S.ClearReverseInsertPts();
Dan Gohman817a7c62012-03-22 18:24:56 +00001666 // FALL THROUGH
1667 case S_CanRelease:
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001668 // Don't do retain+release tracking for ARCInstKind::RetainRV,
1669 // because it's
Dan Gohman817a7c62012-03-22 18:24:56 +00001670 // better to let it remain as the first instruction after a call.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001671 if (Class != ARCInstKind::RetainRV)
Michael Gottesmane3943d02013-06-21 19:44:30 +00001672 Retains[Inst] = S.GetRRInfo();
Dan Gohman817a7c62012-03-22 18:24:56 +00001673 S.ClearSequenceProgress();
1674 break;
1675 case S_None:
1676 break;
1677 case S_Retain:
1678 llvm_unreachable("bottom-up pointer in retain state!");
1679 }
Michael Gottesman79249972013-04-05 23:46:45 +00001680 ANNOTATE_BOTTOMUP(Inst, Arg, OldSeq, S.GetSeq());
Michael Gottesman31ba23a2013-04-05 22:54:32 +00001681 // A retain moving bottom up can be a use.
1682 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001683 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001684 case ARCInstKind::AutoreleasepoolPop:
Dan Gohman817a7c62012-03-22 18:24:56 +00001685 // Conservatively, clear MyStates for all known pointers.
1686 MyStates.clearBottomUpPointers();
1687 return NestingDetected;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001688 case ARCInstKind::AutoreleasepoolPush:
1689 case ARCInstKind::None:
Dan Gohman817a7c62012-03-22 18:24:56 +00001690 // These are irrelevant.
1691 return NestingDetected;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001692 case ARCInstKind::User:
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001693 // If we have a store into an alloca of a pointer we are tracking, the
1694 // pointer has multiple owners implying that we must be more conservative.
1695 //
1696 // This comes up in the context of a pointer being ``KnownSafe''. In the
Alp Tokercb402912014-01-24 17:20:08 +00001697 // presence of a block being initialized, the frontend will emit the
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001698 // objc_retain on the original pointer and the release on the pointer loaded
1699 // from the alloca. The optimizer will through the provenance analysis
1700 // realize that the two are related, but since we only require KnownSafe in
1701 // one direction, will match the inner retain on the original pointer with
1702 // the guard release on the original pointer. This is fixed by ensuring that
Alp Tokercb402912014-01-24 17:20:08 +00001703 // in the presence of allocas we only unconditionally remove pointers if
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001704 // both our retain and our release are KnownSafe.
1705 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1706 if (AreAnyUnderlyingObjectsAnAlloca(SI->getPointerOperand())) {
1707 BBState::ptr_iterator I = MyStates.findPtrBottomUpState(
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001708 GetRCIdentityRoot(SI->getValueOperand()));
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001709 if (I != MyStates.bottom_up_ptr_end())
Michael Gottesman5a91bbf2013-05-24 20:44:02 +00001710 MultiOwnersSet.insert(I->first);
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001711 }
1712 }
1713 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001714 default:
1715 break;
1716 }
1717
1718 // Consider any other possible effects of this instruction on each
1719 // pointer being tracked.
1720 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
1721 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
1722 const Value *Ptr = MI->first;
1723 if (Ptr == Arg)
1724 continue; // Handled above.
1725 PtrState &S = MI->second;
1726 Sequence Seq = S.GetSeq();
1727
1728 // Check for possible releases.
1729 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001730 DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr
1731 << "\n");
Michael Gottesman764b1cf2013-03-23 05:46:19 +00001732 S.ClearKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001733 switch (Seq) {
1734 case S_Use:
1735 S.SetSeq(S_CanRelease);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001736 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S.GetSeq());
Dan Gohman817a7c62012-03-22 18:24:56 +00001737 continue;
1738 case S_CanRelease:
1739 case S_Release:
1740 case S_MovableRelease:
1741 case S_Stop:
1742 case S_None:
1743 break;
1744 case S_Retain:
1745 llvm_unreachable("bottom-up pointer in retain state!");
1746 }
1747 }
1748
1749 // Check for possible direct uses.
1750 switch (Seq) {
1751 case S_Release:
1752 case S_MovableRelease:
1753 if (CanUse(Inst, Ptr, PA, Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001754 DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr
1755 << "\n");
Michael Gottesman4f6ef112013-06-21 19:44:27 +00001756 assert(!S.HasReverseInsertPts());
Dan Gohman5c70fad2012-03-23 17:47:54 +00001757 // If this is an invoke instruction, we're scanning it as part of
1758 // one of its successor blocks, since we can't insert code after it
1759 // in its own block, and we don't want to split critical edges.
1760 if (isa<InvokeInst>(Inst))
Michael Gottesman4f6ef112013-06-21 19:44:27 +00001761 S.InsertReverseInsertPt(BB->getFirstInsertionPt());
Dan Gohman5c70fad2012-03-23 17:47:54 +00001762 else
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001763 S.InsertReverseInsertPt(std::next(BasicBlock::iterator(Inst)));
Dan Gohman817a7c62012-03-22 18:24:56 +00001764 S.SetSeq(S_Use);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001765 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
John McCall20182ac2013-03-22 21:38:36 +00001766 } else if (Seq == S_Release && IsUser(Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001767 DEBUG(dbgs() << "PreciseReleaseUse: Seq: " << Seq << "; " << *Ptr
1768 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00001769 // Non-movable releases depend on any possible objc pointer use.
1770 S.SetSeq(S_Stop);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001771 ANNOTATE_BOTTOMUP(Inst, Ptr, S_Release, S_Stop);
Michael Gottesman4f6ef112013-06-21 19:44:27 +00001772 assert(!S.HasReverseInsertPts());
Dan Gohman5c70fad2012-03-23 17:47:54 +00001773 // As above; handle invoke specially.
1774 if (isa<InvokeInst>(Inst))
Michael Gottesman4f6ef112013-06-21 19:44:27 +00001775 S.InsertReverseInsertPt(BB->getFirstInsertionPt());
Dan Gohman5c70fad2012-03-23 17:47:54 +00001776 else
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001777 S.InsertReverseInsertPt(std::next(BasicBlock::iterator(Inst)));
Dan Gohman817a7c62012-03-22 18:24:56 +00001778 }
1779 break;
1780 case S_Stop:
Michael Gottesman81b1d432013-03-26 00:42:04 +00001781 if (CanUse(Inst, Ptr, PA, Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001782 DEBUG(dbgs() << "PreciseStopUse: Seq: " << Seq << "; " << *Ptr
1783 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00001784 S.SetSeq(S_Use);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001785 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
1786 }
Dan Gohman817a7c62012-03-22 18:24:56 +00001787 break;
1788 case S_CanRelease:
1789 case S_Use:
1790 case S_None:
1791 break;
1792 case S_Retain:
1793 llvm_unreachable("bottom-up pointer in retain state!");
1794 }
1795 }
1796
1797 return NestingDetected;
1798}
1799
Michael Gottesman0be69202015-03-05 23:28:58 +00001800bool ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
1801 DenseMap<const BasicBlock *, BBState> &BBStates,
1802 BlotMapVector<Value *, RRInfo> &Retains) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001803
1804 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitBottomUp ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00001805
John McCalld935e9c2011-06-15 23:37:01 +00001806 bool NestingDetected = false;
1807 BBState &MyStates = BBStates[BB];
1808
1809 // Merge the states from each successor to compute the initial state
1810 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00001811 BBState::edge_iterator SI(MyStates.succ_begin()),
1812 SE(MyStates.succ_end());
1813 if (SI != SE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001814 const BasicBlock *Succ = *SI;
1815 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
1816 assert(I != BBStates.end());
1817 MyStates.InitFromSucc(I->second);
1818 ++SI;
1819 for (; SI != SE; ++SI) {
1820 Succ = *SI;
1821 I = BBStates.find(Succ);
1822 assert(I != BBStates.end());
1823 MyStates.MergeSucc(I->second);
1824 }
Michael Gottesman60f6b282013-03-29 05:13:07 +00001825 }
Michael Gottesmancd4de0f2013-03-26 00:42:09 +00001826
Michael Gottesman43e7e002013-04-03 22:41:59 +00001827 // If ARC Annotations are enabled, output the current state of pointers at the
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00001828 // bottom of the basic block.
Michael Gottesman43e7e002013-04-03 22:41:59 +00001829 ANNOTATE_BOTTOMUP_BBEND(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00001830
John McCalld935e9c2011-06-15 23:37:01 +00001831 // Visit all the instructions, bottom-up.
1832 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001833 Instruction *Inst = std::prev(I);
Dan Gohman5c70fad2012-03-23 17:47:54 +00001834
1835 // Invoke instructions are visited as part of their successors (below).
1836 if (isa<InvokeInst>(Inst))
1837 continue;
1838
Michael Gottesman89279f82013-04-05 18:10:41 +00001839 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001840
Dan Gohman5c70fad2012-03-23 17:47:54 +00001841 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
1842 }
1843
Dan Gohmandae33492012-04-27 18:56:31 +00001844 // If there's a predecessor with an invoke, visit the invoke as if it were
1845 // part of this block, since we can't insert code after an invoke in its own
1846 // block, and we don't want to split critical edges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001847 for (BBState::edge_iterator PI(MyStates.pred_begin()),
1848 PE(MyStates.pred_end()); PI != PE; ++PI) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00001849 BasicBlock *Pred = *PI;
Dan Gohmandae33492012-04-27 18:56:31 +00001850 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
1851 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
Dan Gohman817a7c62012-03-22 18:24:56 +00001852 }
John McCalld935e9c2011-06-15 23:37:01 +00001853
Michael Gottesman43e7e002013-04-03 22:41:59 +00001854 // If ARC Annotations are enabled, output the current state of pointers at the
1855 // top of the basic block.
1856 ANNOTATE_BOTTOMUP_BBSTART(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00001857
Dan Gohman817a7c62012-03-22 18:24:56 +00001858 return NestingDetected;
1859}
John McCalld935e9c2011-06-15 23:37:01 +00001860
Dan Gohman817a7c62012-03-22 18:24:56 +00001861bool
1862ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
1863 DenseMap<Value *, RRInfo> &Releases,
1864 BBState &MyStates) {
1865 bool NestingDetected = false;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001866 ARCInstKind Class = GetARCInstKind(Inst);
Craig Topperf40110f2014-04-25 05:29:35 +00001867 const Value *Arg = nullptr;
John McCalld935e9c2011-06-15 23:37:01 +00001868
Dan Gohman817a7c62012-03-22 18:24:56 +00001869 switch (Class) {
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001870 case ARCInstKind::RetainBlock:
Michael Gottesman158fdf62013-03-28 20:11:19 +00001871 // In OptimizeIndividualCalls, we have strength reduced all optimizable
1872 // objc_retainBlocks to objc_retains. Thus at this point any
1873 // objc_retainBlocks that we see are not optimizable.
1874 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001875 case ARCInstKind::Retain:
1876 case ARCInstKind::RetainRV: {
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001877 Arg = GetArgRCIdentityRoot(Inst);
Dan Gohman817a7c62012-03-22 18:24:56 +00001878
1879 PtrState &S = MyStates.getPtrTopDownState(Arg);
1880
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001881 // Don't do retain+release tracking for ARCInstKind::RetainRV, because
1882 // it's
Dan Gohman817a7c62012-03-22 18:24:56 +00001883 // better to let it remain as the first instruction after a call.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001884 if (Class != ARCInstKind::RetainRV) {
Dan Gohman817a7c62012-03-22 18:24:56 +00001885 // If we see two retains in a row on the same pointer. If so, make
John McCalld935e9c2011-06-15 23:37:01 +00001886 // a note, and we'll cicle back to revisit it after we've
Dan Gohman817a7c62012-03-22 18:24:56 +00001887 // hopefully eliminated the second retain, which may allow us to
1888 // eliminate the first retain too.
John McCalld935e9c2011-06-15 23:37:01 +00001889 // Theoretically we could implement removal of nested retain+release
1890 // pairs by making PtrState hold a stack of states, but this is
1891 // simple and avoids adding overhead for the non-nested case.
Dan Gohman817a7c62012-03-22 18:24:56 +00001892 if (S.GetSeq() == S_Retain)
John McCalld935e9c2011-06-15 23:37:01 +00001893 NestingDetected = true;
1894
Michael Gottesman81b1d432013-03-26 00:42:04 +00001895 ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_Retain);
Dan Gohman62079b42012-04-25 00:50:46 +00001896 S.ResetSequenceProgress(S_Retain);
Michael Gottesman93132252013-06-21 06:59:02 +00001897 S.SetKnownSafe(S.HasKnownPositiveRefCount());
Michael Gottesman4f6ef112013-06-21 19:44:27 +00001898 S.InsertCall(Inst);
John McCalld935e9c2011-06-15 23:37:01 +00001899 }
John McCalld935e9c2011-06-15 23:37:01 +00001900
Dan Gohmandf476e52012-09-04 23:16:20 +00001901 S.SetKnownPositiveRefCount();
Dan Gohmanf64ff8e2012-07-23 19:27:31 +00001902
1903 // A retain can be a potential use; procede to the generic checking
1904 // code below.
1905 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001906 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001907 case ARCInstKind::Release: {
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001908 Arg = GetArgRCIdentityRoot(Inst);
Dan Gohman817a7c62012-03-22 18:24:56 +00001909
1910 PtrState &S = MyStates.getPtrTopDownState(Arg);
Michael Gottesman764b1cf2013-03-23 05:46:19 +00001911 S.ClearKnownPositiveRefCount();
Michael Gottesman79249972013-04-05 23:46:45 +00001912
Michael Gottesman1d8d2572013-04-05 22:54:28 +00001913 Sequence OldSeq = S.GetSeq();
Michael Gottesman79249972013-04-05 23:46:45 +00001914
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001915 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
Michael Gottesman79249972013-04-05 23:46:45 +00001916
Michael Gottesman1d8d2572013-04-05 22:54:28 +00001917 switch (OldSeq) {
Dan Gohman817a7c62012-03-22 18:24:56 +00001918 case S_Retain:
1919 case S_CanRelease:
Craig Topperf40110f2014-04-25 05:29:35 +00001920 if (OldSeq == S_Retain || ReleaseMetadata != nullptr)
Michael Gottesman4f6ef112013-06-21 19:44:27 +00001921 S.ClearReverseInsertPts();
Dan Gohman817a7c62012-03-22 18:24:56 +00001922 // FALL THROUGH
1923 case S_Use:
Michael Gottesmanf701d3f2013-06-21 07:03:07 +00001924 S.SetReleaseMetadata(ReleaseMetadata);
Michael Gottesmanb82a1792013-06-21 07:00:44 +00001925 S.SetTailCallRelease(cast<CallInst>(Inst)->isTailCall());
Michael Gottesmane3943d02013-06-21 19:44:30 +00001926 Releases[Inst] = S.GetRRInfo();
Michael Gottesman81b1d432013-03-26 00:42:04 +00001927 ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_None);
Dan Gohman817a7c62012-03-22 18:24:56 +00001928 S.ClearSequenceProgress();
1929 break;
1930 case S_None:
1931 break;
1932 case S_Stop:
1933 case S_Release:
1934 case S_MovableRelease:
1935 llvm_unreachable("top-down pointer in release state!");
1936 }
1937 break;
1938 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001939 case ARCInstKind::AutoreleasepoolPop:
Dan Gohman817a7c62012-03-22 18:24:56 +00001940 // Conservatively, clear MyStates for all known pointers.
1941 MyStates.clearTopDownPointers();
1942 return NestingDetected;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001943 case ARCInstKind::AutoreleasepoolPush:
1944 case ARCInstKind::None:
Dan Gohman817a7c62012-03-22 18:24:56 +00001945 // These are irrelevant.
1946 return NestingDetected;
1947 default:
1948 break;
1949 }
1950
1951 // Consider any other possible effects of this instruction on each
1952 // pointer being tracked.
1953 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
1954 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
1955 const Value *Ptr = MI->first;
1956 if (Ptr == Arg)
1957 continue; // Handled above.
1958 PtrState &S = MI->second;
1959 Sequence Seq = S.GetSeq();
1960
1961 // Check for possible releases.
1962 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Michael Gottesmanbab49e972013-04-05 18:26:08 +00001963 DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr
Michael Gottesman79249972013-04-05 23:46:45 +00001964 << "\n");
Michael Gottesman764b1cf2013-03-23 05:46:19 +00001965 S.ClearKnownPositiveRefCount();
John McCalld935e9c2011-06-15 23:37:01 +00001966 switch (Seq) {
Dan Gohman817a7c62012-03-22 18:24:56 +00001967 case S_Retain:
1968 S.SetSeq(S_CanRelease);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001969 ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_CanRelease);
Michael Gottesman4f6ef112013-06-21 19:44:27 +00001970 assert(!S.HasReverseInsertPts());
1971 S.InsertReverseInsertPt(Inst);
Dan Gohman817a7c62012-03-22 18:24:56 +00001972
1973 // One call can't cause a transition from S_Retain to S_CanRelease
1974 // and S_CanRelease to S_Use. If we've made the first transition,
1975 // we're done.
1976 continue;
John McCalld935e9c2011-06-15 23:37:01 +00001977 case S_Use:
Dan Gohman817a7c62012-03-22 18:24:56 +00001978 case S_CanRelease:
John McCalld935e9c2011-06-15 23:37:01 +00001979 case S_None:
1980 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001981 case S_Stop:
1982 case S_Release:
1983 case S_MovableRelease:
1984 llvm_unreachable("top-down pointer in release state!");
John McCalld935e9c2011-06-15 23:37:01 +00001985 }
1986 }
Dan Gohman817a7c62012-03-22 18:24:56 +00001987
1988 // Check for possible direct uses.
1989 switch (Seq) {
1990 case S_CanRelease:
Michael Gottesman81b1d432013-03-26 00:42:04 +00001991 if (CanUse(Inst, Ptr, PA, Class)) {
Michael Gottesmanbab49e972013-04-05 18:26:08 +00001992 DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr
1993 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00001994 S.SetSeq(S_Use);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001995 ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_Use);
1996 }
Dan Gohman817a7c62012-03-22 18:24:56 +00001997 break;
1998 case S_Retain:
1999 case S_Use:
2000 case S_None:
2001 break;
2002 case S_Stop:
2003 case S_Release:
2004 case S_MovableRelease:
2005 llvm_unreachable("top-down pointer in release state!");
2006 }
John McCalld935e9c2011-06-15 23:37:01 +00002007 }
2008
2009 return NestingDetected;
2010}
2011
2012bool
2013ObjCARCOpt::VisitTopDown(BasicBlock *BB,
2014 DenseMap<const BasicBlock *, BBState> &BBStates,
2015 DenseMap<Value *, RRInfo> &Releases) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002016 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitTopDown ==\n");
John McCalld935e9c2011-06-15 23:37:01 +00002017 bool NestingDetected = false;
2018 BBState &MyStates = BBStates[BB];
2019
2020 // Merge the states from each predecessor to compute the initial state
2021 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00002022 BBState::edge_iterator PI(MyStates.pred_begin()),
2023 PE(MyStates.pred_end());
2024 if (PI != PE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002025 const BasicBlock *Pred = *PI;
2026 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
2027 assert(I != BBStates.end());
2028 MyStates.InitFromPred(I->second);
2029 ++PI;
2030 for (; PI != PE; ++PI) {
2031 Pred = *PI;
2032 I = BBStates.find(Pred);
2033 assert(I != BBStates.end());
2034 MyStates.MergePred(I->second);
2035 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002036 }
John McCalld935e9c2011-06-15 23:37:01 +00002037
Michael Gottesman43e7e002013-04-03 22:41:59 +00002038 // If ARC Annotations are enabled, output the current state of pointers at the
2039 // top of the basic block.
2040 ANNOTATE_TOPDOWN_BBSTART(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002041
John McCalld935e9c2011-06-15 23:37:01 +00002042 // Visit all the instructions, top-down.
2043 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2044 Instruction *Inst = I;
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00002045
Michael Gottesman89279f82013-04-05 18:10:41 +00002046 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00002047
Dan Gohman817a7c62012-03-22 18:24:56 +00002048 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00002049 }
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002050
Michael Gottesman43e7e002013-04-03 22:41:59 +00002051 // If ARC Annotations are enabled, output the current state of pointers at the
2052 // bottom of the basic block.
2053 ANNOTATE_TOPDOWN_BBEND(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002054
Michael Gottesmanffef24f2013-04-17 20:48:01 +00002055#ifdef ARC_ANNOTATIONS
Michael Gottesmanadb921a2013-04-17 21:03:53 +00002056 if (!(EnableARCAnnotations && DisableCheckForCFGHazards))
Michael Gottesmanffef24f2013-04-17 20:48:01 +00002057#endif
John McCalld935e9c2011-06-15 23:37:01 +00002058 CheckForCFGHazards(BB, BBStates, MyStates);
2059 return NestingDetected;
2060}
2061
Dan Gohmana53a12c2011-12-12 19:42:25 +00002062static void
2063ComputePostOrders(Function &F,
2064 SmallVectorImpl<BasicBlock *> &PostOrder,
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002065 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
2066 unsigned NoObjCARCExceptionsMDKind,
2067 DenseMap<const BasicBlock *, BBState> &BBStates) {
Michael Gottesman97e3df02013-01-14 00:35:14 +00002068 /// The visited set, for doing DFS walks.
Dan Gohmana53a12c2011-12-12 19:42:25 +00002069 SmallPtrSet<BasicBlock *, 16> Visited;
2070
2071 // Do DFS, computing the PostOrder.
2072 SmallPtrSet<BasicBlock *, 16> OnStack;
2073 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002074
2075 // Functions always have exactly one entry block, and we don't have
2076 // any other block that we treat like an entry block.
Dan Gohmana53a12c2011-12-12 19:42:25 +00002077 BasicBlock *EntryBB = &F.getEntryBlock();
Dan Gohman41375a32012-05-08 23:39:44 +00002078 BBState &MyStates = BBStates[EntryBB];
2079 MyStates.SetAsEntry();
2080 TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
2081 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
Dan Gohmana53a12c2011-12-12 19:42:25 +00002082 Visited.insert(EntryBB);
2083 OnStack.insert(EntryBB);
2084 do {
2085 dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002086 BasicBlock *CurrBB = SuccStack.back().first;
2087 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
2088 succ_iterator SE(TI, false);
Dan Gohman41375a32012-05-08 23:39:44 +00002089
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002090 while (SuccStack.back().second != SE) {
2091 BasicBlock *SuccBB = *SuccStack.back().second++;
David Blaikie70573dc2014-11-19 07:49:26 +00002092 if (Visited.insert(SuccBB).second) {
Dan Gohman41375a32012-05-08 23:39:44 +00002093 TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
2094 SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002095 BBStates[CurrBB].addSucc(SuccBB);
Dan Gohman41375a32012-05-08 23:39:44 +00002096 BBState &SuccStates = BBStates[SuccBB];
2097 SuccStates.addPred(CurrBB);
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002098 OnStack.insert(SuccBB);
Dan Gohmana53a12c2011-12-12 19:42:25 +00002099 goto dfs_next_succ;
2100 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002101
2102 if (!OnStack.count(SuccBB)) {
2103 BBStates[CurrBB].addSucc(SuccBB);
2104 BBStates[SuccBB].addPred(CurrBB);
2105 }
Dan Gohmana53a12c2011-12-12 19:42:25 +00002106 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002107 OnStack.erase(CurrBB);
2108 PostOrder.push_back(CurrBB);
2109 SuccStack.pop_back();
Dan Gohmana53a12c2011-12-12 19:42:25 +00002110 } while (!SuccStack.empty());
2111
2112 Visited.clear();
2113
Dan Gohmana53a12c2011-12-12 19:42:25 +00002114 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002115 // Functions may have many exits, and there also blocks which we treat
2116 // as exits due to ignored edges.
2117 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
2118 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
2119 BasicBlock *ExitBB = I;
2120 BBState &MyStates = BBStates[ExitBB];
2121 if (!MyStates.isExit())
2122 continue;
2123
Dan Gohmandae33492012-04-27 18:56:31 +00002124 MyStates.SetAsExit();
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002125
2126 PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00002127 Visited.insert(ExitBB);
2128 while (!PredStack.empty()) {
2129 reverse_dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002130 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
2131 while (PredStack.back().second != PE) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00002132 BasicBlock *BB = *PredStack.back().second++;
David Blaikie70573dc2014-11-19 07:49:26 +00002133 if (Visited.insert(BB).second) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002134 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00002135 goto reverse_dfs_next_succ;
2136 }
2137 }
2138 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
2139 }
2140 }
2141}
2142
Michael Gottesman97e3df02013-01-14 00:35:14 +00002143// Visit the function both top-down and bottom-up.
Michael Gottesman0be69202015-03-05 23:28:58 +00002144bool ObjCARCOpt::Visit(Function &F,
2145 DenseMap<const BasicBlock *, BBState> &BBStates,
2146 BlotMapVector<Value *, RRInfo> &Retains,
2147 DenseMap<Value *, RRInfo> &Releases) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00002148
2149 // Use reverse-postorder traversals, because we magically know that loops
2150 // will be well behaved, i.e. they won't repeatedly call retain on a single
2151 // pointer without doing a release. We can't use the ReversePostOrderTraversal
2152 // class here because we want the reverse-CFG postorder to consider each
2153 // function exit point, and we want to ignore selected cycle edges.
2154 SmallVector<BasicBlock *, 16> PostOrder;
2155 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002156 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
2157 NoObjCARCExceptionsMDKind,
2158 BBStates);
Dan Gohmana53a12c2011-12-12 19:42:25 +00002159
2160 // Use reverse-postorder on the reverse CFG for bottom-up.
John McCalld935e9c2011-06-15 23:37:01 +00002161 bool BottomUpNestingDetected = false;
Dan Gohmanc57b58c2011-08-18 21:27:42 +00002162 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
Dan Gohmana53a12c2011-12-12 19:42:25 +00002163 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
2164 I != E; ++I)
2165 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
John McCalld935e9c2011-06-15 23:37:01 +00002166
Dan Gohmana53a12c2011-12-12 19:42:25 +00002167 // Use reverse-postorder for top-down.
John McCalld935e9c2011-06-15 23:37:01 +00002168 bool TopDownNestingDetected = false;
Dan Gohmana53a12c2011-12-12 19:42:25 +00002169 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2170 PostOrder.rbegin(), E = PostOrder.rend();
2171 I != E; ++I)
2172 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
John McCalld935e9c2011-06-15 23:37:01 +00002173
2174 return TopDownNestingDetected && BottomUpNestingDetected;
2175}
2176
Michael Gottesman97e3df02013-01-14 00:35:14 +00002177/// Move the calls in RetainsToMove and ReleasesToMove.
Michael Gottesman0be69202015-03-05 23:28:58 +00002178void ObjCARCOpt::MoveCalls(Value *Arg, RRInfo &RetainsToMove,
John McCalld935e9c2011-06-15 23:37:01 +00002179 RRInfo &ReleasesToMove,
Michael Gottesman0be69202015-03-05 23:28:58 +00002180 BlotMapVector<Value *, RRInfo> &Retains,
John McCalld935e9c2011-06-15 23:37:01 +00002181 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman6320f522011-07-22 22:29:21 +00002182 SmallVectorImpl<Instruction *> &DeadInsts,
Michael Gottesman79249972013-04-05 23:46:45 +00002183 Module *M) {
Chris Lattner229907c2011-07-18 04:54:35 +00002184 Type *ArgTy = Arg->getType();
Dan Gohman6320f522011-07-22 22:29:21 +00002185 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
Michael Gottesman79249972013-04-05 23:46:45 +00002186
Michael Gottesman89279f82013-04-05 18:10:41 +00002187 DEBUG(dbgs() << "== ObjCARCOpt::MoveCalls ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00002188
John McCalld935e9c2011-06-15 23:37:01 +00002189 // Insert the new retain and release calls.
Craig Topper46276792014-08-24 23:23:06 +00002190 for (Instruction *InsertPt : ReleasesToMove.ReverseInsertPts) {
John McCalld935e9c2011-06-15 23:37:01 +00002191 Value *MyArg = ArgTy == ParamTy ? Arg :
2192 new BitCastInst(Arg, ParamTy, "", InsertPt);
Michael Gottesman14acfac2013-07-06 01:39:23 +00002193 Constant *Decl = EP.get(ARCRuntimeEntryPoints::EPT_Retain);
2194 CallInst *Call = CallInst::Create(Decl, MyArg, "", InsertPt);
John McCalld935e9c2011-06-15 23:37:01 +00002195 Call->setDoesNotThrow();
Michael Gottesmanba648592013-03-28 23:08:44 +00002196 Call->setTailCall();
Michael Gottesman60f6b282013-03-29 05:13:07 +00002197
Michael Gottesmandf110ac2013-04-21 00:30:50 +00002198 DEBUG(dbgs() << "Inserting new Retain: " << *Call << "\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00002199 "At insertion point: " << *InsertPt << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002200 }
Craig Topper46276792014-08-24 23:23:06 +00002201 for (Instruction *InsertPt : RetainsToMove.ReverseInsertPts) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00002202 Value *MyArg = ArgTy == ParamTy ? Arg :
2203 new BitCastInst(Arg, ParamTy, "", InsertPt);
Michael Gottesman14acfac2013-07-06 01:39:23 +00002204 Constant *Decl = EP.get(ARCRuntimeEntryPoints::EPT_Release);
2205 CallInst *Call = CallInst::Create(Decl, MyArg, "", InsertPt);
Dan Gohman5c70fad2012-03-23 17:47:54 +00002206 // Attach a clang.imprecise_release metadata tag, if appropriate.
2207 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
2208 Call->setMetadata(ImpreciseReleaseMDKind, M);
2209 Call->setDoesNotThrow();
2210 if (ReleasesToMove.IsTailCallRelease)
2211 Call->setTailCall();
Michael Gottesmanc189a392013-01-09 19:23:24 +00002212
Michael Gottesman89279f82013-04-05 18:10:41 +00002213 DEBUG(dbgs() << "Inserting new Release: " << *Call << "\n"
2214 "At insertion point: " << *InsertPt << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002215 }
2216
2217 // Delete the original retain and release calls.
Craig Topper46276792014-08-24 23:23:06 +00002218 for (Instruction *OrigRetain : RetainsToMove.Calls) {
John McCalld935e9c2011-06-15 23:37:01 +00002219 Retains.blot(OrigRetain);
2220 DeadInsts.push_back(OrigRetain);
Michael Gottesman89279f82013-04-05 18:10:41 +00002221 DEBUG(dbgs() << "Deleting retain: " << *OrigRetain << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002222 }
Craig Topper46276792014-08-24 23:23:06 +00002223 for (Instruction *OrigRelease : ReleasesToMove.Calls) {
John McCalld935e9c2011-06-15 23:37:01 +00002224 Releases.erase(OrigRelease);
2225 DeadInsts.push_back(OrigRelease);
Michael Gottesman89279f82013-04-05 18:10:41 +00002226 DEBUG(dbgs() << "Deleting release: " << *OrigRelease << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002227 }
Michael Gottesman79249972013-04-05 23:46:45 +00002228
John McCalld935e9c2011-06-15 23:37:01 +00002229}
2230
Michael Gottesman0be69202015-03-05 23:28:58 +00002231bool ObjCARCOpt::ConnectTDBUTraversals(
2232 DenseMap<const BasicBlock *, BBState> &BBStates,
2233 BlotMapVector<Value *, RRInfo> &Retains,
2234 DenseMap<Value *, RRInfo> &Releases, Module *M,
2235 SmallVectorImpl<Instruction *> &NewRetains,
2236 SmallVectorImpl<Instruction *> &NewReleases,
2237 SmallVectorImpl<Instruction *> &DeadInsts, RRInfo &RetainsToMove,
2238 RRInfo &ReleasesToMove, Value *Arg, bool KnownSafe,
2239 bool &AnyPairsCompletelyEliminated) {
Michael Gottesman9de6f962013-01-22 21:49:00 +00002240 // If a pair happens in a region where it is known that the reference count
Michael Gottesmana76143ee2013-05-13 23:49:42 +00002241 // is already incremented, we can similarly ignore possible decrements unless
2242 // we are dealing with a retainable object with multiple provenance sources.
Michael Gottesman9de6f962013-01-22 21:49:00 +00002243 bool KnownSafeTD = true, KnownSafeBU = true;
Michael Gottesmana76143ee2013-05-13 23:49:42 +00002244 bool MultipleOwners = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00002245 bool CFGHazardAfflicted = false;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002246
2247 // Connect the dots between the top-down-collected RetainsToMove and
2248 // bottom-up-collected ReleasesToMove to form sets of related calls.
2249 // This is an iterative process so that we connect multiple releases
2250 // to multiple retains if needed.
2251 unsigned OldDelta = 0;
2252 unsigned NewDelta = 0;
2253 unsigned OldCount = 0;
2254 unsigned NewCount = 0;
2255 bool FirstRelease = true;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002256 for (;;) {
2257 for (SmallVectorImpl<Instruction *>::const_iterator
2258 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
2259 Instruction *NewRetain = *NI;
Michael Gottesman0be69202015-03-05 23:28:58 +00002260 BlotMapVector<Value *, RRInfo>::const_iterator It =
2261 Retains.find(NewRetain);
Michael Gottesman9de6f962013-01-22 21:49:00 +00002262 assert(It != Retains.end());
2263 const RRInfo &NewRetainRRI = It->second;
2264 KnownSafeTD &= NewRetainRRI.KnownSafe;
Michael Gottesman5a91bbf2013-05-24 20:44:02 +00002265 MultipleOwners =
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00002266 MultipleOwners || MultiOwnersSet.count(GetArgRCIdentityRoot(NewRetain));
Craig Topper46276792014-08-24 23:23:06 +00002267 for (Instruction *NewRetainRelease : NewRetainRRI.Calls) {
Michael Gottesman9de6f962013-01-22 21:49:00 +00002268 DenseMap<Value *, RRInfo>::const_iterator Jt =
2269 Releases.find(NewRetainRelease);
2270 if (Jt == Releases.end())
2271 return false;
2272 const RRInfo &NewRetainReleaseRRI = Jt->second;
Michael Gottesman24b2f6f2013-11-05 16:02:40 +00002273
2274 // If the release does not have a reference to the retain as well,
2275 // something happened which is unaccounted for. Do not do anything.
2276 //
2277 // This can happen if we catch an additive overflow during path count
2278 // merging.
2279 if (!NewRetainReleaseRRI.Calls.count(NewRetain))
2280 return false;
2281
David Blaikie70573dc2014-11-19 07:49:26 +00002282 if (ReleasesToMove.Calls.insert(NewRetainRelease).second) {
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002283
2284 // If we overflow when we compute the path count, don't remove/move
2285 // anything.
2286 const BBState &NRRBBState = BBStates[NewRetainRelease->getParent()];
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00002287 unsigned PathCount = BBState::OverflowOccurredValue;
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002288 if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
2289 return false;
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00002290 assert(PathCount != BBState::OverflowOccurredValue &&
2291 "PathCount at this point can not be "
2292 "OverflowOccurredValue.");
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002293 OldDelta -= PathCount;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002294
2295 // Merge the ReleaseMetadata and IsTailCallRelease values.
2296 if (FirstRelease) {
2297 ReleasesToMove.ReleaseMetadata =
2298 NewRetainReleaseRRI.ReleaseMetadata;
2299 ReleasesToMove.IsTailCallRelease =
2300 NewRetainReleaseRRI.IsTailCallRelease;
2301 FirstRelease = false;
2302 } else {
2303 if (ReleasesToMove.ReleaseMetadata !=
2304 NewRetainReleaseRRI.ReleaseMetadata)
Craig Topperf40110f2014-04-25 05:29:35 +00002305 ReleasesToMove.ReleaseMetadata = nullptr;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002306 if (ReleasesToMove.IsTailCallRelease !=
2307 NewRetainReleaseRRI.IsTailCallRelease)
2308 ReleasesToMove.IsTailCallRelease = false;
2309 }
2310
2311 // Collect the optimal insertion points.
2312 if (!KnownSafe)
Craig Topper46276792014-08-24 23:23:06 +00002313 for (Instruction *RIP : NewRetainReleaseRRI.ReverseInsertPts) {
David Blaikie70573dc2014-11-19 07:49:26 +00002314 if (ReleasesToMove.ReverseInsertPts.insert(RIP).second) {
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002315 // If we overflow when we compute the path count, don't
2316 // remove/move anything.
2317 const BBState &RIPBBState = BBStates[RIP->getParent()];
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00002318 PathCount = BBState::OverflowOccurredValue;
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002319 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
2320 return false;
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00002321 assert(PathCount != BBState::OverflowOccurredValue &&
2322 "PathCount at this point can not be "
2323 "OverflowOccurredValue.");
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002324 NewDelta -= PathCount;
2325 }
Michael Gottesman9de6f962013-01-22 21:49:00 +00002326 }
2327 NewReleases.push_back(NewRetainRelease);
2328 }
2329 }
2330 }
2331 NewRetains.clear();
2332 if (NewReleases.empty()) break;
2333
2334 // Back the other way.
2335 for (SmallVectorImpl<Instruction *>::const_iterator
2336 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
2337 Instruction *NewRelease = *NI;
2338 DenseMap<Value *, RRInfo>::const_iterator It =
2339 Releases.find(NewRelease);
2340 assert(It != Releases.end());
2341 const RRInfo &NewReleaseRRI = It->second;
2342 KnownSafeBU &= NewReleaseRRI.KnownSafe;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00002343 CFGHazardAfflicted |= NewReleaseRRI.CFGHazardAfflicted;
Craig Topper46276792014-08-24 23:23:06 +00002344 for (Instruction *NewReleaseRetain : NewReleaseRRI.Calls) {
Michael Gottesman0be69202015-03-05 23:28:58 +00002345 BlotMapVector<Value *, RRInfo>::const_iterator Jt =
2346 Retains.find(NewReleaseRetain);
Michael Gottesman9de6f962013-01-22 21:49:00 +00002347 if (Jt == Retains.end())
2348 return false;
2349 const RRInfo &NewReleaseRetainRRI = Jt->second;
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002350
Michael Gottesman24b2f6f2013-11-05 16:02:40 +00002351 // If the retain does not have a reference to the release as well,
2352 // something happened which is unaccounted for. Do not do anything.
2353 //
2354 // This can happen if we catch an additive overflow during path count
2355 // merging.
2356 if (!NewReleaseRetainRRI.Calls.count(NewRelease))
2357 return false;
2358
David Blaikie70573dc2014-11-19 07:49:26 +00002359 if (RetainsToMove.Calls.insert(NewReleaseRetain).second) {
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002360 // If we overflow when we compute the path count, don't remove/move
2361 // anything.
2362 const BBState &NRRBBState = BBStates[NewReleaseRetain->getParent()];
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00002363 unsigned PathCount = BBState::OverflowOccurredValue;
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002364 if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
2365 return false;
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00002366 assert(PathCount != BBState::OverflowOccurredValue &&
2367 "PathCount at this point can not be "
2368 "OverflowOccurredValue.");
Michael Gottesman9de6f962013-01-22 21:49:00 +00002369 OldDelta += PathCount;
2370 OldCount += PathCount;
2371
Michael Gottesman9de6f962013-01-22 21:49:00 +00002372 // Collect the optimal insertion points.
2373 if (!KnownSafe)
Craig Topper46276792014-08-24 23:23:06 +00002374 for (Instruction *RIP : NewReleaseRetainRRI.ReverseInsertPts) {
David Blaikie70573dc2014-11-19 07:49:26 +00002375 if (RetainsToMove.ReverseInsertPts.insert(RIP).second) {
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002376 // If we overflow when we compute the path count, don't
2377 // remove/move anything.
2378 const BBState &RIPBBState = BBStates[RIP->getParent()];
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00002379
2380 PathCount = BBState::OverflowOccurredValue;
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002381 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
2382 return false;
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00002383 assert(PathCount != BBState::OverflowOccurredValue &&
2384 "PathCount at this point can not be "
2385 "OverflowOccurredValue.");
Michael Gottesman9de6f962013-01-22 21:49:00 +00002386 NewDelta += PathCount;
2387 NewCount += PathCount;
2388 }
2389 }
2390 NewRetains.push_back(NewReleaseRetain);
2391 }
2392 }
2393 }
2394 NewReleases.clear();
2395 if (NewRetains.empty()) break;
2396 }
2397
Michael Gottesmana76143ee2013-05-13 23:49:42 +00002398 // If the pointer is known incremented in 1 direction and we do not have
2399 // MultipleOwners, we can safely remove the retain/releases. Otherwise we need
2400 // to be known safe in both directions.
2401 bool UnconditionallySafe = (KnownSafeTD && KnownSafeBU) ||
2402 ((KnownSafeTD || KnownSafeBU) && !MultipleOwners);
2403 if (UnconditionallySafe) {
Michael Gottesman9de6f962013-01-22 21:49:00 +00002404 RetainsToMove.ReverseInsertPts.clear();
2405 ReleasesToMove.ReverseInsertPts.clear();
2406 NewCount = 0;
2407 } else {
2408 // Determine whether the new insertion points we computed preserve the
2409 // balance of retain and release calls through the program.
2410 // TODO: If the fully aggressive solution isn't valid, try to find a
2411 // less aggressive solution which is.
2412 if (NewDelta != 0)
2413 return false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00002414
2415 // At this point, we are not going to remove any RR pairs, but we still are
2416 // able to move RR pairs. If one of our pointers is afflicted with
2417 // CFGHazards, we cannot perform such code motion so exit early.
2418 const bool WillPerformCodeMotion = RetainsToMove.ReverseInsertPts.size() ||
2419 ReleasesToMove.ReverseInsertPts.size();
2420 if (CFGHazardAfflicted && WillPerformCodeMotion)
2421 return false;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002422 }
2423
2424 // Determine whether the original call points are balanced in the retain and
2425 // release calls through the program. If not, conservatively don't touch
2426 // them.
2427 // TODO: It's theoretically possible to do code motion in this case, as
2428 // long as the existing imbalances are maintained.
2429 if (OldDelta != 0)
2430 return false;
Michael Gottesman8005ad32013-04-29 06:16:55 +00002431
Michael Gottesmana87bb8f2013-04-29 05:13:13 +00002432#ifdef ARC_ANNOTATIONS
2433 // Do not move calls if ARC annotations are requested.
Michael Gottesman3e3977c2013-04-29 05:25:39 +00002434 if (EnableARCAnnotations)
2435 return false;
Michael Gottesmana87bb8f2013-04-29 05:13:13 +00002436#endif // ARC_ANNOTATIONS
Michael Gottesman9de6f962013-01-22 21:49:00 +00002437
2438 Changed = true;
2439 assert(OldCount != 0 && "Unreachable code?");
2440 NumRRs += OldCount - NewCount;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002441 // Set to true if we completely removed any RR pairs.
Michael Gottesman8b5515f2013-01-22 21:53:43 +00002442 AnyPairsCompletelyEliminated = NewCount == 0;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002443
2444 // We can move calls!
2445 return true;
2446}
2447
Michael Gottesman97e3df02013-01-14 00:35:14 +00002448/// Identify pairings between the retains and releases, and delete and/or move
2449/// them.
Michael Gottesman0be69202015-03-05 23:28:58 +00002450bool ObjCARCOpt::PerformCodePlacement(
2451 DenseMap<const BasicBlock *, BBState> &BBStates,
2452 BlotMapVector<Value *, RRInfo> &Retains,
2453 DenseMap<Value *, RRInfo> &Releases, Module *M) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002454 DEBUG(dbgs() << "\n== ObjCARCOpt::PerformCodePlacement ==\n");
2455
John McCalld935e9c2011-06-15 23:37:01 +00002456 bool AnyPairsCompletelyEliminated = false;
2457 RRInfo RetainsToMove;
2458 RRInfo ReleasesToMove;
2459 SmallVector<Instruction *, 4> NewRetains;
2460 SmallVector<Instruction *, 4> NewReleases;
2461 SmallVector<Instruction *, 8> DeadInsts;
2462
Dan Gohman670f9372012-04-13 18:57:48 +00002463 // Visit each retain.
Michael Gottesman0be69202015-03-05 23:28:58 +00002464 for (BlotMapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
2465 E = Retains.end();
2466 I != E; ++I) {
Dan Gohman2053a5d2011-09-29 22:25:23 +00002467 Value *V = I->first;
John McCalld935e9c2011-06-15 23:37:01 +00002468 if (!V) continue; // blotted
2469
2470 Instruction *Retain = cast<Instruction>(V);
Michael Gottesmanc189a392013-01-09 19:23:24 +00002471
Michael Gottesman89279f82013-04-05 18:10:41 +00002472 DEBUG(dbgs() << "Visiting: " << *Retain << "\n");
Michael Gottesmanc189a392013-01-09 19:23:24 +00002473
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00002474 Value *Arg = GetArgRCIdentityRoot(Retain);
John McCalld935e9c2011-06-15 23:37:01 +00002475
Dan Gohman728db492012-01-13 00:39:07 +00002476 // If the object being released is in static or stack storage, we know it's
John McCalld935e9c2011-06-15 23:37:01 +00002477 // not being managed by ObjC reference counting, so we can delete pairs
2478 // regardless of what possible decrements or uses lie between them.
Dan Gohman728db492012-01-13 00:39:07 +00002479 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
Dan Gohman41375a32012-05-08 23:39:44 +00002480
Dan Gohman56e1cef2011-08-22 17:29:11 +00002481 // A constant pointer can't be pointing to an object on the heap. It may
2482 // be reference-counted, but it won't be deleted.
2483 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
2484 if (const GlobalVariable *GV =
2485 dyn_cast<GlobalVariable>(
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00002486 GetRCIdentityRoot(LI->getPointerOperand())))
Dan Gohman56e1cef2011-08-22 17:29:11 +00002487 if (GV->isConstant())
2488 KnownSafe = true;
2489
John McCalld935e9c2011-06-15 23:37:01 +00002490 // Connect the dots between the top-down-collected RetainsToMove and
2491 // bottom-up-collected ReleasesToMove to form sets of related calls.
John McCalld935e9c2011-06-15 23:37:01 +00002492 NewRetains.push_back(Retain);
Michael Gottesman9de6f962013-01-22 21:49:00 +00002493 bool PerformMoveCalls =
2494 ConnectTDBUTraversals(BBStates, Retains, Releases, M, NewRetains,
2495 NewReleases, DeadInsts, RetainsToMove,
2496 ReleasesToMove, Arg, KnownSafe,
2497 AnyPairsCompletelyEliminated);
John McCalld935e9c2011-06-15 23:37:01 +00002498
Michael Gottesman9de6f962013-01-22 21:49:00 +00002499 if (PerformMoveCalls) {
2500 // Ok, everything checks out and we're all set. Let's move/delete some
2501 // code!
2502 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
2503 Retains, Releases, DeadInsts, M);
John McCalld935e9c2011-06-15 23:37:01 +00002504 }
2505
Michael Gottesman9de6f962013-01-22 21:49:00 +00002506 // Clean up state for next retain.
John McCalld935e9c2011-06-15 23:37:01 +00002507 NewReleases.clear();
2508 NewRetains.clear();
2509 RetainsToMove.clear();
2510 ReleasesToMove.clear();
2511 }
2512
2513 // Now that we're done moving everything, we can delete the newly dead
2514 // instructions, as we no longer need them as insert points.
2515 while (!DeadInsts.empty())
2516 EraseInstruction(DeadInsts.pop_back_val());
2517
2518 return AnyPairsCompletelyEliminated;
2519}
2520
Michael Gottesman97e3df02013-01-14 00:35:14 +00002521/// Weak pointer optimizations.
John McCalld935e9c2011-06-15 23:37:01 +00002522void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002523 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeWeakCalls ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00002524
John McCalld935e9c2011-06-15 23:37:01 +00002525 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
2526 // itself because it uses AliasAnalysis and we need to do provenance
2527 // queries instead.
2528 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2529 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +00002530
Michael Gottesman89279f82013-04-05 18:10:41 +00002531 DEBUG(dbgs() << "Visiting: " << *Inst << "\n");
Michael Gottesman3f146e22013-01-01 16:05:48 +00002532
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002533 ARCInstKind Class = GetBasicARCInstKind(Inst);
2534 if (Class != ARCInstKind::LoadWeak &&
2535 Class != ARCInstKind::LoadWeakRetained)
John McCalld935e9c2011-06-15 23:37:01 +00002536 continue;
2537
2538 // Delete objc_loadWeak calls with no users.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002539 if (Class == ARCInstKind::LoadWeak && Inst->use_empty()) {
John McCalld935e9c2011-06-15 23:37:01 +00002540 Inst->eraseFromParent();
2541 continue;
2542 }
2543
2544 // TODO: For now, just look for an earlier available version of this value
2545 // within the same block. Theoretically, we could do memdep-style non-local
2546 // analysis too, but that would want caching. A better approach would be to
2547 // use the technique that EarlyCSE uses.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00002548 inst_iterator Current = std::prev(I);
John McCalld935e9c2011-06-15 23:37:01 +00002549 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
2550 for (BasicBlock::iterator B = CurrentBB->begin(),
2551 J = Current.getInstructionIterator();
2552 J != B; --J) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00002553 Instruction *EarlierInst = &*std::prev(J);
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002554 ARCInstKind EarlierClass = GetARCInstKind(EarlierInst);
John McCalld935e9c2011-06-15 23:37:01 +00002555 switch (EarlierClass) {
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002556 case ARCInstKind::LoadWeak:
2557 case ARCInstKind::LoadWeakRetained: {
John McCalld935e9c2011-06-15 23:37:01 +00002558 // If this is loading from the same pointer, replace this load's value
2559 // with that one.
2560 CallInst *Call = cast<CallInst>(Inst);
2561 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2562 Value *Arg = Call->getArgOperand(0);
2563 Value *EarlierArg = EarlierCall->getArgOperand(0);
2564 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2565 case AliasAnalysis::MustAlias:
2566 Changed = true;
2567 // If the load has a builtin retain, insert a plain retain for it.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002568 if (Class == ARCInstKind::LoadWeakRetained) {
Michael Gottesman14acfac2013-07-06 01:39:23 +00002569 Constant *Decl = EP.get(ARCRuntimeEntryPoints::EPT_Retain);
2570 CallInst *CI = CallInst::Create(Decl, EarlierCall, "", Call);
John McCalld935e9c2011-06-15 23:37:01 +00002571 CI->setTailCall();
2572 }
2573 // Zap the fully redundant load.
2574 Call->replaceAllUsesWith(EarlierCall);
2575 Call->eraseFromParent();
2576 goto clobbered;
2577 case AliasAnalysis::MayAlias:
2578 case AliasAnalysis::PartialAlias:
2579 goto clobbered;
2580 case AliasAnalysis::NoAlias:
2581 break;
2582 }
2583 break;
2584 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002585 case ARCInstKind::StoreWeak:
2586 case ARCInstKind::InitWeak: {
John McCalld935e9c2011-06-15 23:37:01 +00002587 // If this is storing to the same pointer and has the same size etc.
2588 // replace this load's value with the stored value.
2589 CallInst *Call = cast<CallInst>(Inst);
2590 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2591 Value *Arg = Call->getArgOperand(0);
2592 Value *EarlierArg = EarlierCall->getArgOperand(0);
2593 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2594 case AliasAnalysis::MustAlias:
2595 Changed = true;
2596 // If the load has a builtin retain, insert a plain retain for it.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002597 if (Class == ARCInstKind::LoadWeakRetained) {
Michael Gottesman14acfac2013-07-06 01:39:23 +00002598 Constant *Decl = EP.get(ARCRuntimeEntryPoints::EPT_Retain);
2599 CallInst *CI = CallInst::Create(Decl, EarlierCall, "", Call);
John McCalld935e9c2011-06-15 23:37:01 +00002600 CI->setTailCall();
2601 }
2602 // Zap the fully redundant load.
2603 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
2604 Call->eraseFromParent();
2605 goto clobbered;
2606 case AliasAnalysis::MayAlias:
2607 case AliasAnalysis::PartialAlias:
2608 goto clobbered;
2609 case AliasAnalysis::NoAlias:
2610 break;
2611 }
2612 break;
2613 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002614 case ARCInstKind::MoveWeak:
2615 case ARCInstKind::CopyWeak:
John McCalld935e9c2011-06-15 23:37:01 +00002616 // TOOD: Grab the copied value.
2617 goto clobbered;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002618 case ARCInstKind::AutoreleasepoolPush:
2619 case ARCInstKind::None:
2620 case ARCInstKind::IntrinsicUser:
2621 case ARCInstKind::User:
John McCalld935e9c2011-06-15 23:37:01 +00002622 // Weak pointers are only modified through the weak entry points
2623 // (and arbitrary calls, which could call the weak entry points).
2624 break;
2625 default:
2626 // Anything else could modify the weak pointer.
2627 goto clobbered;
2628 }
2629 }
2630 clobbered:;
2631 }
2632
2633 // Then, for each destroyWeak with an alloca operand, check to see if
2634 // the alloca and all its users can be zapped.
2635 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2636 Instruction *Inst = &*I++;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002637 ARCInstKind Class = GetBasicARCInstKind(Inst);
2638 if (Class != ARCInstKind::DestroyWeak)
John McCalld935e9c2011-06-15 23:37:01 +00002639 continue;
2640
2641 CallInst *Call = cast<CallInst>(Inst);
2642 Value *Arg = Call->getArgOperand(0);
2643 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00002644 for (User *U : Alloca->users()) {
2645 const Instruction *UserInst = cast<Instruction>(U);
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002646 switch (GetBasicARCInstKind(UserInst)) {
2647 case ARCInstKind::InitWeak:
2648 case ARCInstKind::StoreWeak:
2649 case ARCInstKind::DestroyWeak:
John McCalld935e9c2011-06-15 23:37:01 +00002650 continue;
2651 default:
2652 goto done;
2653 }
2654 }
2655 Changed = true;
Chandler Carruthcdf47882014-03-09 03:16:01 +00002656 for (auto UI = Alloca->user_begin(), UE = Alloca->user_end(); UI != UE;) {
John McCalld935e9c2011-06-15 23:37:01 +00002657 CallInst *UserInst = cast<CallInst>(*UI++);
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002658 switch (GetBasicARCInstKind(UserInst)) {
2659 case ARCInstKind::InitWeak:
2660 case ARCInstKind::StoreWeak:
Dan Gohman14862c32012-05-18 22:17:29 +00002661 // These functions return their second argument.
2662 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
2663 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002664 case ARCInstKind::DestroyWeak:
Dan Gohman14862c32012-05-18 22:17:29 +00002665 // No return value.
2666 break;
2667 default:
Dan Gohman9c97eea02012-05-21 17:41:28 +00002668 llvm_unreachable("alloca really is used!");
Dan Gohman14862c32012-05-18 22:17:29 +00002669 }
John McCalld935e9c2011-06-15 23:37:01 +00002670 UserInst->eraseFromParent();
2671 }
2672 Alloca->eraseFromParent();
2673 done:;
2674 }
2675 }
2676}
2677
Michael Gottesman97e3df02013-01-14 00:35:14 +00002678/// Identify program paths which execute sequences of retains and releases which
2679/// can be eliminated.
John McCalld935e9c2011-06-15 23:37:01 +00002680bool ObjCARCOpt::OptimizeSequences(Function &F) {
Michael Gottesman740db972013-05-23 02:35:21 +00002681 // Releases, Retains - These are used to store the results of the main flow
2682 // analysis. These use Value* as the key instead of Instruction* so that the
2683 // map stays valid when we get around to rewriting code and calls get
2684 // replaced by arguments.
John McCalld935e9c2011-06-15 23:37:01 +00002685 DenseMap<Value *, RRInfo> Releases;
Michael Gottesman0be69202015-03-05 23:28:58 +00002686 BlotMapVector<Value *, RRInfo> Retains;
John McCalld935e9c2011-06-15 23:37:01 +00002687
Michael Gottesman740db972013-05-23 02:35:21 +00002688 // This is used during the traversal of the function to track the
2689 // states for each identified object at each block.
John McCalld935e9c2011-06-15 23:37:01 +00002690 DenseMap<const BasicBlock *, BBState> BBStates;
2691
2692 // Analyze the CFG of the function, and all instructions.
2693 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
2694
2695 // Transform.
Michael Gottesman5a91bbf2013-05-24 20:44:02 +00002696 bool AnyPairsCompletelyEliminated = PerformCodePlacement(BBStates, Retains,
2697 Releases,
2698 F.getParent());
2699
2700 // Cleanup.
2701 MultiOwnersSet.clear();
2702
2703 return AnyPairsCompletelyEliminated && NestingDetected;
John McCalld935e9c2011-06-15 23:37:01 +00002704}
2705
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002706/// Check if there is a dependent call earlier that does not have anything in
2707/// between the Retain and the call that can affect the reference count of their
2708/// shared pointer argument. Note that Retain need not be in BB.
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002709static bool
2710HasSafePathToPredecessorCall(const Value *Arg, Instruction *Retain,
Craig Topper71b7b682014-08-21 05:55:13 +00002711 SmallPtrSetImpl<Instruction *> &DepInsts,
2712 SmallPtrSetImpl<const BasicBlock *> &Visited,
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002713 ProvenanceAnalysis &PA) {
2714 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
2715 DepInsts, Visited, PA);
2716 if (DepInsts.size() != 1)
2717 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002718
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002719 CallInst *Call =
2720 dyn_cast_or_null<CallInst>(*DepInsts.begin());
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002721
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002722 // Check that the pointer is the return value of the call.
2723 if (!Call || Arg != Call)
2724 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002725
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002726 // Check that the call is a regular call.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002727 ARCInstKind Class = GetBasicARCInstKind(Call);
2728 if (Class != ARCInstKind::CallOrUser && Class != ARCInstKind::Call)
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002729 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002730
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002731 return true;
2732}
2733
Michael Gottesman6908db12013-04-03 23:16:05 +00002734/// Find a dependent retain that precedes the given autorelease for which there
2735/// is nothing in between the two instructions that can affect the ref count of
2736/// Arg.
2737static CallInst *
2738FindPredecessorRetainWithSafePath(const Value *Arg, BasicBlock *BB,
2739 Instruction *Autorelease,
Craig Topper71b7b682014-08-21 05:55:13 +00002740 SmallPtrSetImpl<Instruction *> &DepInsts,
2741 SmallPtrSetImpl<const BasicBlock *> &Visited,
Michael Gottesman6908db12013-04-03 23:16:05 +00002742 ProvenanceAnalysis &PA) {
2743 FindDependencies(CanChangeRetainCount, Arg,
2744 BB, Autorelease, DepInsts, Visited, PA);
2745 if (DepInsts.size() != 1)
Craig Topperf40110f2014-04-25 05:29:35 +00002746 return nullptr;
Michael Gottesman79249972013-04-05 23:46:45 +00002747
Michael Gottesman6908db12013-04-03 23:16:05 +00002748 CallInst *Retain =
2749 dyn_cast_or_null<CallInst>(*DepInsts.begin());
Michael Gottesman79249972013-04-05 23:46:45 +00002750
Michael Gottesman6908db12013-04-03 23:16:05 +00002751 // Check that we found a retain with the same argument.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002752 if (!Retain || !IsRetain(GetBasicARCInstKind(Retain)) ||
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00002753 GetArgRCIdentityRoot(Retain) != Arg) {
Craig Topperf40110f2014-04-25 05:29:35 +00002754 return nullptr;
Michael Gottesman6908db12013-04-03 23:16:05 +00002755 }
Michael Gottesman79249972013-04-05 23:46:45 +00002756
Michael Gottesman6908db12013-04-03 23:16:05 +00002757 return Retain;
2758}
2759
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002760/// Look for an ``autorelease'' instruction dependent on Arg such that there are
2761/// no instructions dependent on Arg that need a positive ref count in between
2762/// the autorelease and the ret.
2763static CallInst *
2764FindPredecessorAutoreleaseWithSafePath(const Value *Arg, BasicBlock *BB,
2765 ReturnInst *Ret,
Craig Topper71b7b682014-08-21 05:55:13 +00002766 SmallPtrSetImpl<Instruction *> &DepInsts,
2767 SmallPtrSetImpl<const BasicBlock *> &V,
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002768 ProvenanceAnalysis &PA) {
2769 FindDependencies(NeedsPositiveRetainCount, Arg,
2770 BB, Ret, DepInsts, V, PA);
2771 if (DepInsts.size() != 1)
Craig Topperf40110f2014-04-25 05:29:35 +00002772 return nullptr;
Michael Gottesman79249972013-04-05 23:46:45 +00002773
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002774 CallInst *Autorelease =
2775 dyn_cast_or_null<CallInst>(*DepInsts.begin());
2776 if (!Autorelease)
Craig Topperf40110f2014-04-25 05:29:35 +00002777 return nullptr;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002778 ARCInstKind AutoreleaseClass = GetBasicARCInstKind(Autorelease);
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002779 if (!IsAutorelease(AutoreleaseClass))
Craig Topperf40110f2014-04-25 05:29:35 +00002780 return nullptr;
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00002781 if (GetArgRCIdentityRoot(Autorelease) != Arg)
Craig Topperf40110f2014-04-25 05:29:35 +00002782 return nullptr;
Michael Gottesman79249972013-04-05 23:46:45 +00002783
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002784 return Autorelease;
2785}
2786
Michael Gottesman97e3df02013-01-14 00:35:14 +00002787/// Look for this pattern:
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00002788/// \code
John McCalld935e9c2011-06-15 23:37:01 +00002789/// %call = call i8* @something(...)
2790/// %2 = call i8* @objc_retain(i8* %call)
2791/// %3 = call i8* @objc_autorelease(i8* %2)
2792/// ret i8* %3
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00002793/// \endcode
John McCalld935e9c2011-06-15 23:37:01 +00002794/// And delete the retain and autorelease.
John McCalld935e9c2011-06-15 23:37:01 +00002795void ObjCARCOpt::OptimizeReturns(Function &F) {
2796 if (!F.getReturnType()->isPointerTy())
2797 return;
Michael Gottesman79249972013-04-05 23:46:45 +00002798
Michael Gottesman89279f82013-04-05 18:10:41 +00002799 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeReturns ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00002800
John McCalld935e9c2011-06-15 23:37:01 +00002801 SmallPtrSet<Instruction *, 4> DependingInstructions;
2802 SmallPtrSet<const BasicBlock *, 4> Visited;
2803 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
2804 BasicBlock *BB = FI;
2805 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
Michael Gottesman3f146e22013-01-01 16:05:48 +00002806
Michael Gottesman89279f82013-04-05 18:10:41 +00002807 DEBUG(dbgs() << "Visiting: " << *Ret << "\n");
Michael Gottesman3f146e22013-01-01 16:05:48 +00002808
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002809 if (!Ret)
2810 continue;
Michael Gottesman79249972013-04-05 23:46:45 +00002811
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00002812 const Value *Arg = GetRCIdentityRoot(Ret->getOperand(0));
Michael Gottesman79249972013-04-05 23:46:45 +00002813
Michael Gottesmancdb7c152013-04-21 00:25:04 +00002814 // Look for an ``autorelease'' instruction that is a predecessor of Ret and
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002815 // dependent on Arg such that there are no instructions dependent on Arg
2816 // that need a positive ref count in between the autorelease and Ret.
2817 CallInst *Autorelease =
2818 FindPredecessorAutoreleaseWithSafePath(Arg, BB, Ret,
2819 DependingInstructions, Visited,
2820 PA);
John McCalld935e9c2011-06-15 23:37:01 +00002821 DependingInstructions.clear();
2822 Visited.clear();
Michael Gottesmanfb9ece92013-04-21 00:25:01 +00002823
2824 if (!Autorelease)
2825 continue;
2826
2827 CallInst *Retain =
2828 FindPredecessorRetainWithSafePath(Arg, BB, Autorelease,
2829 DependingInstructions, Visited, PA);
2830 DependingInstructions.clear();
2831 Visited.clear();
2832
2833 if (!Retain)
2834 continue;
2835
2836 // Check that there is nothing that can affect the reference count
2837 // between the retain and the call. Note that Retain need not be in BB.
2838 bool HasSafePathToCall = HasSafePathToPredecessorCall(Arg, Retain,
2839 DependingInstructions,
2840 Visited, PA);
2841 DependingInstructions.clear();
2842 Visited.clear();
2843
2844 if (!HasSafePathToCall)
2845 continue;
2846
2847 // If so, we can zap the retain and autorelease.
2848 Changed = true;
2849 ++NumRets;
2850 DEBUG(dbgs() << "Erasing: " << *Retain << "\nErasing: "
2851 << *Autorelease << "\n");
2852 EraseInstruction(Retain);
2853 EraseInstruction(Autorelease);
John McCalld935e9c2011-06-15 23:37:01 +00002854 }
2855}
2856
Michael Gottesman9c118152013-04-29 06:16:57 +00002857#ifndef NDEBUG
2858void
2859ObjCARCOpt::GatherStatistics(Function &F, bool AfterOptimization) {
2860 llvm::Statistic &NumRetains =
2861 AfterOptimization? NumRetainsAfterOpt : NumRetainsBeforeOpt;
2862 llvm::Statistic &NumReleases =
2863 AfterOptimization? NumReleasesAfterOpt : NumReleasesBeforeOpt;
2864
2865 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2866 Instruction *Inst = &*I++;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002867 switch (GetBasicARCInstKind(Inst)) {
Michael Gottesman9c118152013-04-29 06:16:57 +00002868 default:
2869 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002870 case ARCInstKind::Retain:
Michael Gottesman9c118152013-04-29 06:16:57 +00002871 ++NumRetains;
2872 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002873 case ARCInstKind::Release:
Michael Gottesman9c118152013-04-29 06:16:57 +00002874 ++NumReleases;
2875 break;
2876 }
2877 }
2878}
2879#endif
2880
John McCalld935e9c2011-06-15 23:37:01 +00002881bool ObjCARCOpt::doInitialization(Module &M) {
2882 if (!EnableARCOpts)
2883 return false;
2884
Dan Gohman670f9372012-04-13 18:57:48 +00002885 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanceaac7c2011-06-20 23:20:43 +00002886 Run = ModuleHasARC(M);
2887 if (!Run)
2888 return false;
2889
John McCalld935e9c2011-06-15 23:37:01 +00002890 // Identify the imprecise release metadata kind.
2891 ImpreciseReleaseMDKind =
2892 M.getContext().getMDKindID("clang.imprecise_release");
Dan Gohmana7107f92011-10-17 22:53:25 +00002893 CopyOnEscapeMDKind =
2894 M.getContext().getMDKindID("clang.arc.copy_on_escape");
Dan Gohman0155f302012-02-17 18:59:53 +00002895 NoObjCARCExceptionsMDKind =
2896 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
Michael Gottesman81b1d432013-03-26 00:42:04 +00002897#ifdef ARC_ANNOTATIONS
2898 ARCAnnotationBottomUpMDKind =
2899 M.getContext().getMDKindID("llvm.arc.annotation.bottomup");
2900 ARCAnnotationTopDownMDKind =
2901 M.getContext().getMDKindID("llvm.arc.annotation.topdown");
2902 ARCAnnotationProvenanceSourceMDKind =
2903 M.getContext().getMDKindID("llvm.arc.annotation.provenancesource");
2904#endif // ARC_ANNOTATIONS
John McCalld935e9c2011-06-15 23:37:01 +00002905
John McCalld935e9c2011-06-15 23:37:01 +00002906 // Intuitively, objc_retain and others are nocapture, however in practice
2907 // they are not, because they return their argument value. And objc_release
Dan Gohmandae33492012-04-27 18:56:31 +00002908 // calls finalizers which can have arbitrary side effects.
John McCalld935e9c2011-06-15 23:37:01 +00002909
Michael Gottesman14acfac2013-07-06 01:39:23 +00002910 // Initialize our runtime entry point cache.
2911 EP.Initialize(&M);
John McCalld935e9c2011-06-15 23:37:01 +00002912
2913 return false;
2914}
2915
2916bool ObjCARCOpt::runOnFunction(Function &F) {
2917 if (!EnableARCOpts)
2918 return false;
2919
Dan Gohmanceaac7c2011-06-20 23:20:43 +00002920 // If nothing in the Module uses ARC, don't do anything.
2921 if (!Run)
2922 return false;
2923
John McCalld935e9c2011-06-15 23:37:01 +00002924 Changed = false;
2925
Michael Gottesman89279f82013-04-05 18:10:41 +00002926 DEBUG(dbgs() << "<<< ObjCARCOpt: Visiting Function: " << F.getName() << " >>>"
2927 "\n");
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00002928
John McCalld935e9c2011-06-15 23:37:01 +00002929 PA.setAA(&getAnalysis<AliasAnalysis>());
2930
Michael Gottesman9fc50b82013-05-13 18:29:07 +00002931#ifndef NDEBUG
2932 if (AreStatisticsEnabled()) {
2933 GatherStatistics(F, false);
2934 }
2935#endif
2936
John McCalld935e9c2011-06-15 23:37:01 +00002937 // This pass performs several distinct transformations. As a compile-time aid
2938 // when compiling code that isn't ObjC, skip these if the relevant ObjC
2939 // library functions aren't declared.
2940
Michael Gottesmancd5b0272013-04-24 22:18:15 +00002941 // Preliminary optimizations. This also computes UsedInThisFunction.
John McCalld935e9c2011-06-15 23:37:01 +00002942 OptimizeIndividualCalls(F);
2943
2944 // Optimizations for weak pointers.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002945 if (UsedInThisFunction & ((1 << unsigned(ARCInstKind::LoadWeak)) |
2946 (1 << unsigned(ARCInstKind::LoadWeakRetained)) |
2947 (1 << unsigned(ARCInstKind::StoreWeak)) |
2948 (1 << unsigned(ARCInstKind::InitWeak)) |
2949 (1 << unsigned(ARCInstKind::CopyWeak)) |
2950 (1 << unsigned(ARCInstKind::MoveWeak)) |
2951 (1 << unsigned(ARCInstKind::DestroyWeak))))
John McCalld935e9c2011-06-15 23:37:01 +00002952 OptimizeWeakCalls(F);
2953
2954 // Optimizations for retain+release pairs.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002955 if (UsedInThisFunction & ((1 << unsigned(ARCInstKind::Retain)) |
2956 (1 << unsigned(ARCInstKind::RetainRV)) |
2957 (1 << unsigned(ARCInstKind::RetainBlock))))
2958 if (UsedInThisFunction & (1 << unsigned(ARCInstKind::Release)))
John McCalld935e9c2011-06-15 23:37:01 +00002959 // Run OptimizeSequences until it either stops making changes or
2960 // no retain+release pair nesting is detected.
2961 while (OptimizeSequences(F)) {}
2962
2963 // Optimizations if objc_autorelease is used.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002964 if (UsedInThisFunction & ((1 << unsigned(ARCInstKind::Autorelease)) |
2965 (1 << unsigned(ARCInstKind::AutoreleaseRV))))
John McCalld935e9c2011-06-15 23:37:01 +00002966 OptimizeReturns(F);
2967
Michael Gottesman9c118152013-04-29 06:16:57 +00002968 // Gather statistics after optimization.
2969#ifndef NDEBUG
2970 if (AreStatisticsEnabled()) {
2971 GatherStatistics(F, true);
2972 }
2973#endif
2974
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00002975 DEBUG(dbgs() << "\n");
2976
John McCalld935e9c2011-06-15 23:37:01 +00002977 return Changed;
2978}
2979
2980void ObjCARCOpt::releaseMemory() {
2981 PA.clear();
2982}
2983
Michael Gottesman97e3df02013-01-14 00:35:14 +00002984/// @}
2985///