23#include "llvm/IR/IRBuilder.h"
24#include "llvm/Transforms/Utils/Cloning.h"
33 : CGM(CGM), VTContext(CGM.getContext().getVTableContext()) {}
37 return GetOrCreateLLVMFunction(Name, FnTy, GD,
true,
42 llvm::GlobalVariable *VTable =
43 CGM.getCXXABI().getAddrOfVTable(RD,
CharUnits());
48 llvm::Function *ThunkFn,
bool ForVTable,
58 ThunkFn->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
59 ThunkFn->setDSOLocal(
true);
63 ThunkFn->setComdat(CGM.
getModule().getOrInsertComdat(ThunkFn->getName()));
82 llvm::BasicBlock *AdjustNull =
nullptr;
83 llvm::BasicBlock *AdjustNotNull =
nullptr;
84 llvm::BasicBlock *AdjustEnd =
nullptr;
106 if (NullCheckValue) {
107 CGF.
Builder.CreateBr(AdjustEnd);
109 CGF.
Builder.CreateBr(AdjustEnd);
112 llvm::PHINode *PHI = CGF.
Builder.CreatePHI(ReturnValue->getType(), 2);
113 PHI->addIncoming(ReturnValue, AdjustNotNull);
114 PHI->addIncoming(llvm::Constant::getNullValue(ReturnValue->getType()),
128 llvm::ValueToValueMapTy &VMap) {
130 auto *DIS = Fn->getSubprogram();
133 auto *NewDIS = llvm::MDNode::replaceWithDistinct(DIS->clone());
138 NewDIS->replaceRetainedNodes(llvm::MDTuple::get(Fn->getContext(), {}));
139 VMap.MD()[DIS].reset(NewDIS);
151 auto PrepareVariableMapping = [&VMap](llvm::DILocalVariable *DILocal) {
152 if (DILocal->isResolved())
155 if (llvm::DIType *Ty = DILocal->getType(); Ty && !Ty->isResolved())
156 VMap.MD()[Ty].reset(Ty);
161 for (
auto &BB : *Fn) {
163 for (llvm::DbgVariableRecord &DVR :
164 llvm::filterDbgVars(I.getDbgRecordRange()))
165 PrepareVariableMapping(DVR.getVariable());
196 llvm::Type *Ty =
CGM.getTypes().GetFunctionType(FnInfo);
197 llvm::Value *Callee =
CGM.GetAddrOfFunction(GD, Ty,
true);
204 CGM.ErrorUnsupported(MD,
"return-adjusting thunk with variadic arguments");
207 assert(!BaseFn->isDeclaration() &&
"cannot clone undefined variadic method");
210 llvm::ValueToValueMapTy VMap;
215 llvm::Function *NewFn = llvm::CloneFunction(BaseFn, VMap);
220 llvm::AttributeList ThunkAttrs = Fn->getAttributes();
222 for (
unsigned I = 0, N = NewFn->arg_size(); I != N; ++I)
223 ParamAttrs.push_back(ThunkAttrs.getParamAttrs(I));
224 NewFn->setAttributes(llvm::AttributeList::get(
226 ThunkAttrs.getRetAttrs(), ParamAttrs));
228 Fn->replaceAllUsesWith(NewFn);
230 Fn->eraseFromParent();
237 llvm::Function::arg_iterator AI = Fn->arg_begin();
238 if (
CGM.ReturnTypeUsesSRet(FnInfo))
248 CGM.getClassPointerAlignment(ThisValueClass));
249 llvm::BasicBlock *EntryBB = &Fn->front();
250 llvm::BasicBlock::iterator ThisStore =
251 llvm::find_if(*EntryBB, [&](llvm::Instruction &I) {
254 assert(ThisStore != EntryBB->end() &&
255 "Store of this should be in entry block?");
257 Builder.SetInsertPoint(&*ThisStore);
259 llvm::Value *AdjustedThisPtr =
CGM.getCXXABI().performThisAdjustment(
260 *
this, ThisPtr, ThisValueClass, Thunk);
261 AdjustedThisPtr =
Builder.CreateBitCast(AdjustedThisPtr,
262 ThisStore->getOperand(0)->getType());
263 ThisStore->setOperand(0, AdjustedThisPtr);
267 for (llvm::BasicBlock &BB : *Fn) {
268 llvm::Instruction *
T = BB.getTerminator();
271 T->eraseFromParent();
285 bool IsUnprototyped) {
286 assert(!
CurGD.getDecl() &&
"CurGD was already set!");
295 ResultType =
CGM.getContext().VoidTy;
296 else if (
CGM.getCXXABI().HasThisReturn(GD))
297 ResultType = ThisType;
298 else if (
CGM.getCXXABI().hasMostDerivedReturn(GD))
299 ResultType =
CGM.getContext().VoidPtrTy;
305 CGM.getCXXABI().buildThisParam(*
this, FunctionArgs);
308 if (!IsUnprototyped) {
312 CGM.getCXXABI().addImplicitStructorParams(*
this, ResultType,
324 CGM.getCXXABI().EmitInstanceFunctionProlog(*
this);
325 CXXThisValue = CXXABIThisValue;
341 bool IsUnprototyped) {
343 "Please use a new CGF for this thunk");
347 llvm::Value *AdjustedThisPtr;
353 CGM.getClassPointerAlignment(ThisValueClass),
false,
355 AdjustedThisPtr =
CGM.getCXXABI().performThisAdjustment(
356 *
this, ThisPtr, ThisValueClass, *Thunk);
367 CGM.ErrorUnsupported(
368 MD,
"return-adjusting thunk with incomplete parameter type");
370 llvm_unreachable(
"shouldn't try to emit musttail return-adjusting "
371 "thunks for variadic functions");
373 CGM.ErrorUnsupported(
374 MD,
"non-trivial argument copy for return-adjusting thunk");
386 CGM.getCXXABI().adjustCallArgsForDestructorThunk(*
this,
CurGD, CallArgs);
389 unsigned PrefixArgs = CallArgs.size() - 1;
400 assert(CallFnInfo.getRegParm() ==
CurFnInfo->getRegParm() &&
401 CallFnInfo.isNoReturn() ==
CurFnInfo->isNoReturn() &&
402 CallFnInfo.getCallingConvention() ==
404 CallFnInfo.getX86ABIAVXLevel() ==
CurFnInfo->getX86ABIAVXLevel());
406 similar(CallFnInfo.getReturnInfo(), CallFnInfo.getReturnType(),
408 assert(CallFnInfo.arg_size() ==
CurFnInfo->arg_size());
409 for (
unsigned i = 0, e =
CurFnInfo->arg_size(); i != e; ++i)
410 assert(
similar(CallFnInfo.arg_begin()[i].info,
411 CallFnInfo.arg_begin()[i].type,
419 :
CGM.getCXXABI().hasMostDerivedReturn(
CurGD)
420 ?
CGM.getContext().VoidPtrTy
430 llvm::CallBase *CallOrInvoke;
432 CallArgs, &CallOrInvoke);
437 else if (llvm::CallInst*
Call = dyn_cast<llvm::CallInst>(CallOrInvoke))
438 Call->setTailCallKind(llvm::CallInst::TCK_Tail);
442 CGM.getCXXABI().EmitReturnFromThunk(*
this, RV, ResultType);
451 llvm::Value *AdjustedThisPtr,
452 llvm::FunctionCallee Callee) {
464 llvm::Type *ThisType = Args[ThisArgNo]->getType();
465 if (ThisType != AdjustedThisPtr->getType())
466 AdjustedThisPtr =
Builder.CreateBitCast(AdjustedThisPtr, ThisType);
467 Args[ThisArgNo] = AdjustedThisPtr;
469 assert(ThisAI.
isInAlloca() &&
"this is passed directly or inalloca");
472 if (ThisType != AdjustedThisPtr->getType())
473 AdjustedThisPtr =
Builder.CreateBitCast(AdjustedThisPtr, ThisType);
474 Builder.CreateStore(AdjustedThisPtr, ThisAddr);
479 llvm::CallInst *
Call =
Builder.CreateCall(Callee, Args);
480 Call->setTailCallKind(llvm::CallInst::TCK_MustTail);
484 llvm::AttributeList Attrs;
485 CGM.ConstructAttributeList(Callee.getCallee()->getName(), *
CurFnInfo, GD,
488 Call->setAttributes(Attrs);
491 if (
Call->getType()->isVoidTy())
506 bool IsUnprototyped) {
517 Ty =
CGM.getTypes().GetFunctionType(FnInfo);
519 llvm::Constant *Callee =
CGM.GetAddrOfFunction(GD, Ty,
true);
523 &Thunk, IsUnprototyped);
527 bool IsUnprototyped,
bool ForVTable) {
544llvm::Constant *CodeGenVTables::maybeEmitThunk(GlobalDecl GD,
552 SmallString<256> Name;
553 MangleContext &MCtx = CGM.getCXXABI().getMangleContext();
554 llvm::raw_svector_ostream
Out(Name);
556 if (
const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
562 if (CGM.getContext().useAbbreviatedThunkName(GD, Name.str())) {
564 if (
const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD))
571 llvm::Type *ThunkVTableTy = CGM.getTypes().GetFunctionTypeForVTable(GD);
572 llvm::Constant *Thunk = CGM.GetAddrOfThunk(Name, ThunkVTableTy, GD);
575 bool IsUnprototyped = !CGM.getTypes().isFuncTypeConvertible(
582 const CGFunctionInfo &FnInfo =
583 IsUnprototyped ? CGM.getTypes().arrangeUnprototypedMustTailThunk(MD)
584 : CGM.getTypes().arrangeGlobalDeclaration(GD);
585 llvm::FunctionType *ThunkFnTy = CGM.getTypes().GetFunctionType(FnInfo);
590 if (ThunkFn->getFunctionType() != ThunkFnTy) {
591 llvm::GlobalValue *OldThunkFn = ThunkFn;
593 assert(OldThunkFn->isDeclaration() &&
"Shouldn't replace non-declaration");
596 OldThunkFn->setName(StringRef());
597 ThunkFn = llvm::Function::Create(ThunkFnTy, llvm::Function::ExternalLinkage,
598 Name.str(), &CGM.getModule());
599 CGM.SetLLVMFunctionAttributes(MD, FnInfo, ThunkFn,
true);
601 if (!OldThunkFn->use_empty()) {
602 OldThunkFn->replaceAllUsesWith(ThunkFn);
606 OldThunkFn->eraseFromParent();
609 bool ABIHasKeyFunctions = CGM.getTarget().getCXXABI().hasKeyFunctions();
610 bool UseAvailableExternallyLinkage = ForVTable && ABIHasKeyFunctions;
612 if (!ThunkFn->isDeclaration()) {
613 if (!ABIHasKeyFunctions || UseAvailableExternallyLinkage) {
627 ThunkFn->addFnAttr(
"thunk");
629 CGM.SetLLVMFunctionAttributesForDefinition(GD.
getDecl(), ThunkFn);
636 bool ShouldCloneVarArgs =
false;
637 if (!IsUnprototyped && ThunkFn->isVarArg()) {
638 ShouldCloneVarArgs =
true;
640 switch (CGM.getTriple().getArch()) {
641 case llvm::Triple::x86_64:
642 case llvm::Triple::x86:
643 case llvm::Triple::aarch64:
644 ShouldCloneVarArgs =
false;
652 if (ShouldCloneVarArgs) {
653 if (UseAvailableExternallyLinkage)
656 CodeGenFunction(CGM).GenerateVarArgsThunk(ThunkFn, FnInfo, GD, TI);
659 CodeGenFunction(CGM).generateThunk(ThunkFn, FnInfo, GD, TI, IsUnprototyped);
675 VTContext->getThunkInfo(GD);
677 if (!ThunkInfoVector)
680 for (
const ThunkInfo& Thunk : *ThunkInfoVector)
681 maybeEmitThunk(GD, Thunk,
false);
685 llvm::Constant *component,
686 unsigned vtableAddressPoint,
687 bool vtableHasLocalLinkage,
688 bool isCompleteDtor)
const {
690 if (component->isNullValue())
691 return builder.
add(llvm::ConstantInt::get(CGM.
Int32Ty, 0));
708 auto stubLinkage = vtableHasLocalLinkage
709 ? llvm::GlobalValue::InternalLinkage
710 : llvm::GlobalValue::LinkOnceODRLinkage;
712 llvm::Constant *target;
713 if (
auto *func = dyn_cast<llvm::Function>(globalVal)) {
714 target = llvm::DSOLocalEquivalent::get(func);
717 rttiProxyName.append(
".rtti_proxy");
723 llvm::GlobalVariable *proxy =
module.getNamedGlobal(rttiProxyName);
725 proxy =
new llvm::GlobalVariable(module, globalVal->getType(),
727 globalVal, rttiProxyName);
728 proxy->setDSOLocal(
true);
729 proxy->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
730 if (!proxy->hasLocalLinkage()) {
731 proxy->setVisibility(llvm::GlobalValue::HiddenVisibility);
732 proxy->setComdat(module.getOrInsertComdat(rttiProxyName));
755 return CGM.getVTableComponentType();
761 builder.
add(llvm::ConstantExpr::getIntToPtr(
773 const VTableLayout &layout,
774 unsigned componentIndex,
775 llvm::Constant *rtti,
776 unsigned &nextVTableThunkIndex,
777 unsigned vtableAddressPoint,
778 bool vtableHasLocalLinkage) {
781 bool RelativeCXXABIVTables = CGM.getLangOpts().RelativeCXXABIVTables;
782 auto addOffsetConstant =
785 switch (component.getKind()) {
787 return addOffsetConstant(CGM, builder, component.getVCallOffset());
790 return addOffsetConstant(CGM, builder, component.getVBaseOffset());
793 return addOffsetConstant(CGM, builder, component.getOffsetToTop());
796 if (RelativeCXXABIVTables)
797 return addRelativeComponent(builder, rtti, vtableAddressPoint,
798 vtableHasLocalLinkage,
801 return builder.
add(rtti);
806 GlobalDecl GD = component.getGlobalDecl(
807 CGM.getContext().getTargetInfo().emitVectorDeletingDtors(
808 CGM.getContext().getLangOpts()));
812 layout.
vtable_thunks()[nextVTableThunkIndex].first == componentIndex;
814 if (CGM.getLangOpts().CUDA) {
822 CGM.getLangOpts().CUDAIsDevice
823 ? MD->
hasAttr<CUDADeviceAttr>()
824 : (MD->
hasAttr<CUDAHostAttr>() || !MD->
hasAttr<CUDADeviceAttr>());
825 if (!CanEmitMethod) {
827 nextVTableThunkIndex++;
829 llvm::ConstantExpr::getNullValue(CGM.GlobalsInt8PtrTy));
834 auto getSpecialVirtualFn = [&](StringRef
name) -> llvm::Constant * {
835 llvm::FunctionType *fnTy =
836 llvm::FunctionType::get(CGM.VoidTy,
false);
838 CGM.CreateRuntimeFunction(fnTy, name).getCallee());
839 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
848 if (CGM.getLangOpts().isTargetDevice()) {
849 F->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
850 CodeGenFunction CGF(CGM);
851 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
852 CGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, F, FI,
854 CGF.EmitTrapCallAndMakeUnreachable();
855 CGF.FinishFunction();
861 llvm::Constant *fnPtr;
867 getSpecialVirtualFn(CGM.getCXXABI().GetPureVirtualCallName());
868 fnPtr = PureVirtualFn;
872 if (!DeletedVirtualFn)
874 getSpecialVirtualFn(CGM.getCXXABI().GetDeletedVirtualCallName());
875 fnPtr = DeletedVirtualFn;
878 }
else if (IsThunk) {
879 auto &thunkInfo = layout.
vtable_thunks()[nextVTableThunkIndex].second;
881 nextVTableThunkIndex++;
882 fnPtr = maybeEmitThunk(GD, thunkInfo,
true);
883 if (CGM.getCodeGenOpts().PointerAuth.CXXVirtualFunctionPointers) {
884 assert(thunkInfo.Method &&
"Method not set");
890 llvm::Type *fnTy = CGM.getTypes().GetFunctionTypeForVTable(GD);
891 fnPtr = CGM.GetAddrOfFunction(GD, fnTy,
true);
892 if (CGM.getCodeGenOpts().PointerAuth.CXXVirtualFunctionPointers)
896 if (RelativeCXXABIVTables) {
897 return addRelativeComponent(
898 builder, fnPtr, vtableAddressPoint, vtableHasLocalLinkage,
905 unsigned FnAS = fnPtr->getType()->getPointerAddressSpace();
906 unsigned GVAS = CGM.GlobalsInt8PtrTy->getPointerAddressSpace();
910 llvm::ConstantExpr::getAddrSpaceCast(fnPtr, CGM.GlobalsInt8PtrTy);
911 if (
const auto &Schema =
912 CGM.getCodeGenOpts().PointerAuth.CXXVirtualFunctionPointers)
914 return builder.
add(fnPtr);
919 if (RelativeCXXABIVTables)
920 return builder.
add(llvm::ConstantExpr::getNullValue(CGM.Int32Ty));
925 llvm_unreachable(
"Unexpected vtable component kind");
931 for (
unsigned i = 0, e = layout.
getNumVTables(); i != e; ++i)
932 tys.push_back(llvm::ArrayType::get(componentType, layout.
getVTableSize(i)));
934 return llvm::StructType::get(CGM.getLLVMContext(), tys);
939 llvm::Constant *rtti,
940 bool vtableHasLocalLinkage) {
944 unsigned nextVTableThunkIndex = 0;
945 for (
unsigned vtableIndex = 0, endIndex = layout.
getNumVTables();
946 vtableIndex != endIndex; ++vtableIndex) {
947 auto vtableElem = builder.
beginArray(componentType);
950 size_t vtableEnd = vtableStart + layout.
getVTableSize(vtableIndex);
951 for (
size_t componentIndex = vtableStart; componentIndex < vtableEnd;
953 addVTableComponent(vtableElem, layout, componentIndex, rtti,
954 nextVTableThunkIndex, addressPoints[vtableIndex],
955 vtableHasLocalLinkage);
957 vtableElem.finishAndAddTo(builder);
963 llvm::GlobalVariable::LinkageTypes
Linkage,
964 VTableAddressPointsMapTy &AddressPoints) {
966 DI->completeClassData(
Base.getBase());
968 std::unique_ptr<VTableLayout> VTLayout(
970 Base.getBase(),
Base.getBaseOffset(), BaseIsVirtual, RD));
973 AddressPoints = VTLayout->getAddressPoints();
977 llvm::raw_svector_ostream Out(OutName);
979 .mangleCXXCtorVTable(RD,
Base.getBaseOffset().getQuantity(),
980 Base.getBase(), Out);
983 bool UsingRelativeLayout = CGM.getLangOpts().RelativeCXXABIVTables;
984 bool VTableAliasExists =
985 UsingRelativeLayout && CGM.getModule().getNamedAlias(Name);
986 if (VTableAliasExists) {
988 Name.append(
".local");
998 if (
Linkage == llvm::GlobalVariable::AvailableExternallyLinkage)
999 Linkage = llvm::GlobalVariable::InternalLinkage;
1001 llvm::Align Align = CGM.getDataLayout().getABITypeAlign(VTType);
1004 llvm::GlobalVariable *VTable =
1005 CGM.CreateOrReplaceCXXRuntimeVariable(Name, VTType,
Linkage, Align);
1012 if (!CGM.shouldEmitRTTI() || CGM.mayVTableBeDuplicated(VTable->getLinkage()))
1013 VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1015 llvm::Constant *RTTI = CGM.GetAddrOfRTTIDescriptor(
1016 CGM.getContext().getCanonicalTagType(
Base.getBase()));
1022 VTable->hasLocalLinkage());
1023 components.finishAndSetAsInitializer(VTable);
1027 assert(!VTable->isDeclaration() &&
"Shouldn't set properties on declaration");
1028 CGM.setGVProperties(VTable, RD);
1030 CGM.EmitVTableTypeMetadata(RD, VTable, *VTLayout);
1032 if (UsingRelativeLayout) {
1034 if (!VTable->isDSOLocal())
1050 if (CGM.getLangOpts().Sanitize.has(SanitizerKind::HWAddress)) {
1051 llvm::GlobalValue::SanitizerMetadata Meta;
1052 if (GV->hasSanitizerMetadata())
1053 Meta = GV->getSanitizerMetadata();
1054 Meta.NoHWAddress =
true;
1055 GV->setSanitizerMetadata(Meta);
1066 llvm::StringRef AliasNameRef) {
1067 assert(CGM.getLangOpts().RelativeCXXABIVTables &&
1068 "Can only use this if the relative vtable ABI is used");
1069 assert(!VTable->isDSOLocal() &&
"This should be called only if the vtable is "
1070 "not guaranteed to be dso_local");
1075 if (VTable->hasAvailableExternallyLinkage())
1082 VTable->setName(AliasName +
".local");
1084 auto Linkage = VTable->getLinkage();
1085 assert(llvm::GlobalAlias::isValidLinkage(
Linkage) &&
1086 "Invalid vtable alias linkage");
1088 llvm::GlobalAlias *VTableAlias = CGM.getModule().getNamedAlias(AliasName);
1090 VTableAlias = llvm::GlobalAlias::create(VTable->getValueType(),
1091 VTable->getAddressSpace(),
Linkage,
1092 AliasName, &CGM.getModule());
1094 assert(VTableAlias->getValueType() == VTable->getValueType());
1095 assert(VTableAlias->getLinkage() ==
Linkage);
1097 VTableAlias->setVisibility(VTable->getVisibility());
1098 VTableAlias->setUnnamedAddr(VTable->getUnnamedAddr());
1101 if (!VTable->hasComdat()) {
1102 VTable->setLinkage(llvm::GlobalValue::InternalLinkage);
1112 VTable->setVisibility(llvm::GlobalValue::HiddenVisibility);
1115 VTableAlias->setAliasee(VTable);
1127llvm::GlobalVariable::LinkageTypes
1130 return llvm::GlobalVariable::InternalLinkage;
1139 IsInNamedModule ?
nullptr : Context.getCurrentKeyFunction(RD);
1140 if (IsInNamedModule || (keyFunction && !RD->
hasAttr<DLLImportAttr>())) {
1144 if (keyFunction && keyFunction->
hasBody(def))
1147 bool IsExternalDefinition =
1161 (IsInNamedModule || def || CodeGenOpts.OptimizationLevel > 0 ||
1162 CodeGenOpts.getDebugInfo() != llvm::codegenoptions::NoDebugInfo ||
1164 "Shouldn't query vtable linkage without the class in module units, "
1165 "key function, optimizations, or debug info");
1166 if (IsExternalDefinition && CodeGenOpts.OptimizationLevel > 0)
1167 return llvm::GlobalVariable::AvailableExternallyLinkage;
1169 if (keyFunction && keyFunction->
isInlined())
1170 return !Context.getLangOpts().AppleKext
1171 ? llvm::GlobalVariable::LinkOnceODRLinkage
1172 : llvm::Function::InternalLinkage;
1174 return llvm::GlobalVariable::ExternalLinkage;
1177 return !Context.getLangOpts().AppleKext ?
1178 llvm::GlobalVariable::LinkOnceODRLinkage :
1179 llvm::Function::InternalLinkage;
1182 return !Context.getLangOpts().AppleKext ?
1183 llvm::GlobalVariable::WeakODRLinkage :
1184 llvm::Function::InternalLinkage;
1187 return IsExternalDefinition
1188 ? llvm::GlobalVariable::AvailableExternallyLinkage
1189 : llvm::GlobalVariable::ExternalLinkage;
1195 if (Context.getLangOpts().AppleKext)
1196 return llvm::Function::InternalLinkage;
1198 llvm::GlobalVariable::LinkageTypes DiscardableODRLinkage =
1199 llvm::GlobalValue::LinkOnceODRLinkage;
1200 llvm::GlobalVariable::LinkageTypes NonDiscardableODRLinkage =
1201 llvm::GlobalValue::WeakODRLinkage;
1202 if (RD->
hasAttr<DLLExportAttr>()) {
1204 DiscardableODRLinkage = NonDiscardableODRLinkage;
1205 }
else if (RD->
hasAttr<DLLImportAttr>()) {
1207 DiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
1208 NonDiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
1215 return DiscardableODRLinkage;
1221 return DiscardableODRLinkage;
1223 ? llvm::GlobalVariable::AvailableExternallyLinkage
1224 : llvm::GlobalVariable::ExternalLinkage;
1227 return NonDiscardableODRLinkage;
1230 llvm_unreachable(
"Invalid TemplateSpecializationKind!");
1234 llvm::GlobalValue::LinkageTypes
Linkage)
const {
1237 llvm::GlobalValue::isWeakForLinker(
Linkage);
1247 VTables.GenerateClassData(theClass);
1248 EmittedVTables.insert(theClass);
1254 DI->completeClassData(RD);
1257 CGM.getCXXABI().emitVirtualInheritanceTables(RD);
1259 CGM.getCXXABI().emitVTableDefinitions(*
this, RD);
1273 assert(RD->
isDynamicClass() &&
"Non-dynamic classes have no VTable.");
1277 if (CGM.getTarget().getCXXABI().isMicrosoft())
1299 const CXXMethodDecl *keyFunction = CGM.getContext().getCurrentKeyFunction(RD);
1305 return !keyFunction->
hasBody();
1324void CodeGenModule::EmitDeferredVTables() {
1328 size_t savedSize = DeferredVTables.size();
1331 for (
const CXXRecordDecl *RD : DeferredVTables) {
1334 if (EmittedVTables.count(RD) &&
1339 VTables.GenerateClassData(RD);
1340 else if (shouldOpportunisticallyEmitVTables())
1341 OpportunisticVTables.push_back(RD);
1344 assert(savedSize == DeferredVTables.size() &&
1345 "deferred extra vtables during vtable emission?");
1346 DeferredVTables.clear();
1350 if (RD->
hasAttr<LTOVisibilityPublicAttr>() || RD->
hasAttr<UuidAttr>() ||
1362 if (
auto *ND = dyn_cast<NamespaceDecl>(D))
1364 if (II->isStr(
"std") || II->isStr(
"stdext"))
1386 const CXXRecordDecl *RD, llvm::DenseSet<const CXXRecordDecl *> &Visited) {
1392 if (!Visited.insert(RD).second)
1393 return llvm::GlobalObject::VCallVisibilityTranslationUnit;
1396 llvm::GlobalObject::VCallVisibility TypeVis;
1398 TypeVis = llvm::GlobalObject::VCallVisibilityTranslationUnit;
1400 TypeVis = llvm::GlobalObject::VCallVisibilityLinkageUnit;
1402 TypeVis = llvm::GlobalObject::VCallVisibilityPublic;
1404 for (
const auto &B : RD->
bases())
1405 if (B.getType()->getAsCXXRecordDecl()->isDynamicClass())
1410 for (
const auto &B : RD->
vbases())
1411 if (B.getType()->getAsCXXRecordDecl()->isDynamicClass())
1420 llvm::GlobalVariable *VTable,
1432 struct AddressPoint {
1436 bool operator<(
const AddressPoint &RHS)
const {
1437 int D =
TypeName.compare(RHS.TypeName);
1438 return D < 0 || (D == 0 && Offset < RHS.Offset);
1441 std::vector<AddressPoint> AddressPoints;
1443 AddressPoint N{AP.first.getBase(),
1445 AP.second.AddressPointIndex,
1447 llvm::raw_string_ostream Stream(N.TypeName);
1450 AddressPoints.push_back(std::move(N));
1454 llvm::sort(AddressPoints);
1457 for (
auto AP : AddressPoints) {
1465 for (
unsigned I = 0; I != Comps.size(); ++I) {
1469 Context.getMemberPointerType(Comps[I].getFunctionDecl()->getType(),
1470 std::nullopt, AP.Base));
1471 VTable->addTypeMetadata((ComponentWidth * I).getQuantity(), MD);
1477 llvm::DenseSet<const CXXRecordDecl *> Visited;
1478 llvm::GlobalObject::VCallVisibility TypeVis =
1480 if (TypeVis != llvm::GlobalObject::VCallVisibilityPublic)
1481 VTable->setVCallVisibilityMetadata(TypeVis);
static RValue PerformReturnAdjustment(CodeGenFunction &CGF, QualType ResultType, RValue RV, const ThunkInfo &Thunk)
static void resolveTopLevelMetadata(llvm::Function *Fn, llvm::ValueToValueMapTy &VMap)
This function clones a function's DISubprogram node and enters it into a value map with the intent th...
static void AddRelativeLayoutOffset(const CodeGenModule &CGM, ConstantArrayBuilder &builder, CharUnits offset)
static void AddPointerLayoutOffset(const CodeGenModule &CGM, ConstantArrayBuilder &builder, CharUnits offset)
static bool similar(const ABIArgInfo &infoL, CanQualType typeL, const ABIArgInfo &infoR, CanQualType typeR)
static bool shouldEmitAvailableExternallyVTable(const CIRGenModule &cgm, const CXXRecordDecl *rd)
static bool shouldEmitVTableAtEndOfTranslationUnit(CIRGenModule &cgm, const CXXRecordDecl *rd)
Given that we're currently at the end of the translation unit, and we've emitted a reference to the v...
static void setThunkProperties(CIRGenModule &cgm, const ThunkInfo &thunk, cir::FuncOp thunkFn, bool forVTable, GlobalDecl gd)
static bool shouldEmitVTableThunk(CIRGenModule &cgm, const CXXMethodDecl *md, bool isUnprototyped, bool forVTable)
static Decl::Kind getKind(const Decl *D)
static bool hasAttr(const Decl *D, bool IgnoreImplicitAttr)
CanQualType getCanonicalTagType(const TagDecl *TD) const
Represents a static or instance method of a struct/union/class.
QualType getThisType() const
Return the type of the this pointer.
Represents a C++ struct/union/class.
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
base_class_range vbases()
bool isDynamicClass() const
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
This is an opaque type for sizes expressed in character units.
QuantityType getQuantity() const
Get the raw integer representation of this quantity.
ABIArgInfo - Helper class to encapsulate information about how a specific C type should be passed to ...
@ Indirect
Indirect - Pass the argument indirectly via a hidden pointer with the specified alignment (0 indicate...
bool isSRetAfterThis() const
Like RawAddress, an abstract representation of an aligned address, but the pointer contained in this ...
llvm::Type * getElementType() const
Return the type of the values stored in this address.
static ApplyDebugLocation CreateArtificial(CodeGenFunction &CGF)
Apply TemporaryLocation if it is valid.
static ApplyDebugLocation CreateEmpty(CodeGenFunction &CGF)
Set the IRBuilder to not attach debug locations.
llvm::Value * CreateIsNull(Address Addr, const Twine &Name="")
virtual bool canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const =0
Determine whether it's possible to emit a vtable for RD, even though we do not know that the vtable h...
virtual llvm::Value * performReturnAdjustment(CodeGenFunction &CGF, Address Ret, const CXXRecordDecl *UnadjustedClass, const ReturnAdjustment &RA)=0
virtual void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, GlobalDecl GD, bool ReturnAdjustment)=0
virtual bool exportThunk()=0
MangleContext & getMangleContext()
Gets the mangle context.
static CGCallee forDirect(llvm::Constant *functionPtr, const CGCalleeInfo &abstractInfo=CGCalleeInfo())
This class gathers all debug information during compilation and is responsible for emitting to llvm g...
CGFunctionInfo - Class to encapsulate the information about a function definition.
CallArgList - Type for representing both the value and type of arguments in a call.
void add(RValue rvalue, QualType type)
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
GlobalDecl CurGD
CurGD - The GlobalDecl for the current function being compiled.
void EmitMustTailThunk(GlobalDecl GD, llvm::Value *AdjustedThisPtr, llvm::FunctionCallee Callee)
Emit a musttail call for a thunk with a potentially adjusted this pointer.
bool CurFuncIsThunk
In C++, whether we are code generating a thunk.
void EmitDelegateCallArg(CallArgList &args, const VarDecl *param, SourceLocation loc)
EmitDelegateCallArg - We are performing a delegate call; that is, the current function is delegating ...
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
Address makeNaturalAddressForPointer(llvm::Value *Ptr, QualType T, CharUnits Alignment=CharUnits::Zero(), bool ForPointeeType=false, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
Construct an address with the natural alignment of T.
const Decl * CurCodeDecl
CurCodeDecl - This is the inner-most code context, which includes blocks.
void EmitCallAndReturnForThunk(llvm::FunctionCallee Callee, const ThunkInfo *Thunk, bool IsUnprototyped)
void StartFunction(GlobalDecl GD, QualType RetTy, llvm::Function *Fn, const CGFunctionInfo &FnInfo, const FunctionArgList &Args, SourceLocation Loc=SourceLocation(), SourceLocation StartLoc=SourceLocation())
Emit code for the start of a function.
llvm::Function * GenerateVarArgsThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo, GlobalDecl GD, const ThunkInfo &Thunk)
RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee, ReturnValueSlot ReturnValue, const CallArgList &Args, llvm::CallBase **CallOrInvoke, bool IsMustTail, SourceLocation Loc, bool IsVirtualFunctionPointerThunk=false)
EmitCall - Generate a call of the given function, expecting the given result type,...
const Decl * CurFuncDecl
CurFuncDecl - Holds the Decl for the current outermost non-closure context.
bool AutoreleaseResult
In ARC, whether we should autorelease the return value.
llvm::Type * ConvertTypeForMem(QualType T)
void generateThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo, GlobalDecl GD, const ThunkInfo &Thunk, bool IsUnprototyped)
Generate a thunk for the given method.
void StartThunk(llvm::Function *Fn, GlobalDecl GD, const CGFunctionInfo &FnInfo, bool IsUnprototyped)
static bool hasAggregateEvaluationKind(QualType T)
void FinishFunction(SourceLocation EndLoc=SourceLocation())
FinishFunction - Complete IR generation of the current function.
llvm::Value * LoadCXXThis()
LoadCXXThis - Load the value of 'this'.
const CGFunctionInfo * CurFnInfo
Address GetAddrOfLocalVar(const VarDecl *VD)
GetAddrOfLocalVar - Return the address of a local variable.
Address ReturnValue
ReturnValue - The temporary alloca to hold the return value.
llvm::LLVMContext & getLLVMContext()
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
This class organizes the cross-function state that is used while generating LLVM code.
void setGVProperties(llvm::GlobalValue *GV, GlobalDecl GD) const
Set visibility, dllimport/dllexport and dso_local.
void AddVTableTypeMetadata(llvm::GlobalVariable *VTable, CharUnits Offset, const CXXRecordDecl *RD)
Create and attach type metadata for the given vtable.
llvm::GlobalObject::VCallVisibility GetVCallVisibilityLevel(const CXXRecordDecl *RD, llvm::DenseSet< const CXXRecordDecl * > &Visited)
Returns the vcall visibility of the given type.
llvm::Module & getModule() const
CodeGenVTables & getVTables()
CharUnits GetTargetTypeStoreSize(llvm::Type *Ty) const
Return the store size, in character units, of the given LLVM type.
const LangOptions & getLangOpts() const
const TargetInfo & getTarget() const
void EmitVTableTypeMetadata(const CXXRecordDecl *RD, llvm::GlobalVariable *VTable, const VTableLayout &VTLayout)
Emit type metadata for the given vtable using the given layout.
bool HasHiddenLTOVisibility(const CXXRecordDecl *RD)
Returns whether the given record has hidden LTO visibility and therefore may participate in (single-m...
CGCXXABI & getCXXABI() const
bool mayVTableBeDuplicated(llvm::GlobalValue::LinkageTypes Linkage) const
Returns true if a vtable with the given linkage may be emitted with more than one address in the prog...
CharUnits getClassPointerAlignment(const CXXRecordDecl *CD)
Returns the assumed alignment of an opaque pointer to the given class.
const llvm::Triple & getTriple() const
bool AlwaysHasLTOVisibilityPublic(const CXXRecordDecl *RD)
Returns whether the given record has public LTO visibility (regardless of -lto-whole-program-visibili...
void EmitVTable(CXXRecordDecl *Class)
This is a callback from Sema to tell us that a particular vtable is required to be emitted in this tr...
void setFunctionLinkage(GlobalDecl GD, llvm::Function *F)
ASTContext & getContext() const
llvm::Type * getVTableComponentType() const
bool supportsCOMDAT() const
const CodeGenOptions & getCodeGenOpts() const
llvm::GlobalVariable::LinkageTypes getVTableLinkage(const CXXRecordDecl *RD)
Return the appropriate linkage for the vtable, VTT, and type information of the given class.
llvm::Metadata * CreateMetadataIdentifierForVirtualMemPtrType(QualType T)
Create a metadata identifier that is intended to be used to check virtual calls via a member function...
llvm::Constant * GetAddrOfThunk(StringRef Name, llvm::Type *FnTy, GlobalDecl GD)
Get the address of the thunk for the given global decl.
llvm::GlobalVariable * GetAddrOfVTable(const CXXRecordDecl *RD)
GetAddrOfVTable - Get the address of the VTable for the given record decl.
void createVTableInitializer(ConstantStructBuilder &builder, const VTableLayout &layout, llvm::Constant *rtti, bool vtableHasLocalLinkage)
Add vtable components for the given vtable layout to the given global initializer.
void GenerateClassData(const CXXRecordDecl *RD)
GenerateClassData - Generate all the class data required to be generated upon definition of a KeyFunc...
void GenerateRelativeVTableAlias(llvm::GlobalVariable *VTable, llvm::StringRef AliasNameRef)
Generate a public facing alias for the vtable and make the vtable either hidden or private.
ItaniumVTableContext & getItaniumVTableContext()
CodeGenVTables(CodeGenModule &CGM)
llvm::GlobalVariable * GenerateConstructionVTable(const CXXRecordDecl *RD, const BaseSubobject &Base, bool BaseIsVirtual, llvm::GlobalVariable::LinkageTypes Linkage, VTableAddressPointsMapTy &AddressPoints)
GenerateConstructionVTable - Generate a construction vtable for the given base subobject.
llvm::Type * getVTableType(const VTableLayout &layout)
Returns the type of a vtable with the given layout.
llvm::Type * getVTableComponentType() const
Return the type used as components for a vtable.
bool isVTableExternal(const CXXRecordDecl *RD)
At this point in the translation unit, does it appear that can we rely on the vtable being defined el...
void RemoveHwasanMetadata(llvm::GlobalValue *GV) const
Specify a global should not be instrumented with hwasan.
void EmitThunks(GlobalDecl GD)
EmitThunks - Emit the associated thunks for the given global decl.
void addRelativeOffsetToPosition(llvm::IntegerType *type, llvm::Constant *target, size_t position)
Same as addRelativeOffset(), but instead relative to an element in this aggregate,...
void add(llvm::Constant *value)
Add a new value to this initializer.
void addNullPointer(llvm::PointerType *ptrTy)
Add a null pointer of a specific type.
void addSignedPointer(llvm::Constant *Pointer, const PointerAuthSchema &Schema, GlobalDecl CalleeDecl, QualType CalleeType)
Add a signed pointer using the given pointer authentication schema.
ArrayBuilder beginArray(llvm::Type *eltTy=nullptr)
A helper class of ConstantInitBuilder, used for building constant array initializers.
StructBuilder beginStruct(llvm::StructType *structTy=nullptr)
The standard implementation of ConstantInitBuilder used in Clang.
A helper class of ConstantInitBuilder, used for building constant struct initializers.
FunctionArgList - Type for representing both the decl and type of parameters to a function.
RValue - This trivial value class is used to represent the result of an expression that is evaluated.
static RValue get(llvm::Value *V)
llvm::Value * getScalarVal() const
getScalarVal() - Return the Value* of this scalar value.
static RequiredArgs forPrototypePlus(const FunctionProtoType *prototype, unsigned additional)
Compute the arguments required by the given formal prototype, given that there may be some additional...
ReturnValueSlot - Contains the address where the return value of a function can be stored,...
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
DeclContext * getParent()
getParent - Returns the containing DeclContext.
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
bool isInNamedModule() const
Whether this declaration comes from a named module.
SourceLocation getLocation() const
bool shouldEmitInExternalSource() const
Whether the definition of the declaration should be emitted in external sources.
Represents a function declaration or definition.
param_iterator param_end()
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
ArrayRef< ParmVarDecl * > parameters() const
param_iterator param_begin()
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
bool isDefined(const FunctionDecl *&Definition, bool CheckForPendingFriendDefinition=false) const
Returns true if the function has a definition that does not need to be instantiated.
Represents a prototype with parameter type info, e.g.
QualType getReturnType() const
GlobalDecl - represents a global declaration.
GlobalDecl getWithDecl(const Decl *D)
CXXDtorType getDtorType() const
const Decl * getDecl() const
One of these records is kept for each identifier that is lexed.
GlobalDecl findOriginalMethod(GlobalDecl GD)
Return the method that added the v-table slot that will be used to call the given method.
Visibility getVisibility() const
Linkage getLinkage() const
virtual void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type, const ThunkInfo &Thunk, bool ElideOverrideInfo, raw_ostream &)=0
virtual void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk, bool ElideOverrideInfo, raw_ostream &)=0
virtual void mangleCanonicalTypeName(QualType T, raw_ostream &, bool NormalizeIntegers=false)=0
Generates a unique string for an externally visible type for use with TBAA or type uniquing.
LinkageInfo getLinkageAndVisibility() const
Determines the linkage and visibility of this entity.
bool isExternallyVisible() const
Represents a parameter to a function.
A (possibly-)qualified type.
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Encodes a location in the source.
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
virtual VTableUniquenessKind getVTableUniqueness() const
Returns whether the target's ABI guarantees that a class's vtable has a unique address program-wide.
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
const T * castAs() const
Member-template castAs<specific type>.
bool isReferenceType() const
const CXXRecordDecl * getPointeeCXXRecordDecl() const
If this is a pointer or reference to a RecordType, return the CXXRecordDecl that the type refers to.
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
@ CK_DeletingDtorPointer
A pointer to the deleting destructor.
@ CK_UnusedFunctionPointer
An entry that is never used.
@ CK_CompleteDtorPointer
A pointer to the complete destructor.
SmallVector< ThunkInfo, 1 > ThunkInfoVectorTy
const AddressPointsIndexMapTy & getAddressPointIndices() const
size_t getVTableOffset(size_t i) const
ArrayRef< VTableComponent > vtable_components() const
size_t getNumVTables() const
ArrayRef< VTableThunkTy > vtable_thunks() const
const AddressPointsMapTy & getAddressPoints() const
size_t getVTableSize(size_t i) const
Top level wrappers for InstallAPI frontend operations.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
@ UniqueIfStrongLinkage
A vtable with strong linkage (e.g., a class with a key function) is unique, but a vague-linkage (weak...
bool isa(CodeGen::Address addr)
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
bool operator<(DeclarationName LHS, DeclarationName RHS)
Ordering on two declaration names.
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have.
const FunctionProtoType * T
@ Dtor_Base
Base object dtor.
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
CallingConv
CallingConv - Specifies the calling convention that a function uses.
U cast(CodeGen::Address addr)
bool isExternallyVisible(Linkage L)
@ HiddenVisibility
Objects with "hidden" visibility are not seen by the dynamic linker.
llvm::PointerType * GlobalsInt8PtrTy
llvm::IntegerType * Int32Ty
llvm::IntegerType * PtrDiffTy
The this pointer adjustment as well as an optional return adjustment for a thunk.
ReturnAdjustment Return
The return adjustment.