#include "CGCXXABI.h"
#include "CodeGenFunction.h"
#include "CodeGenModule.h"
#include "clang/AST/Attr.h"
#include "clang/AST/CXXInheritance.h"
#include "clang/AST/RecordLayout.h"
#include "clang/Basic/CodeGenOptions.h"
#include "clang/CodeGen/CGFunctionInfo.h"
#include "clang/CodeGen/ConstantInitBuilder.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/Support/Format.h"
#include "llvm/Transforms/Utils/Cloning.h"
#include <algorithm>
#include <cstdio>
using namespace clang;
using namespace CodeGen;
CodeGenVTables::CodeGenVTables(CodeGenModule &CGM)
: CGM(CGM), VTContext(CGM.getContext().getVTableContext()) {}
llvm::Constant *CodeGenModule::GetAddrOfThunk(StringRef Name, llvm::Type *FnTy,
GlobalDecl GD) {
return GetOrCreateLLVMFunction(Name, FnTy, GD, true,
true, true);
}
static void setThunkProperties(CodeGenModule &CGM, const ThunkInfo &Thunk,
llvm::Function *ThunkFn, bool ForVTable,
GlobalDecl GD) {
CGM.setFunctionLinkage(GD, ThunkFn);
CGM.getCXXABI().setThunkLinkage(ThunkFn, ForVTable, GD,
!Thunk.Return.isEmpty());
CGM.setGVProperties(ThunkFn, GD);
if (!CGM.getCXXABI().exportThunk()) {
ThunkFn->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
ThunkFn->setDSOLocal(true);
}
if (CGM.supportsCOMDAT() && ThunkFn->isWeakForLinker())
ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));
}
#ifndef NDEBUG
static bool similar(const ABIArgInfo &infoL, CanQualType typeL,
const ABIArgInfo &infoR, CanQualType typeR) {
return (infoL.getKind() == infoR.getKind() &&
(typeL == typeR ||
(isa<PointerType>(typeL) && isa<PointerType>(typeR)) ||
(isa<ReferenceType>(typeL) && isa<ReferenceType>(typeR))));
}
#endif
static RValue PerformReturnAdjustment(CodeGenFunction &CGF,
QualType ResultType, RValue RV,
const ThunkInfo &Thunk) {
bool NullCheckValue = !ResultType->isReferenceType();
llvm::BasicBlock *AdjustNull = nullptr;
llvm::BasicBlock *AdjustNotNull = nullptr;
llvm::BasicBlock *AdjustEnd = nullptr;
llvm::Value *ReturnValue = RV.getScalarVal();
if (NullCheckValue) {
AdjustNull = CGF.createBasicBlock("adjust.null");
AdjustNotNull = CGF.createBasicBlock("adjust.notnull");
AdjustEnd = CGF.createBasicBlock("adjust.end");
llvm::Value *IsNull = CGF.Builder.CreateIsNull(ReturnValue);
CGF.Builder.CreateCondBr(IsNull, AdjustNull, AdjustNotNull);
CGF.EmitBlock(AdjustNotNull);
}
auto ClassDecl = ResultType->getPointeeType()->getAsCXXRecordDecl();
auto ClassAlign = CGF.CGM.getClassPointerAlignment(ClassDecl);
ReturnValue = CGF.CGM.getCXXABI().performReturnAdjustment(
CGF,
Address(ReturnValue, CGF.ConvertTypeForMem(ResultType->getPointeeType()),
ClassAlign),
Thunk.Return);
if (NullCheckValue) {
CGF.Builder.CreateBr(AdjustEnd);
CGF.EmitBlock(AdjustNull);
CGF.Builder.CreateBr(AdjustEnd);
CGF.EmitBlock(AdjustEnd);
llvm::PHINode *PHI = CGF.Builder.CreatePHI(ReturnValue->getType(), 2);
PHI->addIncoming(ReturnValue, AdjustNotNull);
PHI->addIncoming(llvm::Constant::getNullValue(ReturnValue->getType()),
AdjustNull);
ReturnValue = PHI;
}
return RValue::get(ReturnValue);
}
static void resolveTopLevelMetadata(llvm::Function *Fn,
llvm::ValueToValueMapTy &VMap) {
auto *DIS = Fn->getSubprogram();
if (!DIS)
return;
auto *NewDIS = DIS->replaceWithDistinct(DIS->clone());
VMap.MD()[DIS].reset(NewDIS);
for (auto &BB : Fn->getBasicBlockList()) {
for (auto &I : BB) {
if (auto *DII = dyn_cast<llvm::DbgVariableIntrinsic>(&I)) {
auto *DILocal = DII->getVariable();
if (!DILocal->isResolved())
DILocal->resolve();
}
}
}
}
llvm::Function *
CodeGenFunction::GenerateVarArgsThunk(llvm::Function *Fn,
const CGFunctionInfo &FnInfo,
GlobalDecl GD, const ThunkInfo &Thunk) {
const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
QualType ResultType = FPT->getReturnType();
assert(FnInfo.isVariadic());
llvm::Type *Ty = CGM.getTypes().GetFunctionType(FnInfo);
llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, true);
llvm::Function *BaseFn = cast<llvm::Function>(Callee);
if (!MD->isDefined()) {
CGM.ErrorUnsupported(MD, "return-adjusting thunk with variadic arguments");
return Fn;
}
assert(!BaseFn->isDeclaration() && "cannot clone undefined variadic method");
llvm::ValueToValueMapTy VMap;
resolveTopLevelMetadata(BaseFn, VMap);
llvm::Function *NewFn = llvm::CloneFunction(BaseFn, VMap);
Fn->replaceAllUsesWith(NewFn);
NewFn->takeName(Fn);
Fn->eraseFromParent();
Fn = NewFn;
CurFn = Fn;
llvm::Function::arg_iterator AI = Fn->arg_begin();
if (CGM.ReturnTypeUsesSRet(FnInfo))
++AI;
Address ThisPtr =
Address(&*AI, ConvertTypeForMem(MD->getThisType()->getPointeeType()),
CGM.getClassPointerAlignment(MD->getParent()));
llvm::BasicBlock *EntryBB = &Fn->front();
llvm::BasicBlock::iterator ThisStore =
llvm::find_if(*EntryBB, [&](llvm::Instruction &I) {
return isa<llvm::StoreInst>(I) &&
I.getOperand(0) == ThisPtr.getPointer();
});
assert(ThisStore != EntryBB->end() &&
"Store of this should be in entry block?");
Builder.SetInsertPoint(&*ThisStore);
llvm::Value *AdjustedThisPtr =
CGM.getCXXABI().performThisAdjustment(*this, ThisPtr, Thunk.This);
AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr,
ThisStore->getOperand(0)->getType());
ThisStore->setOperand(0, AdjustedThisPtr);
if (!Thunk.Return.isEmpty()) {
for (llvm::BasicBlock &BB : *Fn) {
llvm::Instruction *T = BB.getTerminator();
if (isa<llvm::ReturnInst>(T)) {
RValue RV = RValue::get(T->getOperand(0));
T->eraseFromParent();
Builder.SetInsertPoint(&BB);
RV = PerformReturnAdjustment(*this, ResultType, RV, Thunk);
Builder.CreateRet(RV.getScalarVal());
break;
}
}
}
return Fn;
}
void CodeGenFunction::StartThunk(llvm::Function *Fn, GlobalDecl GD,
const CGFunctionInfo &FnInfo,
bool IsUnprototyped) {
assert(!CurGD.getDecl() && "CurGD was already set!");
CurGD = GD;
CurFuncIsThunk = true;
const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
QualType ThisType = MD->getThisType();
QualType ResultType;
if (IsUnprototyped)
ResultType = CGM.getContext().VoidTy;
else if (CGM.getCXXABI().HasThisReturn(GD))
ResultType = ThisType;
else if (CGM.getCXXABI().hasMostDerivedReturn(GD))
ResultType = CGM.getContext().VoidPtrTy;
else
ResultType = MD->getType()->castAs<FunctionProtoType>()->getReturnType();
FunctionArgList FunctionArgs;
CGM.getCXXABI().buildThisParam(*this, FunctionArgs);
if (!IsUnprototyped) {
FunctionArgs.append(MD->param_begin(), MD->param_end());
if (isa<CXXDestructorDecl>(MD))
CGM.getCXXABI().addImplicitStructorParams(*this, ResultType,
FunctionArgs);
}
auto NL = ApplyDebugLocation::CreateEmpty(*this);
StartFunction(GlobalDecl(), ResultType, Fn, FnInfo, FunctionArgs,
MD->getLocation());
auto AL = ApplyDebugLocation::CreateArtificial(*this);
CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
CXXThisValue = CXXABIThisValue;
CurCodeDecl = MD;
CurFuncDecl = MD;
}
void CodeGenFunction::FinishThunk() {
CurCodeDecl = nullptr;
CurFuncDecl = nullptr;
FinishFunction();
}
void CodeGenFunction::EmitCallAndReturnForThunk(llvm::FunctionCallee Callee,
const ThunkInfo *Thunk,
bool IsUnprototyped) {
assert(isa<CXXMethodDecl>(CurGD.getDecl()) &&
"Please use a new CGF for this thunk");
const CXXMethodDecl *MD = cast<CXXMethodDecl>(CurGD.getDecl());
llvm::Value *AdjustedThisPtr =
Thunk ? CGM.getCXXABI().performThisAdjustment(
*this, LoadCXXThisAddress(), Thunk->This)
: LoadCXXThis();
if (CurFnInfo->usesInAlloca() || CurFnInfo->isVariadic() || IsUnprototyped) {
if (Thunk && !Thunk->Return.isEmpty()) {
if (IsUnprototyped)
CGM.ErrorUnsupported(
MD, "return-adjusting thunk with incomplete parameter type");
else if (CurFnInfo->isVariadic())
llvm_unreachable("shouldn't try to emit musttail return-adjusting "
"thunks for variadic functions");
else
CGM.ErrorUnsupported(
MD, "non-trivial argument copy for return-adjusting thunk");
}
EmitMustTailThunk(CurGD, AdjustedThisPtr, Callee);
return;
}
CallArgList CallArgs;
QualType ThisType = MD->getThisType();
CallArgs.add(RValue::get(AdjustedThisPtr), ThisType);
if (isa<CXXDestructorDecl>(MD))
CGM.getCXXABI().adjustCallArgsForDestructorThunk(*this, CurGD, CallArgs);
#ifndef NDEBUG
unsigned PrefixArgs = CallArgs.size() - 1;
#endif
for (const ParmVarDecl *PD : MD->parameters())
EmitDelegateCallArg(CallArgs, PD, SourceLocation());
const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
#ifndef NDEBUG
const CGFunctionInfo &CallFnInfo = CGM.getTypes().arrangeCXXMethodCall(
CallArgs, FPT, RequiredArgs::forPrototypePlus(FPT, 1), PrefixArgs);
assert(CallFnInfo.getRegParm() == CurFnInfo->getRegParm() &&
CallFnInfo.isNoReturn() == CurFnInfo->isNoReturn() &&
CallFnInfo.getCallingConvention() == CurFnInfo->getCallingConvention());
assert(isa<CXXDestructorDecl>(MD) || similar(CallFnInfo.getReturnInfo(), CallFnInfo.getReturnType(),
CurFnInfo->getReturnInfo(), CurFnInfo->getReturnType()));
assert(CallFnInfo.arg_size() == CurFnInfo->arg_size());
for (unsigned i = 0, e = CurFnInfo->arg_size(); i != e; ++i)
assert(similar(CallFnInfo.arg_begin()[i].info,
CallFnInfo.arg_begin()[i].type,
CurFnInfo->arg_begin()[i].info,
CurFnInfo->arg_begin()[i].type));
#endif
QualType ResultType = CGM.getCXXABI().HasThisReturn(CurGD)
? ThisType
: CGM.getCXXABI().hasMostDerivedReturn(CurGD)
? CGM.getContext().VoidPtrTy
: FPT->getReturnType();
ReturnValueSlot Slot;
if (!ResultType->isVoidType() &&
(CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect ||
hasAggregateEvaluationKind(ResultType)))
Slot = ReturnValueSlot(ReturnValue, ResultType.isVolatileQualified(),
false, true);
llvm::CallBase *CallOrInvoke;
RValue RV = EmitCall(*CurFnInfo, CGCallee::forDirect(Callee, CurGD), Slot,
CallArgs, &CallOrInvoke);
if (Thunk && !Thunk->Return.isEmpty())
RV = PerformReturnAdjustment(*this, ResultType, RV, *Thunk);
else if (llvm::CallInst* Call = dyn_cast<llvm::CallInst>(CallOrInvoke))
Call->setTailCallKind(llvm::CallInst::TCK_Tail);
if (!ResultType->isVoidType() && Slot.isNull())
CGM.getCXXABI().EmitReturnFromThunk(*this, RV, ResultType);
AutoreleaseResult = false;
FinishThunk();
}
void CodeGenFunction::EmitMustTailThunk(GlobalDecl GD,
llvm::Value *AdjustedThisPtr,
llvm::FunctionCallee Callee) {
SmallVector<llvm::Value *, 8> Args(llvm::make_pointer_range(CurFn->args()));
const ABIArgInfo &ThisAI = CurFnInfo->arg_begin()->info;
if (ThisAI.isDirect()) {
const ABIArgInfo &RetAI = CurFnInfo->getReturnInfo();
int ThisArgNo = RetAI.isIndirect() && !RetAI.isSRetAfterThis() ? 1 : 0;
llvm::Type *ThisType = Args[ThisArgNo]->getType();
if (ThisType != AdjustedThisPtr->getType())
AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
Args[ThisArgNo] = AdjustedThisPtr;
} else {
assert(ThisAI.isInAlloca() && "this is passed directly or inalloca");
Address ThisAddr = GetAddrOfLocalVar(CXXABIThisDecl);
llvm::Type *ThisType = ThisAddr.getElementType();
if (ThisType != AdjustedThisPtr->getType())
AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
Builder.CreateStore(AdjustedThisPtr, ThisAddr);
}
llvm::CallInst *Call = Builder.CreateCall(Callee, Args);
Call->setTailCallKind(llvm::CallInst::TCK_MustTail);
unsigned CallingConv;
llvm::AttributeList Attrs;
CGM.ConstructAttributeList(Callee.getCallee()->getName(), *CurFnInfo, GD,
Attrs, CallingConv, true,
false);
Call->setAttributes(Attrs);
Call->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
if (Call->getType()->isVoidTy())
Builder.CreateRetVoid();
else
Builder.CreateRet(Call);
EmitBlock(createBasicBlock());
FinishThunk();
}
void CodeGenFunction::generateThunk(llvm::Function *Fn,
const CGFunctionInfo &FnInfo, GlobalDecl GD,
const ThunkInfo &Thunk,
bool IsUnprototyped) {
StartThunk(Fn, GD, FnInfo, IsUnprototyped);
auto AL = ApplyDebugLocation::CreateArtificial(*this);
llvm::Type *Ty;
if (IsUnprototyped)
Ty = llvm::StructType::get(getLLVMContext());
else
Ty = CGM.getTypes().GetFunctionType(FnInfo);
llvm::Constant *Callee = CGM.GetAddrOfFunction(GD, Ty, true);
if (IsUnprototyped)
Callee = llvm::ConstantExpr::getBitCast(Callee, Fn->getType());
EmitCallAndReturnForThunk(llvm::FunctionCallee(Fn->getFunctionType(), Callee),
&Thunk, IsUnprototyped);
}
static bool shouldEmitVTableThunk(CodeGenModule &CGM, const CXXMethodDecl *MD,
bool IsUnprototyped, bool ForVTable) {
if (CGM.getTarget().getCXXABI().isMicrosoft())
return true;
if (ForVTable)
return CGM.getCodeGenOpts().OptimizationLevel && !IsUnprototyped;
return true;
}
llvm::Constant *CodeGenVTables::maybeEmitThunk(GlobalDecl GD,
const ThunkInfo &TI,
bool ForVTable) {
const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
SmallString<256> Name;
MangleContext &MCtx = CGM.getCXXABI().getMangleContext();
llvm::raw_svector_ostream Out(Name);
if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD))
MCtx.mangleCXXDtorThunk(DD, GD.getDtorType(), TI.This, Out);
else
MCtx.mangleThunk(MD, TI, Out);
llvm::Type *ThunkVTableTy = CGM.getTypes().GetFunctionTypeForVTable(GD);
llvm::Constant *Thunk = CGM.GetAddrOfThunk(Name, ThunkVTableTy, GD);
bool IsUnprototyped = !CGM.getTypes().isFuncTypeConvertible(
MD->getType()->castAs<FunctionType>());
if (!shouldEmitVTableThunk(CGM, MD, IsUnprototyped, ForVTable))
return Thunk;
const CGFunctionInfo &FnInfo =
IsUnprototyped ? CGM.getTypes().arrangeUnprototypedMustTailThunk(MD)
: CGM.getTypes().arrangeGlobalDeclaration(GD);
llvm::FunctionType *ThunkFnTy = CGM.getTypes().GetFunctionType(FnInfo);
llvm::Function *ThunkFn = cast<llvm::Function>(Thunk->stripPointerCasts());
if (ThunkFn->getFunctionType() != ThunkFnTy) {
llvm::GlobalValue *OldThunkFn = ThunkFn;
assert(OldThunkFn->isDeclaration() && "Shouldn't replace non-declaration");
OldThunkFn->setName(StringRef());
ThunkFn = llvm::Function::Create(ThunkFnTy, llvm::Function::ExternalLinkage,
Name.str(), &CGM.getModule());
CGM.SetLLVMFunctionAttributes(MD, FnInfo, ThunkFn, false);
if (!OldThunkFn->use_empty()) {
llvm::Constant *NewPtrForOldDecl =
llvm::ConstantExpr::getBitCast(ThunkFn, OldThunkFn->getType());
OldThunkFn->replaceAllUsesWith(NewPtrForOldDecl);
}
OldThunkFn->eraseFromParent();
}
bool ABIHasKeyFunctions = CGM.getTarget().getCXXABI().hasKeyFunctions();
bool UseAvailableExternallyLinkage = ForVTable && ABIHasKeyFunctions;
if (!ThunkFn->isDeclaration()) {
if (!ABIHasKeyFunctions || UseAvailableExternallyLinkage) {
return ThunkFn;
}
setThunkProperties(CGM, TI, ThunkFn, ForVTable, GD);
return ThunkFn;
}
if (IsUnprototyped)
ThunkFn->addFnAttr("thunk");
CGM.SetLLVMFunctionAttributesForDefinition(GD.getDecl(), ThunkFn);
bool ShouldCloneVarArgs = false;
if (!IsUnprototyped && ThunkFn->isVarArg()) {
ShouldCloneVarArgs = true;
if (TI.Return.isEmpty()) {
switch (CGM.getTriple().getArch()) {
case llvm::Triple::x86_64:
case llvm::Triple::x86:
case llvm::Triple::aarch64:
ShouldCloneVarArgs = false;
break;
default:
break;
}
}
}
if (ShouldCloneVarArgs) {
if (UseAvailableExternallyLinkage)
return ThunkFn;
ThunkFn =
CodeGenFunction(CGM).GenerateVarArgsThunk(ThunkFn, FnInfo, GD, TI);
} else {
CodeGenFunction(CGM).generateThunk(ThunkFn, FnInfo, GD, TI, IsUnprototyped);
}
setThunkProperties(CGM, TI, ThunkFn, ForVTable, GD);
return ThunkFn;
}
void CodeGenVTables::EmitThunks(GlobalDecl GD) {
const CXXMethodDecl *MD =
cast<CXXMethodDecl>(GD.getDecl())->getCanonicalDecl();
if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
return;
const VTableContextBase::ThunkInfoVectorTy *ThunkInfoVector =
VTContext->getThunkInfo(GD);
if (!ThunkInfoVector)
return;
for (const ThunkInfo& Thunk : *ThunkInfoVector)
maybeEmitThunk(GD, Thunk, false);
}
void CodeGenVTables::addRelativeComponent(ConstantArrayBuilder &builder,
llvm::Constant *component,
unsigned vtableAddressPoint,
bool vtableHasLocalLinkage,
bool isCompleteDtor) const {
if (component->isNullValue())
return builder.add(llvm::ConstantInt::get(CGM.Int32Ty, 0));
auto *globalVal =
cast<llvm::GlobalValue>(component->stripPointerCastsAndAliases());
llvm::Module &module = CGM.getModule();
auto stubLinkage = vtableHasLocalLinkage ? llvm::GlobalValue::InternalLinkage
: llvm::GlobalValue::ExternalLinkage;
llvm::Constant *target;
if (auto *func = dyn_cast<llvm::Function>(globalVal)) {
target = llvm::DSOLocalEquivalent::get(func);
} else {
llvm::SmallString<16> rttiProxyName(globalVal->getName());
rttiProxyName.append(".rtti_proxy");
llvm::GlobalVariable *proxy = module.getNamedGlobal(rttiProxyName);
if (!proxy) {
proxy = new llvm::GlobalVariable(module, globalVal->getType(),
true, stubLinkage,
globalVal, rttiProxyName);
proxy->setDSOLocal(true);
proxy->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
if (!proxy->hasLocalLinkage()) {
proxy->setVisibility(llvm::GlobalValue::HiddenVisibility);
proxy->setComdat(module.getOrInsertComdat(rttiProxyName));
}
}
target = proxy;
}
builder.addRelativeOffsetToPosition(CGM.Int32Ty, target,
vtableAddressPoint);
}
bool CodeGenVTables::useRelativeLayout() const {
return CGM.getTarget().getCXXABI().isItaniumFamily() &&
CGM.getItaniumVTableContext().isRelativeLayout();
}
llvm::Type *CodeGenVTables::getVTableComponentType() const {
if (useRelativeLayout())
return CGM.Int32Ty;
return CGM.Int8PtrTy;
}
static void AddPointerLayoutOffset(const CodeGenModule &CGM,
ConstantArrayBuilder &builder,
CharUnits offset) {
builder.add(llvm::ConstantExpr::getIntToPtr(
llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity()),
CGM.Int8PtrTy));
}
static void AddRelativeLayoutOffset(const CodeGenModule &CGM,
ConstantArrayBuilder &builder,
CharUnits offset) {
builder.add(llvm::ConstantInt::get(CGM.Int32Ty, offset.getQuantity()));
}
void CodeGenVTables::addVTableComponent(ConstantArrayBuilder &builder,
const VTableLayout &layout,
unsigned componentIndex,
llvm::Constant *rtti,
unsigned &nextVTableThunkIndex,
unsigned vtableAddressPoint,
bool vtableHasLocalLinkage) {
auto &component = layout.vtable_components()[componentIndex];
auto addOffsetConstant =
useRelativeLayout() ? AddRelativeLayoutOffset : AddPointerLayoutOffset;
switch (component.getKind()) {
case VTableComponent::CK_VCallOffset:
return addOffsetConstant(CGM, builder, component.getVCallOffset());
case VTableComponent::CK_VBaseOffset:
return addOffsetConstant(CGM, builder, component.getVBaseOffset());
case VTableComponent::CK_OffsetToTop:
return addOffsetConstant(CGM, builder, component.getOffsetToTop());
case VTableComponent::CK_RTTI:
if (useRelativeLayout())
return addRelativeComponent(builder, rtti, vtableAddressPoint,
vtableHasLocalLinkage,
false);
else
return builder.add(llvm::ConstantExpr::getBitCast(rtti, CGM.Int8PtrTy));
case VTableComponent::CK_FunctionPointer:
case VTableComponent::CK_CompleteDtorPointer:
case VTableComponent::CK_DeletingDtorPointer: {
GlobalDecl GD = component.getGlobalDecl();
if (CGM.getLangOpts().CUDA) {
const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
bool CanEmitMethod =
CGM.getLangOpts().CUDAIsDevice
? MD->hasAttr<CUDADeviceAttr>()
: (MD->hasAttr<CUDAHostAttr>() || !MD->hasAttr<CUDADeviceAttr>());
if (!CanEmitMethod)
return builder.add(llvm::ConstantExpr::getNullValue(CGM.Int8PtrTy));
}
auto getSpecialVirtualFn = [&](StringRef name) -> llvm::Constant * {
if (useRelativeLayout())
return llvm::ConstantPointerNull::get(CGM.Int8PtrTy);
if (CGM.getLangOpts().OpenMP && CGM.getLangOpts().OpenMPIsDevice &&
CGM.getTriple().isNVPTX())
return llvm::ConstantPointerNull::get(CGM.Int8PtrTy);
llvm::FunctionType *fnTy =
llvm::FunctionType::get(CGM.VoidTy, false);
llvm::Constant *fn = cast<llvm::Constant>(
CGM.CreateRuntimeFunction(fnTy, name).getCallee());
if (auto f = dyn_cast<llvm::Function>(fn))
f->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
return llvm::ConstantExpr::getBitCast(fn, CGM.Int8PtrTy);
};
llvm::Constant *fnPtr;
if (cast<CXXMethodDecl>(GD.getDecl())->isPure()) {
if (!PureVirtualFn)
PureVirtualFn =
getSpecialVirtualFn(CGM.getCXXABI().GetPureVirtualCallName());
fnPtr = PureVirtualFn;
} else if (cast<CXXMethodDecl>(GD.getDecl())->isDeleted()) {
if (!DeletedVirtualFn)
DeletedVirtualFn =
getSpecialVirtualFn(CGM.getCXXABI().GetDeletedVirtualCallName());
fnPtr = DeletedVirtualFn;
} else if (nextVTableThunkIndex < layout.vtable_thunks().size() &&
layout.vtable_thunks()[nextVTableThunkIndex].first ==
componentIndex) {
auto &thunkInfo = layout.vtable_thunks()[nextVTableThunkIndex].second;
nextVTableThunkIndex++;
fnPtr = maybeEmitThunk(GD, thunkInfo, true);
} else {
llvm::Type *fnTy = CGM.getTypes().GetFunctionTypeForVTable(GD);
fnPtr = CGM.GetAddrOfFunction(GD, fnTy, true);
}
if (useRelativeLayout()) {
return addRelativeComponent(
builder, fnPtr, vtableAddressPoint, vtableHasLocalLinkage,
component.getKind() == VTableComponent::CK_CompleteDtorPointer);
} else
return builder.add(llvm::ConstantExpr::getBitCast(fnPtr, CGM.Int8PtrTy));
}
case VTableComponent::CK_UnusedFunctionPointer:
if (useRelativeLayout())
return builder.add(llvm::ConstantExpr::getNullValue(CGM.Int32Ty));
else
return builder.addNullPointer(CGM.Int8PtrTy);
}
llvm_unreachable("Unexpected vtable component kind");
}
llvm::Type *CodeGenVTables::getVTableType(const VTableLayout &layout) {
SmallVector<llvm::Type *, 4> tys;
llvm::Type *componentType = getVTableComponentType();
for (unsigned i = 0, e = layout.getNumVTables(); i != e; ++i)
tys.push_back(llvm::ArrayType::get(componentType, layout.getVTableSize(i)));
return llvm::StructType::get(CGM.getLLVMContext(), tys);
}
void CodeGenVTables::createVTableInitializer(ConstantStructBuilder &builder,
const VTableLayout &layout,
llvm::Constant *rtti,
bool vtableHasLocalLinkage) {
llvm::Type *componentType = getVTableComponentType();
const auto &addressPoints = layout.getAddressPointIndices();
unsigned nextVTableThunkIndex = 0;
for (unsigned vtableIndex = 0, endIndex = layout.getNumVTables();
vtableIndex != endIndex; ++vtableIndex) {
auto vtableElem = builder.beginArray(componentType);
size_t vtableStart = layout.getVTableOffset(vtableIndex);
size_t vtableEnd = vtableStart + layout.getVTableSize(vtableIndex);
for (size_t componentIndex = vtableStart; componentIndex < vtableEnd;
++componentIndex) {
addVTableComponent(vtableElem, layout, componentIndex, rtti,
nextVTableThunkIndex, addressPoints[vtableIndex],
vtableHasLocalLinkage);
}
vtableElem.finishAndAddTo(builder);
}
}
llvm::GlobalVariable *CodeGenVTables::GenerateConstructionVTable(
const CXXRecordDecl *RD, const BaseSubobject &Base, bool BaseIsVirtual,
llvm::GlobalVariable::LinkageTypes Linkage,
VTableAddressPointsMapTy &AddressPoints) {
if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
DI->completeClassData(Base.getBase());
std::unique_ptr<VTableLayout> VTLayout(
getItaniumVTableContext().createConstructionVTableLayout(
Base.getBase(), Base.getBaseOffset(), BaseIsVirtual, RD));
AddressPoints = VTLayout->getAddressPoints();
SmallString<256> OutName;
llvm::raw_svector_ostream Out(OutName);
cast<ItaniumMangleContext>(CGM.getCXXABI().getMangleContext())
.mangleCXXCtorVTable(RD, Base.getBaseOffset().getQuantity(),
Base.getBase(), Out);
SmallString<256> Name(OutName);
bool UsingRelativeLayout = getItaniumVTableContext().isRelativeLayout();
bool VTableAliasExists =
UsingRelativeLayout && CGM.getModule().getNamedAlias(Name);
if (VTableAliasExists) {
Name.append(".local");
}
llvm::Type *VTType = getVTableType(*VTLayout);
if (Linkage == llvm::GlobalVariable::AvailableExternallyLinkage)
Linkage = llvm::GlobalVariable::InternalLinkage;
unsigned Align = CGM.getDataLayout().getABITypeAlignment(VTType);
llvm::GlobalVariable *VTable =
CGM.CreateOrReplaceCXXRuntimeVariable(Name, VTType, Linkage, Align);
VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
llvm::Constant *RTTI = CGM.GetAddrOfRTTIDescriptor(
CGM.getContext().getTagDeclType(Base.getBase()));
ConstantInitBuilder builder(CGM);
auto components = builder.beginStruct();
createVTableInitializer(components, *VTLayout, RTTI,
VTable->hasLocalLinkage());
components.finishAndSetAsInitializer(VTable);
assert(!VTable->isDeclaration() && "Shouldn't set properties on declaration");
CGM.setGVProperties(VTable, RD);
CGM.EmitVTableTypeMetadata(RD, VTable, *VTLayout.get());
if (UsingRelativeLayout && !VTable->isDSOLocal())
GenerateRelativeVTableAlias(VTable, OutName);
return VTable;
}
void CodeGenVTables::GenerateRelativeVTableAlias(llvm::GlobalVariable *VTable,
llvm::StringRef AliasNameRef) {
assert(getItaniumVTableContext().isRelativeLayout() &&
"Can only use this if the relative vtable ABI is used");
assert(!VTable->isDSOLocal() && "This should be called only if the vtable is "
"not guaranteed to be dso_local");
if (VTable->hasAvailableExternallyLinkage())
return;
llvm::SmallString<256> AliasName(AliasNameRef);
VTable->setName(AliasName + ".local");
auto Linkage = VTable->getLinkage();
assert(llvm::GlobalAlias::isValidLinkage(Linkage) &&
"Invalid vtable alias linkage");
llvm::GlobalAlias *VTableAlias = CGM.getModule().getNamedAlias(AliasName);
if (!VTableAlias) {
VTableAlias = llvm::GlobalAlias::create(VTable->getValueType(),
VTable->getAddressSpace(), Linkage,
AliasName, &CGM.getModule());
} else {
assert(VTableAlias->getValueType() == VTable->getValueType());
assert(VTableAlias->getLinkage() == Linkage);
}
VTableAlias->setVisibility(VTable->getVisibility());
VTableAlias->setUnnamedAddr(VTable->getUnnamedAddr());
if (!VTable->hasComdat()) {
VTable->setLinkage(llvm::GlobalValue::PrivateLinkage);
} else {
VTable->setVisibility(llvm::GlobalValue::HiddenVisibility);
}
VTableAlias->setAliasee(VTable);
}
static bool shouldEmitAvailableExternallyVTable(const CodeGenModule &CGM,
const CXXRecordDecl *RD) {
return CGM.getCodeGenOpts().OptimizationLevel > 0 &&
CGM.getCXXABI().canSpeculativelyEmitVTable(RD);
}
llvm::GlobalVariable::LinkageTypes
CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
if (!RD->isExternallyVisible())
return llvm::GlobalVariable::InternalLinkage;
const CXXMethodDecl *keyFunction = Context.getCurrentKeyFunction(RD);
if (keyFunction && !RD->hasAttr<DLLImportAttr>()) {
const FunctionDecl *def = nullptr;
if (keyFunction->hasBody(def))
keyFunction = cast<CXXMethodDecl>(def);
switch (keyFunction->getTemplateSpecializationKind()) {
case TSK_Undeclared:
case TSK_ExplicitSpecialization:
assert((def || CodeGenOpts.OptimizationLevel > 0 ||
CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo) &&
"Shouldn't query vtable linkage without key function, "
"optimizations, or debug info");
if (!def && CodeGenOpts.OptimizationLevel > 0)
return llvm::GlobalVariable::AvailableExternallyLinkage;
if (keyFunction->isInlined())
return !Context.getLangOpts().AppleKext ?
llvm::GlobalVariable::LinkOnceODRLinkage :
llvm::Function::InternalLinkage;
return llvm::GlobalVariable::ExternalLinkage;
case TSK_ImplicitInstantiation:
return !Context.getLangOpts().AppleKext ?
llvm::GlobalVariable::LinkOnceODRLinkage :
llvm::Function::InternalLinkage;
case TSK_ExplicitInstantiationDefinition:
return !Context.getLangOpts().AppleKext ?
llvm::GlobalVariable::WeakODRLinkage :
llvm::Function::InternalLinkage;
case TSK_ExplicitInstantiationDeclaration:
llvm_unreachable("Should not have been asked to emit this");
}
}
if (Context.getLangOpts().AppleKext)
return llvm::Function::InternalLinkage;
llvm::GlobalVariable::LinkageTypes DiscardableODRLinkage =
llvm::GlobalValue::LinkOnceODRLinkage;
llvm::GlobalVariable::LinkageTypes NonDiscardableODRLinkage =
llvm::GlobalValue::WeakODRLinkage;
if (RD->hasAttr<DLLExportAttr>()) {
DiscardableODRLinkage = NonDiscardableODRLinkage;
} else if (RD->hasAttr<DLLImportAttr>()) {
DiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
NonDiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
}
switch (RD->getTemplateSpecializationKind()) {
case TSK_Undeclared:
case TSK_ExplicitSpecialization:
case TSK_ImplicitInstantiation:
return DiscardableODRLinkage;
case TSK_ExplicitInstantiationDeclaration:
if (getTarget().getCXXABI().isMicrosoft())
return DiscardableODRLinkage;
return shouldEmitAvailableExternallyVTable(*this, RD)
? llvm::GlobalVariable::AvailableExternallyLinkage
: llvm::GlobalVariable::ExternalLinkage;
case TSK_ExplicitInstantiationDefinition:
return NonDiscardableODRLinkage;
}
llvm_unreachable("Invalid TemplateSpecializationKind!");
}
void CodeGenModule::EmitVTable(CXXRecordDecl *theClass) {
VTables.GenerateClassData(theClass);
}
void
CodeGenVTables::GenerateClassData(const CXXRecordDecl *RD) {
if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
DI->completeClassData(RD);
if (RD->getNumVBases())
CGM.getCXXABI().emitVirtualInheritanceTables(RD);
CGM.getCXXABI().emitVTableDefinitions(*this, RD);
}
bool CodeGenVTables::isVTableExternal(const CXXRecordDecl *RD) {
assert(RD->isDynamicClass() && "Non-dynamic classes have no VTable.");
if (CGM.getTarget().getCXXABI().isMicrosoft())
return false;
TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
if (TSK == TSK_ExplicitInstantiationDeclaration)
return true;
if (TSK == TSK_ImplicitInstantiation ||
TSK == TSK_ExplicitInstantiationDefinition)
return false;
const CXXMethodDecl *keyFunction = CGM.getContext().getCurrentKeyFunction(RD);
if (!keyFunction)
return false;
return !keyFunction->hasBody();
}
static bool shouldEmitVTableAtEndOfTranslationUnit(CodeGenModule &CGM,
const CXXRecordDecl *RD) {
if (!CGM.getVTables().isVTableExternal(RD))
return true;
return shouldEmitAvailableExternallyVTable(CGM, RD);
}
void CodeGenModule::EmitDeferredVTables() {
#ifndef NDEBUG
size_t savedSize = DeferredVTables.size();
#endif
for (const CXXRecordDecl *RD : DeferredVTables)
if (shouldEmitVTableAtEndOfTranslationUnit(*this, RD))
VTables.GenerateClassData(RD);
else if (shouldOpportunisticallyEmitVTables())
OpportunisticVTables.push_back(RD);
assert(savedSize == DeferredVTables.size() &&
"deferred extra vtables during vtable emission?");
DeferredVTables.clear();
}
bool CodeGenModule::AlwaysHasLTOVisibilityPublic(const CXXRecordDecl *RD) {
if (RD->hasAttr<LTOVisibilityPublicAttr>() || RD->hasAttr<UuidAttr>())
return true;
if (!getCodeGenOpts().LTOVisibilityPublicStd)
return false;
const DeclContext *DC = RD;
while (true) {
auto *D = cast<Decl>(DC);
DC = DC->getParent();
if (isa<TranslationUnitDecl>(DC->getRedeclContext())) {
if (auto *ND = dyn_cast<NamespaceDecl>(D))
if (const IdentifierInfo *II = ND->getIdentifier())
if (II->isStr("std") || II->isStr("stdext"))
return true;
break;
}
}
return false;
}
bool CodeGenModule::HasHiddenLTOVisibility(const CXXRecordDecl *RD) {
LinkageInfo LV = RD->getLinkageAndVisibility();
if (!isExternallyVisible(LV.getLinkage()))
return true;
if (getTriple().isOSBinFormatCOFF()) {
if (RD->hasAttr<DLLExportAttr>() || RD->hasAttr<DLLImportAttr>())
return false;
} else {
if (LV.getVisibility() != HiddenVisibility)
return false;
}
return !AlwaysHasLTOVisibilityPublic(RD);
}
llvm::GlobalObject::VCallVisibility CodeGenModule::GetVCallVisibilityLevel(
const CXXRecordDecl *RD, llvm::DenseSet<const CXXRecordDecl *> &Visited) {
if (!Visited.insert(RD).second)
return llvm::GlobalObject::VCallVisibilityTranslationUnit;
LinkageInfo LV = RD->getLinkageAndVisibility();
llvm::GlobalObject::VCallVisibility TypeVis;
if (!isExternallyVisible(LV.getLinkage()))
TypeVis = llvm::GlobalObject::VCallVisibilityTranslationUnit;
else if (HasHiddenLTOVisibility(RD))
TypeVis = llvm::GlobalObject::VCallVisibilityLinkageUnit;
else
TypeVis = llvm::GlobalObject::VCallVisibilityPublic;
for (auto B : RD->bases())
if (B.getType()->getAsCXXRecordDecl()->isDynamicClass())
TypeVis = std::min(
TypeVis,
GetVCallVisibilityLevel(B.getType()->getAsCXXRecordDecl(), Visited));
for (auto B : RD->vbases())
if (B.getType()->getAsCXXRecordDecl()->isDynamicClass())
TypeVis = std::min(
TypeVis,
GetVCallVisibilityLevel(B.getType()->getAsCXXRecordDecl(), Visited));
return TypeVis;
}
void CodeGenModule::EmitVTableTypeMetadata(const CXXRecordDecl *RD,
llvm::GlobalVariable *VTable,
const VTableLayout &VTLayout) {
if (!getCodeGenOpts().LTOUnit)
return;
CharUnits PointerWidth =
Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
typedef std::pair<const CXXRecordDecl *, unsigned> AddressPoint;
std::vector<AddressPoint> AddressPoints;
for (auto &&AP : VTLayout.getAddressPoints())
AddressPoints.push_back(std::make_pair(
AP.first.getBase(), VTLayout.getVTableOffset(AP.second.VTableIndex) +
AP.second.AddressPointIndex));
llvm::sort(AddressPoints, [this](const AddressPoint &AP1,
const AddressPoint &AP2) {
if (&AP1 == &AP2)
return false;
std::string S1;
llvm::raw_string_ostream O1(S1);
getCXXABI().getMangleContext().mangleTypeName(
QualType(AP1.first->getTypeForDecl(), 0), O1);
O1.flush();
std::string S2;
llvm::raw_string_ostream O2(S2);
getCXXABI().getMangleContext().mangleTypeName(
QualType(AP2.first->getTypeForDecl(), 0), O2);
O2.flush();
if (S1 < S2)
return true;
if (S1 != S2)
return false;
return AP1.second < AP2.second;
});
ArrayRef<VTableComponent> Comps = VTLayout.vtable_components();
for (auto AP : AddressPoints) {
AddVTableTypeMetadata(VTable, PointerWidth * AP.second, AP.first);
for (unsigned I = 0; I != Comps.size(); ++I) {
if (Comps[I].getKind() != VTableComponent::CK_FunctionPointer)
continue;
llvm::Metadata *MD = CreateMetadataIdentifierForVirtualMemPtrType(
Context.getMemberPointerType(
Comps[I].getFunctionDecl()->getType(),
Context.getRecordType(AP.first).getTypePtr()));
VTable->addTypeMetadata((PointerWidth * I).getQuantity(), MD);
}
}
if (getCodeGenOpts().VirtualFunctionElimination ||
getCodeGenOpts().WholeProgramVTables) {
llvm::DenseSet<const CXXRecordDecl *> Visited;
llvm::GlobalObject::VCallVisibility TypeVis =
GetVCallVisibilityLevel(RD, Visited);
if (TypeVis != llvm::GlobalObject::VCallVisibilityPublic)
VTable->setVCallVisibilityMetadata(TypeVis);
}
}