blob: a9e956b5779b943b011b66b0147c0bcfc2c467ce [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"
Michael Gottesman68b91db2015-03-05 23:29:03 +000033#include "PtrState.h"
John McCalld935e9c2011-06-15 23:37:01 +000034#include "llvm/ADT/DenseMap.h"
Michael Gottesman5a91bbf2013-05-24 20:44:02 +000035#include "llvm/ADT/DenseSet.h"
Michael Gottesmanfa0939f2013-01-28 04:12:07 +000036#include "llvm/ADT/STLExtras.h"
Michael Gottesman778138e2013-01-29 03:03:03 +000037#include "llvm/ADT/SmallPtrSet.h"
Michael Gottesman278266f2013-01-29 04:20:52 +000038#include "llvm/ADT/Statistic.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000039#include "llvm/IR/CFG.h"
Michael Gottesmancd4de0f2013-03-26 00:42:09 +000040#include "llvm/IR/IRBuilder.h"
Michael Gottesman278266f2013-01-29 04:20:52 +000041#include "llvm/IR/LLVMContext.h"
Michael Gottesman13a5f1a2013-01-29 04:51:59 +000042#include "llvm/Support/Debug.h"
Timur Iskhodzhanov5d7ff002013-01-29 09:09:27 +000043#include "llvm/Support/raw_ostream.h"
Michael Gottesmanfa0939f2013-01-28 04:12:07 +000044
John McCalld935e9c2011-06-15 23:37:01 +000045using namespace llvm;
Michael Gottesman08904e32013-01-28 03:28:38 +000046using namespace llvm::objcarc;
John McCalld935e9c2011-06-15 23:37:01 +000047
Chandler Carruth964daaa2014-04-22 02:55:47 +000048#define DEBUG_TYPE "objc-arc-opts"
49
Michael Gottesman97e3df02013-01-14 00:35:14 +000050/// \defgroup ARCUtilities Utility declarations/definitions specific to ARC.
51/// @{
John McCalld935e9c2011-06-15 23:37:01 +000052
Michael Gottesmane5ad66f2015-02-19 00:42:38 +000053/// \brief This is similar to GetRCIdentityRoot but it stops as soon
Michael Gottesman97e3df02013-01-14 00:35:14 +000054/// as it finds a value with multiple uses.
John McCalld935e9c2011-06-15 23:37:01 +000055static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
56 if (Arg->hasOneUse()) {
57 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
58 return FindSingleUseIdentifiedObject(BC->getOperand(0));
59 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
60 if (GEP->hasAllZeroIndices())
61 return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
Michael Gottesman6f729fa2015-02-19 19:51:32 +000062 if (IsForwarding(GetBasicARCInstKind(Arg)))
John McCalld935e9c2011-06-15 23:37:01 +000063 return FindSingleUseIdentifiedObject(
64 cast<CallInst>(Arg)->getArgOperand(0));
65 if (!IsObjCIdentifiedObject(Arg))
Craig Topperf40110f2014-04-25 05:29:35 +000066 return nullptr;
John McCalld935e9c2011-06-15 23:37:01 +000067 return Arg;
68 }
69
Dan Gohman41375a32012-05-08 23:39:44 +000070 // If we found an identifiable object but it has multiple uses, but they are
71 // trivial uses, we can still consider this to be a single-use value.
John McCalld935e9c2011-06-15 23:37:01 +000072 if (IsObjCIdentifiedObject(Arg)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +000073 for (const User *U : Arg->users())
Michael Gottesmane5ad66f2015-02-19 00:42:38 +000074 if (!U->use_empty() || GetRCIdentityRoot(U) != Arg)
Craig Topperf40110f2014-04-25 05:29:35 +000075 return nullptr;
John McCalld935e9c2011-06-15 23:37:01 +000076
77 return Arg;
78 }
79
Craig Topperf40110f2014-04-25 05:29:35 +000080 return nullptr;
John McCalld935e9c2011-06-15 23:37:01 +000081}
82
Michael Gottesmana76143ee2013-05-13 23:49:42 +000083/// This is a wrapper around getUnderlyingObjCPtr along the lines of
84/// GetUnderlyingObjects except that it returns early when it sees the first
85/// alloca.
86static inline bool AreAnyUnderlyingObjectsAnAlloca(const Value *V) {
87 SmallPtrSet<const Value *, 4> Visited;
88 SmallVector<const Value *, 4> Worklist;
89 Worklist.push_back(V);
90 do {
91 const Value *P = Worklist.pop_back_val();
92 P = GetUnderlyingObjCPtr(P);
Michael Gottesman0c8b5622013-05-14 06:40:10 +000093
Michael Gottesmana76143ee2013-05-13 23:49:42 +000094 if (isa<AllocaInst>(P))
95 return true;
Michael Gottesman0c8b5622013-05-14 06:40:10 +000096
David Blaikie70573dc2014-11-19 07:49:26 +000097 if (!Visited.insert(P).second)
Michael Gottesmana76143ee2013-05-13 23:49:42 +000098 continue;
Michael Gottesman0c8b5622013-05-14 06:40:10 +000099
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000100 if (const SelectInst *SI = dyn_cast<const SelectInst>(P)) {
101 Worklist.push_back(SI->getTrueValue());
102 Worklist.push_back(SI->getFalseValue());
103 continue;
104 }
Michael Gottesman0c8b5622013-05-14 06:40:10 +0000105
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000106 if (const PHINode *PN = dyn_cast<const PHINode>(P)) {
107 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
108 Worklist.push_back(PN->getIncomingValue(i));
109 continue;
110 }
111 } while (!Worklist.empty());
112
113 return false;
114}
115
116
Michael Gottesman97e3df02013-01-14 00:35:14 +0000117/// @}
118///
Michael Gottesman97e3df02013-01-14 00:35:14 +0000119/// \defgroup ARCOpt ARC Optimization.
120/// @{
John McCalld935e9c2011-06-15 23:37:01 +0000121
122// TODO: On code like this:
123//
124// objc_retain(%x)
125// stuff_that_cannot_release()
126// objc_autorelease(%x)
127// stuff_that_cannot_release()
128// objc_retain(%x)
129// stuff_that_cannot_release()
130// objc_autorelease(%x)
131//
132// The second retain and autorelease can be deleted.
133
134// TODO: It should be possible to delete
135// objc_autoreleasePoolPush and objc_autoreleasePoolPop
136// pairs if nothing is actually autoreleased between them. Also, autorelease
137// calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
138// after inlining) can be turned into plain release calls.
139
140// TODO: Critical-edge splitting. If the optimial insertion point is
141// a critical edge, the current algorithm has to fail, because it doesn't
142// know how to split edges. It should be possible to make the optimizer
143// think in terms of edges, rather than blocks, and then split critical
144// edges on demand.
145
146// TODO: OptimizeSequences could generalized to be Interprocedural.
147
148// TODO: Recognize that a bunch of other objc runtime calls have
149// non-escaping arguments and non-releasing arguments, and may be
150// non-autoreleasing.
151
152// TODO: Sink autorelease calls as far as possible. Unfortunately we
153// usually can't sink them past other calls, which would be the main
154// case where it would be useful.
155
Dan Gohmanb3894012011-08-19 00:26:36 +0000156// TODO: The pointer returned from objc_loadWeakRetained is retained.
157
158// TODO: Delete release+retain pairs (rare).
Dan Gohmanceaac7c2011-06-20 23:20:43 +0000159
John McCalld935e9c2011-06-15 23:37:01 +0000160STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
161STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
162STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
163STATISTIC(NumRets, "Number of return value forwarding "
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000164 "retain+autoreleases eliminated");
John McCalld935e9c2011-06-15 23:37:01 +0000165STATISTIC(NumRRs, "Number of retain+release paths eliminated");
166STATISTIC(NumPeeps, "Number of calls peephole-optimized");
Matt Beaumont-Gaye55d9492013-05-13 21:10:49 +0000167#ifndef NDEBUG
Michael Gottesman9c118152013-04-29 06:16:57 +0000168STATISTIC(NumRetainsBeforeOpt,
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000169 "Number of retains before optimization");
Michael Gottesman9c118152013-04-29 06:16:57 +0000170STATISTIC(NumReleasesBeforeOpt,
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000171 "Number of releases before optimization");
Michael Gottesman9c118152013-04-29 06:16:57 +0000172STATISTIC(NumRetainsAfterOpt,
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000173 "Number of retains after optimization");
Michael Gottesman9c118152013-04-29 06:16:57 +0000174STATISTIC(NumReleasesAfterOpt,
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000175 "Number of releases after optimization");
Michael Gottesman03cf3c82013-04-29 07:29:08 +0000176#endif
John McCalld935e9c2011-06-15 23:37:01 +0000177
178namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000179 /// \brief Per-BasicBlock state.
John McCalld935e9c2011-06-15 23:37:01 +0000180 class BBState {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000181 /// The number of unique control paths from the entry which can reach this
182 /// block.
John McCalld935e9c2011-06-15 23:37:01 +0000183 unsigned TopDownPathCount;
184
Michael Gottesman97e3df02013-01-14 00:35:14 +0000185 /// The number of unique control paths to exits from this block.
John McCalld935e9c2011-06-15 23:37:01 +0000186 unsigned BottomUpPathCount;
187
Michael Gottesman97e3df02013-01-14 00:35:14 +0000188 /// The top-down traversal uses this to record information known about a
189 /// pointer at the bottom of each block.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000190 BlotMapVector<const Value *, TopDownPtrState> PerPtrTopDown;
John McCalld935e9c2011-06-15 23:37:01 +0000191
Michael Gottesman97e3df02013-01-14 00:35:14 +0000192 /// The bottom-up traversal uses this to record information known about a
193 /// pointer at the top of each block.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000194 BlotMapVector<const Value *, BottomUpPtrState> PerPtrBottomUp;
John McCalld935e9c2011-06-15 23:37:01 +0000195
Michael Gottesman97e3df02013-01-14 00:35:14 +0000196 /// Effective predecessors of the current block ignoring ignorable edges and
197 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000198 SmallVector<BasicBlock *, 2> Preds;
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000199
Michael Gottesman97e3df02013-01-14 00:35:14 +0000200 /// Effective successors of the current block ignoring ignorable edges and
201 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000202 SmallVector<BasicBlock *, 2> Succs;
203
John McCalld935e9c2011-06-15 23:37:01 +0000204 public:
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000205 static const unsigned OverflowOccurredValue;
206
207 BBState() : TopDownPathCount(0), BottomUpPathCount(0) { }
John McCalld935e9c2011-06-15 23:37:01 +0000208
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000209 typedef decltype(PerPtrTopDown)::iterator top_down_ptr_iterator;
210 typedef decltype(PerPtrTopDown)::const_iterator const_top_down_ptr_iterator;
John McCalld935e9c2011-06-15 23:37:01 +0000211
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000212 top_down_ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
213 top_down_ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
214 const_top_down_ptr_iterator top_down_ptr_begin() const {
John McCalld935e9c2011-06-15 23:37:01 +0000215 return PerPtrTopDown.begin();
216 }
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000217 const_top_down_ptr_iterator top_down_ptr_end() const {
John McCalld935e9c2011-06-15 23:37:01 +0000218 return PerPtrTopDown.end();
219 }
220
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000221 typedef decltype(PerPtrBottomUp)::iterator bottom_up_ptr_iterator;
222 typedef decltype(
223 PerPtrBottomUp)::const_iterator const_bottom_up_ptr_iterator;
224
225 bottom_up_ptr_iterator bottom_up_ptr_begin() {
John McCalld935e9c2011-06-15 23:37:01 +0000226 return PerPtrBottomUp.begin();
227 }
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000228 bottom_up_ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
229 const_bottom_up_ptr_iterator bottom_up_ptr_begin() const {
230 return PerPtrBottomUp.begin();
231 }
232 const_bottom_up_ptr_iterator bottom_up_ptr_end() const {
John McCalld935e9c2011-06-15 23:37:01 +0000233 return PerPtrBottomUp.end();
234 }
235
Michael Gottesman97e3df02013-01-14 00:35:14 +0000236 /// Mark this block as being an entry block, which has one path from the
237 /// entry by definition.
John McCalld935e9c2011-06-15 23:37:01 +0000238 void SetAsEntry() { TopDownPathCount = 1; }
239
Michael Gottesman97e3df02013-01-14 00:35:14 +0000240 /// Mark this block as being an exit block, which has one path to an exit by
241 /// definition.
John McCalld935e9c2011-06-15 23:37:01 +0000242 void SetAsExit() { BottomUpPathCount = 1; }
243
Michael Gottesman993fbf72013-05-13 19:40:39 +0000244 /// Attempt to find the PtrState object describing the top down state for
245 /// pointer Arg. Return a new initialized PtrState describing the top down
246 /// state for Arg if we do not find one.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000247 TopDownPtrState &getPtrTopDownState(const Value *Arg) {
John McCalld935e9c2011-06-15 23:37:01 +0000248 return PerPtrTopDown[Arg];
249 }
250
Michael Gottesman993fbf72013-05-13 19:40:39 +0000251 /// Attempt to find the PtrState object describing the bottom up state for
252 /// pointer Arg. Return a new initialized PtrState describing the bottom up
253 /// state for Arg if we do not find one.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000254 BottomUpPtrState &getPtrBottomUpState(const Value *Arg) {
John McCalld935e9c2011-06-15 23:37:01 +0000255 return PerPtrBottomUp[Arg];
256 }
257
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000258 /// Attempt to find the PtrState object describing the bottom up state for
259 /// pointer Arg.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000260 bottom_up_ptr_iterator findPtrBottomUpState(const Value *Arg) {
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000261 return PerPtrBottomUp.find(Arg);
262 }
263
John McCalld935e9c2011-06-15 23:37:01 +0000264 void clearBottomUpPointers() {
Evan Chenge4df6a22011-08-04 18:40:26 +0000265 PerPtrBottomUp.clear();
John McCalld935e9c2011-06-15 23:37:01 +0000266 }
267
268 void clearTopDownPointers() {
269 PerPtrTopDown.clear();
270 }
271
272 void InitFromPred(const BBState &Other);
273 void InitFromSucc(const BBState &Other);
274 void MergePred(const BBState &Other);
275 void MergeSucc(const BBState &Other);
276
Michael Gottesman9e7261c2013-06-07 06:16:49 +0000277 /// Compute the number of possible unique paths from an entry to an exit
Michael Gottesman97e3df02013-01-14 00:35:14 +0000278 /// which pass through this block. This is only valid after both the
279 /// top-down and bottom-up traversals are complete.
Michael Gottesman9e7261c2013-06-07 06:16:49 +0000280 ///
Alp Tokercb402912014-01-24 17:20:08 +0000281 /// Returns true if overflow occurred. Returns false if overflow did not
Michael Gottesman9e7261c2013-06-07 06:16:49 +0000282 /// occur.
283 bool GetAllPathCountWithOverflow(unsigned &PathCount) const {
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000284 if (TopDownPathCount == OverflowOccurredValue ||
285 BottomUpPathCount == OverflowOccurredValue)
286 return true;
Michael Gottesman9e7261c2013-06-07 06:16:49 +0000287 unsigned long long Product =
288 (unsigned long long)TopDownPathCount*BottomUpPathCount;
Alp Tokercb402912014-01-24 17:20:08 +0000289 // Overflow occurred if any of the upper bits of Product are set or if all
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000290 // the lower bits of Product are all set.
291 return (Product >> 32) ||
292 ((PathCount = Product) == OverflowOccurredValue);
John McCalld935e9c2011-06-15 23:37:01 +0000293 }
Dan Gohman12130272011-08-12 00:26:31 +0000294
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000295 // Specialized CFG utilities.
Dan Gohmandae33492012-04-27 18:56:31 +0000296 typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
Michael Gottesman0fecf982013-08-07 23:56:34 +0000297 edge_iterator pred_begin() const { return Preds.begin(); }
298 edge_iterator pred_end() const { return Preds.end(); }
299 edge_iterator succ_begin() const { return Succs.begin(); }
300 edge_iterator succ_end() const { return Succs.end(); }
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000301
302 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
303 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
304
305 bool isExit() const { return Succs.empty(); }
John McCalld935e9c2011-06-15 23:37:01 +0000306 };
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000307
308 const unsigned BBState::OverflowOccurredValue = 0xffffffff;
John McCalld935e9c2011-06-15 23:37:01 +0000309}
310
311void BBState::InitFromPred(const BBState &Other) {
312 PerPtrTopDown = Other.PerPtrTopDown;
313 TopDownPathCount = Other.TopDownPathCount;
314}
315
316void BBState::InitFromSucc(const BBState &Other) {
317 PerPtrBottomUp = Other.PerPtrBottomUp;
318 BottomUpPathCount = Other.BottomUpPathCount;
319}
320
Michael Gottesman97e3df02013-01-14 00:35:14 +0000321/// The top-down traversal uses this to merge information about predecessors to
322/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +0000323void BBState::MergePred(const BBState &Other) {
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000324 if (TopDownPathCount == OverflowOccurredValue)
325 return;
326
John McCalld935e9c2011-06-15 23:37:01 +0000327 // Other.TopDownPathCount can be 0, in which case it is either dead or a
328 // loop backedge. Loop backedges are special.
329 TopDownPathCount += Other.TopDownPathCount;
330
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000331 // In order to be consistent, we clear the top down pointers when by adding
332 // TopDownPathCount becomes OverflowOccurredValue even though "true" overflow
Alp Tokercb402912014-01-24 17:20:08 +0000333 // has not occurred.
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000334 if (TopDownPathCount == OverflowOccurredValue) {
335 clearTopDownPointers();
336 return;
337 }
338
Michael Gottesman4385edf2013-01-14 01:47:53 +0000339 // Check for overflow. If we have overflow, fall back to conservative
340 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +0000341 if (TopDownPathCount < Other.TopDownPathCount) {
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000342 TopDownPathCount = OverflowOccurredValue;
Dan Gohman7c84dad2012-09-12 20:45:17 +0000343 clearTopDownPointers();
344 return;
345 }
346
John McCalld935e9c2011-06-15 23:37:01 +0000347 // For each entry in the other set, if our set has an entry with the same key,
348 // merge the entries. Otherwise, copy the entry and merge it with an empty
349 // entry.
Michael Gottesmana9fc0162015-03-05 23:29:06 +0000350 for (auto MI = Other.top_down_ptr_begin(), ME = Other.top_down_ptr_end();
351 MI != ME; ++MI) {
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000352 auto Pair = PerPtrTopDown.insert(*MI);
353 Pair.first->second.Merge(Pair.second ? TopDownPtrState() : MI->second,
John McCalld935e9c2011-06-15 23:37:01 +0000354 /*TopDown=*/true);
355 }
356
Dan Gohman7e315fc32011-08-11 21:06:32 +0000357 // For each entry in our set, if the other set doesn't have an entry with the
John McCalld935e9c2011-06-15 23:37:01 +0000358 // same key, force it to merge with an empty entry.
Michael Gottesmana9fc0162015-03-05 23:29:06 +0000359 for (auto MI = top_down_ptr_begin(), ME = top_down_ptr_end(); MI != ME; ++MI)
John McCalld935e9c2011-06-15 23:37:01 +0000360 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000361 MI->second.Merge(TopDownPtrState(), /*TopDown=*/true);
John McCalld935e9c2011-06-15 23:37:01 +0000362}
363
Michael Gottesman97e3df02013-01-14 00:35:14 +0000364/// The bottom-up traversal uses this to merge information about successors to
365/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +0000366void BBState::MergeSucc(const BBState &Other) {
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000367 if (BottomUpPathCount == OverflowOccurredValue)
368 return;
369
John McCalld935e9c2011-06-15 23:37:01 +0000370 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
371 // loop backedge. Loop backedges are special.
372 BottomUpPathCount += Other.BottomUpPathCount;
373
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000374 // In order to be consistent, we clear the top down pointers when by adding
375 // BottomUpPathCount becomes OverflowOccurredValue even though "true" overflow
Alp Tokercb402912014-01-24 17:20:08 +0000376 // has not occurred.
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000377 if (BottomUpPathCount == OverflowOccurredValue) {
378 clearBottomUpPointers();
379 return;
380 }
381
Michael Gottesman4385edf2013-01-14 01:47:53 +0000382 // Check for overflow. If we have overflow, fall back to conservative
383 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +0000384 if (BottomUpPathCount < Other.BottomUpPathCount) {
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000385 BottomUpPathCount = OverflowOccurredValue;
Dan Gohman7c84dad2012-09-12 20:45:17 +0000386 clearBottomUpPointers();
387 return;
388 }
389
John McCalld935e9c2011-06-15 23:37:01 +0000390 // For each entry in the other set, if our set has an entry with the
391 // same key, merge the entries. Otherwise, copy the entry and merge
392 // it with an empty entry.
Michael Gottesmana9fc0162015-03-05 23:29:06 +0000393 for (auto MI = Other.bottom_up_ptr_begin(), ME = Other.bottom_up_ptr_end();
394 MI != ME; ++MI) {
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000395 auto Pair = PerPtrBottomUp.insert(*MI);
396 Pair.first->second.Merge(Pair.second ? BottomUpPtrState() : MI->second,
John McCalld935e9c2011-06-15 23:37:01 +0000397 /*TopDown=*/false);
398 }
399
Dan Gohman7e315fc32011-08-11 21:06:32 +0000400 // For each entry in our set, if the other set doesn't have an entry
John McCalld935e9c2011-06-15 23:37:01 +0000401 // with the same key, force it to merge with an empty entry.
Michael Gottesmana9fc0162015-03-05 23:29:06 +0000402 for (auto MI = bottom_up_ptr_begin(), ME = bottom_up_ptr_end(); MI != ME;
403 ++MI)
John McCalld935e9c2011-06-15 23:37:01 +0000404 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000405 MI->second.Merge(BottomUpPtrState(), /*TopDown=*/false);
John McCalld935e9c2011-06-15 23:37:01 +0000406}
407
408namespace {
Michael Gottesman41c01002015-03-06 00:34:33 +0000409
Michael Gottesman97e3df02013-01-14 00:35:14 +0000410 /// \brief The main ARC optimization pass.
John McCalld935e9c2011-06-15 23:37:01 +0000411 class ObjCARCOpt : public FunctionPass {
412 bool Changed;
413 ProvenanceAnalysis PA;
Michael Gottesman41c01002015-03-06 00:34:33 +0000414
415 /// A cache of references to runtime entry point constants.
Michael Gottesman14acfac2013-07-06 01:39:23 +0000416 ARCRuntimeEntryPoints EP;
John McCalld935e9c2011-06-15 23:37:01 +0000417
Michael Gottesman41c01002015-03-06 00:34:33 +0000418 /// A cache of MDKinds that can be passed into other functions to propagate
419 /// MDKind identifiers.
420 ARCMDKindCache MDKindCache;
421
Michael Gottesman5a91bbf2013-05-24 20:44:02 +0000422 // This is used to track if a pointer is stored into an alloca.
423 DenseSet<const Value *> MultiOwnersSet;
424
Michael Gottesman97e3df02013-01-14 00:35:14 +0000425 /// A flag indicating whether this optimization pass should run.
Dan Gohmanceaac7c2011-06-20 23:20:43 +0000426 bool Run;
427
Michael Gottesman97e3df02013-01-14 00:35:14 +0000428 /// Flags which determine whether each of the interesting runtine functions
429 /// is in fact used in the current function.
John McCalld935e9c2011-06-15 23:37:01 +0000430 unsigned UsedInThisFunction;
431
John McCalld935e9c2011-06-15 23:37:01 +0000432 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
Michael Gottesman556ff612013-01-12 01:25:19 +0000433 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000434 ARCInstKind &Class);
John McCalld935e9c2011-06-15 23:37:01 +0000435 void OptimizeIndividualCalls(Function &F);
436
437 void CheckForCFGHazards(const BasicBlock *BB,
438 DenseMap<const BasicBlock *, BBState> &BBStates,
439 BBState &MyStates) const;
Michael Gottesman0be69202015-03-05 23:28:58 +0000440 bool VisitInstructionBottomUp(Instruction *Inst, BasicBlock *BB,
441 BlotMapVector<Value *, RRInfo> &Retains,
Dan Gohman817a7c62012-03-22 18:24:56 +0000442 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +0000443 bool VisitBottomUp(BasicBlock *BB,
444 DenseMap<const BasicBlock *, BBState> &BBStates,
Michael Gottesman0be69202015-03-05 23:28:58 +0000445 BlotMapVector<Value *, RRInfo> &Retains);
Dan Gohman817a7c62012-03-22 18:24:56 +0000446 bool VisitInstructionTopDown(Instruction *Inst,
447 DenseMap<Value *, RRInfo> &Releases,
448 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +0000449 bool VisitTopDown(BasicBlock *BB,
450 DenseMap<const BasicBlock *, BBState> &BBStates,
451 DenseMap<Value *, RRInfo> &Releases);
Michael Gottesman0be69202015-03-05 23:28:58 +0000452 bool Visit(Function &F, DenseMap<const BasicBlock *, BBState> &BBStates,
453 BlotMapVector<Value *, RRInfo> &Retains,
John McCalld935e9c2011-06-15 23:37:01 +0000454 DenseMap<Value *, RRInfo> &Releases);
455
456 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
Michael Gottesman0be69202015-03-05 23:28:58 +0000457 BlotMapVector<Value *, RRInfo> &Retains,
John McCalld935e9c2011-06-15 23:37:01 +0000458 DenseMap<Value *, RRInfo> &Releases,
Michael Gottesman0be69202015-03-05 23:28:58 +0000459 SmallVectorImpl<Instruction *> &DeadInsts, Module *M);
John McCalld935e9c2011-06-15 23:37:01 +0000460
Michael Gottesman9de6f962013-01-22 21:49:00 +0000461 bool ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState> &BBStates,
Michael Gottesman0be69202015-03-05 23:28:58 +0000462 BlotMapVector<Value *, RRInfo> &Retains,
463 DenseMap<Value *, RRInfo> &Releases, Module *M,
Craig Topperb94011f2013-07-14 04:42:23 +0000464 SmallVectorImpl<Instruction *> &NewRetains,
465 SmallVectorImpl<Instruction *> &NewReleases,
466 SmallVectorImpl<Instruction *> &DeadInsts,
Michael Gottesman0be69202015-03-05 23:28:58 +0000467 RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
468 Value *Arg, bool KnownSafe,
Michael Gottesman9de6f962013-01-22 21:49:00 +0000469 bool &AnyPairsCompletelyEliminated);
470
John McCalld935e9c2011-06-15 23:37:01 +0000471 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
Michael Gottesman0be69202015-03-05 23:28:58 +0000472 BlotMapVector<Value *, RRInfo> &Retains,
473 DenseMap<Value *, RRInfo> &Releases, Module *M);
John McCalld935e9c2011-06-15 23:37:01 +0000474
475 void OptimizeWeakCalls(Function &F);
476
477 bool OptimizeSequences(Function &F);
478
479 void OptimizeReturns(Function &F);
480
Michael Gottesman9c118152013-04-29 06:16:57 +0000481#ifndef NDEBUG
482 void GatherStatistics(Function &F, bool AfterOptimization = false);
483#endif
484
Craig Topper3e4c6972014-03-05 09:10:37 +0000485 void getAnalysisUsage(AnalysisUsage &AU) const override;
486 bool doInitialization(Module &M) override;
487 bool runOnFunction(Function &F) override;
488 void releaseMemory() override;
John McCalld935e9c2011-06-15 23:37:01 +0000489
490 public:
491 static char ID;
492 ObjCARCOpt() : FunctionPass(ID) {
493 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
494 }
495 };
496}
497
498char ObjCARCOpt::ID = 0;
499INITIALIZE_PASS_BEGIN(ObjCARCOpt,
500 "objc-arc", "ObjC ARC optimization", false, false)
501INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
502INITIALIZE_PASS_END(ObjCARCOpt,
503 "objc-arc", "ObjC ARC optimization", false, false)
504
505Pass *llvm::createObjCARCOptPass() {
506 return new ObjCARCOpt();
507}
508
509void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
510 AU.addRequired<ObjCARCAliasAnalysis>();
511 AU.addRequired<AliasAnalysis>();
512 // ARC optimization doesn't currently split critical edges.
513 AU.setPreservesCFG();
514}
515
Michael Gottesman97e3df02013-01-14 00:35:14 +0000516/// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is
517/// not a return value. Or, if it can be paired with an
518/// objc_autoreleaseReturnValue, delete the pair and return true.
John McCalld935e9c2011-06-15 23:37:01 +0000519bool
520ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +0000521 // Check for the argument being from an immediately preceding call or invoke.
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000522 const Value *Arg = GetArgRCIdentityRoot(RetainRV);
Dan Gohmandae33492012-04-27 18:56:31 +0000523 ImmutableCallSite CS(Arg);
524 if (const Instruction *Call = CS.getInstruction()) {
John McCalld935e9c2011-06-15 23:37:01 +0000525 if (Call->getParent() == RetainRV->getParent()) {
Dan Gohmandae33492012-04-27 18:56:31 +0000526 BasicBlock::const_iterator I = Call;
John McCalld935e9c2011-06-15 23:37:01 +0000527 ++I;
Michael Gottesman65c24812013-03-25 09:27:43 +0000528 while (IsNoopInstruction(I)) ++I;
John McCalld935e9c2011-06-15 23:37:01 +0000529 if (&*I == RetainRV)
530 return false;
Dan Gohmandae33492012-04-27 18:56:31 +0000531 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +0000532 BasicBlock *RetainRVParent = RetainRV->getParent();
533 if (II->getNormalDest() == RetainRVParent) {
Dan Gohmandae33492012-04-27 18:56:31 +0000534 BasicBlock::const_iterator I = RetainRVParent->begin();
Michael Gottesman65c24812013-03-25 09:27:43 +0000535 while (IsNoopInstruction(I)) ++I;
Dan Gohmane3ed2b02012-03-23 18:09:00 +0000536 if (&*I == RetainRV)
537 return false;
538 }
John McCalld935e9c2011-06-15 23:37:01 +0000539 }
Dan Gohmane3ed2b02012-03-23 18:09:00 +0000540 }
John McCalld935e9c2011-06-15 23:37:01 +0000541
542 // Check for being preceded by an objc_autoreleaseReturnValue on the same
543 // pointer. In this case, we can delete the pair.
544 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
545 if (I != Begin) {
Michael Gottesman65c24812013-03-25 09:27:43 +0000546 do --I; while (I != Begin && IsNoopInstruction(I));
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000547 if (GetBasicARCInstKind(I) == ARCInstKind::AutoreleaseRV &&
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000548 GetArgRCIdentityRoot(I) == Arg) {
John McCalld935e9c2011-06-15 23:37:01 +0000549 Changed = true;
550 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +0000551
Michael Gottesman89279f82013-04-05 18:10:41 +0000552 DEBUG(dbgs() << "Erasing autoreleaseRV,retainRV pair: " << *I << "\n"
553 << "Erasing " << *RetainRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +0000554
John McCalld935e9c2011-06-15 23:37:01 +0000555 EraseInstruction(I);
556 EraseInstruction(RetainRV);
557 return true;
558 }
559 }
560
561 // Turn it to a plain objc_retain.
562 Changed = true;
563 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +0000564
Michael Gottesman89279f82013-04-05 18:10:41 +0000565 DEBUG(dbgs() << "Transforming objc_retainAutoreleasedReturnValue => "
Michael Gottesmandef07bb2013-01-05 17:55:42 +0000566 "objc_retain since the operand is not a return value.\n"
Michael Gottesman89279f82013-04-05 18:10:41 +0000567 "Old = " << *RetainRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +0000568
Michael Gottesman14acfac2013-07-06 01:39:23 +0000569 Constant *NewDecl = EP.get(ARCRuntimeEntryPoints::EPT_Retain);
570 cast<CallInst>(RetainRV)->setCalledFunction(NewDecl);
Michael Gottesmandef07bb2013-01-05 17:55:42 +0000571
Michael Gottesman89279f82013-04-05 18:10:41 +0000572 DEBUG(dbgs() << "New = " << *RetainRV << "\n");
Michael Gottesmandef07bb2013-01-05 17:55:42 +0000573
John McCalld935e9c2011-06-15 23:37:01 +0000574 return false;
575}
576
Michael Gottesman97e3df02013-01-14 00:35:14 +0000577/// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not
578/// used as a return value.
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000579void ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F,
580 Instruction *AutoreleaseRV,
581 ARCInstKind &Class) {
John McCalld935e9c2011-06-15 23:37:01 +0000582 // Check for a return of the pointer value.
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000583 const Value *Ptr = GetArgRCIdentityRoot(AutoreleaseRV);
Dan Gohman10a18d52011-08-12 00:36:31 +0000584 SmallVector<const Value *, 2> Users;
585 Users.push_back(Ptr);
586 do {
587 Ptr = Users.pop_back_val();
Chandler Carruthcdf47882014-03-09 03:16:01 +0000588 for (const User *U : Ptr->users()) {
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000589 if (isa<ReturnInst>(U) || GetBasicARCInstKind(U) == ARCInstKind::RetainRV)
Dan Gohman10a18d52011-08-12 00:36:31 +0000590 return;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000591 if (isa<BitCastInst>(U))
592 Users.push_back(U);
Dan Gohman10a18d52011-08-12 00:36:31 +0000593 }
594 } while (!Users.empty());
John McCalld935e9c2011-06-15 23:37:01 +0000595
596 Changed = true;
597 ++NumPeeps;
Michael Gottesman1bf69082013-01-06 21:07:11 +0000598
Michael Gottesman89279f82013-04-05 18:10:41 +0000599 DEBUG(dbgs() << "Transforming objc_autoreleaseReturnValue => "
Michael Gottesman1bf69082013-01-06 21:07:11 +0000600 "objc_autorelease since its operand is not used as a return "
601 "value.\n"
Michael Gottesman89279f82013-04-05 18:10:41 +0000602 "Old = " << *AutoreleaseRV << "\n");
Michael Gottesman1bf69082013-01-06 21:07:11 +0000603
Michael Gottesmanc9656fa2013-01-12 01:25:15 +0000604 CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
Michael Gottesman14acfac2013-07-06 01:39:23 +0000605 Constant *NewDecl = EP.get(ARCRuntimeEntryPoints::EPT_Autorelease);
606 AutoreleaseRVCI->setCalledFunction(NewDecl);
Michael Gottesmanc9656fa2013-01-12 01:25:15 +0000607 AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000608 Class = ARCInstKind::Autorelease;
Michael Gottesman10426b52013-01-07 21:26:07 +0000609
Michael Gottesman89279f82013-04-05 18:10:41 +0000610 DEBUG(dbgs() << "New: " << *AutoreleaseRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +0000611
John McCalld935e9c2011-06-15 23:37:01 +0000612}
613
Michael Gottesman97e3df02013-01-14 00:35:14 +0000614/// Visit each call, one at a time, and make simplifications without doing any
615/// additional analysis.
John McCalld935e9c2011-06-15 23:37:01 +0000616void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
Michael Gottesman89279f82013-04-05 18:10:41 +0000617 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeIndividualCalls ==\n");
John McCalld935e9c2011-06-15 23:37:01 +0000618 // Reset all the flags in preparation for recomputing them.
619 UsedInThisFunction = 0;
620
621 // Visit all objc_* calls in F.
622 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
623 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +0000624
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000625 ARCInstKind Class = GetBasicARCInstKind(Inst);
John McCalld935e9c2011-06-15 23:37:01 +0000626
Michael Gottesman89279f82013-04-05 18:10:41 +0000627 DEBUG(dbgs() << "Visiting: Class: " << Class << "; " << *Inst << "\n");
Michael Gottesman782e3442013-01-17 18:32:34 +0000628
John McCalld935e9c2011-06-15 23:37:01 +0000629 switch (Class) {
630 default: break;
631
632 // Delete no-op casts. These function calls have special semantics, but
633 // the semantics are entirely implemented via lowering in the front-end,
634 // so by the time they reach the optimizer, they are just no-op calls
635 // which return their argument.
636 //
637 // There are gray areas here, as the ability to cast reference-counted
638 // pointers to raw void* and back allows code to break ARC assumptions,
639 // however these are currently considered to be unimportant.
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000640 case ARCInstKind::NoopCast:
John McCalld935e9c2011-06-15 23:37:01 +0000641 Changed = true;
642 ++NumNoops;
Michael Gottesman89279f82013-04-05 18:10:41 +0000643 DEBUG(dbgs() << "Erasing no-op cast: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +0000644 EraseInstruction(Inst);
645 continue;
646
647 // If the pointer-to-weak-pointer is null, it's undefined behavior.
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000648 case ARCInstKind::StoreWeak:
649 case ARCInstKind::LoadWeak:
650 case ARCInstKind::LoadWeakRetained:
651 case ARCInstKind::InitWeak:
652 case ARCInstKind::DestroyWeak: {
John McCalld935e9c2011-06-15 23:37:01 +0000653 CallInst *CI = cast<CallInst>(Inst);
Michael Gottesman65c24812013-03-25 09:27:43 +0000654 if (IsNullOrUndef(CI->getArgOperand(0))) {
Dan Gohman670f9372012-04-13 18:57:48 +0000655 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +0000656 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +0000657 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
658 Constant::getNullValue(Ty),
659 CI);
Michael Gottesman10426b52013-01-07 21:26:07 +0000660 llvm::Value *NewValue = UndefValue::get(CI->getType());
Michael Gottesman89279f82013-04-05 18:10:41 +0000661 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
662 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
Michael Gottesmanfec61c02013-01-06 21:54:30 +0000663 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +0000664 CI->eraseFromParent();
665 continue;
666 }
667 break;
668 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000669 case ARCInstKind::CopyWeak:
670 case ARCInstKind::MoveWeak: {
John McCalld935e9c2011-06-15 23:37:01 +0000671 CallInst *CI = cast<CallInst>(Inst);
Michael Gottesman65c24812013-03-25 09:27:43 +0000672 if (IsNullOrUndef(CI->getArgOperand(0)) ||
673 IsNullOrUndef(CI->getArgOperand(1))) {
Dan Gohman670f9372012-04-13 18:57:48 +0000674 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +0000675 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +0000676 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
677 Constant::getNullValue(Ty),
678 CI);
Michael Gottesmanfec61c02013-01-06 21:54:30 +0000679
680 llvm::Value *NewValue = UndefValue::get(CI->getType());
Michael Gottesman89279f82013-04-05 18:10:41 +0000681 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
682 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +0000683
Michael Gottesmanfec61c02013-01-06 21:54:30 +0000684 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +0000685 CI->eraseFromParent();
686 continue;
687 }
688 break;
689 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000690 case ARCInstKind::RetainRV:
John McCalld935e9c2011-06-15 23:37:01 +0000691 if (OptimizeRetainRVCall(F, Inst))
692 continue;
693 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000694 case ARCInstKind::AutoreleaseRV:
Michael Gottesman556ff612013-01-12 01:25:19 +0000695 OptimizeAutoreleaseRVCall(F, Inst, Class);
John McCalld935e9c2011-06-15 23:37:01 +0000696 break;
697 }
698
Michael Gottesmanb8c88362013-04-03 02:57:24 +0000699 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
John McCalld935e9c2011-06-15 23:37:01 +0000700 if (IsAutorelease(Class) && Inst->use_empty()) {
701 CallInst *Call = cast<CallInst>(Inst);
702 const Value *Arg = Call->getArgOperand(0);
703 Arg = FindSingleUseIdentifiedObject(Arg);
704 if (Arg) {
705 Changed = true;
706 ++NumAutoreleases;
707
708 // Create the declaration lazily.
709 LLVMContext &C = Inst->getContext();
Michael Gottesman01df4502013-07-06 01:41:35 +0000710
Michael Gottesman14acfac2013-07-06 01:39:23 +0000711 Constant *Decl = EP.get(ARCRuntimeEntryPoints::EPT_Release);
712 CallInst *NewCall = CallInst::Create(Decl, Call->getArgOperand(0), "",
713 Call);
Michael Gottesman41c01002015-03-06 00:34:33 +0000714 NewCall->setMetadata(MDKindCache.ImpreciseReleaseMDKind,
715 MDNode::get(C, None));
Michael Gottesman10426b52013-01-07 21:26:07 +0000716
Michael Gottesman89279f82013-04-05 18:10:41 +0000717 DEBUG(dbgs() << "Replacing autorelease{,RV}(x) with objc_release(x) "
718 "since x is otherwise unused.\nOld: " << *Call << "\nNew: "
719 << *NewCall << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +0000720
John McCalld935e9c2011-06-15 23:37:01 +0000721 EraseInstruction(Call);
722 Inst = NewCall;
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000723 Class = ARCInstKind::Release;
John McCalld935e9c2011-06-15 23:37:01 +0000724 }
725 }
726
727 // For functions which can never be passed stack arguments, add
728 // a tail keyword.
729 if (IsAlwaysTail(Class)) {
730 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +0000731 DEBUG(dbgs() << "Adding tail keyword to function since it can never be "
732 "passed stack args: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +0000733 cast<CallInst>(Inst)->setTailCall();
734 }
735
Michael Gottesmanc9656fa2013-01-12 01:25:15 +0000736 // Ensure that functions that can never have a "tail" keyword due to the
737 // semantics of ARC truly do not do so.
738 if (IsNeverTail(Class)) {
739 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +0000740 DEBUG(dbgs() << "Removing tail keyword from function: " << *Inst <<
Michael Gottesmanc9656fa2013-01-12 01:25:15 +0000741 "\n");
742 cast<CallInst>(Inst)->setTailCall(false);
743 }
744
John McCalld935e9c2011-06-15 23:37:01 +0000745 // Set nounwind as needed.
746 if (IsNoThrow(Class)) {
747 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +0000748 DEBUG(dbgs() << "Found no throw class. Setting nounwind on: " << *Inst
749 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +0000750 cast<CallInst>(Inst)->setDoesNotThrow();
751 }
752
753 if (!IsNoopOnNull(Class)) {
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000754 UsedInThisFunction |= 1 << unsigned(Class);
John McCalld935e9c2011-06-15 23:37:01 +0000755 continue;
756 }
757
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000758 const Value *Arg = GetArgRCIdentityRoot(Inst);
John McCalld935e9c2011-06-15 23:37:01 +0000759
760 // ARC calls with null are no-ops. Delete them.
Michael Gottesman65c24812013-03-25 09:27:43 +0000761 if (IsNullOrUndef(Arg)) {
John McCalld935e9c2011-06-15 23:37:01 +0000762 Changed = true;
763 ++NumNoops;
Michael Gottesman89279f82013-04-05 18:10:41 +0000764 DEBUG(dbgs() << "ARC calls with null are no-ops. Erasing: " << *Inst
765 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +0000766 EraseInstruction(Inst);
767 continue;
768 }
769
770 // Keep track of which of retain, release, autorelease, and retain_block
771 // are actually present in this function.
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000772 UsedInThisFunction |= 1 << unsigned(Class);
John McCalld935e9c2011-06-15 23:37:01 +0000773
774 // If Arg is a PHI, and one or more incoming values to the
775 // PHI are null, and the call is control-equivalent to the PHI, and there
776 // are no relevant side effects between the PHI and the call, the call
777 // could be pushed up to just those paths with non-null incoming values.
778 // For now, don't bother splitting critical edges for this.
779 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
780 Worklist.push_back(std::make_pair(Inst, Arg));
781 do {
782 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
783 Inst = Pair.first;
784 Arg = Pair.second;
785
786 const PHINode *PN = dyn_cast<PHINode>(Arg);
787 if (!PN) continue;
788
789 // Determine if the PHI has any null operands, or any incoming
790 // critical edges.
791 bool HasNull = false;
792 bool HasCriticalEdges = false;
793 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
794 Value *Incoming =
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000795 GetRCIdentityRoot(PN->getIncomingValue(i));
Michael Gottesman65c24812013-03-25 09:27:43 +0000796 if (IsNullOrUndef(Incoming))
John McCalld935e9c2011-06-15 23:37:01 +0000797 HasNull = true;
798 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
799 .getNumSuccessors() != 1) {
800 HasCriticalEdges = true;
801 break;
802 }
803 }
804 // If we have null operands and no critical edges, optimize.
805 if (!HasCriticalEdges && HasNull) {
806 SmallPtrSet<Instruction *, 4> DependingInstructions;
807 SmallPtrSet<const BasicBlock *, 4> Visited;
808
809 // Check that there is nothing that cares about the reference
810 // count between the call and the phi.
Dan Gohman8478d762012-04-13 00:59:57 +0000811 switch (Class) {
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000812 case ARCInstKind::Retain:
813 case ARCInstKind::RetainBlock:
Dan Gohman8478d762012-04-13 00:59:57 +0000814 // These can always be moved up.
815 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000816 case ARCInstKind::Release:
Dan Gohman41375a32012-05-08 23:39:44 +0000817 // These can't be moved across things that care about the retain
818 // count.
Dan Gohman8478d762012-04-13 00:59:57 +0000819 FindDependencies(NeedsPositiveRetainCount, Arg,
820 Inst->getParent(), Inst,
821 DependingInstructions, Visited, PA);
822 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000823 case ARCInstKind::Autorelease:
Dan Gohman8478d762012-04-13 00:59:57 +0000824 // These can't be moved across autorelease pool scope boundaries.
825 FindDependencies(AutoreleasePoolBoundary, Arg,
826 Inst->getParent(), Inst,
827 DependingInstructions, Visited, PA);
828 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000829 case ARCInstKind::RetainRV:
830 case ARCInstKind::AutoreleaseRV:
Dan Gohman8478d762012-04-13 00:59:57 +0000831 // Don't move these; the RV optimization depends on the autoreleaseRV
832 // being tail called, and the retainRV being immediately after a call
833 // (which might still happen if we get lucky with codegen layout, but
834 // it's not worth taking the chance).
835 continue;
836 default:
837 llvm_unreachable("Invalid dependence flavor");
838 }
839
John McCalld935e9c2011-06-15 23:37:01 +0000840 if (DependingInstructions.size() == 1 &&
841 *DependingInstructions.begin() == PN) {
842 Changed = true;
843 ++NumPartialNoops;
844 // Clone the call into each predecessor that has a non-null value.
845 CallInst *CInst = cast<CallInst>(Inst);
Chris Lattner229907c2011-07-18 04:54:35 +0000846 Type *ParamTy = CInst->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +0000847 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
848 Value *Incoming =
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000849 GetRCIdentityRoot(PN->getIncomingValue(i));
Michael Gottesman65c24812013-03-25 09:27:43 +0000850 if (!IsNullOrUndef(Incoming)) {
John McCalld935e9c2011-06-15 23:37:01 +0000851 CallInst *Clone = cast<CallInst>(CInst->clone());
852 Value *Op = PN->getIncomingValue(i);
853 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
854 if (Op->getType() != ParamTy)
855 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
856 Clone->setArgOperand(0, Op);
857 Clone->insertBefore(InsertPos);
Michael Gottesmanc189a392013-01-09 19:23:24 +0000858
Michael Gottesman89279f82013-04-05 18:10:41 +0000859 DEBUG(dbgs() << "Cloning "
Michael Gottesmanc189a392013-01-09 19:23:24 +0000860 << *CInst << "\n"
Michael Gottesman89279f82013-04-05 18:10:41 +0000861 "And inserting clone at " << *InsertPos << "\n");
John McCalld935e9c2011-06-15 23:37:01 +0000862 Worklist.push_back(std::make_pair(Clone, Incoming));
863 }
864 }
865 // Erase the original call.
Michael Gottesmanc189a392013-01-09 19:23:24 +0000866 DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +0000867 EraseInstruction(CInst);
868 continue;
869 }
870 }
871 } while (!Worklist.empty());
872 }
873}
874
Michael Gottesman323964c2013-04-18 05:39:45 +0000875/// If we have a top down pointer in the S_Use state, make sure that there are
876/// no CFG hazards by checking the states of various bottom up pointers.
877static void CheckForUseCFGHazard(const Sequence SuccSSeq,
878 const bool SuccSRRIKnownSafe,
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000879 TopDownPtrState &S,
Michael Gottesman323964c2013-04-18 05:39:45 +0000880 bool &SomeSuccHasSame,
881 bool &AllSuccsHaveSame,
Michael Gottesmane67f40c2013-05-24 20:44:05 +0000882 bool &NotAllSeqEqualButKnownSafe,
Michael Gottesman323964c2013-04-18 05:39:45 +0000883 bool &ShouldContinue) {
884 switch (SuccSSeq) {
885 case S_CanRelease: {
Michael Gottesman93132252013-06-21 06:59:02 +0000886 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe) {
Michael Gottesman323964c2013-04-18 05:39:45 +0000887 S.ClearSequenceProgress();
888 break;
889 }
Michael Gottesman2f294592013-06-21 19:12:36 +0000890 S.SetCFGHazardAfflicted(true);
Michael Gottesman323964c2013-04-18 05:39:45 +0000891 ShouldContinue = true;
892 break;
893 }
894 case S_Use:
895 SomeSuccHasSame = true;
896 break;
897 case S_Stop:
898 case S_Release:
899 case S_MovableRelease:
Michael Gottesman93132252013-06-21 06:59:02 +0000900 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe)
Michael Gottesman323964c2013-04-18 05:39:45 +0000901 AllSuccsHaveSame = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +0000902 else
903 NotAllSeqEqualButKnownSafe = true;
Michael Gottesman323964c2013-04-18 05:39:45 +0000904 break;
905 case S_Retain:
906 llvm_unreachable("bottom-up pointer in retain state!");
907 case S_None:
908 llvm_unreachable("This should have been handled earlier.");
909 }
910}
911
912/// If we have a Top Down pointer in the S_CanRelease state, make sure that
913/// there are no CFG hazards by checking the states of various bottom up
914/// pointers.
915static void CheckForCanReleaseCFGHazard(const Sequence SuccSSeq,
916 const bool SuccSRRIKnownSafe,
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000917 TopDownPtrState &S,
Michael Gottesman323964c2013-04-18 05:39:45 +0000918 bool &SomeSuccHasSame,
Michael Gottesmane67f40c2013-05-24 20:44:05 +0000919 bool &AllSuccsHaveSame,
920 bool &NotAllSeqEqualButKnownSafe) {
Michael Gottesman323964c2013-04-18 05:39:45 +0000921 switch (SuccSSeq) {
922 case S_CanRelease:
923 SomeSuccHasSame = true;
924 break;
925 case S_Stop:
926 case S_Release:
927 case S_MovableRelease:
928 case S_Use:
Michael Gottesman93132252013-06-21 06:59:02 +0000929 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe)
Michael Gottesman323964c2013-04-18 05:39:45 +0000930 AllSuccsHaveSame = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +0000931 else
932 NotAllSeqEqualButKnownSafe = true;
Michael Gottesman323964c2013-04-18 05:39:45 +0000933 break;
934 case S_Retain:
935 llvm_unreachable("bottom-up pointer in retain state!");
936 case S_None:
937 llvm_unreachable("This should have been handled earlier.");
938 }
939}
940
Michael Gottesman97e3df02013-01-14 00:35:14 +0000941/// Check for critical edges, loop boundaries, irreducible control flow, or
942/// other CFG structures where moving code across the edge would result in it
943/// being executed more.
John McCalld935e9c2011-06-15 23:37:01 +0000944void
945ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
946 DenseMap<const BasicBlock *, BBState> &BBStates,
947 BBState &MyStates) const {
948 // If any top-down local-use or possible-dec has a succ which is earlier in
949 // the sequence, forget it.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000950 for (auto I = MyStates.top_down_ptr_begin(), E = MyStates.top_down_ptr_end();
951 I != E; ++I) {
952 TopDownPtrState &S = I->second;
Michael Gottesman323964c2013-04-18 05:39:45 +0000953 const Sequence Seq = I->second.GetSeq();
Dan Gohman0155f302012-02-17 18:59:53 +0000954
Michael Gottesman323964c2013-04-18 05:39:45 +0000955 // We only care about S_Retain, S_CanRelease, and S_Use.
956 if (Seq == S_None)
957 continue;
Dan Gohman0155f302012-02-17 18:59:53 +0000958
Michael Gottesman323964c2013-04-18 05:39:45 +0000959 // Make sure that if extra top down states are added in the future that this
960 // code is updated to handle it.
961 assert((Seq == S_Retain || Seq == S_CanRelease || Seq == S_Use) &&
962 "Unknown top down sequence state.");
963
964 const Value *Arg = I->first;
965 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
966 bool SomeSuccHasSame = false;
967 bool AllSuccsHaveSame = true;
Michael Gottesmane67f40c2013-05-24 20:44:05 +0000968 bool NotAllSeqEqualButKnownSafe = false;
Michael Gottesman323964c2013-04-18 05:39:45 +0000969
970 succ_const_iterator SI(TI), SE(TI, false);
971
972 for (; SI != SE; ++SI) {
973 // If VisitBottomUp has pointer information for this successor, take
974 // what we know about it.
975 const DenseMap<const BasicBlock *, BBState>::iterator BBI =
976 BBStates.find(*SI);
977 assert(BBI != BBStates.end());
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000978 const BottomUpPtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
Michael Gottesman323964c2013-04-18 05:39:45 +0000979 const Sequence SuccSSeq = SuccS.GetSeq();
980
981 // If bottom up, the pointer is in an S_None state, clear the sequence
982 // progress since the sequence in the bottom up state finished
983 // suggesting a mismatch in between retains/releases. This is true for
984 // all three cases that we are handling here: S_Retain, S_Use, and
985 // S_CanRelease.
986 if (SuccSSeq == S_None) {
Dan Gohman12130272011-08-12 00:26:31 +0000987 S.ClearSequenceProgress();
Michael Gottesman323964c2013-04-18 05:39:45 +0000988 continue;
989 }
990
991 // If we have S_Use or S_CanRelease, perform our check for cfg hazard
992 // checks.
Michael Gottesman93132252013-06-21 06:59:02 +0000993 const bool SuccSRRIKnownSafe = SuccS.IsKnownSafe();
Michael Gottesman323964c2013-04-18 05:39:45 +0000994
995 // *NOTE* We do not use Seq from above here since we are allowing for
996 // S.GetSeq() to change while we are visiting basic blocks.
997 switch(S.GetSeq()) {
998 case S_Use: {
999 bool ShouldContinue = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001000 CheckForUseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S, SomeSuccHasSame,
1001 AllSuccsHaveSame, NotAllSeqEqualButKnownSafe,
Michael Gottesman323964c2013-04-18 05:39:45 +00001002 ShouldContinue);
1003 if (ShouldContinue)
1004 continue;
1005 break;
1006 }
1007 case S_CanRelease: {
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001008 CheckForCanReleaseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S,
1009 SomeSuccHasSame, AllSuccsHaveSame,
1010 NotAllSeqEqualButKnownSafe);
Michael Gottesman323964c2013-04-18 05:39:45 +00001011 break;
1012 }
1013 case S_Retain:
1014 case S_None:
1015 case S_Stop:
1016 case S_Release:
1017 case S_MovableRelease:
1018 break;
1019 }
John McCalld935e9c2011-06-15 23:37:01 +00001020 }
Michael Gottesman323964c2013-04-18 05:39:45 +00001021
1022 // If the state at the other end of any of the successor edges
1023 // matches the current state, require all edges to match. This
1024 // guards against loops in the middle of a sequence.
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001025 if (SomeSuccHasSame && !AllSuccsHaveSame) {
Michael Gottesman323964c2013-04-18 05:39:45 +00001026 S.ClearSequenceProgress();
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001027 } else if (NotAllSeqEqualButKnownSafe) {
1028 // If we would have cleared the state foregoing the fact that we are known
1029 // safe, stop code motion. This is because whether or not it is safe to
1030 // remove RR pairs via KnownSafe is an orthogonal concept to whether we
1031 // are allowed to perform code motion.
Michael Gottesman2f294592013-06-21 19:12:36 +00001032 S.SetCFGHazardAfflicted(true);
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001033 }
Michael Gottesman323964c2013-04-18 05:39:45 +00001034 }
John McCalld935e9c2011-06-15 23:37:01 +00001035}
1036
Michael Gottesman0be69202015-03-05 23:28:58 +00001037bool ObjCARCOpt::VisitInstructionBottomUp(
1038 Instruction *Inst, BasicBlock *BB, BlotMapVector<Value *, RRInfo> &Retains,
1039 BBState &MyStates) {
Dan Gohman817a7c62012-03-22 18:24:56 +00001040 bool NestingDetected = false;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001041 ARCInstKind Class = GetARCInstKind(Inst);
Craig Topperf40110f2014-04-25 05:29:35 +00001042 const Value *Arg = nullptr;
Michael Gottesman79249972013-04-05 23:46:45 +00001043
Michael Gottesman1d8d2572013-04-05 22:54:28 +00001044 DEBUG(dbgs() << "Class: " << Class << "\n");
Michael Gottesman79249972013-04-05 23:46:45 +00001045
Dan Gohman817a7c62012-03-22 18:24:56 +00001046 switch (Class) {
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001047 case ARCInstKind::Release: {
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001048 Arg = GetArgRCIdentityRoot(Inst);
Dan Gohman817a7c62012-03-22 18:24:56 +00001049
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001050 BottomUpPtrState &S = MyStates.getPtrBottomUpState(Arg);
Michael Gottesman4eae3962015-03-06 00:34:39 +00001051 NestingDetected |= S.InitBottomUp(MDKindCache, Inst);
Dan Gohman817a7c62012-03-22 18:24:56 +00001052 break;
1053 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001054 case ARCInstKind::RetainBlock:
Michael Gottesman158fdf62013-03-28 20:11:19 +00001055 // In OptimizeIndividualCalls, we have strength reduced all optimizable
1056 // objc_retainBlocks to objc_retains. Thus at this point any
1057 // objc_retainBlocks that we see are not optimizable.
1058 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001059 case ARCInstKind::Retain:
1060 case ARCInstKind::RetainRV: {
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001061 Arg = GetArgRCIdentityRoot(Inst);
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001062 BottomUpPtrState &S = MyStates.getPtrBottomUpState(Arg);
Michael Gottesman60805962015-03-06 00:34:42 +00001063 if (S.MatchWithRetain()) {
1064 // Don't do retain+release tracking for ARCInstKind::RetainRV, because
1065 // it's better to let it remain as the first instruction after a call.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001066 if (Class != ARCInstKind::RetainRV)
Michael Gottesmane3943d02013-06-21 19:44:30 +00001067 Retains[Inst] = S.GetRRInfo();
Dan Gohman817a7c62012-03-22 18:24:56 +00001068 S.ClearSequenceProgress();
Dan Gohman817a7c62012-03-22 18:24:56 +00001069 }
Michael Gottesman31ba23a2013-04-05 22:54:32 +00001070 // A retain moving bottom up can be a use.
1071 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001072 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001073 case ARCInstKind::AutoreleasepoolPop:
Dan Gohman817a7c62012-03-22 18:24:56 +00001074 // Conservatively, clear MyStates for all known pointers.
1075 MyStates.clearBottomUpPointers();
1076 return NestingDetected;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001077 case ARCInstKind::AutoreleasepoolPush:
1078 case ARCInstKind::None:
Dan Gohman817a7c62012-03-22 18:24:56 +00001079 // These are irrelevant.
1080 return NestingDetected;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001081 case ARCInstKind::User:
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001082 // If we have a store into an alloca of a pointer we are tracking, the
1083 // pointer has multiple owners implying that we must be more conservative.
1084 //
1085 // This comes up in the context of a pointer being ``KnownSafe''. In the
Alp Tokercb402912014-01-24 17:20:08 +00001086 // presence of a block being initialized, the frontend will emit the
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001087 // objc_retain on the original pointer and the release on the pointer loaded
1088 // from the alloca. The optimizer will through the provenance analysis
1089 // realize that the two are related, but since we only require KnownSafe in
1090 // one direction, will match the inner retain on the original pointer with
1091 // the guard release on the original pointer. This is fixed by ensuring that
Alp Tokercb402912014-01-24 17:20:08 +00001092 // in the presence of allocas we only unconditionally remove pointers if
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001093 // both our retain and our release are KnownSafe.
1094 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1095 if (AreAnyUnderlyingObjectsAnAlloca(SI->getPointerOperand())) {
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001096 auto I = MyStates.findPtrBottomUpState(
1097 GetRCIdentityRoot(SI->getValueOperand()));
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001098 if (I != MyStates.bottom_up_ptr_end())
Michael Gottesman5a91bbf2013-05-24 20:44:02 +00001099 MultiOwnersSet.insert(I->first);
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001100 }
1101 }
1102 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001103 default:
1104 break;
1105 }
1106
1107 // Consider any other possible effects of this instruction on each
1108 // pointer being tracked.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001109 for (auto MI = MyStates.bottom_up_ptr_begin(),
1110 ME = MyStates.bottom_up_ptr_end();
1111 MI != ME; ++MI) {
Dan Gohman817a7c62012-03-22 18:24:56 +00001112 const Value *Ptr = MI->first;
1113 if (Ptr == Arg)
1114 continue; // Handled above.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001115 BottomUpPtrState &S = MI->second;
Dan Gohman817a7c62012-03-22 18:24:56 +00001116 Sequence Seq = S.GetSeq();
1117
1118 // Check for possible releases.
1119 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001120 DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr
1121 << "\n");
Michael Gottesman764b1cf2013-03-23 05:46:19 +00001122 S.ClearKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001123 switch (Seq) {
1124 case S_Use:
1125 S.SetSeq(S_CanRelease);
1126 continue;
1127 case S_CanRelease:
1128 case S_Release:
1129 case S_MovableRelease:
1130 case S_Stop:
1131 case S_None:
1132 break;
1133 case S_Retain:
1134 llvm_unreachable("bottom-up pointer in retain state!");
1135 }
1136 }
1137
1138 // Check for possible direct uses.
1139 switch (Seq) {
1140 case S_Release:
1141 case S_MovableRelease:
1142 if (CanUse(Inst, Ptr, PA, Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001143 DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr
1144 << "\n");
Michael Gottesman4f6ef112013-06-21 19:44:27 +00001145 assert(!S.HasReverseInsertPts());
Dan Gohman5c70fad2012-03-23 17:47:54 +00001146 // If this is an invoke instruction, we're scanning it as part of
1147 // one of its successor blocks, since we can't insert code after it
1148 // in its own block, and we don't want to split critical edges.
1149 if (isa<InvokeInst>(Inst))
Michael Gottesman4f6ef112013-06-21 19:44:27 +00001150 S.InsertReverseInsertPt(BB->getFirstInsertionPt());
Dan Gohman5c70fad2012-03-23 17:47:54 +00001151 else
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001152 S.InsertReverseInsertPt(std::next(BasicBlock::iterator(Inst)));
Dan Gohman817a7c62012-03-22 18:24:56 +00001153 S.SetSeq(S_Use);
John McCall20182ac2013-03-22 21:38:36 +00001154 } else if (Seq == S_Release && IsUser(Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001155 DEBUG(dbgs() << "PreciseReleaseUse: Seq: " << Seq << "; " << *Ptr
1156 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00001157 // Non-movable releases depend on any possible objc pointer use.
1158 S.SetSeq(S_Stop);
Michael Gottesman4f6ef112013-06-21 19:44:27 +00001159 assert(!S.HasReverseInsertPts());
Dan Gohman5c70fad2012-03-23 17:47:54 +00001160 // As above; handle invoke specially.
1161 if (isa<InvokeInst>(Inst))
Michael Gottesman4f6ef112013-06-21 19:44:27 +00001162 S.InsertReverseInsertPt(BB->getFirstInsertionPt());
Dan Gohman5c70fad2012-03-23 17:47:54 +00001163 else
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001164 S.InsertReverseInsertPt(std::next(BasicBlock::iterator(Inst)));
Dan Gohman817a7c62012-03-22 18:24:56 +00001165 }
1166 break;
1167 case S_Stop:
Michael Gottesman81b1d432013-03-26 00:42:04 +00001168 if (CanUse(Inst, Ptr, PA, Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001169 DEBUG(dbgs() << "PreciseStopUse: Seq: " << Seq << "; " << *Ptr
1170 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00001171 S.SetSeq(S_Use);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001172 }
Dan Gohman817a7c62012-03-22 18:24:56 +00001173 break;
1174 case S_CanRelease:
1175 case S_Use:
1176 case S_None:
1177 break;
1178 case S_Retain:
1179 llvm_unreachable("bottom-up pointer in retain state!");
1180 }
1181 }
1182
1183 return NestingDetected;
1184}
1185
Michael Gottesman0be69202015-03-05 23:28:58 +00001186bool ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
1187 DenseMap<const BasicBlock *, BBState> &BBStates,
1188 BlotMapVector<Value *, RRInfo> &Retains) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001189
1190 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitBottomUp ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00001191
John McCalld935e9c2011-06-15 23:37:01 +00001192 bool NestingDetected = false;
1193 BBState &MyStates = BBStates[BB];
1194
1195 // Merge the states from each successor to compute the initial state
1196 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00001197 BBState::edge_iterator SI(MyStates.succ_begin()),
1198 SE(MyStates.succ_end());
1199 if (SI != SE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001200 const BasicBlock *Succ = *SI;
1201 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
1202 assert(I != BBStates.end());
1203 MyStates.InitFromSucc(I->second);
1204 ++SI;
1205 for (; SI != SE; ++SI) {
1206 Succ = *SI;
1207 I = BBStates.find(Succ);
1208 assert(I != BBStates.end());
1209 MyStates.MergeSucc(I->second);
1210 }
Michael Gottesman60f6b282013-03-29 05:13:07 +00001211 }
Michael Gottesmancd4de0f2013-03-26 00:42:09 +00001212
John McCalld935e9c2011-06-15 23:37:01 +00001213 // Visit all the instructions, bottom-up.
1214 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001215 Instruction *Inst = std::prev(I);
Dan Gohman5c70fad2012-03-23 17:47:54 +00001216
1217 // Invoke instructions are visited as part of their successors (below).
1218 if (isa<InvokeInst>(Inst))
1219 continue;
1220
Michael Gottesman89279f82013-04-05 18:10:41 +00001221 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001222
Dan Gohman5c70fad2012-03-23 17:47:54 +00001223 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
1224 }
1225
Dan Gohmandae33492012-04-27 18:56:31 +00001226 // If there's a predecessor with an invoke, visit the invoke as if it were
1227 // part of this block, since we can't insert code after an invoke in its own
1228 // block, and we don't want to split critical edges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001229 for (BBState::edge_iterator PI(MyStates.pred_begin()),
1230 PE(MyStates.pred_end()); PI != PE; ++PI) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00001231 BasicBlock *Pred = *PI;
Dan Gohmandae33492012-04-27 18:56:31 +00001232 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
1233 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
Dan Gohman817a7c62012-03-22 18:24:56 +00001234 }
John McCalld935e9c2011-06-15 23:37:01 +00001235
Dan Gohman817a7c62012-03-22 18:24:56 +00001236 return NestingDetected;
1237}
John McCalld935e9c2011-06-15 23:37:01 +00001238
Dan Gohman817a7c62012-03-22 18:24:56 +00001239bool
1240ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
1241 DenseMap<Value *, RRInfo> &Releases,
1242 BBState &MyStates) {
1243 bool NestingDetected = false;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001244 ARCInstKind Class = GetARCInstKind(Inst);
Craig Topperf40110f2014-04-25 05:29:35 +00001245 const Value *Arg = nullptr;
John McCalld935e9c2011-06-15 23:37:01 +00001246
Dan Gohman817a7c62012-03-22 18:24:56 +00001247 switch (Class) {
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001248 case ARCInstKind::RetainBlock:
Michael Gottesman158fdf62013-03-28 20:11:19 +00001249 // In OptimizeIndividualCalls, we have strength reduced all optimizable
1250 // objc_retainBlocks to objc_retains. Thus at this point any
Michael Gottesman60805962015-03-06 00:34:42 +00001251 // objc_retainBlocks that we see are not optimizable. We need to break since
1252 // a retain can be a potential use.
Michael Gottesman158fdf62013-03-28 20:11:19 +00001253 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001254 case ARCInstKind::Retain:
1255 case ARCInstKind::RetainRV: {
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001256 Arg = GetArgRCIdentityRoot(Inst);
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001257 TopDownPtrState &S = MyStates.getPtrTopDownState(Arg);
Michael Gottesman4eae3962015-03-06 00:34:39 +00001258 NestingDetected |= S.InitTopDown(Class, Inst);
Dan Gohmanf64ff8e2012-07-23 19:27:31 +00001259 // A retain can be a potential use; procede to the generic checking
1260 // code below.
1261 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001262 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001263 case ARCInstKind::Release: {
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001264 Arg = GetArgRCIdentityRoot(Inst);
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001265 TopDownPtrState &S = MyStates.getPtrTopDownState(Arg);
Michael Gottesman60805962015-03-06 00:34:42 +00001266 // Try to form a tentative pair in between this release instruction and the
1267 // top down pointers that we are tracking.
1268 if (S.MatchWithRelease(MDKindCache, Inst)) {
1269 // If we succeed, copy S's RRInfo into the Release -> {Retain Set
1270 // Map}. Then we clear S.
Michael Gottesmane3943d02013-06-21 19:44:30 +00001271 Releases[Inst] = S.GetRRInfo();
Dan Gohman817a7c62012-03-22 18:24:56 +00001272 S.ClearSequenceProgress();
Dan Gohman817a7c62012-03-22 18:24:56 +00001273 }
1274 break;
1275 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001276 case ARCInstKind::AutoreleasepoolPop:
Dan Gohman817a7c62012-03-22 18:24:56 +00001277 // Conservatively, clear MyStates for all known pointers.
1278 MyStates.clearTopDownPointers();
Michael Gottesman60805962015-03-06 00:34:42 +00001279 return false;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001280 case ARCInstKind::AutoreleasepoolPush:
1281 case ARCInstKind::None:
Michael Gottesman60805962015-03-06 00:34:42 +00001282 // These can not be uses of
1283 return false;
Dan Gohman817a7c62012-03-22 18:24:56 +00001284 default:
1285 break;
1286 }
1287
1288 // Consider any other possible effects of this instruction on each
1289 // pointer being tracked.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001290 for (auto MI = MyStates.top_down_ptr_begin(),
1291 ME = MyStates.top_down_ptr_end();
1292 MI != ME; ++MI) {
Dan Gohman817a7c62012-03-22 18:24:56 +00001293 const Value *Ptr = MI->first;
1294 if (Ptr == Arg)
1295 continue; // Handled above.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001296 TopDownPtrState &S = MI->second;
Dan Gohman817a7c62012-03-22 18:24:56 +00001297 Sequence Seq = S.GetSeq();
1298
1299 // Check for possible releases.
1300 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Michael Gottesmanbab49e972013-04-05 18:26:08 +00001301 DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr
Michael Gottesman79249972013-04-05 23:46:45 +00001302 << "\n");
Michael Gottesman764b1cf2013-03-23 05:46:19 +00001303 S.ClearKnownPositiveRefCount();
John McCalld935e9c2011-06-15 23:37:01 +00001304 switch (Seq) {
Dan Gohman817a7c62012-03-22 18:24:56 +00001305 case S_Retain:
1306 S.SetSeq(S_CanRelease);
Michael Gottesman4f6ef112013-06-21 19:44:27 +00001307 assert(!S.HasReverseInsertPts());
1308 S.InsertReverseInsertPt(Inst);
Dan Gohman817a7c62012-03-22 18:24:56 +00001309
1310 // One call can't cause a transition from S_Retain to S_CanRelease
1311 // and S_CanRelease to S_Use. If we've made the first transition,
1312 // we're done.
1313 continue;
John McCalld935e9c2011-06-15 23:37:01 +00001314 case S_Use:
Dan Gohman817a7c62012-03-22 18:24:56 +00001315 case S_CanRelease:
John McCalld935e9c2011-06-15 23:37:01 +00001316 case S_None:
1317 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001318 case S_Stop:
1319 case S_Release:
1320 case S_MovableRelease:
1321 llvm_unreachable("top-down pointer in release state!");
John McCalld935e9c2011-06-15 23:37:01 +00001322 }
1323 }
Dan Gohman817a7c62012-03-22 18:24:56 +00001324
1325 // Check for possible direct uses.
1326 switch (Seq) {
1327 case S_CanRelease:
Michael Gottesman81b1d432013-03-26 00:42:04 +00001328 if (CanUse(Inst, Ptr, PA, Class)) {
Michael Gottesmanbab49e972013-04-05 18:26:08 +00001329 DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr
1330 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00001331 S.SetSeq(S_Use);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001332 }
Dan Gohman817a7c62012-03-22 18:24:56 +00001333 break;
1334 case S_Retain:
1335 case S_Use:
1336 case S_None:
1337 break;
1338 case S_Stop:
1339 case S_Release:
1340 case S_MovableRelease:
1341 llvm_unreachable("top-down pointer in release state!");
1342 }
John McCalld935e9c2011-06-15 23:37:01 +00001343 }
1344
1345 return NestingDetected;
1346}
1347
1348bool
1349ObjCARCOpt::VisitTopDown(BasicBlock *BB,
1350 DenseMap<const BasicBlock *, BBState> &BBStates,
1351 DenseMap<Value *, RRInfo> &Releases) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001352 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitTopDown ==\n");
John McCalld935e9c2011-06-15 23:37:01 +00001353 bool NestingDetected = false;
1354 BBState &MyStates = BBStates[BB];
1355
1356 // Merge the states from each predecessor to compute the initial state
1357 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00001358 BBState::edge_iterator PI(MyStates.pred_begin()),
1359 PE(MyStates.pred_end());
1360 if (PI != PE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001361 const BasicBlock *Pred = *PI;
1362 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
1363 assert(I != BBStates.end());
1364 MyStates.InitFromPred(I->second);
1365 ++PI;
1366 for (; PI != PE; ++PI) {
1367 Pred = *PI;
1368 I = BBStates.find(Pred);
1369 assert(I != BBStates.end());
1370 MyStates.MergePred(I->second);
1371 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001372 }
John McCalld935e9c2011-06-15 23:37:01 +00001373
1374 // Visit all the instructions, top-down.
1375 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1376 Instruction *Inst = I;
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001377
Michael Gottesman89279f82013-04-05 18:10:41 +00001378 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001379
Dan Gohman817a7c62012-03-22 18:24:56 +00001380 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00001381 }
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00001382
John McCalld935e9c2011-06-15 23:37:01 +00001383 CheckForCFGHazards(BB, BBStates, MyStates);
1384 return NestingDetected;
1385}
1386
Dan Gohmana53a12c2011-12-12 19:42:25 +00001387static void
1388ComputePostOrders(Function &F,
1389 SmallVectorImpl<BasicBlock *> &PostOrder,
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001390 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
1391 unsigned NoObjCARCExceptionsMDKind,
1392 DenseMap<const BasicBlock *, BBState> &BBStates) {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001393 /// The visited set, for doing DFS walks.
Dan Gohmana53a12c2011-12-12 19:42:25 +00001394 SmallPtrSet<BasicBlock *, 16> Visited;
1395
1396 // Do DFS, computing the PostOrder.
1397 SmallPtrSet<BasicBlock *, 16> OnStack;
1398 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001399
1400 // Functions always have exactly one entry block, and we don't have
1401 // any other block that we treat like an entry block.
Dan Gohmana53a12c2011-12-12 19:42:25 +00001402 BasicBlock *EntryBB = &F.getEntryBlock();
Dan Gohman41375a32012-05-08 23:39:44 +00001403 BBState &MyStates = BBStates[EntryBB];
1404 MyStates.SetAsEntry();
1405 TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
1406 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
Dan Gohmana53a12c2011-12-12 19:42:25 +00001407 Visited.insert(EntryBB);
1408 OnStack.insert(EntryBB);
1409 do {
1410 dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001411 BasicBlock *CurrBB = SuccStack.back().first;
1412 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
1413 succ_iterator SE(TI, false);
Dan Gohman41375a32012-05-08 23:39:44 +00001414
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001415 while (SuccStack.back().second != SE) {
1416 BasicBlock *SuccBB = *SuccStack.back().second++;
David Blaikie70573dc2014-11-19 07:49:26 +00001417 if (Visited.insert(SuccBB).second) {
Dan Gohman41375a32012-05-08 23:39:44 +00001418 TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
1419 SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001420 BBStates[CurrBB].addSucc(SuccBB);
Dan Gohman41375a32012-05-08 23:39:44 +00001421 BBState &SuccStates = BBStates[SuccBB];
1422 SuccStates.addPred(CurrBB);
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001423 OnStack.insert(SuccBB);
Dan Gohmana53a12c2011-12-12 19:42:25 +00001424 goto dfs_next_succ;
1425 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001426
1427 if (!OnStack.count(SuccBB)) {
1428 BBStates[CurrBB].addSucc(SuccBB);
1429 BBStates[SuccBB].addPred(CurrBB);
1430 }
Dan Gohmana53a12c2011-12-12 19:42:25 +00001431 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001432 OnStack.erase(CurrBB);
1433 PostOrder.push_back(CurrBB);
1434 SuccStack.pop_back();
Dan Gohmana53a12c2011-12-12 19:42:25 +00001435 } while (!SuccStack.empty());
1436
1437 Visited.clear();
1438
Dan Gohmana53a12c2011-12-12 19:42:25 +00001439 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001440 // Functions may have many exits, and there also blocks which we treat
1441 // as exits due to ignored edges.
1442 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
1443 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
1444 BasicBlock *ExitBB = I;
1445 BBState &MyStates = BBStates[ExitBB];
1446 if (!MyStates.isExit())
1447 continue;
1448
Dan Gohmandae33492012-04-27 18:56:31 +00001449 MyStates.SetAsExit();
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001450
1451 PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00001452 Visited.insert(ExitBB);
1453 while (!PredStack.empty()) {
1454 reverse_dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001455 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
1456 while (PredStack.back().second != PE) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00001457 BasicBlock *BB = *PredStack.back().second++;
David Blaikie70573dc2014-11-19 07:49:26 +00001458 if (Visited.insert(BB).second) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001459 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00001460 goto reverse_dfs_next_succ;
1461 }
1462 }
1463 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
1464 }
1465 }
1466}
1467
Michael Gottesman97e3df02013-01-14 00:35:14 +00001468// Visit the function both top-down and bottom-up.
Michael Gottesman0be69202015-03-05 23:28:58 +00001469bool ObjCARCOpt::Visit(Function &F,
1470 DenseMap<const BasicBlock *, BBState> &BBStates,
1471 BlotMapVector<Value *, RRInfo> &Retains,
1472 DenseMap<Value *, RRInfo> &Releases) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00001473
1474 // Use reverse-postorder traversals, because we magically know that loops
1475 // will be well behaved, i.e. they won't repeatedly call retain on a single
1476 // pointer without doing a release. We can't use the ReversePostOrderTraversal
1477 // class here because we want the reverse-CFG postorder to consider each
1478 // function exit point, and we want to ignore selected cycle edges.
1479 SmallVector<BasicBlock *, 16> PostOrder;
1480 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001481 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
Michael Gottesman41c01002015-03-06 00:34:33 +00001482 MDKindCache.NoObjCARCExceptionsMDKind, BBStates);
Dan Gohmana53a12c2011-12-12 19:42:25 +00001483
1484 // Use reverse-postorder on the reverse CFG for bottom-up.
John McCalld935e9c2011-06-15 23:37:01 +00001485 bool BottomUpNestingDetected = false;
Dan Gohmanc57b58c2011-08-18 21:27:42 +00001486 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
Dan Gohmana53a12c2011-12-12 19:42:25 +00001487 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
1488 I != E; ++I)
1489 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
John McCalld935e9c2011-06-15 23:37:01 +00001490
Dan Gohmana53a12c2011-12-12 19:42:25 +00001491 // Use reverse-postorder for top-down.
John McCalld935e9c2011-06-15 23:37:01 +00001492 bool TopDownNestingDetected = false;
Dan Gohmana53a12c2011-12-12 19:42:25 +00001493 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
1494 PostOrder.rbegin(), E = PostOrder.rend();
1495 I != E; ++I)
1496 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
John McCalld935e9c2011-06-15 23:37:01 +00001497
1498 return TopDownNestingDetected && BottomUpNestingDetected;
1499}
1500
Michael Gottesman97e3df02013-01-14 00:35:14 +00001501/// Move the calls in RetainsToMove and ReleasesToMove.
Michael Gottesman0be69202015-03-05 23:28:58 +00001502void ObjCARCOpt::MoveCalls(Value *Arg, RRInfo &RetainsToMove,
John McCalld935e9c2011-06-15 23:37:01 +00001503 RRInfo &ReleasesToMove,
Michael Gottesman0be69202015-03-05 23:28:58 +00001504 BlotMapVector<Value *, RRInfo> &Retains,
John McCalld935e9c2011-06-15 23:37:01 +00001505 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman6320f522011-07-22 22:29:21 +00001506 SmallVectorImpl<Instruction *> &DeadInsts,
Michael Gottesman79249972013-04-05 23:46:45 +00001507 Module *M) {
Chris Lattner229907c2011-07-18 04:54:35 +00001508 Type *ArgTy = Arg->getType();
Dan Gohman6320f522011-07-22 22:29:21 +00001509 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
Michael Gottesman79249972013-04-05 23:46:45 +00001510
Michael Gottesman89279f82013-04-05 18:10:41 +00001511 DEBUG(dbgs() << "== ObjCARCOpt::MoveCalls ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00001512
John McCalld935e9c2011-06-15 23:37:01 +00001513 // Insert the new retain and release calls.
Craig Topper46276792014-08-24 23:23:06 +00001514 for (Instruction *InsertPt : ReleasesToMove.ReverseInsertPts) {
John McCalld935e9c2011-06-15 23:37:01 +00001515 Value *MyArg = ArgTy == ParamTy ? Arg :
1516 new BitCastInst(Arg, ParamTy, "", InsertPt);
Michael Gottesman14acfac2013-07-06 01:39:23 +00001517 Constant *Decl = EP.get(ARCRuntimeEntryPoints::EPT_Retain);
1518 CallInst *Call = CallInst::Create(Decl, MyArg, "", InsertPt);
John McCalld935e9c2011-06-15 23:37:01 +00001519 Call->setDoesNotThrow();
Michael Gottesmanba648592013-03-28 23:08:44 +00001520 Call->setTailCall();
Michael Gottesman60f6b282013-03-29 05:13:07 +00001521
Michael Gottesmandf110ac2013-04-21 00:30:50 +00001522 DEBUG(dbgs() << "Inserting new Retain: " << *Call << "\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00001523 "At insertion point: " << *InsertPt << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001524 }
Craig Topper46276792014-08-24 23:23:06 +00001525 for (Instruction *InsertPt : RetainsToMove.ReverseInsertPts) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00001526 Value *MyArg = ArgTy == ParamTy ? Arg :
1527 new BitCastInst(Arg, ParamTy, "", InsertPt);
Michael Gottesman14acfac2013-07-06 01:39:23 +00001528 Constant *Decl = EP.get(ARCRuntimeEntryPoints::EPT_Release);
1529 CallInst *Call = CallInst::Create(Decl, MyArg, "", InsertPt);
Dan Gohman5c70fad2012-03-23 17:47:54 +00001530 // Attach a clang.imprecise_release metadata tag, if appropriate.
1531 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
Michael Gottesman41c01002015-03-06 00:34:33 +00001532 Call->setMetadata(MDKindCache.ImpreciseReleaseMDKind, M);
Dan Gohman5c70fad2012-03-23 17:47:54 +00001533 Call->setDoesNotThrow();
1534 if (ReleasesToMove.IsTailCallRelease)
1535 Call->setTailCall();
Michael Gottesmanc189a392013-01-09 19:23:24 +00001536
Michael Gottesman89279f82013-04-05 18:10:41 +00001537 DEBUG(dbgs() << "Inserting new Release: " << *Call << "\n"
1538 "At insertion point: " << *InsertPt << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001539 }
1540
1541 // Delete the original retain and release calls.
Craig Topper46276792014-08-24 23:23:06 +00001542 for (Instruction *OrigRetain : RetainsToMove.Calls) {
John McCalld935e9c2011-06-15 23:37:01 +00001543 Retains.blot(OrigRetain);
1544 DeadInsts.push_back(OrigRetain);
Michael Gottesman89279f82013-04-05 18:10:41 +00001545 DEBUG(dbgs() << "Deleting retain: " << *OrigRetain << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001546 }
Craig Topper46276792014-08-24 23:23:06 +00001547 for (Instruction *OrigRelease : ReleasesToMove.Calls) {
John McCalld935e9c2011-06-15 23:37:01 +00001548 Releases.erase(OrigRelease);
1549 DeadInsts.push_back(OrigRelease);
Michael Gottesman89279f82013-04-05 18:10:41 +00001550 DEBUG(dbgs() << "Deleting release: " << *OrigRelease << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001551 }
Michael Gottesman79249972013-04-05 23:46:45 +00001552
John McCalld935e9c2011-06-15 23:37:01 +00001553}
1554
Michael Gottesman0be69202015-03-05 23:28:58 +00001555bool ObjCARCOpt::ConnectTDBUTraversals(
1556 DenseMap<const BasicBlock *, BBState> &BBStates,
1557 BlotMapVector<Value *, RRInfo> &Retains,
1558 DenseMap<Value *, RRInfo> &Releases, Module *M,
1559 SmallVectorImpl<Instruction *> &NewRetains,
1560 SmallVectorImpl<Instruction *> &NewReleases,
1561 SmallVectorImpl<Instruction *> &DeadInsts, RRInfo &RetainsToMove,
1562 RRInfo &ReleasesToMove, Value *Arg, bool KnownSafe,
1563 bool &AnyPairsCompletelyEliminated) {
Michael Gottesman9de6f962013-01-22 21:49:00 +00001564 // If a pair happens in a region where it is known that the reference count
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001565 // is already incremented, we can similarly ignore possible decrements unless
1566 // we are dealing with a retainable object with multiple provenance sources.
Michael Gottesman9de6f962013-01-22 21:49:00 +00001567 bool KnownSafeTD = true, KnownSafeBU = true;
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001568 bool MultipleOwners = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001569 bool CFGHazardAfflicted = false;
Michael Gottesman9de6f962013-01-22 21:49:00 +00001570
1571 // Connect the dots between the top-down-collected RetainsToMove and
1572 // bottom-up-collected ReleasesToMove to form sets of related calls.
1573 // This is an iterative process so that we connect multiple releases
1574 // to multiple retains if needed.
1575 unsigned OldDelta = 0;
1576 unsigned NewDelta = 0;
1577 unsigned OldCount = 0;
1578 unsigned NewCount = 0;
1579 bool FirstRelease = true;
Michael Gottesman9de6f962013-01-22 21:49:00 +00001580 for (;;) {
1581 for (SmallVectorImpl<Instruction *>::const_iterator
1582 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
1583 Instruction *NewRetain = *NI;
Michael Gottesman0be69202015-03-05 23:28:58 +00001584 BlotMapVector<Value *, RRInfo>::const_iterator It =
1585 Retains.find(NewRetain);
Michael Gottesman9de6f962013-01-22 21:49:00 +00001586 assert(It != Retains.end());
1587 const RRInfo &NewRetainRRI = It->second;
1588 KnownSafeTD &= NewRetainRRI.KnownSafe;
Michael Gottesman5a91bbf2013-05-24 20:44:02 +00001589 MultipleOwners =
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001590 MultipleOwners || MultiOwnersSet.count(GetArgRCIdentityRoot(NewRetain));
Craig Topper46276792014-08-24 23:23:06 +00001591 for (Instruction *NewRetainRelease : NewRetainRRI.Calls) {
Michael Gottesman9de6f962013-01-22 21:49:00 +00001592 DenseMap<Value *, RRInfo>::const_iterator Jt =
1593 Releases.find(NewRetainRelease);
1594 if (Jt == Releases.end())
1595 return false;
1596 const RRInfo &NewRetainReleaseRRI = Jt->second;
Michael Gottesman24b2f6f2013-11-05 16:02:40 +00001597
1598 // If the release does not have a reference to the retain as well,
1599 // something happened which is unaccounted for. Do not do anything.
1600 //
1601 // This can happen if we catch an additive overflow during path count
1602 // merging.
1603 if (!NewRetainReleaseRRI.Calls.count(NewRetain))
1604 return false;
1605
David Blaikie70573dc2014-11-19 07:49:26 +00001606 if (ReleasesToMove.Calls.insert(NewRetainRelease).second) {
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001607
1608 // If we overflow when we compute the path count, don't remove/move
1609 // anything.
1610 const BBState &NRRBBState = BBStates[NewRetainRelease->getParent()];
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00001611 unsigned PathCount = BBState::OverflowOccurredValue;
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001612 if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
1613 return false;
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00001614 assert(PathCount != BBState::OverflowOccurredValue &&
1615 "PathCount at this point can not be "
1616 "OverflowOccurredValue.");
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001617 OldDelta -= PathCount;
Michael Gottesman9de6f962013-01-22 21:49:00 +00001618
1619 // Merge the ReleaseMetadata and IsTailCallRelease values.
1620 if (FirstRelease) {
1621 ReleasesToMove.ReleaseMetadata =
1622 NewRetainReleaseRRI.ReleaseMetadata;
1623 ReleasesToMove.IsTailCallRelease =
1624 NewRetainReleaseRRI.IsTailCallRelease;
1625 FirstRelease = false;
1626 } else {
1627 if (ReleasesToMove.ReleaseMetadata !=
1628 NewRetainReleaseRRI.ReleaseMetadata)
Craig Topperf40110f2014-04-25 05:29:35 +00001629 ReleasesToMove.ReleaseMetadata = nullptr;
Michael Gottesman9de6f962013-01-22 21:49:00 +00001630 if (ReleasesToMove.IsTailCallRelease !=
1631 NewRetainReleaseRRI.IsTailCallRelease)
1632 ReleasesToMove.IsTailCallRelease = false;
1633 }
1634
1635 // Collect the optimal insertion points.
1636 if (!KnownSafe)
Craig Topper46276792014-08-24 23:23:06 +00001637 for (Instruction *RIP : NewRetainReleaseRRI.ReverseInsertPts) {
David Blaikie70573dc2014-11-19 07:49:26 +00001638 if (ReleasesToMove.ReverseInsertPts.insert(RIP).second) {
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001639 // If we overflow when we compute the path count, don't
1640 // remove/move anything.
1641 const BBState &RIPBBState = BBStates[RIP->getParent()];
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00001642 PathCount = BBState::OverflowOccurredValue;
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001643 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
1644 return false;
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00001645 assert(PathCount != BBState::OverflowOccurredValue &&
1646 "PathCount at this point can not be "
1647 "OverflowOccurredValue.");
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001648 NewDelta -= PathCount;
1649 }
Michael Gottesman9de6f962013-01-22 21:49:00 +00001650 }
1651 NewReleases.push_back(NewRetainRelease);
1652 }
1653 }
1654 }
1655 NewRetains.clear();
1656 if (NewReleases.empty()) break;
1657
1658 // Back the other way.
1659 for (SmallVectorImpl<Instruction *>::const_iterator
1660 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
1661 Instruction *NewRelease = *NI;
1662 DenseMap<Value *, RRInfo>::const_iterator It =
1663 Releases.find(NewRelease);
1664 assert(It != Releases.end());
1665 const RRInfo &NewReleaseRRI = It->second;
1666 KnownSafeBU &= NewReleaseRRI.KnownSafe;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001667 CFGHazardAfflicted |= NewReleaseRRI.CFGHazardAfflicted;
Craig Topper46276792014-08-24 23:23:06 +00001668 for (Instruction *NewReleaseRetain : NewReleaseRRI.Calls) {
Michael Gottesman0be69202015-03-05 23:28:58 +00001669 BlotMapVector<Value *, RRInfo>::const_iterator Jt =
1670 Retains.find(NewReleaseRetain);
Michael Gottesman9de6f962013-01-22 21:49:00 +00001671 if (Jt == Retains.end())
1672 return false;
1673 const RRInfo &NewReleaseRetainRRI = Jt->second;
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001674
Michael Gottesman24b2f6f2013-11-05 16:02:40 +00001675 // If the retain does not have a reference to the release as well,
1676 // something happened which is unaccounted for. Do not do anything.
1677 //
1678 // This can happen if we catch an additive overflow during path count
1679 // merging.
1680 if (!NewReleaseRetainRRI.Calls.count(NewRelease))
1681 return false;
1682
David Blaikie70573dc2014-11-19 07:49:26 +00001683 if (RetainsToMove.Calls.insert(NewReleaseRetain).second) {
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001684 // If we overflow when we compute the path count, don't remove/move
1685 // anything.
1686 const BBState &NRRBBState = BBStates[NewReleaseRetain->getParent()];
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00001687 unsigned PathCount = BBState::OverflowOccurredValue;
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001688 if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
1689 return false;
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00001690 assert(PathCount != BBState::OverflowOccurredValue &&
1691 "PathCount at this point can not be "
1692 "OverflowOccurredValue.");
Michael Gottesman9de6f962013-01-22 21:49:00 +00001693 OldDelta += PathCount;
1694 OldCount += PathCount;
1695
Michael Gottesman9de6f962013-01-22 21:49:00 +00001696 // Collect the optimal insertion points.
1697 if (!KnownSafe)
Craig Topper46276792014-08-24 23:23:06 +00001698 for (Instruction *RIP : NewReleaseRetainRRI.ReverseInsertPts) {
David Blaikie70573dc2014-11-19 07:49:26 +00001699 if (RetainsToMove.ReverseInsertPts.insert(RIP).second) {
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001700 // If we overflow when we compute the path count, don't
1701 // remove/move anything.
1702 const BBState &RIPBBState = BBStates[RIP->getParent()];
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00001703
1704 PathCount = BBState::OverflowOccurredValue;
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001705 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
1706 return false;
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00001707 assert(PathCount != BBState::OverflowOccurredValue &&
1708 "PathCount at this point can not be "
1709 "OverflowOccurredValue.");
Michael Gottesman9de6f962013-01-22 21:49:00 +00001710 NewDelta += PathCount;
1711 NewCount += PathCount;
1712 }
1713 }
1714 NewRetains.push_back(NewReleaseRetain);
1715 }
1716 }
1717 }
1718 NewReleases.clear();
1719 if (NewRetains.empty()) break;
1720 }
1721
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001722 // If the pointer is known incremented in 1 direction and we do not have
1723 // MultipleOwners, we can safely remove the retain/releases. Otherwise we need
1724 // to be known safe in both directions.
1725 bool UnconditionallySafe = (KnownSafeTD && KnownSafeBU) ||
1726 ((KnownSafeTD || KnownSafeBU) && !MultipleOwners);
1727 if (UnconditionallySafe) {
Michael Gottesman9de6f962013-01-22 21:49:00 +00001728 RetainsToMove.ReverseInsertPts.clear();
1729 ReleasesToMove.ReverseInsertPts.clear();
1730 NewCount = 0;
1731 } else {
1732 // Determine whether the new insertion points we computed preserve the
1733 // balance of retain and release calls through the program.
1734 // TODO: If the fully aggressive solution isn't valid, try to find a
1735 // less aggressive solution which is.
1736 if (NewDelta != 0)
1737 return false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001738
1739 // At this point, we are not going to remove any RR pairs, but we still are
1740 // able to move RR pairs. If one of our pointers is afflicted with
1741 // CFGHazards, we cannot perform such code motion so exit early.
1742 const bool WillPerformCodeMotion = RetainsToMove.ReverseInsertPts.size() ||
1743 ReleasesToMove.ReverseInsertPts.size();
1744 if (CFGHazardAfflicted && WillPerformCodeMotion)
1745 return false;
Michael Gottesman9de6f962013-01-22 21:49:00 +00001746 }
1747
1748 // Determine whether the original call points are balanced in the retain and
1749 // release calls through the program. If not, conservatively don't touch
1750 // them.
1751 // TODO: It's theoretically possible to do code motion in this case, as
1752 // long as the existing imbalances are maintained.
1753 if (OldDelta != 0)
1754 return false;
Michael Gottesman8005ad32013-04-29 06:16:55 +00001755
Michael Gottesman9de6f962013-01-22 21:49:00 +00001756 Changed = true;
1757 assert(OldCount != 0 && "Unreachable code?");
1758 NumRRs += OldCount - NewCount;
Michael Gottesman9de6f962013-01-22 21:49:00 +00001759 // Set to true if we completely removed any RR pairs.
Michael Gottesman8b5515f2013-01-22 21:53:43 +00001760 AnyPairsCompletelyEliminated = NewCount == 0;
Michael Gottesman9de6f962013-01-22 21:49:00 +00001761
1762 // We can move calls!
1763 return true;
1764}
1765
Michael Gottesman97e3df02013-01-14 00:35:14 +00001766/// Identify pairings between the retains and releases, and delete and/or move
1767/// them.
Michael Gottesman0be69202015-03-05 23:28:58 +00001768bool ObjCARCOpt::PerformCodePlacement(
1769 DenseMap<const BasicBlock *, BBState> &BBStates,
1770 BlotMapVector<Value *, RRInfo> &Retains,
1771 DenseMap<Value *, RRInfo> &Releases, Module *M) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001772 DEBUG(dbgs() << "\n== ObjCARCOpt::PerformCodePlacement ==\n");
1773
John McCalld935e9c2011-06-15 23:37:01 +00001774 bool AnyPairsCompletelyEliminated = false;
1775 RRInfo RetainsToMove;
1776 RRInfo ReleasesToMove;
1777 SmallVector<Instruction *, 4> NewRetains;
1778 SmallVector<Instruction *, 4> NewReleases;
1779 SmallVector<Instruction *, 8> DeadInsts;
1780
Dan Gohman670f9372012-04-13 18:57:48 +00001781 // Visit each retain.
Michael Gottesman0be69202015-03-05 23:28:58 +00001782 for (BlotMapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
1783 E = Retains.end();
1784 I != E; ++I) {
Dan Gohman2053a5d2011-09-29 22:25:23 +00001785 Value *V = I->first;
John McCalld935e9c2011-06-15 23:37:01 +00001786 if (!V) continue; // blotted
1787
1788 Instruction *Retain = cast<Instruction>(V);
Michael Gottesmanc189a392013-01-09 19:23:24 +00001789
Michael Gottesman89279f82013-04-05 18:10:41 +00001790 DEBUG(dbgs() << "Visiting: " << *Retain << "\n");
Michael Gottesmanc189a392013-01-09 19:23:24 +00001791
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001792 Value *Arg = GetArgRCIdentityRoot(Retain);
John McCalld935e9c2011-06-15 23:37:01 +00001793
Dan Gohman728db492012-01-13 00:39:07 +00001794 // If the object being released is in static or stack storage, we know it's
John McCalld935e9c2011-06-15 23:37:01 +00001795 // not being managed by ObjC reference counting, so we can delete pairs
1796 // regardless of what possible decrements or uses lie between them.
Dan Gohman728db492012-01-13 00:39:07 +00001797 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
Dan Gohman41375a32012-05-08 23:39:44 +00001798
Dan Gohman56e1cef2011-08-22 17:29:11 +00001799 // A constant pointer can't be pointing to an object on the heap. It may
1800 // be reference-counted, but it won't be deleted.
1801 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
1802 if (const GlobalVariable *GV =
1803 dyn_cast<GlobalVariable>(
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001804 GetRCIdentityRoot(LI->getPointerOperand())))
Dan Gohman56e1cef2011-08-22 17:29:11 +00001805 if (GV->isConstant())
1806 KnownSafe = true;
1807
John McCalld935e9c2011-06-15 23:37:01 +00001808 // Connect the dots between the top-down-collected RetainsToMove and
1809 // bottom-up-collected ReleasesToMove to form sets of related calls.
John McCalld935e9c2011-06-15 23:37:01 +00001810 NewRetains.push_back(Retain);
Michael Gottesman9de6f962013-01-22 21:49:00 +00001811 bool PerformMoveCalls =
1812 ConnectTDBUTraversals(BBStates, Retains, Releases, M, NewRetains,
1813 NewReleases, DeadInsts, RetainsToMove,
1814 ReleasesToMove, Arg, KnownSafe,
1815 AnyPairsCompletelyEliminated);
John McCalld935e9c2011-06-15 23:37:01 +00001816
Michael Gottesman9de6f962013-01-22 21:49:00 +00001817 if (PerformMoveCalls) {
1818 // Ok, everything checks out and we're all set. Let's move/delete some
1819 // code!
1820 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
1821 Retains, Releases, DeadInsts, M);
John McCalld935e9c2011-06-15 23:37:01 +00001822 }
1823
Michael Gottesman9de6f962013-01-22 21:49:00 +00001824 // Clean up state for next retain.
John McCalld935e9c2011-06-15 23:37:01 +00001825 NewReleases.clear();
1826 NewRetains.clear();
1827 RetainsToMove.clear();
1828 ReleasesToMove.clear();
1829 }
1830
1831 // Now that we're done moving everything, we can delete the newly dead
1832 // instructions, as we no longer need them as insert points.
1833 while (!DeadInsts.empty())
1834 EraseInstruction(DeadInsts.pop_back_val());
1835
1836 return AnyPairsCompletelyEliminated;
1837}
1838
Michael Gottesman97e3df02013-01-14 00:35:14 +00001839/// Weak pointer optimizations.
John McCalld935e9c2011-06-15 23:37:01 +00001840void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001841 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeWeakCalls ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00001842
John McCalld935e9c2011-06-15 23:37:01 +00001843 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
1844 // itself because it uses AliasAnalysis and we need to do provenance
1845 // queries instead.
1846 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
1847 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +00001848
Michael Gottesman89279f82013-04-05 18:10:41 +00001849 DEBUG(dbgs() << "Visiting: " << *Inst << "\n");
Michael Gottesman3f146e22013-01-01 16:05:48 +00001850
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001851 ARCInstKind Class = GetBasicARCInstKind(Inst);
1852 if (Class != ARCInstKind::LoadWeak &&
1853 Class != ARCInstKind::LoadWeakRetained)
John McCalld935e9c2011-06-15 23:37:01 +00001854 continue;
1855
1856 // Delete objc_loadWeak calls with no users.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001857 if (Class == ARCInstKind::LoadWeak && Inst->use_empty()) {
John McCalld935e9c2011-06-15 23:37:01 +00001858 Inst->eraseFromParent();
1859 continue;
1860 }
1861
1862 // TODO: For now, just look for an earlier available version of this value
1863 // within the same block. Theoretically, we could do memdep-style non-local
1864 // analysis too, but that would want caching. A better approach would be to
1865 // use the technique that EarlyCSE uses.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001866 inst_iterator Current = std::prev(I);
John McCalld935e9c2011-06-15 23:37:01 +00001867 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
1868 for (BasicBlock::iterator B = CurrentBB->begin(),
1869 J = Current.getInstructionIterator();
1870 J != B; --J) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001871 Instruction *EarlierInst = &*std::prev(J);
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001872 ARCInstKind EarlierClass = GetARCInstKind(EarlierInst);
John McCalld935e9c2011-06-15 23:37:01 +00001873 switch (EarlierClass) {
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001874 case ARCInstKind::LoadWeak:
1875 case ARCInstKind::LoadWeakRetained: {
John McCalld935e9c2011-06-15 23:37:01 +00001876 // If this is loading from the same pointer, replace this load's value
1877 // with that one.
1878 CallInst *Call = cast<CallInst>(Inst);
1879 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
1880 Value *Arg = Call->getArgOperand(0);
1881 Value *EarlierArg = EarlierCall->getArgOperand(0);
1882 switch (PA.getAA()->alias(Arg, EarlierArg)) {
1883 case AliasAnalysis::MustAlias:
1884 Changed = true;
1885 // If the load has a builtin retain, insert a plain retain for it.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001886 if (Class == ARCInstKind::LoadWeakRetained) {
Michael Gottesman14acfac2013-07-06 01:39:23 +00001887 Constant *Decl = EP.get(ARCRuntimeEntryPoints::EPT_Retain);
1888 CallInst *CI = CallInst::Create(Decl, EarlierCall, "", Call);
John McCalld935e9c2011-06-15 23:37:01 +00001889 CI->setTailCall();
1890 }
1891 // Zap the fully redundant load.
1892 Call->replaceAllUsesWith(EarlierCall);
1893 Call->eraseFromParent();
1894 goto clobbered;
1895 case AliasAnalysis::MayAlias:
1896 case AliasAnalysis::PartialAlias:
1897 goto clobbered;
1898 case AliasAnalysis::NoAlias:
1899 break;
1900 }
1901 break;
1902 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001903 case ARCInstKind::StoreWeak:
1904 case ARCInstKind::InitWeak: {
John McCalld935e9c2011-06-15 23:37:01 +00001905 // If this is storing to the same pointer and has the same size etc.
1906 // replace this load's value with the stored value.
1907 CallInst *Call = cast<CallInst>(Inst);
1908 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
1909 Value *Arg = Call->getArgOperand(0);
1910 Value *EarlierArg = EarlierCall->getArgOperand(0);
1911 switch (PA.getAA()->alias(Arg, EarlierArg)) {
1912 case AliasAnalysis::MustAlias:
1913 Changed = true;
1914 // If the load has a builtin retain, insert a plain retain for it.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001915 if (Class == ARCInstKind::LoadWeakRetained) {
Michael Gottesman14acfac2013-07-06 01:39:23 +00001916 Constant *Decl = EP.get(ARCRuntimeEntryPoints::EPT_Retain);
1917 CallInst *CI = CallInst::Create(Decl, EarlierCall, "", Call);
John McCalld935e9c2011-06-15 23:37:01 +00001918 CI->setTailCall();
1919 }
1920 // Zap the fully redundant load.
1921 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
1922 Call->eraseFromParent();
1923 goto clobbered;
1924 case AliasAnalysis::MayAlias:
1925 case AliasAnalysis::PartialAlias:
1926 goto clobbered;
1927 case AliasAnalysis::NoAlias:
1928 break;
1929 }
1930 break;
1931 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001932 case ARCInstKind::MoveWeak:
1933 case ARCInstKind::CopyWeak:
John McCalld935e9c2011-06-15 23:37:01 +00001934 // TOOD: Grab the copied value.
1935 goto clobbered;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001936 case ARCInstKind::AutoreleasepoolPush:
1937 case ARCInstKind::None:
1938 case ARCInstKind::IntrinsicUser:
1939 case ARCInstKind::User:
John McCalld935e9c2011-06-15 23:37:01 +00001940 // Weak pointers are only modified through the weak entry points
1941 // (and arbitrary calls, which could call the weak entry points).
1942 break;
1943 default:
1944 // Anything else could modify the weak pointer.
1945 goto clobbered;
1946 }
1947 }
1948 clobbered:;
1949 }
1950
1951 // Then, for each destroyWeak with an alloca operand, check to see if
1952 // the alloca and all its users can be zapped.
1953 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
1954 Instruction *Inst = &*I++;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001955 ARCInstKind Class = GetBasicARCInstKind(Inst);
1956 if (Class != ARCInstKind::DestroyWeak)
John McCalld935e9c2011-06-15 23:37:01 +00001957 continue;
1958
1959 CallInst *Call = cast<CallInst>(Inst);
1960 Value *Arg = Call->getArgOperand(0);
1961 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001962 for (User *U : Alloca->users()) {
1963 const Instruction *UserInst = cast<Instruction>(U);
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001964 switch (GetBasicARCInstKind(UserInst)) {
1965 case ARCInstKind::InitWeak:
1966 case ARCInstKind::StoreWeak:
1967 case ARCInstKind::DestroyWeak:
John McCalld935e9c2011-06-15 23:37:01 +00001968 continue;
1969 default:
1970 goto done;
1971 }
1972 }
1973 Changed = true;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001974 for (auto UI = Alloca->user_begin(), UE = Alloca->user_end(); UI != UE;) {
John McCalld935e9c2011-06-15 23:37:01 +00001975 CallInst *UserInst = cast<CallInst>(*UI++);
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001976 switch (GetBasicARCInstKind(UserInst)) {
1977 case ARCInstKind::InitWeak:
1978 case ARCInstKind::StoreWeak:
Dan Gohman14862c32012-05-18 22:17:29 +00001979 // These functions return their second argument.
1980 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
1981 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001982 case ARCInstKind::DestroyWeak:
Dan Gohman14862c32012-05-18 22:17:29 +00001983 // No return value.
1984 break;
1985 default:
Dan Gohman9c97eea02012-05-21 17:41:28 +00001986 llvm_unreachable("alloca really is used!");
Dan Gohman14862c32012-05-18 22:17:29 +00001987 }
John McCalld935e9c2011-06-15 23:37:01 +00001988 UserInst->eraseFromParent();
1989 }
1990 Alloca->eraseFromParent();
1991 done:;
1992 }
1993 }
1994}
1995
Michael Gottesman97e3df02013-01-14 00:35:14 +00001996/// Identify program paths which execute sequences of retains and releases which
1997/// can be eliminated.
John McCalld935e9c2011-06-15 23:37:01 +00001998bool ObjCARCOpt::OptimizeSequences(Function &F) {
Michael Gottesman740db972013-05-23 02:35:21 +00001999 // Releases, Retains - These are used to store the results of the main flow
2000 // analysis. These use Value* as the key instead of Instruction* so that the
2001 // map stays valid when we get around to rewriting code and calls get
2002 // replaced by arguments.
John McCalld935e9c2011-06-15 23:37:01 +00002003 DenseMap<Value *, RRInfo> Releases;
Michael Gottesman0be69202015-03-05 23:28:58 +00002004 BlotMapVector<Value *, RRInfo> Retains;
John McCalld935e9c2011-06-15 23:37:01 +00002005
Michael Gottesman740db972013-05-23 02:35:21 +00002006 // This is used during the traversal of the function to track the
2007 // states for each identified object at each block.
John McCalld935e9c2011-06-15 23:37:01 +00002008 DenseMap<const BasicBlock *, BBState> BBStates;
2009
2010 // Analyze the CFG of the function, and all instructions.
2011 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
2012
2013 // Transform.
Michael Gottesman5a91bbf2013-05-24 20:44:02 +00002014 bool AnyPairsCompletelyEliminated = PerformCodePlacement(BBStates, Retains,
2015 Releases,
2016 F.getParent());
2017
2018 // Cleanup.
2019 MultiOwnersSet.clear();
2020
2021 return AnyPairsCompletelyEliminated && NestingDetected;
John McCalld935e9c2011-06-15 23:37:01 +00002022}
2023
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002024/// Check if there is a dependent call earlier that does not have anything in
2025/// between the Retain and the call that can affect the reference count of their
2026/// shared pointer argument. Note that Retain need not be in BB.
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002027static bool
2028HasSafePathToPredecessorCall(const Value *Arg, Instruction *Retain,
Craig Topper71b7b682014-08-21 05:55:13 +00002029 SmallPtrSetImpl<Instruction *> &DepInsts,
2030 SmallPtrSetImpl<const BasicBlock *> &Visited,
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002031 ProvenanceAnalysis &PA) {
2032 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
2033 DepInsts, Visited, PA);
2034 if (DepInsts.size() != 1)
2035 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002036
Michael Gottesmana9fc0162015-03-05 23:29:06 +00002037 auto *Call = dyn_cast_or_null<CallInst>(*DepInsts.begin());
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002038
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002039 // Check that the pointer is the return value of the call.
2040 if (!Call || Arg != Call)
2041 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002042
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002043 // Check that the call is a regular call.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002044 ARCInstKind Class = GetBasicARCInstKind(Call);
2045 if (Class != ARCInstKind::CallOrUser && Class != ARCInstKind::Call)
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002046 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002047
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002048 return true;
2049}
2050
Michael Gottesman6908db12013-04-03 23:16:05 +00002051/// Find a dependent retain that precedes the given autorelease for which there
2052/// is nothing in between the two instructions that can affect the ref count of
2053/// Arg.
2054static CallInst *
2055FindPredecessorRetainWithSafePath(const Value *Arg, BasicBlock *BB,
2056 Instruction *Autorelease,
Craig Topper71b7b682014-08-21 05:55:13 +00002057 SmallPtrSetImpl<Instruction *> &DepInsts,
2058 SmallPtrSetImpl<const BasicBlock *> &Visited,
Michael Gottesman6908db12013-04-03 23:16:05 +00002059 ProvenanceAnalysis &PA) {
2060 FindDependencies(CanChangeRetainCount, Arg,
2061 BB, Autorelease, DepInsts, Visited, PA);
2062 if (DepInsts.size() != 1)
Craig Topperf40110f2014-04-25 05:29:35 +00002063 return nullptr;
Michael Gottesman79249972013-04-05 23:46:45 +00002064
Michael Gottesmana9fc0162015-03-05 23:29:06 +00002065 auto *Retain = dyn_cast_or_null<CallInst>(*DepInsts.begin());
Michael Gottesman79249972013-04-05 23:46:45 +00002066
Michael Gottesman6908db12013-04-03 23:16:05 +00002067 // Check that we found a retain with the same argument.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002068 if (!Retain || !IsRetain(GetBasicARCInstKind(Retain)) ||
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00002069 GetArgRCIdentityRoot(Retain) != Arg) {
Craig Topperf40110f2014-04-25 05:29:35 +00002070 return nullptr;
Michael Gottesman6908db12013-04-03 23:16:05 +00002071 }
Michael Gottesman79249972013-04-05 23:46:45 +00002072
Michael Gottesman6908db12013-04-03 23:16:05 +00002073 return Retain;
2074}
2075
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002076/// Look for an ``autorelease'' instruction dependent on Arg such that there are
2077/// no instructions dependent on Arg that need a positive ref count in between
2078/// the autorelease and the ret.
2079static CallInst *
2080FindPredecessorAutoreleaseWithSafePath(const Value *Arg, BasicBlock *BB,
2081 ReturnInst *Ret,
Craig Topper71b7b682014-08-21 05:55:13 +00002082 SmallPtrSetImpl<Instruction *> &DepInsts,
2083 SmallPtrSetImpl<const BasicBlock *> &V,
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002084 ProvenanceAnalysis &PA) {
2085 FindDependencies(NeedsPositiveRetainCount, Arg,
2086 BB, Ret, DepInsts, V, PA);
2087 if (DepInsts.size() != 1)
Craig Topperf40110f2014-04-25 05:29:35 +00002088 return nullptr;
Michael Gottesman79249972013-04-05 23:46:45 +00002089
Michael Gottesmana9fc0162015-03-05 23:29:06 +00002090 auto *Autorelease = dyn_cast_or_null<CallInst>(*DepInsts.begin());
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002091 if (!Autorelease)
Craig Topperf40110f2014-04-25 05:29:35 +00002092 return nullptr;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002093 ARCInstKind AutoreleaseClass = GetBasicARCInstKind(Autorelease);
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002094 if (!IsAutorelease(AutoreleaseClass))
Craig Topperf40110f2014-04-25 05:29:35 +00002095 return nullptr;
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00002096 if (GetArgRCIdentityRoot(Autorelease) != Arg)
Craig Topperf40110f2014-04-25 05:29:35 +00002097 return nullptr;
Michael Gottesman79249972013-04-05 23:46:45 +00002098
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002099 return Autorelease;
2100}
2101
Michael Gottesman97e3df02013-01-14 00:35:14 +00002102/// Look for this pattern:
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00002103/// \code
John McCalld935e9c2011-06-15 23:37:01 +00002104/// %call = call i8* @something(...)
2105/// %2 = call i8* @objc_retain(i8* %call)
2106/// %3 = call i8* @objc_autorelease(i8* %2)
2107/// ret i8* %3
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00002108/// \endcode
John McCalld935e9c2011-06-15 23:37:01 +00002109/// And delete the retain and autorelease.
John McCalld935e9c2011-06-15 23:37:01 +00002110void ObjCARCOpt::OptimizeReturns(Function &F) {
2111 if (!F.getReturnType()->isPointerTy())
2112 return;
Michael Gottesman79249972013-04-05 23:46:45 +00002113
Michael Gottesman89279f82013-04-05 18:10:41 +00002114 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeReturns ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00002115
John McCalld935e9c2011-06-15 23:37:01 +00002116 SmallPtrSet<Instruction *, 4> DependingInstructions;
2117 SmallPtrSet<const BasicBlock *, 4> Visited;
2118 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
2119 BasicBlock *BB = FI;
2120 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
Michael Gottesman3f146e22013-01-01 16:05:48 +00002121
Michael Gottesman89279f82013-04-05 18:10:41 +00002122 DEBUG(dbgs() << "Visiting: " << *Ret << "\n");
Michael Gottesman3f146e22013-01-01 16:05:48 +00002123
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002124 if (!Ret)
2125 continue;
Michael Gottesman79249972013-04-05 23:46:45 +00002126
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00002127 const Value *Arg = GetRCIdentityRoot(Ret->getOperand(0));
Michael Gottesman79249972013-04-05 23:46:45 +00002128
Michael Gottesmancdb7c152013-04-21 00:25:04 +00002129 // Look for an ``autorelease'' instruction that is a predecessor of Ret and
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002130 // dependent on Arg such that there are no instructions dependent on Arg
2131 // that need a positive ref count in between the autorelease and Ret.
2132 CallInst *Autorelease =
2133 FindPredecessorAutoreleaseWithSafePath(Arg, BB, Ret,
2134 DependingInstructions, Visited,
2135 PA);
John McCalld935e9c2011-06-15 23:37:01 +00002136 DependingInstructions.clear();
2137 Visited.clear();
Michael Gottesmanfb9ece92013-04-21 00:25:01 +00002138
2139 if (!Autorelease)
2140 continue;
2141
2142 CallInst *Retain =
2143 FindPredecessorRetainWithSafePath(Arg, BB, Autorelease,
2144 DependingInstructions, Visited, PA);
2145 DependingInstructions.clear();
2146 Visited.clear();
2147
2148 if (!Retain)
2149 continue;
2150
2151 // Check that there is nothing that can affect the reference count
2152 // between the retain and the call. Note that Retain need not be in BB.
2153 bool HasSafePathToCall = HasSafePathToPredecessorCall(Arg, Retain,
2154 DependingInstructions,
2155 Visited, PA);
2156 DependingInstructions.clear();
2157 Visited.clear();
2158
2159 if (!HasSafePathToCall)
2160 continue;
2161
2162 // If so, we can zap the retain and autorelease.
2163 Changed = true;
2164 ++NumRets;
2165 DEBUG(dbgs() << "Erasing: " << *Retain << "\nErasing: "
2166 << *Autorelease << "\n");
2167 EraseInstruction(Retain);
2168 EraseInstruction(Autorelease);
John McCalld935e9c2011-06-15 23:37:01 +00002169 }
2170}
2171
Michael Gottesman9c118152013-04-29 06:16:57 +00002172#ifndef NDEBUG
2173void
2174ObjCARCOpt::GatherStatistics(Function &F, bool AfterOptimization) {
2175 llvm::Statistic &NumRetains =
2176 AfterOptimization? NumRetainsAfterOpt : NumRetainsBeforeOpt;
2177 llvm::Statistic &NumReleases =
2178 AfterOptimization? NumReleasesAfterOpt : NumReleasesBeforeOpt;
2179
2180 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2181 Instruction *Inst = &*I++;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002182 switch (GetBasicARCInstKind(Inst)) {
Michael Gottesman9c118152013-04-29 06:16:57 +00002183 default:
2184 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002185 case ARCInstKind::Retain:
Michael Gottesman9c118152013-04-29 06:16:57 +00002186 ++NumRetains;
2187 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002188 case ARCInstKind::Release:
Michael Gottesman9c118152013-04-29 06:16:57 +00002189 ++NumReleases;
2190 break;
2191 }
2192 }
2193}
2194#endif
2195
John McCalld935e9c2011-06-15 23:37:01 +00002196bool ObjCARCOpt::doInitialization(Module &M) {
2197 if (!EnableARCOpts)
2198 return false;
2199
Dan Gohman670f9372012-04-13 18:57:48 +00002200 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanceaac7c2011-06-20 23:20:43 +00002201 Run = ModuleHasARC(M);
2202 if (!Run)
2203 return false;
2204
John McCalld935e9c2011-06-15 23:37:01 +00002205 // Identify the imprecise release metadata kind.
Michael Gottesman41c01002015-03-06 00:34:33 +00002206 MDKindCache.ImpreciseReleaseMDKind =
2207 M.getContext().getMDKindID("clang.imprecise_release");
2208 MDKindCache.CopyOnEscapeMDKind =
2209 M.getContext().getMDKindID("clang.arc.copy_on_escape");
2210 MDKindCache.NoObjCARCExceptionsMDKind =
2211 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
John McCalld935e9c2011-06-15 23:37:01 +00002212
John McCalld935e9c2011-06-15 23:37:01 +00002213 // Intuitively, objc_retain and others are nocapture, however in practice
2214 // they are not, because they return their argument value. And objc_release
Dan Gohmandae33492012-04-27 18:56:31 +00002215 // calls finalizers which can have arbitrary side effects.
John McCalld935e9c2011-06-15 23:37:01 +00002216
Michael Gottesman14acfac2013-07-06 01:39:23 +00002217 // Initialize our runtime entry point cache.
2218 EP.Initialize(&M);
John McCalld935e9c2011-06-15 23:37:01 +00002219
2220 return false;
2221}
2222
2223bool ObjCARCOpt::runOnFunction(Function &F) {
2224 if (!EnableARCOpts)
2225 return false;
2226
Dan Gohmanceaac7c2011-06-20 23:20:43 +00002227 // If nothing in the Module uses ARC, don't do anything.
2228 if (!Run)
2229 return false;
2230
John McCalld935e9c2011-06-15 23:37:01 +00002231 Changed = false;
2232
Michael Gottesman89279f82013-04-05 18:10:41 +00002233 DEBUG(dbgs() << "<<< ObjCARCOpt: Visiting Function: " << F.getName() << " >>>"
2234 "\n");
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00002235
John McCalld935e9c2011-06-15 23:37:01 +00002236 PA.setAA(&getAnalysis<AliasAnalysis>());
2237
Michael Gottesman9fc50b82013-05-13 18:29:07 +00002238#ifndef NDEBUG
2239 if (AreStatisticsEnabled()) {
2240 GatherStatistics(F, false);
2241 }
2242#endif
2243
John McCalld935e9c2011-06-15 23:37:01 +00002244 // This pass performs several distinct transformations. As a compile-time aid
2245 // when compiling code that isn't ObjC, skip these if the relevant ObjC
2246 // library functions aren't declared.
2247
Michael Gottesmancd5b0272013-04-24 22:18:15 +00002248 // Preliminary optimizations. This also computes UsedInThisFunction.
John McCalld935e9c2011-06-15 23:37:01 +00002249 OptimizeIndividualCalls(F);
2250
2251 // Optimizations for weak pointers.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002252 if (UsedInThisFunction & ((1 << unsigned(ARCInstKind::LoadWeak)) |
2253 (1 << unsigned(ARCInstKind::LoadWeakRetained)) |
2254 (1 << unsigned(ARCInstKind::StoreWeak)) |
2255 (1 << unsigned(ARCInstKind::InitWeak)) |
2256 (1 << unsigned(ARCInstKind::CopyWeak)) |
2257 (1 << unsigned(ARCInstKind::MoveWeak)) |
2258 (1 << unsigned(ARCInstKind::DestroyWeak))))
John McCalld935e9c2011-06-15 23:37:01 +00002259 OptimizeWeakCalls(F);
2260
2261 // Optimizations for retain+release pairs.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002262 if (UsedInThisFunction & ((1 << unsigned(ARCInstKind::Retain)) |
2263 (1 << unsigned(ARCInstKind::RetainRV)) |
2264 (1 << unsigned(ARCInstKind::RetainBlock))))
2265 if (UsedInThisFunction & (1 << unsigned(ARCInstKind::Release)))
John McCalld935e9c2011-06-15 23:37:01 +00002266 // Run OptimizeSequences until it either stops making changes or
2267 // no retain+release pair nesting is detected.
2268 while (OptimizeSequences(F)) {}
2269
2270 // Optimizations if objc_autorelease is used.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002271 if (UsedInThisFunction & ((1 << unsigned(ARCInstKind::Autorelease)) |
2272 (1 << unsigned(ARCInstKind::AutoreleaseRV))))
John McCalld935e9c2011-06-15 23:37:01 +00002273 OptimizeReturns(F);
2274
Michael Gottesman9c118152013-04-29 06:16:57 +00002275 // Gather statistics after optimization.
2276#ifndef NDEBUG
2277 if (AreStatisticsEnabled()) {
2278 GatherStatistics(F, true);
2279 }
2280#endif
2281
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00002282 DEBUG(dbgs() << "\n");
2283
John McCalld935e9c2011-06-15 23:37:01 +00002284 return Changed;
2285}
2286
2287void ObjCARCOpt::releaseMemory() {
2288 PA.clear();
2289}
2290
Michael Gottesman97e3df02013-01-14 00:35:14 +00002291/// @}
2292///