blob: e1ff6a12304dc57283fc51a48b663e803ca6def1 [file] [log] [blame]
Michael Gottesman79d8d812013-01-28 01:35:51 +00001//===- ObjCARCOpts.cpp - ObjC ARC Optimization ----------------------------===//
John McCalld935e9c2011-06-15 23:37:01 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Michael Gottesman97e3df02013-01-14 00:35:14 +00009/// \file
10/// This file defines ObjC ARC optimizations. ARC stands for Automatic
11/// Reference Counting and is a system for managing reference counts for objects
12/// in Objective C.
13///
14/// The optimizations performed include elimination of redundant, partially
15/// redundant, and inconsequential reference count operations, elimination of
Michael Gottesman697d8b92013-02-07 04:12:57 +000016/// redundant weak pointer operations, and numerous minor simplifications.
Michael Gottesman97e3df02013-01-14 00:35:14 +000017///
18/// WARNING: This file knows about certain library functions. It recognizes them
19/// by name, and hardwires knowledge of their semantics.
20///
21/// WARNING: This file knows about how certain Objective-C library functions are
22/// used. Naive LLVM IR transformations which would otherwise be
23/// behavior-preserving may break these assumptions.
24///
John McCalld935e9c2011-06-15 23:37:01 +000025//===----------------------------------------------------------------------===//
26
Michael Gottesman08904e32013-01-28 03:28:38 +000027#include "ObjCARC.h"
Michael Gottesman14acfac2013-07-06 01:39:23 +000028#include "ARCRuntimeEntryPoints.h"
Michael Gottesman278266f2013-01-29 04:20:52 +000029#include "DependencyAnalysis.h"
Michael Gottesman294e7da2013-01-28 05:51:54 +000030#include "ObjCARCAliasAnalysis.h"
Michael Gottesman778138e2013-01-29 03:03:03 +000031#include "ProvenanceAnalysis.h"
Michael Gottesman0be69202015-03-05 23:28:58 +000032#include "BlotMapVector.h"
Michael Gottesman68b91db2015-03-05 23:29:03 +000033#include "PtrState.h"
John McCalld935e9c2011-06-15 23:37:01 +000034#include "llvm/ADT/DenseMap.h"
Michael Gottesman5a91bbf2013-05-24 20:44:02 +000035#include "llvm/ADT/DenseSet.h"
Michael Gottesmanfa0939f2013-01-28 04:12:07 +000036#include "llvm/ADT/STLExtras.h"
Michael Gottesman778138e2013-01-29 03:03:03 +000037#include "llvm/ADT/SmallPtrSet.h"
Michael Gottesman278266f2013-01-29 04:20:52 +000038#include "llvm/ADT/Statistic.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000039#include "llvm/IR/CFG.h"
Michael Gottesmancd4de0f2013-03-26 00:42:09 +000040#include "llvm/IR/IRBuilder.h"
Michael Gottesman278266f2013-01-29 04:20:52 +000041#include "llvm/IR/LLVMContext.h"
Michael Gottesman13a5f1a2013-01-29 04:51:59 +000042#include "llvm/Support/Debug.h"
Timur Iskhodzhanov5d7ff002013-01-29 09:09:27 +000043#include "llvm/Support/raw_ostream.h"
Michael Gottesmanfa0939f2013-01-28 04:12:07 +000044
John McCalld935e9c2011-06-15 23:37:01 +000045using namespace llvm;
Michael Gottesman08904e32013-01-28 03:28:38 +000046using namespace llvm::objcarc;
John McCalld935e9c2011-06-15 23:37:01 +000047
Chandler Carruth964daaa2014-04-22 02:55:47 +000048#define DEBUG_TYPE "objc-arc-opts"
49
Michael Gottesman97e3df02013-01-14 00:35:14 +000050/// \defgroup ARCUtilities Utility declarations/definitions specific to ARC.
51/// @{
John McCalld935e9c2011-06-15 23:37:01 +000052
Michael Gottesmane5ad66f2015-02-19 00:42:38 +000053/// \brief This is similar to GetRCIdentityRoot but it stops as soon
Michael Gottesman97e3df02013-01-14 00:35:14 +000054/// as it finds a value with multiple uses.
John McCalld935e9c2011-06-15 23:37:01 +000055static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
56 if (Arg->hasOneUse()) {
57 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
58 return FindSingleUseIdentifiedObject(BC->getOperand(0));
59 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
60 if (GEP->hasAllZeroIndices())
61 return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
Michael Gottesman6f729fa2015-02-19 19:51:32 +000062 if (IsForwarding(GetBasicARCInstKind(Arg)))
John McCalld935e9c2011-06-15 23:37:01 +000063 return FindSingleUseIdentifiedObject(
64 cast<CallInst>(Arg)->getArgOperand(0));
65 if (!IsObjCIdentifiedObject(Arg))
Craig Topperf40110f2014-04-25 05:29:35 +000066 return nullptr;
John McCalld935e9c2011-06-15 23:37:01 +000067 return Arg;
68 }
69
Dan Gohman41375a32012-05-08 23:39:44 +000070 // If we found an identifiable object but it has multiple uses, but they are
71 // trivial uses, we can still consider this to be a single-use value.
John McCalld935e9c2011-06-15 23:37:01 +000072 if (IsObjCIdentifiedObject(Arg)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +000073 for (const User *U : Arg->users())
Michael Gottesmane5ad66f2015-02-19 00:42:38 +000074 if (!U->use_empty() || GetRCIdentityRoot(U) != Arg)
Craig Topperf40110f2014-04-25 05:29:35 +000075 return nullptr;
John McCalld935e9c2011-06-15 23:37:01 +000076
77 return Arg;
78 }
79
Craig Topperf40110f2014-04-25 05:29:35 +000080 return nullptr;
John McCalld935e9c2011-06-15 23:37:01 +000081}
82
Michael Gottesmana76143ee2013-05-13 23:49:42 +000083/// This is a wrapper around getUnderlyingObjCPtr along the lines of
84/// GetUnderlyingObjects except that it returns early when it sees the first
85/// alloca.
86static inline bool AreAnyUnderlyingObjectsAnAlloca(const Value *V) {
87 SmallPtrSet<const Value *, 4> Visited;
88 SmallVector<const Value *, 4> Worklist;
89 Worklist.push_back(V);
90 do {
91 const Value *P = Worklist.pop_back_val();
92 P = GetUnderlyingObjCPtr(P);
Michael Gottesman0c8b5622013-05-14 06:40:10 +000093
Michael Gottesmana76143ee2013-05-13 23:49:42 +000094 if (isa<AllocaInst>(P))
95 return true;
Michael Gottesman0c8b5622013-05-14 06:40:10 +000096
David Blaikie70573dc2014-11-19 07:49:26 +000097 if (!Visited.insert(P).second)
Michael Gottesmana76143ee2013-05-13 23:49:42 +000098 continue;
Michael Gottesman0c8b5622013-05-14 06:40:10 +000099
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000100 if (const SelectInst *SI = dyn_cast<const SelectInst>(P)) {
101 Worklist.push_back(SI->getTrueValue());
102 Worklist.push_back(SI->getFalseValue());
103 continue;
104 }
Michael Gottesman0c8b5622013-05-14 06:40:10 +0000105
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000106 if (const PHINode *PN = dyn_cast<const PHINode>(P)) {
107 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
108 Worklist.push_back(PN->getIncomingValue(i));
109 continue;
110 }
111 } while (!Worklist.empty());
112
113 return false;
114}
115
116
Michael Gottesman97e3df02013-01-14 00:35:14 +0000117/// @}
118///
Michael Gottesman97e3df02013-01-14 00:35:14 +0000119/// \defgroup ARCOpt ARC Optimization.
120/// @{
John McCalld935e9c2011-06-15 23:37:01 +0000121
122// TODO: On code like this:
123//
124// objc_retain(%x)
125// stuff_that_cannot_release()
126// objc_autorelease(%x)
127// stuff_that_cannot_release()
128// objc_retain(%x)
129// stuff_that_cannot_release()
130// objc_autorelease(%x)
131//
132// The second retain and autorelease can be deleted.
133
134// TODO: It should be possible to delete
135// objc_autoreleasePoolPush and objc_autoreleasePoolPop
136// pairs if nothing is actually autoreleased between them. Also, autorelease
137// calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
138// after inlining) can be turned into plain release calls.
139
140// TODO: Critical-edge splitting. If the optimial insertion point is
141// a critical edge, the current algorithm has to fail, because it doesn't
142// know how to split edges. It should be possible to make the optimizer
143// think in terms of edges, rather than blocks, and then split critical
144// edges on demand.
145
146// TODO: OptimizeSequences could generalized to be Interprocedural.
147
148// TODO: Recognize that a bunch of other objc runtime calls have
149// non-escaping arguments and non-releasing arguments, and may be
150// non-autoreleasing.
151
152// TODO: Sink autorelease calls as far as possible. Unfortunately we
153// usually can't sink them past other calls, which would be the main
154// case where it would be useful.
155
Dan Gohmanb3894012011-08-19 00:26:36 +0000156// TODO: The pointer returned from objc_loadWeakRetained is retained.
157
158// TODO: Delete release+retain pairs (rare).
Dan Gohmanceaac7c2011-06-20 23:20:43 +0000159
John McCalld935e9c2011-06-15 23:37:01 +0000160STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
161STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
162STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
163STATISTIC(NumRets, "Number of return value forwarding "
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000164 "retain+autoreleases eliminated");
John McCalld935e9c2011-06-15 23:37:01 +0000165STATISTIC(NumRRs, "Number of retain+release paths eliminated");
166STATISTIC(NumPeeps, "Number of calls peephole-optimized");
Matt Beaumont-Gaye55d9492013-05-13 21:10:49 +0000167#ifndef NDEBUG
Michael Gottesman9c118152013-04-29 06:16:57 +0000168STATISTIC(NumRetainsBeforeOpt,
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000169 "Number of retains before optimization");
Michael Gottesman9c118152013-04-29 06:16:57 +0000170STATISTIC(NumReleasesBeforeOpt,
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000171 "Number of releases before optimization");
Michael Gottesman9c118152013-04-29 06:16:57 +0000172STATISTIC(NumRetainsAfterOpt,
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000173 "Number of retains after optimization");
Michael Gottesman9c118152013-04-29 06:16:57 +0000174STATISTIC(NumReleasesAfterOpt,
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000175 "Number of releases after optimization");
Michael Gottesman03cf3c82013-04-29 07:29:08 +0000176#endif
John McCalld935e9c2011-06-15 23:37:01 +0000177
178namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000179 /// \brief Per-BasicBlock state.
John McCalld935e9c2011-06-15 23:37:01 +0000180 class BBState {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000181 /// The number of unique control paths from the entry which can reach this
182 /// block.
John McCalld935e9c2011-06-15 23:37:01 +0000183 unsigned TopDownPathCount;
184
Michael Gottesman97e3df02013-01-14 00:35:14 +0000185 /// The number of unique control paths to exits from this block.
John McCalld935e9c2011-06-15 23:37:01 +0000186 unsigned BottomUpPathCount;
187
Michael Gottesman97e3df02013-01-14 00:35:14 +0000188 /// A type for PerPtrTopDown and PerPtrBottomUp.
Michael Gottesman0be69202015-03-05 23:28:58 +0000189 typedef BlotMapVector<const Value *, PtrState> MapTy;
John McCalld935e9c2011-06-15 23:37:01 +0000190
Michael Gottesman97e3df02013-01-14 00:35:14 +0000191 /// The top-down traversal uses this to record information known about a
192 /// pointer at the bottom of each block.
John McCalld935e9c2011-06-15 23:37:01 +0000193 MapTy PerPtrTopDown;
194
Michael Gottesman97e3df02013-01-14 00:35:14 +0000195 /// The bottom-up traversal uses this to record information known about a
196 /// pointer at the top of each block.
John McCalld935e9c2011-06-15 23:37:01 +0000197 MapTy PerPtrBottomUp;
198
Michael Gottesman97e3df02013-01-14 00:35:14 +0000199 /// Effective predecessors of the current block ignoring ignorable edges and
200 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000201 SmallVector<BasicBlock *, 2> Preds;
Michael Gottesman97e3df02013-01-14 00:35:14 +0000202 /// Effective successors of the current block ignoring ignorable edges and
203 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000204 SmallVector<BasicBlock *, 2> Succs;
205
John McCalld935e9c2011-06-15 23:37:01 +0000206 public:
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000207 static const unsigned OverflowOccurredValue;
208
209 BBState() : TopDownPathCount(0), BottomUpPathCount(0) { }
John McCalld935e9c2011-06-15 23:37:01 +0000210
211 typedef MapTy::iterator ptr_iterator;
212 typedef MapTy::const_iterator ptr_const_iterator;
213
214 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
215 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
216 ptr_const_iterator top_down_ptr_begin() const {
217 return PerPtrTopDown.begin();
218 }
219 ptr_const_iterator top_down_ptr_end() const {
220 return PerPtrTopDown.end();
221 }
222
223 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
224 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
225 ptr_const_iterator bottom_up_ptr_begin() const {
226 return PerPtrBottomUp.begin();
227 }
228 ptr_const_iterator bottom_up_ptr_end() const {
229 return PerPtrBottomUp.end();
230 }
231
Michael Gottesman97e3df02013-01-14 00:35:14 +0000232 /// Mark this block as being an entry block, which has one path from the
233 /// entry by definition.
John McCalld935e9c2011-06-15 23:37:01 +0000234 void SetAsEntry() { TopDownPathCount = 1; }
235
Michael Gottesman97e3df02013-01-14 00:35:14 +0000236 /// Mark this block as being an exit block, which has one path to an exit by
237 /// definition.
John McCalld935e9c2011-06-15 23:37:01 +0000238 void SetAsExit() { BottomUpPathCount = 1; }
239
Michael Gottesman993fbf72013-05-13 19:40:39 +0000240 /// Attempt to find the PtrState object describing the top down state for
241 /// pointer Arg. Return a new initialized PtrState describing the top down
242 /// state for Arg if we do not find one.
John McCalld935e9c2011-06-15 23:37:01 +0000243 PtrState &getPtrTopDownState(const Value *Arg) {
244 return PerPtrTopDown[Arg];
245 }
246
Michael Gottesman993fbf72013-05-13 19:40:39 +0000247 /// Attempt to find the PtrState object describing the bottom up state for
248 /// pointer Arg. Return a new initialized PtrState describing the bottom up
249 /// state for Arg if we do not find one.
John McCalld935e9c2011-06-15 23:37:01 +0000250 PtrState &getPtrBottomUpState(const Value *Arg) {
251 return PerPtrBottomUp[Arg];
252 }
253
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000254 /// Attempt to find the PtrState object describing the bottom up state for
255 /// pointer Arg.
256 ptr_iterator findPtrBottomUpState(const Value *Arg) {
257 return PerPtrBottomUp.find(Arg);
258 }
259
John McCalld935e9c2011-06-15 23:37:01 +0000260 void clearBottomUpPointers() {
Evan Chenge4df6a22011-08-04 18:40:26 +0000261 PerPtrBottomUp.clear();
John McCalld935e9c2011-06-15 23:37:01 +0000262 }
263
264 void clearTopDownPointers() {
265 PerPtrTopDown.clear();
266 }
267
268 void InitFromPred(const BBState &Other);
269 void InitFromSucc(const BBState &Other);
270 void MergePred(const BBState &Other);
271 void MergeSucc(const BBState &Other);
272
Michael Gottesman9e7261c2013-06-07 06:16:49 +0000273 /// Compute the number of possible unique paths from an entry to an exit
Michael Gottesman97e3df02013-01-14 00:35:14 +0000274 /// which pass through this block. This is only valid after both the
275 /// top-down and bottom-up traversals are complete.
Michael Gottesman9e7261c2013-06-07 06:16:49 +0000276 ///
Alp Tokercb402912014-01-24 17:20:08 +0000277 /// Returns true if overflow occurred. Returns false if overflow did not
Michael Gottesman9e7261c2013-06-07 06:16:49 +0000278 /// occur.
279 bool GetAllPathCountWithOverflow(unsigned &PathCount) const {
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000280 if (TopDownPathCount == OverflowOccurredValue ||
281 BottomUpPathCount == OverflowOccurredValue)
282 return true;
Michael Gottesman9e7261c2013-06-07 06:16:49 +0000283 unsigned long long Product =
284 (unsigned long long)TopDownPathCount*BottomUpPathCount;
Alp Tokercb402912014-01-24 17:20:08 +0000285 // Overflow occurred if any of the upper bits of Product are set or if all
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000286 // the lower bits of Product are all set.
287 return (Product >> 32) ||
288 ((PathCount = Product) == OverflowOccurredValue);
John McCalld935e9c2011-06-15 23:37:01 +0000289 }
Dan Gohman12130272011-08-12 00:26:31 +0000290
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000291 // Specialized CFG utilities.
Dan Gohmandae33492012-04-27 18:56:31 +0000292 typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
Michael Gottesman0fecf982013-08-07 23:56:34 +0000293 edge_iterator pred_begin() const { return Preds.begin(); }
294 edge_iterator pred_end() const { return Preds.end(); }
295 edge_iterator succ_begin() const { return Succs.begin(); }
296 edge_iterator succ_end() const { return Succs.end(); }
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000297
298 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
299 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
300
301 bool isExit() const { return Succs.empty(); }
John McCalld935e9c2011-06-15 23:37:01 +0000302 };
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000303
304 const unsigned BBState::OverflowOccurredValue = 0xffffffff;
John McCalld935e9c2011-06-15 23:37:01 +0000305}
306
307void BBState::InitFromPred(const BBState &Other) {
308 PerPtrTopDown = Other.PerPtrTopDown;
309 TopDownPathCount = Other.TopDownPathCount;
310}
311
312void BBState::InitFromSucc(const BBState &Other) {
313 PerPtrBottomUp = Other.PerPtrBottomUp;
314 BottomUpPathCount = Other.BottomUpPathCount;
315}
316
Michael Gottesman97e3df02013-01-14 00:35:14 +0000317/// The top-down traversal uses this to merge information about predecessors to
318/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +0000319void BBState::MergePred(const BBState &Other) {
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000320 if (TopDownPathCount == OverflowOccurredValue)
321 return;
322
John McCalld935e9c2011-06-15 23:37:01 +0000323 // Other.TopDownPathCount can be 0, in which case it is either dead or a
324 // loop backedge. Loop backedges are special.
325 TopDownPathCount += Other.TopDownPathCount;
326
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000327 // In order to be consistent, we clear the top down pointers when by adding
328 // TopDownPathCount becomes OverflowOccurredValue even though "true" overflow
Alp Tokercb402912014-01-24 17:20:08 +0000329 // has not occurred.
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000330 if (TopDownPathCount == OverflowOccurredValue) {
331 clearTopDownPointers();
332 return;
333 }
334
Michael Gottesman4385edf2013-01-14 01:47:53 +0000335 // Check for overflow. If we have overflow, fall back to conservative
336 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +0000337 if (TopDownPathCount < Other.TopDownPathCount) {
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000338 TopDownPathCount = OverflowOccurredValue;
Dan Gohman7c84dad2012-09-12 20:45:17 +0000339 clearTopDownPointers();
340 return;
341 }
342
John McCalld935e9c2011-06-15 23:37:01 +0000343 // For each entry in the other set, if our set has an entry with the same key,
344 // merge the entries. Otherwise, copy the entry and merge it with an empty
345 // entry.
346 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
347 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
348 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
349 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
350 /*TopDown=*/true);
351 }
352
Dan Gohman7e315fc32011-08-11 21:06:32 +0000353 // For each entry in our set, if the other set doesn't have an entry with the
John McCalld935e9c2011-06-15 23:37:01 +0000354 // same key, force it to merge with an empty entry.
355 for (ptr_iterator MI = top_down_ptr_begin(),
356 ME = top_down_ptr_end(); MI != ME; ++MI)
357 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
358 MI->second.Merge(PtrState(), /*TopDown=*/true);
359}
360
Michael Gottesman97e3df02013-01-14 00:35:14 +0000361/// The bottom-up traversal uses this to merge information about successors to
362/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +0000363void BBState::MergeSucc(const BBState &Other) {
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000364 if (BottomUpPathCount == OverflowOccurredValue)
365 return;
366
John McCalld935e9c2011-06-15 23:37:01 +0000367 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
368 // loop backedge. Loop backedges are special.
369 BottomUpPathCount += Other.BottomUpPathCount;
370
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000371 // In order to be consistent, we clear the top down pointers when by adding
372 // BottomUpPathCount becomes OverflowOccurredValue even though "true" overflow
Alp Tokercb402912014-01-24 17:20:08 +0000373 // has not occurred.
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000374 if (BottomUpPathCount == OverflowOccurredValue) {
375 clearBottomUpPointers();
376 return;
377 }
378
Michael Gottesman4385edf2013-01-14 01:47:53 +0000379 // Check for overflow. If we have overflow, fall back to conservative
380 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +0000381 if (BottomUpPathCount < Other.BottomUpPathCount) {
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000382 BottomUpPathCount = OverflowOccurredValue;
Dan Gohman7c84dad2012-09-12 20:45:17 +0000383 clearBottomUpPointers();
384 return;
385 }
386
John McCalld935e9c2011-06-15 23:37:01 +0000387 // For each entry in the other set, if our set has an entry with the
388 // same key, merge the entries. Otherwise, copy the entry and merge
389 // it with an empty entry.
390 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
391 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
392 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
393 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
394 /*TopDown=*/false);
395 }
396
Dan Gohman7e315fc32011-08-11 21:06:32 +0000397 // For each entry in our set, if the other set doesn't have an entry
John McCalld935e9c2011-06-15 23:37:01 +0000398 // with the same key, force it to merge with an empty entry.
399 for (ptr_iterator MI = bottom_up_ptr_begin(),
400 ME = bottom_up_ptr_end(); MI != ME; ++MI)
401 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
402 MI->second.Merge(PtrState(), /*TopDown=*/false);
403}
404
Michael Gottesman81b1d432013-03-26 00:42:04 +0000405// Only enable ARC Annotations if we are building a debug version of
406// libObjCARCOpts.
407#ifndef NDEBUG
408#define ARC_ANNOTATIONS
409#endif
410
411// Define some macros along the lines of DEBUG and some helper functions to make
412// it cleaner to create annotations in the source code and to no-op when not
413// building in debug mode.
414#ifdef ARC_ANNOTATIONS
415
416#include "llvm/Support/CommandLine.h"
417
418/// Enable/disable ARC sequence annotations.
419static cl::opt<bool>
Michael Gottesman6806b512013-04-17 20:48:03 +0000420EnableARCAnnotations("enable-objc-arc-annotations", cl::init(false),
421 cl::desc("Enable emission of arc data flow analysis "
422 "annotations"));
Michael Gottesmanffef24f2013-04-17 20:48:01 +0000423static cl::opt<bool>
Michael Gottesmanadb921a2013-04-17 21:03:53 +0000424DisableCheckForCFGHazards("disable-objc-arc-checkforcfghazards", cl::init(false),
425 cl::desc("Disable check for cfg hazards when "
426 "annotating"));
Michael Gottesman4e88ce62013-04-17 21:59:41 +0000427static cl::opt<std::string>
428ARCAnnotationTargetIdentifier("objc-arc-annotation-target-identifier",
429 cl::init(""),
430 cl::desc("filter out all data flow annotations "
431 "but those that apply to the given "
432 "target llvm identifier."));
Michael Gottesman81b1d432013-03-26 00:42:04 +0000433
434/// This function appends a unique ARCAnnotationProvenanceSourceMDKind id to an
435/// instruction so that we can track backwards when post processing via the llvm
436/// arc annotation processor tool. If the function is an
437static MDString *AppendMDNodeToSourcePtr(unsigned NodeId,
438 Value *Ptr) {
Craig Toppere73658d2014-04-28 04:05:08 +0000439 MDString *Hash = nullptr;
Michael Gottesman81b1d432013-03-26 00:42:04 +0000440
441 // If pointer is a result of an instruction and it does not have a source
442 // MDNode it, attach a new MDNode onto it. If pointer is a result of
443 // an instruction and does have a source MDNode attached to it, return a
444 // reference to said Node. Otherwise just return 0.
445 if (Instruction *Inst = dyn_cast<Instruction>(Ptr)) {
446 MDNode *Node;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000447 if (!(Node = Inst->getMetadata(NodeId))) {
Michael Gottesman81b1d432013-03-26 00:42:04 +0000448 // We do not have any node. Generate and attatch the hash MDString to the
449 // instruction.
450
451 // We just use an MDString to ensure that this metadata gets written out
452 // of line at the module level and to provide a very simple format
453 // encoding the information herein. Both of these makes it simpler to
454 // parse the annotations by a simple external program.
Alp Tokere69170a2014-06-26 22:52:05 +0000455 std::string Str;
456 raw_string_ostream os(Str);
Michael Gottesman81b1d432013-03-26 00:42:04 +0000457 os << "(" << Inst->getParent()->getParent()->getName() << ",%"
458 << Inst->getName() << ")";
459
460 Hash = MDString::get(Inst->getContext(), os.str());
461 Inst->setMetadata(NodeId, MDNode::get(Inst->getContext(),Hash));
462 } else {
463 // We have a node. Grab its hash and return it.
464 assert(Node->getNumOperands() == 1 &&
465 "An ARCAnnotationProvenanceSourceMDKind can only have 1 operand.");
466 Hash = cast<MDString>(Node->getOperand(0));
467 }
468 } else if (Argument *Arg = dyn_cast<Argument>(Ptr)) {
Alp Tokere69170a2014-06-26 22:52:05 +0000469 std::string str;
470 raw_string_ostream os(str);
Michael Gottesman81b1d432013-03-26 00:42:04 +0000471 os << "(" << Arg->getParent()->getName() << ",%" << Arg->getName()
472 << ")";
473 Hash = MDString::get(Arg->getContext(), os.str());
474 }
475
476 return Hash;
477}
478
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000479static std::string SequenceToString(Sequence A) {
Alp Tokere69170a2014-06-26 22:52:05 +0000480 std::string str;
481 raw_string_ostream os(str);
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000482 os << A;
483 return os.str();
484}
485
Michael Gottesman81b1d432013-03-26 00:42:04 +0000486/// Helper function to change a Sequence into a String object using our overload
487/// for raw_ostream so we only have printing code in one location.
488static MDString *SequenceToMDString(LLVMContext &Context,
489 Sequence A) {
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000490 return MDString::get(Context, SequenceToString(A));
Michael Gottesman81b1d432013-03-26 00:42:04 +0000491}
492
493/// A simple function to generate a MDNode which describes the change in state
494/// for Value *Ptr caused by Instruction *Inst.
495static void AppendMDNodeToInstForPtr(unsigned NodeId,
496 Instruction *Inst,
497 Value *Ptr,
498 MDString *PtrSourceMDNodeID,
499 Sequence OldSeq,
500 Sequence NewSeq) {
Craig Toppere73658d2014-04-28 04:05:08 +0000501 MDNode *Node = nullptr;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000502 Metadata *tmp[3] = {PtrSourceMDNodeID,
503 SequenceToMDString(Inst->getContext(), OldSeq),
504 SequenceToMDString(Inst->getContext(), NewSeq)};
Craig Toppere1d12942014-08-27 05:25:25 +0000505 Node = MDNode::get(Inst->getContext(), tmp);
Michael Gottesman81b1d432013-03-26 00:42:04 +0000506
507 Inst->setMetadata(NodeId, Node);
508}
509
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000510/// Add to the beginning of the basic block llvm.ptr.annotations which show the
511/// state of a pointer at the entrance to a basic block.
512static void GenerateARCBBEntranceAnnotation(const char *Name, BasicBlock *BB,
513 Value *Ptr, Sequence Seq) {
Michael Gottesman4e88ce62013-04-17 21:59:41 +0000514 // If we have a target identifier, make sure that we match it before
515 // continuing.
516 if(!ARCAnnotationTargetIdentifier.empty() &&
517 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
518 return;
Michael Gottesman9e518132013-04-18 04:34:11 +0000519
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000520 Module *M = BB->getParent()->getParent();
521 LLVMContext &C = M->getContext();
522 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
523 Type *I8XX = PointerType::getUnqual(I8X);
524 Type *Params[] = {I8XX, I8XX};
Craig Toppere1d12942014-08-27 05:25:25 +0000525 FunctionType *FTy = FunctionType::get(Type::getVoidTy(C), Params,
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000526 /*isVarArg=*/false);
527 Constant *Callee = M->getOrInsertFunction(Name, FTy);
Michael Gottesman60f6b282013-03-29 05:13:07 +0000528
529 IRBuilder<> Builder(BB, BB->getFirstInsertionPt());
530
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000531 Value *PtrName;
532 StringRef Tmp = Ptr->getName();
Craig Toppere73658d2014-04-28 04:05:08 +0000533 if (nullptr == (PtrName = M->getGlobalVariable(Tmp, true))) {
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000534 Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
535 Tmp + "_STR");
536 PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
Michael Gottesman60f6b282013-03-29 05:13:07 +0000537 cast<Constant>(ActualPtrName), Tmp);
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000538 }
539
540 Value *S;
541 std::string SeqStr = SequenceToString(Seq);
Craig Toppere73658d2014-04-28 04:05:08 +0000542 if (nullptr == (S = M->getGlobalVariable(SeqStr, true))) {
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000543 Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
544 SeqStr + "_STR");
545 S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
546 cast<Constant>(ActualPtrName), SeqStr);
547 }
548
549 Builder.CreateCall2(Callee, PtrName, S);
550}
551
552/// Add to the end of the basic block llvm.ptr.annotations which show the state
553/// of the pointer at the bottom of the basic block.
554static void GenerateARCBBTerminatorAnnotation(const char *Name, BasicBlock *BB,
555 Value *Ptr, Sequence Seq) {
Michael Gottesman4e88ce62013-04-17 21:59:41 +0000556 // If we have a target identifier, make sure that we match it before emitting
557 // an annotation.
558 if(!ARCAnnotationTargetIdentifier.empty() &&
559 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
560 return;
Michael Gottesman9e518132013-04-18 04:34:11 +0000561
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000562 Module *M = BB->getParent()->getParent();
563 LLVMContext &C = M->getContext();
564 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
565 Type *I8XX = PointerType::getUnqual(I8X);
566 Type *Params[] = {I8XX, I8XX};
Craig Toppere1d12942014-08-27 05:25:25 +0000567 FunctionType *FTy = FunctionType::get(Type::getVoidTy(C), Params,
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000568 /*isVarArg=*/false);
569 Constant *Callee = M->getOrInsertFunction(Name, FTy);
Michael Gottesman60f6b282013-03-29 05:13:07 +0000570
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000571 IRBuilder<> Builder(BB, std::prev(BB->end()));
Michael Gottesman60f6b282013-03-29 05:13:07 +0000572
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000573 Value *PtrName;
574 StringRef Tmp = Ptr->getName();
Craig Toppere73658d2014-04-28 04:05:08 +0000575 if (nullptr == (PtrName = M->getGlobalVariable(Tmp, true))) {
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000576 Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
577 Tmp + "_STR");
578 PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
Michael Gottesman60f6b282013-03-29 05:13:07 +0000579 cast<Constant>(ActualPtrName), Tmp);
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000580 }
581
582 Value *S;
583 std::string SeqStr = SequenceToString(Seq);
Craig Toppere73658d2014-04-28 04:05:08 +0000584 if (nullptr == (S = M->getGlobalVariable(SeqStr, true))) {
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000585 Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
586 SeqStr + "_STR");
587 S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
588 cast<Constant>(ActualPtrName), SeqStr);
589 }
Michael Gottesman60f6b282013-03-29 05:13:07 +0000590 Builder.CreateCall2(Callee, PtrName, S);
Michael Gottesmancd4de0f2013-03-26 00:42:09 +0000591}
592
Michael Gottesman81b1d432013-03-26 00:42:04 +0000593/// Adds a source annotation to pointer and a state change annotation to Inst
594/// referencing the source annotation and the old/new state of pointer.
595static void GenerateARCAnnotation(unsigned InstMDId,
596 unsigned PtrMDId,
597 Instruction *Inst,
598 Value *Ptr,
599 Sequence OldSeq,
600 Sequence NewSeq) {
601 if (EnableARCAnnotations) {
Michael Gottesman4e88ce62013-04-17 21:59:41 +0000602 // If we have a target identifier, make sure that we match it before
603 // emitting an annotation.
604 if(!ARCAnnotationTargetIdentifier.empty() &&
605 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
606 return;
Michael Gottesman9e518132013-04-18 04:34:11 +0000607
Michael Gottesman81b1d432013-03-26 00:42:04 +0000608 // First generate the source annotation on our pointer. This will return an
609 // MDString* if Ptr actually comes from an instruction implying we can put
610 // in a source annotation. If AppendMDNodeToSourcePtr returns 0 (i.e. NULL),
611 // then we know that our pointer is from an Argument so we put a reference
612 // to the argument number.
613 //
614 // The point of this is to make it easy for the
615 // llvm-arc-annotation-processor tool to cross reference where the source
616 // pointer is in the LLVM IR since the LLVM IR parser does not submit such
617 // information via debug info for backends to use (since why would anyone
Alp Tokerf907b892013-12-05 05:44:44 +0000618 // need such a thing from LLVM IR besides in non-standard cases
Michael Gottesman81b1d432013-03-26 00:42:04 +0000619 // [i.e. this]).
620 MDString *SourcePtrMDNode =
621 AppendMDNodeToSourcePtr(PtrMDId, Ptr);
622 AppendMDNodeToInstForPtr(InstMDId, Inst, Ptr, SourcePtrMDNode, OldSeq,
623 NewSeq);
624 }
625}
626
627// The actual interface for accessing the above functionality is defined via
628// some simple macros which are defined below. We do this so that the user does
629// not need to pass in what metadata id is needed resulting in cleaner code and
630// additionally since it provides an easy way to conditionally no-op all
631// annotation support in a non-debug build.
632
633/// Use this macro to annotate a sequence state change when processing
634/// instructions bottom up,
635#define ANNOTATE_BOTTOMUP(inst, ptr, old, new) \
636 GenerateARCAnnotation(ARCAnnotationBottomUpMDKind, \
637 ARCAnnotationProvenanceSourceMDKind, (inst), \
638 const_cast<Value*>(ptr), (old), (new))
639/// Use this macro to annotate a sequence state change when processing
640/// instructions top down.
641#define ANNOTATE_TOPDOWN(inst, ptr, old, new) \
642 GenerateARCAnnotation(ARCAnnotationTopDownMDKind, \
643 ARCAnnotationProvenanceSourceMDKind, (inst), \
644 const_cast<Value*>(ptr), (old), (new))
645
Michael Gottesman43e7e002013-04-03 22:41:59 +0000646#define ANNOTATE_BB(_states, _bb, _name, _type, _direction) \
647 do { \
Michael Gottesman89279f82013-04-05 18:10:41 +0000648 if (EnableARCAnnotations) { \
649 for(BBState::ptr_const_iterator I = (_states)._direction##_ptr_begin(), \
Michael Gottesman43e7e002013-04-03 22:41:59 +0000650 E = (_states)._direction##_ptr_end(); I != E; ++I) { \
Michael Gottesman89279f82013-04-05 18:10:41 +0000651 Value *Ptr = const_cast<Value*>(I->first); \
652 Sequence Seq = I->second.GetSeq(); \
653 GenerateARCBB ## _type ## Annotation(_name, (_bb), Ptr, Seq); \
654 } \
Michael Gottesman43e7e002013-04-03 22:41:59 +0000655 } \
Michael Gottesman89279f82013-04-05 18:10:41 +0000656 } while (0)
Michael Gottesman43e7e002013-04-03 22:41:59 +0000657
Michael Gottesman89279f82013-04-05 18:10:41 +0000658#define ANNOTATE_BOTTOMUP_BBSTART(_states, _basicblock) \
Michael Gottesman43e7e002013-04-03 22:41:59 +0000659 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbstart", \
660 Entrance, bottom_up)
Michael Gottesman89279f82013-04-05 18:10:41 +0000661#define ANNOTATE_BOTTOMUP_BBEND(_states, _basicblock) \
662 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbend", \
Michael Gottesman43e7e002013-04-03 22:41:59 +0000663 Terminator, bottom_up)
Michael Gottesman89279f82013-04-05 18:10:41 +0000664#define ANNOTATE_TOPDOWN_BBSTART(_states, _basicblock) \
665 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbstart", \
Michael Gottesman43e7e002013-04-03 22:41:59 +0000666 Entrance, top_down)
Michael Gottesman89279f82013-04-05 18:10:41 +0000667#define ANNOTATE_TOPDOWN_BBEND(_states, _basicblock) \
668 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbend", \
Michael Gottesman43e7e002013-04-03 22:41:59 +0000669 Terminator, top_down)
670
Michael Gottesman81b1d432013-03-26 00:42:04 +0000671#else // !ARC_ANNOTATION
672// If annotations are off, noop.
673#define ANNOTATE_BOTTOMUP(inst, ptr, old, new)
674#define ANNOTATE_TOPDOWN(inst, ptr, old, new)
Michael Gottesman43e7e002013-04-03 22:41:59 +0000675#define ANNOTATE_BOTTOMUP_BBSTART(states, basicblock)
676#define ANNOTATE_BOTTOMUP_BBEND(states, basicblock)
677#define ANNOTATE_TOPDOWN_BBSTART(states, basicblock)
678#define ANNOTATE_TOPDOWN_BBEND(states, basicblock)
Michael Gottesman81b1d432013-03-26 00:42:04 +0000679#endif // !ARC_ANNOTATION
680
John McCalld935e9c2011-06-15 23:37:01 +0000681namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000682 /// \brief The main ARC optimization pass.
John McCalld935e9c2011-06-15 23:37:01 +0000683 class ObjCARCOpt : public FunctionPass {
684 bool Changed;
685 ProvenanceAnalysis PA;
Michael Gottesman14acfac2013-07-06 01:39:23 +0000686 ARCRuntimeEntryPoints EP;
John McCalld935e9c2011-06-15 23:37:01 +0000687
Michael Gottesman5a91bbf2013-05-24 20:44:02 +0000688 // This is used to track if a pointer is stored into an alloca.
689 DenseSet<const Value *> MultiOwnersSet;
690
Michael Gottesman97e3df02013-01-14 00:35:14 +0000691 /// A flag indicating whether this optimization pass should run.
Dan Gohmanceaac7c2011-06-20 23:20:43 +0000692 bool Run;
693
Michael Gottesman97e3df02013-01-14 00:35:14 +0000694 /// Flags which determine whether each of the interesting runtine functions
695 /// is in fact used in the current function.
John McCalld935e9c2011-06-15 23:37:01 +0000696 unsigned UsedInThisFunction;
697
Michael Gottesman97e3df02013-01-14 00:35:14 +0000698 /// The Metadata Kind for clang.imprecise_release metadata.
John McCalld935e9c2011-06-15 23:37:01 +0000699 unsigned ImpreciseReleaseMDKind;
700
Michael Gottesman97e3df02013-01-14 00:35:14 +0000701 /// The Metadata Kind for clang.arc.copy_on_escape metadata.
Dan Gohmana7107f92011-10-17 22:53:25 +0000702 unsigned CopyOnEscapeMDKind;
703
Michael Gottesman97e3df02013-01-14 00:35:14 +0000704 /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata.
Dan Gohman0155f302012-02-17 18:59:53 +0000705 unsigned NoObjCARCExceptionsMDKind;
706
Michael Gottesman81b1d432013-03-26 00:42:04 +0000707#ifdef ARC_ANNOTATIONS
708 /// The Metadata Kind for llvm.arc.annotation.bottomup metadata.
709 unsigned ARCAnnotationBottomUpMDKind;
710 /// The Metadata Kind for llvm.arc.annotation.topdown metadata.
711 unsigned ARCAnnotationTopDownMDKind;
712 /// The Metadata Kind for llvm.arc.annotation.provenancesource metadata.
713 unsigned ARCAnnotationProvenanceSourceMDKind;
714#endif // ARC_ANNOATIONS
715
John McCalld935e9c2011-06-15 23:37:01 +0000716 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
Michael Gottesman556ff612013-01-12 01:25:19 +0000717 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000718 ARCInstKind &Class);
John McCalld935e9c2011-06-15 23:37:01 +0000719 void OptimizeIndividualCalls(Function &F);
720
721 void CheckForCFGHazards(const BasicBlock *BB,
722 DenseMap<const BasicBlock *, BBState> &BBStates,
723 BBState &MyStates) const;
Michael Gottesman0be69202015-03-05 23:28:58 +0000724 bool VisitInstructionBottomUp(Instruction *Inst, BasicBlock *BB,
725 BlotMapVector<Value *, RRInfo> &Retains,
Dan Gohman817a7c62012-03-22 18:24:56 +0000726 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +0000727 bool VisitBottomUp(BasicBlock *BB,
728 DenseMap<const BasicBlock *, BBState> &BBStates,
Michael Gottesman0be69202015-03-05 23:28:58 +0000729 BlotMapVector<Value *, RRInfo> &Retains);
Dan Gohman817a7c62012-03-22 18:24:56 +0000730 bool VisitInstructionTopDown(Instruction *Inst,
731 DenseMap<Value *, RRInfo> &Releases,
732 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +0000733 bool VisitTopDown(BasicBlock *BB,
734 DenseMap<const BasicBlock *, BBState> &BBStates,
735 DenseMap<Value *, RRInfo> &Releases);
Michael Gottesman0be69202015-03-05 23:28:58 +0000736 bool Visit(Function &F, DenseMap<const BasicBlock *, BBState> &BBStates,
737 BlotMapVector<Value *, RRInfo> &Retains,
John McCalld935e9c2011-06-15 23:37:01 +0000738 DenseMap<Value *, RRInfo> &Releases);
739
740 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
Michael Gottesman0be69202015-03-05 23:28:58 +0000741 BlotMapVector<Value *, RRInfo> &Retains,
John McCalld935e9c2011-06-15 23:37:01 +0000742 DenseMap<Value *, RRInfo> &Releases,
Michael Gottesman0be69202015-03-05 23:28:58 +0000743 SmallVectorImpl<Instruction *> &DeadInsts, Module *M);
John McCalld935e9c2011-06-15 23:37:01 +0000744
Michael Gottesman9de6f962013-01-22 21:49:00 +0000745 bool ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState> &BBStates,
Michael Gottesman0be69202015-03-05 23:28:58 +0000746 BlotMapVector<Value *, RRInfo> &Retains,
747 DenseMap<Value *, RRInfo> &Releases, Module *M,
Craig Topperb94011f2013-07-14 04:42:23 +0000748 SmallVectorImpl<Instruction *> &NewRetains,
749 SmallVectorImpl<Instruction *> &NewReleases,
750 SmallVectorImpl<Instruction *> &DeadInsts,
Michael Gottesman0be69202015-03-05 23:28:58 +0000751 RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
752 Value *Arg, bool KnownSafe,
Michael Gottesman9de6f962013-01-22 21:49:00 +0000753 bool &AnyPairsCompletelyEliminated);
754
John McCalld935e9c2011-06-15 23:37:01 +0000755 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
Michael Gottesman0be69202015-03-05 23:28:58 +0000756 BlotMapVector<Value *, RRInfo> &Retains,
757 DenseMap<Value *, RRInfo> &Releases, Module *M);
John McCalld935e9c2011-06-15 23:37:01 +0000758
759 void OptimizeWeakCalls(Function &F);
760
761 bool OptimizeSequences(Function &F);
762
763 void OptimizeReturns(Function &F);
764
Michael Gottesman9c118152013-04-29 06:16:57 +0000765#ifndef NDEBUG
766 void GatherStatistics(Function &F, bool AfterOptimization = false);
767#endif
768
Craig Topper3e4c6972014-03-05 09:10:37 +0000769 void getAnalysisUsage(AnalysisUsage &AU) const override;
770 bool doInitialization(Module &M) override;
771 bool runOnFunction(Function &F) override;
772 void releaseMemory() override;
John McCalld935e9c2011-06-15 23:37:01 +0000773
774 public:
775 static char ID;
776 ObjCARCOpt() : FunctionPass(ID) {
777 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
778 }
779 };
780}
781
782char ObjCARCOpt::ID = 0;
783INITIALIZE_PASS_BEGIN(ObjCARCOpt,
784 "objc-arc", "ObjC ARC optimization", false, false)
785INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
786INITIALIZE_PASS_END(ObjCARCOpt,
787 "objc-arc", "ObjC ARC optimization", false, false)
788
789Pass *llvm::createObjCARCOptPass() {
790 return new ObjCARCOpt();
791}
792
793void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
794 AU.addRequired<ObjCARCAliasAnalysis>();
795 AU.addRequired<AliasAnalysis>();
796 // ARC optimization doesn't currently split critical edges.
797 AU.setPreservesCFG();
798}
799
Michael Gottesman97e3df02013-01-14 00:35:14 +0000800/// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is
801/// not a return value. Or, if it can be paired with an
802/// objc_autoreleaseReturnValue, delete the pair and return true.
John McCalld935e9c2011-06-15 23:37:01 +0000803bool
804ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +0000805 // Check for the argument being from an immediately preceding call or invoke.
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000806 const Value *Arg = GetArgRCIdentityRoot(RetainRV);
Dan Gohmandae33492012-04-27 18:56:31 +0000807 ImmutableCallSite CS(Arg);
808 if (const Instruction *Call = CS.getInstruction()) {
John McCalld935e9c2011-06-15 23:37:01 +0000809 if (Call->getParent() == RetainRV->getParent()) {
Dan Gohmandae33492012-04-27 18:56:31 +0000810 BasicBlock::const_iterator I = Call;
John McCalld935e9c2011-06-15 23:37:01 +0000811 ++I;
Michael Gottesman65c24812013-03-25 09:27:43 +0000812 while (IsNoopInstruction(I)) ++I;
John McCalld935e9c2011-06-15 23:37:01 +0000813 if (&*I == RetainRV)
814 return false;
Dan Gohmandae33492012-04-27 18:56:31 +0000815 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +0000816 BasicBlock *RetainRVParent = RetainRV->getParent();
817 if (II->getNormalDest() == RetainRVParent) {
Dan Gohmandae33492012-04-27 18:56:31 +0000818 BasicBlock::const_iterator I = RetainRVParent->begin();
Michael Gottesman65c24812013-03-25 09:27:43 +0000819 while (IsNoopInstruction(I)) ++I;
Dan Gohmane3ed2b02012-03-23 18:09:00 +0000820 if (&*I == RetainRV)
821 return false;
822 }
John McCalld935e9c2011-06-15 23:37:01 +0000823 }
Dan Gohmane3ed2b02012-03-23 18:09:00 +0000824 }
John McCalld935e9c2011-06-15 23:37:01 +0000825
826 // Check for being preceded by an objc_autoreleaseReturnValue on the same
827 // pointer. In this case, we can delete the pair.
828 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
829 if (I != Begin) {
Michael Gottesman65c24812013-03-25 09:27:43 +0000830 do --I; while (I != Begin && IsNoopInstruction(I));
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000831 if (GetBasicARCInstKind(I) == ARCInstKind::AutoreleaseRV &&
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000832 GetArgRCIdentityRoot(I) == Arg) {
John McCalld935e9c2011-06-15 23:37:01 +0000833 Changed = true;
834 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +0000835
Michael Gottesman89279f82013-04-05 18:10:41 +0000836 DEBUG(dbgs() << "Erasing autoreleaseRV,retainRV pair: " << *I << "\n"
837 << "Erasing " << *RetainRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +0000838
John McCalld935e9c2011-06-15 23:37:01 +0000839 EraseInstruction(I);
840 EraseInstruction(RetainRV);
841 return true;
842 }
843 }
844
845 // Turn it to a plain objc_retain.
846 Changed = true;
847 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +0000848
Michael Gottesman89279f82013-04-05 18:10:41 +0000849 DEBUG(dbgs() << "Transforming objc_retainAutoreleasedReturnValue => "
Michael Gottesmandef07bb2013-01-05 17:55:42 +0000850 "objc_retain since the operand is not a return value.\n"
Michael Gottesman89279f82013-04-05 18:10:41 +0000851 "Old = " << *RetainRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +0000852
Michael Gottesman14acfac2013-07-06 01:39:23 +0000853 Constant *NewDecl = EP.get(ARCRuntimeEntryPoints::EPT_Retain);
854 cast<CallInst>(RetainRV)->setCalledFunction(NewDecl);
Michael Gottesmandef07bb2013-01-05 17:55:42 +0000855
Michael Gottesman89279f82013-04-05 18:10:41 +0000856 DEBUG(dbgs() << "New = " << *RetainRV << "\n");
Michael Gottesmandef07bb2013-01-05 17:55:42 +0000857
John McCalld935e9c2011-06-15 23:37:01 +0000858 return false;
859}
860
Michael Gottesman97e3df02013-01-14 00:35:14 +0000861/// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not
862/// used as a return value.
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000863void ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F,
864 Instruction *AutoreleaseRV,
865 ARCInstKind &Class) {
John McCalld935e9c2011-06-15 23:37:01 +0000866 // Check for a return of the pointer value.
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000867 const Value *Ptr = GetArgRCIdentityRoot(AutoreleaseRV);
Dan Gohman10a18d52011-08-12 00:36:31 +0000868 SmallVector<const Value *, 2> Users;
869 Users.push_back(Ptr);
870 do {
871 Ptr = Users.pop_back_val();
Chandler Carruthcdf47882014-03-09 03:16:01 +0000872 for (const User *U : Ptr->users()) {
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000873 if (isa<ReturnInst>(U) || GetBasicARCInstKind(U) == ARCInstKind::RetainRV)
Dan Gohman10a18d52011-08-12 00:36:31 +0000874 return;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000875 if (isa<BitCastInst>(U))
876 Users.push_back(U);
Dan Gohman10a18d52011-08-12 00:36:31 +0000877 }
878 } while (!Users.empty());
John McCalld935e9c2011-06-15 23:37:01 +0000879
880 Changed = true;
881 ++NumPeeps;
Michael Gottesman1bf69082013-01-06 21:07:11 +0000882
Michael Gottesman89279f82013-04-05 18:10:41 +0000883 DEBUG(dbgs() << "Transforming objc_autoreleaseReturnValue => "
Michael Gottesman1bf69082013-01-06 21:07:11 +0000884 "objc_autorelease since its operand is not used as a return "
885 "value.\n"
Michael Gottesman89279f82013-04-05 18:10:41 +0000886 "Old = " << *AutoreleaseRV << "\n");
Michael Gottesman1bf69082013-01-06 21:07:11 +0000887
Michael Gottesmanc9656fa2013-01-12 01:25:15 +0000888 CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
Michael Gottesman14acfac2013-07-06 01:39:23 +0000889 Constant *NewDecl = EP.get(ARCRuntimeEntryPoints::EPT_Autorelease);
890 AutoreleaseRVCI->setCalledFunction(NewDecl);
Michael Gottesmanc9656fa2013-01-12 01:25:15 +0000891 AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000892 Class = ARCInstKind::Autorelease;
Michael Gottesman10426b52013-01-07 21:26:07 +0000893
Michael Gottesman89279f82013-04-05 18:10:41 +0000894 DEBUG(dbgs() << "New: " << *AutoreleaseRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +0000895
John McCalld935e9c2011-06-15 23:37:01 +0000896}
897
Michael Gottesman97e3df02013-01-14 00:35:14 +0000898/// Visit each call, one at a time, and make simplifications without doing any
899/// additional analysis.
John McCalld935e9c2011-06-15 23:37:01 +0000900void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
Michael Gottesman89279f82013-04-05 18:10:41 +0000901 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeIndividualCalls ==\n");
John McCalld935e9c2011-06-15 23:37:01 +0000902 // Reset all the flags in preparation for recomputing them.
903 UsedInThisFunction = 0;
904
905 // Visit all objc_* calls in F.
906 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
907 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +0000908
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000909 ARCInstKind Class = GetBasicARCInstKind(Inst);
John McCalld935e9c2011-06-15 23:37:01 +0000910
Michael Gottesman89279f82013-04-05 18:10:41 +0000911 DEBUG(dbgs() << "Visiting: Class: " << Class << "; " << *Inst << "\n");
Michael Gottesman782e3442013-01-17 18:32:34 +0000912
John McCalld935e9c2011-06-15 23:37:01 +0000913 switch (Class) {
914 default: break;
915
916 // Delete no-op casts. These function calls have special semantics, but
917 // the semantics are entirely implemented via lowering in the front-end,
918 // so by the time they reach the optimizer, they are just no-op calls
919 // which return their argument.
920 //
921 // There are gray areas here, as the ability to cast reference-counted
922 // pointers to raw void* and back allows code to break ARC assumptions,
923 // however these are currently considered to be unimportant.
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000924 case ARCInstKind::NoopCast:
John McCalld935e9c2011-06-15 23:37:01 +0000925 Changed = true;
926 ++NumNoops;
Michael Gottesman89279f82013-04-05 18:10:41 +0000927 DEBUG(dbgs() << "Erasing no-op cast: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +0000928 EraseInstruction(Inst);
929 continue;
930
931 // If the pointer-to-weak-pointer is null, it's undefined behavior.
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000932 case ARCInstKind::StoreWeak:
933 case ARCInstKind::LoadWeak:
934 case ARCInstKind::LoadWeakRetained:
935 case ARCInstKind::InitWeak:
936 case ARCInstKind::DestroyWeak: {
John McCalld935e9c2011-06-15 23:37:01 +0000937 CallInst *CI = cast<CallInst>(Inst);
Michael Gottesman65c24812013-03-25 09:27:43 +0000938 if (IsNullOrUndef(CI->getArgOperand(0))) {
Dan Gohman670f9372012-04-13 18:57:48 +0000939 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +0000940 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +0000941 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
942 Constant::getNullValue(Ty),
943 CI);
Michael Gottesman10426b52013-01-07 21:26:07 +0000944 llvm::Value *NewValue = UndefValue::get(CI->getType());
Michael Gottesman89279f82013-04-05 18:10:41 +0000945 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
946 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
Michael Gottesmanfec61c02013-01-06 21:54:30 +0000947 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +0000948 CI->eraseFromParent();
949 continue;
950 }
951 break;
952 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000953 case ARCInstKind::CopyWeak:
954 case ARCInstKind::MoveWeak: {
John McCalld935e9c2011-06-15 23:37:01 +0000955 CallInst *CI = cast<CallInst>(Inst);
Michael Gottesman65c24812013-03-25 09:27:43 +0000956 if (IsNullOrUndef(CI->getArgOperand(0)) ||
957 IsNullOrUndef(CI->getArgOperand(1))) {
Dan Gohman670f9372012-04-13 18:57:48 +0000958 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +0000959 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +0000960 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
961 Constant::getNullValue(Ty),
962 CI);
Michael Gottesmanfec61c02013-01-06 21:54:30 +0000963
964 llvm::Value *NewValue = UndefValue::get(CI->getType());
Michael Gottesman89279f82013-04-05 18:10:41 +0000965 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
966 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +0000967
Michael Gottesmanfec61c02013-01-06 21:54:30 +0000968 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +0000969 CI->eraseFromParent();
970 continue;
971 }
972 break;
973 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000974 case ARCInstKind::RetainRV:
John McCalld935e9c2011-06-15 23:37:01 +0000975 if (OptimizeRetainRVCall(F, Inst))
976 continue;
977 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000978 case ARCInstKind::AutoreleaseRV:
Michael Gottesman556ff612013-01-12 01:25:19 +0000979 OptimizeAutoreleaseRVCall(F, Inst, Class);
John McCalld935e9c2011-06-15 23:37:01 +0000980 break;
981 }
982
Michael Gottesmanb8c88362013-04-03 02:57:24 +0000983 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
John McCalld935e9c2011-06-15 23:37:01 +0000984 if (IsAutorelease(Class) && Inst->use_empty()) {
985 CallInst *Call = cast<CallInst>(Inst);
986 const Value *Arg = Call->getArgOperand(0);
987 Arg = FindSingleUseIdentifiedObject(Arg);
988 if (Arg) {
989 Changed = true;
990 ++NumAutoreleases;
991
992 // Create the declaration lazily.
993 LLVMContext &C = Inst->getContext();
Michael Gottesman01df4502013-07-06 01:41:35 +0000994
Michael Gottesman14acfac2013-07-06 01:39:23 +0000995 Constant *Decl = EP.get(ARCRuntimeEntryPoints::EPT_Release);
996 CallInst *NewCall = CallInst::Create(Decl, Call->getArgOperand(0), "",
997 Call);
Dmitri Gribenko3238fb72013-05-05 00:40:33 +0000998 NewCall->setMetadata(ImpreciseReleaseMDKind, MDNode::get(C, None));
Michael Gottesman10426b52013-01-07 21:26:07 +0000999
Michael Gottesman89279f82013-04-05 18:10:41 +00001000 DEBUG(dbgs() << "Replacing autorelease{,RV}(x) with objc_release(x) "
1001 "since x is otherwise unused.\nOld: " << *Call << "\nNew: "
1002 << *NewCall << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001003
John McCalld935e9c2011-06-15 23:37:01 +00001004 EraseInstruction(Call);
1005 Inst = NewCall;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001006 Class = ARCInstKind::Release;
John McCalld935e9c2011-06-15 23:37:01 +00001007 }
1008 }
1009
1010 // For functions which can never be passed stack arguments, add
1011 // a tail keyword.
1012 if (IsAlwaysTail(Class)) {
1013 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +00001014 DEBUG(dbgs() << "Adding tail keyword to function since it can never be "
1015 "passed stack args: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001016 cast<CallInst>(Inst)->setTailCall();
1017 }
1018
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001019 // Ensure that functions that can never have a "tail" keyword due to the
1020 // semantics of ARC truly do not do so.
1021 if (IsNeverTail(Class)) {
1022 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +00001023 DEBUG(dbgs() << "Removing tail keyword from function: " << *Inst <<
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001024 "\n");
1025 cast<CallInst>(Inst)->setTailCall(false);
1026 }
1027
John McCalld935e9c2011-06-15 23:37:01 +00001028 // Set nounwind as needed.
1029 if (IsNoThrow(Class)) {
1030 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +00001031 DEBUG(dbgs() << "Found no throw class. Setting nounwind on: " << *Inst
1032 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001033 cast<CallInst>(Inst)->setDoesNotThrow();
1034 }
1035
1036 if (!IsNoopOnNull(Class)) {
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001037 UsedInThisFunction |= 1 << unsigned(Class);
John McCalld935e9c2011-06-15 23:37:01 +00001038 continue;
1039 }
1040
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001041 const Value *Arg = GetArgRCIdentityRoot(Inst);
John McCalld935e9c2011-06-15 23:37:01 +00001042
1043 // ARC calls with null are no-ops. Delete them.
Michael Gottesman65c24812013-03-25 09:27:43 +00001044 if (IsNullOrUndef(Arg)) {
John McCalld935e9c2011-06-15 23:37:01 +00001045 Changed = true;
1046 ++NumNoops;
Michael Gottesman89279f82013-04-05 18:10:41 +00001047 DEBUG(dbgs() << "ARC calls with null are no-ops. Erasing: " << *Inst
1048 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001049 EraseInstruction(Inst);
1050 continue;
1051 }
1052
1053 // Keep track of which of retain, release, autorelease, and retain_block
1054 // are actually present in this function.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001055 UsedInThisFunction |= 1 << unsigned(Class);
John McCalld935e9c2011-06-15 23:37:01 +00001056
1057 // If Arg is a PHI, and one or more incoming values to the
1058 // PHI are null, and the call is control-equivalent to the PHI, and there
1059 // are no relevant side effects between the PHI and the call, the call
1060 // could be pushed up to just those paths with non-null incoming values.
1061 // For now, don't bother splitting critical edges for this.
1062 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
1063 Worklist.push_back(std::make_pair(Inst, Arg));
1064 do {
1065 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
1066 Inst = Pair.first;
1067 Arg = Pair.second;
1068
1069 const PHINode *PN = dyn_cast<PHINode>(Arg);
1070 if (!PN) continue;
1071
1072 // Determine if the PHI has any null operands, or any incoming
1073 // critical edges.
1074 bool HasNull = false;
1075 bool HasCriticalEdges = false;
1076 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1077 Value *Incoming =
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001078 GetRCIdentityRoot(PN->getIncomingValue(i));
Michael Gottesman65c24812013-03-25 09:27:43 +00001079 if (IsNullOrUndef(Incoming))
John McCalld935e9c2011-06-15 23:37:01 +00001080 HasNull = true;
1081 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
1082 .getNumSuccessors() != 1) {
1083 HasCriticalEdges = true;
1084 break;
1085 }
1086 }
1087 // If we have null operands and no critical edges, optimize.
1088 if (!HasCriticalEdges && HasNull) {
1089 SmallPtrSet<Instruction *, 4> DependingInstructions;
1090 SmallPtrSet<const BasicBlock *, 4> Visited;
1091
1092 // Check that there is nothing that cares about the reference
1093 // count between the call and the phi.
Dan Gohman8478d762012-04-13 00:59:57 +00001094 switch (Class) {
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001095 case ARCInstKind::Retain:
1096 case ARCInstKind::RetainBlock:
Dan Gohman8478d762012-04-13 00:59:57 +00001097 // These can always be moved up.
1098 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001099 case ARCInstKind::Release:
Dan Gohman41375a32012-05-08 23:39:44 +00001100 // These can't be moved across things that care about the retain
1101 // count.
Dan Gohman8478d762012-04-13 00:59:57 +00001102 FindDependencies(NeedsPositiveRetainCount, Arg,
1103 Inst->getParent(), Inst,
1104 DependingInstructions, Visited, PA);
1105 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001106 case ARCInstKind::Autorelease:
Dan Gohman8478d762012-04-13 00:59:57 +00001107 // These can't be moved across autorelease pool scope boundaries.
1108 FindDependencies(AutoreleasePoolBoundary, Arg,
1109 Inst->getParent(), Inst,
1110 DependingInstructions, Visited, PA);
1111 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001112 case ARCInstKind::RetainRV:
1113 case ARCInstKind::AutoreleaseRV:
Dan Gohman8478d762012-04-13 00:59:57 +00001114 // Don't move these; the RV optimization depends on the autoreleaseRV
1115 // being tail called, and the retainRV being immediately after a call
1116 // (which might still happen if we get lucky with codegen layout, but
1117 // it's not worth taking the chance).
1118 continue;
1119 default:
1120 llvm_unreachable("Invalid dependence flavor");
1121 }
1122
John McCalld935e9c2011-06-15 23:37:01 +00001123 if (DependingInstructions.size() == 1 &&
1124 *DependingInstructions.begin() == PN) {
1125 Changed = true;
1126 ++NumPartialNoops;
1127 // Clone the call into each predecessor that has a non-null value.
1128 CallInst *CInst = cast<CallInst>(Inst);
Chris Lattner229907c2011-07-18 04:54:35 +00001129 Type *ParamTy = CInst->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001130 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1131 Value *Incoming =
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001132 GetRCIdentityRoot(PN->getIncomingValue(i));
Michael Gottesman65c24812013-03-25 09:27:43 +00001133 if (!IsNullOrUndef(Incoming)) {
John McCalld935e9c2011-06-15 23:37:01 +00001134 CallInst *Clone = cast<CallInst>(CInst->clone());
1135 Value *Op = PN->getIncomingValue(i);
1136 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
1137 if (Op->getType() != ParamTy)
1138 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
1139 Clone->setArgOperand(0, Op);
1140 Clone->insertBefore(InsertPos);
Michael Gottesmanc189a392013-01-09 19:23:24 +00001141
Michael Gottesman89279f82013-04-05 18:10:41 +00001142 DEBUG(dbgs() << "Cloning "
Michael Gottesmanc189a392013-01-09 19:23:24 +00001143 << *CInst << "\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00001144 "And inserting clone at " << *InsertPos << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001145 Worklist.push_back(std::make_pair(Clone, Incoming));
1146 }
1147 }
1148 // Erase the original call.
Michael Gottesmanc189a392013-01-09 19:23:24 +00001149 DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001150 EraseInstruction(CInst);
1151 continue;
1152 }
1153 }
1154 } while (!Worklist.empty());
1155 }
1156}
1157
Michael Gottesman323964c2013-04-18 05:39:45 +00001158/// If we have a top down pointer in the S_Use state, make sure that there are
1159/// no CFG hazards by checking the states of various bottom up pointers.
1160static void CheckForUseCFGHazard(const Sequence SuccSSeq,
1161 const bool SuccSRRIKnownSafe,
1162 PtrState &S,
1163 bool &SomeSuccHasSame,
1164 bool &AllSuccsHaveSame,
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001165 bool &NotAllSeqEqualButKnownSafe,
Michael Gottesman323964c2013-04-18 05:39:45 +00001166 bool &ShouldContinue) {
1167 switch (SuccSSeq) {
1168 case S_CanRelease: {
Michael Gottesman93132252013-06-21 06:59:02 +00001169 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe) {
Michael Gottesman323964c2013-04-18 05:39:45 +00001170 S.ClearSequenceProgress();
1171 break;
1172 }
Michael Gottesman2f294592013-06-21 19:12:36 +00001173 S.SetCFGHazardAfflicted(true);
Michael Gottesman323964c2013-04-18 05:39:45 +00001174 ShouldContinue = true;
1175 break;
1176 }
1177 case S_Use:
1178 SomeSuccHasSame = true;
1179 break;
1180 case S_Stop:
1181 case S_Release:
1182 case S_MovableRelease:
Michael Gottesman93132252013-06-21 06:59:02 +00001183 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe)
Michael Gottesman323964c2013-04-18 05:39:45 +00001184 AllSuccsHaveSame = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001185 else
1186 NotAllSeqEqualButKnownSafe = true;
Michael Gottesman323964c2013-04-18 05:39:45 +00001187 break;
1188 case S_Retain:
1189 llvm_unreachable("bottom-up pointer in retain state!");
1190 case S_None:
1191 llvm_unreachable("This should have been handled earlier.");
1192 }
1193}
1194
1195/// If we have a Top Down pointer in the S_CanRelease state, make sure that
1196/// there are no CFG hazards by checking the states of various bottom up
1197/// pointers.
1198static void CheckForCanReleaseCFGHazard(const Sequence SuccSSeq,
1199 const bool SuccSRRIKnownSafe,
1200 PtrState &S,
1201 bool &SomeSuccHasSame,
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001202 bool &AllSuccsHaveSame,
1203 bool &NotAllSeqEqualButKnownSafe) {
Michael Gottesman323964c2013-04-18 05:39:45 +00001204 switch (SuccSSeq) {
1205 case S_CanRelease:
1206 SomeSuccHasSame = true;
1207 break;
1208 case S_Stop:
1209 case S_Release:
1210 case S_MovableRelease:
1211 case S_Use:
Michael Gottesman93132252013-06-21 06:59:02 +00001212 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe)
Michael Gottesman323964c2013-04-18 05:39:45 +00001213 AllSuccsHaveSame = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001214 else
1215 NotAllSeqEqualButKnownSafe = true;
Michael Gottesman323964c2013-04-18 05:39:45 +00001216 break;
1217 case S_Retain:
1218 llvm_unreachable("bottom-up pointer in retain state!");
1219 case S_None:
1220 llvm_unreachable("This should have been handled earlier.");
1221 }
1222}
1223
Michael Gottesman97e3df02013-01-14 00:35:14 +00001224/// Check for critical edges, loop boundaries, irreducible control flow, or
1225/// other CFG structures where moving code across the edge would result in it
1226/// being executed more.
John McCalld935e9c2011-06-15 23:37:01 +00001227void
1228ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
1229 DenseMap<const BasicBlock *, BBState> &BBStates,
1230 BBState &MyStates) const {
1231 // If any top-down local-use or possible-dec has a succ which is earlier in
1232 // the sequence, forget it.
Dan Gohman55b06742012-03-02 01:13:53 +00001233 for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
Michael Gottesman323964c2013-04-18 05:39:45 +00001234 E = MyStates.top_down_ptr_end(); I != E; ++I) {
1235 PtrState &S = I->second;
1236 const Sequence Seq = I->second.GetSeq();
Dan Gohman0155f302012-02-17 18:59:53 +00001237
Michael Gottesman323964c2013-04-18 05:39:45 +00001238 // We only care about S_Retain, S_CanRelease, and S_Use.
1239 if (Seq == S_None)
1240 continue;
Dan Gohman0155f302012-02-17 18:59:53 +00001241
Michael Gottesman323964c2013-04-18 05:39:45 +00001242 // Make sure that if extra top down states are added in the future that this
1243 // code is updated to handle it.
1244 assert((Seq == S_Retain || Seq == S_CanRelease || Seq == S_Use) &&
1245 "Unknown top down sequence state.");
1246
1247 const Value *Arg = I->first;
1248 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
1249 bool SomeSuccHasSame = false;
1250 bool AllSuccsHaveSame = true;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001251 bool NotAllSeqEqualButKnownSafe = false;
Michael Gottesman323964c2013-04-18 05:39:45 +00001252
1253 succ_const_iterator SI(TI), SE(TI, false);
1254
1255 for (; SI != SE; ++SI) {
1256 // If VisitBottomUp has pointer information for this successor, take
1257 // what we know about it.
1258 const DenseMap<const BasicBlock *, BBState>::iterator BBI =
1259 BBStates.find(*SI);
1260 assert(BBI != BBStates.end());
1261 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
1262 const Sequence SuccSSeq = SuccS.GetSeq();
1263
1264 // If bottom up, the pointer is in an S_None state, clear the sequence
1265 // progress since the sequence in the bottom up state finished
1266 // suggesting a mismatch in between retains/releases. This is true for
1267 // all three cases that we are handling here: S_Retain, S_Use, and
1268 // S_CanRelease.
1269 if (SuccSSeq == S_None) {
Dan Gohman12130272011-08-12 00:26:31 +00001270 S.ClearSequenceProgress();
Michael Gottesman323964c2013-04-18 05:39:45 +00001271 continue;
1272 }
1273
1274 // If we have S_Use or S_CanRelease, perform our check for cfg hazard
1275 // checks.
Michael Gottesman93132252013-06-21 06:59:02 +00001276 const bool SuccSRRIKnownSafe = SuccS.IsKnownSafe();
Michael Gottesman323964c2013-04-18 05:39:45 +00001277
1278 // *NOTE* We do not use Seq from above here since we are allowing for
1279 // S.GetSeq() to change while we are visiting basic blocks.
1280 switch(S.GetSeq()) {
1281 case S_Use: {
1282 bool ShouldContinue = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001283 CheckForUseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S, SomeSuccHasSame,
1284 AllSuccsHaveSame, NotAllSeqEqualButKnownSafe,
Michael Gottesman323964c2013-04-18 05:39:45 +00001285 ShouldContinue);
1286 if (ShouldContinue)
1287 continue;
1288 break;
1289 }
1290 case S_CanRelease: {
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001291 CheckForCanReleaseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S,
1292 SomeSuccHasSame, AllSuccsHaveSame,
1293 NotAllSeqEqualButKnownSafe);
Michael Gottesman323964c2013-04-18 05:39:45 +00001294 break;
1295 }
1296 case S_Retain:
1297 case S_None:
1298 case S_Stop:
1299 case S_Release:
1300 case S_MovableRelease:
1301 break;
1302 }
John McCalld935e9c2011-06-15 23:37:01 +00001303 }
Michael Gottesman323964c2013-04-18 05:39:45 +00001304
1305 // If the state at the other end of any of the successor edges
1306 // matches the current state, require all edges to match. This
1307 // guards against loops in the middle of a sequence.
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001308 if (SomeSuccHasSame && !AllSuccsHaveSame) {
Michael Gottesman323964c2013-04-18 05:39:45 +00001309 S.ClearSequenceProgress();
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001310 } else if (NotAllSeqEqualButKnownSafe) {
1311 // If we would have cleared the state foregoing the fact that we are known
1312 // safe, stop code motion. This is because whether or not it is safe to
1313 // remove RR pairs via KnownSafe is an orthogonal concept to whether we
1314 // are allowed to perform code motion.
Michael Gottesman2f294592013-06-21 19:12:36 +00001315 S.SetCFGHazardAfflicted(true);
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001316 }
Michael Gottesman323964c2013-04-18 05:39:45 +00001317 }
John McCalld935e9c2011-06-15 23:37:01 +00001318}
1319
Michael Gottesman0be69202015-03-05 23:28:58 +00001320bool ObjCARCOpt::VisitInstructionBottomUp(
1321 Instruction *Inst, BasicBlock *BB, BlotMapVector<Value *, RRInfo> &Retains,
1322 BBState &MyStates) {
Dan Gohman817a7c62012-03-22 18:24:56 +00001323 bool NestingDetected = false;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001324 ARCInstKind Class = GetARCInstKind(Inst);
Craig Topperf40110f2014-04-25 05:29:35 +00001325 const Value *Arg = nullptr;
Michael Gottesman79249972013-04-05 23:46:45 +00001326
Michael Gottesman1d8d2572013-04-05 22:54:28 +00001327 DEBUG(dbgs() << "Class: " << Class << "\n");
Michael Gottesman79249972013-04-05 23:46:45 +00001328
Dan Gohman817a7c62012-03-22 18:24:56 +00001329 switch (Class) {
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001330 case ARCInstKind::Release: {
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001331 Arg = GetArgRCIdentityRoot(Inst);
Dan Gohman817a7c62012-03-22 18:24:56 +00001332
1333 PtrState &S = MyStates.getPtrBottomUpState(Arg);
1334
1335 // If we see two releases in a row on the same pointer. If so, make
1336 // a note, and we'll cicle back to revisit it after we've
1337 // hopefully eliminated the second release, which may allow us to
1338 // eliminate the first release too.
1339 // Theoretically we could implement removal of nested retain+release
1340 // pairs by making PtrState hold a stack of states, but this is
1341 // simple and avoids adding overhead for the non-nested case.
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001342 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001343 DEBUG(dbgs() << "Found nested releases (i.e. a release pair)\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00001344 NestingDetected = true;
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001345 }
Dan Gohman817a7c62012-03-22 18:24:56 +00001346
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001347 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001348 Sequence NewSeq = ReleaseMetadata ? S_MovableRelease : S_Release;
1349 ANNOTATE_BOTTOMUP(Inst, Arg, S.GetSeq(), NewSeq);
1350 S.ResetSequenceProgress(NewSeq);
Michael Gottesmanf701d3f2013-06-21 07:03:07 +00001351 S.SetReleaseMetadata(ReleaseMetadata);
Michael Gottesman93132252013-06-21 06:59:02 +00001352 S.SetKnownSafe(S.HasKnownPositiveRefCount());
Michael Gottesmanb82a1792013-06-21 07:00:44 +00001353 S.SetTailCallRelease(cast<CallInst>(Inst)->isTailCall());
Michael Gottesman4f6ef112013-06-21 19:44:27 +00001354 S.InsertCall(Inst);
Dan Gohmandf476e52012-09-04 23:16:20 +00001355 S.SetKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001356 break;
1357 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001358 case ARCInstKind::RetainBlock:
Michael Gottesman158fdf62013-03-28 20:11:19 +00001359 // In OptimizeIndividualCalls, we have strength reduced all optimizable
1360 // objc_retainBlocks to objc_retains. Thus at this point any
1361 // objc_retainBlocks that we see are not optimizable.
1362 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001363 case ARCInstKind::Retain:
1364 case ARCInstKind::RetainRV: {
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001365 Arg = GetArgRCIdentityRoot(Inst);
Dan Gohman817a7c62012-03-22 18:24:56 +00001366
1367 PtrState &S = MyStates.getPtrBottomUpState(Arg);
Dan Gohman62079b42012-04-25 00:50:46 +00001368 S.SetKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001369
Michael Gottesman81b1d432013-03-26 00:42:04 +00001370 Sequence OldSeq = S.GetSeq();
1371 switch (OldSeq) {
Dan Gohman817a7c62012-03-22 18:24:56 +00001372 case S_Stop:
1373 case S_Release:
1374 case S_MovableRelease:
1375 case S_Use:
Michael Gottesman1d8d2572013-04-05 22:54:28 +00001376 // If OldSeq is not S_Use or OldSeq is S_Use and we are tracking an
1377 // imprecise release, clear our reverse insertion points.
Michael Gottesmanf0401182013-06-21 19:12:38 +00001378 if (OldSeq != S_Use || S.IsTrackingImpreciseReleases())
Michael Gottesman4f6ef112013-06-21 19:44:27 +00001379 S.ClearReverseInsertPts();
Dan Gohman817a7c62012-03-22 18:24:56 +00001380 // FALL THROUGH
1381 case S_CanRelease:
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001382 // Don't do retain+release tracking for ARCInstKind::RetainRV,
1383 // because it's
Dan Gohman817a7c62012-03-22 18:24:56 +00001384 // better to let it remain as the first instruction after a call.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001385 if (Class != ARCInstKind::RetainRV)
Michael Gottesmane3943d02013-06-21 19:44:30 +00001386 Retains[Inst] = S.GetRRInfo();
Dan Gohman817a7c62012-03-22 18:24:56 +00001387 S.ClearSequenceProgress();
1388 break;
1389 case S_None:
1390 break;
1391 case S_Retain:
1392 llvm_unreachable("bottom-up pointer in retain state!");
1393 }
Michael Gottesman79249972013-04-05 23:46:45 +00001394 ANNOTATE_BOTTOMUP(Inst, Arg, OldSeq, S.GetSeq());
Michael Gottesman31ba23a2013-04-05 22:54:32 +00001395 // A retain moving bottom up can be a use.
1396 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001397 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001398 case ARCInstKind::AutoreleasepoolPop:
Dan Gohman817a7c62012-03-22 18:24:56 +00001399 // Conservatively, clear MyStates for all known pointers.
1400 MyStates.clearBottomUpPointers();
1401 return NestingDetected;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001402 case ARCInstKind::AutoreleasepoolPush:
1403 case ARCInstKind::None:
Dan Gohman817a7c62012-03-22 18:24:56 +00001404 // These are irrelevant.
1405 return NestingDetected;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001406 case ARCInstKind::User:
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001407 // If we have a store into an alloca of a pointer we are tracking, the
1408 // pointer has multiple owners implying that we must be more conservative.
1409 //
1410 // This comes up in the context of a pointer being ``KnownSafe''. In the
Alp Tokercb402912014-01-24 17:20:08 +00001411 // presence of a block being initialized, the frontend will emit the
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001412 // objc_retain on the original pointer and the release on the pointer loaded
1413 // from the alloca. The optimizer will through the provenance analysis
1414 // realize that the two are related, but since we only require KnownSafe in
1415 // one direction, will match the inner retain on the original pointer with
1416 // the guard release on the original pointer. This is fixed by ensuring that
Alp Tokercb402912014-01-24 17:20:08 +00001417 // in the presence of allocas we only unconditionally remove pointers if
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001418 // both our retain and our release are KnownSafe.
1419 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1420 if (AreAnyUnderlyingObjectsAnAlloca(SI->getPointerOperand())) {
1421 BBState::ptr_iterator I = MyStates.findPtrBottomUpState(
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001422 GetRCIdentityRoot(SI->getValueOperand()));
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001423 if (I != MyStates.bottom_up_ptr_end())
Michael Gottesman5a91bbf2013-05-24 20:44:02 +00001424 MultiOwnersSet.insert(I->first);
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001425 }
1426 }
1427 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001428 default:
1429 break;
1430 }
1431
1432 // Consider any other possible effects of this instruction on each
1433 // pointer being tracked.
1434 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
1435 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
1436 const Value *Ptr = MI->first;
1437 if (Ptr == Arg)
1438 continue; // Handled above.
1439 PtrState &S = MI->second;
1440 Sequence Seq = S.GetSeq();
1441
1442 // Check for possible releases.
1443 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001444 DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr
1445 << "\n");
Michael Gottesman764b1cf2013-03-23 05:46:19 +00001446 S.ClearKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00001447 switch (Seq) {
1448 case S_Use:
1449 S.SetSeq(S_CanRelease);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001450 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S.GetSeq());
Dan Gohman817a7c62012-03-22 18:24:56 +00001451 continue;
1452 case S_CanRelease:
1453 case S_Release:
1454 case S_MovableRelease:
1455 case S_Stop:
1456 case S_None:
1457 break;
1458 case S_Retain:
1459 llvm_unreachable("bottom-up pointer in retain state!");
1460 }
1461 }
1462
1463 // Check for possible direct uses.
1464 switch (Seq) {
1465 case S_Release:
1466 case S_MovableRelease:
1467 if (CanUse(Inst, Ptr, PA, Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001468 DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr
1469 << "\n");
Michael Gottesman4f6ef112013-06-21 19:44:27 +00001470 assert(!S.HasReverseInsertPts());
Dan Gohman5c70fad2012-03-23 17:47:54 +00001471 // If this is an invoke instruction, we're scanning it as part of
1472 // one of its successor blocks, since we can't insert code after it
1473 // in its own block, and we don't want to split critical edges.
1474 if (isa<InvokeInst>(Inst))
Michael Gottesman4f6ef112013-06-21 19:44:27 +00001475 S.InsertReverseInsertPt(BB->getFirstInsertionPt());
Dan Gohman5c70fad2012-03-23 17:47:54 +00001476 else
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001477 S.InsertReverseInsertPt(std::next(BasicBlock::iterator(Inst)));
Dan Gohman817a7c62012-03-22 18:24:56 +00001478 S.SetSeq(S_Use);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001479 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
John McCall20182ac2013-03-22 21:38:36 +00001480 } else if (Seq == S_Release && IsUser(Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001481 DEBUG(dbgs() << "PreciseReleaseUse: Seq: " << Seq << "; " << *Ptr
1482 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00001483 // Non-movable releases depend on any possible objc pointer use.
1484 S.SetSeq(S_Stop);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001485 ANNOTATE_BOTTOMUP(Inst, Ptr, S_Release, S_Stop);
Michael Gottesman4f6ef112013-06-21 19:44:27 +00001486 assert(!S.HasReverseInsertPts());
Dan Gohman5c70fad2012-03-23 17:47:54 +00001487 // As above; handle invoke specially.
1488 if (isa<InvokeInst>(Inst))
Michael Gottesman4f6ef112013-06-21 19:44:27 +00001489 S.InsertReverseInsertPt(BB->getFirstInsertionPt());
Dan Gohman5c70fad2012-03-23 17:47:54 +00001490 else
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001491 S.InsertReverseInsertPt(std::next(BasicBlock::iterator(Inst)));
Dan Gohman817a7c62012-03-22 18:24:56 +00001492 }
1493 break;
1494 case S_Stop:
Michael Gottesman81b1d432013-03-26 00:42:04 +00001495 if (CanUse(Inst, Ptr, PA, Class)) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001496 DEBUG(dbgs() << "PreciseStopUse: Seq: " << Seq << "; " << *Ptr
1497 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00001498 S.SetSeq(S_Use);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001499 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
1500 }
Dan Gohman817a7c62012-03-22 18:24:56 +00001501 break;
1502 case S_CanRelease:
1503 case S_Use:
1504 case S_None:
1505 break;
1506 case S_Retain:
1507 llvm_unreachable("bottom-up pointer in retain state!");
1508 }
1509 }
1510
1511 return NestingDetected;
1512}
1513
Michael Gottesman0be69202015-03-05 23:28:58 +00001514bool ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
1515 DenseMap<const BasicBlock *, BBState> &BBStates,
1516 BlotMapVector<Value *, RRInfo> &Retains) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001517
1518 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitBottomUp ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00001519
John McCalld935e9c2011-06-15 23:37:01 +00001520 bool NestingDetected = false;
1521 BBState &MyStates = BBStates[BB];
1522
1523 // Merge the states from each successor to compute the initial state
1524 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00001525 BBState::edge_iterator SI(MyStates.succ_begin()),
1526 SE(MyStates.succ_end());
1527 if (SI != SE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001528 const BasicBlock *Succ = *SI;
1529 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
1530 assert(I != BBStates.end());
1531 MyStates.InitFromSucc(I->second);
1532 ++SI;
1533 for (; SI != SE; ++SI) {
1534 Succ = *SI;
1535 I = BBStates.find(Succ);
1536 assert(I != BBStates.end());
1537 MyStates.MergeSucc(I->second);
1538 }
Michael Gottesman60f6b282013-03-29 05:13:07 +00001539 }
Michael Gottesmancd4de0f2013-03-26 00:42:09 +00001540
Michael Gottesman43e7e002013-04-03 22:41:59 +00001541 // If ARC Annotations are enabled, output the current state of pointers at the
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00001542 // bottom of the basic block.
Michael Gottesman43e7e002013-04-03 22:41:59 +00001543 ANNOTATE_BOTTOMUP_BBEND(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00001544
John McCalld935e9c2011-06-15 23:37:01 +00001545 // Visit all the instructions, bottom-up.
1546 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001547 Instruction *Inst = std::prev(I);
Dan Gohman5c70fad2012-03-23 17:47:54 +00001548
1549 // Invoke instructions are visited as part of their successors (below).
1550 if (isa<InvokeInst>(Inst))
1551 continue;
1552
Michael Gottesman89279f82013-04-05 18:10:41 +00001553 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001554
Dan Gohman5c70fad2012-03-23 17:47:54 +00001555 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
1556 }
1557
Dan Gohmandae33492012-04-27 18:56:31 +00001558 // If there's a predecessor with an invoke, visit the invoke as if it were
1559 // part of this block, since we can't insert code after an invoke in its own
1560 // block, and we don't want to split critical edges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001561 for (BBState::edge_iterator PI(MyStates.pred_begin()),
1562 PE(MyStates.pred_end()); PI != PE; ++PI) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00001563 BasicBlock *Pred = *PI;
Dan Gohmandae33492012-04-27 18:56:31 +00001564 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
1565 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
Dan Gohman817a7c62012-03-22 18:24:56 +00001566 }
John McCalld935e9c2011-06-15 23:37:01 +00001567
Michael Gottesman43e7e002013-04-03 22:41:59 +00001568 // If ARC Annotations are enabled, output the current state of pointers at the
1569 // top of the basic block.
1570 ANNOTATE_BOTTOMUP_BBSTART(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00001571
Dan Gohman817a7c62012-03-22 18:24:56 +00001572 return NestingDetected;
1573}
John McCalld935e9c2011-06-15 23:37:01 +00001574
Dan Gohman817a7c62012-03-22 18:24:56 +00001575bool
1576ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
1577 DenseMap<Value *, RRInfo> &Releases,
1578 BBState &MyStates) {
1579 bool NestingDetected = false;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001580 ARCInstKind Class = GetARCInstKind(Inst);
Craig Topperf40110f2014-04-25 05:29:35 +00001581 const Value *Arg = nullptr;
John McCalld935e9c2011-06-15 23:37:01 +00001582
Dan Gohman817a7c62012-03-22 18:24:56 +00001583 switch (Class) {
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001584 case ARCInstKind::RetainBlock:
Michael Gottesman158fdf62013-03-28 20:11:19 +00001585 // In OptimizeIndividualCalls, we have strength reduced all optimizable
1586 // objc_retainBlocks to objc_retains. Thus at this point any
1587 // objc_retainBlocks that we see are not optimizable.
1588 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001589 case ARCInstKind::Retain:
1590 case ARCInstKind::RetainRV: {
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001591 Arg = GetArgRCIdentityRoot(Inst);
Dan Gohman817a7c62012-03-22 18:24:56 +00001592
1593 PtrState &S = MyStates.getPtrTopDownState(Arg);
1594
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001595 // Don't do retain+release tracking for ARCInstKind::RetainRV, because
1596 // it's
Dan Gohman817a7c62012-03-22 18:24:56 +00001597 // better to let it remain as the first instruction after a call.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001598 if (Class != ARCInstKind::RetainRV) {
Dan Gohman817a7c62012-03-22 18:24:56 +00001599 // If we see two retains in a row on the same pointer. If so, make
John McCalld935e9c2011-06-15 23:37:01 +00001600 // a note, and we'll cicle back to revisit it after we've
Dan Gohman817a7c62012-03-22 18:24:56 +00001601 // hopefully eliminated the second retain, which may allow us to
1602 // eliminate the first retain too.
John McCalld935e9c2011-06-15 23:37:01 +00001603 // Theoretically we could implement removal of nested retain+release
1604 // pairs by making PtrState hold a stack of states, but this is
1605 // simple and avoids adding overhead for the non-nested case.
Dan Gohman817a7c62012-03-22 18:24:56 +00001606 if (S.GetSeq() == S_Retain)
John McCalld935e9c2011-06-15 23:37:01 +00001607 NestingDetected = true;
1608
Michael Gottesman81b1d432013-03-26 00:42:04 +00001609 ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_Retain);
Dan Gohman62079b42012-04-25 00:50:46 +00001610 S.ResetSequenceProgress(S_Retain);
Michael Gottesman93132252013-06-21 06:59:02 +00001611 S.SetKnownSafe(S.HasKnownPositiveRefCount());
Michael Gottesman4f6ef112013-06-21 19:44:27 +00001612 S.InsertCall(Inst);
John McCalld935e9c2011-06-15 23:37:01 +00001613 }
John McCalld935e9c2011-06-15 23:37:01 +00001614
Dan Gohmandf476e52012-09-04 23:16:20 +00001615 S.SetKnownPositiveRefCount();
Dan Gohmanf64ff8e2012-07-23 19:27:31 +00001616
1617 // A retain can be a potential use; procede to the generic checking
1618 // code below.
1619 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001620 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001621 case ARCInstKind::Release: {
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001622 Arg = GetArgRCIdentityRoot(Inst);
Dan Gohman817a7c62012-03-22 18:24:56 +00001623
1624 PtrState &S = MyStates.getPtrTopDownState(Arg);
Michael Gottesman764b1cf2013-03-23 05:46:19 +00001625 S.ClearKnownPositiveRefCount();
Michael Gottesman79249972013-04-05 23:46:45 +00001626
Michael Gottesman1d8d2572013-04-05 22:54:28 +00001627 Sequence OldSeq = S.GetSeq();
Michael Gottesman79249972013-04-05 23:46:45 +00001628
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001629 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
Michael Gottesman79249972013-04-05 23:46:45 +00001630
Michael Gottesman1d8d2572013-04-05 22:54:28 +00001631 switch (OldSeq) {
Dan Gohman817a7c62012-03-22 18:24:56 +00001632 case S_Retain:
1633 case S_CanRelease:
Craig Topperf40110f2014-04-25 05:29:35 +00001634 if (OldSeq == S_Retain || ReleaseMetadata != nullptr)
Michael Gottesman4f6ef112013-06-21 19:44:27 +00001635 S.ClearReverseInsertPts();
Dan Gohman817a7c62012-03-22 18:24:56 +00001636 // FALL THROUGH
1637 case S_Use:
Michael Gottesmanf701d3f2013-06-21 07:03:07 +00001638 S.SetReleaseMetadata(ReleaseMetadata);
Michael Gottesmanb82a1792013-06-21 07:00:44 +00001639 S.SetTailCallRelease(cast<CallInst>(Inst)->isTailCall());
Michael Gottesmane3943d02013-06-21 19:44:30 +00001640 Releases[Inst] = S.GetRRInfo();
Michael Gottesman81b1d432013-03-26 00:42:04 +00001641 ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_None);
Dan Gohman817a7c62012-03-22 18:24:56 +00001642 S.ClearSequenceProgress();
1643 break;
1644 case S_None:
1645 break;
1646 case S_Stop:
1647 case S_Release:
1648 case S_MovableRelease:
1649 llvm_unreachable("top-down pointer in release state!");
1650 }
1651 break;
1652 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001653 case ARCInstKind::AutoreleasepoolPop:
Dan Gohman817a7c62012-03-22 18:24:56 +00001654 // Conservatively, clear MyStates for all known pointers.
1655 MyStates.clearTopDownPointers();
1656 return NestingDetected;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001657 case ARCInstKind::AutoreleasepoolPush:
1658 case ARCInstKind::None:
Dan Gohman817a7c62012-03-22 18:24:56 +00001659 // These are irrelevant.
1660 return NestingDetected;
1661 default:
1662 break;
1663 }
1664
1665 // Consider any other possible effects of this instruction on each
1666 // pointer being tracked.
1667 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
1668 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
1669 const Value *Ptr = MI->first;
1670 if (Ptr == Arg)
1671 continue; // Handled above.
1672 PtrState &S = MI->second;
1673 Sequence Seq = S.GetSeq();
1674
1675 // Check for possible releases.
1676 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Michael Gottesmanbab49e972013-04-05 18:26:08 +00001677 DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr
Michael Gottesman79249972013-04-05 23:46:45 +00001678 << "\n");
Michael Gottesman764b1cf2013-03-23 05:46:19 +00001679 S.ClearKnownPositiveRefCount();
John McCalld935e9c2011-06-15 23:37:01 +00001680 switch (Seq) {
Dan Gohman817a7c62012-03-22 18:24:56 +00001681 case S_Retain:
1682 S.SetSeq(S_CanRelease);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001683 ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_CanRelease);
Michael Gottesman4f6ef112013-06-21 19:44:27 +00001684 assert(!S.HasReverseInsertPts());
1685 S.InsertReverseInsertPt(Inst);
Dan Gohman817a7c62012-03-22 18:24:56 +00001686
1687 // One call can't cause a transition from S_Retain to S_CanRelease
1688 // and S_CanRelease to S_Use. If we've made the first transition,
1689 // we're done.
1690 continue;
John McCalld935e9c2011-06-15 23:37:01 +00001691 case S_Use:
Dan Gohman817a7c62012-03-22 18:24:56 +00001692 case S_CanRelease:
John McCalld935e9c2011-06-15 23:37:01 +00001693 case S_None:
1694 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001695 case S_Stop:
1696 case S_Release:
1697 case S_MovableRelease:
1698 llvm_unreachable("top-down pointer in release state!");
John McCalld935e9c2011-06-15 23:37:01 +00001699 }
1700 }
Dan Gohman817a7c62012-03-22 18:24:56 +00001701
1702 // Check for possible direct uses.
1703 switch (Seq) {
1704 case S_CanRelease:
Michael Gottesman81b1d432013-03-26 00:42:04 +00001705 if (CanUse(Inst, Ptr, PA, Class)) {
Michael Gottesmanbab49e972013-04-05 18:26:08 +00001706 DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr
1707 << "\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00001708 S.SetSeq(S_Use);
Michael Gottesman81b1d432013-03-26 00:42:04 +00001709 ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_Use);
1710 }
Dan Gohman817a7c62012-03-22 18:24:56 +00001711 break;
1712 case S_Retain:
1713 case S_Use:
1714 case S_None:
1715 break;
1716 case S_Stop:
1717 case S_Release:
1718 case S_MovableRelease:
1719 llvm_unreachable("top-down pointer in release state!");
1720 }
John McCalld935e9c2011-06-15 23:37:01 +00001721 }
1722
1723 return NestingDetected;
1724}
1725
1726bool
1727ObjCARCOpt::VisitTopDown(BasicBlock *BB,
1728 DenseMap<const BasicBlock *, BBState> &BBStates,
1729 DenseMap<Value *, RRInfo> &Releases) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001730 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitTopDown ==\n");
John McCalld935e9c2011-06-15 23:37:01 +00001731 bool NestingDetected = false;
1732 BBState &MyStates = BBStates[BB];
1733
1734 // Merge the states from each predecessor to compute the initial state
1735 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00001736 BBState::edge_iterator PI(MyStates.pred_begin()),
1737 PE(MyStates.pred_end());
1738 if (PI != PE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001739 const BasicBlock *Pred = *PI;
1740 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
1741 assert(I != BBStates.end());
1742 MyStates.InitFromPred(I->second);
1743 ++PI;
1744 for (; PI != PE; ++PI) {
1745 Pred = *PI;
1746 I = BBStates.find(Pred);
1747 assert(I != BBStates.end());
1748 MyStates.MergePred(I->second);
1749 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001750 }
John McCalld935e9c2011-06-15 23:37:01 +00001751
Michael Gottesman43e7e002013-04-03 22:41:59 +00001752 // If ARC Annotations are enabled, output the current state of pointers at the
1753 // top of the basic block.
1754 ANNOTATE_TOPDOWN_BBSTART(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00001755
John McCalld935e9c2011-06-15 23:37:01 +00001756 // Visit all the instructions, top-down.
1757 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1758 Instruction *Inst = I;
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001759
Michael Gottesman89279f82013-04-05 18:10:41 +00001760 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001761
Dan Gohman817a7c62012-03-22 18:24:56 +00001762 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00001763 }
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00001764
Michael Gottesman43e7e002013-04-03 22:41:59 +00001765 // If ARC Annotations are enabled, output the current state of pointers at the
1766 // bottom of the basic block.
1767 ANNOTATE_TOPDOWN_BBEND(MyStates, BB);
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00001768
Michael Gottesmanffef24f2013-04-17 20:48:01 +00001769#ifdef ARC_ANNOTATIONS
Michael Gottesmanadb921a2013-04-17 21:03:53 +00001770 if (!(EnableARCAnnotations && DisableCheckForCFGHazards))
Michael Gottesmanffef24f2013-04-17 20:48:01 +00001771#endif
John McCalld935e9c2011-06-15 23:37:01 +00001772 CheckForCFGHazards(BB, BBStates, MyStates);
1773 return NestingDetected;
1774}
1775
Dan Gohmana53a12c2011-12-12 19:42:25 +00001776static void
1777ComputePostOrders(Function &F,
1778 SmallVectorImpl<BasicBlock *> &PostOrder,
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001779 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
1780 unsigned NoObjCARCExceptionsMDKind,
1781 DenseMap<const BasicBlock *, BBState> &BBStates) {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001782 /// The visited set, for doing DFS walks.
Dan Gohmana53a12c2011-12-12 19:42:25 +00001783 SmallPtrSet<BasicBlock *, 16> Visited;
1784
1785 // Do DFS, computing the PostOrder.
1786 SmallPtrSet<BasicBlock *, 16> OnStack;
1787 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001788
1789 // Functions always have exactly one entry block, and we don't have
1790 // any other block that we treat like an entry block.
Dan Gohmana53a12c2011-12-12 19:42:25 +00001791 BasicBlock *EntryBB = &F.getEntryBlock();
Dan Gohman41375a32012-05-08 23:39:44 +00001792 BBState &MyStates = BBStates[EntryBB];
1793 MyStates.SetAsEntry();
1794 TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
1795 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
Dan Gohmana53a12c2011-12-12 19:42:25 +00001796 Visited.insert(EntryBB);
1797 OnStack.insert(EntryBB);
1798 do {
1799 dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001800 BasicBlock *CurrBB = SuccStack.back().first;
1801 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
1802 succ_iterator SE(TI, false);
Dan Gohman41375a32012-05-08 23:39:44 +00001803
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001804 while (SuccStack.back().second != SE) {
1805 BasicBlock *SuccBB = *SuccStack.back().second++;
David Blaikie70573dc2014-11-19 07:49:26 +00001806 if (Visited.insert(SuccBB).second) {
Dan Gohman41375a32012-05-08 23:39:44 +00001807 TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
1808 SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001809 BBStates[CurrBB].addSucc(SuccBB);
Dan Gohman41375a32012-05-08 23:39:44 +00001810 BBState &SuccStates = BBStates[SuccBB];
1811 SuccStates.addPred(CurrBB);
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001812 OnStack.insert(SuccBB);
Dan Gohmana53a12c2011-12-12 19:42:25 +00001813 goto dfs_next_succ;
1814 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001815
1816 if (!OnStack.count(SuccBB)) {
1817 BBStates[CurrBB].addSucc(SuccBB);
1818 BBStates[SuccBB].addPred(CurrBB);
1819 }
Dan Gohmana53a12c2011-12-12 19:42:25 +00001820 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001821 OnStack.erase(CurrBB);
1822 PostOrder.push_back(CurrBB);
1823 SuccStack.pop_back();
Dan Gohmana53a12c2011-12-12 19:42:25 +00001824 } while (!SuccStack.empty());
1825
1826 Visited.clear();
1827
Dan Gohmana53a12c2011-12-12 19:42:25 +00001828 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001829 // Functions may have many exits, and there also blocks which we treat
1830 // as exits due to ignored edges.
1831 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
1832 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
1833 BasicBlock *ExitBB = I;
1834 BBState &MyStates = BBStates[ExitBB];
1835 if (!MyStates.isExit())
1836 continue;
1837
Dan Gohmandae33492012-04-27 18:56:31 +00001838 MyStates.SetAsExit();
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001839
1840 PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00001841 Visited.insert(ExitBB);
1842 while (!PredStack.empty()) {
1843 reverse_dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001844 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
1845 while (PredStack.back().second != PE) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00001846 BasicBlock *BB = *PredStack.back().second++;
David Blaikie70573dc2014-11-19 07:49:26 +00001847 if (Visited.insert(BB).second) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001848 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00001849 goto reverse_dfs_next_succ;
1850 }
1851 }
1852 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
1853 }
1854 }
1855}
1856
Michael Gottesman97e3df02013-01-14 00:35:14 +00001857// Visit the function both top-down and bottom-up.
Michael Gottesman0be69202015-03-05 23:28:58 +00001858bool ObjCARCOpt::Visit(Function &F,
1859 DenseMap<const BasicBlock *, BBState> &BBStates,
1860 BlotMapVector<Value *, RRInfo> &Retains,
1861 DenseMap<Value *, RRInfo> &Releases) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00001862
1863 // Use reverse-postorder traversals, because we magically know that loops
1864 // will be well behaved, i.e. they won't repeatedly call retain on a single
1865 // pointer without doing a release. We can't use the ReversePostOrderTraversal
1866 // class here because we want the reverse-CFG postorder to consider each
1867 // function exit point, and we want to ignore selected cycle edges.
1868 SmallVector<BasicBlock *, 16> PostOrder;
1869 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001870 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
1871 NoObjCARCExceptionsMDKind,
1872 BBStates);
Dan Gohmana53a12c2011-12-12 19:42:25 +00001873
1874 // Use reverse-postorder on the reverse CFG for bottom-up.
John McCalld935e9c2011-06-15 23:37:01 +00001875 bool BottomUpNestingDetected = false;
Dan Gohmanc57b58c2011-08-18 21:27:42 +00001876 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
Dan Gohmana53a12c2011-12-12 19:42:25 +00001877 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
1878 I != E; ++I)
1879 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
John McCalld935e9c2011-06-15 23:37:01 +00001880
Dan Gohmana53a12c2011-12-12 19:42:25 +00001881 // Use reverse-postorder for top-down.
John McCalld935e9c2011-06-15 23:37:01 +00001882 bool TopDownNestingDetected = false;
Dan Gohmana53a12c2011-12-12 19:42:25 +00001883 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
1884 PostOrder.rbegin(), E = PostOrder.rend();
1885 I != E; ++I)
1886 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
John McCalld935e9c2011-06-15 23:37:01 +00001887
1888 return TopDownNestingDetected && BottomUpNestingDetected;
1889}
1890
Michael Gottesman97e3df02013-01-14 00:35:14 +00001891/// Move the calls in RetainsToMove and ReleasesToMove.
Michael Gottesman0be69202015-03-05 23:28:58 +00001892void ObjCARCOpt::MoveCalls(Value *Arg, RRInfo &RetainsToMove,
John McCalld935e9c2011-06-15 23:37:01 +00001893 RRInfo &ReleasesToMove,
Michael Gottesman0be69202015-03-05 23:28:58 +00001894 BlotMapVector<Value *, RRInfo> &Retains,
John McCalld935e9c2011-06-15 23:37:01 +00001895 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman6320f522011-07-22 22:29:21 +00001896 SmallVectorImpl<Instruction *> &DeadInsts,
Michael Gottesman79249972013-04-05 23:46:45 +00001897 Module *M) {
Chris Lattner229907c2011-07-18 04:54:35 +00001898 Type *ArgTy = Arg->getType();
Dan Gohman6320f522011-07-22 22:29:21 +00001899 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
Michael Gottesman79249972013-04-05 23:46:45 +00001900
Michael Gottesman89279f82013-04-05 18:10:41 +00001901 DEBUG(dbgs() << "== ObjCARCOpt::MoveCalls ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00001902
John McCalld935e9c2011-06-15 23:37:01 +00001903 // Insert the new retain and release calls.
Craig Topper46276792014-08-24 23:23:06 +00001904 for (Instruction *InsertPt : ReleasesToMove.ReverseInsertPts) {
John McCalld935e9c2011-06-15 23:37:01 +00001905 Value *MyArg = ArgTy == ParamTy ? Arg :
1906 new BitCastInst(Arg, ParamTy, "", InsertPt);
Michael Gottesman14acfac2013-07-06 01:39:23 +00001907 Constant *Decl = EP.get(ARCRuntimeEntryPoints::EPT_Retain);
1908 CallInst *Call = CallInst::Create(Decl, MyArg, "", InsertPt);
John McCalld935e9c2011-06-15 23:37:01 +00001909 Call->setDoesNotThrow();
Michael Gottesmanba648592013-03-28 23:08:44 +00001910 Call->setTailCall();
Michael Gottesman60f6b282013-03-29 05:13:07 +00001911
Michael Gottesmandf110ac2013-04-21 00:30:50 +00001912 DEBUG(dbgs() << "Inserting new Retain: " << *Call << "\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00001913 "At insertion point: " << *InsertPt << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001914 }
Craig Topper46276792014-08-24 23:23:06 +00001915 for (Instruction *InsertPt : RetainsToMove.ReverseInsertPts) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00001916 Value *MyArg = ArgTy == ParamTy ? Arg :
1917 new BitCastInst(Arg, ParamTy, "", InsertPt);
Michael Gottesman14acfac2013-07-06 01:39:23 +00001918 Constant *Decl = EP.get(ARCRuntimeEntryPoints::EPT_Release);
1919 CallInst *Call = CallInst::Create(Decl, MyArg, "", InsertPt);
Dan Gohman5c70fad2012-03-23 17:47:54 +00001920 // Attach a clang.imprecise_release metadata tag, if appropriate.
1921 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
1922 Call->setMetadata(ImpreciseReleaseMDKind, M);
1923 Call->setDoesNotThrow();
1924 if (ReleasesToMove.IsTailCallRelease)
1925 Call->setTailCall();
Michael Gottesmanc189a392013-01-09 19:23:24 +00001926
Michael Gottesman89279f82013-04-05 18:10:41 +00001927 DEBUG(dbgs() << "Inserting new Release: " << *Call << "\n"
1928 "At insertion point: " << *InsertPt << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001929 }
1930
1931 // Delete the original retain and release calls.
Craig Topper46276792014-08-24 23:23:06 +00001932 for (Instruction *OrigRetain : RetainsToMove.Calls) {
John McCalld935e9c2011-06-15 23:37:01 +00001933 Retains.blot(OrigRetain);
1934 DeadInsts.push_back(OrigRetain);
Michael Gottesman89279f82013-04-05 18:10:41 +00001935 DEBUG(dbgs() << "Deleting retain: " << *OrigRetain << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001936 }
Craig Topper46276792014-08-24 23:23:06 +00001937 for (Instruction *OrigRelease : ReleasesToMove.Calls) {
John McCalld935e9c2011-06-15 23:37:01 +00001938 Releases.erase(OrigRelease);
1939 DeadInsts.push_back(OrigRelease);
Michael Gottesman89279f82013-04-05 18:10:41 +00001940 DEBUG(dbgs() << "Deleting release: " << *OrigRelease << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001941 }
Michael Gottesman79249972013-04-05 23:46:45 +00001942
John McCalld935e9c2011-06-15 23:37:01 +00001943}
1944
Michael Gottesman0be69202015-03-05 23:28:58 +00001945bool ObjCARCOpt::ConnectTDBUTraversals(
1946 DenseMap<const BasicBlock *, BBState> &BBStates,
1947 BlotMapVector<Value *, RRInfo> &Retains,
1948 DenseMap<Value *, RRInfo> &Releases, Module *M,
1949 SmallVectorImpl<Instruction *> &NewRetains,
1950 SmallVectorImpl<Instruction *> &NewReleases,
1951 SmallVectorImpl<Instruction *> &DeadInsts, RRInfo &RetainsToMove,
1952 RRInfo &ReleasesToMove, Value *Arg, bool KnownSafe,
1953 bool &AnyPairsCompletelyEliminated) {
Michael Gottesman9de6f962013-01-22 21:49:00 +00001954 // If a pair happens in a region where it is known that the reference count
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001955 // is already incremented, we can similarly ignore possible decrements unless
1956 // we are dealing with a retainable object with multiple provenance sources.
Michael Gottesman9de6f962013-01-22 21:49:00 +00001957 bool KnownSafeTD = true, KnownSafeBU = true;
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001958 bool MultipleOwners = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001959 bool CFGHazardAfflicted = false;
Michael Gottesman9de6f962013-01-22 21:49:00 +00001960
1961 // Connect the dots between the top-down-collected RetainsToMove and
1962 // bottom-up-collected ReleasesToMove to form sets of related calls.
1963 // This is an iterative process so that we connect multiple releases
1964 // to multiple retains if needed.
1965 unsigned OldDelta = 0;
1966 unsigned NewDelta = 0;
1967 unsigned OldCount = 0;
1968 unsigned NewCount = 0;
1969 bool FirstRelease = true;
Michael Gottesman9de6f962013-01-22 21:49:00 +00001970 for (;;) {
1971 for (SmallVectorImpl<Instruction *>::const_iterator
1972 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
1973 Instruction *NewRetain = *NI;
Michael Gottesman0be69202015-03-05 23:28:58 +00001974 BlotMapVector<Value *, RRInfo>::const_iterator It =
1975 Retains.find(NewRetain);
Michael Gottesman9de6f962013-01-22 21:49:00 +00001976 assert(It != Retains.end());
1977 const RRInfo &NewRetainRRI = It->second;
1978 KnownSafeTD &= NewRetainRRI.KnownSafe;
Michael Gottesman5a91bbf2013-05-24 20:44:02 +00001979 MultipleOwners =
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001980 MultipleOwners || MultiOwnersSet.count(GetArgRCIdentityRoot(NewRetain));
Craig Topper46276792014-08-24 23:23:06 +00001981 for (Instruction *NewRetainRelease : NewRetainRRI.Calls) {
Michael Gottesman9de6f962013-01-22 21:49:00 +00001982 DenseMap<Value *, RRInfo>::const_iterator Jt =
1983 Releases.find(NewRetainRelease);
1984 if (Jt == Releases.end())
1985 return false;
1986 const RRInfo &NewRetainReleaseRRI = Jt->second;
Michael Gottesman24b2f6f2013-11-05 16:02:40 +00001987
1988 // If the release does not have a reference to the retain as well,
1989 // something happened which is unaccounted for. Do not do anything.
1990 //
1991 // This can happen if we catch an additive overflow during path count
1992 // merging.
1993 if (!NewRetainReleaseRRI.Calls.count(NewRetain))
1994 return false;
1995
David Blaikie70573dc2014-11-19 07:49:26 +00001996 if (ReleasesToMove.Calls.insert(NewRetainRelease).second) {
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001997
1998 // If we overflow when we compute the path count, don't remove/move
1999 // anything.
2000 const BBState &NRRBBState = BBStates[NewRetainRelease->getParent()];
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00002001 unsigned PathCount = BBState::OverflowOccurredValue;
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002002 if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
2003 return false;
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00002004 assert(PathCount != BBState::OverflowOccurredValue &&
2005 "PathCount at this point can not be "
2006 "OverflowOccurredValue.");
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002007 OldDelta -= PathCount;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002008
2009 // Merge the ReleaseMetadata and IsTailCallRelease values.
2010 if (FirstRelease) {
2011 ReleasesToMove.ReleaseMetadata =
2012 NewRetainReleaseRRI.ReleaseMetadata;
2013 ReleasesToMove.IsTailCallRelease =
2014 NewRetainReleaseRRI.IsTailCallRelease;
2015 FirstRelease = false;
2016 } else {
2017 if (ReleasesToMove.ReleaseMetadata !=
2018 NewRetainReleaseRRI.ReleaseMetadata)
Craig Topperf40110f2014-04-25 05:29:35 +00002019 ReleasesToMove.ReleaseMetadata = nullptr;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002020 if (ReleasesToMove.IsTailCallRelease !=
2021 NewRetainReleaseRRI.IsTailCallRelease)
2022 ReleasesToMove.IsTailCallRelease = false;
2023 }
2024
2025 // Collect the optimal insertion points.
2026 if (!KnownSafe)
Craig Topper46276792014-08-24 23:23:06 +00002027 for (Instruction *RIP : NewRetainReleaseRRI.ReverseInsertPts) {
David Blaikie70573dc2014-11-19 07:49:26 +00002028 if (ReleasesToMove.ReverseInsertPts.insert(RIP).second) {
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002029 // If we overflow when we compute the path count, don't
2030 // remove/move anything.
2031 const BBState &RIPBBState = BBStates[RIP->getParent()];
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00002032 PathCount = BBState::OverflowOccurredValue;
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002033 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
2034 return false;
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00002035 assert(PathCount != BBState::OverflowOccurredValue &&
2036 "PathCount at this point can not be "
2037 "OverflowOccurredValue.");
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002038 NewDelta -= PathCount;
2039 }
Michael Gottesman9de6f962013-01-22 21:49:00 +00002040 }
2041 NewReleases.push_back(NewRetainRelease);
2042 }
2043 }
2044 }
2045 NewRetains.clear();
2046 if (NewReleases.empty()) break;
2047
2048 // Back the other way.
2049 for (SmallVectorImpl<Instruction *>::const_iterator
2050 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
2051 Instruction *NewRelease = *NI;
2052 DenseMap<Value *, RRInfo>::const_iterator It =
2053 Releases.find(NewRelease);
2054 assert(It != Releases.end());
2055 const RRInfo &NewReleaseRRI = It->second;
2056 KnownSafeBU &= NewReleaseRRI.KnownSafe;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00002057 CFGHazardAfflicted |= NewReleaseRRI.CFGHazardAfflicted;
Craig Topper46276792014-08-24 23:23:06 +00002058 for (Instruction *NewReleaseRetain : NewReleaseRRI.Calls) {
Michael Gottesman0be69202015-03-05 23:28:58 +00002059 BlotMapVector<Value *, RRInfo>::const_iterator Jt =
2060 Retains.find(NewReleaseRetain);
Michael Gottesman9de6f962013-01-22 21:49:00 +00002061 if (Jt == Retains.end())
2062 return false;
2063 const RRInfo &NewReleaseRetainRRI = Jt->second;
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002064
Michael Gottesman24b2f6f2013-11-05 16:02:40 +00002065 // If the retain does not have a reference to the release as well,
2066 // something happened which is unaccounted for. Do not do anything.
2067 //
2068 // This can happen if we catch an additive overflow during path count
2069 // merging.
2070 if (!NewReleaseRetainRRI.Calls.count(NewRelease))
2071 return false;
2072
David Blaikie70573dc2014-11-19 07:49:26 +00002073 if (RetainsToMove.Calls.insert(NewReleaseRetain).second) {
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002074 // If we overflow when we compute the path count, don't remove/move
2075 // anything.
2076 const BBState &NRRBBState = BBStates[NewReleaseRetain->getParent()];
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00002077 unsigned PathCount = BBState::OverflowOccurredValue;
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002078 if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
2079 return false;
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00002080 assert(PathCount != BBState::OverflowOccurredValue &&
2081 "PathCount at this point can not be "
2082 "OverflowOccurredValue.");
Michael Gottesman9de6f962013-01-22 21:49:00 +00002083 OldDelta += PathCount;
2084 OldCount += PathCount;
2085
Michael Gottesman9de6f962013-01-22 21:49:00 +00002086 // Collect the optimal insertion points.
2087 if (!KnownSafe)
Craig Topper46276792014-08-24 23:23:06 +00002088 for (Instruction *RIP : NewReleaseRetainRRI.ReverseInsertPts) {
David Blaikie70573dc2014-11-19 07:49:26 +00002089 if (RetainsToMove.ReverseInsertPts.insert(RIP).second) {
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002090 // If we overflow when we compute the path count, don't
2091 // remove/move anything.
2092 const BBState &RIPBBState = BBStates[RIP->getParent()];
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00002093
2094 PathCount = BBState::OverflowOccurredValue;
Michael Gottesman9e7261c2013-06-07 06:16:49 +00002095 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
2096 return false;
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00002097 assert(PathCount != BBState::OverflowOccurredValue &&
2098 "PathCount at this point can not be "
2099 "OverflowOccurredValue.");
Michael Gottesman9de6f962013-01-22 21:49:00 +00002100 NewDelta += PathCount;
2101 NewCount += PathCount;
2102 }
2103 }
2104 NewRetains.push_back(NewReleaseRetain);
2105 }
2106 }
2107 }
2108 NewReleases.clear();
2109 if (NewRetains.empty()) break;
2110 }
2111
Michael Gottesmana76143ee2013-05-13 23:49:42 +00002112 // If the pointer is known incremented in 1 direction and we do not have
2113 // MultipleOwners, we can safely remove the retain/releases. Otherwise we need
2114 // to be known safe in both directions.
2115 bool UnconditionallySafe = (KnownSafeTD && KnownSafeBU) ||
2116 ((KnownSafeTD || KnownSafeBU) && !MultipleOwners);
2117 if (UnconditionallySafe) {
Michael Gottesman9de6f962013-01-22 21:49:00 +00002118 RetainsToMove.ReverseInsertPts.clear();
2119 ReleasesToMove.ReverseInsertPts.clear();
2120 NewCount = 0;
2121 } else {
2122 // Determine whether the new insertion points we computed preserve the
2123 // balance of retain and release calls through the program.
2124 // TODO: If the fully aggressive solution isn't valid, try to find a
2125 // less aggressive solution which is.
2126 if (NewDelta != 0)
2127 return false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00002128
2129 // At this point, we are not going to remove any RR pairs, but we still are
2130 // able to move RR pairs. If one of our pointers is afflicted with
2131 // CFGHazards, we cannot perform such code motion so exit early.
2132 const bool WillPerformCodeMotion = RetainsToMove.ReverseInsertPts.size() ||
2133 ReleasesToMove.ReverseInsertPts.size();
2134 if (CFGHazardAfflicted && WillPerformCodeMotion)
2135 return false;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002136 }
2137
2138 // Determine whether the original call points are balanced in the retain and
2139 // release calls through the program. If not, conservatively don't touch
2140 // them.
2141 // TODO: It's theoretically possible to do code motion in this case, as
2142 // long as the existing imbalances are maintained.
2143 if (OldDelta != 0)
2144 return false;
Michael Gottesman8005ad32013-04-29 06:16:55 +00002145
Michael Gottesmana87bb8f2013-04-29 05:13:13 +00002146#ifdef ARC_ANNOTATIONS
2147 // Do not move calls if ARC annotations are requested.
Michael Gottesman3e3977c2013-04-29 05:25:39 +00002148 if (EnableARCAnnotations)
2149 return false;
Michael Gottesmana87bb8f2013-04-29 05:13:13 +00002150#endif // ARC_ANNOTATIONS
Michael Gottesman9de6f962013-01-22 21:49:00 +00002151
2152 Changed = true;
2153 assert(OldCount != 0 && "Unreachable code?");
2154 NumRRs += OldCount - NewCount;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002155 // Set to true if we completely removed any RR pairs.
Michael Gottesman8b5515f2013-01-22 21:53:43 +00002156 AnyPairsCompletelyEliminated = NewCount == 0;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002157
2158 // We can move calls!
2159 return true;
2160}
2161
Michael Gottesman97e3df02013-01-14 00:35:14 +00002162/// Identify pairings between the retains and releases, and delete and/or move
2163/// them.
Michael Gottesman0be69202015-03-05 23:28:58 +00002164bool ObjCARCOpt::PerformCodePlacement(
2165 DenseMap<const BasicBlock *, BBState> &BBStates,
2166 BlotMapVector<Value *, RRInfo> &Retains,
2167 DenseMap<Value *, RRInfo> &Releases, Module *M) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002168 DEBUG(dbgs() << "\n== ObjCARCOpt::PerformCodePlacement ==\n");
2169
John McCalld935e9c2011-06-15 23:37:01 +00002170 bool AnyPairsCompletelyEliminated = false;
2171 RRInfo RetainsToMove;
2172 RRInfo ReleasesToMove;
2173 SmallVector<Instruction *, 4> NewRetains;
2174 SmallVector<Instruction *, 4> NewReleases;
2175 SmallVector<Instruction *, 8> DeadInsts;
2176
Dan Gohman670f9372012-04-13 18:57:48 +00002177 // Visit each retain.
Michael Gottesman0be69202015-03-05 23:28:58 +00002178 for (BlotMapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
2179 E = Retains.end();
2180 I != E; ++I) {
Dan Gohman2053a5d2011-09-29 22:25:23 +00002181 Value *V = I->first;
John McCalld935e9c2011-06-15 23:37:01 +00002182 if (!V) continue; // blotted
2183
2184 Instruction *Retain = cast<Instruction>(V);
Michael Gottesmanc189a392013-01-09 19:23:24 +00002185
Michael Gottesman89279f82013-04-05 18:10:41 +00002186 DEBUG(dbgs() << "Visiting: " << *Retain << "\n");
Michael Gottesmanc189a392013-01-09 19:23:24 +00002187
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00002188 Value *Arg = GetArgRCIdentityRoot(Retain);
John McCalld935e9c2011-06-15 23:37:01 +00002189
Dan Gohman728db492012-01-13 00:39:07 +00002190 // If the object being released is in static or stack storage, we know it's
John McCalld935e9c2011-06-15 23:37:01 +00002191 // not being managed by ObjC reference counting, so we can delete pairs
2192 // regardless of what possible decrements or uses lie between them.
Dan Gohman728db492012-01-13 00:39:07 +00002193 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
Dan Gohman41375a32012-05-08 23:39:44 +00002194
Dan Gohman56e1cef2011-08-22 17:29:11 +00002195 // A constant pointer can't be pointing to an object on the heap. It may
2196 // be reference-counted, but it won't be deleted.
2197 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
2198 if (const GlobalVariable *GV =
2199 dyn_cast<GlobalVariable>(
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00002200 GetRCIdentityRoot(LI->getPointerOperand())))
Dan Gohman56e1cef2011-08-22 17:29:11 +00002201 if (GV->isConstant())
2202 KnownSafe = true;
2203
John McCalld935e9c2011-06-15 23:37:01 +00002204 // Connect the dots between the top-down-collected RetainsToMove and
2205 // bottom-up-collected ReleasesToMove to form sets of related calls.
John McCalld935e9c2011-06-15 23:37:01 +00002206 NewRetains.push_back(Retain);
Michael Gottesman9de6f962013-01-22 21:49:00 +00002207 bool PerformMoveCalls =
2208 ConnectTDBUTraversals(BBStates, Retains, Releases, M, NewRetains,
2209 NewReleases, DeadInsts, RetainsToMove,
2210 ReleasesToMove, Arg, KnownSafe,
2211 AnyPairsCompletelyEliminated);
John McCalld935e9c2011-06-15 23:37:01 +00002212
Michael Gottesman9de6f962013-01-22 21:49:00 +00002213 if (PerformMoveCalls) {
2214 // Ok, everything checks out and we're all set. Let's move/delete some
2215 // code!
2216 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
2217 Retains, Releases, DeadInsts, M);
John McCalld935e9c2011-06-15 23:37:01 +00002218 }
2219
Michael Gottesman9de6f962013-01-22 21:49:00 +00002220 // Clean up state for next retain.
John McCalld935e9c2011-06-15 23:37:01 +00002221 NewReleases.clear();
2222 NewRetains.clear();
2223 RetainsToMove.clear();
2224 ReleasesToMove.clear();
2225 }
2226
2227 // Now that we're done moving everything, we can delete the newly dead
2228 // instructions, as we no longer need them as insert points.
2229 while (!DeadInsts.empty())
2230 EraseInstruction(DeadInsts.pop_back_val());
2231
2232 return AnyPairsCompletelyEliminated;
2233}
2234
Michael Gottesman97e3df02013-01-14 00:35:14 +00002235/// Weak pointer optimizations.
John McCalld935e9c2011-06-15 23:37:01 +00002236void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
Michael Gottesman89279f82013-04-05 18:10:41 +00002237 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeWeakCalls ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00002238
John McCalld935e9c2011-06-15 23:37:01 +00002239 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
2240 // itself because it uses AliasAnalysis and we need to do provenance
2241 // queries instead.
2242 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2243 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +00002244
Michael Gottesman89279f82013-04-05 18:10:41 +00002245 DEBUG(dbgs() << "Visiting: " << *Inst << "\n");
Michael Gottesman3f146e22013-01-01 16:05:48 +00002246
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002247 ARCInstKind Class = GetBasicARCInstKind(Inst);
2248 if (Class != ARCInstKind::LoadWeak &&
2249 Class != ARCInstKind::LoadWeakRetained)
John McCalld935e9c2011-06-15 23:37:01 +00002250 continue;
2251
2252 // Delete objc_loadWeak calls with no users.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002253 if (Class == ARCInstKind::LoadWeak && Inst->use_empty()) {
John McCalld935e9c2011-06-15 23:37:01 +00002254 Inst->eraseFromParent();
2255 continue;
2256 }
2257
2258 // TODO: For now, just look for an earlier available version of this value
2259 // within the same block. Theoretically, we could do memdep-style non-local
2260 // analysis too, but that would want caching. A better approach would be to
2261 // use the technique that EarlyCSE uses.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00002262 inst_iterator Current = std::prev(I);
John McCalld935e9c2011-06-15 23:37:01 +00002263 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
2264 for (BasicBlock::iterator B = CurrentBB->begin(),
2265 J = Current.getInstructionIterator();
2266 J != B; --J) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00002267 Instruction *EarlierInst = &*std::prev(J);
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002268 ARCInstKind EarlierClass = GetARCInstKind(EarlierInst);
John McCalld935e9c2011-06-15 23:37:01 +00002269 switch (EarlierClass) {
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002270 case ARCInstKind::LoadWeak:
2271 case ARCInstKind::LoadWeakRetained: {
John McCalld935e9c2011-06-15 23:37:01 +00002272 // If this is loading from the same pointer, replace this load's value
2273 // with that one.
2274 CallInst *Call = cast<CallInst>(Inst);
2275 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2276 Value *Arg = Call->getArgOperand(0);
2277 Value *EarlierArg = EarlierCall->getArgOperand(0);
2278 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2279 case AliasAnalysis::MustAlias:
2280 Changed = true;
2281 // If the load has a builtin retain, insert a plain retain for it.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002282 if (Class == ARCInstKind::LoadWeakRetained) {
Michael Gottesman14acfac2013-07-06 01:39:23 +00002283 Constant *Decl = EP.get(ARCRuntimeEntryPoints::EPT_Retain);
2284 CallInst *CI = CallInst::Create(Decl, EarlierCall, "", Call);
John McCalld935e9c2011-06-15 23:37:01 +00002285 CI->setTailCall();
2286 }
2287 // Zap the fully redundant load.
2288 Call->replaceAllUsesWith(EarlierCall);
2289 Call->eraseFromParent();
2290 goto clobbered;
2291 case AliasAnalysis::MayAlias:
2292 case AliasAnalysis::PartialAlias:
2293 goto clobbered;
2294 case AliasAnalysis::NoAlias:
2295 break;
2296 }
2297 break;
2298 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002299 case ARCInstKind::StoreWeak:
2300 case ARCInstKind::InitWeak: {
John McCalld935e9c2011-06-15 23:37:01 +00002301 // If this is storing to the same pointer and has the same size etc.
2302 // replace this load's value with the stored value.
2303 CallInst *Call = cast<CallInst>(Inst);
2304 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2305 Value *Arg = Call->getArgOperand(0);
2306 Value *EarlierArg = EarlierCall->getArgOperand(0);
2307 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2308 case AliasAnalysis::MustAlias:
2309 Changed = true;
2310 // If the load has a builtin retain, insert a plain retain for it.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002311 if (Class == ARCInstKind::LoadWeakRetained) {
Michael Gottesman14acfac2013-07-06 01:39:23 +00002312 Constant *Decl = EP.get(ARCRuntimeEntryPoints::EPT_Retain);
2313 CallInst *CI = CallInst::Create(Decl, EarlierCall, "", Call);
John McCalld935e9c2011-06-15 23:37:01 +00002314 CI->setTailCall();
2315 }
2316 // Zap the fully redundant load.
2317 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
2318 Call->eraseFromParent();
2319 goto clobbered;
2320 case AliasAnalysis::MayAlias:
2321 case AliasAnalysis::PartialAlias:
2322 goto clobbered;
2323 case AliasAnalysis::NoAlias:
2324 break;
2325 }
2326 break;
2327 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002328 case ARCInstKind::MoveWeak:
2329 case ARCInstKind::CopyWeak:
John McCalld935e9c2011-06-15 23:37:01 +00002330 // TOOD: Grab the copied value.
2331 goto clobbered;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002332 case ARCInstKind::AutoreleasepoolPush:
2333 case ARCInstKind::None:
2334 case ARCInstKind::IntrinsicUser:
2335 case ARCInstKind::User:
John McCalld935e9c2011-06-15 23:37:01 +00002336 // Weak pointers are only modified through the weak entry points
2337 // (and arbitrary calls, which could call the weak entry points).
2338 break;
2339 default:
2340 // Anything else could modify the weak pointer.
2341 goto clobbered;
2342 }
2343 }
2344 clobbered:;
2345 }
2346
2347 // Then, for each destroyWeak with an alloca operand, check to see if
2348 // the alloca and all its users can be zapped.
2349 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2350 Instruction *Inst = &*I++;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002351 ARCInstKind Class = GetBasicARCInstKind(Inst);
2352 if (Class != ARCInstKind::DestroyWeak)
John McCalld935e9c2011-06-15 23:37:01 +00002353 continue;
2354
2355 CallInst *Call = cast<CallInst>(Inst);
2356 Value *Arg = Call->getArgOperand(0);
2357 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00002358 for (User *U : Alloca->users()) {
2359 const Instruction *UserInst = cast<Instruction>(U);
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002360 switch (GetBasicARCInstKind(UserInst)) {
2361 case ARCInstKind::InitWeak:
2362 case ARCInstKind::StoreWeak:
2363 case ARCInstKind::DestroyWeak:
John McCalld935e9c2011-06-15 23:37:01 +00002364 continue;
2365 default:
2366 goto done;
2367 }
2368 }
2369 Changed = true;
Chandler Carruthcdf47882014-03-09 03:16:01 +00002370 for (auto UI = Alloca->user_begin(), UE = Alloca->user_end(); UI != UE;) {
John McCalld935e9c2011-06-15 23:37:01 +00002371 CallInst *UserInst = cast<CallInst>(*UI++);
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002372 switch (GetBasicARCInstKind(UserInst)) {
2373 case ARCInstKind::InitWeak:
2374 case ARCInstKind::StoreWeak:
Dan Gohman14862c32012-05-18 22:17:29 +00002375 // These functions return their second argument.
2376 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
2377 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002378 case ARCInstKind::DestroyWeak:
Dan Gohman14862c32012-05-18 22:17:29 +00002379 // No return value.
2380 break;
2381 default:
Dan Gohman9c97eea02012-05-21 17:41:28 +00002382 llvm_unreachable("alloca really is used!");
Dan Gohman14862c32012-05-18 22:17:29 +00002383 }
John McCalld935e9c2011-06-15 23:37:01 +00002384 UserInst->eraseFromParent();
2385 }
2386 Alloca->eraseFromParent();
2387 done:;
2388 }
2389 }
2390}
2391
Michael Gottesman97e3df02013-01-14 00:35:14 +00002392/// Identify program paths which execute sequences of retains and releases which
2393/// can be eliminated.
John McCalld935e9c2011-06-15 23:37:01 +00002394bool ObjCARCOpt::OptimizeSequences(Function &F) {
Michael Gottesman740db972013-05-23 02:35:21 +00002395 // Releases, Retains - These are used to store the results of the main flow
2396 // analysis. These use Value* as the key instead of Instruction* so that the
2397 // map stays valid when we get around to rewriting code and calls get
2398 // replaced by arguments.
John McCalld935e9c2011-06-15 23:37:01 +00002399 DenseMap<Value *, RRInfo> Releases;
Michael Gottesman0be69202015-03-05 23:28:58 +00002400 BlotMapVector<Value *, RRInfo> Retains;
John McCalld935e9c2011-06-15 23:37:01 +00002401
Michael Gottesman740db972013-05-23 02:35:21 +00002402 // This is used during the traversal of the function to track the
2403 // states for each identified object at each block.
John McCalld935e9c2011-06-15 23:37:01 +00002404 DenseMap<const BasicBlock *, BBState> BBStates;
2405
2406 // Analyze the CFG of the function, and all instructions.
2407 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
2408
2409 // Transform.
Michael Gottesman5a91bbf2013-05-24 20:44:02 +00002410 bool AnyPairsCompletelyEliminated = PerformCodePlacement(BBStates, Retains,
2411 Releases,
2412 F.getParent());
2413
2414 // Cleanup.
2415 MultiOwnersSet.clear();
2416
2417 return AnyPairsCompletelyEliminated && NestingDetected;
John McCalld935e9c2011-06-15 23:37:01 +00002418}
2419
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002420/// Check if there is a dependent call earlier that does not have anything in
2421/// between the Retain and the call that can affect the reference count of their
2422/// shared pointer argument. Note that Retain need not be in BB.
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002423static bool
2424HasSafePathToPredecessorCall(const Value *Arg, Instruction *Retain,
Craig Topper71b7b682014-08-21 05:55:13 +00002425 SmallPtrSetImpl<Instruction *> &DepInsts,
2426 SmallPtrSetImpl<const BasicBlock *> &Visited,
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002427 ProvenanceAnalysis &PA) {
2428 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
2429 DepInsts, Visited, PA);
2430 if (DepInsts.size() != 1)
2431 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002432
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002433 CallInst *Call =
2434 dyn_cast_or_null<CallInst>(*DepInsts.begin());
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002435
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002436 // Check that the pointer is the return value of the call.
2437 if (!Call || Arg != Call)
2438 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002439
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002440 // Check that the call is a regular call.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002441 ARCInstKind Class = GetBasicARCInstKind(Call);
2442 if (Class != ARCInstKind::CallOrUser && Class != ARCInstKind::Call)
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002443 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002444
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002445 return true;
2446}
2447
Michael Gottesman6908db12013-04-03 23:16:05 +00002448/// Find a dependent retain that precedes the given autorelease for which there
2449/// is nothing in between the two instructions that can affect the ref count of
2450/// Arg.
2451static CallInst *
2452FindPredecessorRetainWithSafePath(const Value *Arg, BasicBlock *BB,
2453 Instruction *Autorelease,
Craig Topper71b7b682014-08-21 05:55:13 +00002454 SmallPtrSetImpl<Instruction *> &DepInsts,
2455 SmallPtrSetImpl<const BasicBlock *> &Visited,
Michael Gottesman6908db12013-04-03 23:16:05 +00002456 ProvenanceAnalysis &PA) {
2457 FindDependencies(CanChangeRetainCount, Arg,
2458 BB, Autorelease, DepInsts, Visited, PA);
2459 if (DepInsts.size() != 1)
Craig Topperf40110f2014-04-25 05:29:35 +00002460 return nullptr;
Michael Gottesman79249972013-04-05 23:46:45 +00002461
Michael Gottesman6908db12013-04-03 23:16:05 +00002462 CallInst *Retain =
2463 dyn_cast_or_null<CallInst>(*DepInsts.begin());
Michael Gottesman79249972013-04-05 23:46:45 +00002464
Michael Gottesman6908db12013-04-03 23:16:05 +00002465 // Check that we found a retain with the same argument.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002466 if (!Retain || !IsRetain(GetBasicARCInstKind(Retain)) ||
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00002467 GetArgRCIdentityRoot(Retain) != Arg) {
Craig Topperf40110f2014-04-25 05:29:35 +00002468 return nullptr;
Michael Gottesman6908db12013-04-03 23:16:05 +00002469 }
Michael Gottesman79249972013-04-05 23:46:45 +00002470
Michael Gottesman6908db12013-04-03 23:16:05 +00002471 return Retain;
2472}
2473
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002474/// Look for an ``autorelease'' instruction dependent on Arg such that there are
2475/// no instructions dependent on Arg that need a positive ref count in between
2476/// the autorelease and the ret.
2477static CallInst *
2478FindPredecessorAutoreleaseWithSafePath(const Value *Arg, BasicBlock *BB,
2479 ReturnInst *Ret,
Craig Topper71b7b682014-08-21 05:55:13 +00002480 SmallPtrSetImpl<Instruction *> &DepInsts,
2481 SmallPtrSetImpl<const BasicBlock *> &V,
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002482 ProvenanceAnalysis &PA) {
2483 FindDependencies(NeedsPositiveRetainCount, Arg,
2484 BB, Ret, DepInsts, V, PA);
2485 if (DepInsts.size() != 1)
Craig Topperf40110f2014-04-25 05:29:35 +00002486 return nullptr;
Michael Gottesman79249972013-04-05 23:46:45 +00002487
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002488 CallInst *Autorelease =
2489 dyn_cast_or_null<CallInst>(*DepInsts.begin());
2490 if (!Autorelease)
Craig Topperf40110f2014-04-25 05:29:35 +00002491 return nullptr;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002492 ARCInstKind AutoreleaseClass = GetBasicARCInstKind(Autorelease);
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002493 if (!IsAutorelease(AutoreleaseClass))
Craig Topperf40110f2014-04-25 05:29:35 +00002494 return nullptr;
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00002495 if (GetArgRCIdentityRoot(Autorelease) != Arg)
Craig Topperf40110f2014-04-25 05:29:35 +00002496 return nullptr;
Michael Gottesman79249972013-04-05 23:46:45 +00002497
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002498 return Autorelease;
2499}
2500
Michael Gottesman97e3df02013-01-14 00:35:14 +00002501/// Look for this pattern:
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00002502/// \code
John McCalld935e9c2011-06-15 23:37:01 +00002503/// %call = call i8* @something(...)
2504/// %2 = call i8* @objc_retain(i8* %call)
2505/// %3 = call i8* @objc_autorelease(i8* %2)
2506/// ret i8* %3
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00002507/// \endcode
John McCalld935e9c2011-06-15 23:37:01 +00002508/// And delete the retain and autorelease.
John McCalld935e9c2011-06-15 23:37:01 +00002509void ObjCARCOpt::OptimizeReturns(Function &F) {
2510 if (!F.getReturnType()->isPointerTy())
2511 return;
Michael Gottesman79249972013-04-05 23:46:45 +00002512
Michael Gottesman89279f82013-04-05 18:10:41 +00002513 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeReturns ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00002514
John McCalld935e9c2011-06-15 23:37:01 +00002515 SmallPtrSet<Instruction *, 4> DependingInstructions;
2516 SmallPtrSet<const BasicBlock *, 4> Visited;
2517 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
2518 BasicBlock *BB = FI;
2519 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
Michael Gottesman3f146e22013-01-01 16:05:48 +00002520
Michael Gottesman89279f82013-04-05 18:10:41 +00002521 DEBUG(dbgs() << "Visiting: " << *Ret << "\n");
Michael Gottesman3f146e22013-01-01 16:05:48 +00002522
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002523 if (!Ret)
2524 continue;
Michael Gottesman79249972013-04-05 23:46:45 +00002525
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00002526 const Value *Arg = GetRCIdentityRoot(Ret->getOperand(0));
Michael Gottesman79249972013-04-05 23:46:45 +00002527
Michael Gottesmancdb7c152013-04-21 00:25:04 +00002528 // Look for an ``autorelease'' instruction that is a predecessor of Ret and
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002529 // dependent on Arg such that there are no instructions dependent on Arg
2530 // that need a positive ref count in between the autorelease and Ret.
2531 CallInst *Autorelease =
2532 FindPredecessorAutoreleaseWithSafePath(Arg, BB, Ret,
2533 DependingInstructions, Visited,
2534 PA);
John McCalld935e9c2011-06-15 23:37:01 +00002535 DependingInstructions.clear();
2536 Visited.clear();
Michael Gottesmanfb9ece92013-04-21 00:25:01 +00002537
2538 if (!Autorelease)
2539 continue;
2540
2541 CallInst *Retain =
2542 FindPredecessorRetainWithSafePath(Arg, BB, Autorelease,
2543 DependingInstructions, Visited, PA);
2544 DependingInstructions.clear();
2545 Visited.clear();
2546
2547 if (!Retain)
2548 continue;
2549
2550 // Check that there is nothing that can affect the reference count
2551 // between the retain and the call. Note that Retain need not be in BB.
2552 bool HasSafePathToCall = HasSafePathToPredecessorCall(Arg, Retain,
2553 DependingInstructions,
2554 Visited, PA);
2555 DependingInstructions.clear();
2556 Visited.clear();
2557
2558 if (!HasSafePathToCall)
2559 continue;
2560
2561 // If so, we can zap the retain and autorelease.
2562 Changed = true;
2563 ++NumRets;
2564 DEBUG(dbgs() << "Erasing: " << *Retain << "\nErasing: "
2565 << *Autorelease << "\n");
2566 EraseInstruction(Retain);
2567 EraseInstruction(Autorelease);
John McCalld935e9c2011-06-15 23:37:01 +00002568 }
2569}
2570
Michael Gottesman9c118152013-04-29 06:16:57 +00002571#ifndef NDEBUG
2572void
2573ObjCARCOpt::GatherStatistics(Function &F, bool AfterOptimization) {
2574 llvm::Statistic &NumRetains =
2575 AfterOptimization? NumRetainsAfterOpt : NumRetainsBeforeOpt;
2576 llvm::Statistic &NumReleases =
2577 AfterOptimization? NumReleasesAfterOpt : NumReleasesBeforeOpt;
2578
2579 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2580 Instruction *Inst = &*I++;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002581 switch (GetBasicARCInstKind(Inst)) {
Michael Gottesman9c118152013-04-29 06:16:57 +00002582 default:
2583 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002584 case ARCInstKind::Retain:
Michael Gottesman9c118152013-04-29 06:16:57 +00002585 ++NumRetains;
2586 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002587 case ARCInstKind::Release:
Michael Gottesman9c118152013-04-29 06:16:57 +00002588 ++NumReleases;
2589 break;
2590 }
2591 }
2592}
2593#endif
2594
John McCalld935e9c2011-06-15 23:37:01 +00002595bool ObjCARCOpt::doInitialization(Module &M) {
2596 if (!EnableARCOpts)
2597 return false;
2598
Dan Gohman670f9372012-04-13 18:57:48 +00002599 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanceaac7c2011-06-20 23:20:43 +00002600 Run = ModuleHasARC(M);
2601 if (!Run)
2602 return false;
2603
John McCalld935e9c2011-06-15 23:37:01 +00002604 // Identify the imprecise release metadata kind.
2605 ImpreciseReleaseMDKind =
2606 M.getContext().getMDKindID("clang.imprecise_release");
Dan Gohmana7107f92011-10-17 22:53:25 +00002607 CopyOnEscapeMDKind =
2608 M.getContext().getMDKindID("clang.arc.copy_on_escape");
Dan Gohman0155f302012-02-17 18:59:53 +00002609 NoObjCARCExceptionsMDKind =
2610 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
Michael Gottesman81b1d432013-03-26 00:42:04 +00002611#ifdef ARC_ANNOTATIONS
2612 ARCAnnotationBottomUpMDKind =
2613 M.getContext().getMDKindID("llvm.arc.annotation.bottomup");
2614 ARCAnnotationTopDownMDKind =
2615 M.getContext().getMDKindID("llvm.arc.annotation.topdown");
2616 ARCAnnotationProvenanceSourceMDKind =
2617 M.getContext().getMDKindID("llvm.arc.annotation.provenancesource");
2618#endif // ARC_ANNOTATIONS
John McCalld935e9c2011-06-15 23:37:01 +00002619
John McCalld935e9c2011-06-15 23:37:01 +00002620 // Intuitively, objc_retain and others are nocapture, however in practice
2621 // they are not, because they return their argument value. And objc_release
Dan Gohmandae33492012-04-27 18:56:31 +00002622 // calls finalizers which can have arbitrary side effects.
John McCalld935e9c2011-06-15 23:37:01 +00002623
Michael Gottesman14acfac2013-07-06 01:39:23 +00002624 // Initialize our runtime entry point cache.
2625 EP.Initialize(&M);
John McCalld935e9c2011-06-15 23:37:01 +00002626
2627 return false;
2628}
2629
2630bool ObjCARCOpt::runOnFunction(Function &F) {
2631 if (!EnableARCOpts)
2632 return false;
2633
Dan Gohmanceaac7c2011-06-20 23:20:43 +00002634 // If nothing in the Module uses ARC, don't do anything.
2635 if (!Run)
2636 return false;
2637
John McCalld935e9c2011-06-15 23:37:01 +00002638 Changed = false;
2639
Michael Gottesman89279f82013-04-05 18:10:41 +00002640 DEBUG(dbgs() << "<<< ObjCARCOpt: Visiting Function: " << F.getName() << " >>>"
2641 "\n");
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00002642
John McCalld935e9c2011-06-15 23:37:01 +00002643 PA.setAA(&getAnalysis<AliasAnalysis>());
2644
Michael Gottesman9fc50b82013-05-13 18:29:07 +00002645#ifndef NDEBUG
2646 if (AreStatisticsEnabled()) {
2647 GatherStatistics(F, false);
2648 }
2649#endif
2650
John McCalld935e9c2011-06-15 23:37:01 +00002651 // This pass performs several distinct transformations. As a compile-time aid
2652 // when compiling code that isn't ObjC, skip these if the relevant ObjC
2653 // library functions aren't declared.
2654
Michael Gottesmancd5b0272013-04-24 22:18:15 +00002655 // Preliminary optimizations. This also computes UsedInThisFunction.
John McCalld935e9c2011-06-15 23:37:01 +00002656 OptimizeIndividualCalls(F);
2657
2658 // Optimizations for weak pointers.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002659 if (UsedInThisFunction & ((1 << unsigned(ARCInstKind::LoadWeak)) |
2660 (1 << unsigned(ARCInstKind::LoadWeakRetained)) |
2661 (1 << unsigned(ARCInstKind::StoreWeak)) |
2662 (1 << unsigned(ARCInstKind::InitWeak)) |
2663 (1 << unsigned(ARCInstKind::CopyWeak)) |
2664 (1 << unsigned(ARCInstKind::MoveWeak)) |
2665 (1 << unsigned(ARCInstKind::DestroyWeak))))
John McCalld935e9c2011-06-15 23:37:01 +00002666 OptimizeWeakCalls(F);
2667
2668 // Optimizations for retain+release pairs.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002669 if (UsedInThisFunction & ((1 << unsigned(ARCInstKind::Retain)) |
2670 (1 << unsigned(ARCInstKind::RetainRV)) |
2671 (1 << unsigned(ARCInstKind::RetainBlock))))
2672 if (UsedInThisFunction & (1 << unsigned(ARCInstKind::Release)))
John McCalld935e9c2011-06-15 23:37:01 +00002673 // Run OptimizeSequences until it either stops making changes or
2674 // no retain+release pair nesting is detected.
2675 while (OptimizeSequences(F)) {}
2676
2677 // Optimizations if objc_autorelease is used.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002678 if (UsedInThisFunction & ((1 << unsigned(ARCInstKind::Autorelease)) |
2679 (1 << unsigned(ARCInstKind::AutoreleaseRV))))
John McCalld935e9c2011-06-15 23:37:01 +00002680 OptimizeReturns(F);
2681
Michael Gottesman9c118152013-04-29 06:16:57 +00002682 // Gather statistics after optimization.
2683#ifndef NDEBUG
2684 if (AreStatisticsEnabled()) {
2685 GatherStatistics(F, true);
2686 }
2687#endif
2688
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00002689 DEBUG(dbgs() << "\n");
2690
John McCalld935e9c2011-06-15 23:37:01 +00002691 return Changed;
2692}
2693
2694void ObjCARCOpt::releaseMemory() {
2695 PA.clear();
2696}
2697
Michael Gottesman97e3df02013-01-14 00:35:14 +00002698/// @}
2699///