1 //===--- MicrosoftCXXABI.cpp - Emit LLVM Code from ASTs for a Module ------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This provides C++ code generation targeting the Microsoft Visual C++ ABI.
10 // The class in this file generates structures that follow the Microsoft
11 // Visual C++ ABI, which is actually not very well documented at all outside
14 //===----------------------------------------------------------------------===//
18 #include "CGCleanup.h"
19 #include "CGVTables.h"
20 #include "CodeGenModule.h"
21 #include "CodeGenTypes.h"
22 #include "TargetInfo.h"
23 #include "clang/AST/Attr.h"
24 #include "clang/AST/CXXInheritance.h"
25 #include "clang/AST/Decl.h"
26 #include "clang/AST/DeclCXX.h"
27 #include "clang/AST/StmtCXX.h"
28 #include "clang/AST/VTableBuilder.h"
29 #include "clang/CodeGen/ConstantInitBuilder.h"
30 #include "llvm/ADT/StringExtras.h"
31 #include "llvm/ADT/StringSet.h"
32 #include "llvm/IR/Intrinsics.h"
34 using namespace clang
;
35 using namespace CodeGen
;
39 /// Holds all the vbtable globals for a given class.
40 struct VBTableGlobals
{
41 const VPtrInfoVector
*VBTables
;
42 SmallVector
<llvm::GlobalVariable
*, 2> Globals
;
45 class MicrosoftCXXABI
: public CGCXXABI
{
47 MicrosoftCXXABI(CodeGenModule
&CGM
)
48 : CGCXXABI(CGM
), BaseClassDescriptorType(nullptr),
49 ClassHierarchyDescriptorType(nullptr),
50 CompleteObjectLocatorType(nullptr), CatchableTypeType(nullptr),
51 ThrowInfoType(nullptr) {
52 assert(!(CGM
.getLangOpts().isExplicitDefaultVisibilityExportMapping() ||
53 CGM
.getLangOpts().isAllDefaultVisibilityExportMapping()) &&
54 "visibility export mapping option unimplemented in this ABI");
57 bool HasThisReturn(GlobalDecl GD
) const override
;
58 bool hasMostDerivedReturn(GlobalDecl GD
) const override
;
60 bool classifyReturnType(CGFunctionInfo
&FI
) const override
;
62 RecordArgABI
getRecordArgABI(const CXXRecordDecl
*RD
) const override
;
64 bool isSRetParameterAfterThis() const override
{ return true; }
66 bool isThisCompleteObject(GlobalDecl GD
) const override
{
67 // The Microsoft ABI doesn't use separate complete-object vs.
68 // base-object variants of constructors, but it does of destructors.
69 if (isa
<CXXDestructorDecl
>(GD
.getDecl())) {
70 switch (GD
.getDtorType()) {
78 case Dtor_Comdat
: llvm_unreachable("emitting dtor comdat as function?");
80 llvm_unreachable("bad dtor kind");
87 size_t getSrcArgforCopyCtor(const CXXConstructorDecl
*CD
,
88 FunctionArgList
&Args
) const override
{
89 assert(Args
.size() >= 2 &&
90 "expected the arglist to have at least two args!");
91 // The 'most_derived' parameter goes second if the ctor is variadic and
93 if (CD
->getParent()->getNumVBases() > 0 &&
94 CD
->getType()->castAs
<FunctionProtoType
>()->isVariadic())
99 std::vector
<CharUnits
> getVBPtrOffsets(const CXXRecordDecl
*RD
) override
{
100 std::vector
<CharUnits
> VBPtrOffsets
;
101 const ASTContext
&Context
= getContext();
102 const ASTRecordLayout
&Layout
= Context
.getASTRecordLayout(RD
);
104 const VBTableGlobals
&VBGlobals
= enumerateVBTables(RD
);
105 for (const std::unique_ptr
<VPtrInfo
> &VBT
: *VBGlobals
.VBTables
) {
106 const ASTRecordLayout
&SubobjectLayout
=
107 Context
.getASTRecordLayout(VBT
->IntroducingObject
);
108 CharUnits Offs
= VBT
->NonVirtualOffset
;
109 Offs
+= SubobjectLayout
.getVBPtrOffset();
110 if (VBT
->getVBaseWithVPtr())
111 Offs
+= Layout
.getVBaseClassOffset(VBT
->getVBaseWithVPtr());
112 VBPtrOffsets
.push_back(Offs
);
114 llvm::array_pod_sort(VBPtrOffsets
.begin(), VBPtrOffsets
.end());
118 StringRef
GetPureVirtualCallName() override
{ return "_purecall"; }
119 StringRef
GetDeletedVirtualCallName() override
{ return "_purecall"; }
121 void emitVirtualObjectDelete(CodeGenFunction
&CGF
, const CXXDeleteExpr
*DE
,
122 Address Ptr
, QualType ElementType
,
123 const CXXDestructorDecl
*Dtor
) override
;
125 void emitRethrow(CodeGenFunction
&CGF
, bool isNoReturn
) override
;
126 void emitThrow(CodeGenFunction
&CGF
, const CXXThrowExpr
*E
) override
;
128 void emitBeginCatch(CodeGenFunction
&CGF
, const CXXCatchStmt
*C
) override
;
130 llvm::GlobalVariable
*getMSCompleteObjectLocator(const CXXRecordDecl
*RD
,
131 const VPtrInfo
&Info
);
133 llvm::Constant
*getAddrOfRTTIDescriptor(QualType Ty
) override
;
135 getAddrOfCXXCatchHandlerType(QualType Ty
, QualType CatchHandlerType
) override
;
137 /// MSVC needs an extra flag to indicate a catchall.
138 CatchTypeInfo
getCatchAllTypeInfo() override
{
139 // For -EHa catch(...) must handle HW exception
140 // Adjective = HT_IsStdDotDot (0x40), only catch C++ exceptions
141 if (getContext().getLangOpts().EHAsynch
)
142 return CatchTypeInfo
{nullptr, 0};
144 return CatchTypeInfo
{nullptr, 0x40};
147 bool shouldTypeidBeNullChecked(bool IsDeref
, QualType SrcRecordTy
) override
;
148 void EmitBadTypeidCall(CodeGenFunction
&CGF
) override
;
149 llvm::Value
*EmitTypeid(CodeGenFunction
&CGF
, QualType SrcRecordTy
,
151 llvm::Type
*StdTypeInfoPtrTy
) override
;
153 bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr
,
154 QualType SrcRecordTy
) override
;
156 bool shouldEmitExactDynamicCast(QualType DestRecordTy
) override
{
157 // TODO: Add support for exact dynamic_casts.
160 llvm::Value
*emitExactDynamicCast(CodeGenFunction
&CGF
, Address Value
,
161 QualType SrcRecordTy
, QualType DestTy
,
162 QualType DestRecordTy
,
163 llvm::BasicBlock
*CastSuccess
,
164 llvm::BasicBlock
*CastFail
) override
{
165 llvm_unreachable("unsupported");
168 llvm::Value
*emitDynamicCastCall(CodeGenFunction
&CGF
, Address Value
,
169 QualType SrcRecordTy
, QualType DestTy
,
170 QualType DestRecordTy
,
171 llvm::BasicBlock
*CastEnd
) override
;
173 llvm::Value
*emitDynamicCastToVoid(CodeGenFunction
&CGF
, Address Value
,
174 QualType SrcRecordTy
) override
;
176 bool EmitBadCastCall(CodeGenFunction
&CGF
) override
;
177 bool canSpeculativelyEmitVTable(const CXXRecordDecl
*RD
) const override
{
182 GetVirtualBaseClassOffset(CodeGenFunction
&CGF
, Address This
,
183 const CXXRecordDecl
*ClassDecl
,
184 const CXXRecordDecl
*BaseClassDecl
) override
;
187 EmitCtorCompleteObjectHandler(CodeGenFunction
&CGF
,
188 const CXXRecordDecl
*RD
) override
;
191 EmitDtorCompleteObjectHandler(CodeGenFunction
&CGF
);
193 void initializeHiddenVirtualInheritanceMembers(CodeGenFunction
&CGF
,
194 const CXXRecordDecl
*RD
) override
;
196 void EmitCXXConstructors(const CXXConstructorDecl
*D
) override
;
198 // Background on MSVC destructors
199 // ==============================
201 // Both Itanium and MSVC ABIs have destructor variants. The variant names
202 // roughly correspond in the following way:
204 // Base -> no name, just ~Class
205 // Complete -> vbase destructor
206 // Deleting -> scalar deleting destructor
207 // vector deleting destructor
209 // The base and complete destructors are the same as in Itanium, although the
210 // complete destructor does not accept a VTT parameter when there are virtual
211 // bases. A separate mechanism involving vtordisps is used to ensure that
212 // virtual methods of destroyed subobjects are not called.
214 // The deleting destructors accept an i32 bitfield as a second parameter. Bit
215 // 1 indicates if the memory should be deleted. Bit 2 indicates if the this
216 // pointer points to an array. The scalar deleting destructor assumes that
217 // bit 2 is zero, and therefore does not contain a loop.
219 // For virtual destructors, only one entry is reserved in the vftable, and it
220 // always points to the vector deleting destructor. The vector deleting
221 // destructor is the most general, so it can be used to destroy objects in
222 // place, delete single heap objects, or delete arrays.
224 // A TU defining a non-inline destructor is only guaranteed to emit a base
225 // destructor, and all of the other variants are emitted on an as-needed basis
226 // in COMDATs. Because a non-base destructor can be emitted in a TU that
227 // lacks a definition for the destructor, non-base destructors must always
228 // delegate to or alias the base destructor.
230 AddedStructorArgCounts
231 buildStructorSignature(GlobalDecl GD
,
232 SmallVectorImpl
<CanQualType
> &ArgTys
) override
;
234 /// Non-base dtors should be emitted as delegating thunks in this ABI.
235 bool useThunkForDtorVariant(const CXXDestructorDecl
*Dtor
,
236 CXXDtorType DT
) const override
{
237 return DT
!= Dtor_Base
;
240 void setCXXDestructorDLLStorage(llvm::GlobalValue
*GV
,
241 const CXXDestructorDecl
*Dtor
,
242 CXXDtorType DT
) const override
;
244 llvm::GlobalValue::LinkageTypes
245 getCXXDestructorLinkage(GVALinkage Linkage
, const CXXDestructorDecl
*Dtor
,
246 CXXDtorType DT
) const override
;
248 void EmitCXXDestructors(const CXXDestructorDecl
*D
) override
;
250 const CXXRecordDecl
*getThisArgumentTypeForMethod(GlobalDecl GD
) override
{
251 auto *MD
= cast
<CXXMethodDecl
>(GD
.getDecl());
253 if (MD
->isVirtual()) {
254 GlobalDecl LookupGD
= GD
;
255 if (const auto *DD
= dyn_cast
<CXXDestructorDecl
>(MD
)) {
256 // Complete dtors take a pointer to the complete object,
257 // thus don't need adjustment.
258 if (GD
.getDtorType() == Dtor_Complete
)
259 return MD
->getParent();
261 // There's only Dtor_Deleting in vftable but it shares the this
262 // adjustment with the base one, so look up the deleting one instead.
263 LookupGD
= GlobalDecl(DD
, Dtor_Deleting
);
265 MethodVFTableLocation ML
=
266 CGM
.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD
);
268 // The vbases might be ordered differently in the final overrider object
269 // and the complete object, so the "this" argument may sometimes point to
270 // memory that has no particular type (e.g. past the complete object).
271 // In this case, we just use a generic pointer type.
272 // FIXME: might want to have a more precise type in the non-virtual
273 // multiple inheritance case.
274 if (ML
.VBase
|| !ML
.VFPtrOffset
.isZero())
277 return MD
->getParent();
281 adjustThisArgumentForVirtualFunctionCall(CodeGenFunction
&CGF
, GlobalDecl GD
,
283 bool VirtualCall
) override
;
285 void addImplicitStructorParams(CodeGenFunction
&CGF
, QualType
&ResTy
,
286 FunctionArgList
&Params
) override
;
288 void EmitInstanceFunctionProlog(CodeGenFunction
&CGF
) override
;
290 AddedStructorArgs
getImplicitConstructorArgs(CodeGenFunction
&CGF
,
291 const CXXConstructorDecl
*D
,
294 bool Delegating
) override
;
296 llvm::Value
*getCXXDestructorImplicitParam(CodeGenFunction
&CGF
,
297 const CXXDestructorDecl
*DD
,
300 bool Delegating
) override
;
302 void EmitDestructorCall(CodeGenFunction
&CGF
, const CXXDestructorDecl
*DD
,
303 CXXDtorType Type
, bool ForVirtualBase
,
304 bool Delegating
, Address This
,
305 QualType ThisTy
) override
;
307 void emitVTableTypeMetadata(const VPtrInfo
&Info
, const CXXRecordDecl
*RD
,
308 llvm::GlobalVariable
*VTable
);
310 void emitVTableDefinitions(CodeGenVTables
&CGVT
,
311 const CXXRecordDecl
*RD
) override
;
313 bool isVirtualOffsetNeededForVTableField(CodeGenFunction
&CGF
,
314 CodeGenFunction::VPtr Vptr
) override
;
316 /// Don't initialize vptrs if dynamic class
317 /// is marked with the 'novtable' attribute.
318 bool doStructorsInitializeVPtrs(const CXXRecordDecl
*VTableClass
) override
{
319 return !VTableClass
->hasAttr
<MSNoVTableAttr
>();
323 getVTableAddressPoint(BaseSubobject Base
,
324 const CXXRecordDecl
*VTableClass
) override
;
326 llvm::Value
*getVTableAddressPointInStructor(
327 CodeGenFunction
&CGF
, const CXXRecordDecl
*VTableClass
,
328 BaseSubobject Base
, const CXXRecordDecl
*NearestVBase
) override
;
331 getVTableAddressPointForConstExpr(BaseSubobject Base
,
332 const CXXRecordDecl
*VTableClass
) override
;
334 llvm::GlobalVariable
*getAddrOfVTable(const CXXRecordDecl
*RD
,
335 CharUnits VPtrOffset
) override
;
337 CGCallee
getVirtualFunctionPointer(CodeGenFunction
&CGF
, GlobalDecl GD
,
338 Address This
, llvm::Type
*Ty
,
339 SourceLocation Loc
) override
;
341 llvm::Value
*EmitVirtualDestructorCall(CodeGenFunction
&CGF
,
342 const CXXDestructorDecl
*Dtor
,
343 CXXDtorType DtorType
, Address This
,
344 DeleteOrMemberCallExpr E
) override
;
346 void adjustCallArgsForDestructorThunk(CodeGenFunction
&CGF
, GlobalDecl GD
,
347 CallArgList
&CallArgs
) override
{
348 assert(GD
.getDtorType() == Dtor_Deleting
&&
349 "Only deleting destructor thunks are available in this ABI");
350 CallArgs
.add(RValue::get(getStructorImplicitParamValue(CGF
)),
354 void emitVirtualInheritanceTables(const CXXRecordDecl
*RD
) override
;
356 llvm::GlobalVariable
*
357 getAddrOfVBTable(const VPtrInfo
&VBT
, const CXXRecordDecl
*RD
,
358 llvm::GlobalVariable::LinkageTypes Linkage
);
360 llvm::GlobalVariable
*
361 getAddrOfVirtualDisplacementMap(const CXXRecordDecl
*SrcRD
,
362 const CXXRecordDecl
*DstRD
) {
363 SmallString
<256> OutName
;
364 llvm::raw_svector_ostream
Out(OutName
);
365 getMangleContext().mangleCXXVirtualDisplacementMap(SrcRD
, DstRD
, Out
);
366 StringRef MangledName
= OutName
.str();
368 if (auto *VDispMap
= CGM
.getModule().getNamedGlobal(MangledName
))
371 MicrosoftVTableContext
&VTContext
= CGM
.getMicrosoftVTableContext();
372 unsigned NumEntries
= 1 + SrcRD
->getNumVBases();
373 SmallVector
<llvm::Constant
*, 4> Map(NumEntries
,
374 llvm::UndefValue::get(CGM
.IntTy
));
375 Map
[0] = llvm::ConstantInt::get(CGM
.IntTy
, 0);
376 bool AnyDifferent
= false;
377 for (const auto &I
: SrcRD
->vbases()) {
378 const CXXRecordDecl
*VBase
= I
.getType()->getAsCXXRecordDecl();
379 if (!DstRD
->isVirtuallyDerivedFrom(VBase
))
382 unsigned SrcVBIndex
= VTContext
.getVBTableIndex(SrcRD
, VBase
);
383 unsigned DstVBIndex
= VTContext
.getVBTableIndex(DstRD
, VBase
);
384 Map
[SrcVBIndex
] = llvm::ConstantInt::get(CGM
.IntTy
, DstVBIndex
* 4);
385 AnyDifferent
|= SrcVBIndex
!= DstVBIndex
;
387 // This map would be useless, don't use it.
391 llvm::ArrayType
*VDispMapTy
= llvm::ArrayType::get(CGM
.IntTy
, Map
.size());
392 llvm::Constant
*Init
= llvm::ConstantArray::get(VDispMapTy
, Map
);
393 llvm::GlobalValue::LinkageTypes Linkage
=
394 SrcRD
->isExternallyVisible() && DstRD
->isExternallyVisible()
395 ? llvm::GlobalValue::LinkOnceODRLinkage
396 : llvm::GlobalValue::InternalLinkage
;
397 auto *VDispMap
= new llvm::GlobalVariable(
398 CGM
.getModule(), VDispMapTy
, /*isConstant=*/true, Linkage
,
399 /*Initializer=*/Init
, MangledName
);
403 void emitVBTableDefinition(const VPtrInfo
&VBT
, const CXXRecordDecl
*RD
,
404 llvm::GlobalVariable
*GV
) const;
406 void setThunkLinkage(llvm::Function
*Thunk
, bool ForVTable
,
407 GlobalDecl GD
, bool ReturnAdjustment
) override
{
409 getContext().GetGVALinkageForFunction(cast
<FunctionDecl
>(GD
.getDecl()));
411 if (Linkage
== GVA_Internal
)
412 Thunk
->setLinkage(llvm::GlobalValue::InternalLinkage
);
413 else if (ReturnAdjustment
)
414 Thunk
->setLinkage(llvm::GlobalValue::WeakODRLinkage
);
416 Thunk
->setLinkage(llvm::GlobalValue::LinkOnceODRLinkage
);
419 bool exportThunk() override
{ return false; }
421 llvm::Value
*performThisAdjustment(CodeGenFunction
&CGF
, Address This
,
422 const ThisAdjustment
&TA
) override
;
424 llvm::Value
*performReturnAdjustment(CodeGenFunction
&CGF
, Address Ret
,
425 const ReturnAdjustment
&RA
) override
;
427 void EmitThreadLocalInitFuncs(
428 CodeGenModule
&CGM
, ArrayRef
<const VarDecl
*> CXXThreadLocals
,
429 ArrayRef
<llvm::Function
*> CXXThreadLocalInits
,
430 ArrayRef
<const VarDecl
*> CXXThreadLocalInitVars
) override
;
432 bool usesThreadWrapperFunction(const VarDecl
*VD
) const override
{
433 return getContext().getLangOpts().isCompatibleWithMSVC(
434 LangOptions::MSVC2019_5
) &&
435 (!isEmittedWithConstantInitializer(VD
) || mayNeedDestruction(VD
));
437 LValue
EmitThreadLocalVarDeclLValue(CodeGenFunction
&CGF
, const VarDecl
*VD
,
438 QualType LValType
) override
;
440 void EmitGuardedInit(CodeGenFunction
&CGF
, const VarDecl
&D
,
441 llvm::GlobalVariable
*DeclPtr
,
442 bool PerformInit
) override
;
443 void registerGlobalDtor(CodeGenFunction
&CGF
, const VarDecl
&D
,
444 llvm::FunctionCallee Dtor
,
445 llvm::Constant
*Addr
) override
;
447 // ==== Notes on array cookies =========
449 // MSVC seems to only use cookies when the class has a destructor; a
450 // two-argument usual array deallocation function isn't sufficient.
452 // For example, this code prints "100" and "1":
455 // void *operator new[](size_t sz) {
456 // printf("%u\n", sz);
457 // return malloc(sz);
459 // void operator delete[](void *p, size_t sz) {
460 // printf("%u\n", sz);
465 // A *p = new A[100];
468 // Whereas it prints "104" and "104" if you give A a destructor.
470 bool requiresArrayCookie(const CXXDeleteExpr
*expr
,
471 QualType elementType
) override
;
472 bool requiresArrayCookie(const CXXNewExpr
*expr
) override
;
473 CharUnits
getArrayCookieSizeImpl(QualType type
) override
;
474 Address
InitializeArrayCookie(CodeGenFunction
&CGF
,
476 llvm::Value
*NumElements
,
477 const CXXNewExpr
*expr
,
478 QualType ElementType
) override
;
479 llvm::Value
*readArrayCookieImpl(CodeGenFunction
&CGF
,
481 CharUnits cookieSize
) override
;
483 friend struct MSRTTIBuilder
;
485 bool isImageRelative() const {
486 return CGM
.getTarget().getPointerWidth(LangAS::Default
) == 64;
489 // 5 routines for constructing the llvm types for MS RTTI structs.
490 llvm::StructType
*getTypeDescriptorType(StringRef TypeInfoString
) {
491 llvm::SmallString
<32> TDTypeName("rtti.TypeDescriptor");
492 TDTypeName
+= llvm::utostr(TypeInfoString
.size());
493 llvm::StructType
*&TypeDescriptorType
=
494 TypeDescriptorTypeMap
[TypeInfoString
.size()];
495 if (TypeDescriptorType
)
496 return TypeDescriptorType
;
497 llvm::Type
*FieldTypes
[] = {
500 llvm::ArrayType::get(CGM
.Int8Ty
, TypeInfoString
.size() + 1)};
502 llvm::StructType::create(CGM
.getLLVMContext(), FieldTypes
, TDTypeName
);
503 return TypeDescriptorType
;
506 llvm::Type
*getImageRelativeType(llvm::Type
*PtrType
) {
507 if (!isImageRelative())
512 llvm::StructType
*getBaseClassDescriptorType() {
513 if (BaseClassDescriptorType
)
514 return BaseClassDescriptorType
;
515 llvm::Type
*FieldTypes
[] = {
516 getImageRelativeType(CGM
.Int8PtrTy
),
522 getImageRelativeType(getClassHierarchyDescriptorType()->getPointerTo()),
524 BaseClassDescriptorType
= llvm::StructType::create(
525 CGM
.getLLVMContext(), FieldTypes
, "rtti.BaseClassDescriptor");
526 return BaseClassDescriptorType
;
529 llvm::StructType
*getClassHierarchyDescriptorType() {
530 if (ClassHierarchyDescriptorType
)
531 return ClassHierarchyDescriptorType
;
532 // Forward-declare RTTIClassHierarchyDescriptor to break a cycle.
533 ClassHierarchyDescriptorType
= llvm::StructType::create(
534 CGM
.getLLVMContext(), "rtti.ClassHierarchyDescriptor");
535 llvm::Type
*FieldTypes
[] = {
539 getImageRelativeType(
540 getBaseClassDescriptorType()->getPointerTo()->getPointerTo()),
542 ClassHierarchyDescriptorType
->setBody(FieldTypes
);
543 return ClassHierarchyDescriptorType
;
546 llvm::StructType
*getCompleteObjectLocatorType() {
547 if (CompleteObjectLocatorType
)
548 return CompleteObjectLocatorType
;
549 CompleteObjectLocatorType
= llvm::StructType::create(
550 CGM
.getLLVMContext(), "rtti.CompleteObjectLocator");
551 llvm::Type
*FieldTypes
[] = {
555 getImageRelativeType(CGM
.Int8PtrTy
),
556 getImageRelativeType(getClassHierarchyDescriptorType()->getPointerTo()),
557 getImageRelativeType(CompleteObjectLocatorType
),
559 llvm::ArrayRef
<llvm::Type
*> FieldTypesRef(FieldTypes
);
560 if (!isImageRelative())
561 FieldTypesRef
= FieldTypesRef
.drop_back();
562 CompleteObjectLocatorType
->setBody(FieldTypesRef
);
563 return CompleteObjectLocatorType
;
566 llvm::GlobalVariable
*getImageBase() {
567 StringRef Name
= "__ImageBase";
568 if (llvm::GlobalVariable
*GV
= CGM
.getModule().getNamedGlobal(Name
))
571 auto *GV
= new llvm::GlobalVariable(CGM
.getModule(), CGM
.Int8Ty
,
573 llvm::GlobalValue::ExternalLinkage
,
574 /*Initializer=*/nullptr, Name
);
579 llvm::Constant
*getImageRelativeConstant(llvm::Constant
*PtrVal
) {
580 if (!isImageRelative())
583 if (PtrVal
->isNullValue())
584 return llvm::Constant::getNullValue(CGM
.IntTy
);
586 llvm::Constant
*ImageBaseAsInt
=
587 llvm::ConstantExpr::getPtrToInt(getImageBase(), CGM
.IntPtrTy
);
588 llvm::Constant
*PtrValAsInt
=
589 llvm::ConstantExpr::getPtrToInt(PtrVal
, CGM
.IntPtrTy
);
590 llvm::Constant
*Diff
=
591 llvm::ConstantExpr::getSub(PtrValAsInt
, ImageBaseAsInt
,
592 /*HasNUW=*/true, /*HasNSW=*/true);
593 return llvm::ConstantExpr::getTrunc(Diff
, CGM
.IntTy
);
597 MicrosoftMangleContext
&getMangleContext() {
598 return cast
<MicrosoftMangleContext
>(CodeGen::CGCXXABI::getMangleContext());
601 llvm::Constant
*getZeroInt() {
602 return llvm::ConstantInt::get(CGM
.IntTy
, 0);
605 llvm::Constant
*getAllOnesInt() {
606 return llvm::Constant::getAllOnesValue(CGM
.IntTy
);
609 CharUnits
getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD
) override
;
612 GetNullMemberPointerFields(const MemberPointerType
*MPT
,
613 llvm::SmallVectorImpl
<llvm::Constant
*> &fields
);
615 /// Shared code for virtual base adjustment. Returns the offset from
616 /// the vbptr to the virtual base. Optionally returns the address of the
618 llvm::Value
*GetVBaseOffsetFromVBPtr(CodeGenFunction
&CGF
,
620 llvm::Value
*VBPtrOffset
,
621 llvm::Value
*VBTableOffset
,
622 llvm::Value
**VBPtr
= nullptr);
624 llvm::Value
*GetVBaseOffsetFromVBPtr(CodeGenFunction
&CGF
,
627 int32_t VBTableOffset
,
628 llvm::Value
**VBPtr
= nullptr) {
629 assert(VBTableOffset
% 4 == 0 && "should be byte offset into table of i32s");
630 llvm::Value
*VBPOffset
= llvm::ConstantInt::get(CGM
.IntTy
, VBPtrOffset
),
631 *VBTOffset
= llvm::ConstantInt::get(CGM
.IntTy
, VBTableOffset
);
632 return GetVBaseOffsetFromVBPtr(CGF
, Base
, VBPOffset
, VBTOffset
, VBPtr
);
635 std::tuple
<Address
, llvm::Value
*, const CXXRecordDecl
*>
636 performBaseAdjustment(CodeGenFunction
&CGF
, Address Value
,
637 QualType SrcRecordTy
);
639 /// Performs a full virtual base adjustment. Used to dereference
640 /// pointers to members of virtual bases.
641 llvm::Value
*AdjustVirtualBase(CodeGenFunction
&CGF
, const Expr
*E
,
642 const CXXRecordDecl
*RD
, Address Base
,
643 llvm::Value
*VirtualBaseAdjustmentOffset
,
644 llvm::Value
*VBPtrOffset
/* optional */);
646 /// Emits a full member pointer with the fields common to data and
647 /// function member pointers.
648 llvm::Constant
*EmitFullMemberPointer(llvm::Constant
*FirstField
,
649 bool IsMemberFunction
,
650 const CXXRecordDecl
*RD
,
651 CharUnits NonVirtualBaseAdjustment
,
652 unsigned VBTableIndex
);
654 bool MemberPointerConstantIsNull(const MemberPointerType
*MPT
,
657 /// - Initialize all vbptrs of 'this' with RD as the complete type.
658 void EmitVBPtrStores(CodeGenFunction
&CGF
, const CXXRecordDecl
*RD
);
660 /// Caching wrapper around VBTableBuilder::enumerateVBTables().
661 const VBTableGlobals
&enumerateVBTables(const CXXRecordDecl
*RD
);
663 /// Generate a thunk for calling a virtual member function MD.
664 llvm::Function
*EmitVirtualMemPtrThunk(const CXXMethodDecl
*MD
,
665 const MethodVFTableLocation
&ML
);
667 llvm::Constant
*EmitMemberDataPointer(const CXXRecordDecl
*RD
,
671 llvm::Type
*ConvertMemberPointerType(const MemberPointerType
*MPT
) override
;
673 bool isZeroInitializable(const MemberPointerType
*MPT
) override
;
675 bool isMemberPointerConvertible(const MemberPointerType
*MPT
) const override
{
676 const CXXRecordDecl
*RD
= MPT
->getMostRecentCXXRecordDecl();
677 return RD
->hasAttr
<MSInheritanceAttr
>();
680 llvm::Constant
*EmitNullMemberPointer(const MemberPointerType
*MPT
) override
;
682 llvm::Constant
*EmitMemberDataPointer(const MemberPointerType
*MPT
,
683 CharUnits offset
) override
;
684 llvm::Constant
*EmitMemberFunctionPointer(const CXXMethodDecl
*MD
) override
;
685 llvm::Constant
*EmitMemberPointer(const APValue
&MP
, QualType MPT
) override
;
687 llvm::Value
*EmitMemberPointerComparison(CodeGenFunction
&CGF
,
690 const MemberPointerType
*MPT
,
691 bool Inequality
) override
;
693 llvm::Value
*EmitMemberPointerIsNotNull(CodeGenFunction
&CGF
,
695 const MemberPointerType
*MPT
) override
;
698 EmitMemberDataPointerAddress(CodeGenFunction
&CGF
, const Expr
*E
,
699 Address Base
, llvm::Value
*MemPtr
,
700 const MemberPointerType
*MPT
) override
;
702 llvm::Value
*EmitNonNullMemberPointerConversion(
703 const MemberPointerType
*SrcTy
, const MemberPointerType
*DstTy
,
704 CastKind CK
, CastExpr::path_const_iterator PathBegin
,
705 CastExpr::path_const_iterator PathEnd
, llvm::Value
*Src
,
706 CGBuilderTy
&Builder
);
708 llvm::Value
*EmitMemberPointerConversion(CodeGenFunction
&CGF
,
710 llvm::Value
*Src
) override
;
712 llvm::Constant
*EmitMemberPointerConversion(const CastExpr
*E
,
713 llvm::Constant
*Src
) override
;
715 llvm::Constant
*EmitMemberPointerConversion(
716 const MemberPointerType
*SrcTy
, const MemberPointerType
*DstTy
,
717 CastKind CK
, CastExpr::path_const_iterator PathBegin
,
718 CastExpr::path_const_iterator PathEnd
, llvm::Constant
*Src
);
721 EmitLoadOfMemberFunctionPointer(CodeGenFunction
&CGF
, const Expr
*E
,
722 Address This
, llvm::Value
*&ThisPtrForCall
,
724 const MemberPointerType
*MPT
) override
;
726 void emitCXXStructor(GlobalDecl GD
) override
;
728 llvm::StructType
*getCatchableTypeType() {
729 if (CatchableTypeType
)
730 return CatchableTypeType
;
731 llvm::Type
*FieldTypes
[] = {
733 getImageRelativeType(CGM
.Int8PtrTy
), // TypeDescriptor
734 CGM
.IntTy
, // NonVirtualAdjustment
735 CGM
.IntTy
, // OffsetToVBPtr
736 CGM
.IntTy
, // VBTableIndex
738 getImageRelativeType(CGM
.Int8PtrTy
) // CopyCtor
740 CatchableTypeType
= llvm::StructType::create(
741 CGM
.getLLVMContext(), FieldTypes
, "eh.CatchableType");
742 return CatchableTypeType
;
745 llvm::StructType
*getCatchableTypeArrayType(uint32_t NumEntries
) {
746 llvm::StructType
*&CatchableTypeArrayType
=
747 CatchableTypeArrayTypeMap
[NumEntries
];
748 if (CatchableTypeArrayType
)
749 return CatchableTypeArrayType
;
751 llvm::SmallString
<23> CTATypeName("eh.CatchableTypeArray.");
752 CTATypeName
+= llvm::utostr(NumEntries
);
754 getImageRelativeType(getCatchableTypeType()->getPointerTo());
755 llvm::Type
*FieldTypes
[] = {
756 CGM
.IntTy
, // NumEntries
757 llvm::ArrayType::get(CTType
, NumEntries
) // CatchableTypes
759 CatchableTypeArrayType
=
760 llvm::StructType::create(CGM
.getLLVMContext(), FieldTypes
, CTATypeName
);
761 return CatchableTypeArrayType
;
764 llvm::StructType
*getThrowInfoType() {
766 return ThrowInfoType
;
767 llvm::Type
*FieldTypes
[] = {
769 getImageRelativeType(CGM
.Int8PtrTy
), // CleanupFn
770 getImageRelativeType(CGM
.Int8PtrTy
), // ForwardCompat
771 getImageRelativeType(CGM
.Int8PtrTy
) // CatchableTypeArray
773 ThrowInfoType
= llvm::StructType::create(CGM
.getLLVMContext(), FieldTypes
,
775 return ThrowInfoType
;
778 llvm::FunctionCallee
getThrowFn() {
779 // _CxxThrowException is passed an exception object and a ThrowInfo object
780 // which describes the exception.
781 llvm::Type
*Args
[] = {CGM
.Int8PtrTy
, getThrowInfoType()->getPointerTo()};
782 llvm::FunctionType
*FTy
=
783 llvm::FunctionType::get(CGM
.VoidTy
, Args
, /*isVarArg=*/false);
784 llvm::FunctionCallee Throw
=
785 CGM
.CreateRuntimeFunction(FTy
, "_CxxThrowException");
786 // _CxxThrowException is stdcall on 32-bit x86 platforms.
787 if (CGM
.getTarget().getTriple().getArch() == llvm::Triple::x86
) {
788 if (auto *Fn
= dyn_cast
<llvm::Function
>(Throw
.getCallee()))
789 Fn
->setCallingConv(llvm::CallingConv::X86_StdCall
);
794 llvm::Function
*getAddrOfCXXCtorClosure(const CXXConstructorDecl
*CD
,
797 llvm::Constant
*getCatchableType(QualType T
,
798 uint32_t NVOffset
= 0,
799 int32_t VBPtrOffset
= -1,
800 uint32_t VBIndex
= 0);
802 llvm::GlobalVariable
*getCatchableTypeArray(QualType T
);
804 llvm::GlobalVariable
*getThrowInfo(QualType T
) override
;
806 std::pair
<llvm::Value
*, const CXXRecordDecl
*>
807 LoadVTablePtr(CodeGenFunction
&CGF
, Address This
,
808 const CXXRecordDecl
*RD
) override
;
811 isPermittedToBeHomogeneousAggregate(const CXXRecordDecl
*RD
) const override
;
814 typedef std::pair
<const CXXRecordDecl
*, CharUnits
> VFTableIdTy
;
815 typedef llvm::DenseMap
<VFTableIdTy
, llvm::GlobalVariable
*> VTablesMapTy
;
816 typedef llvm::DenseMap
<VFTableIdTy
, llvm::GlobalValue
*> VFTablesMapTy
;
817 /// All the vftables that have been referenced.
818 VFTablesMapTy VFTablesMap
;
819 VTablesMapTy VTablesMap
;
821 /// This set holds the record decls we've deferred vtable emission for.
822 llvm::SmallPtrSet
<const CXXRecordDecl
*, 4> DeferredVFTables
;
825 /// All the vbtables which have been referenced.
826 llvm::DenseMap
<const CXXRecordDecl
*, VBTableGlobals
> VBTablesMap
;
828 /// Info on the global variable used to guard initialization of static locals.
829 /// The BitIndex field is only used for externally invisible declarations.
831 GuardInfo() = default;
832 llvm::GlobalVariable
*Guard
= nullptr;
833 unsigned BitIndex
= 0;
836 /// Map from DeclContext to the current guard variable. We assume that the
837 /// AST is visited in source code order.
838 llvm::DenseMap
<const DeclContext
*, GuardInfo
> GuardVariableMap
;
839 llvm::DenseMap
<const DeclContext
*, GuardInfo
> ThreadLocalGuardVariableMap
;
840 llvm::DenseMap
<const DeclContext
*, unsigned> ThreadSafeGuardNumMap
;
842 llvm::DenseMap
<size_t, llvm::StructType
*> TypeDescriptorTypeMap
;
843 llvm::StructType
*BaseClassDescriptorType
;
844 llvm::StructType
*ClassHierarchyDescriptorType
;
845 llvm::StructType
*CompleteObjectLocatorType
;
847 llvm::DenseMap
<QualType
, llvm::GlobalVariable
*> CatchableTypeArrays
;
849 llvm::StructType
*CatchableTypeType
;
850 llvm::DenseMap
<uint32_t, llvm::StructType
*> CatchableTypeArrayTypeMap
;
851 llvm::StructType
*ThrowInfoType
;
856 CGCXXABI::RecordArgABI
857 MicrosoftCXXABI::getRecordArgABI(const CXXRecordDecl
*RD
) const {
858 // Use the default C calling convention rules for things that can be passed in
859 // registers, i.e. non-trivially copyable records or records marked with
861 if (RD
->canPassInRegisters())
864 switch (CGM
.getTarget().getTriple().getArch()) {
866 // FIXME: Implement for other architectures.
869 case llvm::Triple::thumb
:
870 // Pass things indirectly for now because it is simple.
871 // FIXME: This is incompatible with MSVC for arguments with a dtor and no
875 case llvm::Triple::x86
: {
876 // If the argument has *required* alignment greater than four bytes, pass
877 // it indirectly. Prior to MSVC version 19.14, passing overaligned
878 // arguments was not supported and resulted in a compiler error. In 19.14
879 // and later versions, such arguments are now passed indirectly.
880 TypeInfo Info
= getContext().getTypeInfo(RD
->getTypeForDecl());
881 if (Info
.isAlignRequired() && Info
.Align
> 4)
884 // If C++ prohibits us from making a copy, construct the arguments directly
885 // into argument memory.
886 return RAA_DirectInMemory
;
889 case llvm::Triple::x86_64
:
890 case llvm::Triple::aarch64
:
894 llvm_unreachable("invalid enum");
897 void MicrosoftCXXABI::emitVirtualObjectDelete(CodeGenFunction
&CGF
,
898 const CXXDeleteExpr
*DE
,
900 QualType ElementType
,
901 const CXXDestructorDecl
*Dtor
) {
902 // FIXME: Provide a source location here even though there's no
903 // CXXMemberCallExpr for dtor call.
904 bool UseGlobalDelete
= DE
->isGlobalDelete();
905 CXXDtorType DtorType
= UseGlobalDelete
? Dtor_Complete
: Dtor_Deleting
;
906 llvm::Value
*MDThis
= EmitVirtualDestructorCall(CGF
, Dtor
, DtorType
, Ptr
, DE
);
908 CGF
.EmitDeleteCall(DE
->getOperatorDelete(), MDThis
, ElementType
);
911 void MicrosoftCXXABI::emitRethrow(CodeGenFunction
&CGF
, bool isNoReturn
) {
912 llvm::Value
*Args
[] = {
913 llvm::ConstantPointerNull::get(CGM
.Int8PtrTy
),
914 llvm::ConstantPointerNull::get(getThrowInfoType()->getPointerTo())};
915 llvm::FunctionCallee Fn
= getThrowFn();
917 CGF
.EmitNoreturnRuntimeCallOrInvoke(Fn
, Args
);
919 CGF
.EmitRuntimeCallOrInvoke(Fn
, Args
);
922 void MicrosoftCXXABI::emitBeginCatch(CodeGenFunction
&CGF
,
923 const CXXCatchStmt
*S
) {
924 // In the MS ABI, the runtime handles the copy, and the catch handler is
925 // responsible for destruction.
926 VarDecl
*CatchParam
= S
->getExceptionDecl();
927 llvm::BasicBlock
*CatchPadBB
= CGF
.Builder
.GetInsertBlock();
928 llvm::CatchPadInst
*CPI
=
929 cast
<llvm::CatchPadInst
>(CatchPadBB
->getFirstNonPHI());
930 CGF
.CurrentFuncletPad
= CPI
;
932 // If this is a catch-all or the catch parameter is unnamed, we don't need to
933 // emit an alloca to the object.
934 if (!CatchParam
|| !CatchParam
->getDeclName()) {
935 CGF
.EHStack
.pushCleanup
<CatchRetScope
>(NormalCleanup
, CPI
);
939 CodeGenFunction::AutoVarEmission var
= CGF
.EmitAutoVarAlloca(*CatchParam
);
940 CPI
->setArgOperand(2, var
.getObjectAddress(CGF
).getPointer());
941 CGF
.EHStack
.pushCleanup
<CatchRetScope
>(NormalCleanup
, CPI
);
942 CGF
.EmitAutoVarCleanups(var
);
945 /// We need to perform a generic polymorphic operation (like a typeid
946 /// or a cast), which requires an object with a vfptr. Adjust the
947 /// address to point to an object with a vfptr.
948 std::tuple
<Address
, llvm::Value
*, const CXXRecordDecl
*>
949 MicrosoftCXXABI::performBaseAdjustment(CodeGenFunction
&CGF
, Address Value
,
950 QualType SrcRecordTy
) {
951 Value
= Value
.withElementType(CGF
.Int8Ty
);
952 const CXXRecordDecl
*SrcDecl
= SrcRecordTy
->getAsCXXRecordDecl();
953 const ASTContext
&Context
= getContext();
955 // If the class itself has a vfptr, great. This check implicitly
956 // covers non-virtual base subobjects: a class with its own virtual
957 // functions would be a candidate to be a primary base.
958 if (Context
.getASTRecordLayout(SrcDecl
).hasExtendableVFPtr())
959 return std::make_tuple(Value
, llvm::ConstantInt::get(CGF
.Int32Ty
, 0),
962 // Okay, one of the vbases must have a vfptr, or else this isn't
963 // actually a polymorphic class.
964 const CXXRecordDecl
*PolymorphicBase
= nullptr;
965 for (auto &Base
: SrcDecl
->vbases()) {
966 const CXXRecordDecl
*BaseDecl
= Base
.getType()->getAsCXXRecordDecl();
967 if (Context
.getASTRecordLayout(BaseDecl
).hasExtendableVFPtr()) {
968 PolymorphicBase
= BaseDecl
;
972 assert(PolymorphicBase
&& "polymorphic class has no apparent vfptr?");
974 llvm::Value
*Offset
=
975 GetVirtualBaseClassOffset(CGF
, Value
, SrcDecl
, PolymorphicBase
);
976 llvm::Value
*Ptr
= CGF
.Builder
.CreateInBoundsGEP(
977 Value
.getElementType(), Value
.getPointer(), Offset
);
978 CharUnits VBaseAlign
=
979 CGF
.CGM
.getVBaseAlignment(Value
.getAlignment(), SrcDecl
, PolymorphicBase
);
980 return std::make_tuple(Address(Ptr
, CGF
.Int8Ty
, VBaseAlign
), Offset
,
984 bool MicrosoftCXXABI::shouldTypeidBeNullChecked(bool IsDeref
,
985 QualType SrcRecordTy
) {
986 const CXXRecordDecl
*SrcDecl
= SrcRecordTy
->getAsCXXRecordDecl();
988 !getContext().getASTRecordLayout(SrcDecl
).hasExtendableVFPtr();
991 static llvm::CallBase
*emitRTtypeidCall(CodeGenFunction
&CGF
,
992 llvm::Value
*Argument
) {
993 llvm::Type
*ArgTypes
[] = {CGF
.Int8PtrTy
};
994 llvm::FunctionType
*FTy
=
995 llvm::FunctionType::get(CGF
.Int8PtrTy
, ArgTypes
, false);
996 llvm::Value
*Args
[] = {Argument
};
997 llvm::FunctionCallee Fn
= CGF
.CGM
.CreateRuntimeFunction(FTy
, "__RTtypeid");
998 return CGF
.EmitRuntimeCallOrInvoke(Fn
, Args
);
1001 void MicrosoftCXXABI::EmitBadTypeidCall(CodeGenFunction
&CGF
) {
1002 llvm::CallBase
*Call
=
1003 emitRTtypeidCall(CGF
, llvm::Constant::getNullValue(CGM
.VoidPtrTy
));
1004 Call
->setDoesNotReturn();
1005 CGF
.Builder
.CreateUnreachable();
1008 llvm::Value
*MicrosoftCXXABI::EmitTypeid(CodeGenFunction
&CGF
,
1009 QualType SrcRecordTy
,
1011 llvm::Type
*StdTypeInfoPtrTy
) {
1012 std::tie(ThisPtr
, std::ignore
, std::ignore
) =
1013 performBaseAdjustment(CGF
, ThisPtr
, SrcRecordTy
);
1014 llvm::CallBase
*Typeid
= emitRTtypeidCall(CGF
, ThisPtr
.getPointer());
1015 return CGF
.Builder
.CreateBitCast(Typeid
, StdTypeInfoPtrTy
);
1018 bool MicrosoftCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr
,
1019 QualType SrcRecordTy
) {
1020 const CXXRecordDecl
*SrcDecl
= SrcRecordTy
->getAsCXXRecordDecl();
1022 !getContext().getASTRecordLayout(SrcDecl
).hasExtendableVFPtr();
1025 llvm::Value
*MicrosoftCXXABI::emitDynamicCastCall(
1026 CodeGenFunction
&CGF
, Address This
, QualType SrcRecordTy
, QualType DestTy
,
1027 QualType DestRecordTy
, llvm::BasicBlock
*CastEnd
) {
1028 llvm::Value
*SrcRTTI
=
1029 CGF
.CGM
.GetAddrOfRTTIDescriptor(SrcRecordTy
.getUnqualifiedType());
1030 llvm::Value
*DestRTTI
=
1031 CGF
.CGM
.GetAddrOfRTTIDescriptor(DestRecordTy
.getUnqualifiedType());
1033 llvm::Value
*Offset
;
1034 std::tie(This
, Offset
, std::ignore
) =
1035 performBaseAdjustment(CGF
, This
, SrcRecordTy
);
1036 llvm::Value
*ThisPtr
= This
.getPointer();
1037 Offset
= CGF
.Builder
.CreateTrunc(Offset
, CGF
.Int32Ty
);
1039 // PVOID __RTDynamicCast(
1043 // PVOID TargetType,
1044 // BOOL isReference)
1045 llvm::Type
*ArgTypes
[] = {CGF
.Int8PtrTy
, CGF
.Int32Ty
, CGF
.Int8PtrTy
,
1046 CGF
.Int8PtrTy
, CGF
.Int32Ty
};
1047 llvm::FunctionCallee Function
= CGF
.CGM
.CreateRuntimeFunction(
1048 llvm::FunctionType::get(CGF
.Int8PtrTy
, ArgTypes
, false),
1050 llvm::Value
*Args
[] = {
1051 ThisPtr
, Offset
, SrcRTTI
, DestRTTI
,
1052 llvm::ConstantInt::get(CGF
.Int32Ty
, DestTy
->isReferenceType())};
1053 return CGF
.EmitRuntimeCallOrInvoke(Function
, Args
);
1056 llvm::Value
*MicrosoftCXXABI::emitDynamicCastToVoid(CodeGenFunction
&CGF
,
1058 QualType SrcRecordTy
) {
1059 std::tie(Value
, std::ignore
, std::ignore
) =
1060 performBaseAdjustment(CGF
, Value
, SrcRecordTy
);
1062 // PVOID __RTCastToVoid(
1064 llvm::Type
*ArgTypes
[] = {CGF
.Int8PtrTy
};
1065 llvm::FunctionCallee Function
= CGF
.CGM
.CreateRuntimeFunction(
1066 llvm::FunctionType::get(CGF
.Int8PtrTy
, ArgTypes
, false),
1068 llvm::Value
*Args
[] = {Value
.getPointer()};
1069 return CGF
.EmitRuntimeCall(Function
, Args
);
1072 bool MicrosoftCXXABI::EmitBadCastCall(CodeGenFunction
&CGF
) {
1076 llvm::Value
*MicrosoftCXXABI::GetVirtualBaseClassOffset(
1077 CodeGenFunction
&CGF
, Address This
, const CXXRecordDecl
*ClassDecl
,
1078 const CXXRecordDecl
*BaseClassDecl
) {
1079 const ASTContext
&Context
= getContext();
1080 int64_t VBPtrChars
=
1081 Context
.getASTRecordLayout(ClassDecl
).getVBPtrOffset().getQuantity();
1082 llvm::Value
*VBPtrOffset
= llvm::ConstantInt::get(CGM
.PtrDiffTy
, VBPtrChars
);
1083 CharUnits IntSize
= Context
.getTypeSizeInChars(Context
.IntTy
);
1084 CharUnits VBTableChars
=
1086 CGM
.getMicrosoftVTableContext().getVBTableIndex(ClassDecl
, BaseClassDecl
);
1087 llvm::Value
*VBTableOffset
=
1088 llvm::ConstantInt::get(CGM
.IntTy
, VBTableChars
.getQuantity());
1090 llvm::Value
*VBPtrToNewBase
=
1091 GetVBaseOffsetFromVBPtr(CGF
, This
, VBPtrOffset
, VBTableOffset
);
1093 CGF
.Builder
.CreateSExtOrBitCast(VBPtrToNewBase
, CGM
.PtrDiffTy
);
1094 return CGF
.Builder
.CreateNSWAdd(VBPtrOffset
, VBPtrToNewBase
);
1097 bool MicrosoftCXXABI::HasThisReturn(GlobalDecl GD
) const {
1098 return isa
<CXXConstructorDecl
>(GD
.getDecl());
1101 static bool isDeletingDtor(GlobalDecl GD
) {
1102 return isa
<CXXDestructorDecl
>(GD
.getDecl()) &&
1103 GD
.getDtorType() == Dtor_Deleting
;
1106 bool MicrosoftCXXABI::hasMostDerivedReturn(GlobalDecl GD
) const {
1107 return isDeletingDtor(GD
);
1110 static bool isTrivialForMSVC(const CXXRecordDecl
*RD
, QualType Ty
,
1111 CodeGenModule
&CGM
) {
1112 // On AArch64, HVAs that can be passed in registers can also be returned
1113 // in registers. (Note this is using the MSVC definition of an HVA; see
1114 // isPermittedToBeHomogeneousAggregate().)
1115 const Type
*Base
= nullptr;
1116 uint64_t NumElts
= 0;
1117 if (CGM
.getTarget().getTriple().isAArch64() &&
1118 CGM
.getTypes().getABIInfo().isHomogeneousAggregate(Ty
, Base
, NumElts
) &&
1119 isa
<VectorType
>(Base
)) {
1123 // We use the C++14 definition of an aggregate, so we also
1125 // No private or protected non static data members.
1127 // No virtual functions
1128 // Additionally, we need to ensure that there is a trivial copy assignment
1129 // operator, a trivial destructor and no user-provided constructors.
1130 if (RD
->hasProtectedFields() || RD
->hasPrivateFields())
1132 if (RD
->getNumBases() > 0)
1134 if (RD
->isPolymorphic())
1136 if (RD
->hasNonTrivialCopyAssignment())
1138 for (const CXXConstructorDecl
*Ctor
: RD
->ctors())
1139 if (Ctor
->isUserProvided())
1141 if (RD
->hasNonTrivialDestructor())
1146 bool MicrosoftCXXABI::classifyReturnType(CGFunctionInfo
&FI
) const {
1147 const CXXRecordDecl
*RD
= FI
.getReturnType()->getAsCXXRecordDecl();
1151 bool isTrivialForABI
= RD
->canPassInRegisters() &&
1152 isTrivialForMSVC(RD
, FI
.getReturnType(), CGM
);
1154 // MSVC always returns structs indirectly from C++ instance methods.
1155 bool isIndirectReturn
= !isTrivialForABI
|| FI
.isInstanceMethod();
1157 if (isIndirectReturn
) {
1158 CharUnits Align
= CGM
.getContext().getTypeAlignInChars(FI
.getReturnType());
1159 FI
.getReturnInfo() = ABIArgInfo::getIndirect(Align
, /*ByVal=*/false);
1161 // MSVC always passes `this` before the `sret` parameter.
1162 FI
.getReturnInfo().setSRetAfterThis(FI
.isInstanceMethod());
1164 // On AArch64, use the `inreg` attribute if the object is considered to not
1165 // be trivially copyable, or if this is an instance method struct return.
1166 FI
.getReturnInfo().setInReg(CGM
.getTarget().getTriple().isAArch64());
1171 // Otherwise, use the C ABI rules.
1176 MicrosoftCXXABI::EmitCtorCompleteObjectHandler(CodeGenFunction
&CGF
,
1177 const CXXRecordDecl
*RD
) {
1178 llvm::Value
*IsMostDerivedClass
= getStructorImplicitParamValue(CGF
);
1179 assert(IsMostDerivedClass
&&
1180 "ctor for a class with virtual bases must have an implicit parameter");
1181 llvm::Value
*IsCompleteObject
=
1182 CGF
.Builder
.CreateIsNotNull(IsMostDerivedClass
, "is_complete_object");
1184 llvm::BasicBlock
*CallVbaseCtorsBB
= CGF
.createBasicBlock("ctor.init_vbases");
1185 llvm::BasicBlock
*SkipVbaseCtorsBB
= CGF
.createBasicBlock("ctor.skip_vbases");
1186 CGF
.Builder
.CreateCondBr(IsCompleteObject
,
1187 CallVbaseCtorsBB
, SkipVbaseCtorsBB
);
1189 CGF
.EmitBlock(CallVbaseCtorsBB
);
1191 // Fill in the vbtable pointers here.
1192 EmitVBPtrStores(CGF
, RD
);
1194 // CGF will put the base ctor calls in this basic block for us later.
1196 return SkipVbaseCtorsBB
;
1200 MicrosoftCXXABI::EmitDtorCompleteObjectHandler(CodeGenFunction
&CGF
) {
1201 llvm::Value
*IsMostDerivedClass
= getStructorImplicitParamValue(CGF
);
1202 assert(IsMostDerivedClass
&&
1203 "ctor for a class with virtual bases must have an implicit parameter");
1204 llvm::Value
*IsCompleteObject
=
1205 CGF
.Builder
.CreateIsNotNull(IsMostDerivedClass
, "is_complete_object");
1207 llvm::BasicBlock
*CallVbaseDtorsBB
= CGF
.createBasicBlock("Dtor.dtor_vbases");
1208 llvm::BasicBlock
*SkipVbaseDtorsBB
= CGF
.createBasicBlock("Dtor.skip_vbases");
1209 CGF
.Builder
.CreateCondBr(IsCompleteObject
,
1210 CallVbaseDtorsBB
, SkipVbaseDtorsBB
);
1212 CGF
.EmitBlock(CallVbaseDtorsBB
);
1213 // CGF will put the base dtor calls in this basic block for us later.
1215 return SkipVbaseDtorsBB
;
1218 void MicrosoftCXXABI::initializeHiddenVirtualInheritanceMembers(
1219 CodeGenFunction
&CGF
, const CXXRecordDecl
*RD
) {
1220 // In most cases, an override for a vbase virtual method can adjust
1221 // the "this" parameter by applying a constant offset.
1222 // However, this is not enough while a constructor or a destructor of some
1223 // class X is being executed if all the following conditions are met:
1224 // - X has virtual bases, (1)
1225 // - X overrides a virtual method M of a vbase Y, (2)
1226 // - X itself is a vbase of the most derived class.
1228 // If (1) and (2) are true, the vtorDisp for vbase Y is a hidden member of X
1229 // which holds the extra amount of "this" adjustment we must do when we use
1230 // the X vftables (i.e. during X ctor or dtor).
1231 // Outside the ctors and dtors, the values of vtorDisps are zero.
1233 const ASTRecordLayout
&Layout
= getContext().getASTRecordLayout(RD
);
1234 typedef ASTRecordLayout::VBaseOffsetsMapTy VBOffsets
;
1235 const VBOffsets
&VBaseMap
= Layout
.getVBaseOffsetsMap();
1236 CGBuilderTy
&Builder
= CGF
.Builder
;
1238 llvm::Value
*Int8This
= nullptr; // Initialize lazily.
1240 for (const CXXBaseSpecifier
&S
: RD
->vbases()) {
1241 const CXXRecordDecl
*VBase
= S
.getType()->getAsCXXRecordDecl();
1242 auto I
= VBaseMap
.find(VBase
);
1243 assert(I
!= VBaseMap
.end());
1244 if (!I
->second
.hasVtorDisp())
1247 llvm::Value
*VBaseOffset
=
1248 GetVirtualBaseClassOffset(CGF
, getThisAddress(CGF
), RD
, VBase
);
1249 uint64_t ConstantVBaseOffset
= I
->second
.VBaseOffset
.getQuantity();
1251 // vtorDisp_for_vbase = vbptr[vbase_idx] - offsetof(RD, vbase).
1252 llvm::Value
*VtorDispValue
= Builder
.CreateSub(
1253 VBaseOffset
, llvm::ConstantInt::get(CGM
.PtrDiffTy
, ConstantVBaseOffset
),
1255 VtorDispValue
= Builder
.CreateTruncOrBitCast(VtorDispValue
, CGF
.Int32Ty
);
1258 Int8This
= getThisValue(CGF
);
1260 llvm::Value
*VtorDispPtr
=
1261 Builder
.CreateInBoundsGEP(CGF
.Int8Ty
, Int8This
, VBaseOffset
);
1262 // vtorDisp is always the 32-bits before the vbase in the class layout.
1263 VtorDispPtr
= Builder
.CreateConstGEP1_32(CGF
.Int8Ty
, VtorDispPtr
, -4);
1265 Builder
.CreateAlignedStore(VtorDispValue
, VtorDispPtr
,
1266 CharUnits::fromQuantity(4));
1270 static bool hasDefaultCXXMethodCC(ASTContext
&Context
,
1271 const CXXMethodDecl
*MD
) {
1272 CallingConv ExpectedCallingConv
= Context
.getDefaultCallingConvention(
1273 /*IsVariadic=*/false, /*IsCXXMethod=*/true);
1274 CallingConv ActualCallingConv
=
1275 MD
->getType()->castAs
<FunctionProtoType
>()->getCallConv();
1276 return ExpectedCallingConv
== ActualCallingConv
;
1279 void MicrosoftCXXABI::EmitCXXConstructors(const CXXConstructorDecl
*D
) {
1280 // There's only one constructor type in this ABI.
1281 CGM
.EmitGlobal(GlobalDecl(D
, Ctor_Complete
));
1283 // Exported default constructors either have a simple call-site where they use
1284 // the typical calling convention and have a single 'this' pointer for an
1285 // argument -or- they get a wrapper function which appropriately thunks to the
1286 // real default constructor. This thunk is the default constructor closure.
1287 if (D
->hasAttr
<DLLExportAttr
>() && D
->isDefaultConstructor() &&
1289 if (!hasDefaultCXXMethodCC(getContext(), D
) || D
->getNumParams() != 0) {
1290 llvm::Function
*Fn
= getAddrOfCXXCtorClosure(D
, Ctor_DefaultClosure
);
1291 Fn
->setLinkage(llvm::GlobalValue::WeakODRLinkage
);
1292 CGM
.setGVProperties(Fn
, D
);
1297 void MicrosoftCXXABI::EmitVBPtrStores(CodeGenFunction
&CGF
,
1298 const CXXRecordDecl
*RD
) {
1299 Address This
= getThisAddress(CGF
);
1300 This
= This
.withElementType(CGM
.Int8Ty
);
1301 const ASTContext
&Context
= getContext();
1302 const ASTRecordLayout
&Layout
= Context
.getASTRecordLayout(RD
);
1304 const VBTableGlobals
&VBGlobals
= enumerateVBTables(RD
);
1305 for (unsigned I
= 0, E
= VBGlobals
.VBTables
->size(); I
!= E
; ++I
) {
1306 const std::unique_ptr
<VPtrInfo
> &VBT
= (*VBGlobals
.VBTables
)[I
];
1307 llvm::GlobalVariable
*GV
= VBGlobals
.Globals
[I
];
1308 const ASTRecordLayout
&SubobjectLayout
=
1309 Context
.getASTRecordLayout(VBT
->IntroducingObject
);
1310 CharUnits Offs
= VBT
->NonVirtualOffset
;
1311 Offs
+= SubobjectLayout
.getVBPtrOffset();
1312 if (VBT
->getVBaseWithVPtr())
1313 Offs
+= Layout
.getVBaseClassOffset(VBT
->getVBaseWithVPtr());
1314 Address VBPtr
= CGF
.Builder
.CreateConstInBoundsByteGEP(This
, Offs
);
1315 llvm::Value
*GVPtr
=
1316 CGF
.Builder
.CreateConstInBoundsGEP2_32(GV
->getValueType(), GV
, 0, 0);
1317 VBPtr
= VBPtr
.withElementType(GVPtr
->getType());
1318 CGF
.Builder
.CreateStore(GVPtr
, VBPtr
);
1322 CGCXXABI::AddedStructorArgCounts
1323 MicrosoftCXXABI::buildStructorSignature(GlobalDecl GD
,
1324 SmallVectorImpl
<CanQualType
> &ArgTys
) {
1325 AddedStructorArgCounts Added
;
1326 // TODO: 'for base' flag
1327 if (isa
<CXXDestructorDecl
>(GD
.getDecl()) &&
1328 GD
.getDtorType() == Dtor_Deleting
) {
1329 // The scalar deleting destructor takes an implicit int parameter.
1330 ArgTys
.push_back(getContext().IntTy
);
1333 auto *CD
= dyn_cast
<CXXConstructorDecl
>(GD
.getDecl());
1337 // All parameters are already in place except is_most_derived, which goes
1338 // after 'this' if it's variadic and last if it's not.
1340 const CXXRecordDecl
*Class
= CD
->getParent();
1341 const FunctionProtoType
*FPT
= CD
->getType()->castAs
<FunctionProtoType
>();
1342 if (Class
->getNumVBases()) {
1343 if (FPT
->isVariadic()) {
1344 ArgTys
.insert(ArgTys
.begin() + 1, getContext().IntTy
);
1347 ArgTys
.push_back(getContext().IntTy
);
1355 void MicrosoftCXXABI::setCXXDestructorDLLStorage(llvm::GlobalValue
*GV
,
1356 const CXXDestructorDecl
*Dtor
,
1357 CXXDtorType DT
) const {
1358 // Deleting destructor variants are never imported or exported. Give them the
1359 // default storage class.
1360 if (DT
== Dtor_Deleting
) {
1361 GV
->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass
);
1363 const NamedDecl
*ND
= Dtor
;
1364 CGM
.setDLLImportDLLExport(GV
, ND
);
1368 llvm::GlobalValue::LinkageTypes
MicrosoftCXXABI::getCXXDestructorLinkage(
1369 GVALinkage Linkage
, const CXXDestructorDecl
*Dtor
, CXXDtorType DT
) const {
1370 // Internal things are always internal, regardless of attributes. After this,
1371 // we know the thunk is externally visible.
1372 if (Linkage
== GVA_Internal
)
1373 return llvm::GlobalValue::InternalLinkage
;
1377 // The base destructor most closely tracks the user-declared constructor, so
1378 // we delegate back to the normal declarator case.
1379 return CGM
.getLLVMLinkageForDeclarator(Dtor
, Linkage
);
1381 // The complete destructor is like an inline function, but it may be
1382 // imported and therefore must be exported as well. This requires changing
1383 // the linkage if a DLL attribute is present.
1384 if (Dtor
->hasAttr
<DLLExportAttr
>())
1385 return llvm::GlobalValue::WeakODRLinkage
;
1386 if (Dtor
->hasAttr
<DLLImportAttr
>())
1387 return llvm::GlobalValue::AvailableExternallyLinkage
;
1388 return llvm::GlobalValue::LinkOnceODRLinkage
;
1390 // Deleting destructors are like inline functions. They have vague linkage
1391 // and are emitted everywhere they are used. They are internal if the class
1393 return llvm::GlobalValue::LinkOnceODRLinkage
;
1395 llvm_unreachable("MS C++ ABI does not support comdat dtors");
1397 llvm_unreachable("invalid dtor type");
1400 void MicrosoftCXXABI::EmitCXXDestructors(const CXXDestructorDecl
*D
) {
1401 // The TU defining a dtor is only guaranteed to emit a base destructor. All
1402 // other destructor variants are delegating thunks.
1403 CGM
.EmitGlobal(GlobalDecl(D
, Dtor_Base
));
1405 // If the class is dllexported, emit the complete (vbase) destructor wherever
1406 // the base dtor is emitted.
1407 // FIXME: To match MSVC, this should only be done when the class is exported
1408 // with -fdllexport-inlines enabled.
1409 if (D
->getParent()->getNumVBases() > 0 && D
->hasAttr
<DLLExportAttr
>())
1410 CGM
.EmitGlobal(GlobalDecl(D
, Dtor_Complete
));
1414 MicrosoftCXXABI::getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD
) {
1415 const CXXMethodDecl
*MD
= cast
<CXXMethodDecl
>(GD
.getDecl());
1417 if (const CXXDestructorDecl
*DD
= dyn_cast
<CXXDestructorDecl
>(MD
)) {
1418 // Complete destructors take a pointer to the complete object as a
1419 // parameter, thus don't need this adjustment.
1420 if (GD
.getDtorType() == Dtor_Complete
)
1423 // There's no Dtor_Base in vftable but it shares the this adjustment with
1424 // the deleting one, so look it up instead.
1425 GD
= GlobalDecl(DD
, Dtor_Deleting
);
1428 MethodVFTableLocation ML
=
1429 CGM
.getMicrosoftVTableContext().getMethodVFTableLocation(GD
);
1430 CharUnits Adjustment
= ML
.VFPtrOffset
;
1432 // Normal virtual instance methods need to adjust from the vfptr that first
1433 // defined the virtual method to the virtual base subobject, but destructors
1434 // do not. The vector deleting destructor thunk applies this adjustment for
1436 if (isa
<CXXDestructorDecl
>(MD
))
1437 Adjustment
= CharUnits::Zero();
1440 const ASTRecordLayout
&DerivedLayout
=
1441 getContext().getASTRecordLayout(MD
->getParent());
1442 Adjustment
+= DerivedLayout
.getVBaseClassOffset(ML
.VBase
);
1448 Address
MicrosoftCXXABI::adjustThisArgumentForVirtualFunctionCall(
1449 CodeGenFunction
&CGF
, GlobalDecl GD
, Address This
,
1452 // If the call of a virtual function is not virtual, we just have to
1453 // compensate for the adjustment the virtual function does in its prologue.
1454 CharUnits Adjustment
= getVirtualFunctionPrologueThisAdjustment(GD
);
1455 if (Adjustment
.isZero())
1458 This
= This
.withElementType(CGF
.Int8Ty
);
1459 assert(Adjustment
.isPositive());
1460 return CGF
.Builder
.CreateConstByteGEP(This
, Adjustment
);
1463 const CXXMethodDecl
*MD
= cast
<CXXMethodDecl
>(GD
.getDecl());
1465 GlobalDecl LookupGD
= GD
;
1466 if (const CXXDestructorDecl
*DD
= dyn_cast
<CXXDestructorDecl
>(MD
)) {
1467 // Complete dtors take a pointer to the complete object,
1468 // thus don't need adjustment.
1469 if (GD
.getDtorType() == Dtor_Complete
)
1472 // There's only Dtor_Deleting in vftable but it shares the this adjustment
1473 // with the base one, so look up the deleting one instead.
1474 LookupGD
= GlobalDecl(DD
, Dtor_Deleting
);
1476 MethodVFTableLocation ML
=
1477 CGM
.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD
);
1479 CharUnits StaticOffset
= ML
.VFPtrOffset
;
1481 // Base destructors expect 'this' to point to the beginning of the base
1482 // subobject, not the first vfptr that happens to contain the virtual dtor.
1483 // However, we still need to apply the virtual base adjustment.
1484 if (isa
<CXXDestructorDecl
>(MD
) && GD
.getDtorType() == Dtor_Base
)
1485 StaticOffset
= CharUnits::Zero();
1487 Address Result
= This
;
1489 Result
= Result
.withElementType(CGF
.Int8Ty
);
1491 const CXXRecordDecl
*Derived
= MD
->getParent();
1492 const CXXRecordDecl
*VBase
= ML
.VBase
;
1493 llvm::Value
*VBaseOffset
=
1494 GetVirtualBaseClassOffset(CGF
, Result
, Derived
, VBase
);
1495 llvm::Value
*VBasePtr
= CGF
.Builder
.CreateInBoundsGEP(
1496 Result
.getElementType(), Result
.getPointer(), VBaseOffset
);
1497 CharUnits VBaseAlign
=
1498 CGF
.CGM
.getVBaseAlignment(Result
.getAlignment(), Derived
, VBase
);
1499 Result
= Address(VBasePtr
, CGF
.Int8Ty
, VBaseAlign
);
1501 if (!StaticOffset
.isZero()) {
1502 assert(StaticOffset
.isPositive());
1503 Result
= Result
.withElementType(CGF
.Int8Ty
);
1505 // Non-virtual adjustment might result in a pointer outside the allocated
1506 // object, e.g. if the final overrider class is laid out after the virtual
1507 // base that declares a method in the most derived class.
1508 // FIXME: Update the code that emits this adjustment in thunks prologues.
1509 Result
= CGF
.Builder
.CreateConstByteGEP(Result
, StaticOffset
);
1511 Result
= CGF
.Builder
.CreateConstInBoundsByteGEP(Result
, StaticOffset
);
1517 void MicrosoftCXXABI::addImplicitStructorParams(CodeGenFunction
&CGF
,
1519 FunctionArgList
&Params
) {
1520 ASTContext
&Context
= getContext();
1521 const CXXMethodDecl
*MD
= cast
<CXXMethodDecl
>(CGF
.CurGD
.getDecl());
1522 assert(isa
<CXXConstructorDecl
>(MD
) || isa
<CXXDestructorDecl
>(MD
));
1523 if (isa
<CXXConstructorDecl
>(MD
) && MD
->getParent()->getNumVBases()) {
1524 auto *IsMostDerived
= ImplicitParamDecl::Create(
1525 Context
, /*DC=*/nullptr, CGF
.CurGD
.getDecl()->getLocation(),
1526 &Context
.Idents
.get("is_most_derived"), Context
.IntTy
,
1527 ImplicitParamDecl::Other
);
1528 // The 'most_derived' parameter goes second if the ctor is variadic and last
1529 // if it's not. Dtors can't be variadic.
1530 const FunctionProtoType
*FPT
= MD
->getType()->castAs
<FunctionProtoType
>();
1531 if (FPT
->isVariadic())
1532 Params
.insert(Params
.begin() + 1, IsMostDerived
);
1534 Params
.push_back(IsMostDerived
);
1535 getStructorImplicitParamDecl(CGF
) = IsMostDerived
;
1536 } else if (isDeletingDtor(CGF
.CurGD
)) {
1537 auto *ShouldDelete
= ImplicitParamDecl::Create(
1538 Context
, /*DC=*/nullptr, CGF
.CurGD
.getDecl()->getLocation(),
1539 &Context
.Idents
.get("should_call_delete"), Context
.IntTy
,
1540 ImplicitParamDecl::Other
);
1541 Params
.push_back(ShouldDelete
);
1542 getStructorImplicitParamDecl(CGF
) = ShouldDelete
;
1546 void MicrosoftCXXABI::EmitInstanceFunctionProlog(CodeGenFunction
&CGF
) {
1547 // Naked functions have no prolog.
1548 if (CGF
.CurFuncDecl
&& CGF
.CurFuncDecl
->hasAttr
<NakedAttr
>())
1551 // Overridden virtual methods of non-primary bases need to adjust the incoming
1552 // 'this' pointer in the prologue. In this hierarchy, C::b will subtract
1553 // sizeof(void*) to adjust from B* to C*:
1554 // struct A { virtual void a(); };
1555 // struct B { virtual void b(); };
1556 // struct C : A, B { virtual void b(); };
1558 // Leave the value stored in the 'this' alloca unadjusted, so that the
1559 // debugger sees the unadjusted value. Microsoft debuggers require this, and
1560 // will apply the ThisAdjustment in the method type information.
1561 // FIXME: Do something better for DWARF debuggers, which won't expect this,
1562 // without making our codegen depend on debug info settings.
1563 llvm::Value
*This
= loadIncomingCXXThis(CGF
);
1564 const CXXMethodDecl
*MD
= cast
<CXXMethodDecl
>(CGF
.CurGD
.getDecl());
1565 if (!CGF
.CurFuncIsThunk
&& MD
->isVirtual()) {
1566 CharUnits Adjustment
= getVirtualFunctionPrologueThisAdjustment(CGF
.CurGD
);
1567 if (!Adjustment
.isZero()) {
1568 assert(Adjustment
.isPositive());
1569 This
= CGF
.Builder
.CreateConstInBoundsGEP1_32(CGF
.Int8Ty
, This
,
1570 -Adjustment
.getQuantity());
1573 setCXXABIThisValue(CGF
, This
);
1575 // If this is a function that the ABI specifies returns 'this', initialize
1576 // the return slot to 'this' at the start of the function.
1578 // Unlike the setting of return types, this is done within the ABI
1579 // implementation instead of by clients of CGCXXABI because:
1580 // 1) getThisValue is currently protected
1581 // 2) in theory, an ABI could implement 'this' returns some other way;
1582 // HasThisReturn only specifies a contract, not the implementation
1583 if (HasThisReturn(CGF
.CurGD
) || hasMostDerivedReturn(CGF
.CurGD
))
1584 CGF
.Builder
.CreateStore(getThisValue(CGF
), CGF
.ReturnValue
);
1586 if (isa
<CXXConstructorDecl
>(MD
) && MD
->getParent()->getNumVBases()) {
1587 assert(getStructorImplicitParamDecl(CGF
) &&
1588 "no implicit parameter for a constructor with virtual bases?");
1589 getStructorImplicitParamValue(CGF
)
1590 = CGF
.Builder
.CreateLoad(
1591 CGF
.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF
)),
1595 if (isDeletingDtor(CGF
.CurGD
)) {
1596 assert(getStructorImplicitParamDecl(CGF
) &&
1597 "no implicit parameter for a deleting destructor?");
1598 getStructorImplicitParamValue(CGF
)
1599 = CGF
.Builder
.CreateLoad(
1600 CGF
.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF
)),
1601 "should_call_delete");
1605 CGCXXABI::AddedStructorArgs
MicrosoftCXXABI::getImplicitConstructorArgs(
1606 CodeGenFunction
&CGF
, const CXXConstructorDecl
*D
, CXXCtorType Type
,
1607 bool ForVirtualBase
, bool Delegating
) {
1608 assert(Type
== Ctor_Complete
|| Type
== Ctor_Base
);
1610 // Check if we need a 'most_derived' parameter.
1611 if (!D
->getParent()->getNumVBases())
1612 return AddedStructorArgs
{};
1614 // Add the 'most_derived' argument second if we are variadic or last if not.
1615 const FunctionProtoType
*FPT
= D
->getType()->castAs
<FunctionProtoType
>();
1616 llvm::Value
*MostDerivedArg
;
1618 MostDerivedArg
= getStructorImplicitParamValue(CGF
);
1620 MostDerivedArg
= llvm::ConstantInt::get(CGM
.Int32Ty
, Type
== Ctor_Complete
);
1622 if (FPT
->isVariadic()) {
1623 return AddedStructorArgs::prefix({{MostDerivedArg
, getContext().IntTy
}});
1625 return AddedStructorArgs::suffix({{MostDerivedArg
, getContext().IntTy
}});
1628 llvm::Value
*MicrosoftCXXABI::getCXXDestructorImplicitParam(
1629 CodeGenFunction
&CGF
, const CXXDestructorDecl
*DD
, CXXDtorType Type
,
1630 bool ForVirtualBase
, bool Delegating
) {
1634 void MicrosoftCXXABI::EmitDestructorCall(CodeGenFunction
&CGF
,
1635 const CXXDestructorDecl
*DD
,
1636 CXXDtorType Type
, bool ForVirtualBase
,
1637 bool Delegating
, Address This
,
1639 // Use the base destructor variant in place of the complete destructor variant
1640 // if the class has no virtual bases. This effectively implements some of the
1641 // -mconstructor-aliases optimization, but as part of the MS C++ ABI.
1642 if (Type
== Dtor_Complete
&& DD
->getParent()->getNumVBases() == 0)
1645 GlobalDecl
GD(DD
, Type
);
1646 CGCallee Callee
= CGCallee::forDirect(CGM
.getAddrOfCXXStructor(GD
), GD
);
1648 if (DD
->isVirtual()) {
1649 assert(Type
!= CXXDtorType::Dtor_Deleting
&&
1650 "The deleting destructor should only be called via a virtual call");
1651 This
= adjustThisArgumentForVirtualFunctionCall(CGF
, GlobalDecl(DD
, Type
),
1655 llvm::BasicBlock
*BaseDtorEndBB
= nullptr;
1656 if (ForVirtualBase
&& isa
<CXXConstructorDecl
>(CGF
.CurCodeDecl
)) {
1657 BaseDtorEndBB
= EmitDtorCompleteObjectHandler(CGF
);
1660 llvm::Value
*Implicit
=
1661 getCXXDestructorImplicitParam(CGF
, DD
, Type
, ForVirtualBase
,
1662 Delegating
); // = nullptr
1663 CGF
.EmitCXXDestructorCall(GD
, Callee
, This
.getPointer(), ThisTy
,
1664 /*ImplicitParam=*/Implicit
,
1665 /*ImplicitParamTy=*/QualType(), nullptr);
1666 if (BaseDtorEndBB
) {
1667 // Complete object handler should continue to be the remaining
1668 CGF
.Builder
.CreateBr(BaseDtorEndBB
);
1669 CGF
.EmitBlock(BaseDtorEndBB
);
1673 void MicrosoftCXXABI::emitVTableTypeMetadata(const VPtrInfo
&Info
,
1674 const CXXRecordDecl
*RD
,
1675 llvm::GlobalVariable
*VTable
) {
1676 if (!CGM
.getCodeGenOpts().LTOUnit
)
1679 // TODO: Should VirtualFunctionElimination also be supported here?
1680 // See similar handling in CodeGenModule::EmitVTableTypeMetadata.
1681 if (CGM
.getCodeGenOpts().WholeProgramVTables
) {
1682 llvm::DenseSet
<const CXXRecordDecl
*> Visited
;
1683 llvm::GlobalObject::VCallVisibility TypeVis
=
1684 CGM
.GetVCallVisibilityLevel(RD
, Visited
);
1685 if (TypeVis
!= llvm::GlobalObject::VCallVisibilityPublic
)
1686 VTable
->setVCallVisibilityMetadata(TypeVis
);
1689 // The location of the first virtual function pointer in the virtual table,
1690 // aka the "address point" on Itanium. This is at offset 0 if RTTI is
1691 // disabled, or sizeof(void*) if RTTI is enabled.
1692 CharUnits AddressPoint
=
1693 getContext().getLangOpts().RTTIData
1694 ? getContext().toCharUnitsFromBits(
1695 getContext().getTargetInfo().getPointerWidth(LangAS::Default
))
1696 : CharUnits::Zero();
1698 if (Info
.PathToIntroducingObject
.empty()) {
1699 CGM
.AddVTableTypeMetadata(VTable
, AddressPoint
, RD
);
1703 // Add a bitset entry for the least derived base belonging to this vftable.
1704 CGM
.AddVTableTypeMetadata(VTable
, AddressPoint
,
1705 Info
.PathToIntroducingObject
.back());
1707 // Add a bitset entry for each derived class that is laid out at the same
1708 // offset as the least derived base.
1709 for (unsigned I
= Info
.PathToIntroducingObject
.size() - 1; I
!= 0; --I
) {
1710 const CXXRecordDecl
*DerivedRD
= Info
.PathToIntroducingObject
[I
- 1];
1711 const CXXRecordDecl
*BaseRD
= Info
.PathToIntroducingObject
[I
];
1713 const ASTRecordLayout
&Layout
=
1714 getContext().getASTRecordLayout(DerivedRD
);
1716 auto VBI
= Layout
.getVBaseOffsetsMap().find(BaseRD
);
1717 if (VBI
== Layout
.getVBaseOffsetsMap().end())
1718 Offset
= Layout
.getBaseClassOffset(BaseRD
);
1720 Offset
= VBI
->second
.VBaseOffset
;
1721 if (!Offset
.isZero())
1723 CGM
.AddVTableTypeMetadata(VTable
, AddressPoint
, DerivedRD
);
1726 // Finally do the same for the most derived class.
1727 if (Info
.FullOffsetInMDC
.isZero())
1728 CGM
.AddVTableTypeMetadata(VTable
, AddressPoint
, RD
);
1731 void MicrosoftCXXABI::emitVTableDefinitions(CodeGenVTables
&CGVT
,
1732 const CXXRecordDecl
*RD
) {
1733 MicrosoftVTableContext
&VFTContext
= CGM
.getMicrosoftVTableContext();
1734 const VPtrInfoVector
&VFPtrs
= VFTContext
.getVFPtrOffsets(RD
);
1736 for (const std::unique_ptr
<VPtrInfo
>& Info
: VFPtrs
) {
1737 llvm::GlobalVariable
*VTable
= getAddrOfVTable(RD
, Info
->FullOffsetInMDC
);
1738 if (VTable
->hasInitializer())
1741 const VTableLayout
&VTLayout
=
1742 VFTContext
.getVFTableLayout(RD
, Info
->FullOffsetInMDC
);
1744 llvm::Constant
*RTTI
= nullptr;
1745 if (any_of(VTLayout
.vtable_components(),
1746 [](const VTableComponent
&VTC
) { return VTC
.isRTTIKind(); }))
1747 RTTI
= getMSCompleteObjectLocator(RD
, *Info
);
1749 ConstantInitBuilder
builder(CGM
);
1750 auto components
= builder
.beginStruct();
1751 CGVT
.createVTableInitializer(components
, VTLayout
, RTTI
,
1752 VTable
->hasLocalLinkage());
1753 components
.finishAndSetAsInitializer(VTable
);
1755 emitVTableTypeMetadata(*Info
, RD
, VTable
);
1759 bool MicrosoftCXXABI::isVirtualOffsetNeededForVTableField(
1760 CodeGenFunction
&CGF
, CodeGenFunction::VPtr Vptr
) {
1761 return Vptr
.NearestVBase
!= nullptr;
1764 llvm::Value
*MicrosoftCXXABI::getVTableAddressPointInStructor(
1765 CodeGenFunction
&CGF
, const CXXRecordDecl
*VTableClass
, BaseSubobject Base
,
1766 const CXXRecordDecl
*NearestVBase
) {
1767 llvm::Constant
*VTableAddressPoint
= getVTableAddressPoint(Base
, VTableClass
);
1768 if (!VTableAddressPoint
) {
1769 assert(Base
.getBase()->getNumVBases() &&
1770 !getContext().getASTRecordLayout(Base
.getBase()).hasOwnVFPtr());
1772 return VTableAddressPoint
;
1775 static void mangleVFTableName(MicrosoftMangleContext
&MangleContext
,
1776 const CXXRecordDecl
*RD
, const VPtrInfo
&VFPtr
,
1777 SmallString
<256> &Name
) {
1778 llvm::raw_svector_ostream
Out(Name
);
1779 MangleContext
.mangleCXXVFTable(RD
, VFPtr
.MangledPath
, Out
);
1783 MicrosoftCXXABI::getVTableAddressPoint(BaseSubobject Base
,
1784 const CXXRecordDecl
*VTableClass
) {
1785 (void)getAddrOfVTable(VTableClass
, Base
.getBaseOffset());
1786 VFTableIdTy
ID(VTableClass
, Base
.getBaseOffset());
1787 return VFTablesMap
[ID
];
1790 llvm::Constant
*MicrosoftCXXABI::getVTableAddressPointForConstExpr(
1791 BaseSubobject Base
, const CXXRecordDecl
*VTableClass
) {
1792 llvm::Constant
*VFTable
= getVTableAddressPoint(Base
, VTableClass
);
1793 assert(VFTable
&& "Couldn't find a vftable for the given base?");
1797 llvm::GlobalVariable
*MicrosoftCXXABI::getAddrOfVTable(const CXXRecordDecl
*RD
,
1798 CharUnits VPtrOffset
) {
1799 // getAddrOfVTable may return 0 if asked to get an address of a vtable which
1800 // shouldn't be used in the given record type. We want to cache this result in
1801 // VFTablesMap, thus a simple zero check is not sufficient.
1803 VFTableIdTy
ID(RD
, VPtrOffset
);
1804 VTablesMapTy::iterator I
;
1806 std::tie(I
, Inserted
) = VTablesMap
.insert(std::make_pair(ID
, nullptr));
1810 llvm::GlobalVariable
*&VTable
= I
->second
;
1812 MicrosoftVTableContext
&VTContext
= CGM
.getMicrosoftVTableContext();
1813 const VPtrInfoVector
&VFPtrs
= VTContext
.getVFPtrOffsets(RD
);
1815 if (DeferredVFTables
.insert(RD
).second
) {
1816 // We haven't processed this record type before.
1817 // Queue up this vtable for possible deferred emission.
1818 CGM
.addDeferredVTable(RD
);
1821 // Create all the vftables at once in order to make sure each vftable has
1822 // a unique mangled name.
1823 llvm::StringSet
<> ObservedMangledNames
;
1824 for (size_t J
= 0, F
= VFPtrs
.size(); J
!= F
; ++J
) {
1825 SmallString
<256> Name
;
1826 mangleVFTableName(getMangleContext(), RD
, *VFPtrs
[J
], Name
);
1827 if (!ObservedMangledNames
.insert(Name
.str()).second
)
1828 llvm_unreachable("Already saw this mangling before?");
1833 const std::unique_ptr
<VPtrInfo
> *VFPtrI
=
1834 llvm::find_if(VFPtrs
, [&](const std::unique_ptr
<VPtrInfo
> &VPI
) {
1835 return VPI
->FullOffsetInMDC
== VPtrOffset
;
1837 if (VFPtrI
== VFPtrs
.end()) {
1838 VFTablesMap
[ID
] = nullptr;
1841 const std::unique_ptr
<VPtrInfo
> &VFPtr
= *VFPtrI
;
1843 SmallString
<256> VFTableName
;
1844 mangleVFTableName(getMangleContext(), RD
, *VFPtr
, VFTableName
);
1846 // Classes marked __declspec(dllimport) need vftables generated on the
1847 // import-side in order to support features like constexpr. No other
1848 // translation unit relies on the emission of the local vftable, translation
1849 // units are expected to generate them as needed.
1851 // Because of this unique behavior, we maintain this logic here instead of
1852 // getVTableLinkage.
1853 llvm::GlobalValue::LinkageTypes VFTableLinkage
=
1854 RD
->hasAttr
<DLLImportAttr
>() ? llvm::GlobalValue::LinkOnceODRLinkage
1855 : CGM
.getVTableLinkage(RD
);
1856 bool VFTableComesFromAnotherTU
=
1857 llvm::GlobalValue::isAvailableExternallyLinkage(VFTableLinkage
) ||
1858 llvm::GlobalValue::isExternalLinkage(VFTableLinkage
);
1859 bool VTableAliasIsRequred
=
1860 !VFTableComesFromAnotherTU
&& getContext().getLangOpts().RTTIData
;
1862 if (llvm::GlobalValue
*VFTable
=
1863 CGM
.getModule().getNamedGlobal(VFTableName
)) {
1864 VFTablesMap
[ID
] = VFTable
;
1865 VTable
= VTableAliasIsRequred
1866 ? cast
<llvm::GlobalVariable
>(
1867 cast
<llvm::GlobalAlias
>(VFTable
)->getAliaseeObject())
1868 : cast
<llvm::GlobalVariable
>(VFTable
);
1872 const VTableLayout
&VTLayout
=
1873 VTContext
.getVFTableLayout(RD
, VFPtr
->FullOffsetInMDC
);
1874 llvm::GlobalValue::LinkageTypes VTableLinkage
=
1875 VTableAliasIsRequred
? llvm::GlobalValue::PrivateLinkage
: VFTableLinkage
;
1877 StringRef VTableName
= VTableAliasIsRequred
? StringRef() : VFTableName
.str();
1879 llvm::Type
*VTableType
= CGM
.getVTables().getVTableType(VTLayout
);
1881 // Create a backing variable for the contents of VTable. The VTable may
1882 // or may not include space for a pointer to RTTI data.
1883 llvm::GlobalValue
*VFTable
;
1884 VTable
= new llvm::GlobalVariable(CGM
.getModule(), VTableType
,
1885 /*isConstant=*/true, VTableLinkage
,
1886 /*Initializer=*/nullptr, VTableName
);
1887 VTable
->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global
);
1889 llvm::Comdat
*C
= nullptr;
1890 if (!VFTableComesFromAnotherTU
&&
1891 (llvm::GlobalValue::isWeakForLinker(VFTableLinkage
) ||
1892 (llvm::GlobalValue::isLocalLinkage(VFTableLinkage
) &&
1893 VTableAliasIsRequred
)))
1894 C
= CGM
.getModule().getOrInsertComdat(VFTableName
.str());
1896 // Only insert a pointer into the VFTable for RTTI data if we are not
1897 // importing it. We never reference the RTTI data directly so there is no
1898 // need to make room for it.
1899 if (VTableAliasIsRequred
) {
1900 llvm::Value
*GEPIndices
[] = {llvm::ConstantInt::get(CGM
.Int32Ty
, 0),
1901 llvm::ConstantInt::get(CGM
.Int32Ty
, 0),
1902 llvm::ConstantInt::get(CGM
.Int32Ty
, 1)};
1903 // Create a GEP which points just after the first entry in the VFTable,
1904 // this should be the location of the first virtual method.
1905 llvm::Constant
*VTableGEP
= llvm::ConstantExpr::getInBoundsGetElementPtr(
1906 VTable
->getValueType(), VTable
, GEPIndices
);
1907 if (llvm::GlobalValue::isWeakForLinker(VFTableLinkage
)) {
1908 VFTableLinkage
= llvm::GlobalValue::ExternalLinkage
;
1910 C
->setSelectionKind(llvm::Comdat::Largest
);
1912 VFTable
= llvm::GlobalAlias::create(CGM
.Int8PtrTy
,
1913 /*AddressSpace=*/0, VFTableLinkage
,
1914 VFTableName
.str(), VTableGEP
,
1916 VFTable
->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global
);
1918 // We don't need a GlobalAlias to be a symbol for the VTable if we won't
1919 // be referencing any RTTI data.
1920 // The GlobalVariable will end up being an appropriate definition of the
1925 VTable
->setComdat(C
);
1927 if (RD
->hasAttr
<DLLExportAttr
>())
1928 VFTable
->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass
);
1930 VFTablesMap
[ID
] = VFTable
;
1934 CGCallee
MicrosoftCXXABI::getVirtualFunctionPointer(CodeGenFunction
&CGF
,
1938 SourceLocation Loc
) {
1939 CGBuilderTy
&Builder
= CGF
.Builder
;
1941 Ty
= Ty
->getPointerTo();
1943 adjustThisArgumentForVirtualFunctionCall(CGF
, GD
, This
, true);
1945 auto *MethodDecl
= cast
<CXXMethodDecl
>(GD
.getDecl());
1946 llvm::Value
*VTable
= CGF
.GetVTablePtr(VPtr
, Ty
->getPointerTo(),
1947 MethodDecl
->getParent());
1949 MicrosoftVTableContext
&VFTContext
= CGM
.getMicrosoftVTableContext();
1950 MethodVFTableLocation ML
= VFTContext
.getMethodVFTableLocation(GD
);
1952 // Compute the identity of the most derived class whose virtual table is
1953 // located at the MethodVFTableLocation ML.
1954 auto getObjectWithVPtr
= [&] {
1955 return llvm::find_if(VFTContext
.getVFPtrOffsets(
1956 ML
.VBase
? ML
.VBase
: MethodDecl
->getParent()),
1957 [&](const std::unique_ptr
<VPtrInfo
> &Info
) {
1958 return Info
->FullOffsetInMDC
== ML
.VFPtrOffset
;
1965 if (CGF
.ShouldEmitVTableTypeCheckedLoad(MethodDecl
->getParent())) {
1966 VFunc
= CGF
.EmitVTableTypeCheckedLoad(
1967 getObjectWithVPtr(), VTable
, Ty
,
1969 CGM
.getContext().getTargetInfo().getPointerWidth(LangAS::Default
) /
1972 if (CGM
.getCodeGenOpts().PrepareForLTO
)
1973 CGF
.EmitTypeMetadataCodeForVCall(getObjectWithVPtr(), VTable
, Loc
);
1975 llvm::Value
*VFuncPtr
=
1976 Builder
.CreateConstInBoundsGEP1_64(Ty
, VTable
, ML
.Index
, "vfn");
1977 VFunc
= Builder
.CreateAlignedLoad(Ty
, VFuncPtr
, CGF
.getPointerAlign());
1980 CGCallee
Callee(GD
, VFunc
);
1984 llvm::Value
*MicrosoftCXXABI::EmitVirtualDestructorCall(
1985 CodeGenFunction
&CGF
, const CXXDestructorDecl
*Dtor
, CXXDtorType DtorType
,
1986 Address This
, DeleteOrMemberCallExpr E
) {
1987 auto *CE
= E
.dyn_cast
<const CXXMemberCallExpr
*>();
1988 auto *D
= E
.dyn_cast
<const CXXDeleteExpr
*>();
1989 assert((CE
!= nullptr) ^ (D
!= nullptr));
1990 assert(CE
== nullptr || CE
->arg_begin() == CE
->arg_end());
1991 assert(DtorType
== Dtor_Deleting
|| DtorType
== Dtor_Complete
);
1993 // We have only one destructor in the vftable but can get both behaviors
1994 // by passing an implicit int parameter.
1995 GlobalDecl
GD(Dtor
, Dtor_Deleting
);
1996 const CGFunctionInfo
*FInfo
=
1997 &CGM
.getTypes().arrangeCXXStructorDeclaration(GD
);
1998 llvm::FunctionType
*Ty
= CGF
.CGM
.getTypes().GetFunctionType(*FInfo
);
1999 CGCallee Callee
= CGCallee::forVirtual(CE
, GD
, This
, Ty
);
2001 ASTContext
&Context
= getContext();
2002 llvm::Value
*ImplicitParam
= llvm::ConstantInt::get(
2003 llvm::IntegerType::getInt32Ty(CGF
.getLLVMContext()),
2004 DtorType
== Dtor_Deleting
);
2008 ThisTy
= CE
->getObjectType();
2010 ThisTy
= D
->getDestroyedType();
2013 This
= adjustThisArgumentForVirtualFunctionCall(CGF
, GD
, This
, true);
2014 RValue RV
= CGF
.EmitCXXDestructorCall(GD
, Callee
, This
.getPointer(), ThisTy
,
2015 ImplicitParam
, Context
.IntTy
, CE
);
2016 return RV
.getScalarVal();
2019 const VBTableGlobals
&
2020 MicrosoftCXXABI::enumerateVBTables(const CXXRecordDecl
*RD
) {
2021 // At this layer, we can key the cache off of a single class, which is much
2022 // easier than caching each vbtable individually.
2023 llvm::DenseMap
<const CXXRecordDecl
*, VBTableGlobals
>::iterator Entry
;
2025 std::tie(Entry
, Added
) =
2026 VBTablesMap
.insert(std::make_pair(RD
, VBTableGlobals()));
2027 VBTableGlobals
&VBGlobals
= Entry
->second
;
2031 MicrosoftVTableContext
&Context
= CGM
.getMicrosoftVTableContext();
2032 VBGlobals
.VBTables
= &Context
.enumerateVBTables(RD
);
2034 // Cache the globals for all vbtables so we don't have to recompute the
2036 llvm::GlobalVariable::LinkageTypes Linkage
= CGM
.getVTableLinkage(RD
);
2037 for (VPtrInfoVector::const_iterator I
= VBGlobals
.VBTables
->begin(),
2038 E
= VBGlobals
.VBTables
->end();
2040 VBGlobals
.Globals
.push_back(getAddrOfVBTable(**I
, RD
, Linkage
));
2047 MicrosoftCXXABI::EmitVirtualMemPtrThunk(const CXXMethodDecl
*MD
,
2048 const MethodVFTableLocation
&ML
) {
2049 assert(!isa
<CXXConstructorDecl
>(MD
) && !isa
<CXXDestructorDecl
>(MD
) &&
2050 "can't form pointers to ctors or virtual dtors");
2052 // Calculate the mangled name.
2053 SmallString
<256> ThunkName
;
2054 llvm::raw_svector_ostream
Out(ThunkName
);
2055 getMangleContext().mangleVirtualMemPtrThunk(MD
, ML
, Out
);
2057 // If the thunk has been generated previously, just return it.
2058 if (llvm::GlobalValue
*GV
= CGM
.getModule().getNamedValue(ThunkName
))
2059 return cast
<llvm::Function
>(GV
);
2061 // Create the llvm::Function.
2062 const CGFunctionInfo
&FnInfo
=
2063 CGM
.getTypes().arrangeUnprototypedMustTailThunk(MD
);
2064 llvm::FunctionType
*ThunkTy
= CGM
.getTypes().GetFunctionType(FnInfo
);
2065 llvm::Function
*ThunkFn
=
2066 llvm::Function::Create(ThunkTy
, llvm::Function::ExternalLinkage
,
2067 ThunkName
.str(), &CGM
.getModule());
2068 assert(ThunkFn
->getName() == ThunkName
&& "name was uniqued!");
2070 ThunkFn
->setLinkage(MD
->isExternallyVisible()
2071 ? llvm::GlobalValue::LinkOnceODRLinkage
2072 : llvm::GlobalValue::InternalLinkage
);
2073 if (MD
->isExternallyVisible())
2074 ThunkFn
->setComdat(CGM
.getModule().getOrInsertComdat(ThunkFn
->getName()));
2076 CGM
.SetLLVMFunctionAttributes(MD
, FnInfo
, ThunkFn
, /*IsThunk=*/false);
2077 CGM
.SetLLVMFunctionAttributesForDefinition(MD
, ThunkFn
);
2079 // Add the "thunk" attribute so that LLVM knows that the return type is
2080 // meaningless. These thunks can be used to call functions with differing
2081 // return types, and the caller is required to cast the prototype
2082 // appropriately to extract the correct value.
2083 ThunkFn
->addFnAttr("thunk");
2085 // These thunks can be compared, so they are not unnamed.
2086 ThunkFn
->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::None
);
2089 CodeGenFunction
CGF(CGM
);
2090 CGF
.CurGD
= GlobalDecl(MD
);
2091 CGF
.CurFuncIsThunk
= true;
2093 // Build FunctionArgs, but only include the implicit 'this' parameter
2095 FunctionArgList FunctionArgs
;
2096 buildThisParam(CGF
, FunctionArgs
);
2098 // Start defining the function.
2099 CGF
.StartFunction(GlobalDecl(), FnInfo
.getReturnType(), ThunkFn
, FnInfo
,
2100 FunctionArgs
, MD
->getLocation(), SourceLocation());
2102 ApplyDebugLocation
AL(CGF
, MD
->getLocation());
2103 setCXXABIThisValue(CGF
, loadIncomingCXXThis(CGF
));
2105 // Load the vfptr and then callee from the vftable. The callee should have
2106 // adjusted 'this' so that the vfptr is at offset zero.
2107 llvm::Type
*ThunkPtrTy
= ThunkTy
->getPointerTo();
2108 llvm::Value
*VTable
= CGF
.GetVTablePtr(
2109 getThisAddress(CGF
), ThunkPtrTy
->getPointerTo(), MD
->getParent());
2111 llvm::Value
*VFuncPtr
= CGF
.Builder
.CreateConstInBoundsGEP1_64(
2112 ThunkPtrTy
, VTable
, ML
.Index
, "vfn");
2113 llvm::Value
*Callee
=
2114 CGF
.Builder
.CreateAlignedLoad(ThunkPtrTy
, VFuncPtr
, CGF
.getPointerAlign());
2116 CGF
.EmitMustTailThunk(MD
, getThisValue(CGF
), {ThunkTy
, Callee
});
2121 void MicrosoftCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl
*RD
) {
2122 const VBTableGlobals
&VBGlobals
= enumerateVBTables(RD
);
2123 for (unsigned I
= 0, E
= VBGlobals
.VBTables
->size(); I
!= E
; ++I
) {
2124 const std::unique_ptr
<VPtrInfo
>& VBT
= (*VBGlobals
.VBTables
)[I
];
2125 llvm::GlobalVariable
*GV
= VBGlobals
.Globals
[I
];
2126 if (GV
->isDeclaration())
2127 emitVBTableDefinition(*VBT
, RD
, GV
);
2131 llvm::GlobalVariable
*
2132 MicrosoftCXXABI::getAddrOfVBTable(const VPtrInfo
&VBT
, const CXXRecordDecl
*RD
,
2133 llvm::GlobalVariable::LinkageTypes Linkage
) {
2134 SmallString
<256> OutName
;
2135 llvm::raw_svector_ostream
Out(OutName
);
2136 getMangleContext().mangleCXXVBTable(RD
, VBT
.MangledPath
, Out
);
2137 StringRef Name
= OutName
.str();
2139 llvm::ArrayType
*VBTableType
=
2140 llvm::ArrayType::get(CGM
.IntTy
, 1 + VBT
.ObjectWithVPtr
->getNumVBases());
2142 assert(!CGM
.getModule().getNamedGlobal(Name
) &&
2143 "vbtable with this name already exists: mangling bug?");
2144 CharUnits Alignment
=
2145 CGM
.getContext().getTypeAlignInChars(CGM
.getContext().IntTy
);
2146 llvm::GlobalVariable
*GV
= CGM
.CreateOrReplaceCXXRuntimeVariable(
2147 Name
, VBTableType
, Linkage
, Alignment
.getAsAlign());
2148 GV
->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global
);
2150 if (RD
->hasAttr
<DLLImportAttr
>())
2151 GV
->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass
);
2152 else if (RD
->hasAttr
<DLLExportAttr
>())
2153 GV
->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass
);
2155 if (!GV
->hasExternalLinkage())
2156 emitVBTableDefinition(VBT
, RD
, GV
);
2161 void MicrosoftCXXABI::emitVBTableDefinition(const VPtrInfo
&VBT
,
2162 const CXXRecordDecl
*RD
,
2163 llvm::GlobalVariable
*GV
) const {
2164 const CXXRecordDecl
*ObjectWithVPtr
= VBT
.ObjectWithVPtr
;
2166 assert(RD
->getNumVBases() && ObjectWithVPtr
->getNumVBases() &&
2167 "should only emit vbtables for classes with vbtables");
2169 const ASTRecordLayout
&BaseLayout
=
2170 getContext().getASTRecordLayout(VBT
.IntroducingObject
);
2171 const ASTRecordLayout
&DerivedLayout
= getContext().getASTRecordLayout(RD
);
2173 SmallVector
<llvm::Constant
*, 4> Offsets(1 + ObjectWithVPtr
->getNumVBases(),
2176 // The offset from ObjectWithVPtr's vbptr to itself always leads.
2177 CharUnits VBPtrOffset
= BaseLayout
.getVBPtrOffset();
2178 Offsets
[0] = llvm::ConstantInt::get(CGM
.IntTy
, -VBPtrOffset
.getQuantity());
2180 MicrosoftVTableContext
&Context
= CGM
.getMicrosoftVTableContext();
2181 for (const auto &I
: ObjectWithVPtr
->vbases()) {
2182 const CXXRecordDecl
*VBase
= I
.getType()->getAsCXXRecordDecl();
2183 CharUnits Offset
= DerivedLayout
.getVBaseClassOffset(VBase
);
2184 assert(!Offset
.isNegative());
2186 // Make it relative to the subobject vbptr.
2187 CharUnits CompleteVBPtrOffset
= VBT
.NonVirtualOffset
+ VBPtrOffset
;
2188 if (VBT
.getVBaseWithVPtr())
2189 CompleteVBPtrOffset
+=
2190 DerivedLayout
.getVBaseClassOffset(VBT
.getVBaseWithVPtr());
2191 Offset
-= CompleteVBPtrOffset
;
2193 unsigned VBIndex
= Context
.getVBTableIndex(ObjectWithVPtr
, VBase
);
2194 assert(Offsets
[VBIndex
] == nullptr && "The same vbindex seen twice?");
2195 Offsets
[VBIndex
] = llvm::ConstantInt::get(CGM
.IntTy
, Offset
.getQuantity());
2198 assert(Offsets
.size() ==
2199 cast
<llvm::ArrayType
>(GV
->getValueType())->getNumElements());
2200 llvm::ArrayType
*VBTableType
=
2201 llvm::ArrayType::get(CGM
.IntTy
, Offsets
.size());
2202 llvm::Constant
*Init
= llvm::ConstantArray::get(VBTableType
, Offsets
);
2203 GV
->setInitializer(Init
);
2205 if (RD
->hasAttr
<DLLImportAttr
>())
2206 GV
->setLinkage(llvm::GlobalVariable::AvailableExternallyLinkage
);
2209 llvm::Value
*MicrosoftCXXABI::performThisAdjustment(CodeGenFunction
&CGF
,
2211 const ThisAdjustment
&TA
) {
2213 return This
.getPointer();
2215 This
= This
.withElementType(CGF
.Int8Ty
);
2218 if (TA
.Virtual
.isEmpty()) {
2219 V
= This
.getPointer();
2221 assert(TA
.Virtual
.Microsoft
.VtordispOffset
< 0);
2222 // Adjust the this argument based on the vtordisp value.
2223 Address VtorDispPtr
=
2224 CGF
.Builder
.CreateConstInBoundsByteGEP(This
,
2225 CharUnits::fromQuantity(TA
.Virtual
.Microsoft
.VtordispOffset
));
2226 VtorDispPtr
= VtorDispPtr
.withElementType(CGF
.Int32Ty
);
2227 llvm::Value
*VtorDisp
= CGF
.Builder
.CreateLoad(VtorDispPtr
, "vtordisp");
2228 V
= CGF
.Builder
.CreateGEP(This
.getElementType(), This
.getPointer(),
2229 CGF
.Builder
.CreateNeg(VtorDisp
));
2231 // Unfortunately, having applied the vtordisp means that we no
2232 // longer really have a known alignment for the vbptr step.
2233 // We'll assume the vbptr is pointer-aligned.
2235 if (TA
.Virtual
.Microsoft
.VBPtrOffset
) {
2236 // If the final overrider is defined in a virtual base other than the one
2237 // that holds the vfptr, we have to use a vtordispex thunk which looks up
2238 // the vbtable of the derived class.
2239 assert(TA
.Virtual
.Microsoft
.VBPtrOffset
> 0);
2240 assert(TA
.Virtual
.Microsoft
.VBOffsetOffset
>= 0);
2242 llvm::Value
*VBaseOffset
= GetVBaseOffsetFromVBPtr(
2243 CGF
, Address(V
, CGF
.Int8Ty
, CGF
.getPointerAlign()),
2244 -TA
.Virtual
.Microsoft
.VBPtrOffset
,
2245 TA
.Virtual
.Microsoft
.VBOffsetOffset
, &VBPtr
);
2246 V
= CGF
.Builder
.CreateInBoundsGEP(CGF
.Int8Ty
, VBPtr
, VBaseOffset
);
2250 if (TA
.NonVirtual
) {
2251 // Non-virtual adjustment might result in a pointer outside the allocated
2252 // object, e.g. if the final overrider class is laid out after the virtual
2253 // base that declares a method in the most derived class.
2254 V
= CGF
.Builder
.CreateConstGEP1_32(CGF
.Int8Ty
, V
, TA
.NonVirtual
);
2257 // Don't need to bitcast back, the call CodeGen will handle this.
2262 MicrosoftCXXABI::performReturnAdjustment(CodeGenFunction
&CGF
, Address Ret
,
2263 const ReturnAdjustment
&RA
) {
2265 return Ret
.getPointer();
2267 auto OrigTy
= Ret
.getType();
2268 Ret
= Ret
.withElementType(CGF
.Int8Ty
);
2270 llvm::Value
*V
= Ret
.getPointer();
2271 if (RA
.Virtual
.Microsoft
.VBIndex
) {
2272 assert(RA
.Virtual
.Microsoft
.VBIndex
> 0);
2273 int32_t IntSize
= CGF
.getIntSize().getQuantity();
2275 llvm::Value
*VBaseOffset
=
2276 GetVBaseOffsetFromVBPtr(CGF
, Ret
, RA
.Virtual
.Microsoft
.VBPtrOffset
,
2277 IntSize
* RA
.Virtual
.Microsoft
.VBIndex
, &VBPtr
);
2278 V
= CGF
.Builder
.CreateInBoundsGEP(CGF
.Int8Ty
, VBPtr
, VBaseOffset
);
2282 V
= CGF
.Builder
.CreateConstInBoundsGEP1_32(CGF
.Int8Ty
, V
, RA
.NonVirtual
);
2284 // Cast back to the original type.
2285 return CGF
.Builder
.CreateBitCast(V
, OrigTy
);
2288 bool MicrosoftCXXABI::requiresArrayCookie(const CXXDeleteExpr
*expr
,
2289 QualType elementType
) {
2290 // Microsoft seems to completely ignore the possibility of a
2291 // two-argument usual deallocation function.
2292 return elementType
.isDestructedType();
2295 bool MicrosoftCXXABI::requiresArrayCookie(const CXXNewExpr
*expr
) {
2296 // Microsoft seems to completely ignore the possibility of a
2297 // two-argument usual deallocation function.
2298 return expr
->getAllocatedType().isDestructedType();
2301 CharUnits
MicrosoftCXXABI::getArrayCookieSizeImpl(QualType type
) {
2302 // The array cookie is always a size_t; we then pad that out to the
2303 // alignment of the element type.
2304 ASTContext
&Ctx
= getContext();
2305 return std::max(Ctx
.getTypeSizeInChars(Ctx
.getSizeType()),
2306 Ctx
.getTypeAlignInChars(type
));
2309 llvm::Value
*MicrosoftCXXABI::readArrayCookieImpl(CodeGenFunction
&CGF
,
2311 CharUnits cookieSize
) {
2312 Address numElementsPtr
= allocPtr
.withElementType(CGF
.SizeTy
);
2313 return CGF
.Builder
.CreateLoad(numElementsPtr
);
2316 Address
MicrosoftCXXABI::InitializeArrayCookie(CodeGenFunction
&CGF
,
2318 llvm::Value
*numElements
,
2319 const CXXNewExpr
*expr
,
2320 QualType elementType
) {
2321 assert(requiresArrayCookie(expr
));
2323 // The size of the cookie.
2324 CharUnits cookieSize
= getArrayCookieSizeImpl(elementType
);
2326 // Compute an offset to the cookie.
2327 Address cookiePtr
= newPtr
;
2329 // Write the number of elements into the appropriate slot.
2330 Address numElementsPtr
= cookiePtr
.withElementType(CGF
.SizeTy
);
2331 CGF
.Builder
.CreateStore(numElements
, numElementsPtr
);
2333 // Finally, compute a pointer to the actual data buffer by skipping
2334 // over the cookie completely.
2335 return CGF
.Builder
.CreateConstInBoundsByteGEP(newPtr
, cookieSize
);
2338 static void emitGlobalDtorWithTLRegDtor(CodeGenFunction
&CGF
, const VarDecl
&VD
,
2339 llvm::FunctionCallee Dtor
,
2340 llvm::Constant
*Addr
) {
2341 // Create a function which calls the destructor.
2342 llvm::Constant
*DtorStub
= CGF
.createAtExitStub(VD
, Dtor
, Addr
);
2344 // extern "C" int __tlregdtor(void (*f)(void));
2345 llvm::FunctionType
*TLRegDtorTy
= llvm::FunctionType::get(
2346 CGF
.IntTy
, DtorStub
->getType(), /*isVarArg=*/false);
2348 llvm::FunctionCallee TLRegDtor
= CGF
.CGM
.CreateRuntimeFunction(
2349 TLRegDtorTy
, "__tlregdtor", llvm::AttributeList(), /*Local=*/true);
2350 if (llvm::Function
*TLRegDtorFn
=
2351 dyn_cast
<llvm::Function
>(TLRegDtor
.getCallee()))
2352 TLRegDtorFn
->setDoesNotThrow();
2354 CGF
.EmitNounwindRuntimeCall(TLRegDtor
, DtorStub
);
2357 void MicrosoftCXXABI::registerGlobalDtor(CodeGenFunction
&CGF
, const VarDecl
&D
,
2358 llvm::FunctionCallee Dtor
,
2359 llvm::Constant
*Addr
) {
2360 if (D
.isNoDestroy(CGM
.getContext()))
2364 return emitGlobalDtorWithTLRegDtor(CGF
, D
, Dtor
, Addr
);
2366 // HLSL doesn't support atexit.
2367 if (CGM
.getLangOpts().HLSL
)
2368 return CGM
.AddCXXDtorEntry(Dtor
, Addr
);
2370 // The default behavior is to use atexit.
2371 CGF
.registerGlobalDtorWithAtExit(D
, Dtor
, Addr
);
2374 void MicrosoftCXXABI::EmitThreadLocalInitFuncs(
2375 CodeGenModule
&CGM
, ArrayRef
<const VarDecl
*> CXXThreadLocals
,
2376 ArrayRef
<llvm::Function
*> CXXThreadLocalInits
,
2377 ArrayRef
<const VarDecl
*> CXXThreadLocalInitVars
) {
2378 if (CXXThreadLocalInits
.empty())
2381 CGM
.AppendLinkerOptions(CGM
.getTarget().getTriple().getArch() ==
2383 ? "/include:___dyn_tls_init@12"
2384 : "/include:__dyn_tls_init");
2386 // This will create a GV in the .CRT$XDU section. It will point to our
2387 // initialization function. The CRT will call all of these function
2388 // pointers at start-up time and, eventually, at thread-creation time.
2389 auto AddToXDU
= [&CGM
](llvm::Function
*InitFunc
) {
2390 llvm::GlobalVariable
*InitFuncPtr
= new llvm::GlobalVariable(
2391 CGM
.getModule(), InitFunc
->getType(), /*isConstant=*/true,
2392 llvm::GlobalVariable::InternalLinkage
, InitFunc
,
2393 Twine(InitFunc
->getName(), "$initializer$"));
2394 InitFuncPtr
->setSection(".CRT$XDU");
2395 // This variable has discardable linkage, we have to add it to @llvm.used to
2396 // ensure it won't get discarded.
2397 CGM
.addUsedGlobal(InitFuncPtr
);
2401 std::vector
<llvm::Function
*> NonComdatInits
;
2402 for (size_t I
= 0, E
= CXXThreadLocalInitVars
.size(); I
!= E
; ++I
) {
2403 llvm::GlobalVariable
*GV
= cast
<llvm::GlobalVariable
>(
2404 CGM
.GetGlobalValue(CGM
.getMangledName(CXXThreadLocalInitVars
[I
])));
2405 llvm::Function
*F
= CXXThreadLocalInits
[I
];
2407 // If the GV is already in a comdat group, then we have to join it.
2408 if (llvm::Comdat
*C
= GV
->getComdat())
2409 AddToXDU(F
)->setComdat(C
);
2411 NonComdatInits
.push_back(F
);
2414 if (!NonComdatInits
.empty()) {
2415 llvm::FunctionType
*FTy
=
2416 llvm::FunctionType::get(CGM
.VoidTy
, /*isVarArg=*/false);
2417 llvm::Function
*InitFunc
= CGM
.CreateGlobalInitOrCleanUpFunction(
2418 FTy
, "__tls_init", CGM
.getTypes().arrangeNullaryFunction(),
2419 SourceLocation(), /*TLS=*/true);
2420 CodeGenFunction(CGM
).GenerateCXXGlobalInitFunc(InitFunc
, NonComdatInits
);
2426 static llvm::GlobalValue
*getTlsGuardVar(CodeGenModule
&CGM
) {
2427 // __tls_guard comes from the MSVC runtime and reflects
2428 // whether TLS has been initialized for a particular thread.
2429 // It is set from within __dyn_tls_init by the runtime.
2430 // Every library and executable has its own variable.
2431 llvm::Type
*VTy
= llvm::Type::getInt8Ty(CGM
.getLLVMContext());
2432 llvm::Constant
*TlsGuardConstant
=
2433 CGM
.CreateRuntimeVariable(VTy
, "__tls_guard");
2434 llvm::GlobalValue
*TlsGuard
= cast
<llvm::GlobalValue
>(TlsGuardConstant
);
2436 TlsGuard
->setThreadLocal(true);
2441 static llvm::FunctionCallee
getDynTlsOnDemandInitFn(CodeGenModule
&CGM
) {
2442 // __dyn_tls_on_demand_init comes from the MSVC runtime and triggers
2443 // dynamic TLS initialization by calling __dyn_tls_init internally.
2444 llvm::FunctionType
*FTy
=
2445 llvm::FunctionType::get(llvm::Type::getVoidTy(CGM
.getLLVMContext()), {},
2446 /*isVarArg=*/false);
2447 return CGM
.CreateRuntimeFunction(
2448 FTy
, "__dyn_tls_on_demand_init",
2449 llvm::AttributeList::get(CGM
.getLLVMContext(),
2450 llvm::AttributeList::FunctionIndex
,
2451 llvm::Attribute::NoUnwind
),
2455 static void emitTlsGuardCheck(CodeGenFunction
&CGF
, llvm::GlobalValue
*TlsGuard
,
2456 llvm::BasicBlock
*DynInitBB
,
2457 llvm::BasicBlock
*ContinueBB
) {
2458 llvm::LoadInst
*TlsGuardValue
=
2459 CGF
.Builder
.CreateLoad(Address(TlsGuard
, CGF
.Int8Ty
, CharUnits::One()));
2460 llvm::Value
*CmpResult
=
2461 CGF
.Builder
.CreateICmpEQ(TlsGuardValue
, CGF
.Builder
.getInt8(0));
2462 CGF
.Builder
.CreateCondBr(CmpResult
, DynInitBB
, ContinueBB
);
2465 static void emitDynamicTlsInitializationCall(CodeGenFunction
&CGF
,
2466 llvm::GlobalValue
*TlsGuard
,
2467 llvm::BasicBlock
*ContinueBB
) {
2468 llvm::FunctionCallee Initializer
= getDynTlsOnDemandInitFn(CGF
.CGM
);
2469 llvm::Function
*InitializerFunction
=
2470 cast
<llvm::Function
>(Initializer
.getCallee());
2471 llvm::CallInst
*CallVal
= CGF
.Builder
.CreateCall(InitializerFunction
);
2472 CallVal
->setCallingConv(InitializerFunction
->getCallingConv());
2474 CGF
.Builder
.CreateBr(ContinueBB
);
2477 static void emitDynamicTlsInitialization(CodeGenFunction
&CGF
) {
2478 llvm::BasicBlock
*DynInitBB
=
2479 CGF
.createBasicBlock("dyntls.dyn_init", CGF
.CurFn
);
2480 llvm::BasicBlock
*ContinueBB
=
2481 CGF
.createBasicBlock("dyntls.continue", CGF
.CurFn
);
2483 llvm::GlobalValue
*TlsGuard
= getTlsGuardVar(CGF
.CGM
);
2485 emitTlsGuardCheck(CGF
, TlsGuard
, DynInitBB
, ContinueBB
);
2486 CGF
.Builder
.SetInsertPoint(DynInitBB
);
2487 emitDynamicTlsInitializationCall(CGF
, TlsGuard
, ContinueBB
);
2488 CGF
.Builder
.SetInsertPoint(ContinueBB
);
2491 LValue
MicrosoftCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction
&CGF
,
2493 QualType LValType
) {
2494 // Dynamic TLS initialization works by checking the state of a
2495 // guard variable (__tls_guard) to see whether TLS initialization
2496 // for a thread has happend yet.
2497 // If not, the initialization is triggered on-demand
2498 // by calling __dyn_tls_on_demand_init.
2499 emitDynamicTlsInitialization(CGF
);
2501 // Emit the variable just like any regular global variable.
2503 llvm::Value
*V
= CGF
.CGM
.GetAddrOfGlobalVar(VD
);
2504 llvm::Type
*RealVarTy
= CGF
.getTypes().ConvertTypeForMem(VD
->getType());
2506 CharUnits Alignment
= CGF
.getContext().getDeclAlign(VD
);
2507 Address
Addr(V
, RealVarTy
, Alignment
);
2509 LValue LV
= VD
->getType()->isReferenceType()
2510 ? CGF
.EmitLoadOfReferenceLValue(Addr
, VD
->getType(),
2511 AlignmentSource::Decl
)
2512 : CGF
.MakeAddrLValue(Addr
, LValType
, AlignmentSource::Decl
);
2516 static ConstantAddress
getInitThreadEpochPtr(CodeGenModule
&CGM
) {
2517 StringRef
VarName("_Init_thread_epoch");
2518 CharUnits Align
= CGM
.getIntAlign();
2519 if (auto *GV
= CGM
.getModule().getNamedGlobal(VarName
))
2520 return ConstantAddress(GV
, GV
->getValueType(), Align
);
2521 auto *GV
= new llvm::GlobalVariable(
2522 CGM
.getModule(), CGM
.IntTy
,
2523 /*isConstant=*/false, llvm::GlobalVariable::ExternalLinkage
,
2524 /*Initializer=*/nullptr, VarName
,
2525 /*InsertBefore=*/nullptr, llvm::GlobalVariable::GeneralDynamicTLSModel
);
2526 GV
->setAlignment(Align
.getAsAlign());
2527 return ConstantAddress(GV
, GV
->getValueType(), Align
);
2530 static llvm::FunctionCallee
getInitThreadHeaderFn(CodeGenModule
&CGM
) {
2531 llvm::FunctionType
*FTy
=
2532 llvm::FunctionType::get(llvm::Type::getVoidTy(CGM
.getLLVMContext()),
2533 CGM
.IntTy
->getPointerTo(), /*isVarArg=*/false);
2534 return CGM
.CreateRuntimeFunction(
2535 FTy
, "_Init_thread_header",
2536 llvm::AttributeList::get(CGM
.getLLVMContext(),
2537 llvm::AttributeList::FunctionIndex
,
2538 llvm::Attribute::NoUnwind
),
2542 static llvm::FunctionCallee
getInitThreadFooterFn(CodeGenModule
&CGM
) {
2543 llvm::FunctionType
*FTy
=
2544 llvm::FunctionType::get(llvm::Type::getVoidTy(CGM
.getLLVMContext()),
2545 CGM
.IntTy
->getPointerTo(), /*isVarArg=*/false);
2546 return CGM
.CreateRuntimeFunction(
2547 FTy
, "_Init_thread_footer",
2548 llvm::AttributeList::get(CGM
.getLLVMContext(),
2549 llvm::AttributeList::FunctionIndex
,
2550 llvm::Attribute::NoUnwind
),
2554 static llvm::FunctionCallee
getInitThreadAbortFn(CodeGenModule
&CGM
) {
2555 llvm::FunctionType
*FTy
=
2556 llvm::FunctionType::get(llvm::Type::getVoidTy(CGM
.getLLVMContext()),
2557 CGM
.IntTy
->getPointerTo(), /*isVarArg=*/false);
2558 return CGM
.CreateRuntimeFunction(
2559 FTy
, "_Init_thread_abort",
2560 llvm::AttributeList::get(CGM
.getLLVMContext(),
2561 llvm::AttributeList::FunctionIndex
,
2562 llvm::Attribute::NoUnwind
),
2567 struct ResetGuardBit final
: EHScopeStack::Cleanup
{
2570 ResetGuardBit(Address Guard
, unsigned GuardNum
)
2571 : Guard(Guard
), GuardNum(GuardNum
) {}
2573 void Emit(CodeGenFunction
&CGF
, Flags flags
) override
{
2574 // Reset the bit in the mask so that the static variable may be
2576 CGBuilderTy
&Builder
= CGF
.Builder
;
2577 llvm::LoadInst
*LI
= Builder
.CreateLoad(Guard
);
2578 llvm::ConstantInt
*Mask
=
2579 llvm::ConstantInt::get(CGF
.IntTy
, ~(1ULL << GuardNum
));
2580 Builder
.CreateStore(Builder
.CreateAnd(LI
, Mask
), Guard
);
2584 struct CallInitThreadAbort final
: EHScopeStack::Cleanup
{
2586 CallInitThreadAbort(Address Guard
) : Guard(Guard
.getPointer()) {}
2588 void Emit(CodeGenFunction
&CGF
, Flags flags
) override
{
2589 // Calling _Init_thread_abort will reset the guard's state.
2590 CGF
.EmitNounwindRuntimeCall(getInitThreadAbortFn(CGF
.CGM
), Guard
);
2595 void MicrosoftCXXABI::EmitGuardedInit(CodeGenFunction
&CGF
, const VarDecl
&D
,
2596 llvm::GlobalVariable
*GV
,
2598 // MSVC only uses guards for static locals.
2599 if (!D
.isStaticLocal()) {
2600 assert(GV
->hasWeakLinkage() || GV
->hasLinkOnceLinkage());
2601 // GlobalOpt is allowed to discard the initializer, so use linkonce_odr.
2602 llvm::Function
*F
= CGF
.CurFn
;
2603 F
->setLinkage(llvm::GlobalValue::LinkOnceODRLinkage
);
2604 F
->setComdat(CGM
.getModule().getOrInsertComdat(F
->getName()));
2605 CGF
.EmitCXXGlobalVarDeclInit(D
, GV
, PerformInit
);
2609 bool ThreadlocalStatic
= D
.getTLSKind();
2610 bool ThreadsafeStatic
= getContext().getLangOpts().ThreadsafeStatics
;
2612 // Thread-safe static variables which aren't thread-specific have a
2613 // per-variable guard.
2614 bool HasPerVariableGuard
= ThreadsafeStatic
&& !ThreadlocalStatic
;
2616 CGBuilderTy
&Builder
= CGF
.Builder
;
2617 llvm::IntegerType
*GuardTy
= CGF
.Int32Ty
;
2618 llvm::ConstantInt
*Zero
= llvm::ConstantInt::get(GuardTy
, 0);
2619 CharUnits GuardAlign
= CharUnits::fromQuantity(4);
2621 // Get the guard variable for this function if we have one already.
2622 GuardInfo
*GI
= nullptr;
2623 if (ThreadlocalStatic
)
2624 GI
= &ThreadLocalGuardVariableMap
[D
.getDeclContext()];
2625 else if (!ThreadsafeStatic
)
2626 GI
= &GuardVariableMap
[D
.getDeclContext()];
2628 llvm::GlobalVariable
*GuardVar
= GI
? GI
->Guard
: nullptr;
2630 if (D
.isExternallyVisible()) {
2631 // Externally visible variables have to be numbered in Sema to properly
2632 // handle unreachable VarDecls.
2633 GuardNum
= getContext().getStaticLocalNumber(&D
);
2634 assert(GuardNum
> 0);
2636 } else if (HasPerVariableGuard
) {
2637 GuardNum
= ThreadSafeGuardNumMap
[D
.getDeclContext()]++;
2639 // Non-externally visible variables are numbered here in CodeGen.
2640 GuardNum
= GI
->BitIndex
++;
2643 if (!HasPerVariableGuard
&& GuardNum
>= 32) {
2644 if (D
.isExternallyVisible())
2645 ErrorUnsupportedABI(CGF
, "more than 32 guarded initializations");
2651 // Mangle the name for the guard.
2652 SmallString
<256> GuardName
;
2654 llvm::raw_svector_ostream
Out(GuardName
);
2655 if (HasPerVariableGuard
)
2656 getMangleContext().mangleThreadSafeStaticGuardVariable(&D
, GuardNum
,
2659 getMangleContext().mangleStaticGuardVariable(&D
, Out
);
2662 // Create the guard variable with a zero-initializer. Just absorb linkage,
2663 // visibility and dll storage class from the guarded variable.
2665 new llvm::GlobalVariable(CGM
.getModule(), GuardTy
, /*isConstant=*/false,
2666 GV
->getLinkage(), Zero
, GuardName
.str());
2667 GuardVar
->setVisibility(GV
->getVisibility());
2668 GuardVar
->setDLLStorageClass(GV
->getDLLStorageClass());
2669 GuardVar
->setAlignment(GuardAlign
.getAsAlign());
2670 if (GuardVar
->isWeakForLinker())
2671 GuardVar
->setComdat(
2672 CGM
.getModule().getOrInsertComdat(GuardVar
->getName()));
2674 CGM
.setTLSMode(GuardVar
, D
);
2675 if (GI
&& !HasPerVariableGuard
)
2676 GI
->Guard
= GuardVar
;
2679 ConstantAddress
GuardAddr(GuardVar
, GuardTy
, GuardAlign
);
2681 assert(GuardVar
->getLinkage() == GV
->getLinkage() &&
2682 "static local from the same function had different linkage");
2684 if (!HasPerVariableGuard
) {
2685 // Pseudo code for the test:
2686 // if (!(GuardVar & MyGuardBit)) {
2687 // GuardVar |= MyGuardBit;
2688 // ... initialize the object ...;
2691 // Test our bit from the guard variable.
2692 llvm::ConstantInt
*Bit
= llvm::ConstantInt::get(GuardTy
, 1ULL << GuardNum
);
2693 llvm::LoadInst
*LI
= Builder
.CreateLoad(GuardAddr
);
2694 llvm::Value
*NeedsInit
=
2695 Builder
.CreateICmpEQ(Builder
.CreateAnd(LI
, Bit
), Zero
);
2696 llvm::BasicBlock
*InitBlock
= CGF
.createBasicBlock("init");
2697 llvm::BasicBlock
*EndBlock
= CGF
.createBasicBlock("init.end");
2698 CGF
.EmitCXXGuardedInitBranch(NeedsInit
, InitBlock
, EndBlock
,
2699 CodeGenFunction::GuardKind::VariableGuard
, &D
);
2701 // Set our bit in the guard variable and emit the initializer and add a global
2702 // destructor if appropriate.
2703 CGF
.EmitBlock(InitBlock
);
2704 Builder
.CreateStore(Builder
.CreateOr(LI
, Bit
), GuardAddr
);
2705 CGF
.EHStack
.pushCleanup
<ResetGuardBit
>(EHCleanup
, GuardAddr
, GuardNum
);
2706 CGF
.EmitCXXGlobalVarDeclInit(D
, GV
, PerformInit
);
2707 CGF
.PopCleanupBlock();
2708 Builder
.CreateBr(EndBlock
);
2711 CGF
.EmitBlock(EndBlock
);
2713 // Pseudo code for the test:
2714 // if (TSS > _Init_thread_epoch) {
2715 // _Init_thread_header(&TSS);
2717 // ... initialize the object ...;
2718 // _Init_thread_footer(&TSS);
2722 // The algorithm is almost identical to what can be found in the appendix
2725 // This BasicBLock determines whether or not we have any work to do.
2726 llvm::LoadInst
*FirstGuardLoad
= Builder
.CreateLoad(GuardAddr
);
2727 FirstGuardLoad
->setOrdering(llvm::AtomicOrdering::Unordered
);
2728 llvm::LoadInst
*InitThreadEpoch
=
2729 Builder
.CreateLoad(getInitThreadEpochPtr(CGM
));
2730 llvm::Value
*IsUninitialized
=
2731 Builder
.CreateICmpSGT(FirstGuardLoad
, InitThreadEpoch
);
2732 llvm::BasicBlock
*AttemptInitBlock
= CGF
.createBasicBlock("init.attempt");
2733 llvm::BasicBlock
*EndBlock
= CGF
.createBasicBlock("init.end");
2734 CGF
.EmitCXXGuardedInitBranch(IsUninitialized
, AttemptInitBlock
, EndBlock
,
2735 CodeGenFunction::GuardKind::VariableGuard
, &D
);
2737 // This BasicBlock attempts to determine whether or not this thread is
2738 // responsible for doing the initialization.
2739 CGF
.EmitBlock(AttemptInitBlock
);
2740 CGF
.EmitNounwindRuntimeCall(getInitThreadHeaderFn(CGM
),
2741 GuardAddr
.getPointer());
2742 llvm::LoadInst
*SecondGuardLoad
= Builder
.CreateLoad(GuardAddr
);
2743 SecondGuardLoad
->setOrdering(llvm::AtomicOrdering::Unordered
);
2744 llvm::Value
*ShouldDoInit
=
2745 Builder
.CreateICmpEQ(SecondGuardLoad
, getAllOnesInt());
2746 llvm::BasicBlock
*InitBlock
= CGF
.createBasicBlock("init");
2747 Builder
.CreateCondBr(ShouldDoInit
, InitBlock
, EndBlock
);
2749 // Ok, we ended up getting selected as the initializing thread.
2750 CGF
.EmitBlock(InitBlock
);
2751 CGF
.EHStack
.pushCleanup
<CallInitThreadAbort
>(EHCleanup
, GuardAddr
);
2752 CGF
.EmitCXXGlobalVarDeclInit(D
, GV
, PerformInit
);
2753 CGF
.PopCleanupBlock();
2754 CGF
.EmitNounwindRuntimeCall(getInitThreadFooterFn(CGM
),
2755 GuardAddr
.getPointer());
2756 Builder
.CreateBr(EndBlock
);
2758 CGF
.EmitBlock(EndBlock
);
2762 bool MicrosoftCXXABI::isZeroInitializable(const MemberPointerType
*MPT
) {
2763 // Null-ness for function memptrs only depends on the first field, which is
2764 // the function pointer. The rest don't matter, so we can zero initialize.
2765 if (MPT
->isMemberFunctionPointer())
2768 // The virtual base adjustment field is always -1 for null, so if we have one
2769 // we can't zero initialize. The field offset is sometimes also -1 if 0 is a
2770 // valid field offset.
2771 const CXXRecordDecl
*RD
= MPT
->getMostRecentCXXRecordDecl();
2772 MSInheritanceModel Inheritance
= RD
->getMSInheritanceModel();
2773 return (!inheritanceModelHasVBTableOffsetField(Inheritance
) &&
2774 RD
->nullFieldOffsetIsZero());
2778 MicrosoftCXXABI::ConvertMemberPointerType(const MemberPointerType
*MPT
) {
2779 const CXXRecordDecl
*RD
= MPT
->getMostRecentCXXRecordDecl();
2780 MSInheritanceModel Inheritance
= RD
->getMSInheritanceModel();
2781 llvm::SmallVector
<llvm::Type
*, 4> fields
;
2782 if (MPT
->isMemberFunctionPointer())
2783 fields
.push_back(CGM
.VoidPtrTy
); // FunctionPointerOrVirtualThunk
2785 fields
.push_back(CGM
.IntTy
); // FieldOffset
2787 if (inheritanceModelHasNVOffsetField(MPT
->isMemberFunctionPointer(),
2789 fields
.push_back(CGM
.IntTy
);
2790 if (inheritanceModelHasVBPtrOffsetField(Inheritance
))
2791 fields
.push_back(CGM
.IntTy
);
2792 if (inheritanceModelHasVBTableOffsetField(Inheritance
))
2793 fields
.push_back(CGM
.IntTy
); // VirtualBaseAdjustmentOffset
2795 if (fields
.size() == 1)
2797 return llvm::StructType::get(CGM
.getLLVMContext(), fields
);
2800 void MicrosoftCXXABI::
2801 GetNullMemberPointerFields(const MemberPointerType
*MPT
,
2802 llvm::SmallVectorImpl
<llvm::Constant
*> &fields
) {
2803 assert(fields
.empty());
2804 const CXXRecordDecl
*RD
= MPT
->getMostRecentCXXRecordDecl();
2805 MSInheritanceModel Inheritance
= RD
->getMSInheritanceModel();
2806 if (MPT
->isMemberFunctionPointer()) {
2807 // FunctionPointerOrVirtualThunk
2808 fields
.push_back(llvm::Constant::getNullValue(CGM
.VoidPtrTy
));
2810 if (RD
->nullFieldOffsetIsZero())
2811 fields
.push_back(getZeroInt()); // FieldOffset
2813 fields
.push_back(getAllOnesInt()); // FieldOffset
2816 if (inheritanceModelHasNVOffsetField(MPT
->isMemberFunctionPointer(),
2818 fields
.push_back(getZeroInt());
2819 if (inheritanceModelHasVBPtrOffsetField(Inheritance
))
2820 fields
.push_back(getZeroInt());
2821 if (inheritanceModelHasVBTableOffsetField(Inheritance
))
2822 fields
.push_back(getAllOnesInt());
2826 MicrosoftCXXABI::EmitNullMemberPointer(const MemberPointerType
*MPT
) {
2827 llvm::SmallVector
<llvm::Constant
*, 4> fields
;
2828 GetNullMemberPointerFields(MPT
, fields
);
2829 if (fields
.size() == 1)
2831 llvm::Constant
*Res
= llvm::ConstantStruct::getAnon(fields
);
2832 assert(Res
->getType() == ConvertMemberPointerType(MPT
));
2837 MicrosoftCXXABI::EmitFullMemberPointer(llvm::Constant
*FirstField
,
2838 bool IsMemberFunction
,
2839 const CXXRecordDecl
*RD
,
2840 CharUnits NonVirtualBaseAdjustment
,
2841 unsigned VBTableIndex
) {
2842 MSInheritanceModel Inheritance
= RD
->getMSInheritanceModel();
2844 // Single inheritance class member pointer are represented as scalars instead
2846 if (inheritanceModelHasOnlyOneField(IsMemberFunction
, Inheritance
))
2849 llvm::SmallVector
<llvm::Constant
*, 4> fields
;
2850 fields
.push_back(FirstField
);
2852 if (inheritanceModelHasNVOffsetField(IsMemberFunction
, Inheritance
))
2853 fields
.push_back(llvm::ConstantInt::get(
2854 CGM
.IntTy
, NonVirtualBaseAdjustment
.getQuantity()));
2856 if (inheritanceModelHasVBPtrOffsetField(Inheritance
)) {
2857 CharUnits Offs
= CharUnits::Zero();
2859 Offs
= getContext().getASTRecordLayout(RD
).getVBPtrOffset();
2860 fields
.push_back(llvm::ConstantInt::get(CGM
.IntTy
, Offs
.getQuantity()));
2863 // The rest of the fields are adjusted by conversions to a more derived class.
2864 if (inheritanceModelHasVBTableOffsetField(Inheritance
))
2865 fields
.push_back(llvm::ConstantInt::get(CGM
.IntTy
, VBTableIndex
));
2867 return llvm::ConstantStruct::getAnon(fields
);
2871 MicrosoftCXXABI::EmitMemberDataPointer(const MemberPointerType
*MPT
,
2873 return EmitMemberDataPointer(MPT
->getMostRecentCXXRecordDecl(), offset
);
2876 llvm::Constant
*MicrosoftCXXABI::EmitMemberDataPointer(const CXXRecordDecl
*RD
,
2878 if (RD
->getMSInheritanceModel() ==
2879 MSInheritanceModel::Virtual
)
2880 offset
-= getContext().getOffsetOfBaseWithVBPtr(RD
);
2881 llvm::Constant
*FirstField
=
2882 llvm::ConstantInt::get(CGM
.IntTy
, offset
.getQuantity());
2883 return EmitFullMemberPointer(FirstField
, /*IsMemberFunction=*/false, RD
,
2884 CharUnits::Zero(), /*VBTableIndex=*/0);
2887 llvm::Constant
*MicrosoftCXXABI::EmitMemberPointer(const APValue
&MP
,
2889 const MemberPointerType
*DstTy
= MPType
->castAs
<MemberPointerType
>();
2890 const ValueDecl
*MPD
= MP
.getMemberPointerDecl();
2892 return EmitNullMemberPointer(DstTy
);
2894 ASTContext
&Ctx
= getContext();
2895 ArrayRef
<const CXXRecordDecl
*> MemberPointerPath
= MP
.getMemberPointerPath();
2898 if (const CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(MPD
)) {
2899 C
= EmitMemberFunctionPointer(MD
);
2901 // For a pointer to data member, start off with the offset of the field in
2902 // the class in which it was declared, and convert from there if necessary.
2903 // For indirect field decls, get the outermost anonymous field and use the
2905 CharUnits FieldOffset
= Ctx
.toCharUnitsFromBits(Ctx
.getFieldOffset(MPD
));
2906 const FieldDecl
*FD
= dyn_cast
<FieldDecl
>(MPD
);
2908 FD
= cast
<FieldDecl
>(*cast
<IndirectFieldDecl
>(MPD
)->chain_begin());
2909 const CXXRecordDecl
*RD
= cast
<CXXRecordDecl
>(FD
->getParent());
2910 RD
= RD
->getMostRecentNonInjectedDecl();
2911 C
= EmitMemberDataPointer(RD
, FieldOffset
);
2914 if (!MemberPointerPath
.empty()) {
2915 const CXXRecordDecl
*SrcRD
= cast
<CXXRecordDecl
>(MPD
->getDeclContext());
2916 const Type
*SrcRecTy
= Ctx
.getTypeDeclType(SrcRD
).getTypePtr();
2917 const MemberPointerType
*SrcTy
=
2918 Ctx
.getMemberPointerType(DstTy
->getPointeeType(), SrcRecTy
)
2919 ->castAs
<MemberPointerType
>();
2921 bool DerivedMember
= MP
.isMemberPointerToDerivedMember();
2922 SmallVector
<const CXXBaseSpecifier
*, 4> DerivedToBasePath
;
2923 const CXXRecordDecl
*PrevRD
= SrcRD
;
2924 for (const CXXRecordDecl
*PathElem
: MemberPointerPath
) {
2925 const CXXRecordDecl
*Base
= nullptr;
2926 const CXXRecordDecl
*Derived
= nullptr;
2927 if (DerivedMember
) {
2934 for (const CXXBaseSpecifier
&BS
: Derived
->bases())
2935 if (BS
.getType()->getAsCXXRecordDecl()->getCanonicalDecl() ==
2936 Base
->getCanonicalDecl())
2937 DerivedToBasePath
.push_back(&BS
);
2940 assert(DerivedToBasePath
.size() == MemberPointerPath
.size());
2942 CastKind CK
= DerivedMember
? CK_DerivedToBaseMemberPointer
2943 : CK_BaseToDerivedMemberPointer
;
2944 C
= EmitMemberPointerConversion(SrcTy
, DstTy
, CK
, DerivedToBasePath
.begin(),
2945 DerivedToBasePath
.end(), C
);
2951 MicrosoftCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl
*MD
) {
2952 assert(MD
->isInstance() && "Member function must not be static!");
2954 CharUnits NonVirtualBaseAdjustment
= CharUnits::Zero();
2955 const CXXRecordDecl
*RD
= MD
->getParent()->getMostRecentNonInjectedDecl();
2956 CodeGenTypes
&Types
= CGM
.getTypes();
2958 unsigned VBTableIndex
= 0;
2959 llvm::Constant
*FirstField
;
2960 const FunctionProtoType
*FPT
= MD
->getType()->castAs
<FunctionProtoType
>();
2961 if (!MD
->isVirtual()) {
2963 // Check whether the function has a computable LLVM signature.
2964 if (Types
.isFuncTypeConvertible(FPT
)) {
2965 // The function has a computable LLVM signature; use the correct type.
2966 Ty
= Types
.GetFunctionType(Types
.arrangeCXXMethodDeclaration(MD
));
2968 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
2969 // function type is incomplete.
2972 FirstField
= CGM
.GetAddrOfFunction(MD
, Ty
);
2974 auto &VTableContext
= CGM
.getMicrosoftVTableContext();
2975 MethodVFTableLocation ML
= VTableContext
.getMethodVFTableLocation(MD
);
2976 FirstField
= EmitVirtualMemPtrThunk(MD
, ML
);
2977 // Include the vfptr adjustment if the method is in a non-primary vftable.
2978 NonVirtualBaseAdjustment
+= ML
.VFPtrOffset
;
2980 VBTableIndex
= VTableContext
.getVBTableIndex(RD
, ML
.VBase
) * 4;
2983 if (VBTableIndex
== 0 &&
2984 RD
->getMSInheritanceModel() ==
2985 MSInheritanceModel::Virtual
)
2986 NonVirtualBaseAdjustment
-= getContext().getOffsetOfBaseWithVBPtr(RD
);
2988 // The rest of the fields are common with data member pointers.
2989 FirstField
= llvm::ConstantExpr::getBitCast(FirstField
, CGM
.VoidPtrTy
);
2990 return EmitFullMemberPointer(FirstField
, /*IsMemberFunction=*/true, RD
,
2991 NonVirtualBaseAdjustment
, VBTableIndex
);
2994 /// Member pointers are the same if they're either bitwise identical *or* both
2995 /// null. Null-ness for function members is determined by the first field,
2996 /// while for data member pointers we must compare all fields.
2998 MicrosoftCXXABI::EmitMemberPointerComparison(CodeGenFunction
&CGF
,
3001 const MemberPointerType
*MPT
,
3003 CGBuilderTy
&Builder
= CGF
.Builder
;
3005 // Handle != comparisons by switching the sense of all boolean operations.
3006 llvm::ICmpInst::Predicate Eq
;
3007 llvm::Instruction::BinaryOps And
, Or
;
3009 Eq
= llvm::ICmpInst::ICMP_NE
;
3010 And
= llvm::Instruction::Or
;
3011 Or
= llvm::Instruction::And
;
3013 Eq
= llvm::ICmpInst::ICMP_EQ
;
3014 And
= llvm::Instruction::And
;
3015 Or
= llvm::Instruction::Or
;
3018 // If this is a single field member pointer (single inheritance), this is a
3020 const CXXRecordDecl
*RD
= MPT
->getMostRecentCXXRecordDecl();
3021 MSInheritanceModel Inheritance
= RD
->getMSInheritanceModel();
3022 if (inheritanceModelHasOnlyOneField(MPT
->isMemberFunctionPointer(),
3024 return Builder
.CreateICmp(Eq
, L
, R
);
3026 // Compare the first field.
3027 llvm::Value
*L0
= Builder
.CreateExtractValue(L
, 0, "lhs.0");
3028 llvm::Value
*R0
= Builder
.CreateExtractValue(R
, 0, "rhs.0");
3029 llvm::Value
*Cmp0
= Builder
.CreateICmp(Eq
, L0
, R0
, "memptr.cmp.first");
3031 // Compare everything other than the first field.
3032 llvm::Value
*Res
= nullptr;
3033 llvm::StructType
*LType
= cast
<llvm::StructType
>(L
->getType());
3034 for (unsigned I
= 1, E
= LType
->getNumElements(); I
!= E
; ++I
) {
3035 llvm::Value
*LF
= Builder
.CreateExtractValue(L
, I
);
3036 llvm::Value
*RF
= Builder
.CreateExtractValue(R
, I
);
3037 llvm::Value
*Cmp
= Builder
.CreateICmp(Eq
, LF
, RF
, "memptr.cmp.rest");
3039 Res
= Builder
.CreateBinOp(And
, Res
, Cmp
);
3044 // Check if the first field is 0 if this is a function pointer.
3045 if (MPT
->isMemberFunctionPointer()) {
3046 // (l1 == r1 && ...) || l0 == 0
3047 llvm::Value
*Zero
= llvm::Constant::getNullValue(L0
->getType());
3048 llvm::Value
*IsZero
= Builder
.CreateICmp(Eq
, L0
, Zero
, "memptr.cmp.iszero");
3049 Res
= Builder
.CreateBinOp(Or
, Res
, IsZero
);
3052 // Combine the comparison of the first field, which must always be true for
3053 // this comparison to succeeed.
3054 return Builder
.CreateBinOp(And
, Res
, Cmp0
, "memptr.cmp");
3058 MicrosoftCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction
&CGF
,
3059 llvm::Value
*MemPtr
,
3060 const MemberPointerType
*MPT
) {
3061 CGBuilderTy
&Builder
= CGF
.Builder
;
3062 llvm::SmallVector
<llvm::Constant
*, 4> fields
;
3063 // We only need one field for member functions.
3064 if (MPT
->isMemberFunctionPointer())
3065 fields
.push_back(llvm::Constant::getNullValue(CGM
.VoidPtrTy
));
3067 GetNullMemberPointerFields(MPT
, fields
);
3068 assert(!fields
.empty());
3069 llvm::Value
*FirstField
= MemPtr
;
3070 if (MemPtr
->getType()->isStructTy())
3071 FirstField
= Builder
.CreateExtractValue(MemPtr
, 0);
3072 llvm::Value
*Res
= Builder
.CreateICmpNE(FirstField
, fields
[0], "memptr.cmp0");
3074 // For function member pointers, we only need to test the function pointer
3075 // field. The other fields if any can be garbage.
3076 if (MPT
->isMemberFunctionPointer())
3079 // Otherwise, emit a series of compares and combine the results.
3080 for (int I
= 1, E
= fields
.size(); I
< E
; ++I
) {
3081 llvm::Value
*Field
= Builder
.CreateExtractValue(MemPtr
, I
);
3082 llvm::Value
*Next
= Builder
.CreateICmpNE(Field
, fields
[I
], "memptr.cmp");
3083 Res
= Builder
.CreateOr(Res
, Next
, "memptr.tobool");
3088 bool MicrosoftCXXABI::MemberPointerConstantIsNull(const MemberPointerType
*MPT
,
3089 llvm::Constant
*Val
) {
3090 // Function pointers are null if the pointer in the first field is null.
3091 if (MPT
->isMemberFunctionPointer()) {
3092 llvm::Constant
*FirstField
= Val
->getType()->isStructTy() ?
3093 Val
->getAggregateElement(0U) : Val
;
3094 return FirstField
->isNullValue();
3097 // If it's not a function pointer and it's zero initializable, we can easily
3099 if (isZeroInitializable(MPT
) && Val
->isNullValue())
3102 // Otherwise, break down all the fields for comparison. Hopefully these
3103 // little Constants are reused, while a big null struct might not be.
3104 llvm::SmallVector
<llvm::Constant
*, 4> Fields
;
3105 GetNullMemberPointerFields(MPT
, Fields
);
3106 if (Fields
.size() == 1) {
3107 assert(Val
->getType()->isIntegerTy());
3108 return Val
== Fields
[0];
3112 for (I
= 0, E
= Fields
.size(); I
!= E
; ++I
) {
3113 if (Val
->getAggregateElement(I
) != Fields
[I
])
3120 MicrosoftCXXABI::GetVBaseOffsetFromVBPtr(CodeGenFunction
&CGF
,
3122 llvm::Value
*VBPtrOffset
,
3123 llvm::Value
*VBTableOffset
,
3124 llvm::Value
**VBPtrOut
) {
3125 CGBuilderTy
&Builder
= CGF
.Builder
;
3126 // Load the vbtable pointer from the vbptr in the instance.
3127 llvm::Value
*VBPtr
= Builder
.CreateInBoundsGEP(CGM
.Int8Ty
, This
.getPointer(),
3128 VBPtrOffset
, "vbptr");
3132 CharUnits VBPtrAlign
;
3133 if (auto CI
= dyn_cast
<llvm::ConstantInt
>(VBPtrOffset
)) {
3134 VBPtrAlign
= This
.getAlignment().alignmentAtOffset(
3135 CharUnits::fromQuantity(CI
->getSExtValue()));
3137 VBPtrAlign
= CGF
.getPointerAlign();
3140 llvm::Value
*VBTable
= Builder
.CreateAlignedLoad(
3141 CGM
.Int32Ty
->getPointerTo(0), VBPtr
, VBPtrAlign
, "vbtable");
3143 // Translate from byte offset to table index. It improves analyzability.
3144 llvm::Value
*VBTableIndex
= Builder
.CreateAShr(
3145 VBTableOffset
, llvm::ConstantInt::get(VBTableOffset
->getType(), 2),
3146 "vbtindex", /*isExact=*/true);
3148 // Load an i32 offset from the vb-table.
3149 llvm::Value
*VBaseOffs
=
3150 Builder
.CreateInBoundsGEP(CGM
.Int32Ty
, VBTable
, VBTableIndex
);
3151 return Builder
.CreateAlignedLoad(CGM
.Int32Ty
, VBaseOffs
,
3152 CharUnits::fromQuantity(4), "vbase_offs");
3155 // Returns an adjusted base cast to i8*, since we do more address arithmetic on
3157 llvm::Value
*MicrosoftCXXABI::AdjustVirtualBase(
3158 CodeGenFunction
&CGF
, const Expr
*E
, const CXXRecordDecl
*RD
,
3159 Address Base
, llvm::Value
*VBTableOffset
, llvm::Value
*VBPtrOffset
) {
3160 CGBuilderTy
&Builder
= CGF
.Builder
;
3161 Base
= Base
.withElementType(CGM
.Int8Ty
);
3162 llvm::BasicBlock
*OriginalBB
= nullptr;
3163 llvm::BasicBlock
*SkipAdjustBB
= nullptr;
3164 llvm::BasicBlock
*VBaseAdjustBB
= nullptr;
3166 // In the unspecified inheritance model, there might not be a vbtable at all,
3167 // in which case we need to skip the virtual base lookup. If there is a
3168 // vbtable, the first entry is a no-op entry that gives back the original
3169 // base, so look for a virtual base adjustment offset of zero.
3171 OriginalBB
= Builder
.GetInsertBlock();
3172 VBaseAdjustBB
= CGF
.createBasicBlock("memptr.vadjust");
3173 SkipAdjustBB
= CGF
.createBasicBlock("memptr.skip_vadjust");
3174 llvm::Value
*IsVirtual
=
3175 Builder
.CreateICmpNE(VBTableOffset
, getZeroInt(),
3177 Builder
.CreateCondBr(IsVirtual
, VBaseAdjustBB
, SkipAdjustBB
);
3178 CGF
.EmitBlock(VBaseAdjustBB
);
3181 // If we weren't given a dynamic vbptr offset, RD should be complete and we'll
3182 // know the vbptr offset.
3184 CharUnits offs
= CharUnits::Zero();
3185 if (!RD
->hasDefinition()) {
3186 DiagnosticsEngine
&Diags
= CGF
.CGM
.getDiags();
3187 unsigned DiagID
= Diags
.getCustomDiagID(
3188 DiagnosticsEngine::Error
,
3189 "member pointer representation requires a "
3190 "complete class type for %0 to perform this expression");
3191 Diags
.Report(E
->getExprLoc(), DiagID
) << RD
<< E
->getSourceRange();
3192 } else if (RD
->getNumVBases())
3193 offs
= getContext().getASTRecordLayout(RD
).getVBPtrOffset();
3194 VBPtrOffset
= llvm::ConstantInt::get(CGM
.IntTy
, offs
.getQuantity());
3196 llvm::Value
*VBPtr
= nullptr;
3197 llvm::Value
*VBaseOffs
=
3198 GetVBaseOffsetFromVBPtr(CGF
, Base
, VBPtrOffset
, VBTableOffset
, &VBPtr
);
3199 llvm::Value
*AdjustedBase
=
3200 Builder
.CreateInBoundsGEP(CGM
.Int8Ty
, VBPtr
, VBaseOffs
);
3202 // Merge control flow with the case where we didn't have to adjust.
3203 if (VBaseAdjustBB
) {
3204 Builder
.CreateBr(SkipAdjustBB
);
3205 CGF
.EmitBlock(SkipAdjustBB
);
3206 llvm::PHINode
*Phi
= Builder
.CreatePHI(CGM
.Int8PtrTy
, 2, "memptr.base");
3207 Phi
->addIncoming(Base
.getPointer(), OriginalBB
);
3208 Phi
->addIncoming(AdjustedBase
, VBaseAdjustBB
);
3211 return AdjustedBase
;
3214 llvm::Value
*MicrosoftCXXABI::EmitMemberDataPointerAddress(
3215 CodeGenFunction
&CGF
, const Expr
*E
, Address Base
, llvm::Value
*MemPtr
,
3216 const MemberPointerType
*MPT
) {
3217 assert(MPT
->isMemberDataPointer());
3218 CGBuilderTy
&Builder
= CGF
.Builder
;
3219 const CXXRecordDecl
*RD
= MPT
->getMostRecentCXXRecordDecl();
3220 MSInheritanceModel Inheritance
= RD
->getMSInheritanceModel();
3222 // Extract the fields we need, regardless of model. We'll apply them if we
3224 llvm::Value
*FieldOffset
= MemPtr
;
3225 llvm::Value
*VirtualBaseAdjustmentOffset
= nullptr;
3226 llvm::Value
*VBPtrOffset
= nullptr;
3227 if (MemPtr
->getType()->isStructTy()) {
3228 // We need to extract values.
3230 FieldOffset
= Builder
.CreateExtractValue(MemPtr
, I
++);
3231 if (inheritanceModelHasVBPtrOffsetField(Inheritance
))
3232 VBPtrOffset
= Builder
.CreateExtractValue(MemPtr
, I
++);
3233 if (inheritanceModelHasVBTableOffsetField(Inheritance
))
3234 VirtualBaseAdjustmentOffset
= Builder
.CreateExtractValue(MemPtr
, I
++);
3238 if (VirtualBaseAdjustmentOffset
) {
3239 Addr
= AdjustVirtualBase(CGF
, E
, RD
, Base
, VirtualBaseAdjustmentOffset
,
3242 Addr
= Base
.getPointer();
3245 // Apply the offset, which we assume is non-null.
3246 return Builder
.CreateInBoundsGEP(CGF
.Int8Ty
, Addr
, FieldOffset
,
3251 MicrosoftCXXABI::EmitMemberPointerConversion(CodeGenFunction
&CGF
,
3254 assert(E
->getCastKind() == CK_DerivedToBaseMemberPointer
||
3255 E
->getCastKind() == CK_BaseToDerivedMemberPointer
||
3256 E
->getCastKind() == CK_ReinterpretMemberPointer
);
3258 // Use constant emission if we can.
3259 if (isa
<llvm::Constant
>(Src
))
3260 return EmitMemberPointerConversion(E
, cast
<llvm::Constant
>(Src
));
3262 // We may be adding or dropping fields from the member pointer, so we need
3263 // both types and the inheritance models of both records.
3264 const MemberPointerType
*SrcTy
=
3265 E
->getSubExpr()->getType()->castAs
<MemberPointerType
>();
3266 const MemberPointerType
*DstTy
= E
->getType()->castAs
<MemberPointerType
>();
3267 bool IsFunc
= SrcTy
->isMemberFunctionPointer();
3269 // If the classes use the same null representation, reinterpret_cast is a nop.
3270 bool IsReinterpret
= E
->getCastKind() == CK_ReinterpretMemberPointer
;
3271 if (IsReinterpret
&& IsFunc
)
3274 CXXRecordDecl
*SrcRD
= SrcTy
->getMostRecentCXXRecordDecl();
3275 CXXRecordDecl
*DstRD
= DstTy
->getMostRecentCXXRecordDecl();
3276 if (IsReinterpret
&&
3277 SrcRD
->nullFieldOffsetIsZero() == DstRD
->nullFieldOffsetIsZero())
3280 CGBuilderTy
&Builder
= CGF
.Builder
;
3282 // Branch past the conversion if Src is null.
3283 llvm::Value
*IsNotNull
= EmitMemberPointerIsNotNull(CGF
, Src
, SrcTy
);
3284 llvm::Constant
*DstNull
= EmitNullMemberPointer(DstTy
);
3286 // C++ 5.2.10p9: The null member pointer value is converted to the null member
3287 // pointer value of the destination type.
3288 if (IsReinterpret
) {
3289 // For reinterpret casts, sema ensures that src and dst are both functions
3290 // or data and have the same size, which means the LLVM types should match.
3291 assert(Src
->getType() == DstNull
->getType());
3292 return Builder
.CreateSelect(IsNotNull
, Src
, DstNull
);
3295 llvm::BasicBlock
*OriginalBB
= Builder
.GetInsertBlock();
3296 llvm::BasicBlock
*ConvertBB
= CGF
.createBasicBlock("memptr.convert");
3297 llvm::BasicBlock
*ContinueBB
= CGF
.createBasicBlock("memptr.converted");
3298 Builder
.CreateCondBr(IsNotNull
, ConvertBB
, ContinueBB
);
3299 CGF
.EmitBlock(ConvertBB
);
3301 llvm::Value
*Dst
= EmitNonNullMemberPointerConversion(
3302 SrcTy
, DstTy
, E
->getCastKind(), E
->path_begin(), E
->path_end(), Src
,
3305 Builder
.CreateBr(ContinueBB
);
3307 // In the continuation, choose between DstNull and Dst.
3308 CGF
.EmitBlock(ContinueBB
);
3309 llvm::PHINode
*Phi
= Builder
.CreatePHI(DstNull
->getType(), 2, "memptr.converted");
3310 Phi
->addIncoming(DstNull
, OriginalBB
);
3311 Phi
->addIncoming(Dst
, ConvertBB
);
3315 llvm::Value
*MicrosoftCXXABI::EmitNonNullMemberPointerConversion(
3316 const MemberPointerType
*SrcTy
, const MemberPointerType
*DstTy
, CastKind CK
,
3317 CastExpr::path_const_iterator PathBegin
,
3318 CastExpr::path_const_iterator PathEnd
, llvm::Value
*Src
,
3319 CGBuilderTy
&Builder
) {
3320 const CXXRecordDecl
*SrcRD
= SrcTy
->getMostRecentCXXRecordDecl();
3321 const CXXRecordDecl
*DstRD
= DstTy
->getMostRecentCXXRecordDecl();
3322 MSInheritanceModel SrcInheritance
= SrcRD
->getMSInheritanceModel();
3323 MSInheritanceModel DstInheritance
= DstRD
->getMSInheritanceModel();
3324 bool IsFunc
= SrcTy
->isMemberFunctionPointer();
3325 bool IsConstant
= isa
<llvm::Constant
>(Src
);
3328 llvm::Value
*FirstField
= Src
;
3329 llvm::Value
*NonVirtualBaseAdjustment
= getZeroInt();
3330 llvm::Value
*VirtualBaseAdjustmentOffset
= getZeroInt();
3331 llvm::Value
*VBPtrOffset
= getZeroInt();
3332 if (!inheritanceModelHasOnlyOneField(IsFunc
, SrcInheritance
)) {
3333 // We need to extract values.
3335 FirstField
= Builder
.CreateExtractValue(Src
, I
++);
3336 if (inheritanceModelHasNVOffsetField(IsFunc
, SrcInheritance
))
3337 NonVirtualBaseAdjustment
= Builder
.CreateExtractValue(Src
, I
++);
3338 if (inheritanceModelHasVBPtrOffsetField(SrcInheritance
))
3339 VBPtrOffset
= Builder
.CreateExtractValue(Src
, I
++);
3340 if (inheritanceModelHasVBTableOffsetField(SrcInheritance
))
3341 VirtualBaseAdjustmentOffset
= Builder
.CreateExtractValue(Src
, I
++);
3344 bool IsDerivedToBase
= (CK
== CK_DerivedToBaseMemberPointer
);
3345 const MemberPointerType
*DerivedTy
= IsDerivedToBase
? SrcTy
: DstTy
;
3346 const CXXRecordDecl
*DerivedClass
= DerivedTy
->getMostRecentCXXRecordDecl();
3348 // For data pointers, we adjust the field offset directly. For functions, we
3349 // have a separate field.
3350 llvm::Value
*&NVAdjustField
= IsFunc
? NonVirtualBaseAdjustment
: FirstField
;
3352 // The virtual inheritance model has a quirk: the virtual base table is always
3353 // referenced when dereferencing a member pointer even if the member pointer
3354 // is non-virtual. This is accounted for by adjusting the non-virtual offset
3355 // to point backwards to the top of the MDC from the first VBase. Undo this
3356 // adjustment to normalize the member pointer.
3357 llvm::Value
*SrcVBIndexEqZero
=
3358 Builder
.CreateICmpEQ(VirtualBaseAdjustmentOffset
, getZeroInt());
3359 if (SrcInheritance
== MSInheritanceModel::Virtual
) {
3360 if (int64_t SrcOffsetToFirstVBase
=
3361 getContext().getOffsetOfBaseWithVBPtr(SrcRD
).getQuantity()) {
3362 llvm::Value
*UndoSrcAdjustment
= Builder
.CreateSelect(
3364 llvm::ConstantInt::get(CGM
.IntTy
, SrcOffsetToFirstVBase
),
3366 NVAdjustField
= Builder
.CreateNSWAdd(NVAdjustField
, UndoSrcAdjustment
);
3370 // A non-zero vbindex implies that we are dealing with a source member in a
3371 // floating virtual base in addition to some non-virtual offset. If the
3372 // vbindex is zero, we are dealing with a source that exists in a non-virtual,
3373 // fixed, base. The difference between these two cases is that the vbindex +
3374 // nvoffset *always* point to the member regardless of what context they are
3375 // evaluated in so long as the vbindex is adjusted. A member inside a fixed
3376 // base requires explicit nv adjustment.
3377 llvm::Constant
*BaseClassOffset
= llvm::ConstantInt::get(
3379 CGM
.computeNonVirtualBaseClassOffset(DerivedClass
, PathBegin
, PathEnd
)
3382 llvm::Value
*NVDisp
;
3383 if (IsDerivedToBase
)
3384 NVDisp
= Builder
.CreateNSWSub(NVAdjustField
, BaseClassOffset
, "adj");
3386 NVDisp
= Builder
.CreateNSWAdd(NVAdjustField
, BaseClassOffset
, "adj");
3388 NVAdjustField
= Builder
.CreateSelect(SrcVBIndexEqZero
, NVDisp
, getZeroInt());
3390 // Update the vbindex to an appropriate value in the destination because
3391 // SrcRD's vbtable might not be a strict prefix of the one in DstRD.
3392 llvm::Value
*DstVBIndexEqZero
= SrcVBIndexEqZero
;
3393 if (inheritanceModelHasVBTableOffsetField(DstInheritance
) &&
3394 inheritanceModelHasVBTableOffsetField(SrcInheritance
)) {
3395 if (llvm::GlobalVariable
*VDispMap
=
3396 getAddrOfVirtualDisplacementMap(SrcRD
, DstRD
)) {
3397 llvm::Value
*VBIndex
= Builder
.CreateExactUDiv(
3398 VirtualBaseAdjustmentOffset
, llvm::ConstantInt::get(CGM
.IntTy
, 4));
3400 llvm::Constant
*Mapping
= VDispMap
->getInitializer();
3401 VirtualBaseAdjustmentOffset
=
3402 Mapping
->getAggregateElement(cast
<llvm::Constant
>(VBIndex
));
3404 llvm::Value
*Idxs
[] = {getZeroInt(), VBIndex
};
3405 VirtualBaseAdjustmentOffset
= Builder
.CreateAlignedLoad(
3406 CGM
.IntTy
, Builder
.CreateInBoundsGEP(VDispMap
->getValueType(),
3408 CharUnits::fromQuantity(4));
3412 Builder
.CreateICmpEQ(VirtualBaseAdjustmentOffset
, getZeroInt());
3416 // Set the VBPtrOffset to zero if the vbindex is zero. Otherwise, initialize
3417 // it to the offset of the vbptr.
3418 if (inheritanceModelHasVBPtrOffsetField(DstInheritance
)) {
3419 llvm::Value
*DstVBPtrOffset
= llvm::ConstantInt::get(
3421 getContext().getASTRecordLayout(DstRD
).getVBPtrOffset().getQuantity());
3423 Builder
.CreateSelect(DstVBIndexEqZero
, getZeroInt(), DstVBPtrOffset
);
3426 // Likewise, apply a similar adjustment so that dereferencing the member
3427 // pointer correctly accounts for the distance between the start of the first
3428 // virtual base and the top of the MDC.
3429 if (DstInheritance
== MSInheritanceModel::Virtual
) {
3430 if (int64_t DstOffsetToFirstVBase
=
3431 getContext().getOffsetOfBaseWithVBPtr(DstRD
).getQuantity()) {
3432 llvm::Value
*DoDstAdjustment
= Builder
.CreateSelect(
3434 llvm::ConstantInt::get(CGM
.IntTy
, DstOffsetToFirstVBase
),
3436 NVAdjustField
= Builder
.CreateNSWSub(NVAdjustField
, DoDstAdjustment
);
3440 // Recompose dst from the null struct and the adjusted fields from src.
3442 if (inheritanceModelHasOnlyOneField(IsFunc
, DstInheritance
)) {
3445 Dst
= llvm::UndefValue::get(ConvertMemberPointerType(DstTy
));
3447 Dst
= Builder
.CreateInsertValue(Dst
, FirstField
, Idx
++);
3448 if (inheritanceModelHasNVOffsetField(IsFunc
, DstInheritance
))
3449 Dst
= Builder
.CreateInsertValue(Dst
, NonVirtualBaseAdjustment
, Idx
++);
3450 if (inheritanceModelHasVBPtrOffsetField(DstInheritance
))
3451 Dst
= Builder
.CreateInsertValue(Dst
, VBPtrOffset
, Idx
++);
3452 if (inheritanceModelHasVBTableOffsetField(DstInheritance
))
3453 Dst
= Builder
.CreateInsertValue(Dst
, VirtualBaseAdjustmentOffset
, Idx
++);
3459 MicrosoftCXXABI::EmitMemberPointerConversion(const CastExpr
*E
,
3460 llvm::Constant
*Src
) {
3461 const MemberPointerType
*SrcTy
=
3462 E
->getSubExpr()->getType()->castAs
<MemberPointerType
>();
3463 const MemberPointerType
*DstTy
= E
->getType()->castAs
<MemberPointerType
>();
3465 CastKind CK
= E
->getCastKind();
3467 return EmitMemberPointerConversion(SrcTy
, DstTy
, CK
, E
->path_begin(),
3468 E
->path_end(), Src
);
3471 llvm::Constant
*MicrosoftCXXABI::EmitMemberPointerConversion(
3472 const MemberPointerType
*SrcTy
, const MemberPointerType
*DstTy
, CastKind CK
,
3473 CastExpr::path_const_iterator PathBegin
,
3474 CastExpr::path_const_iterator PathEnd
, llvm::Constant
*Src
) {
3475 assert(CK
== CK_DerivedToBaseMemberPointer
||
3476 CK
== CK_BaseToDerivedMemberPointer
||
3477 CK
== CK_ReinterpretMemberPointer
);
3478 // If src is null, emit a new null for dst. We can't return src because dst
3479 // might have a new representation.
3480 if (MemberPointerConstantIsNull(SrcTy
, Src
))
3481 return EmitNullMemberPointer(DstTy
);
3483 // We don't need to do anything for reinterpret_casts of non-null member
3484 // pointers. We should only get here when the two type representations have
3486 if (CK
== CK_ReinterpretMemberPointer
)
3489 CGBuilderTy
Builder(CGM
, CGM
.getLLVMContext());
3490 auto *Dst
= cast
<llvm::Constant
>(EmitNonNullMemberPointerConversion(
3491 SrcTy
, DstTy
, CK
, PathBegin
, PathEnd
, Src
, Builder
));
3496 CGCallee
MicrosoftCXXABI::EmitLoadOfMemberFunctionPointer(
3497 CodeGenFunction
&CGF
, const Expr
*E
, Address This
,
3498 llvm::Value
*&ThisPtrForCall
, llvm::Value
*MemPtr
,
3499 const MemberPointerType
*MPT
) {
3500 assert(MPT
->isMemberFunctionPointer());
3501 const FunctionProtoType
*FPT
=
3502 MPT
->getPointeeType()->castAs
<FunctionProtoType
>();
3503 const CXXRecordDecl
*RD
= MPT
->getMostRecentCXXRecordDecl();
3504 CGBuilderTy
&Builder
= CGF
.Builder
;
3506 MSInheritanceModel Inheritance
= RD
->getMSInheritanceModel();
3508 // Extract the fields we need, regardless of model. We'll apply them if we
3510 llvm::Value
*FunctionPointer
= MemPtr
;
3511 llvm::Value
*NonVirtualBaseAdjustment
= nullptr;
3512 llvm::Value
*VirtualBaseAdjustmentOffset
= nullptr;
3513 llvm::Value
*VBPtrOffset
= nullptr;
3514 if (MemPtr
->getType()->isStructTy()) {
3515 // We need to extract values.
3517 FunctionPointer
= Builder
.CreateExtractValue(MemPtr
, I
++);
3518 if (inheritanceModelHasNVOffsetField(MPT
, Inheritance
))
3519 NonVirtualBaseAdjustment
= Builder
.CreateExtractValue(MemPtr
, I
++);
3520 if (inheritanceModelHasVBPtrOffsetField(Inheritance
))
3521 VBPtrOffset
= Builder
.CreateExtractValue(MemPtr
, I
++);
3522 if (inheritanceModelHasVBTableOffsetField(Inheritance
))
3523 VirtualBaseAdjustmentOffset
= Builder
.CreateExtractValue(MemPtr
, I
++);
3526 if (VirtualBaseAdjustmentOffset
) {
3527 ThisPtrForCall
= AdjustVirtualBase(CGF
, E
, RD
, This
,
3528 VirtualBaseAdjustmentOffset
, VBPtrOffset
);
3530 ThisPtrForCall
= This
.getPointer();
3533 if (NonVirtualBaseAdjustment
)
3534 ThisPtrForCall
= Builder
.CreateInBoundsGEP(CGF
.Int8Ty
, ThisPtrForCall
,
3535 NonVirtualBaseAdjustment
);
3537 CGCallee
Callee(FPT
, FunctionPointer
);
3541 CGCXXABI
*clang::CodeGen::CreateMicrosoftCXXABI(CodeGenModule
&CGM
) {
3542 return new MicrosoftCXXABI(CGM
);
3545 // MS RTTI Overview:
3546 // The run time type information emitted by cl.exe contains 5 distinct types of
3547 // structures. Many of them reference each other.
3549 // TypeInfo: Static classes that are returned by typeid.
3551 // CompleteObjectLocator: Referenced by vftables. They contain information
3552 // required for dynamic casting, including OffsetFromTop. They also contain
3553 // a reference to the TypeInfo for the type and a reference to the
3554 // CompleteHierarchyDescriptor for the type.
3556 // ClassHierarchyDescriptor: Contains information about a class hierarchy.
3557 // Used during dynamic_cast to walk a class hierarchy. References a base
3558 // class array and the size of said array.
3560 // BaseClassArray: Contains a list of classes in a hierarchy. BaseClassArray is
3561 // somewhat of a misnomer because the most derived class is also in the list
3562 // as well as multiple copies of virtual bases (if they occur multiple times
3563 // in the hierarchy.) The BaseClassArray contains one BaseClassDescriptor for
3564 // every path in the hierarchy, in pre-order depth first order. Note, we do
3565 // not declare a specific llvm type for BaseClassArray, it's merely an array
3566 // of BaseClassDescriptor pointers.
3568 // BaseClassDescriptor: Contains information about a class in a class hierarchy.
3569 // BaseClassDescriptor is also somewhat of a misnomer for the same reason that
3570 // BaseClassArray is. It contains information about a class within a
3571 // hierarchy such as: is this base is ambiguous and what is its offset in the
3572 // vbtable. The names of the BaseClassDescriptors have all of their fields
3573 // mangled into them so they can be aggressively deduplicated by the linker.
3575 static llvm::GlobalVariable
*getTypeInfoVTable(CodeGenModule
&CGM
) {
3576 StringRef
MangledName("??_7type_info@@6B@");
3577 if (auto VTable
= CGM
.getModule().getNamedGlobal(MangledName
))
3579 return new llvm::GlobalVariable(CGM
.getModule(), CGM
.Int8PtrTy
,
3580 /*isConstant=*/true,
3581 llvm::GlobalVariable::ExternalLinkage
,
3582 /*Initializer=*/nullptr, MangledName
);
3587 /// A Helper struct that stores information about a class in a class
3588 /// hierarchy. The information stored in these structs struct is used during
3589 /// the generation of ClassHierarchyDescriptors and BaseClassDescriptors.
3590 // During RTTI creation, MSRTTIClasses are stored in a contiguous array with
3591 // implicit depth first pre-order tree connectivity. getFirstChild and
3592 // getNextSibling allow us to walk the tree efficiently.
3593 struct MSRTTIClass
{
3595 IsPrivateOnPath
= 1 | 8,
3599 HasHierarchyDescriptor
= 64
3601 MSRTTIClass(const CXXRecordDecl
*RD
) : RD(RD
) {}
3602 uint32_t initialize(const MSRTTIClass
*Parent
,
3603 const CXXBaseSpecifier
*Specifier
);
3605 MSRTTIClass
*getFirstChild() { return this + 1; }
3606 static MSRTTIClass
*getNextChild(MSRTTIClass
*Child
) {
3607 return Child
+ 1 + Child
->NumBases
;
3610 const CXXRecordDecl
*RD
, *VirtualRoot
;
3611 uint32_t Flags
, NumBases
, OffsetInVBase
;
3614 /// Recursively initialize the base class array.
3615 uint32_t MSRTTIClass::initialize(const MSRTTIClass
*Parent
,
3616 const CXXBaseSpecifier
*Specifier
) {
3617 Flags
= HasHierarchyDescriptor
;
3619 VirtualRoot
= nullptr;
3622 if (Specifier
->getAccessSpecifier() != AS_public
)
3623 Flags
|= IsPrivate
| IsPrivateOnPath
;
3624 if (Specifier
->isVirtual()) {
3629 if (Parent
->Flags
& IsPrivateOnPath
)
3630 Flags
|= IsPrivateOnPath
;
3631 VirtualRoot
= Parent
->VirtualRoot
;
3632 OffsetInVBase
= Parent
->OffsetInVBase
+ RD
->getASTContext()
3633 .getASTRecordLayout(Parent
->RD
).getBaseClassOffset(RD
).getQuantity();
3637 MSRTTIClass
*Child
= getFirstChild();
3638 for (const CXXBaseSpecifier
&Base
: RD
->bases()) {
3639 NumBases
+= Child
->initialize(this, &Base
) + 1;
3640 Child
= getNextChild(Child
);
3645 static llvm::GlobalValue::LinkageTypes
getLinkageForRTTI(QualType Ty
) {
3646 switch (Ty
->getLinkage()) {
3648 case InternalLinkage
:
3649 case UniqueExternalLinkage
:
3650 return llvm::GlobalValue::InternalLinkage
;
3652 case VisibleNoLinkage
:
3654 case ExternalLinkage
:
3655 return llvm::GlobalValue::LinkOnceODRLinkage
;
3657 llvm_unreachable("Invalid linkage!");
3660 /// An ephemeral helper class for building MS RTTI types. It caches some
3661 /// calls to the module and information about the most derived class in a
3663 struct MSRTTIBuilder
{
3665 HasBranchingHierarchy
= 1,
3666 HasVirtualBranchingHierarchy
= 2,
3667 HasAmbiguousBases
= 4
3670 MSRTTIBuilder(MicrosoftCXXABI
&ABI
, const CXXRecordDecl
*RD
)
3671 : CGM(ABI
.CGM
), Context(CGM
.getContext()),
3672 VMContext(CGM
.getLLVMContext()), Module(CGM
.getModule()), RD(RD
),
3673 Linkage(getLinkageForRTTI(CGM
.getContext().getTagDeclType(RD
))),
3676 llvm::GlobalVariable
*getBaseClassDescriptor(const MSRTTIClass
&Classes
);
3677 llvm::GlobalVariable
*
3678 getBaseClassArray(SmallVectorImpl
<MSRTTIClass
> &Classes
);
3679 llvm::GlobalVariable
*getClassHierarchyDescriptor();
3680 llvm::GlobalVariable
*getCompleteObjectLocator(const VPtrInfo
&Info
);
3683 ASTContext
&Context
;
3684 llvm::LLVMContext
&VMContext
;
3685 llvm::Module
&Module
;
3686 const CXXRecordDecl
*RD
;
3687 llvm::GlobalVariable::LinkageTypes Linkage
;
3688 MicrosoftCXXABI
&ABI
;
3693 /// Recursively serializes a class hierarchy in pre-order depth first
3695 static void serializeClassHierarchy(SmallVectorImpl
<MSRTTIClass
> &Classes
,
3696 const CXXRecordDecl
*RD
) {
3697 Classes
.push_back(MSRTTIClass(RD
));
3698 for (const CXXBaseSpecifier
&Base
: RD
->bases())
3699 serializeClassHierarchy(Classes
, Base
.getType()->getAsCXXRecordDecl());
3702 /// Find ambiguity among base classes.
3704 detectAmbiguousBases(SmallVectorImpl
<MSRTTIClass
> &Classes
) {
3705 llvm::SmallPtrSet
<const CXXRecordDecl
*, 8> VirtualBases
;
3706 llvm::SmallPtrSet
<const CXXRecordDecl
*, 8> UniqueBases
;
3707 llvm::SmallPtrSet
<const CXXRecordDecl
*, 8> AmbiguousBases
;
3708 for (MSRTTIClass
*Class
= &Classes
.front(); Class
<= &Classes
.back();) {
3709 if ((Class
->Flags
& MSRTTIClass::IsVirtual
) &&
3710 !VirtualBases
.insert(Class
->RD
).second
) {
3711 Class
= MSRTTIClass::getNextChild(Class
);
3714 if (!UniqueBases
.insert(Class
->RD
).second
)
3715 AmbiguousBases
.insert(Class
->RD
);
3718 if (AmbiguousBases
.empty())
3720 for (MSRTTIClass
&Class
: Classes
)
3721 if (AmbiguousBases
.count(Class
.RD
))
3722 Class
.Flags
|= MSRTTIClass::IsAmbiguous
;
3725 llvm::GlobalVariable
*MSRTTIBuilder::getClassHierarchyDescriptor() {
3726 SmallString
<256> MangledName
;
3728 llvm::raw_svector_ostream
Out(MangledName
);
3729 ABI
.getMangleContext().mangleCXXRTTIClassHierarchyDescriptor(RD
, Out
);
3732 // Check to see if we've already declared this ClassHierarchyDescriptor.
3733 if (auto CHD
= Module
.getNamedGlobal(MangledName
))
3736 // Serialize the class hierarchy and initialize the CHD Fields.
3737 SmallVector
<MSRTTIClass
, 8> Classes
;
3738 serializeClassHierarchy(Classes
, RD
);
3739 Classes
.front().initialize(/*Parent=*/nullptr, /*Specifier=*/nullptr);
3740 detectAmbiguousBases(Classes
);
3742 for (const MSRTTIClass
&Class
: Classes
) {
3743 if (Class
.RD
->getNumBases() > 1)
3744 Flags
|= HasBranchingHierarchy
;
3745 // Note: cl.exe does not calculate "HasAmbiguousBases" correctly. We
3746 // believe the field isn't actually used.
3747 if (Class
.Flags
& MSRTTIClass::IsAmbiguous
)
3748 Flags
|= HasAmbiguousBases
;
3750 if ((Flags
& HasBranchingHierarchy
) && RD
->getNumVBases() != 0)
3751 Flags
|= HasVirtualBranchingHierarchy
;
3752 // These gep indices are used to get the address of the first element of the
3753 // base class array.
3754 llvm::Value
*GEPIndices
[] = {llvm::ConstantInt::get(CGM
.IntTy
, 0),
3755 llvm::ConstantInt::get(CGM
.IntTy
, 0)};
3757 // Forward-declare the class hierarchy descriptor
3758 auto Type
= ABI
.getClassHierarchyDescriptorType();
3759 auto CHD
= new llvm::GlobalVariable(Module
, Type
, /*isConstant=*/true, Linkage
,
3760 /*Initializer=*/nullptr,
3762 if (CHD
->isWeakForLinker())
3763 CHD
->setComdat(CGM
.getModule().getOrInsertComdat(CHD
->getName()));
3765 auto *Bases
= getBaseClassArray(Classes
);
3767 // Initialize the base class ClassHierarchyDescriptor.
3768 llvm::Constant
*Fields
[] = {
3769 llvm::ConstantInt::get(CGM
.IntTy
, 0), // reserved by the runtime
3770 llvm::ConstantInt::get(CGM
.IntTy
, Flags
),
3771 llvm::ConstantInt::get(CGM
.IntTy
, Classes
.size()),
3772 ABI
.getImageRelativeConstant(llvm::ConstantExpr::getInBoundsGetElementPtr(
3773 Bases
->getValueType(), Bases
,
3774 llvm::ArrayRef
<llvm::Value
*>(GEPIndices
))),
3776 CHD
->setInitializer(llvm::ConstantStruct::get(Type
, Fields
));
3780 llvm::GlobalVariable
*
3781 MSRTTIBuilder::getBaseClassArray(SmallVectorImpl
<MSRTTIClass
> &Classes
) {
3782 SmallString
<256> MangledName
;
3784 llvm::raw_svector_ostream
Out(MangledName
);
3785 ABI
.getMangleContext().mangleCXXRTTIBaseClassArray(RD
, Out
);
3788 // Forward-declare the base class array.
3789 // cl.exe pads the base class array with 1 (in 32 bit mode) or 4 (in 64 bit
3790 // mode) bytes of padding. We provide a pointer sized amount of padding by
3791 // adding +1 to Classes.size(). The sections have pointer alignment and are
3792 // marked pick-any so it shouldn't matter.
3793 llvm::Type
*PtrType
= ABI
.getImageRelativeType(
3794 ABI
.getBaseClassDescriptorType()->getPointerTo());
3795 auto *ArrType
= llvm::ArrayType::get(PtrType
, Classes
.size() + 1);
3797 new llvm::GlobalVariable(Module
, ArrType
,
3798 /*isConstant=*/true, Linkage
,
3799 /*Initializer=*/nullptr, MangledName
);
3800 if (BCA
->isWeakForLinker())
3801 BCA
->setComdat(CGM
.getModule().getOrInsertComdat(BCA
->getName()));
3803 // Initialize the BaseClassArray.
3804 SmallVector
<llvm::Constant
*, 8> BaseClassArrayData
;
3805 for (MSRTTIClass
&Class
: Classes
)
3806 BaseClassArrayData
.push_back(
3807 ABI
.getImageRelativeConstant(getBaseClassDescriptor(Class
)));
3808 BaseClassArrayData
.push_back(llvm::Constant::getNullValue(PtrType
));
3809 BCA
->setInitializer(llvm::ConstantArray::get(ArrType
, BaseClassArrayData
));
3813 llvm::GlobalVariable
*
3814 MSRTTIBuilder::getBaseClassDescriptor(const MSRTTIClass
&Class
) {
3815 // Compute the fields for the BaseClassDescriptor. They are computed up front
3816 // because they are mangled into the name of the object.
3817 uint32_t OffsetInVBTable
= 0;
3818 int32_t VBPtrOffset
= -1;
3819 if (Class
.VirtualRoot
) {
3820 auto &VTableContext
= CGM
.getMicrosoftVTableContext();
3821 OffsetInVBTable
= VTableContext
.getVBTableIndex(RD
, Class
.VirtualRoot
) * 4;
3822 VBPtrOffset
= Context
.getASTRecordLayout(RD
).getVBPtrOffset().getQuantity();
3825 SmallString
<256> MangledName
;
3827 llvm::raw_svector_ostream
Out(MangledName
);
3828 ABI
.getMangleContext().mangleCXXRTTIBaseClassDescriptor(
3829 Class
.RD
, Class
.OffsetInVBase
, VBPtrOffset
, OffsetInVBTable
,
3833 // Check to see if we've already declared this object.
3834 if (auto BCD
= Module
.getNamedGlobal(MangledName
))
3837 // Forward-declare the base class descriptor.
3838 auto Type
= ABI
.getBaseClassDescriptorType();
3840 new llvm::GlobalVariable(Module
, Type
, /*isConstant=*/true, Linkage
,
3841 /*Initializer=*/nullptr, MangledName
);
3842 if (BCD
->isWeakForLinker())
3843 BCD
->setComdat(CGM
.getModule().getOrInsertComdat(BCD
->getName()));
3845 // Initialize the BaseClassDescriptor.
3846 llvm::Constant
*Fields
[] = {
3847 ABI
.getImageRelativeConstant(
3848 ABI
.getAddrOfRTTIDescriptor(Context
.getTypeDeclType(Class
.RD
))),
3849 llvm::ConstantInt::get(CGM
.IntTy
, Class
.NumBases
),
3850 llvm::ConstantInt::get(CGM
.IntTy
, Class
.OffsetInVBase
),
3851 llvm::ConstantInt::get(CGM
.IntTy
, VBPtrOffset
),
3852 llvm::ConstantInt::get(CGM
.IntTy
, OffsetInVBTable
),
3853 llvm::ConstantInt::get(CGM
.IntTy
, Class
.Flags
),
3854 ABI
.getImageRelativeConstant(
3855 MSRTTIBuilder(ABI
, Class
.RD
).getClassHierarchyDescriptor()),
3857 BCD
->setInitializer(llvm::ConstantStruct::get(Type
, Fields
));
3861 llvm::GlobalVariable
*
3862 MSRTTIBuilder::getCompleteObjectLocator(const VPtrInfo
&Info
) {
3863 SmallString
<256> MangledName
;
3865 llvm::raw_svector_ostream
Out(MangledName
);
3866 ABI
.getMangleContext().mangleCXXRTTICompleteObjectLocator(RD
, Info
.MangledPath
, Out
);
3869 // Check to see if we've already computed this complete object locator.
3870 if (auto COL
= Module
.getNamedGlobal(MangledName
))
3873 // Compute the fields of the complete object locator.
3874 int OffsetToTop
= Info
.FullOffsetInMDC
.getQuantity();
3875 int VFPtrOffset
= 0;
3876 // The offset includes the vtordisp if one exists.
3877 if (const CXXRecordDecl
*VBase
= Info
.getVBaseWithVPtr())
3878 if (Context
.getASTRecordLayout(RD
)
3879 .getVBaseOffsetsMap()
3881 ->second
.hasVtorDisp())
3882 VFPtrOffset
= Info
.NonVirtualOffset
.getQuantity() + 4;
3884 // Forward-declare the complete object locator.
3885 llvm::StructType
*Type
= ABI
.getCompleteObjectLocatorType();
3886 auto COL
= new llvm::GlobalVariable(Module
, Type
, /*isConstant=*/true, Linkage
,
3887 /*Initializer=*/nullptr, MangledName
);
3889 // Initialize the CompleteObjectLocator.
3890 llvm::Constant
*Fields
[] = {
3891 llvm::ConstantInt::get(CGM
.IntTy
, ABI
.isImageRelative()),
3892 llvm::ConstantInt::get(CGM
.IntTy
, OffsetToTop
),
3893 llvm::ConstantInt::get(CGM
.IntTy
, VFPtrOffset
),
3894 ABI
.getImageRelativeConstant(
3895 CGM
.GetAddrOfRTTIDescriptor(Context
.getTypeDeclType(RD
))),
3896 ABI
.getImageRelativeConstant(getClassHierarchyDescriptor()),
3897 ABI
.getImageRelativeConstant(COL
),
3899 llvm::ArrayRef
<llvm::Constant
*> FieldsRef(Fields
);
3900 if (!ABI
.isImageRelative())
3901 FieldsRef
= FieldsRef
.drop_back();
3902 COL
->setInitializer(llvm::ConstantStruct::get(Type
, FieldsRef
));
3903 if (COL
->isWeakForLinker())
3904 COL
->setComdat(CGM
.getModule().getOrInsertComdat(COL
->getName()));
3908 static QualType
decomposeTypeForEH(ASTContext
&Context
, QualType T
,
3909 bool &IsConst
, bool &IsVolatile
,
3910 bool &IsUnaligned
) {
3911 T
= Context
.getExceptionObjectType(T
);
3913 // C++14 [except.handle]p3:
3914 // A handler is a match for an exception object of type E if [...]
3915 // - the handler is of type cv T or const T& where T is a pointer type and
3916 // E is a pointer type that can be converted to T by [...]
3917 // - a qualification conversion
3920 IsUnaligned
= false;
3921 QualType PointeeType
= T
->getPointeeType();
3922 if (!PointeeType
.isNull()) {
3923 IsConst
= PointeeType
.isConstQualified();
3924 IsVolatile
= PointeeType
.isVolatileQualified();
3925 IsUnaligned
= PointeeType
.getQualifiers().hasUnaligned();
3928 // Member pointer types like "const int A::*" are represented by having RTTI
3929 // for "int A::*" and separately storing the const qualifier.
3930 if (const auto *MPTy
= T
->getAs
<MemberPointerType
>())
3931 T
= Context
.getMemberPointerType(PointeeType
.getUnqualifiedType(),
3934 // Pointer types like "const int * const *" are represented by having RTTI
3935 // for "const int **" and separately storing the const qualifier.
3936 if (T
->isPointerType())
3937 T
= Context
.getPointerType(PointeeType
.getUnqualifiedType());
3943 MicrosoftCXXABI::getAddrOfCXXCatchHandlerType(QualType Type
,
3944 QualType CatchHandlerType
) {
3945 // TypeDescriptors for exceptions never have qualified pointer types,
3946 // qualifiers are stored separately in order to support qualification
3948 bool IsConst
, IsVolatile
, IsUnaligned
;
3950 decomposeTypeForEH(getContext(), Type
, IsConst
, IsVolatile
, IsUnaligned
);
3952 bool IsReference
= CatchHandlerType
->isReferenceType();
3964 return CatchTypeInfo
{getAddrOfRTTIDescriptor(Type
)->stripPointerCasts(),
3968 /// Gets a TypeDescriptor. Returns a llvm::Constant * rather than a
3969 /// llvm::GlobalVariable * because different type descriptors have different
3970 /// types, and need to be abstracted. They are abstracting by casting the
3971 /// address to an Int8PtrTy.
3972 llvm::Constant
*MicrosoftCXXABI::getAddrOfRTTIDescriptor(QualType Type
) {
3973 SmallString
<256> MangledName
;
3975 llvm::raw_svector_ostream
Out(MangledName
);
3976 getMangleContext().mangleCXXRTTI(Type
, Out
);
3979 // Check to see if we've already declared this TypeDescriptor.
3980 if (llvm::GlobalVariable
*GV
= CGM
.getModule().getNamedGlobal(MangledName
))
3981 return llvm::ConstantExpr::getBitCast(GV
, CGM
.Int8PtrTy
);
3983 // Note for the future: If we would ever like to do deferred emission of
3984 // RTTI, check if emitting vtables opportunistically need any adjustment.
3986 // Compute the fields for the TypeDescriptor.
3987 SmallString
<256> TypeInfoString
;
3989 llvm::raw_svector_ostream
Out(TypeInfoString
);
3990 getMangleContext().mangleCXXRTTIName(Type
, Out
);
3993 // Declare and initialize the TypeDescriptor.
3994 llvm::Constant
*Fields
[] = {
3995 getTypeInfoVTable(CGM
), // VFPtr
3996 llvm::ConstantPointerNull::get(CGM
.Int8PtrTy
), // Runtime data
3997 llvm::ConstantDataArray::getString(CGM
.getLLVMContext(), TypeInfoString
)};
3998 llvm::StructType
*TypeDescriptorType
=
3999 getTypeDescriptorType(TypeInfoString
);
4000 auto *Var
= new llvm::GlobalVariable(
4001 CGM
.getModule(), TypeDescriptorType
, /*isConstant=*/false,
4002 getLinkageForRTTI(Type
),
4003 llvm::ConstantStruct::get(TypeDescriptorType
, Fields
),
4005 if (Var
->isWeakForLinker())
4006 Var
->setComdat(CGM
.getModule().getOrInsertComdat(Var
->getName()));
4007 return llvm::ConstantExpr::getBitCast(Var
, CGM
.Int8PtrTy
);
4010 /// Gets or a creates a Microsoft CompleteObjectLocator.
4011 llvm::GlobalVariable
*
4012 MicrosoftCXXABI::getMSCompleteObjectLocator(const CXXRecordDecl
*RD
,
4013 const VPtrInfo
&Info
) {
4014 return MSRTTIBuilder(*this, RD
).getCompleteObjectLocator(Info
);
4017 void MicrosoftCXXABI::emitCXXStructor(GlobalDecl GD
) {
4018 if (auto *ctor
= dyn_cast
<CXXConstructorDecl
>(GD
.getDecl())) {
4019 // There are no constructor variants, always emit the complete destructor.
4020 llvm::Function
*Fn
=
4021 CGM
.codegenCXXStructor(GD
.getWithCtorType(Ctor_Complete
));
4022 CGM
.maybeSetTrivialComdat(*ctor
, *Fn
);
4026 auto *dtor
= cast
<CXXDestructorDecl
>(GD
.getDecl());
4028 // Emit the base destructor if the base and complete (vbase) destructors are
4029 // equivalent. This effectively implements -mconstructor-aliases as part of
4031 if (GD
.getDtorType() == Dtor_Complete
&&
4032 dtor
->getParent()->getNumVBases() == 0)
4033 GD
= GD
.getWithDtorType(Dtor_Base
);
4035 // The base destructor is equivalent to the base destructor of its
4036 // base class if there is exactly one non-virtual base class with a
4037 // non-trivial destructor, there are no fields with a non-trivial
4038 // destructor, and the body of the destructor is trivial.
4039 if (GD
.getDtorType() == Dtor_Base
&& !CGM
.TryEmitBaseDestructorAsAlias(dtor
))
4042 llvm::Function
*Fn
= CGM
.codegenCXXStructor(GD
);
4043 if (Fn
->isWeakForLinker())
4044 Fn
->setComdat(CGM
.getModule().getOrInsertComdat(Fn
->getName()));
4048 MicrosoftCXXABI::getAddrOfCXXCtorClosure(const CXXConstructorDecl
*CD
,
4050 assert(CT
== Ctor_CopyingClosure
|| CT
== Ctor_DefaultClosure
);
4052 // Calculate the mangled name.
4053 SmallString
<256> ThunkName
;
4054 llvm::raw_svector_ostream
Out(ThunkName
);
4055 getMangleContext().mangleName(GlobalDecl(CD
, CT
), Out
);
4057 // If the thunk has been generated previously, just return it.
4058 if (llvm::GlobalValue
*GV
= CGM
.getModule().getNamedValue(ThunkName
))
4059 return cast
<llvm::Function
>(GV
);
4061 // Create the llvm::Function.
4062 const CGFunctionInfo
&FnInfo
= CGM
.getTypes().arrangeMSCtorClosure(CD
, CT
);
4063 llvm::FunctionType
*ThunkTy
= CGM
.getTypes().GetFunctionType(FnInfo
);
4064 const CXXRecordDecl
*RD
= CD
->getParent();
4065 QualType RecordTy
= getContext().getRecordType(RD
);
4066 llvm::Function
*ThunkFn
= llvm::Function::Create(
4067 ThunkTy
, getLinkageForRTTI(RecordTy
), ThunkName
.str(), &CGM
.getModule());
4068 ThunkFn
->setCallingConv(static_cast<llvm::CallingConv::ID
>(
4069 FnInfo
.getEffectiveCallingConvention()));
4070 if (ThunkFn
->isWeakForLinker())
4071 ThunkFn
->setComdat(CGM
.getModule().getOrInsertComdat(ThunkFn
->getName()));
4072 bool IsCopy
= CT
== Ctor_CopyingClosure
;
4075 CodeGenFunction
CGF(CGM
);
4076 CGF
.CurGD
= GlobalDecl(CD
, Ctor_Complete
);
4078 // Build FunctionArgs.
4079 FunctionArgList FunctionArgs
;
4081 // A constructor always starts with a 'this' pointer as its first argument.
4082 buildThisParam(CGF
, FunctionArgs
);
4084 // Following the 'this' pointer is a reference to the source object that we
4085 // are copying from.
4086 ImplicitParamDecl
SrcParam(
4087 getContext(), /*DC=*/nullptr, SourceLocation(),
4088 &getContext().Idents
.get("src"),
4089 getContext().getLValueReferenceType(RecordTy
,
4090 /*SpelledAsLValue=*/true),
4091 ImplicitParamDecl::Other
);
4093 FunctionArgs
.push_back(&SrcParam
);
4095 // Constructors for classes which utilize virtual bases have an additional
4096 // parameter which indicates whether or not it is being delegated to by a more
4097 // derived constructor.
4098 ImplicitParamDecl
IsMostDerived(getContext(), /*DC=*/nullptr,
4100 &getContext().Idents
.get("is_most_derived"),
4101 getContext().IntTy
, ImplicitParamDecl::Other
);
4102 // Only add the parameter to the list if the class has virtual bases.
4103 if (RD
->getNumVBases() > 0)
4104 FunctionArgs
.push_back(&IsMostDerived
);
4106 // Start defining the function.
4107 auto NL
= ApplyDebugLocation::CreateEmpty(CGF
);
4108 CGF
.StartFunction(GlobalDecl(), FnInfo
.getReturnType(), ThunkFn
, FnInfo
,
4109 FunctionArgs
, CD
->getLocation(), SourceLocation());
4110 // Create a scope with an artificial location for the body of this function.
4111 auto AL
= ApplyDebugLocation::CreateArtificial(CGF
);
4112 setCXXABIThisValue(CGF
, loadIncomingCXXThis(CGF
));
4113 llvm::Value
*This
= getThisValue(CGF
);
4115 llvm::Value
*SrcVal
=
4116 IsCopy
? CGF
.Builder
.CreateLoad(CGF
.GetAddrOfLocalVar(&SrcParam
), "src")
4121 // Push the this ptr.
4122 Args
.add(RValue::get(This
), CD
->getThisType());
4124 // Push the src ptr.
4126 Args
.add(RValue::get(SrcVal
), SrcParam
.getType());
4128 // Add the rest of the default arguments.
4129 SmallVector
<const Stmt
*, 4> ArgVec
;
4130 ArrayRef
<ParmVarDecl
*> params
= CD
->parameters().drop_front(IsCopy
? 1 : 0);
4131 for (const ParmVarDecl
*PD
: params
) {
4132 assert(PD
->hasDefaultArg() && "ctor closure lacks default args");
4133 ArgVec
.push_back(PD
->getDefaultArg());
4136 CodeGenFunction::RunCleanupsScope
Cleanups(CGF
);
4138 const auto *FPT
= CD
->getType()->castAs
<FunctionProtoType
>();
4139 CGF
.EmitCallArgs(Args
, FPT
, llvm::ArrayRef(ArgVec
), CD
, IsCopy
? 1 : 0);
4141 // Insert any ABI-specific implicit constructor arguments.
4142 AddedStructorArgCounts ExtraArgs
=
4143 addImplicitConstructorArgs(CGF
, CD
, Ctor_Complete
,
4144 /*ForVirtualBase=*/false,
4145 /*Delegating=*/false, Args
);
4146 // Call the destructor with our arguments.
4147 llvm::Constant
*CalleePtr
=
4148 CGM
.getAddrOfCXXStructor(GlobalDecl(CD
, Ctor_Complete
));
4150 CGCallee::forDirect(CalleePtr
, GlobalDecl(CD
, Ctor_Complete
));
4151 const CGFunctionInfo
&CalleeInfo
= CGM
.getTypes().arrangeCXXConstructorCall(
4152 Args
, CD
, Ctor_Complete
, ExtraArgs
.Prefix
, ExtraArgs
.Suffix
);
4153 CGF
.EmitCall(CalleeInfo
, Callee
, ReturnValueSlot(), Args
);
4155 Cleanups
.ForceCleanup();
4157 // Emit the ret instruction, remove any temporary instructions created for the
4159 CGF
.FinishFunction(SourceLocation());
4164 llvm::Constant
*MicrosoftCXXABI::getCatchableType(QualType T
,
4166 int32_t VBPtrOffset
,
4168 assert(!T
->isReferenceType());
4170 CXXRecordDecl
*RD
= T
->getAsCXXRecordDecl();
4171 const CXXConstructorDecl
*CD
=
4172 RD
? CGM
.getContext().getCopyConstructorForExceptionObject(RD
) : nullptr;
4173 CXXCtorType CT
= Ctor_Complete
;
4175 if (!hasDefaultCXXMethodCC(getContext(), CD
) || CD
->getNumParams() != 1)
4176 CT
= Ctor_CopyingClosure
;
4178 uint32_t Size
= getContext().getTypeSizeInChars(T
).getQuantity();
4179 SmallString
<256> MangledName
;
4181 llvm::raw_svector_ostream
Out(MangledName
);
4182 getMangleContext().mangleCXXCatchableType(T
, CD
, CT
, Size
, NVOffset
,
4183 VBPtrOffset
, VBIndex
, Out
);
4185 if (llvm::GlobalVariable
*GV
= CGM
.getModule().getNamedGlobal(MangledName
))
4186 return getImageRelativeConstant(GV
);
4188 // The TypeDescriptor is used by the runtime to determine if a catch handler
4189 // is appropriate for the exception object.
4190 llvm::Constant
*TD
= getImageRelativeConstant(getAddrOfRTTIDescriptor(T
));
4192 // The runtime is responsible for calling the copy constructor if the
4193 // exception is caught by value.
4194 llvm::Constant
*CopyCtor
;
4196 if (CT
== Ctor_CopyingClosure
)
4197 CopyCtor
= getAddrOfCXXCtorClosure(CD
, Ctor_CopyingClosure
);
4199 CopyCtor
= CGM
.getAddrOfCXXStructor(GlobalDecl(CD
, Ctor_Complete
));
4201 CopyCtor
= llvm::ConstantExpr::getBitCast(CopyCtor
, CGM
.Int8PtrTy
);
4203 CopyCtor
= llvm::Constant::getNullValue(CGM
.Int8PtrTy
);
4205 CopyCtor
= getImageRelativeConstant(CopyCtor
);
4207 bool IsScalar
= !RD
;
4208 bool HasVirtualBases
= false;
4209 bool IsStdBadAlloc
= false; // std::bad_alloc is special for some reason.
4210 QualType PointeeType
= T
;
4211 if (T
->isPointerType())
4212 PointeeType
= T
->getPointeeType();
4213 if (const CXXRecordDecl
*RD
= PointeeType
->getAsCXXRecordDecl()) {
4214 HasVirtualBases
= RD
->getNumVBases() > 0;
4215 if (IdentifierInfo
*II
= RD
->getIdentifier())
4216 IsStdBadAlloc
= II
->isStr("bad_alloc") && RD
->isInStdNamespace();
4219 // Encode the relevant CatchableType properties into the Flags bitfield.
4220 // FIXME: Figure out how bits 2 or 8 can get set.
4224 if (HasVirtualBases
)
4229 llvm::Constant
*Fields
[] = {
4230 llvm::ConstantInt::get(CGM
.IntTy
, Flags
), // Flags
4231 TD
, // TypeDescriptor
4232 llvm::ConstantInt::get(CGM
.IntTy
, NVOffset
), // NonVirtualAdjustment
4233 llvm::ConstantInt::get(CGM
.IntTy
, VBPtrOffset
), // OffsetToVBPtr
4234 llvm::ConstantInt::get(CGM
.IntTy
, VBIndex
), // VBTableIndex
4235 llvm::ConstantInt::get(CGM
.IntTy
, Size
), // Size
4236 CopyCtor
// CopyCtor
4238 llvm::StructType
*CTType
= getCatchableTypeType();
4239 auto *GV
= new llvm::GlobalVariable(
4240 CGM
.getModule(), CTType
, /*isConstant=*/true, getLinkageForRTTI(T
),
4241 llvm::ConstantStruct::get(CTType
, Fields
), MangledName
);
4242 GV
->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global
);
4243 GV
->setSection(".xdata");
4244 if (GV
->isWeakForLinker())
4245 GV
->setComdat(CGM
.getModule().getOrInsertComdat(GV
->getName()));
4246 return getImageRelativeConstant(GV
);
4249 llvm::GlobalVariable
*MicrosoftCXXABI::getCatchableTypeArray(QualType T
) {
4250 assert(!T
->isReferenceType());
4252 // See if we've already generated a CatchableTypeArray for this type before.
4253 llvm::GlobalVariable
*&CTA
= CatchableTypeArrays
[T
];
4257 // Ensure that we don't have duplicate entries in our CatchableTypeArray by
4258 // using a SmallSetVector. Duplicates may arise due to virtual bases
4259 // occurring more than once in the hierarchy.
4260 llvm::SmallSetVector
<llvm::Constant
*, 2> CatchableTypes
;
4262 // C++14 [except.handle]p3:
4263 // A handler is a match for an exception object of type E if [...]
4264 // - the handler is of type cv T or cv T& and T is an unambiguous public
4265 // base class of E, or
4266 // - the handler is of type cv T or const T& where T is a pointer type and
4267 // E is a pointer type that can be converted to T by [...]
4268 // - a standard pointer conversion (4.10) not involving conversions to
4269 // pointers to private or protected or ambiguous classes
4270 const CXXRecordDecl
*MostDerivedClass
= nullptr;
4271 bool IsPointer
= T
->isPointerType();
4273 MostDerivedClass
= T
->getPointeeType()->getAsCXXRecordDecl();
4275 MostDerivedClass
= T
->getAsCXXRecordDecl();
4277 // Collect all the unambiguous public bases of the MostDerivedClass.
4278 if (MostDerivedClass
) {
4279 const ASTContext
&Context
= getContext();
4280 const ASTRecordLayout
&MostDerivedLayout
=
4281 Context
.getASTRecordLayout(MostDerivedClass
);
4282 MicrosoftVTableContext
&VTableContext
= CGM
.getMicrosoftVTableContext();
4283 SmallVector
<MSRTTIClass
, 8> Classes
;
4284 serializeClassHierarchy(Classes
, MostDerivedClass
);
4285 Classes
.front().initialize(/*Parent=*/nullptr, /*Specifier=*/nullptr);
4286 detectAmbiguousBases(Classes
);
4287 for (const MSRTTIClass
&Class
: Classes
) {
4288 // Skip any ambiguous or private bases.
4290 (MSRTTIClass::IsPrivateOnPath
| MSRTTIClass::IsAmbiguous
))
4292 // Write down how to convert from a derived pointer to a base pointer.
4293 uint32_t OffsetInVBTable
= 0;
4294 int32_t VBPtrOffset
= -1;
4295 if (Class
.VirtualRoot
) {
4297 VTableContext
.getVBTableIndex(MostDerivedClass
, Class
.VirtualRoot
)*4;
4298 VBPtrOffset
= MostDerivedLayout
.getVBPtrOffset().getQuantity();
4301 // Turn our record back into a pointer if the exception object is a
4303 QualType RTTITy
= QualType(Class
.RD
->getTypeForDecl(), 0);
4305 RTTITy
= Context
.getPointerType(RTTITy
);
4306 CatchableTypes
.insert(getCatchableType(RTTITy
, Class
.OffsetInVBase
,
4307 VBPtrOffset
, OffsetInVBTable
));
4311 // C++14 [except.handle]p3:
4312 // A handler is a match for an exception object of type E if
4313 // - The handler is of type cv T or cv T& and E and T are the same type
4314 // (ignoring the top-level cv-qualifiers)
4315 CatchableTypes
.insert(getCatchableType(T
));
4317 // C++14 [except.handle]p3:
4318 // A handler is a match for an exception object of type E if
4319 // - the handler is of type cv T or const T& where T is a pointer type and
4320 // E is a pointer type that can be converted to T by [...]
4321 // - a standard pointer conversion (4.10) not involving conversions to
4322 // pointers to private or protected or ambiguous classes
4324 // C++14 [conv.ptr]p2:
4325 // A prvalue of type "pointer to cv T," where T is an object type, can be
4326 // converted to a prvalue of type "pointer to cv void".
4327 if (IsPointer
&& T
->getPointeeType()->isObjectType())
4328 CatchableTypes
.insert(getCatchableType(getContext().VoidPtrTy
));
4330 // C++14 [except.handle]p3:
4331 // A handler is a match for an exception object of type E if [...]
4332 // - the handler is of type cv T or const T& where T is a pointer or
4333 // pointer to member type and E is std::nullptr_t.
4335 // We cannot possibly list all possible pointer types here, making this
4336 // implementation incompatible with the standard. However, MSVC includes an
4337 // entry for pointer-to-void in this case. Let's do the same.
4338 if (T
->isNullPtrType())
4339 CatchableTypes
.insert(getCatchableType(getContext().VoidPtrTy
));
4341 uint32_t NumEntries
= CatchableTypes
.size();
4342 llvm::Type
*CTType
=
4343 getImageRelativeType(getCatchableTypeType()->getPointerTo());
4344 llvm::ArrayType
*AT
= llvm::ArrayType::get(CTType
, NumEntries
);
4345 llvm::StructType
*CTAType
= getCatchableTypeArrayType(NumEntries
);
4346 llvm::Constant
*Fields
[] = {
4347 llvm::ConstantInt::get(CGM
.IntTy
, NumEntries
), // NumEntries
4348 llvm::ConstantArray::get(
4349 AT
, llvm::ArrayRef(CatchableTypes
.begin(),
4350 CatchableTypes
.end())) // CatchableTypes
4352 SmallString
<256> MangledName
;
4354 llvm::raw_svector_ostream
Out(MangledName
);
4355 getMangleContext().mangleCXXCatchableTypeArray(T
, NumEntries
, Out
);
4357 CTA
= new llvm::GlobalVariable(
4358 CGM
.getModule(), CTAType
, /*isConstant=*/true, getLinkageForRTTI(T
),
4359 llvm::ConstantStruct::get(CTAType
, Fields
), MangledName
);
4360 CTA
->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global
);
4361 CTA
->setSection(".xdata");
4362 if (CTA
->isWeakForLinker())
4363 CTA
->setComdat(CGM
.getModule().getOrInsertComdat(CTA
->getName()));
4367 llvm::GlobalVariable
*MicrosoftCXXABI::getThrowInfo(QualType T
) {
4368 bool IsConst
, IsVolatile
, IsUnaligned
;
4369 T
= decomposeTypeForEH(getContext(), T
, IsConst
, IsVolatile
, IsUnaligned
);
4371 // The CatchableTypeArray enumerates the various (CV-unqualified) types that
4372 // the exception object may be caught as.
4373 llvm::GlobalVariable
*CTA
= getCatchableTypeArray(T
);
4374 // The first field in a CatchableTypeArray is the number of CatchableTypes.
4375 // This is used as a component of the mangled name which means that we need to
4376 // know what it is in order to see if we have previously generated the
4378 uint32_t NumEntries
=
4379 cast
<llvm::ConstantInt
>(CTA
->getInitializer()->getAggregateElement(0U))
4380 ->getLimitedValue();
4382 SmallString
<256> MangledName
;
4384 llvm::raw_svector_ostream
Out(MangledName
);
4385 getMangleContext().mangleCXXThrowInfo(T
, IsConst
, IsVolatile
, IsUnaligned
,
4389 // Reuse a previously generated ThrowInfo if we have generated an appropriate
4391 if (llvm::GlobalVariable
*GV
= CGM
.getModule().getNamedGlobal(MangledName
))
4394 // The RTTI TypeDescriptor uses an unqualified type but catch clauses must
4395 // be at least as CV qualified. Encode this requirement into the Flags
4405 // The cleanup-function (a destructor) must be called when the exception
4406 // object's lifetime ends.
4407 llvm::Constant
*CleanupFn
= llvm::Constant::getNullValue(CGM
.Int8PtrTy
);
4408 if (const CXXRecordDecl
*RD
= T
->getAsCXXRecordDecl())
4409 if (CXXDestructorDecl
*DtorD
= RD
->getDestructor())
4410 if (!DtorD
->isTrivial())
4411 CleanupFn
= llvm::ConstantExpr::getBitCast(
4412 CGM
.getAddrOfCXXStructor(GlobalDecl(DtorD
, Dtor_Complete
)),
4414 // This is unused as far as we can tell, initialize it to null.
4415 llvm::Constant
*ForwardCompat
=
4416 getImageRelativeConstant(llvm::Constant::getNullValue(CGM
.Int8PtrTy
));
4417 llvm::Constant
*PointerToCatchableTypes
= getImageRelativeConstant(
4418 llvm::ConstantExpr::getBitCast(CTA
, CGM
.Int8PtrTy
));
4419 llvm::StructType
*TIType
= getThrowInfoType();
4420 llvm::Constant
*Fields
[] = {
4421 llvm::ConstantInt::get(CGM
.IntTy
, Flags
), // Flags
4422 getImageRelativeConstant(CleanupFn
), // CleanupFn
4423 ForwardCompat
, // ForwardCompat
4424 PointerToCatchableTypes
// CatchableTypeArray
4426 auto *GV
= new llvm::GlobalVariable(
4427 CGM
.getModule(), TIType
, /*isConstant=*/true, getLinkageForRTTI(T
),
4428 llvm::ConstantStruct::get(TIType
, Fields
), MangledName
.str());
4429 GV
->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global
);
4430 GV
->setSection(".xdata");
4431 if (GV
->isWeakForLinker())
4432 GV
->setComdat(CGM
.getModule().getOrInsertComdat(GV
->getName()));
4436 void MicrosoftCXXABI::emitThrow(CodeGenFunction
&CGF
, const CXXThrowExpr
*E
) {
4437 const Expr
*SubExpr
= E
->getSubExpr();
4438 assert(SubExpr
&& "SubExpr cannot be null");
4439 QualType ThrowType
= SubExpr
->getType();
4440 // The exception object lives on the stack and it's address is passed to the
4441 // runtime function.
4442 Address AI
= CGF
.CreateMemTemp(ThrowType
);
4443 CGF
.EmitAnyExprToMem(SubExpr
, AI
, ThrowType
.getQualifiers(),
4446 // The so-called ThrowInfo is used to describe how the exception object may be
4448 llvm::GlobalVariable
*TI
= getThrowInfo(ThrowType
);
4450 // Call into the runtime to throw the exception.
4451 llvm::Value
*Args
[] = {
4455 CGF
.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(), Args
);
4458 std::pair
<llvm::Value
*, const CXXRecordDecl
*>
4459 MicrosoftCXXABI::LoadVTablePtr(CodeGenFunction
&CGF
, Address This
,
4460 const CXXRecordDecl
*RD
) {
4461 std::tie(This
, std::ignore
, RD
) =
4462 performBaseAdjustment(CGF
, This
, QualType(RD
->getTypeForDecl(), 0));
4463 return {CGF
.GetVTablePtr(This
, CGM
.Int8PtrTy
, RD
), RD
};
4466 bool MicrosoftCXXABI::isPermittedToBeHomogeneousAggregate(
4467 const CXXRecordDecl
*RD
) const {
4468 // All aggregates are permitted to be HFA on non-ARM platforms, which mostly
4469 // affects vectorcall on x64/x86.
4470 if (!CGM
.getTarget().getTriple().isAArch64())
4472 // MSVC Windows on Arm64 has its own rules for determining if a type is HFA
4473 // that are inconsistent with the AAPCS64 ABI. The following are our best
4474 // determination of those rules so far, based on observation of MSVC's
4478 if (RD
->isPolymorphic())
4480 if (RD
->hasNonTrivialCopyAssignment())
4482 if (RD
->hasNonTrivialDestructor())
4484 if (RD
->hasNonTrivialDefaultConstructor())
4486 // These two are somewhat redundant given the caller
4487 // (ABIInfo::isHomogeneousAggregate) checks the bases and fields, but that
4488 // caller doesn't consider empty bases/fields to be non-homogenous, but it
4489 // looks like Microsoft's AArch64 ABI does care about these empty types &
4490 // anything containing/derived from one is non-homogeneous.
4491 // Instead we could add another CXXABI entry point to query this property and
4492 // have ABIInfo::isHomogeneousAggregate use that property.
4493 // I don't think any other of the features listed above could be true of a
4494 // base/field while not true of the outer struct. For example, if you have a
4495 // base/field that has an non-trivial copy assignment/dtor/default ctor, then
4496 // the outer struct's corresponding operation must be non-trivial.
4497 for (const CXXBaseSpecifier
&B
: RD
->bases()) {
4498 if (const CXXRecordDecl
*FRD
= B
.getType()->getAsCXXRecordDecl()) {
4499 if (!isPermittedToBeHomogeneousAggregate(FRD
))
4503 // empty fields seem to be caught by the ABIInfo::isHomogeneousAggregate
4504 // checking for padding - but maybe there are ways to end up with an empty
4505 // field without padding? Not that I know of, so don't check fields here &
4506 // rely on the padding check.