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 "CGVTables.h"
19 #include "CodeGenModule.h"
20 #include "CodeGenTypes.h"
21 #include "TargetInfo.h"
22 #include "clang/AST/Decl.h"
23 #include "clang/AST/DeclCXX.h"
24 #include "clang/AST/StmtCXX.h"
25 #include "clang/AST/VTableBuilder.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringSet.h"
28 #include "llvm/IR/CallSite.h"
29 #include "llvm/IR/Intrinsics.h"
31 using namespace clang;
32 using namespace CodeGen;
36 /// Holds all the vbtable globals for a given class.
37 struct VBTableGlobals {
38 const VPtrInfoVector *VBTables;
39 SmallVector<llvm::GlobalVariable *, 2> Globals;
42 class MicrosoftCXXABI : public CGCXXABI {
44 MicrosoftCXXABI(CodeGenModule &CGM)
45 : CGCXXABI(CGM), BaseClassDescriptorType(nullptr),
46 ClassHierarchyDescriptorType(nullptr),
47 CompleteObjectLocatorType(nullptr), CatchableTypeType(nullptr),
48 ThrowInfoType(nullptr), CatchHandlerTypeType(nullptr) {}
50 bool HasThisReturn(GlobalDecl GD) const override;
51 bool hasMostDerivedReturn(GlobalDecl GD) const override;
53 bool classifyReturnType(CGFunctionInfo &FI) const override;
55 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override;
57 bool isSRetParameterAfterThis() const override { return true; }
59 size_t getSrcArgforCopyCtor(const CXXConstructorDecl *CD,
60 FunctionArgList &Args) const override {
61 assert(Args.size() >= 2 &&
62 "expected the arglist to have at least two args!");
63 // The 'most_derived' parameter goes second if the ctor is variadic and
65 if (CD->getParent()->getNumVBases() > 0 &&
66 CD->getType()->castAs<FunctionProtoType>()->isVariadic())
71 StringRef GetPureVirtualCallName() override { return "_purecall"; }
72 StringRef GetDeletedVirtualCallName() override { return "_purecall"; }
74 void emitVirtualObjectDelete(CodeGenFunction &CGF, const CXXDeleteExpr *DE,
75 llvm::Value *Ptr, QualType ElementType,
76 const CXXDestructorDecl *Dtor) override;
78 void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) override;
79 void emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) override;
81 void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override;
83 llvm::GlobalVariable *getMSCompleteObjectLocator(const CXXRecordDecl *RD,
84 const VPtrInfo *Info);
86 llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override;
88 getAddrOfCXXCatchHandlerType(QualType Ty, QualType CatchHandlerType) override;
90 bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override;
91 void EmitBadTypeidCall(CodeGenFunction &CGF) override;
92 llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
94 llvm::Type *StdTypeInfoPtrTy) override;
96 bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
97 QualType SrcRecordTy) override;
99 llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, llvm::Value *Value,
100 QualType SrcRecordTy, QualType DestTy,
101 QualType DestRecordTy,
102 llvm::BasicBlock *CastEnd) override;
104 llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, llvm::Value *Value,
105 QualType SrcRecordTy,
106 QualType DestTy) override;
108 bool EmitBadCastCall(CodeGenFunction &CGF) override;
111 GetVirtualBaseClassOffset(CodeGenFunction &CGF, llvm::Value *This,
112 const CXXRecordDecl *ClassDecl,
113 const CXXRecordDecl *BaseClassDecl) override;
116 EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
117 const CXXRecordDecl *RD) override;
119 void initializeHiddenVirtualInheritanceMembers(CodeGenFunction &CGF,
120 const CXXRecordDecl *RD) override;
122 void EmitCXXConstructors(const CXXConstructorDecl *D) override;
124 // Background on MSVC destructors
125 // ==============================
127 // Both Itanium and MSVC ABIs have destructor variants. The variant names
128 // roughly correspond in the following way:
130 // Base -> no name, just ~Class
131 // Complete -> vbase destructor
132 // Deleting -> scalar deleting destructor
133 // vector deleting destructor
135 // The base and complete destructors are the same as in Itanium, although the
136 // complete destructor does not accept a VTT parameter when there are virtual
137 // bases. A separate mechanism involving vtordisps is used to ensure that
138 // virtual methods of destroyed subobjects are not called.
140 // The deleting destructors accept an i32 bitfield as a second parameter. Bit
141 // 1 indicates if the memory should be deleted. Bit 2 indicates if the this
142 // pointer points to an array. The scalar deleting destructor assumes that
143 // bit 2 is zero, and therefore does not contain a loop.
145 // For virtual destructors, only one entry is reserved in the vftable, and it
146 // always points to the vector deleting destructor. The vector deleting
147 // destructor is the most general, so it can be used to destroy objects in
148 // place, delete single heap objects, or delete arrays.
150 // A TU defining a non-inline destructor is only guaranteed to emit a base
151 // destructor, and all of the other variants are emitted on an as-needed basis
152 // in COMDATs. Because a non-base destructor can be emitted in a TU that
153 // lacks a definition for the destructor, non-base destructors must always
154 // delegate to or alias the base destructor.
156 void buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
157 SmallVectorImpl<CanQualType> &ArgTys) override;
159 /// Non-base dtors should be emitted as delegating thunks in this ABI.
160 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
161 CXXDtorType DT) const override {
162 return DT != Dtor_Base;
165 void EmitCXXDestructors(const CXXDestructorDecl *D) override;
167 const CXXRecordDecl *
168 getThisArgumentTypeForMethod(const CXXMethodDecl *MD) override {
169 MD = MD->getCanonicalDecl();
170 if (MD->isVirtual() && !isa<CXXDestructorDecl>(MD)) {
171 MicrosoftVTableContext::MethodVFTableLocation ML =
172 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(MD);
173 // The vbases might be ordered differently in the final overrider object
174 // and the complete object, so the "this" argument may sometimes point to
175 // memory that has no particular type (e.g. past the complete object).
176 // In this case, we just use a generic pointer type.
177 // FIXME: might want to have a more precise type in the non-virtual
178 // multiple inheritance case.
179 if (ML.VBase || !ML.VFPtrOffset.isZero())
182 return MD->getParent();
186 adjustThisArgumentForVirtualFunctionCall(CodeGenFunction &CGF, GlobalDecl GD,
188 bool VirtualCall) override;
190 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
191 FunctionArgList &Params) override;
193 llvm::Value *adjustThisParameterInVirtualFunctionPrologue(
194 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) override;
196 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
198 unsigned addImplicitConstructorArgs(CodeGenFunction &CGF,
199 const CXXConstructorDecl *D,
200 CXXCtorType Type, bool ForVirtualBase,
202 CallArgList &Args) override;
204 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
205 CXXDtorType Type, bool ForVirtualBase,
206 bool Delegating, llvm::Value *This) override;
208 void emitVTableDefinitions(CodeGenVTables &CGVT,
209 const CXXRecordDecl *RD) override;
211 llvm::Value *getVTableAddressPointInStructor(
212 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
213 BaseSubobject Base, const CXXRecordDecl *NearestVBase,
214 bool &NeedsVirtualOffset) override;
217 getVTableAddressPointForConstExpr(BaseSubobject Base,
218 const CXXRecordDecl *VTableClass) override;
220 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
221 CharUnits VPtrOffset) override;
223 llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
225 llvm::Type *Ty) override;
227 llvm::Value *EmitVirtualDestructorCall(CodeGenFunction &CGF,
228 const CXXDestructorDecl *Dtor,
229 CXXDtorType DtorType,
231 const CXXMemberCallExpr *CE) override;
233 void adjustCallArgsForDestructorThunk(CodeGenFunction &CGF, GlobalDecl GD,
234 CallArgList &CallArgs) override {
235 assert(GD.getDtorType() == Dtor_Deleting &&
236 "Only deleting destructor thunks are available in this ABI");
237 CallArgs.add(RValue::get(getStructorImplicitParamValue(CGF)),
241 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
243 llvm::GlobalVariable *
244 getAddrOfVBTable(const VPtrInfo &VBT, const CXXRecordDecl *RD,
245 llvm::GlobalVariable::LinkageTypes Linkage);
247 void emitVBTableDefinition(const VPtrInfo &VBT, const CXXRecordDecl *RD,
248 llvm::GlobalVariable *GV) const;
250 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable,
251 GlobalDecl GD, bool ReturnAdjustment) override {
252 // Never dllimport/dllexport thunks.
253 Thunk->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
256 getContext().GetGVALinkageForFunction(cast<FunctionDecl>(GD.getDecl()));
258 if (Linkage == GVA_Internal)
259 Thunk->setLinkage(llvm::GlobalValue::InternalLinkage);
260 else if (ReturnAdjustment)
261 Thunk->setLinkage(llvm::GlobalValue::WeakODRLinkage);
263 Thunk->setLinkage(llvm::GlobalValue::LinkOnceODRLinkage);
266 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, llvm::Value *This,
267 const ThisAdjustment &TA) override;
269 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
270 const ReturnAdjustment &RA) override;
272 void EmitThreadLocalInitFuncs(
274 ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *>>
276 ArrayRef<llvm::Function *> CXXThreadLocalInits,
277 ArrayRef<llvm::GlobalVariable *> CXXThreadLocalInitVars) override;
279 bool usesThreadWrapperFunction() const override { return false; }
280 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
281 QualType LValType) override;
283 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
284 llvm::GlobalVariable *DeclPtr,
285 bool PerformInit) override;
286 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
287 llvm::Constant *Dtor, llvm::Constant *Addr) override;
289 // ==== Notes on array cookies =========
291 // MSVC seems to only use cookies when the class has a destructor; a
292 // two-argument usual array deallocation function isn't sufficient.
294 // For example, this code prints "100" and "1":
297 // void *operator new[](size_t sz) {
298 // printf("%u\n", sz);
299 // return malloc(sz);
301 // void operator delete[](void *p, size_t sz) {
302 // printf("%u\n", sz);
307 // A *p = new A[100];
310 // Whereas it prints "104" and "104" if you give A a destructor.
312 bool requiresArrayCookie(const CXXDeleteExpr *expr,
313 QualType elementType) override;
314 bool requiresArrayCookie(const CXXNewExpr *expr) override;
315 CharUnits getArrayCookieSizeImpl(QualType type) override;
316 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
318 llvm::Value *NumElements,
319 const CXXNewExpr *expr,
320 QualType ElementType) override;
321 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
322 llvm::Value *allocPtr,
323 CharUnits cookieSize) override;
325 friend struct MSRTTIBuilder;
327 bool isImageRelative() const {
328 return CGM.getTarget().getPointerWidth(/*AddressSpace=*/0) == 64;
331 // 5 routines for constructing the llvm types for MS RTTI structs.
332 llvm::StructType *getTypeDescriptorType(StringRef TypeInfoString) {
333 llvm::SmallString<32> TDTypeName("rtti.TypeDescriptor");
334 TDTypeName += llvm::utostr(TypeInfoString.size());
335 llvm::StructType *&TypeDescriptorType =
336 TypeDescriptorTypeMap[TypeInfoString.size()];
337 if (TypeDescriptorType)
338 return TypeDescriptorType;
339 llvm::Type *FieldTypes[] = {
342 llvm::ArrayType::get(CGM.Int8Ty, TypeInfoString.size() + 1)};
344 llvm::StructType::create(CGM.getLLVMContext(), FieldTypes, TDTypeName);
345 return TypeDescriptorType;
348 llvm::Type *getImageRelativeType(llvm::Type *PtrType) {
349 if (!isImageRelative())
354 llvm::StructType *getBaseClassDescriptorType() {
355 if (BaseClassDescriptorType)
356 return BaseClassDescriptorType;
357 llvm::Type *FieldTypes[] = {
358 getImageRelativeType(CGM.Int8PtrTy),
364 getImageRelativeType(getClassHierarchyDescriptorType()->getPointerTo()),
366 BaseClassDescriptorType = llvm::StructType::create(
367 CGM.getLLVMContext(), FieldTypes, "rtti.BaseClassDescriptor");
368 return BaseClassDescriptorType;
371 llvm::StructType *getClassHierarchyDescriptorType() {
372 if (ClassHierarchyDescriptorType)
373 return ClassHierarchyDescriptorType;
374 // Forward-declare RTTIClassHierarchyDescriptor to break a cycle.
375 ClassHierarchyDescriptorType = llvm::StructType::create(
376 CGM.getLLVMContext(), "rtti.ClassHierarchyDescriptor");
377 llvm::Type *FieldTypes[] = {
381 getImageRelativeType(
382 getBaseClassDescriptorType()->getPointerTo()->getPointerTo()),
384 ClassHierarchyDescriptorType->setBody(FieldTypes);
385 return ClassHierarchyDescriptorType;
388 llvm::StructType *getCompleteObjectLocatorType() {
389 if (CompleteObjectLocatorType)
390 return CompleteObjectLocatorType;
391 CompleteObjectLocatorType = llvm::StructType::create(
392 CGM.getLLVMContext(), "rtti.CompleteObjectLocator");
393 llvm::Type *FieldTypes[] = {
397 getImageRelativeType(CGM.Int8PtrTy),
398 getImageRelativeType(getClassHierarchyDescriptorType()->getPointerTo()),
399 getImageRelativeType(CompleteObjectLocatorType),
401 llvm::ArrayRef<llvm::Type *> FieldTypesRef(FieldTypes);
402 if (!isImageRelative())
403 FieldTypesRef = FieldTypesRef.drop_back();
404 CompleteObjectLocatorType->setBody(FieldTypesRef);
405 return CompleteObjectLocatorType;
408 llvm::GlobalVariable *getImageBase() {
409 StringRef Name = "__ImageBase";
410 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name))
413 return new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty,
415 llvm::GlobalValue::ExternalLinkage,
416 /*Initializer=*/nullptr, Name);
419 llvm::Constant *getImageRelativeConstant(llvm::Constant *PtrVal) {
420 if (!isImageRelative())
423 if (PtrVal->isNullValue())
424 return llvm::Constant::getNullValue(CGM.IntTy);
426 llvm::Constant *ImageBaseAsInt =
427 llvm::ConstantExpr::getPtrToInt(getImageBase(), CGM.IntPtrTy);
428 llvm::Constant *PtrValAsInt =
429 llvm::ConstantExpr::getPtrToInt(PtrVal, CGM.IntPtrTy);
430 llvm::Constant *Diff =
431 llvm::ConstantExpr::getSub(PtrValAsInt, ImageBaseAsInt,
432 /*HasNUW=*/true, /*HasNSW=*/true);
433 return llvm::ConstantExpr::getTrunc(Diff, CGM.IntTy);
437 MicrosoftMangleContext &getMangleContext() {
438 return cast<MicrosoftMangleContext>(CodeGen::CGCXXABI::getMangleContext());
441 llvm::Constant *getZeroInt() {
442 return llvm::ConstantInt::get(CGM.IntTy, 0);
445 llvm::Constant *getAllOnesInt() {
446 return llvm::Constant::getAllOnesValue(CGM.IntTy);
449 llvm::Constant *getConstantOrZeroInt(llvm::Constant *C) {
450 return C ? C : getZeroInt();
453 llvm::Value *getValueOrZeroInt(llvm::Value *C) {
454 return C ? C : getZeroInt();
457 CharUnits getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD);
460 GetNullMemberPointerFields(const MemberPointerType *MPT,
461 llvm::SmallVectorImpl<llvm::Constant *> &fields);
463 /// \brief Shared code for virtual base adjustment. Returns the offset from
464 /// the vbptr to the virtual base. Optionally returns the address of the
466 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
468 llvm::Value *VBPtrOffset,
469 llvm::Value *VBTableOffset,
470 llvm::Value **VBPtr = nullptr);
472 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
475 int32_t VBTableOffset,
476 llvm::Value **VBPtr = nullptr) {
477 assert(VBTableOffset % 4 == 0 && "should be byte offset into table of i32s");
478 llvm::Value *VBPOffset = llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset),
479 *VBTOffset = llvm::ConstantInt::get(CGM.IntTy, VBTableOffset);
480 return GetVBaseOffsetFromVBPtr(CGF, Base, VBPOffset, VBTOffset, VBPtr);
483 std::pair<llvm::Value *, llvm::Value *>
484 performBaseAdjustment(CodeGenFunction &CGF, llvm::Value *Value,
485 QualType SrcRecordTy);
487 /// \brief Performs a full virtual base adjustment. Used to dereference
488 /// pointers to members of virtual bases.
489 llvm::Value *AdjustVirtualBase(CodeGenFunction &CGF, const Expr *E,
490 const CXXRecordDecl *RD, llvm::Value *Base,
491 llvm::Value *VirtualBaseAdjustmentOffset,
492 llvm::Value *VBPtrOffset /* optional */);
494 /// \brief Emits a full member pointer with the fields common to data and
495 /// function member pointers.
496 llvm::Constant *EmitFullMemberPointer(llvm::Constant *FirstField,
497 bool IsMemberFunction,
498 const CXXRecordDecl *RD,
499 CharUnits NonVirtualBaseAdjustment);
501 llvm::Constant *BuildMemberPointer(const CXXRecordDecl *RD,
502 const CXXMethodDecl *MD,
503 CharUnits NonVirtualBaseAdjustment);
505 bool MemberPointerConstantIsNull(const MemberPointerType *MPT,
508 /// \brief - Initialize all vbptrs of 'this' with RD as the complete type.
509 void EmitVBPtrStores(CodeGenFunction &CGF, const CXXRecordDecl *RD);
511 /// \brief Caching wrapper around VBTableBuilder::enumerateVBTables().
512 const VBTableGlobals &enumerateVBTables(const CXXRecordDecl *RD);
514 /// \brief Generate a thunk for calling a virtual member function MD.
515 llvm::Function *EmitVirtualMemPtrThunk(
516 const CXXMethodDecl *MD,
517 const MicrosoftVTableContext::MethodVFTableLocation &ML);
520 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override;
522 bool isZeroInitializable(const MemberPointerType *MPT) override;
524 bool isMemberPointerConvertible(const MemberPointerType *MPT) const override {
525 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
526 return RD->hasAttr<MSInheritanceAttr>();
529 bool isTypeInfoCalculable(QualType Ty) const override {
530 if (!CGCXXABI::isTypeInfoCalculable(Ty))
532 if (const auto *MPT = Ty->getAs<MemberPointerType>()) {
533 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
534 if (!RD->hasAttr<MSInheritanceAttr>())
540 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override;
542 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
543 CharUnits offset) override;
544 llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD) override;
545 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override;
547 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
550 const MemberPointerType *MPT,
551 bool Inequality) override;
553 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
555 const MemberPointerType *MPT) override;
558 EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
559 llvm::Value *Base, llvm::Value *MemPtr,
560 const MemberPointerType *MPT) override;
562 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
564 llvm::Value *Src) override;
566 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
567 llvm::Constant *Src) override;
570 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF, const Expr *E,
571 llvm::Value *&This, llvm::Value *MemPtr,
572 const MemberPointerType *MPT) override;
574 void emitCXXStructor(const CXXMethodDecl *MD, StructorType Type) override;
576 llvm::StructType *getCatchHandlerTypeType() {
577 if (!CatchHandlerTypeType) {
578 llvm::Type *FieldTypes[] = {
580 CGM.Int8PtrTy, // TypeDescriptor
582 CatchHandlerTypeType = llvm::StructType::create(
583 CGM.getLLVMContext(), FieldTypes, "eh.CatchHandlerType");
585 return CatchHandlerTypeType;
588 llvm::StructType *getCatchableTypeType() {
589 if (CatchableTypeType)
590 return CatchableTypeType;
591 llvm::Type *FieldTypes[] = {
593 getImageRelativeType(CGM.Int8PtrTy), // TypeDescriptor
594 CGM.IntTy, // NonVirtualAdjustment
595 CGM.IntTy, // OffsetToVBPtr
596 CGM.IntTy, // VBTableIndex
598 getImageRelativeType(CGM.Int8PtrTy) // CopyCtor
600 CatchableTypeType = llvm::StructType::create(
601 CGM.getLLVMContext(), FieldTypes, "eh.CatchableType");
602 return CatchableTypeType;
605 llvm::StructType *getCatchableTypeArrayType(uint32_t NumEntries) {
606 llvm::StructType *&CatchableTypeArrayType =
607 CatchableTypeArrayTypeMap[NumEntries];
608 if (CatchableTypeArrayType)
609 return CatchableTypeArrayType;
611 llvm::SmallString<23> CTATypeName("eh.CatchableTypeArray.");
612 CTATypeName += llvm::utostr(NumEntries);
614 getImageRelativeType(getCatchableTypeType()->getPointerTo());
615 llvm::Type *FieldTypes[] = {
616 CGM.IntTy, // NumEntries
617 llvm::ArrayType::get(CTType, NumEntries) // CatchableTypes
619 CatchableTypeArrayType =
620 llvm::StructType::create(CGM.getLLVMContext(), FieldTypes, CTATypeName);
621 return CatchableTypeArrayType;
624 llvm::StructType *getThrowInfoType() {
626 return ThrowInfoType;
627 llvm::Type *FieldTypes[] = {
629 getImageRelativeType(CGM.Int8PtrTy), // CleanupFn
630 getImageRelativeType(CGM.Int8PtrTy), // ForwardCompat
631 getImageRelativeType(CGM.Int8PtrTy) // CatchableTypeArray
633 ThrowInfoType = llvm::StructType::create(CGM.getLLVMContext(), FieldTypes,
635 return ThrowInfoType;
638 llvm::Constant *getThrowFn() {
639 // _CxxThrowException is passed an exception object and a ThrowInfo object
640 // which describes the exception.
641 llvm::Type *Args[] = {CGM.Int8PtrTy, getThrowInfoType()->getPointerTo()};
642 llvm::FunctionType *FTy =
643 llvm::FunctionType::get(CGM.VoidTy, Args, /*IsVarArgs=*/false);
644 auto *Fn = cast<llvm::Function>(
645 CGM.CreateRuntimeFunction(FTy, "_CxxThrowException"));
646 // _CxxThrowException is stdcall on 32-bit x86 platforms.
647 if (CGM.getTarget().getTriple().getArch() == llvm::Triple::x86)
648 Fn->setCallingConv(llvm::CallingConv::X86_StdCall);
652 llvm::Function *getAddrOfCXXCtorClosure(const CXXConstructorDecl *CD,
655 llvm::Constant *getCatchableType(QualType T,
656 uint32_t NVOffset = 0,
657 int32_t VBPtrOffset = -1,
658 uint32_t VBIndex = 0);
660 llvm::GlobalVariable *getCatchableTypeArray(QualType T);
662 llvm::GlobalVariable *getThrowInfo(QualType T) override;
665 typedef std::pair<const CXXRecordDecl *, CharUnits> VFTableIdTy;
666 typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalVariable *> VTablesMapTy;
667 typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalValue *> VFTablesMapTy;
668 /// \brief All the vftables that have been referenced.
669 VFTablesMapTy VFTablesMap;
670 VTablesMapTy VTablesMap;
672 /// \brief This set holds the record decls we've deferred vtable emission for.
673 llvm::SmallPtrSet<const CXXRecordDecl *, 4> DeferredVFTables;
676 /// \brief All the vbtables which have been referenced.
677 llvm::DenseMap<const CXXRecordDecl *, VBTableGlobals> VBTablesMap;
679 /// Info on the global variable used to guard initialization of static locals.
680 /// The BitIndex field is only used for externally invisible declarations.
682 GuardInfo() : Guard(nullptr), BitIndex(0) {}
683 llvm::GlobalVariable *Guard;
687 /// Map from DeclContext to the current guard variable. We assume that the
688 /// AST is visited in source code order.
689 llvm::DenseMap<const DeclContext *, GuardInfo> GuardVariableMap;
691 llvm::DenseMap<size_t, llvm::StructType *> TypeDescriptorTypeMap;
692 llvm::StructType *BaseClassDescriptorType;
693 llvm::StructType *ClassHierarchyDescriptorType;
694 llvm::StructType *CompleteObjectLocatorType;
696 llvm::DenseMap<QualType, llvm::GlobalVariable *> CatchableTypeArrays;
698 llvm::StructType *CatchableTypeType;
699 llvm::DenseMap<uint32_t, llvm::StructType *> CatchableTypeArrayTypeMap;
700 llvm::StructType *ThrowInfoType;
701 llvm::StructType *CatchHandlerTypeType;
706 CGCXXABI::RecordArgABI
707 MicrosoftCXXABI::getRecordArgABI(const CXXRecordDecl *RD) const {
708 switch (CGM.getTarget().getTriple().getArch()) {
710 // FIXME: Implement for other architectures.
713 case llvm::Triple::x86:
714 // All record arguments are passed in memory on x86. Decide whether to
715 // construct the object directly in argument memory, or to construct the
716 // argument elsewhere and copy the bytes during the call.
718 // If C++ prohibits us from making a copy, construct the arguments directly
719 // into argument memory.
720 if (!canCopyArgument(RD))
721 return RAA_DirectInMemory;
723 // Otherwise, construct the argument into a temporary and copy the bytes
724 // into the outgoing argument memory.
727 case llvm::Triple::x86_64:
728 // Win64 passes objects with non-trivial copy ctors indirectly.
729 if (RD->hasNonTrivialCopyConstructor())
732 // If an object has a destructor, we'd really like to pass it indirectly
733 // because it allows us to elide copies. Unfortunately, MSVC makes that
734 // impossible for small types, which it will pass in a single register or
735 // stack slot. Most objects with dtors are large-ish, so handle that early.
736 // We can't call out all large objects as being indirect because there are
737 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
738 // how we pass large POD types.
739 if (RD->hasNonTrivialDestructor() &&
740 getContext().getTypeSize(RD->getTypeForDecl()) > 64)
743 // We have a trivial copy constructor or no copy constructors, but we have
744 // to make sure it isn't deleted.
745 bool CopyDeleted = false;
746 for (const CXXConstructorDecl *CD : RD->ctors()) {
747 if (CD->isCopyConstructor()) {
748 assert(CD->isTrivial());
749 // We had at least one undeleted trivial copy ctor. Return directly.
750 if (!CD->isDeleted())
756 // The trivial copy constructor was deleted. Return indirectly.
760 // There were no copy ctors. Return in RAX.
764 llvm_unreachable("invalid enum");
767 void MicrosoftCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
768 const CXXDeleteExpr *DE,
770 QualType ElementType,
771 const CXXDestructorDecl *Dtor) {
772 // FIXME: Provide a source location here even though there's no
773 // CXXMemberCallExpr for dtor call.
774 bool UseGlobalDelete = DE->isGlobalDelete();
775 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
776 llvm::Value *MDThis =
777 EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, /*CE=*/nullptr);
779 CGF.EmitDeleteCall(DE->getOperatorDelete(), MDThis, ElementType);
782 void MicrosoftCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
783 llvm::Value *Args[] = {
784 llvm::ConstantPointerNull::get(CGM.Int8PtrTy),
785 llvm::ConstantPointerNull::get(getThrowInfoType()->getPointerTo())};
786 auto *Fn = getThrowFn();
788 CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, Args);
790 CGF.EmitRuntimeCallOrInvoke(Fn, Args);
794 struct CallEndCatchMSVC : EHScopeStack::Cleanup {
795 CallEndCatchMSVC() {}
796 void Emit(CodeGenFunction &CGF, Flags flags) override {
797 CGF.EmitNounwindRuntimeCall(
798 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_endcatch));
803 void MicrosoftCXXABI::emitBeginCatch(CodeGenFunction &CGF,
804 const CXXCatchStmt *S) {
805 // In the MS ABI, the runtime handles the copy, and the catch handler is
806 // responsible for destruction.
807 VarDecl *CatchParam = S->getExceptionDecl();
808 llvm::Value *Exn = CGF.getExceptionFromSlot();
809 llvm::Function *BeginCatch =
810 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_begincatch);
812 // If this is a catch-all or the catch parameter is unnamed, we don't need to
813 // emit an alloca to the object.
814 if (!CatchParam || !CatchParam->getDeclName()) {
815 llvm::Value *Args[2] = {Exn, llvm::Constant::getNullValue(CGF.Int8PtrTy)};
816 CGF.EmitNounwindRuntimeCall(BeginCatch, Args);
817 CGF.EHStack.pushCleanup<CallEndCatchMSVC>(NormalCleanup);
821 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
822 llvm::Value *ParamAddr =
823 CGF.Builder.CreateBitCast(var.getObjectAddress(CGF), CGF.Int8PtrTy);
824 llvm::Value *Args[2] = {Exn, ParamAddr};
825 CGF.EmitNounwindRuntimeCall(BeginCatch, Args);
826 CGF.EHStack.pushCleanup<CallEndCatchMSVC>(NormalCleanup);
827 CGF.EmitAutoVarCleanups(var);
830 std::pair<llvm::Value *, llvm::Value *>
831 MicrosoftCXXABI::performBaseAdjustment(CodeGenFunction &CGF, llvm::Value *Value,
832 QualType SrcRecordTy) {
833 Value = CGF.Builder.CreateBitCast(Value, CGF.Int8PtrTy);
834 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
835 const ASTContext &Context = getContext();
837 if (Context.getASTRecordLayout(SrcDecl).hasExtendableVFPtr())
838 return std::make_pair(Value, llvm::ConstantInt::get(CGF.Int32Ty, 0));
840 // Perform a base adjustment.
841 const CXXBaseSpecifier *PolymorphicBase = std::find_if(
842 SrcDecl->vbases_begin(), SrcDecl->vbases_end(),
843 [&](const CXXBaseSpecifier &Base) {
844 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
845 return Context.getASTRecordLayout(BaseDecl).hasExtendableVFPtr();
847 llvm::Value *Offset = GetVirtualBaseClassOffset(
848 CGF, Value, SrcDecl, PolymorphicBase->getType()->getAsCXXRecordDecl());
849 Value = CGF.Builder.CreateInBoundsGEP(Value, Offset);
850 Offset = CGF.Builder.CreateTrunc(Offset, CGF.Int32Ty);
851 return std::make_pair(Value, Offset);
854 bool MicrosoftCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
855 QualType SrcRecordTy) {
856 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
858 !getContext().getASTRecordLayout(SrcDecl).hasExtendableVFPtr();
861 static llvm::CallSite emitRTtypeidCall(CodeGenFunction &CGF,
862 llvm::Value *Argument) {
863 llvm::Type *ArgTypes[] = {CGF.Int8PtrTy};
864 llvm::FunctionType *FTy =
865 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false);
866 llvm::Value *Args[] = {Argument};
867 llvm::Constant *Fn = CGF.CGM.CreateRuntimeFunction(FTy, "__RTtypeid");
868 return CGF.EmitRuntimeCallOrInvoke(Fn, Args);
871 void MicrosoftCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
872 llvm::CallSite Call =
873 emitRTtypeidCall(CGF, llvm::Constant::getNullValue(CGM.VoidPtrTy));
874 Call.setDoesNotReturn();
875 CGF.Builder.CreateUnreachable();
878 llvm::Value *MicrosoftCXXABI::EmitTypeid(CodeGenFunction &CGF,
879 QualType SrcRecordTy,
880 llvm::Value *ThisPtr,
881 llvm::Type *StdTypeInfoPtrTy) {
883 std::tie(ThisPtr, Offset) = performBaseAdjustment(CGF, ThisPtr, SrcRecordTy);
884 return CGF.Builder.CreateBitCast(
885 emitRTtypeidCall(CGF, ThisPtr).getInstruction(), StdTypeInfoPtrTy);
888 bool MicrosoftCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
889 QualType SrcRecordTy) {
890 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
892 !getContext().getASTRecordLayout(SrcDecl).hasExtendableVFPtr();
895 llvm::Value *MicrosoftCXXABI::EmitDynamicCastCall(
896 CodeGenFunction &CGF, llvm::Value *Value, QualType SrcRecordTy,
897 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
898 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
900 llvm::Value *SrcRTTI =
901 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
902 llvm::Value *DestRTTI =
903 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
906 std::tie(Value, Offset) = performBaseAdjustment(CGF, Value, SrcRecordTy);
908 // PVOID __RTDynamicCast(
914 llvm::Type *ArgTypes[] = {CGF.Int8PtrTy, CGF.Int32Ty, CGF.Int8PtrTy,
915 CGF.Int8PtrTy, CGF.Int32Ty};
916 llvm::Constant *Function = CGF.CGM.CreateRuntimeFunction(
917 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false),
919 llvm::Value *Args[] = {
920 Value, Offset, SrcRTTI, DestRTTI,
921 llvm::ConstantInt::get(CGF.Int32Ty, DestTy->isReferenceType())};
922 Value = CGF.EmitRuntimeCallOrInvoke(Function, Args).getInstruction();
923 return CGF.Builder.CreateBitCast(Value, DestLTy);
927 MicrosoftCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF, llvm::Value *Value,
928 QualType SrcRecordTy,
931 std::tie(Value, Offset) = performBaseAdjustment(CGF, Value, SrcRecordTy);
933 // PVOID __RTCastToVoid(
935 llvm::Type *ArgTypes[] = {CGF.Int8PtrTy};
936 llvm::Constant *Function = CGF.CGM.CreateRuntimeFunction(
937 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false),
939 llvm::Value *Args[] = {Value};
940 return CGF.EmitRuntimeCall(Function, Args);
943 bool MicrosoftCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
947 llvm::Value *MicrosoftCXXABI::GetVirtualBaseClassOffset(
948 CodeGenFunction &CGF, llvm::Value *This, const CXXRecordDecl *ClassDecl,
949 const CXXRecordDecl *BaseClassDecl) {
950 const ASTContext &Context = getContext();
952 Context.getASTRecordLayout(ClassDecl).getVBPtrOffset().getQuantity();
953 llvm::Value *VBPtrOffset = llvm::ConstantInt::get(CGM.PtrDiffTy, VBPtrChars);
954 CharUnits IntSize = Context.getTypeSizeInChars(Context.IntTy);
955 CharUnits VBTableChars =
957 CGM.getMicrosoftVTableContext().getVBTableIndex(ClassDecl, BaseClassDecl);
958 llvm::Value *VBTableOffset =
959 llvm::ConstantInt::get(CGM.IntTy, VBTableChars.getQuantity());
961 llvm::Value *VBPtrToNewBase =
962 GetVBaseOffsetFromVBPtr(CGF, This, VBPtrOffset, VBTableOffset);
964 CGF.Builder.CreateSExtOrBitCast(VBPtrToNewBase, CGM.PtrDiffTy);
965 return CGF.Builder.CreateNSWAdd(VBPtrOffset, VBPtrToNewBase);
968 bool MicrosoftCXXABI::HasThisReturn(GlobalDecl GD) const {
969 return isa<CXXConstructorDecl>(GD.getDecl());
972 static bool isDeletingDtor(GlobalDecl GD) {
973 return isa<CXXDestructorDecl>(GD.getDecl()) &&
974 GD.getDtorType() == Dtor_Deleting;
977 bool MicrosoftCXXABI::hasMostDerivedReturn(GlobalDecl GD) const {
978 return isDeletingDtor(GD);
981 bool MicrosoftCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
982 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
986 if (FI.isInstanceMethod()) {
987 // If it's an instance method, aggregates are always returned indirectly via
988 // the second parameter.
989 FI.getReturnInfo() = ABIArgInfo::getIndirect(0, /*ByVal=*/false);
990 FI.getReturnInfo().setSRetAfterThis(FI.isInstanceMethod());
992 } else if (!RD->isPOD()) {
993 // If it's a free function, non-POD types are returned indirectly.
994 FI.getReturnInfo() = ABIArgInfo::getIndirect(0, /*ByVal=*/false);
998 // Otherwise, use the C ABI rules.
1003 MicrosoftCXXABI::EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
1004 const CXXRecordDecl *RD) {
1005 llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);
1006 assert(IsMostDerivedClass &&
1007 "ctor for a class with virtual bases must have an implicit parameter");
1008 llvm::Value *IsCompleteObject =
1009 CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");
1011 llvm::BasicBlock *CallVbaseCtorsBB = CGF.createBasicBlock("ctor.init_vbases");
1012 llvm::BasicBlock *SkipVbaseCtorsBB = CGF.createBasicBlock("ctor.skip_vbases");
1013 CGF.Builder.CreateCondBr(IsCompleteObject,
1014 CallVbaseCtorsBB, SkipVbaseCtorsBB);
1016 CGF.EmitBlock(CallVbaseCtorsBB);
1018 // Fill in the vbtable pointers here.
1019 EmitVBPtrStores(CGF, RD);
1021 // CGF will put the base ctor calls in this basic block for us later.
1023 return SkipVbaseCtorsBB;
1026 void MicrosoftCXXABI::initializeHiddenVirtualInheritanceMembers(
1027 CodeGenFunction &CGF, const CXXRecordDecl *RD) {
1028 // In most cases, an override for a vbase virtual method can adjust
1029 // the "this" parameter by applying a constant offset.
1030 // However, this is not enough while a constructor or a destructor of some
1031 // class X is being executed if all the following conditions are met:
1032 // - X has virtual bases, (1)
1033 // - X overrides a virtual method M of a vbase Y, (2)
1034 // - X itself is a vbase of the most derived class.
1036 // If (1) and (2) are true, the vtorDisp for vbase Y is a hidden member of X
1037 // which holds the extra amount of "this" adjustment we must do when we use
1038 // the X vftables (i.e. during X ctor or dtor).
1039 // Outside the ctors and dtors, the values of vtorDisps are zero.
1041 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1042 typedef ASTRecordLayout::VBaseOffsetsMapTy VBOffsets;
1043 const VBOffsets &VBaseMap = Layout.getVBaseOffsetsMap();
1044 CGBuilderTy &Builder = CGF.Builder;
1047 cast<llvm::PointerType>(getThisValue(CGF)->getType())->getAddressSpace();
1048 llvm::Value *Int8This = nullptr; // Initialize lazily.
1050 for (VBOffsets::const_iterator I = VBaseMap.begin(), E = VBaseMap.end();
1052 if (!I->second.hasVtorDisp())
1055 llvm::Value *VBaseOffset =
1056 GetVirtualBaseClassOffset(CGF, getThisValue(CGF), RD, I->first);
1057 // FIXME: it doesn't look right that we SExt in GetVirtualBaseClassOffset()
1058 // just to Trunc back immediately.
1059 VBaseOffset = Builder.CreateTruncOrBitCast(VBaseOffset, CGF.Int32Ty);
1060 uint64_t ConstantVBaseOffset =
1061 Layout.getVBaseClassOffset(I->first).getQuantity();
1063 // vtorDisp_for_vbase = vbptr[vbase_idx] - offsetof(RD, vbase).
1064 llvm::Value *VtorDispValue = Builder.CreateSub(
1065 VBaseOffset, llvm::ConstantInt::get(CGM.Int32Ty, ConstantVBaseOffset),
1069 Int8This = Builder.CreateBitCast(getThisValue(CGF),
1070 CGF.Int8Ty->getPointerTo(AS));
1071 llvm::Value *VtorDispPtr = Builder.CreateInBoundsGEP(Int8This, VBaseOffset);
1072 // vtorDisp is always the 32-bits before the vbase in the class layout.
1073 VtorDispPtr = Builder.CreateConstGEP1_32(VtorDispPtr, -4);
1074 VtorDispPtr = Builder.CreateBitCast(
1075 VtorDispPtr, CGF.Int32Ty->getPointerTo(AS), "vtordisp.ptr");
1077 Builder.CreateStore(VtorDispValue, VtorDispPtr);
1081 static bool hasDefaultCXXMethodCC(ASTContext &Context,
1082 const CXXMethodDecl *MD) {
1083 CallingConv ExpectedCallingConv = Context.getDefaultCallingConvention(
1084 /*IsVariadic=*/false, /*IsCXXMethod=*/true);
1085 CallingConv ActualCallingConv =
1086 MD->getType()->getAs<FunctionProtoType>()->getCallConv();
1087 return ExpectedCallingConv == ActualCallingConv;
1090 void MicrosoftCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1091 // There's only one constructor type in this ABI.
1092 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1094 // Exported default constructors either have a simple call-site where they use
1095 // the typical calling convention and have a single 'this' pointer for an
1096 // argument -or- they get a wrapper function which appropriately thunks to the
1097 // real default constructor. This thunk is the default constructor closure.
1098 if (D->hasAttr<DLLExportAttr>() && D->isDefaultConstructor())
1099 if (!hasDefaultCXXMethodCC(getContext(), D) || D->getNumParams() != 0) {
1100 llvm::Function *Fn = getAddrOfCXXCtorClosure(D, Ctor_DefaultClosure);
1101 Fn->setLinkage(llvm::GlobalValue::WeakODRLinkage);
1102 Fn->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1106 void MicrosoftCXXABI::EmitVBPtrStores(CodeGenFunction &CGF,
1107 const CXXRecordDecl *RD) {
1108 llvm::Value *ThisInt8Ptr =
1109 CGF.Builder.CreateBitCast(getThisValue(CGF), CGM.Int8PtrTy, "this.int8");
1110 const ASTContext &Context = getContext();
1111 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1113 const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
1114 for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) {
1115 const VPtrInfo *VBT = (*VBGlobals.VBTables)[I];
1116 llvm::GlobalVariable *GV = VBGlobals.Globals[I];
1117 const ASTRecordLayout &SubobjectLayout =
1118 Context.getASTRecordLayout(VBT->BaseWithVPtr);
1119 CharUnits Offs = VBT->NonVirtualOffset;
1120 Offs += SubobjectLayout.getVBPtrOffset();
1121 if (VBT->getVBaseWithVPtr())
1122 Offs += Layout.getVBaseClassOffset(VBT->getVBaseWithVPtr());
1123 llvm::Value *VBPtr =
1124 CGF.Builder.CreateConstInBoundsGEP1_64(ThisInt8Ptr, Offs.getQuantity());
1125 llvm::Value *GVPtr =
1126 CGF.Builder.CreateConstInBoundsGEP2_32(GV->getValueType(), GV, 0, 0);
1127 VBPtr = CGF.Builder.CreateBitCast(VBPtr, GVPtr->getType()->getPointerTo(0),
1128 "vbptr." + VBT->ReusingBase->getName());
1129 CGF.Builder.CreateStore(GVPtr, VBPtr);
1134 MicrosoftCXXABI::buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
1135 SmallVectorImpl<CanQualType> &ArgTys) {
1136 // TODO: 'for base' flag
1137 if (T == StructorType::Deleting) {
1138 // The scalar deleting destructor takes an implicit int parameter.
1139 ArgTys.push_back(getContext().IntTy);
1141 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
1145 // All parameters are already in place except is_most_derived, which goes
1146 // after 'this' if it's variadic and last if it's not.
1148 const CXXRecordDecl *Class = CD->getParent();
1149 const FunctionProtoType *FPT = CD->getType()->castAs<FunctionProtoType>();
1150 if (Class->getNumVBases()) {
1151 if (FPT->isVariadic())
1152 ArgTys.insert(ArgTys.begin() + 1, getContext().IntTy);
1154 ArgTys.push_back(getContext().IntTy);
1158 void MicrosoftCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
1159 // The TU defining a dtor is only guaranteed to emit a base destructor. All
1160 // other destructor variants are delegating thunks.
1161 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
1165 MicrosoftCXXABI::getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD) {
1166 GD = GD.getCanonicalDecl();
1167 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1169 GlobalDecl LookupGD = GD;
1170 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1171 // Complete destructors take a pointer to the complete object as a
1172 // parameter, thus don't need this adjustment.
1173 if (GD.getDtorType() == Dtor_Complete)
1176 // There's no Dtor_Base in vftable but it shares the this adjustment with
1177 // the deleting one, so look it up instead.
1178 LookupGD = GlobalDecl(DD, Dtor_Deleting);
1181 MicrosoftVTableContext::MethodVFTableLocation ML =
1182 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD);
1183 CharUnits Adjustment = ML.VFPtrOffset;
1185 // Normal virtual instance methods need to adjust from the vfptr that first
1186 // defined the virtual method to the virtual base subobject, but destructors
1187 // do not. The vector deleting destructor thunk applies this adjustment for
1189 if (isa<CXXDestructorDecl>(MD))
1190 Adjustment = CharUnits::Zero();
1193 const ASTRecordLayout &DerivedLayout =
1194 getContext().getASTRecordLayout(MD->getParent());
1195 Adjustment += DerivedLayout.getVBaseClassOffset(ML.VBase);
1201 llvm::Value *MicrosoftCXXABI::adjustThisArgumentForVirtualFunctionCall(
1202 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This, bool VirtualCall) {
1204 // If the call of a virtual function is not virtual, we just have to
1205 // compensate for the adjustment the virtual function does in its prologue.
1206 CharUnits Adjustment = getVirtualFunctionPrologueThisAdjustment(GD);
1207 if (Adjustment.isZero())
1210 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
1211 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS);
1212 This = CGF.Builder.CreateBitCast(This, charPtrTy);
1213 assert(Adjustment.isPositive());
1214 return CGF.Builder.CreateConstGEP1_32(This, Adjustment.getQuantity());
1217 GD = GD.getCanonicalDecl();
1218 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1220 GlobalDecl LookupGD = GD;
1221 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1222 // Complete dtors take a pointer to the complete object,
1223 // thus don't need adjustment.
1224 if (GD.getDtorType() == Dtor_Complete)
1227 // There's only Dtor_Deleting in vftable but it shares the this adjustment
1228 // with the base one, so look up the deleting one instead.
1229 LookupGD = GlobalDecl(DD, Dtor_Deleting);
1231 MicrosoftVTableContext::MethodVFTableLocation ML =
1232 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD);
1234 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
1235 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS);
1236 CharUnits StaticOffset = ML.VFPtrOffset;
1238 // Base destructors expect 'this' to point to the beginning of the base
1239 // subobject, not the first vfptr that happens to contain the virtual dtor.
1240 // However, we still need to apply the virtual base adjustment.
1241 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
1242 StaticOffset = CharUnits::Zero();
1245 This = CGF.Builder.CreateBitCast(This, charPtrTy);
1246 llvm::Value *VBaseOffset =
1247 GetVirtualBaseClassOffset(CGF, This, MD->getParent(), ML.VBase);
1248 This = CGF.Builder.CreateInBoundsGEP(This, VBaseOffset);
1250 if (!StaticOffset.isZero()) {
1251 assert(StaticOffset.isPositive());
1252 This = CGF.Builder.CreateBitCast(This, charPtrTy);
1254 // Non-virtual adjustment might result in a pointer outside the allocated
1255 // object, e.g. if the final overrider class is laid out after the virtual
1256 // base that declares a method in the most derived class.
1257 // FIXME: Update the code that emits this adjustment in thunks prologues.
1258 This = CGF.Builder.CreateConstGEP1_32(This, StaticOffset.getQuantity());
1260 This = CGF.Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, This,
1261 StaticOffset.getQuantity());
1267 void MicrosoftCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1269 FunctionArgList &Params) {
1270 ASTContext &Context = getContext();
1271 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
1272 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
1273 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
1274 ImplicitParamDecl *IsMostDerived
1275 = ImplicitParamDecl::Create(Context, nullptr,
1276 CGF.CurGD.getDecl()->getLocation(),
1277 &Context.Idents.get("is_most_derived"),
1279 // The 'most_derived' parameter goes second if the ctor is variadic and last
1280 // if it's not. Dtors can't be variadic.
1281 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
1282 if (FPT->isVariadic())
1283 Params.insert(Params.begin() + 1, IsMostDerived);
1285 Params.push_back(IsMostDerived);
1286 getStructorImplicitParamDecl(CGF) = IsMostDerived;
1287 } else if (isDeletingDtor(CGF.CurGD)) {
1288 ImplicitParamDecl *ShouldDelete
1289 = ImplicitParamDecl::Create(Context, nullptr,
1290 CGF.CurGD.getDecl()->getLocation(),
1291 &Context.Idents.get("should_call_delete"),
1293 Params.push_back(ShouldDelete);
1294 getStructorImplicitParamDecl(CGF) = ShouldDelete;
1298 llvm::Value *MicrosoftCXXABI::adjustThisParameterInVirtualFunctionPrologue(
1299 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) {
1300 // In this ABI, every virtual function takes a pointer to one of the
1301 // subobjects that first defines it as the 'this' parameter, rather than a
1302 // pointer to the final overrider subobject. Thus, we need to adjust it back
1303 // to the final overrider subobject before use.
1304 // See comments in the MicrosoftVFTableContext implementation for the details.
1305 CharUnits Adjustment = getVirtualFunctionPrologueThisAdjustment(GD);
1306 if (Adjustment.isZero())
1309 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
1310 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS),
1311 *thisTy = This->getType();
1313 This = CGF.Builder.CreateBitCast(This, charPtrTy);
1314 assert(Adjustment.isPositive());
1315 This = CGF.Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, This,
1316 -Adjustment.getQuantity());
1317 return CGF.Builder.CreateBitCast(This, thisTy);
1320 void MicrosoftCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
1323 /// If this is a function that the ABI specifies returns 'this', initialize
1324 /// the return slot to 'this' at the start of the function.
1326 /// Unlike the setting of return types, this is done within the ABI
1327 /// implementation instead of by clients of CGCXXABI because:
1328 /// 1) getThisValue is currently protected
1329 /// 2) in theory, an ABI could implement 'this' returns some other way;
1330 /// HasThisReturn only specifies a contract, not the implementation
1331 if (HasThisReturn(CGF.CurGD))
1332 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
1333 else if (hasMostDerivedReturn(CGF.CurGD))
1334 CGF.Builder.CreateStore(CGF.EmitCastToVoidPtr(getThisValue(CGF)),
1337 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
1338 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
1339 assert(getStructorImplicitParamDecl(CGF) &&
1340 "no implicit parameter for a constructor with virtual bases?");
1341 getStructorImplicitParamValue(CGF)
1342 = CGF.Builder.CreateLoad(
1343 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
1347 if (isDeletingDtor(CGF.CurGD)) {
1348 assert(getStructorImplicitParamDecl(CGF) &&
1349 "no implicit parameter for a deleting destructor?");
1350 getStructorImplicitParamValue(CGF)
1351 = CGF.Builder.CreateLoad(
1352 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
1353 "should_call_delete");
1357 unsigned MicrosoftCXXABI::addImplicitConstructorArgs(
1358 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1359 bool ForVirtualBase, bool Delegating, CallArgList &Args) {
1360 assert(Type == Ctor_Complete || Type == Ctor_Base);
1362 // Check if we need a 'most_derived' parameter.
1363 if (!D->getParent()->getNumVBases())
1366 // Add the 'most_derived' argument second if we are variadic or last if not.
1367 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
1368 llvm::Value *MostDerivedArg =
1369 llvm::ConstantInt::get(CGM.Int32Ty, Type == Ctor_Complete);
1370 RValue RV = RValue::get(MostDerivedArg);
1371 if (MostDerivedArg) {
1372 if (FPT->isVariadic())
1373 Args.insert(Args.begin() + 1,
1374 CallArg(RV, getContext().IntTy, /*needscopy=*/false));
1376 Args.add(RV, getContext().IntTy);
1379 return 1; // Added one arg.
1382 void MicrosoftCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1383 const CXXDestructorDecl *DD,
1384 CXXDtorType Type, bool ForVirtualBase,
1385 bool Delegating, llvm::Value *This) {
1386 llvm::Value *Callee = CGM.getAddrOfCXXStructor(DD, getFromDtorType(Type));
1388 if (DD->isVirtual()) {
1389 assert(Type != CXXDtorType::Dtor_Deleting &&
1390 "The deleting destructor should only be called via a virtual call");
1391 This = adjustThisArgumentForVirtualFunctionCall(CGF, GlobalDecl(DD, Type),
1395 CGF.EmitCXXStructorCall(DD, Callee, ReturnValueSlot(), This,
1396 /*ImplicitParam=*/nullptr,
1397 /*ImplicitParamTy=*/QualType(), nullptr,
1398 getFromDtorType(Type));
1401 void MicrosoftCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1402 const CXXRecordDecl *RD) {
1403 MicrosoftVTableContext &VFTContext = CGM.getMicrosoftVTableContext();
1404 const VPtrInfoVector &VFPtrs = VFTContext.getVFPtrOffsets(RD);
1406 for (VPtrInfo *Info : VFPtrs) {
1407 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, Info->FullOffsetInMDC);
1408 if (VTable->hasInitializer())
1411 llvm::Constant *RTTI = getContext().getLangOpts().RTTIData
1412 ? getMSCompleteObjectLocator(RD, Info)
1415 const VTableLayout &VTLayout =
1416 VFTContext.getVFTableLayout(RD, Info->FullOffsetInMDC);
1417 llvm::Constant *Init = CGVT.CreateVTableInitializer(
1418 RD, VTLayout.vtable_component_begin(),
1419 VTLayout.getNumVTableComponents(), VTLayout.vtable_thunk_begin(),
1420 VTLayout.getNumVTableThunks(), RTTI);
1422 VTable->setInitializer(Init);
1426 llvm::Value *MicrosoftCXXABI::getVTableAddressPointInStructor(
1427 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1428 const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) {
1429 NeedsVirtualOffset = (NearestVBase != nullptr);
1431 (void)getAddrOfVTable(VTableClass, Base.getBaseOffset());
1432 VFTableIdTy ID(VTableClass, Base.getBaseOffset());
1433 llvm::GlobalValue *VTableAddressPoint = VFTablesMap[ID];
1434 if (!VTableAddressPoint) {
1435 assert(Base.getBase()->getNumVBases() &&
1436 !getContext().getASTRecordLayout(Base.getBase()).hasOwnVFPtr());
1438 return VTableAddressPoint;
1441 static void mangleVFTableName(MicrosoftMangleContext &MangleContext,
1442 const CXXRecordDecl *RD, const VPtrInfo *VFPtr,
1443 SmallString<256> &Name) {
1444 llvm::raw_svector_ostream Out(Name);
1445 MangleContext.mangleCXXVFTable(RD, VFPtr->MangledPath, Out);
1448 llvm::Constant *MicrosoftCXXABI::getVTableAddressPointForConstExpr(
1449 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1450 (void)getAddrOfVTable(VTableClass, Base.getBaseOffset());
1451 VFTableIdTy ID(VTableClass, Base.getBaseOffset());
1452 llvm::GlobalValue *VFTable = VFTablesMap[ID];
1453 assert(VFTable && "Couldn't find a vftable for the given base?");
1457 llvm::GlobalVariable *MicrosoftCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1458 CharUnits VPtrOffset) {
1459 // getAddrOfVTable may return 0 if asked to get an address of a vtable which
1460 // shouldn't be used in the given record type. We want to cache this result in
1461 // VFTablesMap, thus a simple zero check is not sufficient.
1462 VFTableIdTy ID(RD, VPtrOffset);
1463 VTablesMapTy::iterator I;
1465 std::tie(I, Inserted) = VTablesMap.insert(std::make_pair(ID, nullptr));
1469 llvm::GlobalVariable *&VTable = I->second;
1471 MicrosoftVTableContext &VTContext = CGM.getMicrosoftVTableContext();
1472 const VPtrInfoVector &VFPtrs = VTContext.getVFPtrOffsets(RD);
1474 if (DeferredVFTables.insert(RD).second) {
1475 // We haven't processed this record type before.
1476 // Queue up this v-table for possible deferred emission.
1477 CGM.addDeferredVTable(RD);
1480 // Create all the vftables at once in order to make sure each vftable has
1481 // a unique mangled name.
1482 llvm::StringSet<> ObservedMangledNames;
1483 for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) {
1484 SmallString<256> Name;
1485 mangleVFTableName(getMangleContext(), RD, VFPtrs[J], Name);
1486 if (!ObservedMangledNames.insert(Name.str()).second)
1487 llvm_unreachable("Already saw this mangling before?");
1492 VPtrInfo *const *VFPtrI =
1493 std::find_if(VFPtrs.begin(), VFPtrs.end(), [&](VPtrInfo *VPI) {
1494 return VPI->FullOffsetInMDC == VPtrOffset;
1496 if (VFPtrI == VFPtrs.end()) {
1497 VFTablesMap[ID] = nullptr;
1500 VPtrInfo *VFPtr = *VFPtrI;
1502 SmallString<256> VFTableName;
1503 mangleVFTableName(getMangleContext(), RD, VFPtr, VFTableName);
1505 llvm::GlobalValue::LinkageTypes VFTableLinkage = CGM.getVTableLinkage(RD);
1506 bool VFTableComesFromAnotherTU =
1507 llvm::GlobalValue::isAvailableExternallyLinkage(VFTableLinkage) ||
1508 llvm::GlobalValue::isExternalLinkage(VFTableLinkage);
1509 bool VTableAliasIsRequred =
1510 !VFTableComesFromAnotherTU && getContext().getLangOpts().RTTIData;
1512 if (llvm::GlobalValue *VFTable =
1513 CGM.getModule().getNamedGlobal(VFTableName)) {
1514 VFTablesMap[ID] = VFTable;
1515 return VTableAliasIsRequred
1516 ? cast<llvm::GlobalVariable>(
1517 cast<llvm::GlobalAlias>(VFTable)->getBaseObject())
1518 : cast<llvm::GlobalVariable>(VFTable);
1521 uint64_t NumVTableSlots =
1522 VTContext.getVFTableLayout(RD, VFPtr->FullOffsetInMDC)
1523 .getNumVTableComponents();
1524 llvm::GlobalValue::LinkageTypes VTableLinkage =
1525 VTableAliasIsRequred ? llvm::GlobalValue::PrivateLinkage : VFTableLinkage;
1527 StringRef VTableName = VTableAliasIsRequred ? StringRef() : VFTableName.str();
1529 llvm::ArrayType *VTableType =
1530 llvm::ArrayType::get(CGM.Int8PtrTy, NumVTableSlots);
1532 // Create a backing variable for the contents of VTable. The VTable may
1533 // or may not include space for a pointer to RTTI data.
1534 llvm::GlobalValue *VFTable;
1535 VTable = new llvm::GlobalVariable(CGM.getModule(), VTableType,
1536 /*isConstant=*/true, VTableLinkage,
1537 /*Initializer=*/nullptr, VTableName);
1538 VTable->setUnnamedAddr(true);
1540 llvm::Comdat *C = nullptr;
1541 if (!VFTableComesFromAnotherTU &&
1542 (llvm::GlobalValue::isWeakForLinker(VFTableLinkage) ||
1543 (llvm::GlobalValue::isLocalLinkage(VFTableLinkage) &&
1544 VTableAliasIsRequred)))
1545 C = CGM.getModule().getOrInsertComdat(VFTableName.str());
1547 // Only insert a pointer into the VFTable for RTTI data if we are not
1548 // importing it. We never reference the RTTI data directly so there is no
1549 // need to make room for it.
1550 if (VTableAliasIsRequred) {
1551 llvm::Value *GEPIndices[] = {llvm::ConstantInt::get(CGM.IntTy, 0),
1552 llvm::ConstantInt::get(CGM.IntTy, 1)};
1553 // Create a GEP which points just after the first entry in the VFTable,
1554 // this should be the location of the first virtual method.
1555 llvm::Constant *VTableGEP = llvm::ConstantExpr::getInBoundsGetElementPtr(
1556 VTable->getValueType(), VTable, GEPIndices);
1557 if (llvm::GlobalValue::isWeakForLinker(VFTableLinkage)) {
1558 VFTableLinkage = llvm::GlobalValue::ExternalLinkage;
1560 C->setSelectionKind(llvm::Comdat::Largest);
1562 VFTable = llvm::GlobalAlias::create(
1563 cast<llvm::PointerType>(VTableGEP->getType()), VFTableLinkage,
1564 VFTableName.str(), VTableGEP, &CGM.getModule());
1565 VFTable->setUnnamedAddr(true);
1567 // We don't need a GlobalAlias to be a symbol for the VTable if we won't
1568 // be referencing any RTTI data.
1569 // The GlobalVariable will end up being an appropriate definition of the
1574 VTable->setComdat(C);
1576 if (RD->hasAttr<DLLImportAttr>())
1577 VFTable->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1578 else if (RD->hasAttr<DLLExportAttr>())
1579 VFTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1581 VFTablesMap[ID] = VFTable;
1585 llvm::Value *MicrosoftCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1589 GD = GD.getCanonicalDecl();
1590 CGBuilderTy &Builder = CGF.Builder;
1592 Ty = Ty->getPointerTo()->getPointerTo();
1594 adjustThisArgumentForVirtualFunctionCall(CGF, GD, This, true);
1595 llvm::Value *VTable = CGF.GetVTablePtr(VPtr, Ty);
1597 MicrosoftVTableContext::MethodVFTableLocation ML =
1598 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD);
1599 llvm::Value *VFuncPtr =
1600 Builder.CreateConstInBoundsGEP1_64(VTable, ML.Index, "vfn");
1601 return Builder.CreateLoad(VFuncPtr);
1604 llvm::Value *MicrosoftCXXABI::EmitVirtualDestructorCall(
1605 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
1606 llvm::Value *This, const CXXMemberCallExpr *CE) {
1607 assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
1608 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1610 // We have only one destructor in the vftable but can get both behaviors
1611 // by passing an implicit int parameter.
1612 GlobalDecl GD(Dtor, Dtor_Deleting);
1613 const CGFunctionInfo *FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
1614 Dtor, StructorType::Deleting);
1615 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
1616 llvm::Value *Callee = getVirtualFunctionPointer(CGF, GD, This, Ty);
1618 ASTContext &Context = getContext();
1619 llvm::Value *ImplicitParam = llvm::ConstantInt::get(
1620 llvm::IntegerType::getInt32Ty(CGF.getLLVMContext()),
1621 DtorType == Dtor_Deleting);
1623 This = adjustThisArgumentForVirtualFunctionCall(CGF, GD, This, true);
1624 RValue RV = CGF.EmitCXXStructorCall(Dtor, Callee, ReturnValueSlot(), This,
1625 ImplicitParam, Context.IntTy, CE,
1626 StructorType::Deleting);
1627 return RV.getScalarVal();
1630 const VBTableGlobals &
1631 MicrosoftCXXABI::enumerateVBTables(const CXXRecordDecl *RD) {
1632 // At this layer, we can key the cache off of a single class, which is much
1633 // easier than caching each vbtable individually.
1634 llvm::DenseMap<const CXXRecordDecl*, VBTableGlobals>::iterator Entry;
1636 std::tie(Entry, Added) =
1637 VBTablesMap.insert(std::make_pair(RD, VBTableGlobals()));
1638 VBTableGlobals &VBGlobals = Entry->second;
1642 MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext();
1643 VBGlobals.VBTables = &Context.enumerateVBTables(RD);
1645 // Cache the globals for all vbtables so we don't have to recompute the
1647 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
1648 for (VPtrInfoVector::const_iterator I = VBGlobals.VBTables->begin(),
1649 E = VBGlobals.VBTables->end();
1651 VBGlobals.Globals.push_back(getAddrOfVBTable(**I, RD, Linkage));
1657 llvm::Function *MicrosoftCXXABI::EmitVirtualMemPtrThunk(
1658 const CXXMethodDecl *MD,
1659 const MicrosoftVTableContext::MethodVFTableLocation &ML) {
1660 assert(!isa<CXXConstructorDecl>(MD) && !isa<CXXDestructorDecl>(MD) &&
1661 "can't form pointers to ctors or virtual dtors");
1663 // Calculate the mangled name.
1664 SmallString<256> ThunkName;
1665 llvm::raw_svector_ostream Out(ThunkName);
1666 getMangleContext().mangleVirtualMemPtrThunk(MD, Out);
1669 // If the thunk has been generated previously, just return it.
1670 if (llvm::GlobalValue *GV = CGM.getModule().getNamedValue(ThunkName))
1671 return cast<llvm::Function>(GV);
1673 // Create the llvm::Function.
1674 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeMSMemberPointerThunk(MD);
1675 llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo);
1676 llvm::Function *ThunkFn =
1677 llvm::Function::Create(ThunkTy, llvm::Function::ExternalLinkage,
1678 ThunkName.str(), &CGM.getModule());
1679 assert(ThunkFn->getName() == ThunkName && "name was uniqued!");
1681 ThunkFn->setLinkage(MD->isExternallyVisible()
1682 ? llvm::GlobalValue::LinkOnceODRLinkage
1683 : llvm::GlobalValue::InternalLinkage);
1684 if (MD->isExternallyVisible())
1685 ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));
1687 CGM.SetLLVMFunctionAttributes(MD, FnInfo, ThunkFn);
1688 CGM.SetLLVMFunctionAttributesForDefinition(MD, ThunkFn);
1690 // Add the "thunk" attribute so that LLVM knows that the return type is
1691 // meaningless. These thunks can be used to call functions with differing
1692 // return types, and the caller is required to cast the prototype
1693 // appropriately to extract the correct value.
1694 ThunkFn->addFnAttr("thunk");
1696 // These thunks can be compared, so they are not unnamed.
1697 ThunkFn->setUnnamedAddr(false);
1700 CodeGenFunction CGF(CGM);
1701 CGF.CurGD = GlobalDecl(MD);
1702 CGF.CurFuncIsThunk = true;
1704 // Build FunctionArgs, but only include the implicit 'this' parameter
1706 FunctionArgList FunctionArgs;
1707 buildThisParam(CGF, FunctionArgs);
1709 // Start defining the function.
1710 CGF.StartFunction(GlobalDecl(), FnInfo.getReturnType(), ThunkFn, FnInfo,
1711 FunctionArgs, MD->getLocation(), SourceLocation());
1714 // Load the vfptr and then callee from the vftable. The callee should have
1715 // adjusted 'this' so that the vfptr is at offset zero.
1716 llvm::Value *VTable = CGF.GetVTablePtr(
1717 getThisValue(CGF), ThunkTy->getPointerTo()->getPointerTo());
1718 llvm::Value *VFuncPtr =
1719 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, ML.Index, "vfn");
1720 llvm::Value *Callee = CGF.Builder.CreateLoad(VFuncPtr);
1722 CGF.EmitMustTailThunk(MD, getThisValue(CGF), Callee);
1727 void MicrosoftCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
1728 const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
1729 for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) {
1730 const VPtrInfo *VBT = (*VBGlobals.VBTables)[I];
1731 llvm::GlobalVariable *GV = VBGlobals.Globals[I];
1732 if (GV->isDeclaration())
1733 emitVBTableDefinition(*VBT, RD, GV);
1737 llvm::GlobalVariable *
1738 MicrosoftCXXABI::getAddrOfVBTable(const VPtrInfo &VBT, const CXXRecordDecl *RD,
1739 llvm::GlobalVariable::LinkageTypes Linkage) {
1740 SmallString<256> OutName;
1741 llvm::raw_svector_ostream Out(OutName);
1742 getMangleContext().mangleCXXVBTable(RD, VBT.MangledPath, Out);
1744 StringRef Name = OutName.str();
1746 llvm::ArrayType *VBTableType =
1747 llvm::ArrayType::get(CGM.IntTy, 1 + VBT.ReusingBase->getNumVBases());
1749 assert(!CGM.getModule().getNamedGlobal(Name) &&
1750 "vbtable with this name already exists: mangling bug?");
1751 llvm::GlobalVariable *GV =
1752 CGM.CreateOrReplaceCXXRuntimeVariable(Name, VBTableType, Linkage);
1753 GV->setUnnamedAddr(true);
1755 if (RD->hasAttr<DLLImportAttr>())
1756 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1757 else if (RD->hasAttr<DLLExportAttr>())
1758 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1760 if (!GV->hasExternalLinkage())
1761 emitVBTableDefinition(VBT, RD, GV);
1766 void MicrosoftCXXABI::emitVBTableDefinition(const VPtrInfo &VBT,
1767 const CXXRecordDecl *RD,
1768 llvm::GlobalVariable *GV) const {
1769 const CXXRecordDecl *ReusingBase = VBT.ReusingBase;
1771 assert(RD->getNumVBases() && ReusingBase->getNumVBases() &&
1772 "should only emit vbtables for classes with vbtables");
1774 const ASTRecordLayout &BaseLayout =
1775 getContext().getASTRecordLayout(VBT.BaseWithVPtr);
1776 const ASTRecordLayout &DerivedLayout = getContext().getASTRecordLayout(RD);
1778 SmallVector<llvm::Constant *, 4> Offsets(1 + ReusingBase->getNumVBases(),
1781 // The offset from ReusingBase's vbptr to itself always leads.
1782 CharUnits VBPtrOffset = BaseLayout.getVBPtrOffset();
1783 Offsets[0] = llvm::ConstantInt::get(CGM.IntTy, -VBPtrOffset.getQuantity());
1785 MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext();
1786 for (const auto &I : ReusingBase->vbases()) {
1787 const CXXRecordDecl *VBase = I.getType()->getAsCXXRecordDecl();
1788 CharUnits Offset = DerivedLayout.getVBaseClassOffset(VBase);
1789 assert(!Offset.isNegative());
1791 // Make it relative to the subobject vbptr.
1792 CharUnits CompleteVBPtrOffset = VBT.NonVirtualOffset + VBPtrOffset;
1793 if (VBT.getVBaseWithVPtr())
1794 CompleteVBPtrOffset +=
1795 DerivedLayout.getVBaseClassOffset(VBT.getVBaseWithVPtr());
1796 Offset -= CompleteVBPtrOffset;
1798 unsigned VBIndex = Context.getVBTableIndex(ReusingBase, VBase);
1799 assert(Offsets[VBIndex] == nullptr && "The same vbindex seen twice?");
1800 Offsets[VBIndex] = llvm::ConstantInt::get(CGM.IntTy, Offset.getQuantity());
1803 assert(Offsets.size() ==
1804 cast<llvm::ArrayType>(cast<llvm::PointerType>(GV->getType())
1805 ->getElementType())->getNumElements());
1806 llvm::ArrayType *VBTableType =
1807 llvm::ArrayType::get(CGM.IntTy, Offsets.size());
1808 llvm::Constant *Init = llvm::ConstantArray::get(VBTableType, Offsets);
1809 GV->setInitializer(Init);
1812 llvm::Value *MicrosoftCXXABI::performThisAdjustment(CodeGenFunction &CGF,
1814 const ThisAdjustment &TA) {
1818 llvm::Value *V = CGF.Builder.CreateBitCast(This, CGF.Int8PtrTy);
1820 if (!TA.Virtual.isEmpty()) {
1821 assert(TA.Virtual.Microsoft.VtordispOffset < 0);
1822 // Adjust the this argument based on the vtordisp value.
1823 llvm::Value *VtorDispPtr =
1824 CGF.Builder.CreateConstGEP1_32(V, TA.Virtual.Microsoft.VtordispOffset);
1826 CGF.Builder.CreateBitCast(VtorDispPtr, CGF.Int32Ty->getPointerTo());
1827 llvm::Value *VtorDisp = CGF.Builder.CreateLoad(VtorDispPtr, "vtordisp");
1828 V = CGF.Builder.CreateGEP(V, CGF.Builder.CreateNeg(VtorDisp));
1830 if (TA.Virtual.Microsoft.VBPtrOffset) {
1831 // If the final overrider is defined in a virtual base other than the one
1832 // that holds the vfptr, we have to use a vtordispex thunk which looks up
1833 // the vbtable of the derived class.
1834 assert(TA.Virtual.Microsoft.VBPtrOffset > 0);
1835 assert(TA.Virtual.Microsoft.VBOffsetOffset >= 0);
1837 llvm::Value *VBaseOffset =
1838 GetVBaseOffsetFromVBPtr(CGF, V, -TA.Virtual.Microsoft.VBPtrOffset,
1839 TA.Virtual.Microsoft.VBOffsetOffset, &VBPtr);
1840 V = CGF.Builder.CreateInBoundsGEP(VBPtr, VBaseOffset);
1844 if (TA.NonVirtual) {
1845 // Non-virtual adjustment might result in a pointer outside the allocated
1846 // object, e.g. if the final overrider class is laid out after the virtual
1847 // base that declares a method in the most derived class.
1848 V = CGF.Builder.CreateConstGEP1_32(V, TA.NonVirtual);
1851 // Don't need to bitcast back, the call CodeGen will handle this.
1856 MicrosoftCXXABI::performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
1857 const ReturnAdjustment &RA) {
1861 llvm::Value *V = CGF.Builder.CreateBitCast(Ret, CGF.Int8PtrTy);
1863 if (RA.Virtual.Microsoft.VBIndex) {
1864 assert(RA.Virtual.Microsoft.VBIndex > 0);
1865 const ASTContext &Context = getContext();
1866 int32_t IntSize = Context.getTypeSizeInChars(Context.IntTy).getQuantity();
1868 llvm::Value *VBaseOffset =
1869 GetVBaseOffsetFromVBPtr(CGF, V, RA.Virtual.Microsoft.VBPtrOffset,
1870 IntSize * RA.Virtual.Microsoft.VBIndex, &VBPtr);
1871 V = CGF.Builder.CreateInBoundsGEP(VBPtr, VBaseOffset);
1875 V = CGF.Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, V, RA.NonVirtual);
1877 // Cast back to the original type.
1878 return CGF.Builder.CreateBitCast(V, Ret->getType());
1881 bool MicrosoftCXXABI::requiresArrayCookie(const CXXDeleteExpr *expr,
1882 QualType elementType) {
1883 // Microsoft seems to completely ignore the possibility of a
1884 // two-argument usual deallocation function.
1885 return elementType.isDestructedType();
1888 bool MicrosoftCXXABI::requiresArrayCookie(const CXXNewExpr *expr) {
1889 // Microsoft seems to completely ignore the possibility of a
1890 // two-argument usual deallocation function.
1891 return expr->getAllocatedType().isDestructedType();
1894 CharUnits MicrosoftCXXABI::getArrayCookieSizeImpl(QualType type) {
1895 // The array cookie is always a size_t; we then pad that out to the
1896 // alignment of the element type.
1897 ASTContext &Ctx = getContext();
1898 return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()),
1899 Ctx.getTypeAlignInChars(type));
1902 llvm::Value *MicrosoftCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1903 llvm::Value *allocPtr,
1904 CharUnits cookieSize) {
1905 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
1906 llvm::Value *numElementsPtr =
1907 CGF.Builder.CreateBitCast(allocPtr, CGF.SizeTy->getPointerTo(AS));
1908 return CGF.Builder.CreateLoad(numElementsPtr);
1911 llvm::Value* MicrosoftCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1912 llvm::Value *newPtr,
1913 llvm::Value *numElements,
1914 const CXXNewExpr *expr,
1915 QualType elementType) {
1916 assert(requiresArrayCookie(expr));
1918 // The size of the cookie.
1919 CharUnits cookieSize = getArrayCookieSizeImpl(elementType);
1921 // Compute an offset to the cookie.
1922 llvm::Value *cookiePtr = newPtr;
1924 // Write the number of elements into the appropriate slot.
1925 unsigned AS = newPtr->getType()->getPointerAddressSpace();
1926 llvm::Value *numElementsPtr
1927 = CGF.Builder.CreateBitCast(cookiePtr, CGF.SizeTy->getPointerTo(AS));
1928 CGF.Builder.CreateStore(numElements, numElementsPtr);
1930 // Finally, compute a pointer to the actual data buffer by skipping
1931 // over the cookie completely.
1932 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
1933 cookieSize.getQuantity());
1936 static void emitGlobalDtorWithTLRegDtor(CodeGenFunction &CGF, const VarDecl &VD,
1937 llvm::Constant *Dtor,
1938 llvm::Constant *Addr) {
1939 // Create a function which calls the destructor.
1940 llvm::Constant *DtorStub = CGF.createAtExitStub(VD, Dtor, Addr);
1942 // extern "C" int __tlregdtor(void (*f)(void));
1943 llvm::FunctionType *TLRegDtorTy = llvm::FunctionType::get(
1944 CGF.IntTy, DtorStub->getType(), /*IsVarArg=*/false);
1946 llvm::Constant *TLRegDtor =
1947 CGF.CGM.CreateRuntimeFunction(TLRegDtorTy, "__tlregdtor");
1948 if (llvm::Function *TLRegDtorFn = dyn_cast<llvm::Function>(TLRegDtor))
1949 TLRegDtorFn->setDoesNotThrow();
1951 CGF.EmitNounwindRuntimeCall(TLRegDtor, DtorStub);
1954 void MicrosoftCXXABI::registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
1955 llvm::Constant *Dtor,
1956 llvm::Constant *Addr) {
1958 return emitGlobalDtorWithTLRegDtor(CGF, D, Dtor, Addr);
1960 // The default behavior is to use atexit.
1961 CGF.registerGlobalDtorWithAtExit(D, Dtor, Addr);
1964 void MicrosoftCXXABI::EmitThreadLocalInitFuncs(
1966 ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *>>
1968 ArrayRef<llvm::Function *> CXXThreadLocalInits,
1969 ArrayRef<llvm::GlobalVariable *> CXXThreadLocalInitVars) {
1970 // This will create a GV in the .CRT$XDU section. It will point to our
1971 // initialization function. The CRT will call all of these function
1972 // pointers at start-up time and, eventually, at thread-creation time.
1973 auto AddToXDU = [&CGM](llvm::Function *InitFunc) {
1974 llvm::GlobalVariable *InitFuncPtr = new llvm::GlobalVariable(
1975 CGM.getModule(), InitFunc->getType(), /*IsConstant=*/true,
1976 llvm::GlobalVariable::InternalLinkage, InitFunc,
1977 Twine(InitFunc->getName(), "$initializer$"));
1978 InitFuncPtr->setSection(".CRT$XDU");
1979 // This variable has discardable linkage, we have to add it to @llvm.used to
1980 // ensure it won't get discarded.
1981 CGM.addUsedGlobal(InitFuncPtr);
1985 std::vector<llvm::Function *> NonComdatInits;
1986 for (size_t I = 0, E = CXXThreadLocalInitVars.size(); I != E; ++I) {
1987 llvm::GlobalVariable *GV = CXXThreadLocalInitVars[I];
1988 llvm::Function *F = CXXThreadLocalInits[I];
1990 // If the GV is already in a comdat group, then we have to join it.
1991 if (llvm::Comdat *C = GV->getComdat())
1992 AddToXDU(F)->setComdat(C);
1994 NonComdatInits.push_back(F);
1997 if (!NonComdatInits.empty()) {
1998 llvm::FunctionType *FTy =
1999 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
2000 llvm::Function *InitFunc = CGM.CreateGlobalInitOrDestructFunction(
2001 FTy, "__tls_init", SourceLocation(),
2003 CodeGenFunction(CGM).GenerateCXXGlobalInitFunc(InitFunc, NonComdatInits);
2009 LValue MicrosoftCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
2011 QualType LValType) {
2012 CGF.CGM.ErrorUnsupported(VD, "thread wrappers");
2016 void MicrosoftCXXABI::EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
2017 llvm::GlobalVariable *GV,
2019 // MSVC only uses guards for static locals.
2020 if (!D.isStaticLocal()) {
2021 assert(GV->hasWeakLinkage() || GV->hasLinkOnceLinkage());
2022 // GlobalOpt is allowed to discard the initializer, so use linkonce_odr.
2023 llvm::Function *F = CGF.CurFn;
2024 F->setLinkage(llvm::GlobalValue::LinkOnceODRLinkage);
2025 F->setComdat(CGM.getModule().getOrInsertComdat(F->getName()));
2026 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
2030 // MSVC always uses an i32 bitfield to guard initialization, which is *not*
2031 // threadsafe. Since the user may be linking in inline functions compiled by
2032 // cl.exe, there's no reason to provide a false sense of security by using
2033 // critical sections here.
2036 CGM.ErrorUnsupported(&D, "dynamic TLS initialization");
2038 CGBuilderTy &Builder = CGF.Builder;
2039 llvm::IntegerType *GuardTy = CGF.Int32Ty;
2040 llvm::ConstantInt *Zero = llvm::ConstantInt::get(GuardTy, 0);
2042 // Get the guard variable for this function if we have one already.
2043 GuardInfo *GI = &GuardVariableMap[D.getDeclContext()];
2046 if (D.isStaticLocal() && D.isExternallyVisible()) {
2047 // Externally visible variables have to be numbered in Sema to properly
2048 // handle unreachable VarDecls.
2049 BitIndex = getContext().getStaticLocalNumber(&D);
2050 assert(BitIndex > 0);
2053 // Non-externally visible variables are numbered here in CodeGen.
2054 BitIndex = GI->BitIndex++;
2057 if (BitIndex >= 32) {
2058 if (D.isExternallyVisible())
2059 ErrorUnsupportedABI(CGF, "more than 32 guarded initializations");
2061 GI->Guard = nullptr;
2064 // Lazily create the i32 bitfield for this function.
2066 // Mangle the name for the guard.
2067 SmallString<256> GuardName;
2069 llvm::raw_svector_ostream Out(GuardName);
2070 getMangleContext().mangleStaticGuardVariable(&D, Out);
2074 // Create the guard variable with a zero-initializer. Just absorb linkage,
2075 // visibility and dll storage class from the guarded variable.
2077 new llvm::GlobalVariable(CGM.getModule(), GuardTy, false,
2078 GV->getLinkage(), Zero, GuardName.str());
2079 GI->Guard->setVisibility(GV->getVisibility());
2080 GI->Guard->setDLLStorageClass(GV->getDLLStorageClass());
2081 if (GI->Guard->isWeakForLinker())
2082 GI->Guard->setComdat(
2083 CGM.getModule().getOrInsertComdat(GI->Guard->getName()));
2085 assert(GI->Guard->getLinkage() == GV->getLinkage() &&
2086 "static local from the same function had different linkage");
2089 // Pseudo code for the test:
2090 // if (!(GuardVar & MyGuardBit)) {
2091 // GuardVar |= MyGuardBit;
2092 // ... initialize the object ...;
2095 // Test our bit from the guard variable.
2096 llvm::ConstantInt *Bit = llvm::ConstantInt::get(GuardTy, 1U << BitIndex);
2097 llvm::LoadInst *LI = Builder.CreateLoad(GI->Guard);
2098 llvm::Value *IsInitialized =
2099 Builder.CreateICmpNE(Builder.CreateAnd(LI, Bit), Zero);
2100 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
2101 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2102 Builder.CreateCondBr(IsInitialized, EndBlock, InitBlock);
2104 // Set our bit in the guard variable and emit the initializer and add a global
2105 // destructor if appropriate.
2106 CGF.EmitBlock(InitBlock);
2107 Builder.CreateStore(Builder.CreateOr(LI, Bit), GI->Guard);
2108 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
2109 Builder.CreateBr(EndBlock);
2112 CGF.EmitBlock(EndBlock);
2115 bool MicrosoftCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
2116 // Null-ness for function memptrs only depends on the first field, which is
2117 // the function pointer. The rest don't matter, so we can zero initialize.
2118 if (MPT->isMemberFunctionPointer())
2121 // The virtual base adjustment field is always -1 for null, so if we have one
2122 // we can't zero initialize. The field offset is sometimes also -1 if 0 is a
2123 // valid field offset.
2124 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2125 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
2126 return (!MSInheritanceAttr::hasVBTableOffsetField(Inheritance) &&
2127 RD->nullFieldOffsetIsZero());
2131 MicrosoftCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
2132 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2133 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
2134 llvm::SmallVector<llvm::Type *, 4> fields;
2135 if (MPT->isMemberFunctionPointer())
2136 fields.push_back(CGM.VoidPtrTy); // FunctionPointerOrVirtualThunk
2138 fields.push_back(CGM.IntTy); // FieldOffset
2140 if (MSInheritanceAttr::hasNVOffsetField(MPT->isMemberFunctionPointer(),
2142 fields.push_back(CGM.IntTy);
2143 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance))
2144 fields.push_back(CGM.IntTy);
2145 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance))
2146 fields.push_back(CGM.IntTy); // VirtualBaseAdjustmentOffset
2148 if (fields.size() == 1)
2150 return llvm::StructType::get(CGM.getLLVMContext(), fields);
2153 void MicrosoftCXXABI::
2154 GetNullMemberPointerFields(const MemberPointerType *MPT,
2155 llvm::SmallVectorImpl<llvm::Constant *> &fields) {
2156 assert(fields.empty());
2157 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2158 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
2159 if (MPT->isMemberFunctionPointer()) {
2160 // FunctionPointerOrVirtualThunk
2161 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
2163 if (RD->nullFieldOffsetIsZero())
2164 fields.push_back(getZeroInt()); // FieldOffset
2166 fields.push_back(getAllOnesInt()); // FieldOffset
2169 if (MSInheritanceAttr::hasNVOffsetField(MPT->isMemberFunctionPointer(),
2171 fields.push_back(getZeroInt());
2172 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance))
2173 fields.push_back(getZeroInt());
2174 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance))
2175 fields.push_back(getAllOnesInt());
2179 MicrosoftCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
2180 llvm::SmallVector<llvm::Constant *, 4> fields;
2181 GetNullMemberPointerFields(MPT, fields);
2182 if (fields.size() == 1)
2184 llvm::Constant *Res = llvm::ConstantStruct::getAnon(fields);
2185 assert(Res->getType() == ConvertMemberPointerType(MPT));
2190 MicrosoftCXXABI::EmitFullMemberPointer(llvm::Constant *FirstField,
2191 bool IsMemberFunction,
2192 const CXXRecordDecl *RD,
2193 CharUnits NonVirtualBaseAdjustment)
2195 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
2197 // Single inheritance class member pointer are represented as scalars instead
2199 if (MSInheritanceAttr::hasOnlyOneField(IsMemberFunction, Inheritance))
2202 llvm::SmallVector<llvm::Constant *, 4> fields;
2203 fields.push_back(FirstField);
2205 if (MSInheritanceAttr::hasNVOffsetField(IsMemberFunction, Inheritance))
2206 fields.push_back(llvm::ConstantInt::get(
2207 CGM.IntTy, NonVirtualBaseAdjustment.getQuantity()));
2209 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance)) {
2210 CharUnits Offs = CharUnits::Zero();
2211 if (RD->getNumVBases())
2212 Offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
2213 fields.push_back(llvm::ConstantInt::get(CGM.IntTy, Offs.getQuantity()));
2216 // The rest of the fields are adjusted by conversions to a more derived class.
2217 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance))
2218 fields.push_back(getZeroInt());
2220 return llvm::ConstantStruct::getAnon(fields);
2224 MicrosoftCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
2226 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2227 llvm::Constant *FirstField =
2228 llvm::ConstantInt::get(CGM.IntTy, offset.getQuantity());
2229 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/false, RD,
2233 llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
2234 return BuildMemberPointer(MD->getParent(), MD, CharUnits::Zero());
2237 llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const APValue &MP,
2239 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
2240 const ValueDecl *MPD = MP.getMemberPointerDecl();
2242 return EmitNullMemberPointer(MPT);
2244 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
2246 // FIXME PR15713: Support virtual inheritance paths.
2248 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
2249 return BuildMemberPointer(MPT->getMostRecentCXXRecordDecl(), MD,
2252 CharUnits FieldOffset =
2253 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
2254 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
2258 MicrosoftCXXABI::BuildMemberPointer(const CXXRecordDecl *RD,
2259 const CXXMethodDecl *MD,
2260 CharUnits NonVirtualBaseAdjustment) {
2261 assert(MD->isInstance() && "Member function must not be static!");
2262 MD = MD->getCanonicalDecl();
2263 RD = RD->getMostRecentDecl();
2264 CodeGenTypes &Types = CGM.getTypes();
2266 llvm::Constant *FirstField;
2267 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
2268 if (!MD->isVirtual()) {
2270 // Check whether the function has a computable LLVM signature.
2271 if (Types.isFuncTypeConvertible(FPT)) {
2272 // The function has a computable LLVM signature; use the correct type.
2273 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
2275 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
2276 // function type is incomplete.
2279 FirstField = CGM.GetAddrOfFunction(MD, Ty);
2280 FirstField = llvm::ConstantExpr::getBitCast(FirstField, CGM.VoidPtrTy);
2282 MicrosoftVTableContext::MethodVFTableLocation ML =
2283 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(MD);
2284 if (!CGM.getTypes().isFuncTypeConvertible(
2285 MD->getType()->castAs<FunctionType>())) {
2286 CGM.ErrorUnsupported(MD, "pointer to virtual member function with "
2287 "incomplete return or parameter type");
2288 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
2289 } else if (FPT->getCallConv() == CC_X86FastCall) {
2290 CGM.ErrorUnsupported(MD, "pointer to fastcall virtual member function");
2291 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
2292 } else if (ML.VBase) {
2293 CGM.ErrorUnsupported(MD, "pointer to virtual member function overriding "
2294 "member function in virtual base class");
2295 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
2297 llvm::Function *Thunk = EmitVirtualMemPtrThunk(MD, ML);
2298 FirstField = llvm::ConstantExpr::getBitCast(Thunk, CGM.VoidPtrTy);
2299 // Include the vfptr adjustment if the method is in a non-primary vftable.
2300 NonVirtualBaseAdjustment += ML.VFPtrOffset;
2304 // The rest of the fields are common with data member pointers.
2305 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/true, RD,
2306 NonVirtualBaseAdjustment);
2309 /// Member pointers are the same if they're either bitwise identical *or* both
2310 /// null. Null-ness for function members is determined by the first field,
2311 /// while for data member pointers we must compare all fields.
2313 MicrosoftCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
2316 const MemberPointerType *MPT,
2318 CGBuilderTy &Builder = CGF.Builder;
2320 // Handle != comparisons by switching the sense of all boolean operations.
2321 llvm::ICmpInst::Predicate Eq;
2322 llvm::Instruction::BinaryOps And, Or;
2324 Eq = llvm::ICmpInst::ICMP_NE;
2325 And = llvm::Instruction::Or;
2326 Or = llvm::Instruction::And;
2328 Eq = llvm::ICmpInst::ICMP_EQ;
2329 And = llvm::Instruction::And;
2330 Or = llvm::Instruction::Or;
2333 // If this is a single field member pointer (single inheritance), this is a
2335 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2336 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
2337 if (MSInheritanceAttr::hasOnlyOneField(MPT->isMemberFunctionPointer(),
2339 return Builder.CreateICmp(Eq, L, R);
2341 // Compare the first field.
2342 llvm::Value *L0 = Builder.CreateExtractValue(L, 0, "lhs.0");
2343 llvm::Value *R0 = Builder.CreateExtractValue(R, 0, "rhs.0");
2344 llvm::Value *Cmp0 = Builder.CreateICmp(Eq, L0, R0, "memptr.cmp.first");
2346 // Compare everything other than the first field.
2347 llvm::Value *Res = nullptr;
2348 llvm::StructType *LType = cast<llvm::StructType>(L->getType());
2349 for (unsigned I = 1, E = LType->getNumElements(); I != E; ++I) {
2350 llvm::Value *LF = Builder.CreateExtractValue(L, I);
2351 llvm::Value *RF = Builder.CreateExtractValue(R, I);
2352 llvm::Value *Cmp = Builder.CreateICmp(Eq, LF, RF, "memptr.cmp.rest");
2354 Res = Builder.CreateBinOp(And, Res, Cmp);
2359 // Check if the first field is 0 if this is a function pointer.
2360 if (MPT->isMemberFunctionPointer()) {
2361 // (l1 == r1 && ...) || l0 == 0
2362 llvm::Value *Zero = llvm::Constant::getNullValue(L0->getType());
2363 llvm::Value *IsZero = Builder.CreateICmp(Eq, L0, Zero, "memptr.cmp.iszero");
2364 Res = Builder.CreateBinOp(Or, Res, IsZero);
2367 // Combine the comparison of the first field, which must always be true for
2368 // this comparison to succeeed.
2369 return Builder.CreateBinOp(And, Res, Cmp0, "memptr.cmp");
2373 MicrosoftCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
2374 llvm::Value *MemPtr,
2375 const MemberPointerType *MPT) {
2376 CGBuilderTy &Builder = CGF.Builder;
2377 llvm::SmallVector<llvm::Constant *, 4> fields;
2378 // We only need one field for member functions.
2379 if (MPT->isMemberFunctionPointer())
2380 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
2382 GetNullMemberPointerFields(MPT, fields);
2383 assert(!fields.empty());
2384 llvm::Value *FirstField = MemPtr;
2385 if (MemPtr->getType()->isStructTy())
2386 FirstField = Builder.CreateExtractValue(MemPtr, 0);
2387 llvm::Value *Res = Builder.CreateICmpNE(FirstField, fields[0], "memptr.cmp0");
2389 // For function member pointers, we only need to test the function pointer
2390 // field. The other fields if any can be garbage.
2391 if (MPT->isMemberFunctionPointer())
2394 // Otherwise, emit a series of compares and combine the results.
2395 for (int I = 1, E = fields.size(); I < E; ++I) {
2396 llvm::Value *Field = Builder.CreateExtractValue(MemPtr, I);
2397 llvm::Value *Next = Builder.CreateICmpNE(Field, fields[I], "memptr.cmp");
2398 Res = Builder.CreateOr(Res, Next, "memptr.tobool");
2403 bool MicrosoftCXXABI::MemberPointerConstantIsNull(const MemberPointerType *MPT,
2404 llvm::Constant *Val) {
2405 // Function pointers are null if the pointer in the first field is null.
2406 if (MPT->isMemberFunctionPointer()) {
2407 llvm::Constant *FirstField = Val->getType()->isStructTy() ?
2408 Val->getAggregateElement(0U) : Val;
2409 return FirstField->isNullValue();
2412 // If it's not a function pointer and it's zero initializable, we can easily
2414 if (isZeroInitializable(MPT) && Val->isNullValue())
2417 // Otherwise, break down all the fields for comparison. Hopefully these
2418 // little Constants are reused, while a big null struct might not be.
2419 llvm::SmallVector<llvm::Constant *, 4> Fields;
2420 GetNullMemberPointerFields(MPT, Fields);
2421 if (Fields.size() == 1) {
2422 assert(Val->getType()->isIntegerTy());
2423 return Val == Fields[0];
2427 for (I = 0, E = Fields.size(); I != E; ++I) {
2428 if (Val->getAggregateElement(I) != Fields[I])
2435 MicrosoftCXXABI::GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
2437 llvm::Value *VBPtrOffset,
2438 llvm::Value *VBTableOffset,
2439 llvm::Value **VBPtrOut) {
2440 CGBuilderTy &Builder = CGF.Builder;
2441 // Load the vbtable pointer from the vbptr in the instance.
2442 This = Builder.CreateBitCast(This, CGM.Int8PtrTy);
2443 llvm::Value *VBPtr =
2444 Builder.CreateInBoundsGEP(This, VBPtrOffset, "vbptr");
2445 if (VBPtrOut) *VBPtrOut = VBPtr;
2446 VBPtr = Builder.CreateBitCast(VBPtr,
2447 CGM.Int32Ty->getPointerTo(0)->getPointerTo(0));
2448 llvm::Value *VBTable = Builder.CreateLoad(VBPtr, "vbtable");
2450 // Translate from byte offset to table index. It improves analyzability.
2451 llvm::Value *VBTableIndex = Builder.CreateAShr(
2452 VBTableOffset, llvm::ConstantInt::get(VBTableOffset->getType(), 2),
2453 "vbtindex", /*isExact=*/true);
2455 // Load an i32 offset from the vb-table.
2456 llvm::Value *VBaseOffs = Builder.CreateInBoundsGEP(VBTable, VBTableIndex);
2457 VBaseOffs = Builder.CreateBitCast(VBaseOffs, CGM.Int32Ty->getPointerTo(0));
2458 return Builder.CreateLoad(VBaseOffs, "vbase_offs");
2461 // Returns an adjusted base cast to i8*, since we do more address arithmetic on
2463 llvm::Value *MicrosoftCXXABI::AdjustVirtualBase(
2464 CodeGenFunction &CGF, const Expr *E, const CXXRecordDecl *RD,
2465 llvm::Value *Base, llvm::Value *VBTableOffset, llvm::Value *VBPtrOffset) {
2466 CGBuilderTy &Builder = CGF.Builder;
2467 Base = Builder.CreateBitCast(Base, CGM.Int8PtrTy);
2468 llvm::BasicBlock *OriginalBB = nullptr;
2469 llvm::BasicBlock *SkipAdjustBB = nullptr;
2470 llvm::BasicBlock *VBaseAdjustBB = nullptr;
2472 // In the unspecified inheritance model, there might not be a vbtable at all,
2473 // in which case we need to skip the virtual base lookup. If there is a
2474 // vbtable, the first entry is a no-op entry that gives back the original
2475 // base, so look for a virtual base adjustment offset of zero.
2477 OriginalBB = Builder.GetInsertBlock();
2478 VBaseAdjustBB = CGF.createBasicBlock("memptr.vadjust");
2479 SkipAdjustBB = CGF.createBasicBlock("memptr.skip_vadjust");
2480 llvm::Value *IsVirtual =
2481 Builder.CreateICmpNE(VBTableOffset, getZeroInt(),
2483 Builder.CreateCondBr(IsVirtual, VBaseAdjustBB, SkipAdjustBB);
2484 CGF.EmitBlock(VBaseAdjustBB);
2487 // If we weren't given a dynamic vbptr offset, RD should be complete and we'll
2488 // know the vbptr offset.
2490 CharUnits offs = CharUnits::Zero();
2491 if (!RD->hasDefinition()) {
2492 DiagnosticsEngine &Diags = CGF.CGM.getDiags();
2493 unsigned DiagID = Diags.getCustomDiagID(
2494 DiagnosticsEngine::Error,
2495 "member pointer representation requires a "
2496 "complete class type for %0 to perform this expression");
2497 Diags.Report(E->getExprLoc(), DiagID) << RD << E->getSourceRange();
2498 } else if (RD->getNumVBases())
2499 offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
2500 VBPtrOffset = llvm::ConstantInt::get(CGM.IntTy, offs.getQuantity());
2502 llvm::Value *VBPtr = nullptr;
2503 llvm::Value *VBaseOffs =
2504 GetVBaseOffsetFromVBPtr(CGF, Base, VBPtrOffset, VBTableOffset, &VBPtr);
2505 llvm::Value *AdjustedBase = Builder.CreateInBoundsGEP(VBPtr, VBaseOffs);
2507 // Merge control flow with the case where we didn't have to adjust.
2508 if (VBaseAdjustBB) {
2509 Builder.CreateBr(SkipAdjustBB);
2510 CGF.EmitBlock(SkipAdjustBB);
2511 llvm::PHINode *Phi = Builder.CreatePHI(CGM.Int8PtrTy, 2, "memptr.base");
2512 Phi->addIncoming(Base, OriginalBB);
2513 Phi->addIncoming(AdjustedBase, VBaseAdjustBB);
2516 return AdjustedBase;
2519 llvm::Value *MicrosoftCXXABI::EmitMemberDataPointerAddress(
2520 CodeGenFunction &CGF, const Expr *E, llvm::Value *Base, llvm::Value *MemPtr,
2521 const MemberPointerType *MPT) {
2522 assert(MPT->isMemberDataPointer());
2523 unsigned AS = Base->getType()->getPointerAddressSpace();
2525 CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
2526 CGBuilderTy &Builder = CGF.Builder;
2527 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2528 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
2530 // Extract the fields we need, regardless of model. We'll apply them if we
2532 llvm::Value *FieldOffset = MemPtr;
2533 llvm::Value *VirtualBaseAdjustmentOffset = nullptr;
2534 llvm::Value *VBPtrOffset = nullptr;
2535 if (MemPtr->getType()->isStructTy()) {
2536 // We need to extract values.
2538 FieldOffset = Builder.CreateExtractValue(MemPtr, I++);
2539 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance))
2540 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
2541 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance))
2542 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
2545 if (VirtualBaseAdjustmentOffset) {
2546 Base = AdjustVirtualBase(CGF, E, RD, Base, VirtualBaseAdjustmentOffset,
2551 Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
2553 // Apply the offset, which we assume is non-null.
2555 Builder.CreateInBoundsGEP(Base, FieldOffset, "memptr.offset");
2557 // Cast the address to the appropriate pointer type, adopting the address
2558 // space of the base pointer.
2559 return Builder.CreateBitCast(Addr, PType);
2562 static MSInheritanceAttr::Spelling
2563 getInheritanceFromMemptr(const MemberPointerType *MPT) {
2564 return MPT->getMostRecentCXXRecordDecl()->getMSInheritanceModel();
2568 MicrosoftCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
2571 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
2572 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
2573 E->getCastKind() == CK_ReinterpretMemberPointer);
2575 // Use constant emission if we can.
2576 if (isa<llvm::Constant>(Src))
2577 return EmitMemberPointerConversion(E, cast<llvm::Constant>(Src));
2579 // We may be adding or dropping fields from the member pointer, so we need
2580 // both types and the inheritance models of both records.
2581 const MemberPointerType *SrcTy =
2582 E->getSubExpr()->getType()->castAs<MemberPointerType>();
2583 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
2584 bool IsFunc = SrcTy->isMemberFunctionPointer();
2586 // If the classes use the same null representation, reinterpret_cast is a nop.
2587 bool IsReinterpret = E->getCastKind() == CK_ReinterpretMemberPointer;
2588 if (IsReinterpret && IsFunc)
2591 CXXRecordDecl *SrcRD = SrcTy->getMostRecentCXXRecordDecl();
2592 CXXRecordDecl *DstRD = DstTy->getMostRecentCXXRecordDecl();
2593 if (IsReinterpret &&
2594 SrcRD->nullFieldOffsetIsZero() == DstRD->nullFieldOffsetIsZero())
2597 CGBuilderTy &Builder = CGF.Builder;
2599 // Branch past the conversion if Src is null.
2600 llvm::Value *IsNotNull = EmitMemberPointerIsNotNull(CGF, Src, SrcTy);
2601 llvm::Constant *DstNull = EmitNullMemberPointer(DstTy);
2603 // C++ 5.2.10p9: The null member pointer value is converted to the null member
2604 // pointer value of the destination type.
2605 if (IsReinterpret) {
2606 // For reinterpret casts, sema ensures that src and dst are both functions
2607 // or data and have the same size, which means the LLVM types should match.
2608 assert(Src->getType() == DstNull->getType());
2609 return Builder.CreateSelect(IsNotNull, Src, DstNull);
2612 llvm::BasicBlock *OriginalBB = Builder.GetInsertBlock();
2613 llvm::BasicBlock *ConvertBB = CGF.createBasicBlock("memptr.convert");
2614 llvm::BasicBlock *ContinueBB = CGF.createBasicBlock("memptr.converted");
2615 Builder.CreateCondBr(IsNotNull, ConvertBB, ContinueBB);
2616 CGF.EmitBlock(ConvertBB);
2619 llvm::Value *FirstField = Src;
2620 llvm::Value *NonVirtualBaseAdjustment = nullptr;
2621 llvm::Value *VirtualBaseAdjustmentOffset = nullptr;
2622 llvm::Value *VBPtrOffset = nullptr;
2623 MSInheritanceAttr::Spelling SrcInheritance = SrcRD->getMSInheritanceModel();
2624 if (!MSInheritanceAttr::hasOnlyOneField(IsFunc, SrcInheritance)) {
2625 // We need to extract values.
2627 FirstField = Builder.CreateExtractValue(Src, I++);
2628 if (MSInheritanceAttr::hasNVOffsetField(IsFunc, SrcInheritance))
2629 NonVirtualBaseAdjustment = Builder.CreateExtractValue(Src, I++);
2630 if (MSInheritanceAttr::hasVBPtrOffsetField(SrcInheritance))
2631 VBPtrOffset = Builder.CreateExtractValue(Src, I++);
2632 if (MSInheritanceAttr::hasVBTableOffsetField(SrcInheritance))
2633 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(Src, I++);
2636 // For data pointers, we adjust the field offset directly. For functions, we
2637 // have a separate field.
2638 llvm::Constant *Adj = getMemberPointerAdjustment(E);
2640 Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy);
2641 llvm::Value *&NVAdjustField = IsFunc ? NonVirtualBaseAdjustment : FirstField;
2642 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
2643 if (!NVAdjustField) // If this field didn't exist in src, it's zero.
2644 NVAdjustField = getZeroInt();
2645 if (isDerivedToBase)
2646 NVAdjustField = Builder.CreateNSWSub(NVAdjustField, Adj, "adj");
2648 NVAdjustField = Builder.CreateNSWAdd(NVAdjustField, Adj, "adj");
2651 // FIXME PR15713: Support conversions through virtually derived classes.
2653 // Recompose dst from the null struct and the adjusted fields from src.
2654 MSInheritanceAttr::Spelling DstInheritance = DstRD->getMSInheritanceModel();
2656 if (MSInheritanceAttr::hasOnlyOneField(IsFunc, DstInheritance)) {
2659 Dst = llvm::UndefValue::get(DstNull->getType());
2661 Dst = Builder.CreateInsertValue(Dst, FirstField, Idx++);
2662 if (MSInheritanceAttr::hasNVOffsetField(IsFunc, DstInheritance))
2663 Dst = Builder.CreateInsertValue(
2664 Dst, getValueOrZeroInt(NonVirtualBaseAdjustment), Idx++);
2665 if (MSInheritanceAttr::hasVBPtrOffsetField(DstInheritance))
2666 Dst = Builder.CreateInsertValue(
2667 Dst, getValueOrZeroInt(VBPtrOffset), Idx++);
2668 if (MSInheritanceAttr::hasVBTableOffsetField(DstInheritance))
2669 Dst = Builder.CreateInsertValue(
2670 Dst, getValueOrZeroInt(VirtualBaseAdjustmentOffset), Idx++);
2672 Builder.CreateBr(ContinueBB);
2674 // In the continuation, choose between DstNull and Dst.
2675 CGF.EmitBlock(ContinueBB);
2676 llvm::PHINode *Phi = Builder.CreatePHI(DstNull->getType(), 2, "memptr.converted");
2677 Phi->addIncoming(DstNull, OriginalBB);
2678 Phi->addIncoming(Dst, ConvertBB);
2683 MicrosoftCXXABI::EmitMemberPointerConversion(const CastExpr *E,
2684 llvm::Constant *Src) {
2685 const MemberPointerType *SrcTy =
2686 E->getSubExpr()->getType()->castAs<MemberPointerType>();
2687 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
2689 // If src is null, emit a new null for dst. We can't return src because dst
2690 // might have a new representation.
2691 if (MemberPointerConstantIsNull(SrcTy, Src))
2692 return EmitNullMemberPointer(DstTy);
2694 // We don't need to do anything for reinterpret_casts of non-null member
2695 // pointers. We should only get here when the two type representations have
2697 if (E->getCastKind() == CK_ReinterpretMemberPointer)
2700 MSInheritanceAttr::Spelling SrcInheritance = getInheritanceFromMemptr(SrcTy);
2701 MSInheritanceAttr::Spelling DstInheritance = getInheritanceFromMemptr(DstTy);
2704 llvm::Constant *FirstField = Src;
2705 llvm::Constant *NonVirtualBaseAdjustment = nullptr;
2706 llvm::Constant *VirtualBaseAdjustmentOffset = nullptr;
2707 llvm::Constant *VBPtrOffset = nullptr;
2708 bool IsFunc = SrcTy->isMemberFunctionPointer();
2709 if (!MSInheritanceAttr::hasOnlyOneField(IsFunc, SrcInheritance)) {
2710 // We need to extract values.
2712 FirstField = Src->getAggregateElement(I++);
2713 if (MSInheritanceAttr::hasNVOffsetField(IsFunc, SrcInheritance))
2714 NonVirtualBaseAdjustment = Src->getAggregateElement(I++);
2715 if (MSInheritanceAttr::hasVBPtrOffsetField(SrcInheritance))
2716 VBPtrOffset = Src->getAggregateElement(I++);
2717 if (MSInheritanceAttr::hasVBTableOffsetField(SrcInheritance))
2718 VirtualBaseAdjustmentOffset = Src->getAggregateElement(I++);
2721 // For data pointers, we adjust the field offset directly. For functions, we
2722 // have a separate field.
2723 llvm::Constant *Adj = getMemberPointerAdjustment(E);
2725 Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy);
2726 llvm::Constant *&NVAdjustField =
2727 IsFunc ? NonVirtualBaseAdjustment : FirstField;
2728 bool IsDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
2729 if (!NVAdjustField) // If this field didn't exist in src, it's zero.
2730 NVAdjustField = getZeroInt();
2731 if (IsDerivedToBase)
2732 NVAdjustField = llvm::ConstantExpr::getNSWSub(NVAdjustField, Adj);
2734 NVAdjustField = llvm::ConstantExpr::getNSWAdd(NVAdjustField, Adj);
2737 // FIXME PR15713: Support conversions through virtually derived classes.
2739 // Recompose dst from the null struct and the adjusted fields from src.
2740 if (MSInheritanceAttr::hasOnlyOneField(IsFunc, DstInheritance))
2743 llvm::SmallVector<llvm::Constant *, 4> Fields;
2744 Fields.push_back(FirstField);
2745 if (MSInheritanceAttr::hasNVOffsetField(IsFunc, DstInheritance))
2746 Fields.push_back(getConstantOrZeroInt(NonVirtualBaseAdjustment));
2747 if (MSInheritanceAttr::hasVBPtrOffsetField(DstInheritance))
2748 Fields.push_back(getConstantOrZeroInt(VBPtrOffset));
2749 if (MSInheritanceAttr::hasVBTableOffsetField(DstInheritance))
2750 Fields.push_back(getConstantOrZeroInt(VirtualBaseAdjustmentOffset));
2751 return llvm::ConstantStruct::getAnon(Fields);
2754 llvm::Value *MicrosoftCXXABI::EmitLoadOfMemberFunctionPointer(
2755 CodeGenFunction &CGF, const Expr *E, llvm::Value *&This,
2756 llvm::Value *MemPtr, const MemberPointerType *MPT) {
2757 assert(MPT->isMemberFunctionPointer());
2758 const FunctionProtoType *FPT =
2759 MPT->getPointeeType()->castAs<FunctionProtoType>();
2760 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2761 llvm::FunctionType *FTy =
2762 CGM.getTypes().GetFunctionType(
2763 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
2764 CGBuilderTy &Builder = CGF.Builder;
2766 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
2768 // Extract the fields we need, regardless of model. We'll apply them if we
2770 llvm::Value *FunctionPointer = MemPtr;
2771 llvm::Value *NonVirtualBaseAdjustment = nullptr;
2772 llvm::Value *VirtualBaseAdjustmentOffset = nullptr;
2773 llvm::Value *VBPtrOffset = nullptr;
2774 if (MemPtr->getType()->isStructTy()) {
2775 // We need to extract values.
2777 FunctionPointer = Builder.CreateExtractValue(MemPtr, I++);
2778 if (MSInheritanceAttr::hasNVOffsetField(MPT, Inheritance))
2779 NonVirtualBaseAdjustment = Builder.CreateExtractValue(MemPtr, I++);
2780 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance))
2781 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
2782 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance))
2783 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
2786 if (VirtualBaseAdjustmentOffset) {
2787 This = AdjustVirtualBase(CGF, E, RD, This, VirtualBaseAdjustmentOffset,
2791 if (NonVirtualBaseAdjustment) {
2792 // Apply the adjustment and cast back to the original struct type.
2793 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
2794 Ptr = Builder.CreateInBoundsGEP(Ptr, NonVirtualBaseAdjustment);
2795 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
2798 return Builder.CreateBitCast(FunctionPointer, FTy->getPointerTo());
2801 CGCXXABI *clang::CodeGen::CreateMicrosoftCXXABI(CodeGenModule &CGM) {
2802 return new MicrosoftCXXABI(CGM);
2805 // MS RTTI Overview:
2806 // The run time type information emitted by cl.exe contains 5 distinct types of
2807 // structures. Many of them reference each other.
2809 // TypeInfo: Static classes that are returned by typeid.
2811 // CompleteObjectLocator: Referenced by vftables. They contain information
2812 // required for dynamic casting, including OffsetFromTop. They also contain
2813 // a reference to the TypeInfo for the type and a reference to the
2814 // CompleteHierarchyDescriptor for the type.
2816 // ClassHieararchyDescriptor: Contains information about a class hierarchy.
2817 // Used during dynamic_cast to walk a class hierarchy. References a base
2818 // class array and the size of said array.
2820 // BaseClassArray: Contains a list of classes in a hierarchy. BaseClassArray is
2821 // somewhat of a misnomer because the most derived class is also in the list
2822 // as well as multiple copies of virtual bases (if they occur multiple times
2823 // in the hiearchy.) The BaseClassArray contains one BaseClassDescriptor for
2824 // every path in the hierarchy, in pre-order depth first order. Note, we do
2825 // not declare a specific llvm type for BaseClassArray, it's merely an array
2826 // of BaseClassDescriptor pointers.
2828 // BaseClassDescriptor: Contains information about a class in a class hierarchy.
2829 // BaseClassDescriptor is also somewhat of a misnomer for the same reason that
2830 // BaseClassArray is. It contains information about a class within a
2831 // hierarchy such as: is this base is ambiguous and what is its offset in the
2832 // vbtable. The names of the BaseClassDescriptors have all of their fields
2833 // mangled into them so they can be aggressively deduplicated by the linker.
2835 static llvm::GlobalVariable *getTypeInfoVTable(CodeGenModule &CGM) {
2836 StringRef MangledName("\01??_7type_info@@6B@");
2837 if (auto VTable = CGM.getModule().getNamedGlobal(MangledName))
2839 return new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
2841 llvm::GlobalVariable::ExternalLinkage,
2842 /*Initializer=*/nullptr, MangledName);
2847 /// \brief A Helper struct that stores information about a class in a class
2848 /// hierarchy. The information stored in these structs struct is used during
2849 /// the generation of ClassHierarchyDescriptors and BaseClassDescriptors.
2850 // During RTTI creation, MSRTTIClasses are stored in a contiguous array with
2851 // implicit depth first pre-order tree connectivity. getFirstChild and
2852 // getNextSibling allow us to walk the tree efficiently.
2853 struct MSRTTIClass {
2855 IsPrivateOnPath = 1 | 8,
2859 HasHierarchyDescriptor = 64
2861 MSRTTIClass(const CXXRecordDecl *RD) : RD(RD) {}
2862 uint32_t initialize(const MSRTTIClass *Parent,
2863 const CXXBaseSpecifier *Specifier);
2865 MSRTTIClass *getFirstChild() { return this + 1; }
2866 static MSRTTIClass *getNextChild(MSRTTIClass *Child) {
2867 return Child + 1 + Child->NumBases;
2870 const CXXRecordDecl *RD, *VirtualRoot;
2871 uint32_t Flags, NumBases, OffsetInVBase;
2874 /// \brief Recursively initialize the base class array.
2875 uint32_t MSRTTIClass::initialize(const MSRTTIClass *Parent,
2876 const CXXBaseSpecifier *Specifier) {
2877 Flags = HasHierarchyDescriptor;
2879 VirtualRoot = nullptr;
2882 if (Specifier->getAccessSpecifier() != AS_public)
2883 Flags |= IsPrivate | IsPrivateOnPath;
2884 if (Specifier->isVirtual()) {
2889 if (Parent->Flags & IsPrivateOnPath)
2890 Flags |= IsPrivateOnPath;
2891 VirtualRoot = Parent->VirtualRoot;
2892 OffsetInVBase = Parent->OffsetInVBase + RD->getASTContext()
2893 .getASTRecordLayout(Parent->RD).getBaseClassOffset(RD).getQuantity();
2897 MSRTTIClass *Child = getFirstChild();
2898 for (const CXXBaseSpecifier &Base : RD->bases()) {
2899 NumBases += Child->initialize(this, &Base) + 1;
2900 Child = getNextChild(Child);
2905 static llvm::GlobalValue::LinkageTypes getLinkageForRTTI(QualType Ty) {
2906 switch (Ty->getLinkage()) {
2908 case InternalLinkage:
2909 case UniqueExternalLinkage:
2910 return llvm::GlobalValue::InternalLinkage;
2912 case VisibleNoLinkage:
2913 case ExternalLinkage:
2914 return llvm::GlobalValue::LinkOnceODRLinkage;
2916 llvm_unreachable("Invalid linkage!");
2919 /// \brief An ephemeral helper class for building MS RTTI types. It caches some
2920 /// calls to the module and information about the most derived class in a
2922 struct MSRTTIBuilder {
2924 HasBranchingHierarchy = 1,
2925 HasVirtualBranchingHierarchy = 2,
2926 HasAmbiguousBases = 4
2929 MSRTTIBuilder(MicrosoftCXXABI &ABI, const CXXRecordDecl *RD)
2930 : CGM(ABI.CGM), Context(CGM.getContext()),
2931 VMContext(CGM.getLLVMContext()), Module(CGM.getModule()), RD(RD),
2932 Linkage(getLinkageForRTTI(CGM.getContext().getTagDeclType(RD))),
2935 llvm::GlobalVariable *getBaseClassDescriptor(const MSRTTIClass &Classes);
2936 llvm::GlobalVariable *
2937 getBaseClassArray(SmallVectorImpl<MSRTTIClass> &Classes);
2938 llvm::GlobalVariable *getClassHierarchyDescriptor();
2939 llvm::GlobalVariable *getCompleteObjectLocator(const VPtrInfo *Info);
2942 ASTContext &Context;
2943 llvm::LLVMContext &VMContext;
2944 llvm::Module &Module;
2945 const CXXRecordDecl *RD;
2946 llvm::GlobalVariable::LinkageTypes Linkage;
2947 MicrosoftCXXABI &ABI;
2952 /// \brief Recursively serializes a class hierarchy in pre-order depth first
2954 static void serializeClassHierarchy(SmallVectorImpl<MSRTTIClass> &Classes,
2955 const CXXRecordDecl *RD) {
2956 Classes.push_back(MSRTTIClass(RD));
2957 for (const CXXBaseSpecifier &Base : RD->bases())
2958 serializeClassHierarchy(Classes, Base.getType()->getAsCXXRecordDecl());
2961 /// \brief Find ambiguity among base classes.
2963 detectAmbiguousBases(SmallVectorImpl<MSRTTIClass> &Classes) {
2964 llvm::SmallPtrSet<const CXXRecordDecl *, 8> VirtualBases;
2965 llvm::SmallPtrSet<const CXXRecordDecl *, 8> UniqueBases;
2966 llvm::SmallPtrSet<const CXXRecordDecl *, 8> AmbiguousBases;
2967 for (MSRTTIClass *Class = &Classes.front(); Class <= &Classes.back();) {
2968 if ((Class->Flags & MSRTTIClass::IsVirtual) &&
2969 !VirtualBases.insert(Class->RD).second) {
2970 Class = MSRTTIClass::getNextChild(Class);
2973 if (!UniqueBases.insert(Class->RD).second)
2974 AmbiguousBases.insert(Class->RD);
2977 if (AmbiguousBases.empty())
2979 for (MSRTTIClass &Class : Classes)
2980 if (AmbiguousBases.count(Class.RD))
2981 Class.Flags |= MSRTTIClass::IsAmbiguous;
2984 llvm::GlobalVariable *MSRTTIBuilder::getClassHierarchyDescriptor() {
2985 SmallString<256> MangledName;
2987 llvm::raw_svector_ostream Out(MangledName);
2988 ABI.getMangleContext().mangleCXXRTTIClassHierarchyDescriptor(RD, Out);
2991 // Check to see if we've already declared this ClassHierarchyDescriptor.
2992 if (auto CHD = Module.getNamedGlobal(MangledName))
2995 // Serialize the class hierarchy and initialize the CHD Fields.
2996 SmallVector<MSRTTIClass, 8> Classes;
2997 serializeClassHierarchy(Classes, RD);
2998 Classes.front().initialize(/*Parent=*/nullptr, /*Specifier=*/nullptr);
2999 detectAmbiguousBases(Classes);
3001 for (auto Class : Classes) {
3002 if (Class.RD->getNumBases() > 1)
3003 Flags |= HasBranchingHierarchy;
3004 // Note: cl.exe does not calculate "HasAmbiguousBases" correctly. We
3005 // believe the field isn't actually used.
3006 if (Class.Flags & MSRTTIClass::IsAmbiguous)
3007 Flags |= HasAmbiguousBases;
3009 if ((Flags & HasBranchingHierarchy) && RD->getNumVBases() != 0)
3010 Flags |= HasVirtualBranchingHierarchy;
3011 // These gep indices are used to get the address of the first element of the
3012 // base class array.
3013 llvm::Value *GEPIndices[] = {llvm::ConstantInt::get(CGM.IntTy, 0),
3014 llvm::ConstantInt::get(CGM.IntTy, 0)};
3016 // Forward-declare the class hierarchy descriptor
3017 auto Type = ABI.getClassHierarchyDescriptorType();
3018 auto CHD = new llvm::GlobalVariable(Module, Type, /*Constant=*/true, Linkage,
3019 /*Initializer=*/nullptr,
3020 StringRef(MangledName));
3021 if (CHD->isWeakForLinker())
3022 CHD->setComdat(CGM.getModule().getOrInsertComdat(CHD->getName()));
3024 auto *Bases = getBaseClassArray(Classes);
3026 // Initialize the base class ClassHierarchyDescriptor.
3027 llvm::Constant *Fields[] = {
3028 llvm::ConstantInt::get(CGM.IntTy, 0), // Unknown
3029 llvm::ConstantInt::get(CGM.IntTy, Flags),
3030 llvm::ConstantInt::get(CGM.IntTy, Classes.size()),
3031 ABI.getImageRelativeConstant(llvm::ConstantExpr::getInBoundsGetElementPtr(
3032 Bases->getValueType(), Bases,
3033 llvm::ArrayRef<llvm::Value *>(GEPIndices))),
3035 CHD->setInitializer(llvm::ConstantStruct::get(Type, Fields));
3039 llvm::GlobalVariable *
3040 MSRTTIBuilder::getBaseClassArray(SmallVectorImpl<MSRTTIClass> &Classes) {
3041 SmallString<256> MangledName;
3043 llvm::raw_svector_ostream Out(MangledName);
3044 ABI.getMangleContext().mangleCXXRTTIBaseClassArray(RD, Out);
3047 // Forward-declare the base class array.
3048 // cl.exe pads the base class array with 1 (in 32 bit mode) or 4 (in 64 bit
3049 // mode) bytes of padding. We provide a pointer sized amount of padding by
3050 // adding +1 to Classes.size(). The sections have pointer alignment and are
3051 // marked pick-any so it shouldn't matter.
3052 llvm::Type *PtrType = ABI.getImageRelativeType(
3053 ABI.getBaseClassDescriptorType()->getPointerTo());
3054 auto *ArrType = llvm::ArrayType::get(PtrType, Classes.size() + 1);
3056 new llvm::GlobalVariable(Module, ArrType,
3057 /*Constant=*/true, Linkage,
3058 /*Initializer=*/nullptr, StringRef(MangledName));
3059 if (BCA->isWeakForLinker())
3060 BCA->setComdat(CGM.getModule().getOrInsertComdat(BCA->getName()));
3062 // Initialize the BaseClassArray.
3063 SmallVector<llvm::Constant *, 8> BaseClassArrayData;
3064 for (MSRTTIClass &Class : Classes)
3065 BaseClassArrayData.push_back(
3066 ABI.getImageRelativeConstant(getBaseClassDescriptor(Class)));
3067 BaseClassArrayData.push_back(llvm::Constant::getNullValue(PtrType));
3068 BCA->setInitializer(llvm::ConstantArray::get(ArrType, BaseClassArrayData));
3072 llvm::GlobalVariable *
3073 MSRTTIBuilder::getBaseClassDescriptor(const MSRTTIClass &Class) {
3074 // Compute the fields for the BaseClassDescriptor. They are computed up front
3075 // because they are mangled into the name of the object.
3076 uint32_t OffsetInVBTable = 0;
3077 int32_t VBPtrOffset = -1;
3078 if (Class.VirtualRoot) {
3079 auto &VTableContext = CGM.getMicrosoftVTableContext();
3080 OffsetInVBTable = VTableContext.getVBTableIndex(RD, Class.VirtualRoot) * 4;
3081 VBPtrOffset = Context.getASTRecordLayout(RD).getVBPtrOffset().getQuantity();
3084 SmallString<256> MangledName;
3086 llvm::raw_svector_ostream Out(MangledName);
3087 ABI.getMangleContext().mangleCXXRTTIBaseClassDescriptor(
3088 Class.RD, Class.OffsetInVBase, VBPtrOffset, OffsetInVBTable,
3092 // Check to see if we've already declared this object.
3093 if (auto BCD = Module.getNamedGlobal(MangledName))
3096 // Forward-declare the base class descriptor.
3097 auto Type = ABI.getBaseClassDescriptorType();
3099 new llvm::GlobalVariable(Module, Type, /*Constant=*/true, Linkage,
3100 /*Initializer=*/nullptr, StringRef(MangledName));
3101 if (BCD->isWeakForLinker())
3102 BCD->setComdat(CGM.getModule().getOrInsertComdat(BCD->getName()));
3104 // Initialize the BaseClassDescriptor.
3105 llvm::Constant *Fields[] = {
3106 ABI.getImageRelativeConstant(
3107 ABI.getAddrOfRTTIDescriptor(Context.getTypeDeclType(Class.RD))),
3108 llvm::ConstantInt::get(CGM.IntTy, Class.NumBases),
3109 llvm::ConstantInt::get(CGM.IntTy, Class.OffsetInVBase),
3110 llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset),
3111 llvm::ConstantInt::get(CGM.IntTy, OffsetInVBTable),
3112 llvm::ConstantInt::get(CGM.IntTy, Class.Flags),
3113 ABI.getImageRelativeConstant(
3114 MSRTTIBuilder(ABI, Class.RD).getClassHierarchyDescriptor()),
3116 BCD->setInitializer(llvm::ConstantStruct::get(Type, Fields));
3120 llvm::GlobalVariable *
3121 MSRTTIBuilder::getCompleteObjectLocator(const VPtrInfo *Info) {
3122 SmallString<256> MangledName;
3124 llvm::raw_svector_ostream Out(MangledName);
3125 ABI.getMangleContext().mangleCXXRTTICompleteObjectLocator(RD, Info->MangledPath, Out);
3128 // Check to see if we've already computed this complete object locator.
3129 if (auto COL = Module.getNamedGlobal(MangledName))
3132 // Compute the fields of the complete object locator.
3133 int OffsetToTop = Info->FullOffsetInMDC.getQuantity();
3134 int VFPtrOffset = 0;
3135 // The offset includes the vtordisp if one exists.
3136 if (const CXXRecordDecl *VBase = Info->getVBaseWithVPtr())
3137 if (Context.getASTRecordLayout(RD)
3138 .getVBaseOffsetsMap()
3140 ->second.hasVtorDisp())
3141 VFPtrOffset = Info->NonVirtualOffset.getQuantity() + 4;
3143 // Forward-declare the complete object locator.
3144 llvm::StructType *Type = ABI.getCompleteObjectLocatorType();
3145 auto COL = new llvm::GlobalVariable(Module, Type, /*Constant=*/true, Linkage,
3146 /*Initializer=*/nullptr, StringRef(MangledName));
3148 // Initialize the CompleteObjectLocator.
3149 llvm::Constant *Fields[] = {
3150 llvm::ConstantInt::get(CGM.IntTy, ABI.isImageRelative()),
3151 llvm::ConstantInt::get(CGM.IntTy, OffsetToTop),
3152 llvm::ConstantInt::get(CGM.IntTy, VFPtrOffset),
3153 ABI.getImageRelativeConstant(
3154 CGM.GetAddrOfRTTIDescriptor(Context.getTypeDeclType(RD))),
3155 ABI.getImageRelativeConstant(getClassHierarchyDescriptor()),
3156 ABI.getImageRelativeConstant(COL),
3158 llvm::ArrayRef<llvm::Constant *> FieldsRef(Fields);
3159 if (!ABI.isImageRelative())
3160 FieldsRef = FieldsRef.drop_back();
3161 COL->setInitializer(llvm::ConstantStruct::get(Type, FieldsRef));
3162 if (COL->isWeakForLinker())
3163 COL->setComdat(CGM.getModule().getOrInsertComdat(COL->getName()));
3167 static QualType decomposeTypeForEH(ASTContext &Context, QualType T,
3168 bool &IsConst, bool &IsVolatile) {
3169 T = Context.getExceptionObjectType(T);
3171 // C++14 [except.handle]p3:
3172 // A handler is a match for an exception object of type E if [...]
3173 // - the handler is of type cv T or const T& where T is a pointer type and
3174 // E is a pointer type that can be converted to T by [...]
3175 // - a qualification conversion
3178 QualType PointeeType = T->getPointeeType();
3179 if (!PointeeType.isNull()) {
3180 IsConst = PointeeType.isConstQualified();
3181 IsVolatile = PointeeType.isVolatileQualified();
3184 // Member pointer types like "const int A::*" are represented by having RTTI
3185 // for "int A::*" and separately storing the const qualifier.
3186 if (const auto *MPTy = T->getAs<MemberPointerType>())
3187 T = Context.getMemberPointerType(PointeeType.getUnqualifiedType(),
3190 // Pointer types like "const int * const *" are represented by having RTTI
3191 // for "const int **" and separately storing the const qualifier.
3192 if (T->isPointerType())
3193 T = Context.getPointerType(PointeeType.getUnqualifiedType());
3199 MicrosoftCXXABI::getAddrOfCXXCatchHandlerType(QualType Type,
3200 QualType CatchHandlerType) {
3201 // TypeDescriptors for exceptions never have qualified pointer types,
3202 // qualifiers are stored seperately in order to support qualification
3204 bool IsConst, IsVolatile;
3205 Type = decomposeTypeForEH(getContext(), Type, IsConst, IsVolatile);
3207 bool IsReference = CatchHandlerType->isReferenceType();
3217 SmallString<256> MangledName;
3219 llvm::raw_svector_ostream Out(MangledName);
3220 getMangleContext().mangleCXXCatchHandlerType(Type, Flags, Out);
3223 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
3224 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
3226 llvm::Constant *Fields[] = {
3227 llvm::ConstantInt::get(CGM.IntTy, Flags), // Flags
3228 getAddrOfRTTIDescriptor(Type), // TypeDescriptor
3230 llvm::StructType *CatchHandlerTypeType = getCatchHandlerTypeType();
3231 auto *Var = new llvm::GlobalVariable(
3232 CGM.getModule(), CatchHandlerTypeType, /*Constant=*/true,
3233 llvm::GlobalValue::PrivateLinkage,
3234 llvm::ConstantStruct::get(CatchHandlerTypeType, Fields),
3235 StringRef(MangledName));
3236 Var->setUnnamedAddr(true);
3237 Var->setSection("llvm.metadata");
3241 /// \brief Gets a TypeDescriptor. Returns a llvm::Constant * rather than a
3242 /// llvm::GlobalVariable * because different type descriptors have different
3243 /// types, and need to be abstracted. They are abstracting by casting the
3244 /// address to an Int8PtrTy.
3245 llvm::Constant *MicrosoftCXXABI::getAddrOfRTTIDescriptor(QualType Type) {
3246 SmallString<256> MangledName;
3248 llvm::raw_svector_ostream Out(MangledName);
3249 getMangleContext().mangleCXXRTTI(Type, Out);
3252 // Check to see if we've already declared this TypeDescriptor.
3253 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
3254 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
3256 // Compute the fields for the TypeDescriptor.
3257 SmallString<256> TypeInfoString;
3259 llvm::raw_svector_ostream Out(TypeInfoString);
3260 getMangleContext().mangleCXXRTTIName(Type, Out);
3263 // Declare and initialize the TypeDescriptor.
3264 llvm::Constant *Fields[] = {
3265 getTypeInfoVTable(CGM), // VFPtr
3266 llvm::ConstantPointerNull::get(CGM.Int8PtrTy), // Runtime data
3267 llvm::ConstantDataArray::getString(CGM.getLLVMContext(), TypeInfoString)};
3268 llvm::StructType *TypeDescriptorType =
3269 getTypeDescriptorType(TypeInfoString);
3270 auto *Var = new llvm::GlobalVariable(
3271 CGM.getModule(), TypeDescriptorType, /*Constant=*/false,
3272 getLinkageForRTTI(Type),
3273 llvm::ConstantStruct::get(TypeDescriptorType, Fields),
3274 StringRef(MangledName));
3275 if (Var->isWeakForLinker())
3276 Var->setComdat(CGM.getModule().getOrInsertComdat(Var->getName()));
3277 return llvm::ConstantExpr::getBitCast(Var, CGM.Int8PtrTy);
3280 /// \brief Gets or a creates a Microsoft CompleteObjectLocator.
3281 llvm::GlobalVariable *
3282 MicrosoftCXXABI::getMSCompleteObjectLocator(const CXXRecordDecl *RD,
3283 const VPtrInfo *Info) {
3284 return MSRTTIBuilder(*this, RD).getCompleteObjectLocator(Info);
3287 static void emitCXXConstructor(CodeGenModule &CGM,
3288 const CXXConstructorDecl *ctor,
3289 StructorType ctorType) {
3290 // There are no constructor variants, always emit the complete destructor.
3291 llvm::Function *Fn = CGM.codegenCXXStructor(ctor, StructorType::Complete);
3292 CGM.maybeSetTrivialComdat(*ctor, *Fn);
3295 static void emitCXXDestructor(CodeGenModule &CGM, const CXXDestructorDecl *dtor,
3296 StructorType dtorType) {
3297 // The complete destructor is equivalent to the base destructor for
3298 // classes with no virtual bases, so try to emit it as an alias.
3299 if (!dtor->getParent()->getNumVBases() &&
3300 (dtorType == StructorType::Complete || dtorType == StructorType::Base)) {
3301 bool ProducedAlias = !CGM.TryEmitDefinitionAsAlias(
3302 GlobalDecl(dtor, Dtor_Complete), GlobalDecl(dtor, Dtor_Base), true);
3303 if (ProducedAlias) {
3304 if (dtorType == StructorType::Complete)
3306 if (dtor->isVirtual())
3307 CGM.getVTables().EmitThunks(GlobalDecl(dtor, Dtor_Complete));
3311 // The base destructor is equivalent to the base destructor of its
3312 // base class if there is exactly one non-virtual base class with a
3313 // non-trivial destructor, there are no fields with a non-trivial
3314 // destructor, and the body of the destructor is trivial.
3315 if (dtorType == StructorType::Base && !CGM.TryEmitBaseDestructorAsAlias(dtor))
3318 llvm::Function *Fn = CGM.codegenCXXStructor(dtor, dtorType);
3319 if (Fn->isWeakForLinker())
3320 Fn->setComdat(CGM.getModule().getOrInsertComdat(Fn->getName()));
3323 void MicrosoftCXXABI::emitCXXStructor(const CXXMethodDecl *MD,
3324 StructorType Type) {
3325 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
3326 emitCXXConstructor(CGM, CD, Type);
3329 emitCXXDestructor(CGM, cast<CXXDestructorDecl>(MD), Type);
3333 MicrosoftCXXABI::getAddrOfCXXCtorClosure(const CXXConstructorDecl *CD,
3335 assert(CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure);
3337 // Calculate the mangled name.
3338 SmallString<256> ThunkName;
3339 llvm::raw_svector_ostream Out(ThunkName);
3340 getMangleContext().mangleCXXCtor(CD, CT, Out);
3343 // If the thunk has been generated previously, just return it.
3344 if (llvm::GlobalValue *GV = CGM.getModule().getNamedValue(ThunkName))
3345 return cast<llvm::Function>(GV);
3347 // Create the llvm::Function.
3348 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeMSCtorClosure(CD, CT);
3349 llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo);
3350 const CXXRecordDecl *RD = CD->getParent();
3351 QualType RecordTy = getContext().getRecordType(RD);
3352 llvm::Function *ThunkFn = llvm::Function::Create(
3353 ThunkTy, getLinkageForRTTI(RecordTy), ThunkName.str(), &CGM.getModule());
3354 ThunkFn->setCallingConv(static_cast<llvm::CallingConv::ID>(
3355 FnInfo.getEffectiveCallingConvention()));
3356 bool IsCopy = CT == Ctor_CopyingClosure;
3359 CodeGenFunction CGF(CGM);
3360 CGF.CurGD = GlobalDecl(CD, Ctor_Complete);
3362 // Build FunctionArgs.
3363 FunctionArgList FunctionArgs;
3365 // A constructor always starts with a 'this' pointer as its first argument.
3366 buildThisParam(CGF, FunctionArgs);
3368 // Following the 'this' pointer is a reference to the source object that we
3369 // are copying from.
3370 ImplicitParamDecl SrcParam(
3371 getContext(), nullptr, SourceLocation(), &getContext().Idents.get("src"),
3372 getContext().getLValueReferenceType(RecordTy,
3373 /*SpelledAsLValue=*/true));
3375 FunctionArgs.push_back(&SrcParam);
3377 // Constructors for classes which utilize virtual bases have an additional
3378 // parameter which indicates whether or not it is being delegated to by a more
3379 // derived constructor.
3380 ImplicitParamDecl IsMostDerived(getContext(), nullptr, SourceLocation(),
3381 &getContext().Idents.get("is_most_derived"),
3382 getContext().IntTy);
3383 // Only add the parameter to the list if thie class has virtual bases.
3384 if (RD->getNumVBases() > 0)
3385 FunctionArgs.push_back(&IsMostDerived);
3387 // Start defining the function.
3388 CGF.StartFunction(GlobalDecl(), FnInfo.getReturnType(), ThunkFn, FnInfo,
3389 FunctionArgs, CD->getLocation(), SourceLocation());
3391 llvm::Value *This = getThisValue(CGF);
3393 llvm::Value *SrcVal =
3394 IsCopy ? CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&SrcParam), "src")
3399 // Push the this ptr.
3400 Args.add(RValue::get(This), CD->getThisType(getContext()));
3402 // Push the src ptr.
3404 Args.add(RValue::get(SrcVal), SrcParam.getType());
3406 // Add the rest of the default arguments.
3407 std::vector<Stmt *> ArgVec;
3408 for (unsigned I = IsCopy ? 1 : 0, E = CD->getNumParams(); I != E; ++I) {
3409 Stmt *DefaultArg = getContext().getDefaultArgExprForConstructor(CD, I);
3410 assert(DefaultArg && "sema forgot to instantiate default args");
3411 ArgVec.push_back(DefaultArg);
3414 CodeGenFunction::RunCleanupsScope Cleanups(CGF);
3416 const auto *FPT = CD->getType()->castAs<FunctionProtoType>();
3417 ConstExprIterator ArgBegin(ArgVec.data()),
3418 ArgEnd(ArgVec.data() + ArgVec.size());
3419 CGF.EmitCallArgs(Args, FPT, ArgBegin, ArgEnd, CD, IsCopy ? 1 : 0);
3421 // Insert any ABI-specific implicit constructor arguments.
3422 unsigned ExtraArgs = addImplicitConstructorArgs(CGF, CD, Ctor_Complete,
3423 /*ForVirtualBase=*/false,
3424 /*Delegating=*/false, Args);
3426 // Call the destructor with our arguments.
3427 llvm::Value *CalleeFn = CGM.getAddrOfCXXStructor(CD, StructorType::Complete);
3428 const CGFunctionInfo &CalleeInfo = CGM.getTypes().arrangeCXXConstructorCall(
3429 Args, CD, Ctor_Complete, ExtraArgs);
3430 CGF.EmitCall(CalleeInfo, CalleeFn, ReturnValueSlot(), Args, CD);
3432 Cleanups.ForceCleanup();
3434 // Emit the ret instruction, remove any temporary instructions created for the
3436 CGF.FinishFunction(SourceLocation());
3441 llvm::Constant *MicrosoftCXXABI::getCatchableType(QualType T,
3443 int32_t VBPtrOffset,
3445 assert(!T->isReferenceType());
3447 CXXRecordDecl *RD = T->getAsCXXRecordDecl();
3448 const CXXConstructorDecl *CD =
3449 RD ? CGM.getContext().getCopyConstructorForExceptionObject(RD) : nullptr;
3450 CXXCtorType CT = Ctor_Complete;
3452 if (!hasDefaultCXXMethodCC(getContext(), CD) || CD->getNumParams() != 1)
3453 CT = Ctor_CopyingClosure;
3455 uint32_t Size = getContext().getTypeSizeInChars(T).getQuantity();
3456 SmallString<256> MangledName;
3458 llvm::raw_svector_ostream Out(MangledName);
3459 getMangleContext().mangleCXXCatchableType(T, CD, CT, Size, NVOffset,
3460 VBPtrOffset, VBIndex, Out);
3462 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
3463 return getImageRelativeConstant(GV);
3465 // The TypeDescriptor is used by the runtime to determine if a catch handler
3466 // is appropriate for the exception object.
3467 llvm::Constant *TD = getImageRelativeConstant(getAddrOfRTTIDescriptor(T));
3469 // The runtime is responsible for calling the copy constructor if the
3470 // exception is caught by value.
3471 llvm::Constant *CopyCtor;
3473 if (CT == Ctor_CopyingClosure)
3474 CopyCtor = getAddrOfCXXCtorClosure(CD, Ctor_CopyingClosure);
3476 CopyCtor = CGM.getAddrOfCXXStructor(CD, StructorType::Complete);
3478 CopyCtor = llvm::ConstantExpr::getBitCast(CopyCtor, CGM.Int8PtrTy);
3480 CopyCtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);
3482 CopyCtor = getImageRelativeConstant(CopyCtor);
3484 bool IsScalar = !RD;
3485 bool HasVirtualBases = false;
3486 bool IsStdBadAlloc = false; // std::bad_alloc is special for some reason.
3487 QualType PointeeType = T;
3488 if (T->isPointerType())
3489 PointeeType = T->getPointeeType();
3490 if (const CXXRecordDecl *RD = PointeeType->getAsCXXRecordDecl()) {
3491 HasVirtualBases = RD->getNumVBases() > 0;
3492 if (IdentifierInfo *II = RD->getIdentifier())
3493 IsStdBadAlloc = II->isStr("bad_alloc") && RD->isInStdNamespace();
3496 // Encode the relevant CatchableType properties into the Flags bitfield.
3497 // FIXME: Figure out how bits 2 or 8 can get set.
3501 if (HasVirtualBases)
3506 llvm::Constant *Fields[] = {
3507 llvm::ConstantInt::get(CGM.IntTy, Flags), // Flags
3508 TD, // TypeDescriptor
3509 llvm::ConstantInt::get(CGM.IntTy, NVOffset), // NonVirtualAdjustment
3510 llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset), // OffsetToVBPtr
3511 llvm::ConstantInt::get(CGM.IntTy, VBIndex), // VBTableIndex
3512 llvm::ConstantInt::get(CGM.IntTy, Size), // Size
3513 CopyCtor // CopyCtor
3515 llvm::StructType *CTType = getCatchableTypeType();
3516 auto *GV = new llvm::GlobalVariable(
3517 CGM.getModule(), CTType, /*Constant=*/true, getLinkageForRTTI(T),
3518 llvm::ConstantStruct::get(CTType, Fields), StringRef(MangledName));
3519 GV->setUnnamedAddr(true);
3520 GV->setSection(".xdata");
3521 if (GV->isWeakForLinker())
3522 GV->setComdat(CGM.getModule().getOrInsertComdat(GV->getName()));
3523 return getImageRelativeConstant(GV);
3526 llvm::GlobalVariable *MicrosoftCXXABI::getCatchableTypeArray(QualType T) {
3527 assert(!T->isReferenceType());
3529 // See if we've already generated a CatchableTypeArray for this type before.
3530 llvm::GlobalVariable *&CTA = CatchableTypeArrays[T];
3534 // Ensure that we don't have duplicate entries in our CatchableTypeArray by
3535 // using a SmallSetVector. Duplicates may arise due to virtual bases
3536 // occurring more than once in the hierarchy.
3537 llvm::SmallSetVector<llvm::Constant *, 2> CatchableTypes;
3539 // C++14 [except.handle]p3:
3540 // A handler is a match for an exception object of type E if [...]
3541 // - the handler is of type cv T or cv T& and T is an unambiguous public
3542 // base class of E, or
3543 // - the handler is of type cv T or const T& where T is a pointer type and
3544 // E is a pointer type that can be converted to T by [...]
3545 // - a standard pointer conversion (4.10) not involving conversions to
3546 // pointers to private or protected or ambiguous classes
3547 const CXXRecordDecl *MostDerivedClass = nullptr;
3548 bool IsPointer = T->isPointerType();
3550 MostDerivedClass = T->getPointeeType()->getAsCXXRecordDecl();
3552 MostDerivedClass = T->getAsCXXRecordDecl();
3554 // Collect all the unambiguous public bases of the MostDerivedClass.
3555 if (MostDerivedClass) {
3556 const ASTContext &Context = getContext();
3557 const ASTRecordLayout &MostDerivedLayout =
3558 Context.getASTRecordLayout(MostDerivedClass);
3559 MicrosoftVTableContext &VTableContext = CGM.getMicrosoftVTableContext();
3560 SmallVector<MSRTTIClass, 8> Classes;
3561 serializeClassHierarchy(Classes, MostDerivedClass);
3562 Classes.front().initialize(/*Parent=*/nullptr, /*Specifier=*/nullptr);
3563 detectAmbiguousBases(Classes);
3564 for (const MSRTTIClass &Class : Classes) {
3565 // Skip any ambiguous or private bases.
3567 (MSRTTIClass::IsPrivateOnPath | MSRTTIClass::IsAmbiguous))
3569 // Write down how to convert from a derived pointer to a base pointer.
3570 uint32_t OffsetInVBTable = 0;
3571 int32_t VBPtrOffset = -1;
3572 if (Class.VirtualRoot) {
3574 VTableContext.getVBTableIndex(MostDerivedClass, Class.VirtualRoot)*4;
3575 VBPtrOffset = MostDerivedLayout.getVBPtrOffset().getQuantity();
3578 // Turn our record back into a pointer if the exception object is a
3580 QualType RTTITy = QualType(Class.RD->getTypeForDecl(), 0);
3582 RTTITy = Context.getPointerType(RTTITy);
3583 CatchableTypes.insert(getCatchableType(RTTITy, Class.OffsetInVBase,
3584 VBPtrOffset, OffsetInVBTable));
3588 // C++14 [except.handle]p3:
3589 // A handler is a match for an exception object of type E if
3590 // - The handler is of type cv T or cv T& and E and T are the same type
3591 // (ignoring the top-level cv-qualifiers)
3592 CatchableTypes.insert(getCatchableType(T));
3594 // C++14 [except.handle]p3:
3595 // A handler is a match for an exception object of type E if
3596 // - the handler is of type cv T or const T& where T is a pointer type and
3597 // E is a pointer type that can be converted to T by [...]
3598 // - a standard pointer conversion (4.10) not involving conversions to
3599 // pointers to private or protected or ambiguous classes
3601 // C++14 [conv.ptr]p2:
3602 // A prvalue of type "pointer to cv T," where T is an object type, can be
3603 // converted to a prvalue of type "pointer to cv void".
3604 if (IsPointer && T->getPointeeType()->isObjectType())
3605 CatchableTypes.insert(getCatchableType(getContext().VoidPtrTy));
3607 // C++14 [except.handle]p3:
3608 // A handler is a match for an exception object of type E if [...]
3609 // - the handler is of type cv T or const T& where T is a pointer or
3610 // pointer to member type and E is std::nullptr_t.
3612 // We cannot possibly list all possible pointer types here, making this
3613 // implementation incompatible with the standard. However, MSVC includes an
3614 // entry for pointer-to-void in this case. Let's do the same.
3615 if (T->isNullPtrType())
3616 CatchableTypes.insert(getCatchableType(getContext().VoidPtrTy));
3618 uint32_t NumEntries = CatchableTypes.size();
3619 llvm::Type *CTType =
3620 getImageRelativeType(getCatchableTypeType()->getPointerTo());
3621 llvm::ArrayType *AT = llvm::ArrayType::get(CTType, NumEntries);
3622 llvm::StructType *CTAType = getCatchableTypeArrayType(NumEntries);
3623 llvm::Constant *Fields[] = {
3624 llvm::ConstantInt::get(CGM.IntTy, NumEntries), // NumEntries
3625 llvm::ConstantArray::get(
3626 AT, llvm::makeArrayRef(CatchableTypes.begin(),
3627 CatchableTypes.end())) // CatchableTypes
3629 SmallString<256> MangledName;
3631 llvm::raw_svector_ostream Out(MangledName);
3632 getMangleContext().mangleCXXCatchableTypeArray(T, NumEntries, Out);
3634 CTA = new llvm::GlobalVariable(
3635 CGM.getModule(), CTAType, /*Constant=*/true, getLinkageForRTTI(T),
3636 llvm::ConstantStruct::get(CTAType, Fields), StringRef(MangledName));
3637 CTA->setUnnamedAddr(true);
3638 CTA->setSection(".xdata");
3639 if (CTA->isWeakForLinker())
3640 CTA->setComdat(CGM.getModule().getOrInsertComdat(CTA->getName()));
3644 llvm::GlobalVariable *MicrosoftCXXABI::getThrowInfo(QualType T) {
3645 bool IsConst, IsVolatile;
3646 T = decomposeTypeForEH(getContext(), T, IsConst, IsVolatile);
3648 // The CatchableTypeArray enumerates the various (CV-unqualified) types that
3649 // the exception object may be caught as.
3650 llvm::GlobalVariable *CTA = getCatchableTypeArray(T);
3651 // The first field in a CatchableTypeArray is the number of CatchableTypes.
3652 // This is used as a component of the mangled name which means that we need to
3653 // know what it is in order to see if we have previously generated the
3655 uint32_t NumEntries =
3656 cast<llvm::ConstantInt>(CTA->getInitializer()->getAggregateElement(0U))
3657 ->getLimitedValue();
3659 SmallString<256> MangledName;
3661 llvm::raw_svector_ostream Out(MangledName);
3662 getMangleContext().mangleCXXThrowInfo(T, IsConst, IsVolatile, NumEntries,
3666 // Reuse a previously generated ThrowInfo if we have generated an appropriate
3668 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
3671 // The RTTI TypeDescriptor uses an unqualified type but catch clauses must
3672 // be at least as CV qualified. Encode this requirement into the Flags
3680 // The cleanup-function (a destructor) must be called when the exception
3681 // object's lifetime ends.
3682 llvm::Constant *CleanupFn = llvm::Constant::getNullValue(CGM.Int8PtrTy);
3683 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3684 if (CXXDestructorDecl *DtorD = RD->getDestructor())
3685 if (!DtorD->isTrivial())
3686 CleanupFn = llvm::ConstantExpr::getBitCast(
3687 CGM.getAddrOfCXXStructor(DtorD, StructorType::Complete),
3689 // This is unused as far as we can tell, initialize it to null.
3690 llvm::Constant *ForwardCompat =
3691 getImageRelativeConstant(llvm::Constant::getNullValue(CGM.Int8PtrTy));
3692 llvm::Constant *PointerToCatchableTypes = getImageRelativeConstant(
3693 llvm::ConstantExpr::getBitCast(CTA, CGM.Int8PtrTy));
3694 llvm::StructType *TIType = getThrowInfoType();
3695 llvm::Constant *Fields[] = {
3696 llvm::ConstantInt::get(CGM.IntTy, Flags), // Flags
3697 getImageRelativeConstant(CleanupFn), // CleanupFn
3698 ForwardCompat, // ForwardCompat
3699 PointerToCatchableTypes // CatchableTypeArray
3701 auto *GV = new llvm::GlobalVariable(
3702 CGM.getModule(), TIType, /*Constant=*/true, getLinkageForRTTI(T),
3703 llvm::ConstantStruct::get(TIType, Fields), StringRef(MangledName));
3704 GV->setUnnamedAddr(true);
3705 GV->setSection(".xdata");
3706 if (GV->isWeakForLinker())
3707 GV->setComdat(CGM.getModule().getOrInsertComdat(GV->getName()));
3711 void MicrosoftCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
3712 const Expr *SubExpr = E->getSubExpr();
3713 QualType ThrowType = SubExpr->getType();
3714 // The exception object lives on the stack and it's address is passed to the
3715 // runtime function.
3716 llvm::AllocaInst *AI = CGF.CreateMemTemp(ThrowType);
3717 CGF.EmitAnyExprToMem(SubExpr, AI, ThrowType.getQualifiers(),
3720 // The so-called ThrowInfo is used to describe how the exception object may be
3722 llvm::GlobalVariable *TI = getThrowInfo(ThrowType);
3724 // Call into the runtime to throw the exception.
3725 llvm::Value *Args[] = {CGF.Builder.CreateBitCast(AI, CGM.Int8PtrTy), TI};
3726 CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(), Args);