blob: 04e19beb53b8372347f984be7a96062547f1df43 [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 Gottesman9de6f962013-01-22 21:49:00 +0000462 bool ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState> &BBStates,
Michael Gottesman0be69202015-03-05 23:28:58 +0000463 BlotMapVector<Value *, RRInfo> &Retains,
464 DenseMap<Value *, RRInfo> &Releases, Module *M,
Craig Topperb94011f2013-07-14 04:42:23 +0000465 SmallVectorImpl<Instruction *> &NewRetains,
466 SmallVectorImpl<Instruction *> &NewReleases,
467 SmallVectorImpl<Instruction *> &DeadInsts,
Michael Gottesman0be69202015-03-05 23:28:58 +0000468 RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
469 Value *Arg, bool KnownSafe,
Michael Gottesman9de6f962013-01-22 21:49:00 +0000470 bool &AnyPairsCompletelyEliminated);
471
John McCalld935e9c2011-06-15 23:37:01 +0000472 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
Michael Gottesman0be69202015-03-05 23:28:58 +0000473 BlotMapVector<Value *, RRInfo> &Retains,
474 DenseMap<Value *, RRInfo> &Releases, Module *M);
John McCalld935e9c2011-06-15 23:37:01 +0000475
476 void OptimizeWeakCalls(Function &F);
477
478 bool OptimizeSequences(Function &F);
479
480 void OptimizeReturns(Function &F);
481
Michael Gottesman9c118152013-04-29 06:16:57 +0000482#ifndef NDEBUG
483 void GatherStatistics(Function &F, bool AfterOptimization = false);
484#endif
485
Craig Topper3e4c6972014-03-05 09:10:37 +0000486 void getAnalysisUsage(AnalysisUsage &AU) const override;
487 bool doInitialization(Module &M) override;
488 bool runOnFunction(Function &F) override;
489 void releaseMemory() override;
John McCalld935e9c2011-06-15 23:37:01 +0000490
491 public:
492 static char ID;
493 ObjCARCOpt() : FunctionPass(ID) {
494 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
495 }
496 };
497}
498
499char ObjCARCOpt::ID = 0;
500INITIALIZE_PASS_BEGIN(ObjCARCOpt,
501 "objc-arc", "ObjC ARC optimization", false, false)
502INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
503INITIALIZE_PASS_END(ObjCARCOpt,
504 "objc-arc", "ObjC ARC optimization", false, false)
505
506Pass *llvm::createObjCARCOptPass() {
507 return new ObjCARCOpt();
508}
509
510void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
511 AU.addRequired<ObjCARCAliasAnalysis>();
512 AU.addRequired<AliasAnalysis>();
513 // ARC optimization doesn't currently split critical edges.
514 AU.setPreservesCFG();
515}
516
Michael Gottesman97e3df02013-01-14 00:35:14 +0000517/// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is
518/// not a return value. Or, if it can be paired with an
519/// objc_autoreleaseReturnValue, delete the pair and return true.
John McCalld935e9c2011-06-15 23:37:01 +0000520bool
521ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +0000522 // Check for the argument being from an immediately preceding call or invoke.
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000523 const Value *Arg = GetArgRCIdentityRoot(RetainRV);
Dan Gohmandae33492012-04-27 18:56:31 +0000524 ImmutableCallSite CS(Arg);
525 if (const Instruction *Call = CS.getInstruction()) {
John McCalld935e9c2011-06-15 23:37:01 +0000526 if (Call->getParent() == RetainRV->getParent()) {
Dan Gohmandae33492012-04-27 18:56:31 +0000527 BasicBlock::const_iterator I = Call;
John McCalld935e9c2011-06-15 23:37:01 +0000528 ++I;
Michael Gottesman65c24812013-03-25 09:27:43 +0000529 while (IsNoopInstruction(I)) ++I;
John McCalld935e9c2011-06-15 23:37:01 +0000530 if (&*I == RetainRV)
531 return false;
Dan Gohmandae33492012-04-27 18:56:31 +0000532 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +0000533 BasicBlock *RetainRVParent = RetainRV->getParent();
534 if (II->getNormalDest() == RetainRVParent) {
Dan Gohmandae33492012-04-27 18:56:31 +0000535 BasicBlock::const_iterator I = RetainRVParent->begin();
Michael Gottesman65c24812013-03-25 09:27:43 +0000536 while (IsNoopInstruction(I)) ++I;
Dan Gohmane3ed2b02012-03-23 18:09:00 +0000537 if (&*I == RetainRV)
538 return false;
539 }
John McCalld935e9c2011-06-15 23:37:01 +0000540 }
Dan Gohmane3ed2b02012-03-23 18:09:00 +0000541 }
John McCalld935e9c2011-06-15 23:37:01 +0000542
543 // Check for being preceded by an objc_autoreleaseReturnValue on the same
544 // pointer. In this case, we can delete the pair.
545 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
546 if (I != Begin) {
Michael Gottesman65c24812013-03-25 09:27:43 +0000547 do --I; while (I != Begin && IsNoopInstruction(I));
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000548 if (GetBasicARCInstKind(I) == ARCInstKind::AutoreleaseRV &&
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000549 GetArgRCIdentityRoot(I) == Arg) {
John McCalld935e9c2011-06-15 23:37:01 +0000550 Changed = true;
551 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +0000552
Michael Gottesman89279f82013-04-05 18:10:41 +0000553 DEBUG(dbgs() << "Erasing autoreleaseRV,retainRV pair: " << *I << "\n"
554 << "Erasing " << *RetainRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +0000555
John McCalld935e9c2011-06-15 23:37:01 +0000556 EraseInstruction(I);
557 EraseInstruction(RetainRV);
558 return true;
559 }
560 }
561
562 // Turn it to a plain objc_retain.
563 Changed = true;
564 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +0000565
Michael Gottesman89279f82013-04-05 18:10:41 +0000566 DEBUG(dbgs() << "Transforming objc_retainAutoreleasedReturnValue => "
Michael Gottesmandef07bb2013-01-05 17:55:42 +0000567 "objc_retain since the operand is not a return value.\n"
Michael Gottesman89279f82013-04-05 18:10:41 +0000568 "Old = " << *RetainRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +0000569
Michael Gottesman14acfac2013-07-06 01:39:23 +0000570 Constant *NewDecl = EP.get(ARCRuntimeEntryPoints::EPT_Retain);
571 cast<CallInst>(RetainRV)->setCalledFunction(NewDecl);
Michael Gottesmandef07bb2013-01-05 17:55:42 +0000572
Michael Gottesman89279f82013-04-05 18:10:41 +0000573 DEBUG(dbgs() << "New = " << *RetainRV << "\n");
Michael Gottesmandef07bb2013-01-05 17:55:42 +0000574
John McCalld935e9c2011-06-15 23:37:01 +0000575 return false;
576}
577
Michael Gottesman97e3df02013-01-14 00:35:14 +0000578/// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not
579/// used as a return value.
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000580void ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F,
581 Instruction *AutoreleaseRV,
582 ARCInstKind &Class) {
John McCalld935e9c2011-06-15 23:37:01 +0000583 // Check for a return of the pointer value.
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000584 const Value *Ptr = GetArgRCIdentityRoot(AutoreleaseRV);
Dan Gohman10a18d52011-08-12 00:36:31 +0000585 SmallVector<const Value *, 2> Users;
586 Users.push_back(Ptr);
587 do {
588 Ptr = Users.pop_back_val();
Chandler Carruthcdf47882014-03-09 03:16:01 +0000589 for (const User *U : Ptr->users()) {
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000590 if (isa<ReturnInst>(U) || GetBasicARCInstKind(U) == ARCInstKind::RetainRV)
Dan Gohman10a18d52011-08-12 00:36:31 +0000591 return;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000592 if (isa<BitCastInst>(U))
593 Users.push_back(U);
Dan Gohman10a18d52011-08-12 00:36:31 +0000594 }
595 } while (!Users.empty());
John McCalld935e9c2011-06-15 23:37:01 +0000596
597 Changed = true;
598 ++NumPeeps;
Michael Gottesman1bf69082013-01-06 21:07:11 +0000599
Michael Gottesman89279f82013-04-05 18:10:41 +0000600 DEBUG(dbgs() << "Transforming objc_autoreleaseReturnValue => "
Michael Gottesman1bf69082013-01-06 21:07:11 +0000601 "objc_autorelease since its operand is not used as a return "
602 "value.\n"
Michael Gottesman89279f82013-04-05 18:10:41 +0000603 "Old = " << *AutoreleaseRV << "\n");
Michael Gottesman1bf69082013-01-06 21:07:11 +0000604
Michael Gottesmanc9656fa2013-01-12 01:25:15 +0000605 CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
Michael Gottesman14acfac2013-07-06 01:39:23 +0000606 Constant *NewDecl = EP.get(ARCRuntimeEntryPoints::EPT_Autorelease);
607 AutoreleaseRVCI->setCalledFunction(NewDecl);
Michael Gottesmanc9656fa2013-01-12 01:25:15 +0000608 AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000609 Class = ARCInstKind::Autorelease;
Michael Gottesman10426b52013-01-07 21:26:07 +0000610
Michael Gottesman89279f82013-04-05 18:10:41 +0000611 DEBUG(dbgs() << "New: " << *AutoreleaseRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +0000612
John McCalld935e9c2011-06-15 23:37:01 +0000613}
614
Michael Gottesman97e3df02013-01-14 00:35:14 +0000615/// Visit each call, one at a time, and make simplifications without doing any
616/// additional analysis.
John McCalld935e9c2011-06-15 23:37:01 +0000617void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
Michael Gottesman89279f82013-04-05 18:10:41 +0000618 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeIndividualCalls ==\n");
John McCalld935e9c2011-06-15 23:37:01 +0000619 // Reset all the flags in preparation for recomputing them.
620 UsedInThisFunction = 0;
621
622 // Visit all objc_* calls in F.
623 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
624 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +0000625
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000626 ARCInstKind Class = GetBasicARCInstKind(Inst);
John McCalld935e9c2011-06-15 23:37:01 +0000627
Michael Gottesman89279f82013-04-05 18:10:41 +0000628 DEBUG(dbgs() << "Visiting: Class: " << Class << "; " << *Inst << "\n");
Michael Gottesman782e3442013-01-17 18:32:34 +0000629
John McCalld935e9c2011-06-15 23:37:01 +0000630 switch (Class) {
631 default: break;
632
633 // Delete no-op casts. These function calls have special semantics, but
634 // the semantics are entirely implemented via lowering in the front-end,
635 // so by the time they reach the optimizer, they are just no-op calls
636 // which return their argument.
637 //
638 // There are gray areas here, as the ability to cast reference-counted
639 // pointers to raw void* and back allows code to break ARC assumptions,
640 // however these are currently considered to be unimportant.
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000641 case ARCInstKind::NoopCast:
John McCalld935e9c2011-06-15 23:37:01 +0000642 Changed = true;
643 ++NumNoops;
Michael Gottesman89279f82013-04-05 18:10:41 +0000644 DEBUG(dbgs() << "Erasing no-op cast: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +0000645 EraseInstruction(Inst);
646 continue;
647
648 // If the pointer-to-weak-pointer is null, it's undefined behavior.
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000649 case ARCInstKind::StoreWeak:
650 case ARCInstKind::LoadWeak:
651 case ARCInstKind::LoadWeakRetained:
652 case ARCInstKind::InitWeak:
653 case ARCInstKind::DestroyWeak: {
John McCalld935e9c2011-06-15 23:37:01 +0000654 CallInst *CI = cast<CallInst>(Inst);
Michael Gottesman65c24812013-03-25 09:27:43 +0000655 if (IsNullOrUndef(CI->getArgOperand(0))) {
Dan Gohman670f9372012-04-13 18:57:48 +0000656 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +0000657 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +0000658 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
659 Constant::getNullValue(Ty),
660 CI);
Michael Gottesman10426b52013-01-07 21:26:07 +0000661 llvm::Value *NewValue = UndefValue::get(CI->getType());
Michael Gottesman89279f82013-04-05 18:10:41 +0000662 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
663 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
Michael Gottesmanfec61c02013-01-06 21:54:30 +0000664 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +0000665 CI->eraseFromParent();
666 continue;
667 }
668 break;
669 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000670 case ARCInstKind::CopyWeak:
671 case ARCInstKind::MoveWeak: {
John McCalld935e9c2011-06-15 23:37:01 +0000672 CallInst *CI = cast<CallInst>(Inst);
Michael Gottesman65c24812013-03-25 09:27:43 +0000673 if (IsNullOrUndef(CI->getArgOperand(0)) ||
674 IsNullOrUndef(CI->getArgOperand(1))) {
Dan Gohman670f9372012-04-13 18:57:48 +0000675 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +0000676 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +0000677 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
678 Constant::getNullValue(Ty),
679 CI);
Michael Gottesmanfec61c02013-01-06 21:54:30 +0000680
681 llvm::Value *NewValue = UndefValue::get(CI->getType());
Michael Gottesman89279f82013-04-05 18:10:41 +0000682 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
683 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +0000684
Michael Gottesmanfec61c02013-01-06 21:54:30 +0000685 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +0000686 CI->eraseFromParent();
687 continue;
688 }
689 break;
690 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000691 case ARCInstKind::RetainRV:
John McCalld935e9c2011-06-15 23:37:01 +0000692 if (OptimizeRetainRVCall(F, Inst))
693 continue;
694 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000695 case ARCInstKind::AutoreleaseRV:
Michael Gottesman556ff612013-01-12 01:25:19 +0000696 OptimizeAutoreleaseRVCall(F, Inst, Class);
John McCalld935e9c2011-06-15 23:37:01 +0000697 break;
698 }
699
Michael Gottesmanb8c88362013-04-03 02:57:24 +0000700 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
John McCalld935e9c2011-06-15 23:37:01 +0000701 if (IsAutorelease(Class) && Inst->use_empty()) {
702 CallInst *Call = cast<CallInst>(Inst);
703 const Value *Arg = Call->getArgOperand(0);
704 Arg = FindSingleUseIdentifiedObject(Arg);
705 if (Arg) {
706 Changed = true;
707 ++NumAutoreleases;
708
709 // Create the declaration lazily.
710 LLVMContext &C = Inst->getContext();
Michael Gottesman01df4502013-07-06 01:41:35 +0000711
Michael Gottesman14acfac2013-07-06 01:39:23 +0000712 Constant *Decl = EP.get(ARCRuntimeEntryPoints::EPT_Release);
713 CallInst *NewCall = CallInst::Create(Decl, Call->getArgOperand(0), "",
714 Call);
Michael Gottesman41c01002015-03-06 00:34:33 +0000715 NewCall->setMetadata(MDKindCache.ImpreciseReleaseMDKind,
716 MDNode::get(C, None));
Michael Gottesman10426b52013-01-07 21:26:07 +0000717
Michael Gottesman89279f82013-04-05 18:10:41 +0000718 DEBUG(dbgs() << "Replacing autorelease{,RV}(x) with objc_release(x) "
719 "since x is otherwise unused.\nOld: " << *Call << "\nNew: "
720 << *NewCall << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +0000721
John McCalld935e9c2011-06-15 23:37:01 +0000722 EraseInstruction(Call);
723 Inst = NewCall;
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000724 Class = ARCInstKind::Release;
John McCalld935e9c2011-06-15 23:37:01 +0000725 }
726 }
727
728 // For functions which can never be passed stack arguments, add
729 // a tail keyword.
730 if (IsAlwaysTail(Class)) {
731 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +0000732 DEBUG(dbgs() << "Adding tail keyword to function since it can never be "
733 "passed stack args: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +0000734 cast<CallInst>(Inst)->setTailCall();
735 }
736
Michael Gottesmanc9656fa2013-01-12 01:25:15 +0000737 // Ensure that functions that can never have a "tail" keyword due to the
738 // semantics of ARC truly do not do so.
739 if (IsNeverTail(Class)) {
740 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +0000741 DEBUG(dbgs() << "Removing tail keyword from function: " << *Inst <<
Michael Gottesmanc9656fa2013-01-12 01:25:15 +0000742 "\n");
743 cast<CallInst>(Inst)->setTailCall(false);
744 }
745
John McCalld935e9c2011-06-15 23:37:01 +0000746 // Set nounwind as needed.
747 if (IsNoThrow(Class)) {
748 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +0000749 DEBUG(dbgs() << "Found no throw class. Setting nounwind on: " << *Inst
750 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +0000751 cast<CallInst>(Inst)->setDoesNotThrow();
752 }
753
754 if (!IsNoopOnNull(Class)) {
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000755 UsedInThisFunction |= 1 << unsigned(Class);
John McCalld935e9c2011-06-15 23:37:01 +0000756 continue;
757 }
758
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000759 const Value *Arg = GetArgRCIdentityRoot(Inst);
John McCalld935e9c2011-06-15 23:37:01 +0000760
761 // ARC calls with null are no-ops. Delete them.
Michael Gottesman65c24812013-03-25 09:27:43 +0000762 if (IsNullOrUndef(Arg)) {
John McCalld935e9c2011-06-15 23:37:01 +0000763 Changed = true;
764 ++NumNoops;
Michael Gottesman89279f82013-04-05 18:10:41 +0000765 DEBUG(dbgs() << "ARC calls with null are no-ops. Erasing: " << *Inst
766 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +0000767 EraseInstruction(Inst);
768 continue;
769 }
770
771 // Keep track of which of retain, release, autorelease, and retain_block
772 // are actually present in this function.
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000773 UsedInThisFunction |= 1 << unsigned(Class);
John McCalld935e9c2011-06-15 23:37:01 +0000774
775 // If Arg is a PHI, and one or more incoming values to the
776 // PHI are null, and the call is control-equivalent to the PHI, and there
777 // are no relevant side effects between the PHI and the call, the call
778 // could be pushed up to just those paths with non-null incoming values.
779 // For now, don't bother splitting critical edges for this.
780 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
781 Worklist.push_back(std::make_pair(Inst, Arg));
782 do {
783 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
784 Inst = Pair.first;
785 Arg = Pair.second;
786
787 const PHINode *PN = dyn_cast<PHINode>(Arg);
788 if (!PN) continue;
789
790 // Determine if the PHI has any null operands, or any incoming
791 // critical edges.
792 bool HasNull = false;
793 bool HasCriticalEdges = false;
794 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
795 Value *Incoming =
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000796 GetRCIdentityRoot(PN->getIncomingValue(i));
Michael Gottesman65c24812013-03-25 09:27:43 +0000797 if (IsNullOrUndef(Incoming))
John McCalld935e9c2011-06-15 23:37:01 +0000798 HasNull = true;
799 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
800 .getNumSuccessors() != 1) {
801 HasCriticalEdges = true;
802 break;
803 }
804 }
805 // If we have null operands and no critical edges, optimize.
806 if (!HasCriticalEdges && HasNull) {
807 SmallPtrSet<Instruction *, 4> DependingInstructions;
808 SmallPtrSet<const BasicBlock *, 4> Visited;
809
810 // Check that there is nothing that cares about the reference
811 // count between the call and the phi.
Dan Gohman8478d762012-04-13 00:59:57 +0000812 switch (Class) {
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000813 case ARCInstKind::Retain:
814 case ARCInstKind::RetainBlock:
Dan Gohman8478d762012-04-13 00:59:57 +0000815 // These can always be moved up.
816 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000817 case ARCInstKind::Release:
Dan Gohman41375a32012-05-08 23:39:44 +0000818 // These can't be moved across things that care about the retain
819 // count.
Dan Gohman8478d762012-04-13 00:59:57 +0000820 FindDependencies(NeedsPositiveRetainCount, Arg,
821 Inst->getParent(), Inst,
822 DependingInstructions, Visited, PA);
823 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000824 case ARCInstKind::Autorelease:
Dan Gohman8478d762012-04-13 00:59:57 +0000825 // These can't be moved across autorelease pool scope boundaries.
826 FindDependencies(AutoreleasePoolBoundary, Arg,
827 Inst->getParent(), Inst,
828 DependingInstructions, Visited, PA);
829 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000830 case ARCInstKind::RetainRV:
831 case ARCInstKind::AutoreleaseRV:
Dan Gohman8478d762012-04-13 00:59:57 +0000832 // Don't move these; the RV optimization depends on the autoreleaseRV
833 // being tail called, and the retainRV being immediately after a call
834 // (which might still happen if we get lucky with codegen layout, but
835 // it's not worth taking the chance).
836 continue;
837 default:
838 llvm_unreachable("Invalid dependence flavor");
839 }
840
John McCalld935e9c2011-06-15 23:37:01 +0000841 if (DependingInstructions.size() == 1 &&
842 *DependingInstructions.begin() == PN) {
843 Changed = true;
844 ++NumPartialNoops;
845 // Clone the call into each predecessor that has a non-null value.
846 CallInst *CInst = cast<CallInst>(Inst);
Chris Lattner229907c2011-07-18 04:54:35 +0000847 Type *ParamTy = CInst->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +0000848 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
849 Value *Incoming =
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000850 GetRCIdentityRoot(PN->getIncomingValue(i));
Michael Gottesman65c24812013-03-25 09:27:43 +0000851 if (!IsNullOrUndef(Incoming)) {
John McCalld935e9c2011-06-15 23:37:01 +0000852 CallInst *Clone = cast<CallInst>(CInst->clone());
853 Value *Op = PN->getIncomingValue(i);
854 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
855 if (Op->getType() != ParamTy)
856 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
857 Clone->setArgOperand(0, Op);
858 Clone->insertBefore(InsertPos);
Michael Gottesmanc189a392013-01-09 19:23:24 +0000859
Michael Gottesman89279f82013-04-05 18:10:41 +0000860 DEBUG(dbgs() << "Cloning "
Michael Gottesmanc189a392013-01-09 19:23:24 +0000861 << *CInst << "\n"
Michael Gottesman89279f82013-04-05 18:10:41 +0000862 "And inserting clone at " << *InsertPos << "\n");
John McCalld935e9c2011-06-15 23:37:01 +0000863 Worklist.push_back(std::make_pair(Clone, Incoming));
864 }
865 }
866 // Erase the original call.
Michael Gottesmanc189a392013-01-09 19:23:24 +0000867 DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +0000868 EraseInstruction(CInst);
869 continue;
870 }
871 }
872 } while (!Worklist.empty());
873 }
874}
875
Michael Gottesman323964c2013-04-18 05:39:45 +0000876/// If we have a top down pointer in the S_Use state, make sure that there are
877/// no CFG hazards by checking the states of various bottom up pointers.
878static void CheckForUseCFGHazard(const Sequence SuccSSeq,
879 const bool SuccSRRIKnownSafe,
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000880 TopDownPtrState &S,
Michael Gottesman323964c2013-04-18 05:39:45 +0000881 bool &SomeSuccHasSame,
882 bool &AllSuccsHaveSame,
Michael Gottesmane67f40c2013-05-24 20:44:05 +0000883 bool &NotAllSeqEqualButKnownSafe,
Michael Gottesman323964c2013-04-18 05:39:45 +0000884 bool &ShouldContinue) {
885 switch (SuccSSeq) {
886 case S_CanRelease: {
Michael Gottesman93132252013-06-21 06:59:02 +0000887 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe) {
Michael Gottesman323964c2013-04-18 05:39:45 +0000888 S.ClearSequenceProgress();
889 break;
890 }
Michael Gottesman2f294592013-06-21 19:12:36 +0000891 S.SetCFGHazardAfflicted(true);
Michael Gottesman323964c2013-04-18 05:39:45 +0000892 ShouldContinue = true;
893 break;
894 }
895 case S_Use:
896 SomeSuccHasSame = true;
897 break;
898 case S_Stop:
899 case S_Release:
900 case S_MovableRelease:
Michael Gottesman93132252013-06-21 06:59:02 +0000901 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe)
Michael Gottesman323964c2013-04-18 05:39:45 +0000902 AllSuccsHaveSame = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +0000903 else
904 NotAllSeqEqualButKnownSafe = true;
Michael Gottesman323964c2013-04-18 05:39:45 +0000905 break;
906 case S_Retain:
907 llvm_unreachable("bottom-up pointer in retain state!");
908 case S_None:
909 llvm_unreachable("This should have been handled earlier.");
910 }
911}
912
913/// If we have a Top Down pointer in the S_CanRelease state, make sure that
914/// there are no CFG hazards by checking the states of various bottom up
915/// pointers.
916static void CheckForCanReleaseCFGHazard(const Sequence SuccSSeq,
917 const bool SuccSRRIKnownSafe,
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000918 TopDownPtrState &S,
Michael Gottesman323964c2013-04-18 05:39:45 +0000919 bool &SomeSuccHasSame,
Michael Gottesmane67f40c2013-05-24 20:44:05 +0000920 bool &AllSuccsHaveSame,
921 bool &NotAllSeqEqualButKnownSafe) {
Michael Gottesman323964c2013-04-18 05:39:45 +0000922 switch (SuccSSeq) {
923 case S_CanRelease:
924 SomeSuccHasSame = true;
925 break;
926 case S_Stop:
927 case S_Release:
928 case S_MovableRelease:
929 case S_Use:
Michael Gottesman93132252013-06-21 06:59:02 +0000930 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe)
Michael Gottesman323964c2013-04-18 05:39:45 +0000931 AllSuccsHaveSame = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +0000932 else
933 NotAllSeqEqualButKnownSafe = true;
Michael Gottesman323964c2013-04-18 05:39:45 +0000934 break;
935 case S_Retain:
936 llvm_unreachable("bottom-up pointer in retain state!");
937 case S_None:
938 llvm_unreachable("This should have been handled earlier.");
939 }
940}
941
Michael Gottesman97e3df02013-01-14 00:35:14 +0000942/// Check for critical edges, loop boundaries, irreducible control flow, or
943/// other CFG structures where moving code across the edge would result in it
944/// being executed more.
John McCalld935e9c2011-06-15 23:37:01 +0000945void
946ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
947 DenseMap<const BasicBlock *, BBState> &BBStates,
948 BBState &MyStates) const {
949 // If any top-down local-use or possible-dec has a succ which is earlier in
950 // the sequence, forget it.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000951 for (auto I = MyStates.top_down_ptr_begin(), E = MyStates.top_down_ptr_end();
952 I != E; ++I) {
953 TopDownPtrState &S = I->second;
Michael Gottesman323964c2013-04-18 05:39:45 +0000954 const Sequence Seq = I->second.GetSeq();
Dan Gohman0155f302012-02-17 18:59:53 +0000955
Michael Gottesman323964c2013-04-18 05:39:45 +0000956 // We only care about S_Retain, S_CanRelease, and S_Use.
957 if (Seq == S_None)
958 continue;
Dan Gohman0155f302012-02-17 18:59:53 +0000959
Michael Gottesman323964c2013-04-18 05:39:45 +0000960 // Make sure that if extra top down states are added in the future that this
961 // code is updated to handle it.
962 assert((Seq == S_Retain || Seq == S_CanRelease || Seq == S_Use) &&
963 "Unknown top down sequence state.");
964
965 const Value *Arg = I->first;
966 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
967 bool SomeSuccHasSame = false;
968 bool AllSuccsHaveSame = true;
Michael Gottesmane67f40c2013-05-24 20:44:05 +0000969 bool NotAllSeqEqualButKnownSafe = false;
Michael Gottesman323964c2013-04-18 05:39:45 +0000970
971 succ_const_iterator SI(TI), SE(TI, false);
972
973 for (; SI != SE; ++SI) {
974 // If VisitBottomUp has pointer information for this successor, take
975 // what we know about it.
976 const DenseMap<const BasicBlock *, BBState>::iterator BBI =
977 BBStates.find(*SI);
978 assert(BBI != BBStates.end());
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000979 const BottomUpPtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
Michael Gottesman323964c2013-04-18 05:39:45 +0000980 const Sequence SuccSSeq = SuccS.GetSeq();
981
982 // If bottom up, the pointer is in an S_None state, clear the sequence
983 // progress since the sequence in the bottom up state finished
984 // suggesting a mismatch in between retains/releases. This is true for
985 // all three cases that we are handling here: S_Retain, S_Use, and
986 // S_CanRelease.
987 if (SuccSSeq == S_None) {
Dan Gohman12130272011-08-12 00:26:31 +0000988 S.ClearSequenceProgress();
Michael Gottesman323964c2013-04-18 05:39:45 +0000989 continue;
990 }
991
992 // If we have S_Use or S_CanRelease, perform our check for cfg hazard
993 // checks.
Michael Gottesman93132252013-06-21 06:59:02 +0000994 const bool SuccSRRIKnownSafe = SuccS.IsKnownSafe();
Michael Gottesman323964c2013-04-18 05:39:45 +0000995
996 // *NOTE* We do not use Seq from above here since we are allowing for
997 // S.GetSeq() to change while we are visiting basic blocks.
998 switch(S.GetSeq()) {
999 case S_Use: {
1000 bool ShouldContinue = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001001 CheckForUseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S, SomeSuccHasSame,
1002 AllSuccsHaveSame, NotAllSeqEqualButKnownSafe,
Michael Gottesman323964c2013-04-18 05:39:45 +00001003 ShouldContinue);
1004 if (ShouldContinue)
1005 continue;
1006 break;
1007 }
1008 case S_CanRelease: {
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001009 CheckForCanReleaseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S,
1010 SomeSuccHasSame, AllSuccsHaveSame,
1011 NotAllSeqEqualButKnownSafe);
Michael Gottesman323964c2013-04-18 05:39:45 +00001012 break;
1013 }
1014 case S_Retain:
1015 case S_None:
1016 case S_Stop:
1017 case S_Release:
1018 case S_MovableRelease:
1019 break;
1020 }
John McCalld935e9c2011-06-15 23:37:01 +00001021 }
Michael Gottesman323964c2013-04-18 05:39:45 +00001022
1023 // If the state at the other end of any of the successor edges
1024 // matches the current state, require all edges to match. This
1025 // guards against loops in the middle of a sequence.
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001026 if (SomeSuccHasSame && !AllSuccsHaveSame) {
Michael Gottesman323964c2013-04-18 05:39:45 +00001027 S.ClearSequenceProgress();
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001028 } else if (NotAllSeqEqualButKnownSafe) {
1029 // If we would have cleared the state foregoing the fact that we are known
1030 // safe, stop code motion. This is because whether or not it is safe to
1031 // remove RR pairs via KnownSafe is an orthogonal concept to whether we
1032 // are allowed to perform code motion.
Michael Gottesman2f294592013-06-21 19:12:36 +00001033 S.SetCFGHazardAfflicted(true);
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001034 }
Michael Gottesman323964c2013-04-18 05:39:45 +00001035 }
John McCalld935e9c2011-06-15 23:37:01 +00001036}
1037
Michael Gottesman0be69202015-03-05 23:28:58 +00001038bool ObjCARCOpt::VisitInstructionBottomUp(
1039 Instruction *Inst, BasicBlock *BB, BlotMapVector<Value *, RRInfo> &Retains,
1040 BBState &MyStates) {
Dan Gohman817a7c62012-03-22 18:24:56 +00001041 bool NestingDetected = false;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001042 ARCInstKind Class = GetARCInstKind(Inst);
Craig Topperf40110f2014-04-25 05:29:35 +00001043 const Value *Arg = nullptr;
Michael Gottesman79249972013-04-05 23:46:45 +00001044
Michael Gottesman1d8d2572013-04-05 22:54:28 +00001045 DEBUG(dbgs() << "Class: " << Class << "\n");
Michael Gottesman79249972013-04-05 23:46:45 +00001046
Dan Gohman817a7c62012-03-22 18:24:56 +00001047 switch (Class) {
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001048 case ARCInstKind::Release: {
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001049 Arg = GetArgRCIdentityRoot(Inst);
Dan Gohman817a7c62012-03-22 18:24:56 +00001050
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001051 BottomUpPtrState &S = MyStates.getPtrBottomUpState(Arg);
Michael Gottesman4eae3962015-03-06 00:34:39 +00001052 NestingDetected |= S.InitBottomUp(MDKindCache, Inst);
Dan Gohman817a7c62012-03-22 18:24:56 +00001053 break;
1054 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001055 case ARCInstKind::RetainBlock:
Michael Gottesman158fdf62013-03-28 20:11:19 +00001056 // In OptimizeIndividualCalls, we have strength reduced all optimizable
1057 // objc_retainBlocks to objc_retains. Thus at this point any
1058 // objc_retainBlocks that we see are not optimizable.
1059 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001060 case ARCInstKind::Retain:
1061 case ARCInstKind::RetainRV: {
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001062 Arg = GetArgRCIdentityRoot(Inst);
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001063 BottomUpPtrState &S = MyStates.getPtrBottomUpState(Arg);
Michael Gottesman60805962015-03-06 00:34:42 +00001064 if (S.MatchWithRetain()) {
1065 // Don't do retain+release tracking for ARCInstKind::RetainRV, because
1066 // it's better to let it remain as the first instruction after a call.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001067 if (Class != ARCInstKind::RetainRV)
Michael Gottesmane3943d02013-06-21 19:44:30 +00001068 Retains[Inst] = S.GetRRInfo();
Dan Gohman817a7c62012-03-22 18:24:56 +00001069 S.ClearSequenceProgress();
Dan Gohman817a7c62012-03-22 18:24:56 +00001070 }
Michael Gottesman31ba23a2013-04-05 22:54:32 +00001071 // A retain moving bottom up can be a use.
1072 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001073 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001074 case ARCInstKind::AutoreleasepoolPop:
Dan Gohman817a7c62012-03-22 18:24:56 +00001075 // Conservatively, clear MyStates for all known pointers.
1076 MyStates.clearBottomUpPointers();
1077 return NestingDetected;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001078 case ARCInstKind::AutoreleasepoolPush:
1079 case ARCInstKind::None:
Dan Gohman817a7c62012-03-22 18:24:56 +00001080 // These are irrelevant.
1081 return NestingDetected;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001082 case ARCInstKind::User:
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001083 // If we have a store into an alloca of a pointer we are tracking, the
1084 // pointer has multiple owners implying that we must be more conservative.
1085 //
1086 // This comes up in the context of a pointer being ``KnownSafe''. In the
Alp Tokercb402912014-01-24 17:20:08 +00001087 // presence of a block being initialized, the frontend will emit the
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001088 // objc_retain on the original pointer and the release on the pointer loaded
1089 // from the alloca. The optimizer will through the provenance analysis
1090 // realize that the two are related, but since we only require KnownSafe in
1091 // one direction, will match the inner retain on the original pointer with
1092 // the guard release on the original pointer. This is fixed by ensuring that
Alp Tokercb402912014-01-24 17:20:08 +00001093 // in the presence of allocas we only unconditionally remove pointers if
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001094 // both our retain and our release are KnownSafe.
1095 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001096 const DataLayout &DL = BB->getModule()->getDataLayout();
1097 if (AreAnyUnderlyingObjectsAnAlloca(SI->getPointerOperand(), DL)) {
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001098 auto I = MyStates.findPtrBottomUpState(
1099 GetRCIdentityRoot(SI->getValueOperand()));
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001100 if (I != MyStates.bottom_up_ptr_end())
Michael Gottesman5a91bbf2013-05-24 20:44:02 +00001101 MultiOwnersSet.insert(I->first);
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001102 }
1103 }
1104 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001105 default:
1106 break;
1107 }
1108
1109 // Consider any other possible effects of this instruction on each
1110 // pointer being tracked.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001111 for (auto MI = MyStates.bottom_up_ptr_begin(),
1112 ME = MyStates.bottom_up_ptr_end();
1113 MI != ME; ++MI) {
Dan Gohman817a7c62012-03-22 18:24:56 +00001114 const Value *Ptr = MI->first;
1115 if (Ptr == Arg)
1116 continue; // Handled above.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001117 BottomUpPtrState &S = MI->second;
Dan Gohman817a7c62012-03-22 18:24:56 +00001118
Michael Gottesman16e6a202015-03-06 02:07:12 +00001119 if (S.HandlePotentialAlterRefCount(Inst, Ptr, PA, Class))
1120 continue;
Dan Gohman817a7c62012-03-22 18:24:56 +00001121
Michael Gottesman16e6a202015-03-06 02:07:12 +00001122 S.HandlePotentialUse(BB, Inst, Ptr, PA, Class);
Dan Gohman817a7c62012-03-22 18:24:56 +00001123 }
1124
1125 return NestingDetected;
1126}
1127
Michael Gottesman0be69202015-03-05 23:28:58 +00001128bool ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
1129 DenseMap<const BasicBlock *, BBState> &BBStates,
1130 BlotMapVector<Value *, RRInfo> &Retains) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001131
1132 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitBottomUp ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00001133
John McCalld935e9c2011-06-15 23:37:01 +00001134 bool NestingDetected = false;
1135 BBState &MyStates = BBStates[BB];
1136
1137 // Merge the states from each successor to compute the initial state
1138 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00001139 BBState::edge_iterator SI(MyStates.succ_begin()),
1140 SE(MyStates.succ_end());
1141 if (SI != SE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001142 const BasicBlock *Succ = *SI;
1143 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
1144 assert(I != BBStates.end());
1145 MyStates.InitFromSucc(I->second);
1146 ++SI;
1147 for (; SI != SE; ++SI) {
1148 Succ = *SI;
1149 I = BBStates.find(Succ);
1150 assert(I != BBStates.end());
1151 MyStates.MergeSucc(I->second);
1152 }
Michael Gottesman60f6b282013-03-29 05:13:07 +00001153 }
Michael Gottesmancd4de0f2013-03-26 00:42:09 +00001154
John McCalld935e9c2011-06-15 23:37:01 +00001155 // Visit all the instructions, bottom-up.
1156 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001157 Instruction *Inst = std::prev(I);
Dan Gohman5c70fad2012-03-23 17:47:54 +00001158
1159 // Invoke instructions are visited as part of their successors (below).
1160 if (isa<InvokeInst>(Inst))
1161 continue;
1162
Michael Gottesman89279f82013-04-05 18:10:41 +00001163 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001164
Dan Gohman5c70fad2012-03-23 17:47:54 +00001165 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
1166 }
1167
Dan Gohmandae33492012-04-27 18:56:31 +00001168 // If there's a predecessor with an invoke, visit the invoke as if it were
1169 // part of this block, since we can't insert code after an invoke in its own
1170 // block, and we don't want to split critical edges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001171 for (BBState::edge_iterator PI(MyStates.pred_begin()),
1172 PE(MyStates.pred_end()); PI != PE; ++PI) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00001173 BasicBlock *Pred = *PI;
Dan Gohmandae33492012-04-27 18:56:31 +00001174 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
1175 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
Dan Gohman817a7c62012-03-22 18:24:56 +00001176 }
John McCalld935e9c2011-06-15 23:37:01 +00001177
Dan Gohman817a7c62012-03-22 18:24:56 +00001178 return NestingDetected;
1179}
John McCalld935e9c2011-06-15 23:37:01 +00001180
Dan Gohman817a7c62012-03-22 18:24:56 +00001181bool
1182ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
1183 DenseMap<Value *, RRInfo> &Releases,
1184 BBState &MyStates) {
1185 bool NestingDetected = false;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001186 ARCInstKind Class = GetARCInstKind(Inst);
Craig Topperf40110f2014-04-25 05:29:35 +00001187 const Value *Arg = nullptr;
John McCalld935e9c2011-06-15 23:37:01 +00001188
Dan Gohman817a7c62012-03-22 18:24:56 +00001189 switch (Class) {
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001190 case ARCInstKind::RetainBlock:
Michael Gottesman158fdf62013-03-28 20:11:19 +00001191 // In OptimizeIndividualCalls, we have strength reduced all optimizable
1192 // objc_retainBlocks to objc_retains. Thus at this point any
Michael Gottesman60805962015-03-06 00:34:42 +00001193 // objc_retainBlocks that we see are not optimizable. We need to break since
1194 // a retain can be a potential use.
Michael Gottesman158fdf62013-03-28 20:11:19 +00001195 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001196 case ARCInstKind::Retain:
1197 case ARCInstKind::RetainRV: {
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001198 Arg = GetArgRCIdentityRoot(Inst);
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001199 TopDownPtrState &S = MyStates.getPtrTopDownState(Arg);
Michael Gottesman4eae3962015-03-06 00:34:39 +00001200 NestingDetected |= S.InitTopDown(Class, Inst);
Dan Gohmanf64ff8e2012-07-23 19:27:31 +00001201 // A retain can be a potential use; procede to the generic checking
1202 // code below.
1203 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001204 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001205 case ARCInstKind::Release: {
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001206 Arg = GetArgRCIdentityRoot(Inst);
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001207 TopDownPtrState &S = MyStates.getPtrTopDownState(Arg);
Michael Gottesman60805962015-03-06 00:34:42 +00001208 // Try to form a tentative pair in between this release instruction and the
1209 // top down pointers that we are tracking.
1210 if (S.MatchWithRelease(MDKindCache, Inst)) {
1211 // If we succeed, copy S's RRInfo into the Release -> {Retain Set
1212 // Map}. Then we clear S.
Michael Gottesmane3943d02013-06-21 19:44:30 +00001213 Releases[Inst] = S.GetRRInfo();
Dan Gohman817a7c62012-03-22 18:24:56 +00001214 S.ClearSequenceProgress();
Dan Gohman817a7c62012-03-22 18:24:56 +00001215 }
1216 break;
1217 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001218 case ARCInstKind::AutoreleasepoolPop:
Dan Gohman817a7c62012-03-22 18:24:56 +00001219 // Conservatively, clear MyStates for all known pointers.
1220 MyStates.clearTopDownPointers();
Michael Gottesman60805962015-03-06 00:34:42 +00001221 return false;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001222 case ARCInstKind::AutoreleasepoolPush:
1223 case ARCInstKind::None:
Michael Gottesman60805962015-03-06 00:34:42 +00001224 // These can not be uses of
1225 return false;
Dan Gohman817a7c62012-03-22 18:24:56 +00001226 default:
1227 break;
1228 }
1229
1230 // Consider any other possible effects of this instruction on each
1231 // pointer being tracked.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001232 for (auto MI = MyStates.top_down_ptr_begin(),
1233 ME = MyStates.top_down_ptr_end();
1234 MI != ME; ++MI) {
Dan Gohman817a7c62012-03-22 18:24:56 +00001235 const Value *Ptr = MI->first;
1236 if (Ptr == Arg)
1237 continue; // Handled above.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001238 TopDownPtrState &S = MI->second;
Michael Gottesman16e6a202015-03-06 02:07:12 +00001239 if (S.HandlePotentialAlterRefCount(Inst, Ptr, PA, Class))
1240 continue;
Dan Gohman817a7c62012-03-22 18:24:56 +00001241
Michael Gottesman16e6a202015-03-06 02:07:12 +00001242 S.HandlePotentialUse(Inst, Ptr, PA, Class);
John McCalld935e9c2011-06-15 23:37:01 +00001243 }
1244
1245 return NestingDetected;
1246}
1247
1248bool
1249ObjCARCOpt::VisitTopDown(BasicBlock *BB,
1250 DenseMap<const BasicBlock *, BBState> &BBStates,
1251 DenseMap<Value *, RRInfo> &Releases) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001252 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitTopDown ==\n");
John McCalld935e9c2011-06-15 23:37:01 +00001253 bool NestingDetected = false;
1254 BBState &MyStates = BBStates[BB];
1255
1256 // Merge the states from each predecessor to compute the initial state
1257 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00001258 BBState::edge_iterator PI(MyStates.pred_begin()),
1259 PE(MyStates.pred_end());
1260 if (PI != PE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001261 const BasicBlock *Pred = *PI;
1262 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
1263 assert(I != BBStates.end());
1264 MyStates.InitFromPred(I->second);
1265 ++PI;
1266 for (; PI != PE; ++PI) {
1267 Pred = *PI;
1268 I = BBStates.find(Pred);
1269 assert(I != BBStates.end());
1270 MyStates.MergePred(I->second);
1271 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001272 }
John McCalld935e9c2011-06-15 23:37:01 +00001273
1274 // Visit all the instructions, top-down.
1275 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1276 Instruction *Inst = I;
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001277
Michael Gottesman89279f82013-04-05 18:10:41 +00001278 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001279
Dan Gohman817a7c62012-03-22 18:24:56 +00001280 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00001281 }
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00001282
John McCalld935e9c2011-06-15 23:37:01 +00001283 CheckForCFGHazards(BB, BBStates, MyStates);
1284 return NestingDetected;
1285}
1286
Dan Gohmana53a12c2011-12-12 19:42:25 +00001287static void
1288ComputePostOrders(Function &F,
1289 SmallVectorImpl<BasicBlock *> &PostOrder,
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001290 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
1291 unsigned NoObjCARCExceptionsMDKind,
1292 DenseMap<const BasicBlock *, BBState> &BBStates) {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001293 /// The visited set, for doing DFS walks.
Dan Gohmana53a12c2011-12-12 19:42:25 +00001294 SmallPtrSet<BasicBlock *, 16> Visited;
1295
1296 // Do DFS, computing the PostOrder.
1297 SmallPtrSet<BasicBlock *, 16> OnStack;
1298 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001299
1300 // Functions always have exactly one entry block, and we don't have
1301 // any other block that we treat like an entry block.
Dan Gohmana53a12c2011-12-12 19:42:25 +00001302 BasicBlock *EntryBB = &F.getEntryBlock();
Dan Gohman41375a32012-05-08 23:39:44 +00001303 BBState &MyStates = BBStates[EntryBB];
1304 MyStates.SetAsEntry();
1305 TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
1306 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
Dan Gohmana53a12c2011-12-12 19:42:25 +00001307 Visited.insert(EntryBB);
1308 OnStack.insert(EntryBB);
1309 do {
1310 dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001311 BasicBlock *CurrBB = SuccStack.back().first;
1312 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
1313 succ_iterator SE(TI, false);
Dan Gohman41375a32012-05-08 23:39:44 +00001314
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001315 while (SuccStack.back().second != SE) {
1316 BasicBlock *SuccBB = *SuccStack.back().second++;
David Blaikie70573dc2014-11-19 07:49:26 +00001317 if (Visited.insert(SuccBB).second) {
Dan Gohman41375a32012-05-08 23:39:44 +00001318 TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
1319 SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001320 BBStates[CurrBB].addSucc(SuccBB);
Dan Gohman41375a32012-05-08 23:39:44 +00001321 BBState &SuccStates = BBStates[SuccBB];
1322 SuccStates.addPred(CurrBB);
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001323 OnStack.insert(SuccBB);
Dan Gohmana53a12c2011-12-12 19:42:25 +00001324 goto dfs_next_succ;
1325 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001326
1327 if (!OnStack.count(SuccBB)) {
1328 BBStates[CurrBB].addSucc(SuccBB);
1329 BBStates[SuccBB].addPred(CurrBB);
1330 }
Dan Gohmana53a12c2011-12-12 19:42:25 +00001331 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001332 OnStack.erase(CurrBB);
1333 PostOrder.push_back(CurrBB);
1334 SuccStack.pop_back();
Dan Gohmana53a12c2011-12-12 19:42:25 +00001335 } while (!SuccStack.empty());
1336
1337 Visited.clear();
1338
Dan Gohmana53a12c2011-12-12 19:42:25 +00001339 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001340 // Functions may have many exits, and there also blocks which we treat
1341 // as exits due to ignored edges.
1342 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
1343 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
1344 BasicBlock *ExitBB = I;
1345 BBState &MyStates = BBStates[ExitBB];
1346 if (!MyStates.isExit())
1347 continue;
1348
Dan Gohmandae33492012-04-27 18:56:31 +00001349 MyStates.SetAsExit();
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001350
1351 PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00001352 Visited.insert(ExitBB);
1353 while (!PredStack.empty()) {
1354 reverse_dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001355 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
1356 while (PredStack.back().second != PE) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00001357 BasicBlock *BB = *PredStack.back().second++;
David Blaikie70573dc2014-11-19 07:49:26 +00001358 if (Visited.insert(BB).second) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001359 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00001360 goto reverse_dfs_next_succ;
1361 }
1362 }
1363 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
1364 }
1365 }
1366}
1367
Michael Gottesman97e3df02013-01-14 00:35:14 +00001368// Visit the function both top-down and bottom-up.
Michael Gottesman0be69202015-03-05 23:28:58 +00001369bool ObjCARCOpt::Visit(Function &F,
1370 DenseMap<const BasicBlock *, BBState> &BBStates,
1371 BlotMapVector<Value *, RRInfo> &Retains,
1372 DenseMap<Value *, RRInfo> &Releases) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00001373
1374 // Use reverse-postorder traversals, because we magically know that loops
1375 // will be well behaved, i.e. they won't repeatedly call retain on a single
1376 // pointer without doing a release. We can't use the ReversePostOrderTraversal
1377 // class here because we want the reverse-CFG postorder to consider each
1378 // function exit point, and we want to ignore selected cycle edges.
1379 SmallVector<BasicBlock *, 16> PostOrder;
1380 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001381 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
Michael Gottesman41c01002015-03-06 00:34:33 +00001382 MDKindCache.NoObjCARCExceptionsMDKind, BBStates);
Dan Gohmana53a12c2011-12-12 19:42:25 +00001383
1384 // Use reverse-postorder on the reverse CFG for bottom-up.
John McCalld935e9c2011-06-15 23:37:01 +00001385 bool BottomUpNestingDetected = false;
Dan Gohmanc57b58c2011-08-18 21:27:42 +00001386 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
Dan Gohmana53a12c2011-12-12 19:42:25 +00001387 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
1388 I != E; ++I)
1389 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
John McCalld935e9c2011-06-15 23:37:01 +00001390
Dan Gohmana53a12c2011-12-12 19:42:25 +00001391 // Use reverse-postorder for top-down.
John McCalld935e9c2011-06-15 23:37:01 +00001392 bool TopDownNestingDetected = false;
Dan Gohmana53a12c2011-12-12 19:42:25 +00001393 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
1394 PostOrder.rbegin(), E = PostOrder.rend();
1395 I != E; ++I)
1396 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
John McCalld935e9c2011-06-15 23:37:01 +00001397
1398 return TopDownNestingDetected && BottomUpNestingDetected;
1399}
1400
Michael Gottesman97e3df02013-01-14 00:35:14 +00001401/// Move the calls in RetainsToMove and ReleasesToMove.
Michael Gottesman0be69202015-03-05 23:28:58 +00001402void ObjCARCOpt::MoveCalls(Value *Arg, RRInfo &RetainsToMove,
John McCalld935e9c2011-06-15 23:37:01 +00001403 RRInfo &ReleasesToMove,
Michael Gottesman0be69202015-03-05 23:28:58 +00001404 BlotMapVector<Value *, RRInfo> &Retains,
John McCalld935e9c2011-06-15 23:37:01 +00001405 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman6320f522011-07-22 22:29:21 +00001406 SmallVectorImpl<Instruction *> &DeadInsts,
Michael Gottesman79249972013-04-05 23:46:45 +00001407 Module *M) {
Chris Lattner229907c2011-07-18 04:54:35 +00001408 Type *ArgTy = Arg->getType();
Dan Gohman6320f522011-07-22 22:29:21 +00001409 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
Michael Gottesman79249972013-04-05 23:46:45 +00001410
Michael Gottesman89279f82013-04-05 18:10:41 +00001411 DEBUG(dbgs() << "== ObjCARCOpt::MoveCalls ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00001412
John McCalld935e9c2011-06-15 23:37:01 +00001413 // Insert the new retain and release calls.
Craig Topper46276792014-08-24 23:23:06 +00001414 for (Instruction *InsertPt : ReleasesToMove.ReverseInsertPts) {
John McCalld935e9c2011-06-15 23:37:01 +00001415 Value *MyArg = ArgTy == ParamTy ? Arg :
1416 new BitCastInst(Arg, ParamTy, "", InsertPt);
Michael Gottesman14acfac2013-07-06 01:39:23 +00001417 Constant *Decl = EP.get(ARCRuntimeEntryPoints::EPT_Retain);
1418 CallInst *Call = CallInst::Create(Decl, MyArg, "", InsertPt);
John McCalld935e9c2011-06-15 23:37:01 +00001419 Call->setDoesNotThrow();
Michael Gottesmanba648592013-03-28 23:08:44 +00001420 Call->setTailCall();
Michael Gottesman60f6b282013-03-29 05:13:07 +00001421
Michael Gottesmandf110ac2013-04-21 00:30:50 +00001422 DEBUG(dbgs() << "Inserting new Retain: " << *Call << "\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00001423 "At insertion point: " << *InsertPt << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001424 }
Craig Topper46276792014-08-24 23:23:06 +00001425 for (Instruction *InsertPt : RetainsToMove.ReverseInsertPts) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00001426 Value *MyArg = ArgTy == ParamTy ? Arg :
1427 new BitCastInst(Arg, ParamTy, "", InsertPt);
Michael Gottesman14acfac2013-07-06 01:39:23 +00001428 Constant *Decl = EP.get(ARCRuntimeEntryPoints::EPT_Release);
1429 CallInst *Call = CallInst::Create(Decl, MyArg, "", InsertPt);
Dan Gohman5c70fad2012-03-23 17:47:54 +00001430 // Attach a clang.imprecise_release metadata tag, if appropriate.
1431 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
Michael Gottesman41c01002015-03-06 00:34:33 +00001432 Call->setMetadata(MDKindCache.ImpreciseReleaseMDKind, M);
Dan Gohman5c70fad2012-03-23 17:47:54 +00001433 Call->setDoesNotThrow();
1434 if (ReleasesToMove.IsTailCallRelease)
1435 Call->setTailCall();
Michael Gottesmanc189a392013-01-09 19:23:24 +00001436
Michael Gottesman89279f82013-04-05 18:10:41 +00001437 DEBUG(dbgs() << "Inserting new Release: " << *Call << "\n"
1438 "At insertion point: " << *InsertPt << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001439 }
1440
1441 // Delete the original retain and release calls.
Craig Topper46276792014-08-24 23:23:06 +00001442 for (Instruction *OrigRetain : RetainsToMove.Calls) {
John McCalld935e9c2011-06-15 23:37:01 +00001443 Retains.blot(OrigRetain);
1444 DeadInsts.push_back(OrigRetain);
Michael Gottesman89279f82013-04-05 18:10:41 +00001445 DEBUG(dbgs() << "Deleting retain: " << *OrigRetain << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001446 }
Craig Topper46276792014-08-24 23:23:06 +00001447 for (Instruction *OrigRelease : ReleasesToMove.Calls) {
John McCalld935e9c2011-06-15 23:37:01 +00001448 Releases.erase(OrigRelease);
1449 DeadInsts.push_back(OrigRelease);
Michael Gottesman89279f82013-04-05 18:10:41 +00001450 DEBUG(dbgs() << "Deleting release: " << *OrigRelease << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001451 }
Michael Gottesman79249972013-04-05 23:46:45 +00001452
John McCalld935e9c2011-06-15 23:37:01 +00001453}
1454
Michael Gottesman0be69202015-03-05 23:28:58 +00001455bool ObjCARCOpt::ConnectTDBUTraversals(
1456 DenseMap<const BasicBlock *, BBState> &BBStates,
1457 BlotMapVector<Value *, RRInfo> &Retains,
1458 DenseMap<Value *, RRInfo> &Releases, Module *M,
1459 SmallVectorImpl<Instruction *> &NewRetains,
1460 SmallVectorImpl<Instruction *> &NewReleases,
1461 SmallVectorImpl<Instruction *> &DeadInsts, RRInfo &RetainsToMove,
1462 RRInfo &ReleasesToMove, Value *Arg, bool KnownSafe,
1463 bool &AnyPairsCompletelyEliminated) {
Michael Gottesman9de6f962013-01-22 21:49:00 +00001464 // If a pair happens in a region where it is known that the reference count
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001465 // is already incremented, we can similarly ignore possible decrements unless
1466 // we are dealing with a retainable object with multiple provenance sources.
Michael Gottesman9de6f962013-01-22 21:49:00 +00001467 bool KnownSafeTD = true, KnownSafeBU = true;
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001468 bool MultipleOwners = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001469 bool CFGHazardAfflicted = false;
Michael Gottesman9de6f962013-01-22 21:49:00 +00001470
1471 // Connect the dots between the top-down-collected RetainsToMove and
1472 // bottom-up-collected ReleasesToMove to form sets of related calls.
1473 // This is an iterative process so that we connect multiple releases
1474 // to multiple retains if needed.
1475 unsigned OldDelta = 0;
1476 unsigned NewDelta = 0;
1477 unsigned OldCount = 0;
1478 unsigned NewCount = 0;
1479 bool FirstRelease = true;
Michael Gottesman9de6f962013-01-22 21:49:00 +00001480 for (;;) {
1481 for (SmallVectorImpl<Instruction *>::const_iterator
1482 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
1483 Instruction *NewRetain = *NI;
Michael Gottesman6ff10c92015-03-06 02:10:03 +00001484 auto It = Retains.find(NewRetain);
Michael Gottesman9de6f962013-01-22 21:49:00 +00001485 assert(It != Retains.end());
1486 const RRInfo &NewRetainRRI = It->second;
1487 KnownSafeTD &= NewRetainRRI.KnownSafe;
Michael Gottesman5a91bbf2013-05-24 20:44:02 +00001488 MultipleOwners =
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001489 MultipleOwners || MultiOwnersSet.count(GetArgRCIdentityRoot(NewRetain));
Craig Topper46276792014-08-24 23:23:06 +00001490 for (Instruction *NewRetainRelease : NewRetainRRI.Calls) {
Michael Gottesman6ff10c92015-03-06 02:10:03 +00001491 auto Jt = Releases.find(NewRetainRelease);
Michael Gottesman9de6f962013-01-22 21:49:00 +00001492 if (Jt == Releases.end())
1493 return false;
1494 const RRInfo &NewRetainReleaseRRI = Jt->second;
Michael Gottesman24b2f6f2013-11-05 16:02:40 +00001495
1496 // If the release does not have a reference to the retain as well,
1497 // something happened which is unaccounted for. Do not do anything.
1498 //
1499 // This can happen if we catch an additive overflow during path count
1500 // merging.
1501 if (!NewRetainReleaseRRI.Calls.count(NewRetain))
1502 return false;
1503
David Blaikie70573dc2014-11-19 07:49:26 +00001504 if (ReleasesToMove.Calls.insert(NewRetainRelease).second) {
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001505
1506 // If we overflow when we compute the path count, don't remove/move
1507 // anything.
1508 const BBState &NRRBBState = BBStates[NewRetainRelease->getParent()];
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00001509 unsigned PathCount = BBState::OverflowOccurredValue;
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001510 if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
1511 return false;
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00001512 assert(PathCount != BBState::OverflowOccurredValue &&
1513 "PathCount at this point can not be "
1514 "OverflowOccurredValue.");
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001515 OldDelta -= PathCount;
Michael Gottesman9de6f962013-01-22 21:49:00 +00001516
1517 // Merge the ReleaseMetadata and IsTailCallRelease values.
1518 if (FirstRelease) {
1519 ReleasesToMove.ReleaseMetadata =
1520 NewRetainReleaseRRI.ReleaseMetadata;
1521 ReleasesToMove.IsTailCallRelease =
1522 NewRetainReleaseRRI.IsTailCallRelease;
1523 FirstRelease = false;
1524 } else {
1525 if (ReleasesToMove.ReleaseMetadata !=
1526 NewRetainReleaseRRI.ReleaseMetadata)
Craig Topperf40110f2014-04-25 05:29:35 +00001527 ReleasesToMove.ReleaseMetadata = nullptr;
Michael Gottesman9de6f962013-01-22 21:49:00 +00001528 if (ReleasesToMove.IsTailCallRelease !=
1529 NewRetainReleaseRRI.IsTailCallRelease)
1530 ReleasesToMove.IsTailCallRelease = false;
1531 }
1532
1533 // Collect the optimal insertion points.
1534 if (!KnownSafe)
Craig Topper46276792014-08-24 23:23:06 +00001535 for (Instruction *RIP : NewRetainReleaseRRI.ReverseInsertPts) {
David Blaikie70573dc2014-11-19 07:49:26 +00001536 if (ReleasesToMove.ReverseInsertPts.insert(RIP).second) {
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001537 // If we overflow when we compute the path count, don't
1538 // remove/move anything.
1539 const BBState &RIPBBState = BBStates[RIP->getParent()];
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00001540 PathCount = BBState::OverflowOccurredValue;
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001541 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
1542 return false;
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00001543 assert(PathCount != BBState::OverflowOccurredValue &&
1544 "PathCount at this point can not be "
1545 "OverflowOccurredValue.");
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001546 NewDelta -= PathCount;
1547 }
Michael Gottesman9de6f962013-01-22 21:49:00 +00001548 }
1549 NewReleases.push_back(NewRetainRelease);
1550 }
1551 }
1552 }
1553 NewRetains.clear();
1554 if (NewReleases.empty()) break;
1555
1556 // Back the other way.
1557 for (SmallVectorImpl<Instruction *>::const_iterator
1558 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
1559 Instruction *NewRelease = *NI;
Michael Gottesman6ff10c92015-03-06 02:10:03 +00001560 auto It = Releases.find(NewRelease);
Michael Gottesman9de6f962013-01-22 21:49:00 +00001561 assert(It != Releases.end());
1562 const RRInfo &NewReleaseRRI = It->second;
1563 KnownSafeBU &= NewReleaseRRI.KnownSafe;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001564 CFGHazardAfflicted |= NewReleaseRRI.CFGHazardAfflicted;
Craig Topper46276792014-08-24 23:23:06 +00001565 for (Instruction *NewReleaseRetain : NewReleaseRRI.Calls) {
Michael Gottesman6ff10c92015-03-06 02:10:03 +00001566 auto Jt = Retains.find(NewReleaseRetain);
Michael Gottesman9de6f962013-01-22 21:49:00 +00001567 if (Jt == Retains.end())
1568 return false;
1569 const RRInfo &NewReleaseRetainRRI = Jt->second;
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001570
Michael Gottesman24b2f6f2013-11-05 16:02:40 +00001571 // If the retain does not have a reference to the release as well,
1572 // something happened which is unaccounted for. Do not do anything.
1573 //
1574 // This can happen if we catch an additive overflow during path count
1575 // merging.
1576 if (!NewReleaseRetainRRI.Calls.count(NewRelease))
1577 return false;
1578
David Blaikie70573dc2014-11-19 07:49:26 +00001579 if (RetainsToMove.Calls.insert(NewReleaseRetain).second) {
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001580 // If we overflow when we compute the path count, don't remove/move
1581 // anything.
1582 const BBState &NRRBBState = BBStates[NewReleaseRetain->getParent()];
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00001583 unsigned PathCount = BBState::OverflowOccurredValue;
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001584 if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
1585 return false;
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00001586 assert(PathCount != BBState::OverflowOccurredValue &&
1587 "PathCount at this point can not be "
1588 "OverflowOccurredValue.");
Michael Gottesman9de6f962013-01-22 21:49:00 +00001589 OldDelta += PathCount;
1590 OldCount += PathCount;
1591
Michael Gottesman9de6f962013-01-22 21:49:00 +00001592 // Collect the optimal insertion points.
1593 if (!KnownSafe)
Craig Topper46276792014-08-24 23:23:06 +00001594 for (Instruction *RIP : NewReleaseRetainRRI.ReverseInsertPts) {
David Blaikie70573dc2014-11-19 07:49:26 +00001595 if (RetainsToMove.ReverseInsertPts.insert(RIP).second) {
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001596 // If we overflow when we compute the path count, don't
1597 // remove/move anything.
1598 const BBState &RIPBBState = BBStates[RIP->getParent()];
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00001599
1600 PathCount = BBState::OverflowOccurredValue;
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001601 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
1602 return false;
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00001603 assert(PathCount != BBState::OverflowOccurredValue &&
1604 "PathCount at this point can not be "
1605 "OverflowOccurredValue.");
Michael Gottesman9de6f962013-01-22 21:49:00 +00001606 NewDelta += PathCount;
1607 NewCount += PathCount;
1608 }
1609 }
1610 NewRetains.push_back(NewReleaseRetain);
1611 }
1612 }
1613 }
1614 NewReleases.clear();
1615 if (NewRetains.empty()) break;
1616 }
1617
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001618 // If the pointer is known incremented in 1 direction and we do not have
1619 // MultipleOwners, we can safely remove the retain/releases. Otherwise we need
1620 // to be known safe in both directions.
1621 bool UnconditionallySafe = (KnownSafeTD && KnownSafeBU) ||
1622 ((KnownSafeTD || KnownSafeBU) && !MultipleOwners);
1623 if (UnconditionallySafe) {
Michael Gottesman9de6f962013-01-22 21:49:00 +00001624 RetainsToMove.ReverseInsertPts.clear();
1625 ReleasesToMove.ReverseInsertPts.clear();
1626 NewCount = 0;
1627 } else {
1628 // Determine whether the new insertion points we computed preserve the
1629 // balance of retain and release calls through the program.
1630 // TODO: If the fully aggressive solution isn't valid, try to find a
1631 // less aggressive solution which is.
1632 if (NewDelta != 0)
1633 return false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001634
1635 // At this point, we are not going to remove any RR pairs, but we still are
1636 // able to move RR pairs. If one of our pointers is afflicted with
1637 // CFGHazards, we cannot perform such code motion so exit early.
1638 const bool WillPerformCodeMotion = RetainsToMove.ReverseInsertPts.size() ||
1639 ReleasesToMove.ReverseInsertPts.size();
1640 if (CFGHazardAfflicted && WillPerformCodeMotion)
1641 return false;
Michael Gottesman9de6f962013-01-22 21:49:00 +00001642 }
1643
1644 // Determine whether the original call points are balanced in the retain and
1645 // release calls through the program. If not, conservatively don't touch
1646 // them.
1647 // TODO: It's theoretically possible to do code motion in this case, as
1648 // long as the existing imbalances are maintained.
1649 if (OldDelta != 0)
1650 return false;
Michael Gottesman8005ad32013-04-29 06:16:55 +00001651
Michael Gottesman9de6f962013-01-22 21:49:00 +00001652 Changed = true;
1653 assert(OldCount != 0 && "Unreachable code?");
1654 NumRRs += OldCount - NewCount;
Michael Gottesman9de6f962013-01-22 21:49:00 +00001655 // Set to true if we completely removed any RR pairs.
Michael Gottesman8b5515f2013-01-22 21:53:43 +00001656 AnyPairsCompletelyEliminated = NewCount == 0;
Michael Gottesman9de6f962013-01-22 21:49:00 +00001657
1658 // We can move calls!
1659 return true;
1660}
1661
Michael Gottesman97e3df02013-01-14 00:35:14 +00001662/// Identify pairings between the retains and releases, and delete and/or move
1663/// them.
Michael Gottesman0be69202015-03-05 23:28:58 +00001664bool ObjCARCOpt::PerformCodePlacement(
1665 DenseMap<const BasicBlock *, BBState> &BBStates,
1666 BlotMapVector<Value *, RRInfo> &Retains,
1667 DenseMap<Value *, RRInfo> &Releases, Module *M) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001668 DEBUG(dbgs() << "\n== ObjCARCOpt::PerformCodePlacement ==\n");
1669
John McCalld935e9c2011-06-15 23:37:01 +00001670 bool AnyPairsCompletelyEliminated = false;
1671 RRInfo RetainsToMove;
1672 RRInfo ReleasesToMove;
1673 SmallVector<Instruction *, 4> NewRetains;
1674 SmallVector<Instruction *, 4> NewReleases;
1675 SmallVector<Instruction *, 8> DeadInsts;
1676
Dan Gohman670f9372012-04-13 18:57:48 +00001677 // Visit each retain.
Michael Gottesman0be69202015-03-05 23:28:58 +00001678 for (BlotMapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
1679 E = Retains.end();
1680 I != E; ++I) {
Dan Gohman2053a5d2011-09-29 22:25:23 +00001681 Value *V = I->first;
John McCalld935e9c2011-06-15 23:37:01 +00001682 if (!V) continue; // blotted
1683
1684 Instruction *Retain = cast<Instruction>(V);
Michael Gottesmanc189a392013-01-09 19:23:24 +00001685
Michael Gottesman89279f82013-04-05 18:10:41 +00001686 DEBUG(dbgs() << "Visiting: " << *Retain << "\n");
Michael Gottesmanc189a392013-01-09 19:23:24 +00001687
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001688 Value *Arg = GetArgRCIdentityRoot(Retain);
John McCalld935e9c2011-06-15 23:37:01 +00001689
Dan Gohman728db492012-01-13 00:39:07 +00001690 // If the object being released is in static or stack storage, we know it's
John McCalld935e9c2011-06-15 23:37:01 +00001691 // not being managed by ObjC reference counting, so we can delete pairs
1692 // regardless of what possible decrements or uses lie between them.
Dan Gohman728db492012-01-13 00:39:07 +00001693 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
Dan Gohman41375a32012-05-08 23:39:44 +00001694
Dan Gohman56e1cef2011-08-22 17:29:11 +00001695 // A constant pointer can't be pointing to an object on the heap. It may
1696 // be reference-counted, but it won't be deleted.
1697 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
1698 if (const GlobalVariable *GV =
1699 dyn_cast<GlobalVariable>(
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001700 GetRCIdentityRoot(LI->getPointerOperand())))
Dan Gohman56e1cef2011-08-22 17:29:11 +00001701 if (GV->isConstant())
1702 KnownSafe = true;
1703
John McCalld935e9c2011-06-15 23:37:01 +00001704 // Connect the dots between the top-down-collected RetainsToMove and
1705 // bottom-up-collected ReleasesToMove to form sets of related calls.
John McCalld935e9c2011-06-15 23:37:01 +00001706 NewRetains.push_back(Retain);
Michael Gottesman9de6f962013-01-22 21:49:00 +00001707 bool PerformMoveCalls =
1708 ConnectTDBUTraversals(BBStates, Retains, Releases, M, NewRetains,
1709 NewReleases, DeadInsts, RetainsToMove,
1710 ReleasesToMove, Arg, KnownSafe,
1711 AnyPairsCompletelyEliminated);
John McCalld935e9c2011-06-15 23:37:01 +00001712
Michael Gottesman9de6f962013-01-22 21:49:00 +00001713 if (PerformMoveCalls) {
1714 // Ok, everything checks out and we're all set. Let's move/delete some
1715 // code!
1716 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
1717 Retains, Releases, DeadInsts, M);
John McCalld935e9c2011-06-15 23:37:01 +00001718 }
1719
Michael Gottesman9de6f962013-01-22 21:49:00 +00001720 // Clean up state for next retain.
John McCalld935e9c2011-06-15 23:37:01 +00001721 NewReleases.clear();
1722 NewRetains.clear();
1723 RetainsToMove.clear();
1724 ReleasesToMove.clear();
1725 }
1726
1727 // Now that we're done moving everything, we can delete the newly dead
1728 // instructions, as we no longer need them as insert points.
1729 while (!DeadInsts.empty())
1730 EraseInstruction(DeadInsts.pop_back_val());
1731
1732 return AnyPairsCompletelyEliminated;
1733}
1734
Michael Gottesman97e3df02013-01-14 00:35:14 +00001735/// Weak pointer optimizations.
John McCalld935e9c2011-06-15 23:37:01 +00001736void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001737 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeWeakCalls ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00001738
John McCalld935e9c2011-06-15 23:37:01 +00001739 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
1740 // itself because it uses AliasAnalysis and we need to do provenance
1741 // queries instead.
1742 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
1743 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +00001744
Michael Gottesman89279f82013-04-05 18:10:41 +00001745 DEBUG(dbgs() << "Visiting: " << *Inst << "\n");
Michael Gottesman3f146e22013-01-01 16:05:48 +00001746
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001747 ARCInstKind Class = GetBasicARCInstKind(Inst);
1748 if (Class != ARCInstKind::LoadWeak &&
1749 Class != ARCInstKind::LoadWeakRetained)
John McCalld935e9c2011-06-15 23:37:01 +00001750 continue;
1751
1752 // Delete objc_loadWeak calls with no users.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001753 if (Class == ARCInstKind::LoadWeak && Inst->use_empty()) {
John McCalld935e9c2011-06-15 23:37:01 +00001754 Inst->eraseFromParent();
1755 continue;
1756 }
1757
1758 // TODO: For now, just look for an earlier available version of this value
1759 // within the same block. Theoretically, we could do memdep-style non-local
1760 // analysis too, but that would want caching. A better approach would be to
1761 // use the technique that EarlyCSE uses.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001762 inst_iterator Current = std::prev(I);
John McCalld935e9c2011-06-15 23:37:01 +00001763 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
1764 for (BasicBlock::iterator B = CurrentBB->begin(),
1765 J = Current.getInstructionIterator();
1766 J != B; --J) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001767 Instruction *EarlierInst = &*std::prev(J);
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001768 ARCInstKind EarlierClass = GetARCInstKind(EarlierInst);
John McCalld935e9c2011-06-15 23:37:01 +00001769 switch (EarlierClass) {
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001770 case ARCInstKind::LoadWeak:
1771 case ARCInstKind::LoadWeakRetained: {
John McCalld935e9c2011-06-15 23:37:01 +00001772 // If this is loading from the same pointer, replace this load's value
1773 // with that one.
1774 CallInst *Call = cast<CallInst>(Inst);
1775 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
1776 Value *Arg = Call->getArgOperand(0);
1777 Value *EarlierArg = EarlierCall->getArgOperand(0);
1778 switch (PA.getAA()->alias(Arg, EarlierArg)) {
1779 case AliasAnalysis::MustAlias:
1780 Changed = true;
1781 // If the load has a builtin retain, insert a plain retain for it.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001782 if (Class == ARCInstKind::LoadWeakRetained) {
Michael Gottesman14acfac2013-07-06 01:39:23 +00001783 Constant *Decl = EP.get(ARCRuntimeEntryPoints::EPT_Retain);
1784 CallInst *CI = CallInst::Create(Decl, EarlierCall, "", Call);
John McCalld935e9c2011-06-15 23:37:01 +00001785 CI->setTailCall();
1786 }
1787 // Zap the fully redundant load.
1788 Call->replaceAllUsesWith(EarlierCall);
1789 Call->eraseFromParent();
1790 goto clobbered;
1791 case AliasAnalysis::MayAlias:
1792 case AliasAnalysis::PartialAlias:
1793 goto clobbered;
1794 case AliasAnalysis::NoAlias:
1795 break;
1796 }
1797 break;
1798 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001799 case ARCInstKind::StoreWeak:
1800 case ARCInstKind::InitWeak: {
John McCalld935e9c2011-06-15 23:37:01 +00001801 // If this is storing to the same pointer and has the same size etc.
1802 // replace this load's value with the stored value.
1803 CallInst *Call = cast<CallInst>(Inst);
1804 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
1805 Value *Arg = Call->getArgOperand(0);
1806 Value *EarlierArg = EarlierCall->getArgOperand(0);
1807 switch (PA.getAA()->alias(Arg, EarlierArg)) {
1808 case AliasAnalysis::MustAlias:
1809 Changed = true;
1810 // If the load has a builtin retain, insert a plain retain for it.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001811 if (Class == ARCInstKind::LoadWeakRetained) {
Michael Gottesman14acfac2013-07-06 01:39:23 +00001812 Constant *Decl = EP.get(ARCRuntimeEntryPoints::EPT_Retain);
1813 CallInst *CI = CallInst::Create(Decl, EarlierCall, "", Call);
John McCalld935e9c2011-06-15 23:37:01 +00001814 CI->setTailCall();
1815 }
1816 // Zap the fully redundant load.
1817 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
1818 Call->eraseFromParent();
1819 goto clobbered;
1820 case AliasAnalysis::MayAlias:
1821 case AliasAnalysis::PartialAlias:
1822 goto clobbered;
1823 case AliasAnalysis::NoAlias:
1824 break;
1825 }
1826 break;
1827 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001828 case ARCInstKind::MoveWeak:
1829 case ARCInstKind::CopyWeak:
John McCalld935e9c2011-06-15 23:37:01 +00001830 // TOOD: Grab the copied value.
1831 goto clobbered;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001832 case ARCInstKind::AutoreleasepoolPush:
1833 case ARCInstKind::None:
1834 case ARCInstKind::IntrinsicUser:
1835 case ARCInstKind::User:
John McCalld935e9c2011-06-15 23:37:01 +00001836 // Weak pointers are only modified through the weak entry points
1837 // (and arbitrary calls, which could call the weak entry points).
1838 break;
1839 default:
1840 // Anything else could modify the weak pointer.
1841 goto clobbered;
1842 }
1843 }
1844 clobbered:;
1845 }
1846
1847 // Then, for each destroyWeak with an alloca operand, check to see if
1848 // the alloca and all its users can be zapped.
1849 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
1850 Instruction *Inst = &*I++;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001851 ARCInstKind Class = GetBasicARCInstKind(Inst);
1852 if (Class != ARCInstKind::DestroyWeak)
John McCalld935e9c2011-06-15 23:37:01 +00001853 continue;
1854
1855 CallInst *Call = cast<CallInst>(Inst);
1856 Value *Arg = Call->getArgOperand(0);
1857 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001858 for (User *U : Alloca->users()) {
1859 const Instruction *UserInst = cast<Instruction>(U);
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001860 switch (GetBasicARCInstKind(UserInst)) {
1861 case ARCInstKind::InitWeak:
1862 case ARCInstKind::StoreWeak:
1863 case ARCInstKind::DestroyWeak:
John McCalld935e9c2011-06-15 23:37:01 +00001864 continue;
1865 default:
1866 goto done;
1867 }
1868 }
1869 Changed = true;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001870 for (auto UI = Alloca->user_begin(), UE = Alloca->user_end(); UI != UE;) {
John McCalld935e9c2011-06-15 23:37:01 +00001871 CallInst *UserInst = cast<CallInst>(*UI++);
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001872 switch (GetBasicARCInstKind(UserInst)) {
1873 case ARCInstKind::InitWeak:
1874 case ARCInstKind::StoreWeak:
Dan Gohman14862c32012-05-18 22:17:29 +00001875 // These functions return their second argument.
1876 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
1877 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001878 case ARCInstKind::DestroyWeak:
Dan Gohman14862c32012-05-18 22:17:29 +00001879 // No return value.
1880 break;
1881 default:
Dan Gohman9c97eea02012-05-21 17:41:28 +00001882 llvm_unreachable("alloca really is used!");
Dan Gohman14862c32012-05-18 22:17:29 +00001883 }
John McCalld935e9c2011-06-15 23:37:01 +00001884 UserInst->eraseFromParent();
1885 }
1886 Alloca->eraseFromParent();
1887 done:;
1888 }
1889 }
1890}
1891
Michael Gottesman97e3df02013-01-14 00:35:14 +00001892/// Identify program paths which execute sequences of retains and releases which
1893/// can be eliminated.
John McCalld935e9c2011-06-15 23:37:01 +00001894bool ObjCARCOpt::OptimizeSequences(Function &F) {
Michael Gottesman740db972013-05-23 02:35:21 +00001895 // Releases, Retains - These are used to store the results of the main flow
1896 // analysis. These use Value* as the key instead of Instruction* so that the
1897 // map stays valid when we get around to rewriting code and calls get
1898 // replaced by arguments.
John McCalld935e9c2011-06-15 23:37:01 +00001899 DenseMap<Value *, RRInfo> Releases;
Michael Gottesman0be69202015-03-05 23:28:58 +00001900 BlotMapVector<Value *, RRInfo> Retains;
John McCalld935e9c2011-06-15 23:37:01 +00001901
Michael Gottesman740db972013-05-23 02:35:21 +00001902 // This is used during the traversal of the function to track the
1903 // states for each identified object at each block.
John McCalld935e9c2011-06-15 23:37:01 +00001904 DenseMap<const BasicBlock *, BBState> BBStates;
1905
1906 // Analyze the CFG of the function, and all instructions.
1907 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
1908
1909 // Transform.
Michael Gottesman5a91bbf2013-05-24 20:44:02 +00001910 bool AnyPairsCompletelyEliminated = PerformCodePlacement(BBStates, Retains,
1911 Releases,
1912 F.getParent());
1913
1914 // Cleanup.
1915 MultiOwnersSet.clear();
1916
1917 return AnyPairsCompletelyEliminated && NestingDetected;
John McCalld935e9c2011-06-15 23:37:01 +00001918}
1919
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00001920/// Check if there is a dependent call earlier that does not have anything in
1921/// between the Retain and the call that can affect the reference count of their
1922/// shared pointer argument. Note that Retain need not be in BB.
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00001923static bool
1924HasSafePathToPredecessorCall(const Value *Arg, Instruction *Retain,
Craig Topper71b7b682014-08-21 05:55:13 +00001925 SmallPtrSetImpl<Instruction *> &DepInsts,
1926 SmallPtrSetImpl<const BasicBlock *> &Visited,
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00001927 ProvenanceAnalysis &PA) {
1928 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
1929 DepInsts, Visited, PA);
1930 if (DepInsts.size() != 1)
1931 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00001932
Michael Gottesmana9fc0162015-03-05 23:29:06 +00001933 auto *Call = dyn_cast_or_null<CallInst>(*DepInsts.begin());
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00001934
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00001935 // Check that the pointer is the return value of the call.
1936 if (!Call || Arg != Call)
1937 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00001938
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00001939 // Check that the call is a regular call.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001940 ARCInstKind Class = GetBasicARCInstKind(Call);
1941 if (Class != ARCInstKind::CallOrUser && Class != ARCInstKind::Call)
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00001942 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00001943
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00001944 return true;
1945}
1946
Michael Gottesman6908db12013-04-03 23:16:05 +00001947/// Find a dependent retain that precedes the given autorelease for which there
1948/// is nothing in between the two instructions that can affect the ref count of
1949/// Arg.
1950static CallInst *
1951FindPredecessorRetainWithSafePath(const Value *Arg, BasicBlock *BB,
1952 Instruction *Autorelease,
Craig Topper71b7b682014-08-21 05:55:13 +00001953 SmallPtrSetImpl<Instruction *> &DepInsts,
1954 SmallPtrSetImpl<const BasicBlock *> &Visited,
Michael Gottesman6908db12013-04-03 23:16:05 +00001955 ProvenanceAnalysis &PA) {
1956 FindDependencies(CanChangeRetainCount, Arg,
1957 BB, Autorelease, DepInsts, Visited, PA);
1958 if (DepInsts.size() != 1)
Craig Topperf40110f2014-04-25 05:29:35 +00001959 return nullptr;
Michael Gottesman79249972013-04-05 23:46:45 +00001960
Michael Gottesmana9fc0162015-03-05 23:29:06 +00001961 auto *Retain = dyn_cast_or_null<CallInst>(*DepInsts.begin());
Michael Gottesman79249972013-04-05 23:46:45 +00001962
Michael Gottesman6908db12013-04-03 23:16:05 +00001963 // Check that we found a retain with the same argument.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001964 if (!Retain || !IsRetain(GetBasicARCInstKind(Retain)) ||
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001965 GetArgRCIdentityRoot(Retain) != Arg) {
Craig Topperf40110f2014-04-25 05:29:35 +00001966 return nullptr;
Michael Gottesman6908db12013-04-03 23:16:05 +00001967 }
Michael Gottesman79249972013-04-05 23:46:45 +00001968
Michael Gottesman6908db12013-04-03 23:16:05 +00001969 return Retain;
1970}
1971
Michael Gottesman21a4ed32013-04-03 23:39:14 +00001972/// Look for an ``autorelease'' instruction dependent on Arg such that there are
1973/// no instructions dependent on Arg that need a positive ref count in between
1974/// the autorelease and the ret.
1975static CallInst *
1976FindPredecessorAutoreleaseWithSafePath(const Value *Arg, BasicBlock *BB,
1977 ReturnInst *Ret,
Craig Topper71b7b682014-08-21 05:55:13 +00001978 SmallPtrSetImpl<Instruction *> &DepInsts,
1979 SmallPtrSetImpl<const BasicBlock *> &V,
Michael Gottesman21a4ed32013-04-03 23:39:14 +00001980 ProvenanceAnalysis &PA) {
1981 FindDependencies(NeedsPositiveRetainCount, Arg,
1982 BB, Ret, DepInsts, V, PA);
1983 if (DepInsts.size() != 1)
Craig Topperf40110f2014-04-25 05:29:35 +00001984 return nullptr;
Michael Gottesman79249972013-04-05 23:46:45 +00001985
Michael Gottesmana9fc0162015-03-05 23:29:06 +00001986 auto *Autorelease = dyn_cast_or_null<CallInst>(*DepInsts.begin());
Michael Gottesman21a4ed32013-04-03 23:39:14 +00001987 if (!Autorelease)
Craig Topperf40110f2014-04-25 05:29:35 +00001988 return nullptr;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001989 ARCInstKind AutoreleaseClass = GetBasicARCInstKind(Autorelease);
Michael Gottesman21a4ed32013-04-03 23:39:14 +00001990 if (!IsAutorelease(AutoreleaseClass))
Craig Topperf40110f2014-04-25 05:29:35 +00001991 return nullptr;
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001992 if (GetArgRCIdentityRoot(Autorelease) != Arg)
Craig Topperf40110f2014-04-25 05:29:35 +00001993 return nullptr;
Michael Gottesman79249972013-04-05 23:46:45 +00001994
Michael Gottesman21a4ed32013-04-03 23:39:14 +00001995 return Autorelease;
1996}
1997
Michael Gottesman97e3df02013-01-14 00:35:14 +00001998/// Look for this pattern:
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00001999/// \code
John McCalld935e9c2011-06-15 23:37:01 +00002000/// %call = call i8* @something(...)
2001/// %2 = call i8* @objc_retain(i8* %call)
2002/// %3 = call i8* @objc_autorelease(i8* %2)
2003/// ret i8* %3
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00002004/// \endcode
John McCalld935e9c2011-06-15 23:37:01 +00002005/// And delete the retain and autorelease.
John McCalld935e9c2011-06-15 23:37:01 +00002006void ObjCARCOpt::OptimizeReturns(Function &F) {
2007 if (!F.getReturnType()->isPointerTy())
2008 return;
Michael Gottesman79249972013-04-05 23:46:45 +00002009
Michael Gottesman89279f82013-04-05 18:10:41 +00002010 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeReturns ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00002011
John McCalld935e9c2011-06-15 23:37:01 +00002012 SmallPtrSet<Instruction *, 4> DependingInstructions;
2013 SmallPtrSet<const BasicBlock *, 4> Visited;
2014 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
2015 BasicBlock *BB = FI;
2016 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
Michael Gottesman3f146e22013-01-01 16:05:48 +00002017
Michael Gottesman89279f82013-04-05 18:10:41 +00002018 DEBUG(dbgs() << "Visiting: " << *Ret << "\n");
Michael Gottesman3f146e22013-01-01 16:05:48 +00002019
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002020 if (!Ret)
2021 continue;
Michael Gottesman79249972013-04-05 23:46:45 +00002022
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00002023 const Value *Arg = GetRCIdentityRoot(Ret->getOperand(0));
Michael Gottesman79249972013-04-05 23:46:45 +00002024
Michael Gottesmancdb7c152013-04-21 00:25:04 +00002025 // Look for an ``autorelease'' instruction that is a predecessor of Ret and
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002026 // dependent on Arg such that there are no instructions dependent on Arg
2027 // that need a positive ref count in between the autorelease and Ret.
2028 CallInst *Autorelease =
2029 FindPredecessorAutoreleaseWithSafePath(Arg, BB, Ret,
2030 DependingInstructions, Visited,
2031 PA);
John McCalld935e9c2011-06-15 23:37:01 +00002032 DependingInstructions.clear();
2033 Visited.clear();
Michael Gottesmanfb9ece92013-04-21 00:25:01 +00002034
2035 if (!Autorelease)
2036 continue;
2037
2038 CallInst *Retain =
2039 FindPredecessorRetainWithSafePath(Arg, BB, Autorelease,
2040 DependingInstructions, Visited, PA);
2041 DependingInstructions.clear();
2042 Visited.clear();
2043
2044 if (!Retain)
2045 continue;
2046
2047 // Check that there is nothing that can affect the reference count
2048 // between the retain and the call. Note that Retain need not be in BB.
2049 bool HasSafePathToCall = HasSafePathToPredecessorCall(Arg, Retain,
2050 DependingInstructions,
2051 Visited, PA);
2052 DependingInstructions.clear();
2053 Visited.clear();
2054
2055 if (!HasSafePathToCall)
2056 continue;
2057
2058 // If so, we can zap the retain and autorelease.
2059 Changed = true;
2060 ++NumRets;
2061 DEBUG(dbgs() << "Erasing: " << *Retain << "\nErasing: "
2062 << *Autorelease << "\n");
2063 EraseInstruction(Retain);
2064 EraseInstruction(Autorelease);
John McCalld935e9c2011-06-15 23:37:01 +00002065 }
2066}
2067
Michael Gottesman9c118152013-04-29 06:16:57 +00002068#ifndef NDEBUG
2069void
2070ObjCARCOpt::GatherStatistics(Function &F, bool AfterOptimization) {
2071 llvm::Statistic &NumRetains =
2072 AfterOptimization? NumRetainsAfterOpt : NumRetainsBeforeOpt;
2073 llvm::Statistic &NumReleases =
2074 AfterOptimization? NumReleasesAfterOpt : NumReleasesBeforeOpt;
2075
2076 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2077 Instruction *Inst = &*I++;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002078 switch (GetBasicARCInstKind(Inst)) {
Michael Gottesman9c118152013-04-29 06:16:57 +00002079 default:
2080 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002081 case ARCInstKind::Retain:
Michael Gottesman9c118152013-04-29 06:16:57 +00002082 ++NumRetains;
2083 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002084 case ARCInstKind::Release:
Michael Gottesman9c118152013-04-29 06:16:57 +00002085 ++NumReleases;
2086 break;
2087 }
2088 }
2089}
2090#endif
2091
John McCalld935e9c2011-06-15 23:37:01 +00002092bool ObjCARCOpt::doInitialization(Module &M) {
2093 if (!EnableARCOpts)
2094 return false;
2095
Dan Gohman670f9372012-04-13 18:57:48 +00002096 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanceaac7c2011-06-20 23:20:43 +00002097 Run = ModuleHasARC(M);
2098 if (!Run)
2099 return false;
2100
John McCalld935e9c2011-06-15 23:37:01 +00002101 // Identify the imprecise release metadata kind.
Michael Gottesman41c01002015-03-06 00:34:33 +00002102 MDKindCache.ImpreciseReleaseMDKind =
2103 M.getContext().getMDKindID("clang.imprecise_release");
2104 MDKindCache.CopyOnEscapeMDKind =
2105 M.getContext().getMDKindID("clang.arc.copy_on_escape");
2106 MDKindCache.NoObjCARCExceptionsMDKind =
2107 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
John McCalld935e9c2011-06-15 23:37:01 +00002108
John McCalld935e9c2011-06-15 23:37:01 +00002109 // Intuitively, objc_retain and others are nocapture, however in practice
2110 // they are not, because they return their argument value. And objc_release
Dan Gohmandae33492012-04-27 18:56:31 +00002111 // calls finalizers which can have arbitrary side effects.
John McCalld935e9c2011-06-15 23:37:01 +00002112
Michael Gottesman14acfac2013-07-06 01:39:23 +00002113 // Initialize our runtime entry point cache.
2114 EP.Initialize(&M);
John McCalld935e9c2011-06-15 23:37:01 +00002115
2116 return false;
2117}
2118
2119bool ObjCARCOpt::runOnFunction(Function &F) {
2120 if (!EnableARCOpts)
2121 return false;
2122
Dan Gohmanceaac7c2011-06-20 23:20:43 +00002123 // If nothing in the Module uses ARC, don't do anything.
2124 if (!Run)
2125 return false;
2126
John McCalld935e9c2011-06-15 23:37:01 +00002127 Changed = false;
2128
Michael Gottesman89279f82013-04-05 18:10:41 +00002129 DEBUG(dbgs() << "<<< ObjCARCOpt: Visiting Function: " << F.getName() << " >>>"
2130 "\n");
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00002131
John McCalld935e9c2011-06-15 23:37:01 +00002132 PA.setAA(&getAnalysis<AliasAnalysis>());
2133
Michael Gottesman9fc50b82013-05-13 18:29:07 +00002134#ifndef NDEBUG
2135 if (AreStatisticsEnabled()) {
2136 GatherStatistics(F, false);
2137 }
2138#endif
2139
John McCalld935e9c2011-06-15 23:37:01 +00002140 // This pass performs several distinct transformations. As a compile-time aid
2141 // when compiling code that isn't ObjC, skip these if the relevant ObjC
2142 // library functions aren't declared.
2143
Michael Gottesmancd5b0272013-04-24 22:18:15 +00002144 // Preliminary optimizations. This also computes UsedInThisFunction.
John McCalld935e9c2011-06-15 23:37:01 +00002145 OptimizeIndividualCalls(F);
2146
2147 // Optimizations for weak pointers.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002148 if (UsedInThisFunction & ((1 << unsigned(ARCInstKind::LoadWeak)) |
2149 (1 << unsigned(ARCInstKind::LoadWeakRetained)) |
2150 (1 << unsigned(ARCInstKind::StoreWeak)) |
2151 (1 << unsigned(ARCInstKind::InitWeak)) |
2152 (1 << unsigned(ARCInstKind::CopyWeak)) |
2153 (1 << unsigned(ARCInstKind::MoveWeak)) |
2154 (1 << unsigned(ARCInstKind::DestroyWeak))))
John McCalld935e9c2011-06-15 23:37:01 +00002155 OptimizeWeakCalls(F);
2156
2157 // Optimizations for retain+release pairs.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002158 if (UsedInThisFunction & ((1 << unsigned(ARCInstKind::Retain)) |
2159 (1 << unsigned(ARCInstKind::RetainRV)) |
2160 (1 << unsigned(ARCInstKind::RetainBlock))))
2161 if (UsedInThisFunction & (1 << unsigned(ARCInstKind::Release)))
John McCalld935e9c2011-06-15 23:37:01 +00002162 // Run OptimizeSequences until it either stops making changes or
2163 // no retain+release pair nesting is detected.
2164 while (OptimizeSequences(F)) {}
2165
2166 // Optimizations if objc_autorelease is used.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002167 if (UsedInThisFunction & ((1 << unsigned(ARCInstKind::Autorelease)) |
2168 (1 << unsigned(ARCInstKind::AutoreleaseRV))))
John McCalld935e9c2011-06-15 23:37:01 +00002169 OptimizeReturns(F);
2170
Michael Gottesman9c118152013-04-29 06:16:57 +00002171 // Gather statistics after optimization.
2172#ifndef NDEBUG
2173 if (AreStatisticsEnabled()) {
2174 GatherStatistics(F, true);
2175 }
2176#endif
2177
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00002178 DEBUG(dbgs() << "\n");
2179
John McCalld935e9c2011-06-15 23:37:01 +00002180 return Changed;
2181}
2182
2183void ObjCARCOpt::releaseMemory() {
2184 PA.clear();
2185}
2186
Michael Gottesman97e3df02013-01-14 00:35:14 +00002187/// @}
2188///