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 const DataLayout &DL) {
88 SmallPtrSet<const Value *, 4> Visited;
89 SmallVector<const Value *, 4> Worklist;
90 Worklist.push_back(V);
92 const Value *P = Worklist.pop_back_val();
93 P = GetUnderlyingObjCPtr(P, DL);
95 if (isa<AllocaInst>(P))
98 if (!Visited.insert(P).second)
101 if (const SelectInst *SI = dyn_cast<const SelectInst>(P)) {
102 Worklist.push_back(SI->getTrueValue());
103 Worklist.push_back(SI->getFalseValue());
107 if (const PHINode *PN = dyn_cast<const PHINode>(P)) {
108 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
109 Worklist.push_back(PN->getIncomingValue(i));
112 } while (!Worklist.empty());
120 /// \defgroup ARCOpt ARC Optimization.
123 // TODO: On code like this:
126 // stuff_that_cannot_release()
127 // objc_autorelease(%x)
128 // stuff_that_cannot_release()
130 // stuff_that_cannot_release()
131 // objc_autorelease(%x)
133 // The second retain and autorelease can be deleted.
135 // TODO: It should be possible to delete
136 // objc_autoreleasePoolPush and objc_autoreleasePoolPop
137 // pairs if nothing is actually autoreleased between them. Also, autorelease
138 // calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
139 // after inlining) can be turned into plain release calls.
141 // TODO: Critical-edge splitting. If the optimial insertion point is
142 // a critical edge, the current algorithm has to fail, because it doesn't
143 // know how to split edges. It should be possible to make the optimizer
144 // think in terms of edges, rather than blocks, and then split critical
147 // TODO: OptimizeSequences could generalized to be Interprocedural.
149 // TODO: Recognize that a bunch of other objc runtime calls have
150 // non-escaping arguments and non-releasing arguments, and may be
151 // non-autoreleasing.
153 // TODO: Sink autorelease calls as far as possible. Unfortunately we
154 // usually can't sink them past other calls, which would be the main
155 // case where it would be useful.
157 // TODO: The pointer returned from objc_loadWeakRetained is retained.
159 // TODO: Delete release+retain pairs (rare).
161 STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
162 STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
163 STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
164 STATISTIC(NumRets, "Number of return value forwarding "
165 "retain+autoreleases eliminated");
166 STATISTIC(NumRRs, "Number of retain+release paths eliminated");
167 STATISTIC(NumPeeps, "Number of calls peephole-optimized");
169 STATISTIC(NumRetainsBeforeOpt,
170 "Number of retains before optimization");
171 STATISTIC(NumReleasesBeforeOpt,
172 "Number of releases before optimization");
173 STATISTIC(NumRetainsAfterOpt,
174 "Number of retains after optimization");
175 STATISTIC(NumReleasesAfterOpt,
176 "Number of releases after optimization");
180 /// \brief Per-BasicBlock state.
182 /// The number of unique control paths from the entry which can reach this
184 unsigned TopDownPathCount;
186 /// The number of unique control paths to exits from this block.
187 unsigned BottomUpPathCount;
189 /// The top-down traversal uses this to record information known about a
190 /// pointer at the bottom of each block.
191 BlotMapVector<const Value *, TopDownPtrState> PerPtrTopDown;
193 /// The bottom-up traversal uses this to record information known about a
194 /// pointer at the top of each block.
195 BlotMapVector<const Value *, BottomUpPtrState> PerPtrBottomUp;
197 /// Effective predecessors of the current block ignoring ignorable edges and
198 /// ignored backedges.
199 SmallVector<BasicBlock *, 2> Preds;
201 /// Effective successors of the current block ignoring ignorable edges and
202 /// ignored backedges.
203 SmallVector<BasicBlock *, 2> Succs;
206 static const unsigned OverflowOccurredValue;
208 BBState() : TopDownPathCount(0), BottomUpPathCount(0) { }
210 typedef decltype(PerPtrTopDown)::iterator top_down_ptr_iterator;
211 typedef decltype(PerPtrTopDown)::const_iterator const_top_down_ptr_iterator;
213 top_down_ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
214 top_down_ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
215 const_top_down_ptr_iterator top_down_ptr_begin() const {
216 return PerPtrTopDown.begin();
218 const_top_down_ptr_iterator top_down_ptr_end() const {
219 return PerPtrTopDown.end();
222 typedef decltype(PerPtrBottomUp)::iterator bottom_up_ptr_iterator;
224 PerPtrBottomUp)::const_iterator const_bottom_up_ptr_iterator;
226 bottom_up_ptr_iterator bottom_up_ptr_begin() {
227 return PerPtrBottomUp.begin();
229 bottom_up_ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
230 const_bottom_up_ptr_iterator bottom_up_ptr_begin() const {
231 return PerPtrBottomUp.begin();
233 const_bottom_up_ptr_iterator bottom_up_ptr_end() const {
234 return PerPtrBottomUp.end();
237 /// Mark this block as being an entry block, which has one path from the
238 /// entry by definition.
239 void SetAsEntry() { TopDownPathCount = 1; }
241 /// Mark this block as being an exit block, which has one path to an exit by
243 void SetAsExit() { BottomUpPathCount = 1; }
245 /// Attempt to find the PtrState object describing the top down state for
246 /// pointer Arg. Return a new initialized PtrState describing the top down
247 /// state for Arg if we do not find one.
248 TopDownPtrState &getPtrTopDownState(const Value *Arg) {
249 return PerPtrTopDown[Arg];
252 /// Attempt to find the PtrState object describing the bottom up state for
253 /// pointer Arg. Return a new initialized PtrState describing the bottom up
254 /// state for Arg if we do not find one.
255 BottomUpPtrState &getPtrBottomUpState(const Value *Arg) {
256 return PerPtrBottomUp[Arg];
259 /// Attempt to find the PtrState object describing the bottom up state for
261 bottom_up_ptr_iterator findPtrBottomUpState(const Value *Arg) {
262 return PerPtrBottomUp.find(Arg);
265 void clearBottomUpPointers() {
266 PerPtrBottomUp.clear();
269 void clearTopDownPointers() {
270 PerPtrTopDown.clear();
273 void InitFromPred(const BBState &Other);
274 void InitFromSucc(const BBState &Other);
275 void MergePred(const BBState &Other);
276 void MergeSucc(const BBState &Other);
278 /// Compute the number of possible unique paths from an entry to an exit
279 /// which pass through this block. This is only valid after both the
280 /// top-down and bottom-up traversals are complete.
282 /// Returns true if overflow occurred. Returns false if overflow did not
284 bool GetAllPathCountWithOverflow(unsigned &PathCount) const {
285 if (TopDownPathCount == OverflowOccurredValue ||
286 BottomUpPathCount == OverflowOccurredValue)
288 unsigned long long Product =
289 (unsigned long long)TopDownPathCount*BottomUpPathCount;
290 // Overflow occurred if any of the upper bits of Product are set or if all
291 // the lower bits of Product are all set.
292 return (Product >> 32) ||
293 ((PathCount = Product) == OverflowOccurredValue);
296 // Specialized CFG utilities.
297 typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
298 edge_iterator pred_begin() const { return Preds.begin(); }
299 edge_iterator pred_end() const { return Preds.end(); }
300 edge_iterator succ_begin() const { return Succs.begin(); }
301 edge_iterator succ_end() const { return Succs.end(); }
303 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
304 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
306 bool isExit() const { return Succs.empty(); }
309 const unsigned BBState::OverflowOccurredValue = 0xffffffff;
312 void BBState::InitFromPred(const BBState &Other) {
313 PerPtrTopDown = Other.PerPtrTopDown;
314 TopDownPathCount = Other.TopDownPathCount;
317 void BBState::InitFromSucc(const BBState &Other) {
318 PerPtrBottomUp = Other.PerPtrBottomUp;
319 BottomUpPathCount = Other.BottomUpPathCount;
322 /// The top-down traversal uses this to merge information about predecessors to
323 /// form the initial state for a new block.
324 void BBState::MergePred(const BBState &Other) {
325 if (TopDownPathCount == OverflowOccurredValue)
328 // Other.TopDownPathCount can be 0, in which case it is either dead or a
329 // loop backedge. Loop backedges are special.
330 TopDownPathCount += Other.TopDownPathCount;
332 // In order to be consistent, we clear the top down pointers when by adding
333 // TopDownPathCount becomes OverflowOccurredValue even though "true" overflow
335 if (TopDownPathCount == OverflowOccurredValue) {
336 clearTopDownPointers();
340 // Check for overflow. If we have overflow, fall back to conservative
342 if (TopDownPathCount < Other.TopDownPathCount) {
343 TopDownPathCount = OverflowOccurredValue;
344 clearTopDownPointers();
348 // For each entry in the other set, if our set has an entry with the same key,
349 // merge the entries. Otherwise, copy the entry and merge it with an empty
351 for (auto MI = Other.top_down_ptr_begin(), ME = Other.top_down_ptr_end();
353 auto Pair = PerPtrTopDown.insert(*MI);
354 Pair.first->second.Merge(Pair.second ? TopDownPtrState() : MI->second,
358 // For each entry in our set, if the other set doesn't have an entry with the
359 // same key, force it to merge with an empty entry.
360 for (auto MI = top_down_ptr_begin(), ME = top_down_ptr_end(); MI != ME; ++MI)
361 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
362 MI->second.Merge(TopDownPtrState(), /*TopDown=*/true);
365 /// The bottom-up traversal uses this to merge information about successors to
366 /// form the initial state for a new block.
367 void BBState::MergeSucc(const BBState &Other) {
368 if (BottomUpPathCount == OverflowOccurredValue)
371 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
372 // loop backedge. Loop backedges are special.
373 BottomUpPathCount += Other.BottomUpPathCount;
375 // In order to be consistent, we clear the top down pointers when by adding
376 // BottomUpPathCount becomes OverflowOccurredValue even though "true" overflow
378 if (BottomUpPathCount == OverflowOccurredValue) {
379 clearBottomUpPointers();
383 // Check for overflow. If we have overflow, fall back to conservative
385 if (BottomUpPathCount < Other.BottomUpPathCount) {
386 BottomUpPathCount = OverflowOccurredValue;
387 clearBottomUpPointers();
391 // For each entry in the other set, if our set has an entry with the
392 // same key, merge the entries. Otherwise, copy the entry and merge
393 // it with an empty entry.
394 for (auto MI = Other.bottom_up_ptr_begin(), ME = Other.bottom_up_ptr_end();
396 auto Pair = PerPtrBottomUp.insert(*MI);
397 Pair.first->second.Merge(Pair.second ? BottomUpPtrState() : MI->second,
401 // For each entry in our set, if the other set doesn't have an entry
402 // with the same key, force it to merge with an empty entry.
403 for (auto MI = bottom_up_ptr_begin(), ME = bottom_up_ptr_end(); MI != ME;
405 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
406 MI->second.Merge(BottomUpPtrState(), /*TopDown=*/false);
411 /// \brief The main ARC optimization pass.
412 class ObjCARCOpt : public FunctionPass {
414 ProvenanceAnalysis PA;
416 /// A cache of references to runtime entry point constants.
417 ARCRuntimeEntryPoints EP;
419 /// A cache of MDKinds that can be passed into other functions to propagate
420 /// MDKind identifiers.
421 ARCMDKindCache MDKindCache;
423 // This is used to track if a pointer is stored into an alloca.
424 DenseSet<const Value *> MultiOwnersSet;
426 /// A flag indicating whether this optimization pass should run.
429 /// Flags which determine whether each of the interesting runtine functions
430 /// is in fact used in the current function.
431 unsigned UsedInThisFunction;
433 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
434 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
436 void OptimizeIndividualCalls(Function &F);
438 void CheckForCFGHazards(const BasicBlock *BB,
439 DenseMap<const BasicBlock *, BBState> &BBStates,
440 BBState &MyStates) const;
441 bool VisitInstructionBottomUp(Instruction *Inst, BasicBlock *BB,
442 BlotMapVector<Value *, RRInfo> &Retains,
444 bool VisitBottomUp(BasicBlock *BB,
445 DenseMap<const BasicBlock *, BBState> &BBStates,
446 BlotMapVector<Value *, RRInfo> &Retains);
447 bool VisitInstructionTopDown(Instruction *Inst,
448 DenseMap<Value *, RRInfo> &Releases,
450 bool VisitTopDown(BasicBlock *BB,
451 DenseMap<const BasicBlock *, BBState> &BBStates,
452 DenseMap<Value *, RRInfo> &Releases);
453 bool Visit(Function &F, DenseMap<const BasicBlock *, BBState> &BBStates,
454 BlotMapVector<Value *, RRInfo> &Retains,
455 DenseMap<Value *, RRInfo> &Releases);
457 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
458 BlotMapVector<Value *, RRInfo> &Retains,
459 DenseMap<Value *, RRInfo> &Releases,
460 SmallVectorImpl<Instruction *> &DeadInsts, Module *M);
463 PairUpRetainsAndReleases(DenseMap<const BasicBlock *, BBState> &BBStates,
464 BlotMapVector<Value *, RRInfo> &Retains,
465 DenseMap<Value *, RRInfo> &Releases, Module *M,
466 SmallVectorImpl<Instruction *> &NewRetains,
467 SmallVectorImpl<Instruction *> &NewReleases,
468 SmallVectorImpl<Instruction *> &DeadInsts,
469 RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
470 Value *Arg, bool KnownSafe,
471 bool &AnyPairsCompletelyEliminated);
473 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
474 BlotMapVector<Value *, RRInfo> &Retains,
475 DenseMap<Value *, RRInfo> &Releases, Module *M);
477 void OptimizeWeakCalls(Function &F);
479 bool OptimizeSequences(Function &F);
481 void OptimizeReturns(Function &F);
484 void GatherStatistics(Function &F, bool AfterOptimization = false);
487 void getAnalysisUsage(AnalysisUsage &AU) const override;
488 bool doInitialization(Module &M) override;
489 bool runOnFunction(Function &F) override;
490 void releaseMemory() override;
494 ObjCARCOpt() : FunctionPass(ID) {
495 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
500 char ObjCARCOpt::ID = 0;
501 INITIALIZE_PASS_BEGIN(ObjCARCOpt,
502 "objc-arc", "ObjC ARC optimization", false, false)
503 INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
504 INITIALIZE_PASS_END(ObjCARCOpt,
505 "objc-arc", "ObjC ARC optimization", false, false)
507 Pass *llvm::createObjCARCOptPass() {
508 return new ObjCARCOpt();
511 void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
512 AU.addRequired<ObjCARCAliasAnalysis>();
513 AU.addRequired<AliasAnalysis>();
514 // ARC optimization doesn't currently split critical edges.
515 AU.setPreservesCFG();
518 /// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is
519 /// not a return value. Or, if it can be paired with an
520 /// objc_autoreleaseReturnValue, delete the pair and return true.
522 ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
523 // Check for the argument being from an immediately preceding call or invoke.
524 const Value *Arg = GetArgRCIdentityRoot(RetainRV);
525 ImmutableCallSite CS(Arg);
526 if (const Instruction *Call = CS.getInstruction()) {
527 if (Call->getParent() == RetainRV->getParent()) {
528 BasicBlock::const_iterator I = Call;
530 while (IsNoopInstruction(I)) ++I;
533 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
534 BasicBlock *RetainRVParent = RetainRV->getParent();
535 if (II->getNormalDest() == RetainRVParent) {
536 BasicBlock::const_iterator I = RetainRVParent->begin();
537 while (IsNoopInstruction(I)) ++I;
544 // Check for being preceded by an objc_autoreleaseReturnValue on the same
545 // pointer. In this case, we can delete the pair.
546 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
548 do --I; while (I != Begin && IsNoopInstruction(I));
549 if (GetBasicARCInstKind(I) == ARCInstKind::AutoreleaseRV &&
550 GetArgRCIdentityRoot(I) == Arg) {
554 DEBUG(dbgs() << "Erasing autoreleaseRV,retainRV pair: " << *I << "\n"
555 << "Erasing " << *RetainRV << "\n");
558 EraseInstruction(RetainRV);
563 // Turn it to a plain objc_retain.
567 DEBUG(dbgs() << "Transforming objc_retainAutoreleasedReturnValue => "
568 "objc_retain since the operand is not a return value.\n"
569 "Old = " << *RetainRV << "\n");
571 Constant *NewDecl = EP.get(ARCRuntimeEntryPointKind::Retain);
572 cast<CallInst>(RetainRV)->setCalledFunction(NewDecl);
574 DEBUG(dbgs() << "New = " << *RetainRV << "\n");
579 /// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not
580 /// used as a return value.
581 void ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F,
582 Instruction *AutoreleaseRV,
583 ARCInstKind &Class) {
584 // Check for a return of the pointer value.
585 const Value *Ptr = GetArgRCIdentityRoot(AutoreleaseRV);
586 SmallVector<const Value *, 2> Users;
587 Users.push_back(Ptr);
589 Ptr = Users.pop_back_val();
590 for (const User *U : Ptr->users()) {
591 if (isa<ReturnInst>(U) || GetBasicARCInstKind(U) == ARCInstKind::RetainRV)
593 if (isa<BitCastInst>(U))
596 } while (!Users.empty());
601 DEBUG(dbgs() << "Transforming objc_autoreleaseReturnValue => "
602 "objc_autorelease since its operand is not used as a return "
604 "Old = " << *AutoreleaseRV << "\n");
606 CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
607 Constant *NewDecl = EP.get(ARCRuntimeEntryPointKind::Autorelease);
608 AutoreleaseRVCI->setCalledFunction(NewDecl);
609 AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
610 Class = ARCInstKind::Autorelease;
612 DEBUG(dbgs() << "New: " << *AutoreleaseRV << "\n");
616 /// Visit each call, one at a time, and make simplifications without doing any
617 /// additional analysis.
618 void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
619 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeIndividualCalls ==\n");
620 // Reset all the flags in preparation for recomputing them.
621 UsedInThisFunction = 0;
623 // Visit all objc_* calls in F.
624 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
625 Instruction *Inst = &*I++;
627 ARCInstKind Class = GetBasicARCInstKind(Inst);
629 DEBUG(dbgs() << "Visiting: Class: " << Class << "; " << *Inst << "\n");
634 // Delete no-op casts. These function calls have special semantics, but
635 // the semantics are entirely implemented via lowering in the front-end,
636 // so by the time they reach the optimizer, they are just no-op calls
637 // which return their argument.
639 // There are gray areas here, as the ability to cast reference-counted
640 // pointers to raw void* and back allows code to break ARC assumptions,
641 // however these are currently considered to be unimportant.
642 case ARCInstKind::NoopCast:
645 DEBUG(dbgs() << "Erasing no-op cast: " << *Inst << "\n");
646 EraseInstruction(Inst);
649 // If the pointer-to-weak-pointer is null, it's undefined behavior.
650 case ARCInstKind::StoreWeak:
651 case ARCInstKind::LoadWeak:
652 case ARCInstKind::LoadWeakRetained:
653 case ARCInstKind::InitWeak:
654 case ARCInstKind::DestroyWeak: {
655 CallInst *CI = cast<CallInst>(Inst);
656 if (IsNullOrUndef(CI->getArgOperand(0))) {
658 Type *Ty = CI->getArgOperand(0)->getType();
659 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
660 Constant::getNullValue(Ty),
662 llvm::Value *NewValue = UndefValue::get(CI->getType());
663 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
664 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
665 CI->replaceAllUsesWith(NewValue);
666 CI->eraseFromParent();
671 case ARCInstKind::CopyWeak:
672 case ARCInstKind::MoveWeak: {
673 CallInst *CI = cast<CallInst>(Inst);
674 if (IsNullOrUndef(CI->getArgOperand(0)) ||
675 IsNullOrUndef(CI->getArgOperand(1))) {
677 Type *Ty = CI->getArgOperand(0)->getType();
678 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
679 Constant::getNullValue(Ty),
682 llvm::Value *NewValue = UndefValue::get(CI->getType());
683 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
684 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
686 CI->replaceAllUsesWith(NewValue);
687 CI->eraseFromParent();
692 case ARCInstKind::RetainRV:
693 if (OptimizeRetainRVCall(F, Inst))
696 case ARCInstKind::AutoreleaseRV:
697 OptimizeAutoreleaseRVCall(F, Inst, Class);
701 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
702 if (IsAutorelease(Class) && Inst->use_empty()) {
703 CallInst *Call = cast<CallInst>(Inst);
704 const Value *Arg = Call->getArgOperand(0);
705 Arg = FindSingleUseIdentifiedObject(Arg);
710 // Create the declaration lazily.
711 LLVMContext &C = Inst->getContext();
713 Constant *Decl = EP.get(ARCRuntimeEntryPointKind::Release);
714 CallInst *NewCall = CallInst::Create(Decl, Call->getArgOperand(0), "",
716 NewCall->setMetadata(MDKindCache.get(ARCMDKindID::ImpreciseRelease),
717 MDNode::get(C, None));
719 DEBUG(dbgs() << "Replacing autorelease{,RV}(x) with objc_release(x) "
720 "since x is otherwise unused.\nOld: " << *Call << "\nNew: "
721 << *NewCall << "\n");
723 EraseInstruction(Call);
725 Class = ARCInstKind::Release;
729 // For functions which can never be passed stack arguments, add
731 if (IsAlwaysTail(Class)) {
733 DEBUG(dbgs() << "Adding tail keyword to function since it can never be "
734 "passed stack args: " << *Inst << "\n");
735 cast<CallInst>(Inst)->setTailCall();
738 // Ensure that functions that can never have a "tail" keyword due to the
739 // semantics of ARC truly do not do so.
740 if (IsNeverTail(Class)) {
742 DEBUG(dbgs() << "Removing tail keyword from function: " << *Inst <<
744 cast<CallInst>(Inst)->setTailCall(false);
747 // Set nounwind as needed.
748 if (IsNoThrow(Class)) {
750 DEBUG(dbgs() << "Found no throw class. Setting nounwind on: " << *Inst
752 cast<CallInst>(Inst)->setDoesNotThrow();
755 if (!IsNoopOnNull(Class)) {
756 UsedInThisFunction |= 1 << unsigned(Class);
760 const Value *Arg = GetArgRCIdentityRoot(Inst);
762 // ARC calls with null are no-ops. Delete them.
763 if (IsNullOrUndef(Arg)) {
766 DEBUG(dbgs() << "ARC calls with null are no-ops. Erasing: " << *Inst
768 EraseInstruction(Inst);
772 // Keep track of which of retain, release, autorelease, and retain_block
773 // are actually present in this function.
774 UsedInThisFunction |= 1 << unsigned(Class);
776 // If Arg is a PHI, and one or more incoming values to the
777 // PHI are null, and the call is control-equivalent to the PHI, and there
778 // are no relevant side effects between the PHI and the call, the call
779 // could be pushed up to just those paths with non-null incoming values.
780 // For now, don't bother splitting critical edges for this.
781 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
782 Worklist.push_back(std::make_pair(Inst, Arg));
784 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
788 const PHINode *PN = dyn_cast<PHINode>(Arg);
791 // Determine if the PHI has any null operands, or any incoming
793 bool HasNull = false;
794 bool HasCriticalEdges = false;
795 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
797 GetRCIdentityRoot(PN->getIncomingValue(i));
798 if (IsNullOrUndef(Incoming))
800 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
801 .getNumSuccessors() != 1) {
802 HasCriticalEdges = true;
806 // If we have null operands and no critical edges, optimize.
807 if (!HasCriticalEdges && HasNull) {
808 SmallPtrSet<Instruction *, 4> DependingInstructions;
809 SmallPtrSet<const BasicBlock *, 4> Visited;
811 // Check that there is nothing that cares about the reference
812 // count between the call and the phi.
814 case ARCInstKind::Retain:
815 case ARCInstKind::RetainBlock:
816 // These can always be moved up.
818 case ARCInstKind::Release:
819 // These can't be moved across things that care about the retain
821 FindDependencies(NeedsPositiveRetainCount, Arg,
822 Inst->getParent(), Inst,
823 DependingInstructions, Visited, PA);
825 case ARCInstKind::Autorelease:
826 // These can't be moved across autorelease pool scope boundaries.
827 FindDependencies(AutoreleasePoolBoundary, Arg,
828 Inst->getParent(), Inst,
829 DependingInstructions, Visited, PA);
831 case ARCInstKind::RetainRV:
832 case ARCInstKind::AutoreleaseRV:
833 // Don't move these; the RV optimization depends on the autoreleaseRV
834 // being tail called, and the retainRV being immediately after a call
835 // (which might still happen if we get lucky with codegen layout, but
836 // it's not worth taking the chance).
839 llvm_unreachable("Invalid dependence flavor");
842 if (DependingInstructions.size() == 1 &&
843 *DependingInstructions.begin() == PN) {
846 // Clone the call into each predecessor that has a non-null value.
847 CallInst *CInst = cast<CallInst>(Inst);
848 Type *ParamTy = CInst->getArgOperand(0)->getType();
849 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
851 GetRCIdentityRoot(PN->getIncomingValue(i));
852 if (!IsNullOrUndef(Incoming)) {
853 CallInst *Clone = cast<CallInst>(CInst->clone());
854 Value *Op = PN->getIncomingValue(i);
855 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
856 if (Op->getType() != ParamTy)
857 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
858 Clone->setArgOperand(0, Op);
859 Clone->insertBefore(InsertPos);
861 DEBUG(dbgs() << "Cloning "
863 "And inserting clone at " << *InsertPos << "\n");
864 Worklist.push_back(std::make_pair(Clone, Incoming));
867 // Erase the original call.
868 DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
869 EraseInstruction(CInst);
873 } while (!Worklist.empty());
877 /// If we have a top down pointer in the S_Use state, make sure that there are
878 /// no CFG hazards by checking the states of various bottom up pointers.
879 static void CheckForUseCFGHazard(const Sequence SuccSSeq,
880 const bool SuccSRRIKnownSafe,
882 bool &SomeSuccHasSame,
883 bool &AllSuccsHaveSame,
884 bool &NotAllSeqEqualButKnownSafe,
885 bool &ShouldContinue) {
888 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe) {
889 S.ClearSequenceProgress();
892 S.SetCFGHazardAfflicted(true);
893 ShouldContinue = true;
897 SomeSuccHasSame = true;
901 case S_MovableRelease:
902 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe)
903 AllSuccsHaveSame = false;
905 NotAllSeqEqualButKnownSafe = true;
908 llvm_unreachable("bottom-up pointer in retain state!");
910 llvm_unreachable("This should have been handled earlier.");
914 /// If we have a Top Down pointer in the S_CanRelease state, make sure that
915 /// there are no CFG hazards by checking the states of various bottom up
917 static void CheckForCanReleaseCFGHazard(const Sequence SuccSSeq,
918 const bool SuccSRRIKnownSafe,
920 bool &SomeSuccHasSame,
921 bool &AllSuccsHaveSame,
922 bool &NotAllSeqEqualButKnownSafe) {
925 SomeSuccHasSame = true;
929 case S_MovableRelease:
931 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe)
932 AllSuccsHaveSame = false;
934 NotAllSeqEqualButKnownSafe = true;
937 llvm_unreachable("bottom-up pointer in retain state!");
939 llvm_unreachable("This should have been handled earlier.");
943 /// Check for critical edges, loop boundaries, irreducible control flow, or
944 /// other CFG structures where moving code across the edge would result in it
945 /// being executed more.
947 ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
948 DenseMap<const BasicBlock *, BBState> &BBStates,
949 BBState &MyStates) const {
950 // If any top-down local-use or possible-dec has a succ which is earlier in
951 // the sequence, forget it.
952 for (auto I = MyStates.top_down_ptr_begin(), E = MyStates.top_down_ptr_end();
954 TopDownPtrState &S = I->second;
955 const Sequence Seq = I->second.GetSeq();
957 // We only care about S_Retain, S_CanRelease, and S_Use.
961 // Make sure that if extra top down states are added in the future that this
962 // code is updated to handle it.
963 assert((Seq == S_Retain || Seq == S_CanRelease || Seq == S_Use) &&
964 "Unknown top down sequence state.");
966 const Value *Arg = I->first;
967 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
968 bool SomeSuccHasSame = false;
969 bool AllSuccsHaveSame = true;
970 bool NotAllSeqEqualButKnownSafe = false;
972 succ_const_iterator SI(TI), SE(TI, false);
974 for (; SI != SE; ++SI) {
975 // If VisitBottomUp has pointer information for this successor, take
976 // what we know about it.
977 const DenseMap<const BasicBlock *, BBState>::iterator BBI =
979 assert(BBI != BBStates.end());
980 const BottomUpPtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
981 const Sequence SuccSSeq = SuccS.GetSeq();
983 // If bottom up, the pointer is in an S_None state, clear the sequence
984 // progress since the sequence in the bottom up state finished
985 // suggesting a mismatch in between retains/releases. This is true for
986 // all three cases that we are handling here: S_Retain, S_Use, and
988 if (SuccSSeq == S_None) {
989 S.ClearSequenceProgress();
993 // If we have S_Use or S_CanRelease, perform our check for cfg hazard
995 const bool SuccSRRIKnownSafe = SuccS.IsKnownSafe();
997 // *NOTE* We do not use Seq from above here since we are allowing for
998 // S.GetSeq() to change while we are visiting basic blocks.
1001 bool ShouldContinue = false;
1002 CheckForUseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S, SomeSuccHasSame,
1003 AllSuccsHaveSame, NotAllSeqEqualButKnownSafe,
1009 case S_CanRelease: {
1010 CheckForCanReleaseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S,
1011 SomeSuccHasSame, AllSuccsHaveSame,
1012 NotAllSeqEqualButKnownSafe);
1019 case S_MovableRelease:
1024 // If the state at the other end of any of the successor edges
1025 // matches the current state, require all edges to match. This
1026 // guards against loops in the middle of a sequence.
1027 if (SomeSuccHasSame && !AllSuccsHaveSame) {
1028 S.ClearSequenceProgress();
1029 } else if (NotAllSeqEqualButKnownSafe) {
1030 // If we would have cleared the state foregoing the fact that we are known
1031 // safe, stop code motion. This is because whether or not it is safe to
1032 // remove RR pairs via KnownSafe is an orthogonal concept to whether we
1033 // are allowed to perform code motion.
1034 S.SetCFGHazardAfflicted(true);
1039 bool ObjCARCOpt::VisitInstructionBottomUp(
1040 Instruction *Inst, BasicBlock *BB, BlotMapVector<Value *, RRInfo> &Retains,
1041 BBState &MyStates) {
1042 bool NestingDetected = false;
1043 ARCInstKind Class = GetARCInstKind(Inst);
1044 const Value *Arg = nullptr;
1046 DEBUG(dbgs() << "Class: " << Class << "\n");
1049 case ARCInstKind::Release: {
1050 Arg = GetArgRCIdentityRoot(Inst);
1052 BottomUpPtrState &S = MyStates.getPtrBottomUpState(Arg);
1053 NestingDetected |= S.InitBottomUp(MDKindCache, Inst);
1056 case ARCInstKind::RetainBlock:
1057 // In OptimizeIndividualCalls, we have strength reduced all optimizable
1058 // objc_retainBlocks to objc_retains. Thus at this point any
1059 // objc_retainBlocks that we see are not optimizable.
1061 case ARCInstKind::Retain:
1062 case ARCInstKind::RetainRV: {
1063 Arg = GetArgRCIdentityRoot(Inst);
1064 BottomUpPtrState &S = MyStates.getPtrBottomUpState(Arg);
1065 if (S.MatchWithRetain()) {
1066 // Don't do retain+release tracking for ARCInstKind::RetainRV, because
1067 // it's better to let it remain as the first instruction after a call.
1068 if (Class != ARCInstKind::RetainRV)
1069 Retains[Inst] = S.GetRRInfo();
1070 S.ClearSequenceProgress();
1072 // A retain moving bottom up can be a use.
1075 case ARCInstKind::AutoreleasepoolPop:
1076 // Conservatively, clear MyStates for all known pointers.
1077 MyStates.clearBottomUpPointers();
1078 return NestingDetected;
1079 case ARCInstKind::AutoreleasepoolPush:
1080 case ARCInstKind::None:
1081 // These are irrelevant.
1082 return NestingDetected;
1083 case ARCInstKind::User:
1084 // If we have a store into an alloca of a pointer we are tracking, the
1085 // pointer has multiple owners implying that we must be more conservative.
1087 // This comes up in the context of a pointer being ``KnownSafe''. In the
1088 // presence of a block being initialized, the frontend will emit the
1089 // objc_retain on the original pointer and the release on the pointer loaded
1090 // from the alloca. The optimizer will through the provenance analysis
1091 // realize that the two are related, but since we only require KnownSafe in
1092 // one direction, will match the inner retain on the original pointer with
1093 // the guard release on the original pointer. This is fixed by ensuring that
1094 // in the presence of allocas we only unconditionally remove pointers if
1095 // both our retain and our release are KnownSafe.
1096 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1097 const DataLayout &DL = BB->getModule()->getDataLayout();
1098 if (AreAnyUnderlyingObjectsAnAlloca(SI->getPointerOperand(), DL)) {
1099 auto I = MyStates.findPtrBottomUpState(
1100 GetRCIdentityRoot(SI->getValueOperand()));
1101 if (I != MyStates.bottom_up_ptr_end())
1102 MultiOwnersSet.insert(I->first);
1110 // Consider any other possible effects of this instruction on each
1111 // pointer being tracked.
1112 for (auto MI = MyStates.bottom_up_ptr_begin(),
1113 ME = MyStates.bottom_up_ptr_end();
1115 const Value *Ptr = MI->first;
1117 continue; // Handled above.
1118 BottomUpPtrState &S = MI->second;
1120 if (S.HandlePotentialAlterRefCount(Inst, Ptr, PA, Class))
1123 S.HandlePotentialUse(BB, Inst, Ptr, PA, Class);
1126 return NestingDetected;
1129 bool ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
1130 DenseMap<const BasicBlock *, BBState> &BBStates,
1131 BlotMapVector<Value *, RRInfo> &Retains) {
1133 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitBottomUp ==\n");
1135 bool NestingDetected = false;
1136 BBState &MyStates = BBStates[BB];
1138 // Merge the states from each successor to compute the initial state
1139 // for the current block.
1140 BBState::edge_iterator SI(MyStates.succ_begin()),
1141 SE(MyStates.succ_end());
1143 const BasicBlock *Succ = *SI;
1144 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
1145 assert(I != BBStates.end());
1146 MyStates.InitFromSucc(I->second);
1148 for (; SI != SE; ++SI) {
1150 I = BBStates.find(Succ);
1151 assert(I != BBStates.end());
1152 MyStates.MergeSucc(I->second);
1156 // Visit all the instructions, bottom-up.
1157 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
1158 Instruction *Inst = std::prev(I);
1160 // Invoke instructions are visited as part of their successors (below).
1161 if (isa<InvokeInst>(Inst))
1164 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
1166 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
1169 // If there's a predecessor with an invoke, visit the invoke as if it were
1170 // part of this block, since we can't insert code after an invoke in its own
1171 // block, and we don't want to split critical edges.
1172 for (BBState::edge_iterator PI(MyStates.pred_begin()),
1173 PE(MyStates.pred_end()); PI != PE; ++PI) {
1174 BasicBlock *Pred = *PI;
1175 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
1176 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
1179 return NestingDetected;
1183 ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
1184 DenseMap<Value *, RRInfo> &Releases,
1185 BBState &MyStates) {
1186 bool NestingDetected = false;
1187 ARCInstKind Class = GetARCInstKind(Inst);
1188 const Value *Arg = nullptr;
1191 case ARCInstKind::RetainBlock:
1192 // In OptimizeIndividualCalls, we have strength reduced all optimizable
1193 // objc_retainBlocks to objc_retains. Thus at this point any
1194 // objc_retainBlocks that we see are not optimizable. We need to break since
1195 // a retain can be a potential use.
1197 case ARCInstKind::Retain:
1198 case ARCInstKind::RetainRV: {
1199 Arg = GetArgRCIdentityRoot(Inst);
1200 TopDownPtrState &S = MyStates.getPtrTopDownState(Arg);
1201 NestingDetected |= S.InitTopDown(Class, Inst);
1202 // A retain can be a potential use; procede to the generic checking
1206 case ARCInstKind::Release: {
1207 Arg = GetArgRCIdentityRoot(Inst);
1208 TopDownPtrState &S = MyStates.getPtrTopDownState(Arg);
1209 // Try to form a tentative pair in between this release instruction and the
1210 // top down pointers that we are tracking.
1211 if (S.MatchWithRelease(MDKindCache, Inst)) {
1212 // If we succeed, copy S's RRInfo into the Release -> {Retain Set
1213 // Map}. Then we clear S.
1214 Releases[Inst] = S.GetRRInfo();
1215 S.ClearSequenceProgress();
1219 case ARCInstKind::AutoreleasepoolPop:
1220 // Conservatively, clear MyStates for all known pointers.
1221 MyStates.clearTopDownPointers();
1223 case ARCInstKind::AutoreleasepoolPush:
1224 case ARCInstKind::None:
1225 // These can not be uses of
1231 // Consider any other possible effects of this instruction on each
1232 // pointer being tracked.
1233 for (auto MI = MyStates.top_down_ptr_begin(),
1234 ME = MyStates.top_down_ptr_end();
1236 const Value *Ptr = MI->first;
1238 continue; // Handled above.
1239 TopDownPtrState &S = MI->second;
1240 if (S.HandlePotentialAlterRefCount(Inst, Ptr, PA, Class))
1243 S.HandlePotentialUse(Inst, Ptr, PA, Class);
1246 return NestingDetected;
1250 ObjCARCOpt::VisitTopDown(BasicBlock *BB,
1251 DenseMap<const BasicBlock *, BBState> &BBStates,
1252 DenseMap<Value *, RRInfo> &Releases) {
1253 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitTopDown ==\n");
1254 bool NestingDetected = false;
1255 BBState &MyStates = BBStates[BB];
1257 // Merge the states from each predecessor to compute the initial state
1258 // for the current block.
1259 BBState::edge_iterator PI(MyStates.pred_begin()),
1260 PE(MyStates.pred_end());
1262 const BasicBlock *Pred = *PI;
1263 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
1264 assert(I != BBStates.end());
1265 MyStates.InitFromPred(I->second);
1267 for (; PI != PE; ++PI) {
1269 I = BBStates.find(Pred);
1270 assert(I != BBStates.end());
1271 MyStates.MergePred(I->second);
1275 // Visit all the instructions, top-down.
1276 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1277 Instruction *Inst = I;
1279 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
1281 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
1284 CheckForCFGHazards(BB, BBStates, MyStates);
1285 return NestingDetected;
1289 ComputePostOrders(Function &F,
1290 SmallVectorImpl<BasicBlock *> &PostOrder,
1291 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
1292 unsigned NoObjCARCExceptionsMDKind,
1293 DenseMap<const BasicBlock *, BBState> &BBStates) {
1294 /// The visited set, for doing DFS walks.
1295 SmallPtrSet<BasicBlock *, 16> Visited;
1297 // Do DFS, computing the PostOrder.
1298 SmallPtrSet<BasicBlock *, 16> OnStack;
1299 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
1301 // Functions always have exactly one entry block, and we don't have
1302 // any other block that we treat like an entry block.
1303 BasicBlock *EntryBB = &F.getEntryBlock();
1304 BBState &MyStates = BBStates[EntryBB];
1305 MyStates.SetAsEntry();
1306 TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
1307 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
1308 Visited.insert(EntryBB);
1309 OnStack.insert(EntryBB);
1312 BasicBlock *CurrBB = SuccStack.back().first;
1313 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
1314 succ_iterator SE(TI, false);
1316 while (SuccStack.back().second != SE) {
1317 BasicBlock *SuccBB = *SuccStack.back().second++;
1318 if (Visited.insert(SuccBB).second) {
1319 TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
1320 SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
1321 BBStates[CurrBB].addSucc(SuccBB);
1322 BBState &SuccStates = BBStates[SuccBB];
1323 SuccStates.addPred(CurrBB);
1324 OnStack.insert(SuccBB);
1328 if (!OnStack.count(SuccBB)) {
1329 BBStates[CurrBB].addSucc(SuccBB);
1330 BBStates[SuccBB].addPred(CurrBB);
1333 OnStack.erase(CurrBB);
1334 PostOrder.push_back(CurrBB);
1335 SuccStack.pop_back();
1336 } while (!SuccStack.empty());
1340 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
1341 // Functions may have many exits, and there also blocks which we treat
1342 // as exits due to ignored edges.
1343 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
1344 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
1345 BasicBlock *ExitBB = I;
1346 BBState &MyStates = BBStates[ExitBB];
1347 if (!MyStates.isExit())
1350 MyStates.SetAsExit();
1352 PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
1353 Visited.insert(ExitBB);
1354 while (!PredStack.empty()) {
1355 reverse_dfs_next_succ:
1356 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
1357 while (PredStack.back().second != PE) {
1358 BasicBlock *BB = *PredStack.back().second++;
1359 if (Visited.insert(BB).second) {
1360 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
1361 goto reverse_dfs_next_succ;
1364 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
1369 // Visit the function both top-down and bottom-up.
1370 bool ObjCARCOpt::Visit(Function &F,
1371 DenseMap<const BasicBlock *, BBState> &BBStates,
1372 BlotMapVector<Value *, RRInfo> &Retains,
1373 DenseMap<Value *, RRInfo> &Releases) {
1375 // Use reverse-postorder traversals, because we magically know that loops
1376 // will be well behaved, i.e. they won't repeatedly call retain on a single
1377 // pointer without doing a release. We can't use the ReversePostOrderTraversal
1378 // class here because we want the reverse-CFG postorder to consider each
1379 // function exit point, and we want to ignore selected cycle edges.
1380 SmallVector<BasicBlock *, 16> PostOrder;
1381 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
1382 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
1383 MDKindCache.get(ARCMDKindID::NoObjCARCExceptions),
1386 // Use reverse-postorder on the reverse CFG for bottom-up.
1387 bool BottomUpNestingDetected = false;
1388 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
1389 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
1391 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
1393 // Use reverse-postorder for top-down.
1394 bool TopDownNestingDetected = false;
1395 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
1396 PostOrder.rbegin(), E = PostOrder.rend();
1398 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
1400 return TopDownNestingDetected && BottomUpNestingDetected;
1403 /// Move the calls in RetainsToMove and ReleasesToMove.
1404 void ObjCARCOpt::MoveCalls(Value *Arg, RRInfo &RetainsToMove,
1405 RRInfo &ReleasesToMove,
1406 BlotMapVector<Value *, RRInfo> &Retains,
1407 DenseMap<Value *, RRInfo> &Releases,
1408 SmallVectorImpl<Instruction *> &DeadInsts,
1410 Type *ArgTy = Arg->getType();
1411 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
1413 DEBUG(dbgs() << "== ObjCARCOpt::MoveCalls ==\n");
1415 // Insert the new retain and release calls.
1416 for (Instruction *InsertPt : ReleasesToMove.ReverseInsertPts) {
1417 Value *MyArg = ArgTy == ParamTy ? Arg :
1418 new BitCastInst(Arg, ParamTy, "", InsertPt);
1419 Constant *Decl = EP.get(ARCRuntimeEntryPointKind::Retain);
1420 CallInst *Call = CallInst::Create(Decl, MyArg, "", InsertPt);
1421 Call->setDoesNotThrow();
1422 Call->setTailCall();
1424 DEBUG(dbgs() << "Inserting new Retain: " << *Call << "\n"
1425 "At insertion point: " << *InsertPt << "\n");
1427 for (Instruction *InsertPt : RetainsToMove.ReverseInsertPts) {
1428 Value *MyArg = ArgTy == ParamTy ? Arg :
1429 new BitCastInst(Arg, ParamTy, "", InsertPt);
1430 Constant *Decl = EP.get(ARCRuntimeEntryPointKind::Release);
1431 CallInst *Call = CallInst::Create(Decl, MyArg, "", InsertPt);
1432 // Attach a clang.imprecise_release metadata tag, if appropriate.
1433 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
1434 Call->setMetadata(MDKindCache.get(ARCMDKindID::ImpreciseRelease), M);
1435 Call->setDoesNotThrow();
1436 if (ReleasesToMove.IsTailCallRelease)
1437 Call->setTailCall();
1439 DEBUG(dbgs() << "Inserting new Release: " << *Call << "\n"
1440 "At insertion point: " << *InsertPt << "\n");
1443 // Delete the original retain and release calls.
1444 for (Instruction *OrigRetain : RetainsToMove.Calls) {
1445 Retains.blot(OrigRetain);
1446 DeadInsts.push_back(OrigRetain);
1447 DEBUG(dbgs() << "Deleting retain: " << *OrigRetain << "\n");
1449 for (Instruction *OrigRelease : ReleasesToMove.Calls) {
1450 Releases.erase(OrigRelease);
1451 DeadInsts.push_back(OrigRelease);
1452 DEBUG(dbgs() << "Deleting release: " << *OrigRelease << "\n");
1457 bool ObjCARCOpt::PairUpRetainsAndReleases(
1458 DenseMap<const BasicBlock *, BBState> &BBStates,
1459 BlotMapVector<Value *, RRInfo> &Retains,
1460 DenseMap<Value *, RRInfo> &Releases, Module *M,
1461 SmallVectorImpl<Instruction *> &NewRetains,
1462 SmallVectorImpl<Instruction *> &NewReleases,
1463 SmallVectorImpl<Instruction *> &DeadInsts, RRInfo &RetainsToMove,
1464 RRInfo &ReleasesToMove, Value *Arg, bool KnownSafe,
1465 bool &AnyPairsCompletelyEliminated) {
1466 // If a pair happens in a region where it is known that the reference count
1467 // is already incremented, we can similarly ignore possible decrements unless
1468 // we are dealing with a retainable object with multiple provenance sources.
1469 bool KnownSafeTD = true, KnownSafeBU = true;
1470 bool MultipleOwners = false;
1471 bool CFGHazardAfflicted = false;
1473 // Connect the dots between the top-down-collected RetainsToMove and
1474 // bottom-up-collected ReleasesToMove to form sets of related calls.
1475 // This is an iterative process so that we connect multiple releases
1476 // to multiple retains if needed.
1477 unsigned OldDelta = 0;
1478 unsigned NewDelta = 0;
1479 unsigned OldCount = 0;
1480 unsigned NewCount = 0;
1481 bool FirstRelease = true;
1483 for (SmallVectorImpl<Instruction *>::const_iterator
1484 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
1485 Instruction *NewRetain = *NI;
1486 auto It = Retains.find(NewRetain);
1487 assert(It != Retains.end());
1488 const RRInfo &NewRetainRRI = It->second;
1489 KnownSafeTD &= NewRetainRRI.KnownSafe;
1491 MultipleOwners || MultiOwnersSet.count(GetArgRCIdentityRoot(NewRetain));
1492 for (Instruction *NewRetainRelease : NewRetainRRI.Calls) {
1493 auto Jt = Releases.find(NewRetainRelease);
1494 if (Jt == Releases.end())
1496 const RRInfo &NewRetainReleaseRRI = Jt->second;
1498 // If the release does not have a reference to the retain as well,
1499 // something happened which is unaccounted for. Do not do anything.
1501 // This can happen if we catch an additive overflow during path count
1503 if (!NewRetainReleaseRRI.Calls.count(NewRetain))
1506 if (ReleasesToMove.Calls.insert(NewRetainRelease).second) {
1508 // If we overflow when we compute the path count, don't remove/move
1510 const BBState &NRRBBState = BBStates[NewRetainRelease->getParent()];
1511 unsigned PathCount = BBState::OverflowOccurredValue;
1512 if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
1514 assert(PathCount != BBState::OverflowOccurredValue &&
1515 "PathCount at this point can not be "
1516 "OverflowOccurredValue.");
1517 OldDelta -= PathCount;
1519 // Merge the ReleaseMetadata and IsTailCallRelease values.
1521 ReleasesToMove.ReleaseMetadata =
1522 NewRetainReleaseRRI.ReleaseMetadata;
1523 ReleasesToMove.IsTailCallRelease =
1524 NewRetainReleaseRRI.IsTailCallRelease;
1525 FirstRelease = false;
1527 if (ReleasesToMove.ReleaseMetadata !=
1528 NewRetainReleaseRRI.ReleaseMetadata)
1529 ReleasesToMove.ReleaseMetadata = nullptr;
1530 if (ReleasesToMove.IsTailCallRelease !=
1531 NewRetainReleaseRRI.IsTailCallRelease)
1532 ReleasesToMove.IsTailCallRelease = false;
1535 // Collect the optimal insertion points.
1537 for (Instruction *RIP : NewRetainReleaseRRI.ReverseInsertPts) {
1538 if (ReleasesToMove.ReverseInsertPts.insert(RIP).second) {
1539 // If we overflow when we compute the path count, don't
1540 // remove/move anything.
1541 const BBState &RIPBBState = BBStates[RIP->getParent()];
1542 PathCount = BBState::OverflowOccurredValue;
1543 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
1545 assert(PathCount != BBState::OverflowOccurredValue &&
1546 "PathCount at this point can not be "
1547 "OverflowOccurredValue.");
1548 NewDelta -= PathCount;
1551 NewReleases.push_back(NewRetainRelease);
1556 if (NewReleases.empty()) break;
1558 // Back the other way.
1559 for (SmallVectorImpl<Instruction *>::const_iterator
1560 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
1561 Instruction *NewRelease = *NI;
1562 auto It = Releases.find(NewRelease);
1563 assert(It != Releases.end());
1564 const RRInfo &NewReleaseRRI = It->second;
1565 KnownSafeBU &= NewReleaseRRI.KnownSafe;
1566 CFGHazardAfflicted |= NewReleaseRRI.CFGHazardAfflicted;
1567 for (Instruction *NewReleaseRetain : NewReleaseRRI.Calls) {
1568 auto Jt = Retains.find(NewReleaseRetain);
1569 if (Jt == Retains.end())
1571 const RRInfo &NewReleaseRetainRRI = Jt->second;
1573 // If the retain does not have a reference to the release as well,
1574 // something happened which is unaccounted for. Do not do anything.
1576 // This can happen if we catch an additive overflow during path count
1578 if (!NewReleaseRetainRRI.Calls.count(NewRelease))
1581 if (RetainsToMove.Calls.insert(NewReleaseRetain).second) {
1582 // If we overflow when we compute the path count, don't remove/move
1584 const BBState &NRRBBState = BBStates[NewReleaseRetain->getParent()];
1585 unsigned PathCount = BBState::OverflowOccurredValue;
1586 if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
1588 assert(PathCount != BBState::OverflowOccurredValue &&
1589 "PathCount at this point can not be "
1590 "OverflowOccurredValue.");
1591 OldDelta += PathCount;
1592 OldCount += PathCount;
1594 // Collect the optimal insertion points.
1596 for (Instruction *RIP : NewReleaseRetainRRI.ReverseInsertPts) {
1597 if (RetainsToMove.ReverseInsertPts.insert(RIP).second) {
1598 // If we overflow when we compute the path count, don't
1599 // remove/move anything.
1600 const BBState &RIPBBState = BBStates[RIP->getParent()];
1602 PathCount = BBState::OverflowOccurredValue;
1603 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
1605 assert(PathCount != BBState::OverflowOccurredValue &&
1606 "PathCount at this point can not be "
1607 "OverflowOccurredValue.");
1608 NewDelta += PathCount;
1609 NewCount += PathCount;
1612 NewRetains.push_back(NewReleaseRetain);
1616 NewReleases.clear();
1617 if (NewRetains.empty()) break;
1620 // If the pointer is known incremented in 1 direction and we do not have
1621 // MultipleOwners, we can safely remove the retain/releases. Otherwise we need
1622 // to be known safe in both directions.
1623 bool UnconditionallySafe = (KnownSafeTD && KnownSafeBU) ||
1624 ((KnownSafeTD || KnownSafeBU) && !MultipleOwners);
1625 if (UnconditionallySafe) {
1626 RetainsToMove.ReverseInsertPts.clear();
1627 ReleasesToMove.ReverseInsertPts.clear();
1630 // Determine whether the new insertion points we computed preserve the
1631 // balance of retain and release calls through the program.
1632 // TODO: If the fully aggressive solution isn't valid, try to find a
1633 // less aggressive solution which is.
1637 // At this point, we are not going to remove any RR pairs, but we still are
1638 // able to move RR pairs. If one of our pointers is afflicted with
1639 // CFGHazards, we cannot perform such code motion so exit early.
1640 const bool WillPerformCodeMotion = RetainsToMove.ReverseInsertPts.size() ||
1641 ReleasesToMove.ReverseInsertPts.size();
1642 if (CFGHazardAfflicted && WillPerformCodeMotion)
1646 // Determine whether the original call points are balanced in the retain and
1647 // release calls through the program. If not, conservatively don't touch
1649 // TODO: It's theoretically possible to do code motion in this case, as
1650 // long as the existing imbalances are maintained.
1655 assert(OldCount != 0 && "Unreachable code?");
1656 NumRRs += OldCount - NewCount;
1657 // Set to true if we completely removed any RR pairs.
1658 AnyPairsCompletelyEliminated = NewCount == 0;
1660 // We can move calls!
1664 /// Identify pairings between the retains and releases, and delete and/or move
1666 bool ObjCARCOpt::PerformCodePlacement(
1667 DenseMap<const BasicBlock *, BBState> &BBStates,
1668 BlotMapVector<Value *, RRInfo> &Retains,
1669 DenseMap<Value *, RRInfo> &Releases, Module *M) {
1670 DEBUG(dbgs() << "\n== ObjCARCOpt::PerformCodePlacement ==\n");
1672 bool AnyPairsCompletelyEliminated = false;
1673 RRInfo RetainsToMove;
1674 RRInfo ReleasesToMove;
1675 SmallVector<Instruction *, 4> NewRetains;
1676 SmallVector<Instruction *, 4> NewReleases;
1677 SmallVector<Instruction *, 8> DeadInsts;
1679 // Visit each retain.
1680 for (BlotMapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
1683 Value *V = I->first;
1684 if (!V) continue; // blotted
1686 Instruction *Retain = cast<Instruction>(V);
1688 DEBUG(dbgs() << "Visiting: " << *Retain << "\n");
1690 Value *Arg = GetArgRCIdentityRoot(Retain);
1692 // If the object being released is in static or stack storage, we know it's
1693 // not being managed by ObjC reference counting, so we can delete pairs
1694 // regardless of what possible decrements or uses lie between them.
1695 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
1697 // A constant pointer can't be pointing to an object on the heap. It may
1698 // be reference-counted, but it won't be deleted.
1699 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
1700 if (const GlobalVariable *GV =
1701 dyn_cast<GlobalVariable>(
1702 GetRCIdentityRoot(LI->getPointerOperand())))
1703 if (GV->isConstant())
1706 // Connect the dots between the top-down-collected RetainsToMove and
1707 // bottom-up-collected ReleasesToMove to form sets of related calls.
1708 NewRetains.push_back(Retain);
1709 bool PerformMoveCalls = PairUpRetainsAndReleases(
1710 BBStates, Retains, Releases, M, NewRetains, NewReleases, DeadInsts,
1711 RetainsToMove, ReleasesToMove, Arg, KnownSafe,
1712 AnyPairsCompletelyEliminated);
1714 if (PerformMoveCalls) {
1715 // Ok, everything checks out and we're all set. Let's move/delete some
1717 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
1718 Retains, Releases, DeadInsts, M);
1721 // Clean up state for next retain.
1722 NewReleases.clear();
1724 RetainsToMove.clear();
1725 ReleasesToMove.clear();
1728 // Now that we're done moving everything, we can delete the newly dead
1729 // instructions, as we no longer need them as insert points.
1730 while (!DeadInsts.empty())
1731 EraseInstruction(DeadInsts.pop_back_val());
1733 return AnyPairsCompletelyEliminated;
1736 /// Weak pointer optimizations.
1737 void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
1738 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeWeakCalls ==\n");
1740 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
1741 // itself because it uses AliasAnalysis and we need to do provenance
1743 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
1744 Instruction *Inst = &*I++;
1746 DEBUG(dbgs() << "Visiting: " << *Inst << "\n");
1748 ARCInstKind Class = GetBasicARCInstKind(Inst);
1749 if (Class != ARCInstKind::LoadWeak &&
1750 Class != ARCInstKind::LoadWeakRetained)
1753 // Delete objc_loadWeak calls with no users.
1754 if (Class == ARCInstKind::LoadWeak && Inst->use_empty()) {
1755 Inst->eraseFromParent();
1759 // TODO: For now, just look for an earlier available version of this value
1760 // within the same block. Theoretically, we could do memdep-style non-local
1761 // analysis too, but that would want caching. A better approach would be to
1762 // use the technique that EarlyCSE uses.
1763 inst_iterator Current = std::prev(I);
1764 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
1765 for (BasicBlock::iterator B = CurrentBB->begin(),
1766 J = Current.getInstructionIterator();
1768 Instruction *EarlierInst = &*std::prev(J);
1769 ARCInstKind EarlierClass = GetARCInstKind(EarlierInst);
1770 switch (EarlierClass) {
1771 case ARCInstKind::LoadWeak:
1772 case ARCInstKind::LoadWeakRetained: {
1773 // If this is loading from the same pointer, replace this load's value
1775 CallInst *Call = cast<CallInst>(Inst);
1776 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
1777 Value *Arg = Call->getArgOperand(0);
1778 Value *EarlierArg = EarlierCall->getArgOperand(0);
1779 switch (PA.getAA()->alias(Arg, EarlierArg)) {
1780 case AliasAnalysis::MustAlias:
1782 // If the load has a builtin retain, insert a plain retain for it.
1783 if (Class == ARCInstKind::LoadWeakRetained) {
1784 Constant *Decl = EP.get(ARCRuntimeEntryPointKind::Retain);
1785 CallInst *CI = CallInst::Create(Decl, EarlierCall, "", Call);
1788 // Zap the fully redundant load.
1789 Call->replaceAllUsesWith(EarlierCall);
1790 Call->eraseFromParent();
1792 case AliasAnalysis::MayAlias:
1793 case AliasAnalysis::PartialAlias:
1795 case AliasAnalysis::NoAlias:
1800 case ARCInstKind::StoreWeak:
1801 case ARCInstKind::InitWeak: {
1802 // If this is storing to the same pointer and has the same size etc.
1803 // replace this load's value with the stored value.
1804 CallInst *Call = cast<CallInst>(Inst);
1805 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
1806 Value *Arg = Call->getArgOperand(0);
1807 Value *EarlierArg = EarlierCall->getArgOperand(0);
1808 switch (PA.getAA()->alias(Arg, EarlierArg)) {
1809 case AliasAnalysis::MustAlias:
1811 // If the load has a builtin retain, insert a plain retain for it.
1812 if (Class == ARCInstKind::LoadWeakRetained) {
1813 Constant *Decl = EP.get(ARCRuntimeEntryPointKind::Retain);
1814 CallInst *CI = CallInst::Create(Decl, EarlierCall, "", Call);
1817 // Zap the fully redundant load.
1818 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
1819 Call->eraseFromParent();
1821 case AliasAnalysis::MayAlias:
1822 case AliasAnalysis::PartialAlias:
1824 case AliasAnalysis::NoAlias:
1829 case ARCInstKind::MoveWeak:
1830 case ARCInstKind::CopyWeak:
1831 // TOOD: Grab the copied value.
1833 case ARCInstKind::AutoreleasepoolPush:
1834 case ARCInstKind::None:
1835 case ARCInstKind::IntrinsicUser:
1836 case ARCInstKind::User:
1837 // Weak pointers are only modified through the weak entry points
1838 // (and arbitrary calls, which could call the weak entry points).
1841 // Anything else could modify the weak pointer.
1848 // Then, for each destroyWeak with an alloca operand, check to see if
1849 // the alloca and all its users can be zapped.
1850 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
1851 Instruction *Inst = &*I++;
1852 ARCInstKind Class = GetBasicARCInstKind(Inst);
1853 if (Class != ARCInstKind::DestroyWeak)
1856 CallInst *Call = cast<CallInst>(Inst);
1857 Value *Arg = Call->getArgOperand(0);
1858 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
1859 for (User *U : Alloca->users()) {
1860 const Instruction *UserInst = cast<Instruction>(U);
1861 switch (GetBasicARCInstKind(UserInst)) {
1862 case ARCInstKind::InitWeak:
1863 case ARCInstKind::StoreWeak:
1864 case ARCInstKind::DestroyWeak:
1871 for (auto UI = Alloca->user_begin(), UE = Alloca->user_end(); UI != UE;) {
1872 CallInst *UserInst = cast<CallInst>(*UI++);
1873 switch (GetBasicARCInstKind(UserInst)) {
1874 case ARCInstKind::InitWeak:
1875 case ARCInstKind::StoreWeak:
1876 // These functions return their second argument.
1877 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
1879 case ARCInstKind::DestroyWeak:
1883 llvm_unreachable("alloca really is used!");
1885 UserInst->eraseFromParent();
1887 Alloca->eraseFromParent();
1893 /// Identify program paths which execute sequences of retains and releases which
1894 /// can be eliminated.
1895 bool ObjCARCOpt::OptimizeSequences(Function &F) {
1896 // Releases, Retains - These are used to store the results of the main flow
1897 // analysis. These use Value* as the key instead of Instruction* so that the
1898 // map stays valid when we get around to rewriting code and calls get
1899 // replaced by arguments.
1900 DenseMap<Value *, RRInfo> Releases;
1901 BlotMapVector<Value *, RRInfo> Retains;
1903 // This is used during the traversal of the function to track the
1904 // states for each identified object at each block.
1905 DenseMap<const BasicBlock *, BBState> BBStates;
1907 // Analyze the CFG of the function, and all instructions.
1908 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
1911 bool AnyPairsCompletelyEliminated = PerformCodePlacement(BBStates, Retains,
1916 MultiOwnersSet.clear();
1918 return AnyPairsCompletelyEliminated && NestingDetected;
1921 /// Check if there is a dependent call earlier that does not have anything in
1922 /// between the Retain and the call that can affect the reference count of their
1923 /// shared pointer argument. Note that Retain need not be in BB.
1925 HasSafePathToPredecessorCall(const Value *Arg, Instruction *Retain,
1926 SmallPtrSetImpl<Instruction *> &DepInsts,
1927 SmallPtrSetImpl<const BasicBlock *> &Visited,
1928 ProvenanceAnalysis &PA) {
1929 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
1930 DepInsts, Visited, PA);
1931 if (DepInsts.size() != 1)
1934 auto *Call = dyn_cast_or_null<CallInst>(*DepInsts.begin());
1936 // Check that the pointer is the return value of the call.
1937 if (!Call || Arg != Call)
1940 // Check that the call is a regular call.
1941 ARCInstKind Class = GetBasicARCInstKind(Call);
1942 if (Class != ARCInstKind::CallOrUser && Class != ARCInstKind::Call)
1948 /// Find a dependent retain that precedes the given autorelease for which there
1949 /// is nothing in between the two instructions that can affect the ref count of
1952 FindPredecessorRetainWithSafePath(const Value *Arg, BasicBlock *BB,
1953 Instruction *Autorelease,
1954 SmallPtrSetImpl<Instruction *> &DepInsts,
1955 SmallPtrSetImpl<const BasicBlock *> &Visited,
1956 ProvenanceAnalysis &PA) {
1957 FindDependencies(CanChangeRetainCount, Arg,
1958 BB, Autorelease, DepInsts, Visited, PA);
1959 if (DepInsts.size() != 1)
1962 auto *Retain = dyn_cast_or_null<CallInst>(*DepInsts.begin());
1964 // Check that we found a retain with the same argument.
1965 if (!Retain || !IsRetain(GetBasicARCInstKind(Retain)) ||
1966 GetArgRCIdentityRoot(Retain) != Arg) {
1973 /// Look for an ``autorelease'' instruction dependent on Arg such that there are
1974 /// no instructions dependent on Arg that need a positive ref count in between
1975 /// the autorelease and the ret.
1977 FindPredecessorAutoreleaseWithSafePath(const Value *Arg, BasicBlock *BB,
1979 SmallPtrSetImpl<Instruction *> &DepInsts,
1980 SmallPtrSetImpl<const BasicBlock *> &V,
1981 ProvenanceAnalysis &PA) {
1982 FindDependencies(NeedsPositiveRetainCount, Arg,
1983 BB, Ret, DepInsts, V, PA);
1984 if (DepInsts.size() != 1)
1987 auto *Autorelease = dyn_cast_or_null<CallInst>(*DepInsts.begin());
1990 ARCInstKind AutoreleaseClass = GetBasicARCInstKind(Autorelease);
1991 if (!IsAutorelease(AutoreleaseClass))
1993 if (GetArgRCIdentityRoot(Autorelease) != Arg)
1999 /// Look for this pattern:
2001 /// %call = call i8* @something(...)
2002 /// %2 = call i8* @objc_retain(i8* %call)
2003 /// %3 = call i8* @objc_autorelease(i8* %2)
2006 /// And delete the retain and autorelease.
2007 void ObjCARCOpt::OptimizeReturns(Function &F) {
2008 if (!F.getReturnType()->isPointerTy())
2011 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeReturns ==\n");
2013 SmallPtrSet<Instruction *, 4> DependingInstructions;
2014 SmallPtrSet<const BasicBlock *, 4> Visited;
2015 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
2016 BasicBlock *BB = FI;
2017 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
2019 DEBUG(dbgs() << "Visiting: " << *Ret << "\n");
2024 const Value *Arg = GetRCIdentityRoot(Ret->getOperand(0));
2026 // Look for an ``autorelease'' instruction that is a predecessor of Ret and
2027 // dependent on Arg such that there are no instructions dependent on Arg
2028 // that need a positive ref count in between the autorelease and Ret.
2029 CallInst *Autorelease =
2030 FindPredecessorAutoreleaseWithSafePath(Arg, BB, Ret,
2031 DependingInstructions, Visited,
2033 DependingInstructions.clear();
2040 FindPredecessorRetainWithSafePath(Arg, BB, Autorelease,
2041 DependingInstructions, Visited, PA);
2042 DependingInstructions.clear();
2048 // Check that there is nothing that can affect the reference count
2049 // between the retain and the call. Note that Retain need not be in BB.
2050 bool HasSafePathToCall = HasSafePathToPredecessorCall(Arg, Retain,
2051 DependingInstructions,
2053 DependingInstructions.clear();
2056 if (!HasSafePathToCall)
2059 // If so, we can zap the retain and autorelease.
2062 DEBUG(dbgs() << "Erasing: " << *Retain << "\nErasing: "
2063 << *Autorelease << "\n");
2064 EraseInstruction(Retain);
2065 EraseInstruction(Autorelease);
2071 ObjCARCOpt::GatherStatistics(Function &F, bool AfterOptimization) {
2072 llvm::Statistic &NumRetains =
2073 AfterOptimization? NumRetainsAfterOpt : NumRetainsBeforeOpt;
2074 llvm::Statistic &NumReleases =
2075 AfterOptimization? NumReleasesAfterOpt : NumReleasesBeforeOpt;
2077 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2078 Instruction *Inst = &*I++;
2079 switch (GetBasicARCInstKind(Inst)) {
2082 case ARCInstKind::Retain:
2085 case ARCInstKind::Release:
2093 bool ObjCARCOpt::doInitialization(Module &M) {
2097 // If nothing in the Module uses ARC, don't do anything.
2098 Run = ModuleHasARC(M);
2102 // Intuitively, objc_retain and others are nocapture, however in practice
2103 // they are not, because they return their argument value. And objc_release
2104 // calls finalizers which can have arbitrary side effects.
2105 MDKindCache.init(&M);
2107 // Initialize our runtime entry point cache.
2113 bool ObjCARCOpt::runOnFunction(Function &F) {
2117 // If nothing in the Module uses ARC, don't do anything.
2123 DEBUG(dbgs() << "<<< ObjCARCOpt: Visiting Function: " << F.getName() << " >>>"
2126 PA.setAA(&getAnalysis<AliasAnalysis>());
2129 if (AreStatisticsEnabled()) {
2130 GatherStatistics(F, false);
2134 // This pass performs several distinct transformations. As a compile-time aid
2135 // when compiling code that isn't ObjC, skip these if the relevant ObjC
2136 // library functions aren't declared.
2138 // Preliminary optimizations. This also computes UsedInThisFunction.
2139 OptimizeIndividualCalls(F);
2141 // Optimizations for weak pointers.
2142 if (UsedInThisFunction & ((1 << unsigned(ARCInstKind::LoadWeak)) |
2143 (1 << unsigned(ARCInstKind::LoadWeakRetained)) |
2144 (1 << unsigned(ARCInstKind::StoreWeak)) |
2145 (1 << unsigned(ARCInstKind::InitWeak)) |
2146 (1 << unsigned(ARCInstKind::CopyWeak)) |
2147 (1 << unsigned(ARCInstKind::MoveWeak)) |
2148 (1 << unsigned(ARCInstKind::DestroyWeak))))
2149 OptimizeWeakCalls(F);
2151 // Optimizations for retain+release pairs.
2152 if (UsedInThisFunction & ((1 << unsigned(ARCInstKind::Retain)) |
2153 (1 << unsigned(ARCInstKind::RetainRV)) |
2154 (1 << unsigned(ARCInstKind::RetainBlock))))
2155 if (UsedInThisFunction & (1 << unsigned(ARCInstKind::Release)))
2156 // Run OptimizeSequences until it either stops making changes or
2157 // no retain+release pair nesting is detected.
2158 while (OptimizeSequences(F)) {}
2160 // Optimizations if objc_autorelease is used.
2161 if (UsedInThisFunction & ((1 << unsigned(ARCInstKind::Autorelease)) |
2162 (1 << unsigned(ARCInstKind::AutoreleaseRV))))
2165 // Gather statistics after optimization.
2167 if (AreStatisticsEnabled()) {
2168 GatherStatistics(F, true);
2172 DEBUG(dbgs() << "\n");
2177 void ObjCARCOpt::releaseMemory() {