blob: 1c054f9b0bc0efe5f211d45f96bb2826a9752fb8 [file] [log] [blame]
John McCalld935e9c2011-06-15 23:37:01 +00001//===- ObjCARC.cpp - ObjC ARC Optimization --------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Michael Gottesman97e3df02013-01-14 00:35:14 +00009/// \file
10/// This file defines ObjC ARC optimizations. ARC stands for Automatic
11/// Reference Counting and is a system for managing reference counts for objects
12/// in Objective C.
13///
14/// The optimizations performed include elimination of redundant, partially
15/// redundant, and inconsequential reference count operations, elimination of
16/// redundant weak pointer operations, pattern-matching and replacement of
17/// low-level operations into higher-level operations, and numerous minor
18/// simplifications.
19///
20/// This file also defines a simple ARC-aware AliasAnalysis.
21///
22/// WARNING: This file knows about certain library functions. It recognizes them
23/// by name, and hardwires knowledge of their semantics.
24///
25/// WARNING: This file knows about how certain Objective-C library functions are
26/// used. Naive LLVM IR transformations which would otherwise be
27/// behavior-preserving may break these assumptions.
28///
John McCalld935e9c2011-06-15 23:37:01 +000029//===----------------------------------------------------------------------===//
30
31#define DEBUG_TYPE "objc-arc"
John McCalld935e9c2011-06-15 23:37:01 +000032#include "llvm/ADT/DenseMap.h"
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +000033#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000034#include "llvm/Support/CommandLine.h"
Chandler Carruthbe810232013-01-02 10:22:59 +000035#include "llvm/Support/Debug.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000036#include "llvm/Support/raw_ostream.h"
John McCalld935e9c2011-06-15 23:37:01 +000037using namespace llvm;
38
Michael Gottesman97e3df02013-01-14 00:35:14 +000039/// \brief A handy option to enable/disable all optimizations in this file.
John McCalld935e9c2011-06-15 23:37:01 +000040static cl::opt<bool> EnableARCOpts("enable-objc-arc-opts", cl::init(true));
41
Michael Gottesman97e3df02013-01-14 00:35:14 +000042/// \defgroup MiscUtils Miscellaneous utilities that are not ARC specific.
43/// @{
John McCalld935e9c2011-06-15 23:37:01 +000044
45namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +000046 /// \brief An associative container with fast insertion-order (deterministic)
47 /// iteration over its elements. Plus the special blot operation.
John McCalld935e9c2011-06-15 23:37:01 +000048 template<class KeyT, class ValueT>
49 class MapVector {
Michael Gottesman97e3df02013-01-14 00:35:14 +000050 /// Map keys to indices in Vector.
John McCalld935e9c2011-06-15 23:37:01 +000051 typedef DenseMap<KeyT, size_t> MapTy;
52 MapTy Map;
53
John McCalld935e9c2011-06-15 23:37:01 +000054 typedef std::vector<std::pair<KeyT, ValueT> > VectorTy;
Michael Gottesman97e3df02013-01-14 00:35:14 +000055 /// Keys and values.
John McCalld935e9c2011-06-15 23:37:01 +000056 VectorTy Vector;
57
58 public:
59 typedef typename VectorTy::iterator iterator;
60 typedef typename VectorTy::const_iterator const_iterator;
61 iterator begin() { return Vector.begin(); }
62 iterator end() { return Vector.end(); }
63 const_iterator begin() const { return Vector.begin(); }
64 const_iterator end() const { return Vector.end(); }
65
66#ifdef XDEBUG
67 ~MapVector() {
68 assert(Vector.size() >= Map.size()); // May differ due to blotting.
69 for (typename MapTy::const_iterator I = Map.begin(), E = Map.end();
70 I != E; ++I) {
71 assert(I->second < Vector.size());
72 assert(Vector[I->second].first == I->first);
73 }
74 for (typename VectorTy::const_iterator I = Vector.begin(),
75 E = Vector.end(); I != E; ++I)
76 assert(!I->first ||
77 (Map.count(I->first) &&
78 Map[I->first] == size_t(I - Vector.begin())));
79 }
80#endif
81
Dan Gohman55b06742012-03-02 01:13:53 +000082 ValueT &operator[](const KeyT &Arg) {
John McCalld935e9c2011-06-15 23:37:01 +000083 std::pair<typename MapTy::iterator, bool> Pair =
84 Map.insert(std::make_pair(Arg, size_t(0)));
85 if (Pair.second) {
Dan Gohman55b06742012-03-02 01:13:53 +000086 size_t Num = Vector.size();
87 Pair.first->second = Num;
John McCalld935e9c2011-06-15 23:37:01 +000088 Vector.push_back(std::make_pair(Arg, ValueT()));
Dan Gohman55b06742012-03-02 01:13:53 +000089 return Vector[Num].second;
John McCalld935e9c2011-06-15 23:37:01 +000090 }
91 return Vector[Pair.first->second].second;
92 }
93
94 std::pair<iterator, bool>
95 insert(const std::pair<KeyT, ValueT> &InsertPair) {
96 std::pair<typename MapTy::iterator, bool> Pair =
97 Map.insert(std::make_pair(InsertPair.first, size_t(0)));
98 if (Pair.second) {
Dan Gohman55b06742012-03-02 01:13:53 +000099 size_t Num = Vector.size();
100 Pair.first->second = Num;
John McCalld935e9c2011-06-15 23:37:01 +0000101 Vector.push_back(InsertPair);
Dan Gohman55b06742012-03-02 01:13:53 +0000102 return std::make_pair(Vector.begin() + Num, true);
John McCalld935e9c2011-06-15 23:37:01 +0000103 }
104 return std::make_pair(Vector.begin() + Pair.first->second, false);
105 }
106
Dan Gohman55b06742012-03-02 01:13:53 +0000107 const_iterator find(const KeyT &Key) const {
John McCalld935e9c2011-06-15 23:37:01 +0000108 typename MapTy::const_iterator It = Map.find(Key);
109 if (It == Map.end()) return Vector.end();
110 return Vector.begin() + It->second;
111 }
112
Michael Gottesman97e3df02013-01-14 00:35:14 +0000113 /// This is similar to erase, but instead of removing the element from the
114 /// vector, it just zeros out the key in the vector. This leaves iterators
115 /// intact, but clients must be prepared for zeroed-out keys when iterating.
Dan Gohman55b06742012-03-02 01:13:53 +0000116 void blot(const KeyT &Key) {
John McCalld935e9c2011-06-15 23:37:01 +0000117 typename MapTy::iterator It = Map.find(Key);
118 if (It == Map.end()) return;
119 Vector[It->second].first = KeyT();
120 Map.erase(It);
121 }
122
123 void clear() {
124 Map.clear();
125 Vector.clear();
126 }
127 };
128}
129
Michael Gottesman97e3df02013-01-14 00:35:14 +0000130/// @}
131///
132/// \defgroup ARCUtilities Utility declarations/definitions specific to ARC.
133/// @{
John McCalld935e9c2011-06-15 23:37:01 +0000134
Chandler Carruthed0881b2012-12-03 16:50:05 +0000135#include "llvm/ADT/StringSwitch.h"
136#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +0000137#include "llvm/IR/Intrinsics.h"
138#include "llvm/IR/Module.h"
Dan Gohman41375a32012-05-08 23:39:44 +0000139#include "llvm/Support/CallSite.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +0000140#include "llvm/Transforms/Utils/Local.h"
Dan Gohman41375a32012-05-08 23:39:44 +0000141
John McCalld935e9c2011-06-15 23:37:01 +0000142namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000143 /// \enum InstructionClass
144 /// \brief A simple classification for instructions.
John McCalld935e9c2011-06-15 23:37:01 +0000145 enum InstructionClass {
146 IC_Retain, ///< objc_retain
147 IC_RetainRV, ///< objc_retainAutoreleasedReturnValue
148 IC_RetainBlock, ///< objc_retainBlock
149 IC_Release, ///< objc_release
150 IC_Autorelease, ///< objc_autorelease
151 IC_AutoreleaseRV, ///< objc_autoreleaseReturnValue
152 IC_AutoreleasepoolPush, ///< objc_autoreleasePoolPush
153 IC_AutoreleasepoolPop, ///< objc_autoreleasePoolPop
154 IC_NoopCast, ///< objc_retainedObject, etc.
155 IC_FusedRetainAutorelease, ///< objc_retainAutorelease
156 IC_FusedRetainAutoreleaseRV, ///< objc_retainAutoreleaseReturnValue
157 IC_LoadWeakRetained, ///< objc_loadWeakRetained (primitive)
158 IC_StoreWeak, ///< objc_storeWeak (primitive)
159 IC_InitWeak, ///< objc_initWeak (derived)
160 IC_LoadWeak, ///< objc_loadWeak (derived)
161 IC_MoveWeak, ///< objc_moveWeak (derived)
162 IC_CopyWeak, ///< objc_copyWeak (derived)
163 IC_DestroyWeak, ///< objc_destroyWeak (derived)
Dan Gohmane1e352a2012-04-13 18:28:58 +0000164 IC_StoreStrong, ///< objc_storeStrong (derived)
John McCalld935e9c2011-06-15 23:37:01 +0000165 IC_CallOrUser, ///< could call objc_release and/or "use" pointers
166 IC_Call, ///< could call objc_release
167 IC_User, ///< could "use" a pointer
168 IC_None ///< anything else
169 };
Michael Gottesman782e3442013-01-17 18:32:34 +0000170
171 raw_ostream &operator<<(raw_ostream &OS, const InstructionClass Class)
172 LLVM_ATTRIBUTE_USED;
Michael Gottesman1d777512013-01-17 18:36:17 +0000173 raw_ostream &operator<<(raw_ostream &OS, const InstructionClass Class) {
Michael Gottesman782e3442013-01-17 18:32:34 +0000174 switch (Class) {
175 case IC_Retain:
176 return OS << "IC_Retain";
177 case IC_RetainRV:
178 return OS << "IC_RetainRV";
179 case IC_RetainBlock:
180 return OS << "IC_RetainBlock";
181 case IC_Release:
182 return OS << "IC_Release";
183 case IC_Autorelease:
184 return OS << "IC_Autorelease";
185 case IC_AutoreleaseRV:
186 return OS << "IC_AutoreleaseRV";
187 case IC_AutoreleasepoolPush:
188 return OS << "IC_AutoreleasepoolPush";
189 case IC_AutoreleasepoolPop:
190 return OS << "IC_AutoreleasepoolPop";
191 case IC_NoopCast:
192 return OS << "IC_NoopCast";
193 case IC_FusedRetainAutorelease:
194 return OS << "IC_FusedRetainAutorelease";
195 case IC_FusedRetainAutoreleaseRV:
196 return OS << "IC_FusedRetainAutoreleaseRV";
197 case IC_LoadWeakRetained:
198 return OS << "IC_LoadWeakRetained";
199 case IC_StoreWeak:
200 return OS << "IC_StoreWeak";
201 case IC_InitWeak:
202 return OS << "IC_InitWeak";
203 case IC_LoadWeak:
204 return OS << "IC_LoadWeak";
205 case IC_MoveWeak:
206 return OS << "IC_MoveWeak";
207 case IC_CopyWeak:
208 return OS << "IC_CopyWeak";
209 case IC_DestroyWeak:
210 return OS << "IC_DestroyWeak";
211 case IC_StoreStrong:
212 return OS << "IC_StoreStrong";
213 case IC_CallOrUser:
214 return OS << "IC_CallOrUser";
215 case IC_Call:
216 return OS << "IC_Call";
217 case IC_User:
218 return OS << "IC_User";
219 case IC_None:
220 return OS << "IC_None";
221 }
Benjamin Kramer0eba5772013-01-18 19:45:22 +0000222 llvm_unreachable("Unknown instruction class!");
Michael Gottesman782e3442013-01-17 18:32:34 +0000223 }
John McCalld935e9c2011-06-15 23:37:01 +0000224}
225
Michael Gottesman97e3df02013-01-14 00:35:14 +0000226/// \brief Test whether the given value is possible a reference-counted pointer.
John McCalld935e9c2011-06-15 23:37:01 +0000227static bool IsPotentialUse(const Value *Op) {
228 // Pointers to static or stack storage are not reference-counted pointers.
229 if (isa<Constant>(Op) || isa<AllocaInst>(Op))
230 return false;
231 // Special arguments are not reference-counted.
232 if (const Argument *Arg = dyn_cast<Argument>(Op))
233 if (Arg->hasByValAttr() ||
234 Arg->hasNestAttr() ||
235 Arg->hasStructRetAttr())
236 return false;
Dan Gohmanbd944b42011-12-14 19:10:53 +0000237 // Only consider values with pointer types.
238 // It seemes intuitive to exclude function pointer types as well, since
239 // functions are never reference-counted, however clang occasionally
240 // bitcasts reference-counted pointers to function-pointer type
241 // temporarily.
Chris Lattner229907c2011-07-18 04:54:35 +0000242 PointerType *Ty = dyn_cast<PointerType>(Op->getType());
Dan Gohmanbd944b42011-12-14 19:10:53 +0000243 if (!Ty)
John McCalld935e9c2011-06-15 23:37:01 +0000244 return false;
245 // Conservatively assume anything else is a potential use.
246 return true;
247}
248
Michael Gottesman4385edf2013-01-14 01:47:53 +0000249/// \brief Helper for GetInstructionClass. Determines what kind of construct CS
250/// is.
John McCalld935e9c2011-06-15 23:37:01 +0000251static InstructionClass GetCallSiteClass(ImmutableCallSite CS) {
252 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
253 I != E; ++I)
254 if (IsPotentialUse(*I))
255 return CS.onlyReadsMemory() ? IC_User : IC_CallOrUser;
256
257 return CS.onlyReadsMemory() ? IC_None : IC_Call;
258}
259
Michael Gottesman97e3df02013-01-14 00:35:14 +0000260/// \brief Determine if F is one of the special known Functions. If it isn't,
261/// return IC_CallOrUser.
John McCalld935e9c2011-06-15 23:37:01 +0000262static InstructionClass GetFunctionClass(const Function *F) {
263 Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
264
265 // No arguments.
266 if (AI == AE)
267 return StringSwitch<InstructionClass>(F->getName())
268 .Case("objc_autoreleasePoolPush", IC_AutoreleasepoolPush)
269 .Default(IC_CallOrUser);
270
271 // One argument.
272 const Argument *A0 = AI++;
273 if (AI == AE)
274 // Argument is a pointer.
Chris Lattner229907c2011-07-18 04:54:35 +0000275 if (PointerType *PTy = dyn_cast<PointerType>(A0->getType())) {
276 Type *ETy = PTy->getElementType();
John McCalld935e9c2011-06-15 23:37:01 +0000277 // Argument is i8*.
278 if (ETy->isIntegerTy(8))
279 return StringSwitch<InstructionClass>(F->getName())
280 .Case("objc_retain", IC_Retain)
281 .Case("objc_retainAutoreleasedReturnValue", IC_RetainRV)
282 .Case("objc_retainBlock", IC_RetainBlock)
283 .Case("objc_release", IC_Release)
284 .Case("objc_autorelease", IC_Autorelease)
285 .Case("objc_autoreleaseReturnValue", IC_AutoreleaseRV)
286 .Case("objc_autoreleasePoolPop", IC_AutoreleasepoolPop)
287 .Case("objc_retainedObject", IC_NoopCast)
288 .Case("objc_unretainedObject", IC_NoopCast)
289 .Case("objc_unretainedPointer", IC_NoopCast)
290 .Case("objc_retain_autorelease", IC_FusedRetainAutorelease)
291 .Case("objc_retainAutorelease", IC_FusedRetainAutorelease)
292 .Case("objc_retainAutoreleaseReturnValue",IC_FusedRetainAutoreleaseRV)
293 .Default(IC_CallOrUser);
294
295 // Argument is i8**
Chris Lattner229907c2011-07-18 04:54:35 +0000296 if (PointerType *Pte = dyn_cast<PointerType>(ETy))
John McCalld935e9c2011-06-15 23:37:01 +0000297 if (Pte->getElementType()->isIntegerTy(8))
298 return StringSwitch<InstructionClass>(F->getName())
299 .Case("objc_loadWeakRetained", IC_LoadWeakRetained)
300 .Case("objc_loadWeak", IC_LoadWeak)
301 .Case("objc_destroyWeak", IC_DestroyWeak)
302 .Default(IC_CallOrUser);
303 }
304
305 // Two arguments, first is i8**.
306 const Argument *A1 = AI++;
307 if (AI == AE)
Chris Lattner229907c2011-07-18 04:54:35 +0000308 if (PointerType *PTy = dyn_cast<PointerType>(A0->getType()))
309 if (PointerType *Pte = dyn_cast<PointerType>(PTy->getElementType()))
John McCalld935e9c2011-06-15 23:37:01 +0000310 if (Pte->getElementType()->isIntegerTy(8))
Chris Lattner229907c2011-07-18 04:54:35 +0000311 if (PointerType *PTy1 = dyn_cast<PointerType>(A1->getType())) {
312 Type *ETy1 = PTy1->getElementType();
John McCalld935e9c2011-06-15 23:37:01 +0000313 // Second argument is i8*
314 if (ETy1->isIntegerTy(8))
315 return StringSwitch<InstructionClass>(F->getName())
316 .Case("objc_storeWeak", IC_StoreWeak)
317 .Case("objc_initWeak", IC_InitWeak)
Dan Gohmane1e352a2012-04-13 18:28:58 +0000318 .Case("objc_storeStrong", IC_StoreStrong)
John McCalld935e9c2011-06-15 23:37:01 +0000319 .Default(IC_CallOrUser);
320 // Second argument is i8**.
Chris Lattner229907c2011-07-18 04:54:35 +0000321 if (PointerType *Pte1 = dyn_cast<PointerType>(ETy1))
John McCalld935e9c2011-06-15 23:37:01 +0000322 if (Pte1->getElementType()->isIntegerTy(8))
323 return StringSwitch<InstructionClass>(F->getName())
324 .Case("objc_moveWeak", IC_MoveWeak)
325 .Case("objc_copyWeak", IC_CopyWeak)
326 .Default(IC_CallOrUser);
327 }
328
329 // Anything else.
330 return IC_CallOrUser;
331}
332
Michael Gottesman97e3df02013-01-14 00:35:14 +0000333/// \brief Determine what kind of construct V is.
John McCalld935e9c2011-06-15 23:37:01 +0000334static InstructionClass GetInstructionClass(const Value *V) {
335 if (const Instruction *I = dyn_cast<Instruction>(V)) {
336 // Any instruction other than bitcast and gep with a pointer operand have a
337 // use of an objc pointer. Bitcasts, GEPs, Selects, PHIs transfer a pointer
338 // to a subsequent use, rather than using it themselves, in this sense.
339 // As a short cut, several other opcodes are known to have no pointer
340 // operands of interest. And ret is never followed by a release, so it's
341 // not interesting to examine.
342 switch (I->getOpcode()) {
343 case Instruction::Call: {
344 const CallInst *CI = cast<CallInst>(I);
345 // Check for calls to special functions.
346 if (const Function *F = CI->getCalledFunction()) {
347 InstructionClass Class = GetFunctionClass(F);
348 if (Class != IC_CallOrUser)
349 return Class;
350
351 // None of the intrinsic functions do objc_release. For intrinsics, the
352 // only question is whether or not they may be users.
353 switch (F->getIntrinsicID()) {
John McCalld935e9c2011-06-15 23:37:01 +0000354 case Intrinsic::returnaddress: case Intrinsic::frameaddress:
355 case Intrinsic::stacksave: case Intrinsic::stackrestore:
356 case Intrinsic::vastart: case Intrinsic::vacopy: case Intrinsic::vaend:
Dan Gohman41375a32012-05-08 23:39:44 +0000357 case Intrinsic::objectsize: case Intrinsic::prefetch:
358 case Intrinsic::stackprotector:
359 case Intrinsic::eh_return_i32: case Intrinsic::eh_return_i64:
360 case Intrinsic::eh_typeid_for: case Intrinsic::eh_dwarf_cfa:
361 case Intrinsic::eh_sjlj_lsda: case Intrinsic::eh_sjlj_functioncontext:
362 case Intrinsic::init_trampoline: case Intrinsic::adjust_trampoline:
363 case Intrinsic::lifetime_start: case Intrinsic::lifetime_end:
364 case Intrinsic::invariant_start: case Intrinsic::invariant_end:
John McCalld935e9c2011-06-15 23:37:01 +0000365 // Don't let dbg info affect our results.
366 case Intrinsic::dbg_declare: case Intrinsic::dbg_value:
367 // Short cut: Some intrinsics obviously don't use ObjC pointers.
368 return IC_None;
369 default:
Dan Gohman41375a32012-05-08 23:39:44 +0000370 break;
John McCalld935e9c2011-06-15 23:37:01 +0000371 }
372 }
373 return GetCallSiteClass(CI);
374 }
375 case Instruction::Invoke:
376 return GetCallSiteClass(cast<InvokeInst>(I));
377 case Instruction::BitCast:
378 case Instruction::GetElementPtr:
379 case Instruction::Select: case Instruction::PHI:
380 case Instruction::Ret: case Instruction::Br:
381 case Instruction::Switch: case Instruction::IndirectBr:
382 case Instruction::Alloca: case Instruction::VAArg:
383 case Instruction::Add: case Instruction::FAdd:
384 case Instruction::Sub: case Instruction::FSub:
385 case Instruction::Mul: case Instruction::FMul:
386 case Instruction::SDiv: case Instruction::UDiv: case Instruction::FDiv:
387 case Instruction::SRem: case Instruction::URem: case Instruction::FRem:
388 case Instruction::Shl: case Instruction::LShr: case Instruction::AShr:
389 case Instruction::And: case Instruction::Or: case Instruction::Xor:
390 case Instruction::SExt: case Instruction::ZExt: case Instruction::Trunc:
391 case Instruction::IntToPtr: case Instruction::FCmp:
392 case Instruction::FPTrunc: case Instruction::FPExt:
393 case Instruction::FPToUI: case Instruction::FPToSI:
394 case Instruction::UIToFP: case Instruction::SIToFP:
395 case Instruction::InsertElement: case Instruction::ExtractElement:
396 case Instruction::ShuffleVector:
397 case Instruction::ExtractValue:
398 break;
399 case Instruction::ICmp:
400 // Comparing a pointer with null, or any other constant, isn't an
401 // interesting use, because we don't care what the pointer points to, or
402 // about the values of any other dynamic reference-counted pointers.
403 if (IsPotentialUse(I->getOperand(1)))
404 return IC_User;
405 break;
406 default:
407 // For anything else, check all the operands.
Dan Gohman4b8e8ce2011-08-22 17:29:37 +0000408 // Note that this includes both operands of a Store: while the first
409 // operand isn't actually being dereferenced, it is being stored to
410 // memory where we can no longer track who might read it and dereference
411 // it, so we have to consider it potentially used.
John McCalld935e9c2011-06-15 23:37:01 +0000412 for (User::const_op_iterator OI = I->op_begin(), OE = I->op_end();
413 OI != OE; ++OI)
414 if (IsPotentialUse(*OI))
415 return IC_User;
416 }
417 }
418
419 // Otherwise, it's totally inert for ARC purposes.
420 return IC_None;
421}
422
Michael Gottesman97e3df02013-01-14 00:35:14 +0000423/// \brief Determine which objc runtime call instruction class V belongs to.
424///
425/// This is similar to GetInstructionClass except that it only detects objc
426/// runtime calls. This allows it to be faster.
427///
John McCalld935e9c2011-06-15 23:37:01 +0000428static InstructionClass GetBasicInstructionClass(const Value *V) {
429 if (const CallInst *CI = dyn_cast<CallInst>(V)) {
430 if (const Function *F = CI->getCalledFunction())
431 return GetFunctionClass(F);
432 // Otherwise, be conservative.
433 return IC_CallOrUser;
434 }
435
436 // Otherwise, be conservative.
Dan Gohmane7a243f2012-01-17 20:52:24 +0000437 return isa<InvokeInst>(V) ? IC_CallOrUser : IC_User;
John McCalld935e9c2011-06-15 23:37:01 +0000438}
439
Michael Gottesman97e3df02013-01-14 00:35:14 +0000440/// \brief Test if the given class is objc_retain or equivalent.
John McCalld935e9c2011-06-15 23:37:01 +0000441static bool IsRetain(InstructionClass Class) {
442 return Class == IC_Retain ||
443 Class == IC_RetainRV;
444}
445
Michael Gottesman97e3df02013-01-14 00:35:14 +0000446/// \brief Test if the given class is objc_autorelease or equivalent.
John McCalld935e9c2011-06-15 23:37:01 +0000447static bool IsAutorelease(InstructionClass Class) {
448 return Class == IC_Autorelease ||
449 Class == IC_AutoreleaseRV;
450}
451
Michael Gottesman97e3df02013-01-14 00:35:14 +0000452/// \brief Test if the given class represents instructions which return their
453/// argument verbatim.
John McCalld935e9c2011-06-15 23:37:01 +0000454static bool IsForwarding(InstructionClass Class) {
455 // objc_retainBlock technically doesn't always return its argument
456 // verbatim, but it doesn't matter for our purposes here.
457 return Class == IC_Retain ||
458 Class == IC_RetainRV ||
459 Class == IC_Autorelease ||
460 Class == IC_AutoreleaseRV ||
461 Class == IC_RetainBlock ||
462 Class == IC_NoopCast;
463}
464
Michael Gottesman97e3df02013-01-14 00:35:14 +0000465/// \brief Test if the given class represents instructions which do nothing if
466/// passed a null pointer.
John McCalld935e9c2011-06-15 23:37:01 +0000467static bool IsNoopOnNull(InstructionClass Class) {
468 return Class == IC_Retain ||
469 Class == IC_RetainRV ||
470 Class == IC_Release ||
471 Class == IC_Autorelease ||
472 Class == IC_AutoreleaseRV ||
473 Class == IC_RetainBlock;
474}
475
Michael Gottesman4385edf2013-01-14 01:47:53 +0000476/// \brief Test if the given class represents instructions which are always safe
477/// to mark with the "tail" keyword.
John McCalld935e9c2011-06-15 23:37:01 +0000478static bool IsAlwaysTail(InstructionClass Class) {
479 // IC_RetainBlock may be given a stack argument.
480 return Class == IC_Retain ||
481 Class == IC_RetainRV ||
John McCalld935e9c2011-06-15 23:37:01 +0000482 Class == IC_AutoreleaseRV;
483}
484
Michael Gottesmanc9656fa2013-01-12 01:25:15 +0000485/// \brief Test if the given class represents instructions which are never safe
486/// to mark with the "tail" keyword.
487static bool IsNeverTail(InstructionClass Class) {
488 /// It is never safe to tail call objc_autorelease since by tail calling
489 /// objc_autorelease, we also tail call -[NSObject autorelease] which supports
490 /// fast autoreleasing causing our object to be potentially reclaimed from the
491 /// autorelease pool which violates the semantics of __autoreleasing types in
492 /// ARC.
493 return Class == IC_Autorelease;
494}
495
Michael Gottesman97e3df02013-01-14 00:35:14 +0000496/// \brief Test if the given class represents instructions which are always safe
497/// to mark with the nounwind attribute.
John McCalld935e9c2011-06-15 23:37:01 +0000498static bool IsNoThrow(InstructionClass Class) {
Dan Gohmanfca43c22011-09-14 18:33:34 +0000499 // objc_retainBlock is not nounwind because it calls user copy constructors
500 // which could theoretically throw.
John McCalld935e9c2011-06-15 23:37:01 +0000501 return Class == IC_Retain ||
502 Class == IC_RetainRV ||
John McCalld935e9c2011-06-15 23:37:01 +0000503 Class == IC_Release ||
504 Class == IC_Autorelease ||
505 Class == IC_AutoreleaseRV ||
506 Class == IC_AutoreleasepoolPush ||
507 Class == IC_AutoreleasepoolPop;
508}
509
Michael Gottesman97e3df02013-01-14 00:35:14 +0000510/// \brief Erase the given instruction.
511///
512/// Many ObjC calls return their argument verbatim,
513/// so if it's such a call and the return value has users, replace them with the
514/// argument value.
515///
John McCalld935e9c2011-06-15 23:37:01 +0000516static void EraseInstruction(Instruction *CI) {
517 Value *OldArg = cast<CallInst>(CI)->getArgOperand(0);
518
519 bool Unused = CI->use_empty();
520
521 if (!Unused) {
522 // Replace the return value with the argument.
523 assert(IsForwarding(GetBasicInstructionClass(CI)) &&
524 "Can't delete non-forwarding instruction with users!");
525 CI->replaceAllUsesWith(OldArg);
526 }
527
528 CI->eraseFromParent();
529
530 if (Unused)
531 RecursivelyDeleteTriviallyDeadInstructions(OldArg);
532}
533
Michael Gottesman97e3df02013-01-14 00:35:14 +0000534/// \brief This is a wrapper around getUnderlyingObject which also knows how to
535/// look through objc_retain and objc_autorelease calls, which we know to return
536/// their argument verbatim.
John McCalld935e9c2011-06-15 23:37:01 +0000537static const Value *GetUnderlyingObjCPtr(const Value *V) {
538 for (;;) {
539 V = GetUnderlyingObject(V);
540 if (!IsForwarding(GetBasicInstructionClass(V)))
541 break;
542 V = cast<CallInst>(V)->getArgOperand(0);
543 }
544
545 return V;
546}
547
Michael Gottesman97e3df02013-01-14 00:35:14 +0000548/// \brief This is a wrapper around Value::stripPointerCasts which also knows
549/// how to look through objc_retain and objc_autorelease calls, which we know to
550/// return their argument verbatim.
John McCalld935e9c2011-06-15 23:37:01 +0000551static const Value *StripPointerCastsAndObjCCalls(const Value *V) {
552 for (;;) {
553 V = V->stripPointerCasts();
554 if (!IsForwarding(GetBasicInstructionClass(V)))
555 break;
556 V = cast<CallInst>(V)->getArgOperand(0);
557 }
558 return V;
559}
560
Michael Gottesman97e3df02013-01-14 00:35:14 +0000561/// \brief This is a wrapper around Value::stripPointerCasts which also knows
562/// how to look through objc_retain and objc_autorelease calls, which we know to
563/// return their argument verbatim.
John McCalld935e9c2011-06-15 23:37:01 +0000564static Value *StripPointerCastsAndObjCCalls(Value *V) {
565 for (;;) {
566 V = V->stripPointerCasts();
567 if (!IsForwarding(GetBasicInstructionClass(V)))
568 break;
569 V = cast<CallInst>(V)->getArgOperand(0);
570 }
571 return V;
572}
573
Michael Gottesman97e3df02013-01-14 00:35:14 +0000574/// \brief Assuming the given instruction is one of the special calls such as
575/// objc_retain or objc_release, return the argument value, stripped of no-op
John McCalld935e9c2011-06-15 23:37:01 +0000576/// casts and forwarding calls.
577static Value *GetObjCArg(Value *Inst) {
578 return StripPointerCastsAndObjCCalls(cast<CallInst>(Inst)->getArgOperand(0));
579}
580
Michael Gottesman87db35752013-01-18 23:02:45 +0000581/// \brief Return true if this value refers to a distinct and identifiable
582/// object.
583///
584/// This is similar to AliasAnalysis's isIdentifiedObject, except that it uses
585/// special knowledge of ObjC conventions.
John McCalld935e9c2011-06-15 23:37:01 +0000586static bool IsObjCIdentifiedObject(const Value *V) {
587 // Assume that call results and arguments have their own "provenance".
588 // Constants (including GlobalVariables) and Allocas are never
589 // reference-counted.
590 if (isa<CallInst>(V) || isa<InvokeInst>(V) ||
591 isa<Argument>(V) || isa<Constant>(V) ||
592 isa<AllocaInst>(V))
593 return true;
594
595 if (const LoadInst *LI = dyn_cast<LoadInst>(V)) {
596 const Value *Pointer =
597 StripPointerCastsAndObjCCalls(LI->getPointerOperand());
598 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Pointer)) {
Dan Gohman56e1cef2011-08-22 17:29:11 +0000599 // A constant pointer can't be pointing to an object on the heap. It may
600 // be reference-counted, but it won't be deleted.
601 if (GV->isConstant())
602 return true;
John McCalld935e9c2011-06-15 23:37:01 +0000603 StringRef Name = GV->getName();
604 // These special variables are known to hold values which are not
605 // reference-counted pointers.
606 if (Name.startswith("\01L_OBJC_SELECTOR_REFERENCES_") ||
607 Name.startswith("\01L_OBJC_CLASSLIST_REFERENCES_") ||
608 Name.startswith("\01L_OBJC_CLASSLIST_SUP_REFS_$_") ||
609 Name.startswith("\01L_OBJC_METH_VAR_NAME_") ||
610 Name.startswith("\01l_objc_msgSend_fixup_"))
611 return true;
612 }
613 }
614
615 return false;
616}
617
Michael Gottesman97e3df02013-01-14 00:35:14 +0000618/// \brief This is similar to StripPointerCastsAndObjCCalls but it stops as soon
619/// as it finds a value with multiple uses.
John McCalld935e9c2011-06-15 23:37:01 +0000620static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
621 if (Arg->hasOneUse()) {
622 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
623 return FindSingleUseIdentifiedObject(BC->getOperand(0));
624 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
625 if (GEP->hasAllZeroIndices())
626 return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
627 if (IsForwarding(GetBasicInstructionClass(Arg)))
628 return FindSingleUseIdentifiedObject(
629 cast<CallInst>(Arg)->getArgOperand(0));
630 if (!IsObjCIdentifiedObject(Arg))
631 return 0;
632 return Arg;
633 }
634
Dan Gohman41375a32012-05-08 23:39:44 +0000635 // If we found an identifiable object but it has multiple uses, but they are
636 // trivial uses, we can still consider this to be a single-use value.
John McCalld935e9c2011-06-15 23:37:01 +0000637 if (IsObjCIdentifiedObject(Arg)) {
638 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
639 UI != UE; ++UI) {
640 const User *U = *UI;
641 if (!U->use_empty() || StripPointerCastsAndObjCCalls(U) != Arg)
642 return 0;
643 }
644
645 return Arg;
646 }
647
648 return 0;
649}
650
Michael Gottesman97e3df02013-01-14 00:35:14 +0000651/// \brief Test if the given module looks interesting to run ARC optimization
652/// on.
Dan Gohmanceaac7c2011-06-20 23:20:43 +0000653static bool ModuleHasARC(const Module &M) {
654 return
655 M.getNamedValue("objc_retain") ||
656 M.getNamedValue("objc_release") ||
657 M.getNamedValue("objc_autorelease") ||
658 M.getNamedValue("objc_retainAutoreleasedReturnValue") ||
659 M.getNamedValue("objc_retainBlock") ||
660 M.getNamedValue("objc_autoreleaseReturnValue") ||
661 M.getNamedValue("objc_autoreleasePoolPush") ||
662 M.getNamedValue("objc_loadWeakRetained") ||
663 M.getNamedValue("objc_loadWeak") ||
664 M.getNamedValue("objc_destroyWeak") ||
665 M.getNamedValue("objc_storeWeak") ||
666 M.getNamedValue("objc_initWeak") ||
667 M.getNamedValue("objc_moveWeak") ||
668 M.getNamedValue("objc_copyWeak") ||
669 M.getNamedValue("objc_retainedObject") ||
670 M.getNamedValue("objc_unretainedObject") ||
671 M.getNamedValue("objc_unretainedPointer");
672}
673
Michael Gottesman4385edf2013-01-14 01:47:53 +0000674/// \brief Test whether the given pointer, which is an Objective C block
675/// pointer, does not "escape".
Michael Gottesman97e3df02013-01-14 00:35:14 +0000676///
677/// This differs from regular escape analysis in that a use as an
678/// argument to a call is not considered an escape.
679///
Dan Gohman728db492012-01-13 00:39:07 +0000680static bool DoesObjCBlockEscape(const Value *BlockPtr) {
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000681
682 DEBUG(dbgs() << "DoesObjCBlockEscape: Target: " << *BlockPtr << "\n");
683
Dan Gohman728db492012-01-13 00:39:07 +0000684 // Walk the def-use chains.
685 SmallVector<const Value *, 4> Worklist;
686 Worklist.push_back(BlockPtr);
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000687
688 // Ensure we do not visit any value twice.
689 SmallPtrSet<const Value *, 4> VisitedSet;
690
Dan Gohman728db492012-01-13 00:39:07 +0000691 do {
692 const Value *V = Worklist.pop_back_val();
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000693
694 DEBUG(dbgs() << "DoesObjCBlockEscape: Visiting: " << *V << "\n");
695
Dan Gohman728db492012-01-13 00:39:07 +0000696 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
697 UI != UE; ++UI) {
698 const User *UUser = *UI;
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000699
700 DEBUG(dbgs() << "DoesObjCBlockEscape: User: " << *UUser << "\n");
701
Dan Gohman728db492012-01-13 00:39:07 +0000702 // Special - Use by a call (callee or argument) is not considered
703 // to be an escape.
Dan Gohmane1e352a2012-04-13 18:28:58 +0000704 switch (GetBasicInstructionClass(UUser)) {
705 case IC_StoreWeak:
706 case IC_InitWeak:
707 case IC_StoreStrong:
708 case IC_Autorelease:
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000709 case IC_AutoreleaseRV: {
710 DEBUG(dbgs() << "DoesObjCBlockEscape: User copies pointer arguments. "
711 "Block Escapes!\n");
Dan Gohmane1e352a2012-04-13 18:28:58 +0000712 // These special functions make copies of their pointer arguments.
713 return true;
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000714 }
Dan Gohmane1e352a2012-04-13 18:28:58 +0000715 case IC_User:
716 case IC_None:
717 // Use by an instruction which copies the value is an escape if the
718 // result is an escape.
719 if (isa<BitCastInst>(UUser) || isa<GetElementPtrInst>(UUser) ||
720 isa<PHINode>(UUser) || isa<SelectInst>(UUser)) {
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000721
Michael Gottesmane9145d32013-01-14 19:18:39 +0000722 if (!VisitedSet.insert(UUser)) {
Michael Gottesman4385edf2013-01-14 01:47:53 +0000723 DEBUG(dbgs() << "DoesObjCBlockEscape: User copies value. Escapes "
724 "if result escapes. Adding to list.\n");
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000725 Worklist.push_back(UUser);
726 } else {
727 DEBUG(dbgs() << "DoesObjCBlockEscape: Already visited node.\n");
728 }
Dan Gohmane1e352a2012-04-13 18:28:58 +0000729 continue;
730 }
731 // Use by a load is not an escape.
732 if (isa<LoadInst>(UUser))
733 continue;
734 // Use by a store is not an escape if the use is the address.
735 if (const StoreInst *SI = dyn_cast<StoreInst>(UUser))
736 if (V != SI->getValueOperand())
737 continue;
738 break;
739 default:
740 // Regular calls and other stuff are not considered escapes.
Dan Gohman728db492012-01-13 00:39:07 +0000741 continue;
742 }
Dan Gohmaneb6e0152012-02-13 22:57:02 +0000743 // Otherwise, conservatively assume an escape.
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000744 DEBUG(dbgs() << "DoesObjCBlockEscape: Assuming block escapes.\n");
Dan Gohman728db492012-01-13 00:39:07 +0000745 return true;
746 }
747 } while (!Worklist.empty());
748
749 // No escapes found.
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000750 DEBUG(dbgs() << "DoesObjCBlockEscape: Block does not escape.\n");
Dan Gohman728db492012-01-13 00:39:07 +0000751 return false;
752}
753
Michael Gottesman97e3df02013-01-14 00:35:14 +0000754/// @}
755///
Michael Gottesman4385edf2013-01-14 01:47:53 +0000756/// \defgroup ARCAA Extends alias analysis using ObjC specific knowledge.
Michael Gottesman97e3df02013-01-14 00:35:14 +0000757/// @{
John McCalld935e9c2011-06-15 23:37:01 +0000758
John McCalld935e9c2011-06-15 23:37:01 +0000759#include "llvm/Analysis/AliasAnalysis.h"
760#include "llvm/Analysis/Passes.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +0000761#include "llvm/Pass.h"
John McCalld935e9c2011-06-15 23:37:01 +0000762
763namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000764 /// \brief This is a simple alias analysis implementation that uses knowledge
765 /// of ARC constructs to answer queries.
John McCalld935e9c2011-06-15 23:37:01 +0000766 ///
767 /// TODO: This class could be generalized to know about other ObjC-specific
768 /// tricks. Such as knowing that ivars in the non-fragile ABI are non-aliasing
769 /// even though their offsets are dynamic.
770 class ObjCARCAliasAnalysis : public ImmutablePass,
771 public AliasAnalysis {
772 public:
773 static char ID; // Class identification, replacement for typeinfo
774 ObjCARCAliasAnalysis() : ImmutablePass(ID) {
775 initializeObjCARCAliasAnalysisPass(*PassRegistry::getPassRegistry());
776 }
777
778 private:
779 virtual void initializePass() {
780 InitializeAliasAnalysis(this);
781 }
782
Michael Gottesman97e3df02013-01-14 00:35:14 +0000783 /// This method is used when a pass implements an analysis interface through
784 /// multiple inheritance. If needed, it should override this to adjust the
785 /// this pointer as needed for the specified pass info.
John McCalld935e9c2011-06-15 23:37:01 +0000786 virtual void *getAdjustedAnalysisPointer(const void *PI) {
787 if (PI == &AliasAnalysis::ID)
Dan Gohmandae33492012-04-27 18:56:31 +0000788 return static_cast<AliasAnalysis *>(this);
John McCalld935e9c2011-06-15 23:37:01 +0000789 return this;
790 }
791
792 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
793 virtual AliasResult alias(const Location &LocA, const Location &LocB);
794 virtual bool pointsToConstantMemory(const Location &Loc, bool OrLocal);
795 virtual ModRefBehavior getModRefBehavior(ImmutableCallSite CS);
796 virtual ModRefBehavior getModRefBehavior(const Function *F);
797 virtual ModRefResult getModRefInfo(ImmutableCallSite CS,
798 const Location &Loc);
799 virtual ModRefResult getModRefInfo(ImmutableCallSite CS1,
800 ImmutableCallSite CS2);
801 };
802} // End of anonymous namespace
803
804// Register this pass...
805char ObjCARCAliasAnalysis::ID = 0;
806INITIALIZE_AG_PASS(ObjCARCAliasAnalysis, AliasAnalysis, "objc-arc-aa",
807 "ObjC-ARC-Based Alias Analysis", false, true, false)
808
809ImmutablePass *llvm::createObjCARCAliasAnalysisPass() {
810 return new ObjCARCAliasAnalysis();
811}
812
813void
814ObjCARCAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
815 AU.setPreservesAll();
816 AliasAnalysis::getAnalysisUsage(AU);
817}
818
819AliasAnalysis::AliasResult
820ObjCARCAliasAnalysis::alias(const Location &LocA, const Location &LocB) {
821 if (!EnableARCOpts)
822 return AliasAnalysis::alias(LocA, LocB);
823
824 // First, strip off no-ops, including ObjC-specific no-ops, and try making a
825 // precise alias query.
826 const Value *SA = StripPointerCastsAndObjCCalls(LocA.Ptr);
827 const Value *SB = StripPointerCastsAndObjCCalls(LocB.Ptr);
828 AliasResult Result =
829 AliasAnalysis::alias(Location(SA, LocA.Size, LocA.TBAATag),
830 Location(SB, LocB.Size, LocB.TBAATag));
831 if (Result != MayAlias)
832 return Result;
833
834 // If that failed, climb to the underlying object, including climbing through
835 // ObjC-specific no-ops, and try making an imprecise alias query.
836 const Value *UA = GetUnderlyingObjCPtr(SA);
837 const Value *UB = GetUnderlyingObjCPtr(SB);
838 if (UA != SA || UB != SB) {
839 Result = AliasAnalysis::alias(Location(UA), Location(UB));
840 // We can't use MustAlias or PartialAlias results here because
841 // GetUnderlyingObjCPtr may return an offsetted pointer value.
842 if (Result == NoAlias)
843 return NoAlias;
844 }
845
846 // If that failed, fail. We don't need to chain here, since that's covered
847 // by the earlier precise query.
848 return MayAlias;
849}
850
851bool
852ObjCARCAliasAnalysis::pointsToConstantMemory(const Location &Loc,
853 bool OrLocal) {
854 if (!EnableARCOpts)
855 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
856
857 // First, strip off no-ops, including ObjC-specific no-ops, and try making
858 // a precise alias query.
859 const Value *S = StripPointerCastsAndObjCCalls(Loc.Ptr);
860 if (AliasAnalysis::pointsToConstantMemory(Location(S, Loc.Size, Loc.TBAATag),
861 OrLocal))
862 return true;
863
864 // If that failed, climb to the underlying object, including climbing through
865 // ObjC-specific no-ops, and try making an imprecise alias query.
866 const Value *U = GetUnderlyingObjCPtr(S);
867 if (U != S)
868 return AliasAnalysis::pointsToConstantMemory(Location(U), OrLocal);
869
870 // If that failed, fail. We don't need to chain here, since that's covered
871 // by the earlier precise query.
872 return false;
873}
874
875AliasAnalysis::ModRefBehavior
876ObjCARCAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
877 // We have nothing to do. Just chain to the next AliasAnalysis.
878 return AliasAnalysis::getModRefBehavior(CS);
879}
880
881AliasAnalysis::ModRefBehavior
882ObjCARCAliasAnalysis::getModRefBehavior(const Function *F) {
883 if (!EnableARCOpts)
884 return AliasAnalysis::getModRefBehavior(F);
885
886 switch (GetFunctionClass(F)) {
887 case IC_NoopCast:
888 return DoesNotAccessMemory;
889 default:
890 break;
891 }
892
893 return AliasAnalysis::getModRefBehavior(F);
894}
895
896AliasAnalysis::ModRefResult
897ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS, const Location &Loc) {
898 if (!EnableARCOpts)
899 return AliasAnalysis::getModRefInfo(CS, Loc);
900
901 switch (GetBasicInstructionClass(CS.getInstruction())) {
902 case IC_Retain:
903 case IC_RetainRV:
John McCalld935e9c2011-06-15 23:37:01 +0000904 case IC_Autorelease:
905 case IC_AutoreleaseRV:
906 case IC_NoopCast:
907 case IC_AutoreleasepoolPush:
908 case IC_FusedRetainAutorelease:
909 case IC_FusedRetainAutoreleaseRV:
910 // These functions don't access any memory visible to the compiler.
Benjamin Kramerbde91762012-06-02 10:20:22 +0000911 // Note that this doesn't include objc_retainBlock, because it updates
Dan Gohmand4b5e3a2011-09-14 18:13:00 +0000912 // pointers when it copies block data.
John McCalld935e9c2011-06-15 23:37:01 +0000913 return NoModRef;
914 default:
915 break;
916 }
917
918 return AliasAnalysis::getModRefInfo(CS, Loc);
919}
920
921AliasAnalysis::ModRefResult
922ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
923 ImmutableCallSite CS2) {
924 // TODO: Theoretically we could check for dependencies between objc_* calls
925 // and OnlyAccessesArgumentPointees calls or other well-behaved calls.
926 return AliasAnalysis::getModRefInfo(CS1, CS2);
927}
928
Michael Gottesman97e3df02013-01-14 00:35:14 +0000929/// @}
930///
931/// \defgroup ARCExpansion Early ARC Optimizations.
932/// @{
John McCalld935e9c2011-06-15 23:37:01 +0000933
934#include "llvm/Support/InstIterator.h"
935#include "llvm/Transforms/Scalar.h"
936
937namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000938 /// \brief Early ARC transformations.
John McCalld935e9c2011-06-15 23:37:01 +0000939 class ObjCARCExpand : public FunctionPass {
940 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Dan Gohmanceaac7c2011-06-20 23:20:43 +0000941 virtual bool doInitialization(Module &M);
John McCalld935e9c2011-06-15 23:37:01 +0000942 virtual bool runOnFunction(Function &F);
943
Michael Gottesman97e3df02013-01-14 00:35:14 +0000944 /// A flag indicating whether this optimization pass should run.
Dan Gohmanceaac7c2011-06-20 23:20:43 +0000945 bool Run;
946
John McCalld935e9c2011-06-15 23:37:01 +0000947 public:
948 static char ID;
949 ObjCARCExpand() : FunctionPass(ID) {
950 initializeObjCARCExpandPass(*PassRegistry::getPassRegistry());
951 }
952 };
953}
954
955char ObjCARCExpand::ID = 0;
956INITIALIZE_PASS(ObjCARCExpand,
957 "objc-arc-expand", "ObjC ARC expansion", false, false)
958
959Pass *llvm::createObjCARCExpandPass() {
960 return new ObjCARCExpand();
961}
962
963void ObjCARCExpand::getAnalysisUsage(AnalysisUsage &AU) const {
964 AU.setPreservesCFG();
965}
966
Dan Gohmanceaac7c2011-06-20 23:20:43 +0000967bool ObjCARCExpand::doInitialization(Module &M) {
968 Run = ModuleHasARC(M);
969 return false;
970}
971
John McCalld935e9c2011-06-15 23:37:01 +0000972bool ObjCARCExpand::runOnFunction(Function &F) {
973 if (!EnableARCOpts)
974 return false;
975
Dan Gohmanceaac7c2011-06-20 23:20:43 +0000976 // If nothing in the Module uses ARC, don't do anything.
977 if (!Run)
978 return false;
979
John McCalld935e9c2011-06-15 23:37:01 +0000980 bool Changed = false;
981
Michael Gottesmanaf2113f2013-01-13 07:00:51 +0000982 DEBUG(dbgs() << "ObjCARCExpand: Visiting Function: " << F.getName() << "\n");
983
John McCalld935e9c2011-06-15 23:37:01 +0000984 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
985 Instruction *Inst = &*I;
Michael Gottesman10426b52013-01-07 21:26:07 +0000986
Michael Gottesman3f146e22013-01-01 16:05:48 +0000987 DEBUG(dbgs() << "ObjCARCExpand: Visiting: " << *Inst << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +0000988
John McCalld935e9c2011-06-15 23:37:01 +0000989 switch (GetBasicInstructionClass(Inst)) {
990 case IC_Retain:
991 case IC_RetainRV:
992 case IC_Autorelease:
993 case IC_AutoreleaseRV:
994 case IC_FusedRetainAutorelease:
Michael Gottesmanc8a11df2013-01-01 16:05:54 +0000995 case IC_FusedRetainAutoreleaseRV: {
John McCalld935e9c2011-06-15 23:37:01 +0000996 // These calls return their argument verbatim, as a low-level
997 // optimization. However, this makes high-level optimizations
998 // harder. Undo any uses of this optimization that the front-end
Dan Gohman670f9372012-04-13 18:57:48 +0000999 // emitted here. We'll redo them in the contract pass.
John McCalld935e9c2011-06-15 23:37:01 +00001000 Changed = true;
Michael Gottesmanc8a11df2013-01-01 16:05:54 +00001001 Value *Value = cast<CallInst>(Inst)->getArgOperand(0);
1002 DEBUG(dbgs() << "ObjCARCExpand: Old = " << *Inst << "\n"
1003 " New = " << *Value << "\n");
1004 Inst->replaceAllUsesWith(Value);
John McCalld935e9c2011-06-15 23:37:01 +00001005 break;
Michael Gottesmanc8a11df2013-01-01 16:05:54 +00001006 }
John McCalld935e9c2011-06-15 23:37:01 +00001007 default:
1008 break;
1009 }
1010 }
Michael Gottesman10426b52013-01-07 21:26:07 +00001011
Michael Gottesman50ae5b22013-01-03 08:09:27 +00001012 DEBUG(dbgs() << "ObjCARCExpand: Finished List.\n\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001013
John McCalld935e9c2011-06-15 23:37:01 +00001014 return Changed;
1015}
1016
Michael Gottesman97e3df02013-01-14 00:35:14 +00001017/// @}
1018///
1019/// \defgroup ARCAPElim ARC Autorelease Pool Elimination.
1020/// @{
Dan Gohmane7a243f2012-01-17 20:52:24 +00001021
Dan Gohman41375a32012-05-08 23:39:44 +00001022#include "llvm/ADT/STLExtras.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +00001023#include "llvm/IR/Constants.h"
Dan Gohman82041c22012-01-18 21:19:38 +00001024
Dan Gohmane7a243f2012-01-17 20:52:24 +00001025namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001026 /// \brief Autorelease pool elimination.
Dan Gohmane7a243f2012-01-17 20:52:24 +00001027 class ObjCARCAPElim : public ModulePass {
1028 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1029 virtual bool runOnModule(Module &M);
1030
Dan Gohmandae33492012-04-27 18:56:31 +00001031 static bool MayAutorelease(ImmutableCallSite CS, unsigned Depth = 0);
1032 static bool OptimizeBB(BasicBlock *BB);
Dan Gohmane7a243f2012-01-17 20:52:24 +00001033
1034 public:
1035 static char ID;
1036 ObjCARCAPElim() : ModulePass(ID) {
1037 initializeObjCARCAPElimPass(*PassRegistry::getPassRegistry());
1038 }
1039 };
1040}
1041
1042char ObjCARCAPElim::ID = 0;
1043INITIALIZE_PASS(ObjCARCAPElim,
1044 "objc-arc-apelim",
1045 "ObjC ARC autorelease pool elimination",
1046 false, false)
1047
1048Pass *llvm::createObjCARCAPElimPass() {
1049 return new ObjCARCAPElim();
1050}
1051
1052void ObjCARCAPElim::getAnalysisUsage(AnalysisUsage &AU) const {
1053 AU.setPreservesCFG();
1054}
1055
Michael Gottesman97e3df02013-01-14 00:35:14 +00001056/// Interprocedurally determine if calls made by the given call site can
1057/// possibly produce autoreleases.
Dan Gohmandae33492012-04-27 18:56:31 +00001058bool ObjCARCAPElim::MayAutorelease(ImmutableCallSite CS, unsigned Depth) {
1059 if (const Function *Callee = CS.getCalledFunction()) {
Dan Gohmane7a243f2012-01-17 20:52:24 +00001060 if (Callee->isDeclaration() || Callee->mayBeOverridden())
1061 return true;
Dan Gohmandae33492012-04-27 18:56:31 +00001062 for (Function::const_iterator I = Callee->begin(), E = Callee->end();
Dan Gohmane7a243f2012-01-17 20:52:24 +00001063 I != E; ++I) {
Dan Gohmandae33492012-04-27 18:56:31 +00001064 const BasicBlock *BB = I;
1065 for (BasicBlock::const_iterator J = BB->begin(), F = BB->end();
1066 J != F; ++J)
1067 if (ImmutableCallSite JCS = ImmutableCallSite(J))
Dan Gohman8f12fae2012-01-18 21:24:45 +00001068 // This recursion depth limit is arbitrary. It's just great
1069 // enough to cover known interesting testcases.
1070 if (Depth < 3 &&
1071 !JCS.onlyReadsMemory() &&
1072 MayAutorelease(JCS, Depth + 1))
Dan Gohmane7a243f2012-01-17 20:52:24 +00001073 return true;
1074 }
1075 return false;
1076 }
1077
1078 return true;
1079}
1080
1081bool ObjCARCAPElim::OptimizeBB(BasicBlock *BB) {
1082 bool Changed = false;
1083
1084 Instruction *Push = 0;
1085 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1086 Instruction *Inst = I++;
1087 switch (GetBasicInstructionClass(Inst)) {
1088 case IC_AutoreleasepoolPush:
1089 Push = Inst;
1090 break;
1091 case IC_AutoreleasepoolPop:
1092 // If this pop matches a push and nothing in between can autorelease,
1093 // zap the pair.
1094 if (Push && cast<CallInst>(Inst)->getArgOperand(0) == Push) {
1095 Changed = true;
Michael Gottesman4385edf2013-01-14 01:47:53 +00001096 DEBUG(dbgs() << "ObjCARCAPElim::OptimizeBB: Zapping push pop "
1097 "autorelease pair:\n"
1098 " Pop: " << *Inst << "\n"
Michael Gottesmanef682c52013-01-03 08:09:17 +00001099 << " Push: " << *Push << "\n");
Dan Gohmane7a243f2012-01-17 20:52:24 +00001100 Inst->eraseFromParent();
1101 Push->eraseFromParent();
1102 }
1103 Push = 0;
1104 break;
1105 case IC_CallOrUser:
Dan Gohmandae33492012-04-27 18:56:31 +00001106 if (MayAutorelease(ImmutableCallSite(Inst)))
Dan Gohmane7a243f2012-01-17 20:52:24 +00001107 Push = 0;
1108 break;
1109 default:
1110 break;
1111 }
1112 }
1113
1114 return Changed;
1115}
1116
1117bool ObjCARCAPElim::runOnModule(Module &M) {
1118 if (!EnableARCOpts)
1119 return false;
1120
1121 // If nothing in the Module uses ARC, don't do anything.
1122 if (!ModuleHasARC(M))
1123 return false;
1124
Dan Gohman82041c22012-01-18 21:19:38 +00001125 // Find the llvm.global_ctors variable, as the first step in
Dan Gohman670f9372012-04-13 18:57:48 +00001126 // identifying the global constructors. In theory, unnecessary autorelease
1127 // pools could occur anywhere, but in practice it's pretty rare. Global
1128 // ctors are a place where autorelease pools get inserted automatically,
1129 // so it's pretty common for them to be unnecessary, and it's pretty
1130 // profitable to eliminate them.
Dan Gohman82041c22012-01-18 21:19:38 +00001131 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1132 if (!GV)
1133 return false;
1134
1135 assert(GV->hasDefinitiveInitializer() &&
1136 "llvm.global_ctors is uncooperative!");
1137
Dan Gohmane7a243f2012-01-17 20:52:24 +00001138 bool Changed = false;
1139
Dan Gohman82041c22012-01-18 21:19:38 +00001140 // Dig the constructor functions out of GV's initializer.
1141 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
1142 for (User::op_iterator OI = Init->op_begin(), OE = Init->op_end();
1143 OI != OE; ++OI) {
1144 Value *Op = *OI;
1145 // llvm.global_ctors is an array of pairs where the second members
1146 // are constructor functions.
Dan Gohman22fbe8d2012-04-18 22:24:33 +00001147 Function *F = dyn_cast<Function>(cast<ConstantStruct>(Op)->getOperand(1));
1148 // If the user used a constructor function with the wrong signature and
1149 // it got bitcasted or whatever, look the other way.
1150 if (!F)
1151 continue;
Dan Gohmane7a243f2012-01-17 20:52:24 +00001152 // Only look at function definitions.
1153 if (F->isDeclaration())
1154 continue;
Dan Gohmane7a243f2012-01-17 20:52:24 +00001155 // Only look at functions with one basic block.
1156 if (llvm::next(F->begin()) != F->end())
1157 continue;
1158 // Ok, a single-block constructor function definition. Try to optimize it.
1159 Changed |= OptimizeBB(F->begin());
1160 }
1161
1162 return Changed;
1163}
1164
Michael Gottesman97e3df02013-01-14 00:35:14 +00001165/// @}
1166///
1167/// \defgroup ARCOpt ARC Optimization.
1168/// @{
John McCalld935e9c2011-06-15 23:37:01 +00001169
1170// TODO: On code like this:
1171//
1172// objc_retain(%x)
1173// stuff_that_cannot_release()
1174// objc_autorelease(%x)
1175// stuff_that_cannot_release()
1176// objc_retain(%x)
1177// stuff_that_cannot_release()
1178// objc_autorelease(%x)
1179//
1180// The second retain and autorelease can be deleted.
1181
1182// TODO: It should be possible to delete
1183// objc_autoreleasePoolPush and objc_autoreleasePoolPop
1184// pairs if nothing is actually autoreleased between them. Also, autorelease
1185// calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
1186// after inlining) can be turned into plain release calls.
1187
1188// TODO: Critical-edge splitting. If the optimial insertion point is
1189// a critical edge, the current algorithm has to fail, because it doesn't
1190// know how to split edges. It should be possible to make the optimizer
1191// think in terms of edges, rather than blocks, and then split critical
1192// edges on demand.
1193
1194// TODO: OptimizeSequences could generalized to be Interprocedural.
1195
1196// TODO: Recognize that a bunch of other objc runtime calls have
1197// non-escaping arguments and non-releasing arguments, and may be
1198// non-autoreleasing.
1199
1200// TODO: Sink autorelease calls as far as possible. Unfortunately we
1201// usually can't sink them past other calls, which would be the main
1202// case where it would be useful.
1203
Dan Gohmanb3894012011-08-19 00:26:36 +00001204// TODO: The pointer returned from objc_loadWeakRetained is retained.
1205
1206// TODO: Delete release+retain pairs (rare).
Dan Gohmanceaac7c2011-06-20 23:20:43 +00001207
Chandler Carruthed0881b2012-12-03 16:50:05 +00001208#include "llvm/ADT/SmallPtrSet.h"
1209#include "llvm/ADT/Statistic.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +00001210#include "llvm/IR/LLVMContext.h"
John McCalld935e9c2011-06-15 23:37:01 +00001211#include "llvm/Support/CFG.h"
John McCalld935e9c2011-06-15 23:37:01 +00001212
1213STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
1214STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
1215STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
1216STATISTIC(NumRets, "Number of return value forwarding "
1217 "retain+autoreleaes eliminated");
1218STATISTIC(NumRRs, "Number of retain+release paths eliminated");
1219STATISTIC(NumPeeps, "Number of calls peephole-optimized");
1220
1221namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001222 /// \brief This is similar to BasicAliasAnalysis, and it uses many of the same
1223 /// techniques, except it uses special ObjC-specific reasoning about pointer
1224 /// relationships.
John McCalld935e9c2011-06-15 23:37:01 +00001225 class ProvenanceAnalysis {
1226 AliasAnalysis *AA;
1227
1228 typedef std::pair<const Value *, const Value *> ValuePairTy;
1229 typedef DenseMap<ValuePairTy, bool> CachedResultsTy;
1230 CachedResultsTy CachedResults;
1231
1232 bool relatedCheck(const Value *A, const Value *B);
1233 bool relatedSelect(const SelectInst *A, const Value *B);
1234 bool relatedPHI(const PHINode *A, const Value *B);
1235
Craig Topperb1d83e82012-09-18 02:01:41 +00001236 void operator=(const ProvenanceAnalysis &) LLVM_DELETED_FUNCTION;
1237 ProvenanceAnalysis(const ProvenanceAnalysis &) LLVM_DELETED_FUNCTION;
John McCalld935e9c2011-06-15 23:37:01 +00001238
1239 public:
1240 ProvenanceAnalysis() {}
1241
1242 void setAA(AliasAnalysis *aa) { AA = aa; }
1243
1244 AliasAnalysis *getAA() const { return AA; }
1245
1246 bool related(const Value *A, const Value *B);
1247
1248 void clear() {
1249 CachedResults.clear();
1250 }
1251 };
1252}
1253
1254bool ProvenanceAnalysis::relatedSelect(const SelectInst *A, const Value *B) {
1255 // If the values are Selects with the same condition, we can do a more precise
1256 // check: just check for relations between the values on corresponding arms.
1257 if (const SelectInst *SB = dyn_cast<SelectInst>(B))
Dan Gohmandae33492012-04-27 18:56:31 +00001258 if (A->getCondition() == SB->getCondition())
1259 return related(A->getTrueValue(), SB->getTrueValue()) ||
1260 related(A->getFalseValue(), SB->getFalseValue());
John McCalld935e9c2011-06-15 23:37:01 +00001261
1262 // Check both arms of the Select node individually.
Dan Gohmandae33492012-04-27 18:56:31 +00001263 return related(A->getTrueValue(), B) ||
1264 related(A->getFalseValue(), B);
John McCalld935e9c2011-06-15 23:37:01 +00001265}
1266
1267bool ProvenanceAnalysis::relatedPHI(const PHINode *A, const Value *B) {
1268 // If the values are PHIs in the same block, we can do a more precise as well
1269 // as efficient check: just check for relations between the values on
1270 // corresponding edges.
1271 if (const PHINode *PNB = dyn_cast<PHINode>(B))
1272 if (PNB->getParent() == A->getParent()) {
1273 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i)
1274 if (related(A->getIncomingValue(i),
1275 PNB->getIncomingValueForBlock(A->getIncomingBlock(i))))
1276 return true;
1277 return false;
1278 }
1279
1280 // Check each unique source of the PHI node against B.
1281 SmallPtrSet<const Value *, 4> UniqueSrc;
1282 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i) {
1283 const Value *PV1 = A->getIncomingValue(i);
1284 if (UniqueSrc.insert(PV1) && related(PV1, B))
1285 return true;
1286 }
1287
1288 // All of the arms checked out.
1289 return false;
1290}
1291
Michael Gottesman97e3df02013-01-14 00:35:14 +00001292/// Test if the value of P, or any value covered by its provenance, is ever
1293/// stored within the function (not counting callees).
John McCalld935e9c2011-06-15 23:37:01 +00001294static bool isStoredObjCPointer(const Value *P) {
1295 SmallPtrSet<const Value *, 8> Visited;
1296 SmallVector<const Value *, 8> Worklist;
1297 Worklist.push_back(P);
1298 Visited.insert(P);
1299 do {
1300 P = Worklist.pop_back_val();
1301 for (Value::const_use_iterator UI = P->use_begin(), UE = P->use_end();
1302 UI != UE; ++UI) {
1303 const User *Ur = *UI;
1304 if (isa<StoreInst>(Ur)) {
1305 if (UI.getOperandNo() == 0)
1306 // The pointer is stored.
1307 return true;
1308 // The pointed is stored through.
1309 continue;
1310 }
1311 if (isa<CallInst>(Ur))
1312 // The pointer is passed as an argument, ignore this.
1313 continue;
1314 if (isa<PtrToIntInst>(P))
1315 // Assume the worst.
1316 return true;
1317 if (Visited.insert(Ur))
1318 Worklist.push_back(Ur);
1319 }
1320 } while (!Worklist.empty());
1321
1322 // Everything checked out.
1323 return false;
1324}
1325
1326bool ProvenanceAnalysis::relatedCheck(const Value *A, const Value *B) {
1327 // Skip past provenance pass-throughs.
1328 A = GetUnderlyingObjCPtr(A);
1329 B = GetUnderlyingObjCPtr(B);
1330
1331 // Quick check.
1332 if (A == B)
1333 return true;
1334
1335 // Ask regular AliasAnalysis, for a first approximation.
1336 switch (AA->alias(A, B)) {
1337 case AliasAnalysis::NoAlias:
1338 return false;
1339 case AliasAnalysis::MustAlias:
1340 case AliasAnalysis::PartialAlias:
1341 return true;
1342 case AliasAnalysis::MayAlias:
1343 break;
1344 }
1345
1346 bool AIsIdentified = IsObjCIdentifiedObject(A);
1347 bool BIsIdentified = IsObjCIdentifiedObject(B);
1348
1349 // An ObjC-Identified object can't alias a load if it is never locally stored.
1350 if (AIsIdentified) {
Dan Gohmandf476e52012-09-04 23:16:20 +00001351 // Check for an obvious escape.
1352 if (isa<LoadInst>(B))
1353 return isStoredObjCPointer(A);
John McCalld935e9c2011-06-15 23:37:01 +00001354 if (BIsIdentified) {
Dan Gohmandf476e52012-09-04 23:16:20 +00001355 // Check for an obvious escape.
1356 if (isa<LoadInst>(A))
1357 return isStoredObjCPointer(B);
1358 // Both pointers are identified and escapes aren't an evident problem.
1359 return false;
John McCalld935e9c2011-06-15 23:37:01 +00001360 }
Dan Gohmandf476e52012-09-04 23:16:20 +00001361 } else if (BIsIdentified) {
1362 // Check for an obvious escape.
1363 if (isa<LoadInst>(A))
John McCalld935e9c2011-06-15 23:37:01 +00001364 return isStoredObjCPointer(B);
1365 }
1366
1367 // Special handling for PHI and Select.
1368 if (const PHINode *PN = dyn_cast<PHINode>(A))
1369 return relatedPHI(PN, B);
1370 if (const PHINode *PN = dyn_cast<PHINode>(B))
1371 return relatedPHI(PN, A);
1372 if (const SelectInst *S = dyn_cast<SelectInst>(A))
1373 return relatedSelect(S, B);
1374 if (const SelectInst *S = dyn_cast<SelectInst>(B))
1375 return relatedSelect(S, A);
1376
1377 // Conservative.
1378 return true;
1379}
1380
1381bool ProvenanceAnalysis::related(const Value *A, const Value *B) {
1382 // Begin by inserting a conservative value into the map. If the insertion
1383 // fails, we have the answer already. If it succeeds, leave it there until we
1384 // compute the real answer to guard against recursive queries.
1385 if (A > B) std::swap(A, B);
1386 std::pair<CachedResultsTy::iterator, bool> Pair =
1387 CachedResults.insert(std::make_pair(ValuePairTy(A, B), true));
1388 if (!Pair.second)
1389 return Pair.first->second;
1390
1391 bool Result = relatedCheck(A, B);
1392 CachedResults[ValuePairTy(A, B)] = Result;
1393 return Result;
1394}
1395
1396namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001397 /// \enum Sequence
1398 ///
1399 /// \brief A sequence of states that a pointer may go through in which an
1400 /// objc_retain and objc_release are actually needed.
John McCalld935e9c2011-06-15 23:37:01 +00001401 enum Sequence {
1402 S_None,
1403 S_Retain, ///< objc_retain(x)
1404 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement
1405 S_Use, ///< any use of x
1406 S_Stop, ///< like S_Release, but code motion is stopped
1407 S_Release, ///< objc_release(x)
1408 S_MovableRelease ///< objc_release(x), !clang.imprecise_release
1409 };
1410}
1411
1412static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
1413 // The easy cases.
1414 if (A == B)
1415 return A;
1416 if (A == S_None || B == S_None)
1417 return S_None;
1418
John McCalld935e9c2011-06-15 23:37:01 +00001419 if (A > B) std::swap(A, B);
1420 if (TopDown) {
1421 // Choose the side which is further along in the sequence.
Dan Gohman12130272011-08-12 00:26:31 +00001422 if ((A == S_Retain || A == S_CanRelease) &&
1423 (B == S_CanRelease || B == S_Use))
John McCalld935e9c2011-06-15 23:37:01 +00001424 return B;
1425 } else {
1426 // Choose the side which is further along in the sequence.
1427 if ((A == S_Use || A == S_CanRelease) &&
Dan Gohman12130272011-08-12 00:26:31 +00001428 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
John McCalld935e9c2011-06-15 23:37:01 +00001429 return A;
1430 // If both sides are releases, choose the more conservative one.
1431 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
1432 return A;
1433 if (A == S_Release && B == S_MovableRelease)
1434 return A;
1435 }
1436
1437 return S_None;
1438}
1439
1440namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001441 /// \brief Unidirectional information about either a
John McCalld935e9c2011-06-15 23:37:01 +00001442 /// retain-decrement-use-release sequence or release-use-decrement-retain
1443 /// reverese sequence.
1444 struct RRInfo {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001445 /// After an objc_retain, the reference count of the referenced
Dan Gohmanb3894012011-08-19 00:26:36 +00001446 /// object is known to be positive. Similarly, before an objc_release, the
1447 /// reference count of the referenced object is known to be positive. If
1448 /// there are retain-release pairs in code regions where the retain count
1449 /// is known to be positive, they can be eliminated, regardless of any side
1450 /// effects between them.
1451 ///
1452 /// Also, a retain+release pair nested within another retain+release
1453 /// pair all on the known same pointer value can be eliminated, regardless
1454 /// of any intervening side effects.
1455 ///
1456 /// KnownSafe is true when either of these conditions is satisfied.
1457 bool KnownSafe;
John McCalld935e9c2011-06-15 23:37:01 +00001458
Michael Gottesman97e3df02013-01-14 00:35:14 +00001459 /// True if the Calls are objc_retainBlock calls (as opposed to objc_retain
1460 /// calls).
John McCalld935e9c2011-06-15 23:37:01 +00001461 bool IsRetainBlock;
1462
Michael Gottesman97e3df02013-01-14 00:35:14 +00001463 /// True of the objc_release calls are all marked with the "tail" keyword.
John McCalld935e9c2011-06-15 23:37:01 +00001464 bool IsTailCallRelease;
1465
Michael Gottesman97e3df02013-01-14 00:35:14 +00001466 /// If the Calls are objc_release calls and they all have a
1467 /// clang.imprecise_release tag, this is the metadata tag.
John McCalld935e9c2011-06-15 23:37:01 +00001468 MDNode *ReleaseMetadata;
1469
Michael Gottesman97e3df02013-01-14 00:35:14 +00001470 /// For a top-down sequence, the set of objc_retains or
John McCalld935e9c2011-06-15 23:37:01 +00001471 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
1472 SmallPtrSet<Instruction *, 2> Calls;
1473
Michael Gottesman97e3df02013-01-14 00:35:14 +00001474 /// The set of optimal insert positions for moving calls in the opposite
1475 /// sequence.
John McCalld935e9c2011-06-15 23:37:01 +00001476 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
1477
1478 RRInfo() :
Dan Gohman728db492012-01-13 00:39:07 +00001479 KnownSafe(false), IsRetainBlock(false),
Dan Gohman62079b42012-04-25 00:50:46 +00001480 IsTailCallRelease(false),
John McCalld935e9c2011-06-15 23:37:01 +00001481 ReleaseMetadata(0) {}
1482
1483 void clear();
1484 };
1485}
1486
1487void RRInfo::clear() {
Dan Gohmanb3894012011-08-19 00:26:36 +00001488 KnownSafe = false;
John McCalld935e9c2011-06-15 23:37:01 +00001489 IsRetainBlock = false;
1490 IsTailCallRelease = false;
1491 ReleaseMetadata = 0;
1492 Calls.clear();
1493 ReverseInsertPts.clear();
1494}
1495
1496namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001497 /// \brief This class summarizes several per-pointer runtime properties which
1498 /// are propogated through the flow graph.
John McCalld935e9c2011-06-15 23:37:01 +00001499 class PtrState {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001500 /// True if the reference count is known to be incremented.
Dan Gohman62079b42012-04-25 00:50:46 +00001501 bool KnownPositiveRefCount;
1502
Michael Gottesman97e3df02013-01-14 00:35:14 +00001503 /// True of we've seen an opportunity for partial RR elimination, such as
1504 /// pushing calls into a CFG triangle or into one side of a CFG diamond.
Dan Gohman62079b42012-04-25 00:50:46 +00001505 bool Partial;
John McCalld935e9c2011-06-15 23:37:01 +00001506
Michael Gottesman97e3df02013-01-14 00:35:14 +00001507 /// The current position in the sequence.
Dan Gohman41375a32012-05-08 23:39:44 +00001508 Sequence Seq : 8;
John McCalld935e9c2011-06-15 23:37:01 +00001509
1510 public:
Michael Gottesman97e3df02013-01-14 00:35:14 +00001511 /// Unidirectional information about the current sequence.
1512 ///
John McCalld935e9c2011-06-15 23:37:01 +00001513 /// TODO: Encapsulate this better.
1514 RRInfo RRI;
1515
Dan Gohmandf476e52012-09-04 23:16:20 +00001516 PtrState() : KnownPositiveRefCount(false), Partial(false),
Dan Gohman41375a32012-05-08 23:39:44 +00001517 Seq(S_None) {}
John McCalld935e9c2011-06-15 23:37:01 +00001518
Dan Gohman62079b42012-04-25 00:50:46 +00001519 void SetKnownPositiveRefCount() {
1520 KnownPositiveRefCount = true;
Dan Gohman12130272011-08-12 00:26:31 +00001521 }
1522
Dan Gohman62079b42012-04-25 00:50:46 +00001523 void ClearRefCount() {
1524 KnownPositiveRefCount = false;
John McCalld935e9c2011-06-15 23:37:01 +00001525 }
1526
John McCalld935e9c2011-06-15 23:37:01 +00001527 bool IsKnownIncremented() const {
Dan Gohman62079b42012-04-25 00:50:46 +00001528 return KnownPositiveRefCount;
John McCalld935e9c2011-06-15 23:37:01 +00001529 }
1530
1531 void SetSeq(Sequence NewSeq) {
1532 Seq = NewSeq;
1533 }
1534
John McCalld935e9c2011-06-15 23:37:01 +00001535 Sequence GetSeq() const {
1536 return Seq;
1537 }
1538
1539 void ClearSequenceProgress() {
Dan Gohman62079b42012-04-25 00:50:46 +00001540 ResetSequenceProgress(S_None);
1541 }
1542
1543 void ResetSequenceProgress(Sequence NewSeq) {
1544 Seq = NewSeq;
1545 Partial = false;
John McCalld935e9c2011-06-15 23:37:01 +00001546 RRI.clear();
1547 }
1548
1549 void Merge(const PtrState &Other, bool TopDown);
1550 };
1551}
1552
1553void
1554PtrState::Merge(const PtrState &Other, bool TopDown) {
1555 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
Dan Gohman62079b42012-04-25 00:50:46 +00001556 KnownPositiveRefCount = KnownPositiveRefCount && Other.KnownPositiveRefCount;
John McCalld935e9c2011-06-15 23:37:01 +00001557
1558 // We can't merge a plain objc_retain with an objc_retainBlock.
1559 if (RRI.IsRetainBlock != Other.RRI.IsRetainBlock)
1560 Seq = S_None;
1561
Dan Gohman1736c142011-10-17 18:48:25 +00001562 // If we're not in a sequence (anymore), drop all associated state.
John McCalld935e9c2011-06-15 23:37:01 +00001563 if (Seq == S_None) {
Dan Gohman62079b42012-04-25 00:50:46 +00001564 Partial = false;
John McCalld935e9c2011-06-15 23:37:01 +00001565 RRI.clear();
Dan Gohman62079b42012-04-25 00:50:46 +00001566 } else if (Partial || Other.Partial) {
Dan Gohman1736c142011-10-17 18:48:25 +00001567 // If we're doing a merge on a path that's previously seen a partial
1568 // merge, conservatively drop the sequence, to avoid doing partial
1569 // RR elimination. If the branch predicates for the two merge differ,
1570 // mixing them is unsafe.
Dan Gohman62079b42012-04-25 00:50:46 +00001571 ClearSequenceProgress();
John McCalld935e9c2011-06-15 23:37:01 +00001572 } else {
1573 // Conservatively merge the ReleaseMetadata information.
1574 if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
1575 RRI.ReleaseMetadata = 0;
1576
Dan Gohmanb3894012011-08-19 00:26:36 +00001577 RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
Dan Gohman41375a32012-05-08 23:39:44 +00001578 RRI.IsTailCallRelease = RRI.IsTailCallRelease &&
1579 Other.RRI.IsTailCallRelease;
John McCalld935e9c2011-06-15 23:37:01 +00001580 RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
Dan Gohman1736c142011-10-17 18:48:25 +00001581
1582 // Merge the insert point sets. If there are any differences,
1583 // that makes this a partial merge.
Dan Gohman41375a32012-05-08 23:39:44 +00001584 Partial = RRI.ReverseInsertPts.size() != Other.RRI.ReverseInsertPts.size();
Dan Gohman1736c142011-10-17 18:48:25 +00001585 for (SmallPtrSet<Instruction *, 2>::const_iterator
1586 I = Other.RRI.ReverseInsertPts.begin(),
1587 E = Other.RRI.ReverseInsertPts.end(); I != E; ++I)
Dan Gohman62079b42012-04-25 00:50:46 +00001588 Partial |= RRI.ReverseInsertPts.insert(*I);
John McCalld935e9c2011-06-15 23:37:01 +00001589 }
1590}
1591
1592namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001593 /// \brief Per-BasicBlock state.
John McCalld935e9c2011-06-15 23:37:01 +00001594 class BBState {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001595 /// The number of unique control paths from the entry which can reach this
1596 /// block.
John McCalld935e9c2011-06-15 23:37:01 +00001597 unsigned TopDownPathCount;
1598
Michael Gottesman97e3df02013-01-14 00:35:14 +00001599 /// The number of unique control paths to exits from this block.
John McCalld935e9c2011-06-15 23:37:01 +00001600 unsigned BottomUpPathCount;
1601
Michael Gottesman97e3df02013-01-14 00:35:14 +00001602 /// A type for PerPtrTopDown and PerPtrBottomUp.
John McCalld935e9c2011-06-15 23:37:01 +00001603 typedef MapVector<const Value *, PtrState> MapTy;
1604
Michael Gottesman97e3df02013-01-14 00:35:14 +00001605 /// The top-down traversal uses this to record information known about a
1606 /// pointer at the bottom of each block.
John McCalld935e9c2011-06-15 23:37:01 +00001607 MapTy PerPtrTopDown;
1608
Michael Gottesman97e3df02013-01-14 00:35:14 +00001609 /// The bottom-up traversal uses this to record information known about a
1610 /// pointer at the top of each block.
John McCalld935e9c2011-06-15 23:37:01 +00001611 MapTy PerPtrBottomUp;
1612
Michael Gottesman97e3df02013-01-14 00:35:14 +00001613 /// Effective predecessors of the current block ignoring ignorable edges and
1614 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001615 SmallVector<BasicBlock *, 2> Preds;
Michael Gottesman97e3df02013-01-14 00:35:14 +00001616 /// Effective successors of the current block ignoring ignorable edges and
1617 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001618 SmallVector<BasicBlock *, 2> Succs;
1619
John McCalld935e9c2011-06-15 23:37:01 +00001620 public:
1621 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
1622
1623 typedef MapTy::iterator ptr_iterator;
1624 typedef MapTy::const_iterator ptr_const_iterator;
1625
1626 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
1627 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
1628 ptr_const_iterator top_down_ptr_begin() const {
1629 return PerPtrTopDown.begin();
1630 }
1631 ptr_const_iterator top_down_ptr_end() const {
1632 return PerPtrTopDown.end();
1633 }
1634
1635 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
1636 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
1637 ptr_const_iterator bottom_up_ptr_begin() const {
1638 return PerPtrBottomUp.begin();
1639 }
1640 ptr_const_iterator bottom_up_ptr_end() const {
1641 return PerPtrBottomUp.end();
1642 }
1643
Michael Gottesman97e3df02013-01-14 00:35:14 +00001644 /// Mark this block as being an entry block, which has one path from the
1645 /// entry by definition.
John McCalld935e9c2011-06-15 23:37:01 +00001646 void SetAsEntry() { TopDownPathCount = 1; }
1647
Michael Gottesman97e3df02013-01-14 00:35:14 +00001648 /// Mark this block as being an exit block, which has one path to an exit by
1649 /// definition.
John McCalld935e9c2011-06-15 23:37:01 +00001650 void SetAsExit() { BottomUpPathCount = 1; }
1651
1652 PtrState &getPtrTopDownState(const Value *Arg) {
1653 return PerPtrTopDown[Arg];
1654 }
1655
1656 PtrState &getPtrBottomUpState(const Value *Arg) {
1657 return PerPtrBottomUp[Arg];
1658 }
1659
1660 void clearBottomUpPointers() {
Evan Chenge4df6a22011-08-04 18:40:26 +00001661 PerPtrBottomUp.clear();
John McCalld935e9c2011-06-15 23:37:01 +00001662 }
1663
1664 void clearTopDownPointers() {
1665 PerPtrTopDown.clear();
1666 }
1667
1668 void InitFromPred(const BBState &Other);
1669 void InitFromSucc(const BBState &Other);
1670 void MergePred(const BBState &Other);
1671 void MergeSucc(const BBState &Other);
1672
Michael Gottesman97e3df02013-01-14 00:35:14 +00001673 /// Return the number of possible unique paths from an entry to an exit
1674 /// which pass through this block. This is only valid after both the
1675 /// top-down and bottom-up traversals are complete.
John McCalld935e9c2011-06-15 23:37:01 +00001676 unsigned GetAllPathCount() const {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001677 assert(TopDownPathCount != 0);
1678 assert(BottomUpPathCount != 0);
John McCalld935e9c2011-06-15 23:37:01 +00001679 return TopDownPathCount * BottomUpPathCount;
1680 }
Dan Gohman12130272011-08-12 00:26:31 +00001681
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001682 // Specialized CFG utilities.
Dan Gohmandae33492012-04-27 18:56:31 +00001683 typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001684 edge_iterator pred_begin() { return Preds.begin(); }
1685 edge_iterator pred_end() { return Preds.end(); }
1686 edge_iterator succ_begin() { return Succs.begin(); }
1687 edge_iterator succ_end() { return Succs.end(); }
1688
1689 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
1690 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
1691
1692 bool isExit() const { return Succs.empty(); }
John McCalld935e9c2011-06-15 23:37:01 +00001693 };
1694}
1695
1696void BBState::InitFromPred(const BBState &Other) {
1697 PerPtrTopDown = Other.PerPtrTopDown;
1698 TopDownPathCount = Other.TopDownPathCount;
1699}
1700
1701void BBState::InitFromSucc(const BBState &Other) {
1702 PerPtrBottomUp = Other.PerPtrBottomUp;
1703 BottomUpPathCount = Other.BottomUpPathCount;
1704}
1705
Michael Gottesman97e3df02013-01-14 00:35:14 +00001706/// The top-down traversal uses this to merge information about predecessors to
1707/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +00001708void BBState::MergePred(const BBState &Other) {
1709 // Other.TopDownPathCount can be 0, in which case it is either dead or a
1710 // loop backedge. Loop backedges are special.
1711 TopDownPathCount += Other.TopDownPathCount;
1712
Michael Gottesman4385edf2013-01-14 01:47:53 +00001713 // Check for overflow. If we have overflow, fall back to conservative
1714 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +00001715 if (TopDownPathCount < Other.TopDownPathCount) {
1716 clearTopDownPointers();
1717 return;
1718 }
1719
John McCalld935e9c2011-06-15 23:37:01 +00001720 // For each entry in the other set, if our set has an entry with the same key,
1721 // merge the entries. Otherwise, copy the entry and merge it with an empty
1722 // entry.
1723 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
1724 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
1725 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
1726 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1727 /*TopDown=*/true);
1728 }
1729
Dan Gohman7e315fc32011-08-11 21:06:32 +00001730 // For each entry in our set, if the other set doesn't have an entry with the
John McCalld935e9c2011-06-15 23:37:01 +00001731 // same key, force it to merge with an empty entry.
1732 for (ptr_iterator MI = top_down_ptr_begin(),
1733 ME = top_down_ptr_end(); MI != ME; ++MI)
1734 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
1735 MI->second.Merge(PtrState(), /*TopDown=*/true);
1736}
1737
Michael Gottesman97e3df02013-01-14 00:35:14 +00001738/// The bottom-up traversal uses this to merge information about successors to
1739/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +00001740void BBState::MergeSucc(const BBState &Other) {
1741 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
1742 // loop backedge. Loop backedges are special.
1743 BottomUpPathCount += Other.BottomUpPathCount;
1744
Michael Gottesman4385edf2013-01-14 01:47:53 +00001745 // Check for overflow. If we have overflow, fall back to conservative
1746 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +00001747 if (BottomUpPathCount < Other.BottomUpPathCount) {
1748 clearBottomUpPointers();
1749 return;
1750 }
1751
John McCalld935e9c2011-06-15 23:37:01 +00001752 // For each entry in the other set, if our set has an entry with the
1753 // same key, merge the entries. Otherwise, copy the entry and merge
1754 // it with an empty entry.
1755 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
1756 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
1757 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
1758 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1759 /*TopDown=*/false);
1760 }
1761
Dan Gohman7e315fc32011-08-11 21:06:32 +00001762 // For each entry in our set, if the other set doesn't have an entry
John McCalld935e9c2011-06-15 23:37:01 +00001763 // with the same key, force it to merge with an empty entry.
1764 for (ptr_iterator MI = bottom_up_ptr_begin(),
1765 ME = bottom_up_ptr_end(); MI != ME; ++MI)
1766 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
1767 MI->second.Merge(PtrState(), /*TopDown=*/false);
1768}
1769
1770namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001771 /// \brief The main ARC optimization pass.
John McCalld935e9c2011-06-15 23:37:01 +00001772 class ObjCARCOpt : public FunctionPass {
1773 bool Changed;
1774 ProvenanceAnalysis PA;
1775
Michael Gottesman97e3df02013-01-14 00:35:14 +00001776 /// A flag indicating whether this optimization pass should run.
Dan Gohmanceaac7c2011-06-20 23:20:43 +00001777 bool Run;
1778
Michael Gottesman97e3df02013-01-14 00:35:14 +00001779 /// Declarations for ObjC runtime functions, for use in creating calls to
1780 /// them. These are initialized lazily to avoid cluttering up the Module
1781 /// with unused declarations.
John McCalld935e9c2011-06-15 23:37:01 +00001782
Michael Gottesman97e3df02013-01-14 00:35:14 +00001783 /// Declaration for ObjC runtime function
1784 /// objc_retainAutoreleasedReturnValue.
1785 Constant *RetainRVCallee;
1786 /// Declaration for ObjC runtime function objc_autoreleaseReturnValue.
1787 Constant *AutoreleaseRVCallee;
1788 /// Declaration for ObjC runtime function objc_release.
1789 Constant *ReleaseCallee;
1790 /// Declaration for ObjC runtime function objc_retain.
1791 Constant *RetainCallee;
1792 /// Declaration for ObjC runtime function objc_retainBlock.
1793 Constant *RetainBlockCallee;
1794 /// Declaration for ObjC runtime function objc_autorelease.
1795 Constant *AutoreleaseCallee;
1796
1797 /// Flags which determine whether each of the interesting runtine functions
1798 /// is in fact used in the current function.
John McCalld935e9c2011-06-15 23:37:01 +00001799 unsigned UsedInThisFunction;
1800
Michael Gottesman97e3df02013-01-14 00:35:14 +00001801 /// The Metadata Kind for clang.imprecise_release metadata.
John McCalld935e9c2011-06-15 23:37:01 +00001802 unsigned ImpreciseReleaseMDKind;
1803
Michael Gottesman97e3df02013-01-14 00:35:14 +00001804 /// The Metadata Kind for clang.arc.copy_on_escape metadata.
Dan Gohmana7107f92011-10-17 22:53:25 +00001805 unsigned CopyOnEscapeMDKind;
1806
Michael Gottesman97e3df02013-01-14 00:35:14 +00001807 /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata.
Dan Gohman0155f302012-02-17 18:59:53 +00001808 unsigned NoObjCARCExceptionsMDKind;
1809
John McCalld935e9c2011-06-15 23:37:01 +00001810 Constant *getRetainRVCallee(Module *M);
1811 Constant *getAutoreleaseRVCallee(Module *M);
1812 Constant *getReleaseCallee(Module *M);
1813 Constant *getRetainCallee(Module *M);
Dan Gohman6320f522011-07-22 22:29:21 +00001814 Constant *getRetainBlockCallee(Module *M);
John McCalld935e9c2011-06-15 23:37:01 +00001815 Constant *getAutoreleaseCallee(Module *M);
1816
Dan Gohman728db492012-01-13 00:39:07 +00001817 bool IsRetainBlockOptimizable(const Instruction *Inst);
1818
John McCalld935e9c2011-06-15 23:37:01 +00001819 void OptimizeRetainCall(Function &F, Instruction *Retain);
1820 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
Michael Gottesman556ff612013-01-12 01:25:19 +00001821 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1822 InstructionClass &Class);
John McCalld935e9c2011-06-15 23:37:01 +00001823 void OptimizeIndividualCalls(Function &F);
1824
1825 void CheckForCFGHazards(const BasicBlock *BB,
1826 DenseMap<const BasicBlock *, BBState> &BBStates,
1827 BBState &MyStates) const;
Dan Gohman817a7c62012-03-22 18:24:56 +00001828 bool VisitInstructionBottomUp(Instruction *Inst,
Dan Gohman5c70fad2012-03-23 17:47:54 +00001829 BasicBlock *BB,
Dan Gohman817a7c62012-03-22 18:24:56 +00001830 MapVector<Value *, RRInfo> &Retains,
1831 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00001832 bool VisitBottomUp(BasicBlock *BB,
1833 DenseMap<const BasicBlock *, BBState> &BBStates,
1834 MapVector<Value *, RRInfo> &Retains);
Dan Gohman817a7c62012-03-22 18:24:56 +00001835 bool VisitInstructionTopDown(Instruction *Inst,
1836 DenseMap<Value *, RRInfo> &Releases,
1837 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00001838 bool VisitTopDown(BasicBlock *BB,
1839 DenseMap<const BasicBlock *, BBState> &BBStates,
1840 DenseMap<Value *, RRInfo> &Releases);
1841 bool Visit(Function &F,
1842 DenseMap<const BasicBlock *, BBState> &BBStates,
1843 MapVector<Value *, RRInfo> &Retains,
1844 DenseMap<Value *, RRInfo> &Releases);
1845
1846 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1847 MapVector<Value *, RRInfo> &Retains,
1848 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman6320f522011-07-22 22:29:21 +00001849 SmallVectorImpl<Instruction *> &DeadInsts,
1850 Module *M);
John McCalld935e9c2011-06-15 23:37:01 +00001851
1852 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1853 MapVector<Value *, RRInfo> &Retains,
Dan Gohman6320f522011-07-22 22:29:21 +00001854 DenseMap<Value *, RRInfo> &Releases,
1855 Module *M);
John McCalld935e9c2011-06-15 23:37:01 +00001856
1857 void OptimizeWeakCalls(Function &F);
1858
1859 bool OptimizeSequences(Function &F);
1860
1861 void OptimizeReturns(Function &F);
1862
1863 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1864 virtual bool doInitialization(Module &M);
1865 virtual bool runOnFunction(Function &F);
1866 virtual void releaseMemory();
1867
1868 public:
1869 static char ID;
1870 ObjCARCOpt() : FunctionPass(ID) {
1871 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1872 }
1873 };
1874}
1875
1876char ObjCARCOpt::ID = 0;
1877INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1878 "objc-arc", "ObjC ARC optimization", false, false)
1879INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1880INITIALIZE_PASS_END(ObjCARCOpt,
1881 "objc-arc", "ObjC ARC optimization", false, false)
1882
1883Pass *llvm::createObjCARCOptPass() {
1884 return new ObjCARCOpt();
1885}
1886
1887void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1888 AU.addRequired<ObjCARCAliasAnalysis>();
1889 AU.addRequired<AliasAnalysis>();
1890 // ARC optimization doesn't currently split critical edges.
1891 AU.setPreservesCFG();
1892}
1893
Dan Gohman728db492012-01-13 00:39:07 +00001894bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1895 // Without the magic metadata tag, we have to assume this might be an
1896 // objc_retainBlock call inserted to convert a block pointer to an id,
1897 // in which case it really is needed.
1898 if (!Inst->getMetadata(CopyOnEscapeMDKind))
1899 return false;
1900
1901 // If the pointer "escapes" (not including being used in a call),
1902 // the copy may be needed.
1903 if (DoesObjCBlockEscape(Inst))
1904 return false;
1905
1906 // Otherwise, it's not needed.
1907 return true;
1908}
1909
John McCalld935e9c2011-06-15 23:37:01 +00001910Constant *ObjCARCOpt::getRetainRVCallee(Module *M) {
1911 if (!RetainRVCallee) {
1912 LLVMContext &C = M->getContext();
Jay Foadb804a2b2011-07-12 14:06:48 +00001913 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman41375a32012-05-08 23:39:44 +00001914 Type *Params[] = { I8X };
1915 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001916 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001917 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1918 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001919 RetainRVCallee =
1920 M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy,
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001921 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001922 }
1923 return RetainRVCallee;
1924}
1925
1926Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1927 if (!AutoreleaseRVCallee) {
1928 LLVMContext &C = M->getContext();
Jay Foadb804a2b2011-07-12 14:06:48 +00001929 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman41375a32012-05-08 23:39:44 +00001930 Type *Params[] = { I8X };
1931 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001932 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001933 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1934 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001935 AutoreleaseRVCallee =
1936 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001937 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001938 }
1939 return AutoreleaseRVCallee;
1940}
1941
1942Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1943 if (!ReleaseCallee) {
1944 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001945 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001946 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001947 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1948 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001949 ReleaseCallee =
1950 M->getOrInsertFunction(
1951 "objc_release",
1952 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001953 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001954 }
1955 return ReleaseCallee;
1956}
1957
1958Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1959 if (!RetainCallee) {
1960 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001961 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001962 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001963 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1964 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001965 RetainCallee =
1966 M->getOrInsertFunction(
1967 "objc_retain",
1968 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001969 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001970 }
1971 return RetainCallee;
1972}
1973
Dan Gohman6320f522011-07-22 22:29:21 +00001974Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1975 if (!RetainBlockCallee) {
1976 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001977 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Dan Gohmanfca43c22011-09-14 18:33:34 +00001978 // objc_retainBlock is not nounwind because it calls user copy constructors
1979 // which could theoretically throw.
Dan Gohman6320f522011-07-22 22:29:21 +00001980 RetainBlockCallee =
1981 M->getOrInsertFunction(
1982 "objc_retainBlock",
1983 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendlinge94d8432012-12-07 23:16:57 +00001984 AttributeSet());
Dan Gohman6320f522011-07-22 22:29:21 +00001985 }
1986 return RetainBlockCallee;
1987}
1988
John McCalld935e9c2011-06-15 23:37:01 +00001989Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1990 if (!AutoreleaseCallee) {
1991 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001992 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001993 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001994 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1995 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001996 AutoreleaseCallee =
1997 M->getOrInsertFunction(
1998 "objc_autorelease",
1999 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +00002000 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00002001 }
2002 return AutoreleaseCallee;
2003}
2004
Michael Gottesman97e3df02013-01-14 00:35:14 +00002005/// Test whether the given value is possible a reference-counted pointer,
2006/// including tests which utilize AliasAnalysis.
Dan Gohmandf476e52012-09-04 23:16:20 +00002007static bool IsPotentialUse(const Value *Op, AliasAnalysis &AA) {
2008 // First make the rudimentary check.
2009 if (!IsPotentialUse(Op))
2010 return false;
2011
2012 // Objects in constant memory are not reference-counted.
2013 if (AA.pointsToConstantMemory(Op))
2014 return false;
2015
2016 // Pointers in constant memory are not pointing to reference-counted objects.
2017 if (const LoadInst *LI = dyn_cast<LoadInst>(Op))
2018 if (AA.pointsToConstantMemory(LI->getPointerOperand()))
2019 return false;
2020
2021 // Otherwise assume the worst.
2022 return true;
2023}
2024
Michael Gottesman97e3df02013-01-14 00:35:14 +00002025/// Test whether the given instruction can result in a reference count
2026/// modification (positive or negative) for the pointer's object.
John McCalld935e9c2011-06-15 23:37:01 +00002027static bool
2028CanAlterRefCount(const Instruction *Inst, const Value *Ptr,
2029 ProvenanceAnalysis &PA, InstructionClass Class) {
2030 switch (Class) {
2031 case IC_Autorelease:
2032 case IC_AutoreleaseRV:
2033 case IC_User:
2034 // These operations never directly modify a reference count.
2035 return false;
2036 default: break;
2037 }
2038
2039 ImmutableCallSite CS = static_cast<const Value *>(Inst);
2040 assert(CS && "Only calls can alter reference counts!");
2041
2042 // See if AliasAnalysis can help us with the call.
2043 AliasAnalysis::ModRefBehavior MRB = PA.getAA()->getModRefBehavior(CS);
2044 if (AliasAnalysis::onlyReadsMemory(MRB))
2045 return false;
2046 if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
2047 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
2048 I != E; ++I) {
2049 const Value *Op = *I;
Dan Gohmandf476e52012-09-04 23:16:20 +00002050 if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
John McCalld935e9c2011-06-15 23:37:01 +00002051 return true;
2052 }
2053 return false;
2054 }
2055
2056 // Assume the worst.
2057 return true;
2058}
2059
Michael Gottesman97e3df02013-01-14 00:35:14 +00002060/// Test whether the given instruction can "use" the given pointer's object in a
2061/// way that requires the reference count to be positive.
John McCalld935e9c2011-06-15 23:37:01 +00002062static bool
2063CanUse(const Instruction *Inst, const Value *Ptr, ProvenanceAnalysis &PA,
2064 InstructionClass Class) {
2065 // IC_Call operations (as opposed to IC_CallOrUser) never "use" objc pointers.
2066 if (Class == IC_Call)
2067 return false;
2068
2069 // Consider various instructions which may have pointer arguments which are
2070 // not "uses".
2071 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(Inst)) {
2072 // Comparing a pointer with null, or any other constant, isn't really a use,
2073 // because we don't care what the pointer points to, or about the values
2074 // of any other dynamic reference-counted pointers.
Dan Gohmandf476e52012-09-04 23:16:20 +00002075 if (!IsPotentialUse(ICI->getOperand(1), *PA.getAA()))
John McCalld935e9c2011-06-15 23:37:01 +00002076 return false;
2077 } else if (ImmutableCallSite CS = static_cast<const Value *>(Inst)) {
2078 // For calls, just check the arguments (and not the callee operand).
2079 for (ImmutableCallSite::arg_iterator OI = CS.arg_begin(),
2080 OE = CS.arg_end(); OI != OE; ++OI) {
2081 const Value *Op = *OI;
Dan Gohmandf476e52012-09-04 23:16:20 +00002082 if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
John McCalld935e9c2011-06-15 23:37:01 +00002083 return true;
2084 }
2085 return false;
2086 } else if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
2087 // Special-case stores, because we don't care about the stored value, just
2088 // the store address.
2089 const Value *Op = GetUnderlyingObjCPtr(SI->getPointerOperand());
2090 // If we can't tell what the underlying object was, assume there is a
2091 // dependence.
Dan Gohmandf476e52012-09-04 23:16:20 +00002092 return IsPotentialUse(Op, *PA.getAA()) && PA.related(Op, Ptr);
John McCalld935e9c2011-06-15 23:37:01 +00002093 }
2094
2095 // Check each operand for a match.
2096 for (User::const_op_iterator OI = Inst->op_begin(), OE = Inst->op_end();
2097 OI != OE; ++OI) {
2098 const Value *Op = *OI;
Dan Gohmandf476e52012-09-04 23:16:20 +00002099 if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
John McCalld935e9c2011-06-15 23:37:01 +00002100 return true;
2101 }
2102 return false;
2103}
2104
Michael Gottesman97e3df02013-01-14 00:35:14 +00002105/// Test whether the given instruction can autorelease any pointer or cause an
2106/// autoreleasepool pop.
John McCalld935e9c2011-06-15 23:37:01 +00002107static bool
2108CanInterruptRV(InstructionClass Class) {
2109 switch (Class) {
2110 case IC_AutoreleasepoolPop:
2111 case IC_CallOrUser:
2112 case IC_Call:
2113 case IC_Autorelease:
2114 case IC_AutoreleaseRV:
2115 case IC_FusedRetainAutorelease:
2116 case IC_FusedRetainAutoreleaseRV:
2117 return true;
2118 default:
2119 return false;
2120 }
2121}
2122
2123namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +00002124 /// \enum DependenceKind
2125 /// \brief Defines different dependence kinds among various ARC constructs.
2126 ///
2127 /// There are several kinds of dependence-like concepts in use here.
2128 ///
John McCalld935e9c2011-06-15 23:37:01 +00002129 enum DependenceKind {
2130 NeedsPositiveRetainCount,
Dan Gohman8478d762012-04-13 00:59:57 +00002131 AutoreleasePoolBoundary,
John McCalld935e9c2011-06-15 23:37:01 +00002132 CanChangeRetainCount,
2133 RetainAutoreleaseDep, ///< Blocks objc_retainAutorelease.
2134 RetainAutoreleaseRVDep, ///< Blocks objc_retainAutoreleaseReturnValue.
2135 RetainRVDep ///< Blocks objc_retainAutoreleasedReturnValue.
2136 };
2137}
2138
Michael Gottesman97e3df02013-01-14 00:35:14 +00002139/// Test if there can be dependencies on Inst through Arg. This function only
2140/// tests dependencies relevant for removing pairs of calls.
John McCalld935e9c2011-06-15 23:37:01 +00002141static bool
2142Depends(DependenceKind Flavor, Instruction *Inst, const Value *Arg,
2143 ProvenanceAnalysis &PA) {
2144 // If we've reached the definition of Arg, stop.
2145 if (Inst == Arg)
2146 return true;
2147
2148 switch (Flavor) {
2149 case NeedsPositiveRetainCount: {
2150 InstructionClass Class = GetInstructionClass(Inst);
2151 switch (Class) {
2152 case IC_AutoreleasepoolPop:
2153 case IC_AutoreleasepoolPush:
2154 case IC_None:
2155 return false;
2156 default:
2157 return CanUse(Inst, Arg, PA, Class);
2158 }
2159 }
2160
Dan Gohman8478d762012-04-13 00:59:57 +00002161 case AutoreleasePoolBoundary: {
2162 InstructionClass Class = GetInstructionClass(Inst);
2163 switch (Class) {
2164 case IC_AutoreleasepoolPop:
2165 case IC_AutoreleasepoolPush:
2166 // These mark the end and begin of an autorelease pool scope.
2167 return true;
2168 default:
2169 // Nothing else does this.
2170 return false;
2171 }
2172 }
2173
John McCalld935e9c2011-06-15 23:37:01 +00002174 case CanChangeRetainCount: {
2175 InstructionClass Class = GetInstructionClass(Inst);
2176 switch (Class) {
2177 case IC_AutoreleasepoolPop:
2178 // Conservatively assume this can decrement any count.
2179 return true;
2180 case IC_AutoreleasepoolPush:
2181 case IC_None:
2182 return false;
2183 default:
2184 return CanAlterRefCount(Inst, Arg, PA, Class);
2185 }
2186 }
2187
2188 case RetainAutoreleaseDep:
2189 switch (GetBasicInstructionClass(Inst)) {
2190 case IC_AutoreleasepoolPop:
Dan Gohman8478d762012-04-13 00:59:57 +00002191 case IC_AutoreleasepoolPush:
John McCalld935e9c2011-06-15 23:37:01 +00002192 // Don't merge an objc_autorelease with an objc_retain inside a different
2193 // autoreleasepool scope.
2194 return true;
2195 case IC_Retain:
2196 case IC_RetainRV:
2197 // Check for a retain of the same pointer for merging.
2198 return GetObjCArg(Inst) == Arg;
2199 default:
2200 // Nothing else matters for objc_retainAutorelease formation.
2201 return false;
2202 }
John McCalld935e9c2011-06-15 23:37:01 +00002203
2204 case RetainAutoreleaseRVDep: {
2205 InstructionClass Class = GetBasicInstructionClass(Inst);
2206 switch (Class) {
2207 case IC_Retain:
2208 case IC_RetainRV:
2209 // Check for a retain of the same pointer for merging.
2210 return GetObjCArg(Inst) == Arg;
2211 default:
2212 // Anything that can autorelease interrupts
2213 // retainAutoreleaseReturnValue formation.
2214 return CanInterruptRV(Class);
2215 }
John McCalld935e9c2011-06-15 23:37:01 +00002216 }
2217
2218 case RetainRVDep:
2219 return CanInterruptRV(GetBasicInstructionClass(Inst));
2220 }
2221
2222 llvm_unreachable("Invalid dependence flavor");
John McCalld935e9c2011-06-15 23:37:01 +00002223}
2224
Michael Gottesman97e3df02013-01-14 00:35:14 +00002225/// Walk up the CFG from StartPos (which is in StartBB) and find local and
2226/// non-local dependencies on Arg.
2227///
John McCalld935e9c2011-06-15 23:37:01 +00002228/// TODO: Cache results?
2229static void
2230FindDependencies(DependenceKind Flavor,
2231 const Value *Arg,
2232 BasicBlock *StartBB, Instruction *StartInst,
2233 SmallPtrSet<Instruction *, 4> &DependingInstructions,
2234 SmallPtrSet<const BasicBlock *, 4> &Visited,
2235 ProvenanceAnalysis &PA) {
2236 BasicBlock::iterator StartPos = StartInst;
2237
2238 SmallVector<std::pair<BasicBlock *, BasicBlock::iterator>, 4> Worklist;
2239 Worklist.push_back(std::make_pair(StartBB, StartPos));
2240 do {
2241 std::pair<BasicBlock *, BasicBlock::iterator> Pair =
2242 Worklist.pop_back_val();
2243 BasicBlock *LocalStartBB = Pair.first;
2244 BasicBlock::iterator LocalStartPos = Pair.second;
2245 BasicBlock::iterator StartBBBegin = LocalStartBB->begin();
2246 for (;;) {
2247 if (LocalStartPos == StartBBBegin) {
2248 pred_iterator PI(LocalStartBB), PE(LocalStartBB, false);
2249 if (PI == PE)
2250 // If we've reached the function entry, produce a null dependence.
2251 DependingInstructions.insert(0);
2252 else
2253 // Add the predecessors to the worklist.
2254 do {
2255 BasicBlock *PredBB = *PI;
2256 if (Visited.insert(PredBB))
2257 Worklist.push_back(std::make_pair(PredBB, PredBB->end()));
2258 } while (++PI != PE);
2259 break;
2260 }
2261
2262 Instruction *Inst = --LocalStartPos;
2263 if (Depends(Flavor, Inst, Arg, PA)) {
2264 DependingInstructions.insert(Inst);
2265 break;
2266 }
2267 }
2268 } while (!Worklist.empty());
2269
2270 // Determine whether the original StartBB post-dominates all of the blocks we
2271 // visited. If not, insert a sentinal indicating that most optimizations are
2272 // not safe.
2273 for (SmallPtrSet<const BasicBlock *, 4>::const_iterator I = Visited.begin(),
2274 E = Visited.end(); I != E; ++I) {
2275 const BasicBlock *BB = *I;
2276 if (BB == StartBB)
2277 continue;
2278 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2279 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2280 const BasicBlock *Succ = *SI;
2281 if (Succ != StartBB && !Visited.count(Succ)) {
2282 DependingInstructions.insert(reinterpret_cast<Instruction *>(-1));
2283 return;
2284 }
2285 }
2286 }
2287}
2288
2289static bool isNullOrUndef(const Value *V) {
2290 return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
2291}
2292
2293static bool isNoopInstruction(const Instruction *I) {
2294 return isa<BitCastInst>(I) ||
2295 (isa<GetElementPtrInst>(I) &&
2296 cast<GetElementPtrInst>(I)->hasAllZeroIndices());
2297}
2298
Michael Gottesman97e3df02013-01-14 00:35:14 +00002299/// Turn objc_retain into objc_retainAutoreleasedReturnValue if the operand is a
2300/// return value.
John McCalld935e9c2011-06-15 23:37:01 +00002301void
2302ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) {
Dan Gohmandae33492012-04-27 18:56:31 +00002303 ImmutableCallSite CS(GetObjCArg(Retain));
2304 const Instruction *Call = CS.getInstruction();
John McCalld935e9c2011-06-15 23:37:01 +00002305 if (!Call) return;
2306 if (Call->getParent() != Retain->getParent()) return;
2307
2308 // Check that the call is next to the retain.
Dan Gohmandae33492012-04-27 18:56:31 +00002309 BasicBlock::const_iterator I = Call;
John McCalld935e9c2011-06-15 23:37:01 +00002310 ++I;
2311 while (isNoopInstruction(I)) ++I;
2312 if (&*I != Retain)
2313 return;
2314
2315 // Turn it to an objc_retainAutoreleasedReturnValue..
2316 Changed = true;
2317 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00002318
Michael Gottesman1e00ac62013-01-04 21:30:38 +00002319 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainCall: Transforming "
Michael Gottesman9f1be682013-01-12 03:45:49 +00002320 "objc_retain => objc_retainAutoreleasedReturnValue"
2321 " since the operand is a return value.\n"
Michael Gottesman1e00ac62013-01-04 21:30:38 +00002322 " Old: "
2323 << *Retain << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00002324
John McCalld935e9c2011-06-15 23:37:01 +00002325 cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent()));
Michael Gottesman1e00ac62013-01-04 21:30:38 +00002326
2327 DEBUG(dbgs() << " New: "
2328 << *Retain << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002329}
2330
Michael Gottesman97e3df02013-01-14 00:35:14 +00002331/// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is
2332/// not a return value. Or, if it can be paired with an
2333/// objc_autoreleaseReturnValue, delete the pair and return true.
John McCalld935e9c2011-06-15 23:37:01 +00002334bool
2335ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +00002336 // Check for the argument being from an immediately preceding call or invoke.
Dan Gohmandae33492012-04-27 18:56:31 +00002337 const Value *Arg = GetObjCArg(RetainRV);
2338 ImmutableCallSite CS(Arg);
2339 if (const Instruction *Call = CS.getInstruction()) {
John McCalld935e9c2011-06-15 23:37:01 +00002340 if (Call->getParent() == RetainRV->getParent()) {
Dan Gohmandae33492012-04-27 18:56:31 +00002341 BasicBlock::const_iterator I = Call;
John McCalld935e9c2011-06-15 23:37:01 +00002342 ++I;
2343 while (isNoopInstruction(I)) ++I;
2344 if (&*I == RetainRV)
2345 return false;
Dan Gohmandae33492012-04-27 18:56:31 +00002346 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +00002347 BasicBlock *RetainRVParent = RetainRV->getParent();
2348 if (II->getNormalDest() == RetainRVParent) {
Dan Gohmandae33492012-04-27 18:56:31 +00002349 BasicBlock::const_iterator I = RetainRVParent->begin();
Dan Gohmane3ed2b02012-03-23 18:09:00 +00002350 while (isNoopInstruction(I)) ++I;
2351 if (&*I == RetainRV)
2352 return false;
2353 }
John McCalld935e9c2011-06-15 23:37:01 +00002354 }
Dan Gohmane3ed2b02012-03-23 18:09:00 +00002355 }
John McCalld935e9c2011-06-15 23:37:01 +00002356
2357 // Check for being preceded by an objc_autoreleaseReturnValue on the same
2358 // pointer. In this case, we can delete the pair.
2359 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
2360 if (I != Begin) {
2361 do --I; while (I != Begin && isNoopInstruction(I));
2362 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
2363 GetObjCArg(I) == Arg) {
2364 Changed = true;
2365 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00002366
Michael Gottesman5c32ce92013-01-05 17:55:35 +00002367 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainRVCall: Erasing " << *I << "\n"
2368 << " Erasing " << *RetainRV
2369 << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00002370
John McCalld935e9c2011-06-15 23:37:01 +00002371 EraseInstruction(I);
2372 EraseInstruction(RetainRV);
2373 return true;
2374 }
2375 }
2376
2377 // Turn it to a plain objc_retain.
2378 Changed = true;
2379 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00002380
Michael Gottesmandef07bb2013-01-05 17:55:42 +00002381 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainRVCall: Transforming "
2382 "objc_retainAutoreleasedReturnValue => "
2383 "objc_retain since the operand is not a return value.\n"
2384 " Old: "
2385 << *RetainRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00002386
John McCalld935e9c2011-06-15 23:37:01 +00002387 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
Michael Gottesmandef07bb2013-01-05 17:55:42 +00002388
2389 DEBUG(dbgs() << " New: "
2390 << *RetainRV << "\n");
2391
John McCalld935e9c2011-06-15 23:37:01 +00002392 return false;
2393}
2394
Michael Gottesman97e3df02013-01-14 00:35:14 +00002395/// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not
2396/// used as a return value.
John McCalld935e9c2011-06-15 23:37:01 +00002397void
Michael Gottesman556ff612013-01-12 01:25:19 +00002398ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
2399 InstructionClass &Class) {
John McCalld935e9c2011-06-15 23:37:01 +00002400 // Check for a return of the pointer value.
2401 const Value *Ptr = GetObjCArg(AutoreleaseRV);
Dan Gohman10a18d52011-08-12 00:36:31 +00002402 SmallVector<const Value *, 2> Users;
2403 Users.push_back(Ptr);
2404 do {
2405 Ptr = Users.pop_back_val();
2406 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
2407 UI != UE; ++UI) {
2408 const User *I = *UI;
2409 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
2410 return;
2411 if (isa<BitCastInst>(I))
2412 Users.push_back(I);
2413 }
2414 } while (!Users.empty());
John McCalld935e9c2011-06-15 23:37:01 +00002415
2416 Changed = true;
2417 ++NumPeeps;
Michael Gottesman1bf69082013-01-06 21:07:11 +00002418
2419 DEBUG(dbgs() << "ObjCARCOpt::OptimizeAutoreleaseRVCall: Transforming "
2420 "objc_autoreleaseReturnValue => "
2421 "objc_autorelease since its operand is not used as a return "
2422 "value.\n"
2423 " Old: "
2424 << *AutoreleaseRV << "\n");
2425
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00002426 CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
2427 AutoreleaseRVCI->
John McCalld935e9c2011-06-15 23:37:01 +00002428 setCalledFunction(getAutoreleaseCallee(F.getParent()));
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00002429 AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
Michael Gottesman556ff612013-01-12 01:25:19 +00002430 Class = IC_Autorelease;
Michael Gottesman10426b52013-01-07 21:26:07 +00002431
Michael Gottesman1bf69082013-01-06 21:07:11 +00002432 DEBUG(dbgs() << " New: "
2433 << *AutoreleaseRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00002434
John McCalld935e9c2011-06-15 23:37:01 +00002435}
2436
Michael Gottesman97e3df02013-01-14 00:35:14 +00002437/// Visit each call, one at a time, and make simplifications without doing any
2438/// additional analysis.
John McCalld935e9c2011-06-15 23:37:01 +00002439void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
2440 // Reset all the flags in preparation for recomputing them.
2441 UsedInThisFunction = 0;
2442
2443 // Visit all objc_* calls in F.
2444 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2445 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +00002446
John McCalld935e9c2011-06-15 23:37:01 +00002447 InstructionClass Class = GetBasicInstructionClass(Inst);
2448
Michael Gottesmand359e062013-01-18 03:08:39 +00002449 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Visiting: Class: "
2450 << Class << "; " << *Inst << "\n");
Michael Gottesman782e3442013-01-17 18:32:34 +00002451
John McCalld935e9c2011-06-15 23:37:01 +00002452 switch (Class) {
2453 default: break;
2454
2455 // Delete no-op casts. These function calls have special semantics, but
2456 // the semantics are entirely implemented via lowering in the front-end,
2457 // so by the time they reach the optimizer, they are just no-op calls
2458 // which return their argument.
2459 //
2460 // There are gray areas here, as the ability to cast reference-counted
2461 // pointers to raw void* and back allows code to break ARC assumptions,
2462 // however these are currently considered to be unimportant.
2463 case IC_NoopCast:
2464 Changed = true;
2465 ++NumNoops;
Michael Gottesmandc042f02013-01-06 21:07:15 +00002466 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Erasing no-op cast:"
2467 " " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002468 EraseInstruction(Inst);
2469 continue;
2470
2471 // If the pointer-to-weak-pointer is null, it's undefined behavior.
2472 case IC_StoreWeak:
2473 case IC_LoadWeak:
2474 case IC_LoadWeakRetained:
2475 case IC_InitWeak:
2476 case IC_DestroyWeak: {
2477 CallInst *CI = cast<CallInst>(Inst);
2478 if (isNullOrUndef(CI->getArgOperand(0))) {
Dan Gohman670f9372012-04-13 18:57:48 +00002479 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +00002480 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00002481 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2482 Constant::getNullValue(Ty),
2483 CI);
Michael Gottesman10426b52013-01-07 21:26:07 +00002484 llvm::Value *NewValue = UndefValue::get(CI->getType());
Michael Gottesmanfec61c02013-01-06 21:54:30 +00002485 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: A null "
2486 "pointer-to-weak-pointer is undefined behavior.\n"
2487 " Old = " << *CI <<
2488 "\n New = " <<
Michael Gottesman10426b52013-01-07 21:26:07 +00002489 *NewValue << "\n");
Michael Gottesmanfec61c02013-01-06 21:54:30 +00002490 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +00002491 CI->eraseFromParent();
2492 continue;
2493 }
2494 break;
2495 }
2496 case IC_CopyWeak:
2497 case IC_MoveWeak: {
2498 CallInst *CI = cast<CallInst>(Inst);
2499 if (isNullOrUndef(CI->getArgOperand(0)) ||
2500 isNullOrUndef(CI->getArgOperand(1))) {
Dan Gohman670f9372012-04-13 18:57:48 +00002501 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +00002502 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00002503 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2504 Constant::getNullValue(Ty),
2505 CI);
Michael Gottesmanfec61c02013-01-06 21:54:30 +00002506
2507 llvm::Value *NewValue = UndefValue::get(CI->getType());
2508 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: A null "
2509 "pointer-to-weak-pointer is undefined behavior.\n"
2510 " Old = " << *CI <<
2511 "\n New = " <<
2512 *NewValue << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00002513
Michael Gottesmanfec61c02013-01-06 21:54:30 +00002514 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +00002515 CI->eraseFromParent();
2516 continue;
2517 }
2518 break;
2519 }
2520 case IC_Retain:
2521 OptimizeRetainCall(F, Inst);
2522 break;
2523 case IC_RetainRV:
2524 if (OptimizeRetainRVCall(F, Inst))
2525 continue;
2526 break;
2527 case IC_AutoreleaseRV:
Michael Gottesman556ff612013-01-12 01:25:19 +00002528 OptimizeAutoreleaseRVCall(F, Inst, Class);
John McCalld935e9c2011-06-15 23:37:01 +00002529 break;
2530 }
2531
2532 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
2533 if (IsAutorelease(Class) && Inst->use_empty()) {
2534 CallInst *Call = cast<CallInst>(Inst);
2535 const Value *Arg = Call->getArgOperand(0);
2536 Arg = FindSingleUseIdentifiedObject(Arg);
2537 if (Arg) {
2538 Changed = true;
2539 ++NumAutoreleases;
2540
2541 // Create the declaration lazily.
2542 LLVMContext &C = Inst->getContext();
2543 CallInst *NewCall =
2544 CallInst::Create(getReleaseCallee(F.getParent()),
2545 Call->getArgOperand(0), "", Call);
2546 NewCall->setMetadata(ImpreciseReleaseMDKind,
2547 MDNode::get(C, ArrayRef<Value *>()));
Michael Gottesman10426b52013-01-07 21:26:07 +00002548
Michael Gottesmana6a1dad2013-01-06 22:56:50 +00002549 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Replacing "
2550 "objc_autorelease(x) with objc_release(x) since x is "
2551 "otherwise unused.\n"
Michael Gottesman4bf6e752013-01-06 22:56:54 +00002552 " Old: " << *Call <<
Michael Gottesmana6a1dad2013-01-06 22:56:50 +00002553 "\n New: " <<
2554 *NewCall << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00002555
John McCalld935e9c2011-06-15 23:37:01 +00002556 EraseInstruction(Call);
2557 Inst = NewCall;
2558 Class = IC_Release;
2559 }
2560 }
2561
2562 // For functions which can never be passed stack arguments, add
2563 // a tail keyword.
2564 if (IsAlwaysTail(Class)) {
2565 Changed = true;
Michael Gottesman2d763312013-01-06 23:39:09 +00002566 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Adding tail keyword"
2567 " to function since it can never be passed stack args: " << *Inst <<
2568 "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002569 cast<CallInst>(Inst)->setTailCall();
2570 }
2571
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00002572 // Ensure that functions that can never have a "tail" keyword due to the
2573 // semantics of ARC truly do not do so.
2574 if (IsNeverTail(Class)) {
2575 Changed = true;
Michael Gottesman4385edf2013-01-14 01:47:53 +00002576 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Removing tail "
2577 "keyword from function: " << *Inst <<
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00002578 "\n");
2579 cast<CallInst>(Inst)->setTailCall(false);
2580 }
2581
John McCalld935e9c2011-06-15 23:37:01 +00002582 // Set nounwind as needed.
2583 if (IsNoThrow(Class)) {
2584 Changed = true;
Michael Gottesman8800a512013-01-06 23:39:13 +00002585 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Found no throw"
2586 " class. Setting nounwind on: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002587 cast<CallInst>(Inst)->setDoesNotThrow();
2588 }
2589
2590 if (!IsNoopOnNull(Class)) {
2591 UsedInThisFunction |= 1 << Class;
2592 continue;
2593 }
2594
2595 const Value *Arg = GetObjCArg(Inst);
2596
2597 // ARC calls with null are no-ops. Delete them.
2598 if (isNullOrUndef(Arg)) {
2599 Changed = true;
2600 ++NumNoops;
Michael Gottesman5b970e12013-01-07 00:04:52 +00002601 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: ARC calls with "
2602 " null are no-ops. Erasing: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002603 EraseInstruction(Inst);
2604 continue;
2605 }
2606
2607 // Keep track of which of retain, release, autorelease, and retain_block
2608 // are actually present in this function.
2609 UsedInThisFunction |= 1 << Class;
2610
2611 // If Arg is a PHI, and one or more incoming values to the
2612 // PHI are null, and the call is control-equivalent to the PHI, and there
2613 // are no relevant side effects between the PHI and the call, the call
2614 // could be pushed up to just those paths with non-null incoming values.
2615 // For now, don't bother splitting critical edges for this.
2616 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
2617 Worklist.push_back(std::make_pair(Inst, Arg));
2618 do {
2619 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
2620 Inst = Pair.first;
2621 Arg = Pair.second;
2622
2623 const PHINode *PN = dyn_cast<PHINode>(Arg);
2624 if (!PN) continue;
2625
2626 // Determine if the PHI has any null operands, or any incoming
2627 // critical edges.
2628 bool HasNull = false;
2629 bool HasCriticalEdges = false;
2630 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2631 Value *Incoming =
2632 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2633 if (isNullOrUndef(Incoming))
2634 HasNull = true;
2635 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
2636 .getNumSuccessors() != 1) {
2637 HasCriticalEdges = true;
2638 break;
2639 }
2640 }
2641 // If we have null operands and no critical edges, optimize.
2642 if (!HasCriticalEdges && HasNull) {
2643 SmallPtrSet<Instruction *, 4> DependingInstructions;
2644 SmallPtrSet<const BasicBlock *, 4> Visited;
2645
2646 // Check that there is nothing that cares about the reference
2647 // count between the call and the phi.
Dan Gohman8478d762012-04-13 00:59:57 +00002648 switch (Class) {
2649 case IC_Retain:
2650 case IC_RetainBlock:
2651 // These can always be moved up.
2652 break;
2653 case IC_Release:
Dan Gohman41375a32012-05-08 23:39:44 +00002654 // These can't be moved across things that care about the retain
2655 // count.
Dan Gohman8478d762012-04-13 00:59:57 +00002656 FindDependencies(NeedsPositiveRetainCount, Arg,
2657 Inst->getParent(), Inst,
2658 DependingInstructions, Visited, PA);
2659 break;
2660 case IC_Autorelease:
2661 // These can't be moved across autorelease pool scope boundaries.
2662 FindDependencies(AutoreleasePoolBoundary, Arg,
2663 Inst->getParent(), Inst,
2664 DependingInstructions, Visited, PA);
2665 break;
2666 case IC_RetainRV:
2667 case IC_AutoreleaseRV:
2668 // Don't move these; the RV optimization depends on the autoreleaseRV
2669 // being tail called, and the retainRV being immediately after a call
2670 // (which might still happen if we get lucky with codegen layout, but
2671 // it's not worth taking the chance).
2672 continue;
2673 default:
2674 llvm_unreachable("Invalid dependence flavor");
2675 }
2676
John McCalld935e9c2011-06-15 23:37:01 +00002677 if (DependingInstructions.size() == 1 &&
2678 *DependingInstructions.begin() == PN) {
2679 Changed = true;
2680 ++NumPartialNoops;
2681 // Clone the call into each predecessor that has a non-null value.
2682 CallInst *CInst = cast<CallInst>(Inst);
Chris Lattner229907c2011-07-18 04:54:35 +00002683 Type *ParamTy = CInst->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00002684 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2685 Value *Incoming =
2686 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2687 if (!isNullOrUndef(Incoming)) {
2688 CallInst *Clone = cast<CallInst>(CInst->clone());
2689 Value *Op = PN->getIncomingValue(i);
2690 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
2691 if (Op->getType() != ParamTy)
2692 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
2693 Clone->setArgOperand(0, Op);
2694 Clone->insertBefore(InsertPos);
Michael Gottesmanc189a392013-01-09 19:23:24 +00002695
2696 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Cloning "
2697 << *CInst << "\n"
2698 " And inserting "
2699 "clone at " << *InsertPos << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002700 Worklist.push_back(std::make_pair(Clone, Incoming));
2701 }
2702 }
2703 // Erase the original call.
Michael Gottesmanc189a392013-01-09 19:23:24 +00002704 DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002705 EraseInstruction(CInst);
2706 continue;
2707 }
2708 }
2709 } while (!Worklist.empty());
2710 }
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00002711 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Finished List.\n");
John McCalld935e9c2011-06-15 23:37:01 +00002712}
2713
Michael Gottesman97e3df02013-01-14 00:35:14 +00002714/// Check for critical edges, loop boundaries, irreducible control flow, or
2715/// other CFG structures where moving code across the edge would result in it
2716/// being executed more.
John McCalld935e9c2011-06-15 23:37:01 +00002717void
2718ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
2719 DenseMap<const BasicBlock *, BBState> &BBStates,
2720 BBState &MyStates) const {
2721 // If any top-down local-use or possible-dec has a succ which is earlier in
2722 // the sequence, forget it.
Dan Gohman55b06742012-03-02 01:13:53 +00002723 for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
John McCalld935e9c2011-06-15 23:37:01 +00002724 E = MyStates.top_down_ptr_end(); I != E; ++I)
2725 switch (I->second.GetSeq()) {
2726 default: break;
2727 case S_Use: {
2728 const Value *Arg = I->first;
2729 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2730 bool SomeSuccHasSame = false;
2731 bool AllSuccsHaveSame = true;
Dan Gohman55b06742012-03-02 01:13:53 +00002732 PtrState &S = I->second;
Dan Gohman0155f302012-02-17 18:59:53 +00002733 succ_const_iterator SI(TI), SE(TI, false);
2734
Dan Gohman0155f302012-02-17 18:59:53 +00002735 for (; SI != SE; ++SI) {
Dan Gohman362eb692012-03-02 01:26:46 +00002736 Sequence SuccSSeq = S_None;
2737 bool SuccSRRIKnownSafe = false;
Dan Gohman41375a32012-05-08 23:39:44 +00002738 // If VisitBottomUp has pointer information for this successor, take
2739 // what we know about it.
Dan Gohmandae33492012-04-27 18:56:31 +00002740 DenseMap<const BasicBlock *, BBState>::iterator BBI =
2741 BBStates.find(*SI);
2742 assert(BBI != BBStates.end());
2743 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2744 SuccSSeq = SuccS.GetSeq();
2745 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
Dan Gohman362eb692012-03-02 01:26:46 +00002746 switch (SuccSSeq) {
John McCalld935e9c2011-06-15 23:37:01 +00002747 case S_None:
Dan Gohman12130272011-08-12 00:26:31 +00002748 case S_CanRelease: {
Dan Gohman362eb692012-03-02 01:26:46 +00002749 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
Dan Gohman12130272011-08-12 00:26:31 +00002750 S.ClearSequenceProgress();
Dan Gohman362eb692012-03-02 01:26:46 +00002751 break;
2752 }
Dan Gohman12130272011-08-12 00:26:31 +00002753 continue;
2754 }
John McCalld935e9c2011-06-15 23:37:01 +00002755 case S_Use:
2756 SomeSuccHasSame = true;
2757 break;
2758 case S_Stop:
2759 case S_Release:
2760 case S_MovableRelease:
Dan Gohman362eb692012-03-02 01:26:46 +00002761 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
Dan Gohman12130272011-08-12 00:26:31 +00002762 AllSuccsHaveSame = false;
John McCalld935e9c2011-06-15 23:37:01 +00002763 break;
2764 case S_Retain:
2765 llvm_unreachable("bottom-up pointer in retain state!");
2766 }
Dan Gohman12130272011-08-12 00:26:31 +00002767 }
John McCalld935e9c2011-06-15 23:37:01 +00002768 // If the state at the other end of any of the successor edges
2769 // matches the current state, require all edges to match. This
2770 // guards against loops in the middle of a sequence.
2771 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohman12130272011-08-12 00:26:31 +00002772 S.ClearSequenceProgress();
Dan Gohman044437062011-12-12 18:13:53 +00002773 break;
John McCalld935e9c2011-06-15 23:37:01 +00002774 }
2775 case S_CanRelease: {
2776 const Value *Arg = I->first;
2777 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2778 bool SomeSuccHasSame = false;
2779 bool AllSuccsHaveSame = true;
Dan Gohman55b06742012-03-02 01:13:53 +00002780 PtrState &S = I->second;
Dan Gohman0155f302012-02-17 18:59:53 +00002781 succ_const_iterator SI(TI), SE(TI, false);
2782
Dan Gohman0155f302012-02-17 18:59:53 +00002783 for (; SI != SE; ++SI) {
Dan Gohman362eb692012-03-02 01:26:46 +00002784 Sequence SuccSSeq = S_None;
2785 bool SuccSRRIKnownSafe = false;
Dan Gohman41375a32012-05-08 23:39:44 +00002786 // If VisitBottomUp has pointer information for this successor, take
2787 // what we know about it.
Dan Gohmandae33492012-04-27 18:56:31 +00002788 DenseMap<const BasicBlock *, BBState>::iterator BBI =
2789 BBStates.find(*SI);
2790 assert(BBI != BBStates.end());
2791 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2792 SuccSSeq = SuccS.GetSeq();
2793 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
Dan Gohman362eb692012-03-02 01:26:46 +00002794 switch (SuccSSeq) {
Dan Gohman12130272011-08-12 00:26:31 +00002795 case S_None: {
Dan Gohman362eb692012-03-02 01:26:46 +00002796 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
Dan Gohman12130272011-08-12 00:26:31 +00002797 S.ClearSequenceProgress();
Dan Gohman362eb692012-03-02 01:26:46 +00002798 break;
2799 }
Dan Gohman12130272011-08-12 00:26:31 +00002800 continue;
2801 }
John McCalld935e9c2011-06-15 23:37:01 +00002802 case S_CanRelease:
2803 SomeSuccHasSame = true;
2804 break;
2805 case S_Stop:
2806 case S_Release:
2807 case S_MovableRelease:
2808 case S_Use:
Dan Gohman362eb692012-03-02 01:26:46 +00002809 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
Dan Gohman12130272011-08-12 00:26:31 +00002810 AllSuccsHaveSame = false;
John McCalld935e9c2011-06-15 23:37:01 +00002811 break;
2812 case S_Retain:
2813 llvm_unreachable("bottom-up pointer in retain state!");
2814 }
Dan Gohman12130272011-08-12 00:26:31 +00002815 }
John McCalld935e9c2011-06-15 23:37:01 +00002816 // If the state at the other end of any of the successor edges
2817 // matches the current state, require all edges to match. This
2818 // guards against loops in the middle of a sequence.
2819 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohman12130272011-08-12 00:26:31 +00002820 S.ClearSequenceProgress();
Dan Gohman044437062011-12-12 18:13:53 +00002821 break;
John McCalld935e9c2011-06-15 23:37:01 +00002822 }
2823 }
2824}
2825
2826bool
Dan Gohman817a7c62012-03-22 18:24:56 +00002827ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
Dan Gohman5c70fad2012-03-23 17:47:54 +00002828 BasicBlock *BB,
Dan Gohman817a7c62012-03-22 18:24:56 +00002829 MapVector<Value *, RRInfo> &Retains,
2830 BBState &MyStates) {
2831 bool NestingDetected = false;
2832 InstructionClass Class = GetInstructionClass(Inst);
2833 const Value *Arg = 0;
2834
2835 switch (Class) {
2836 case IC_Release: {
2837 Arg = GetObjCArg(Inst);
2838
2839 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2840
2841 // If we see two releases in a row on the same pointer. If so, make
2842 // a note, and we'll cicle back to revisit it after we've
2843 // hopefully eliminated the second release, which may allow us to
2844 // eliminate the first release too.
2845 // Theoretically we could implement removal of nested retain+release
2846 // pairs by making PtrState hold a stack of states, but this is
2847 // simple and avoids adding overhead for the non-nested case.
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00002848 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease) {
2849 DEBUG(dbgs() << "ObjCARCOpt::VisitInstructionBottomUp: Found nested "
2850 "releases (i.e. a release pair)\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00002851 NestingDetected = true;
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00002852 }
Dan Gohman817a7c62012-03-22 18:24:56 +00002853
Dan Gohman817a7c62012-03-22 18:24:56 +00002854 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
Dan Gohman62079b42012-04-25 00:50:46 +00002855 S.ResetSequenceProgress(ReleaseMetadata ? S_MovableRelease : S_Release);
Dan Gohman817a7c62012-03-22 18:24:56 +00002856 S.RRI.ReleaseMetadata = ReleaseMetadata;
Dan Gohmandf476e52012-09-04 23:16:20 +00002857 S.RRI.KnownSafe = S.IsKnownIncremented();
Dan Gohman817a7c62012-03-22 18:24:56 +00002858 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2859 S.RRI.Calls.insert(Inst);
2860
Dan Gohmandf476e52012-09-04 23:16:20 +00002861 S.SetKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00002862 break;
2863 }
2864 case IC_RetainBlock:
2865 // An objc_retainBlock call with just a use may need to be kept,
2866 // because it may be copying a block from the stack to the heap.
2867 if (!IsRetainBlockOptimizable(Inst))
2868 break;
2869 // FALLTHROUGH
2870 case IC_Retain:
2871 case IC_RetainRV: {
2872 Arg = GetObjCArg(Inst);
2873
2874 PtrState &S = MyStates.getPtrBottomUpState(Arg);
Dan Gohman62079b42012-04-25 00:50:46 +00002875 S.SetKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00002876
2877 switch (S.GetSeq()) {
2878 case S_Stop:
2879 case S_Release:
2880 case S_MovableRelease:
2881 case S_Use:
2882 S.RRI.ReverseInsertPts.clear();
2883 // FALL THROUGH
2884 case S_CanRelease:
2885 // Don't do retain+release tracking for IC_RetainRV, because it's
2886 // better to let it remain as the first instruction after a call.
2887 if (Class != IC_RetainRV) {
2888 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2889 Retains[Inst] = S.RRI;
2890 }
2891 S.ClearSequenceProgress();
2892 break;
2893 case S_None:
2894 break;
2895 case S_Retain:
2896 llvm_unreachable("bottom-up pointer in retain state!");
2897 }
2898 return NestingDetected;
2899 }
2900 case IC_AutoreleasepoolPop:
2901 // Conservatively, clear MyStates for all known pointers.
2902 MyStates.clearBottomUpPointers();
2903 return NestingDetected;
2904 case IC_AutoreleasepoolPush:
2905 case IC_None:
2906 // These are irrelevant.
2907 return NestingDetected;
2908 default:
2909 break;
2910 }
2911
2912 // Consider any other possible effects of this instruction on each
2913 // pointer being tracked.
2914 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
2915 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
2916 const Value *Ptr = MI->first;
2917 if (Ptr == Arg)
2918 continue; // Handled above.
2919 PtrState &S = MI->second;
2920 Sequence Seq = S.GetSeq();
2921
2922 // Check for possible releases.
2923 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Dan Gohman62079b42012-04-25 00:50:46 +00002924 S.ClearRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00002925 switch (Seq) {
2926 case S_Use:
2927 S.SetSeq(S_CanRelease);
2928 continue;
2929 case S_CanRelease:
2930 case S_Release:
2931 case S_MovableRelease:
2932 case S_Stop:
2933 case S_None:
2934 break;
2935 case S_Retain:
2936 llvm_unreachable("bottom-up pointer in retain state!");
2937 }
2938 }
2939
2940 // Check for possible direct uses.
2941 switch (Seq) {
2942 case S_Release:
2943 case S_MovableRelease:
2944 if (CanUse(Inst, Ptr, PA, Class)) {
2945 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohman5c70fad2012-03-23 17:47:54 +00002946 // If this is an invoke instruction, we're scanning it as part of
2947 // one of its successor blocks, since we can't insert code after it
2948 // in its own block, and we don't want to split critical edges.
2949 if (isa<InvokeInst>(Inst))
2950 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2951 else
Francois Pichet4b9ab742012-03-24 01:36:37 +00002952 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohman817a7c62012-03-22 18:24:56 +00002953 S.SetSeq(S_Use);
2954 } else if (Seq == S_Release &&
2955 (Class == IC_User || Class == IC_CallOrUser)) {
2956 // Non-movable releases depend on any possible objc pointer use.
2957 S.SetSeq(S_Stop);
2958 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohman5c70fad2012-03-23 17:47:54 +00002959 // As above; handle invoke specially.
2960 if (isa<InvokeInst>(Inst))
2961 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2962 else
Francois Pichet4b9ab742012-03-24 01:36:37 +00002963 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohman817a7c62012-03-22 18:24:56 +00002964 }
2965 break;
2966 case S_Stop:
2967 if (CanUse(Inst, Ptr, PA, Class))
2968 S.SetSeq(S_Use);
2969 break;
2970 case S_CanRelease:
2971 case S_Use:
2972 case S_None:
2973 break;
2974 case S_Retain:
2975 llvm_unreachable("bottom-up pointer in retain state!");
2976 }
2977 }
2978
2979 return NestingDetected;
2980}
2981
2982bool
John McCalld935e9c2011-06-15 23:37:01 +00002983ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2984 DenseMap<const BasicBlock *, BBState> &BBStates,
2985 MapVector<Value *, RRInfo> &Retains) {
2986 bool NestingDetected = false;
2987 BBState &MyStates = BBStates[BB];
2988
2989 // Merge the states from each successor to compute the initial state
2990 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00002991 BBState::edge_iterator SI(MyStates.succ_begin()),
2992 SE(MyStates.succ_end());
2993 if (SI != SE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002994 const BasicBlock *Succ = *SI;
2995 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
2996 assert(I != BBStates.end());
2997 MyStates.InitFromSucc(I->second);
2998 ++SI;
2999 for (; SI != SE; ++SI) {
3000 Succ = *SI;
3001 I = BBStates.find(Succ);
3002 assert(I != BBStates.end());
3003 MyStates.MergeSucc(I->second);
3004 }
Dan Gohman0155f302012-02-17 18:59:53 +00003005 }
John McCalld935e9c2011-06-15 23:37:01 +00003006
3007 // Visit all the instructions, bottom-up.
3008 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
3009 Instruction *Inst = llvm::prior(I);
Dan Gohman5c70fad2012-03-23 17:47:54 +00003010
3011 // Invoke instructions are visited as part of their successors (below).
3012 if (isa<InvokeInst>(Inst))
3013 continue;
3014
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00003015 DEBUG(dbgs() << "ObjCARCOpt::VisitButtonUp: Visiting " << *Inst << "\n");
3016
Dan Gohman5c70fad2012-03-23 17:47:54 +00003017 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
3018 }
3019
Dan Gohmandae33492012-04-27 18:56:31 +00003020 // If there's a predecessor with an invoke, visit the invoke as if it were
3021 // part of this block, since we can't insert code after an invoke in its own
3022 // block, and we don't want to split critical edges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003023 for (BBState::edge_iterator PI(MyStates.pred_begin()),
3024 PE(MyStates.pred_end()); PI != PE; ++PI) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00003025 BasicBlock *Pred = *PI;
Dan Gohmandae33492012-04-27 18:56:31 +00003026 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
3027 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
Dan Gohman817a7c62012-03-22 18:24:56 +00003028 }
John McCalld935e9c2011-06-15 23:37:01 +00003029
Dan Gohman817a7c62012-03-22 18:24:56 +00003030 return NestingDetected;
3031}
John McCalld935e9c2011-06-15 23:37:01 +00003032
Dan Gohman817a7c62012-03-22 18:24:56 +00003033bool
3034ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
3035 DenseMap<Value *, RRInfo> &Releases,
3036 BBState &MyStates) {
3037 bool NestingDetected = false;
3038 InstructionClass Class = GetInstructionClass(Inst);
3039 const Value *Arg = 0;
John McCalld935e9c2011-06-15 23:37:01 +00003040
Dan Gohman817a7c62012-03-22 18:24:56 +00003041 switch (Class) {
3042 case IC_RetainBlock:
3043 // An objc_retainBlock call with just a use may need to be kept,
3044 // because it may be copying a block from the stack to the heap.
3045 if (!IsRetainBlockOptimizable(Inst))
3046 break;
3047 // FALLTHROUGH
3048 case IC_Retain:
3049 case IC_RetainRV: {
3050 Arg = GetObjCArg(Inst);
3051
3052 PtrState &S = MyStates.getPtrTopDownState(Arg);
3053
3054 // Don't do retain+release tracking for IC_RetainRV, because it's
3055 // better to let it remain as the first instruction after a call.
3056 if (Class != IC_RetainRV) {
3057 // If we see two retains in a row on the same pointer. If so, make
John McCalld935e9c2011-06-15 23:37:01 +00003058 // a note, and we'll cicle back to revisit it after we've
Dan Gohman817a7c62012-03-22 18:24:56 +00003059 // hopefully eliminated the second retain, which may allow us to
3060 // eliminate the first retain too.
John McCalld935e9c2011-06-15 23:37:01 +00003061 // Theoretically we could implement removal of nested retain+release
3062 // pairs by making PtrState hold a stack of states, but this is
3063 // simple and avoids adding overhead for the non-nested case.
Dan Gohman817a7c62012-03-22 18:24:56 +00003064 if (S.GetSeq() == S_Retain)
John McCalld935e9c2011-06-15 23:37:01 +00003065 NestingDetected = true;
3066
Dan Gohman62079b42012-04-25 00:50:46 +00003067 S.ResetSequenceProgress(S_Retain);
Dan Gohman817a7c62012-03-22 18:24:56 +00003068 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
Dan Gohmandf476e52012-09-04 23:16:20 +00003069 S.RRI.KnownSafe = S.IsKnownIncremented();
John McCalld935e9c2011-06-15 23:37:01 +00003070 S.RRI.Calls.insert(Inst);
John McCalld935e9c2011-06-15 23:37:01 +00003071 }
John McCalld935e9c2011-06-15 23:37:01 +00003072
Dan Gohmandf476e52012-09-04 23:16:20 +00003073 S.SetKnownPositiveRefCount();
Dan Gohmanf64ff8e2012-07-23 19:27:31 +00003074
3075 // A retain can be a potential use; procede to the generic checking
3076 // code below.
3077 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00003078 }
3079 case IC_Release: {
3080 Arg = GetObjCArg(Inst);
3081
3082 PtrState &S = MyStates.getPtrTopDownState(Arg);
Dan Gohmandf476e52012-09-04 23:16:20 +00003083 S.ClearRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00003084
3085 switch (S.GetSeq()) {
3086 case S_Retain:
3087 case S_CanRelease:
3088 S.RRI.ReverseInsertPts.clear();
3089 // FALL THROUGH
3090 case S_Use:
3091 S.RRI.ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
3092 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
3093 Releases[Inst] = S.RRI;
3094 S.ClearSequenceProgress();
3095 break;
3096 case S_None:
3097 break;
3098 case S_Stop:
3099 case S_Release:
3100 case S_MovableRelease:
3101 llvm_unreachable("top-down pointer in release state!");
3102 }
3103 break;
3104 }
3105 case IC_AutoreleasepoolPop:
3106 // Conservatively, clear MyStates for all known pointers.
3107 MyStates.clearTopDownPointers();
3108 return NestingDetected;
3109 case IC_AutoreleasepoolPush:
3110 case IC_None:
3111 // These are irrelevant.
3112 return NestingDetected;
3113 default:
3114 break;
3115 }
3116
3117 // Consider any other possible effects of this instruction on each
3118 // pointer being tracked.
3119 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
3120 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
3121 const Value *Ptr = MI->first;
3122 if (Ptr == Arg)
3123 continue; // Handled above.
3124 PtrState &S = MI->second;
3125 Sequence Seq = S.GetSeq();
3126
3127 // Check for possible releases.
3128 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Dan Gohman62079b42012-04-25 00:50:46 +00003129 S.ClearRefCount();
John McCalld935e9c2011-06-15 23:37:01 +00003130 switch (Seq) {
Dan Gohman817a7c62012-03-22 18:24:56 +00003131 case S_Retain:
3132 S.SetSeq(S_CanRelease);
3133 assert(S.RRI.ReverseInsertPts.empty());
3134 S.RRI.ReverseInsertPts.insert(Inst);
3135
3136 // One call can't cause a transition from S_Retain to S_CanRelease
3137 // and S_CanRelease to S_Use. If we've made the first transition,
3138 // we're done.
3139 continue;
John McCalld935e9c2011-06-15 23:37:01 +00003140 case S_Use:
Dan Gohman817a7c62012-03-22 18:24:56 +00003141 case S_CanRelease:
John McCalld935e9c2011-06-15 23:37:01 +00003142 case S_None:
3143 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00003144 case S_Stop:
3145 case S_Release:
3146 case S_MovableRelease:
3147 llvm_unreachable("top-down pointer in release state!");
John McCalld935e9c2011-06-15 23:37:01 +00003148 }
3149 }
Dan Gohman817a7c62012-03-22 18:24:56 +00003150
3151 // Check for possible direct uses.
3152 switch (Seq) {
3153 case S_CanRelease:
3154 if (CanUse(Inst, Ptr, PA, Class))
3155 S.SetSeq(S_Use);
3156 break;
3157 case S_Retain:
3158 case S_Use:
3159 case S_None:
3160 break;
3161 case S_Stop:
3162 case S_Release:
3163 case S_MovableRelease:
3164 llvm_unreachable("top-down pointer in release state!");
3165 }
John McCalld935e9c2011-06-15 23:37:01 +00003166 }
3167
3168 return NestingDetected;
3169}
3170
3171bool
3172ObjCARCOpt::VisitTopDown(BasicBlock *BB,
3173 DenseMap<const BasicBlock *, BBState> &BBStates,
3174 DenseMap<Value *, RRInfo> &Releases) {
3175 bool NestingDetected = false;
3176 BBState &MyStates = BBStates[BB];
3177
3178 // Merge the states from each predecessor to compute the initial state
3179 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00003180 BBState::edge_iterator PI(MyStates.pred_begin()),
3181 PE(MyStates.pred_end());
3182 if (PI != PE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003183 const BasicBlock *Pred = *PI;
3184 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
3185 assert(I != BBStates.end());
3186 MyStates.InitFromPred(I->second);
3187 ++PI;
3188 for (; PI != PE; ++PI) {
3189 Pred = *PI;
3190 I = BBStates.find(Pred);
3191 assert(I != BBStates.end());
3192 MyStates.MergePred(I->second);
3193 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003194 }
John McCalld935e9c2011-06-15 23:37:01 +00003195
3196 // Visit all the instructions, top-down.
3197 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3198 Instruction *Inst = I;
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00003199
3200 DEBUG(dbgs() << "ObjCARCOpt::VisitTopDown: Visiting " << *Inst << "\n");
3201
Dan Gohman817a7c62012-03-22 18:24:56 +00003202 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00003203 }
3204
3205 CheckForCFGHazards(BB, BBStates, MyStates);
3206 return NestingDetected;
3207}
3208
Dan Gohmana53a12c2011-12-12 19:42:25 +00003209static void
3210ComputePostOrders(Function &F,
3211 SmallVectorImpl<BasicBlock *> &PostOrder,
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003212 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
3213 unsigned NoObjCARCExceptionsMDKind,
3214 DenseMap<const BasicBlock *, BBState> &BBStates) {
Michael Gottesman97e3df02013-01-14 00:35:14 +00003215 /// The visited set, for doing DFS walks.
Dan Gohmana53a12c2011-12-12 19:42:25 +00003216 SmallPtrSet<BasicBlock *, 16> Visited;
3217
3218 // Do DFS, computing the PostOrder.
3219 SmallPtrSet<BasicBlock *, 16> OnStack;
3220 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003221
3222 // Functions always have exactly one entry block, and we don't have
3223 // any other block that we treat like an entry block.
Dan Gohmana53a12c2011-12-12 19:42:25 +00003224 BasicBlock *EntryBB = &F.getEntryBlock();
Dan Gohman41375a32012-05-08 23:39:44 +00003225 BBState &MyStates = BBStates[EntryBB];
3226 MyStates.SetAsEntry();
3227 TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
3228 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
Dan Gohmana53a12c2011-12-12 19:42:25 +00003229 Visited.insert(EntryBB);
3230 OnStack.insert(EntryBB);
3231 do {
3232 dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003233 BasicBlock *CurrBB = SuccStack.back().first;
3234 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
3235 succ_iterator SE(TI, false);
Dan Gohman41375a32012-05-08 23:39:44 +00003236
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003237 while (SuccStack.back().second != SE) {
3238 BasicBlock *SuccBB = *SuccStack.back().second++;
3239 if (Visited.insert(SuccBB)) {
Dan Gohman41375a32012-05-08 23:39:44 +00003240 TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
3241 SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003242 BBStates[CurrBB].addSucc(SuccBB);
Dan Gohman41375a32012-05-08 23:39:44 +00003243 BBState &SuccStates = BBStates[SuccBB];
3244 SuccStates.addPred(CurrBB);
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003245 OnStack.insert(SuccBB);
Dan Gohmana53a12c2011-12-12 19:42:25 +00003246 goto dfs_next_succ;
3247 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003248
3249 if (!OnStack.count(SuccBB)) {
3250 BBStates[CurrBB].addSucc(SuccBB);
3251 BBStates[SuccBB].addPred(CurrBB);
3252 }
Dan Gohmana53a12c2011-12-12 19:42:25 +00003253 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003254 OnStack.erase(CurrBB);
3255 PostOrder.push_back(CurrBB);
3256 SuccStack.pop_back();
Dan Gohmana53a12c2011-12-12 19:42:25 +00003257 } while (!SuccStack.empty());
3258
3259 Visited.clear();
3260
Dan Gohmana53a12c2011-12-12 19:42:25 +00003261 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003262 // Functions may have many exits, and there also blocks which we treat
3263 // as exits due to ignored edges.
3264 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
3265 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
3266 BasicBlock *ExitBB = I;
3267 BBState &MyStates = BBStates[ExitBB];
3268 if (!MyStates.isExit())
3269 continue;
3270
Dan Gohmandae33492012-04-27 18:56:31 +00003271 MyStates.SetAsExit();
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003272
3273 PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00003274 Visited.insert(ExitBB);
3275 while (!PredStack.empty()) {
3276 reverse_dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003277 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
3278 while (PredStack.back().second != PE) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00003279 BasicBlock *BB = *PredStack.back().second++;
Dan Gohmana53a12c2011-12-12 19:42:25 +00003280 if (Visited.insert(BB)) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003281 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00003282 goto reverse_dfs_next_succ;
3283 }
3284 }
3285 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
3286 }
3287 }
3288}
3289
Michael Gottesman97e3df02013-01-14 00:35:14 +00003290// Visit the function both top-down and bottom-up.
John McCalld935e9c2011-06-15 23:37:01 +00003291bool
3292ObjCARCOpt::Visit(Function &F,
3293 DenseMap<const BasicBlock *, BBState> &BBStates,
3294 MapVector<Value *, RRInfo> &Retains,
3295 DenseMap<Value *, RRInfo> &Releases) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00003296
3297 // Use reverse-postorder traversals, because we magically know that loops
3298 // will be well behaved, i.e. they won't repeatedly call retain on a single
3299 // pointer without doing a release. We can't use the ReversePostOrderTraversal
3300 // class here because we want the reverse-CFG postorder to consider each
3301 // function exit point, and we want to ignore selected cycle edges.
3302 SmallVector<BasicBlock *, 16> PostOrder;
3303 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003304 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
3305 NoObjCARCExceptionsMDKind,
3306 BBStates);
Dan Gohmana53a12c2011-12-12 19:42:25 +00003307
3308 // Use reverse-postorder on the reverse CFG for bottom-up.
John McCalld935e9c2011-06-15 23:37:01 +00003309 bool BottomUpNestingDetected = false;
Dan Gohmanc57b58c2011-08-18 21:27:42 +00003310 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
Dan Gohmana53a12c2011-12-12 19:42:25 +00003311 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
3312 I != E; ++I)
3313 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
John McCalld935e9c2011-06-15 23:37:01 +00003314
Dan Gohmana53a12c2011-12-12 19:42:25 +00003315 // Use reverse-postorder for top-down.
John McCalld935e9c2011-06-15 23:37:01 +00003316 bool TopDownNestingDetected = false;
Dan Gohmana53a12c2011-12-12 19:42:25 +00003317 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
3318 PostOrder.rbegin(), E = PostOrder.rend();
3319 I != E; ++I)
3320 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
John McCalld935e9c2011-06-15 23:37:01 +00003321
3322 return TopDownNestingDetected && BottomUpNestingDetected;
3323}
3324
Michael Gottesman97e3df02013-01-14 00:35:14 +00003325/// Move the calls in RetainsToMove and ReleasesToMove.
John McCalld935e9c2011-06-15 23:37:01 +00003326void ObjCARCOpt::MoveCalls(Value *Arg,
3327 RRInfo &RetainsToMove,
3328 RRInfo &ReleasesToMove,
3329 MapVector<Value *, RRInfo> &Retains,
3330 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman6320f522011-07-22 22:29:21 +00003331 SmallVectorImpl<Instruction *> &DeadInsts,
3332 Module *M) {
Chris Lattner229907c2011-07-18 04:54:35 +00003333 Type *ArgTy = Arg->getType();
Dan Gohman6320f522011-07-22 22:29:21 +00003334 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
John McCalld935e9c2011-06-15 23:37:01 +00003335
3336 // Insert the new retain and release calls.
3337 for (SmallPtrSet<Instruction *, 2>::const_iterator
3338 PI = ReleasesToMove.ReverseInsertPts.begin(),
3339 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
3340 Instruction *InsertPt = *PI;
3341 Value *MyArg = ArgTy == ParamTy ? Arg :
3342 new BitCastInst(Arg, ParamTy, "", InsertPt);
3343 CallInst *Call =
3344 CallInst::Create(RetainsToMove.IsRetainBlock ?
Dan Gohman6320f522011-07-22 22:29:21 +00003345 getRetainBlockCallee(M) : getRetainCallee(M),
John McCalld935e9c2011-06-15 23:37:01 +00003346 MyArg, "", InsertPt);
3347 Call->setDoesNotThrow();
Dan Gohman728db492012-01-13 00:39:07 +00003348 if (RetainsToMove.IsRetainBlock)
Dan Gohmana7107f92011-10-17 22:53:25 +00003349 Call->setMetadata(CopyOnEscapeMDKind,
3350 MDNode::get(M->getContext(), ArrayRef<Value *>()));
Dan Gohman728db492012-01-13 00:39:07 +00003351 else
John McCalld935e9c2011-06-15 23:37:01 +00003352 Call->setTailCall();
Michael Gottesmanc189a392013-01-09 19:23:24 +00003353
3354 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Inserting new Release: " << *Call
3355 << "\n"
3356 " At insertion point: " << *InsertPt
3357 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00003358 }
3359 for (SmallPtrSet<Instruction *, 2>::const_iterator
3360 PI = RetainsToMove.ReverseInsertPts.begin(),
3361 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00003362 Instruction *InsertPt = *PI;
3363 Value *MyArg = ArgTy == ParamTy ? Arg :
3364 new BitCastInst(Arg, ParamTy, "", InsertPt);
3365 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
3366 "", InsertPt);
3367 // Attach a clang.imprecise_release metadata tag, if appropriate.
3368 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
3369 Call->setMetadata(ImpreciseReleaseMDKind, M);
3370 Call->setDoesNotThrow();
3371 if (ReleasesToMove.IsTailCallRelease)
3372 Call->setTailCall();
Michael Gottesmanc189a392013-01-09 19:23:24 +00003373
3374 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Inserting new Retain: " << *Call
3375 << "\n"
3376 " At insertion point: " << *InsertPt
3377 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00003378 }
3379
3380 // Delete the original retain and release calls.
3381 for (SmallPtrSet<Instruction *, 2>::const_iterator
3382 AI = RetainsToMove.Calls.begin(),
3383 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
3384 Instruction *OrigRetain = *AI;
3385 Retains.blot(OrigRetain);
3386 DeadInsts.push_back(OrigRetain);
Michael Gottesmanc189a392013-01-09 19:23:24 +00003387 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Deleting retain: " << *OrigRetain <<
3388 "\n");
John McCalld935e9c2011-06-15 23:37:01 +00003389 }
3390 for (SmallPtrSet<Instruction *, 2>::const_iterator
3391 AI = ReleasesToMove.Calls.begin(),
3392 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
3393 Instruction *OrigRelease = *AI;
3394 Releases.erase(OrigRelease);
3395 DeadInsts.push_back(OrigRelease);
Michael Gottesmanc189a392013-01-09 19:23:24 +00003396 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Deleting release: " << *OrigRelease
3397 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00003398 }
3399}
3400
Michael Gottesman97e3df02013-01-14 00:35:14 +00003401/// Identify pairings between the retains and releases, and delete and/or move
3402/// them.
John McCalld935e9c2011-06-15 23:37:01 +00003403bool
3404ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
3405 &BBStates,
3406 MapVector<Value *, RRInfo> &Retains,
Dan Gohman6320f522011-07-22 22:29:21 +00003407 DenseMap<Value *, RRInfo> &Releases,
3408 Module *M) {
John McCalld935e9c2011-06-15 23:37:01 +00003409 bool AnyPairsCompletelyEliminated = false;
3410 RRInfo RetainsToMove;
3411 RRInfo ReleasesToMove;
3412 SmallVector<Instruction *, 4> NewRetains;
3413 SmallVector<Instruction *, 4> NewReleases;
3414 SmallVector<Instruction *, 8> DeadInsts;
3415
Dan Gohman670f9372012-04-13 18:57:48 +00003416 // Visit each retain.
John McCalld935e9c2011-06-15 23:37:01 +00003417 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
Dan Gohman2053a5d2011-09-29 22:25:23 +00003418 E = Retains.end(); I != E; ++I) {
3419 Value *V = I->first;
John McCalld935e9c2011-06-15 23:37:01 +00003420 if (!V) continue; // blotted
3421
3422 Instruction *Retain = cast<Instruction>(V);
Michael Gottesmanc189a392013-01-09 19:23:24 +00003423
3424 DEBUG(dbgs() << "ObjCARCOpt::PerformCodePlacement: Visiting: " << *Retain
3425 << "\n");
3426
John McCalld935e9c2011-06-15 23:37:01 +00003427 Value *Arg = GetObjCArg(Retain);
3428
Dan Gohman728db492012-01-13 00:39:07 +00003429 // If the object being released is in static or stack storage, we know it's
John McCalld935e9c2011-06-15 23:37:01 +00003430 // not being managed by ObjC reference counting, so we can delete pairs
3431 // regardless of what possible decrements or uses lie between them.
Dan Gohman728db492012-01-13 00:39:07 +00003432 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
Dan Gohman41375a32012-05-08 23:39:44 +00003433
Dan Gohman56e1cef2011-08-22 17:29:11 +00003434 // A constant pointer can't be pointing to an object on the heap. It may
3435 // be reference-counted, but it won't be deleted.
3436 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
3437 if (const GlobalVariable *GV =
3438 dyn_cast<GlobalVariable>(
3439 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
3440 if (GV->isConstant())
3441 KnownSafe = true;
3442
John McCalld935e9c2011-06-15 23:37:01 +00003443 // If a pair happens in a region where it is known that the reference count
3444 // is already incremented, we can similarly ignore possible decrements.
Dan Gohmanb3894012011-08-19 00:26:36 +00003445 bool KnownSafeTD = true, KnownSafeBU = true;
John McCalld935e9c2011-06-15 23:37:01 +00003446
3447 // Connect the dots between the top-down-collected RetainsToMove and
3448 // bottom-up-collected ReleasesToMove to form sets of related calls.
3449 // This is an iterative process so that we connect multiple releases
3450 // to multiple retains if needed.
3451 unsigned OldDelta = 0;
3452 unsigned NewDelta = 0;
3453 unsigned OldCount = 0;
3454 unsigned NewCount = 0;
3455 bool FirstRelease = true;
3456 bool FirstRetain = true;
3457 NewRetains.push_back(Retain);
3458 for (;;) {
3459 for (SmallVectorImpl<Instruction *>::const_iterator
3460 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
3461 Instruction *NewRetain = *NI;
3462 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
3463 assert(It != Retains.end());
3464 const RRInfo &NewRetainRRI = It->second;
Dan Gohmanb3894012011-08-19 00:26:36 +00003465 KnownSafeTD &= NewRetainRRI.KnownSafe;
John McCalld935e9c2011-06-15 23:37:01 +00003466 for (SmallPtrSet<Instruction *, 2>::const_iterator
3467 LI = NewRetainRRI.Calls.begin(),
3468 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
3469 Instruction *NewRetainRelease = *LI;
3470 DenseMap<Value *, RRInfo>::const_iterator Jt =
3471 Releases.find(NewRetainRelease);
3472 if (Jt == Releases.end())
3473 goto next_retain;
3474 const RRInfo &NewRetainReleaseRRI = Jt->second;
3475 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
3476 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
3477 OldDelta -=
3478 BBStates[NewRetainRelease->getParent()].GetAllPathCount();
3479
3480 // Merge the ReleaseMetadata and IsTailCallRelease values.
3481 if (FirstRelease) {
3482 ReleasesToMove.ReleaseMetadata =
3483 NewRetainReleaseRRI.ReleaseMetadata;
3484 ReleasesToMove.IsTailCallRelease =
3485 NewRetainReleaseRRI.IsTailCallRelease;
3486 FirstRelease = false;
3487 } else {
3488 if (ReleasesToMove.ReleaseMetadata !=
3489 NewRetainReleaseRRI.ReleaseMetadata)
3490 ReleasesToMove.ReleaseMetadata = 0;
3491 if (ReleasesToMove.IsTailCallRelease !=
3492 NewRetainReleaseRRI.IsTailCallRelease)
3493 ReleasesToMove.IsTailCallRelease = false;
3494 }
3495
3496 // Collect the optimal insertion points.
3497 if (!KnownSafe)
3498 for (SmallPtrSet<Instruction *, 2>::const_iterator
3499 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
3500 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
3501 RI != RE; ++RI) {
3502 Instruction *RIP = *RI;
3503 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
3504 NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
3505 }
3506 NewReleases.push_back(NewRetainRelease);
3507 }
3508 }
3509 }
3510 NewRetains.clear();
3511 if (NewReleases.empty()) break;
3512
3513 // Back the other way.
3514 for (SmallVectorImpl<Instruction *>::const_iterator
3515 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
3516 Instruction *NewRelease = *NI;
3517 DenseMap<Value *, RRInfo>::const_iterator It =
3518 Releases.find(NewRelease);
3519 assert(It != Releases.end());
3520 const RRInfo &NewReleaseRRI = It->second;
Dan Gohmanb3894012011-08-19 00:26:36 +00003521 KnownSafeBU &= NewReleaseRRI.KnownSafe;
John McCalld935e9c2011-06-15 23:37:01 +00003522 for (SmallPtrSet<Instruction *, 2>::const_iterator
3523 LI = NewReleaseRRI.Calls.begin(),
3524 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
3525 Instruction *NewReleaseRetain = *LI;
3526 MapVector<Value *, RRInfo>::const_iterator Jt =
3527 Retains.find(NewReleaseRetain);
3528 if (Jt == Retains.end())
3529 goto next_retain;
3530 const RRInfo &NewReleaseRetainRRI = Jt->second;
3531 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
3532 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
3533 unsigned PathCount =
3534 BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
3535 OldDelta += PathCount;
3536 OldCount += PathCount;
3537
3538 // Merge the IsRetainBlock values.
3539 if (FirstRetain) {
3540 RetainsToMove.IsRetainBlock = NewReleaseRetainRRI.IsRetainBlock;
3541 FirstRetain = false;
3542 } else if (ReleasesToMove.IsRetainBlock !=
3543 NewReleaseRetainRRI.IsRetainBlock)
3544 // It's not possible to merge the sequences if one uses
3545 // objc_retain and the other uses objc_retainBlock.
3546 goto next_retain;
3547
3548 // Collect the optimal insertion points.
3549 if (!KnownSafe)
3550 for (SmallPtrSet<Instruction *, 2>::const_iterator
3551 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
3552 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
3553 RI != RE; ++RI) {
3554 Instruction *RIP = *RI;
3555 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
3556 PathCount = BBStates[RIP->getParent()].GetAllPathCount();
3557 NewDelta += PathCount;
3558 NewCount += PathCount;
3559 }
3560 }
3561 NewRetains.push_back(NewReleaseRetain);
3562 }
3563 }
3564 }
3565 NewReleases.clear();
3566 if (NewRetains.empty()) break;
3567 }
3568
Dan Gohmanb3894012011-08-19 00:26:36 +00003569 // If the pointer is known incremented or nested, we can safely delete the
3570 // pair regardless of what's between them.
3571 if (KnownSafeTD || KnownSafeBU) {
John McCalld935e9c2011-06-15 23:37:01 +00003572 RetainsToMove.ReverseInsertPts.clear();
3573 ReleasesToMove.ReverseInsertPts.clear();
3574 NewCount = 0;
Dan Gohman12130272011-08-12 00:26:31 +00003575 } else {
3576 // Determine whether the new insertion points we computed preserve the
3577 // balance of retain and release calls through the program.
3578 // TODO: If the fully aggressive solution isn't valid, try to find a
3579 // less aggressive solution which is.
3580 if (NewDelta != 0)
3581 goto next_retain;
John McCalld935e9c2011-06-15 23:37:01 +00003582 }
3583
3584 // Determine whether the original call points are balanced in the retain and
3585 // release calls through the program. If not, conservatively don't touch
3586 // them.
3587 // TODO: It's theoretically possible to do code motion in this case, as
3588 // long as the existing imbalances are maintained.
3589 if (OldDelta != 0)
3590 goto next_retain;
3591
John McCalld935e9c2011-06-15 23:37:01 +00003592 // Ok, everything checks out and we're all set. Let's move some code!
3593 Changed = true;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003594 assert(OldCount != 0 && "Unreachable code?");
3595 AnyPairsCompletelyEliminated = NewCount == 0;
John McCalld935e9c2011-06-15 23:37:01 +00003596 NumRRs += OldCount - NewCount;
Dan Gohman6320f522011-07-22 22:29:21 +00003597 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
3598 Retains, Releases, DeadInsts, M);
John McCalld935e9c2011-06-15 23:37:01 +00003599
3600 next_retain:
3601 NewReleases.clear();
3602 NewRetains.clear();
3603 RetainsToMove.clear();
3604 ReleasesToMove.clear();
3605 }
3606
3607 // Now that we're done moving everything, we can delete the newly dead
3608 // instructions, as we no longer need them as insert points.
3609 while (!DeadInsts.empty())
3610 EraseInstruction(DeadInsts.pop_back_val());
3611
3612 return AnyPairsCompletelyEliminated;
3613}
3614
Michael Gottesman97e3df02013-01-14 00:35:14 +00003615/// Weak pointer optimizations.
John McCalld935e9c2011-06-15 23:37:01 +00003616void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
3617 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
3618 // itself because it uses AliasAnalysis and we need to do provenance
3619 // queries instead.
3620 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3621 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +00003622
Michael Gottesman9f848ae2013-01-04 21:29:57 +00003623 DEBUG(dbgs() << "ObjCARCOpt::OptimizeWeakCalls: Visiting: " << *Inst <<
Michael Gottesman3f146e22013-01-01 16:05:48 +00003624 "\n");
3625
John McCalld935e9c2011-06-15 23:37:01 +00003626 InstructionClass Class = GetBasicInstructionClass(Inst);
3627 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
3628 continue;
3629
3630 // Delete objc_loadWeak calls with no users.
3631 if (Class == IC_LoadWeak && Inst->use_empty()) {
3632 Inst->eraseFromParent();
3633 continue;
3634 }
3635
3636 // TODO: For now, just look for an earlier available version of this value
3637 // within the same block. Theoretically, we could do memdep-style non-local
3638 // analysis too, but that would want caching. A better approach would be to
3639 // use the technique that EarlyCSE uses.
3640 inst_iterator Current = llvm::prior(I);
3641 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
3642 for (BasicBlock::iterator B = CurrentBB->begin(),
3643 J = Current.getInstructionIterator();
3644 J != B; --J) {
3645 Instruction *EarlierInst = &*llvm::prior(J);
3646 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
3647 switch (EarlierClass) {
3648 case IC_LoadWeak:
3649 case IC_LoadWeakRetained: {
3650 // If this is loading from the same pointer, replace this load's value
3651 // with that one.
3652 CallInst *Call = cast<CallInst>(Inst);
3653 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3654 Value *Arg = Call->getArgOperand(0);
3655 Value *EarlierArg = EarlierCall->getArgOperand(0);
3656 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3657 case AliasAnalysis::MustAlias:
3658 Changed = true;
3659 // If the load has a builtin retain, insert a plain retain for it.
3660 if (Class == IC_LoadWeakRetained) {
3661 CallInst *CI =
3662 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3663 "", Call);
3664 CI->setTailCall();
3665 }
3666 // Zap the fully redundant load.
3667 Call->replaceAllUsesWith(EarlierCall);
3668 Call->eraseFromParent();
3669 goto clobbered;
3670 case AliasAnalysis::MayAlias:
3671 case AliasAnalysis::PartialAlias:
3672 goto clobbered;
3673 case AliasAnalysis::NoAlias:
3674 break;
3675 }
3676 break;
3677 }
3678 case IC_StoreWeak:
3679 case IC_InitWeak: {
3680 // If this is storing to the same pointer and has the same size etc.
3681 // replace this load's value with the stored value.
3682 CallInst *Call = cast<CallInst>(Inst);
3683 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3684 Value *Arg = Call->getArgOperand(0);
3685 Value *EarlierArg = EarlierCall->getArgOperand(0);
3686 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3687 case AliasAnalysis::MustAlias:
3688 Changed = true;
3689 // If the load has a builtin retain, insert a plain retain for it.
3690 if (Class == IC_LoadWeakRetained) {
3691 CallInst *CI =
3692 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3693 "", Call);
3694 CI->setTailCall();
3695 }
3696 // Zap the fully redundant load.
3697 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
3698 Call->eraseFromParent();
3699 goto clobbered;
3700 case AliasAnalysis::MayAlias:
3701 case AliasAnalysis::PartialAlias:
3702 goto clobbered;
3703 case AliasAnalysis::NoAlias:
3704 break;
3705 }
3706 break;
3707 }
3708 case IC_MoveWeak:
3709 case IC_CopyWeak:
3710 // TOOD: Grab the copied value.
3711 goto clobbered;
3712 case IC_AutoreleasepoolPush:
3713 case IC_None:
3714 case IC_User:
3715 // Weak pointers are only modified through the weak entry points
3716 // (and arbitrary calls, which could call the weak entry points).
3717 break;
3718 default:
3719 // Anything else could modify the weak pointer.
3720 goto clobbered;
3721 }
3722 }
3723 clobbered:;
3724 }
3725
3726 // Then, for each destroyWeak with an alloca operand, check to see if
3727 // the alloca and all its users can be zapped.
3728 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3729 Instruction *Inst = &*I++;
3730 InstructionClass Class = GetBasicInstructionClass(Inst);
3731 if (Class != IC_DestroyWeak)
3732 continue;
3733
3734 CallInst *Call = cast<CallInst>(Inst);
3735 Value *Arg = Call->getArgOperand(0);
3736 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
3737 for (Value::use_iterator UI = Alloca->use_begin(),
3738 UE = Alloca->use_end(); UI != UE; ++UI) {
Dan Gohmandae33492012-04-27 18:56:31 +00003739 const Instruction *UserInst = cast<Instruction>(*UI);
John McCalld935e9c2011-06-15 23:37:01 +00003740 switch (GetBasicInstructionClass(UserInst)) {
3741 case IC_InitWeak:
3742 case IC_StoreWeak:
3743 case IC_DestroyWeak:
3744 continue;
3745 default:
3746 goto done;
3747 }
3748 }
3749 Changed = true;
3750 for (Value::use_iterator UI = Alloca->use_begin(),
3751 UE = Alloca->use_end(); UI != UE; ) {
3752 CallInst *UserInst = cast<CallInst>(*UI++);
Dan Gohman14862c32012-05-18 22:17:29 +00003753 switch (GetBasicInstructionClass(UserInst)) {
3754 case IC_InitWeak:
3755 case IC_StoreWeak:
3756 // These functions return their second argument.
3757 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
3758 break;
3759 case IC_DestroyWeak:
3760 // No return value.
3761 break;
3762 default:
Dan Gohman9c97eea02012-05-21 17:41:28 +00003763 llvm_unreachable("alloca really is used!");
Dan Gohman14862c32012-05-18 22:17:29 +00003764 }
John McCalld935e9c2011-06-15 23:37:01 +00003765 UserInst->eraseFromParent();
3766 }
3767 Alloca->eraseFromParent();
3768 done:;
3769 }
3770 }
Michael Gottesman10426b52013-01-07 21:26:07 +00003771
Michael Gottesman9f848ae2013-01-04 21:29:57 +00003772 DEBUG(dbgs() << "ObjCARCOpt::OptimizeWeakCalls: Finished List.\n\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00003773
John McCalld935e9c2011-06-15 23:37:01 +00003774}
3775
Michael Gottesman97e3df02013-01-14 00:35:14 +00003776/// Identify program paths which execute sequences of retains and releases which
3777/// can be eliminated.
John McCalld935e9c2011-06-15 23:37:01 +00003778bool ObjCARCOpt::OptimizeSequences(Function &F) {
3779 /// Releases, Retains - These are used to store the results of the main flow
3780 /// analysis. These use Value* as the key instead of Instruction* so that the
3781 /// map stays valid when we get around to rewriting code and calls get
3782 /// replaced by arguments.
3783 DenseMap<Value *, RRInfo> Releases;
3784 MapVector<Value *, RRInfo> Retains;
3785
Michael Gottesman97e3df02013-01-14 00:35:14 +00003786 /// This is used during the traversal of the function to track the
John McCalld935e9c2011-06-15 23:37:01 +00003787 /// states for each identified object at each block.
3788 DenseMap<const BasicBlock *, BBState> BBStates;
3789
3790 // Analyze the CFG of the function, and all instructions.
3791 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
3792
3793 // Transform.
Dan Gohman6320f522011-07-22 22:29:21 +00003794 return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) &&
3795 NestingDetected;
John McCalld935e9c2011-06-15 23:37:01 +00003796}
3797
Michael Gottesman97e3df02013-01-14 00:35:14 +00003798/// Look for this pattern:
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00003799/// \code
John McCalld935e9c2011-06-15 23:37:01 +00003800/// %call = call i8* @something(...)
3801/// %2 = call i8* @objc_retain(i8* %call)
3802/// %3 = call i8* @objc_autorelease(i8* %2)
3803/// ret i8* %3
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00003804/// \endcode
John McCalld935e9c2011-06-15 23:37:01 +00003805/// And delete the retain and autorelease.
3806///
3807/// Otherwise if it's just this:
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00003808/// \code
John McCalld935e9c2011-06-15 23:37:01 +00003809/// %3 = call i8* @objc_autorelease(i8* %2)
3810/// ret i8* %3
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00003811/// \endcode
John McCalld935e9c2011-06-15 23:37:01 +00003812/// convert the autorelease to autoreleaseRV.
3813void ObjCARCOpt::OptimizeReturns(Function &F) {
3814 if (!F.getReturnType()->isPointerTy())
3815 return;
3816
3817 SmallPtrSet<Instruction *, 4> DependingInstructions;
3818 SmallPtrSet<const BasicBlock *, 4> Visited;
3819 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3820 BasicBlock *BB = FI;
3821 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
Michael Gottesman3f146e22013-01-01 16:05:48 +00003822
Michael Gottesman9f848ae2013-01-04 21:29:57 +00003823 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Visiting: " << *Ret << "\n");
Michael Gottesman3f146e22013-01-01 16:05:48 +00003824
John McCalld935e9c2011-06-15 23:37:01 +00003825 if (!Ret) continue;
3826
3827 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
3828 FindDependencies(NeedsPositiveRetainCount, Arg,
3829 BB, Ret, DependingInstructions, Visited, PA);
3830 if (DependingInstructions.size() != 1)
3831 goto next_block;
3832
3833 {
3834 CallInst *Autorelease =
3835 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3836 if (!Autorelease)
3837 goto next_block;
Dan Gohman41375a32012-05-08 23:39:44 +00003838 InstructionClass AutoreleaseClass = GetBasicInstructionClass(Autorelease);
John McCalld935e9c2011-06-15 23:37:01 +00003839 if (!IsAutorelease(AutoreleaseClass))
3840 goto next_block;
3841 if (GetObjCArg(Autorelease) != Arg)
3842 goto next_block;
3843
3844 DependingInstructions.clear();
3845 Visited.clear();
3846
3847 // Check that there is nothing that can affect the reference
3848 // count between the autorelease and the retain.
3849 FindDependencies(CanChangeRetainCount, Arg,
3850 BB, Autorelease, DependingInstructions, Visited, PA);
3851 if (DependingInstructions.size() != 1)
3852 goto next_block;
3853
3854 {
3855 CallInst *Retain =
3856 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3857
3858 // Check that we found a retain with the same argument.
3859 if (!Retain ||
3860 !IsRetain(GetBasicInstructionClass(Retain)) ||
3861 GetObjCArg(Retain) != Arg)
3862 goto next_block;
3863
3864 DependingInstructions.clear();
3865 Visited.clear();
3866
3867 // Convert the autorelease to an autoreleaseRV, since it's
3868 // returning the value.
3869 if (AutoreleaseClass == IC_Autorelease) {
Michael Gottesmana6cb0182013-01-10 02:03:50 +00003870 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Converting autorelease "
3871 "=> autoreleaseRV since it's returning a value.\n"
3872 " In: " << *Autorelease
3873 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00003874 Autorelease->setCalledFunction(getAutoreleaseRVCallee(F.getParent()));
Michael Gottesmana6cb0182013-01-10 02:03:50 +00003875 DEBUG(dbgs() << " Out: " << *Autorelease
3876 << "\n");
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00003877 Autorelease->setTailCall(); // Always tail call autoreleaseRV.
John McCalld935e9c2011-06-15 23:37:01 +00003878 AutoreleaseClass = IC_AutoreleaseRV;
3879 }
3880
3881 // Check that there is nothing that can affect the reference
3882 // count between the retain and the call.
Dan Gohman4ac148d2011-09-29 22:27:34 +00003883 // Note that Retain need not be in BB.
3884 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
John McCalld935e9c2011-06-15 23:37:01 +00003885 DependingInstructions, Visited, PA);
3886 if (DependingInstructions.size() != 1)
3887 goto next_block;
3888
3889 {
3890 CallInst *Call =
3891 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3892
3893 // Check that the pointer is the return value of the call.
3894 if (!Call || Arg != Call)
3895 goto next_block;
3896
3897 // Check that the call is a regular call.
3898 InstructionClass Class = GetBasicInstructionClass(Call);
3899 if (Class != IC_CallOrUser && Class != IC_Call)
3900 goto next_block;
3901
3902 // If so, we can zap the retain and autorelease.
3903 Changed = true;
3904 ++NumRets;
Michael Gottesmand61a3b22013-01-07 00:04:56 +00003905 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Erasing: " << *Retain
3906 << "\n Erasing: "
3907 << *Autorelease << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00003908 EraseInstruction(Retain);
3909 EraseInstruction(Autorelease);
3910 }
3911 }
3912 }
3913
3914 next_block:
3915 DependingInstructions.clear();
3916 Visited.clear();
3917 }
Michael Gottesman10426b52013-01-07 21:26:07 +00003918
Michael Gottesman9f848ae2013-01-04 21:29:57 +00003919 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Finished List.\n\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00003920
John McCalld935e9c2011-06-15 23:37:01 +00003921}
3922
3923bool ObjCARCOpt::doInitialization(Module &M) {
3924 if (!EnableARCOpts)
3925 return false;
3926
Dan Gohman670f9372012-04-13 18:57:48 +00003927 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanceaac7c2011-06-20 23:20:43 +00003928 Run = ModuleHasARC(M);
3929 if (!Run)
3930 return false;
3931
John McCalld935e9c2011-06-15 23:37:01 +00003932 // Identify the imprecise release metadata kind.
3933 ImpreciseReleaseMDKind =
3934 M.getContext().getMDKindID("clang.imprecise_release");
Dan Gohmana7107f92011-10-17 22:53:25 +00003935 CopyOnEscapeMDKind =
3936 M.getContext().getMDKindID("clang.arc.copy_on_escape");
Dan Gohman0155f302012-02-17 18:59:53 +00003937 NoObjCARCExceptionsMDKind =
3938 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
John McCalld935e9c2011-06-15 23:37:01 +00003939
John McCalld935e9c2011-06-15 23:37:01 +00003940 // Intuitively, objc_retain and others are nocapture, however in practice
3941 // they are not, because they return their argument value. And objc_release
Dan Gohmandae33492012-04-27 18:56:31 +00003942 // calls finalizers which can have arbitrary side effects.
John McCalld935e9c2011-06-15 23:37:01 +00003943
3944 // These are initialized lazily.
3945 RetainRVCallee = 0;
3946 AutoreleaseRVCallee = 0;
3947 ReleaseCallee = 0;
3948 RetainCallee = 0;
Dan Gohman6320f522011-07-22 22:29:21 +00003949 RetainBlockCallee = 0;
John McCalld935e9c2011-06-15 23:37:01 +00003950 AutoreleaseCallee = 0;
3951
3952 return false;
3953}
3954
3955bool ObjCARCOpt::runOnFunction(Function &F) {
3956 if (!EnableARCOpts)
3957 return false;
3958
Dan Gohmanceaac7c2011-06-20 23:20:43 +00003959 // If nothing in the Module uses ARC, don't do anything.
3960 if (!Run)
3961 return false;
3962
John McCalld935e9c2011-06-15 23:37:01 +00003963 Changed = false;
3964
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00003965 DEBUG(dbgs() << "ObjCARCOpt: Visiting Function: " << F.getName() << "\n");
3966
John McCalld935e9c2011-06-15 23:37:01 +00003967 PA.setAA(&getAnalysis<AliasAnalysis>());
3968
3969 // This pass performs several distinct transformations. As a compile-time aid
3970 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3971 // library functions aren't declared.
3972
3973 // Preliminary optimizations. This also computs UsedInThisFunction.
3974 OptimizeIndividualCalls(F);
3975
3976 // Optimizations for weak pointers.
3977 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3978 (1 << IC_LoadWeakRetained) |
3979 (1 << IC_StoreWeak) |
3980 (1 << IC_InitWeak) |
3981 (1 << IC_CopyWeak) |
3982 (1 << IC_MoveWeak) |
3983 (1 << IC_DestroyWeak)))
3984 OptimizeWeakCalls(F);
3985
3986 // Optimizations for retain+release pairs.
3987 if (UsedInThisFunction & ((1 << IC_Retain) |
3988 (1 << IC_RetainRV) |
3989 (1 << IC_RetainBlock)))
3990 if (UsedInThisFunction & (1 << IC_Release))
3991 // Run OptimizeSequences until it either stops making changes or
3992 // no retain+release pair nesting is detected.
3993 while (OptimizeSequences(F)) {}
3994
3995 // Optimizations if objc_autorelease is used.
Dan Gohman41375a32012-05-08 23:39:44 +00003996 if (UsedInThisFunction & ((1 << IC_Autorelease) |
3997 (1 << IC_AutoreleaseRV)))
John McCalld935e9c2011-06-15 23:37:01 +00003998 OptimizeReturns(F);
3999
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00004000 DEBUG(dbgs() << "\n");
4001
John McCalld935e9c2011-06-15 23:37:01 +00004002 return Changed;
4003}
4004
4005void ObjCARCOpt::releaseMemory() {
4006 PA.clear();
4007}
4008
Michael Gottesman97e3df02013-01-14 00:35:14 +00004009/// @}
4010///
4011/// \defgroup ARCContract ARC Contraction.
4012/// @{
John McCalld935e9c2011-06-15 23:37:01 +00004013
4014// TODO: ObjCARCContract could insert PHI nodes when uses aren't
4015// dominated by single calls.
4016
John McCalld935e9c2011-06-15 23:37:01 +00004017#include "llvm/Analysis/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +00004018#include "llvm/IR/InlineAsm.h"
4019#include "llvm/IR/Operator.h"
John McCalld935e9c2011-06-15 23:37:01 +00004020
4021STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed");
4022
4023namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +00004024 /// \brief Late ARC optimizations
4025 ///
4026 /// These change the IR in a way that makes it difficult to be analyzed by
4027 /// ObjCARCOpt, so it's run late.
John McCalld935e9c2011-06-15 23:37:01 +00004028 class ObjCARCContract : public FunctionPass {
4029 bool Changed;
4030 AliasAnalysis *AA;
4031 DominatorTree *DT;
4032 ProvenanceAnalysis PA;
4033
Michael Gottesman97e3df02013-01-14 00:35:14 +00004034 /// A flag indicating whether this optimization pass should run.
Dan Gohmanceaac7c2011-06-20 23:20:43 +00004035 bool Run;
4036
Michael Gottesman97e3df02013-01-14 00:35:14 +00004037 /// Declarations for ObjC runtime functions, for use in creating calls to
4038 /// them. These are initialized lazily to avoid cluttering up the Module
4039 /// with unused declarations.
John McCalld935e9c2011-06-15 23:37:01 +00004040
Michael Gottesman97e3df02013-01-14 00:35:14 +00004041 /// Declaration for objc_storeStrong().
4042 Constant *StoreStrongCallee;
4043 /// Declaration for objc_retainAutorelease().
4044 Constant *RetainAutoreleaseCallee;
4045 /// Declaration for objc_retainAutoreleaseReturnValue().
4046 Constant *RetainAutoreleaseRVCallee;
4047
4048 /// The inline asm string to insert between calls and RetainRV calls to make
4049 /// the optimization work on targets which need it.
John McCalld935e9c2011-06-15 23:37:01 +00004050 const MDString *RetainRVMarker;
4051
Michael Gottesman97e3df02013-01-14 00:35:14 +00004052 /// The set of inserted objc_storeStrong calls. If at the end of walking the
4053 /// function we have found no alloca instructions, these calls can be marked
4054 /// "tail".
Dan Gohman41375a32012-05-08 23:39:44 +00004055 SmallPtrSet<CallInst *, 8> StoreStrongCalls;
Dan Gohman8ee108b2012-01-19 19:14:36 +00004056
John McCalld935e9c2011-06-15 23:37:01 +00004057 Constant *getStoreStrongCallee(Module *M);
4058 Constant *getRetainAutoreleaseCallee(Module *M);
4059 Constant *getRetainAutoreleaseRVCallee(Module *M);
4060
4061 bool ContractAutorelease(Function &F, Instruction *Autorelease,
4062 InstructionClass Class,
4063 SmallPtrSet<Instruction *, 4>
4064 &DependingInstructions,
4065 SmallPtrSet<const BasicBlock *, 4>
4066 &Visited);
4067
4068 void ContractRelease(Instruction *Release,
4069 inst_iterator &Iter);
4070
4071 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
4072 virtual bool doInitialization(Module &M);
4073 virtual bool runOnFunction(Function &F);
4074
4075 public:
4076 static char ID;
4077 ObjCARCContract() : FunctionPass(ID) {
4078 initializeObjCARCContractPass(*PassRegistry::getPassRegistry());
4079 }
4080 };
4081}
4082
4083char ObjCARCContract::ID = 0;
4084INITIALIZE_PASS_BEGIN(ObjCARCContract,
4085 "objc-arc-contract", "ObjC ARC contraction", false, false)
4086INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
4087INITIALIZE_PASS_DEPENDENCY(DominatorTree)
4088INITIALIZE_PASS_END(ObjCARCContract,
4089 "objc-arc-contract", "ObjC ARC contraction", false, false)
4090
4091Pass *llvm::createObjCARCContractPass() {
4092 return new ObjCARCContract();
4093}
4094
4095void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const {
4096 AU.addRequired<AliasAnalysis>();
4097 AU.addRequired<DominatorTree>();
4098 AU.setPreservesCFG();
4099}
4100
4101Constant *ObjCARCContract::getStoreStrongCallee(Module *M) {
4102 if (!StoreStrongCallee) {
4103 LLVMContext &C = M->getContext();
Jay Foadb804a2b2011-07-12 14:06:48 +00004104 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
4105 Type *I8XX = PointerType::getUnqual(I8X);
Dan Gohman41375a32012-05-08 23:39:44 +00004106 Type *Params[] = { I8XX, I8X };
John McCalld935e9c2011-06-15 23:37:01 +00004107
Bill Wendling09175b32013-01-22 21:15:51 +00004108 AttributeSet Attr = AttributeSet()
4109 .addAttribute(M->getContext(), AttributeSet::FunctionIndex,
4110 Attribute::NoUnwind)
4111 .addAttribute(M->getContext(), 1, Attribute::NoCapture);
John McCalld935e9c2011-06-15 23:37:01 +00004112
4113 StoreStrongCallee =
4114 M->getOrInsertFunction(
4115 "objc_storeStrong",
4116 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
Bill Wendling09175b32013-01-22 21:15:51 +00004117 Attr);
John McCalld935e9c2011-06-15 23:37:01 +00004118 }
4119 return StoreStrongCallee;
4120}
4121
4122Constant *ObjCARCContract::getRetainAutoreleaseCallee(Module *M) {
4123 if (!RetainAutoreleaseCallee) {
4124 LLVMContext &C = M->getContext();
Jay Foadb804a2b2011-07-12 14:06:48 +00004125 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman41375a32012-05-08 23:39:44 +00004126 Type *Params[] = { I8X };
4127 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004128 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00004129 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
4130 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00004131 RetainAutoreleaseCallee =
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004132 M->getOrInsertFunction("objc_retainAutorelease", FTy, Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00004133 }
4134 return RetainAutoreleaseCallee;
4135}
4136
4137Constant *ObjCARCContract::getRetainAutoreleaseRVCallee(Module *M) {
4138 if (!RetainAutoreleaseRVCallee) {
4139 LLVMContext &C = M->getContext();
Jay Foadb804a2b2011-07-12 14:06:48 +00004140 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman41375a32012-05-08 23:39:44 +00004141 Type *Params[] = { I8X };
4142 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004143 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00004144 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
4145 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00004146 RetainAutoreleaseRVCallee =
4147 M->getOrInsertFunction("objc_retainAutoreleaseReturnValue", FTy,
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004148 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00004149 }
4150 return RetainAutoreleaseRVCallee;
4151}
4152
Michael Gottesman97e3df02013-01-14 00:35:14 +00004153/// Merge an autorelease with a retain into a fused call.
John McCalld935e9c2011-06-15 23:37:01 +00004154bool
4155ObjCARCContract::ContractAutorelease(Function &F, Instruction *Autorelease,
4156 InstructionClass Class,
4157 SmallPtrSet<Instruction *, 4>
4158 &DependingInstructions,
4159 SmallPtrSet<const BasicBlock *, 4>
4160 &Visited) {
4161 const Value *Arg = GetObjCArg(Autorelease);
4162
4163 // Check that there are no instructions between the retain and the autorelease
4164 // (such as an autorelease_pop) which may change the count.
4165 CallInst *Retain = 0;
4166 if (Class == IC_AutoreleaseRV)
4167 FindDependencies(RetainAutoreleaseRVDep, Arg,
4168 Autorelease->getParent(), Autorelease,
4169 DependingInstructions, Visited, PA);
4170 else
4171 FindDependencies(RetainAutoreleaseDep, Arg,
4172 Autorelease->getParent(), Autorelease,
4173 DependingInstructions, Visited, PA);
4174
4175 Visited.clear();
4176 if (DependingInstructions.size() != 1) {
4177 DependingInstructions.clear();
4178 return false;
4179 }
4180
4181 Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
4182 DependingInstructions.clear();
4183
4184 if (!Retain ||
4185 GetBasicInstructionClass(Retain) != IC_Retain ||
4186 GetObjCArg(Retain) != Arg)
4187 return false;
4188
4189 Changed = true;
4190 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00004191
Michael Gottesmanadd08472013-01-07 00:31:26 +00004192 DEBUG(dbgs() << "ObjCARCContract::ContractAutorelease: Fusing "
4193 "retain/autorelease. Erasing: " << *Autorelease << "\n"
4194 " Old Retain: "
4195 << *Retain << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00004196
John McCalld935e9c2011-06-15 23:37:01 +00004197 if (Class == IC_AutoreleaseRV)
4198 Retain->setCalledFunction(getRetainAutoreleaseRVCallee(F.getParent()));
4199 else
4200 Retain->setCalledFunction(getRetainAutoreleaseCallee(F.getParent()));
Michael Gottesman10426b52013-01-07 21:26:07 +00004201
Michael Gottesmanadd08472013-01-07 00:31:26 +00004202 DEBUG(dbgs() << " New Retain: "
4203 << *Retain << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00004204
John McCalld935e9c2011-06-15 23:37:01 +00004205 EraseInstruction(Autorelease);
4206 return true;
4207}
4208
Michael Gottesman97e3df02013-01-14 00:35:14 +00004209/// Attempt to merge an objc_release with a store, load, and objc_retain to form
4210/// an objc_storeStrong. This can be a little tricky because the instructions
4211/// don't always appear in order, and there may be unrelated intervening
4212/// instructions.
John McCalld935e9c2011-06-15 23:37:01 +00004213void ObjCARCContract::ContractRelease(Instruction *Release,
4214 inst_iterator &Iter) {
4215 LoadInst *Load = dyn_cast<LoadInst>(GetObjCArg(Release));
Eli Friedman7c5dc122011-09-12 20:23:13 +00004216 if (!Load || !Load->isSimple()) return;
John McCalld935e9c2011-06-15 23:37:01 +00004217
4218 // For now, require everything to be in one basic block.
4219 BasicBlock *BB = Release->getParent();
4220 if (Load->getParent() != BB) return;
4221
Dan Gohman61708d32012-05-08 23:34:08 +00004222 // Walk down to find the store and the release, which may be in either order.
Dan Gohmanf8b19d02012-05-09 23:08:33 +00004223 BasicBlock::iterator I = Load, End = BB->end();
John McCalld935e9c2011-06-15 23:37:01 +00004224 ++I;
4225 AliasAnalysis::Location Loc = AA->getLocation(Load);
Dan Gohman61708d32012-05-08 23:34:08 +00004226 StoreInst *Store = 0;
4227 bool SawRelease = false;
4228 for (; !Store || !SawRelease; ++I) {
Dan Gohmanf8b19d02012-05-09 23:08:33 +00004229 if (I == End)
4230 return;
4231
Dan Gohman61708d32012-05-08 23:34:08 +00004232 Instruction *Inst = I;
4233 if (Inst == Release) {
4234 SawRelease = true;
4235 continue;
4236 }
4237
4238 InstructionClass Class = GetBasicInstructionClass(Inst);
4239
4240 // Unrelated retains are harmless.
4241 if (IsRetain(Class))
4242 continue;
4243
4244 if (Store) {
4245 // The store is the point where we're going to put the objc_storeStrong,
4246 // so make sure there are no uses after it.
4247 if (CanUse(Inst, Load, PA, Class))
4248 return;
4249 } else if (AA->getModRefInfo(Inst, Loc) & AliasAnalysis::Mod) {
4250 // We are moving the load down to the store, so check for anything
4251 // else which writes to the memory between the load and the store.
4252 Store = dyn_cast<StoreInst>(Inst);
4253 if (!Store || !Store->isSimple()) return;
4254 if (Store->getPointerOperand() != Loc.Ptr) return;
4255 }
4256 }
John McCalld935e9c2011-06-15 23:37:01 +00004257
4258 Value *New = StripPointerCastsAndObjCCalls(Store->getValueOperand());
4259
4260 // Walk up to find the retain.
4261 I = Store;
4262 BasicBlock::iterator Begin = BB->begin();
4263 while (I != Begin && GetBasicInstructionClass(I) != IC_Retain)
4264 --I;
4265 Instruction *Retain = I;
4266 if (GetBasicInstructionClass(Retain) != IC_Retain) return;
4267 if (GetObjCArg(Retain) != New) return;
4268
4269 Changed = true;
4270 ++NumStoreStrongs;
4271
4272 LLVMContext &C = Release->getContext();
Chris Lattner229907c2011-07-18 04:54:35 +00004273 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
4274 Type *I8XX = PointerType::getUnqual(I8X);
John McCalld935e9c2011-06-15 23:37:01 +00004275
4276 Value *Args[] = { Load->getPointerOperand(), New };
4277 if (Args[0]->getType() != I8XX)
4278 Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
4279 if (Args[1]->getType() != I8X)
4280 Args[1] = new BitCastInst(Args[1], I8X, "", Store);
4281 CallInst *StoreStrong =
4282 CallInst::Create(getStoreStrongCallee(BB->getParent()->getParent()),
Jay Foad5bd375a2011-07-15 08:37:34 +00004283 Args, "", Store);
John McCalld935e9c2011-06-15 23:37:01 +00004284 StoreStrong->setDoesNotThrow();
4285 StoreStrong->setDebugLoc(Store->getDebugLoc());
4286
Dan Gohman8ee108b2012-01-19 19:14:36 +00004287 // We can't set the tail flag yet, because we haven't yet determined
4288 // whether there are any escaping allocas. Remember this call, so that
4289 // we can set the tail flag once we know it's safe.
4290 StoreStrongCalls.insert(StoreStrong);
4291
John McCalld935e9c2011-06-15 23:37:01 +00004292 if (&*Iter == Store) ++Iter;
4293 Store->eraseFromParent();
4294 Release->eraseFromParent();
4295 EraseInstruction(Retain);
4296 if (Load->use_empty())
4297 Load->eraseFromParent();
4298}
4299
4300bool ObjCARCContract::doInitialization(Module &M) {
Dan Gohman670f9372012-04-13 18:57:48 +00004301 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanceaac7c2011-06-20 23:20:43 +00004302 Run = ModuleHasARC(M);
4303 if (!Run)
4304 return false;
4305
John McCalld935e9c2011-06-15 23:37:01 +00004306 // These are initialized lazily.
4307 StoreStrongCallee = 0;
4308 RetainAutoreleaseCallee = 0;
4309 RetainAutoreleaseRVCallee = 0;
4310
4311 // Initialize RetainRVMarker.
4312 RetainRVMarker = 0;
4313 if (NamedMDNode *NMD =
4314 M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker"))
4315 if (NMD->getNumOperands() == 1) {
4316 const MDNode *N = NMD->getOperand(0);
4317 if (N->getNumOperands() == 1)
4318 if (const MDString *S = dyn_cast<MDString>(N->getOperand(0)))
4319 RetainRVMarker = S;
4320 }
4321
4322 return false;
4323}
4324
4325bool ObjCARCContract::runOnFunction(Function &F) {
4326 if (!EnableARCOpts)
4327 return false;
4328
Dan Gohmanceaac7c2011-06-20 23:20:43 +00004329 // If nothing in the Module uses ARC, don't do anything.
4330 if (!Run)
4331 return false;
4332
John McCalld935e9c2011-06-15 23:37:01 +00004333 Changed = false;
4334 AA = &getAnalysis<AliasAnalysis>();
4335 DT = &getAnalysis<DominatorTree>();
4336
4337 PA.setAA(&getAnalysis<AliasAnalysis>());
4338
Dan Gohman8ee108b2012-01-19 19:14:36 +00004339 // Track whether it's ok to mark objc_storeStrong calls with the "tail"
4340 // keyword. Be conservative if the function has variadic arguments.
4341 // It seems that functions which "return twice" are also unsafe for the
4342 // "tail" argument, because they are setjmp, which could need to
4343 // return to an earlier stack state.
Dan Gohman41375a32012-05-08 23:39:44 +00004344 bool TailOkForStoreStrongs = !F.isVarArg() &&
4345 !F.callsFunctionThatReturnsTwice();
Dan Gohman8ee108b2012-01-19 19:14:36 +00004346
John McCalld935e9c2011-06-15 23:37:01 +00004347 // For ObjC library calls which return their argument, replace uses of the
4348 // argument with uses of the call return value, if it dominates the use. This
4349 // reduces register pressure.
4350 SmallPtrSet<Instruction *, 4> DependingInstructions;
4351 SmallPtrSet<const BasicBlock *, 4> Visited;
4352 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
4353 Instruction *Inst = &*I++;
Michael Gottesman10426b52013-01-07 21:26:07 +00004354
Michael Gottesman3f146e22013-01-01 16:05:48 +00004355 DEBUG(dbgs() << "ObjCARCContract: Visiting: " << *Inst << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00004356
John McCalld935e9c2011-06-15 23:37:01 +00004357 // Only these library routines return their argument. In particular,
4358 // objc_retainBlock does not necessarily return its argument.
4359 InstructionClass Class = GetBasicInstructionClass(Inst);
4360 switch (Class) {
4361 case IC_Retain:
4362 case IC_FusedRetainAutorelease:
4363 case IC_FusedRetainAutoreleaseRV:
4364 break;
4365 case IC_Autorelease:
4366 case IC_AutoreleaseRV:
4367 if (ContractAutorelease(F, Inst, Class, DependingInstructions, Visited))
4368 continue;
4369 break;
4370 case IC_RetainRV: {
4371 // If we're compiling for a target which needs a special inline-asm
4372 // marker to do the retainAutoreleasedReturnValue optimization,
4373 // insert it now.
4374 if (!RetainRVMarker)
4375 break;
4376 BasicBlock::iterator BBI = Inst;
Dan Gohman5f725cd2012-06-25 19:47:37 +00004377 BasicBlock *InstParent = Inst->getParent();
4378
4379 // Step up to see if the call immediately precedes the RetainRV call.
4380 // If it's an invoke, we have to cross a block boundary. And we have
4381 // to carefully dodge no-op instructions.
4382 do {
4383 if (&*BBI == InstParent->begin()) {
4384 BasicBlock *Pred = InstParent->getSinglePredecessor();
4385 if (!Pred)
4386 goto decline_rv_optimization;
4387 BBI = Pred->getTerminator();
4388 break;
4389 }
4390 --BBI;
4391 } while (isNoopInstruction(BBI));
4392
John McCalld935e9c2011-06-15 23:37:01 +00004393 if (&*BBI == GetObjCArg(Inst)) {
Michael Gottesman00d1f962013-01-03 07:32:41 +00004394 DEBUG(dbgs() << "ObjCARCContract: Adding inline asm marker for "
Michael Gottesman9f848ae2013-01-04 21:29:57 +00004395 "retainAutoreleasedReturnValue optimization.\n");
Dan Gohman670f9372012-04-13 18:57:48 +00004396 Changed = true;
John McCalld935e9c2011-06-15 23:37:01 +00004397 InlineAsm *IA =
4398 InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()),
4399 /*isVarArg=*/false),
4400 RetainRVMarker->getString(),
4401 /*Constraints=*/"", /*hasSideEffects=*/true);
4402 CallInst::Create(IA, "", Inst);
4403 }
Dan Gohman5f725cd2012-06-25 19:47:37 +00004404 decline_rv_optimization:
John McCalld935e9c2011-06-15 23:37:01 +00004405 break;
4406 }
4407 case IC_InitWeak: {
4408 // objc_initWeak(p, null) => *p = null
4409 CallInst *CI = cast<CallInst>(Inst);
4410 if (isNullOrUndef(CI->getArgOperand(1))) {
4411 Value *Null =
4412 ConstantPointerNull::get(cast<PointerType>(CI->getType()));
4413 Changed = true;
4414 new StoreInst(Null, CI->getArgOperand(0), CI);
Michael Gottesman10426b52013-01-07 21:26:07 +00004415
Michael Gottesman416dc002013-01-03 07:32:53 +00004416 DEBUG(dbgs() << "OBJCARCContract: Old = " << *CI << "\n"
4417 << " New = " << *Null << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00004418
John McCalld935e9c2011-06-15 23:37:01 +00004419 CI->replaceAllUsesWith(Null);
4420 CI->eraseFromParent();
4421 }
4422 continue;
4423 }
4424 case IC_Release:
4425 ContractRelease(Inst, I);
4426 continue;
Dan Gohman8ee108b2012-01-19 19:14:36 +00004427 case IC_User:
4428 // Be conservative if the function has any alloca instructions.
4429 // Technically we only care about escaping alloca instructions,
4430 // but this is sufficient to handle some interesting cases.
4431 if (isa<AllocaInst>(Inst))
4432 TailOkForStoreStrongs = false;
4433 continue;
John McCalld935e9c2011-06-15 23:37:01 +00004434 default:
4435 continue;
4436 }
4437
Michael Gottesman50ae5b22013-01-03 08:09:27 +00004438 DEBUG(dbgs() << "ObjCARCContract: Finished List.\n\n");
Michael Gottesman3f146e22013-01-01 16:05:48 +00004439
John McCalld935e9c2011-06-15 23:37:01 +00004440 // Don't use GetObjCArg because we don't want to look through bitcasts
4441 // and such; to do the replacement, the argument must have type i8*.
4442 const Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
4443 for (;;) {
4444 // If we're compiling bugpointed code, don't get in trouble.
4445 if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
4446 break;
4447 // Look through the uses of the pointer.
4448 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
4449 UI != UE; ) {
4450 Use &U = UI.getUse();
4451 unsigned OperandNo = UI.getOperandNo();
4452 ++UI; // Increment UI now, because we may unlink its element.
Dan Gohman670f9372012-04-13 18:57:48 +00004453
4454 // If the call's return value dominates a use of the call's argument
4455 // value, rewrite the use to use the return value. We check for
4456 // reachability here because an unreachable call is considered to
4457 // trivially dominate itself, which would lead us to rewriting its
4458 // argument in terms of its return value, which would lead to
4459 // infinite loops in GetObjCArg.
Dan Gohman41375a32012-05-08 23:39:44 +00004460 if (DT->isReachableFromEntry(U) && DT->dominates(Inst, U)) {
Rafael Espindolaf5892782012-03-15 15:52:59 +00004461 Changed = true;
4462 Instruction *Replacement = Inst;
4463 Type *UseTy = U.get()->getType();
Dan Gohmande8d2c42012-04-13 01:08:28 +00004464 if (PHINode *PHI = dyn_cast<PHINode>(U.getUser())) {
Rafael Espindolaf5892782012-03-15 15:52:59 +00004465 // For PHI nodes, insert the bitcast in the predecessor block.
Dan Gohman41375a32012-05-08 23:39:44 +00004466 unsigned ValNo = PHINode::getIncomingValueNumForOperand(OperandNo);
4467 BasicBlock *BB = PHI->getIncomingBlock(ValNo);
Rafael Espindolaf5892782012-03-15 15:52:59 +00004468 if (Replacement->getType() != UseTy)
4469 Replacement = new BitCastInst(Replacement, UseTy, "",
4470 &BB->back());
Dan Gohman670f9372012-04-13 18:57:48 +00004471 // While we're here, rewrite all edges for this PHI, rather
4472 // than just one use at a time, to minimize the number of
4473 // bitcasts we emit.
Dan Gohmandae33492012-04-27 18:56:31 +00004474 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
Rafael Espindolaf5892782012-03-15 15:52:59 +00004475 if (PHI->getIncomingBlock(i) == BB) {
4476 // Keep the UI iterator valid.
4477 if (&PHI->getOperandUse(
4478 PHINode::getOperandNumForIncomingValue(i)) ==
4479 &UI.getUse())
4480 ++UI;
4481 PHI->setIncomingValue(i, Replacement);
4482 }
4483 } else {
4484 if (Replacement->getType() != UseTy)
Dan Gohmande8d2c42012-04-13 01:08:28 +00004485 Replacement = new BitCastInst(Replacement, UseTy, "",
4486 cast<Instruction>(U.getUser()));
Rafael Espindolaf5892782012-03-15 15:52:59 +00004487 U.set(Replacement);
John McCalld935e9c2011-06-15 23:37:01 +00004488 }
Rafael Espindolaf5892782012-03-15 15:52:59 +00004489 }
John McCalld935e9c2011-06-15 23:37:01 +00004490 }
4491
Dan Gohmandae33492012-04-27 18:56:31 +00004492 // If Arg is a no-op casted pointer, strip one level of casts and iterate.
John McCalld935e9c2011-06-15 23:37:01 +00004493 if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
4494 Arg = BI->getOperand(0);
4495 else if (isa<GEPOperator>(Arg) &&
4496 cast<GEPOperator>(Arg)->hasAllZeroIndices())
4497 Arg = cast<GEPOperator>(Arg)->getPointerOperand();
4498 else if (isa<GlobalAlias>(Arg) &&
4499 !cast<GlobalAlias>(Arg)->mayBeOverridden())
4500 Arg = cast<GlobalAlias>(Arg)->getAliasee();
4501 else
4502 break;
4503 }
4504 }
4505
Dan Gohman8ee108b2012-01-19 19:14:36 +00004506 // If this function has no escaping allocas or suspicious vararg usage,
4507 // objc_storeStrong calls can be marked with the "tail" keyword.
4508 if (TailOkForStoreStrongs)
Dan Gohman41375a32012-05-08 23:39:44 +00004509 for (SmallPtrSet<CallInst *, 8>::iterator I = StoreStrongCalls.begin(),
Dan Gohman8ee108b2012-01-19 19:14:36 +00004510 E = StoreStrongCalls.end(); I != E; ++I)
4511 (*I)->setTailCall();
4512 StoreStrongCalls.clear();
4513
John McCalld935e9c2011-06-15 23:37:01 +00004514 return Changed;
4515}
Michael Gottesman97e3df02013-01-14 00:35:14 +00004516
4517/// @}
4518///