#include "LLVMContextImpl.h"
#include "llvm/ADT/Triple.h"
#include "llvm/IR/ConstantRange.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/GlobalAlias.h"
#include "llvm/IR/GlobalValue.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/ErrorHandling.h"
using namespace llvm;
static_assert(sizeof(GlobalValue) ==
sizeof(Constant) + 2 * sizeof(void *) + 2 * sizeof(unsigned),
"unexpected GlobalValue size growth");
static_assert(sizeof(GlobalObject) == sizeof(GlobalValue) + sizeof(void *),
"unexpected GlobalObject size growth");
bool GlobalValue::isMaterializable() const {
if (const Function *F = dyn_cast<Function>(this))
return F->isMaterializable();
return false;
}
Error GlobalValue::materialize() {
return getParent()->materialize(this);
}
void GlobalValue::destroyConstantImpl() {
llvm_unreachable("You can't GV->destroyConstantImpl()!");
}
Value *GlobalValue::handleOperandChangeImpl(Value *From, Value *To) {
llvm_unreachable("Unsupported class for handleOperandChange()!");
}
void GlobalValue::copyAttributesFrom(const GlobalValue *Src) {
setVisibility(Src->getVisibility());
setUnnamedAddr(Src->getUnnamedAddr());
setThreadLocalMode(Src->getThreadLocalMode());
setDLLStorageClass(Src->getDLLStorageClass());
setDSOLocal(Src->isDSOLocal());
setPartition(Src->getPartition());
if (Src->hasSanitizerMetadata())
setSanitizerMetadata(Src->getSanitizerMetadata());
else
removeSanitizerMetadata();
}
void GlobalValue::removeFromParent() {
switch (getValueID()) {
#define HANDLE_GLOBAL_VALUE(NAME) \
case Value::NAME##Val: \
return static_cast<NAME *>(this)->removeFromParent();
#include "llvm/IR/Value.def"
default:
break;
}
llvm_unreachable("not a global");
}
void GlobalValue::eraseFromParent() {
switch (getValueID()) {
#define HANDLE_GLOBAL_VALUE(NAME) \
case Value::NAME##Val: \
return static_cast<NAME *>(this)->eraseFromParent();
#include "llvm/IR/Value.def"
default:
break;
}
llvm_unreachable("not a global");
}
GlobalObject::~GlobalObject() { setComdat(nullptr); }
bool GlobalValue::isInterposable() const {
if (isInterposableLinkage(getLinkage()))
return true;
return getParent() && getParent()->getSemanticInterposition() &&
!isDSOLocal();
}
bool GlobalValue::canBenefitFromLocalAlias() const {
auto isDeduplicateComdat = [](const Comdat *C) {
return C && C->getSelectionKind() != Comdat::NoDeduplicate;
};
return hasDefaultVisibility() &&
GlobalObject::isExternalLinkage(getLinkage()) && !isDeclaration() &&
!isa<GlobalIFunc>(this) && !isDeduplicateComdat(getComdat());
}
unsigned GlobalValue::getAddressSpace() const {
PointerType *PtrTy = getType();
return PtrTy->getAddressSpace();
}
void GlobalObject::setAlignment(MaybeAlign Align) {
assert((!Align || *Align <= MaximumAlignment) &&
"Alignment is greater than MaximumAlignment!");
unsigned AlignmentData = encode(Align);
unsigned OldData = getGlobalValueSubClassData();
setGlobalValueSubClassData((OldData & ~AlignmentMask) | AlignmentData);
assert(MaybeAlign(getAlignment()) == Align &&
"Alignment representation error!");
}
void GlobalObject::copyAttributesFrom(const GlobalObject *Src) {
GlobalValue::copyAttributesFrom(Src);
setAlignment(Src->getAlign());
setSection(Src->getSection());
}
std::string GlobalValue::getGlobalIdentifier(StringRef Name,
GlobalValue::LinkageTypes Linkage,
StringRef FileName) {
if (Name[0] == '\1')
Name = Name.substr(1);
std::string NewName = std::string(Name);
if (llvm::GlobalValue::isLocalLinkage(Linkage)) {
if (FileName.empty())
NewName = NewName.insert(0, "<unknown>:");
else
NewName = NewName.insert(0, FileName.str() + ":");
}
return NewName;
}
std::string GlobalValue::getGlobalIdentifier() const {
return getGlobalIdentifier(getName(), getLinkage(),
getParent()->getSourceFileName());
}
StringRef GlobalValue::getSection() const {
if (auto *GA = dyn_cast<GlobalAlias>(this)) {
if (const GlobalObject *GO = GA->getAliaseeObject())
return GO->getSection();
return "";
}
return cast<GlobalObject>(this)->getSection();
}
const Comdat *GlobalValue::getComdat() const {
if (auto *GA = dyn_cast<GlobalAlias>(this)) {
if (const GlobalObject *GO = GA->getAliaseeObject())
return const_cast<GlobalObject *>(GO)->getComdat();
return nullptr;
}
if (isa<GlobalIFunc>(this))
return nullptr;
return cast<GlobalObject>(this)->getComdat();
}
void GlobalObject::setComdat(Comdat *C) {
if (ObjComdat)
ObjComdat->removeUser(this);
ObjComdat = C;
if (C)
C->addUser(this);
}
StringRef GlobalValue::getPartition() const {
if (!hasPartition())
return "";
return getContext().pImpl->GlobalValuePartitions[this];
}
void GlobalValue::setPartition(StringRef S) {
if (!hasPartition() && S.empty())
return;
if (!S.empty())
S = getContext().pImpl->Saver.save(S);
getContext().pImpl->GlobalValuePartitions[this] = S;
HasPartition = !S.empty();
}
using SanitizerMetadata = GlobalValue::SanitizerMetadata;
const SanitizerMetadata &GlobalValue::getSanitizerMetadata() const {
assert(hasSanitizerMetadata());
assert(getContext().pImpl->GlobalValueSanitizerMetadata.count(this));
return getContext().pImpl->GlobalValueSanitizerMetadata[this];
}
void GlobalValue::setSanitizerMetadata(SanitizerMetadata Meta) {
getContext().pImpl->GlobalValueSanitizerMetadata[this] = Meta;
HasSanitizerMetadata = true;
}
void GlobalValue::removeSanitizerMetadata() {
DenseMap<const GlobalValue *, SanitizerMetadata> &MetadataMap =
getContext().pImpl->GlobalValueSanitizerMetadata;
MetadataMap.erase(this);
HasSanitizerMetadata = false;
}
StringRef GlobalObject::getSectionImpl() const {
assert(hasSection());
return getContext().pImpl->GlobalObjectSections[this];
}
void GlobalObject::setSection(StringRef S) {
if (!hasSection() && S.empty())
return;
if (!S.empty())
S = getContext().pImpl->Saver.save(S);
getContext().pImpl->GlobalObjectSections[this] = S;
setGlobalObjectFlag(HasSectionHashEntryBit, !S.empty());
}
bool GlobalValue::isDeclaration() const {
if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(this))
return GV->getNumOperands() == 0;
if (const Function *F = dyn_cast<Function>(this))
return F->empty() && !F->isMaterializable();
assert(isa<GlobalAlias>(this) || isa<GlobalIFunc>(this));
return false;
}
bool GlobalObject::canIncreaseAlignment() const {
if (!isStrongDefinitionForLinker())
return false;
if (hasSection() && getAlign())
return false;
bool isELF =
(!Parent || Triple(Parent->getTargetTriple()).isOSBinFormatELF());
if (isELF && !isDSOLocal())
return false;
return true;
}
template <typename Operation>
static const GlobalObject *
findBaseObject(const Constant *C, DenseSet<const GlobalAlias *> &Aliases,
const Operation &Op) {
if (auto *GO = dyn_cast<GlobalObject>(C)) {
Op(*GO);
return GO;
}
if (auto *GA = dyn_cast<GlobalAlias>(C)) {
Op(*GA);
if (Aliases.insert(GA).second)
return findBaseObject(GA->getOperand(0), Aliases, Op);
}
if (auto *CE = dyn_cast<ConstantExpr>(C)) {
switch (CE->getOpcode()) {
case Instruction::Add: {
auto *LHS = findBaseObject(CE->getOperand(0), Aliases, Op);
auto *RHS = findBaseObject(CE->getOperand(1), Aliases, Op);
if (LHS && RHS)
return nullptr;
return LHS ? LHS : RHS;
}
case Instruction::Sub: {
if (findBaseObject(CE->getOperand(1), Aliases, Op))
return nullptr;
return findBaseObject(CE->getOperand(0), Aliases, Op);
}
case Instruction::IntToPtr:
case Instruction::PtrToInt:
case Instruction::BitCast:
case Instruction::GetElementPtr:
return findBaseObject(CE->getOperand(0), Aliases, Op);
default:
break;
}
}
return nullptr;
}
const GlobalObject *GlobalValue::getAliaseeObject() const {
DenseSet<const GlobalAlias *> Aliases;
return findBaseObject(this, Aliases, [](const GlobalValue &) {});
}
bool GlobalValue::isAbsoluteSymbolRef() const {
auto *GO = dyn_cast<GlobalObject>(this);
if (!GO)
return false;
return GO->getMetadata(LLVMContext::MD_absolute_symbol);
}
Optional<ConstantRange> GlobalValue::getAbsoluteSymbolRange() const {
auto *GO = dyn_cast<GlobalObject>(this);
if (!GO)
return None;
MDNode *MD = GO->getMetadata(LLVMContext::MD_absolute_symbol);
if (!MD)
return None;
return getConstantRangeFromMetadata(*MD);
}
bool GlobalValue::canBeOmittedFromSymbolTable() const {
if (!hasLinkOnceODRLinkage())
return false;
if (hasGlobalUnnamedAddr())
return true;
if (auto *Var = dyn_cast<GlobalVariable>(this))
if (!Var->isConstant())
return false;
return hasAtLeastLocalUnnamedAddr();
}
GlobalVariable::GlobalVariable(Type *Ty, bool constant, LinkageTypes Link,
Constant *InitVal, const Twine &Name,
ThreadLocalMode TLMode, unsigned AddressSpace,
bool isExternallyInitialized)
: GlobalObject(Ty, Value::GlobalVariableVal,
OperandTraits<GlobalVariable>::op_begin(this),
InitVal != nullptr, Link, Name, AddressSpace),
isConstantGlobal(constant),
isExternallyInitializedConstant(isExternallyInitialized) {
assert(!Ty->isFunctionTy() && PointerType::isValidElementType(Ty) &&
"invalid type for global variable");
setThreadLocalMode(TLMode);
if (InitVal) {
assert(InitVal->getType() == Ty &&
"Initializer should be the same type as the GlobalVariable!");
Op<0>() = InitVal;
}
}
GlobalVariable::GlobalVariable(Module &M, Type *Ty, bool constant,
LinkageTypes Link, Constant *InitVal,
const Twine &Name, GlobalVariable *Before,
ThreadLocalMode TLMode,
Optional<unsigned> AddressSpace,
bool isExternallyInitialized)
: GlobalObject(Ty, Value::GlobalVariableVal,
OperandTraits<GlobalVariable>::op_begin(this),
InitVal != nullptr, Link, Name,
AddressSpace
? *AddressSpace
: M.getDataLayout().getDefaultGlobalsAddressSpace()),
isConstantGlobal(constant),
isExternallyInitializedConstant(isExternallyInitialized) {
assert(!Ty->isFunctionTy() && PointerType::isValidElementType(Ty) &&
"invalid type for global variable");
setThreadLocalMode(TLMode);
if (InitVal) {
assert(InitVal->getType() == Ty &&
"Initializer should be the same type as the GlobalVariable!");
Op<0>() = InitVal;
}
if (Before)
Before->getParent()->getGlobalList().insert(Before->getIterator(), this);
else
M.getGlobalList().push_back(this);
}
void GlobalVariable::removeFromParent() {
getParent()->getGlobalList().remove(getIterator());
}
void GlobalVariable::eraseFromParent() {
getParent()->getGlobalList().erase(getIterator());
}
void GlobalVariable::setInitializer(Constant *InitVal) {
if (!InitVal) {
if (hasInitializer()) {
Op<0>().set(nullptr);
setGlobalVariableNumOperands(0);
}
} else {
assert(InitVal->getType() == getValueType() &&
"Initializer type must match GlobalVariable type");
if (!hasInitializer())
setGlobalVariableNumOperands(1);
Op<0>().set(InitVal);
}
}
void GlobalVariable::copyAttributesFrom(const GlobalVariable *Src) {
GlobalObject::copyAttributesFrom(Src);
setExternallyInitialized(Src->isExternallyInitialized());
setAttributes(Src->getAttributes());
}
void GlobalVariable::dropAllReferences() {
User::dropAllReferences();
clearMetadata();
}
GlobalAlias::GlobalAlias(Type *Ty, unsigned AddressSpace, LinkageTypes Link,
const Twine &Name, Constant *Aliasee,
Module *ParentModule)
: GlobalValue(Ty, Value::GlobalAliasVal, &Op<0>(), 1, Link, Name,
AddressSpace) {
setAliasee(Aliasee);
if (ParentModule)
ParentModule->getAliasList().push_back(this);
}
GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
LinkageTypes Link, const Twine &Name,
Constant *Aliasee, Module *ParentModule) {
return new GlobalAlias(Ty, AddressSpace, Link, Name, Aliasee, ParentModule);
}
GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
LinkageTypes Linkage, const Twine &Name,
Module *Parent) {
return create(Ty, AddressSpace, Linkage, Name, nullptr, Parent);
}
GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
LinkageTypes Linkage, const Twine &Name,
GlobalValue *Aliasee) {
return create(Ty, AddressSpace, Linkage, Name, Aliasee, Aliasee->getParent());
}
GlobalAlias *GlobalAlias::create(LinkageTypes Link, const Twine &Name,
GlobalValue *Aliasee) {
return create(Aliasee->getValueType(), Aliasee->getAddressSpace(), Link, Name,
Aliasee);
}
GlobalAlias *GlobalAlias::create(const Twine &Name, GlobalValue *Aliasee) {
return create(Aliasee->getLinkage(), Name, Aliasee);
}
void GlobalAlias::removeFromParent() {
getParent()->getAliasList().remove(getIterator());
}
void GlobalAlias::eraseFromParent() {
getParent()->getAliasList().erase(getIterator());
}
void GlobalAlias::setAliasee(Constant *Aliasee) {
assert((!Aliasee || Aliasee->getType() == getType()) &&
"Alias and aliasee types should match!");
Op<0>().set(Aliasee);
}
const GlobalObject *GlobalAlias::getAliaseeObject() const {
DenseSet<const GlobalAlias *> Aliases;
return findBaseObject(getOperand(0), Aliases, [](const GlobalValue &) {});
}
GlobalIFunc::GlobalIFunc(Type *Ty, unsigned AddressSpace, LinkageTypes Link,
const Twine &Name, Constant *Resolver,
Module *ParentModule)
: GlobalObject(Ty, Value::GlobalIFuncVal, &Op<0>(), 1, Link, Name,
AddressSpace) {
setResolver(Resolver);
if (ParentModule)
ParentModule->getIFuncList().push_back(this);
}
GlobalIFunc *GlobalIFunc::create(Type *Ty, unsigned AddressSpace,
LinkageTypes Link, const Twine &Name,
Constant *Resolver, Module *ParentModule) {
return new GlobalIFunc(Ty, AddressSpace, Link, Name, Resolver, ParentModule);
}
void GlobalIFunc::removeFromParent() {
getParent()->getIFuncList().remove(getIterator());
}
void GlobalIFunc::eraseFromParent() {
getParent()->getIFuncList().erase(getIterator());
}
const Function *GlobalIFunc::getResolverFunction() const {
DenseSet<const GlobalAlias *> Aliases;
return dyn_cast<Function>(
findBaseObject(getResolver(), Aliases, [](const GlobalValue &) {}));
}
void GlobalIFunc::applyAlongResolverPath(
function_ref<void(const GlobalValue &)> Op) const {
DenseSet<const GlobalAlias *> Aliases;
findBaseObject(getResolver(), Aliases, Op);
}