1778138e9SMichael Gottesman //===- DependencyAnalysis.cpp - ObjC ARC Optimization ---------------------===//
2778138e9SMichael Gottesman //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6778138e9SMichael Gottesman //
7778138e9SMichael Gottesman //===----------------------------------------------------------------------===//
8778138e9SMichael Gottesman /// \file
9778138e9SMichael Gottesman ///
10778138e9SMichael Gottesman /// This file defines special dependency analysis routines used in Objective C
11778138e9SMichael Gottesman /// ARC Optimizations.
12778138e9SMichael Gottesman ///
13778138e9SMichael Gottesman /// WARNING: This file knows about certain library functions. It recognizes them
14778138e9SMichael Gottesman /// by name, and hardwires knowledge of their semantics.
15778138e9SMichael Gottesman ///
16778138e9SMichael Gottesman /// WARNING: This file knows about how certain Objective-C library functions are
17778138e9SMichael Gottesman /// used. Naive LLVM IR transformations which would otherwise be
18778138e9SMichael Gottesman /// behavior-preserving may break these assumptions.
19778138e9SMichael Gottesman ///
20778138e9SMichael Gottesman //===----------------------------------------------------------------------===//
21778138e9SMichael Gottesman 
22778138e9SMichael Gottesman #include "DependencyAnalysis.h"
236bda14b3SChandler Carruth #include "ObjCARC.h"
24278266faSMichael Gottesman #include "ProvenanceAnalysis.h"
252ce38b3fSdfukalov #include "llvm/Analysis/AliasAnalysis.h"
261305dc33SChandler Carruth #include "llvm/IR/CFG.h"
27778138e9SMichael Gottesman 
28778138e9SMichael Gottesman using namespace llvm;
29778138e9SMichael Gottesman using namespace llvm::objcarc;
30778138e9SMichael Gottesman 
31964daaafSChandler Carruth #define DEBUG_TYPE "objc-arc-dependency"
32964daaafSChandler Carruth 
33778138e9SMichael Gottesman /// Test whether the given instruction can result in a reference count
34778138e9SMichael Gottesman /// modification (positive or negative) for the pointer's object.
CanAlterRefCount(const Instruction * Inst,const Value * Ptr,ProvenanceAnalysis & PA,ARCInstKind Class)356f729fa6SMichael Gottesman bool llvm::objcarc::CanAlterRefCount(const Instruction *Inst, const Value *Ptr,
36778138e9SMichael Gottesman                                      ProvenanceAnalysis &PA,
376f729fa6SMichael Gottesman                                      ARCInstKind Class) {
38778138e9SMichael Gottesman   switch (Class) {
396f729fa6SMichael Gottesman   case ARCInstKind::Autorelease:
406f729fa6SMichael Gottesman   case ARCInstKind::AutoreleaseRV:
416f729fa6SMichael Gottesman   case ARCInstKind::IntrinsicUser:
426f729fa6SMichael Gottesman   case ARCInstKind::User:
43778138e9SMichael Gottesman     // These operations never directly modify a reference count.
44778138e9SMichael Gottesman     return false;
45778138e9SMichael Gottesman   default: break;
46778138e9SMichael Gottesman   }
47778138e9SMichael Gottesman 
48363ac683SChandler Carruth   const auto *Call = cast<CallBase>(Inst);
49778138e9SMichael Gottesman 
50778138e9SMichael Gottesman   // See if AliasAnalysis can help us with the call.
51363ac683SChandler Carruth   FunctionModRefBehavior MRB = PA.getAA()->getModRefBehavior(Call);
52778138e9SMichael Gottesman   if (AliasAnalysis::onlyReadsMemory(MRB))
53778138e9SMichael Gottesman     return false;
54778138e9SMichael Gottesman   if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
55363ac683SChandler Carruth     for (const Value *Op : Call->args()) {
56b0f1d7d5SAkira Hatanaka       if (IsPotentialRetainableObjPtr(Op, *PA.getAA()) && PA.related(Ptr, Op))
57778138e9SMichael Gottesman         return true;
58778138e9SMichael Gottesman     }
59778138e9SMichael Gottesman     return false;
60778138e9SMichael Gottesman   }
61778138e9SMichael Gottesman 
62778138e9SMichael Gottesman   // Assume the worst.
63778138e9SMichael Gottesman   return true;
64778138e9SMichael Gottesman }
65778138e9SMichael Gottesman 
CanDecrementRefCount(const Instruction * Inst,const Value * Ptr,ProvenanceAnalysis & PA,ARCInstKind Class)665ab64de6SMichael Gottesman bool llvm::objcarc::CanDecrementRefCount(const Instruction *Inst,
675ab64de6SMichael Gottesman                                          const Value *Ptr,
685ab64de6SMichael Gottesman                                          ProvenanceAnalysis &PA,
695ab64de6SMichael Gottesman                                          ARCInstKind Class) {
705ab64de6SMichael Gottesman   // First perform a quick check if Class can not touch ref counts.
715ab64de6SMichael Gottesman   if (!CanDecrementRefCount(Class))
725ab64de6SMichael Gottesman     return false;
735ab64de6SMichael Gottesman 
745ab64de6SMichael Gottesman   // Otherwise, just use CanAlterRefCount for now.
755ab64de6SMichael Gottesman   return CanAlterRefCount(Inst, Ptr, PA, Class);
765ab64de6SMichael Gottesman }
775ab64de6SMichael Gottesman 
78778138e9SMichael Gottesman /// Test whether the given instruction can "use" the given pointer's object in a
79778138e9SMichael Gottesman /// way that requires the reference count to be positive.
CanUse(const Instruction * Inst,const Value * Ptr,ProvenanceAnalysis & PA,ARCInstKind Class)806f729fa6SMichael Gottesman bool llvm::objcarc::CanUse(const Instruction *Inst, const Value *Ptr,
816f729fa6SMichael Gottesman                            ProvenanceAnalysis &PA, ARCInstKind Class) {
826f729fa6SMichael Gottesman   // ARCInstKind::Call operations (as opposed to
836f729fa6SMichael Gottesman   // ARCInstKind::CallOrUser) never "use" objc pointers.
846f729fa6SMichael Gottesman   if (Class == ARCInstKind::Call)
85778138e9SMichael Gottesman     return false;
86778138e9SMichael Gottesman 
87778138e9SMichael Gottesman   // Consider various instructions which may have pointer arguments which are
88778138e9SMichael Gottesman   // not "uses".
89778138e9SMichael Gottesman   if (const ICmpInst *ICI = dyn_cast<ICmpInst>(Inst)) {
90778138e9SMichael Gottesman     // Comparing a pointer with null, or any other constant, isn't really a use,
91778138e9SMichael Gottesman     // because we don't care what the pointer points to, or about the values
92778138e9SMichael Gottesman     // of any other dynamic reference-counted pointers.
93778138e9SMichael Gottesman     if (!IsPotentialRetainableObjPtr(ICI->getOperand(1), *PA.getAA()))
94778138e9SMichael Gottesman       return false;
952059a6e3SMircea Trofin   } else if (const auto *CS = dyn_cast<CallBase>(Inst)) {
96778138e9SMichael Gottesman     // For calls, just check the arguments (and not the callee operand).
97*fd7d4064SKazu Hirata     for (const Value *Op : CS->args())
98b0f1d7d5SAkira Hatanaka       if (IsPotentialRetainableObjPtr(Op, *PA.getAA()) && PA.related(Ptr, Op))
99778138e9SMichael Gottesman         return true;
100778138e9SMichael Gottesman     return false;
101778138e9SMichael Gottesman   } else if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
102778138e9SMichael Gottesman     // Special-case stores, because we don't care about the stored value, just
103778138e9SMichael Gottesman     // the store address.
104b0eb40caSVitaly Buka     const Value *Op = GetUnderlyingObjCPtr(SI->getPointerOperand());
105778138e9SMichael Gottesman     // If we can't tell what the underlying object was, assume there is a
106778138e9SMichael Gottesman     // dependence.
107b0f1d7d5SAkira Hatanaka     return IsPotentialRetainableObjPtr(Op, *PA.getAA()) && PA.related(Op, Ptr);
108778138e9SMichael Gottesman   }
109778138e9SMichael Gottesman 
110778138e9SMichael Gottesman   // Check each operand for a match.
111302313a2SKazu Hirata   for (const Use &U : Inst->operands()) {
112302313a2SKazu Hirata     const Value *Op = U;
113b0f1d7d5SAkira Hatanaka     if (IsPotentialRetainableObjPtr(Op, *PA.getAA()) && PA.related(Ptr, Op))
114778138e9SMichael Gottesman       return true;
115778138e9SMichael Gottesman   }
116778138e9SMichael Gottesman   return false;
117778138e9SMichael Gottesman }
118778138e9SMichael Gottesman 
119778138e9SMichael Gottesman /// Test if there can be dependencies on Inst through Arg. This function only
120778138e9SMichael Gottesman /// tests dependencies relevant for removing pairs of calls.
121778138e9SMichael Gottesman bool
Depends(DependenceKind Flavor,Instruction * Inst,const Value * Arg,ProvenanceAnalysis & PA)122778138e9SMichael Gottesman llvm::objcarc::Depends(DependenceKind Flavor, Instruction *Inst,
123778138e9SMichael Gottesman                        const Value *Arg, ProvenanceAnalysis &PA) {
124778138e9SMichael Gottesman   // If we've reached the definition of Arg, stop.
125778138e9SMichael Gottesman   if (Inst == Arg)
126778138e9SMichael Gottesman     return true;
127778138e9SMichael Gottesman 
128778138e9SMichael Gottesman   switch (Flavor) {
129778138e9SMichael Gottesman   case NeedsPositiveRetainCount: {
1306f729fa6SMichael Gottesman     ARCInstKind Class = GetARCInstKind(Inst);
131778138e9SMichael Gottesman     switch (Class) {
1326f729fa6SMichael Gottesman     case ARCInstKind::AutoreleasepoolPop:
1336f729fa6SMichael Gottesman     case ARCInstKind::AutoreleasepoolPush:
1346f729fa6SMichael Gottesman     case ARCInstKind::None:
135778138e9SMichael Gottesman       return false;
136778138e9SMichael Gottesman     default:
137778138e9SMichael Gottesman       return CanUse(Inst, Arg, PA, Class);
138778138e9SMichael Gottesman     }
139778138e9SMichael Gottesman   }
140778138e9SMichael Gottesman 
141778138e9SMichael Gottesman   case AutoreleasePoolBoundary: {
1426f729fa6SMichael Gottesman     ARCInstKind Class = GetARCInstKind(Inst);
143778138e9SMichael Gottesman     switch (Class) {
1446f729fa6SMichael Gottesman     case ARCInstKind::AutoreleasepoolPop:
1456f729fa6SMichael Gottesman     case ARCInstKind::AutoreleasepoolPush:
146778138e9SMichael Gottesman       // These mark the end and begin of an autorelease pool scope.
147778138e9SMichael Gottesman       return true;
148778138e9SMichael Gottesman     default:
149778138e9SMichael Gottesman       // Nothing else does this.
150778138e9SMichael Gottesman       return false;
151778138e9SMichael Gottesman     }
152778138e9SMichael Gottesman   }
153778138e9SMichael Gottesman 
154778138e9SMichael Gottesman   case CanChangeRetainCount: {
1556f729fa6SMichael Gottesman     ARCInstKind Class = GetARCInstKind(Inst);
156778138e9SMichael Gottesman     switch (Class) {
1576f729fa6SMichael Gottesman     case ARCInstKind::AutoreleasepoolPop:
158778138e9SMichael Gottesman       // Conservatively assume this can decrement any count.
159778138e9SMichael Gottesman       return true;
1606f729fa6SMichael Gottesman     case ARCInstKind::AutoreleasepoolPush:
1616f729fa6SMichael Gottesman     case ARCInstKind::None:
162778138e9SMichael Gottesman       return false;
163778138e9SMichael Gottesman     default:
164778138e9SMichael Gottesman       return CanAlterRefCount(Inst, Arg, PA, Class);
165778138e9SMichael Gottesman     }
166778138e9SMichael Gottesman   }
167778138e9SMichael Gottesman 
168778138e9SMichael Gottesman   case RetainAutoreleaseDep:
1696f729fa6SMichael Gottesman     switch (GetBasicARCInstKind(Inst)) {
1706f729fa6SMichael Gottesman     case ARCInstKind::AutoreleasepoolPop:
1716f729fa6SMichael Gottesman     case ARCInstKind::AutoreleasepoolPush:
172778138e9SMichael Gottesman       // Don't merge an objc_autorelease with an objc_retain inside a different
173778138e9SMichael Gottesman       // autoreleasepool scope.
174778138e9SMichael Gottesman       return true;
1756f729fa6SMichael Gottesman     case ARCInstKind::Retain:
1766f729fa6SMichael Gottesman     case ARCInstKind::RetainRV:
177778138e9SMichael Gottesman       // Check for a retain of the same pointer for merging.
178e5ad66f8SMichael Gottesman       return GetArgRCIdentityRoot(Inst) == Arg;
179778138e9SMichael Gottesman     default:
180778138e9SMichael Gottesman       // Nothing else matters for objc_retainAutorelease formation.
181778138e9SMichael Gottesman       return false;
182778138e9SMichael Gottesman     }
183778138e9SMichael Gottesman 
184778138e9SMichael Gottesman   case RetainAutoreleaseRVDep: {
1856f729fa6SMichael Gottesman     ARCInstKind Class = GetBasicARCInstKind(Inst);
186778138e9SMichael Gottesman     switch (Class) {
1876f729fa6SMichael Gottesman     case ARCInstKind::Retain:
1886f729fa6SMichael Gottesman     case ARCInstKind::RetainRV:
189778138e9SMichael Gottesman       // Check for a retain of the same pointer for merging.
190e5ad66f8SMichael Gottesman       return GetArgRCIdentityRoot(Inst) == Arg;
191778138e9SMichael Gottesman     default:
192778138e9SMichael Gottesman       // Anything that can autorelease interrupts
193778138e9SMichael Gottesman       // retainAutoreleaseReturnValue formation.
194778138e9SMichael Gottesman       return CanInterruptRV(Class);
195778138e9SMichael Gottesman     }
196778138e9SMichael Gottesman   }
197778138e9SMichael Gottesman   }
198778138e9SMichael Gottesman 
199778138e9SMichael Gottesman   llvm_unreachable("Invalid dependence flavor");
200778138e9SMichael Gottesman }
201778138e9SMichael Gottesman 
202778138e9SMichael Gottesman /// Walk up the CFG from StartPos (which is in StartBB) and find local and
203778138e9SMichael Gottesman /// non-local dependencies on Arg.
204778138e9SMichael Gottesman ///
205778138e9SMichael Gottesman /// TODO: Cache results?
findDependencies(DependenceKind Flavor,const Value * Arg,BasicBlock * StartBB,Instruction * StartInst,SmallPtrSetImpl<Instruction * > & DependingInsts,ProvenanceAnalysis & PA)2062ed3a767SAkira Hatanaka static bool findDependencies(DependenceKind Flavor, const Value *Arg,
207778138e9SMichael Gottesman                              BasicBlock *StartBB, Instruction *StartInst,
20871b7b68bSCraig Topper                              SmallPtrSetImpl<Instruction *> &DependingInsts,
209778138e9SMichael Gottesman                              ProvenanceAnalysis &PA) {
2101e59a66cSDuncan P. N. Exon Smith   BasicBlock::iterator StartPos = StartInst->getIterator();
211778138e9SMichael Gottesman 
21200d0974eSAkira Hatanaka   SmallPtrSet<const BasicBlock *, 4> Visited;
213778138e9SMichael Gottesman   SmallVector<std::pair<BasicBlock *, BasicBlock::iterator>, 4> Worklist;
214778138e9SMichael Gottesman   Worklist.push_back(std::make_pair(StartBB, StartPos));
215778138e9SMichael Gottesman   do {
216778138e9SMichael Gottesman     std::pair<BasicBlock *, BasicBlock::iterator> Pair =
217778138e9SMichael Gottesman       Worklist.pop_back_val();
218778138e9SMichael Gottesman     BasicBlock *LocalStartBB = Pair.first;
219778138e9SMichael Gottesman     BasicBlock::iterator LocalStartPos = Pair.second;
220778138e9SMichael Gottesman     BasicBlock::iterator StartBBBegin = LocalStartBB->begin();
221778138e9SMichael Gottesman     for (;;) {
222778138e9SMichael Gottesman       if (LocalStartPos == StartBBBegin) {
223778138e9SMichael Gottesman         pred_iterator PI(LocalStartBB), PE(LocalStartBB, false);
224778138e9SMichael Gottesman         if (PI == PE)
2252ed3a767SAkira Hatanaka           // Return if we've reached the function entry.
2262ed3a767SAkira Hatanaka           return false;
227778138e9SMichael Gottesman         // Add the predecessors to the worklist.
228778138e9SMichael Gottesman         do {
229778138e9SMichael Gottesman           BasicBlock *PredBB = *PI;
23070573dcdSDavid Blaikie           if (Visited.insert(PredBB).second)
231778138e9SMichael Gottesman             Worklist.push_back(std::make_pair(PredBB, PredBB->end()));
232778138e9SMichael Gottesman         } while (++PI != PE);
233778138e9SMichael Gottesman         break;
234778138e9SMichael Gottesman       }
235778138e9SMichael Gottesman 
2361e59a66cSDuncan P. N. Exon Smith       Instruction *Inst = &*--LocalStartPos;
237778138e9SMichael Gottesman       if (Depends(Flavor, Inst, Arg, PA)) {
238778138e9SMichael Gottesman         DependingInsts.insert(Inst);
239778138e9SMichael Gottesman         break;
240778138e9SMichael Gottesman       }
241778138e9SMichael Gottesman     }
242778138e9SMichael Gottesman   } while (!Worklist.empty());
243778138e9SMichael Gottesman 
244778138e9SMichael Gottesman   // Determine whether the original StartBB post-dominates all of the blocks we
245778138e9SMichael Gottesman   // visited. If not, insert a sentinal indicating that most optimizations are
246778138e9SMichael Gottesman   // not safe.
2474627679cSCraig Topper   for (const BasicBlock *BB : Visited) {
248778138e9SMichael Gottesman     if (BB == StartBB)
249778138e9SMichael Gottesman       continue;
250c1e3ee29SChandler Carruth     for (const BasicBlock *Succ : successors(BB))
2512ed3a767SAkira Hatanaka       if (Succ != StartBB && !Visited.count(Succ))
2522ed3a767SAkira Hatanaka         return false;
253778138e9SMichael Gottesman   }
2542ed3a767SAkira Hatanaka 
2552ed3a767SAkira Hatanaka   return true;
256778138e9SMichael Gottesman }
2572ed3a767SAkira Hatanaka 
findSingleDependency(DependenceKind Flavor,const Value * Arg,BasicBlock * StartBB,Instruction * StartInst,ProvenanceAnalysis & PA)2582ed3a767SAkira Hatanaka llvm::Instruction *llvm::objcarc::findSingleDependency(DependenceKind Flavor,
2592ed3a767SAkira Hatanaka                                                        const Value *Arg,
2602ed3a767SAkira Hatanaka                                                        BasicBlock *StartBB,
2612ed3a767SAkira Hatanaka                                                        Instruction *StartInst,
2622ed3a767SAkira Hatanaka                                                        ProvenanceAnalysis &PA) {
2632ed3a767SAkira Hatanaka   SmallPtrSet<Instruction *, 4> DependingInsts;
2642ed3a767SAkira Hatanaka 
2652ed3a767SAkira Hatanaka   if (!findDependencies(Flavor, Arg, StartBB, StartInst, DependingInsts, PA) ||
2662ed3a767SAkira Hatanaka       DependingInsts.size() != 1)
2672ed3a767SAkira Hatanaka     return nullptr;
2682ed3a767SAkira Hatanaka   return *DependingInsts.begin();
269778138e9SMichael Gottesman }
270