ObjCARCContract.cpp [plain text]
#include "ObjCARC.h"
#include "ARCRuntimeEntryPoints.h"
#include "DependencyAnalysis.h"
#include "ProvenanceAnalysis.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/InlineAsm.h"
#include "llvm/IR/Operator.h"
#include "llvm/Support/Debug.h"
using namespace llvm;
using namespace llvm::objcarc;
#define DEBUG_TYPE "objc-arc-contract"
STATISTIC(NumPeeps, "Number of calls peephole-optimized");
STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed");
namespace {
class ObjCARCContract : public FunctionPass {
bool Changed;
AliasAnalysis *AA;
DominatorTree *DT;
ProvenanceAnalysis PA;
ARCRuntimeEntryPoints EP;
bool Run;
const MDString *RVInstMarker;
SmallPtrSet<CallInst *, 8> StoreStrongCalls;
bool tryToPeepholeInstruction(Function &F, Instruction *Inst,
inst_iterator &Iter,
SmallPtrSetImpl<Instruction *> &DepInsts,
SmallPtrSetImpl<const BasicBlock *> &Visited,
bool &TailOkForStoreStrong);
bool optimizeRetainCall(Function &F, Instruction *Retain);
bool
contractAutorelease(Function &F, Instruction *Autorelease,
ARCInstKind Class,
SmallPtrSetImpl<Instruction *> &DependingInstructions,
SmallPtrSetImpl<const BasicBlock *> &Visited);
void tryToContractReleaseIntoStoreStrong(Instruction *Release,
inst_iterator &Iter);
void getAnalysisUsage(AnalysisUsage &AU) const override;
bool doInitialization(Module &M) override;
bool runOnFunction(Function &F) override;
public:
static char ID;
ObjCARCContract() : FunctionPass(ID) {
initializeObjCARCContractPass(*PassRegistry::getPassRegistry());
}
};
}
bool ObjCARCContract::optimizeRetainCall(Function &F, Instruction *Retain) {
ImmutableCallSite CS(GetArgRCIdentityRoot(Retain));
const Instruction *Call = CS.getInstruction();
if (!Call)
return false;
if (Call->getParent() != Retain->getParent())
return false;
BasicBlock::const_iterator I = Call;
++I;
while (IsNoopInstruction(I)) ++I;
if (&*I != Retain)
return false;
Changed = true;
++NumPeeps;
DEBUG(dbgs() << "Transforming objc_retain => "
"objc_retainAutoreleasedReturnValue since the operand is a "
"return value.\nOld: "<< *Retain << "\n");
Constant *Decl = EP.get(ARCRuntimeEntryPointKind::RetainRV);
cast<CallInst>(Retain)->setCalledFunction(Decl);
DEBUG(dbgs() << "New: " << *Retain << "\n");
return true;
}
bool ObjCARCContract::contractAutorelease(
Function &F, Instruction *Autorelease, ARCInstKind Class,
SmallPtrSetImpl<Instruction *> &DependingInstructions,
SmallPtrSetImpl<const BasicBlock *> &Visited) {
const Value *Arg = GetArgRCIdentityRoot(Autorelease);
CallInst *Retain = nullptr;
if (Class == ARCInstKind::AutoreleaseRV)
FindDependencies(RetainAutoreleaseRVDep, Arg,
Autorelease->getParent(), Autorelease,
DependingInstructions, Visited, PA);
else
FindDependencies(RetainAutoreleaseDep, Arg,
Autorelease->getParent(), Autorelease,
DependingInstructions, Visited, PA);
Visited.clear();
if (DependingInstructions.size() != 1) {
DependingInstructions.clear();
return false;
}
Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
DependingInstructions.clear();
if (!Retain || GetBasicARCInstKind(Retain) != ARCInstKind::Retain ||
GetArgRCIdentityRoot(Retain) != Arg)
return false;
Changed = true;
++NumPeeps;
DEBUG(dbgs() << " Fusing retain/autorelease!\n"
" Autorelease:" << *Autorelease << "\n"
" Retain: " << *Retain << "\n");
Constant *Decl = EP.get(Class == ARCInstKind::AutoreleaseRV
? ARCRuntimeEntryPointKind::RetainAutoreleaseRV
: ARCRuntimeEntryPointKind::RetainAutorelease);
Retain->setCalledFunction(Decl);
DEBUG(dbgs() << " New RetainAutorelease: " << *Retain << "\n");
EraseInstruction(Autorelease);
return true;
}
static StoreInst *findSafeStoreForStoreStrongContraction(LoadInst *Load,
Instruction *Release,
ProvenanceAnalysis &PA,
AliasAnalysis *AA) {
StoreInst *Store = nullptr;
bool SawRelease = false;
AliasAnalysis::Location Loc = AA->getLocation(Load);
for (auto I = std::next(BasicBlock::iterator(Load)),
E = Load->getParent()->end();
I != E; ++I) {
if (Store && SawRelease)
break;
Instruction *Inst = &*I;
if (Inst == Release) {
SawRelease = true;
continue;
}
ARCInstKind Class = GetBasicARCInstKind(Inst);
if (IsRetain(Class))
continue;
if (Store) {
if (!CanUse(Inst, Load, PA, Class)) {
continue;
}
return nullptr;
}
if (!(AA->getModRefInfo(Inst, Loc) & AliasAnalysis::Mod))
continue;
Store = dyn_cast<StoreInst>(Inst);
if (!Store || !Store->isSimple())
return nullptr;
if (Store->getPointerOperand() == Loc.Ptr)
continue;
return nullptr;
}
if (!Store || !SawRelease)
return nullptr;
return Store;
}
static Instruction *
findRetainForStoreStrongContraction(Value *New, StoreInst *Store,
Instruction *Release,
ProvenanceAnalysis &PA) {
BasicBlock::iterator I = Store;
BasicBlock::iterator Begin = Store->getParent()->begin();
while (I != Begin && GetBasicARCInstKind(I) != ARCInstKind::Retain) {
Instruction *Inst = &*I;
if (CanDecrementRefCount(Inst, New, PA) && Inst != Release)
return nullptr;
--I;
}
Instruction *Retain = I;
if (GetBasicARCInstKind(Retain) != ARCInstKind::Retain)
return nullptr;
if (GetArgRCIdentityRoot(Retain) != New)
return nullptr;
return Retain;
}
void ObjCARCContract::tryToContractReleaseIntoStoreStrong(Instruction *Release,
inst_iterator &Iter) {
auto *Load = dyn_cast<LoadInst>(GetArgRCIdentityRoot(Release));
if (!Load || !Load->isSimple())
return;
BasicBlock *BB = Release->getParent();
if (Load->getParent() != BB)
return;
StoreInst *Store =
findSafeStoreForStoreStrongContraction(Load, Release, PA, AA);
if (!Store)
return;
Value *New = GetRCIdentityRoot(Store->getValueOperand());
Instruction *Retain =
findRetainForStoreStrongContraction(New, Store, Release, PA);
if (!Retain)
return;
Changed = true;
++NumStoreStrongs;
DEBUG(
llvm::dbgs() << " Contracting retain, release into objc_storeStrong.\n"
<< " Old:\n"
<< " Store: " << *Store << "\n"
<< " Release: " << *Release << "\n"
<< " Retain: " << *Retain << "\n"
<< " Load: " << *Load << "\n");
LLVMContext &C = Release->getContext();
Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Type *I8XX = PointerType::getUnqual(I8X);
Value *Args[] = { Load->getPointerOperand(), New };
if (Args[0]->getType() != I8XX)
Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
if (Args[1]->getType() != I8X)
Args[1] = new BitCastInst(Args[1], I8X, "", Store);
Constant *Decl = EP.get(ARCRuntimeEntryPointKind::StoreStrong);
CallInst *StoreStrong = CallInst::Create(Decl, Args, "", Store);
StoreStrong->setDoesNotThrow();
StoreStrong->setDebugLoc(Store->getDebugLoc());
StoreStrongCalls.insert(StoreStrong);
DEBUG(llvm::dbgs() << " New Store Strong: " << *StoreStrong << "\n");
if (&*Iter == Store) ++Iter;
Store->eraseFromParent();
Release->eraseFromParent();
EraseInstruction(Retain);
if (Load->use_empty())
Load->eraseFromParent();
}
bool ObjCARCContract::tryToPeepholeInstruction(
Function &F, Instruction *Inst, inst_iterator &Iter,
SmallPtrSetImpl<Instruction *> &DependingInsts,
SmallPtrSetImpl<const BasicBlock *> &Visited,
bool &TailOkForStoreStrongs) {
ARCInstKind Class = GetBasicARCInstKind(Inst);
switch (Class) {
case ARCInstKind::FusedRetainAutorelease:
case ARCInstKind::FusedRetainAutoreleaseRV:
return false;
case ARCInstKind::Autorelease:
case ARCInstKind::AutoreleaseRV:
return contractAutorelease(F, Inst, Class, DependingInsts, Visited);
case ARCInstKind::Retain:
if (!optimizeRetainCall(F, Inst))
return false;
case ARCInstKind::RetainRV:
case ARCInstKind::ClaimRV: {
if (!RVInstMarker)
return false;
BasicBlock::iterator BBI = Inst;
BasicBlock *InstParent = Inst->getParent();
do {
if (&*BBI == InstParent->begin()) {
BasicBlock *Pred = InstParent->getSinglePredecessor();
if (!Pred)
goto decline_rv_optimization;
BBI = Pred->getTerminator();
break;
}
--BBI;
} while (IsNoopInstruction(BBI));
if (&*BBI == GetArgRCIdentityRoot(Inst)) {
DEBUG(dbgs() << "Adding inline asm marker for the return value "
"optimization.\n");
Changed = true;
InlineAsm *IA = InlineAsm::get(
FunctionType::get(Type::getVoidTy(Inst->getContext()),
false),
RVInstMarker->getString(),
"", true);
CallInst::Create(IA, "", Inst);
}
decline_rv_optimization:
return false;
}
case ARCInstKind::InitWeak: {
CallInst *CI = cast<CallInst>(Inst);
if (IsNullOrUndef(CI->getArgOperand(1))) {
Value *Null =
ConstantPointerNull::get(cast<PointerType>(CI->getType()));
Changed = true;
new StoreInst(Null, CI->getArgOperand(0), CI);
DEBUG(dbgs() << "OBJCARCContract: Old = " << *CI << "\n"
<< " New = " << *Null << "\n");
CI->replaceAllUsesWith(Null);
CI->eraseFromParent();
}
return true;
}
case ARCInstKind::Release:
tryToContractReleaseIntoStoreStrong(Inst, Iter);
return true;
case ARCInstKind::User:
if (isa<AllocaInst>(Inst))
TailOkForStoreStrongs = false;
return true;
case ARCInstKind::IntrinsicUser:
Inst->eraseFromParent();
return true;
default:
return true;
}
}
bool ObjCARCContract::runOnFunction(Function &F) {
if (!EnableARCOpts)
return false;
if (!Run)
return false;
Changed = false;
AA = &getAnalysis<AliasAnalysis>();
DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
PA.setAA(&getAnalysis<AliasAnalysis>());
DEBUG(llvm::dbgs() << "**** ObjCARC Contract ****\n");
bool TailOkForStoreStrongs =
!F.isVarArg() && !F.callsFunctionThatReturnsTwice();
SmallPtrSet<Instruction *, 4> DependingInstructions;
SmallPtrSet<const BasicBlock *, 4> Visited;
for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E;) {
Instruction *Inst = &*I++;
DEBUG(dbgs() << "Visiting: " << *Inst << "\n");
if (tryToPeepholeInstruction(F, Inst, I, DependingInstructions, Visited,
TailOkForStoreStrongs))
continue;
Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
for (;;) {
if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
break;
for (Value::use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
UI != UE; ) {
Use &U = *UI++;
unsigned OperandNo = U.getOperandNo();
if (DT->isReachableFromEntry(U) && DT->dominates(Inst, U)) {
Changed = true;
Instruction *Replacement = Inst;
Type *UseTy = U.get()->getType();
if (PHINode *PHI = dyn_cast<PHINode>(U.getUser())) {
unsigned ValNo = PHINode::getIncomingValueNumForOperand(OperandNo);
BasicBlock *BB = PHI->getIncomingBlock(ValNo);
if (Replacement->getType() != UseTy)
Replacement = new BitCastInst(Replacement, UseTy, "",
&BB->back());
for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
if (PHI->getIncomingBlock(i) == BB) {
if (UI != UE &&
&PHI->getOperandUse(
PHINode::getOperandNumForIncomingValue(i)) == &*UI)
++UI;
PHI->setIncomingValue(i, Replacement);
}
} else {
if (Replacement->getType() != UseTy)
Replacement = new BitCastInst(Replacement, UseTy, "",
cast<Instruction>(U.getUser()));
U.set(Replacement);
}
}
}
if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
Arg = BI->getOperand(0);
else if (isa<GEPOperator>(Arg) &&
cast<GEPOperator>(Arg)->hasAllZeroIndices())
Arg = cast<GEPOperator>(Arg)->getPointerOperand();
else if (isa<GlobalAlias>(Arg) &&
!cast<GlobalAlias>(Arg)->mayBeOverridden())
Arg = cast<GlobalAlias>(Arg)->getAliasee();
else
break;
}
}
if (TailOkForStoreStrongs)
for (CallInst *CI : StoreStrongCalls)
CI->setTailCall();
StoreStrongCalls.clear();
return Changed;
}
char ObjCARCContract::ID = 0;
INITIALIZE_PASS_BEGIN(ObjCARCContract, "objc-arc-contract",
"ObjC ARC contraction", false, false)
INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
INITIALIZE_PASS_END(ObjCARCContract, "objc-arc-contract",
"ObjC ARC contraction", false, false)
void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired<AliasAnalysis>();
AU.addRequired<DominatorTreeWrapperPass>();
AU.setPreservesCFG();
}
Pass *llvm::createObjCARCContractPass() { return new ObjCARCContract(); }
bool ObjCARCContract::doInitialization(Module &M) {
Run = ModuleHasARC(M);
if (!Run)
return false;
EP.Initialize(&M);
RVInstMarker = nullptr;
if (NamedMDNode *NMD =
M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker"))
if (NMD->getNumOperands() == 1) {
const MDNode *N = NMD->getOperand(0);
if (N->getNumOperands() == 1)
if (const MDString *S = dyn_cast<MDString>(N->getOperand(0)))
RVInstMarker = S;
}
return false;
}