blob: abd6b4185f6305f82f2a0cf747b8cb0fb8f9cb06 [file] [log] [blame]
John McCall9fbd3182011-06-15 23:37:01 +00001//===- ObjCARC.cpp - ObjC ARC Optimization --------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Michael Gottesman81c61212013-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
16/// redundant weak pointer operations, pattern-matching and replacement of
17/// low-level operations into higher-level operations, and numerous minor
18/// simplifications.
19///
20/// This file also defines a simple ARC-aware AliasAnalysis.
21///
22/// WARNING: This file knows about certain library functions. It recognizes them
23/// by name, and hardwires knowledge of their semantics.
24///
25/// WARNING: This file knows about how certain Objective-C library functions are
26/// used. Naive LLVM IR transformations which would otherwise be
27/// behavior-preserving may break these assumptions.
28///
John McCall9fbd3182011-06-15 23:37:01 +000029//===----------------------------------------------------------------------===//
30
31#define DEBUG_TYPE "objc-arc"
John McCall9fbd3182011-06-15 23:37:01 +000032#include "llvm/ADT/DenseMap.h"
Michael Gottesman6056b852013-01-13 22:12:06 +000033#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000034#include "llvm/Support/CommandLine.h"
Chandler Carruth58a2cbe2013-01-02 10:22:59 +000035#include "llvm/Support/Debug.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000036#include "llvm/Support/raw_ostream.h"
John McCall9fbd3182011-06-15 23:37:01 +000037using namespace llvm;
38
Michael Gottesman81c61212013-01-14 00:35:14 +000039/// \brief A handy option to enable/disable all optimizations in this file.
John McCall9fbd3182011-06-15 23:37:01 +000040static cl::opt<bool> EnableARCOpts("enable-objc-arc-opts", cl::init(true));
41
Michael Gottesman81c61212013-01-14 00:35:14 +000042/// \defgroup MiscUtils Miscellaneous utilities that are not ARC specific.
43/// @{
John McCall9fbd3182011-06-15 23:37:01 +000044
45namespace {
Michael Gottesman81c61212013-01-14 00:35:14 +000046 /// \brief An associative container with fast insertion-order (deterministic)
47 /// iteration over its elements. Plus the special blot operation.
John McCall9fbd3182011-06-15 23:37:01 +000048 template<class KeyT, class ValueT>
49 class MapVector {
Michael Gottesman81c61212013-01-14 00:35:14 +000050 /// Map keys to indices in Vector.
John McCall9fbd3182011-06-15 23:37:01 +000051 typedef DenseMap<KeyT, size_t> MapTy;
52 MapTy Map;
53
John McCall9fbd3182011-06-15 23:37:01 +000054 typedef std::vector<std::pair<KeyT, ValueT> > VectorTy;
Michael Gottesman81c61212013-01-14 00:35:14 +000055 /// Keys and values.
John McCall9fbd3182011-06-15 23:37:01 +000056 VectorTy Vector;
57
58 public:
59 typedef typename VectorTy::iterator iterator;
60 typedef typename VectorTy::const_iterator const_iterator;
61 iterator begin() { return Vector.begin(); }
62 iterator end() { return Vector.end(); }
63 const_iterator begin() const { return Vector.begin(); }
64 const_iterator end() const { return Vector.end(); }
65
66#ifdef XDEBUG
67 ~MapVector() {
68 assert(Vector.size() >= Map.size()); // May differ due to blotting.
69 for (typename MapTy::const_iterator I = Map.begin(), E = Map.end();
70 I != E; ++I) {
71 assert(I->second < Vector.size());
72 assert(Vector[I->second].first == I->first);
73 }
74 for (typename VectorTy::const_iterator I = Vector.begin(),
75 E = Vector.end(); I != E; ++I)
76 assert(!I->first ||
77 (Map.count(I->first) &&
78 Map[I->first] == size_t(I - Vector.begin())));
79 }
80#endif
81
Dan Gohman22cc4cc2012-03-02 01:13:53 +000082 ValueT &operator[](const KeyT &Arg) {
John McCall9fbd3182011-06-15 23:37:01 +000083 std::pair<typename MapTy::iterator, bool> Pair =
84 Map.insert(std::make_pair(Arg, size_t(0)));
85 if (Pair.second) {
Dan Gohman22cc4cc2012-03-02 01:13:53 +000086 size_t Num = Vector.size();
87 Pair.first->second = Num;
John McCall9fbd3182011-06-15 23:37:01 +000088 Vector.push_back(std::make_pair(Arg, ValueT()));
Dan Gohman22cc4cc2012-03-02 01:13:53 +000089 return Vector[Num].second;
John McCall9fbd3182011-06-15 23:37:01 +000090 }
91 return Vector[Pair.first->second].second;
92 }
93
94 std::pair<iterator, bool>
95 insert(const std::pair<KeyT, ValueT> &InsertPair) {
96 std::pair<typename MapTy::iterator, bool> Pair =
97 Map.insert(std::make_pair(InsertPair.first, size_t(0)));
98 if (Pair.second) {
Dan Gohman22cc4cc2012-03-02 01:13:53 +000099 size_t Num = Vector.size();
100 Pair.first->second = Num;
John McCall9fbd3182011-06-15 23:37:01 +0000101 Vector.push_back(InsertPair);
Dan Gohman22cc4cc2012-03-02 01:13:53 +0000102 return std::make_pair(Vector.begin() + Num, true);
John McCall9fbd3182011-06-15 23:37:01 +0000103 }
104 return std::make_pair(Vector.begin() + Pair.first->second, false);
105 }
106
Dan Gohman22cc4cc2012-03-02 01:13:53 +0000107 const_iterator find(const KeyT &Key) const {
John McCall9fbd3182011-06-15 23:37:01 +0000108 typename MapTy::const_iterator It = Map.find(Key);
109 if (It == Map.end()) return Vector.end();
110 return Vector.begin() + It->second;
111 }
112
Michael Gottesman81c61212013-01-14 00:35:14 +0000113 /// This is similar to erase, but instead of removing the element from the
114 /// vector, it just zeros out the key in the vector. This leaves iterators
115 /// intact, but clients must be prepared for zeroed-out keys when iterating.
Dan Gohman22cc4cc2012-03-02 01:13:53 +0000116 void blot(const KeyT &Key) {
John McCall9fbd3182011-06-15 23:37:01 +0000117 typename MapTy::iterator It = Map.find(Key);
118 if (It == Map.end()) return;
119 Vector[It->second].first = KeyT();
120 Map.erase(It);
121 }
122
123 void clear() {
124 Map.clear();
125 Vector.clear();
126 }
127 };
128}
129
Michael Gottesman81c61212013-01-14 00:35:14 +0000130/// @}
131///
132/// \defgroup ARCUtilities Utility declarations/definitions specific to ARC.
133/// @{
John McCall9fbd3182011-06-15 23:37:01 +0000134
Chandler Carruthd04a8d42012-12-03 16:50:05 +0000135#include "llvm/ADT/StringSwitch.h"
136#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +0000137#include "llvm/IR/Intrinsics.h"
138#include "llvm/IR/Module.h"
Dan Gohman0daef3d2012-05-08 23:39:44 +0000139#include "llvm/Support/CallSite.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +0000140#include "llvm/Transforms/Utils/Local.h"
Dan Gohman0daef3d2012-05-08 23:39:44 +0000141
John McCall9fbd3182011-06-15 23:37:01 +0000142namespace {
Michael Gottesman81c61212013-01-14 00:35:14 +0000143 /// \enum InstructionClass
144 /// \brief A simple classification for instructions.
John McCall9fbd3182011-06-15 23:37:01 +0000145 enum InstructionClass {
146 IC_Retain, ///< objc_retain
147 IC_RetainRV, ///< objc_retainAutoreleasedReturnValue
148 IC_RetainBlock, ///< objc_retainBlock
149 IC_Release, ///< objc_release
150 IC_Autorelease, ///< objc_autorelease
151 IC_AutoreleaseRV, ///< objc_autoreleaseReturnValue
152 IC_AutoreleasepoolPush, ///< objc_autoreleasePoolPush
153 IC_AutoreleasepoolPop, ///< objc_autoreleasePoolPop
154 IC_NoopCast, ///< objc_retainedObject, etc.
155 IC_FusedRetainAutorelease, ///< objc_retainAutorelease
156 IC_FusedRetainAutoreleaseRV, ///< objc_retainAutoreleaseReturnValue
157 IC_LoadWeakRetained, ///< objc_loadWeakRetained (primitive)
158 IC_StoreWeak, ///< objc_storeWeak (primitive)
159 IC_InitWeak, ///< objc_initWeak (derived)
160 IC_LoadWeak, ///< objc_loadWeak (derived)
161 IC_MoveWeak, ///< objc_moveWeak (derived)
162 IC_CopyWeak, ///< objc_copyWeak (derived)
163 IC_DestroyWeak, ///< objc_destroyWeak (derived)
Dan Gohman44234772012-04-13 18:28:58 +0000164 IC_StoreStrong, ///< objc_storeStrong (derived)
John McCall9fbd3182011-06-15 23:37:01 +0000165 IC_CallOrUser, ///< could call objc_release and/or "use" pointers
166 IC_Call, ///< could call objc_release
167 IC_User, ///< could "use" a pointer
168 IC_None ///< anything else
169 };
170}
171
Michael Gottesman81c61212013-01-14 00:35:14 +0000172/// \brief Test whether the given value is possible a reference-counted pointer.
John McCall9fbd3182011-06-15 23:37:01 +0000173static bool IsPotentialUse(const Value *Op) {
174 // Pointers to static or stack storage are not reference-counted pointers.
175 if (isa<Constant>(Op) || isa<AllocaInst>(Op))
176 return false;
177 // Special arguments are not reference-counted.
178 if (const Argument *Arg = dyn_cast<Argument>(Op))
179 if (Arg->hasByValAttr() ||
180 Arg->hasNestAttr() ||
181 Arg->hasStructRetAttr())
182 return false;
Dan Gohmanf9096e42011-12-14 19:10:53 +0000183 // Only consider values with pointer types.
184 // It seemes intuitive to exclude function pointer types as well, since
185 // functions are never reference-counted, however clang occasionally
186 // bitcasts reference-counted pointers to function-pointer type
187 // temporarily.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000188 PointerType *Ty = dyn_cast<PointerType>(Op->getType());
Dan Gohmanf9096e42011-12-14 19:10:53 +0000189 if (!Ty)
John McCall9fbd3182011-06-15 23:37:01 +0000190 return false;
191 // Conservatively assume anything else is a potential use.
192 return true;
193}
194
Michael Gottesman7899e472013-01-14 01:47:53 +0000195/// \brief Helper for GetInstructionClass. Determines what kind of construct CS
196/// is.
John McCall9fbd3182011-06-15 23:37:01 +0000197static InstructionClass GetCallSiteClass(ImmutableCallSite CS) {
198 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
199 I != E; ++I)
200 if (IsPotentialUse(*I))
201 return CS.onlyReadsMemory() ? IC_User : IC_CallOrUser;
202
203 return CS.onlyReadsMemory() ? IC_None : IC_Call;
204}
205
Michael Gottesman81c61212013-01-14 00:35:14 +0000206/// \brief Determine if F is one of the special known Functions. If it isn't,
207/// return IC_CallOrUser.
John McCall9fbd3182011-06-15 23:37:01 +0000208static InstructionClass GetFunctionClass(const Function *F) {
209 Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
210
211 // No arguments.
212 if (AI == AE)
213 return StringSwitch<InstructionClass>(F->getName())
214 .Case("objc_autoreleasePoolPush", IC_AutoreleasepoolPush)
215 .Default(IC_CallOrUser);
216
217 // One argument.
218 const Argument *A0 = AI++;
219 if (AI == AE)
220 // Argument is a pointer.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000221 if (PointerType *PTy = dyn_cast<PointerType>(A0->getType())) {
222 Type *ETy = PTy->getElementType();
John McCall9fbd3182011-06-15 23:37:01 +0000223 // Argument is i8*.
224 if (ETy->isIntegerTy(8))
225 return StringSwitch<InstructionClass>(F->getName())
226 .Case("objc_retain", IC_Retain)
227 .Case("objc_retainAutoreleasedReturnValue", IC_RetainRV)
228 .Case("objc_retainBlock", IC_RetainBlock)
229 .Case("objc_release", IC_Release)
230 .Case("objc_autorelease", IC_Autorelease)
231 .Case("objc_autoreleaseReturnValue", IC_AutoreleaseRV)
232 .Case("objc_autoreleasePoolPop", IC_AutoreleasepoolPop)
233 .Case("objc_retainedObject", IC_NoopCast)
234 .Case("objc_unretainedObject", IC_NoopCast)
235 .Case("objc_unretainedPointer", IC_NoopCast)
236 .Case("objc_retain_autorelease", IC_FusedRetainAutorelease)
237 .Case("objc_retainAutorelease", IC_FusedRetainAutorelease)
238 .Case("objc_retainAutoreleaseReturnValue",IC_FusedRetainAutoreleaseRV)
239 .Default(IC_CallOrUser);
240
241 // Argument is i8**
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000242 if (PointerType *Pte = dyn_cast<PointerType>(ETy))
John McCall9fbd3182011-06-15 23:37:01 +0000243 if (Pte->getElementType()->isIntegerTy(8))
244 return StringSwitch<InstructionClass>(F->getName())
245 .Case("objc_loadWeakRetained", IC_LoadWeakRetained)
246 .Case("objc_loadWeak", IC_LoadWeak)
247 .Case("objc_destroyWeak", IC_DestroyWeak)
248 .Default(IC_CallOrUser);
249 }
250
251 // Two arguments, first is i8**.
252 const Argument *A1 = AI++;
253 if (AI == AE)
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000254 if (PointerType *PTy = dyn_cast<PointerType>(A0->getType()))
255 if (PointerType *Pte = dyn_cast<PointerType>(PTy->getElementType()))
John McCall9fbd3182011-06-15 23:37:01 +0000256 if (Pte->getElementType()->isIntegerTy(8))
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000257 if (PointerType *PTy1 = dyn_cast<PointerType>(A1->getType())) {
258 Type *ETy1 = PTy1->getElementType();
John McCall9fbd3182011-06-15 23:37:01 +0000259 // Second argument is i8*
260 if (ETy1->isIntegerTy(8))
261 return StringSwitch<InstructionClass>(F->getName())
262 .Case("objc_storeWeak", IC_StoreWeak)
263 .Case("objc_initWeak", IC_InitWeak)
Dan Gohman44234772012-04-13 18:28:58 +0000264 .Case("objc_storeStrong", IC_StoreStrong)
John McCall9fbd3182011-06-15 23:37:01 +0000265 .Default(IC_CallOrUser);
266 // Second argument is i8**.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000267 if (PointerType *Pte1 = dyn_cast<PointerType>(ETy1))
John McCall9fbd3182011-06-15 23:37:01 +0000268 if (Pte1->getElementType()->isIntegerTy(8))
269 return StringSwitch<InstructionClass>(F->getName())
270 .Case("objc_moveWeak", IC_MoveWeak)
271 .Case("objc_copyWeak", IC_CopyWeak)
272 .Default(IC_CallOrUser);
273 }
274
275 // Anything else.
276 return IC_CallOrUser;
277}
278
Michael Gottesman81c61212013-01-14 00:35:14 +0000279/// \brief Determine what kind of construct V is.
John McCall9fbd3182011-06-15 23:37:01 +0000280static InstructionClass GetInstructionClass(const Value *V) {
281 if (const Instruction *I = dyn_cast<Instruction>(V)) {
282 // Any instruction other than bitcast and gep with a pointer operand have a
283 // use of an objc pointer. Bitcasts, GEPs, Selects, PHIs transfer a pointer
284 // to a subsequent use, rather than using it themselves, in this sense.
285 // As a short cut, several other opcodes are known to have no pointer
286 // operands of interest. And ret is never followed by a release, so it's
287 // not interesting to examine.
288 switch (I->getOpcode()) {
289 case Instruction::Call: {
290 const CallInst *CI = cast<CallInst>(I);
291 // Check for calls to special functions.
292 if (const Function *F = CI->getCalledFunction()) {
293 InstructionClass Class = GetFunctionClass(F);
294 if (Class != IC_CallOrUser)
295 return Class;
296
297 // None of the intrinsic functions do objc_release. For intrinsics, the
298 // only question is whether or not they may be users.
299 switch (F->getIntrinsicID()) {
John McCall9fbd3182011-06-15 23:37:01 +0000300 case Intrinsic::returnaddress: case Intrinsic::frameaddress:
301 case Intrinsic::stacksave: case Intrinsic::stackrestore:
302 case Intrinsic::vastart: case Intrinsic::vacopy: case Intrinsic::vaend:
Dan Gohman0daef3d2012-05-08 23:39:44 +0000303 case Intrinsic::objectsize: case Intrinsic::prefetch:
304 case Intrinsic::stackprotector:
305 case Intrinsic::eh_return_i32: case Intrinsic::eh_return_i64:
306 case Intrinsic::eh_typeid_for: case Intrinsic::eh_dwarf_cfa:
307 case Intrinsic::eh_sjlj_lsda: case Intrinsic::eh_sjlj_functioncontext:
308 case Intrinsic::init_trampoline: case Intrinsic::adjust_trampoline:
309 case Intrinsic::lifetime_start: case Intrinsic::lifetime_end:
310 case Intrinsic::invariant_start: case Intrinsic::invariant_end:
John McCall9fbd3182011-06-15 23:37:01 +0000311 // Don't let dbg info affect our results.
312 case Intrinsic::dbg_declare: case Intrinsic::dbg_value:
313 // Short cut: Some intrinsics obviously don't use ObjC pointers.
314 return IC_None;
315 default:
Dan Gohman0daef3d2012-05-08 23:39:44 +0000316 break;
John McCall9fbd3182011-06-15 23:37:01 +0000317 }
318 }
319 return GetCallSiteClass(CI);
320 }
321 case Instruction::Invoke:
322 return GetCallSiteClass(cast<InvokeInst>(I));
323 case Instruction::BitCast:
324 case Instruction::GetElementPtr:
325 case Instruction::Select: case Instruction::PHI:
326 case Instruction::Ret: case Instruction::Br:
327 case Instruction::Switch: case Instruction::IndirectBr:
328 case Instruction::Alloca: case Instruction::VAArg:
329 case Instruction::Add: case Instruction::FAdd:
330 case Instruction::Sub: case Instruction::FSub:
331 case Instruction::Mul: case Instruction::FMul:
332 case Instruction::SDiv: case Instruction::UDiv: case Instruction::FDiv:
333 case Instruction::SRem: case Instruction::URem: case Instruction::FRem:
334 case Instruction::Shl: case Instruction::LShr: case Instruction::AShr:
335 case Instruction::And: case Instruction::Or: case Instruction::Xor:
336 case Instruction::SExt: case Instruction::ZExt: case Instruction::Trunc:
337 case Instruction::IntToPtr: case Instruction::FCmp:
338 case Instruction::FPTrunc: case Instruction::FPExt:
339 case Instruction::FPToUI: case Instruction::FPToSI:
340 case Instruction::UIToFP: case Instruction::SIToFP:
341 case Instruction::InsertElement: case Instruction::ExtractElement:
342 case Instruction::ShuffleVector:
343 case Instruction::ExtractValue:
344 break;
345 case Instruction::ICmp:
346 // Comparing a pointer with null, or any other constant, isn't an
347 // interesting use, because we don't care what the pointer points to, or
348 // about the values of any other dynamic reference-counted pointers.
349 if (IsPotentialUse(I->getOperand(1)))
350 return IC_User;
351 break;
352 default:
353 // For anything else, check all the operands.
Dan Gohmand4464602011-08-22 17:29:37 +0000354 // Note that this includes both operands of a Store: while the first
355 // operand isn't actually being dereferenced, it is being stored to
356 // memory where we can no longer track who might read it and dereference
357 // it, so we have to consider it potentially used.
John McCall9fbd3182011-06-15 23:37:01 +0000358 for (User::const_op_iterator OI = I->op_begin(), OE = I->op_end();
359 OI != OE; ++OI)
360 if (IsPotentialUse(*OI))
361 return IC_User;
362 }
363 }
364
365 // Otherwise, it's totally inert for ARC purposes.
366 return IC_None;
367}
368
Michael Gottesman81c61212013-01-14 00:35:14 +0000369/// \brief Determine which objc runtime call instruction class V belongs to.
370///
371/// This is similar to GetInstructionClass except that it only detects objc
372/// runtime calls. This allows it to be faster.
373///
John McCall9fbd3182011-06-15 23:37:01 +0000374static InstructionClass GetBasicInstructionClass(const Value *V) {
375 if (const CallInst *CI = dyn_cast<CallInst>(V)) {
376 if (const Function *F = CI->getCalledFunction())
377 return GetFunctionClass(F);
378 // Otherwise, be conservative.
379 return IC_CallOrUser;
380 }
381
382 // Otherwise, be conservative.
Dan Gohman2f6263c2012-01-17 20:52:24 +0000383 return isa<InvokeInst>(V) ? IC_CallOrUser : IC_User;
John McCall9fbd3182011-06-15 23:37:01 +0000384}
385
Michael Gottesman81c61212013-01-14 00:35:14 +0000386/// \brief Test if the given class is objc_retain or equivalent.
John McCall9fbd3182011-06-15 23:37:01 +0000387static bool IsRetain(InstructionClass Class) {
388 return Class == IC_Retain ||
389 Class == IC_RetainRV;
390}
391
Michael Gottesman81c61212013-01-14 00:35:14 +0000392/// \brief Test if the given class is objc_autorelease or equivalent.
John McCall9fbd3182011-06-15 23:37:01 +0000393static bool IsAutorelease(InstructionClass Class) {
394 return Class == IC_Autorelease ||
395 Class == IC_AutoreleaseRV;
396}
397
Michael Gottesman81c61212013-01-14 00:35:14 +0000398/// \brief Test if the given class represents instructions which return their
399/// argument verbatim.
John McCall9fbd3182011-06-15 23:37:01 +0000400static bool IsForwarding(InstructionClass Class) {
401 // objc_retainBlock technically doesn't always return its argument
402 // verbatim, but it doesn't matter for our purposes here.
403 return Class == IC_Retain ||
404 Class == IC_RetainRV ||
405 Class == IC_Autorelease ||
406 Class == IC_AutoreleaseRV ||
407 Class == IC_RetainBlock ||
408 Class == IC_NoopCast;
409}
410
Michael Gottesman81c61212013-01-14 00:35:14 +0000411/// \brief Test if the given class represents instructions which do nothing if
412/// passed a null pointer.
John McCall9fbd3182011-06-15 23:37:01 +0000413static bool IsNoopOnNull(InstructionClass Class) {
414 return Class == IC_Retain ||
415 Class == IC_RetainRV ||
416 Class == IC_Release ||
417 Class == IC_Autorelease ||
418 Class == IC_AutoreleaseRV ||
419 Class == IC_RetainBlock;
420}
421
Michael Gottesman7899e472013-01-14 01:47:53 +0000422/// \brief Test if the given class represents instructions which are always safe
423/// to mark with the "tail" keyword.
John McCall9fbd3182011-06-15 23:37:01 +0000424static bool IsAlwaysTail(InstructionClass Class) {
425 // IC_RetainBlock may be given a stack argument.
426 return Class == IC_Retain ||
427 Class == IC_RetainRV ||
John McCall9fbd3182011-06-15 23:37:01 +0000428 Class == IC_AutoreleaseRV;
429}
430
Michael Gottesmane8c161a2013-01-12 01:25:15 +0000431/// \brief Test if the given class represents instructions which are never safe
432/// to mark with the "tail" keyword.
433static bool IsNeverTail(InstructionClass Class) {
434 /// It is never safe to tail call objc_autorelease since by tail calling
435 /// objc_autorelease, we also tail call -[NSObject autorelease] which supports
436 /// fast autoreleasing causing our object to be potentially reclaimed from the
437 /// autorelease pool which violates the semantics of __autoreleasing types in
438 /// ARC.
439 return Class == IC_Autorelease;
440}
441
Michael Gottesman81c61212013-01-14 00:35:14 +0000442/// \brief Test if the given class represents instructions which are always safe
443/// to mark with the nounwind attribute.
John McCall9fbd3182011-06-15 23:37:01 +0000444static bool IsNoThrow(InstructionClass Class) {
Dan Gohman1d2fd752011-09-14 18:33:34 +0000445 // objc_retainBlock is not nounwind because it calls user copy constructors
446 // which could theoretically throw.
John McCall9fbd3182011-06-15 23:37:01 +0000447 return Class == IC_Retain ||
448 Class == IC_RetainRV ||
John McCall9fbd3182011-06-15 23:37:01 +0000449 Class == IC_Release ||
450 Class == IC_Autorelease ||
451 Class == IC_AutoreleaseRV ||
452 Class == IC_AutoreleasepoolPush ||
453 Class == IC_AutoreleasepoolPop;
454}
455
Michael Gottesman81c61212013-01-14 00:35:14 +0000456/// \brief Erase the given instruction.
457///
458/// Many ObjC calls return their argument verbatim,
459/// so if it's such a call and the return value has users, replace them with the
460/// argument value.
461///
John McCall9fbd3182011-06-15 23:37:01 +0000462static void EraseInstruction(Instruction *CI) {
463 Value *OldArg = cast<CallInst>(CI)->getArgOperand(0);
464
465 bool Unused = CI->use_empty();
466
467 if (!Unused) {
468 // Replace the return value with the argument.
469 assert(IsForwarding(GetBasicInstructionClass(CI)) &&
470 "Can't delete non-forwarding instruction with users!");
471 CI->replaceAllUsesWith(OldArg);
472 }
473
474 CI->eraseFromParent();
475
476 if (Unused)
477 RecursivelyDeleteTriviallyDeadInstructions(OldArg);
478}
479
Michael Gottesman81c61212013-01-14 00:35:14 +0000480/// \brief This is a wrapper around getUnderlyingObject which also knows how to
481/// look through objc_retain and objc_autorelease calls, which we know to return
482/// their argument verbatim.
John McCall9fbd3182011-06-15 23:37:01 +0000483static const Value *GetUnderlyingObjCPtr(const Value *V) {
484 for (;;) {
485 V = GetUnderlyingObject(V);
486 if (!IsForwarding(GetBasicInstructionClass(V)))
487 break;
488 V = cast<CallInst>(V)->getArgOperand(0);
489 }
490
491 return V;
492}
493
Michael Gottesman81c61212013-01-14 00:35:14 +0000494/// \brief This is a wrapper around Value::stripPointerCasts which also knows
495/// how to look through objc_retain and objc_autorelease calls, which we know to
496/// return their argument verbatim.
John McCall9fbd3182011-06-15 23:37:01 +0000497static const Value *StripPointerCastsAndObjCCalls(const Value *V) {
498 for (;;) {
499 V = V->stripPointerCasts();
500 if (!IsForwarding(GetBasicInstructionClass(V)))
501 break;
502 V = cast<CallInst>(V)->getArgOperand(0);
503 }
504 return V;
505}
506
Michael Gottesman81c61212013-01-14 00:35:14 +0000507/// \brief This is a wrapper around Value::stripPointerCasts which also knows
508/// how to look through objc_retain and objc_autorelease calls, which we know to
509/// return their argument verbatim.
John McCall9fbd3182011-06-15 23:37:01 +0000510static Value *StripPointerCastsAndObjCCalls(Value *V) {
511 for (;;) {
512 V = V->stripPointerCasts();
513 if (!IsForwarding(GetBasicInstructionClass(V)))
514 break;
515 V = cast<CallInst>(V)->getArgOperand(0);
516 }
517 return V;
518}
519
Michael Gottesman81c61212013-01-14 00:35:14 +0000520/// \brief Assuming the given instruction is one of the special calls such as
521/// objc_retain or objc_release, return the argument value, stripped of no-op
John McCall9fbd3182011-06-15 23:37:01 +0000522/// casts and forwarding calls.
523static Value *GetObjCArg(Value *Inst) {
524 return StripPointerCastsAndObjCCalls(cast<CallInst>(Inst)->getArgOperand(0));
525}
526
Michael Gottesman81c61212013-01-14 00:35:14 +0000527/// \brief This is similar to AliasAnalysis's isObjCIdentifiedObject, except
528/// that it uses special knowledge of ObjC conventions.
John McCall9fbd3182011-06-15 23:37:01 +0000529static bool IsObjCIdentifiedObject(const Value *V) {
530 // Assume that call results and arguments have their own "provenance".
531 // Constants (including GlobalVariables) and Allocas are never
532 // reference-counted.
533 if (isa<CallInst>(V) || isa<InvokeInst>(V) ||
534 isa<Argument>(V) || isa<Constant>(V) ||
535 isa<AllocaInst>(V))
536 return true;
537
538 if (const LoadInst *LI = dyn_cast<LoadInst>(V)) {
539 const Value *Pointer =
540 StripPointerCastsAndObjCCalls(LI->getPointerOperand());
541 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Pointer)) {
Dan Gohman1b31ea82011-08-22 17:29:11 +0000542 // A constant pointer can't be pointing to an object on the heap. It may
543 // be reference-counted, but it won't be deleted.
544 if (GV->isConstant())
545 return true;
John McCall9fbd3182011-06-15 23:37:01 +0000546 StringRef Name = GV->getName();
547 // These special variables are known to hold values which are not
548 // reference-counted pointers.
549 if (Name.startswith("\01L_OBJC_SELECTOR_REFERENCES_") ||
550 Name.startswith("\01L_OBJC_CLASSLIST_REFERENCES_") ||
551 Name.startswith("\01L_OBJC_CLASSLIST_SUP_REFS_$_") ||
552 Name.startswith("\01L_OBJC_METH_VAR_NAME_") ||
553 Name.startswith("\01l_objc_msgSend_fixup_"))
554 return true;
555 }
556 }
557
558 return false;
559}
560
Michael Gottesman81c61212013-01-14 00:35:14 +0000561/// \brief This is similar to StripPointerCastsAndObjCCalls but it stops as soon
562/// as it finds a value with multiple uses.
John McCall9fbd3182011-06-15 23:37:01 +0000563static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
564 if (Arg->hasOneUse()) {
565 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
566 return FindSingleUseIdentifiedObject(BC->getOperand(0));
567 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
568 if (GEP->hasAllZeroIndices())
569 return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
570 if (IsForwarding(GetBasicInstructionClass(Arg)))
571 return FindSingleUseIdentifiedObject(
572 cast<CallInst>(Arg)->getArgOperand(0));
573 if (!IsObjCIdentifiedObject(Arg))
574 return 0;
575 return Arg;
576 }
577
Dan Gohman0daef3d2012-05-08 23:39:44 +0000578 // If we found an identifiable object but it has multiple uses, but they are
579 // trivial uses, we can still consider this to be a single-use value.
John McCall9fbd3182011-06-15 23:37:01 +0000580 if (IsObjCIdentifiedObject(Arg)) {
581 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
582 UI != UE; ++UI) {
583 const User *U = *UI;
584 if (!U->use_empty() || StripPointerCastsAndObjCCalls(U) != Arg)
585 return 0;
586 }
587
588 return Arg;
589 }
590
591 return 0;
592}
593
Michael Gottesman81c61212013-01-14 00:35:14 +0000594/// \brief Test if the given module looks interesting to run ARC optimization
595/// on.
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000596static bool ModuleHasARC(const Module &M) {
597 return
598 M.getNamedValue("objc_retain") ||
599 M.getNamedValue("objc_release") ||
600 M.getNamedValue("objc_autorelease") ||
601 M.getNamedValue("objc_retainAutoreleasedReturnValue") ||
602 M.getNamedValue("objc_retainBlock") ||
603 M.getNamedValue("objc_autoreleaseReturnValue") ||
604 M.getNamedValue("objc_autoreleasePoolPush") ||
605 M.getNamedValue("objc_loadWeakRetained") ||
606 M.getNamedValue("objc_loadWeak") ||
607 M.getNamedValue("objc_destroyWeak") ||
608 M.getNamedValue("objc_storeWeak") ||
609 M.getNamedValue("objc_initWeak") ||
610 M.getNamedValue("objc_moveWeak") ||
611 M.getNamedValue("objc_copyWeak") ||
612 M.getNamedValue("objc_retainedObject") ||
613 M.getNamedValue("objc_unretainedObject") ||
614 M.getNamedValue("objc_unretainedPointer");
615}
616
Michael Gottesman7899e472013-01-14 01:47:53 +0000617/// \brief Test whether the given pointer, which is an Objective C block
618/// pointer, does not "escape".
Michael Gottesman81c61212013-01-14 00:35:14 +0000619///
620/// This differs from regular escape analysis in that a use as an
621/// argument to a call is not considered an escape.
622///
Dan Gohman79522dc2012-01-13 00:39:07 +0000623static bool DoesObjCBlockEscape(const Value *BlockPtr) {
Michael Gottesman981308c2013-01-13 07:47:32 +0000624
625 DEBUG(dbgs() << "DoesObjCBlockEscape: Target: " << *BlockPtr << "\n");
626
Dan Gohman79522dc2012-01-13 00:39:07 +0000627 // Walk the def-use chains.
628 SmallVector<const Value *, 4> Worklist;
629 Worklist.push_back(BlockPtr);
Michael Gottesman6056b852013-01-13 22:12:06 +0000630
631 // Ensure we do not visit any value twice.
632 SmallPtrSet<const Value *, 4> VisitedSet;
633
Dan Gohman79522dc2012-01-13 00:39:07 +0000634 do {
635 const Value *V = Worklist.pop_back_val();
Michael Gottesman981308c2013-01-13 07:47:32 +0000636
637 DEBUG(dbgs() << "DoesObjCBlockEscape: Visiting: " << *V << "\n");
638
Dan Gohman79522dc2012-01-13 00:39:07 +0000639 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
640 UI != UE; ++UI) {
641 const User *UUser = *UI;
Michael Gottesman981308c2013-01-13 07:47:32 +0000642
643 DEBUG(dbgs() << "DoesObjCBlockEscape: User: " << *UUser << "\n");
644
Dan Gohman79522dc2012-01-13 00:39:07 +0000645 // Special - Use by a call (callee or argument) is not considered
646 // to be an escape.
Dan Gohman44234772012-04-13 18:28:58 +0000647 switch (GetBasicInstructionClass(UUser)) {
648 case IC_StoreWeak:
649 case IC_InitWeak:
650 case IC_StoreStrong:
651 case IC_Autorelease:
Michael Gottesman981308c2013-01-13 07:47:32 +0000652 case IC_AutoreleaseRV: {
653 DEBUG(dbgs() << "DoesObjCBlockEscape: User copies pointer arguments. "
654 "Block Escapes!\n");
Dan Gohman44234772012-04-13 18:28:58 +0000655 // These special functions make copies of their pointer arguments.
656 return true;
Michael Gottesman981308c2013-01-13 07:47:32 +0000657 }
Dan Gohman44234772012-04-13 18:28:58 +0000658 case IC_User:
659 case IC_None:
660 // Use by an instruction which copies the value is an escape if the
661 // result is an escape.
662 if (isa<BitCastInst>(UUser) || isa<GetElementPtrInst>(UUser) ||
663 isa<PHINode>(UUser) || isa<SelectInst>(UUser)) {
Michael Gottesman6056b852013-01-13 22:12:06 +0000664
Michael Gottesmanf3c13352013-01-14 19:18:39 +0000665 if (!VisitedSet.insert(UUser)) {
Michael Gottesman7899e472013-01-14 01:47:53 +0000666 DEBUG(dbgs() << "DoesObjCBlockEscape: User copies value. Escapes "
667 "if result escapes. Adding to list.\n");
Michael Gottesman6056b852013-01-13 22:12:06 +0000668 Worklist.push_back(UUser);
669 } else {
670 DEBUG(dbgs() << "DoesObjCBlockEscape: Already visited node.\n");
671 }
Dan Gohman44234772012-04-13 18:28:58 +0000672 continue;
673 }
674 // Use by a load is not an escape.
675 if (isa<LoadInst>(UUser))
676 continue;
677 // Use by a store is not an escape if the use is the address.
678 if (const StoreInst *SI = dyn_cast<StoreInst>(UUser))
679 if (V != SI->getValueOperand())
680 continue;
681 break;
682 default:
683 // Regular calls and other stuff are not considered escapes.
Dan Gohman79522dc2012-01-13 00:39:07 +0000684 continue;
685 }
Dan Gohmana3b08d62012-02-13 22:57:02 +0000686 // Otherwise, conservatively assume an escape.
Michael Gottesman981308c2013-01-13 07:47:32 +0000687 DEBUG(dbgs() << "DoesObjCBlockEscape: Assuming block escapes.\n");
Dan Gohman79522dc2012-01-13 00:39:07 +0000688 return true;
689 }
690 } while (!Worklist.empty());
691
692 // No escapes found.
Michael Gottesman981308c2013-01-13 07:47:32 +0000693 DEBUG(dbgs() << "DoesObjCBlockEscape: Block does not escape.\n");
Dan Gohman79522dc2012-01-13 00:39:07 +0000694 return false;
695}
696
Michael Gottesman81c61212013-01-14 00:35:14 +0000697/// @}
698///
Michael Gottesman7899e472013-01-14 01:47:53 +0000699/// \defgroup ARCAA Extends alias analysis using ObjC specific knowledge.
Michael Gottesman81c61212013-01-14 00:35:14 +0000700/// @{
John McCall9fbd3182011-06-15 23:37:01 +0000701
John McCall9fbd3182011-06-15 23:37:01 +0000702#include "llvm/Analysis/AliasAnalysis.h"
703#include "llvm/Analysis/Passes.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +0000704#include "llvm/Pass.h"
John McCall9fbd3182011-06-15 23:37:01 +0000705
706namespace {
Michael Gottesman81c61212013-01-14 00:35:14 +0000707 /// \brief This is a simple alias analysis implementation that uses knowledge
708 /// of ARC constructs to answer queries.
John McCall9fbd3182011-06-15 23:37:01 +0000709 ///
710 /// TODO: This class could be generalized to know about other ObjC-specific
711 /// tricks. Such as knowing that ivars in the non-fragile ABI are non-aliasing
712 /// even though their offsets are dynamic.
713 class ObjCARCAliasAnalysis : public ImmutablePass,
714 public AliasAnalysis {
715 public:
716 static char ID; // Class identification, replacement for typeinfo
717 ObjCARCAliasAnalysis() : ImmutablePass(ID) {
718 initializeObjCARCAliasAnalysisPass(*PassRegistry::getPassRegistry());
719 }
720
721 private:
722 virtual void initializePass() {
723 InitializeAliasAnalysis(this);
724 }
725
Michael Gottesman81c61212013-01-14 00:35:14 +0000726 /// This method is used when a pass implements an analysis interface through
727 /// multiple inheritance. If needed, it should override this to adjust the
728 /// this pointer as needed for the specified pass info.
John McCall9fbd3182011-06-15 23:37:01 +0000729 virtual void *getAdjustedAnalysisPointer(const void *PI) {
730 if (PI == &AliasAnalysis::ID)
Dan Gohman447989c2012-04-27 18:56:31 +0000731 return static_cast<AliasAnalysis *>(this);
John McCall9fbd3182011-06-15 23:37:01 +0000732 return this;
733 }
734
735 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
736 virtual AliasResult alias(const Location &LocA, const Location &LocB);
737 virtual bool pointsToConstantMemory(const Location &Loc, bool OrLocal);
738 virtual ModRefBehavior getModRefBehavior(ImmutableCallSite CS);
739 virtual ModRefBehavior getModRefBehavior(const Function *F);
740 virtual ModRefResult getModRefInfo(ImmutableCallSite CS,
741 const Location &Loc);
742 virtual ModRefResult getModRefInfo(ImmutableCallSite CS1,
743 ImmutableCallSite CS2);
744 };
745} // End of anonymous namespace
746
747// Register this pass...
748char ObjCARCAliasAnalysis::ID = 0;
749INITIALIZE_AG_PASS(ObjCARCAliasAnalysis, AliasAnalysis, "objc-arc-aa",
750 "ObjC-ARC-Based Alias Analysis", false, true, false)
751
752ImmutablePass *llvm::createObjCARCAliasAnalysisPass() {
753 return new ObjCARCAliasAnalysis();
754}
755
756void
757ObjCARCAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
758 AU.setPreservesAll();
759 AliasAnalysis::getAnalysisUsage(AU);
760}
761
762AliasAnalysis::AliasResult
763ObjCARCAliasAnalysis::alias(const Location &LocA, const Location &LocB) {
764 if (!EnableARCOpts)
765 return AliasAnalysis::alias(LocA, LocB);
766
767 // First, strip off no-ops, including ObjC-specific no-ops, and try making a
768 // precise alias query.
769 const Value *SA = StripPointerCastsAndObjCCalls(LocA.Ptr);
770 const Value *SB = StripPointerCastsAndObjCCalls(LocB.Ptr);
771 AliasResult Result =
772 AliasAnalysis::alias(Location(SA, LocA.Size, LocA.TBAATag),
773 Location(SB, LocB.Size, LocB.TBAATag));
774 if (Result != MayAlias)
775 return Result;
776
777 // If that failed, climb to the underlying object, including climbing through
778 // ObjC-specific no-ops, and try making an imprecise alias query.
779 const Value *UA = GetUnderlyingObjCPtr(SA);
780 const Value *UB = GetUnderlyingObjCPtr(SB);
781 if (UA != SA || UB != SB) {
782 Result = AliasAnalysis::alias(Location(UA), Location(UB));
783 // We can't use MustAlias or PartialAlias results here because
784 // GetUnderlyingObjCPtr may return an offsetted pointer value.
785 if (Result == NoAlias)
786 return NoAlias;
787 }
788
789 // If that failed, fail. We don't need to chain here, since that's covered
790 // by the earlier precise query.
791 return MayAlias;
792}
793
794bool
795ObjCARCAliasAnalysis::pointsToConstantMemory(const Location &Loc,
796 bool OrLocal) {
797 if (!EnableARCOpts)
798 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
799
800 // First, strip off no-ops, including ObjC-specific no-ops, and try making
801 // a precise alias query.
802 const Value *S = StripPointerCastsAndObjCCalls(Loc.Ptr);
803 if (AliasAnalysis::pointsToConstantMemory(Location(S, Loc.Size, Loc.TBAATag),
804 OrLocal))
805 return true;
806
807 // If that failed, climb to the underlying object, including climbing through
808 // ObjC-specific no-ops, and try making an imprecise alias query.
809 const Value *U = GetUnderlyingObjCPtr(S);
810 if (U != S)
811 return AliasAnalysis::pointsToConstantMemory(Location(U), OrLocal);
812
813 // If that failed, fail. We don't need to chain here, since that's covered
814 // by the earlier precise query.
815 return false;
816}
817
818AliasAnalysis::ModRefBehavior
819ObjCARCAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
820 // We have nothing to do. Just chain to the next AliasAnalysis.
821 return AliasAnalysis::getModRefBehavior(CS);
822}
823
824AliasAnalysis::ModRefBehavior
825ObjCARCAliasAnalysis::getModRefBehavior(const Function *F) {
826 if (!EnableARCOpts)
827 return AliasAnalysis::getModRefBehavior(F);
828
829 switch (GetFunctionClass(F)) {
830 case IC_NoopCast:
831 return DoesNotAccessMemory;
832 default:
833 break;
834 }
835
836 return AliasAnalysis::getModRefBehavior(F);
837}
838
839AliasAnalysis::ModRefResult
840ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS, const Location &Loc) {
841 if (!EnableARCOpts)
842 return AliasAnalysis::getModRefInfo(CS, Loc);
843
844 switch (GetBasicInstructionClass(CS.getInstruction())) {
845 case IC_Retain:
846 case IC_RetainRV:
John McCall9fbd3182011-06-15 23:37:01 +0000847 case IC_Autorelease:
848 case IC_AutoreleaseRV:
849 case IC_NoopCast:
850 case IC_AutoreleasepoolPush:
851 case IC_FusedRetainAutorelease:
852 case IC_FusedRetainAutoreleaseRV:
853 // These functions don't access any memory visible to the compiler.
Benjamin Kramerd9b0b022012-06-02 10:20:22 +0000854 // Note that this doesn't include objc_retainBlock, because it updates
Dan Gohman21104822011-09-14 18:13:00 +0000855 // pointers when it copies block data.
John McCall9fbd3182011-06-15 23:37:01 +0000856 return NoModRef;
857 default:
858 break;
859 }
860
861 return AliasAnalysis::getModRefInfo(CS, Loc);
862}
863
864AliasAnalysis::ModRefResult
865ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
866 ImmutableCallSite CS2) {
867 // TODO: Theoretically we could check for dependencies between objc_* calls
868 // and OnlyAccessesArgumentPointees calls or other well-behaved calls.
869 return AliasAnalysis::getModRefInfo(CS1, CS2);
870}
871
Michael Gottesman81c61212013-01-14 00:35:14 +0000872/// @}
873///
874/// \defgroup ARCExpansion Early ARC Optimizations.
875/// @{
John McCall9fbd3182011-06-15 23:37:01 +0000876
877#include "llvm/Support/InstIterator.h"
878#include "llvm/Transforms/Scalar.h"
879
880namespace {
Michael Gottesman81c61212013-01-14 00:35:14 +0000881 /// \brief Early ARC transformations.
John McCall9fbd3182011-06-15 23:37:01 +0000882 class ObjCARCExpand : public FunctionPass {
883 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000884 virtual bool doInitialization(Module &M);
John McCall9fbd3182011-06-15 23:37:01 +0000885 virtual bool runOnFunction(Function &F);
886
Michael Gottesman81c61212013-01-14 00:35:14 +0000887 /// A flag indicating whether this optimization pass should run.
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000888 bool Run;
889
John McCall9fbd3182011-06-15 23:37:01 +0000890 public:
891 static char ID;
892 ObjCARCExpand() : FunctionPass(ID) {
893 initializeObjCARCExpandPass(*PassRegistry::getPassRegistry());
894 }
895 };
896}
897
898char ObjCARCExpand::ID = 0;
899INITIALIZE_PASS(ObjCARCExpand,
900 "objc-arc-expand", "ObjC ARC expansion", false, false)
901
902Pass *llvm::createObjCARCExpandPass() {
903 return new ObjCARCExpand();
904}
905
906void ObjCARCExpand::getAnalysisUsage(AnalysisUsage &AU) const {
907 AU.setPreservesCFG();
908}
909
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000910bool ObjCARCExpand::doInitialization(Module &M) {
911 Run = ModuleHasARC(M);
912 return false;
913}
914
John McCall9fbd3182011-06-15 23:37:01 +0000915bool ObjCARCExpand::runOnFunction(Function &F) {
916 if (!EnableARCOpts)
917 return false;
918
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000919 // If nothing in the Module uses ARC, don't do anything.
920 if (!Run)
921 return false;
922
John McCall9fbd3182011-06-15 23:37:01 +0000923 bool Changed = false;
924
Michael Gottesmancf140052013-01-13 07:00:51 +0000925 DEBUG(dbgs() << "ObjCARCExpand: Visiting Function: " << F.getName() << "\n");
926
John McCall9fbd3182011-06-15 23:37:01 +0000927 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
928 Instruction *Inst = &*I;
Michael Gottesman2f1bfc42013-01-07 21:26:07 +0000929
Michael Gottesman8f22c8b2013-01-01 16:05:48 +0000930 DEBUG(dbgs() << "ObjCARCExpand: Visiting: " << *Inst << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +0000931
John McCall9fbd3182011-06-15 23:37:01 +0000932 switch (GetBasicInstructionClass(Inst)) {
933 case IC_Retain:
934 case IC_RetainRV:
935 case IC_Autorelease:
936 case IC_AutoreleaseRV:
937 case IC_FusedRetainAutorelease:
Michael Gottesmana6e23cc2013-01-01 16:05:54 +0000938 case IC_FusedRetainAutoreleaseRV: {
John McCall9fbd3182011-06-15 23:37:01 +0000939 // These calls return their argument verbatim, as a low-level
940 // optimization. However, this makes high-level optimizations
941 // harder. Undo any uses of this optimization that the front-end
Dan Gohmand6bf2012012-04-13 18:57:48 +0000942 // emitted here. We'll redo them in the contract pass.
John McCall9fbd3182011-06-15 23:37:01 +0000943 Changed = true;
Michael Gottesmana6e23cc2013-01-01 16:05:54 +0000944 Value *Value = cast<CallInst>(Inst)->getArgOperand(0);
945 DEBUG(dbgs() << "ObjCARCExpand: Old = " << *Inst << "\n"
946 " New = " << *Value << "\n");
947 Inst->replaceAllUsesWith(Value);
John McCall9fbd3182011-06-15 23:37:01 +0000948 break;
Michael Gottesmana6e23cc2013-01-01 16:05:54 +0000949 }
John McCall9fbd3182011-06-15 23:37:01 +0000950 default:
951 break;
952 }
953 }
Michael Gottesman2f1bfc42013-01-07 21:26:07 +0000954
Michael Gottesmanec21e2a2013-01-03 08:09:27 +0000955 DEBUG(dbgs() << "ObjCARCExpand: Finished List.\n\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +0000956
John McCall9fbd3182011-06-15 23:37:01 +0000957 return Changed;
958}
959
Michael Gottesman81c61212013-01-14 00:35:14 +0000960/// @}
961///
962/// \defgroup ARCAPElim ARC Autorelease Pool Elimination.
963/// @{
Dan Gohman2f6263c2012-01-17 20:52:24 +0000964
Dan Gohman0daef3d2012-05-08 23:39:44 +0000965#include "llvm/ADT/STLExtras.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +0000966#include "llvm/IR/Constants.h"
Dan Gohman1dae3e92012-01-18 21:19:38 +0000967
Dan Gohman2f6263c2012-01-17 20:52:24 +0000968namespace {
Michael Gottesman81c61212013-01-14 00:35:14 +0000969 /// \brief Autorelease pool elimination.
Dan Gohman2f6263c2012-01-17 20:52:24 +0000970 class ObjCARCAPElim : public ModulePass {
971 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
972 virtual bool runOnModule(Module &M);
973
Dan Gohman447989c2012-04-27 18:56:31 +0000974 static bool MayAutorelease(ImmutableCallSite CS, unsigned Depth = 0);
975 static bool OptimizeBB(BasicBlock *BB);
Dan Gohman2f6263c2012-01-17 20:52:24 +0000976
977 public:
978 static char ID;
979 ObjCARCAPElim() : ModulePass(ID) {
980 initializeObjCARCAPElimPass(*PassRegistry::getPassRegistry());
981 }
982 };
983}
984
985char ObjCARCAPElim::ID = 0;
986INITIALIZE_PASS(ObjCARCAPElim,
987 "objc-arc-apelim",
988 "ObjC ARC autorelease pool elimination",
989 false, false)
990
991Pass *llvm::createObjCARCAPElimPass() {
992 return new ObjCARCAPElim();
993}
994
995void ObjCARCAPElim::getAnalysisUsage(AnalysisUsage &AU) const {
996 AU.setPreservesCFG();
997}
998
Michael Gottesman81c61212013-01-14 00:35:14 +0000999/// Interprocedurally determine if calls made by the given call site can
1000/// possibly produce autoreleases.
Dan Gohman447989c2012-04-27 18:56:31 +00001001bool ObjCARCAPElim::MayAutorelease(ImmutableCallSite CS, unsigned Depth) {
1002 if (const Function *Callee = CS.getCalledFunction()) {
Dan Gohman2f6263c2012-01-17 20:52:24 +00001003 if (Callee->isDeclaration() || Callee->mayBeOverridden())
1004 return true;
Dan Gohman447989c2012-04-27 18:56:31 +00001005 for (Function::const_iterator I = Callee->begin(), E = Callee->end();
Dan Gohman2f6263c2012-01-17 20:52:24 +00001006 I != E; ++I) {
Dan Gohman447989c2012-04-27 18:56:31 +00001007 const BasicBlock *BB = I;
1008 for (BasicBlock::const_iterator J = BB->begin(), F = BB->end();
1009 J != F; ++J)
1010 if (ImmutableCallSite JCS = ImmutableCallSite(J))
Dan Gohman2f77bbd2012-01-18 21:24:45 +00001011 // This recursion depth limit is arbitrary. It's just great
1012 // enough to cover known interesting testcases.
1013 if (Depth < 3 &&
1014 !JCS.onlyReadsMemory() &&
1015 MayAutorelease(JCS, Depth + 1))
Dan Gohman2f6263c2012-01-17 20:52:24 +00001016 return true;
1017 }
1018 return false;
1019 }
1020
1021 return true;
1022}
1023
1024bool ObjCARCAPElim::OptimizeBB(BasicBlock *BB) {
1025 bool Changed = false;
1026
1027 Instruction *Push = 0;
1028 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1029 Instruction *Inst = I++;
1030 switch (GetBasicInstructionClass(Inst)) {
1031 case IC_AutoreleasepoolPush:
1032 Push = Inst;
1033 break;
1034 case IC_AutoreleasepoolPop:
1035 // If this pop matches a push and nothing in between can autorelease,
1036 // zap the pair.
1037 if (Push && cast<CallInst>(Inst)->getArgOperand(0) == Push) {
1038 Changed = true;
Michael Gottesman7899e472013-01-14 01:47:53 +00001039 DEBUG(dbgs() << "ObjCARCAPElim::OptimizeBB: Zapping push pop "
1040 "autorelease pair:\n"
1041 " Pop: " << *Inst << "\n"
Michael Gottesmandf379f42013-01-03 08:09:17 +00001042 << " Push: " << *Push << "\n");
Dan Gohman2f6263c2012-01-17 20:52:24 +00001043 Inst->eraseFromParent();
1044 Push->eraseFromParent();
1045 }
1046 Push = 0;
1047 break;
1048 case IC_CallOrUser:
Dan Gohman447989c2012-04-27 18:56:31 +00001049 if (MayAutorelease(ImmutableCallSite(Inst)))
Dan Gohman2f6263c2012-01-17 20:52:24 +00001050 Push = 0;
1051 break;
1052 default:
1053 break;
1054 }
1055 }
1056
1057 return Changed;
1058}
1059
1060bool ObjCARCAPElim::runOnModule(Module &M) {
1061 if (!EnableARCOpts)
1062 return false;
1063
1064 // If nothing in the Module uses ARC, don't do anything.
1065 if (!ModuleHasARC(M))
1066 return false;
1067
Dan Gohman1dae3e92012-01-18 21:19:38 +00001068 // Find the llvm.global_ctors variable, as the first step in
Dan Gohmand6bf2012012-04-13 18:57:48 +00001069 // identifying the global constructors. In theory, unnecessary autorelease
1070 // pools could occur anywhere, but in practice it's pretty rare. Global
1071 // ctors are a place where autorelease pools get inserted automatically,
1072 // so it's pretty common for them to be unnecessary, and it's pretty
1073 // profitable to eliminate them.
Dan Gohman1dae3e92012-01-18 21:19:38 +00001074 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1075 if (!GV)
1076 return false;
1077
1078 assert(GV->hasDefinitiveInitializer() &&
1079 "llvm.global_ctors is uncooperative!");
1080
Dan Gohman2f6263c2012-01-17 20:52:24 +00001081 bool Changed = false;
1082
Dan Gohman1dae3e92012-01-18 21:19:38 +00001083 // Dig the constructor functions out of GV's initializer.
1084 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
1085 for (User::op_iterator OI = Init->op_begin(), OE = Init->op_end();
1086 OI != OE; ++OI) {
1087 Value *Op = *OI;
1088 // llvm.global_ctors is an array of pairs where the second members
1089 // are constructor functions.
Dan Gohman3b5b2a22012-04-18 22:24:33 +00001090 Function *F = dyn_cast<Function>(cast<ConstantStruct>(Op)->getOperand(1));
1091 // If the user used a constructor function with the wrong signature and
1092 // it got bitcasted or whatever, look the other way.
1093 if (!F)
1094 continue;
Dan Gohman2f6263c2012-01-17 20:52:24 +00001095 // Only look at function definitions.
1096 if (F->isDeclaration())
1097 continue;
Dan Gohman2f6263c2012-01-17 20:52:24 +00001098 // Only look at functions with one basic block.
1099 if (llvm::next(F->begin()) != F->end())
1100 continue;
1101 // Ok, a single-block constructor function definition. Try to optimize it.
1102 Changed |= OptimizeBB(F->begin());
1103 }
1104
1105 return Changed;
1106}
1107
Michael Gottesman81c61212013-01-14 00:35:14 +00001108/// @}
1109///
1110/// \defgroup ARCOpt ARC Optimization.
1111/// @{
John McCall9fbd3182011-06-15 23:37:01 +00001112
1113// TODO: On code like this:
1114//
1115// objc_retain(%x)
1116// stuff_that_cannot_release()
1117// objc_autorelease(%x)
1118// stuff_that_cannot_release()
1119// objc_retain(%x)
1120// stuff_that_cannot_release()
1121// objc_autorelease(%x)
1122//
1123// The second retain and autorelease can be deleted.
1124
1125// TODO: It should be possible to delete
1126// objc_autoreleasePoolPush and objc_autoreleasePoolPop
1127// pairs if nothing is actually autoreleased between them. Also, autorelease
1128// calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
1129// after inlining) can be turned into plain release calls.
1130
1131// TODO: Critical-edge splitting. If the optimial insertion point is
1132// a critical edge, the current algorithm has to fail, because it doesn't
1133// know how to split edges. It should be possible to make the optimizer
1134// think in terms of edges, rather than blocks, and then split critical
1135// edges on demand.
1136
1137// TODO: OptimizeSequences could generalized to be Interprocedural.
1138
1139// TODO: Recognize that a bunch of other objc runtime calls have
1140// non-escaping arguments and non-releasing arguments, and may be
1141// non-autoreleasing.
1142
1143// TODO: Sink autorelease calls as far as possible. Unfortunately we
1144// usually can't sink them past other calls, which would be the main
1145// case where it would be useful.
1146
Dan Gohmane6d5e882011-08-19 00:26:36 +00001147// TODO: The pointer returned from objc_loadWeakRetained is retained.
1148
1149// TODO: Delete release+retain pairs (rare).
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00001150
Chandler Carruthd04a8d42012-12-03 16:50:05 +00001151#include "llvm/ADT/SmallPtrSet.h"
1152#include "llvm/ADT/Statistic.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +00001153#include "llvm/IR/LLVMContext.h"
John McCall9fbd3182011-06-15 23:37:01 +00001154#include "llvm/Support/CFG.h"
John McCall9fbd3182011-06-15 23:37:01 +00001155
1156STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
1157STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
1158STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
1159STATISTIC(NumRets, "Number of return value forwarding "
1160 "retain+autoreleaes eliminated");
1161STATISTIC(NumRRs, "Number of retain+release paths eliminated");
1162STATISTIC(NumPeeps, "Number of calls peephole-optimized");
1163
1164namespace {
Michael Gottesman81c61212013-01-14 00:35:14 +00001165 /// \brief This is similar to BasicAliasAnalysis, and it uses many of the same
1166 /// techniques, except it uses special ObjC-specific reasoning about pointer
1167 /// relationships.
John McCall9fbd3182011-06-15 23:37:01 +00001168 class ProvenanceAnalysis {
1169 AliasAnalysis *AA;
1170
1171 typedef std::pair<const Value *, const Value *> ValuePairTy;
1172 typedef DenseMap<ValuePairTy, bool> CachedResultsTy;
1173 CachedResultsTy CachedResults;
1174
1175 bool relatedCheck(const Value *A, const Value *B);
1176 bool relatedSelect(const SelectInst *A, const Value *B);
1177 bool relatedPHI(const PHINode *A, const Value *B);
1178
Craig Topperc2945e42012-09-18 02:01:41 +00001179 void operator=(const ProvenanceAnalysis &) LLVM_DELETED_FUNCTION;
1180 ProvenanceAnalysis(const ProvenanceAnalysis &) LLVM_DELETED_FUNCTION;
John McCall9fbd3182011-06-15 23:37:01 +00001181
1182 public:
1183 ProvenanceAnalysis() {}
1184
1185 void setAA(AliasAnalysis *aa) { AA = aa; }
1186
1187 AliasAnalysis *getAA() const { return AA; }
1188
1189 bool related(const Value *A, const Value *B);
1190
1191 void clear() {
1192 CachedResults.clear();
1193 }
1194 };
1195}
1196
1197bool ProvenanceAnalysis::relatedSelect(const SelectInst *A, const Value *B) {
1198 // If the values are Selects with the same condition, we can do a more precise
1199 // check: just check for relations between the values on corresponding arms.
1200 if (const SelectInst *SB = dyn_cast<SelectInst>(B))
Dan Gohman447989c2012-04-27 18:56:31 +00001201 if (A->getCondition() == SB->getCondition())
1202 return related(A->getTrueValue(), SB->getTrueValue()) ||
1203 related(A->getFalseValue(), SB->getFalseValue());
John McCall9fbd3182011-06-15 23:37:01 +00001204
1205 // Check both arms of the Select node individually.
Dan Gohman447989c2012-04-27 18:56:31 +00001206 return related(A->getTrueValue(), B) ||
1207 related(A->getFalseValue(), B);
John McCall9fbd3182011-06-15 23:37:01 +00001208}
1209
1210bool ProvenanceAnalysis::relatedPHI(const PHINode *A, const Value *B) {
1211 // If the values are PHIs in the same block, we can do a more precise as well
1212 // as efficient check: just check for relations between the values on
1213 // corresponding edges.
1214 if (const PHINode *PNB = dyn_cast<PHINode>(B))
1215 if (PNB->getParent() == A->getParent()) {
1216 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i)
1217 if (related(A->getIncomingValue(i),
1218 PNB->getIncomingValueForBlock(A->getIncomingBlock(i))))
1219 return true;
1220 return false;
1221 }
1222
1223 // Check each unique source of the PHI node against B.
1224 SmallPtrSet<const Value *, 4> UniqueSrc;
1225 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i) {
1226 const Value *PV1 = A->getIncomingValue(i);
1227 if (UniqueSrc.insert(PV1) && related(PV1, B))
1228 return true;
1229 }
1230
1231 // All of the arms checked out.
1232 return false;
1233}
1234
Michael Gottesman81c61212013-01-14 00:35:14 +00001235/// Test if the value of P, or any value covered by its provenance, is ever
1236/// stored within the function (not counting callees).
John McCall9fbd3182011-06-15 23:37:01 +00001237static bool isStoredObjCPointer(const Value *P) {
1238 SmallPtrSet<const Value *, 8> Visited;
1239 SmallVector<const Value *, 8> Worklist;
1240 Worklist.push_back(P);
1241 Visited.insert(P);
1242 do {
1243 P = Worklist.pop_back_val();
1244 for (Value::const_use_iterator UI = P->use_begin(), UE = P->use_end();
1245 UI != UE; ++UI) {
1246 const User *Ur = *UI;
1247 if (isa<StoreInst>(Ur)) {
1248 if (UI.getOperandNo() == 0)
1249 // The pointer is stored.
1250 return true;
1251 // The pointed is stored through.
1252 continue;
1253 }
1254 if (isa<CallInst>(Ur))
1255 // The pointer is passed as an argument, ignore this.
1256 continue;
1257 if (isa<PtrToIntInst>(P))
1258 // Assume the worst.
1259 return true;
1260 if (Visited.insert(Ur))
1261 Worklist.push_back(Ur);
1262 }
1263 } while (!Worklist.empty());
1264
1265 // Everything checked out.
1266 return false;
1267}
1268
1269bool ProvenanceAnalysis::relatedCheck(const Value *A, const Value *B) {
1270 // Skip past provenance pass-throughs.
1271 A = GetUnderlyingObjCPtr(A);
1272 B = GetUnderlyingObjCPtr(B);
1273
1274 // Quick check.
1275 if (A == B)
1276 return true;
1277
1278 // Ask regular AliasAnalysis, for a first approximation.
1279 switch (AA->alias(A, B)) {
1280 case AliasAnalysis::NoAlias:
1281 return false;
1282 case AliasAnalysis::MustAlias:
1283 case AliasAnalysis::PartialAlias:
1284 return true;
1285 case AliasAnalysis::MayAlias:
1286 break;
1287 }
1288
1289 bool AIsIdentified = IsObjCIdentifiedObject(A);
1290 bool BIsIdentified = IsObjCIdentifiedObject(B);
1291
1292 // An ObjC-Identified object can't alias a load if it is never locally stored.
1293 if (AIsIdentified) {
Dan Gohman230768b2012-09-04 23:16:20 +00001294 // Check for an obvious escape.
1295 if (isa<LoadInst>(B))
1296 return isStoredObjCPointer(A);
John McCall9fbd3182011-06-15 23:37:01 +00001297 if (BIsIdentified) {
Dan Gohman230768b2012-09-04 23:16:20 +00001298 // Check for an obvious escape.
1299 if (isa<LoadInst>(A))
1300 return isStoredObjCPointer(B);
1301 // Both pointers are identified and escapes aren't an evident problem.
1302 return false;
John McCall9fbd3182011-06-15 23:37:01 +00001303 }
Dan Gohman230768b2012-09-04 23:16:20 +00001304 } else if (BIsIdentified) {
1305 // Check for an obvious escape.
1306 if (isa<LoadInst>(A))
John McCall9fbd3182011-06-15 23:37:01 +00001307 return isStoredObjCPointer(B);
1308 }
1309
1310 // Special handling for PHI and Select.
1311 if (const PHINode *PN = dyn_cast<PHINode>(A))
1312 return relatedPHI(PN, B);
1313 if (const PHINode *PN = dyn_cast<PHINode>(B))
1314 return relatedPHI(PN, A);
1315 if (const SelectInst *S = dyn_cast<SelectInst>(A))
1316 return relatedSelect(S, B);
1317 if (const SelectInst *S = dyn_cast<SelectInst>(B))
1318 return relatedSelect(S, A);
1319
1320 // Conservative.
1321 return true;
1322}
1323
1324bool ProvenanceAnalysis::related(const Value *A, const Value *B) {
1325 // Begin by inserting a conservative value into the map. If the insertion
1326 // fails, we have the answer already. If it succeeds, leave it there until we
1327 // compute the real answer to guard against recursive queries.
1328 if (A > B) std::swap(A, B);
1329 std::pair<CachedResultsTy::iterator, bool> Pair =
1330 CachedResults.insert(std::make_pair(ValuePairTy(A, B), true));
1331 if (!Pair.second)
1332 return Pair.first->second;
1333
1334 bool Result = relatedCheck(A, B);
1335 CachedResults[ValuePairTy(A, B)] = Result;
1336 return Result;
1337}
1338
1339namespace {
Michael Gottesman81c61212013-01-14 00:35:14 +00001340 /// \enum Sequence
1341 ///
1342 /// \brief A sequence of states that a pointer may go through in which an
1343 /// objc_retain and objc_release are actually needed.
John McCall9fbd3182011-06-15 23:37:01 +00001344 enum Sequence {
1345 S_None,
1346 S_Retain, ///< objc_retain(x)
1347 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement
1348 S_Use, ///< any use of x
1349 S_Stop, ///< like S_Release, but code motion is stopped
1350 S_Release, ///< objc_release(x)
1351 S_MovableRelease ///< objc_release(x), !clang.imprecise_release
1352 };
1353}
1354
1355static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
1356 // The easy cases.
1357 if (A == B)
1358 return A;
1359 if (A == S_None || B == S_None)
1360 return S_None;
1361
John McCall9fbd3182011-06-15 23:37:01 +00001362 if (A > B) std::swap(A, B);
1363 if (TopDown) {
1364 // Choose the side which is further along in the sequence.
Dan Gohmana7f7db22011-08-12 00:26:31 +00001365 if ((A == S_Retain || A == S_CanRelease) &&
1366 (B == S_CanRelease || B == S_Use))
John McCall9fbd3182011-06-15 23:37:01 +00001367 return B;
1368 } else {
1369 // Choose the side which is further along in the sequence.
1370 if ((A == S_Use || A == S_CanRelease) &&
Dan Gohmana7f7db22011-08-12 00:26:31 +00001371 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
John McCall9fbd3182011-06-15 23:37:01 +00001372 return A;
1373 // If both sides are releases, choose the more conservative one.
1374 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
1375 return A;
1376 if (A == S_Release && B == S_MovableRelease)
1377 return A;
1378 }
1379
1380 return S_None;
1381}
1382
1383namespace {
Michael Gottesman81c61212013-01-14 00:35:14 +00001384 /// \brief Unidirectional information about either a
John McCall9fbd3182011-06-15 23:37:01 +00001385 /// retain-decrement-use-release sequence or release-use-decrement-retain
1386 /// reverese sequence.
1387 struct RRInfo {
Michael Gottesman81c61212013-01-14 00:35:14 +00001388 /// After an objc_retain, the reference count of the referenced
Dan Gohmane6d5e882011-08-19 00:26:36 +00001389 /// object is known to be positive. Similarly, before an objc_release, the
1390 /// reference count of the referenced object is known to be positive. If
1391 /// there are retain-release pairs in code regions where the retain count
1392 /// is known to be positive, they can be eliminated, regardless of any side
1393 /// effects between them.
1394 ///
1395 /// Also, a retain+release pair nested within another retain+release
1396 /// pair all on the known same pointer value can be eliminated, regardless
1397 /// of any intervening side effects.
1398 ///
1399 /// KnownSafe is true when either of these conditions is satisfied.
1400 bool KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00001401
Michael Gottesman81c61212013-01-14 00:35:14 +00001402 /// True if the Calls are objc_retainBlock calls (as opposed to objc_retain
1403 /// calls).
John McCall9fbd3182011-06-15 23:37:01 +00001404 bool IsRetainBlock;
1405
Michael Gottesman81c61212013-01-14 00:35:14 +00001406 /// True of the objc_release calls are all marked with the "tail" keyword.
John McCall9fbd3182011-06-15 23:37:01 +00001407 bool IsTailCallRelease;
1408
Michael Gottesman81c61212013-01-14 00:35:14 +00001409 /// If the Calls are objc_release calls and they all have a
1410 /// clang.imprecise_release tag, this is the metadata tag.
John McCall9fbd3182011-06-15 23:37:01 +00001411 MDNode *ReleaseMetadata;
1412
Michael Gottesman81c61212013-01-14 00:35:14 +00001413 /// For a top-down sequence, the set of objc_retains or
John McCall9fbd3182011-06-15 23:37:01 +00001414 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
1415 SmallPtrSet<Instruction *, 2> Calls;
1416
Michael Gottesman81c61212013-01-14 00:35:14 +00001417 /// The set of optimal insert positions for moving calls in the opposite
1418 /// sequence.
John McCall9fbd3182011-06-15 23:37:01 +00001419 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
1420
1421 RRInfo() :
Dan Gohman79522dc2012-01-13 00:39:07 +00001422 KnownSafe(false), IsRetainBlock(false),
Dan Gohman50ade652012-04-25 00:50:46 +00001423 IsTailCallRelease(false),
John McCall9fbd3182011-06-15 23:37:01 +00001424 ReleaseMetadata(0) {}
1425
1426 void clear();
1427 };
1428}
1429
1430void RRInfo::clear() {
Dan Gohmane6d5e882011-08-19 00:26:36 +00001431 KnownSafe = false;
John McCall9fbd3182011-06-15 23:37:01 +00001432 IsRetainBlock = false;
1433 IsTailCallRelease = false;
1434 ReleaseMetadata = 0;
1435 Calls.clear();
1436 ReverseInsertPts.clear();
1437}
1438
1439namespace {
Michael Gottesman81c61212013-01-14 00:35:14 +00001440 /// \brief This class summarizes several per-pointer runtime properties which
1441 /// are propogated through the flow graph.
John McCall9fbd3182011-06-15 23:37:01 +00001442 class PtrState {
Michael Gottesman81c61212013-01-14 00:35:14 +00001443 /// True if the reference count is known to be incremented.
Dan Gohman50ade652012-04-25 00:50:46 +00001444 bool KnownPositiveRefCount;
1445
Michael Gottesman81c61212013-01-14 00:35:14 +00001446 /// True of we've seen an opportunity for partial RR elimination, such as
1447 /// pushing calls into a CFG triangle or into one side of a CFG diamond.
Dan Gohman50ade652012-04-25 00:50:46 +00001448 bool Partial;
John McCall9fbd3182011-06-15 23:37:01 +00001449
Michael Gottesman81c61212013-01-14 00:35:14 +00001450 /// The current position in the sequence.
Dan Gohman0daef3d2012-05-08 23:39:44 +00001451 Sequence Seq : 8;
John McCall9fbd3182011-06-15 23:37:01 +00001452
1453 public:
Michael Gottesman81c61212013-01-14 00:35:14 +00001454 /// Unidirectional information about the current sequence.
1455 ///
John McCall9fbd3182011-06-15 23:37:01 +00001456 /// TODO: Encapsulate this better.
1457 RRInfo RRI;
1458
Dan Gohman230768b2012-09-04 23:16:20 +00001459 PtrState() : KnownPositiveRefCount(false), Partial(false),
Dan Gohman0daef3d2012-05-08 23:39:44 +00001460 Seq(S_None) {}
John McCall9fbd3182011-06-15 23:37:01 +00001461
Dan Gohman50ade652012-04-25 00:50:46 +00001462 void SetKnownPositiveRefCount() {
1463 KnownPositiveRefCount = true;
Dan Gohmana7f7db22011-08-12 00:26:31 +00001464 }
1465
Dan Gohman50ade652012-04-25 00:50:46 +00001466 void ClearRefCount() {
1467 KnownPositiveRefCount = false;
John McCall9fbd3182011-06-15 23:37:01 +00001468 }
1469
John McCall9fbd3182011-06-15 23:37:01 +00001470 bool IsKnownIncremented() const {
Dan Gohman50ade652012-04-25 00:50:46 +00001471 return KnownPositiveRefCount;
John McCall9fbd3182011-06-15 23:37:01 +00001472 }
1473
1474 void SetSeq(Sequence NewSeq) {
1475 Seq = NewSeq;
1476 }
1477
John McCall9fbd3182011-06-15 23:37:01 +00001478 Sequence GetSeq() const {
1479 return Seq;
1480 }
1481
1482 void ClearSequenceProgress() {
Dan Gohman50ade652012-04-25 00:50:46 +00001483 ResetSequenceProgress(S_None);
1484 }
1485
1486 void ResetSequenceProgress(Sequence NewSeq) {
1487 Seq = NewSeq;
1488 Partial = false;
John McCall9fbd3182011-06-15 23:37:01 +00001489 RRI.clear();
1490 }
1491
1492 void Merge(const PtrState &Other, bool TopDown);
1493 };
1494}
1495
1496void
1497PtrState::Merge(const PtrState &Other, bool TopDown) {
1498 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
Dan Gohman50ade652012-04-25 00:50:46 +00001499 KnownPositiveRefCount = KnownPositiveRefCount && Other.KnownPositiveRefCount;
John McCall9fbd3182011-06-15 23:37:01 +00001500
1501 // We can't merge a plain objc_retain with an objc_retainBlock.
1502 if (RRI.IsRetainBlock != Other.RRI.IsRetainBlock)
1503 Seq = S_None;
1504
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001505 // If we're not in a sequence (anymore), drop all associated state.
John McCall9fbd3182011-06-15 23:37:01 +00001506 if (Seq == S_None) {
Dan Gohman50ade652012-04-25 00:50:46 +00001507 Partial = false;
John McCall9fbd3182011-06-15 23:37:01 +00001508 RRI.clear();
Dan Gohman50ade652012-04-25 00:50:46 +00001509 } else if (Partial || Other.Partial) {
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001510 // If we're doing a merge on a path that's previously seen a partial
1511 // merge, conservatively drop the sequence, to avoid doing partial
1512 // RR elimination. If the branch predicates for the two merge differ,
1513 // mixing them is unsafe.
Dan Gohman50ade652012-04-25 00:50:46 +00001514 ClearSequenceProgress();
John McCall9fbd3182011-06-15 23:37:01 +00001515 } else {
1516 // Conservatively merge the ReleaseMetadata information.
1517 if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
1518 RRI.ReleaseMetadata = 0;
1519
Dan Gohmane6d5e882011-08-19 00:26:36 +00001520 RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
Dan Gohman0daef3d2012-05-08 23:39:44 +00001521 RRI.IsTailCallRelease = RRI.IsTailCallRelease &&
1522 Other.RRI.IsTailCallRelease;
John McCall9fbd3182011-06-15 23:37:01 +00001523 RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001524
1525 // Merge the insert point sets. If there are any differences,
1526 // that makes this a partial merge.
Dan Gohman0daef3d2012-05-08 23:39:44 +00001527 Partial = RRI.ReverseInsertPts.size() != Other.RRI.ReverseInsertPts.size();
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001528 for (SmallPtrSet<Instruction *, 2>::const_iterator
1529 I = Other.RRI.ReverseInsertPts.begin(),
1530 E = Other.RRI.ReverseInsertPts.end(); I != E; ++I)
Dan Gohman50ade652012-04-25 00:50:46 +00001531 Partial |= RRI.ReverseInsertPts.insert(*I);
John McCall9fbd3182011-06-15 23:37:01 +00001532 }
1533}
1534
1535namespace {
Michael Gottesman81c61212013-01-14 00:35:14 +00001536 /// \brief Per-BasicBlock state.
John McCall9fbd3182011-06-15 23:37:01 +00001537 class BBState {
Michael Gottesman81c61212013-01-14 00:35:14 +00001538 /// The number of unique control paths from the entry which can reach this
1539 /// block.
John McCall9fbd3182011-06-15 23:37:01 +00001540 unsigned TopDownPathCount;
1541
Michael Gottesman81c61212013-01-14 00:35:14 +00001542 /// The number of unique control paths to exits from this block.
John McCall9fbd3182011-06-15 23:37:01 +00001543 unsigned BottomUpPathCount;
1544
Michael Gottesman81c61212013-01-14 00:35:14 +00001545 /// A type for PerPtrTopDown and PerPtrBottomUp.
John McCall9fbd3182011-06-15 23:37:01 +00001546 typedef MapVector<const Value *, PtrState> MapTy;
1547
Michael Gottesman81c61212013-01-14 00:35:14 +00001548 /// The top-down traversal uses this to record information known about a
1549 /// pointer at the bottom of each block.
John McCall9fbd3182011-06-15 23:37:01 +00001550 MapTy PerPtrTopDown;
1551
Michael Gottesman81c61212013-01-14 00:35:14 +00001552 /// The bottom-up traversal uses this to record information known about a
1553 /// pointer at the top of each block.
John McCall9fbd3182011-06-15 23:37:01 +00001554 MapTy PerPtrBottomUp;
1555
Michael Gottesman81c61212013-01-14 00:35:14 +00001556 /// Effective predecessors of the current block ignoring ignorable edges and
1557 /// ignored backedges.
Dan Gohmaneeeb7752012-04-24 22:53:18 +00001558 SmallVector<BasicBlock *, 2> Preds;
Michael Gottesman81c61212013-01-14 00:35:14 +00001559 /// Effective successors of the current block ignoring ignorable edges and
1560 /// ignored backedges.
Dan Gohmaneeeb7752012-04-24 22:53:18 +00001561 SmallVector<BasicBlock *, 2> Succs;
1562
John McCall9fbd3182011-06-15 23:37:01 +00001563 public:
1564 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
1565
1566 typedef MapTy::iterator ptr_iterator;
1567 typedef MapTy::const_iterator ptr_const_iterator;
1568
1569 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
1570 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
1571 ptr_const_iterator top_down_ptr_begin() const {
1572 return PerPtrTopDown.begin();
1573 }
1574 ptr_const_iterator top_down_ptr_end() const {
1575 return PerPtrTopDown.end();
1576 }
1577
1578 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
1579 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
1580 ptr_const_iterator bottom_up_ptr_begin() const {
1581 return PerPtrBottomUp.begin();
1582 }
1583 ptr_const_iterator bottom_up_ptr_end() const {
1584 return PerPtrBottomUp.end();
1585 }
1586
Michael Gottesman81c61212013-01-14 00:35:14 +00001587 /// Mark this block as being an entry block, which has one path from the
1588 /// entry by definition.
John McCall9fbd3182011-06-15 23:37:01 +00001589 void SetAsEntry() { TopDownPathCount = 1; }
1590
Michael Gottesman81c61212013-01-14 00:35:14 +00001591 /// Mark this block as being an exit block, which has one path to an exit by
1592 /// definition.
John McCall9fbd3182011-06-15 23:37:01 +00001593 void SetAsExit() { BottomUpPathCount = 1; }
1594
1595 PtrState &getPtrTopDownState(const Value *Arg) {
1596 return PerPtrTopDown[Arg];
1597 }
1598
1599 PtrState &getPtrBottomUpState(const Value *Arg) {
1600 return PerPtrBottomUp[Arg];
1601 }
1602
1603 void clearBottomUpPointers() {
Evan Chenga81388f2011-08-04 18:40:26 +00001604 PerPtrBottomUp.clear();
John McCall9fbd3182011-06-15 23:37:01 +00001605 }
1606
1607 void clearTopDownPointers() {
1608 PerPtrTopDown.clear();
1609 }
1610
1611 void InitFromPred(const BBState &Other);
1612 void InitFromSucc(const BBState &Other);
1613 void MergePred(const BBState &Other);
1614 void MergeSucc(const BBState &Other);
1615
Michael Gottesman81c61212013-01-14 00:35:14 +00001616 /// Return the number of possible unique paths from an entry to an exit
1617 /// which pass through this block. This is only valid after both the
1618 /// top-down and bottom-up traversals are complete.
John McCall9fbd3182011-06-15 23:37:01 +00001619 unsigned GetAllPathCount() const {
Dan Gohmaneeeb7752012-04-24 22:53:18 +00001620 assert(TopDownPathCount != 0);
1621 assert(BottomUpPathCount != 0);
John McCall9fbd3182011-06-15 23:37:01 +00001622 return TopDownPathCount * BottomUpPathCount;
1623 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00001624
Dan Gohmaneeeb7752012-04-24 22:53:18 +00001625 // Specialized CFG utilities.
Dan Gohman447989c2012-04-27 18:56:31 +00001626 typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
Dan Gohmaneeeb7752012-04-24 22:53:18 +00001627 edge_iterator pred_begin() { return Preds.begin(); }
1628 edge_iterator pred_end() { return Preds.end(); }
1629 edge_iterator succ_begin() { return Succs.begin(); }
1630 edge_iterator succ_end() { return Succs.end(); }
1631
1632 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
1633 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
1634
1635 bool isExit() const { return Succs.empty(); }
John McCall9fbd3182011-06-15 23:37:01 +00001636 };
1637}
1638
1639void BBState::InitFromPred(const BBState &Other) {
1640 PerPtrTopDown = Other.PerPtrTopDown;
1641 TopDownPathCount = Other.TopDownPathCount;
1642}
1643
1644void BBState::InitFromSucc(const BBState &Other) {
1645 PerPtrBottomUp = Other.PerPtrBottomUp;
1646 BottomUpPathCount = Other.BottomUpPathCount;
1647}
1648
Michael Gottesman81c61212013-01-14 00:35:14 +00001649/// The top-down traversal uses this to merge information about predecessors to
1650/// form the initial state for a new block.
John McCall9fbd3182011-06-15 23:37:01 +00001651void BBState::MergePred(const BBState &Other) {
1652 // Other.TopDownPathCount can be 0, in which case it is either dead or a
1653 // loop backedge. Loop backedges are special.
1654 TopDownPathCount += Other.TopDownPathCount;
1655
Michael Gottesman7899e472013-01-14 01:47:53 +00001656 // Check for overflow. If we have overflow, fall back to conservative
1657 // behavior.
Dan Gohman0d1bc5f2012-09-12 20:45:17 +00001658 if (TopDownPathCount < Other.TopDownPathCount) {
1659 clearTopDownPointers();
1660 return;
1661 }
1662
John McCall9fbd3182011-06-15 23:37:01 +00001663 // For each entry in the other set, if our set has an entry with the same key,
1664 // merge the entries. Otherwise, copy the entry and merge it with an empty
1665 // entry.
1666 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
1667 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
1668 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
1669 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1670 /*TopDown=*/true);
1671 }
1672
Dan Gohmanfa7eed12011-08-11 21:06:32 +00001673 // For each entry in our set, if the other set doesn't have an entry with the
John McCall9fbd3182011-06-15 23:37:01 +00001674 // same key, force it to merge with an empty entry.
1675 for (ptr_iterator MI = top_down_ptr_begin(),
1676 ME = top_down_ptr_end(); MI != ME; ++MI)
1677 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
1678 MI->second.Merge(PtrState(), /*TopDown=*/true);
1679}
1680
Michael Gottesman81c61212013-01-14 00:35:14 +00001681/// The bottom-up traversal uses this to merge information about successors to
1682/// form the initial state for a new block.
John McCall9fbd3182011-06-15 23:37:01 +00001683void BBState::MergeSucc(const BBState &Other) {
1684 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
1685 // loop backedge. Loop backedges are special.
1686 BottomUpPathCount += Other.BottomUpPathCount;
1687
Michael Gottesman7899e472013-01-14 01:47:53 +00001688 // Check for overflow. If we have overflow, fall back to conservative
1689 // behavior.
Dan Gohman0d1bc5f2012-09-12 20:45:17 +00001690 if (BottomUpPathCount < Other.BottomUpPathCount) {
1691 clearBottomUpPointers();
1692 return;
1693 }
1694
John McCall9fbd3182011-06-15 23:37:01 +00001695 // For each entry in the other set, if our set has an entry with the
1696 // same key, merge the entries. Otherwise, copy the entry and merge
1697 // it with an empty entry.
1698 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
1699 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
1700 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
1701 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1702 /*TopDown=*/false);
1703 }
1704
Dan Gohmanfa7eed12011-08-11 21:06:32 +00001705 // For each entry in our set, if the other set doesn't have an entry
John McCall9fbd3182011-06-15 23:37:01 +00001706 // with the same key, force it to merge with an empty entry.
1707 for (ptr_iterator MI = bottom_up_ptr_begin(),
1708 ME = bottom_up_ptr_end(); MI != ME; ++MI)
1709 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
1710 MI->second.Merge(PtrState(), /*TopDown=*/false);
1711}
1712
1713namespace {
Michael Gottesman81c61212013-01-14 00:35:14 +00001714 /// \brief The main ARC optimization pass.
John McCall9fbd3182011-06-15 23:37:01 +00001715 class ObjCARCOpt : public FunctionPass {
1716 bool Changed;
1717 ProvenanceAnalysis PA;
1718
Michael Gottesman81c61212013-01-14 00:35:14 +00001719 /// A flag indicating whether this optimization pass should run.
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00001720 bool Run;
1721
Michael Gottesman81c61212013-01-14 00:35:14 +00001722 /// Declarations for ObjC runtime functions, for use in creating calls to
1723 /// them. These are initialized lazily to avoid cluttering up the Module
1724 /// with unused declarations.
John McCall9fbd3182011-06-15 23:37:01 +00001725
Michael Gottesman81c61212013-01-14 00:35:14 +00001726 /// Declaration for ObjC runtime function
1727 /// objc_retainAutoreleasedReturnValue.
1728 Constant *RetainRVCallee;
1729 /// Declaration for ObjC runtime function objc_autoreleaseReturnValue.
1730 Constant *AutoreleaseRVCallee;
1731 /// Declaration for ObjC runtime function objc_release.
1732 Constant *ReleaseCallee;
1733 /// Declaration for ObjC runtime function objc_retain.
1734 Constant *RetainCallee;
1735 /// Declaration for ObjC runtime function objc_retainBlock.
1736 Constant *RetainBlockCallee;
1737 /// Declaration for ObjC runtime function objc_autorelease.
1738 Constant *AutoreleaseCallee;
1739
1740 /// Flags which determine whether each of the interesting runtine functions
1741 /// is in fact used in the current function.
John McCall9fbd3182011-06-15 23:37:01 +00001742 unsigned UsedInThisFunction;
1743
Michael Gottesman81c61212013-01-14 00:35:14 +00001744 /// The Metadata Kind for clang.imprecise_release metadata.
John McCall9fbd3182011-06-15 23:37:01 +00001745 unsigned ImpreciseReleaseMDKind;
1746
Michael Gottesman81c61212013-01-14 00:35:14 +00001747 /// The Metadata Kind for clang.arc.copy_on_escape metadata.
Dan Gohmana974bea2011-10-17 22:53:25 +00001748 unsigned CopyOnEscapeMDKind;
1749
Michael Gottesman81c61212013-01-14 00:35:14 +00001750 /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata.
Dan Gohmandbe266b2012-02-17 18:59:53 +00001751 unsigned NoObjCARCExceptionsMDKind;
1752
John McCall9fbd3182011-06-15 23:37:01 +00001753 Constant *getRetainRVCallee(Module *M);
1754 Constant *getAutoreleaseRVCallee(Module *M);
1755 Constant *getReleaseCallee(Module *M);
1756 Constant *getRetainCallee(Module *M);
Dan Gohman44280692011-07-22 22:29:21 +00001757 Constant *getRetainBlockCallee(Module *M);
John McCall9fbd3182011-06-15 23:37:01 +00001758 Constant *getAutoreleaseCallee(Module *M);
1759
Dan Gohman79522dc2012-01-13 00:39:07 +00001760 bool IsRetainBlockOptimizable(const Instruction *Inst);
1761
John McCall9fbd3182011-06-15 23:37:01 +00001762 void OptimizeRetainCall(Function &F, Instruction *Retain);
1763 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
Michael Gottesman0e385452013-01-12 01:25:19 +00001764 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1765 InstructionClass &Class);
John McCall9fbd3182011-06-15 23:37:01 +00001766 void OptimizeIndividualCalls(Function &F);
1767
1768 void CheckForCFGHazards(const BasicBlock *BB,
1769 DenseMap<const BasicBlock *, BBState> &BBStates,
1770 BBState &MyStates) const;
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00001771 bool VisitInstructionBottomUp(Instruction *Inst,
Dan Gohmanfbab4a82012-03-23 17:47:54 +00001772 BasicBlock *BB,
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00001773 MapVector<Value *, RRInfo> &Retains,
1774 BBState &MyStates);
John McCall9fbd3182011-06-15 23:37:01 +00001775 bool VisitBottomUp(BasicBlock *BB,
1776 DenseMap<const BasicBlock *, BBState> &BBStates,
1777 MapVector<Value *, RRInfo> &Retains);
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00001778 bool VisitInstructionTopDown(Instruction *Inst,
1779 DenseMap<Value *, RRInfo> &Releases,
1780 BBState &MyStates);
John McCall9fbd3182011-06-15 23:37:01 +00001781 bool VisitTopDown(BasicBlock *BB,
1782 DenseMap<const BasicBlock *, BBState> &BBStates,
1783 DenseMap<Value *, RRInfo> &Releases);
1784 bool Visit(Function &F,
1785 DenseMap<const BasicBlock *, BBState> &BBStates,
1786 MapVector<Value *, RRInfo> &Retains,
1787 DenseMap<Value *, RRInfo> &Releases);
1788
1789 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1790 MapVector<Value *, RRInfo> &Retains,
1791 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman44280692011-07-22 22:29:21 +00001792 SmallVectorImpl<Instruction *> &DeadInsts,
1793 Module *M);
John McCall9fbd3182011-06-15 23:37:01 +00001794
1795 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1796 MapVector<Value *, RRInfo> &Retains,
Dan Gohman44280692011-07-22 22:29:21 +00001797 DenseMap<Value *, RRInfo> &Releases,
1798 Module *M);
John McCall9fbd3182011-06-15 23:37:01 +00001799
1800 void OptimizeWeakCalls(Function &F);
1801
1802 bool OptimizeSequences(Function &F);
1803
1804 void OptimizeReturns(Function &F);
1805
1806 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1807 virtual bool doInitialization(Module &M);
1808 virtual bool runOnFunction(Function &F);
1809 virtual void releaseMemory();
1810
1811 public:
1812 static char ID;
1813 ObjCARCOpt() : FunctionPass(ID) {
1814 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1815 }
1816 };
1817}
1818
1819char ObjCARCOpt::ID = 0;
1820INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1821 "objc-arc", "ObjC ARC optimization", false, false)
1822INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1823INITIALIZE_PASS_END(ObjCARCOpt,
1824 "objc-arc", "ObjC ARC optimization", false, false)
1825
1826Pass *llvm::createObjCARCOptPass() {
1827 return new ObjCARCOpt();
1828}
1829
1830void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1831 AU.addRequired<ObjCARCAliasAnalysis>();
1832 AU.addRequired<AliasAnalysis>();
1833 // ARC optimization doesn't currently split critical edges.
1834 AU.setPreservesCFG();
1835}
1836
Dan Gohman79522dc2012-01-13 00:39:07 +00001837bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1838 // Without the magic metadata tag, we have to assume this might be an
1839 // objc_retainBlock call inserted to convert a block pointer to an id,
1840 // in which case it really is needed.
1841 if (!Inst->getMetadata(CopyOnEscapeMDKind))
1842 return false;
1843
1844 // If the pointer "escapes" (not including being used in a call),
1845 // the copy may be needed.
1846 if (DoesObjCBlockEscape(Inst))
1847 return false;
1848
1849 // Otherwise, it's not needed.
1850 return true;
1851}
1852
John McCall9fbd3182011-06-15 23:37:01 +00001853Constant *ObjCARCOpt::getRetainRVCallee(Module *M) {
1854 if (!RetainRVCallee) {
1855 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001856 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman0daef3d2012-05-08 23:39:44 +00001857 Type *Params[] = { I8X };
1858 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling034b94b2012-12-19 07:18:57 +00001859 AttributeSet Attribute =
Bill Wendling99faa3b2012-12-07 23:16:57 +00001860 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00001861 Attribute::get(C, Attribute::NoUnwind));
John McCall9fbd3182011-06-15 23:37:01 +00001862 RetainRVCallee =
1863 M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy,
Bill Wendling034b94b2012-12-19 07:18:57 +00001864 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00001865 }
1866 return RetainRVCallee;
1867}
1868
1869Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1870 if (!AutoreleaseRVCallee) {
1871 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001872 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman0daef3d2012-05-08 23:39:44 +00001873 Type *Params[] = { I8X };
1874 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling034b94b2012-12-19 07:18:57 +00001875 AttributeSet Attribute =
Bill Wendling99faa3b2012-12-07 23:16:57 +00001876 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00001877 Attribute::get(C, Attribute::NoUnwind));
John McCall9fbd3182011-06-15 23:37:01 +00001878 AutoreleaseRVCallee =
1879 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
Bill Wendling034b94b2012-12-19 07:18:57 +00001880 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00001881 }
1882 return AutoreleaseRVCallee;
1883}
1884
1885Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1886 if (!ReleaseCallee) {
1887 LLVMContext &C = M->getContext();
Dan Gohman0daef3d2012-05-08 23:39:44 +00001888 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling034b94b2012-12-19 07:18:57 +00001889 AttributeSet Attribute =
Bill Wendling99faa3b2012-12-07 23:16:57 +00001890 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00001891 Attribute::get(C, Attribute::NoUnwind));
John McCall9fbd3182011-06-15 23:37:01 +00001892 ReleaseCallee =
1893 M->getOrInsertFunction(
1894 "objc_release",
1895 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
Bill Wendling034b94b2012-12-19 07:18:57 +00001896 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00001897 }
1898 return ReleaseCallee;
1899}
1900
1901Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1902 if (!RetainCallee) {
1903 LLVMContext &C = M->getContext();
Dan Gohman0daef3d2012-05-08 23:39:44 +00001904 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling034b94b2012-12-19 07:18:57 +00001905 AttributeSet Attribute =
Bill Wendling99faa3b2012-12-07 23:16:57 +00001906 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00001907 Attribute::get(C, Attribute::NoUnwind));
John McCall9fbd3182011-06-15 23:37:01 +00001908 RetainCallee =
1909 M->getOrInsertFunction(
1910 "objc_retain",
1911 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling034b94b2012-12-19 07:18:57 +00001912 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00001913 }
1914 return RetainCallee;
1915}
1916
Dan Gohman44280692011-07-22 22:29:21 +00001917Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1918 if (!RetainBlockCallee) {
1919 LLVMContext &C = M->getContext();
Dan Gohman0daef3d2012-05-08 23:39:44 +00001920 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Dan Gohman1d2fd752011-09-14 18:33:34 +00001921 // objc_retainBlock is not nounwind because it calls user copy constructors
1922 // which could theoretically throw.
Dan Gohman44280692011-07-22 22:29:21 +00001923 RetainBlockCallee =
1924 M->getOrInsertFunction(
1925 "objc_retainBlock",
1926 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling99faa3b2012-12-07 23:16:57 +00001927 AttributeSet());
Dan Gohman44280692011-07-22 22:29:21 +00001928 }
1929 return RetainBlockCallee;
1930}
1931
John McCall9fbd3182011-06-15 23:37:01 +00001932Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1933 if (!AutoreleaseCallee) {
1934 LLVMContext &C = M->getContext();
Dan Gohman0daef3d2012-05-08 23:39:44 +00001935 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling034b94b2012-12-19 07:18:57 +00001936 AttributeSet Attribute =
Bill Wendling99faa3b2012-12-07 23:16:57 +00001937 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00001938 Attribute::get(C, Attribute::NoUnwind));
John McCall9fbd3182011-06-15 23:37:01 +00001939 AutoreleaseCallee =
1940 M->getOrInsertFunction(
1941 "objc_autorelease",
1942 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling034b94b2012-12-19 07:18:57 +00001943 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00001944 }
1945 return AutoreleaseCallee;
1946}
1947
Michael Gottesman81c61212013-01-14 00:35:14 +00001948/// Test whether the given value is possible a reference-counted pointer,
1949/// including tests which utilize AliasAnalysis.
Dan Gohman230768b2012-09-04 23:16:20 +00001950static bool IsPotentialUse(const Value *Op, AliasAnalysis &AA) {
1951 // First make the rudimentary check.
1952 if (!IsPotentialUse(Op))
1953 return false;
1954
1955 // Objects in constant memory are not reference-counted.
1956 if (AA.pointsToConstantMemory(Op))
1957 return false;
1958
1959 // Pointers in constant memory are not pointing to reference-counted objects.
1960 if (const LoadInst *LI = dyn_cast<LoadInst>(Op))
1961 if (AA.pointsToConstantMemory(LI->getPointerOperand()))
1962 return false;
1963
1964 // Otherwise assume the worst.
1965 return true;
1966}
1967
Michael Gottesman81c61212013-01-14 00:35:14 +00001968/// Test whether the given instruction can result in a reference count
1969/// modification (positive or negative) for the pointer's object.
John McCall9fbd3182011-06-15 23:37:01 +00001970static bool
1971CanAlterRefCount(const Instruction *Inst, const Value *Ptr,
1972 ProvenanceAnalysis &PA, InstructionClass Class) {
1973 switch (Class) {
1974 case IC_Autorelease:
1975 case IC_AutoreleaseRV:
1976 case IC_User:
1977 // These operations never directly modify a reference count.
1978 return false;
1979 default: break;
1980 }
1981
1982 ImmutableCallSite CS = static_cast<const Value *>(Inst);
1983 assert(CS && "Only calls can alter reference counts!");
1984
1985 // See if AliasAnalysis can help us with the call.
1986 AliasAnalysis::ModRefBehavior MRB = PA.getAA()->getModRefBehavior(CS);
1987 if (AliasAnalysis::onlyReadsMemory(MRB))
1988 return false;
1989 if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
1990 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1991 I != E; ++I) {
1992 const Value *Op = *I;
Dan Gohman230768b2012-09-04 23:16:20 +00001993 if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
John McCall9fbd3182011-06-15 23:37:01 +00001994 return true;
1995 }
1996 return false;
1997 }
1998
1999 // Assume the worst.
2000 return true;
2001}
2002
Michael Gottesman81c61212013-01-14 00:35:14 +00002003/// Test whether the given instruction can "use" the given pointer's object in a
2004/// way that requires the reference count to be positive.
John McCall9fbd3182011-06-15 23:37:01 +00002005static bool
2006CanUse(const Instruction *Inst, const Value *Ptr, ProvenanceAnalysis &PA,
2007 InstructionClass Class) {
2008 // IC_Call operations (as opposed to IC_CallOrUser) never "use" objc pointers.
2009 if (Class == IC_Call)
2010 return false;
2011
2012 // Consider various instructions which may have pointer arguments which are
2013 // not "uses".
2014 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(Inst)) {
2015 // Comparing a pointer with null, or any other constant, isn't really a use,
2016 // because we don't care what the pointer points to, or about the values
2017 // of any other dynamic reference-counted pointers.
Dan Gohman230768b2012-09-04 23:16:20 +00002018 if (!IsPotentialUse(ICI->getOperand(1), *PA.getAA()))
John McCall9fbd3182011-06-15 23:37:01 +00002019 return false;
2020 } else if (ImmutableCallSite CS = static_cast<const Value *>(Inst)) {
2021 // For calls, just check the arguments (and not the callee operand).
2022 for (ImmutableCallSite::arg_iterator OI = CS.arg_begin(),
2023 OE = CS.arg_end(); OI != OE; ++OI) {
2024 const Value *Op = *OI;
Dan Gohman230768b2012-09-04 23:16:20 +00002025 if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
John McCall9fbd3182011-06-15 23:37:01 +00002026 return true;
2027 }
2028 return false;
2029 } else if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
2030 // Special-case stores, because we don't care about the stored value, just
2031 // the store address.
2032 const Value *Op = GetUnderlyingObjCPtr(SI->getPointerOperand());
2033 // If we can't tell what the underlying object was, assume there is a
2034 // dependence.
Dan Gohman230768b2012-09-04 23:16:20 +00002035 return IsPotentialUse(Op, *PA.getAA()) && PA.related(Op, Ptr);
John McCall9fbd3182011-06-15 23:37:01 +00002036 }
2037
2038 // Check each operand for a match.
2039 for (User::const_op_iterator OI = Inst->op_begin(), OE = Inst->op_end();
2040 OI != OE; ++OI) {
2041 const Value *Op = *OI;
Dan Gohman230768b2012-09-04 23:16:20 +00002042 if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
John McCall9fbd3182011-06-15 23:37:01 +00002043 return true;
2044 }
2045 return false;
2046}
2047
Michael Gottesman81c61212013-01-14 00:35:14 +00002048/// Test whether the given instruction can autorelease any pointer or cause an
2049/// autoreleasepool pop.
John McCall9fbd3182011-06-15 23:37:01 +00002050static bool
2051CanInterruptRV(InstructionClass Class) {
2052 switch (Class) {
2053 case IC_AutoreleasepoolPop:
2054 case IC_CallOrUser:
2055 case IC_Call:
2056 case IC_Autorelease:
2057 case IC_AutoreleaseRV:
2058 case IC_FusedRetainAutorelease:
2059 case IC_FusedRetainAutoreleaseRV:
2060 return true;
2061 default:
2062 return false;
2063 }
2064}
2065
2066namespace {
Michael Gottesman81c61212013-01-14 00:35:14 +00002067 /// \enum DependenceKind
2068 /// \brief Defines different dependence kinds among various ARC constructs.
2069 ///
2070 /// There are several kinds of dependence-like concepts in use here.
2071 ///
John McCall9fbd3182011-06-15 23:37:01 +00002072 enum DependenceKind {
2073 NeedsPositiveRetainCount,
Dan Gohman511568d2012-04-13 00:59:57 +00002074 AutoreleasePoolBoundary,
John McCall9fbd3182011-06-15 23:37:01 +00002075 CanChangeRetainCount,
2076 RetainAutoreleaseDep, ///< Blocks objc_retainAutorelease.
2077 RetainAutoreleaseRVDep, ///< Blocks objc_retainAutoreleaseReturnValue.
2078 RetainRVDep ///< Blocks objc_retainAutoreleasedReturnValue.
2079 };
2080}
2081
Michael Gottesman81c61212013-01-14 00:35:14 +00002082/// Test if there can be dependencies on Inst through Arg. This function only
2083/// tests dependencies relevant for removing pairs of calls.
John McCall9fbd3182011-06-15 23:37:01 +00002084static bool
2085Depends(DependenceKind Flavor, Instruction *Inst, const Value *Arg,
2086 ProvenanceAnalysis &PA) {
2087 // If we've reached the definition of Arg, stop.
2088 if (Inst == Arg)
2089 return true;
2090
2091 switch (Flavor) {
2092 case NeedsPositiveRetainCount: {
2093 InstructionClass Class = GetInstructionClass(Inst);
2094 switch (Class) {
2095 case IC_AutoreleasepoolPop:
2096 case IC_AutoreleasepoolPush:
2097 case IC_None:
2098 return false;
2099 default:
2100 return CanUse(Inst, Arg, PA, Class);
2101 }
2102 }
2103
Dan Gohman511568d2012-04-13 00:59:57 +00002104 case AutoreleasePoolBoundary: {
2105 InstructionClass Class = GetInstructionClass(Inst);
2106 switch (Class) {
2107 case IC_AutoreleasepoolPop:
2108 case IC_AutoreleasepoolPush:
2109 // These mark the end and begin of an autorelease pool scope.
2110 return true;
2111 default:
2112 // Nothing else does this.
2113 return false;
2114 }
2115 }
2116
John McCall9fbd3182011-06-15 23:37:01 +00002117 case CanChangeRetainCount: {
2118 InstructionClass Class = GetInstructionClass(Inst);
2119 switch (Class) {
2120 case IC_AutoreleasepoolPop:
2121 // Conservatively assume this can decrement any count.
2122 return true;
2123 case IC_AutoreleasepoolPush:
2124 case IC_None:
2125 return false;
2126 default:
2127 return CanAlterRefCount(Inst, Arg, PA, Class);
2128 }
2129 }
2130
2131 case RetainAutoreleaseDep:
2132 switch (GetBasicInstructionClass(Inst)) {
2133 case IC_AutoreleasepoolPop:
Dan Gohman511568d2012-04-13 00:59:57 +00002134 case IC_AutoreleasepoolPush:
John McCall9fbd3182011-06-15 23:37:01 +00002135 // Don't merge an objc_autorelease with an objc_retain inside a different
2136 // autoreleasepool scope.
2137 return true;
2138 case IC_Retain:
2139 case IC_RetainRV:
2140 // Check for a retain of the same pointer for merging.
2141 return GetObjCArg(Inst) == Arg;
2142 default:
2143 // Nothing else matters for objc_retainAutorelease formation.
2144 return false;
2145 }
John McCall9fbd3182011-06-15 23:37:01 +00002146
2147 case RetainAutoreleaseRVDep: {
2148 InstructionClass Class = GetBasicInstructionClass(Inst);
2149 switch (Class) {
2150 case IC_Retain:
2151 case IC_RetainRV:
2152 // Check for a retain of the same pointer for merging.
2153 return GetObjCArg(Inst) == Arg;
2154 default:
2155 // Anything that can autorelease interrupts
2156 // retainAutoreleaseReturnValue formation.
2157 return CanInterruptRV(Class);
2158 }
John McCall9fbd3182011-06-15 23:37:01 +00002159 }
2160
2161 case RetainRVDep:
2162 return CanInterruptRV(GetBasicInstructionClass(Inst));
2163 }
2164
2165 llvm_unreachable("Invalid dependence flavor");
John McCall9fbd3182011-06-15 23:37:01 +00002166}
2167
Michael Gottesman81c61212013-01-14 00:35:14 +00002168/// Walk up the CFG from StartPos (which is in StartBB) and find local and
2169/// non-local dependencies on Arg.
2170///
John McCall9fbd3182011-06-15 23:37:01 +00002171/// TODO: Cache results?
2172static void
2173FindDependencies(DependenceKind Flavor,
2174 const Value *Arg,
2175 BasicBlock *StartBB, Instruction *StartInst,
2176 SmallPtrSet<Instruction *, 4> &DependingInstructions,
2177 SmallPtrSet<const BasicBlock *, 4> &Visited,
2178 ProvenanceAnalysis &PA) {
2179 BasicBlock::iterator StartPos = StartInst;
2180
2181 SmallVector<std::pair<BasicBlock *, BasicBlock::iterator>, 4> Worklist;
2182 Worklist.push_back(std::make_pair(StartBB, StartPos));
2183 do {
2184 std::pair<BasicBlock *, BasicBlock::iterator> Pair =
2185 Worklist.pop_back_val();
2186 BasicBlock *LocalStartBB = Pair.first;
2187 BasicBlock::iterator LocalStartPos = Pair.second;
2188 BasicBlock::iterator StartBBBegin = LocalStartBB->begin();
2189 for (;;) {
2190 if (LocalStartPos == StartBBBegin) {
2191 pred_iterator PI(LocalStartBB), PE(LocalStartBB, false);
2192 if (PI == PE)
2193 // If we've reached the function entry, produce a null dependence.
2194 DependingInstructions.insert(0);
2195 else
2196 // Add the predecessors to the worklist.
2197 do {
2198 BasicBlock *PredBB = *PI;
2199 if (Visited.insert(PredBB))
2200 Worklist.push_back(std::make_pair(PredBB, PredBB->end()));
2201 } while (++PI != PE);
2202 break;
2203 }
2204
2205 Instruction *Inst = --LocalStartPos;
2206 if (Depends(Flavor, Inst, Arg, PA)) {
2207 DependingInstructions.insert(Inst);
2208 break;
2209 }
2210 }
2211 } while (!Worklist.empty());
2212
2213 // Determine whether the original StartBB post-dominates all of the blocks we
2214 // visited. If not, insert a sentinal indicating that most optimizations are
2215 // not safe.
2216 for (SmallPtrSet<const BasicBlock *, 4>::const_iterator I = Visited.begin(),
2217 E = Visited.end(); I != E; ++I) {
2218 const BasicBlock *BB = *I;
2219 if (BB == StartBB)
2220 continue;
2221 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2222 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2223 const BasicBlock *Succ = *SI;
2224 if (Succ != StartBB && !Visited.count(Succ)) {
2225 DependingInstructions.insert(reinterpret_cast<Instruction *>(-1));
2226 return;
2227 }
2228 }
2229 }
2230}
2231
2232static bool isNullOrUndef(const Value *V) {
2233 return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
2234}
2235
2236static bool isNoopInstruction(const Instruction *I) {
2237 return isa<BitCastInst>(I) ||
2238 (isa<GetElementPtrInst>(I) &&
2239 cast<GetElementPtrInst>(I)->hasAllZeroIndices());
2240}
2241
Michael Gottesman81c61212013-01-14 00:35:14 +00002242/// Turn objc_retain into objc_retainAutoreleasedReturnValue if the operand is a
2243/// return value.
John McCall9fbd3182011-06-15 23:37:01 +00002244void
2245ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) {
Dan Gohman447989c2012-04-27 18:56:31 +00002246 ImmutableCallSite CS(GetObjCArg(Retain));
2247 const Instruction *Call = CS.getInstruction();
John McCall9fbd3182011-06-15 23:37:01 +00002248 if (!Call) return;
2249 if (Call->getParent() != Retain->getParent()) return;
2250
2251 // Check that the call is next to the retain.
Dan Gohman447989c2012-04-27 18:56:31 +00002252 BasicBlock::const_iterator I = Call;
John McCall9fbd3182011-06-15 23:37:01 +00002253 ++I;
2254 while (isNoopInstruction(I)) ++I;
2255 if (&*I != Retain)
2256 return;
2257
2258 // Turn it to an objc_retainAutoreleasedReturnValue..
2259 Changed = true;
2260 ++NumPeeps;
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002261
Michael Gottesman715f6a62013-01-04 21:30:38 +00002262 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainCall: Transforming "
Michael Gottesmane7a715f2013-01-12 03:45:49 +00002263 "objc_retain => objc_retainAutoreleasedReturnValue"
2264 " since the operand is a return value.\n"
Michael Gottesman715f6a62013-01-04 21:30:38 +00002265 " Old: "
2266 << *Retain << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002267
John McCall9fbd3182011-06-15 23:37:01 +00002268 cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent()));
Michael Gottesman715f6a62013-01-04 21:30:38 +00002269
2270 DEBUG(dbgs() << " New: "
2271 << *Retain << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00002272}
2273
Michael Gottesman81c61212013-01-14 00:35:14 +00002274/// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is
2275/// not a return value. Or, if it can be paired with an
2276/// objc_autoreleaseReturnValue, delete the pair and return true.
John McCall9fbd3182011-06-15 23:37:01 +00002277bool
2278ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
Dan Gohman6fedb3c2012-03-23 18:09:00 +00002279 // Check for the argument being from an immediately preceding call or invoke.
Dan Gohman447989c2012-04-27 18:56:31 +00002280 const Value *Arg = GetObjCArg(RetainRV);
2281 ImmutableCallSite CS(Arg);
2282 if (const Instruction *Call = CS.getInstruction()) {
John McCall9fbd3182011-06-15 23:37:01 +00002283 if (Call->getParent() == RetainRV->getParent()) {
Dan Gohman447989c2012-04-27 18:56:31 +00002284 BasicBlock::const_iterator I = Call;
John McCall9fbd3182011-06-15 23:37:01 +00002285 ++I;
2286 while (isNoopInstruction(I)) ++I;
2287 if (&*I == RetainRV)
2288 return false;
Dan Gohman447989c2012-04-27 18:56:31 +00002289 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Dan Gohman6fedb3c2012-03-23 18:09:00 +00002290 BasicBlock *RetainRVParent = RetainRV->getParent();
2291 if (II->getNormalDest() == RetainRVParent) {
Dan Gohman447989c2012-04-27 18:56:31 +00002292 BasicBlock::const_iterator I = RetainRVParent->begin();
Dan Gohman6fedb3c2012-03-23 18:09:00 +00002293 while (isNoopInstruction(I)) ++I;
2294 if (&*I == RetainRV)
2295 return false;
2296 }
John McCall9fbd3182011-06-15 23:37:01 +00002297 }
Dan Gohman6fedb3c2012-03-23 18:09:00 +00002298 }
John McCall9fbd3182011-06-15 23:37:01 +00002299
2300 // Check for being preceded by an objc_autoreleaseReturnValue on the same
2301 // pointer. In this case, we can delete the pair.
2302 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
2303 if (I != Begin) {
2304 do --I; while (I != Begin && isNoopInstruction(I));
2305 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
2306 GetObjCArg(I) == Arg) {
2307 Changed = true;
2308 ++NumPeeps;
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002309
Michael Gottesman87a0f022013-01-05 17:55:35 +00002310 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainRVCall: Erasing " << *I << "\n"
2311 << " Erasing " << *RetainRV
2312 << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002313
John McCall9fbd3182011-06-15 23:37:01 +00002314 EraseInstruction(I);
2315 EraseInstruction(RetainRV);
2316 return true;
2317 }
2318 }
2319
2320 // Turn it to a plain objc_retain.
2321 Changed = true;
2322 ++NumPeeps;
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002323
Michael Gottesman36e4bc42013-01-05 17:55:42 +00002324 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainRVCall: Transforming "
2325 "objc_retainAutoreleasedReturnValue => "
2326 "objc_retain since the operand is not a return value.\n"
2327 " Old: "
2328 << *RetainRV << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002329
John McCall9fbd3182011-06-15 23:37:01 +00002330 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
Michael Gottesman36e4bc42013-01-05 17:55:42 +00002331
2332 DEBUG(dbgs() << " New: "
2333 << *RetainRV << "\n");
2334
John McCall9fbd3182011-06-15 23:37:01 +00002335 return false;
2336}
2337
Michael Gottesman81c61212013-01-14 00:35:14 +00002338/// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not
2339/// used as a return value.
John McCall9fbd3182011-06-15 23:37:01 +00002340void
Michael Gottesman0e385452013-01-12 01:25:19 +00002341ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
2342 InstructionClass &Class) {
John McCall9fbd3182011-06-15 23:37:01 +00002343 // Check for a return of the pointer value.
2344 const Value *Ptr = GetObjCArg(AutoreleaseRV);
Dan Gohman126a54f2011-08-12 00:36:31 +00002345 SmallVector<const Value *, 2> Users;
2346 Users.push_back(Ptr);
2347 do {
2348 Ptr = Users.pop_back_val();
2349 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
2350 UI != UE; ++UI) {
2351 const User *I = *UI;
2352 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
2353 return;
2354 if (isa<BitCastInst>(I))
2355 Users.push_back(I);
2356 }
2357 } while (!Users.empty());
John McCall9fbd3182011-06-15 23:37:01 +00002358
2359 Changed = true;
2360 ++NumPeeps;
Michael Gottesman48239c72013-01-06 21:07:11 +00002361
2362 DEBUG(dbgs() << "ObjCARCOpt::OptimizeAutoreleaseRVCall: Transforming "
2363 "objc_autoreleaseReturnValue => "
2364 "objc_autorelease since its operand is not used as a return "
2365 "value.\n"
2366 " Old: "
2367 << *AutoreleaseRV << "\n");
2368
Michael Gottesmane8c161a2013-01-12 01:25:15 +00002369 CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
2370 AutoreleaseRVCI->
John McCall9fbd3182011-06-15 23:37:01 +00002371 setCalledFunction(getAutoreleaseCallee(F.getParent()));
Michael Gottesmane8c161a2013-01-12 01:25:15 +00002372 AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
Michael Gottesman0e385452013-01-12 01:25:19 +00002373 Class = IC_Autorelease;
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002374
Michael Gottesman48239c72013-01-06 21:07:11 +00002375 DEBUG(dbgs() << " New: "
2376 << *AutoreleaseRV << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002377
John McCall9fbd3182011-06-15 23:37:01 +00002378}
2379
Michael Gottesman81c61212013-01-14 00:35:14 +00002380/// Visit each call, one at a time, and make simplifications without doing any
2381/// additional analysis.
John McCall9fbd3182011-06-15 23:37:01 +00002382void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
2383 // Reset all the flags in preparation for recomputing them.
2384 UsedInThisFunction = 0;
2385
2386 // Visit all objc_* calls in F.
2387 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2388 Instruction *Inst = &*I++;
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00002389
Michael Gottesman5c0ae472013-01-04 21:29:57 +00002390 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Visiting: " <<
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00002391 *Inst << "\n");
2392
John McCall9fbd3182011-06-15 23:37:01 +00002393 InstructionClass Class = GetBasicInstructionClass(Inst);
2394
2395 switch (Class) {
2396 default: break;
2397
2398 // Delete no-op casts. These function calls have special semantics, but
2399 // the semantics are entirely implemented via lowering in the front-end,
2400 // so by the time they reach the optimizer, they are just no-op calls
2401 // which return their argument.
2402 //
2403 // There are gray areas here, as the ability to cast reference-counted
2404 // pointers to raw void* and back allows code to break ARC assumptions,
2405 // however these are currently considered to be unimportant.
2406 case IC_NoopCast:
2407 Changed = true;
2408 ++NumNoops;
Michael Gottesman4680abe2013-01-06 21:07:15 +00002409 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Erasing no-op cast:"
2410 " " << *Inst << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00002411 EraseInstruction(Inst);
2412 continue;
2413
2414 // If the pointer-to-weak-pointer is null, it's undefined behavior.
2415 case IC_StoreWeak:
2416 case IC_LoadWeak:
2417 case IC_LoadWeakRetained:
2418 case IC_InitWeak:
2419 case IC_DestroyWeak: {
2420 CallInst *CI = cast<CallInst>(Inst);
2421 if (isNullOrUndef(CI->getArgOperand(0))) {
Dan Gohmand6bf2012012-04-13 18:57:48 +00002422 Changed = true;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002423 Type *Ty = CI->getArgOperand(0)->getType();
John McCall9fbd3182011-06-15 23:37:01 +00002424 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2425 Constant::getNullValue(Ty),
2426 CI);
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002427 llvm::Value *NewValue = UndefValue::get(CI->getType());
Michael Gottesmane5494922013-01-06 21:54:30 +00002428 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: A null "
2429 "pointer-to-weak-pointer is undefined behavior.\n"
2430 " Old = " << *CI <<
2431 "\n New = " <<
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002432 *NewValue << "\n");
Michael Gottesmane5494922013-01-06 21:54:30 +00002433 CI->replaceAllUsesWith(NewValue);
John McCall9fbd3182011-06-15 23:37:01 +00002434 CI->eraseFromParent();
2435 continue;
2436 }
2437 break;
2438 }
2439 case IC_CopyWeak:
2440 case IC_MoveWeak: {
2441 CallInst *CI = cast<CallInst>(Inst);
2442 if (isNullOrUndef(CI->getArgOperand(0)) ||
2443 isNullOrUndef(CI->getArgOperand(1))) {
Dan Gohmand6bf2012012-04-13 18:57:48 +00002444 Changed = true;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002445 Type *Ty = CI->getArgOperand(0)->getType();
John McCall9fbd3182011-06-15 23:37:01 +00002446 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2447 Constant::getNullValue(Ty),
2448 CI);
Michael Gottesmane5494922013-01-06 21:54:30 +00002449
2450 llvm::Value *NewValue = UndefValue::get(CI->getType());
2451 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: A null "
2452 "pointer-to-weak-pointer is undefined behavior.\n"
2453 " Old = " << *CI <<
2454 "\n New = " <<
2455 *NewValue << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002456
Michael Gottesmane5494922013-01-06 21:54:30 +00002457 CI->replaceAllUsesWith(NewValue);
John McCall9fbd3182011-06-15 23:37:01 +00002458 CI->eraseFromParent();
2459 continue;
2460 }
2461 break;
2462 }
2463 case IC_Retain:
2464 OptimizeRetainCall(F, Inst);
2465 break;
2466 case IC_RetainRV:
2467 if (OptimizeRetainRVCall(F, Inst))
2468 continue;
2469 break;
2470 case IC_AutoreleaseRV:
Michael Gottesman0e385452013-01-12 01:25:19 +00002471 OptimizeAutoreleaseRVCall(F, Inst, Class);
John McCall9fbd3182011-06-15 23:37:01 +00002472 break;
2473 }
2474
2475 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
2476 if (IsAutorelease(Class) && Inst->use_empty()) {
2477 CallInst *Call = cast<CallInst>(Inst);
2478 const Value *Arg = Call->getArgOperand(0);
2479 Arg = FindSingleUseIdentifiedObject(Arg);
2480 if (Arg) {
2481 Changed = true;
2482 ++NumAutoreleases;
2483
2484 // Create the declaration lazily.
2485 LLVMContext &C = Inst->getContext();
2486 CallInst *NewCall =
2487 CallInst::Create(getReleaseCallee(F.getParent()),
2488 Call->getArgOperand(0), "", Call);
2489 NewCall->setMetadata(ImpreciseReleaseMDKind,
2490 MDNode::get(C, ArrayRef<Value *>()));
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002491
Michael Gottesman20d9fff2013-01-06 22:56:50 +00002492 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Replacing "
2493 "objc_autorelease(x) with objc_release(x) since x is "
2494 "otherwise unused.\n"
Michael Gottesman79561272013-01-06 22:56:54 +00002495 " Old: " << *Call <<
Michael Gottesman20d9fff2013-01-06 22:56:50 +00002496 "\n New: " <<
2497 *NewCall << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002498
John McCall9fbd3182011-06-15 23:37:01 +00002499 EraseInstruction(Call);
2500 Inst = NewCall;
2501 Class = IC_Release;
2502 }
2503 }
2504
2505 // For functions which can never be passed stack arguments, add
2506 // a tail keyword.
2507 if (IsAlwaysTail(Class)) {
2508 Changed = true;
Michael Gottesman817d4e92013-01-06 23:39:09 +00002509 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Adding tail keyword"
2510 " to function since it can never be passed stack args: " << *Inst <<
2511 "\n");
John McCall9fbd3182011-06-15 23:37:01 +00002512 cast<CallInst>(Inst)->setTailCall();
2513 }
2514
Michael Gottesmane8c161a2013-01-12 01:25:15 +00002515 // Ensure that functions that can never have a "tail" keyword due to the
2516 // semantics of ARC truly do not do so.
2517 if (IsNeverTail(Class)) {
2518 Changed = true;
Michael Gottesman7899e472013-01-14 01:47:53 +00002519 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Removing tail "
2520 "keyword from function: " << *Inst <<
Michael Gottesmane8c161a2013-01-12 01:25:15 +00002521 "\n");
2522 cast<CallInst>(Inst)->setTailCall(false);
2523 }
2524
John McCall9fbd3182011-06-15 23:37:01 +00002525 // Set nounwind as needed.
2526 if (IsNoThrow(Class)) {
2527 Changed = true;
Michael Gottesman38bc25a2013-01-06 23:39:13 +00002528 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Found no throw"
2529 " class. Setting nounwind on: " << *Inst << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00002530 cast<CallInst>(Inst)->setDoesNotThrow();
2531 }
2532
2533 if (!IsNoopOnNull(Class)) {
2534 UsedInThisFunction |= 1 << Class;
2535 continue;
2536 }
2537
2538 const Value *Arg = GetObjCArg(Inst);
2539
2540 // ARC calls with null are no-ops. Delete them.
2541 if (isNullOrUndef(Arg)) {
2542 Changed = true;
2543 ++NumNoops;
Michael Gottesmanfbe4d6b2013-01-07 00:04:52 +00002544 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: ARC calls with "
2545 " null are no-ops. Erasing: " << *Inst << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00002546 EraseInstruction(Inst);
2547 continue;
2548 }
2549
2550 // Keep track of which of retain, release, autorelease, and retain_block
2551 // are actually present in this function.
2552 UsedInThisFunction |= 1 << Class;
2553
2554 // If Arg is a PHI, and one or more incoming values to the
2555 // PHI are null, and the call is control-equivalent to the PHI, and there
2556 // are no relevant side effects between the PHI and the call, the call
2557 // could be pushed up to just those paths with non-null incoming values.
2558 // For now, don't bother splitting critical edges for this.
2559 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
2560 Worklist.push_back(std::make_pair(Inst, Arg));
2561 do {
2562 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
2563 Inst = Pair.first;
2564 Arg = Pair.second;
2565
2566 const PHINode *PN = dyn_cast<PHINode>(Arg);
2567 if (!PN) continue;
2568
2569 // Determine if the PHI has any null operands, or any incoming
2570 // critical edges.
2571 bool HasNull = false;
2572 bool HasCriticalEdges = false;
2573 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2574 Value *Incoming =
2575 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2576 if (isNullOrUndef(Incoming))
2577 HasNull = true;
2578 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
2579 .getNumSuccessors() != 1) {
2580 HasCriticalEdges = true;
2581 break;
2582 }
2583 }
2584 // If we have null operands and no critical edges, optimize.
2585 if (!HasCriticalEdges && HasNull) {
2586 SmallPtrSet<Instruction *, 4> DependingInstructions;
2587 SmallPtrSet<const BasicBlock *, 4> Visited;
2588
2589 // Check that there is nothing that cares about the reference
2590 // count between the call and the phi.
Dan Gohman511568d2012-04-13 00:59:57 +00002591 switch (Class) {
2592 case IC_Retain:
2593 case IC_RetainBlock:
2594 // These can always be moved up.
2595 break;
2596 case IC_Release:
Dan Gohman0daef3d2012-05-08 23:39:44 +00002597 // These can't be moved across things that care about the retain
2598 // count.
Dan Gohman511568d2012-04-13 00:59:57 +00002599 FindDependencies(NeedsPositiveRetainCount, Arg,
2600 Inst->getParent(), Inst,
2601 DependingInstructions, Visited, PA);
2602 break;
2603 case IC_Autorelease:
2604 // These can't be moved across autorelease pool scope boundaries.
2605 FindDependencies(AutoreleasePoolBoundary, Arg,
2606 Inst->getParent(), Inst,
2607 DependingInstructions, Visited, PA);
2608 break;
2609 case IC_RetainRV:
2610 case IC_AutoreleaseRV:
2611 // Don't move these; the RV optimization depends on the autoreleaseRV
2612 // being tail called, and the retainRV being immediately after a call
2613 // (which might still happen if we get lucky with codegen layout, but
2614 // it's not worth taking the chance).
2615 continue;
2616 default:
2617 llvm_unreachable("Invalid dependence flavor");
2618 }
2619
John McCall9fbd3182011-06-15 23:37:01 +00002620 if (DependingInstructions.size() == 1 &&
2621 *DependingInstructions.begin() == PN) {
2622 Changed = true;
2623 ++NumPartialNoops;
2624 // Clone the call into each predecessor that has a non-null value.
2625 CallInst *CInst = cast<CallInst>(Inst);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002626 Type *ParamTy = CInst->getArgOperand(0)->getType();
John McCall9fbd3182011-06-15 23:37:01 +00002627 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2628 Value *Incoming =
2629 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2630 if (!isNullOrUndef(Incoming)) {
2631 CallInst *Clone = cast<CallInst>(CInst->clone());
2632 Value *Op = PN->getIncomingValue(i);
2633 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
2634 if (Op->getType() != ParamTy)
2635 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
2636 Clone->setArgOperand(0, Op);
2637 Clone->insertBefore(InsertPos);
Michael Gottesman55811152013-01-09 19:23:24 +00002638
2639 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Cloning "
2640 << *CInst << "\n"
2641 " And inserting "
2642 "clone at " << *InsertPos << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00002643 Worklist.push_back(std::make_pair(Clone, Incoming));
2644 }
2645 }
2646 // Erase the original call.
Michael Gottesman55811152013-01-09 19:23:24 +00002647 DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00002648 EraseInstruction(CInst);
2649 continue;
2650 }
2651 }
2652 } while (!Worklist.empty());
2653 }
Michael Gottesman0d3582b2013-01-12 02:57:16 +00002654 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Finished List.\n");
John McCall9fbd3182011-06-15 23:37:01 +00002655}
2656
Michael Gottesman81c61212013-01-14 00:35:14 +00002657/// Check for critical edges, loop boundaries, irreducible control flow, or
2658/// other CFG structures where moving code across the edge would result in it
2659/// being executed more.
John McCall9fbd3182011-06-15 23:37:01 +00002660void
2661ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
2662 DenseMap<const BasicBlock *, BBState> &BBStates,
2663 BBState &MyStates) const {
2664 // If any top-down local-use or possible-dec has a succ which is earlier in
2665 // the sequence, forget it.
Dan Gohman22cc4cc2012-03-02 01:13:53 +00002666 for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
John McCall9fbd3182011-06-15 23:37:01 +00002667 E = MyStates.top_down_ptr_end(); I != E; ++I)
2668 switch (I->second.GetSeq()) {
2669 default: break;
2670 case S_Use: {
2671 const Value *Arg = I->first;
2672 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2673 bool SomeSuccHasSame = false;
2674 bool AllSuccsHaveSame = true;
Dan Gohman22cc4cc2012-03-02 01:13:53 +00002675 PtrState &S = I->second;
Dan Gohmandbe266b2012-02-17 18:59:53 +00002676 succ_const_iterator SI(TI), SE(TI, false);
2677
2678 // If the terminator is an invoke marked with the
2679 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
2680 // ignored, for ARC purposes.
Michael Gottesmancf140052013-01-13 07:00:51 +00002681 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind)) {
2682 DEBUG(dbgs() << "ObjCARCOpt::CheckForCFGHazards: Found an invoke "
2683 "terminator marked with "
2684 "clang.arc.no_objc_arc_exceptions. Ignoring unwind "
2685 "edge.\n");
Dan Gohmandbe266b2012-02-17 18:59:53 +00002686 --SE;
Michael Gottesmancf140052013-01-13 07:00:51 +00002687 }
Dan Gohmandbe266b2012-02-17 18:59:53 +00002688
2689 for (; SI != SE; ++SI) {
Dan Gohman70e29682012-03-02 01:26:46 +00002690 Sequence SuccSSeq = S_None;
2691 bool SuccSRRIKnownSafe = false;
Dan Gohman0daef3d2012-05-08 23:39:44 +00002692 // If VisitBottomUp has pointer information for this successor, take
2693 // what we know about it.
Dan Gohman447989c2012-04-27 18:56:31 +00002694 DenseMap<const BasicBlock *, BBState>::iterator BBI =
2695 BBStates.find(*SI);
2696 assert(BBI != BBStates.end());
2697 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2698 SuccSSeq = SuccS.GetSeq();
2699 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
Dan Gohman70e29682012-03-02 01:26:46 +00002700 switch (SuccSSeq) {
John McCall9fbd3182011-06-15 23:37:01 +00002701 case S_None:
Dan Gohmana7f7db22011-08-12 00:26:31 +00002702 case S_CanRelease: {
Dan Gohman70e29682012-03-02 01:26:46 +00002703 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
Dan Gohmana7f7db22011-08-12 00:26:31 +00002704 S.ClearSequenceProgress();
Dan Gohman70e29682012-03-02 01:26:46 +00002705 break;
2706 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002707 continue;
2708 }
John McCall9fbd3182011-06-15 23:37:01 +00002709 case S_Use:
2710 SomeSuccHasSame = true;
2711 break;
2712 case S_Stop:
2713 case S_Release:
2714 case S_MovableRelease:
Dan Gohman70e29682012-03-02 01:26:46 +00002715 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002716 AllSuccsHaveSame = false;
John McCall9fbd3182011-06-15 23:37:01 +00002717 break;
2718 case S_Retain:
2719 llvm_unreachable("bottom-up pointer in retain state!");
2720 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002721 }
John McCall9fbd3182011-06-15 23:37:01 +00002722 // If the state at the other end of any of the successor edges
2723 // matches the current state, require all edges to match. This
2724 // guards against loops in the middle of a sequence.
2725 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002726 S.ClearSequenceProgress();
Dan Gohman2e68beb2011-12-12 18:13:53 +00002727 break;
John McCall9fbd3182011-06-15 23:37:01 +00002728 }
2729 case S_CanRelease: {
2730 const Value *Arg = I->first;
2731 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2732 bool SomeSuccHasSame = false;
2733 bool AllSuccsHaveSame = true;
Dan Gohman22cc4cc2012-03-02 01:13:53 +00002734 PtrState &S = I->second;
Dan Gohmandbe266b2012-02-17 18:59:53 +00002735 succ_const_iterator SI(TI), SE(TI, false);
2736
2737 // If the terminator is an invoke marked with the
2738 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
2739 // ignored, for ARC purposes.
Michael Gottesmancf140052013-01-13 07:00:51 +00002740 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind)) {
2741 DEBUG(dbgs() << "ObjCARCOpt::CheckForCFGHazards: Found an invoke "
2742 "terminator marked with "
2743 "clang.arc.no_objc_arc_exceptions. Ignoring unwind "
2744 "edge.\n");
Dan Gohmandbe266b2012-02-17 18:59:53 +00002745 --SE;
Michael Gottesmancf140052013-01-13 07:00:51 +00002746 }
Dan Gohmandbe266b2012-02-17 18:59:53 +00002747
2748 for (; SI != SE; ++SI) {
Dan Gohman70e29682012-03-02 01:26:46 +00002749 Sequence SuccSSeq = S_None;
2750 bool SuccSRRIKnownSafe = false;
Dan Gohman0daef3d2012-05-08 23:39:44 +00002751 // If VisitBottomUp has pointer information for this successor, take
2752 // what we know about it.
Dan Gohman447989c2012-04-27 18:56:31 +00002753 DenseMap<const BasicBlock *, BBState>::iterator BBI =
2754 BBStates.find(*SI);
2755 assert(BBI != BBStates.end());
2756 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2757 SuccSSeq = SuccS.GetSeq();
2758 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
Dan Gohman70e29682012-03-02 01:26:46 +00002759 switch (SuccSSeq) {
Dan Gohmana7f7db22011-08-12 00:26:31 +00002760 case S_None: {
Dan Gohman70e29682012-03-02 01:26:46 +00002761 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
Dan Gohmana7f7db22011-08-12 00:26:31 +00002762 S.ClearSequenceProgress();
Dan Gohman70e29682012-03-02 01:26:46 +00002763 break;
2764 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002765 continue;
2766 }
John McCall9fbd3182011-06-15 23:37:01 +00002767 case S_CanRelease:
2768 SomeSuccHasSame = true;
2769 break;
2770 case S_Stop:
2771 case S_Release:
2772 case S_MovableRelease:
2773 case S_Use:
Dan Gohman70e29682012-03-02 01:26:46 +00002774 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002775 AllSuccsHaveSame = false;
John McCall9fbd3182011-06-15 23:37:01 +00002776 break;
2777 case S_Retain:
2778 llvm_unreachable("bottom-up pointer in retain state!");
2779 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002780 }
John McCall9fbd3182011-06-15 23:37:01 +00002781 // If the state at the other end of any of the successor edges
2782 // matches the current state, require all edges to match. This
2783 // guards against loops in the middle of a sequence.
2784 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002785 S.ClearSequenceProgress();
Dan Gohman2e68beb2011-12-12 18:13:53 +00002786 break;
John McCall9fbd3182011-06-15 23:37:01 +00002787 }
2788 }
2789}
2790
2791bool
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002792ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002793 BasicBlock *BB,
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002794 MapVector<Value *, RRInfo> &Retains,
2795 BBState &MyStates) {
2796 bool NestingDetected = false;
2797 InstructionClass Class = GetInstructionClass(Inst);
2798 const Value *Arg = 0;
2799
2800 switch (Class) {
2801 case IC_Release: {
2802 Arg = GetObjCArg(Inst);
2803
2804 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2805
2806 // If we see two releases in a row on the same pointer. If so, make
2807 // a note, and we'll cicle back to revisit it after we've
2808 // hopefully eliminated the second release, which may allow us to
2809 // eliminate the first release too.
2810 // Theoretically we could implement removal of nested retain+release
2811 // pairs by making PtrState hold a stack of states, but this is
2812 // simple and avoids adding overhead for the non-nested case.
Michael Gottesmancf140052013-01-13 07:00:51 +00002813 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease) {
2814 DEBUG(dbgs() << "ObjCARCOpt::VisitInstructionBottomUp: Found nested "
2815 "releases (i.e. a release pair)\n");
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002816 NestingDetected = true;
Michael Gottesmancf140052013-01-13 07:00:51 +00002817 }
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002818
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002819 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
Dan Gohman50ade652012-04-25 00:50:46 +00002820 S.ResetSequenceProgress(ReleaseMetadata ? S_MovableRelease : S_Release);
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002821 S.RRI.ReleaseMetadata = ReleaseMetadata;
Dan Gohman230768b2012-09-04 23:16:20 +00002822 S.RRI.KnownSafe = S.IsKnownIncremented();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002823 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2824 S.RRI.Calls.insert(Inst);
2825
Dan Gohman230768b2012-09-04 23:16:20 +00002826 S.SetKnownPositiveRefCount();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002827 break;
2828 }
2829 case IC_RetainBlock:
2830 // An objc_retainBlock call with just a use may need to be kept,
2831 // because it may be copying a block from the stack to the heap.
2832 if (!IsRetainBlockOptimizable(Inst))
2833 break;
2834 // FALLTHROUGH
2835 case IC_Retain:
2836 case IC_RetainRV: {
2837 Arg = GetObjCArg(Inst);
2838
2839 PtrState &S = MyStates.getPtrBottomUpState(Arg);
Dan Gohman50ade652012-04-25 00:50:46 +00002840 S.SetKnownPositiveRefCount();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002841
2842 switch (S.GetSeq()) {
2843 case S_Stop:
2844 case S_Release:
2845 case S_MovableRelease:
2846 case S_Use:
2847 S.RRI.ReverseInsertPts.clear();
2848 // FALL THROUGH
2849 case S_CanRelease:
2850 // Don't do retain+release tracking for IC_RetainRV, because it's
2851 // better to let it remain as the first instruction after a call.
2852 if (Class != IC_RetainRV) {
2853 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2854 Retains[Inst] = S.RRI;
2855 }
2856 S.ClearSequenceProgress();
2857 break;
2858 case S_None:
2859 break;
2860 case S_Retain:
2861 llvm_unreachable("bottom-up pointer in retain state!");
2862 }
2863 return NestingDetected;
2864 }
2865 case IC_AutoreleasepoolPop:
2866 // Conservatively, clear MyStates for all known pointers.
2867 MyStates.clearBottomUpPointers();
2868 return NestingDetected;
2869 case IC_AutoreleasepoolPush:
2870 case IC_None:
2871 // These are irrelevant.
2872 return NestingDetected;
2873 default:
2874 break;
2875 }
2876
2877 // Consider any other possible effects of this instruction on each
2878 // pointer being tracked.
2879 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
2880 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
2881 const Value *Ptr = MI->first;
2882 if (Ptr == Arg)
2883 continue; // Handled above.
2884 PtrState &S = MI->second;
2885 Sequence Seq = S.GetSeq();
2886
2887 // Check for possible releases.
2888 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Dan Gohman50ade652012-04-25 00:50:46 +00002889 S.ClearRefCount();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002890 switch (Seq) {
2891 case S_Use:
2892 S.SetSeq(S_CanRelease);
2893 continue;
2894 case S_CanRelease:
2895 case S_Release:
2896 case S_MovableRelease:
2897 case S_Stop:
2898 case S_None:
2899 break;
2900 case S_Retain:
2901 llvm_unreachable("bottom-up pointer in retain state!");
2902 }
2903 }
2904
2905 // Check for possible direct uses.
2906 switch (Seq) {
2907 case S_Release:
2908 case S_MovableRelease:
2909 if (CanUse(Inst, Ptr, PA, Class)) {
2910 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002911 // If this is an invoke instruction, we're scanning it as part of
2912 // one of its successor blocks, since we can't insert code after it
2913 // in its own block, and we don't want to split critical edges.
2914 if (isa<InvokeInst>(Inst))
2915 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2916 else
Francois Pichetb54a5ed2012-03-24 01:36:37 +00002917 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002918 S.SetSeq(S_Use);
2919 } else if (Seq == S_Release &&
2920 (Class == IC_User || Class == IC_CallOrUser)) {
2921 // Non-movable releases depend on any possible objc pointer use.
2922 S.SetSeq(S_Stop);
2923 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002924 // As above; handle invoke specially.
2925 if (isa<InvokeInst>(Inst))
2926 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2927 else
Francois Pichetb54a5ed2012-03-24 01:36:37 +00002928 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002929 }
2930 break;
2931 case S_Stop:
2932 if (CanUse(Inst, Ptr, PA, Class))
2933 S.SetSeq(S_Use);
2934 break;
2935 case S_CanRelease:
2936 case S_Use:
2937 case S_None:
2938 break;
2939 case S_Retain:
2940 llvm_unreachable("bottom-up pointer in retain state!");
2941 }
2942 }
2943
2944 return NestingDetected;
2945}
2946
2947bool
John McCall9fbd3182011-06-15 23:37:01 +00002948ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2949 DenseMap<const BasicBlock *, BBState> &BBStates,
2950 MapVector<Value *, RRInfo> &Retains) {
2951 bool NestingDetected = false;
2952 BBState &MyStates = BBStates[BB];
2953
2954 // Merge the states from each successor to compute the initial state
2955 // for the current block.
Dan Gohman40e46602012-08-27 18:31:36 +00002956 BBState::edge_iterator SI(MyStates.succ_begin()),
2957 SE(MyStates.succ_end());
2958 if (SI != SE) {
Dan Gohmaneeeb7752012-04-24 22:53:18 +00002959 const BasicBlock *Succ = *SI;
2960 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
2961 assert(I != BBStates.end());
2962 MyStates.InitFromSucc(I->second);
2963 ++SI;
2964 for (; SI != SE; ++SI) {
2965 Succ = *SI;
2966 I = BBStates.find(Succ);
2967 assert(I != BBStates.end());
2968 MyStates.MergeSucc(I->second);
2969 }
Dan Gohmandbe266b2012-02-17 18:59:53 +00002970 }
John McCall9fbd3182011-06-15 23:37:01 +00002971
2972 // Visit all the instructions, bottom-up.
2973 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2974 Instruction *Inst = llvm::prior(I);
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002975
2976 // Invoke instructions are visited as part of their successors (below).
2977 if (isa<InvokeInst>(Inst))
2978 continue;
2979
Michael Gottesmancf140052013-01-13 07:00:51 +00002980 DEBUG(dbgs() << "ObjCARCOpt::VisitButtonUp: Visiting " << *Inst << "\n");
2981
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002982 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
2983 }
2984
Dan Gohman447989c2012-04-27 18:56:31 +00002985 // If there's a predecessor with an invoke, visit the invoke as if it were
2986 // part of this block, since we can't insert code after an invoke in its own
2987 // block, and we don't want to split critical edges.
Dan Gohmaneeeb7752012-04-24 22:53:18 +00002988 for (BBState::edge_iterator PI(MyStates.pred_begin()),
2989 PE(MyStates.pred_end()); PI != PE; ++PI) {
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002990 BasicBlock *Pred = *PI;
Dan Gohman447989c2012-04-27 18:56:31 +00002991 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
2992 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002993 }
John McCall9fbd3182011-06-15 23:37:01 +00002994
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002995 return NestingDetected;
2996}
John McCall9fbd3182011-06-15 23:37:01 +00002997
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002998bool
2999ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
3000 DenseMap<Value *, RRInfo> &Releases,
3001 BBState &MyStates) {
3002 bool NestingDetected = false;
3003 InstructionClass Class = GetInstructionClass(Inst);
3004 const Value *Arg = 0;
John McCall9fbd3182011-06-15 23:37:01 +00003005
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003006 switch (Class) {
3007 case IC_RetainBlock:
3008 // An objc_retainBlock call with just a use may need to be kept,
3009 // because it may be copying a block from the stack to the heap.
3010 if (!IsRetainBlockOptimizable(Inst))
3011 break;
3012 // FALLTHROUGH
3013 case IC_Retain:
3014 case IC_RetainRV: {
3015 Arg = GetObjCArg(Inst);
3016
3017 PtrState &S = MyStates.getPtrTopDownState(Arg);
3018
3019 // Don't do retain+release tracking for IC_RetainRV, because it's
3020 // better to let it remain as the first instruction after a call.
3021 if (Class != IC_RetainRV) {
3022 // If we see two retains in a row on the same pointer. If so, make
John McCall9fbd3182011-06-15 23:37:01 +00003023 // a note, and we'll cicle back to revisit it after we've
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003024 // hopefully eliminated the second retain, which may allow us to
3025 // eliminate the first retain too.
John McCall9fbd3182011-06-15 23:37:01 +00003026 // Theoretically we could implement removal of nested retain+release
3027 // pairs by making PtrState hold a stack of states, but this is
3028 // simple and avoids adding overhead for the non-nested case.
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003029 if (S.GetSeq() == S_Retain)
John McCall9fbd3182011-06-15 23:37:01 +00003030 NestingDetected = true;
3031
Dan Gohman50ade652012-04-25 00:50:46 +00003032 S.ResetSequenceProgress(S_Retain);
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003033 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
Dan Gohman230768b2012-09-04 23:16:20 +00003034 S.RRI.KnownSafe = S.IsKnownIncremented();
John McCall9fbd3182011-06-15 23:37:01 +00003035 S.RRI.Calls.insert(Inst);
John McCall9fbd3182011-06-15 23:37:01 +00003036 }
John McCall9fbd3182011-06-15 23:37:01 +00003037
Dan Gohman230768b2012-09-04 23:16:20 +00003038 S.SetKnownPositiveRefCount();
Dan Gohmanc72d3be2012-07-23 19:27:31 +00003039
3040 // A retain can be a potential use; procede to the generic checking
3041 // code below.
3042 break;
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003043 }
3044 case IC_Release: {
3045 Arg = GetObjCArg(Inst);
3046
3047 PtrState &S = MyStates.getPtrTopDownState(Arg);
Dan Gohman230768b2012-09-04 23:16:20 +00003048 S.ClearRefCount();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003049
3050 switch (S.GetSeq()) {
3051 case S_Retain:
3052 case S_CanRelease:
3053 S.RRI.ReverseInsertPts.clear();
3054 // FALL THROUGH
3055 case S_Use:
3056 S.RRI.ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
3057 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
3058 Releases[Inst] = S.RRI;
3059 S.ClearSequenceProgress();
3060 break;
3061 case S_None:
3062 break;
3063 case S_Stop:
3064 case S_Release:
3065 case S_MovableRelease:
3066 llvm_unreachable("top-down pointer in release state!");
3067 }
3068 break;
3069 }
3070 case IC_AutoreleasepoolPop:
3071 // Conservatively, clear MyStates for all known pointers.
3072 MyStates.clearTopDownPointers();
3073 return NestingDetected;
3074 case IC_AutoreleasepoolPush:
3075 case IC_None:
3076 // These are irrelevant.
3077 return NestingDetected;
3078 default:
3079 break;
3080 }
3081
3082 // Consider any other possible effects of this instruction on each
3083 // pointer being tracked.
3084 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
3085 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
3086 const Value *Ptr = MI->first;
3087 if (Ptr == Arg)
3088 continue; // Handled above.
3089 PtrState &S = MI->second;
3090 Sequence Seq = S.GetSeq();
3091
3092 // Check for possible releases.
3093 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Dan Gohman50ade652012-04-25 00:50:46 +00003094 S.ClearRefCount();
John McCall9fbd3182011-06-15 23:37:01 +00003095 switch (Seq) {
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003096 case S_Retain:
3097 S.SetSeq(S_CanRelease);
3098 assert(S.RRI.ReverseInsertPts.empty());
3099 S.RRI.ReverseInsertPts.insert(Inst);
3100
3101 // One call can't cause a transition from S_Retain to S_CanRelease
3102 // and S_CanRelease to S_Use. If we've made the first transition,
3103 // we're done.
3104 continue;
John McCall9fbd3182011-06-15 23:37:01 +00003105 case S_Use:
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003106 case S_CanRelease:
John McCall9fbd3182011-06-15 23:37:01 +00003107 case S_None:
3108 break;
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003109 case S_Stop:
3110 case S_Release:
3111 case S_MovableRelease:
3112 llvm_unreachable("top-down pointer in release state!");
John McCall9fbd3182011-06-15 23:37:01 +00003113 }
3114 }
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003115
3116 // Check for possible direct uses.
3117 switch (Seq) {
3118 case S_CanRelease:
3119 if (CanUse(Inst, Ptr, PA, Class))
3120 S.SetSeq(S_Use);
3121 break;
3122 case S_Retain:
3123 case S_Use:
3124 case S_None:
3125 break;
3126 case S_Stop:
3127 case S_Release:
3128 case S_MovableRelease:
3129 llvm_unreachable("top-down pointer in release state!");
3130 }
John McCall9fbd3182011-06-15 23:37:01 +00003131 }
3132
3133 return NestingDetected;
3134}
3135
3136bool
3137ObjCARCOpt::VisitTopDown(BasicBlock *BB,
3138 DenseMap<const BasicBlock *, BBState> &BBStates,
3139 DenseMap<Value *, RRInfo> &Releases) {
3140 bool NestingDetected = false;
3141 BBState &MyStates = BBStates[BB];
3142
3143 // Merge the states from each predecessor to compute the initial state
3144 // for the current block.
Dan Gohman40e46602012-08-27 18:31:36 +00003145 BBState::edge_iterator PI(MyStates.pred_begin()),
3146 PE(MyStates.pred_end());
3147 if (PI != PE) {
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003148 const BasicBlock *Pred = *PI;
3149 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
3150 assert(I != BBStates.end());
3151 MyStates.InitFromPred(I->second);
3152 ++PI;
3153 for (; PI != PE; ++PI) {
3154 Pred = *PI;
3155 I = BBStates.find(Pred);
3156 assert(I != BBStates.end());
3157 MyStates.MergePred(I->second);
3158 }
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003159 }
John McCall9fbd3182011-06-15 23:37:01 +00003160
3161 // Visit all the instructions, top-down.
3162 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3163 Instruction *Inst = I;
Michael Gottesmancf140052013-01-13 07:00:51 +00003164
3165 DEBUG(dbgs() << "ObjCARCOpt::VisitTopDown: Visiting " << *Inst << "\n");
3166
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003167 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
John McCall9fbd3182011-06-15 23:37:01 +00003168 }
3169
3170 CheckForCFGHazards(BB, BBStates, MyStates);
3171 return NestingDetected;
3172}
3173
Dan Gohman59a1c932011-12-12 19:42:25 +00003174static void
3175ComputePostOrders(Function &F,
3176 SmallVectorImpl<BasicBlock *> &PostOrder,
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003177 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
3178 unsigned NoObjCARCExceptionsMDKind,
3179 DenseMap<const BasicBlock *, BBState> &BBStates) {
Michael Gottesman81c61212013-01-14 00:35:14 +00003180 /// The visited set, for doing DFS walks.
Dan Gohman59a1c932011-12-12 19:42:25 +00003181 SmallPtrSet<BasicBlock *, 16> Visited;
3182
3183 // Do DFS, computing the PostOrder.
3184 SmallPtrSet<BasicBlock *, 16> OnStack;
3185 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003186
3187 // Functions always have exactly one entry block, and we don't have
3188 // any other block that we treat like an entry block.
Dan Gohman59a1c932011-12-12 19:42:25 +00003189 BasicBlock *EntryBB = &F.getEntryBlock();
Dan Gohman0daef3d2012-05-08 23:39:44 +00003190 BBState &MyStates = BBStates[EntryBB];
3191 MyStates.SetAsEntry();
3192 TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
3193 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
Dan Gohman59a1c932011-12-12 19:42:25 +00003194 Visited.insert(EntryBB);
3195 OnStack.insert(EntryBB);
3196 do {
3197 dfs_next_succ:
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003198 BasicBlock *CurrBB = SuccStack.back().first;
3199 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
3200 succ_iterator SE(TI, false);
Dan Gohman0daef3d2012-05-08 23:39:44 +00003201
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003202 // If the terminator is an invoke marked with the
3203 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
3204 // ignored, for ARC purposes.
Michael Gottesmancf140052013-01-13 07:00:51 +00003205 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind)) {
3206 DEBUG(dbgs() << "ObjCARCOpt::ComputePostOrders: Found an invoke "
3207 "terminator marked with "
3208 "clang.arc.no_objc_arc_exceptions. Ignoring unwind "
3209 "edge.\n");
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003210 --SE;
Michael Gottesmancf140052013-01-13 07:00:51 +00003211 }
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003212
3213 while (SuccStack.back().second != SE) {
3214 BasicBlock *SuccBB = *SuccStack.back().second++;
3215 if (Visited.insert(SuccBB)) {
Dan Gohman0daef3d2012-05-08 23:39:44 +00003216 TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
3217 SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003218 BBStates[CurrBB].addSucc(SuccBB);
Dan Gohman0daef3d2012-05-08 23:39:44 +00003219 BBState &SuccStates = BBStates[SuccBB];
3220 SuccStates.addPred(CurrBB);
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003221 OnStack.insert(SuccBB);
Dan Gohman59a1c932011-12-12 19:42:25 +00003222 goto dfs_next_succ;
3223 }
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003224
3225 if (!OnStack.count(SuccBB)) {
3226 BBStates[CurrBB].addSucc(SuccBB);
3227 BBStates[SuccBB].addPred(CurrBB);
3228 }
Dan Gohman59a1c932011-12-12 19:42:25 +00003229 }
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003230 OnStack.erase(CurrBB);
3231 PostOrder.push_back(CurrBB);
3232 SuccStack.pop_back();
Dan Gohman59a1c932011-12-12 19:42:25 +00003233 } while (!SuccStack.empty());
3234
3235 Visited.clear();
3236
Dan Gohman59a1c932011-12-12 19:42:25 +00003237 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003238 // Functions may have many exits, and there also blocks which we treat
3239 // as exits due to ignored edges.
3240 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
3241 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
3242 BasicBlock *ExitBB = I;
3243 BBState &MyStates = BBStates[ExitBB];
3244 if (!MyStates.isExit())
3245 continue;
3246
Dan Gohman447989c2012-04-27 18:56:31 +00003247 MyStates.SetAsExit();
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003248
3249 PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
Dan Gohman59a1c932011-12-12 19:42:25 +00003250 Visited.insert(ExitBB);
3251 while (!PredStack.empty()) {
3252 reverse_dfs_next_succ:
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003253 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
3254 while (PredStack.back().second != PE) {
Dan Gohman59a1c932011-12-12 19:42:25 +00003255 BasicBlock *BB = *PredStack.back().second++;
Dan Gohman59a1c932011-12-12 19:42:25 +00003256 if (Visited.insert(BB)) {
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003257 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
Dan Gohman59a1c932011-12-12 19:42:25 +00003258 goto reverse_dfs_next_succ;
3259 }
3260 }
3261 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
3262 }
3263 }
3264}
3265
Michael Gottesman81c61212013-01-14 00:35:14 +00003266// Visit the function both top-down and bottom-up.
John McCall9fbd3182011-06-15 23:37:01 +00003267bool
3268ObjCARCOpt::Visit(Function &F,
3269 DenseMap<const BasicBlock *, BBState> &BBStates,
3270 MapVector<Value *, RRInfo> &Retains,
3271 DenseMap<Value *, RRInfo> &Releases) {
Dan Gohman59a1c932011-12-12 19:42:25 +00003272
3273 // Use reverse-postorder traversals, because we magically know that loops
3274 // will be well behaved, i.e. they won't repeatedly call retain on a single
3275 // pointer without doing a release. We can't use the ReversePostOrderTraversal
3276 // class here because we want the reverse-CFG postorder to consider each
3277 // function exit point, and we want to ignore selected cycle edges.
3278 SmallVector<BasicBlock *, 16> PostOrder;
3279 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003280 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
3281 NoObjCARCExceptionsMDKind,
3282 BBStates);
Dan Gohman59a1c932011-12-12 19:42:25 +00003283
3284 // Use reverse-postorder on the reverse CFG for bottom-up.
John McCall9fbd3182011-06-15 23:37:01 +00003285 bool BottomUpNestingDetected = false;
Dan Gohmanb48ef3a2011-08-18 21:27:42 +00003286 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
Dan Gohman59a1c932011-12-12 19:42:25 +00003287 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
3288 I != E; ++I)
3289 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
John McCall9fbd3182011-06-15 23:37:01 +00003290
Dan Gohman59a1c932011-12-12 19:42:25 +00003291 // Use reverse-postorder for top-down.
John McCall9fbd3182011-06-15 23:37:01 +00003292 bool TopDownNestingDetected = false;
Dan Gohman59a1c932011-12-12 19:42:25 +00003293 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
3294 PostOrder.rbegin(), E = PostOrder.rend();
3295 I != E; ++I)
3296 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
John McCall9fbd3182011-06-15 23:37:01 +00003297
3298 return TopDownNestingDetected && BottomUpNestingDetected;
3299}
3300
Michael Gottesman81c61212013-01-14 00:35:14 +00003301/// Move the calls in RetainsToMove and ReleasesToMove.
John McCall9fbd3182011-06-15 23:37:01 +00003302void ObjCARCOpt::MoveCalls(Value *Arg,
3303 RRInfo &RetainsToMove,
3304 RRInfo &ReleasesToMove,
3305 MapVector<Value *, RRInfo> &Retains,
3306 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman44280692011-07-22 22:29:21 +00003307 SmallVectorImpl<Instruction *> &DeadInsts,
3308 Module *M) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003309 Type *ArgTy = Arg->getType();
Dan Gohman44280692011-07-22 22:29:21 +00003310 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
John McCall9fbd3182011-06-15 23:37:01 +00003311
3312 // Insert the new retain and release calls.
3313 for (SmallPtrSet<Instruction *, 2>::const_iterator
3314 PI = ReleasesToMove.ReverseInsertPts.begin(),
3315 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
3316 Instruction *InsertPt = *PI;
3317 Value *MyArg = ArgTy == ParamTy ? Arg :
3318 new BitCastInst(Arg, ParamTy, "", InsertPt);
3319 CallInst *Call =
3320 CallInst::Create(RetainsToMove.IsRetainBlock ?
Dan Gohman44280692011-07-22 22:29:21 +00003321 getRetainBlockCallee(M) : getRetainCallee(M),
John McCall9fbd3182011-06-15 23:37:01 +00003322 MyArg, "", InsertPt);
3323 Call->setDoesNotThrow();
Dan Gohman79522dc2012-01-13 00:39:07 +00003324 if (RetainsToMove.IsRetainBlock)
Dan Gohmana974bea2011-10-17 22:53:25 +00003325 Call->setMetadata(CopyOnEscapeMDKind,
3326 MDNode::get(M->getContext(), ArrayRef<Value *>()));
Dan Gohman79522dc2012-01-13 00:39:07 +00003327 else
John McCall9fbd3182011-06-15 23:37:01 +00003328 Call->setTailCall();
Michael Gottesman55811152013-01-09 19:23:24 +00003329
3330 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Inserting new Release: " << *Call
3331 << "\n"
3332 " At insertion point: " << *InsertPt
3333 << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00003334 }
3335 for (SmallPtrSet<Instruction *, 2>::const_iterator
3336 PI = RetainsToMove.ReverseInsertPts.begin(),
3337 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
Dan Gohmanfbab4a82012-03-23 17:47:54 +00003338 Instruction *InsertPt = *PI;
3339 Value *MyArg = ArgTy == ParamTy ? Arg :
3340 new BitCastInst(Arg, ParamTy, "", InsertPt);
3341 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
3342 "", InsertPt);
3343 // Attach a clang.imprecise_release metadata tag, if appropriate.
3344 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
3345 Call->setMetadata(ImpreciseReleaseMDKind, M);
3346 Call->setDoesNotThrow();
3347 if (ReleasesToMove.IsTailCallRelease)
3348 Call->setTailCall();
Michael Gottesman55811152013-01-09 19:23:24 +00003349
3350 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Inserting new Retain: " << *Call
3351 << "\n"
3352 " At insertion point: " << *InsertPt
3353 << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00003354 }
3355
3356 // Delete the original retain and release calls.
3357 for (SmallPtrSet<Instruction *, 2>::const_iterator
3358 AI = RetainsToMove.Calls.begin(),
3359 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
3360 Instruction *OrigRetain = *AI;
3361 Retains.blot(OrigRetain);
3362 DeadInsts.push_back(OrigRetain);
Michael Gottesman55811152013-01-09 19:23:24 +00003363 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Deleting retain: " << *OrigRetain <<
3364 "\n");
John McCall9fbd3182011-06-15 23:37:01 +00003365 }
3366 for (SmallPtrSet<Instruction *, 2>::const_iterator
3367 AI = ReleasesToMove.Calls.begin(),
3368 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
3369 Instruction *OrigRelease = *AI;
3370 Releases.erase(OrigRelease);
3371 DeadInsts.push_back(OrigRelease);
Michael Gottesman55811152013-01-09 19:23:24 +00003372 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Deleting release: " << *OrigRelease
3373 << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00003374 }
3375}
3376
Michael Gottesman81c61212013-01-14 00:35:14 +00003377/// Identify pairings between the retains and releases, and delete and/or move
3378/// them.
John McCall9fbd3182011-06-15 23:37:01 +00003379bool
3380ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
3381 &BBStates,
3382 MapVector<Value *, RRInfo> &Retains,
Dan Gohman44280692011-07-22 22:29:21 +00003383 DenseMap<Value *, RRInfo> &Releases,
3384 Module *M) {
John McCall9fbd3182011-06-15 23:37:01 +00003385 bool AnyPairsCompletelyEliminated = false;
3386 RRInfo RetainsToMove;
3387 RRInfo ReleasesToMove;
3388 SmallVector<Instruction *, 4> NewRetains;
3389 SmallVector<Instruction *, 4> NewReleases;
3390 SmallVector<Instruction *, 8> DeadInsts;
3391
Dan Gohmand6bf2012012-04-13 18:57:48 +00003392 // Visit each retain.
John McCall9fbd3182011-06-15 23:37:01 +00003393 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
Dan Gohman597fece2011-09-29 22:25:23 +00003394 E = Retains.end(); I != E; ++I) {
3395 Value *V = I->first;
John McCall9fbd3182011-06-15 23:37:01 +00003396 if (!V) continue; // blotted
3397
3398 Instruction *Retain = cast<Instruction>(V);
Michael Gottesman55811152013-01-09 19:23:24 +00003399
3400 DEBUG(dbgs() << "ObjCARCOpt::PerformCodePlacement: Visiting: " << *Retain
3401 << "\n");
3402
John McCall9fbd3182011-06-15 23:37:01 +00003403 Value *Arg = GetObjCArg(Retain);
3404
Dan Gohman79522dc2012-01-13 00:39:07 +00003405 // If the object being released is in static or stack storage, we know it's
John McCall9fbd3182011-06-15 23:37:01 +00003406 // not being managed by ObjC reference counting, so we can delete pairs
3407 // regardless of what possible decrements or uses lie between them.
Dan Gohman79522dc2012-01-13 00:39:07 +00003408 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
Dan Gohman0daef3d2012-05-08 23:39:44 +00003409
Dan Gohman1b31ea82011-08-22 17:29:11 +00003410 // A constant pointer can't be pointing to an object on the heap. It may
3411 // be reference-counted, but it won't be deleted.
3412 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
3413 if (const GlobalVariable *GV =
3414 dyn_cast<GlobalVariable>(
3415 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
3416 if (GV->isConstant())
3417 KnownSafe = true;
3418
John McCall9fbd3182011-06-15 23:37:01 +00003419 // If a pair happens in a region where it is known that the reference count
3420 // is already incremented, we can similarly ignore possible decrements.
Dan Gohmane6d5e882011-08-19 00:26:36 +00003421 bool KnownSafeTD = true, KnownSafeBU = true;
John McCall9fbd3182011-06-15 23:37:01 +00003422
3423 // Connect the dots between the top-down-collected RetainsToMove and
3424 // bottom-up-collected ReleasesToMove to form sets of related calls.
3425 // This is an iterative process so that we connect multiple releases
3426 // to multiple retains if needed.
3427 unsigned OldDelta = 0;
3428 unsigned NewDelta = 0;
3429 unsigned OldCount = 0;
3430 unsigned NewCount = 0;
3431 bool FirstRelease = true;
3432 bool FirstRetain = true;
3433 NewRetains.push_back(Retain);
3434 for (;;) {
3435 for (SmallVectorImpl<Instruction *>::const_iterator
3436 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
3437 Instruction *NewRetain = *NI;
3438 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
3439 assert(It != Retains.end());
3440 const RRInfo &NewRetainRRI = It->second;
Dan Gohmane6d5e882011-08-19 00:26:36 +00003441 KnownSafeTD &= NewRetainRRI.KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00003442 for (SmallPtrSet<Instruction *, 2>::const_iterator
3443 LI = NewRetainRRI.Calls.begin(),
3444 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
3445 Instruction *NewRetainRelease = *LI;
3446 DenseMap<Value *, RRInfo>::const_iterator Jt =
3447 Releases.find(NewRetainRelease);
3448 if (Jt == Releases.end())
3449 goto next_retain;
3450 const RRInfo &NewRetainReleaseRRI = Jt->second;
3451 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
3452 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
3453 OldDelta -=
3454 BBStates[NewRetainRelease->getParent()].GetAllPathCount();
3455
3456 // Merge the ReleaseMetadata and IsTailCallRelease values.
3457 if (FirstRelease) {
3458 ReleasesToMove.ReleaseMetadata =
3459 NewRetainReleaseRRI.ReleaseMetadata;
3460 ReleasesToMove.IsTailCallRelease =
3461 NewRetainReleaseRRI.IsTailCallRelease;
3462 FirstRelease = false;
3463 } else {
3464 if (ReleasesToMove.ReleaseMetadata !=
3465 NewRetainReleaseRRI.ReleaseMetadata)
3466 ReleasesToMove.ReleaseMetadata = 0;
3467 if (ReleasesToMove.IsTailCallRelease !=
3468 NewRetainReleaseRRI.IsTailCallRelease)
3469 ReleasesToMove.IsTailCallRelease = false;
3470 }
3471
3472 // Collect the optimal insertion points.
3473 if (!KnownSafe)
3474 for (SmallPtrSet<Instruction *, 2>::const_iterator
3475 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
3476 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
3477 RI != RE; ++RI) {
3478 Instruction *RIP = *RI;
3479 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
3480 NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
3481 }
3482 NewReleases.push_back(NewRetainRelease);
3483 }
3484 }
3485 }
3486 NewRetains.clear();
3487 if (NewReleases.empty()) break;
3488
3489 // Back the other way.
3490 for (SmallVectorImpl<Instruction *>::const_iterator
3491 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
3492 Instruction *NewRelease = *NI;
3493 DenseMap<Value *, RRInfo>::const_iterator It =
3494 Releases.find(NewRelease);
3495 assert(It != Releases.end());
3496 const RRInfo &NewReleaseRRI = It->second;
Dan Gohmane6d5e882011-08-19 00:26:36 +00003497 KnownSafeBU &= NewReleaseRRI.KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00003498 for (SmallPtrSet<Instruction *, 2>::const_iterator
3499 LI = NewReleaseRRI.Calls.begin(),
3500 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
3501 Instruction *NewReleaseRetain = *LI;
3502 MapVector<Value *, RRInfo>::const_iterator Jt =
3503 Retains.find(NewReleaseRetain);
3504 if (Jt == Retains.end())
3505 goto next_retain;
3506 const RRInfo &NewReleaseRetainRRI = Jt->second;
3507 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
3508 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
3509 unsigned PathCount =
3510 BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
3511 OldDelta += PathCount;
3512 OldCount += PathCount;
3513
3514 // Merge the IsRetainBlock values.
3515 if (FirstRetain) {
3516 RetainsToMove.IsRetainBlock = NewReleaseRetainRRI.IsRetainBlock;
3517 FirstRetain = false;
3518 } else if (ReleasesToMove.IsRetainBlock !=
3519 NewReleaseRetainRRI.IsRetainBlock)
3520 // It's not possible to merge the sequences if one uses
3521 // objc_retain and the other uses objc_retainBlock.
3522 goto next_retain;
3523
3524 // Collect the optimal insertion points.
3525 if (!KnownSafe)
3526 for (SmallPtrSet<Instruction *, 2>::const_iterator
3527 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
3528 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
3529 RI != RE; ++RI) {
3530 Instruction *RIP = *RI;
3531 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
3532 PathCount = BBStates[RIP->getParent()].GetAllPathCount();
3533 NewDelta += PathCount;
3534 NewCount += PathCount;
3535 }
3536 }
3537 NewRetains.push_back(NewReleaseRetain);
3538 }
3539 }
3540 }
3541 NewReleases.clear();
3542 if (NewRetains.empty()) break;
3543 }
3544
Dan Gohmane6d5e882011-08-19 00:26:36 +00003545 // If the pointer is known incremented or nested, we can safely delete the
3546 // pair regardless of what's between them.
3547 if (KnownSafeTD || KnownSafeBU) {
John McCall9fbd3182011-06-15 23:37:01 +00003548 RetainsToMove.ReverseInsertPts.clear();
3549 ReleasesToMove.ReverseInsertPts.clear();
3550 NewCount = 0;
Dan Gohmana7f7db22011-08-12 00:26:31 +00003551 } else {
3552 // Determine whether the new insertion points we computed preserve the
3553 // balance of retain and release calls through the program.
3554 // TODO: If the fully aggressive solution isn't valid, try to find a
3555 // less aggressive solution which is.
3556 if (NewDelta != 0)
3557 goto next_retain;
John McCall9fbd3182011-06-15 23:37:01 +00003558 }
3559
3560 // Determine whether the original call points are balanced in the retain and
3561 // release calls through the program. If not, conservatively don't touch
3562 // them.
3563 // TODO: It's theoretically possible to do code motion in this case, as
3564 // long as the existing imbalances are maintained.
3565 if (OldDelta != 0)
3566 goto next_retain;
3567
John McCall9fbd3182011-06-15 23:37:01 +00003568 // Ok, everything checks out and we're all set. Let's move some code!
3569 Changed = true;
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003570 assert(OldCount != 0 && "Unreachable code?");
3571 AnyPairsCompletelyEliminated = NewCount == 0;
John McCall9fbd3182011-06-15 23:37:01 +00003572 NumRRs += OldCount - NewCount;
Dan Gohman44280692011-07-22 22:29:21 +00003573 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
3574 Retains, Releases, DeadInsts, M);
John McCall9fbd3182011-06-15 23:37:01 +00003575
3576 next_retain:
3577 NewReleases.clear();
3578 NewRetains.clear();
3579 RetainsToMove.clear();
3580 ReleasesToMove.clear();
3581 }
3582
3583 // Now that we're done moving everything, we can delete the newly dead
3584 // instructions, as we no longer need them as insert points.
3585 while (!DeadInsts.empty())
3586 EraseInstruction(DeadInsts.pop_back_val());
3587
3588 return AnyPairsCompletelyEliminated;
3589}
3590
Michael Gottesman81c61212013-01-14 00:35:14 +00003591/// Weak pointer optimizations.
John McCall9fbd3182011-06-15 23:37:01 +00003592void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
3593 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
3594 // itself because it uses AliasAnalysis and we need to do provenance
3595 // queries instead.
3596 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3597 Instruction *Inst = &*I++;
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00003598
Michael Gottesman5c0ae472013-01-04 21:29:57 +00003599 DEBUG(dbgs() << "ObjCARCOpt::OptimizeWeakCalls: Visiting: " << *Inst <<
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00003600 "\n");
3601
John McCall9fbd3182011-06-15 23:37:01 +00003602 InstructionClass Class = GetBasicInstructionClass(Inst);
3603 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
3604 continue;
3605
3606 // Delete objc_loadWeak calls with no users.
3607 if (Class == IC_LoadWeak && Inst->use_empty()) {
3608 Inst->eraseFromParent();
3609 continue;
3610 }
3611
3612 // TODO: For now, just look for an earlier available version of this value
3613 // within the same block. Theoretically, we could do memdep-style non-local
3614 // analysis too, but that would want caching. A better approach would be to
3615 // use the technique that EarlyCSE uses.
3616 inst_iterator Current = llvm::prior(I);
3617 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
3618 for (BasicBlock::iterator B = CurrentBB->begin(),
3619 J = Current.getInstructionIterator();
3620 J != B; --J) {
3621 Instruction *EarlierInst = &*llvm::prior(J);
3622 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
3623 switch (EarlierClass) {
3624 case IC_LoadWeak:
3625 case IC_LoadWeakRetained: {
3626 // If this is loading from the same pointer, replace this load's value
3627 // with that one.
3628 CallInst *Call = cast<CallInst>(Inst);
3629 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3630 Value *Arg = Call->getArgOperand(0);
3631 Value *EarlierArg = EarlierCall->getArgOperand(0);
3632 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3633 case AliasAnalysis::MustAlias:
3634 Changed = true;
3635 // If the load has a builtin retain, insert a plain retain for it.
3636 if (Class == IC_LoadWeakRetained) {
3637 CallInst *CI =
3638 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3639 "", Call);
3640 CI->setTailCall();
3641 }
3642 // Zap the fully redundant load.
3643 Call->replaceAllUsesWith(EarlierCall);
3644 Call->eraseFromParent();
3645 goto clobbered;
3646 case AliasAnalysis::MayAlias:
3647 case AliasAnalysis::PartialAlias:
3648 goto clobbered;
3649 case AliasAnalysis::NoAlias:
3650 break;
3651 }
3652 break;
3653 }
3654 case IC_StoreWeak:
3655 case IC_InitWeak: {
3656 // If this is storing to the same pointer and has the same size etc.
3657 // replace this load's value with the stored value.
3658 CallInst *Call = cast<CallInst>(Inst);
3659 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3660 Value *Arg = Call->getArgOperand(0);
3661 Value *EarlierArg = EarlierCall->getArgOperand(0);
3662 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3663 case AliasAnalysis::MustAlias:
3664 Changed = true;
3665 // If the load has a builtin retain, insert a plain retain for it.
3666 if (Class == IC_LoadWeakRetained) {
3667 CallInst *CI =
3668 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3669 "", Call);
3670 CI->setTailCall();
3671 }
3672 // Zap the fully redundant load.
3673 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
3674 Call->eraseFromParent();
3675 goto clobbered;
3676 case AliasAnalysis::MayAlias:
3677 case AliasAnalysis::PartialAlias:
3678 goto clobbered;
3679 case AliasAnalysis::NoAlias:
3680 break;
3681 }
3682 break;
3683 }
3684 case IC_MoveWeak:
3685 case IC_CopyWeak:
3686 // TOOD: Grab the copied value.
3687 goto clobbered;
3688 case IC_AutoreleasepoolPush:
3689 case IC_None:
3690 case IC_User:
3691 // Weak pointers are only modified through the weak entry points
3692 // (and arbitrary calls, which could call the weak entry points).
3693 break;
3694 default:
3695 // Anything else could modify the weak pointer.
3696 goto clobbered;
3697 }
3698 }
3699 clobbered:;
3700 }
3701
3702 // Then, for each destroyWeak with an alloca operand, check to see if
3703 // the alloca and all its users can be zapped.
3704 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3705 Instruction *Inst = &*I++;
3706 InstructionClass Class = GetBasicInstructionClass(Inst);
3707 if (Class != IC_DestroyWeak)
3708 continue;
3709
3710 CallInst *Call = cast<CallInst>(Inst);
3711 Value *Arg = Call->getArgOperand(0);
3712 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
3713 for (Value::use_iterator UI = Alloca->use_begin(),
3714 UE = Alloca->use_end(); UI != UE; ++UI) {
Dan Gohman447989c2012-04-27 18:56:31 +00003715 const Instruction *UserInst = cast<Instruction>(*UI);
John McCall9fbd3182011-06-15 23:37:01 +00003716 switch (GetBasicInstructionClass(UserInst)) {
3717 case IC_InitWeak:
3718 case IC_StoreWeak:
3719 case IC_DestroyWeak:
3720 continue;
3721 default:
3722 goto done;
3723 }
3724 }
3725 Changed = true;
3726 for (Value::use_iterator UI = Alloca->use_begin(),
3727 UE = Alloca->use_end(); UI != UE; ) {
3728 CallInst *UserInst = cast<CallInst>(*UI++);
Dan Gohmance5d8b02012-05-18 22:17:29 +00003729 switch (GetBasicInstructionClass(UserInst)) {
3730 case IC_InitWeak:
3731 case IC_StoreWeak:
3732 // These functions return their second argument.
3733 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
3734 break;
3735 case IC_DestroyWeak:
3736 // No return value.
3737 break;
3738 default:
Dan Gohman4c8f9092012-05-21 17:41:28 +00003739 llvm_unreachable("alloca really is used!");
Dan Gohmance5d8b02012-05-18 22:17:29 +00003740 }
John McCall9fbd3182011-06-15 23:37:01 +00003741 UserInst->eraseFromParent();
3742 }
3743 Alloca->eraseFromParent();
3744 done:;
3745 }
3746 }
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00003747
Michael Gottesman5c0ae472013-01-04 21:29:57 +00003748 DEBUG(dbgs() << "ObjCARCOpt::OptimizeWeakCalls: Finished List.\n\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00003749
John McCall9fbd3182011-06-15 23:37:01 +00003750}
3751
Michael Gottesman81c61212013-01-14 00:35:14 +00003752/// Identify program paths which execute sequences of retains and releases which
3753/// can be eliminated.
John McCall9fbd3182011-06-15 23:37:01 +00003754bool ObjCARCOpt::OptimizeSequences(Function &F) {
3755 /// Releases, Retains - These are used to store the results of the main flow
3756 /// analysis. These use Value* as the key instead of Instruction* so that the
3757 /// map stays valid when we get around to rewriting code and calls get
3758 /// replaced by arguments.
3759 DenseMap<Value *, RRInfo> Releases;
3760 MapVector<Value *, RRInfo> Retains;
3761
Michael Gottesman81c61212013-01-14 00:35:14 +00003762 /// This is used during the traversal of the function to track the
John McCall9fbd3182011-06-15 23:37:01 +00003763 /// states for each identified object at each block.
3764 DenseMap<const BasicBlock *, BBState> BBStates;
3765
3766 // Analyze the CFG of the function, and all instructions.
3767 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
3768
3769 // Transform.
Dan Gohman44280692011-07-22 22:29:21 +00003770 return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) &&
3771 NestingDetected;
John McCall9fbd3182011-06-15 23:37:01 +00003772}
3773
Michael Gottesman81c61212013-01-14 00:35:14 +00003774/// Look for this pattern:
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +00003775/// \code
John McCall9fbd3182011-06-15 23:37:01 +00003776/// %call = call i8* @something(...)
3777/// %2 = call i8* @objc_retain(i8* %call)
3778/// %3 = call i8* @objc_autorelease(i8* %2)
3779/// ret i8* %3
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +00003780/// \endcode
John McCall9fbd3182011-06-15 23:37:01 +00003781/// And delete the retain and autorelease.
3782///
3783/// Otherwise if it's just this:
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +00003784/// \code
John McCall9fbd3182011-06-15 23:37:01 +00003785/// %3 = call i8* @objc_autorelease(i8* %2)
3786/// ret i8* %3
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +00003787/// \endcode
John McCall9fbd3182011-06-15 23:37:01 +00003788/// convert the autorelease to autoreleaseRV.
3789void ObjCARCOpt::OptimizeReturns(Function &F) {
3790 if (!F.getReturnType()->isPointerTy())
3791 return;
3792
3793 SmallPtrSet<Instruction *, 4> DependingInstructions;
3794 SmallPtrSet<const BasicBlock *, 4> Visited;
3795 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3796 BasicBlock *BB = FI;
3797 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00003798
Michael Gottesman5c0ae472013-01-04 21:29:57 +00003799 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Visiting: " << *Ret << "\n");
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00003800
John McCall9fbd3182011-06-15 23:37:01 +00003801 if (!Ret) continue;
3802
3803 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
3804 FindDependencies(NeedsPositiveRetainCount, Arg,
3805 BB, Ret, DependingInstructions, Visited, PA);
3806 if (DependingInstructions.size() != 1)
3807 goto next_block;
3808
3809 {
3810 CallInst *Autorelease =
3811 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3812 if (!Autorelease)
3813 goto next_block;
Dan Gohman0daef3d2012-05-08 23:39:44 +00003814 InstructionClass AutoreleaseClass = GetBasicInstructionClass(Autorelease);
John McCall9fbd3182011-06-15 23:37:01 +00003815 if (!IsAutorelease(AutoreleaseClass))
3816 goto next_block;
3817 if (GetObjCArg(Autorelease) != Arg)
3818 goto next_block;
3819
3820 DependingInstructions.clear();
3821 Visited.clear();
3822
3823 // Check that there is nothing that can affect the reference
3824 // count between the autorelease and the retain.
3825 FindDependencies(CanChangeRetainCount, Arg,
3826 BB, Autorelease, DependingInstructions, Visited, PA);
3827 if (DependingInstructions.size() != 1)
3828 goto next_block;
3829
3830 {
3831 CallInst *Retain =
3832 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3833
3834 // Check that we found a retain with the same argument.
3835 if (!Retain ||
3836 !IsRetain(GetBasicInstructionClass(Retain)) ||
3837 GetObjCArg(Retain) != Arg)
3838 goto next_block;
3839
3840 DependingInstructions.clear();
3841 Visited.clear();
3842
3843 // Convert the autorelease to an autoreleaseRV, since it's
3844 // returning the value.
3845 if (AutoreleaseClass == IC_Autorelease) {
Michael Gottesman5dc30012013-01-10 02:03:50 +00003846 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Converting autorelease "
3847 "=> autoreleaseRV since it's returning a value.\n"
3848 " In: " << *Autorelease
3849 << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00003850 Autorelease->setCalledFunction(getAutoreleaseRVCallee(F.getParent()));
Michael Gottesman5dc30012013-01-10 02:03:50 +00003851 DEBUG(dbgs() << " Out: " << *Autorelease
3852 << "\n");
Michael Gottesmane8c161a2013-01-12 01:25:15 +00003853 Autorelease->setTailCall(); // Always tail call autoreleaseRV.
John McCall9fbd3182011-06-15 23:37:01 +00003854 AutoreleaseClass = IC_AutoreleaseRV;
3855 }
3856
3857 // Check that there is nothing that can affect the reference
3858 // count between the retain and the call.
Dan Gohman27e06662011-09-29 22:27:34 +00003859 // Note that Retain need not be in BB.
3860 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
John McCall9fbd3182011-06-15 23:37:01 +00003861 DependingInstructions, Visited, PA);
3862 if (DependingInstructions.size() != 1)
3863 goto next_block;
3864
3865 {
3866 CallInst *Call =
3867 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3868
3869 // Check that the pointer is the return value of the call.
3870 if (!Call || Arg != Call)
3871 goto next_block;
3872
3873 // Check that the call is a regular call.
3874 InstructionClass Class = GetBasicInstructionClass(Call);
3875 if (Class != IC_CallOrUser && Class != IC_Call)
3876 goto next_block;
3877
3878 // If so, we can zap the retain and autorelease.
3879 Changed = true;
3880 ++NumRets;
Michael Gottesmanf93109a2013-01-07 00:04:56 +00003881 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Erasing: " << *Retain
3882 << "\n Erasing: "
3883 << *Autorelease << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00003884 EraseInstruction(Retain);
3885 EraseInstruction(Autorelease);
3886 }
3887 }
3888 }
3889
3890 next_block:
3891 DependingInstructions.clear();
3892 Visited.clear();
3893 }
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00003894
Michael Gottesman5c0ae472013-01-04 21:29:57 +00003895 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Finished List.\n\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00003896
John McCall9fbd3182011-06-15 23:37:01 +00003897}
3898
3899bool ObjCARCOpt::doInitialization(Module &M) {
3900 if (!EnableARCOpts)
3901 return false;
3902
Dan Gohmand6bf2012012-04-13 18:57:48 +00003903 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003904 Run = ModuleHasARC(M);
3905 if (!Run)
3906 return false;
3907
John McCall9fbd3182011-06-15 23:37:01 +00003908 // Identify the imprecise release metadata kind.
3909 ImpreciseReleaseMDKind =
3910 M.getContext().getMDKindID("clang.imprecise_release");
Dan Gohmana974bea2011-10-17 22:53:25 +00003911 CopyOnEscapeMDKind =
3912 M.getContext().getMDKindID("clang.arc.copy_on_escape");
Dan Gohmandbe266b2012-02-17 18:59:53 +00003913 NoObjCARCExceptionsMDKind =
3914 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
John McCall9fbd3182011-06-15 23:37:01 +00003915
John McCall9fbd3182011-06-15 23:37:01 +00003916 // Intuitively, objc_retain and others are nocapture, however in practice
3917 // they are not, because they return their argument value. And objc_release
Dan Gohman447989c2012-04-27 18:56:31 +00003918 // calls finalizers which can have arbitrary side effects.
John McCall9fbd3182011-06-15 23:37:01 +00003919
3920 // These are initialized lazily.
3921 RetainRVCallee = 0;
3922 AutoreleaseRVCallee = 0;
3923 ReleaseCallee = 0;
3924 RetainCallee = 0;
Dan Gohman44280692011-07-22 22:29:21 +00003925 RetainBlockCallee = 0;
John McCall9fbd3182011-06-15 23:37:01 +00003926 AutoreleaseCallee = 0;
3927
3928 return false;
3929}
3930
3931bool ObjCARCOpt::runOnFunction(Function &F) {
3932 if (!EnableARCOpts)
3933 return false;
3934
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003935 // If nothing in the Module uses ARC, don't do anything.
3936 if (!Run)
3937 return false;
3938
John McCall9fbd3182011-06-15 23:37:01 +00003939 Changed = false;
3940
Michael Gottesman0d3582b2013-01-12 02:57:16 +00003941 DEBUG(dbgs() << "ObjCARCOpt: Visiting Function: " << F.getName() << "\n");
3942
John McCall9fbd3182011-06-15 23:37:01 +00003943 PA.setAA(&getAnalysis<AliasAnalysis>());
3944
3945 // This pass performs several distinct transformations. As a compile-time aid
3946 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3947 // library functions aren't declared.
3948
3949 // Preliminary optimizations. This also computs UsedInThisFunction.
3950 OptimizeIndividualCalls(F);
3951
3952 // Optimizations for weak pointers.
3953 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3954 (1 << IC_LoadWeakRetained) |
3955 (1 << IC_StoreWeak) |
3956 (1 << IC_InitWeak) |
3957 (1 << IC_CopyWeak) |
3958 (1 << IC_MoveWeak) |
3959 (1 << IC_DestroyWeak)))
3960 OptimizeWeakCalls(F);
3961
3962 // Optimizations for retain+release pairs.
3963 if (UsedInThisFunction & ((1 << IC_Retain) |
3964 (1 << IC_RetainRV) |
3965 (1 << IC_RetainBlock)))
3966 if (UsedInThisFunction & (1 << IC_Release))
3967 // Run OptimizeSequences until it either stops making changes or
3968 // no retain+release pair nesting is detected.
3969 while (OptimizeSequences(F)) {}
3970
3971 // Optimizations if objc_autorelease is used.
Dan Gohman0daef3d2012-05-08 23:39:44 +00003972 if (UsedInThisFunction & ((1 << IC_Autorelease) |
3973 (1 << IC_AutoreleaseRV)))
John McCall9fbd3182011-06-15 23:37:01 +00003974 OptimizeReturns(F);
3975
Michael Gottesman0d3582b2013-01-12 02:57:16 +00003976 DEBUG(dbgs() << "\n");
3977
John McCall9fbd3182011-06-15 23:37:01 +00003978 return Changed;
3979}
3980
3981void ObjCARCOpt::releaseMemory() {
3982 PA.clear();
3983}
3984
Michael Gottesman81c61212013-01-14 00:35:14 +00003985/// @}
3986///
3987/// \defgroup ARCContract ARC Contraction.
3988/// @{
John McCall9fbd3182011-06-15 23:37:01 +00003989
3990// TODO: ObjCARCContract could insert PHI nodes when uses aren't
3991// dominated by single calls.
3992
John McCall9fbd3182011-06-15 23:37:01 +00003993#include "llvm/Analysis/Dominators.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +00003994#include "llvm/IR/InlineAsm.h"
3995#include "llvm/IR/Operator.h"
John McCall9fbd3182011-06-15 23:37:01 +00003996
3997STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed");
3998
3999namespace {
Michael Gottesman81c61212013-01-14 00:35:14 +00004000 /// \brief Late ARC optimizations
4001 ///
4002 /// These change the IR in a way that makes it difficult to be analyzed by
4003 /// ObjCARCOpt, so it's run late.
John McCall9fbd3182011-06-15 23:37:01 +00004004 class ObjCARCContract : public FunctionPass {
4005 bool Changed;
4006 AliasAnalysis *AA;
4007 DominatorTree *DT;
4008 ProvenanceAnalysis PA;
4009
Michael Gottesman81c61212013-01-14 00:35:14 +00004010 /// A flag indicating whether this optimization pass should run.
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00004011 bool Run;
4012
Michael Gottesman81c61212013-01-14 00:35:14 +00004013 /// Declarations for ObjC runtime functions, for use in creating calls to
4014 /// them. These are initialized lazily to avoid cluttering up the Module
4015 /// with unused declarations.
John McCall9fbd3182011-06-15 23:37:01 +00004016
Michael Gottesman81c61212013-01-14 00:35:14 +00004017 /// Declaration for objc_storeStrong().
4018 Constant *StoreStrongCallee;
4019 /// Declaration for objc_retainAutorelease().
4020 Constant *RetainAutoreleaseCallee;
4021 /// Declaration for objc_retainAutoreleaseReturnValue().
4022 Constant *RetainAutoreleaseRVCallee;
4023
4024 /// The inline asm string to insert between calls and RetainRV calls to make
4025 /// the optimization work on targets which need it.
John McCall9fbd3182011-06-15 23:37:01 +00004026 const MDString *RetainRVMarker;
4027
Michael Gottesman81c61212013-01-14 00:35:14 +00004028 /// The set of inserted objc_storeStrong calls. If at the end of walking the
4029 /// function we have found no alloca instructions, these calls can be marked
4030 /// "tail".
Dan Gohman0daef3d2012-05-08 23:39:44 +00004031 SmallPtrSet<CallInst *, 8> StoreStrongCalls;
Dan Gohman0cdece42012-01-19 19:14:36 +00004032
John McCall9fbd3182011-06-15 23:37:01 +00004033 Constant *getStoreStrongCallee(Module *M);
4034 Constant *getRetainAutoreleaseCallee(Module *M);
4035 Constant *getRetainAutoreleaseRVCallee(Module *M);
4036
4037 bool ContractAutorelease(Function &F, Instruction *Autorelease,
4038 InstructionClass Class,
4039 SmallPtrSet<Instruction *, 4>
4040 &DependingInstructions,
4041 SmallPtrSet<const BasicBlock *, 4>
4042 &Visited);
4043
4044 void ContractRelease(Instruction *Release,
4045 inst_iterator &Iter);
4046
4047 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
4048 virtual bool doInitialization(Module &M);
4049 virtual bool runOnFunction(Function &F);
4050
4051 public:
4052 static char ID;
4053 ObjCARCContract() : FunctionPass(ID) {
4054 initializeObjCARCContractPass(*PassRegistry::getPassRegistry());
4055 }
4056 };
4057}
4058
4059char ObjCARCContract::ID = 0;
4060INITIALIZE_PASS_BEGIN(ObjCARCContract,
4061 "objc-arc-contract", "ObjC ARC contraction", false, false)
4062INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
4063INITIALIZE_PASS_DEPENDENCY(DominatorTree)
4064INITIALIZE_PASS_END(ObjCARCContract,
4065 "objc-arc-contract", "ObjC ARC contraction", false, false)
4066
4067Pass *llvm::createObjCARCContractPass() {
4068 return new ObjCARCContract();
4069}
4070
4071void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const {
4072 AU.addRequired<AliasAnalysis>();
4073 AU.addRequired<DominatorTree>();
4074 AU.setPreservesCFG();
4075}
4076
4077Constant *ObjCARCContract::getStoreStrongCallee(Module *M) {
4078 if (!StoreStrongCallee) {
4079 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00004080 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
4081 Type *I8XX = PointerType::getUnqual(I8X);
Dan Gohman0daef3d2012-05-08 23:39:44 +00004082 Type *Params[] = { I8XX, I8X };
John McCall9fbd3182011-06-15 23:37:01 +00004083
Bill Wendling034b94b2012-12-19 07:18:57 +00004084 AttributeSet Attribute = AttributeSet()
Bill Wendling99faa3b2012-12-07 23:16:57 +00004085 .addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00004086 Attribute::get(C, Attribute::NoUnwind))
4087 .addAttr(M->getContext(), 1, Attribute::get(C, Attribute::NoCapture));
John McCall9fbd3182011-06-15 23:37:01 +00004088
4089 StoreStrongCallee =
4090 M->getOrInsertFunction(
4091 "objc_storeStrong",
4092 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
Bill Wendling034b94b2012-12-19 07:18:57 +00004093 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00004094 }
4095 return StoreStrongCallee;
4096}
4097
4098Constant *ObjCARCContract::getRetainAutoreleaseCallee(Module *M) {
4099 if (!RetainAutoreleaseCallee) {
4100 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00004101 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman0daef3d2012-05-08 23:39:44 +00004102 Type *Params[] = { I8X };
4103 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling034b94b2012-12-19 07:18:57 +00004104 AttributeSet Attribute =
Bill Wendling99faa3b2012-12-07 23:16:57 +00004105 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00004106 Attribute::get(C, Attribute::NoUnwind));
John McCall9fbd3182011-06-15 23:37:01 +00004107 RetainAutoreleaseCallee =
Bill Wendling034b94b2012-12-19 07:18:57 +00004108 M->getOrInsertFunction("objc_retainAutorelease", FTy, Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00004109 }
4110 return RetainAutoreleaseCallee;
4111}
4112
4113Constant *ObjCARCContract::getRetainAutoreleaseRVCallee(Module *M) {
4114 if (!RetainAutoreleaseRVCallee) {
4115 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00004116 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman0daef3d2012-05-08 23:39:44 +00004117 Type *Params[] = { I8X };
4118 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling034b94b2012-12-19 07:18:57 +00004119 AttributeSet Attribute =
Bill Wendling99faa3b2012-12-07 23:16:57 +00004120 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00004121 Attribute::get(C, Attribute::NoUnwind));
John McCall9fbd3182011-06-15 23:37:01 +00004122 RetainAutoreleaseRVCallee =
4123 M->getOrInsertFunction("objc_retainAutoreleaseReturnValue", FTy,
Bill Wendling034b94b2012-12-19 07:18:57 +00004124 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00004125 }
4126 return RetainAutoreleaseRVCallee;
4127}
4128
Michael Gottesman81c61212013-01-14 00:35:14 +00004129/// Merge an autorelease with a retain into a fused call.
John McCall9fbd3182011-06-15 23:37:01 +00004130bool
4131ObjCARCContract::ContractAutorelease(Function &F, Instruction *Autorelease,
4132 InstructionClass Class,
4133 SmallPtrSet<Instruction *, 4>
4134 &DependingInstructions,
4135 SmallPtrSet<const BasicBlock *, 4>
4136 &Visited) {
4137 const Value *Arg = GetObjCArg(Autorelease);
4138
4139 // Check that there are no instructions between the retain and the autorelease
4140 // (such as an autorelease_pop) which may change the count.
4141 CallInst *Retain = 0;
4142 if (Class == IC_AutoreleaseRV)
4143 FindDependencies(RetainAutoreleaseRVDep, Arg,
4144 Autorelease->getParent(), Autorelease,
4145 DependingInstructions, Visited, PA);
4146 else
4147 FindDependencies(RetainAutoreleaseDep, Arg,
4148 Autorelease->getParent(), Autorelease,
4149 DependingInstructions, Visited, PA);
4150
4151 Visited.clear();
4152 if (DependingInstructions.size() != 1) {
4153 DependingInstructions.clear();
4154 return false;
4155 }
4156
4157 Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
4158 DependingInstructions.clear();
4159
4160 if (!Retain ||
4161 GetBasicInstructionClass(Retain) != IC_Retain ||
4162 GetObjCArg(Retain) != Arg)
4163 return false;
4164
4165 Changed = true;
4166 ++NumPeeps;
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004167
Michael Gottesman916d52a2013-01-07 00:31:26 +00004168 DEBUG(dbgs() << "ObjCARCContract::ContractAutorelease: Fusing "
4169 "retain/autorelease. Erasing: " << *Autorelease << "\n"
4170 " Old Retain: "
4171 << *Retain << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004172
John McCall9fbd3182011-06-15 23:37:01 +00004173 if (Class == IC_AutoreleaseRV)
4174 Retain->setCalledFunction(getRetainAutoreleaseRVCallee(F.getParent()));
4175 else
4176 Retain->setCalledFunction(getRetainAutoreleaseCallee(F.getParent()));
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004177
Michael Gottesman916d52a2013-01-07 00:31:26 +00004178 DEBUG(dbgs() << " New Retain: "
4179 << *Retain << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004180
John McCall9fbd3182011-06-15 23:37:01 +00004181 EraseInstruction(Autorelease);
4182 return true;
4183}
4184
Michael Gottesman81c61212013-01-14 00:35:14 +00004185/// Attempt to merge an objc_release with a store, load, and objc_retain to form
4186/// an objc_storeStrong. This can be a little tricky because the instructions
4187/// don't always appear in order, and there may be unrelated intervening
4188/// instructions.
John McCall9fbd3182011-06-15 23:37:01 +00004189void ObjCARCContract::ContractRelease(Instruction *Release,
4190 inst_iterator &Iter) {
4191 LoadInst *Load = dyn_cast<LoadInst>(GetObjCArg(Release));
Eli Friedman2bc3d522011-09-12 20:23:13 +00004192 if (!Load || !Load->isSimple()) return;
John McCall9fbd3182011-06-15 23:37:01 +00004193
4194 // For now, require everything to be in one basic block.
4195 BasicBlock *BB = Release->getParent();
4196 if (Load->getParent() != BB) return;
4197
Dan Gohman4670dac2012-05-08 23:34:08 +00004198 // Walk down to find the store and the release, which may be in either order.
Dan Gohman95b8cf12012-05-09 23:08:33 +00004199 BasicBlock::iterator I = Load, End = BB->end();
John McCall9fbd3182011-06-15 23:37:01 +00004200 ++I;
4201 AliasAnalysis::Location Loc = AA->getLocation(Load);
Dan Gohman4670dac2012-05-08 23:34:08 +00004202 StoreInst *Store = 0;
4203 bool SawRelease = false;
4204 for (; !Store || !SawRelease; ++I) {
Dan Gohman95b8cf12012-05-09 23:08:33 +00004205 if (I == End)
4206 return;
4207
Dan Gohman4670dac2012-05-08 23:34:08 +00004208 Instruction *Inst = I;
4209 if (Inst == Release) {
4210 SawRelease = true;
4211 continue;
4212 }
4213
4214 InstructionClass Class = GetBasicInstructionClass(Inst);
4215
4216 // Unrelated retains are harmless.
4217 if (IsRetain(Class))
4218 continue;
4219
4220 if (Store) {
4221 // The store is the point where we're going to put the objc_storeStrong,
4222 // so make sure there are no uses after it.
4223 if (CanUse(Inst, Load, PA, Class))
4224 return;
4225 } else if (AA->getModRefInfo(Inst, Loc) & AliasAnalysis::Mod) {
4226 // We are moving the load down to the store, so check for anything
4227 // else which writes to the memory between the load and the store.
4228 Store = dyn_cast<StoreInst>(Inst);
4229 if (!Store || !Store->isSimple()) return;
4230 if (Store->getPointerOperand() != Loc.Ptr) return;
4231 }
4232 }
John McCall9fbd3182011-06-15 23:37:01 +00004233
4234 Value *New = StripPointerCastsAndObjCCalls(Store->getValueOperand());
4235
4236 // Walk up to find the retain.
4237 I = Store;
4238 BasicBlock::iterator Begin = BB->begin();
4239 while (I != Begin && GetBasicInstructionClass(I) != IC_Retain)
4240 --I;
4241 Instruction *Retain = I;
4242 if (GetBasicInstructionClass(Retain) != IC_Retain) return;
4243 if (GetObjCArg(Retain) != New) return;
4244
4245 Changed = true;
4246 ++NumStoreStrongs;
4247
4248 LLVMContext &C = Release->getContext();
Chris Lattnerdb125cf2011-07-18 04:54:35 +00004249 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
4250 Type *I8XX = PointerType::getUnqual(I8X);
John McCall9fbd3182011-06-15 23:37:01 +00004251
4252 Value *Args[] = { Load->getPointerOperand(), New };
4253 if (Args[0]->getType() != I8XX)
4254 Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
4255 if (Args[1]->getType() != I8X)
4256 Args[1] = new BitCastInst(Args[1], I8X, "", Store);
4257 CallInst *StoreStrong =
4258 CallInst::Create(getStoreStrongCallee(BB->getParent()->getParent()),
Jay Foada3efbb12011-07-15 08:37:34 +00004259 Args, "", Store);
John McCall9fbd3182011-06-15 23:37:01 +00004260 StoreStrong->setDoesNotThrow();
4261 StoreStrong->setDebugLoc(Store->getDebugLoc());
4262
Dan Gohman0cdece42012-01-19 19:14:36 +00004263 // We can't set the tail flag yet, because we haven't yet determined
4264 // whether there are any escaping allocas. Remember this call, so that
4265 // we can set the tail flag once we know it's safe.
4266 StoreStrongCalls.insert(StoreStrong);
4267
John McCall9fbd3182011-06-15 23:37:01 +00004268 if (&*Iter == Store) ++Iter;
4269 Store->eraseFromParent();
4270 Release->eraseFromParent();
4271 EraseInstruction(Retain);
4272 if (Load->use_empty())
4273 Load->eraseFromParent();
4274}
4275
4276bool ObjCARCContract::doInitialization(Module &M) {
Dan Gohmand6bf2012012-04-13 18:57:48 +00004277 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00004278 Run = ModuleHasARC(M);
4279 if (!Run)
4280 return false;
4281
John McCall9fbd3182011-06-15 23:37:01 +00004282 // These are initialized lazily.
4283 StoreStrongCallee = 0;
4284 RetainAutoreleaseCallee = 0;
4285 RetainAutoreleaseRVCallee = 0;
4286
4287 // Initialize RetainRVMarker.
4288 RetainRVMarker = 0;
4289 if (NamedMDNode *NMD =
4290 M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker"))
4291 if (NMD->getNumOperands() == 1) {
4292 const MDNode *N = NMD->getOperand(0);
4293 if (N->getNumOperands() == 1)
4294 if (const MDString *S = dyn_cast<MDString>(N->getOperand(0)))
4295 RetainRVMarker = S;
4296 }
4297
4298 return false;
4299}
4300
4301bool ObjCARCContract::runOnFunction(Function &F) {
4302 if (!EnableARCOpts)
4303 return false;
4304
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00004305 // If nothing in the Module uses ARC, don't do anything.
4306 if (!Run)
4307 return false;
4308
John McCall9fbd3182011-06-15 23:37:01 +00004309 Changed = false;
4310 AA = &getAnalysis<AliasAnalysis>();
4311 DT = &getAnalysis<DominatorTree>();
4312
4313 PA.setAA(&getAnalysis<AliasAnalysis>());
4314
Dan Gohman0cdece42012-01-19 19:14:36 +00004315 // Track whether it's ok to mark objc_storeStrong calls with the "tail"
4316 // keyword. Be conservative if the function has variadic arguments.
4317 // It seems that functions which "return twice" are also unsafe for the
4318 // "tail" argument, because they are setjmp, which could need to
4319 // return to an earlier stack state.
Dan Gohman0daef3d2012-05-08 23:39:44 +00004320 bool TailOkForStoreStrongs = !F.isVarArg() &&
4321 !F.callsFunctionThatReturnsTwice();
Dan Gohman0cdece42012-01-19 19:14:36 +00004322
John McCall9fbd3182011-06-15 23:37:01 +00004323 // For ObjC library calls which return their argument, replace uses of the
4324 // argument with uses of the call return value, if it dominates the use. This
4325 // reduces register pressure.
4326 SmallPtrSet<Instruction *, 4> DependingInstructions;
4327 SmallPtrSet<const BasicBlock *, 4> Visited;
4328 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
4329 Instruction *Inst = &*I++;
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004330
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00004331 DEBUG(dbgs() << "ObjCARCContract: Visiting: " << *Inst << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004332
John McCall9fbd3182011-06-15 23:37:01 +00004333 // Only these library routines return their argument. In particular,
4334 // objc_retainBlock does not necessarily return its argument.
4335 InstructionClass Class = GetBasicInstructionClass(Inst);
4336 switch (Class) {
4337 case IC_Retain:
4338 case IC_FusedRetainAutorelease:
4339 case IC_FusedRetainAutoreleaseRV:
4340 break;
4341 case IC_Autorelease:
4342 case IC_AutoreleaseRV:
4343 if (ContractAutorelease(F, Inst, Class, DependingInstructions, Visited))
4344 continue;
4345 break;
4346 case IC_RetainRV: {
4347 // If we're compiling for a target which needs a special inline-asm
4348 // marker to do the retainAutoreleasedReturnValue optimization,
4349 // insert it now.
4350 if (!RetainRVMarker)
4351 break;
4352 BasicBlock::iterator BBI = Inst;
Dan Gohman58fb3402012-06-25 19:47:37 +00004353 BasicBlock *InstParent = Inst->getParent();
4354
4355 // Step up to see if the call immediately precedes the RetainRV call.
4356 // If it's an invoke, we have to cross a block boundary. And we have
4357 // to carefully dodge no-op instructions.
4358 do {
4359 if (&*BBI == InstParent->begin()) {
4360 BasicBlock *Pred = InstParent->getSinglePredecessor();
4361 if (!Pred)
4362 goto decline_rv_optimization;
4363 BBI = Pred->getTerminator();
4364 break;
4365 }
4366 --BBI;
4367 } while (isNoopInstruction(BBI));
4368
John McCall9fbd3182011-06-15 23:37:01 +00004369 if (&*BBI == GetObjCArg(Inst)) {
Michael Gottesman50652cd2013-01-03 07:32:41 +00004370 DEBUG(dbgs() << "ObjCARCContract: Adding inline asm marker for "
Michael Gottesman5c0ae472013-01-04 21:29:57 +00004371 "retainAutoreleasedReturnValue optimization.\n");
Dan Gohmand6bf2012012-04-13 18:57:48 +00004372 Changed = true;
John McCall9fbd3182011-06-15 23:37:01 +00004373 InlineAsm *IA =
4374 InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()),
4375 /*isVarArg=*/false),
4376 RetainRVMarker->getString(),
4377 /*Constraints=*/"", /*hasSideEffects=*/true);
4378 CallInst::Create(IA, "", Inst);
4379 }
Dan Gohman58fb3402012-06-25 19:47:37 +00004380 decline_rv_optimization:
John McCall9fbd3182011-06-15 23:37:01 +00004381 break;
4382 }
4383 case IC_InitWeak: {
4384 // objc_initWeak(p, null) => *p = null
4385 CallInst *CI = cast<CallInst>(Inst);
4386 if (isNullOrUndef(CI->getArgOperand(1))) {
4387 Value *Null =
4388 ConstantPointerNull::get(cast<PointerType>(CI->getType()));
4389 Changed = true;
4390 new StoreInst(Null, CI->getArgOperand(0), CI);
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004391
Michael Gottesman1ebbdcf2013-01-03 07:32:53 +00004392 DEBUG(dbgs() << "OBJCARCContract: Old = " << *CI << "\n"
4393 << " New = " << *Null << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004394
John McCall9fbd3182011-06-15 23:37:01 +00004395 CI->replaceAllUsesWith(Null);
4396 CI->eraseFromParent();
4397 }
4398 continue;
4399 }
4400 case IC_Release:
4401 ContractRelease(Inst, I);
4402 continue;
Dan Gohman0cdece42012-01-19 19:14:36 +00004403 case IC_User:
4404 // Be conservative if the function has any alloca instructions.
4405 // Technically we only care about escaping alloca instructions,
4406 // but this is sufficient to handle some interesting cases.
4407 if (isa<AllocaInst>(Inst))
4408 TailOkForStoreStrongs = false;
4409 continue;
John McCall9fbd3182011-06-15 23:37:01 +00004410 default:
4411 continue;
4412 }
4413
Michael Gottesmanec21e2a2013-01-03 08:09:27 +00004414 DEBUG(dbgs() << "ObjCARCContract: Finished List.\n\n");
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00004415
John McCall9fbd3182011-06-15 23:37:01 +00004416 // Don't use GetObjCArg because we don't want to look through bitcasts
4417 // and such; to do the replacement, the argument must have type i8*.
4418 const Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
4419 for (;;) {
4420 // If we're compiling bugpointed code, don't get in trouble.
4421 if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
4422 break;
4423 // Look through the uses of the pointer.
4424 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
4425 UI != UE; ) {
4426 Use &U = UI.getUse();
4427 unsigned OperandNo = UI.getOperandNo();
4428 ++UI; // Increment UI now, because we may unlink its element.
Dan Gohmand6bf2012012-04-13 18:57:48 +00004429
4430 // If the call's return value dominates a use of the call's argument
4431 // value, rewrite the use to use the return value. We check for
4432 // reachability here because an unreachable call is considered to
4433 // trivially dominate itself, which would lead us to rewriting its
4434 // argument in terms of its return value, which would lead to
4435 // infinite loops in GetObjCArg.
Dan Gohman0daef3d2012-05-08 23:39:44 +00004436 if (DT->isReachableFromEntry(U) && DT->dominates(Inst, U)) {
Rafael Espindola2453dff2012-03-15 15:52:59 +00004437 Changed = true;
4438 Instruction *Replacement = Inst;
4439 Type *UseTy = U.get()->getType();
Dan Gohman6c189ec2012-04-13 01:08:28 +00004440 if (PHINode *PHI = dyn_cast<PHINode>(U.getUser())) {
Rafael Espindola2453dff2012-03-15 15:52:59 +00004441 // For PHI nodes, insert the bitcast in the predecessor block.
Dan Gohman0daef3d2012-05-08 23:39:44 +00004442 unsigned ValNo = PHINode::getIncomingValueNumForOperand(OperandNo);
4443 BasicBlock *BB = PHI->getIncomingBlock(ValNo);
Rafael Espindola2453dff2012-03-15 15:52:59 +00004444 if (Replacement->getType() != UseTy)
4445 Replacement = new BitCastInst(Replacement, UseTy, "",
4446 &BB->back());
Dan Gohmand6bf2012012-04-13 18:57:48 +00004447 // While we're here, rewrite all edges for this PHI, rather
4448 // than just one use at a time, to minimize the number of
4449 // bitcasts we emit.
Dan Gohman447989c2012-04-27 18:56:31 +00004450 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
Rafael Espindola2453dff2012-03-15 15:52:59 +00004451 if (PHI->getIncomingBlock(i) == BB) {
4452 // Keep the UI iterator valid.
4453 if (&PHI->getOperandUse(
4454 PHINode::getOperandNumForIncomingValue(i)) ==
4455 &UI.getUse())
4456 ++UI;
4457 PHI->setIncomingValue(i, Replacement);
4458 }
4459 } else {
4460 if (Replacement->getType() != UseTy)
Dan Gohman6c189ec2012-04-13 01:08:28 +00004461 Replacement = new BitCastInst(Replacement, UseTy, "",
4462 cast<Instruction>(U.getUser()));
Rafael Espindola2453dff2012-03-15 15:52:59 +00004463 U.set(Replacement);
John McCall9fbd3182011-06-15 23:37:01 +00004464 }
Rafael Espindola2453dff2012-03-15 15:52:59 +00004465 }
John McCall9fbd3182011-06-15 23:37:01 +00004466 }
4467
Dan Gohman447989c2012-04-27 18:56:31 +00004468 // If Arg is a no-op casted pointer, strip one level of casts and iterate.
John McCall9fbd3182011-06-15 23:37:01 +00004469 if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
4470 Arg = BI->getOperand(0);
4471 else if (isa<GEPOperator>(Arg) &&
4472 cast<GEPOperator>(Arg)->hasAllZeroIndices())
4473 Arg = cast<GEPOperator>(Arg)->getPointerOperand();
4474 else if (isa<GlobalAlias>(Arg) &&
4475 !cast<GlobalAlias>(Arg)->mayBeOverridden())
4476 Arg = cast<GlobalAlias>(Arg)->getAliasee();
4477 else
4478 break;
4479 }
4480 }
4481
Dan Gohman0cdece42012-01-19 19:14:36 +00004482 // If this function has no escaping allocas or suspicious vararg usage,
4483 // objc_storeStrong calls can be marked with the "tail" keyword.
4484 if (TailOkForStoreStrongs)
Dan Gohman0daef3d2012-05-08 23:39:44 +00004485 for (SmallPtrSet<CallInst *, 8>::iterator I = StoreStrongCalls.begin(),
Dan Gohman0cdece42012-01-19 19:14:36 +00004486 E = StoreStrongCalls.end(); I != E; ++I)
4487 (*I)->setTailCall();
4488 StoreStrongCalls.clear();
4489
John McCall9fbd3182011-06-15 23:37:01 +00004490 return Changed;
4491}
Michael Gottesman81c61212013-01-14 00:35:14 +00004492
4493/// @}
4494///