1 //===--- MicrosoftCXXABI.cpp - Emit LLVM Code from ASTs for a Module ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This provides C++ code generation targeting the Microsoft Visual C++ ABI.
11 // The class in this file generates structures that follow the Microsoft
12 // Visual C++ ABI, which is actually not very well documented at all outside
15 //===----------------------------------------------------------------------===//
18 #include "CGCleanup.h"
19 #include "CGVTables.h"
20 #include "CodeGenModule.h"
21 #include "CodeGenTypes.h"
22 #include "TargetInfo.h"
23 #include "clang/AST/Decl.h"
24 #include "clang/AST/DeclCXX.h"
25 #include "clang/AST/StmtCXX.h"
26 #include "clang/AST/VTableBuilder.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/ADT/StringSet.h"
29 #include "llvm/IR/CallSite.h"
30 #include "llvm/IR/Intrinsics.h"
32 using namespace clang;
33 using namespace CodeGen;
37 /// Holds all the vbtable globals for a given class.
38 struct VBTableGlobals {
39 const VPtrInfoVector *VBTables;
40 SmallVector<llvm::GlobalVariable *, 2> Globals;
43 class MicrosoftCXXABI : public CGCXXABI {
45 MicrosoftCXXABI(CodeGenModule &CGM)
46 : CGCXXABI(CGM), BaseClassDescriptorType(nullptr),
47 ClassHierarchyDescriptorType(nullptr),
48 CompleteObjectLocatorType(nullptr), CatchableTypeType(nullptr),
49 ThrowInfoType(nullptr) {}
51 bool HasThisReturn(GlobalDecl GD) const override;
52 bool hasMostDerivedReturn(GlobalDecl GD) const override;
54 bool classifyReturnType(CGFunctionInfo &FI) const override;
56 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override;
58 bool isSRetParameterAfterThis() const override { return true; }
60 bool isThisCompleteObject(GlobalDecl GD) const override {
61 // The Microsoft ABI doesn't use separate complete-object vs.
62 // base-object variants of constructors, but it does of destructors.
63 if (isa<CXXDestructorDecl>(GD.getDecl())) {
64 switch (GD.getDtorType()) {
72 case Dtor_Comdat: llvm_unreachable("emitting dtor comdat as function?");
74 llvm_unreachable("bad dtor kind");
81 size_t getSrcArgforCopyCtor(const CXXConstructorDecl *CD,
82 FunctionArgList &Args) const override {
83 assert(Args.size() >= 2 &&
84 "expected the arglist to have at least two args!");
85 // The 'most_derived' parameter goes second if the ctor is variadic and
87 if (CD->getParent()->getNumVBases() > 0 &&
88 CD->getType()->castAs<FunctionProtoType>()->isVariadic())
93 std::vector<CharUnits> getVBPtrOffsets(const CXXRecordDecl *RD) override {
94 std::vector<CharUnits> VBPtrOffsets;
95 const ASTContext &Context = getContext();
96 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
98 const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
99 for (const VPtrInfo *VBT : *VBGlobals.VBTables) {
100 const ASTRecordLayout &SubobjectLayout =
101 Context.getASTRecordLayout(VBT->BaseWithVPtr);
102 CharUnits Offs = VBT->NonVirtualOffset;
103 Offs += SubobjectLayout.getVBPtrOffset();
104 if (VBT->getVBaseWithVPtr())
105 Offs += Layout.getVBaseClassOffset(VBT->getVBaseWithVPtr());
106 VBPtrOffsets.push_back(Offs);
108 llvm::array_pod_sort(VBPtrOffsets.begin(), VBPtrOffsets.end());
112 StringRef GetPureVirtualCallName() override { return "_purecall"; }
113 StringRef GetDeletedVirtualCallName() override { return "_purecall"; }
115 void emitVirtualObjectDelete(CodeGenFunction &CGF, const CXXDeleteExpr *DE,
116 Address Ptr, QualType ElementType,
117 const CXXDestructorDecl *Dtor) override;
119 void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) override;
120 void emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) override;
122 void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override;
124 llvm::GlobalVariable *getMSCompleteObjectLocator(const CXXRecordDecl *RD,
125 const VPtrInfo *Info);
127 llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override;
129 getAddrOfCXXCatchHandlerType(QualType Ty, QualType CatchHandlerType) override;
131 /// MSVC needs an extra flag to indicate a catchall.
132 CatchTypeInfo getCatchAllTypeInfo() override {
133 return CatchTypeInfo{nullptr, 0x40};
136 bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override;
137 void EmitBadTypeidCall(CodeGenFunction &CGF) override;
138 llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
140 llvm::Type *StdTypeInfoPtrTy) override;
142 bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
143 QualType SrcRecordTy) override;
145 llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, Address Value,
146 QualType SrcRecordTy, QualType DestTy,
147 QualType DestRecordTy,
148 llvm::BasicBlock *CastEnd) override;
150 llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, Address Value,
151 QualType SrcRecordTy,
152 QualType DestTy) override;
154 bool EmitBadCastCall(CodeGenFunction &CGF) override;
155 bool canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const override {
160 GetVirtualBaseClassOffset(CodeGenFunction &CGF, Address This,
161 const CXXRecordDecl *ClassDecl,
162 const CXXRecordDecl *BaseClassDecl) override;
165 EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
166 const CXXRecordDecl *RD) override;
168 void initializeHiddenVirtualInheritanceMembers(CodeGenFunction &CGF,
169 const CXXRecordDecl *RD) override;
171 void EmitCXXConstructors(const CXXConstructorDecl *D) override;
173 // Background on MSVC destructors
174 // ==============================
176 // Both Itanium and MSVC ABIs have destructor variants. The variant names
177 // roughly correspond in the following way:
179 // Base -> no name, just ~Class
180 // Complete -> vbase destructor
181 // Deleting -> scalar deleting destructor
182 // vector deleting destructor
184 // The base and complete destructors are the same as in Itanium, although the
185 // complete destructor does not accept a VTT parameter when there are virtual
186 // bases. A separate mechanism involving vtordisps is used to ensure that
187 // virtual methods of destroyed subobjects are not called.
189 // The deleting destructors accept an i32 bitfield as a second parameter. Bit
190 // 1 indicates if the memory should be deleted. Bit 2 indicates if the this
191 // pointer points to an array. The scalar deleting destructor assumes that
192 // bit 2 is zero, and therefore does not contain a loop.
194 // For virtual destructors, only one entry is reserved in the vftable, and it
195 // always points to the vector deleting destructor. The vector deleting
196 // destructor is the most general, so it can be used to destroy objects in
197 // place, delete single heap objects, or delete arrays.
199 // A TU defining a non-inline destructor is only guaranteed to emit a base
200 // destructor, and all of the other variants are emitted on an as-needed basis
201 // in COMDATs. Because a non-base destructor can be emitted in a TU that
202 // lacks a definition for the destructor, non-base destructors must always
203 // delegate to or alias the base destructor.
205 void buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
206 SmallVectorImpl<CanQualType> &ArgTys) override;
208 /// Non-base dtors should be emitted as delegating thunks in this ABI.
209 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
210 CXXDtorType DT) const override {
211 return DT != Dtor_Base;
214 void EmitCXXDestructors(const CXXDestructorDecl *D) override;
216 const CXXRecordDecl *
217 getThisArgumentTypeForMethod(const CXXMethodDecl *MD) override {
218 MD = MD->getCanonicalDecl();
219 if (MD->isVirtual() && !isa<CXXDestructorDecl>(MD)) {
220 MicrosoftVTableContext::MethodVFTableLocation ML =
221 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(MD);
222 // The vbases might be ordered differently in the final overrider object
223 // and the complete object, so the "this" argument may sometimes point to
224 // memory that has no particular type (e.g. past the complete object).
225 // In this case, we just use a generic pointer type.
226 // FIXME: might want to have a more precise type in the non-virtual
227 // multiple inheritance case.
228 if (ML.VBase || !ML.VFPtrOffset.isZero())
231 return MD->getParent();
235 adjustThisArgumentForVirtualFunctionCall(CodeGenFunction &CGF, GlobalDecl GD,
237 bool VirtualCall) override;
239 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
240 FunctionArgList &Params) override;
242 llvm::Value *adjustThisParameterInVirtualFunctionPrologue(
243 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) override;
245 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
247 unsigned addImplicitConstructorArgs(CodeGenFunction &CGF,
248 const CXXConstructorDecl *D,
249 CXXCtorType Type, bool ForVirtualBase,
251 CallArgList &Args) override;
253 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
254 CXXDtorType Type, bool ForVirtualBase,
255 bool Delegating, Address This) override;
257 void emitVTableBitSetEntries(VPtrInfo *Info, const CXXRecordDecl *RD,
258 llvm::GlobalVariable *VTable);
260 void emitVTableDefinitions(CodeGenVTables &CGVT,
261 const CXXRecordDecl *RD) override;
263 bool isVirtualOffsetNeededForVTableField(CodeGenFunction &CGF,
264 CodeGenFunction::VPtr Vptr) override;
266 /// Don't initialize vptrs if dynamic class
267 /// is marked with with the 'novtable' attribute.
268 bool doStructorsInitializeVPtrs(const CXXRecordDecl *VTableClass) override {
269 return !VTableClass->hasAttr<MSNoVTableAttr>();
273 getVTableAddressPoint(BaseSubobject Base,
274 const CXXRecordDecl *VTableClass) override;
276 llvm::Value *getVTableAddressPointInStructor(
277 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
278 BaseSubobject Base, const CXXRecordDecl *NearestVBase) override;
281 getVTableAddressPointForConstExpr(BaseSubobject Base,
282 const CXXRecordDecl *VTableClass) override;
284 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
285 CharUnits VPtrOffset) override;
287 llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
288 Address This, llvm::Type *Ty,
289 SourceLocation Loc) override;
291 llvm::Value *EmitVirtualDestructorCall(CodeGenFunction &CGF,
292 const CXXDestructorDecl *Dtor,
293 CXXDtorType DtorType,
295 const CXXMemberCallExpr *CE) override;
297 void adjustCallArgsForDestructorThunk(CodeGenFunction &CGF, GlobalDecl GD,
298 CallArgList &CallArgs) override {
299 assert(GD.getDtorType() == Dtor_Deleting &&
300 "Only deleting destructor thunks are available in this ABI");
301 CallArgs.add(RValue::get(getStructorImplicitParamValue(CGF)),
305 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
307 llvm::GlobalVariable *
308 getAddrOfVBTable(const VPtrInfo &VBT, const CXXRecordDecl *RD,
309 llvm::GlobalVariable::LinkageTypes Linkage);
311 llvm::GlobalVariable *
312 getAddrOfVirtualDisplacementMap(const CXXRecordDecl *SrcRD,
313 const CXXRecordDecl *DstRD) {
314 SmallString<256> OutName;
315 llvm::raw_svector_ostream Out(OutName);
316 getMangleContext().mangleCXXVirtualDisplacementMap(SrcRD, DstRD, Out);
317 StringRef MangledName = OutName.str();
319 if (auto *VDispMap = CGM.getModule().getNamedGlobal(MangledName))
322 MicrosoftVTableContext &VTContext = CGM.getMicrosoftVTableContext();
323 unsigned NumEntries = 1 + SrcRD->getNumVBases();
324 SmallVector<llvm::Constant *, 4> Map(NumEntries,
325 llvm::UndefValue::get(CGM.IntTy));
326 Map[0] = llvm::ConstantInt::get(CGM.IntTy, 0);
327 bool AnyDifferent = false;
328 for (const auto &I : SrcRD->vbases()) {
329 const CXXRecordDecl *VBase = I.getType()->getAsCXXRecordDecl();
330 if (!DstRD->isVirtuallyDerivedFrom(VBase))
333 unsigned SrcVBIndex = VTContext.getVBTableIndex(SrcRD, VBase);
334 unsigned DstVBIndex = VTContext.getVBTableIndex(DstRD, VBase);
335 Map[SrcVBIndex] = llvm::ConstantInt::get(CGM.IntTy, DstVBIndex * 4);
336 AnyDifferent |= SrcVBIndex != DstVBIndex;
338 // This map would be useless, don't use it.
342 llvm::ArrayType *VDispMapTy = llvm::ArrayType::get(CGM.IntTy, Map.size());
343 llvm::Constant *Init = llvm::ConstantArray::get(VDispMapTy, Map);
344 llvm::GlobalValue::LinkageTypes Linkage =
345 SrcRD->isExternallyVisible() && DstRD->isExternallyVisible()
346 ? llvm::GlobalValue::LinkOnceODRLinkage
347 : llvm::GlobalValue::InternalLinkage;
348 auto *VDispMap = new llvm::GlobalVariable(
349 CGM.getModule(), VDispMapTy, /*Constant=*/true, Linkage,
350 /*Initializer=*/Init, MangledName);
354 void emitVBTableDefinition(const VPtrInfo &VBT, const CXXRecordDecl *RD,
355 llvm::GlobalVariable *GV) const;
357 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable,
358 GlobalDecl GD, bool ReturnAdjustment) override {
359 // Never dllimport/dllexport thunks.
360 Thunk->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
363 getContext().GetGVALinkageForFunction(cast<FunctionDecl>(GD.getDecl()));
365 if (Linkage == GVA_Internal)
366 Thunk->setLinkage(llvm::GlobalValue::InternalLinkage);
367 else if (ReturnAdjustment)
368 Thunk->setLinkage(llvm::GlobalValue::WeakODRLinkage);
370 Thunk->setLinkage(llvm::GlobalValue::LinkOnceODRLinkage);
373 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, Address This,
374 const ThisAdjustment &TA) override;
376 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
377 const ReturnAdjustment &RA) override;
379 void EmitThreadLocalInitFuncs(
380 CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
381 ArrayRef<llvm::Function *> CXXThreadLocalInits,
382 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) override;
384 bool usesThreadWrapperFunction() const override { return false; }
385 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
386 QualType LValType) override;
388 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
389 llvm::GlobalVariable *DeclPtr,
390 bool PerformInit) override;
391 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
392 llvm::Constant *Dtor, llvm::Constant *Addr) override;
394 // ==== Notes on array cookies =========
396 // MSVC seems to only use cookies when the class has a destructor; a
397 // two-argument usual array deallocation function isn't sufficient.
399 // For example, this code prints "100" and "1":
402 // void *operator new[](size_t sz) {
403 // printf("%u\n", sz);
404 // return malloc(sz);
406 // void operator delete[](void *p, size_t sz) {
407 // printf("%u\n", sz);
412 // A *p = new A[100];
415 // Whereas it prints "104" and "104" if you give A a destructor.
417 bool requiresArrayCookie(const CXXDeleteExpr *expr,
418 QualType elementType) override;
419 bool requiresArrayCookie(const CXXNewExpr *expr) override;
420 CharUnits getArrayCookieSizeImpl(QualType type) override;
421 Address InitializeArrayCookie(CodeGenFunction &CGF,
423 llvm::Value *NumElements,
424 const CXXNewExpr *expr,
425 QualType ElementType) override;
426 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
428 CharUnits cookieSize) override;
430 friend struct MSRTTIBuilder;
432 bool isImageRelative() const {
433 return CGM.getTarget().getPointerWidth(/*AddressSpace=*/0) == 64;
436 // 5 routines for constructing the llvm types for MS RTTI structs.
437 llvm::StructType *getTypeDescriptorType(StringRef TypeInfoString) {
438 llvm::SmallString<32> TDTypeName("rtti.TypeDescriptor");
439 TDTypeName += llvm::utostr(TypeInfoString.size());
440 llvm::StructType *&TypeDescriptorType =
441 TypeDescriptorTypeMap[TypeInfoString.size()];
442 if (TypeDescriptorType)
443 return TypeDescriptorType;
444 llvm::Type *FieldTypes[] = {
447 llvm::ArrayType::get(CGM.Int8Ty, TypeInfoString.size() + 1)};
449 llvm::StructType::create(CGM.getLLVMContext(), FieldTypes, TDTypeName);
450 return TypeDescriptorType;
453 llvm::Type *getImageRelativeType(llvm::Type *PtrType) {
454 if (!isImageRelative())
459 llvm::StructType *getBaseClassDescriptorType() {
460 if (BaseClassDescriptorType)
461 return BaseClassDescriptorType;
462 llvm::Type *FieldTypes[] = {
463 getImageRelativeType(CGM.Int8PtrTy),
469 getImageRelativeType(getClassHierarchyDescriptorType()->getPointerTo()),
471 BaseClassDescriptorType = llvm::StructType::create(
472 CGM.getLLVMContext(), FieldTypes, "rtti.BaseClassDescriptor");
473 return BaseClassDescriptorType;
476 llvm::StructType *getClassHierarchyDescriptorType() {
477 if (ClassHierarchyDescriptorType)
478 return ClassHierarchyDescriptorType;
479 // Forward-declare RTTIClassHierarchyDescriptor to break a cycle.
480 ClassHierarchyDescriptorType = llvm::StructType::create(
481 CGM.getLLVMContext(), "rtti.ClassHierarchyDescriptor");
482 llvm::Type *FieldTypes[] = {
486 getImageRelativeType(
487 getBaseClassDescriptorType()->getPointerTo()->getPointerTo()),
489 ClassHierarchyDescriptorType->setBody(FieldTypes);
490 return ClassHierarchyDescriptorType;
493 llvm::StructType *getCompleteObjectLocatorType() {
494 if (CompleteObjectLocatorType)
495 return CompleteObjectLocatorType;
496 CompleteObjectLocatorType = llvm::StructType::create(
497 CGM.getLLVMContext(), "rtti.CompleteObjectLocator");
498 llvm::Type *FieldTypes[] = {
502 getImageRelativeType(CGM.Int8PtrTy),
503 getImageRelativeType(getClassHierarchyDescriptorType()->getPointerTo()),
504 getImageRelativeType(CompleteObjectLocatorType),
506 llvm::ArrayRef<llvm::Type *> FieldTypesRef(FieldTypes);
507 if (!isImageRelative())
508 FieldTypesRef = FieldTypesRef.drop_back();
509 CompleteObjectLocatorType->setBody(FieldTypesRef);
510 return CompleteObjectLocatorType;
513 llvm::GlobalVariable *getImageBase() {
514 StringRef Name = "__ImageBase";
515 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name))
518 return new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty,
520 llvm::GlobalValue::ExternalLinkage,
521 /*Initializer=*/nullptr, Name);
524 llvm::Constant *getImageRelativeConstant(llvm::Constant *PtrVal) {
525 if (!isImageRelative())
528 if (PtrVal->isNullValue())
529 return llvm::Constant::getNullValue(CGM.IntTy);
531 llvm::Constant *ImageBaseAsInt =
532 llvm::ConstantExpr::getPtrToInt(getImageBase(), CGM.IntPtrTy);
533 llvm::Constant *PtrValAsInt =
534 llvm::ConstantExpr::getPtrToInt(PtrVal, CGM.IntPtrTy);
535 llvm::Constant *Diff =
536 llvm::ConstantExpr::getSub(PtrValAsInt, ImageBaseAsInt,
537 /*HasNUW=*/true, /*HasNSW=*/true);
538 return llvm::ConstantExpr::getTrunc(Diff, CGM.IntTy);
542 MicrosoftMangleContext &getMangleContext() {
543 return cast<MicrosoftMangleContext>(CodeGen::CGCXXABI::getMangleContext());
546 llvm::Constant *getZeroInt() {
547 return llvm::ConstantInt::get(CGM.IntTy, 0);
550 llvm::Constant *getAllOnesInt() {
551 return llvm::Constant::getAllOnesValue(CGM.IntTy);
554 CharUnits getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD);
557 GetNullMemberPointerFields(const MemberPointerType *MPT,
558 llvm::SmallVectorImpl<llvm::Constant *> &fields);
560 /// \brief Shared code for virtual base adjustment. Returns the offset from
561 /// the vbptr to the virtual base. Optionally returns the address of the
563 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
565 llvm::Value *VBPtrOffset,
566 llvm::Value *VBTableOffset,
567 llvm::Value **VBPtr = nullptr);
569 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
572 int32_t VBTableOffset,
573 llvm::Value **VBPtr = nullptr) {
574 assert(VBTableOffset % 4 == 0 && "should be byte offset into table of i32s");
575 llvm::Value *VBPOffset = llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset),
576 *VBTOffset = llvm::ConstantInt::get(CGM.IntTy, VBTableOffset);
577 return GetVBaseOffsetFromVBPtr(CGF, Base, VBPOffset, VBTOffset, VBPtr);
580 std::pair<Address, llvm::Value *>
581 performBaseAdjustment(CodeGenFunction &CGF, Address Value,
582 QualType SrcRecordTy);
584 /// \brief Performs a full virtual base adjustment. Used to dereference
585 /// pointers to members of virtual bases.
586 llvm::Value *AdjustVirtualBase(CodeGenFunction &CGF, const Expr *E,
587 const CXXRecordDecl *RD, Address Base,
588 llvm::Value *VirtualBaseAdjustmentOffset,
589 llvm::Value *VBPtrOffset /* optional */);
591 /// \brief Emits a full member pointer with the fields common to data and
592 /// function member pointers.
593 llvm::Constant *EmitFullMemberPointer(llvm::Constant *FirstField,
594 bool IsMemberFunction,
595 const CXXRecordDecl *RD,
596 CharUnits NonVirtualBaseAdjustment,
597 unsigned VBTableIndex);
599 bool MemberPointerConstantIsNull(const MemberPointerType *MPT,
602 /// \brief - Initialize all vbptrs of 'this' with RD as the complete type.
603 void EmitVBPtrStores(CodeGenFunction &CGF, const CXXRecordDecl *RD);
605 /// \brief Caching wrapper around VBTableBuilder::enumerateVBTables().
606 const VBTableGlobals &enumerateVBTables(const CXXRecordDecl *RD);
608 /// \brief Generate a thunk for calling a virtual member function MD.
609 llvm::Function *EmitVirtualMemPtrThunk(
610 const CXXMethodDecl *MD,
611 const MicrosoftVTableContext::MethodVFTableLocation &ML);
614 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override;
616 bool isZeroInitializable(const MemberPointerType *MPT) override;
618 bool isMemberPointerConvertible(const MemberPointerType *MPT) const override {
619 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
620 return RD->hasAttr<MSInheritanceAttr>();
623 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override;
625 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
626 CharUnits offset) override;
627 llvm::Constant *EmitMemberFunctionPointer(const CXXMethodDecl *MD) override;
628 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override;
630 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
633 const MemberPointerType *MPT,
634 bool Inequality) override;
636 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
638 const MemberPointerType *MPT) override;
641 EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
642 Address Base, llvm::Value *MemPtr,
643 const MemberPointerType *MPT) override;
645 llvm::Value *EmitNonNullMemberPointerConversion(
646 const MemberPointerType *SrcTy, const MemberPointerType *DstTy,
647 CastKind CK, CastExpr::path_const_iterator PathBegin,
648 CastExpr::path_const_iterator PathEnd, llvm::Value *Src,
649 CGBuilderTy &Builder);
651 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
653 llvm::Value *Src) override;
655 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
656 llvm::Constant *Src) override;
658 llvm::Constant *EmitMemberPointerConversion(
659 const MemberPointerType *SrcTy, const MemberPointerType *DstTy,
660 CastKind CK, CastExpr::path_const_iterator PathBegin,
661 CastExpr::path_const_iterator PathEnd, llvm::Constant *Src);
664 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF, const Expr *E,
665 Address This, llvm::Value *&ThisPtrForCall,
667 const MemberPointerType *MPT) override;
669 void emitCXXStructor(const CXXMethodDecl *MD, StructorType Type) override;
671 llvm::StructType *getCatchableTypeType() {
672 if (CatchableTypeType)
673 return CatchableTypeType;
674 llvm::Type *FieldTypes[] = {
676 getImageRelativeType(CGM.Int8PtrTy), // TypeDescriptor
677 CGM.IntTy, // NonVirtualAdjustment
678 CGM.IntTy, // OffsetToVBPtr
679 CGM.IntTy, // VBTableIndex
681 getImageRelativeType(CGM.Int8PtrTy) // CopyCtor
683 CatchableTypeType = llvm::StructType::create(
684 CGM.getLLVMContext(), FieldTypes, "eh.CatchableType");
685 return CatchableTypeType;
688 llvm::StructType *getCatchableTypeArrayType(uint32_t NumEntries) {
689 llvm::StructType *&CatchableTypeArrayType =
690 CatchableTypeArrayTypeMap[NumEntries];
691 if (CatchableTypeArrayType)
692 return CatchableTypeArrayType;
694 llvm::SmallString<23> CTATypeName("eh.CatchableTypeArray.");
695 CTATypeName += llvm::utostr(NumEntries);
697 getImageRelativeType(getCatchableTypeType()->getPointerTo());
698 llvm::Type *FieldTypes[] = {
699 CGM.IntTy, // NumEntries
700 llvm::ArrayType::get(CTType, NumEntries) // CatchableTypes
702 CatchableTypeArrayType =
703 llvm::StructType::create(CGM.getLLVMContext(), FieldTypes, CTATypeName);
704 return CatchableTypeArrayType;
707 llvm::StructType *getThrowInfoType() {
709 return ThrowInfoType;
710 llvm::Type *FieldTypes[] = {
712 getImageRelativeType(CGM.Int8PtrTy), // CleanupFn
713 getImageRelativeType(CGM.Int8PtrTy), // ForwardCompat
714 getImageRelativeType(CGM.Int8PtrTy) // CatchableTypeArray
716 ThrowInfoType = llvm::StructType::create(CGM.getLLVMContext(), FieldTypes,
718 return ThrowInfoType;
721 llvm::Constant *getThrowFn() {
722 // _CxxThrowException is passed an exception object and a ThrowInfo object
723 // which describes the exception.
724 llvm::Type *Args[] = {CGM.Int8PtrTy, getThrowInfoType()->getPointerTo()};
725 llvm::FunctionType *FTy =
726 llvm::FunctionType::get(CGM.VoidTy, Args, /*IsVarArgs=*/false);
727 auto *Fn = cast<llvm::Function>(
728 CGM.CreateRuntimeFunction(FTy, "_CxxThrowException"));
729 // _CxxThrowException is stdcall on 32-bit x86 platforms.
730 if (CGM.getTarget().getTriple().getArch() == llvm::Triple::x86)
731 Fn->setCallingConv(llvm::CallingConv::X86_StdCall);
735 llvm::Function *getAddrOfCXXCtorClosure(const CXXConstructorDecl *CD,
738 llvm::Constant *getCatchableType(QualType T,
739 uint32_t NVOffset = 0,
740 int32_t VBPtrOffset = -1,
741 uint32_t VBIndex = 0);
743 llvm::GlobalVariable *getCatchableTypeArray(QualType T);
745 llvm::GlobalVariable *getThrowInfo(QualType T) override;
748 typedef std::pair<const CXXRecordDecl *, CharUnits> VFTableIdTy;
749 typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalVariable *> VTablesMapTy;
750 typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalValue *> VFTablesMapTy;
751 /// \brief All the vftables that have been referenced.
752 VFTablesMapTy VFTablesMap;
753 VTablesMapTy VTablesMap;
755 /// \brief This set holds the record decls we've deferred vtable emission for.
756 llvm::SmallPtrSet<const CXXRecordDecl *, 4> DeferredVFTables;
759 /// \brief All the vbtables which have been referenced.
760 llvm::DenseMap<const CXXRecordDecl *, VBTableGlobals> VBTablesMap;
762 /// Info on the global variable used to guard initialization of static locals.
763 /// The BitIndex field is only used for externally invisible declarations.
765 GuardInfo() : Guard(nullptr), BitIndex(0) {}
766 llvm::GlobalVariable *Guard;
770 /// Map from DeclContext to the current guard variable. We assume that the
771 /// AST is visited in source code order.
772 llvm::DenseMap<const DeclContext *, GuardInfo> GuardVariableMap;
773 llvm::DenseMap<const DeclContext *, GuardInfo> ThreadLocalGuardVariableMap;
774 llvm::DenseMap<const DeclContext *, unsigned> ThreadSafeGuardNumMap;
776 llvm::DenseMap<size_t, llvm::StructType *> TypeDescriptorTypeMap;
777 llvm::StructType *BaseClassDescriptorType;
778 llvm::StructType *ClassHierarchyDescriptorType;
779 llvm::StructType *CompleteObjectLocatorType;
781 llvm::DenseMap<QualType, llvm::GlobalVariable *> CatchableTypeArrays;
783 llvm::StructType *CatchableTypeType;
784 llvm::DenseMap<uint32_t, llvm::StructType *> CatchableTypeArrayTypeMap;
785 llvm::StructType *ThrowInfoType;
790 CGCXXABI::RecordArgABI
791 MicrosoftCXXABI::getRecordArgABI(const CXXRecordDecl *RD) const {
792 switch (CGM.getTarget().getTriple().getArch()) {
794 // FIXME: Implement for other architectures.
797 case llvm::Triple::x86:
798 // All record arguments are passed in memory on x86. Decide whether to
799 // construct the object directly in argument memory, or to construct the
800 // argument elsewhere and copy the bytes during the call.
802 // If C++ prohibits us from making a copy, construct the arguments directly
803 // into argument memory.
804 if (!canCopyArgument(RD))
805 return RAA_DirectInMemory;
807 // Otherwise, construct the argument into a temporary and copy the bytes
808 // into the outgoing argument memory.
811 case llvm::Triple::x86_64:
812 // Win64 passes objects with non-trivial copy ctors indirectly.
813 if (RD->hasNonTrivialCopyConstructor())
816 // If an object has a destructor, we'd really like to pass it indirectly
817 // because it allows us to elide copies. Unfortunately, MSVC makes that
818 // impossible for small types, which it will pass in a single register or
819 // stack slot. Most objects with dtors are large-ish, so handle that early.
820 // We can't call out all large objects as being indirect because there are
821 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
822 // how we pass large POD types.
823 if (RD->hasNonTrivialDestructor() &&
824 getContext().getTypeSize(RD->getTypeForDecl()) > 64)
827 // We have a trivial copy constructor or no copy constructors, but we have
828 // to make sure it isn't deleted.
829 bool CopyDeleted = false;
830 for (const CXXConstructorDecl *CD : RD->ctors()) {
831 if (CD->isCopyConstructor()) {
832 assert(CD->isTrivial());
833 // We had at least one undeleted trivial copy ctor. Return directly.
834 if (!CD->isDeleted())
840 // The trivial copy constructor was deleted. Return indirectly.
844 // There were no copy ctors. Return in RAX.
848 llvm_unreachable("invalid enum");
851 void MicrosoftCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
852 const CXXDeleteExpr *DE,
854 QualType ElementType,
855 const CXXDestructorDecl *Dtor) {
856 // FIXME: Provide a source location here even though there's no
857 // CXXMemberCallExpr for dtor call.
858 bool UseGlobalDelete = DE->isGlobalDelete();
859 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
860 llvm::Value *MDThis =
861 EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, /*CE=*/nullptr);
863 CGF.EmitDeleteCall(DE->getOperatorDelete(), MDThis, ElementType);
866 void MicrosoftCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
867 llvm::Value *Args[] = {
868 llvm::ConstantPointerNull::get(CGM.Int8PtrTy),
869 llvm::ConstantPointerNull::get(getThrowInfoType()->getPointerTo())};
870 auto *Fn = getThrowFn();
872 CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, Args);
874 CGF.EmitRuntimeCallOrInvoke(Fn, Args);
878 struct CatchRetScope final : EHScopeStack::Cleanup {
879 llvm::CatchPadInst *CPI;
881 CatchRetScope(llvm::CatchPadInst *CPI) : CPI(CPI) {}
883 void Emit(CodeGenFunction &CGF, Flags flags) override {
884 llvm::BasicBlock *BB = CGF.createBasicBlock("catchret.dest");
885 CGF.Builder.CreateCatchRet(CPI, BB);
891 void MicrosoftCXXABI::emitBeginCatch(CodeGenFunction &CGF,
892 const CXXCatchStmt *S) {
893 // In the MS ABI, the runtime handles the copy, and the catch handler is
894 // responsible for destruction.
895 VarDecl *CatchParam = S->getExceptionDecl();
896 llvm::BasicBlock *CatchPadBB = CGF.Builder.GetInsertBlock();
897 llvm::CatchPadInst *CPI =
898 cast<llvm::CatchPadInst>(CatchPadBB->getFirstNonPHI());
899 CGF.CurrentFuncletPad = CPI;
901 // If this is a catch-all or the catch parameter is unnamed, we don't need to
902 // emit an alloca to the object.
903 if (!CatchParam || !CatchParam->getDeclName()) {
904 CGF.EHStack.pushCleanup<CatchRetScope>(NormalCleanup, CPI);
908 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
909 CPI->setArgOperand(2, var.getObjectAddress(CGF).getPointer());
910 CGF.EHStack.pushCleanup<CatchRetScope>(NormalCleanup, CPI);
911 CGF.EmitAutoVarCleanups(var);
914 /// We need to perform a generic polymorphic operation (like a typeid
915 /// or a cast), which requires an object with a vfptr. Adjust the
916 /// address to point to an object with a vfptr.
917 std::pair<Address, llvm::Value *>
918 MicrosoftCXXABI::performBaseAdjustment(CodeGenFunction &CGF, Address Value,
919 QualType SrcRecordTy) {
920 Value = CGF.Builder.CreateBitCast(Value, CGF.Int8PtrTy);
921 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
922 const ASTContext &Context = getContext();
924 // If the class itself has a vfptr, great. This check implicitly
925 // covers non-virtual base subobjects: a class with its own virtual
926 // functions would be a candidate to be a primary base.
927 if (Context.getASTRecordLayout(SrcDecl).hasExtendableVFPtr())
928 return std::make_pair(Value, llvm::ConstantInt::get(CGF.Int32Ty, 0));
930 // Okay, one of the vbases must have a vfptr, or else this isn't
931 // actually a polymorphic class.
932 const CXXRecordDecl *PolymorphicBase = nullptr;
933 for (auto &Base : SrcDecl->vbases()) {
934 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
935 if (Context.getASTRecordLayout(BaseDecl).hasExtendableVFPtr()) {
936 PolymorphicBase = BaseDecl;
940 assert(PolymorphicBase && "polymorphic class has no apparent vfptr?");
942 llvm::Value *Offset =
943 GetVirtualBaseClassOffset(CGF, Value, SrcDecl, PolymorphicBase);
944 llvm::Value *Ptr = CGF.Builder.CreateInBoundsGEP(Value.getPointer(), Offset);
945 Offset = CGF.Builder.CreateTrunc(Offset, CGF.Int32Ty);
946 CharUnits VBaseAlign =
947 CGF.CGM.getVBaseAlignment(Value.getAlignment(), SrcDecl, PolymorphicBase);
948 return std::make_pair(Address(Ptr, VBaseAlign), Offset);
951 bool MicrosoftCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
952 QualType SrcRecordTy) {
953 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
955 !getContext().getASTRecordLayout(SrcDecl).hasExtendableVFPtr();
958 static llvm::CallSite emitRTtypeidCall(CodeGenFunction &CGF,
959 llvm::Value *Argument) {
960 llvm::Type *ArgTypes[] = {CGF.Int8PtrTy};
961 llvm::FunctionType *FTy =
962 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false);
963 llvm::Value *Args[] = {Argument};
964 llvm::Constant *Fn = CGF.CGM.CreateRuntimeFunction(FTy, "__RTtypeid");
965 return CGF.EmitRuntimeCallOrInvoke(Fn, Args);
968 void MicrosoftCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
969 llvm::CallSite Call =
970 emitRTtypeidCall(CGF, llvm::Constant::getNullValue(CGM.VoidPtrTy));
971 Call.setDoesNotReturn();
972 CGF.Builder.CreateUnreachable();
975 llvm::Value *MicrosoftCXXABI::EmitTypeid(CodeGenFunction &CGF,
976 QualType SrcRecordTy,
978 llvm::Type *StdTypeInfoPtrTy) {
980 std::tie(ThisPtr, Offset) = performBaseAdjustment(CGF, ThisPtr, SrcRecordTy);
981 auto Typeid = emitRTtypeidCall(CGF, ThisPtr.getPointer()).getInstruction();
982 return CGF.Builder.CreateBitCast(Typeid, StdTypeInfoPtrTy);
985 bool MicrosoftCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
986 QualType SrcRecordTy) {
987 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
989 !getContext().getASTRecordLayout(SrcDecl).hasExtendableVFPtr();
992 llvm::Value *MicrosoftCXXABI::EmitDynamicCastCall(
993 CodeGenFunction &CGF, Address This, QualType SrcRecordTy,
994 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
995 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
997 llvm::Value *SrcRTTI =
998 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
999 llvm::Value *DestRTTI =
1000 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1002 llvm::Value *Offset;
1003 std::tie(This, Offset) = performBaseAdjustment(CGF, This, SrcRecordTy);
1004 llvm::Value *ThisPtr = This.getPointer();
1006 // PVOID __RTDynamicCast(
1010 // PVOID TargetType,
1011 // BOOL isReference)
1012 llvm::Type *ArgTypes[] = {CGF.Int8PtrTy, CGF.Int32Ty, CGF.Int8PtrTy,
1013 CGF.Int8PtrTy, CGF.Int32Ty};
1014 llvm::Constant *Function = CGF.CGM.CreateRuntimeFunction(
1015 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false),
1017 llvm::Value *Args[] = {
1018 ThisPtr, Offset, SrcRTTI, DestRTTI,
1019 llvm::ConstantInt::get(CGF.Int32Ty, DestTy->isReferenceType())};
1020 ThisPtr = CGF.EmitRuntimeCallOrInvoke(Function, Args).getInstruction();
1021 return CGF.Builder.CreateBitCast(ThisPtr, DestLTy);
1025 MicrosoftCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF, Address Value,
1026 QualType SrcRecordTy,
1028 llvm::Value *Offset;
1029 std::tie(Value, Offset) = performBaseAdjustment(CGF, Value, SrcRecordTy);
1031 // PVOID __RTCastToVoid(
1033 llvm::Type *ArgTypes[] = {CGF.Int8PtrTy};
1034 llvm::Constant *Function = CGF.CGM.CreateRuntimeFunction(
1035 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false),
1037 llvm::Value *Args[] = {Value.getPointer()};
1038 return CGF.EmitRuntimeCall(Function, Args);
1041 bool MicrosoftCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1045 llvm::Value *MicrosoftCXXABI::GetVirtualBaseClassOffset(
1046 CodeGenFunction &CGF, Address This, const CXXRecordDecl *ClassDecl,
1047 const CXXRecordDecl *BaseClassDecl) {
1048 const ASTContext &Context = getContext();
1049 int64_t VBPtrChars =
1050 Context.getASTRecordLayout(ClassDecl).getVBPtrOffset().getQuantity();
1051 llvm::Value *VBPtrOffset = llvm::ConstantInt::get(CGM.PtrDiffTy, VBPtrChars);
1052 CharUnits IntSize = Context.getTypeSizeInChars(Context.IntTy);
1053 CharUnits VBTableChars =
1055 CGM.getMicrosoftVTableContext().getVBTableIndex(ClassDecl, BaseClassDecl);
1056 llvm::Value *VBTableOffset =
1057 llvm::ConstantInt::get(CGM.IntTy, VBTableChars.getQuantity());
1059 llvm::Value *VBPtrToNewBase =
1060 GetVBaseOffsetFromVBPtr(CGF, This, VBPtrOffset, VBTableOffset);
1062 CGF.Builder.CreateSExtOrBitCast(VBPtrToNewBase, CGM.PtrDiffTy);
1063 return CGF.Builder.CreateNSWAdd(VBPtrOffset, VBPtrToNewBase);
1066 bool MicrosoftCXXABI::HasThisReturn(GlobalDecl GD) const {
1067 return isa<CXXConstructorDecl>(GD.getDecl());
1070 static bool isDeletingDtor(GlobalDecl GD) {
1071 return isa<CXXDestructorDecl>(GD.getDecl()) &&
1072 GD.getDtorType() == Dtor_Deleting;
1075 bool MicrosoftCXXABI::hasMostDerivedReturn(GlobalDecl GD) const {
1076 return isDeletingDtor(GD);
1079 bool MicrosoftCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
1080 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
1084 CharUnits Align = CGM.getContext().getTypeAlignInChars(FI.getReturnType());
1085 if (FI.isInstanceMethod()) {
1086 // If it's an instance method, aggregates are always returned indirectly via
1087 // the second parameter.
1088 FI.getReturnInfo() = ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
1089 FI.getReturnInfo().setSRetAfterThis(FI.isInstanceMethod());
1091 } else if (!RD->isPOD()) {
1092 // If it's a free function, non-POD types are returned indirectly.
1093 FI.getReturnInfo() = ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
1097 // Otherwise, use the C ABI rules.
1102 MicrosoftCXXABI::EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
1103 const CXXRecordDecl *RD) {
1104 llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);
1105 assert(IsMostDerivedClass &&
1106 "ctor for a class with virtual bases must have an implicit parameter");
1107 llvm::Value *IsCompleteObject =
1108 CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");
1110 llvm::BasicBlock *CallVbaseCtorsBB = CGF.createBasicBlock("ctor.init_vbases");
1111 llvm::BasicBlock *SkipVbaseCtorsBB = CGF.createBasicBlock("ctor.skip_vbases");
1112 CGF.Builder.CreateCondBr(IsCompleteObject,
1113 CallVbaseCtorsBB, SkipVbaseCtorsBB);
1115 CGF.EmitBlock(CallVbaseCtorsBB);
1117 // Fill in the vbtable pointers here.
1118 EmitVBPtrStores(CGF, RD);
1120 // CGF will put the base ctor calls in this basic block for us later.
1122 return SkipVbaseCtorsBB;
1125 void MicrosoftCXXABI::initializeHiddenVirtualInheritanceMembers(
1126 CodeGenFunction &CGF, const CXXRecordDecl *RD) {
1127 // In most cases, an override for a vbase virtual method can adjust
1128 // the "this" parameter by applying a constant offset.
1129 // However, this is not enough while a constructor or a destructor of some
1130 // class X is being executed if all the following conditions are met:
1131 // - X has virtual bases, (1)
1132 // - X overrides a virtual method M of a vbase Y, (2)
1133 // - X itself is a vbase of the most derived class.
1135 // If (1) and (2) are true, the vtorDisp for vbase Y is a hidden member of X
1136 // which holds the extra amount of "this" adjustment we must do when we use
1137 // the X vftables (i.e. during X ctor or dtor).
1138 // Outside the ctors and dtors, the values of vtorDisps are zero.
1140 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1141 typedef ASTRecordLayout::VBaseOffsetsMapTy VBOffsets;
1142 const VBOffsets &VBaseMap = Layout.getVBaseOffsetsMap();
1143 CGBuilderTy &Builder = CGF.Builder;
1145 unsigned AS = getThisAddress(CGF).getAddressSpace();
1146 llvm::Value *Int8This = nullptr; // Initialize lazily.
1148 for (VBOffsets::const_iterator I = VBaseMap.begin(), E = VBaseMap.end();
1150 if (!I->second.hasVtorDisp())
1153 llvm::Value *VBaseOffset =
1154 GetVirtualBaseClassOffset(CGF, getThisAddress(CGF), RD, I->first);
1155 // FIXME: it doesn't look right that we SExt in GetVirtualBaseClassOffset()
1156 // just to Trunc back immediately.
1157 VBaseOffset = Builder.CreateTruncOrBitCast(VBaseOffset, CGF.Int32Ty);
1158 uint64_t ConstantVBaseOffset =
1159 Layout.getVBaseClassOffset(I->first).getQuantity();
1161 // vtorDisp_for_vbase = vbptr[vbase_idx] - offsetof(RD, vbase).
1162 llvm::Value *VtorDispValue = Builder.CreateSub(
1163 VBaseOffset, llvm::ConstantInt::get(CGM.Int32Ty, ConstantVBaseOffset),
1167 Int8This = Builder.CreateBitCast(getThisValue(CGF),
1168 CGF.Int8Ty->getPointerTo(AS));
1169 llvm::Value *VtorDispPtr = Builder.CreateInBoundsGEP(Int8This, VBaseOffset);
1170 // vtorDisp is always the 32-bits before the vbase in the class layout.
1171 VtorDispPtr = Builder.CreateConstGEP1_32(VtorDispPtr, -4);
1172 VtorDispPtr = Builder.CreateBitCast(
1173 VtorDispPtr, CGF.Int32Ty->getPointerTo(AS), "vtordisp.ptr");
1175 Builder.CreateAlignedStore(VtorDispValue, VtorDispPtr,
1176 CharUnits::fromQuantity(4));
1180 static bool hasDefaultCXXMethodCC(ASTContext &Context,
1181 const CXXMethodDecl *MD) {
1182 CallingConv ExpectedCallingConv = Context.getDefaultCallingConvention(
1183 /*IsVariadic=*/false, /*IsCXXMethod=*/true);
1184 CallingConv ActualCallingConv =
1185 MD->getType()->getAs<FunctionProtoType>()->getCallConv();
1186 return ExpectedCallingConv == ActualCallingConv;
1189 void MicrosoftCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1190 // There's only one constructor type in this ABI.
1191 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1193 // Exported default constructors either have a simple call-site where they use
1194 // the typical calling convention and have a single 'this' pointer for an
1195 // argument -or- they get a wrapper function which appropriately thunks to the
1196 // real default constructor. This thunk is the default constructor closure.
1197 if (D->hasAttr<DLLExportAttr>() && D->isDefaultConstructor())
1198 if (!hasDefaultCXXMethodCC(getContext(), D) || D->getNumParams() != 0) {
1199 llvm::Function *Fn = getAddrOfCXXCtorClosure(D, Ctor_DefaultClosure);
1200 Fn->setLinkage(llvm::GlobalValue::WeakODRLinkage);
1201 Fn->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1205 void MicrosoftCXXABI::EmitVBPtrStores(CodeGenFunction &CGF,
1206 const CXXRecordDecl *RD) {
1207 Address This = getThisAddress(CGF);
1208 This = CGF.Builder.CreateElementBitCast(This, CGM.Int8Ty, "this.int8");
1209 const ASTContext &Context = getContext();
1210 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1212 const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
1213 for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) {
1214 const VPtrInfo *VBT = (*VBGlobals.VBTables)[I];
1215 llvm::GlobalVariable *GV = VBGlobals.Globals[I];
1216 const ASTRecordLayout &SubobjectLayout =
1217 Context.getASTRecordLayout(VBT->BaseWithVPtr);
1218 CharUnits Offs = VBT->NonVirtualOffset;
1219 Offs += SubobjectLayout.getVBPtrOffset();
1220 if (VBT->getVBaseWithVPtr())
1221 Offs += Layout.getVBaseClassOffset(VBT->getVBaseWithVPtr());
1222 Address VBPtr = CGF.Builder.CreateConstInBoundsByteGEP(This, Offs);
1223 llvm::Value *GVPtr =
1224 CGF.Builder.CreateConstInBoundsGEP2_32(GV->getValueType(), GV, 0, 0);
1225 VBPtr = CGF.Builder.CreateElementBitCast(VBPtr, GVPtr->getType(),
1226 "vbptr." + VBT->ReusingBase->getName());
1227 CGF.Builder.CreateStore(GVPtr, VBPtr);
1232 MicrosoftCXXABI::buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
1233 SmallVectorImpl<CanQualType> &ArgTys) {
1234 // TODO: 'for base' flag
1235 if (T == StructorType::Deleting) {
1236 // The scalar deleting destructor takes an implicit int parameter.
1237 ArgTys.push_back(getContext().IntTy);
1239 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
1243 // All parameters are already in place except is_most_derived, which goes
1244 // after 'this' if it's variadic and last if it's not.
1246 const CXXRecordDecl *Class = CD->getParent();
1247 const FunctionProtoType *FPT = CD->getType()->castAs<FunctionProtoType>();
1248 if (Class->getNumVBases()) {
1249 if (FPT->isVariadic())
1250 ArgTys.insert(ArgTys.begin() + 1, getContext().IntTy);
1252 ArgTys.push_back(getContext().IntTy);
1256 void MicrosoftCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
1257 // The TU defining a dtor is only guaranteed to emit a base destructor. All
1258 // other destructor variants are delegating thunks.
1259 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
1263 MicrosoftCXXABI::getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD) {
1264 GD = GD.getCanonicalDecl();
1265 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1267 GlobalDecl LookupGD = GD;
1268 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1269 // Complete destructors take a pointer to the complete object as a
1270 // parameter, thus don't need this adjustment.
1271 if (GD.getDtorType() == Dtor_Complete)
1274 // There's no Dtor_Base in vftable but it shares the this adjustment with
1275 // the deleting one, so look it up instead.
1276 LookupGD = GlobalDecl(DD, Dtor_Deleting);
1279 MicrosoftVTableContext::MethodVFTableLocation ML =
1280 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD);
1281 CharUnits Adjustment = ML.VFPtrOffset;
1283 // Normal virtual instance methods need to adjust from the vfptr that first
1284 // defined the virtual method to the virtual base subobject, but destructors
1285 // do not. The vector deleting destructor thunk applies this adjustment for
1287 if (isa<CXXDestructorDecl>(MD))
1288 Adjustment = CharUnits::Zero();
1291 const ASTRecordLayout &DerivedLayout =
1292 getContext().getASTRecordLayout(MD->getParent());
1293 Adjustment += DerivedLayout.getVBaseClassOffset(ML.VBase);
1299 Address MicrosoftCXXABI::adjustThisArgumentForVirtualFunctionCall(
1300 CodeGenFunction &CGF, GlobalDecl GD, Address This,
1303 // If the call of a virtual function is not virtual, we just have to
1304 // compensate for the adjustment the virtual function does in its prologue.
1305 CharUnits Adjustment = getVirtualFunctionPrologueThisAdjustment(GD);
1306 if (Adjustment.isZero())
1309 This = CGF.Builder.CreateElementBitCast(This, CGF.Int8Ty);
1310 assert(Adjustment.isPositive());
1311 return CGF.Builder.CreateConstByteGEP(This, Adjustment);
1314 GD = GD.getCanonicalDecl();
1315 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1317 GlobalDecl LookupGD = GD;
1318 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1319 // Complete dtors take a pointer to the complete object,
1320 // thus don't need adjustment.
1321 if (GD.getDtorType() == Dtor_Complete)
1324 // There's only Dtor_Deleting in vftable but it shares the this adjustment
1325 // with the base one, so look up the deleting one instead.
1326 LookupGD = GlobalDecl(DD, Dtor_Deleting);
1328 MicrosoftVTableContext::MethodVFTableLocation ML =
1329 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD);
1331 CharUnits StaticOffset = ML.VFPtrOffset;
1333 // Base destructors expect 'this' to point to the beginning of the base
1334 // subobject, not the first vfptr that happens to contain the virtual dtor.
1335 // However, we still need to apply the virtual base adjustment.
1336 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
1337 StaticOffset = CharUnits::Zero();
1339 Address Result = This;
1341 Result = CGF.Builder.CreateElementBitCast(Result, CGF.Int8Ty);
1343 const CXXRecordDecl *Derived = MD->getParent();
1344 const CXXRecordDecl *VBase = ML.VBase;
1345 llvm::Value *VBaseOffset =
1346 GetVirtualBaseClassOffset(CGF, Result, Derived, VBase);
1347 llvm::Value *VBasePtr =
1348 CGF.Builder.CreateInBoundsGEP(Result.getPointer(), VBaseOffset);
1349 CharUnits VBaseAlign =
1350 CGF.CGM.getVBaseAlignment(Result.getAlignment(), Derived, VBase);
1351 Result = Address(VBasePtr, VBaseAlign);
1353 if (!StaticOffset.isZero()) {
1354 assert(StaticOffset.isPositive());
1355 Result = CGF.Builder.CreateElementBitCast(Result, CGF.Int8Ty);
1357 // Non-virtual adjustment might result in a pointer outside the allocated
1358 // object, e.g. if the final overrider class is laid out after the virtual
1359 // base that declares a method in the most derived class.
1360 // FIXME: Update the code that emits this adjustment in thunks prologues.
1361 Result = CGF.Builder.CreateConstByteGEP(Result, StaticOffset);
1363 Result = CGF.Builder.CreateConstInBoundsByteGEP(Result, StaticOffset);
1369 void MicrosoftCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1371 FunctionArgList &Params) {
1372 ASTContext &Context = getContext();
1373 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
1374 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
1375 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
1376 ImplicitParamDecl *IsMostDerived
1377 = ImplicitParamDecl::Create(Context, nullptr,
1378 CGF.CurGD.getDecl()->getLocation(),
1379 &Context.Idents.get("is_most_derived"),
1381 // The 'most_derived' parameter goes second if the ctor is variadic and last
1382 // if it's not. Dtors can't be variadic.
1383 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
1384 if (FPT->isVariadic())
1385 Params.insert(Params.begin() + 1, IsMostDerived);
1387 Params.push_back(IsMostDerived);
1388 getStructorImplicitParamDecl(CGF) = IsMostDerived;
1389 } else if (isDeletingDtor(CGF.CurGD)) {
1390 ImplicitParamDecl *ShouldDelete
1391 = ImplicitParamDecl::Create(Context, nullptr,
1392 CGF.CurGD.getDecl()->getLocation(),
1393 &Context.Idents.get("should_call_delete"),
1395 Params.push_back(ShouldDelete);
1396 getStructorImplicitParamDecl(CGF) = ShouldDelete;
1400 llvm::Value *MicrosoftCXXABI::adjustThisParameterInVirtualFunctionPrologue(
1401 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) {
1402 // In this ABI, every virtual function takes a pointer to one of the
1403 // subobjects that first defines it as the 'this' parameter, rather than a
1404 // pointer to the final overrider subobject. Thus, we need to adjust it back
1405 // to the final overrider subobject before use.
1406 // See comments in the MicrosoftVFTableContext implementation for the details.
1407 CharUnits Adjustment = getVirtualFunctionPrologueThisAdjustment(GD);
1408 if (Adjustment.isZero())
1411 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
1412 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS),
1413 *thisTy = This->getType();
1415 This = CGF.Builder.CreateBitCast(This, charPtrTy);
1416 assert(Adjustment.isPositive());
1417 This = CGF.Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, This,
1418 -Adjustment.getQuantity());
1419 return CGF.Builder.CreateBitCast(This, thisTy);
1422 void MicrosoftCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
1425 /// If this is a function that the ABI specifies returns 'this', initialize
1426 /// the return slot to 'this' at the start of the function.
1428 /// Unlike the setting of return types, this is done within the ABI
1429 /// implementation instead of by clients of CGCXXABI because:
1430 /// 1) getThisValue is currently protected
1431 /// 2) in theory, an ABI could implement 'this' returns some other way;
1432 /// HasThisReturn only specifies a contract, not the implementation
1433 if (HasThisReturn(CGF.CurGD))
1434 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
1435 else if (hasMostDerivedReturn(CGF.CurGD))
1436 CGF.Builder.CreateStore(CGF.EmitCastToVoidPtr(getThisValue(CGF)),
1439 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
1440 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
1441 assert(getStructorImplicitParamDecl(CGF) &&
1442 "no implicit parameter for a constructor with virtual bases?");
1443 getStructorImplicitParamValue(CGF)
1444 = CGF.Builder.CreateLoad(
1445 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
1449 if (isDeletingDtor(CGF.CurGD)) {
1450 assert(getStructorImplicitParamDecl(CGF) &&
1451 "no implicit parameter for a deleting destructor?");
1452 getStructorImplicitParamValue(CGF)
1453 = CGF.Builder.CreateLoad(
1454 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
1455 "should_call_delete");
1459 unsigned MicrosoftCXXABI::addImplicitConstructorArgs(
1460 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1461 bool ForVirtualBase, bool Delegating, CallArgList &Args) {
1462 assert(Type == Ctor_Complete || Type == Ctor_Base);
1464 // Check if we need a 'most_derived' parameter.
1465 if (!D->getParent()->getNumVBases())
1468 // Add the 'most_derived' argument second if we are variadic or last if not.
1469 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
1470 llvm::Value *MostDerivedArg =
1471 llvm::ConstantInt::get(CGM.Int32Ty, Type == Ctor_Complete);
1472 RValue RV = RValue::get(MostDerivedArg);
1473 if (MostDerivedArg) {
1474 if (FPT->isVariadic())
1475 Args.insert(Args.begin() + 1,
1476 CallArg(RV, getContext().IntTy, /*needscopy=*/false));
1478 Args.add(RV, getContext().IntTy);
1481 return 1; // Added one arg.
1484 void MicrosoftCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1485 const CXXDestructorDecl *DD,
1486 CXXDtorType Type, bool ForVirtualBase,
1487 bool Delegating, Address This) {
1488 llvm::Value *Callee = CGM.getAddrOfCXXStructor(DD, getFromDtorType(Type));
1490 if (DD->isVirtual()) {
1491 assert(Type != CXXDtorType::Dtor_Deleting &&
1492 "The deleting destructor should only be called via a virtual call");
1493 This = adjustThisArgumentForVirtualFunctionCall(CGF, GlobalDecl(DD, Type),
1497 CGF.EmitCXXStructorCall(DD, Callee, ReturnValueSlot(), This.getPointer(),
1498 /*ImplicitParam=*/nullptr,
1499 /*ImplicitParamTy=*/QualType(), nullptr,
1500 getFromDtorType(Type));
1503 void MicrosoftCXXABI::emitVTableBitSetEntries(VPtrInfo *Info,
1504 const CXXRecordDecl *RD,
1505 llvm::GlobalVariable *VTable) {
1506 if (!getContext().getLangOpts().Sanitize.has(SanitizerKind::CFIVCall) &&
1507 !getContext().getLangOpts().Sanitize.has(SanitizerKind::CFINVCall) &&
1508 !getContext().getLangOpts().Sanitize.has(SanitizerKind::CFIDerivedCast) &&
1509 !getContext().getLangOpts().Sanitize.has(SanitizerKind::CFIUnrelatedCast))
1512 llvm::NamedMDNode *BitsetsMD =
1513 CGM.getModule().getOrInsertNamedMetadata("llvm.bitsets");
1515 // The location of the first virtual function pointer in the virtual table,
1516 // aka the "address point" on Itanium. This is at offset 0 if RTTI is
1517 // disabled, or sizeof(void*) if RTTI is enabled.
1518 CharUnits AddressPoint =
1519 getContext().getLangOpts().RTTIData
1520 ? getContext().toCharUnitsFromBits(
1521 getContext().getTargetInfo().getPointerWidth(0))
1522 : CharUnits::Zero();
1524 if (Info->PathToBaseWithVPtr.empty()) {
1525 if (!CGM.IsCFIBlacklistedRecord(RD))
1526 CGM.CreateVTableBitSetEntry(BitsetsMD, VTable, AddressPoint, RD);
1530 // Add a bitset entry for the least derived base belonging to this vftable.
1531 if (!CGM.IsCFIBlacklistedRecord(Info->PathToBaseWithVPtr.back()))
1532 CGM.CreateVTableBitSetEntry(BitsetsMD, VTable, AddressPoint,
1533 Info->PathToBaseWithVPtr.back());
1535 // Add a bitset entry for each derived class that is laid out at the same
1536 // offset as the least derived base.
1537 for (unsigned I = Info->PathToBaseWithVPtr.size() - 1; I != 0; --I) {
1538 const CXXRecordDecl *DerivedRD = Info->PathToBaseWithVPtr[I - 1];
1539 const CXXRecordDecl *BaseRD = Info->PathToBaseWithVPtr[I];
1541 const ASTRecordLayout &Layout =
1542 getContext().getASTRecordLayout(DerivedRD);
1544 auto VBI = Layout.getVBaseOffsetsMap().find(BaseRD);
1545 if (VBI == Layout.getVBaseOffsetsMap().end())
1546 Offset = Layout.getBaseClassOffset(BaseRD);
1548 Offset = VBI->second.VBaseOffset;
1549 if (!Offset.isZero())
1551 if (!CGM.IsCFIBlacklistedRecord(DerivedRD))
1552 CGM.CreateVTableBitSetEntry(BitsetsMD, VTable, AddressPoint, DerivedRD);
1555 // Finally do the same for the most derived class.
1556 if (Info->FullOffsetInMDC.isZero() && !CGM.IsCFIBlacklistedRecord(RD))
1557 CGM.CreateVTableBitSetEntry(BitsetsMD, VTable, AddressPoint, RD);
1560 void MicrosoftCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1561 const CXXRecordDecl *RD) {
1562 MicrosoftVTableContext &VFTContext = CGM.getMicrosoftVTableContext();
1563 const VPtrInfoVector &VFPtrs = VFTContext.getVFPtrOffsets(RD);
1565 for (VPtrInfo *Info : VFPtrs) {
1566 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, Info->FullOffsetInMDC);
1567 if (VTable->hasInitializer())
1570 const VTableLayout &VTLayout =
1571 VFTContext.getVFTableLayout(RD, Info->FullOffsetInMDC);
1573 llvm::Constant *RTTI = nullptr;
1574 if (any_of(VTLayout.vtable_components(),
1575 [](const VTableComponent &VTC) { return VTC.isRTTIKind(); }))
1576 RTTI = getMSCompleteObjectLocator(RD, Info);
1578 llvm::Constant *Init = CGVT.CreateVTableInitializer(
1579 RD, VTLayout.vtable_component_begin(),
1580 VTLayout.getNumVTableComponents(), VTLayout.vtable_thunk_begin(),
1581 VTLayout.getNumVTableThunks(), RTTI);
1583 VTable->setInitializer(Init);
1585 emitVTableBitSetEntries(Info, RD, VTable);
1589 bool MicrosoftCXXABI::isVirtualOffsetNeededForVTableField(
1590 CodeGenFunction &CGF, CodeGenFunction::VPtr Vptr) {
1591 return Vptr.NearestVBase != nullptr;
1594 llvm::Value *MicrosoftCXXABI::getVTableAddressPointInStructor(
1595 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1596 const CXXRecordDecl *NearestVBase) {
1597 llvm::Constant *VTableAddressPoint = getVTableAddressPoint(Base, VTableClass);
1598 if (!VTableAddressPoint) {
1599 assert(Base.getBase()->getNumVBases() &&
1600 !getContext().getASTRecordLayout(Base.getBase()).hasOwnVFPtr());
1602 return VTableAddressPoint;
1605 static void mangleVFTableName(MicrosoftMangleContext &MangleContext,
1606 const CXXRecordDecl *RD, const VPtrInfo *VFPtr,
1607 SmallString<256> &Name) {
1608 llvm::raw_svector_ostream Out(Name);
1609 MangleContext.mangleCXXVFTable(RD, VFPtr->MangledPath, Out);
1613 MicrosoftCXXABI::getVTableAddressPoint(BaseSubobject Base,
1614 const CXXRecordDecl *VTableClass) {
1615 (void)getAddrOfVTable(VTableClass, Base.getBaseOffset());
1616 VFTableIdTy ID(VTableClass, Base.getBaseOffset());
1617 return VFTablesMap[ID];
1620 llvm::Constant *MicrosoftCXXABI::getVTableAddressPointForConstExpr(
1621 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1622 llvm::Constant *VFTable = getVTableAddressPoint(Base, VTableClass);
1623 assert(VFTable && "Couldn't find a vftable for the given base?");
1627 llvm::GlobalVariable *MicrosoftCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1628 CharUnits VPtrOffset) {
1629 // getAddrOfVTable may return 0 if asked to get an address of a vtable which
1630 // shouldn't be used in the given record type. We want to cache this result in
1631 // VFTablesMap, thus a simple zero check is not sufficient.
1633 VFTableIdTy ID(RD, VPtrOffset);
1634 VTablesMapTy::iterator I;
1636 std::tie(I, Inserted) = VTablesMap.insert(std::make_pair(ID, nullptr));
1640 llvm::GlobalVariable *&VTable = I->second;
1642 MicrosoftVTableContext &VTContext = CGM.getMicrosoftVTableContext();
1643 const VPtrInfoVector &VFPtrs = VTContext.getVFPtrOffsets(RD);
1645 if (DeferredVFTables.insert(RD).second) {
1646 // We haven't processed this record type before.
1647 // Queue up this vtable for possible deferred emission.
1648 CGM.addDeferredVTable(RD);
1651 // Create all the vftables at once in order to make sure each vftable has
1652 // a unique mangled name.
1653 llvm::StringSet<> ObservedMangledNames;
1654 for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) {
1655 SmallString<256> Name;
1656 mangleVFTableName(getMangleContext(), RD, VFPtrs[J], Name);
1657 if (!ObservedMangledNames.insert(Name.str()).second)
1658 llvm_unreachable("Already saw this mangling before?");
1663 VPtrInfo *const *VFPtrI =
1664 std::find_if(VFPtrs.begin(), VFPtrs.end(), [&](VPtrInfo *VPI) {
1665 return VPI->FullOffsetInMDC == VPtrOffset;
1667 if (VFPtrI == VFPtrs.end()) {
1668 VFTablesMap[ID] = nullptr;
1671 VPtrInfo *VFPtr = *VFPtrI;
1673 SmallString<256> VFTableName;
1674 mangleVFTableName(getMangleContext(), RD, VFPtr, VFTableName);
1676 // Classes marked __declspec(dllimport) need vftables generated on the
1677 // import-side in order to support features like constexpr. No other
1678 // translation unit relies on the emission of the local vftable, translation
1679 // units are expected to generate them as needed.
1681 // Because of this unique behavior, we maintain this logic here instead of
1682 // getVTableLinkage.
1683 llvm::GlobalValue::LinkageTypes VFTableLinkage =
1684 RD->hasAttr<DLLImportAttr>() ? llvm::GlobalValue::LinkOnceODRLinkage
1685 : CGM.getVTableLinkage(RD);
1686 bool VFTableComesFromAnotherTU =
1687 llvm::GlobalValue::isAvailableExternallyLinkage(VFTableLinkage) ||
1688 llvm::GlobalValue::isExternalLinkage(VFTableLinkage);
1689 bool VTableAliasIsRequred =
1690 !VFTableComesFromAnotherTU && getContext().getLangOpts().RTTIData;
1692 if (llvm::GlobalValue *VFTable =
1693 CGM.getModule().getNamedGlobal(VFTableName)) {
1694 VFTablesMap[ID] = VFTable;
1695 VTable = VTableAliasIsRequred
1696 ? cast<llvm::GlobalVariable>(
1697 cast<llvm::GlobalAlias>(VFTable)->getBaseObject())
1698 : cast<llvm::GlobalVariable>(VFTable);
1702 uint64_t NumVTableSlots =
1703 VTContext.getVFTableLayout(RD, VFPtr->FullOffsetInMDC)
1704 .getNumVTableComponents();
1705 llvm::GlobalValue::LinkageTypes VTableLinkage =
1706 VTableAliasIsRequred ? llvm::GlobalValue::PrivateLinkage : VFTableLinkage;
1708 StringRef VTableName = VTableAliasIsRequred ? StringRef() : VFTableName.str();
1710 llvm::ArrayType *VTableType =
1711 llvm::ArrayType::get(CGM.Int8PtrTy, NumVTableSlots);
1713 // Create a backing variable for the contents of VTable. The VTable may
1714 // or may not include space for a pointer to RTTI data.
1715 llvm::GlobalValue *VFTable;
1716 VTable = new llvm::GlobalVariable(CGM.getModule(), VTableType,
1717 /*isConstant=*/true, VTableLinkage,
1718 /*Initializer=*/nullptr, VTableName);
1719 VTable->setUnnamedAddr(true);
1721 llvm::Comdat *C = nullptr;
1722 if (!VFTableComesFromAnotherTU &&
1723 (llvm::GlobalValue::isWeakForLinker(VFTableLinkage) ||
1724 (llvm::GlobalValue::isLocalLinkage(VFTableLinkage) &&
1725 VTableAliasIsRequred)))
1726 C = CGM.getModule().getOrInsertComdat(VFTableName.str());
1728 // Only insert a pointer into the VFTable for RTTI data if we are not
1729 // importing it. We never reference the RTTI data directly so there is no
1730 // need to make room for it.
1731 if (VTableAliasIsRequred) {
1732 llvm::Value *GEPIndices[] = {llvm::ConstantInt::get(CGM.IntTy, 0),
1733 llvm::ConstantInt::get(CGM.IntTy, 1)};
1734 // Create a GEP which points just after the first entry in the VFTable,
1735 // this should be the location of the first virtual method.
1736 llvm::Constant *VTableGEP = llvm::ConstantExpr::getInBoundsGetElementPtr(
1737 VTable->getValueType(), VTable, GEPIndices);
1738 if (llvm::GlobalValue::isWeakForLinker(VFTableLinkage)) {
1739 VFTableLinkage = llvm::GlobalValue::ExternalLinkage;
1741 C->setSelectionKind(llvm::Comdat::Largest);
1743 VFTable = llvm::GlobalAlias::create(CGM.Int8PtrTy,
1744 /*AddressSpace=*/0, VFTableLinkage,
1745 VFTableName.str(), VTableGEP,
1747 VFTable->setUnnamedAddr(true);
1749 // We don't need a GlobalAlias to be a symbol for the VTable if we won't
1750 // be referencing any RTTI data.
1751 // The GlobalVariable will end up being an appropriate definition of the
1756 VTable->setComdat(C);
1758 if (RD->hasAttr<DLLExportAttr>())
1759 VFTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1761 VFTablesMap[ID] = VFTable;
1765 // Compute the identity of the most derived class whose virtual table is located
1766 // at the given offset into RD.
1767 static const CXXRecordDecl *getClassAtVTableLocation(ASTContext &Ctx,
1768 const CXXRecordDecl *RD,
1770 if (Offset.isZero())
1773 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(RD);
1774 const CXXRecordDecl *MaxBase = nullptr;
1775 CharUnits MaxBaseOffset;
1776 for (auto &&B : RD->bases()) {
1777 const CXXRecordDecl *Base = B.getType()->getAsCXXRecordDecl();
1778 CharUnits BaseOffset = Layout.getBaseClassOffset(Base);
1779 if (BaseOffset <= Offset && BaseOffset >= MaxBaseOffset) {
1781 MaxBaseOffset = BaseOffset;
1784 for (auto &&B : RD->vbases()) {
1785 const CXXRecordDecl *Base = B.getType()->getAsCXXRecordDecl();
1786 CharUnits BaseOffset = Layout.getVBaseClassOffset(Base);
1787 if (BaseOffset <= Offset && BaseOffset >= MaxBaseOffset) {
1789 MaxBaseOffset = BaseOffset;
1793 return getClassAtVTableLocation(Ctx, MaxBase, Offset - MaxBaseOffset);
1796 // Compute the identity of the most derived class whose virtual table is located
1797 // at the MethodVFTableLocation ML.
1798 static const CXXRecordDecl *
1799 getClassAtVTableLocation(ASTContext &Ctx, GlobalDecl GD,
1800 MicrosoftVTableContext::MethodVFTableLocation &ML) {
1801 const CXXRecordDecl *RD = ML.VBase;
1803 RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
1805 return getClassAtVTableLocation(Ctx, RD, ML.VFPtrOffset);
1808 llvm::Value *MicrosoftCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1812 SourceLocation Loc) {
1813 GD = GD.getCanonicalDecl();
1814 CGBuilderTy &Builder = CGF.Builder;
1816 Ty = Ty->getPointerTo()->getPointerTo();
1818 adjustThisArgumentForVirtualFunctionCall(CGF, GD, This, true);
1820 auto *MethodDecl = cast<CXXMethodDecl>(GD.getDecl());
1821 llvm::Value *VTable = CGF.GetVTablePtr(VPtr, Ty, MethodDecl->getParent());
1823 MicrosoftVTableContext::MethodVFTableLocation ML =
1824 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD);
1825 if (CGF.SanOpts.has(SanitizerKind::CFIVCall))
1826 CGF.EmitVTablePtrCheck(getClassAtVTableLocation(getContext(), GD, ML),
1827 VTable, CodeGenFunction::CFITCK_VCall, Loc);
1829 llvm::Value *VFuncPtr =
1830 Builder.CreateConstInBoundsGEP1_64(VTable, ML.Index, "vfn");
1831 return Builder.CreateAlignedLoad(VFuncPtr, CGF.getPointerAlign());
1834 llvm::Value *MicrosoftCXXABI::EmitVirtualDestructorCall(
1835 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
1836 Address This, const CXXMemberCallExpr *CE) {
1837 assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
1838 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1840 // We have only one destructor in the vftable but can get both behaviors
1841 // by passing an implicit int parameter.
1842 GlobalDecl GD(Dtor, Dtor_Deleting);
1843 const CGFunctionInfo *FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
1844 Dtor, StructorType::Deleting);
1845 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
1846 llvm::Value *Callee = getVirtualFunctionPointer(
1847 CGF, GD, This, Ty, CE ? CE->getLocStart() : SourceLocation());
1849 ASTContext &Context = getContext();
1850 llvm::Value *ImplicitParam = llvm::ConstantInt::get(
1851 llvm::IntegerType::getInt32Ty(CGF.getLLVMContext()),
1852 DtorType == Dtor_Deleting);
1854 This = adjustThisArgumentForVirtualFunctionCall(CGF, GD, This, true);
1855 RValue RV = CGF.EmitCXXStructorCall(Dtor, Callee, ReturnValueSlot(),
1857 ImplicitParam, Context.IntTy, CE,
1858 StructorType::Deleting);
1859 return RV.getScalarVal();
1862 const VBTableGlobals &
1863 MicrosoftCXXABI::enumerateVBTables(const CXXRecordDecl *RD) {
1864 // At this layer, we can key the cache off of a single class, which is much
1865 // easier than caching each vbtable individually.
1866 llvm::DenseMap<const CXXRecordDecl*, VBTableGlobals>::iterator Entry;
1868 std::tie(Entry, Added) =
1869 VBTablesMap.insert(std::make_pair(RD, VBTableGlobals()));
1870 VBTableGlobals &VBGlobals = Entry->second;
1874 MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext();
1875 VBGlobals.VBTables = &Context.enumerateVBTables(RD);
1877 // Cache the globals for all vbtables so we don't have to recompute the
1879 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
1880 for (VPtrInfoVector::const_iterator I = VBGlobals.VBTables->begin(),
1881 E = VBGlobals.VBTables->end();
1883 VBGlobals.Globals.push_back(getAddrOfVBTable(**I, RD, Linkage));
1889 llvm::Function *MicrosoftCXXABI::EmitVirtualMemPtrThunk(
1890 const CXXMethodDecl *MD,
1891 const MicrosoftVTableContext::MethodVFTableLocation &ML) {
1892 assert(!isa<CXXConstructorDecl>(MD) && !isa<CXXDestructorDecl>(MD) &&
1893 "can't form pointers to ctors or virtual dtors");
1895 // Calculate the mangled name.
1896 SmallString<256> ThunkName;
1897 llvm::raw_svector_ostream Out(ThunkName);
1898 getMangleContext().mangleVirtualMemPtrThunk(MD, Out);
1900 // If the thunk has been generated previously, just return it.
1901 if (llvm::GlobalValue *GV = CGM.getModule().getNamedValue(ThunkName))
1902 return cast<llvm::Function>(GV);
1904 // Create the llvm::Function.
1905 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeMSMemberPointerThunk(MD);
1906 llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo);
1907 llvm::Function *ThunkFn =
1908 llvm::Function::Create(ThunkTy, llvm::Function::ExternalLinkage,
1909 ThunkName.str(), &CGM.getModule());
1910 assert(ThunkFn->getName() == ThunkName && "name was uniqued!");
1912 ThunkFn->setLinkage(MD->isExternallyVisible()
1913 ? llvm::GlobalValue::LinkOnceODRLinkage
1914 : llvm::GlobalValue::InternalLinkage);
1915 if (MD->isExternallyVisible())
1916 ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));
1918 CGM.SetLLVMFunctionAttributes(MD, FnInfo, ThunkFn);
1919 CGM.SetLLVMFunctionAttributesForDefinition(MD, ThunkFn);
1921 // Add the "thunk" attribute so that LLVM knows that the return type is
1922 // meaningless. These thunks can be used to call functions with differing
1923 // return types, and the caller is required to cast the prototype
1924 // appropriately to extract the correct value.
1925 ThunkFn->addFnAttr("thunk");
1927 // These thunks can be compared, so they are not unnamed.
1928 ThunkFn->setUnnamedAddr(false);
1931 CodeGenFunction CGF(CGM);
1932 CGF.CurGD = GlobalDecl(MD);
1933 CGF.CurFuncIsThunk = true;
1935 // Build FunctionArgs, but only include the implicit 'this' parameter
1937 FunctionArgList FunctionArgs;
1938 buildThisParam(CGF, FunctionArgs);
1940 // Start defining the function.
1941 CGF.StartFunction(GlobalDecl(), FnInfo.getReturnType(), ThunkFn, FnInfo,
1942 FunctionArgs, MD->getLocation(), SourceLocation());
1945 // Load the vfptr and then callee from the vftable. The callee should have
1946 // adjusted 'this' so that the vfptr is at offset zero.
1947 llvm::Value *VTable = CGF.GetVTablePtr(
1948 getThisAddress(CGF), ThunkTy->getPointerTo()->getPointerTo(), MD->getParent());
1950 llvm::Value *VFuncPtr =
1951 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, ML.Index, "vfn");
1952 llvm::Value *Callee =
1953 CGF.Builder.CreateAlignedLoad(VFuncPtr, CGF.getPointerAlign());
1955 CGF.EmitMustTailThunk(MD, getThisValue(CGF), Callee);
1960 void MicrosoftCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
1961 const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
1962 for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) {
1963 const VPtrInfo *VBT = (*VBGlobals.VBTables)[I];
1964 llvm::GlobalVariable *GV = VBGlobals.Globals[I];
1965 if (GV->isDeclaration())
1966 emitVBTableDefinition(*VBT, RD, GV);
1970 llvm::GlobalVariable *
1971 MicrosoftCXXABI::getAddrOfVBTable(const VPtrInfo &VBT, const CXXRecordDecl *RD,
1972 llvm::GlobalVariable::LinkageTypes Linkage) {
1973 SmallString<256> OutName;
1974 llvm::raw_svector_ostream Out(OutName);
1975 getMangleContext().mangleCXXVBTable(RD, VBT.MangledPath, Out);
1976 StringRef Name = OutName.str();
1978 llvm::ArrayType *VBTableType =
1979 llvm::ArrayType::get(CGM.IntTy, 1 + VBT.ReusingBase->getNumVBases());
1981 assert(!CGM.getModule().getNamedGlobal(Name) &&
1982 "vbtable with this name already exists: mangling bug?");
1983 llvm::GlobalVariable *GV =
1984 CGM.CreateOrReplaceCXXRuntimeVariable(Name, VBTableType, Linkage);
1985 GV->setUnnamedAddr(true);
1987 if (RD->hasAttr<DLLImportAttr>())
1988 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1989 else if (RD->hasAttr<DLLExportAttr>())
1990 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1992 if (!GV->hasExternalLinkage())
1993 emitVBTableDefinition(VBT, RD, GV);
1998 void MicrosoftCXXABI::emitVBTableDefinition(const VPtrInfo &VBT,
1999 const CXXRecordDecl *RD,
2000 llvm::GlobalVariable *GV) const {
2001 const CXXRecordDecl *ReusingBase = VBT.ReusingBase;
2003 assert(RD->getNumVBases() && ReusingBase->getNumVBases() &&
2004 "should only emit vbtables for classes with vbtables");
2006 const ASTRecordLayout &BaseLayout =
2007 getContext().getASTRecordLayout(VBT.BaseWithVPtr);
2008 const ASTRecordLayout &DerivedLayout = getContext().getASTRecordLayout(RD);
2010 SmallVector<llvm::Constant *, 4> Offsets(1 + ReusingBase->getNumVBases(),
2013 // The offset from ReusingBase's vbptr to itself always leads.
2014 CharUnits VBPtrOffset = BaseLayout.getVBPtrOffset();
2015 Offsets[0] = llvm::ConstantInt::get(CGM.IntTy, -VBPtrOffset.getQuantity());
2017 MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext();
2018 for (const auto &I : ReusingBase->vbases()) {
2019 const CXXRecordDecl *VBase = I.getType()->getAsCXXRecordDecl();
2020 CharUnits Offset = DerivedLayout.getVBaseClassOffset(VBase);
2021 assert(!Offset.isNegative());
2023 // Make it relative to the subobject vbptr.
2024 CharUnits CompleteVBPtrOffset = VBT.NonVirtualOffset + VBPtrOffset;
2025 if (VBT.getVBaseWithVPtr())
2026 CompleteVBPtrOffset +=
2027 DerivedLayout.getVBaseClassOffset(VBT.getVBaseWithVPtr());
2028 Offset -= CompleteVBPtrOffset;
2030 unsigned VBIndex = Context.getVBTableIndex(ReusingBase, VBase);
2031 assert(Offsets[VBIndex] == nullptr && "The same vbindex seen twice?");
2032 Offsets[VBIndex] = llvm::ConstantInt::get(CGM.IntTy, Offset.getQuantity());
2035 assert(Offsets.size() ==
2036 cast<llvm::ArrayType>(cast<llvm::PointerType>(GV->getType())
2037 ->getElementType())->getNumElements());
2038 llvm::ArrayType *VBTableType =
2039 llvm::ArrayType::get(CGM.IntTy, Offsets.size());
2040 llvm::Constant *Init = llvm::ConstantArray::get(VBTableType, Offsets);
2041 GV->setInitializer(Init);
2044 llvm::Value *MicrosoftCXXABI::performThisAdjustment(CodeGenFunction &CGF,
2046 const ThisAdjustment &TA) {
2048 return This.getPointer();
2050 This = CGF.Builder.CreateElementBitCast(This, CGF.Int8Ty);
2053 if (TA.Virtual.isEmpty()) {
2054 V = This.getPointer();
2056 assert(TA.Virtual.Microsoft.VtordispOffset < 0);
2057 // Adjust the this argument based on the vtordisp value.
2058 Address VtorDispPtr =
2059 CGF.Builder.CreateConstInBoundsByteGEP(This,
2060 CharUnits::fromQuantity(TA.Virtual.Microsoft.VtordispOffset));
2061 VtorDispPtr = CGF.Builder.CreateElementBitCast(VtorDispPtr, CGF.Int32Ty);
2062 llvm::Value *VtorDisp = CGF.Builder.CreateLoad(VtorDispPtr, "vtordisp");
2063 V = CGF.Builder.CreateGEP(This.getPointer(),
2064 CGF.Builder.CreateNeg(VtorDisp));
2066 // Unfortunately, having applied the vtordisp means that we no
2067 // longer really have a known alignment for the vbptr step.
2068 // We'll assume the vbptr is pointer-aligned.
2070 if (TA.Virtual.Microsoft.VBPtrOffset) {
2071 // If the final overrider is defined in a virtual base other than the one
2072 // that holds the vfptr, we have to use a vtordispex thunk which looks up
2073 // the vbtable of the derived class.
2074 assert(TA.Virtual.Microsoft.VBPtrOffset > 0);
2075 assert(TA.Virtual.Microsoft.VBOffsetOffset >= 0);
2077 llvm::Value *VBaseOffset =
2078 GetVBaseOffsetFromVBPtr(CGF, Address(V, CGF.getPointerAlign()),
2079 -TA.Virtual.Microsoft.VBPtrOffset,
2080 TA.Virtual.Microsoft.VBOffsetOffset, &VBPtr);
2081 V = CGF.Builder.CreateInBoundsGEP(VBPtr, VBaseOffset);
2085 if (TA.NonVirtual) {
2086 // Non-virtual adjustment might result in a pointer outside the allocated
2087 // object, e.g. if the final overrider class is laid out after the virtual
2088 // base that declares a method in the most derived class.
2089 V = CGF.Builder.CreateConstGEP1_32(V, TA.NonVirtual);
2092 // Don't need to bitcast back, the call CodeGen will handle this.
2097 MicrosoftCXXABI::performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
2098 const ReturnAdjustment &RA) {
2100 return Ret.getPointer();
2102 auto OrigTy = Ret.getType();
2103 Ret = CGF.Builder.CreateElementBitCast(Ret, CGF.Int8Ty);
2105 llvm::Value *V = Ret.getPointer();
2106 if (RA.Virtual.Microsoft.VBIndex) {
2107 assert(RA.Virtual.Microsoft.VBIndex > 0);
2108 int32_t IntSize = CGF.getIntSize().getQuantity();
2110 llvm::Value *VBaseOffset =
2111 GetVBaseOffsetFromVBPtr(CGF, Ret, RA.Virtual.Microsoft.VBPtrOffset,
2112 IntSize * RA.Virtual.Microsoft.VBIndex, &VBPtr);
2113 V = CGF.Builder.CreateInBoundsGEP(VBPtr, VBaseOffset);
2117 V = CGF.Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, V, RA.NonVirtual);
2119 // Cast back to the original type.
2120 return CGF.Builder.CreateBitCast(V, OrigTy);
2123 bool MicrosoftCXXABI::requiresArrayCookie(const CXXDeleteExpr *expr,
2124 QualType elementType) {
2125 // Microsoft seems to completely ignore the possibility of a
2126 // two-argument usual deallocation function.
2127 return elementType.isDestructedType();
2130 bool MicrosoftCXXABI::requiresArrayCookie(const CXXNewExpr *expr) {
2131 // Microsoft seems to completely ignore the possibility of a
2132 // two-argument usual deallocation function.
2133 return expr->getAllocatedType().isDestructedType();
2136 CharUnits MicrosoftCXXABI::getArrayCookieSizeImpl(QualType type) {
2137 // The array cookie is always a size_t; we then pad that out to the
2138 // alignment of the element type.
2139 ASTContext &Ctx = getContext();
2140 return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()),
2141 Ctx.getTypeAlignInChars(type));
2144 llvm::Value *MicrosoftCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
2146 CharUnits cookieSize) {
2147 Address numElementsPtr =
2148 CGF.Builder.CreateElementBitCast(allocPtr, CGF.SizeTy);
2149 return CGF.Builder.CreateLoad(numElementsPtr);
2152 Address MicrosoftCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
2154 llvm::Value *numElements,
2155 const CXXNewExpr *expr,
2156 QualType elementType) {
2157 assert(requiresArrayCookie(expr));
2159 // The size of the cookie.
2160 CharUnits cookieSize = getArrayCookieSizeImpl(elementType);
2162 // Compute an offset to the cookie.
2163 Address cookiePtr = newPtr;
2165 // Write the number of elements into the appropriate slot.
2166 Address numElementsPtr
2167 = CGF.Builder.CreateElementBitCast(cookiePtr, CGF.SizeTy);
2168 CGF.Builder.CreateStore(numElements, numElementsPtr);
2170 // Finally, compute a pointer to the actual data buffer by skipping
2171 // over the cookie completely.
2172 return CGF.Builder.CreateConstInBoundsByteGEP(newPtr, cookieSize);
2175 static void emitGlobalDtorWithTLRegDtor(CodeGenFunction &CGF, const VarDecl &VD,
2176 llvm::Constant *Dtor,
2177 llvm::Constant *Addr) {
2178 // Create a function which calls the destructor.
2179 llvm::Constant *DtorStub = CGF.createAtExitStub(VD, Dtor, Addr);
2181 // extern "C" int __tlregdtor(void (*f)(void));
2182 llvm::FunctionType *TLRegDtorTy = llvm::FunctionType::get(
2183 CGF.IntTy, DtorStub->getType(), /*IsVarArg=*/false);
2185 llvm::Constant *TLRegDtor =
2186 CGF.CGM.CreateRuntimeFunction(TLRegDtorTy, "__tlregdtor");
2187 if (llvm::Function *TLRegDtorFn = dyn_cast<llvm::Function>(TLRegDtor))
2188 TLRegDtorFn->setDoesNotThrow();
2190 CGF.EmitNounwindRuntimeCall(TLRegDtor, DtorStub);
2193 void MicrosoftCXXABI::registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
2194 llvm::Constant *Dtor,
2195 llvm::Constant *Addr) {
2197 return emitGlobalDtorWithTLRegDtor(CGF, D, Dtor, Addr);
2199 // The default behavior is to use atexit.
2200 CGF.registerGlobalDtorWithAtExit(D, Dtor, Addr);
2203 void MicrosoftCXXABI::EmitThreadLocalInitFuncs(
2204 CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
2205 ArrayRef<llvm::Function *> CXXThreadLocalInits,
2206 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) {
2207 // This will create a GV in the .CRT$XDU section. It will point to our
2208 // initialization function. The CRT will call all of these function
2209 // pointers at start-up time and, eventually, at thread-creation time.
2210 auto AddToXDU = [&CGM](llvm::Function *InitFunc) {
2211 llvm::GlobalVariable *InitFuncPtr = new llvm::GlobalVariable(
2212 CGM.getModule(), InitFunc->getType(), /*IsConstant=*/true,
2213 llvm::GlobalVariable::InternalLinkage, InitFunc,
2214 Twine(InitFunc->getName(), "$initializer$"));
2215 InitFuncPtr->setSection(".CRT$XDU");
2216 // This variable has discardable linkage, we have to add it to @llvm.used to
2217 // ensure it won't get discarded.
2218 CGM.addUsedGlobal(InitFuncPtr);
2222 std::vector<llvm::Function *> NonComdatInits;
2223 for (size_t I = 0, E = CXXThreadLocalInitVars.size(); I != E; ++I) {
2224 llvm::GlobalVariable *GV = cast<llvm::GlobalVariable>(
2225 CGM.GetGlobalValue(CGM.getMangledName(CXXThreadLocalInitVars[I])));
2226 llvm::Function *F = CXXThreadLocalInits[I];
2228 // If the GV is already in a comdat group, then we have to join it.
2229 if (llvm::Comdat *C = GV->getComdat())
2230 AddToXDU(F)->setComdat(C);
2232 NonComdatInits.push_back(F);
2235 if (!NonComdatInits.empty()) {
2236 llvm::FunctionType *FTy =
2237 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
2238 llvm::Function *InitFunc = CGM.CreateGlobalInitOrDestructFunction(
2239 FTy, "__tls_init", CGM.getTypes().arrangeNullaryFunction(),
2240 SourceLocation(), /*TLS=*/true);
2241 CodeGenFunction(CGM).GenerateCXXGlobalInitFunc(InitFunc, NonComdatInits);
2247 LValue MicrosoftCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
2249 QualType LValType) {
2250 CGF.CGM.ErrorUnsupported(VD, "thread wrappers");
2254 static ConstantAddress getInitThreadEpochPtr(CodeGenModule &CGM) {
2255 StringRef VarName("_Init_thread_epoch");
2256 CharUnits Align = CGM.getIntAlign();
2257 if (auto *GV = CGM.getModule().getNamedGlobal(VarName))
2258 return ConstantAddress(GV, Align);
2259 auto *GV = new llvm::GlobalVariable(
2260 CGM.getModule(), CGM.IntTy,
2261 /*Constant=*/false, llvm::GlobalVariable::ExternalLinkage,
2262 /*Initializer=*/nullptr, VarName,
2263 /*InsertBefore=*/nullptr, llvm::GlobalVariable::GeneralDynamicTLSModel);
2264 GV->setAlignment(Align.getQuantity());
2265 return ConstantAddress(GV, Align);
2268 static llvm::Constant *getInitThreadHeaderFn(CodeGenModule &CGM) {
2269 llvm::FunctionType *FTy =
2270 llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
2271 CGM.IntTy->getPointerTo(), /*isVarArg=*/false);
2272 return CGM.CreateRuntimeFunction(
2273 FTy, "_Init_thread_header",
2274 llvm::AttributeSet::get(CGM.getLLVMContext(),
2275 llvm::AttributeSet::FunctionIndex,
2276 llvm::Attribute::NoUnwind));
2279 static llvm::Constant *getInitThreadFooterFn(CodeGenModule &CGM) {
2280 llvm::FunctionType *FTy =
2281 llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
2282 CGM.IntTy->getPointerTo(), /*isVarArg=*/false);
2283 return CGM.CreateRuntimeFunction(
2284 FTy, "_Init_thread_footer",
2285 llvm::AttributeSet::get(CGM.getLLVMContext(),
2286 llvm::AttributeSet::FunctionIndex,
2287 llvm::Attribute::NoUnwind));
2290 static llvm::Constant *getInitThreadAbortFn(CodeGenModule &CGM) {
2291 llvm::FunctionType *FTy =
2292 llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
2293 CGM.IntTy->getPointerTo(), /*isVarArg=*/false);
2294 return CGM.CreateRuntimeFunction(
2295 FTy, "_Init_thread_abort",
2296 llvm::AttributeSet::get(CGM.getLLVMContext(),
2297 llvm::AttributeSet::FunctionIndex,
2298 llvm::Attribute::NoUnwind));
2302 struct ResetGuardBit final : EHScopeStack::Cleanup {
2305 ResetGuardBit(Address Guard, unsigned GuardNum)
2306 : Guard(Guard), GuardNum(GuardNum) {}
2308 void Emit(CodeGenFunction &CGF, Flags flags) override {
2309 // Reset the bit in the mask so that the static variable may be
2311 CGBuilderTy &Builder = CGF.Builder;
2312 llvm::LoadInst *LI = Builder.CreateLoad(Guard);
2313 llvm::ConstantInt *Mask =
2314 llvm::ConstantInt::get(CGF.IntTy, ~(1ULL << GuardNum));
2315 Builder.CreateStore(Builder.CreateAnd(LI, Mask), Guard);
2319 struct CallInitThreadAbort final : EHScopeStack::Cleanup {
2321 CallInitThreadAbort(Address Guard) : Guard(Guard.getPointer()) {}
2323 void Emit(CodeGenFunction &CGF, Flags flags) override {
2324 // Calling _Init_thread_abort will reset the guard's state.
2325 CGF.EmitNounwindRuntimeCall(getInitThreadAbortFn(CGF.CGM), Guard);
2330 void MicrosoftCXXABI::EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
2331 llvm::GlobalVariable *GV,
2333 // MSVC only uses guards for static locals.
2334 if (!D.isStaticLocal()) {
2335 assert(GV->hasWeakLinkage() || GV->hasLinkOnceLinkage());
2336 // GlobalOpt is allowed to discard the initializer, so use linkonce_odr.
2337 llvm::Function *F = CGF.CurFn;
2338 F->setLinkage(llvm::GlobalValue::LinkOnceODRLinkage);
2339 F->setComdat(CGM.getModule().getOrInsertComdat(F->getName()));
2340 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
2344 bool ThreadlocalStatic = D.getTLSKind();
2345 bool ThreadsafeStatic = getContext().getLangOpts().ThreadsafeStatics;
2347 // Thread-safe static variables which aren't thread-specific have a
2348 // per-variable guard.
2349 bool HasPerVariableGuard = ThreadsafeStatic && !ThreadlocalStatic;
2351 CGBuilderTy &Builder = CGF.Builder;
2352 llvm::IntegerType *GuardTy = CGF.Int32Ty;
2353 llvm::ConstantInt *Zero = llvm::ConstantInt::get(GuardTy, 0);
2354 CharUnits GuardAlign = CharUnits::fromQuantity(4);
2356 // Get the guard variable for this function if we have one already.
2357 GuardInfo *GI = nullptr;
2358 if (ThreadlocalStatic)
2359 GI = &ThreadLocalGuardVariableMap[D.getDeclContext()];
2360 else if (!ThreadsafeStatic)
2361 GI = &GuardVariableMap[D.getDeclContext()];
2363 llvm::GlobalVariable *GuardVar = GI ? GI->Guard : nullptr;
2365 if (D.isExternallyVisible()) {
2366 // Externally visible variables have to be numbered in Sema to properly
2367 // handle unreachable VarDecls.
2368 GuardNum = getContext().getStaticLocalNumber(&D);
2369 assert(GuardNum > 0);
2371 } else if (HasPerVariableGuard) {
2372 GuardNum = ThreadSafeGuardNumMap[D.getDeclContext()]++;
2374 // Non-externally visible variables are numbered here in CodeGen.
2375 GuardNum = GI->BitIndex++;
2378 if (!HasPerVariableGuard && GuardNum >= 32) {
2379 if (D.isExternallyVisible())
2380 ErrorUnsupportedABI(CGF, "more than 32 guarded initializations");
2386 // Mangle the name for the guard.
2387 SmallString<256> GuardName;
2389 llvm::raw_svector_ostream Out(GuardName);
2390 if (HasPerVariableGuard)
2391 getMangleContext().mangleThreadSafeStaticGuardVariable(&D, GuardNum,
2394 getMangleContext().mangleStaticGuardVariable(&D, Out);
2397 // Create the guard variable with a zero-initializer. Just absorb linkage,
2398 // visibility and dll storage class from the guarded variable.
2400 new llvm::GlobalVariable(CGM.getModule(), GuardTy, /*isConstant=*/false,
2401 GV->getLinkage(), Zero, GuardName.str());
2402 GuardVar->setVisibility(GV->getVisibility());
2403 GuardVar->setDLLStorageClass(GV->getDLLStorageClass());
2404 GuardVar->setAlignment(GuardAlign.getQuantity());
2405 if (GuardVar->isWeakForLinker())
2406 GuardVar->setComdat(
2407 CGM.getModule().getOrInsertComdat(GuardVar->getName()));
2409 GuardVar->setThreadLocal(true);
2410 if (GI && !HasPerVariableGuard)
2411 GI->Guard = GuardVar;
2414 ConstantAddress GuardAddr(GuardVar, GuardAlign);
2416 assert(GuardVar->getLinkage() == GV->getLinkage() &&
2417 "static local from the same function had different linkage");
2419 if (!HasPerVariableGuard) {
2420 // Pseudo code for the test:
2421 // if (!(GuardVar & MyGuardBit)) {
2422 // GuardVar |= MyGuardBit;
2423 // ... initialize the object ...;
2426 // Test our bit from the guard variable.
2427 llvm::ConstantInt *Bit = llvm::ConstantInt::get(GuardTy, 1U << GuardNum);
2428 llvm::LoadInst *LI = Builder.CreateLoad(GuardAddr);
2429 llvm::Value *IsInitialized =
2430 Builder.CreateICmpNE(Builder.CreateAnd(LI, Bit), Zero);
2431 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
2432 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2433 Builder.CreateCondBr(IsInitialized, EndBlock, InitBlock);
2435 // Set our bit in the guard variable and emit the initializer and add a global
2436 // destructor if appropriate.
2437 CGF.EmitBlock(InitBlock);
2438 Builder.CreateStore(Builder.CreateOr(LI, Bit), GuardAddr);
2439 CGF.EHStack.pushCleanup<ResetGuardBit>(EHCleanup, GuardAddr, GuardNum);
2440 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
2441 CGF.PopCleanupBlock();
2442 Builder.CreateBr(EndBlock);
2445 CGF.EmitBlock(EndBlock);
2447 // Pseudo code for the test:
2448 // if (TSS > _Init_thread_epoch) {
2449 // _Init_thread_header(&TSS);
2451 // ... initialize the object ...;
2452 // _Init_thread_footer(&TSS);
2456 // The algorithm is almost identical to what can be found in the appendix
2459 // This BasicBLock determines whether or not we have any work to do.
2460 llvm::LoadInst *FirstGuardLoad = Builder.CreateLoad(GuardAddr);
2461 FirstGuardLoad->setOrdering(llvm::AtomicOrdering::Unordered);
2462 llvm::LoadInst *InitThreadEpoch =
2463 Builder.CreateLoad(getInitThreadEpochPtr(CGM));
2464 llvm::Value *IsUninitialized =
2465 Builder.CreateICmpSGT(FirstGuardLoad, InitThreadEpoch);
2466 llvm::BasicBlock *AttemptInitBlock = CGF.createBasicBlock("init.attempt");
2467 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2468 Builder.CreateCondBr(IsUninitialized, AttemptInitBlock, EndBlock);
2470 // This BasicBlock attempts to determine whether or not this thread is
2471 // responsible for doing the initialization.
2472 CGF.EmitBlock(AttemptInitBlock);
2473 CGF.EmitNounwindRuntimeCall(getInitThreadHeaderFn(CGM),
2474 GuardAddr.getPointer());
2475 llvm::LoadInst *SecondGuardLoad = Builder.CreateLoad(GuardAddr);
2476 SecondGuardLoad->setOrdering(llvm::AtomicOrdering::Unordered);
2477 llvm::Value *ShouldDoInit =
2478 Builder.CreateICmpEQ(SecondGuardLoad, getAllOnesInt());
2479 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
2480 Builder.CreateCondBr(ShouldDoInit, InitBlock, EndBlock);
2482 // Ok, we ended up getting selected as the initializing thread.
2483 CGF.EmitBlock(InitBlock);
2484 CGF.EHStack.pushCleanup<CallInitThreadAbort>(EHCleanup, GuardAddr);
2485 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
2486 CGF.PopCleanupBlock();
2487 CGF.EmitNounwindRuntimeCall(getInitThreadFooterFn(CGM),
2488 GuardAddr.getPointer());
2489 Builder.CreateBr(EndBlock);
2491 CGF.EmitBlock(EndBlock);
2495 bool MicrosoftCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
2496 // Null-ness for function memptrs only depends on the first field, which is
2497 // the function pointer. The rest don't matter, so we can zero initialize.
2498 if (MPT->isMemberFunctionPointer())
2501 // The virtual base adjustment field is always -1 for null, so if we have one
2502 // we can't zero initialize. The field offset is sometimes also -1 if 0 is a
2503 // valid field offset.
2504 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2505 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
2506 return (!MSInheritanceAttr::hasVBTableOffsetField(Inheritance) &&
2507 RD->nullFieldOffsetIsZero());
2511 MicrosoftCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
2512 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2513 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
2514 llvm::SmallVector<llvm::Type *, 4> fields;
2515 if (MPT->isMemberFunctionPointer())
2516 fields.push_back(CGM.VoidPtrTy); // FunctionPointerOrVirtualThunk
2518 fields.push_back(CGM.IntTy); // FieldOffset
2520 if (MSInheritanceAttr::hasNVOffsetField(MPT->isMemberFunctionPointer(),
2522 fields.push_back(CGM.IntTy);
2523 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance))
2524 fields.push_back(CGM.IntTy);
2525 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance))
2526 fields.push_back(CGM.IntTy); // VirtualBaseAdjustmentOffset
2528 if (fields.size() == 1)
2530 return llvm::StructType::get(CGM.getLLVMContext(), fields);
2533 void MicrosoftCXXABI::
2534 GetNullMemberPointerFields(const MemberPointerType *MPT,
2535 llvm::SmallVectorImpl<llvm::Constant *> &fields) {
2536 assert(fields.empty());
2537 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2538 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
2539 if (MPT->isMemberFunctionPointer()) {
2540 // FunctionPointerOrVirtualThunk
2541 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
2543 if (RD->nullFieldOffsetIsZero())
2544 fields.push_back(getZeroInt()); // FieldOffset
2546 fields.push_back(getAllOnesInt()); // FieldOffset
2549 if (MSInheritanceAttr::hasNVOffsetField(MPT->isMemberFunctionPointer(),
2551 fields.push_back(getZeroInt());
2552 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance))
2553 fields.push_back(getZeroInt());
2554 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance))
2555 fields.push_back(getAllOnesInt());
2559 MicrosoftCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
2560 llvm::SmallVector<llvm::Constant *, 4> fields;
2561 GetNullMemberPointerFields(MPT, fields);
2562 if (fields.size() == 1)
2564 llvm::Constant *Res = llvm::ConstantStruct::getAnon(fields);
2565 assert(Res->getType() == ConvertMemberPointerType(MPT));
2570 MicrosoftCXXABI::EmitFullMemberPointer(llvm::Constant *FirstField,
2571 bool IsMemberFunction,
2572 const CXXRecordDecl *RD,
2573 CharUnits NonVirtualBaseAdjustment,
2574 unsigned VBTableIndex) {
2575 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
2577 // Single inheritance class member pointer are represented as scalars instead
2579 if (MSInheritanceAttr::hasOnlyOneField(IsMemberFunction, Inheritance))
2582 llvm::SmallVector<llvm::Constant *, 4> fields;
2583 fields.push_back(FirstField);
2585 if (MSInheritanceAttr::hasNVOffsetField(IsMemberFunction, Inheritance))
2586 fields.push_back(llvm::ConstantInt::get(
2587 CGM.IntTy, NonVirtualBaseAdjustment.getQuantity()));
2589 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance)) {
2590 CharUnits Offs = CharUnits::Zero();
2592 Offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
2593 fields.push_back(llvm::ConstantInt::get(CGM.IntTy, Offs.getQuantity()));
2596 // The rest of the fields are adjusted by conversions to a more derived class.
2597 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance))
2598 fields.push_back(llvm::ConstantInt::get(CGM.IntTy, VBTableIndex));
2600 return llvm::ConstantStruct::getAnon(fields);
2604 MicrosoftCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
2606 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2607 if (RD->getMSInheritanceModel() ==
2608 MSInheritanceAttr::Keyword_virtual_inheritance)
2609 offset -= getContext().getOffsetOfBaseWithVBPtr(RD);
2610 llvm::Constant *FirstField =
2611 llvm::ConstantInt::get(CGM.IntTy, offset.getQuantity());
2612 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/false, RD,
2613 CharUnits::Zero(), /*VBTableIndex=*/0);
2616 llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const APValue &MP,
2618 const MemberPointerType *DstTy = MPType->castAs<MemberPointerType>();
2619 const ValueDecl *MPD = MP.getMemberPointerDecl();
2621 return EmitNullMemberPointer(DstTy);
2623 ASTContext &Ctx = getContext();
2624 ArrayRef<const CXXRecordDecl *> MemberPointerPath = MP.getMemberPointerPath();
2627 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD)) {
2628 C = EmitMemberFunctionPointer(MD);
2630 CharUnits FieldOffset = Ctx.toCharUnitsFromBits(Ctx.getFieldOffset(MPD));
2631 C = EmitMemberDataPointer(DstTy, FieldOffset);
2634 if (!MemberPointerPath.empty()) {
2635 const CXXRecordDecl *SrcRD = cast<CXXRecordDecl>(MPD->getDeclContext());
2636 const Type *SrcRecTy = Ctx.getTypeDeclType(SrcRD).getTypePtr();
2637 const MemberPointerType *SrcTy =
2638 Ctx.getMemberPointerType(DstTy->getPointeeType(), SrcRecTy)
2639 ->castAs<MemberPointerType>();
2641 bool DerivedMember = MP.isMemberPointerToDerivedMember();
2642 SmallVector<const CXXBaseSpecifier *, 4> DerivedToBasePath;
2643 const CXXRecordDecl *PrevRD = SrcRD;
2644 for (const CXXRecordDecl *PathElem : MemberPointerPath) {
2645 const CXXRecordDecl *Base = nullptr;
2646 const CXXRecordDecl *Derived = nullptr;
2647 if (DerivedMember) {
2654 for (const CXXBaseSpecifier &BS : Derived->bases())
2655 if (BS.getType()->getAsCXXRecordDecl()->getCanonicalDecl() ==
2656 Base->getCanonicalDecl())
2657 DerivedToBasePath.push_back(&BS);
2660 assert(DerivedToBasePath.size() == MemberPointerPath.size());
2662 CastKind CK = DerivedMember ? CK_DerivedToBaseMemberPointer
2663 : CK_BaseToDerivedMemberPointer;
2664 C = EmitMemberPointerConversion(SrcTy, DstTy, CK, DerivedToBasePath.begin(),
2665 DerivedToBasePath.end(), C);
2671 MicrosoftCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) {
2672 assert(MD->isInstance() && "Member function must not be static!");
2674 MD = MD->getCanonicalDecl();
2675 CharUnits NonVirtualBaseAdjustment = CharUnits::Zero();
2676 const CXXRecordDecl *RD = MD->getParent()->getMostRecentDecl();
2677 CodeGenTypes &Types = CGM.getTypes();
2679 unsigned VBTableIndex = 0;
2680 llvm::Constant *FirstField;
2681 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
2682 if (!MD->isVirtual()) {
2684 // Check whether the function has a computable LLVM signature.
2685 if (Types.isFuncTypeConvertible(FPT)) {
2686 // The function has a computable LLVM signature; use the correct type.
2687 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
2689 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
2690 // function type is incomplete.
2693 FirstField = CGM.GetAddrOfFunction(MD, Ty);
2695 auto &VTableContext = CGM.getMicrosoftVTableContext();
2696 MicrosoftVTableContext::MethodVFTableLocation ML =
2697 VTableContext.getMethodVFTableLocation(MD);
2698 FirstField = EmitVirtualMemPtrThunk(MD, ML);
2699 // Include the vfptr adjustment if the method is in a non-primary vftable.
2700 NonVirtualBaseAdjustment += ML.VFPtrOffset;
2702 VBTableIndex = VTableContext.getVBTableIndex(RD, ML.VBase) * 4;
2705 if (VBTableIndex == 0 &&
2706 RD->getMSInheritanceModel() ==
2707 MSInheritanceAttr::Keyword_virtual_inheritance)
2708 NonVirtualBaseAdjustment -= getContext().getOffsetOfBaseWithVBPtr(RD);
2710 // The rest of the fields are common with data member pointers.
2711 FirstField = llvm::ConstantExpr::getBitCast(FirstField, CGM.VoidPtrTy);
2712 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/true, RD,
2713 NonVirtualBaseAdjustment, VBTableIndex);
2716 /// Member pointers are the same if they're either bitwise identical *or* both
2717 /// null. Null-ness for function members is determined by the first field,
2718 /// while for data member pointers we must compare all fields.
2720 MicrosoftCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
2723 const MemberPointerType *MPT,
2725 CGBuilderTy &Builder = CGF.Builder;
2727 // Handle != comparisons by switching the sense of all boolean operations.
2728 llvm::ICmpInst::Predicate Eq;
2729 llvm::Instruction::BinaryOps And, Or;
2731 Eq = llvm::ICmpInst::ICMP_NE;
2732 And = llvm::Instruction::Or;
2733 Or = llvm::Instruction::And;
2735 Eq = llvm::ICmpInst::ICMP_EQ;
2736 And = llvm::Instruction::And;
2737 Or = llvm::Instruction::Or;
2740 // If this is a single field member pointer (single inheritance), this is a
2742 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2743 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
2744 if (MSInheritanceAttr::hasOnlyOneField(MPT->isMemberFunctionPointer(),
2746 return Builder.CreateICmp(Eq, L, R);
2748 // Compare the first field.
2749 llvm::Value *L0 = Builder.CreateExtractValue(L, 0, "lhs.0");
2750 llvm::Value *R0 = Builder.CreateExtractValue(R, 0, "rhs.0");
2751 llvm::Value *Cmp0 = Builder.CreateICmp(Eq, L0, R0, "memptr.cmp.first");
2753 // Compare everything other than the first field.
2754 llvm::Value *Res = nullptr;
2755 llvm::StructType *LType = cast<llvm::StructType>(L->getType());
2756 for (unsigned I = 1, E = LType->getNumElements(); I != E; ++I) {
2757 llvm::Value *LF = Builder.CreateExtractValue(L, I);
2758 llvm::Value *RF = Builder.CreateExtractValue(R, I);
2759 llvm::Value *Cmp = Builder.CreateICmp(Eq, LF, RF, "memptr.cmp.rest");
2761 Res = Builder.CreateBinOp(And, Res, Cmp);
2766 // Check if the first field is 0 if this is a function pointer.
2767 if (MPT->isMemberFunctionPointer()) {
2768 // (l1 == r1 && ...) || l0 == 0
2769 llvm::Value *Zero = llvm::Constant::getNullValue(L0->getType());
2770 llvm::Value *IsZero = Builder.CreateICmp(Eq, L0, Zero, "memptr.cmp.iszero");
2771 Res = Builder.CreateBinOp(Or, Res, IsZero);
2774 // Combine the comparison of the first field, which must always be true for
2775 // this comparison to succeeed.
2776 return Builder.CreateBinOp(And, Res, Cmp0, "memptr.cmp");
2780 MicrosoftCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
2781 llvm::Value *MemPtr,
2782 const MemberPointerType *MPT) {
2783 CGBuilderTy &Builder = CGF.Builder;
2784 llvm::SmallVector<llvm::Constant *, 4> fields;
2785 // We only need one field for member functions.
2786 if (MPT->isMemberFunctionPointer())
2787 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
2789 GetNullMemberPointerFields(MPT, fields);
2790 assert(!fields.empty());
2791 llvm::Value *FirstField = MemPtr;
2792 if (MemPtr->getType()->isStructTy())
2793 FirstField = Builder.CreateExtractValue(MemPtr, 0);
2794 llvm::Value *Res = Builder.CreateICmpNE(FirstField, fields[0], "memptr.cmp0");
2796 // For function member pointers, we only need to test the function pointer
2797 // field. The other fields if any can be garbage.
2798 if (MPT->isMemberFunctionPointer())
2801 // Otherwise, emit a series of compares and combine the results.
2802 for (int I = 1, E = fields.size(); I < E; ++I) {
2803 llvm::Value *Field = Builder.CreateExtractValue(MemPtr, I);
2804 llvm::Value *Next = Builder.CreateICmpNE(Field, fields[I], "memptr.cmp");
2805 Res = Builder.CreateOr(Res, Next, "memptr.tobool");
2810 bool MicrosoftCXXABI::MemberPointerConstantIsNull(const MemberPointerType *MPT,
2811 llvm::Constant *Val) {
2812 // Function pointers are null if the pointer in the first field is null.
2813 if (MPT->isMemberFunctionPointer()) {
2814 llvm::Constant *FirstField = Val->getType()->isStructTy() ?
2815 Val->getAggregateElement(0U) : Val;
2816 return FirstField->isNullValue();
2819 // If it's not a function pointer and it's zero initializable, we can easily
2821 if (isZeroInitializable(MPT) && Val->isNullValue())
2824 // Otherwise, break down all the fields for comparison. Hopefully these
2825 // little Constants are reused, while a big null struct might not be.
2826 llvm::SmallVector<llvm::Constant *, 4> Fields;
2827 GetNullMemberPointerFields(MPT, Fields);
2828 if (Fields.size() == 1) {
2829 assert(Val->getType()->isIntegerTy());
2830 return Val == Fields[0];
2834 for (I = 0, E = Fields.size(); I != E; ++I) {
2835 if (Val->getAggregateElement(I) != Fields[I])
2842 MicrosoftCXXABI::GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
2844 llvm::Value *VBPtrOffset,
2845 llvm::Value *VBTableOffset,
2846 llvm::Value **VBPtrOut) {
2847 CGBuilderTy &Builder = CGF.Builder;
2848 // Load the vbtable pointer from the vbptr in the instance.
2849 This = Builder.CreateElementBitCast(This, CGM.Int8Ty);
2850 llvm::Value *VBPtr =
2851 Builder.CreateInBoundsGEP(This.getPointer(), VBPtrOffset, "vbptr");
2852 if (VBPtrOut) *VBPtrOut = VBPtr;
2853 VBPtr = Builder.CreateBitCast(VBPtr,
2854 CGM.Int32Ty->getPointerTo(0)->getPointerTo(This.getAddressSpace()));
2856 CharUnits VBPtrAlign;
2857 if (auto CI = dyn_cast<llvm::ConstantInt>(VBPtrOffset)) {
2858 VBPtrAlign = This.getAlignment().alignmentAtOffset(
2859 CharUnits::fromQuantity(CI->getSExtValue()));
2861 VBPtrAlign = CGF.getPointerAlign();
2864 llvm::Value *VBTable = Builder.CreateAlignedLoad(VBPtr, VBPtrAlign, "vbtable");
2866 // Translate from byte offset to table index. It improves analyzability.
2867 llvm::Value *VBTableIndex = Builder.CreateAShr(
2868 VBTableOffset, llvm::ConstantInt::get(VBTableOffset->getType(), 2),
2869 "vbtindex", /*isExact=*/true);
2871 // Load an i32 offset from the vb-table.
2872 llvm::Value *VBaseOffs = Builder.CreateInBoundsGEP(VBTable, VBTableIndex);
2873 VBaseOffs = Builder.CreateBitCast(VBaseOffs, CGM.Int32Ty->getPointerTo(0));
2874 return Builder.CreateAlignedLoad(VBaseOffs, CharUnits::fromQuantity(4),
2878 // Returns an adjusted base cast to i8*, since we do more address arithmetic on
2880 llvm::Value *MicrosoftCXXABI::AdjustVirtualBase(
2881 CodeGenFunction &CGF, const Expr *E, const CXXRecordDecl *RD,
2882 Address Base, llvm::Value *VBTableOffset, llvm::Value *VBPtrOffset) {
2883 CGBuilderTy &Builder = CGF.Builder;
2884 Base = Builder.CreateElementBitCast(Base, CGM.Int8Ty);
2885 llvm::BasicBlock *OriginalBB = nullptr;
2886 llvm::BasicBlock *SkipAdjustBB = nullptr;
2887 llvm::BasicBlock *VBaseAdjustBB = nullptr;
2889 // In the unspecified inheritance model, there might not be a vbtable at all,
2890 // in which case we need to skip the virtual base lookup. If there is a
2891 // vbtable, the first entry is a no-op entry that gives back the original
2892 // base, so look for a virtual base adjustment offset of zero.
2894 OriginalBB = Builder.GetInsertBlock();
2895 VBaseAdjustBB = CGF.createBasicBlock("memptr.vadjust");
2896 SkipAdjustBB = CGF.createBasicBlock("memptr.skip_vadjust");
2897 llvm::Value *IsVirtual =
2898 Builder.CreateICmpNE(VBTableOffset, getZeroInt(),
2900 Builder.CreateCondBr(IsVirtual, VBaseAdjustBB, SkipAdjustBB);
2901 CGF.EmitBlock(VBaseAdjustBB);
2904 // If we weren't given a dynamic vbptr offset, RD should be complete and we'll
2905 // know the vbptr offset.
2907 CharUnits offs = CharUnits::Zero();
2908 if (!RD->hasDefinition()) {
2909 DiagnosticsEngine &Diags = CGF.CGM.getDiags();
2910 unsigned DiagID = Diags.getCustomDiagID(
2911 DiagnosticsEngine::Error,
2912 "member pointer representation requires a "
2913 "complete class type for %0 to perform this expression");
2914 Diags.Report(E->getExprLoc(), DiagID) << RD << E->getSourceRange();
2915 } else if (RD->getNumVBases())
2916 offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
2917 VBPtrOffset = llvm::ConstantInt::get(CGM.IntTy, offs.getQuantity());
2919 llvm::Value *VBPtr = nullptr;
2920 llvm::Value *VBaseOffs =
2921 GetVBaseOffsetFromVBPtr(CGF, Base, VBPtrOffset, VBTableOffset, &VBPtr);
2922 llvm::Value *AdjustedBase = Builder.CreateInBoundsGEP(VBPtr, VBaseOffs);
2924 // Merge control flow with the case where we didn't have to adjust.
2925 if (VBaseAdjustBB) {
2926 Builder.CreateBr(SkipAdjustBB);
2927 CGF.EmitBlock(SkipAdjustBB);
2928 llvm::PHINode *Phi = Builder.CreatePHI(CGM.Int8PtrTy, 2, "memptr.base");
2929 Phi->addIncoming(Base.getPointer(), OriginalBB);
2930 Phi->addIncoming(AdjustedBase, VBaseAdjustBB);
2933 return AdjustedBase;
2936 llvm::Value *MicrosoftCXXABI::EmitMemberDataPointerAddress(
2937 CodeGenFunction &CGF, const Expr *E, Address Base, llvm::Value *MemPtr,
2938 const MemberPointerType *MPT) {
2939 assert(MPT->isMemberDataPointer());
2940 unsigned AS = Base.getAddressSpace();
2942 CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
2943 CGBuilderTy &Builder = CGF.Builder;
2944 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2945 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
2947 // Extract the fields we need, regardless of model. We'll apply them if we
2949 llvm::Value *FieldOffset = MemPtr;
2950 llvm::Value *VirtualBaseAdjustmentOffset = nullptr;
2951 llvm::Value *VBPtrOffset = nullptr;
2952 if (MemPtr->getType()->isStructTy()) {
2953 // We need to extract values.
2955 FieldOffset = Builder.CreateExtractValue(MemPtr, I++);
2956 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance))
2957 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
2958 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance))
2959 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
2963 if (VirtualBaseAdjustmentOffset) {
2964 Addr = AdjustVirtualBase(CGF, E, RD, Base, VirtualBaseAdjustmentOffset,
2967 Addr = Base.getPointer();
2971 Addr = Builder.CreateBitCast(Addr, CGF.Int8Ty->getPointerTo(AS));
2973 // Apply the offset, which we assume is non-null.
2974 Addr = Builder.CreateInBoundsGEP(Addr, FieldOffset, "memptr.offset");
2976 // Cast the address to the appropriate pointer type, adopting the address
2977 // space of the base pointer.
2978 return Builder.CreateBitCast(Addr, PType);
2982 MicrosoftCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
2985 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
2986 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
2987 E->getCastKind() == CK_ReinterpretMemberPointer);
2989 // Use constant emission if we can.
2990 if (isa<llvm::Constant>(Src))
2991 return EmitMemberPointerConversion(E, cast<llvm::Constant>(Src));
2993 // We may be adding or dropping fields from the member pointer, so we need
2994 // both types and the inheritance models of both records.
2995 const MemberPointerType *SrcTy =
2996 E->getSubExpr()->getType()->castAs<MemberPointerType>();
2997 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
2998 bool IsFunc = SrcTy->isMemberFunctionPointer();
3000 // If the classes use the same null representation, reinterpret_cast is a nop.
3001 bool IsReinterpret = E->getCastKind() == CK_ReinterpretMemberPointer;
3002 if (IsReinterpret && IsFunc)
3005 CXXRecordDecl *SrcRD = SrcTy->getMostRecentCXXRecordDecl();
3006 CXXRecordDecl *DstRD = DstTy->getMostRecentCXXRecordDecl();
3007 if (IsReinterpret &&
3008 SrcRD->nullFieldOffsetIsZero() == DstRD->nullFieldOffsetIsZero())
3011 CGBuilderTy &Builder = CGF.Builder;
3013 // Branch past the conversion if Src is null.
3014 llvm::Value *IsNotNull = EmitMemberPointerIsNotNull(CGF, Src, SrcTy);
3015 llvm::Constant *DstNull = EmitNullMemberPointer(DstTy);
3017 // C++ 5.2.10p9: The null member pointer value is converted to the null member
3018 // pointer value of the destination type.
3019 if (IsReinterpret) {
3020 // For reinterpret casts, sema ensures that src and dst are both functions
3021 // or data and have the same size, which means the LLVM types should match.
3022 assert(Src->getType() == DstNull->getType());
3023 return Builder.CreateSelect(IsNotNull, Src, DstNull);
3026 llvm::BasicBlock *OriginalBB = Builder.GetInsertBlock();
3027 llvm::BasicBlock *ConvertBB = CGF.createBasicBlock("memptr.convert");
3028 llvm::BasicBlock *ContinueBB = CGF.createBasicBlock("memptr.converted");
3029 Builder.CreateCondBr(IsNotNull, ConvertBB, ContinueBB);
3030 CGF.EmitBlock(ConvertBB);
3032 llvm::Value *Dst = EmitNonNullMemberPointerConversion(
3033 SrcTy, DstTy, E->getCastKind(), E->path_begin(), E->path_end(), Src,
3036 Builder.CreateBr(ContinueBB);
3038 // In the continuation, choose between DstNull and Dst.
3039 CGF.EmitBlock(ContinueBB);
3040 llvm::PHINode *Phi = Builder.CreatePHI(DstNull->getType(), 2, "memptr.converted");
3041 Phi->addIncoming(DstNull, OriginalBB);
3042 Phi->addIncoming(Dst, ConvertBB);
3046 llvm::Value *MicrosoftCXXABI::EmitNonNullMemberPointerConversion(
3047 const MemberPointerType *SrcTy, const MemberPointerType *DstTy, CastKind CK,
3048 CastExpr::path_const_iterator PathBegin,
3049 CastExpr::path_const_iterator PathEnd, llvm::Value *Src,
3050 CGBuilderTy &Builder) {
3051 const CXXRecordDecl *SrcRD = SrcTy->getMostRecentCXXRecordDecl();
3052 const CXXRecordDecl *DstRD = DstTy->getMostRecentCXXRecordDecl();
3053 MSInheritanceAttr::Spelling SrcInheritance = SrcRD->getMSInheritanceModel();
3054 MSInheritanceAttr::Spelling DstInheritance = DstRD->getMSInheritanceModel();
3055 bool IsFunc = SrcTy->isMemberFunctionPointer();
3056 bool IsConstant = isa<llvm::Constant>(Src);
3059 llvm::Value *FirstField = Src;
3060 llvm::Value *NonVirtualBaseAdjustment = getZeroInt();
3061 llvm::Value *VirtualBaseAdjustmentOffset = getZeroInt();
3062 llvm::Value *VBPtrOffset = getZeroInt();
3063 if (!MSInheritanceAttr::hasOnlyOneField(IsFunc, SrcInheritance)) {
3064 // We need to extract values.
3066 FirstField = Builder.CreateExtractValue(Src, I++);
3067 if (MSInheritanceAttr::hasNVOffsetField(IsFunc, SrcInheritance))
3068 NonVirtualBaseAdjustment = Builder.CreateExtractValue(Src, I++);
3069 if (MSInheritanceAttr::hasVBPtrOffsetField(SrcInheritance))
3070 VBPtrOffset = Builder.CreateExtractValue(Src, I++);
3071 if (MSInheritanceAttr::hasVBTableOffsetField(SrcInheritance))
3072 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(Src, I++);
3075 bool IsDerivedToBase = (CK == CK_DerivedToBaseMemberPointer);
3076 const MemberPointerType *DerivedTy = IsDerivedToBase ? SrcTy : DstTy;
3077 const CXXRecordDecl *DerivedClass = DerivedTy->getMostRecentCXXRecordDecl();
3079 // For data pointers, we adjust the field offset directly. For functions, we
3080 // have a separate field.
3081 llvm::Value *&NVAdjustField = IsFunc ? NonVirtualBaseAdjustment : FirstField;
3083 // The virtual inheritance model has a quirk: the virtual base table is always
3084 // referenced when dereferencing a member pointer even if the member pointer
3085 // is non-virtual. This is accounted for by adjusting the non-virtual offset
3086 // to point backwards to the top of the MDC from the first VBase. Undo this
3087 // adjustment to normalize the member pointer.
3088 llvm::Value *SrcVBIndexEqZero =
3089 Builder.CreateICmpEQ(VirtualBaseAdjustmentOffset, getZeroInt());
3090 if (SrcInheritance == MSInheritanceAttr::Keyword_virtual_inheritance) {
3091 if (int64_t SrcOffsetToFirstVBase =
3092 getContext().getOffsetOfBaseWithVBPtr(SrcRD).getQuantity()) {
3093 llvm::Value *UndoSrcAdjustment = Builder.CreateSelect(
3095 llvm::ConstantInt::get(CGM.IntTy, SrcOffsetToFirstVBase),
3097 NVAdjustField = Builder.CreateNSWAdd(NVAdjustField, UndoSrcAdjustment);
3101 // A non-zero vbindex implies that we are dealing with a source member in a
3102 // floating virtual base in addition to some non-virtual offset. If the
3103 // vbindex is zero, we are dealing with a source that exists in a non-virtual,
3104 // fixed, base. The difference between these two cases is that the vbindex +
3105 // nvoffset *always* point to the member regardless of what context they are
3106 // evaluated in so long as the vbindex is adjusted. A member inside a fixed
3107 // base requires explicit nv adjustment.
3108 llvm::Constant *BaseClassOffset = llvm::ConstantInt::get(
3110 CGM.computeNonVirtualBaseClassOffset(DerivedClass, PathBegin, PathEnd)
3113 llvm::Value *NVDisp;
3114 if (IsDerivedToBase)
3115 NVDisp = Builder.CreateNSWSub(NVAdjustField, BaseClassOffset, "adj");
3117 NVDisp = Builder.CreateNSWAdd(NVAdjustField, BaseClassOffset, "adj");
3119 NVAdjustField = Builder.CreateSelect(SrcVBIndexEqZero, NVDisp, getZeroInt());
3121 // Update the vbindex to an appropriate value in the destination because
3122 // SrcRD's vbtable might not be a strict prefix of the one in DstRD.
3123 llvm::Value *DstVBIndexEqZero = SrcVBIndexEqZero;
3124 if (MSInheritanceAttr::hasVBTableOffsetField(DstInheritance) &&
3125 MSInheritanceAttr::hasVBTableOffsetField(SrcInheritance)) {
3126 if (llvm::GlobalVariable *VDispMap =
3127 getAddrOfVirtualDisplacementMap(SrcRD, DstRD)) {
3128 llvm::Value *VBIndex = Builder.CreateExactUDiv(
3129 VirtualBaseAdjustmentOffset, llvm::ConstantInt::get(CGM.IntTy, 4));
3131 llvm::Constant *Mapping = VDispMap->getInitializer();
3132 VirtualBaseAdjustmentOffset =
3133 Mapping->getAggregateElement(cast<llvm::Constant>(VBIndex));
3135 llvm::Value *Idxs[] = {getZeroInt(), VBIndex};
3136 VirtualBaseAdjustmentOffset =
3137 Builder.CreateAlignedLoad(Builder.CreateInBoundsGEP(VDispMap, Idxs),
3138 CharUnits::fromQuantity(4));
3142 Builder.CreateICmpEQ(VirtualBaseAdjustmentOffset, getZeroInt());
3146 // Set the VBPtrOffset to zero if the vbindex is zero. Otherwise, initialize
3147 // it to the offset of the vbptr.
3148 if (MSInheritanceAttr::hasVBPtrOffsetField(DstInheritance)) {
3149 llvm::Value *DstVBPtrOffset = llvm::ConstantInt::get(
3151 getContext().getASTRecordLayout(DstRD).getVBPtrOffset().getQuantity());
3153 Builder.CreateSelect(DstVBIndexEqZero, getZeroInt(), DstVBPtrOffset);
3156 // Likewise, apply a similar adjustment so that dereferencing the member
3157 // pointer correctly accounts for the distance between the start of the first
3158 // virtual base and the top of the MDC.
3159 if (DstInheritance == MSInheritanceAttr::Keyword_virtual_inheritance) {
3160 if (int64_t DstOffsetToFirstVBase =
3161 getContext().getOffsetOfBaseWithVBPtr(DstRD).getQuantity()) {
3162 llvm::Value *DoDstAdjustment = Builder.CreateSelect(
3164 llvm::ConstantInt::get(CGM.IntTy, DstOffsetToFirstVBase),
3166 NVAdjustField = Builder.CreateNSWSub(NVAdjustField, DoDstAdjustment);
3170 // Recompose dst from the null struct and the adjusted fields from src.
3172 if (MSInheritanceAttr::hasOnlyOneField(IsFunc, DstInheritance)) {
3175 Dst = llvm::UndefValue::get(ConvertMemberPointerType(DstTy));
3177 Dst = Builder.CreateInsertValue(Dst, FirstField, Idx++);
3178 if (MSInheritanceAttr::hasNVOffsetField(IsFunc, DstInheritance))
3179 Dst = Builder.CreateInsertValue(Dst, NonVirtualBaseAdjustment, Idx++);
3180 if (MSInheritanceAttr::hasVBPtrOffsetField(DstInheritance))
3181 Dst = Builder.CreateInsertValue(Dst, VBPtrOffset, Idx++);
3182 if (MSInheritanceAttr::hasVBTableOffsetField(DstInheritance))
3183 Dst = Builder.CreateInsertValue(Dst, VirtualBaseAdjustmentOffset, Idx++);
3189 MicrosoftCXXABI::EmitMemberPointerConversion(const CastExpr *E,
3190 llvm::Constant *Src) {
3191 const MemberPointerType *SrcTy =
3192 E->getSubExpr()->getType()->castAs<MemberPointerType>();
3193 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
3195 CastKind CK = E->getCastKind();
3197 return EmitMemberPointerConversion(SrcTy, DstTy, CK, E->path_begin(),
3198 E->path_end(), Src);
3201 llvm::Constant *MicrosoftCXXABI::EmitMemberPointerConversion(
3202 const MemberPointerType *SrcTy, const MemberPointerType *DstTy, CastKind CK,
3203 CastExpr::path_const_iterator PathBegin,
3204 CastExpr::path_const_iterator PathEnd, llvm::Constant *Src) {
3205 assert(CK == CK_DerivedToBaseMemberPointer ||
3206 CK == CK_BaseToDerivedMemberPointer ||
3207 CK == CK_ReinterpretMemberPointer);
3208 // If src is null, emit a new null for dst. We can't return src because dst
3209 // might have a new representation.
3210 if (MemberPointerConstantIsNull(SrcTy, Src))
3211 return EmitNullMemberPointer(DstTy);
3213 // We don't need to do anything for reinterpret_casts of non-null member
3214 // pointers. We should only get here when the two type representations have
3216 if (CK == CK_ReinterpretMemberPointer)
3219 CGBuilderTy Builder(CGM, CGM.getLLVMContext());
3220 auto *Dst = cast<llvm::Constant>(EmitNonNullMemberPointerConversion(
3221 SrcTy, DstTy, CK, PathBegin, PathEnd, Src, Builder));
3226 llvm::Value *MicrosoftCXXABI::EmitLoadOfMemberFunctionPointer(
3227 CodeGenFunction &CGF, const Expr *E, Address This,
3228 llvm::Value *&ThisPtrForCall, llvm::Value *MemPtr,
3229 const MemberPointerType *MPT) {
3230 assert(MPT->isMemberFunctionPointer());
3231 const FunctionProtoType *FPT =
3232 MPT->getPointeeType()->castAs<FunctionProtoType>();
3233 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
3234 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(
3235 CGM.getTypes().arrangeCXXMethodType(RD, FPT, /*FD=*/nullptr));
3236 CGBuilderTy &Builder = CGF.Builder;
3238 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
3240 // Extract the fields we need, regardless of model. We'll apply them if we
3242 llvm::Value *FunctionPointer = MemPtr;
3243 llvm::Value *NonVirtualBaseAdjustment = nullptr;
3244 llvm::Value *VirtualBaseAdjustmentOffset = nullptr;
3245 llvm::Value *VBPtrOffset = nullptr;
3246 if (MemPtr->getType()->isStructTy()) {
3247 // We need to extract values.
3249 FunctionPointer = Builder.CreateExtractValue(MemPtr, I++);
3250 if (MSInheritanceAttr::hasNVOffsetField(MPT, Inheritance))
3251 NonVirtualBaseAdjustment = Builder.CreateExtractValue(MemPtr, I++);
3252 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance))
3253 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
3254 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance))
3255 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
3258 if (VirtualBaseAdjustmentOffset) {
3259 ThisPtrForCall = AdjustVirtualBase(CGF, E, RD, This,
3260 VirtualBaseAdjustmentOffset, VBPtrOffset);
3262 ThisPtrForCall = This.getPointer();
3265 if (NonVirtualBaseAdjustment) {
3266 // Apply the adjustment and cast back to the original struct type.
3267 llvm::Value *Ptr = Builder.CreateBitCast(ThisPtrForCall, CGF.Int8PtrTy);
3268 Ptr = Builder.CreateInBoundsGEP(Ptr, NonVirtualBaseAdjustment);
3269 ThisPtrForCall = Builder.CreateBitCast(Ptr, ThisPtrForCall->getType(),
3273 return Builder.CreateBitCast(FunctionPointer, FTy->getPointerTo());
3276 CGCXXABI *clang::CodeGen::CreateMicrosoftCXXABI(CodeGenModule &CGM) {
3277 return new MicrosoftCXXABI(CGM);
3280 // MS RTTI Overview:
3281 // The run time type information emitted by cl.exe contains 5 distinct types of
3282 // structures. Many of them reference each other.
3284 // TypeInfo: Static classes that are returned by typeid.
3286 // CompleteObjectLocator: Referenced by vftables. They contain information
3287 // required for dynamic casting, including OffsetFromTop. They also contain
3288 // a reference to the TypeInfo for the type and a reference to the
3289 // CompleteHierarchyDescriptor for the type.
3291 // ClassHieararchyDescriptor: Contains information about a class hierarchy.
3292 // Used during dynamic_cast to walk a class hierarchy. References a base
3293 // class array and the size of said array.
3295 // BaseClassArray: Contains a list of classes in a hierarchy. BaseClassArray is
3296 // somewhat of a misnomer because the most derived class is also in the list
3297 // as well as multiple copies of virtual bases (if they occur multiple times
3298 // in the hiearchy.) The BaseClassArray contains one BaseClassDescriptor for
3299 // every path in the hierarchy, in pre-order depth first order. Note, we do
3300 // not declare a specific llvm type for BaseClassArray, it's merely an array
3301 // of BaseClassDescriptor pointers.
3303 // BaseClassDescriptor: Contains information about a class in a class hierarchy.
3304 // BaseClassDescriptor is also somewhat of a misnomer for the same reason that
3305 // BaseClassArray is. It contains information about a class within a
3306 // hierarchy such as: is this base is ambiguous and what is its offset in the
3307 // vbtable. The names of the BaseClassDescriptors have all of their fields
3308 // mangled into them so they can be aggressively deduplicated by the linker.
3310 static llvm::GlobalVariable *getTypeInfoVTable(CodeGenModule &CGM) {
3311 StringRef MangledName("\01??_7type_info@@6B@");
3312 if (auto VTable = CGM.getModule().getNamedGlobal(MangledName))
3314 return new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
3316 llvm::GlobalVariable::ExternalLinkage,
3317 /*Initializer=*/nullptr, MangledName);
3322 /// \brief A Helper struct that stores information about a class in a class
3323 /// hierarchy. The information stored in these structs struct is used during
3324 /// the generation of ClassHierarchyDescriptors and BaseClassDescriptors.
3325 // During RTTI creation, MSRTTIClasses are stored in a contiguous array with
3326 // implicit depth first pre-order tree connectivity. getFirstChild and
3327 // getNextSibling allow us to walk the tree efficiently.
3328 struct MSRTTIClass {
3330 IsPrivateOnPath = 1 | 8,
3334 HasHierarchyDescriptor = 64
3336 MSRTTIClass(const CXXRecordDecl *RD) : RD(RD) {}
3337 uint32_t initialize(const MSRTTIClass *Parent,
3338 const CXXBaseSpecifier *Specifier);
3340 MSRTTIClass *getFirstChild() { return this + 1; }
3341 static MSRTTIClass *getNextChild(MSRTTIClass *Child) {
3342 return Child + 1 + Child->NumBases;
3345 const CXXRecordDecl *RD, *VirtualRoot;
3346 uint32_t Flags, NumBases, OffsetInVBase;
3349 /// \brief Recursively initialize the base class array.
3350 uint32_t MSRTTIClass::initialize(const MSRTTIClass *Parent,
3351 const CXXBaseSpecifier *Specifier) {
3352 Flags = HasHierarchyDescriptor;
3354 VirtualRoot = nullptr;
3357 if (Specifier->getAccessSpecifier() != AS_public)
3358 Flags |= IsPrivate | IsPrivateOnPath;
3359 if (Specifier->isVirtual()) {
3364 if (Parent->Flags & IsPrivateOnPath)
3365 Flags |= IsPrivateOnPath;
3366 VirtualRoot = Parent->VirtualRoot;
3367 OffsetInVBase = Parent->OffsetInVBase + RD->getASTContext()
3368 .getASTRecordLayout(Parent->RD).getBaseClassOffset(RD).getQuantity();
3372 MSRTTIClass *Child = getFirstChild();
3373 for (const CXXBaseSpecifier &Base : RD->bases()) {
3374 NumBases += Child->initialize(this, &Base) + 1;
3375 Child = getNextChild(Child);
3380 static llvm::GlobalValue::LinkageTypes getLinkageForRTTI(QualType Ty) {
3381 switch (Ty->getLinkage()) {
3383 case InternalLinkage:
3384 case UniqueExternalLinkage:
3385 return llvm::GlobalValue::InternalLinkage;
3387 case VisibleNoLinkage:
3388 case ExternalLinkage:
3389 return llvm::GlobalValue::LinkOnceODRLinkage;
3391 llvm_unreachable("Invalid linkage!");
3394 /// \brief An ephemeral helper class for building MS RTTI types. It caches some
3395 /// calls to the module and information about the most derived class in a
3397 struct MSRTTIBuilder {
3399 HasBranchingHierarchy = 1,
3400 HasVirtualBranchingHierarchy = 2,
3401 HasAmbiguousBases = 4
3404 MSRTTIBuilder(MicrosoftCXXABI &ABI, const CXXRecordDecl *RD)
3405 : CGM(ABI.CGM), Context(CGM.getContext()),
3406 VMContext(CGM.getLLVMContext()), Module(CGM.getModule()), RD(RD),
3407 Linkage(getLinkageForRTTI(CGM.getContext().getTagDeclType(RD))),
3410 llvm::GlobalVariable *getBaseClassDescriptor(const MSRTTIClass &Classes);
3411 llvm::GlobalVariable *
3412 getBaseClassArray(SmallVectorImpl<MSRTTIClass> &Classes);
3413 llvm::GlobalVariable *getClassHierarchyDescriptor();
3414 llvm::GlobalVariable *getCompleteObjectLocator(const VPtrInfo *Info);
3417 ASTContext &Context;
3418 llvm::LLVMContext &VMContext;
3419 llvm::Module &Module;
3420 const CXXRecordDecl *RD;
3421 llvm::GlobalVariable::LinkageTypes Linkage;
3422 MicrosoftCXXABI &ABI;
3427 /// \brief Recursively serializes a class hierarchy in pre-order depth first
3429 static void serializeClassHierarchy(SmallVectorImpl<MSRTTIClass> &Classes,
3430 const CXXRecordDecl *RD) {
3431 Classes.push_back(MSRTTIClass(RD));
3432 for (const CXXBaseSpecifier &Base : RD->bases())
3433 serializeClassHierarchy(Classes, Base.getType()->getAsCXXRecordDecl());
3436 /// \brief Find ambiguity among base classes.
3438 detectAmbiguousBases(SmallVectorImpl<MSRTTIClass> &Classes) {
3439 llvm::SmallPtrSet<const CXXRecordDecl *, 8> VirtualBases;
3440 llvm::SmallPtrSet<const CXXRecordDecl *, 8> UniqueBases;
3441 llvm::SmallPtrSet<const CXXRecordDecl *, 8> AmbiguousBases;
3442 for (MSRTTIClass *Class = &Classes.front(); Class <= &Classes.back();) {
3443 if ((Class->Flags & MSRTTIClass::IsVirtual) &&
3444 !VirtualBases.insert(Class->RD).second) {
3445 Class = MSRTTIClass::getNextChild(Class);
3448 if (!UniqueBases.insert(Class->RD).second)
3449 AmbiguousBases.insert(Class->RD);
3452 if (AmbiguousBases.empty())
3454 for (MSRTTIClass &Class : Classes)
3455 if (AmbiguousBases.count(Class.RD))
3456 Class.Flags |= MSRTTIClass::IsAmbiguous;
3459 llvm::GlobalVariable *MSRTTIBuilder::getClassHierarchyDescriptor() {
3460 SmallString<256> MangledName;
3462 llvm::raw_svector_ostream Out(MangledName);
3463 ABI.getMangleContext().mangleCXXRTTIClassHierarchyDescriptor(RD, Out);
3466 // Check to see if we've already declared this ClassHierarchyDescriptor.
3467 if (auto CHD = Module.getNamedGlobal(MangledName))
3470 // Serialize the class hierarchy and initialize the CHD Fields.
3471 SmallVector<MSRTTIClass, 8> Classes;
3472 serializeClassHierarchy(Classes, RD);
3473 Classes.front().initialize(/*Parent=*/nullptr, /*Specifier=*/nullptr);
3474 detectAmbiguousBases(Classes);
3476 for (auto Class : Classes) {
3477 if (Class.RD->getNumBases() > 1)
3478 Flags |= HasBranchingHierarchy;
3479 // Note: cl.exe does not calculate "HasAmbiguousBases" correctly. We
3480 // believe the field isn't actually used.
3481 if (Class.Flags & MSRTTIClass::IsAmbiguous)
3482 Flags |= HasAmbiguousBases;
3484 if ((Flags & HasBranchingHierarchy) && RD->getNumVBases() != 0)
3485 Flags |= HasVirtualBranchingHierarchy;
3486 // These gep indices are used to get the address of the first element of the
3487 // base class array.
3488 llvm::Value *GEPIndices[] = {llvm::ConstantInt::get(CGM.IntTy, 0),
3489 llvm::ConstantInt::get(CGM.IntTy, 0)};
3491 // Forward-declare the class hierarchy descriptor
3492 auto Type = ABI.getClassHierarchyDescriptorType();
3493 auto CHD = new llvm::GlobalVariable(Module, Type, /*Constant=*/true, Linkage,
3494 /*Initializer=*/nullptr,
3496 if (CHD->isWeakForLinker())
3497 CHD->setComdat(CGM.getModule().getOrInsertComdat(CHD->getName()));
3499 auto *Bases = getBaseClassArray(Classes);
3501 // Initialize the base class ClassHierarchyDescriptor.
3502 llvm::Constant *Fields[] = {
3503 llvm::ConstantInt::get(CGM.IntTy, 0), // Unknown
3504 llvm::ConstantInt::get(CGM.IntTy, Flags),
3505 llvm::ConstantInt::get(CGM.IntTy, Classes.size()),
3506 ABI.getImageRelativeConstant(llvm::ConstantExpr::getInBoundsGetElementPtr(
3507 Bases->getValueType(), Bases,
3508 llvm::ArrayRef<llvm::Value *>(GEPIndices))),
3510 CHD->setInitializer(llvm::ConstantStruct::get(Type, Fields));
3514 llvm::GlobalVariable *
3515 MSRTTIBuilder::getBaseClassArray(SmallVectorImpl<MSRTTIClass> &Classes) {
3516 SmallString<256> MangledName;
3518 llvm::raw_svector_ostream Out(MangledName);
3519 ABI.getMangleContext().mangleCXXRTTIBaseClassArray(RD, Out);
3522 // Forward-declare the base class array.
3523 // cl.exe pads the base class array with 1 (in 32 bit mode) or 4 (in 64 bit
3524 // mode) bytes of padding. We provide a pointer sized amount of padding by
3525 // adding +1 to Classes.size(). The sections have pointer alignment and are
3526 // marked pick-any so it shouldn't matter.
3527 llvm::Type *PtrType = ABI.getImageRelativeType(
3528 ABI.getBaseClassDescriptorType()->getPointerTo());
3529 auto *ArrType = llvm::ArrayType::get(PtrType, Classes.size() + 1);
3531 new llvm::GlobalVariable(Module, ArrType,
3532 /*Constant=*/true, Linkage,
3533 /*Initializer=*/nullptr, MangledName);
3534 if (BCA->isWeakForLinker())
3535 BCA->setComdat(CGM.getModule().getOrInsertComdat(BCA->getName()));
3537 // Initialize the BaseClassArray.
3538 SmallVector<llvm::Constant *, 8> BaseClassArrayData;
3539 for (MSRTTIClass &Class : Classes)
3540 BaseClassArrayData.push_back(
3541 ABI.getImageRelativeConstant(getBaseClassDescriptor(Class)));
3542 BaseClassArrayData.push_back(llvm::Constant::getNullValue(PtrType));
3543 BCA->setInitializer(llvm::ConstantArray::get(ArrType, BaseClassArrayData));
3547 llvm::GlobalVariable *
3548 MSRTTIBuilder::getBaseClassDescriptor(const MSRTTIClass &Class) {
3549 // Compute the fields for the BaseClassDescriptor. They are computed up front
3550 // because they are mangled into the name of the object.
3551 uint32_t OffsetInVBTable = 0;
3552 int32_t VBPtrOffset = -1;
3553 if (Class.VirtualRoot) {
3554 auto &VTableContext = CGM.getMicrosoftVTableContext();
3555 OffsetInVBTable = VTableContext.getVBTableIndex(RD, Class.VirtualRoot) * 4;
3556 VBPtrOffset = Context.getASTRecordLayout(RD).getVBPtrOffset().getQuantity();
3559 SmallString<256> MangledName;
3561 llvm::raw_svector_ostream Out(MangledName);
3562 ABI.getMangleContext().mangleCXXRTTIBaseClassDescriptor(
3563 Class.RD, Class.OffsetInVBase, VBPtrOffset, OffsetInVBTable,
3567 // Check to see if we've already declared this object.
3568 if (auto BCD = Module.getNamedGlobal(MangledName))
3571 // Forward-declare the base class descriptor.
3572 auto Type = ABI.getBaseClassDescriptorType();
3574 new llvm::GlobalVariable(Module, Type, /*Constant=*/true, Linkage,
3575 /*Initializer=*/nullptr, MangledName);
3576 if (BCD->isWeakForLinker())
3577 BCD->setComdat(CGM.getModule().getOrInsertComdat(BCD->getName()));
3579 // Initialize the BaseClassDescriptor.
3580 llvm::Constant *Fields[] = {
3581 ABI.getImageRelativeConstant(
3582 ABI.getAddrOfRTTIDescriptor(Context.getTypeDeclType(Class.RD))),
3583 llvm::ConstantInt::get(CGM.IntTy, Class.NumBases),
3584 llvm::ConstantInt::get(CGM.IntTy, Class.OffsetInVBase),
3585 llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset),
3586 llvm::ConstantInt::get(CGM.IntTy, OffsetInVBTable),
3587 llvm::ConstantInt::get(CGM.IntTy, Class.Flags),
3588 ABI.getImageRelativeConstant(
3589 MSRTTIBuilder(ABI, Class.RD).getClassHierarchyDescriptor()),
3591 BCD->setInitializer(llvm::ConstantStruct::get(Type, Fields));
3595 llvm::GlobalVariable *
3596 MSRTTIBuilder::getCompleteObjectLocator(const VPtrInfo *Info) {
3597 SmallString<256> MangledName;
3599 llvm::raw_svector_ostream Out(MangledName);
3600 ABI.getMangleContext().mangleCXXRTTICompleteObjectLocator(RD, Info->MangledPath, Out);
3603 // Check to see if we've already computed this complete object locator.
3604 if (auto COL = Module.getNamedGlobal(MangledName))
3607 // Compute the fields of the complete object locator.
3608 int OffsetToTop = Info->FullOffsetInMDC.getQuantity();
3609 int VFPtrOffset = 0;
3610 // The offset includes the vtordisp if one exists.
3611 if (const CXXRecordDecl *VBase = Info->getVBaseWithVPtr())
3612 if (Context.getASTRecordLayout(RD)
3613 .getVBaseOffsetsMap()
3615 ->second.hasVtorDisp())
3616 VFPtrOffset = Info->NonVirtualOffset.getQuantity() + 4;
3618 // Forward-declare the complete object locator.
3619 llvm::StructType *Type = ABI.getCompleteObjectLocatorType();
3620 auto COL = new llvm::GlobalVariable(Module, Type, /*Constant=*/true, Linkage,
3621 /*Initializer=*/nullptr, MangledName);
3623 // Initialize the CompleteObjectLocator.
3624 llvm::Constant *Fields[] = {
3625 llvm::ConstantInt::get(CGM.IntTy, ABI.isImageRelative()),
3626 llvm::ConstantInt::get(CGM.IntTy, OffsetToTop),
3627 llvm::ConstantInt::get(CGM.IntTy, VFPtrOffset),
3628 ABI.getImageRelativeConstant(
3629 CGM.GetAddrOfRTTIDescriptor(Context.getTypeDeclType(RD))),
3630 ABI.getImageRelativeConstant(getClassHierarchyDescriptor()),
3631 ABI.getImageRelativeConstant(COL),
3633 llvm::ArrayRef<llvm::Constant *> FieldsRef(Fields);
3634 if (!ABI.isImageRelative())
3635 FieldsRef = FieldsRef.drop_back();
3636 COL->setInitializer(llvm::ConstantStruct::get(Type, FieldsRef));
3637 if (COL->isWeakForLinker())
3638 COL->setComdat(CGM.getModule().getOrInsertComdat(COL->getName()));
3642 static QualType decomposeTypeForEH(ASTContext &Context, QualType T,
3643 bool &IsConst, bool &IsVolatile) {
3644 T = Context.getExceptionObjectType(T);
3646 // C++14 [except.handle]p3:
3647 // A handler is a match for an exception object of type E if [...]
3648 // - the handler is of type cv T or const T& where T is a pointer type and
3649 // E is a pointer type that can be converted to T by [...]
3650 // - a qualification conversion
3653 QualType PointeeType = T->getPointeeType();
3654 if (!PointeeType.isNull()) {
3655 IsConst = PointeeType.isConstQualified();
3656 IsVolatile = PointeeType.isVolatileQualified();
3659 // Member pointer types like "const int A::*" are represented by having RTTI
3660 // for "int A::*" and separately storing the const qualifier.
3661 if (const auto *MPTy = T->getAs<MemberPointerType>())
3662 T = Context.getMemberPointerType(PointeeType.getUnqualifiedType(),
3665 // Pointer types like "const int * const *" are represented by having RTTI
3666 // for "const int **" and separately storing the const qualifier.
3667 if (T->isPointerType())
3668 T = Context.getPointerType(PointeeType.getUnqualifiedType());
3674 MicrosoftCXXABI::getAddrOfCXXCatchHandlerType(QualType Type,
3675 QualType CatchHandlerType) {
3676 // TypeDescriptors for exceptions never have qualified pointer types,
3677 // qualifiers are stored seperately in order to support qualification
3679 bool IsConst, IsVolatile;
3680 Type = decomposeTypeForEH(getContext(), Type, IsConst, IsVolatile);
3682 bool IsReference = CatchHandlerType->isReferenceType();
3692 return CatchTypeInfo{getAddrOfRTTIDescriptor(Type)->stripPointerCasts(),
3696 /// \brief Gets a TypeDescriptor. Returns a llvm::Constant * rather than a
3697 /// llvm::GlobalVariable * because different type descriptors have different
3698 /// types, and need to be abstracted. They are abstracting by casting the
3699 /// address to an Int8PtrTy.
3700 llvm::Constant *MicrosoftCXXABI::getAddrOfRTTIDescriptor(QualType Type) {
3701 SmallString<256> MangledName;
3703 llvm::raw_svector_ostream Out(MangledName);
3704 getMangleContext().mangleCXXRTTI(Type, Out);
3707 // Check to see if we've already declared this TypeDescriptor.
3708 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
3709 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
3711 // Compute the fields for the TypeDescriptor.
3712 SmallString<256> TypeInfoString;
3714 llvm::raw_svector_ostream Out(TypeInfoString);
3715 getMangleContext().mangleCXXRTTIName(Type, Out);
3718 // Declare and initialize the TypeDescriptor.
3719 llvm::Constant *Fields[] = {
3720 getTypeInfoVTable(CGM), // VFPtr
3721 llvm::ConstantPointerNull::get(CGM.Int8PtrTy), // Runtime data
3722 llvm::ConstantDataArray::getString(CGM.getLLVMContext(), TypeInfoString)};
3723 llvm::StructType *TypeDescriptorType =
3724 getTypeDescriptorType(TypeInfoString);
3725 auto *Var = new llvm::GlobalVariable(
3726 CGM.getModule(), TypeDescriptorType, /*Constant=*/false,
3727 getLinkageForRTTI(Type),
3728 llvm::ConstantStruct::get(TypeDescriptorType, Fields),
3730 if (Var->isWeakForLinker())
3731 Var->setComdat(CGM.getModule().getOrInsertComdat(Var->getName()));
3732 return llvm::ConstantExpr::getBitCast(Var, CGM.Int8PtrTy);
3735 /// \brief Gets or a creates a Microsoft CompleteObjectLocator.
3736 llvm::GlobalVariable *
3737 MicrosoftCXXABI::getMSCompleteObjectLocator(const CXXRecordDecl *RD,
3738 const VPtrInfo *Info) {
3739 return MSRTTIBuilder(*this, RD).getCompleteObjectLocator(Info);
3742 static void emitCXXConstructor(CodeGenModule &CGM,
3743 const CXXConstructorDecl *ctor,
3744 StructorType ctorType) {
3745 // There are no constructor variants, always emit the complete destructor.
3746 llvm::Function *Fn = CGM.codegenCXXStructor(ctor, StructorType::Complete);
3747 CGM.maybeSetTrivialComdat(*ctor, *Fn);
3750 static void emitCXXDestructor(CodeGenModule &CGM, const CXXDestructorDecl *dtor,
3751 StructorType dtorType) {
3752 // The complete destructor is equivalent to the base destructor for
3753 // classes with no virtual bases, so try to emit it as an alias.
3754 if (!dtor->getParent()->getNumVBases() &&
3755 (dtorType == StructorType::Complete || dtorType == StructorType::Base)) {
3756 bool ProducedAlias = !CGM.TryEmitDefinitionAsAlias(
3757 GlobalDecl(dtor, Dtor_Complete), GlobalDecl(dtor, Dtor_Base), true);
3758 if (ProducedAlias) {
3759 if (dtorType == StructorType::Complete)
3761 if (dtor->isVirtual())
3762 CGM.getVTables().EmitThunks(GlobalDecl(dtor, Dtor_Complete));
3766 // The base destructor is equivalent to the base destructor of its
3767 // base class if there is exactly one non-virtual base class with a
3768 // non-trivial destructor, there are no fields with a non-trivial
3769 // destructor, and the body of the destructor is trivial.
3770 if (dtorType == StructorType::Base && !CGM.TryEmitBaseDestructorAsAlias(dtor))
3773 llvm::Function *Fn = CGM.codegenCXXStructor(dtor, dtorType);
3774 if (Fn->isWeakForLinker())
3775 Fn->setComdat(CGM.getModule().getOrInsertComdat(Fn->getName()));
3778 void MicrosoftCXXABI::emitCXXStructor(const CXXMethodDecl *MD,
3779 StructorType Type) {
3780 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
3781 emitCXXConstructor(CGM, CD, Type);
3784 emitCXXDestructor(CGM, cast<CXXDestructorDecl>(MD), Type);
3788 MicrosoftCXXABI::getAddrOfCXXCtorClosure(const CXXConstructorDecl *CD,
3790 assert(CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure);
3792 // Calculate the mangled name.
3793 SmallString<256> ThunkName;
3794 llvm::raw_svector_ostream Out(ThunkName);
3795 getMangleContext().mangleCXXCtor(CD, CT, Out);
3797 // If the thunk has been generated previously, just return it.
3798 if (llvm::GlobalValue *GV = CGM.getModule().getNamedValue(ThunkName))
3799 return cast<llvm::Function>(GV);
3801 // Create the llvm::Function.
3802 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeMSCtorClosure(CD, CT);
3803 llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo);
3804 const CXXRecordDecl *RD = CD->getParent();
3805 QualType RecordTy = getContext().getRecordType(RD);
3806 llvm::Function *ThunkFn = llvm::Function::Create(
3807 ThunkTy, getLinkageForRTTI(RecordTy), ThunkName.str(), &CGM.getModule());
3808 ThunkFn->setCallingConv(static_cast<llvm::CallingConv::ID>(
3809 FnInfo.getEffectiveCallingConvention()));
3810 if (ThunkFn->isWeakForLinker())
3811 ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));
3812 bool IsCopy = CT == Ctor_CopyingClosure;
3815 CodeGenFunction CGF(CGM);
3816 CGF.CurGD = GlobalDecl(CD, Ctor_Complete);
3818 // Build FunctionArgs.
3819 FunctionArgList FunctionArgs;
3821 // A constructor always starts with a 'this' pointer as its first argument.
3822 buildThisParam(CGF, FunctionArgs);
3824 // Following the 'this' pointer is a reference to the source object that we
3825 // are copying from.
3826 ImplicitParamDecl SrcParam(
3827 getContext(), nullptr, SourceLocation(), &getContext().Idents.get("src"),
3828 getContext().getLValueReferenceType(RecordTy,
3829 /*SpelledAsLValue=*/true));
3831 FunctionArgs.push_back(&SrcParam);
3833 // Constructors for classes which utilize virtual bases have an additional
3834 // parameter which indicates whether or not it is being delegated to by a more
3835 // derived constructor.
3836 ImplicitParamDecl IsMostDerived(getContext(), nullptr, SourceLocation(),
3837 &getContext().Idents.get("is_most_derived"),
3838 getContext().IntTy);
3839 // Only add the parameter to the list if thie class has virtual bases.
3840 if (RD->getNumVBases() > 0)
3841 FunctionArgs.push_back(&IsMostDerived);
3843 // Start defining the function.
3844 CGF.StartFunction(GlobalDecl(), FnInfo.getReturnType(), ThunkFn, FnInfo,
3845 FunctionArgs, CD->getLocation(), SourceLocation());
3847 llvm::Value *This = getThisValue(CGF);
3849 llvm::Value *SrcVal =
3850 IsCopy ? CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&SrcParam), "src")
3855 // Push the this ptr.
3856 Args.add(RValue::get(This), CD->getThisType(getContext()));
3858 // Push the src ptr.
3860 Args.add(RValue::get(SrcVal), SrcParam.getType());
3862 // Add the rest of the default arguments.
3863 std::vector<Stmt *> ArgVec;
3864 for (unsigned I = IsCopy ? 1 : 0, E = CD->getNumParams(); I != E; ++I) {
3865 Stmt *DefaultArg = getContext().getDefaultArgExprForConstructor(CD, I);
3866 assert(DefaultArg && "sema forgot to instantiate default args");
3867 ArgVec.push_back(DefaultArg);
3870 CodeGenFunction::RunCleanupsScope Cleanups(CGF);
3872 const auto *FPT = CD->getType()->castAs<FunctionProtoType>();
3873 CGF.EmitCallArgs(Args, FPT, llvm::makeArrayRef(ArgVec), CD, IsCopy ? 1 : 0);
3875 // Insert any ABI-specific implicit constructor arguments.
3876 unsigned ExtraArgs = addImplicitConstructorArgs(CGF, CD, Ctor_Complete,
3877 /*ForVirtualBase=*/false,
3878 /*Delegating=*/false, Args);
3880 // Call the destructor with our arguments.
3881 llvm::Value *CalleeFn = CGM.getAddrOfCXXStructor(CD, StructorType::Complete);
3882 const CGFunctionInfo &CalleeInfo = CGM.getTypes().arrangeCXXConstructorCall(
3883 Args, CD, Ctor_Complete, ExtraArgs);
3884 CGF.EmitCall(CalleeInfo, CalleeFn, ReturnValueSlot(), Args, CD);
3886 Cleanups.ForceCleanup();
3888 // Emit the ret instruction, remove any temporary instructions created for the
3890 CGF.FinishFunction(SourceLocation());
3895 llvm::Constant *MicrosoftCXXABI::getCatchableType(QualType T,
3897 int32_t VBPtrOffset,
3899 assert(!T->isReferenceType());
3901 CXXRecordDecl *RD = T->getAsCXXRecordDecl();
3902 const CXXConstructorDecl *CD =
3903 RD ? CGM.getContext().getCopyConstructorForExceptionObject(RD) : nullptr;
3904 CXXCtorType CT = Ctor_Complete;
3906 if (!hasDefaultCXXMethodCC(getContext(), CD) || CD->getNumParams() != 1)
3907 CT = Ctor_CopyingClosure;
3909 uint32_t Size = getContext().getTypeSizeInChars(T).getQuantity();
3910 SmallString<256> MangledName;
3912 llvm::raw_svector_ostream Out(MangledName);
3913 getMangleContext().mangleCXXCatchableType(T, CD, CT, Size, NVOffset,
3914 VBPtrOffset, VBIndex, Out);
3916 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
3917 return getImageRelativeConstant(GV);
3919 // The TypeDescriptor is used by the runtime to determine if a catch handler
3920 // is appropriate for the exception object.
3921 llvm::Constant *TD = getImageRelativeConstant(getAddrOfRTTIDescriptor(T));
3923 // The runtime is responsible for calling the copy constructor if the
3924 // exception is caught by value.
3925 llvm::Constant *CopyCtor;
3927 if (CT == Ctor_CopyingClosure)
3928 CopyCtor = getAddrOfCXXCtorClosure(CD, Ctor_CopyingClosure);
3930 CopyCtor = CGM.getAddrOfCXXStructor(CD, StructorType::Complete);
3932 CopyCtor = llvm::ConstantExpr::getBitCast(CopyCtor, CGM.Int8PtrTy);
3934 CopyCtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);
3936 CopyCtor = getImageRelativeConstant(CopyCtor);
3938 bool IsScalar = !RD;
3939 bool HasVirtualBases = false;
3940 bool IsStdBadAlloc = false; // std::bad_alloc is special for some reason.
3941 QualType PointeeType = T;
3942 if (T->isPointerType())
3943 PointeeType = T->getPointeeType();
3944 if (const CXXRecordDecl *RD = PointeeType->getAsCXXRecordDecl()) {
3945 HasVirtualBases = RD->getNumVBases() > 0;
3946 if (IdentifierInfo *II = RD->getIdentifier())
3947 IsStdBadAlloc = II->isStr("bad_alloc") && RD->isInStdNamespace();
3950 // Encode the relevant CatchableType properties into the Flags bitfield.
3951 // FIXME: Figure out how bits 2 or 8 can get set.
3955 if (HasVirtualBases)
3960 llvm::Constant *Fields[] = {
3961 llvm::ConstantInt::get(CGM.IntTy, Flags), // Flags
3962 TD, // TypeDescriptor
3963 llvm::ConstantInt::get(CGM.IntTy, NVOffset), // NonVirtualAdjustment
3964 llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset), // OffsetToVBPtr
3965 llvm::ConstantInt::get(CGM.IntTy, VBIndex), // VBTableIndex
3966 llvm::ConstantInt::get(CGM.IntTy, Size), // Size
3967 CopyCtor // CopyCtor
3969 llvm::StructType *CTType = getCatchableTypeType();
3970 auto *GV = new llvm::GlobalVariable(
3971 CGM.getModule(), CTType, /*Constant=*/true, getLinkageForRTTI(T),
3972 llvm::ConstantStruct::get(CTType, Fields), MangledName);
3973 GV->setUnnamedAddr(true);
3974 GV->setSection(".xdata");
3975 if (GV->isWeakForLinker())
3976 GV->setComdat(CGM.getModule().getOrInsertComdat(GV->getName()));
3977 return getImageRelativeConstant(GV);
3980 llvm::GlobalVariable *MicrosoftCXXABI::getCatchableTypeArray(QualType T) {
3981 assert(!T->isReferenceType());
3983 // See if we've already generated a CatchableTypeArray for this type before.
3984 llvm::GlobalVariable *&CTA = CatchableTypeArrays[T];
3988 // Ensure that we don't have duplicate entries in our CatchableTypeArray by
3989 // using a SmallSetVector. Duplicates may arise due to virtual bases
3990 // occurring more than once in the hierarchy.
3991 llvm::SmallSetVector<llvm::Constant *, 2> CatchableTypes;
3993 // C++14 [except.handle]p3:
3994 // A handler is a match for an exception object of type E if [...]
3995 // - the handler is of type cv T or cv T& and T is an unambiguous public
3996 // base class of E, or
3997 // - the handler is of type cv T or const T& where T is a pointer type and
3998 // E is a pointer type that can be converted to T by [...]
3999 // - a standard pointer conversion (4.10) not involving conversions to
4000 // pointers to private or protected or ambiguous classes
4001 const CXXRecordDecl *MostDerivedClass = nullptr;
4002 bool IsPointer = T->isPointerType();
4004 MostDerivedClass = T->getPointeeType()->getAsCXXRecordDecl();
4006 MostDerivedClass = T->getAsCXXRecordDecl();
4008 // Collect all the unambiguous public bases of the MostDerivedClass.
4009 if (MostDerivedClass) {
4010 const ASTContext &Context = getContext();
4011 const ASTRecordLayout &MostDerivedLayout =
4012 Context.getASTRecordLayout(MostDerivedClass);
4013 MicrosoftVTableContext &VTableContext = CGM.getMicrosoftVTableContext();
4014 SmallVector<MSRTTIClass, 8> Classes;
4015 serializeClassHierarchy(Classes, MostDerivedClass);
4016 Classes.front().initialize(/*Parent=*/nullptr, /*Specifier=*/nullptr);
4017 detectAmbiguousBases(Classes);
4018 for (const MSRTTIClass &Class : Classes) {
4019 // Skip any ambiguous or private bases.
4021 (MSRTTIClass::IsPrivateOnPath | MSRTTIClass::IsAmbiguous))
4023 // Write down how to convert from a derived pointer to a base pointer.
4024 uint32_t OffsetInVBTable = 0;
4025 int32_t VBPtrOffset = -1;
4026 if (Class.VirtualRoot) {
4028 VTableContext.getVBTableIndex(MostDerivedClass, Class.VirtualRoot)*4;
4029 VBPtrOffset = MostDerivedLayout.getVBPtrOffset().getQuantity();
4032 // Turn our record back into a pointer if the exception object is a
4034 QualType RTTITy = QualType(Class.RD->getTypeForDecl(), 0);
4036 RTTITy = Context.getPointerType(RTTITy);
4037 CatchableTypes.insert(getCatchableType(RTTITy, Class.OffsetInVBase,
4038 VBPtrOffset, OffsetInVBTable));
4042 // C++14 [except.handle]p3:
4043 // A handler is a match for an exception object of type E if
4044 // - The handler is of type cv T or cv T& and E and T are the same type
4045 // (ignoring the top-level cv-qualifiers)
4046 CatchableTypes.insert(getCatchableType(T));
4048 // C++14 [except.handle]p3:
4049 // A handler is a match for an exception object of type E if
4050 // - the handler is of type cv T or const T& where T is a pointer type and
4051 // E is a pointer type that can be converted to T by [...]
4052 // - a standard pointer conversion (4.10) not involving conversions to
4053 // pointers to private or protected or ambiguous classes
4055 // C++14 [conv.ptr]p2:
4056 // A prvalue of type "pointer to cv T," where T is an object type, can be
4057 // converted to a prvalue of type "pointer to cv void".
4058 if (IsPointer && T->getPointeeType()->isObjectType())
4059 CatchableTypes.insert(getCatchableType(getContext().VoidPtrTy));
4061 // C++14 [except.handle]p3:
4062 // A handler is a match for an exception object of type E if [...]
4063 // - the handler is of type cv T or const T& where T is a pointer or
4064 // pointer to member type and E is std::nullptr_t.
4066 // We cannot possibly list all possible pointer types here, making this
4067 // implementation incompatible with the standard. However, MSVC includes an
4068 // entry for pointer-to-void in this case. Let's do the same.
4069 if (T->isNullPtrType())
4070 CatchableTypes.insert(getCatchableType(getContext().VoidPtrTy));
4072 uint32_t NumEntries = CatchableTypes.size();
4073 llvm::Type *CTType =
4074 getImageRelativeType(getCatchableTypeType()->getPointerTo());
4075 llvm::ArrayType *AT = llvm::ArrayType::get(CTType, NumEntries);
4076 llvm::StructType *CTAType = getCatchableTypeArrayType(NumEntries);
4077 llvm::Constant *Fields[] = {
4078 llvm::ConstantInt::get(CGM.IntTy, NumEntries), // NumEntries
4079 llvm::ConstantArray::get(
4080 AT, llvm::makeArrayRef(CatchableTypes.begin(),
4081 CatchableTypes.end())) // CatchableTypes
4083 SmallString<256> MangledName;
4085 llvm::raw_svector_ostream Out(MangledName);
4086 getMangleContext().mangleCXXCatchableTypeArray(T, NumEntries, Out);
4088 CTA = new llvm::GlobalVariable(
4089 CGM.getModule(), CTAType, /*Constant=*/true, getLinkageForRTTI(T),
4090 llvm::ConstantStruct::get(CTAType, Fields), MangledName);
4091 CTA->setUnnamedAddr(true);
4092 CTA->setSection(".xdata");
4093 if (CTA->isWeakForLinker())
4094 CTA->setComdat(CGM.getModule().getOrInsertComdat(CTA->getName()));
4098 llvm::GlobalVariable *MicrosoftCXXABI::getThrowInfo(QualType T) {
4099 bool IsConst, IsVolatile;
4100 T = decomposeTypeForEH(getContext(), T, IsConst, IsVolatile);
4102 // The CatchableTypeArray enumerates the various (CV-unqualified) types that
4103 // the exception object may be caught as.
4104 llvm::GlobalVariable *CTA = getCatchableTypeArray(T);
4105 // The first field in a CatchableTypeArray is the number of CatchableTypes.
4106 // This is used as a component of the mangled name which means that we need to
4107 // know what it is in order to see if we have previously generated the
4109 uint32_t NumEntries =
4110 cast<llvm::ConstantInt>(CTA->getInitializer()->getAggregateElement(0U))
4111 ->getLimitedValue();
4113 SmallString<256> MangledName;
4115 llvm::raw_svector_ostream Out(MangledName);
4116 getMangleContext().mangleCXXThrowInfo(T, IsConst, IsVolatile, NumEntries,
4120 // Reuse a previously generated ThrowInfo if we have generated an appropriate
4122 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
4125 // The RTTI TypeDescriptor uses an unqualified type but catch clauses must
4126 // be at least as CV qualified. Encode this requirement into the Flags
4134 // The cleanup-function (a destructor) must be called when the exception
4135 // object's lifetime ends.
4136 llvm::Constant *CleanupFn = llvm::Constant::getNullValue(CGM.Int8PtrTy);
4137 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4138 if (CXXDestructorDecl *DtorD = RD->getDestructor())
4139 if (!DtorD->isTrivial())
4140 CleanupFn = llvm::ConstantExpr::getBitCast(
4141 CGM.getAddrOfCXXStructor(DtorD, StructorType::Complete),
4143 // This is unused as far as we can tell, initialize it to null.
4144 llvm::Constant *ForwardCompat =
4145 getImageRelativeConstant(llvm::Constant::getNullValue(CGM.Int8PtrTy));
4146 llvm::Constant *PointerToCatchableTypes = getImageRelativeConstant(
4147 llvm::ConstantExpr::getBitCast(CTA, CGM.Int8PtrTy));
4148 llvm::StructType *TIType = getThrowInfoType();
4149 llvm::Constant *Fields[] = {
4150 llvm::ConstantInt::get(CGM.IntTy, Flags), // Flags
4151 getImageRelativeConstant(CleanupFn), // CleanupFn
4152 ForwardCompat, // ForwardCompat
4153 PointerToCatchableTypes // CatchableTypeArray
4155 auto *GV = new llvm::GlobalVariable(
4156 CGM.getModule(), TIType, /*Constant=*/true, getLinkageForRTTI(T),
4157 llvm::ConstantStruct::get(TIType, Fields), StringRef(MangledName));
4158 GV->setUnnamedAddr(true);
4159 GV->setSection(".xdata");
4160 if (GV->isWeakForLinker())
4161 GV->setComdat(CGM.getModule().getOrInsertComdat(GV->getName()));
4165 void MicrosoftCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
4166 const Expr *SubExpr = E->getSubExpr();
4167 QualType ThrowType = SubExpr->getType();
4168 // The exception object lives on the stack and it's address is passed to the
4169 // runtime function.
4170 Address AI = CGF.CreateMemTemp(ThrowType);
4171 CGF.EmitAnyExprToMem(SubExpr, AI, ThrowType.getQualifiers(),
4174 // The so-called ThrowInfo is used to describe how the exception object may be
4176 llvm::GlobalVariable *TI = getThrowInfo(ThrowType);
4178 // Call into the runtime to throw the exception.
4179 llvm::Value *Args[] = {
4180 CGF.Builder.CreateBitCast(AI.getPointer(), CGM.Int8PtrTy),
4183 CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(), Args);