blob: f2cda41c9769aceefa49695a12e7f1363740634a [file] [log] [blame]
John McCall9fbd3182011-06-15 23:37:01 +00001//===- ObjCARC.cpp - ObjC ARC Optimization --------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines ObjC ARC optimizations. ARC stands for
11// Automatic Reference Counting and is a system for managing reference counts
12// for objects 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 knowedge 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//
29//===----------------------------------------------------------------------===//
30
31#define DEBUG_TYPE "objc-arc"
32#include "llvm/Function.h"
33#include "llvm/Intrinsics.h"
34#include "llvm/GlobalVariable.h"
35#include "llvm/DerivedTypes.h"
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +000036#include "llvm/Module.h"
John McCall9fbd3182011-06-15 23:37:01 +000037#include "llvm/Analysis/ValueTracking.h"
38#include "llvm/Transforms/Utils/Local.h"
39#include "llvm/Support/CallSite.h"
40#include "llvm/Support/CommandLine.h"
41#include "llvm/ADT/StringSwitch.h"
42#include "llvm/ADT/DenseMap.h"
43#include "llvm/ADT/STLExtras.h"
44using namespace llvm;
45
46// A handy option to enable/disable all optimizations in this file.
47static cl::opt<bool> EnableARCOpts("enable-objc-arc-opts", cl::init(true));
48
49//===----------------------------------------------------------------------===//
50// Misc. Utilities
51//===----------------------------------------------------------------------===//
52
53namespace {
54 /// MapVector - An associative container with fast insertion-order
55 /// (deterministic) iteration over its elements. Plus the special
56 /// blot operation.
57 template<class KeyT, class ValueT>
58 class MapVector {
59 /// Map - Map keys to indices in Vector.
60 typedef DenseMap<KeyT, size_t> MapTy;
61 MapTy Map;
62
63 /// Vector - Keys and values.
64 typedef std::vector<std::pair<KeyT, ValueT> > VectorTy;
65 VectorTy Vector;
66
67 public:
68 typedef typename VectorTy::iterator iterator;
69 typedef typename VectorTy::const_iterator const_iterator;
70 iterator begin() { return Vector.begin(); }
71 iterator end() { return Vector.end(); }
72 const_iterator begin() const { return Vector.begin(); }
73 const_iterator end() const { return Vector.end(); }
74
75#ifdef XDEBUG
76 ~MapVector() {
77 assert(Vector.size() >= Map.size()); // May differ due to blotting.
78 for (typename MapTy::const_iterator I = Map.begin(), E = Map.end();
79 I != E; ++I) {
80 assert(I->second < Vector.size());
81 assert(Vector[I->second].first == I->first);
82 }
83 for (typename VectorTy::const_iterator I = Vector.begin(),
84 E = Vector.end(); I != E; ++I)
85 assert(!I->first ||
86 (Map.count(I->first) &&
87 Map[I->first] == size_t(I - Vector.begin())));
88 }
89#endif
90
91 ValueT &operator[](KeyT Arg) {
92 std::pair<typename MapTy::iterator, bool> Pair =
93 Map.insert(std::make_pair(Arg, size_t(0)));
94 if (Pair.second) {
95 Pair.first->second = Vector.size();
96 Vector.push_back(std::make_pair(Arg, ValueT()));
97 return Vector.back().second;
98 }
99 return Vector[Pair.first->second].second;
100 }
101
102 std::pair<iterator, bool>
103 insert(const std::pair<KeyT, ValueT> &InsertPair) {
104 std::pair<typename MapTy::iterator, bool> Pair =
105 Map.insert(std::make_pair(InsertPair.first, size_t(0)));
106 if (Pair.second) {
107 Pair.first->second = Vector.size();
108 Vector.push_back(InsertPair);
109 return std::make_pair(llvm::prior(Vector.end()), true);
110 }
111 return std::make_pair(Vector.begin() + Pair.first->second, false);
112 }
113
114 const_iterator find(KeyT Key) const {
115 typename MapTy::const_iterator It = Map.find(Key);
116 if (It == Map.end()) return Vector.end();
117 return Vector.begin() + It->second;
118 }
119
120 /// blot - This is similar to erase, but instead of removing the element
121 /// from the vector, it just zeros out the key in the vector. This leaves
122 /// iterators intact, but clients must be prepared for zeroed-out keys when
123 /// iterating.
124 void blot(KeyT Key) {
125 typename MapTy::iterator It = Map.find(Key);
126 if (It == Map.end()) return;
127 Vector[It->second].first = KeyT();
128 Map.erase(It);
129 }
130
131 void clear() {
132 Map.clear();
133 Vector.clear();
134 }
135 };
136}
137
138//===----------------------------------------------------------------------===//
139// ARC Utilities.
140//===----------------------------------------------------------------------===//
141
142namespace {
143 /// InstructionClass - A simple classification for instructions.
144 enum InstructionClass {
145 IC_Retain, ///< objc_retain
146 IC_RetainRV, ///< objc_retainAutoreleasedReturnValue
147 IC_RetainBlock, ///< objc_retainBlock
148 IC_Release, ///< objc_release
149 IC_Autorelease, ///< objc_autorelease
150 IC_AutoreleaseRV, ///< objc_autoreleaseReturnValue
151 IC_AutoreleasepoolPush, ///< objc_autoreleasePoolPush
152 IC_AutoreleasepoolPop, ///< objc_autoreleasePoolPop
153 IC_NoopCast, ///< objc_retainedObject, etc.
154 IC_FusedRetainAutorelease, ///< objc_retainAutorelease
155 IC_FusedRetainAutoreleaseRV, ///< objc_retainAutoreleaseReturnValue
156 IC_LoadWeakRetained, ///< objc_loadWeakRetained (primitive)
157 IC_StoreWeak, ///< objc_storeWeak (primitive)
158 IC_InitWeak, ///< objc_initWeak (derived)
159 IC_LoadWeak, ///< objc_loadWeak (derived)
160 IC_MoveWeak, ///< objc_moveWeak (derived)
161 IC_CopyWeak, ///< objc_copyWeak (derived)
162 IC_DestroyWeak, ///< objc_destroyWeak (derived)
163 IC_CallOrUser, ///< could call objc_release and/or "use" pointers
164 IC_Call, ///< could call objc_release
165 IC_User, ///< could "use" a pointer
166 IC_None ///< anything else
167 };
168}
169
170/// IsPotentialUse - Test whether the given value is possible a
171/// reference-counted pointer.
172static bool IsPotentialUse(const Value *Op) {
173 // Pointers to static or stack storage are not reference-counted pointers.
174 if (isa<Constant>(Op) || isa<AllocaInst>(Op))
175 return false;
176 // Special arguments are not reference-counted.
177 if (const Argument *Arg = dyn_cast<Argument>(Op))
178 if (Arg->hasByValAttr() ||
179 Arg->hasNestAttr() ||
180 Arg->hasStructRetAttr())
181 return false;
182 // Only consider values with pointer types, and not function pointers.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000183 PointerType *Ty = dyn_cast<PointerType>(Op->getType());
John McCall9fbd3182011-06-15 23:37:01 +0000184 if (!Ty || isa<FunctionType>(Ty->getElementType()))
185 return false;
186 // Conservatively assume anything else is a potential use.
187 return true;
188}
189
190/// GetCallSiteClass - Helper for GetInstructionClass. Determines what kind
191/// of construct CS is.
192static InstructionClass GetCallSiteClass(ImmutableCallSite CS) {
193 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
194 I != E; ++I)
195 if (IsPotentialUse(*I))
196 return CS.onlyReadsMemory() ? IC_User : IC_CallOrUser;
197
198 return CS.onlyReadsMemory() ? IC_None : IC_Call;
199}
200
201/// GetFunctionClass - Determine if F is one of the special known Functions.
202/// If it isn't, return IC_CallOrUser.
203static InstructionClass GetFunctionClass(const Function *F) {
204 Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
205
206 // No arguments.
207 if (AI == AE)
208 return StringSwitch<InstructionClass>(F->getName())
209 .Case("objc_autoreleasePoolPush", IC_AutoreleasepoolPush)
210 .Default(IC_CallOrUser);
211
212 // One argument.
213 const Argument *A0 = AI++;
214 if (AI == AE)
215 // Argument is a pointer.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000216 if (PointerType *PTy = dyn_cast<PointerType>(A0->getType())) {
217 Type *ETy = PTy->getElementType();
John McCall9fbd3182011-06-15 23:37:01 +0000218 // Argument is i8*.
219 if (ETy->isIntegerTy(8))
220 return StringSwitch<InstructionClass>(F->getName())
221 .Case("objc_retain", IC_Retain)
222 .Case("objc_retainAutoreleasedReturnValue", IC_RetainRV)
223 .Case("objc_retainBlock", IC_RetainBlock)
224 .Case("objc_release", IC_Release)
225 .Case("objc_autorelease", IC_Autorelease)
226 .Case("objc_autoreleaseReturnValue", IC_AutoreleaseRV)
227 .Case("objc_autoreleasePoolPop", IC_AutoreleasepoolPop)
228 .Case("objc_retainedObject", IC_NoopCast)
229 .Case("objc_unretainedObject", IC_NoopCast)
230 .Case("objc_unretainedPointer", IC_NoopCast)
231 .Case("objc_retain_autorelease", IC_FusedRetainAutorelease)
232 .Case("objc_retainAutorelease", IC_FusedRetainAutorelease)
233 .Case("objc_retainAutoreleaseReturnValue",IC_FusedRetainAutoreleaseRV)
234 .Default(IC_CallOrUser);
235
236 // Argument is i8**
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000237 if (PointerType *Pte = dyn_cast<PointerType>(ETy))
John McCall9fbd3182011-06-15 23:37:01 +0000238 if (Pte->getElementType()->isIntegerTy(8))
239 return StringSwitch<InstructionClass>(F->getName())
240 .Case("objc_loadWeakRetained", IC_LoadWeakRetained)
241 .Case("objc_loadWeak", IC_LoadWeak)
242 .Case("objc_destroyWeak", IC_DestroyWeak)
243 .Default(IC_CallOrUser);
244 }
245
246 // Two arguments, first is i8**.
247 const Argument *A1 = AI++;
248 if (AI == AE)
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000249 if (PointerType *PTy = dyn_cast<PointerType>(A0->getType()))
250 if (PointerType *Pte = dyn_cast<PointerType>(PTy->getElementType()))
John McCall9fbd3182011-06-15 23:37:01 +0000251 if (Pte->getElementType()->isIntegerTy(8))
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000252 if (PointerType *PTy1 = dyn_cast<PointerType>(A1->getType())) {
253 Type *ETy1 = PTy1->getElementType();
John McCall9fbd3182011-06-15 23:37:01 +0000254 // Second argument is i8*
255 if (ETy1->isIntegerTy(8))
256 return StringSwitch<InstructionClass>(F->getName())
257 .Case("objc_storeWeak", IC_StoreWeak)
258 .Case("objc_initWeak", IC_InitWeak)
259 .Default(IC_CallOrUser);
260 // Second argument is i8**.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000261 if (PointerType *Pte1 = dyn_cast<PointerType>(ETy1))
John McCall9fbd3182011-06-15 23:37:01 +0000262 if (Pte1->getElementType()->isIntegerTy(8))
263 return StringSwitch<InstructionClass>(F->getName())
264 .Case("objc_moveWeak", IC_MoveWeak)
265 .Case("objc_copyWeak", IC_CopyWeak)
266 .Default(IC_CallOrUser);
267 }
268
269 // Anything else.
270 return IC_CallOrUser;
271}
272
273/// GetInstructionClass - Determine what kind of construct V is.
274static InstructionClass GetInstructionClass(const Value *V) {
275 if (const Instruction *I = dyn_cast<Instruction>(V)) {
276 // Any instruction other than bitcast and gep with a pointer operand have a
277 // use of an objc pointer. Bitcasts, GEPs, Selects, PHIs transfer a pointer
278 // to a subsequent use, rather than using it themselves, in this sense.
279 // As a short cut, several other opcodes are known to have no pointer
280 // operands of interest. And ret is never followed by a release, so it's
281 // not interesting to examine.
282 switch (I->getOpcode()) {
283 case Instruction::Call: {
284 const CallInst *CI = cast<CallInst>(I);
285 // Check for calls to special functions.
286 if (const Function *F = CI->getCalledFunction()) {
287 InstructionClass Class = GetFunctionClass(F);
288 if (Class != IC_CallOrUser)
289 return Class;
290
291 // None of the intrinsic functions do objc_release. For intrinsics, the
292 // only question is whether or not they may be users.
293 switch (F->getIntrinsicID()) {
294 case 0: break;
295 case Intrinsic::bswap: case Intrinsic::ctpop:
296 case Intrinsic::ctlz: case Intrinsic::cttz:
297 case Intrinsic::returnaddress: case Intrinsic::frameaddress:
298 case Intrinsic::stacksave: case Intrinsic::stackrestore:
299 case Intrinsic::vastart: case Intrinsic::vacopy: case Intrinsic::vaend:
300 // Don't let dbg info affect our results.
301 case Intrinsic::dbg_declare: case Intrinsic::dbg_value:
302 // Short cut: Some intrinsics obviously don't use ObjC pointers.
303 return IC_None;
304 default:
305 for (Function::const_arg_iterator AI = F->arg_begin(),
306 AE = F->arg_end(); AI != AE; ++AI)
307 if (IsPotentialUse(AI))
308 return IC_User;
309 return IC_None;
310 }
311 }
312 return GetCallSiteClass(CI);
313 }
314 case Instruction::Invoke:
315 return GetCallSiteClass(cast<InvokeInst>(I));
316 case Instruction::BitCast:
317 case Instruction::GetElementPtr:
318 case Instruction::Select: case Instruction::PHI:
319 case Instruction::Ret: case Instruction::Br:
320 case Instruction::Switch: case Instruction::IndirectBr:
321 case Instruction::Alloca: case Instruction::VAArg:
322 case Instruction::Add: case Instruction::FAdd:
323 case Instruction::Sub: case Instruction::FSub:
324 case Instruction::Mul: case Instruction::FMul:
325 case Instruction::SDiv: case Instruction::UDiv: case Instruction::FDiv:
326 case Instruction::SRem: case Instruction::URem: case Instruction::FRem:
327 case Instruction::Shl: case Instruction::LShr: case Instruction::AShr:
328 case Instruction::And: case Instruction::Or: case Instruction::Xor:
329 case Instruction::SExt: case Instruction::ZExt: case Instruction::Trunc:
330 case Instruction::IntToPtr: case Instruction::FCmp:
331 case Instruction::FPTrunc: case Instruction::FPExt:
332 case Instruction::FPToUI: case Instruction::FPToSI:
333 case Instruction::UIToFP: case Instruction::SIToFP:
334 case Instruction::InsertElement: case Instruction::ExtractElement:
335 case Instruction::ShuffleVector:
336 case Instruction::ExtractValue:
337 break;
338 case Instruction::ICmp:
339 // Comparing a pointer with null, or any other constant, isn't an
340 // interesting use, because we don't care what the pointer points to, or
341 // about the values of any other dynamic reference-counted pointers.
342 if (IsPotentialUse(I->getOperand(1)))
343 return IC_User;
344 break;
345 default:
346 // For anything else, check all the operands.
347 for (User::const_op_iterator OI = I->op_begin(), OE = I->op_end();
348 OI != OE; ++OI)
349 if (IsPotentialUse(*OI))
350 return IC_User;
351 }
352 }
353
354 // Otherwise, it's totally inert for ARC purposes.
355 return IC_None;
356}
357
358/// GetBasicInstructionClass - Determine what kind of construct V is. This is
359/// similar to GetInstructionClass except that it only detects objc runtine
360/// calls. This allows it to be faster.
361static InstructionClass GetBasicInstructionClass(const Value *V) {
362 if (const CallInst *CI = dyn_cast<CallInst>(V)) {
363 if (const Function *F = CI->getCalledFunction())
364 return GetFunctionClass(F);
365 // Otherwise, be conservative.
366 return IC_CallOrUser;
367 }
368
369 // Otherwise, be conservative.
370 return IC_User;
371}
372
373/// IsRetain - Test if the the given class is objc_retain or
374/// equivalent.
375static bool IsRetain(InstructionClass Class) {
376 return Class == IC_Retain ||
377 Class == IC_RetainRV;
378}
379
380/// IsAutorelease - Test if the the given class is objc_autorelease or
381/// equivalent.
382static bool IsAutorelease(InstructionClass Class) {
383 return Class == IC_Autorelease ||
384 Class == IC_AutoreleaseRV;
385}
386
387/// IsForwarding - Test if the given class represents instructions which return
388/// their argument verbatim.
389static bool IsForwarding(InstructionClass Class) {
390 // objc_retainBlock technically doesn't always return its argument
391 // verbatim, but it doesn't matter for our purposes here.
392 return Class == IC_Retain ||
393 Class == IC_RetainRV ||
394 Class == IC_Autorelease ||
395 Class == IC_AutoreleaseRV ||
396 Class == IC_RetainBlock ||
397 Class == IC_NoopCast;
398}
399
400/// IsNoopOnNull - Test if the given class represents instructions which do
401/// nothing if passed a null pointer.
402static bool IsNoopOnNull(InstructionClass Class) {
403 return Class == IC_Retain ||
404 Class == IC_RetainRV ||
405 Class == IC_Release ||
406 Class == IC_Autorelease ||
407 Class == IC_AutoreleaseRV ||
408 Class == IC_RetainBlock;
409}
410
411/// IsAlwaysTail - Test if the given class represents instructions which are
412/// always safe to mark with the "tail" keyword.
413static bool IsAlwaysTail(InstructionClass Class) {
414 // IC_RetainBlock may be given a stack argument.
415 return Class == IC_Retain ||
416 Class == IC_RetainRV ||
417 Class == IC_Autorelease ||
418 Class == IC_AutoreleaseRV;
419}
420
421/// IsNoThrow - Test if the given class represents instructions which are always
422/// safe to mark with the nounwind attribute..
423static bool IsNoThrow(InstructionClass Class) {
424 return Class == IC_Retain ||
425 Class == IC_RetainRV ||
426 Class == IC_RetainBlock ||
427 Class == IC_Release ||
428 Class == IC_Autorelease ||
429 Class == IC_AutoreleaseRV ||
430 Class == IC_AutoreleasepoolPush ||
431 Class == IC_AutoreleasepoolPop;
432}
433
434/// EraseInstruction - Erase the given instruction. ObjC calls return their
435/// argument verbatim, so if it's such a call and the return value has users,
436/// replace them with the argument value.
437static void EraseInstruction(Instruction *CI) {
438 Value *OldArg = cast<CallInst>(CI)->getArgOperand(0);
439
440 bool Unused = CI->use_empty();
441
442 if (!Unused) {
443 // Replace the return value with the argument.
444 assert(IsForwarding(GetBasicInstructionClass(CI)) &&
445 "Can't delete non-forwarding instruction with users!");
446 CI->replaceAllUsesWith(OldArg);
447 }
448
449 CI->eraseFromParent();
450
451 if (Unused)
452 RecursivelyDeleteTriviallyDeadInstructions(OldArg);
453}
454
455/// GetUnderlyingObjCPtr - This is a wrapper around getUnderlyingObject which
456/// also knows how to look through objc_retain and objc_autorelease calls, which
457/// we know to return their argument verbatim.
458static const Value *GetUnderlyingObjCPtr(const Value *V) {
459 for (;;) {
460 V = GetUnderlyingObject(V);
461 if (!IsForwarding(GetBasicInstructionClass(V)))
462 break;
463 V = cast<CallInst>(V)->getArgOperand(0);
464 }
465
466 return V;
467}
468
469/// StripPointerCastsAndObjCCalls - This is a wrapper around
470/// Value::stripPointerCasts which also knows how to look through objc_retain
471/// and objc_autorelease calls, which we know to return their argument verbatim.
472static const Value *StripPointerCastsAndObjCCalls(const Value *V) {
473 for (;;) {
474 V = V->stripPointerCasts();
475 if (!IsForwarding(GetBasicInstructionClass(V)))
476 break;
477 V = cast<CallInst>(V)->getArgOperand(0);
478 }
479 return V;
480}
481
482/// StripPointerCastsAndObjCCalls - This is a wrapper around
483/// Value::stripPointerCasts which also knows how to look through objc_retain
484/// and objc_autorelease calls, which we know to return their argument verbatim.
485static Value *StripPointerCastsAndObjCCalls(Value *V) {
486 for (;;) {
487 V = V->stripPointerCasts();
488 if (!IsForwarding(GetBasicInstructionClass(V)))
489 break;
490 V = cast<CallInst>(V)->getArgOperand(0);
491 }
492 return V;
493}
494
495/// GetObjCArg - Assuming the given instruction is one of the special calls such
496/// as objc_retain or objc_release, return the argument value, stripped of no-op
497/// casts and forwarding calls.
498static Value *GetObjCArg(Value *Inst) {
499 return StripPointerCastsAndObjCCalls(cast<CallInst>(Inst)->getArgOperand(0));
500}
501
502/// IsObjCIdentifiedObject - This is similar to AliasAnalysis'
503/// isObjCIdentifiedObject, except that it uses special knowledge of
504/// ObjC conventions...
505static bool IsObjCIdentifiedObject(const Value *V) {
506 // Assume that call results and arguments have their own "provenance".
507 // Constants (including GlobalVariables) and Allocas are never
508 // reference-counted.
509 if (isa<CallInst>(V) || isa<InvokeInst>(V) ||
510 isa<Argument>(V) || isa<Constant>(V) ||
511 isa<AllocaInst>(V))
512 return true;
513
514 if (const LoadInst *LI = dyn_cast<LoadInst>(V)) {
515 const Value *Pointer =
516 StripPointerCastsAndObjCCalls(LI->getPointerOperand());
517 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Pointer)) {
518 StringRef Name = GV->getName();
519 // These special variables are known to hold values which are not
520 // reference-counted pointers.
521 if (Name.startswith("\01L_OBJC_SELECTOR_REFERENCES_") ||
522 Name.startswith("\01L_OBJC_CLASSLIST_REFERENCES_") ||
523 Name.startswith("\01L_OBJC_CLASSLIST_SUP_REFS_$_") ||
524 Name.startswith("\01L_OBJC_METH_VAR_NAME_") ||
525 Name.startswith("\01l_objc_msgSend_fixup_"))
526 return true;
527 }
528 }
529
530 return false;
531}
532
533/// FindSingleUseIdentifiedObject - This is similar to
534/// StripPointerCastsAndObjCCalls but it stops as soon as it finds a value
535/// with multiple uses.
536static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
537 if (Arg->hasOneUse()) {
538 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
539 return FindSingleUseIdentifiedObject(BC->getOperand(0));
540 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
541 if (GEP->hasAllZeroIndices())
542 return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
543 if (IsForwarding(GetBasicInstructionClass(Arg)))
544 return FindSingleUseIdentifiedObject(
545 cast<CallInst>(Arg)->getArgOperand(0));
546 if (!IsObjCIdentifiedObject(Arg))
547 return 0;
548 return Arg;
549 }
550
551 // If we found an identifiable object but it has multiple uses, but they
552 // are trivial uses, we can still consider this to be a single-use
553 // value.
554 if (IsObjCIdentifiedObject(Arg)) {
555 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
556 UI != UE; ++UI) {
557 const User *U = *UI;
558 if (!U->use_empty() || StripPointerCastsAndObjCCalls(U) != Arg)
559 return 0;
560 }
561
562 return Arg;
563 }
564
565 return 0;
566}
567
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000568/// ModuleHasARC - Test if the given module looks interesting to run ARC
569/// optimization on.
570static bool ModuleHasARC(const Module &M) {
571 return
572 M.getNamedValue("objc_retain") ||
573 M.getNamedValue("objc_release") ||
574 M.getNamedValue("objc_autorelease") ||
575 M.getNamedValue("objc_retainAutoreleasedReturnValue") ||
576 M.getNamedValue("objc_retainBlock") ||
577 M.getNamedValue("objc_autoreleaseReturnValue") ||
578 M.getNamedValue("objc_autoreleasePoolPush") ||
579 M.getNamedValue("objc_loadWeakRetained") ||
580 M.getNamedValue("objc_loadWeak") ||
581 M.getNamedValue("objc_destroyWeak") ||
582 M.getNamedValue("objc_storeWeak") ||
583 M.getNamedValue("objc_initWeak") ||
584 M.getNamedValue("objc_moveWeak") ||
585 M.getNamedValue("objc_copyWeak") ||
586 M.getNamedValue("objc_retainedObject") ||
587 M.getNamedValue("objc_unretainedObject") ||
588 M.getNamedValue("objc_unretainedPointer");
589}
590
John McCall9fbd3182011-06-15 23:37:01 +0000591//===----------------------------------------------------------------------===//
592// ARC AliasAnalysis.
593//===----------------------------------------------------------------------===//
594
595#include "llvm/Pass.h"
596#include "llvm/Analysis/AliasAnalysis.h"
597#include "llvm/Analysis/Passes.h"
598
599namespace {
600 /// ObjCARCAliasAnalysis - This is a simple alias analysis
601 /// implementation that uses knowledge of ARC constructs to answer queries.
602 ///
603 /// TODO: This class could be generalized to know about other ObjC-specific
604 /// tricks. Such as knowing that ivars in the non-fragile ABI are non-aliasing
605 /// even though their offsets are dynamic.
606 class ObjCARCAliasAnalysis : public ImmutablePass,
607 public AliasAnalysis {
608 public:
609 static char ID; // Class identification, replacement for typeinfo
610 ObjCARCAliasAnalysis() : ImmutablePass(ID) {
611 initializeObjCARCAliasAnalysisPass(*PassRegistry::getPassRegistry());
612 }
613
614 private:
615 virtual void initializePass() {
616 InitializeAliasAnalysis(this);
617 }
618
619 /// getAdjustedAnalysisPointer - This method is used when a pass implements
620 /// an analysis interface through multiple inheritance. If needed, it
621 /// should override this to adjust the this pointer as needed for the
622 /// specified pass info.
623 virtual void *getAdjustedAnalysisPointer(const void *PI) {
624 if (PI == &AliasAnalysis::ID)
625 return (AliasAnalysis*)this;
626 return this;
627 }
628
629 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
630 virtual AliasResult alias(const Location &LocA, const Location &LocB);
631 virtual bool pointsToConstantMemory(const Location &Loc, bool OrLocal);
632 virtual ModRefBehavior getModRefBehavior(ImmutableCallSite CS);
633 virtual ModRefBehavior getModRefBehavior(const Function *F);
634 virtual ModRefResult getModRefInfo(ImmutableCallSite CS,
635 const Location &Loc);
636 virtual ModRefResult getModRefInfo(ImmutableCallSite CS1,
637 ImmutableCallSite CS2);
638 };
639} // End of anonymous namespace
640
641// Register this pass...
642char ObjCARCAliasAnalysis::ID = 0;
643INITIALIZE_AG_PASS(ObjCARCAliasAnalysis, AliasAnalysis, "objc-arc-aa",
644 "ObjC-ARC-Based Alias Analysis", false, true, false)
645
646ImmutablePass *llvm::createObjCARCAliasAnalysisPass() {
647 return new ObjCARCAliasAnalysis();
648}
649
650void
651ObjCARCAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
652 AU.setPreservesAll();
653 AliasAnalysis::getAnalysisUsage(AU);
654}
655
656AliasAnalysis::AliasResult
657ObjCARCAliasAnalysis::alias(const Location &LocA, const Location &LocB) {
658 if (!EnableARCOpts)
659 return AliasAnalysis::alias(LocA, LocB);
660
661 // First, strip off no-ops, including ObjC-specific no-ops, and try making a
662 // precise alias query.
663 const Value *SA = StripPointerCastsAndObjCCalls(LocA.Ptr);
664 const Value *SB = StripPointerCastsAndObjCCalls(LocB.Ptr);
665 AliasResult Result =
666 AliasAnalysis::alias(Location(SA, LocA.Size, LocA.TBAATag),
667 Location(SB, LocB.Size, LocB.TBAATag));
668 if (Result != MayAlias)
669 return Result;
670
671 // If that failed, climb to the underlying object, including climbing through
672 // ObjC-specific no-ops, and try making an imprecise alias query.
673 const Value *UA = GetUnderlyingObjCPtr(SA);
674 const Value *UB = GetUnderlyingObjCPtr(SB);
675 if (UA != SA || UB != SB) {
676 Result = AliasAnalysis::alias(Location(UA), Location(UB));
677 // We can't use MustAlias or PartialAlias results here because
678 // GetUnderlyingObjCPtr may return an offsetted pointer value.
679 if (Result == NoAlias)
680 return NoAlias;
681 }
682
683 // If that failed, fail. We don't need to chain here, since that's covered
684 // by the earlier precise query.
685 return MayAlias;
686}
687
688bool
689ObjCARCAliasAnalysis::pointsToConstantMemory(const Location &Loc,
690 bool OrLocal) {
691 if (!EnableARCOpts)
692 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
693
694 // First, strip off no-ops, including ObjC-specific no-ops, and try making
695 // a precise alias query.
696 const Value *S = StripPointerCastsAndObjCCalls(Loc.Ptr);
697 if (AliasAnalysis::pointsToConstantMemory(Location(S, Loc.Size, Loc.TBAATag),
698 OrLocal))
699 return true;
700
701 // If that failed, climb to the underlying object, including climbing through
702 // ObjC-specific no-ops, and try making an imprecise alias query.
703 const Value *U = GetUnderlyingObjCPtr(S);
704 if (U != S)
705 return AliasAnalysis::pointsToConstantMemory(Location(U), OrLocal);
706
707 // If that failed, fail. We don't need to chain here, since that's covered
708 // by the earlier precise query.
709 return false;
710}
711
712AliasAnalysis::ModRefBehavior
713ObjCARCAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
714 // We have nothing to do. Just chain to the next AliasAnalysis.
715 return AliasAnalysis::getModRefBehavior(CS);
716}
717
718AliasAnalysis::ModRefBehavior
719ObjCARCAliasAnalysis::getModRefBehavior(const Function *F) {
720 if (!EnableARCOpts)
721 return AliasAnalysis::getModRefBehavior(F);
722
723 switch (GetFunctionClass(F)) {
724 case IC_NoopCast:
725 return DoesNotAccessMemory;
726 default:
727 break;
728 }
729
730 return AliasAnalysis::getModRefBehavior(F);
731}
732
733AliasAnalysis::ModRefResult
734ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS, const Location &Loc) {
735 if (!EnableARCOpts)
736 return AliasAnalysis::getModRefInfo(CS, Loc);
737
738 switch (GetBasicInstructionClass(CS.getInstruction())) {
739 case IC_Retain:
740 case IC_RetainRV:
741 case IC_RetainBlock:
742 case IC_Autorelease:
743 case IC_AutoreleaseRV:
744 case IC_NoopCast:
745 case IC_AutoreleasepoolPush:
746 case IC_FusedRetainAutorelease:
747 case IC_FusedRetainAutoreleaseRV:
748 // These functions don't access any memory visible to the compiler.
749 return NoModRef;
750 default:
751 break;
752 }
753
754 return AliasAnalysis::getModRefInfo(CS, Loc);
755}
756
757AliasAnalysis::ModRefResult
758ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
759 ImmutableCallSite CS2) {
760 // TODO: Theoretically we could check for dependencies between objc_* calls
761 // and OnlyAccessesArgumentPointees calls or other well-behaved calls.
762 return AliasAnalysis::getModRefInfo(CS1, CS2);
763}
764
765//===----------------------------------------------------------------------===//
766// ARC expansion.
767//===----------------------------------------------------------------------===//
768
769#include "llvm/Support/InstIterator.h"
770#include "llvm/Transforms/Scalar.h"
771
772namespace {
773 /// ObjCARCExpand - Early ARC transformations.
774 class ObjCARCExpand : public FunctionPass {
775 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000776 virtual bool doInitialization(Module &M);
John McCall9fbd3182011-06-15 23:37:01 +0000777 virtual bool runOnFunction(Function &F);
778
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000779 /// Run - A flag indicating whether this optimization pass should run.
780 bool Run;
781
John McCall9fbd3182011-06-15 23:37:01 +0000782 public:
783 static char ID;
784 ObjCARCExpand() : FunctionPass(ID) {
785 initializeObjCARCExpandPass(*PassRegistry::getPassRegistry());
786 }
787 };
788}
789
790char ObjCARCExpand::ID = 0;
791INITIALIZE_PASS(ObjCARCExpand,
792 "objc-arc-expand", "ObjC ARC expansion", false, false)
793
794Pass *llvm::createObjCARCExpandPass() {
795 return new ObjCARCExpand();
796}
797
798void ObjCARCExpand::getAnalysisUsage(AnalysisUsage &AU) const {
799 AU.setPreservesCFG();
800}
801
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000802bool ObjCARCExpand::doInitialization(Module &M) {
803 Run = ModuleHasARC(M);
804 return false;
805}
806
John McCall9fbd3182011-06-15 23:37:01 +0000807bool ObjCARCExpand::runOnFunction(Function &F) {
808 if (!EnableARCOpts)
809 return false;
810
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000811 // If nothing in the Module uses ARC, don't do anything.
812 if (!Run)
813 return false;
814
John McCall9fbd3182011-06-15 23:37:01 +0000815 bool Changed = false;
816
817 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
818 Instruction *Inst = &*I;
819
820 switch (GetBasicInstructionClass(Inst)) {
821 case IC_Retain:
822 case IC_RetainRV:
823 case IC_Autorelease:
824 case IC_AutoreleaseRV:
825 case IC_FusedRetainAutorelease:
826 case IC_FusedRetainAutoreleaseRV:
827 // These calls return their argument verbatim, as a low-level
828 // optimization. However, this makes high-level optimizations
829 // harder. Undo any uses of this optimization that the front-end
830 // emitted here. We'll redo them in a later pass.
831 Changed = true;
832 Inst->replaceAllUsesWith(cast<CallInst>(Inst)->getArgOperand(0));
833 break;
834 default:
835 break;
836 }
837 }
838
839 return Changed;
840}
841
842//===----------------------------------------------------------------------===//
843// ARC optimization.
844//===----------------------------------------------------------------------===//
845
846// TODO: On code like this:
847//
848// objc_retain(%x)
849// stuff_that_cannot_release()
850// objc_autorelease(%x)
851// stuff_that_cannot_release()
852// objc_retain(%x)
853// stuff_that_cannot_release()
854// objc_autorelease(%x)
855//
856// The second retain and autorelease can be deleted.
857
858// TODO: It should be possible to delete
859// objc_autoreleasePoolPush and objc_autoreleasePoolPop
860// pairs if nothing is actually autoreleased between them. Also, autorelease
861// calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
862// after inlining) can be turned into plain release calls.
863
864// TODO: Critical-edge splitting. If the optimial insertion point is
865// a critical edge, the current algorithm has to fail, because it doesn't
866// know how to split edges. It should be possible to make the optimizer
867// think in terms of edges, rather than blocks, and then split critical
868// edges on demand.
869
870// TODO: OptimizeSequences could generalized to be Interprocedural.
871
872// TODO: Recognize that a bunch of other objc runtime calls have
873// non-escaping arguments and non-releasing arguments, and may be
874// non-autoreleasing.
875
876// TODO: Sink autorelease calls as far as possible. Unfortunately we
877// usually can't sink them past other calls, which would be the main
878// case where it would be useful.
879
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000880/// TODO: The pointer returned from objc_loadWeakRetained is retained.
881
John McCall9fbd3182011-06-15 23:37:01 +0000882#include "llvm/GlobalAlias.h"
John McCall9fbd3182011-06-15 23:37:01 +0000883#include "llvm/Constants.h"
884#include "llvm/LLVMContext.h"
885#include "llvm/Support/ErrorHandling.h"
886#include "llvm/Support/CFG.h"
887#include "llvm/ADT/PostOrderIterator.h"
888#include "llvm/ADT/Statistic.h"
889
890STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
891STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
892STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
893STATISTIC(NumRets, "Number of return value forwarding "
894 "retain+autoreleaes eliminated");
895STATISTIC(NumRRs, "Number of retain+release paths eliminated");
896STATISTIC(NumPeeps, "Number of calls peephole-optimized");
897
898namespace {
899 /// ProvenanceAnalysis - This is similar to BasicAliasAnalysis, and it
900 /// uses many of the same techniques, except it uses special ObjC-specific
901 /// reasoning about pointer relationships.
902 class ProvenanceAnalysis {
903 AliasAnalysis *AA;
904
905 typedef std::pair<const Value *, const Value *> ValuePairTy;
906 typedef DenseMap<ValuePairTy, bool> CachedResultsTy;
907 CachedResultsTy CachedResults;
908
909 bool relatedCheck(const Value *A, const Value *B);
910 bool relatedSelect(const SelectInst *A, const Value *B);
911 bool relatedPHI(const PHINode *A, const Value *B);
912
913 // Do not implement.
914 void operator=(const ProvenanceAnalysis &);
915 ProvenanceAnalysis(const ProvenanceAnalysis &);
916
917 public:
918 ProvenanceAnalysis() {}
919
920 void setAA(AliasAnalysis *aa) { AA = aa; }
921
922 AliasAnalysis *getAA() const { return AA; }
923
924 bool related(const Value *A, const Value *B);
925
926 void clear() {
927 CachedResults.clear();
928 }
929 };
930}
931
932bool ProvenanceAnalysis::relatedSelect(const SelectInst *A, const Value *B) {
933 // If the values are Selects with the same condition, we can do a more precise
934 // check: just check for relations between the values on corresponding arms.
935 if (const SelectInst *SB = dyn_cast<SelectInst>(B))
936 if (A->getCondition() == SB->getCondition()) {
937 if (related(A->getTrueValue(), SB->getTrueValue()))
938 return true;
939 if (related(A->getFalseValue(), SB->getFalseValue()))
940 return true;
941 return false;
942 }
943
944 // Check both arms of the Select node individually.
945 if (related(A->getTrueValue(), B))
946 return true;
947 if (related(A->getFalseValue(), B))
948 return true;
949
950 // The arms both checked out.
951 return false;
952}
953
954bool ProvenanceAnalysis::relatedPHI(const PHINode *A, const Value *B) {
955 // If the values are PHIs in the same block, we can do a more precise as well
956 // as efficient check: just check for relations between the values on
957 // corresponding edges.
958 if (const PHINode *PNB = dyn_cast<PHINode>(B))
959 if (PNB->getParent() == A->getParent()) {
960 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i)
961 if (related(A->getIncomingValue(i),
962 PNB->getIncomingValueForBlock(A->getIncomingBlock(i))))
963 return true;
964 return false;
965 }
966
967 // Check each unique source of the PHI node against B.
968 SmallPtrSet<const Value *, 4> UniqueSrc;
969 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i) {
970 const Value *PV1 = A->getIncomingValue(i);
971 if (UniqueSrc.insert(PV1) && related(PV1, B))
972 return true;
973 }
974
975 // All of the arms checked out.
976 return false;
977}
978
979/// isStoredObjCPointer - Test if the value of P, or any value covered by its
980/// provenance, is ever stored within the function (not counting callees).
981static bool isStoredObjCPointer(const Value *P) {
982 SmallPtrSet<const Value *, 8> Visited;
983 SmallVector<const Value *, 8> Worklist;
984 Worklist.push_back(P);
985 Visited.insert(P);
986 do {
987 P = Worklist.pop_back_val();
988 for (Value::const_use_iterator UI = P->use_begin(), UE = P->use_end();
989 UI != UE; ++UI) {
990 const User *Ur = *UI;
991 if (isa<StoreInst>(Ur)) {
992 if (UI.getOperandNo() == 0)
993 // The pointer is stored.
994 return true;
995 // The pointed is stored through.
996 continue;
997 }
998 if (isa<CallInst>(Ur))
999 // The pointer is passed as an argument, ignore this.
1000 continue;
1001 if (isa<PtrToIntInst>(P))
1002 // Assume the worst.
1003 return true;
1004 if (Visited.insert(Ur))
1005 Worklist.push_back(Ur);
1006 }
1007 } while (!Worklist.empty());
1008
1009 // Everything checked out.
1010 return false;
1011}
1012
1013bool ProvenanceAnalysis::relatedCheck(const Value *A, const Value *B) {
1014 // Skip past provenance pass-throughs.
1015 A = GetUnderlyingObjCPtr(A);
1016 B = GetUnderlyingObjCPtr(B);
1017
1018 // Quick check.
1019 if (A == B)
1020 return true;
1021
1022 // Ask regular AliasAnalysis, for a first approximation.
1023 switch (AA->alias(A, B)) {
1024 case AliasAnalysis::NoAlias:
1025 return false;
1026 case AliasAnalysis::MustAlias:
1027 case AliasAnalysis::PartialAlias:
1028 return true;
1029 case AliasAnalysis::MayAlias:
1030 break;
1031 }
1032
1033 bool AIsIdentified = IsObjCIdentifiedObject(A);
1034 bool BIsIdentified = IsObjCIdentifiedObject(B);
1035
1036 // An ObjC-Identified object can't alias a load if it is never locally stored.
1037 if (AIsIdentified) {
1038 if (BIsIdentified) {
1039 // If both pointers have provenance, they can be directly compared.
1040 if (A != B)
1041 return false;
1042 } else {
1043 if (isa<LoadInst>(B))
1044 return isStoredObjCPointer(A);
1045 }
1046 } else {
1047 if (BIsIdentified && isa<LoadInst>(A))
1048 return isStoredObjCPointer(B);
1049 }
1050
1051 // Special handling for PHI and Select.
1052 if (const PHINode *PN = dyn_cast<PHINode>(A))
1053 return relatedPHI(PN, B);
1054 if (const PHINode *PN = dyn_cast<PHINode>(B))
1055 return relatedPHI(PN, A);
1056 if (const SelectInst *S = dyn_cast<SelectInst>(A))
1057 return relatedSelect(S, B);
1058 if (const SelectInst *S = dyn_cast<SelectInst>(B))
1059 return relatedSelect(S, A);
1060
1061 // Conservative.
1062 return true;
1063}
1064
1065bool ProvenanceAnalysis::related(const Value *A, const Value *B) {
1066 // Begin by inserting a conservative value into the map. If the insertion
1067 // fails, we have the answer already. If it succeeds, leave it there until we
1068 // compute the real answer to guard against recursive queries.
1069 if (A > B) std::swap(A, B);
1070 std::pair<CachedResultsTy::iterator, bool> Pair =
1071 CachedResults.insert(std::make_pair(ValuePairTy(A, B), true));
1072 if (!Pair.second)
1073 return Pair.first->second;
1074
1075 bool Result = relatedCheck(A, B);
1076 CachedResults[ValuePairTy(A, B)] = Result;
1077 return Result;
1078}
1079
1080namespace {
1081 // Sequence - A sequence of states that a pointer may go through in which an
1082 // objc_retain and objc_release are actually needed.
1083 enum Sequence {
1084 S_None,
1085 S_Retain, ///< objc_retain(x)
1086 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement
1087 S_Use, ///< any use of x
1088 S_Stop, ///< like S_Release, but code motion is stopped
1089 S_Release, ///< objc_release(x)
1090 S_MovableRelease ///< objc_release(x), !clang.imprecise_release
1091 };
1092}
1093
1094static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
1095 // The easy cases.
1096 if (A == B)
1097 return A;
1098 if (A == S_None || B == S_None)
1099 return S_None;
1100
John McCall9fbd3182011-06-15 23:37:01 +00001101 if (A > B) std::swap(A, B);
1102 if (TopDown) {
1103 // Choose the side which is further along in the sequence.
Dan Gohmana7f7db22011-08-12 00:26:31 +00001104 if ((A == S_Retain || A == S_CanRelease) &&
1105 (B == S_CanRelease || B == S_Use))
John McCall9fbd3182011-06-15 23:37:01 +00001106 return B;
1107 } else {
1108 // Choose the side which is further along in the sequence.
1109 if ((A == S_Use || A == S_CanRelease) &&
Dan Gohmana7f7db22011-08-12 00:26:31 +00001110 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
John McCall9fbd3182011-06-15 23:37:01 +00001111 return A;
1112 // If both sides are releases, choose the more conservative one.
1113 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
1114 return A;
1115 if (A == S_Release && B == S_MovableRelease)
1116 return A;
1117 }
1118
1119 return S_None;
1120}
1121
1122namespace {
1123 /// RRInfo - Unidirectional information about either a
1124 /// retain-decrement-use-release sequence or release-use-decrement-retain
1125 /// reverese sequence.
1126 struct RRInfo {
1127 /// KnownIncremented - After an objc_retain, the reference count of the
1128 /// referenced object is known to be positive. Similarly, before an
1129 /// objc_release, the reference count of the referenced object is known to
1130 /// be positive. If there are retain-release pairs in code regions where the
1131 /// retain count is known to be positive, they can be eliminated, regardless
1132 /// of any side effects between them.
1133 bool KnownIncremented;
1134
1135 /// IsRetainBlock - True if the Calls are objc_retainBlock calls (as
1136 /// opposed to objc_retain calls).
1137 bool IsRetainBlock;
1138
1139 /// IsTailCallRelease - True of the objc_release calls are all marked
1140 /// with the "tail" keyword.
1141 bool IsTailCallRelease;
1142
1143 /// ReleaseMetadata - If the Calls are objc_release calls and they all have
1144 /// a clang.imprecise_release tag, this is the metadata tag.
1145 MDNode *ReleaseMetadata;
1146
1147 /// Calls - For a top-down sequence, the set of objc_retains or
1148 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
1149 SmallPtrSet<Instruction *, 2> Calls;
1150
1151 /// ReverseInsertPts - The set of optimal insert positions for
1152 /// moving calls in the opposite sequence.
1153 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
1154
1155 RRInfo() :
1156 KnownIncremented(false), IsRetainBlock(false), IsTailCallRelease(false),
1157 ReleaseMetadata(0) {}
1158
1159 void clear();
1160 };
1161}
1162
1163void RRInfo::clear() {
1164 KnownIncremented = false;
1165 IsRetainBlock = false;
1166 IsTailCallRelease = false;
1167 ReleaseMetadata = 0;
1168 Calls.clear();
1169 ReverseInsertPts.clear();
1170}
1171
1172namespace {
1173 /// PtrState - This class summarizes several per-pointer runtime properties
1174 /// which are propogated through the flow graph.
1175 class PtrState {
1176 /// RefCount - The known minimum number of reference count increments.
1177 unsigned RefCount;
1178
1179 /// Seq - The current position in the sequence.
1180 Sequence Seq;
1181
1182 public:
1183 /// RRI - Unidirectional information about the current sequence.
1184 /// TODO: Encapsulate this better.
1185 RRInfo RRI;
1186
1187 PtrState() : RefCount(0), Seq(S_None) {}
1188
Dan Gohmana7f7db22011-08-12 00:26:31 +00001189 void SetAtLeastOneRefCount() {
1190 if (RefCount == 0) RefCount = 1;
1191 }
1192
John McCall9fbd3182011-06-15 23:37:01 +00001193 void IncrementRefCount() {
1194 if (RefCount != UINT_MAX) ++RefCount;
1195 }
1196
1197 void DecrementRefCount() {
1198 if (RefCount != 0) --RefCount;
1199 }
1200
John McCall9fbd3182011-06-15 23:37:01 +00001201 bool IsKnownIncremented() const {
1202 return RefCount > 0;
1203 }
1204
1205 void SetSeq(Sequence NewSeq) {
1206 Seq = NewSeq;
1207 }
1208
1209 void SetSeqToRelease(MDNode *M) {
1210 if (Seq == S_None || Seq == S_Use) {
1211 Seq = M ? S_MovableRelease : S_Release;
1212 RRI.ReleaseMetadata = M;
1213 } else if (Seq != S_MovableRelease || RRI.ReleaseMetadata != M) {
1214 Seq = S_Release;
1215 RRI.ReleaseMetadata = 0;
1216 }
1217 }
1218
1219 Sequence GetSeq() const {
1220 return Seq;
1221 }
1222
1223 void ClearSequenceProgress() {
1224 Seq = S_None;
1225 RRI.clear();
1226 }
1227
1228 void Merge(const PtrState &Other, bool TopDown);
1229 };
1230}
1231
1232void
1233PtrState::Merge(const PtrState &Other, bool TopDown) {
1234 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
1235 RefCount = std::min(RefCount, Other.RefCount);
1236
1237 // We can't merge a plain objc_retain with an objc_retainBlock.
1238 if (RRI.IsRetainBlock != Other.RRI.IsRetainBlock)
1239 Seq = S_None;
1240
1241 if (Seq == S_None) {
1242 RRI.clear();
1243 } else {
1244 // Conservatively merge the ReleaseMetadata information.
1245 if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
1246 RRI.ReleaseMetadata = 0;
1247
1248 RRI.KnownIncremented = RRI.KnownIncremented && Other.RRI.KnownIncremented;
1249 RRI.IsTailCallRelease = RRI.IsTailCallRelease && Other.RRI.IsTailCallRelease;
1250 RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
1251 RRI.ReverseInsertPts.insert(Other.RRI.ReverseInsertPts.begin(),
1252 Other.RRI.ReverseInsertPts.end());
1253 }
1254}
1255
1256namespace {
1257 /// BBState - Per-BasicBlock state.
1258 class BBState {
1259 /// TopDownPathCount - The number of unique control paths from the entry
1260 /// which can reach this block.
1261 unsigned TopDownPathCount;
1262
1263 /// BottomUpPathCount - The number of unique control paths to exits
1264 /// from this block.
1265 unsigned BottomUpPathCount;
1266
1267 /// MapTy - A type for PerPtrTopDown and PerPtrBottomUp.
1268 typedef MapVector<const Value *, PtrState> MapTy;
1269
1270 /// PerPtrTopDown - The top-down traversal uses this to record information
1271 /// known about a pointer at the bottom of each block.
1272 MapTy PerPtrTopDown;
1273
1274 /// PerPtrBottomUp - The bottom-up traversal uses this to record information
1275 /// known about a pointer at the top of each block.
1276 MapTy PerPtrBottomUp;
1277
1278 public:
1279 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
1280
1281 typedef MapTy::iterator ptr_iterator;
1282 typedef MapTy::const_iterator ptr_const_iterator;
1283
1284 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
1285 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
1286 ptr_const_iterator top_down_ptr_begin() const {
1287 return PerPtrTopDown.begin();
1288 }
1289 ptr_const_iterator top_down_ptr_end() const {
1290 return PerPtrTopDown.end();
1291 }
1292
1293 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
1294 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
1295 ptr_const_iterator bottom_up_ptr_begin() const {
1296 return PerPtrBottomUp.begin();
1297 }
1298 ptr_const_iterator bottom_up_ptr_end() const {
1299 return PerPtrBottomUp.end();
1300 }
1301
1302 /// SetAsEntry - Mark this block as being an entry block, which has one
1303 /// path from the entry by definition.
1304 void SetAsEntry() { TopDownPathCount = 1; }
1305
1306 /// SetAsExit - Mark this block as being an exit block, which has one
1307 /// path to an exit by definition.
1308 void SetAsExit() { BottomUpPathCount = 1; }
1309
1310 PtrState &getPtrTopDownState(const Value *Arg) {
1311 return PerPtrTopDown[Arg];
1312 }
1313
1314 PtrState &getPtrBottomUpState(const Value *Arg) {
1315 return PerPtrBottomUp[Arg];
1316 }
1317
1318 void clearBottomUpPointers() {
Evan Chenga81388f2011-08-04 18:40:26 +00001319 PerPtrBottomUp.clear();
John McCall9fbd3182011-06-15 23:37:01 +00001320 }
1321
1322 void clearTopDownPointers() {
1323 PerPtrTopDown.clear();
1324 }
1325
1326 void InitFromPred(const BBState &Other);
1327 void InitFromSucc(const BBState &Other);
1328 void MergePred(const BBState &Other);
1329 void MergeSucc(const BBState &Other);
1330
1331 /// GetAllPathCount - Return the number of possible unique paths from an
1332 /// entry to an exit which pass through this block. This is only valid
1333 /// after both the top-down and bottom-up traversals are complete.
1334 unsigned GetAllPathCount() const {
1335 return TopDownPathCount * BottomUpPathCount;
1336 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00001337
1338 /// IsVisitedTopDown - Test whether the block for this BBState has been
1339 /// visited by the top-down portion of the algorithm.
1340 bool isVisitedTopDown() const {
1341 return TopDownPathCount != 0;
1342 }
John McCall9fbd3182011-06-15 23:37:01 +00001343 };
1344}
1345
1346void BBState::InitFromPred(const BBState &Other) {
1347 PerPtrTopDown = Other.PerPtrTopDown;
1348 TopDownPathCount = Other.TopDownPathCount;
1349}
1350
1351void BBState::InitFromSucc(const BBState &Other) {
1352 PerPtrBottomUp = Other.PerPtrBottomUp;
1353 BottomUpPathCount = Other.BottomUpPathCount;
1354}
1355
1356/// MergePred - The top-down traversal uses this to merge information about
1357/// predecessors to form the initial state for a new block.
1358void BBState::MergePred(const BBState &Other) {
1359 // Other.TopDownPathCount can be 0, in which case it is either dead or a
1360 // loop backedge. Loop backedges are special.
1361 TopDownPathCount += Other.TopDownPathCount;
1362
1363 // For each entry in the other set, if our set has an entry with the same key,
1364 // merge the entries. Otherwise, copy the entry and merge it with an empty
1365 // entry.
1366 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
1367 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
1368 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
1369 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1370 /*TopDown=*/true);
1371 }
1372
Dan Gohmanfa7eed12011-08-11 21:06:32 +00001373 // For each entry in our set, if the other set doesn't have an entry with the
John McCall9fbd3182011-06-15 23:37:01 +00001374 // same key, force it to merge with an empty entry.
1375 for (ptr_iterator MI = top_down_ptr_begin(),
1376 ME = top_down_ptr_end(); MI != ME; ++MI)
1377 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
1378 MI->second.Merge(PtrState(), /*TopDown=*/true);
1379}
1380
1381/// MergeSucc - The bottom-up traversal uses this to merge information about
1382/// successors to form the initial state for a new block.
1383void BBState::MergeSucc(const BBState &Other) {
1384 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
1385 // loop backedge. Loop backedges are special.
1386 BottomUpPathCount += Other.BottomUpPathCount;
1387
1388 // For each entry in the other set, if our set has an entry with the
1389 // same key, merge the entries. Otherwise, copy the entry and merge
1390 // it with an empty entry.
1391 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
1392 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
1393 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
1394 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1395 /*TopDown=*/false);
1396 }
1397
Dan Gohmanfa7eed12011-08-11 21:06:32 +00001398 // For each entry in our set, if the other set doesn't have an entry
John McCall9fbd3182011-06-15 23:37:01 +00001399 // with the same key, force it to merge with an empty entry.
1400 for (ptr_iterator MI = bottom_up_ptr_begin(),
1401 ME = bottom_up_ptr_end(); MI != ME; ++MI)
1402 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
1403 MI->second.Merge(PtrState(), /*TopDown=*/false);
1404}
1405
1406namespace {
1407 /// ObjCARCOpt - The main ARC optimization pass.
1408 class ObjCARCOpt : public FunctionPass {
1409 bool Changed;
1410 ProvenanceAnalysis PA;
1411
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00001412 /// Run - A flag indicating whether this optimization pass should run.
1413 bool Run;
1414
John McCall9fbd3182011-06-15 23:37:01 +00001415 /// RetainRVCallee, etc. - Declarations for ObjC runtime
1416 /// functions, for use in creating calls to them. These are initialized
1417 /// lazily to avoid cluttering up the Module with unused declarations.
1418 Constant *RetainRVCallee, *AutoreleaseRVCallee, *ReleaseCallee,
Dan Gohman44280692011-07-22 22:29:21 +00001419 *RetainCallee, *RetainBlockCallee, *AutoreleaseCallee;
John McCall9fbd3182011-06-15 23:37:01 +00001420
1421 /// UsedInThisFunciton - Flags which determine whether each of the
1422 /// interesting runtine functions is in fact used in the current function.
1423 unsigned UsedInThisFunction;
1424
1425 /// ImpreciseReleaseMDKind - The Metadata Kind for clang.imprecise_release
1426 /// metadata.
1427 unsigned ImpreciseReleaseMDKind;
1428
1429 Constant *getRetainRVCallee(Module *M);
1430 Constant *getAutoreleaseRVCallee(Module *M);
1431 Constant *getReleaseCallee(Module *M);
1432 Constant *getRetainCallee(Module *M);
Dan Gohman44280692011-07-22 22:29:21 +00001433 Constant *getRetainBlockCallee(Module *M);
John McCall9fbd3182011-06-15 23:37:01 +00001434 Constant *getAutoreleaseCallee(Module *M);
1435
1436 void OptimizeRetainCall(Function &F, Instruction *Retain);
1437 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
1438 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV);
1439 void OptimizeIndividualCalls(Function &F);
1440
1441 void CheckForCFGHazards(const BasicBlock *BB,
1442 DenseMap<const BasicBlock *, BBState> &BBStates,
1443 BBState &MyStates) const;
1444 bool VisitBottomUp(BasicBlock *BB,
1445 DenseMap<const BasicBlock *, BBState> &BBStates,
1446 MapVector<Value *, RRInfo> &Retains);
1447 bool VisitTopDown(BasicBlock *BB,
1448 DenseMap<const BasicBlock *, BBState> &BBStates,
1449 DenseMap<Value *, RRInfo> &Releases);
1450 bool Visit(Function &F,
1451 DenseMap<const BasicBlock *, BBState> &BBStates,
1452 MapVector<Value *, RRInfo> &Retains,
1453 DenseMap<Value *, RRInfo> &Releases);
1454
1455 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1456 MapVector<Value *, RRInfo> &Retains,
1457 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman44280692011-07-22 22:29:21 +00001458 SmallVectorImpl<Instruction *> &DeadInsts,
1459 Module *M);
John McCall9fbd3182011-06-15 23:37:01 +00001460
1461 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1462 MapVector<Value *, RRInfo> &Retains,
Dan Gohman44280692011-07-22 22:29:21 +00001463 DenseMap<Value *, RRInfo> &Releases,
1464 Module *M);
John McCall9fbd3182011-06-15 23:37:01 +00001465
1466 void OptimizeWeakCalls(Function &F);
1467
1468 bool OptimizeSequences(Function &F);
1469
1470 void OptimizeReturns(Function &F);
1471
1472 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1473 virtual bool doInitialization(Module &M);
1474 virtual bool runOnFunction(Function &F);
1475 virtual void releaseMemory();
1476
1477 public:
1478 static char ID;
1479 ObjCARCOpt() : FunctionPass(ID) {
1480 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1481 }
1482 };
1483}
1484
1485char ObjCARCOpt::ID = 0;
1486INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1487 "objc-arc", "ObjC ARC optimization", false, false)
1488INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1489INITIALIZE_PASS_END(ObjCARCOpt,
1490 "objc-arc", "ObjC ARC optimization", false, false)
1491
1492Pass *llvm::createObjCARCOptPass() {
1493 return new ObjCARCOpt();
1494}
1495
1496void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1497 AU.addRequired<ObjCARCAliasAnalysis>();
1498 AU.addRequired<AliasAnalysis>();
1499 // ARC optimization doesn't currently split critical edges.
1500 AU.setPreservesCFG();
1501}
1502
1503Constant *ObjCARCOpt::getRetainRVCallee(Module *M) {
1504 if (!RetainRVCallee) {
1505 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001506 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1507 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00001508 Params.push_back(I8X);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001509 FunctionType *FTy =
John McCall9fbd3182011-06-15 23:37:01 +00001510 FunctionType::get(I8X, Params, /*isVarArg=*/false);
1511 AttrListPtr Attributes;
1512 Attributes.addAttr(~0u, Attribute::NoUnwind);
1513 RetainRVCallee =
1514 M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy,
1515 Attributes);
1516 }
1517 return RetainRVCallee;
1518}
1519
1520Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1521 if (!AutoreleaseRVCallee) {
1522 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001523 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1524 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00001525 Params.push_back(I8X);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001526 FunctionType *FTy =
John McCall9fbd3182011-06-15 23:37:01 +00001527 FunctionType::get(I8X, Params, /*isVarArg=*/false);
1528 AttrListPtr Attributes;
1529 Attributes.addAttr(~0u, Attribute::NoUnwind);
1530 AutoreleaseRVCallee =
1531 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
1532 Attributes);
1533 }
1534 return AutoreleaseRVCallee;
1535}
1536
1537Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1538 if (!ReleaseCallee) {
1539 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001540 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00001541 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1542 AttrListPtr Attributes;
1543 Attributes.addAttr(~0u, Attribute::NoUnwind);
1544 ReleaseCallee =
1545 M->getOrInsertFunction(
1546 "objc_release",
1547 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
1548 Attributes);
1549 }
1550 return ReleaseCallee;
1551}
1552
1553Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1554 if (!RetainCallee) {
1555 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001556 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00001557 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1558 AttrListPtr Attributes;
1559 Attributes.addAttr(~0u, Attribute::NoUnwind);
1560 RetainCallee =
1561 M->getOrInsertFunction(
1562 "objc_retain",
1563 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1564 Attributes);
1565 }
1566 return RetainCallee;
1567}
1568
Dan Gohman44280692011-07-22 22:29:21 +00001569Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1570 if (!RetainBlockCallee) {
1571 LLVMContext &C = M->getContext();
1572 std::vector<Type *> Params;
1573 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1574 AttrListPtr Attributes;
1575 Attributes.addAttr(~0u, Attribute::NoUnwind);
1576 RetainBlockCallee =
1577 M->getOrInsertFunction(
1578 "objc_retainBlock",
1579 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1580 Attributes);
1581 }
1582 return RetainBlockCallee;
1583}
1584
John McCall9fbd3182011-06-15 23:37:01 +00001585Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1586 if (!AutoreleaseCallee) {
1587 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001588 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00001589 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1590 AttrListPtr Attributes;
1591 Attributes.addAttr(~0u, Attribute::NoUnwind);
1592 AutoreleaseCallee =
1593 M->getOrInsertFunction(
1594 "objc_autorelease",
1595 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1596 Attributes);
1597 }
1598 return AutoreleaseCallee;
1599}
1600
1601/// CanAlterRefCount - Test whether the given instruction can result in a
1602/// reference count modification (positive or negative) for the pointer's
1603/// object.
1604static bool
1605CanAlterRefCount(const Instruction *Inst, const Value *Ptr,
1606 ProvenanceAnalysis &PA, InstructionClass Class) {
1607 switch (Class) {
1608 case IC_Autorelease:
1609 case IC_AutoreleaseRV:
1610 case IC_User:
1611 // These operations never directly modify a reference count.
1612 return false;
1613 default: break;
1614 }
1615
1616 ImmutableCallSite CS = static_cast<const Value *>(Inst);
1617 assert(CS && "Only calls can alter reference counts!");
1618
1619 // See if AliasAnalysis can help us with the call.
1620 AliasAnalysis::ModRefBehavior MRB = PA.getAA()->getModRefBehavior(CS);
1621 if (AliasAnalysis::onlyReadsMemory(MRB))
1622 return false;
1623 if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
1624 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1625 I != E; ++I) {
1626 const Value *Op = *I;
1627 if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1628 return true;
1629 }
1630 return false;
1631 }
1632
1633 // Assume the worst.
1634 return true;
1635}
1636
1637/// CanUse - Test whether the given instruction can "use" the given pointer's
1638/// object in a way that requires the reference count to be positive.
1639static bool
1640CanUse(const Instruction *Inst, const Value *Ptr, ProvenanceAnalysis &PA,
1641 InstructionClass Class) {
1642 // IC_Call operations (as opposed to IC_CallOrUser) never "use" objc pointers.
1643 if (Class == IC_Call)
1644 return false;
1645
1646 // Consider various instructions which may have pointer arguments which are
1647 // not "uses".
1648 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(Inst)) {
1649 // Comparing a pointer with null, or any other constant, isn't really a use,
1650 // because we don't care what the pointer points to, or about the values
1651 // of any other dynamic reference-counted pointers.
1652 if (!IsPotentialUse(ICI->getOperand(1)))
1653 return false;
1654 } else if (ImmutableCallSite CS = static_cast<const Value *>(Inst)) {
1655 // For calls, just check the arguments (and not the callee operand).
1656 for (ImmutableCallSite::arg_iterator OI = CS.arg_begin(),
1657 OE = CS.arg_end(); OI != OE; ++OI) {
1658 const Value *Op = *OI;
1659 if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1660 return true;
1661 }
1662 return false;
1663 } else if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1664 // Special-case stores, because we don't care about the stored value, just
1665 // the store address.
1666 const Value *Op = GetUnderlyingObjCPtr(SI->getPointerOperand());
1667 // If we can't tell what the underlying object was, assume there is a
1668 // dependence.
1669 return IsPotentialUse(Op) && PA.related(Op, Ptr);
1670 }
1671
1672 // Check each operand for a match.
1673 for (User::const_op_iterator OI = Inst->op_begin(), OE = Inst->op_end();
1674 OI != OE; ++OI) {
1675 const Value *Op = *OI;
1676 if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1677 return true;
1678 }
1679 return false;
1680}
1681
1682/// CanInterruptRV - Test whether the given instruction can autorelease
1683/// any pointer or cause an autoreleasepool pop.
1684static bool
1685CanInterruptRV(InstructionClass Class) {
1686 switch (Class) {
1687 case IC_AutoreleasepoolPop:
1688 case IC_CallOrUser:
1689 case IC_Call:
1690 case IC_Autorelease:
1691 case IC_AutoreleaseRV:
1692 case IC_FusedRetainAutorelease:
1693 case IC_FusedRetainAutoreleaseRV:
1694 return true;
1695 default:
1696 return false;
1697 }
1698}
1699
1700namespace {
1701 /// DependenceKind - There are several kinds of dependence-like concepts in
1702 /// use here.
1703 enum DependenceKind {
1704 NeedsPositiveRetainCount,
1705 CanChangeRetainCount,
1706 RetainAutoreleaseDep, ///< Blocks objc_retainAutorelease.
1707 RetainAutoreleaseRVDep, ///< Blocks objc_retainAutoreleaseReturnValue.
1708 RetainRVDep ///< Blocks objc_retainAutoreleasedReturnValue.
1709 };
1710}
1711
1712/// Depends - Test if there can be dependencies on Inst through Arg. This
1713/// function only tests dependencies relevant for removing pairs of calls.
1714static bool
1715Depends(DependenceKind Flavor, Instruction *Inst, const Value *Arg,
1716 ProvenanceAnalysis &PA) {
1717 // If we've reached the definition of Arg, stop.
1718 if (Inst == Arg)
1719 return true;
1720
1721 switch (Flavor) {
1722 case NeedsPositiveRetainCount: {
1723 InstructionClass Class = GetInstructionClass(Inst);
1724 switch (Class) {
1725 case IC_AutoreleasepoolPop:
1726 case IC_AutoreleasepoolPush:
1727 case IC_None:
1728 return false;
1729 default:
1730 return CanUse(Inst, Arg, PA, Class);
1731 }
1732 }
1733
1734 case CanChangeRetainCount: {
1735 InstructionClass Class = GetInstructionClass(Inst);
1736 switch (Class) {
1737 case IC_AutoreleasepoolPop:
1738 // Conservatively assume this can decrement any count.
1739 return true;
1740 case IC_AutoreleasepoolPush:
1741 case IC_None:
1742 return false;
1743 default:
1744 return CanAlterRefCount(Inst, Arg, PA, Class);
1745 }
1746 }
1747
1748 case RetainAutoreleaseDep:
1749 switch (GetBasicInstructionClass(Inst)) {
1750 case IC_AutoreleasepoolPop:
1751 // Don't merge an objc_autorelease with an objc_retain inside a different
1752 // autoreleasepool scope.
1753 return true;
1754 case IC_Retain:
1755 case IC_RetainRV:
1756 // Check for a retain of the same pointer for merging.
1757 return GetObjCArg(Inst) == Arg;
1758 default:
1759 // Nothing else matters for objc_retainAutorelease formation.
1760 return false;
1761 }
1762 break;
1763
1764 case RetainAutoreleaseRVDep: {
1765 InstructionClass Class = GetBasicInstructionClass(Inst);
1766 switch (Class) {
1767 case IC_Retain:
1768 case IC_RetainRV:
1769 // Check for a retain of the same pointer for merging.
1770 return GetObjCArg(Inst) == Arg;
1771 default:
1772 // Anything that can autorelease interrupts
1773 // retainAutoreleaseReturnValue formation.
1774 return CanInterruptRV(Class);
1775 }
1776 break;
1777 }
1778
1779 case RetainRVDep:
1780 return CanInterruptRV(GetBasicInstructionClass(Inst));
1781 }
1782
1783 llvm_unreachable("Invalid dependence flavor");
1784 return true;
1785}
1786
1787/// FindDependencies - Walk up the CFG from StartPos (which is in StartBB) and
1788/// find local and non-local dependencies on Arg.
1789/// TODO: Cache results?
1790static void
1791FindDependencies(DependenceKind Flavor,
1792 const Value *Arg,
1793 BasicBlock *StartBB, Instruction *StartInst,
1794 SmallPtrSet<Instruction *, 4> &DependingInstructions,
1795 SmallPtrSet<const BasicBlock *, 4> &Visited,
1796 ProvenanceAnalysis &PA) {
1797 BasicBlock::iterator StartPos = StartInst;
1798
1799 SmallVector<std::pair<BasicBlock *, BasicBlock::iterator>, 4> Worklist;
1800 Worklist.push_back(std::make_pair(StartBB, StartPos));
1801 do {
1802 std::pair<BasicBlock *, BasicBlock::iterator> Pair =
1803 Worklist.pop_back_val();
1804 BasicBlock *LocalStartBB = Pair.first;
1805 BasicBlock::iterator LocalStartPos = Pair.second;
1806 BasicBlock::iterator StartBBBegin = LocalStartBB->begin();
1807 for (;;) {
1808 if (LocalStartPos == StartBBBegin) {
1809 pred_iterator PI(LocalStartBB), PE(LocalStartBB, false);
1810 if (PI == PE)
1811 // If we've reached the function entry, produce a null dependence.
1812 DependingInstructions.insert(0);
1813 else
1814 // Add the predecessors to the worklist.
1815 do {
1816 BasicBlock *PredBB = *PI;
1817 if (Visited.insert(PredBB))
1818 Worklist.push_back(std::make_pair(PredBB, PredBB->end()));
1819 } while (++PI != PE);
1820 break;
1821 }
1822
1823 Instruction *Inst = --LocalStartPos;
1824 if (Depends(Flavor, Inst, Arg, PA)) {
1825 DependingInstructions.insert(Inst);
1826 break;
1827 }
1828 }
1829 } while (!Worklist.empty());
1830
1831 // Determine whether the original StartBB post-dominates all of the blocks we
1832 // visited. If not, insert a sentinal indicating that most optimizations are
1833 // not safe.
1834 for (SmallPtrSet<const BasicBlock *, 4>::const_iterator I = Visited.begin(),
1835 E = Visited.end(); I != E; ++I) {
1836 const BasicBlock *BB = *I;
1837 if (BB == StartBB)
1838 continue;
1839 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
1840 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
1841 const BasicBlock *Succ = *SI;
1842 if (Succ != StartBB && !Visited.count(Succ)) {
1843 DependingInstructions.insert(reinterpret_cast<Instruction *>(-1));
1844 return;
1845 }
1846 }
1847 }
1848}
1849
1850static bool isNullOrUndef(const Value *V) {
1851 return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
1852}
1853
1854static bool isNoopInstruction(const Instruction *I) {
1855 return isa<BitCastInst>(I) ||
1856 (isa<GetElementPtrInst>(I) &&
1857 cast<GetElementPtrInst>(I)->hasAllZeroIndices());
1858}
1859
1860/// OptimizeRetainCall - Turn objc_retain into
1861/// objc_retainAutoreleasedReturnValue if the operand is a return value.
1862void
1863ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) {
1864 CallSite CS(GetObjCArg(Retain));
1865 Instruction *Call = CS.getInstruction();
1866 if (!Call) return;
1867 if (Call->getParent() != Retain->getParent()) return;
1868
1869 // Check that the call is next to the retain.
1870 BasicBlock::iterator I = Call;
1871 ++I;
1872 while (isNoopInstruction(I)) ++I;
1873 if (&*I != Retain)
1874 return;
1875
1876 // Turn it to an objc_retainAutoreleasedReturnValue..
1877 Changed = true;
1878 ++NumPeeps;
1879 cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent()));
1880}
1881
1882/// OptimizeRetainRVCall - Turn objc_retainAutoreleasedReturnValue into
1883/// objc_retain if the operand is not a return value. Or, if it can be
1884/// paired with an objc_autoreleaseReturnValue, delete the pair and
1885/// return true.
1886bool
1887ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
1888 // Check for the argument being from an immediately preceding call.
1889 Value *Arg = GetObjCArg(RetainRV);
1890 CallSite CS(Arg);
1891 if (Instruction *Call = CS.getInstruction())
1892 if (Call->getParent() == RetainRV->getParent()) {
1893 BasicBlock::iterator I = Call;
1894 ++I;
1895 while (isNoopInstruction(I)) ++I;
1896 if (&*I == RetainRV)
1897 return false;
1898 }
1899
1900 // Check for being preceded by an objc_autoreleaseReturnValue on the same
1901 // pointer. In this case, we can delete the pair.
1902 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
1903 if (I != Begin) {
1904 do --I; while (I != Begin && isNoopInstruction(I));
1905 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
1906 GetObjCArg(I) == Arg) {
1907 Changed = true;
1908 ++NumPeeps;
1909 EraseInstruction(I);
1910 EraseInstruction(RetainRV);
1911 return true;
1912 }
1913 }
1914
1915 // Turn it to a plain objc_retain.
1916 Changed = true;
1917 ++NumPeeps;
1918 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
1919 return false;
1920}
1921
1922/// OptimizeAutoreleaseRVCall - Turn objc_autoreleaseReturnValue into
1923/// objc_autorelease if the result is not used as a return value.
1924void
1925ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV) {
1926 // Check for a return of the pointer value.
1927 const Value *Ptr = GetObjCArg(AutoreleaseRV);
1928 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
1929 UI != UE; ++UI) {
1930 const User *I = *UI;
1931 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
1932 return;
1933 }
1934
1935 Changed = true;
1936 ++NumPeeps;
1937 cast<CallInst>(AutoreleaseRV)->
1938 setCalledFunction(getAutoreleaseCallee(F.getParent()));
1939}
1940
1941/// OptimizeIndividualCalls - Visit each call, one at a time, and make
1942/// simplifications without doing any additional analysis.
1943void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
1944 // Reset all the flags in preparation for recomputing them.
1945 UsedInThisFunction = 0;
1946
1947 // Visit all objc_* calls in F.
1948 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
1949 Instruction *Inst = &*I++;
1950 InstructionClass Class = GetBasicInstructionClass(Inst);
1951
1952 switch (Class) {
1953 default: break;
1954
1955 // Delete no-op casts. These function calls have special semantics, but
1956 // the semantics are entirely implemented via lowering in the front-end,
1957 // so by the time they reach the optimizer, they are just no-op calls
1958 // which return their argument.
1959 //
1960 // There are gray areas here, as the ability to cast reference-counted
1961 // pointers to raw void* and back allows code to break ARC assumptions,
1962 // however these are currently considered to be unimportant.
1963 case IC_NoopCast:
1964 Changed = true;
1965 ++NumNoops;
1966 EraseInstruction(Inst);
1967 continue;
1968
1969 // If the pointer-to-weak-pointer is null, it's undefined behavior.
1970 case IC_StoreWeak:
1971 case IC_LoadWeak:
1972 case IC_LoadWeakRetained:
1973 case IC_InitWeak:
1974 case IC_DestroyWeak: {
1975 CallInst *CI = cast<CallInst>(Inst);
1976 if (isNullOrUndef(CI->getArgOperand(0))) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001977 Type *Ty = CI->getArgOperand(0)->getType();
John McCall9fbd3182011-06-15 23:37:01 +00001978 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1979 Constant::getNullValue(Ty),
1980 CI);
1981 CI->replaceAllUsesWith(UndefValue::get(CI->getType()));
1982 CI->eraseFromParent();
1983 continue;
1984 }
1985 break;
1986 }
1987 case IC_CopyWeak:
1988 case IC_MoveWeak: {
1989 CallInst *CI = cast<CallInst>(Inst);
1990 if (isNullOrUndef(CI->getArgOperand(0)) ||
1991 isNullOrUndef(CI->getArgOperand(1))) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001992 Type *Ty = CI->getArgOperand(0)->getType();
John McCall9fbd3182011-06-15 23:37:01 +00001993 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1994 Constant::getNullValue(Ty),
1995 CI);
1996 CI->replaceAllUsesWith(UndefValue::get(CI->getType()));
1997 CI->eraseFromParent();
1998 continue;
1999 }
2000 break;
2001 }
2002 case IC_Retain:
2003 OptimizeRetainCall(F, Inst);
2004 break;
2005 case IC_RetainRV:
2006 if (OptimizeRetainRVCall(F, Inst))
2007 continue;
2008 break;
2009 case IC_AutoreleaseRV:
2010 OptimizeAutoreleaseRVCall(F, Inst);
2011 break;
2012 }
2013
2014 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
2015 if (IsAutorelease(Class) && Inst->use_empty()) {
2016 CallInst *Call = cast<CallInst>(Inst);
2017 const Value *Arg = Call->getArgOperand(0);
2018 Arg = FindSingleUseIdentifiedObject(Arg);
2019 if (Arg) {
2020 Changed = true;
2021 ++NumAutoreleases;
2022
2023 // Create the declaration lazily.
2024 LLVMContext &C = Inst->getContext();
2025 CallInst *NewCall =
2026 CallInst::Create(getReleaseCallee(F.getParent()),
2027 Call->getArgOperand(0), "", Call);
2028 NewCall->setMetadata(ImpreciseReleaseMDKind,
2029 MDNode::get(C, ArrayRef<Value *>()));
2030 EraseInstruction(Call);
2031 Inst = NewCall;
2032 Class = IC_Release;
2033 }
2034 }
2035
2036 // For functions which can never be passed stack arguments, add
2037 // a tail keyword.
2038 if (IsAlwaysTail(Class)) {
2039 Changed = true;
2040 cast<CallInst>(Inst)->setTailCall();
2041 }
2042
2043 // Set nounwind as needed.
2044 if (IsNoThrow(Class)) {
2045 Changed = true;
2046 cast<CallInst>(Inst)->setDoesNotThrow();
2047 }
2048
2049 if (!IsNoopOnNull(Class)) {
2050 UsedInThisFunction |= 1 << Class;
2051 continue;
2052 }
2053
2054 const Value *Arg = GetObjCArg(Inst);
2055
2056 // ARC calls with null are no-ops. Delete them.
2057 if (isNullOrUndef(Arg)) {
2058 Changed = true;
2059 ++NumNoops;
2060 EraseInstruction(Inst);
2061 continue;
2062 }
2063
2064 // Keep track of which of retain, release, autorelease, and retain_block
2065 // are actually present in this function.
2066 UsedInThisFunction |= 1 << Class;
2067
2068 // If Arg is a PHI, and one or more incoming values to the
2069 // PHI are null, and the call is control-equivalent to the PHI, and there
2070 // are no relevant side effects between the PHI and the call, the call
2071 // could be pushed up to just those paths with non-null incoming values.
2072 // For now, don't bother splitting critical edges for this.
2073 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
2074 Worklist.push_back(std::make_pair(Inst, Arg));
2075 do {
2076 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
2077 Inst = Pair.first;
2078 Arg = Pair.second;
2079
2080 const PHINode *PN = dyn_cast<PHINode>(Arg);
2081 if (!PN) continue;
2082
2083 // Determine if the PHI has any null operands, or any incoming
2084 // critical edges.
2085 bool HasNull = false;
2086 bool HasCriticalEdges = false;
2087 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2088 Value *Incoming =
2089 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2090 if (isNullOrUndef(Incoming))
2091 HasNull = true;
2092 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
2093 .getNumSuccessors() != 1) {
2094 HasCriticalEdges = true;
2095 break;
2096 }
2097 }
2098 // If we have null operands and no critical edges, optimize.
2099 if (!HasCriticalEdges && HasNull) {
2100 SmallPtrSet<Instruction *, 4> DependingInstructions;
2101 SmallPtrSet<const BasicBlock *, 4> Visited;
2102
2103 // Check that there is nothing that cares about the reference
2104 // count between the call and the phi.
2105 FindDependencies(NeedsPositiveRetainCount, Arg,
2106 Inst->getParent(), Inst,
2107 DependingInstructions, Visited, PA);
2108 if (DependingInstructions.size() == 1 &&
2109 *DependingInstructions.begin() == PN) {
2110 Changed = true;
2111 ++NumPartialNoops;
2112 // Clone the call into each predecessor that has a non-null value.
2113 CallInst *CInst = cast<CallInst>(Inst);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002114 Type *ParamTy = CInst->getArgOperand(0)->getType();
John McCall9fbd3182011-06-15 23:37:01 +00002115 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2116 Value *Incoming =
2117 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2118 if (!isNullOrUndef(Incoming)) {
2119 CallInst *Clone = cast<CallInst>(CInst->clone());
2120 Value *Op = PN->getIncomingValue(i);
2121 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
2122 if (Op->getType() != ParamTy)
2123 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
2124 Clone->setArgOperand(0, Op);
2125 Clone->insertBefore(InsertPos);
2126 Worklist.push_back(std::make_pair(Clone, Incoming));
2127 }
2128 }
2129 // Erase the original call.
2130 EraseInstruction(CInst);
2131 continue;
2132 }
2133 }
2134 } while (!Worklist.empty());
2135 }
2136}
2137
2138/// CheckForCFGHazards - Check for critical edges, loop boundaries, irreducible
2139/// control flow, or other CFG structures where moving code across the edge
2140/// would result in it being executed more.
2141void
2142ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
2143 DenseMap<const BasicBlock *, BBState> &BBStates,
2144 BBState &MyStates) const {
2145 // If any top-down local-use or possible-dec has a succ which is earlier in
2146 // the sequence, forget it.
2147 for (BBState::ptr_const_iterator I = MyStates.top_down_ptr_begin(),
2148 E = MyStates.top_down_ptr_end(); I != E; ++I)
2149 switch (I->second.GetSeq()) {
2150 default: break;
2151 case S_Use: {
2152 const Value *Arg = I->first;
2153 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2154 bool SomeSuccHasSame = false;
2155 bool AllSuccsHaveSame = true;
Dan Gohmana7f7db22011-08-12 00:26:31 +00002156 PtrState &S = MyStates.getPtrTopDownState(Arg);
2157 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2158 PtrState &SuccS = BBStates[*SI].getPtrBottomUpState(Arg);
2159 switch (SuccS.GetSeq()) {
John McCall9fbd3182011-06-15 23:37:01 +00002160 case S_None:
Dan Gohmana7f7db22011-08-12 00:26:31 +00002161 case S_CanRelease: {
2162 if (!S.RRI.KnownIncremented && !SuccS.RRI.KnownIncremented)
2163 S.ClearSequenceProgress();
2164 continue;
2165 }
John McCall9fbd3182011-06-15 23:37:01 +00002166 case S_Use:
2167 SomeSuccHasSame = true;
2168 break;
2169 case S_Stop:
2170 case S_Release:
2171 case S_MovableRelease:
Dan Gohmana7f7db22011-08-12 00:26:31 +00002172 if (!S.RRI.KnownIncremented && !SuccS.RRI.KnownIncremented)
2173 AllSuccsHaveSame = false;
John McCall9fbd3182011-06-15 23:37:01 +00002174 break;
2175 case S_Retain:
2176 llvm_unreachable("bottom-up pointer in retain state!");
2177 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002178 }
John McCall9fbd3182011-06-15 23:37:01 +00002179 // If the state at the other end of any of the successor edges
2180 // matches the current state, require all edges to match. This
2181 // guards against loops in the middle of a sequence.
2182 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002183 S.ClearSequenceProgress();
John McCall9fbd3182011-06-15 23:37:01 +00002184 }
2185 case S_CanRelease: {
2186 const Value *Arg = I->first;
2187 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2188 bool SomeSuccHasSame = false;
2189 bool AllSuccsHaveSame = true;
Dan Gohmana7f7db22011-08-12 00:26:31 +00002190 PtrState &S = MyStates.getPtrTopDownState(Arg);
2191 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2192 PtrState &SuccS = BBStates[*SI].getPtrBottomUpState(Arg);
2193 switch (SuccS.GetSeq()) {
2194 case S_None: {
2195 if (!S.RRI.KnownIncremented && !SuccS.RRI.KnownIncremented)
2196 S.ClearSequenceProgress();
2197 continue;
2198 }
John McCall9fbd3182011-06-15 23:37:01 +00002199 case S_CanRelease:
2200 SomeSuccHasSame = true;
2201 break;
2202 case S_Stop:
2203 case S_Release:
2204 case S_MovableRelease:
2205 case S_Use:
Dan Gohmana7f7db22011-08-12 00:26:31 +00002206 if (!S.RRI.KnownIncremented && !SuccS.RRI.KnownIncremented)
2207 AllSuccsHaveSame = false;
John McCall9fbd3182011-06-15 23:37:01 +00002208 break;
2209 case S_Retain:
2210 llvm_unreachable("bottom-up pointer in retain state!");
2211 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002212 }
John McCall9fbd3182011-06-15 23:37:01 +00002213 // If the state at the other end of any of the successor edges
2214 // matches the current state, require all edges to match. This
2215 // guards against loops in the middle of a sequence.
2216 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002217 S.ClearSequenceProgress();
John McCall9fbd3182011-06-15 23:37:01 +00002218 }
2219 }
2220}
2221
2222bool
2223ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2224 DenseMap<const BasicBlock *, BBState> &BBStates,
2225 MapVector<Value *, RRInfo> &Retains) {
2226 bool NestingDetected = false;
2227 BBState &MyStates = BBStates[BB];
2228
2229 // Merge the states from each successor to compute the initial state
2230 // for the current block.
2231 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2232 succ_const_iterator SI(TI), SE(TI, false);
2233 if (SI == SE)
2234 MyStates.SetAsExit();
2235 else
2236 do {
2237 const BasicBlock *Succ = *SI++;
2238 if (Succ == BB)
2239 continue;
2240 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
Dan Gohmana7f7db22011-08-12 00:26:31 +00002241 // If we haven't seen this node yet, then we've found a CFG cycle.
2242 // Be optimistic here; it's CheckForCFGHazards' job detect trouble.
John McCall9fbd3182011-06-15 23:37:01 +00002243 if (I == BBStates.end())
2244 continue;
2245 MyStates.InitFromSucc(I->second);
2246 while (SI != SE) {
2247 Succ = *SI++;
2248 if (Succ != BB) {
2249 I = BBStates.find(Succ);
2250 if (I != BBStates.end())
2251 MyStates.MergeSucc(I->second);
2252 }
2253 }
2254 break;
2255 } while (SI != SE);
2256
2257 // Visit all the instructions, bottom-up.
2258 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2259 Instruction *Inst = llvm::prior(I);
2260 InstructionClass Class = GetInstructionClass(Inst);
2261 const Value *Arg = 0;
2262
2263 switch (Class) {
2264 case IC_Release: {
2265 Arg = GetObjCArg(Inst);
2266
2267 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2268
2269 // If we see two releases in a row on the same pointer. If so, make
2270 // a note, and we'll cicle back to revisit it after we've
2271 // hopefully eliminated the second release, which may allow us to
2272 // eliminate the first release too.
2273 // Theoretically we could implement removal of nested retain+release
2274 // pairs by making PtrState hold a stack of states, but this is
2275 // simple and avoids adding overhead for the non-nested case.
2276 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease)
2277 NestingDetected = true;
2278
2279 S.SetSeqToRelease(Inst->getMetadata(ImpreciseReleaseMDKind));
2280 S.RRI.clear();
2281 S.RRI.KnownIncremented = S.IsKnownIncremented();
2282 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2283 S.RRI.Calls.insert(Inst);
2284
2285 S.IncrementRefCount();
2286 break;
2287 }
2288 case IC_RetainBlock:
2289 case IC_Retain:
2290 case IC_RetainRV: {
2291 Arg = GetObjCArg(Inst);
2292
2293 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2294 S.DecrementRefCount();
Dan Gohmana7f7db22011-08-12 00:26:31 +00002295 S.SetAtLeastOneRefCount();
John McCall9fbd3182011-06-15 23:37:01 +00002296
2297 switch (S.GetSeq()) {
2298 case S_Stop:
2299 case S_Release:
2300 case S_MovableRelease:
2301 case S_Use:
2302 S.RRI.ReverseInsertPts.clear();
2303 // FALL THROUGH
2304 case S_CanRelease:
2305 // Don't do retain+release tracking for IC_RetainRV, because it's
2306 // better to let it remain as the first instruction after a call.
2307 if (Class != IC_RetainRV) {
2308 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2309 Retains[Inst] = S.RRI;
2310 }
2311 S.ClearSequenceProgress();
2312 break;
2313 case S_None:
2314 break;
2315 case S_Retain:
2316 llvm_unreachable("bottom-up pointer in retain state!");
2317 }
2318 break;
2319 }
2320 case IC_AutoreleasepoolPop:
2321 // Conservatively, clear MyStates for all known pointers.
2322 MyStates.clearBottomUpPointers();
2323 continue;
2324 case IC_AutoreleasepoolPush:
2325 case IC_None:
2326 // These are irrelevant.
2327 continue;
2328 default:
2329 break;
2330 }
2331
2332 // Consider any other possible effects of this instruction on each
2333 // pointer being tracked.
2334 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
2335 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
2336 const Value *Ptr = MI->first;
2337 if (Ptr == Arg)
2338 continue; // Handled above.
2339 PtrState &S = MI->second;
2340 Sequence Seq = S.GetSeq();
2341
Dan Gohmana7f7db22011-08-12 00:26:31 +00002342 // Check for possible releases. Note that we don't have to update
2343 // S's RefCount because any reference count modifications would be
2344 // done through a different provenance.
2345 if (!IsRetain(Class) && Class != IC_RetainBlock &&
2346 CanAlterRefCount(Inst, Ptr, PA, Class))
2347 switch (Seq) {
2348 case S_Use:
2349 S.SetSeq(S_CanRelease);
2350 continue;
2351 case S_CanRelease:
2352 case S_Release:
2353 case S_MovableRelease:
2354 case S_Stop:
2355 case S_None:
2356 break;
2357 case S_Retain:
2358 llvm_unreachable("bottom-up pointer in retain state!");
2359 }
John McCall9fbd3182011-06-15 23:37:01 +00002360
2361 // Check for possible direct uses.
2362 switch (Seq) {
2363 case S_Release:
2364 case S_MovableRelease:
2365 if (CanUse(Inst, Ptr, PA, Class)) {
2366 S.RRI.ReverseInsertPts.clear();
2367 S.RRI.ReverseInsertPts.insert(Inst);
2368 S.SetSeq(S_Use);
2369 } else if (Seq == S_Release &&
2370 (Class == IC_User || Class == IC_CallOrUser)) {
2371 // Non-movable releases depend on any possible objc pointer use.
2372 S.SetSeq(S_Stop);
2373 S.RRI.ReverseInsertPts.clear();
2374 S.RRI.ReverseInsertPts.insert(Inst);
2375 }
2376 break;
2377 case S_Stop:
2378 if (CanUse(Inst, Ptr, PA, Class))
2379 S.SetSeq(S_Use);
2380 break;
2381 case S_CanRelease:
2382 case S_Use:
2383 case S_None:
2384 break;
2385 case S_Retain:
2386 llvm_unreachable("bottom-up pointer in retain state!");
2387 }
2388 }
2389 }
2390
2391 return NestingDetected;
2392}
2393
2394bool
2395ObjCARCOpt::VisitTopDown(BasicBlock *BB,
2396 DenseMap<const BasicBlock *, BBState> &BBStates,
2397 DenseMap<Value *, RRInfo> &Releases) {
2398 bool NestingDetected = false;
2399 BBState &MyStates = BBStates[BB];
2400
2401 // Merge the states from each predecessor to compute the initial state
2402 // for the current block.
2403 const_pred_iterator PI(BB), PE(BB, false);
2404 if (PI == PE)
2405 MyStates.SetAsEntry();
2406 else
2407 do {
2408 const BasicBlock *Pred = *PI++;
2409 if (Pred == BB)
2410 continue;
2411 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
Dan Gohmana7f7db22011-08-12 00:26:31 +00002412 assert(I != BBStates.end());
2413 // If we haven't seen this node yet, then we've found a CFG cycle.
2414 // Be optimistic here; it's CheckForCFGHazards' job detect trouble.
2415 if (!I->second.isVisitedTopDown())
John McCall9fbd3182011-06-15 23:37:01 +00002416 continue;
2417 MyStates.InitFromPred(I->second);
2418 while (PI != PE) {
2419 Pred = *PI++;
2420 if (Pred != BB) {
2421 I = BBStates.find(Pred);
Dan Gohmana7f7db22011-08-12 00:26:31 +00002422 assert(I != BBStates.end());
2423 if (I->second.isVisitedTopDown())
John McCall9fbd3182011-06-15 23:37:01 +00002424 MyStates.MergePred(I->second);
2425 }
2426 }
2427 break;
2428 } while (PI != PE);
2429
2430 // Visit all the instructions, top-down.
2431 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2432 Instruction *Inst = I;
2433 InstructionClass Class = GetInstructionClass(Inst);
2434 const Value *Arg = 0;
2435
2436 switch (Class) {
2437 case IC_RetainBlock:
2438 case IC_Retain:
2439 case IC_RetainRV: {
2440 Arg = GetObjCArg(Inst);
2441
2442 PtrState &S = MyStates.getPtrTopDownState(Arg);
2443
2444 // Don't do retain+release tracking for IC_RetainRV, because it's
2445 // better to let it remain as the first instruction after a call.
2446 if (Class != IC_RetainRV) {
2447 // If we see two retains in a row on the same pointer. If so, make
2448 // a note, and we'll cicle back to revisit it after we've
2449 // hopefully eliminated the second retain, which may allow us to
2450 // eliminate the first retain too.
2451 // Theoretically we could implement removal of nested retain+release
2452 // pairs by making PtrState hold a stack of states, but this is
2453 // simple and avoids adding overhead for the non-nested case.
2454 if (S.GetSeq() == S_Retain)
2455 NestingDetected = true;
2456
2457 S.SetSeq(S_Retain);
2458 S.RRI.clear();
2459 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2460 S.RRI.KnownIncremented = S.IsKnownIncremented();
2461 S.RRI.Calls.insert(Inst);
2462 }
2463
Dan Gohmana7f7db22011-08-12 00:26:31 +00002464 S.SetAtLeastOneRefCount();
John McCall9fbd3182011-06-15 23:37:01 +00002465 S.IncrementRefCount();
2466 break;
2467 }
2468 case IC_Release: {
2469 Arg = GetObjCArg(Inst);
2470
2471 PtrState &S = MyStates.getPtrTopDownState(Arg);
2472 S.DecrementRefCount();
2473
2474 switch (S.GetSeq()) {
2475 case S_Retain:
2476 case S_CanRelease:
2477 S.RRI.ReverseInsertPts.clear();
2478 // FALL THROUGH
2479 case S_Use:
2480 S.RRI.ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2481 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2482 Releases[Inst] = S.RRI;
2483 S.ClearSequenceProgress();
2484 break;
2485 case S_None:
2486 break;
2487 case S_Stop:
2488 case S_Release:
2489 case S_MovableRelease:
2490 llvm_unreachable("top-down pointer in release state!");
2491 }
2492 break;
2493 }
2494 case IC_AutoreleasepoolPop:
2495 // Conservatively, clear MyStates for all known pointers.
2496 MyStates.clearTopDownPointers();
2497 continue;
2498 case IC_AutoreleasepoolPush:
2499 case IC_None:
2500 // These are irrelevant.
2501 continue;
2502 default:
2503 break;
2504 }
2505
2506 // Consider any other possible effects of this instruction on each
2507 // pointer being tracked.
2508 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
2509 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
2510 const Value *Ptr = MI->first;
2511 if (Ptr == Arg)
2512 continue; // Handled above.
2513 PtrState &S = MI->second;
2514 Sequence Seq = S.GetSeq();
2515
Dan Gohmana7f7db22011-08-12 00:26:31 +00002516 // Check for possible releases. Note that we don't have to update
2517 // S's RefCount because any reference count modifications would be
2518 // done through a different provenance.
John McCall9fbd3182011-06-15 23:37:01 +00002519 if (!IsRetain(Class) && Class != IC_RetainBlock &&
Dan Gohmana7f7db22011-08-12 00:26:31 +00002520 CanAlterRefCount(Inst, Ptr, PA, Class))
John McCall9fbd3182011-06-15 23:37:01 +00002521 switch (Seq) {
2522 case S_Retain:
2523 S.SetSeq(S_CanRelease);
2524 S.RRI.ReverseInsertPts.clear();
2525 S.RRI.ReverseInsertPts.insert(Inst);
2526
2527 // One call can't cause a transition from S_Retain to S_CanRelease
2528 // and S_CanRelease to S_Use. If we've made the first transition,
2529 // we're done.
2530 continue;
2531 case S_Use:
2532 case S_CanRelease:
2533 case S_None:
2534 break;
2535 case S_Stop:
2536 case S_Release:
2537 case S_MovableRelease:
2538 llvm_unreachable("top-down pointer in release state!");
2539 }
John McCall9fbd3182011-06-15 23:37:01 +00002540
2541 // Check for possible direct uses.
2542 switch (Seq) {
2543 case S_CanRelease:
2544 if (CanUse(Inst, Ptr, PA, Class))
2545 S.SetSeq(S_Use);
2546 break;
2547 case S_Use:
2548 case S_Retain:
2549 case S_None:
2550 break;
2551 case S_Stop:
2552 case S_Release:
2553 case S_MovableRelease:
2554 llvm_unreachable("top-down pointer in release state!");
2555 }
2556 }
2557 }
2558
2559 CheckForCFGHazards(BB, BBStates, MyStates);
2560 return NestingDetected;
2561}
2562
2563// Visit - Visit the function both top-down and bottom-up.
2564bool
2565ObjCARCOpt::Visit(Function &F,
2566 DenseMap<const BasicBlock *, BBState> &BBStates,
2567 MapVector<Value *, RRInfo> &Retains,
2568 DenseMap<Value *, RRInfo> &Releases) {
Dan Gohmand8e48c42011-08-12 00:24:29 +00002569 // Use reverse-postorder on the reverse CFG for bottom-up, because we
John McCall9fbd3182011-06-15 23:37:01 +00002570 // magically know that loops will be well behaved, i.e. they won't repeatedly
Dan Gohmand8e48c42011-08-12 00:24:29 +00002571 // call retain on a single pointer without doing a release. We can't use
2572 // ReversePostOrderTraversal here because we want to walk up from each
2573 // function exit point.
2574 SmallPtrSet<BasicBlock *, 16> Visited;
2575 SmallVector<std::pair<BasicBlock *, pred_iterator>, 16> Stack;
2576 SmallVector<BasicBlock *, 16> Order;
2577 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
2578 BasicBlock *BB = I;
2579 if (BB->getTerminator()->getNumSuccessors() == 0)
2580 Stack.push_back(std::make_pair(BB, pred_begin(BB)));
2581 }
2582 while (!Stack.empty()) {
2583 pred_iterator End = pred_end(Stack.back().first);
2584 while (Stack.back().second != End) {
2585 BasicBlock *BB = *Stack.back().second++;
2586 if (Visited.insert(BB))
2587 Stack.push_back(std::make_pair(BB, pred_begin(BB)));
2588 }
2589 Order.push_back(Stack.pop_back_val().first);
2590 }
John McCall9fbd3182011-06-15 23:37:01 +00002591 bool BottomUpNestingDetected = false;
Dan Gohmand8e48c42011-08-12 00:24:29 +00002592 while (!Order.empty()) {
2593 BasicBlock *BB = Order.pop_back_val();
John McCall9fbd3182011-06-15 23:37:01 +00002594 BottomUpNestingDetected |= VisitBottomUp(BB, BBStates, Retains);
2595 }
2596
Dan Gohmand8e48c42011-08-12 00:24:29 +00002597 // Use regular reverse-postorder for top-down.
John McCall9fbd3182011-06-15 23:37:01 +00002598 bool TopDownNestingDetected = false;
Dan Gohmand8e48c42011-08-12 00:24:29 +00002599 typedef ReversePostOrderTraversal<Function *> RPOTType;
2600 RPOTType RPOT(&F);
2601 for (RPOTType::rpo_iterator I = RPOT.begin(), E = RPOT.end(); I != E; ++I) {
2602 BasicBlock *BB = *I;
2603 TopDownNestingDetected |= VisitTopDown(BB, BBStates, Releases);
2604 }
John McCall9fbd3182011-06-15 23:37:01 +00002605
2606 return TopDownNestingDetected && BottomUpNestingDetected;
2607}
2608
2609/// MoveCalls - Move the calls in RetainsToMove and ReleasesToMove.
2610void ObjCARCOpt::MoveCalls(Value *Arg,
2611 RRInfo &RetainsToMove,
2612 RRInfo &ReleasesToMove,
2613 MapVector<Value *, RRInfo> &Retains,
2614 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman44280692011-07-22 22:29:21 +00002615 SmallVectorImpl<Instruction *> &DeadInsts,
2616 Module *M) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002617 Type *ArgTy = Arg->getType();
Dan Gohman44280692011-07-22 22:29:21 +00002618 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
John McCall9fbd3182011-06-15 23:37:01 +00002619
2620 // Insert the new retain and release calls.
2621 for (SmallPtrSet<Instruction *, 2>::const_iterator
2622 PI = ReleasesToMove.ReverseInsertPts.begin(),
2623 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2624 Instruction *InsertPt = *PI;
2625 Value *MyArg = ArgTy == ParamTy ? Arg :
2626 new BitCastInst(Arg, ParamTy, "", InsertPt);
2627 CallInst *Call =
2628 CallInst::Create(RetainsToMove.IsRetainBlock ?
Dan Gohman44280692011-07-22 22:29:21 +00002629 getRetainBlockCallee(M) : getRetainCallee(M),
John McCall9fbd3182011-06-15 23:37:01 +00002630 MyArg, "", InsertPt);
2631 Call->setDoesNotThrow();
2632 if (!RetainsToMove.IsRetainBlock)
2633 Call->setTailCall();
2634 }
2635 for (SmallPtrSet<Instruction *, 2>::const_iterator
2636 PI = RetainsToMove.ReverseInsertPts.begin(),
2637 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
Dan Gohman0860d0b2011-06-16 20:57:14 +00002638 Instruction *LastUse = *PI;
2639 Instruction *InsertPts[] = { 0, 0, 0 };
2640 if (InvokeInst *II = dyn_cast<InvokeInst>(LastUse)) {
2641 // We can't insert code immediately after an invoke instruction, so
2642 // insert code at the beginning of both successor blocks instead.
2643 // The invoke's return value isn't available in the unwind block,
2644 // but our releases will never depend on it, because they must be
2645 // paired with retains from before the invoke.
2646 InsertPts[0] = II->getNormalDest()->getFirstNonPHI();
2647 InsertPts[1] = II->getUnwindDest()->getFirstNonPHI();
2648 } else {
2649 // Insert code immediately after the last use.
2650 InsertPts[0] = llvm::next(BasicBlock::iterator(LastUse));
2651 }
2652
2653 for (Instruction **I = InsertPts; *I; ++I) {
2654 Instruction *InsertPt = *I;
2655 Value *MyArg = ArgTy == ParamTy ? Arg :
2656 new BitCastInst(Arg, ParamTy, "", InsertPt);
Dan Gohman44280692011-07-22 22:29:21 +00002657 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
2658 "", InsertPt);
Dan Gohman0860d0b2011-06-16 20:57:14 +00002659 // Attach a clang.imprecise_release metadata tag, if appropriate.
2660 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
2661 Call->setMetadata(ImpreciseReleaseMDKind, M);
2662 Call->setDoesNotThrow();
2663 if (ReleasesToMove.IsTailCallRelease)
2664 Call->setTailCall();
2665 }
John McCall9fbd3182011-06-15 23:37:01 +00002666 }
2667
2668 // Delete the original retain and release calls.
2669 for (SmallPtrSet<Instruction *, 2>::const_iterator
2670 AI = RetainsToMove.Calls.begin(),
2671 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
2672 Instruction *OrigRetain = *AI;
2673 Retains.blot(OrigRetain);
2674 DeadInsts.push_back(OrigRetain);
2675 }
2676 for (SmallPtrSet<Instruction *, 2>::const_iterator
2677 AI = ReleasesToMove.Calls.begin(),
2678 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
2679 Instruction *OrigRelease = *AI;
2680 Releases.erase(OrigRelease);
2681 DeadInsts.push_back(OrigRelease);
2682 }
2683}
2684
2685bool
2686ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
2687 &BBStates,
2688 MapVector<Value *, RRInfo> &Retains,
Dan Gohman44280692011-07-22 22:29:21 +00002689 DenseMap<Value *, RRInfo> &Releases,
2690 Module *M) {
John McCall9fbd3182011-06-15 23:37:01 +00002691 bool AnyPairsCompletelyEliminated = false;
2692 RRInfo RetainsToMove;
2693 RRInfo ReleasesToMove;
2694 SmallVector<Instruction *, 4> NewRetains;
2695 SmallVector<Instruction *, 4> NewReleases;
2696 SmallVector<Instruction *, 8> DeadInsts;
2697
2698 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
2699 E = Retains.end(); I != E; ) {
2700 Value *V = (I++)->first;
2701 if (!V) continue; // blotted
2702
2703 Instruction *Retain = cast<Instruction>(V);
2704 Value *Arg = GetObjCArg(Retain);
2705
2706 // If the object being released is in static or stack storage, we know it's
2707 // not being managed by ObjC reference counting, so we can delete pairs
2708 // regardless of what possible decrements or uses lie between them.
2709 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
2710
2711 // If a pair happens in a region where it is known that the reference count
2712 // is already incremented, we can similarly ignore possible decrements.
2713 bool KnownIncrementedTD = true, KnownIncrementedBU = true;
2714
2715 // Connect the dots between the top-down-collected RetainsToMove and
2716 // bottom-up-collected ReleasesToMove to form sets of related calls.
2717 // This is an iterative process so that we connect multiple releases
2718 // to multiple retains if needed.
2719 unsigned OldDelta = 0;
2720 unsigned NewDelta = 0;
2721 unsigned OldCount = 0;
2722 unsigned NewCount = 0;
2723 bool FirstRelease = true;
2724 bool FirstRetain = true;
2725 NewRetains.push_back(Retain);
2726 for (;;) {
2727 for (SmallVectorImpl<Instruction *>::const_iterator
2728 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
2729 Instruction *NewRetain = *NI;
2730 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
2731 assert(It != Retains.end());
2732 const RRInfo &NewRetainRRI = It->second;
2733 KnownIncrementedTD &= NewRetainRRI.KnownIncremented;
2734 for (SmallPtrSet<Instruction *, 2>::const_iterator
2735 LI = NewRetainRRI.Calls.begin(),
2736 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
2737 Instruction *NewRetainRelease = *LI;
2738 DenseMap<Value *, RRInfo>::const_iterator Jt =
2739 Releases.find(NewRetainRelease);
2740 if (Jt == Releases.end())
2741 goto next_retain;
2742 const RRInfo &NewRetainReleaseRRI = Jt->second;
2743 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
2744 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
2745 OldDelta -=
2746 BBStates[NewRetainRelease->getParent()].GetAllPathCount();
2747
2748 // Merge the ReleaseMetadata and IsTailCallRelease values.
2749 if (FirstRelease) {
2750 ReleasesToMove.ReleaseMetadata =
2751 NewRetainReleaseRRI.ReleaseMetadata;
2752 ReleasesToMove.IsTailCallRelease =
2753 NewRetainReleaseRRI.IsTailCallRelease;
2754 FirstRelease = false;
2755 } else {
2756 if (ReleasesToMove.ReleaseMetadata !=
2757 NewRetainReleaseRRI.ReleaseMetadata)
2758 ReleasesToMove.ReleaseMetadata = 0;
2759 if (ReleasesToMove.IsTailCallRelease !=
2760 NewRetainReleaseRRI.IsTailCallRelease)
2761 ReleasesToMove.IsTailCallRelease = false;
2762 }
2763
2764 // Collect the optimal insertion points.
2765 if (!KnownSafe)
2766 for (SmallPtrSet<Instruction *, 2>::const_iterator
2767 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
2768 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
2769 RI != RE; ++RI) {
2770 Instruction *RIP = *RI;
2771 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
2772 NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
2773 }
2774 NewReleases.push_back(NewRetainRelease);
2775 }
2776 }
2777 }
2778 NewRetains.clear();
2779 if (NewReleases.empty()) break;
2780
2781 // Back the other way.
2782 for (SmallVectorImpl<Instruction *>::const_iterator
2783 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
2784 Instruction *NewRelease = *NI;
2785 DenseMap<Value *, RRInfo>::const_iterator It =
2786 Releases.find(NewRelease);
2787 assert(It != Releases.end());
2788 const RRInfo &NewReleaseRRI = It->second;
2789 KnownIncrementedBU &= NewReleaseRRI.KnownIncremented;
2790 for (SmallPtrSet<Instruction *, 2>::const_iterator
2791 LI = NewReleaseRRI.Calls.begin(),
2792 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
2793 Instruction *NewReleaseRetain = *LI;
2794 MapVector<Value *, RRInfo>::const_iterator Jt =
2795 Retains.find(NewReleaseRetain);
2796 if (Jt == Retains.end())
2797 goto next_retain;
2798 const RRInfo &NewReleaseRetainRRI = Jt->second;
2799 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
2800 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
2801 unsigned PathCount =
2802 BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
2803 OldDelta += PathCount;
2804 OldCount += PathCount;
2805
2806 // Merge the IsRetainBlock values.
2807 if (FirstRetain) {
2808 RetainsToMove.IsRetainBlock = NewReleaseRetainRRI.IsRetainBlock;
2809 FirstRetain = false;
2810 } else if (ReleasesToMove.IsRetainBlock !=
2811 NewReleaseRetainRRI.IsRetainBlock)
2812 // It's not possible to merge the sequences if one uses
2813 // objc_retain and the other uses objc_retainBlock.
2814 goto next_retain;
2815
2816 // Collect the optimal insertion points.
2817 if (!KnownSafe)
2818 for (SmallPtrSet<Instruction *, 2>::const_iterator
2819 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
2820 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
2821 RI != RE; ++RI) {
2822 Instruction *RIP = *RI;
2823 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
2824 PathCount = BBStates[RIP->getParent()].GetAllPathCount();
2825 NewDelta += PathCount;
2826 NewCount += PathCount;
2827 }
2828 }
2829 NewRetains.push_back(NewReleaseRetain);
2830 }
2831 }
2832 }
2833 NewReleases.clear();
2834 if (NewRetains.empty()) break;
2835 }
2836
2837 // If the pointer is known incremented, we can safely delete the pair
2838 // regardless of what's between them.
2839 if (KnownIncrementedTD || KnownIncrementedBU) {
2840 RetainsToMove.ReverseInsertPts.clear();
2841 ReleasesToMove.ReverseInsertPts.clear();
2842 NewCount = 0;
Dan Gohmana7f7db22011-08-12 00:26:31 +00002843 } else {
2844 // Determine whether the new insertion points we computed preserve the
2845 // balance of retain and release calls through the program.
2846 // TODO: If the fully aggressive solution isn't valid, try to find a
2847 // less aggressive solution which is.
2848 if (NewDelta != 0)
2849 goto next_retain;
John McCall9fbd3182011-06-15 23:37:01 +00002850 }
2851
2852 // Determine whether the original call points are balanced in the retain and
2853 // release calls through the program. If not, conservatively don't touch
2854 // them.
2855 // TODO: It's theoretically possible to do code motion in this case, as
2856 // long as the existing imbalances are maintained.
2857 if (OldDelta != 0)
2858 goto next_retain;
2859
John McCall9fbd3182011-06-15 23:37:01 +00002860 // Ok, everything checks out and we're all set. Let's move some code!
2861 Changed = true;
2862 AnyPairsCompletelyEliminated = NewCount == 0;
2863 NumRRs += OldCount - NewCount;
Dan Gohman44280692011-07-22 22:29:21 +00002864 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
2865 Retains, Releases, DeadInsts, M);
John McCall9fbd3182011-06-15 23:37:01 +00002866
2867 next_retain:
2868 NewReleases.clear();
2869 NewRetains.clear();
2870 RetainsToMove.clear();
2871 ReleasesToMove.clear();
2872 }
2873
2874 // Now that we're done moving everything, we can delete the newly dead
2875 // instructions, as we no longer need them as insert points.
2876 while (!DeadInsts.empty())
2877 EraseInstruction(DeadInsts.pop_back_val());
2878
2879 return AnyPairsCompletelyEliminated;
2880}
2881
2882/// OptimizeWeakCalls - Weak pointer optimizations.
2883void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
2884 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
2885 // itself because it uses AliasAnalysis and we need to do provenance
2886 // queries instead.
2887 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2888 Instruction *Inst = &*I++;
2889 InstructionClass Class = GetBasicInstructionClass(Inst);
2890 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
2891 continue;
2892
2893 // Delete objc_loadWeak calls with no users.
2894 if (Class == IC_LoadWeak && Inst->use_empty()) {
2895 Inst->eraseFromParent();
2896 continue;
2897 }
2898
2899 // TODO: For now, just look for an earlier available version of this value
2900 // within the same block. Theoretically, we could do memdep-style non-local
2901 // analysis too, but that would want caching. A better approach would be to
2902 // use the technique that EarlyCSE uses.
2903 inst_iterator Current = llvm::prior(I);
2904 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
2905 for (BasicBlock::iterator B = CurrentBB->begin(),
2906 J = Current.getInstructionIterator();
2907 J != B; --J) {
2908 Instruction *EarlierInst = &*llvm::prior(J);
2909 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
2910 switch (EarlierClass) {
2911 case IC_LoadWeak:
2912 case IC_LoadWeakRetained: {
2913 // If this is loading from the same pointer, replace this load's value
2914 // with that one.
2915 CallInst *Call = cast<CallInst>(Inst);
2916 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2917 Value *Arg = Call->getArgOperand(0);
2918 Value *EarlierArg = EarlierCall->getArgOperand(0);
2919 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2920 case AliasAnalysis::MustAlias:
2921 Changed = true;
2922 // If the load has a builtin retain, insert a plain retain for it.
2923 if (Class == IC_LoadWeakRetained) {
2924 CallInst *CI =
2925 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
2926 "", Call);
2927 CI->setTailCall();
2928 }
2929 // Zap the fully redundant load.
2930 Call->replaceAllUsesWith(EarlierCall);
2931 Call->eraseFromParent();
2932 goto clobbered;
2933 case AliasAnalysis::MayAlias:
2934 case AliasAnalysis::PartialAlias:
2935 goto clobbered;
2936 case AliasAnalysis::NoAlias:
2937 break;
2938 }
2939 break;
2940 }
2941 case IC_StoreWeak:
2942 case IC_InitWeak: {
2943 // If this is storing to the same pointer and has the same size etc.
2944 // replace this load's value with the stored value.
2945 CallInst *Call = cast<CallInst>(Inst);
2946 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2947 Value *Arg = Call->getArgOperand(0);
2948 Value *EarlierArg = EarlierCall->getArgOperand(0);
2949 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2950 case AliasAnalysis::MustAlias:
2951 Changed = true;
2952 // If the load has a builtin retain, insert a plain retain for it.
2953 if (Class == IC_LoadWeakRetained) {
2954 CallInst *CI =
2955 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
2956 "", Call);
2957 CI->setTailCall();
2958 }
2959 // Zap the fully redundant load.
2960 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
2961 Call->eraseFromParent();
2962 goto clobbered;
2963 case AliasAnalysis::MayAlias:
2964 case AliasAnalysis::PartialAlias:
2965 goto clobbered;
2966 case AliasAnalysis::NoAlias:
2967 break;
2968 }
2969 break;
2970 }
2971 case IC_MoveWeak:
2972 case IC_CopyWeak:
2973 // TOOD: Grab the copied value.
2974 goto clobbered;
2975 case IC_AutoreleasepoolPush:
2976 case IC_None:
2977 case IC_User:
2978 // Weak pointers are only modified through the weak entry points
2979 // (and arbitrary calls, which could call the weak entry points).
2980 break;
2981 default:
2982 // Anything else could modify the weak pointer.
2983 goto clobbered;
2984 }
2985 }
2986 clobbered:;
2987 }
2988
2989 // Then, for each destroyWeak with an alloca operand, check to see if
2990 // the alloca and all its users can be zapped.
2991 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2992 Instruction *Inst = &*I++;
2993 InstructionClass Class = GetBasicInstructionClass(Inst);
2994 if (Class != IC_DestroyWeak)
2995 continue;
2996
2997 CallInst *Call = cast<CallInst>(Inst);
2998 Value *Arg = Call->getArgOperand(0);
2999 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
3000 for (Value::use_iterator UI = Alloca->use_begin(),
3001 UE = Alloca->use_end(); UI != UE; ++UI) {
3002 Instruction *UserInst = cast<Instruction>(*UI);
3003 switch (GetBasicInstructionClass(UserInst)) {
3004 case IC_InitWeak:
3005 case IC_StoreWeak:
3006 case IC_DestroyWeak:
3007 continue;
3008 default:
3009 goto done;
3010 }
3011 }
3012 Changed = true;
3013 for (Value::use_iterator UI = Alloca->use_begin(),
3014 UE = Alloca->use_end(); UI != UE; ) {
3015 CallInst *UserInst = cast<CallInst>(*UI++);
3016 if (!UserInst->use_empty())
3017 UserInst->replaceAllUsesWith(UserInst->getOperand(1));
3018 UserInst->eraseFromParent();
3019 }
3020 Alloca->eraseFromParent();
3021 done:;
3022 }
3023 }
3024}
3025
3026/// OptimizeSequences - Identify program paths which execute sequences of
3027/// retains and releases which can be eliminated.
3028bool ObjCARCOpt::OptimizeSequences(Function &F) {
3029 /// Releases, Retains - These are used to store the results of the main flow
3030 /// analysis. These use Value* as the key instead of Instruction* so that the
3031 /// map stays valid when we get around to rewriting code and calls get
3032 /// replaced by arguments.
3033 DenseMap<Value *, RRInfo> Releases;
3034 MapVector<Value *, RRInfo> Retains;
3035
3036 /// BBStates, This is used during the traversal of the function to track the
3037 /// states for each identified object at each block.
3038 DenseMap<const BasicBlock *, BBState> BBStates;
3039
3040 // Analyze the CFG of the function, and all instructions.
3041 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
3042
3043 // Transform.
Dan Gohman44280692011-07-22 22:29:21 +00003044 return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) &&
3045 NestingDetected;
John McCall9fbd3182011-06-15 23:37:01 +00003046}
3047
3048/// OptimizeReturns - Look for this pattern:
3049///
3050/// %call = call i8* @something(...)
3051/// %2 = call i8* @objc_retain(i8* %call)
3052/// %3 = call i8* @objc_autorelease(i8* %2)
3053/// ret i8* %3
3054///
3055/// And delete the retain and autorelease.
3056///
3057/// Otherwise if it's just this:
3058///
3059/// %3 = call i8* @objc_autorelease(i8* %2)
3060/// ret i8* %3
3061///
3062/// convert the autorelease to autoreleaseRV.
3063void ObjCARCOpt::OptimizeReturns(Function &F) {
3064 if (!F.getReturnType()->isPointerTy())
3065 return;
3066
3067 SmallPtrSet<Instruction *, 4> DependingInstructions;
3068 SmallPtrSet<const BasicBlock *, 4> Visited;
3069 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3070 BasicBlock *BB = FI;
3071 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
3072 if (!Ret) continue;
3073
3074 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
3075 FindDependencies(NeedsPositiveRetainCount, Arg,
3076 BB, Ret, DependingInstructions, Visited, PA);
3077 if (DependingInstructions.size() != 1)
3078 goto next_block;
3079
3080 {
3081 CallInst *Autorelease =
3082 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3083 if (!Autorelease)
3084 goto next_block;
3085 InstructionClass AutoreleaseClass =
3086 GetBasicInstructionClass(Autorelease);
3087 if (!IsAutorelease(AutoreleaseClass))
3088 goto next_block;
3089 if (GetObjCArg(Autorelease) != Arg)
3090 goto next_block;
3091
3092 DependingInstructions.clear();
3093 Visited.clear();
3094
3095 // Check that there is nothing that can affect the reference
3096 // count between the autorelease and the retain.
3097 FindDependencies(CanChangeRetainCount, Arg,
3098 BB, Autorelease, DependingInstructions, Visited, PA);
3099 if (DependingInstructions.size() != 1)
3100 goto next_block;
3101
3102 {
3103 CallInst *Retain =
3104 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3105
3106 // Check that we found a retain with the same argument.
3107 if (!Retain ||
3108 !IsRetain(GetBasicInstructionClass(Retain)) ||
3109 GetObjCArg(Retain) != Arg)
3110 goto next_block;
3111
3112 DependingInstructions.clear();
3113 Visited.clear();
3114
3115 // Convert the autorelease to an autoreleaseRV, since it's
3116 // returning the value.
3117 if (AutoreleaseClass == IC_Autorelease) {
3118 Autorelease->setCalledFunction(getAutoreleaseRVCallee(F.getParent()));
3119 AutoreleaseClass = IC_AutoreleaseRV;
3120 }
3121
3122 // Check that there is nothing that can affect the reference
3123 // count between the retain and the call.
3124 FindDependencies(CanChangeRetainCount, Arg, BB, Retain,
3125 DependingInstructions, Visited, PA);
3126 if (DependingInstructions.size() != 1)
3127 goto next_block;
3128
3129 {
3130 CallInst *Call =
3131 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3132
3133 // Check that the pointer is the return value of the call.
3134 if (!Call || Arg != Call)
3135 goto next_block;
3136
3137 // Check that the call is a regular call.
3138 InstructionClass Class = GetBasicInstructionClass(Call);
3139 if (Class != IC_CallOrUser && Class != IC_Call)
3140 goto next_block;
3141
3142 // If so, we can zap the retain and autorelease.
3143 Changed = true;
3144 ++NumRets;
3145 EraseInstruction(Retain);
3146 EraseInstruction(Autorelease);
3147 }
3148 }
3149 }
3150
3151 next_block:
3152 DependingInstructions.clear();
3153 Visited.clear();
3154 }
3155}
3156
3157bool ObjCARCOpt::doInitialization(Module &M) {
3158 if (!EnableARCOpts)
3159 return false;
3160
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003161 Run = ModuleHasARC(M);
3162 if (!Run)
3163 return false;
3164
John McCall9fbd3182011-06-15 23:37:01 +00003165 // Identify the imprecise release metadata kind.
3166 ImpreciseReleaseMDKind =
3167 M.getContext().getMDKindID("clang.imprecise_release");
3168
John McCall9fbd3182011-06-15 23:37:01 +00003169 // Intuitively, objc_retain and others are nocapture, however in practice
3170 // they are not, because they return their argument value. And objc_release
3171 // calls finalizers.
3172
3173 // These are initialized lazily.
3174 RetainRVCallee = 0;
3175 AutoreleaseRVCallee = 0;
3176 ReleaseCallee = 0;
3177 RetainCallee = 0;
Dan Gohman44280692011-07-22 22:29:21 +00003178 RetainBlockCallee = 0;
John McCall9fbd3182011-06-15 23:37:01 +00003179 AutoreleaseCallee = 0;
3180
3181 return false;
3182}
3183
3184bool ObjCARCOpt::runOnFunction(Function &F) {
3185 if (!EnableARCOpts)
3186 return false;
3187
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003188 // If nothing in the Module uses ARC, don't do anything.
3189 if (!Run)
3190 return false;
3191
John McCall9fbd3182011-06-15 23:37:01 +00003192 Changed = false;
3193
3194 PA.setAA(&getAnalysis<AliasAnalysis>());
3195
3196 // This pass performs several distinct transformations. As a compile-time aid
3197 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3198 // library functions aren't declared.
3199
3200 // Preliminary optimizations. This also computs UsedInThisFunction.
3201 OptimizeIndividualCalls(F);
3202
3203 // Optimizations for weak pointers.
3204 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3205 (1 << IC_LoadWeakRetained) |
3206 (1 << IC_StoreWeak) |
3207 (1 << IC_InitWeak) |
3208 (1 << IC_CopyWeak) |
3209 (1 << IC_MoveWeak) |
3210 (1 << IC_DestroyWeak)))
3211 OptimizeWeakCalls(F);
3212
3213 // Optimizations for retain+release pairs.
3214 if (UsedInThisFunction & ((1 << IC_Retain) |
3215 (1 << IC_RetainRV) |
3216 (1 << IC_RetainBlock)))
3217 if (UsedInThisFunction & (1 << IC_Release))
3218 // Run OptimizeSequences until it either stops making changes or
3219 // no retain+release pair nesting is detected.
3220 while (OptimizeSequences(F)) {}
3221
3222 // Optimizations if objc_autorelease is used.
3223 if (UsedInThisFunction &
3224 ((1 << IC_Autorelease) | (1 << IC_AutoreleaseRV)))
3225 OptimizeReturns(F);
3226
3227 return Changed;
3228}
3229
3230void ObjCARCOpt::releaseMemory() {
3231 PA.clear();
3232}
3233
3234//===----------------------------------------------------------------------===//
3235// ARC contraction.
3236//===----------------------------------------------------------------------===//
3237
3238// TODO: ObjCARCContract could insert PHI nodes when uses aren't
3239// dominated by single calls.
3240
3241#include "llvm/Operator.h"
3242#include "llvm/InlineAsm.h"
3243#include "llvm/Analysis/Dominators.h"
3244
3245STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed");
3246
3247namespace {
3248 /// ObjCARCContract - Late ARC optimizations. These change the IR in a way
3249 /// that makes it difficult to be analyzed by ObjCARCOpt, so it's run late.
3250 class ObjCARCContract : public FunctionPass {
3251 bool Changed;
3252 AliasAnalysis *AA;
3253 DominatorTree *DT;
3254 ProvenanceAnalysis PA;
3255
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003256 /// Run - A flag indicating whether this optimization pass should run.
3257 bool Run;
3258
John McCall9fbd3182011-06-15 23:37:01 +00003259 /// StoreStrongCallee, etc. - Declarations for ObjC runtime
3260 /// functions, for use in creating calls to them. These are initialized
3261 /// lazily to avoid cluttering up the Module with unused declarations.
3262 Constant *StoreStrongCallee,
3263 *RetainAutoreleaseCallee, *RetainAutoreleaseRVCallee;
3264
3265 /// RetainRVMarker - The inline asm string to insert between calls and
3266 /// RetainRV calls to make the optimization work on targets which need it.
3267 const MDString *RetainRVMarker;
3268
3269 Constant *getStoreStrongCallee(Module *M);
3270 Constant *getRetainAutoreleaseCallee(Module *M);
3271 Constant *getRetainAutoreleaseRVCallee(Module *M);
3272
3273 bool ContractAutorelease(Function &F, Instruction *Autorelease,
3274 InstructionClass Class,
3275 SmallPtrSet<Instruction *, 4>
3276 &DependingInstructions,
3277 SmallPtrSet<const BasicBlock *, 4>
3278 &Visited);
3279
3280 void ContractRelease(Instruction *Release,
3281 inst_iterator &Iter);
3282
3283 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
3284 virtual bool doInitialization(Module &M);
3285 virtual bool runOnFunction(Function &F);
3286
3287 public:
3288 static char ID;
3289 ObjCARCContract() : FunctionPass(ID) {
3290 initializeObjCARCContractPass(*PassRegistry::getPassRegistry());
3291 }
3292 };
3293}
3294
3295char ObjCARCContract::ID = 0;
3296INITIALIZE_PASS_BEGIN(ObjCARCContract,
3297 "objc-arc-contract", "ObjC ARC contraction", false, false)
3298INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3299INITIALIZE_PASS_DEPENDENCY(DominatorTree)
3300INITIALIZE_PASS_END(ObjCARCContract,
3301 "objc-arc-contract", "ObjC ARC contraction", false, false)
3302
3303Pass *llvm::createObjCARCContractPass() {
3304 return new ObjCARCContract();
3305}
3306
3307void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const {
3308 AU.addRequired<AliasAnalysis>();
3309 AU.addRequired<DominatorTree>();
3310 AU.setPreservesCFG();
3311}
3312
3313Constant *ObjCARCContract::getStoreStrongCallee(Module *M) {
3314 if (!StoreStrongCallee) {
3315 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00003316 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3317 Type *I8XX = PointerType::getUnqual(I8X);
3318 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00003319 Params.push_back(I8XX);
3320 Params.push_back(I8X);
3321
3322 AttrListPtr Attributes;
3323 Attributes.addAttr(~0u, Attribute::NoUnwind);
3324 Attributes.addAttr(1, Attribute::NoCapture);
3325
3326 StoreStrongCallee =
3327 M->getOrInsertFunction(
3328 "objc_storeStrong",
3329 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
3330 Attributes);
3331 }
3332 return StoreStrongCallee;
3333}
3334
3335Constant *ObjCARCContract::getRetainAutoreleaseCallee(Module *M) {
3336 if (!RetainAutoreleaseCallee) {
3337 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00003338 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3339 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00003340 Params.push_back(I8X);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003341 FunctionType *FTy =
John McCall9fbd3182011-06-15 23:37:01 +00003342 FunctionType::get(I8X, Params, /*isVarArg=*/false);
3343 AttrListPtr Attributes;
3344 Attributes.addAttr(~0u, Attribute::NoUnwind);
3345 RetainAutoreleaseCallee =
3346 M->getOrInsertFunction("objc_retainAutorelease", FTy, Attributes);
3347 }
3348 return RetainAutoreleaseCallee;
3349}
3350
3351Constant *ObjCARCContract::getRetainAutoreleaseRVCallee(Module *M) {
3352 if (!RetainAutoreleaseRVCallee) {
3353 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00003354 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3355 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00003356 Params.push_back(I8X);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003357 FunctionType *FTy =
John McCall9fbd3182011-06-15 23:37:01 +00003358 FunctionType::get(I8X, Params, /*isVarArg=*/false);
3359 AttrListPtr Attributes;
3360 Attributes.addAttr(~0u, Attribute::NoUnwind);
3361 RetainAutoreleaseRVCallee =
3362 M->getOrInsertFunction("objc_retainAutoreleaseReturnValue", FTy,
3363 Attributes);
3364 }
3365 return RetainAutoreleaseRVCallee;
3366}
3367
3368/// ContractAutorelease - Merge an autorelease with a retain into a fused
3369/// call.
3370bool
3371ObjCARCContract::ContractAutorelease(Function &F, Instruction *Autorelease,
3372 InstructionClass Class,
3373 SmallPtrSet<Instruction *, 4>
3374 &DependingInstructions,
3375 SmallPtrSet<const BasicBlock *, 4>
3376 &Visited) {
3377 const Value *Arg = GetObjCArg(Autorelease);
3378
3379 // Check that there are no instructions between the retain and the autorelease
3380 // (such as an autorelease_pop) which may change the count.
3381 CallInst *Retain = 0;
3382 if (Class == IC_AutoreleaseRV)
3383 FindDependencies(RetainAutoreleaseRVDep, Arg,
3384 Autorelease->getParent(), Autorelease,
3385 DependingInstructions, Visited, PA);
3386 else
3387 FindDependencies(RetainAutoreleaseDep, Arg,
3388 Autorelease->getParent(), Autorelease,
3389 DependingInstructions, Visited, PA);
3390
3391 Visited.clear();
3392 if (DependingInstructions.size() != 1) {
3393 DependingInstructions.clear();
3394 return false;
3395 }
3396
3397 Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3398 DependingInstructions.clear();
3399
3400 if (!Retain ||
3401 GetBasicInstructionClass(Retain) != IC_Retain ||
3402 GetObjCArg(Retain) != Arg)
3403 return false;
3404
3405 Changed = true;
3406 ++NumPeeps;
3407
3408 if (Class == IC_AutoreleaseRV)
3409 Retain->setCalledFunction(getRetainAutoreleaseRVCallee(F.getParent()));
3410 else
3411 Retain->setCalledFunction(getRetainAutoreleaseCallee(F.getParent()));
3412
3413 EraseInstruction(Autorelease);
3414 return true;
3415}
3416
3417/// ContractRelease - Attempt to merge an objc_release with a store, load, and
3418/// objc_retain to form an objc_storeStrong. This can be a little tricky because
3419/// the instructions don't always appear in order, and there may be unrelated
3420/// intervening instructions.
3421void ObjCARCContract::ContractRelease(Instruction *Release,
3422 inst_iterator &Iter) {
3423 LoadInst *Load = dyn_cast<LoadInst>(GetObjCArg(Release));
3424 if (!Load || Load->isVolatile()) return;
3425
3426 // For now, require everything to be in one basic block.
3427 BasicBlock *BB = Release->getParent();
3428 if (Load->getParent() != BB) return;
3429
3430 // Walk down to find the store.
3431 BasicBlock::iterator I = Load, End = BB->end();
3432 ++I;
3433 AliasAnalysis::Location Loc = AA->getLocation(Load);
3434 while (I != End &&
3435 (&*I == Release ||
3436 IsRetain(GetBasicInstructionClass(I)) ||
3437 !(AA->getModRefInfo(I, Loc) & AliasAnalysis::Mod)))
3438 ++I;
3439 StoreInst *Store = dyn_cast<StoreInst>(I);
3440 if (!Store || Store->isVolatile()) return;
3441 if (Store->getPointerOperand() != Loc.Ptr) return;
3442
3443 Value *New = StripPointerCastsAndObjCCalls(Store->getValueOperand());
3444
3445 // Walk up to find the retain.
3446 I = Store;
3447 BasicBlock::iterator Begin = BB->begin();
3448 while (I != Begin && GetBasicInstructionClass(I) != IC_Retain)
3449 --I;
3450 Instruction *Retain = I;
3451 if (GetBasicInstructionClass(Retain) != IC_Retain) return;
3452 if (GetObjCArg(Retain) != New) return;
3453
3454 Changed = true;
3455 ++NumStoreStrongs;
3456
3457 LLVMContext &C = Release->getContext();
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003458 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3459 Type *I8XX = PointerType::getUnqual(I8X);
John McCall9fbd3182011-06-15 23:37:01 +00003460
3461 Value *Args[] = { Load->getPointerOperand(), New };
3462 if (Args[0]->getType() != I8XX)
3463 Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
3464 if (Args[1]->getType() != I8X)
3465 Args[1] = new BitCastInst(Args[1], I8X, "", Store);
3466 CallInst *StoreStrong =
3467 CallInst::Create(getStoreStrongCallee(BB->getParent()->getParent()),
Jay Foada3efbb12011-07-15 08:37:34 +00003468 Args, "", Store);
John McCall9fbd3182011-06-15 23:37:01 +00003469 StoreStrong->setDoesNotThrow();
3470 StoreStrong->setDebugLoc(Store->getDebugLoc());
3471
3472 if (&*Iter == Store) ++Iter;
3473 Store->eraseFromParent();
3474 Release->eraseFromParent();
3475 EraseInstruction(Retain);
3476 if (Load->use_empty())
3477 Load->eraseFromParent();
3478}
3479
3480bool ObjCARCContract::doInitialization(Module &M) {
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003481 Run = ModuleHasARC(M);
3482 if (!Run)
3483 return false;
3484
John McCall9fbd3182011-06-15 23:37:01 +00003485 // These are initialized lazily.
3486 StoreStrongCallee = 0;
3487 RetainAutoreleaseCallee = 0;
3488 RetainAutoreleaseRVCallee = 0;
3489
3490 // Initialize RetainRVMarker.
3491 RetainRVMarker = 0;
3492 if (NamedMDNode *NMD =
3493 M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker"))
3494 if (NMD->getNumOperands() == 1) {
3495 const MDNode *N = NMD->getOperand(0);
3496 if (N->getNumOperands() == 1)
3497 if (const MDString *S = dyn_cast<MDString>(N->getOperand(0)))
3498 RetainRVMarker = S;
3499 }
3500
3501 return false;
3502}
3503
3504bool ObjCARCContract::runOnFunction(Function &F) {
3505 if (!EnableARCOpts)
3506 return false;
3507
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003508 // If nothing in the Module uses ARC, don't do anything.
3509 if (!Run)
3510 return false;
3511
John McCall9fbd3182011-06-15 23:37:01 +00003512 Changed = false;
3513 AA = &getAnalysis<AliasAnalysis>();
3514 DT = &getAnalysis<DominatorTree>();
3515
3516 PA.setAA(&getAnalysis<AliasAnalysis>());
3517
3518 // For ObjC library calls which return their argument, replace uses of the
3519 // argument with uses of the call return value, if it dominates the use. This
3520 // reduces register pressure.
3521 SmallPtrSet<Instruction *, 4> DependingInstructions;
3522 SmallPtrSet<const BasicBlock *, 4> Visited;
3523 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3524 Instruction *Inst = &*I++;
3525
3526 // Only these library routines return their argument. In particular,
3527 // objc_retainBlock does not necessarily return its argument.
3528 InstructionClass Class = GetBasicInstructionClass(Inst);
3529 switch (Class) {
3530 case IC_Retain:
3531 case IC_FusedRetainAutorelease:
3532 case IC_FusedRetainAutoreleaseRV:
3533 break;
3534 case IC_Autorelease:
3535 case IC_AutoreleaseRV:
3536 if (ContractAutorelease(F, Inst, Class, DependingInstructions, Visited))
3537 continue;
3538 break;
3539 case IC_RetainRV: {
3540 // If we're compiling for a target which needs a special inline-asm
3541 // marker to do the retainAutoreleasedReturnValue optimization,
3542 // insert it now.
3543 if (!RetainRVMarker)
3544 break;
3545 BasicBlock::iterator BBI = Inst;
3546 --BBI;
3547 while (isNoopInstruction(BBI)) --BBI;
3548 if (&*BBI == GetObjCArg(Inst)) {
3549 InlineAsm *IA =
3550 InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()),
3551 /*isVarArg=*/false),
3552 RetainRVMarker->getString(),
3553 /*Constraints=*/"", /*hasSideEffects=*/true);
3554 CallInst::Create(IA, "", Inst);
3555 }
3556 break;
3557 }
3558 case IC_InitWeak: {
3559 // objc_initWeak(p, null) => *p = null
3560 CallInst *CI = cast<CallInst>(Inst);
3561 if (isNullOrUndef(CI->getArgOperand(1))) {
3562 Value *Null =
3563 ConstantPointerNull::get(cast<PointerType>(CI->getType()));
3564 Changed = true;
3565 new StoreInst(Null, CI->getArgOperand(0), CI);
3566 CI->replaceAllUsesWith(Null);
3567 CI->eraseFromParent();
3568 }
3569 continue;
3570 }
3571 case IC_Release:
3572 ContractRelease(Inst, I);
3573 continue;
3574 default:
3575 continue;
3576 }
3577
3578 // Don't use GetObjCArg because we don't want to look through bitcasts
3579 // and such; to do the replacement, the argument must have type i8*.
3580 const Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
3581 for (;;) {
3582 // If we're compiling bugpointed code, don't get in trouble.
3583 if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
3584 break;
3585 // Look through the uses of the pointer.
3586 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
3587 UI != UE; ) {
3588 Use &U = UI.getUse();
3589 unsigned OperandNo = UI.getOperandNo();
3590 ++UI; // Increment UI now, because we may unlink its element.
3591 if (Instruction *UserInst = dyn_cast<Instruction>(U.getUser()))
3592 if (Inst != UserInst && DT->dominates(Inst, UserInst)) {
3593 Changed = true;
3594 Instruction *Replacement = Inst;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003595 Type *UseTy = U.get()->getType();
John McCall9fbd3182011-06-15 23:37:01 +00003596 if (PHINode *PHI = dyn_cast<PHINode>(UserInst)) {
3597 // For PHI nodes, insert the bitcast in the predecessor block.
3598 unsigned ValNo =
3599 PHINode::getIncomingValueNumForOperand(OperandNo);
3600 BasicBlock *BB =
3601 PHI->getIncomingBlock(ValNo);
3602 if (Replacement->getType() != UseTy)
3603 Replacement = new BitCastInst(Replacement, UseTy, "",
3604 &BB->back());
3605 for (unsigned i = 0, e = PHI->getNumIncomingValues();
3606 i != e; ++i)
3607 if (PHI->getIncomingBlock(i) == BB) {
3608 // Keep the UI iterator valid.
3609 if (&PHI->getOperandUse(
3610 PHINode::getOperandNumForIncomingValue(i)) ==
3611 &UI.getUse())
3612 ++UI;
3613 PHI->setIncomingValue(i, Replacement);
3614 }
3615 } else {
3616 if (Replacement->getType() != UseTy)
3617 Replacement = new BitCastInst(Replacement, UseTy, "", UserInst);
3618 U.set(Replacement);
3619 }
3620 }
3621 }
3622
3623 // If Arg is a no-op casted pointer, strip one level of casts and
3624 // iterate.
3625 if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
3626 Arg = BI->getOperand(0);
3627 else if (isa<GEPOperator>(Arg) &&
3628 cast<GEPOperator>(Arg)->hasAllZeroIndices())
3629 Arg = cast<GEPOperator>(Arg)->getPointerOperand();
3630 else if (isa<GlobalAlias>(Arg) &&
3631 !cast<GlobalAlias>(Arg)->mayBeOverridden())
3632 Arg = cast<GlobalAlias>(Arg)->getAliasee();
3633 else
3634 break;
3635 }
3636 }
3637
3638 return Changed;
3639}