Imported Upstream version 5.18.0.167

Former-commit-id: 289509151e0fee68a1b591a20c9f109c3c789d3a
This commit is contained in:
Xamarin Public Jenkins (auto-signing)
2018-10-20 08:25:10 +00:00
parent e19d552987
commit b084638f15
28489 changed files with 184 additions and 3866856 deletions

View File

@ -1,189 +0,0 @@
//===- ARCRuntimeEntryPoints.h - ObjC ARC Optimization ----------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
/// \file
/// This file contains a class ARCRuntimeEntryPoints for use in
/// creating/managing references to entry points to the arc objective c runtime.
///
/// WARNING: This file knows about certain library functions. It recognizes them
/// by name, and hardwires knowledge of their semantics.
///
/// WARNING: This file knows about how certain Objective-C library functions are
/// used. Naive LLVM IR transformations which would otherwise be
/// behavior-preserving may break these assumptions.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_LIB_TRANSFORMS_OBJCARC_ARCRUNTIMEENTRYPOINTS_H
#define LLVM_LIB_TRANSFORMS_OBJCARC_ARCRUNTIMEENTRYPOINTS_H
#include "llvm/ADT/StringRef.h"
#include "llvm/IR/Attributes.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Type.h"
#include "llvm/Support/ErrorHandling.h"
#include <cassert>
namespace llvm {
class Constant;
class LLVMContext;
namespace objcarc {
enum class ARCRuntimeEntryPointKind {
AutoreleaseRV,
Release,
Retain,
RetainBlock,
Autorelease,
StoreStrong,
RetainRV,
RetainAutorelease,
RetainAutoreleaseRV,
};
/// Declarations for ObjC runtime functions and constants. These are initialized
/// lazily to avoid cluttering up the Module with unused declarations.
class ARCRuntimeEntryPoints {
public:
ARCRuntimeEntryPoints() = default;
void init(Module *M) {
TheModule = M;
AutoreleaseRV = nullptr;
Release = nullptr;
Retain = nullptr;
RetainBlock = nullptr;
Autorelease = nullptr;
StoreStrong = nullptr;
RetainRV = nullptr;
RetainAutorelease = nullptr;
RetainAutoreleaseRV = nullptr;
}
Constant *get(ARCRuntimeEntryPointKind kind) {
assert(TheModule != nullptr && "Not initialized.");
switch (kind) {
case ARCRuntimeEntryPointKind::AutoreleaseRV:
return getI8XRetI8XEntryPoint(AutoreleaseRV,
"objc_autoreleaseReturnValue", true);
case ARCRuntimeEntryPointKind::Release:
return getVoidRetI8XEntryPoint(Release, "objc_release");
case ARCRuntimeEntryPointKind::Retain:
return getI8XRetI8XEntryPoint(Retain, "objc_retain", true);
case ARCRuntimeEntryPointKind::RetainBlock:
return getI8XRetI8XEntryPoint(RetainBlock, "objc_retainBlock", false);
case ARCRuntimeEntryPointKind::Autorelease:
return getI8XRetI8XEntryPoint(Autorelease, "objc_autorelease", true);
case ARCRuntimeEntryPointKind::StoreStrong:
return getI8XRetI8XXI8XEntryPoint(StoreStrong, "objc_storeStrong");
case ARCRuntimeEntryPointKind::RetainRV:
return getI8XRetI8XEntryPoint(RetainRV,
"objc_retainAutoreleasedReturnValue", true);
case ARCRuntimeEntryPointKind::RetainAutorelease:
return getI8XRetI8XEntryPoint(RetainAutorelease, "objc_retainAutorelease",
true);
case ARCRuntimeEntryPointKind::RetainAutoreleaseRV:
return getI8XRetI8XEntryPoint(RetainAutoreleaseRV,
"objc_retainAutoreleaseReturnValue", true);
}
llvm_unreachable("Switch should be a covered switch.");
}
private:
/// Cached reference to the module which we will insert declarations into.
Module *TheModule = nullptr;
/// Declaration for ObjC runtime function objc_autoreleaseReturnValue.
Constant *AutoreleaseRV = nullptr;
/// Declaration for ObjC runtime function objc_release.
Constant *Release = nullptr;
/// Declaration for ObjC runtime function objc_retain.
Constant *Retain = nullptr;
/// Declaration for ObjC runtime function objc_retainBlock.
Constant *RetainBlock = nullptr;
/// Declaration for ObjC runtime function objc_autorelease.
Constant *Autorelease = nullptr;
/// Declaration for objc_storeStrong().
Constant *StoreStrong = nullptr;
/// Declaration for objc_retainAutoreleasedReturnValue().
Constant *RetainRV = nullptr;
/// Declaration for objc_retainAutorelease().
Constant *RetainAutorelease = nullptr;
/// Declaration for objc_retainAutoreleaseReturnValue().
Constant *RetainAutoreleaseRV = nullptr;
Constant *getVoidRetI8XEntryPoint(Constant *&Decl, StringRef Name) {
if (Decl)
return Decl;
LLVMContext &C = TheModule->getContext();
Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
AttributeList Attr = AttributeList().addAttribute(
C, AttributeList::FunctionIndex, Attribute::NoUnwind);
FunctionType *Fty = FunctionType::get(Type::getVoidTy(C), Params,
/*isVarArg=*/false);
return Decl = TheModule->getOrInsertFunction(Name, Fty, Attr);
}
Constant *getI8XRetI8XEntryPoint(Constant *&Decl, StringRef Name,
bool NoUnwind = false) {
if (Decl)
return Decl;
LLVMContext &C = TheModule->getContext();
Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Type *Params[] = { I8X };
FunctionType *Fty = FunctionType::get(I8X, Params, /*isVarArg=*/false);
AttributeList Attr = AttributeList();
if (NoUnwind)
Attr = Attr.addAttribute(C, AttributeList::FunctionIndex,
Attribute::NoUnwind);
return Decl = TheModule->getOrInsertFunction(Name, Fty, Attr);
}
Constant *getI8XRetI8XXI8XEntryPoint(Constant *&Decl, StringRef Name) {
if (Decl)
return Decl;
LLVMContext &C = TheModule->getContext();
Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Type *I8XX = PointerType::getUnqual(I8X);
Type *Params[] = { I8XX, I8X };
AttributeList Attr = AttributeList().addAttribute(
C, AttributeList::FunctionIndex, Attribute::NoUnwind);
Attr = Attr.addParamAttribute(C, 0, Attribute::NoCapture);
FunctionType *Fty = FunctionType::get(Type::getVoidTy(C), Params,
/*isVarArg=*/false);
return Decl = TheModule->getOrInsertFunction(Name, Fty, Attr);
}
};
} // end namespace objcarc
} // end namespace llvm
#endif // LLVM_LIB_TRANSFORMS_OBJCARC_ARCRUNTIMEENTRYPOINTS_H

View File

@ -1,118 +0,0 @@
//===- BlotMapVector.h - A MapVector with the blot operation ----*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_LIB_TRANSFORMS_OBJCARC_BLOTMAPVECTOR_H
#define LLVM_LIB_TRANSFORMS_OBJCARC_BLOTMAPVECTOR_H
#include "llvm/ADT/DenseMap.h"
#include <cassert>
#include <cstddef>
#include <utility>
#include <vector>
namespace llvm {
/// \brief An associative container with fast insertion-order (deterministic)
/// iteration over its elements. Plus the special blot operation.
template <class KeyT, class ValueT> class BlotMapVector {
/// Map keys to indices in Vector.
using MapTy = DenseMap<KeyT, size_t>;
MapTy Map;
/// Keys and values.
using VectorTy = std::vector<std::pair<KeyT, ValueT>>;
VectorTy Vector;
public:
#ifdef EXPENSIVE_CHECKS
~BlotMapVector() {
assert(Vector.size() >= Map.size()); // May differ due to blotting.
for (typename MapTy::const_iterator I = Map.begin(), E = Map.end(); I != E;
++I) {
assert(I->second < Vector.size());
assert(Vector[I->second].first == I->first);
}
for (typename VectorTy::const_iterator I = Vector.begin(), E = Vector.end();
I != E; ++I)
assert(!I->first || (Map.count(I->first) &&
Map[I->first] == size_t(I - Vector.begin())));
}
#endif
using iterator = typename VectorTy::iterator;
using const_iterator = typename VectorTy::const_iterator;
iterator begin() { return Vector.begin(); }
iterator end() { return Vector.end(); }
const_iterator begin() const { return Vector.begin(); }
const_iterator end() const { return Vector.end(); }
ValueT &operator[](const KeyT &Arg) {
std::pair<typename MapTy::iterator, bool> Pair =
Map.insert(std::make_pair(Arg, size_t(0)));
if (Pair.second) {
size_t Num = Vector.size();
Pair.first->second = Num;
Vector.push_back(std::make_pair(Arg, ValueT()));
return Vector[Num].second;
}
return Vector[Pair.first->second].second;
}
std::pair<iterator, bool> insert(const std::pair<KeyT, ValueT> &InsertPair) {
std::pair<typename MapTy::iterator, bool> Pair =
Map.insert(std::make_pair(InsertPair.first, size_t(0)));
if (Pair.second) {
size_t Num = Vector.size();
Pair.first->second = Num;
Vector.push_back(InsertPair);
return std::make_pair(Vector.begin() + Num, true);
}
return std::make_pair(Vector.begin() + Pair.first->second, false);
}
iterator find(const KeyT &Key) {
typename MapTy::iterator It = Map.find(Key);
if (It == Map.end())
return Vector.end();
return Vector.begin() + It->second;
}
const_iterator find(const KeyT &Key) const {
typename MapTy::const_iterator It = Map.find(Key);
if (It == Map.end())
return Vector.end();
return Vector.begin() + It->second;
}
/// This is similar to erase, but instead of removing the element from the
/// vector, it just zeros out the key in the vector. This leaves iterators
/// intact, but clients must be prepared for zeroed-out keys when iterating.
void blot(const KeyT &Key) {
typename MapTy::iterator It = Map.find(Key);
if (It == Map.end())
return;
Vector[It->second].first = KeyT();
Map.erase(It);
}
void clear() {
Map.clear();
Vector.clear();
}
bool empty() const {
assert(Map.empty() == Vector.empty());
return Map.empty();
}
};
} // end namespace llvm
#endif // LLVM_LIB_TRANSFORMS_OBJCARC_BLOTMAPVECTOR_H

View File

@ -1,17 +0,0 @@
add_llvm_library(LLVMObjCARCOpts
ObjCARC.cpp
ObjCARCOpts.cpp
ObjCARCExpand.cpp
ObjCARCAPElim.cpp
ObjCARCContract.cpp
DependencyAnalysis.cpp
ProvenanceAnalysis.cpp
ProvenanceAnalysisEvaluator.cpp
PtrState.cpp
ADDITIONAL_HEADER_DIRS
${LLVM_MAIN_INCLUDE_DIR}/llvm/Transforms
DEPENDS
intrinsics_gen
)

View File

@ -1,278 +0,0 @@
//===- DependencyAnalysis.cpp - ObjC ARC Optimization ---------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
///
/// This file defines special dependency analysis routines used in Objective C
/// ARC Optimizations.
///
/// WARNING: This file knows about certain library functions. It recognizes them
/// by name, and hardwires knowledge of their semantics.
///
/// WARNING: This file knows about how certain Objective-C library functions are
/// used. Naive LLVM IR transformations which would otherwise be
/// behavior-preserving may break these assumptions.
///
//===----------------------------------------------------------------------===//
#include "DependencyAnalysis.h"
#include "ObjCARC.h"
#include "ProvenanceAnalysis.h"
#include "llvm/IR/CFG.h"
using namespace llvm;
using namespace llvm::objcarc;
#define DEBUG_TYPE "objc-arc-dependency"
/// Test whether the given instruction can result in a reference count
/// modification (positive or negative) for the pointer's object.
bool llvm::objcarc::CanAlterRefCount(const Instruction *Inst, const Value *Ptr,
ProvenanceAnalysis &PA,
ARCInstKind Class) {
switch (Class) {
case ARCInstKind::Autorelease:
case ARCInstKind::AutoreleaseRV:
case ARCInstKind::IntrinsicUser:
case ARCInstKind::User:
// These operations never directly modify a reference count.
return false;
default: break;
}
ImmutableCallSite CS(Inst);
assert(CS && "Only calls can alter reference counts!");
// See if AliasAnalysis can help us with the call.
FunctionModRefBehavior MRB = PA.getAA()->getModRefBehavior(CS);
if (AliasAnalysis::onlyReadsMemory(MRB))
return false;
if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
const DataLayout &DL = Inst->getModule()->getDataLayout();
for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
I != E; ++I) {
const Value *Op = *I;
if (IsPotentialRetainableObjPtr(Op, *PA.getAA()) &&
PA.related(Ptr, Op, DL))
return true;
}
return false;
}
// Assume the worst.
return true;
}
bool llvm::objcarc::CanDecrementRefCount(const Instruction *Inst,
const Value *Ptr,
ProvenanceAnalysis &PA,
ARCInstKind Class) {
// First perform a quick check if Class can not touch ref counts.
if (!CanDecrementRefCount(Class))
return false;
// Otherwise, just use CanAlterRefCount for now.
return CanAlterRefCount(Inst, Ptr, PA, Class);
}
/// Test whether the given instruction can "use" the given pointer's object in a
/// way that requires the reference count to be positive.
bool llvm::objcarc::CanUse(const Instruction *Inst, const Value *Ptr,
ProvenanceAnalysis &PA, ARCInstKind Class) {
// ARCInstKind::Call operations (as opposed to
// ARCInstKind::CallOrUser) never "use" objc pointers.
if (Class == ARCInstKind::Call)
return false;
const DataLayout &DL = Inst->getModule()->getDataLayout();
// Consider various instructions which may have pointer arguments which are
// not "uses".
if (const ICmpInst *ICI = dyn_cast<ICmpInst>(Inst)) {
// Comparing a pointer with null, or any other constant, isn't really a use,
// because we don't care what the pointer points to, or about the values
// of any other dynamic reference-counted pointers.
if (!IsPotentialRetainableObjPtr(ICI->getOperand(1), *PA.getAA()))
return false;
} else if (auto CS = ImmutableCallSite(Inst)) {
// For calls, just check the arguments (and not the callee operand).
for (ImmutableCallSite::arg_iterator OI = CS.arg_begin(),
OE = CS.arg_end(); OI != OE; ++OI) {
const Value *Op = *OI;
if (IsPotentialRetainableObjPtr(Op, *PA.getAA()) &&
PA.related(Ptr, Op, DL))
return true;
}
return false;
} else if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
// Special-case stores, because we don't care about the stored value, just
// the store address.
const Value *Op = GetUnderlyingObjCPtr(SI->getPointerOperand(), DL);
// If we can't tell what the underlying object was, assume there is a
// dependence.
return IsPotentialRetainableObjPtr(Op, *PA.getAA()) &&
PA.related(Op, Ptr, DL);
}
// Check each operand for a match.
for (User::const_op_iterator OI = Inst->op_begin(), OE = Inst->op_end();
OI != OE; ++OI) {
const Value *Op = *OI;
if (IsPotentialRetainableObjPtr(Op, *PA.getAA()) && PA.related(Ptr, Op, DL))
return true;
}
return false;
}
/// Test if there can be dependencies on Inst through Arg. This function only
/// tests dependencies relevant for removing pairs of calls.
bool
llvm::objcarc::Depends(DependenceKind Flavor, Instruction *Inst,
const Value *Arg, ProvenanceAnalysis &PA) {
// If we've reached the definition of Arg, stop.
if (Inst == Arg)
return true;
switch (Flavor) {
case NeedsPositiveRetainCount: {
ARCInstKind Class = GetARCInstKind(Inst);
switch (Class) {
case ARCInstKind::AutoreleasepoolPop:
case ARCInstKind::AutoreleasepoolPush:
case ARCInstKind::None:
return false;
default:
return CanUse(Inst, Arg, PA, Class);
}
}
case AutoreleasePoolBoundary: {
ARCInstKind Class = GetARCInstKind(Inst);
switch (Class) {
case ARCInstKind::AutoreleasepoolPop:
case ARCInstKind::AutoreleasepoolPush:
// These mark the end and begin of an autorelease pool scope.
return true;
default:
// Nothing else does this.
return false;
}
}
case CanChangeRetainCount: {
ARCInstKind Class = GetARCInstKind(Inst);
switch (Class) {
case ARCInstKind::AutoreleasepoolPop:
// Conservatively assume this can decrement any count.
return true;
case ARCInstKind::AutoreleasepoolPush:
case ARCInstKind::None:
return false;
default:
return CanAlterRefCount(Inst, Arg, PA, Class);
}
}
case RetainAutoreleaseDep:
switch (GetBasicARCInstKind(Inst)) {
case ARCInstKind::AutoreleasepoolPop:
case ARCInstKind::AutoreleasepoolPush:
// Don't merge an objc_autorelease with an objc_retain inside a different
// autoreleasepool scope.
return true;
case ARCInstKind::Retain:
case ARCInstKind::RetainRV:
// Check for a retain of the same pointer for merging.
return GetArgRCIdentityRoot(Inst) == Arg;
default:
// Nothing else matters for objc_retainAutorelease formation.
return false;
}
case RetainAutoreleaseRVDep: {
ARCInstKind Class = GetBasicARCInstKind(Inst);
switch (Class) {
case ARCInstKind::Retain:
case ARCInstKind::RetainRV:
// Check for a retain of the same pointer for merging.
return GetArgRCIdentityRoot(Inst) == Arg;
default:
// Anything that can autorelease interrupts
// retainAutoreleaseReturnValue formation.
return CanInterruptRV(Class);
}
}
case RetainRVDep:
return CanInterruptRV(GetBasicARCInstKind(Inst));
}
llvm_unreachable("Invalid dependence flavor");
}
/// Walk up the CFG from StartPos (which is in StartBB) and find local and
/// non-local dependencies on Arg.
///
/// TODO: Cache results?
void
llvm::objcarc::FindDependencies(DependenceKind Flavor,
const Value *Arg,
BasicBlock *StartBB, Instruction *StartInst,
SmallPtrSetImpl<Instruction *> &DependingInsts,
SmallPtrSetImpl<const BasicBlock *> &Visited,
ProvenanceAnalysis &PA) {
BasicBlock::iterator StartPos = StartInst->getIterator();
SmallVector<std::pair<BasicBlock *, BasicBlock::iterator>, 4> Worklist;
Worklist.push_back(std::make_pair(StartBB, StartPos));
do {
std::pair<BasicBlock *, BasicBlock::iterator> Pair =
Worklist.pop_back_val();
BasicBlock *LocalStartBB = Pair.first;
BasicBlock::iterator LocalStartPos = Pair.second;
BasicBlock::iterator StartBBBegin = LocalStartBB->begin();
for (;;) {
if (LocalStartPos == StartBBBegin) {
pred_iterator PI(LocalStartBB), PE(LocalStartBB, false);
if (PI == PE)
// If we've reached the function entry, produce a null dependence.
DependingInsts.insert(nullptr);
else
// Add the predecessors to the worklist.
do {
BasicBlock *PredBB = *PI;
if (Visited.insert(PredBB).second)
Worklist.push_back(std::make_pair(PredBB, PredBB->end()));
} while (++PI != PE);
break;
}
Instruction *Inst = &*--LocalStartPos;
if (Depends(Flavor, Inst, Arg, PA)) {
DependingInsts.insert(Inst);
break;
}
}
} while (!Worklist.empty());
// Determine whether the original StartBB post-dominates all of the blocks we
// visited. If not, insert a sentinal indicating that most optimizations are
// not safe.
for (const BasicBlock *BB : Visited) {
if (BB == StartBB)
continue;
const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
const BasicBlock *Succ = *SI;
if (Succ != StartBB && !Visited.count(Succ)) {
DependingInsts.insert(reinterpret_cast<Instruction *>(-1));
return;
}
}
}
}

View File

@ -1,89 +0,0 @@
//===- DependencyAnalysis.h - ObjC ARC Optimization ---*- C++ -*-----------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
///
/// This file declares special dependency analysis routines used in Objective C
/// ARC Optimizations.
///
/// WARNING: This file knows about certain library functions. It recognizes them
/// by name, and hardwires knowledge of their semantics.
///
/// WARNING: This file knows about how certain Objective-C library functions are
/// used. Naive LLVM IR transformations which would otherwise be
/// behavior-preserving may break these assumptions.
///
//===----------------------------------------------------------------------===//
#ifndef LLVM_LIB_TRANSFORMS_OBJCARC_DEPENDENCYANALYSIS_H
#define LLVM_LIB_TRANSFORMS_OBJCARC_DEPENDENCYANALYSIS_H
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/Analysis/ObjCARCInstKind.h"
namespace llvm {
class BasicBlock;
class Instruction;
class Value;
}
namespace llvm {
namespace objcarc {
class ProvenanceAnalysis;
/// \enum DependenceKind
/// \brief Defines different dependence kinds among various ARC constructs.
///
/// There are several kinds of dependence-like concepts in use here.
///
enum DependenceKind {
NeedsPositiveRetainCount,
AutoreleasePoolBoundary,
CanChangeRetainCount,
RetainAutoreleaseDep, ///< Blocks objc_retainAutorelease.
RetainAutoreleaseRVDep, ///< Blocks objc_retainAutoreleaseReturnValue.
RetainRVDep ///< Blocks objc_retainAutoreleasedReturnValue.
};
void FindDependencies(DependenceKind Flavor,
const Value *Arg,
BasicBlock *StartBB, Instruction *StartInst,
SmallPtrSetImpl<Instruction *> &DependingInstructions,
SmallPtrSetImpl<const BasicBlock *> &Visited,
ProvenanceAnalysis &PA);
bool
Depends(DependenceKind Flavor, Instruction *Inst, const Value *Arg,
ProvenanceAnalysis &PA);
/// Test whether the given instruction can "use" the given pointer's object in a
/// way that requires the reference count to be positive.
bool CanUse(const Instruction *Inst, const Value *Ptr, ProvenanceAnalysis &PA,
ARCInstKind Class);
/// Test whether the given instruction can result in a reference count
/// modification (positive or negative) for the pointer's object.
bool CanAlterRefCount(const Instruction *Inst, const Value *Ptr,
ProvenanceAnalysis &PA, ARCInstKind Class);
/// Returns true if we can not conservatively prove that Inst can not decrement
/// the reference count of Ptr. Returns false if we can.
bool CanDecrementRefCount(const Instruction *Inst, const Value *Ptr,
ProvenanceAnalysis &PA, ARCInstKind Class);
static inline bool CanDecrementRefCount(const Instruction *Inst,
const Value *Ptr,
ProvenanceAnalysis &PA) {
return CanDecrementRefCount(Inst, Ptr, PA, GetARCInstKind(Inst));
}
} // namespace objcarc
} // namespace llvm
#endif

View File

@ -1,23 +0,0 @@
;===- ./lib/Transforms/ObjCARC/LLVMBuild.txt -------------------*- Conf -*--===;
;
; The LLVM Compiler Infrastructure
;
; This file is distributed under the University of Illinois Open Source
; License. See LICENSE.TXT for details.
;
;===------------------------------------------------------------------------===;
;
; This is an LLVMBuild description file for the components in this subdirectory.
;
; For more information on the LLVMBuild system, please see:
;
; http://llvm.org/docs/LLVMBuild.html
;
;===------------------------------------------------------------------------===;
[component_0]
type = Library
name = ObjCARC
parent = Transforms
library_name = ObjCARCOpts
required_libraries = Analysis Core Support TransformUtils

View File

@ -1,40 +0,0 @@
//===-- ObjCARC.cpp -------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements common infrastructure for libLLVMObjCARCOpts.a, which
// implements several scalar transformations over the LLVM intermediate
// representation, including the C bindings for that library.
//
//===----------------------------------------------------------------------===//
#include "ObjCARC.h"
#include "llvm-c/Initialization.h"
#include "llvm/InitializePasses.h"
namespace llvm {
class PassRegistry;
}
using namespace llvm;
using namespace llvm::objcarc;
/// initializeObjCARCOptsPasses - Initialize all passes linked into the
/// ObjCARCOpts library.
void llvm::initializeObjCARCOpts(PassRegistry &Registry) {
initializeObjCARCAAWrapperPassPass(Registry);
initializeObjCARCAPElimPass(Registry);
initializeObjCARCExpandPass(Registry);
initializeObjCARCContractPass(Registry);
initializeObjCARCOptPass(Registry);
initializePAEvalPass(Registry);
}
void LLVMInitializeObjCARCOpts(LLVMPassRegistryRef R) {
initializeObjCARCOpts(*unwrap(R));
}

View File

@ -1,88 +0,0 @@
//===- ObjCARC.h - ObjC ARC Optimization --------------*- C++ -*-----------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
/// This file defines common definitions/declarations used by the ObjC ARC
/// Optimizer. ARC stands for Automatic Reference Counting and is a system for
/// managing reference counts for objects in Objective C.
///
/// WARNING: This file knows about certain library functions. It recognizes them
/// by name, and hardwires knowledge of their semantics.
///
/// WARNING: This file knows about how certain Objective-C library functions are
/// used. Naive LLVM IR transformations which would otherwise be
/// behavior-preserving may break these assumptions.
///
//===----------------------------------------------------------------------===//
#ifndef LLVM_LIB_TRANSFORMS_OBJCARC_OBJCARC_H
#define LLVM_LIB_TRANSFORMS_OBJCARC_OBJCARC_H
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Analysis/ObjCARCAnalysisUtils.h"
#include "llvm/Analysis/ObjCARCInstKind.h"
#include "llvm/Analysis/Passes.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/IR/CallSite.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/Module.h"
#include "llvm/Pass.h"
#include "llvm/Transforms/ObjCARC.h"
#include "llvm/Transforms/Utils/Local.h"
namespace llvm {
class raw_ostream;
}
namespace llvm {
namespace objcarc {
/// \brief Erase the given instruction.
///
/// Many ObjC calls return their argument verbatim,
/// so if it's such a call and the return value has users, replace them with the
/// argument value.
///
static inline void EraseInstruction(Instruction *CI) {
Value *OldArg = cast<CallInst>(CI)->getArgOperand(0);
bool Unused = CI->use_empty();
if (!Unused) {
// Replace the return value with the argument.
assert((IsForwarding(GetBasicARCInstKind(CI)) ||
(IsNoopOnNull(GetBasicARCInstKind(CI)) &&
isa<ConstantPointerNull>(OldArg))) &&
"Can't delete non-forwarding instruction with users!");
CI->replaceAllUsesWith(OldArg);
}
CI->eraseFromParent();
if (Unused)
RecursivelyDeleteTriviallyDeadInstructions(OldArg);
}
/// If Inst is a ReturnRV and its operand is a call or invoke, return the
/// operand. Otherwise return null.
static inline const Instruction *getreturnRVOperand(const Instruction &Inst,
ARCInstKind Class) {
if (Class != ARCInstKind::RetainRV)
return nullptr;
const auto *Opnd = Inst.getOperand(0)->stripPointerCasts();
if (const auto *C = dyn_cast<CallInst>(Opnd))
return C;
return dyn_cast<InvokeInst>(Opnd);
}
} // end namespace objcarc
} // end namespace llvm
#endif

View File

@ -1,176 +0,0 @@
//===- ObjCARCAPElim.cpp - ObjC ARC Optimization --------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
///
/// This file defines ObjC ARC optimizations. ARC stands for Automatic
/// Reference Counting and is a system for managing reference counts for objects
/// in Objective C.
///
/// This specific file implements optimizations which remove extraneous
/// autorelease pools.
///
/// WARNING: This file knows about certain library functions. It recognizes them
/// by name, and hardwires knowledge of their semantics.
///
/// WARNING: This file knows about how certain Objective-C library functions are
/// used. Naive LLVM IR transformations which would otherwise be
/// behavior-preserving may break these assumptions.
///
//===----------------------------------------------------------------------===//
#include "ObjCARC.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/IR/Constants.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
using namespace llvm::objcarc;
#define DEBUG_TYPE "objc-arc-ap-elim"
namespace {
/// \brief Autorelease pool elimination.
class ObjCARCAPElim : public ModulePass {
void getAnalysisUsage(AnalysisUsage &AU) const override;
bool runOnModule(Module &M) override;
static bool MayAutorelease(ImmutableCallSite CS, unsigned Depth = 0);
static bool OptimizeBB(BasicBlock *BB);
public:
static char ID;
ObjCARCAPElim() : ModulePass(ID) {
initializeObjCARCAPElimPass(*PassRegistry::getPassRegistry());
}
};
}
char ObjCARCAPElim::ID = 0;
INITIALIZE_PASS(ObjCARCAPElim,
"objc-arc-apelim",
"ObjC ARC autorelease pool elimination",
false, false)
Pass *llvm::createObjCARCAPElimPass() {
return new ObjCARCAPElim();
}
void ObjCARCAPElim::getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesCFG();
}
/// Interprocedurally determine if calls made by the given call site can
/// possibly produce autoreleases.
bool ObjCARCAPElim::MayAutorelease(ImmutableCallSite CS, unsigned Depth) {
if (const Function *Callee = CS.getCalledFunction()) {
if (!Callee->hasExactDefinition())
return true;
for (const BasicBlock &BB : *Callee) {
for (const Instruction &I : BB)
if (ImmutableCallSite JCS = ImmutableCallSite(&I))
// This recursion depth limit is arbitrary. It's just great
// enough to cover known interesting testcases.
if (Depth < 3 &&
!JCS.onlyReadsMemory() &&
MayAutorelease(JCS, Depth + 1))
return true;
}
return false;
}
return true;
}
bool ObjCARCAPElim::OptimizeBB(BasicBlock *BB) {
bool Changed = false;
Instruction *Push = nullptr;
for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
Instruction *Inst = &*I++;
switch (GetBasicARCInstKind(Inst)) {
case ARCInstKind::AutoreleasepoolPush:
Push = Inst;
break;
case ARCInstKind::AutoreleasepoolPop:
// If this pop matches a push and nothing in between can autorelease,
// zap the pair.
if (Push && cast<CallInst>(Inst)->getArgOperand(0) == Push) {
Changed = true;
DEBUG(dbgs() << "ObjCARCAPElim::OptimizeBB: Zapping push pop "
"autorelease pair:\n"
" Pop: " << *Inst << "\n"
<< " Push: " << *Push << "\n");
Inst->eraseFromParent();
Push->eraseFromParent();
}
Push = nullptr;
break;
case ARCInstKind::CallOrUser:
if (MayAutorelease(ImmutableCallSite(Inst)))
Push = nullptr;
break;
default:
break;
}
}
return Changed;
}
bool ObjCARCAPElim::runOnModule(Module &M) {
if (!EnableARCOpts)
return false;
// If nothing in the Module uses ARC, don't do anything.
if (!ModuleHasARC(M))
return false;
if (skipModule(M))
return false;
// Find the llvm.global_ctors variable, as the first step in
// identifying the global constructors. In theory, unnecessary autorelease
// pools could occur anywhere, but in practice it's pretty rare. Global
// ctors are a place where autorelease pools get inserted automatically,
// so it's pretty common for them to be unnecessary, and it's pretty
// profitable to eliminate them.
GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
if (!GV)
return false;
assert(GV->hasDefinitiveInitializer() &&
"llvm.global_ctors is uncooperative!");
bool Changed = false;
// Dig the constructor functions out of GV's initializer.
ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
for (User::op_iterator OI = Init->op_begin(), OE = Init->op_end();
OI != OE; ++OI) {
Value *Op = *OI;
// llvm.global_ctors is an array of three-field structs where the second
// members are constructor functions.
Function *F = dyn_cast<Function>(cast<ConstantStruct>(Op)->getOperand(1));
// If the user used a constructor function with the wrong signature and
// it got bitcasted or whatever, look the other way.
if (!F)
continue;
// Only look at function definitions.
if (F->isDeclaration())
continue;
// Only look at functions with one basic block.
if (std::next(F->begin()) != F->end())
continue;
// Ok, a single-block constructor function definition. Try to optimize it.
Changed |= OptimizeBB(&F->front());
}
return Changed;
}

File diff suppressed because it is too large Load Diff

View File

@ -1,127 +0,0 @@
//===- ObjCARCExpand.cpp - ObjC ARC Optimization --------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
/// This file defines ObjC ARC optimizations. ARC stands for Automatic
/// Reference Counting and is a system for managing reference counts for objects
/// in Objective C.
///
/// This specific file deals with early optimizations which perform certain
/// cleanup operations.
///
/// WARNING: This file knows about certain library functions. It recognizes them
/// by name, and hardwires knowledge of their semantics.
///
/// WARNING: This file knows about how certain Objective-C library functions are
/// used. Naive LLVM IR transformations which would otherwise be
/// behavior-preserving may break these assumptions.
///
//===----------------------------------------------------------------------===//
#include "ObjCARC.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Value.h"
#include "llvm/Pass.h"
#include "llvm/PassAnalysisSupport.h"
#include "llvm/PassRegistry.h"
#include "llvm/PassSupport.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#define DEBUG_TYPE "objc-arc-expand"
namespace llvm {
class Module;
}
using namespace llvm;
using namespace llvm::objcarc;
namespace {
/// \brief Early ARC transformations.
class ObjCARCExpand : public FunctionPass {
void getAnalysisUsage(AnalysisUsage &AU) const override;
bool doInitialization(Module &M) override;
bool runOnFunction(Function &F) override;
/// A flag indicating whether this optimization pass should run.
bool Run;
public:
static char ID;
ObjCARCExpand() : FunctionPass(ID) {
initializeObjCARCExpandPass(*PassRegistry::getPassRegistry());
}
};
}
char ObjCARCExpand::ID = 0;
INITIALIZE_PASS(ObjCARCExpand,
"objc-arc-expand", "ObjC ARC expansion", false, false)
Pass *llvm::createObjCARCExpandPass() {
return new ObjCARCExpand();
}
void ObjCARCExpand::getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesCFG();
}
bool ObjCARCExpand::doInitialization(Module &M) {
Run = ModuleHasARC(M);
return false;
}
bool ObjCARCExpand::runOnFunction(Function &F) {
if (!EnableARCOpts)
return false;
// If nothing in the Module uses ARC, don't do anything.
if (!Run)
return false;
bool Changed = false;
DEBUG(dbgs() << "ObjCARCExpand: Visiting Function: " << F.getName() << "\n");
for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
Instruction *Inst = &*I;
DEBUG(dbgs() << "ObjCARCExpand: Visiting: " << *Inst << "\n");
switch (GetBasicARCInstKind(Inst)) {
case ARCInstKind::Retain:
case ARCInstKind::RetainRV:
case ARCInstKind::Autorelease:
case ARCInstKind::AutoreleaseRV:
case ARCInstKind::FusedRetainAutorelease:
case ARCInstKind::FusedRetainAutoreleaseRV: {
// These calls return their argument verbatim, as a low-level
// optimization. However, this makes high-level optimizations
// harder. Undo any uses of this optimization that the front-end
// emitted here. We'll redo them in the contract pass.
Changed = true;
Value *Value = cast<CallInst>(Inst)->getArgOperand(0);
DEBUG(dbgs() << "ObjCARCExpand: Old = " << *Inst << "\n"
" New = " << *Value << "\n");
Inst->replaceAllUsesWith(Value);
break;
}
default:
break;
}
}
DEBUG(dbgs() << "ObjCARCExpand: Finished List.\n\n");
return Changed;
}

File diff suppressed because it is too large Load Diff

View File

@ -1,186 +0,0 @@
//===- ProvenanceAnalysis.cpp - ObjC ARC Optimization ---------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
/// \file
///
/// This file defines a special form of Alias Analysis called ``Provenance
/// Analysis''. The word ``provenance'' refers to the history of the ownership
/// of an object. Thus ``Provenance Analysis'' is an analysis which attempts to
/// use various techniques to determine if locally
///
/// WARNING: This file knows about certain library functions. It recognizes them
/// by name, and hardwires knowledge of their semantics.
///
/// WARNING: This file knows about how certain Objective-C library functions are
/// used. Naive LLVM IR transformations which would otherwise be
/// behavior-preserving may break these assumptions.
//
//===----------------------------------------------------------------------===//
#include "ProvenanceAnalysis.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Analysis/ObjCARCAnalysisUtils.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Use.h"
#include "llvm/IR/User.h"
#include "llvm/IR/Value.h"
#include "llvm/Support/Casting.h"
#include <utility>
using namespace llvm;
using namespace llvm::objcarc;
bool ProvenanceAnalysis::relatedSelect(const SelectInst *A,
const Value *B) {
const DataLayout &DL = A->getModule()->getDataLayout();
// If the values are Selects with the same condition, we can do a more precise
// check: just check for relations between the values on corresponding arms.
if (const SelectInst *SB = dyn_cast<SelectInst>(B))
if (A->getCondition() == SB->getCondition())
return related(A->getTrueValue(), SB->getTrueValue(), DL) ||
related(A->getFalseValue(), SB->getFalseValue(), DL);
// Check both arms of the Select node individually.
return related(A->getTrueValue(), B, DL) ||
related(A->getFalseValue(), B, DL);
}
bool ProvenanceAnalysis::relatedPHI(const PHINode *A,
const Value *B) {
const DataLayout &DL = A->getModule()->getDataLayout();
// If the values are PHIs in the same block, we can do a more precise as well
// as efficient check: just check for relations between the values on
// corresponding edges.
if (const PHINode *PNB = dyn_cast<PHINode>(B))
if (PNB->getParent() == A->getParent()) {
for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i)
if (related(A->getIncomingValue(i),
PNB->getIncomingValueForBlock(A->getIncomingBlock(i)), DL))
return true;
return false;
}
// Check each unique source of the PHI node against B.
SmallPtrSet<const Value *, 4> UniqueSrc;
for (Value *PV1 : A->incoming_values()) {
if (UniqueSrc.insert(PV1).second && related(PV1, B, DL))
return true;
}
// All of the arms checked out.
return false;
}
/// Test if the value of P, or any value covered by its provenance, is ever
/// stored within the function (not counting callees).
static bool IsStoredObjCPointer(const Value *P) {
SmallPtrSet<const Value *, 8> Visited;
SmallVector<const Value *, 8> Worklist;
Worklist.push_back(P);
Visited.insert(P);
do {
P = Worklist.pop_back_val();
for (const Use &U : P->uses()) {
const User *Ur = U.getUser();
if (isa<StoreInst>(Ur)) {
if (U.getOperandNo() == 0)
// The pointer is stored.
return true;
// The pointed is stored through.
continue;
}
if (isa<CallInst>(Ur))
// The pointer is passed as an argument, ignore this.
continue;
if (isa<PtrToIntInst>(P))
// Assume the worst.
return true;
if (Visited.insert(Ur).second)
Worklist.push_back(Ur);
}
} while (!Worklist.empty());
// Everything checked out.
return false;
}
bool ProvenanceAnalysis::relatedCheck(const Value *A, const Value *B,
const DataLayout &DL) {
// Skip past provenance pass-throughs.
A = GetUnderlyingObjCPtr(A, DL);
B = GetUnderlyingObjCPtr(B, DL);
// Quick check.
if (A == B)
return true;
// Ask regular AliasAnalysis, for a first approximation.
switch (AA->alias(A, B)) {
case NoAlias:
return false;
case MustAlias:
case PartialAlias:
return true;
case MayAlias:
break;
}
bool AIsIdentified = IsObjCIdentifiedObject(A);
bool BIsIdentified = IsObjCIdentifiedObject(B);
// An ObjC-Identified object can't alias a load if it is never locally stored.
if (AIsIdentified) {
// Check for an obvious escape.
if (isa<LoadInst>(B))
return IsStoredObjCPointer(A);
if (BIsIdentified) {
// Check for an obvious escape.
if (isa<LoadInst>(A))
return IsStoredObjCPointer(B);
// Both pointers are identified and escapes aren't an evident problem.
return false;
}
} else if (BIsIdentified) {
// Check for an obvious escape.
if (isa<LoadInst>(A))
return IsStoredObjCPointer(B);
}
// Special handling for PHI and Select.
if (const PHINode *PN = dyn_cast<PHINode>(A))
return relatedPHI(PN, B);
if (const PHINode *PN = dyn_cast<PHINode>(B))
return relatedPHI(PN, A);
if (const SelectInst *S = dyn_cast<SelectInst>(A))
return relatedSelect(S, B);
if (const SelectInst *S = dyn_cast<SelectInst>(B))
return relatedSelect(S, A);
// Conservative.
return true;
}
bool ProvenanceAnalysis::related(const Value *A, const Value *B,
const DataLayout &DL) {
// Begin by inserting a conservative value into the map. If the insertion
// fails, we have the answer already. If it succeeds, leave it there until we
// compute the real answer to guard against recursive queries.
if (A > B) std::swap(A, B);
std::pair<CachedResultsTy::iterator, bool> Pair =
CachedResults.insert(std::make_pair(ValuePairTy(A, B), true));
if (!Pair.second)
return Pair.first->second;
bool Result = relatedCheck(A, B, DL);
CachedResults[ValuePairTy(A, B)] = Result;
return Result;
}

View File

@ -1,83 +0,0 @@
//===- ProvenanceAnalysis.h - ObjC ARC Optimization -------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
/// \file
///
/// This file declares a special form of Alias Analysis called ``Provenance
/// Analysis''. The word ``provenance'' refers to the history of the ownership
/// of an object. Thus ``Provenance Analysis'' is an analysis which attempts to
/// use various techniques to determine if locally
///
/// WARNING: This file knows about certain library functions. It recognizes them
/// by name, and hardwires knowledge of their semantics.
///
/// WARNING: This file knows about how certain Objective-C library functions are
/// used. Naive LLVM IR transformations which would otherwise be
/// behavior-preserving may break these assumptions.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_LIB_TRANSFORMS_OBJCARC_PROVENANCEANALYSIS_H
#define LLVM_LIB_TRANSFORMS_OBJCARC_PROVENANCEANALYSIS_H
#include "llvm/ADT/DenseMap.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include <utility>
namespace llvm {
class DataLayout;
class PHINode;
class SelectInst;
class Value;
namespace objcarc {
/// \brief This is similar to BasicAliasAnalysis, and it uses many of the same
/// techniques, except it uses special ObjC-specific reasoning about pointer
/// relationships.
///
/// In this context ``Provenance'' is defined as the history of an object's
/// ownership. Thus ``Provenance Analysis'' is defined by using the notion of
/// an ``independent provenance source'' of a pointer to determine whether or
/// not two pointers have the same provenance source and thus could
/// potentially be related.
class ProvenanceAnalysis {
AliasAnalysis *AA;
using ValuePairTy = std::pair<const Value *, const Value *>;
using CachedResultsTy = DenseMap<ValuePairTy, bool>;
CachedResultsTy CachedResults;
bool relatedCheck(const Value *A, const Value *B, const DataLayout &DL);
bool relatedSelect(const SelectInst *A, const Value *B);
bool relatedPHI(const PHINode *A, const Value *B);
public:
ProvenanceAnalysis() = default;
ProvenanceAnalysis(const ProvenanceAnalysis &) = delete;
ProvenanceAnalysis &operator=(const ProvenanceAnalysis &) = delete;
void setAA(AliasAnalysis *aa) { AA = aa; }
AliasAnalysis *getAA() const { return AA; }
bool related(const Value *A, const Value *B, const DataLayout &DL);
void clear() {
CachedResults.clear();
}
};
} // end namespace objcarc
} // end namespace llvm
#endif // LLVM_LIB_TRANSFORMS_OBJCARC_PROVENANCEANALYSIS_H

View File

@ -1,94 +0,0 @@
//===- ProvenanceAnalysisEvaluator.cpp - ObjC ARC Optimization ------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "ProvenanceAnalysis.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Analysis/Passes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/Module.h"
#include "llvm/Pass.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
using namespace llvm::objcarc;
namespace {
class PAEval : public FunctionPass {
public:
static char ID;
PAEval();
void getAnalysisUsage(AnalysisUsage &AU) const override;
bool runOnFunction(Function &F) override;
};
}
char PAEval::ID = 0;
PAEval::PAEval() : FunctionPass(ID) {}
void PAEval::getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired<AAResultsWrapperPass>();
}
static StringRef getName(Value *V) {
StringRef Name = V->getName();
if (Name.startswith("\1"))
return Name.substr(1);
return Name;
}
static void insertIfNamed(SetVector<Value *> &Values, Value *V) {
if (!V->hasName())
return;
Values.insert(V);
}
bool PAEval::runOnFunction(Function &F) {
SetVector<Value *> Values;
for (auto &Arg : F.args())
insertIfNamed(Values, &Arg);
for (auto I = inst_begin(F), E = inst_end(F); I != E; ++I) {
insertIfNamed(Values, &*I);
for (auto &Op : I->operands())
insertIfNamed(Values, Op);
}
ProvenanceAnalysis PA;
PA.setAA(&getAnalysis<AAResultsWrapperPass>().getAAResults());
const DataLayout &DL = F.getParent()->getDataLayout();
for (Value *V1 : Values) {
StringRef NameV1 = getName(V1);
for (Value *V2 : Values) {
StringRef NameV2 = getName(V2);
if (NameV1 >= NameV2)
continue;
errs() << NameV1 << " and " << NameV2;
if (PA.related(V1, V2, DL))
errs() << " are related.\n";
else
errs() << " are not related.\n";
}
}
return false;
}
FunctionPass *llvm::createPAEvalPass() { return new PAEval(); }
INITIALIZE_PASS_BEGIN(PAEval, "pa-eval",
"Evaluate ProvenanceAnalysis on all pairs", false, true)
INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
INITIALIZE_PASS_END(PAEval, "pa-eval",
"Evaluate ProvenanceAnalysis on all pairs", false, true)

View File

@ -1,426 +0,0 @@
//===- PtrState.cpp -------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "PtrState.h"
#include "DependencyAnalysis.h"
#include "ObjCARC.h"
#include "llvm/Analysis/ObjCARCAnalysisUtils.h"
#include "llvm/Analysis/ObjCARCInstKind.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Value.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include <cassert>
#include <iterator>
#include <utility>
using namespace llvm;
using namespace llvm::objcarc;
#define DEBUG_TYPE "objc-arc-ptr-state"
//===----------------------------------------------------------------------===//
// Utility
//===----------------------------------------------------------------------===//
raw_ostream &llvm::objcarc::operator<<(raw_ostream &OS, const Sequence S) {
switch (S) {
case S_None:
return OS << "S_None";
case S_Retain:
return OS << "S_Retain";
case S_CanRelease:
return OS << "S_CanRelease";
case S_Use:
return OS << "S_Use";
case S_Release:
return OS << "S_Release";
case S_MovableRelease:
return OS << "S_MovableRelease";
case S_Stop:
return OS << "S_Stop";
}
llvm_unreachable("Unknown sequence type.");
}
//===----------------------------------------------------------------------===//
// Sequence
//===----------------------------------------------------------------------===//
static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
// The easy cases.
if (A == B)
return A;
if (A == S_None || B == S_None)
return S_None;
if (A > B)
std::swap(A, B);
if (TopDown) {
// Choose the side which is further along in the sequence.
if ((A == S_Retain || A == S_CanRelease) &&
(B == S_CanRelease || B == S_Use))
return B;
} else {
// Choose the side which is further along in the sequence.
if ((A == S_Use || A == S_CanRelease) &&
(B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
return A;
// If both sides are releases, choose the more conservative one.
if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
return A;
if (A == S_Release && B == S_MovableRelease)
return A;
}
return S_None;
}
//===----------------------------------------------------------------------===//
// RRInfo
//===----------------------------------------------------------------------===//
void RRInfo::clear() {
KnownSafe = false;
IsTailCallRelease = false;
ReleaseMetadata = nullptr;
Calls.clear();
ReverseInsertPts.clear();
CFGHazardAfflicted = false;
}
bool RRInfo::Merge(const RRInfo &Other) {
// Conservatively merge the ReleaseMetadata information.
if (ReleaseMetadata != Other.ReleaseMetadata)
ReleaseMetadata = nullptr;
// Conservatively merge the boolean state.
KnownSafe &= Other.KnownSafe;
IsTailCallRelease &= Other.IsTailCallRelease;
CFGHazardAfflicted |= Other.CFGHazardAfflicted;
// Merge the call sets.
Calls.insert(Other.Calls.begin(), Other.Calls.end());
// Merge the insert point sets. If there are any differences,
// that makes this a partial merge.
bool Partial = ReverseInsertPts.size() != Other.ReverseInsertPts.size();
for (Instruction *Inst : Other.ReverseInsertPts)
Partial |= ReverseInsertPts.insert(Inst).second;
return Partial;
}
//===----------------------------------------------------------------------===//
// PtrState
//===----------------------------------------------------------------------===//
void PtrState::SetKnownPositiveRefCount() {
DEBUG(dbgs() << " Setting Known Positive.\n");
KnownPositiveRefCount = true;
}
void PtrState::ClearKnownPositiveRefCount() {
DEBUG(dbgs() << " Clearing Known Positive.\n");
KnownPositiveRefCount = false;
}
void PtrState::SetSeq(Sequence NewSeq) {
DEBUG(dbgs() << " Old: " << GetSeq() << "; New: " << NewSeq << "\n");
Seq = NewSeq;
}
void PtrState::ResetSequenceProgress(Sequence NewSeq) {
DEBUG(dbgs() << " Resetting sequence progress.\n");
SetSeq(NewSeq);
Partial = false;
RRI.clear();
}
void PtrState::Merge(const PtrState &Other, bool TopDown) {
Seq = MergeSeqs(GetSeq(), Other.GetSeq(), TopDown);
KnownPositiveRefCount &= Other.KnownPositiveRefCount;
// If we're not in a sequence (anymore), drop all associated state.
if (Seq == S_None) {
Partial = false;
RRI.clear();
} else if (Partial || Other.Partial) {
// If we're doing a merge on a path that's previously seen a partial
// merge, conservatively drop the sequence, to avoid doing partial
// RR elimination. If the branch predicates for the two merge differ,
// mixing them is unsafe.
ClearSequenceProgress();
} else {
// Otherwise merge the other PtrState's RRInfo into our RRInfo. At this
// point, we know that currently we are not partial. Stash whether or not
// the merge operation caused us to undergo a partial merging of reverse
// insertion points.
Partial = RRI.Merge(Other.RRI);
}
}
//===----------------------------------------------------------------------===//
// BottomUpPtrState
//===----------------------------------------------------------------------===//
bool BottomUpPtrState::InitBottomUp(ARCMDKindCache &Cache, Instruction *I) {
// If we see two releases in a row on the same pointer. If so, make
// a note, and we'll cicle back to revisit it after we've
// hopefully eliminated the second release, which may allow us to
// eliminate the first release too.
// Theoretically we could implement removal of nested retain+release
// pairs by making PtrState hold a stack of states, but this is
// simple and avoids adding overhead for the non-nested case.
bool NestingDetected = false;
if (GetSeq() == S_Release || GetSeq() == S_MovableRelease) {
DEBUG(dbgs() << " Found nested releases (i.e. a release pair)\n");
NestingDetected = true;
}
MDNode *ReleaseMetadata =
I->getMetadata(Cache.get(ARCMDKindID::ImpreciseRelease));
Sequence NewSeq = ReleaseMetadata ? S_MovableRelease : S_Release;
ResetSequenceProgress(NewSeq);
SetReleaseMetadata(ReleaseMetadata);
SetKnownSafe(HasKnownPositiveRefCount());
SetTailCallRelease(cast<CallInst>(I)->isTailCall());
InsertCall(I);
SetKnownPositiveRefCount();
return NestingDetected;
}
bool BottomUpPtrState::MatchWithRetain() {
SetKnownPositiveRefCount();
Sequence OldSeq = GetSeq();
switch (OldSeq) {
case S_Stop:
case S_Release:
case S_MovableRelease:
case S_Use:
// If OldSeq is not S_Use or OldSeq is S_Use and we are tracking an
// imprecise release, clear our reverse insertion points.
if (OldSeq != S_Use || IsTrackingImpreciseReleases())
ClearReverseInsertPts();
LLVM_FALLTHROUGH;
case S_CanRelease:
return true;
case S_None:
return false;
case S_Retain:
llvm_unreachable("bottom-up pointer in retain state!");
}
llvm_unreachable("Sequence unknown enum value");
}
bool BottomUpPtrState::HandlePotentialAlterRefCount(Instruction *Inst,
const Value *Ptr,
ProvenanceAnalysis &PA,
ARCInstKind Class) {
Sequence S = GetSeq();
// Check for possible releases.
if (!CanAlterRefCount(Inst, Ptr, PA, Class))
return false;
DEBUG(dbgs() << " CanAlterRefCount: Seq: " << S << "; " << *Ptr
<< "\n");
switch (S) {
case S_Use:
SetSeq(S_CanRelease);
return true;
case S_CanRelease:
case S_Release:
case S_MovableRelease:
case S_Stop:
case S_None:
return false;
case S_Retain:
llvm_unreachable("bottom-up pointer in retain state!");
}
llvm_unreachable("Sequence unknown enum value");
}
void BottomUpPtrState::HandlePotentialUse(BasicBlock *BB, Instruction *Inst,
const Value *Ptr,
ProvenanceAnalysis &PA,
ARCInstKind Class) {
auto SetSeqAndInsertReverseInsertPt = [&](Sequence NewSeq){
assert(!HasReverseInsertPts());
SetSeq(NewSeq);
// If this is an invoke instruction, we're scanning it as part of
// one of its successor blocks, since we can't insert code after it
// in its own block, and we don't want to split critical edges.
BasicBlock::iterator InsertAfter;
if (isa<InvokeInst>(Inst)) {
const auto IP = BB->getFirstInsertionPt();
InsertAfter = IP == BB->end() ? std::prev(BB->end()) : IP;
} else {
InsertAfter = std::next(Inst->getIterator());
}
InsertReverseInsertPt(&*InsertAfter);
};
// Check for possible direct uses.
switch (GetSeq()) {
case S_Release:
case S_MovableRelease:
if (CanUse(Inst, Ptr, PA, Class)) {
DEBUG(dbgs() << " CanUse: Seq: " << GetSeq() << "; " << *Ptr
<< "\n");
SetSeqAndInsertReverseInsertPt(S_Use);
} else if (Seq == S_Release && IsUser(Class)) {
DEBUG(dbgs() << " PreciseReleaseUse: Seq: " << GetSeq() << "; "
<< *Ptr << "\n");
// Non-movable releases depend on any possible objc pointer use.
SetSeqAndInsertReverseInsertPt(S_Stop);
} else if (const auto *Call = getreturnRVOperand(*Inst, Class)) {
if (CanUse(Call, Ptr, PA, GetBasicARCInstKind(Call))) {
DEBUG(dbgs() << " ReleaseUse: Seq: " << GetSeq() << "; "
<< *Ptr << "\n");
SetSeqAndInsertReverseInsertPt(S_Stop);
}
}
break;
case S_Stop:
if (CanUse(Inst, Ptr, PA, Class)) {
DEBUG(dbgs() << " PreciseStopUse: Seq: " << GetSeq() << "; "
<< *Ptr << "\n");
SetSeq(S_Use);
}
break;
case S_CanRelease:
case S_Use:
case S_None:
break;
case S_Retain:
llvm_unreachable("bottom-up pointer in retain state!");
}
}
//===----------------------------------------------------------------------===//
// TopDownPtrState
//===----------------------------------------------------------------------===//
bool TopDownPtrState::InitTopDown(ARCInstKind Kind, Instruction *I) {
bool NestingDetected = false;
// Don't do retain+release tracking for ARCInstKind::RetainRV, because
// it's
// better to let it remain as the first instruction after a call.
if (Kind != ARCInstKind::RetainRV) {
// If we see two retains in a row on the same pointer. If so, make
// a note, and we'll cicle back to revisit it after we've
// hopefully eliminated the second retain, which may allow us to
// eliminate the first retain too.
// Theoretically we could implement removal of nested retain+release
// pairs by making PtrState hold a stack of states, but this is
// simple and avoids adding overhead for the non-nested case.
if (GetSeq() == S_Retain)
NestingDetected = true;
ResetSequenceProgress(S_Retain);
SetKnownSafe(HasKnownPositiveRefCount());
InsertCall(I);
}
SetKnownPositiveRefCount();
return NestingDetected;
}
bool TopDownPtrState::MatchWithRelease(ARCMDKindCache &Cache,
Instruction *Release) {
ClearKnownPositiveRefCount();
Sequence OldSeq = GetSeq();
MDNode *ReleaseMetadata =
Release->getMetadata(Cache.get(ARCMDKindID::ImpreciseRelease));
switch (OldSeq) {
case S_Retain:
case S_CanRelease:
if (OldSeq == S_Retain || ReleaseMetadata != nullptr)
ClearReverseInsertPts();
LLVM_FALLTHROUGH;
case S_Use:
SetReleaseMetadata(ReleaseMetadata);
SetTailCallRelease(cast<CallInst>(Release)->isTailCall());
return true;
case S_None:
return false;
case S_Stop:
case S_Release:
case S_MovableRelease:
llvm_unreachable("top-down pointer in bottom up state!");
}
llvm_unreachable("Sequence unknown enum value");
}
bool TopDownPtrState::HandlePotentialAlterRefCount(Instruction *Inst,
const Value *Ptr,
ProvenanceAnalysis &PA,
ARCInstKind Class) {
// Check for possible releases. Treat clang.arc.use as a releasing instruction
// to prevent sinking a retain past it.
if (!CanAlterRefCount(Inst, Ptr, PA, Class) &&
Class != ARCInstKind::IntrinsicUser)
return false;
DEBUG(dbgs() << " CanAlterRefCount: Seq: " << GetSeq() << "; " << *Ptr
<< "\n");
ClearKnownPositiveRefCount();
switch (GetSeq()) {
case S_Retain:
SetSeq(S_CanRelease);
assert(!HasReverseInsertPts());
InsertReverseInsertPt(Inst);
// One call can't cause a transition from S_Retain to S_CanRelease
// and S_CanRelease to S_Use. If we've made the first transition,
// we're done.
return true;
case S_Use:
case S_CanRelease:
case S_None:
return false;
case S_Stop:
case S_Release:
case S_MovableRelease:
llvm_unreachable("top-down pointer in release state!");
}
llvm_unreachable("covered switch is not covered!?");
}
void TopDownPtrState::HandlePotentialUse(Instruction *Inst, const Value *Ptr,
ProvenanceAnalysis &PA,
ARCInstKind Class) {
// Check for possible direct uses.
switch (GetSeq()) {
case S_CanRelease:
if (!CanUse(Inst, Ptr, PA, Class))
return;
DEBUG(dbgs() << " CanUse: Seq: " << GetSeq() << "; " << *Ptr
<< "\n");
SetSeq(S_Use);
return;
case S_Retain:
case S_Use:
case S_None:
return;
case S_Stop:
case S_Release:
case S_MovableRelease:
llvm_unreachable("top-down pointer in release state!");
}
}

View File

@ -1,213 +0,0 @@
//===- PtrState.h - ARC State for a Ptr -------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains declarations for the ARC state associated with a ptr. It
// is only used by the ARC Sequence Dataflow computation. By separating this
// from the actual dataflow, it is easier to consider the mechanics of the ARC
// optimization separate from the actual predicates being used.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_LIB_TRANSFORMS_OBJCARC_PTRSTATE_H
#define LLVM_LIB_TRANSFORMS_OBJCARC_PTRSTATE_H
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/Analysis/ObjCARCInstKind.h"
#include "llvm/Support/Compiler.h"
namespace llvm {
class BasicBlock;
class Instruction;
class MDNode;
class raw_ostream;
class Value;
namespace objcarc {
class ARCMDKindCache;
class ProvenanceAnalysis;
/// \enum Sequence
///
/// \brief A sequence of states that a pointer may go through in which an
/// objc_retain and objc_release are actually needed.
enum Sequence {
S_None,
S_Retain, ///< objc_retain(x).
S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement.
S_Use, ///< any use of x.
S_Stop, ///< like S_Release, but code motion is stopped.
S_Release, ///< objc_release(x).
S_MovableRelease ///< objc_release(x), !clang.imprecise_release.
};
raw_ostream &operator<<(raw_ostream &OS,
const Sequence S) LLVM_ATTRIBUTE_UNUSED;
/// \brief Unidirectional information about either a
/// retain-decrement-use-release sequence or release-use-decrement-retain
/// reverse sequence.
struct RRInfo {
/// After an objc_retain, the reference count of the referenced
/// object is known to be positive. Similarly, before an objc_release, the
/// reference count of the referenced object is known to be positive. If
/// there are retain-release pairs in code regions where the retain count
/// is known to be positive, they can be eliminated, regardless of any side
/// effects between them.
///
/// Also, a retain+release pair nested within another retain+release
/// pair all on the known same pointer value can be eliminated, regardless
/// of any intervening side effects.
///
/// KnownSafe is true when either of these conditions is satisfied.
bool KnownSafe = false;
/// True of the objc_release calls are all marked with the "tail" keyword.
bool IsTailCallRelease = false;
/// If the Calls are objc_release calls and they all have a
/// clang.imprecise_release tag, this is the metadata tag.
MDNode *ReleaseMetadata = nullptr;
/// For a top-down sequence, the set of objc_retains or
/// objc_retainBlocks. For bottom-up, the set of objc_releases.
SmallPtrSet<Instruction *, 2> Calls;
/// The set of optimal insert positions for moving calls in the opposite
/// sequence.
SmallPtrSet<Instruction *, 2> ReverseInsertPts;
/// If this is true, we cannot perform code motion but can still remove
/// retain/release pairs.
bool CFGHazardAfflicted = false;
RRInfo() = default;
void clear();
/// Conservatively merge the two RRInfo. Returns true if a partial merge has
/// occurred, false otherwise.
bool Merge(const RRInfo &Other);
};
/// \brief This class summarizes several per-pointer runtime properties which
/// are propagated through the flow graph.
class PtrState {
protected:
/// True if the reference count is known to be incremented.
bool KnownPositiveRefCount = false;
/// True if we've seen an opportunity for partial RR elimination, such as
/// pushing calls into a CFG triangle or into one side of a CFG diamond.
bool Partial = false;
/// The current position in the sequence.
unsigned char Seq : 8;
/// Unidirectional information about the current sequence.
RRInfo RRI;
PtrState() : Seq(S_None) {}
public:
bool IsKnownSafe() const { return RRI.KnownSafe; }
void SetKnownSafe(const bool NewValue) { RRI.KnownSafe = NewValue; }
bool IsTailCallRelease() const { return RRI.IsTailCallRelease; }
void SetTailCallRelease(const bool NewValue) {
RRI.IsTailCallRelease = NewValue;
}
bool IsTrackingImpreciseReleases() const {
return RRI.ReleaseMetadata != nullptr;
}
const MDNode *GetReleaseMetadata() const { return RRI.ReleaseMetadata; }
void SetReleaseMetadata(MDNode *NewValue) { RRI.ReleaseMetadata = NewValue; }
bool IsCFGHazardAfflicted() const { return RRI.CFGHazardAfflicted; }
void SetCFGHazardAfflicted(const bool NewValue) {
RRI.CFGHazardAfflicted = NewValue;
}
void SetKnownPositiveRefCount();
void ClearKnownPositiveRefCount();
bool HasKnownPositiveRefCount() const { return KnownPositiveRefCount; }
void SetSeq(Sequence NewSeq);
Sequence GetSeq() const { return static_cast<Sequence>(Seq); }
void ClearSequenceProgress() { ResetSequenceProgress(S_None); }
void ResetSequenceProgress(Sequence NewSeq);
void Merge(const PtrState &Other, bool TopDown);
void InsertCall(Instruction *I) { RRI.Calls.insert(I); }
void InsertReverseInsertPt(Instruction *I) { RRI.ReverseInsertPts.insert(I); }
void ClearReverseInsertPts() { RRI.ReverseInsertPts.clear(); }
bool HasReverseInsertPts() const { return !RRI.ReverseInsertPts.empty(); }
const RRInfo &GetRRInfo() const { return RRI; }
};
struct BottomUpPtrState : PtrState {
BottomUpPtrState() = default;
/// (Re-)Initialize this bottom up pointer returning true if we detected a
/// pointer with nested releases.
bool InitBottomUp(ARCMDKindCache &Cache, Instruction *I);
/// Return true if this set of releases can be paired with a release. Modifies
/// state appropriately to reflect that the matching occurred if it is
/// successful.
///
/// It is assumed that one has already checked that the RCIdentity of the
/// retain and the RCIdentity of this ptr state are the same.
bool MatchWithRetain();
void HandlePotentialUse(BasicBlock *BB, Instruction *Inst, const Value *Ptr,
ProvenanceAnalysis &PA, ARCInstKind Class);
bool HandlePotentialAlterRefCount(Instruction *Inst, const Value *Ptr,
ProvenanceAnalysis &PA, ARCInstKind Class);
};
struct TopDownPtrState : PtrState {
TopDownPtrState() = default;
/// (Re-)Initialize this bottom up pointer returning true if we detected a
/// pointer with nested releases.
bool InitTopDown(ARCInstKind Kind, Instruction *I);
/// Return true if this set of retains can be paired with the given
/// release. Modifies state appropriately to reflect that the matching
/// occurred.
bool MatchWithRelease(ARCMDKindCache &Cache, Instruction *Release);
void HandlePotentialUse(Instruction *Inst, const Value *Ptr,
ProvenanceAnalysis &PA, ARCInstKind Class);
bool HandlePotentialAlterRefCount(Instruction *Inst, const Value *Ptr,
ProvenanceAnalysis &PA, ARCInstKind Class);
};
} // end namespace objcarc
} // end namespace llvm
#endif // LLVM_LIB_TRANSFORMS_OBJCARC_PTRSTATE_H