41 using namespace llvm::objcarc;
43 #define DEBUG_TYPE "objc-arc-contract"
45 STATISTIC(NumPeeps,
"Number of calls peephole-optimized");
46 STATISTIC(NumStoreStrongs,
"Number objc_storeStrong calls formed");
81 bool &TailOkForStoreStrong);
95 bool doInitialization(
Module &M)
override;
132 DEBUG(
dbgs() <<
"Transforming objc_retain => "
133 "objc_retainAutoreleasedReturnValue since the operand is a "
134 "return value.\nOld: "<< *Retain <<
"\n");
139 cast<CallInst>(Retain)->setCalledFunction(Decl);
141 DEBUG(
dbgs() <<
"New: " << *Retain <<
"\n");
146 bool ObjCARCContract::contractAutorelease(
158 DependingInstructions, Visited, PA);
162 DependingInstructions, Visited, PA);
165 if (DependingInstructions.size() != 1) {
166 DependingInstructions.clear();
170 Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
171 DependingInstructions.clear();
180 DEBUG(
dbgs() <<
" Fusing retain/autorelease!\n"
181 " Autorelease:" << *Autorelease <<
"\n"
182 " Retain: " << *Retain <<
"\n");
189 DEBUG(
dbgs() <<
" New RetainAutorelease: " << *Retain <<
"\n");
200 bool SawRelease =
false;
212 if (Store && SawRelease)
218 if (Inst == Release) {
241 if (!
CanUse(Inst, Load, PA, Class)) {
274 if (!Store || !SawRelease)
333 void ObjCARCContract::tryToContractReleaseIntoStoreStrong(
Instruction *Release,
342 if (
Load->getParent() != BB)
369 llvm::dbgs() <<
" Contracting retain, release into objc_storeStrong.\n"
371 <<
" Store: " << *Store <<
"\n"
372 <<
" Release: " << *Release <<
"\n"
373 <<
" Retain: " << *Retain <<
"\n"
374 <<
" Load: " << *
Load <<
"\n");
381 if (Args[0]->
getType() != I8XX)
382 Args[0] =
new BitCastInst(Args[0], I8XX,
"", Store);
384 Args[1] =
new BitCastInst(Args[1], I8X,
"", Store);
393 StoreStrongCalls.insert(StoreStrong);
397 if (&*Iter == Store) ++Iter;
401 if (
Load->use_empty())
402 Load->eraseFromParent();
405 bool ObjCARCContract::tryToPeepholeInstruction(
409 bool &TailOkForStoreStrongs) {
419 return contractAutorelease(F, Inst, Class, DependingInsts, Visited);
423 if (!optimizeRetainCall(F, Inst))
440 if (BBI == InstParent->
begin()) {
443 goto decline_rv_optimization;
451 DEBUG(
dbgs() <<
"Adding inline asm marker for the return value "
457 RVInstMarker->getString(),
461 decline_rv_optimization:
466 CallInst *CI = cast<CallInst>(Inst);
473 DEBUG(
dbgs() <<
"OBJCARCContract: Old = " << *CI <<
"\n"
474 <<
" New = " << *Null <<
"\n");
484 tryToContractReleaseIntoStoreStrong(Inst, Iter);
490 if (isa<AllocaInst>(Inst))
491 TailOkForStoreStrongs =
false;
506 bool ObjCARCContract::runOnFunction(
Function &F) {
515 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
516 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
518 PA.setAA(&getAnalysis<AAResultsWrapperPass>().getAAResults());
527 bool TailOkForStoreStrongs =
538 DEBUG(
dbgs() <<
"Visiting: " << *Inst <<
"\n");
542 if (tryToPeepholeInstruction(F, Inst, I, DependingInstructions, Visited,
543 TailOkForStoreStrongs))
552 auto ReplaceArgUses = [Inst,
this](
Value *Arg) {
554 if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
570 if (DT->isReachableFromEntry(U) && DT->dominates(Inst, U)) {
577 BasicBlock *BB = PHI->getIncomingBlock(ValNo);
578 if (Replacement->
getType() != UseTy)
579 Replacement =
new BitCastInst(Replacement, UseTy,
"",
584 for (
unsigned i = 0, e = PHI->getNumIncomingValues();
i != e; ++
i)
585 if (PHI->getIncomingBlock(
i) == BB) {
591 PHI->setIncomingValue(
i, Replacement);
594 if (Replacement->
getType() != UseTy)
595 Replacement =
new BitCastInst(Replacement, UseTy,
"",
596 cast<Instruction>(U.
getUser()));
604 Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
605 Value *OrigArg = Arg;
612 if (
const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
613 Arg = BI->getOperand(0);
614 else if (isa<GEPOperator>(Arg) &&
615 cast<GEPOperator>(Arg)->hasAllZeroIndices())
617 else if (isa<GlobalAlias>(Arg) &&
618 !cast<GlobalAlias>(Arg)->isInterposable())
619 Arg = cast<GlobalAlias>(Arg)->getAliasee();
629 if (
auto *BC = dyn_cast<BitCastInst>(U))
633 while (!BitCastUsers.
empty()) {
636 if (
auto *
B = dyn_cast<BitCastInst>(U))
645 if (TailOkForStoreStrongs)
646 for (
CallInst *CI : StoreStrongCalls)
648 StoreStrongCalls.clear();
659 "ObjC ARC contraction",
false,
false)
665 void ObjCARCContract::getAnalysisUsage(
AnalysisUsage &AU)
const {
668 AU.setPreservesCFG();
673 bool ObjCARCContract::doInitialization(
Module &M) {
682 RVInstMarker =
nullptr;
685 if (NMD->getNumOperands() == 1) {
686 const MDNode *
N = NMD->getOperand(0);
Pass interface - Implemented by all 'passes'.
Value * getValueOperand()
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void push_back(const T &Elt)
use_iterator_impl< Use > use_iterator
This file declares special dependency analysis routines used in Objective C ARC Optimizations.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
const Instruction & back() const
This file contains a class ARCRuntimeEntryPoints for use in creating/managing references to entry poi...
STATISTIC(NumFunctions,"Total number of functions")
A Module instance is used to store all the information related to an LLVM module. ...
bool CanUse(const Instruction *Inst, const Value *Ptr, ProvenanceAnalysis &PA, ARCInstKind Class)
Test whether the given instruction can "use" the given pointer's object in a way that requires the ...
Blocks objc_retainAutorelease.
unsigned getNumOperands() const
Return number of MDNode operands.
This class represents a function call, abstracting a target machine's calling convention.
Value * GetArgRCIdentityRoot(Value *Inst)
Assuming the given instruction is one of the special calls such as objc_retain or objc_release...
An instruction for reading from memory.
FunctionType * getType(LLVMContext &Context, ID id, ArrayRef< Type * > Tys=None)
Return the function type for an intrinsic.
The access modifies the value stored in memory.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
iterator begin()
Instruction iterator methods.
static unsigned getOperandNumForIncomingValue(unsigned i)
#define INITIALIZE_PASS_DEPENDENCY(depName)
objc_autoreleaseReturnValue
static Value * getPointerOperand(Instruction &Inst)
inst_iterator inst_begin(Function *F)
A Use represents the edge between a Value definition and its users.
void initializeObjCARCContractPass(PassRegistry &)
bool IsNullOrUndef(const Value *V)
LLVM_NODISCARD bool empty() const
INITIALIZE_PASS_BEGIN(ObjCARCContract,"objc-arc-contract","ObjC ARC contraction", false, false) INITIALIZE_PASS_END(ObjCARCContract
objc_retainAutoreleasedReturnValue
Pass * createObjCARCContractPass()
bool EnableARCOpts
A handy option to enable/disable all ARC Optimizations.
This class represents a no-op cast from one type to another.
static FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
static GCRegistry::Add< OcamlGC > B("ocaml","ocaml 3.10-compatible GC")
An instruction for storing to memory.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
bool ModuleHasARC(const Module &M)
Test if the given module looks interesting to run ARC optimization on.
static GCRegistry::Add< CoreCLRGC > E("coreclr","CoreCLR-compatible GC")
static MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
static StoreInst * findSafeStoreForStoreStrongContraction(LoadInst *Load, Instruction *Release, ProvenanceAnalysis &PA, AliasAnalysis *AA)
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
static ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
unsigned getOperandNo() const
Return the operand # of this use in its User.
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
This is an important class for using LLVM in a threaded context.
This is an important base class in LLVM.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Represent the analysis usage information of a pass.
static Type * getVoidTy(LLVMContext &C)
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
User * getUser() const
Returns the User that contains this Use.
FunctionPass class - This class is used to implement most global optimizations.
self_iterator getIterator()
static Instruction * findRetainForStoreStrongContraction(Value *New, StoreInst *Store, Instruction *Release, ProvenanceAnalysis &PA)
void setTailCall(bool isTC=true)
LLVMContext & getContext() const
All values hold a context through their type.
static unsigned getIncomingValueNumForOperand(unsigned i)
ARCInstKind GetBasicARCInstKind(const Value *V)
Determine which objc runtime call instruction class V belongs to.
bool CanDecrementRefCount(ARCInstKind Kind)
Returns false if conservatively we can prove that any instruction mapped to this kind can not decreme...
const Value * Ptr
The address of the start of the location.
Representation for a specific memory location.
static void EraseInstruction(Instruction *CI)
Erase the given instruction.
objc arc ObjC ARC contraction
const MDOperand & getOperand(unsigned I) const
Iterator for intrusive lists based on ilist_node.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the generic address space (address sp...
static CallInst * Create(Value *Func, ArrayRef< Value * > Args, ArrayRef< OperandBundleDef > Bundles=None, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
This file declares a special form of Alias Analysis called ``Provenance Analysis''.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
ARCInstKind
Equivalence classes of instructions in the ARC Model.
Type * getType() const
All values are typed, get the type of this value.
objc_unsafeClaimAutoreleasedReturnValue
LLVM_NODISCARD T pop_back_val()
Value * stripPointerCasts()
Strip off pointer casts, all-zero GEPs, and aliases.
static GCRegistry::Add< ShadowStackGC > C("shadow-stack","Very portable GC for uncooperative code generators")
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Value * getArgOperand(unsigned i) const
getArgOperand/setArgOperand - Return/set the i-th call argument.
ModRefInfo getModRefInfo(ImmutableCallSite CS, const MemoryLocation &Loc)
getModRefInfo (for call sites) - Return information about whether a particular call site modifies or ...
iterator_range< user_iterator > users()
BasicBlock * getSinglePredecessor()
Return the predecessor of this block if it has a single predecessor block.
objc_storeStrong (derived)
bool IsRetain(ARCInstKind Class)
Test if the given class is objc_retain or equivalent.
void setCalledFunction(Value *Fn)
Set the function called.
NamedMDNode * getNamedMetadata(const Twine &Name) const
Return the first NamedMDNode in the module with the specified name.
ImmutableCallSite - establish a view to a call site for examination.
Blocks objc_retainAutoreleaseReturnValue.
TerminatorInst * getTerminator()
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
bool callsFunctionThatReturnsTwice() const
callsFunctionThatReturnsTwice - Return true if the function has a call to setjmp or other function th...
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Declarations for ObjC runtime functions and constants.
static InlineAsm * get(FunctionType *Ty, StringRef AsmString, StringRef Constraints, bool hasSideEffects, bool isAlignStack=false, AsmDialect asmDialect=AD_ATT)
InlineAsm::get - Return the specified uniqued inline asm string.
objc_retainAutoreleaseReturnValue
LLVM Value Representation.
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
This is similar to BasicAliasAnalysis, and it uses many of the same techniques, except it uses specia...
const Value * GetRCIdentityRoot(const Value *V)
The RCIdentity root of a value V is a dominating value U for which retaining or releasing U is equiva...
inst_iterator inst_end(Function *F)
Legacy analysis pass which computes a DominatorTree.
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
bool isVarArg() const
isVarArg - Return true if this function takes a variable number of arguments.
void FindDependencies(DependenceKind Flavor, const Value *Arg, BasicBlock *StartBB, Instruction *StartInst, SmallPtrSetImpl< Instruction * > &DependingInstructions, SmallPtrSetImpl< const BasicBlock * > &Visited, ProvenanceAnalysis &PA)
Walk up the CFG from StartPos (which is in StartBB) and find local and non-local dependencies on Arg...
Value * getPointerOperand()
static IntegerType * getInt8Ty(LLVMContext &C)
const BasicBlock * getParent() const
bool IsNoopInstruction(const Instruction *I)