blob: fa30ee6f72b1c0f0302da3364a072b9014c4f0d5 [file] [log] [blame]
Michael Gottesman79d8d812013-01-28 01:35:51 +00001//===- ObjCARCOpts.cpp - ObjC ARC Optimization ----------------------------===//
John McCalld935e9c2011-06-15 23:37:01 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
John McCalld935e9c2011-06-15 23:37:01 +00006//
7//===----------------------------------------------------------------------===//
Eugene Zelenko57bd5a02017-10-27 01:09:08 +00008//
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.
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000024//
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"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000034#include "llvm/ADT/None.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"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000037#include "llvm/ADT/SmallVector.h"
Michael Gottesman278266f2013-01-29 04:20:52 +000038#include "llvm/ADT/Statistic.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000039#include "llvm/Analysis/AliasAnalysis.h"
Saleem Abdulrasool8b342682018-03-12 21:46:09 +000040#include "llvm/Analysis/EHPersonalities.h"
Chandler Carruth0f792182015-08-20 08:06:03 +000041#include "llvm/Analysis/ObjCARCAliasAnalysis.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000042#include "llvm/Analysis/ObjCARCAnalysisUtils.h"
43#include "llvm/Analysis/ObjCARCInstKind.h"
44#include "llvm/IR/BasicBlock.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000045#include "llvm/IR/CFG.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000046#include "llvm/IR/CallSite.h"
47#include "llvm/IR/Constant.h"
48#include "llvm/IR/Constants.h"
49#include "llvm/IR/DerivedTypes.h"
50#include "llvm/IR/Function.h"
51#include "llvm/IR/GlobalVariable.h"
52#include "llvm/IR/InstIterator.h"
53#include "llvm/IR/InstrTypes.h"
54#include "llvm/IR/Instruction.h"
55#include "llvm/IR/Instructions.h"
Michael Gottesman278266f2013-01-29 04:20:52 +000056#include "llvm/IR/LLVMContext.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000057#include "llvm/IR/Metadata.h"
58#include "llvm/IR/Type.h"
59#include "llvm/IR/User.h"
60#include "llvm/IR/Value.h"
61#include "llvm/Pass.h"
62#include "llvm/Support/Casting.h"
63#include "llvm/Support/Compiler.h"
Michael Gottesman13a5f1a2013-01-29 04:51:59 +000064#include "llvm/Support/Debug.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000065#include "llvm/Support/ErrorHandling.h"
Timur Iskhodzhanov5d7ff002013-01-29 09:09:27 +000066#include "llvm/Support/raw_ostream.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000067#include <cassert>
68#include <iterator>
69#include <utility>
Michael Gottesmanfa0939f2013-01-28 04:12:07 +000070
John McCalld935e9c2011-06-15 23:37:01 +000071using namespace llvm;
Michael Gottesman08904e32013-01-28 03:28:38 +000072using namespace llvm::objcarc;
John McCalld935e9c2011-06-15 23:37:01 +000073
Chandler Carruth964daaa2014-04-22 02:55:47 +000074#define DEBUG_TYPE "objc-arc-opts"
75
Akira Hatanaka8edf8f32019-04-25 19:42:55 +000076static cl::opt<unsigned> MaxPtrStates("arc-opt-max-ptr-states",
77 cl::Hidden,
78 cl::desc("Maximum number of ptr states the optimizer keeps track of"),
79 cl::init(4095));
80
Michael Gottesman97e3df02013-01-14 00:35:14 +000081/// \defgroup ARCUtilities Utility declarations/definitions specific to ARC.
82/// @{
John McCalld935e9c2011-06-15 23:37:01 +000083
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000084/// This is similar to GetRCIdentityRoot but it stops as soon
Michael Gottesman97e3df02013-01-14 00:35:14 +000085/// as it finds a value with multiple uses.
John McCalld935e9c2011-06-15 23:37:01 +000086static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
Duncan P. N. Exon Smith11c06ea2016-09-24 21:01:20 +000087 // ConstantData (like ConstantPointerNull and UndefValue) is used across
88 // modules. It's never a single-use value.
89 if (isa<ConstantData>(Arg))
90 return nullptr;
91
John McCalld935e9c2011-06-15 23:37:01 +000092 if (Arg->hasOneUse()) {
93 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
94 return FindSingleUseIdentifiedObject(BC->getOperand(0));
95 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
96 if (GEP->hasAllZeroIndices())
97 return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
Michael Gottesman6f729fa2015-02-19 19:51:32 +000098 if (IsForwarding(GetBasicARCInstKind(Arg)))
John McCalld935e9c2011-06-15 23:37:01 +000099 return FindSingleUseIdentifiedObject(
100 cast<CallInst>(Arg)->getArgOperand(0));
101 if (!IsObjCIdentifiedObject(Arg))
Craig Topperf40110f2014-04-25 05:29:35 +0000102 return nullptr;
John McCalld935e9c2011-06-15 23:37:01 +0000103 return Arg;
104 }
105
Dan Gohman41375a32012-05-08 23:39:44 +0000106 // If we found an identifiable object but it has multiple uses, but they are
107 // trivial uses, we can still consider this to be a single-use value.
John McCalld935e9c2011-06-15 23:37:01 +0000108 if (IsObjCIdentifiedObject(Arg)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000109 for (const User *U : Arg->users())
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000110 if (!U->use_empty() || GetRCIdentityRoot(U) != Arg)
Craig Topperf40110f2014-04-25 05:29:35 +0000111 return nullptr;
John McCalld935e9c2011-06-15 23:37:01 +0000112
113 return Arg;
114 }
115
Craig Topperf40110f2014-04-25 05:29:35 +0000116 return nullptr;
John McCalld935e9c2011-06-15 23:37:01 +0000117}
118
Michael Gottesman97e3df02013-01-14 00:35:14 +0000119/// @}
120///
Michael Gottesman97e3df02013-01-14 00:35:14 +0000121/// \defgroup ARCOpt ARC Optimization.
122/// @{
John McCalld935e9c2011-06-15 23:37:01 +0000123
124// TODO: On code like this:
125//
126// objc_retain(%x)
127// stuff_that_cannot_release()
128// objc_autorelease(%x)
129// stuff_that_cannot_release()
130// objc_retain(%x)
131// stuff_that_cannot_release()
132// objc_autorelease(%x)
133//
134// The second retain and autorelease can be deleted.
135
136// TODO: It should be possible to delete
137// objc_autoreleasePoolPush and objc_autoreleasePoolPop
138// pairs if nothing is actually autoreleased between them. Also, autorelease
139// calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
140// after inlining) can be turned into plain release calls.
141
142// TODO: Critical-edge splitting. If the optimial insertion point is
143// a critical edge, the current algorithm has to fail, because it doesn't
144// know how to split edges. It should be possible to make the optimizer
145// think in terms of edges, rather than blocks, and then split critical
146// edges on demand.
147
148// TODO: OptimizeSequences could generalized to be Interprocedural.
149
150// TODO: Recognize that a bunch of other objc runtime calls have
151// non-escaping arguments and non-releasing arguments, and may be
152// non-autoreleasing.
153
154// TODO: Sink autorelease calls as far as possible. Unfortunately we
155// usually can't sink them past other calls, which would be the main
156// case where it would be useful.
157
Dan Gohmanb3894012011-08-19 00:26:36 +0000158// TODO: The pointer returned from objc_loadWeakRetained is retained.
159
160// TODO: Delete release+retain pairs (rare).
Dan Gohmanceaac7c2011-06-20 23:20:43 +0000161
John McCalld935e9c2011-06-15 23:37:01 +0000162STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
163STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
164STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
165STATISTIC(NumRets, "Number of return value forwarding "
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000166 "retain+autoreleases eliminated");
John McCalld935e9c2011-06-15 23:37:01 +0000167STATISTIC(NumRRs, "Number of retain+release paths eliminated");
168STATISTIC(NumPeeps, "Number of calls peephole-optimized");
Matt Beaumont-Gaye55d9492013-05-13 21:10:49 +0000169#ifndef NDEBUG
Michael Gottesman9c118152013-04-29 06:16:57 +0000170STATISTIC(NumRetainsBeforeOpt,
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000171 "Number of retains before optimization");
Michael Gottesman9c118152013-04-29 06:16:57 +0000172STATISTIC(NumReleasesBeforeOpt,
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000173 "Number of releases before optimization");
Michael Gottesman9c118152013-04-29 06:16:57 +0000174STATISTIC(NumRetainsAfterOpt,
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000175 "Number of retains after optimization");
Michael Gottesman9c118152013-04-29 06:16:57 +0000176STATISTIC(NumReleasesAfterOpt,
Michael Gottesmanb4e7f4d2013-05-15 17:43:03 +0000177 "Number of releases after optimization");
Michael Gottesman03cf3c82013-04-29 07:29:08 +0000178#endif
John McCalld935e9c2011-06-15 23:37:01 +0000179
180namespace {
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000181
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000182 /// Per-BasicBlock state.
John McCalld935e9c2011-06-15 23:37:01 +0000183 class BBState {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000184 /// The number of unique control paths from the entry which can reach this
185 /// block.
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000186 unsigned TopDownPathCount = 0;
John McCalld935e9c2011-06-15 23:37:01 +0000187
Michael Gottesman97e3df02013-01-14 00:35:14 +0000188 /// The number of unique control paths to exits from this block.
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000189 unsigned BottomUpPathCount = 0;
John McCalld935e9c2011-06-15 23:37:01 +0000190
Michael Gottesman97e3df02013-01-14 00:35:14 +0000191 /// The top-down traversal uses this to record information known about a
192 /// pointer at the bottom of each block.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000193 BlotMapVector<const Value *, TopDownPtrState> PerPtrTopDown;
John McCalld935e9c2011-06-15 23:37:01 +0000194
Michael Gottesman97e3df02013-01-14 00:35:14 +0000195 /// The bottom-up traversal uses this to record information known about a
196 /// pointer at the top of each block.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000197 BlotMapVector<const Value *, BottomUpPtrState> PerPtrBottomUp;
John McCalld935e9c2011-06-15 23:37:01 +0000198
Michael Gottesman97e3df02013-01-14 00:35:14 +0000199 /// Effective predecessors of the current block ignoring ignorable edges and
200 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000201 SmallVector<BasicBlock *, 2> Preds;
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000202
Michael Gottesman97e3df02013-01-14 00:35:14 +0000203 /// Effective successors of the current block ignoring ignorable edges and
204 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000205 SmallVector<BasicBlock *, 2> Succs;
206
John McCalld935e9c2011-06-15 23:37:01 +0000207 public:
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000208 static const unsigned OverflowOccurredValue;
209
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000210 BBState() = default;
John McCalld935e9c2011-06-15 23:37:01 +0000211
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000212 using top_down_ptr_iterator = decltype(PerPtrTopDown)::iterator;
213 using const_top_down_ptr_iterator = decltype(PerPtrTopDown)::const_iterator;
John McCalld935e9c2011-06-15 23:37:01 +0000214
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000215 top_down_ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
216 top_down_ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
217 const_top_down_ptr_iterator top_down_ptr_begin() const {
John McCalld935e9c2011-06-15 23:37:01 +0000218 return PerPtrTopDown.begin();
219 }
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000220 const_top_down_ptr_iterator top_down_ptr_end() const {
John McCalld935e9c2011-06-15 23:37:01 +0000221 return PerPtrTopDown.end();
222 }
Michael Gottesmanc01ab512015-03-16 07:02:39 +0000223 bool hasTopDownPtrs() const {
224 return !PerPtrTopDown.empty();
225 }
John McCalld935e9c2011-06-15 23:37:01 +0000226
Akira Hatanaka8edf8f32019-04-25 19:42:55 +0000227 unsigned top_down_ptr_list_size() const {
228 return std::distance(top_down_ptr_begin(), top_down_ptr_end());
229 }
230
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000231 using bottom_up_ptr_iterator = decltype(PerPtrBottomUp)::iterator;
232 using const_bottom_up_ptr_iterator =
233 decltype(PerPtrBottomUp)::const_iterator;
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000234
235 bottom_up_ptr_iterator bottom_up_ptr_begin() {
John McCalld935e9c2011-06-15 23:37:01 +0000236 return PerPtrBottomUp.begin();
237 }
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000238 bottom_up_ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
239 const_bottom_up_ptr_iterator bottom_up_ptr_begin() const {
240 return PerPtrBottomUp.begin();
241 }
242 const_bottom_up_ptr_iterator bottom_up_ptr_end() const {
John McCalld935e9c2011-06-15 23:37:01 +0000243 return PerPtrBottomUp.end();
244 }
Michael Gottesmanc01ab512015-03-16 07:02:39 +0000245 bool hasBottomUpPtrs() const {
246 return !PerPtrBottomUp.empty();
247 }
John McCalld935e9c2011-06-15 23:37:01 +0000248
Akira Hatanaka8edf8f32019-04-25 19:42:55 +0000249 unsigned bottom_up_ptr_list_size() const {
250 return std::distance(bottom_up_ptr_begin(), bottom_up_ptr_end());
251 }
252
Michael Gottesman97e3df02013-01-14 00:35:14 +0000253 /// Mark this block as being an entry block, which has one path from the
254 /// entry by definition.
John McCalld935e9c2011-06-15 23:37:01 +0000255 void SetAsEntry() { TopDownPathCount = 1; }
256
Michael Gottesman97e3df02013-01-14 00:35:14 +0000257 /// Mark this block as being an exit block, which has one path to an exit by
258 /// definition.
John McCalld935e9c2011-06-15 23:37:01 +0000259 void SetAsExit() { BottomUpPathCount = 1; }
260
Michael Gottesman993fbf72013-05-13 19:40:39 +0000261 /// Attempt to find the PtrState object describing the top down state for
262 /// pointer Arg. Return a new initialized PtrState describing the top down
263 /// state for Arg if we do not find one.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000264 TopDownPtrState &getPtrTopDownState(const Value *Arg) {
John McCalld935e9c2011-06-15 23:37:01 +0000265 return PerPtrTopDown[Arg];
266 }
267
Michael Gottesman993fbf72013-05-13 19:40:39 +0000268 /// Attempt to find the PtrState object describing the bottom up state for
269 /// pointer Arg. Return a new initialized PtrState describing the bottom up
270 /// state for Arg if we do not find one.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000271 BottomUpPtrState &getPtrBottomUpState(const Value *Arg) {
John McCalld935e9c2011-06-15 23:37:01 +0000272 return PerPtrBottomUp[Arg];
273 }
274
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000275 /// Attempt to find the PtrState object describing the bottom up state for
276 /// pointer Arg.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000277 bottom_up_ptr_iterator findPtrBottomUpState(const Value *Arg) {
Michael Gottesmana76143ee2013-05-13 23:49:42 +0000278 return PerPtrBottomUp.find(Arg);
279 }
280
John McCalld935e9c2011-06-15 23:37:01 +0000281 void clearBottomUpPointers() {
Evan Chenge4df6a22011-08-04 18:40:26 +0000282 PerPtrBottomUp.clear();
John McCalld935e9c2011-06-15 23:37:01 +0000283 }
284
285 void clearTopDownPointers() {
286 PerPtrTopDown.clear();
287 }
288
289 void InitFromPred(const BBState &Other);
290 void InitFromSucc(const BBState &Other);
291 void MergePred(const BBState &Other);
292 void MergeSucc(const BBState &Other);
293
Michael Gottesman9e7261c2013-06-07 06:16:49 +0000294 /// Compute the number of possible unique paths from an entry to an exit
Michael Gottesman97e3df02013-01-14 00:35:14 +0000295 /// which pass through this block. This is only valid after both the
296 /// top-down and bottom-up traversals are complete.
Michael Gottesman9e7261c2013-06-07 06:16:49 +0000297 ///
Alp Tokercb402912014-01-24 17:20:08 +0000298 /// Returns true if overflow occurred. Returns false if overflow did not
Michael Gottesman9e7261c2013-06-07 06:16:49 +0000299 /// occur.
300 bool GetAllPathCountWithOverflow(unsigned &PathCount) const {
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000301 if (TopDownPathCount == OverflowOccurredValue ||
302 BottomUpPathCount == OverflowOccurredValue)
303 return true;
Michael Gottesman9e7261c2013-06-07 06:16:49 +0000304 unsigned long long Product =
305 (unsigned long long)TopDownPathCount*BottomUpPathCount;
Alp Tokercb402912014-01-24 17:20:08 +0000306 // Overflow occurred if any of the upper bits of Product are set or if all
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000307 // the lower bits of Product are all set.
308 return (Product >> 32) ||
309 ((PathCount = Product) == OverflowOccurredValue);
John McCalld935e9c2011-06-15 23:37:01 +0000310 }
Dan Gohman12130272011-08-12 00:26:31 +0000311
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000312 // Specialized CFG utilities.
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000313 using edge_iterator = SmallVectorImpl<BasicBlock *>::const_iterator;
314
Michael Gottesman0fecf982013-08-07 23:56:34 +0000315 edge_iterator pred_begin() const { return Preds.begin(); }
316 edge_iterator pred_end() const { return Preds.end(); }
317 edge_iterator succ_begin() const { return Succs.begin(); }
318 edge_iterator succ_end() const { return Succs.end(); }
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000319
320 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
321 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
322
323 bool isExit() const { return Succs.empty(); }
John McCalld935e9c2011-06-15 23:37:01 +0000324 };
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000325
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000326} // end anonymous namespace
327
328const unsigned BBState::OverflowOccurredValue = 0xffffffff;
John McCalld935e9c2011-06-15 23:37:01 +0000329
Michael Gottesmanc01ab512015-03-16 07:02:39 +0000330namespace llvm {
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000331
Michael Gottesmand63436f2015-03-16 08:00:27 +0000332raw_ostream &operator<<(raw_ostream &OS,
333 BBState &BBState) LLVM_ATTRIBUTE_UNUSED;
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000334
335} // end namespace llvm
Michael Gottesmanc01ab512015-03-16 07:02:39 +0000336
John McCalld935e9c2011-06-15 23:37:01 +0000337void BBState::InitFromPred(const BBState &Other) {
338 PerPtrTopDown = Other.PerPtrTopDown;
339 TopDownPathCount = Other.TopDownPathCount;
340}
341
342void BBState::InitFromSucc(const BBState &Other) {
343 PerPtrBottomUp = Other.PerPtrBottomUp;
344 BottomUpPathCount = Other.BottomUpPathCount;
345}
346
Michael Gottesman97e3df02013-01-14 00:35:14 +0000347/// The top-down traversal uses this to merge information about predecessors to
348/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +0000349void BBState::MergePred(const BBState &Other) {
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000350 if (TopDownPathCount == OverflowOccurredValue)
351 return;
352
John McCalld935e9c2011-06-15 23:37:01 +0000353 // Other.TopDownPathCount can be 0, in which case it is either dead or a
354 // loop backedge. Loop backedges are special.
355 TopDownPathCount += Other.TopDownPathCount;
356
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000357 // In order to be consistent, we clear the top down pointers when by adding
358 // TopDownPathCount becomes OverflowOccurredValue even though "true" overflow
Alp Tokercb402912014-01-24 17:20:08 +0000359 // has not occurred.
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000360 if (TopDownPathCount == OverflowOccurredValue) {
361 clearTopDownPointers();
362 return;
363 }
364
Michael Gottesman4385edf2013-01-14 01:47:53 +0000365 // Check for overflow. If we have overflow, fall back to conservative
366 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +0000367 if (TopDownPathCount < Other.TopDownPathCount) {
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000368 TopDownPathCount = OverflowOccurredValue;
Dan Gohman7c84dad2012-09-12 20:45:17 +0000369 clearTopDownPointers();
370 return;
371 }
372
John McCalld935e9c2011-06-15 23:37:01 +0000373 // For each entry in the other set, if our set has an entry with the same key,
374 // merge the entries. Otherwise, copy the entry and merge it with an empty
375 // entry.
Michael Gottesmana9fc0162015-03-05 23:29:06 +0000376 for (auto MI = Other.top_down_ptr_begin(), ME = Other.top_down_ptr_end();
377 MI != ME; ++MI) {
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000378 auto Pair = PerPtrTopDown.insert(*MI);
379 Pair.first->second.Merge(Pair.second ? TopDownPtrState() : MI->second,
John McCalld935e9c2011-06-15 23:37:01 +0000380 /*TopDown=*/true);
381 }
382
Dan Gohman7e315fc32011-08-11 21:06:32 +0000383 // For each entry in our set, if the other set doesn't have an entry with the
John McCalld935e9c2011-06-15 23:37:01 +0000384 // same key, force it to merge with an empty entry.
Michael Gottesmana9fc0162015-03-05 23:29:06 +0000385 for (auto MI = top_down_ptr_begin(), ME = top_down_ptr_end(); MI != ME; ++MI)
John McCalld935e9c2011-06-15 23:37:01 +0000386 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000387 MI->second.Merge(TopDownPtrState(), /*TopDown=*/true);
John McCalld935e9c2011-06-15 23:37:01 +0000388}
389
Michael Gottesman97e3df02013-01-14 00:35:14 +0000390/// The bottom-up traversal uses this to merge information about successors to
391/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +0000392void BBState::MergeSucc(const BBState &Other) {
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000393 if (BottomUpPathCount == OverflowOccurredValue)
394 return;
395
John McCalld935e9c2011-06-15 23:37:01 +0000396 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
397 // loop backedge. Loop backedges are special.
398 BottomUpPathCount += Other.BottomUpPathCount;
399
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000400 // In order to be consistent, we clear the top down pointers when by adding
401 // BottomUpPathCount becomes OverflowOccurredValue even though "true" overflow
Alp Tokercb402912014-01-24 17:20:08 +0000402 // has not occurred.
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000403 if (BottomUpPathCount == OverflowOccurredValue) {
404 clearBottomUpPointers();
405 return;
406 }
407
Michael Gottesman4385edf2013-01-14 01:47:53 +0000408 // Check for overflow. If we have overflow, fall back to conservative
409 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +0000410 if (BottomUpPathCount < Other.BottomUpPathCount) {
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +0000411 BottomUpPathCount = OverflowOccurredValue;
Dan Gohman7c84dad2012-09-12 20:45:17 +0000412 clearBottomUpPointers();
413 return;
414 }
415
John McCalld935e9c2011-06-15 23:37:01 +0000416 // For each entry in the other set, if our set has an entry with the
417 // same key, merge the entries. Otherwise, copy the entry and merge
418 // it with an empty entry.
Michael Gottesmana9fc0162015-03-05 23:29:06 +0000419 for (auto MI = Other.bottom_up_ptr_begin(), ME = Other.bottom_up_ptr_end();
420 MI != ME; ++MI) {
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000421 auto Pair = PerPtrBottomUp.insert(*MI);
422 Pair.first->second.Merge(Pair.second ? BottomUpPtrState() : MI->second,
John McCalld935e9c2011-06-15 23:37:01 +0000423 /*TopDown=*/false);
424 }
425
Dan Gohman7e315fc32011-08-11 21:06:32 +0000426 // For each entry in our set, if the other set doesn't have an entry
John McCalld935e9c2011-06-15 23:37:01 +0000427 // with the same key, force it to merge with an empty entry.
Michael Gottesmana9fc0162015-03-05 23:29:06 +0000428 for (auto MI = bottom_up_ptr_begin(), ME = bottom_up_ptr_end(); MI != ME;
429 ++MI)
John McCalld935e9c2011-06-15 23:37:01 +0000430 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
Michael Gottesmanfeb138e2015-03-06 00:34:36 +0000431 MI->second.Merge(BottomUpPtrState(), /*TopDown=*/false);
John McCalld935e9c2011-06-15 23:37:01 +0000432}
433
Michael Gottesmanc01ab512015-03-16 07:02:39 +0000434raw_ostream &llvm::operator<<(raw_ostream &OS, BBState &BBInfo) {
435 // Dump the pointers we are tracking.
436 OS << " TopDown State:\n";
437 if (!BBInfo.hasTopDownPtrs()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000438 LLVM_DEBUG(dbgs() << " NONE!\n");
Michael Gottesmanc01ab512015-03-16 07:02:39 +0000439 } else {
440 for (auto I = BBInfo.top_down_ptr_begin(), E = BBInfo.top_down_ptr_end();
441 I != E; ++I) {
442 const PtrState &P = I->second;
443 OS << " Ptr: " << *I->first
444 << "\n KnownSafe: " << (P.IsKnownSafe()?"true":"false")
445 << "\n ImpreciseRelease: "
446 << (P.IsTrackingImpreciseReleases()?"true":"false") << "\n"
447 << " HasCFGHazards: "
448 << (P.IsCFGHazardAfflicted()?"true":"false") << "\n"
449 << " KnownPositive: "
450 << (P.HasKnownPositiveRefCount()?"true":"false") << "\n"
451 << " Seq: "
452 << P.GetSeq() << "\n";
453 }
454 }
455
456 OS << " BottomUp State:\n";
457 if (!BBInfo.hasBottomUpPtrs()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000458 LLVM_DEBUG(dbgs() << " NONE!\n");
Michael Gottesmanc01ab512015-03-16 07:02:39 +0000459 } else {
460 for (auto I = BBInfo.bottom_up_ptr_begin(), E = BBInfo.bottom_up_ptr_end();
461 I != E; ++I) {
462 const PtrState &P = I->second;
463 OS << " Ptr: " << *I->first
464 << "\n KnownSafe: " << (P.IsKnownSafe()?"true":"false")
465 << "\n ImpreciseRelease: "
466 << (P.IsTrackingImpreciseReleases()?"true":"false") << "\n"
467 << " HasCFGHazards: "
468 << (P.IsCFGHazardAfflicted()?"true":"false") << "\n"
469 << " KnownPositive: "
470 << (P.HasKnownPositiveRefCount()?"true":"false") << "\n"
471 << " Seq: "
472 << P.GetSeq() << "\n";
473 }
474 }
475
476 return OS;
477}
478
John McCalld935e9c2011-06-15 23:37:01 +0000479namespace {
Michael Gottesman41c01002015-03-06 00:34:33 +0000480
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000481 /// The main ARC optimization pass.
John McCalld935e9c2011-06-15 23:37:01 +0000482 class ObjCARCOpt : public FunctionPass {
483 bool Changed;
484 ProvenanceAnalysis PA;
Michael Gottesman41c01002015-03-06 00:34:33 +0000485
486 /// A cache of references to runtime entry point constants.
Michael Gottesman14acfac2013-07-06 01:39:23 +0000487 ARCRuntimeEntryPoints EP;
John McCalld935e9c2011-06-15 23:37:01 +0000488
Michael Gottesman41c01002015-03-06 00:34:33 +0000489 /// A cache of MDKinds that can be passed into other functions to propagate
490 /// MDKind identifiers.
491 ARCMDKindCache MDKindCache;
492
Michael Gottesman97e3df02013-01-14 00:35:14 +0000493 /// A flag indicating whether this optimization pass should run.
Dan Gohmanceaac7c2011-06-20 23:20:43 +0000494 bool Run;
495
Akira Hatanaka8edf8f32019-04-25 19:42:55 +0000496 /// A flag indicating whether the optimization that removes or moves
497 /// retain/release pairs should be performed.
498 bool DisableRetainReleasePairing = false;
499
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000500 /// Flags which determine whether each of the interesting runtime functions
Michael Gottesman97e3df02013-01-14 00:35:14 +0000501 /// is in fact used in the current function.
John McCalld935e9c2011-06-15 23:37:01 +0000502 unsigned UsedInThisFunction;
503
John McCalld935e9c2011-06-15 23:37:01 +0000504 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
Michael Gottesman556ff612013-01-12 01:25:19 +0000505 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000506 ARCInstKind &Class);
John McCalld935e9c2011-06-15 23:37:01 +0000507 void OptimizeIndividualCalls(Function &F);
508
509 void CheckForCFGHazards(const BasicBlock *BB,
510 DenseMap<const BasicBlock *, BBState> &BBStates,
511 BBState &MyStates) const;
Michael Gottesman0be69202015-03-05 23:28:58 +0000512 bool VisitInstructionBottomUp(Instruction *Inst, BasicBlock *BB,
513 BlotMapVector<Value *, RRInfo> &Retains,
Dan Gohman817a7c62012-03-22 18:24:56 +0000514 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +0000515 bool VisitBottomUp(BasicBlock *BB,
516 DenseMap<const BasicBlock *, BBState> &BBStates,
Michael Gottesman0be69202015-03-05 23:28:58 +0000517 BlotMapVector<Value *, RRInfo> &Retains);
Dan Gohman817a7c62012-03-22 18:24:56 +0000518 bool VisitInstructionTopDown(Instruction *Inst,
519 DenseMap<Value *, RRInfo> &Releases,
520 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +0000521 bool VisitTopDown(BasicBlock *BB,
522 DenseMap<const BasicBlock *, BBState> &BBStates,
523 DenseMap<Value *, RRInfo> &Releases);
Michael Gottesman0be69202015-03-05 23:28:58 +0000524 bool Visit(Function &F, DenseMap<const BasicBlock *, BBState> &BBStates,
525 BlotMapVector<Value *, RRInfo> &Retains,
John McCalld935e9c2011-06-15 23:37:01 +0000526 DenseMap<Value *, RRInfo> &Releases);
527
528 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
Michael Gottesman0be69202015-03-05 23:28:58 +0000529 BlotMapVector<Value *, RRInfo> &Retains,
John McCalld935e9c2011-06-15 23:37:01 +0000530 DenseMap<Value *, RRInfo> &Releases,
Michael Gottesman0be69202015-03-05 23:28:58 +0000531 SmallVectorImpl<Instruction *> &DeadInsts, Module *M);
John McCalld935e9c2011-06-15 23:37:01 +0000532
Michael Gottesman67792172015-03-16 07:02:30 +0000533 bool
534 PairUpRetainsAndReleases(DenseMap<const BasicBlock *, BBState> &BBStates,
535 BlotMapVector<Value *, RRInfo> &Retains,
536 DenseMap<Value *, RRInfo> &Releases, Module *M,
Akira Hatanaka2b882052017-02-25 00:53:38 +0000537 Instruction * Retain,
Michael Gottesman67792172015-03-16 07:02:30 +0000538 SmallVectorImpl<Instruction *> &DeadInsts,
539 RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
540 Value *Arg, bool KnownSafe,
541 bool &AnyPairsCompletelyEliminated);
Michael Gottesman9de6f962013-01-22 21:49:00 +0000542
John McCalld935e9c2011-06-15 23:37:01 +0000543 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
Michael Gottesman0be69202015-03-05 23:28:58 +0000544 BlotMapVector<Value *, RRInfo> &Retains,
545 DenseMap<Value *, RRInfo> &Releases, Module *M);
John McCalld935e9c2011-06-15 23:37:01 +0000546
547 void OptimizeWeakCalls(Function &F);
548
549 bool OptimizeSequences(Function &F);
550
551 void OptimizeReturns(Function &F);
552
Michael Gottesman9c118152013-04-29 06:16:57 +0000553#ifndef NDEBUG
554 void GatherStatistics(Function &F, bool AfterOptimization = false);
555#endif
556
Craig Topper3e4c6972014-03-05 09:10:37 +0000557 void getAnalysisUsage(AnalysisUsage &AU) const override;
558 bool doInitialization(Module &M) override;
559 bool runOnFunction(Function &F) override;
560 void releaseMemory() override;
John McCalld935e9c2011-06-15 23:37:01 +0000561
562 public:
563 static char ID;
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000564
John McCalld935e9c2011-06-15 23:37:01 +0000565 ObjCARCOpt() : FunctionPass(ID) {
566 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
567 }
568 };
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000569
570} // end anonymous namespace
John McCalld935e9c2011-06-15 23:37:01 +0000571
572char ObjCARCOpt::ID = 0;
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000573
John McCalld935e9c2011-06-15 23:37:01 +0000574INITIALIZE_PASS_BEGIN(ObjCARCOpt,
575 "objc-arc", "ObjC ARC optimization", false, false)
Chandler Carruth7b560d42015-09-09 17:55:00 +0000576INITIALIZE_PASS_DEPENDENCY(ObjCARCAAWrapperPass)
John McCalld935e9c2011-06-15 23:37:01 +0000577INITIALIZE_PASS_END(ObjCARCOpt,
578 "objc-arc", "ObjC ARC optimization", false, false)
579
580Pass *llvm::createObjCARCOptPass() {
581 return new ObjCARCOpt();
582}
583
584void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruth7b560d42015-09-09 17:55:00 +0000585 AU.addRequired<ObjCARCAAWrapperPass>();
586 AU.addRequired<AAResultsWrapperPass>();
John McCalld935e9c2011-06-15 23:37:01 +0000587 // ARC optimization doesn't currently split critical edges.
588 AU.setPreservesCFG();
589}
590
Michael Gottesman97e3df02013-01-14 00:35:14 +0000591/// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is
592/// not a return value. Or, if it can be paired with an
593/// objc_autoreleaseReturnValue, delete the pair and return true.
John McCalld935e9c2011-06-15 23:37:01 +0000594bool
595ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +0000596 // Check for the argument being from an immediately preceding call or invoke.
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000597 const Value *Arg = GetArgRCIdentityRoot(RetainRV);
Dan Gohmandae33492012-04-27 18:56:31 +0000598 ImmutableCallSite CS(Arg);
599 if (const Instruction *Call = CS.getInstruction()) {
John McCalld935e9c2011-06-15 23:37:01 +0000600 if (Call->getParent() == RetainRV->getParent()) {
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +0000601 BasicBlock::const_iterator I(Call);
John McCalld935e9c2011-06-15 23:37:01 +0000602 ++I;
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +0000603 while (IsNoopInstruction(&*I))
604 ++I;
John McCalld935e9c2011-06-15 23:37:01 +0000605 if (&*I == RetainRV)
606 return false;
Dan Gohmandae33492012-04-27 18:56:31 +0000607 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +0000608 BasicBlock *RetainRVParent = RetainRV->getParent();
609 if (II->getNormalDest() == RetainRVParent) {
Dan Gohmandae33492012-04-27 18:56:31 +0000610 BasicBlock::const_iterator I = RetainRVParent->begin();
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +0000611 while (IsNoopInstruction(&*I))
612 ++I;
Dan Gohmane3ed2b02012-03-23 18:09:00 +0000613 if (&*I == RetainRV)
614 return false;
615 }
John McCalld935e9c2011-06-15 23:37:01 +0000616 }
Dan Gohmane3ed2b02012-03-23 18:09:00 +0000617 }
John McCalld935e9c2011-06-15 23:37:01 +0000618
Pete Cooper697281d2019-01-03 01:38:08 +0000619 // Track PHIs which are equivalent to our Arg.
620 SmallDenseSet<const Value*, 2> EquivalentArgs;
621 EquivalentArgs.insert(Arg);
622
623 // Add PHIs that are equivalent to Arg to ArgUsers.
624 if (const PHINode *PN = dyn_cast<PHINode>(Arg)) {
625 SmallVector<const Value *, 2> ArgUsers;
626 getEquivalentPHIs(*PN, ArgUsers);
627 EquivalentArgs.insert(ArgUsers.begin(), ArgUsers.end());
628 }
629
John McCalld935e9c2011-06-15 23:37:01 +0000630 // Check for being preceded by an objc_autoreleaseReturnValue on the same
631 // pointer. In this case, we can delete the pair.
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +0000632 BasicBlock::iterator I = RetainRV->getIterator(),
633 Begin = RetainRV->getParent()->begin();
John McCalld935e9c2011-06-15 23:37:01 +0000634 if (I != Begin) {
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +0000635 do
636 --I;
637 while (I != Begin && IsNoopInstruction(&*I));
638 if (GetBasicARCInstKind(&*I) == ARCInstKind::AutoreleaseRV &&
Pete Cooper697281d2019-01-03 01:38:08 +0000639 EquivalentArgs.count(GetArgRCIdentityRoot(&*I))) {
John McCalld935e9c2011-06-15 23:37:01 +0000640 Changed = true;
641 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +0000642
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000643 LLVM_DEBUG(dbgs() << "Erasing autoreleaseRV,retainRV pair: " << *I << "\n"
644 << "Erasing " << *RetainRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +0000645
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +0000646 EraseInstruction(&*I);
John McCalld935e9c2011-06-15 23:37:01 +0000647 EraseInstruction(RetainRV);
648 return true;
649 }
650 }
651
652 // Turn it to a plain objc_retain.
653 Changed = true;
654 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +0000655
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000656 LLVM_DEBUG(dbgs() << "Transforming objc_retainAutoreleasedReturnValue => "
657 "objc_retain since the operand is not a return value.\n"
658 "Old = "
659 << *RetainRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +0000660
James Y Knight291f7912019-02-01 20:44:54 +0000661 Function *NewDecl = EP.get(ARCRuntimeEntryPointKind::Retain);
Michael Gottesman14acfac2013-07-06 01:39:23 +0000662 cast<CallInst>(RetainRV)->setCalledFunction(NewDecl);
Michael Gottesmandef07bb2013-01-05 17:55:42 +0000663
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000664 LLVM_DEBUG(dbgs() << "New = " << *RetainRV << "\n");
Michael Gottesmandef07bb2013-01-05 17:55:42 +0000665
John McCalld935e9c2011-06-15 23:37:01 +0000666 return false;
667}
668
Michael Gottesman97e3df02013-01-14 00:35:14 +0000669/// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not
670/// used as a return value.
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000671void ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F,
672 Instruction *AutoreleaseRV,
673 ARCInstKind &Class) {
John McCalld935e9c2011-06-15 23:37:01 +0000674 // Check for a return of the pointer value.
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000675 const Value *Ptr = GetArgRCIdentityRoot(AutoreleaseRV);
Duncan P. N. Exon Smith11c06ea2016-09-24 21:01:20 +0000676
677 // If the argument is ConstantPointerNull or UndefValue, its other users
678 // aren't actually interesting to look at.
679 if (isa<ConstantData>(Ptr))
680 return;
681
Dan Gohman10a18d52011-08-12 00:36:31 +0000682 SmallVector<const Value *, 2> Users;
683 Users.push_back(Ptr);
Akira Hatanaka73ceb502018-01-19 23:51:13 +0000684
685 // Add PHIs that are equivalent to Ptr to Users.
686 if (const PHINode *PN = dyn_cast<PHINode>(Ptr))
687 getEquivalentPHIs(*PN, Users);
688
Dan Gohman10a18d52011-08-12 00:36:31 +0000689 do {
690 Ptr = Users.pop_back_val();
Chandler Carruthcdf47882014-03-09 03:16:01 +0000691 for (const User *U : Ptr->users()) {
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000692 if (isa<ReturnInst>(U) || GetBasicARCInstKind(U) == ARCInstKind::RetainRV)
Dan Gohman10a18d52011-08-12 00:36:31 +0000693 return;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000694 if (isa<BitCastInst>(U))
695 Users.push_back(U);
Dan Gohman10a18d52011-08-12 00:36:31 +0000696 }
697 } while (!Users.empty());
John McCalld935e9c2011-06-15 23:37:01 +0000698
699 Changed = true;
700 ++NumPeeps;
Michael Gottesman1bf69082013-01-06 21:07:11 +0000701
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000702 LLVM_DEBUG(
703 dbgs() << "Transforming objc_autoreleaseReturnValue => "
704 "objc_autorelease since its operand is not used as a return "
705 "value.\n"
706 "Old = "
707 << *AutoreleaseRV << "\n");
Michael Gottesman1bf69082013-01-06 21:07:11 +0000708
Michael Gottesmanc9656fa2013-01-12 01:25:15 +0000709 CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
James Y Knight291f7912019-02-01 20:44:54 +0000710 Function *NewDecl = EP.get(ARCRuntimeEntryPointKind::Autorelease);
Michael Gottesman14acfac2013-07-06 01:39:23 +0000711 AutoreleaseRVCI->setCalledFunction(NewDecl);
Michael Gottesmanc9656fa2013-01-12 01:25:15 +0000712 AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000713 Class = ARCInstKind::Autorelease;
Michael Gottesman10426b52013-01-07 21:26:07 +0000714
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000715 LLVM_DEBUG(dbgs() << "New: " << *AutoreleaseRV << "\n");
John McCalld935e9c2011-06-15 23:37:01 +0000716}
717
Saleem Abdulrasool8b342682018-03-12 21:46:09 +0000718namespace {
719Instruction *
Saleem Abdulrasoolf159a3892018-03-12 23:48:20 +0000720CloneCallInstForBB(CallInst &CI, BasicBlock &BB,
Shoaib Meenai106df7d2018-04-20 22:14:45 +0000721 const DenseMap<BasicBlock *, ColorVector> &BlockColors) {
Saleem Abdulrasool8b342682018-03-12 21:46:09 +0000722 SmallVector<OperandBundleDef, 1> OpBundles;
Saleem Abdulrasoolf159a3892018-03-12 23:48:20 +0000723 for (unsigned I = 0, E = CI.getNumOperandBundles(); I != E; ++I) {
724 auto Bundle = CI.getOperandBundleAt(I);
725 // Funclets will be reassociated in the future.
Saleem Abdulrasool8b342682018-03-12 21:46:09 +0000726 if (Bundle.getTagID() == LLVMContext::OB_funclet)
727 continue;
728 OpBundles.emplace_back(Bundle);
729 }
730
731 if (!BlockColors.empty()) {
732 const ColorVector &CV = BlockColors.find(&BB)->second;
733 assert(CV.size() == 1 && "non-unique color for block!");
734 Instruction *EHPad = CV.front()->getFirstNonPHI();
735 if (EHPad->isEHPad())
736 OpBundles.emplace_back("funclet", EHPad);
737 }
738
Saleem Abdulrasoolf159a3892018-03-12 23:48:20 +0000739 return CallInst::Create(&CI, OpBundles);
Saleem Abdulrasool8b342682018-03-12 21:46:09 +0000740}
741}
742
Michael Gottesman97e3df02013-01-14 00:35:14 +0000743/// Visit each call, one at a time, and make simplifications without doing any
744/// additional analysis.
John McCalld935e9c2011-06-15 23:37:01 +0000745void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000746 LLVM_DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeIndividualCalls ==\n");
John McCalld935e9c2011-06-15 23:37:01 +0000747 // Reset all the flags in preparation for recomputing them.
748 UsedInThisFunction = 0;
749
Saleem Abdulrasool8b342682018-03-12 21:46:09 +0000750 DenseMap<BasicBlock *, ColorVector> BlockColors;
751 if (F.hasPersonalityFn() &&
Heejin Ahnb4be38f2018-05-17 20:52:03 +0000752 isScopedEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
Saleem Abdulrasool8b342682018-03-12 21:46:09 +0000753 BlockColors = colorEHFunclets(F);
754
John McCalld935e9c2011-06-15 23:37:01 +0000755 // Visit all objc_* calls in F.
756 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
757 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +0000758
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000759 ARCInstKind Class = GetBasicARCInstKind(Inst);
John McCalld935e9c2011-06-15 23:37:01 +0000760
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000761 LLVM_DEBUG(dbgs() << "Visiting: Class: " << Class << "; " << *Inst << "\n");
Michael Gottesman782e3442013-01-17 18:32:34 +0000762
John McCalld935e9c2011-06-15 23:37:01 +0000763 switch (Class) {
764 default: break;
765
766 // Delete no-op casts. These function calls have special semantics, but
767 // the semantics are entirely implemented via lowering in the front-end,
768 // so by the time they reach the optimizer, they are just no-op calls
769 // which return their argument.
770 //
771 // There are gray areas here, as the ability to cast reference-counted
772 // pointers to raw void* and back allows code to break ARC assumptions,
773 // however these are currently considered to be unimportant.
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000774 case ARCInstKind::NoopCast:
John McCalld935e9c2011-06-15 23:37:01 +0000775 Changed = true;
776 ++NumNoops;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000777 LLVM_DEBUG(dbgs() << "Erasing no-op cast: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +0000778 EraseInstruction(Inst);
779 continue;
780
781 // If the pointer-to-weak-pointer is null, it's undefined behavior.
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000782 case ARCInstKind::StoreWeak:
783 case ARCInstKind::LoadWeak:
784 case ARCInstKind::LoadWeakRetained:
785 case ARCInstKind::InitWeak:
786 case ARCInstKind::DestroyWeak: {
John McCalld935e9c2011-06-15 23:37:01 +0000787 CallInst *CI = cast<CallInst>(Inst);
Michael Gottesman65c24812013-03-25 09:27:43 +0000788 if (IsNullOrUndef(CI->getArgOperand(0))) {
Dan Gohman670f9372012-04-13 18:57:48 +0000789 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +0000790 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +0000791 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
792 Constant::getNullValue(Ty),
793 CI);
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000794 Value *NewValue = UndefValue::get(CI->getType());
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000795 LLVM_DEBUG(
796 dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
797 "\nOld = "
798 << *CI << "\nNew = " << *NewValue << "\n");
Michael Gottesmanfec61c02013-01-06 21:54:30 +0000799 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +0000800 CI->eraseFromParent();
801 continue;
802 }
803 break;
804 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000805 case ARCInstKind::CopyWeak:
806 case ARCInstKind::MoveWeak: {
John McCalld935e9c2011-06-15 23:37:01 +0000807 CallInst *CI = cast<CallInst>(Inst);
Michael Gottesman65c24812013-03-25 09:27:43 +0000808 if (IsNullOrUndef(CI->getArgOperand(0)) ||
809 IsNullOrUndef(CI->getArgOperand(1))) {
Dan Gohman670f9372012-04-13 18:57:48 +0000810 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +0000811 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +0000812 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
813 Constant::getNullValue(Ty),
814 CI);
Michael Gottesmanfec61c02013-01-06 21:54:30 +0000815
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000816 Value *NewValue = UndefValue::get(CI->getType());
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000817 LLVM_DEBUG(
818 dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
819 "\nOld = "
820 << *CI << "\nNew = " << *NewValue << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +0000821
Michael Gottesmanfec61c02013-01-06 21:54:30 +0000822 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +0000823 CI->eraseFromParent();
824 continue;
825 }
826 break;
827 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000828 case ARCInstKind::RetainRV:
John McCalld935e9c2011-06-15 23:37:01 +0000829 if (OptimizeRetainRVCall(F, Inst))
830 continue;
831 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000832 case ARCInstKind::AutoreleaseRV:
Michael Gottesman556ff612013-01-12 01:25:19 +0000833 OptimizeAutoreleaseRVCall(F, Inst, Class);
John McCalld935e9c2011-06-15 23:37:01 +0000834 break;
835 }
836
Michael Gottesmanb8c88362013-04-03 02:57:24 +0000837 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
John McCalld935e9c2011-06-15 23:37:01 +0000838 if (IsAutorelease(Class) && Inst->use_empty()) {
839 CallInst *Call = cast<CallInst>(Inst);
840 const Value *Arg = Call->getArgOperand(0);
841 Arg = FindSingleUseIdentifiedObject(Arg);
842 if (Arg) {
843 Changed = true;
844 ++NumAutoreleases;
845
846 // Create the declaration lazily.
847 LLVMContext &C = Inst->getContext();
Michael Gottesman01df4502013-07-06 01:41:35 +0000848
James Y Knight7976eb52019-02-01 20:43:25 +0000849 Function *Decl = EP.get(ARCRuntimeEntryPointKind::Release);
Michael Gottesman14acfac2013-07-06 01:39:23 +0000850 CallInst *NewCall = CallInst::Create(Decl, Call->getArgOperand(0), "",
851 Call);
Michael Gottesman65cb7372015-03-16 07:02:27 +0000852 NewCall->setMetadata(MDKindCache.get(ARCMDKindID::ImpreciseRelease),
Michael Gottesman41c01002015-03-06 00:34:33 +0000853 MDNode::get(C, None));
Michael Gottesman10426b52013-01-07 21:26:07 +0000854
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000855 LLVM_DEBUG(
856 dbgs() << "Replacing autorelease{,RV}(x) with objc_release(x) "
857 "since x is otherwise unused.\nOld: "
858 << *Call << "\nNew: " << *NewCall << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +0000859
John McCalld935e9c2011-06-15 23:37:01 +0000860 EraseInstruction(Call);
861 Inst = NewCall;
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000862 Class = ARCInstKind::Release;
John McCalld935e9c2011-06-15 23:37:01 +0000863 }
864 }
865
866 // For functions which can never be passed stack arguments, add
867 // a tail keyword.
Akira Hatanakab576c772019-03-21 20:16:09 +0000868 if (IsAlwaysTail(Class) && !cast<CallInst>(Inst)->isNoTailCall()) {
John McCalld935e9c2011-06-15 23:37:01 +0000869 Changed = true;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000870 LLVM_DEBUG(
871 dbgs() << "Adding tail keyword to function since it can never be "
872 "passed stack args: "
873 << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +0000874 cast<CallInst>(Inst)->setTailCall();
875 }
876
Michael Gottesmanc9656fa2013-01-12 01:25:15 +0000877 // Ensure that functions that can never have a "tail" keyword due to the
878 // semantics of ARC truly do not do so.
879 if (IsNeverTail(Class)) {
880 Changed = true;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000881 LLVM_DEBUG(dbgs() << "Removing tail keyword from function: " << *Inst
882 << "\n");
Michael Gottesmanc9656fa2013-01-12 01:25:15 +0000883 cast<CallInst>(Inst)->setTailCall(false);
884 }
885
John McCalld935e9c2011-06-15 23:37:01 +0000886 // Set nounwind as needed.
887 if (IsNoThrow(Class)) {
888 Changed = true;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000889 LLVM_DEBUG(dbgs() << "Found no throw class. Setting nounwind on: "
890 << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +0000891 cast<CallInst>(Inst)->setDoesNotThrow();
892 }
893
894 if (!IsNoopOnNull(Class)) {
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000895 UsedInThisFunction |= 1 << unsigned(Class);
John McCalld935e9c2011-06-15 23:37:01 +0000896 continue;
897 }
898
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000899 const Value *Arg = GetArgRCIdentityRoot(Inst);
John McCalld935e9c2011-06-15 23:37:01 +0000900
901 // ARC calls with null are no-ops. Delete them.
Michael Gottesman65c24812013-03-25 09:27:43 +0000902 if (IsNullOrUndef(Arg)) {
John McCalld935e9c2011-06-15 23:37:01 +0000903 Changed = true;
904 ++NumNoops;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000905 LLVM_DEBUG(dbgs() << "ARC calls with null are no-ops. Erasing: " << *Inst
906 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +0000907 EraseInstruction(Inst);
908 continue;
909 }
910
911 // Keep track of which of retain, release, autorelease, and retain_block
912 // are actually present in this function.
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000913 UsedInThisFunction |= 1 << unsigned(Class);
John McCalld935e9c2011-06-15 23:37:01 +0000914
915 // If Arg is a PHI, and one or more incoming values to the
916 // PHI are null, and the call is control-equivalent to the PHI, and there
Akira Hatanakae8c1a542017-10-16 16:46:59 +0000917 // are no relevant side effects between the PHI and the call, and the call
918 // is not a release that doesn't have the clang.imprecise_release tag, the
919 // call could be pushed up to just those paths with non-null incoming
920 // values. For now, don't bother splitting critical edges for this.
921 if (Class == ARCInstKind::Release &&
922 !Inst->getMetadata(MDKindCache.get(ARCMDKindID::ImpreciseRelease)))
923 continue;
924
John McCalld935e9c2011-06-15 23:37:01 +0000925 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
926 Worklist.push_back(std::make_pair(Inst, Arg));
927 do {
928 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
929 Inst = Pair.first;
930 Arg = Pair.second;
931
932 const PHINode *PN = dyn_cast<PHINode>(Arg);
933 if (!PN) continue;
934
935 // Determine if the PHI has any null operands, or any incoming
936 // critical edges.
937 bool HasNull = false;
938 bool HasCriticalEdges = false;
939 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
940 Value *Incoming =
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000941 GetRCIdentityRoot(PN->getIncomingValue(i));
Michael Gottesman65c24812013-03-25 09:27:43 +0000942 if (IsNullOrUndef(Incoming))
John McCalld935e9c2011-06-15 23:37:01 +0000943 HasNull = true;
Chandler Carruthc1e3ee22018-10-18 00:38:34 +0000944 else if (PN->getIncomingBlock(i)->getTerminator()->getNumSuccessors() !=
945 1) {
John McCalld935e9c2011-06-15 23:37:01 +0000946 HasCriticalEdges = true;
947 break;
948 }
949 }
950 // If we have null operands and no critical edges, optimize.
951 if (!HasCriticalEdges && HasNull) {
952 SmallPtrSet<Instruction *, 4> DependingInstructions;
953 SmallPtrSet<const BasicBlock *, 4> Visited;
954
955 // Check that there is nothing that cares about the reference
956 // count between the call and the phi.
Dan Gohman8478d762012-04-13 00:59:57 +0000957 switch (Class) {
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000958 case ARCInstKind::Retain:
959 case ARCInstKind::RetainBlock:
Dan Gohman8478d762012-04-13 00:59:57 +0000960 // These can always be moved up.
961 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000962 case ARCInstKind::Release:
Dan Gohman41375a32012-05-08 23:39:44 +0000963 // These can't be moved across things that care about the retain
964 // count.
Dan Gohman8478d762012-04-13 00:59:57 +0000965 FindDependencies(NeedsPositiveRetainCount, Arg,
966 Inst->getParent(), Inst,
967 DependingInstructions, Visited, PA);
968 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000969 case ARCInstKind::Autorelease:
Dan Gohman8478d762012-04-13 00:59:57 +0000970 // These can't be moved across autorelease pool scope boundaries.
971 FindDependencies(AutoreleasePoolBoundary, Arg,
972 Inst->getParent(), Inst,
973 DependingInstructions, Visited, PA);
974 break;
Frederic Riss009d6062016-02-17 18:51:27 +0000975 case ARCInstKind::ClaimRV:
Michael Gottesman6f729fa2015-02-19 19:51:32 +0000976 case ARCInstKind::RetainRV:
977 case ARCInstKind::AutoreleaseRV:
Dan Gohman8478d762012-04-13 00:59:57 +0000978 // Don't move these; the RV optimization depends on the autoreleaseRV
979 // being tail called, and the retainRV being immediately after a call
980 // (which might still happen if we get lucky with codegen layout, but
981 // it's not worth taking the chance).
982 continue;
983 default:
984 llvm_unreachable("Invalid dependence flavor");
985 }
986
John McCalld935e9c2011-06-15 23:37:01 +0000987 if (DependingInstructions.size() == 1 &&
988 *DependingInstructions.begin() == PN) {
989 Changed = true;
990 ++NumPartialNoops;
991 // Clone the call into each predecessor that has a non-null value.
992 CallInst *CInst = cast<CallInst>(Inst);
Chris Lattner229907c2011-07-18 04:54:35 +0000993 Type *ParamTy = CInst->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +0000994 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
995 Value *Incoming =
Michael Gottesmane5ad66f2015-02-19 00:42:38 +0000996 GetRCIdentityRoot(PN->getIncomingValue(i));
Michael Gottesman65c24812013-03-25 09:27:43 +0000997 if (!IsNullOrUndef(Incoming)) {
John McCalld935e9c2011-06-15 23:37:01 +0000998 Value *Op = PN->getIncomingValue(i);
999 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
Saleem Abdulrasool8b342682018-03-12 21:46:09 +00001000 CallInst *Clone = cast<CallInst>(CloneCallInstForBB(
1001 *CInst, *InsertPos->getParent(), BlockColors));
John McCalld935e9c2011-06-15 23:37:01 +00001002 if (Op->getType() != ParamTy)
1003 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
1004 Clone->setArgOperand(0, Op);
1005 Clone->insertBefore(InsertPos);
Michael Gottesmanc189a392013-01-09 19:23:24 +00001006
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001007 LLVM_DEBUG(dbgs() << "Cloning " << *CInst
1008 << "\n"
1009 "And inserting clone at "
1010 << *InsertPos << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001011 Worklist.push_back(std::make_pair(Clone, Incoming));
1012 }
1013 }
1014 // Erase the original call.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001015 LLVM_DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001016 EraseInstruction(CInst);
1017 continue;
1018 }
1019 }
1020 } while (!Worklist.empty());
1021 }
1022}
1023
Michael Gottesman323964c2013-04-18 05:39:45 +00001024/// If we have a top down pointer in the S_Use state, make sure that there are
1025/// no CFG hazards by checking the states of various bottom up pointers.
1026static void CheckForUseCFGHazard(const Sequence SuccSSeq,
1027 const bool SuccSRRIKnownSafe,
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001028 TopDownPtrState &S,
Michael Gottesman323964c2013-04-18 05:39:45 +00001029 bool &SomeSuccHasSame,
1030 bool &AllSuccsHaveSame,
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001031 bool &NotAllSeqEqualButKnownSafe,
Michael Gottesman323964c2013-04-18 05:39:45 +00001032 bool &ShouldContinue) {
1033 switch (SuccSSeq) {
1034 case S_CanRelease: {
Michael Gottesman93132252013-06-21 06:59:02 +00001035 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe) {
Michael Gottesman323964c2013-04-18 05:39:45 +00001036 S.ClearSequenceProgress();
1037 break;
1038 }
Michael Gottesman2f294592013-06-21 19:12:36 +00001039 S.SetCFGHazardAfflicted(true);
Michael Gottesman323964c2013-04-18 05:39:45 +00001040 ShouldContinue = true;
1041 break;
1042 }
1043 case S_Use:
1044 SomeSuccHasSame = true;
1045 break;
1046 case S_Stop:
1047 case S_Release:
1048 case S_MovableRelease:
Michael Gottesman93132252013-06-21 06:59:02 +00001049 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe)
Michael Gottesman323964c2013-04-18 05:39:45 +00001050 AllSuccsHaveSame = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001051 else
1052 NotAllSeqEqualButKnownSafe = true;
Michael Gottesman323964c2013-04-18 05:39:45 +00001053 break;
1054 case S_Retain:
1055 llvm_unreachable("bottom-up pointer in retain state!");
1056 case S_None:
1057 llvm_unreachable("This should have been handled earlier.");
1058 }
1059}
1060
1061/// If we have a Top Down pointer in the S_CanRelease state, make sure that
1062/// there are no CFG hazards by checking the states of various bottom up
1063/// pointers.
1064static void CheckForCanReleaseCFGHazard(const Sequence SuccSSeq,
1065 const bool SuccSRRIKnownSafe,
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001066 TopDownPtrState &S,
Michael Gottesman323964c2013-04-18 05:39:45 +00001067 bool &SomeSuccHasSame,
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001068 bool &AllSuccsHaveSame,
1069 bool &NotAllSeqEqualButKnownSafe) {
Michael Gottesman323964c2013-04-18 05:39:45 +00001070 switch (SuccSSeq) {
1071 case S_CanRelease:
1072 SomeSuccHasSame = true;
1073 break;
1074 case S_Stop:
1075 case S_Release:
1076 case S_MovableRelease:
1077 case S_Use:
Michael Gottesman93132252013-06-21 06:59:02 +00001078 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe)
Michael Gottesman323964c2013-04-18 05:39:45 +00001079 AllSuccsHaveSame = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001080 else
1081 NotAllSeqEqualButKnownSafe = true;
Michael Gottesman323964c2013-04-18 05:39:45 +00001082 break;
1083 case S_Retain:
1084 llvm_unreachable("bottom-up pointer in retain state!");
1085 case S_None:
1086 llvm_unreachable("This should have been handled earlier.");
1087 }
1088}
1089
Michael Gottesman97e3df02013-01-14 00:35:14 +00001090/// Check for critical edges, loop boundaries, irreducible control flow, or
1091/// other CFG structures where moving code across the edge would result in it
1092/// being executed more.
John McCalld935e9c2011-06-15 23:37:01 +00001093void
1094ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
1095 DenseMap<const BasicBlock *, BBState> &BBStates,
1096 BBState &MyStates) const {
1097 // If any top-down local-use or possible-dec has a succ which is earlier in
1098 // the sequence, forget it.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001099 for (auto I = MyStates.top_down_ptr_begin(), E = MyStates.top_down_ptr_end();
1100 I != E; ++I) {
1101 TopDownPtrState &S = I->second;
Michael Gottesman323964c2013-04-18 05:39:45 +00001102 const Sequence Seq = I->second.GetSeq();
Dan Gohman0155f302012-02-17 18:59:53 +00001103
Michael Gottesman323964c2013-04-18 05:39:45 +00001104 // We only care about S_Retain, S_CanRelease, and S_Use.
1105 if (Seq == S_None)
1106 continue;
Dan Gohman0155f302012-02-17 18:59:53 +00001107
Michael Gottesman323964c2013-04-18 05:39:45 +00001108 // Make sure that if extra top down states are added in the future that this
1109 // code is updated to handle it.
1110 assert((Seq == S_Retain || Seq == S_CanRelease || Seq == S_Use) &&
1111 "Unknown top down sequence state.");
1112
1113 const Value *Arg = I->first;
Michael Gottesman323964c2013-04-18 05:39:45 +00001114 bool SomeSuccHasSame = false;
1115 bool AllSuccsHaveSame = true;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001116 bool NotAllSeqEqualButKnownSafe = false;
Michael Gottesman323964c2013-04-18 05:39:45 +00001117
Chandler Carruthc1e3ee22018-10-18 00:38:34 +00001118 for (const BasicBlock *Succ : successors(BB)) {
Michael Gottesman323964c2013-04-18 05:39:45 +00001119 // If VisitBottomUp has pointer information for this successor, take
1120 // what we know about it.
1121 const DenseMap<const BasicBlock *, BBState>::iterator BBI =
Chandler Carruthc1e3ee22018-10-18 00:38:34 +00001122 BBStates.find(Succ);
Michael Gottesman323964c2013-04-18 05:39:45 +00001123 assert(BBI != BBStates.end());
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001124 const BottomUpPtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
Michael Gottesman323964c2013-04-18 05:39:45 +00001125 const Sequence SuccSSeq = SuccS.GetSeq();
1126
1127 // If bottom up, the pointer is in an S_None state, clear the sequence
1128 // progress since the sequence in the bottom up state finished
1129 // suggesting a mismatch in between retains/releases. This is true for
1130 // all three cases that we are handling here: S_Retain, S_Use, and
1131 // S_CanRelease.
1132 if (SuccSSeq == S_None) {
Dan Gohman12130272011-08-12 00:26:31 +00001133 S.ClearSequenceProgress();
Michael Gottesman323964c2013-04-18 05:39:45 +00001134 continue;
1135 }
1136
1137 // If we have S_Use or S_CanRelease, perform our check for cfg hazard
1138 // checks.
Michael Gottesman93132252013-06-21 06:59:02 +00001139 const bool SuccSRRIKnownSafe = SuccS.IsKnownSafe();
Michael Gottesman323964c2013-04-18 05:39:45 +00001140
1141 // *NOTE* We do not use Seq from above here since we are allowing for
1142 // S.GetSeq() to change while we are visiting basic blocks.
1143 switch(S.GetSeq()) {
1144 case S_Use: {
1145 bool ShouldContinue = false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001146 CheckForUseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S, SomeSuccHasSame,
1147 AllSuccsHaveSame, NotAllSeqEqualButKnownSafe,
Michael Gottesman323964c2013-04-18 05:39:45 +00001148 ShouldContinue);
1149 if (ShouldContinue)
1150 continue;
1151 break;
1152 }
Eugene Zelenko57bd5a02017-10-27 01:09:08 +00001153 case S_CanRelease:
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001154 CheckForCanReleaseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S,
1155 SomeSuccHasSame, AllSuccsHaveSame,
1156 NotAllSeqEqualButKnownSafe);
Michael Gottesman323964c2013-04-18 05:39:45 +00001157 break;
Michael Gottesman323964c2013-04-18 05:39:45 +00001158 case S_Retain:
1159 case S_None:
1160 case S_Stop:
1161 case S_Release:
1162 case S_MovableRelease:
1163 break;
1164 }
John McCalld935e9c2011-06-15 23:37:01 +00001165 }
Michael Gottesman323964c2013-04-18 05:39:45 +00001166
1167 // If the state at the other end of any of the successor edges
1168 // matches the current state, require all edges to match. This
1169 // guards against loops in the middle of a sequence.
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001170 if (SomeSuccHasSame && !AllSuccsHaveSame) {
Michael Gottesman323964c2013-04-18 05:39:45 +00001171 S.ClearSequenceProgress();
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001172 } else if (NotAllSeqEqualButKnownSafe) {
1173 // If we would have cleared the state foregoing the fact that we are known
1174 // safe, stop code motion. This is because whether or not it is safe to
1175 // remove RR pairs via KnownSafe is an orthogonal concept to whether we
1176 // are allowed to perform code motion.
Michael Gottesman2f294592013-06-21 19:12:36 +00001177 S.SetCFGHazardAfflicted(true);
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001178 }
Michael Gottesman323964c2013-04-18 05:39:45 +00001179 }
John McCalld935e9c2011-06-15 23:37:01 +00001180}
1181
Michael Gottesman0be69202015-03-05 23:28:58 +00001182bool ObjCARCOpt::VisitInstructionBottomUp(
1183 Instruction *Inst, BasicBlock *BB, BlotMapVector<Value *, RRInfo> &Retains,
1184 BBState &MyStates) {
Dan Gohman817a7c62012-03-22 18:24:56 +00001185 bool NestingDetected = false;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001186 ARCInstKind Class = GetARCInstKind(Inst);
Craig Topperf40110f2014-04-25 05:29:35 +00001187 const Value *Arg = nullptr;
Michael Gottesman79249972013-04-05 23:46:45 +00001188
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001189 LLVM_DEBUG(dbgs() << " Class: " << Class << "\n");
Michael Gottesman79249972013-04-05 23:46:45 +00001190
Dan Gohman817a7c62012-03-22 18:24:56 +00001191 switch (Class) {
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001192 case ARCInstKind::Release: {
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001193 Arg = GetArgRCIdentityRoot(Inst);
Dan Gohman817a7c62012-03-22 18:24:56 +00001194
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001195 BottomUpPtrState &S = MyStates.getPtrBottomUpState(Arg);
Michael Gottesman4eae3962015-03-06 00:34:39 +00001196 NestingDetected |= S.InitBottomUp(MDKindCache, Inst);
Dan Gohman817a7c62012-03-22 18:24:56 +00001197 break;
1198 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001199 case ARCInstKind::RetainBlock:
Michael Gottesman158fdf62013-03-28 20:11:19 +00001200 // In OptimizeIndividualCalls, we have strength reduced all optimizable
1201 // objc_retainBlocks to objc_retains. Thus at this point any
1202 // objc_retainBlocks that we see are not optimizable.
1203 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001204 case ARCInstKind::Retain:
1205 case ARCInstKind::RetainRV: {
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001206 Arg = GetArgRCIdentityRoot(Inst);
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001207 BottomUpPtrState &S = MyStates.getPtrBottomUpState(Arg);
Michael Gottesman60805962015-03-06 00:34:42 +00001208 if (S.MatchWithRetain()) {
1209 // Don't do retain+release tracking for ARCInstKind::RetainRV, because
1210 // it's better to let it remain as the first instruction after a call.
Michael Gottesmanc01ab512015-03-16 07:02:39 +00001211 if (Class != ARCInstKind::RetainRV) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001212 LLVM_DEBUG(dbgs() << " Matching with: " << *Inst << "\n");
Michael Gottesmane3943d02013-06-21 19:44:30 +00001213 Retains[Inst] = S.GetRRInfo();
Michael Gottesmanc01ab512015-03-16 07:02:39 +00001214 }
Dan Gohman817a7c62012-03-22 18:24:56 +00001215 S.ClearSequenceProgress();
Dan Gohman817a7c62012-03-22 18:24:56 +00001216 }
Michael Gottesman31ba23a2013-04-05 22:54:32 +00001217 // A retain moving bottom up can be a use.
1218 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001219 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001220 case ARCInstKind::AutoreleasepoolPop:
Dan Gohman817a7c62012-03-22 18:24:56 +00001221 // Conservatively, clear MyStates for all known pointers.
1222 MyStates.clearBottomUpPointers();
1223 return NestingDetected;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001224 case ARCInstKind::AutoreleasepoolPush:
1225 case ARCInstKind::None:
Dan Gohman817a7c62012-03-22 18:24:56 +00001226 // These are irrelevant.
1227 return NestingDetected;
1228 default:
1229 break;
1230 }
1231
1232 // Consider any other possible effects of this instruction on each
1233 // pointer being tracked.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001234 for (auto MI = MyStates.bottom_up_ptr_begin(),
1235 ME = MyStates.bottom_up_ptr_end();
1236 MI != ME; ++MI) {
Dan Gohman817a7c62012-03-22 18:24:56 +00001237 const Value *Ptr = MI->first;
1238 if (Ptr == Arg)
1239 continue; // Handled above.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001240 BottomUpPtrState &S = MI->second;
Dan Gohman817a7c62012-03-22 18:24:56 +00001241
Michael Gottesman16e6a202015-03-06 02:07:12 +00001242 if (S.HandlePotentialAlterRefCount(Inst, Ptr, PA, Class))
1243 continue;
Dan Gohman817a7c62012-03-22 18:24:56 +00001244
Michael Gottesman16e6a202015-03-06 02:07:12 +00001245 S.HandlePotentialUse(BB, Inst, Ptr, PA, Class);
Dan Gohman817a7c62012-03-22 18:24:56 +00001246 }
1247
1248 return NestingDetected;
1249}
1250
Michael Gottesman0be69202015-03-05 23:28:58 +00001251bool ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
1252 DenseMap<const BasicBlock *, BBState> &BBStates,
1253 BlotMapVector<Value *, RRInfo> &Retains) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001254 LLVM_DEBUG(dbgs() << "\n== ObjCARCOpt::VisitBottomUp ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00001255
John McCalld935e9c2011-06-15 23:37:01 +00001256 bool NestingDetected = false;
1257 BBState &MyStates = BBStates[BB];
1258
1259 // Merge the states from each successor to compute the initial state
1260 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00001261 BBState::edge_iterator SI(MyStates.succ_begin()),
1262 SE(MyStates.succ_end());
1263 if (SI != SE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001264 const BasicBlock *Succ = *SI;
1265 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
1266 assert(I != BBStates.end());
1267 MyStates.InitFromSucc(I->second);
1268 ++SI;
1269 for (; SI != SE; ++SI) {
1270 Succ = *SI;
1271 I = BBStates.find(Succ);
1272 assert(I != BBStates.end());
1273 MyStates.MergeSucc(I->second);
1274 }
Michael Gottesman60f6b282013-03-29 05:13:07 +00001275 }
Michael Gottesmancd4de0f2013-03-26 00:42:09 +00001276
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001277 LLVM_DEBUG(dbgs() << "Before:\n"
1278 << BBStates[BB] << "\n"
1279 << "Performing Dataflow:\n");
Michael Gottesmanc01ab512015-03-16 07:02:39 +00001280
John McCalld935e9c2011-06-15 23:37:01 +00001281 // Visit all the instructions, bottom-up.
1282 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +00001283 Instruction *Inst = &*std::prev(I);
Dan Gohman5c70fad2012-03-23 17:47:54 +00001284
1285 // Invoke instructions are visited as part of their successors (below).
1286 if (isa<InvokeInst>(Inst))
1287 continue;
1288
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001289 LLVM_DEBUG(dbgs() << " Visiting " << *Inst << "\n");
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001290
Dan Gohman5c70fad2012-03-23 17:47:54 +00001291 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
Akira Hatanaka8edf8f32019-04-25 19:42:55 +00001292
1293 // Bail out if the number of pointers being tracked becomes too large so
1294 // that this pass can complete in a reasonable amount of time.
1295 if (MyStates.bottom_up_ptr_list_size() > MaxPtrStates) {
1296 DisableRetainReleasePairing = true;
1297 return false;
1298 }
Dan Gohman5c70fad2012-03-23 17:47:54 +00001299 }
1300
Dan Gohmandae33492012-04-27 18:56:31 +00001301 // If there's a predecessor with an invoke, visit the invoke as if it were
1302 // part of this block, since we can't insert code after an invoke in its own
1303 // block, and we don't want to split critical edges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001304 for (BBState::edge_iterator PI(MyStates.pred_begin()),
1305 PE(MyStates.pred_end()); PI != PE; ++PI) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00001306 BasicBlock *Pred = *PI;
Dan Gohmandae33492012-04-27 18:56:31 +00001307 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
1308 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
Dan Gohman817a7c62012-03-22 18:24:56 +00001309 }
John McCalld935e9c2011-06-15 23:37:01 +00001310
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001311 LLVM_DEBUG(dbgs() << "\nFinal State:\n" << BBStates[BB] << "\n");
Michael Gottesmanc01ab512015-03-16 07:02:39 +00001312
Dan Gohman817a7c62012-03-22 18:24:56 +00001313 return NestingDetected;
1314}
John McCalld935e9c2011-06-15 23:37:01 +00001315
Dan Gohman817a7c62012-03-22 18:24:56 +00001316bool
1317ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
1318 DenseMap<Value *, RRInfo> &Releases,
1319 BBState &MyStates) {
1320 bool NestingDetected = false;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001321 ARCInstKind Class = GetARCInstKind(Inst);
Craig Topperf40110f2014-04-25 05:29:35 +00001322 const Value *Arg = nullptr;
John McCalld935e9c2011-06-15 23:37:01 +00001323
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001324 LLVM_DEBUG(dbgs() << " Class: " << Class << "\n");
Michael Gottesmanc01ab512015-03-16 07:02:39 +00001325
Dan Gohman817a7c62012-03-22 18:24:56 +00001326 switch (Class) {
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001327 case ARCInstKind::RetainBlock:
Michael Gottesman158fdf62013-03-28 20:11:19 +00001328 // In OptimizeIndividualCalls, we have strength reduced all optimizable
1329 // objc_retainBlocks to objc_retains. Thus at this point any
Michael Gottesman60805962015-03-06 00:34:42 +00001330 // objc_retainBlocks that we see are not optimizable. We need to break since
1331 // a retain can be a potential use.
Michael Gottesman158fdf62013-03-28 20:11:19 +00001332 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001333 case ARCInstKind::Retain:
1334 case ARCInstKind::RetainRV: {
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001335 Arg = GetArgRCIdentityRoot(Inst);
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001336 TopDownPtrState &S = MyStates.getPtrTopDownState(Arg);
Michael Gottesman4eae3962015-03-06 00:34:39 +00001337 NestingDetected |= S.InitTopDown(Class, Inst);
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001338 // A retain can be a potential use; proceed to the generic checking
Dan Gohmanf64ff8e2012-07-23 19:27:31 +00001339 // code below.
1340 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00001341 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001342 case ARCInstKind::Release: {
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001343 Arg = GetArgRCIdentityRoot(Inst);
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001344 TopDownPtrState &S = MyStates.getPtrTopDownState(Arg);
Michael Gottesman60805962015-03-06 00:34:42 +00001345 // Try to form a tentative pair in between this release instruction and the
1346 // top down pointers that we are tracking.
1347 if (S.MatchWithRelease(MDKindCache, Inst)) {
1348 // If we succeed, copy S's RRInfo into the Release -> {Retain Set
1349 // Map}. Then we clear S.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001350 LLVM_DEBUG(dbgs() << " Matching with: " << *Inst << "\n");
Michael Gottesmane3943d02013-06-21 19:44:30 +00001351 Releases[Inst] = S.GetRRInfo();
Dan Gohman817a7c62012-03-22 18:24:56 +00001352 S.ClearSequenceProgress();
Dan Gohman817a7c62012-03-22 18:24:56 +00001353 }
1354 break;
1355 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001356 case ARCInstKind::AutoreleasepoolPop:
Dan Gohman817a7c62012-03-22 18:24:56 +00001357 // Conservatively, clear MyStates for all known pointers.
1358 MyStates.clearTopDownPointers();
Michael Gottesman60805962015-03-06 00:34:42 +00001359 return false;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001360 case ARCInstKind::AutoreleasepoolPush:
1361 case ARCInstKind::None:
Michael Gottesman60805962015-03-06 00:34:42 +00001362 // These can not be uses of
1363 return false;
Dan Gohman817a7c62012-03-22 18:24:56 +00001364 default:
1365 break;
1366 }
1367
1368 // Consider any other possible effects of this instruction on each
1369 // pointer being tracked.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001370 for (auto MI = MyStates.top_down_ptr_begin(),
1371 ME = MyStates.top_down_ptr_end();
1372 MI != ME; ++MI) {
Dan Gohman817a7c62012-03-22 18:24:56 +00001373 const Value *Ptr = MI->first;
1374 if (Ptr == Arg)
1375 continue; // Handled above.
Michael Gottesmanfeb138e2015-03-06 00:34:36 +00001376 TopDownPtrState &S = MI->second;
Michael Gottesman16e6a202015-03-06 02:07:12 +00001377 if (S.HandlePotentialAlterRefCount(Inst, Ptr, PA, Class))
1378 continue;
Dan Gohman817a7c62012-03-22 18:24:56 +00001379
Michael Gottesman16e6a202015-03-06 02:07:12 +00001380 S.HandlePotentialUse(Inst, Ptr, PA, Class);
John McCalld935e9c2011-06-15 23:37:01 +00001381 }
1382
1383 return NestingDetected;
1384}
1385
1386bool
1387ObjCARCOpt::VisitTopDown(BasicBlock *BB,
1388 DenseMap<const BasicBlock *, BBState> &BBStates,
1389 DenseMap<Value *, RRInfo> &Releases) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001390 LLVM_DEBUG(dbgs() << "\n== ObjCARCOpt::VisitTopDown ==\n");
John McCalld935e9c2011-06-15 23:37:01 +00001391 bool NestingDetected = false;
1392 BBState &MyStates = BBStates[BB];
1393
1394 // Merge the states from each predecessor to compute the initial state
1395 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00001396 BBState::edge_iterator PI(MyStates.pred_begin()),
1397 PE(MyStates.pred_end());
1398 if (PI != PE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001399 const BasicBlock *Pred = *PI;
1400 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
1401 assert(I != BBStates.end());
1402 MyStates.InitFromPred(I->second);
1403 ++PI;
1404 for (; PI != PE; ++PI) {
1405 Pred = *PI;
1406 I = BBStates.find(Pred);
1407 assert(I != BBStates.end());
1408 MyStates.MergePred(I->second);
1409 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001410 }
John McCalld935e9c2011-06-15 23:37:01 +00001411
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001412 LLVM_DEBUG(dbgs() << "Before:\n"
1413 << BBStates[BB] << "\n"
1414 << "Performing Dataflow:\n");
Michael Gottesmanc01ab512015-03-16 07:02:39 +00001415
John McCalld935e9c2011-06-15 23:37:01 +00001416 // Visit all the instructions, top-down.
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +00001417 for (Instruction &Inst : *BB) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001418 LLVM_DEBUG(dbgs() << " Visiting " << Inst << "\n");
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00001419
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +00001420 NestingDetected |= VisitInstructionTopDown(&Inst, Releases, MyStates);
Akira Hatanaka8edf8f32019-04-25 19:42:55 +00001421
1422 // Bail out if the number of pointers being tracked becomes too large so
1423 // that this pass can complete in a reasonable amount of time.
1424 if (MyStates.top_down_ptr_list_size() > MaxPtrStates) {
1425 DisableRetainReleasePairing = true;
1426 return false;
1427 }
John McCalld935e9c2011-06-15 23:37:01 +00001428 }
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00001429
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001430 LLVM_DEBUG(dbgs() << "\nState Before Checking for CFG Hazards:\n"
1431 << BBStates[BB] << "\n\n");
John McCalld935e9c2011-06-15 23:37:01 +00001432 CheckForCFGHazards(BB, BBStates, MyStates);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001433 LLVM_DEBUG(dbgs() << "Final State:\n" << BBStates[BB] << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001434 return NestingDetected;
1435}
1436
Dan Gohmana53a12c2011-12-12 19:42:25 +00001437static void
1438ComputePostOrders(Function &F,
1439 SmallVectorImpl<BasicBlock *> &PostOrder,
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001440 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
1441 unsigned NoObjCARCExceptionsMDKind,
1442 DenseMap<const BasicBlock *, BBState> &BBStates) {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001443 /// The visited set, for doing DFS walks.
Dan Gohmana53a12c2011-12-12 19:42:25 +00001444 SmallPtrSet<BasicBlock *, 16> Visited;
1445
1446 // Do DFS, computing the PostOrder.
1447 SmallPtrSet<BasicBlock *, 16> OnStack;
1448 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001449
1450 // Functions always have exactly one entry block, and we don't have
1451 // any other block that we treat like an entry block.
Dan Gohmana53a12c2011-12-12 19:42:25 +00001452 BasicBlock *EntryBB = &F.getEntryBlock();
Dan Gohman41375a32012-05-08 23:39:44 +00001453 BBState &MyStates = BBStates[EntryBB];
1454 MyStates.SetAsEntry();
Chandler Carruthc1e3ee22018-10-18 00:38:34 +00001455 Instruction *EntryTI = EntryBB->getTerminator();
Dan Gohman41375a32012-05-08 23:39:44 +00001456 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
Dan Gohmana53a12c2011-12-12 19:42:25 +00001457 Visited.insert(EntryBB);
1458 OnStack.insert(EntryBB);
1459 do {
1460 dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001461 BasicBlock *CurrBB = SuccStack.back().first;
Chandler Carruthc1e3ee22018-10-18 00:38:34 +00001462 succ_iterator SE(CurrBB->getTerminator(), false);
Dan Gohman41375a32012-05-08 23:39:44 +00001463
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001464 while (SuccStack.back().second != SE) {
1465 BasicBlock *SuccBB = *SuccStack.back().second++;
David Blaikie70573dc2014-11-19 07:49:26 +00001466 if (Visited.insert(SuccBB).second) {
Chandler Carruthc1e3ee22018-10-18 00:38:34 +00001467 SuccStack.push_back(
1468 std::make_pair(SuccBB, succ_iterator(SuccBB->getTerminator())));
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001469 BBStates[CurrBB].addSucc(SuccBB);
Dan Gohman41375a32012-05-08 23:39:44 +00001470 BBState &SuccStates = BBStates[SuccBB];
1471 SuccStates.addPred(CurrBB);
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001472 OnStack.insert(SuccBB);
Dan Gohmana53a12c2011-12-12 19:42:25 +00001473 goto dfs_next_succ;
1474 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001475
1476 if (!OnStack.count(SuccBB)) {
1477 BBStates[CurrBB].addSucc(SuccBB);
1478 BBStates[SuccBB].addPred(CurrBB);
1479 }
Dan Gohmana53a12c2011-12-12 19:42:25 +00001480 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001481 OnStack.erase(CurrBB);
1482 PostOrder.push_back(CurrBB);
1483 SuccStack.pop_back();
Dan Gohmana53a12c2011-12-12 19:42:25 +00001484 } while (!SuccStack.empty());
1485
1486 Visited.clear();
1487
Dan Gohmana53a12c2011-12-12 19:42:25 +00001488 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001489 // Functions may have many exits, and there also blocks which we treat
1490 // as exits due to ignored edges.
1491 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +00001492 for (BasicBlock &ExitBB : F) {
1493 BBState &MyStates = BBStates[&ExitBB];
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001494 if (!MyStates.isExit())
1495 continue;
1496
Dan Gohmandae33492012-04-27 18:56:31 +00001497 MyStates.SetAsExit();
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001498
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +00001499 PredStack.push_back(std::make_pair(&ExitBB, MyStates.pred_begin()));
1500 Visited.insert(&ExitBB);
Dan Gohmana53a12c2011-12-12 19:42:25 +00001501 while (!PredStack.empty()) {
1502 reverse_dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001503 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
1504 while (PredStack.back().second != PE) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00001505 BasicBlock *BB = *PredStack.back().second++;
David Blaikie70573dc2014-11-19 07:49:26 +00001506 if (Visited.insert(BB).second) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001507 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00001508 goto reverse_dfs_next_succ;
1509 }
1510 }
1511 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
1512 }
1513 }
1514}
1515
Michael Gottesman97e3df02013-01-14 00:35:14 +00001516// Visit the function both top-down and bottom-up.
Michael Gottesman0be69202015-03-05 23:28:58 +00001517bool ObjCARCOpt::Visit(Function &F,
1518 DenseMap<const BasicBlock *, BBState> &BBStates,
1519 BlotMapVector<Value *, RRInfo> &Retains,
1520 DenseMap<Value *, RRInfo> &Releases) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00001521 // Use reverse-postorder traversals, because we magically know that loops
1522 // will be well behaved, i.e. they won't repeatedly call retain on a single
1523 // pointer without doing a release. We can't use the ReversePostOrderTraversal
1524 // class here because we want the reverse-CFG postorder to consider each
1525 // function exit point, and we want to ignore selected cycle edges.
1526 SmallVector<BasicBlock *, 16> PostOrder;
1527 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001528 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
Michael Gottesman65cb7372015-03-16 07:02:27 +00001529 MDKindCache.get(ARCMDKindID::NoObjCARCExceptions),
1530 BBStates);
Dan Gohmana53a12c2011-12-12 19:42:25 +00001531
1532 // Use reverse-postorder on the reverse CFG for bottom-up.
John McCalld935e9c2011-06-15 23:37:01 +00001533 bool BottomUpNestingDetected = false;
Akira Hatanaka8edf8f32019-04-25 19:42:55 +00001534 for (BasicBlock *BB : llvm::reverse(ReverseCFGPostOrder)) {
David Majnemerd7708772016-06-24 04:05:21 +00001535 BottomUpNestingDetected |= VisitBottomUp(BB, BBStates, Retains);
Akira Hatanaka8edf8f32019-04-25 19:42:55 +00001536 if (DisableRetainReleasePairing)
1537 return false;
1538 }
John McCalld935e9c2011-06-15 23:37:01 +00001539
Dan Gohmana53a12c2011-12-12 19:42:25 +00001540 // Use reverse-postorder for top-down.
John McCalld935e9c2011-06-15 23:37:01 +00001541 bool TopDownNestingDetected = false;
Akira Hatanaka8edf8f32019-04-25 19:42:55 +00001542 for (BasicBlock *BB : llvm::reverse(PostOrder)) {
David Majnemerd7708772016-06-24 04:05:21 +00001543 TopDownNestingDetected |= VisitTopDown(BB, BBStates, Releases);
Akira Hatanaka8edf8f32019-04-25 19:42:55 +00001544 if (DisableRetainReleasePairing)
1545 return false;
1546 }
John McCalld935e9c2011-06-15 23:37:01 +00001547
1548 return TopDownNestingDetected && BottomUpNestingDetected;
1549}
1550
Michael Gottesman97e3df02013-01-14 00:35:14 +00001551/// Move the calls in RetainsToMove and ReleasesToMove.
Michael Gottesman0be69202015-03-05 23:28:58 +00001552void ObjCARCOpt::MoveCalls(Value *Arg, RRInfo &RetainsToMove,
John McCalld935e9c2011-06-15 23:37:01 +00001553 RRInfo &ReleasesToMove,
Michael Gottesman0be69202015-03-05 23:28:58 +00001554 BlotMapVector<Value *, RRInfo> &Retains,
John McCalld935e9c2011-06-15 23:37:01 +00001555 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman6320f522011-07-22 22:29:21 +00001556 SmallVectorImpl<Instruction *> &DeadInsts,
Michael Gottesman79249972013-04-05 23:46:45 +00001557 Module *M) {
Chris Lattner229907c2011-07-18 04:54:35 +00001558 Type *ArgTy = Arg->getType();
Dan Gohman6320f522011-07-22 22:29:21 +00001559 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
Michael Gottesman79249972013-04-05 23:46:45 +00001560
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001561 LLVM_DEBUG(dbgs() << "== ObjCARCOpt::MoveCalls ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00001562
John McCalld935e9c2011-06-15 23:37:01 +00001563 // Insert the new retain and release calls.
Craig Topper46276792014-08-24 23:23:06 +00001564 for (Instruction *InsertPt : ReleasesToMove.ReverseInsertPts) {
John McCalld935e9c2011-06-15 23:37:01 +00001565 Value *MyArg = ArgTy == ParamTy ? Arg :
1566 new BitCastInst(Arg, ParamTy, "", InsertPt);
James Y Knight7976eb52019-02-01 20:43:25 +00001567 Function *Decl = EP.get(ARCRuntimeEntryPointKind::Retain);
Michael Gottesman14acfac2013-07-06 01:39:23 +00001568 CallInst *Call = CallInst::Create(Decl, MyArg, "", InsertPt);
John McCalld935e9c2011-06-15 23:37:01 +00001569 Call->setDoesNotThrow();
Michael Gottesmanba648592013-03-28 23:08:44 +00001570 Call->setTailCall();
Michael Gottesman60f6b282013-03-29 05:13:07 +00001571
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001572 LLVM_DEBUG(dbgs() << "Inserting new Retain: " << *Call
1573 << "\n"
1574 "At insertion point: "
1575 << *InsertPt << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001576 }
Craig Topper46276792014-08-24 23:23:06 +00001577 for (Instruction *InsertPt : RetainsToMove.ReverseInsertPts) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00001578 Value *MyArg = ArgTy == ParamTy ? Arg :
1579 new BitCastInst(Arg, ParamTy, "", InsertPt);
James Y Knight7976eb52019-02-01 20:43:25 +00001580 Function *Decl = EP.get(ARCRuntimeEntryPointKind::Release);
Michael Gottesman14acfac2013-07-06 01:39:23 +00001581 CallInst *Call = CallInst::Create(Decl, MyArg, "", InsertPt);
Dan Gohman5c70fad2012-03-23 17:47:54 +00001582 // Attach a clang.imprecise_release metadata tag, if appropriate.
1583 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
Michael Gottesman65cb7372015-03-16 07:02:27 +00001584 Call->setMetadata(MDKindCache.get(ARCMDKindID::ImpreciseRelease), M);
Dan Gohman5c70fad2012-03-23 17:47:54 +00001585 Call->setDoesNotThrow();
1586 if (ReleasesToMove.IsTailCallRelease)
1587 Call->setTailCall();
Michael Gottesmanc189a392013-01-09 19:23:24 +00001588
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001589 LLVM_DEBUG(dbgs() << "Inserting new Release: " << *Call
1590 << "\n"
1591 "At insertion point: "
1592 << *InsertPt << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001593 }
1594
1595 // Delete the original retain and release calls.
Craig Topper46276792014-08-24 23:23:06 +00001596 for (Instruction *OrigRetain : RetainsToMove.Calls) {
John McCalld935e9c2011-06-15 23:37:01 +00001597 Retains.blot(OrigRetain);
1598 DeadInsts.push_back(OrigRetain);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001599 LLVM_DEBUG(dbgs() << "Deleting retain: " << *OrigRetain << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001600 }
Craig Topper46276792014-08-24 23:23:06 +00001601 for (Instruction *OrigRelease : ReleasesToMove.Calls) {
John McCalld935e9c2011-06-15 23:37:01 +00001602 Releases.erase(OrigRelease);
1603 DeadInsts.push_back(OrigRelease);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001604 LLVM_DEBUG(dbgs() << "Deleting release: " << *OrigRelease << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001605 }
1606}
1607
Michael Gottesman67792172015-03-16 07:02:30 +00001608bool ObjCARCOpt::PairUpRetainsAndReleases(
Michael Gottesman0be69202015-03-05 23:28:58 +00001609 DenseMap<const BasicBlock *, BBState> &BBStates,
1610 BlotMapVector<Value *, RRInfo> &Retains,
1611 DenseMap<Value *, RRInfo> &Releases, Module *M,
Akira Hatanaka2b882052017-02-25 00:53:38 +00001612 Instruction *Retain,
Michael Gottesman0be69202015-03-05 23:28:58 +00001613 SmallVectorImpl<Instruction *> &DeadInsts, RRInfo &RetainsToMove,
1614 RRInfo &ReleasesToMove, Value *Arg, bool KnownSafe,
1615 bool &AnyPairsCompletelyEliminated) {
Michael Gottesman9de6f962013-01-22 21:49:00 +00001616 // If a pair happens in a region where it is known that the reference count
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001617 // is already incremented, we can similarly ignore possible decrements unless
1618 // we are dealing with a retainable object with multiple provenance sources.
Michael Gottesman9de6f962013-01-22 21:49:00 +00001619 bool KnownSafeTD = true, KnownSafeBU = true;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001620 bool CFGHazardAfflicted = false;
Michael Gottesman9de6f962013-01-22 21:49:00 +00001621
1622 // Connect the dots between the top-down-collected RetainsToMove and
1623 // bottom-up-collected ReleasesToMove to form sets of related calls.
1624 // This is an iterative process so that we connect multiple releases
1625 // to multiple retains if needed.
1626 unsigned OldDelta = 0;
1627 unsigned NewDelta = 0;
1628 unsigned OldCount = 0;
1629 unsigned NewCount = 0;
1630 bool FirstRelease = true;
Akira Hatanaka2b882052017-02-25 00:53:38 +00001631 for (SmallVector<Instruction *, 4> NewRetains{Retain};;) {
1632 SmallVector<Instruction *, 4> NewReleases;
Benjamin Kramer135f7352016-06-26 12:28:59 +00001633 for (Instruction *NewRetain : NewRetains) {
Michael Gottesman6ff10c92015-03-06 02:10:03 +00001634 auto It = Retains.find(NewRetain);
Michael Gottesman9de6f962013-01-22 21:49:00 +00001635 assert(It != Retains.end());
1636 const RRInfo &NewRetainRRI = It->second;
1637 KnownSafeTD &= NewRetainRRI.KnownSafe;
Shoaib Meenai074728a2018-05-16 04:52:18 +00001638 CFGHazardAfflicted |= NewRetainRRI.CFGHazardAfflicted;
Craig Topper46276792014-08-24 23:23:06 +00001639 for (Instruction *NewRetainRelease : NewRetainRRI.Calls) {
Michael Gottesman6ff10c92015-03-06 02:10:03 +00001640 auto Jt = Releases.find(NewRetainRelease);
Michael Gottesman9de6f962013-01-22 21:49:00 +00001641 if (Jt == Releases.end())
1642 return false;
1643 const RRInfo &NewRetainReleaseRRI = Jt->second;
Michael Gottesman24b2f6f2013-11-05 16:02:40 +00001644
1645 // If the release does not have a reference to the retain as well,
1646 // something happened which is unaccounted for. Do not do anything.
1647 //
1648 // This can happen if we catch an additive overflow during path count
1649 // merging.
1650 if (!NewRetainReleaseRRI.Calls.count(NewRetain))
1651 return false;
1652
David Blaikie70573dc2014-11-19 07:49:26 +00001653 if (ReleasesToMove.Calls.insert(NewRetainRelease).second) {
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001654 // If we overflow when we compute the path count, don't remove/move
1655 // anything.
1656 const BBState &NRRBBState = BBStates[NewRetainRelease->getParent()];
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00001657 unsigned PathCount = BBState::OverflowOccurredValue;
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001658 if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
1659 return false;
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00001660 assert(PathCount != BBState::OverflowOccurredValue &&
1661 "PathCount at this point can not be "
1662 "OverflowOccurredValue.");
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001663 OldDelta -= PathCount;
Michael Gottesman9de6f962013-01-22 21:49:00 +00001664
1665 // Merge the ReleaseMetadata and IsTailCallRelease values.
1666 if (FirstRelease) {
1667 ReleasesToMove.ReleaseMetadata =
1668 NewRetainReleaseRRI.ReleaseMetadata;
1669 ReleasesToMove.IsTailCallRelease =
1670 NewRetainReleaseRRI.IsTailCallRelease;
1671 FirstRelease = false;
1672 } else {
1673 if (ReleasesToMove.ReleaseMetadata !=
1674 NewRetainReleaseRRI.ReleaseMetadata)
Craig Topperf40110f2014-04-25 05:29:35 +00001675 ReleasesToMove.ReleaseMetadata = nullptr;
Michael Gottesman9de6f962013-01-22 21:49:00 +00001676 if (ReleasesToMove.IsTailCallRelease !=
1677 NewRetainReleaseRRI.IsTailCallRelease)
1678 ReleasesToMove.IsTailCallRelease = false;
1679 }
1680
1681 // Collect the optimal insertion points.
1682 if (!KnownSafe)
Craig Topper46276792014-08-24 23:23:06 +00001683 for (Instruction *RIP : NewRetainReleaseRRI.ReverseInsertPts) {
David Blaikie70573dc2014-11-19 07:49:26 +00001684 if (ReleasesToMove.ReverseInsertPts.insert(RIP).second) {
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001685 // If we overflow when we compute the path count, don't
1686 // remove/move anything.
1687 const BBState &RIPBBState = BBStates[RIP->getParent()];
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00001688 PathCount = BBState::OverflowOccurredValue;
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001689 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
1690 return false;
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00001691 assert(PathCount != BBState::OverflowOccurredValue &&
1692 "PathCount at this point can not be "
1693 "OverflowOccurredValue.");
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001694 NewDelta -= PathCount;
1695 }
Michael Gottesman9de6f962013-01-22 21:49:00 +00001696 }
1697 NewReleases.push_back(NewRetainRelease);
1698 }
1699 }
1700 }
1701 NewRetains.clear();
1702 if (NewReleases.empty()) break;
1703
1704 // Back the other way.
Benjamin Kramer135f7352016-06-26 12:28:59 +00001705 for (Instruction *NewRelease : NewReleases) {
Michael Gottesman6ff10c92015-03-06 02:10:03 +00001706 auto It = Releases.find(NewRelease);
Michael Gottesman9de6f962013-01-22 21:49:00 +00001707 assert(It != Releases.end());
1708 const RRInfo &NewReleaseRRI = It->second;
1709 KnownSafeBU &= NewReleaseRRI.KnownSafe;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001710 CFGHazardAfflicted |= NewReleaseRRI.CFGHazardAfflicted;
Craig Topper46276792014-08-24 23:23:06 +00001711 for (Instruction *NewReleaseRetain : NewReleaseRRI.Calls) {
Michael Gottesman6ff10c92015-03-06 02:10:03 +00001712 auto Jt = Retains.find(NewReleaseRetain);
Michael Gottesman9de6f962013-01-22 21:49:00 +00001713 if (Jt == Retains.end())
1714 return false;
1715 const RRInfo &NewReleaseRetainRRI = Jt->second;
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001716
Michael Gottesman24b2f6f2013-11-05 16:02:40 +00001717 // If the retain does not have a reference to the release as well,
1718 // something happened which is unaccounted for. Do not do anything.
1719 //
1720 // This can happen if we catch an additive overflow during path count
1721 // merging.
1722 if (!NewReleaseRetainRRI.Calls.count(NewRelease))
1723 return false;
1724
David Blaikie70573dc2014-11-19 07:49:26 +00001725 if (RetainsToMove.Calls.insert(NewReleaseRetain).second) {
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001726 // If we overflow when we compute the path count, don't remove/move
1727 // anything.
1728 const BBState &NRRBBState = BBStates[NewReleaseRetain->getParent()];
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00001729 unsigned PathCount = BBState::OverflowOccurredValue;
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001730 if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
1731 return false;
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00001732 assert(PathCount != BBState::OverflowOccurredValue &&
1733 "PathCount at this point can not be "
1734 "OverflowOccurredValue.");
Michael Gottesman9de6f962013-01-22 21:49:00 +00001735 OldDelta += PathCount;
1736 OldCount += PathCount;
1737
Michael Gottesman9de6f962013-01-22 21:49:00 +00001738 // Collect the optimal insertion points.
1739 if (!KnownSafe)
Craig Topper46276792014-08-24 23:23:06 +00001740 for (Instruction *RIP : NewReleaseRetainRRI.ReverseInsertPts) {
David Blaikie70573dc2014-11-19 07:49:26 +00001741 if (RetainsToMove.ReverseInsertPts.insert(RIP).second) {
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001742 // If we overflow when we compute the path count, don't
1743 // remove/move anything.
1744 const BBState &RIPBBState = BBStates[RIP->getParent()];
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00001745
1746 PathCount = BBState::OverflowOccurredValue;
Michael Gottesman9e7261c2013-06-07 06:16:49 +00001747 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
1748 return false;
Michael Gottesmand6ce6cb2013-08-09 23:22:27 +00001749 assert(PathCount != BBState::OverflowOccurredValue &&
1750 "PathCount at this point can not be "
1751 "OverflowOccurredValue.");
Michael Gottesman9de6f962013-01-22 21:49:00 +00001752 NewDelta += PathCount;
1753 NewCount += PathCount;
1754 }
1755 }
1756 NewRetains.push_back(NewReleaseRetain);
1757 }
1758 }
1759 }
Michael Gottesman9de6f962013-01-22 21:49:00 +00001760 if (NewRetains.empty()) break;
1761 }
1762
Michael Gottesmandd60f9b2015-03-16 07:02:36 +00001763 // We can only remove pointers if we are known safe in both directions.
1764 bool UnconditionallySafe = KnownSafeTD && KnownSafeBU;
Michael Gottesmana76143ee2013-05-13 23:49:42 +00001765 if (UnconditionallySafe) {
Michael Gottesman9de6f962013-01-22 21:49:00 +00001766 RetainsToMove.ReverseInsertPts.clear();
1767 ReleasesToMove.ReverseInsertPts.clear();
1768 NewCount = 0;
1769 } else {
1770 // Determine whether the new insertion points we computed preserve the
1771 // balance of retain and release calls through the program.
1772 // TODO: If the fully aggressive solution isn't valid, try to find a
1773 // less aggressive solution which is.
1774 if (NewDelta != 0)
1775 return false;
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001776
1777 // At this point, we are not going to remove any RR pairs, but we still are
1778 // able to move RR pairs. If one of our pointers is afflicted with
1779 // CFGHazards, we cannot perform such code motion so exit early.
Eugene Zelenko57bd5a02017-10-27 01:09:08 +00001780 const bool WillPerformCodeMotion =
1781 !RetainsToMove.ReverseInsertPts.empty() ||
1782 !ReleasesToMove.ReverseInsertPts.empty();
Michael Gottesmane67f40c2013-05-24 20:44:05 +00001783 if (CFGHazardAfflicted && WillPerformCodeMotion)
1784 return false;
Michael Gottesman9de6f962013-01-22 21:49:00 +00001785 }
1786
1787 // Determine whether the original call points are balanced in the retain and
1788 // release calls through the program. If not, conservatively don't touch
1789 // them.
1790 // TODO: It's theoretically possible to do code motion in this case, as
1791 // long as the existing imbalances are maintained.
1792 if (OldDelta != 0)
1793 return false;
Michael Gottesman8005ad32013-04-29 06:16:55 +00001794
Michael Gottesman9de6f962013-01-22 21:49:00 +00001795 Changed = true;
1796 assert(OldCount != 0 && "Unreachable code?");
1797 NumRRs += OldCount - NewCount;
Michael Gottesman9de6f962013-01-22 21:49:00 +00001798 // Set to true if we completely removed any RR pairs.
Michael Gottesman8b5515f2013-01-22 21:53:43 +00001799 AnyPairsCompletelyEliminated = NewCount == 0;
Michael Gottesman9de6f962013-01-22 21:49:00 +00001800
1801 // We can move calls!
1802 return true;
1803}
1804
Michael Gottesman97e3df02013-01-14 00:35:14 +00001805/// Identify pairings between the retains and releases, and delete and/or move
1806/// them.
Michael Gottesman0be69202015-03-05 23:28:58 +00001807bool ObjCARCOpt::PerformCodePlacement(
1808 DenseMap<const BasicBlock *, BBState> &BBStates,
1809 BlotMapVector<Value *, RRInfo> &Retains,
1810 DenseMap<Value *, RRInfo> &Releases, Module *M) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001811 LLVM_DEBUG(dbgs() << "\n== ObjCARCOpt::PerformCodePlacement ==\n");
Michael Gottesman89279f82013-04-05 18:10:41 +00001812
John McCalld935e9c2011-06-15 23:37:01 +00001813 bool AnyPairsCompletelyEliminated = false;
John McCalld935e9c2011-06-15 23:37:01 +00001814 SmallVector<Instruction *, 8> DeadInsts;
1815
Dan Gohman670f9372012-04-13 18:57:48 +00001816 // Visit each retain.
Michael Gottesman0be69202015-03-05 23:28:58 +00001817 for (BlotMapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
1818 E = Retains.end();
1819 I != E; ++I) {
Dan Gohman2053a5d2011-09-29 22:25:23 +00001820 Value *V = I->first;
John McCalld935e9c2011-06-15 23:37:01 +00001821 if (!V) continue; // blotted
1822
1823 Instruction *Retain = cast<Instruction>(V);
Michael Gottesmanc189a392013-01-09 19:23:24 +00001824
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001825 LLVM_DEBUG(dbgs() << "Visiting: " << *Retain << "\n");
Michael Gottesmanc189a392013-01-09 19:23:24 +00001826
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001827 Value *Arg = GetArgRCIdentityRoot(Retain);
John McCalld935e9c2011-06-15 23:37:01 +00001828
Dan Gohman728db492012-01-13 00:39:07 +00001829 // If the object being released is in static or stack storage, we know it's
John McCalld935e9c2011-06-15 23:37:01 +00001830 // not being managed by ObjC reference counting, so we can delete pairs
1831 // regardless of what possible decrements or uses lie between them.
Dan Gohman728db492012-01-13 00:39:07 +00001832 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
Dan Gohman41375a32012-05-08 23:39:44 +00001833
Dan Gohman56e1cef2011-08-22 17:29:11 +00001834 // A constant pointer can't be pointing to an object on the heap. It may
1835 // be reference-counted, but it won't be deleted.
1836 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
1837 if (const GlobalVariable *GV =
1838 dyn_cast<GlobalVariable>(
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00001839 GetRCIdentityRoot(LI->getPointerOperand())))
Dan Gohman56e1cef2011-08-22 17:29:11 +00001840 if (GV->isConstant())
1841 KnownSafe = true;
1842
John McCalld935e9c2011-06-15 23:37:01 +00001843 // Connect the dots between the top-down-collected RetainsToMove and
1844 // bottom-up-collected ReleasesToMove to form sets of related calls.
Akira Hatanaka2b882052017-02-25 00:53:38 +00001845 RRInfo RetainsToMove, ReleasesToMove;
1846
Michael Gottesman67792172015-03-16 07:02:30 +00001847 bool PerformMoveCalls = PairUpRetainsAndReleases(
Akira Hatanaka2b882052017-02-25 00:53:38 +00001848 BBStates, Retains, Releases, M, Retain, DeadInsts,
Michael Gottesman67792172015-03-16 07:02:30 +00001849 RetainsToMove, ReleasesToMove, Arg, KnownSafe,
1850 AnyPairsCompletelyEliminated);
John McCalld935e9c2011-06-15 23:37:01 +00001851
Michael Gottesman9de6f962013-01-22 21:49:00 +00001852 if (PerformMoveCalls) {
1853 // Ok, everything checks out and we're all set. Let's move/delete some
1854 // code!
1855 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
1856 Retains, Releases, DeadInsts, M);
John McCalld935e9c2011-06-15 23:37:01 +00001857 }
John McCalld935e9c2011-06-15 23:37:01 +00001858 }
1859
1860 // Now that we're done moving everything, we can delete the newly dead
1861 // instructions, as we no longer need them as insert points.
1862 while (!DeadInsts.empty())
1863 EraseInstruction(DeadInsts.pop_back_val());
1864
1865 return AnyPairsCompletelyEliminated;
1866}
1867
Michael Gottesman97e3df02013-01-14 00:35:14 +00001868/// Weak pointer optimizations.
John McCalld935e9c2011-06-15 23:37:01 +00001869void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001870 LLVM_DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeWeakCalls ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00001871
John McCalld935e9c2011-06-15 23:37:01 +00001872 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
1873 // itself because it uses AliasAnalysis and we need to do provenance
1874 // queries instead.
1875 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
1876 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +00001877
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001878 LLVM_DEBUG(dbgs() << "Visiting: " << *Inst << "\n");
Michael Gottesman3f146e22013-01-01 16:05:48 +00001879
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001880 ARCInstKind Class = GetBasicARCInstKind(Inst);
1881 if (Class != ARCInstKind::LoadWeak &&
1882 Class != ARCInstKind::LoadWeakRetained)
John McCalld935e9c2011-06-15 23:37:01 +00001883 continue;
1884
1885 // Delete objc_loadWeak calls with no users.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001886 if (Class == ARCInstKind::LoadWeak && Inst->use_empty()) {
John McCalld935e9c2011-06-15 23:37:01 +00001887 Inst->eraseFromParent();
1888 continue;
1889 }
1890
1891 // TODO: For now, just look for an earlier available version of this value
1892 // within the same block. Theoretically, we could do memdep-style non-local
1893 // analysis too, but that would want caching. A better approach would be to
1894 // use the technique that EarlyCSE uses.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001895 inst_iterator Current = std::prev(I);
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +00001896 BasicBlock *CurrentBB = &*Current.getBasicBlockIterator();
John McCalld935e9c2011-06-15 23:37:01 +00001897 for (BasicBlock::iterator B = CurrentBB->begin(),
1898 J = Current.getInstructionIterator();
1899 J != B; --J) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001900 Instruction *EarlierInst = &*std::prev(J);
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001901 ARCInstKind EarlierClass = GetARCInstKind(EarlierInst);
John McCalld935e9c2011-06-15 23:37:01 +00001902 switch (EarlierClass) {
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001903 case ARCInstKind::LoadWeak:
1904 case ARCInstKind::LoadWeakRetained: {
John McCalld935e9c2011-06-15 23:37:01 +00001905 // If this is loading from the same pointer, replace this load's value
1906 // with that one.
1907 CallInst *Call = cast<CallInst>(Inst);
1908 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
1909 Value *Arg = Call->getArgOperand(0);
1910 Value *EarlierArg = EarlierCall->getArgOperand(0);
1911 switch (PA.getAA()->alias(Arg, EarlierArg)) {
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001912 case MustAlias:
John McCalld935e9c2011-06-15 23:37:01 +00001913 Changed = true;
1914 // If the load has a builtin retain, insert a plain retain for it.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001915 if (Class == ARCInstKind::LoadWeakRetained) {
James Y Knight7976eb52019-02-01 20:43:25 +00001916 Function *Decl = EP.get(ARCRuntimeEntryPointKind::Retain);
Michael Gottesman14acfac2013-07-06 01:39:23 +00001917 CallInst *CI = CallInst::Create(Decl, EarlierCall, "", Call);
John McCalld935e9c2011-06-15 23:37:01 +00001918 CI->setTailCall();
1919 }
1920 // Zap the fully redundant load.
1921 Call->replaceAllUsesWith(EarlierCall);
1922 Call->eraseFromParent();
1923 goto clobbered;
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001924 case MayAlias:
1925 case PartialAlias:
John McCalld935e9c2011-06-15 23:37:01 +00001926 goto clobbered;
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001927 case NoAlias:
John McCalld935e9c2011-06-15 23:37:01 +00001928 break;
1929 }
1930 break;
1931 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001932 case ARCInstKind::StoreWeak:
1933 case ARCInstKind::InitWeak: {
John McCalld935e9c2011-06-15 23:37:01 +00001934 // If this is storing to the same pointer and has the same size etc.
1935 // replace this load's value with the stored value.
1936 CallInst *Call = cast<CallInst>(Inst);
1937 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
1938 Value *Arg = Call->getArgOperand(0);
1939 Value *EarlierArg = EarlierCall->getArgOperand(0);
1940 switch (PA.getAA()->alias(Arg, EarlierArg)) {
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001941 case MustAlias:
John McCalld935e9c2011-06-15 23:37:01 +00001942 Changed = true;
1943 // If the load has a builtin retain, insert a plain retain for it.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001944 if (Class == ARCInstKind::LoadWeakRetained) {
James Y Knight7976eb52019-02-01 20:43:25 +00001945 Function *Decl = EP.get(ARCRuntimeEntryPointKind::Retain);
Michael Gottesman14acfac2013-07-06 01:39:23 +00001946 CallInst *CI = CallInst::Create(Decl, EarlierCall, "", Call);
John McCalld935e9c2011-06-15 23:37:01 +00001947 CI->setTailCall();
1948 }
1949 // Zap the fully redundant load.
1950 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
1951 Call->eraseFromParent();
1952 goto clobbered;
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001953 case MayAlias:
1954 case PartialAlias:
John McCalld935e9c2011-06-15 23:37:01 +00001955 goto clobbered;
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001956 case NoAlias:
John McCalld935e9c2011-06-15 23:37:01 +00001957 break;
1958 }
1959 break;
1960 }
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001961 case ARCInstKind::MoveWeak:
1962 case ARCInstKind::CopyWeak:
John McCalld935e9c2011-06-15 23:37:01 +00001963 // TOOD: Grab the copied value.
1964 goto clobbered;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001965 case ARCInstKind::AutoreleasepoolPush:
1966 case ARCInstKind::None:
1967 case ARCInstKind::IntrinsicUser:
1968 case ARCInstKind::User:
John McCalld935e9c2011-06-15 23:37:01 +00001969 // Weak pointers are only modified through the weak entry points
1970 // (and arbitrary calls, which could call the weak entry points).
1971 break;
1972 default:
1973 // Anything else could modify the weak pointer.
1974 goto clobbered;
1975 }
1976 }
1977 clobbered:;
1978 }
1979
1980 // Then, for each destroyWeak with an alloca operand, check to see if
1981 // the alloca and all its users can be zapped.
1982 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
1983 Instruction *Inst = &*I++;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001984 ARCInstKind Class = GetBasicARCInstKind(Inst);
1985 if (Class != ARCInstKind::DestroyWeak)
John McCalld935e9c2011-06-15 23:37:01 +00001986 continue;
1987
1988 CallInst *Call = cast<CallInst>(Inst);
1989 Value *Arg = Call->getArgOperand(0);
1990 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001991 for (User *U : Alloca->users()) {
1992 const Instruction *UserInst = cast<Instruction>(U);
Michael Gottesman6f729fa2015-02-19 19:51:32 +00001993 switch (GetBasicARCInstKind(UserInst)) {
1994 case ARCInstKind::InitWeak:
1995 case ARCInstKind::StoreWeak:
1996 case ARCInstKind::DestroyWeak:
John McCalld935e9c2011-06-15 23:37:01 +00001997 continue;
1998 default:
1999 goto done;
2000 }
2001 }
2002 Changed = true;
Chandler Carruthcdf47882014-03-09 03:16:01 +00002003 for (auto UI = Alloca->user_begin(), UE = Alloca->user_end(); UI != UE;) {
John McCalld935e9c2011-06-15 23:37:01 +00002004 CallInst *UserInst = cast<CallInst>(*UI++);
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002005 switch (GetBasicARCInstKind(UserInst)) {
2006 case ARCInstKind::InitWeak:
2007 case ARCInstKind::StoreWeak:
Dan Gohman14862c32012-05-18 22:17:29 +00002008 // These functions return their second argument.
2009 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
2010 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002011 case ARCInstKind::DestroyWeak:
Dan Gohman14862c32012-05-18 22:17:29 +00002012 // No return value.
2013 break;
2014 default:
Dan Gohman9c97eea02012-05-21 17:41:28 +00002015 llvm_unreachable("alloca really is used!");
Dan Gohman14862c32012-05-18 22:17:29 +00002016 }
John McCalld935e9c2011-06-15 23:37:01 +00002017 UserInst->eraseFromParent();
2018 }
2019 Alloca->eraseFromParent();
2020 done:;
2021 }
2022 }
2023}
2024
Michael Gottesman97e3df02013-01-14 00:35:14 +00002025/// Identify program paths which execute sequences of retains and releases which
2026/// can be eliminated.
John McCalld935e9c2011-06-15 23:37:01 +00002027bool ObjCARCOpt::OptimizeSequences(Function &F) {
Michael Gottesman740db972013-05-23 02:35:21 +00002028 // Releases, Retains - These are used to store the results of the main flow
2029 // analysis. These use Value* as the key instead of Instruction* so that the
2030 // map stays valid when we get around to rewriting code and calls get
2031 // replaced by arguments.
John McCalld935e9c2011-06-15 23:37:01 +00002032 DenseMap<Value *, RRInfo> Releases;
Michael Gottesman0be69202015-03-05 23:28:58 +00002033 BlotMapVector<Value *, RRInfo> Retains;
John McCalld935e9c2011-06-15 23:37:01 +00002034
Michael Gottesman740db972013-05-23 02:35:21 +00002035 // This is used during the traversal of the function to track the
2036 // states for each identified object at each block.
John McCalld935e9c2011-06-15 23:37:01 +00002037 DenseMap<const BasicBlock *, BBState> BBStates;
2038
2039 // Analyze the CFG of the function, and all instructions.
2040 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
2041
Akira Hatanaka8edf8f32019-04-25 19:42:55 +00002042 if (DisableRetainReleasePairing)
2043 return false;
2044
John McCalld935e9c2011-06-15 23:37:01 +00002045 // Transform.
Michael Gottesman5a91bbf2013-05-24 20:44:02 +00002046 bool AnyPairsCompletelyEliminated = PerformCodePlacement(BBStates, Retains,
2047 Releases,
2048 F.getParent());
2049
Michael Gottesman5a91bbf2013-05-24 20:44:02 +00002050 return AnyPairsCompletelyEliminated && NestingDetected;
John McCalld935e9c2011-06-15 23:37:01 +00002051}
2052
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002053/// Check if there is a dependent call earlier that does not have anything in
2054/// between the Retain and the call that can affect the reference count of their
2055/// shared pointer argument. Note that Retain need not be in BB.
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002056static bool
2057HasSafePathToPredecessorCall(const Value *Arg, Instruction *Retain,
Craig Topper71b7b682014-08-21 05:55:13 +00002058 SmallPtrSetImpl<Instruction *> &DepInsts,
2059 SmallPtrSetImpl<const BasicBlock *> &Visited,
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002060 ProvenanceAnalysis &PA) {
2061 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
2062 DepInsts, Visited, PA);
2063 if (DepInsts.size() != 1)
2064 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002065
Michael Gottesmana9fc0162015-03-05 23:29:06 +00002066 auto *Call = dyn_cast_or_null<CallInst>(*DepInsts.begin());
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002067
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002068 // Check that the pointer is the return value of the call.
2069 if (!Call || Arg != Call)
2070 return false;
Michael Gottesmanc2d5bf52013-04-03 23:07:45 +00002071
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002072 // Check that the call is a regular call.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002073 ARCInstKind Class = GetBasicARCInstKind(Call);
Alexander Kornienkod0af3b32015-12-28 16:19:08 +00002074 return Class == ARCInstKind::CallOrUser || Class == ARCInstKind::Call;
Michael Gottesman54dc7fd2013-04-03 23:04:28 +00002075}
2076
Michael Gottesman6908db12013-04-03 23:16:05 +00002077/// Find a dependent retain that precedes the given autorelease for which there
2078/// is nothing in between the two instructions that can affect the ref count of
2079/// Arg.
2080static CallInst *
2081FindPredecessorRetainWithSafePath(const Value *Arg, BasicBlock *BB,
2082 Instruction *Autorelease,
Craig Topper71b7b682014-08-21 05:55:13 +00002083 SmallPtrSetImpl<Instruction *> &DepInsts,
2084 SmallPtrSetImpl<const BasicBlock *> &Visited,
Michael Gottesman6908db12013-04-03 23:16:05 +00002085 ProvenanceAnalysis &PA) {
2086 FindDependencies(CanChangeRetainCount, Arg,
2087 BB, Autorelease, DepInsts, Visited, PA);
2088 if (DepInsts.size() != 1)
Craig Topperf40110f2014-04-25 05:29:35 +00002089 return nullptr;
Michael Gottesman79249972013-04-05 23:46:45 +00002090
Michael Gottesmana9fc0162015-03-05 23:29:06 +00002091 auto *Retain = dyn_cast_or_null<CallInst>(*DepInsts.begin());
Michael Gottesman79249972013-04-05 23:46:45 +00002092
Michael Gottesman6908db12013-04-03 23:16:05 +00002093 // Check that we found a retain with the same argument.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002094 if (!Retain || !IsRetain(GetBasicARCInstKind(Retain)) ||
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00002095 GetArgRCIdentityRoot(Retain) != Arg) {
Craig Topperf40110f2014-04-25 05:29:35 +00002096 return nullptr;
Michael Gottesman6908db12013-04-03 23:16:05 +00002097 }
Michael Gottesman79249972013-04-05 23:46:45 +00002098
Michael Gottesman6908db12013-04-03 23:16:05 +00002099 return Retain;
2100}
2101
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002102/// Look for an ``autorelease'' instruction dependent on Arg such that there are
2103/// no instructions dependent on Arg that need a positive ref count in between
2104/// the autorelease and the ret.
2105static CallInst *
2106FindPredecessorAutoreleaseWithSafePath(const Value *Arg, BasicBlock *BB,
2107 ReturnInst *Ret,
Craig Topper71b7b682014-08-21 05:55:13 +00002108 SmallPtrSetImpl<Instruction *> &DepInsts,
2109 SmallPtrSetImpl<const BasicBlock *> &V,
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002110 ProvenanceAnalysis &PA) {
2111 FindDependencies(NeedsPositiveRetainCount, Arg,
2112 BB, Ret, DepInsts, V, PA);
2113 if (DepInsts.size() != 1)
Craig Topperf40110f2014-04-25 05:29:35 +00002114 return nullptr;
Michael Gottesman79249972013-04-05 23:46:45 +00002115
Michael Gottesmana9fc0162015-03-05 23:29:06 +00002116 auto *Autorelease = dyn_cast_or_null<CallInst>(*DepInsts.begin());
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002117 if (!Autorelease)
Craig Topperf40110f2014-04-25 05:29:35 +00002118 return nullptr;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002119 ARCInstKind AutoreleaseClass = GetBasicARCInstKind(Autorelease);
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002120 if (!IsAutorelease(AutoreleaseClass))
Craig Topperf40110f2014-04-25 05:29:35 +00002121 return nullptr;
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00002122 if (GetArgRCIdentityRoot(Autorelease) != Arg)
Craig Topperf40110f2014-04-25 05:29:35 +00002123 return nullptr;
Michael Gottesman79249972013-04-05 23:46:45 +00002124
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002125 return Autorelease;
2126}
2127
Michael Gottesman97e3df02013-01-14 00:35:14 +00002128/// Look for this pattern:
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00002129/// \code
John McCalld935e9c2011-06-15 23:37:01 +00002130/// %call = call i8* @something(...)
2131/// %2 = call i8* @objc_retain(i8* %call)
2132/// %3 = call i8* @objc_autorelease(i8* %2)
2133/// ret i8* %3
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00002134/// \endcode
John McCalld935e9c2011-06-15 23:37:01 +00002135/// And delete the retain and autorelease.
John McCalld935e9c2011-06-15 23:37:01 +00002136void ObjCARCOpt::OptimizeReturns(Function &F) {
2137 if (!F.getReturnType()->isPointerTy())
2138 return;
Michael Gottesman79249972013-04-05 23:46:45 +00002139
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002140 LLVM_DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeReturns ==\n");
Michael Gottesman79249972013-04-05 23:46:45 +00002141
John McCalld935e9c2011-06-15 23:37:01 +00002142 SmallPtrSet<Instruction *, 4> DependingInstructions;
2143 SmallPtrSet<const BasicBlock *, 4> Visited;
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +00002144 for (BasicBlock &BB: F) {
2145 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB.back());
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002146 if (!Ret)
2147 continue;
Michael Gottesman79249972013-04-05 23:46:45 +00002148
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002149 LLVM_DEBUG(dbgs() << "Visiting: " << *Ret << "\n");
Chandler Carruthd9ef4b62016-11-04 06:59:50 +00002150
Michael Gottesmane5ad66f2015-02-19 00:42:38 +00002151 const Value *Arg = GetRCIdentityRoot(Ret->getOperand(0));
Michael Gottesman79249972013-04-05 23:46:45 +00002152
Michael Gottesmancdb7c152013-04-21 00:25:04 +00002153 // Look for an ``autorelease'' instruction that is a predecessor of Ret and
Michael Gottesman21a4ed32013-04-03 23:39:14 +00002154 // dependent on Arg such that there are no instructions dependent on Arg
2155 // that need a positive ref count in between the autorelease and Ret.
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +00002156 CallInst *Autorelease = FindPredecessorAutoreleaseWithSafePath(
2157 Arg, &BB, Ret, DependingInstructions, Visited, PA);
John McCalld935e9c2011-06-15 23:37:01 +00002158 DependingInstructions.clear();
2159 Visited.clear();
Michael Gottesmanfb9ece92013-04-21 00:25:01 +00002160
2161 if (!Autorelease)
2162 continue;
2163
Duncan P. N. Exon Smith1e59a662015-10-19 23:20:14 +00002164 CallInst *Retain = FindPredecessorRetainWithSafePath(
Akira Hatanaka13d2beb2017-08-31 18:27:47 +00002165 Arg, Autorelease->getParent(), Autorelease, DependingInstructions,
2166 Visited, PA);
Michael Gottesmanfb9ece92013-04-21 00:25:01 +00002167 DependingInstructions.clear();
2168 Visited.clear();
2169
2170 if (!Retain)
2171 continue;
2172
2173 // Check that there is nothing that can affect the reference count
2174 // between the retain and the call. Note that Retain need not be in BB.
2175 bool HasSafePathToCall = HasSafePathToPredecessorCall(Arg, Retain,
2176 DependingInstructions,
2177 Visited, PA);
2178 DependingInstructions.clear();
2179 Visited.clear();
2180
2181 if (!HasSafePathToCall)
2182 continue;
2183
2184 // If so, we can zap the retain and autorelease.
2185 Changed = true;
2186 ++NumRets;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002187 LLVM_DEBUG(dbgs() << "Erasing: " << *Retain << "\nErasing: " << *Autorelease
2188 << "\n");
Michael Gottesmanfb9ece92013-04-21 00:25:01 +00002189 EraseInstruction(Retain);
2190 EraseInstruction(Autorelease);
John McCalld935e9c2011-06-15 23:37:01 +00002191 }
2192}
2193
Michael Gottesman9c118152013-04-29 06:16:57 +00002194#ifndef NDEBUG
2195void
2196ObjCARCOpt::GatherStatistics(Function &F, bool AfterOptimization) {
Eugene Zelenko57bd5a02017-10-27 01:09:08 +00002197 Statistic &NumRetains =
2198 AfterOptimization ? NumRetainsAfterOpt : NumRetainsBeforeOpt;
2199 Statistic &NumReleases =
2200 AfterOptimization ? NumReleasesAfterOpt : NumReleasesBeforeOpt;
Michael Gottesman9c118152013-04-29 06:16:57 +00002201
2202 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2203 Instruction *Inst = &*I++;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002204 switch (GetBasicARCInstKind(Inst)) {
Michael Gottesman9c118152013-04-29 06:16:57 +00002205 default:
2206 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002207 case ARCInstKind::Retain:
Michael Gottesman9c118152013-04-29 06:16:57 +00002208 ++NumRetains;
2209 break;
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002210 case ARCInstKind::Release:
Michael Gottesman9c118152013-04-29 06:16:57 +00002211 ++NumReleases;
2212 break;
2213 }
2214 }
2215}
2216#endif
2217
John McCalld935e9c2011-06-15 23:37:01 +00002218bool ObjCARCOpt::doInitialization(Module &M) {
2219 if (!EnableARCOpts)
2220 return false;
2221
Dan Gohman670f9372012-04-13 18:57:48 +00002222 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanceaac7c2011-06-20 23:20:43 +00002223 Run = ModuleHasARC(M);
2224 if (!Run)
2225 return false;
2226
John McCalld935e9c2011-06-15 23:37:01 +00002227 // Intuitively, objc_retain and others are nocapture, however in practice
2228 // they are not, because they return their argument value. And objc_release
Dan Gohmandae33492012-04-27 18:56:31 +00002229 // calls finalizers which can have arbitrary side effects.
Michael Gottesman65cb7372015-03-16 07:02:27 +00002230 MDKindCache.init(&M);
John McCalld935e9c2011-06-15 23:37:01 +00002231
Michael Gottesman14acfac2013-07-06 01:39:23 +00002232 // Initialize our runtime entry point cache.
Michael Gottesman65cb7372015-03-16 07:02:27 +00002233 EP.init(&M);
John McCalld935e9c2011-06-15 23:37:01 +00002234
2235 return false;
2236}
2237
2238bool ObjCARCOpt::runOnFunction(Function &F) {
2239 if (!EnableARCOpts)
2240 return false;
2241
Dan Gohmanceaac7c2011-06-20 23:20:43 +00002242 // If nothing in the Module uses ARC, don't do anything.
2243 if (!Run)
2244 return false;
2245
John McCalld935e9c2011-06-15 23:37:01 +00002246 Changed = false;
2247
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002248 LLVM_DEBUG(dbgs() << "<<< ObjCARCOpt: Visiting Function: " << F.getName()
2249 << " >>>"
2250 "\n");
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00002251
Chandler Carruth7b560d42015-09-09 17:55:00 +00002252 PA.setAA(&getAnalysis<AAResultsWrapperPass>().getAAResults());
John McCalld935e9c2011-06-15 23:37:01 +00002253
Michael Gottesman9fc50b82013-05-13 18:29:07 +00002254#ifndef NDEBUG
2255 if (AreStatisticsEnabled()) {
2256 GatherStatistics(F, false);
2257 }
2258#endif
2259
John McCalld935e9c2011-06-15 23:37:01 +00002260 // This pass performs several distinct transformations. As a compile-time aid
2261 // when compiling code that isn't ObjC, skip these if the relevant ObjC
2262 // library functions aren't declared.
2263
Michael Gottesmancd5b0272013-04-24 22:18:15 +00002264 // Preliminary optimizations. This also computes UsedInThisFunction.
John McCalld935e9c2011-06-15 23:37:01 +00002265 OptimizeIndividualCalls(F);
2266
2267 // Optimizations for weak pointers.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002268 if (UsedInThisFunction & ((1 << unsigned(ARCInstKind::LoadWeak)) |
2269 (1 << unsigned(ARCInstKind::LoadWeakRetained)) |
2270 (1 << unsigned(ARCInstKind::StoreWeak)) |
2271 (1 << unsigned(ARCInstKind::InitWeak)) |
2272 (1 << unsigned(ARCInstKind::CopyWeak)) |
2273 (1 << unsigned(ARCInstKind::MoveWeak)) |
2274 (1 << unsigned(ARCInstKind::DestroyWeak))))
John McCalld935e9c2011-06-15 23:37:01 +00002275 OptimizeWeakCalls(F);
2276
2277 // Optimizations for retain+release pairs.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002278 if (UsedInThisFunction & ((1 << unsigned(ARCInstKind::Retain)) |
2279 (1 << unsigned(ARCInstKind::RetainRV)) |
2280 (1 << unsigned(ARCInstKind::RetainBlock))))
2281 if (UsedInThisFunction & (1 << unsigned(ARCInstKind::Release)))
John McCalld935e9c2011-06-15 23:37:01 +00002282 // Run OptimizeSequences until it either stops making changes or
2283 // no retain+release pair nesting is detected.
2284 while (OptimizeSequences(F)) {}
2285
2286 // Optimizations if objc_autorelease is used.
Michael Gottesman6f729fa2015-02-19 19:51:32 +00002287 if (UsedInThisFunction & ((1 << unsigned(ARCInstKind::Autorelease)) |
2288 (1 << unsigned(ARCInstKind::AutoreleaseRV))))
John McCalld935e9c2011-06-15 23:37:01 +00002289 OptimizeReturns(F);
2290
Michael Gottesman9c118152013-04-29 06:16:57 +00002291 // Gather statistics after optimization.
2292#ifndef NDEBUG
2293 if (AreStatisticsEnabled()) {
2294 GatherStatistics(F, true);
2295 }
2296#endif
2297
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002298 LLVM_DEBUG(dbgs() << "\n");
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00002299
John McCalld935e9c2011-06-15 23:37:01 +00002300 return Changed;
2301}
2302
2303void ObjCARCOpt::releaseMemory() {
2304 PA.clear();
2305}
2306
Michael Gottesman97e3df02013-01-14 00:35:14 +00002307/// @}
2308///