#include "ARCRuntimeEntryPoints.h"
#include "BlotMapVector.h"
#include "DependencyAnalysis.h"
#include "ObjCARC.h"
#include "ProvenanceAnalysis.h"
#include "PtrState.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/None.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Analysis/EHPersonalities.h"
#include "llvm/Analysis/ObjCARCAliasAnalysis.h"
#include "llvm/Analysis/ObjCARCAnalysisUtils.h"
#include "llvm/Analysis/ObjCARCInstKind.h"
#include "llvm/Analysis/ObjCARCUtil.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/CFG.h"
#include "llvm/IR/Constant.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/InstrTypes.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/User.h"
#include "llvm/IR/Value.h"
#include "llvm/InitializePasses.h"
#include "llvm/Pass.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/ObjCARC.h"
#include <cassert>
#include <iterator>
#include <utility>
using namespace llvm;
using namespace llvm::objcarc;
#define DEBUG_TYPE "objc-arc-opts"
static cl::opt<unsigned> MaxPtrStates("arc-opt-max-ptr-states",
cl::Hidden,
cl::desc("Maximum number of ptr states the optimizer keeps track of"),
cl::init(4095));
static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
if (isa<ConstantData>(Arg))
return nullptr;
if (Arg->hasOneUse()) {
if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
return FindSingleUseIdentifiedObject(BC->getOperand(0));
if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
if (GEP->hasAllZeroIndices())
return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
if (IsForwarding(GetBasicARCInstKind(Arg)))
return FindSingleUseIdentifiedObject(
cast<CallInst>(Arg)->getArgOperand(0));
if (!IsObjCIdentifiedObject(Arg))
return nullptr;
return Arg;
}
if (IsObjCIdentifiedObject(Arg)) {
for (const User *U : Arg->users())
if (!U->use_empty() || GetRCIdentityRoot(U) != Arg)
return nullptr;
return Arg;
}
return nullptr;
}
STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
STATISTIC(NumRets, "Number of return value forwarding "
"retain+autoreleases eliminated");
STATISTIC(NumRRs, "Number of retain+release paths eliminated");
STATISTIC(NumPeeps, "Number of calls peephole-optimized");
#ifndef NDEBUG
STATISTIC(NumRetainsBeforeOpt,
"Number of retains before optimization");
STATISTIC(NumReleasesBeforeOpt,
"Number of releases before optimization");
STATISTIC(NumRetainsAfterOpt,
"Number of retains after optimization");
STATISTIC(NumReleasesAfterOpt,
"Number of releases after optimization");
#endif
namespace {
class BBState {
unsigned TopDownPathCount = 0;
unsigned BottomUpPathCount = 0;
BlotMapVector<const Value *, TopDownPtrState> PerPtrTopDown;
BlotMapVector<const Value *, BottomUpPtrState> PerPtrBottomUp;
SmallVector<BasicBlock *, 2> Preds;
SmallVector<BasicBlock *, 2> Succs;
public:
static const unsigned OverflowOccurredValue;
BBState() = default;
using top_down_ptr_iterator = decltype(PerPtrTopDown)::iterator;
using const_top_down_ptr_iterator = decltype(PerPtrTopDown)::const_iterator;
top_down_ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
top_down_ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
const_top_down_ptr_iterator top_down_ptr_begin() const {
return PerPtrTopDown.begin();
}
const_top_down_ptr_iterator top_down_ptr_end() const {
return PerPtrTopDown.end();
}
bool hasTopDownPtrs() const {
return !PerPtrTopDown.empty();
}
unsigned top_down_ptr_list_size() const {
return std::distance(top_down_ptr_begin(), top_down_ptr_end());
}
using bottom_up_ptr_iterator = decltype(PerPtrBottomUp)::iterator;
using const_bottom_up_ptr_iterator =
decltype(PerPtrBottomUp)::const_iterator;
bottom_up_ptr_iterator bottom_up_ptr_begin() {
return PerPtrBottomUp.begin();
}
bottom_up_ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
const_bottom_up_ptr_iterator bottom_up_ptr_begin() const {
return PerPtrBottomUp.begin();
}
const_bottom_up_ptr_iterator bottom_up_ptr_end() const {
return PerPtrBottomUp.end();
}
bool hasBottomUpPtrs() const {
return !PerPtrBottomUp.empty();
}
unsigned bottom_up_ptr_list_size() const {
return std::distance(bottom_up_ptr_begin(), bottom_up_ptr_end());
}
void SetAsEntry() { TopDownPathCount = 1; }
void SetAsExit() { BottomUpPathCount = 1; }
TopDownPtrState &getPtrTopDownState(const Value *Arg) {
return PerPtrTopDown[Arg];
}
BottomUpPtrState &getPtrBottomUpState(const Value *Arg) {
return PerPtrBottomUp[Arg];
}
bottom_up_ptr_iterator findPtrBottomUpState(const Value *Arg) {
return PerPtrBottomUp.find(Arg);
}
void clearBottomUpPointers() {
PerPtrBottomUp.clear();
}
void clearTopDownPointers() {
PerPtrTopDown.clear();
}
void InitFromPred(const BBState &Other);
void InitFromSucc(const BBState &Other);
void MergePred(const BBState &Other);
void MergeSucc(const BBState &Other);
bool GetAllPathCountWithOverflow(unsigned &PathCount) const {
if (TopDownPathCount == OverflowOccurredValue ||
BottomUpPathCount == OverflowOccurredValue)
return true;
unsigned long long Product =
(unsigned long long)TopDownPathCount*BottomUpPathCount;
return (Product >> 32) ||
((PathCount = Product) == OverflowOccurredValue);
}
using edge_iterator = SmallVectorImpl<BasicBlock *>::const_iterator;
edge_iterator pred_begin() const { return Preds.begin(); }
edge_iterator pred_end() const { return Preds.end(); }
edge_iterator succ_begin() const { return Succs.begin(); }
edge_iterator succ_end() const { return Succs.end(); }
void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
bool isExit() const { return Succs.empty(); }
};
}
const unsigned BBState::OverflowOccurredValue = 0xffffffff;
namespace llvm {
raw_ostream &operator<<(raw_ostream &OS,
BBState &BBState) LLVM_ATTRIBUTE_UNUSED;
}
void BBState::InitFromPred(const BBState &Other) {
PerPtrTopDown = Other.PerPtrTopDown;
TopDownPathCount = Other.TopDownPathCount;
}
void BBState::InitFromSucc(const BBState &Other) {
PerPtrBottomUp = Other.PerPtrBottomUp;
BottomUpPathCount = Other.BottomUpPathCount;
}
void BBState::MergePred(const BBState &Other) {
if (TopDownPathCount == OverflowOccurredValue)
return;
TopDownPathCount += Other.TopDownPathCount;
if (TopDownPathCount == OverflowOccurredValue) {
clearTopDownPointers();
return;
}
if (TopDownPathCount < Other.TopDownPathCount) {
TopDownPathCount = OverflowOccurredValue;
clearTopDownPointers();
return;
}
for (auto MI = Other.top_down_ptr_begin(), ME = Other.top_down_ptr_end();
MI != ME; ++MI) {
auto Pair = PerPtrTopDown.insert(*MI);
Pair.first->second.Merge(Pair.second ? TopDownPtrState() : MI->second,
true);
}
for (auto MI = top_down_ptr_begin(), ME = top_down_ptr_end(); MI != ME; ++MI)
if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
MI->second.Merge(TopDownPtrState(), true);
}
void BBState::MergeSucc(const BBState &Other) {
if (BottomUpPathCount == OverflowOccurredValue)
return;
BottomUpPathCount += Other.BottomUpPathCount;
if (BottomUpPathCount == OverflowOccurredValue) {
clearBottomUpPointers();
return;
}
if (BottomUpPathCount < Other.BottomUpPathCount) {
BottomUpPathCount = OverflowOccurredValue;
clearBottomUpPointers();
return;
}
for (auto MI = Other.bottom_up_ptr_begin(), ME = Other.bottom_up_ptr_end();
MI != ME; ++MI) {
auto Pair = PerPtrBottomUp.insert(*MI);
Pair.first->second.Merge(Pair.second ? BottomUpPtrState() : MI->second,
false);
}
for (auto MI = bottom_up_ptr_begin(), ME = bottom_up_ptr_end(); MI != ME;
++MI)
if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
MI->second.Merge(BottomUpPtrState(), false);
}
raw_ostream &llvm::operator<<(raw_ostream &OS, BBState &BBInfo) {
OS << " TopDown State:\n";
if (!BBInfo.hasTopDownPtrs()) {
LLVM_DEBUG(dbgs() << " NONE!\n");
} else {
for (auto I = BBInfo.top_down_ptr_begin(), E = BBInfo.top_down_ptr_end();
I != E; ++I) {
const PtrState &P = I->second;
OS << " Ptr: " << *I->first
<< "\n KnownSafe: " << (P.IsKnownSafe()?"true":"false")
<< "\n ImpreciseRelease: "
<< (P.IsTrackingImpreciseReleases()?"true":"false") << "\n"
<< " HasCFGHazards: "
<< (P.IsCFGHazardAfflicted()?"true":"false") << "\n"
<< " KnownPositive: "
<< (P.HasKnownPositiveRefCount()?"true":"false") << "\n"
<< " Seq: "
<< P.GetSeq() << "\n";
}
}
OS << " BottomUp State:\n";
if (!BBInfo.hasBottomUpPtrs()) {
LLVM_DEBUG(dbgs() << " NONE!\n");
} else {
for (auto I = BBInfo.bottom_up_ptr_begin(), E = BBInfo.bottom_up_ptr_end();
I != E; ++I) {
const PtrState &P = I->second;
OS << " Ptr: " << *I->first
<< "\n KnownSafe: " << (P.IsKnownSafe()?"true":"false")
<< "\n ImpreciseRelease: "
<< (P.IsTrackingImpreciseReleases()?"true":"false") << "\n"
<< " HasCFGHazards: "
<< (P.IsCFGHazardAfflicted()?"true":"false") << "\n"
<< " KnownPositive: "
<< (P.HasKnownPositiveRefCount()?"true":"false") << "\n"
<< " Seq: "
<< P.GetSeq() << "\n";
}
}
return OS;
}
namespace {
class ObjCARCOpt {
bool Changed;
bool CFGChanged;
ProvenanceAnalysis PA;
ARCRuntimeEntryPoints EP;
ARCMDKindCache MDKindCache;
BundledRetainClaimRVs *BundledInsts = nullptr;
bool DisableRetainReleasePairing = false;
unsigned UsedInThisFunction;
bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
ARCInstKind &Class);
void OptimizeIndividualCalls(Function &F);
void OptimizeIndividualCallImpl(
Function &F, DenseMap<BasicBlock *, ColorVector> &BlockColors,
Instruction *Inst, ARCInstKind Class, const Value *Arg);
bool OptimizeInlinedAutoreleaseRVCall(
Function &F, DenseMap<BasicBlock *, ColorVector> &BlockColors,
Instruction *Inst, const Value *&Arg, ARCInstKind Class,
Instruction *AutoreleaseRV, const Value *&AutoreleaseRVArg);
void CheckForCFGHazards(const BasicBlock *BB,
DenseMap<const BasicBlock *, BBState> &BBStates,
BBState &MyStates) const;
bool VisitInstructionBottomUp(Instruction *Inst, BasicBlock *BB,
BlotMapVector<Value *, RRInfo> &Retains,
BBState &MyStates);
bool VisitBottomUp(BasicBlock *BB,
DenseMap<const BasicBlock *, BBState> &BBStates,
BlotMapVector<Value *, RRInfo> &Retains);
bool VisitInstructionTopDown(
Instruction *Inst, DenseMap<Value *, RRInfo> &Releases, BBState &MyStates,
const DenseMap<const Instruction *, SmallPtrSet<const Value *, 2>>
&ReleaseInsertPtToRCIdentityRoots);
bool VisitTopDown(
BasicBlock *BB, DenseMap<const BasicBlock *, BBState> &BBStates,
DenseMap<Value *, RRInfo> &Releases,
const DenseMap<const Instruction *, SmallPtrSet<const Value *, 2>>
&ReleaseInsertPtToRCIdentityRoots);
bool Visit(Function &F, DenseMap<const BasicBlock *, BBState> &BBStates,
BlotMapVector<Value *, RRInfo> &Retains,
DenseMap<Value *, RRInfo> &Releases);
void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
BlotMapVector<Value *, RRInfo> &Retains,
DenseMap<Value *, RRInfo> &Releases,
SmallVectorImpl<Instruction *> &DeadInsts, Module *M);
bool PairUpRetainsAndReleases(DenseMap<const BasicBlock *, BBState> &BBStates,
BlotMapVector<Value *, RRInfo> &Retains,
DenseMap<Value *, RRInfo> &Releases, Module *M,
Instruction *Retain,
SmallVectorImpl<Instruction *> &DeadInsts,
RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
Value *Arg, bool KnownSafe,
bool &AnyPairsCompletelyEliminated);
bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
BlotMapVector<Value *, RRInfo> &Retains,
DenseMap<Value *, RRInfo> &Releases, Module *M);
void OptimizeWeakCalls(Function &F);
bool OptimizeSequences(Function &F);
void OptimizeReturns(Function &F);
#ifndef NDEBUG
void GatherStatistics(Function &F, bool AfterOptimization = false);
#endif
public:
void init(Module &M);
bool run(Function &F, AAResults &AA);
void releaseMemory();
bool hasCFGChanged() const { return CFGChanged; }
};
class ObjCARCOptLegacyPass : public FunctionPass {
public:
ObjCARCOptLegacyPass() : FunctionPass(ID) {
initializeObjCARCOptLegacyPassPass(*PassRegistry::getPassRegistry());
}
void getAnalysisUsage(AnalysisUsage &AU) const override;
bool doInitialization(Module &M) override {
OCAO.init(M);
return false;
}
bool runOnFunction(Function &F) override {
return OCAO.run(F, getAnalysis<AAResultsWrapperPass>().getAAResults());
}
void releaseMemory() override { OCAO.releaseMemory(); }
static char ID;
private:
ObjCARCOpt OCAO;
};
}
char ObjCARCOptLegacyPass::ID = 0;
INITIALIZE_PASS_BEGIN(ObjCARCOptLegacyPass, "objc-arc", "ObjC ARC optimization",
false, false)
INITIALIZE_PASS_DEPENDENCY(ObjCARCAAWrapperPass)
INITIALIZE_PASS_END(ObjCARCOptLegacyPass, "objc-arc", "ObjC ARC optimization",
false, false)
Pass *llvm::createObjCARCOptPass() { return new ObjCARCOptLegacyPass(); }
void ObjCARCOptLegacyPass::getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired<ObjCARCAAWrapperPass>();
AU.addRequired<AAResultsWrapperPass>();
}
bool
ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
const Value *Arg = GetArgRCIdentityRoot(RetainRV);
if (const Instruction *Call = dyn_cast<CallBase>(Arg)) {
if (Call->getParent() == RetainRV->getParent()) {
BasicBlock::const_iterator I(Call);
++I;
while (IsNoopInstruction(&*I))
++I;
if (&*I == RetainRV)
return false;
} else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
BasicBlock *RetainRVParent = RetainRV->getParent();
if (II->getNormalDest() == RetainRVParent) {
BasicBlock::const_iterator I = RetainRVParent->begin();
while (IsNoopInstruction(&*I))
++I;
if (&*I == RetainRV)
return false;
}
}
}
assert(!BundledInsts->contains(RetainRV) &&
"a bundled retainRV's argument should be a call");
Changed = true;
++NumPeeps;
LLVM_DEBUG(dbgs() << "Transforming objc_retainAutoreleasedReturnValue => "
"objc_retain since the operand is not a return value.\n"
"Old = "
<< *RetainRV << "\n");
Function *NewDecl = EP.get(ARCRuntimeEntryPointKind::Retain);
cast<CallInst>(RetainRV)->setCalledFunction(NewDecl);
LLVM_DEBUG(dbgs() << "New = " << *RetainRV << "\n");
return false;
}
bool ObjCARCOpt::OptimizeInlinedAutoreleaseRVCall(
Function &F, DenseMap<BasicBlock *, ColorVector> &BlockColors,
Instruction *Inst, const Value *&Arg, ARCInstKind Class,
Instruction *AutoreleaseRV, const Value *&AutoreleaseRVArg) {
if (BundledInsts->contains(Inst))
return false;
assert(Inst->getParent() == AutoreleaseRV->getParent());
Arg = GetArgRCIdentityRoot(Inst);
AutoreleaseRVArg = GetArgRCIdentityRoot(AutoreleaseRV);
if (Arg != AutoreleaseRVArg) {
const PHINode *PN = dyn_cast<PHINode>(Arg);
if (!PN)
return false;
SmallVector<const Value *, 4> ArgUsers;
getEquivalentPHIs(*PN, ArgUsers);
if (!llvm::is_contained(ArgUsers, AutoreleaseRVArg))
return false;
}
++NumPeeps;
LLVM_DEBUG(dbgs() << "Found inlined objc_autoreleaseReturnValue '"
<< *AutoreleaseRV << "' paired with '" << *Inst << "'\n");
AutoreleaseRV->replaceAllUsesWith(
cast<CallInst>(AutoreleaseRV)->getArgOperand(0));
Changed = true;
EraseInstruction(AutoreleaseRV);
if (Class == ARCInstKind::RetainRV) {
Inst->replaceAllUsesWith(cast<CallInst>(Inst)->getArgOperand(0));
EraseInstruction(Inst);
return true;
}
assert(Class == ARCInstKind::UnsafeClaimRV);
Value *CallArg = cast<CallInst>(Inst)->getArgOperand(0);
CallInst *Release = CallInst::Create(
EP.get(ARCRuntimeEntryPointKind::Release), CallArg, "", Inst);
assert(IsAlwaysTail(ARCInstKind::UnsafeClaimRV) &&
"Expected UnsafeClaimRV to be safe to tail call");
Release->setTailCall();
Inst->replaceAllUsesWith(CallArg);
EraseInstruction(Inst);
OptimizeIndividualCallImpl(F, BlockColors, Release, ARCInstKind::Release,
Arg);
return true;
}
void ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F,
Instruction *AutoreleaseRV,
ARCInstKind &Class) {
const Value *Ptr = GetArgRCIdentityRoot(AutoreleaseRV);
if (isa<ConstantData>(Ptr))
return;
SmallVector<const Value *, 2> Users;
Users.push_back(Ptr);
if (const PHINode *PN = dyn_cast<PHINode>(Ptr))
getEquivalentPHIs(*PN, Users);
do {
Ptr = Users.pop_back_val();
for (const User *U : Ptr->users()) {
if (isa<ReturnInst>(U) || GetBasicARCInstKind(U) == ARCInstKind::RetainRV)
return;
if (isa<BitCastInst>(U))
Users.push_back(U);
}
} while (!Users.empty());
Changed = true;
++NumPeeps;
LLVM_DEBUG(
dbgs() << "Transforming objc_autoreleaseReturnValue => "
"objc_autorelease since its operand is not used as a return "
"value.\n"
"Old = "
<< *AutoreleaseRV << "\n");
CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
Function *NewDecl = EP.get(ARCRuntimeEntryPointKind::Autorelease);
AutoreleaseRVCI->setCalledFunction(NewDecl);
AutoreleaseRVCI->setTailCall(false); Class = ARCInstKind::Autorelease;
LLVM_DEBUG(dbgs() << "New: " << *AutoreleaseRV << "\n");
}
namespace {
Instruction *
CloneCallInstForBB(CallInst &CI, BasicBlock &BB,
const DenseMap<BasicBlock *, ColorVector> &BlockColors) {
SmallVector<OperandBundleDef, 1> OpBundles;
for (unsigned I = 0, E = CI.getNumOperandBundles(); I != E; ++I) {
auto Bundle = CI.getOperandBundleAt(I);
if (Bundle.getTagID() == LLVMContext::OB_funclet)
continue;
OpBundles.emplace_back(Bundle);
}
if (!BlockColors.empty()) {
const ColorVector &CV = BlockColors.find(&BB)->second;
assert(CV.size() == 1 && "non-unique color for block!");
Instruction *EHPad = CV.front()->getFirstNonPHI();
if (EHPad->isEHPad())
OpBundles.emplace_back("funclet", EHPad);
}
return CallInst::Create(&CI, OpBundles);
}
}
void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
LLVM_DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeIndividualCalls ==\n");
UsedInThisFunction = 0;
DenseMap<BasicBlock *, ColorVector> BlockColors;
if (F.hasPersonalityFn() &&
isScopedEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
BlockColors = colorEHFunclets(F);
Instruction *DelayedAutoreleaseRV = nullptr;
const Value *DelayedAutoreleaseRVArg = nullptr;
auto setDelayedAutoreleaseRV = [&](Instruction *AutoreleaseRV) {
assert(!DelayedAutoreleaseRV || !AutoreleaseRV);
DelayedAutoreleaseRV = AutoreleaseRV;
DelayedAutoreleaseRVArg = nullptr;
};
auto optimizeDelayedAutoreleaseRV = [&]() {
if (!DelayedAutoreleaseRV)
return;
OptimizeIndividualCallImpl(F, BlockColors, DelayedAutoreleaseRV,
ARCInstKind::AutoreleaseRV,
DelayedAutoreleaseRVArg);
setDelayedAutoreleaseRV(nullptr);
};
auto shouldDelayAutoreleaseRV = [&](Instruction *NonARCInst) {
if (!DelayedAutoreleaseRV)
return true;
if (NonARCInst->isTerminator())
return false;
auto *CB = dyn_cast<CallBase>(NonARCInst);
if (!CB)
return true;
return CB->getIntrinsicID() != Intrinsic::not_intrinsic;
};
for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
Instruction *Inst = &*I++;
if (auto *CI = dyn_cast<CallInst>(Inst))
if (objcarc::hasAttachedCallOpBundle(CI)) {
BundledInsts->insertRVCall(&*I, CI);
Changed = true;
}
ARCInstKind Class = GetBasicARCInstKind(Inst);
const Value *Arg = nullptr;
switch (Class) {
default:
optimizeDelayedAutoreleaseRV();
break;
case ARCInstKind::CallOrUser:
case ARCInstKind::User:
case ARCInstKind::None:
if (!shouldDelayAutoreleaseRV(Inst))
optimizeDelayedAutoreleaseRV();
continue;
case ARCInstKind::AutoreleaseRV:
optimizeDelayedAutoreleaseRV();
setDelayedAutoreleaseRV(Inst);
continue;
case ARCInstKind::RetainRV:
case ARCInstKind::UnsafeClaimRV:
if (DelayedAutoreleaseRV) {
if (OptimizeInlinedAutoreleaseRVCall(F, BlockColors, Inst, Arg, Class,
DelayedAutoreleaseRV,
DelayedAutoreleaseRVArg)) {
setDelayedAutoreleaseRV(nullptr);
continue;
}
optimizeDelayedAutoreleaseRV();
}
break;
}
OptimizeIndividualCallImpl(F, BlockColors, Inst, Class, Arg);
}
optimizeDelayedAutoreleaseRV();
}
static bool isInertARCValue(Value *V, SmallPtrSet<Value *, 1> &VisitedPhis) {
V = V->stripPointerCasts();
if (IsNullOrUndef(V))
return true;
if (auto *GV = dyn_cast<GlobalVariable>(V))
if (GV->hasAttribute("objc_arc_inert"))
return true;
if (auto PN = dyn_cast<PHINode>(V)) {
if (!VisitedPhis.insert(PN).second)
return true;
for (Value *Opnd : PN->incoming_values())
if (!isInertARCValue(Opnd, VisitedPhis))
return false;
return true;
}
return false;
}
void ObjCARCOpt::OptimizeIndividualCallImpl(
Function &F, DenseMap<BasicBlock *, ColorVector> &BlockColors,
Instruction *Inst, ARCInstKind Class, const Value *Arg) {
LLVM_DEBUG(dbgs() << "Visiting: Class: " << Class << "; " << *Inst << "\n");
SmallPtrSet<Value *, 1> VisitedPhis;
if (BundledInsts->contains(Inst)) {
UsedInThisFunction |= 1 << unsigned(Class);
return;
}
if (IsNoopOnGlobal(Class))
if (isInertARCValue(Inst->getOperand(0), VisitedPhis)) {
if (!Inst->getType()->isVoidTy())
Inst->replaceAllUsesWith(Inst->getOperand(0));
Inst->eraseFromParent();
Changed = true;
return;
}
switch (Class) {
default:
break;
case ARCInstKind::NoopCast:
Changed = true;
++NumNoops;
LLVM_DEBUG(dbgs() << "Erasing no-op cast: " << *Inst << "\n");
EraseInstruction(Inst);
return;
case ARCInstKind::StoreWeak:
case ARCInstKind::LoadWeak:
case ARCInstKind::LoadWeakRetained:
case ARCInstKind::InitWeak:
case ARCInstKind::DestroyWeak: {
CallInst *CI = cast<CallInst>(Inst);
if (IsNullOrUndef(CI->getArgOperand(0))) {
Changed = true;
new StoreInst(ConstantInt::getTrue(CI->getContext()),
UndefValue::get(Type::getInt1PtrTy(CI->getContext())), CI);
Value *NewValue = UndefValue::get(CI->getType());
LLVM_DEBUG(
dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
"\nOld = "
<< *CI << "\nNew = " << *NewValue << "\n");
CI->replaceAllUsesWith(NewValue);
CI->eraseFromParent();
return;
}
break;
}
case ARCInstKind::CopyWeak:
case ARCInstKind::MoveWeak: {
CallInst *CI = cast<CallInst>(Inst);
if (IsNullOrUndef(CI->getArgOperand(0)) ||
IsNullOrUndef(CI->getArgOperand(1))) {
Changed = true;
new StoreInst(ConstantInt::getTrue(CI->getContext()),
UndefValue::get(Type::getInt1PtrTy(CI->getContext())), CI);
Value *NewValue = UndefValue::get(CI->getType());
LLVM_DEBUG(
dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
"\nOld = "
<< *CI << "\nNew = " << *NewValue << "\n");
CI->replaceAllUsesWith(NewValue);
CI->eraseFromParent();
return;
}
break;
}
case ARCInstKind::RetainRV:
if (OptimizeRetainRVCall(F, Inst))
return;
break;
case ARCInstKind::AutoreleaseRV:
OptimizeAutoreleaseRVCall(F, Inst, Class);
break;
}
if (IsAutorelease(Class) && Inst->use_empty()) {
CallInst *Call = cast<CallInst>(Inst);
const Value *Arg = Call->getArgOperand(0);
Arg = FindSingleUseIdentifiedObject(Arg);
if (Arg) {
Changed = true;
++NumAutoreleases;
LLVMContext &C = Inst->getContext();
Function *Decl = EP.get(ARCRuntimeEntryPointKind::Release);
CallInst *NewCall =
CallInst::Create(Decl, Call->getArgOperand(0), "", Call);
NewCall->setMetadata(MDKindCache.get(ARCMDKindID::ImpreciseRelease),
MDNode::get(C, None));
LLVM_DEBUG(dbgs() << "Replacing autorelease{,RV}(x) with objc_release(x) "
"since x is otherwise unused.\nOld: "
<< *Call << "\nNew: " << *NewCall << "\n");
EraseInstruction(Call);
Inst = NewCall;
Class = ARCInstKind::Release;
}
}
if (IsAlwaysTail(Class) && !cast<CallInst>(Inst)->isNoTailCall()) {
Changed = true;
LLVM_DEBUG(
dbgs() << "Adding tail keyword to function since it can never be "
"passed stack args: "
<< *Inst << "\n");
cast<CallInst>(Inst)->setTailCall();
}
if (IsNeverTail(Class)) {
Changed = true;
LLVM_DEBUG(dbgs() << "Removing tail keyword from function: " << *Inst
<< "\n");
cast<CallInst>(Inst)->setTailCall(false);
}
if (IsNoThrow(Class)) {
Changed = true;
LLVM_DEBUG(dbgs() << "Found no throw class. Setting nounwind on: " << *Inst
<< "\n");
cast<CallInst>(Inst)->setDoesNotThrow();
}
if (!IsNoopOnNull(Class)) {
UsedInThisFunction |= 1 << unsigned(Class);
return;
}
if (!Arg)
Arg = GetArgRCIdentityRoot(Inst);
if (IsNullOrUndef(Arg)) {
Changed = true;
++NumNoops;
LLVM_DEBUG(dbgs() << "ARC calls with null are no-ops. Erasing: " << *Inst
<< "\n");
EraseInstruction(Inst);
return;
}
UsedInThisFunction |= 1 << unsigned(Class);
if (Class == ARCInstKind::Release &&
!Inst->getMetadata(MDKindCache.get(ARCMDKindID::ImpreciseRelease)))
return;
SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
Worklist.push_back(std::make_pair(Inst, Arg));
do {
std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
Inst = Pair.first;
Arg = Pair.second;
const PHINode *PN = dyn_cast<PHINode>(Arg);
if (!PN)
continue;
bool HasNull = false;
bool HasCriticalEdges = false;
for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Value *Incoming = GetRCIdentityRoot(PN->getIncomingValue(i));
if (IsNullOrUndef(Incoming))
HasNull = true;
else if (PN->getIncomingBlock(i)->getTerminator()->getNumSuccessors() !=
1) {
HasCriticalEdges = true;
break;
}
}
if (HasCriticalEdges)
continue;
if (!HasNull)
continue;
Instruction *DepInst = nullptr;
switch (Class) {
case ARCInstKind::Retain:
case ARCInstKind::RetainBlock:
break;
case ARCInstKind::Release:
DepInst = findSingleDependency(NeedsPositiveRetainCount, Arg,
Inst->getParent(), Inst, PA);
break;
case ARCInstKind::Autorelease:
DepInst = findSingleDependency(AutoreleasePoolBoundary, Arg,
Inst->getParent(), Inst, PA);
break;
case ARCInstKind::UnsafeClaimRV:
case ARCInstKind::RetainRV:
case ARCInstKind::AutoreleaseRV:
continue;
default:
llvm_unreachable("Invalid dependence flavor");
}
if (DepInst != PN)
continue;
Changed = true;
++NumPartialNoops;
CallInst *CInst = cast<CallInst>(Inst);
Type *ParamTy = CInst->getArgOperand(0)->getType();
for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Value *Incoming = GetRCIdentityRoot(PN->getIncomingValue(i));
if (IsNullOrUndef(Incoming))
continue;
Value *Op = PN->getIncomingValue(i);
Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
CallInst *Clone = cast<CallInst>(
CloneCallInstForBB(*CInst, *InsertPos->getParent(), BlockColors));
if (Op->getType() != ParamTy)
Op = new BitCastInst(Op, ParamTy, "", InsertPos);
Clone->setArgOperand(0, Op);
Clone->insertBefore(InsertPos);
LLVM_DEBUG(dbgs() << "Cloning " << *CInst << "\n"
"And inserting clone at "
<< *InsertPos << "\n");
Worklist.push_back(std::make_pair(Clone, Incoming));
}
LLVM_DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
EraseInstruction(CInst);
} while (!Worklist.empty());
}
static void CheckForUseCFGHazard(const Sequence SuccSSeq,
const bool SuccSRRIKnownSafe,
TopDownPtrState &S,
bool &SomeSuccHasSame,
bool &AllSuccsHaveSame,
bool &NotAllSeqEqualButKnownSafe,
bool &ShouldContinue) {
switch (SuccSSeq) {
case S_CanRelease: {
if (!S.IsKnownSafe() && !SuccSRRIKnownSafe) {
S.ClearSequenceProgress();
break;
}
S.SetCFGHazardAfflicted(true);
ShouldContinue = true;
break;
}
case S_Use:
SomeSuccHasSame = true;
break;
case S_Stop:
case S_MovableRelease:
if (!S.IsKnownSafe() && !SuccSRRIKnownSafe)
AllSuccsHaveSame = false;
else
NotAllSeqEqualButKnownSafe = true;
break;
case S_Retain:
llvm_unreachable("bottom-up pointer in retain state!");
case S_None:
llvm_unreachable("This should have been handled earlier.");
}
}
static void CheckForCanReleaseCFGHazard(const Sequence SuccSSeq,
const bool SuccSRRIKnownSafe,
TopDownPtrState &S,
bool &SomeSuccHasSame,
bool &AllSuccsHaveSame,
bool &NotAllSeqEqualButKnownSafe) {
switch (SuccSSeq) {
case S_CanRelease:
SomeSuccHasSame = true;
break;
case S_Stop:
case S_MovableRelease:
case S_Use:
if (!S.IsKnownSafe() && !SuccSRRIKnownSafe)
AllSuccsHaveSame = false;
else
NotAllSeqEqualButKnownSafe = true;
break;
case S_Retain:
llvm_unreachable("bottom-up pointer in retain state!");
case S_None:
llvm_unreachable("This should have been handled earlier.");
}
}
void
ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
DenseMap<const BasicBlock *, BBState> &BBStates,
BBState &MyStates) const {
for (auto I = MyStates.top_down_ptr_begin(), E = MyStates.top_down_ptr_end();
I != E; ++I) {
TopDownPtrState &S = I->second;
const Sequence Seq = I->second.GetSeq();
if (Seq == S_None)
continue;
assert((Seq == S_Retain || Seq == S_CanRelease || Seq == S_Use) &&
"Unknown top down sequence state.");
const Value *Arg = I->first;
bool SomeSuccHasSame = false;
bool AllSuccsHaveSame = true;
bool NotAllSeqEqualButKnownSafe = false;
for (const BasicBlock *Succ : successors(BB)) {
const DenseMap<const BasicBlock *, BBState>::iterator BBI =
BBStates.find(Succ);
assert(BBI != BBStates.end());
const BottomUpPtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
const Sequence SuccSSeq = SuccS.GetSeq();
if (SuccSSeq == S_None) {
S.ClearSequenceProgress();
continue;
}
const bool SuccSRRIKnownSafe = SuccS.IsKnownSafe();
switch(S.GetSeq()) {
case S_Use: {
bool ShouldContinue = false;
CheckForUseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S, SomeSuccHasSame,
AllSuccsHaveSame, NotAllSeqEqualButKnownSafe,
ShouldContinue);
if (ShouldContinue)
continue;
break;
}
case S_CanRelease:
CheckForCanReleaseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S,
SomeSuccHasSame, AllSuccsHaveSame,
NotAllSeqEqualButKnownSafe);
break;
case S_Retain:
case S_None:
case S_Stop:
case S_MovableRelease:
break;
}
}
if (SomeSuccHasSame && !AllSuccsHaveSame) {
S.ClearSequenceProgress();
} else if (NotAllSeqEqualButKnownSafe) {
S.SetCFGHazardAfflicted(true);
}
}
}
bool ObjCARCOpt::VisitInstructionBottomUp(
Instruction *Inst, BasicBlock *BB, BlotMapVector<Value *, RRInfo> &Retains,
BBState &MyStates) {
bool NestingDetected = false;
ARCInstKind Class = GetARCInstKind(Inst);
const Value *Arg = nullptr;
LLVM_DEBUG(dbgs() << " Class: " << Class << "\n");
switch (Class) {
case ARCInstKind::Release: {
Arg = GetArgRCIdentityRoot(Inst);
BottomUpPtrState &S = MyStates.getPtrBottomUpState(Arg);
NestingDetected |= S.InitBottomUp(MDKindCache, Inst);
break;
}
case ARCInstKind::RetainBlock:
break;
case ARCInstKind::Retain:
case ARCInstKind::RetainRV: {
Arg = GetArgRCIdentityRoot(Inst);
BottomUpPtrState &S = MyStates.getPtrBottomUpState(Arg);
if (S.MatchWithRetain()) {
if (Class != ARCInstKind::RetainRV) {
LLVM_DEBUG(dbgs() << " Matching with: " << *Inst << "\n");
Retains[Inst] = S.GetRRInfo();
}
S.ClearSequenceProgress();
}
break;
}
case ARCInstKind::AutoreleasepoolPop:
MyStates.clearBottomUpPointers();
return NestingDetected;
case ARCInstKind::AutoreleasepoolPush:
case ARCInstKind::None:
return NestingDetected;
default:
break;
}
for (auto MI = MyStates.bottom_up_ptr_begin(),
ME = MyStates.bottom_up_ptr_end();
MI != ME; ++MI) {
const Value *Ptr = MI->first;
if (Ptr == Arg)
continue; BottomUpPtrState &S = MI->second;
if (S.HandlePotentialAlterRefCount(Inst, Ptr, PA, Class))
continue;
S.HandlePotentialUse(BB, Inst, Ptr, PA, Class);
}
return NestingDetected;
}
bool ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
DenseMap<const BasicBlock *, BBState> &BBStates,
BlotMapVector<Value *, RRInfo> &Retains) {
LLVM_DEBUG(dbgs() << "\n== ObjCARCOpt::VisitBottomUp ==\n");
bool NestingDetected = false;
BBState &MyStates = BBStates[BB];
BBState::edge_iterator SI(MyStates.succ_begin()),
SE(MyStates.succ_end());
if (SI != SE) {
const BasicBlock *Succ = *SI;
DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
assert(I != BBStates.end());
MyStates.InitFromSucc(I->second);
++SI;
for (; SI != SE; ++SI) {
Succ = *SI;
I = BBStates.find(Succ);
assert(I != BBStates.end());
MyStates.MergeSucc(I->second);
}
}
LLVM_DEBUG(dbgs() << "Before:\n"
<< BBStates[BB] << "\n"
<< "Performing Dataflow:\n");
for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
Instruction *Inst = &*std::prev(I);
if (isa<InvokeInst>(Inst))
continue;
LLVM_DEBUG(dbgs() << " Visiting " << *Inst << "\n");
NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
if (MyStates.bottom_up_ptr_list_size() > MaxPtrStates) {
DisableRetainReleasePairing = true;
return false;
}
}
for (BBState::edge_iterator PI(MyStates.pred_begin()),
PE(MyStates.pred_end()); PI != PE; ++PI) {
BasicBlock *Pred = *PI;
if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
}
LLVM_DEBUG(dbgs() << "\nFinal State:\n" << BBStates[BB] << "\n");
return NestingDetected;
}
static void collectReleaseInsertPts(
const BlotMapVector<Value *, RRInfo> &Retains,
DenseMap<const Instruction *, SmallPtrSet<const Value *, 2>>
&ReleaseInsertPtToRCIdentityRoots) {
for (auto &P : Retains) {
Instruction *Retain = cast<Instruction>(P.first);
Value *Root = GetRCIdentityRoot(Retain->getOperand(0));
for (const Instruction *InsertPt : P.second.ReverseInsertPts)
ReleaseInsertPtToRCIdentityRoots[InsertPt].insert(Root);
}
}
static const SmallPtrSet<const Value *, 2> *
getRCIdentityRootsFromReleaseInsertPt(
const Instruction *InsertPt,
const DenseMap<const Instruction *, SmallPtrSet<const Value *, 2>>
&ReleaseInsertPtToRCIdentityRoots) {
auto I = ReleaseInsertPtToRCIdentityRoots.find(InsertPt);
if (I == ReleaseInsertPtToRCIdentityRoots.end())
return nullptr;
return &I->second;
}
bool ObjCARCOpt::VisitInstructionTopDown(
Instruction *Inst, DenseMap<Value *, RRInfo> &Releases, BBState &MyStates,
const DenseMap<const Instruction *, SmallPtrSet<const Value *, 2>>
&ReleaseInsertPtToRCIdentityRoots) {
bool NestingDetected = false;
ARCInstKind Class = GetARCInstKind(Inst);
const Value *Arg = nullptr;
if (const SmallPtrSet<const Value *, 2> *Roots =
getRCIdentityRootsFromReleaseInsertPt(
Inst, ReleaseInsertPtToRCIdentityRoots))
for (auto *Root : *Roots) {
TopDownPtrState &S = MyStates.getPtrTopDownState(Root);
if (S.GetSeq() == S_Retain)
S.SetCFGHazardAfflicted(true);
}
LLVM_DEBUG(dbgs() << " Class: " << Class << "\n");
switch (Class) {
case ARCInstKind::RetainBlock:
break;
case ARCInstKind::Retain:
case ARCInstKind::RetainRV: {
Arg = GetArgRCIdentityRoot(Inst);
TopDownPtrState &S = MyStates.getPtrTopDownState(Arg);
NestingDetected |= S.InitTopDown(Class, Inst);
break;
}
case ARCInstKind::Release: {
Arg = GetArgRCIdentityRoot(Inst);
TopDownPtrState &S = MyStates.getPtrTopDownState(Arg);
if (S.MatchWithRelease(MDKindCache, Inst)) {
LLVM_DEBUG(dbgs() << " Matching with: " << *Inst << "\n");
Releases[Inst] = S.GetRRInfo();
S.ClearSequenceProgress();
}
break;
}
case ARCInstKind::AutoreleasepoolPop:
MyStates.clearTopDownPointers();
return false;
case ARCInstKind::AutoreleasepoolPush:
case ARCInstKind::None:
return false;
default:
break;
}
for (auto MI = MyStates.top_down_ptr_begin(),
ME = MyStates.top_down_ptr_end();
MI != ME; ++MI) {
const Value *Ptr = MI->first;
if (Ptr == Arg)
continue; TopDownPtrState &S = MI->second;
if (S.HandlePotentialAlterRefCount(Inst, Ptr, PA, Class, *BundledInsts))
continue;
S.HandlePotentialUse(Inst, Ptr, PA, Class);
}
return NestingDetected;
}
bool ObjCARCOpt::VisitTopDown(
BasicBlock *BB, DenseMap<const BasicBlock *, BBState> &BBStates,
DenseMap<Value *, RRInfo> &Releases,
const DenseMap<const Instruction *, SmallPtrSet<const Value *, 2>>
&ReleaseInsertPtToRCIdentityRoots) {
LLVM_DEBUG(dbgs() << "\n== ObjCARCOpt::VisitTopDown ==\n");
bool NestingDetected = false;
BBState &MyStates = BBStates[BB];
BBState::edge_iterator PI(MyStates.pred_begin()),
PE(MyStates.pred_end());
if (PI != PE) {
const BasicBlock *Pred = *PI;
DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
assert(I != BBStates.end());
MyStates.InitFromPred(I->second);
++PI;
for (; PI != PE; ++PI) {
Pred = *PI;
I = BBStates.find(Pred);
assert(I != BBStates.end());
MyStates.MergePred(I->second);
}
}
if (!BB->hasNPredecessors(MyStates.pred_end() - MyStates.pred_begin()))
for (auto I = MyStates.top_down_ptr_begin(),
E = MyStates.top_down_ptr_end();
I != E; ++I)
I->second.SetCFGHazardAfflicted(true);
LLVM_DEBUG(dbgs() << "Before:\n"
<< BBStates[BB] << "\n"
<< "Performing Dataflow:\n");
for (Instruction &Inst : *BB) {
LLVM_DEBUG(dbgs() << " Visiting " << Inst << "\n");
NestingDetected |= VisitInstructionTopDown(
&Inst, Releases, MyStates, ReleaseInsertPtToRCIdentityRoots);
if (MyStates.top_down_ptr_list_size() > MaxPtrStates) {
DisableRetainReleasePairing = true;
return false;
}
}
LLVM_DEBUG(dbgs() << "\nState Before Checking for CFG Hazards:\n"
<< BBStates[BB] << "\n\n");
CheckForCFGHazards(BB, BBStates, MyStates);
LLVM_DEBUG(dbgs() << "Final State:\n" << BBStates[BB] << "\n");
return NestingDetected;
}
static void
ComputePostOrders(Function &F,
SmallVectorImpl<BasicBlock *> &PostOrder,
SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
unsigned NoObjCARCExceptionsMDKind,
DenseMap<const BasicBlock *, BBState> &BBStates) {
SmallPtrSet<BasicBlock *, 16> Visited;
SmallPtrSet<BasicBlock *, 16> OnStack;
SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
BasicBlock *EntryBB = &F.getEntryBlock();
BBState &MyStates = BBStates[EntryBB];
MyStates.SetAsEntry();
Instruction *EntryTI = EntryBB->getTerminator();
SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
Visited.insert(EntryBB);
OnStack.insert(EntryBB);
do {
dfs_next_succ:
BasicBlock *CurrBB = SuccStack.back().first;
succ_iterator SE(CurrBB->getTerminator(), false);
while (SuccStack.back().second != SE) {
BasicBlock *SuccBB = *SuccStack.back().second++;
if (Visited.insert(SuccBB).second) {
SuccStack.push_back(
std::make_pair(SuccBB, succ_iterator(SuccBB->getTerminator())));
BBStates[CurrBB].addSucc(SuccBB);
BBState &SuccStates = BBStates[SuccBB];
SuccStates.addPred(CurrBB);
OnStack.insert(SuccBB);
goto dfs_next_succ;
}
if (!OnStack.count(SuccBB)) {
BBStates[CurrBB].addSucc(SuccBB);
BBStates[SuccBB].addPred(CurrBB);
}
}
OnStack.erase(CurrBB);
PostOrder.push_back(CurrBB);
SuccStack.pop_back();
} while (!SuccStack.empty());
Visited.clear();
SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
for (BasicBlock &ExitBB : F) {
BBState &MyStates = BBStates[&ExitBB];
if (!MyStates.isExit())
continue;
MyStates.SetAsExit();
PredStack.push_back(std::make_pair(&ExitBB, MyStates.pred_begin()));
Visited.insert(&ExitBB);
while (!PredStack.empty()) {
reverse_dfs_next_succ:
BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
while (PredStack.back().second != PE) {
BasicBlock *BB = *PredStack.back().second++;
if (Visited.insert(BB).second) {
PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
goto reverse_dfs_next_succ;
}
}
ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
}
}
}
bool ObjCARCOpt::Visit(Function &F,
DenseMap<const BasicBlock *, BBState> &BBStates,
BlotMapVector<Value *, RRInfo> &Retains,
DenseMap<Value *, RRInfo> &Releases) {
SmallVector<BasicBlock *, 16> PostOrder;
SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
MDKindCache.get(ARCMDKindID::NoObjCARCExceptions),
BBStates);
bool BottomUpNestingDetected = false;
for (BasicBlock *BB : llvm::reverse(ReverseCFGPostOrder)) {
BottomUpNestingDetected |= VisitBottomUp(BB, BBStates, Retains);
if (DisableRetainReleasePairing)
return false;
}
DenseMap<const Instruction *, SmallPtrSet<const Value *, 2>>
ReleaseInsertPtToRCIdentityRoots;
collectReleaseInsertPts(Retains, ReleaseInsertPtToRCIdentityRoots);
bool TopDownNestingDetected = false;
for (BasicBlock *BB : llvm::reverse(PostOrder)) {
TopDownNestingDetected |=
VisitTopDown(BB, BBStates, Releases, ReleaseInsertPtToRCIdentityRoots);
if (DisableRetainReleasePairing)
return false;
}
return TopDownNestingDetected && BottomUpNestingDetected;
}
void ObjCARCOpt::MoveCalls(Value *Arg, RRInfo &RetainsToMove,
RRInfo &ReleasesToMove,
BlotMapVector<Value *, RRInfo> &Retains,
DenseMap<Value *, RRInfo> &Releases,
SmallVectorImpl<Instruction *> &DeadInsts,
Module *M) {
Type *ArgTy = Arg->getType();
Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
LLVM_DEBUG(dbgs() << "== ObjCARCOpt::MoveCalls ==\n");
for (Instruction *InsertPt : ReleasesToMove.ReverseInsertPts) {
Value *MyArg = ArgTy == ParamTy ? Arg :
new BitCastInst(Arg, ParamTy, "", InsertPt);
Function *Decl = EP.get(ARCRuntimeEntryPointKind::Retain);
CallInst *Call = CallInst::Create(Decl, MyArg, "", InsertPt);
Call->setDoesNotThrow();
Call->setTailCall();
LLVM_DEBUG(dbgs() << "Inserting new Retain: " << *Call
<< "\n"
"At insertion point: "
<< *InsertPt << "\n");
}
for (Instruction *InsertPt : RetainsToMove.ReverseInsertPts) {
Value *MyArg = ArgTy == ParamTy ? Arg :
new BitCastInst(Arg, ParamTy, "", InsertPt);
Function *Decl = EP.get(ARCRuntimeEntryPointKind::Release);
CallInst *Call = CallInst::Create(Decl, MyArg, "", InsertPt);
if (MDNode *M = ReleasesToMove.ReleaseMetadata)
Call->setMetadata(MDKindCache.get(ARCMDKindID::ImpreciseRelease), M);
Call->setDoesNotThrow();
if (ReleasesToMove.IsTailCallRelease)
Call->setTailCall();
LLVM_DEBUG(dbgs() << "Inserting new Release: " << *Call
<< "\n"
"At insertion point: "
<< *InsertPt << "\n");
}
for (Instruction *OrigRetain : RetainsToMove.Calls) {
Retains.blot(OrigRetain);
DeadInsts.push_back(OrigRetain);
LLVM_DEBUG(dbgs() << "Deleting retain: " << *OrigRetain << "\n");
}
for (Instruction *OrigRelease : ReleasesToMove.Calls) {
Releases.erase(OrigRelease);
DeadInsts.push_back(OrigRelease);
LLVM_DEBUG(dbgs() << "Deleting release: " << *OrigRelease << "\n");
}
}
bool ObjCARCOpt::PairUpRetainsAndReleases(
DenseMap<const BasicBlock *, BBState> &BBStates,
BlotMapVector<Value *, RRInfo> &Retains,
DenseMap<Value *, RRInfo> &Releases, Module *M,
Instruction *Retain,
SmallVectorImpl<Instruction *> &DeadInsts, RRInfo &RetainsToMove,
RRInfo &ReleasesToMove, Value *Arg, bool KnownSafe,
bool &AnyPairsCompletelyEliminated) {
bool KnownSafeTD = true, KnownSafeBU = true;
bool CFGHazardAfflicted = false;
unsigned OldDelta = 0;
unsigned NewDelta = 0;
unsigned OldCount = 0;
unsigned NewCount = 0;
bool FirstRelease = true;
for (SmallVector<Instruction *, 4> NewRetains{Retain};;) {
SmallVector<Instruction *, 4> NewReleases;
for (Instruction *NewRetain : NewRetains) {
auto It = Retains.find(NewRetain);
assert(It != Retains.end());
const RRInfo &NewRetainRRI = It->second;
KnownSafeTD &= NewRetainRRI.KnownSafe;
CFGHazardAfflicted |= NewRetainRRI.CFGHazardAfflicted;
for (Instruction *NewRetainRelease : NewRetainRRI.Calls) {
auto Jt = Releases.find(NewRetainRelease);
if (Jt == Releases.end())
return false;
const RRInfo &NewRetainReleaseRRI = Jt->second;
if (!NewRetainReleaseRRI.Calls.count(NewRetain))
return false;
if (ReleasesToMove.Calls.insert(NewRetainRelease).second) {
const BBState &NRRBBState = BBStates[NewRetainRelease->getParent()];
unsigned PathCount = BBState::OverflowOccurredValue;
if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
return false;
assert(PathCount != BBState::OverflowOccurredValue &&
"PathCount at this point can not be "
"OverflowOccurredValue.");
OldDelta -= PathCount;
if (FirstRelease) {
ReleasesToMove.ReleaseMetadata =
NewRetainReleaseRRI.ReleaseMetadata;
ReleasesToMove.IsTailCallRelease =
NewRetainReleaseRRI.IsTailCallRelease;
FirstRelease = false;
} else {
if (ReleasesToMove.ReleaseMetadata !=
NewRetainReleaseRRI.ReleaseMetadata)
ReleasesToMove.ReleaseMetadata = nullptr;
if (ReleasesToMove.IsTailCallRelease !=
NewRetainReleaseRRI.IsTailCallRelease)
ReleasesToMove.IsTailCallRelease = false;
}
if (!KnownSafe)
for (Instruction *RIP : NewRetainReleaseRRI.ReverseInsertPts) {
if (ReleasesToMove.ReverseInsertPts.insert(RIP).second) {
const BBState &RIPBBState = BBStates[RIP->getParent()];
PathCount = BBState::OverflowOccurredValue;
if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
return false;
assert(PathCount != BBState::OverflowOccurredValue &&
"PathCount at this point can not be "
"OverflowOccurredValue.");
NewDelta -= PathCount;
}
}
NewReleases.push_back(NewRetainRelease);
}
}
}
NewRetains.clear();
if (NewReleases.empty()) break;
for (Instruction *NewRelease : NewReleases) {
auto It = Releases.find(NewRelease);
assert(It != Releases.end());
const RRInfo &NewReleaseRRI = It->second;
KnownSafeBU &= NewReleaseRRI.KnownSafe;
CFGHazardAfflicted |= NewReleaseRRI.CFGHazardAfflicted;
for (Instruction *NewReleaseRetain : NewReleaseRRI.Calls) {
auto Jt = Retains.find(NewReleaseRetain);
if (Jt == Retains.end())
return false;
const RRInfo &NewReleaseRetainRRI = Jt->second;
if (!NewReleaseRetainRRI.Calls.count(NewRelease))
return false;
if (RetainsToMove.Calls.insert(NewReleaseRetain).second) {
const BBState &NRRBBState = BBStates[NewReleaseRetain->getParent()];
unsigned PathCount = BBState::OverflowOccurredValue;
if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
return false;
assert(PathCount != BBState::OverflowOccurredValue &&
"PathCount at this point can not be "
"OverflowOccurredValue.");
OldDelta += PathCount;
OldCount += PathCount;
if (!KnownSafe)
for (Instruction *RIP : NewReleaseRetainRRI.ReverseInsertPts) {
if (RetainsToMove.ReverseInsertPts.insert(RIP).second) {
const BBState &RIPBBState = BBStates[RIP->getParent()];
PathCount = BBState::OverflowOccurredValue;
if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
return false;
assert(PathCount != BBState::OverflowOccurredValue &&
"PathCount at this point can not be "
"OverflowOccurredValue.");
NewDelta += PathCount;
NewCount += PathCount;
}
}
NewRetains.push_back(NewReleaseRetain);
}
}
}
if (NewRetains.empty()) break;
}
bool UnconditionallySafe = KnownSafeTD && KnownSafeBU;
if (UnconditionallySafe) {
RetainsToMove.ReverseInsertPts.clear();
ReleasesToMove.ReverseInsertPts.clear();
NewCount = 0;
} else {
if (NewDelta != 0)
return false;
const bool WillPerformCodeMotion =
!RetainsToMove.ReverseInsertPts.empty() ||
!ReleasesToMove.ReverseInsertPts.empty();
if (CFGHazardAfflicted && WillPerformCodeMotion)
return false;
}
if (OldDelta != 0)
return false;
Changed = true;
assert(OldCount != 0 && "Unreachable code?");
NumRRs += OldCount - NewCount;
AnyPairsCompletelyEliminated = NewCount == 0;
return true;
}
bool ObjCARCOpt::PerformCodePlacement(
DenseMap<const BasicBlock *, BBState> &BBStates,
BlotMapVector<Value *, RRInfo> &Retains,
DenseMap<Value *, RRInfo> &Releases, Module *M) {
LLVM_DEBUG(dbgs() << "\n== ObjCARCOpt::PerformCodePlacement ==\n");
bool AnyPairsCompletelyEliminated = false;
SmallVector<Instruction *, 8> DeadInsts;
for (BlotMapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
E = Retains.end();
I != E; ++I) {
Value *V = I->first;
if (!V) continue;
Instruction *Retain = cast<Instruction>(V);
LLVM_DEBUG(dbgs() << "Visiting: " << *Retain << "\n");
Value *Arg = GetArgRCIdentityRoot(Retain);
bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
if (const GlobalVariable *GV =
dyn_cast<GlobalVariable>(
GetRCIdentityRoot(LI->getPointerOperand())))
if (GV->isConstant())
KnownSafe = true;
RRInfo RetainsToMove, ReleasesToMove;
bool PerformMoveCalls = PairUpRetainsAndReleases(
BBStates, Retains, Releases, M, Retain, DeadInsts,
RetainsToMove, ReleasesToMove, Arg, KnownSafe,
AnyPairsCompletelyEliminated);
if (PerformMoveCalls) {
MoveCalls(Arg, RetainsToMove, ReleasesToMove,
Retains, Releases, DeadInsts, M);
}
}
while (!DeadInsts.empty())
EraseInstruction(DeadInsts.pop_back_val());
return AnyPairsCompletelyEliminated;
}
void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
LLVM_DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeWeakCalls ==\n");
for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
Instruction *Inst = &*I++;
LLVM_DEBUG(dbgs() << "Visiting: " << *Inst << "\n");
ARCInstKind Class = GetBasicARCInstKind(Inst);
if (Class != ARCInstKind::LoadWeak &&
Class != ARCInstKind::LoadWeakRetained)
continue;
if (Class == ARCInstKind::LoadWeak && Inst->use_empty()) {
Inst->eraseFromParent();
Changed = true;
continue;
}
inst_iterator Current = std::prev(I);
BasicBlock *CurrentBB = &*Current.getBasicBlockIterator();
for (BasicBlock::iterator B = CurrentBB->begin(),
J = Current.getInstructionIterator();
J != B; --J) {
Instruction *EarlierInst = &*std::prev(J);
ARCInstKind EarlierClass = GetARCInstKind(EarlierInst);
switch (EarlierClass) {
case ARCInstKind::LoadWeak:
case ARCInstKind::LoadWeakRetained: {
CallInst *Call = cast<CallInst>(Inst);
CallInst *EarlierCall = cast<CallInst>(EarlierInst);
Value *Arg = Call->getArgOperand(0);
Value *EarlierArg = EarlierCall->getArgOperand(0);
switch (PA.getAA()->alias(Arg, EarlierArg)) {
case AliasResult::MustAlias:
Changed = true;
if (Class == ARCInstKind::LoadWeakRetained) {
Function *Decl = EP.get(ARCRuntimeEntryPointKind::Retain);
CallInst *CI = CallInst::Create(Decl, EarlierCall, "", Call);
CI->setTailCall();
}
Call->replaceAllUsesWith(EarlierCall);
Call->eraseFromParent();
goto clobbered;
case AliasResult::MayAlias:
case AliasResult::PartialAlias:
goto clobbered;
case AliasResult::NoAlias:
break;
}
break;
}
case ARCInstKind::StoreWeak:
case ARCInstKind::InitWeak: {
CallInst *Call = cast<CallInst>(Inst);
CallInst *EarlierCall = cast<CallInst>(EarlierInst);
Value *Arg = Call->getArgOperand(0);
Value *EarlierArg = EarlierCall->getArgOperand(0);
switch (PA.getAA()->alias(Arg, EarlierArg)) {
case AliasResult::MustAlias:
Changed = true;
if (Class == ARCInstKind::LoadWeakRetained) {
Function *Decl = EP.get(ARCRuntimeEntryPointKind::Retain);
CallInst *CI = CallInst::Create(Decl, EarlierCall, "", Call);
CI->setTailCall();
}
Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
Call->eraseFromParent();
goto clobbered;
case AliasResult::MayAlias:
case AliasResult::PartialAlias:
goto clobbered;
case AliasResult::NoAlias:
break;
}
break;
}
case ARCInstKind::MoveWeak:
case ARCInstKind::CopyWeak:
goto clobbered;
case ARCInstKind::AutoreleasepoolPush:
case ARCInstKind::None:
case ARCInstKind::IntrinsicUser:
case ARCInstKind::User:
break;
default:
goto clobbered;
}
}
clobbered:;
}
for (Instruction &Inst : llvm::make_early_inc_range(instructions(F))) {
ARCInstKind Class = GetBasicARCInstKind(&Inst);
if (Class != ARCInstKind::DestroyWeak)
continue;
CallInst *Call = cast<CallInst>(&Inst);
Value *Arg = Call->getArgOperand(0);
if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
for (User *U : Alloca->users()) {
const Instruction *UserInst = cast<Instruction>(U);
switch (GetBasicARCInstKind(UserInst)) {
case ARCInstKind::InitWeak:
case ARCInstKind::StoreWeak:
case ARCInstKind::DestroyWeak:
continue;
default:
goto done;
}
}
Changed = true;
for (User *U : llvm::make_early_inc_range(Alloca->users())) {
CallInst *UserInst = cast<CallInst>(U);
switch (GetBasicARCInstKind(UserInst)) {
case ARCInstKind::InitWeak:
case ARCInstKind::StoreWeak:
UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
break;
case ARCInstKind::DestroyWeak:
break;
default:
llvm_unreachable("alloca really is used!");
}
UserInst->eraseFromParent();
}
Alloca->eraseFromParent();
done:;
}
}
}
bool ObjCARCOpt::OptimizeSequences(Function &F) {
DenseMap<Value *, RRInfo> Releases;
BlotMapVector<Value *, RRInfo> Retains;
DenseMap<const BasicBlock *, BBState> BBStates;
bool NestingDetected = Visit(F, BBStates, Retains, Releases);
if (DisableRetainReleasePairing)
return false;
bool AnyPairsCompletelyEliminated = PerformCodePlacement(BBStates, Retains,
Releases,
F.getParent());
return AnyPairsCompletelyEliminated && NestingDetected;
}
static CallInst *HasSafePathToPredecessorCall(const Value *Arg,
Instruction *Retain,
ProvenanceAnalysis &PA) {
auto *Call = dyn_cast_or_null<CallInst>(findSingleDependency(
CanChangeRetainCount, Arg, Retain->getParent(), Retain, PA));
if (!Call || Arg != Call)
return nullptr;
ARCInstKind Class = GetBasicARCInstKind(Call);
return Class == ARCInstKind::CallOrUser || Class == ARCInstKind::Call
? Call
: nullptr;
}
static CallInst *
FindPredecessorRetainWithSafePath(const Value *Arg, BasicBlock *BB,
Instruction *Autorelease,
ProvenanceAnalysis &PA) {
auto *Retain = dyn_cast_or_null<CallInst>(
findSingleDependency(CanChangeRetainCount, Arg, BB, Autorelease, PA));
if (!Retain || !IsRetain(GetBasicARCInstKind(Retain)) ||
GetArgRCIdentityRoot(Retain) != Arg) {
return nullptr;
}
return Retain;
}
static CallInst *
FindPredecessorAutoreleaseWithSafePath(const Value *Arg, BasicBlock *BB,
ReturnInst *Ret,
ProvenanceAnalysis &PA) {
SmallPtrSet<Instruction *, 4> DepInsts;
auto *Autorelease = dyn_cast_or_null<CallInst>(
findSingleDependency(NeedsPositiveRetainCount, Arg, BB, Ret, PA));
if (!Autorelease)
return nullptr;
ARCInstKind AutoreleaseClass = GetBasicARCInstKind(Autorelease);
if (!IsAutorelease(AutoreleaseClass))
return nullptr;
if (GetArgRCIdentityRoot(Autorelease) != Arg)
return nullptr;
return Autorelease;
}
void ObjCARCOpt::OptimizeReturns(Function &F) {
if (!F.getReturnType()->isPointerTy())
return;
LLVM_DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeReturns ==\n");
for (BasicBlock &BB: F) {
ReturnInst *Ret = dyn_cast<ReturnInst>(&BB.back());
if (!Ret)
continue;
LLVM_DEBUG(dbgs() << "Visiting: " << *Ret << "\n");
const Value *Arg = GetRCIdentityRoot(Ret->getOperand(0));
CallInst *Autorelease =
FindPredecessorAutoreleaseWithSafePath(Arg, &BB, Ret, PA);
if (!Autorelease)
continue;
CallInst *Retain = FindPredecessorRetainWithSafePath(
Arg, Autorelease->getParent(), Autorelease, PA);
if (!Retain)
continue;
CallInst *Call = HasSafePathToPredecessorCall(Arg, Retain, PA);
if (!Call ||
(!Call->isTailCall() &&
GetBasicARCInstKind(Retain) == ARCInstKind::RetainRV &&
GetBasicARCInstKind(Autorelease) == ARCInstKind::AutoreleaseRV))
continue;
Changed = true;
++NumRets;
LLVM_DEBUG(dbgs() << "Erasing: " << *Retain << "\nErasing: " << *Autorelease
<< "\n");
BundledInsts->eraseInst(Retain);
EraseInstruction(Autorelease);
}
}
#ifndef NDEBUG
void
ObjCARCOpt::GatherStatistics(Function &F, bool AfterOptimization) {
Statistic &NumRetains =
AfterOptimization ? NumRetainsAfterOpt : NumRetainsBeforeOpt;
Statistic &NumReleases =
AfterOptimization ? NumReleasesAfterOpt : NumReleasesBeforeOpt;
for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
Instruction *Inst = &*I++;
switch (GetBasicARCInstKind(Inst)) {
default:
break;
case ARCInstKind::Retain:
++NumRetains;
break;
case ARCInstKind::Release:
++NumReleases;
break;
}
}
}
#endif
void ObjCARCOpt::init(Module &M) {
if (!EnableARCOpts)
return;
MDKindCache.init(&M);
EP.init(&M);
}
bool ObjCARCOpt::run(Function &F, AAResults &AA) {
if (!EnableARCOpts)
return false;
Changed = CFGChanged = false;
BundledRetainClaimRVs BRV(false);
BundledInsts = &BRV;
LLVM_DEBUG(dbgs() << "<<< ObjCARCOpt: Visiting Function: " << F.getName()
<< " >>>"
"\n");
std::pair<bool, bool> R = BundledInsts->insertAfterInvokes(F, nullptr);
Changed |= R.first;
CFGChanged |= R.second;
PA.setAA(&AA);
#ifndef NDEBUG
if (AreStatisticsEnabled()) {
GatherStatistics(F, false);
}
#endif
OptimizeIndividualCalls(F);
if (UsedInThisFunction & ((1 << unsigned(ARCInstKind::LoadWeak)) |
(1 << unsigned(ARCInstKind::LoadWeakRetained)) |
(1 << unsigned(ARCInstKind::StoreWeak)) |
(1 << unsigned(ARCInstKind::InitWeak)) |
(1 << unsigned(ARCInstKind::CopyWeak)) |
(1 << unsigned(ARCInstKind::MoveWeak)) |
(1 << unsigned(ARCInstKind::DestroyWeak))))
OptimizeWeakCalls(F);
if (UsedInThisFunction & ((1 << unsigned(ARCInstKind::Retain)) |
(1 << unsigned(ARCInstKind::RetainRV)) |
(1 << unsigned(ARCInstKind::RetainBlock))))
if (UsedInThisFunction & (1 << unsigned(ARCInstKind::Release)))
while (OptimizeSequences(F)) {}
if (UsedInThisFunction & ((1 << unsigned(ARCInstKind::Autorelease)) |
(1 << unsigned(ARCInstKind::AutoreleaseRV))))
OptimizeReturns(F);
#ifndef NDEBUG
if (AreStatisticsEnabled()) {
GatherStatistics(F, true);
}
#endif
LLVM_DEBUG(dbgs() << "\n");
return Changed;
}
void ObjCARCOpt::releaseMemory() {
PA.clear();
}
PreservedAnalyses ObjCARCOptPass::run(Function &F,
FunctionAnalysisManager &AM) {
ObjCARCOpt OCAO;
OCAO.init(*F.getParent());
bool Changed = OCAO.run(F, AM.getResult<AAManager>(F));
bool CFGChanged = OCAO.hasCFGChanged();
if (Changed) {
PreservedAnalyses PA;
if (!CFGChanged)
PA.preserveSet<CFGAnalyses>();
return PA;
}
return PreservedAnalyses::all();
}