#include "CodeGenFunction.h"
#include "CGCXXABI.h"
#include "CodeGenModule.h"
#include "clang/AST/CXXInheritance.h"
#include "clang/AST/RecordLayout.h"
#include "clang/CodeGen/CGFunctionInfo.h"
#include "clang/Frontend/CodeGenOptions.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/Support/Compiler.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(GlobalDecl GD,
const ThunkInfo &Thunk) {
const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
SmallString<256> Name;
llvm::raw_svector_ostream Out(Name);
if (const CXXDestructorDecl* DD = dyn_cast<CXXDestructorDecl>(MD))
getCXXABI().getMangleContext().mangleCXXDtorThunk(DD, GD.getDtorType(),
Thunk.This, Out);
else
getCXXABI().getMangleContext().mangleThunk(MD, Thunk, Out);
llvm::Type *Ty = getTypes().GetFunctionTypeForVTable(GD);
return GetOrCreateLLVMFunction(Name, Ty, GD, true,
true, true);
}
static void setThunkVisibility(CodeGenModule &CGM, const CXXMethodDecl *MD,
const ThunkInfo &Thunk, llvm::Function *Fn) {
CGM.setGlobalVisibility(Fn, MD);
}
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());
const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
setThunkVisibility(CGM, MD, Thunk, ThunkFn);
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, 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);
}
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()->getAs<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);
llvm::ValueToValueMapTy VMap;
llvm::Function *NewFn = llvm::CloneFunction(BaseFn, VMap,
false);
CGM.getModule().getFunctionList().push_back(NewFn);
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(&*AI, CGM.getClassPointerAlignment(MD->getParent()));
llvm::BasicBlock *EntryBB = &Fn->front();
llvm::BasicBlock::iterator ThisStore =
std::find_if(EntryBB->begin(), EntryBB->end(), [&](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);
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) {
assert(!CurGD.getDecl() && "CurGD was already set!");
CurGD = GD;
CurFuncIsThunk = true;
const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
QualType ThisType = MD->getThisType(getContext());
const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
QualType ResultType = CGM.getCXXABI().HasThisReturn(GD)
? ThisType
: CGM.getCXXABI().hasMostDerivedReturn(GD)
? CGM.getContext().VoidPtrTy
: FPT->getReturnType();
FunctionArgList FunctionArgs;
CGM.getCXXABI().buildThisParam(*this, FunctionArgs);
FunctionArgs.append(MD->param_begin(), MD->param_end());
if (isa<CXXDestructorDecl>(MD))
CGM.getCXXABI().addImplicitStructorParams(*this, ResultType, FunctionArgs);
StartFunction(GlobalDecl(), ResultType, Fn, FnInfo, FunctionArgs,
MD->getLocation(), MD->getLocation());
CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
CXXThisValue = CXXABIThisValue;
CurCodeDecl = MD;
CurFuncDecl = MD;
}
void CodeGenFunction::FinishThunk() {
CurCodeDecl = nullptr;
CurFuncDecl = nullptr;
FinishFunction();
}
void CodeGenFunction::EmitCallAndReturnForThunk(llvm::Value *Callee,
const ThunkInfo *Thunk) {
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()) {
if (Thunk && !Thunk->Return.isEmpty()) {
CGM.ErrorUnsupported(
MD, "non-trivial argument copy for return-adjusting thunk");
}
EmitMustTailThunk(MD, AdjustedThisPtr, Callee);
return;
}
CallArgList CallArgs;
QualType ThisType = MD->getThisType(getContext());
CallArgs.add(RValue::get(AdjustedThisPtr), ThisType);
if (isa<CXXDestructorDecl>(MD))
CGM.getCXXABI().adjustCallArgsForDestructorThunk(*this, CurGD, CallArgs);
for (const ParmVarDecl *PD : MD->params())
EmitDelegateCallArg(CallArgs, PD, PD->getLocStart());
const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
#ifndef NDEBUG
const CGFunctionInfo &CallFnInfo =
CGM.getTypes().arrangeCXXMethodCall(CallArgs, FPT,
RequiredArgs::forPrototypePlus(FPT, 1));
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 &&
!hasScalarEvaluationKind(CurFnInfo->getReturnType()))
Slot = ReturnValueSlot(ReturnValue, ResultType.isVolatileQualified());
llvm::Instruction *CallOrInvoke;
RValue RV = EmitCall(*CurFnInfo, Callee, Slot, CallArgs, MD, &CallOrInvoke);
if (Thunk && !Thunk->Return.isEmpty())
RV = PerformReturnAdjustment(*this, ResultType, RV, *Thunk);
if (!ResultType->isVoidType() && Slot.isNull())
CGM.getCXXABI().EmitReturnFromThunk(*this, RV, ResultType);
AutoreleaseResult = false;
FinishThunk();
}
void CodeGenFunction::EmitMustTailThunk(const CXXMethodDecl *MD,
llvm::Value *AdjustedThisPtr,
llvm::Value *Callee) {
SmallVector<llvm::Value *, 8> Args;
for (llvm::Argument &A : CurFn->args())
Args.push_back(&A);
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;
CodeGen::AttributeListType AttributeList;
CGM.ConstructAttributeList(Callee->getName(), *CurFnInfo, MD, AttributeList,
CallingConv, true);
llvm::AttributeSet Attrs =
llvm::AttributeSet::get(getLLVMContext(), AttributeList);
Call->setAttributes(Attrs);
Call->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
if (Call->getType()->isVoidTy())
Builder.CreateRetVoid();
else
Builder.CreateRet(Call);
EmitBlock(createBasicBlock());
FinishFunction();
}
void CodeGenFunction::generateThunk(llvm::Function *Fn,
const CGFunctionInfo &FnInfo,
GlobalDecl GD, const ThunkInfo &Thunk) {
StartThunk(Fn, GD, FnInfo);
llvm::Type *Ty =
CGM.getTypes().GetFunctionType(CGM.getTypes().arrangeGlobalDeclaration(GD));
llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, true);
EmitCallAndReturnForThunk(Callee, &Thunk);
}
void CodeGenVTables::emitThunk(GlobalDecl GD, const ThunkInfo &Thunk,
bool ForVTable) {
const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeGlobalDeclaration(GD);
llvm::Constant *C = CGM.GetAddrOfThunk(GD, Thunk);
llvm::GlobalValue *Entry;
if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(C)) {
assert(CE->getOpcode() == llvm::Instruction::BitCast);
Entry = cast<llvm::GlobalValue>(CE->getOperand(0));
} else {
Entry = cast<llvm::GlobalValue>(C);
}
if (Entry->getType()->getElementType() !=
CGM.getTypes().GetFunctionTypeForVTable(GD)) {
llvm::GlobalValue *OldThunkFn = Entry;
assert(OldThunkFn->isDeclaration() &&
"Shouldn't replace non-declaration");
OldThunkFn->setName(StringRef());
Entry = cast<llvm::GlobalValue>(CGM.GetAddrOfThunk(GD, Thunk));
if (!OldThunkFn->use_empty()) {
llvm::Constant *NewPtrForOldDecl =
llvm::ConstantExpr::getBitCast(Entry, OldThunkFn->getType());
OldThunkFn->replaceAllUsesWith(NewPtrForOldDecl);
}
OldThunkFn->eraseFromParent();
}
llvm::Function *ThunkFn = cast<llvm::Function>(Entry);
bool ABIHasKeyFunctions = CGM.getTarget().getCXXABI().hasKeyFunctions();
bool UseAvailableExternallyLinkage = ForVTable && ABIHasKeyFunctions;
if (!ThunkFn->isDeclaration()) {
if (!ABIHasKeyFunctions || UseAvailableExternallyLinkage) {
return;
}
setThunkProperties(CGM, Thunk, ThunkFn, ForVTable, GD);
return;
}
CGM.SetLLVMFunctionAttributesForDefinition(GD.getDecl(), ThunkFn);
if (ThunkFn->isVarArg()) {
if (UseAvailableExternallyLinkage)
return;
ThunkFn =
CodeGenFunction(CGM).GenerateVarArgsThunk(ThunkFn, FnInfo, GD, Thunk);
} else {
CodeGenFunction(CGM).generateThunk(ThunkFn, FnInfo, GD, Thunk);
}
setThunkProperties(CGM, Thunk, ThunkFn, ForVTable, GD);
}
void CodeGenVTables::maybeEmitThunkForVTable(GlobalDecl GD,
const ThunkInfo &Thunk) {
if (CGM.getTarget().getCXXABI().hasKeyFunctions() &&
!CGM.getCodeGenOpts().OptimizationLevel)
return;
const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
if (!CGM.getTypes().isFuncTypeConvertible(
MD->getType()->castAs<FunctionType>()))
return;
emitThunk(GD, Thunk, true);
}
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)
emitThunk(GD, Thunk, false);
}
llvm::Constant *CodeGenVTables::CreateVTableInitializer(
const CXXRecordDecl *RD, const VTableComponent *Components,
unsigned NumComponents, const VTableLayout::VTableThunkTy *VTableThunks,
unsigned NumVTableThunks, llvm::Constant *RTTI) {
SmallVector<llvm::Constant *, 64> Inits;
llvm::Type *Int8PtrTy = CGM.Int8PtrTy;
llvm::Type *PtrDiffTy =
CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
unsigned NextVTableThunkIndex = 0;
llvm::Constant *PureVirtualFn = nullptr, *DeletedVirtualFn = nullptr;
for (unsigned I = 0; I != NumComponents; ++I) {
VTableComponent Component = Components[I];
llvm::Constant *Init = nullptr;
switch (Component.getKind()) {
case VTableComponent::CK_VCallOffset:
Init = llvm::ConstantInt::get(PtrDiffTy,
Component.getVCallOffset().getQuantity());
Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
break;
case VTableComponent::CK_VBaseOffset:
Init = llvm::ConstantInt::get(PtrDiffTy,
Component.getVBaseOffset().getQuantity());
Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
break;
case VTableComponent::CK_OffsetToTop:
Init = llvm::ConstantInt::get(PtrDiffTy,
Component.getOffsetToTop().getQuantity());
Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
break;
case VTableComponent::CK_RTTI:
Init = llvm::ConstantExpr::getBitCast(RTTI, Int8PtrTy);
break;
case VTableComponent::CK_FunctionPointer:
case VTableComponent::CK_CompleteDtorPointer:
case VTableComponent::CK_DeletingDtorPointer: {
GlobalDecl GD;
switch (Component.getKind()) {
default:
llvm_unreachable("Unexpected vtable component kind");
case VTableComponent::CK_FunctionPointer:
GD = Component.getFunctionDecl();
break;
case VTableComponent::CK_CompleteDtorPointer:
GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Complete);
break;
case VTableComponent::CK_DeletingDtorPointer:
GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Deleting);
break;
}
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) {
Init = llvm::ConstantExpr::getNullValue(Int8PtrTy);
break;
}
}
if (cast<CXXMethodDecl>(GD.getDecl())->isPure()) {
if (!PureVirtualFn) {
llvm::FunctionType *Ty =
llvm::FunctionType::get(CGM.VoidTy, false);
StringRef PureCallName = CGM.getCXXABI().GetPureVirtualCallName();
PureVirtualFn = CGM.CreateRuntimeFunction(Ty, PureCallName);
PureVirtualFn = llvm::ConstantExpr::getBitCast(PureVirtualFn,
CGM.Int8PtrTy);
}
Init = PureVirtualFn;
} else if (cast<CXXMethodDecl>(GD.getDecl())->isDeleted()) {
if (!DeletedVirtualFn) {
llvm::FunctionType *Ty =
llvm::FunctionType::get(CGM.VoidTy, false);
StringRef DeletedCallName =
CGM.getCXXABI().GetDeletedVirtualCallName();
DeletedVirtualFn = CGM.CreateRuntimeFunction(Ty, DeletedCallName);
DeletedVirtualFn = llvm::ConstantExpr::getBitCast(DeletedVirtualFn,
CGM.Int8PtrTy);
}
Init = DeletedVirtualFn;
} else {
if (NextVTableThunkIndex < NumVTableThunks &&
VTableThunks[NextVTableThunkIndex].first == I) {
const ThunkInfo &Thunk = VTableThunks[NextVTableThunkIndex].second;
maybeEmitThunkForVTable(GD, Thunk);
Init = CGM.GetAddrOfThunk(GD, Thunk);
NextVTableThunkIndex++;
} else {
llvm::Type *Ty = CGM.getTypes().GetFunctionTypeForVTable(GD);
Init = CGM.GetAddrOfFunction(GD, Ty, true);
}
Init = llvm::ConstantExpr::getBitCast(Init, Int8PtrTy);
}
break;
}
case VTableComponent::CK_UnusedFunctionPointer:
Init = llvm::ConstantExpr::getNullValue(Int8PtrTy);
break;
};
Inits.push_back(Init);
}
llvm::ArrayType *ArrayType = llvm::ArrayType::get(Int8PtrTy, NumComponents);
return llvm::ConstantArray::get(ArrayType, Inits);
}
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);
StringRef Name = OutName.str();
llvm::ArrayType *ArrayType =
llvm::ArrayType::get(CGM.Int8PtrTy, VTLayout->getNumVTableComponents());
if (Linkage == llvm::GlobalVariable::AvailableExternallyLinkage)
Linkage = llvm::GlobalVariable::InternalLinkage;
llvm::GlobalVariable *VTable =
CGM.CreateOrReplaceCXXRuntimeVariable(Name, ArrayType, Linkage);
CGM.setGlobalVisibility(VTable, RD);
VTable->setUnnamedAddr(true);
llvm::Constant *RTTI = CGM.GetAddrOfRTTIDescriptor(
CGM.getContext().getTagDeclType(Base.getBase()));
llvm::Constant *Init = CreateVTableInitializer(
Base.getBase(), VTLayout->vtable_component_begin(),
VTLayout->getNumVTableComponents(), VTLayout->vtable_thunk_begin(),
VTLayout->getNumVTableThunks(), RTTI);
VTable->setInitializer(Init);
CGM.EmitVTableBitSetEntries(VTable, *VTLayout.get());
return 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) &&
"Shouldn't query vtable linkage without key function or "
"optimizations");
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:
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.");
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);
assert(savedSize == DeferredVTables.size() &&
"deferred extra vtables during vtable emission?");
DeferredVTables.clear();
}
bool CodeGenModule::IsCFIBlacklistedRecord(const CXXRecordDecl *RD) {
if (RD->hasAttr<UuidAttr>() &&
getContext().getSanitizerBlacklist().isBlacklistedType("attr:uuid"))
return true;
return getContext().getSanitizerBlacklist().isBlacklistedType(
RD->getQualifiedNameAsString());
}
void CodeGenModule::EmitVTableBitSetEntries(llvm::GlobalVariable *VTable,
const VTableLayout &VTLayout) {
if (!LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
!LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
!LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
!LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast))
return;
CharUnits PointerWidth =
Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
typedef std::pair<const CXXRecordDecl *, unsigned> BSEntry;
std::vector<BSEntry> BitsetEntries;
for (auto &&AP : VTLayout.getAddressPoints()) {
if (IsCFIBlacklistedRecord(AP.first.getBase()))
continue;
BitsetEntries.push_back(std::make_pair(AP.first.getBase(), AP.second));
}
std::sort(BitsetEntries.begin(), BitsetEntries.end(),
[this](const BSEntry &E1, const BSEntry &E2) {
if (&E1 == &E2)
return false;
std::string S1;
llvm::raw_string_ostream O1(S1);
getCXXABI().getMangleContext().mangleTypeName(
QualType(E1.first->getTypeForDecl(), 0), O1);
O1.flush();
std::string S2;
llvm::raw_string_ostream O2(S2);
getCXXABI().getMangleContext().mangleTypeName(
QualType(E2.first->getTypeForDecl(), 0), O2);
O2.flush();
if (S1 < S2)
return true;
if (S1 != S2)
return false;
return E1.second < E2.second;
});
llvm::NamedMDNode *BitsetsMD =
getModule().getOrInsertNamedMetadata("llvm.bitsets");
for (auto BitsetEntry : BitsetEntries)
CreateVTableBitSetEntry(BitsetsMD, VTable,
PointerWidth * BitsetEntry.second,
BitsetEntry.first);
}