1 //===- ObjCARCOpts.cpp - ObjC ARC Optimization ----------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 /// This file defines ObjC ARC optimizations. ARC stands for Automatic
11 /// Reference Counting and is a system for managing reference counts for objects
14 /// The optimizations performed include elimination of redundant, partially
15 /// redundant, and inconsequential reference count operations, elimination of
16 /// redundant weak pointer operations, and numerous minor simplifications.
18 /// WARNING: This file knows about certain library functions. It recognizes them
19 /// by name, and hardwires knowledge of their semantics.
21 /// WARNING: This file knows about how certain Objective-C library functions are
22 /// used. Naive LLVM IR transformations which would otherwise be
23 /// behavior-preserving may break these assumptions.
25 //===----------------------------------------------------------------------===//
28 #include "ARCRuntimeEntryPoints.h"
29 #include "DependencyAnalysis.h"
30 #include "ObjCARCAliasAnalysis.h"
31 #include "ProvenanceAnalysis.h"
32 #include "BlotMapVector.h"
34 #include "llvm/ADT/DenseMap.h"
35 #include "llvm/ADT/DenseSet.h"
36 #include "llvm/ADT/STLExtras.h"
37 #include "llvm/ADT/SmallPtrSet.h"
38 #include "llvm/ADT/Statistic.h"
39 #include "llvm/IR/CFG.h"
40 #include "llvm/IR/IRBuilder.h"
41 #include "llvm/IR/LLVMContext.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/Support/raw_ostream.h"
46 using namespace llvm::objcarc;
48 #define DEBUG_TYPE "objc-arc-opts"
50 /// \defgroup ARCUtilities Utility declarations/definitions specific to ARC.
53 /// \brief This is similar to GetRCIdentityRoot but it stops as soon
54 /// as it finds a value with multiple uses.
55 static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
56 if (Arg->hasOneUse()) {
57 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
58 return FindSingleUseIdentifiedObject(BC->getOperand(0));
59 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
60 if (GEP->hasAllZeroIndices())
61 return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
62 if (IsForwarding(GetBasicARCInstKind(Arg)))
63 return FindSingleUseIdentifiedObject(
64 cast<CallInst>(Arg)->getArgOperand(0));
65 if (!IsObjCIdentifiedObject(Arg))
70 // If we found an identifiable object but it has multiple uses, but they are
71 // trivial uses, we can still consider this to be a single-use value.
72 if (IsObjCIdentifiedObject(Arg)) {
73 for (const User *U : Arg->users())
74 if (!U->use_empty() || GetRCIdentityRoot(U) != Arg)
83 /// This is a wrapper around getUnderlyingObjCPtr along the lines of
84 /// GetUnderlyingObjects except that it returns early when it sees the first
86 static inline bool AreAnyUnderlyingObjectsAnAlloca(const Value *V) {
87 SmallPtrSet<const Value *, 4> Visited;
88 SmallVector<const Value *, 4> Worklist;
89 Worklist.push_back(V);
91 const Value *P = Worklist.pop_back_val();
92 P = GetUnderlyingObjCPtr(P);
94 if (isa<AllocaInst>(P))
97 if (!Visited.insert(P).second)
100 if (const SelectInst *SI = dyn_cast<const SelectInst>(P)) {
101 Worklist.push_back(SI->getTrueValue());
102 Worklist.push_back(SI->getFalseValue());
106 if (const PHINode *PN = dyn_cast<const PHINode>(P)) {
107 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
108 Worklist.push_back(PN->getIncomingValue(i));
111 } while (!Worklist.empty());
119 /// \defgroup ARCOpt ARC Optimization.
122 // TODO: On code like this:
125 // stuff_that_cannot_release()
126 // objc_autorelease(%x)
127 // stuff_that_cannot_release()
129 // stuff_that_cannot_release()
130 // objc_autorelease(%x)
132 // The second retain and autorelease can be deleted.
134 // TODO: It should be possible to delete
135 // objc_autoreleasePoolPush and objc_autoreleasePoolPop
136 // pairs if nothing is actually autoreleased between them. Also, autorelease
137 // calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
138 // after inlining) can be turned into plain release calls.
140 // TODO: Critical-edge splitting. If the optimial insertion point is
141 // a critical edge, the current algorithm has to fail, because it doesn't
142 // know how to split edges. It should be possible to make the optimizer
143 // think in terms of edges, rather than blocks, and then split critical
146 // TODO: OptimizeSequences could generalized to be Interprocedural.
148 // TODO: Recognize that a bunch of other objc runtime calls have
149 // non-escaping arguments and non-releasing arguments, and may be
150 // non-autoreleasing.
152 // TODO: Sink autorelease calls as far as possible. Unfortunately we
153 // usually can't sink them past other calls, which would be the main
154 // case where it would be useful.
156 // TODO: The pointer returned from objc_loadWeakRetained is retained.
158 // TODO: Delete release+retain pairs (rare).
160 STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
161 STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
162 STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
163 STATISTIC(NumRets, "Number of return value forwarding "
164 "retain+autoreleases eliminated");
165 STATISTIC(NumRRs, "Number of retain+release paths eliminated");
166 STATISTIC(NumPeeps, "Number of calls peephole-optimized");
168 STATISTIC(NumRetainsBeforeOpt,
169 "Number of retains before optimization");
170 STATISTIC(NumReleasesBeforeOpt,
171 "Number of releases before optimization");
172 STATISTIC(NumRetainsAfterOpt,
173 "Number of retains after optimization");
174 STATISTIC(NumReleasesAfterOpt,
175 "Number of releases after optimization");
179 /// \brief Per-BasicBlock state.
181 /// The number of unique control paths from the entry which can reach this
183 unsigned TopDownPathCount;
185 /// The number of unique control paths to exits from this block.
186 unsigned BottomUpPathCount;
188 /// A type for PerPtrTopDown and PerPtrBottomUp.
189 typedef BlotMapVector<const Value *, PtrState> MapTy;
191 /// The top-down traversal uses this to record information known about a
192 /// pointer at the bottom of each block.
195 /// The bottom-up traversal uses this to record information known about a
196 /// pointer at the top of each block.
197 MapTy PerPtrBottomUp;
199 /// Effective predecessors of the current block ignoring ignorable edges and
200 /// ignored backedges.
201 SmallVector<BasicBlock *, 2> Preds;
202 /// Effective successors of the current block ignoring ignorable edges and
203 /// ignored backedges.
204 SmallVector<BasicBlock *, 2> Succs;
207 static const unsigned OverflowOccurredValue;
209 BBState() : TopDownPathCount(0), BottomUpPathCount(0) { }
211 typedef MapTy::iterator ptr_iterator;
212 typedef MapTy::const_iterator ptr_const_iterator;
214 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
215 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
216 ptr_const_iterator top_down_ptr_begin() const {
217 return PerPtrTopDown.begin();
219 ptr_const_iterator top_down_ptr_end() const {
220 return PerPtrTopDown.end();
223 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
224 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
225 ptr_const_iterator bottom_up_ptr_begin() const {
226 return PerPtrBottomUp.begin();
228 ptr_const_iterator bottom_up_ptr_end() const {
229 return PerPtrBottomUp.end();
232 /// Mark this block as being an entry block, which has one path from the
233 /// entry by definition.
234 void SetAsEntry() { TopDownPathCount = 1; }
236 /// Mark this block as being an exit block, which has one path to an exit by
238 void SetAsExit() { BottomUpPathCount = 1; }
240 /// Attempt to find the PtrState object describing the top down state for
241 /// pointer Arg. Return a new initialized PtrState describing the top down
242 /// state for Arg if we do not find one.
243 PtrState &getPtrTopDownState(const Value *Arg) {
244 return PerPtrTopDown[Arg];
247 /// Attempt to find the PtrState object describing the bottom up state for
248 /// pointer Arg. Return a new initialized PtrState describing the bottom up
249 /// state for Arg if we do not find one.
250 PtrState &getPtrBottomUpState(const Value *Arg) {
251 return PerPtrBottomUp[Arg];
254 /// Attempt to find the PtrState object describing the bottom up state for
256 ptr_iterator findPtrBottomUpState(const Value *Arg) {
257 return PerPtrBottomUp.find(Arg);
260 void clearBottomUpPointers() {
261 PerPtrBottomUp.clear();
264 void clearTopDownPointers() {
265 PerPtrTopDown.clear();
268 void InitFromPred(const BBState &Other);
269 void InitFromSucc(const BBState &Other);
270 void MergePred(const BBState &Other);
271 void MergeSucc(const BBState &Other);
273 /// Compute the number of possible unique paths from an entry to an exit
274 /// which pass through this block. This is only valid after both the
275 /// top-down and bottom-up traversals are complete.
277 /// Returns true if overflow occurred. Returns false if overflow did not
279 bool GetAllPathCountWithOverflow(unsigned &PathCount) const {
280 if (TopDownPathCount == OverflowOccurredValue ||
281 BottomUpPathCount == OverflowOccurredValue)
283 unsigned long long Product =
284 (unsigned long long)TopDownPathCount*BottomUpPathCount;
285 // Overflow occurred if any of the upper bits of Product are set or if all
286 // the lower bits of Product are all set.
287 return (Product >> 32) ||
288 ((PathCount = Product) == OverflowOccurredValue);
291 // Specialized CFG utilities.
292 typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
293 edge_iterator pred_begin() const { return Preds.begin(); }
294 edge_iterator pred_end() const { return Preds.end(); }
295 edge_iterator succ_begin() const { return Succs.begin(); }
296 edge_iterator succ_end() const { return Succs.end(); }
298 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
299 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
301 bool isExit() const { return Succs.empty(); }
304 const unsigned BBState::OverflowOccurredValue = 0xffffffff;
307 void BBState::InitFromPred(const BBState &Other) {
308 PerPtrTopDown = Other.PerPtrTopDown;
309 TopDownPathCount = Other.TopDownPathCount;
312 void BBState::InitFromSucc(const BBState &Other) {
313 PerPtrBottomUp = Other.PerPtrBottomUp;
314 BottomUpPathCount = Other.BottomUpPathCount;
317 /// The top-down traversal uses this to merge information about predecessors to
318 /// form the initial state for a new block.
319 void BBState::MergePred(const BBState &Other) {
320 if (TopDownPathCount == OverflowOccurredValue)
323 // Other.TopDownPathCount can be 0, in which case it is either dead or a
324 // loop backedge. Loop backedges are special.
325 TopDownPathCount += Other.TopDownPathCount;
327 // In order to be consistent, we clear the top down pointers when by adding
328 // TopDownPathCount becomes OverflowOccurredValue even though "true" overflow
330 if (TopDownPathCount == OverflowOccurredValue) {
331 clearTopDownPointers();
335 // Check for overflow. If we have overflow, fall back to conservative
337 if (TopDownPathCount < Other.TopDownPathCount) {
338 TopDownPathCount = OverflowOccurredValue;
339 clearTopDownPointers();
343 // For each entry in the other set, if our set has an entry with the same key,
344 // merge the entries. Otherwise, copy the entry and merge it with an empty
346 for (auto MI = Other.top_down_ptr_begin(), ME = Other.top_down_ptr_end();
348 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
349 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
353 // For each entry in our set, if the other set doesn't have an entry with the
354 // same key, force it to merge with an empty entry.
355 for (auto MI = top_down_ptr_begin(), ME = top_down_ptr_end(); MI != ME; ++MI)
356 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
357 MI->second.Merge(PtrState(), /*TopDown=*/true);
360 /// The bottom-up traversal uses this to merge information about successors to
361 /// form the initial state for a new block.
362 void BBState::MergeSucc(const BBState &Other) {
363 if (BottomUpPathCount == OverflowOccurredValue)
366 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
367 // loop backedge. Loop backedges are special.
368 BottomUpPathCount += Other.BottomUpPathCount;
370 // In order to be consistent, we clear the top down pointers when by adding
371 // BottomUpPathCount becomes OverflowOccurredValue even though "true" overflow
373 if (BottomUpPathCount == OverflowOccurredValue) {
374 clearBottomUpPointers();
378 // Check for overflow. If we have overflow, fall back to conservative
380 if (BottomUpPathCount < Other.BottomUpPathCount) {
381 BottomUpPathCount = OverflowOccurredValue;
382 clearBottomUpPointers();
386 // For each entry in the other set, if our set has an entry with the
387 // same key, merge the entries. Otherwise, copy the entry and merge
388 // it with an empty entry.
389 for (auto MI = Other.bottom_up_ptr_begin(), ME = Other.bottom_up_ptr_end();
391 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
392 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
396 // For each entry in our set, if the other set doesn't have an entry
397 // with the same key, force it to merge with an empty entry.
398 for (auto MI = bottom_up_ptr_begin(), ME = bottom_up_ptr_end(); MI != ME;
400 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
401 MI->second.Merge(PtrState(), /*TopDown=*/false);
404 // Only enable ARC Annotations if we are building a debug version of
407 #define ARC_ANNOTATIONS
410 // Define some macros along the lines of DEBUG and some helper functions to make
411 // it cleaner to create annotations in the source code and to no-op when not
412 // building in debug mode.
413 #ifdef ARC_ANNOTATIONS
415 #include "llvm/Support/CommandLine.h"
417 /// Enable/disable ARC sequence annotations.
419 EnableARCAnnotations("enable-objc-arc-annotations", cl::init(false),
420 cl::desc("Enable emission of arc data flow analysis "
423 DisableCheckForCFGHazards("disable-objc-arc-checkforcfghazards", cl::init(false),
424 cl::desc("Disable check for cfg hazards when "
426 static cl::opt<std::string>
427 ARCAnnotationTargetIdentifier("objc-arc-annotation-target-identifier",
429 cl::desc("filter out all data flow annotations "
430 "but those that apply to the given "
431 "target llvm identifier."));
433 /// This function appends a unique ARCAnnotationProvenanceSourceMDKind id to an
434 /// instruction so that we can track backwards when post processing via the llvm
435 /// arc annotation processor tool. If the function is an
436 static MDString *AppendMDNodeToSourcePtr(unsigned NodeId,
438 MDString *Hash = nullptr;
440 // If pointer is a result of an instruction and it does not have a source
441 // MDNode it, attach a new MDNode onto it. If pointer is a result of
442 // an instruction and does have a source MDNode attached to it, return a
443 // reference to said Node. Otherwise just return 0.
444 if (auto *Inst = dyn_cast<Instruction>(Ptr)) {
446 if (!(Node = Inst->getMetadata(NodeId))) {
447 // We do not have any node. Generate and attatch the hash MDString to the
450 // We just use an MDString to ensure that this metadata gets written out
451 // of line at the module level and to provide a very simple format
452 // encoding the information herein. Both of these makes it simpler to
453 // parse the annotations by a simple external program.
455 raw_string_ostream os(Str);
456 os << "(" << Inst->getParent()->getParent()->getName() << ",%"
457 << Inst->getName() << ")";
459 Hash = MDString::get(Inst->getContext(), os.str());
460 Inst->setMetadata(NodeId, MDNode::get(Inst->getContext(),Hash));
462 // We have a node. Grab its hash and return it.
463 assert(Node->getNumOperands() == 1 &&
464 "An ARCAnnotationProvenanceSourceMDKind can only have 1 operand.");
465 Hash = cast<MDString>(Node->getOperand(0));
467 } else if (auto *Arg = dyn_cast<Argument>(Ptr)) {
469 raw_string_ostream os(str);
470 os << "(" << Arg->getParent()->getName() << ",%" << Arg->getName()
472 Hash = MDString::get(Arg->getContext(), os.str());
478 static std::string SequenceToString(Sequence A) {
480 raw_string_ostream os(str);
485 /// Helper function to change a Sequence into a String object using our overload
486 /// for raw_ostream so we only have printing code in one location.
487 static MDString *SequenceToMDString(LLVMContext &Context,
489 return MDString::get(Context, SequenceToString(A));
492 /// A simple function to generate a MDNode which describes the change in state
493 /// for Value *Ptr caused by Instruction *Inst.
494 static void AppendMDNodeToInstForPtr(unsigned NodeId,
497 MDString *PtrSourceMDNodeID,
500 MDNode *Node = nullptr;
501 Metadata *tmp[3] = {PtrSourceMDNodeID,
502 SequenceToMDString(Inst->getContext(), OldSeq),
503 SequenceToMDString(Inst->getContext(), NewSeq)};
504 Node = MDNode::get(Inst->getContext(), tmp);
506 Inst->setMetadata(NodeId, Node);
509 /// Add to the beginning of the basic block llvm.ptr.annotations which show the
510 /// state of a pointer at the entrance to a basic block.
511 static void GenerateARCBBEntranceAnnotation(const char *Name, BasicBlock *BB,
512 Value *Ptr, Sequence Seq) {
513 // If we have a target identifier, make sure that we match it before
515 if(!ARCAnnotationTargetIdentifier.empty() &&
516 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
519 Module *M = BB->getParent()->getParent();
520 LLVMContext &C = M->getContext();
521 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
522 Type *I8XX = PointerType::getUnqual(I8X);
523 Type *Params[] = {I8XX, I8XX};
524 FunctionType *FTy = FunctionType::get(Type::getVoidTy(C), Params,
526 Constant *Callee = M->getOrInsertFunction(Name, FTy);
528 IRBuilder<> Builder(BB, BB->getFirstInsertionPt());
531 StringRef Tmp = Ptr->getName();
532 if (nullptr == (PtrName = M->getGlobalVariable(Tmp, true))) {
533 Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
535 PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
536 cast<Constant>(ActualPtrName), Tmp);
540 std::string SeqStr = SequenceToString(Seq);
541 if (nullptr == (S = M->getGlobalVariable(SeqStr, true))) {
542 Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
544 S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
545 cast<Constant>(ActualPtrName), SeqStr);
548 Builder.CreateCall2(Callee, PtrName, S);
551 /// Add to the end of the basic block llvm.ptr.annotations which show the state
552 /// of the pointer at the bottom of the basic block.
553 static void GenerateARCBBTerminatorAnnotation(const char *Name, BasicBlock *BB,
554 Value *Ptr, Sequence Seq) {
555 // If we have a target identifier, make sure that we match it before emitting
557 if(!ARCAnnotationTargetIdentifier.empty() &&
558 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
561 Module *M = BB->getParent()->getParent();
562 LLVMContext &C = M->getContext();
563 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
564 Type *I8XX = PointerType::getUnqual(I8X);
565 Type *Params[] = {I8XX, I8XX};
566 FunctionType *FTy = FunctionType::get(Type::getVoidTy(C), Params,
568 Constant *Callee = M->getOrInsertFunction(Name, FTy);
570 IRBuilder<> Builder(BB, std::prev(BB->end()));
573 StringRef Tmp = Ptr->getName();
574 if (nullptr == (PtrName = M->getGlobalVariable(Tmp, true))) {
575 Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
577 PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
578 cast<Constant>(ActualPtrName), Tmp);
582 std::string SeqStr = SequenceToString(Seq);
583 if (nullptr == (S = M->getGlobalVariable(SeqStr, true))) {
584 Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
586 S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
587 cast<Constant>(ActualPtrName), SeqStr);
589 Builder.CreateCall2(Callee, PtrName, S);
592 /// Adds a source annotation to pointer and a state change annotation to Inst
593 /// referencing the source annotation and the old/new state of pointer.
594 static void GenerateARCAnnotation(unsigned InstMDId,
600 if (EnableARCAnnotations) {
601 // If we have a target identifier, make sure that we match it before
602 // emitting an annotation.
603 if(!ARCAnnotationTargetIdentifier.empty() &&
604 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
607 // First generate the source annotation on our pointer. This will return an
608 // MDString* if Ptr actually comes from an instruction implying we can put
609 // in a source annotation. If AppendMDNodeToSourcePtr returns 0 (i.e. NULL),
610 // then we know that our pointer is from an Argument so we put a reference
611 // to the argument number.
613 // The point of this is to make it easy for the
614 // llvm-arc-annotation-processor tool to cross reference where the source
615 // pointer is in the LLVM IR since the LLVM IR parser does not submit such
616 // information via debug info for backends to use (since why would anyone
617 // need such a thing from LLVM IR besides in non-standard cases
619 MDString *SourcePtrMDNode =
620 AppendMDNodeToSourcePtr(PtrMDId, Ptr);
621 AppendMDNodeToInstForPtr(InstMDId, Inst, Ptr, SourcePtrMDNode, OldSeq,
626 // The actual interface for accessing the above functionality is defined via
627 // some simple macros which are defined below. We do this so that the user does
628 // not need to pass in what metadata id is needed resulting in cleaner code and
629 // additionally since it provides an easy way to conditionally no-op all
630 // annotation support in a non-debug build.
632 /// Use this macro to annotate a sequence state change when processing
633 /// instructions bottom up,
634 #define ANNOTATE_BOTTOMUP(inst, ptr, old, new) \
635 GenerateARCAnnotation(ARCAnnotationBottomUpMDKind, \
636 ARCAnnotationProvenanceSourceMDKind, (inst), \
637 const_cast<Value*>(ptr), (old), (new))
638 /// Use this macro to annotate a sequence state change when processing
639 /// instructions top down.
640 #define ANNOTATE_TOPDOWN(inst, ptr, old, new) \
641 GenerateARCAnnotation(ARCAnnotationTopDownMDKind, \
642 ARCAnnotationProvenanceSourceMDKind, (inst), \
643 const_cast<Value*>(ptr), (old), (new))
645 #define ANNOTATE_BB(_states, _bb, _name, _type, _direction) \
647 if (EnableARCAnnotations) { \
648 for(BBState::ptr_const_iterator I = (_states)._direction##_ptr_begin(), \
649 E = (_states)._direction##_ptr_end(); I != E; ++I) { \
650 Value *Ptr = const_cast<Value*>(I->first); \
651 Sequence Seq = I->second.GetSeq(); \
652 GenerateARCBB ## _type ## Annotation(_name, (_bb), Ptr, Seq); \
657 #define ANNOTATE_BOTTOMUP_BBSTART(_states, _basicblock) \
658 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbstart", \
660 #define ANNOTATE_BOTTOMUP_BBEND(_states, _basicblock) \
661 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbend", \
662 Terminator, bottom_up)
663 #define ANNOTATE_TOPDOWN_BBSTART(_states, _basicblock) \
664 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbstart", \
666 #define ANNOTATE_TOPDOWN_BBEND(_states, _basicblock) \
667 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbend", \
668 Terminator, top_down)
670 #else // !ARC_ANNOTATION
671 // If annotations are off, noop.
672 #define ANNOTATE_BOTTOMUP(inst, ptr, old, new)
673 #define ANNOTATE_TOPDOWN(inst, ptr, old, new)
674 #define ANNOTATE_BOTTOMUP_BBSTART(states, basicblock)
675 #define ANNOTATE_BOTTOMUP_BBEND(states, basicblock)
676 #define ANNOTATE_TOPDOWN_BBSTART(states, basicblock)
677 #define ANNOTATE_TOPDOWN_BBEND(states, basicblock)
678 #endif // !ARC_ANNOTATION
681 /// \brief The main ARC optimization pass.
682 class ObjCARCOpt : public FunctionPass {
684 ProvenanceAnalysis PA;
685 ARCRuntimeEntryPoints EP;
687 // This is used to track if a pointer is stored into an alloca.
688 DenseSet<const Value *> MultiOwnersSet;
690 /// A flag indicating whether this optimization pass should run.
693 /// Flags which determine whether each of the interesting runtine functions
694 /// is in fact used in the current function.
695 unsigned UsedInThisFunction;
697 /// The Metadata Kind for clang.imprecise_release metadata.
698 unsigned ImpreciseReleaseMDKind;
700 /// The Metadata Kind for clang.arc.copy_on_escape metadata.
701 unsigned CopyOnEscapeMDKind;
703 /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata.
704 unsigned NoObjCARCExceptionsMDKind;
706 #ifdef ARC_ANNOTATIONS
707 /// The Metadata Kind for llvm.arc.annotation.bottomup metadata.
708 unsigned ARCAnnotationBottomUpMDKind;
709 /// The Metadata Kind for llvm.arc.annotation.topdown metadata.
710 unsigned ARCAnnotationTopDownMDKind;
711 /// The Metadata Kind for llvm.arc.annotation.provenancesource metadata.
712 unsigned ARCAnnotationProvenanceSourceMDKind;
713 #endif // ARC_ANNOATIONS
715 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
716 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
718 void OptimizeIndividualCalls(Function &F);
720 void CheckForCFGHazards(const BasicBlock *BB,
721 DenseMap<const BasicBlock *, BBState> &BBStates,
722 BBState &MyStates) const;
723 bool VisitInstructionBottomUp(Instruction *Inst, BasicBlock *BB,
724 BlotMapVector<Value *, RRInfo> &Retains,
726 bool VisitBottomUp(BasicBlock *BB,
727 DenseMap<const BasicBlock *, BBState> &BBStates,
728 BlotMapVector<Value *, RRInfo> &Retains);
729 bool VisitInstructionTopDown(Instruction *Inst,
730 DenseMap<Value *, RRInfo> &Releases,
732 bool VisitTopDown(BasicBlock *BB,
733 DenseMap<const BasicBlock *, BBState> &BBStates,
734 DenseMap<Value *, RRInfo> &Releases);
735 bool Visit(Function &F, DenseMap<const BasicBlock *, BBState> &BBStates,
736 BlotMapVector<Value *, RRInfo> &Retains,
737 DenseMap<Value *, RRInfo> &Releases);
739 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
740 BlotMapVector<Value *, RRInfo> &Retains,
741 DenseMap<Value *, RRInfo> &Releases,
742 SmallVectorImpl<Instruction *> &DeadInsts, Module *M);
744 bool ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState> &BBStates,
745 BlotMapVector<Value *, RRInfo> &Retains,
746 DenseMap<Value *, RRInfo> &Releases, Module *M,
747 SmallVectorImpl<Instruction *> &NewRetains,
748 SmallVectorImpl<Instruction *> &NewReleases,
749 SmallVectorImpl<Instruction *> &DeadInsts,
750 RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
751 Value *Arg, bool KnownSafe,
752 bool &AnyPairsCompletelyEliminated);
754 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
755 BlotMapVector<Value *, RRInfo> &Retains,
756 DenseMap<Value *, RRInfo> &Releases, Module *M);
758 void OptimizeWeakCalls(Function &F);
760 bool OptimizeSequences(Function &F);
762 void OptimizeReturns(Function &F);
765 void GatherStatistics(Function &F, bool AfterOptimization = false);
768 void getAnalysisUsage(AnalysisUsage &AU) const override;
769 bool doInitialization(Module &M) override;
770 bool runOnFunction(Function &F) override;
771 void releaseMemory() override;
775 ObjCARCOpt() : FunctionPass(ID) {
776 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
781 char ObjCARCOpt::ID = 0;
782 INITIALIZE_PASS_BEGIN(ObjCARCOpt,
783 "objc-arc", "ObjC ARC optimization", false, false)
784 INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
785 INITIALIZE_PASS_END(ObjCARCOpt,
786 "objc-arc", "ObjC ARC optimization", false, false)
788 Pass *llvm::createObjCARCOptPass() {
789 return new ObjCARCOpt();
792 void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
793 AU.addRequired<ObjCARCAliasAnalysis>();
794 AU.addRequired<AliasAnalysis>();
795 // ARC optimization doesn't currently split critical edges.
796 AU.setPreservesCFG();
799 /// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is
800 /// not a return value. Or, if it can be paired with an
801 /// objc_autoreleaseReturnValue, delete the pair and return true.
803 ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
804 // Check for the argument being from an immediately preceding call or invoke.
805 const Value *Arg = GetArgRCIdentityRoot(RetainRV);
806 ImmutableCallSite CS(Arg);
807 if (const Instruction *Call = CS.getInstruction()) {
808 if (Call->getParent() == RetainRV->getParent()) {
809 BasicBlock::const_iterator I = Call;
811 while (IsNoopInstruction(I)) ++I;
814 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
815 BasicBlock *RetainRVParent = RetainRV->getParent();
816 if (II->getNormalDest() == RetainRVParent) {
817 BasicBlock::const_iterator I = RetainRVParent->begin();
818 while (IsNoopInstruction(I)) ++I;
825 // Check for being preceded by an objc_autoreleaseReturnValue on the same
826 // pointer. In this case, we can delete the pair.
827 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
829 do --I; while (I != Begin && IsNoopInstruction(I));
830 if (GetBasicARCInstKind(I) == ARCInstKind::AutoreleaseRV &&
831 GetArgRCIdentityRoot(I) == Arg) {
835 DEBUG(dbgs() << "Erasing autoreleaseRV,retainRV pair: " << *I << "\n"
836 << "Erasing " << *RetainRV << "\n");
839 EraseInstruction(RetainRV);
844 // Turn it to a plain objc_retain.
848 DEBUG(dbgs() << "Transforming objc_retainAutoreleasedReturnValue => "
849 "objc_retain since the operand is not a return value.\n"
850 "Old = " << *RetainRV << "\n");
852 Constant *NewDecl = EP.get(ARCRuntimeEntryPoints::EPT_Retain);
853 cast<CallInst>(RetainRV)->setCalledFunction(NewDecl);
855 DEBUG(dbgs() << "New = " << *RetainRV << "\n");
860 /// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not
861 /// used as a return value.
862 void ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F,
863 Instruction *AutoreleaseRV,
864 ARCInstKind &Class) {
865 // Check for a return of the pointer value.
866 const Value *Ptr = GetArgRCIdentityRoot(AutoreleaseRV);
867 SmallVector<const Value *, 2> Users;
868 Users.push_back(Ptr);
870 Ptr = Users.pop_back_val();
871 for (const User *U : Ptr->users()) {
872 if (isa<ReturnInst>(U) || GetBasicARCInstKind(U) == ARCInstKind::RetainRV)
874 if (isa<BitCastInst>(U))
877 } while (!Users.empty());
882 DEBUG(dbgs() << "Transforming objc_autoreleaseReturnValue => "
883 "objc_autorelease since its operand is not used as a return "
885 "Old = " << *AutoreleaseRV << "\n");
887 CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
888 Constant *NewDecl = EP.get(ARCRuntimeEntryPoints::EPT_Autorelease);
889 AutoreleaseRVCI->setCalledFunction(NewDecl);
890 AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
891 Class = ARCInstKind::Autorelease;
893 DEBUG(dbgs() << "New: " << *AutoreleaseRV << "\n");
897 /// Visit each call, one at a time, and make simplifications without doing any
898 /// additional analysis.
899 void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
900 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeIndividualCalls ==\n");
901 // Reset all the flags in preparation for recomputing them.
902 UsedInThisFunction = 0;
904 // Visit all objc_* calls in F.
905 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
906 Instruction *Inst = &*I++;
908 ARCInstKind Class = GetBasicARCInstKind(Inst);
910 DEBUG(dbgs() << "Visiting: Class: " << Class << "; " << *Inst << "\n");
915 // Delete no-op casts. These function calls have special semantics, but
916 // the semantics are entirely implemented via lowering in the front-end,
917 // so by the time they reach the optimizer, they are just no-op calls
918 // which return their argument.
920 // There are gray areas here, as the ability to cast reference-counted
921 // pointers to raw void* and back allows code to break ARC assumptions,
922 // however these are currently considered to be unimportant.
923 case ARCInstKind::NoopCast:
926 DEBUG(dbgs() << "Erasing no-op cast: " << *Inst << "\n");
927 EraseInstruction(Inst);
930 // If the pointer-to-weak-pointer is null, it's undefined behavior.
931 case ARCInstKind::StoreWeak:
932 case ARCInstKind::LoadWeak:
933 case ARCInstKind::LoadWeakRetained:
934 case ARCInstKind::InitWeak:
935 case ARCInstKind::DestroyWeak: {
936 CallInst *CI = cast<CallInst>(Inst);
937 if (IsNullOrUndef(CI->getArgOperand(0))) {
939 Type *Ty = CI->getArgOperand(0)->getType();
940 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
941 Constant::getNullValue(Ty),
943 llvm::Value *NewValue = UndefValue::get(CI->getType());
944 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
945 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
946 CI->replaceAllUsesWith(NewValue);
947 CI->eraseFromParent();
952 case ARCInstKind::CopyWeak:
953 case ARCInstKind::MoveWeak: {
954 CallInst *CI = cast<CallInst>(Inst);
955 if (IsNullOrUndef(CI->getArgOperand(0)) ||
956 IsNullOrUndef(CI->getArgOperand(1))) {
958 Type *Ty = CI->getArgOperand(0)->getType();
959 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
960 Constant::getNullValue(Ty),
963 llvm::Value *NewValue = UndefValue::get(CI->getType());
964 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
965 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
967 CI->replaceAllUsesWith(NewValue);
968 CI->eraseFromParent();
973 case ARCInstKind::RetainRV:
974 if (OptimizeRetainRVCall(F, Inst))
977 case ARCInstKind::AutoreleaseRV:
978 OptimizeAutoreleaseRVCall(F, Inst, Class);
982 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
983 if (IsAutorelease(Class) && Inst->use_empty()) {
984 CallInst *Call = cast<CallInst>(Inst);
985 const Value *Arg = Call->getArgOperand(0);
986 Arg = FindSingleUseIdentifiedObject(Arg);
991 // Create the declaration lazily.
992 LLVMContext &C = Inst->getContext();
994 Constant *Decl = EP.get(ARCRuntimeEntryPoints::EPT_Release);
995 CallInst *NewCall = CallInst::Create(Decl, Call->getArgOperand(0), "",
997 NewCall->setMetadata(ImpreciseReleaseMDKind, MDNode::get(C, None));
999 DEBUG(dbgs() << "Replacing autorelease{,RV}(x) with objc_release(x) "
1000 "since x is otherwise unused.\nOld: " << *Call << "\nNew: "
1001 << *NewCall << "\n");
1003 EraseInstruction(Call);
1005 Class = ARCInstKind::Release;
1009 // For functions which can never be passed stack arguments, add
1011 if (IsAlwaysTail(Class)) {
1013 DEBUG(dbgs() << "Adding tail keyword to function since it can never be "
1014 "passed stack args: " << *Inst << "\n");
1015 cast<CallInst>(Inst)->setTailCall();
1018 // Ensure that functions that can never have a "tail" keyword due to the
1019 // semantics of ARC truly do not do so.
1020 if (IsNeverTail(Class)) {
1022 DEBUG(dbgs() << "Removing tail keyword from function: " << *Inst <<
1024 cast<CallInst>(Inst)->setTailCall(false);
1027 // Set nounwind as needed.
1028 if (IsNoThrow(Class)) {
1030 DEBUG(dbgs() << "Found no throw class. Setting nounwind on: " << *Inst
1032 cast<CallInst>(Inst)->setDoesNotThrow();
1035 if (!IsNoopOnNull(Class)) {
1036 UsedInThisFunction |= 1 << unsigned(Class);
1040 const Value *Arg = GetArgRCIdentityRoot(Inst);
1042 // ARC calls with null are no-ops. Delete them.
1043 if (IsNullOrUndef(Arg)) {
1046 DEBUG(dbgs() << "ARC calls with null are no-ops. Erasing: " << *Inst
1048 EraseInstruction(Inst);
1052 // Keep track of which of retain, release, autorelease, and retain_block
1053 // are actually present in this function.
1054 UsedInThisFunction |= 1 << unsigned(Class);
1056 // If Arg is a PHI, and one or more incoming values to the
1057 // PHI are null, and the call is control-equivalent to the PHI, and there
1058 // are no relevant side effects between the PHI and the call, the call
1059 // could be pushed up to just those paths with non-null incoming values.
1060 // For now, don't bother splitting critical edges for this.
1061 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
1062 Worklist.push_back(std::make_pair(Inst, Arg));
1064 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
1068 const PHINode *PN = dyn_cast<PHINode>(Arg);
1071 // Determine if the PHI has any null operands, or any incoming
1073 bool HasNull = false;
1074 bool HasCriticalEdges = false;
1075 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1077 GetRCIdentityRoot(PN->getIncomingValue(i));
1078 if (IsNullOrUndef(Incoming))
1080 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
1081 .getNumSuccessors() != 1) {
1082 HasCriticalEdges = true;
1086 // If we have null operands and no critical edges, optimize.
1087 if (!HasCriticalEdges && HasNull) {
1088 SmallPtrSet<Instruction *, 4> DependingInstructions;
1089 SmallPtrSet<const BasicBlock *, 4> Visited;
1091 // Check that there is nothing that cares about the reference
1092 // count between the call and the phi.
1094 case ARCInstKind::Retain:
1095 case ARCInstKind::RetainBlock:
1096 // These can always be moved up.
1098 case ARCInstKind::Release:
1099 // These can't be moved across things that care about the retain
1101 FindDependencies(NeedsPositiveRetainCount, Arg,
1102 Inst->getParent(), Inst,
1103 DependingInstructions, Visited, PA);
1105 case ARCInstKind::Autorelease:
1106 // These can't be moved across autorelease pool scope boundaries.
1107 FindDependencies(AutoreleasePoolBoundary, Arg,
1108 Inst->getParent(), Inst,
1109 DependingInstructions, Visited, PA);
1111 case ARCInstKind::RetainRV:
1112 case ARCInstKind::AutoreleaseRV:
1113 // Don't move these; the RV optimization depends on the autoreleaseRV
1114 // being tail called, and the retainRV being immediately after a call
1115 // (which might still happen if we get lucky with codegen layout, but
1116 // it's not worth taking the chance).
1119 llvm_unreachable("Invalid dependence flavor");
1122 if (DependingInstructions.size() == 1 &&
1123 *DependingInstructions.begin() == PN) {
1126 // Clone the call into each predecessor that has a non-null value.
1127 CallInst *CInst = cast<CallInst>(Inst);
1128 Type *ParamTy = CInst->getArgOperand(0)->getType();
1129 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1131 GetRCIdentityRoot(PN->getIncomingValue(i));
1132 if (!IsNullOrUndef(Incoming)) {
1133 CallInst *Clone = cast<CallInst>(CInst->clone());
1134 Value *Op = PN->getIncomingValue(i);
1135 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
1136 if (Op->getType() != ParamTy)
1137 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
1138 Clone->setArgOperand(0, Op);
1139 Clone->insertBefore(InsertPos);
1141 DEBUG(dbgs() << "Cloning "
1143 "And inserting clone at " << *InsertPos << "\n");
1144 Worklist.push_back(std::make_pair(Clone, Incoming));
1147 // Erase the original call.
1148 DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
1149 EraseInstruction(CInst);
1153 } while (!Worklist.empty());
1157 /// If we have a top down pointer in the S_Use state, make sure that there are
1158 /// no CFG hazards by checking the states of various bottom up pointers.
1159 static void CheckForUseCFGHazard(const Sequence SuccSSeq,
1160 const bool SuccSRRIKnownSafe,
1162 bool &SomeSuccHasSame,
1163 bool &AllSuccsHaveSame,
1164 bool &NotAllSeqEqualButKnownSafe,
1165 bool &ShouldContinue) {
1167 case S_CanRelease: {
1168 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe) {
1169 S.ClearSequenceProgress();
1172 S.SetCFGHazardAfflicted(true);
1173 ShouldContinue = true;
1177 SomeSuccHasSame = true;
1181 case S_MovableRelease:
1182 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe)
1183 AllSuccsHaveSame = false;
1185 NotAllSeqEqualButKnownSafe = true;
1188 llvm_unreachable("bottom-up pointer in retain state!");
1190 llvm_unreachable("This should have been handled earlier.");
1194 /// If we have a Top Down pointer in the S_CanRelease state, make sure that
1195 /// there are no CFG hazards by checking the states of various bottom up
1197 static void CheckForCanReleaseCFGHazard(const Sequence SuccSSeq,
1198 const bool SuccSRRIKnownSafe,
1200 bool &SomeSuccHasSame,
1201 bool &AllSuccsHaveSame,
1202 bool &NotAllSeqEqualButKnownSafe) {
1205 SomeSuccHasSame = true;
1209 case S_MovableRelease:
1211 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe)
1212 AllSuccsHaveSame = false;
1214 NotAllSeqEqualButKnownSafe = true;
1217 llvm_unreachable("bottom-up pointer in retain state!");
1219 llvm_unreachable("This should have been handled earlier.");
1223 /// Check for critical edges, loop boundaries, irreducible control flow, or
1224 /// other CFG structures where moving code across the edge would result in it
1225 /// being executed more.
1227 ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
1228 DenseMap<const BasicBlock *, BBState> &BBStates,
1229 BBState &MyStates) const {
1230 // If any top-down local-use or possible-dec has a succ which is earlier in
1231 // the sequence, forget it.
1232 for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
1233 E = MyStates.top_down_ptr_end(); I != E; ++I) {
1234 PtrState &S = I->second;
1235 const Sequence Seq = I->second.GetSeq();
1237 // We only care about S_Retain, S_CanRelease, and S_Use.
1241 // Make sure that if extra top down states are added in the future that this
1242 // code is updated to handle it.
1243 assert((Seq == S_Retain || Seq == S_CanRelease || Seq == S_Use) &&
1244 "Unknown top down sequence state.");
1246 const Value *Arg = I->first;
1247 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
1248 bool SomeSuccHasSame = false;
1249 bool AllSuccsHaveSame = true;
1250 bool NotAllSeqEqualButKnownSafe = false;
1252 succ_const_iterator SI(TI), SE(TI, false);
1254 for (; SI != SE; ++SI) {
1255 // If VisitBottomUp has pointer information for this successor, take
1256 // what we know about it.
1257 const DenseMap<const BasicBlock *, BBState>::iterator BBI =
1259 assert(BBI != BBStates.end());
1260 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
1261 const Sequence SuccSSeq = SuccS.GetSeq();
1263 // If bottom up, the pointer is in an S_None state, clear the sequence
1264 // progress since the sequence in the bottom up state finished
1265 // suggesting a mismatch in between retains/releases. This is true for
1266 // all three cases that we are handling here: S_Retain, S_Use, and
1268 if (SuccSSeq == S_None) {
1269 S.ClearSequenceProgress();
1273 // If we have S_Use or S_CanRelease, perform our check for cfg hazard
1275 const bool SuccSRRIKnownSafe = SuccS.IsKnownSafe();
1277 // *NOTE* We do not use Seq from above here since we are allowing for
1278 // S.GetSeq() to change while we are visiting basic blocks.
1279 switch(S.GetSeq()) {
1281 bool ShouldContinue = false;
1282 CheckForUseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S, SomeSuccHasSame,
1283 AllSuccsHaveSame, NotAllSeqEqualButKnownSafe,
1289 case S_CanRelease: {
1290 CheckForCanReleaseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S,
1291 SomeSuccHasSame, AllSuccsHaveSame,
1292 NotAllSeqEqualButKnownSafe);
1299 case S_MovableRelease:
1304 // If the state at the other end of any of the successor edges
1305 // matches the current state, require all edges to match. This
1306 // guards against loops in the middle of a sequence.
1307 if (SomeSuccHasSame && !AllSuccsHaveSame) {
1308 S.ClearSequenceProgress();
1309 } else if (NotAllSeqEqualButKnownSafe) {
1310 // If we would have cleared the state foregoing the fact that we are known
1311 // safe, stop code motion. This is because whether or not it is safe to
1312 // remove RR pairs via KnownSafe is an orthogonal concept to whether we
1313 // are allowed to perform code motion.
1314 S.SetCFGHazardAfflicted(true);
1319 bool ObjCARCOpt::VisitInstructionBottomUp(
1320 Instruction *Inst, BasicBlock *BB, BlotMapVector<Value *, RRInfo> &Retains,
1321 BBState &MyStates) {
1322 bool NestingDetected = false;
1323 ARCInstKind Class = GetARCInstKind(Inst);
1324 const Value *Arg = nullptr;
1326 DEBUG(dbgs() << "Class: " << Class << "\n");
1329 case ARCInstKind::Release: {
1330 Arg = GetArgRCIdentityRoot(Inst);
1332 PtrState &S = MyStates.getPtrBottomUpState(Arg);
1334 // If we see two releases in a row on the same pointer. If so, make
1335 // a note, and we'll cicle back to revisit it after we've
1336 // hopefully eliminated the second release, which may allow us to
1337 // eliminate the first release too.
1338 // Theoretically we could implement removal of nested retain+release
1339 // pairs by making PtrState hold a stack of states, but this is
1340 // simple and avoids adding overhead for the non-nested case.
1341 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease) {
1342 DEBUG(dbgs() << "Found nested releases (i.e. a release pair)\n");
1343 NestingDetected = true;
1346 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
1347 Sequence NewSeq = ReleaseMetadata ? S_MovableRelease : S_Release;
1348 ANNOTATE_BOTTOMUP(Inst, Arg, S.GetSeq(), NewSeq);
1349 S.ResetSequenceProgress(NewSeq);
1350 S.SetReleaseMetadata(ReleaseMetadata);
1351 S.SetKnownSafe(S.HasKnownPositiveRefCount());
1352 S.SetTailCallRelease(cast<CallInst>(Inst)->isTailCall());
1354 S.SetKnownPositiveRefCount();
1357 case ARCInstKind::RetainBlock:
1358 // In OptimizeIndividualCalls, we have strength reduced all optimizable
1359 // objc_retainBlocks to objc_retains. Thus at this point any
1360 // objc_retainBlocks that we see are not optimizable.
1362 case ARCInstKind::Retain:
1363 case ARCInstKind::RetainRV: {
1364 Arg = GetArgRCIdentityRoot(Inst);
1366 PtrState &S = MyStates.getPtrBottomUpState(Arg);
1367 S.SetKnownPositiveRefCount();
1369 Sequence OldSeq = S.GetSeq();
1373 case S_MovableRelease:
1375 // If OldSeq is not S_Use or OldSeq is S_Use and we are tracking an
1376 // imprecise release, clear our reverse insertion points.
1377 if (OldSeq != S_Use || S.IsTrackingImpreciseReleases())
1378 S.ClearReverseInsertPts();
1381 // Don't do retain+release tracking for ARCInstKind::RetainRV,
1383 // better to let it remain as the first instruction after a call.
1384 if (Class != ARCInstKind::RetainRV)
1385 Retains[Inst] = S.GetRRInfo();
1386 S.ClearSequenceProgress();
1391 llvm_unreachable("bottom-up pointer in retain state!");
1393 ANNOTATE_BOTTOMUP(Inst, Arg, OldSeq, S.GetSeq());
1394 // A retain moving bottom up can be a use.
1397 case ARCInstKind::AutoreleasepoolPop:
1398 // Conservatively, clear MyStates for all known pointers.
1399 MyStates.clearBottomUpPointers();
1400 return NestingDetected;
1401 case ARCInstKind::AutoreleasepoolPush:
1402 case ARCInstKind::None:
1403 // These are irrelevant.
1404 return NestingDetected;
1405 case ARCInstKind::User:
1406 // If we have a store into an alloca of a pointer we are tracking, the
1407 // pointer has multiple owners implying that we must be more conservative.
1409 // This comes up in the context of a pointer being ``KnownSafe''. In the
1410 // presence of a block being initialized, the frontend will emit the
1411 // objc_retain on the original pointer and the release on the pointer loaded
1412 // from the alloca. The optimizer will through the provenance analysis
1413 // realize that the two are related, but since we only require KnownSafe in
1414 // one direction, will match the inner retain on the original pointer with
1415 // the guard release on the original pointer. This is fixed by ensuring that
1416 // in the presence of allocas we only unconditionally remove pointers if
1417 // both our retain and our release are KnownSafe.
1418 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1419 if (AreAnyUnderlyingObjectsAnAlloca(SI->getPointerOperand())) {
1420 BBState::ptr_iterator I = MyStates.findPtrBottomUpState(
1421 GetRCIdentityRoot(SI->getValueOperand()));
1422 if (I != MyStates.bottom_up_ptr_end())
1423 MultiOwnersSet.insert(I->first);
1431 // Consider any other possible effects of this instruction on each
1432 // pointer being tracked.
1433 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
1434 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
1435 const Value *Ptr = MI->first;
1437 continue; // Handled above.
1438 PtrState &S = MI->second;
1439 Sequence Seq = S.GetSeq();
1441 // Check for possible releases.
1442 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
1443 DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr
1445 S.ClearKnownPositiveRefCount();
1448 S.SetSeq(S_CanRelease);
1449 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S.GetSeq());
1453 case S_MovableRelease:
1458 llvm_unreachable("bottom-up pointer in retain state!");
1462 // Check for possible direct uses.
1465 case S_MovableRelease:
1466 if (CanUse(Inst, Ptr, PA, Class)) {
1467 DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr
1469 assert(!S.HasReverseInsertPts());
1470 // If this is an invoke instruction, we're scanning it as part of
1471 // one of its successor blocks, since we can't insert code after it
1472 // in its own block, and we don't want to split critical edges.
1473 if (isa<InvokeInst>(Inst))
1474 S.InsertReverseInsertPt(BB->getFirstInsertionPt());
1476 S.InsertReverseInsertPt(std::next(BasicBlock::iterator(Inst)));
1478 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
1479 } else if (Seq == S_Release && IsUser(Class)) {
1480 DEBUG(dbgs() << "PreciseReleaseUse: Seq: " << Seq << "; " << *Ptr
1482 // Non-movable releases depend on any possible objc pointer use.
1484 ANNOTATE_BOTTOMUP(Inst, Ptr, S_Release, S_Stop);
1485 assert(!S.HasReverseInsertPts());
1486 // As above; handle invoke specially.
1487 if (isa<InvokeInst>(Inst))
1488 S.InsertReverseInsertPt(BB->getFirstInsertionPt());
1490 S.InsertReverseInsertPt(std::next(BasicBlock::iterator(Inst)));
1494 if (CanUse(Inst, Ptr, PA, Class)) {
1495 DEBUG(dbgs() << "PreciseStopUse: Seq: " << Seq << "; " << *Ptr
1498 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
1506 llvm_unreachable("bottom-up pointer in retain state!");
1510 return NestingDetected;
1513 bool ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
1514 DenseMap<const BasicBlock *, BBState> &BBStates,
1515 BlotMapVector<Value *, RRInfo> &Retains) {
1517 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitBottomUp ==\n");
1519 bool NestingDetected = false;
1520 BBState &MyStates = BBStates[BB];
1522 // Merge the states from each successor to compute the initial state
1523 // for the current block.
1524 BBState::edge_iterator SI(MyStates.succ_begin()),
1525 SE(MyStates.succ_end());
1527 const BasicBlock *Succ = *SI;
1528 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
1529 assert(I != BBStates.end());
1530 MyStates.InitFromSucc(I->second);
1532 for (; SI != SE; ++SI) {
1534 I = BBStates.find(Succ);
1535 assert(I != BBStates.end());
1536 MyStates.MergeSucc(I->second);
1540 // If ARC Annotations are enabled, output the current state of pointers at the
1541 // bottom of the basic block.
1542 ANNOTATE_BOTTOMUP_BBEND(MyStates, BB);
1544 // Visit all the instructions, bottom-up.
1545 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
1546 Instruction *Inst = std::prev(I);
1548 // Invoke instructions are visited as part of their successors (below).
1549 if (isa<InvokeInst>(Inst))
1552 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
1554 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
1557 // If there's a predecessor with an invoke, visit the invoke as if it were
1558 // part of this block, since we can't insert code after an invoke in its own
1559 // block, and we don't want to split critical edges.
1560 for (BBState::edge_iterator PI(MyStates.pred_begin()),
1561 PE(MyStates.pred_end()); PI != PE; ++PI) {
1562 BasicBlock *Pred = *PI;
1563 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
1564 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
1567 // If ARC Annotations are enabled, output the current state of pointers at the
1568 // top of the basic block.
1569 ANNOTATE_BOTTOMUP_BBSTART(MyStates, BB);
1571 return NestingDetected;
1575 ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
1576 DenseMap<Value *, RRInfo> &Releases,
1577 BBState &MyStates) {
1578 bool NestingDetected = false;
1579 ARCInstKind Class = GetARCInstKind(Inst);
1580 const Value *Arg = nullptr;
1583 case ARCInstKind::RetainBlock:
1584 // In OptimizeIndividualCalls, we have strength reduced all optimizable
1585 // objc_retainBlocks to objc_retains. Thus at this point any
1586 // objc_retainBlocks that we see are not optimizable.
1588 case ARCInstKind::Retain:
1589 case ARCInstKind::RetainRV: {
1590 Arg = GetArgRCIdentityRoot(Inst);
1592 PtrState &S = MyStates.getPtrTopDownState(Arg);
1594 // Don't do retain+release tracking for ARCInstKind::RetainRV, because
1596 // better to let it remain as the first instruction after a call.
1597 if (Class != ARCInstKind::RetainRV) {
1598 // If we see two retains in a row on the same pointer. If so, make
1599 // a note, and we'll cicle back to revisit it after we've
1600 // hopefully eliminated the second retain, which may allow us to
1601 // eliminate the first retain too.
1602 // Theoretically we could implement removal of nested retain+release
1603 // pairs by making PtrState hold a stack of states, but this is
1604 // simple and avoids adding overhead for the non-nested case.
1605 if (S.GetSeq() == S_Retain)
1606 NestingDetected = true;
1608 ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_Retain);
1609 S.ResetSequenceProgress(S_Retain);
1610 S.SetKnownSafe(S.HasKnownPositiveRefCount());
1614 S.SetKnownPositiveRefCount();
1616 // A retain can be a potential use; procede to the generic checking
1620 case ARCInstKind::Release: {
1621 Arg = GetArgRCIdentityRoot(Inst);
1623 PtrState &S = MyStates.getPtrTopDownState(Arg);
1624 S.ClearKnownPositiveRefCount();
1626 Sequence OldSeq = S.GetSeq();
1628 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
1633 if (OldSeq == S_Retain || ReleaseMetadata != nullptr)
1634 S.ClearReverseInsertPts();
1637 S.SetReleaseMetadata(ReleaseMetadata);
1638 S.SetTailCallRelease(cast<CallInst>(Inst)->isTailCall());
1639 Releases[Inst] = S.GetRRInfo();
1640 ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_None);
1641 S.ClearSequenceProgress();
1647 case S_MovableRelease:
1648 llvm_unreachable("top-down pointer in release state!");
1652 case ARCInstKind::AutoreleasepoolPop:
1653 // Conservatively, clear MyStates for all known pointers.
1654 MyStates.clearTopDownPointers();
1655 return NestingDetected;
1656 case ARCInstKind::AutoreleasepoolPush:
1657 case ARCInstKind::None:
1658 // These are irrelevant.
1659 return NestingDetected;
1664 // Consider any other possible effects of this instruction on each
1665 // pointer being tracked.
1666 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
1667 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
1668 const Value *Ptr = MI->first;
1670 continue; // Handled above.
1671 PtrState &S = MI->second;
1672 Sequence Seq = S.GetSeq();
1674 // Check for possible releases.
1675 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
1676 DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr
1678 S.ClearKnownPositiveRefCount();
1681 S.SetSeq(S_CanRelease);
1682 ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_CanRelease);
1683 assert(!S.HasReverseInsertPts());
1684 S.InsertReverseInsertPt(Inst);
1686 // One call can't cause a transition from S_Retain to S_CanRelease
1687 // and S_CanRelease to S_Use. If we've made the first transition,
1696 case S_MovableRelease:
1697 llvm_unreachable("top-down pointer in release state!");
1701 // Check for possible direct uses.
1704 if (CanUse(Inst, Ptr, PA, Class)) {
1705 DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr
1708 ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_Use);
1717 case S_MovableRelease:
1718 llvm_unreachable("top-down pointer in release state!");
1722 return NestingDetected;
1726 ObjCARCOpt::VisitTopDown(BasicBlock *BB,
1727 DenseMap<const BasicBlock *, BBState> &BBStates,
1728 DenseMap<Value *, RRInfo> &Releases) {
1729 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitTopDown ==\n");
1730 bool NestingDetected = false;
1731 BBState &MyStates = BBStates[BB];
1733 // Merge the states from each predecessor to compute the initial state
1734 // for the current block.
1735 BBState::edge_iterator PI(MyStates.pred_begin()),
1736 PE(MyStates.pred_end());
1738 const BasicBlock *Pred = *PI;
1739 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
1740 assert(I != BBStates.end());
1741 MyStates.InitFromPred(I->second);
1743 for (; PI != PE; ++PI) {
1745 I = BBStates.find(Pred);
1746 assert(I != BBStates.end());
1747 MyStates.MergePred(I->second);
1751 // If ARC Annotations are enabled, output the current state of pointers at the
1752 // top of the basic block.
1753 ANNOTATE_TOPDOWN_BBSTART(MyStates, BB);
1755 // Visit all the instructions, top-down.
1756 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1757 Instruction *Inst = I;
1759 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
1761 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
1764 // If ARC Annotations are enabled, output the current state of pointers at the
1765 // bottom of the basic block.
1766 ANNOTATE_TOPDOWN_BBEND(MyStates, BB);
1768 #ifdef ARC_ANNOTATIONS
1769 if (!(EnableARCAnnotations && DisableCheckForCFGHazards))
1771 CheckForCFGHazards(BB, BBStates, MyStates);
1772 return NestingDetected;
1776 ComputePostOrders(Function &F,
1777 SmallVectorImpl<BasicBlock *> &PostOrder,
1778 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
1779 unsigned NoObjCARCExceptionsMDKind,
1780 DenseMap<const BasicBlock *, BBState> &BBStates) {
1781 /// The visited set, for doing DFS walks.
1782 SmallPtrSet<BasicBlock *, 16> Visited;
1784 // Do DFS, computing the PostOrder.
1785 SmallPtrSet<BasicBlock *, 16> OnStack;
1786 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
1788 // Functions always have exactly one entry block, and we don't have
1789 // any other block that we treat like an entry block.
1790 BasicBlock *EntryBB = &F.getEntryBlock();
1791 BBState &MyStates = BBStates[EntryBB];
1792 MyStates.SetAsEntry();
1793 TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
1794 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
1795 Visited.insert(EntryBB);
1796 OnStack.insert(EntryBB);
1799 BasicBlock *CurrBB = SuccStack.back().first;
1800 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
1801 succ_iterator SE(TI, false);
1803 while (SuccStack.back().second != SE) {
1804 BasicBlock *SuccBB = *SuccStack.back().second++;
1805 if (Visited.insert(SuccBB).second) {
1806 TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
1807 SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
1808 BBStates[CurrBB].addSucc(SuccBB);
1809 BBState &SuccStates = BBStates[SuccBB];
1810 SuccStates.addPred(CurrBB);
1811 OnStack.insert(SuccBB);
1815 if (!OnStack.count(SuccBB)) {
1816 BBStates[CurrBB].addSucc(SuccBB);
1817 BBStates[SuccBB].addPred(CurrBB);
1820 OnStack.erase(CurrBB);
1821 PostOrder.push_back(CurrBB);
1822 SuccStack.pop_back();
1823 } while (!SuccStack.empty());
1827 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
1828 // Functions may have many exits, and there also blocks which we treat
1829 // as exits due to ignored edges.
1830 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
1831 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
1832 BasicBlock *ExitBB = I;
1833 BBState &MyStates = BBStates[ExitBB];
1834 if (!MyStates.isExit())
1837 MyStates.SetAsExit();
1839 PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
1840 Visited.insert(ExitBB);
1841 while (!PredStack.empty()) {
1842 reverse_dfs_next_succ:
1843 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
1844 while (PredStack.back().second != PE) {
1845 BasicBlock *BB = *PredStack.back().second++;
1846 if (Visited.insert(BB).second) {
1847 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
1848 goto reverse_dfs_next_succ;
1851 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
1856 // Visit the function both top-down and bottom-up.
1857 bool ObjCARCOpt::Visit(Function &F,
1858 DenseMap<const BasicBlock *, BBState> &BBStates,
1859 BlotMapVector<Value *, RRInfo> &Retains,
1860 DenseMap<Value *, RRInfo> &Releases) {
1862 // Use reverse-postorder traversals, because we magically know that loops
1863 // will be well behaved, i.e. they won't repeatedly call retain on a single
1864 // pointer without doing a release. We can't use the ReversePostOrderTraversal
1865 // class here because we want the reverse-CFG postorder to consider each
1866 // function exit point, and we want to ignore selected cycle edges.
1867 SmallVector<BasicBlock *, 16> PostOrder;
1868 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
1869 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
1870 NoObjCARCExceptionsMDKind,
1873 // Use reverse-postorder on the reverse CFG for bottom-up.
1874 bool BottomUpNestingDetected = false;
1875 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
1876 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
1878 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
1880 // Use reverse-postorder for top-down.
1881 bool TopDownNestingDetected = false;
1882 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
1883 PostOrder.rbegin(), E = PostOrder.rend();
1885 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
1887 return TopDownNestingDetected && BottomUpNestingDetected;
1890 /// Move the calls in RetainsToMove and ReleasesToMove.
1891 void ObjCARCOpt::MoveCalls(Value *Arg, RRInfo &RetainsToMove,
1892 RRInfo &ReleasesToMove,
1893 BlotMapVector<Value *, RRInfo> &Retains,
1894 DenseMap<Value *, RRInfo> &Releases,
1895 SmallVectorImpl<Instruction *> &DeadInsts,
1897 Type *ArgTy = Arg->getType();
1898 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
1900 DEBUG(dbgs() << "== ObjCARCOpt::MoveCalls ==\n");
1902 // Insert the new retain and release calls.
1903 for (Instruction *InsertPt : ReleasesToMove.ReverseInsertPts) {
1904 Value *MyArg = ArgTy == ParamTy ? Arg :
1905 new BitCastInst(Arg, ParamTy, "", InsertPt);
1906 Constant *Decl = EP.get(ARCRuntimeEntryPoints::EPT_Retain);
1907 CallInst *Call = CallInst::Create(Decl, MyArg, "", InsertPt);
1908 Call->setDoesNotThrow();
1909 Call->setTailCall();
1911 DEBUG(dbgs() << "Inserting new Retain: " << *Call << "\n"
1912 "At insertion point: " << *InsertPt << "\n");
1914 for (Instruction *InsertPt : RetainsToMove.ReverseInsertPts) {
1915 Value *MyArg = ArgTy == ParamTy ? Arg :
1916 new BitCastInst(Arg, ParamTy, "", InsertPt);
1917 Constant *Decl = EP.get(ARCRuntimeEntryPoints::EPT_Release);
1918 CallInst *Call = CallInst::Create(Decl, MyArg, "", InsertPt);
1919 // Attach a clang.imprecise_release metadata tag, if appropriate.
1920 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
1921 Call->setMetadata(ImpreciseReleaseMDKind, M);
1922 Call->setDoesNotThrow();
1923 if (ReleasesToMove.IsTailCallRelease)
1924 Call->setTailCall();
1926 DEBUG(dbgs() << "Inserting new Release: " << *Call << "\n"
1927 "At insertion point: " << *InsertPt << "\n");
1930 // Delete the original retain and release calls.
1931 for (Instruction *OrigRetain : RetainsToMove.Calls) {
1932 Retains.blot(OrigRetain);
1933 DeadInsts.push_back(OrigRetain);
1934 DEBUG(dbgs() << "Deleting retain: " << *OrigRetain << "\n");
1936 for (Instruction *OrigRelease : ReleasesToMove.Calls) {
1937 Releases.erase(OrigRelease);
1938 DeadInsts.push_back(OrigRelease);
1939 DEBUG(dbgs() << "Deleting release: " << *OrigRelease << "\n");
1944 bool ObjCARCOpt::ConnectTDBUTraversals(
1945 DenseMap<const BasicBlock *, BBState> &BBStates,
1946 BlotMapVector<Value *, RRInfo> &Retains,
1947 DenseMap<Value *, RRInfo> &Releases, Module *M,
1948 SmallVectorImpl<Instruction *> &NewRetains,
1949 SmallVectorImpl<Instruction *> &NewReleases,
1950 SmallVectorImpl<Instruction *> &DeadInsts, RRInfo &RetainsToMove,
1951 RRInfo &ReleasesToMove, Value *Arg, bool KnownSafe,
1952 bool &AnyPairsCompletelyEliminated) {
1953 // If a pair happens in a region where it is known that the reference count
1954 // is already incremented, we can similarly ignore possible decrements unless
1955 // we are dealing with a retainable object with multiple provenance sources.
1956 bool KnownSafeTD = true, KnownSafeBU = true;
1957 bool MultipleOwners = false;
1958 bool CFGHazardAfflicted = false;
1960 // Connect the dots between the top-down-collected RetainsToMove and
1961 // bottom-up-collected ReleasesToMove to form sets of related calls.
1962 // This is an iterative process so that we connect multiple releases
1963 // to multiple retains if needed.
1964 unsigned OldDelta = 0;
1965 unsigned NewDelta = 0;
1966 unsigned OldCount = 0;
1967 unsigned NewCount = 0;
1968 bool FirstRelease = true;
1970 for (SmallVectorImpl<Instruction *>::const_iterator
1971 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
1972 Instruction *NewRetain = *NI;
1973 BlotMapVector<Value *, RRInfo>::const_iterator It =
1974 Retains.find(NewRetain);
1975 assert(It != Retains.end());
1976 const RRInfo &NewRetainRRI = It->second;
1977 KnownSafeTD &= NewRetainRRI.KnownSafe;
1979 MultipleOwners || MultiOwnersSet.count(GetArgRCIdentityRoot(NewRetain));
1980 for (Instruction *NewRetainRelease : NewRetainRRI.Calls) {
1981 DenseMap<Value *, RRInfo>::const_iterator Jt =
1982 Releases.find(NewRetainRelease);
1983 if (Jt == Releases.end())
1985 const RRInfo &NewRetainReleaseRRI = Jt->second;
1987 // If the release does not have a reference to the retain as well,
1988 // something happened which is unaccounted for. Do not do anything.
1990 // This can happen if we catch an additive overflow during path count
1992 if (!NewRetainReleaseRRI.Calls.count(NewRetain))
1995 if (ReleasesToMove.Calls.insert(NewRetainRelease).second) {
1997 // If we overflow when we compute the path count, don't remove/move
1999 const BBState &NRRBBState = BBStates[NewRetainRelease->getParent()];
2000 unsigned PathCount = BBState::OverflowOccurredValue;
2001 if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
2003 assert(PathCount != BBState::OverflowOccurredValue &&
2004 "PathCount at this point can not be "
2005 "OverflowOccurredValue.");
2006 OldDelta -= PathCount;
2008 // Merge the ReleaseMetadata and IsTailCallRelease values.
2010 ReleasesToMove.ReleaseMetadata =
2011 NewRetainReleaseRRI.ReleaseMetadata;
2012 ReleasesToMove.IsTailCallRelease =
2013 NewRetainReleaseRRI.IsTailCallRelease;
2014 FirstRelease = false;
2016 if (ReleasesToMove.ReleaseMetadata !=
2017 NewRetainReleaseRRI.ReleaseMetadata)
2018 ReleasesToMove.ReleaseMetadata = nullptr;
2019 if (ReleasesToMove.IsTailCallRelease !=
2020 NewRetainReleaseRRI.IsTailCallRelease)
2021 ReleasesToMove.IsTailCallRelease = false;
2024 // Collect the optimal insertion points.
2026 for (Instruction *RIP : NewRetainReleaseRRI.ReverseInsertPts) {
2027 if (ReleasesToMove.ReverseInsertPts.insert(RIP).second) {
2028 // If we overflow when we compute the path count, don't
2029 // remove/move anything.
2030 const BBState &RIPBBState = BBStates[RIP->getParent()];
2031 PathCount = BBState::OverflowOccurredValue;
2032 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
2034 assert(PathCount != BBState::OverflowOccurredValue &&
2035 "PathCount at this point can not be "
2036 "OverflowOccurredValue.");
2037 NewDelta -= PathCount;
2040 NewReleases.push_back(NewRetainRelease);
2045 if (NewReleases.empty()) break;
2047 // Back the other way.
2048 for (SmallVectorImpl<Instruction *>::const_iterator
2049 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
2050 Instruction *NewRelease = *NI;
2051 DenseMap<Value *, RRInfo>::const_iterator It =
2052 Releases.find(NewRelease);
2053 assert(It != Releases.end());
2054 const RRInfo &NewReleaseRRI = It->second;
2055 KnownSafeBU &= NewReleaseRRI.KnownSafe;
2056 CFGHazardAfflicted |= NewReleaseRRI.CFGHazardAfflicted;
2057 for (Instruction *NewReleaseRetain : NewReleaseRRI.Calls) {
2058 BlotMapVector<Value *, RRInfo>::const_iterator Jt =
2059 Retains.find(NewReleaseRetain);
2060 if (Jt == Retains.end())
2062 const RRInfo &NewReleaseRetainRRI = Jt->second;
2064 // If the retain does not have a reference to the release as well,
2065 // something happened which is unaccounted for. Do not do anything.
2067 // This can happen if we catch an additive overflow during path count
2069 if (!NewReleaseRetainRRI.Calls.count(NewRelease))
2072 if (RetainsToMove.Calls.insert(NewReleaseRetain).second) {
2073 // If we overflow when we compute the path count, don't remove/move
2075 const BBState &NRRBBState = BBStates[NewReleaseRetain->getParent()];
2076 unsigned PathCount = BBState::OverflowOccurredValue;
2077 if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
2079 assert(PathCount != BBState::OverflowOccurredValue &&
2080 "PathCount at this point can not be "
2081 "OverflowOccurredValue.");
2082 OldDelta += PathCount;
2083 OldCount += PathCount;
2085 // Collect the optimal insertion points.
2087 for (Instruction *RIP : NewReleaseRetainRRI.ReverseInsertPts) {
2088 if (RetainsToMove.ReverseInsertPts.insert(RIP).second) {
2089 // If we overflow when we compute the path count, don't
2090 // remove/move anything.
2091 const BBState &RIPBBState = BBStates[RIP->getParent()];
2093 PathCount = BBState::OverflowOccurredValue;
2094 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
2096 assert(PathCount != BBState::OverflowOccurredValue &&
2097 "PathCount at this point can not be "
2098 "OverflowOccurredValue.");
2099 NewDelta += PathCount;
2100 NewCount += PathCount;
2103 NewRetains.push_back(NewReleaseRetain);
2107 NewReleases.clear();
2108 if (NewRetains.empty()) break;
2111 // If the pointer is known incremented in 1 direction and we do not have
2112 // MultipleOwners, we can safely remove the retain/releases. Otherwise we need
2113 // to be known safe in both directions.
2114 bool UnconditionallySafe = (KnownSafeTD && KnownSafeBU) ||
2115 ((KnownSafeTD || KnownSafeBU) && !MultipleOwners);
2116 if (UnconditionallySafe) {
2117 RetainsToMove.ReverseInsertPts.clear();
2118 ReleasesToMove.ReverseInsertPts.clear();
2121 // Determine whether the new insertion points we computed preserve the
2122 // balance of retain and release calls through the program.
2123 // TODO: If the fully aggressive solution isn't valid, try to find a
2124 // less aggressive solution which is.
2128 // At this point, we are not going to remove any RR pairs, but we still are
2129 // able to move RR pairs. If one of our pointers is afflicted with
2130 // CFGHazards, we cannot perform such code motion so exit early.
2131 const bool WillPerformCodeMotion = RetainsToMove.ReverseInsertPts.size() ||
2132 ReleasesToMove.ReverseInsertPts.size();
2133 if (CFGHazardAfflicted && WillPerformCodeMotion)
2137 // Determine whether the original call points are balanced in the retain and
2138 // release calls through the program. If not, conservatively don't touch
2140 // TODO: It's theoretically possible to do code motion in this case, as
2141 // long as the existing imbalances are maintained.
2145 #ifdef ARC_ANNOTATIONS
2146 // Do not move calls if ARC annotations are requested.
2147 if (EnableARCAnnotations)
2149 #endif // ARC_ANNOTATIONS
2152 assert(OldCount != 0 && "Unreachable code?");
2153 NumRRs += OldCount - NewCount;
2154 // Set to true if we completely removed any RR pairs.
2155 AnyPairsCompletelyEliminated = NewCount == 0;
2157 // We can move calls!
2161 /// Identify pairings between the retains and releases, and delete and/or move
2163 bool ObjCARCOpt::PerformCodePlacement(
2164 DenseMap<const BasicBlock *, BBState> &BBStates,
2165 BlotMapVector<Value *, RRInfo> &Retains,
2166 DenseMap<Value *, RRInfo> &Releases, Module *M) {
2167 DEBUG(dbgs() << "\n== ObjCARCOpt::PerformCodePlacement ==\n");
2169 bool AnyPairsCompletelyEliminated = false;
2170 RRInfo RetainsToMove;
2171 RRInfo ReleasesToMove;
2172 SmallVector<Instruction *, 4> NewRetains;
2173 SmallVector<Instruction *, 4> NewReleases;
2174 SmallVector<Instruction *, 8> DeadInsts;
2176 // Visit each retain.
2177 for (BlotMapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
2180 Value *V = I->first;
2181 if (!V) continue; // blotted
2183 Instruction *Retain = cast<Instruction>(V);
2185 DEBUG(dbgs() << "Visiting: " << *Retain << "\n");
2187 Value *Arg = GetArgRCIdentityRoot(Retain);
2189 // If the object being released is in static or stack storage, we know it's
2190 // not being managed by ObjC reference counting, so we can delete pairs
2191 // regardless of what possible decrements or uses lie between them.
2192 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
2194 // A constant pointer can't be pointing to an object on the heap. It may
2195 // be reference-counted, but it won't be deleted.
2196 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
2197 if (const GlobalVariable *GV =
2198 dyn_cast<GlobalVariable>(
2199 GetRCIdentityRoot(LI->getPointerOperand())))
2200 if (GV->isConstant())
2203 // Connect the dots between the top-down-collected RetainsToMove and
2204 // bottom-up-collected ReleasesToMove to form sets of related calls.
2205 NewRetains.push_back(Retain);
2206 bool PerformMoveCalls =
2207 ConnectTDBUTraversals(BBStates, Retains, Releases, M, NewRetains,
2208 NewReleases, DeadInsts, RetainsToMove,
2209 ReleasesToMove, Arg, KnownSafe,
2210 AnyPairsCompletelyEliminated);
2212 if (PerformMoveCalls) {
2213 // Ok, everything checks out and we're all set. Let's move/delete some
2215 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
2216 Retains, Releases, DeadInsts, M);
2219 // Clean up state for next retain.
2220 NewReleases.clear();
2222 RetainsToMove.clear();
2223 ReleasesToMove.clear();
2226 // Now that we're done moving everything, we can delete the newly dead
2227 // instructions, as we no longer need them as insert points.
2228 while (!DeadInsts.empty())
2229 EraseInstruction(DeadInsts.pop_back_val());
2231 return AnyPairsCompletelyEliminated;
2234 /// Weak pointer optimizations.
2235 void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
2236 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeWeakCalls ==\n");
2238 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
2239 // itself because it uses AliasAnalysis and we need to do provenance
2241 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2242 Instruction *Inst = &*I++;
2244 DEBUG(dbgs() << "Visiting: " << *Inst << "\n");
2246 ARCInstKind Class = GetBasicARCInstKind(Inst);
2247 if (Class != ARCInstKind::LoadWeak &&
2248 Class != ARCInstKind::LoadWeakRetained)
2251 // Delete objc_loadWeak calls with no users.
2252 if (Class == ARCInstKind::LoadWeak && Inst->use_empty()) {
2253 Inst->eraseFromParent();
2257 // TODO: For now, just look for an earlier available version of this value
2258 // within the same block. Theoretically, we could do memdep-style non-local
2259 // analysis too, but that would want caching. A better approach would be to
2260 // use the technique that EarlyCSE uses.
2261 inst_iterator Current = std::prev(I);
2262 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
2263 for (BasicBlock::iterator B = CurrentBB->begin(),
2264 J = Current.getInstructionIterator();
2266 Instruction *EarlierInst = &*std::prev(J);
2267 ARCInstKind EarlierClass = GetARCInstKind(EarlierInst);
2268 switch (EarlierClass) {
2269 case ARCInstKind::LoadWeak:
2270 case ARCInstKind::LoadWeakRetained: {
2271 // If this is loading from the same pointer, replace this load's value
2273 CallInst *Call = cast<CallInst>(Inst);
2274 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2275 Value *Arg = Call->getArgOperand(0);
2276 Value *EarlierArg = EarlierCall->getArgOperand(0);
2277 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2278 case AliasAnalysis::MustAlias:
2280 // If the load has a builtin retain, insert a plain retain for it.
2281 if (Class == ARCInstKind::LoadWeakRetained) {
2282 Constant *Decl = EP.get(ARCRuntimeEntryPoints::EPT_Retain);
2283 CallInst *CI = CallInst::Create(Decl, EarlierCall, "", Call);
2286 // Zap the fully redundant load.
2287 Call->replaceAllUsesWith(EarlierCall);
2288 Call->eraseFromParent();
2290 case AliasAnalysis::MayAlias:
2291 case AliasAnalysis::PartialAlias:
2293 case AliasAnalysis::NoAlias:
2298 case ARCInstKind::StoreWeak:
2299 case ARCInstKind::InitWeak: {
2300 // If this is storing to the same pointer and has the same size etc.
2301 // replace this load's value with the stored value.
2302 CallInst *Call = cast<CallInst>(Inst);
2303 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2304 Value *Arg = Call->getArgOperand(0);
2305 Value *EarlierArg = EarlierCall->getArgOperand(0);
2306 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2307 case AliasAnalysis::MustAlias:
2309 // If the load has a builtin retain, insert a plain retain for it.
2310 if (Class == ARCInstKind::LoadWeakRetained) {
2311 Constant *Decl = EP.get(ARCRuntimeEntryPoints::EPT_Retain);
2312 CallInst *CI = CallInst::Create(Decl, EarlierCall, "", Call);
2315 // Zap the fully redundant load.
2316 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
2317 Call->eraseFromParent();
2319 case AliasAnalysis::MayAlias:
2320 case AliasAnalysis::PartialAlias:
2322 case AliasAnalysis::NoAlias:
2327 case ARCInstKind::MoveWeak:
2328 case ARCInstKind::CopyWeak:
2329 // TOOD: Grab the copied value.
2331 case ARCInstKind::AutoreleasepoolPush:
2332 case ARCInstKind::None:
2333 case ARCInstKind::IntrinsicUser:
2334 case ARCInstKind::User:
2335 // Weak pointers are only modified through the weak entry points
2336 // (and arbitrary calls, which could call the weak entry points).
2339 // Anything else could modify the weak pointer.
2346 // Then, for each destroyWeak with an alloca operand, check to see if
2347 // the alloca and all its users can be zapped.
2348 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2349 Instruction *Inst = &*I++;
2350 ARCInstKind Class = GetBasicARCInstKind(Inst);
2351 if (Class != ARCInstKind::DestroyWeak)
2354 CallInst *Call = cast<CallInst>(Inst);
2355 Value *Arg = Call->getArgOperand(0);
2356 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
2357 for (User *U : Alloca->users()) {
2358 const Instruction *UserInst = cast<Instruction>(U);
2359 switch (GetBasicARCInstKind(UserInst)) {
2360 case ARCInstKind::InitWeak:
2361 case ARCInstKind::StoreWeak:
2362 case ARCInstKind::DestroyWeak:
2369 for (auto UI = Alloca->user_begin(), UE = Alloca->user_end(); UI != UE;) {
2370 CallInst *UserInst = cast<CallInst>(*UI++);
2371 switch (GetBasicARCInstKind(UserInst)) {
2372 case ARCInstKind::InitWeak:
2373 case ARCInstKind::StoreWeak:
2374 // These functions return their second argument.
2375 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
2377 case ARCInstKind::DestroyWeak:
2381 llvm_unreachable("alloca really is used!");
2383 UserInst->eraseFromParent();
2385 Alloca->eraseFromParent();
2391 /// Identify program paths which execute sequences of retains and releases which
2392 /// can be eliminated.
2393 bool ObjCARCOpt::OptimizeSequences(Function &F) {
2394 // Releases, Retains - These are used to store the results of the main flow
2395 // analysis. These use Value* as the key instead of Instruction* so that the
2396 // map stays valid when we get around to rewriting code and calls get
2397 // replaced by arguments.
2398 DenseMap<Value *, RRInfo> Releases;
2399 BlotMapVector<Value *, RRInfo> Retains;
2401 // This is used during the traversal of the function to track the
2402 // states for each identified object at each block.
2403 DenseMap<const BasicBlock *, BBState> BBStates;
2405 // Analyze the CFG of the function, and all instructions.
2406 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
2409 bool AnyPairsCompletelyEliminated = PerformCodePlacement(BBStates, Retains,
2414 MultiOwnersSet.clear();
2416 return AnyPairsCompletelyEliminated && NestingDetected;
2419 /// Check if there is a dependent call earlier that does not have anything in
2420 /// between the Retain and the call that can affect the reference count of their
2421 /// shared pointer argument. Note that Retain need not be in BB.
2423 HasSafePathToPredecessorCall(const Value *Arg, Instruction *Retain,
2424 SmallPtrSetImpl<Instruction *> &DepInsts,
2425 SmallPtrSetImpl<const BasicBlock *> &Visited,
2426 ProvenanceAnalysis &PA) {
2427 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
2428 DepInsts, Visited, PA);
2429 if (DepInsts.size() != 1)
2432 auto *Call = dyn_cast_or_null<CallInst>(*DepInsts.begin());
2434 // Check that the pointer is the return value of the call.
2435 if (!Call || Arg != Call)
2438 // Check that the call is a regular call.
2439 ARCInstKind Class = GetBasicARCInstKind(Call);
2440 if (Class != ARCInstKind::CallOrUser && Class != ARCInstKind::Call)
2446 /// Find a dependent retain that precedes the given autorelease for which there
2447 /// is nothing in between the two instructions that can affect the ref count of
2450 FindPredecessorRetainWithSafePath(const Value *Arg, BasicBlock *BB,
2451 Instruction *Autorelease,
2452 SmallPtrSetImpl<Instruction *> &DepInsts,
2453 SmallPtrSetImpl<const BasicBlock *> &Visited,
2454 ProvenanceAnalysis &PA) {
2455 FindDependencies(CanChangeRetainCount, Arg,
2456 BB, Autorelease, DepInsts, Visited, PA);
2457 if (DepInsts.size() != 1)
2460 auto *Retain = dyn_cast_or_null<CallInst>(*DepInsts.begin());
2462 // Check that we found a retain with the same argument.
2463 if (!Retain || !IsRetain(GetBasicARCInstKind(Retain)) ||
2464 GetArgRCIdentityRoot(Retain) != Arg) {
2471 /// Look for an ``autorelease'' instruction dependent on Arg such that there are
2472 /// no instructions dependent on Arg that need a positive ref count in between
2473 /// the autorelease and the ret.
2475 FindPredecessorAutoreleaseWithSafePath(const Value *Arg, BasicBlock *BB,
2477 SmallPtrSetImpl<Instruction *> &DepInsts,
2478 SmallPtrSetImpl<const BasicBlock *> &V,
2479 ProvenanceAnalysis &PA) {
2480 FindDependencies(NeedsPositiveRetainCount, Arg,
2481 BB, Ret, DepInsts, V, PA);
2482 if (DepInsts.size() != 1)
2485 auto *Autorelease = dyn_cast_or_null<CallInst>(*DepInsts.begin());
2488 ARCInstKind AutoreleaseClass = GetBasicARCInstKind(Autorelease);
2489 if (!IsAutorelease(AutoreleaseClass))
2491 if (GetArgRCIdentityRoot(Autorelease) != Arg)
2497 /// Look for this pattern:
2499 /// %call = call i8* @something(...)
2500 /// %2 = call i8* @objc_retain(i8* %call)
2501 /// %3 = call i8* @objc_autorelease(i8* %2)
2504 /// And delete the retain and autorelease.
2505 void ObjCARCOpt::OptimizeReturns(Function &F) {
2506 if (!F.getReturnType()->isPointerTy())
2509 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeReturns ==\n");
2511 SmallPtrSet<Instruction *, 4> DependingInstructions;
2512 SmallPtrSet<const BasicBlock *, 4> Visited;
2513 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
2514 BasicBlock *BB = FI;
2515 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
2517 DEBUG(dbgs() << "Visiting: " << *Ret << "\n");
2522 const Value *Arg = GetRCIdentityRoot(Ret->getOperand(0));
2524 // Look for an ``autorelease'' instruction that is a predecessor of Ret and
2525 // dependent on Arg such that there are no instructions dependent on Arg
2526 // that need a positive ref count in between the autorelease and Ret.
2527 CallInst *Autorelease =
2528 FindPredecessorAutoreleaseWithSafePath(Arg, BB, Ret,
2529 DependingInstructions, Visited,
2531 DependingInstructions.clear();
2538 FindPredecessorRetainWithSafePath(Arg, BB, Autorelease,
2539 DependingInstructions, Visited, PA);
2540 DependingInstructions.clear();
2546 // Check that there is nothing that can affect the reference count
2547 // between the retain and the call. Note that Retain need not be in BB.
2548 bool HasSafePathToCall = HasSafePathToPredecessorCall(Arg, Retain,
2549 DependingInstructions,
2551 DependingInstructions.clear();
2554 if (!HasSafePathToCall)
2557 // If so, we can zap the retain and autorelease.
2560 DEBUG(dbgs() << "Erasing: " << *Retain << "\nErasing: "
2561 << *Autorelease << "\n");
2562 EraseInstruction(Retain);
2563 EraseInstruction(Autorelease);
2569 ObjCARCOpt::GatherStatistics(Function &F, bool AfterOptimization) {
2570 llvm::Statistic &NumRetains =
2571 AfterOptimization? NumRetainsAfterOpt : NumRetainsBeforeOpt;
2572 llvm::Statistic &NumReleases =
2573 AfterOptimization? NumReleasesAfterOpt : NumReleasesBeforeOpt;
2575 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2576 Instruction *Inst = &*I++;
2577 switch (GetBasicARCInstKind(Inst)) {
2580 case ARCInstKind::Retain:
2583 case ARCInstKind::Release:
2591 bool ObjCARCOpt::doInitialization(Module &M) {
2595 // If nothing in the Module uses ARC, don't do anything.
2596 Run = ModuleHasARC(M);
2600 // Identify the imprecise release metadata kind.
2601 ImpreciseReleaseMDKind =
2602 M.getContext().getMDKindID("clang.imprecise_release");
2603 CopyOnEscapeMDKind =
2604 M.getContext().getMDKindID("clang.arc.copy_on_escape");
2605 NoObjCARCExceptionsMDKind =
2606 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
2607 #ifdef ARC_ANNOTATIONS
2608 ARCAnnotationBottomUpMDKind =
2609 M.getContext().getMDKindID("llvm.arc.annotation.bottomup");
2610 ARCAnnotationTopDownMDKind =
2611 M.getContext().getMDKindID("llvm.arc.annotation.topdown");
2612 ARCAnnotationProvenanceSourceMDKind =
2613 M.getContext().getMDKindID("llvm.arc.annotation.provenancesource");
2614 #endif // ARC_ANNOTATIONS
2616 // Intuitively, objc_retain and others are nocapture, however in practice
2617 // they are not, because they return their argument value. And objc_release
2618 // calls finalizers which can have arbitrary side effects.
2620 // Initialize our runtime entry point cache.
2626 bool ObjCARCOpt::runOnFunction(Function &F) {
2630 // If nothing in the Module uses ARC, don't do anything.
2636 DEBUG(dbgs() << "<<< ObjCARCOpt: Visiting Function: " << F.getName() << " >>>"
2639 PA.setAA(&getAnalysis<AliasAnalysis>());
2642 if (AreStatisticsEnabled()) {
2643 GatherStatistics(F, false);
2647 // This pass performs several distinct transformations. As a compile-time aid
2648 // when compiling code that isn't ObjC, skip these if the relevant ObjC
2649 // library functions aren't declared.
2651 // Preliminary optimizations. This also computes UsedInThisFunction.
2652 OptimizeIndividualCalls(F);
2654 // Optimizations for weak pointers.
2655 if (UsedInThisFunction & ((1 << unsigned(ARCInstKind::LoadWeak)) |
2656 (1 << unsigned(ARCInstKind::LoadWeakRetained)) |
2657 (1 << unsigned(ARCInstKind::StoreWeak)) |
2658 (1 << unsigned(ARCInstKind::InitWeak)) |
2659 (1 << unsigned(ARCInstKind::CopyWeak)) |
2660 (1 << unsigned(ARCInstKind::MoveWeak)) |
2661 (1 << unsigned(ARCInstKind::DestroyWeak))))
2662 OptimizeWeakCalls(F);
2664 // Optimizations for retain+release pairs.
2665 if (UsedInThisFunction & ((1 << unsigned(ARCInstKind::Retain)) |
2666 (1 << unsigned(ARCInstKind::RetainRV)) |
2667 (1 << unsigned(ARCInstKind::RetainBlock))))
2668 if (UsedInThisFunction & (1 << unsigned(ARCInstKind::Release)))
2669 // Run OptimizeSequences until it either stops making changes or
2670 // no retain+release pair nesting is detected.
2671 while (OptimizeSequences(F)) {}
2673 // Optimizations if objc_autorelease is used.
2674 if (UsedInThisFunction & ((1 << unsigned(ARCInstKind::Autorelease)) |
2675 (1 << unsigned(ARCInstKind::AutoreleaseRV))))
2678 // Gather statistics after optimization.
2680 if (AreStatisticsEnabled()) {
2681 GatherStatistics(F, true);
2685 DEBUG(dbgs() << "\n");
2690 void ObjCARCOpt::releaseMemory() {