45 #define DEBUG_TYPE "objc-arc-contract" 47 STATISTIC(NumPeeps,
"Number of calls peephole-optimized");
48 STATISTIC(NumStoreStrongs,
"Number objc_storeStrong calls formed");
51 cl::desc(
"Maximum basic block size to discover the dominance relation of " 52 "two instructions in the same basic block"),
cl::init(65535));
83 bool tryToPeepholeInstruction(
87 bool &TailOkForStoreStrong,
98 void tryToContractReleaseIntoStoreStrong(
103 bool doInitialization(
Module &M)
override;
141 dbgs() <<
"Transforming objc_retain => " 142 "objc_retainAutoreleasedReturnValue since the operand is a " 143 "return value.\nOld: " 149 cast<CallInst>(
Retain)->setCalledFunction(Decl);
156 bool ObjCARCContract::contractAutorelease(
168 DependingInstructions, Visited, PA);
172 DependingInstructions, Visited, PA);
175 if (DependingInstructions.size() != 1) {
176 DependingInstructions.clear();
180 Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
181 DependingInstructions.clear();
202 LLVM_DEBUG(
dbgs() <<
" New RetainAutorelease: " << *Retain <<
"\n");
213 bool SawRelease =
false;
225 if (Store && SawRelease)
231 if (Inst == Release) {
254 if (!
CanUse(Inst, Load, PA, Class)) {
287 if (!Store || !SawRelease)
326 if (!BlockColors.
empty()) {
328 assert(CV.
size() == 1 &&
"non-unique color for block!");
330 if (EHPad->isEHPad())
342 InsertBefore, BlockColors);
372 void ObjCARCContract::tryToContractReleaseIntoStoreStrong(
382 if (
Load->getParent() != BB)
409 llvm::dbgs() <<
" Contracting retain, release into objc_storeStrong.\n" 411 <<
" Store: " << *Store <<
"\n" 412 <<
" Release: " << *Release <<
"\n" 413 <<
" Retain: " << *Retain <<
"\n" 414 <<
" Load: " << *
Load <<
"\n");
421 if (Args[0]->
getType() != I8XX)
422 Args[0] =
new BitCastInst(Args[0], I8XX,
"", Store);
424 Args[1] =
new BitCastInst(Args[1], I8X,
"", Store);
433 StoreStrongCalls.insert(StoreStrong);
438 if (&*Iter == Retain) ++Iter;
439 if (&*Iter == Store) ++Iter;
443 if (
Load->use_empty())
444 Load->eraseFromParent();
447 bool ObjCARCContract::tryToPeepholeInstruction(
461 return contractAutorelease(F, Inst, Class, DependingInsts, Visited);
465 if (!optimizeRetainCall(F, Inst))
482 if (BBI == InstParent->
begin()) {
485 goto decline_rv_optimization;
493 LLVM_DEBUG(
dbgs() <<
"Adding inline asm marker for the return value " 499 RVInstMarker->getString(),
504 decline_rv_optimization:
509 CallInst *CI = cast<CallInst>(Inst);
516 <<
" New = " << *Null <<
"\n");
526 tryToContractReleaseIntoStoreStrong(Inst, Iter, BlockColors);
532 if (isa<AllocaInst>(Inst))
533 TailOkForStoreStrongs =
false;
557 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
558 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
560 PA.setAA(&getAnalysis<AAResultsWrapperPass>().getAAResults());
574 bool TailOkForStoreStrongs =
590 auto I = BBSizeMap.
find(BB);
592 if (I != BBSizeMap.
end())
595 BBSize = BBSizeMap[BB] = BB->
size();
607 if (tryToPeepholeInstruction(F, Inst, I, DependingInstructions, Visited,
608 TailOkForStoreStrongs, BlockColors))
617 auto ReplaceArgUses = [Inst, IsLargeBB,
this](
Value *
Arg) {
619 if (!isa<Instruction>(Arg) && !isa<Argument>(
Arg))
646 if (!DT->isReachableFromEntry(U) || !DT->dominates(Inst, U))
655 BasicBlock *IncomingBB = PHI->getIncomingBlock(ValNo);
656 if (Replacement->
getType() != UseTy) {
662 InsertBB = DT->getNode(InsertBB)->getIDom()->getBlock();
665 assert(DT->dominates(Inst, &InsertBB->
back()) &&
666 "Invalid insertion point for bitcast");
674 for (
unsigned i = 0,
e = PHI->getNumIncomingValues(); i !=
e; ++i)
675 if (PHI->getIncomingBlock(i) == IncomingBB) {
681 PHI->setIncomingValue(i, Replacement);
684 if (Replacement->
getType() != UseTy)
685 Replacement =
new BitCastInst(Replacement, UseTy,
"",
686 cast<Instruction>(U.
getUser()));
693 Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
701 if (
const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
702 Arg = BI->getOperand(0);
703 else if (isa<GEPOperator>(Arg) &&
704 cast<GEPOperator>(Arg)->hasAllZeroIndices())
706 else if (isa<GlobalAlias>(Arg) &&
707 !cast<GlobalAlias>(Arg)->isInterposable())
708 Arg = cast<GlobalAlias>(
Arg)->getAliasee();
712 if (
PHINode *PN = dyn_cast<PHINode>(Arg)) {
715 for (
Value *PHI : PHIList)
727 if (
auto *BC = dyn_cast<BitCastInst>(U))
731 while (!BitCastUsers.
empty()) {
734 if (
auto *
B = dyn_cast<BitCastInst>(U))
743 if (TailOkForStoreStrongs)
744 for (
CallInst *CI : StoreStrongCalls)
746 StoreStrongCalls.clear();
757 "ObjC ARC contraction",
false,
false)
763 void ObjCARCContract::getAnalysisUsage(
AnalysisUsage &AU)
const {
766 AU.setPreservesCFG();
771 bool ObjCARCContract::doInitialization(
Module &M) {
780 const char *MarkerKey =
"clang.arc.retainAutoreleasedReturnValueMarker";
781 RVInstMarker = dyn_cast_or_null<MDString>(M.
getModuleFlag(MarkerKey));
Pass interface - Implemented by all 'passes'.
bool isVarArg() const
isVarArg - Return true if this function takes a variable number of arguments.
Value * getValueOperand()
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
reference emplace_back(ArgTypes &&... Args)
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...
This file contains a class ARCRuntimeEntryPoints for use in creating/managing references to entry poi...
This class represents lattice values for constants.
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 re...
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Blocks objc_retainAutorelease.
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
void push_back(const T &Elt)
This class represents a function call, abstracting a target machine's calling convention.
static CallInst * createCallInst(FunctionType *FTy, Value *Func, ArrayRef< Value *> Args, const Twine &NameStr, Instruction *InsertBefore, const DenseMap< BasicBlock *, ColorVector > &BlockColors)
Create a call instruction with the correct funclet token.
Value * GetArgRCIdentityRoot(Value *Inst)
Assuming the given instruction is one of the special calls such as objc_retain or objc_release...
LLVMContext & getContext() const
All values hold a context through their type.
STATISTIC(NumFunctions, "Total number of functions")
An instruction for reading from memory.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
TinyPtrVector - This class is specialized for cases where there are normally 0 or 1 element in a vect...
iterator begin()
Instruction iterator methods.
Value * getArgOperand(unsigned i) const
static unsigned getOperandNumForIncomingValue(unsigned i)
#define INITIALIZE_PASS_DEPENDENCY(depName)
objc_autoreleaseReturnValue
static cl::opt< unsigned > MaxBBSize("arc-contract-max-bb-size", cl::Hidden, cl::desc("Maximum basic block size to discover the dominance relation of " "two instructions in the same basic block"), cl::init(65535))
inst_iterator inst_begin(Function *F)
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
A Use represents the edge between a Value definition and its users.
void initializeObjCARCContractPass(PassRegistry &)
bool IsNullOrUndef(const Value *V)
bool isScopedEHPersonality(EHPersonality Pers)
Returns true if this personality uses scope-style EH IR instructions: catchswitch, catchpad/ret, and cleanuppad/ret.
objc_retainAutoreleasedReturnValue
User * getUser() const LLVM_READONLY
Returns the User that contains this Use.
Class to represent function types.
Type * getType() const
All values are typed, get the type of this value.
void setCalledFunction(Function *Fn)
Sets the function called, including updating the function type.
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.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
An instruction for storing to memory.
bool hasPersonalityFn() const
Check whether this function has a personality function.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
unsigned getOperandNo() const
Return the operand # of this use in its User.
INITIALIZE_PASS_BEGIN(ObjCARCContract, "objc-arc-contract", "ObjC ARC contraction", false, false) INITIALIZE_PASS_END(ObjCARCContract
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.
use_iterator_impl< Use > use_iterator
iterator find(const_arg_type_t< KeyT > Val)
static bool runOnFunction(Function &F, bool PostInlining)
static MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
initializer< Ty > init(const Ty &Val)
const Instruction * getFirstNonPHI() const
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
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.
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
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.
Metadata * getModuleFlag(StringRef Key) const
Return the corresponding value if Key appears in module flags, otherwise return null.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
Represent the analysis usage information of a pass.
static Type * getVoidTy(LLVMContext &C)
const Instruction & back() const
FunctionPass class - This class is used to implement most global optimizations.
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
static FunctionType * get(Type *Result, ArrayRef< Type *> Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
self_iterator getIterator()
static Instruction * findRetainForStoreStrongContraction(Value *New, StoreInst *Store, Instruction *Release, ProvenanceAnalysis &PA)
const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
static unsigned getIncomingValueNumForOperand(unsigned i)
static wasm::ValType getType(const TargetRegisterClass *RC)
anything that is inert from an ARC perspective.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
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
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...
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.
objc_unsafeClaimAutoreleasedReturnValue
LLVM_NODISCARD T pop_back_val()
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
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...
iterator_range< user_iterator > users()
objc_storeStrong (derived)
bool IsRetain(ARCInstKind Class)
Test if the given class is objc_retain or equivalent.
LLVM_NODISCARD bool isModSet(const ModRefInfo MRI)
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_NODISCARD bool empty() const
Establish a view to a call site for examination.
Blocks objc_retainAutoreleaseReturnValue.
FunctionType * getFunctionType()
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.
const Value * getPointerOperand(const Value *V)
A helper function that returns the pointer operand of a load, store or GEP instruction.
objc_retainAutoreleaseReturnValue
LLVM_NODISCARD bool empty() const
bool callsFunctionThatReturnsTwice() const
callsFunctionThatReturnsTwice - Return true if the function has a call to setjmp or other function th...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
Constant * getPersonalityFn() const
Get the personality function associated with this function.
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
static const Function * getParent(const Value *V)
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...
ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc)
getModRefInfo (for call sites) - Return information about whether a particular call site modifies or ...
DenseMap< BasicBlock *, ColorVector > colorEHFunclets(Function &F)
If an EH funclet personality is in use (see isFuncletEHPersonality), this will recompute which blocks...
Value * getPointerOperand()
static IntegerType * getInt8Ty(LLVMContext &C)
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
void getEquivalentPHIs(PHINodeTy &PN, VectorTy &PHIList)
Return the list of PHI nodes that are equivalent to PN.
bool IsNoopInstruction(const Instruction *I)
const BasicBlock * getParent() const