blob: ab23884bb0486a57de703a23202caf5a768489a4 [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.
Dan Gohmand4464602011-08-22 17:29:37 +0000347 // Note that this includes both operands of a Store: while the first
348 // operand isn't actually being dereferenced, it is being stored to
349 // memory where we can no longer track who might read it and dereference
350 // it, so we have to consider it potentially used.
John McCall9fbd3182011-06-15 23:37:01 +0000351 for (User::const_op_iterator OI = I->op_begin(), OE = I->op_end();
352 OI != OE; ++OI)
353 if (IsPotentialUse(*OI))
354 return IC_User;
355 }
356 }
357
358 // Otherwise, it's totally inert for ARC purposes.
359 return IC_None;
360}
361
362/// GetBasicInstructionClass - Determine what kind of construct V is. This is
363/// similar to GetInstructionClass except that it only detects objc runtine
364/// calls. This allows it to be faster.
365static InstructionClass GetBasicInstructionClass(const Value *V) {
366 if (const CallInst *CI = dyn_cast<CallInst>(V)) {
367 if (const Function *F = CI->getCalledFunction())
368 return GetFunctionClass(F);
369 // Otherwise, be conservative.
370 return IC_CallOrUser;
371 }
372
373 // Otherwise, be conservative.
374 return IC_User;
375}
376
377/// IsRetain - Test if the the given class is objc_retain or
378/// equivalent.
379static bool IsRetain(InstructionClass Class) {
380 return Class == IC_Retain ||
381 Class == IC_RetainRV;
382}
383
384/// IsAutorelease - Test if the the given class is objc_autorelease or
385/// equivalent.
386static bool IsAutorelease(InstructionClass Class) {
387 return Class == IC_Autorelease ||
388 Class == IC_AutoreleaseRV;
389}
390
391/// IsForwarding - Test if the given class represents instructions which return
392/// their argument verbatim.
393static bool IsForwarding(InstructionClass Class) {
394 // objc_retainBlock technically doesn't always return its argument
395 // verbatim, but it doesn't matter for our purposes here.
396 return Class == IC_Retain ||
397 Class == IC_RetainRV ||
398 Class == IC_Autorelease ||
399 Class == IC_AutoreleaseRV ||
400 Class == IC_RetainBlock ||
401 Class == IC_NoopCast;
402}
403
404/// IsNoopOnNull - Test if the given class represents instructions which do
405/// nothing if passed a null pointer.
406static bool IsNoopOnNull(InstructionClass Class) {
407 return Class == IC_Retain ||
408 Class == IC_RetainRV ||
409 Class == IC_Release ||
410 Class == IC_Autorelease ||
411 Class == IC_AutoreleaseRV ||
412 Class == IC_RetainBlock;
413}
414
415/// IsAlwaysTail - Test if the given class represents instructions which are
416/// always safe to mark with the "tail" keyword.
417static bool IsAlwaysTail(InstructionClass Class) {
418 // IC_RetainBlock may be given a stack argument.
419 return Class == IC_Retain ||
420 Class == IC_RetainRV ||
421 Class == IC_Autorelease ||
422 Class == IC_AutoreleaseRV;
423}
424
425/// IsNoThrow - Test if the given class represents instructions which are always
426/// safe to mark with the nounwind attribute..
427static bool IsNoThrow(InstructionClass Class) {
Dan Gohman1d2fd752011-09-14 18:33:34 +0000428 // objc_retainBlock is not nounwind because it calls user copy constructors
429 // which could theoretically throw.
John McCall9fbd3182011-06-15 23:37:01 +0000430 return Class == IC_Retain ||
431 Class == IC_RetainRV ||
John McCall9fbd3182011-06-15 23:37:01 +0000432 Class == IC_Release ||
433 Class == IC_Autorelease ||
434 Class == IC_AutoreleaseRV ||
435 Class == IC_AutoreleasepoolPush ||
436 Class == IC_AutoreleasepoolPop;
437}
438
439/// EraseInstruction - Erase the given instruction. ObjC calls return their
440/// argument verbatim, so if it's such a call and the return value has users,
441/// replace them with the argument value.
442static void EraseInstruction(Instruction *CI) {
443 Value *OldArg = cast<CallInst>(CI)->getArgOperand(0);
444
445 bool Unused = CI->use_empty();
446
447 if (!Unused) {
448 // Replace the return value with the argument.
449 assert(IsForwarding(GetBasicInstructionClass(CI)) &&
450 "Can't delete non-forwarding instruction with users!");
451 CI->replaceAllUsesWith(OldArg);
452 }
453
454 CI->eraseFromParent();
455
456 if (Unused)
457 RecursivelyDeleteTriviallyDeadInstructions(OldArg);
458}
459
460/// GetUnderlyingObjCPtr - This is a wrapper around getUnderlyingObject which
461/// also knows how to look through objc_retain and objc_autorelease calls, which
462/// we know to return their argument verbatim.
463static const Value *GetUnderlyingObjCPtr(const Value *V) {
464 for (;;) {
465 V = GetUnderlyingObject(V);
466 if (!IsForwarding(GetBasicInstructionClass(V)))
467 break;
468 V = cast<CallInst>(V)->getArgOperand(0);
469 }
470
471 return V;
472}
473
474/// StripPointerCastsAndObjCCalls - This is a wrapper around
475/// Value::stripPointerCasts which also knows how to look through objc_retain
476/// and objc_autorelease calls, which we know to return their argument verbatim.
477static const Value *StripPointerCastsAndObjCCalls(const Value *V) {
478 for (;;) {
479 V = V->stripPointerCasts();
480 if (!IsForwarding(GetBasicInstructionClass(V)))
481 break;
482 V = cast<CallInst>(V)->getArgOperand(0);
483 }
484 return V;
485}
486
487/// StripPointerCastsAndObjCCalls - This is a wrapper around
488/// Value::stripPointerCasts which also knows how to look through objc_retain
489/// and objc_autorelease calls, which we know to return their argument verbatim.
490static Value *StripPointerCastsAndObjCCalls(Value *V) {
491 for (;;) {
492 V = V->stripPointerCasts();
493 if (!IsForwarding(GetBasicInstructionClass(V)))
494 break;
495 V = cast<CallInst>(V)->getArgOperand(0);
496 }
497 return V;
498}
499
500/// GetObjCArg - Assuming the given instruction is one of the special calls such
501/// as objc_retain or objc_release, return the argument value, stripped of no-op
502/// casts and forwarding calls.
503static Value *GetObjCArg(Value *Inst) {
504 return StripPointerCastsAndObjCCalls(cast<CallInst>(Inst)->getArgOperand(0));
505}
506
507/// IsObjCIdentifiedObject - This is similar to AliasAnalysis'
508/// isObjCIdentifiedObject, except that it uses special knowledge of
509/// ObjC conventions...
510static bool IsObjCIdentifiedObject(const Value *V) {
511 // Assume that call results and arguments have their own "provenance".
512 // Constants (including GlobalVariables) and Allocas are never
513 // reference-counted.
514 if (isa<CallInst>(V) || isa<InvokeInst>(V) ||
515 isa<Argument>(V) || isa<Constant>(V) ||
516 isa<AllocaInst>(V))
517 return true;
518
519 if (const LoadInst *LI = dyn_cast<LoadInst>(V)) {
520 const Value *Pointer =
521 StripPointerCastsAndObjCCalls(LI->getPointerOperand());
522 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Pointer)) {
Dan Gohman1b31ea82011-08-22 17:29:11 +0000523 // A constant pointer can't be pointing to an object on the heap. It may
524 // be reference-counted, but it won't be deleted.
525 if (GV->isConstant())
526 return true;
John McCall9fbd3182011-06-15 23:37:01 +0000527 StringRef Name = GV->getName();
528 // These special variables are known to hold values which are not
529 // reference-counted pointers.
530 if (Name.startswith("\01L_OBJC_SELECTOR_REFERENCES_") ||
531 Name.startswith("\01L_OBJC_CLASSLIST_REFERENCES_") ||
532 Name.startswith("\01L_OBJC_CLASSLIST_SUP_REFS_$_") ||
533 Name.startswith("\01L_OBJC_METH_VAR_NAME_") ||
534 Name.startswith("\01l_objc_msgSend_fixup_"))
535 return true;
536 }
537 }
538
539 return false;
540}
541
542/// FindSingleUseIdentifiedObject - This is similar to
543/// StripPointerCastsAndObjCCalls but it stops as soon as it finds a value
544/// with multiple uses.
545static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
546 if (Arg->hasOneUse()) {
547 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
548 return FindSingleUseIdentifiedObject(BC->getOperand(0));
549 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
550 if (GEP->hasAllZeroIndices())
551 return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
552 if (IsForwarding(GetBasicInstructionClass(Arg)))
553 return FindSingleUseIdentifiedObject(
554 cast<CallInst>(Arg)->getArgOperand(0));
555 if (!IsObjCIdentifiedObject(Arg))
556 return 0;
557 return Arg;
558 }
559
560 // If we found an identifiable object but it has multiple uses, but they
561 // are trivial uses, we can still consider this to be a single-use
562 // value.
563 if (IsObjCIdentifiedObject(Arg)) {
564 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
565 UI != UE; ++UI) {
566 const User *U = *UI;
567 if (!U->use_empty() || StripPointerCastsAndObjCCalls(U) != Arg)
568 return 0;
569 }
570
571 return Arg;
572 }
573
574 return 0;
575}
576
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000577/// ModuleHasARC - Test if the given module looks interesting to run ARC
578/// optimization on.
579static bool ModuleHasARC(const Module &M) {
580 return
581 M.getNamedValue("objc_retain") ||
582 M.getNamedValue("objc_release") ||
583 M.getNamedValue("objc_autorelease") ||
584 M.getNamedValue("objc_retainAutoreleasedReturnValue") ||
585 M.getNamedValue("objc_retainBlock") ||
586 M.getNamedValue("objc_autoreleaseReturnValue") ||
587 M.getNamedValue("objc_autoreleasePoolPush") ||
588 M.getNamedValue("objc_loadWeakRetained") ||
589 M.getNamedValue("objc_loadWeak") ||
590 M.getNamedValue("objc_destroyWeak") ||
591 M.getNamedValue("objc_storeWeak") ||
592 M.getNamedValue("objc_initWeak") ||
593 M.getNamedValue("objc_moveWeak") ||
594 M.getNamedValue("objc_copyWeak") ||
595 M.getNamedValue("objc_retainedObject") ||
596 M.getNamedValue("objc_unretainedObject") ||
597 M.getNamedValue("objc_unretainedPointer");
598}
599
John McCall9fbd3182011-06-15 23:37:01 +0000600//===----------------------------------------------------------------------===//
601// ARC AliasAnalysis.
602//===----------------------------------------------------------------------===//
603
604#include "llvm/Pass.h"
605#include "llvm/Analysis/AliasAnalysis.h"
606#include "llvm/Analysis/Passes.h"
607
608namespace {
609 /// ObjCARCAliasAnalysis - This is a simple alias analysis
610 /// implementation that uses knowledge of ARC constructs to answer queries.
611 ///
612 /// TODO: This class could be generalized to know about other ObjC-specific
613 /// tricks. Such as knowing that ivars in the non-fragile ABI are non-aliasing
614 /// even though their offsets are dynamic.
615 class ObjCARCAliasAnalysis : public ImmutablePass,
616 public AliasAnalysis {
617 public:
618 static char ID; // Class identification, replacement for typeinfo
619 ObjCARCAliasAnalysis() : ImmutablePass(ID) {
620 initializeObjCARCAliasAnalysisPass(*PassRegistry::getPassRegistry());
621 }
622
623 private:
624 virtual void initializePass() {
625 InitializeAliasAnalysis(this);
626 }
627
628 /// getAdjustedAnalysisPointer - This method is used when a pass implements
629 /// an analysis interface through multiple inheritance. If needed, it
630 /// should override this to adjust the this pointer as needed for the
631 /// specified pass info.
632 virtual void *getAdjustedAnalysisPointer(const void *PI) {
633 if (PI == &AliasAnalysis::ID)
634 return (AliasAnalysis*)this;
635 return this;
636 }
637
638 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
639 virtual AliasResult alias(const Location &LocA, const Location &LocB);
640 virtual bool pointsToConstantMemory(const Location &Loc, bool OrLocal);
641 virtual ModRefBehavior getModRefBehavior(ImmutableCallSite CS);
642 virtual ModRefBehavior getModRefBehavior(const Function *F);
643 virtual ModRefResult getModRefInfo(ImmutableCallSite CS,
644 const Location &Loc);
645 virtual ModRefResult getModRefInfo(ImmutableCallSite CS1,
646 ImmutableCallSite CS2);
647 };
648} // End of anonymous namespace
649
650// Register this pass...
651char ObjCARCAliasAnalysis::ID = 0;
652INITIALIZE_AG_PASS(ObjCARCAliasAnalysis, AliasAnalysis, "objc-arc-aa",
653 "ObjC-ARC-Based Alias Analysis", false, true, false)
654
655ImmutablePass *llvm::createObjCARCAliasAnalysisPass() {
656 return new ObjCARCAliasAnalysis();
657}
658
659void
660ObjCARCAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
661 AU.setPreservesAll();
662 AliasAnalysis::getAnalysisUsage(AU);
663}
664
665AliasAnalysis::AliasResult
666ObjCARCAliasAnalysis::alias(const Location &LocA, const Location &LocB) {
667 if (!EnableARCOpts)
668 return AliasAnalysis::alias(LocA, LocB);
669
670 // First, strip off no-ops, including ObjC-specific no-ops, and try making a
671 // precise alias query.
672 const Value *SA = StripPointerCastsAndObjCCalls(LocA.Ptr);
673 const Value *SB = StripPointerCastsAndObjCCalls(LocB.Ptr);
674 AliasResult Result =
675 AliasAnalysis::alias(Location(SA, LocA.Size, LocA.TBAATag),
676 Location(SB, LocB.Size, LocB.TBAATag));
677 if (Result != MayAlias)
678 return Result;
679
680 // If that failed, climb to the underlying object, including climbing through
681 // ObjC-specific no-ops, and try making an imprecise alias query.
682 const Value *UA = GetUnderlyingObjCPtr(SA);
683 const Value *UB = GetUnderlyingObjCPtr(SB);
684 if (UA != SA || UB != SB) {
685 Result = AliasAnalysis::alias(Location(UA), Location(UB));
686 // We can't use MustAlias or PartialAlias results here because
687 // GetUnderlyingObjCPtr may return an offsetted pointer value.
688 if (Result == NoAlias)
689 return NoAlias;
690 }
691
692 // If that failed, fail. We don't need to chain here, since that's covered
693 // by the earlier precise query.
694 return MayAlias;
695}
696
697bool
698ObjCARCAliasAnalysis::pointsToConstantMemory(const Location &Loc,
699 bool OrLocal) {
700 if (!EnableARCOpts)
701 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
702
703 // First, strip off no-ops, including ObjC-specific no-ops, and try making
704 // a precise alias query.
705 const Value *S = StripPointerCastsAndObjCCalls(Loc.Ptr);
706 if (AliasAnalysis::pointsToConstantMemory(Location(S, Loc.Size, Loc.TBAATag),
707 OrLocal))
708 return true;
709
710 // If that failed, climb to the underlying object, including climbing through
711 // ObjC-specific no-ops, and try making an imprecise alias query.
712 const Value *U = GetUnderlyingObjCPtr(S);
713 if (U != S)
714 return AliasAnalysis::pointsToConstantMemory(Location(U), OrLocal);
715
716 // If that failed, fail. We don't need to chain here, since that's covered
717 // by the earlier precise query.
718 return false;
719}
720
721AliasAnalysis::ModRefBehavior
722ObjCARCAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
723 // We have nothing to do. Just chain to the next AliasAnalysis.
724 return AliasAnalysis::getModRefBehavior(CS);
725}
726
727AliasAnalysis::ModRefBehavior
728ObjCARCAliasAnalysis::getModRefBehavior(const Function *F) {
729 if (!EnableARCOpts)
730 return AliasAnalysis::getModRefBehavior(F);
731
732 switch (GetFunctionClass(F)) {
733 case IC_NoopCast:
734 return DoesNotAccessMemory;
735 default:
736 break;
737 }
738
739 return AliasAnalysis::getModRefBehavior(F);
740}
741
742AliasAnalysis::ModRefResult
743ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS, const Location &Loc) {
744 if (!EnableARCOpts)
745 return AliasAnalysis::getModRefInfo(CS, Loc);
746
747 switch (GetBasicInstructionClass(CS.getInstruction())) {
748 case IC_Retain:
749 case IC_RetainRV:
John McCall9fbd3182011-06-15 23:37:01 +0000750 case IC_Autorelease:
751 case IC_AutoreleaseRV:
752 case IC_NoopCast:
753 case IC_AutoreleasepoolPush:
754 case IC_FusedRetainAutorelease:
755 case IC_FusedRetainAutoreleaseRV:
756 // These functions don't access any memory visible to the compiler.
Dan Gohman21104822011-09-14 18:13:00 +0000757 // Note that this doesn't include objc_retainBlock, becuase it updates
758 // pointers when it copies block data.
John McCall9fbd3182011-06-15 23:37:01 +0000759 return NoModRef;
760 default:
761 break;
762 }
763
764 return AliasAnalysis::getModRefInfo(CS, Loc);
765}
766
767AliasAnalysis::ModRefResult
768ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
769 ImmutableCallSite CS2) {
770 // TODO: Theoretically we could check for dependencies between objc_* calls
771 // and OnlyAccessesArgumentPointees calls or other well-behaved calls.
772 return AliasAnalysis::getModRefInfo(CS1, CS2);
773}
774
775//===----------------------------------------------------------------------===//
776// ARC expansion.
777//===----------------------------------------------------------------------===//
778
779#include "llvm/Support/InstIterator.h"
780#include "llvm/Transforms/Scalar.h"
781
782namespace {
783 /// ObjCARCExpand - Early ARC transformations.
784 class ObjCARCExpand : public FunctionPass {
785 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000786 virtual bool doInitialization(Module &M);
John McCall9fbd3182011-06-15 23:37:01 +0000787 virtual bool runOnFunction(Function &F);
788
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000789 /// Run - A flag indicating whether this optimization pass should run.
790 bool Run;
791
John McCall9fbd3182011-06-15 23:37:01 +0000792 public:
793 static char ID;
794 ObjCARCExpand() : FunctionPass(ID) {
795 initializeObjCARCExpandPass(*PassRegistry::getPassRegistry());
796 }
797 };
798}
799
800char ObjCARCExpand::ID = 0;
801INITIALIZE_PASS(ObjCARCExpand,
802 "objc-arc-expand", "ObjC ARC expansion", false, false)
803
804Pass *llvm::createObjCARCExpandPass() {
805 return new ObjCARCExpand();
806}
807
808void ObjCARCExpand::getAnalysisUsage(AnalysisUsage &AU) const {
809 AU.setPreservesCFG();
810}
811
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000812bool ObjCARCExpand::doInitialization(Module &M) {
813 Run = ModuleHasARC(M);
814 return false;
815}
816
John McCall9fbd3182011-06-15 23:37:01 +0000817bool ObjCARCExpand::runOnFunction(Function &F) {
818 if (!EnableARCOpts)
819 return false;
820
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000821 // If nothing in the Module uses ARC, don't do anything.
822 if (!Run)
823 return false;
824
John McCall9fbd3182011-06-15 23:37:01 +0000825 bool Changed = false;
826
827 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
828 Instruction *Inst = &*I;
829
830 switch (GetBasicInstructionClass(Inst)) {
831 case IC_Retain:
832 case IC_RetainRV:
833 case IC_Autorelease:
834 case IC_AutoreleaseRV:
835 case IC_FusedRetainAutorelease:
836 case IC_FusedRetainAutoreleaseRV:
837 // These calls return their argument verbatim, as a low-level
838 // optimization. However, this makes high-level optimizations
839 // harder. Undo any uses of this optimization that the front-end
840 // emitted here. We'll redo them in a later pass.
841 Changed = true;
842 Inst->replaceAllUsesWith(cast<CallInst>(Inst)->getArgOperand(0));
843 break;
844 default:
845 break;
846 }
847 }
848
849 return Changed;
850}
851
852//===----------------------------------------------------------------------===//
853// ARC optimization.
854//===----------------------------------------------------------------------===//
855
856// TODO: On code like this:
857//
858// objc_retain(%x)
859// stuff_that_cannot_release()
860// objc_autorelease(%x)
861// stuff_that_cannot_release()
862// objc_retain(%x)
863// stuff_that_cannot_release()
864// objc_autorelease(%x)
865//
866// The second retain and autorelease can be deleted.
867
868// TODO: It should be possible to delete
869// objc_autoreleasePoolPush and objc_autoreleasePoolPop
870// pairs if nothing is actually autoreleased between them. Also, autorelease
871// calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
872// after inlining) can be turned into plain release calls.
873
874// TODO: Critical-edge splitting. If the optimial insertion point is
875// a critical edge, the current algorithm has to fail, because it doesn't
876// know how to split edges. It should be possible to make the optimizer
877// think in terms of edges, rather than blocks, and then split critical
878// edges on demand.
879
880// TODO: OptimizeSequences could generalized to be Interprocedural.
881
882// TODO: Recognize that a bunch of other objc runtime calls have
883// non-escaping arguments and non-releasing arguments, and may be
884// non-autoreleasing.
885
886// TODO: Sink autorelease calls as far as possible. Unfortunately we
887// usually can't sink them past other calls, which would be the main
888// case where it would be useful.
889
Dan Gohmane6d5e882011-08-19 00:26:36 +0000890// TODO: The pointer returned from objc_loadWeakRetained is retained.
891
892// TODO: Delete release+retain pairs (rare).
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000893
John McCall9fbd3182011-06-15 23:37:01 +0000894#include "llvm/GlobalAlias.h"
John McCall9fbd3182011-06-15 23:37:01 +0000895#include "llvm/Constants.h"
896#include "llvm/LLVMContext.h"
897#include "llvm/Support/ErrorHandling.h"
898#include "llvm/Support/CFG.h"
John McCall9fbd3182011-06-15 23:37:01 +0000899#include "llvm/ADT/Statistic.h"
Dan Gohman59a1c932011-12-12 19:42:25 +0000900#include "llvm/ADT/SmallPtrSet.h"
901#include "llvm/ADT/DenseSet.h"
John McCall9fbd3182011-06-15 23:37:01 +0000902
903STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
904STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
905STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
906STATISTIC(NumRets, "Number of return value forwarding "
907 "retain+autoreleaes eliminated");
908STATISTIC(NumRRs, "Number of retain+release paths eliminated");
909STATISTIC(NumPeeps, "Number of calls peephole-optimized");
910
911namespace {
912 /// ProvenanceAnalysis - This is similar to BasicAliasAnalysis, and it
913 /// uses many of the same techniques, except it uses special ObjC-specific
914 /// reasoning about pointer relationships.
915 class ProvenanceAnalysis {
916 AliasAnalysis *AA;
917
918 typedef std::pair<const Value *, const Value *> ValuePairTy;
919 typedef DenseMap<ValuePairTy, bool> CachedResultsTy;
920 CachedResultsTy CachedResults;
921
922 bool relatedCheck(const Value *A, const Value *B);
923 bool relatedSelect(const SelectInst *A, const Value *B);
924 bool relatedPHI(const PHINode *A, const Value *B);
925
926 // Do not implement.
927 void operator=(const ProvenanceAnalysis &);
928 ProvenanceAnalysis(const ProvenanceAnalysis &);
929
930 public:
931 ProvenanceAnalysis() {}
932
933 void setAA(AliasAnalysis *aa) { AA = aa; }
934
935 AliasAnalysis *getAA() const { return AA; }
936
937 bool related(const Value *A, const Value *B);
938
939 void clear() {
940 CachedResults.clear();
941 }
942 };
943}
944
945bool ProvenanceAnalysis::relatedSelect(const SelectInst *A, const Value *B) {
946 // If the values are Selects with the same condition, we can do a more precise
947 // check: just check for relations between the values on corresponding arms.
948 if (const SelectInst *SB = dyn_cast<SelectInst>(B))
949 if (A->getCondition() == SB->getCondition()) {
950 if (related(A->getTrueValue(), SB->getTrueValue()))
951 return true;
952 if (related(A->getFalseValue(), SB->getFalseValue()))
953 return true;
954 return false;
955 }
956
957 // Check both arms of the Select node individually.
958 if (related(A->getTrueValue(), B))
959 return true;
960 if (related(A->getFalseValue(), B))
961 return true;
962
963 // The arms both checked out.
964 return false;
965}
966
967bool ProvenanceAnalysis::relatedPHI(const PHINode *A, const Value *B) {
968 // If the values are PHIs in the same block, we can do a more precise as well
969 // as efficient check: just check for relations between the values on
970 // corresponding edges.
971 if (const PHINode *PNB = dyn_cast<PHINode>(B))
972 if (PNB->getParent() == A->getParent()) {
973 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i)
974 if (related(A->getIncomingValue(i),
975 PNB->getIncomingValueForBlock(A->getIncomingBlock(i))))
976 return true;
977 return false;
978 }
979
980 // Check each unique source of the PHI node against B.
981 SmallPtrSet<const Value *, 4> UniqueSrc;
982 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i) {
983 const Value *PV1 = A->getIncomingValue(i);
984 if (UniqueSrc.insert(PV1) && related(PV1, B))
985 return true;
986 }
987
988 // All of the arms checked out.
989 return false;
990}
991
992/// isStoredObjCPointer - Test if the value of P, or any value covered by its
993/// provenance, is ever stored within the function (not counting callees).
994static bool isStoredObjCPointer(const Value *P) {
995 SmallPtrSet<const Value *, 8> Visited;
996 SmallVector<const Value *, 8> Worklist;
997 Worklist.push_back(P);
998 Visited.insert(P);
999 do {
1000 P = Worklist.pop_back_val();
1001 for (Value::const_use_iterator UI = P->use_begin(), UE = P->use_end();
1002 UI != UE; ++UI) {
1003 const User *Ur = *UI;
1004 if (isa<StoreInst>(Ur)) {
1005 if (UI.getOperandNo() == 0)
1006 // The pointer is stored.
1007 return true;
1008 // The pointed is stored through.
1009 continue;
1010 }
1011 if (isa<CallInst>(Ur))
1012 // The pointer is passed as an argument, ignore this.
1013 continue;
1014 if (isa<PtrToIntInst>(P))
1015 // Assume the worst.
1016 return true;
1017 if (Visited.insert(Ur))
1018 Worklist.push_back(Ur);
1019 }
1020 } while (!Worklist.empty());
1021
1022 // Everything checked out.
1023 return false;
1024}
1025
1026bool ProvenanceAnalysis::relatedCheck(const Value *A, const Value *B) {
1027 // Skip past provenance pass-throughs.
1028 A = GetUnderlyingObjCPtr(A);
1029 B = GetUnderlyingObjCPtr(B);
1030
1031 // Quick check.
1032 if (A == B)
1033 return true;
1034
1035 // Ask regular AliasAnalysis, for a first approximation.
1036 switch (AA->alias(A, B)) {
1037 case AliasAnalysis::NoAlias:
1038 return false;
1039 case AliasAnalysis::MustAlias:
1040 case AliasAnalysis::PartialAlias:
1041 return true;
1042 case AliasAnalysis::MayAlias:
1043 break;
1044 }
1045
1046 bool AIsIdentified = IsObjCIdentifiedObject(A);
1047 bool BIsIdentified = IsObjCIdentifiedObject(B);
1048
1049 // An ObjC-Identified object can't alias a load if it is never locally stored.
1050 if (AIsIdentified) {
1051 if (BIsIdentified) {
1052 // If both pointers have provenance, they can be directly compared.
1053 if (A != B)
1054 return false;
1055 } else {
1056 if (isa<LoadInst>(B))
1057 return isStoredObjCPointer(A);
1058 }
1059 } else {
1060 if (BIsIdentified && isa<LoadInst>(A))
1061 return isStoredObjCPointer(B);
1062 }
1063
1064 // Special handling for PHI and Select.
1065 if (const PHINode *PN = dyn_cast<PHINode>(A))
1066 return relatedPHI(PN, B);
1067 if (const PHINode *PN = dyn_cast<PHINode>(B))
1068 return relatedPHI(PN, A);
1069 if (const SelectInst *S = dyn_cast<SelectInst>(A))
1070 return relatedSelect(S, B);
1071 if (const SelectInst *S = dyn_cast<SelectInst>(B))
1072 return relatedSelect(S, A);
1073
1074 // Conservative.
1075 return true;
1076}
1077
1078bool ProvenanceAnalysis::related(const Value *A, const Value *B) {
1079 // Begin by inserting a conservative value into the map. If the insertion
1080 // fails, we have the answer already. If it succeeds, leave it there until we
1081 // compute the real answer to guard against recursive queries.
1082 if (A > B) std::swap(A, B);
1083 std::pair<CachedResultsTy::iterator, bool> Pair =
1084 CachedResults.insert(std::make_pair(ValuePairTy(A, B), true));
1085 if (!Pair.second)
1086 return Pair.first->second;
1087
1088 bool Result = relatedCheck(A, B);
1089 CachedResults[ValuePairTy(A, B)] = Result;
1090 return Result;
1091}
1092
1093namespace {
1094 // Sequence - A sequence of states that a pointer may go through in which an
1095 // objc_retain and objc_release are actually needed.
1096 enum Sequence {
1097 S_None,
1098 S_Retain, ///< objc_retain(x)
1099 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement
1100 S_Use, ///< any use of x
1101 S_Stop, ///< like S_Release, but code motion is stopped
1102 S_Release, ///< objc_release(x)
1103 S_MovableRelease ///< objc_release(x), !clang.imprecise_release
1104 };
1105}
1106
1107static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
1108 // The easy cases.
1109 if (A == B)
1110 return A;
1111 if (A == S_None || B == S_None)
1112 return S_None;
1113
John McCall9fbd3182011-06-15 23:37:01 +00001114 if (A > B) std::swap(A, B);
1115 if (TopDown) {
1116 // Choose the side which is further along in the sequence.
Dan Gohmana7f7db22011-08-12 00:26:31 +00001117 if ((A == S_Retain || A == S_CanRelease) &&
1118 (B == S_CanRelease || B == S_Use))
John McCall9fbd3182011-06-15 23:37:01 +00001119 return B;
1120 } else {
1121 // Choose the side which is further along in the sequence.
1122 if ((A == S_Use || A == S_CanRelease) &&
Dan Gohmana7f7db22011-08-12 00:26:31 +00001123 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
John McCall9fbd3182011-06-15 23:37:01 +00001124 return A;
1125 // If both sides are releases, choose the more conservative one.
1126 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
1127 return A;
1128 if (A == S_Release && B == S_MovableRelease)
1129 return A;
1130 }
1131
1132 return S_None;
1133}
1134
1135namespace {
1136 /// RRInfo - Unidirectional information about either a
1137 /// retain-decrement-use-release sequence or release-use-decrement-retain
1138 /// reverese sequence.
1139 struct RRInfo {
Dan Gohmane6d5e882011-08-19 00:26:36 +00001140 /// KnownSafe - After an objc_retain, the reference count of the referenced
1141 /// object is known to be positive. Similarly, before an objc_release, the
1142 /// reference count of the referenced object is known to be positive. If
1143 /// there are retain-release pairs in code regions where the retain count
1144 /// is known to be positive, they can be eliminated, regardless of any side
1145 /// effects between them.
1146 ///
1147 /// Also, a retain+release pair nested within another retain+release
1148 /// pair all on the known same pointer value can be eliminated, regardless
1149 /// of any intervening side effects.
1150 ///
1151 /// KnownSafe is true when either of these conditions is satisfied.
1152 bool KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00001153
1154 /// IsRetainBlock - True if the Calls are objc_retainBlock calls (as
1155 /// opposed to objc_retain calls).
1156 bool IsRetainBlock;
1157
Dan Gohmana974bea2011-10-17 22:53:25 +00001158 /// CopyOnEscape - True if this the Calls are objc_retainBlock calls
1159 /// which all have the !clang.arc.copy_on_escape metadata.
1160 bool CopyOnEscape;
1161
John McCall9fbd3182011-06-15 23:37:01 +00001162 /// IsTailCallRelease - True of the objc_release calls are all marked
1163 /// with the "tail" keyword.
1164 bool IsTailCallRelease;
1165
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001166 /// Partial - True of we've seen an opportunity for partial RR elimination,
1167 /// such as pushing calls into a CFG triangle or into one side of a
1168 /// CFG diamond.
Dan Gohmanafee0272011-12-12 18:30:26 +00001169 /// TODO: Consider moving this to PtrState.
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001170 bool Partial;
1171
John McCall9fbd3182011-06-15 23:37:01 +00001172 /// ReleaseMetadata - If the Calls are objc_release calls and they all have
1173 /// a clang.imprecise_release tag, this is the metadata tag.
1174 MDNode *ReleaseMetadata;
1175
1176 /// Calls - For a top-down sequence, the set of objc_retains or
1177 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
1178 SmallPtrSet<Instruction *, 2> Calls;
1179
1180 /// ReverseInsertPts - The set of optimal insert positions for
1181 /// moving calls in the opposite sequence.
1182 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
1183
1184 RRInfo() :
Dan Gohmana974bea2011-10-17 22:53:25 +00001185 KnownSafe(false), IsRetainBlock(false), CopyOnEscape(false),
1186 IsTailCallRelease(false), Partial(false),
John McCall9fbd3182011-06-15 23:37:01 +00001187 ReleaseMetadata(0) {}
1188
1189 void clear();
1190 };
1191}
1192
1193void RRInfo::clear() {
Dan Gohmane6d5e882011-08-19 00:26:36 +00001194 KnownSafe = false;
John McCall9fbd3182011-06-15 23:37:01 +00001195 IsRetainBlock = false;
Dan Gohmana974bea2011-10-17 22:53:25 +00001196 CopyOnEscape = false;
John McCall9fbd3182011-06-15 23:37:01 +00001197 IsTailCallRelease = false;
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001198 Partial = false;
John McCall9fbd3182011-06-15 23:37:01 +00001199 ReleaseMetadata = 0;
1200 Calls.clear();
1201 ReverseInsertPts.clear();
1202}
1203
1204namespace {
1205 /// PtrState - This class summarizes several per-pointer runtime properties
1206 /// which are propogated through the flow graph.
1207 class PtrState {
1208 /// RefCount - The known minimum number of reference count increments.
1209 unsigned RefCount;
1210
Dan Gohmane6d5e882011-08-19 00:26:36 +00001211 /// NestCount - The known minimum level of retain+release nesting.
1212 unsigned NestCount;
1213
John McCall9fbd3182011-06-15 23:37:01 +00001214 /// Seq - The current position in the sequence.
1215 Sequence Seq;
1216
1217 public:
1218 /// RRI - Unidirectional information about the current sequence.
1219 /// TODO: Encapsulate this better.
1220 RRInfo RRI;
1221
Dan Gohmane6d5e882011-08-19 00:26:36 +00001222 PtrState() : RefCount(0), NestCount(0), Seq(S_None) {}
John McCall9fbd3182011-06-15 23:37:01 +00001223
Dan Gohmana7f7db22011-08-12 00:26:31 +00001224 void SetAtLeastOneRefCount() {
1225 if (RefCount == 0) RefCount = 1;
1226 }
1227
John McCall9fbd3182011-06-15 23:37:01 +00001228 void IncrementRefCount() {
1229 if (RefCount != UINT_MAX) ++RefCount;
1230 }
1231
1232 void DecrementRefCount() {
1233 if (RefCount != 0) --RefCount;
1234 }
1235
John McCall9fbd3182011-06-15 23:37:01 +00001236 bool IsKnownIncremented() const {
1237 return RefCount > 0;
1238 }
1239
Dan Gohmane6d5e882011-08-19 00:26:36 +00001240 void IncrementNestCount() {
1241 if (NestCount != UINT_MAX) ++NestCount;
1242 }
1243
1244 void DecrementNestCount() {
1245 if (NestCount != 0) --NestCount;
1246 }
1247
1248 bool IsKnownNested() const {
1249 return NestCount > 0;
1250 }
1251
John McCall9fbd3182011-06-15 23:37:01 +00001252 void SetSeq(Sequence NewSeq) {
1253 Seq = NewSeq;
1254 }
1255
John McCall9fbd3182011-06-15 23:37:01 +00001256 Sequence GetSeq() const {
1257 return Seq;
1258 }
1259
1260 void ClearSequenceProgress() {
1261 Seq = S_None;
1262 RRI.clear();
1263 }
1264
1265 void Merge(const PtrState &Other, bool TopDown);
1266 };
1267}
1268
1269void
1270PtrState::Merge(const PtrState &Other, bool TopDown) {
1271 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
1272 RefCount = std::min(RefCount, Other.RefCount);
Dan Gohmane6d5e882011-08-19 00:26:36 +00001273 NestCount = std::min(NestCount, Other.NestCount);
John McCall9fbd3182011-06-15 23:37:01 +00001274
1275 // We can't merge a plain objc_retain with an objc_retainBlock.
1276 if (RRI.IsRetainBlock != Other.RRI.IsRetainBlock)
1277 Seq = S_None;
1278
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001279 // If we're not in a sequence (anymore), drop all associated state.
John McCall9fbd3182011-06-15 23:37:01 +00001280 if (Seq == S_None) {
1281 RRI.clear();
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001282 } else if (RRI.Partial || Other.RRI.Partial) {
1283 // If we're doing a merge on a path that's previously seen a partial
1284 // merge, conservatively drop the sequence, to avoid doing partial
1285 // RR elimination. If the branch predicates for the two merge differ,
1286 // mixing them is unsafe.
1287 Seq = S_None;
1288 RRI.clear();
John McCall9fbd3182011-06-15 23:37:01 +00001289 } else {
1290 // Conservatively merge the ReleaseMetadata information.
1291 if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
1292 RRI.ReleaseMetadata = 0;
1293
Dan Gohmana974bea2011-10-17 22:53:25 +00001294 RRI.CopyOnEscape = RRI.CopyOnEscape && Other.RRI.CopyOnEscape;
Dan Gohmane6d5e882011-08-19 00:26:36 +00001295 RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00001296 RRI.IsTailCallRelease = RRI.IsTailCallRelease && Other.RRI.IsTailCallRelease;
1297 RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001298
1299 // Merge the insert point sets. If there are any differences,
1300 // that makes this a partial merge.
1301 RRI.Partial = RRI.ReverseInsertPts.size() !=
1302 Other.RRI.ReverseInsertPts.size();
1303 for (SmallPtrSet<Instruction *, 2>::const_iterator
1304 I = Other.RRI.ReverseInsertPts.begin(),
1305 E = Other.RRI.ReverseInsertPts.end(); I != E; ++I)
1306 RRI.Partial |= RRI.ReverseInsertPts.insert(*I);
John McCall9fbd3182011-06-15 23:37:01 +00001307 }
1308}
1309
1310namespace {
1311 /// BBState - Per-BasicBlock state.
1312 class BBState {
1313 /// TopDownPathCount - The number of unique control paths from the entry
1314 /// which can reach this block.
1315 unsigned TopDownPathCount;
1316
1317 /// BottomUpPathCount - The number of unique control paths to exits
1318 /// from this block.
1319 unsigned BottomUpPathCount;
1320
1321 /// MapTy - A type for PerPtrTopDown and PerPtrBottomUp.
1322 typedef MapVector<const Value *, PtrState> MapTy;
1323
1324 /// PerPtrTopDown - The top-down traversal uses this to record information
1325 /// known about a pointer at the bottom of each block.
1326 MapTy PerPtrTopDown;
1327
1328 /// PerPtrBottomUp - The bottom-up traversal uses this to record information
1329 /// known about a pointer at the top of each block.
1330 MapTy PerPtrBottomUp;
1331
1332 public:
1333 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
1334
1335 typedef MapTy::iterator ptr_iterator;
1336 typedef MapTy::const_iterator ptr_const_iterator;
1337
1338 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
1339 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
1340 ptr_const_iterator top_down_ptr_begin() const {
1341 return PerPtrTopDown.begin();
1342 }
1343 ptr_const_iterator top_down_ptr_end() const {
1344 return PerPtrTopDown.end();
1345 }
1346
1347 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
1348 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
1349 ptr_const_iterator bottom_up_ptr_begin() const {
1350 return PerPtrBottomUp.begin();
1351 }
1352 ptr_const_iterator bottom_up_ptr_end() const {
1353 return PerPtrBottomUp.end();
1354 }
1355
1356 /// SetAsEntry - Mark this block as being an entry block, which has one
1357 /// path from the entry by definition.
1358 void SetAsEntry() { TopDownPathCount = 1; }
1359
1360 /// SetAsExit - Mark this block as being an exit block, which has one
1361 /// path to an exit by definition.
1362 void SetAsExit() { BottomUpPathCount = 1; }
1363
1364 PtrState &getPtrTopDownState(const Value *Arg) {
1365 return PerPtrTopDown[Arg];
1366 }
1367
1368 PtrState &getPtrBottomUpState(const Value *Arg) {
1369 return PerPtrBottomUp[Arg];
1370 }
1371
1372 void clearBottomUpPointers() {
Evan Chenga81388f2011-08-04 18:40:26 +00001373 PerPtrBottomUp.clear();
John McCall9fbd3182011-06-15 23:37:01 +00001374 }
1375
1376 void clearTopDownPointers() {
1377 PerPtrTopDown.clear();
1378 }
1379
1380 void InitFromPred(const BBState &Other);
1381 void InitFromSucc(const BBState &Other);
1382 void MergePred(const BBState &Other);
1383 void MergeSucc(const BBState &Other);
1384
1385 /// GetAllPathCount - Return the number of possible unique paths from an
1386 /// entry to an exit which pass through this block. This is only valid
1387 /// after both the top-down and bottom-up traversals are complete.
1388 unsigned GetAllPathCount() const {
1389 return TopDownPathCount * BottomUpPathCount;
1390 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00001391
1392 /// IsVisitedTopDown - Test whether the block for this BBState has been
1393 /// visited by the top-down portion of the algorithm.
1394 bool isVisitedTopDown() const {
1395 return TopDownPathCount != 0;
1396 }
John McCall9fbd3182011-06-15 23:37:01 +00001397 };
1398}
1399
1400void BBState::InitFromPred(const BBState &Other) {
1401 PerPtrTopDown = Other.PerPtrTopDown;
1402 TopDownPathCount = Other.TopDownPathCount;
1403}
1404
1405void BBState::InitFromSucc(const BBState &Other) {
1406 PerPtrBottomUp = Other.PerPtrBottomUp;
1407 BottomUpPathCount = Other.BottomUpPathCount;
1408}
1409
1410/// MergePred - The top-down traversal uses this to merge information about
1411/// predecessors to form the initial state for a new block.
1412void BBState::MergePred(const BBState &Other) {
1413 // Other.TopDownPathCount can be 0, in which case it is either dead or a
1414 // loop backedge. Loop backedges are special.
1415 TopDownPathCount += Other.TopDownPathCount;
1416
1417 // For each entry in the other set, if our set has an entry with the same key,
1418 // merge the entries. Otherwise, copy the entry and merge it with an empty
1419 // entry.
1420 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
1421 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
1422 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
1423 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1424 /*TopDown=*/true);
1425 }
1426
Dan Gohmanfa7eed12011-08-11 21:06:32 +00001427 // For each entry in our set, if the other set doesn't have an entry with the
John McCall9fbd3182011-06-15 23:37:01 +00001428 // same key, force it to merge with an empty entry.
1429 for (ptr_iterator MI = top_down_ptr_begin(),
1430 ME = top_down_ptr_end(); MI != ME; ++MI)
1431 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
1432 MI->second.Merge(PtrState(), /*TopDown=*/true);
1433}
1434
1435/// MergeSucc - The bottom-up traversal uses this to merge information about
1436/// successors to form the initial state for a new block.
1437void BBState::MergeSucc(const BBState &Other) {
1438 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
1439 // loop backedge. Loop backedges are special.
1440 BottomUpPathCount += Other.BottomUpPathCount;
1441
1442 // For each entry in the other set, if our set has an entry with the
1443 // same key, merge the entries. Otherwise, copy the entry and merge
1444 // it with an empty entry.
1445 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
1446 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
1447 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
1448 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1449 /*TopDown=*/false);
1450 }
1451
Dan Gohmanfa7eed12011-08-11 21:06:32 +00001452 // For each entry in our set, if the other set doesn't have an entry
John McCall9fbd3182011-06-15 23:37:01 +00001453 // with the same key, force it to merge with an empty entry.
1454 for (ptr_iterator MI = bottom_up_ptr_begin(),
1455 ME = bottom_up_ptr_end(); MI != ME; ++MI)
1456 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
1457 MI->second.Merge(PtrState(), /*TopDown=*/false);
1458}
1459
1460namespace {
1461 /// ObjCARCOpt - The main ARC optimization pass.
1462 class ObjCARCOpt : public FunctionPass {
1463 bool Changed;
1464 ProvenanceAnalysis PA;
1465
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00001466 /// Run - A flag indicating whether this optimization pass should run.
1467 bool Run;
1468
John McCall9fbd3182011-06-15 23:37:01 +00001469 /// RetainRVCallee, etc. - Declarations for ObjC runtime
1470 /// functions, for use in creating calls to them. These are initialized
1471 /// lazily to avoid cluttering up the Module with unused declarations.
1472 Constant *RetainRVCallee, *AutoreleaseRVCallee, *ReleaseCallee,
Dan Gohman44280692011-07-22 22:29:21 +00001473 *RetainCallee, *RetainBlockCallee, *AutoreleaseCallee;
John McCall9fbd3182011-06-15 23:37:01 +00001474
1475 /// UsedInThisFunciton - Flags which determine whether each of the
1476 /// interesting runtine functions is in fact used in the current function.
1477 unsigned UsedInThisFunction;
1478
1479 /// ImpreciseReleaseMDKind - The Metadata Kind for clang.imprecise_release
1480 /// metadata.
1481 unsigned ImpreciseReleaseMDKind;
1482
Dan Gohman62e5b402011-12-12 18:20:00 +00001483 /// CopyOnEscapeMDKind - The Metadata Kind for clang.arc.copy_on_escape
Dan Gohmana974bea2011-10-17 22:53:25 +00001484 /// metadata.
1485 unsigned CopyOnEscapeMDKind;
1486
John McCall9fbd3182011-06-15 23:37:01 +00001487 Constant *getRetainRVCallee(Module *M);
1488 Constant *getAutoreleaseRVCallee(Module *M);
1489 Constant *getReleaseCallee(Module *M);
1490 Constant *getRetainCallee(Module *M);
Dan Gohman44280692011-07-22 22:29:21 +00001491 Constant *getRetainBlockCallee(Module *M);
John McCall9fbd3182011-06-15 23:37:01 +00001492 Constant *getAutoreleaseCallee(Module *M);
1493
1494 void OptimizeRetainCall(Function &F, Instruction *Retain);
1495 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
1496 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV);
1497 void OptimizeIndividualCalls(Function &F);
1498
1499 void CheckForCFGHazards(const BasicBlock *BB,
1500 DenseMap<const BasicBlock *, BBState> &BBStates,
1501 BBState &MyStates) const;
1502 bool VisitBottomUp(BasicBlock *BB,
1503 DenseMap<const BasicBlock *, BBState> &BBStates,
1504 MapVector<Value *, RRInfo> &Retains);
1505 bool VisitTopDown(BasicBlock *BB,
1506 DenseMap<const BasicBlock *, BBState> &BBStates,
1507 DenseMap<Value *, RRInfo> &Releases);
1508 bool Visit(Function &F,
1509 DenseMap<const BasicBlock *, BBState> &BBStates,
1510 MapVector<Value *, RRInfo> &Retains,
1511 DenseMap<Value *, RRInfo> &Releases);
1512
1513 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1514 MapVector<Value *, RRInfo> &Retains,
1515 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman44280692011-07-22 22:29:21 +00001516 SmallVectorImpl<Instruction *> &DeadInsts,
1517 Module *M);
John McCall9fbd3182011-06-15 23:37:01 +00001518
1519 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1520 MapVector<Value *, RRInfo> &Retains,
Dan Gohman44280692011-07-22 22:29:21 +00001521 DenseMap<Value *, RRInfo> &Releases,
1522 Module *M);
John McCall9fbd3182011-06-15 23:37:01 +00001523
1524 void OptimizeWeakCalls(Function &F);
1525
1526 bool OptimizeSequences(Function &F);
1527
1528 void OptimizeReturns(Function &F);
1529
1530 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1531 virtual bool doInitialization(Module &M);
1532 virtual bool runOnFunction(Function &F);
1533 virtual void releaseMemory();
1534
1535 public:
1536 static char ID;
1537 ObjCARCOpt() : FunctionPass(ID) {
1538 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1539 }
1540 };
1541}
1542
1543char ObjCARCOpt::ID = 0;
1544INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1545 "objc-arc", "ObjC ARC optimization", false, false)
1546INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1547INITIALIZE_PASS_END(ObjCARCOpt,
1548 "objc-arc", "ObjC ARC optimization", false, false)
1549
1550Pass *llvm::createObjCARCOptPass() {
1551 return new ObjCARCOpt();
1552}
1553
1554void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1555 AU.addRequired<ObjCARCAliasAnalysis>();
1556 AU.addRequired<AliasAnalysis>();
1557 // ARC optimization doesn't currently split critical edges.
1558 AU.setPreservesCFG();
1559}
1560
1561Constant *ObjCARCOpt::getRetainRVCallee(Module *M) {
1562 if (!RetainRVCallee) {
1563 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001564 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1565 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00001566 Params.push_back(I8X);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001567 FunctionType *FTy =
John McCall9fbd3182011-06-15 23:37:01 +00001568 FunctionType::get(I8X, Params, /*isVarArg=*/false);
1569 AttrListPtr Attributes;
1570 Attributes.addAttr(~0u, Attribute::NoUnwind);
1571 RetainRVCallee =
1572 M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy,
1573 Attributes);
1574 }
1575 return RetainRVCallee;
1576}
1577
1578Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1579 if (!AutoreleaseRVCallee) {
1580 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001581 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1582 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00001583 Params.push_back(I8X);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001584 FunctionType *FTy =
John McCall9fbd3182011-06-15 23:37:01 +00001585 FunctionType::get(I8X, Params, /*isVarArg=*/false);
1586 AttrListPtr Attributes;
1587 Attributes.addAttr(~0u, Attribute::NoUnwind);
1588 AutoreleaseRVCallee =
1589 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
1590 Attributes);
1591 }
1592 return AutoreleaseRVCallee;
1593}
1594
1595Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1596 if (!ReleaseCallee) {
1597 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001598 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00001599 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1600 AttrListPtr Attributes;
1601 Attributes.addAttr(~0u, Attribute::NoUnwind);
1602 ReleaseCallee =
1603 M->getOrInsertFunction(
1604 "objc_release",
1605 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
1606 Attributes);
1607 }
1608 return ReleaseCallee;
1609}
1610
1611Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1612 if (!RetainCallee) {
1613 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001614 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00001615 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1616 AttrListPtr Attributes;
1617 Attributes.addAttr(~0u, Attribute::NoUnwind);
1618 RetainCallee =
1619 M->getOrInsertFunction(
1620 "objc_retain",
1621 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1622 Attributes);
1623 }
1624 return RetainCallee;
1625}
1626
Dan Gohman44280692011-07-22 22:29:21 +00001627Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1628 if (!RetainBlockCallee) {
1629 LLVMContext &C = M->getContext();
1630 std::vector<Type *> Params;
1631 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1632 AttrListPtr Attributes;
Dan Gohman1d2fd752011-09-14 18:33:34 +00001633 // objc_retainBlock is not nounwind because it calls user copy constructors
1634 // which could theoretically throw.
Dan Gohman44280692011-07-22 22:29:21 +00001635 RetainBlockCallee =
1636 M->getOrInsertFunction(
1637 "objc_retainBlock",
1638 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1639 Attributes);
1640 }
1641 return RetainBlockCallee;
1642}
1643
John McCall9fbd3182011-06-15 23:37:01 +00001644Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1645 if (!AutoreleaseCallee) {
1646 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001647 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00001648 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1649 AttrListPtr Attributes;
1650 Attributes.addAttr(~0u, Attribute::NoUnwind);
1651 AutoreleaseCallee =
1652 M->getOrInsertFunction(
1653 "objc_autorelease",
1654 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1655 Attributes);
1656 }
1657 return AutoreleaseCallee;
1658}
1659
1660/// CanAlterRefCount - Test whether the given instruction can result in a
1661/// reference count modification (positive or negative) for the pointer's
1662/// object.
1663static bool
1664CanAlterRefCount(const Instruction *Inst, const Value *Ptr,
1665 ProvenanceAnalysis &PA, InstructionClass Class) {
1666 switch (Class) {
1667 case IC_Autorelease:
1668 case IC_AutoreleaseRV:
1669 case IC_User:
1670 // These operations never directly modify a reference count.
1671 return false;
1672 default: break;
1673 }
1674
1675 ImmutableCallSite CS = static_cast<const Value *>(Inst);
1676 assert(CS && "Only calls can alter reference counts!");
1677
1678 // See if AliasAnalysis can help us with the call.
1679 AliasAnalysis::ModRefBehavior MRB = PA.getAA()->getModRefBehavior(CS);
1680 if (AliasAnalysis::onlyReadsMemory(MRB))
1681 return false;
1682 if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
1683 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1684 I != E; ++I) {
1685 const Value *Op = *I;
1686 if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1687 return true;
1688 }
1689 return false;
1690 }
1691
1692 // Assume the worst.
1693 return true;
1694}
1695
1696/// CanUse - Test whether the given instruction can "use" the given pointer's
1697/// object in a way that requires the reference count to be positive.
1698static bool
1699CanUse(const Instruction *Inst, const Value *Ptr, ProvenanceAnalysis &PA,
1700 InstructionClass Class) {
1701 // IC_Call operations (as opposed to IC_CallOrUser) never "use" objc pointers.
1702 if (Class == IC_Call)
1703 return false;
1704
1705 // Consider various instructions which may have pointer arguments which are
1706 // not "uses".
1707 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(Inst)) {
1708 // Comparing a pointer with null, or any other constant, isn't really a use,
1709 // because we don't care what the pointer points to, or about the values
1710 // of any other dynamic reference-counted pointers.
1711 if (!IsPotentialUse(ICI->getOperand(1)))
1712 return false;
1713 } else if (ImmutableCallSite CS = static_cast<const Value *>(Inst)) {
1714 // For calls, just check the arguments (and not the callee operand).
1715 for (ImmutableCallSite::arg_iterator OI = CS.arg_begin(),
1716 OE = CS.arg_end(); OI != OE; ++OI) {
1717 const Value *Op = *OI;
1718 if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1719 return true;
1720 }
1721 return false;
1722 } else if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1723 // Special-case stores, because we don't care about the stored value, just
1724 // the store address.
1725 const Value *Op = GetUnderlyingObjCPtr(SI->getPointerOperand());
1726 // If we can't tell what the underlying object was, assume there is a
1727 // dependence.
1728 return IsPotentialUse(Op) && PA.related(Op, Ptr);
1729 }
1730
1731 // Check each operand for a match.
1732 for (User::const_op_iterator OI = Inst->op_begin(), OE = Inst->op_end();
1733 OI != OE; ++OI) {
1734 const Value *Op = *OI;
1735 if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1736 return true;
1737 }
1738 return false;
1739}
1740
1741/// CanInterruptRV - Test whether the given instruction can autorelease
1742/// any pointer or cause an autoreleasepool pop.
1743static bool
1744CanInterruptRV(InstructionClass Class) {
1745 switch (Class) {
1746 case IC_AutoreleasepoolPop:
1747 case IC_CallOrUser:
1748 case IC_Call:
1749 case IC_Autorelease:
1750 case IC_AutoreleaseRV:
1751 case IC_FusedRetainAutorelease:
1752 case IC_FusedRetainAutoreleaseRV:
1753 return true;
1754 default:
1755 return false;
1756 }
1757}
1758
1759namespace {
1760 /// DependenceKind - There are several kinds of dependence-like concepts in
1761 /// use here.
1762 enum DependenceKind {
1763 NeedsPositiveRetainCount,
1764 CanChangeRetainCount,
1765 RetainAutoreleaseDep, ///< Blocks objc_retainAutorelease.
1766 RetainAutoreleaseRVDep, ///< Blocks objc_retainAutoreleaseReturnValue.
1767 RetainRVDep ///< Blocks objc_retainAutoreleasedReturnValue.
1768 };
1769}
1770
1771/// Depends - Test if there can be dependencies on Inst through Arg. This
1772/// function only tests dependencies relevant for removing pairs of calls.
1773static bool
1774Depends(DependenceKind Flavor, Instruction *Inst, const Value *Arg,
1775 ProvenanceAnalysis &PA) {
1776 // If we've reached the definition of Arg, stop.
1777 if (Inst == Arg)
1778 return true;
1779
1780 switch (Flavor) {
1781 case NeedsPositiveRetainCount: {
1782 InstructionClass Class = GetInstructionClass(Inst);
1783 switch (Class) {
1784 case IC_AutoreleasepoolPop:
1785 case IC_AutoreleasepoolPush:
1786 case IC_None:
1787 return false;
1788 default:
1789 return CanUse(Inst, Arg, PA, Class);
1790 }
1791 }
1792
1793 case CanChangeRetainCount: {
1794 InstructionClass Class = GetInstructionClass(Inst);
1795 switch (Class) {
1796 case IC_AutoreleasepoolPop:
1797 // Conservatively assume this can decrement any count.
1798 return true;
1799 case IC_AutoreleasepoolPush:
1800 case IC_None:
1801 return false;
1802 default:
1803 return CanAlterRefCount(Inst, Arg, PA, Class);
1804 }
1805 }
1806
1807 case RetainAutoreleaseDep:
1808 switch (GetBasicInstructionClass(Inst)) {
1809 case IC_AutoreleasepoolPop:
1810 // Don't merge an objc_autorelease with an objc_retain inside a different
1811 // autoreleasepool scope.
1812 return true;
1813 case IC_Retain:
1814 case IC_RetainRV:
1815 // Check for a retain of the same pointer for merging.
1816 return GetObjCArg(Inst) == Arg;
1817 default:
1818 // Nothing else matters for objc_retainAutorelease formation.
1819 return false;
1820 }
1821 break;
1822
1823 case RetainAutoreleaseRVDep: {
1824 InstructionClass Class = GetBasicInstructionClass(Inst);
1825 switch (Class) {
1826 case IC_Retain:
1827 case IC_RetainRV:
1828 // Check for a retain of the same pointer for merging.
1829 return GetObjCArg(Inst) == Arg;
1830 default:
1831 // Anything that can autorelease interrupts
1832 // retainAutoreleaseReturnValue formation.
1833 return CanInterruptRV(Class);
1834 }
1835 break;
1836 }
1837
1838 case RetainRVDep:
1839 return CanInterruptRV(GetBasicInstructionClass(Inst));
1840 }
1841
1842 llvm_unreachable("Invalid dependence flavor");
1843 return true;
1844}
1845
1846/// FindDependencies - Walk up the CFG from StartPos (which is in StartBB) and
1847/// find local and non-local dependencies on Arg.
1848/// TODO: Cache results?
1849static void
1850FindDependencies(DependenceKind Flavor,
1851 const Value *Arg,
1852 BasicBlock *StartBB, Instruction *StartInst,
1853 SmallPtrSet<Instruction *, 4> &DependingInstructions,
1854 SmallPtrSet<const BasicBlock *, 4> &Visited,
1855 ProvenanceAnalysis &PA) {
1856 BasicBlock::iterator StartPos = StartInst;
1857
1858 SmallVector<std::pair<BasicBlock *, BasicBlock::iterator>, 4> Worklist;
1859 Worklist.push_back(std::make_pair(StartBB, StartPos));
1860 do {
1861 std::pair<BasicBlock *, BasicBlock::iterator> Pair =
1862 Worklist.pop_back_val();
1863 BasicBlock *LocalStartBB = Pair.first;
1864 BasicBlock::iterator LocalStartPos = Pair.second;
1865 BasicBlock::iterator StartBBBegin = LocalStartBB->begin();
1866 for (;;) {
1867 if (LocalStartPos == StartBBBegin) {
1868 pred_iterator PI(LocalStartBB), PE(LocalStartBB, false);
1869 if (PI == PE)
1870 // If we've reached the function entry, produce a null dependence.
1871 DependingInstructions.insert(0);
1872 else
1873 // Add the predecessors to the worklist.
1874 do {
1875 BasicBlock *PredBB = *PI;
1876 if (Visited.insert(PredBB))
1877 Worklist.push_back(std::make_pair(PredBB, PredBB->end()));
1878 } while (++PI != PE);
1879 break;
1880 }
1881
1882 Instruction *Inst = --LocalStartPos;
1883 if (Depends(Flavor, Inst, Arg, PA)) {
1884 DependingInstructions.insert(Inst);
1885 break;
1886 }
1887 }
1888 } while (!Worklist.empty());
1889
1890 // Determine whether the original StartBB post-dominates all of the blocks we
1891 // visited. If not, insert a sentinal indicating that most optimizations are
1892 // not safe.
1893 for (SmallPtrSet<const BasicBlock *, 4>::const_iterator I = Visited.begin(),
1894 E = Visited.end(); I != E; ++I) {
1895 const BasicBlock *BB = *I;
1896 if (BB == StartBB)
1897 continue;
1898 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
1899 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
1900 const BasicBlock *Succ = *SI;
1901 if (Succ != StartBB && !Visited.count(Succ)) {
1902 DependingInstructions.insert(reinterpret_cast<Instruction *>(-1));
1903 return;
1904 }
1905 }
1906 }
1907}
1908
1909static bool isNullOrUndef(const Value *V) {
1910 return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
1911}
1912
1913static bool isNoopInstruction(const Instruction *I) {
1914 return isa<BitCastInst>(I) ||
1915 (isa<GetElementPtrInst>(I) &&
1916 cast<GetElementPtrInst>(I)->hasAllZeroIndices());
1917}
1918
1919/// OptimizeRetainCall - Turn objc_retain into
1920/// objc_retainAutoreleasedReturnValue if the operand is a return value.
1921void
1922ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) {
1923 CallSite CS(GetObjCArg(Retain));
1924 Instruction *Call = CS.getInstruction();
1925 if (!Call) return;
1926 if (Call->getParent() != Retain->getParent()) return;
1927
1928 // Check that the call is next to the retain.
1929 BasicBlock::iterator I = Call;
1930 ++I;
1931 while (isNoopInstruction(I)) ++I;
1932 if (&*I != Retain)
1933 return;
1934
1935 // Turn it to an objc_retainAutoreleasedReturnValue..
1936 Changed = true;
1937 ++NumPeeps;
1938 cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent()));
1939}
1940
1941/// OptimizeRetainRVCall - Turn objc_retainAutoreleasedReturnValue into
1942/// objc_retain if the operand is not a return value. Or, if it can be
1943/// paired with an objc_autoreleaseReturnValue, delete the pair and
1944/// return true.
1945bool
1946ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
1947 // Check for the argument being from an immediately preceding call.
1948 Value *Arg = GetObjCArg(RetainRV);
1949 CallSite CS(Arg);
1950 if (Instruction *Call = CS.getInstruction())
1951 if (Call->getParent() == RetainRV->getParent()) {
1952 BasicBlock::iterator I = Call;
1953 ++I;
1954 while (isNoopInstruction(I)) ++I;
1955 if (&*I == RetainRV)
1956 return false;
1957 }
1958
1959 // Check for being preceded by an objc_autoreleaseReturnValue on the same
1960 // pointer. In this case, we can delete the pair.
1961 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
1962 if (I != Begin) {
1963 do --I; while (I != Begin && isNoopInstruction(I));
1964 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
1965 GetObjCArg(I) == Arg) {
1966 Changed = true;
1967 ++NumPeeps;
1968 EraseInstruction(I);
1969 EraseInstruction(RetainRV);
1970 return true;
1971 }
1972 }
1973
1974 // Turn it to a plain objc_retain.
1975 Changed = true;
1976 ++NumPeeps;
1977 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
1978 return false;
1979}
1980
1981/// OptimizeAutoreleaseRVCall - Turn objc_autoreleaseReturnValue into
1982/// objc_autorelease if the result is not used as a return value.
1983void
1984ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV) {
1985 // Check for a return of the pointer value.
1986 const Value *Ptr = GetObjCArg(AutoreleaseRV);
Dan Gohman126a54f2011-08-12 00:36:31 +00001987 SmallVector<const Value *, 2> Users;
1988 Users.push_back(Ptr);
1989 do {
1990 Ptr = Users.pop_back_val();
1991 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
1992 UI != UE; ++UI) {
1993 const User *I = *UI;
1994 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
1995 return;
1996 if (isa<BitCastInst>(I))
1997 Users.push_back(I);
1998 }
1999 } while (!Users.empty());
John McCall9fbd3182011-06-15 23:37:01 +00002000
2001 Changed = true;
2002 ++NumPeeps;
2003 cast<CallInst>(AutoreleaseRV)->
2004 setCalledFunction(getAutoreleaseCallee(F.getParent()));
2005}
2006
2007/// OptimizeIndividualCalls - Visit each call, one at a time, and make
2008/// simplifications without doing any additional analysis.
2009void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
2010 // Reset all the flags in preparation for recomputing them.
2011 UsedInThisFunction = 0;
2012
2013 // Visit all objc_* calls in F.
2014 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2015 Instruction *Inst = &*I++;
2016 InstructionClass Class = GetBasicInstructionClass(Inst);
2017
2018 switch (Class) {
2019 default: break;
2020
2021 // Delete no-op casts. These function calls have special semantics, but
2022 // the semantics are entirely implemented via lowering in the front-end,
2023 // so by the time they reach the optimizer, they are just no-op calls
2024 // which return their argument.
2025 //
2026 // There are gray areas here, as the ability to cast reference-counted
2027 // pointers to raw void* and back allows code to break ARC assumptions,
2028 // however these are currently considered to be unimportant.
2029 case IC_NoopCast:
2030 Changed = true;
2031 ++NumNoops;
2032 EraseInstruction(Inst);
2033 continue;
2034
2035 // If the pointer-to-weak-pointer is null, it's undefined behavior.
2036 case IC_StoreWeak:
2037 case IC_LoadWeak:
2038 case IC_LoadWeakRetained:
2039 case IC_InitWeak:
2040 case IC_DestroyWeak: {
2041 CallInst *CI = cast<CallInst>(Inst);
2042 if (isNullOrUndef(CI->getArgOperand(0))) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002043 Type *Ty = CI->getArgOperand(0)->getType();
John McCall9fbd3182011-06-15 23:37:01 +00002044 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2045 Constant::getNullValue(Ty),
2046 CI);
2047 CI->replaceAllUsesWith(UndefValue::get(CI->getType()));
2048 CI->eraseFromParent();
2049 continue;
2050 }
2051 break;
2052 }
2053 case IC_CopyWeak:
2054 case IC_MoveWeak: {
2055 CallInst *CI = cast<CallInst>(Inst);
2056 if (isNullOrUndef(CI->getArgOperand(0)) ||
2057 isNullOrUndef(CI->getArgOperand(1))) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002058 Type *Ty = CI->getArgOperand(0)->getType();
John McCall9fbd3182011-06-15 23:37:01 +00002059 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2060 Constant::getNullValue(Ty),
2061 CI);
2062 CI->replaceAllUsesWith(UndefValue::get(CI->getType()));
2063 CI->eraseFromParent();
2064 continue;
2065 }
2066 break;
2067 }
2068 case IC_Retain:
2069 OptimizeRetainCall(F, Inst);
2070 break;
2071 case IC_RetainRV:
2072 if (OptimizeRetainRVCall(F, Inst))
2073 continue;
2074 break;
2075 case IC_AutoreleaseRV:
2076 OptimizeAutoreleaseRVCall(F, Inst);
2077 break;
2078 }
2079
2080 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
2081 if (IsAutorelease(Class) && Inst->use_empty()) {
2082 CallInst *Call = cast<CallInst>(Inst);
2083 const Value *Arg = Call->getArgOperand(0);
2084 Arg = FindSingleUseIdentifiedObject(Arg);
2085 if (Arg) {
2086 Changed = true;
2087 ++NumAutoreleases;
2088
2089 // Create the declaration lazily.
2090 LLVMContext &C = Inst->getContext();
2091 CallInst *NewCall =
2092 CallInst::Create(getReleaseCallee(F.getParent()),
2093 Call->getArgOperand(0), "", Call);
2094 NewCall->setMetadata(ImpreciseReleaseMDKind,
2095 MDNode::get(C, ArrayRef<Value *>()));
2096 EraseInstruction(Call);
2097 Inst = NewCall;
2098 Class = IC_Release;
2099 }
2100 }
2101
2102 // For functions which can never be passed stack arguments, add
2103 // a tail keyword.
2104 if (IsAlwaysTail(Class)) {
2105 Changed = true;
2106 cast<CallInst>(Inst)->setTailCall();
2107 }
2108
2109 // Set nounwind as needed.
2110 if (IsNoThrow(Class)) {
2111 Changed = true;
2112 cast<CallInst>(Inst)->setDoesNotThrow();
2113 }
2114
2115 if (!IsNoopOnNull(Class)) {
2116 UsedInThisFunction |= 1 << Class;
2117 continue;
2118 }
2119
2120 const Value *Arg = GetObjCArg(Inst);
2121
2122 // ARC calls with null are no-ops. Delete them.
2123 if (isNullOrUndef(Arg)) {
2124 Changed = true;
2125 ++NumNoops;
2126 EraseInstruction(Inst);
2127 continue;
2128 }
2129
2130 // Keep track of which of retain, release, autorelease, and retain_block
2131 // are actually present in this function.
2132 UsedInThisFunction |= 1 << Class;
2133
2134 // If Arg is a PHI, and one or more incoming values to the
2135 // PHI are null, and the call is control-equivalent to the PHI, and there
2136 // are no relevant side effects between the PHI and the call, the call
2137 // could be pushed up to just those paths with non-null incoming values.
2138 // For now, don't bother splitting critical edges for this.
2139 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
2140 Worklist.push_back(std::make_pair(Inst, Arg));
2141 do {
2142 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
2143 Inst = Pair.first;
2144 Arg = Pair.second;
2145
2146 const PHINode *PN = dyn_cast<PHINode>(Arg);
2147 if (!PN) continue;
2148
2149 // Determine if the PHI has any null operands, or any incoming
2150 // critical edges.
2151 bool HasNull = false;
2152 bool HasCriticalEdges = false;
2153 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2154 Value *Incoming =
2155 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2156 if (isNullOrUndef(Incoming))
2157 HasNull = true;
2158 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
2159 .getNumSuccessors() != 1) {
2160 HasCriticalEdges = true;
2161 break;
2162 }
2163 }
2164 // If we have null operands and no critical edges, optimize.
2165 if (!HasCriticalEdges && HasNull) {
2166 SmallPtrSet<Instruction *, 4> DependingInstructions;
2167 SmallPtrSet<const BasicBlock *, 4> Visited;
2168
2169 // Check that there is nothing that cares about the reference
2170 // count between the call and the phi.
2171 FindDependencies(NeedsPositiveRetainCount, Arg,
2172 Inst->getParent(), Inst,
2173 DependingInstructions, Visited, PA);
2174 if (DependingInstructions.size() == 1 &&
2175 *DependingInstructions.begin() == PN) {
2176 Changed = true;
2177 ++NumPartialNoops;
2178 // Clone the call into each predecessor that has a non-null value.
2179 CallInst *CInst = cast<CallInst>(Inst);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002180 Type *ParamTy = CInst->getArgOperand(0)->getType();
John McCall9fbd3182011-06-15 23:37:01 +00002181 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2182 Value *Incoming =
2183 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2184 if (!isNullOrUndef(Incoming)) {
2185 CallInst *Clone = cast<CallInst>(CInst->clone());
2186 Value *Op = PN->getIncomingValue(i);
2187 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
2188 if (Op->getType() != ParamTy)
2189 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
2190 Clone->setArgOperand(0, Op);
2191 Clone->insertBefore(InsertPos);
2192 Worklist.push_back(std::make_pair(Clone, Incoming));
2193 }
2194 }
2195 // Erase the original call.
2196 EraseInstruction(CInst);
2197 continue;
2198 }
2199 }
2200 } while (!Worklist.empty());
2201 }
2202}
2203
2204/// CheckForCFGHazards - Check for critical edges, loop boundaries, irreducible
2205/// control flow, or other CFG structures where moving code across the edge
2206/// would result in it being executed more.
2207void
2208ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
2209 DenseMap<const BasicBlock *, BBState> &BBStates,
2210 BBState &MyStates) const {
2211 // If any top-down local-use or possible-dec has a succ which is earlier in
2212 // the sequence, forget it.
2213 for (BBState::ptr_const_iterator I = MyStates.top_down_ptr_begin(),
2214 E = MyStates.top_down_ptr_end(); I != E; ++I)
2215 switch (I->second.GetSeq()) {
2216 default: break;
2217 case S_Use: {
2218 const Value *Arg = I->first;
2219 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2220 bool SomeSuccHasSame = false;
2221 bool AllSuccsHaveSame = true;
Dan Gohmana7f7db22011-08-12 00:26:31 +00002222 PtrState &S = MyStates.getPtrTopDownState(Arg);
2223 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2224 PtrState &SuccS = BBStates[*SI].getPtrBottomUpState(Arg);
2225 switch (SuccS.GetSeq()) {
John McCall9fbd3182011-06-15 23:37:01 +00002226 case S_None:
Dan Gohmana7f7db22011-08-12 00:26:31 +00002227 case S_CanRelease: {
Dan Gohmane6d5e882011-08-19 00:26:36 +00002228 if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002229 S.ClearSequenceProgress();
2230 continue;
2231 }
John McCall9fbd3182011-06-15 23:37:01 +00002232 case S_Use:
2233 SomeSuccHasSame = true;
2234 break;
2235 case S_Stop:
2236 case S_Release:
2237 case S_MovableRelease:
Dan Gohmane6d5e882011-08-19 00:26:36 +00002238 if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002239 AllSuccsHaveSame = false;
John McCall9fbd3182011-06-15 23:37:01 +00002240 break;
2241 case S_Retain:
2242 llvm_unreachable("bottom-up pointer in retain state!");
2243 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002244 }
John McCall9fbd3182011-06-15 23:37:01 +00002245 // If the state at the other end of any of the successor edges
2246 // matches the current state, require all edges to match. This
2247 // guards against loops in the middle of a sequence.
2248 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002249 S.ClearSequenceProgress();
Dan Gohman2e68beb2011-12-12 18:13:53 +00002250 break;
John McCall9fbd3182011-06-15 23:37:01 +00002251 }
2252 case S_CanRelease: {
2253 const Value *Arg = I->first;
2254 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2255 bool SomeSuccHasSame = false;
2256 bool AllSuccsHaveSame = true;
Dan Gohmana7f7db22011-08-12 00:26:31 +00002257 PtrState &S = MyStates.getPtrTopDownState(Arg);
2258 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2259 PtrState &SuccS = BBStates[*SI].getPtrBottomUpState(Arg);
2260 switch (SuccS.GetSeq()) {
2261 case S_None: {
Dan Gohmane6d5e882011-08-19 00:26:36 +00002262 if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002263 S.ClearSequenceProgress();
2264 continue;
2265 }
John McCall9fbd3182011-06-15 23:37:01 +00002266 case S_CanRelease:
2267 SomeSuccHasSame = true;
2268 break;
2269 case S_Stop:
2270 case S_Release:
2271 case S_MovableRelease:
2272 case S_Use:
Dan Gohmane6d5e882011-08-19 00:26:36 +00002273 if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002274 AllSuccsHaveSame = false;
John McCall9fbd3182011-06-15 23:37:01 +00002275 break;
2276 case S_Retain:
2277 llvm_unreachable("bottom-up pointer in retain state!");
2278 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002279 }
John McCall9fbd3182011-06-15 23:37:01 +00002280 // If the state at the other end of any of the successor edges
2281 // matches the current state, require all edges to match. This
2282 // guards against loops in the middle of a sequence.
2283 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002284 S.ClearSequenceProgress();
Dan Gohman2e68beb2011-12-12 18:13:53 +00002285 break;
John McCall9fbd3182011-06-15 23:37:01 +00002286 }
2287 }
2288}
2289
2290bool
2291ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2292 DenseMap<const BasicBlock *, BBState> &BBStates,
2293 MapVector<Value *, RRInfo> &Retains) {
2294 bool NestingDetected = false;
2295 BBState &MyStates = BBStates[BB];
2296
2297 // Merge the states from each successor to compute the initial state
2298 // for the current block.
2299 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2300 succ_const_iterator SI(TI), SE(TI, false);
2301 if (SI == SE)
2302 MyStates.SetAsExit();
2303 else
2304 do {
2305 const BasicBlock *Succ = *SI++;
2306 if (Succ == BB)
2307 continue;
2308 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
Dan Gohmana7f7db22011-08-12 00:26:31 +00002309 // If we haven't seen this node yet, then we've found a CFG cycle.
2310 // Be optimistic here; it's CheckForCFGHazards' job detect trouble.
John McCall9fbd3182011-06-15 23:37:01 +00002311 if (I == BBStates.end())
2312 continue;
2313 MyStates.InitFromSucc(I->second);
2314 while (SI != SE) {
2315 Succ = *SI++;
2316 if (Succ != BB) {
2317 I = BBStates.find(Succ);
2318 if (I != BBStates.end())
2319 MyStates.MergeSucc(I->second);
2320 }
2321 }
2322 break;
2323 } while (SI != SE);
2324
2325 // Visit all the instructions, bottom-up.
2326 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2327 Instruction *Inst = llvm::prior(I);
2328 InstructionClass Class = GetInstructionClass(Inst);
2329 const Value *Arg = 0;
2330
2331 switch (Class) {
2332 case IC_Release: {
2333 Arg = GetObjCArg(Inst);
2334
2335 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2336
2337 // If we see two releases in a row on the same pointer. If so, make
2338 // a note, and we'll cicle back to revisit it after we've
2339 // hopefully eliminated the second release, which may allow us to
2340 // eliminate the first release too.
2341 // Theoretically we could implement removal of nested retain+release
2342 // pairs by making PtrState hold a stack of states, but this is
2343 // simple and avoids adding overhead for the non-nested case.
2344 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease)
2345 NestingDetected = true;
2346
John McCall9fbd3182011-06-15 23:37:01 +00002347 S.RRI.clear();
Dan Gohman28588ff2011-12-12 18:16:56 +00002348
2349 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2350 S.SetSeq(ReleaseMetadata ? S_MovableRelease : S_Release);
2351 S.RRI.ReleaseMetadata = ReleaseMetadata;
Dan Gohmane6d5e882011-08-19 00:26:36 +00002352 S.RRI.KnownSafe = S.IsKnownNested() || S.IsKnownIncremented();
John McCall9fbd3182011-06-15 23:37:01 +00002353 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2354 S.RRI.Calls.insert(Inst);
2355
2356 S.IncrementRefCount();
Dan Gohmane6d5e882011-08-19 00:26:36 +00002357 S.IncrementNestCount();
John McCall9fbd3182011-06-15 23:37:01 +00002358 break;
2359 }
2360 case IC_RetainBlock:
2361 case IC_Retain:
2362 case IC_RetainRV: {
2363 Arg = GetObjCArg(Inst);
2364
2365 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2366 S.DecrementRefCount();
Dan Gohmana7f7db22011-08-12 00:26:31 +00002367 S.SetAtLeastOneRefCount();
Dan Gohmane6d5e882011-08-19 00:26:36 +00002368 S.DecrementNestCount();
John McCall9fbd3182011-06-15 23:37:01 +00002369
Dan Gohmana974bea2011-10-17 22:53:25 +00002370 // An non-copy-on-escape objc_retainBlock call with just a use still
2371 // needs to be kept, because it may be copying a block from the stack
2372 // to the heap.
2373 if (Class == IC_RetainBlock &&
2374 !Inst->getMetadata(CopyOnEscapeMDKind) &&
2375 S.GetSeq() == S_Use)
Dan Gohman597fece2011-09-29 22:25:23 +00002376 S.SetSeq(S_CanRelease);
2377
John McCall9fbd3182011-06-15 23:37:01 +00002378 switch (S.GetSeq()) {
2379 case S_Stop:
2380 case S_Release:
2381 case S_MovableRelease:
2382 case S_Use:
2383 S.RRI.ReverseInsertPts.clear();
2384 // FALL THROUGH
2385 case S_CanRelease:
2386 // Don't do retain+release tracking for IC_RetainRV, because it's
2387 // better to let it remain as the first instruction after a call.
2388 if (Class != IC_RetainRV) {
2389 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
Dan Gohmana974bea2011-10-17 22:53:25 +00002390 if (S.RRI.IsRetainBlock)
2391 S.RRI.CopyOnEscape = !!Inst->getMetadata(CopyOnEscapeMDKind);
John McCall9fbd3182011-06-15 23:37:01 +00002392 Retains[Inst] = S.RRI;
2393 }
2394 S.ClearSequenceProgress();
2395 break;
2396 case S_None:
2397 break;
2398 case S_Retain:
2399 llvm_unreachable("bottom-up pointer in retain state!");
2400 }
Dan Gohmane6d5e882011-08-19 00:26:36 +00002401 continue;
John McCall9fbd3182011-06-15 23:37:01 +00002402 }
2403 case IC_AutoreleasepoolPop:
2404 // Conservatively, clear MyStates for all known pointers.
2405 MyStates.clearBottomUpPointers();
2406 continue;
2407 case IC_AutoreleasepoolPush:
2408 case IC_None:
2409 // These are irrelevant.
2410 continue;
2411 default:
2412 break;
2413 }
2414
2415 // Consider any other possible effects of this instruction on each
2416 // pointer being tracked.
2417 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
2418 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
2419 const Value *Ptr = MI->first;
2420 if (Ptr == Arg)
2421 continue; // Handled above.
2422 PtrState &S = MI->second;
2423 Sequence Seq = S.GetSeq();
2424
Dan Gohmane6d5e882011-08-19 00:26:36 +00002425 // Check for possible releases.
2426 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2427 S.DecrementRefCount();
Dan Gohmana7f7db22011-08-12 00:26:31 +00002428 switch (Seq) {
2429 case S_Use:
2430 S.SetSeq(S_CanRelease);
2431 continue;
2432 case S_CanRelease:
2433 case S_Release:
2434 case S_MovableRelease:
2435 case S_Stop:
2436 case S_None:
2437 break;
2438 case S_Retain:
2439 llvm_unreachable("bottom-up pointer in retain state!");
2440 }
Dan Gohmane6d5e882011-08-19 00:26:36 +00002441 }
John McCall9fbd3182011-06-15 23:37:01 +00002442
2443 // Check for possible direct uses.
2444 switch (Seq) {
2445 case S_Release:
2446 case S_MovableRelease:
2447 if (CanUse(Inst, Ptr, PA, Class)) {
Dan Gohman597fece2011-09-29 22:25:23 +00002448 assert(S.RRI.ReverseInsertPts.empty());
John McCall9fbd3182011-06-15 23:37:01 +00002449 S.RRI.ReverseInsertPts.insert(Inst);
2450 S.SetSeq(S_Use);
2451 } else if (Seq == S_Release &&
2452 (Class == IC_User || Class == IC_CallOrUser)) {
2453 // Non-movable releases depend on any possible objc pointer use.
2454 S.SetSeq(S_Stop);
Dan Gohman597fece2011-09-29 22:25:23 +00002455 assert(S.RRI.ReverseInsertPts.empty());
John McCall9fbd3182011-06-15 23:37:01 +00002456 S.RRI.ReverseInsertPts.insert(Inst);
2457 }
2458 break;
2459 case S_Stop:
2460 if (CanUse(Inst, Ptr, PA, Class))
2461 S.SetSeq(S_Use);
2462 break;
2463 case S_CanRelease:
2464 case S_Use:
2465 case S_None:
2466 break;
2467 case S_Retain:
2468 llvm_unreachable("bottom-up pointer in retain state!");
2469 }
2470 }
2471 }
2472
2473 return NestingDetected;
2474}
2475
2476bool
2477ObjCARCOpt::VisitTopDown(BasicBlock *BB,
2478 DenseMap<const BasicBlock *, BBState> &BBStates,
2479 DenseMap<Value *, RRInfo> &Releases) {
2480 bool NestingDetected = false;
2481 BBState &MyStates = BBStates[BB];
2482
2483 // Merge the states from each predecessor to compute the initial state
2484 // for the current block.
2485 const_pred_iterator PI(BB), PE(BB, false);
2486 if (PI == PE)
2487 MyStates.SetAsEntry();
2488 else
2489 do {
2490 const BasicBlock *Pred = *PI++;
2491 if (Pred == BB)
2492 continue;
2493 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
Dan Gohmana7f7db22011-08-12 00:26:31 +00002494 // If we haven't seen this node yet, then we've found a CFG cycle.
2495 // Be optimistic here; it's CheckForCFGHazards' job detect trouble.
Dan Gohman59a1c932011-12-12 19:42:25 +00002496 if (I == BBStates.end() || !I->second.isVisitedTopDown())
John McCall9fbd3182011-06-15 23:37:01 +00002497 continue;
2498 MyStates.InitFromPred(I->second);
2499 while (PI != PE) {
2500 Pred = *PI++;
2501 if (Pred != BB) {
2502 I = BBStates.find(Pred);
Dan Gohman59a1c932011-12-12 19:42:25 +00002503 if (I == BBStates.end() || I->second.isVisitedTopDown())
John McCall9fbd3182011-06-15 23:37:01 +00002504 MyStates.MergePred(I->second);
2505 }
2506 }
2507 break;
2508 } while (PI != PE);
2509
2510 // Visit all the instructions, top-down.
2511 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2512 Instruction *Inst = I;
2513 InstructionClass Class = GetInstructionClass(Inst);
2514 const Value *Arg = 0;
2515
2516 switch (Class) {
2517 case IC_RetainBlock:
2518 case IC_Retain:
2519 case IC_RetainRV: {
2520 Arg = GetObjCArg(Inst);
2521
2522 PtrState &S = MyStates.getPtrTopDownState(Arg);
2523
2524 // Don't do retain+release tracking for IC_RetainRV, because it's
2525 // better to let it remain as the first instruction after a call.
2526 if (Class != IC_RetainRV) {
2527 // If we see two retains in a row on the same pointer. If so, make
2528 // a note, and we'll cicle back to revisit it after we've
2529 // hopefully eliminated the second retain, which may allow us to
2530 // eliminate the first retain too.
2531 // Theoretically we could implement removal of nested retain+release
2532 // pairs by making PtrState hold a stack of states, but this is
2533 // simple and avoids adding overhead for the non-nested case.
2534 if (S.GetSeq() == S_Retain)
2535 NestingDetected = true;
2536
2537 S.SetSeq(S_Retain);
2538 S.RRI.clear();
2539 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
Dan Gohmana974bea2011-10-17 22:53:25 +00002540 if (S.RRI.IsRetainBlock)
2541 S.RRI.CopyOnEscape = !!Inst->getMetadata(CopyOnEscapeMDKind);
Dan Gohmane6d5e882011-08-19 00:26:36 +00002542 // Don't check S.IsKnownIncremented() here because it's not
2543 // sufficient.
2544 S.RRI.KnownSafe = S.IsKnownNested();
John McCall9fbd3182011-06-15 23:37:01 +00002545 S.RRI.Calls.insert(Inst);
2546 }
2547
Dan Gohmana7f7db22011-08-12 00:26:31 +00002548 S.SetAtLeastOneRefCount();
John McCall9fbd3182011-06-15 23:37:01 +00002549 S.IncrementRefCount();
Dan Gohmane6d5e882011-08-19 00:26:36 +00002550 S.IncrementNestCount();
2551 continue;
John McCall9fbd3182011-06-15 23:37:01 +00002552 }
2553 case IC_Release: {
2554 Arg = GetObjCArg(Inst);
2555
2556 PtrState &S = MyStates.getPtrTopDownState(Arg);
2557 S.DecrementRefCount();
Dan Gohmane6d5e882011-08-19 00:26:36 +00002558 S.DecrementNestCount();
John McCall9fbd3182011-06-15 23:37:01 +00002559
2560 switch (S.GetSeq()) {
2561 case S_Retain:
2562 case S_CanRelease:
2563 S.RRI.ReverseInsertPts.clear();
2564 // FALL THROUGH
2565 case S_Use:
2566 S.RRI.ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2567 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2568 Releases[Inst] = S.RRI;
2569 S.ClearSequenceProgress();
2570 break;
2571 case S_None:
2572 break;
2573 case S_Stop:
2574 case S_Release:
2575 case S_MovableRelease:
2576 llvm_unreachable("top-down pointer in release state!");
2577 }
2578 break;
2579 }
2580 case IC_AutoreleasepoolPop:
2581 // Conservatively, clear MyStates for all known pointers.
2582 MyStates.clearTopDownPointers();
2583 continue;
2584 case IC_AutoreleasepoolPush:
2585 case IC_None:
2586 // These are irrelevant.
2587 continue;
2588 default:
2589 break;
2590 }
2591
2592 // Consider any other possible effects of this instruction on each
2593 // pointer being tracked.
2594 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
2595 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
2596 const Value *Ptr = MI->first;
2597 if (Ptr == Arg)
2598 continue; // Handled above.
2599 PtrState &S = MI->second;
2600 Sequence Seq = S.GetSeq();
2601
Dan Gohmane6d5e882011-08-19 00:26:36 +00002602 // Check for possible releases.
2603 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2604 S.DecrementRefCount();
John McCall9fbd3182011-06-15 23:37:01 +00002605 switch (Seq) {
2606 case S_Retain:
2607 S.SetSeq(S_CanRelease);
Dan Gohman597fece2011-09-29 22:25:23 +00002608 assert(S.RRI.ReverseInsertPts.empty());
John McCall9fbd3182011-06-15 23:37:01 +00002609 S.RRI.ReverseInsertPts.insert(Inst);
2610
2611 // One call can't cause a transition from S_Retain to S_CanRelease
2612 // and S_CanRelease to S_Use. If we've made the first transition,
2613 // we're done.
2614 continue;
2615 case S_Use:
2616 case S_CanRelease:
2617 case S_None:
2618 break;
2619 case S_Stop:
2620 case S_Release:
2621 case S_MovableRelease:
2622 llvm_unreachable("top-down pointer in release state!");
2623 }
Dan Gohmane6d5e882011-08-19 00:26:36 +00002624 }
John McCall9fbd3182011-06-15 23:37:01 +00002625
2626 // Check for possible direct uses.
2627 switch (Seq) {
2628 case S_CanRelease:
2629 if (CanUse(Inst, Ptr, PA, Class))
2630 S.SetSeq(S_Use);
2631 break;
John McCall9fbd3182011-06-15 23:37:01 +00002632 case S_Retain:
Dan Gohmana974bea2011-10-17 22:53:25 +00002633 // A non-copy-on-scape objc_retainBlock call may be responsible for
2634 // copying the block data from the stack to the heap. Model this by
2635 // moving it straight from S_Retain to S_Use.
Dan Gohman597fece2011-09-29 22:25:23 +00002636 if (S.RRI.IsRetainBlock &&
Dan Gohmana974bea2011-10-17 22:53:25 +00002637 !S.RRI.CopyOnEscape &&
Dan Gohman597fece2011-09-29 22:25:23 +00002638 CanUse(Inst, Ptr, PA, Class)) {
2639 assert(S.RRI.ReverseInsertPts.empty());
2640 S.RRI.ReverseInsertPts.insert(Inst);
2641 S.SetSeq(S_Use);
2642 }
2643 break;
2644 case S_Use:
John McCall9fbd3182011-06-15 23:37:01 +00002645 case S_None:
2646 break;
2647 case S_Stop:
2648 case S_Release:
2649 case S_MovableRelease:
2650 llvm_unreachable("top-down pointer in release state!");
2651 }
2652 }
2653 }
2654
2655 CheckForCFGHazards(BB, BBStates, MyStates);
2656 return NestingDetected;
2657}
2658
Dan Gohman59a1c932011-12-12 19:42:25 +00002659static void
2660ComputePostOrders(Function &F,
2661 SmallVectorImpl<BasicBlock *> &PostOrder,
2662 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder) {
2663 /// Backedges - Backedges detected in the DFS. These edges will be
2664 /// ignored in the reverse-CFG DFS, so that loops with multiple exits will be
2665 /// traversed in the desired order.
2666 DenseSet<std::pair<BasicBlock *, BasicBlock *> > Backedges;
2667
2668 /// Visited - The visited set, for doing DFS walks.
2669 SmallPtrSet<BasicBlock *, 16> Visited;
2670
2671 // Do DFS, computing the PostOrder.
2672 SmallPtrSet<BasicBlock *, 16> OnStack;
2673 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
2674 BasicBlock *EntryBB = &F.getEntryBlock();
2675 SuccStack.push_back(std::make_pair(EntryBB, succ_begin(EntryBB)));
2676 Visited.insert(EntryBB);
2677 OnStack.insert(EntryBB);
2678 do {
2679 dfs_next_succ:
2680 succ_iterator End = succ_end(SuccStack.back().first);
2681 while (SuccStack.back().second != End) {
2682 BasicBlock *BB = *SuccStack.back().second++;
2683 if (Visited.insert(BB)) {
2684 SuccStack.push_back(std::make_pair(BB, succ_begin(BB)));
2685 OnStack.insert(BB);
2686 goto dfs_next_succ;
2687 }
2688 if (OnStack.count(BB))
2689 Backedges.insert(std::make_pair(SuccStack.back().first, BB));
2690 }
2691 OnStack.erase(SuccStack.back().first);
2692 PostOrder.push_back(SuccStack.pop_back_val().first);
2693 } while (!SuccStack.empty());
2694
2695 Visited.clear();
2696
2697 // Compute the exits, which are the starting points for reverse-CFG DFS.
2698 SmallVector<BasicBlock *, 4> Exits;
2699 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
2700 BasicBlock *BB = I;
2701 if (BB->getTerminator()->getNumSuccessors() == 0)
2702 Exits.push_back(BB);
2703 }
2704
2705 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
2706 SmallVector<std::pair<BasicBlock *, pred_iterator>, 16> PredStack;
2707 for (SmallVectorImpl<BasicBlock *>::iterator I = Exits.begin(), E = Exits.end();
2708 I != E; ++I) {
2709 BasicBlock *ExitBB = *I;
2710 PredStack.push_back(std::make_pair(ExitBB, pred_begin(ExitBB)));
2711 Visited.insert(ExitBB);
2712 while (!PredStack.empty()) {
2713 reverse_dfs_next_succ:
2714 pred_iterator End = pred_end(PredStack.back().first);
2715 while (PredStack.back().second != End) {
2716 BasicBlock *BB = *PredStack.back().second++;
2717 // Skip backedges detected in the forward-CFG DFS.
2718 if (Backedges.count(std::make_pair(BB, PredStack.back().first)))
2719 continue;
2720 if (Visited.insert(BB)) {
2721 PredStack.push_back(std::make_pair(BB, pred_begin(BB)));
2722 goto reverse_dfs_next_succ;
2723 }
2724 }
2725 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
2726 }
2727 }
2728}
2729
John McCall9fbd3182011-06-15 23:37:01 +00002730// Visit - Visit the function both top-down and bottom-up.
2731bool
2732ObjCARCOpt::Visit(Function &F,
2733 DenseMap<const BasicBlock *, BBState> &BBStates,
2734 MapVector<Value *, RRInfo> &Retains,
2735 DenseMap<Value *, RRInfo> &Releases) {
Dan Gohman59a1c932011-12-12 19:42:25 +00002736
2737 // Use reverse-postorder traversals, because we magically know that loops
2738 // will be well behaved, i.e. they won't repeatedly call retain on a single
2739 // pointer without doing a release. We can't use the ReversePostOrderTraversal
2740 // class here because we want the reverse-CFG postorder to consider each
2741 // function exit point, and we want to ignore selected cycle edges.
2742 SmallVector<BasicBlock *, 16> PostOrder;
2743 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
2744 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder);
2745
2746 // Use reverse-postorder on the reverse CFG for bottom-up.
John McCall9fbd3182011-06-15 23:37:01 +00002747 bool BottomUpNestingDetected = false;
Dan Gohmanb48ef3a2011-08-18 21:27:42 +00002748 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
Dan Gohman59a1c932011-12-12 19:42:25 +00002749 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
2750 I != E; ++I)
2751 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
John McCall9fbd3182011-06-15 23:37:01 +00002752
Dan Gohman59a1c932011-12-12 19:42:25 +00002753 // Use reverse-postorder for top-down.
John McCall9fbd3182011-06-15 23:37:01 +00002754 bool TopDownNestingDetected = false;
Dan Gohman59a1c932011-12-12 19:42:25 +00002755 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2756 PostOrder.rbegin(), E = PostOrder.rend();
2757 I != E; ++I)
2758 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
John McCall9fbd3182011-06-15 23:37:01 +00002759
2760 return TopDownNestingDetected && BottomUpNestingDetected;
2761}
2762
2763/// MoveCalls - Move the calls in RetainsToMove and ReleasesToMove.
2764void ObjCARCOpt::MoveCalls(Value *Arg,
2765 RRInfo &RetainsToMove,
2766 RRInfo &ReleasesToMove,
2767 MapVector<Value *, RRInfo> &Retains,
2768 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman44280692011-07-22 22:29:21 +00002769 SmallVectorImpl<Instruction *> &DeadInsts,
2770 Module *M) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002771 Type *ArgTy = Arg->getType();
Dan Gohman44280692011-07-22 22:29:21 +00002772 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
John McCall9fbd3182011-06-15 23:37:01 +00002773
2774 // Insert the new retain and release calls.
2775 for (SmallPtrSet<Instruction *, 2>::const_iterator
2776 PI = ReleasesToMove.ReverseInsertPts.begin(),
2777 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2778 Instruction *InsertPt = *PI;
2779 Value *MyArg = ArgTy == ParamTy ? Arg :
2780 new BitCastInst(Arg, ParamTy, "", InsertPt);
2781 CallInst *Call =
2782 CallInst::Create(RetainsToMove.IsRetainBlock ?
Dan Gohman44280692011-07-22 22:29:21 +00002783 getRetainBlockCallee(M) : getRetainCallee(M),
John McCall9fbd3182011-06-15 23:37:01 +00002784 MyArg, "", InsertPt);
2785 Call->setDoesNotThrow();
Dan Gohmana974bea2011-10-17 22:53:25 +00002786 if (RetainsToMove.CopyOnEscape)
2787 Call->setMetadata(CopyOnEscapeMDKind,
2788 MDNode::get(M->getContext(), ArrayRef<Value *>()));
John McCall9fbd3182011-06-15 23:37:01 +00002789 if (!RetainsToMove.IsRetainBlock)
2790 Call->setTailCall();
2791 }
2792 for (SmallPtrSet<Instruction *, 2>::const_iterator
2793 PI = RetainsToMove.ReverseInsertPts.begin(),
2794 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
Dan Gohman0860d0b2011-06-16 20:57:14 +00002795 Instruction *LastUse = *PI;
2796 Instruction *InsertPts[] = { 0, 0, 0 };
2797 if (InvokeInst *II = dyn_cast<InvokeInst>(LastUse)) {
2798 // We can't insert code immediately after an invoke instruction, so
2799 // insert code at the beginning of both successor blocks instead.
2800 // The invoke's return value isn't available in the unwind block,
2801 // but our releases will never depend on it, because they must be
2802 // paired with retains from before the invoke.
Bill Wendling89d44112011-08-25 01:08:34 +00002803 InsertPts[0] = II->getNormalDest()->getFirstInsertionPt();
2804 InsertPts[1] = II->getUnwindDest()->getFirstInsertionPt();
Dan Gohman0860d0b2011-06-16 20:57:14 +00002805 } else {
2806 // Insert code immediately after the last use.
2807 InsertPts[0] = llvm::next(BasicBlock::iterator(LastUse));
2808 }
2809
2810 for (Instruction **I = InsertPts; *I; ++I) {
2811 Instruction *InsertPt = *I;
2812 Value *MyArg = ArgTy == ParamTy ? Arg :
2813 new BitCastInst(Arg, ParamTy, "", InsertPt);
Dan Gohman44280692011-07-22 22:29:21 +00002814 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
2815 "", InsertPt);
Dan Gohman0860d0b2011-06-16 20:57:14 +00002816 // Attach a clang.imprecise_release metadata tag, if appropriate.
2817 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
2818 Call->setMetadata(ImpreciseReleaseMDKind, M);
2819 Call->setDoesNotThrow();
2820 if (ReleasesToMove.IsTailCallRelease)
2821 Call->setTailCall();
2822 }
John McCall9fbd3182011-06-15 23:37:01 +00002823 }
2824
2825 // Delete the original retain and release calls.
2826 for (SmallPtrSet<Instruction *, 2>::const_iterator
2827 AI = RetainsToMove.Calls.begin(),
2828 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
2829 Instruction *OrigRetain = *AI;
2830 Retains.blot(OrigRetain);
2831 DeadInsts.push_back(OrigRetain);
2832 }
2833 for (SmallPtrSet<Instruction *, 2>::const_iterator
2834 AI = ReleasesToMove.Calls.begin(),
2835 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
2836 Instruction *OrigRelease = *AI;
2837 Releases.erase(OrigRelease);
2838 DeadInsts.push_back(OrigRelease);
2839 }
2840}
2841
2842bool
2843ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
2844 &BBStates,
2845 MapVector<Value *, RRInfo> &Retains,
Dan Gohman44280692011-07-22 22:29:21 +00002846 DenseMap<Value *, RRInfo> &Releases,
2847 Module *M) {
John McCall9fbd3182011-06-15 23:37:01 +00002848 bool AnyPairsCompletelyEliminated = false;
2849 RRInfo RetainsToMove;
2850 RRInfo ReleasesToMove;
2851 SmallVector<Instruction *, 4> NewRetains;
2852 SmallVector<Instruction *, 4> NewReleases;
2853 SmallVector<Instruction *, 8> DeadInsts;
2854
2855 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
Dan Gohman597fece2011-09-29 22:25:23 +00002856 E = Retains.end(); I != E; ++I) {
2857 Value *V = I->first;
John McCall9fbd3182011-06-15 23:37:01 +00002858 if (!V) continue; // blotted
2859
2860 Instruction *Retain = cast<Instruction>(V);
2861 Value *Arg = GetObjCArg(Retain);
2862
Dan Gohman597fece2011-09-29 22:25:23 +00002863 // If the object being released is in static storage, we know it's
John McCall9fbd3182011-06-15 23:37:01 +00002864 // not being managed by ObjC reference counting, so we can delete pairs
2865 // regardless of what possible decrements or uses lie between them.
Dan Gohman597fece2011-09-29 22:25:23 +00002866 bool KnownSafe = isa<Constant>(Arg);
2867
Dan Gohmana974bea2011-10-17 22:53:25 +00002868 // Same for stack storage, unless this is a non-copy-on-escape
2869 // objc_retainBlock call, which is responsible for copying the block data
2870 // from the stack to the heap.
2871 if ((!I->second.IsRetainBlock || I->second.CopyOnEscape) &&
2872 isa<AllocaInst>(Arg))
Dan Gohman597fece2011-09-29 22:25:23 +00002873 KnownSafe = true;
John McCall9fbd3182011-06-15 23:37:01 +00002874
Dan Gohman1b31ea82011-08-22 17:29:11 +00002875 // A constant pointer can't be pointing to an object on the heap. It may
2876 // be reference-counted, but it won't be deleted.
2877 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
2878 if (const GlobalVariable *GV =
2879 dyn_cast<GlobalVariable>(
2880 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
2881 if (GV->isConstant())
2882 KnownSafe = true;
2883
John McCall9fbd3182011-06-15 23:37:01 +00002884 // If a pair happens in a region where it is known that the reference count
2885 // is already incremented, we can similarly ignore possible decrements.
Dan Gohmane6d5e882011-08-19 00:26:36 +00002886 bool KnownSafeTD = true, KnownSafeBU = true;
John McCall9fbd3182011-06-15 23:37:01 +00002887
2888 // Connect the dots between the top-down-collected RetainsToMove and
2889 // bottom-up-collected ReleasesToMove to form sets of related calls.
2890 // This is an iterative process so that we connect multiple releases
2891 // to multiple retains if needed.
2892 unsigned OldDelta = 0;
2893 unsigned NewDelta = 0;
2894 unsigned OldCount = 0;
2895 unsigned NewCount = 0;
2896 bool FirstRelease = true;
2897 bool FirstRetain = true;
2898 NewRetains.push_back(Retain);
2899 for (;;) {
2900 for (SmallVectorImpl<Instruction *>::const_iterator
2901 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
2902 Instruction *NewRetain = *NI;
2903 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
2904 assert(It != Retains.end());
2905 const RRInfo &NewRetainRRI = It->second;
Dan Gohmane6d5e882011-08-19 00:26:36 +00002906 KnownSafeTD &= NewRetainRRI.KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00002907 for (SmallPtrSet<Instruction *, 2>::const_iterator
2908 LI = NewRetainRRI.Calls.begin(),
2909 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
2910 Instruction *NewRetainRelease = *LI;
2911 DenseMap<Value *, RRInfo>::const_iterator Jt =
2912 Releases.find(NewRetainRelease);
2913 if (Jt == Releases.end())
2914 goto next_retain;
2915 const RRInfo &NewRetainReleaseRRI = Jt->second;
2916 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
2917 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
2918 OldDelta -=
2919 BBStates[NewRetainRelease->getParent()].GetAllPathCount();
2920
2921 // Merge the ReleaseMetadata and IsTailCallRelease values.
2922 if (FirstRelease) {
2923 ReleasesToMove.ReleaseMetadata =
2924 NewRetainReleaseRRI.ReleaseMetadata;
2925 ReleasesToMove.IsTailCallRelease =
2926 NewRetainReleaseRRI.IsTailCallRelease;
2927 FirstRelease = false;
2928 } else {
2929 if (ReleasesToMove.ReleaseMetadata !=
2930 NewRetainReleaseRRI.ReleaseMetadata)
2931 ReleasesToMove.ReleaseMetadata = 0;
2932 if (ReleasesToMove.IsTailCallRelease !=
2933 NewRetainReleaseRRI.IsTailCallRelease)
2934 ReleasesToMove.IsTailCallRelease = false;
2935 }
2936
2937 // Collect the optimal insertion points.
2938 if (!KnownSafe)
2939 for (SmallPtrSet<Instruction *, 2>::const_iterator
2940 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
2941 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
2942 RI != RE; ++RI) {
2943 Instruction *RIP = *RI;
2944 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
2945 NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
2946 }
2947 NewReleases.push_back(NewRetainRelease);
2948 }
2949 }
2950 }
2951 NewRetains.clear();
2952 if (NewReleases.empty()) break;
2953
2954 // Back the other way.
2955 for (SmallVectorImpl<Instruction *>::const_iterator
2956 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
2957 Instruction *NewRelease = *NI;
2958 DenseMap<Value *, RRInfo>::const_iterator It =
2959 Releases.find(NewRelease);
2960 assert(It != Releases.end());
2961 const RRInfo &NewReleaseRRI = It->second;
Dan Gohmane6d5e882011-08-19 00:26:36 +00002962 KnownSafeBU &= NewReleaseRRI.KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00002963 for (SmallPtrSet<Instruction *, 2>::const_iterator
2964 LI = NewReleaseRRI.Calls.begin(),
2965 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
2966 Instruction *NewReleaseRetain = *LI;
2967 MapVector<Value *, RRInfo>::const_iterator Jt =
2968 Retains.find(NewReleaseRetain);
2969 if (Jt == Retains.end())
2970 goto next_retain;
2971 const RRInfo &NewReleaseRetainRRI = Jt->second;
2972 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
2973 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
2974 unsigned PathCount =
2975 BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
2976 OldDelta += PathCount;
2977 OldCount += PathCount;
2978
2979 // Merge the IsRetainBlock values.
2980 if (FirstRetain) {
2981 RetainsToMove.IsRetainBlock = NewReleaseRetainRRI.IsRetainBlock;
Dan Gohmana974bea2011-10-17 22:53:25 +00002982 RetainsToMove.CopyOnEscape = NewReleaseRetainRRI.CopyOnEscape;
John McCall9fbd3182011-06-15 23:37:01 +00002983 FirstRetain = false;
2984 } else if (ReleasesToMove.IsRetainBlock !=
2985 NewReleaseRetainRRI.IsRetainBlock)
2986 // It's not possible to merge the sequences if one uses
2987 // objc_retain and the other uses objc_retainBlock.
2988 goto next_retain;
2989
Dan Gohmana974bea2011-10-17 22:53:25 +00002990 // Merge the CopyOnEscape values.
2991 RetainsToMove.CopyOnEscape &= NewReleaseRetainRRI.CopyOnEscape;
2992
John McCall9fbd3182011-06-15 23:37:01 +00002993 // Collect the optimal insertion points.
2994 if (!KnownSafe)
2995 for (SmallPtrSet<Instruction *, 2>::const_iterator
2996 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
2997 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
2998 RI != RE; ++RI) {
2999 Instruction *RIP = *RI;
3000 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
3001 PathCount = BBStates[RIP->getParent()].GetAllPathCount();
3002 NewDelta += PathCount;
3003 NewCount += PathCount;
3004 }
3005 }
3006 NewRetains.push_back(NewReleaseRetain);
3007 }
3008 }
3009 }
3010 NewReleases.clear();
3011 if (NewRetains.empty()) break;
3012 }
3013
Dan Gohmane6d5e882011-08-19 00:26:36 +00003014 // If the pointer is known incremented or nested, we can safely delete the
3015 // pair regardless of what's between them.
3016 if (KnownSafeTD || KnownSafeBU) {
John McCall9fbd3182011-06-15 23:37:01 +00003017 RetainsToMove.ReverseInsertPts.clear();
3018 ReleasesToMove.ReverseInsertPts.clear();
3019 NewCount = 0;
Dan Gohmana7f7db22011-08-12 00:26:31 +00003020 } else {
3021 // Determine whether the new insertion points we computed preserve the
3022 // balance of retain and release calls through the program.
3023 // TODO: If the fully aggressive solution isn't valid, try to find a
3024 // less aggressive solution which is.
3025 if (NewDelta != 0)
3026 goto next_retain;
John McCall9fbd3182011-06-15 23:37:01 +00003027 }
3028
3029 // Determine whether the original call points are balanced in the retain and
3030 // release calls through the program. If not, conservatively don't touch
3031 // them.
3032 // TODO: It's theoretically possible to do code motion in this case, as
3033 // long as the existing imbalances are maintained.
3034 if (OldDelta != 0)
3035 goto next_retain;
3036
John McCall9fbd3182011-06-15 23:37:01 +00003037 // Ok, everything checks out and we're all set. Let's move some code!
3038 Changed = true;
3039 AnyPairsCompletelyEliminated = NewCount == 0;
3040 NumRRs += OldCount - NewCount;
Dan Gohman44280692011-07-22 22:29:21 +00003041 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
3042 Retains, Releases, DeadInsts, M);
John McCall9fbd3182011-06-15 23:37:01 +00003043
3044 next_retain:
3045 NewReleases.clear();
3046 NewRetains.clear();
3047 RetainsToMove.clear();
3048 ReleasesToMove.clear();
3049 }
3050
3051 // Now that we're done moving everything, we can delete the newly dead
3052 // instructions, as we no longer need them as insert points.
3053 while (!DeadInsts.empty())
3054 EraseInstruction(DeadInsts.pop_back_val());
3055
3056 return AnyPairsCompletelyEliminated;
3057}
3058
3059/// OptimizeWeakCalls - Weak pointer optimizations.
3060void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
3061 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
3062 // itself because it uses AliasAnalysis and we need to do provenance
3063 // queries instead.
3064 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3065 Instruction *Inst = &*I++;
3066 InstructionClass Class = GetBasicInstructionClass(Inst);
3067 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
3068 continue;
3069
3070 // Delete objc_loadWeak calls with no users.
3071 if (Class == IC_LoadWeak && Inst->use_empty()) {
3072 Inst->eraseFromParent();
3073 continue;
3074 }
3075
3076 // TODO: For now, just look for an earlier available version of this value
3077 // within the same block. Theoretically, we could do memdep-style non-local
3078 // analysis too, but that would want caching. A better approach would be to
3079 // use the technique that EarlyCSE uses.
3080 inst_iterator Current = llvm::prior(I);
3081 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
3082 for (BasicBlock::iterator B = CurrentBB->begin(),
3083 J = Current.getInstructionIterator();
3084 J != B; --J) {
3085 Instruction *EarlierInst = &*llvm::prior(J);
3086 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
3087 switch (EarlierClass) {
3088 case IC_LoadWeak:
3089 case IC_LoadWeakRetained: {
3090 // If this is loading from the same pointer, replace this load's value
3091 // with that one.
3092 CallInst *Call = cast<CallInst>(Inst);
3093 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3094 Value *Arg = Call->getArgOperand(0);
3095 Value *EarlierArg = EarlierCall->getArgOperand(0);
3096 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3097 case AliasAnalysis::MustAlias:
3098 Changed = true;
3099 // If the load has a builtin retain, insert a plain retain for it.
3100 if (Class == IC_LoadWeakRetained) {
3101 CallInst *CI =
3102 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3103 "", Call);
3104 CI->setTailCall();
3105 }
3106 // Zap the fully redundant load.
3107 Call->replaceAllUsesWith(EarlierCall);
3108 Call->eraseFromParent();
3109 goto clobbered;
3110 case AliasAnalysis::MayAlias:
3111 case AliasAnalysis::PartialAlias:
3112 goto clobbered;
3113 case AliasAnalysis::NoAlias:
3114 break;
3115 }
3116 break;
3117 }
3118 case IC_StoreWeak:
3119 case IC_InitWeak: {
3120 // If this is storing to the same pointer and has the same size etc.
3121 // replace this load's value with the stored value.
3122 CallInst *Call = cast<CallInst>(Inst);
3123 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3124 Value *Arg = Call->getArgOperand(0);
3125 Value *EarlierArg = EarlierCall->getArgOperand(0);
3126 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3127 case AliasAnalysis::MustAlias:
3128 Changed = true;
3129 // If the load has a builtin retain, insert a plain retain for it.
3130 if (Class == IC_LoadWeakRetained) {
3131 CallInst *CI =
3132 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3133 "", Call);
3134 CI->setTailCall();
3135 }
3136 // Zap the fully redundant load.
3137 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
3138 Call->eraseFromParent();
3139 goto clobbered;
3140 case AliasAnalysis::MayAlias:
3141 case AliasAnalysis::PartialAlias:
3142 goto clobbered;
3143 case AliasAnalysis::NoAlias:
3144 break;
3145 }
3146 break;
3147 }
3148 case IC_MoveWeak:
3149 case IC_CopyWeak:
3150 // TOOD: Grab the copied value.
3151 goto clobbered;
3152 case IC_AutoreleasepoolPush:
3153 case IC_None:
3154 case IC_User:
3155 // Weak pointers are only modified through the weak entry points
3156 // (and arbitrary calls, which could call the weak entry points).
3157 break;
3158 default:
3159 // Anything else could modify the weak pointer.
3160 goto clobbered;
3161 }
3162 }
3163 clobbered:;
3164 }
3165
3166 // Then, for each destroyWeak with an alloca operand, check to see if
3167 // the alloca and all its users can be zapped.
3168 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3169 Instruction *Inst = &*I++;
3170 InstructionClass Class = GetBasicInstructionClass(Inst);
3171 if (Class != IC_DestroyWeak)
3172 continue;
3173
3174 CallInst *Call = cast<CallInst>(Inst);
3175 Value *Arg = Call->getArgOperand(0);
3176 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
3177 for (Value::use_iterator UI = Alloca->use_begin(),
3178 UE = Alloca->use_end(); UI != UE; ++UI) {
3179 Instruction *UserInst = cast<Instruction>(*UI);
3180 switch (GetBasicInstructionClass(UserInst)) {
3181 case IC_InitWeak:
3182 case IC_StoreWeak:
3183 case IC_DestroyWeak:
3184 continue;
3185 default:
3186 goto done;
3187 }
3188 }
3189 Changed = true;
3190 for (Value::use_iterator UI = Alloca->use_begin(),
3191 UE = Alloca->use_end(); UI != UE; ) {
3192 CallInst *UserInst = cast<CallInst>(*UI++);
3193 if (!UserInst->use_empty())
Dan Gohman8a9eebe2011-12-12 18:19:12 +00003194 UserInst->replaceAllUsesWith(UserInst->getArgOperand(0));
John McCall9fbd3182011-06-15 23:37:01 +00003195 UserInst->eraseFromParent();
3196 }
3197 Alloca->eraseFromParent();
3198 done:;
3199 }
3200 }
3201}
3202
3203/// OptimizeSequences - Identify program paths which execute sequences of
3204/// retains and releases which can be eliminated.
3205bool ObjCARCOpt::OptimizeSequences(Function &F) {
3206 /// Releases, Retains - These are used to store the results of the main flow
3207 /// analysis. These use Value* as the key instead of Instruction* so that the
3208 /// map stays valid when we get around to rewriting code and calls get
3209 /// replaced by arguments.
3210 DenseMap<Value *, RRInfo> Releases;
3211 MapVector<Value *, RRInfo> Retains;
3212
3213 /// BBStates, This is used during the traversal of the function to track the
3214 /// states for each identified object at each block.
3215 DenseMap<const BasicBlock *, BBState> BBStates;
3216
3217 // Analyze the CFG of the function, and all instructions.
3218 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
3219
3220 // Transform.
Dan Gohman44280692011-07-22 22:29:21 +00003221 return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) &&
3222 NestingDetected;
John McCall9fbd3182011-06-15 23:37:01 +00003223}
3224
3225/// OptimizeReturns - Look for this pattern:
3226///
3227/// %call = call i8* @something(...)
3228/// %2 = call i8* @objc_retain(i8* %call)
3229/// %3 = call i8* @objc_autorelease(i8* %2)
3230/// ret i8* %3
3231///
3232/// And delete the retain and autorelease.
3233///
3234/// Otherwise if it's just this:
3235///
3236/// %3 = call i8* @objc_autorelease(i8* %2)
3237/// ret i8* %3
3238///
3239/// convert the autorelease to autoreleaseRV.
3240void ObjCARCOpt::OptimizeReturns(Function &F) {
3241 if (!F.getReturnType()->isPointerTy())
3242 return;
3243
3244 SmallPtrSet<Instruction *, 4> DependingInstructions;
3245 SmallPtrSet<const BasicBlock *, 4> Visited;
3246 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3247 BasicBlock *BB = FI;
3248 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
3249 if (!Ret) continue;
3250
3251 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
3252 FindDependencies(NeedsPositiveRetainCount, Arg,
3253 BB, Ret, DependingInstructions, Visited, PA);
3254 if (DependingInstructions.size() != 1)
3255 goto next_block;
3256
3257 {
3258 CallInst *Autorelease =
3259 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3260 if (!Autorelease)
3261 goto next_block;
3262 InstructionClass AutoreleaseClass =
3263 GetBasicInstructionClass(Autorelease);
3264 if (!IsAutorelease(AutoreleaseClass))
3265 goto next_block;
3266 if (GetObjCArg(Autorelease) != Arg)
3267 goto next_block;
3268
3269 DependingInstructions.clear();
3270 Visited.clear();
3271
3272 // Check that there is nothing that can affect the reference
3273 // count between the autorelease and the retain.
3274 FindDependencies(CanChangeRetainCount, Arg,
3275 BB, Autorelease, DependingInstructions, Visited, PA);
3276 if (DependingInstructions.size() != 1)
3277 goto next_block;
3278
3279 {
3280 CallInst *Retain =
3281 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3282
3283 // Check that we found a retain with the same argument.
3284 if (!Retain ||
3285 !IsRetain(GetBasicInstructionClass(Retain)) ||
3286 GetObjCArg(Retain) != Arg)
3287 goto next_block;
3288
3289 DependingInstructions.clear();
3290 Visited.clear();
3291
3292 // Convert the autorelease to an autoreleaseRV, since it's
3293 // returning the value.
3294 if (AutoreleaseClass == IC_Autorelease) {
3295 Autorelease->setCalledFunction(getAutoreleaseRVCallee(F.getParent()));
3296 AutoreleaseClass = IC_AutoreleaseRV;
3297 }
3298
3299 // Check that there is nothing that can affect the reference
3300 // count between the retain and the call.
Dan Gohman27e06662011-09-29 22:27:34 +00003301 // Note that Retain need not be in BB.
3302 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
John McCall9fbd3182011-06-15 23:37:01 +00003303 DependingInstructions, Visited, PA);
3304 if (DependingInstructions.size() != 1)
3305 goto next_block;
3306
3307 {
3308 CallInst *Call =
3309 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3310
3311 // Check that the pointer is the return value of the call.
3312 if (!Call || Arg != Call)
3313 goto next_block;
3314
3315 // Check that the call is a regular call.
3316 InstructionClass Class = GetBasicInstructionClass(Call);
3317 if (Class != IC_CallOrUser && Class != IC_Call)
3318 goto next_block;
3319
3320 // If so, we can zap the retain and autorelease.
3321 Changed = true;
3322 ++NumRets;
3323 EraseInstruction(Retain);
3324 EraseInstruction(Autorelease);
3325 }
3326 }
3327 }
3328
3329 next_block:
3330 DependingInstructions.clear();
3331 Visited.clear();
3332 }
3333}
3334
3335bool ObjCARCOpt::doInitialization(Module &M) {
3336 if (!EnableARCOpts)
3337 return false;
3338
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003339 Run = ModuleHasARC(M);
3340 if (!Run)
3341 return false;
3342
John McCall9fbd3182011-06-15 23:37:01 +00003343 // Identify the imprecise release metadata kind.
3344 ImpreciseReleaseMDKind =
3345 M.getContext().getMDKindID("clang.imprecise_release");
Dan Gohmana974bea2011-10-17 22:53:25 +00003346 CopyOnEscapeMDKind =
3347 M.getContext().getMDKindID("clang.arc.copy_on_escape");
John McCall9fbd3182011-06-15 23:37:01 +00003348
John McCall9fbd3182011-06-15 23:37:01 +00003349 // Intuitively, objc_retain and others are nocapture, however in practice
3350 // they are not, because they return their argument value. And objc_release
3351 // calls finalizers.
3352
3353 // These are initialized lazily.
3354 RetainRVCallee = 0;
3355 AutoreleaseRVCallee = 0;
3356 ReleaseCallee = 0;
3357 RetainCallee = 0;
Dan Gohman44280692011-07-22 22:29:21 +00003358 RetainBlockCallee = 0;
John McCall9fbd3182011-06-15 23:37:01 +00003359 AutoreleaseCallee = 0;
3360
3361 return false;
3362}
3363
3364bool ObjCARCOpt::runOnFunction(Function &F) {
3365 if (!EnableARCOpts)
3366 return false;
3367
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003368 // If nothing in the Module uses ARC, don't do anything.
3369 if (!Run)
3370 return false;
3371
John McCall9fbd3182011-06-15 23:37:01 +00003372 Changed = false;
3373
3374 PA.setAA(&getAnalysis<AliasAnalysis>());
3375
3376 // This pass performs several distinct transformations. As a compile-time aid
3377 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3378 // library functions aren't declared.
3379
3380 // Preliminary optimizations. This also computs UsedInThisFunction.
3381 OptimizeIndividualCalls(F);
3382
3383 // Optimizations for weak pointers.
3384 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3385 (1 << IC_LoadWeakRetained) |
3386 (1 << IC_StoreWeak) |
3387 (1 << IC_InitWeak) |
3388 (1 << IC_CopyWeak) |
3389 (1 << IC_MoveWeak) |
3390 (1 << IC_DestroyWeak)))
3391 OptimizeWeakCalls(F);
3392
3393 // Optimizations for retain+release pairs.
3394 if (UsedInThisFunction & ((1 << IC_Retain) |
3395 (1 << IC_RetainRV) |
3396 (1 << IC_RetainBlock)))
3397 if (UsedInThisFunction & (1 << IC_Release))
3398 // Run OptimizeSequences until it either stops making changes or
3399 // no retain+release pair nesting is detected.
3400 while (OptimizeSequences(F)) {}
3401
3402 // Optimizations if objc_autorelease is used.
3403 if (UsedInThisFunction &
3404 ((1 << IC_Autorelease) | (1 << IC_AutoreleaseRV)))
3405 OptimizeReturns(F);
3406
3407 return Changed;
3408}
3409
3410void ObjCARCOpt::releaseMemory() {
3411 PA.clear();
3412}
3413
3414//===----------------------------------------------------------------------===//
3415// ARC contraction.
3416//===----------------------------------------------------------------------===//
3417
3418// TODO: ObjCARCContract could insert PHI nodes when uses aren't
3419// dominated by single calls.
3420
3421#include "llvm/Operator.h"
3422#include "llvm/InlineAsm.h"
3423#include "llvm/Analysis/Dominators.h"
3424
3425STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed");
3426
3427namespace {
3428 /// ObjCARCContract - Late ARC optimizations. These change the IR in a way
3429 /// that makes it difficult to be analyzed by ObjCARCOpt, so it's run late.
3430 class ObjCARCContract : public FunctionPass {
3431 bool Changed;
3432 AliasAnalysis *AA;
3433 DominatorTree *DT;
3434 ProvenanceAnalysis PA;
3435
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003436 /// Run - A flag indicating whether this optimization pass should run.
3437 bool Run;
3438
John McCall9fbd3182011-06-15 23:37:01 +00003439 /// StoreStrongCallee, etc. - Declarations for ObjC runtime
3440 /// functions, for use in creating calls to them. These are initialized
3441 /// lazily to avoid cluttering up the Module with unused declarations.
3442 Constant *StoreStrongCallee,
3443 *RetainAutoreleaseCallee, *RetainAutoreleaseRVCallee;
3444
3445 /// RetainRVMarker - The inline asm string to insert between calls and
3446 /// RetainRV calls to make the optimization work on targets which need it.
3447 const MDString *RetainRVMarker;
3448
3449 Constant *getStoreStrongCallee(Module *M);
3450 Constant *getRetainAutoreleaseCallee(Module *M);
3451 Constant *getRetainAutoreleaseRVCallee(Module *M);
3452
3453 bool ContractAutorelease(Function &F, Instruction *Autorelease,
3454 InstructionClass Class,
3455 SmallPtrSet<Instruction *, 4>
3456 &DependingInstructions,
3457 SmallPtrSet<const BasicBlock *, 4>
3458 &Visited);
3459
3460 void ContractRelease(Instruction *Release,
3461 inst_iterator &Iter);
3462
3463 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
3464 virtual bool doInitialization(Module &M);
3465 virtual bool runOnFunction(Function &F);
3466
3467 public:
3468 static char ID;
3469 ObjCARCContract() : FunctionPass(ID) {
3470 initializeObjCARCContractPass(*PassRegistry::getPassRegistry());
3471 }
3472 };
3473}
3474
3475char ObjCARCContract::ID = 0;
3476INITIALIZE_PASS_BEGIN(ObjCARCContract,
3477 "objc-arc-contract", "ObjC ARC contraction", false, false)
3478INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3479INITIALIZE_PASS_DEPENDENCY(DominatorTree)
3480INITIALIZE_PASS_END(ObjCARCContract,
3481 "objc-arc-contract", "ObjC ARC contraction", false, false)
3482
3483Pass *llvm::createObjCARCContractPass() {
3484 return new ObjCARCContract();
3485}
3486
3487void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const {
3488 AU.addRequired<AliasAnalysis>();
3489 AU.addRequired<DominatorTree>();
3490 AU.setPreservesCFG();
3491}
3492
3493Constant *ObjCARCContract::getStoreStrongCallee(Module *M) {
3494 if (!StoreStrongCallee) {
3495 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00003496 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3497 Type *I8XX = PointerType::getUnqual(I8X);
3498 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00003499 Params.push_back(I8XX);
3500 Params.push_back(I8X);
3501
3502 AttrListPtr Attributes;
3503 Attributes.addAttr(~0u, Attribute::NoUnwind);
3504 Attributes.addAttr(1, Attribute::NoCapture);
3505
3506 StoreStrongCallee =
3507 M->getOrInsertFunction(
3508 "objc_storeStrong",
3509 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
3510 Attributes);
3511 }
3512 return StoreStrongCallee;
3513}
3514
3515Constant *ObjCARCContract::getRetainAutoreleaseCallee(Module *M) {
3516 if (!RetainAutoreleaseCallee) {
3517 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00003518 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3519 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00003520 Params.push_back(I8X);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003521 FunctionType *FTy =
John McCall9fbd3182011-06-15 23:37:01 +00003522 FunctionType::get(I8X, Params, /*isVarArg=*/false);
3523 AttrListPtr Attributes;
3524 Attributes.addAttr(~0u, Attribute::NoUnwind);
3525 RetainAutoreleaseCallee =
3526 M->getOrInsertFunction("objc_retainAutorelease", FTy, Attributes);
3527 }
3528 return RetainAutoreleaseCallee;
3529}
3530
3531Constant *ObjCARCContract::getRetainAutoreleaseRVCallee(Module *M) {
3532 if (!RetainAutoreleaseRVCallee) {
3533 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00003534 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3535 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00003536 Params.push_back(I8X);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003537 FunctionType *FTy =
John McCall9fbd3182011-06-15 23:37:01 +00003538 FunctionType::get(I8X, Params, /*isVarArg=*/false);
3539 AttrListPtr Attributes;
3540 Attributes.addAttr(~0u, Attribute::NoUnwind);
3541 RetainAutoreleaseRVCallee =
3542 M->getOrInsertFunction("objc_retainAutoreleaseReturnValue", FTy,
3543 Attributes);
3544 }
3545 return RetainAutoreleaseRVCallee;
3546}
3547
3548/// ContractAutorelease - Merge an autorelease with a retain into a fused
3549/// call.
3550bool
3551ObjCARCContract::ContractAutorelease(Function &F, Instruction *Autorelease,
3552 InstructionClass Class,
3553 SmallPtrSet<Instruction *, 4>
3554 &DependingInstructions,
3555 SmallPtrSet<const BasicBlock *, 4>
3556 &Visited) {
3557 const Value *Arg = GetObjCArg(Autorelease);
3558
3559 // Check that there are no instructions between the retain and the autorelease
3560 // (such as an autorelease_pop) which may change the count.
3561 CallInst *Retain = 0;
3562 if (Class == IC_AutoreleaseRV)
3563 FindDependencies(RetainAutoreleaseRVDep, Arg,
3564 Autorelease->getParent(), Autorelease,
3565 DependingInstructions, Visited, PA);
3566 else
3567 FindDependencies(RetainAutoreleaseDep, Arg,
3568 Autorelease->getParent(), Autorelease,
3569 DependingInstructions, Visited, PA);
3570
3571 Visited.clear();
3572 if (DependingInstructions.size() != 1) {
3573 DependingInstructions.clear();
3574 return false;
3575 }
3576
3577 Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3578 DependingInstructions.clear();
3579
3580 if (!Retain ||
3581 GetBasicInstructionClass(Retain) != IC_Retain ||
3582 GetObjCArg(Retain) != Arg)
3583 return false;
3584
3585 Changed = true;
3586 ++NumPeeps;
3587
3588 if (Class == IC_AutoreleaseRV)
3589 Retain->setCalledFunction(getRetainAutoreleaseRVCallee(F.getParent()));
3590 else
3591 Retain->setCalledFunction(getRetainAutoreleaseCallee(F.getParent()));
3592
3593 EraseInstruction(Autorelease);
3594 return true;
3595}
3596
3597/// ContractRelease - Attempt to merge an objc_release with a store, load, and
3598/// objc_retain to form an objc_storeStrong. This can be a little tricky because
3599/// the instructions don't always appear in order, and there may be unrelated
3600/// intervening instructions.
3601void ObjCARCContract::ContractRelease(Instruction *Release,
3602 inst_iterator &Iter) {
3603 LoadInst *Load = dyn_cast<LoadInst>(GetObjCArg(Release));
Eli Friedman2bc3d522011-09-12 20:23:13 +00003604 if (!Load || !Load->isSimple()) return;
John McCall9fbd3182011-06-15 23:37:01 +00003605
3606 // For now, require everything to be in one basic block.
3607 BasicBlock *BB = Release->getParent();
3608 if (Load->getParent() != BB) return;
3609
3610 // Walk down to find the store.
3611 BasicBlock::iterator I = Load, End = BB->end();
3612 ++I;
3613 AliasAnalysis::Location Loc = AA->getLocation(Load);
3614 while (I != End &&
3615 (&*I == Release ||
3616 IsRetain(GetBasicInstructionClass(I)) ||
3617 !(AA->getModRefInfo(I, Loc) & AliasAnalysis::Mod)))
3618 ++I;
3619 StoreInst *Store = dyn_cast<StoreInst>(I);
Eli Friedman2bc3d522011-09-12 20:23:13 +00003620 if (!Store || !Store->isSimple()) return;
John McCall9fbd3182011-06-15 23:37:01 +00003621 if (Store->getPointerOperand() != Loc.Ptr) return;
3622
3623 Value *New = StripPointerCastsAndObjCCalls(Store->getValueOperand());
3624
3625 // Walk up to find the retain.
3626 I = Store;
3627 BasicBlock::iterator Begin = BB->begin();
3628 while (I != Begin && GetBasicInstructionClass(I) != IC_Retain)
3629 --I;
3630 Instruction *Retain = I;
3631 if (GetBasicInstructionClass(Retain) != IC_Retain) return;
3632 if (GetObjCArg(Retain) != New) return;
3633
3634 Changed = true;
3635 ++NumStoreStrongs;
3636
3637 LLVMContext &C = Release->getContext();
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003638 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3639 Type *I8XX = PointerType::getUnqual(I8X);
John McCall9fbd3182011-06-15 23:37:01 +00003640
3641 Value *Args[] = { Load->getPointerOperand(), New };
3642 if (Args[0]->getType() != I8XX)
3643 Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
3644 if (Args[1]->getType() != I8X)
3645 Args[1] = new BitCastInst(Args[1], I8X, "", Store);
3646 CallInst *StoreStrong =
3647 CallInst::Create(getStoreStrongCallee(BB->getParent()->getParent()),
Jay Foada3efbb12011-07-15 08:37:34 +00003648 Args, "", Store);
John McCall9fbd3182011-06-15 23:37:01 +00003649 StoreStrong->setDoesNotThrow();
3650 StoreStrong->setDebugLoc(Store->getDebugLoc());
3651
3652 if (&*Iter == Store) ++Iter;
3653 Store->eraseFromParent();
3654 Release->eraseFromParent();
3655 EraseInstruction(Retain);
3656 if (Load->use_empty())
3657 Load->eraseFromParent();
3658}
3659
3660bool ObjCARCContract::doInitialization(Module &M) {
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003661 Run = ModuleHasARC(M);
3662 if (!Run)
3663 return false;
3664
John McCall9fbd3182011-06-15 23:37:01 +00003665 // These are initialized lazily.
3666 StoreStrongCallee = 0;
3667 RetainAutoreleaseCallee = 0;
3668 RetainAutoreleaseRVCallee = 0;
3669
3670 // Initialize RetainRVMarker.
3671 RetainRVMarker = 0;
3672 if (NamedMDNode *NMD =
3673 M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker"))
3674 if (NMD->getNumOperands() == 1) {
3675 const MDNode *N = NMD->getOperand(0);
3676 if (N->getNumOperands() == 1)
3677 if (const MDString *S = dyn_cast<MDString>(N->getOperand(0)))
3678 RetainRVMarker = S;
3679 }
3680
3681 return false;
3682}
3683
3684bool ObjCARCContract::runOnFunction(Function &F) {
3685 if (!EnableARCOpts)
3686 return false;
3687
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003688 // If nothing in the Module uses ARC, don't do anything.
3689 if (!Run)
3690 return false;
3691
John McCall9fbd3182011-06-15 23:37:01 +00003692 Changed = false;
3693 AA = &getAnalysis<AliasAnalysis>();
3694 DT = &getAnalysis<DominatorTree>();
3695
3696 PA.setAA(&getAnalysis<AliasAnalysis>());
3697
3698 // For ObjC library calls which return their argument, replace uses of the
3699 // argument with uses of the call return value, if it dominates the use. This
3700 // reduces register pressure.
3701 SmallPtrSet<Instruction *, 4> DependingInstructions;
3702 SmallPtrSet<const BasicBlock *, 4> Visited;
3703 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3704 Instruction *Inst = &*I++;
3705
3706 // Only these library routines return their argument. In particular,
3707 // objc_retainBlock does not necessarily return its argument.
3708 InstructionClass Class = GetBasicInstructionClass(Inst);
3709 switch (Class) {
3710 case IC_Retain:
3711 case IC_FusedRetainAutorelease:
3712 case IC_FusedRetainAutoreleaseRV:
3713 break;
3714 case IC_Autorelease:
3715 case IC_AutoreleaseRV:
3716 if (ContractAutorelease(F, Inst, Class, DependingInstructions, Visited))
3717 continue;
3718 break;
3719 case IC_RetainRV: {
3720 // If we're compiling for a target which needs a special inline-asm
3721 // marker to do the retainAutoreleasedReturnValue optimization,
3722 // insert it now.
3723 if (!RetainRVMarker)
3724 break;
3725 BasicBlock::iterator BBI = Inst;
3726 --BBI;
3727 while (isNoopInstruction(BBI)) --BBI;
3728 if (&*BBI == GetObjCArg(Inst)) {
3729 InlineAsm *IA =
3730 InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()),
3731 /*isVarArg=*/false),
3732 RetainRVMarker->getString(),
3733 /*Constraints=*/"", /*hasSideEffects=*/true);
3734 CallInst::Create(IA, "", Inst);
3735 }
3736 break;
3737 }
3738 case IC_InitWeak: {
3739 // objc_initWeak(p, null) => *p = null
3740 CallInst *CI = cast<CallInst>(Inst);
3741 if (isNullOrUndef(CI->getArgOperand(1))) {
3742 Value *Null =
3743 ConstantPointerNull::get(cast<PointerType>(CI->getType()));
3744 Changed = true;
3745 new StoreInst(Null, CI->getArgOperand(0), CI);
3746 CI->replaceAllUsesWith(Null);
3747 CI->eraseFromParent();
3748 }
3749 continue;
3750 }
3751 case IC_Release:
3752 ContractRelease(Inst, I);
3753 continue;
3754 default:
3755 continue;
3756 }
3757
3758 // Don't use GetObjCArg because we don't want to look through bitcasts
3759 // and such; to do the replacement, the argument must have type i8*.
3760 const Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
3761 for (;;) {
3762 // If we're compiling bugpointed code, don't get in trouble.
3763 if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
3764 break;
3765 // Look through the uses of the pointer.
3766 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
3767 UI != UE; ) {
3768 Use &U = UI.getUse();
3769 unsigned OperandNo = UI.getOperandNo();
3770 ++UI; // Increment UI now, because we may unlink its element.
3771 if (Instruction *UserInst = dyn_cast<Instruction>(U.getUser()))
3772 if (Inst != UserInst && DT->dominates(Inst, UserInst)) {
3773 Changed = true;
3774 Instruction *Replacement = Inst;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003775 Type *UseTy = U.get()->getType();
John McCall9fbd3182011-06-15 23:37:01 +00003776 if (PHINode *PHI = dyn_cast<PHINode>(UserInst)) {
3777 // For PHI nodes, insert the bitcast in the predecessor block.
3778 unsigned ValNo =
3779 PHINode::getIncomingValueNumForOperand(OperandNo);
3780 BasicBlock *BB =
3781 PHI->getIncomingBlock(ValNo);
3782 if (Replacement->getType() != UseTy)
3783 Replacement = new BitCastInst(Replacement, UseTy, "",
3784 &BB->back());
3785 for (unsigned i = 0, e = PHI->getNumIncomingValues();
3786 i != e; ++i)
3787 if (PHI->getIncomingBlock(i) == BB) {
3788 // Keep the UI iterator valid.
3789 if (&PHI->getOperandUse(
3790 PHINode::getOperandNumForIncomingValue(i)) ==
3791 &UI.getUse())
3792 ++UI;
3793 PHI->setIncomingValue(i, Replacement);
3794 }
3795 } else {
3796 if (Replacement->getType() != UseTy)
3797 Replacement = new BitCastInst(Replacement, UseTy, "", UserInst);
3798 U.set(Replacement);
3799 }
3800 }
3801 }
3802
3803 // If Arg is a no-op casted pointer, strip one level of casts and
3804 // iterate.
3805 if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
3806 Arg = BI->getOperand(0);
3807 else if (isa<GEPOperator>(Arg) &&
3808 cast<GEPOperator>(Arg)->hasAllZeroIndices())
3809 Arg = cast<GEPOperator>(Arg)->getPointerOperand();
3810 else if (isa<GlobalAlias>(Arg) &&
3811 !cast<GlobalAlias>(Arg)->mayBeOverridden())
3812 Arg = cast<GlobalAlias>(Arg)->getAliasee();
3813 else
3814 break;
3815 }
3816 }
3817
3818 return Changed;
3819}