blob: 055f30c11564c3b121801935659b229acfa2a76c [file] [log] [blame]
John McCalld935e9c2011-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 Gottesman97e3df02013-01-14 00:35:14 +00009/// \file
10/// This file defines ObjC ARC optimizations. ARC stands for Automatic
11/// Reference Counting and is a system for managing reference counts for objects
12/// in Objective C.
13///
14/// The optimizations performed include elimination of redundant, partially
15/// redundant, and inconsequential reference count operations, elimination of
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 McCalld935e9c2011-06-15 23:37:01 +000029//===----------------------------------------------------------------------===//
30
31#define DEBUG_TYPE "objc-arc"
John McCalld935e9c2011-06-15 23:37:01 +000032#include "llvm/ADT/DenseMap.h"
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +000033#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000034#include "llvm/Support/CommandLine.h"
Chandler Carruthbe810232013-01-02 10:22:59 +000035#include "llvm/Support/Debug.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000036#include "llvm/Support/raw_ostream.h"
John McCalld935e9c2011-06-15 23:37:01 +000037using namespace llvm;
38
Michael Gottesman97e3df02013-01-14 00:35:14 +000039/// \brief A handy option to enable/disable all optimizations in this file.
John McCalld935e9c2011-06-15 23:37:01 +000040static cl::opt<bool> EnableARCOpts("enable-objc-arc-opts", cl::init(true));
41
Michael Gottesman97e3df02013-01-14 00:35:14 +000042/// \defgroup MiscUtils Miscellaneous utilities that are not ARC specific.
43/// @{
John McCalld935e9c2011-06-15 23:37:01 +000044
45namespace {
Michael Gottesman97e3df02013-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 McCalld935e9c2011-06-15 23:37:01 +000048 template<class KeyT, class ValueT>
49 class MapVector {
Michael Gottesman97e3df02013-01-14 00:35:14 +000050 /// Map keys to indices in Vector.
John McCalld935e9c2011-06-15 23:37:01 +000051 typedef DenseMap<KeyT, size_t> MapTy;
52 MapTy Map;
53
John McCalld935e9c2011-06-15 23:37:01 +000054 typedef std::vector<std::pair<KeyT, ValueT> > VectorTy;
Michael Gottesman97e3df02013-01-14 00:35:14 +000055 /// Keys and values.
John McCalld935e9c2011-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 Gohman55b06742012-03-02 01:13:53 +000082 ValueT &operator[](const KeyT &Arg) {
John McCalld935e9c2011-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 Gohman55b06742012-03-02 01:13:53 +000086 size_t Num = Vector.size();
87 Pair.first->second = Num;
John McCalld935e9c2011-06-15 23:37:01 +000088 Vector.push_back(std::make_pair(Arg, ValueT()));
Dan Gohman55b06742012-03-02 01:13:53 +000089 return Vector[Num].second;
John McCalld935e9c2011-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 Gohman55b06742012-03-02 01:13:53 +000099 size_t Num = Vector.size();
100 Pair.first->second = Num;
John McCalld935e9c2011-06-15 23:37:01 +0000101 Vector.push_back(InsertPair);
Dan Gohman55b06742012-03-02 01:13:53 +0000102 return std::make_pair(Vector.begin() + Num, true);
John McCalld935e9c2011-06-15 23:37:01 +0000103 }
104 return std::make_pair(Vector.begin() + Pair.first->second, false);
105 }
106
Dan Gohman55b06742012-03-02 01:13:53 +0000107 const_iterator find(const KeyT &Key) const {
John McCalld935e9c2011-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 Gottesman97e3df02013-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 Gohman55b06742012-03-02 01:13:53 +0000116 void blot(const KeyT &Key) {
John McCalld935e9c2011-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 Gottesman97e3df02013-01-14 00:35:14 +0000130/// @}
131///
132/// \defgroup ARCUtilities Utility declarations/definitions specific to ARC.
133/// @{
John McCalld935e9c2011-06-15 23:37:01 +0000134
Chandler Carruthed0881b2012-12-03 16:50:05 +0000135#include "llvm/ADT/StringSwitch.h"
136#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +0000137#include "llvm/IR/Intrinsics.h"
138#include "llvm/IR/Module.h"
Dan Gohman41375a32012-05-08 23:39:44 +0000139#include "llvm/Support/CallSite.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +0000140#include "llvm/Transforms/Utils/Local.h"
Dan Gohman41375a32012-05-08 23:39:44 +0000141
John McCalld935e9c2011-06-15 23:37:01 +0000142namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000143 /// \enum InstructionClass
144 /// \brief A simple classification for instructions.
John McCalld935e9c2011-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 Gohmane1e352a2012-04-13 18:28:58 +0000164 IC_StoreStrong, ///< objc_storeStrong (derived)
John McCalld935e9c2011-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 };
Michael Gottesman782e3442013-01-17 18:32:34 +0000170
171 raw_ostream &operator<<(raw_ostream &OS, const InstructionClass Class)
172 LLVM_ATTRIBUTE_USED;
Michael Gottesman1d777512013-01-17 18:36:17 +0000173 raw_ostream &operator<<(raw_ostream &OS, const InstructionClass Class) {
Michael Gottesman782e3442013-01-17 18:32:34 +0000174 switch (Class) {
175 case IC_Retain:
176 return OS << "IC_Retain";
177 case IC_RetainRV:
178 return OS << "IC_RetainRV";
179 case IC_RetainBlock:
180 return OS << "IC_RetainBlock";
181 case IC_Release:
182 return OS << "IC_Release";
183 case IC_Autorelease:
184 return OS << "IC_Autorelease";
185 case IC_AutoreleaseRV:
186 return OS << "IC_AutoreleaseRV";
187 case IC_AutoreleasepoolPush:
188 return OS << "IC_AutoreleasepoolPush";
189 case IC_AutoreleasepoolPop:
190 return OS << "IC_AutoreleasepoolPop";
191 case IC_NoopCast:
192 return OS << "IC_NoopCast";
193 case IC_FusedRetainAutorelease:
194 return OS << "IC_FusedRetainAutorelease";
195 case IC_FusedRetainAutoreleaseRV:
196 return OS << "IC_FusedRetainAutoreleaseRV";
197 case IC_LoadWeakRetained:
198 return OS << "IC_LoadWeakRetained";
199 case IC_StoreWeak:
200 return OS << "IC_StoreWeak";
201 case IC_InitWeak:
202 return OS << "IC_InitWeak";
203 case IC_LoadWeak:
204 return OS << "IC_LoadWeak";
205 case IC_MoveWeak:
206 return OS << "IC_MoveWeak";
207 case IC_CopyWeak:
208 return OS << "IC_CopyWeak";
209 case IC_DestroyWeak:
210 return OS << "IC_DestroyWeak";
211 case IC_StoreStrong:
212 return OS << "IC_StoreStrong";
213 case IC_CallOrUser:
214 return OS << "IC_CallOrUser";
215 case IC_Call:
216 return OS << "IC_Call";
217 case IC_User:
218 return OS << "IC_User";
219 case IC_None:
220 return OS << "IC_None";
221 }
Benjamin Kramer0eba5772013-01-18 19:45:22 +0000222 llvm_unreachable("Unknown instruction class!");
Michael Gottesman782e3442013-01-17 18:32:34 +0000223 }
John McCalld935e9c2011-06-15 23:37:01 +0000224}
225
Michael Gottesman97e3df02013-01-14 00:35:14 +0000226/// \brief Test whether the given value is possible a reference-counted pointer.
John McCalld935e9c2011-06-15 23:37:01 +0000227static bool IsPotentialUse(const Value *Op) {
228 // Pointers to static or stack storage are not reference-counted pointers.
229 if (isa<Constant>(Op) || isa<AllocaInst>(Op))
230 return false;
231 // Special arguments are not reference-counted.
232 if (const Argument *Arg = dyn_cast<Argument>(Op))
233 if (Arg->hasByValAttr() ||
234 Arg->hasNestAttr() ||
235 Arg->hasStructRetAttr())
236 return false;
Dan Gohmanbd944b42011-12-14 19:10:53 +0000237 // Only consider values with pointer types.
238 // It seemes intuitive to exclude function pointer types as well, since
239 // functions are never reference-counted, however clang occasionally
240 // bitcasts reference-counted pointers to function-pointer type
241 // temporarily.
Chris Lattner229907c2011-07-18 04:54:35 +0000242 PointerType *Ty = dyn_cast<PointerType>(Op->getType());
Dan Gohmanbd944b42011-12-14 19:10:53 +0000243 if (!Ty)
John McCalld935e9c2011-06-15 23:37:01 +0000244 return false;
245 // Conservatively assume anything else is a potential use.
246 return true;
247}
248
Michael Gottesman4385edf2013-01-14 01:47:53 +0000249/// \brief Helper for GetInstructionClass. Determines what kind of construct CS
250/// is.
John McCalld935e9c2011-06-15 23:37:01 +0000251static InstructionClass GetCallSiteClass(ImmutableCallSite CS) {
252 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
253 I != E; ++I)
254 if (IsPotentialUse(*I))
255 return CS.onlyReadsMemory() ? IC_User : IC_CallOrUser;
256
257 return CS.onlyReadsMemory() ? IC_None : IC_Call;
258}
259
Michael Gottesman97e3df02013-01-14 00:35:14 +0000260/// \brief Determine if F is one of the special known Functions. If it isn't,
261/// return IC_CallOrUser.
John McCalld935e9c2011-06-15 23:37:01 +0000262static InstructionClass GetFunctionClass(const Function *F) {
263 Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
264
265 // No arguments.
266 if (AI == AE)
267 return StringSwitch<InstructionClass>(F->getName())
268 .Case("objc_autoreleasePoolPush", IC_AutoreleasepoolPush)
269 .Default(IC_CallOrUser);
270
271 // One argument.
272 const Argument *A0 = AI++;
273 if (AI == AE)
274 // Argument is a pointer.
Chris Lattner229907c2011-07-18 04:54:35 +0000275 if (PointerType *PTy = dyn_cast<PointerType>(A0->getType())) {
276 Type *ETy = PTy->getElementType();
John McCalld935e9c2011-06-15 23:37:01 +0000277 // Argument is i8*.
278 if (ETy->isIntegerTy(8))
279 return StringSwitch<InstructionClass>(F->getName())
280 .Case("objc_retain", IC_Retain)
281 .Case("objc_retainAutoreleasedReturnValue", IC_RetainRV)
282 .Case("objc_retainBlock", IC_RetainBlock)
283 .Case("objc_release", IC_Release)
284 .Case("objc_autorelease", IC_Autorelease)
285 .Case("objc_autoreleaseReturnValue", IC_AutoreleaseRV)
286 .Case("objc_autoreleasePoolPop", IC_AutoreleasepoolPop)
287 .Case("objc_retainedObject", IC_NoopCast)
288 .Case("objc_unretainedObject", IC_NoopCast)
289 .Case("objc_unretainedPointer", IC_NoopCast)
290 .Case("objc_retain_autorelease", IC_FusedRetainAutorelease)
291 .Case("objc_retainAutorelease", IC_FusedRetainAutorelease)
292 .Case("objc_retainAutoreleaseReturnValue",IC_FusedRetainAutoreleaseRV)
293 .Default(IC_CallOrUser);
294
295 // Argument is i8**
Chris Lattner229907c2011-07-18 04:54:35 +0000296 if (PointerType *Pte = dyn_cast<PointerType>(ETy))
John McCalld935e9c2011-06-15 23:37:01 +0000297 if (Pte->getElementType()->isIntegerTy(8))
298 return StringSwitch<InstructionClass>(F->getName())
299 .Case("objc_loadWeakRetained", IC_LoadWeakRetained)
300 .Case("objc_loadWeak", IC_LoadWeak)
301 .Case("objc_destroyWeak", IC_DestroyWeak)
302 .Default(IC_CallOrUser);
303 }
304
305 // Two arguments, first is i8**.
306 const Argument *A1 = AI++;
307 if (AI == AE)
Chris Lattner229907c2011-07-18 04:54:35 +0000308 if (PointerType *PTy = dyn_cast<PointerType>(A0->getType()))
309 if (PointerType *Pte = dyn_cast<PointerType>(PTy->getElementType()))
John McCalld935e9c2011-06-15 23:37:01 +0000310 if (Pte->getElementType()->isIntegerTy(8))
Chris Lattner229907c2011-07-18 04:54:35 +0000311 if (PointerType *PTy1 = dyn_cast<PointerType>(A1->getType())) {
312 Type *ETy1 = PTy1->getElementType();
John McCalld935e9c2011-06-15 23:37:01 +0000313 // Second argument is i8*
314 if (ETy1->isIntegerTy(8))
315 return StringSwitch<InstructionClass>(F->getName())
316 .Case("objc_storeWeak", IC_StoreWeak)
317 .Case("objc_initWeak", IC_InitWeak)
Dan Gohmane1e352a2012-04-13 18:28:58 +0000318 .Case("objc_storeStrong", IC_StoreStrong)
John McCalld935e9c2011-06-15 23:37:01 +0000319 .Default(IC_CallOrUser);
320 // Second argument is i8**.
Chris Lattner229907c2011-07-18 04:54:35 +0000321 if (PointerType *Pte1 = dyn_cast<PointerType>(ETy1))
John McCalld935e9c2011-06-15 23:37:01 +0000322 if (Pte1->getElementType()->isIntegerTy(8))
323 return StringSwitch<InstructionClass>(F->getName())
324 .Case("objc_moveWeak", IC_MoveWeak)
325 .Case("objc_copyWeak", IC_CopyWeak)
326 .Default(IC_CallOrUser);
327 }
328
329 // Anything else.
330 return IC_CallOrUser;
331}
332
Michael Gottesman97e3df02013-01-14 00:35:14 +0000333/// \brief Determine what kind of construct V is.
John McCalld935e9c2011-06-15 23:37:01 +0000334static InstructionClass GetInstructionClass(const Value *V) {
335 if (const Instruction *I = dyn_cast<Instruction>(V)) {
336 // Any instruction other than bitcast and gep with a pointer operand have a
337 // use of an objc pointer. Bitcasts, GEPs, Selects, PHIs transfer a pointer
338 // to a subsequent use, rather than using it themselves, in this sense.
339 // As a short cut, several other opcodes are known to have no pointer
340 // operands of interest. And ret is never followed by a release, so it's
341 // not interesting to examine.
342 switch (I->getOpcode()) {
343 case Instruction::Call: {
344 const CallInst *CI = cast<CallInst>(I);
345 // Check for calls to special functions.
346 if (const Function *F = CI->getCalledFunction()) {
347 InstructionClass Class = GetFunctionClass(F);
348 if (Class != IC_CallOrUser)
349 return Class;
350
351 // None of the intrinsic functions do objc_release. For intrinsics, the
352 // only question is whether or not they may be users.
353 switch (F->getIntrinsicID()) {
John McCalld935e9c2011-06-15 23:37:01 +0000354 case Intrinsic::returnaddress: case Intrinsic::frameaddress:
355 case Intrinsic::stacksave: case Intrinsic::stackrestore:
356 case Intrinsic::vastart: case Intrinsic::vacopy: case Intrinsic::vaend:
Dan Gohman41375a32012-05-08 23:39:44 +0000357 case Intrinsic::objectsize: case Intrinsic::prefetch:
358 case Intrinsic::stackprotector:
359 case Intrinsic::eh_return_i32: case Intrinsic::eh_return_i64:
360 case Intrinsic::eh_typeid_for: case Intrinsic::eh_dwarf_cfa:
361 case Intrinsic::eh_sjlj_lsda: case Intrinsic::eh_sjlj_functioncontext:
362 case Intrinsic::init_trampoline: case Intrinsic::adjust_trampoline:
363 case Intrinsic::lifetime_start: case Intrinsic::lifetime_end:
364 case Intrinsic::invariant_start: case Intrinsic::invariant_end:
John McCalld935e9c2011-06-15 23:37:01 +0000365 // Don't let dbg info affect our results.
366 case Intrinsic::dbg_declare: case Intrinsic::dbg_value:
367 // Short cut: Some intrinsics obviously don't use ObjC pointers.
368 return IC_None;
369 default:
Dan Gohman41375a32012-05-08 23:39:44 +0000370 break;
John McCalld935e9c2011-06-15 23:37:01 +0000371 }
372 }
373 return GetCallSiteClass(CI);
374 }
375 case Instruction::Invoke:
376 return GetCallSiteClass(cast<InvokeInst>(I));
377 case Instruction::BitCast:
378 case Instruction::GetElementPtr:
379 case Instruction::Select: case Instruction::PHI:
380 case Instruction::Ret: case Instruction::Br:
381 case Instruction::Switch: case Instruction::IndirectBr:
382 case Instruction::Alloca: case Instruction::VAArg:
383 case Instruction::Add: case Instruction::FAdd:
384 case Instruction::Sub: case Instruction::FSub:
385 case Instruction::Mul: case Instruction::FMul:
386 case Instruction::SDiv: case Instruction::UDiv: case Instruction::FDiv:
387 case Instruction::SRem: case Instruction::URem: case Instruction::FRem:
388 case Instruction::Shl: case Instruction::LShr: case Instruction::AShr:
389 case Instruction::And: case Instruction::Or: case Instruction::Xor:
390 case Instruction::SExt: case Instruction::ZExt: case Instruction::Trunc:
391 case Instruction::IntToPtr: case Instruction::FCmp:
392 case Instruction::FPTrunc: case Instruction::FPExt:
393 case Instruction::FPToUI: case Instruction::FPToSI:
394 case Instruction::UIToFP: case Instruction::SIToFP:
395 case Instruction::InsertElement: case Instruction::ExtractElement:
396 case Instruction::ShuffleVector:
397 case Instruction::ExtractValue:
398 break;
399 case Instruction::ICmp:
400 // Comparing a pointer with null, or any other constant, isn't an
401 // interesting use, because we don't care what the pointer points to, or
402 // about the values of any other dynamic reference-counted pointers.
403 if (IsPotentialUse(I->getOperand(1)))
404 return IC_User;
405 break;
406 default:
407 // For anything else, check all the operands.
Dan Gohman4b8e8ce2011-08-22 17:29:37 +0000408 // Note that this includes both operands of a Store: while the first
409 // operand isn't actually being dereferenced, it is being stored to
410 // memory where we can no longer track who might read it and dereference
411 // it, so we have to consider it potentially used.
John McCalld935e9c2011-06-15 23:37:01 +0000412 for (User::const_op_iterator OI = I->op_begin(), OE = I->op_end();
413 OI != OE; ++OI)
414 if (IsPotentialUse(*OI))
415 return IC_User;
416 }
417 }
418
419 // Otherwise, it's totally inert for ARC purposes.
420 return IC_None;
421}
422
Michael Gottesman97e3df02013-01-14 00:35:14 +0000423/// \brief Determine which objc runtime call instruction class V belongs to.
424///
425/// This is similar to GetInstructionClass except that it only detects objc
426/// runtime calls. This allows it to be faster.
427///
John McCalld935e9c2011-06-15 23:37:01 +0000428static InstructionClass GetBasicInstructionClass(const Value *V) {
429 if (const CallInst *CI = dyn_cast<CallInst>(V)) {
430 if (const Function *F = CI->getCalledFunction())
431 return GetFunctionClass(F);
432 // Otherwise, be conservative.
433 return IC_CallOrUser;
434 }
435
436 // Otherwise, be conservative.
Dan Gohmane7a243f2012-01-17 20:52:24 +0000437 return isa<InvokeInst>(V) ? IC_CallOrUser : IC_User;
John McCalld935e9c2011-06-15 23:37:01 +0000438}
439
Michael Gottesman97e3df02013-01-14 00:35:14 +0000440/// \brief Test if the given class is objc_retain or equivalent.
John McCalld935e9c2011-06-15 23:37:01 +0000441static bool IsRetain(InstructionClass Class) {
442 return Class == IC_Retain ||
443 Class == IC_RetainRV;
444}
445
Michael Gottesman97e3df02013-01-14 00:35:14 +0000446/// \brief Test if the given class is objc_autorelease or equivalent.
John McCalld935e9c2011-06-15 23:37:01 +0000447static bool IsAutorelease(InstructionClass Class) {
448 return Class == IC_Autorelease ||
449 Class == IC_AutoreleaseRV;
450}
451
Michael Gottesman97e3df02013-01-14 00:35:14 +0000452/// \brief Test if the given class represents instructions which return their
453/// argument verbatim.
John McCalld935e9c2011-06-15 23:37:01 +0000454static bool IsForwarding(InstructionClass Class) {
455 // objc_retainBlock technically doesn't always return its argument
456 // verbatim, but it doesn't matter for our purposes here.
457 return Class == IC_Retain ||
458 Class == IC_RetainRV ||
459 Class == IC_Autorelease ||
460 Class == IC_AutoreleaseRV ||
461 Class == IC_RetainBlock ||
462 Class == IC_NoopCast;
463}
464
Michael Gottesman97e3df02013-01-14 00:35:14 +0000465/// \brief Test if the given class represents instructions which do nothing if
466/// passed a null pointer.
John McCalld935e9c2011-06-15 23:37:01 +0000467static bool IsNoopOnNull(InstructionClass Class) {
468 return Class == IC_Retain ||
469 Class == IC_RetainRV ||
470 Class == IC_Release ||
471 Class == IC_Autorelease ||
472 Class == IC_AutoreleaseRV ||
473 Class == IC_RetainBlock;
474}
475
Michael Gottesman4385edf2013-01-14 01:47:53 +0000476/// \brief Test if the given class represents instructions which are always safe
477/// to mark with the "tail" keyword.
John McCalld935e9c2011-06-15 23:37:01 +0000478static bool IsAlwaysTail(InstructionClass Class) {
479 // IC_RetainBlock may be given a stack argument.
480 return Class == IC_Retain ||
481 Class == IC_RetainRV ||
John McCalld935e9c2011-06-15 23:37:01 +0000482 Class == IC_AutoreleaseRV;
483}
484
Michael Gottesmanc9656fa2013-01-12 01:25:15 +0000485/// \brief Test if the given class represents instructions which are never safe
486/// to mark with the "tail" keyword.
487static bool IsNeverTail(InstructionClass Class) {
488 /// It is never safe to tail call objc_autorelease since by tail calling
489 /// objc_autorelease, we also tail call -[NSObject autorelease] which supports
490 /// fast autoreleasing causing our object to be potentially reclaimed from the
491 /// autorelease pool which violates the semantics of __autoreleasing types in
492 /// ARC.
493 return Class == IC_Autorelease;
494}
495
Michael Gottesman97e3df02013-01-14 00:35:14 +0000496/// \brief Test if the given class represents instructions which are always safe
497/// to mark with the nounwind attribute.
John McCalld935e9c2011-06-15 23:37:01 +0000498static bool IsNoThrow(InstructionClass Class) {
Dan Gohmanfca43c22011-09-14 18:33:34 +0000499 // objc_retainBlock is not nounwind because it calls user copy constructors
500 // which could theoretically throw.
John McCalld935e9c2011-06-15 23:37:01 +0000501 return Class == IC_Retain ||
502 Class == IC_RetainRV ||
John McCalld935e9c2011-06-15 23:37:01 +0000503 Class == IC_Release ||
504 Class == IC_Autorelease ||
505 Class == IC_AutoreleaseRV ||
506 Class == IC_AutoreleasepoolPush ||
507 Class == IC_AutoreleasepoolPop;
508}
509
Michael Gottesman97e3df02013-01-14 00:35:14 +0000510/// \brief Erase the given instruction.
511///
512/// Many ObjC calls return their argument verbatim,
513/// so if it's such a call and the return value has users, replace them with the
514/// argument value.
515///
John McCalld935e9c2011-06-15 23:37:01 +0000516static void EraseInstruction(Instruction *CI) {
517 Value *OldArg = cast<CallInst>(CI)->getArgOperand(0);
518
519 bool Unused = CI->use_empty();
520
521 if (!Unused) {
522 // Replace the return value with the argument.
523 assert(IsForwarding(GetBasicInstructionClass(CI)) &&
524 "Can't delete non-forwarding instruction with users!");
525 CI->replaceAllUsesWith(OldArg);
526 }
527
528 CI->eraseFromParent();
529
530 if (Unused)
531 RecursivelyDeleteTriviallyDeadInstructions(OldArg);
532}
533
Michael Gottesman97e3df02013-01-14 00:35:14 +0000534/// \brief This is a wrapper around getUnderlyingObject which also knows how to
535/// look through objc_retain and objc_autorelease calls, which we know to return
536/// their argument verbatim.
John McCalld935e9c2011-06-15 23:37:01 +0000537static const Value *GetUnderlyingObjCPtr(const Value *V) {
538 for (;;) {
539 V = GetUnderlyingObject(V);
540 if (!IsForwarding(GetBasicInstructionClass(V)))
541 break;
542 V = cast<CallInst>(V)->getArgOperand(0);
543 }
544
545 return V;
546}
547
Michael Gottesman97e3df02013-01-14 00:35:14 +0000548/// \brief This is a wrapper around Value::stripPointerCasts which also knows
549/// how to look through objc_retain and objc_autorelease calls, which we know to
550/// return their argument verbatim.
John McCalld935e9c2011-06-15 23:37:01 +0000551static const Value *StripPointerCastsAndObjCCalls(const Value *V) {
552 for (;;) {
553 V = V->stripPointerCasts();
554 if (!IsForwarding(GetBasicInstructionClass(V)))
555 break;
556 V = cast<CallInst>(V)->getArgOperand(0);
557 }
558 return V;
559}
560
Michael Gottesman97e3df02013-01-14 00:35:14 +0000561/// \brief This is a wrapper around Value::stripPointerCasts which also knows
562/// how to look through objc_retain and objc_autorelease calls, which we know to
563/// return their argument verbatim.
John McCalld935e9c2011-06-15 23:37:01 +0000564static Value *StripPointerCastsAndObjCCalls(Value *V) {
565 for (;;) {
566 V = V->stripPointerCasts();
567 if (!IsForwarding(GetBasicInstructionClass(V)))
568 break;
569 V = cast<CallInst>(V)->getArgOperand(0);
570 }
571 return V;
572}
573
Michael Gottesman97e3df02013-01-14 00:35:14 +0000574/// \brief Assuming the given instruction is one of the special calls such as
575/// objc_retain or objc_release, return the argument value, stripped of no-op
John McCalld935e9c2011-06-15 23:37:01 +0000576/// casts and forwarding calls.
577static Value *GetObjCArg(Value *Inst) {
578 return StripPointerCastsAndObjCCalls(cast<CallInst>(Inst)->getArgOperand(0));
579}
580
Michael Gottesman9854e0c2013-01-18 23:00:33 +0000581/// \brief This is similar to AliasAnalysis's isIdentifiedObject, except that it
582/// uses special knowledge of ObjC conventions.
John McCalld935e9c2011-06-15 23:37:01 +0000583static bool IsObjCIdentifiedObject(const Value *V) {
584 // Assume that call results and arguments have their own "provenance".
585 // Constants (including GlobalVariables) and Allocas are never
586 // reference-counted.
587 if (isa<CallInst>(V) || isa<InvokeInst>(V) ||
588 isa<Argument>(V) || isa<Constant>(V) ||
589 isa<AllocaInst>(V))
590 return true;
591
592 if (const LoadInst *LI = dyn_cast<LoadInst>(V)) {
593 const Value *Pointer =
594 StripPointerCastsAndObjCCalls(LI->getPointerOperand());
595 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Pointer)) {
Dan Gohman56e1cef2011-08-22 17:29:11 +0000596 // A constant pointer can't be pointing to an object on the heap. It may
597 // be reference-counted, but it won't be deleted.
598 if (GV->isConstant())
599 return true;
John McCalld935e9c2011-06-15 23:37:01 +0000600 StringRef Name = GV->getName();
601 // These special variables are known to hold values which are not
602 // reference-counted pointers.
603 if (Name.startswith("\01L_OBJC_SELECTOR_REFERENCES_") ||
604 Name.startswith("\01L_OBJC_CLASSLIST_REFERENCES_") ||
605 Name.startswith("\01L_OBJC_CLASSLIST_SUP_REFS_$_") ||
606 Name.startswith("\01L_OBJC_METH_VAR_NAME_") ||
607 Name.startswith("\01l_objc_msgSend_fixup_"))
608 return true;
609 }
610 }
611
612 return false;
613}
614
Michael Gottesman97e3df02013-01-14 00:35:14 +0000615/// \brief This is similar to StripPointerCastsAndObjCCalls but it stops as soon
616/// as it finds a value with multiple uses.
John McCalld935e9c2011-06-15 23:37:01 +0000617static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
618 if (Arg->hasOneUse()) {
619 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
620 return FindSingleUseIdentifiedObject(BC->getOperand(0));
621 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
622 if (GEP->hasAllZeroIndices())
623 return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
624 if (IsForwarding(GetBasicInstructionClass(Arg)))
625 return FindSingleUseIdentifiedObject(
626 cast<CallInst>(Arg)->getArgOperand(0));
627 if (!IsObjCIdentifiedObject(Arg))
628 return 0;
629 return Arg;
630 }
631
Dan Gohman41375a32012-05-08 23:39:44 +0000632 // If we found an identifiable object but it has multiple uses, but they are
633 // trivial uses, we can still consider this to be a single-use value.
John McCalld935e9c2011-06-15 23:37:01 +0000634 if (IsObjCIdentifiedObject(Arg)) {
635 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
636 UI != UE; ++UI) {
637 const User *U = *UI;
638 if (!U->use_empty() || StripPointerCastsAndObjCCalls(U) != Arg)
639 return 0;
640 }
641
642 return Arg;
643 }
644
645 return 0;
646}
647
Michael Gottesman97e3df02013-01-14 00:35:14 +0000648/// \brief Test if the given module looks interesting to run ARC optimization
649/// on.
Dan Gohmanceaac7c2011-06-20 23:20:43 +0000650static bool ModuleHasARC(const Module &M) {
651 return
652 M.getNamedValue("objc_retain") ||
653 M.getNamedValue("objc_release") ||
654 M.getNamedValue("objc_autorelease") ||
655 M.getNamedValue("objc_retainAutoreleasedReturnValue") ||
656 M.getNamedValue("objc_retainBlock") ||
657 M.getNamedValue("objc_autoreleaseReturnValue") ||
658 M.getNamedValue("objc_autoreleasePoolPush") ||
659 M.getNamedValue("objc_loadWeakRetained") ||
660 M.getNamedValue("objc_loadWeak") ||
661 M.getNamedValue("objc_destroyWeak") ||
662 M.getNamedValue("objc_storeWeak") ||
663 M.getNamedValue("objc_initWeak") ||
664 M.getNamedValue("objc_moveWeak") ||
665 M.getNamedValue("objc_copyWeak") ||
666 M.getNamedValue("objc_retainedObject") ||
667 M.getNamedValue("objc_unretainedObject") ||
668 M.getNamedValue("objc_unretainedPointer");
669}
670
Michael Gottesman4385edf2013-01-14 01:47:53 +0000671/// \brief Test whether the given pointer, which is an Objective C block
672/// pointer, does not "escape".
Michael Gottesman97e3df02013-01-14 00:35:14 +0000673///
674/// This differs from regular escape analysis in that a use as an
675/// argument to a call is not considered an escape.
676///
Dan Gohman728db492012-01-13 00:39:07 +0000677static bool DoesObjCBlockEscape(const Value *BlockPtr) {
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000678
679 DEBUG(dbgs() << "DoesObjCBlockEscape: Target: " << *BlockPtr << "\n");
680
Dan Gohman728db492012-01-13 00:39:07 +0000681 // Walk the def-use chains.
682 SmallVector<const Value *, 4> Worklist;
683 Worklist.push_back(BlockPtr);
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000684
685 // Ensure we do not visit any value twice.
686 SmallPtrSet<const Value *, 4> VisitedSet;
687
Dan Gohman728db492012-01-13 00:39:07 +0000688 do {
689 const Value *V = Worklist.pop_back_val();
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000690
691 DEBUG(dbgs() << "DoesObjCBlockEscape: Visiting: " << *V << "\n");
692
Dan Gohman728db492012-01-13 00:39:07 +0000693 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
694 UI != UE; ++UI) {
695 const User *UUser = *UI;
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000696
697 DEBUG(dbgs() << "DoesObjCBlockEscape: User: " << *UUser << "\n");
698
Dan Gohman728db492012-01-13 00:39:07 +0000699 // Special - Use by a call (callee or argument) is not considered
700 // to be an escape.
Dan Gohmane1e352a2012-04-13 18:28:58 +0000701 switch (GetBasicInstructionClass(UUser)) {
702 case IC_StoreWeak:
703 case IC_InitWeak:
704 case IC_StoreStrong:
705 case IC_Autorelease:
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000706 case IC_AutoreleaseRV: {
707 DEBUG(dbgs() << "DoesObjCBlockEscape: User copies pointer arguments. "
708 "Block Escapes!\n");
Dan Gohmane1e352a2012-04-13 18:28:58 +0000709 // These special functions make copies of their pointer arguments.
710 return true;
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000711 }
Dan Gohmane1e352a2012-04-13 18:28:58 +0000712 case IC_User:
713 case IC_None:
714 // Use by an instruction which copies the value is an escape if the
715 // result is an escape.
716 if (isa<BitCastInst>(UUser) || isa<GetElementPtrInst>(UUser) ||
717 isa<PHINode>(UUser) || isa<SelectInst>(UUser)) {
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000718
Michael Gottesmane9145d32013-01-14 19:18:39 +0000719 if (!VisitedSet.insert(UUser)) {
Michael Gottesman4385edf2013-01-14 01:47:53 +0000720 DEBUG(dbgs() << "DoesObjCBlockEscape: User copies value. Escapes "
721 "if result escapes. Adding to list.\n");
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000722 Worklist.push_back(UUser);
723 } else {
724 DEBUG(dbgs() << "DoesObjCBlockEscape: Already visited node.\n");
725 }
Dan Gohmane1e352a2012-04-13 18:28:58 +0000726 continue;
727 }
728 // Use by a load is not an escape.
729 if (isa<LoadInst>(UUser))
730 continue;
731 // Use by a store is not an escape if the use is the address.
732 if (const StoreInst *SI = dyn_cast<StoreInst>(UUser))
733 if (V != SI->getValueOperand())
734 continue;
735 break;
736 default:
737 // Regular calls and other stuff are not considered escapes.
Dan Gohman728db492012-01-13 00:39:07 +0000738 continue;
739 }
Dan Gohmaneb6e0152012-02-13 22:57:02 +0000740 // Otherwise, conservatively assume an escape.
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000741 DEBUG(dbgs() << "DoesObjCBlockEscape: Assuming block escapes.\n");
Dan Gohman728db492012-01-13 00:39:07 +0000742 return true;
743 }
744 } while (!Worklist.empty());
745
746 // No escapes found.
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000747 DEBUG(dbgs() << "DoesObjCBlockEscape: Block does not escape.\n");
Dan Gohman728db492012-01-13 00:39:07 +0000748 return false;
749}
750
Michael Gottesman97e3df02013-01-14 00:35:14 +0000751/// @}
752///
Michael Gottesman4385edf2013-01-14 01:47:53 +0000753/// \defgroup ARCAA Extends alias analysis using ObjC specific knowledge.
Michael Gottesman97e3df02013-01-14 00:35:14 +0000754/// @{
John McCalld935e9c2011-06-15 23:37:01 +0000755
John McCalld935e9c2011-06-15 23:37:01 +0000756#include "llvm/Analysis/AliasAnalysis.h"
757#include "llvm/Analysis/Passes.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +0000758#include "llvm/Pass.h"
John McCalld935e9c2011-06-15 23:37:01 +0000759
760namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000761 /// \brief This is a simple alias analysis implementation that uses knowledge
762 /// of ARC constructs to answer queries.
John McCalld935e9c2011-06-15 23:37:01 +0000763 ///
764 /// TODO: This class could be generalized to know about other ObjC-specific
765 /// tricks. Such as knowing that ivars in the non-fragile ABI are non-aliasing
766 /// even though their offsets are dynamic.
767 class ObjCARCAliasAnalysis : public ImmutablePass,
768 public AliasAnalysis {
769 public:
770 static char ID; // Class identification, replacement for typeinfo
771 ObjCARCAliasAnalysis() : ImmutablePass(ID) {
772 initializeObjCARCAliasAnalysisPass(*PassRegistry::getPassRegistry());
773 }
774
775 private:
776 virtual void initializePass() {
777 InitializeAliasAnalysis(this);
778 }
779
Michael Gottesman97e3df02013-01-14 00:35:14 +0000780 /// This method is used when a pass implements an analysis interface through
781 /// multiple inheritance. If needed, it should override this to adjust the
782 /// this pointer as needed for the specified pass info.
John McCalld935e9c2011-06-15 23:37:01 +0000783 virtual void *getAdjustedAnalysisPointer(const void *PI) {
784 if (PI == &AliasAnalysis::ID)
Dan Gohmandae33492012-04-27 18:56:31 +0000785 return static_cast<AliasAnalysis *>(this);
John McCalld935e9c2011-06-15 23:37:01 +0000786 return this;
787 }
788
789 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
790 virtual AliasResult alias(const Location &LocA, const Location &LocB);
791 virtual bool pointsToConstantMemory(const Location &Loc, bool OrLocal);
792 virtual ModRefBehavior getModRefBehavior(ImmutableCallSite CS);
793 virtual ModRefBehavior getModRefBehavior(const Function *F);
794 virtual ModRefResult getModRefInfo(ImmutableCallSite CS,
795 const Location &Loc);
796 virtual ModRefResult getModRefInfo(ImmutableCallSite CS1,
797 ImmutableCallSite CS2);
798 };
799} // End of anonymous namespace
800
801// Register this pass...
802char ObjCARCAliasAnalysis::ID = 0;
803INITIALIZE_AG_PASS(ObjCARCAliasAnalysis, AliasAnalysis, "objc-arc-aa",
804 "ObjC-ARC-Based Alias Analysis", false, true, false)
805
806ImmutablePass *llvm::createObjCARCAliasAnalysisPass() {
807 return new ObjCARCAliasAnalysis();
808}
809
810void
811ObjCARCAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
812 AU.setPreservesAll();
813 AliasAnalysis::getAnalysisUsage(AU);
814}
815
816AliasAnalysis::AliasResult
817ObjCARCAliasAnalysis::alias(const Location &LocA, const Location &LocB) {
818 if (!EnableARCOpts)
819 return AliasAnalysis::alias(LocA, LocB);
820
821 // First, strip off no-ops, including ObjC-specific no-ops, and try making a
822 // precise alias query.
823 const Value *SA = StripPointerCastsAndObjCCalls(LocA.Ptr);
824 const Value *SB = StripPointerCastsAndObjCCalls(LocB.Ptr);
825 AliasResult Result =
826 AliasAnalysis::alias(Location(SA, LocA.Size, LocA.TBAATag),
827 Location(SB, LocB.Size, LocB.TBAATag));
828 if (Result != MayAlias)
829 return Result;
830
831 // If that failed, climb to the underlying object, including climbing through
832 // ObjC-specific no-ops, and try making an imprecise alias query.
833 const Value *UA = GetUnderlyingObjCPtr(SA);
834 const Value *UB = GetUnderlyingObjCPtr(SB);
835 if (UA != SA || UB != SB) {
836 Result = AliasAnalysis::alias(Location(UA), Location(UB));
837 // We can't use MustAlias or PartialAlias results here because
838 // GetUnderlyingObjCPtr may return an offsetted pointer value.
839 if (Result == NoAlias)
840 return NoAlias;
841 }
842
843 // If that failed, fail. We don't need to chain here, since that's covered
844 // by the earlier precise query.
845 return MayAlias;
846}
847
848bool
849ObjCARCAliasAnalysis::pointsToConstantMemory(const Location &Loc,
850 bool OrLocal) {
851 if (!EnableARCOpts)
852 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
853
854 // First, strip off no-ops, including ObjC-specific no-ops, and try making
855 // a precise alias query.
856 const Value *S = StripPointerCastsAndObjCCalls(Loc.Ptr);
857 if (AliasAnalysis::pointsToConstantMemory(Location(S, Loc.Size, Loc.TBAATag),
858 OrLocal))
859 return true;
860
861 // If that failed, climb to the underlying object, including climbing through
862 // ObjC-specific no-ops, and try making an imprecise alias query.
863 const Value *U = GetUnderlyingObjCPtr(S);
864 if (U != S)
865 return AliasAnalysis::pointsToConstantMemory(Location(U), OrLocal);
866
867 // If that failed, fail. We don't need to chain here, since that's covered
868 // by the earlier precise query.
869 return false;
870}
871
872AliasAnalysis::ModRefBehavior
873ObjCARCAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
874 // We have nothing to do. Just chain to the next AliasAnalysis.
875 return AliasAnalysis::getModRefBehavior(CS);
876}
877
878AliasAnalysis::ModRefBehavior
879ObjCARCAliasAnalysis::getModRefBehavior(const Function *F) {
880 if (!EnableARCOpts)
881 return AliasAnalysis::getModRefBehavior(F);
882
883 switch (GetFunctionClass(F)) {
884 case IC_NoopCast:
885 return DoesNotAccessMemory;
886 default:
887 break;
888 }
889
890 return AliasAnalysis::getModRefBehavior(F);
891}
892
893AliasAnalysis::ModRefResult
894ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS, const Location &Loc) {
895 if (!EnableARCOpts)
896 return AliasAnalysis::getModRefInfo(CS, Loc);
897
898 switch (GetBasicInstructionClass(CS.getInstruction())) {
899 case IC_Retain:
900 case IC_RetainRV:
John McCalld935e9c2011-06-15 23:37:01 +0000901 case IC_Autorelease:
902 case IC_AutoreleaseRV:
903 case IC_NoopCast:
904 case IC_AutoreleasepoolPush:
905 case IC_FusedRetainAutorelease:
906 case IC_FusedRetainAutoreleaseRV:
907 // These functions don't access any memory visible to the compiler.
Benjamin Kramerbde91762012-06-02 10:20:22 +0000908 // Note that this doesn't include objc_retainBlock, because it updates
Dan Gohmand4b5e3a2011-09-14 18:13:00 +0000909 // pointers when it copies block data.
John McCalld935e9c2011-06-15 23:37:01 +0000910 return NoModRef;
911 default:
912 break;
913 }
914
915 return AliasAnalysis::getModRefInfo(CS, Loc);
916}
917
918AliasAnalysis::ModRefResult
919ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
920 ImmutableCallSite CS2) {
921 // TODO: Theoretically we could check for dependencies between objc_* calls
922 // and OnlyAccessesArgumentPointees calls or other well-behaved calls.
923 return AliasAnalysis::getModRefInfo(CS1, CS2);
924}
925
Michael Gottesman97e3df02013-01-14 00:35:14 +0000926/// @}
927///
928/// \defgroup ARCExpansion Early ARC Optimizations.
929/// @{
John McCalld935e9c2011-06-15 23:37:01 +0000930
931#include "llvm/Support/InstIterator.h"
932#include "llvm/Transforms/Scalar.h"
933
934namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000935 /// \brief Early ARC transformations.
John McCalld935e9c2011-06-15 23:37:01 +0000936 class ObjCARCExpand : public FunctionPass {
937 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Dan Gohmanceaac7c2011-06-20 23:20:43 +0000938 virtual bool doInitialization(Module &M);
John McCalld935e9c2011-06-15 23:37:01 +0000939 virtual bool runOnFunction(Function &F);
940
Michael Gottesman97e3df02013-01-14 00:35:14 +0000941 /// A flag indicating whether this optimization pass should run.
Dan Gohmanceaac7c2011-06-20 23:20:43 +0000942 bool Run;
943
John McCalld935e9c2011-06-15 23:37:01 +0000944 public:
945 static char ID;
946 ObjCARCExpand() : FunctionPass(ID) {
947 initializeObjCARCExpandPass(*PassRegistry::getPassRegistry());
948 }
949 };
950}
951
952char ObjCARCExpand::ID = 0;
953INITIALIZE_PASS(ObjCARCExpand,
954 "objc-arc-expand", "ObjC ARC expansion", false, false)
955
956Pass *llvm::createObjCARCExpandPass() {
957 return new ObjCARCExpand();
958}
959
960void ObjCARCExpand::getAnalysisUsage(AnalysisUsage &AU) const {
961 AU.setPreservesCFG();
962}
963
Dan Gohmanceaac7c2011-06-20 23:20:43 +0000964bool ObjCARCExpand::doInitialization(Module &M) {
965 Run = ModuleHasARC(M);
966 return false;
967}
968
John McCalld935e9c2011-06-15 23:37:01 +0000969bool ObjCARCExpand::runOnFunction(Function &F) {
970 if (!EnableARCOpts)
971 return false;
972
Dan Gohmanceaac7c2011-06-20 23:20:43 +0000973 // If nothing in the Module uses ARC, don't do anything.
974 if (!Run)
975 return false;
976
John McCalld935e9c2011-06-15 23:37:01 +0000977 bool Changed = false;
978
Michael Gottesmanaf2113f2013-01-13 07:00:51 +0000979 DEBUG(dbgs() << "ObjCARCExpand: Visiting Function: " << F.getName() << "\n");
980
John McCalld935e9c2011-06-15 23:37:01 +0000981 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
982 Instruction *Inst = &*I;
Michael Gottesman10426b52013-01-07 21:26:07 +0000983
Michael Gottesman3f146e22013-01-01 16:05:48 +0000984 DEBUG(dbgs() << "ObjCARCExpand: Visiting: " << *Inst << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +0000985
John McCalld935e9c2011-06-15 23:37:01 +0000986 switch (GetBasicInstructionClass(Inst)) {
987 case IC_Retain:
988 case IC_RetainRV:
989 case IC_Autorelease:
990 case IC_AutoreleaseRV:
991 case IC_FusedRetainAutorelease:
Michael Gottesmanc8a11df2013-01-01 16:05:54 +0000992 case IC_FusedRetainAutoreleaseRV: {
John McCalld935e9c2011-06-15 23:37:01 +0000993 // These calls return their argument verbatim, as a low-level
994 // optimization. However, this makes high-level optimizations
995 // harder. Undo any uses of this optimization that the front-end
Dan Gohman670f9372012-04-13 18:57:48 +0000996 // emitted here. We'll redo them in the contract pass.
John McCalld935e9c2011-06-15 23:37:01 +0000997 Changed = true;
Michael Gottesmanc8a11df2013-01-01 16:05:54 +0000998 Value *Value = cast<CallInst>(Inst)->getArgOperand(0);
999 DEBUG(dbgs() << "ObjCARCExpand: Old = " << *Inst << "\n"
1000 " New = " << *Value << "\n");
1001 Inst->replaceAllUsesWith(Value);
John McCalld935e9c2011-06-15 23:37:01 +00001002 break;
Michael Gottesmanc8a11df2013-01-01 16:05:54 +00001003 }
John McCalld935e9c2011-06-15 23:37:01 +00001004 default:
1005 break;
1006 }
1007 }
Michael Gottesman10426b52013-01-07 21:26:07 +00001008
Michael Gottesman50ae5b22013-01-03 08:09:27 +00001009 DEBUG(dbgs() << "ObjCARCExpand: Finished List.\n\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001010
John McCalld935e9c2011-06-15 23:37:01 +00001011 return Changed;
1012}
1013
Michael Gottesman97e3df02013-01-14 00:35:14 +00001014/// @}
1015///
1016/// \defgroup ARCAPElim ARC Autorelease Pool Elimination.
1017/// @{
Dan Gohmane7a243f2012-01-17 20:52:24 +00001018
Dan Gohman41375a32012-05-08 23:39:44 +00001019#include "llvm/ADT/STLExtras.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +00001020#include "llvm/IR/Constants.h"
Dan Gohman82041c22012-01-18 21:19:38 +00001021
Dan Gohmane7a243f2012-01-17 20:52:24 +00001022namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001023 /// \brief Autorelease pool elimination.
Dan Gohmane7a243f2012-01-17 20:52:24 +00001024 class ObjCARCAPElim : public ModulePass {
1025 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1026 virtual bool runOnModule(Module &M);
1027
Dan Gohmandae33492012-04-27 18:56:31 +00001028 static bool MayAutorelease(ImmutableCallSite CS, unsigned Depth = 0);
1029 static bool OptimizeBB(BasicBlock *BB);
Dan Gohmane7a243f2012-01-17 20:52:24 +00001030
1031 public:
1032 static char ID;
1033 ObjCARCAPElim() : ModulePass(ID) {
1034 initializeObjCARCAPElimPass(*PassRegistry::getPassRegistry());
1035 }
1036 };
1037}
1038
1039char ObjCARCAPElim::ID = 0;
1040INITIALIZE_PASS(ObjCARCAPElim,
1041 "objc-arc-apelim",
1042 "ObjC ARC autorelease pool elimination",
1043 false, false)
1044
1045Pass *llvm::createObjCARCAPElimPass() {
1046 return new ObjCARCAPElim();
1047}
1048
1049void ObjCARCAPElim::getAnalysisUsage(AnalysisUsage &AU) const {
1050 AU.setPreservesCFG();
1051}
1052
Michael Gottesman97e3df02013-01-14 00:35:14 +00001053/// Interprocedurally determine if calls made by the given call site can
1054/// possibly produce autoreleases.
Dan Gohmandae33492012-04-27 18:56:31 +00001055bool ObjCARCAPElim::MayAutorelease(ImmutableCallSite CS, unsigned Depth) {
1056 if (const Function *Callee = CS.getCalledFunction()) {
Dan Gohmane7a243f2012-01-17 20:52:24 +00001057 if (Callee->isDeclaration() || Callee->mayBeOverridden())
1058 return true;
Dan Gohmandae33492012-04-27 18:56:31 +00001059 for (Function::const_iterator I = Callee->begin(), E = Callee->end();
Dan Gohmane7a243f2012-01-17 20:52:24 +00001060 I != E; ++I) {
Dan Gohmandae33492012-04-27 18:56:31 +00001061 const BasicBlock *BB = I;
1062 for (BasicBlock::const_iterator J = BB->begin(), F = BB->end();
1063 J != F; ++J)
1064 if (ImmutableCallSite JCS = ImmutableCallSite(J))
Dan Gohman8f12fae2012-01-18 21:24:45 +00001065 // This recursion depth limit is arbitrary. It's just great
1066 // enough to cover known interesting testcases.
1067 if (Depth < 3 &&
1068 !JCS.onlyReadsMemory() &&
1069 MayAutorelease(JCS, Depth + 1))
Dan Gohmane7a243f2012-01-17 20:52:24 +00001070 return true;
1071 }
1072 return false;
1073 }
1074
1075 return true;
1076}
1077
1078bool ObjCARCAPElim::OptimizeBB(BasicBlock *BB) {
1079 bool Changed = false;
1080
1081 Instruction *Push = 0;
1082 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1083 Instruction *Inst = I++;
1084 switch (GetBasicInstructionClass(Inst)) {
1085 case IC_AutoreleasepoolPush:
1086 Push = Inst;
1087 break;
1088 case IC_AutoreleasepoolPop:
1089 // If this pop matches a push and nothing in between can autorelease,
1090 // zap the pair.
1091 if (Push && cast<CallInst>(Inst)->getArgOperand(0) == Push) {
1092 Changed = true;
Michael Gottesman4385edf2013-01-14 01:47:53 +00001093 DEBUG(dbgs() << "ObjCARCAPElim::OptimizeBB: Zapping push pop "
1094 "autorelease pair:\n"
1095 " Pop: " << *Inst << "\n"
Michael Gottesmanef682c52013-01-03 08:09:17 +00001096 << " Push: " << *Push << "\n");
Dan Gohmane7a243f2012-01-17 20:52:24 +00001097 Inst->eraseFromParent();
1098 Push->eraseFromParent();
1099 }
1100 Push = 0;
1101 break;
1102 case IC_CallOrUser:
Dan Gohmandae33492012-04-27 18:56:31 +00001103 if (MayAutorelease(ImmutableCallSite(Inst)))
Dan Gohmane7a243f2012-01-17 20:52:24 +00001104 Push = 0;
1105 break;
1106 default:
1107 break;
1108 }
1109 }
1110
1111 return Changed;
1112}
1113
1114bool ObjCARCAPElim::runOnModule(Module &M) {
1115 if (!EnableARCOpts)
1116 return false;
1117
1118 // If nothing in the Module uses ARC, don't do anything.
1119 if (!ModuleHasARC(M))
1120 return false;
1121
Dan Gohman82041c22012-01-18 21:19:38 +00001122 // Find the llvm.global_ctors variable, as the first step in
Dan Gohman670f9372012-04-13 18:57:48 +00001123 // identifying the global constructors. In theory, unnecessary autorelease
1124 // pools could occur anywhere, but in practice it's pretty rare. Global
1125 // ctors are a place where autorelease pools get inserted automatically,
1126 // so it's pretty common for them to be unnecessary, and it's pretty
1127 // profitable to eliminate them.
Dan Gohman82041c22012-01-18 21:19:38 +00001128 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1129 if (!GV)
1130 return false;
1131
1132 assert(GV->hasDefinitiveInitializer() &&
1133 "llvm.global_ctors is uncooperative!");
1134
Dan Gohmane7a243f2012-01-17 20:52:24 +00001135 bool Changed = false;
1136
Dan Gohman82041c22012-01-18 21:19:38 +00001137 // Dig the constructor functions out of GV's initializer.
1138 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
1139 for (User::op_iterator OI = Init->op_begin(), OE = Init->op_end();
1140 OI != OE; ++OI) {
1141 Value *Op = *OI;
1142 // llvm.global_ctors is an array of pairs where the second members
1143 // are constructor functions.
Dan Gohman22fbe8d2012-04-18 22:24:33 +00001144 Function *F = dyn_cast<Function>(cast<ConstantStruct>(Op)->getOperand(1));
1145 // If the user used a constructor function with the wrong signature and
1146 // it got bitcasted or whatever, look the other way.
1147 if (!F)
1148 continue;
Dan Gohmane7a243f2012-01-17 20:52:24 +00001149 // Only look at function definitions.
1150 if (F->isDeclaration())
1151 continue;
Dan Gohmane7a243f2012-01-17 20:52:24 +00001152 // Only look at functions with one basic block.
1153 if (llvm::next(F->begin()) != F->end())
1154 continue;
1155 // Ok, a single-block constructor function definition. Try to optimize it.
1156 Changed |= OptimizeBB(F->begin());
1157 }
1158
1159 return Changed;
1160}
1161
Michael Gottesman97e3df02013-01-14 00:35:14 +00001162/// @}
1163///
1164/// \defgroup ARCOpt ARC Optimization.
1165/// @{
John McCalld935e9c2011-06-15 23:37:01 +00001166
1167// TODO: On code like this:
1168//
1169// objc_retain(%x)
1170// stuff_that_cannot_release()
1171// objc_autorelease(%x)
1172// stuff_that_cannot_release()
1173// objc_retain(%x)
1174// stuff_that_cannot_release()
1175// objc_autorelease(%x)
1176//
1177// The second retain and autorelease can be deleted.
1178
1179// TODO: It should be possible to delete
1180// objc_autoreleasePoolPush and objc_autoreleasePoolPop
1181// pairs if nothing is actually autoreleased between them. Also, autorelease
1182// calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
1183// after inlining) can be turned into plain release calls.
1184
1185// TODO: Critical-edge splitting. If the optimial insertion point is
1186// a critical edge, the current algorithm has to fail, because it doesn't
1187// know how to split edges. It should be possible to make the optimizer
1188// think in terms of edges, rather than blocks, and then split critical
1189// edges on demand.
1190
1191// TODO: OptimizeSequences could generalized to be Interprocedural.
1192
1193// TODO: Recognize that a bunch of other objc runtime calls have
1194// non-escaping arguments and non-releasing arguments, and may be
1195// non-autoreleasing.
1196
1197// TODO: Sink autorelease calls as far as possible. Unfortunately we
1198// usually can't sink them past other calls, which would be the main
1199// case where it would be useful.
1200
Dan Gohmanb3894012011-08-19 00:26:36 +00001201// TODO: The pointer returned from objc_loadWeakRetained is retained.
1202
1203// TODO: Delete release+retain pairs (rare).
Dan Gohmanceaac7c2011-06-20 23:20:43 +00001204
Chandler Carruthed0881b2012-12-03 16:50:05 +00001205#include "llvm/ADT/SmallPtrSet.h"
1206#include "llvm/ADT/Statistic.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +00001207#include "llvm/IR/LLVMContext.h"
John McCalld935e9c2011-06-15 23:37:01 +00001208#include "llvm/Support/CFG.h"
John McCalld935e9c2011-06-15 23:37:01 +00001209
1210STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
1211STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
1212STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
1213STATISTIC(NumRets, "Number of return value forwarding "
1214 "retain+autoreleaes eliminated");
1215STATISTIC(NumRRs, "Number of retain+release paths eliminated");
1216STATISTIC(NumPeeps, "Number of calls peephole-optimized");
1217
1218namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001219 /// \brief This is similar to BasicAliasAnalysis, and it uses many of the same
1220 /// techniques, except it uses special ObjC-specific reasoning about pointer
1221 /// relationships.
John McCalld935e9c2011-06-15 23:37:01 +00001222 class ProvenanceAnalysis {
1223 AliasAnalysis *AA;
1224
1225 typedef std::pair<const Value *, const Value *> ValuePairTy;
1226 typedef DenseMap<ValuePairTy, bool> CachedResultsTy;
1227 CachedResultsTy CachedResults;
1228
1229 bool relatedCheck(const Value *A, const Value *B);
1230 bool relatedSelect(const SelectInst *A, const Value *B);
1231 bool relatedPHI(const PHINode *A, const Value *B);
1232
Craig Topperb1d83e82012-09-18 02:01:41 +00001233 void operator=(const ProvenanceAnalysis &) LLVM_DELETED_FUNCTION;
1234 ProvenanceAnalysis(const ProvenanceAnalysis &) LLVM_DELETED_FUNCTION;
John McCalld935e9c2011-06-15 23:37:01 +00001235
1236 public:
1237 ProvenanceAnalysis() {}
1238
1239 void setAA(AliasAnalysis *aa) { AA = aa; }
1240
1241 AliasAnalysis *getAA() const { return AA; }
1242
1243 bool related(const Value *A, const Value *B);
1244
1245 void clear() {
1246 CachedResults.clear();
1247 }
1248 };
1249}
1250
1251bool ProvenanceAnalysis::relatedSelect(const SelectInst *A, const Value *B) {
1252 // If the values are Selects with the same condition, we can do a more precise
1253 // check: just check for relations between the values on corresponding arms.
1254 if (const SelectInst *SB = dyn_cast<SelectInst>(B))
Dan Gohmandae33492012-04-27 18:56:31 +00001255 if (A->getCondition() == SB->getCondition())
1256 return related(A->getTrueValue(), SB->getTrueValue()) ||
1257 related(A->getFalseValue(), SB->getFalseValue());
John McCalld935e9c2011-06-15 23:37:01 +00001258
1259 // Check both arms of the Select node individually.
Dan Gohmandae33492012-04-27 18:56:31 +00001260 return related(A->getTrueValue(), B) ||
1261 related(A->getFalseValue(), B);
John McCalld935e9c2011-06-15 23:37:01 +00001262}
1263
1264bool ProvenanceAnalysis::relatedPHI(const PHINode *A, const Value *B) {
1265 // If the values are PHIs in the same block, we can do a more precise as well
1266 // as efficient check: just check for relations between the values on
1267 // corresponding edges.
1268 if (const PHINode *PNB = dyn_cast<PHINode>(B))
1269 if (PNB->getParent() == A->getParent()) {
1270 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i)
1271 if (related(A->getIncomingValue(i),
1272 PNB->getIncomingValueForBlock(A->getIncomingBlock(i))))
1273 return true;
1274 return false;
1275 }
1276
1277 // Check each unique source of the PHI node against B.
1278 SmallPtrSet<const Value *, 4> UniqueSrc;
1279 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i) {
1280 const Value *PV1 = A->getIncomingValue(i);
1281 if (UniqueSrc.insert(PV1) && related(PV1, B))
1282 return true;
1283 }
1284
1285 // All of the arms checked out.
1286 return false;
1287}
1288
Michael Gottesman97e3df02013-01-14 00:35:14 +00001289/// Test if the value of P, or any value covered by its provenance, is ever
1290/// stored within the function (not counting callees).
John McCalld935e9c2011-06-15 23:37:01 +00001291static bool isStoredObjCPointer(const Value *P) {
1292 SmallPtrSet<const Value *, 8> Visited;
1293 SmallVector<const Value *, 8> Worklist;
1294 Worklist.push_back(P);
1295 Visited.insert(P);
1296 do {
1297 P = Worklist.pop_back_val();
1298 for (Value::const_use_iterator UI = P->use_begin(), UE = P->use_end();
1299 UI != UE; ++UI) {
1300 const User *Ur = *UI;
1301 if (isa<StoreInst>(Ur)) {
1302 if (UI.getOperandNo() == 0)
1303 // The pointer is stored.
1304 return true;
1305 // The pointed is stored through.
1306 continue;
1307 }
1308 if (isa<CallInst>(Ur))
1309 // The pointer is passed as an argument, ignore this.
1310 continue;
1311 if (isa<PtrToIntInst>(P))
1312 // Assume the worst.
1313 return true;
1314 if (Visited.insert(Ur))
1315 Worklist.push_back(Ur);
1316 }
1317 } while (!Worklist.empty());
1318
1319 // Everything checked out.
1320 return false;
1321}
1322
1323bool ProvenanceAnalysis::relatedCheck(const Value *A, const Value *B) {
1324 // Skip past provenance pass-throughs.
1325 A = GetUnderlyingObjCPtr(A);
1326 B = GetUnderlyingObjCPtr(B);
1327
1328 // Quick check.
1329 if (A == B)
1330 return true;
1331
1332 // Ask regular AliasAnalysis, for a first approximation.
1333 switch (AA->alias(A, B)) {
1334 case AliasAnalysis::NoAlias:
1335 return false;
1336 case AliasAnalysis::MustAlias:
1337 case AliasAnalysis::PartialAlias:
1338 return true;
1339 case AliasAnalysis::MayAlias:
1340 break;
1341 }
1342
1343 bool AIsIdentified = IsObjCIdentifiedObject(A);
1344 bool BIsIdentified = IsObjCIdentifiedObject(B);
1345
1346 // An ObjC-Identified object can't alias a load if it is never locally stored.
1347 if (AIsIdentified) {
Dan Gohmandf476e52012-09-04 23:16:20 +00001348 // Check for an obvious escape.
1349 if (isa<LoadInst>(B))
1350 return isStoredObjCPointer(A);
John McCalld935e9c2011-06-15 23:37:01 +00001351 if (BIsIdentified) {
Dan Gohmandf476e52012-09-04 23:16:20 +00001352 // Check for an obvious escape.
1353 if (isa<LoadInst>(A))
1354 return isStoredObjCPointer(B);
1355 // Both pointers are identified and escapes aren't an evident problem.
1356 return false;
John McCalld935e9c2011-06-15 23:37:01 +00001357 }
Dan Gohmandf476e52012-09-04 23:16:20 +00001358 } else if (BIsIdentified) {
1359 // Check for an obvious escape.
1360 if (isa<LoadInst>(A))
John McCalld935e9c2011-06-15 23:37:01 +00001361 return isStoredObjCPointer(B);
1362 }
1363
1364 // Special handling for PHI and Select.
1365 if (const PHINode *PN = dyn_cast<PHINode>(A))
1366 return relatedPHI(PN, B);
1367 if (const PHINode *PN = dyn_cast<PHINode>(B))
1368 return relatedPHI(PN, A);
1369 if (const SelectInst *S = dyn_cast<SelectInst>(A))
1370 return relatedSelect(S, B);
1371 if (const SelectInst *S = dyn_cast<SelectInst>(B))
1372 return relatedSelect(S, A);
1373
1374 // Conservative.
1375 return true;
1376}
1377
1378bool ProvenanceAnalysis::related(const Value *A, const Value *B) {
1379 // Begin by inserting a conservative value into the map. If the insertion
1380 // fails, we have the answer already. If it succeeds, leave it there until we
1381 // compute the real answer to guard against recursive queries.
1382 if (A > B) std::swap(A, B);
1383 std::pair<CachedResultsTy::iterator, bool> Pair =
1384 CachedResults.insert(std::make_pair(ValuePairTy(A, B), true));
1385 if (!Pair.second)
1386 return Pair.first->second;
1387
1388 bool Result = relatedCheck(A, B);
1389 CachedResults[ValuePairTy(A, B)] = Result;
1390 return Result;
1391}
1392
1393namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001394 /// \enum Sequence
1395 ///
1396 /// \brief A sequence of states that a pointer may go through in which an
1397 /// objc_retain and objc_release are actually needed.
John McCalld935e9c2011-06-15 23:37:01 +00001398 enum Sequence {
1399 S_None,
1400 S_Retain, ///< objc_retain(x)
1401 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement
1402 S_Use, ///< any use of x
1403 S_Stop, ///< like S_Release, but code motion is stopped
1404 S_Release, ///< objc_release(x)
1405 S_MovableRelease ///< objc_release(x), !clang.imprecise_release
1406 };
1407}
1408
1409static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
1410 // The easy cases.
1411 if (A == B)
1412 return A;
1413 if (A == S_None || B == S_None)
1414 return S_None;
1415
John McCalld935e9c2011-06-15 23:37:01 +00001416 if (A > B) std::swap(A, B);
1417 if (TopDown) {
1418 // Choose the side which is further along in the sequence.
Dan Gohman12130272011-08-12 00:26:31 +00001419 if ((A == S_Retain || A == S_CanRelease) &&
1420 (B == S_CanRelease || B == S_Use))
John McCalld935e9c2011-06-15 23:37:01 +00001421 return B;
1422 } else {
1423 // Choose the side which is further along in the sequence.
1424 if ((A == S_Use || A == S_CanRelease) &&
Dan Gohman12130272011-08-12 00:26:31 +00001425 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
John McCalld935e9c2011-06-15 23:37:01 +00001426 return A;
1427 // If both sides are releases, choose the more conservative one.
1428 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
1429 return A;
1430 if (A == S_Release && B == S_MovableRelease)
1431 return A;
1432 }
1433
1434 return S_None;
1435}
1436
1437namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001438 /// \brief Unidirectional information about either a
John McCalld935e9c2011-06-15 23:37:01 +00001439 /// retain-decrement-use-release sequence or release-use-decrement-retain
1440 /// reverese sequence.
1441 struct RRInfo {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001442 /// After an objc_retain, the reference count of the referenced
Dan Gohmanb3894012011-08-19 00:26:36 +00001443 /// object is known to be positive. Similarly, before an objc_release, the
1444 /// reference count of the referenced object is known to be positive. If
1445 /// there are retain-release pairs in code regions where the retain count
1446 /// is known to be positive, they can be eliminated, regardless of any side
1447 /// effects between them.
1448 ///
1449 /// Also, a retain+release pair nested within another retain+release
1450 /// pair all on the known same pointer value can be eliminated, regardless
1451 /// of any intervening side effects.
1452 ///
1453 /// KnownSafe is true when either of these conditions is satisfied.
1454 bool KnownSafe;
John McCalld935e9c2011-06-15 23:37:01 +00001455
Michael Gottesman97e3df02013-01-14 00:35:14 +00001456 /// True if the Calls are objc_retainBlock calls (as opposed to objc_retain
1457 /// calls).
John McCalld935e9c2011-06-15 23:37:01 +00001458 bool IsRetainBlock;
1459
Michael Gottesman97e3df02013-01-14 00:35:14 +00001460 /// True of the objc_release calls are all marked with the "tail" keyword.
John McCalld935e9c2011-06-15 23:37:01 +00001461 bool IsTailCallRelease;
1462
Michael Gottesman97e3df02013-01-14 00:35:14 +00001463 /// If the Calls are objc_release calls and they all have a
1464 /// clang.imprecise_release tag, this is the metadata tag.
John McCalld935e9c2011-06-15 23:37:01 +00001465 MDNode *ReleaseMetadata;
1466
Michael Gottesman97e3df02013-01-14 00:35:14 +00001467 /// For a top-down sequence, the set of objc_retains or
John McCalld935e9c2011-06-15 23:37:01 +00001468 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
1469 SmallPtrSet<Instruction *, 2> Calls;
1470
Michael Gottesman97e3df02013-01-14 00:35:14 +00001471 /// The set of optimal insert positions for moving calls in the opposite
1472 /// sequence.
John McCalld935e9c2011-06-15 23:37:01 +00001473 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
1474
1475 RRInfo() :
Dan Gohman728db492012-01-13 00:39:07 +00001476 KnownSafe(false), IsRetainBlock(false),
Dan Gohman62079b42012-04-25 00:50:46 +00001477 IsTailCallRelease(false),
John McCalld935e9c2011-06-15 23:37:01 +00001478 ReleaseMetadata(0) {}
1479
1480 void clear();
1481 };
1482}
1483
1484void RRInfo::clear() {
Dan Gohmanb3894012011-08-19 00:26:36 +00001485 KnownSafe = false;
John McCalld935e9c2011-06-15 23:37:01 +00001486 IsRetainBlock = false;
1487 IsTailCallRelease = false;
1488 ReleaseMetadata = 0;
1489 Calls.clear();
1490 ReverseInsertPts.clear();
1491}
1492
1493namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001494 /// \brief This class summarizes several per-pointer runtime properties which
1495 /// are propogated through the flow graph.
John McCalld935e9c2011-06-15 23:37:01 +00001496 class PtrState {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001497 /// True if the reference count is known to be incremented.
Dan Gohman62079b42012-04-25 00:50:46 +00001498 bool KnownPositiveRefCount;
1499
Michael Gottesman97e3df02013-01-14 00:35:14 +00001500 /// True of we've seen an opportunity for partial RR elimination, such as
1501 /// pushing calls into a CFG triangle or into one side of a CFG diamond.
Dan Gohman62079b42012-04-25 00:50:46 +00001502 bool Partial;
John McCalld935e9c2011-06-15 23:37:01 +00001503
Michael Gottesman97e3df02013-01-14 00:35:14 +00001504 /// The current position in the sequence.
Dan Gohman41375a32012-05-08 23:39:44 +00001505 Sequence Seq : 8;
John McCalld935e9c2011-06-15 23:37:01 +00001506
1507 public:
Michael Gottesman97e3df02013-01-14 00:35:14 +00001508 /// Unidirectional information about the current sequence.
1509 ///
John McCalld935e9c2011-06-15 23:37:01 +00001510 /// TODO: Encapsulate this better.
1511 RRInfo RRI;
1512
Dan Gohmandf476e52012-09-04 23:16:20 +00001513 PtrState() : KnownPositiveRefCount(false), Partial(false),
Dan Gohman41375a32012-05-08 23:39:44 +00001514 Seq(S_None) {}
John McCalld935e9c2011-06-15 23:37:01 +00001515
Dan Gohman62079b42012-04-25 00:50:46 +00001516 void SetKnownPositiveRefCount() {
1517 KnownPositiveRefCount = true;
Dan Gohman12130272011-08-12 00:26:31 +00001518 }
1519
Dan Gohman62079b42012-04-25 00:50:46 +00001520 void ClearRefCount() {
1521 KnownPositiveRefCount = false;
John McCalld935e9c2011-06-15 23:37:01 +00001522 }
1523
John McCalld935e9c2011-06-15 23:37:01 +00001524 bool IsKnownIncremented() const {
Dan Gohman62079b42012-04-25 00:50:46 +00001525 return KnownPositiveRefCount;
John McCalld935e9c2011-06-15 23:37:01 +00001526 }
1527
1528 void SetSeq(Sequence NewSeq) {
1529 Seq = NewSeq;
1530 }
1531
John McCalld935e9c2011-06-15 23:37:01 +00001532 Sequence GetSeq() const {
1533 return Seq;
1534 }
1535
1536 void ClearSequenceProgress() {
Dan Gohman62079b42012-04-25 00:50:46 +00001537 ResetSequenceProgress(S_None);
1538 }
1539
1540 void ResetSequenceProgress(Sequence NewSeq) {
1541 Seq = NewSeq;
1542 Partial = false;
John McCalld935e9c2011-06-15 23:37:01 +00001543 RRI.clear();
1544 }
1545
1546 void Merge(const PtrState &Other, bool TopDown);
1547 };
1548}
1549
1550void
1551PtrState::Merge(const PtrState &Other, bool TopDown) {
1552 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
Dan Gohman62079b42012-04-25 00:50:46 +00001553 KnownPositiveRefCount = KnownPositiveRefCount && Other.KnownPositiveRefCount;
John McCalld935e9c2011-06-15 23:37:01 +00001554
1555 // We can't merge a plain objc_retain with an objc_retainBlock.
1556 if (RRI.IsRetainBlock != Other.RRI.IsRetainBlock)
1557 Seq = S_None;
1558
Dan Gohman1736c142011-10-17 18:48:25 +00001559 // If we're not in a sequence (anymore), drop all associated state.
John McCalld935e9c2011-06-15 23:37:01 +00001560 if (Seq == S_None) {
Dan Gohman62079b42012-04-25 00:50:46 +00001561 Partial = false;
John McCalld935e9c2011-06-15 23:37:01 +00001562 RRI.clear();
Dan Gohman62079b42012-04-25 00:50:46 +00001563 } else if (Partial || Other.Partial) {
Dan Gohman1736c142011-10-17 18:48:25 +00001564 // If we're doing a merge on a path that's previously seen a partial
1565 // merge, conservatively drop the sequence, to avoid doing partial
1566 // RR elimination. If the branch predicates for the two merge differ,
1567 // mixing them is unsafe.
Dan Gohman62079b42012-04-25 00:50:46 +00001568 ClearSequenceProgress();
John McCalld935e9c2011-06-15 23:37:01 +00001569 } else {
1570 // Conservatively merge the ReleaseMetadata information.
1571 if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
1572 RRI.ReleaseMetadata = 0;
1573
Dan Gohmanb3894012011-08-19 00:26:36 +00001574 RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
Dan Gohman41375a32012-05-08 23:39:44 +00001575 RRI.IsTailCallRelease = RRI.IsTailCallRelease &&
1576 Other.RRI.IsTailCallRelease;
John McCalld935e9c2011-06-15 23:37:01 +00001577 RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
Dan Gohman1736c142011-10-17 18:48:25 +00001578
1579 // Merge the insert point sets. If there are any differences,
1580 // that makes this a partial merge.
Dan Gohman41375a32012-05-08 23:39:44 +00001581 Partial = RRI.ReverseInsertPts.size() != Other.RRI.ReverseInsertPts.size();
Dan Gohman1736c142011-10-17 18:48:25 +00001582 for (SmallPtrSet<Instruction *, 2>::const_iterator
1583 I = Other.RRI.ReverseInsertPts.begin(),
1584 E = Other.RRI.ReverseInsertPts.end(); I != E; ++I)
Dan Gohman62079b42012-04-25 00:50:46 +00001585 Partial |= RRI.ReverseInsertPts.insert(*I);
John McCalld935e9c2011-06-15 23:37:01 +00001586 }
1587}
1588
1589namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001590 /// \brief Per-BasicBlock state.
John McCalld935e9c2011-06-15 23:37:01 +00001591 class BBState {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001592 /// The number of unique control paths from the entry which can reach this
1593 /// block.
John McCalld935e9c2011-06-15 23:37:01 +00001594 unsigned TopDownPathCount;
1595
Michael Gottesman97e3df02013-01-14 00:35:14 +00001596 /// The number of unique control paths to exits from this block.
John McCalld935e9c2011-06-15 23:37:01 +00001597 unsigned BottomUpPathCount;
1598
Michael Gottesman97e3df02013-01-14 00:35:14 +00001599 /// A type for PerPtrTopDown and PerPtrBottomUp.
John McCalld935e9c2011-06-15 23:37:01 +00001600 typedef MapVector<const Value *, PtrState> MapTy;
1601
Michael Gottesman97e3df02013-01-14 00:35:14 +00001602 /// The top-down traversal uses this to record information known about a
1603 /// pointer at the bottom of each block.
John McCalld935e9c2011-06-15 23:37:01 +00001604 MapTy PerPtrTopDown;
1605
Michael Gottesman97e3df02013-01-14 00:35:14 +00001606 /// The bottom-up traversal uses this to record information known about a
1607 /// pointer at the top of each block.
John McCalld935e9c2011-06-15 23:37:01 +00001608 MapTy PerPtrBottomUp;
1609
Michael Gottesman97e3df02013-01-14 00:35:14 +00001610 /// Effective predecessors of the current block ignoring ignorable edges and
1611 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001612 SmallVector<BasicBlock *, 2> Preds;
Michael Gottesman97e3df02013-01-14 00:35:14 +00001613 /// Effective successors of the current block ignoring ignorable edges and
1614 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001615 SmallVector<BasicBlock *, 2> Succs;
1616
John McCalld935e9c2011-06-15 23:37:01 +00001617 public:
1618 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
1619
1620 typedef MapTy::iterator ptr_iterator;
1621 typedef MapTy::const_iterator ptr_const_iterator;
1622
1623 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
1624 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
1625 ptr_const_iterator top_down_ptr_begin() const {
1626 return PerPtrTopDown.begin();
1627 }
1628 ptr_const_iterator top_down_ptr_end() const {
1629 return PerPtrTopDown.end();
1630 }
1631
1632 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
1633 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
1634 ptr_const_iterator bottom_up_ptr_begin() const {
1635 return PerPtrBottomUp.begin();
1636 }
1637 ptr_const_iterator bottom_up_ptr_end() const {
1638 return PerPtrBottomUp.end();
1639 }
1640
Michael Gottesman97e3df02013-01-14 00:35:14 +00001641 /// Mark this block as being an entry block, which has one path from the
1642 /// entry by definition.
John McCalld935e9c2011-06-15 23:37:01 +00001643 void SetAsEntry() { TopDownPathCount = 1; }
1644
Michael Gottesman97e3df02013-01-14 00:35:14 +00001645 /// Mark this block as being an exit block, which has one path to an exit by
1646 /// definition.
John McCalld935e9c2011-06-15 23:37:01 +00001647 void SetAsExit() { BottomUpPathCount = 1; }
1648
1649 PtrState &getPtrTopDownState(const Value *Arg) {
1650 return PerPtrTopDown[Arg];
1651 }
1652
1653 PtrState &getPtrBottomUpState(const Value *Arg) {
1654 return PerPtrBottomUp[Arg];
1655 }
1656
1657 void clearBottomUpPointers() {
Evan Chenge4df6a22011-08-04 18:40:26 +00001658 PerPtrBottomUp.clear();
John McCalld935e9c2011-06-15 23:37:01 +00001659 }
1660
1661 void clearTopDownPointers() {
1662 PerPtrTopDown.clear();
1663 }
1664
1665 void InitFromPred(const BBState &Other);
1666 void InitFromSucc(const BBState &Other);
1667 void MergePred(const BBState &Other);
1668 void MergeSucc(const BBState &Other);
1669
Michael Gottesman97e3df02013-01-14 00:35:14 +00001670 /// Return the number of possible unique paths from an entry to an exit
1671 /// which pass through this block. This is only valid after both the
1672 /// top-down and bottom-up traversals are complete.
John McCalld935e9c2011-06-15 23:37:01 +00001673 unsigned GetAllPathCount() const {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001674 assert(TopDownPathCount != 0);
1675 assert(BottomUpPathCount != 0);
John McCalld935e9c2011-06-15 23:37:01 +00001676 return TopDownPathCount * BottomUpPathCount;
1677 }
Dan Gohman12130272011-08-12 00:26:31 +00001678
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001679 // Specialized CFG utilities.
Dan Gohmandae33492012-04-27 18:56:31 +00001680 typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001681 edge_iterator pred_begin() { return Preds.begin(); }
1682 edge_iterator pred_end() { return Preds.end(); }
1683 edge_iterator succ_begin() { return Succs.begin(); }
1684 edge_iterator succ_end() { return Succs.end(); }
1685
1686 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
1687 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
1688
1689 bool isExit() const { return Succs.empty(); }
John McCalld935e9c2011-06-15 23:37:01 +00001690 };
1691}
1692
1693void BBState::InitFromPred(const BBState &Other) {
1694 PerPtrTopDown = Other.PerPtrTopDown;
1695 TopDownPathCount = Other.TopDownPathCount;
1696}
1697
1698void BBState::InitFromSucc(const BBState &Other) {
1699 PerPtrBottomUp = Other.PerPtrBottomUp;
1700 BottomUpPathCount = Other.BottomUpPathCount;
1701}
1702
Michael Gottesman97e3df02013-01-14 00:35:14 +00001703/// The top-down traversal uses this to merge information about predecessors to
1704/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +00001705void BBState::MergePred(const BBState &Other) {
1706 // Other.TopDownPathCount can be 0, in which case it is either dead or a
1707 // loop backedge. Loop backedges are special.
1708 TopDownPathCount += Other.TopDownPathCount;
1709
Michael Gottesman4385edf2013-01-14 01:47:53 +00001710 // Check for overflow. If we have overflow, fall back to conservative
1711 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +00001712 if (TopDownPathCount < Other.TopDownPathCount) {
1713 clearTopDownPointers();
1714 return;
1715 }
1716
John McCalld935e9c2011-06-15 23:37:01 +00001717 // For each entry in the other set, if our set has an entry with the same key,
1718 // merge the entries. Otherwise, copy the entry and merge it with an empty
1719 // entry.
1720 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
1721 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
1722 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
1723 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1724 /*TopDown=*/true);
1725 }
1726
Dan Gohman7e315fc32011-08-11 21:06:32 +00001727 // For each entry in our set, if the other set doesn't have an entry with the
John McCalld935e9c2011-06-15 23:37:01 +00001728 // same key, force it to merge with an empty entry.
1729 for (ptr_iterator MI = top_down_ptr_begin(),
1730 ME = top_down_ptr_end(); MI != ME; ++MI)
1731 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
1732 MI->second.Merge(PtrState(), /*TopDown=*/true);
1733}
1734
Michael Gottesman97e3df02013-01-14 00:35:14 +00001735/// The bottom-up traversal uses this to merge information about successors to
1736/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +00001737void BBState::MergeSucc(const BBState &Other) {
1738 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
1739 // loop backedge. Loop backedges are special.
1740 BottomUpPathCount += Other.BottomUpPathCount;
1741
Michael Gottesman4385edf2013-01-14 01:47:53 +00001742 // Check for overflow. If we have overflow, fall back to conservative
1743 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +00001744 if (BottomUpPathCount < Other.BottomUpPathCount) {
1745 clearBottomUpPointers();
1746 return;
1747 }
1748
John McCalld935e9c2011-06-15 23:37:01 +00001749 // For each entry in the other set, if our set has an entry with the
1750 // same key, merge the entries. Otherwise, copy the entry and merge
1751 // it with an empty entry.
1752 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
1753 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
1754 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
1755 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1756 /*TopDown=*/false);
1757 }
1758
Dan Gohman7e315fc32011-08-11 21:06:32 +00001759 // For each entry in our set, if the other set doesn't have an entry
John McCalld935e9c2011-06-15 23:37:01 +00001760 // with the same key, force it to merge with an empty entry.
1761 for (ptr_iterator MI = bottom_up_ptr_begin(),
1762 ME = bottom_up_ptr_end(); MI != ME; ++MI)
1763 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
1764 MI->second.Merge(PtrState(), /*TopDown=*/false);
1765}
1766
1767namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001768 /// \brief The main ARC optimization pass.
John McCalld935e9c2011-06-15 23:37:01 +00001769 class ObjCARCOpt : public FunctionPass {
1770 bool Changed;
1771 ProvenanceAnalysis PA;
1772
Michael Gottesman97e3df02013-01-14 00:35:14 +00001773 /// A flag indicating whether this optimization pass should run.
Dan Gohmanceaac7c2011-06-20 23:20:43 +00001774 bool Run;
1775
Michael Gottesman97e3df02013-01-14 00:35:14 +00001776 /// Declarations for ObjC runtime functions, for use in creating calls to
1777 /// them. These are initialized lazily to avoid cluttering up the Module
1778 /// with unused declarations.
John McCalld935e9c2011-06-15 23:37:01 +00001779
Michael Gottesman97e3df02013-01-14 00:35:14 +00001780 /// Declaration for ObjC runtime function
1781 /// objc_retainAutoreleasedReturnValue.
1782 Constant *RetainRVCallee;
1783 /// Declaration for ObjC runtime function objc_autoreleaseReturnValue.
1784 Constant *AutoreleaseRVCallee;
1785 /// Declaration for ObjC runtime function objc_release.
1786 Constant *ReleaseCallee;
1787 /// Declaration for ObjC runtime function objc_retain.
1788 Constant *RetainCallee;
1789 /// Declaration for ObjC runtime function objc_retainBlock.
1790 Constant *RetainBlockCallee;
1791 /// Declaration for ObjC runtime function objc_autorelease.
1792 Constant *AutoreleaseCallee;
1793
1794 /// Flags which determine whether each of the interesting runtine functions
1795 /// is in fact used in the current function.
John McCalld935e9c2011-06-15 23:37:01 +00001796 unsigned UsedInThisFunction;
1797
Michael Gottesman97e3df02013-01-14 00:35:14 +00001798 /// The Metadata Kind for clang.imprecise_release metadata.
John McCalld935e9c2011-06-15 23:37:01 +00001799 unsigned ImpreciseReleaseMDKind;
1800
Michael Gottesman97e3df02013-01-14 00:35:14 +00001801 /// The Metadata Kind for clang.arc.copy_on_escape metadata.
Dan Gohmana7107f92011-10-17 22:53:25 +00001802 unsigned CopyOnEscapeMDKind;
1803
Michael Gottesman97e3df02013-01-14 00:35:14 +00001804 /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata.
Dan Gohman0155f302012-02-17 18:59:53 +00001805 unsigned NoObjCARCExceptionsMDKind;
1806
John McCalld935e9c2011-06-15 23:37:01 +00001807 Constant *getRetainRVCallee(Module *M);
1808 Constant *getAutoreleaseRVCallee(Module *M);
1809 Constant *getReleaseCallee(Module *M);
1810 Constant *getRetainCallee(Module *M);
Dan Gohman6320f522011-07-22 22:29:21 +00001811 Constant *getRetainBlockCallee(Module *M);
John McCalld935e9c2011-06-15 23:37:01 +00001812 Constant *getAutoreleaseCallee(Module *M);
1813
Dan Gohman728db492012-01-13 00:39:07 +00001814 bool IsRetainBlockOptimizable(const Instruction *Inst);
1815
John McCalld935e9c2011-06-15 23:37:01 +00001816 void OptimizeRetainCall(Function &F, Instruction *Retain);
1817 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
Michael Gottesman556ff612013-01-12 01:25:19 +00001818 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1819 InstructionClass &Class);
John McCalld935e9c2011-06-15 23:37:01 +00001820 void OptimizeIndividualCalls(Function &F);
1821
1822 void CheckForCFGHazards(const BasicBlock *BB,
1823 DenseMap<const BasicBlock *, BBState> &BBStates,
1824 BBState &MyStates) const;
Dan Gohman817a7c62012-03-22 18:24:56 +00001825 bool VisitInstructionBottomUp(Instruction *Inst,
Dan Gohman5c70fad2012-03-23 17:47:54 +00001826 BasicBlock *BB,
Dan Gohman817a7c62012-03-22 18:24:56 +00001827 MapVector<Value *, RRInfo> &Retains,
1828 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00001829 bool VisitBottomUp(BasicBlock *BB,
1830 DenseMap<const BasicBlock *, BBState> &BBStates,
1831 MapVector<Value *, RRInfo> &Retains);
Dan Gohman817a7c62012-03-22 18:24:56 +00001832 bool VisitInstructionTopDown(Instruction *Inst,
1833 DenseMap<Value *, RRInfo> &Releases,
1834 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00001835 bool VisitTopDown(BasicBlock *BB,
1836 DenseMap<const BasicBlock *, BBState> &BBStates,
1837 DenseMap<Value *, RRInfo> &Releases);
1838 bool Visit(Function &F,
1839 DenseMap<const BasicBlock *, BBState> &BBStates,
1840 MapVector<Value *, RRInfo> &Retains,
1841 DenseMap<Value *, RRInfo> &Releases);
1842
1843 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1844 MapVector<Value *, RRInfo> &Retains,
1845 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman6320f522011-07-22 22:29:21 +00001846 SmallVectorImpl<Instruction *> &DeadInsts,
1847 Module *M);
John McCalld935e9c2011-06-15 23:37:01 +00001848
1849 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1850 MapVector<Value *, RRInfo> &Retains,
Dan Gohman6320f522011-07-22 22:29:21 +00001851 DenseMap<Value *, RRInfo> &Releases,
1852 Module *M);
John McCalld935e9c2011-06-15 23:37:01 +00001853
1854 void OptimizeWeakCalls(Function &F);
1855
1856 bool OptimizeSequences(Function &F);
1857
1858 void OptimizeReturns(Function &F);
1859
1860 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1861 virtual bool doInitialization(Module &M);
1862 virtual bool runOnFunction(Function &F);
1863 virtual void releaseMemory();
1864
1865 public:
1866 static char ID;
1867 ObjCARCOpt() : FunctionPass(ID) {
1868 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1869 }
1870 };
1871}
1872
1873char ObjCARCOpt::ID = 0;
1874INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1875 "objc-arc", "ObjC ARC optimization", false, false)
1876INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1877INITIALIZE_PASS_END(ObjCARCOpt,
1878 "objc-arc", "ObjC ARC optimization", false, false)
1879
1880Pass *llvm::createObjCARCOptPass() {
1881 return new ObjCARCOpt();
1882}
1883
1884void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1885 AU.addRequired<ObjCARCAliasAnalysis>();
1886 AU.addRequired<AliasAnalysis>();
1887 // ARC optimization doesn't currently split critical edges.
1888 AU.setPreservesCFG();
1889}
1890
Dan Gohman728db492012-01-13 00:39:07 +00001891bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1892 // Without the magic metadata tag, we have to assume this might be an
1893 // objc_retainBlock call inserted to convert a block pointer to an id,
1894 // in which case it really is needed.
1895 if (!Inst->getMetadata(CopyOnEscapeMDKind))
1896 return false;
1897
1898 // If the pointer "escapes" (not including being used in a call),
1899 // the copy may be needed.
1900 if (DoesObjCBlockEscape(Inst))
1901 return false;
1902
1903 // Otherwise, it's not needed.
1904 return true;
1905}
1906
John McCalld935e9c2011-06-15 23:37:01 +00001907Constant *ObjCARCOpt::getRetainRVCallee(Module *M) {
1908 if (!RetainRVCallee) {
1909 LLVMContext &C = M->getContext();
Jay Foadb804a2b2011-07-12 14:06:48 +00001910 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman41375a32012-05-08 23:39:44 +00001911 Type *Params[] = { I8X };
1912 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001913 AttributeSet Attribute =
Bill Wendlinge94d8432012-12-07 23:16:57 +00001914 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001915 Attribute::get(C, Attribute::NoUnwind));
John McCalld935e9c2011-06-15 23:37:01 +00001916 RetainRVCallee =
1917 M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy,
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001918 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001919 }
1920 return RetainRVCallee;
1921}
1922
1923Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1924 if (!AutoreleaseRVCallee) {
1925 LLVMContext &C = M->getContext();
Jay Foadb804a2b2011-07-12 14:06:48 +00001926 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman41375a32012-05-08 23:39:44 +00001927 Type *Params[] = { I8X };
1928 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001929 AttributeSet Attribute =
Bill Wendlinge94d8432012-12-07 23:16:57 +00001930 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001931 Attribute::get(C, Attribute::NoUnwind));
John McCalld935e9c2011-06-15 23:37:01 +00001932 AutoreleaseRVCallee =
1933 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001934 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001935 }
1936 return AutoreleaseRVCallee;
1937}
1938
1939Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1940 if (!ReleaseCallee) {
1941 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001942 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001943 AttributeSet Attribute =
Bill Wendlinge94d8432012-12-07 23:16:57 +00001944 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001945 Attribute::get(C, Attribute::NoUnwind));
John McCalld935e9c2011-06-15 23:37:01 +00001946 ReleaseCallee =
1947 M->getOrInsertFunction(
1948 "objc_release",
1949 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001950 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001951 }
1952 return ReleaseCallee;
1953}
1954
1955Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1956 if (!RetainCallee) {
1957 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001958 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001959 AttributeSet Attribute =
Bill Wendlinge94d8432012-12-07 23:16:57 +00001960 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001961 Attribute::get(C, Attribute::NoUnwind));
John McCalld935e9c2011-06-15 23:37:01 +00001962 RetainCallee =
1963 M->getOrInsertFunction(
1964 "objc_retain",
1965 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001966 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001967 }
1968 return RetainCallee;
1969}
1970
Dan Gohman6320f522011-07-22 22:29:21 +00001971Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1972 if (!RetainBlockCallee) {
1973 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001974 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Dan Gohmanfca43c22011-09-14 18:33:34 +00001975 // objc_retainBlock is not nounwind because it calls user copy constructors
1976 // which could theoretically throw.
Dan Gohman6320f522011-07-22 22:29:21 +00001977 RetainBlockCallee =
1978 M->getOrInsertFunction(
1979 "objc_retainBlock",
1980 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendlinge94d8432012-12-07 23:16:57 +00001981 AttributeSet());
Dan Gohman6320f522011-07-22 22:29:21 +00001982 }
1983 return RetainBlockCallee;
1984}
1985
John McCalld935e9c2011-06-15 23:37:01 +00001986Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1987 if (!AutoreleaseCallee) {
1988 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001989 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001990 AttributeSet Attribute =
Bill Wendlinge94d8432012-12-07 23:16:57 +00001991 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001992 Attribute::get(C, Attribute::NoUnwind));
John McCalld935e9c2011-06-15 23:37:01 +00001993 AutoreleaseCallee =
1994 M->getOrInsertFunction(
1995 "objc_autorelease",
1996 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001997 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001998 }
1999 return AutoreleaseCallee;
2000}
2001
Michael Gottesman97e3df02013-01-14 00:35:14 +00002002/// Test whether the given value is possible a reference-counted pointer,
2003/// including tests which utilize AliasAnalysis.
Dan Gohmandf476e52012-09-04 23:16:20 +00002004static bool IsPotentialUse(const Value *Op, AliasAnalysis &AA) {
2005 // First make the rudimentary check.
2006 if (!IsPotentialUse(Op))
2007 return false;
2008
2009 // Objects in constant memory are not reference-counted.
2010 if (AA.pointsToConstantMemory(Op))
2011 return false;
2012
2013 // Pointers in constant memory are not pointing to reference-counted objects.
2014 if (const LoadInst *LI = dyn_cast<LoadInst>(Op))
2015 if (AA.pointsToConstantMemory(LI->getPointerOperand()))
2016 return false;
2017
2018 // Otherwise assume the worst.
2019 return true;
2020}
2021
Michael Gottesman97e3df02013-01-14 00:35:14 +00002022/// Test whether the given instruction can result in a reference count
2023/// modification (positive or negative) for the pointer's object.
John McCalld935e9c2011-06-15 23:37:01 +00002024static bool
2025CanAlterRefCount(const Instruction *Inst, const Value *Ptr,
2026 ProvenanceAnalysis &PA, InstructionClass Class) {
2027 switch (Class) {
2028 case IC_Autorelease:
2029 case IC_AutoreleaseRV:
2030 case IC_User:
2031 // These operations never directly modify a reference count.
2032 return false;
2033 default: break;
2034 }
2035
2036 ImmutableCallSite CS = static_cast<const Value *>(Inst);
2037 assert(CS && "Only calls can alter reference counts!");
2038
2039 // See if AliasAnalysis can help us with the call.
2040 AliasAnalysis::ModRefBehavior MRB = PA.getAA()->getModRefBehavior(CS);
2041 if (AliasAnalysis::onlyReadsMemory(MRB))
2042 return false;
2043 if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
2044 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
2045 I != E; ++I) {
2046 const Value *Op = *I;
Dan Gohmandf476e52012-09-04 23:16:20 +00002047 if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
John McCalld935e9c2011-06-15 23:37:01 +00002048 return true;
2049 }
2050 return false;
2051 }
2052
2053 // Assume the worst.
2054 return true;
2055}
2056
Michael Gottesman97e3df02013-01-14 00:35:14 +00002057/// Test whether the given instruction can "use" the given pointer's object in a
2058/// way that requires the reference count to be positive.
John McCalld935e9c2011-06-15 23:37:01 +00002059static bool
2060CanUse(const Instruction *Inst, const Value *Ptr, ProvenanceAnalysis &PA,
2061 InstructionClass Class) {
2062 // IC_Call operations (as opposed to IC_CallOrUser) never "use" objc pointers.
2063 if (Class == IC_Call)
2064 return false;
2065
2066 // Consider various instructions which may have pointer arguments which are
2067 // not "uses".
2068 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(Inst)) {
2069 // Comparing a pointer with null, or any other constant, isn't really a use,
2070 // because we don't care what the pointer points to, or about the values
2071 // of any other dynamic reference-counted pointers.
Dan Gohmandf476e52012-09-04 23:16:20 +00002072 if (!IsPotentialUse(ICI->getOperand(1), *PA.getAA()))
John McCalld935e9c2011-06-15 23:37:01 +00002073 return false;
2074 } else if (ImmutableCallSite CS = static_cast<const Value *>(Inst)) {
2075 // For calls, just check the arguments (and not the callee operand).
2076 for (ImmutableCallSite::arg_iterator OI = CS.arg_begin(),
2077 OE = CS.arg_end(); OI != OE; ++OI) {
2078 const Value *Op = *OI;
Dan Gohmandf476e52012-09-04 23:16:20 +00002079 if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
John McCalld935e9c2011-06-15 23:37:01 +00002080 return true;
2081 }
2082 return false;
2083 } else if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
2084 // Special-case stores, because we don't care about the stored value, just
2085 // the store address.
2086 const Value *Op = GetUnderlyingObjCPtr(SI->getPointerOperand());
2087 // If we can't tell what the underlying object was, assume there is a
2088 // dependence.
Dan Gohmandf476e52012-09-04 23:16:20 +00002089 return IsPotentialUse(Op, *PA.getAA()) && PA.related(Op, Ptr);
John McCalld935e9c2011-06-15 23:37:01 +00002090 }
2091
2092 // Check each operand for a match.
2093 for (User::const_op_iterator OI = Inst->op_begin(), OE = Inst->op_end();
2094 OI != OE; ++OI) {
2095 const Value *Op = *OI;
Dan Gohmandf476e52012-09-04 23:16:20 +00002096 if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
John McCalld935e9c2011-06-15 23:37:01 +00002097 return true;
2098 }
2099 return false;
2100}
2101
Michael Gottesman97e3df02013-01-14 00:35:14 +00002102/// Test whether the given instruction can autorelease any pointer or cause an
2103/// autoreleasepool pop.
John McCalld935e9c2011-06-15 23:37:01 +00002104static bool
2105CanInterruptRV(InstructionClass Class) {
2106 switch (Class) {
2107 case IC_AutoreleasepoolPop:
2108 case IC_CallOrUser:
2109 case IC_Call:
2110 case IC_Autorelease:
2111 case IC_AutoreleaseRV:
2112 case IC_FusedRetainAutorelease:
2113 case IC_FusedRetainAutoreleaseRV:
2114 return true;
2115 default:
2116 return false;
2117 }
2118}
2119
2120namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +00002121 /// \enum DependenceKind
2122 /// \brief Defines different dependence kinds among various ARC constructs.
2123 ///
2124 /// There are several kinds of dependence-like concepts in use here.
2125 ///
John McCalld935e9c2011-06-15 23:37:01 +00002126 enum DependenceKind {
2127 NeedsPositiveRetainCount,
Dan Gohman8478d762012-04-13 00:59:57 +00002128 AutoreleasePoolBoundary,
John McCalld935e9c2011-06-15 23:37:01 +00002129 CanChangeRetainCount,
2130 RetainAutoreleaseDep, ///< Blocks objc_retainAutorelease.
2131 RetainAutoreleaseRVDep, ///< Blocks objc_retainAutoreleaseReturnValue.
2132 RetainRVDep ///< Blocks objc_retainAutoreleasedReturnValue.
2133 };
2134}
2135
Michael Gottesman97e3df02013-01-14 00:35:14 +00002136/// Test if there can be dependencies on Inst through Arg. This function only
2137/// tests dependencies relevant for removing pairs of calls.
John McCalld935e9c2011-06-15 23:37:01 +00002138static bool
2139Depends(DependenceKind Flavor, Instruction *Inst, const Value *Arg,
2140 ProvenanceAnalysis &PA) {
2141 // If we've reached the definition of Arg, stop.
2142 if (Inst == Arg)
2143 return true;
2144
2145 switch (Flavor) {
2146 case NeedsPositiveRetainCount: {
2147 InstructionClass Class = GetInstructionClass(Inst);
2148 switch (Class) {
2149 case IC_AutoreleasepoolPop:
2150 case IC_AutoreleasepoolPush:
2151 case IC_None:
2152 return false;
2153 default:
2154 return CanUse(Inst, Arg, PA, Class);
2155 }
2156 }
2157
Dan Gohman8478d762012-04-13 00:59:57 +00002158 case AutoreleasePoolBoundary: {
2159 InstructionClass Class = GetInstructionClass(Inst);
2160 switch (Class) {
2161 case IC_AutoreleasepoolPop:
2162 case IC_AutoreleasepoolPush:
2163 // These mark the end and begin of an autorelease pool scope.
2164 return true;
2165 default:
2166 // Nothing else does this.
2167 return false;
2168 }
2169 }
2170
John McCalld935e9c2011-06-15 23:37:01 +00002171 case CanChangeRetainCount: {
2172 InstructionClass Class = GetInstructionClass(Inst);
2173 switch (Class) {
2174 case IC_AutoreleasepoolPop:
2175 // Conservatively assume this can decrement any count.
2176 return true;
2177 case IC_AutoreleasepoolPush:
2178 case IC_None:
2179 return false;
2180 default:
2181 return CanAlterRefCount(Inst, Arg, PA, Class);
2182 }
2183 }
2184
2185 case RetainAutoreleaseDep:
2186 switch (GetBasicInstructionClass(Inst)) {
2187 case IC_AutoreleasepoolPop:
Dan Gohman8478d762012-04-13 00:59:57 +00002188 case IC_AutoreleasepoolPush:
John McCalld935e9c2011-06-15 23:37:01 +00002189 // Don't merge an objc_autorelease with an objc_retain inside a different
2190 // autoreleasepool scope.
2191 return true;
2192 case IC_Retain:
2193 case IC_RetainRV:
2194 // Check for a retain of the same pointer for merging.
2195 return GetObjCArg(Inst) == Arg;
2196 default:
2197 // Nothing else matters for objc_retainAutorelease formation.
2198 return false;
2199 }
John McCalld935e9c2011-06-15 23:37:01 +00002200
2201 case RetainAutoreleaseRVDep: {
2202 InstructionClass Class = GetBasicInstructionClass(Inst);
2203 switch (Class) {
2204 case IC_Retain:
2205 case IC_RetainRV:
2206 // Check for a retain of the same pointer for merging.
2207 return GetObjCArg(Inst) == Arg;
2208 default:
2209 // Anything that can autorelease interrupts
2210 // retainAutoreleaseReturnValue formation.
2211 return CanInterruptRV(Class);
2212 }
John McCalld935e9c2011-06-15 23:37:01 +00002213 }
2214
2215 case RetainRVDep:
2216 return CanInterruptRV(GetBasicInstructionClass(Inst));
2217 }
2218
2219 llvm_unreachable("Invalid dependence flavor");
John McCalld935e9c2011-06-15 23:37:01 +00002220}
2221
Michael Gottesman97e3df02013-01-14 00:35:14 +00002222/// Walk up the CFG from StartPos (which is in StartBB) and find local and
2223/// non-local dependencies on Arg.
2224///
John McCalld935e9c2011-06-15 23:37:01 +00002225/// TODO: Cache results?
2226static void
2227FindDependencies(DependenceKind Flavor,
2228 const Value *Arg,
2229 BasicBlock *StartBB, Instruction *StartInst,
2230 SmallPtrSet<Instruction *, 4> &DependingInstructions,
2231 SmallPtrSet<const BasicBlock *, 4> &Visited,
2232 ProvenanceAnalysis &PA) {
2233 BasicBlock::iterator StartPos = StartInst;
2234
2235 SmallVector<std::pair<BasicBlock *, BasicBlock::iterator>, 4> Worklist;
2236 Worklist.push_back(std::make_pair(StartBB, StartPos));
2237 do {
2238 std::pair<BasicBlock *, BasicBlock::iterator> Pair =
2239 Worklist.pop_back_val();
2240 BasicBlock *LocalStartBB = Pair.first;
2241 BasicBlock::iterator LocalStartPos = Pair.second;
2242 BasicBlock::iterator StartBBBegin = LocalStartBB->begin();
2243 for (;;) {
2244 if (LocalStartPos == StartBBBegin) {
2245 pred_iterator PI(LocalStartBB), PE(LocalStartBB, false);
2246 if (PI == PE)
2247 // If we've reached the function entry, produce a null dependence.
2248 DependingInstructions.insert(0);
2249 else
2250 // Add the predecessors to the worklist.
2251 do {
2252 BasicBlock *PredBB = *PI;
2253 if (Visited.insert(PredBB))
2254 Worklist.push_back(std::make_pair(PredBB, PredBB->end()));
2255 } while (++PI != PE);
2256 break;
2257 }
2258
2259 Instruction *Inst = --LocalStartPos;
2260 if (Depends(Flavor, Inst, Arg, PA)) {
2261 DependingInstructions.insert(Inst);
2262 break;
2263 }
2264 }
2265 } while (!Worklist.empty());
2266
2267 // Determine whether the original StartBB post-dominates all of the blocks we
2268 // visited. If not, insert a sentinal indicating that most optimizations are
2269 // not safe.
2270 for (SmallPtrSet<const BasicBlock *, 4>::const_iterator I = Visited.begin(),
2271 E = Visited.end(); I != E; ++I) {
2272 const BasicBlock *BB = *I;
2273 if (BB == StartBB)
2274 continue;
2275 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2276 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2277 const BasicBlock *Succ = *SI;
2278 if (Succ != StartBB && !Visited.count(Succ)) {
2279 DependingInstructions.insert(reinterpret_cast<Instruction *>(-1));
2280 return;
2281 }
2282 }
2283 }
2284}
2285
2286static bool isNullOrUndef(const Value *V) {
2287 return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
2288}
2289
2290static bool isNoopInstruction(const Instruction *I) {
2291 return isa<BitCastInst>(I) ||
2292 (isa<GetElementPtrInst>(I) &&
2293 cast<GetElementPtrInst>(I)->hasAllZeroIndices());
2294}
2295
Michael Gottesman97e3df02013-01-14 00:35:14 +00002296/// Turn objc_retain into objc_retainAutoreleasedReturnValue if the operand is a
2297/// return value.
John McCalld935e9c2011-06-15 23:37:01 +00002298void
2299ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) {
Dan Gohmandae33492012-04-27 18:56:31 +00002300 ImmutableCallSite CS(GetObjCArg(Retain));
2301 const Instruction *Call = CS.getInstruction();
John McCalld935e9c2011-06-15 23:37:01 +00002302 if (!Call) return;
2303 if (Call->getParent() != Retain->getParent()) return;
2304
2305 // Check that the call is next to the retain.
Dan Gohmandae33492012-04-27 18:56:31 +00002306 BasicBlock::const_iterator I = Call;
John McCalld935e9c2011-06-15 23:37:01 +00002307 ++I;
2308 while (isNoopInstruction(I)) ++I;
2309 if (&*I != Retain)
2310 return;
2311
2312 // Turn it to an objc_retainAutoreleasedReturnValue..
2313 Changed = true;
2314 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00002315
Michael Gottesman1e00ac62013-01-04 21:30:38 +00002316 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainCall: Transforming "
Michael Gottesman9f1be682013-01-12 03:45:49 +00002317 "objc_retain => objc_retainAutoreleasedReturnValue"
2318 " since the operand is a return value.\n"
Michael Gottesman1e00ac62013-01-04 21:30:38 +00002319 " Old: "
2320 << *Retain << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00002321
John McCalld935e9c2011-06-15 23:37:01 +00002322 cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent()));
Michael Gottesman1e00ac62013-01-04 21:30:38 +00002323
2324 DEBUG(dbgs() << " New: "
2325 << *Retain << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002326}
2327
Michael Gottesman97e3df02013-01-14 00:35:14 +00002328/// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is
2329/// not a return value. Or, if it can be paired with an
2330/// objc_autoreleaseReturnValue, delete the pair and return true.
John McCalld935e9c2011-06-15 23:37:01 +00002331bool
2332ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +00002333 // Check for the argument being from an immediately preceding call or invoke.
Dan Gohmandae33492012-04-27 18:56:31 +00002334 const Value *Arg = GetObjCArg(RetainRV);
2335 ImmutableCallSite CS(Arg);
2336 if (const Instruction *Call = CS.getInstruction()) {
John McCalld935e9c2011-06-15 23:37:01 +00002337 if (Call->getParent() == RetainRV->getParent()) {
Dan Gohmandae33492012-04-27 18:56:31 +00002338 BasicBlock::const_iterator I = Call;
John McCalld935e9c2011-06-15 23:37:01 +00002339 ++I;
2340 while (isNoopInstruction(I)) ++I;
2341 if (&*I == RetainRV)
2342 return false;
Dan Gohmandae33492012-04-27 18:56:31 +00002343 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +00002344 BasicBlock *RetainRVParent = RetainRV->getParent();
2345 if (II->getNormalDest() == RetainRVParent) {
Dan Gohmandae33492012-04-27 18:56:31 +00002346 BasicBlock::const_iterator I = RetainRVParent->begin();
Dan Gohmane3ed2b02012-03-23 18:09:00 +00002347 while (isNoopInstruction(I)) ++I;
2348 if (&*I == RetainRV)
2349 return false;
2350 }
John McCalld935e9c2011-06-15 23:37:01 +00002351 }
Dan Gohmane3ed2b02012-03-23 18:09:00 +00002352 }
John McCalld935e9c2011-06-15 23:37:01 +00002353
2354 // Check for being preceded by an objc_autoreleaseReturnValue on the same
2355 // pointer. In this case, we can delete the pair.
2356 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
2357 if (I != Begin) {
2358 do --I; while (I != Begin && isNoopInstruction(I));
2359 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
2360 GetObjCArg(I) == Arg) {
2361 Changed = true;
2362 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00002363
Michael Gottesman5c32ce92013-01-05 17:55:35 +00002364 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainRVCall: Erasing " << *I << "\n"
2365 << " Erasing " << *RetainRV
2366 << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00002367
John McCalld935e9c2011-06-15 23:37:01 +00002368 EraseInstruction(I);
2369 EraseInstruction(RetainRV);
2370 return true;
2371 }
2372 }
2373
2374 // Turn it to a plain objc_retain.
2375 Changed = true;
2376 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00002377
Michael Gottesmandef07bb2013-01-05 17:55:42 +00002378 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainRVCall: Transforming "
2379 "objc_retainAutoreleasedReturnValue => "
2380 "objc_retain since the operand is not a return value.\n"
2381 " Old: "
2382 << *RetainRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00002383
John McCalld935e9c2011-06-15 23:37:01 +00002384 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
Michael Gottesmandef07bb2013-01-05 17:55:42 +00002385
2386 DEBUG(dbgs() << " New: "
2387 << *RetainRV << "\n");
2388
John McCalld935e9c2011-06-15 23:37:01 +00002389 return false;
2390}
2391
Michael Gottesman97e3df02013-01-14 00:35:14 +00002392/// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not
2393/// used as a return value.
John McCalld935e9c2011-06-15 23:37:01 +00002394void
Michael Gottesman556ff612013-01-12 01:25:19 +00002395ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
2396 InstructionClass &Class) {
John McCalld935e9c2011-06-15 23:37:01 +00002397 // Check for a return of the pointer value.
2398 const Value *Ptr = GetObjCArg(AutoreleaseRV);
Dan Gohman10a18d52011-08-12 00:36:31 +00002399 SmallVector<const Value *, 2> Users;
2400 Users.push_back(Ptr);
2401 do {
2402 Ptr = Users.pop_back_val();
2403 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
2404 UI != UE; ++UI) {
2405 const User *I = *UI;
2406 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
2407 return;
2408 if (isa<BitCastInst>(I))
2409 Users.push_back(I);
2410 }
2411 } while (!Users.empty());
John McCalld935e9c2011-06-15 23:37:01 +00002412
2413 Changed = true;
2414 ++NumPeeps;
Michael Gottesman1bf69082013-01-06 21:07:11 +00002415
2416 DEBUG(dbgs() << "ObjCARCOpt::OptimizeAutoreleaseRVCall: Transforming "
2417 "objc_autoreleaseReturnValue => "
2418 "objc_autorelease since its operand is not used as a return "
2419 "value.\n"
2420 " Old: "
2421 << *AutoreleaseRV << "\n");
2422
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00002423 CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
2424 AutoreleaseRVCI->
John McCalld935e9c2011-06-15 23:37:01 +00002425 setCalledFunction(getAutoreleaseCallee(F.getParent()));
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00002426 AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
Michael Gottesman556ff612013-01-12 01:25:19 +00002427 Class = IC_Autorelease;
Michael Gottesman10426b52013-01-07 21:26:07 +00002428
Michael Gottesman1bf69082013-01-06 21:07:11 +00002429 DEBUG(dbgs() << " New: "
2430 << *AutoreleaseRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00002431
John McCalld935e9c2011-06-15 23:37:01 +00002432}
2433
Michael Gottesman97e3df02013-01-14 00:35:14 +00002434/// Visit each call, one at a time, and make simplifications without doing any
2435/// additional analysis.
John McCalld935e9c2011-06-15 23:37:01 +00002436void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
2437 // Reset all the flags in preparation for recomputing them.
2438 UsedInThisFunction = 0;
2439
2440 // Visit all objc_* calls in F.
2441 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2442 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +00002443
John McCalld935e9c2011-06-15 23:37:01 +00002444 InstructionClass Class = GetBasicInstructionClass(Inst);
2445
Michael Gottesmand359e062013-01-18 03:08:39 +00002446 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Visiting: Class: "
2447 << Class << "; " << *Inst << "\n");
Michael Gottesman782e3442013-01-17 18:32:34 +00002448
John McCalld935e9c2011-06-15 23:37:01 +00002449 switch (Class) {
2450 default: break;
2451
2452 // Delete no-op casts. These function calls have special semantics, but
2453 // the semantics are entirely implemented via lowering in the front-end,
2454 // so by the time they reach the optimizer, they are just no-op calls
2455 // which return their argument.
2456 //
2457 // There are gray areas here, as the ability to cast reference-counted
2458 // pointers to raw void* and back allows code to break ARC assumptions,
2459 // however these are currently considered to be unimportant.
2460 case IC_NoopCast:
2461 Changed = true;
2462 ++NumNoops;
Michael Gottesmandc042f02013-01-06 21:07:15 +00002463 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Erasing no-op cast:"
2464 " " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002465 EraseInstruction(Inst);
2466 continue;
2467
2468 // If the pointer-to-weak-pointer is null, it's undefined behavior.
2469 case IC_StoreWeak:
2470 case IC_LoadWeak:
2471 case IC_LoadWeakRetained:
2472 case IC_InitWeak:
2473 case IC_DestroyWeak: {
2474 CallInst *CI = cast<CallInst>(Inst);
2475 if (isNullOrUndef(CI->getArgOperand(0))) {
Dan Gohman670f9372012-04-13 18:57:48 +00002476 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +00002477 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00002478 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2479 Constant::getNullValue(Ty),
2480 CI);
Michael Gottesman10426b52013-01-07 21:26:07 +00002481 llvm::Value *NewValue = UndefValue::get(CI->getType());
Michael Gottesmanfec61c02013-01-06 21:54:30 +00002482 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: A null "
2483 "pointer-to-weak-pointer is undefined behavior.\n"
2484 " Old = " << *CI <<
2485 "\n New = " <<
Michael Gottesman10426b52013-01-07 21:26:07 +00002486 *NewValue << "\n");
Michael Gottesmanfec61c02013-01-06 21:54:30 +00002487 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +00002488 CI->eraseFromParent();
2489 continue;
2490 }
2491 break;
2492 }
2493 case IC_CopyWeak:
2494 case IC_MoveWeak: {
2495 CallInst *CI = cast<CallInst>(Inst);
2496 if (isNullOrUndef(CI->getArgOperand(0)) ||
2497 isNullOrUndef(CI->getArgOperand(1))) {
Dan Gohman670f9372012-04-13 18:57:48 +00002498 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +00002499 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00002500 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2501 Constant::getNullValue(Ty),
2502 CI);
Michael Gottesmanfec61c02013-01-06 21:54:30 +00002503
2504 llvm::Value *NewValue = UndefValue::get(CI->getType());
2505 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: A null "
2506 "pointer-to-weak-pointer is undefined behavior.\n"
2507 " Old = " << *CI <<
2508 "\n New = " <<
2509 *NewValue << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00002510
Michael Gottesmanfec61c02013-01-06 21:54:30 +00002511 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +00002512 CI->eraseFromParent();
2513 continue;
2514 }
2515 break;
2516 }
2517 case IC_Retain:
2518 OptimizeRetainCall(F, Inst);
2519 break;
2520 case IC_RetainRV:
2521 if (OptimizeRetainRVCall(F, Inst))
2522 continue;
2523 break;
2524 case IC_AutoreleaseRV:
Michael Gottesman556ff612013-01-12 01:25:19 +00002525 OptimizeAutoreleaseRVCall(F, Inst, Class);
John McCalld935e9c2011-06-15 23:37:01 +00002526 break;
2527 }
2528
2529 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
2530 if (IsAutorelease(Class) && Inst->use_empty()) {
2531 CallInst *Call = cast<CallInst>(Inst);
2532 const Value *Arg = Call->getArgOperand(0);
2533 Arg = FindSingleUseIdentifiedObject(Arg);
2534 if (Arg) {
2535 Changed = true;
2536 ++NumAutoreleases;
2537
2538 // Create the declaration lazily.
2539 LLVMContext &C = Inst->getContext();
2540 CallInst *NewCall =
2541 CallInst::Create(getReleaseCallee(F.getParent()),
2542 Call->getArgOperand(0), "", Call);
2543 NewCall->setMetadata(ImpreciseReleaseMDKind,
2544 MDNode::get(C, ArrayRef<Value *>()));
Michael Gottesman10426b52013-01-07 21:26:07 +00002545
Michael Gottesmana6a1dad2013-01-06 22:56:50 +00002546 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Replacing "
2547 "objc_autorelease(x) with objc_release(x) since x is "
2548 "otherwise unused.\n"
Michael Gottesman4bf6e752013-01-06 22:56:54 +00002549 " Old: " << *Call <<
Michael Gottesmana6a1dad2013-01-06 22:56:50 +00002550 "\n New: " <<
2551 *NewCall << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00002552
John McCalld935e9c2011-06-15 23:37:01 +00002553 EraseInstruction(Call);
2554 Inst = NewCall;
2555 Class = IC_Release;
2556 }
2557 }
2558
2559 // For functions which can never be passed stack arguments, add
2560 // a tail keyword.
2561 if (IsAlwaysTail(Class)) {
2562 Changed = true;
Michael Gottesman2d763312013-01-06 23:39:09 +00002563 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Adding tail keyword"
2564 " to function since it can never be passed stack args: " << *Inst <<
2565 "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002566 cast<CallInst>(Inst)->setTailCall();
2567 }
2568
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00002569 // Ensure that functions that can never have a "tail" keyword due to the
2570 // semantics of ARC truly do not do so.
2571 if (IsNeverTail(Class)) {
2572 Changed = true;
Michael Gottesman4385edf2013-01-14 01:47:53 +00002573 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Removing tail "
2574 "keyword from function: " << *Inst <<
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00002575 "\n");
2576 cast<CallInst>(Inst)->setTailCall(false);
2577 }
2578
John McCalld935e9c2011-06-15 23:37:01 +00002579 // Set nounwind as needed.
2580 if (IsNoThrow(Class)) {
2581 Changed = true;
Michael Gottesman8800a512013-01-06 23:39:13 +00002582 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Found no throw"
2583 " class. Setting nounwind on: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002584 cast<CallInst>(Inst)->setDoesNotThrow();
2585 }
2586
2587 if (!IsNoopOnNull(Class)) {
2588 UsedInThisFunction |= 1 << Class;
2589 continue;
2590 }
2591
2592 const Value *Arg = GetObjCArg(Inst);
2593
2594 // ARC calls with null are no-ops. Delete them.
2595 if (isNullOrUndef(Arg)) {
2596 Changed = true;
2597 ++NumNoops;
Michael Gottesman5b970e12013-01-07 00:04:52 +00002598 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: ARC calls with "
2599 " null are no-ops. Erasing: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002600 EraseInstruction(Inst);
2601 continue;
2602 }
2603
2604 // Keep track of which of retain, release, autorelease, and retain_block
2605 // are actually present in this function.
2606 UsedInThisFunction |= 1 << Class;
2607
2608 // If Arg is a PHI, and one or more incoming values to the
2609 // PHI are null, and the call is control-equivalent to the PHI, and there
2610 // are no relevant side effects between the PHI and the call, the call
2611 // could be pushed up to just those paths with non-null incoming values.
2612 // For now, don't bother splitting critical edges for this.
2613 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
2614 Worklist.push_back(std::make_pair(Inst, Arg));
2615 do {
2616 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
2617 Inst = Pair.first;
2618 Arg = Pair.second;
2619
2620 const PHINode *PN = dyn_cast<PHINode>(Arg);
2621 if (!PN) continue;
2622
2623 // Determine if the PHI has any null operands, or any incoming
2624 // critical edges.
2625 bool HasNull = false;
2626 bool HasCriticalEdges = false;
2627 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2628 Value *Incoming =
2629 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2630 if (isNullOrUndef(Incoming))
2631 HasNull = true;
2632 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
2633 .getNumSuccessors() != 1) {
2634 HasCriticalEdges = true;
2635 break;
2636 }
2637 }
2638 // If we have null operands and no critical edges, optimize.
2639 if (!HasCriticalEdges && HasNull) {
2640 SmallPtrSet<Instruction *, 4> DependingInstructions;
2641 SmallPtrSet<const BasicBlock *, 4> Visited;
2642
2643 // Check that there is nothing that cares about the reference
2644 // count between the call and the phi.
Dan Gohman8478d762012-04-13 00:59:57 +00002645 switch (Class) {
2646 case IC_Retain:
2647 case IC_RetainBlock:
2648 // These can always be moved up.
2649 break;
2650 case IC_Release:
Dan Gohman41375a32012-05-08 23:39:44 +00002651 // These can't be moved across things that care about the retain
2652 // count.
Dan Gohman8478d762012-04-13 00:59:57 +00002653 FindDependencies(NeedsPositiveRetainCount, Arg,
2654 Inst->getParent(), Inst,
2655 DependingInstructions, Visited, PA);
2656 break;
2657 case IC_Autorelease:
2658 // These can't be moved across autorelease pool scope boundaries.
2659 FindDependencies(AutoreleasePoolBoundary, Arg,
2660 Inst->getParent(), Inst,
2661 DependingInstructions, Visited, PA);
2662 break;
2663 case IC_RetainRV:
2664 case IC_AutoreleaseRV:
2665 // Don't move these; the RV optimization depends on the autoreleaseRV
2666 // being tail called, and the retainRV being immediately after a call
2667 // (which might still happen if we get lucky with codegen layout, but
2668 // it's not worth taking the chance).
2669 continue;
2670 default:
2671 llvm_unreachable("Invalid dependence flavor");
2672 }
2673
John McCalld935e9c2011-06-15 23:37:01 +00002674 if (DependingInstructions.size() == 1 &&
2675 *DependingInstructions.begin() == PN) {
2676 Changed = true;
2677 ++NumPartialNoops;
2678 // Clone the call into each predecessor that has a non-null value.
2679 CallInst *CInst = cast<CallInst>(Inst);
Chris Lattner229907c2011-07-18 04:54:35 +00002680 Type *ParamTy = CInst->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00002681 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2682 Value *Incoming =
2683 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2684 if (!isNullOrUndef(Incoming)) {
2685 CallInst *Clone = cast<CallInst>(CInst->clone());
2686 Value *Op = PN->getIncomingValue(i);
2687 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
2688 if (Op->getType() != ParamTy)
2689 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
2690 Clone->setArgOperand(0, Op);
2691 Clone->insertBefore(InsertPos);
Michael Gottesmanc189a392013-01-09 19:23:24 +00002692
2693 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Cloning "
2694 << *CInst << "\n"
2695 " And inserting "
2696 "clone at " << *InsertPos << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002697 Worklist.push_back(std::make_pair(Clone, Incoming));
2698 }
2699 }
2700 // Erase the original call.
Michael Gottesmanc189a392013-01-09 19:23:24 +00002701 DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002702 EraseInstruction(CInst);
2703 continue;
2704 }
2705 }
2706 } while (!Worklist.empty());
2707 }
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00002708 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Finished List.\n");
John McCalld935e9c2011-06-15 23:37:01 +00002709}
2710
Michael Gottesman97e3df02013-01-14 00:35:14 +00002711/// Check for critical edges, loop boundaries, irreducible control flow, or
2712/// other CFG structures where moving code across the edge would result in it
2713/// being executed more.
John McCalld935e9c2011-06-15 23:37:01 +00002714void
2715ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
2716 DenseMap<const BasicBlock *, BBState> &BBStates,
2717 BBState &MyStates) const {
2718 // If any top-down local-use or possible-dec has a succ which is earlier in
2719 // the sequence, forget it.
Dan Gohman55b06742012-03-02 01:13:53 +00002720 for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
John McCalld935e9c2011-06-15 23:37:01 +00002721 E = MyStates.top_down_ptr_end(); I != E; ++I)
2722 switch (I->second.GetSeq()) {
2723 default: break;
2724 case S_Use: {
2725 const Value *Arg = I->first;
2726 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2727 bool SomeSuccHasSame = false;
2728 bool AllSuccsHaveSame = true;
Dan Gohman55b06742012-03-02 01:13:53 +00002729 PtrState &S = I->second;
Dan Gohman0155f302012-02-17 18:59:53 +00002730 succ_const_iterator SI(TI), SE(TI, false);
2731
Dan Gohman0155f302012-02-17 18:59:53 +00002732 for (; SI != SE; ++SI) {
Dan Gohman362eb692012-03-02 01:26:46 +00002733 Sequence SuccSSeq = S_None;
2734 bool SuccSRRIKnownSafe = false;
Dan Gohman41375a32012-05-08 23:39:44 +00002735 // If VisitBottomUp has pointer information for this successor, take
2736 // what we know about it.
Dan Gohmandae33492012-04-27 18:56:31 +00002737 DenseMap<const BasicBlock *, BBState>::iterator BBI =
2738 BBStates.find(*SI);
2739 assert(BBI != BBStates.end());
2740 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2741 SuccSSeq = SuccS.GetSeq();
2742 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
Dan Gohman362eb692012-03-02 01:26:46 +00002743 switch (SuccSSeq) {
John McCalld935e9c2011-06-15 23:37:01 +00002744 case S_None:
Dan Gohman12130272011-08-12 00:26:31 +00002745 case S_CanRelease: {
Dan Gohman362eb692012-03-02 01:26:46 +00002746 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
Dan Gohman12130272011-08-12 00:26:31 +00002747 S.ClearSequenceProgress();
Dan Gohman362eb692012-03-02 01:26:46 +00002748 break;
2749 }
Dan Gohman12130272011-08-12 00:26:31 +00002750 continue;
2751 }
John McCalld935e9c2011-06-15 23:37:01 +00002752 case S_Use:
2753 SomeSuccHasSame = true;
2754 break;
2755 case S_Stop:
2756 case S_Release:
2757 case S_MovableRelease:
Dan Gohman362eb692012-03-02 01:26:46 +00002758 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
Dan Gohman12130272011-08-12 00:26:31 +00002759 AllSuccsHaveSame = false;
John McCalld935e9c2011-06-15 23:37:01 +00002760 break;
2761 case S_Retain:
2762 llvm_unreachable("bottom-up pointer in retain state!");
2763 }
Dan Gohman12130272011-08-12 00:26:31 +00002764 }
John McCalld935e9c2011-06-15 23:37:01 +00002765 // If the state at the other end of any of the successor edges
2766 // matches the current state, require all edges to match. This
2767 // guards against loops in the middle of a sequence.
2768 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohman12130272011-08-12 00:26:31 +00002769 S.ClearSequenceProgress();
Dan Gohman044437062011-12-12 18:13:53 +00002770 break;
John McCalld935e9c2011-06-15 23:37:01 +00002771 }
2772 case S_CanRelease: {
2773 const Value *Arg = I->first;
2774 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2775 bool SomeSuccHasSame = false;
2776 bool AllSuccsHaveSame = true;
Dan Gohman55b06742012-03-02 01:13:53 +00002777 PtrState &S = I->second;
Dan Gohman0155f302012-02-17 18:59:53 +00002778 succ_const_iterator SI(TI), SE(TI, false);
2779
Dan Gohman0155f302012-02-17 18:59:53 +00002780 for (; SI != SE; ++SI) {
Dan Gohman362eb692012-03-02 01:26:46 +00002781 Sequence SuccSSeq = S_None;
2782 bool SuccSRRIKnownSafe = false;
Dan Gohman41375a32012-05-08 23:39:44 +00002783 // If VisitBottomUp has pointer information for this successor, take
2784 // what we know about it.
Dan Gohmandae33492012-04-27 18:56:31 +00002785 DenseMap<const BasicBlock *, BBState>::iterator BBI =
2786 BBStates.find(*SI);
2787 assert(BBI != BBStates.end());
2788 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2789 SuccSSeq = SuccS.GetSeq();
2790 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
Dan Gohman362eb692012-03-02 01:26:46 +00002791 switch (SuccSSeq) {
Dan Gohman12130272011-08-12 00:26:31 +00002792 case S_None: {
Dan Gohman362eb692012-03-02 01:26:46 +00002793 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
Dan Gohman12130272011-08-12 00:26:31 +00002794 S.ClearSequenceProgress();
Dan Gohman362eb692012-03-02 01:26:46 +00002795 break;
2796 }
Dan Gohman12130272011-08-12 00:26:31 +00002797 continue;
2798 }
John McCalld935e9c2011-06-15 23:37:01 +00002799 case S_CanRelease:
2800 SomeSuccHasSame = true;
2801 break;
2802 case S_Stop:
2803 case S_Release:
2804 case S_MovableRelease:
2805 case S_Use:
Dan Gohman362eb692012-03-02 01:26:46 +00002806 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
Dan Gohman12130272011-08-12 00:26:31 +00002807 AllSuccsHaveSame = false;
John McCalld935e9c2011-06-15 23:37:01 +00002808 break;
2809 case S_Retain:
2810 llvm_unreachable("bottom-up pointer in retain state!");
2811 }
Dan Gohman12130272011-08-12 00:26:31 +00002812 }
John McCalld935e9c2011-06-15 23:37:01 +00002813 // If the state at the other end of any of the successor edges
2814 // matches the current state, require all edges to match. This
2815 // guards against loops in the middle of a sequence.
2816 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohman12130272011-08-12 00:26:31 +00002817 S.ClearSequenceProgress();
Dan Gohman044437062011-12-12 18:13:53 +00002818 break;
John McCalld935e9c2011-06-15 23:37:01 +00002819 }
2820 }
2821}
2822
2823bool
Dan Gohman817a7c62012-03-22 18:24:56 +00002824ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
Dan Gohman5c70fad2012-03-23 17:47:54 +00002825 BasicBlock *BB,
Dan Gohman817a7c62012-03-22 18:24:56 +00002826 MapVector<Value *, RRInfo> &Retains,
2827 BBState &MyStates) {
2828 bool NestingDetected = false;
2829 InstructionClass Class = GetInstructionClass(Inst);
2830 const Value *Arg = 0;
2831
2832 switch (Class) {
2833 case IC_Release: {
2834 Arg = GetObjCArg(Inst);
2835
2836 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2837
2838 // If we see two releases in a row on the same pointer. If so, make
2839 // a note, and we'll cicle back to revisit it after we've
2840 // hopefully eliminated the second release, which may allow us to
2841 // eliminate the first release too.
2842 // Theoretically we could implement removal of nested retain+release
2843 // pairs by making PtrState hold a stack of states, but this is
2844 // simple and avoids adding overhead for the non-nested case.
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00002845 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease) {
2846 DEBUG(dbgs() << "ObjCARCOpt::VisitInstructionBottomUp: Found nested "
2847 "releases (i.e. a release pair)\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00002848 NestingDetected = true;
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00002849 }
Dan Gohman817a7c62012-03-22 18:24:56 +00002850
Dan Gohman817a7c62012-03-22 18:24:56 +00002851 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
Dan Gohman62079b42012-04-25 00:50:46 +00002852 S.ResetSequenceProgress(ReleaseMetadata ? S_MovableRelease : S_Release);
Dan Gohman817a7c62012-03-22 18:24:56 +00002853 S.RRI.ReleaseMetadata = ReleaseMetadata;
Dan Gohmandf476e52012-09-04 23:16:20 +00002854 S.RRI.KnownSafe = S.IsKnownIncremented();
Dan Gohman817a7c62012-03-22 18:24:56 +00002855 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2856 S.RRI.Calls.insert(Inst);
2857
Dan Gohmandf476e52012-09-04 23:16:20 +00002858 S.SetKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00002859 break;
2860 }
2861 case IC_RetainBlock:
2862 // An objc_retainBlock call with just a use may need to be kept,
2863 // because it may be copying a block from the stack to the heap.
2864 if (!IsRetainBlockOptimizable(Inst))
2865 break;
2866 // FALLTHROUGH
2867 case IC_Retain:
2868 case IC_RetainRV: {
2869 Arg = GetObjCArg(Inst);
2870
2871 PtrState &S = MyStates.getPtrBottomUpState(Arg);
Dan Gohman62079b42012-04-25 00:50:46 +00002872 S.SetKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00002873
2874 switch (S.GetSeq()) {
2875 case S_Stop:
2876 case S_Release:
2877 case S_MovableRelease:
2878 case S_Use:
2879 S.RRI.ReverseInsertPts.clear();
2880 // FALL THROUGH
2881 case S_CanRelease:
2882 // Don't do retain+release tracking for IC_RetainRV, because it's
2883 // better to let it remain as the first instruction after a call.
2884 if (Class != IC_RetainRV) {
2885 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2886 Retains[Inst] = S.RRI;
2887 }
2888 S.ClearSequenceProgress();
2889 break;
2890 case S_None:
2891 break;
2892 case S_Retain:
2893 llvm_unreachable("bottom-up pointer in retain state!");
2894 }
2895 return NestingDetected;
2896 }
2897 case IC_AutoreleasepoolPop:
2898 // Conservatively, clear MyStates for all known pointers.
2899 MyStates.clearBottomUpPointers();
2900 return NestingDetected;
2901 case IC_AutoreleasepoolPush:
2902 case IC_None:
2903 // These are irrelevant.
2904 return NestingDetected;
2905 default:
2906 break;
2907 }
2908
2909 // Consider any other possible effects of this instruction on each
2910 // pointer being tracked.
2911 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
2912 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
2913 const Value *Ptr = MI->first;
2914 if (Ptr == Arg)
2915 continue; // Handled above.
2916 PtrState &S = MI->second;
2917 Sequence Seq = S.GetSeq();
2918
2919 // Check for possible releases.
2920 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Dan Gohman62079b42012-04-25 00:50:46 +00002921 S.ClearRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00002922 switch (Seq) {
2923 case S_Use:
2924 S.SetSeq(S_CanRelease);
2925 continue;
2926 case S_CanRelease:
2927 case S_Release:
2928 case S_MovableRelease:
2929 case S_Stop:
2930 case S_None:
2931 break;
2932 case S_Retain:
2933 llvm_unreachable("bottom-up pointer in retain state!");
2934 }
2935 }
2936
2937 // Check for possible direct uses.
2938 switch (Seq) {
2939 case S_Release:
2940 case S_MovableRelease:
2941 if (CanUse(Inst, Ptr, PA, Class)) {
2942 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohman5c70fad2012-03-23 17:47:54 +00002943 // If this is an invoke instruction, we're scanning it as part of
2944 // one of its successor blocks, since we can't insert code after it
2945 // in its own block, and we don't want to split critical edges.
2946 if (isa<InvokeInst>(Inst))
2947 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2948 else
Francois Pichet4b9ab742012-03-24 01:36:37 +00002949 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohman817a7c62012-03-22 18:24:56 +00002950 S.SetSeq(S_Use);
2951 } else if (Seq == S_Release &&
2952 (Class == IC_User || Class == IC_CallOrUser)) {
2953 // Non-movable releases depend on any possible objc pointer use.
2954 S.SetSeq(S_Stop);
2955 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohman5c70fad2012-03-23 17:47:54 +00002956 // As above; handle invoke specially.
2957 if (isa<InvokeInst>(Inst))
2958 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2959 else
Francois Pichet4b9ab742012-03-24 01:36:37 +00002960 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohman817a7c62012-03-22 18:24:56 +00002961 }
2962 break;
2963 case S_Stop:
2964 if (CanUse(Inst, Ptr, PA, Class))
2965 S.SetSeq(S_Use);
2966 break;
2967 case S_CanRelease:
2968 case S_Use:
2969 case S_None:
2970 break;
2971 case S_Retain:
2972 llvm_unreachable("bottom-up pointer in retain state!");
2973 }
2974 }
2975
2976 return NestingDetected;
2977}
2978
2979bool
John McCalld935e9c2011-06-15 23:37:01 +00002980ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2981 DenseMap<const BasicBlock *, BBState> &BBStates,
2982 MapVector<Value *, RRInfo> &Retains) {
2983 bool NestingDetected = false;
2984 BBState &MyStates = BBStates[BB];
2985
2986 // Merge the states from each successor to compute the initial state
2987 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00002988 BBState::edge_iterator SI(MyStates.succ_begin()),
2989 SE(MyStates.succ_end());
2990 if (SI != SE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002991 const BasicBlock *Succ = *SI;
2992 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
2993 assert(I != BBStates.end());
2994 MyStates.InitFromSucc(I->second);
2995 ++SI;
2996 for (; SI != SE; ++SI) {
2997 Succ = *SI;
2998 I = BBStates.find(Succ);
2999 assert(I != BBStates.end());
3000 MyStates.MergeSucc(I->second);
3001 }
Dan Gohman0155f302012-02-17 18:59:53 +00003002 }
John McCalld935e9c2011-06-15 23:37:01 +00003003
3004 // Visit all the instructions, bottom-up.
3005 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
3006 Instruction *Inst = llvm::prior(I);
Dan Gohman5c70fad2012-03-23 17:47:54 +00003007
3008 // Invoke instructions are visited as part of their successors (below).
3009 if (isa<InvokeInst>(Inst))
3010 continue;
3011
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00003012 DEBUG(dbgs() << "ObjCARCOpt::VisitButtonUp: Visiting " << *Inst << "\n");
3013
Dan Gohman5c70fad2012-03-23 17:47:54 +00003014 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
3015 }
3016
Dan Gohmandae33492012-04-27 18:56:31 +00003017 // If there's a predecessor with an invoke, visit the invoke as if it were
3018 // part of this block, since we can't insert code after an invoke in its own
3019 // block, and we don't want to split critical edges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003020 for (BBState::edge_iterator PI(MyStates.pred_begin()),
3021 PE(MyStates.pred_end()); PI != PE; ++PI) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00003022 BasicBlock *Pred = *PI;
Dan Gohmandae33492012-04-27 18:56:31 +00003023 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
3024 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
Dan Gohman817a7c62012-03-22 18:24:56 +00003025 }
John McCalld935e9c2011-06-15 23:37:01 +00003026
Dan Gohman817a7c62012-03-22 18:24:56 +00003027 return NestingDetected;
3028}
John McCalld935e9c2011-06-15 23:37:01 +00003029
Dan Gohman817a7c62012-03-22 18:24:56 +00003030bool
3031ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
3032 DenseMap<Value *, RRInfo> &Releases,
3033 BBState &MyStates) {
3034 bool NestingDetected = false;
3035 InstructionClass Class = GetInstructionClass(Inst);
3036 const Value *Arg = 0;
John McCalld935e9c2011-06-15 23:37:01 +00003037
Dan Gohman817a7c62012-03-22 18:24:56 +00003038 switch (Class) {
3039 case IC_RetainBlock:
3040 // An objc_retainBlock call with just a use may need to be kept,
3041 // because it may be copying a block from the stack to the heap.
3042 if (!IsRetainBlockOptimizable(Inst))
3043 break;
3044 // FALLTHROUGH
3045 case IC_Retain:
3046 case IC_RetainRV: {
3047 Arg = GetObjCArg(Inst);
3048
3049 PtrState &S = MyStates.getPtrTopDownState(Arg);
3050
3051 // Don't do retain+release tracking for IC_RetainRV, because it's
3052 // better to let it remain as the first instruction after a call.
3053 if (Class != IC_RetainRV) {
3054 // If we see two retains in a row on the same pointer. If so, make
John McCalld935e9c2011-06-15 23:37:01 +00003055 // a note, and we'll cicle back to revisit it after we've
Dan Gohman817a7c62012-03-22 18:24:56 +00003056 // hopefully eliminated the second retain, which may allow us to
3057 // eliminate the first retain too.
John McCalld935e9c2011-06-15 23:37:01 +00003058 // Theoretically we could implement removal of nested retain+release
3059 // pairs by making PtrState hold a stack of states, but this is
3060 // simple and avoids adding overhead for the non-nested case.
Dan Gohman817a7c62012-03-22 18:24:56 +00003061 if (S.GetSeq() == S_Retain)
John McCalld935e9c2011-06-15 23:37:01 +00003062 NestingDetected = true;
3063
Dan Gohman62079b42012-04-25 00:50:46 +00003064 S.ResetSequenceProgress(S_Retain);
Dan Gohman817a7c62012-03-22 18:24:56 +00003065 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
Dan Gohmandf476e52012-09-04 23:16:20 +00003066 S.RRI.KnownSafe = S.IsKnownIncremented();
John McCalld935e9c2011-06-15 23:37:01 +00003067 S.RRI.Calls.insert(Inst);
John McCalld935e9c2011-06-15 23:37:01 +00003068 }
John McCalld935e9c2011-06-15 23:37:01 +00003069
Dan Gohmandf476e52012-09-04 23:16:20 +00003070 S.SetKnownPositiveRefCount();
Dan Gohmanf64ff8e2012-07-23 19:27:31 +00003071
3072 // A retain can be a potential use; procede to the generic checking
3073 // code below.
3074 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00003075 }
3076 case IC_Release: {
3077 Arg = GetObjCArg(Inst);
3078
3079 PtrState &S = MyStates.getPtrTopDownState(Arg);
Dan Gohmandf476e52012-09-04 23:16:20 +00003080 S.ClearRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00003081
3082 switch (S.GetSeq()) {
3083 case S_Retain:
3084 case S_CanRelease:
3085 S.RRI.ReverseInsertPts.clear();
3086 // FALL THROUGH
3087 case S_Use:
3088 S.RRI.ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
3089 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
3090 Releases[Inst] = S.RRI;
3091 S.ClearSequenceProgress();
3092 break;
3093 case S_None:
3094 break;
3095 case S_Stop:
3096 case S_Release:
3097 case S_MovableRelease:
3098 llvm_unreachable("top-down pointer in release state!");
3099 }
3100 break;
3101 }
3102 case IC_AutoreleasepoolPop:
3103 // Conservatively, clear MyStates for all known pointers.
3104 MyStates.clearTopDownPointers();
3105 return NestingDetected;
3106 case IC_AutoreleasepoolPush:
3107 case IC_None:
3108 // These are irrelevant.
3109 return NestingDetected;
3110 default:
3111 break;
3112 }
3113
3114 // Consider any other possible effects of this instruction on each
3115 // pointer being tracked.
3116 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
3117 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
3118 const Value *Ptr = MI->first;
3119 if (Ptr == Arg)
3120 continue; // Handled above.
3121 PtrState &S = MI->second;
3122 Sequence Seq = S.GetSeq();
3123
3124 // Check for possible releases.
3125 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Dan Gohman62079b42012-04-25 00:50:46 +00003126 S.ClearRefCount();
John McCalld935e9c2011-06-15 23:37:01 +00003127 switch (Seq) {
Dan Gohman817a7c62012-03-22 18:24:56 +00003128 case S_Retain:
3129 S.SetSeq(S_CanRelease);
3130 assert(S.RRI.ReverseInsertPts.empty());
3131 S.RRI.ReverseInsertPts.insert(Inst);
3132
3133 // One call can't cause a transition from S_Retain to S_CanRelease
3134 // and S_CanRelease to S_Use. If we've made the first transition,
3135 // we're done.
3136 continue;
John McCalld935e9c2011-06-15 23:37:01 +00003137 case S_Use:
Dan Gohman817a7c62012-03-22 18:24:56 +00003138 case S_CanRelease:
John McCalld935e9c2011-06-15 23:37:01 +00003139 case S_None:
3140 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00003141 case S_Stop:
3142 case S_Release:
3143 case S_MovableRelease:
3144 llvm_unreachable("top-down pointer in release state!");
John McCalld935e9c2011-06-15 23:37:01 +00003145 }
3146 }
Dan Gohman817a7c62012-03-22 18:24:56 +00003147
3148 // Check for possible direct uses.
3149 switch (Seq) {
3150 case S_CanRelease:
3151 if (CanUse(Inst, Ptr, PA, Class))
3152 S.SetSeq(S_Use);
3153 break;
3154 case S_Retain:
3155 case S_Use:
3156 case S_None:
3157 break;
3158 case S_Stop:
3159 case S_Release:
3160 case S_MovableRelease:
3161 llvm_unreachable("top-down pointer in release state!");
3162 }
John McCalld935e9c2011-06-15 23:37:01 +00003163 }
3164
3165 return NestingDetected;
3166}
3167
3168bool
3169ObjCARCOpt::VisitTopDown(BasicBlock *BB,
3170 DenseMap<const BasicBlock *, BBState> &BBStates,
3171 DenseMap<Value *, RRInfo> &Releases) {
3172 bool NestingDetected = false;
3173 BBState &MyStates = BBStates[BB];
3174
3175 // Merge the states from each predecessor to compute the initial state
3176 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00003177 BBState::edge_iterator PI(MyStates.pred_begin()),
3178 PE(MyStates.pred_end());
3179 if (PI != PE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003180 const BasicBlock *Pred = *PI;
3181 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
3182 assert(I != BBStates.end());
3183 MyStates.InitFromPred(I->second);
3184 ++PI;
3185 for (; PI != PE; ++PI) {
3186 Pred = *PI;
3187 I = BBStates.find(Pred);
3188 assert(I != BBStates.end());
3189 MyStates.MergePred(I->second);
3190 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003191 }
John McCalld935e9c2011-06-15 23:37:01 +00003192
3193 // Visit all the instructions, top-down.
3194 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3195 Instruction *Inst = I;
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00003196
3197 DEBUG(dbgs() << "ObjCARCOpt::VisitTopDown: Visiting " << *Inst << "\n");
3198
Dan Gohman817a7c62012-03-22 18:24:56 +00003199 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00003200 }
3201
3202 CheckForCFGHazards(BB, BBStates, MyStates);
3203 return NestingDetected;
3204}
3205
Dan Gohmana53a12c2011-12-12 19:42:25 +00003206static void
3207ComputePostOrders(Function &F,
3208 SmallVectorImpl<BasicBlock *> &PostOrder,
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003209 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
3210 unsigned NoObjCARCExceptionsMDKind,
3211 DenseMap<const BasicBlock *, BBState> &BBStates) {
Michael Gottesman97e3df02013-01-14 00:35:14 +00003212 /// The visited set, for doing DFS walks.
Dan Gohmana53a12c2011-12-12 19:42:25 +00003213 SmallPtrSet<BasicBlock *, 16> Visited;
3214
3215 // Do DFS, computing the PostOrder.
3216 SmallPtrSet<BasicBlock *, 16> OnStack;
3217 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003218
3219 // Functions always have exactly one entry block, and we don't have
3220 // any other block that we treat like an entry block.
Dan Gohmana53a12c2011-12-12 19:42:25 +00003221 BasicBlock *EntryBB = &F.getEntryBlock();
Dan Gohman41375a32012-05-08 23:39:44 +00003222 BBState &MyStates = BBStates[EntryBB];
3223 MyStates.SetAsEntry();
3224 TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
3225 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
Dan Gohmana53a12c2011-12-12 19:42:25 +00003226 Visited.insert(EntryBB);
3227 OnStack.insert(EntryBB);
3228 do {
3229 dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003230 BasicBlock *CurrBB = SuccStack.back().first;
3231 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
3232 succ_iterator SE(TI, false);
Dan Gohman41375a32012-05-08 23:39:44 +00003233
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003234 while (SuccStack.back().second != SE) {
3235 BasicBlock *SuccBB = *SuccStack.back().second++;
3236 if (Visited.insert(SuccBB)) {
Dan Gohman41375a32012-05-08 23:39:44 +00003237 TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
3238 SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003239 BBStates[CurrBB].addSucc(SuccBB);
Dan Gohman41375a32012-05-08 23:39:44 +00003240 BBState &SuccStates = BBStates[SuccBB];
3241 SuccStates.addPred(CurrBB);
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003242 OnStack.insert(SuccBB);
Dan Gohmana53a12c2011-12-12 19:42:25 +00003243 goto dfs_next_succ;
3244 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003245
3246 if (!OnStack.count(SuccBB)) {
3247 BBStates[CurrBB].addSucc(SuccBB);
3248 BBStates[SuccBB].addPred(CurrBB);
3249 }
Dan Gohmana53a12c2011-12-12 19:42:25 +00003250 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003251 OnStack.erase(CurrBB);
3252 PostOrder.push_back(CurrBB);
3253 SuccStack.pop_back();
Dan Gohmana53a12c2011-12-12 19:42:25 +00003254 } while (!SuccStack.empty());
3255
3256 Visited.clear();
3257
Dan Gohmana53a12c2011-12-12 19:42:25 +00003258 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003259 // Functions may have many exits, and there also blocks which we treat
3260 // as exits due to ignored edges.
3261 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
3262 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
3263 BasicBlock *ExitBB = I;
3264 BBState &MyStates = BBStates[ExitBB];
3265 if (!MyStates.isExit())
3266 continue;
3267
Dan Gohmandae33492012-04-27 18:56:31 +00003268 MyStates.SetAsExit();
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003269
3270 PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00003271 Visited.insert(ExitBB);
3272 while (!PredStack.empty()) {
3273 reverse_dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003274 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
3275 while (PredStack.back().second != PE) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00003276 BasicBlock *BB = *PredStack.back().second++;
Dan Gohmana53a12c2011-12-12 19:42:25 +00003277 if (Visited.insert(BB)) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003278 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00003279 goto reverse_dfs_next_succ;
3280 }
3281 }
3282 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
3283 }
3284 }
3285}
3286
Michael Gottesman97e3df02013-01-14 00:35:14 +00003287// Visit the function both top-down and bottom-up.
John McCalld935e9c2011-06-15 23:37:01 +00003288bool
3289ObjCARCOpt::Visit(Function &F,
3290 DenseMap<const BasicBlock *, BBState> &BBStates,
3291 MapVector<Value *, RRInfo> &Retains,
3292 DenseMap<Value *, RRInfo> &Releases) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00003293
3294 // Use reverse-postorder traversals, because we magically know that loops
3295 // will be well behaved, i.e. they won't repeatedly call retain on a single
3296 // pointer without doing a release. We can't use the ReversePostOrderTraversal
3297 // class here because we want the reverse-CFG postorder to consider each
3298 // function exit point, and we want to ignore selected cycle edges.
3299 SmallVector<BasicBlock *, 16> PostOrder;
3300 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003301 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
3302 NoObjCARCExceptionsMDKind,
3303 BBStates);
Dan Gohmana53a12c2011-12-12 19:42:25 +00003304
3305 // Use reverse-postorder on the reverse CFG for bottom-up.
John McCalld935e9c2011-06-15 23:37:01 +00003306 bool BottomUpNestingDetected = false;
Dan Gohmanc57b58c2011-08-18 21:27:42 +00003307 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
Dan Gohmana53a12c2011-12-12 19:42:25 +00003308 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
3309 I != E; ++I)
3310 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
John McCalld935e9c2011-06-15 23:37:01 +00003311
Dan Gohmana53a12c2011-12-12 19:42:25 +00003312 // Use reverse-postorder for top-down.
John McCalld935e9c2011-06-15 23:37:01 +00003313 bool TopDownNestingDetected = false;
Dan Gohmana53a12c2011-12-12 19:42:25 +00003314 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
3315 PostOrder.rbegin(), E = PostOrder.rend();
3316 I != E; ++I)
3317 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
John McCalld935e9c2011-06-15 23:37:01 +00003318
3319 return TopDownNestingDetected && BottomUpNestingDetected;
3320}
3321
Michael Gottesman97e3df02013-01-14 00:35:14 +00003322/// Move the calls in RetainsToMove and ReleasesToMove.
John McCalld935e9c2011-06-15 23:37:01 +00003323void ObjCARCOpt::MoveCalls(Value *Arg,
3324 RRInfo &RetainsToMove,
3325 RRInfo &ReleasesToMove,
3326 MapVector<Value *, RRInfo> &Retains,
3327 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman6320f522011-07-22 22:29:21 +00003328 SmallVectorImpl<Instruction *> &DeadInsts,
3329 Module *M) {
Chris Lattner229907c2011-07-18 04:54:35 +00003330 Type *ArgTy = Arg->getType();
Dan Gohman6320f522011-07-22 22:29:21 +00003331 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
John McCalld935e9c2011-06-15 23:37:01 +00003332
3333 // Insert the new retain and release calls.
3334 for (SmallPtrSet<Instruction *, 2>::const_iterator
3335 PI = ReleasesToMove.ReverseInsertPts.begin(),
3336 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
3337 Instruction *InsertPt = *PI;
3338 Value *MyArg = ArgTy == ParamTy ? Arg :
3339 new BitCastInst(Arg, ParamTy, "", InsertPt);
3340 CallInst *Call =
3341 CallInst::Create(RetainsToMove.IsRetainBlock ?
Dan Gohman6320f522011-07-22 22:29:21 +00003342 getRetainBlockCallee(M) : getRetainCallee(M),
John McCalld935e9c2011-06-15 23:37:01 +00003343 MyArg, "", InsertPt);
3344 Call->setDoesNotThrow();
Dan Gohman728db492012-01-13 00:39:07 +00003345 if (RetainsToMove.IsRetainBlock)
Dan Gohmana7107f92011-10-17 22:53:25 +00003346 Call->setMetadata(CopyOnEscapeMDKind,
3347 MDNode::get(M->getContext(), ArrayRef<Value *>()));
Dan Gohman728db492012-01-13 00:39:07 +00003348 else
John McCalld935e9c2011-06-15 23:37:01 +00003349 Call->setTailCall();
Michael Gottesmanc189a392013-01-09 19:23:24 +00003350
3351 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Inserting new Release: " << *Call
3352 << "\n"
3353 " At insertion point: " << *InsertPt
3354 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00003355 }
3356 for (SmallPtrSet<Instruction *, 2>::const_iterator
3357 PI = RetainsToMove.ReverseInsertPts.begin(),
3358 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00003359 Instruction *InsertPt = *PI;
3360 Value *MyArg = ArgTy == ParamTy ? Arg :
3361 new BitCastInst(Arg, ParamTy, "", InsertPt);
3362 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
3363 "", InsertPt);
3364 // Attach a clang.imprecise_release metadata tag, if appropriate.
3365 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
3366 Call->setMetadata(ImpreciseReleaseMDKind, M);
3367 Call->setDoesNotThrow();
3368 if (ReleasesToMove.IsTailCallRelease)
3369 Call->setTailCall();
Michael Gottesmanc189a392013-01-09 19:23:24 +00003370
3371 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Inserting new Retain: " << *Call
3372 << "\n"
3373 " At insertion point: " << *InsertPt
3374 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00003375 }
3376
3377 // Delete the original retain and release calls.
3378 for (SmallPtrSet<Instruction *, 2>::const_iterator
3379 AI = RetainsToMove.Calls.begin(),
3380 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
3381 Instruction *OrigRetain = *AI;
3382 Retains.blot(OrigRetain);
3383 DeadInsts.push_back(OrigRetain);
Michael Gottesmanc189a392013-01-09 19:23:24 +00003384 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Deleting retain: " << *OrigRetain <<
3385 "\n");
John McCalld935e9c2011-06-15 23:37:01 +00003386 }
3387 for (SmallPtrSet<Instruction *, 2>::const_iterator
3388 AI = ReleasesToMove.Calls.begin(),
3389 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
3390 Instruction *OrigRelease = *AI;
3391 Releases.erase(OrigRelease);
3392 DeadInsts.push_back(OrigRelease);
Michael Gottesmanc189a392013-01-09 19:23:24 +00003393 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Deleting release: " << *OrigRelease
3394 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00003395 }
3396}
3397
Michael Gottesman97e3df02013-01-14 00:35:14 +00003398/// Identify pairings between the retains and releases, and delete and/or move
3399/// them.
John McCalld935e9c2011-06-15 23:37:01 +00003400bool
3401ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
3402 &BBStates,
3403 MapVector<Value *, RRInfo> &Retains,
Dan Gohman6320f522011-07-22 22:29:21 +00003404 DenseMap<Value *, RRInfo> &Releases,
3405 Module *M) {
John McCalld935e9c2011-06-15 23:37:01 +00003406 bool AnyPairsCompletelyEliminated = false;
3407 RRInfo RetainsToMove;
3408 RRInfo ReleasesToMove;
3409 SmallVector<Instruction *, 4> NewRetains;
3410 SmallVector<Instruction *, 4> NewReleases;
3411 SmallVector<Instruction *, 8> DeadInsts;
3412
Dan Gohman670f9372012-04-13 18:57:48 +00003413 // Visit each retain.
John McCalld935e9c2011-06-15 23:37:01 +00003414 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
Dan Gohman2053a5d2011-09-29 22:25:23 +00003415 E = Retains.end(); I != E; ++I) {
3416 Value *V = I->first;
John McCalld935e9c2011-06-15 23:37:01 +00003417 if (!V) continue; // blotted
3418
3419 Instruction *Retain = cast<Instruction>(V);
Michael Gottesmanc189a392013-01-09 19:23:24 +00003420
3421 DEBUG(dbgs() << "ObjCARCOpt::PerformCodePlacement: Visiting: " << *Retain
3422 << "\n");
3423
John McCalld935e9c2011-06-15 23:37:01 +00003424 Value *Arg = GetObjCArg(Retain);
3425
Dan Gohman728db492012-01-13 00:39:07 +00003426 // If the object being released is in static or stack storage, we know it's
John McCalld935e9c2011-06-15 23:37:01 +00003427 // not being managed by ObjC reference counting, so we can delete pairs
3428 // regardless of what possible decrements or uses lie between them.
Dan Gohman728db492012-01-13 00:39:07 +00003429 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
Dan Gohman41375a32012-05-08 23:39:44 +00003430
Dan Gohman56e1cef2011-08-22 17:29:11 +00003431 // A constant pointer can't be pointing to an object on the heap. It may
3432 // be reference-counted, but it won't be deleted.
3433 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
3434 if (const GlobalVariable *GV =
3435 dyn_cast<GlobalVariable>(
3436 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
3437 if (GV->isConstant())
3438 KnownSafe = true;
3439
John McCalld935e9c2011-06-15 23:37:01 +00003440 // If a pair happens in a region where it is known that the reference count
3441 // is already incremented, we can similarly ignore possible decrements.
Dan Gohmanb3894012011-08-19 00:26:36 +00003442 bool KnownSafeTD = true, KnownSafeBU = true;
John McCalld935e9c2011-06-15 23:37:01 +00003443
3444 // Connect the dots between the top-down-collected RetainsToMove and
3445 // bottom-up-collected ReleasesToMove to form sets of related calls.
3446 // This is an iterative process so that we connect multiple releases
3447 // to multiple retains if needed.
3448 unsigned OldDelta = 0;
3449 unsigned NewDelta = 0;
3450 unsigned OldCount = 0;
3451 unsigned NewCount = 0;
3452 bool FirstRelease = true;
3453 bool FirstRetain = true;
3454 NewRetains.push_back(Retain);
3455 for (;;) {
3456 for (SmallVectorImpl<Instruction *>::const_iterator
3457 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
3458 Instruction *NewRetain = *NI;
3459 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
3460 assert(It != Retains.end());
3461 const RRInfo &NewRetainRRI = It->second;
Dan Gohmanb3894012011-08-19 00:26:36 +00003462 KnownSafeTD &= NewRetainRRI.KnownSafe;
John McCalld935e9c2011-06-15 23:37:01 +00003463 for (SmallPtrSet<Instruction *, 2>::const_iterator
3464 LI = NewRetainRRI.Calls.begin(),
3465 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
3466 Instruction *NewRetainRelease = *LI;
3467 DenseMap<Value *, RRInfo>::const_iterator Jt =
3468 Releases.find(NewRetainRelease);
3469 if (Jt == Releases.end())
3470 goto next_retain;
3471 const RRInfo &NewRetainReleaseRRI = Jt->second;
3472 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
3473 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
3474 OldDelta -=
3475 BBStates[NewRetainRelease->getParent()].GetAllPathCount();
3476
3477 // Merge the ReleaseMetadata and IsTailCallRelease values.
3478 if (FirstRelease) {
3479 ReleasesToMove.ReleaseMetadata =
3480 NewRetainReleaseRRI.ReleaseMetadata;
3481 ReleasesToMove.IsTailCallRelease =
3482 NewRetainReleaseRRI.IsTailCallRelease;
3483 FirstRelease = false;
3484 } else {
3485 if (ReleasesToMove.ReleaseMetadata !=
3486 NewRetainReleaseRRI.ReleaseMetadata)
3487 ReleasesToMove.ReleaseMetadata = 0;
3488 if (ReleasesToMove.IsTailCallRelease !=
3489 NewRetainReleaseRRI.IsTailCallRelease)
3490 ReleasesToMove.IsTailCallRelease = false;
3491 }
3492
3493 // Collect the optimal insertion points.
3494 if (!KnownSafe)
3495 for (SmallPtrSet<Instruction *, 2>::const_iterator
3496 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
3497 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
3498 RI != RE; ++RI) {
3499 Instruction *RIP = *RI;
3500 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
3501 NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
3502 }
3503 NewReleases.push_back(NewRetainRelease);
3504 }
3505 }
3506 }
3507 NewRetains.clear();
3508 if (NewReleases.empty()) break;
3509
3510 // Back the other way.
3511 for (SmallVectorImpl<Instruction *>::const_iterator
3512 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
3513 Instruction *NewRelease = *NI;
3514 DenseMap<Value *, RRInfo>::const_iterator It =
3515 Releases.find(NewRelease);
3516 assert(It != Releases.end());
3517 const RRInfo &NewReleaseRRI = It->second;
Dan Gohmanb3894012011-08-19 00:26:36 +00003518 KnownSafeBU &= NewReleaseRRI.KnownSafe;
John McCalld935e9c2011-06-15 23:37:01 +00003519 for (SmallPtrSet<Instruction *, 2>::const_iterator
3520 LI = NewReleaseRRI.Calls.begin(),
3521 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
3522 Instruction *NewReleaseRetain = *LI;
3523 MapVector<Value *, RRInfo>::const_iterator Jt =
3524 Retains.find(NewReleaseRetain);
3525 if (Jt == Retains.end())
3526 goto next_retain;
3527 const RRInfo &NewReleaseRetainRRI = Jt->second;
3528 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
3529 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
3530 unsigned PathCount =
3531 BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
3532 OldDelta += PathCount;
3533 OldCount += PathCount;
3534
3535 // Merge the IsRetainBlock values.
3536 if (FirstRetain) {
3537 RetainsToMove.IsRetainBlock = NewReleaseRetainRRI.IsRetainBlock;
3538 FirstRetain = false;
3539 } else if (ReleasesToMove.IsRetainBlock !=
3540 NewReleaseRetainRRI.IsRetainBlock)
3541 // It's not possible to merge the sequences if one uses
3542 // objc_retain and the other uses objc_retainBlock.
3543 goto next_retain;
3544
3545 // Collect the optimal insertion points.
3546 if (!KnownSafe)
3547 for (SmallPtrSet<Instruction *, 2>::const_iterator
3548 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
3549 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
3550 RI != RE; ++RI) {
3551 Instruction *RIP = *RI;
3552 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
3553 PathCount = BBStates[RIP->getParent()].GetAllPathCount();
3554 NewDelta += PathCount;
3555 NewCount += PathCount;
3556 }
3557 }
3558 NewRetains.push_back(NewReleaseRetain);
3559 }
3560 }
3561 }
3562 NewReleases.clear();
3563 if (NewRetains.empty()) break;
3564 }
3565
Dan Gohmanb3894012011-08-19 00:26:36 +00003566 // If the pointer is known incremented or nested, we can safely delete the
3567 // pair regardless of what's between them.
3568 if (KnownSafeTD || KnownSafeBU) {
John McCalld935e9c2011-06-15 23:37:01 +00003569 RetainsToMove.ReverseInsertPts.clear();
3570 ReleasesToMove.ReverseInsertPts.clear();
3571 NewCount = 0;
Dan Gohman12130272011-08-12 00:26:31 +00003572 } else {
3573 // Determine whether the new insertion points we computed preserve the
3574 // balance of retain and release calls through the program.
3575 // TODO: If the fully aggressive solution isn't valid, try to find a
3576 // less aggressive solution which is.
3577 if (NewDelta != 0)
3578 goto next_retain;
John McCalld935e9c2011-06-15 23:37:01 +00003579 }
3580
3581 // Determine whether the original call points are balanced in the retain and
3582 // release calls through the program. If not, conservatively don't touch
3583 // them.
3584 // TODO: It's theoretically possible to do code motion in this case, as
3585 // long as the existing imbalances are maintained.
3586 if (OldDelta != 0)
3587 goto next_retain;
3588
John McCalld935e9c2011-06-15 23:37:01 +00003589 // Ok, everything checks out and we're all set. Let's move some code!
3590 Changed = true;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003591 assert(OldCount != 0 && "Unreachable code?");
3592 AnyPairsCompletelyEliminated = NewCount == 0;
John McCalld935e9c2011-06-15 23:37:01 +00003593 NumRRs += OldCount - NewCount;
Dan Gohman6320f522011-07-22 22:29:21 +00003594 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
3595 Retains, Releases, DeadInsts, M);
John McCalld935e9c2011-06-15 23:37:01 +00003596
3597 next_retain:
3598 NewReleases.clear();
3599 NewRetains.clear();
3600 RetainsToMove.clear();
3601 ReleasesToMove.clear();
3602 }
3603
3604 // Now that we're done moving everything, we can delete the newly dead
3605 // instructions, as we no longer need them as insert points.
3606 while (!DeadInsts.empty())
3607 EraseInstruction(DeadInsts.pop_back_val());
3608
3609 return AnyPairsCompletelyEliminated;
3610}
3611
Michael Gottesman97e3df02013-01-14 00:35:14 +00003612/// Weak pointer optimizations.
John McCalld935e9c2011-06-15 23:37:01 +00003613void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
3614 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
3615 // itself because it uses AliasAnalysis and we need to do provenance
3616 // queries instead.
3617 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3618 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +00003619
Michael Gottesman9f848ae2013-01-04 21:29:57 +00003620 DEBUG(dbgs() << "ObjCARCOpt::OptimizeWeakCalls: Visiting: " << *Inst <<
Michael Gottesman3f146e22013-01-01 16:05:48 +00003621 "\n");
3622
John McCalld935e9c2011-06-15 23:37:01 +00003623 InstructionClass Class = GetBasicInstructionClass(Inst);
3624 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
3625 continue;
3626
3627 // Delete objc_loadWeak calls with no users.
3628 if (Class == IC_LoadWeak && Inst->use_empty()) {
3629 Inst->eraseFromParent();
3630 continue;
3631 }
3632
3633 // TODO: For now, just look for an earlier available version of this value
3634 // within the same block. Theoretically, we could do memdep-style non-local
3635 // analysis too, but that would want caching. A better approach would be to
3636 // use the technique that EarlyCSE uses.
3637 inst_iterator Current = llvm::prior(I);
3638 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
3639 for (BasicBlock::iterator B = CurrentBB->begin(),
3640 J = Current.getInstructionIterator();
3641 J != B; --J) {
3642 Instruction *EarlierInst = &*llvm::prior(J);
3643 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
3644 switch (EarlierClass) {
3645 case IC_LoadWeak:
3646 case IC_LoadWeakRetained: {
3647 // If this is loading from the same pointer, replace this load's value
3648 // with that one.
3649 CallInst *Call = cast<CallInst>(Inst);
3650 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3651 Value *Arg = Call->getArgOperand(0);
3652 Value *EarlierArg = EarlierCall->getArgOperand(0);
3653 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3654 case AliasAnalysis::MustAlias:
3655 Changed = true;
3656 // If the load has a builtin retain, insert a plain retain for it.
3657 if (Class == IC_LoadWeakRetained) {
3658 CallInst *CI =
3659 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3660 "", Call);
3661 CI->setTailCall();
3662 }
3663 // Zap the fully redundant load.
3664 Call->replaceAllUsesWith(EarlierCall);
3665 Call->eraseFromParent();
3666 goto clobbered;
3667 case AliasAnalysis::MayAlias:
3668 case AliasAnalysis::PartialAlias:
3669 goto clobbered;
3670 case AliasAnalysis::NoAlias:
3671 break;
3672 }
3673 break;
3674 }
3675 case IC_StoreWeak:
3676 case IC_InitWeak: {
3677 // If this is storing to the same pointer and has the same size etc.
3678 // replace this load's value with the stored value.
3679 CallInst *Call = cast<CallInst>(Inst);
3680 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3681 Value *Arg = Call->getArgOperand(0);
3682 Value *EarlierArg = EarlierCall->getArgOperand(0);
3683 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3684 case AliasAnalysis::MustAlias:
3685 Changed = true;
3686 // If the load has a builtin retain, insert a plain retain for it.
3687 if (Class == IC_LoadWeakRetained) {
3688 CallInst *CI =
3689 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3690 "", Call);
3691 CI->setTailCall();
3692 }
3693 // Zap the fully redundant load.
3694 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
3695 Call->eraseFromParent();
3696 goto clobbered;
3697 case AliasAnalysis::MayAlias:
3698 case AliasAnalysis::PartialAlias:
3699 goto clobbered;
3700 case AliasAnalysis::NoAlias:
3701 break;
3702 }
3703 break;
3704 }
3705 case IC_MoveWeak:
3706 case IC_CopyWeak:
3707 // TOOD: Grab the copied value.
3708 goto clobbered;
3709 case IC_AutoreleasepoolPush:
3710 case IC_None:
3711 case IC_User:
3712 // Weak pointers are only modified through the weak entry points
3713 // (and arbitrary calls, which could call the weak entry points).
3714 break;
3715 default:
3716 // Anything else could modify the weak pointer.
3717 goto clobbered;
3718 }
3719 }
3720 clobbered:;
3721 }
3722
3723 // Then, for each destroyWeak with an alloca operand, check to see if
3724 // the alloca and all its users can be zapped.
3725 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3726 Instruction *Inst = &*I++;
3727 InstructionClass Class = GetBasicInstructionClass(Inst);
3728 if (Class != IC_DestroyWeak)
3729 continue;
3730
3731 CallInst *Call = cast<CallInst>(Inst);
3732 Value *Arg = Call->getArgOperand(0);
3733 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
3734 for (Value::use_iterator UI = Alloca->use_begin(),
3735 UE = Alloca->use_end(); UI != UE; ++UI) {
Dan Gohmandae33492012-04-27 18:56:31 +00003736 const Instruction *UserInst = cast<Instruction>(*UI);
John McCalld935e9c2011-06-15 23:37:01 +00003737 switch (GetBasicInstructionClass(UserInst)) {
3738 case IC_InitWeak:
3739 case IC_StoreWeak:
3740 case IC_DestroyWeak:
3741 continue;
3742 default:
3743 goto done;
3744 }
3745 }
3746 Changed = true;
3747 for (Value::use_iterator UI = Alloca->use_begin(),
3748 UE = Alloca->use_end(); UI != UE; ) {
3749 CallInst *UserInst = cast<CallInst>(*UI++);
Dan Gohman14862c32012-05-18 22:17:29 +00003750 switch (GetBasicInstructionClass(UserInst)) {
3751 case IC_InitWeak:
3752 case IC_StoreWeak:
3753 // These functions return their second argument.
3754 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
3755 break;
3756 case IC_DestroyWeak:
3757 // No return value.
3758 break;
3759 default:
Dan Gohman9c97eea02012-05-21 17:41:28 +00003760 llvm_unreachable("alloca really is used!");
Dan Gohman14862c32012-05-18 22:17:29 +00003761 }
John McCalld935e9c2011-06-15 23:37:01 +00003762 UserInst->eraseFromParent();
3763 }
3764 Alloca->eraseFromParent();
3765 done:;
3766 }
3767 }
Michael Gottesman10426b52013-01-07 21:26:07 +00003768
Michael Gottesman9f848ae2013-01-04 21:29:57 +00003769 DEBUG(dbgs() << "ObjCARCOpt::OptimizeWeakCalls: Finished List.\n\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00003770
John McCalld935e9c2011-06-15 23:37:01 +00003771}
3772
Michael Gottesman97e3df02013-01-14 00:35:14 +00003773/// Identify program paths which execute sequences of retains and releases which
3774/// can be eliminated.
John McCalld935e9c2011-06-15 23:37:01 +00003775bool ObjCARCOpt::OptimizeSequences(Function &F) {
3776 /// Releases, Retains - These are used to store the results of the main flow
3777 /// analysis. These use Value* as the key instead of Instruction* so that the
3778 /// map stays valid when we get around to rewriting code and calls get
3779 /// replaced by arguments.
3780 DenseMap<Value *, RRInfo> Releases;
3781 MapVector<Value *, RRInfo> Retains;
3782
Michael Gottesman97e3df02013-01-14 00:35:14 +00003783 /// This is used during the traversal of the function to track the
John McCalld935e9c2011-06-15 23:37:01 +00003784 /// states for each identified object at each block.
3785 DenseMap<const BasicBlock *, BBState> BBStates;
3786
3787 // Analyze the CFG of the function, and all instructions.
3788 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
3789
3790 // Transform.
Dan Gohman6320f522011-07-22 22:29:21 +00003791 return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) &&
3792 NestingDetected;
John McCalld935e9c2011-06-15 23:37:01 +00003793}
3794
Michael Gottesman97e3df02013-01-14 00:35:14 +00003795/// Look for this pattern:
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00003796/// \code
John McCalld935e9c2011-06-15 23:37:01 +00003797/// %call = call i8* @something(...)
3798/// %2 = call i8* @objc_retain(i8* %call)
3799/// %3 = call i8* @objc_autorelease(i8* %2)
3800/// ret i8* %3
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00003801/// \endcode
John McCalld935e9c2011-06-15 23:37:01 +00003802/// And delete the retain and autorelease.
3803///
3804/// Otherwise if it's just this:
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00003805/// \code
John McCalld935e9c2011-06-15 23:37:01 +00003806/// %3 = call i8* @objc_autorelease(i8* %2)
3807/// ret i8* %3
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00003808/// \endcode
John McCalld935e9c2011-06-15 23:37:01 +00003809/// convert the autorelease to autoreleaseRV.
3810void ObjCARCOpt::OptimizeReturns(Function &F) {
3811 if (!F.getReturnType()->isPointerTy())
3812 return;
3813
3814 SmallPtrSet<Instruction *, 4> DependingInstructions;
3815 SmallPtrSet<const BasicBlock *, 4> Visited;
3816 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3817 BasicBlock *BB = FI;
3818 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
Michael Gottesman3f146e22013-01-01 16:05:48 +00003819
Michael Gottesman9f848ae2013-01-04 21:29:57 +00003820 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Visiting: " << *Ret << "\n");
Michael Gottesman3f146e22013-01-01 16:05:48 +00003821
John McCalld935e9c2011-06-15 23:37:01 +00003822 if (!Ret) continue;
3823
3824 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
3825 FindDependencies(NeedsPositiveRetainCount, Arg,
3826 BB, Ret, DependingInstructions, Visited, PA);
3827 if (DependingInstructions.size() != 1)
3828 goto next_block;
3829
3830 {
3831 CallInst *Autorelease =
3832 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3833 if (!Autorelease)
3834 goto next_block;
Dan Gohman41375a32012-05-08 23:39:44 +00003835 InstructionClass AutoreleaseClass = GetBasicInstructionClass(Autorelease);
John McCalld935e9c2011-06-15 23:37:01 +00003836 if (!IsAutorelease(AutoreleaseClass))
3837 goto next_block;
3838 if (GetObjCArg(Autorelease) != Arg)
3839 goto next_block;
3840
3841 DependingInstructions.clear();
3842 Visited.clear();
3843
3844 // Check that there is nothing that can affect the reference
3845 // count between the autorelease and the retain.
3846 FindDependencies(CanChangeRetainCount, Arg,
3847 BB, Autorelease, DependingInstructions, Visited, PA);
3848 if (DependingInstructions.size() != 1)
3849 goto next_block;
3850
3851 {
3852 CallInst *Retain =
3853 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3854
3855 // Check that we found a retain with the same argument.
3856 if (!Retain ||
3857 !IsRetain(GetBasicInstructionClass(Retain)) ||
3858 GetObjCArg(Retain) != Arg)
3859 goto next_block;
3860
3861 DependingInstructions.clear();
3862 Visited.clear();
3863
3864 // Convert the autorelease to an autoreleaseRV, since it's
3865 // returning the value.
3866 if (AutoreleaseClass == IC_Autorelease) {
Michael Gottesmana6cb0182013-01-10 02:03:50 +00003867 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Converting autorelease "
3868 "=> autoreleaseRV since it's returning a value.\n"
3869 " In: " << *Autorelease
3870 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00003871 Autorelease->setCalledFunction(getAutoreleaseRVCallee(F.getParent()));
Michael Gottesmana6cb0182013-01-10 02:03:50 +00003872 DEBUG(dbgs() << " Out: " << *Autorelease
3873 << "\n");
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00003874 Autorelease->setTailCall(); // Always tail call autoreleaseRV.
John McCalld935e9c2011-06-15 23:37:01 +00003875 AutoreleaseClass = IC_AutoreleaseRV;
3876 }
3877
3878 // Check that there is nothing that can affect the reference
3879 // count between the retain and the call.
Dan Gohman4ac148d2011-09-29 22:27:34 +00003880 // Note that Retain need not be in BB.
3881 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
John McCalld935e9c2011-06-15 23:37:01 +00003882 DependingInstructions, Visited, PA);
3883 if (DependingInstructions.size() != 1)
3884 goto next_block;
3885
3886 {
3887 CallInst *Call =
3888 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3889
3890 // Check that the pointer is the return value of the call.
3891 if (!Call || Arg != Call)
3892 goto next_block;
3893
3894 // Check that the call is a regular call.
3895 InstructionClass Class = GetBasicInstructionClass(Call);
3896 if (Class != IC_CallOrUser && Class != IC_Call)
3897 goto next_block;
3898
3899 // If so, we can zap the retain and autorelease.
3900 Changed = true;
3901 ++NumRets;
Michael Gottesmand61a3b22013-01-07 00:04:56 +00003902 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Erasing: " << *Retain
3903 << "\n Erasing: "
3904 << *Autorelease << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00003905 EraseInstruction(Retain);
3906 EraseInstruction(Autorelease);
3907 }
3908 }
3909 }
3910
3911 next_block:
3912 DependingInstructions.clear();
3913 Visited.clear();
3914 }
Michael Gottesman10426b52013-01-07 21:26:07 +00003915
Michael Gottesman9f848ae2013-01-04 21:29:57 +00003916 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Finished List.\n\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00003917
John McCalld935e9c2011-06-15 23:37:01 +00003918}
3919
3920bool ObjCARCOpt::doInitialization(Module &M) {
3921 if (!EnableARCOpts)
3922 return false;
3923
Dan Gohman670f9372012-04-13 18:57:48 +00003924 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanceaac7c2011-06-20 23:20:43 +00003925 Run = ModuleHasARC(M);
3926 if (!Run)
3927 return false;
3928
John McCalld935e9c2011-06-15 23:37:01 +00003929 // Identify the imprecise release metadata kind.
3930 ImpreciseReleaseMDKind =
3931 M.getContext().getMDKindID("clang.imprecise_release");
Dan Gohmana7107f92011-10-17 22:53:25 +00003932 CopyOnEscapeMDKind =
3933 M.getContext().getMDKindID("clang.arc.copy_on_escape");
Dan Gohman0155f302012-02-17 18:59:53 +00003934 NoObjCARCExceptionsMDKind =
3935 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
John McCalld935e9c2011-06-15 23:37:01 +00003936
John McCalld935e9c2011-06-15 23:37:01 +00003937 // Intuitively, objc_retain and others are nocapture, however in practice
3938 // they are not, because they return their argument value. And objc_release
Dan Gohmandae33492012-04-27 18:56:31 +00003939 // calls finalizers which can have arbitrary side effects.
John McCalld935e9c2011-06-15 23:37:01 +00003940
3941 // These are initialized lazily.
3942 RetainRVCallee = 0;
3943 AutoreleaseRVCallee = 0;
3944 ReleaseCallee = 0;
3945 RetainCallee = 0;
Dan Gohman6320f522011-07-22 22:29:21 +00003946 RetainBlockCallee = 0;
John McCalld935e9c2011-06-15 23:37:01 +00003947 AutoreleaseCallee = 0;
3948
3949 return false;
3950}
3951
3952bool ObjCARCOpt::runOnFunction(Function &F) {
3953 if (!EnableARCOpts)
3954 return false;
3955
Dan Gohmanceaac7c2011-06-20 23:20:43 +00003956 // If nothing in the Module uses ARC, don't do anything.
3957 if (!Run)
3958 return false;
3959
John McCalld935e9c2011-06-15 23:37:01 +00003960 Changed = false;
3961
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00003962 DEBUG(dbgs() << "ObjCARCOpt: Visiting Function: " << F.getName() << "\n");
3963
John McCalld935e9c2011-06-15 23:37:01 +00003964 PA.setAA(&getAnalysis<AliasAnalysis>());
3965
3966 // This pass performs several distinct transformations. As a compile-time aid
3967 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3968 // library functions aren't declared.
3969
3970 // Preliminary optimizations. This also computs UsedInThisFunction.
3971 OptimizeIndividualCalls(F);
3972
3973 // Optimizations for weak pointers.
3974 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3975 (1 << IC_LoadWeakRetained) |
3976 (1 << IC_StoreWeak) |
3977 (1 << IC_InitWeak) |
3978 (1 << IC_CopyWeak) |
3979 (1 << IC_MoveWeak) |
3980 (1 << IC_DestroyWeak)))
3981 OptimizeWeakCalls(F);
3982
3983 // Optimizations for retain+release pairs.
3984 if (UsedInThisFunction & ((1 << IC_Retain) |
3985 (1 << IC_RetainRV) |
3986 (1 << IC_RetainBlock)))
3987 if (UsedInThisFunction & (1 << IC_Release))
3988 // Run OptimizeSequences until it either stops making changes or
3989 // no retain+release pair nesting is detected.
3990 while (OptimizeSequences(F)) {}
3991
3992 // Optimizations if objc_autorelease is used.
Dan Gohman41375a32012-05-08 23:39:44 +00003993 if (UsedInThisFunction & ((1 << IC_Autorelease) |
3994 (1 << IC_AutoreleaseRV)))
John McCalld935e9c2011-06-15 23:37:01 +00003995 OptimizeReturns(F);
3996
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00003997 DEBUG(dbgs() << "\n");
3998
John McCalld935e9c2011-06-15 23:37:01 +00003999 return Changed;
4000}
4001
4002void ObjCARCOpt::releaseMemory() {
4003 PA.clear();
4004}
4005
Michael Gottesman97e3df02013-01-14 00:35:14 +00004006/// @}
4007///
4008/// \defgroup ARCContract ARC Contraction.
4009/// @{
John McCalld935e9c2011-06-15 23:37:01 +00004010
4011// TODO: ObjCARCContract could insert PHI nodes when uses aren't
4012// dominated by single calls.
4013
John McCalld935e9c2011-06-15 23:37:01 +00004014#include "llvm/Analysis/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +00004015#include "llvm/IR/InlineAsm.h"
4016#include "llvm/IR/Operator.h"
John McCalld935e9c2011-06-15 23:37:01 +00004017
4018STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed");
4019
4020namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +00004021 /// \brief Late ARC optimizations
4022 ///
4023 /// These change the IR in a way that makes it difficult to be analyzed by
4024 /// ObjCARCOpt, so it's run late.
John McCalld935e9c2011-06-15 23:37:01 +00004025 class ObjCARCContract : public FunctionPass {
4026 bool Changed;
4027 AliasAnalysis *AA;
4028 DominatorTree *DT;
4029 ProvenanceAnalysis PA;
4030
Michael Gottesman97e3df02013-01-14 00:35:14 +00004031 /// A flag indicating whether this optimization pass should run.
Dan Gohmanceaac7c2011-06-20 23:20:43 +00004032 bool Run;
4033
Michael Gottesman97e3df02013-01-14 00:35:14 +00004034 /// Declarations for ObjC runtime functions, for use in creating calls to
4035 /// them. These are initialized lazily to avoid cluttering up the Module
4036 /// with unused declarations.
John McCalld935e9c2011-06-15 23:37:01 +00004037
Michael Gottesman97e3df02013-01-14 00:35:14 +00004038 /// Declaration for objc_storeStrong().
4039 Constant *StoreStrongCallee;
4040 /// Declaration for objc_retainAutorelease().
4041 Constant *RetainAutoreleaseCallee;
4042 /// Declaration for objc_retainAutoreleaseReturnValue().
4043 Constant *RetainAutoreleaseRVCallee;
4044
4045 /// The inline asm string to insert between calls and RetainRV calls to make
4046 /// the optimization work on targets which need it.
John McCalld935e9c2011-06-15 23:37:01 +00004047 const MDString *RetainRVMarker;
4048
Michael Gottesman97e3df02013-01-14 00:35:14 +00004049 /// The set of inserted objc_storeStrong calls. If at the end of walking the
4050 /// function we have found no alloca instructions, these calls can be marked
4051 /// "tail".
Dan Gohman41375a32012-05-08 23:39:44 +00004052 SmallPtrSet<CallInst *, 8> StoreStrongCalls;
Dan Gohman8ee108b2012-01-19 19:14:36 +00004053
John McCalld935e9c2011-06-15 23:37:01 +00004054 Constant *getStoreStrongCallee(Module *M);
4055 Constant *getRetainAutoreleaseCallee(Module *M);
4056 Constant *getRetainAutoreleaseRVCallee(Module *M);
4057
4058 bool ContractAutorelease(Function &F, Instruction *Autorelease,
4059 InstructionClass Class,
4060 SmallPtrSet<Instruction *, 4>
4061 &DependingInstructions,
4062 SmallPtrSet<const BasicBlock *, 4>
4063 &Visited);
4064
4065 void ContractRelease(Instruction *Release,
4066 inst_iterator &Iter);
4067
4068 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
4069 virtual bool doInitialization(Module &M);
4070 virtual bool runOnFunction(Function &F);
4071
4072 public:
4073 static char ID;
4074 ObjCARCContract() : FunctionPass(ID) {
4075 initializeObjCARCContractPass(*PassRegistry::getPassRegistry());
4076 }
4077 };
4078}
4079
4080char ObjCARCContract::ID = 0;
4081INITIALIZE_PASS_BEGIN(ObjCARCContract,
4082 "objc-arc-contract", "ObjC ARC contraction", false, false)
4083INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
4084INITIALIZE_PASS_DEPENDENCY(DominatorTree)
4085INITIALIZE_PASS_END(ObjCARCContract,
4086 "objc-arc-contract", "ObjC ARC contraction", false, false)
4087
4088Pass *llvm::createObjCARCContractPass() {
4089 return new ObjCARCContract();
4090}
4091
4092void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const {
4093 AU.addRequired<AliasAnalysis>();
4094 AU.addRequired<DominatorTree>();
4095 AU.setPreservesCFG();
4096}
4097
4098Constant *ObjCARCContract::getStoreStrongCallee(Module *M) {
4099 if (!StoreStrongCallee) {
4100 LLVMContext &C = M->getContext();
Jay Foadb804a2b2011-07-12 14:06:48 +00004101 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
4102 Type *I8XX = PointerType::getUnqual(I8X);
Dan Gohman41375a32012-05-08 23:39:44 +00004103 Type *Params[] = { I8XX, I8X };
John McCalld935e9c2011-06-15 23:37:01 +00004104
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004105 AttributeSet Attribute = AttributeSet()
Bill Wendlinge94d8432012-12-07 23:16:57 +00004106 .addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004107 Attribute::get(C, Attribute::NoUnwind))
4108 .addAttr(M->getContext(), 1, Attribute::get(C, Attribute::NoCapture));
John McCalld935e9c2011-06-15 23:37:01 +00004109
4110 StoreStrongCallee =
4111 M->getOrInsertFunction(
4112 "objc_storeStrong",
4113 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004114 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00004115 }
4116 return StoreStrongCallee;
4117}
4118
4119Constant *ObjCARCContract::getRetainAutoreleaseCallee(Module *M) {
4120 if (!RetainAutoreleaseCallee) {
4121 LLVMContext &C = M->getContext();
Jay Foadb804a2b2011-07-12 14:06:48 +00004122 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman41375a32012-05-08 23:39:44 +00004123 Type *Params[] = { I8X };
4124 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004125 AttributeSet Attribute =
Bill Wendlinge94d8432012-12-07 23:16:57 +00004126 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004127 Attribute::get(C, Attribute::NoUnwind));
John McCalld935e9c2011-06-15 23:37:01 +00004128 RetainAutoreleaseCallee =
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004129 M->getOrInsertFunction("objc_retainAutorelease", FTy, Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00004130 }
4131 return RetainAutoreleaseCallee;
4132}
4133
4134Constant *ObjCARCContract::getRetainAutoreleaseRVCallee(Module *M) {
4135 if (!RetainAutoreleaseRVCallee) {
4136 LLVMContext &C = M->getContext();
Jay Foadb804a2b2011-07-12 14:06:48 +00004137 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman41375a32012-05-08 23:39:44 +00004138 Type *Params[] = { I8X };
4139 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004140 AttributeSet Attribute =
Bill Wendlinge94d8432012-12-07 23:16:57 +00004141 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004142 Attribute::get(C, Attribute::NoUnwind));
John McCalld935e9c2011-06-15 23:37:01 +00004143 RetainAutoreleaseRVCallee =
4144 M->getOrInsertFunction("objc_retainAutoreleaseReturnValue", FTy,
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004145 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00004146 }
4147 return RetainAutoreleaseRVCallee;
4148}
4149
Michael Gottesman97e3df02013-01-14 00:35:14 +00004150/// Merge an autorelease with a retain into a fused call.
John McCalld935e9c2011-06-15 23:37:01 +00004151bool
4152ObjCARCContract::ContractAutorelease(Function &F, Instruction *Autorelease,
4153 InstructionClass Class,
4154 SmallPtrSet<Instruction *, 4>
4155 &DependingInstructions,
4156 SmallPtrSet<const BasicBlock *, 4>
4157 &Visited) {
4158 const Value *Arg = GetObjCArg(Autorelease);
4159
4160 // Check that there are no instructions between the retain and the autorelease
4161 // (such as an autorelease_pop) which may change the count.
4162 CallInst *Retain = 0;
4163 if (Class == IC_AutoreleaseRV)
4164 FindDependencies(RetainAutoreleaseRVDep, Arg,
4165 Autorelease->getParent(), Autorelease,
4166 DependingInstructions, Visited, PA);
4167 else
4168 FindDependencies(RetainAutoreleaseDep, Arg,
4169 Autorelease->getParent(), Autorelease,
4170 DependingInstructions, Visited, PA);
4171
4172 Visited.clear();
4173 if (DependingInstructions.size() != 1) {
4174 DependingInstructions.clear();
4175 return false;
4176 }
4177
4178 Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
4179 DependingInstructions.clear();
4180
4181 if (!Retain ||
4182 GetBasicInstructionClass(Retain) != IC_Retain ||
4183 GetObjCArg(Retain) != Arg)
4184 return false;
4185
4186 Changed = true;
4187 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00004188
Michael Gottesmanadd08472013-01-07 00:31:26 +00004189 DEBUG(dbgs() << "ObjCARCContract::ContractAutorelease: Fusing "
4190 "retain/autorelease. Erasing: " << *Autorelease << "\n"
4191 " Old Retain: "
4192 << *Retain << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00004193
John McCalld935e9c2011-06-15 23:37:01 +00004194 if (Class == IC_AutoreleaseRV)
4195 Retain->setCalledFunction(getRetainAutoreleaseRVCallee(F.getParent()));
4196 else
4197 Retain->setCalledFunction(getRetainAutoreleaseCallee(F.getParent()));
Michael Gottesman10426b52013-01-07 21:26:07 +00004198
Michael Gottesmanadd08472013-01-07 00:31:26 +00004199 DEBUG(dbgs() << " New Retain: "
4200 << *Retain << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00004201
John McCalld935e9c2011-06-15 23:37:01 +00004202 EraseInstruction(Autorelease);
4203 return true;
4204}
4205
Michael Gottesman97e3df02013-01-14 00:35:14 +00004206/// Attempt to merge an objc_release with a store, load, and objc_retain to form
4207/// an objc_storeStrong. This can be a little tricky because the instructions
4208/// don't always appear in order, and there may be unrelated intervening
4209/// instructions.
John McCalld935e9c2011-06-15 23:37:01 +00004210void ObjCARCContract::ContractRelease(Instruction *Release,
4211 inst_iterator &Iter) {
4212 LoadInst *Load = dyn_cast<LoadInst>(GetObjCArg(Release));
Eli Friedman7c5dc122011-09-12 20:23:13 +00004213 if (!Load || !Load->isSimple()) return;
John McCalld935e9c2011-06-15 23:37:01 +00004214
4215 // For now, require everything to be in one basic block.
4216 BasicBlock *BB = Release->getParent();
4217 if (Load->getParent() != BB) return;
4218
Dan Gohman61708d32012-05-08 23:34:08 +00004219 // Walk down to find the store and the release, which may be in either order.
Dan Gohmanf8b19d02012-05-09 23:08:33 +00004220 BasicBlock::iterator I = Load, End = BB->end();
John McCalld935e9c2011-06-15 23:37:01 +00004221 ++I;
4222 AliasAnalysis::Location Loc = AA->getLocation(Load);
Dan Gohman61708d32012-05-08 23:34:08 +00004223 StoreInst *Store = 0;
4224 bool SawRelease = false;
4225 for (; !Store || !SawRelease; ++I) {
Dan Gohmanf8b19d02012-05-09 23:08:33 +00004226 if (I == End)
4227 return;
4228
Dan Gohman61708d32012-05-08 23:34:08 +00004229 Instruction *Inst = I;
4230 if (Inst == Release) {
4231 SawRelease = true;
4232 continue;
4233 }
4234
4235 InstructionClass Class = GetBasicInstructionClass(Inst);
4236
4237 // Unrelated retains are harmless.
4238 if (IsRetain(Class))
4239 continue;
4240
4241 if (Store) {
4242 // The store is the point where we're going to put the objc_storeStrong,
4243 // so make sure there are no uses after it.
4244 if (CanUse(Inst, Load, PA, Class))
4245 return;
4246 } else if (AA->getModRefInfo(Inst, Loc) & AliasAnalysis::Mod) {
4247 // We are moving the load down to the store, so check for anything
4248 // else which writes to the memory between the load and the store.
4249 Store = dyn_cast<StoreInst>(Inst);
4250 if (!Store || !Store->isSimple()) return;
4251 if (Store->getPointerOperand() != Loc.Ptr) return;
4252 }
4253 }
John McCalld935e9c2011-06-15 23:37:01 +00004254
4255 Value *New = StripPointerCastsAndObjCCalls(Store->getValueOperand());
4256
4257 // Walk up to find the retain.
4258 I = Store;
4259 BasicBlock::iterator Begin = BB->begin();
4260 while (I != Begin && GetBasicInstructionClass(I) != IC_Retain)
4261 --I;
4262 Instruction *Retain = I;
4263 if (GetBasicInstructionClass(Retain) != IC_Retain) return;
4264 if (GetObjCArg(Retain) != New) return;
4265
4266 Changed = true;
4267 ++NumStoreStrongs;
4268
4269 LLVMContext &C = Release->getContext();
Chris Lattner229907c2011-07-18 04:54:35 +00004270 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
4271 Type *I8XX = PointerType::getUnqual(I8X);
John McCalld935e9c2011-06-15 23:37:01 +00004272
4273 Value *Args[] = { Load->getPointerOperand(), New };
4274 if (Args[0]->getType() != I8XX)
4275 Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
4276 if (Args[1]->getType() != I8X)
4277 Args[1] = new BitCastInst(Args[1], I8X, "", Store);
4278 CallInst *StoreStrong =
4279 CallInst::Create(getStoreStrongCallee(BB->getParent()->getParent()),
Jay Foad5bd375a2011-07-15 08:37:34 +00004280 Args, "", Store);
John McCalld935e9c2011-06-15 23:37:01 +00004281 StoreStrong->setDoesNotThrow();
4282 StoreStrong->setDebugLoc(Store->getDebugLoc());
4283
Dan Gohman8ee108b2012-01-19 19:14:36 +00004284 // We can't set the tail flag yet, because we haven't yet determined
4285 // whether there are any escaping allocas. Remember this call, so that
4286 // we can set the tail flag once we know it's safe.
4287 StoreStrongCalls.insert(StoreStrong);
4288
John McCalld935e9c2011-06-15 23:37:01 +00004289 if (&*Iter == Store) ++Iter;
4290 Store->eraseFromParent();
4291 Release->eraseFromParent();
4292 EraseInstruction(Retain);
4293 if (Load->use_empty())
4294 Load->eraseFromParent();
4295}
4296
4297bool ObjCARCContract::doInitialization(Module &M) {
Dan Gohman670f9372012-04-13 18:57:48 +00004298 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanceaac7c2011-06-20 23:20:43 +00004299 Run = ModuleHasARC(M);
4300 if (!Run)
4301 return false;
4302
John McCalld935e9c2011-06-15 23:37:01 +00004303 // These are initialized lazily.
4304 StoreStrongCallee = 0;
4305 RetainAutoreleaseCallee = 0;
4306 RetainAutoreleaseRVCallee = 0;
4307
4308 // Initialize RetainRVMarker.
4309 RetainRVMarker = 0;
4310 if (NamedMDNode *NMD =
4311 M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker"))
4312 if (NMD->getNumOperands() == 1) {
4313 const MDNode *N = NMD->getOperand(0);
4314 if (N->getNumOperands() == 1)
4315 if (const MDString *S = dyn_cast<MDString>(N->getOperand(0)))
4316 RetainRVMarker = S;
4317 }
4318
4319 return false;
4320}
4321
4322bool ObjCARCContract::runOnFunction(Function &F) {
4323 if (!EnableARCOpts)
4324 return false;
4325
Dan Gohmanceaac7c2011-06-20 23:20:43 +00004326 // If nothing in the Module uses ARC, don't do anything.
4327 if (!Run)
4328 return false;
4329
John McCalld935e9c2011-06-15 23:37:01 +00004330 Changed = false;
4331 AA = &getAnalysis<AliasAnalysis>();
4332 DT = &getAnalysis<DominatorTree>();
4333
4334 PA.setAA(&getAnalysis<AliasAnalysis>());
4335
Dan Gohman8ee108b2012-01-19 19:14:36 +00004336 // Track whether it's ok to mark objc_storeStrong calls with the "tail"
4337 // keyword. Be conservative if the function has variadic arguments.
4338 // It seems that functions which "return twice" are also unsafe for the
4339 // "tail" argument, because they are setjmp, which could need to
4340 // return to an earlier stack state.
Dan Gohman41375a32012-05-08 23:39:44 +00004341 bool TailOkForStoreStrongs = !F.isVarArg() &&
4342 !F.callsFunctionThatReturnsTwice();
Dan Gohman8ee108b2012-01-19 19:14:36 +00004343
John McCalld935e9c2011-06-15 23:37:01 +00004344 // For ObjC library calls which return their argument, replace uses of the
4345 // argument with uses of the call return value, if it dominates the use. This
4346 // reduces register pressure.
4347 SmallPtrSet<Instruction *, 4> DependingInstructions;
4348 SmallPtrSet<const BasicBlock *, 4> Visited;
4349 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
4350 Instruction *Inst = &*I++;
Michael Gottesman10426b52013-01-07 21:26:07 +00004351
Michael Gottesman3f146e22013-01-01 16:05:48 +00004352 DEBUG(dbgs() << "ObjCARCContract: Visiting: " << *Inst << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00004353
John McCalld935e9c2011-06-15 23:37:01 +00004354 // Only these library routines return their argument. In particular,
4355 // objc_retainBlock does not necessarily return its argument.
4356 InstructionClass Class = GetBasicInstructionClass(Inst);
4357 switch (Class) {
4358 case IC_Retain:
4359 case IC_FusedRetainAutorelease:
4360 case IC_FusedRetainAutoreleaseRV:
4361 break;
4362 case IC_Autorelease:
4363 case IC_AutoreleaseRV:
4364 if (ContractAutorelease(F, Inst, Class, DependingInstructions, Visited))
4365 continue;
4366 break;
4367 case IC_RetainRV: {
4368 // If we're compiling for a target which needs a special inline-asm
4369 // marker to do the retainAutoreleasedReturnValue optimization,
4370 // insert it now.
4371 if (!RetainRVMarker)
4372 break;
4373 BasicBlock::iterator BBI = Inst;
Dan Gohman5f725cd2012-06-25 19:47:37 +00004374 BasicBlock *InstParent = Inst->getParent();
4375
4376 // Step up to see if the call immediately precedes the RetainRV call.
4377 // If it's an invoke, we have to cross a block boundary. And we have
4378 // to carefully dodge no-op instructions.
4379 do {
4380 if (&*BBI == InstParent->begin()) {
4381 BasicBlock *Pred = InstParent->getSinglePredecessor();
4382 if (!Pred)
4383 goto decline_rv_optimization;
4384 BBI = Pred->getTerminator();
4385 break;
4386 }
4387 --BBI;
4388 } while (isNoopInstruction(BBI));
4389
John McCalld935e9c2011-06-15 23:37:01 +00004390 if (&*BBI == GetObjCArg(Inst)) {
Michael Gottesman00d1f962013-01-03 07:32:41 +00004391 DEBUG(dbgs() << "ObjCARCContract: Adding inline asm marker for "
Michael Gottesman9f848ae2013-01-04 21:29:57 +00004392 "retainAutoreleasedReturnValue optimization.\n");
Dan Gohman670f9372012-04-13 18:57:48 +00004393 Changed = true;
John McCalld935e9c2011-06-15 23:37:01 +00004394 InlineAsm *IA =
4395 InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()),
4396 /*isVarArg=*/false),
4397 RetainRVMarker->getString(),
4398 /*Constraints=*/"", /*hasSideEffects=*/true);
4399 CallInst::Create(IA, "", Inst);
4400 }
Dan Gohman5f725cd2012-06-25 19:47:37 +00004401 decline_rv_optimization:
John McCalld935e9c2011-06-15 23:37:01 +00004402 break;
4403 }
4404 case IC_InitWeak: {
4405 // objc_initWeak(p, null) => *p = null
4406 CallInst *CI = cast<CallInst>(Inst);
4407 if (isNullOrUndef(CI->getArgOperand(1))) {
4408 Value *Null =
4409 ConstantPointerNull::get(cast<PointerType>(CI->getType()));
4410 Changed = true;
4411 new StoreInst(Null, CI->getArgOperand(0), CI);
Michael Gottesman10426b52013-01-07 21:26:07 +00004412
Michael Gottesman416dc002013-01-03 07:32:53 +00004413 DEBUG(dbgs() << "OBJCARCContract: Old = " << *CI << "\n"
4414 << " New = " << *Null << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00004415
John McCalld935e9c2011-06-15 23:37:01 +00004416 CI->replaceAllUsesWith(Null);
4417 CI->eraseFromParent();
4418 }
4419 continue;
4420 }
4421 case IC_Release:
4422 ContractRelease(Inst, I);
4423 continue;
Dan Gohman8ee108b2012-01-19 19:14:36 +00004424 case IC_User:
4425 // Be conservative if the function has any alloca instructions.
4426 // Technically we only care about escaping alloca instructions,
4427 // but this is sufficient to handle some interesting cases.
4428 if (isa<AllocaInst>(Inst))
4429 TailOkForStoreStrongs = false;
4430 continue;
John McCalld935e9c2011-06-15 23:37:01 +00004431 default:
4432 continue;
4433 }
4434
Michael Gottesman50ae5b22013-01-03 08:09:27 +00004435 DEBUG(dbgs() << "ObjCARCContract: Finished List.\n\n");
Michael Gottesman3f146e22013-01-01 16:05:48 +00004436
John McCalld935e9c2011-06-15 23:37:01 +00004437 // Don't use GetObjCArg because we don't want to look through bitcasts
4438 // and such; to do the replacement, the argument must have type i8*.
4439 const Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
4440 for (;;) {
4441 // If we're compiling bugpointed code, don't get in trouble.
4442 if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
4443 break;
4444 // Look through the uses of the pointer.
4445 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
4446 UI != UE; ) {
4447 Use &U = UI.getUse();
4448 unsigned OperandNo = UI.getOperandNo();
4449 ++UI; // Increment UI now, because we may unlink its element.
Dan Gohman670f9372012-04-13 18:57:48 +00004450
4451 // If the call's return value dominates a use of the call's argument
4452 // value, rewrite the use to use the return value. We check for
4453 // reachability here because an unreachable call is considered to
4454 // trivially dominate itself, which would lead us to rewriting its
4455 // argument in terms of its return value, which would lead to
4456 // infinite loops in GetObjCArg.
Dan Gohman41375a32012-05-08 23:39:44 +00004457 if (DT->isReachableFromEntry(U) && DT->dominates(Inst, U)) {
Rafael Espindolaf5892782012-03-15 15:52:59 +00004458 Changed = true;
4459 Instruction *Replacement = Inst;
4460 Type *UseTy = U.get()->getType();
Dan Gohmande8d2c42012-04-13 01:08:28 +00004461 if (PHINode *PHI = dyn_cast<PHINode>(U.getUser())) {
Rafael Espindolaf5892782012-03-15 15:52:59 +00004462 // For PHI nodes, insert the bitcast in the predecessor block.
Dan Gohman41375a32012-05-08 23:39:44 +00004463 unsigned ValNo = PHINode::getIncomingValueNumForOperand(OperandNo);
4464 BasicBlock *BB = PHI->getIncomingBlock(ValNo);
Rafael Espindolaf5892782012-03-15 15:52:59 +00004465 if (Replacement->getType() != UseTy)
4466 Replacement = new BitCastInst(Replacement, UseTy, "",
4467 &BB->back());
Dan Gohman670f9372012-04-13 18:57:48 +00004468 // While we're here, rewrite all edges for this PHI, rather
4469 // than just one use at a time, to minimize the number of
4470 // bitcasts we emit.
Dan Gohmandae33492012-04-27 18:56:31 +00004471 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
Rafael Espindolaf5892782012-03-15 15:52:59 +00004472 if (PHI->getIncomingBlock(i) == BB) {
4473 // Keep the UI iterator valid.
4474 if (&PHI->getOperandUse(
4475 PHINode::getOperandNumForIncomingValue(i)) ==
4476 &UI.getUse())
4477 ++UI;
4478 PHI->setIncomingValue(i, Replacement);
4479 }
4480 } else {
4481 if (Replacement->getType() != UseTy)
Dan Gohmande8d2c42012-04-13 01:08:28 +00004482 Replacement = new BitCastInst(Replacement, UseTy, "",
4483 cast<Instruction>(U.getUser()));
Rafael Espindolaf5892782012-03-15 15:52:59 +00004484 U.set(Replacement);
John McCalld935e9c2011-06-15 23:37:01 +00004485 }
Rafael Espindolaf5892782012-03-15 15:52:59 +00004486 }
John McCalld935e9c2011-06-15 23:37:01 +00004487 }
4488
Dan Gohmandae33492012-04-27 18:56:31 +00004489 // If Arg is a no-op casted pointer, strip one level of casts and iterate.
John McCalld935e9c2011-06-15 23:37:01 +00004490 if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
4491 Arg = BI->getOperand(0);
4492 else if (isa<GEPOperator>(Arg) &&
4493 cast<GEPOperator>(Arg)->hasAllZeroIndices())
4494 Arg = cast<GEPOperator>(Arg)->getPointerOperand();
4495 else if (isa<GlobalAlias>(Arg) &&
4496 !cast<GlobalAlias>(Arg)->mayBeOverridden())
4497 Arg = cast<GlobalAlias>(Arg)->getAliasee();
4498 else
4499 break;
4500 }
4501 }
4502
Dan Gohman8ee108b2012-01-19 19:14:36 +00004503 // If this function has no escaping allocas or suspicious vararg usage,
4504 // objc_storeStrong calls can be marked with the "tail" keyword.
4505 if (TailOkForStoreStrongs)
Dan Gohman41375a32012-05-08 23:39:44 +00004506 for (SmallPtrSet<CallInst *, 8>::iterator I = StoreStrongCalls.begin(),
Dan Gohman8ee108b2012-01-19 19:14:36 +00004507 E = StoreStrongCalls.end(); I != E; ++I)
4508 (*I)->setTailCall();
4509 StoreStrongCalls.clear();
4510
John McCalld935e9c2011-06-15 23:37:01 +00004511 return Changed;
4512}
Michael Gottesman97e3df02013-01-14 00:35:14 +00004513
4514/// @}
4515///