blob: e93ca273b1149f03eb26238d9223503397b6803c [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 }
222 }
John McCalld935e9c2011-06-15 23:37:01 +0000223}
224
Michael Gottesman97e3df02013-01-14 00:35:14 +0000225/// \brief Test whether the given value is possible a reference-counted pointer.
John McCalld935e9c2011-06-15 23:37:01 +0000226static bool IsPotentialUse(const Value *Op) {
227 // Pointers to static or stack storage are not reference-counted pointers.
228 if (isa<Constant>(Op) || isa<AllocaInst>(Op))
229 return false;
230 // Special arguments are not reference-counted.
231 if (const Argument *Arg = dyn_cast<Argument>(Op))
232 if (Arg->hasByValAttr() ||
233 Arg->hasNestAttr() ||
234 Arg->hasStructRetAttr())
235 return false;
Dan Gohmanbd944b42011-12-14 19:10:53 +0000236 // Only consider values with pointer types.
237 // It seemes intuitive to exclude function pointer types as well, since
238 // functions are never reference-counted, however clang occasionally
239 // bitcasts reference-counted pointers to function-pointer type
240 // temporarily.
Chris Lattner229907c2011-07-18 04:54:35 +0000241 PointerType *Ty = dyn_cast<PointerType>(Op->getType());
Dan Gohmanbd944b42011-12-14 19:10:53 +0000242 if (!Ty)
John McCalld935e9c2011-06-15 23:37:01 +0000243 return false;
244 // Conservatively assume anything else is a potential use.
245 return true;
246}
247
Michael Gottesman4385edf2013-01-14 01:47:53 +0000248/// \brief Helper for GetInstructionClass. Determines what kind of construct CS
249/// is.
John McCalld935e9c2011-06-15 23:37:01 +0000250static InstructionClass GetCallSiteClass(ImmutableCallSite CS) {
251 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
252 I != E; ++I)
253 if (IsPotentialUse(*I))
254 return CS.onlyReadsMemory() ? IC_User : IC_CallOrUser;
255
256 return CS.onlyReadsMemory() ? IC_None : IC_Call;
257}
258
Michael Gottesman97e3df02013-01-14 00:35:14 +0000259/// \brief Determine if F is one of the special known Functions. If it isn't,
260/// return IC_CallOrUser.
John McCalld935e9c2011-06-15 23:37:01 +0000261static InstructionClass GetFunctionClass(const Function *F) {
262 Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
263
264 // No arguments.
265 if (AI == AE)
266 return StringSwitch<InstructionClass>(F->getName())
267 .Case("objc_autoreleasePoolPush", IC_AutoreleasepoolPush)
268 .Default(IC_CallOrUser);
269
270 // One argument.
271 const Argument *A0 = AI++;
272 if (AI == AE)
273 // Argument is a pointer.
Chris Lattner229907c2011-07-18 04:54:35 +0000274 if (PointerType *PTy = dyn_cast<PointerType>(A0->getType())) {
275 Type *ETy = PTy->getElementType();
John McCalld935e9c2011-06-15 23:37:01 +0000276 // Argument is i8*.
277 if (ETy->isIntegerTy(8))
278 return StringSwitch<InstructionClass>(F->getName())
279 .Case("objc_retain", IC_Retain)
280 .Case("objc_retainAutoreleasedReturnValue", IC_RetainRV)
281 .Case("objc_retainBlock", IC_RetainBlock)
282 .Case("objc_release", IC_Release)
283 .Case("objc_autorelease", IC_Autorelease)
284 .Case("objc_autoreleaseReturnValue", IC_AutoreleaseRV)
285 .Case("objc_autoreleasePoolPop", IC_AutoreleasepoolPop)
286 .Case("objc_retainedObject", IC_NoopCast)
287 .Case("objc_unretainedObject", IC_NoopCast)
288 .Case("objc_unretainedPointer", IC_NoopCast)
289 .Case("objc_retain_autorelease", IC_FusedRetainAutorelease)
290 .Case("objc_retainAutorelease", IC_FusedRetainAutorelease)
291 .Case("objc_retainAutoreleaseReturnValue",IC_FusedRetainAutoreleaseRV)
292 .Default(IC_CallOrUser);
293
294 // Argument is i8**
Chris Lattner229907c2011-07-18 04:54:35 +0000295 if (PointerType *Pte = dyn_cast<PointerType>(ETy))
John McCalld935e9c2011-06-15 23:37:01 +0000296 if (Pte->getElementType()->isIntegerTy(8))
297 return StringSwitch<InstructionClass>(F->getName())
298 .Case("objc_loadWeakRetained", IC_LoadWeakRetained)
299 .Case("objc_loadWeak", IC_LoadWeak)
300 .Case("objc_destroyWeak", IC_DestroyWeak)
301 .Default(IC_CallOrUser);
302 }
303
304 // Two arguments, first is i8**.
305 const Argument *A1 = AI++;
306 if (AI == AE)
Chris Lattner229907c2011-07-18 04:54:35 +0000307 if (PointerType *PTy = dyn_cast<PointerType>(A0->getType()))
308 if (PointerType *Pte = dyn_cast<PointerType>(PTy->getElementType()))
John McCalld935e9c2011-06-15 23:37:01 +0000309 if (Pte->getElementType()->isIntegerTy(8))
Chris Lattner229907c2011-07-18 04:54:35 +0000310 if (PointerType *PTy1 = dyn_cast<PointerType>(A1->getType())) {
311 Type *ETy1 = PTy1->getElementType();
John McCalld935e9c2011-06-15 23:37:01 +0000312 // Second argument is i8*
313 if (ETy1->isIntegerTy(8))
314 return StringSwitch<InstructionClass>(F->getName())
315 .Case("objc_storeWeak", IC_StoreWeak)
316 .Case("objc_initWeak", IC_InitWeak)
Dan Gohmane1e352a2012-04-13 18:28:58 +0000317 .Case("objc_storeStrong", IC_StoreStrong)
John McCalld935e9c2011-06-15 23:37:01 +0000318 .Default(IC_CallOrUser);
319 // Second argument is i8**.
Chris Lattner229907c2011-07-18 04:54:35 +0000320 if (PointerType *Pte1 = dyn_cast<PointerType>(ETy1))
John McCalld935e9c2011-06-15 23:37:01 +0000321 if (Pte1->getElementType()->isIntegerTy(8))
322 return StringSwitch<InstructionClass>(F->getName())
323 .Case("objc_moveWeak", IC_MoveWeak)
324 .Case("objc_copyWeak", IC_CopyWeak)
325 .Default(IC_CallOrUser);
326 }
327
328 // Anything else.
329 return IC_CallOrUser;
330}
331
Michael Gottesman97e3df02013-01-14 00:35:14 +0000332/// \brief Determine what kind of construct V is.
John McCalld935e9c2011-06-15 23:37:01 +0000333static InstructionClass GetInstructionClass(const Value *V) {
334 if (const Instruction *I = dyn_cast<Instruction>(V)) {
335 // Any instruction other than bitcast and gep with a pointer operand have a
336 // use of an objc pointer. Bitcasts, GEPs, Selects, PHIs transfer a pointer
337 // to a subsequent use, rather than using it themselves, in this sense.
338 // As a short cut, several other opcodes are known to have no pointer
339 // operands of interest. And ret is never followed by a release, so it's
340 // not interesting to examine.
341 switch (I->getOpcode()) {
342 case Instruction::Call: {
343 const CallInst *CI = cast<CallInst>(I);
344 // Check for calls to special functions.
345 if (const Function *F = CI->getCalledFunction()) {
346 InstructionClass Class = GetFunctionClass(F);
347 if (Class != IC_CallOrUser)
348 return Class;
349
350 // None of the intrinsic functions do objc_release. For intrinsics, the
351 // only question is whether or not they may be users.
352 switch (F->getIntrinsicID()) {
John McCalld935e9c2011-06-15 23:37:01 +0000353 case Intrinsic::returnaddress: case Intrinsic::frameaddress:
354 case Intrinsic::stacksave: case Intrinsic::stackrestore:
355 case Intrinsic::vastart: case Intrinsic::vacopy: case Intrinsic::vaend:
Dan Gohman41375a32012-05-08 23:39:44 +0000356 case Intrinsic::objectsize: case Intrinsic::prefetch:
357 case Intrinsic::stackprotector:
358 case Intrinsic::eh_return_i32: case Intrinsic::eh_return_i64:
359 case Intrinsic::eh_typeid_for: case Intrinsic::eh_dwarf_cfa:
360 case Intrinsic::eh_sjlj_lsda: case Intrinsic::eh_sjlj_functioncontext:
361 case Intrinsic::init_trampoline: case Intrinsic::adjust_trampoline:
362 case Intrinsic::lifetime_start: case Intrinsic::lifetime_end:
363 case Intrinsic::invariant_start: case Intrinsic::invariant_end:
John McCalld935e9c2011-06-15 23:37:01 +0000364 // Don't let dbg info affect our results.
365 case Intrinsic::dbg_declare: case Intrinsic::dbg_value:
366 // Short cut: Some intrinsics obviously don't use ObjC pointers.
367 return IC_None;
368 default:
Dan Gohman41375a32012-05-08 23:39:44 +0000369 break;
John McCalld935e9c2011-06-15 23:37:01 +0000370 }
371 }
372 return GetCallSiteClass(CI);
373 }
374 case Instruction::Invoke:
375 return GetCallSiteClass(cast<InvokeInst>(I));
376 case Instruction::BitCast:
377 case Instruction::GetElementPtr:
378 case Instruction::Select: case Instruction::PHI:
379 case Instruction::Ret: case Instruction::Br:
380 case Instruction::Switch: case Instruction::IndirectBr:
381 case Instruction::Alloca: case Instruction::VAArg:
382 case Instruction::Add: case Instruction::FAdd:
383 case Instruction::Sub: case Instruction::FSub:
384 case Instruction::Mul: case Instruction::FMul:
385 case Instruction::SDiv: case Instruction::UDiv: case Instruction::FDiv:
386 case Instruction::SRem: case Instruction::URem: case Instruction::FRem:
387 case Instruction::Shl: case Instruction::LShr: case Instruction::AShr:
388 case Instruction::And: case Instruction::Or: case Instruction::Xor:
389 case Instruction::SExt: case Instruction::ZExt: case Instruction::Trunc:
390 case Instruction::IntToPtr: case Instruction::FCmp:
391 case Instruction::FPTrunc: case Instruction::FPExt:
392 case Instruction::FPToUI: case Instruction::FPToSI:
393 case Instruction::UIToFP: case Instruction::SIToFP:
394 case Instruction::InsertElement: case Instruction::ExtractElement:
395 case Instruction::ShuffleVector:
396 case Instruction::ExtractValue:
397 break;
398 case Instruction::ICmp:
399 // Comparing a pointer with null, or any other constant, isn't an
400 // interesting use, because we don't care what the pointer points to, or
401 // about the values of any other dynamic reference-counted pointers.
402 if (IsPotentialUse(I->getOperand(1)))
403 return IC_User;
404 break;
405 default:
406 // For anything else, check all the operands.
Dan Gohman4b8e8ce2011-08-22 17:29:37 +0000407 // Note that this includes both operands of a Store: while the first
408 // operand isn't actually being dereferenced, it is being stored to
409 // memory where we can no longer track who might read it and dereference
410 // it, so we have to consider it potentially used.
John McCalld935e9c2011-06-15 23:37:01 +0000411 for (User::const_op_iterator OI = I->op_begin(), OE = I->op_end();
412 OI != OE; ++OI)
413 if (IsPotentialUse(*OI))
414 return IC_User;
415 }
416 }
417
418 // Otherwise, it's totally inert for ARC purposes.
419 return IC_None;
420}
421
Michael Gottesman97e3df02013-01-14 00:35:14 +0000422/// \brief Determine which objc runtime call instruction class V belongs to.
423///
424/// This is similar to GetInstructionClass except that it only detects objc
425/// runtime calls. This allows it to be faster.
426///
John McCalld935e9c2011-06-15 23:37:01 +0000427static InstructionClass GetBasicInstructionClass(const Value *V) {
428 if (const CallInst *CI = dyn_cast<CallInst>(V)) {
429 if (const Function *F = CI->getCalledFunction())
430 return GetFunctionClass(F);
431 // Otherwise, be conservative.
432 return IC_CallOrUser;
433 }
434
435 // Otherwise, be conservative.
Dan Gohmane7a243f2012-01-17 20:52:24 +0000436 return isa<InvokeInst>(V) ? IC_CallOrUser : IC_User;
John McCalld935e9c2011-06-15 23:37:01 +0000437}
438
Michael Gottesman97e3df02013-01-14 00:35:14 +0000439/// \brief Test if the given class is objc_retain or equivalent.
John McCalld935e9c2011-06-15 23:37:01 +0000440static bool IsRetain(InstructionClass Class) {
441 return Class == IC_Retain ||
442 Class == IC_RetainRV;
443}
444
Michael Gottesman97e3df02013-01-14 00:35:14 +0000445/// \brief Test if the given class is objc_autorelease or equivalent.
John McCalld935e9c2011-06-15 23:37:01 +0000446static bool IsAutorelease(InstructionClass Class) {
447 return Class == IC_Autorelease ||
448 Class == IC_AutoreleaseRV;
449}
450
Michael Gottesman97e3df02013-01-14 00:35:14 +0000451/// \brief Test if the given class represents instructions which return their
452/// argument verbatim.
John McCalld935e9c2011-06-15 23:37:01 +0000453static bool IsForwarding(InstructionClass Class) {
454 // objc_retainBlock technically doesn't always return its argument
455 // verbatim, but it doesn't matter for our purposes here.
456 return Class == IC_Retain ||
457 Class == IC_RetainRV ||
458 Class == IC_Autorelease ||
459 Class == IC_AutoreleaseRV ||
460 Class == IC_RetainBlock ||
461 Class == IC_NoopCast;
462}
463
Michael Gottesman97e3df02013-01-14 00:35:14 +0000464/// \brief Test if the given class represents instructions which do nothing if
465/// passed a null pointer.
John McCalld935e9c2011-06-15 23:37:01 +0000466static bool IsNoopOnNull(InstructionClass Class) {
467 return Class == IC_Retain ||
468 Class == IC_RetainRV ||
469 Class == IC_Release ||
470 Class == IC_Autorelease ||
471 Class == IC_AutoreleaseRV ||
472 Class == IC_RetainBlock;
473}
474
Michael Gottesman4385edf2013-01-14 01:47:53 +0000475/// \brief Test if the given class represents instructions which are always safe
476/// to mark with the "tail" keyword.
John McCalld935e9c2011-06-15 23:37:01 +0000477static bool IsAlwaysTail(InstructionClass Class) {
478 // IC_RetainBlock may be given a stack argument.
479 return Class == IC_Retain ||
480 Class == IC_RetainRV ||
John McCalld935e9c2011-06-15 23:37:01 +0000481 Class == IC_AutoreleaseRV;
482}
483
Michael Gottesmanc9656fa2013-01-12 01:25:15 +0000484/// \brief Test if the given class represents instructions which are never safe
485/// to mark with the "tail" keyword.
486static bool IsNeverTail(InstructionClass Class) {
487 /// It is never safe to tail call objc_autorelease since by tail calling
488 /// objc_autorelease, we also tail call -[NSObject autorelease] which supports
489 /// fast autoreleasing causing our object to be potentially reclaimed from the
490 /// autorelease pool which violates the semantics of __autoreleasing types in
491 /// ARC.
492 return Class == IC_Autorelease;
493}
494
Michael Gottesman97e3df02013-01-14 00:35:14 +0000495/// \brief Test if the given class represents instructions which are always safe
496/// to mark with the nounwind attribute.
John McCalld935e9c2011-06-15 23:37:01 +0000497static bool IsNoThrow(InstructionClass Class) {
Dan Gohmanfca43c22011-09-14 18:33:34 +0000498 // objc_retainBlock is not nounwind because it calls user copy constructors
499 // which could theoretically throw.
John McCalld935e9c2011-06-15 23:37:01 +0000500 return Class == IC_Retain ||
501 Class == IC_RetainRV ||
John McCalld935e9c2011-06-15 23:37:01 +0000502 Class == IC_Release ||
503 Class == IC_Autorelease ||
504 Class == IC_AutoreleaseRV ||
505 Class == IC_AutoreleasepoolPush ||
506 Class == IC_AutoreleasepoolPop;
507}
508
Michael Gottesman97e3df02013-01-14 00:35:14 +0000509/// \brief Erase the given instruction.
510///
511/// Many ObjC calls return their argument verbatim,
512/// so if it's such a call and the return value has users, replace them with the
513/// argument value.
514///
John McCalld935e9c2011-06-15 23:37:01 +0000515static void EraseInstruction(Instruction *CI) {
516 Value *OldArg = cast<CallInst>(CI)->getArgOperand(0);
517
518 bool Unused = CI->use_empty();
519
520 if (!Unused) {
521 // Replace the return value with the argument.
522 assert(IsForwarding(GetBasicInstructionClass(CI)) &&
523 "Can't delete non-forwarding instruction with users!");
524 CI->replaceAllUsesWith(OldArg);
525 }
526
527 CI->eraseFromParent();
528
529 if (Unused)
530 RecursivelyDeleteTriviallyDeadInstructions(OldArg);
531}
532
Michael Gottesman97e3df02013-01-14 00:35:14 +0000533/// \brief This is a wrapper around getUnderlyingObject which also knows how to
534/// look through objc_retain and objc_autorelease calls, which we know to return
535/// their argument verbatim.
John McCalld935e9c2011-06-15 23:37:01 +0000536static const Value *GetUnderlyingObjCPtr(const Value *V) {
537 for (;;) {
538 V = GetUnderlyingObject(V);
539 if (!IsForwarding(GetBasicInstructionClass(V)))
540 break;
541 V = cast<CallInst>(V)->getArgOperand(0);
542 }
543
544 return V;
545}
546
Michael Gottesman97e3df02013-01-14 00:35:14 +0000547/// \brief This is a wrapper around Value::stripPointerCasts which also knows
548/// how to look through objc_retain and objc_autorelease calls, which we know to
549/// return their argument verbatim.
John McCalld935e9c2011-06-15 23:37:01 +0000550static const Value *StripPointerCastsAndObjCCalls(const Value *V) {
551 for (;;) {
552 V = V->stripPointerCasts();
553 if (!IsForwarding(GetBasicInstructionClass(V)))
554 break;
555 V = cast<CallInst>(V)->getArgOperand(0);
556 }
557 return V;
558}
559
Michael Gottesman97e3df02013-01-14 00:35:14 +0000560/// \brief This is a wrapper around Value::stripPointerCasts which also knows
561/// how to look through objc_retain and objc_autorelease calls, which we know to
562/// return their argument verbatim.
John McCalld935e9c2011-06-15 23:37:01 +0000563static Value *StripPointerCastsAndObjCCalls(Value *V) {
564 for (;;) {
565 V = V->stripPointerCasts();
566 if (!IsForwarding(GetBasicInstructionClass(V)))
567 break;
568 V = cast<CallInst>(V)->getArgOperand(0);
569 }
570 return V;
571}
572
Michael Gottesman97e3df02013-01-14 00:35:14 +0000573/// \brief Assuming the given instruction is one of the special calls such as
574/// objc_retain or objc_release, return the argument value, stripped of no-op
John McCalld935e9c2011-06-15 23:37:01 +0000575/// casts and forwarding calls.
576static Value *GetObjCArg(Value *Inst) {
577 return StripPointerCastsAndObjCCalls(cast<CallInst>(Inst)->getArgOperand(0));
578}
579
Michael Gottesman97e3df02013-01-14 00:35:14 +0000580/// \brief This is similar to AliasAnalysis's isObjCIdentifiedObject, except
581/// that it uses special knowledge of ObjC conventions.
John McCalld935e9c2011-06-15 23:37:01 +0000582static bool IsObjCIdentifiedObject(const Value *V) {
583 // Assume that call results and arguments have their own "provenance".
584 // Constants (including GlobalVariables) and Allocas are never
585 // reference-counted.
586 if (isa<CallInst>(V) || isa<InvokeInst>(V) ||
587 isa<Argument>(V) || isa<Constant>(V) ||
588 isa<AllocaInst>(V))
589 return true;
590
591 if (const LoadInst *LI = dyn_cast<LoadInst>(V)) {
592 const Value *Pointer =
593 StripPointerCastsAndObjCCalls(LI->getPointerOperand());
594 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Pointer)) {
Dan Gohman56e1cef2011-08-22 17:29:11 +0000595 // A constant pointer can't be pointing to an object on the heap. It may
596 // be reference-counted, but it won't be deleted.
597 if (GV->isConstant())
598 return true;
John McCalld935e9c2011-06-15 23:37:01 +0000599 StringRef Name = GV->getName();
600 // These special variables are known to hold values which are not
601 // reference-counted pointers.
602 if (Name.startswith("\01L_OBJC_SELECTOR_REFERENCES_") ||
603 Name.startswith("\01L_OBJC_CLASSLIST_REFERENCES_") ||
604 Name.startswith("\01L_OBJC_CLASSLIST_SUP_REFS_$_") ||
605 Name.startswith("\01L_OBJC_METH_VAR_NAME_") ||
606 Name.startswith("\01l_objc_msgSend_fixup_"))
607 return true;
608 }
609 }
610
611 return false;
612}
613
Michael Gottesman97e3df02013-01-14 00:35:14 +0000614/// \brief This is similar to StripPointerCastsAndObjCCalls but it stops as soon
615/// as it finds a value with multiple uses.
John McCalld935e9c2011-06-15 23:37:01 +0000616static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
617 if (Arg->hasOneUse()) {
618 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
619 return FindSingleUseIdentifiedObject(BC->getOperand(0));
620 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
621 if (GEP->hasAllZeroIndices())
622 return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
623 if (IsForwarding(GetBasicInstructionClass(Arg)))
624 return FindSingleUseIdentifiedObject(
625 cast<CallInst>(Arg)->getArgOperand(0));
626 if (!IsObjCIdentifiedObject(Arg))
627 return 0;
628 return Arg;
629 }
630
Dan Gohman41375a32012-05-08 23:39:44 +0000631 // If we found an identifiable object but it has multiple uses, but they are
632 // trivial uses, we can still consider this to be a single-use value.
John McCalld935e9c2011-06-15 23:37:01 +0000633 if (IsObjCIdentifiedObject(Arg)) {
634 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
635 UI != UE; ++UI) {
636 const User *U = *UI;
637 if (!U->use_empty() || StripPointerCastsAndObjCCalls(U) != Arg)
638 return 0;
639 }
640
641 return Arg;
642 }
643
644 return 0;
645}
646
Michael Gottesman97e3df02013-01-14 00:35:14 +0000647/// \brief Test if the given module looks interesting to run ARC optimization
648/// on.
Dan Gohmanceaac7c2011-06-20 23:20:43 +0000649static bool ModuleHasARC(const Module &M) {
650 return
651 M.getNamedValue("objc_retain") ||
652 M.getNamedValue("objc_release") ||
653 M.getNamedValue("objc_autorelease") ||
654 M.getNamedValue("objc_retainAutoreleasedReturnValue") ||
655 M.getNamedValue("objc_retainBlock") ||
656 M.getNamedValue("objc_autoreleaseReturnValue") ||
657 M.getNamedValue("objc_autoreleasePoolPush") ||
658 M.getNamedValue("objc_loadWeakRetained") ||
659 M.getNamedValue("objc_loadWeak") ||
660 M.getNamedValue("objc_destroyWeak") ||
661 M.getNamedValue("objc_storeWeak") ||
662 M.getNamedValue("objc_initWeak") ||
663 M.getNamedValue("objc_moveWeak") ||
664 M.getNamedValue("objc_copyWeak") ||
665 M.getNamedValue("objc_retainedObject") ||
666 M.getNamedValue("objc_unretainedObject") ||
667 M.getNamedValue("objc_unretainedPointer");
668}
669
Michael Gottesman4385edf2013-01-14 01:47:53 +0000670/// \brief Test whether the given pointer, which is an Objective C block
671/// pointer, does not "escape".
Michael Gottesman97e3df02013-01-14 00:35:14 +0000672///
673/// This differs from regular escape analysis in that a use as an
674/// argument to a call is not considered an escape.
675///
Dan Gohman728db492012-01-13 00:39:07 +0000676static bool DoesObjCBlockEscape(const Value *BlockPtr) {
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000677
678 DEBUG(dbgs() << "DoesObjCBlockEscape: Target: " << *BlockPtr << "\n");
679
Dan Gohman728db492012-01-13 00:39:07 +0000680 // Walk the def-use chains.
681 SmallVector<const Value *, 4> Worklist;
682 Worklist.push_back(BlockPtr);
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000683
684 // Ensure we do not visit any value twice.
685 SmallPtrSet<const Value *, 4> VisitedSet;
686
Dan Gohman728db492012-01-13 00:39:07 +0000687 do {
688 const Value *V = Worklist.pop_back_val();
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000689
690 DEBUG(dbgs() << "DoesObjCBlockEscape: Visiting: " << *V << "\n");
691
Dan Gohman728db492012-01-13 00:39:07 +0000692 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
693 UI != UE; ++UI) {
694 const User *UUser = *UI;
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000695
696 DEBUG(dbgs() << "DoesObjCBlockEscape: User: " << *UUser << "\n");
697
Dan Gohman728db492012-01-13 00:39:07 +0000698 // Special - Use by a call (callee or argument) is not considered
699 // to be an escape.
Dan Gohmane1e352a2012-04-13 18:28:58 +0000700 switch (GetBasicInstructionClass(UUser)) {
701 case IC_StoreWeak:
702 case IC_InitWeak:
703 case IC_StoreStrong:
704 case IC_Autorelease:
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000705 case IC_AutoreleaseRV: {
706 DEBUG(dbgs() << "DoesObjCBlockEscape: User copies pointer arguments. "
707 "Block Escapes!\n");
Dan Gohmane1e352a2012-04-13 18:28:58 +0000708 // These special functions make copies of their pointer arguments.
709 return true;
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000710 }
Dan Gohmane1e352a2012-04-13 18:28:58 +0000711 case IC_User:
712 case IC_None:
713 // Use by an instruction which copies the value is an escape if the
714 // result is an escape.
715 if (isa<BitCastInst>(UUser) || isa<GetElementPtrInst>(UUser) ||
716 isa<PHINode>(UUser) || isa<SelectInst>(UUser)) {
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000717
Michael Gottesmane9145d32013-01-14 19:18:39 +0000718 if (!VisitedSet.insert(UUser)) {
Michael Gottesman4385edf2013-01-14 01:47:53 +0000719 DEBUG(dbgs() << "DoesObjCBlockEscape: User copies value. Escapes "
720 "if result escapes. Adding to list.\n");
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000721 Worklist.push_back(UUser);
722 } else {
723 DEBUG(dbgs() << "DoesObjCBlockEscape: Already visited node.\n");
724 }
Dan Gohmane1e352a2012-04-13 18:28:58 +0000725 continue;
726 }
727 // Use by a load is not an escape.
728 if (isa<LoadInst>(UUser))
729 continue;
730 // Use by a store is not an escape if the use is the address.
731 if (const StoreInst *SI = dyn_cast<StoreInst>(UUser))
732 if (V != SI->getValueOperand())
733 continue;
734 break;
735 default:
736 // Regular calls and other stuff are not considered escapes.
Dan Gohman728db492012-01-13 00:39:07 +0000737 continue;
738 }
Dan Gohmaneb6e0152012-02-13 22:57:02 +0000739 // Otherwise, conservatively assume an escape.
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000740 DEBUG(dbgs() << "DoesObjCBlockEscape: Assuming block escapes.\n");
Dan Gohman728db492012-01-13 00:39:07 +0000741 return true;
742 }
743 } while (!Worklist.empty());
744
745 // No escapes found.
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000746 DEBUG(dbgs() << "DoesObjCBlockEscape: Block does not escape.\n");
Dan Gohman728db492012-01-13 00:39:07 +0000747 return false;
748}
749
Michael Gottesman97e3df02013-01-14 00:35:14 +0000750/// @}
751///
Michael Gottesman4385edf2013-01-14 01:47:53 +0000752/// \defgroup ARCAA Extends alias analysis using ObjC specific knowledge.
Michael Gottesman97e3df02013-01-14 00:35:14 +0000753/// @{
John McCalld935e9c2011-06-15 23:37:01 +0000754
John McCalld935e9c2011-06-15 23:37:01 +0000755#include "llvm/Analysis/AliasAnalysis.h"
756#include "llvm/Analysis/Passes.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +0000757#include "llvm/Pass.h"
John McCalld935e9c2011-06-15 23:37:01 +0000758
759namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000760 /// \brief This is a simple alias analysis implementation that uses knowledge
761 /// of ARC constructs to answer queries.
John McCalld935e9c2011-06-15 23:37:01 +0000762 ///
763 /// TODO: This class could be generalized to know about other ObjC-specific
764 /// tricks. Such as knowing that ivars in the non-fragile ABI are non-aliasing
765 /// even though their offsets are dynamic.
766 class ObjCARCAliasAnalysis : public ImmutablePass,
767 public AliasAnalysis {
768 public:
769 static char ID; // Class identification, replacement for typeinfo
770 ObjCARCAliasAnalysis() : ImmutablePass(ID) {
771 initializeObjCARCAliasAnalysisPass(*PassRegistry::getPassRegistry());
772 }
773
774 private:
775 virtual void initializePass() {
776 InitializeAliasAnalysis(this);
777 }
778
Michael Gottesman97e3df02013-01-14 00:35:14 +0000779 /// This method is used when a pass implements an analysis interface through
780 /// multiple inheritance. If needed, it should override this to adjust the
781 /// this pointer as needed for the specified pass info.
John McCalld935e9c2011-06-15 23:37:01 +0000782 virtual void *getAdjustedAnalysisPointer(const void *PI) {
783 if (PI == &AliasAnalysis::ID)
Dan Gohmandae33492012-04-27 18:56:31 +0000784 return static_cast<AliasAnalysis *>(this);
John McCalld935e9c2011-06-15 23:37:01 +0000785 return this;
786 }
787
788 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
789 virtual AliasResult alias(const Location &LocA, const Location &LocB);
790 virtual bool pointsToConstantMemory(const Location &Loc, bool OrLocal);
791 virtual ModRefBehavior getModRefBehavior(ImmutableCallSite CS);
792 virtual ModRefBehavior getModRefBehavior(const Function *F);
793 virtual ModRefResult getModRefInfo(ImmutableCallSite CS,
794 const Location &Loc);
795 virtual ModRefResult getModRefInfo(ImmutableCallSite CS1,
796 ImmutableCallSite CS2);
797 };
798} // End of anonymous namespace
799
800// Register this pass...
801char ObjCARCAliasAnalysis::ID = 0;
802INITIALIZE_AG_PASS(ObjCARCAliasAnalysis, AliasAnalysis, "objc-arc-aa",
803 "ObjC-ARC-Based Alias Analysis", false, true, false)
804
805ImmutablePass *llvm::createObjCARCAliasAnalysisPass() {
806 return new ObjCARCAliasAnalysis();
807}
808
809void
810ObjCARCAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
811 AU.setPreservesAll();
812 AliasAnalysis::getAnalysisUsage(AU);
813}
814
815AliasAnalysis::AliasResult
816ObjCARCAliasAnalysis::alias(const Location &LocA, const Location &LocB) {
817 if (!EnableARCOpts)
818 return AliasAnalysis::alias(LocA, LocB);
819
820 // First, strip off no-ops, including ObjC-specific no-ops, and try making a
821 // precise alias query.
822 const Value *SA = StripPointerCastsAndObjCCalls(LocA.Ptr);
823 const Value *SB = StripPointerCastsAndObjCCalls(LocB.Ptr);
824 AliasResult Result =
825 AliasAnalysis::alias(Location(SA, LocA.Size, LocA.TBAATag),
826 Location(SB, LocB.Size, LocB.TBAATag));
827 if (Result != MayAlias)
828 return Result;
829
830 // If that failed, climb to the underlying object, including climbing through
831 // ObjC-specific no-ops, and try making an imprecise alias query.
832 const Value *UA = GetUnderlyingObjCPtr(SA);
833 const Value *UB = GetUnderlyingObjCPtr(SB);
834 if (UA != SA || UB != SB) {
835 Result = AliasAnalysis::alias(Location(UA), Location(UB));
836 // We can't use MustAlias or PartialAlias results here because
837 // GetUnderlyingObjCPtr may return an offsetted pointer value.
838 if (Result == NoAlias)
839 return NoAlias;
840 }
841
842 // If that failed, fail. We don't need to chain here, since that's covered
843 // by the earlier precise query.
844 return MayAlias;
845}
846
847bool
848ObjCARCAliasAnalysis::pointsToConstantMemory(const Location &Loc,
849 bool OrLocal) {
850 if (!EnableARCOpts)
851 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
852
853 // First, strip off no-ops, including ObjC-specific no-ops, and try making
854 // a precise alias query.
855 const Value *S = StripPointerCastsAndObjCCalls(Loc.Ptr);
856 if (AliasAnalysis::pointsToConstantMemory(Location(S, Loc.Size, Loc.TBAATag),
857 OrLocal))
858 return true;
859
860 // If that failed, climb to the underlying object, including climbing through
861 // ObjC-specific no-ops, and try making an imprecise alias query.
862 const Value *U = GetUnderlyingObjCPtr(S);
863 if (U != S)
864 return AliasAnalysis::pointsToConstantMemory(Location(U), OrLocal);
865
866 // If that failed, fail. We don't need to chain here, since that's covered
867 // by the earlier precise query.
868 return false;
869}
870
871AliasAnalysis::ModRefBehavior
872ObjCARCAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
873 // We have nothing to do. Just chain to the next AliasAnalysis.
874 return AliasAnalysis::getModRefBehavior(CS);
875}
876
877AliasAnalysis::ModRefBehavior
878ObjCARCAliasAnalysis::getModRefBehavior(const Function *F) {
879 if (!EnableARCOpts)
880 return AliasAnalysis::getModRefBehavior(F);
881
882 switch (GetFunctionClass(F)) {
883 case IC_NoopCast:
884 return DoesNotAccessMemory;
885 default:
886 break;
887 }
888
889 return AliasAnalysis::getModRefBehavior(F);
890}
891
892AliasAnalysis::ModRefResult
893ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS, const Location &Loc) {
894 if (!EnableARCOpts)
895 return AliasAnalysis::getModRefInfo(CS, Loc);
896
897 switch (GetBasicInstructionClass(CS.getInstruction())) {
898 case IC_Retain:
899 case IC_RetainRV:
John McCalld935e9c2011-06-15 23:37:01 +0000900 case IC_Autorelease:
901 case IC_AutoreleaseRV:
902 case IC_NoopCast:
903 case IC_AutoreleasepoolPush:
904 case IC_FusedRetainAutorelease:
905 case IC_FusedRetainAutoreleaseRV:
906 // These functions don't access any memory visible to the compiler.
Benjamin Kramerbde91762012-06-02 10:20:22 +0000907 // Note that this doesn't include objc_retainBlock, because it updates
Dan Gohmand4b5e3a2011-09-14 18:13:00 +0000908 // pointers when it copies block data.
John McCalld935e9c2011-06-15 23:37:01 +0000909 return NoModRef;
910 default:
911 break;
912 }
913
914 return AliasAnalysis::getModRefInfo(CS, Loc);
915}
916
917AliasAnalysis::ModRefResult
918ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
919 ImmutableCallSite CS2) {
920 // TODO: Theoretically we could check for dependencies between objc_* calls
921 // and OnlyAccessesArgumentPointees calls or other well-behaved calls.
922 return AliasAnalysis::getModRefInfo(CS1, CS2);
923}
924
Michael Gottesman97e3df02013-01-14 00:35:14 +0000925/// @}
926///
927/// \defgroup ARCExpansion Early ARC Optimizations.
928/// @{
John McCalld935e9c2011-06-15 23:37:01 +0000929
930#include "llvm/Support/InstIterator.h"
931#include "llvm/Transforms/Scalar.h"
932
933namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000934 /// \brief Early ARC transformations.
John McCalld935e9c2011-06-15 23:37:01 +0000935 class ObjCARCExpand : public FunctionPass {
936 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Dan Gohmanceaac7c2011-06-20 23:20:43 +0000937 virtual bool doInitialization(Module &M);
John McCalld935e9c2011-06-15 23:37:01 +0000938 virtual bool runOnFunction(Function &F);
939
Michael Gottesman97e3df02013-01-14 00:35:14 +0000940 /// A flag indicating whether this optimization pass should run.
Dan Gohmanceaac7c2011-06-20 23:20:43 +0000941 bool Run;
942
John McCalld935e9c2011-06-15 23:37:01 +0000943 public:
944 static char ID;
945 ObjCARCExpand() : FunctionPass(ID) {
946 initializeObjCARCExpandPass(*PassRegistry::getPassRegistry());
947 }
948 };
949}
950
951char ObjCARCExpand::ID = 0;
952INITIALIZE_PASS(ObjCARCExpand,
953 "objc-arc-expand", "ObjC ARC expansion", false, false)
954
955Pass *llvm::createObjCARCExpandPass() {
956 return new ObjCARCExpand();
957}
958
959void ObjCARCExpand::getAnalysisUsage(AnalysisUsage &AU) const {
960 AU.setPreservesCFG();
961}
962
Dan Gohmanceaac7c2011-06-20 23:20:43 +0000963bool ObjCARCExpand::doInitialization(Module &M) {
964 Run = ModuleHasARC(M);
965 return false;
966}
967
John McCalld935e9c2011-06-15 23:37:01 +0000968bool ObjCARCExpand::runOnFunction(Function &F) {
969 if (!EnableARCOpts)
970 return false;
971
Dan Gohmanceaac7c2011-06-20 23:20:43 +0000972 // If nothing in the Module uses ARC, don't do anything.
973 if (!Run)
974 return false;
975
John McCalld935e9c2011-06-15 23:37:01 +0000976 bool Changed = false;
977
Michael Gottesmanaf2113f2013-01-13 07:00:51 +0000978 DEBUG(dbgs() << "ObjCARCExpand: Visiting Function: " << F.getName() << "\n");
979
John McCalld935e9c2011-06-15 23:37:01 +0000980 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
981 Instruction *Inst = &*I;
Michael Gottesman10426b52013-01-07 21:26:07 +0000982
Michael Gottesman3f146e22013-01-01 16:05:48 +0000983 DEBUG(dbgs() << "ObjCARCExpand: Visiting: " << *Inst << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +0000984
John McCalld935e9c2011-06-15 23:37:01 +0000985 switch (GetBasicInstructionClass(Inst)) {
986 case IC_Retain:
987 case IC_RetainRV:
988 case IC_Autorelease:
989 case IC_AutoreleaseRV:
990 case IC_FusedRetainAutorelease:
Michael Gottesmanc8a11df2013-01-01 16:05:54 +0000991 case IC_FusedRetainAutoreleaseRV: {
John McCalld935e9c2011-06-15 23:37:01 +0000992 // These calls return their argument verbatim, as a low-level
993 // optimization. However, this makes high-level optimizations
994 // harder. Undo any uses of this optimization that the front-end
Dan Gohman670f9372012-04-13 18:57:48 +0000995 // emitted here. We'll redo them in the contract pass.
John McCalld935e9c2011-06-15 23:37:01 +0000996 Changed = true;
Michael Gottesmanc8a11df2013-01-01 16:05:54 +0000997 Value *Value = cast<CallInst>(Inst)->getArgOperand(0);
998 DEBUG(dbgs() << "ObjCARCExpand: Old = " << *Inst << "\n"
999 " New = " << *Value << "\n");
1000 Inst->replaceAllUsesWith(Value);
John McCalld935e9c2011-06-15 23:37:01 +00001001 break;
Michael Gottesmanc8a11df2013-01-01 16:05:54 +00001002 }
John McCalld935e9c2011-06-15 23:37:01 +00001003 default:
1004 break;
1005 }
1006 }
Michael Gottesman10426b52013-01-07 21:26:07 +00001007
Michael Gottesman50ae5b22013-01-03 08:09:27 +00001008 DEBUG(dbgs() << "ObjCARCExpand: Finished List.\n\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001009
John McCalld935e9c2011-06-15 23:37:01 +00001010 return Changed;
1011}
1012
Michael Gottesman97e3df02013-01-14 00:35:14 +00001013/// @}
1014///
1015/// \defgroup ARCAPElim ARC Autorelease Pool Elimination.
1016/// @{
Dan Gohmane7a243f2012-01-17 20:52:24 +00001017
Dan Gohman41375a32012-05-08 23:39:44 +00001018#include "llvm/ADT/STLExtras.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +00001019#include "llvm/IR/Constants.h"
Dan Gohman82041c22012-01-18 21:19:38 +00001020
Dan Gohmane7a243f2012-01-17 20:52:24 +00001021namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001022 /// \brief Autorelease pool elimination.
Dan Gohmane7a243f2012-01-17 20:52:24 +00001023 class ObjCARCAPElim : public ModulePass {
1024 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1025 virtual bool runOnModule(Module &M);
1026
Dan Gohmandae33492012-04-27 18:56:31 +00001027 static bool MayAutorelease(ImmutableCallSite CS, unsigned Depth = 0);
1028 static bool OptimizeBB(BasicBlock *BB);
Dan Gohmane7a243f2012-01-17 20:52:24 +00001029
1030 public:
1031 static char ID;
1032 ObjCARCAPElim() : ModulePass(ID) {
1033 initializeObjCARCAPElimPass(*PassRegistry::getPassRegistry());
1034 }
1035 };
1036}
1037
1038char ObjCARCAPElim::ID = 0;
1039INITIALIZE_PASS(ObjCARCAPElim,
1040 "objc-arc-apelim",
1041 "ObjC ARC autorelease pool elimination",
1042 false, false)
1043
1044Pass *llvm::createObjCARCAPElimPass() {
1045 return new ObjCARCAPElim();
1046}
1047
1048void ObjCARCAPElim::getAnalysisUsage(AnalysisUsage &AU) const {
1049 AU.setPreservesCFG();
1050}
1051
Michael Gottesman97e3df02013-01-14 00:35:14 +00001052/// Interprocedurally determine if calls made by the given call site can
1053/// possibly produce autoreleases.
Dan Gohmandae33492012-04-27 18:56:31 +00001054bool ObjCARCAPElim::MayAutorelease(ImmutableCallSite CS, unsigned Depth) {
1055 if (const Function *Callee = CS.getCalledFunction()) {
Dan Gohmane7a243f2012-01-17 20:52:24 +00001056 if (Callee->isDeclaration() || Callee->mayBeOverridden())
1057 return true;
Dan Gohmandae33492012-04-27 18:56:31 +00001058 for (Function::const_iterator I = Callee->begin(), E = Callee->end();
Dan Gohmane7a243f2012-01-17 20:52:24 +00001059 I != E; ++I) {
Dan Gohmandae33492012-04-27 18:56:31 +00001060 const BasicBlock *BB = I;
1061 for (BasicBlock::const_iterator J = BB->begin(), F = BB->end();
1062 J != F; ++J)
1063 if (ImmutableCallSite JCS = ImmutableCallSite(J))
Dan Gohman8f12fae2012-01-18 21:24:45 +00001064 // This recursion depth limit is arbitrary. It's just great
1065 // enough to cover known interesting testcases.
1066 if (Depth < 3 &&
1067 !JCS.onlyReadsMemory() &&
1068 MayAutorelease(JCS, Depth + 1))
Dan Gohmane7a243f2012-01-17 20:52:24 +00001069 return true;
1070 }
1071 return false;
1072 }
1073
1074 return true;
1075}
1076
1077bool ObjCARCAPElim::OptimizeBB(BasicBlock *BB) {
1078 bool Changed = false;
1079
1080 Instruction *Push = 0;
1081 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1082 Instruction *Inst = I++;
1083 switch (GetBasicInstructionClass(Inst)) {
1084 case IC_AutoreleasepoolPush:
1085 Push = Inst;
1086 break;
1087 case IC_AutoreleasepoolPop:
1088 // If this pop matches a push and nothing in between can autorelease,
1089 // zap the pair.
1090 if (Push && cast<CallInst>(Inst)->getArgOperand(0) == Push) {
1091 Changed = true;
Michael Gottesman4385edf2013-01-14 01:47:53 +00001092 DEBUG(dbgs() << "ObjCARCAPElim::OptimizeBB: Zapping push pop "
1093 "autorelease pair:\n"
1094 " Pop: " << *Inst << "\n"
Michael Gottesmanef682c52013-01-03 08:09:17 +00001095 << " Push: " << *Push << "\n");
Dan Gohmane7a243f2012-01-17 20:52:24 +00001096 Inst->eraseFromParent();
1097 Push->eraseFromParent();
1098 }
1099 Push = 0;
1100 break;
1101 case IC_CallOrUser:
Dan Gohmandae33492012-04-27 18:56:31 +00001102 if (MayAutorelease(ImmutableCallSite(Inst)))
Dan Gohmane7a243f2012-01-17 20:52:24 +00001103 Push = 0;
1104 break;
1105 default:
1106 break;
1107 }
1108 }
1109
1110 return Changed;
1111}
1112
1113bool ObjCARCAPElim::runOnModule(Module &M) {
1114 if (!EnableARCOpts)
1115 return false;
1116
1117 // If nothing in the Module uses ARC, don't do anything.
1118 if (!ModuleHasARC(M))
1119 return false;
1120
Dan Gohman82041c22012-01-18 21:19:38 +00001121 // Find the llvm.global_ctors variable, as the first step in
Dan Gohman670f9372012-04-13 18:57:48 +00001122 // identifying the global constructors. In theory, unnecessary autorelease
1123 // pools could occur anywhere, but in practice it's pretty rare. Global
1124 // ctors are a place where autorelease pools get inserted automatically,
1125 // so it's pretty common for them to be unnecessary, and it's pretty
1126 // profitable to eliminate them.
Dan Gohman82041c22012-01-18 21:19:38 +00001127 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1128 if (!GV)
1129 return false;
1130
1131 assert(GV->hasDefinitiveInitializer() &&
1132 "llvm.global_ctors is uncooperative!");
1133
Dan Gohmane7a243f2012-01-17 20:52:24 +00001134 bool Changed = false;
1135
Dan Gohman82041c22012-01-18 21:19:38 +00001136 // Dig the constructor functions out of GV's initializer.
1137 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
1138 for (User::op_iterator OI = Init->op_begin(), OE = Init->op_end();
1139 OI != OE; ++OI) {
1140 Value *Op = *OI;
1141 // llvm.global_ctors is an array of pairs where the second members
1142 // are constructor functions.
Dan Gohman22fbe8d2012-04-18 22:24:33 +00001143 Function *F = dyn_cast<Function>(cast<ConstantStruct>(Op)->getOperand(1));
1144 // If the user used a constructor function with the wrong signature and
1145 // it got bitcasted or whatever, look the other way.
1146 if (!F)
1147 continue;
Dan Gohmane7a243f2012-01-17 20:52:24 +00001148 // Only look at function definitions.
1149 if (F->isDeclaration())
1150 continue;
Dan Gohmane7a243f2012-01-17 20:52:24 +00001151 // Only look at functions with one basic block.
1152 if (llvm::next(F->begin()) != F->end())
1153 continue;
1154 // Ok, a single-block constructor function definition. Try to optimize it.
1155 Changed |= OptimizeBB(F->begin());
1156 }
1157
1158 return Changed;
1159}
1160
Michael Gottesman97e3df02013-01-14 00:35:14 +00001161/// @}
1162///
1163/// \defgroup ARCOpt ARC Optimization.
1164/// @{
John McCalld935e9c2011-06-15 23:37:01 +00001165
1166// TODO: On code like this:
1167//
1168// objc_retain(%x)
1169// stuff_that_cannot_release()
1170// objc_autorelease(%x)
1171// stuff_that_cannot_release()
1172// objc_retain(%x)
1173// stuff_that_cannot_release()
1174// objc_autorelease(%x)
1175//
1176// The second retain and autorelease can be deleted.
1177
1178// TODO: It should be possible to delete
1179// objc_autoreleasePoolPush and objc_autoreleasePoolPop
1180// pairs if nothing is actually autoreleased between them. Also, autorelease
1181// calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
1182// after inlining) can be turned into plain release calls.
1183
1184// TODO: Critical-edge splitting. If the optimial insertion point is
1185// a critical edge, the current algorithm has to fail, because it doesn't
1186// know how to split edges. It should be possible to make the optimizer
1187// think in terms of edges, rather than blocks, and then split critical
1188// edges on demand.
1189
1190// TODO: OptimizeSequences could generalized to be Interprocedural.
1191
1192// TODO: Recognize that a bunch of other objc runtime calls have
1193// non-escaping arguments and non-releasing arguments, and may be
1194// non-autoreleasing.
1195
1196// TODO: Sink autorelease calls as far as possible. Unfortunately we
1197// usually can't sink them past other calls, which would be the main
1198// case where it would be useful.
1199
Dan Gohmanb3894012011-08-19 00:26:36 +00001200// TODO: The pointer returned from objc_loadWeakRetained is retained.
1201
1202// TODO: Delete release+retain pairs (rare).
Dan Gohmanceaac7c2011-06-20 23:20:43 +00001203
Chandler Carruthed0881b2012-12-03 16:50:05 +00001204#include "llvm/ADT/SmallPtrSet.h"
1205#include "llvm/ADT/Statistic.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +00001206#include "llvm/IR/LLVMContext.h"
John McCalld935e9c2011-06-15 23:37:01 +00001207#include "llvm/Support/CFG.h"
John McCalld935e9c2011-06-15 23:37:01 +00001208
1209STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
1210STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
1211STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
1212STATISTIC(NumRets, "Number of return value forwarding "
1213 "retain+autoreleaes eliminated");
1214STATISTIC(NumRRs, "Number of retain+release paths eliminated");
1215STATISTIC(NumPeeps, "Number of calls peephole-optimized");
1216
1217namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001218 /// \brief This is similar to BasicAliasAnalysis, and it uses many of the same
1219 /// techniques, except it uses special ObjC-specific reasoning about pointer
1220 /// relationships.
John McCalld935e9c2011-06-15 23:37:01 +00001221 class ProvenanceAnalysis {
1222 AliasAnalysis *AA;
1223
1224 typedef std::pair<const Value *, const Value *> ValuePairTy;
1225 typedef DenseMap<ValuePairTy, bool> CachedResultsTy;
1226 CachedResultsTy CachedResults;
1227
1228 bool relatedCheck(const Value *A, const Value *B);
1229 bool relatedSelect(const SelectInst *A, const Value *B);
1230 bool relatedPHI(const PHINode *A, const Value *B);
1231
Craig Topperb1d83e82012-09-18 02:01:41 +00001232 void operator=(const ProvenanceAnalysis &) LLVM_DELETED_FUNCTION;
1233 ProvenanceAnalysis(const ProvenanceAnalysis &) LLVM_DELETED_FUNCTION;
John McCalld935e9c2011-06-15 23:37:01 +00001234
1235 public:
1236 ProvenanceAnalysis() {}
1237
1238 void setAA(AliasAnalysis *aa) { AA = aa; }
1239
1240 AliasAnalysis *getAA() const { return AA; }
1241
1242 bool related(const Value *A, const Value *B);
1243
1244 void clear() {
1245 CachedResults.clear();
1246 }
1247 };
1248}
1249
1250bool ProvenanceAnalysis::relatedSelect(const SelectInst *A, const Value *B) {
1251 // If the values are Selects with the same condition, we can do a more precise
1252 // check: just check for relations between the values on corresponding arms.
1253 if (const SelectInst *SB = dyn_cast<SelectInst>(B))
Dan Gohmandae33492012-04-27 18:56:31 +00001254 if (A->getCondition() == SB->getCondition())
1255 return related(A->getTrueValue(), SB->getTrueValue()) ||
1256 related(A->getFalseValue(), SB->getFalseValue());
John McCalld935e9c2011-06-15 23:37:01 +00001257
1258 // Check both arms of the Select node individually.
Dan Gohmandae33492012-04-27 18:56:31 +00001259 return related(A->getTrueValue(), B) ||
1260 related(A->getFalseValue(), B);
John McCalld935e9c2011-06-15 23:37:01 +00001261}
1262
1263bool ProvenanceAnalysis::relatedPHI(const PHINode *A, const Value *B) {
1264 // If the values are PHIs in the same block, we can do a more precise as well
1265 // as efficient check: just check for relations between the values on
1266 // corresponding edges.
1267 if (const PHINode *PNB = dyn_cast<PHINode>(B))
1268 if (PNB->getParent() == A->getParent()) {
1269 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i)
1270 if (related(A->getIncomingValue(i),
1271 PNB->getIncomingValueForBlock(A->getIncomingBlock(i))))
1272 return true;
1273 return false;
1274 }
1275
1276 // Check each unique source of the PHI node against B.
1277 SmallPtrSet<const Value *, 4> UniqueSrc;
1278 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i) {
1279 const Value *PV1 = A->getIncomingValue(i);
1280 if (UniqueSrc.insert(PV1) && related(PV1, B))
1281 return true;
1282 }
1283
1284 // All of the arms checked out.
1285 return false;
1286}
1287
Michael Gottesman97e3df02013-01-14 00:35:14 +00001288/// Test if the value of P, or any value covered by its provenance, is ever
1289/// stored within the function (not counting callees).
John McCalld935e9c2011-06-15 23:37:01 +00001290static bool isStoredObjCPointer(const Value *P) {
1291 SmallPtrSet<const Value *, 8> Visited;
1292 SmallVector<const Value *, 8> Worklist;
1293 Worklist.push_back(P);
1294 Visited.insert(P);
1295 do {
1296 P = Worklist.pop_back_val();
1297 for (Value::const_use_iterator UI = P->use_begin(), UE = P->use_end();
1298 UI != UE; ++UI) {
1299 const User *Ur = *UI;
1300 if (isa<StoreInst>(Ur)) {
1301 if (UI.getOperandNo() == 0)
1302 // The pointer is stored.
1303 return true;
1304 // The pointed is stored through.
1305 continue;
1306 }
1307 if (isa<CallInst>(Ur))
1308 // The pointer is passed as an argument, ignore this.
1309 continue;
1310 if (isa<PtrToIntInst>(P))
1311 // Assume the worst.
1312 return true;
1313 if (Visited.insert(Ur))
1314 Worklist.push_back(Ur);
1315 }
1316 } while (!Worklist.empty());
1317
1318 // Everything checked out.
1319 return false;
1320}
1321
1322bool ProvenanceAnalysis::relatedCheck(const Value *A, const Value *B) {
1323 // Skip past provenance pass-throughs.
1324 A = GetUnderlyingObjCPtr(A);
1325 B = GetUnderlyingObjCPtr(B);
1326
1327 // Quick check.
1328 if (A == B)
1329 return true;
1330
1331 // Ask regular AliasAnalysis, for a first approximation.
1332 switch (AA->alias(A, B)) {
1333 case AliasAnalysis::NoAlias:
1334 return false;
1335 case AliasAnalysis::MustAlias:
1336 case AliasAnalysis::PartialAlias:
1337 return true;
1338 case AliasAnalysis::MayAlias:
1339 break;
1340 }
1341
1342 bool AIsIdentified = IsObjCIdentifiedObject(A);
1343 bool BIsIdentified = IsObjCIdentifiedObject(B);
1344
1345 // An ObjC-Identified object can't alias a load if it is never locally stored.
1346 if (AIsIdentified) {
Dan Gohmandf476e52012-09-04 23:16:20 +00001347 // Check for an obvious escape.
1348 if (isa<LoadInst>(B))
1349 return isStoredObjCPointer(A);
John McCalld935e9c2011-06-15 23:37:01 +00001350 if (BIsIdentified) {
Dan Gohmandf476e52012-09-04 23:16:20 +00001351 // Check for an obvious escape.
1352 if (isa<LoadInst>(A))
1353 return isStoredObjCPointer(B);
1354 // Both pointers are identified and escapes aren't an evident problem.
1355 return false;
John McCalld935e9c2011-06-15 23:37:01 +00001356 }
Dan Gohmandf476e52012-09-04 23:16:20 +00001357 } else if (BIsIdentified) {
1358 // Check for an obvious escape.
1359 if (isa<LoadInst>(A))
John McCalld935e9c2011-06-15 23:37:01 +00001360 return isStoredObjCPointer(B);
1361 }
1362
1363 // Special handling for PHI and Select.
1364 if (const PHINode *PN = dyn_cast<PHINode>(A))
1365 return relatedPHI(PN, B);
1366 if (const PHINode *PN = dyn_cast<PHINode>(B))
1367 return relatedPHI(PN, A);
1368 if (const SelectInst *S = dyn_cast<SelectInst>(A))
1369 return relatedSelect(S, B);
1370 if (const SelectInst *S = dyn_cast<SelectInst>(B))
1371 return relatedSelect(S, A);
1372
1373 // Conservative.
1374 return true;
1375}
1376
1377bool ProvenanceAnalysis::related(const Value *A, const Value *B) {
1378 // Begin by inserting a conservative value into the map. If the insertion
1379 // fails, we have the answer already. If it succeeds, leave it there until we
1380 // compute the real answer to guard against recursive queries.
1381 if (A > B) std::swap(A, B);
1382 std::pair<CachedResultsTy::iterator, bool> Pair =
1383 CachedResults.insert(std::make_pair(ValuePairTy(A, B), true));
1384 if (!Pair.second)
1385 return Pair.first->second;
1386
1387 bool Result = relatedCheck(A, B);
1388 CachedResults[ValuePairTy(A, B)] = Result;
1389 return Result;
1390}
1391
1392namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001393 /// \enum Sequence
1394 ///
1395 /// \brief A sequence of states that a pointer may go through in which an
1396 /// objc_retain and objc_release are actually needed.
John McCalld935e9c2011-06-15 23:37:01 +00001397 enum Sequence {
1398 S_None,
1399 S_Retain, ///< objc_retain(x)
1400 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement
1401 S_Use, ///< any use of x
1402 S_Stop, ///< like S_Release, but code motion is stopped
1403 S_Release, ///< objc_release(x)
1404 S_MovableRelease ///< objc_release(x), !clang.imprecise_release
1405 };
1406}
1407
1408static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
1409 // The easy cases.
1410 if (A == B)
1411 return A;
1412 if (A == S_None || B == S_None)
1413 return S_None;
1414
John McCalld935e9c2011-06-15 23:37:01 +00001415 if (A > B) std::swap(A, B);
1416 if (TopDown) {
1417 // Choose the side which is further along in the sequence.
Dan Gohman12130272011-08-12 00:26:31 +00001418 if ((A == S_Retain || A == S_CanRelease) &&
1419 (B == S_CanRelease || B == S_Use))
John McCalld935e9c2011-06-15 23:37:01 +00001420 return B;
1421 } else {
1422 // Choose the side which is further along in the sequence.
1423 if ((A == S_Use || A == S_CanRelease) &&
Dan Gohman12130272011-08-12 00:26:31 +00001424 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
John McCalld935e9c2011-06-15 23:37:01 +00001425 return A;
1426 // If both sides are releases, choose the more conservative one.
1427 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
1428 return A;
1429 if (A == S_Release && B == S_MovableRelease)
1430 return A;
1431 }
1432
1433 return S_None;
1434}
1435
1436namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001437 /// \brief Unidirectional information about either a
John McCalld935e9c2011-06-15 23:37:01 +00001438 /// retain-decrement-use-release sequence or release-use-decrement-retain
1439 /// reverese sequence.
1440 struct RRInfo {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001441 /// After an objc_retain, the reference count of the referenced
Dan Gohmanb3894012011-08-19 00:26:36 +00001442 /// object is known to be positive. Similarly, before an objc_release, the
1443 /// reference count of the referenced object is known to be positive. If
1444 /// there are retain-release pairs in code regions where the retain count
1445 /// is known to be positive, they can be eliminated, regardless of any side
1446 /// effects between them.
1447 ///
1448 /// Also, a retain+release pair nested within another retain+release
1449 /// pair all on the known same pointer value can be eliminated, regardless
1450 /// of any intervening side effects.
1451 ///
1452 /// KnownSafe is true when either of these conditions is satisfied.
1453 bool KnownSafe;
John McCalld935e9c2011-06-15 23:37:01 +00001454
Michael Gottesman97e3df02013-01-14 00:35:14 +00001455 /// True if the Calls are objc_retainBlock calls (as opposed to objc_retain
1456 /// calls).
John McCalld935e9c2011-06-15 23:37:01 +00001457 bool IsRetainBlock;
1458
Michael Gottesman97e3df02013-01-14 00:35:14 +00001459 /// True of the objc_release calls are all marked with the "tail" keyword.
John McCalld935e9c2011-06-15 23:37:01 +00001460 bool IsTailCallRelease;
1461
Michael Gottesman97e3df02013-01-14 00:35:14 +00001462 /// If the Calls are objc_release calls and they all have a
1463 /// clang.imprecise_release tag, this is the metadata tag.
John McCalld935e9c2011-06-15 23:37:01 +00001464 MDNode *ReleaseMetadata;
1465
Michael Gottesman97e3df02013-01-14 00:35:14 +00001466 /// For a top-down sequence, the set of objc_retains or
John McCalld935e9c2011-06-15 23:37:01 +00001467 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
1468 SmallPtrSet<Instruction *, 2> Calls;
1469
Michael Gottesman97e3df02013-01-14 00:35:14 +00001470 /// The set of optimal insert positions for moving calls in the opposite
1471 /// sequence.
John McCalld935e9c2011-06-15 23:37:01 +00001472 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
1473
1474 RRInfo() :
Dan Gohman728db492012-01-13 00:39:07 +00001475 KnownSafe(false), IsRetainBlock(false),
Dan Gohman62079b42012-04-25 00:50:46 +00001476 IsTailCallRelease(false),
John McCalld935e9c2011-06-15 23:37:01 +00001477 ReleaseMetadata(0) {}
1478
1479 void clear();
1480 };
1481}
1482
1483void RRInfo::clear() {
Dan Gohmanb3894012011-08-19 00:26:36 +00001484 KnownSafe = false;
John McCalld935e9c2011-06-15 23:37:01 +00001485 IsRetainBlock = false;
1486 IsTailCallRelease = false;
1487 ReleaseMetadata = 0;
1488 Calls.clear();
1489 ReverseInsertPts.clear();
1490}
1491
1492namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001493 /// \brief This class summarizes several per-pointer runtime properties which
1494 /// are propogated through the flow graph.
John McCalld935e9c2011-06-15 23:37:01 +00001495 class PtrState {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001496 /// True if the reference count is known to be incremented.
Dan Gohman62079b42012-04-25 00:50:46 +00001497 bool KnownPositiveRefCount;
1498
Michael Gottesman97e3df02013-01-14 00:35:14 +00001499 /// True of we've seen an opportunity for partial RR elimination, such as
1500 /// pushing calls into a CFG triangle or into one side of a CFG diamond.
Dan Gohman62079b42012-04-25 00:50:46 +00001501 bool Partial;
John McCalld935e9c2011-06-15 23:37:01 +00001502
Michael Gottesman97e3df02013-01-14 00:35:14 +00001503 /// The current position in the sequence.
Dan Gohman41375a32012-05-08 23:39:44 +00001504 Sequence Seq : 8;
John McCalld935e9c2011-06-15 23:37:01 +00001505
1506 public:
Michael Gottesman97e3df02013-01-14 00:35:14 +00001507 /// Unidirectional information about the current sequence.
1508 ///
John McCalld935e9c2011-06-15 23:37:01 +00001509 /// TODO: Encapsulate this better.
1510 RRInfo RRI;
1511
Dan Gohmandf476e52012-09-04 23:16:20 +00001512 PtrState() : KnownPositiveRefCount(false), Partial(false),
Dan Gohman41375a32012-05-08 23:39:44 +00001513 Seq(S_None) {}
John McCalld935e9c2011-06-15 23:37:01 +00001514
Dan Gohman62079b42012-04-25 00:50:46 +00001515 void SetKnownPositiveRefCount() {
1516 KnownPositiveRefCount = true;
Dan Gohman12130272011-08-12 00:26:31 +00001517 }
1518
Dan Gohman62079b42012-04-25 00:50:46 +00001519 void ClearRefCount() {
1520 KnownPositiveRefCount = false;
John McCalld935e9c2011-06-15 23:37:01 +00001521 }
1522
John McCalld935e9c2011-06-15 23:37:01 +00001523 bool IsKnownIncremented() const {
Dan Gohman62079b42012-04-25 00:50:46 +00001524 return KnownPositiveRefCount;
John McCalld935e9c2011-06-15 23:37:01 +00001525 }
1526
1527 void SetSeq(Sequence NewSeq) {
1528 Seq = NewSeq;
1529 }
1530
John McCalld935e9c2011-06-15 23:37:01 +00001531 Sequence GetSeq() const {
1532 return Seq;
1533 }
1534
1535 void ClearSequenceProgress() {
Dan Gohman62079b42012-04-25 00:50:46 +00001536 ResetSequenceProgress(S_None);
1537 }
1538
1539 void ResetSequenceProgress(Sequence NewSeq) {
1540 Seq = NewSeq;
1541 Partial = false;
John McCalld935e9c2011-06-15 23:37:01 +00001542 RRI.clear();
1543 }
1544
1545 void Merge(const PtrState &Other, bool TopDown);
1546 };
1547}
1548
1549void
1550PtrState::Merge(const PtrState &Other, bool TopDown) {
1551 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
Dan Gohman62079b42012-04-25 00:50:46 +00001552 KnownPositiveRefCount = KnownPositiveRefCount && Other.KnownPositiveRefCount;
John McCalld935e9c2011-06-15 23:37:01 +00001553
1554 // We can't merge a plain objc_retain with an objc_retainBlock.
1555 if (RRI.IsRetainBlock != Other.RRI.IsRetainBlock)
1556 Seq = S_None;
1557
Dan Gohman1736c142011-10-17 18:48:25 +00001558 // If we're not in a sequence (anymore), drop all associated state.
John McCalld935e9c2011-06-15 23:37:01 +00001559 if (Seq == S_None) {
Dan Gohman62079b42012-04-25 00:50:46 +00001560 Partial = false;
John McCalld935e9c2011-06-15 23:37:01 +00001561 RRI.clear();
Dan Gohman62079b42012-04-25 00:50:46 +00001562 } else if (Partial || Other.Partial) {
Dan Gohman1736c142011-10-17 18:48:25 +00001563 // If we're doing a merge on a path that's previously seen a partial
1564 // merge, conservatively drop the sequence, to avoid doing partial
1565 // RR elimination. If the branch predicates for the two merge differ,
1566 // mixing them is unsafe.
Dan Gohman62079b42012-04-25 00:50:46 +00001567 ClearSequenceProgress();
John McCalld935e9c2011-06-15 23:37:01 +00001568 } else {
1569 // Conservatively merge the ReleaseMetadata information.
1570 if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
1571 RRI.ReleaseMetadata = 0;
1572
Dan Gohmanb3894012011-08-19 00:26:36 +00001573 RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
Dan Gohman41375a32012-05-08 23:39:44 +00001574 RRI.IsTailCallRelease = RRI.IsTailCallRelease &&
1575 Other.RRI.IsTailCallRelease;
John McCalld935e9c2011-06-15 23:37:01 +00001576 RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
Dan Gohman1736c142011-10-17 18:48:25 +00001577
1578 // Merge the insert point sets. If there are any differences,
1579 // that makes this a partial merge.
Dan Gohman41375a32012-05-08 23:39:44 +00001580 Partial = RRI.ReverseInsertPts.size() != Other.RRI.ReverseInsertPts.size();
Dan Gohman1736c142011-10-17 18:48:25 +00001581 for (SmallPtrSet<Instruction *, 2>::const_iterator
1582 I = Other.RRI.ReverseInsertPts.begin(),
1583 E = Other.RRI.ReverseInsertPts.end(); I != E; ++I)
Dan Gohman62079b42012-04-25 00:50:46 +00001584 Partial |= RRI.ReverseInsertPts.insert(*I);
John McCalld935e9c2011-06-15 23:37:01 +00001585 }
1586}
1587
1588namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001589 /// \brief Per-BasicBlock state.
John McCalld935e9c2011-06-15 23:37:01 +00001590 class BBState {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001591 /// The number of unique control paths from the entry which can reach this
1592 /// block.
John McCalld935e9c2011-06-15 23:37:01 +00001593 unsigned TopDownPathCount;
1594
Michael Gottesman97e3df02013-01-14 00:35:14 +00001595 /// The number of unique control paths to exits from this block.
John McCalld935e9c2011-06-15 23:37:01 +00001596 unsigned BottomUpPathCount;
1597
Michael Gottesman97e3df02013-01-14 00:35:14 +00001598 /// A type for PerPtrTopDown and PerPtrBottomUp.
John McCalld935e9c2011-06-15 23:37:01 +00001599 typedef MapVector<const Value *, PtrState> MapTy;
1600
Michael Gottesman97e3df02013-01-14 00:35:14 +00001601 /// The top-down traversal uses this to record information known about a
1602 /// pointer at the bottom of each block.
John McCalld935e9c2011-06-15 23:37:01 +00001603 MapTy PerPtrTopDown;
1604
Michael Gottesman97e3df02013-01-14 00:35:14 +00001605 /// The bottom-up traversal uses this to record information known about a
1606 /// pointer at the top of each block.
John McCalld935e9c2011-06-15 23:37:01 +00001607 MapTy PerPtrBottomUp;
1608
Michael Gottesman97e3df02013-01-14 00:35:14 +00001609 /// Effective predecessors of the current block ignoring ignorable edges and
1610 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001611 SmallVector<BasicBlock *, 2> Preds;
Michael Gottesman97e3df02013-01-14 00:35:14 +00001612 /// Effective successors of the current block ignoring ignorable edges and
1613 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001614 SmallVector<BasicBlock *, 2> Succs;
1615
John McCalld935e9c2011-06-15 23:37:01 +00001616 public:
1617 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
1618
1619 typedef MapTy::iterator ptr_iterator;
1620 typedef MapTy::const_iterator ptr_const_iterator;
1621
1622 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
1623 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
1624 ptr_const_iterator top_down_ptr_begin() const {
1625 return PerPtrTopDown.begin();
1626 }
1627 ptr_const_iterator top_down_ptr_end() const {
1628 return PerPtrTopDown.end();
1629 }
1630
1631 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
1632 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
1633 ptr_const_iterator bottom_up_ptr_begin() const {
1634 return PerPtrBottomUp.begin();
1635 }
1636 ptr_const_iterator bottom_up_ptr_end() const {
1637 return PerPtrBottomUp.end();
1638 }
1639
Michael Gottesman97e3df02013-01-14 00:35:14 +00001640 /// Mark this block as being an entry block, which has one path from the
1641 /// entry by definition.
John McCalld935e9c2011-06-15 23:37:01 +00001642 void SetAsEntry() { TopDownPathCount = 1; }
1643
Michael Gottesman97e3df02013-01-14 00:35:14 +00001644 /// Mark this block as being an exit block, which has one path to an exit by
1645 /// definition.
John McCalld935e9c2011-06-15 23:37:01 +00001646 void SetAsExit() { BottomUpPathCount = 1; }
1647
1648 PtrState &getPtrTopDownState(const Value *Arg) {
1649 return PerPtrTopDown[Arg];
1650 }
1651
1652 PtrState &getPtrBottomUpState(const Value *Arg) {
1653 return PerPtrBottomUp[Arg];
1654 }
1655
1656 void clearBottomUpPointers() {
Evan Chenge4df6a22011-08-04 18:40:26 +00001657 PerPtrBottomUp.clear();
John McCalld935e9c2011-06-15 23:37:01 +00001658 }
1659
1660 void clearTopDownPointers() {
1661 PerPtrTopDown.clear();
1662 }
1663
1664 void InitFromPred(const BBState &Other);
1665 void InitFromSucc(const BBState &Other);
1666 void MergePred(const BBState &Other);
1667 void MergeSucc(const BBState &Other);
1668
Michael Gottesman97e3df02013-01-14 00:35:14 +00001669 /// Return the number of possible unique paths from an entry to an exit
1670 /// which pass through this block. This is only valid after both the
1671 /// top-down and bottom-up traversals are complete.
John McCalld935e9c2011-06-15 23:37:01 +00001672 unsigned GetAllPathCount() const {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001673 assert(TopDownPathCount != 0);
1674 assert(BottomUpPathCount != 0);
John McCalld935e9c2011-06-15 23:37:01 +00001675 return TopDownPathCount * BottomUpPathCount;
1676 }
Dan Gohman12130272011-08-12 00:26:31 +00001677
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001678 // Specialized CFG utilities.
Dan Gohmandae33492012-04-27 18:56:31 +00001679 typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001680 edge_iterator pred_begin() { return Preds.begin(); }
1681 edge_iterator pred_end() { return Preds.end(); }
1682 edge_iterator succ_begin() { return Succs.begin(); }
1683 edge_iterator succ_end() { return Succs.end(); }
1684
1685 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
1686 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
1687
1688 bool isExit() const { return Succs.empty(); }
John McCalld935e9c2011-06-15 23:37:01 +00001689 };
1690}
1691
1692void BBState::InitFromPred(const BBState &Other) {
1693 PerPtrTopDown = Other.PerPtrTopDown;
1694 TopDownPathCount = Other.TopDownPathCount;
1695}
1696
1697void BBState::InitFromSucc(const BBState &Other) {
1698 PerPtrBottomUp = Other.PerPtrBottomUp;
1699 BottomUpPathCount = Other.BottomUpPathCount;
1700}
1701
Michael Gottesman97e3df02013-01-14 00:35:14 +00001702/// The top-down traversal uses this to merge information about predecessors to
1703/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +00001704void BBState::MergePred(const BBState &Other) {
1705 // Other.TopDownPathCount can be 0, in which case it is either dead or a
1706 // loop backedge. Loop backedges are special.
1707 TopDownPathCount += Other.TopDownPathCount;
1708
Michael Gottesman4385edf2013-01-14 01:47:53 +00001709 // Check for overflow. If we have overflow, fall back to conservative
1710 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +00001711 if (TopDownPathCount < Other.TopDownPathCount) {
1712 clearTopDownPointers();
1713 return;
1714 }
1715
John McCalld935e9c2011-06-15 23:37:01 +00001716 // For each entry in the other set, if our set has an entry with the same key,
1717 // merge the entries. Otherwise, copy the entry and merge it with an empty
1718 // entry.
1719 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
1720 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
1721 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
1722 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1723 /*TopDown=*/true);
1724 }
1725
Dan Gohman7e315fc32011-08-11 21:06:32 +00001726 // For each entry in our set, if the other set doesn't have an entry with the
John McCalld935e9c2011-06-15 23:37:01 +00001727 // same key, force it to merge with an empty entry.
1728 for (ptr_iterator MI = top_down_ptr_begin(),
1729 ME = top_down_ptr_end(); MI != ME; ++MI)
1730 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
1731 MI->second.Merge(PtrState(), /*TopDown=*/true);
1732}
1733
Michael Gottesman97e3df02013-01-14 00:35:14 +00001734/// The bottom-up traversal uses this to merge information about successors to
1735/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +00001736void BBState::MergeSucc(const BBState &Other) {
1737 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
1738 // loop backedge. Loop backedges are special.
1739 BottomUpPathCount += Other.BottomUpPathCount;
1740
Michael Gottesman4385edf2013-01-14 01:47:53 +00001741 // Check for overflow. If we have overflow, fall back to conservative
1742 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +00001743 if (BottomUpPathCount < Other.BottomUpPathCount) {
1744 clearBottomUpPointers();
1745 return;
1746 }
1747
John McCalld935e9c2011-06-15 23:37:01 +00001748 // For each entry in the other set, if our set has an entry with the
1749 // same key, merge the entries. Otherwise, copy the entry and merge
1750 // it with an empty entry.
1751 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
1752 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
1753 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
1754 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1755 /*TopDown=*/false);
1756 }
1757
Dan Gohman7e315fc32011-08-11 21:06:32 +00001758 // For each entry in our set, if the other set doesn't have an entry
John McCalld935e9c2011-06-15 23:37:01 +00001759 // with the same key, force it to merge with an empty entry.
1760 for (ptr_iterator MI = bottom_up_ptr_begin(),
1761 ME = bottom_up_ptr_end(); MI != ME; ++MI)
1762 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
1763 MI->second.Merge(PtrState(), /*TopDown=*/false);
1764}
1765
1766namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001767 /// \brief The main ARC optimization pass.
John McCalld935e9c2011-06-15 23:37:01 +00001768 class ObjCARCOpt : public FunctionPass {
1769 bool Changed;
1770 ProvenanceAnalysis PA;
1771
Michael Gottesman97e3df02013-01-14 00:35:14 +00001772 /// A flag indicating whether this optimization pass should run.
Dan Gohmanceaac7c2011-06-20 23:20:43 +00001773 bool Run;
1774
Michael Gottesman97e3df02013-01-14 00:35:14 +00001775 /// Declarations for ObjC runtime functions, for use in creating calls to
1776 /// them. These are initialized lazily to avoid cluttering up the Module
1777 /// with unused declarations.
John McCalld935e9c2011-06-15 23:37:01 +00001778
Michael Gottesman97e3df02013-01-14 00:35:14 +00001779 /// Declaration for ObjC runtime function
1780 /// objc_retainAutoreleasedReturnValue.
1781 Constant *RetainRVCallee;
1782 /// Declaration for ObjC runtime function objc_autoreleaseReturnValue.
1783 Constant *AutoreleaseRVCallee;
1784 /// Declaration for ObjC runtime function objc_release.
1785 Constant *ReleaseCallee;
1786 /// Declaration for ObjC runtime function objc_retain.
1787 Constant *RetainCallee;
1788 /// Declaration for ObjC runtime function objc_retainBlock.
1789 Constant *RetainBlockCallee;
1790 /// Declaration for ObjC runtime function objc_autorelease.
1791 Constant *AutoreleaseCallee;
1792
1793 /// Flags which determine whether each of the interesting runtine functions
1794 /// is in fact used in the current function.
John McCalld935e9c2011-06-15 23:37:01 +00001795 unsigned UsedInThisFunction;
1796
Michael Gottesman97e3df02013-01-14 00:35:14 +00001797 /// The Metadata Kind for clang.imprecise_release metadata.
John McCalld935e9c2011-06-15 23:37:01 +00001798 unsigned ImpreciseReleaseMDKind;
1799
Michael Gottesman97e3df02013-01-14 00:35:14 +00001800 /// The Metadata Kind for clang.arc.copy_on_escape metadata.
Dan Gohmana7107f92011-10-17 22:53:25 +00001801 unsigned CopyOnEscapeMDKind;
1802
Michael Gottesman97e3df02013-01-14 00:35:14 +00001803 /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata.
Dan Gohman0155f302012-02-17 18:59:53 +00001804 unsigned NoObjCARCExceptionsMDKind;
1805
John McCalld935e9c2011-06-15 23:37:01 +00001806 Constant *getRetainRVCallee(Module *M);
1807 Constant *getAutoreleaseRVCallee(Module *M);
1808 Constant *getReleaseCallee(Module *M);
1809 Constant *getRetainCallee(Module *M);
Dan Gohman6320f522011-07-22 22:29:21 +00001810 Constant *getRetainBlockCallee(Module *M);
John McCalld935e9c2011-06-15 23:37:01 +00001811 Constant *getAutoreleaseCallee(Module *M);
1812
Dan Gohman728db492012-01-13 00:39:07 +00001813 bool IsRetainBlockOptimizable(const Instruction *Inst);
1814
John McCalld935e9c2011-06-15 23:37:01 +00001815 void OptimizeRetainCall(Function &F, Instruction *Retain);
1816 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
Michael Gottesman556ff612013-01-12 01:25:19 +00001817 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1818 InstructionClass &Class);
John McCalld935e9c2011-06-15 23:37:01 +00001819 void OptimizeIndividualCalls(Function &F);
1820
1821 void CheckForCFGHazards(const BasicBlock *BB,
1822 DenseMap<const BasicBlock *, BBState> &BBStates,
1823 BBState &MyStates) const;
Dan Gohman817a7c62012-03-22 18:24:56 +00001824 bool VisitInstructionBottomUp(Instruction *Inst,
Dan Gohman5c70fad2012-03-23 17:47:54 +00001825 BasicBlock *BB,
Dan Gohman817a7c62012-03-22 18:24:56 +00001826 MapVector<Value *, RRInfo> &Retains,
1827 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00001828 bool VisitBottomUp(BasicBlock *BB,
1829 DenseMap<const BasicBlock *, BBState> &BBStates,
1830 MapVector<Value *, RRInfo> &Retains);
Dan Gohman817a7c62012-03-22 18:24:56 +00001831 bool VisitInstructionTopDown(Instruction *Inst,
1832 DenseMap<Value *, RRInfo> &Releases,
1833 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00001834 bool VisitTopDown(BasicBlock *BB,
1835 DenseMap<const BasicBlock *, BBState> &BBStates,
1836 DenseMap<Value *, RRInfo> &Releases);
1837 bool Visit(Function &F,
1838 DenseMap<const BasicBlock *, BBState> &BBStates,
1839 MapVector<Value *, RRInfo> &Retains,
1840 DenseMap<Value *, RRInfo> &Releases);
1841
1842 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1843 MapVector<Value *, RRInfo> &Retains,
1844 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman6320f522011-07-22 22:29:21 +00001845 SmallVectorImpl<Instruction *> &DeadInsts,
1846 Module *M);
John McCalld935e9c2011-06-15 23:37:01 +00001847
1848 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1849 MapVector<Value *, RRInfo> &Retains,
Dan Gohman6320f522011-07-22 22:29:21 +00001850 DenseMap<Value *, RRInfo> &Releases,
1851 Module *M);
John McCalld935e9c2011-06-15 23:37:01 +00001852
1853 void OptimizeWeakCalls(Function &F);
1854
1855 bool OptimizeSequences(Function &F);
1856
1857 void OptimizeReturns(Function &F);
1858
1859 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1860 virtual bool doInitialization(Module &M);
1861 virtual bool runOnFunction(Function &F);
1862 virtual void releaseMemory();
1863
1864 public:
1865 static char ID;
1866 ObjCARCOpt() : FunctionPass(ID) {
1867 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1868 }
1869 };
1870}
1871
1872char ObjCARCOpt::ID = 0;
1873INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1874 "objc-arc", "ObjC ARC optimization", false, false)
1875INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1876INITIALIZE_PASS_END(ObjCARCOpt,
1877 "objc-arc", "ObjC ARC optimization", false, false)
1878
1879Pass *llvm::createObjCARCOptPass() {
1880 return new ObjCARCOpt();
1881}
1882
1883void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1884 AU.addRequired<ObjCARCAliasAnalysis>();
1885 AU.addRequired<AliasAnalysis>();
1886 // ARC optimization doesn't currently split critical edges.
1887 AU.setPreservesCFG();
1888}
1889
Dan Gohman728db492012-01-13 00:39:07 +00001890bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1891 // Without the magic metadata tag, we have to assume this might be an
1892 // objc_retainBlock call inserted to convert a block pointer to an id,
1893 // in which case it really is needed.
1894 if (!Inst->getMetadata(CopyOnEscapeMDKind))
1895 return false;
1896
1897 // If the pointer "escapes" (not including being used in a call),
1898 // the copy may be needed.
1899 if (DoesObjCBlockEscape(Inst))
1900 return false;
1901
1902 // Otherwise, it's not needed.
1903 return true;
1904}
1905
John McCalld935e9c2011-06-15 23:37:01 +00001906Constant *ObjCARCOpt::getRetainRVCallee(Module *M) {
1907 if (!RetainRVCallee) {
1908 LLVMContext &C = M->getContext();
Jay Foadb804a2b2011-07-12 14:06:48 +00001909 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman41375a32012-05-08 23:39:44 +00001910 Type *Params[] = { I8X };
1911 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001912 AttributeSet Attribute =
Bill Wendlinge94d8432012-12-07 23:16:57 +00001913 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001914 Attribute::get(C, Attribute::NoUnwind));
John McCalld935e9c2011-06-15 23:37:01 +00001915 RetainRVCallee =
1916 M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy,
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001917 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001918 }
1919 return RetainRVCallee;
1920}
1921
1922Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1923 if (!AutoreleaseRVCallee) {
1924 LLVMContext &C = M->getContext();
Jay Foadb804a2b2011-07-12 14:06:48 +00001925 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman41375a32012-05-08 23:39:44 +00001926 Type *Params[] = { I8X };
1927 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001928 AttributeSet Attribute =
Bill Wendlinge94d8432012-12-07 23:16:57 +00001929 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001930 Attribute::get(C, Attribute::NoUnwind));
John McCalld935e9c2011-06-15 23:37:01 +00001931 AutoreleaseRVCallee =
1932 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001933 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001934 }
1935 return AutoreleaseRVCallee;
1936}
1937
1938Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1939 if (!ReleaseCallee) {
1940 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001941 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001942 AttributeSet Attribute =
Bill Wendlinge94d8432012-12-07 23:16:57 +00001943 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001944 Attribute::get(C, Attribute::NoUnwind));
John McCalld935e9c2011-06-15 23:37:01 +00001945 ReleaseCallee =
1946 M->getOrInsertFunction(
1947 "objc_release",
1948 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001949 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001950 }
1951 return ReleaseCallee;
1952}
1953
1954Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1955 if (!RetainCallee) {
1956 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001957 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001958 AttributeSet Attribute =
Bill Wendlinge94d8432012-12-07 23:16:57 +00001959 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001960 Attribute::get(C, Attribute::NoUnwind));
John McCalld935e9c2011-06-15 23:37:01 +00001961 RetainCallee =
1962 M->getOrInsertFunction(
1963 "objc_retain",
1964 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001965 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001966 }
1967 return RetainCallee;
1968}
1969
Dan Gohman6320f522011-07-22 22:29:21 +00001970Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1971 if (!RetainBlockCallee) {
1972 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001973 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Dan Gohmanfca43c22011-09-14 18:33:34 +00001974 // objc_retainBlock is not nounwind because it calls user copy constructors
1975 // which could theoretically throw.
Dan Gohman6320f522011-07-22 22:29:21 +00001976 RetainBlockCallee =
1977 M->getOrInsertFunction(
1978 "objc_retainBlock",
1979 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendlinge94d8432012-12-07 23:16:57 +00001980 AttributeSet());
Dan Gohman6320f522011-07-22 22:29:21 +00001981 }
1982 return RetainBlockCallee;
1983}
1984
John McCalld935e9c2011-06-15 23:37:01 +00001985Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1986 if (!AutoreleaseCallee) {
1987 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001988 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001989 AttributeSet Attribute =
Bill Wendlinge94d8432012-12-07 23:16:57 +00001990 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001991 Attribute::get(C, Attribute::NoUnwind));
John McCalld935e9c2011-06-15 23:37:01 +00001992 AutoreleaseCallee =
1993 M->getOrInsertFunction(
1994 "objc_autorelease",
1995 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001996 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001997 }
1998 return AutoreleaseCallee;
1999}
2000
Michael Gottesman97e3df02013-01-14 00:35:14 +00002001/// Test whether the given value is possible a reference-counted pointer,
2002/// including tests which utilize AliasAnalysis.
Dan Gohmandf476e52012-09-04 23:16:20 +00002003static bool IsPotentialUse(const Value *Op, AliasAnalysis &AA) {
2004 // First make the rudimentary check.
2005 if (!IsPotentialUse(Op))
2006 return false;
2007
2008 // Objects in constant memory are not reference-counted.
2009 if (AA.pointsToConstantMemory(Op))
2010 return false;
2011
2012 // Pointers in constant memory are not pointing to reference-counted objects.
2013 if (const LoadInst *LI = dyn_cast<LoadInst>(Op))
2014 if (AA.pointsToConstantMemory(LI->getPointerOperand()))
2015 return false;
2016
2017 // Otherwise assume the worst.
2018 return true;
2019}
2020
Michael Gottesman97e3df02013-01-14 00:35:14 +00002021/// Test whether the given instruction can result in a reference count
2022/// modification (positive or negative) for the pointer's object.
John McCalld935e9c2011-06-15 23:37:01 +00002023static bool
2024CanAlterRefCount(const Instruction *Inst, const Value *Ptr,
2025 ProvenanceAnalysis &PA, InstructionClass Class) {
2026 switch (Class) {
2027 case IC_Autorelease:
2028 case IC_AutoreleaseRV:
2029 case IC_User:
2030 // These operations never directly modify a reference count.
2031 return false;
2032 default: break;
2033 }
2034
2035 ImmutableCallSite CS = static_cast<const Value *>(Inst);
2036 assert(CS && "Only calls can alter reference counts!");
2037
2038 // See if AliasAnalysis can help us with the call.
2039 AliasAnalysis::ModRefBehavior MRB = PA.getAA()->getModRefBehavior(CS);
2040 if (AliasAnalysis::onlyReadsMemory(MRB))
2041 return false;
2042 if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
2043 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
2044 I != E; ++I) {
2045 const Value *Op = *I;
Dan Gohmandf476e52012-09-04 23:16:20 +00002046 if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
John McCalld935e9c2011-06-15 23:37:01 +00002047 return true;
2048 }
2049 return false;
2050 }
2051
2052 // Assume the worst.
2053 return true;
2054}
2055
Michael Gottesman97e3df02013-01-14 00:35:14 +00002056/// Test whether the given instruction can "use" the given pointer's object in a
2057/// way that requires the reference count to be positive.
John McCalld935e9c2011-06-15 23:37:01 +00002058static bool
2059CanUse(const Instruction *Inst, const Value *Ptr, ProvenanceAnalysis &PA,
2060 InstructionClass Class) {
2061 // IC_Call operations (as opposed to IC_CallOrUser) never "use" objc pointers.
2062 if (Class == IC_Call)
2063 return false;
2064
2065 // Consider various instructions which may have pointer arguments which are
2066 // not "uses".
2067 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(Inst)) {
2068 // Comparing a pointer with null, or any other constant, isn't really a use,
2069 // because we don't care what the pointer points to, or about the values
2070 // of any other dynamic reference-counted pointers.
Dan Gohmandf476e52012-09-04 23:16:20 +00002071 if (!IsPotentialUse(ICI->getOperand(1), *PA.getAA()))
John McCalld935e9c2011-06-15 23:37:01 +00002072 return false;
2073 } else if (ImmutableCallSite CS = static_cast<const Value *>(Inst)) {
2074 // For calls, just check the arguments (and not the callee operand).
2075 for (ImmutableCallSite::arg_iterator OI = CS.arg_begin(),
2076 OE = CS.arg_end(); OI != OE; ++OI) {
2077 const Value *Op = *OI;
Dan Gohmandf476e52012-09-04 23:16:20 +00002078 if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
John McCalld935e9c2011-06-15 23:37:01 +00002079 return true;
2080 }
2081 return false;
2082 } else if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
2083 // Special-case stores, because we don't care about the stored value, just
2084 // the store address.
2085 const Value *Op = GetUnderlyingObjCPtr(SI->getPointerOperand());
2086 // If we can't tell what the underlying object was, assume there is a
2087 // dependence.
Dan Gohmandf476e52012-09-04 23:16:20 +00002088 return IsPotentialUse(Op, *PA.getAA()) && PA.related(Op, Ptr);
John McCalld935e9c2011-06-15 23:37:01 +00002089 }
2090
2091 // Check each operand for a match.
2092 for (User::const_op_iterator OI = Inst->op_begin(), OE = Inst->op_end();
2093 OI != OE; ++OI) {
2094 const Value *Op = *OI;
Dan Gohmandf476e52012-09-04 23:16:20 +00002095 if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
John McCalld935e9c2011-06-15 23:37:01 +00002096 return true;
2097 }
2098 return false;
2099}
2100
Michael Gottesman97e3df02013-01-14 00:35:14 +00002101/// Test whether the given instruction can autorelease any pointer or cause an
2102/// autoreleasepool pop.
John McCalld935e9c2011-06-15 23:37:01 +00002103static bool
2104CanInterruptRV(InstructionClass Class) {
2105 switch (Class) {
2106 case IC_AutoreleasepoolPop:
2107 case IC_CallOrUser:
2108 case IC_Call:
2109 case IC_Autorelease:
2110 case IC_AutoreleaseRV:
2111 case IC_FusedRetainAutorelease:
2112 case IC_FusedRetainAutoreleaseRV:
2113 return true;
2114 default:
2115 return false;
2116 }
2117}
2118
2119namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +00002120 /// \enum DependenceKind
2121 /// \brief Defines different dependence kinds among various ARC constructs.
2122 ///
2123 /// There are several kinds of dependence-like concepts in use here.
2124 ///
John McCalld935e9c2011-06-15 23:37:01 +00002125 enum DependenceKind {
2126 NeedsPositiveRetainCount,
Dan Gohman8478d762012-04-13 00:59:57 +00002127 AutoreleasePoolBoundary,
John McCalld935e9c2011-06-15 23:37:01 +00002128 CanChangeRetainCount,
2129 RetainAutoreleaseDep, ///< Blocks objc_retainAutorelease.
2130 RetainAutoreleaseRVDep, ///< Blocks objc_retainAutoreleaseReturnValue.
2131 RetainRVDep ///< Blocks objc_retainAutoreleasedReturnValue.
2132 };
2133}
2134
Michael Gottesman97e3df02013-01-14 00:35:14 +00002135/// Test if there can be dependencies on Inst through Arg. This function only
2136/// tests dependencies relevant for removing pairs of calls.
John McCalld935e9c2011-06-15 23:37:01 +00002137static bool
2138Depends(DependenceKind Flavor, Instruction *Inst, const Value *Arg,
2139 ProvenanceAnalysis &PA) {
2140 // If we've reached the definition of Arg, stop.
2141 if (Inst == Arg)
2142 return true;
2143
2144 switch (Flavor) {
2145 case NeedsPositiveRetainCount: {
2146 InstructionClass Class = GetInstructionClass(Inst);
2147 switch (Class) {
2148 case IC_AutoreleasepoolPop:
2149 case IC_AutoreleasepoolPush:
2150 case IC_None:
2151 return false;
2152 default:
2153 return CanUse(Inst, Arg, PA, Class);
2154 }
2155 }
2156
Dan Gohman8478d762012-04-13 00:59:57 +00002157 case AutoreleasePoolBoundary: {
2158 InstructionClass Class = GetInstructionClass(Inst);
2159 switch (Class) {
2160 case IC_AutoreleasepoolPop:
2161 case IC_AutoreleasepoolPush:
2162 // These mark the end and begin of an autorelease pool scope.
2163 return true;
2164 default:
2165 // Nothing else does this.
2166 return false;
2167 }
2168 }
2169
John McCalld935e9c2011-06-15 23:37:01 +00002170 case CanChangeRetainCount: {
2171 InstructionClass Class = GetInstructionClass(Inst);
2172 switch (Class) {
2173 case IC_AutoreleasepoolPop:
2174 // Conservatively assume this can decrement any count.
2175 return true;
2176 case IC_AutoreleasepoolPush:
2177 case IC_None:
2178 return false;
2179 default:
2180 return CanAlterRefCount(Inst, Arg, PA, Class);
2181 }
2182 }
2183
2184 case RetainAutoreleaseDep:
2185 switch (GetBasicInstructionClass(Inst)) {
2186 case IC_AutoreleasepoolPop:
Dan Gohman8478d762012-04-13 00:59:57 +00002187 case IC_AutoreleasepoolPush:
John McCalld935e9c2011-06-15 23:37:01 +00002188 // Don't merge an objc_autorelease with an objc_retain inside a different
2189 // autoreleasepool scope.
2190 return true;
2191 case IC_Retain:
2192 case IC_RetainRV:
2193 // Check for a retain of the same pointer for merging.
2194 return GetObjCArg(Inst) == Arg;
2195 default:
2196 // Nothing else matters for objc_retainAutorelease formation.
2197 return false;
2198 }
John McCalld935e9c2011-06-15 23:37:01 +00002199
2200 case RetainAutoreleaseRVDep: {
2201 InstructionClass Class = GetBasicInstructionClass(Inst);
2202 switch (Class) {
2203 case IC_Retain:
2204 case IC_RetainRV:
2205 // Check for a retain of the same pointer for merging.
2206 return GetObjCArg(Inst) == Arg;
2207 default:
2208 // Anything that can autorelease interrupts
2209 // retainAutoreleaseReturnValue formation.
2210 return CanInterruptRV(Class);
2211 }
John McCalld935e9c2011-06-15 23:37:01 +00002212 }
2213
2214 case RetainRVDep:
2215 return CanInterruptRV(GetBasicInstructionClass(Inst));
2216 }
2217
2218 llvm_unreachable("Invalid dependence flavor");
John McCalld935e9c2011-06-15 23:37:01 +00002219}
2220
Michael Gottesman97e3df02013-01-14 00:35:14 +00002221/// Walk up the CFG from StartPos (which is in StartBB) and find local and
2222/// non-local dependencies on Arg.
2223///
John McCalld935e9c2011-06-15 23:37:01 +00002224/// TODO: Cache results?
2225static void
2226FindDependencies(DependenceKind Flavor,
2227 const Value *Arg,
2228 BasicBlock *StartBB, Instruction *StartInst,
2229 SmallPtrSet<Instruction *, 4> &DependingInstructions,
2230 SmallPtrSet<const BasicBlock *, 4> &Visited,
2231 ProvenanceAnalysis &PA) {
2232 BasicBlock::iterator StartPos = StartInst;
2233
2234 SmallVector<std::pair<BasicBlock *, BasicBlock::iterator>, 4> Worklist;
2235 Worklist.push_back(std::make_pair(StartBB, StartPos));
2236 do {
2237 std::pair<BasicBlock *, BasicBlock::iterator> Pair =
2238 Worklist.pop_back_val();
2239 BasicBlock *LocalStartBB = Pair.first;
2240 BasicBlock::iterator LocalStartPos = Pair.second;
2241 BasicBlock::iterator StartBBBegin = LocalStartBB->begin();
2242 for (;;) {
2243 if (LocalStartPos == StartBBBegin) {
2244 pred_iterator PI(LocalStartBB), PE(LocalStartBB, false);
2245 if (PI == PE)
2246 // If we've reached the function entry, produce a null dependence.
2247 DependingInstructions.insert(0);
2248 else
2249 // Add the predecessors to the worklist.
2250 do {
2251 BasicBlock *PredBB = *PI;
2252 if (Visited.insert(PredBB))
2253 Worklist.push_back(std::make_pair(PredBB, PredBB->end()));
2254 } while (++PI != PE);
2255 break;
2256 }
2257
2258 Instruction *Inst = --LocalStartPos;
2259 if (Depends(Flavor, Inst, Arg, PA)) {
2260 DependingInstructions.insert(Inst);
2261 break;
2262 }
2263 }
2264 } while (!Worklist.empty());
2265
2266 // Determine whether the original StartBB post-dominates all of the blocks we
2267 // visited. If not, insert a sentinal indicating that most optimizations are
2268 // not safe.
2269 for (SmallPtrSet<const BasicBlock *, 4>::const_iterator I = Visited.begin(),
2270 E = Visited.end(); I != E; ++I) {
2271 const BasicBlock *BB = *I;
2272 if (BB == StartBB)
2273 continue;
2274 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2275 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2276 const BasicBlock *Succ = *SI;
2277 if (Succ != StartBB && !Visited.count(Succ)) {
2278 DependingInstructions.insert(reinterpret_cast<Instruction *>(-1));
2279 return;
2280 }
2281 }
2282 }
2283}
2284
2285static bool isNullOrUndef(const Value *V) {
2286 return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
2287}
2288
2289static bool isNoopInstruction(const Instruction *I) {
2290 return isa<BitCastInst>(I) ||
2291 (isa<GetElementPtrInst>(I) &&
2292 cast<GetElementPtrInst>(I)->hasAllZeroIndices());
2293}
2294
Michael Gottesman97e3df02013-01-14 00:35:14 +00002295/// Turn objc_retain into objc_retainAutoreleasedReturnValue if the operand is a
2296/// return value.
John McCalld935e9c2011-06-15 23:37:01 +00002297void
2298ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) {
Dan Gohmandae33492012-04-27 18:56:31 +00002299 ImmutableCallSite CS(GetObjCArg(Retain));
2300 const Instruction *Call = CS.getInstruction();
John McCalld935e9c2011-06-15 23:37:01 +00002301 if (!Call) return;
2302 if (Call->getParent() != Retain->getParent()) return;
2303
2304 // Check that the call is next to the retain.
Dan Gohmandae33492012-04-27 18:56:31 +00002305 BasicBlock::const_iterator I = Call;
John McCalld935e9c2011-06-15 23:37:01 +00002306 ++I;
2307 while (isNoopInstruction(I)) ++I;
2308 if (&*I != Retain)
2309 return;
2310
2311 // Turn it to an objc_retainAutoreleasedReturnValue..
2312 Changed = true;
2313 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00002314
Michael Gottesman1e00ac62013-01-04 21:30:38 +00002315 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainCall: Transforming "
Michael Gottesman9f1be682013-01-12 03:45:49 +00002316 "objc_retain => objc_retainAutoreleasedReturnValue"
2317 " since the operand is a return value.\n"
Michael Gottesman1e00ac62013-01-04 21:30:38 +00002318 " Old: "
2319 << *Retain << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00002320
John McCalld935e9c2011-06-15 23:37:01 +00002321 cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent()));
Michael Gottesman1e00ac62013-01-04 21:30:38 +00002322
2323 DEBUG(dbgs() << " New: "
2324 << *Retain << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002325}
2326
Michael Gottesman97e3df02013-01-14 00:35:14 +00002327/// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is
2328/// not a return value. Or, if it can be paired with an
2329/// objc_autoreleaseReturnValue, delete the pair and return true.
John McCalld935e9c2011-06-15 23:37:01 +00002330bool
2331ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +00002332 // Check for the argument being from an immediately preceding call or invoke.
Dan Gohmandae33492012-04-27 18:56:31 +00002333 const Value *Arg = GetObjCArg(RetainRV);
2334 ImmutableCallSite CS(Arg);
2335 if (const Instruction *Call = CS.getInstruction()) {
John McCalld935e9c2011-06-15 23:37:01 +00002336 if (Call->getParent() == RetainRV->getParent()) {
Dan Gohmandae33492012-04-27 18:56:31 +00002337 BasicBlock::const_iterator I = Call;
John McCalld935e9c2011-06-15 23:37:01 +00002338 ++I;
2339 while (isNoopInstruction(I)) ++I;
2340 if (&*I == RetainRV)
2341 return false;
Dan Gohmandae33492012-04-27 18:56:31 +00002342 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +00002343 BasicBlock *RetainRVParent = RetainRV->getParent();
2344 if (II->getNormalDest() == RetainRVParent) {
Dan Gohmandae33492012-04-27 18:56:31 +00002345 BasicBlock::const_iterator I = RetainRVParent->begin();
Dan Gohmane3ed2b02012-03-23 18:09:00 +00002346 while (isNoopInstruction(I)) ++I;
2347 if (&*I == RetainRV)
2348 return false;
2349 }
John McCalld935e9c2011-06-15 23:37:01 +00002350 }
Dan Gohmane3ed2b02012-03-23 18:09:00 +00002351 }
John McCalld935e9c2011-06-15 23:37:01 +00002352
2353 // Check for being preceded by an objc_autoreleaseReturnValue on the same
2354 // pointer. In this case, we can delete the pair.
2355 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
2356 if (I != Begin) {
2357 do --I; while (I != Begin && isNoopInstruction(I));
2358 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
2359 GetObjCArg(I) == Arg) {
2360 Changed = true;
2361 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00002362
Michael Gottesman5c32ce92013-01-05 17:55:35 +00002363 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainRVCall: Erasing " << *I << "\n"
2364 << " Erasing " << *RetainRV
2365 << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00002366
John McCalld935e9c2011-06-15 23:37:01 +00002367 EraseInstruction(I);
2368 EraseInstruction(RetainRV);
2369 return true;
2370 }
2371 }
2372
2373 // Turn it to a plain objc_retain.
2374 Changed = true;
2375 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00002376
Michael Gottesmandef07bb2013-01-05 17:55:42 +00002377 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainRVCall: Transforming "
2378 "objc_retainAutoreleasedReturnValue => "
2379 "objc_retain since the operand is not a return value.\n"
2380 " Old: "
2381 << *RetainRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00002382
John McCalld935e9c2011-06-15 23:37:01 +00002383 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
Michael Gottesmandef07bb2013-01-05 17:55:42 +00002384
2385 DEBUG(dbgs() << " New: "
2386 << *RetainRV << "\n");
2387
John McCalld935e9c2011-06-15 23:37:01 +00002388 return false;
2389}
2390
Michael Gottesman97e3df02013-01-14 00:35:14 +00002391/// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not
2392/// used as a return value.
John McCalld935e9c2011-06-15 23:37:01 +00002393void
Michael Gottesman556ff612013-01-12 01:25:19 +00002394ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
2395 InstructionClass &Class) {
John McCalld935e9c2011-06-15 23:37:01 +00002396 // Check for a return of the pointer value.
2397 const Value *Ptr = GetObjCArg(AutoreleaseRV);
Dan Gohman10a18d52011-08-12 00:36:31 +00002398 SmallVector<const Value *, 2> Users;
2399 Users.push_back(Ptr);
2400 do {
2401 Ptr = Users.pop_back_val();
2402 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
2403 UI != UE; ++UI) {
2404 const User *I = *UI;
2405 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
2406 return;
2407 if (isa<BitCastInst>(I))
2408 Users.push_back(I);
2409 }
2410 } while (!Users.empty());
John McCalld935e9c2011-06-15 23:37:01 +00002411
2412 Changed = true;
2413 ++NumPeeps;
Michael Gottesman1bf69082013-01-06 21:07:11 +00002414
2415 DEBUG(dbgs() << "ObjCARCOpt::OptimizeAutoreleaseRVCall: Transforming "
2416 "objc_autoreleaseReturnValue => "
2417 "objc_autorelease since its operand is not used as a return "
2418 "value.\n"
2419 " Old: "
2420 << *AutoreleaseRV << "\n");
2421
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00002422 CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
2423 AutoreleaseRVCI->
John McCalld935e9c2011-06-15 23:37:01 +00002424 setCalledFunction(getAutoreleaseCallee(F.getParent()));
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00002425 AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
Michael Gottesman556ff612013-01-12 01:25:19 +00002426 Class = IC_Autorelease;
Michael Gottesman10426b52013-01-07 21:26:07 +00002427
Michael Gottesman1bf69082013-01-06 21:07:11 +00002428 DEBUG(dbgs() << " New: "
2429 << *AutoreleaseRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00002430
John McCalld935e9c2011-06-15 23:37:01 +00002431}
2432
Michael Gottesman97e3df02013-01-14 00:35:14 +00002433/// Visit each call, one at a time, and make simplifications without doing any
2434/// additional analysis.
John McCalld935e9c2011-06-15 23:37:01 +00002435void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
2436 // Reset all the flags in preparation for recomputing them.
2437 UsedInThisFunction = 0;
2438
2439 // Visit all objc_* calls in F.
2440 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2441 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +00002442
John McCalld935e9c2011-06-15 23:37:01 +00002443 InstructionClass Class = GetBasicInstructionClass(Inst);
2444
Michael Gottesmand359e062013-01-18 03:08:39 +00002445 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Visiting: Class: "
2446 << Class << "; " << *Inst << "\n");
Michael Gottesman782e3442013-01-17 18:32:34 +00002447
John McCalld935e9c2011-06-15 23:37:01 +00002448 switch (Class) {
2449 default: break;
2450
2451 // Delete no-op casts. These function calls have special semantics, but
2452 // the semantics are entirely implemented via lowering in the front-end,
2453 // so by the time they reach the optimizer, they are just no-op calls
2454 // which return their argument.
2455 //
2456 // There are gray areas here, as the ability to cast reference-counted
2457 // pointers to raw void* and back allows code to break ARC assumptions,
2458 // however these are currently considered to be unimportant.
2459 case IC_NoopCast:
2460 Changed = true;
2461 ++NumNoops;
Michael Gottesmandc042f02013-01-06 21:07:15 +00002462 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Erasing no-op cast:"
2463 " " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002464 EraseInstruction(Inst);
2465 continue;
2466
2467 // If the pointer-to-weak-pointer is null, it's undefined behavior.
2468 case IC_StoreWeak:
2469 case IC_LoadWeak:
2470 case IC_LoadWeakRetained:
2471 case IC_InitWeak:
2472 case IC_DestroyWeak: {
2473 CallInst *CI = cast<CallInst>(Inst);
2474 if (isNullOrUndef(CI->getArgOperand(0))) {
Dan Gohman670f9372012-04-13 18:57:48 +00002475 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +00002476 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00002477 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2478 Constant::getNullValue(Ty),
2479 CI);
Michael Gottesman10426b52013-01-07 21:26:07 +00002480 llvm::Value *NewValue = UndefValue::get(CI->getType());
Michael Gottesmanfec61c02013-01-06 21:54:30 +00002481 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: A null "
2482 "pointer-to-weak-pointer is undefined behavior.\n"
2483 " Old = " << *CI <<
2484 "\n New = " <<
Michael Gottesman10426b52013-01-07 21:26:07 +00002485 *NewValue << "\n");
Michael Gottesmanfec61c02013-01-06 21:54:30 +00002486 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +00002487 CI->eraseFromParent();
2488 continue;
2489 }
2490 break;
2491 }
2492 case IC_CopyWeak:
2493 case IC_MoveWeak: {
2494 CallInst *CI = cast<CallInst>(Inst);
2495 if (isNullOrUndef(CI->getArgOperand(0)) ||
2496 isNullOrUndef(CI->getArgOperand(1))) {
Dan Gohman670f9372012-04-13 18:57:48 +00002497 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +00002498 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00002499 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2500 Constant::getNullValue(Ty),
2501 CI);
Michael Gottesmanfec61c02013-01-06 21:54:30 +00002502
2503 llvm::Value *NewValue = UndefValue::get(CI->getType());
2504 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: A null "
2505 "pointer-to-weak-pointer is undefined behavior.\n"
2506 " Old = " << *CI <<
2507 "\n New = " <<
2508 *NewValue << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00002509
Michael Gottesmanfec61c02013-01-06 21:54:30 +00002510 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +00002511 CI->eraseFromParent();
2512 continue;
2513 }
2514 break;
2515 }
2516 case IC_Retain:
2517 OptimizeRetainCall(F, Inst);
2518 break;
2519 case IC_RetainRV:
2520 if (OptimizeRetainRVCall(F, Inst))
2521 continue;
2522 break;
2523 case IC_AutoreleaseRV:
Michael Gottesman556ff612013-01-12 01:25:19 +00002524 OptimizeAutoreleaseRVCall(F, Inst, Class);
John McCalld935e9c2011-06-15 23:37:01 +00002525 break;
2526 }
2527
2528 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
2529 if (IsAutorelease(Class) && Inst->use_empty()) {
2530 CallInst *Call = cast<CallInst>(Inst);
2531 const Value *Arg = Call->getArgOperand(0);
2532 Arg = FindSingleUseIdentifiedObject(Arg);
2533 if (Arg) {
2534 Changed = true;
2535 ++NumAutoreleases;
2536
2537 // Create the declaration lazily.
2538 LLVMContext &C = Inst->getContext();
2539 CallInst *NewCall =
2540 CallInst::Create(getReleaseCallee(F.getParent()),
2541 Call->getArgOperand(0), "", Call);
2542 NewCall->setMetadata(ImpreciseReleaseMDKind,
2543 MDNode::get(C, ArrayRef<Value *>()));
Michael Gottesman10426b52013-01-07 21:26:07 +00002544
Michael Gottesmana6a1dad2013-01-06 22:56:50 +00002545 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Replacing "
2546 "objc_autorelease(x) with objc_release(x) since x is "
2547 "otherwise unused.\n"
Michael Gottesman4bf6e752013-01-06 22:56:54 +00002548 " Old: " << *Call <<
Michael Gottesmana6a1dad2013-01-06 22:56:50 +00002549 "\n New: " <<
2550 *NewCall << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00002551
John McCalld935e9c2011-06-15 23:37:01 +00002552 EraseInstruction(Call);
2553 Inst = NewCall;
2554 Class = IC_Release;
2555 }
2556 }
2557
2558 // For functions which can never be passed stack arguments, add
2559 // a tail keyword.
2560 if (IsAlwaysTail(Class)) {
2561 Changed = true;
Michael Gottesman2d763312013-01-06 23:39:09 +00002562 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Adding tail keyword"
2563 " to function since it can never be passed stack args: " << *Inst <<
2564 "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002565 cast<CallInst>(Inst)->setTailCall();
2566 }
2567
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00002568 // Ensure that functions that can never have a "tail" keyword due to the
2569 // semantics of ARC truly do not do so.
2570 if (IsNeverTail(Class)) {
2571 Changed = true;
Michael Gottesman4385edf2013-01-14 01:47:53 +00002572 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Removing tail "
2573 "keyword from function: " << *Inst <<
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00002574 "\n");
2575 cast<CallInst>(Inst)->setTailCall(false);
2576 }
2577
John McCalld935e9c2011-06-15 23:37:01 +00002578 // Set nounwind as needed.
2579 if (IsNoThrow(Class)) {
2580 Changed = true;
Michael Gottesman8800a512013-01-06 23:39:13 +00002581 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Found no throw"
2582 " class. Setting nounwind on: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002583 cast<CallInst>(Inst)->setDoesNotThrow();
2584 }
2585
2586 if (!IsNoopOnNull(Class)) {
2587 UsedInThisFunction |= 1 << Class;
2588 continue;
2589 }
2590
2591 const Value *Arg = GetObjCArg(Inst);
2592
2593 // ARC calls with null are no-ops. Delete them.
2594 if (isNullOrUndef(Arg)) {
2595 Changed = true;
2596 ++NumNoops;
Michael Gottesman5b970e12013-01-07 00:04:52 +00002597 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: ARC calls with "
2598 " null are no-ops. Erasing: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002599 EraseInstruction(Inst);
2600 continue;
2601 }
2602
2603 // Keep track of which of retain, release, autorelease, and retain_block
2604 // are actually present in this function.
2605 UsedInThisFunction |= 1 << Class;
2606
2607 // If Arg is a PHI, and one or more incoming values to the
2608 // PHI are null, and the call is control-equivalent to the PHI, and there
2609 // are no relevant side effects between the PHI and the call, the call
2610 // could be pushed up to just those paths with non-null incoming values.
2611 // For now, don't bother splitting critical edges for this.
2612 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
2613 Worklist.push_back(std::make_pair(Inst, Arg));
2614 do {
2615 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
2616 Inst = Pair.first;
2617 Arg = Pair.second;
2618
2619 const PHINode *PN = dyn_cast<PHINode>(Arg);
2620 if (!PN) continue;
2621
2622 // Determine if the PHI has any null operands, or any incoming
2623 // critical edges.
2624 bool HasNull = false;
2625 bool HasCriticalEdges = false;
2626 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2627 Value *Incoming =
2628 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2629 if (isNullOrUndef(Incoming))
2630 HasNull = true;
2631 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
2632 .getNumSuccessors() != 1) {
2633 HasCriticalEdges = true;
2634 break;
2635 }
2636 }
2637 // If we have null operands and no critical edges, optimize.
2638 if (!HasCriticalEdges && HasNull) {
2639 SmallPtrSet<Instruction *, 4> DependingInstructions;
2640 SmallPtrSet<const BasicBlock *, 4> Visited;
2641
2642 // Check that there is nothing that cares about the reference
2643 // count between the call and the phi.
Dan Gohman8478d762012-04-13 00:59:57 +00002644 switch (Class) {
2645 case IC_Retain:
2646 case IC_RetainBlock:
2647 // These can always be moved up.
2648 break;
2649 case IC_Release:
Dan Gohman41375a32012-05-08 23:39:44 +00002650 // These can't be moved across things that care about the retain
2651 // count.
Dan Gohman8478d762012-04-13 00:59:57 +00002652 FindDependencies(NeedsPositiveRetainCount, Arg,
2653 Inst->getParent(), Inst,
2654 DependingInstructions, Visited, PA);
2655 break;
2656 case IC_Autorelease:
2657 // These can't be moved across autorelease pool scope boundaries.
2658 FindDependencies(AutoreleasePoolBoundary, Arg,
2659 Inst->getParent(), Inst,
2660 DependingInstructions, Visited, PA);
2661 break;
2662 case IC_RetainRV:
2663 case IC_AutoreleaseRV:
2664 // Don't move these; the RV optimization depends on the autoreleaseRV
2665 // being tail called, and the retainRV being immediately after a call
2666 // (which might still happen if we get lucky with codegen layout, but
2667 // it's not worth taking the chance).
2668 continue;
2669 default:
2670 llvm_unreachable("Invalid dependence flavor");
2671 }
2672
John McCalld935e9c2011-06-15 23:37:01 +00002673 if (DependingInstructions.size() == 1 &&
2674 *DependingInstructions.begin() == PN) {
2675 Changed = true;
2676 ++NumPartialNoops;
2677 // Clone the call into each predecessor that has a non-null value.
2678 CallInst *CInst = cast<CallInst>(Inst);
Chris Lattner229907c2011-07-18 04:54:35 +00002679 Type *ParamTy = CInst->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00002680 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2681 Value *Incoming =
2682 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2683 if (!isNullOrUndef(Incoming)) {
2684 CallInst *Clone = cast<CallInst>(CInst->clone());
2685 Value *Op = PN->getIncomingValue(i);
2686 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
2687 if (Op->getType() != ParamTy)
2688 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
2689 Clone->setArgOperand(0, Op);
2690 Clone->insertBefore(InsertPos);
Michael Gottesmanc189a392013-01-09 19:23:24 +00002691
2692 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Cloning "
2693 << *CInst << "\n"
2694 " And inserting "
2695 "clone at " << *InsertPos << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002696 Worklist.push_back(std::make_pair(Clone, Incoming));
2697 }
2698 }
2699 // Erase the original call.
Michael Gottesmanc189a392013-01-09 19:23:24 +00002700 DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002701 EraseInstruction(CInst);
2702 continue;
2703 }
2704 }
2705 } while (!Worklist.empty());
2706 }
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00002707 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Finished List.\n");
John McCalld935e9c2011-06-15 23:37:01 +00002708}
2709
Michael Gottesman97e3df02013-01-14 00:35:14 +00002710/// Check for critical edges, loop boundaries, irreducible control flow, or
2711/// other CFG structures where moving code across the edge would result in it
2712/// being executed more.
John McCalld935e9c2011-06-15 23:37:01 +00002713void
2714ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
2715 DenseMap<const BasicBlock *, BBState> &BBStates,
2716 BBState &MyStates) const {
2717 // If any top-down local-use or possible-dec has a succ which is earlier in
2718 // the sequence, forget it.
Dan Gohman55b06742012-03-02 01:13:53 +00002719 for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
John McCalld935e9c2011-06-15 23:37:01 +00002720 E = MyStates.top_down_ptr_end(); I != E; ++I)
2721 switch (I->second.GetSeq()) {
2722 default: break;
2723 case S_Use: {
2724 const Value *Arg = I->first;
2725 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2726 bool SomeSuccHasSame = false;
2727 bool AllSuccsHaveSame = true;
Dan Gohman55b06742012-03-02 01:13:53 +00002728 PtrState &S = I->second;
Dan Gohman0155f302012-02-17 18:59:53 +00002729 succ_const_iterator SI(TI), SE(TI, false);
2730
Dan Gohman0155f302012-02-17 18:59:53 +00002731 for (; SI != SE; ++SI) {
Dan Gohman362eb692012-03-02 01:26:46 +00002732 Sequence SuccSSeq = S_None;
2733 bool SuccSRRIKnownSafe = false;
Dan Gohman41375a32012-05-08 23:39:44 +00002734 // If VisitBottomUp has pointer information for this successor, take
2735 // what we know about it.
Dan Gohmandae33492012-04-27 18:56:31 +00002736 DenseMap<const BasicBlock *, BBState>::iterator BBI =
2737 BBStates.find(*SI);
2738 assert(BBI != BBStates.end());
2739 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2740 SuccSSeq = SuccS.GetSeq();
2741 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
Dan Gohman362eb692012-03-02 01:26:46 +00002742 switch (SuccSSeq) {
John McCalld935e9c2011-06-15 23:37:01 +00002743 case S_None:
Dan Gohman12130272011-08-12 00:26:31 +00002744 case S_CanRelease: {
Dan Gohman362eb692012-03-02 01:26:46 +00002745 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
Dan Gohman12130272011-08-12 00:26:31 +00002746 S.ClearSequenceProgress();
Dan Gohman362eb692012-03-02 01:26:46 +00002747 break;
2748 }
Dan Gohman12130272011-08-12 00:26:31 +00002749 continue;
2750 }
John McCalld935e9c2011-06-15 23:37:01 +00002751 case S_Use:
2752 SomeSuccHasSame = true;
2753 break;
2754 case S_Stop:
2755 case S_Release:
2756 case S_MovableRelease:
Dan Gohman362eb692012-03-02 01:26:46 +00002757 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
Dan Gohman12130272011-08-12 00:26:31 +00002758 AllSuccsHaveSame = false;
John McCalld935e9c2011-06-15 23:37:01 +00002759 break;
2760 case S_Retain:
2761 llvm_unreachable("bottom-up pointer in retain state!");
2762 }
Dan Gohman12130272011-08-12 00:26:31 +00002763 }
John McCalld935e9c2011-06-15 23:37:01 +00002764 // If the state at the other end of any of the successor edges
2765 // matches the current state, require all edges to match. This
2766 // guards against loops in the middle of a sequence.
2767 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohman12130272011-08-12 00:26:31 +00002768 S.ClearSequenceProgress();
Dan Gohman044437062011-12-12 18:13:53 +00002769 break;
John McCalld935e9c2011-06-15 23:37:01 +00002770 }
2771 case S_CanRelease: {
2772 const Value *Arg = I->first;
2773 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2774 bool SomeSuccHasSame = false;
2775 bool AllSuccsHaveSame = true;
Dan Gohman55b06742012-03-02 01:13:53 +00002776 PtrState &S = I->second;
Dan Gohman0155f302012-02-17 18:59:53 +00002777 succ_const_iterator SI(TI), SE(TI, false);
2778
Dan Gohman0155f302012-02-17 18:59:53 +00002779 for (; SI != SE; ++SI) {
Dan Gohman362eb692012-03-02 01:26:46 +00002780 Sequence SuccSSeq = S_None;
2781 bool SuccSRRIKnownSafe = false;
Dan Gohman41375a32012-05-08 23:39:44 +00002782 // If VisitBottomUp has pointer information for this successor, take
2783 // what we know about it.
Dan Gohmandae33492012-04-27 18:56:31 +00002784 DenseMap<const BasicBlock *, BBState>::iterator BBI =
2785 BBStates.find(*SI);
2786 assert(BBI != BBStates.end());
2787 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2788 SuccSSeq = SuccS.GetSeq();
2789 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
Dan Gohman362eb692012-03-02 01:26:46 +00002790 switch (SuccSSeq) {
Dan Gohman12130272011-08-12 00:26:31 +00002791 case S_None: {
Dan Gohman362eb692012-03-02 01:26:46 +00002792 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
Dan Gohman12130272011-08-12 00:26:31 +00002793 S.ClearSequenceProgress();
Dan Gohman362eb692012-03-02 01:26:46 +00002794 break;
2795 }
Dan Gohman12130272011-08-12 00:26:31 +00002796 continue;
2797 }
John McCalld935e9c2011-06-15 23:37:01 +00002798 case S_CanRelease:
2799 SomeSuccHasSame = true;
2800 break;
2801 case S_Stop:
2802 case S_Release:
2803 case S_MovableRelease:
2804 case S_Use:
Dan Gohman362eb692012-03-02 01:26:46 +00002805 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
Dan Gohman12130272011-08-12 00:26:31 +00002806 AllSuccsHaveSame = false;
John McCalld935e9c2011-06-15 23:37:01 +00002807 break;
2808 case S_Retain:
2809 llvm_unreachable("bottom-up pointer in retain state!");
2810 }
Dan Gohman12130272011-08-12 00:26:31 +00002811 }
John McCalld935e9c2011-06-15 23:37:01 +00002812 // If the state at the other end of any of the successor edges
2813 // matches the current state, require all edges to match. This
2814 // guards against loops in the middle of a sequence.
2815 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohman12130272011-08-12 00:26:31 +00002816 S.ClearSequenceProgress();
Dan Gohman044437062011-12-12 18:13:53 +00002817 break;
John McCalld935e9c2011-06-15 23:37:01 +00002818 }
2819 }
2820}
2821
2822bool
Dan Gohman817a7c62012-03-22 18:24:56 +00002823ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
Dan Gohman5c70fad2012-03-23 17:47:54 +00002824 BasicBlock *BB,
Dan Gohman817a7c62012-03-22 18:24:56 +00002825 MapVector<Value *, RRInfo> &Retains,
2826 BBState &MyStates) {
2827 bool NestingDetected = false;
2828 InstructionClass Class = GetInstructionClass(Inst);
2829 const Value *Arg = 0;
2830
2831 switch (Class) {
2832 case IC_Release: {
2833 Arg = GetObjCArg(Inst);
2834
2835 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2836
2837 // If we see two releases in a row on the same pointer. If so, make
2838 // a note, and we'll cicle back to revisit it after we've
2839 // hopefully eliminated the second release, which may allow us to
2840 // eliminate the first release too.
2841 // Theoretically we could implement removal of nested retain+release
2842 // pairs by making PtrState hold a stack of states, but this is
2843 // simple and avoids adding overhead for the non-nested case.
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00002844 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease) {
2845 DEBUG(dbgs() << "ObjCARCOpt::VisitInstructionBottomUp: Found nested "
2846 "releases (i.e. a release pair)\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00002847 NestingDetected = true;
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00002848 }
Dan Gohman817a7c62012-03-22 18:24:56 +00002849
Dan Gohman817a7c62012-03-22 18:24:56 +00002850 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
Dan Gohman62079b42012-04-25 00:50:46 +00002851 S.ResetSequenceProgress(ReleaseMetadata ? S_MovableRelease : S_Release);
Dan Gohman817a7c62012-03-22 18:24:56 +00002852 S.RRI.ReleaseMetadata = ReleaseMetadata;
Dan Gohmandf476e52012-09-04 23:16:20 +00002853 S.RRI.KnownSafe = S.IsKnownIncremented();
Dan Gohman817a7c62012-03-22 18:24:56 +00002854 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2855 S.RRI.Calls.insert(Inst);
2856
Dan Gohmandf476e52012-09-04 23:16:20 +00002857 S.SetKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00002858 break;
2859 }
2860 case IC_RetainBlock:
2861 // An objc_retainBlock call with just a use may need to be kept,
2862 // because it may be copying a block from the stack to the heap.
2863 if (!IsRetainBlockOptimizable(Inst))
2864 break;
2865 // FALLTHROUGH
2866 case IC_Retain:
2867 case IC_RetainRV: {
2868 Arg = GetObjCArg(Inst);
2869
2870 PtrState &S = MyStates.getPtrBottomUpState(Arg);
Dan Gohman62079b42012-04-25 00:50:46 +00002871 S.SetKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00002872
2873 switch (S.GetSeq()) {
2874 case S_Stop:
2875 case S_Release:
2876 case S_MovableRelease:
2877 case S_Use:
2878 S.RRI.ReverseInsertPts.clear();
2879 // FALL THROUGH
2880 case S_CanRelease:
2881 // Don't do retain+release tracking for IC_RetainRV, because it's
2882 // better to let it remain as the first instruction after a call.
2883 if (Class != IC_RetainRV) {
2884 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2885 Retains[Inst] = S.RRI;
2886 }
2887 S.ClearSequenceProgress();
2888 break;
2889 case S_None:
2890 break;
2891 case S_Retain:
2892 llvm_unreachable("bottom-up pointer in retain state!");
2893 }
2894 return NestingDetected;
2895 }
2896 case IC_AutoreleasepoolPop:
2897 // Conservatively, clear MyStates for all known pointers.
2898 MyStates.clearBottomUpPointers();
2899 return NestingDetected;
2900 case IC_AutoreleasepoolPush:
2901 case IC_None:
2902 // These are irrelevant.
2903 return NestingDetected;
2904 default:
2905 break;
2906 }
2907
2908 // Consider any other possible effects of this instruction on each
2909 // pointer being tracked.
2910 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
2911 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
2912 const Value *Ptr = MI->first;
2913 if (Ptr == Arg)
2914 continue; // Handled above.
2915 PtrState &S = MI->second;
2916 Sequence Seq = S.GetSeq();
2917
2918 // Check for possible releases.
2919 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Dan Gohman62079b42012-04-25 00:50:46 +00002920 S.ClearRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00002921 switch (Seq) {
2922 case S_Use:
2923 S.SetSeq(S_CanRelease);
2924 continue;
2925 case S_CanRelease:
2926 case S_Release:
2927 case S_MovableRelease:
2928 case S_Stop:
2929 case S_None:
2930 break;
2931 case S_Retain:
2932 llvm_unreachable("bottom-up pointer in retain state!");
2933 }
2934 }
2935
2936 // Check for possible direct uses.
2937 switch (Seq) {
2938 case S_Release:
2939 case S_MovableRelease:
2940 if (CanUse(Inst, Ptr, PA, Class)) {
2941 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohman5c70fad2012-03-23 17:47:54 +00002942 // If this is an invoke instruction, we're scanning it as part of
2943 // one of its successor blocks, since we can't insert code after it
2944 // in its own block, and we don't want to split critical edges.
2945 if (isa<InvokeInst>(Inst))
2946 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2947 else
Francois Pichet4b9ab742012-03-24 01:36:37 +00002948 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohman817a7c62012-03-22 18:24:56 +00002949 S.SetSeq(S_Use);
2950 } else if (Seq == S_Release &&
2951 (Class == IC_User || Class == IC_CallOrUser)) {
2952 // Non-movable releases depend on any possible objc pointer use.
2953 S.SetSeq(S_Stop);
2954 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohman5c70fad2012-03-23 17:47:54 +00002955 // As above; handle invoke specially.
2956 if (isa<InvokeInst>(Inst))
2957 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2958 else
Francois Pichet4b9ab742012-03-24 01:36:37 +00002959 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohman817a7c62012-03-22 18:24:56 +00002960 }
2961 break;
2962 case S_Stop:
2963 if (CanUse(Inst, Ptr, PA, Class))
2964 S.SetSeq(S_Use);
2965 break;
2966 case S_CanRelease:
2967 case S_Use:
2968 case S_None:
2969 break;
2970 case S_Retain:
2971 llvm_unreachable("bottom-up pointer in retain state!");
2972 }
2973 }
2974
2975 return NestingDetected;
2976}
2977
2978bool
John McCalld935e9c2011-06-15 23:37:01 +00002979ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2980 DenseMap<const BasicBlock *, BBState> &BBStates,
2981 MapVector<Value *, RRInfo> &Retains) {
2982 bool NestingDetected = false;
2983 BBState &MyStates = BBStates[BB];
2984
2985 // Merge the states from each successor to compute the initial state
2986 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00002987 BBState::edge_iterator SI(MyStates.succ_begin()),
2988 SE(MyStates.succ_end());
2989 if (SI != SE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002990 const BasicBlock *Succ = *SI;
2991 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
2992 assert(I != BBStates.end());
2993 MyStates.InitFromSucc(I->second);
2994 ++SI;
2995 for (; SI != SE; ++SI) {
2996 Succ = *SI;
2997 I = BBStates.find(Succ);
2998 assert(I != BBStates.end());
2999 MyStates.MergeSucc(I->second);
3000 }
Dan Gohman0155f302012-02-17 18:59:53 +00003001 }
John McCalld935e9c2011-06-15 23:37:01 +00003002
3003 // Visit all the instructions, bottom-up.
3004 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
3005 Instruction *Inst = llvm::prior(I);
Dan Gohman5c70fad2012-03-23 17:47:54 +00003006
3007 // Invoke instructions are visited as part of their successors (below).
3008 if (isa<InvokeInst>(Inst))
3009 continue;
3010
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00003011 DEBUG(dbgs() << "ObjCARCOpt::VisitButtonUp: Visiting " << *Inst << "\n");
3012
Dan Gohman5c70fad2012-03-23 17:47:54 +00003013 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
3014 }
3015
Dan Gohmandae33492012-04-27 18:56:31 +00003016 // If there's a predecessor with an invoke, visit the invoke as if it were
3017 // part of this block, since we can't insert code after an invoke in its own
3018 // block, and we don't want to split critical edges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003019 for (BBState::edge_iterator PI(MyStates.pred_begin()),
3020 PE(MyStates.pred_end()); PI != PE; ++PI) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00003021 BasicBlock *Pred = *PI;
Dan Gohmandae33492012-04-27 18:56:31 +00003022 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
3023 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
Dan Gohman817a7c62012-03-22 18:24:56 +00003024 }
John McCalld935e9c2011-06-15 23:37:01 +00003025
Dan Gohman817a7c62012-03-22 18:24:56 +00003026 return NestingDetected;
3027}
John McCalld935e9c2011-06-15 23:37:01 +00003028
Dan Gohman817a7c62012-03-22 18:24:56 +00003029bool
3030ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
3031 DenseMap<Value *, RRInfo> &Releases,
3032 BBState &MyStates) {
3033 bool NestingDetected = false;
3034 InstructionClass Class = GetInstructionClass(Inst);
3035 const Value *Arg = 0;
John McCalld935e9c2011-06-15 23:37:01 +00003036
Dan Gohman817a7c62012-03-22 18:24:56 +00003037 switch (Class) {
3038 case IC_RetainBlock:
3039 // An objc_retainBlock call with just a use may need to be kept,
3040 // because it may be copying a block from the stack to the heap.
3041 if (!IsRetainBlockOptimizable(Inst))
3042 break;
3043 // FALLTHROUGH
3044 case IC_Retain:
3045 case IC_RetainRV: {
3046 Arg = GetObjCArg(Inst);
3047
3048 PtrState &S = MyStates.getPtrTopDownState(Arg);
3049
3050 // Don't do retain+release tracking for IC_RetainRV, because it's
3051 // better to let it remain as the first instruction after a call.
3052 if (Class != IC_RetainRV) {
3053 // If we see two retains in a row on the same pointer. If so, make
John McCalld935e9c2011-06-15 23:37:01 +00003054 // a note, and we'll cicle back to revisit it after we've
Dan Gohman817a7c62012-03-22 18:24:56 +00003055 // hopefully eliminated the second retain, which may allow us to
3056 // eliminate the first retain too.
John McCalld935e9c2011-06-15 23:37:01 +00003057 // Theoretically we could implement removal of nested retain+release
3058 // pairs by making PtrState hold a stack of states, but this is
3059 // simple and avoids adding overhead for the non-nested case.
Dan Gohman817a7c62012-03-22 18:24:56 +00003060 if (S.GetSeq() == S_Retain)
John McCalld935e9c2011-06-15 23:37:01 +00003061 NestingDetected = true;
3062
Dan Gohman62079b42012-04-25 00:50:46 +00003063 S.ResetSequenceProgress(S_Retain);
Dan Gohman817a7c62012-03-22 18:24:56 +00003064 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
Dan Gohmandf476e52012-09-04 23:16:20 +00003065 S.RRI.KnownSafe = S.IsKnownIncremented();
John McCalld935e9c2011-06-15 23:37:01 +00003066 S.RRI.Calls.insert(Inst);
John McCalld935e9c2011-06-15 23:37:01 +00003067 }
John McCalld935e9c2011-06-15 23:37:01 +00003068
Dan Gohmandf476e52012-09-04 23:16:20 +00003069 S.SetKnownPositiveRefCount();
Dan Gohmanf64ff8e2012-07-23 19:27:31 +00003070
3071 // A retain can be a potential use; procede to the generic checking
3072 // code below.
3073 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00003074 }
3075 case IC_Release: {
3076 Arg = GetObjCArg(Inst);
3077
3078 PtrState &S = MyStates.getPtrTopDownState(Arg);
Dan Gohmandf476e52012-09-04 23:16:20 +00003079 S.ClearRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00003080
3081 switch (S.GetSeq()) {
3082 case S_Retain:
3083 case S_CanRelease:
3084 S.RRI.ReverseInsertPts.clear();
3085 // FALL THROUGH
3086 case S_Use:
3087 S.RRI.ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
3088 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
3089 Releases[Inst] = S.RRI;
3090 S.ClearSequenceProgress();
3091 break;
3092 case S_None:
3093 break;
3094 case S_Stop:
3095 case S_Release:
3096 case S_MovableRelease:
3097 llvm_unreachable("top-down pointer in release state!");
3098 }
3099 break;
3100 }
3101 case IC_AutoreleasepoolPop:
3102 // Conservatively, clear MyStates for all known pointers.
3103 MyStates.clearTopDownPointers();
3104 return NestingDetected;
3105 case IC_AutoreleasepoolPush:
3106 case IC_None:
3107 // These are irrelevant.
3108 return NestingDetected;
3109 default:
3110 break;
3111 }
3112
3113 // Consider any other possible effects of this instruction on each
3114 // pointer being tracked.
3115 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
3116 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
3117 const Value *Ptr = MI->first;
3118 if (Ptr == Arg)
3119 continue; // Handled above.
3120 PtrState &S = MI->second;
3121 Sequence Seq = S.GetSeq();
3122
3123 // Check for possible releases.
3124 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Dan Gohman62079b42012-04-25 00:50:46 +00003125 S.ClearRefCount();
John McCalld935e9c2011-06-15 23:37:01 +00003126 switch (Seq) {
Dan Gohman817a7c62012-03-22 18:24:56 +00003127 case S_Retain:
3128 S.SetSeq(S_CanRelease);
3129 assert(S.RRI.ReverseInsertPts.empty());
3130 S.RRI.ReverseInsertPts.insert(Inst);
3131
3132 // One call can't cause a transition from S_Retain to S_CanRelease
3133 // and S_CanRelease to S_Use. If we've made the first transition,
3134 // we're done.
3135 continue;
John McCalld935e9c2011-06-15 23:37:01 +00003136 case S_Use:
Dan Gohman817a7c62012-03-22 18:24:56 +00003137 case S_CanRelease:
John McCalld935e9c2011-06-15 23:37:01 +00003138 case S_None:
3139 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00003140 case S_Stop:
3141 case S_Release:
3142 case S_MovableRelease:
3143 llvm_unreachable("top-down pointer in release state!");
John McCalld935e9c2011-06-15 23:37:01 +00003144 }
3145 }
Dan Gohman817a7c62012-03-22 18:24:56 +00003146
3147 // Check for possible direct uses.
3148 switch (Seq) {
3149 case S_CanRelease:
3150 if (CanUse(Inst, Ptr, PA, Class))
3151 S.SetSeq(S_Use);
3152 break;
3153 case S_Retain:
3154 case S_Use:
3155 case S_None:
3156 break;
3157 case S_Stop:
3158 case S_Release:
3159 case S_MovableRelease:
3160 llvm_unreachable("top-down pointer in release state!");
3161 }
John McCalld935e9c2011-06-15 23:37:01 +00003162 }
3163
3164 return NestingDetected;
3165}
3166
3167bool
3168ObjCARCOpt::VisitTopDown(BasicBlock *BB,
3169 DenseMap<const BasicBlock *, BBState> &BBStates,
3170 DenseMap<Value *, RRInfo> &Releases) {
3171 bool NestingDetected = false;
3172 BBState &MyStates = BBStates[BB];
3173
3174 // Merge the states from each predecessor to compute the initial state
3175 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00003176 BBState::edge_iterator PI(MyStates.pred_begin()),
3177 PE(MyStates.pred_end());
3178 if (PI != PE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003179 const BasicBlock *Pred = *PI;
3180 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
3181 assert(I != BBStates.end());
3182 MyStates.InitFromPred(I->second);
3183 ++PI;
3184 for (; PI != PE; ++PI) {
3185 Pred = *PI;
3186 I = BBStates.find(Pred);
3187 assert(I != BBStates.end());
3188 MyStates.MergePred(I->second);
3189 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003190 }
John McCalld935e9c2011-06-15 23:37:01 +00003191
3192 // Visit all the instructions, top-down.
3193 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3194 Instruction *Inst = I;
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00003195
3196 DEBUG(dbgs() << "ObjCARCOpt::VisitTopDown: Visiting " << *Inst << "\n");
3197
Dan Gohman817a7c62012-03-22 18:24:56 +00003198 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00003199 }
3200
3201 CheckForCFGHazards(BB, BBStates, MyStates);
3202 return NestingDetected;
3203}
3204
Dan Gohmana53a12c2011-12-12 19:42:25 +00003205static void
3206ComputePostOrders(Function &F,
3207 SmallVectorImpl<BasicBlock *> &PostOrder,
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003208 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
3209 unsigned NoObjCARCExceptionsMDKind,
3210 DenseMap<const BasicBlock *, BBState> &BBStates) {
Michael Gottesman97e3df02013-01-14 00:35:14 +00003211 /// The visited set, for doing DFS walks.
Dan Gohmana53a12c2011-12-12 19:42:25 +00003212 SmallPtrSet<BasicBlock *, 16> Visited;
3213
3214 // Do DFS, computing the PostOrder.
3215 SmallPtrSet<BasicBlock *, 16> OnStack;
3216 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003217
3218 // Functions always have exactly one entry block, and we don't have
3219 // any other block that we treat like an entry block.
Dan Gohmana53a12c2011-12-12 19:42:25 +00003220 BasicBlock *EntryBB = &F.getEntryBlock();
Dan Gohman41375a32012-05-08 23:39:44 +00003221 BBState &MyStates = BBStates[EntryBB];
3222 MyStates.SetAsEntry();
3223 TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
3224 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
Dan Gohmana53a12c2011-12-12 19:42:25 +00003225 Visited.insert(EntryBB);
3226 OnStack.insert(EntryBB);
3227 do {
3228 dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003229 BasicBlock *CurrBB = SuccStack.back().first;
3230 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
3231 succ_iterator SE(TI, false);
Dan Gohman41375a32012-05-08 23:39:44 +00003232
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003233 while (SuccStack.back().second != SE) {
3234 BasicBlock *SuccBB = *SuccStack.back().second++;
3235 if (Visited.insert(SuccBB)) {
Dan Gohman41375a32012-05-08 23:39:44 +00003236 TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
3237 SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003238 BBStates[CurrBB].addSucc(SuccBB);
Dan Gohman41375a32012-05-08 23:39:44 +00003239 BBState &SuccStates = BBStates[SuccBB];
3240 SuccStates.addPred(CurrBB);
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003241 OnStack.insert(SuccBB);
Dan Gohmana53a12c2011-12-12 19:42:25 +00003242 goto dfs_next_succ;
3243 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003244
3245 if (!OnStack.count(SuccBB)) {
3246 BBStates[CurrBB].addSucc(SuccBB);
3247 BBStates[SuccBB].addPred(CurrBB);
3248 }
Dan Gohmana53a12c2011-12-12 19:42:25 +00003249 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003250 OnStack.erase(CurrBB);
3251 PostOrder.push_back(CurrBB);
3252 SuccStack.pop_back();
Dan Gohmana53a12c2011-12-12 19:42:25 +00003253 } while (!SuccStack.empty());
3254
3255 Visited.clear();
3256
Dan Gohmana53a12c2011-12-12 19:42:25 +00003257 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003258 // Functions may have many exits, and there also blocks which we treat
3259 // as exits due to ignored edges.
3260 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
3261 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
3262 BasicBlock *ExitBB = I;
3263 BBState &MyStates = BBStates[ExitBB];
3264 if (!MyStates.isExit())
3265 continue;
3266
Dan Gohmandae33492012-04-27 18:56:31 +00003267 MyStates.SetAsExit();
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003268
3269 PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00003270 Visited.insert(ExitBB);
3271 while (!PredStack.empty()) {
3272 reverse_dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003273 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
3274 while (PredStack.back().second != PE) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00003275 BasicBlock *BB = *PredStack.back().second++;
Dan Gohmana53a12c2011-12-12 19:42:25 +00003276 if (Visited.insert(BB)) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003277 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00003278 goto reverse_dfs_next_succ;
3279 }
3280 }
3281 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
3282 }
3283 }
3284}
3285
Michael Gottesman97e3df02013-01-14 00:35:14 +00003286// Visit the function both top-down and bottom-up.
John McCalld935e9c2011-06-15 23:37:01 +00003287bool
3288ObjCARCOpt::Visit(Function &F,
3289 DenseMap<const BasicBlock *, BBState> &BBStates,
3290 MapVector<Value *, RRInfo> &Retains,
3291 DenseMap<Value *, RRInfo> &Releases) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00003292
3293 // Use reverse-postorder traversals, because we magically know that loops
3294 // will be well behaved, i.e. they won't repeatedly call retain on a single
3295 // pointer without doing a release. We can't use the ReversePostOrderTraversal
3296 // class here because we want the reverse-CFG postorder to consider each
3297 // function exit point, and we want to ignore selected cycle edges.
3298 SmallVector<BasicBlock *, 16> PostOrder;
3299 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003300 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
3301 NoObjCARCExceptionsMDKind,
3302 BBStates);
Dan Gohmana53a12c2011-12-12 19:42:25 +00003303
3304 // Use reverse-postorder on the reverse CFG for bottom-up.
John McCalld935e9c2011-06-15 23:37:01 +00003305 bool BottomUpNestingDetected = false;
Dan Gohmanc57b58c2011-08-18 21:27:42 +00003306 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
Dan Gohmana53a12c2011-12-12 19:42:25 +00003307 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
3308 I != E; ++I)
3309 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
John McCalld935e9c2011-06-15 23:37:01 +00003310
Dan Gohmana53a12c2011-12-12 19:42:25 +00003311 // Use reverse-postorder for top-down.
John McCalld935e9c2011-06-15 23:37:01 +00003312 bool TopDownNestingDetected = false;
Dan Gohmana53a12c2011-12-12 19:42:25 +00003313 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
3314 PostOrder.rbegin(), E = PostOrder.rend();
3315 I != E; ++I)
3316 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
John McCalld935e9c2011-06-15 23:37:01 +00003317
3318 return TopDownNestingDetected && BottomUpNestingDetected;
3319}
3320
Michael Gottesman97e3df02013-01-14 00:35:14 +00003321/// Move the calls in RetainsToMove and ReleasesToMove.
John McCalld935e9c2011-06-15 23:37:01 +00003322void ObjCARCOpt::MoveCalls(Value *Arg,
3323 RRInfo &RetainsToMove,
3324 RRInfo &ReleasesToMove,
3325 MapVector<Value *, RRInfo> &Retains,
3326 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman6320f522011-07-22 22:29:21 +00003327 SmallVectorImpl<Instruction *> &DeadInsts,
3328 Module *M) {
Chris Lattner229907c2011-07-18 04:54:35 +00003329 Type *ArgTy = Arg->getType();
Dan Gohman6320f522011-07-22 22:29:21 +00003330 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
John McCalld935e9c2011-06-15 23:37:01 +00003331
3332 // Insert the new retain and release calls.
3333 for (SmallPtrSet<Instruction *, 2>::const_iterator
3334 PI = ReleasesToMove.ReverseInsertPts.begin(),
3335 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
3336 Instruction *InsertPt = *PI;
3337 Value *MyArg = ArgTy == ParamTy ? Arg :
3338 new BitCastInst(Arg, ParamTy, "", InsertPt);
3339 CallInst *Call =
3340 CallInst::Create(RetainsToMove.IsRetainBlock ?
Dan Gohman6320f522011-07-22 22:29:21 +00003341 getRetainBlockCallee(M) : getRetainCallee(M),
John McCalld935e9c2011-06-15 23:37:01 +00003342 MyArg, "", InsertPt);
3343 Call->setDoesNotThrow();
Dan Gohman728db492012-01-13 00:39:07 +00003344 if (RetainsToMove.IsRetainBlock)
Dan Gohmana7107f92011-10-17 22:53:25 +00003345 Call->setMetadata(CopyOnEscapeMDKind,
3346 MDNode::get(M->getContext(), ArrayRef<Value *>()));
Dan Gohman728db492012-01-13 00:39:07 +00003347 else
John McCalld935e9c2011-06-15 23:37:01 +00003348 Call->setTailCall();
Michael Gottesmanc189a392013-01-09 19:23:24 +00003349
3350 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Inserting new Release: " << *Call
3351 << "\n"
3352 " At insertion point: " << *InsertPt
3353 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00003354 }
3355 for (SmallPtrSet<Instruction *, 2>::const_iterator
3356 PI = RetainsToMove.ReverseInsertPts.begin(),
3357 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00003358 Instruction *InsertPt = *PI;
3359 Value *MyArg = ArgTy == ParamTy ? Arg :
3360 new BitCastInst(Arg, ParamTy, "", InsertPt);
3361 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
3362 "", InsertPt);
3363 // Attach a clang.imprecise_release metadata tag, if appropriate.
3364 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
3365 Call->setMetadata(ImpreciseReleaseMDKind, M);
3366 Call->setDoesNotThrow();
3367 if (ReleasesToMove.IsTailCallRelease)
3368 Call->setTailCall();
Michael Gottesmanc189a392013-01-09 19:23:24 +00003369
3370 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Inserting new Retain: " << *Call
3371 << "\n"
3372 " At insertion point: " << *InsertPt
3373 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00003374 }
3375
3376 // Delete the original retain and release calls.
3377 for (SmallPtrSet<Instruction *, 2>::const_iterator
3378 AI = RetainsToMove.Calls.begin(),
3379 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
3380 Instruction *OrigRetain = *AI;
3381 Retains.blot(OrigRetain);
3382 DeadInsts.push_back(OrigRetain);
Michael Gottesmanc189a392013-01-09 19:23:24 +00003383 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Deleting retain: " << *OrigRetain <<
3384 "\n");
John McCalld935e9c2011-06-15 23:37:01 +00003385 }
3386 for (SmallPtrSet<Instruction *, 2>::const_iterator
3387 AI = ReleasesToMove.Calls.begin(),
3388 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
3389 Instruction *OrigRelease = *AI;
3390 Releases.erase(OrigRelease);
3391 DeadInsts.push_back(OrigRelease);
Michael Gottesmanc189a392013-01-09 19:23:24 +00003392 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Deleting release: " << *OrigRelease
3393 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00003394 }
3395}
3396
Michael Gottesman97e3df02013-01-14 00:35:14 +00003397/// Identify pairings between the retains and releases, and delete and/or move
3398/// them.
John McCalld935e9c2011-06-15 23:37:01 +00003399bool
3400ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
3401 &BBStates,
3402 MapVector<Value *, RRInfo> &Retains,
Dan Gohman6320f522011-07-22 22:29:21 +00003403 DenseMap<Value *, RRInfo> &Releases,
3404 Module *M) {
John McCalld935e9c2011-06-15 23:37:01 +00003405 bool AnyPairsCompletelyEliminated = false;
3406 RRInfo RetainsToMove;
3407 RRInfo ReleasesToMove;
3408 SmallVector<Instruction *, 4> NewRetains;
3409 SmallVector<Instruction *, 4> NewReleases;
3410 SmallVector<Instruction *, 8> DeadInsts;
3411
Dan Gohman670f9372012-04-13 18:57:48 +00003412 // Visit each retain.
John McCalld935e9c2011-06-15 23:37:01 +00003413 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
Dan Gohman2053a5d2011-09-29 22:25:23 +00003414 E = Retains.end(); I != E; ++I) {
3415 Value *V = I->first;
John McCalld935e9c2011-06-15 23:37:01 +00003416 if (!V) continue; // blotted
3417
3418 Instruction *Retain = cast<Instruction>(V);
Michael Gottesmanc189a392013-01-09 19:23:24 +00003419
3420 DEBUG(dbgs() << "ObjCARCOpt::PerformCodePlacement: Visiting: " << *Retain
3421 << "\n");
3422
John McCalld935e9c2011-06-15 23:37:01 +00003423 Value *Arg = GetObjCArg(Retain);
3424
Dan Gohman728db492012-01-13 00:39:07 +00003425 // If the object being released is in static or stack storage, we know it's
John McCalld935e9c2011-06-15 23:37:01 +00003426 // not being managed by ObjC reference counting, so we can delete pairs
3427 // regardless of what possible decrements or uses lie between them.
Dan Gohman728db492012-01-13 00:39:07 +00003428 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
Dan Gohman41375a32012-05-08 23:39:44 +00003429
Dan Gohman56e1cef2011-08-22 17:29:11 +00003430 // A constant pointer can't be pointing to an object on the heap. It may
3431 // be reference-counted, but it won't be deleted.
3432 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
3433 if (const GlobalVariable *GV =
3434 dyn_cast<GlobalVariable>(
3435 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
3436 if (GV->isConstant())
3437 KnownSafe = true;
3438
John McCalld935e9c2011-06-15 23:37:01 +00003439 // If a pair happens in a region where it is known that the reference count
3440 // is already incremented, we can similarly ignore possible decrements.
Dan Gohmanb3894012011-08-19 00:26:36 +00003441 bool KnownSafeTD = true, KnownSafeBU = true;
John McCalld935e9c2011-06-15 23:37:01 +00003442
3443 // Connect the dots between the top-down-collected RetainsToMove and
3444 // bottom-up-collected ReleasesToMove to form sets of related calls.
3445 // This is an iterative process so that we connect multiple releases
3446 // to multiple retains if needed.
3447 unsigned OldDelta = 0;
3448 unsigned NewDelta = 0;
3449 unsigned OldCount = 0;
3450 unsigned NewCount = 0;
3451 bool FirstRelease = true;
3452 bool FirstRetain = true;
3453 NewRetains.push_back(Retain);
3454 for (;;) {
3455 for (SmallVectorImpl<Instruction *>::const_iterator
3456 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
3457 Instruction *NewRetain = *NI;
3458 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
3459 assert(It != Retains.end());
3460 const RRInfo &NewRetainRRI = It->second;
Dan Gohmanb3894012011-08-19 00:26:36 +00003461 KnownSafeTD &= NewRetainRRI.KnownSafe;
John McCalld935e9c2011-06-15 23:37:01 +00003462 for (SmallPtrSet<Instruction *, 2>::const_iterator
3463 LI = NewRetainRRI.Calls.begin(),
3464 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
3465 Instruction *NewRetainRelease = *LI;
3466 DenseMap<Value *, RRInfo>::const_iterator Jt =
3467 Releases.find(NewRetainRelease);
3468 if (Jt == Releases.end())
3469 goto next_retain;
3470 const RRInfo &NewRetainReleaseRRI = Jt->second;
3471 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
3472 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
3473 OldDelta -=
3474 BBStates[NewRetainRelease->getParent()].GetAllPathCount();
3475
3476 // Merge the ReleaseMetadata and IsTailCallRelease values.
3477 if (FirstRelease) {
3478 ReleasesToMove.ReleaseMetadata =
3479 NewRetainReleaseRRI.ReleaseMetadata;
3480 ReleasesToMove.IsTailCallRelease =
3481 NewRetainReleaseRRI.IsTailCallRelease;
3482 FirstRelease = false;
3483 } else {
3484 if (ReleasesToMove.ReleaseMetadata !=
3485 NewRetainReleaseRRI.ReleaseMetadata)
3486 ReleasesToMove.ReleaseMetadata = 0;
3487 if (ReleasesToMove.IsTailCallRelease !=
3488 NewRetainReleaseRRI.IsTailCallRelease)
3489 ReleasesToMove.IsTailCallRelease = false;
3490 }
3491
3492 // Collect the optimal insertion points.
3493 if (!KnownSafe)
3494 for (SmallPtrSet<Instruction *, 2>::const_iterator
3495 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
3496 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
3497 RI != RE; ++RI) {
3498 Instruction *RIP = *RI;
3499 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
3500 NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
3501 }
3502 NewReleases.push_back(NewRetainRelease);
3503 }
3504 }
3505 }
3506 NewRetains.clear();
3507 if (NewReleases.empty()) break;
3508
3509 // Back the other way.
3510 for (SmallVectorImpl<Instruction *>::const_iterator
3511 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
3512 Instruction *NewRelease = *NI;
3513 DenseMap<Value *, RRInfo>::const_iterator It =
3514 Releases.find(NewRelease);
3515 assert(It != Releases.end());
3516 const RRInfo &NewReleaseRRI = It->second;
Dan Gohmanb3894012011-08-19 00:26:36 +00003517 KnownSafeBU &= NewReleaseRRI.KnownSafe;
John McCalld935e9c2011-06-15 23:37:01 +00003518 for (SmallPtrSet<Instruction *, 2>::const_iterator
3519 LI = NewReleaseRRI.Calls.begin(),
3520 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
3521 Instruction *NewReleaseRetain = *LI;
3522 MapVector<Value *, RRInfo>::const_iterator Jt =
3523 Retains.find(NewReleaseRetain);
3524 if (Jt == Retains.end())
3525 goto next_retain;
3526 const RRInfo &NewReleaseRetainRRI = Jt->second;
3527 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
3528 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
3529 unsigned PathCount =
3530 BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
3531 OldDelta += PathCount;
3532 OldCount += PathCount;
3533
3534 // Merge the IsRetainBlock values.
3535 if (FirstRetain) {
3536 RetainsToMove.IsRetainBlock = NewReleaseRetainRRI.IsRetainBlock;
3537 FirstRetain = false;
3538 } else if (ReleasesToMove.IsRetainBlock !=
3539 NewReleaseRetainRRI.IsRetainBlock)
3540 // It's not possible to merge the sequences if one uses
3541 // objc_retain and the other uses objc_retainBlock.
3542 goto next_retain;
3543
3544 // Collect the optimal insertion points.
3545 if (!KnownSafe)
3546 for (SmallPtrSet<Instruction *, 2>::const_iterator
3547 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
3548 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
3549 RI != RE; ++RI) {
3550 Instruction *RIP = *RI;
3551 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
3552 PathCount = BBStates[RIP->getParent()].GetAllPathCount();
3553 NewDelta += PathCount;
3554 NewCount += PathCount;
3555 }
3556 }
3557 NewRetains.push_back(NewReleaseRetain);
3558 }
3559 }
3560 }
3561 NewReleases.clear();
3562 if (NewRetains.empty()) break;
3563 }
3564
Dan Gohmanb3894012011-08-19 00:26:36 +00003565 // If the pointer is known incremented or nested, we can safely delete the
3566 // pair regardless of what's between them.
3567 if (KnownSafeTD || KnownSafeBU) {
John McCalld935e9c2011-06-15 23:37:01 +00003568 RetainsToMove.ReverseInsertPts.clear();
3569 ReleasesToMove.ReverseInsertPts.clear();
3570 NewCount = 0;
Dan Gohman12130272011-08-12 00:26:31 +00003571 } else {
3572 // Determine whether the new insertion points we computed preserve the
3573 // balance of retain and release calls through the program.
3574 // TODO: If the fully aggressive solution isn't valid, try to find a
3575 // less aggressive solution which is.
3576 if (NewDelta != 0)
3577 goto next_retain;
John McCalld935e9c2011-06-15 23:37:01 +00003578 }
3579
3580 // Determine whether the original call points are balanced in the retain and
3581 // release calls through the program. If not, conservatively don't touch
3582 // them.
3583 // TODO: It's theoretically possible to do code motion in this case, as
3584 // long as the existing imbalances are maintained.
3585 if (OldDelta != 0)
3586 goto next_retain;
3587
John McCalld935e9c2011-06-15 23:37:01 +00003588 // Ok, everything checks out and we're all set. Let's move some code!
3589 Changed = true;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003590 assert(OldCount != 0 && "Unreachable code?");
3591 AnyPairsCompletelyEliminated = NewCount == 0;
John McCalld935e9c2011-06-15 23:37:01 +00003592 NumRRs += OldCount - NewCount;
Dan Gohman6320f522011-07-22 22:29:21 +00003593 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
3594 Retains, Releases, DeadInsts, M);
John McCalld935e9c2011-06-15 23:37:01 +00003595
3596 next_retain:
3597 NewReleases.clear();
3598 NewRetains.clear();
3599 RetainsToMove.clear();
3600 ReleasesToMove.clear();
3601 }
3602
3603 // Now that we're done moving everything, we can delete the newly dead
3604 // instructions, as we no longer need them as insert points.
3605 while (!DeadInsts.empty())
3606 EraseInstruction(DeadInsts.pop_back_val());
3607
3608 return AnyPairsCompletelyEliminated;
3609}
3610
Michael Gottesman97e3df02013-01-14 00:35:14 +00003611/// Weak pointer optimizations.
John McCalld935e9c2011-06-15 23:37:01 +00003612void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
3613 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
3614 // itself because it uses AliasAnalysis and we need to do provenance
3615 // queries instead.
3616 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3617 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +00003618
Michael Gottesman9f848ae2013-01-04 21:29:57 +00003619 DEBUG(dbgs() << "ObjCARCOpt::OptimizeWeakCalls: Visiting: " << *Inst <<
Michael Gottesman3f146e22013-01-01 16:05:48 +00003620 "\n");
3621
John McCalld935e9c2011-06-15 23:37:01 +00003622 InstructionClass Class = GetBasicInstructionClass(Inst);
3623 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
3624 continue;
3625
3626 // Delete objc_loadWeak calls with no users.
3627 if (Class == IC_LoadWeak && Inst->use_empty()) {
3628 Inst->eraseFromParent();
3629 continue;
3630 }
3631
3632 // TODO: For now, just look for an earlier available version of this value
3633 // within the same block. Theoretically, we could do memdep-style non-local
3634 // analysis too, but that would want caching. A better approach would be to
3635 // use the technique that EarlyCSE uses.
3636 inst_iterator Current = llvm::prior(I);
3637 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
3638 for (BasicBlock::iterator B = CurrentBB->begin(),
3639 J = Current.getInstructionIterator();
3640 J != B; --J) {
3641 Instruction *EarlierInst = &*llvm::prior(J);
3642 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
3643 switch (EarlierClass) {
3644 case IC_LoadWeak:
3645 case IC_LoadWeakRetained: {
3646 // If this is loading from the same pointer, replace this load's value
3647 // with that one.
3648 CallInst *Call = cast<CallInst>(Inst);
3649 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3650 Value *Arg = Call->getArgOperand(0);
3651 Value *EarlierArg = EarlierCall->getArgOperand(0);
3652 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3653 case AliasAnalysis::MustAlias:
3654 Changed = true;
3655 // If the load has a builtin retain, insert a plain retain for it.
3656 if (Class == IC_LoadWeakRetained) {
3657 CallInst *CI =
3658 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3659 "", Call);
3660 CI->setTailCall();
3661 }
3662 // Zap the fully redundant load.
3663 Call->replaceAllUsesWith(EarlierCall);
3664 Call->eraseFromParent();
3665 goto clobbered;
3666 case AliasAnalysis::MayAlias:
3667 case AliasAnalysis::PartialAlias:
3668 goto clobbered;
3669 case AliasAnalysis::NoAlias:
3670 break;
3671 }
3672 break;
3673 }
3674 case IC_StoreWeak:
3675 case IC_InitWeak: {
3676 // If this is storing to the same pointer and has the same size etc.
3677 // replace this load's value with the stored value.
3678 CallInst *Call = cast<CallInst>(Inst);
3679 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3680 Value *Arg = Call->getArgOperand(0);
3681 Value *EarlierArg = EarlierCall->getArgOperand(0);
3682 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3683 case AliasAnalysis::MustAlias:
3684 Changed = true;
3685 // If the load has a builtin retain, insert a plain retain for it.
3686 if (Class == IC_LoadWeakRetained) {
3687 CallInst *CI =
3688 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3689 "", Call);
3690 CI->setTailCall();
3691 }
3692 // Zap the fully redundant load.
3693 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
3694 Call->eraseFromParent();
3695 goto clobbered;
3696 case AliasAnalysis::MayAlias:
3697 case AliasAnalysis::PartialAlias:
3698 goto clobbered;
3699 case AliasAnalysis::NoAlias:
3700 break;
3701 }
3702 break;
3703 }
3704 case IC_MoveWeak:
3705 case IC_CopyWeak:
3706 // TOOD: Grab the copied value.
3707 goto clobbered;
3708 case IC_AutoreleasepoolPush:
3709 case IC_None:
3710 case IC_User:
3711 // Weak pointers are only modified through the weak entry points
3712 // (and arbitrary calls, which could call the weak entry points).
3713 break;
3714 default:
3715 // Anything else could modify the weak pointer.
3716 goto clobbered;
3717 }
3718 }
3719 clobbered:;
3720 }
3721
3722 // Then, for each destroyWeak with an alloca operand, check to see if
3723 // the alloca and all its users can be zapped.
3724 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3725 Instruction *Inst = &*I++;
3726 InstructionClass Class = GetBasicInstructionClass(Inst);
3727 if (Class != IC_DestroyWeak)
3728 continue;
3729
3730 CallInst *Call = cast<CallInst>(Inst);
3731 Value *Arg = Call->getArgOperand(0);
3732 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
3733 for (Value::use_iterator UI = Alloca->use_begin(),
3734 UE = Alloca->use_end(); UI != UE; ++UI) {
Dan Gohmandae33492012-04-27 18:56:31 +00003735 const Instruction *UserInst = cast<Instruction>(*UI);
John McCalld935e9c2011-06-15 23:37:01 +00003736 switch (GetBasicInstructionClass(UserInst)) {
3737 case IC_InitWeak:
3738 case IC_StoreWeak:
3739 case IC_DestroyWeak:
3740 continue;
3741 default:
3742 goto done;
3743 }
3744 }
3745 Changed = true;
3746 for (Value::use_iterator UI = Alloca->use_begin(),
3747 UE = Alloca->use_end(); UI != UE; ) {
3748 CallInst *UserInst = cast<CallInst>(*UI++);
Dan Gohman14862c32012-05-18 22:17:29 +00003749 switch (GetBasicInstructionClass(UserInst)) {
3750 case IC_InitWeak:
3751 case IC_StoreWeak:
3752 // These functions return their second argument.
3753 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
3754 break;
3755 case IC_DestroyWeak:
3756 // No return value.
3757 break;
3758 default:
Dan Gohman9c97eea02012-05-21 17:41:28 +00003759 llvm_unreachable("alloca really is used!");
Dan Gohman14862c32012-05-18 22:17:29 +00003760 }
John McCalld935e9c2011-06-15 23:37:01 +00003761 UserInst->eraseFromParent();
3762 }
3763 Alloca->eraseFromParent();
3764 done:;
3765 }
3766 }
Michael Gottesman10426b52013-01-07 21:26:07 +00003767
Michael Gottesman9f848ae2013-01-04 21:29:57 +00003768 DEBUG(dbgs() << "ObjCARCOpt::OptimizeWeakCalls: Finished List.\n\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00003769
John McCalld935e9c2011-06-15 23:37:01 +00003770}
3771
Michael Gottesman97e3df02013-01-14 00:35:14 +00003772/// Identify program paths which execute sequences of retains and releases which
3773/// can be eliminated.
John McCalld935e9c2011-06-15 23:37:01 +00003774bool ObjCARCOpt::OptimizeSequences(Function &F) {
3775 /// Releases, Retains - These are used to store the results of the main flow
3776 /// analysis. These use Value* as the key instead of Instruction* so that the
3777 /// map stays valid when we get around to rewriting code and calls get
3778 /// replaced by arguments.
3779 DenseMap<Value *, RRInfo> Releases;
3780 MapVector<Value *, RRInfo> Retains;
3781
Michael Gottesman97e3df02013-01-14 00:35:14 +00003782 /// This is used during the traversal of the function to track the
John McCalld935e9c2011-06-15 23:37:01 +00003783 /// states for each identified object at each block.
3784 DenseMap<const BasicBlock *, BBState> BBStates;
3785
3786 // Analyze the CFG of the function, and all instructions.
3787 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
3788
3789 // Transform.
Dan Gohman6320f522011-07-22 22:29:21 +00003790 return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) &&
3791 NestingDetected;
John McCalld935e9c2011-06-15 23:37:01 +00003792}
3793
Michael Gottesman97e3df02013-01-14 00:35:14 +00003794/// Look for this pattern:
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00003795/// \code
John McCalld935e9c2011-06-15 23:37:01 +00003796/// %call = call i8* @something(...)
3797/// %2 = call i8* @objc_retain(i8* %call)
3798/// %3 = call i8* @objc_autorelease(i8* %2)
3799/// ret i8* %3
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00003800/// \endcode
John McCalld935e9c2011-06-15 23:37:01 +00003801/// And delete the retain and autorelease.
3802///
3803/// Otherwise if it's just this:
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00003804/// \code
John McCalld935e9c2011-06-15 23:37:01 +00003805/// %3 = call i8* @objc_autorelease(i8* %2)
3806/// ret i8* %3
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00003807/// \endcode
John McCalld935e9c2011-06-15 23:37:01 +00003808/// convert the autorelease to autoreleaseRV.
3809void ObjCARCOpt::OptimizeReturns(Function &F) {
3810 if (!F.getReturnType()->isPointerTy())
3811 return;
3812
3813 SmallPtrSet<Instruction *, 4> DependingInstructions;
3814 SmallPtrSet<const BasicBlock *, 4> Visited;
3815 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3816 BasicBlock *BB = FI;
3817 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
Michael Gottesman3f146e22013-01-01 16:05:48 +00003818
Michael Gottesman9f848ae2013-01-04 21:29:57 +00003819 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Visiting: " << *Ret << "\n");
Michael Gottesman3f146e22013-01-01 16:05:48 +00003820
John McCalld935e9c2011-06-15 23:37:01 +00003821 if (!Ret) continue;
3822
3823 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
3824 FindDependencies(NeedsPositiveRetainCount, Arg,
3825 BB, Ret, DependingInstructions, Visited, PA);
3826 if (DependingInstructions.size() != 1)
3827 goto next_block;
3828
3829 {
3830 CallInst *Autorelease =
3831 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3832 if (!Autorelease)
3833 goto next_block;
Dan Gohman41375a32012-05-08 23:39:44 +00003834 InstructionClass AutoreleaseClass = GetBasicInstructionClass(Autorelease);
John McCalld935e9c2011-06-15 23:37:01 +00003835 if (!IsAutorelease(AutoreleaseClass))
3836 goto next_block;
3837 if (GetObjCArg(Autorelease) != Arg)
3838 goto next_block;
3839
3840 DependingInstructions.clear();
3841 Visited.clear();
3842
3843 // Check that there is nothing that can affect the reference
3844 // count between the autorelease and the retain.
3845 FindDependencies(CanChangeRetainCount, Arg,
3846 BB, Autorelease, DependingInstructions, Visited, PA);
3847 if (DependingInstructions.size() != 1)
3848 goto next_block;
3849
3850 {
3851 CallInst *Retain =
3852 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3853
3854 // Check that we found a retain with the same argument.
3855 if (!Retain ||
3856 !IsRetain(GetBasicInstructionClass(Retain)) ||
3857 GetObjCArg(Retain) != Arg)
3858 goto next_block;
3859
3860 DependingInstructions.clear();
3861 Visited.clear();
3862
3863 // Convert the autorelease to an autoreleaseRV, since it's
3864 // returning the value.
3865 if (AutoreleaseClass == IC_Autorelease) {
Michael Gottesmana6cb0182013-01-10 02:03:50 +00003866 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Converting autorelease "
3867 "=> autoreleaseRV since it's returning a value.\n"
3868 " In: " << *Autorelease
3869 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00003870 Autorelease->setCalledFunction(getAutoreleaseRVCallee(F.getParent()));
Michael Gottesmana6cb0182013-01-10 02:03:50 +00003871 DEBUG(dbgs() << " Out: " << *Autorelease
3872 << "\n");
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00003873 Autorelease->setTailCall(); // Always tail call autoreleaseRV.
John McCalld935e9c2011-06-15 23:37:01 +00003874 AutoreleaseClass = IC_AutoreleaseRV;
3875 }
3876
3877 // Check that there is nothing that can affect the reference
3878 // count between the retain and the call.
Dan Gohman4ac148d2011-09-29 22:27:34 +00003879 // Note that Retain need not be in BB.
3880 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
John McCalld935e9c2011-06-15 23:37:01 +00003881 DependingInstructions, Visited, PA);
3882 if (DependingInstructions.size() != 1)
3883 goto next_block;
3884
3885 {
3886 CallInst *Call =
3887 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3888
3889 // Check that the pointer is the return value of the call.
3890 if (!Call || Arg != Call)
3891 goto next_block;
3892
3893 // Check that the call is a regular call.
3894 InstructionClass Class = GetBasicInstructionClass(Call);
3895 if (Class != IC_CallOrUser && Class != IC_Call)
3896 goto next_block;
3897
3898 // If so, we can zap the retain and autorelease.
3899 Changed = true;
3900 ++NumRets;
Michael Gottesmand61a3b22013-01-07 00:04:56 +00003901 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Erasing: " << *Retain
3902 << "\n Erasing: "
3903 << *Autorelease << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00003904 EraseInstruction(Retain);
3905 EraseInstruction(Autorelease);
3906 }
3907 }
3908 }
3909
3910 next_block:
3911 DependingInstructions.clear();
3912 Visited.clear();
3913 }
Michael Gottesman10426b52013-01-07 21:26:07 +00003914
Michael Gottesman9f848ae2013-01-04 21:29:57 +00003915 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Finished List.\n\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00003916
John McCalld935e9c2011-06-15 23:37:01 +00003917}
3918
3919bool ObjCARCOpt::doInitialization(Module &M) {
3920 if (!EnableARCOpts)
3921 return false;
3922
Dan Gohman670f9372012-04-13 18:57:48 +00003923 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanceaac7c2011-06-20 23:20:43 +00003924 Run = ModuleHasARC(M);
3925 if (!Run)
3926 return false;
3927
John McCalld935e9c2011-06-15 23:37:01 +00003928 // Identify the imprecise release metadata kind.
3929 ImpreciseReleaseMDKind =
3930 M.getContext().getMDKindID("clang.imprecise_release");
Dan Gohmana7107f92011-10-17 22:53:25 +00003931 CopyOnEscapeMDKind =
3932 M.getContext().getMDKindID("clang.arc.copy_on_escape");
Dan Gohman0155f302012-02-17 18:59:53 +00003933 NoObjCARCExceptionsMDKind =
3934 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
John McCalld935e9c2011-06-15 23:37:01 +00003935
John McCalld935e9c2011-06-15 23:37:01 +00003936 // Intuitively, objc_retain and others are nocapture, however in practice
3937 // they are not, because they return their argument value. And objc_release
Dan Gohmandae33492012-04-27 18:56:31 +00003938 // calls finalizers which can have arbitrary side effects.
John McCalld935e9c2011-06-15 23:37:01 +00003939
3940 // These are initialized lazily.
3941 RetainRVCallee = 0;
3942 AutoreleaseRVCallee = 0;
3943 ReleaseCallee = 0;
3944 RetainCallee = 0;
Dan Gohman6320f522011-07-22 22:29:21 +00003945 RetainBlockCallee = 0;
John McCalld935e9c2011-06-15 23:37:01 +00003946 AutoreleaseCallee = 0;
3947
3948 return false;
3949}
3950
3951bool ObjCARCOpt::runOnFunction(Function &F) {
3952 if (!EnableARCOpts)
3953 return false;
3954
Dan Gohmanceaac7c2011-06-20 23:20:43 +00003955 // If nothing in the Module uses ARC, don't do anything.
3956 if (!Run)
3957 return false;
3958
John McCalld935e9c2011-06-15 23:37:01 +00003959 Changed = false;
3960
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00003961 DEBUG(dbgs() << "ObjCARCOpt: Visiting Function: " << F.getName() << "\n");
3962
John McCalld935e9c2011-06-15 23:37:01 +00003963 PA.setAA(&getAnalysis<AliasAnalysis>());
3964
3965 // This pass performs several distinct transformations. As a compile-time aid
3966 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3967 // library functions aren't declared.
3968
3969 // Preliminary optimizations. This also computs UsedInThisFunction.
3970 OptimizeIndividualCalls(F);
3971
3972 // Optimizations for weak pointers.
3973 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3974 (1 << IC_LoadWeakRetained) |
3975 (1 << IC_StoreWeak) |
3976 (1 << IC_InitWeak) |
3977 (1 << IC_CopyWeak) |
3978 (1 << IC_MoveWeak) |
3979 (1 << IC_DestroyWeak)))
3980 OptimizeWeakCalls(F);
3981
3982 // Optimizations for retain+release pairs.
3983 if (UsedInThisFunction & ((1 << IC_Retain) |
3984 (1 << IC_RetainRV) |
3985 (1 << IC_RetainBlock)))
3986 if (UsedInThisFunction & (1 << IC_Release))
3987 // Run OptimizeSequences until it either stops making changes or
3988 // no retain+release pair nesting is detected.
3989 while (OptimizeSequences(F)) {}
3990
3991 // Optimizations if objc_autorelease is used.
Dan Gohman41375a32012-05-08 23:39:44 +00003992 if (UsedInThisFunction & ((1 << IC_Autorelease) |
3993 (1 << IC_AutoreleaseRV)))
John McCalld935e9c2011-06-15 23:37:01 +00003994 OptimizeReturns(F);
3995
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00003996 DEBUG(dbgs() << "\n");
3997
John McCalld935e9c2011-06-15 23:37:01 +00003998 return Changed;
3999}
4000
4001void ObjCARCOpt::releaseMemory() {
4002 PA.clear();
4003}
4004
Michael Gottesman97e3df02013-01-14 00:35:14 +00004005/// @}
4006///
4007/// \defgroup ARCContract ARC Contraction.
4008/// @{
John McCalld935e9c2011-06-15 23:37:01 +00004009
4010// TODO: ObjCARCContract could insert PHI nodes when uses aren't
4011// dominated by single calls.
4012
John McCalld935e9c2011-06-15 23:37:01 +00004013#include "llvm/Analysis/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +00004014#include "llvm/IR/InlineAsm.h"
4015#include "llvm/IR/Operator.h"
John McCalld935e9c2011-06-15 23:37:01 +00004016
4017STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed");
4018
4019namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +00004020 /// \brief Late ARC optimizations
4021 ///
4022 /// These change the IR in a way that makes it difficult to be analyzed by
4023 /// ObjCARCOpt, so it's run late.
John McCalld935e9c2011-06-15 23:37:01 +00004024 class ObjCARCContract : public FunctionPass {
4025 bool Changed;
4026 AliasAnalysis *AA;
4027 DominatorTree *DT;
4028 ProvenanceAnalysis PA;
4029
Michael Gottesman97e3df02013-01-14 00:35:14 +00004030 /// A flag indicating whether this optimization pass should run.
Dan Gohmanceaac7c2011-06-20 23:20:43 +00004031 bool Run;
4032
Michael Gottesman97e3df02013-01-14 00:35:14 +00004033 /// Declarations for ObjC runtime functions, for use in creating calls to
4034 /// them. These are initialized lazily to avoid cluttering up the Module
4035 /// with unused declarations.
John McCalld935e9c2011-06-15 23:37:01 +00004036
Michael Gottesman97e3df02013-01-14 00:35:14 +00004037 /// Declaration for objc_storeStrong().
4038 Constant *StoreStrongCallee;
4039 /// Declaration for objc_retainAutorelease().
4040 Constant *RetainAutoreleaseCallee;
4041 /// Declaration for objc_retainAutoreleaseReturnValue().
4042 Constant *RetainAutoreleaseRVCallee;
4043
4044 /// The inline asm string to insert between calls and RetainRV calls to make
4045 /// the optimization work on targets which need it.
John McCalld935e9c2011-06-15 23:37:01 +00004046 const MDString *RetainRVMarker;
4047
Michael Gottesman97e3df02013-01-14 00:35:14 +00004048 /// The set of inserted objc_storeStrong calls. If at the end of walking the
4049 /// function we have found no alloca instructions, these calls can be marked
4050 /// "tail".
Dan Gohman41375a32012-05-08 23:39:44 +00004051 SmallPtrSet<CallInst *, 8> StoreStrongCalls;
Dan Gohman8ee108b2012-01-19 19:14:36 +00004052
John McCalld935e9c2011-06-15 23:37:01 +00004053 Constant *getStoreStrongCallee(Module *M);
4054 Constant *getRetainAutoreleaseCallee(Module *M);
4055 Constant *getRetainAutoreleaseRVCallee(Module *M);
4056
4057 bool ContractAutorelease(Function &F, Instruction *Autorelease,
4058 InstructionClass Class,
4059 SmallPtrSet<Instruction *, 4>
4060 &DependingInstructions,
4061 SmallPtrSet<const BasicBlock *, 4>
4062 &Visited);
4063
4064 void ContractRelease(Instruction *Release,
4065 inst_iterator &Iter);
4066
4067 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
4068 virtual bool doInitialization(Module &M);
4069 virtual bool runOnFunction(Function &F);
4070
4071 public:
4072 static char ID;
4073 ObjCARCContract() : FunctionPass(ID) {
4074 initializeObjCARCContractPass(*PassRegistry::getPassRegistry());
4075 }
4076 };
4077}
4078
4079char ObjCARCContract::ID = 0;
4080INITIALIZE_PASS_BEGIN(ObjCARCContract,
4081 "objc-arc-contract", "ObjC ARC contraction", false, false)
4082INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
4083INITIALIZE_PASS_DEPENDENCY(DominatorTree)
4084INITIALIZE_PASS_END(ObjCARCContract,
4085 "objc-arc-contract", "ObjC ARC contraction", false, false)
4086
4087Pass *llvm::createObjCARCContractPass() {
4088 return new ObjCARCContract();
4089}
4090
4091void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const {
4092 AU.addRequired<AliasAnalysis>();
4093 AU.addRequired<DominatorTree>();
4094 AU.setPreservesCFG();
4095}
4096
4097Constant *ObjCARCContract::getStoreStrongCallee(Module *M) {
4098 if (!StoreStrongCallee) {
4099 LLVMContext &C = M->getContext();
Jay Foadb804a2b2011-07-12 14:06:48 +00004100 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
4101 Type *I8XX = PointerType::getUnqual(I8X);
Dan Gohman41375a32012-05-08 23:39:44 +00004102 Type *Params[] = { I8XX, I8X };
John McCalld935e9c2011-06-15 23:37:01 +00004103
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004104 AttributeSet Attribute = AttributeSet()
Bill Wendlinge94d8432012-12-07 23:16:57 +00004105 .addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004106 Attribute::get(C, Attribute::NoUnwind))
4107 .addAttr(M->getContext(), 1, Attribute::get(C, Attribute::NoCapture));
John McCalld935e9c2011-06-15 23:37:01 +00004108
4109 StoreStrongCallee =
4110 M->getOrInsertFunction(
4111 "objc_storeStrong",
4112 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004113 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00004114 }
4115 return StoreStrongCallee;
4116}
4117
4118Constant *ObjCARCContract::getRetainAutoreleaseCallee(Module *M) {
4119 if (!RetainAutoreleaseCallee) {
4120 LLVMContext &C = M->getContext();
Jay Foadb804a2b2011-07-12 14:06:48 +00004121 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman41375a32012-05-08 23:39:44 +00004122 Type *Params[] = { I8X };
4123 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004124 AttributeSet Attribute =
Bill Wendlinge94d8432012-12-07 23:16:57 +00004125 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004126 Attribute::get(C, Attribute::NoUnwind));
John McCalld935e9c2011-06-15 23:37:01 +00004127 RetainAutoreleaseCallee =
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004128 M->getOrInsertFunction("objc_retainAutorelease", FTy, Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00004129 }
4130 return RetainAutoreleaseCallee;
4131}
4132
4133Constant *ObjCARCContract::getRetainAutoreleaseRVCallee(Module *M) {
4134 if (!RetainAutoreleaseRVCallee) {
4135 LLVMContext &C = M->getContext();
Jay Foadb804a2b2011-07-12 14:06:48 +00004136 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman41375a32012-05-08 23:39:44 +00004137 Type *Params[] = { I8X };
4138 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004139 AttributeSet Attribute =
Bill Wendlinge94d8432012-12-07 23:16:57 +00004140 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004141 Attribute::get(C, Attribute::NoUnwind));
John McCalld935e9c2011-06-15 23:37:01 +00004142 RetainAutoreleaseRVCallee =
4143 M->getOrInsertFunction("objc_retainAutoreleaseReturnValue", FTy,
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004144 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00004145 }
4146 return RetainAutoreleaseRVCallee;
4147}
4148
Michael Gottesman97e3df02013-01-14 00:35:14 +00004149/// Merge an autorelease with a retain into a fused call.
John McCalld935e9c2011-06-15 23:37:01 +00004150bool
4151ObjCARCContract::ContractAutorelease(Function &F, Instruction *Autorelease,
4152 InstructionClass Class,
4153 SmallPtrSet<Instruction *, 4>
4154 &DependingInstructions,
4155 SmallPtrSet<const BasicBlock *, 4>
4156 &Visited) {
4157 const Value *Arg = GetObjCArg(Autorelease);
4158
4159 // Check that there are no instructions between the retain and the autorelease
4160 // (such as an autorelease_pop) which may change the count.
4161 CallInst *Retain = 0;
4162 if (Class == IC_AutoreleaseRV)
4163 FindDependencies(RetainAutoreleaseRVDep, Arg,
4164 Autorelease->getParent(), Autorelease,
4165 DependingInstructions, Visited, PA);
4166 else
4167 FindDependencies(RetainAutoreleaseDep, Arg,
4168 Autorelease->getParent(), Autorelease,
4169 DependingInstructions, Visited, PA);
4170
4171 Visited.clear();
4172 if (DependingInstructions.size() != 1) {
4173 DependingInstructions.clear();
4174 return false;
4175 }
4176
4177 Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
4178 DependingInstructions.clear();
4179
4180 if (!Retain ||
4181 GetBasicInstructionClass(Retain) != IC_Retain ||
4182 GetObjCArg(Retain) != Arg)
4183 return false;
4184
4185 Changed = true;
4186 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00004187
Michael Gottesmanadd08472013-01-07 00:31:26 +00004188 DEBUG(dbgs() << "ObjCARCContract::ContractAutorelease: Fusing "
4189 "retain/autorelease. Erasing: " << *Autorelease << "\n"
4190 " Old Retain: "
4191 << *Retain << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00004192
John McCalld935e9c2011-06-15 23:37:01 +00004193 if (Class == IC_AutoreleaseRV)
4194 Retain->setCalledFunction(getRetainAutoreleaseRVCallee(F.getParent()));
4195 else
4196 Retain->setCalledFunction(getRetainAutoreleaseCallee(F.getParent()));
Michael Gottesman10426b52013-01-07 21:26:07 +00004197
Michael Gottesmanadd08472013-01-07 00:31:26 +00004198 DEBUG(dbgs() << " New Retain: "
4199 << *Retain << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00004200
John McCalld935e9c2011-06-15 23:37:01 +00004201 EraseInstruction(Autorelease);
4202 return true;
4203}
4204
Michael Gottesman97e3df02013-01-14 00:35:14 +00004205/// Attempt to merge an objc_release with a store, load, and objc_retain to form
4206/// an objc_storeStrong. This can be a little tricky because the instructions
4207/// don't always appear in order, and there may be unrelated intervening
4208/// instructions.
John McCalld935e9c2011-06-15 23:37:01 +00004209void ObjCARCContract::ContractRelease(Instruction *Release,
4210 inst_iterator &Iter) {
4211 LoadInst *Load = dyn_cast<LoadInst>(GetObjCArg(Release));
Eli Friedman7c5dc122011-09-12 20:23:13 +00004212 if (!Load || !Load->isSimple()) return;
John McCalld935e9c2011-06-15 23:37:01 +00004213
4214 // For now, require everything to be in one basic block.
4215 BasicBlock *BB = Release->getParent();
4216 if (Load->getParent() != BB) return;
4217
Dan Gohman61708d32012-05-08 23:34:08 +00004218 // Walk down to find the store and the release, which may be in either order.
Dan Gohmanf8b19d02012-05-09 23:08:33 +00004219 BasicBlock::iterator I = Load, End = BB->end();
John McCalld935e9c2011-06-15 23:37:01 +00004220 ++I;
4221 AliasAnalysis::Location Loc = AA->getLocation(Load);
Dan Gohman61708d32012-05-08 23:34:08 +00004222 StoreInst *Store = 0;
4223 bool SawRelease = false;
4224 for (; !Store || !SawRelease; ++I) {
Dan Gohmanf8b19d02012-05-09 23:08:33 +00004225 if (I == End)
4226 return;
4227
Dan Gohman61708d32012-05-08 23:34:08 +00004228 Instruction *Inst = I;
4229 if (Inst == Release) {
4230 SawRelease = true;
4231 continue;
4232 }
4233
4234 InstructionClass Class = GetBasicInstructionClass(Inst);
4235
4236 // Unrelated retains are harmless.
4237 if (IsRetain(Class))
4238 continue;
4239
4240 if (Store) {
4241 // The store is the point where we're going to put the objc_storeStrong,
4242 // so make sure there are no uses after it.
4243 if (CanUse(Inst, Load, PA, Class))
4244 return;
4245 } else if (AA->getModRefInfo(Inst, Loc) & AliasAnalysis::Mod) {
4246 // We are moving the load down to the store, so check for anything
4247 // else which writes to the memory between the load and the store.
4248 Store = dyn_cast<StoreInst>(Inst);
4249 if (!Store || !Store->isSimple()) return;
4250 if (Store->getPointerOperand() != Loc.Ptr) return;
4251 }
4252 }
John McCalld935e9c2011-06-15 23:37:01 +00004253
4254 Value *New = StripPointerCastsAndObjCCalls(Store->getValueOperand());
4255
4256 // Walk up to find the retain.
4257 I = Store;
4258 BasicBlock::iterator Begin = BB->begin();
4259 while (I != Begin && GetBasicInstructionClass(I) != IC_Retain)
4260 --I;
4261 Instruction *Retain = I;
4262 if (GetBasicInstructionClass(Retain) != IC_Retain) return;
4263 if (GetObjCArg(Retain) != New) return;
4264
4265 Changed = true;
4266 ++NumStoreStrongs;
4267
4268 LLVMContext &C = Release->getContext();
Chris Lattner229907c2011-07-18 04:54:35 +00004269 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
4270 Type *I8XX = PointerType::getUnqual(I8X);
John McCalld935e9c2011-06-15 23:37:01 +00004271
4272 Value *Args[] = { Load->getPointerOperand(), New };
4273 if (Args[0]->getType() != I8XX)
4274 Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
4275 if (Args[1]->getType() != I8X)
4276 Args[1] = new BitCastInst(Args[1], I8X, "", Store);
4277 CallInst *StoreStrong =
4278 CallInst::Create(getStoreStrongCallee(BB->getParent()->getParent()),
Jay Foad5bd375a2011-07-15 08:37:34 +00004279 Args, "", Store);
John McCalld935e9c2011-06-15 23:37:01 +00004280 StoreStrong->setDoesNotThrow();
4281 StoreStrong->setDebugLoc(Store->getDebugLoc());
4282
Dan Gohman8ee108b2012-01-19 19:14:36 +00004283 // We can't set the tail flag yet, because we haven't yet determined
4284 // whether there are any escaping allocas. Remember this call, so that
4285 // we can set the tail flag once we know it's safe.
4286 StoreStrongCalls.insert(StoreStrong);
4287
John McCalld935e9c2011-06-15 23:37:01 +00004288 if (&*Iter == Store) ++Iter;
4289 Store->eraseFromParent();
4290 Release->eraseFromParent();
4291 EraseInstruction(Retain);
4292 if (Load->use_empty())
4293 Load->eraseFromParent();
4294}
4295
4296bool ObjCARCContract::doInitialization(Module &M) {
Dan Gohman670f9372012-04-13 18:57:48 +00004297 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanceaac7c2011-06-20 23:20:43 +00004298 Run = ModuleHasARC(M);
4299 if (!Run)
4300 return false;
4301
John McCalld935e9c2011-06-15 23:37:01 +00004302 // These are initialized lazily.
4303 StoreStrongCallee = 0;
4304 RetainAutoreleaseCallee = 0;
4305 RetainAutoreleaseRVCallee = 0;
4306
4307 // Initialize RetainRVMarker.
4308 RetainRVMarker = 0;
4309 if (NamedMDNode *NMD =
4310 M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker"))
4311 if (NMD->getNumOperands() == 1) {
4312 const MDNode *N = NMD->getOperand(0);
4313 if (N->getNumOperands() == 1)
4314 if (const MDString *S = dyn_cast<MDString>(N->getOperand(0)))
4315 RetainRVMarker = S;
4316 }
4317
4318 return false;
4319}
4320
4321bool ObjCARCContract::runOnFunction(Function &F) {
4322 if (!EnableARCOpts)
4323 return false;
4324
Dan Gohmanceaac7c2011-06-20 23:20:43 +00004325 // If nothing in the Module uses ARC, don't do anything.
4326 if (!Run)
4327 return false;
4328
John McCalld935e9c2011-06-15 23:37:01 +00004329 Changed = false;
4330 AA = &getAnalysis<AliasAnalysis>();
4331 DT = &getAnalysis<DominatorTree>();
4332
4333 PA.setAA(&getAnalysis<AliasAnalysis>());
4334
Dan Gohman8ee108b2012-01-19 19:14:36 +00004335 // Track whether it's ok to mark objc_storeStrong calls with the "tail"
4336 // keyword. Be conservative if the function has variadic arguments.
4337 // It seems that functions which "return twice" are also unsafe for the
4338 // "tail" argument, because they are setjmp, which could need to
4339 // return to an earlier stack state.
Dan Gohman41375a32012-05-08 23:39:44 +00004340 bool TailOkForStoreStrongs = !F.isVarArg() &&
4341 !F.callsFunctionThatReturnsTwice();
Dan Gohman8ee108b2012-01-19 19:14:36 +00004342
John McCalld935e9c2011-06-15 23:37:01 +00004343 // For ObjC library calls which return their argument, replace uses of the
4344 // argument with uses of the call return value, if it dominates the use. This
4345 // reduces register pressure.
4346 SmallPtrSet<Instruction *, 4> DependingInstructions;
4347 SmallPtrSet<const BasicBlock *, 4> Visited;
4348 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
4349 Instruction *Inst = &*I++;
Michael Gottesman10426b52013-01-07 21:26:07 +00004350
Michael Gottesman3f146e22013-01-01 16:05:48 +00004351 DEBUG(dbgs() << "ObjCARCContract: Visiting: " << *Inst << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00004352
John McCalld935e9c2011-06-15 23:37:01 +00004353 // Only these library routines return their argument. In particular,
4354 // objc_retainBlock does not necessarily return its argument.
4355 InstructionClass Class = GetBasicInstructionClass(Inst);
4356 switch (Class) {
4357 case IC_Retain:
4358 case IC_FusedRetainAutorelease:
4359 case IC_FusedRetainAutoreleaseRV:
4360 break;
4361 case IC_Autorelease:
4362 case IC_AutoreleaseRV:
4363 if (ContractAutorelease(F, Inst, Class, DependingInstructions, Visited))
4364 continue;
4365 break;
4366 case IC_RetainRV: {
4367 // If we're compiling for a target which needs a special inline-asm
4368 // marker to do the retainAutoreleasedReturnValue optimization,
4369 // insert it now.
4370 if (!RetainRVMarker)
4371 break;
4372 BasicBlock::iterator BBI = Inst;
Dan Gohman5f725cd2012-06-25 19:47:37 +00004373 BasicBlock *InstParent = Inst->getParent();
4374
4375 // Step up to see if the call immediately precedes the RetainRV call.
4376 // If it's an invoke, we have to cross a block boundary. And we have
4377 // to carefully dodge no-op instructions.
4378 do {
4379 if (&*BBI == InstParent->begin()) {
4380 BasicBlock *Pred = InstParent->getSinglePredecessor();
4381 if (!Pred)
4382 goto decline_rv_optimization;
4383 BBI = Pred->getTerminator();
4384 break;
4385 }
4386 --BBI;
4387 } while (isNoopInstruction(BBI));
4388
John McCalld935e9c2011-06-15 23:37:01 +00004389 if (&*BBI == GetObjCArg(Inst)) {
Michael Gottesman00d1f962013-01-03 07:32:41 +00004390 DEBUG(dbgs() << "ObjCARCContract: Adding inline asm marker for "
Michael Gottesman9f848ae2013-01-04 21:29:57 +00004391 "retainAutoreleasedReturnValue optimization.\n");
Dan Gohman670f9372012-04-13 18:57:48 +00004392 Changed = true;
John McCalld935e9c2011-06-15 23:37:01 +00004393 InlineAsm *IA =
4394 InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()),
4395 /*isVarArg=*/false),
4396 RetainRVMarker->getString(),
4397 /*Constraints=*/"", /*hasSideEffects=*/true);
4398 CallInst::Create(IA, "", Inst);
4399 }
Dan Gohman5f725cd2012-06-25 19:47:37 +00004400 decline_rv_optimization:
John McCalld935e9c2011-06-15 23:37:01 +00004401 break;
4402 }
4403 case IC_InitWeak: {
4404 // objc_initWeak(p, null) => *p = null
4405 CallInst *CI = cast<CallInst>(Inst);
4406 if (isNullOrUndef(CI->getArgOperand(1))) {
4407 Value *Null =
4408 ConstantPointerNull::get(cast<PointerType>(CI->getType()));
4409 Changed = true;
4410 new StoreInst(Null, CI->getArgOperand(0), CI);
Michael Gottesman10426b52013-01-07 21:26:07 +00004411
Michael Gottesman416dc002013-01-03 07:32:53 +00004412 DEBUG(dbgs() << "OBJCARCContract: Old = " << *CI << "\n"
4413 << " New = " << *Null << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00004414
John McCalld935e9c2011-06-15 23:37:01 +00004415 CI->replaceAllUsesWith(Null);
4416 CI->eraseFromParent();
4417 }
4418 continue;
4419 }
4420 case IC_Release:
4421 ContractRelease(Inst, I);
4422 continue;
Dan Gohman8ee108b2012-01-19 19:14:36 +00004423 case IC_User:
4424 // Be conservative if the function has any alloca instructions.
4425 // Technically we only care about escaping alloca instructions,
4426 // but this is sufficient to handle some interesting cases.
4427 if (isa<AllocaInst>(Inst))
4428 TailOkForStoreStrongs = false;
4429 continue;
John McCalld935e9c2011-06-15 23:37:01 +00004430 default:
4431 continue;
4432 }
4433
Michael Gottesman50ae5b22013-01-03 08:09:27 +00004434 DEBUG(dbgs() << "ObjCARCContract: Finished List.\n\n");
Michael Gottesman3f146e22013-01-01 16:05:48 +00004435
John McCalld935e9c2011-06-15 23:37:01 +00004436 // Don't use GetObjCArg because we don't want to look through bitcasts
4437 // and such; to do the replacement, the argument must have type i8*.
4438 const Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
4439 for (;;) {
4440 // If we're compiling bugpointed code, don't get in trouble.
4441 if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
4442 break;
4443 // Look through the uses of the pointer.
4444 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
4445 UI != UE; ) {
4446 Use &U = UI.getUse();
4447 unsigned OperandNo = UI.getOperandNo();
4448 ++UI; // Increment UI now, because we may unlink its element.
Dan Gohman670f9372012-04-13 18:57:48 +00004449
4450 // If the call's return value dominates a use of the call's argument
4451 // value, rewrite the use to use the return value. We check for
4452 // reachability here because an unreachable call is considered to
4453 // trivially dominate itself, which would lead us to rewriting its
4454 // argument in terms of its return value, which would lead to
4455 // infinite loops in GetObjCArg.
Dan Gohman41375a32012-05-08 23:39:44 +00004456 if (DT->isReachableFromEntry(U) && DT->dominates(Inst, U)) {
Rafael Espindolaf5892782012-03-15 15:52:59 +00004457 Changed = true;
4458 Instruction *Replacement = Inst;
4459 Type *UseTy = U.get()->getType();
Dan Gohmande8d2c42012-04-13 01:08:28 +00004460 if (PHINode *PHI = dyn_cast<PHINode>(U.getUser())) {
Rafael Espindolaf5892782012-03-15 15:52:59 +00004461 // For PHI nodes, insert the bitcast in the predecessor block.
Dan Gohman41375a32012-05-08 23:39:44 +00004462 unsigned ValNo = PHINode::getIncomingValueNumForOperand(OperandNo);
4463 BasicBlock *BB = PHI->getIncomingBlock(ValNo);
Rafael Espindolaf5892782012-03-15 15:52:59 +00004464 if (Replacement->getType() != UseTy)
4465 Replacement = new BitCastInst(Replacement, UseTy, "",
4466 &BB->back());
Dan Gohman670f9372012-04-13 18:57:48 +00004467 // While we're here, rewrite all edges for this PHI, rather
4468 // than just one use at a time, to minimize the number of
4469 // bitcasts we emit.
Dan Gohmandae33492012-04-27 18:56:31 +00004470 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
Rafael Espindolaf5892782012-03-15 15:52:59 +00004471 if (PHI->getIncomingBlock(i) == BB) {
4472 // Keep the UI iterator valid.
4473 if (&PHI->getOperandUse(
4474 PHINode::getOperandNumForIncomingValue(i)) ==
4475 &UI.getUse())
4476 ++UI;
4477 PHI->setIncomingValue(i, Replacement);
4478 }
4479 } else {
4480 if (Replacement->getType() != UseTy)
Dan Gohmande8d2c42012-04-13 01:08:28 +00004481 Replacement = new BitCastInst(Replacement, UseTy, "",
4482 cast<Instruction>(U.getUser()));
Rafael Espindolaf5892782012-03-15 15:52:59 +00004483 U.set(Replacement);
John McCalld935e9c2011-06-15 23:37:01 +00004484 }
Rafael Espindolaf5892782012-03-15 15:52:59 +00004485 }
John McCalld935e9c2011-06-15 23:37:01 +00004486 }
4487
Dan Gohmandae33492012-04-27 18:56:31 +00004488 // If Arg is a no-op casted pointer, strip one level of casts and iterate.
John McCalld935e9c2011-06-15 23:37:01 +00004489 if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
4490 Arg = BI->getOperand(0);
4491 else if (isa<GEPOperator>(Arg) &&
4492 cast<GEPOperator>(Arg)->hasAllZeroIndices())
4493 Arg = cast<GEPOperator>(Arg)->getPointerOperand();
4494 else if (isa<GlobalAlias>(Arg) &&
4495 !cast<GlobalAlias>(Arg)->mayBeOverridden())
4496 Arg = cast<GlobalAlias>(Arg)->getAliasee();
4497 else
4498 break;
4499 }
4500 }
4501
Dan Gohman8ee108b2012-01-19 19:14:36 +00004502 // If this function has no escaping allocas or suspicious vararg usage,
4503 // objc_storeStrong calls can be marked with the "tail" keyword.
4504 if (TailOkForStoreStrongs)
Dan Gohman41375a32012-05-08 23:39:44 +00004505 for (SmallPtrSet<CallInst *, 8>::iterator I = StoreStrongCalls.begin(),
Dan Gohman8ee108b2012-01-19 19:14:36 +00004506 E = StoreStrongCalls.end(); I != E; ++I)
4507 (*I)->setTailCall();
4508 StoreStrongCalls.clear();
4509
John McCalld935e9c2011-06-15 23:37:01 +00004510 return Changed;
4511}
Michael Gottesman97e3df02013-01-14 00:35:14 +00004512
4513/// @}
4514///