blob: 8f3a33f66c7f5f400a36ddcde575a9f48fc31437 [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 Gottesman14acfac2013-07-06 01:39:23 +000027#include "ARCRuntimeEntryPoints.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000028#include "BlotMapVector.h"
Michael Gottesman278266f2013-01-29 04:20:52 +000029#include "DependencyAnalysis.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000030#include "ObjCARC.h"
Michael Gottesman778138e2013-01-29 03:03:03 +000031#include "ProvenanceAnalysis.h"
Michael Gottesman68b91db2015-03-05 23:29:03 +000032#include "PtrState.h"
John McCalld935e9c2011-06-15 23:37:01 +000033#include "llvm/ADT/DenseMap.h"
Michael Gottesman5a91bbf2013-05-24 20:44:02 +000034#include "llvm/ADT/DenseSet.h"
Michael Gottesmanfa0939f2013-01-28 04:12:07 +000035#include "llvm/ADT/STLExtras.h"
Michael Gottesman778138e2013-01-29 03:03:03 +000036#include "llvm/ADT/SmallPtrSet.h"
Michael Gottesman278266f2013-01-29 04:20:52 +000037#include "llvm/ADT/Statistic.h"
Chandler Carruth0f792182015-08-20 08:06:03 +000038#include "llvm/Analysis/ObjCARCAliasAnalysis.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) {
Duncan P. N. Exon Smith11c06ea2016-09-24 21:01:20 +000056 // ConstantData (like ConstantPointerNull and UndefValue) is used across
57 // modules. It's never a single-use value.
58 if (isa<ConstantData>(Arg))
59 return nullptr;
60
John McCalld935e9c2011-06-15 23:37:01 +000061 if (Arg->hasOneUse()) {
62 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
63 return FindSingleUseIdentifiedObject(BC->getOperand(0));
64 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
65 if (GEP->hasAllZeroIndices())
66 return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
Michael Gottesman6f729fa2015-02-19 19:51:32 +000067 if (IsForwarding(GetBasicARCInstKind(Arg)))
John McCalld935e9c2011-06-15 23:37:01 +000068 return FindSingleUseIdentifiedObject(
69 cast<CallInst>(Arg)->getArgOperand(0));
70 if (!IsObjCIdentifiedObject(Arg))
Craig Topperf40110f2014-04-25 05:29:35 +000071 return nullptr;
John McCalld935e9c2011-06-15 23:37:01 +000072 return Arg;
73 }
74
Dan Gohman41375a32012-05-08 23:39:44 +000075 // If we found an identifiable object but it has multiple uses, but they are
76 // trivial uses, we can still consider this to be a single-use value.
John McCalld935e9c2011-06-15 23:37:01 +000077 if (IsObjCIdentifiedObject(Arg)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +000078 for (const User *U : Arg->users())
Michael Gottesmane5ad66f2015-02-19 00:42:38 +000079 if (!U->use_empty() || GetRCIdentityRoot(U) != Arg)
Craig Topperf40110f2014-04-25 05:29:35 +000080 return nullptr;
John McCalld935e9c2011-06-15 23:37:01 +000081
82 return Arg;
83 }
84
Craig Topperf40110f2014-04-25 05:29:35 +000085 return nullptr;
John McCalld935e9c2011-06-15 23:37:01 +000086}
87
Michael Gottesman97e3df02013-01-14 00:35:14 +000088/// @}
89///
Michael Gottesman97e3df02013-01-14 00:35:14 +000090/// \defgroup ARCOpt ARC Optimization.
91/// @{
John McCalld935e9c2011-06-15 23:37:01 +000092
93// TODO: On code like this:
94//
95// objc_retain(%x)
96// stuff_that_cannot_release()
97// objc_autorelease(%x)
98// stuff_that_cannot_release()
99// objc_retain(%x)
100// stuff_that_cannot_release()
101// objc_autorelease(%x)
102//
103// The second retain and autorelease can be deleted.
104
105// TODO: It should be possible to delete
106// objc_autoreleasePoolPush and objc_autoreleasePoolPop
107// pairs if nothing is actually autoreleased between them. Also, autorelease
108// calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
109// after inlining) can be turned into plain release calls.
110
111// TODO: Critical-edge splitting. If the optimial insertion point is
112// a critical edge, the current algorithm has to fail, because it doesn't
113// know how to split edges. It should be possible to make the optimizer
114// think in terms of edges, rather than blocks, and then split critical
115// edges on demand.
116
117// TODO: OptimizeSequences could generalized to be Interprocedural.
118
119// TODO: Recognize that a bunch of other objc runtime calls have
120// non-escaping arguments and non-releasing arguments, and may be
121// non-autoreleasing.
122
123// TODO: Sink autorelease calls as far as possible. Unfortunately we
124// usually can't sink them past other calls, which would be the main
125// case where it would be useful.
126
Dan Gohmanb3894012011-08-19 00:26:36 +0000127// TODO: The pointer returned from objc_loadWeakRetained is retained.
128
129// TODO: Delete release+retain pairs (rare).
Dan Gohmanceaac7c2011-06-20 23:20:43 +0000130
John McCalld935e9c2011-06-15 23:37:01 +0000131STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
132STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
133STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
134STATISTIC(NumRets, "Number of return value forwarding "
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000135 "retain+autoreleases eliminated");
John McCalld935e9c2011-06-15 23:37:01 +0000136STATISTIC(NumRRs, "Number of retain+release paths eliminated");
137STATISTIC(NumPeeps, "Number of calls peephole-optimized");
Matt Beaumont-Gaye55d9492013-05-13 21:10:49 +0000138#ifndef NDEBUG
Michael Gottesman9c118152013-04-29 06:16:57 +0000139STATISTIC(NumRetainsBeforeOpt,
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000140 "Number of retains before optimization");
Michael Gottesman9c118152013-04-29 06:16:57 +0000141STATISTIC(NumReleasesBeforeOpt,
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000142 "Number of releases before optimization");
Michael Gottesman9c118152013-04-29 06:16:57 +0000143STATISTIC(NumRetainsAfterOpt,
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000144 "Number of retains after optimization");
Michael Gottesman9c118152013-04-29 06:16:57 +0000145STATISTIC(NumReleasesAfterOpt,
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000146 "Number of releases after optimization");
Michael Gottesman03cf3c82013-04-29 07:29:08 +0000147#endif
John McCalld935e9c2011-06-15 23:37:01 +0000148
149namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000150 /// \brief Per-BasicBlock state.
John McCalld935e9c2011-06-15 23:37:01 +0000151 class BBState {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000152 /// The number of unique control paths from the entry which can reach this
153 /// block.
John McCalld935e9c2011-06-15 23:37:01 +0000154 unsigned TopDownPathCount;
155
Michael Gottesman97e3df02013-01-14 00:35:14 +0000156 /// The number of unique control paths to exits from this block.
John McCalld935e9c2011-06-15 23:37:01 +0000157 unsigned BottomUpPathCount;
158
Michael Gottesman97e3df02013-01-14 00:35:14 +0000159 /// The top-down traversal uses this to record information known about a
160 /// pointer at the bottom of each block.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000161 BlotMapVector<const Value *, TopDownPtrState> PerPtrTopDown;
John McCalld935e9c2011-06-15 23:37:01 +0000162
Michael Gottesman97e3df02013-01-14 00:35:14 +0000163 /// The bottom-up traversal uses this to record information known about a
164 /// pointer at the top of each block.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000165 BlotMapVector<const Value *, BottomUpPtrState> PerPtrBottomUp;
John McCalld935e9c2011-06-15 23:37:01 +0000166
Michael Gottesman97e3df02013-01-14 00:35:14 +0000167 /// Effective predecessors of the current block ignoring ignorable edges and
168 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000169 SmallVector<BasicBlock *, 2> Preds;
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000170
Michael Gottesman97e3df02013-01-14 00:35:14 +0000171 /// Effective successors of the current block ignoring ignorable edges and
172 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000173 SmallVector<BasicBlock *, 2> Succs;
174
John McCalld935e9c2011-06-15 23:37:01 +0000175 public:
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000176 static const unsigned OverflowOccurredValue;
177
178 BBState() : TopDownPathCount(0), BottomUpPathCount(0) { }
John McCalld935e9c2011-06-15 23:37:01 +0000179
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000180 typedef decltype(PerPtrTopDown)::iterator top_down_ptr_iterator;
181 typedef decltype(PerPtrTopDown)::const_iterator const_top_down_ptr_iterator;
John McCalld935e9c2011-06-15 23:37:01 +0000182
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000183 top_down_ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
184 top_down_ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
185 const_top_down_ptr_iterator top_down_ptr_begin() const {
John McCalld935e9c2011-06-15 23:37:01 +0000186 return PerPtrTopDown.begin();
187 }
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000188 const_top_down_ptr_iterator top_down_ptr_end() const {
John McCalld935e9c2011-06-15 23:37:01 +0000189 return PerPtrTopDown.end();
190 }
Michael Gottesmanc01ab512015-03-16 07:02:39 +0000191 bool hasTopDownPtrs() const {
192 return !PerPtrTopDown.empty();
193 }
John McCalld935e9c2011-06-15 23:37:01 +0000194
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000195 typedef decltype(PerPtrBottomUp)::iterator bottom_up_ptr_iterator;
196 typedef decltype(
197 PerPtrBottomUp)::const_iterator const_bottom_up_ptr_iterator;
198
199 bottom_up_ptr_iterator bottom_up_ptr_begin() {
John McCalld935e9c2011-06-15 23:37:01 +0000200 return PerPtrBottomUp.begin();
201 }
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000202 bottom_up_ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
203 const_bottom_up_ptr_iterator bottom_up_ptr_begin() const {
204 return PerPtrBottomUp.begin();
205 }
206 const_bottom_up_ptr_iterator bottom_up_ptr_end() const {
John McCalld935e9c2011-06-15 23:37:01 +0000207 return PerPtrBottomUp.end();
208 }
Michael Gottesmanc01ab512015-03-16 07:02:39 +0000209 bool hasBottomUpPtrs() const {
210 return !PerPtrBottomUp.empty();
211 }
John McCalld935e9c2011-06-15 23:37:01 +0000212
Michael Gottesman97e3df02013-01-14 00:35:14 +0000213 /// Mark this block as being an entry block, which has one path from the
214 /// entry by definition.
John McCalld935e9c2011-06-15 23:37:01 +0000215 void SetAsEntry() { TopDownPathCount = 1; }
216
Michael Gottesman97e3df02013-01-14 00:35:14 +0000217 /// Mark this block as being an exit block, which has one path to an exit by
218 /// definition.
John McCalld935e9c2011-06-15 23:37:01 +0000219 void SetAsExit() { BottomUpPathCount = 1; }
220
Michael Gottesman993fbf72013-05-13 19:40:39 +0000221 /// Attempt to find the PtrState object describing the top down state for
222 /// pointer Arg. Return a new initialized PtrState describing the top down
223 /// state for Arg if we do not find one.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000224 TopDownPtrState &getPtrTopDownState(const Value *Arg) {
John McCalld935e9c2011-06-15 23:37:01 +0000225 return PerPtrTopDown[Arg];
226 }
227
Michael Gottesman993fbf72013-05-13 19:40:39 +0000228 /// Attempt to find the PtrState object describing the bottom up state for
229 /// pointer Arg. Return a new initialized PtrState describing the bottom up
230 /// state for Arg if we do not find one.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000231 BottomUpPtrState &getPtrBottomUpState(const Value *Arg) {
John McCalld935e9c2011-06-15 23:37:01 +0000232 return PerPtrBottomUp[Arg];
233 }
234
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000235 /// Attempt to find the PtrState object describing the bottom up state for
236 /// pointer Arg.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000237 bottom_up_ptr_iterator findPtrBottomUpState(const Value *Arg) {
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000238 return PerPtrBottomUp.find(Arg);
239 }
240
John McCalld935e9c2011-06-15 23:37:01 +0000241 void clearBottomUpPointers() {
Evan Chenge4df6a22011-08-04 18:40:26 +0000242 PerPtrBottomUp.clear();
John McCalld935e9c2011-06-15 23:37:01 +0000243 }
244
245 void clearTopDownPointers() {
246 PerPtrTopDown.clear();
247 }
248
249 void InitFromPred(const BBState &Other);
250 void InitFromSucc(const BBState &Other);
251 void MergePred(const BBState &Other);
252 void MergeSucc(const BBState &Other);
253
Michael Gottesman9e7261c2013-06-07 06:16:49 +0000254 /// Compute the number of possible unique paths from an entry to an exit
Michael Gottesman97e3df02013-01-14 00:35:14 +0000255 /// which pass through this block. This is only valid after both the
256 /// top-down and bottom-up traversals are complete.
Michael Gottesman9e7261c2013-06-07 06:16:49 +0000257 ///
Alp Tokercb402912014-01-24 17:20:08 +0000258 /// Returns true if overflow occurred. Returns false if overflow did not
Michael Gottesman9e7261c2013-06-07 06:16:49 +0000259 /// occur.
260 bool GetAllPathCountWithOverflow(unsigned &PathCount) const {
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000261 if (TopDownPathCount == OverflowOccurredValue ||
262 BottomUpPathCount == OverflowOccurredValue)
263 return true;
Michael Gottesman9e7261c2013-06-07 06:16:49 +0000264 unsigned long long Product =
265 (unsigned long long)TopDownPathCount*BottomUpPathCount;
Alp Tokercb402912014-01-24 17:20:08 +0000266 // Overflow occurred if any of the upper bits of Product are set or if all
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000267 // the lower bits of Product are all set.
268 return (Product >> 32) ||
269 ((PathCount = Product) == OverflowOccurredValue);
John McCalld935e9c2011-06-15 23:37:01 +0000270 }
Dan Gohman12130272011-08-12 00:26:31 +0000271
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000272 // Specialized CFG utilities.
Dan Gohmandae33492012-04-27 18:56:31 +0000273 typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
Michael Gottesman0fecf982013-08-07 23:56:34 +0000274 edge_iterator pred_begin() const { return Preds.begin(); }
275 edge_iterator pred_end() const { return Preds.end(); }
276 edge_iterator succ_begin() const { return Succs.begin(); }
277 edge_iterator succ_end() const { return Succs.end(); }
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000278
279 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
280 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
281
282 bool isExit() const { return Succs.empty(); }
John McCalld935e9c2011-06-15 23:37:01 +0000283 };
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000284
285 const unsigned BBState::OverflowOccurredValue = 0xffffffff;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000286}
John McCalld935e9c2011-06-15 23:37:01 +0000287
Michael Gottesmanc01ab512015-03-16 07:02:39 +0000288namespace llvm {
Michael Gottesmand63436f2015-03-16 08:00:27 +0000289raw_ostream &operator<<(raw_ostream &OS,
290 BBState &BBState) LLVM_ATTRIBUTE_UNUSED;
Michael Gottesmanc01ab512015-03-16 07:02:39 +0000291}
292
John McCalld935e9c2011-06-15 23:37:01 +0000293void BBState::InitFromPred(const BBState &Other) {
294 PerPtrTopDown = Other.PerPtrTopDown;
295 TopDownPathCount = Other.TopDownPathCount;
296}
297
298void BBState::InitFromSucc(const BBState &Other) {
299 PerPtrBottomUp = Other.PerPtrBottomUp;
300 BottomUpPathCount = Other.BottomUpPathCount;
301}
302
Michael Gottesman97e3df02013-01-14 00:35:14 +0000303/// The top-down traversal uses this to merge information about predecessors to
304/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +0000305void BBState::MergePred(const BBState &Other) {
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000306 if (TopDownPathCount == OverflowOccurredValue)
307 return;
308
John McCalld935e9c2011-06-15 23:37:01 +0000309 // Other.TopDownPathCount can be 0, in which case it is either dead or a
310 // loop backedge. Loop backedges are special.
311 TopDownPathCount += Other.TopDownPathCount;
312
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000313 // In order to be consistent, we clear the top down pointers when by adding
314 // TopDownPathCount becomes OverflowOccurredValue even though "true" overflow
Alp Tokercb402912014-01-24 17:20:08 +0000315 // has not occurred.
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000316 if (TopDownPathCount == OverflowOccurredValue) {
317 clearTopDownPointers();
318 return;
319 }
320
Michael Gottesman4385edf2013-01-14 01:47:53 +0000321 // Check for overflow. If we have overflow, fall back to conservative
322 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +0000323 if (TopDownPathCount < Other.TopDownPathCount) {
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000324 TopDownPathCount = OverflowOccurredValue;
Dan Gohman7c84dad2012-09-12 20:45:17 +0000325 clearTopDownPointers();
326 return;
327 }
328
John McCalld935e9c2011-06-15 23:37:01 +0000329 // For each entry in the other set, if our set has an entry with the same key,
330 // merge the entries. Otherwise, copy the entry and merge it with an empty
331 // entry.
Michael Gottesmana9fc0162015-03-05 23:29:06 +0000332 for (auto MI = Other.top_down_ptr_begin(), ME = Other.top_down_ptr_end();
333 MI != ME; ++MI) {
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000334 auto Pair = PerPtrTopDown.insert(*MI);
335 Pair.first->second.Merge(Pair.second ? TopDownPtrState() : MI->second,
John McCalld935e9c2011-06-15 23:37:01 +0000336 /*TopDown=*/true);
337 }
338
Dan Gohman7e315fc32011-08-11 21:06:32 +0000339 // For each entry in our set, if the other set doesn't have an entry with the
John McCalld935e9c2011-06-15 23:37:01 +0000340 // same key, force it to merge with an empty entry.
Michael Gottesmana9fc0162015-03-05 23:29:06 +0000341 for (auto MI = top_down_ptr_begin(), ME = top_down_ptr_end(); MI != ME; ++MI)
John McCalld935e9c2011-06-15 23:37:01 +0000342 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000343 MI->second.Merge(TopDownPtrState(), /*TopDown=*/true);
John McCalld935e9c2011-06-15 23:37:01 +0000344}
345
Michael Gottesman97e3df02013-01-14 00:35:14 +0000346/// The bottom-up traversal uses this to merge information about successors to
347/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +0000348void BBState::MergeSucc(const BBState &Other) {
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000349 if (BottomUpPathCount == OverflowOccurredValue)
350 return;
351
John McCalld935e9c2011-06-15 23:37:01 +0000352 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
353 // loop backedge. Loop backedges are special.
354 BottomUpPathCount += Other.BottomUpPathCount;
355
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000356 // In order to be consistent, we clear the top down pointers when by adding
357 // BottomUpPathCount becomes OverflowOccurredValue even though "true" overflow
Alp Tokercb402912014-01-24 17:20:08 +0000358 // has not occurred.
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000359 if (BottomUpPathCount == OverflowOccurredValue) {
360 clearBottomUpPointers();
361 return;
362 }
363
Michael Gottesman4385edf2013-01-14 01:47:53 +0000364 // Check for overflow. If we have overflow, fall back to conservative
365 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +0000366 if (BottomUpPathCount < Other.BottomUpPathCount) {
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000367 BottomUpPathCount = OverflowOccurredValue;
Dan Gohman7c84dad2012-09-12 20:45:17 +0000368 clearBottomUpPointers();
369 return;
370 }
371
John McCalld935e9c2011-06-15 23:37:01 +0000372 // For each entry in the other set, if our set has an entry with the
373 // same key, merge the entries. Otherwise, copy the entry and merge
374 // it with an empty entry.
Michael Gottesmana9fc0162015-03-05 23:29:06 +0000375 for (auto MI = Other.bottom_up_ptr_begin(), ME = Other.bottom_up_ptr_end();
376 MI != ME; ++MI) {
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000377 auto Pair = PerPtrBottomUp.insert(*MI);
378 Pair.first->second.Merge(Pair.second ? BottomUpPtrState() : MI->second,
John McCalld935e9c2011-06-15 23:37:01 +0000379 /*TopDown=*/false);
380 }
381
Dan Gohman7e315fc32011-08-11 21:06:32 +0000382 // For each entry in our set, if the other set doesn't have an entry
John McCalld935e9c2011-06-15 23:37:01 +0000383 // with the same key, force it to merge with an empty entry.
Michael Gottesmana9fc0162015-03-05 23:29:06 +0000384 for (auto MI = bottom_up_ptr_begin(), ME = bottom_up_ptr_end(); MI != ME;
385 ++MI)
John McCalld935e9c2011-06-15 23:37:01 +0000386 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000387 MI->second.Merge(BottomUpPtrState(), /*TopDown=*/false);
John McCalld935e9c2011-06-15 23:37:01 +0000388}
389
Michael Gottesmanc01ab512015-03-16 07:02:39 +0000390raw_ostream &llvm::operator<<(raw_ostream &OS, BBState &BBInfo) {
391 // Dump the pointers we are tracking.
392 OS << " TopDown State:\n";
393 if (!BBInfo.hasTopDownPtrs()) {
394 DEBUG(llvm::dbgs() << " NONE!\n");
395 } else {
396 for (auto I = BBInfo.top_down_ptr_begin(), E = BBInfo.top_down_ptr_end();
397 I != E; ++I) {
398 const PtrState &P = I->second;
399 OS << " Ptr: " << *I->first
400 << "\n KnownSafe: " << (P.IsKnownSafe()?"true":"false")
401 << "\n ImpreciseRelease: "
402 << (P.IsTrackingImpreciseReleases()?"true":"false") << "\n"
403 << " HasCFGHazards: "
404 << (P.IsCFGHazardAfflicted()?"true":"false") << "\n"
405 << " KnownPositive: "
406 << (P.HasKnownPositiveRefCount()?"true":"false") << "\n"
407 << " Seq: "
408 << P.GetSeq() << "\n";
409 }
410 }
411
412 OS << " BottomUp State:\n";
413 if (!BBInfo.hasBottomUpPtrs()) {
414 DEBUG(llvm::dbgs() << " NONE!\n");
415 } else {
416 for (auto I = BBInfo.bottom_up_ptr_begin(), E = BBInfo.bottom_up_ptr_end();
417 I != E; ++I) {
418 const PtrState &P = I->second;
419 OS << " Ptr: " << *I->first
420 << "\n KnownSafe: " << (P.IsKnownSafe()?"true":"false")
421 << "\n ImpreciseRelease: "
422 << (P.IsTrackingImpreciseReleases()?"true":"false") << "\n"
423 << " HasCFGHazards: "
424 << (P.IsCFGHazardAfflicted()?"true":"false") << "\n"
425 << " KnownPositive: "
426 << (P.HasKnownPositiveRefCount()?"true":"false") << "\n"
427 << " Seq: "
428 << P.GetSeq() << "\n";
429 }
430 }
431
432 return OS;
433}
434
John McCalld935e9c2011-06-15 23:37:01 +0000435namespace {
Michael Gottesman41c01002015-03-06 00:34:33 +0000436
Michael Gottesman97e3df02013-01-14 00:35:14 +0000437 /// \brief The main ARC optimization pass.
John McCalld935e9c2011-06-15 23:37:01 +0000438 class ObjCARCOpt : public FunctionPass {
439 bool Changed;
440 ProvenanceAnalysis PA;
Michael Gottesman41c01002015-03-06 00:34:33 +0000441
442 /// A cache of references to runtime entry point constants.
Michael Gottesman14acfac2013-07-06 01:39:23 +0000443 ARCRuntimeEntryPoints EP;
John McCalld935e9c2011-06-15 23:37:01 +0000444
Michael Gottesman41c01002015-03-06 00:34:33 +0000445 /// A cache of MDKinds that can be passed into other functions to propagate
446 /// MDKind identifiers.
447 ARCMDKindCache MDKindCache;
448
Michael Gottesman97e3df02013-01-14 00:35:14 +0000449 /// A flag indicating whether this optimization pass should run.
Dan Gohmanceaac7c2011-06-20 23:20:43 +0000450 bool Run;
451
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000452 /// Flags which determine whether each of the interesting runtime functions
Michael Gottesman97e3df02013-01-14 00:35:14 +0000453 /// is in fact used in the current function.
John McCalld935e9c2011-06-15 23:37:01 +0000454 unsigned UsedInThisFunction;
455
John McCalld935e9c2011-06-15 23:37:01 +0000456 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
Michael Gottesman556ff612013-01-12 01:25:19 +0000457 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000458 ARCInstKind &Class);
John McCalld935e9c2011-06-15 23:37:01 +0000459 void OptimizeIndividualCalls(Function &F);
460
461 void CheckForCFGHazards(const BasicBlock *BB,
462 DenseMap<const BasicBlock *, BBState> &BBStates,
463 BBState &MyStates) const;
Michael Gottesman0be69202015-03-05 23:28:58 +0000464 bool VisitInstructionBottomUp(Instruction *Inst, BasicBlock *BB,
465 BlotMapVector<Value *, RRInfo> &Retains,
Dan Gohman817a7c62012-03-22 18:24:56 +0000466 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +0000467 bool VisitBottomUp(BasicBlock *BB,
468 DenseMap<const BasicBlock *, BBState> &BBStates,
Michael Gottesman0be69202015-03-05 23:28:58 +0000469 BlotMapVector<Value *, RRInfo> &Retains);
Dan Gohman817a7c62012-03-22 18:24:56 +0000470 bool VisitInstructionTopDown(Instruction *Inst,
471 DenseMap<Value *, RRInfo> &Releases,
472 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +0000473 bool VisitTopDown(BasicBlock *BB,
474 DenseMap<const BasicBlock *, BBState> &BBStates,
475 DenseMap<Value *, RRInfo> &Releases);
Michael Gottesman0be69202015-03-05 23:28:58 +0000476 bool Visit(Function &F, DenseMap<const BasicBlock *, BBState> &BBStates,
477 BlotMapVector<Value *, RRInfo> &Retains,
John McCalld935e9c2011-06-15 23:37:01 +0000478 DenseMap<Value *, RRInfo> &Releases);
479
480 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
Michael Gottesman0be69202015-03-05 23:28:58 +0000481 BlotMapVector<Value *, RRInfo> &Retains,
John McCalld935e9c2011-06-15 23:37:01 +0000482 DenseMap<Value *, RRInfo> &Releases,
Michael Gottesman0be69202015-03-05 23:28:58 +0000483 SmallVectorImpl<Instruction *> &DeadInsts, Module *M);
John McCalld935e9c2011-06-15 23:37:01 +0000484
Michael Gottesman67792172015-03-16 07:02:30 +0000485 bool
486 PairUpRetainsAndReleases(DenseMap<const BasicBlock *, BBState> &BBStates,
487 BlotMapVector<Value *, RRInfo> &Retains,
488 DenseMap<Value *, RRInfo> &Releases, Module *M,
Akira Hatanaka2b882052017-02-25 00:53:38 +0000489 Instruction * Retain,
Michael Gottesman67792172015-03-16 07:02:30 +0000490 SmallVectorImpl<Instruction *> &DeadInsts,
491 RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
492 Value *Arg, bool KnownSafe,
493 bool &AnyPairsCompletelyEliminated);
Michael Gottesman9de6f962013-01-22 21:49:00 +0000494
John McCalld935e9c2011-06-15 23:37:01 +0000495 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
Michael Gottesman0be69202015-03-05 23:28:58 +0000496 BlotMapVector<Value *, RRInfo> &Retains,
497 DenseMap<Value *, RRInfo> &Releases, Module *M);
John McCalld935e9c2011-06-15 23:37:01 +0000498
499 void OptimizeWeakCalls(Function &F);
500
501 bool OptimizeSequences(Function &F);
502
503 void OptimizeReturns(Function &F);
504
Michael Gottesman9c118152013-04-29 06:16:57 +0000505#ifndef NDEBUG
506 void GatherStatistics(Function &F, bool AfterOptimization = false);
507#endif
508
Craig Topper3e4c6972014-03-05 09:10:37 +0000509 void getAnalysisUsage(AnalysisUsage &AU) const override;
510 bool doInitialization(Module &M) override;
511 bool runOnFunction(Function &F) override;
512 void releaseMemory() override;
John McCalld935e9c2011-06-15 23:37:01 +0000513
514 public:
515 static char ID;
516 ObjCARCOpt() : FunctionPass(ID) {
517 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
518 }
519 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000520}
John McCalld935e9c2011-06-15 23:37:01 +0000521
522char ObjCARCOpt::ID = 0;
523INITIALIZE_PASS_BEGIN(ObjCARCOpt,
524 "objc-arc", "ObjC ARC optimization", false, false)
Chandler Carruth7b560d42015-09-09 17:55:00 +0000525INITIALIZE_PASS_DEPENDENCY(ObjCARCAAWrapperPass)
John McCalld935e9c2011-06-15 23:37:01 +0000526INITIALIZE_PASS_END(ObjCARCOpt,
527 "objc-arc", "ObjC ARC optimization", false, false)
528
529Pass *llvm::createObjCARCOptPass() {
530 return new ObjCARCOpt();
531}
532
533void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruth7b560d42015-09-09 17:55:00 +0000534 AU.addRequired<ObjCARCAAWrapperPass>();
535 AU.addRequired<AAResultsWrapperPass>();
John McCalld935e9c2011-06-15 23:37:01 +0000536 // ARC optimization doesn't currently split critical edges.
537 AU.setPreservesCFG();
538}
539
Michael Gottesman97e3df02013-01-14 00:35:14 +0000540/// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is
541/// not a return value. Or, if it can be paired with an
542/// objc_autoreleaseReturnValue, delete the pair and return true.
John McCalld935e9c2011-06-15 23:37:01 +0000543bool
544ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +0000545 // Check for the argument being from an immediately preceding call or invoke.
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000546 const Value *Arg = GetArgRCIdentityRoot(RetainRV);
Dan Gohmandae33492012-04-27 18:56:31 +0000547 ImmutableCallSite CS(Arg);
548 if (const Instruction *Call = CS.getInstruction()) {
John McCalld935e9c2011-06-15 23:37:01 +0000549 if (Call->getParent() == RetainRV->getParent()) {
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +0000550 BasicBlock::const_iterator I(Call);
John McCalld935e9c2011-06-15 23:37:01 +0000551 ++I;
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +0000552 while (IsNoopInstruction(&*I))
553 ++I;
John McCalld935e9c2011-06-15 23:37:01 +0000554 if (&*I == RetainRV)
555 return false;
Dan Gohmandae33492012-04-27 18:56:31 +0000556 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +0000557 BasicBlock *RetainRVParent = RetainRV->getParent();
558 if (II->getNormalDest() == RetainRVParent) {
Dan Gohmandae33492012-04-27 18:56:31 +0000559 BasicBlock::const_iterator I = RetainRVParent->begin();
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +0000560 while (IsNoopInstruction(&*I))
561 ++I;
Dan Gohmane3ed2b02012-03-23 18:09:00 +0000562 if (&*I == RetainRV)
563 return false;
564 }
John McCalld935e9c2011-06-15 23:37:01 +0000565 }
Dan Gohmane3ed2b02012-03-23 18:09:00 +0000566 }
John McCalld935e9c2011-06-15 23:37:01 +0000567
568 // Check for being preceded by an objc_autoreleaseReturnValue on the same
569 // pointer. In this case, we can delete the pair.
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +0000570 BasicBlock::iterator I = RetainRV->getIterator(),
571 Begin = RetainRV->getParent()->begin();
John McCalld935e9c2011-06-15 23:37:01 +0000572 if (I != Begin) {
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +0000573 do
574 --I;
575 while (I != Begin && IsNoopInstruction(&*I));
576 if (GetBasicARCInstKind(&*I) == ARCInstKind::AutoreleaseRV &&
577 GetArgRCIdentityRoot(&*I) == Arg) {
John McCalld935e9c2011-06-15 23:37:01 +0000578 Changed = true;
579 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +0000580
Michael Gottesman89279f82013-04-05 18:10:41 +0000581 DEBUG(dbgs() << "Erasing autoreleaseRV,retainRV pair: " << *I << "\n"
582 << "Erasing " << *RetainRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +0000583
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +0000584 EraseInstruction(&*I);
John McCalld935e9c2011-06-15 23:37:01 +0000585 EraseInstruction(RetainRV);
586 return true;
587 }
588 }
589
590 // Turn it to a plain objc_retain.
591 Changed = true;
592 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +0000593
Michael Gottesman89279f82013-04-05 18:10:41 +0000594 DEBUG(dbgs() << "Transforming objc_retainAutoreleasedReturnValue => "
Michael Gottesmandef07bb2013-01-05 17:55:42 +0000595 "objc_retain since the operand is not a return value.\n"
Michael Gottesman89279f82013-04-05 18:10:41 +0000596 "Old = " << *RetainRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +0000597
Michael Gottesmanca3a4722015-03-16 07:02:24 +0000598 Constant *NewDecl = EP.get(ARCRuntimeEntryPointKind::Retain);
Michael Gottesman14acfac2013-07-06 01:39:23 +0000599 cast<CallInst>(RetainRV)->setCalledFunction(NewDecl);
Michael Gottesmandef07bb2013-01-05 17:55:42 +0000600
Michael Gottesman89279f82013-04-05 18:10:41 +0000601 DEBUG(dbgs() << "New = " << *RetainRV << "\n");
Michael Gottesmandef07bb2013-01-05 17:55:42 +0000602
John McCalld935e9c2011-06-15 23:37:01 +0000603 return false;
604}
605
Michael Gottesman97e3df02013-01-14 00:35:14 +0000606/// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not
607/// used as a return value.
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000608void ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F,
609 Instruction *AutoreleaseRV,
610 ARCInstKind &Class) {
John McCalld935e9c2011-06-15 23:37:01 +0000611 // Check for a return of the pointer value.
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000612 const Value *Ptr = GetArgRCIdentityRoot(AutoreleaseRV);
Duncan P. N. Exon Smith11c06ea2016-09-24 21:01:20 +0000613
614 // If the argument is ConstantPointerNull or UndefValue, its other users
615 // aren't actually interesting to look at.
616 if (isa<ConstantData>(Ptr))
617 return;
618
Dan Gohman10a18d52011-08-12 00:36:31 +0000619 SmallVector<const Value *, 2> Users;
620 Users.push_back(Ptr);
621 do {
622 Ptr = Users.pop_back_val();
Chandler Carruthcdf47882014-03-09 03:16:01 +0000623 for (const User *U : Ptr->users()) {
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000624 if (isa<ReturnInst>(U) || GetBasicARCInstKind(U) == ARCInstKind::RetainRV)
Dan Gohman10a18d52011-08-12 00:36:31 +0000625 return;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000626 if (isa<BitCastInst>(U))
627 Users.push_back(U);
Dan Gohman10a18d52011-08-12 00:36:31 +0000628 }
629 } while (!Users.empty());
John McCalld935e9c2011-06-15 23:37:01 +0000630
631 Changed = true;
632 ++NumPeeps;
Michael Gottesman1bf69082013-01-06 21:07:11 +0000633
Michael Gottesman89279f82013-04-05 18:10:41 +0000634 DEBUG(dbgs() << "Transforming objc_autoreleaseReturnValue => "
Michael Gottesman1bf69082013-01-06 21:07:11 +0000635 "objc_autorelease since its operand is not used as a return "
636 "value.\n"
Michael Gottesman89279f82013-04-05 18:10:41 +0000637 "Old = " << *AutoreleaseRV << "\n");
Michael Gottesman1bf69082013-01-06 21:07:11 +0000638
Michael Gottesmanc9656fa2013-01-12 01:25:15 +0000639 CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
Michael Gottesmanca3a4722015-03-16 07:02:24 +0000640 Constant *NewDecl = EP.get(ARCRuntimeEntryPointKind::Autorelease);
Michael Gottesman14acfac2013-07-06 01:39:23 +0000641 AutoreleaseRVCI->setCalledFunction(NewDecl);
Michael Gottesmanc9656fa2013-01-12 01:25:15 +0000642 AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000643 Class = ARCInstKind::Autorelease;
Michael Gottesman10426b52013-01-07 21:26:07 +0000644
Michael Gottesman89279f82013-04-05 18:10:41 +0000645 DEBUG(dbgs() << "New: " << *AutoreleaseRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +0000646
John McCalld935e9c2011-06-15 23:37:01 +0000647}
648
Michael Gottesman97e3df02013-01-14 00:35:14 +0000649/// Visit each call, one at a time, and make simplifications without doing any
650/// additional analysis.
John McCalld935e9c2011-06-15 23:37:01 +0000651void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
Michael Gottesman89279f82013-04-05 18:10:41 +0000652 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeIndividualCalls ==\n");
John McCalld935e9c2011-06-15 23:37:01 +0000653 // Reset all the flags in preparation for recomputing them.
654 UsedInThisFunction = 0;
655
656 // Visit all objc_* calls in F.
657 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
658 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +0000659
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000660 ARCInstKind Class = GetBasicARCInstKind(Inst);
John McCalld935e9c2011-06-15 23:37:01 +0000661
Michael Gottesman89279f82013-04-05 18:10:41 +0000662 DEBUG(dbgs() << "Visiting: Class: " << Class << "; " << *Inst << "\n");
Michael Gottesman782e3442013-01-17 18:32:34 +0000663
John McCalld935e9c2011-06-15 23:37:01 +0000664 switch (Class) {
665 default: break;
666
667 // Delete no-op casts. These function calls have special semantics, but
668 // the semantics are entirely implemented via lowering in the front-end,
669 // so by the time they reach the optimizer, they are just no-op calls
670 // which return their argument.
671 //
672 // There are gray areas here, as the ability to cast reference-counted
673 // pointers to raw void* and back allows code to break ARC assumptions,
674 // however these are currently considered to be unimportant.
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000675 case ARCInstKind::NoopCast:
John McCalld935e9c2011-06-15 23:37:01 +0000676 Changed = true;
677 ++NumNoops;
Michael Gottesman89279f82013-04-05 18:10:41 +0000678 DEBUG(dbgs() << "Erasing no-op cast: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +0000679 EraseInstruction(Inst);
680 continue;
681
682 // If the pointer-to-weak-pointer is null, it's undefined behavior.
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000683 case ARCInstKind::StoreWeak:
684 case ARCInstKind::LoadWeak:
685 case ARCInstKind::LoadWeakRetained:
686 case ARCInstKind::InitWeak:
687 case ARCInstKind::DestroyWeak: {
John McCalld935e9c2011-06-15 23:37:01 +0000688 CallInst *CI = cast<CallInst>(Inst);
Michael Gottesman65c24812013-03-25 09:27:43 +0000689 if (IsNullOrUndef(CI->getArgOperand(0))) {
Dan Gohman670f9372012-04-13 18:57:48 +0000690 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +0000691 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +0000692 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
693 Constant::getNullValue(Ty),
694 CI);
Michael Gottesman10426b52013-01-07 21:26:07 +0000695 llvm::Value *NewValue = UndefValue::get(CI->getType());
Michael Gottesman89279f82013-04-05 18:10:41 +0000696 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
697 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
Michael Gottesmanfec61c02013-01-06 21:54:30 +0000698 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +0000699 CI->eraseFromParent();
700 continue;
701 }
702 break;
703 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000704 case ARCInstKind::CopyWeak:
705 case ARCInstKind::MoveWeak: {
John McCalld935e9c2011-06-15 23:37:01 +0000706 CallInst *CI = cast<CallInst>(Inst);
Michael Gottesman65c24812013-03-25 09:27:43 +0000707 if (IsNullOrUndef(CI->getArgOperand(0)) ||
708 IsNullOrUndef(CI->getArgOperand(1))) {
Dan Gohman670f9372012-04-13 18:57:48 +0000709 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +0000710 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +0000711 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
712 Constant::getNullValue(Ty),
713 CI);
Michael Gottesmanfec61c02013-01-06 21:54:30 +0000714
715 llvm::Value *NewValue = UndefValue::get(CI->getType());
Michael Gottesman89279f82013-04-05 18:10:41 +0000716 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
717 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +0000718
Michael Gottesmanfec61c02013-01-06 21:54:30 +0000719 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +0000720 CI->eraseFromParent();
721 continue;
722 }
723 break;
724 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000725 case ARCInstKind::RetainRV:
John McCalld935e9c2011-06-15 23:37:01 +0000726 if (OptimizeRetainRVCall(F, Inst))
727 continue;
728 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000729 case ARCInstKind::AutoreleaseRV:
Michael Gottesman556ff612013-01-12 01:25:19 +0000730 OptimizeAutoreleaseRVCall(F, Inst, Class);
John McCalld935e9c2011-06-15 23:37:01 +0000731 break;
732 }
733
Michael Gottesmanb8c88362013-04-03 02:57:24 +0000734 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
John McCalld935e9c2011-06-15 23:37:01 +0000735 if (IsAutorelease(Class) && Inst->use_empty()) {
736 CallInst *Call = cast<CallInst>(Inst);
737 const Value *Arg = Call->getArgOperand(0);
738 Arg = FindSingleUseIdentifiedObject(Arg);
739 if (Arg) {
740 Changed = true;
741 ++NumAutoreleases;
742
743 // Create the declaration lazily.
744 LLVMContext &C = Inst->getContext();
Michael Gottesman01df4502013-07-06 01:41:35 +0000745
Michael Gottesmanca3a4722015-03-16 07:02:24 +0000746 Constant *Decl = EP.get(ARCRuntimeEntryPointKind::Release);
Michael Gottesman14acfac2013-07-06 01:39:23 +0000747 CallInst *NewCall = CallInst::Create(Decl, Call->getArgOperand(0), "",
748 Call);
Michael Gottesman65cb7372015-03-16 07:02:27 +0000749 NewCall->setMetadata(MDKindCache.get(ARCMDKindID::ImpreciseRelease),
Michael Gottesman41c01002015-03-06 00:34:33 +0000750 MDNode::get(C, None));
Michael Gottesman10426b52013-01-07 21:26:07 +0000751
Michael Gottesman89279f82013-04-05 18:10:41 +0000752 DEBUG(dbgs() << "Replacing autorelease{,RV}(x) with objc_release(x) "
753 "since x is otherwise unused.\nOld: " << *Call << "\nNew: "
754 << *NewCall << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +0000755
John McCalld935e9c2011-06-15 23:37:01 +0000756 EraseInstruction(Call);
757 Inst = NewCall;
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000758 Class = ARCInstKind::Release;
John McCalld935e9c2011-06-15 23:37:01 +0000759 }
760 }
761
762 // For functions which can never be passed stack arguments, add
763 // a tail keyword.
764 if (IsAlwaysTail(Class)) {
765 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +0000766 DEBUG(dbgs() << "Adding tail keyword to function since it can never be "
767 "passed stack args: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +0000768 cast<CallInst>(Inst)->setTailCall();
769 }
770
Michael Gottesmanc9656fa2013-01-12 01:25:15 +0000771 // Ensure that functions that can never have a "tail" keyword due to the
772 // semantics of ARC truly do not do so.
773 if (IsNeverTail(Class)) {
774 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +0000775 DEBUG(dbgs() << "Removing tail keyword from function: " << *Inst <<
Michael Gottesmanc9656fa2013-01-12 01:25:15 +0000776 "\n");
777 cast<CallInst>(Inst)->setTailCall(false);
778 }
779
John McCalld935e9c2011-06-15 23:37:01 +0000780 // Set nounwind as needed.
781 if (IsNoThrow(Class)) {
782 Changed = true;
Michael Gottesman89279f82013-04-05 18:10:41 +0000783 DEBUG(dbgs() << "Found no throw class. Setting nounwind on: " << *Inst
784 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +0000785 cast<CallInst>(Inst)->setDoesNotThrow();
786 }
787
788 if (!IsNoopOnNull(Class)) {
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000789 UsedInThisFunction |= 1 << unsigned(Class);
John McCalld935e9c2011-06-15 23:37:01 +0000790 continue;
791 }
792
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000793 const Value *Arg = GetArgRCIdentityRoot(Inst);
John McCalld935e9c2011-06-15 23:37:01 +0000794
795 // ARC calls with null are no-ops. Delete them.
Michael Gottesman65c24812013-03-25 09:27:43 +0000796 if (IsNullOrUndef(Arg)) {
John McCalld935e9c2011-06-15 23:37:01 +0000797 Changed = true;
798 ++NumNoops;
Michael Gottesman89279f82013-04-05 18:10:41 +0000799 DEBUG(dbgs() << "ARC calls with null are no-ops. Erasing: " << *Inst
800 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +0000801 EraseInstruction(Inst);
802 continue;
803 }
804
805 // Keep track of which of retain, release, autorelease, and retain_block
806 // are actually present in this function.
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000807 UsedInThisFunction |= 1 << unsigned(Class);
John McCalld935e9c2011-06-15 23:37:01 +0000808
809 // If Arg is a PHI, and one or more incoming values to the
810 // PHI are null, and the call is control-equivalent to the PHI, and there
811 // are no relevant side effects between the PHI and the call, the call
812 // could be pushed up to just those paths with non-null incoming values.
813 // For now, don't bother splitting critical edges for this.
814 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
815 Worklist.push_back(std::make_pair(Inst, Arg));
816 do {
817 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
818 Inst = Pair.first;
819 Arg = Pair.second;
820
821 const PHINode *PN = dyn_cast<PHINode>(Arg);
822 if (!PN) continue;
823
824 // Determine if the PHI has any null operands, or any incoming
825 // critical edges.
826 bool HasNull = false;
827 bool HasCriticalEdges = false;
828 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
829 Value *Incoming =
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000830 GetRCIdentityRoot(PN->getIncomingValue(i));
Michael Gottesman65c24812013-03-25 09:27:43 +0000831 if (IsNullOrUndef(Incoming))
John McCalld935e9c2011-06-15 23:37:01 +0000832 HasNull = true;
833 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
834 .getNumSuccessors() != 1) {
835 HasCriticalEdges = true;
836 break;
837 }
838 }
839 // If we have null operands and no critical edges, optimize.
840 if (!HasCriticalEdges && HasNull) {
841 SmallPtrSet<Instruction *, 4> DependingInstructions;
842 SmallPtrSet<const BasicBlock *, 4> Visited;
843
844 // Check that there is nothing that cares about the reference
845 // count between the call and the phi.
Dan Gohman8478d762012-04-13 00:59:57 +0000846 switch (Class) {
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000847 case ARCInstKind::Retain:
848 case ARCInstKind::RetainBlock:
Dan Gohman8478d762012-04-13 00:59:57 +0000849 // These can always be moved up.
850 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000851 case ARCInstKind::Release:
Dan Gohman41375a32012-05-08 23:39:44 +0000852 // These can't be moved across things that care about the retain
853 // count.
Dan Gohman8478d762012-04-13 00:59:57 +0000854 FindDependencies(NeedsPositiveRetainCount, Arg,
855 Inst->getParent(), Inst,
856 DependingInstructions, Visited, PA);
857 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000858 case ARCInstKind::Autorelease:
Dan Gohman8478d762012-04-13 00:59:57 +0000859 // These can't be moved across autorelease pool scope boundaries.
860 FindDependencies(AutoreleasePoolBoundary, Arg,
861 Inst->getParent(), Inst,
862 DependingInstructions, Visited, PA);
863 break;
Frederic Riss009d6062016-02-17 18:51:27 +0000864 case ARCInstKind::ClaimRV:
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000865 case ARCInstKind::RetainRV:
866 case ARCInstKind::AutoreleaseRV:
Dan Gohman8478d762012-04-13 00:59:57 +0000867 // Don't move these; the RV optimization depends on the autoreleaseRV
868 // being tail called, and the retainRV being immediately after a call
869 // (which might still happen if we get lucky with codegen layout, but
870 // it's not worth taking the chance).
871 continue;
872 default:
873 llvm_unreachable("Invalid dependence flavor");
874 }
875
John McCalld935e9c2011-06-15 23:37:01 +0000876 if (DependingInstructions.size() == 1 &&
877 *DependingInstructions.begin() == PN) {
878 Changed = true;
879 ++NumPartialNoops;
880 // Clone the call into each predecessor that has a non-null value.
881 CallInst *CInst = cast<CallInst>(Inst);
Chris Lattner229907c2011-07-18 04:54:35 +0000882 Type *ParamTy = CInst->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +0000883 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
884 Value *Incoming =
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000885 GetRCIdentityRoot(PN->getIncomingValue(i));
Michael Gottesman65c24812013-03-25 09:27:43 +0000886 if (!IsNullOrUndef(Incoming)) {
John McCalld935e9c2011-06-15 23:37:01 +0000887 CallInst *Clone = cast<CallInst>(CInst->clone());
888 Value *Op = PN->getIncomingValue(i);
889 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
890 if (Op->getType() != ParamTy)
891 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
892 Clone->setArgOperand(0, Op);
893 Clone->insertBefore(InsertPos);
Michael Gottesmanc189a392013-01-09 19:23:24 +0000894
Michael Gottesman89279f82013-04-05 18:10:41 +0000895 DEBUG(dbgs() << "Cloning "
Michael Gottesmanc189a392013-01-09 19:23:24 +0000896 << *CInst << "\n"
Michael Gottesman89279f82013-04-05 18:10:41 +0000897 "And inserting clone at " << *InsertPos << "\n");
John McCalld935e9c2011-06-15 23:37:01 +0000898 Worklist.push_back(std::make_pair(Clone, Incoming));
899 }
900 }
901 // Erase the original call.
Michael Gottesmanc189a392013-01-09 19:23:24 +0000902 DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +0000903 EraseInstruction(CInst);
904 continue;
905 }
906 }
907 } while (!Worklist.empty());
908 }
909}
910
Michael Gottesman323964c2013-04-18 05:39:45 +0000911/// If we have a top down pointer in the S_Use state, make sure that there are
912/// no CFG hazards by checking the states of various bottom up pointers.
913static void CheckForUseCFGHazard(const Sequence SuccSSeq,
914 const bool SuccSRRIKnownSafe,
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000915 TopDownPtrState &S,
Michael Gottesman323964c2013-04-18 05:39:45 +0000916 bool &SomeSuccHasSame,
917 bool &AllSuccsHaveSame,
Michael Gottesmane67f40c2013-05-24 20:44:05 +0000918 bool &NotAllSeqEqualButKnownSafe,
Michael Gottesman323964c2013-04-18 05:39:45 +0000919 bool &ShouldContinue) {
920 switch (SuccSSeq) {
921 case S_CanRelease: {
Michael Gottesman93132252013-06-21 06:59:02 +0000922 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe) {
Michael Gottesman323964c2013-04-18 05:39:45 +0000923 S.ClearSequenceProgress();
924 break;
925 }
Michael Gottesman2f294592013-06-21 19:12:36 +0000926 S.SetCFGHazardAfflicted(true);
Michael Gottesman323964c2013-04-18 05:39:45 +0000927 ShouldContinue = true;
928 break;
929 }
930 case S_Use:
931 SomeSuccHasSame = true;
932 break;
933 case S_Stop:
934 case S_Release:
935 case S_MovableRelease:
Michael Gottesman93132252013-06-21 06:59:02 +0000936 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe)
Michael Gottesman323964c2013-04-18 05:39:45 +0000937 AllSuccsHaveSame = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +0000938 else
939 NotAllSeqEqualButKnownSafe = true;
Michael Gottesman323964c2013-04-18 05:39:45 +0000940 break;
941 case S_Retain:
942 llvm_unreachable("bottom-up pointer in retain state!");
943 case S_None:
944 llvm_unreachable("This should have been handled earlier.");
945 }
946}
947
948/// If we have a Top Down pointer in the S_CanRelease state, make sure that
949/// there are no CFG hazards by checking the states of various bottom up
950/// pointers.
951static void CheckForCanReleaseCFGHazard(const Sequence SuccSSeq,
952 const bool SuccSRRIKnownSafe,
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000953 TopDownPtrState &S,
Michael Gottesman323964c2013-04-18 05:39:45 +0000954 bool &SomeSuccHasSame,
Michael Gottesmane67f40c2013-05-24 20:44:05 +0000955 bool &AllSuccsHaveSame,
956 bool &NotAllSeqEqualButKnownSafe) {
Michael Gottesman323964c2013-04-18 05:39:45 +0000957 switch (SuccSSeq) {
958 case S_CanRelease:
959 SomeSuccHasSame = true;
960 break;
961 case S_Stop:
962 case S_Release:
963 case S_MovableRelease:
964 case S_Use:
Michael Gottesman93132252013-06-21 06:59:02 +0000965 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe)
Michael Gottesman323964c2013-04-18 05:39:45 +0000966 AllSuccsHaveSame = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +0000967 else
968 NotAllSeqEqualButKnownSafe = true;
Michael Gottesman323964c2013-04-18 05:39:45 +0000969 break;
970 case S_Retain:
971 llvm_unreachable("bottom-up pointer in retain state!");
972 case S_None:
973 llvm_unreachable("This should have been handled earlier.");
974 }
975}
976
Michael Gottesman97e3df02013-01-14 00:35:14 +0000977/// Check for critical edges, loop boundaries, irreducible control flow, or
978/// other CFG structures where moving code across the edge would result in it
979/// being executed more.
John McCalld935e9c2011-06-15 23:37:01 +0000980void
981ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
982 DenseMap<const BasicBlock *, BBState> &BBStates,
983 BBState &MyStates) const {
984 // If any top-down local-use or possible-dec has a succ which is earlier in
985 // the sequence, forget it.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000986 for (auto I = MyStates.top_down_ptr_begin(), E = MyStates.top_down_ptr_end();
987 I != E; ++I) {
988 TopDownPtrState &S = I->second;
Michael Gottesman323964c2013-04-18 05:39:45 +0000989 const Sequence Seq = I->second.GetSeq();
Dan Gohman0155f302012-02-17 18:59:53 +0000990
Michael Gottesman323964c2013-04-18 05:39:45 +0000991 // We only care about S_Retain, S_CanRelease, and S_Use.
992 if (Seq == S_None)
993 continue;
Dan Gohman0155f302012-02-17 18:59:53 +0000994
Michael Gottesman323964c2013-04-18 05:39:45 +0000995 // Make sure that if extra top down states are added in the future that this
996 // code is updated to handle it.
997 assert((Seq == S_Retain || Seq == S_CanRelease || Seq == S_Use) &&
998 "Unknown top down sequence state.");
999
1000 const Value *Arg = I->first;
1001 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
1002 bool SomeSuccHasSame = false;
1003 bool AllSuccsHaveSame = true;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001004 bool NotAllSeqEqualButKnownSafe = false;
Michael Gottesman323964c2013-04-18 05:39:45 +00001005
1006 succ_const_iterator SI(TI), SE(TI, false);
1007
1008 for (; SI != SE; ++SI) {
1009 // If VisitBottomUp has pointer information for this successor, take
1010 // what we know about it.
1011 const DenseMap<const BasicBlock *, BBState>::iterator BBI =
1012 BBStates.find(*SI);
1013 assert(BBI != BBStates.end());
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001014 const BottomUpPtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
Michael Gottesman323964c2013-04-18 05:39:45 +00001015 const Sequence SuccSSeq = SuccS.GetSeq();
1016
1017 // If bottom up, the pointer is in an S_None state, clear the sequence
1018 // progress since the sequence in the bottom up state finished
1019 // suggesting a mismatch in between retains/releases. This is true for
1020 // all three cases that we are handling here: S_Retain, S_Use, and
1021 // S_CanRelease.
1022 if (SuccSSeq == S_None) {
Dan Gohman12130272011-08-12 00:26:31 +00001023 S.ClearSequenceProgress();
Michael Gottesman323964c2013-04-18 05:39:45 +00001024 continue;
1025 }
1026
1027 // If we have S_Use or S_CanRelease, perform our check for cfg hazard
1028 // checks.
Michael Gottesman93132252013-06-21 06:59:02 +00001029 const bool SuccSRRIKnownSafe = SuccS.IsKnownSafe();
Michael Gottesman323964c2013-04-18 05:39:45 +00001030
1031 // *NOTE* We do not use Seq from above here since we are allowing for
1032 // S.GetSeq() to change while we are visiting basic blocks.
1033 switch(S.GetSeq()) {
1034 case S_Use: {
1035 bool ShouldContinue = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001036 CheckForUseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S, SomeSuccHasSame,
1037 AllSuccsHaveSame, NotAllSeqEqualButKnownSafe,
Michael Gottesman323964c2013-04-18 05:39:45 +00001038 ShouldContinue);
1039 if (ShouldContinue)
1040 continue;
1041 break;
1042 }
1043 case S_CanRelease: {
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001044 CheckForCanReleaseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S,
1045 SomeSuccHasSame, AllSuccsHaveSame,
1046 NotAllSeqEqualButKnownSafe);
Michael Gottesman323964c2013-04-18 05:39:45 +00001047 break;
1048 }
1049 case S_Retain:
1050 case S_None:
1051 case S_Stop:
1052 case S_Release:
1053 case S_MovableRelease:
1054 break;
1055 }
John McCalld935e9c2011-06-15 23:37:01 +00001056 }
Michael Gottesman323964c2013-04-18 05:39:45 +00001057
1058 // If the state at the other end of any of the successor edges
1059 // matches the current state, require all edges to match. This
1060 // guards against loops in the middle of a sequence.
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001061 if (SomeSuccHasSame && !AllSuccsHaveSame) {
Michael Gottesman323964c2013-04-18 05:39:45 +00001062 S.ClearSequenceProgress();
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001063 } else if (NotAllSeqEqualButKnownSafe) {
1064 // If we would have cleared the state foregoing the fact that we are known
1065 // safe, stop code motion. This is because whether or not it is safe to
1066 // remove RR pairs via KnownSafe is an orthogonal concept to whether we
1067 // are allowed to perform code motion.
Michael Gottesman2f294592013-06-21 19:12:36 +00001068 S.SetCFGHazardAfflicted(true);
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001069 }
Michael Gottesman323964c2013-04-18 05:39:45 +00001070 }
John McCalld935e9c2011-06-15 23:37:01 +00001071}
1072
Michael Gottesman0be69202015-03-05 23:28:58 +00001073bool ObjCARCOpt::VisitInstructionBottomUp(
1074 Instruction *Inst, BasicBlock *BB, BlotMapVector<Value *, RRInfo> &Retains,
1075 BBState &MyStates) {
Dan Gohman817a7c62012-03-22 18:24:56 +00001076 bool NestingDetected = false;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001077 ARCInstKind Class = GetARCInstKind(Inst);
Craig Topperf40110f2014-04-25 05:29:35 +00001078 const Value *Arg = nullptr;
Michael Gottesman79249972013-04-05 23:46:45 +00001079
Michael Gottesmanc01ab512015-03-16 07:02:39 +00001080 DEBUG(dbgs() << " Class: " << Class << "\n");
Michael Gottesman79249972013-04-05 23:46:45 +00001081
Dan Gohman817a7c62012-03-22 18:24:56 +00001082 switch (Class) {
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001083 case ARCInstKind::Release: {
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001084 Arg = GetArgRCIdentityRoot(Inst);
Dan Gohman817a7c62012-03-22 18:24:56 +00001085
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001086 BottomUpPtrState &S = MyStates.getPtrBottomUpState(Arg);
Michael Gottesman4eae3962015-03-06 00:34:39 +00001087 NestingDetected |= S.InitBottomUp(MDKindCache, Inst);
Dan Gohman817a7c62012-03-22 18:24:56 +00001088 break;
1089 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001090 case ARCInstKind::RetainBlock:
Michael Gottesman158fdf62013-03-28 20:11:19 +00001091 // In OptimizeIndividualCalls, we have strength reduced all optimizable
1092 // objc_retainBlocks to objc_retains. Thus at this point any
1093 // objc_retainBlocks that we see are not optimizable.
1094 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001095 case ARCInstKind::Retain:
1096 case ARCInstKind::RetainRV: {
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001097 Arg = GetArgRCIdentityRoot(Inst);
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001098 BottomUpPtrState &S = MyStates.getPtrBottomUpState(Arg);
Michael Gottesman60805962015-03-06 00:34:42 +00001099 if (S.MatchWithRetain()) {
1100 // Don't do retain+release tracking for ARCInstKind::RetainRV, because
1101 // it's better to let it remain as the first instruction after a call.
Michael Gottesmanc01ab512015-03-16 07:02:39 +00001102 if (Class != ARCInstKind::RetainRV) {
1103 DEBUG(llvm::dbgs() << " Matching with: " << *Inst << "\n");
Michael Gottesmane3943d02013-06-21 19:44:30 +00001104 Retains[Inst] = S.GetRRInfo();
Michael Gottesmanc01ab512015-03-16 07:02:39 +00001105 }
Dan Gohman817a7c62012-03-22 18:24:56 +00001106 S.ClearSequenceProgress();
Dan Gohman817a7c62012-03-22 18:24:56 +00001107 }
Michael Gottesman31ba23a2013-04-05 22:54:32 +00001108 // A retain moving bottom up can be a use.
1109 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001110 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001111 case ARCInstKind::AutoreleasepoolPop:
Dan Gohman817a7c62012-03-22 18:24:56 +00001112 // Conservatively, clear MyStates for all known pointers.
1113 MyStates.clearBottomUpPointers();
1114 return NestingDetected;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001115 case ARCInstKind::AutoreleasepoolPush:
1116 case ARCInstKind::None:
Dan Gohman817a7c62012-03-22 18:24:56 +00001117 // These are irrelevant.
1118 return NestingDetected;
1119 default:
1120 break;
1121 }
1122
1123 // Consider any other possible effects of this instruction on each
1124 // pointer being tracked.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001125 for (auto MI = MyStates.bottom_up_ptr_begin(),
1126 ME = MyStates.bottom_up_ptr_end();
1127 MI != ME; ++MI) {
Dan Gohman817a7c62012-03-22 18:24:56 +00001128 const Value *Ptr = MI->first;
1129 if (Ptr == Arg)
1130 continue; // Handled above.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001131 BottomUpPtrState &S = MI->second;
Dan Gohman817a7c62012-03-22 18:24:56 +00001132
Michael Gottesman16e6a202015-03-06 02:07:12 +00001133 if (S.HandlePotentialAlterRefCount(Inst, Ptr, PA, Class))
1134 continue;
Dan Gohman817a7c62012-03-22 18:24:56 +00001135
Michael Gottesman16e6a202015-03-06 02:07:12 +00001136 S.HandlePotentialUse(BB, Inst, Ptr, PA, Class);
Dan Gohman817a7c62012-03-22 18:24:56 +00001137 }
1138
1139 return NestingDetected;
1140}
1141
Michael Gottesman0be69202015-03-05 23:28:58 +00001142bool ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
1143 DenseMap<const BasicBlock *, BBState> &BBStates,
1144 BlotMapVector<Value *, RRInfo> &Retains) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001145
1146 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitBottomUp ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00001147
John McCalld935e9c2011-06-15 23:37:01 +00001148 bool NestingDetected = false;
1149 BBState &MyStates = BBStates[BB];
1150
1151 // Merge the states from each successor to compute the initial state
1152 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00001153 BBState::edge_iterator SI(MyStates.succ_begin()),
1154 SE(MyStates.succ_end());
1155 if (SI != SE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001156 const BasicBlock *Succ = *SI;
1157 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
1158 assert(I != BBStates.end());
1159 MyStates.InitFromSucc(I->second);
1160 ++SI;
1161 for (; SI != SE; ++SI) {
1162 Succ = *SI;
1163 I = BBStates.find(Succ);
1164 assert(I != BBStates.end());
1165 MyStates.MergeSucc(I->second);
1166 }
Michael Gottesman60f6b282013-03-29 05:13:07 +00001167 }
Michael Gottesmancd4de0f2013-03-26 00:42:09 +00001168
Michael Gottesmanc01ab512015-03-16 07:02:39 +00001169 DEBUG(llvm::dbgs() << "Before:\n" << BBStates[BB] << "\n"
1170 << "Performing Dataflow:\n");
1171
John McCalld935e9c2011-06-15 23:37:01 +00001172 // Visit all the instructions, bottom-up.
1173 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +00001174 Instruction *Inst = &*std::prev(I);
Dan Gohman5c70fad2012-03-23 17:47:54 +00001175
1176 // Invoke instructions are visited as part of their successors (below).
1177 if (isa<InvokeInst>(Inst))
1178 continue;
1179
Michael Gottesmanc01ab512015-03-16 07:02:39 +00001180 DEBUG(dbgs() << " Visiting " << *Inst << "\n");
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001181
Dan Gohman5c70fad2012-03-23 17:47:54 +00001182 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
1183 }
1184
Dan Gohmandae33492012-04-27 18:56:31 +00001185 // If there's a predecessor with an invoke, visit the invoke as if it were
1186 // part of this block, since we can't insert code after an invoke in its own
1187 // block, and we don't want to split critical edges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001188 for (BBState::edge_iterator PI(MyStates.pred_begin()),
1189 PE(MyStates.pred_end()); PI != PE; ++PI) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00001190 BasicBlock *Pred = *PI;
Dan Gohmandae33492012-04-27 18:56:31 +00001191 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
1192 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
Dan Gohman817a7c62012-03-22 18:24:56 +00001193 }
John McCalld935e9c2011-06-15 23:37:01 +00001194
Michael Gottesmanc01ab512015-03-16 07:02:39 +00001195 DEBUG(llvm::dbgs() << "\nFinal State:\n" << BBStates[BB] << "\n");
1196
Dan Gohman817a7c62012-03-22 18:24:56 +00001197 return NestingDetected;
1198}
John McCalld935e9c2011-06-15 23:37:01 +00001199
Dan Gohman817a7c62012-03-22 18:24:56 +00001200bool
1201ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
1202 DenseMap<Value *, RRInfo> &Releases,
1203 BBState &MyStates) {
1204 bool NestingDetected = false;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001205 ARCInstKind Class = GetARCInstKind(Inst);
Craig Topperf40110f2014-04-25 05:29:35 +00001206 const Value *Arg = nullptr;
John McCalld935e9c2011-06-15 23:37:01 +00001207
Michael Gottesmanc01ab512015-03-16 07:02:39 +00001208 DEBUG(llvm::dbgs() << " Class: " << Class << "\n");
1209
Dan Gohman817a7c62012-03-22 18:24:56 +00001210 switch (Class) {
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001211 case ARCInstKind::RetainBlock:
Michael Gottesman158fdf62013-03-28 20:11:19 +00001212 // In OptimizeIndividualCalls, we have strength reduced all optimizable
1213 // objc_retainBlocks to objc_retains. Thus at this point any
Michael Gottesman60805962015-03-06 00:34:42 +00001214 // objc_retainBlocks that we see are not optimizable. We need to break since
1215 // a retain can be a potential use.
Michael Gottesman158fdf62013-03-28 20:11:19 +00001216 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001217 case ARCInstKind::Retain:
1218 case ARCInstKind::RetainRV: {
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001219 Arg = GetArgRCIdentityRoot(Inst);
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001220 TopDownPtrState &S = MyStates.getPtrTopDownState(Arg);
Michael Gottesman4eae3962015-03-06 00:34:39 +00001221 NestingDetected |= S.InitTopDown(Class, Inst);
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001222 // A retain can be a potential use; proceed to the generic checking
Dan Gohmanf64ff8e2012-07-23 19:27:31 +00001223 // code below.
1224 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001225 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001226 case ARCInstKind::Release: {
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001227 Arg = GetArgRCIdentityRoot(Inst);
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001228 TopDownPtrState &S = MyStates.getPtrTopDownState(Arg);
Michael Gottesman60805962015-03-06 00:34:42 +00001229 // Try to form a tentative pair in between this release instruction and the
1230 // top down pointers that we are tracking.
1231 if (S.MatchWithRelease(MDKindCache, Inst)) {
1232 // If we succeed, copy S's RRInfo into the Release -> {Retain Set
1233 // Map}. Then we clear S.
Michael Gottesmanc01ab512015-03-16 07:02:39 +00001234 DEBUG(llvm::dbgs() << " Matching with: " << *Inst << "\n");
Michael Gottesmane3943d02013-06-21 19:44:30 +00001235 Releases[Inst] = S.GetRRInfo();
Dan Gohman817a7c62012-03-22 18:24:56 +00001236 S.ClearSequenceProgress();
Dan Gohman817a7c62012-03-22 18:24:56 +00001237 }
1238 break;
1239 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001240 case ARCInstKind::AutoreleasepoolPop:
Dan Gohman817a7c62012-03-22 18:24:56 +00001241 // Conservatively, clear MyStates for all known pointers.
1242 MyStates.clearTopDownPointers();
Michael Gottesman60805962015-03-06 00:34:42 +00001243 return false;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001244 case ARCInstKind::AutoreleasepoolPush:
1245 case ARCInstKind::None:
Michael Gottesman60805962015-03-06 00:34:42 +00001246 // These can not be uses of
1247 return false;
Dan Gohman817a7c62012-03-22 18:24:56 +00001248 default:
1249 break;
1250 }
1251
1252 // Consider any other possible effects of this instruction on each
1253 // pointer being tracked.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001254 for (auto MI = MyStates.top_down_ptr_begin(),
1255 ME = MyStates.top_down_ptr_end();
1256 MI != ME; ++MI) {
Dan Gohman817a7c62012-03-22 18:24:56 +00001257 const Value *Ptr = MI->first;
1258 if (Ptr == Arg)
1259 continue; // Handled above.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001260 TopDownPtrState &S = MI->second;
Michael Gottesman16e6a202015-03-06 02:07:12 +00001261 if (S.HandlePotentialAlterRefCount(Inst, Ptr, PA, Class))
1262 continue;
Dan Gohman817a7c62012-03-22 18:24:56 +00001263
Michael Gottesman16e6a202015-03-06 02:07:12 +00001264 S.HandlePotentialUse(Inst, Ptr, PA, Class);
John McCalld935e9c2011-06-15 23:37:01 +00001265 }
1266
1267 return NestingDetected;
1268}
1269
1270bool
1271ObjCARCOpt::VisitTopDown(BasicBlock *BB,
1272 DenseMap<const BasicBlock *, BBState> &BBStates,
1273 DenseMap<Value *, RRInfo> &Releases) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001274 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitTopDown ==\n");
John McCalld935e9c2011-06-15 23:37:01 +00001275 bool NestingDetected = false;
1276 BBState &MyStates = BBStates[BB];
1277
1278 // Merge the states from each predecessor to compute the initial state
1279 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00001280 BBState::edge_iterator PI(MyStates.pred_begin()),
1281 PE(MyStates.pred_end());
1282 if (PI != PE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001283 const BasicBlock *Pred = *PI;
1284 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
1285 assert(I != BBStates.end());
1286 MyStates.InitFromPred(I->second);
1287 ++PI;
1288 for (; PI != PE; ++PI) {
1289 Pred = *PI;
1290 I = BBStates.find(Pred);
1291 assert(I != BBStates.end());
1292 MyStates.MergePred(I->second);
1293 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001294 }
John McCalld935e9c2011-06-15 23:37:01 +00001295
Michael Gottesmanc01ab512015-03-16 07:02:39 +00001296 DEBUG(llvm::dbgs() << "Before:\n" << BBStates[BB] << "\n"
1297 << "Performing Dataflow:\n");
1298
John McCalld935e9c2011-06-15 23:37:01 +00001299 // Visit all the instructions, top-down.
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +00001300 for (Instruction &Inst : *BB) {
1301 DEBUG(dbgs() << " Visiting " << Inst << "\n");
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001302
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +00001303 NestingDetected |= VisitInstructionTopDown(&Inst, Releases, MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00001304 }
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00001305
Michael Gottesmanc01ab512015-03-16 07:02:39 +00001306 DEBUG(llvm::dbgs() << "\nState Before Checking for CFG Hazards:\n"
1307 << BBStates[BB] << "\n\n");
John McCalld935e9c2011-06-15 23:37:01 +00001308 CheckForCFGHazards(BB, BBStates, MyStates);
Michael Gottesmanc01ab512015-03-16 07:02:39 +00001309 DEBUG(llvm::dbgs() << "Final State:\n" << BBStates[BB] << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001310 return NestingDetected;
1311}
1312
Dan Gohmana53a12c2011-12-12 19:42:25 +00001313static void
1314ComputePostOrders(Function &F,
1315 SmallVectorImpl<BasicBlock *> &PostOrder,
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001316 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
1317 unsigned NoObjCARCExceptionsMDKind,
1318 DenseMap<const BasicBlock *, BBState> &BBStates) {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001319 /// The visited set, for doing DFS walks.
Dan Gohmana53a12c2011-12-12 19:42:25 +00001320 SmallPtrSet<BasicBlock *, 16> Visited;
1321
1322 // Do DFS, computing the PostOrder.
1323 SmallPtrSet<BasicBlock *, 16> OnStack;
1324 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001325
1326 // Functions always have exactly one entry block, and we don't have
1327 // any other block that we treat like an entry block.
Dan Gohmana53a12c2011-12-12 19:42:25 +00001328 BasicBlock *EntryBB = &F.getEntryBlock();
Dan Gohman41375a32012-05-08 23:39:44 +00001329 BBState &MyStates = BBStates[EntryBB];
1330 MyStates.SetAsEntry();
1331 TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
1332 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
Dan Gohmana53a12c2011-12-12 19:42:25 +00001333 Visited.insert(EntryBB);
1334 OnStack.insert(EntryBB);
1335 do {
1336 dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001337 BasicBlock *CurrBB = SuccStack.back().first;
1338 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
1339 succ_iterator SE(TI, false);
Dan Gohman41375a32012-05-08 23:39:44 +00001340
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001341 while (SuccStack.back().second != SE) {
1342 BasicBlock *SuccBB = *SuccStack.back().second++;
David Blaikie70573dc2014-11-19 07:49:26 +00001343 if (Visited.insert(SuccBB).second) {
Dan Gohman41375a32012-05-08 23:39:44 +00001344 TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
1345 SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001346 BBStates[CurrBB].addSucc(SuccBB);
Dan Gohman41375a32012-05-08 23:39:44 +00001347 BBState &SuccStates = BBStates[SuccBB];
1348 SuccStates.addPred(CurrBB);
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001349 OnStack.insert(SuccBB);
Dan Gohmana53a12c2011-12-12 19:42:25 +00001350 goto dfs_next_succ;
1351 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001352
1353 if (!OnStack.count(SuccBB)) {
1354 BBStates[CurrBB].addSucc(SuccBB);
1355 BBStates[SuccBB].addPred(CurrBB);
1356 }
Dan Gohmana53a12c2011-12-12 19:42:25 +00001357 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001358 OnStack.erase(CurrBB);
1359 PostOrder.push_back(CurrBB);
1360 SuccStack.pop_back();
Dan Gohmana53a12c2011-12-12 19:42:25 +00001361 } while (!SuccStack.empty());
1362
1363 Visited.clear();
1364
Dan Gohmana53a12c2011-12-12 19:42:25 +00001365 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001366 // Functions may have many exits, and there also blocks which we treat
1367 // as exits due to ignored edges.
1368 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +00001369 for (BasicBlock &ExitBB : F) {
1370 BBState &MyStates = BBStates[&ExitBB];
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001371 if (!MyStates.isExit())
1372 continue;
1373
Dan Gohmandae33492012-04-27 18:56:31 +00001374 MyStates.SetAsExit();
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001375
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +00001376 PredStack.push_back(std::make_pair(&ExitBB, MyStates.pred_begin()));
1377 Visited.insert(&ExitBB);
Dan Gohmana53a12c2011-12-12 19:42:25 +00001378 while (!PredStack.empty()) {
1379 reverse_dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001380 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
1381 while (PredStack.back().second != PE) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00001382 BasicBlock *BB = *PredStack.back().second++;
David Blaikie70573dc2014-11-19 07:49:26 +00001383 if (Visited.insert(BB).second) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001384 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00001385 goto reverse_dfs_next_succ;
1386 }
1387 }
1388 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
1389 }
1390 }
1391}
1392
Michael Gottesman97e3df02013-01-14 00:35:14 +00001393// Visit the function both top-down and bottom-up.
Michael Gottesman0be69202015-03-05 23:28:58 +00001394bool ObjCARCOpt::Visit(Function &F,
1395 DenseMap<const BasicBlock *, BBState> &BBStates,
1396 BlotMapVector<Value *, RRInfo> &Retains,
1397 DenseMap<Value *, RRInfo> &Releases) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00001398
1399 // Use reverse-postorder traversals, because we magically know that loops
1400 // will be well behaved, i.e. they won't repeatedly call retain on a single
1401 // pointer without doing a release. We can't use the ReversePostOrderTraversal
1402 // class here because we want the reverse-CFG postorder to consider each
1403 // function exit point, and we want to ignore selected cycle edges.
1404 SmallVector<BasicBlock *, 16> PostOrder;
1405 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001406 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
Michael Gottesman65cb7372015-03-16 07:02:27 +00001407 MDKindCache.get(ARCMDKindID::NoObjCARCExceptions),
1408 BBStates);
Dan Gohmana53a12c2011-12-12 19:42:25 +00001409
1410 // Use reverse-postorder on the reverse CFG for bottom-up.
John McCalld935e9c2011-06-15 23:37:01 +00001411 bool BottomUpNestingDetected = false;
David Majnemerd7708772016-06-24 04:05:21 +00001412 for (BasicBlock *BB : reverse(ReverseCFGPostOrder))
1413 BottomUpNestingDetected |= VisitBottomUp(BB, BBStates, Retains);
John McCalld935e9c2011-06-15 23:37:01 +00001414
Dan Gohmana53a12c2011-12-12 19:42:25 +00001415 // Use reverse-postorder for top-down.
John McCalld935e9c2011-06-15 23:37:01 +00001416 bool TopDownNestingDetected = false;
David Majnemerd7708772016-06-24 04:05:21 +00001417 for (BasicBlock *BB : reverse(PostOrder))
1418 TopDownNestingDetected |= VisitTopDown(BB, BBStates, Releases);
John McCalld935e9c2011-06-15 23:37:01 +00001419
1420 return TopDownNestingDetected && BottomUpNestingDetected;
1421}
1422
Michael Gottesman97e3df02013-01-14 00:35:14 +00001423/// Move the calls in RetainsToMove and ReleasesToMove.
Michael Gottesman0be69202015-03-05 23:28:58 +00001424void ObjCARCOpt::MoveCalls(Value *Arg, RRInfo &RetainsToMove,
John McCalld935e9c2011-06-15 23:37:01 +00001425 RRInfo &ReleasesToMove,
Michael Gottesman0be69202015-03-05 23:28:58 +00001426 BlotMapVector<Value *, RRInfo> &Retains,
John McCalld935e9c2011-06-15 23:37:01 +00001427 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman6320f522011-07-22 22:29:21 +00001428 SmallVectorImpl<Instruction *> &DeadInsts,
Michael Gottesman79249972013-04-05 23:46:45 +00001429 Module *M) {
Chris Lattner229907c2011-07-18 04:54:35 +00001430 Type *ArgTy = Arg->getType();
Dan Gohman6320f522011-07-22 22:29:21 +00001431 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
Michael Gottesman79249972013-04-05 23:46:45 +00001432
Michael Gottesman89279f82013-04-05 18:10:41 +00001433 DEBUG(dbgs() << "== ObjCARCOpt::MoveCalls ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00001434
John McCalld935e9c2011-06-15 23:37:01 +00001435 // Insert the new retain and release calls.
Craig Topper46276792014-08-24 23:23:06 +00001436 for (Instruction *InsertPt : ReleasesToMove.ReverseInsertPts) {
John McCalld935e9c2011-06-15 23:37:01 +00001437 Value *MyArg = ArgTy == ParamTy ? Arg :
1438 new BitCastInst(Arg, ParamTy, "", InsertPt);
Michael Gottesmanca3a4722015-03-16 07:02:24 +00001439 Constant *Decl = EP.get(ARCRuntimeEntryPointKind::Retain);
Michael Gottesman14acfac2013-07-06 01:39:23 +00001440 CallInst *Call = CallInst::Create(Decl, MyArg, "", InsertPt);
John McCalld935e9c2011-06-15 23:37:01 +00001441 Call->setDoesNotThrow();
Michael Gottesmanba648592013-03-28 23:08:44 +00001442 Call->setTailCall();
Michael Gottesman60f6b282013-03-29 05:13:07 +00001443
Michael Gottesmandf110ac2013-04-21 00:30:50 +00001444 DEBUG(dbgs() << "Inserting new Retain: " << *Call << "\n"
Michael Gottesman89279f82013-04-05 18:10:41 +00001445 "At insertion point: " << *InsertPt << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001446 }
Craig Topper46276792014-08-24 23:23:06 +00001447 for (Instruction *InsertPt : RetainsToMove.ReverseInsertPts) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00001448 Value *MyArg = ArgTy == ParamTy ? Arg :
1449 new BitCastInst(Arg, ParamTy, "", InsertPt);
Michael Gottesmanca3a4722015-03-16 07:02:24 +00001450 Constant *Decl = EP.get(ARCRuntimeEntryPointKind::Release);
Michael Gottesman14acfac2013-07-06 01:39:23 +00001451 CallInst *Call = CallInst::Create(Decl, MyArg, "", InsertPt);
Dan Gohman5c70fad2012-03-23 17:47:54 +00001452 // Attach a clang.imprecise_release metadata tag, if appropriate.
1453 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
Michael Gottesman65cb7372015-03-16 07:02:27 +00001454 Call->setMetadata(MDKindCache.get(ARCMDKindID::ImpreciseRelease), M);
Dan Gohman5c70fad2012-03-23 17:47:54 +00001455 Call->setDoesNotThrow();
1456 if (ReleasesToMove.IsTailCallRelease)
1457 Call->setTailCall();
Michael Gottesmanc189a392013-01-09 19:23:24 +00001458
Michael Gottesman89279f82013-04-05 18:10:41 +00001459 DEBUG(dbgs() << "Inserting new Release: " << *Call << "\n"
1460 "At insertion point: " << *InsertPt << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001461 }
1462
1463 // Delete the original retain and release calls.
Craig Topper46276792014-08-24 23:23:06 +00001464 for (Instruction *OrigRetain : RetainsToMove.Calls) {
John McCalld935e9c2011-06-15 23:37:01 +00001465 Retains.blot(OrigRetain);
1466 DeadInsts.push_back(OrigRetain);
Michael Gottesman89279f82013-04-05 18:10:41 +00001467 DEBUG(dbgs() << "Deleting retain: " << *OrigRetain << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001468 }
Craig Topper46276792014-08-24 23:23:06 +00001469 for (Instruction *OrigRelease : ReleasesToMove.Calls) {
John McCalld935e9c2011-06-15 23:37:01 +00001470 Releases.erase(OrigRelease);
1471 DeadInsts.push_back(OrigRelease);
Michael Gottesman89279f82013-04-05 18:10:41 +00001472 DEBUG(dbgs() << "Deleting release: " << *OrigRelease << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001473 }
Michael Gottesman79249972013-04-05 23:46:45 +00001474
John McCalld935e9c2011-06-15 23:37:01 +00001475}
1476
Michael Gottesman67792172015-03-16 07:02:30 +00001477bool ObjCARCOpt::PairUpRetainsAndReleases(
Michael Gottesman0be69202015-03-05 23:28:58 +00001478 DenseMap<const BasicBlock *, BBState> &BBStates,
1479 BlotMapVector<Value *, RRInfo> &Retains,
1480 DenseMap<Value *, RRInfo> &Releases, Module *M,
Akira Hatanaka2b882052017-02-25 00:53:38 +00001481 Instruction *Retain,
Michael Gottesman0be69202015-03-05 23:28:58 +00001482 SmallVectorImpl<Instruction *> &DeadInsts, RRInfo &RetainsToMove,
1483 RRInfo &ReleasesToMove, Value *Arg, bool KnownSafe,
1484 bool &AnyPairsCompletelyEliminated) {
Michael Gottesman9de6f962013-01-22 21:49:00 +00001485 // If a pair happens in a region where it is known that the reference count
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001486 // is already incremented, we can similarly ignore possible decrements unless
1487 // we are dealing with a retainable object with multiple provenance sources.
Michael Gottesman9de6f962013-01-22 21:49:00 +00001488 bool KnownSafeTD = true, KnownSafeBU = true;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001489 bool CFGHazardAfflicted = false;
Michael Gottesman9de6f962013-01-22 21:49:00 +00001490
1491 // Connect the dots between the top-down-collected RetainsToMove and
1492 // bottom-up-collected ReleasesToMove to form sets of related calls.
1493 // This is an iterative process so that we connect multiple releases
1494 // to multiple retains if needed.
1495 unsigned OldDelta = 0;
1496 unsigned NewDelta = 0;
1497 unsigned OldCount = 0;
1498 unsigned NewCount = 0;
1499 bool FirstRelease = true;
Akira Hatanaka2b882052017-02-25 00:53:38 +00001500 for (SmallVector<Instruction *, 4> NewRetains{Retain};;) {
1501 SmallVector<Instruction *, 4> NewReleases;
Benjamin Kramer135f7352016-06-26 12:28:59 +00001502 for (Instruction *NewRetain : NewRetains) {
Michael Gottesman6ff10c92015-03-06 02:10:03 +00001503 auto It = Retains.find(NewRetain);
Michael Gottesman9de6f962013-01-22 21:49:00 +00001504 assert(It != Retains.end());
1505 const RRInfo &NewRetainRRI = It->second;
1506 KnownSafeTD &= NewRetainRRI.KnownSafe;
Craig Topper46276792014-08-24 23:23:06 +00001507 for (Instruction *NewRetainRelease : NewRetainRRI.Calls) {
Michael Gottesman6ff10c92015-03-06 02:10:03 +00001508 auto Jt = Releases.find(NewRetainRelease);
Michael Gottesman9de6f962013-01-22 21:49:00 +00001509 if (Jt == Releases.end())
1510 return false;
1511 const RRInfo &NewRetainReleaseRRI = Jt->second;
Michael Gottesman24b2f6f2013-11-05 16:02:40 +00001512
1513 // If the release does not have a reference to the retain as well,
1514 // something happened which is unaccounted for. Do not do anything.
1515 //
1516 // This can happen if we catch an additive overflow during path count
1517 // merging.
1518 if (!NewRetainReleaseRRI.Calls.count(NewRetain))
1519 return false;
1520
David Blaikie70573dc2014-11-19 07:49:26 +00001521 if (ReleasesToMove.Calls.insert(NewRetainRelease).second) {
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001522
1523 // If we overflow when we compute the path count, don't remove/move
1524 // anything.
1525 const BBState &NRRBBState = BBStates[NewRetainRelease->getParent()];
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00001526 unsigned PathCount = BBState::OverflowOccurredValue;
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001527 if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
1528 return false;
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00001529 assert(PathCount != BBState::OverflowOccurredValue &&
1530 "PathCount at this point can not be "
1531 "OverflowOccurredValue.");
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001532 OldDelta -= PathCount;
Michael Gottesman9de6f962013-01-22 21:49:00 +00001533
1534 // Merge the ReleaseMetadata and IsTailCallRelease values.
1535 if (FirstRelease) {
1536 ReleasesToMove.ReleaseMetadata =
1537 NewRetainReleaseRRI.ReleaseMetadata;
1538 ReleasesToMove.IsTailCallRelease =
1539 NewRetainReleaseRRI.IsTailCallRelease;
1540 FirstRelease = false;
1541 } else {
1542 if (ReleasesToMove.ReleaseMetadata !=
1543 NewRetainReleaseRRI.ReleaseMetadata)
Craig Topperf40110f2014-04-25 05:29:35 +00001544 ReleasesToMove.ReleaseMetadata = nullptr;
Michael Gottesman9de6f962013-01-22 21:49:00 +00001545 if (ReleasesToMove.IsTailCallRelease !=
1546 NewRetainReleaseRRI.IsTailCallRelease)
1547 ReleasesToMove.IsTailCallRelease = false;
1548 }
1549
1550 // Collect the optimal insertion points.
1551 if (!KnownSafe)
Craig Topper46276792014-08-24 23:23:06 +00001552 for (Instruction *RIP : NewRetainReleaseRRI.ReverseInsertPts) {
David Blaikie70573dc2014-11-19 07:49:26 +00001553 if (ReleasesToMove.ReverseInsertPts.insert(RIP).second) {
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001554 // If we overflow when we compute the path count, don't
1555 // remove/move anything.
1556 const BBState &RIPBBState = BBStates[RIP->getParent()];
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00001557 PathCount = BBState::OverflowOccurredValue;
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001558 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
1559 return false;
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00001560 assert(PathCount != BBState::OverflowOccurredValue &&
1561 "PathCount at this point can not be "
1562 "OverflowOccurredValue.");
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001563 NewDelta -= PathCount;
1564 }
Michael Gottesman9de6f962013-01-22 21:49:00 +00001565 }
1566 NewReleases.push_back(NewRetainRelease);
1567 }
1568 }
1569 }
1570 NewRetains.clear();
1571 if (NewReleases.empty()) break;
1572
1573 // Back the other way.
Benjamin Kramer135f7352016-06-26 12:28:59 +00001574 for (Instruction *NewRelease : NewReleases) {
Michael Gottesman6ff10c92015-03-06 02:10:03 +00001575 auto It = Releases.find(NewRelease);
Michael Gottesman9de6f962013-01-22 21:49:00 +00001576 assert(It != Releases.end());
1577 const RRInfo &NewReleaseRRI = It->second;
1578 KnownSafeBU &= NewReleaseRRI.KnownSafe;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001579 CFGHazardAfflicted |= NewReleaseRRI.CFGHazardAfflicted;
Craig Topper46276792014-08-24 23:23:06 +00001580 for (Instruction *NewReleaseRetain : NewReleaseRRI.Calls) {
Michael Gottesman6ff10c92015-03-06 02:10:03 +00001581 auto Jt = Retains.find(NewReleaseRetain);
Michael Gottesman9de6f962013-01-22 21:49:00 +00001582 if (Jt == Retains.end())
1583 return false;
1584 const RRInfo &NewReleaseRetainRRI = Jt->second;
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001585
Michael Gottesman24b2f6f2013-11-05 16:02:40 +00001586 // If the retain does not have a reference to the release as well,
1587 // something happened which is unaccounted for. Do not do anything.
1588 //
1589 // This can happen if we catch an additive overflow during path count
1590 // merging.
1591 if (!NewReleaseRetainRRI.Calls.count(NewRelease))
1592 return false;
1593
David Blaikie70573dc2014-11-19 07:49:26 +00001594 if (RetainsToMove.Calls.insert(NewReleaseRetain).second) {
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001595 // If we overflow when we compute the path count, don't remove/move
1596 // anything.
1597 const BBState &NRRBBState = BBStates[NewReleaseRetain->getParent()];
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00001598 unsigned PathCount = BBState::OverflowOccurredValue;
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001599 if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
1600 return false;
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00001601 assert(PathCount != BBState::OverflowOccurredValue &&
1602 "PathCount at this point can not be "
1603 "OverflowOccurredValue.");
Michael Gottesman9de6f962013-01-22 21:49:00 +00001604 OldDelta += PathCount;
1605 OldCount += PathCount;
1606
Michael Gottesman9de6f962013-01-22 21:49:00 +00001607 // Collect the optimal insertion points.
1608 if (!KnownSafe)
Craig Topper46276792014-08-24 23:23:06 +00001609 for (Instruction *RIP : NewReleaseRetainRRI.ReverseInsertPts) {
David Blaikie70573dc2014-11-19 07:49:26 +00001610 if (RetainsToMove.ReverseInsertPts.insert(RIP).second) {
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001611 // If we overflow when we compute the path count, don't
1612 // remove/move anything.
1613 const BBState &RIPBBState = BBStates[RIP->getParent()];
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00001614
1615 PathCount = BBState::OverflowOccurredValue;
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001616 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
1617 return false;
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00001618 assert(PathCount != BBState::OverflowOccurredValue &&
1619 "PathCount at this point can not be "
1620 "OverflowOccurredValue.");
Michael Gottesman9de6f962013-01-22 21:49:00 +00001621 NewDelta += PathCount;
1622 NewCount += PathCount;
1623 }
1624 }
1625 NewRetains.push_back(NewReleaseRetain);
1626 }
1627 }
1628 }
Michael Gottesman9de6f962013-01-22 21:49:00 +00001629 if (NewRetains.empty()) break;
1630 }
1631
Michael Gottesmandd60f9b2015-03-16 07:02:36 +00001632 // We can only remove pointers if we are known safe in both directions.
1633 bool UnconditionallySafe = KnownSafeTD && KnownSafeBU;
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001634 if (UnconditionallySafe) {
Michael Gottesman9de6f962013-01-22 21:49:00 +00001635 RetainsToMove.ReverseInsertPts.clear();
1636 ReleasesToMove.ReverseInsertPts.clear();
1637 NewCount = 0;
1638 } else {
1639 // Determine whether the new insertion points we computed preserve the
1640 // balance of retain and release calls through the program.
1641 // TODO: If the fully aggressive solution isn't valid, try to find a
1642 // less aggressive solution which is.
1643 if (NewDelta != 0)
1644 return false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001645
1646 // At this point, we are not going to remove any RR pairs, but we still are
1647 // able to move RR pairs. If one of our pointers is afflicted with
1648 // CFGHazards, we cannot perform such code motion so exit early.
1649 const bool WillPerformCodeMotion = RetainsToMove.ReverseInsertPts.size() ||
1650 ReleasesToMove.ReverseInsertPts.size();
1651 if (CFGHazardAfflicted && WillPerformCodeMotion)
1652 return false;
Michael Gottesman9de6f962013-01-22 21:49:00 +00001653 }
1654
1655 // Determine whether the original call points are balanced in the retain and
1656 // release calls through the program. If not, conservatively don't touch
1657 // them.
1658 // TODO: It's theoretically possible to do code motion in this case, as
1659 // long as the existing imbalances are maintained.
1660 if (OldDelta != 0)
1661 return false;
Michael Gottesman8005ad32013-04-29 06:16:55 +00001662
Michael Gottesman9de6f962013-01-22 21:49:00 +00001663 Changed = true;
1664 assert(OldCount != 0 && "Unreachable code?");
1665 NumRRs += OldCount - NewCount;
Michael Gottesman9de6f962013-01-22 21:49:00 +00001666 // Set to true if we completely removed any RR pairs.
Michael Gottesman8b5515f2013-01-22 21:53:43 +00001667 AnyPairsCompletelyEliminated = NewCount == 0;
Michael Gottesman9de6f962013-01-22 21:49:00 +00001668
1669 // We can move calls!
1670 return true;
1671}
1672
Michael Gottesman97e3df02013-01-14 00:35:14 +00001673/// Identify pairings between the retains and releases, and delete and/or move
1674/// them.
Michael Gottesman0be69202015-03-05 23:28:58 +00001675bool ObjCARCOpt::PerformCodePlacement(
1676 DenseMap<const BasicBlock *, BBState> &BBStates,
1677 BlotMapVector<Value *, RRInfo> &Retains,
1678 DenseMap<Value *, RRInfo> &Releases, Module *M) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001679 DEBUG(dbgs() << "\n== ObjCARCOpt::PerformCodePlacement ==\n");
1680
John McCalld935e9c2011-06-15 23:37:01 +00001681 bool AnyPairsCompletelyEliminated = false;
John McCalld935e9c2011-06-15 23:37:01 +00001682 SmallVector<Instruction *, 8> DeadInsts;
1683
Dan Gohman670f9372012-04-13 18:57:48 +00001684 // Visit each retain.
Michael Gottesman0be69202015-03-05 23:28:58 +00001685 for (BlotMapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
1686 E = Retains.end();
1687 I != E; ++I) {
Dan Gohman2053a5d2011-09-29 22:25:23 +00001688 Value *V = I->first;
John McCalld935e9c2011-06-15 23:37:01 +00001689 if (!V) continue; // blotted
1690
1691 Instruction *Retain = cast<Instruction>(V);
Michael Gottesmanc189a392013-01-09 19:23:24 +00001692
Michael Gottesman89279f82013-04-05 18:10:41 +00001693 DEBUG(dbgs() << "Visiting: " << *Retain << "\n");
Michael Gottesmanc189a392013-01-09 19:23:24 +00001694
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001695 Value *Arg = GetArgRCIdentityRoot(Retain);
John McCalld935e9c2011-06-15 23:37:01 +00001696
Dan Gohman728db492012-01-13 00:39:07 +00001697 // If the object being released is in static or stack storage, we know it's
John McCalld935e9c2011-06-15 23:37:01 +00001698 // not being managed by ObjC reference counting, so we can delete pairs
1699 // regardless of what possible decrements or uses lie between them.
Dan Gohman728db492012-01-13 00:39:07 +00001700 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
Dan Gohman41375a32012-05-08 23:39:44 +00001701
Dan Gohman56e1cef2011-08-22 17:29:11 +00001702 // A constant pointer can't be pointing to an object on the heap. It may
1703 // be reference-counted, but it won't be deleted.
1704 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
1705 if (const GlobalVariable *GV =
1706 dyn_cast<GlobalVariable>(
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001707 GetRCIdentityRoot(LI->getPointerOperand())))
Dan Gohman56e1cef2011-08-22 17:29:11 +00001708 if (GV->isConstant())
1709 KnownSafe = true;
1710
John McCalld935e9c2011-06-15 23:37:01 +00001711 // Connect the dots between the top-down-collected RetainsToMove and
1712 // bottom-up-collected ReleasesToMove to form sets of related calls.
Akira Hatanaka2b882052017-02-25 00:53:38 +00001713 RRInfo RetainsToMove, ReleasesToMove;
1714
Michael Gottesman67792172015-03-16 07:02:30 +00001715 bool PerformMoveCalls = PairUpRetainsAndReleases(
Akira Hatanaka2b882052017-02-25 00:53:38 +00001716 BBStates, Retains, Releases, M, Retain, DeadInsts,
Michael Gottesman67792172015-03-16 07:02:30 +00001717 RetainsToMove, ReleasesToMove, Arg, KnownSafe,
1718 AnyPairsCompletelyEliminated);
John McCalld935e9c2011-06-15 23:37:01 +00001719
Michael Gottesman9de6f962013-01-22 21:49:00 +00001720 if (PerformMoveCalls) {
1721 // Ok, everything checks out and we're all set. Let's move/delete some
1722 // code!
1723 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
1724 Retains, Releases, DeadInsts, M);
John McCalld935e9c2011-06-15 23:37:01 +00001725 }
John McCalld935e9c2011-06-15 23:37:01 +00001726 }
1727
1728 // Now that we're done moving everything, we can delete the newly dead
1729 // instructions, as we no longer need them as insert points.
1730 while (!DeadInsts.empty())
1731 EraseInstruction(DeadInsts.pop_back_val());
1732
1733 return AnyPairsCompletelyEliminated;
1734}
1735
Michael Gottesman97e3df02013-01-14 00:35:14 +00001736/// Weak pointer optimizations.
John McCalld935e9c2011-06-15 23:37:01 +00001737void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
Michael Gottesman89279f82013-04-05 18:10:41 +00001738 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeWeakCalls ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00001739
John McCalld935e9c2011-06-15 23:37:01 +00001740 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
1741 // itself because it uses AliasAnalysis and we need to do provenance
1742 // queries instead.
1743 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
1744 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +00001745
Michael Gottesman89279f82013-04-05 18:10:41 +00001746 DEBUG(dbgs() << "Visiting: " << *Inst << "\n");
Michael Gottesman3f146e22013-01-01 16:05:48 +00001747
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001748 ARCInstKind Class = GetBasicARCInstKind(Inst);
1749 if (Class != ARCInstKind::LoadWeak &&
1750 Class != ARCInstKind::LoadWeakRetained)
John McCalld935e9c2011-06-15 23:37:01 +00001751 continue;
1752
1753 // Delete objc_loadWeak calls with no users.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001754 if (Class == ARCInstKind::LoadWeak && Inst->use_empty()) {
John McCalld935e9c2011-06-15 23:37:01 +00001755 Inst->eraseFromParent();
1756 continue;
1757 }
1758
1759 // TODO: For now, just look for an earlier available version of this value
1760 // within the same block. Theoretically, we could do memdep-style non-local
1761 // analysis too, but that would want caching. A better approach would be to
1762 // use the technique that EarlyCSE uses.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001763 inst_iterator Current = std::prev(I);
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +00001764 BasicBlock *CurrentBB = &*Current.getBasicBlockIterator();
John McCalld935e9c2011-06-15 23:37:01 +00001765 for (BasicBlock::iterator B = CurrentBB->begin(),
1766 J = Current.getInstructionIterator();
1767 J != B; --J) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001768 Instruction *EarlierInst = &*std::prev(J);
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001769 ARCInstKind EarlierClass = GetARCInstKind(EarlierInst);
John McCalld935e9c2011-06-15 23:37:01 +00001770 switch (EarlierClass) {
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001771 case ARCInstKind::LoadWeak:
1772 case ARCInstKind::LoadWeakRetained: {
John McCalld935e9c2011-06-15 23:37:01 +00001773 // If this is loading from the same pointer, replace this load's value
1774 // with that one.
1775 CallInst *Call = cast<CallInst>(Inst);
1776 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
1777 Value *Arg = Call->getArgOperand(0);
1778 Value *EarlierArg = EarlierCall->getArgOperand(0);
1779 switch (PA.getAA()->alias(Arg, EarlierArg)) {
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001780 case MustAlias:
John McCalld935e9c2011-06-15 23:37:01 +00001781 Changed = true;
1782 // If the load has a builtin retain, insert a plain retain for it.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001783 if (Class == ARCInstKind::LoadWeakRetained) {
Michael Gottesmanca3a4722015-03-16 07:02:24 +00001784 Constant *Decl = EP.get(ARCRuntimeEntryPointKind::Retain);
Michael Gottesman14acfac2013-07-06 01:39:23 +00001785 CallInst *CI = CallInst::Create(Decl, EarlierCall, "", Call);
John McCalld935e9c2011-06-15 23:37:01 +00001786 CI->setTailCall();
1787 }
1788 // Zap the fully redundant load.
1789 Call->replaceAllUsesWith(EarlierCall);
1790 Call->eraseFromParent();
1791 goto clobbered;
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001792 case MayAlias:
1793 case PartialAlias:
John McCalld935e9c2011-06-15 23:37:01 +00001794 goto clobbered;
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001795 case NoAlias:
John McCalld935e9c2011-06-15 23:37:01 +00001796 break;
1797 }
1798 break;
1799 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001800 case ARCInstKind::StoreWeak:
1801 case ARCInstKind::InitWeak: {
John McCalld935e9c2011-06-15 23:37:01 +00001802 // If this is storing to the same pointer and has the same size etc.
1803 // replace this load's value with the stored value.
1804 CallInst *Call = cast<CallInst>(Inst);
1805 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
1806 Value *Arg = Call->getArgOperand(0);
1807 Value *EarlierArg = EarlierCall->getArgOperand(0);
1808 switch (PA.getAA()->alias(Arg, EarlierArg)) {
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001809 case MustAlias:
John McCalld935e9c2011-06-15 23:37:01 +00001810 Changed = true;
1811 // If the load has a builtin retain, insert a plain retain for it.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001812 if (Class == ARCInstKind::LoadWeakRetained) {
Michael Gottesmanca3a4722015-03-16 07:02:24 +00001813 Constant *Decl = EP.get(ARCRuntimeEntryPointKind::Retain);
Michael Gottesman14acfac2013-07-06 01:39:23 +00001814 CallInst *CI = CallInst::Create(Decl, EarlierCall, "", Call);
John McCalld935e9c2011-06-15 23:37:01 +00001815 CI->setTailCall();
1816 }
1817 // Zap the fully redundant load.
1818 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
1819 Call->eraseFromParent();
1820 goto clobbered;
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001821 case MayAlias:
1822 case PartialAlias:
John McCalld935e9c2011-06-15 23:37:01 +00001823 goto clobbered;
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001824 case NoAlias:
John McCalld935e9c2011-06-15 23:37:01 +00001825 break;
1826 }
1827 break;
1828 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001829 case ARCInstKind::MoveWeak:
1830 case ARCInstKind::CopyWeak:
John McCalld935e9c2011-06-15 23:37:01 +00001831 // TOOD: Grab the copied value.
1832 goto clobbered;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001833 case ARCInstKind::AutoreleasepoolPush:
1834 case ARCInstKind::None:
1835 case ARCInstKind::IntrinsicUser:
1836 case ARCInstKind::User:
John McCalld935e9c2011-06-15 23:37:01 +00001837 // Weak pointers are only modified through the weak entry points
1838 // (and arbitrary calls, which could call the weak entry points).
1839 break;
1840 default:
1841 // Anything else could modify the weak pointer.
1842 goto clobbered;
1843 }
1844 }
1845 clobbered:;
1846 }
1847
1848 // Then, for each destroyWeak with an alloca operand, check to see if
1849 // the alloca and all its users can be zapped.
1850 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
1851 Instruction *Inst = &*I++;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001852 ARCInstKind Class = GetBasicARCInstKind(Inst);
1853 if (Class != ARCInstKind::DestroyWeak)
John McCalld935e9c2011-06-15 23:37:01 +00001854 continue;
1855
1856 CallInst *Call = cast<CallInst>(Inst);
1857 Value *Arg = Call->getArgOperand(0);
1858 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001859 for (User *U : Alloca->users()) {
1860 const Instruction *UserInst = cast<Instruction>(U);
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001861 switch (GetBasicARCInstKind(UserInst)) {
1862 case ARCInstKind::InitWeak:
1863 case ARCInstKind::StoreWeak:
1864 case ARCInstKind::DestroyWeak:
John McCalld935e9c2011-06-15 23:37:01 +00001865 continue;
1866 default:
1867 goto done;
1868 }
1869 }
1870 Changed = true;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001871 for (auto UI = Alloca->user_begin(), UE = Alloca->user_end(); UI != UE;) {
John McCalld935e9c2011-06-15 23:37:01 +00001872 CallInst *UserInst = cast<CallInst>(*UI++);
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001873 switch (GetBasicARCInstKind(UserInst)) {
1874 case ARCInstKind::InitWeak:
1875 case ARCInstKind::StoreWeak:
Dan Gohman14862c32012-05-18 22:17:29 +00001876 // These functions return their second argument.
1877 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
1878 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001879 case ARCInstKind::DestroyWeak:
Dan Gohman14862c32012-05-18 22:17:29 +00001880 // No return value.
1881 break;
1882 default:
Dan Gohman9c97eea02012-05-21 17:41:28 +00001883 llvm_unreachable("alloca really is used!");
Dan Gohman14862c32012-05-18 22:17:29 +00001884 }
John McCalld935e9c2011-06-15 23:37:01 +00001885 UserInst->eraseFromParent();
1886 }
1887 Alloca->eraseFromParent();
1888 done:;
1889 }
1890 }
1891}
1892
Michael Gottesman97e3df02013-01-14 00:35:14 +00001893/// Identify program paths which execute sequences of retains and releases which
1894/// can be eliminated.
John McCalld935e9c2011-06-15 23:37:01 +00001895bool ObjCARCOpt::OptimizeSequences(Function &F) {
Michael Gottesman740db972013-05-23 02:35:21 +00001896 // Releases, Retains - These are used to store the results of the main flow
1897 // analysis. These use Value* as the key instead of Instruction* so that the
1898 // map stays valid when we get around to rewriting code and calls get
1899 // replaced by arguments.
John McCalld935e9c2011-06-15 23:37:01 +00001900 DenseMap<Value *, RRInfo> Releases;
Michael Gottesman0be69202015-03-05 23:28:58 +00001901 BlotMapVector<Value *, RRInfo> Retains;
John McCalld935e9c2011-06-15 23:37:01 +00001902
Michael Gottesman740db972013-05-23 02:35:21 +00001903 // This is used during the traversal of the function to track the
1904 // states for each identified object at each block.
John McCalld935e9c2011-06-15 23:37:01 +00001905 DenseMap<const BasicBlock *, BBState> BBStates;
1906
1907 // Analyze the CFG of the function, and all instructions.
1908 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
1909
1910 // Transform.
Michael Gottesman5a91bbf2013-05-24 20:44:02 +00001911 bool AnyPairsCompletelyEliminated = PerformCodePlacement(BBStates, Retains,
1912 Releases,
1913 F.getParent());
1914
Michael Gottesman5a91bbf2013-05-24 20:44:02 +00001915 return AnyPairsCompletelyEliminated && NestingDetected;
John McCalld935e9c2011-06-15 23:37:01 +00001916}
1917
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00001918/// Check if there is a dependent call earlier that does not have anything in
1919/// between the Retain and the call that can affect the reference count of their
1920/// shared pointer argument. Note that Retain need not be in BB.
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00001921static bool
1922HasSafePathToPredecessorCall(const Value *Arg, Instruction *Retain,
Craig Topper71b7b682014-08-21 05:55:13 +00001923 SmallPtrSetImpl<Instruction *> &DepInsts,
1924 SmallPtrSetImpl<const BasicBlock *> &Visited,
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00001925 ProvenanceAnalysis &PA) {
1926 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
1927 DepInsts, Visited, PA);
1928 if (DepInsts.size() != 1)
1929 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00001930
Michael Gottesmana9fc0162015-03-05 23:29:06 +00001931 auto *Call = dyn_cast_or_null<CallInst>(*DepInsts.begin());
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00001932
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00001933 // Check that the pointer is the return value of the call.
1934 if (!Call || Arg != Call)
1935 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00001936
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00001937 // Check that the call is a regular call.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001938 ARCInstKind Class = GetBasicARCInstKind(Call);
Alexander Kornienkod0af3b32015-12-28 16:19:08 +00001939 return Class == ARCInstKind::CallOrUser || Class == ARCInstKind::Call;
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00001940}
1941
Michael Gottesman6908db12013-04-03 23:16:05 +00001942/// Find a dependent retain that precedes the given autorelease for which there
1943/// is nothing in between the two instructions that can affect the ref count of
1944/// Arg.
1945static CallInst *
1946FindPredecessorRetainWithSafePath(const Value *Arg, BasicBlock *BB,
1947 Instruction *Autorelease,
Craig Topper71b7b682014-08-21 05:55:13 +00001948 SmallPtrSetImpl<Instruction *> &DepInsts,
1949 SmallPtrSetImpl<const BasicBlock *> &Visited,
Michael Gottesman6908db12013-04-03 23:16:05 +00001950 ProvenanceAnalysis &PA) {
1951 FindDependencies(CanChangeRetainCount, Arg,
1952 BB, Autorelease, DepInsts, Visited, PA);
1953 if (DepInsts.size() != 1)
Craig Topperf40110f2014-04-25 05:29:35 +00001954 return nullptr;
Michael Gottesman79249972013-04-05 23:46:45 +00001955
Michael Gottesmana9fc0162015-03-05 23:29:06 +00001956 auto *Retain = dyn_cast_or_null<CallInst>(*DepInsts.begin());
Michael Gottesman79249972013-04-05 23:46:45 +00001957
Michael Gottesman6908db12013-04-03 23:16:05 +00001958 // Check that we found a retain with the same argument.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001959 if (!Retain || !IsRetain(GetBasicARCInstKind(Retain)) ||
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001960 GetArgRCIdentityRoot(Retain) != Arg) {
Craig Topperf40110f2014-04-25 05:29:35 +00001961 return nullptr;
Michael Gottesman6908db12013-04-03 23:16:05 +00001962 }
Michael Gottesman79249972013-04-05 23:46:45 +00001963
Michael Gottesman6908db12013-04-03 23:16:05 +00001964 return Retain;
1965}
1966
Michael Gottesman21a4ed32013-04-03 23:39:14 +00001967/// Look for an ``autorelease'' instruction dependent on Arg such that there are
1968/// no instructions dependent on Arg that need a positive ref count in between
1969/// the autorelease and the ret.
1970static CallInst *
1971FindPredecessorAutoreleaseWithSafePath(const Value *Arg, BasicBlock *BB,
1972 ReturnInst *Ret,
Craig Topper71b7b682014-08-21 05:55:13 +00001973 SmallPtrSetImpl<Instruction *> &DepInsts,
1974 SmallPtrSetImpl<const BasicBlock *> &V,
Michael Gottesman21a4ed32013-04-03 23:39:14 +00001975 ProvenanceAnalysis &PA) {
1976 FindDependencies(NeedsPositiveRetainCount, Arg,
1977 BB, Ret, DepInsts, V, PA);
1978 if (DepInsts.size() != 1)
Craig Topperf40110f2014-04-25 05:29:35 +00001979 return nullptr;
Michael Gottesman79249972013-04-05 23:46:45 +00001980
Michael Gottesmana9fc0162015-03-05 23:29:06 +00001981 auto *Autorelease = dyn_cast_or_null<CallInst>(*DepInsts.begin());
Michael Gottesman21a4ed32013-04-03 23:39:14 +00001982 if (!Autorelease)
Craig Topperf40110f2014-04-25 05:29:35 +00001983 return nullptr;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001984 ARCInstKind AutoreleaseClass = GetBasicARCInstKind(Autorelease);
Michael Gottesman21a4ed32013-04-03 23:39:14 +00001985 if (!IsAutorelease(AutoreleaseClass))
Craig Topperf40110f2014-04-25 05:29:35 +00001986 return nullptr;
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001987 if (GetArgRCIdentityRoot(Autorelease) != Arg)
Craig Topperf40110f2014-04-25 05:29:35 +00001988 return nullptr;
Michael Gottesman79249972013-04-05 23:46:45 +00001989
Michael Gottesman21a4ed32013-04-03 23:39:14 +00001990 return Autorelease;
1991}
1992
Michael Gottesman97e3df02013-01-14 00:35:14 +00001993/// Look for this pattern:
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00001994/// \code
John McCalld935e9c2011-06-15 23:37:01 +00001995/// %call = call i8* @something(...)
1996/// %2 = call i8* @objc_retain(i8* %call)
1997/// %3 = call i8* @objc_autorelease(i8* %2)
1998/// ret i8* %3
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00001999/// \endcode
John McCalld935e9c2011-06-15 23:37:01 +00002000/// And delete the retain and autorelease.
John McCalld935e9c2011-06-15 23:37:01 +00002001void ObjCARCOpt::OptimizeReturns(Function &F) {
2002 if (!F.getReturnType()->isPointerTy())
2003 return;
Michael Gottesman79249972013-04-05 23:46:45 +00002004
Michael Gottesman89279f82013-04-05 18:10:41 +00002005 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeReturns ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00002006
John McCalld935e9c2011-06-15 23:37:01 +00002007 SmallPtrSet<Instruction *, 4> DependingInstructions;
2008 SmallPtrSet<const BasicBlock *, 4> Visited;
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +00002009 for (BasicBlock &BB: F) {
2010 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB.back());
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002011 if (!Ret)
2012 continue;
Michael Gottesman79249972013-04-05 23:46:45 +00002013
Chandler Carruthd9ef4b62016-11-04 06:59:50 +00002014 DEBUG(dbgs() << "Visiting: " << *Ret << "\n");
2015
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00002016 const Value *Arg = GetRCIdentityRoot(Ret->getOperand(0));
Michael Gottesman79249972013-04-05 23:46:45 +00002017
Michael Gottesmancdb7c152013-04-21 00:25:04 +00002018 // Look for an ``autorelease'' instruction that is a predecessor of Ret and
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002019 // dependent on Arg such that there are no instructions dependent on Arg
2020 // that need a positive ref count in between the autorelease and Ret.
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +00002021 CallInst *Autorelease = FindPredecessorAutoreleaseWithSafePath(
2022 Arg, &BB, Ret, DependingInstructions, Visited, PA);
John McCalld935e9c2011-06-15 23:37:01 +00002023 DependingInstructions.clear();
2024 Visited.clear();
Michael Gottesmanfb9ece92013-04-21 00:25:01 +00002025
2026 if (!Autorelease)
2027 continue;
2028
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +00002029 CallInst *Retain = FindPredecessorRetainWithSafePath(
2030 Arg, &BB, Autorelease, DependingInstructions, Visited, PA);
Michael Gottesmanfb9ece92013-04-21 00:25:01 +00002031 DependingInstructions.clear();
2032 Visited.clear();
2033
2034 if (!Retain)
2035 continue;
2036
2037 // Check that there is nothing that can affect the reference count
2038 // between the retain and the call. Note that Retain need not be in BB.
2039 bool HasSafePathToCall = HasSafePathToPredecessorCall(Arg, Retain,
2040 DependingInstructions,
2041 Visited, PA);
2042 DependingInstructions.clear();
2043 Visited.clear();
2044
2045 if (!HasSafePathToCall)
2046 continue;
2047
2048 // If so, we can zap the retain and autorelease.
2049 Changed = true;
2050 ++NumRets;
2051 DEBUG(dbgs() << "Erasing: " << *Retain << "\nErasing: "
2052 << *Autorelease << "\n");
2053 EraseInstruction(Retain);
2054 EraseInstruction(Autorelease);
John McCalld935e9c2011-06-15 23:37:01 +00002055 }
2056}
2057
Michael Gottesman9c118152013-04-29 06:16:57 +00002058#ifndef NDEBUG
2059void
2060ObjCARCOpt::GatherStatistics(Function &F, bool AfterOptimization) {
2061 llvm::Statistic &NumRetains =
2062 AfterOptimization? NumRetainsAfterOpt : NumRetainsBeforeOpt;
2063 llvm::Statistic &NumReleases =
2064 AfterOptimization? NumReleasesAfterOpt : NumReleasesBeforeOpt;
2065
2066 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2067 Instruction *Inst = &*I++;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002068 switch (GetBasicARCInstKind(Inst)) {
Michael Gottesman9c118152013-04-29 06:16:57 +00002069 default:
2070 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002071 case ARCInstKind::Retain:
Michael Gottesman9c118152013-04-29 06:16:57 +00002072 ++NumRetains;
2073 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002074 case ARCInstKind::Release:
Michael Gottesman9c118152013-04-29 06:16:57 +00002075 ++NumReleases;
2076 break;
2077 }
2078 }
2079}
2080#endif
2081
John McCalld935e9c2011-06-15 23:37:01 +00002082bool ObjCARCOpt::doInitialization(Module &M) {
2083 if (!EnableARCOpts)
2084 return false;
2085
Dan Gohman670f9372012-04-13 18:57:48 +00002086 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanceaac7c2011-06-20 23:20:43 +00002087 Run = ModuleHasARC(M);
2088 if (!Run)
2089 return false;
2090
John McCalld935e9c2011-06-15 23:37:01 +00002091 // Intuitively, objc_retain and others are nocapture, however in practice
2092 // they are not, because they return their argument value. And objc_release
Dan Gohmandae33492012-04-27 18:56:31 +00002093 // calls finalizers which can have arbitrary side effects.
Michael Gottesman65cb7372015-03-16 07:02:27 +00002094 MDKindCache.init(&M);
John McCalld935e9c2011-06-15 23:37:01 +00002095
Michael Gottesman14acfac2013-07-06 01:39:23 +00002096 // Initialize our runtime entry point cache.
Michael Gottesman65cb7372015-03-16 07:02:27 +00002097 EP.init(&M);
John McCalld935e9c2011-06-15 23:37:01 +00002098
2099 return false;
2100}
2101
2102bool ObjCARCOpt::runOnFunction(Function &F) {
2103 if (!EnableARCOpts)
2104 return false;
2105
Dan Gohmanceaac7c2011-06-20 23:20:43 +00002106 // If nothing in the Module uses ARC, don't do anything.
2107 if (!Run)
2108 return false;
2109
John McCalld935e9c2011-06-15 23:37:01 +00002110 Changed = false;
2111
Michael Gottesman89279f82013-04-05 18:10:41 +00002112 DEBUG(dbgs() << "<<< ObjCARCOpt: Visiting Function: " << F.getName() << " >>>"
2113 "\n");
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00002114
Chandler Carruth7b560d42015-09-09 17:55:00 +00002115 PA.setAA(&getAnalysis<AAResultsWrapperPass>().getAAResults());
John McCalld935e9c2011-06-15 23:37:01 +00002116
Michael Gottesman9fc50b82013-05-13 18:29:07 +00002117#ifndef NDEBUG
2118 if (AreStatisticsEnabled()) {
2119 GatherStatistics(F, false);
2120 }
2121#endif
2122
John McCalld935e9c2011-06-15 23:37:01 +00002123 // This pass performs several distinct transformations. As a compile-time aid
2124 // when compiling code that isn't ObjC, skip these if the relevant ObjC
2125 // library functions aren't declared.
2126
Michael Gottesmancd5b0272013-04-24 22:18:15 +00002127 // Preliminary optimizations. This also computes UsedInThisFunction.
John McCalld935e9c2011-06-15 23:37:01 +00002128 OptimizeIndividualCalls(F);
2129
2130 // Optimizations for weak pointers.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002131 if (UsedInThisFunction & ((1 << unsigned(ARCInstKind::LoadWeak)) |
2132 (1 << unsigned(ARCInstKind::LoadWeakRetained)) |
2133 (1 << unsigned(ARCInstKind::StoreWeak)) |
2134 (1 << unsigned(ARCInstKind::InitWeak)) |
2135 (1 << unsigned(ARCInstKind::CopyWeak)) |
2136 (1 << unsigned(ARCInstKind::MoveWeak)) |
2137 (1 << unsigned(ARCInstKind::DestroyWeak))))
John McCalld935e9c2011-06-15 23:37:01 +00002138 OptimizeWeakCalls(F);
2139
2140 // Optimizations for retain+release pairs.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002141 if (UsedInThisFunction & ((1 << unsigned(ARCInstKind::Retain)) |
2142 (1 << unsigned(ARCInstKind::RetainRV)) |
2143 (1 << unsigned(ARCInstKind::RetainBlock))))
2144 if (UsedInThisFunction & (1 << unsigned(ARCInstKind::Release)))
John McCalld935e9c2011-06-15 23:37:01 +00002145 // Run OptimizeSequences until it either stops making changes or
2146 // no retain+release pair nesting is detected.
2147 while (OptimizeSequences(F)) {}
2148
2149 // Optimizations if objc_autorelease is used.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002150 if (UsedInThisFunction & ((1 << unsigned(ARCInstKind::Autorelease)) |
2151 (1 << unsigned(ARCInstKind::AutoreleaseRV))))
John McCalld935e9c2011-06-15 23:37:01 +00002152 OptimizeReturns(F);
2153
Michael Gottesman9c118152013-04-29 06:16:57 +00002154 // Gather statistics after optimization.
2155#ifndef NDEBUG
2156 if (AreStatisticsEnabled()) {
2157 GatherStatistics(F, true);
2158 }
2159#endif
2160
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00002161 DEBUG(dbgs() << "\n");
2162
John McCalld935e9c2011-06-15 23:37:01 +00002163 return Changed;
2164}
2165
2166void ObjCARCOpt::releaseMemory() {
2167 PA.clear();
2168}
2169
Michael Gottesman97e3df02013-01-14 00:35:14 +00002170/// @}
2171///