blob: a517ffb1e5e91e1c34f71543d4707f58f6f80314 [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.
Mehdi Aminia28d91d2015-03-10 02:37:25 +000086static inline bool AreAnyUnderlyingObjectsAnAlloca(const Value *V,
87 const DataLayout &DL) {
Michael Gottesmana76143ee2013-05-13 23:49:42 +000088 SmallPtrSet<const Value *, 4> Visited;
89 SmallVector<const Value *, 4> Worklist;
90 Worklist.push_back(V);
91 do {
92 const Value *P = Worklist.pop_back_val();
Mehdi Aminia28d91d2015-03-10 02:37:25 +000093 P = GetUnderlyingObjCPtr(P, DL);
Michael Gottesman0c8b5622013-05-14 06:40:10 +000094
Michael Gottesmana76143ee2013-05-13 23:49:42 +000095 if (isa<AllocaInst>(P))
96 return true;
Michael Gottesman0c8b5622013-05-14 06:40:10 +000097
David Blaikie70573dc2014-11-19 07:49:26 +000098 if (!Visited.insert(P).second)
Michael Gottesmana76143ee2013-05-13 23:49:42 +000099 continue;
Michael Gottesman0c8b5622013-05-14 06:40:10 +0000100
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000101 if (const SelectInst *SI = dyn_cast<const SelectInst>(P)) {
102 Worklist.push_back(SI->getTrueValue());
103 Worklist.push_back(SI->getFalseValue());
104 continue;
105 }
Michael Gottesman0c8b5622013-05-14 06:40:10 +0000106
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000107 if (const PHINode *PN = dyn_cast<const PHINode>(P)) {
108 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
109 Worklist.push_back(PN->getIncomingValue(i));
110 continue;
111 }
112 } while (!Worklist.empty());
113
114 return false;
115}
116
117
Michael Gottesman97e3df02013-01-14 00:35:14 +0000118/// @}
119///
Michael Gottesman97e3df02013-01-14 00:35:14 +0000120/// \defgroup ARCOpt ARC Optimization.
121/// @{
John McCalld935e9c2011-06-15 23:37:01 +0000122
123// TODO: On code like this:
124//
125// objc_retain(%x)
126// stuff_that_cannot_release()
127// objc_autorelease(%x)
128// stuff_that_cannot_release()
129// objc_retain(%x)
130// stuff_that_cannot_release()
131// objc_autorelease(%x)
132//
133// The second retain and autorelease can be deleted.
134
135// TODO: It should be possible to delete
136// objc_autoreleasePoolPush and objc_autoreleasePoolPop
137// pairs if nothing is actually autoreleased between them. Also, autorelease
138// calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
139// after inlining) can be turned into plain release calls.
140
141// TODO: Critical-edge splitting. If the optimial insertion point is
142// a critical edge, the current algorithm has to fail, because it doesn't
143// know how to split edges. It should be possible to make the optimizer
144// think in terms of edges, rather than blocks, and then split critical
145// edges on demand.
146
147// TODO: OptimizeSequences could generalized to be Interprocedural.
148
149// TODO: Recognize that a bunch of other objc runtime calls have
150// non-escaping arguments and non-releasing arguments, and may be
151// non-autoreleasing.
152
153// TODO: Sink autorelease calls as far as possible. Unfortunately we
154// usually can't sink them past other calls, which would be the main
155// case where it would be useful.
156
Dan Gohmanb3894012011-08-19 00:26:36 +0000157// TODO: The pointer returned from objc_loadWeakRetained is retained.
158
159// TODO: Delete release+retain pairs (rare).
Dan Gohmanceaac7c2011-06-20 23:20:43 +0000160
John McCalld935e9c2011-06-15 23:37:01 +0000161STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
162STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
163STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
164STATISTIC(NumRets, "Number of return value forwarding "
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000165 "retain+autoreleases eliminated");
John McCalld935e9c2011-06-15 23:37:01 +0000166STATISTIC(NumRRs, "Number of retain+release paths eliminated");
167STATISTIC(NumPeeps, "Number of calls peephole-optimized");
Matt Beaumont-Gaye55d9492013-05-13 21:10:49 +0000168#ifndef NDEBUG
Michael Gottesman9c118152013-04-29 06:16:57 +0000169STATISTIC(NumRetainsBeforeOpt,
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000170 "Number of retains before optimization");
Michael Gottesman9c118152013-04-29 06:16:57 +0000171STATISTIC(NumReleasesBeforeOpt,
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000172 "Number of releases before optimization");
Michael Gottesman9c118152013-04-29 06:16:57 +0000173STATISTIC(NumRetainsAfterOpt,
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000174 "Number of retains after optimization");
Michael Gottesman9c118152013-04-29 06:16:57 +0000175STATISTIC(NumReleasesAfterOpt,
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000176 "Number of releases after optimization");
Michael Gottesman03cf3c82013-04-29 07:29:08 +0000177#endif
John McCalld935e9c2011-06-15 23:37:01 +0000178
179namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000180 /// \brief Per-BasicBlock state.
John McCalld935e9c2011-06-15 23:37:01 +0000181 class BBState {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000182 /// The number of unique control paths from the entry which can reach this
183 /// block.
John McCalld935e9c2011-06-15 23:37:01 +0000184 unsigned TopDownPathCount;
185
Michael Gottesman97e3df02013-01-14 00:35:14 +0000186 /// The number of unique control paths to exits from this block.
John McCalld935e9c2011-06-15 23:37:01 +0000187 unsigned BottomUpPathCount;
188
Michael Gottesman97e3df02013-01-14 00:35:14 +0000189 /// The top-down traversal uses this to record information known about a
190 /// pointer at the bottom of each block.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000191 BlotMapVector<const Value *, TopDownPtrState> PerPtrTopDown;
John McCalld935e9c2011-06-15 23:37:01 +0000192
Michael Gottesman97e3df02013-01-14 00:35:14 +0000193 /// The bottom-up traversal uses this to record information known about a
194 /// pointer at the top of each block.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000195 BlotMapVector<const Value *, BottomUpPtrState> PerPtrBottomUp;
John McCalld935e9c2011-06-15 23:37:01 +0000196
Michael Gottesman97e3df02013-01-14 00:35:14 +0000197 /// Effective predecessors of the current block ignoring ignorable edges and
198 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000199 SmallVector<BasicBlock *, 2> Preds;
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000200
Michael Gottesman97e3df02013-01-14 00:35:14 +0000201 /// Effective successors of the current block ignoring ignorable edges and
202 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000203 SmallVector<BasicBlock *, 2> Succs;
204
John McCalld935e9c2011-06-15 23:37:01 +0000205 public:
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000206 static const unsigned OverflowOccurredValue;
207
208 BBState() : TopDownPathCount(0), BottomUpPathCount(0) { }
John McCalld935e9c2011-06-15 23:37:01 +0000209
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000210 typedef decltype(PerPtrTopDown)::iterator top_down_ptr_iterator;
211 typedef decltype(PerPtrTopDown)::const_iterator const_top_down_ptr_iterator;
John McCalld935e9c2011-06-15 23:37:01 +0000212
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000213 top_down_ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
214 top_down_ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
215 const_top_down_ptr_iterator top_down_ptr_begin() const {
John McCalld935e9c2011-06-15 23:37:01 +0000216 return PerPtrTopDown.begin();
217 }
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000218 const_top_down_ptr_iterator top_down_ptr_end() const {
John McCalld935e9c2011-06-15 23:37:01 +0000219 return PerPtrTopDown.end();
220 }
221
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000222 typedef decltype(PerPtrBottomUp)::iterator bottom_up_ptr_iterator;
223 typedef decltype(
224 PerPtrBottomUp)::const_iterator const_bottom_up_ptr_iterator;
225
226 bottom_up_ptr_iterator bottom_up_ptr_begin() {
John McCalld935e9c2011-06-15 23:37:01 +0000227 return PerPtrBottomUp.begin();
228 }
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000229 bottom_up_ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
230 const_bottom_up_ptr_iterator bottom_up_ptr_begin() const {
231 return PerPtrBottomUp.begin();
232 }
233 const_bottom_up_ptr_iterator bottom_up_ptr_end() const {
John McCalld935e9c2011-06-15 23:37:01 +0000234 return PerPtrBottomUp.end();
235 }
236
Michael Gottesman97e3df02013-01-14 00:35:14 +0000237 /// Mark this block as being an entry block, which has one path from the
238 /// entry by definition.
John McCalld935e9c2011-06-15 23:37:01 +0000239 void SetAsEntry() { TopDownPathCount = 1; }
240
Michael Gottesman97e3df02013-01-14 00:35:14 +0000241 /// Mark this block as being an exit block, which has one path to an exit by
242 /// definition.
John McCalld935e9c2011-06-15 23:37:01 +0000243 void SetAsExit() { BottomUpPathCount = 1; }
244
Michael Gottesman993fbf72013-05-13 19:40:39 +0000245 /// Attempt to find the PtrState object describing the top down state for
246 /// pointer Arg. Return a new initialized PtrState describing the top down
247 /// state for Arg if we do not find one.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000248 TopDownPtrState &getPtrTopDownState(const Value *Arg) {
John McCalld935e9c2011-06-15 23:37:01 +0000249 return PerPtrTopDown[Arg];
250 }
251
Michael Gottesman993fbf72013-05-13 19:40:39 +0000252 /// Attempt to find the PtrState object describing the bottom up state for
253 /// pointer Arg. Return a new initialized PtrState describing the bottom up
254 /// state for Arg if we do not find one.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000255 BottomUpPtrState &getPtrBottomUpState(const Value *Arg) {
John McCalld935e9c2011-06-15 23:37:01 +0000256 return PerPtrBottomUp[Arg];
257 }
258
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000259 /// Attempt to find the PtrState object describing the bottom up state for
260 /// pointer Arg.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000261 bottom_up_ptr_iterator findPtrBottomUpState(const Value *Arg) {
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000262 return PerPtrBottomUp.find(Arg);
263 }
264
John McCalld935e9c2011-06-15 23:37:01 +0000265 void clearBottomUpPointers() {
Evan Chenge4df6a22011-08-04 18:40:26 +0000266 PerPtrBottomUp.clear();
John McCalld935e9c2011-06-15 23:37:01 +0000267 }
268
269 void clearTopDownPointers() {
270 PerPtrTopDown.clear();
271 }
272
273 void InitFromPred(const BBState &Other);
274 void InitFromSucc(const BBState &Other);
275 void MergePred(const BBState &Other);
276 void MergeSucc(const BBState &Other);
277
Michael Gottesman9e7261c2013-06-07 06:16:49 +0000278 /// Compute the number of possible unique paths from an entry to an exit
Michael Gottesman97e3df02013-01-14 00:35:14 +0000279 /// which pass through this block. This is only valid after both the
280 /// top-down and bottom-up traversals are complete.
Michael Gottesman9e7261c2013-06-07 06:16:49 +0000281 ///
Alp Tokercb402912014-01-24 17:20:08 +0000282 /// Returns true if overflow occurred. Returns false if overflow did not
Michael Gottesman9e7261c2013-06-07 06:16:49 +0000283 /// occur.
284 bool GetAllPathCountWithOverflow(unsigned &PathCount) const {
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000285 if (TopDownPathCount == OverflowOccurredValue ||
286 BottomUpPathCount == OverflowOccurredValue)
287 return true;
Michael Gottesman9e7261c2013-06-07 06:16:49 +0000288 unsigned long long Product =
289 (unsigned long long)TopDownPathCount*BottomUpPathCount;
Alp Tokercb402912014-01-24 17:20:08 +0000290 // Overflow occurred if any of the upper bits of Product are set or if all
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000291 // the lower bits of Product are all set.
292 return (Product >> 32) ||
293 ((PathCount = Product) == OverflowOccurredValue);
John McCalld935e9c2011-06-15 23:37:01 +0000294 }
Dan Gohman12130272011-08-12 00:26:31 +0000295
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000296 // Specialized CFG utilities.
Dan Gohmandae33492012-04-27 18:56:31 +0000297 typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
Michael Gottesman0fecf982013-08-07 23:56:34 +0000298 edge_iterator pred_begin() const { return Preds.begin(); }
299 edge_iterator pred_end() const { return Preds.end(); }
300 edge_iterator succ_begin() const { return Succs.begin(); }
301 edge_iterator succ_end() const { return Succs.end(); }
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000302
303 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
304 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
305
306 bool isExit() const { return Succs.empty(); }
John McCalld935e9c2011-06-15 23:37:01 +0000307 };
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000308
309 const unsigned BBState::OverflowOccurredValue = 0xffffffff;
John McCalld935e9c2011-06-15 23:37:01 +0000310}
311
312void BBState::InitFromPred(const BBState &Other) {
313 PerPtrTopDown = Other.PerPtrTopDown;
314 TopDownPathCount = Other.TopDownPathCount;
315}
316
317void BBState::InitFromSucc(const BBState &Other) {
318 PerPtrBottomUp = Other.PerPtrBottomUp;
319 BottomUpPathCount = Other.BottomUpPathCount;
320}
321
Michael Gottesman97e3df02013-01-14 00:35:14 +0000322/// The top-down traversal uses this to merge information about predecessors to
323/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +0000324void BBState::MergePred(const BBState &Other) {
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000325 if (TopDownPathCount == OverflowOccurredValue)
326 return;
327
John McCalld935e9c2011-06-15 23:37:01 +0000328 // Other.TopDownPathCount can be 0, in which case it is either dead or a
329 // loop backedge. Loop backedges are special.
330 TopDownPathCount += Other.TopDownPathCount;
331
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000332 // In order to be consistent, we clear the top down pointers when by adding
333 // TopDownPathCount becomes OverflowOccurredValue even though "true" overflow
Alp Tokercb402912014-01-24 17:20:08 +0000334 // has not occurred.
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000335 if (TopDownPathCount == OverflowOccurredValue) {
336 clearTopDownPointers();
337 return;
338 }
339
Michael Gottesman4385edf2013-01-14 01:47:53 +0000340 // Check for overflow. If we have overflow, fall back to conservative
341 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +0000342 if (TopDownPathCount < Other.TopDownPathCount) {
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000343 TopDownPathCount = OverflowOccurredValue;
Dan Gohman7c84dad2012-09-12 20:45:17 +0000344 clearTopDownPointers();
345 return;
346 }
347
John McCalld935e9c2011-06-15 23:37:01 +0000348 // For each entry in the other set, if our set has an entry with the same key,
349 // merge the entries. Otherwise, copy the entry and merge it with an empty
350 // entry.
Michael Gottesmana9fc0162015-03-05 23:29:06 +0000351 for (auto MI = Other.top_down_ptr_begin(), ME = Other.top_down_ptr_end();
352 MI != ME; ++MI) {
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000353 auto Pair = PerPtrTopDown.insert(*MI);
354 Pair.first->second.Merge(Pair.second ? TopDownPtrState() : MI->second,
John McCalld935e9c2011-06-15 23:37:01 +0000355 /*TopDown=*/true);
356 }
357
Dan Gohman7e315fc32011-08-11 21:06:32 +0000358 // For each entry in our set, if the other set doesn't have an entry with the
John McCalld935e9c2011-06-15 23:37:01 +0000359 // same key, force it to merge with an empty entry.
Michael Gottesmana9fc0162015-03-05 23:29:06 +0000360 for (auto MI = top_down_ptr_begin(), ME = top_down_ptr_end(); MI != ME; ++MI)
John McCalld935e9c2011-06-15 23:37:01 +0000361 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000362 MI->second.Merge(TopDownPtrState(), /*TopDown=*/true);
John McCalld935e9c2011-06-15 23:37:01 +0000363}
364
Michael Gottesman97e3df02013-01-14 00:35:14 +0000365/// The bottom-up traversal uses this to merge information about successors to
366/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +0000367void BBState::MergeSucc(const BBState &Other) {
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000368 if (BottomUpPathCount == OverflowOccurredValue)
369 return;
370
John McCalld935e9c2011-06-15 23:37:01 +0000371 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
372 // loop backedge. Loop backedges are special.
373 BottomUpPathCount += Other.BottomUpPathCount;
374
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000375 // In order to be consistent, we clear the top down pointers when by adding
376 // BottomUpPathCount becomes OverflowOccurredValue even though "true" overflow
Alp Tokercb402912014-01-24 17:20:08 +0000377 // has not occurred.
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000378 if (BottomUpPathCount == OverflowOccurredValue) {
379 clearBottomUpPointers();
380 return;
381 }
382
Michael Gottesman4385edf2013-01-14 01:47:53 +0000383 // Check for overflow. If we have overflow, fall back to conservative
384 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +0000385 if (BottomUpPathCount < Other.BottomUpPathCount) {
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000386 BottomUpPathCount = OverflowOccurredValue;
Dan Gohman7c84dad2012-09-12 20:45:17 +0000387 clearBottomUpPointers();
388 return;
389 }
390
John McCalld935e9c2011-06-15 23:37:01 +0000391 // For each entry in the other set, if our set has an entry with the
392 // same key, merge the entries. Otherwise, copy the entry and merge
393 // it with an empty entry.
Michael Gottesmana9fc0162015-03-05 23:29:06 +0000394 for (auto MI = Other.bottom_up_ptr_begin(), ME = Other.bottom_up_ptr_end();
395 MI != ME; ++MI) {
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000396 auto Pair = PerPtrBottomUp.insert(*MI);
397 Pair.first->second.Merge(Pair.second ? BottomUpPtrState() : MI->second,
John McCalld935e9c2011-06-15 23:37:01 +0000398 /*TopDown=*/false);
399 }
400
Dan Gohman7e315fc32011-08-11 21:06:32 +0000401 // For each entry in our set, if the other set doesn't have an entry
John McCalld935e9c2011-06-15 23:37:01 +0000402 // with the same key, force it to merge with an empty entry.
Michael Gottesmana9fc0162015-03-05 23:29:06 +0000403 for (auto MI = bottom_up_ptr_begin(), ME = bottom_up_ptr_end(); MI != ME;
404 ++MI)
John McCalld935e9c2011-06-15 23:37:01 +0000405 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000406 MI->second.Merge(BottomUpPtrState(), /*TopDown=*/false);
John McCalld935e9c2011-06-15 23:37:01 +0000407}
408
409namespace {
Michael Gottesman41c01002015-03-06 00:34:33 +0000410
Michael Gottesman97e3df02013-01-14 00:35:14 +0000411 /// \brief The main ARC optimization pass.
John McCalld935e9c2011-06-15 23:37:01 +0000412 class ObjCARCOpt : public FunctionPass {
413 bool Changed;
414 ProvenanceAnalysis PA;
Michael Gottesman41c01002015-03-06 00:34:33 +0000415
416 /// A cache of references to runtime entry point constants.
Michael Gottesman14acfac2013-07-06 01:39:23 +0000417 ARCRuntimeEntryPoints EP;
John McCalld935e9c2011-06-15 23:37:01 +0000418
Michael Gottesman41c01002015-03-06 00:34:33 +0000419 /// A cache of MDKinds that can be passed into other functions to propagate
420 /// MDKind identifiers.
421 ARCMDKindCache MDKindCache;
422
Michael Gottesman5a91bbf2013-05-24 20:44:02 +0000423 // This is used to track if a pointer is stored into an alloca.
424 DenseSet<const Value *> MultiOwnersSet;
425
Michael Gottesman97e3df02013-01-14 00:35:14 +0000426 /// A flag indicating whether this optimization pass should run.
Dan Gohmanceaac7c2011-06-20 23:20:43 +0000427 bool Run;
428
Michael Gottesman97e3df02013-01-14 00:35:14 +0000429 /// Flags which determine whether each of the interesting runtine functions
430 /// is in fact used in the current function.
John McCalld935e9c2011-06-15 23:37:01 +0000431 unsigned UsedInThisFunction;
432
John McCalld935e9c2011-06-15 23:37:01 +0000433 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
Michael Gottesman556ff612013-01-12 01:25:19 +0000434 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000435 ARCInstKind &Class);
John McCalld935e9c2011-06-15 23:37:01 +0000436 void OptimizeIndividualCalls(Function &F);
437
438 void CheckForCFGHazards(const BasicBlock *BB,
439 DenseMap<const BasicBlock *, BBState> &BBStates,
440 BBState &MyStates) const;
Michael Gottesman0be69202015-03-05 23:28:58 +0000441 bool VisitInstructionBottomUp(Instruction *Inst, BasicBlock *BB,
442 BlotMapVector<Value *, RRInfo> &Retains,
Dan Gohman817a7c62012-03-22 18:24:56 +0000443 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +0000444 bool VisitBottomUp(BasicBlock *BB,
445 DenseMap<const BasicBlock *, BBState> &BBStates,
Michael Gottesman0be69202015-03-05 23:28:58 +0000446 BlotMapVector<Value *, RRInfo> &Retains);
Dan Gohman817a7c62012-03-22 18:24:56 +0000447 bool VisitInstructionTopDown(Instruction *Inst,
448 DenseMap<Value *, RRInfo> &Releases,
449 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +0000450 bool VisitTopDown(BasicBlock *BB,
451 DenseMap<const BasicBlock *, BBState> &BBStates,
452 DenseMap<Value *, RRInfo> &Releases);
Michael Gottesman0be69202015-03-05 23:28:58 +0000453 bool Visit(Function &F, DenseMap<const BasicBlock *, BBState> &BBStates,
454 BlotMapVector<Value *, RRInfo> &Retains,
John McCalld935e9c2011-06-15 23:37:01 +0000455 DenseMap<Value *, RRInfo> &Releases);
456
457 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
Michael Gottesman0be69202015-03-05 23:28:58 +0000458 BlotMapVector<Value *, RRInfo> &Retains,
John McCalld935e9c2011-06-15 23:37:01 +0000459 DenseMap<Value *, RRInfo> &Releases,
Michael Gottesman0be69202015-03-05 23:28:58 +0000460 SmallVectorImpl<Instruction *> &DeadInsts, Module *M);
John McCalld935e9c2011-06-15 23:37:01 +0000461
Michael Gottesman67792172015-03-16 07:02:30 +0000462 bool
463 PairUpRetainsAndReleases(DenseMap<const BasicBlock *, BBState> &BBStates,
464 BlotMapVector<Value *, RRInfo> &Retains,
465 DenseMap<Value *, RRInfo> &Releases, Module *M,
466 SmallVectorImpl<Instruction *> &NewRetains,
467 SmallVectorImpl<Instruction *> &NewReleases,
468 SmallVectorImpl<Instruction *> &DeadInsts,
469 RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
470 Value *Arg, bool KnownSafe,
471 bool &AnyPairsCompletelyEliminated);
Michael Gottesman9de6f962013-01-22 21:49:00 +0000472
John McCalld935e9c2011-06-15 23:37:01 +0000473 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
Michael Gottesman0be69202015-03-05 23:28:58 +0000474 BlotMapVector<Value *, RRInfo> &Retains,
475 DenseMap<Value *, RRInfo> &Releases, Module *M);
John McCalld935e9c2011-06-15 23:37:01 +0000476
477 void OptimizeWeakCalls(Function &F);
478
479 bool OptimizeSequences(Function &F);
480
481 void OptimizeReturns(Function &F);
482
Michael Gottesman9c118152013-04-29 06:16:57 +0000483#ifndef NDEBUG
484 void GatherStatistics(Function &F, bool AfterOptimization = false);
485#endif
486
Craig Topper3e4c6972014-03-05 09:10:37 +0000487 void getAnalysisUsage(AnalysisUsage &AU) const override;
488 bool doInitialization(Module &M) override;
489 bool runOnFunction(Function &F) override;
490 void releaseMemory() override;
John McCalld935e9c2011-06-15 23:37:01 +0000491
492 public:
493 static char ID;
494 ObjCARCOpt() : FunctionPass(ID) {
495 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
496 }
497 };
498}
499
500char ObjCARCOpt::ID = 0;
501INITIALIZE_PASS_BEGIN(ObjCARCOpt,
502 "objc-arc", "ObjC ARC optimization", false, false)
503INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
504INITIALIZE_PASS_END(ObjCARCOpt,
505 "objc-arc", "ObjC ARC optimization", false, false)
506
507Pass *llvm::createObjCARCOptPass() {
508 return new ObjCARCOpt();
509}
510
511void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
512 AU.addRequired<ObjCARCAliasAnalysis>();
513 AU.addRequired<AliasAnalysis>();
514 // ARC optimization doesn't currently split critical edges.
515 AU.setPreservesCFG();
516}
517
Michael Gottesman97e3df02013-01-14 00:35:14 +0000518/// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is
519/// not a return value. Or, if it can be paired with an
520/// objc_autoreleaseReturnValue, delete the pair and return true.
John McCalld935e9c2011-06-15 23:37:01 +0000521bool
522ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +0000523 // Check for the argument being from an immediately preceding call or invoke.
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000524 const Value *Arg = GetArgRCIdentityRoot(RetainRV);
Dan Gohmandae33492012-04-27 18:56:31 +0000525 ImmutableCallSite CS(Arg);
526 if (const Instruction *Call = CS.getInstruction()) {
John McCalld935e9c2011-06-15 23:37:01 +0000527 if (Call->getParent() == RetainRV->getParent()) {
Dan Gohmandae33492012-04-27 18:56:31 +0000528 BasicBlock::const_iterator I = Call;
John McCalld935e9c2011-06-15 23:37:01 +0000529 ++I;
Michael Gottesman65c24812013-03-25 09:27:43 +0000530 while (IsNoopInstruction(I)) ++I;
John McCalld935e9c2011-06-15 23:37:01 +0000531 if (&*I == RetainRV)
532 return false;
Dan Gohmandae33492012-04-27 18:56:31 +0000533 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +0000534 BasicBlock *RetainRVParent = RetainRV->getParent();
535 if (II->getNormalDest() == RetainRVParent) {
Dan Gohmandae33492012-04-27 18:56:31 +0000536 BasicBlock::const_iterator I = RetainRVParent->begin();
Michael Gottesman65c24812013-03-25 09:27:43 +0000537 while (IsNoopInstruction(I)) ++I;
Dan Gohmane3ed2b02012-03-23 18:09:00 +0000538 if (&*I == RetainRV)
539 return false;
540 }
John McCalld935e9c2011-06-15 23:37:01 +0000541 }
Dan Gohmane3ed2b02012-03-23 18:09:00 +0000542 }
John McCalld935e9c2011-06-15 23:37:01 +0000543
544 // Check for being preceded by an objc_autoreleaseReturnValue on the same
545 // pointer. In this case, we can delete the pair.
546 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
547 if (I != Begin) {
Michael Gottesman65c24812013-03-25 09:27:43 +0000548 do --I; while (I != Begin && IsNoopInstruction(I));
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000549 if (GetBasicARCInstKind(I) == ARCInstKind::AutoreleaseRV &&
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000550 GetArgRCIdentityRoot(I) == Arg) {
John McCalld935e9c2011-06-15 23:37:01 +0000551 Changed = true;
552 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +0000553
Michael Gottesman89279f82013-04-05 18:10:41 +0000554 DEBUG(dbgs() << "Erasing autoreleaseRV,retainRV pair: " << *I << "\n"
555 << "Erasing " << *RetainRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +0000556
John McCalld935e9c2011-06-15 23:37:01 +0000557 EraseInstruction(I);
558 EraseInstruction(RetainRV);
559 return true;
560 }
561 }
562
563 // Turn it to a plain objc_retain.
564 Changed = true;
565 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +0000566
Michael Gottesman89279f82013-04-05 18:10:41 +0000567 DEBUG(dbgs() << "Transforming objc_retainAutoreleasedReturnValue => "
Michael Gottesmandef07bb2013-01-05 17:55:42 +0000568 "objc_retain since the operand is not a return value.\n"
Michael Gottesman89279f82013-04-05 18:10:41 +0000569 "Old = " << *RetainRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +0000570
Michael Gottesmanca3a4722015-03-16 07:02:24 +0000571 Constant *NewDecl = EP.get(ARCRuntimeEntryPointKind::Retain);
Michael Gottesman14acfac2013-07-06 01:39:23 +0000572 cast<CallInst>(RetainRV)->setCalledFunction(NewDecl);
Michael Gottesmandef07bb2013-01-05 17:55:42 +0000573
Michael Gottesman89279f82013-04-05 18:10:41 +0000574 DEBUG(dbgs() << "New = " << *RetainRV << "\n");
Michael Gottesmandef07bb2013-01-05 17:55:42 +0000575
John McCalld935e9c2011-06-15 23:37:01 +0000576 return false;
577}
578
Michael Gottesman97e3df02013-01-14 00:35:14 +0000579/// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not
580/// used as a return value.
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000581void ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F,
582 Instruction *AutoreleaseRV,
583 ARCInstKind &Class) {
John McCalld935e9c2011-06-15 23:37:01 +0000584 // Check for a return of the pointer value.
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000585 const Value *Ptr = GetArgRCIdentityRoot(AutoreleaseRV);
Dan Gohman10a18d52011-08-12 00:36:31 +0000586 SmallVector<const Value *, 2> Users;
587 Users.push_back(Ptr);
588 do {
589 Ptr = Users.pop_back_val();
Chandler Carruthcdf47882014-03-09 03:16:01 +0000590 for (const User *U : Ptr->users()) {
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000591 if (isa<ReturnInst>(U) || GetBasicARCInstKind(U) == ARCInstKind::RetainRV)
Dan Gohman10a18d52011-08-12 00:36:31 +0000592 return;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000593 if (isa<BitCastInst>(U))
594 Users.push_back(U);
Dan Gohman10a18d52011-08-12 00:36:31 +0000595 }
596 } while (!Users.empty());
John McCalld935e9c2011-06-15 23:37:01 +0000597
598 Changed = true;
599 ++NumPeeps;
Michael Gottesman1bf69082013-01-06 21:07:11 +0000600
Michael Gottesman89279f82013-04-05 18:10:41 +0000601 DEBUG(dbgs() << "Transforming objc_autoreleaseReturnValue => "
Michael Gottesman1bf69082013-01-06 21:07:11 +0000602 "objc_autorelease since its operand is not used as a return "
603 "value.\n"
Michael Gottesman89279f82013-04-05 18:10:41 +0000604 "Old = " << *AutoreleaseRV << "\n");
Michael Gottesman1bf69082013-01-06 21:07:11 +0000605
Michael Gottesmanc9656fa2013-01-12 01:25:15 +0000606 CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
Michael Gottesmanca3a4722015-03-16 07:02:24 +0000607 Constant *NewDecl = EP.get(ARCRuntimeEntryPointKind::Autorelease);
Michael Gottesman14acfac2013-07-06 01:39:23 +0000608 AutoreleaseRVCI->setCalledFunction(NewDecl);
Michael Gottesmanc9656fa2013-01-12 01:25:15 +0000609 AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000610 Class = ARCInstKind::Autorelease;
Michael Gottesman10426b52013-01-07 21:26:07 +0000611
Michael Gottesman89279f82013-04-05 18:10:41 +0000612 DEBUG(dbgs() << "New: " << *AutoreleaseRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +0000613
John McCalld935e9c2011-06-15 23:37:01 +0000614}
615
Michael Gottesman97e3df02013-01-14 00:35:14 +0000616/// Visit each call, one at a time, and make simplifications without doing any
617/// additional analysis.
John McCalld935e9c2011-06-15 23:37:01 +0000618void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
Michael Gottesman89279f82013-04-05 18:10:41 +0000619 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeIndividualCalls ==\n");
John McCalld935e9c2011-06-15 23:37:01 +0000620 // Reset all the flags in preparation for recomputing them.
621 UsedInThisFunction = 0;
622
623 // Visit all objc_* calls in F.
624 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
625 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +0000626
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000627 ARCInstKind Class = GetBasicARCInstKind(Inst);
John McCalld935e9c2011-06-15 23:37:01 +0000628
Michael Gottesman89279f82013-04-05 18:10:41 +0000629 DEBUG(dbgs() << "Visiting: Class: " << Class << "; " << *Inst << "\n");
Michael Gottesman782e3442013-01-17 18:32:34 +0000630
John McCalld935e9c2011-06-15 23:37:01 +0000631 switch (Class) {
632 default: break;
633
634 // Delete no-op casts. These function calls have special semantics, but
635 // the semantics are entirely implemented via lowering in the front-end,
636 // so by the time they reach the optimizer, they are just no-op calls
637 // which return their argument.
638 //
639 // There are gray areas here, as the ability to cast reference-counted
640 // pointers to raw void* and back allows code to break ARC assumptions,
641 // however these are currently considered to be unimportant.
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000642 case ARCInstKind::NoopCast:
John McCalld935e9c2011-06-15 23:37:01 +0000643 Changed = true;
644 ++NumNoops;
Michael Gottesman89279f82013-04-05 18:10:41 +0000645 DEBUG(dbgs() << "Erasing no-op cast: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +0000646 EraseInstruction(Inst);
647 continue;
648
649 // If the pointer-to-weak-pointer is null, it's undefined behavior.
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000650 case ARCInstKind::StoreWeak:
651 case ARCInstKind::LoadWeak:
652 case ARCInstKind::LoadWeakRetained:
653 case ARCInstKind::InitWeak:
654 case ARCInstKind::DestroyWeak: {
John McCalld935e9c2011-06-15 23:37:01 +0000655 CallInst *CI = cast<CallInst>(Inst);
Michael Gottesman65c24812013-03-25 09:27:43 +0000656 if (IsNullOrUndef(CI->getArgOperand(0))) {
Dan Gohman670f9372012-04-13 18:57:48 +0000657 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +0000658 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +0000659 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
660 Constant::getNullValue(Ty),
661 CI);
Michael Gottesman10426b52013-01-07 21:26:07 +0000662 llvm::Value *NewValue = UndefValue::get(CI->getType());
Michael Gottesman89279f82013-04-05 18:10:41 +0000663 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
664 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
Michael Gottesmanfec61c02013-01-06 21:54:30 +0000665 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +0000666 CI->eraseFromParent();
667 continue;
668 }
669 break;
670 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000671 case ARCInstKind::CopyWeak:
672 case ARCInstKind::MoveWeak: {
John McCalld935e9c2011-06-15 23:37:01 +0000673 CallInst *CI = cast<CallInst>(Inst);
Michael Gottesman65c24812013-03-25 09:27:43 +0000674 if (IsNullOrUndef(CI->getArgOperand(0)) ||
675 IsNullOrUndef(CI->getArgOperand(1))) {
Dan Gohman670f9372012-04-13 18:57:48 +0000676 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +0000677 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +0000678 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
679 Constant::getNullValue(Ty),
680 CI);
Michael Gottesmanfec61c02013-01-06 21:54:30 +0000681
682 llvm::Value *NewValue = UndefValue::get(CI->getType());
Michael Gottesman89279f82013-04-05 18:10:41 +0000683 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
684 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +0000685
Michael Gottesmanfec61c02013-01-06 21:54:30 +0000686 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +0000687 CI->eraseFromParent();
688 continue;
689 }
690 break;
691 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000692 case ARCInstKind::RetainRV:
John McCalld935e9c2011-06-15 23:37:01 +0000693 if (OptimizeRetainRVCall(F, Inst))
694 continue;
695 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000696 case ARCInstKind::AutoreleaseRV:
Michael Gottesman556ff612013-01-12 01:25:19 +0000697 OptimizeAutoreleaseRVCall(F, Inst, Class);
John McCalld935e9c2011-06-15 23:37:01 +0000698 break;
699 }
700
Michael Gottesmanb8c88362013-04-03 02:57:24 +0000701 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
John McCalld935e9c2011-06-15 23:37:01 +0000702 if (IsAutorelease(Class) && Inst->use_empty()) {
703 CallInst *Call = cast<CallInst>(Inst);
704 const Value *Arg = Call->getArgOperand(0);
705 Arg = FindSingleUseIdentifiedObject(Arg);
706 if (Arg) {
707 Changed = true;
708 ++NumAutoreleases;
709
710 // Create the declaration lazily.
711 LLVMContext &C = Inst->getContext();
Michael Gottesman01df4502013-07-06 01:41:35 +0000712
Michael Gottesmanca3a4722015-03-16 07:02:24 +0000713 Constant *Decl = EP.get(ARCRuntimeEntryPointKind::Release);
Michael Gottesman14acfac2013-07-06 01:39:23 +0000714 CallInst *NewCall = CallInst::Create(Decl, Call->getArgOperand(0), "",
715 Call);
Michael Gottesman65cb7372015-03-16 07:02:27 +0000716 NewCall->setMetadata(MDKindCache.get(ARCMDKindID::ImpreciseRelease),
Michael Gottesman41c01002015-03-06 00:34:33 +0000717 MDNode::get(C, None));
Michael Gottesman10426b52013-01-07 21:26:07 +0000718
Michael Gottesman89279f82013-04-05 18:10:41 +0000719 DEBUG(dbgs() << "Replacing autorelease{,RV}(x) with objc_release(x) "
720 "since x is otherwise unused.\nOld: " << *Call << "\nNew: "
721 << *NewCall << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +0000722
John McCalld935e9c2011-06-15 23:37:01 +0000723 EraseInstruction(Call);
724 Inst = NewCall;
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000725 Class = ARCInstKind::Release;
John McCalld935e9c2011-06-15 23:37:01 +0000726 }
727 }
728
729 // For functions which can never be passed stack arguments, add
730 // a tail keyword.
731 if (IsAlwaysTail(Class)) {
732 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +0000733 DEBUG(dbgs() << "Adding tail keyword to function since it can never be "
734 "passed stack args: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +0000735 cast<CallInst>(Inst)->setTailCall();
736 }
737
Michael Gottesmanc9656fa2013-01-12 01:25:15 +0000738 // Ensure that functions that can never have a "tail" keyword due to the
739 // semantics of ARC truly do not do so.
740 if (IsNeverTail(Class)) {
741 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +0000742 DEBUG(dbgs() << "Removing tail keyword from function: " << *Inst <<
Michael Gottesmanc9656fa2013-01-12 01:25:15 +0000743 "\n");
744 cast<CallInst>(Inst)->setTailCall(false);
745 }
746
John McCalld935e9c2011-06-15 23:37:01 +0000747 // Set nounwind as needed.
748 if (IsNoThrow(Class)) {
749 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +0000750 DEBUG(dbgs() << "Found no throw class. Setting nounwind on: " << *Inst
751 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +0000752 cast<CallInst>(Inst)->setDoesNotThrow();
753 }
754
755 if (!IsNoopOnNull(Class)) {
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000756 UsedInThisFunction |= 1 << unsigned(Class);
John McCalld935e9c2011-06-15 23:37:01 +0000757 continue;
758 }
759
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000760 const Value *Arg = GetArgRCIdentityRoot(Inst);
John McCalld935e9c2011-06-15 23:37:01 +0000761
762 // ARC calls with null are no-ops. Delete them.
Michael Gottesman65c24812013-03-25 09:27:43 +0000763 if (IsNullOrUndef(Arg)) {
John McCalld935e9c2011-06-15 23:37:01 +0000764 Changed = true;
765 ++NumNoops;
Michael Gottesman89279f82013-04-05 18:10:41 +0000766 DEBUG(dbgs() << "ARC calls with null are no-ops. Erasing: " << *Inst
767 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +0000768 EraseInstruction(Inst);
769 continue;
770 }
771
772 // Keep track of which of retain, release, autorelease, and retain_block
773 // are actually present in this function.
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000774 UsedInThisFunction |= 1 << unsigned(Class);
John McCalld935e9c2011-06-15 23:37:01 +0000775
776 // If Arg is a PHI, and one or more incoming values to the
777 // PHI are null, and the call is control-equivalent to the PHI, and there
778 // are no relevant side effects between the PHI and the call, the call
779 // could be pushed up to just those paths with non-null incoming values.
780 // For now, don't bother splitting critical edges for this.
781 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
782 Worklist.push_back(std::make_pair(Inst, Arg));
783 do {
784 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
785 Inst = Pair.first;
786 Arg = Pair.second;
787
788 const PHINode *PN = dyn_cast<PHINode>(Arg);
789 if (!PN) continue;
790
791 // Determine if the PHI has any null operands, or any incoming
792 // critical edges.
793 bool HasNull = false;
794 bool HasCriticalEdges = false;
795 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
796 Value *Incoming =
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000797 GetRCIdentityRoot(PN->getIncomingValue(i));
Michael Gottesman65c24812013-03-25 09:27:43 +0000798 if (IsNullOrUndef(Incoming))
John McCalld935e9c2011-06-15 23:37:01 +0000799 HasNull = true;
800 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
801 .getNumSuccessors() != 1) {
802 HasCriticalEdges = true;
803 break;
804 }
805 }
806 // If we have null operands and no critical edges, optimize.
807 if (!HasCriticalEdges && HasNull) {
808 SmallPtrSet<Instruction *, 4> DependingInstructions;
809 SmallPtrSet<const BasicBlock *, 4> Visited;
810
811 // Check that there is nothing that cares about the reference
812 // count between the call and the phi.
Dan Gohman8478d762012-04-13 00:59:57 +0000813 switch (Class) {
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000814 case ARCInstKind::Retain:
815 case ARCInstKind::RetainBlock:
Dan Gohman8478d762012-04-13 00:59:57 +0000816 // These can always be moved up.
817 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000818 case ARCInstKind::Release:
Dan Gohman41375a32012-05-08 23:39:44 +0000819 // These can't be moved across things that care about the retain
820 // count.
Dan Gohman8478d762012-04-13 00:59:57 +0000821 FindDependencies(NeedsPositiveRetainCount, Arg,
822 Inst->getParent(), Inst,
823 DependingInstructions, Visited, PA);
824 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000825 case ARCInstKind::Autorelease:
Dan Gohman8478d762012-04-13 00:59:57 +0000826 // These can't be moved across autorelease pool scope boundaries.
827 FindDependencies(AutoreleasePoolBoundary, Arg,
828 Inst->getParent(), Inst,
829 DependingInstructions, Visited, PA);
830 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000831 case ARCInstKind::RetainRV:
832 case ARCInstKind::AutoreleaseRV:
Dan Gohman8478d762012-04-13 00:59:57 +0000833 // Don't move these; the RV optimization depends on the autoreleaseRV
834 // being tail called, and the retainRV being immediately after a call
835 // (which might still happen if we get lucky with codegen layout, but
836 // it's not worth taking the chance).
837 continue;
838 default:
839 llvm_unreachable("Invalid dependence flavor");
840 }
841
John McCalld935e9c2011-06-15 23:37:01 +0000842 if (DependingInstructions.size() == 1 &&
843 *DependingInstructions.begin() == PN) {
844 Changed = true;
845 ++NumPartialNoops;
846 // Clone the call into each predecessor that has a non-null value.
847 CallInst *CInst = cast<CallInst>(Inst);
Chris Lattner229907c2011-07-18 04:54:35 +0000848 Type *ParamTy = CInst->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +0000849 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
850 Value *Incoming =
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000851 GetRCIdentityRoot(PN->getIncomingValue(i));
Michael Gottesman65c24812013-03-25 09:27:43 +0000852 if (!IsNullOrUndef(Incoming)) {
John McCalld935e9c2011-06-15 23:37:01 +0000853 CallInst *Clone = cast<CallInst>(CInst->clone());
854 Value *Op = PN->getIncomingValue(i);
855 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
856 if (Op->getType() != ParamTy)
857 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
858 Clone->setArgOperand(0, Op);
859 Clone->insertBefore(InsertPos);
Michael Gottesmanc189a392013-01-09 19:23:24 +0000860
Michael Gottesman89279f82013-04-05 18:10:41 +0000861 DEBUG(dbgs() << "Cloning "
Michael Gottesmanc189a392013-01-09 19:23:24 +0000862 << *CInst << "\n"
Michael Gottesman89279f82013-04-05 18:10:41 +0000863 "And inserting clone at " << *InsertPos << "\n");
John McCalld935e9c2011-06-15 23:37:01 +0000864 Worklist.push_back(std::make_pair(Clone, Incoming));
865 }
866 }
867 // Erase the original call.
Michael Gottesmanc189a392013-01-09 19:23:24 +0000868 DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +0000869 EraseInstruction(CInst);
870 continue;
871 }
872 }
873 } while (!Worklist.empty());
874 }
875}
876
Michael Gottesman323964c2013-04-18 05:39:45 +0000877/// If we have a top down pointer in the S_Use state, make sure that there are
878/// no CFG hazards by checking the states of various bottom up pointers.
879static void CheckForUseCFGHazard(const Sequence SuccSSeq,
880 const bool SuccSRRIKnownSafe,
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000881 TopDownPtrState &S,
Michael Gottesman323964c2013-04-18 05:39:45 +0000882 bool &SomeSuccHasSame,
883 bool &AllSuccsHaveSame,
Michael Gottesmane67f40c2013-05-24 20:44:05 +0000884 bool &NotAllSeqEqualButKnownSafe,
Michael Gottesman323964c2013-04-18 05:39:45 +0000885 bool &ShouldContinue) {
886 switch (SuccSSeq) {
887 case S_CanRelease: {
Michael Gottesman93132252013-06-21 06:59:02 +0000888 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe) {
Michael Gottesman323964c2013-04-18 05:39:45 +0000889 S.ClearSequenceProgress();
890 break;
891 }
Michael Gottesman2f294592013-06-21 19:12:36 +0000892 S.SetCFGHazardAfflicted(true);
Michael Gottesman323964c2013-04-18 05:39:45 +0000893 ShouldContinue = true;
894 break;
895 }
896 case S_Use:
897 SomeSuccHasSame = true;
898 break;
899 case S_Stop:
900 case S_Release:
901 case S_MovableRelease:
Michael Gottesman93132252013-06-21 06:59:02 +0000902 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe)
Michael Gottesman323964c2013-04-18 05:39:45 +0000903 AllSuccsHaveSame = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +0000904 else
905 NotAllSeqEqualButKnownSafe = true;
Michael Gottesman323964c2013-04-18 05:39:45 +0000906 break;
907 case S_Retain:
908 llvm_unreachable("bottom-up pointer in retain state!");
909 case S_None:
910 llvm_unreachable("This should have been handled earlier.");
911 }
912}
913
914/// If we have a Top Down pointer in the S_CanRelease state, make sure that
915/// there are no CFG hazards by checking the states of various bottom up
916/// pointers.
917static void CheckForCanReleaseCFGHazard(const Sequence SuccSSeq,
918 const bool SuccSRRIKnownSafe,
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000919 TopDownPtrState &S,
Michael Gottesman323964c2013-04-18 05:39:45 +0000920 bool &SomeSuccHasSame,
Michael Gottesmane67f40c2013-05-24 20:44:05 +0000921 bool &AllSuccsHaveSame,
922 bool &NotAllSeqEqualButKnownSafe) {
Michael Gottesman323964c2013-04-18 05:39:45 +0000923 switch (SuccSSeq) {
924 case S_CanRelease:
925 SomeSuccHasSame = true;
926 break;
927 case S_Stop:
928 case S_Release:
929 case S_MovableRelease:
930 case S_Use:
Michael Gottesman93132252013-06-21 06:59:02 +0000931 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe)
Michael Gottesman323964c2013-04-18 05:39:45 +0000932 AllSuccsHaveSame = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +0000933 else
934 NotAllSeqEqualButKnownSafe = true;
Michael Gottesman323964c2013-04-18 05:39:45 +0000935 break;
936 case S_Retain:
937 llvm_unreachable("bottom-up pointer in retain state!");
938 case S_None:
939 llvm_unreachable("This should have been handled earlier.");
940 }
941}
942
Michael Gottesman97e3df02013-01-14 00:35:14 +0000943/// Check for critical edges, loop boundaries, irreducible control flow, or
944/// other CFG structures where moving code across the edge would result in it
945/// being executed more.
John McCalld935e9c2011-06-15 23:37:01 +0000946void
947ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
948 DenseMap<const BasicBlock *, BBState> &BBStates,
949 BBState &MyStates) const {
950 // If any top-down local-use or possible-dec has a succ which is earlier in
951 // the sequence, forget it.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000952 for (auto I = MyStates.top_down_ptr_begin(), E = MyStates.top_down_ptr_end();
953 I != E; ++I) {
954 TopDownPtrState &S = I->second;
Michael Gottesman323964c2013-04-18 05:39:45 +0000955 const Sequence Seq = I->second.GetSeq();
Dan Gohman0155f302012-02-17 18:59:53 +0000956
Michael Gottesman323964c2013-04-18 05:39:45 +0000957 // We only care about S_Retain, S_CanRelease, and S_Use.
958 if (Seq == S_None)
959 continue;
Dan Gohman0155f302012-02-17 18:59:53 +0000960
Michael Gottesman323964c2013-04-18 05:39:45 +0000961 // Make sure that if extra top down states are added in the future that this
962 // code is updated to handle it.
963 assert((Seq == S_Retain || Seq == S_CanRelease || Seq == S_Use) &&
964 "Unknown top down sequence state.");
965
966 const Value *Arg = I->first;
967 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
968 bool SomeSuccHasSame = false;
969 bool AllSuccsHaveSame = true;
Michael Gottesmane67f40c2013-05-24 20:44:05 +0000970 bool NotAllSeqEqualButKnownSafe = false;
Michael Gottesman323964c2013-04-18 05:39:45 +0000971
972 succ_const_iterator SI(TI), SE(TI, false);
973
974 for (; SI != SE; ++SI) {
975 // If VisitBottomUp has pointer information for this successor, take
976 // what we know about it.
977 const DenseMap<const BasicBlock *, BBState>::iterator BBI =
978 BBStates.find(*SI);
979 assert(BBI != BBStates.end());
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000980 const BottomUpPtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
Michael Gottesman323964c2013-04-18 05:39:45 +0000981 const Sequence SuccSSeq = SuccS.GetSeq();
982
983 // If bottom up, the pointer is in an S_None state, clear the sequence
984 // progress since the sequence in the bottom up state finished
985 // suggesting a mismatch in between retains/releases. This is true for
986 // all three cases that we are handling here: S_Retain, S_Use, and
987 // S_CanRelease.
988 if (SuccSSeq == S_None) {
Dan Gohman12130272011-08-12 00:26:31 +0000989 S.ClearSequenceProgress();
Michael Gottesman323964c2013-04-18 05:39:45 +0000990 continue;
991 }
992
993 // If we have S_Use or S_CanRelease, perform our check for cfg hazard
994 // checks.
Michael Gottesman93132252013-06-21 06:59:02 +0000995 const bool SuccSRRIKnownSafe = SuccS.IsKnownSafe();
Michael Gottesman323964c2013-04-18 05:39:45 +0000996
997 // *NOTE* We do not use Seq from above here since we are allowing for
998 // S.GetSeq() to change while we are visiting basic blocks.
999 switch(S.GetSeq()) {
1000 case S_Use: {
1001 bool ShouldContinue = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001002 CheckForUseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S, SomeSuccHasSame,
1003 AllSuccsHaveSame, NotAllSeqEqualButKnownSafe,
Michael Gottesman323964c2013-04-18 05:39:45 +00001004 ShouldContinue);
1005 if (ShouldContinue)
1006 continue;
1007 break;
1008 }
1009 case S_CanRelease: {
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001010 CheckForCanReleaseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S,
1011 SomeSuccHasSame, AllSuccsHaveSame,
1012 NotAllSeqEqualButKnownSafe);
Michael Gottesman323964c2013-04-18 05:39:45 +00001013 break;
1014 }
1015 case S_Retain:
1016 case S_None:
1017 case S_Stop:
1018 case S_Release:
1019 case S_MovableRelease:
1020 break;
1021 }
John McCalld935e9c2011-06-15 23:37:01 +00001022 }
Michael Gottesman323964c2013-04-18 05:39:45 +00001023
1024 // If the state at the other end of any of the successor edges
1025 // matches the current state, require all edges to match. This
1026 // guards against loops in the middle of a sequence.
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001027 if (SomeSuccHasSame && !AllSuccsHaveSame) {
Michael Gottesman323964c2013-04-18 05:39:45 +00001028 S.ClearSequenceProgress();
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001029 } else if (NotAllSeqEqualButKnownSafe) {
1030 // If we would have cleared the state foregoing the fact that we are known
1031 // safe, stop code motion. This is because whether or not it is safe to
1032 // remove RR pairs via KnownSafe is an orthogonal concept to whether we
1033 // are allowed to perform code motion.
Michael Gottesman2f294592013-06-21 19:12:36 +00001034 S.SetCFGHazardAfflicted(true);
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001035 }
Michael Gottesman323964c2013-04-18 05:39:45 +00001036 }
John McCalld935e9c2011-06-15 23:37:01 +00001037}
1038
Michael Gottesman0be69202015-03-05 23:28:58 +00001039bool ObjCARCOpt::VisitInstructionBottomUp(
1040 Instruction *Inst, BasicBlock *BB, BlotMapVector<Value *, RRInfo> &Retains,
1041 BBState &MyStates) {
Dan Gohman817a7c62012-03-22 18:24:56 +00001042 bool NestingDetected = false;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001043 ARCInstKind Class = GetARCInstKind(Inst);
Craig Topperf40110f2014-04-25 05:29:35 +00001044 const Value *Arg = nullptr;
Michael Gottesman79249972013-04-05 23:46:45 +00001045
Michael Gottesman1d8d2572013-04-05 22:54:28 +00001046 DEBUG(dbgs() << "Class: " << Class << "\n");
Michael Gottesman79249972013-04-05 23:46:45 +00001047
Dan Gohman817a7c62012-03-22 18:24:56 +00001048 switch (Class) {
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001049 case ARCInstKind::Release: {
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001050 Arg = GetArgRCIdentityRoot(Inst);
Dan Gohman817a7c62012-03-22 18:24:56 +00001051
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001052 BottomUpPtrState &S = MyStates.getPtrBottomUpState(Arg);
Michael Gottesman4eae3962015-03-06 00:34:39 +00001053 NestingDetected |= S.InitBottomUp(MDKindCache, Inst);
Dan Gohman817a7c62012-03-22 18:24:56 +00001054 break;
1055 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001056 case ARCInstKind::RetainBlock:
Michael Gottesman158fdf62013-03-28 20:11:19 +00001057 // In OptimizeIndividualCalls, we have strength reduced all optimizable
1058 // objc_retainBlocks to objc_retains. Thus at this point any
1059 // objc_retainBlocks that we see are not optimizable.
1060 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001061 case ARCInstKind::Retain:
1062 case ARCInstKind::RetainRV: {
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001063 Arg = GetArgRCIdentityRoot(Inst);
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001064 BottomUpPtrState &S = MyStates.getPtrBottomUpState(Arg);
Michael Gottesman60805962015-03-06 00:34:42 +00001065 if (S.MatchWithRetain()) {
1066 // Don't do retain+release tracking for ARCInstKind::RetainRV, because
1067 // it's better to let it remain as the first instruction after a call.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001068 if (Class != ARCInstKind::RetainRV)
Michael Gottesmane3943d02013-06-21 19:44:30 +00001069 Retains[Inst] = S.GetRRInfo();
Dan Gohman817a7c62012-03-22 18:24:56 +00001070 S.ClearSequenceProgress();
Dan Gohman817a7c62012-03-22 18:24:56 +00001071 }
Michael Gottesman31ba23a2013-04-05 22:54:32 +00001072 // A retain moving bottom up can be a use.
1073 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001074 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001075 case ARCInstKind::AutoreleasepoolPop:
Dan Gohman817a7c62012-03-22 18:24:56 +00001076 // Conservatively, clear MyStates for all known pointers.
1077 MyStates.clearBottomUpPointers();
1078 return NestingDetected;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001079 case ARCInstKind::AutoreleasepoolPush:
1080 case ARCInstKind::None:
Dan Gohman817a7c62012-03-22 18:24:56 +00001081 // These are irrelevant.
1082 return NestingDetected;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001083 case ARCInstKind::User:
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001084 // If we have a store into an alloca of a pointer we are tracking, the
1085 // pointer has multiple owners implying that we must be more conservative.
1086 //
1087 // This comes up in the context of a pointer being ``KnownSafe''. In the
Alp Tokercb402912014-01-24 17:20:08 +00001088 // presence of a block being initialized, the frontend will emit the
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001089 // objc_retain on the original pointer and the release on the pointer loaded
1090 // from the alloca. The optimizer will through the provenance analysis
1091 // realize that the two are related, but since we only require KnownSafe in
1092 // one direction, will match the inner retain on the original pointer with
1093 // the guard release on the original pointer. This is fixed by ensuring that
Alp Tokercb402912014-01-24 17:20:08 +00001094 // in the presence of allocas we only unconditionally remove pointers if
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001095 // both our retain and our release are KnownSafe.
1096 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001097 const DataLayout &DL = BB->getModule()->getDataLayout();
1098 if (AreAnyUnderlyingObjectsAnAlloca(SI->getPointerOperand(), DL)) {
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001099 auto I = MyStates.findPtrBottomUpState(
1100 GetRCIdentityRoot(SI->getValueOperand()));
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001101 if (I != MyStates.bottom_up_ptr_end())
Michael Gottesman5a91bbf2013-05-24 20:44:02 +00001102 MultiOwnersSet.insert(I->first);
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001103 }
1104 }
1105 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001106 default:
1107 break;
1108 }
1109
1110 // Consider any other possible effects of this instruction on each
1111 // pointer being tracked.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001112 for (auto MI = MyStates.bottom_up_ptr_begin(),
1113 ME = MyStates.bottom_up_ptr_end();
1114 MI != ME; ++MI) {
Dan Gohman817a7c62012-03-22 18:24:56 +00001115 const Value *Ptr = MI->first;
1116 if (Ptr == Arg)
1117 continue; // Handled above.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001118 BottomUpPtrState &S = MI->second;
Dan Gohman817a7c62012-03-22 18:24:56 +00001119
Michael Gottesman16e6a202015-03-06 02:07:12 +00001120 if (S.HandlePotentialAlterRefCount(Inst, Ptr, PA, Class))
1121 continue;
Dan Gohman817a7c62012-03-22 18:24:56 +00001122
Michael Gottesman16e6a202015-03-06 02:07:12 +00001123 S.HandlePotentialUse(BB, Inst, Ptr, PA, Class);
Dan Gohman817a7c62012-03-22 18:24:56 +00001124 }
1125
1126 return NestingDetected;
1127}
1128
Michael Gottesman0be69202015-03-05 23:28:58 +00001129bool ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
1130 DenseMap<const BasicBlock *, BBState> &BBStates,
1131 BlotMapVector<Value *, RRInfo> &Retains) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001132
1133 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitBottomUp ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00001134
John McCalld935e9c2011-06-15 23:37:01 +00001135 bool NestingDetected = false;
1136 BBState &MyStates = BBStates[BB];
1137
1138 // Merge the states from each successor to compute the initial state
1139 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00001140 BBState::edge_iterator SI(MyStates.succ_begin()),
1141 SE(MyStates.succ_end());
1142 if (SI != SE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001143 const BasicBlock *Succ = *SI;
1144 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
1145 assert(I != BBStates.end());
1146 MyStates.InitFromSucc(I->second);
1147 ++SI;
1148 for (; SI != SE; ++SI) {
1149 Succ = *SI;
1150 I = BBStates.find(Succ);
1151 assert(I != BBStates.end());
1152 MyStates.MergeSucc(I->second);
1153 }
Michael Gottesman60f6b282013-03-29 05:13:07 +00001154 }
Michael Gottesmancd4de0f2013-03-26 00:42:09 +00001155
John McCalld935e9c2011-06-15 23:37:01 +00001156 // Visit all the instructions, bottom-up.
1157 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001158 Instruction *Inst = std::prev(I);
Dan Gohman5c70fad2012-03-23 17:47:54 +00001159
1160 // Invoke instructions are visited as part of their successors (below).
1161 if (isa<InvokeInst>(Inst))
1162 continue;
1163
Michael Gottesman89279f82013-04-05 18:10:41 +00001164 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001165
Dan Gohman5c70fad2012-03-23 17:47:54 +00001166 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
1167 }
1168
Dan Gohmandae33492012-04-27 18:56:31 +00001169 // If there's a predecessor with an invoke, visit the invoke as if it were
1170 // part of this block, since we can't insert code after an invoke in its own
1171 // block, and we don't want to split critical edges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001172 for (BBState::edge_iterator PI(MyStates.pred_begin()),
1173 PE(MyStates.pred_end()); PI != PE; ++PI) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00001174 BasicBlock *Pred = *PI;
Dan Gohmandae33492012-04-27 18:56:31 +00001175 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
1176 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
Dan Gohman817a7c62012-03-22 18:24:56 +00001177 }
John McCalld935e9c2011-06-15 23:37:01 +00001178
Dan Gohman817a7c62012-03-22 18:24:56 +00001179 return NestingDetected;
1180}
John McCalld935e9c2011-06-15 23:37:01 +00001181
Dan Gohman817a7c62012-03-22 18:24:56 +00001182bool
1183ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
1184 DenseMap<Value *, RRInfo> &Releases,
1185 BBState &MyStates) {
1186 bool NestingDetected = false;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001187 ARCInstKind Class = GetARCInstKind(Inst);
Craig Topperf40110f2014-04-25 05:29:35 +00001188 const Value *Arg = nullptr;
John McCalld935e9c2011-06-15 23:37:01 +00001189
Dan Gohman817a7c62012-03-22 18:24:56 +00001190 switch (Class) {
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001191 case ARCInstKind::RetainBlock:
Michael Gottesman158fdf62013-03-28 20:11:19 +00001192 // In OptimizeIndividualCalls, we have strength reduced all optimizable
1193 // objc_retainBlocks to objc_retains. Thus at this point any
Michael Gottesman60805962015-03-06 00:34:42 +00001194 // objc_retainBlocks that we see are not optimizable. We need to break since
1195 // a retain can be a potential use.
Michael Gottesman158fdf62013-03-28 20:11:19 +00001196 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001197 case ARCInstKind::Retain:
1198 case ARCInstKind::RetainRV: {
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001199 Arg = GetArgRCIdentityRoot(Inst);
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001200 TopDownPtrState &S = MyStates.getPtrTopDownState(Arg);
Michael Gottesman4eae3962015-03-06 00:34:39 +00001201 NestingDetected |= S.InitTopDown(Class, Inst);
Dan Gohmanf64ff8e2012-07-23 19:27:31 +00001202 // A retain can be a potential use; procede to the generic checking
1203 // code below.
1204 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001205 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001206 case ARCInstKind::Release: {
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001207 Arg = GetArgRCIdentityRoot(Inst);
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001208 TopDownPtrState &S = MyStates.getPtrTopDownState(Arg);
Michael Gottesman60805962015-03-06 00:34:42 +00001209 // Try to form a tentative pair in between this release instruction and the
1210 // top down pointers that we are tracking.
1211 if (S.MatchWithRelease(MDKindCache, Inst)) {
1212 // If we succeed, copy S's RRInfo into the Release -> {Retain Set
1213 // Map}. Then we clear S.
Michael Gottesmane3943d02013-06-21 19:44:30 +00001214 Releases[Inst] = S.GetRRInfo();
Dan Gohman817a7c62012-03-22 18:24:56 +00001215 S.ClearSequenceProgress();
Dan Gohman817a7c62012-03-22 18:24:56 +00001216 }
1217 break;
1218 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001219 case ARCInstKind::AutoreleasepoolPop:
Dan Gohman817a7c62012-03-22 18:24:56 +00001220 // Conservatively, clear MyStates for all known pointers.
1221 MyStates.clearTopDownPointers();
Michael Gottesman60805962015-03-06 00:34:42 +00001222 return false;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001223 case ARCInstKind::AutoreleasepoolPush:
1224 case ARCInstKind::None:
Michael Gottesman60805962015-03-06 00:34:42 +00001225 // These can not be uses of
1226 return false;
Dan Gohman817a7c62012-03-22 18:24:56 +00001227 default:
1228 break;
1229 }
1230
1231 // Consider any other possible effects of this instruction on each
1232 // pointer being tracked.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001233 for (auto MI = MyStates.top_down_ptr_begin(),
1234 ME = MyStates.top_down_ptr_end();
1235 MI != ME; ++MI) {
Dan Gohman817a7c62012-03-22 18:24:56 +00001236 const Value *Ptr = MI->first;
1237 if (Ptr == Arg)
1238 continue; // Handled above.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001239 TopDownPtrState &S = MI->second;
Michael Gottesman16e6a202015-03-06 02:07:12 +00001240 if (S.HandlePotentialAlterRefCount(Inst, Ptr, PA, Class))
1241 continue;
Dan Gohman817a7c62012-03-22 18:24:56 +00001242
Michael Gottesman16e6a202015-03-06 02:07:12 +00001243 S.HandlePotentialUse(Inst, Ptr, PA, Class);
John McCalld935e9c2011-06-15 23:37:01 +00001244 }
1245
1246 return NestingDetected;
1247}
1248
1249bool
1250ObjCARCOpt::VisitTopDown(BasicBlock *BB,
1251 DenseMap<const BasicBlock *, BBState> &BBStates,
1252 DenseMap<Value *, RRInfo> &Releases) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001253 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitTopDown ==\n");
John McCalld935e9c2011-06-15 23:37:01 +00001254 bool NestingDetected = false;
1255 BBState &MyStates = BBStates[BB];
1256
1257 // Merge the states from each predecessor to compute the initial state
1258 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00001259 BBState::edge_iterator PI(MyStates.pred_begin()),
1260 PE(MyStates.pred_end());
1261 if (PI != PE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001262 const BasicBlock *Pred = *PI;
1263 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
1264 assert(I != BBStates.end());
1265 MyStates.InitFromPred(I->second);
1266 ++PI;
1267 for (; PI != PE; ++PI) {
1268 Pred = *PI;
1269 I = BBStates.find(Pred);
1270 assert(I != BBStates.end());
1271 MyStates.MergePred(I->second);
1272 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001273 }
John McCalld935e9c2011-06-15 23:37:01 +00001274
1275 // Visit all the instructions, top-down.
1276 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1277 Instruction *Inst = I;
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001278
Michael Gottesman89279f82013-04-05 18:10:41 +00001279 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001280
Dan Gohman817a7c62012-03-22 18:24:56 +00001281 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00001282 }
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00001283
John McCalld935e9c2011-06-15 23:37:01 +00001284 CheckForCFGHazards(BB, BBStates, MyStates);
1285 return NestingDetected;
1286}
1287
Dan Gohmana53a12c2011-12-12 19:42:25 +00001288static void
1289ComputePostOrders(Function &F,
1290 SmallVectorImpl<BasicBlock *> &PostOrder,
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001291 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
1292 unsigned NoObjCARCExceptionsMDKind,
1293 DenseMap<const BasicBlock *, BBState> &BBStates) {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001294 /// The visited set, for doing DFS walks.
Dan Gohmana53a12c2011-12-12 19:42:25 +00001295 SmallPtrSet<BasicBlock *, 16> Visited;
1296
1297 // Do DFS, computing the PostOrder.
1298 SmallPtrSet<BasicBlock *, 16> OnStack;
1299 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001300
1301 // Functions always have exactly one entry block, and we don't have
1302 // any other block that we treat like an entry block.
Dan Gohmana53a12c2011-12-12 19:42:25 +00001303 BasicBlock *EntryBB = &F.getEntryBlock();
Dan Gohman41375a32012-05-08 23:39:44 +00001304 BBState &MyStates = BBStates[EntryBB];
1305 MyStates.SetAsEntry();
1306 TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
1307 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
Dan Gohmana53a12c2011-12-12 19:42:25 +00001308 Visited.insert(EntryBB);
1309 OnStack.insert(EntryBB);
1310 do {
1311 dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001312 BasicBlock *CurrBB = SuccStack.back().first;
1313 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
1314 succ_iterator SE(TI, false);
Dan Gohman41375a32012-05-08 23:39:44 +00001315
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001316 while (SuccStack.back().second != SE) {
1317 BasicBlock *SuccBB = *SuccStack.back().second++;
David Blaikie70573dc2014-11-19 07:49:26 +00001318 if (Visited.insert(SuccBB).second) {
Dan Gohman41375a32012-05-08 23:39:44 +00001319 TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
1320 SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001321 BBStates[CurrBB].addSucc(SuccBB);
Dan Gohman41375a32012-05-08 23:39:44 +00001322 BBState &SuccStates = BBStates[SuccBB];
1323 SuccStates.addPred(CurrBB);
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001324 OnStack.insert(SuccBB);
Dan Gohmana53a12c2011-12-12 19:42:25 +00001325 goto dfs_next_succ;
1326 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001327
1328 if (!OnStack.count(SuccBB)) {
1329 BBStates[CurrBB].addSucc(SuccBB);
1330 BBStates[SuccBB].addPred(CurrBB);
1331 }
Dan Gohmana53a12c2011-12-12 19:42:25 +00001332 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001333 OnStack.erase(CurrBB);
1334 PostOrder.push_back(CurrBB);
1335 SuccStack.pop_back();
Dan Gohmana53a12c2011-12-12 19:42:25 +00001336 } while (!SuccStack.empty());
1337
1338 Visited.clear();
1339
Dan Gohmana53a12c2011-12-12 19:42:25 +00001340 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001341 // Functions may have many exits, and there also blocks which we treat
1342 // as exits due to ignored edges.
1343 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
1344 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
1345 BasicBlock *ExitBB = I;
1346 BBState &MyStates = BBStates[ExitBB];
1347 if (!MyStates.isExit())
1348 continue;
1349
Dan Gohmandae33492012-04-27 18:56:31 +00001350 MyStates.SetAsExit();
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001351
1352 PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00001353 Visited.insert(ExitBB);
1354 while (!PredStack.empty()) {
1355 reverse_dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001356 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
1357 while (PredStack.back().second != PE) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00001358 BasicBlock *BB = *PredStack.back().second++;
David Blaikie70573dc2014-11-19 07:49:26 +00001359 if (Visited.insert(BB).second) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001360 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00001361 goto reverse_dfs_next_succ;
1362 }
1363 }
1364 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
1365 }
1366 }
1367}
1368
Michael Gottesman97e3df02013-01-14 00:35:14 +00001369// Visit the function both top-down and bottom-up.
Michael Gottesman0be69202015-03-05 23:28:58 +00001370bool ObjCARCOpt::Visit(Function &F,
1371 DenseMap<const BasicBlock *, BBState> &BBStates,
1372 BlotMapVector<Value *, RRInfo> &Retains,
1373 DenseMap<Value *, RRInfo> &Releases) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00001374
1375 // Use reverse-postorder traversals, because we magically know that loops
1376 // will be well behaved, i.e. they won't repeatedly call retain on a single
1377 // pointer without doing a release. We can't use the ReversePostOrderTraversal
1378 // class here because we want the reverse-CFG postorder to consider each
1379 // function exit point, and we want to ignore selected cycle edges.
1380 SmallVector<BasicBlock *, 16> PostOrder;
1381 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001382 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
Michael Gottesman65cb7372015-03-16 07:02:27 +00001383 MDKindCache.get(ARCMDKindID::NoObjCARCExceptions),
1384 BBStates);
Dan Gohmana53a12c2011-12-12 19:42:25 +00001385
1386 // Use reverse-postorder on the reverse CFG for bottom-up.
John McCalld935e9c2011-06-15 23:37:01 +00001387 bool BottomUpNestingDetected = false;
Dan Gohmanc57b58c2011-08-18 21:27:42 +00001388 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
Dan Gohmana53a12c2011-12-12 19:42:25 +00001389 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
1390 I != E; ++I)
1391 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
John McCalld935e9c2011-06-15 23:37:01 +00001392
Dan Gohmana53a12c2011-12-12 19:42:25 +00001393 // Use reverse-postorder for top-down.
John McCalld935e9c2011-06-15 23:37:01 +00001394 bool TopDownNestingDetected = false;
Dan Gohmana53a12c2011-12-12 19:42:25 +00001395 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
1396 PostOrder.rbegin(), E = PostOrder.rend();
1397 I != E; ++I)
1398 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
John McCalld935e9c2011-06-15 23:37:01 +00001399
1400 return TopDownNestingDetected && BottomUpNestingDetected;
1401}
1402
Michael Gottesman97e3df02013-01-14 00:35:14 +00001403/// Move the calls in RetainsToMove and ReleasesToMove.
Michael Gottesman0be69202015-03-05 23:28:58 +00001404void ObjCARCOpt::MoveCalls(Value *Arg, RRInfo &RetainsToMove,
John McCalld935e9c2011-06-15 23:37:01 +00001405 RRInfo &ReleasesToMove,
Michael Gottesman0be69202015-03-05 23:28:58 +00001406 BlotMapVector<Value *, RRInfo> &Retains,
John McCalld935e9c2011-06-15 23:37:01 +00001407 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman6320f522011-07-22 22:29:21 +00001408 SmallVectorImpl<Instruction *> &DeadInsts,
Michael Gottesman79249972013-04-05 23:46:45 +00001409 Module *M) {
Chris Lattner229907c2011-07-18 04:54:35 +00001410 Type *ArgTy = Arg->getType();
Dan Gohman6320f522011-07-22 22:29:21 +00001411 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
Michael Gottesman79249972013-04-05 23:46:45 +00001412
Michael Gottesman89279f82013-04-05 18:10:41 +00001413 DEBUG(dbgs() << "== ObjCARCOpt::MoveCalls ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00001414
John McCalld935e9c2011-06-15 23:37:01 +00001415 // Insert the new retain and release calls.
Craig Topper46276792014-08-24 23:23:06 +00001416 for (Instruction *InsertPt : ReleasesToMove.ReverseInsertPts) {
John McCalld935e9c2011-06-15 23:37:01 +00001417 Value *MyArg = ArgTy == ParamTy ? Arg :
1418 new BitCastInst(Arg, ParamTy, "", InsertPt);
Michael Gottesmanca3a4722015-03-16 07:02:24 +00001419 Constant *Decl = EP.get(ARCRuntimeEntryPointKind::Retain);
Michael Gottesman14acfac2013-07-06 01:39:23 +00001420 CallInst *Call = CallInst::Create(Decl, MyArg, "", InsertPt);
John McCalld935e9c2011-06-15 23:37:01 +00001421 Call->setDoesNotThrow();
Michael Gottesmanba648592013-03-28 23:08:44 +00001422 Call->setTailCall();
Michael Gottesman60f6b282013-03-29 05:13:07 +00001423
Michael Gottesmandf110ac2013-04-21 00:30:50 +00001424 DEBUG(dbgs() << "Inserting new Retain: " << *Call << "\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00001425 "At insertion point: " << *InsertPt << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001426 }
Craig Topper46276792014-08-24 23:23:06 +00001427 for (Instruction *InsertPt : RetainsToMove.ReverseInsertPts) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00001428 Value *MyArg = ArgTy == ParamTy ? Arg :
1429 new BitCastInst(Arg, ParamTy, "", InsertPt);
Michael Gottesmanca3a4722015-03-16 07:02:24 +00001430 Constant *Decl = EP.get(ARCRuntimeEntryPointKind::Release);
Michael Gottesman14acfac2013-07-06 01:39:23 +00001431 CallInst *Call = CallInst::Create(Decl, MyArg, "", InsertPt);
Dan Gohman5c70fad2012-03-23 17:47:54 +00001432 // Attach a clang.imprecise_release metadata tag, if appropriate.
1433 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
Michael Gottesman65cb7372015-03-16 07:02:27 +00001434 Call->setMetadata(MDKindCache.get(ARCMDKindID::ImpreciseRelease), M);
Dan Gohman5c70fad2012-03-23 17:47:54 +00001435 Call->setDoesNotThrow();
1436 if (ReleasesToMove.IsTailCallRelease)
1437 Call->setTailCall();
Michael Gottesmanc189a392013-01-09 19:23:24 +00001438
Michael Gottesman89279f82013-04-05 18:10:41 +00001439 DEBUG(dbgs() << "Inserting new Release: " << *Call << "\n"
1440 "At insertion point: " << *InsertPt << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001441 }
1442
1443 // Delete the original retain and release calls.
Craig Topper46276792014-08-24 23:23:06 +00001444 for (Instruction *OrigRetain : RetainsToMove.Calls) {
John McCalld935e9c2011-06-15 23:37:01 +00001445 Retains.blot(OrigRetain);
1446 DeadInsts.push_back(OrigRetain);
Michael Gottesman89279f82013-04-05 18:10:41 +00001447 DEBUG(dbgs() << "Deleting retain: " << *OrigRetain << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001448 }
Craig Topper46276792014-08-24 23:23:06 +00001449 for (Instruction *OrigRelease : ReleasesToMove.Calls) {
John McCalld935e9c2011-06-15 23:37:01 +00001450 Releases.erase(OrigRelease);
1451 DeadInsts.push_back(OrigRelease);
Michael Gottesman89279f82013-04-05 18:10:41 +00001452 DEBUG(dbgs() << "Deleting release: " << *OrigRelease << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001453 }
Michael Gottesman79249972013-04-05 23:46:45 +00001454
John McCalld935e9c2011-06-15 23:37:01 +00001455}
1456
Michael Gottesman67792172015-03-16 07:02:30 +00001457bool ObjCARCOpt::PairUpRetainsAndReleases(
Michael Gottesman0be69202015-03-05 23:28:58 +00001458 DenseMap<const BasicBlock *, BBState> &BBStates,
1459 BlotMapVector<Value *, RRInfo> &Retains,
1460 DenseMap<Value *, RRInfo> &Releases, Module *M,
1461 SmallVectorImpl<Instruction *> &NewRetains,
1462 SmallVectorImpl<Instruction *> &NewReleases,
1463 SmallVectorImpl<Instruction *> &DeadInsts, RRInfo &RetainsToMove,
1464 RRInfo &ReleasesToMove, Value *Arg, bool KnownSafe,
1465 bool &AnyPairsCompletelyEliminated) {
Michael Gottesman9de6f962013-01-22 21:49:00 +00001466 // If a pair happens in a region where it is known that the reference count
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001467 // is already incremented, we can similarly ignore possible decrements unless
1468 // we are dealing with a retainable object with multiple provenance sources.
Michael Gottesman9de6f962013-01-22 21:49:00 +00001469 bool KnownSafeTD = true, KnownSafeBU = true;
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001470 bool MultipleOwners = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001471 bool CFGHazardAfflicted = false;
Michael Gottesman9de6f962013-01-22 21:49:00 +00001472
1473 // Connect the dots between the top-down-collected RetainsToMove and
1474 // bottom-up-collected ReleasesToMove to form sets of related calls.
1475 // This is an iterative process so that we connect multiple releases
1476 // to multiple retains if needed.
1477 unsigned OldDelta = 0;
1478 unsigned NewDelta = 0;
1479 unsigned OldCount = 0;
1480 unsigned NewCount = 0;
1481 bool FirstRelease = true;
Michael Gottesman9de6f962013-01-22 21:49:00 +00001482 for (;;) {
1483 for (SmallVectorImpl<Instruction *>::const_iterator
1484 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
1485 Instruction *NewRetain = *NI;
Michael Gottesman6ff10c92015-03-06 02:10:03 +00001486 auto It = Retains.find(NewRetain);
Michael Gottesman9de6f962013-01-22 21:49:00 +00001487 assert(It != Retains.end());
1488 const RRInfo &NewRetainRRI = It->second;
1489 KnownSafeTD &= NewRetainRRI.KnownSafe;
Michael Gottesman5a91bbf2013-05-24 20:44:02 +00001490 MultipleOwners =
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001491 MultipleOwners || MultiOwnersSet.count(GetArgRCIdentityRoot(NewRetain));
Craig Topper46276792014-08-24 23:23:06 +00001492 for (Instruction *NewRetainRelease : NewRetainRRI.Calls) {
Michael Gottesman6ff10c92015-03-06 02:10:03 +00001493 auto Jt = Releases.find(NewRetainRelease);
Michael Gottesman9de6f962013-01-22 21:49:00 +00001494 if (Jt == Releases.end())
1495 return false;
1496 const RRInfo &NewRetainReleaseRRI = Jt->second;
Michael Gottesman24b2f6f2013-11-05 16:02:40 +00001497
1498 // If the release does not have a reference to the retain as well,
1499 // something happened which is unaccounted for. Do not do anything.
1500 //
1501 // This can happen if we catch an additive overflow during path count
1502 // merging.
1503 if (!NewRetainReleaseRRI.Calls.count(NewRetain))
1504 return false;
1505
David Blaikie70573dc2014-11-19 07:49:26 +00001506 if (ReleasesToMove.Calls.insert(NewRetainRelease).second) {
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001507
1508 // If we overflow when we compute the path count, don't remove/move
1509 // anything.
1510 const BBState &NRRBBState = BBStates[NewRetainRelease->getParent()];
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00001511 unsigned PathCount = BBState::OverflowOccurredValue;
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001512 if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
1513 return false;
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00001514 assert(PathCount != BBState::OverflowOccurredValue &&
1515 "PathCount at this point can not be "
1516 "OverflowOccurredValue.");
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001517 OldDelta -= PathCount;
Michael Gottesman9de6f962013-01-22 21:49:00 +00001518
1519 // Merge the ReleaseMetadata and IsTailCallRelease values.
1520 if (FirstRelease) {
1521 ReleasesToMove.ReleaseMetadata =
1522 NewRetainReleaseRRI.ReleaseMetadata;
1523 ReleasesToMove.IsTailCallRelease =
1524 NewRetainReleaseRRI.IsTailCallRelease;
1525 FirstRelease = false;
1526 } else {
1527 if (ReleasesToMove.ReleaseMetadata !=
1528 NewRetainReleaseRRI.ReleaseMetadata)
Craig Topperf40110f2014-04-25 05:29:35 +00001529 ReleasesToMove.ReleaseMetadata = nullptr;
Michael Gottesman9de6f962013-01-22 21:49:00 +00001530 if (ReleasesToMove.IsTailCallRelease !=
1531 NewRetainReleaseRRI.IsTailCallRelease)
1532 ReleasesToMove.IsTailCallRelease = false;
1533 }
1534
1535 // Collect the optimal insertion points.
1536 if (!KnownSafe)
Craig Topper46276792014-08-24 23:23:06 +00001537 for (Instruction *RIP : NewRetainReleaseRRI.ReverseInsertPts) {
David Blaikie70573dc2014-11-19 07:49:26 +00001538 if (ReleasesToMove.ReverseInsertPts.insert(RIP).second) {
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001539 // If we overflow when we compute the path count, don't
1540 // remove/move anything.
1541 const BBState &RIPBBState = BBStates[RIP->getParent()];
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00001542 PathCount = BBState::OverflowOccurredValue;
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001543 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
1544 return false;
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00001545 assert(PathCount != BBState::OverflowOccurredValue &&
1546 "PathCount at this point can not be "
1547 "OverflowOccurredValue.");
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001548 NewDelta -= PathCount;
1549 }
Michael Gottesman9de6f962013-01-22 21:49:00 +00001550 }
1551 NewReleases.push_back(NewRetainRelease);
1552 }
1553 }
1554 }
1555 NewRetains.clear();
1556 if (NewReleases.empty()) break;
1557
1558 // Back the other way.
1559 for (SmallVectorImpl<Instruction *>::const_iterator
1560 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
1561 Instruction *NewRelease = *NI;
Michael Gottesman6ff10c92015-03-06 02:10:03 +00001562 auto It = Releases.find(NewRelease);
Michael Gottesman9de6f962013-01-22 21:49:00 +00001563 assert(It != Releases.end());
1564 const RRInfo &NewReleaseRRI = It->second;
1565 KnownSafeBU &= NewReleaseRRI.KnownSafe;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001566 CFGHazardAfflicted |= NewReleaseRRI.CFGHazardAfflicted;
Craig Topper46276792014-08-24 23:23:06 +00001567 for (Instruction *NewReleaseRetain : NewReleaseRRI.Calls) {
Michael Gottesman6ff10c92015-03-06 02:10:03 +00001568 auto Jt = Retains.find(NewReleaseRetain);
Michael Gottesman9de6f962013-01-22 21:49:00 +00001569 if (Jt == Retains.end())
1570 return false;
1571 const RRInfo &NewReleaseRetainRRI = Jt->second;
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001572
Michael Gottesman24b2f6f2013-11-05 16:02:40 +00001573 // If the retain does not have a reference to the release as well,
1574 // something happened which is unaccounted for. Do not do anything.
1575 //
1576 // This can happen if we catch an additive overflow during path count
1577 // merging.
1578 if (!NewReleaseRetainRRI.Calls.count(NewRelease))
1579 return false;
1580
David Blaikie70573dc2014-11-19 07:49:26 +00001581 if (RetainsToMove.Calls.insert(NewReleaseRetain).second) {
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001582 // If we overflow when we compute the path count, don't remove/move
1583 // anything.
1584 const BBState &NRRBBState = BBStates[NewReleaseRetain->getParent()];
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00001585 unsigned PathCount = BBState::OverflowOccurredValue;
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001586 if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
1587 return false;
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00001588 assert(PathCount != BBState::OverflowOccurredValue &&
1589 "PathCount at this point can not be "
1590 "OverflowOccurredValue.");
Michael Gottesman9de6f962013-01-22 21:49:00 +00001591 OldDelta += PathCount;
1592 OldCount += PathCount;
1593
Michael Gottesman9de6f962013-01-22 21:49:00 +00001594 // Collect the optimal insertion points.
1595 if (!KnownSafe)
Craig Topper46276792014-08-24 23:23:06 +00001596 for (Instruction *RIP : NewReleaseRetainRRI.ReverseInsertPts) {
David Blaikie70573dc2014-11-19 07:49:26 +00001597 if (RetainsToMove.ReverseInsertPts.insert(RIP).second) {
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001598 // If we overflow when we compute the path count, don't
1599 // remove/move anything.
1600 const BBState &RIPBBState = BBStates[RIP->getParent()];
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00001601
1602 PathCount = BBState::OverflowOccurredValue;
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001603 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
1604 return false;
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00001605 assert(PathCount != BBState::OverflowOccurredValue &&
1606 "PathCount at this point can not be "
1607 "OverflowOccurredValue.");
Michael Gottesman9de6f962013-01-22 21:49:00 +00001608 NewDelta += PathCount;
1609 NewCount += PathCount;
1610 }
1611 }
1612 NewRetains.push_back(NewReleaseRetain);
1613 }
1614 }
1615 }
1616 NewReleases.clear();
1617 if (NewRetains.empty()) break;
1618 }
1619
Michael Gottesmandd60f9b2015-03-16 07:02:36 +00001620 // We can only remove pointers if we are known safe in both directions.
1621 bool UnconditionallySafe = KnownSafeTD && KnownSafeBU;
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001622 if (UnconditionallySafe) {
Michael Gottesman9de6f962013-01-22 21:49:00 +00001623 RetainsToMove.ReverseInsertPts.clear();
1624 ReleasesToMove.ReverseInsertPts.clear();
1625 NewCount = 0;
1626 } else {
1627 // Determine whether the new insertion points we computed preserve the
1628 // balance of retain and release calls through the program.
1629 // TODO: If the fully aggressive solution isn't valid, try to find a
1630 // less aggressive solution which is.
1631 if (NewDelta != 0)
1632 return false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001633
1634 // At this point, we are not going to remove any RR pairs, but we still are
1635 // able to move RR pairs. If one of our pointers is afflicted with
1636 // CFGHazards, we cannot perform such code motion so exit early.
1637 const bool WillPerformCodeMotion = RetainsToMove.ReverseInsertPts.size() ||
1638 ReleasesToMove.ReverseInsertPts.size();
1639 if (CFGHazardAfflicted && WillPerformCodeMotion)
1640 return false;
Michael Gottesman9de6f962013-01-22 21:49:00 +00001641 }
1642
1643 // Determine whether the original call points are balanced in the retain and
1644 // release calls through the program. If not, conservatively don't touch
1645 // them.
1646 // TODO: It's theoretically possible to do code motion in this case, as
1647 // long as the existing imbalances are maintained.
1648 if (OldDelta != 0)
1649 return false;
Michael Gottesman8005ad32013-04-29 06:16:55 +00001650
Michael Gottesman9de6f962013-01-22 21:49:00 +00001651 Changed = true;
1652 assert(OldCount != 0 && "Unreachable code?");
1653 NumRRs += OldCount - NewCount;
Michael Gottesman9de6f962013-01-22 21:49:00 +00001654 // Set to true if we completely removed any RR pairs.
Michael Gottesman8b5515f2013-01-22 21:53:43 +00001655 AnyPairsCompletelyEliminated = NewCount == 0;
Michael Gottesman9de6f962013-01-22 21:49:00 +00001656
1657 // We can move calls!
1658 return true;
1659}
1660
Michael Gottesman97e3df02013-01-14 00:35:14 +00001661/// Identify pairings between the retains and releases, and delete and/or move
1662/// them.
Michael Gottesman0be69202015-03-05 23:28:58 +00001663bool ObjCARCOpt::PerformCodePlacement(
1664 DenseMap<const BasicBlock *, BBState> &BBStates,
1665 BlotMapVector<Value *, RRInfo> &Retains,
1666 DenseMap<Value *, RRInfo> &Releases, Module *M) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001667 DEBUG(dbgs() << "\n== ObjCARCOpt::PerformCodePlacement ==\n");
1668
John McCalld935e9c2011-06-15 23:37:01 +00001669 bool AnyPairsCompletelyEliminated = false;
1670 RRInfo RetainsToMove;
1671 RRInfo ReleasesToMove;
1672 SmallVector<Instruction *, 4> NewRetains;
1673 SmallVector<Instruction *, 4> NewReleases;
1674 SmallVector<Instruction *, 8> DeadInsts;
1675
Dan Gohman670f9372012-04-13 18:57:48 +00001676 // Visit each retain.
Michael Gottesman0be69202015-03-05 23:28:58 +00001677 for (BlotMapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
1678 E = Retains.end();
1679 I != E; ++I) {
Dan Gohman2053a5d2011-09-29 22:25:23 +00001680 Value *V = I->first;
John McCalld935e9c2011-06-15 23:37:01 +00001681 if (!V) continue; // blotted
1682
1683 Instruction *Retain = cast<Instruction>(V);
Michael Gottesmanc189a392013-01-09 19:23:24 +00001684
Michael Gottesman89279f82013-04-05 18:10:41 +00001685 DEBUG(dbgs() << "Visiting: " << *Retain << "\n");
Michael Gottesmanc189a392013-01-09 19:23:24 +00001686
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001687 Value *Arg = GetArgRCIdentityRoot(Retain);
John McCalld935e9c2011-06-15 23:37:01 +00001688
Dan Gohman728db492012-01-13 00:39:07 +00001689 // If the object being released is in static or stack storage, we know it's
John McCalld935e9c2011-06-15 23:37:01 +00001690 // not being managed by ObjC reference counting, so we can delete pairs
1691 // regardless of what possible decrements or uses lie between them.
Dan Gohman728db492012-01-13 00:39:07 +00001692 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
Dan Gohman41375a32012-05-08 23:39:44 +00001693
Dan Gohman56e1cef2011-08-22 17:29:11 +00001694 // A constant pointer can't be pointing to an object on the heap. It may
1695 // be reference-counted, but it won't be deleted.
1696 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
1697 if (const GlobalVariable *GV =
1698 dyn_cast<GlobalVariable>(
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001699 GetRCIdentityRoot(LI->getPointerOperand())))
Dan Gohman56e1cef2011-08-22 17:29:11 +00001700 if (GV->isConstant())
1701 KnownSafe = true;
1702
John McCalld935e9c2011-06-15 23:37:01 +00001703 // Connect the dots between the top-down-collected RetainsToMove and
1704 // bottom-up-collected ReleasesToMove to form sets of related calls.
John McCalld935e9c2011-06-15 23:37:01 +00001705 NewRetains.push_back(Retain);
Michael Gottesman67792172015-03-16 07:02:30 +00001706 bool PerformMoveCalls = PairUpRetainsAndReleases(
1707 BBStates, Retains, Releases, M, NewRetains, NewReleases, DeadInsts,
1708 RetainsToMove, ReleasesToMove, Arg, KnownSafe,
1709 AnyPairsCompletelyEliminated);
John McCalld935e9c2011-06-15 23:37:01 +00001710
Michael Gottesman9de6f962013-01-22 21:49:00 +00001711 if (PerformMoveCalls) {
1712 // Ok, everything checks out and we're all set. Let's move/delete some
1713 // code!
1714 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
1715 Retains, Releases, DeadInsts, M);
John McCalld935e9c2011-06-15 23:37:01 +00001716 }
1717
Michael Gottesman9de6f962013-01-22 21:49:00 +00001718 // Clean up state for next retain.
John McCalld935e9c2011-06-15 23:37:01 +00001719 NewReleases.clear();
1720 NewRetains.clear();
1721 RetainsToMove.clear();
1722 ReleasesToMove.clear();
1723 }
1724
1725 // Now that we're done moving everything, we can delete the newly dead
1726 // instructions, as we no longer need them as insert points.
1727 while (!DeadInsts.empty())
1728 EraseInstruction(DeadInsts.pop_back_val());
1729
1730 return AnyPairsCompletelyEliminated;
1731}
1732
Michael Gottesman97e3df02013-01-14 00:35:14 +00001733/// Weak pointer optimizations.
John McCalld935e9c2011-06-15 23:37:01 +00001734void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001735 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeWeakCalls ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00001736
John McCalld935e9c2011-06-15 23:37:01 +00001737 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
1738 // itself because it uses AliasAnalysis and we need to do provenance
1739 // queries instead.
1740 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
1741 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +00001742
Michael Gottesman89279f82013-04-05 18:10:41 +00001743 DEBUG(dbgs() << "Visiting: " << *Inst << "\n");
Michael Gottesman3f146e22013-01-01 16:05:48 +00001744
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001745 ARCInstKind Class = GetBasicARCInstKind(Inst);
1746 if (Class != ARCInstKind::LoadWeak &&
1747 Class != ARCInstKind::LoadWeakRetained)
John McCalld935e9c2011-06-15 23:37:01 +00001748 continue;
1749
1750 // Delete objc_loadWeak calls with no users.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001751 if (Class == ARCInstKind::LoadWeak && Inst->use_empty()) {
John McCalld935e9c2011-06-15 23:37:01 +00001752 Inst->eraseFromParent();
1753 continue;
1754 }
1755
1756 // TODO: For now, just look for an earlier available version of this value
1757 // within the same block. Theoretically, we could do memdep-style non-local
1758 // analysis too, but that would want caching. A better approach would be to
1759 // use the technique that EarlyCSE uses.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001760 inst_iterator Current = std::prev(I);
John McCalld935e9c2011-06-15 23:37:01 +00001761 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
1762 for (BasicBlock::iterator B = CurrentBB->begin(),
1763 J = Current.getInstructionIterator();
1764 J != B; --J) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001765 Instruction *EarlierInst = &*std::prev(J);
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001766 ARCInstKind EarlierClass = GetARCInstKind(EarlierInst);
John McCalld935e9c2011-06-15 23:37:01 +00001767 switch (EarlierClass) {
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001768 case ARCInstKind::LoadWeak:
1769 case ARCInstKind::LoadWeakRetained: {
John McCalld935e9c2011-06-15 23:37:01 +00001770 // If this is loading from the same pointer, replace this load's value
1771 // with that one.
1772 CallInst *Call = cast<CallInst>(Inst);
1773 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
1774 Value *Arg = Call->getArgOperand(0);
1775 Value *EarlierArg = EarlierCall->getArgOperand(0);
1776 switch (PA.getAA()->alias(Arg, EarlierArg)) {
1777 case AliasAnalysis::MustAlias:
1778 Changed = true;
1779 // If the load has a builtin retain, insert a plain retain for it.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001780 if (Class == ARCInstKind::LoadWeakRetained) {
Michael Gottesmanca3a4722015-03-16 07:02:24 +00001781 Constant *Decl = EP.get(ARCRuntimeEntryPointKind::Retain);
Michael Gottesman14acfac2013-07-06 01:39:23 +00001782 CallInst *CI = CallInst::Create(Decl, EarlierCall, "", Call);
John McCalld935e9c2011-06-15 23:37:01 +00001783 CI->setTailCall();
1784 }
1785 // Zap the fully redundant load.
1786 Call->replaceAllUsesWith(EarlierCall);
1787 Call->eraseFromParent();
1788 goto clobbered;
1789 case AliasAnalysis::MayAlias:
1790 case AliasAnalysis::PartialAlias:
1791 goto clobbered;
1792 case AliasAnalysis::NoAlias:
1793 break;
1794 }
1795 break;
1796 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001797 case ARCInstKind::StoreWeak:
1798 case ARCInstKind::InitWeak: {
John McCalld935e9c2011-06-15 23:37:01 +00001799 // If this is storing to the same pointer and has the same size etc.
1800 // replace this load's value with the stored value.
1801 CallInst *Call = cast<CallInst>(Inst);
1802 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
1803 Value *Arg = Call->getArgOperand(0);
1804 Value *EarlierArg = EarlierCall->getArgOperand(0);
1805 switch (PA.getAA()->alias(Arg, EarlierArg)) {
1806 case AliasAnalysis::MustAlias:
1807 Changed = true;
1808 // If the load has a builtin retain, insert a plain retain for it.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001809 if (Class == ARCInstKind::LoadWeakRetained) {
Michael Gottesmanca3a4722015-03-16 07:02:24 +00001810 Constant *Decl = EP.get(ARCRuntimeEntryPointKind::Retain);
Michael Gottesman14acfac2013-07-06 01:39:23 +00001811 CallInst *CI = CallInst::Create(Decl, EarlierCall, "", Call);
John McCalld935e9c2011-06-15 23:37:01 +00001812 CI->setTailCall();
1813 }
1814 // Zap the fully redundant load.
1815 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
1816 Call->eraseFromParent();
1817 goto clobbered;
1818 case AliasAnalysis::MayAlias:
1819 case AliasAnalysis::PartialAlias:
1820 goto clobbered;
1821 case AliasAnalysis::NoAlias:
1822 break;
1823 }
1824 break;
1825 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001826 case ARCInstKind::MoveWeak:
1827 case ARCInstKind::CopyWeak:
John McCalld935e9c2011-06-15 23:37:01 +00001828 // TOOD: Grab the copied value.
1829 goto clobbered;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001830 case ARCInstKind::AutoreleasepoolPush:
1831 case ARCInstKind::None:
1832 case ARCInstKind::IntrinsicUser:
1833 case ARCInstKind::User:
John McCalld935e9c2011-06-15 23:37:01 +00001834 // Weak pointers are only modified through the weak entry points
1835 // (and arbitrary calls, which could call the weak entry points).
1836 break;
1837 default:
1838 // Anything else could modify the weak pointer.
1839 goto clobbered;
1840 }
1841 }
1842 clobbered:;
1843 }
1844
1845 // Then, for each destroyWeak with an alloca operand, check to see if
1846 // the alloca and all its users can be zapped.
1847 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
1848 Instruction *Inst = &*I++;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001849 ARCInstKind Class = GetBasicARCInstKind(Inst);
1850 if (Class != ARCInstKind::DestroyWeak)
John McCalld935e9c2011-06-15 23:37:01 +00001851 continue;
1852
1853 CallInst *Call = cast<CallInst>(Inst);
1854 Value *Arg = Call->getArgOperand(0);
1855 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001856 for (User *U : Alloca->users()) {
1857 const Instruction *UserInst = cast<Instruction>(U);
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001858 switch (GetBasicARCInstKind(UserInst)) {
1859 case ARCInstKind::InitWeak:
1860 case ARCInstKind::StoreWeak:
1861 case ARCInstKind::DestroyWeak:
John McCalld935e9c2011-06-15 23:37:01 +00001862 continue;
1863 default:
1864 goto done;
1865 }
1866 }
1867 Changed = true;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001868 for (auto UI = Alloca->user_begin(), UE = Alloca->user_end(); UI != UE;) {
John McCalld935e9c2011-06-15 23:37:01 +00001869 CallInst *UserInst = cast<CallInst>(*UI++);
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001870 switch (GetBasicARCInstKind(UserInst)) {
1871 case ARCInstKind::InitWeak:
1872 case ARCInstKind::StoreWeak:
Dan Gohman14862c32012-05-18 22:17:29 +00001873 // These functions return their second argument.
1874 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
1875 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001876 case ARCInstKind::DestroyWeak:
Dan Gohman14862c32012-05-18 22:17:29 +00001877 // No return value.
1878 break;
1879 default:
Dan Gohman9c97eea02012-05-21 17:41:28 +00001880 llvm_unreachable("alloca really is used!");
Dan Gohman14862c32012-05-18 22:17:29 +00001881 }
John McCalld935e9c2011-06-15 23:37:01 +00001882 UserInst->eraseFromParent();
1883 }
1884 Alloca->eraseFromParent();
1885 done:;
1886 }
1887 }
1888}
1889
Michael Gottesman97e3df02013-01-14 00:35:14 +00001890/// Identify program paths which execute sequences of retains and releases which
1891/// can be eliminated.
John McCalld935e9c2011-06-15 23:37:01 +00001892bool ObjCARCOpt::OptimizeSequences(Function &F) {
Michael Gottesman740db972013-05-23 02:35:21 +00001893 // Releases, Retains - These are used to store the results of the main flow
1894 // analysis. These use Value* as the key instead of Instruction* so that the
1895 // map stays valid when we get around to rewriting code and calls get
1896 // replaced by arguments.
John McCalld935e9c2011-06-15 23:37:01 +00001897 DenseMap<Value *, RRInfo> Releases;
Michael Gottesman0be69202015-03-05 23:28:58 +00001898 BlotMapVector<Value *, RRInfo> Retains;
John McCalld935e9c2011-06-15 23:37:01 +00001899
Michael Gottesman740db972013-05-23 02:35:21 +00001900 // This is used during the traversal of the function to track the
1901 // states for each identified object at each block.
John McCalld935e9c2011-06-15 23:37:01 +00001902 DenseMap<const BasicBlock *, BBState> BBStates;
1903
1904 // Analyze the CFG of the function, and all instructions.
1905 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
1906
1907 // Transform.
Michael Gottesman5a91bbf2013-05-24 20:44:02 +00001908 bool AnyPairsCompletelyEliminated = PerformCodePlacement(BBStates, Retains,
1909 Releases,
1910 F.getParent());
1911
1912 // Cleanup.
1913 MultiOwnersSet.clear();
1914
1915 return AnyPairsCompletelyEliminated && NestingDetected;
John McCalld935e9c2011-06-15 23:37:01 +00001916}
1917
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00001918/// Check if there is a dependent call earlier that does not have anything in
1919/// between the Retain and the call that can affect the reference count of their
1920/// shared pointer argument. Note that Retain need not be in BB.
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00001921static bool
1922HasSafePathToPredecessorCall(const Value *Arg, Instruction *Retain,
Craig Topper71b7b682014-08-21 05:55:13 +00001923 SmallPtrSetImpl<Instruction *> &DepInsts,
1924 SmallPtrSetImpl<const BasicBlock *> &Visited,
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00001925 ProvenanceAnalysis &PA) {
1926 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
1927 DepInsts, Visited, PA);
1928 if (DepInsts.size() != 1)
1929 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00001930
Michael Gottesmana9fc0162015-03-05 23:29:06 +00001931 auto *Call = dyn_cast_or_null<CallInst>(*DepInsts.begin());
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00001932
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00001933 // Check that the pointer is the return value of the call.
1934 if (!Call || Arg != Call)
1935 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00001936
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00001937 // Check that the call is a regular call.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001938 ARCInstKind Class = GetBasicARCInstKind(Call);
1939 if (Class != ARCInstKind::CallOrUser && Class != ARCInstKind::Call)
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00001940 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00001941
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00001942 return true;
1943}
1944
Michael Gottesman6908db12013-04-03 23:16:05 +00001945/// Find a dependent retain that precedes the given autorelease for which there
1946/// is nothing in between the two instructions that can affect the ref count of
1947/// Arg.
1948static CallInst *
1949FindPredecessorRetainWithSafePath(const Value *Arg, BasicBlock *BB,
1950 Instruction *Autorelease,
Craig Topper71b7b682014-08-21 05:55:13 +00001951 SmallPtrSetImpl<Instruction *> &DepInsts,
1952 SmallPtrSetImpl<const BasicBlock *> &Visited,
Michael Gottesman6908db12013-04-03 23:16:05 +00001953 ProvenanceAnalysis &PA) {
1954 FindDependencies(CanChangeRetainCount, Arg,
1955 BB, Autorelease, DepInsts, Visited, PA);
1956 if (DepInsts.size() != 1)
Craig Topperf40110f2014-04-25 05:29:35 +00001957 return nullptr;
Michael Gottesman79249972013-04-05 23:46:45 +00001958
Michael Gottesmana9fc0162015-03-05 23:29:06 +00001959 auto *Retain = dyn_cast_or_null<CallInst>(*DepInsts.begin());
Michael Gottesman79249972013-04-05 23:46:45 +00001960
Michael Gottesman6908db12013-04-03 23:16:05 +00001961 // Check that we found a retain with the same argument.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001962 if (!Retain || !IsRetain(GetBasicARCInstKind(Retain)) ||
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001963 GetArgRCIdentityRoot(Retain) != Arg) {
Craig Topperf40110f2014-04-25 05:29:35 +00001964 return nullptr;
Michael Gottesman6908db12013-04-03 23:16:05 +00001965 }
Michael Gottesman79249972013-04-05 23:46:45 +00001966
Michael Gottesman6908db12013-04-03 23:16:05 +00001967 return Retain;
1968}
1969
Michael Gottesman21a4ed32013-04-03 23:39:14 +00001970/// Look for an ``autorelease'' instruction dependent on Arg such that there are
1971/// no instructions dependent on Arg that need a positive ref count in between
1972/// the autorelease and the ret.
1973static CallInst *
1974FindPredecessorAutoreleaseWithSafePath(const Value *Arg, BasicBlock *BB,
1975 ReturnInst *Ret,
Craig Topper71b7b682014-08-21 05:55:13 +00001976 SmallPtrSetImpl<Instruction *> &DepInsts,
1977 SmallPtrSetImpl<const BasicBlock *> &V,
Michael Gottesman21a4ed32013-04-03 23:39:14 +00001978 ProvenanceAnalysis &PA) {
1979 FindDependencies(NeedsPositiveRetainCount, Arg,
1980 BB, Ret, DepInsts, V, PA);
1981 if (DepInsts.size() != 1)
Craig Topperf40110f2014-04-25 05:29:35 +00001982 return nullptr;
Michael Gottesman79249972013-04-05 23:46:45 +00001983
Michael Gottesmana9fc0162015-03-05 23:29:06 +00001984 auto *Autorelease = dyn_cast_or_null<CallInst>(*DepInsts.begin());
Michael Gottesman21a4ed32013-04-03 23:39:14 +00001985 if (!Autorelease)
Craig Topperf40110f2014-04-25 05:29:35 +00001986 return nullptr;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001987 ARCInstKind AutoreleaseClass = GetBasicARCInstKind(Autorelease);
Michael Gottesman21a4ed32013-04-03 23:39:14 +00001988 if (!IsAutorelease(AutoreleaseClass))
Craig Topperf40110f2014-04-25 05:29:35 +00001989 return nullptr;
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001990 if (GetArgRCIdentityRoot(Autorelease) != Arg)
Craig Topperf40110f2014-04-25 05:29:35 +00001991 return nullptr;
Michael Gottesman79249972013-04-05 23:46:45 +00001992
Michael Gottesman21a4ed32013-04-03 23:39:14 +00001993 return Autorelease;
1994}
1995
Michael Gottesman97e3df02013-01-14 00:35:14 +00001996/// Look for this pattern:
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00001997/// \code
John McCalld935e9c2011-06-15 23:37:01 +00001998/// %call = call i8* @something(...)
1999/// %2 = call i8* @objc_retain(i8* %call)
2000/// %3 = call i8* @objc_autorelease(i8* %2)
2001/// ret i8* %3
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00002002/// \endcode
John McCalld935e9c2011-06-15 23:37:01 +00002003/// And delete the retain and autorelease.
John McCalld935e9c2011-06-15 23:37:01 +00002004void ObjCARCOpt::OptimizeReturns(Function &F) {
2005 if (!F.getReturnType()->isPointerTy())
2006 return;
Michael Gottesman79249972013-04-05 23:46:45 +00002007
Michael Gottesman89279f82013-04-05 18:10:41 +00002008 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeReturns ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00002009
John McCalld935e9c2011-06-15 23:37:01 +00002010 SmallPtrSet<Instruction *, 4> DependingInstructions;
2011 SmallPtrSet<const BasicBlock *, 4> Visited;
2012 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
2013 BasicBlock *BB = FI;
2014 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
Michael Gottesman3f146e22013-01-01 16:05:48 +00002015
Michael Gottesman89279f82013-04-05 18:10:41 +00002016 DEBUG(dbgs() << "Visiting: " << *Ret << "\n");
Michael Gottesman3f146e22013-01-01 16:05:48 +00002017
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002018 if (!Ret)
2019 continue;
Michael Gottesman79249972013-04-05 23:46:45 +00002020
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00002021 const Value *Arg = GetRCIdentityRoot(Ret->getOperand(0));
Michael Gottesman79249972013-04-05 23:46:45 +00002022
Michael Gottesmancdb7c152013-04-21 00:25:04 +00002023 // Look for an ``autorelease'' instruction that is a predecessor of Ret and
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002024 // dependent on Arg such that there are no instructions dependent on Arg
2025 // that need a positive ref count in between the autorelease and Ret.
2026 CallInst *Autorelease =
2027 FindPredecessorAutoreleaseWithSafePath(Arg, BB, Ret,
2028 DependingInstructions, Visited,
2029 PA);
John McCalld935e9c2011-06-15 23:37:01 +00002030 DependingInstructions.clear();
2031 Visited.clear();
Michael Gottesmanfb9ece92013-04-21 00:25:01 +00002032
2033 if (!Autorelease)
2034 continue;
2035
2036 CallInst *Retain =
2037 FindPredecessorRetainWithSafePath(Arg, BB, Autorelease,
2038 DependingInstructions, Visited, PA);
2039 DependingInstructions.clear();
2040 Visited.clear();
2041
2042 if (!Retain)
2043 continue;
2044
2045 // Check that there is nothing that can affect the reference count
2046 // between the retain and the call. Note that Retain need not be in BB.
2047 bool HasSafePathToCall = HasSafePathToPredecessorCall(Arg, Retain,
2048 DependingInstructions,
2049 Visited, PA);
2050 DependingInstructions.clear();
2051 Visited.clear();
2052
2053 if (!HasSafePathToCall)
2054 continue;
2055
2056 // If so, we can zap the retain and autorelease.
2057 Changed = true;
2058 ++NumRets;
2059 DEBUG(dbgs() << "Erasing: " << *Retain << "\nErasing: "
2060 << *Autorelease << "\n");
2061 EraseInstruction(Retain);
2062 EraseInstruction(Autorelease);
John McCalld935e9c2011-06-15 23:37:01 +00002063 }
2064}
2065
Michael Gottesman9c118152013-04-29 06:16:57 +00002066#ifndef NDEBUG
2067void
2068ObjCARCOpt::GatherStatistics(Function &F, bool AfterOptimization) {
2069 llvm::Statistic &NumRetains =
2070 AfterOptimization? NumRetainsAfterOpt : NumRetainsBeforeOpt;
2071 llvm::Statistic &NumReleases =
2072 AfterOptimization? NumReleasesAfterOpt : NumReleasesBeforeOpt;
2073
2074 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2075 Instruction *Inst = &*I++;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002076 switch (GetBasicARCInstKind(Inst)) {
Michael Gottesman9c118152013-04-29 06:16:57 +00002077 default:
2078 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002079 case ARCInstKind::Retain:
Michael Gottesman9c118152013-04-29 06:16:57 +00002080 ++NumRetains;
2081 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002082 case ARCInstKind::Release:
Michael Gottesman9c118152013-04-29 06:16:57 +00002083 ++NumReleases;
2084 break;
2085 }
2086 }
2087}
2088#endif
2089
John McCalld935e9c2011-06-15 23:37:01 +00002090bool ObjCARCOpt::doInitialization(Module &M) {
2091 if (!EnableARCOpts)
2092 return false;
2093
Dan Gohman670f9372012-04-13 18:57:48 +00002094 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanceaac7c2011-06-20 23:20:43 +00002095 Run = ModuleHasARC(M);
2096 if (!Run)
2097 return false;
2098
John McCalld935e9c2011-06-15 23:37:01 +00002099 // Intuitively, objc_retain and others are nocapture, however in practice
2100 // they are not, because they return their argument value. And objc_release
Dan Gohmandae33492012-04-27 18:56:31 +00002101 // calls finalizers which can have arbitrary side effects.
Michael Gottesman65cb7372015-03-16 07:02:27 +00002102 MDKindCache.init(&M);
John McCalld935e9c2011-06-15 23:37:01 +00002103
Michael Gottesman14acfac2013-07-06 01:39:23 +00002104 // Initialize our runtime entry point cache.
Michael Gottesman65cb7372015-03-16 07:02:27 +00002105 EP.init(&M);
John McCalld935e9c2011-06-15 23:37:01 +00002106
2107 return false;
2108}
2109
2110bool ObjCARCOpt::runOnFunction(Function &F) {
2111 if (!EnableARCOpts)
2112 return false;
2113
Dan Gohmanceaac7c2011-06-20 23:20:43 +00002114 // If nothing in the Module uses ARC, don't do anything.
2115 if (!Run)
2116 return false;
2117
John McCalld935e9c2011-06-15 23:37:01 +00002118 Changed = false;
2119
Michael Gottesman89279f82013-04-05 18:10:41 +00002120 DEBUG(dbgs() << "<<< ObjCARCOpt: Visiting Function: " << F.getName() << " >>>"
2121 "\n");
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00002122
John McCalld935e9c2011-06-15 23:37:01 +00002123 PA.setAA(&getAnalysis<AliasAnalysis>());
2124
Michael Gottesman9fc50b82013-05-13 18:29:07 +00002125#ifndef NDEBUG
2126 if (AreStatisticsEnabled()) {
2127 GatherStatistics(F, false);
2128 }
2129#endif
2130
John McCalld935e9c2011-06-15 23:37:01 +00002131 // This pass performs several distinct transformations. As a compile-time aid
2132 // when compiling code that isn't ObjC, skip these if the relevant ObjC
2133 // library functions aren't declared.
2134
Michael Gottesmancd5b0272013-04-24 22:18:15 +00002135 // Preliminary optimizations. This also computes UsedInThisFunction.
John McCalld935e9c2011-06-15 23:37:01 +00002136 OptimizeIndividualCalls(F);
2137
2138 // Optimizations for weak pointers.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002139 if (UsedInThisFunction & ((1 << unsigned(ARCInstKind::LoadWeak)) |
2140 (1 << unsigned(ARCInstKind::LoadWeakRetained)) |
2141 (1 << unsigned(ARCInstKind::StoreWeak)) |
2142 (1 << unsigned(ARCInstKind::InitWeak)) |
2143 (1 << unsigned(ARCInstKind::CopyWeak)) |
2144 (1 << unsigned(ARCInstKind::MoveWeak)) |
2145 (1 << unsigned(ARCInstKind::DestroyWeak))))
John McCalld935e9c2011-06-15 23:37:01 +00002146 OptimizeWeakCalls(F);
2147
2148 // Optimizations for retain+release pairs.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002149 if (UsedInThisFunction & ((1 << unsigned(ARCInstKind::Retain)) |
2150 (1 << unsigned(ARCInstKind::RetainRV)) |
2151 (1 << unsigned(ARCInstKind::RetainBlock))))
2152 if (UsedInThisFunction & (1 << unsigned(ARCInstKind::Release)))
John McCalld935e9c2011-06-15 23:37:01 +00002153 // Run OptimizeSequences until it either stops making changes or
2154 // no retain+release pair nesting is detected.
2155 while (OptimizeSequences(F)) {}
2156
2157 // Optimizations if objc_autorelease is used.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002158 if (UsedInThisFunction & ((1 << unsigned(ARCInstKind::Autorelease)) |
2159 (1 << unsigned(ARCInstKind::AutoreleaseRV))))
John McCalld935e9c2011-06-15 23:37:01 +00002160 OptimizeReturns(F);
2161
Michael Gottesman9c118152013-04-29 06:16:57 +00002162 // Gather statistics after optimization.
2163#ifndef NDEBUG
2164 if (AreStatisticsEnabled()) {
2165 GatherStatistics(F, true);
2166 }
2167#endif
2168
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00002169 DEBUG(dbgs() << "\n");
2170
John McCalld935e9c2011-06-15 23:37:01 +00002171 return Changed;
2172}
2173
2174void ObjCARCOpt::releaseMemory() {
2175 PA.clear();
2176}
2177
Michael Gottesman97e3df02013-01-14 00:35:14 +00002178/// @}
2179///