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 "clang/AST/Decl.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/VTableBuilder.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/StringSet.h"
25 #include "llvm/IR/CallSite.h"
27 using namespace clang;
28 using namespace CodeGen;
32 /// Holds all the vbtable globals for a given class.
33 struct VBTableGlobals {
34 const VPtrInfoVector *VBTables;
35 SmallVector<llvm::GlobalVariable *, 2> Globals;
38 class MicrosoftCXXABI : public CGCXXABI {
40 MicrosoftCXXABI(CodeGenModule &CGM)
41 : CGCXXABI(CGM), BaseClassDescriptorType(nullptr),
42 ClassHierarchyDescriptorType(nullptr),
43 CompleteObjectLocatorType(nullptr) {}
45 bool HasThisReturn(GlobalDecl GD) const override;
46 bool hasMostDerivedReturn(GlobalDecl GD) const override;
48 bool classifyReturnType(CGFunctionInfo &FI) const override;
50 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override;
52 bool isSRetParameterAfterThis() const override { return true; }
54 size_t getSrcArgforCopyCtor(const CXXConstructorDecl *CD,
55 FunctionArgList &Args) const override {
56 assert(Args.size() >= 2 &&
57 "expected the arglist to have at least two args!");
58 // The 'most_derived' parameter goes second if the ctor is variadic and
60 if (CD->getParent()->getNumVBases() > 0 &&
61 CD->getType()->castAs<FunctionProtoType>()->isVariadic())
66 StringRef GetPureVirtualCallName() override { return "_purecall"; }
67 StringRef GetDeletedVirtualCallName() override { return "_purecall"; }
69 void emitVirtualObjectDelete(CodeGenFunction &CGF, const CXXDeleteExpr *DE,
70 llvm::Value *Ptr, QualType ElementType,
71 const CXXDestructorDecl *Dtor) override;
73 void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) override;
75 llvm::GlobalVariable *getMSCompleteObjectLocator(const CXXRecordDecl *RD,
76 const VPtrInfo *Info);
78 llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override;
80 bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override;
81 void EmitBadTypeidCall(CodeGenFunction &CGF) override;
82 llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
84 llvm::Type *StdTypeInfoPtrTy) override;
86 bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
87 QualType SrcRecordTy) override;
89 llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, llvm::Value *Value,
90 QualType SrcRecordTy, QualType DestTy,
91 QualType DestRecordTy,
92 llvm::BasicBlock *CastEnd) override;
94 llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, llvm::Value *Value,
96 QualType DestTy) override;
98 bool EmitBadCastCall(CodeGenFunction &CGF) override;
101 GetVirtualBaseClassOffset(CodeGenFunction &CGF, llvm::Value *This,
102 const CXXRecordDecl *ClassDecl,
103 const CXXRecordDecl *BaseClassDecl) override;
106 EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
107 const CXXRecordDecl *RD) override;
109 void initializeHiddenVirtualInheritanceMembers(CodeGenFunction &CGF,
110 const CXXRecordDecl *RD) override;
112 void EmitCXXConstructors(const CXXConstructorDecl *D) override;
114 // Background on MSVC destructors
115 // ==============================
117 // Both Itanium and MSVC ABIs have destructor variants. The variant names
118 // roughly correspond in the following way:
120 // Base -> no name, just ~Class
121 // Complete -> vbase destructor
122 // Deleting -> scalar deleting destructor
123 // vector deleting destructor
125 // The base and complete destructors are the same as in Itanium, although the
126 // complete destructor does not accept a VTT parameter when there are virtual
127 // bases. A separate mechanism involving vtordisps is used to ensure that
128 // virtual methods of destroyed subobjects are not called.
130 // The deleting destructors accept an i32 bitfield as a second parameter. Bit
131 // 1 indicates if the memory should be deleted. Bit 2 indicates if the this
132 // pointer points to an array. The scalar deleting destructor assumes that
133 // bit 2 is zero, and therefore does not contain a loop.
135 // For virtual destructors, only one entry is reserved in the vftable, and it
136 // always points to the vector deleting destructor. The vector deleting
137 // destructor is the most general, so it can be used to destroy objects in
138 // place, delete single heap objects, or delete arrays.
140 // A TU defining a non-inline destructor is only guaranteed to emit a base
141 // destructor, and all of the other variants are emitted on an as-needed basis
142 // in COMDATs. Because a non-base destructor can be emitted in a TU that
143 // lacks a definition for the destructor, non-base destructors must always
144 // delegate to or alias the base destructor.
146 void buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
147 SmallVectorImpl<CanQualType> &ArgTys) override;
149 /// Non-base dtors should be emitted as delegating thunks in this ABI.
150 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
151 CXXDtorType DT) const override {
152 return DT != Dtor_Base;
155 void EmitCXXDestructors(const CXXDestructorDecl *D) override;
157 const CXXRecordDecl *
158 getThisArgumentTypeForMethod(const CXXMethodDecl *MD) override {
159 MD = MD->getCanonicalDecl();
160 if (MD->isVirtual() && !isa<CXXDestructorDecl>(MD)) {
161 MicrosoftVTableContext::MethodVFTableLocation ML =
162 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(MD);
163 // The vbases might be ordered differently in the final overrider object
164 // and the complete object, so the "this" argument may sometimes point to
165 // memory that has no particular type (e.g. past the complete object).
166 // In this case, we just use a generic pointer type.
167 // FIXME: might want to have a more precise type in the non-virtual
168 // multiple inheritance case.
169 if (ML.VBase || !ML.VFPtrOffset.isZero())
172 return MD->getParent();
176 adjustThisArgumentForVirtualFunctionCall(CodeGenFunction &CGF, GlobalDecl GD,
178 bool VirtualCall) override;
180 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
181 FunctionArgList &Params) override;
183 llvm::Value *adjustThisParameterInVirtualFunctionPrologue(
184 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) override;
186 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
188 unsigned addImplicitConstructorArgs(CodeGenFunction &CGF,
189 const CXXConstructorDecl *D,
190 CXXCtorType Type, bool ForVirtualBase,
192 CallArgList &Args) override;
194 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
195 CXXDtorType Type, bool ForVirtualBase,
196 bool Delegating, llvm::Value *This) override;
198 void emitVTableDefinitions(CodeGenVTables &CGVT,
199 const CXXRecordDecl *RD) override;
201 llvm::Value *getVTableAddressPointInStructor(
202 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
203 BaseSubobject Base, const CXXRecordDecl *NearestVBase,
204 bool &NeedsVirtualOffset) override;
207 getVTableAddressPointForConstExpr(BaseSubobject Base,
208 const CXXRecordDecl *VTableClass) override;
210 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
211 CharUnits VPtrOffset) override;
213 llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
215 llvm::Type *Ty) override;
217 llvm::Value *EmitVirtualDestructorCall(CodeGenFunction &CGF,
218 const CXXDestructorDecl *Dtor,
219 CXXDtorType DtorType,
221 const CXXMemberCallExpr *CE) override;
223 void adjustCallArgsForDestructorThunk(CodeGenFunction &CGF, GlobalDecl GD,
224 CallArgList &CallArgs) override {
225 assert(GD.getDtorType() == Dtor_Deleting &&
226 "Only deleting destructor thunks are available in this ABI");
227 CallArgs.add(RValue::get(getStructorImplicitParamValue(CGF)),
228 CGM.getContext().IntTy);
231 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
233 llvm::GlobalVariable *
234 getAddrOfVBTable(const VPtrInfo &VBT, const CXXRecordDecl *RD,
235 llvm::GlobalVariable::LinkageTypes Linkage);
237 void emitVBTableDefinition(const VPtrInfo &VBT, const CXXRecordDecl *RD,
238 llvm::GlobalVariable *GV) const;
240 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable,
241 GlobalDecl GD, bool ReturnAdjustment) override {
242 // Never dllimport/dllexport thunks.
243 Thunk->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
246 getContext().GetGVALinkageForFunction(cast<FunctionDecl>(GD.getDecl()));
248 if (Linkage == GVA_Internal)
249 Thunk->setLinkage(llvm::GlobalValue::InternalLinkage);
250 else if (ReturnAdjustment)
251 Thunk->setLinkage(llvm::GlobalValue::WeakODRLinkage);
253 Thunk->setLinkage(llvm::GlobalValue::LinkOnceODRLinkage);
256 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, llvm::Value *This,
257 const ThisAdjustment &TA) override;
259 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
260 const ReturnAdjustment &RA) override;
262 void EmitThreadLocalInitFuncs(
264 ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *>>
266 ArrayRef<llvm::Function *> CXXThreadLocalInits,
267 ArrayRef<llvm::GlobalVariable *> CXXThreadLocalInitVars) override;
269 bool usesThreadWrapperFunction() const override { return false; }
270 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
271 QualType LValType) override;
273 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
274 llvm::GlobalVariable *DeclPtr,
275 bool PerformInit) override;
276 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
277 llvm::Constant *Dtor, llvm::Constant *Addr) override;
279 // ==== Notes on array cookies =========
281 // MSVC seems to only use cookies when the class has a destructor; a
282 // two-argument usual array deallocation function isn't sufficient.
284 // For example, this code prints "100" and "1":
287 // void *operator new[](size_t sz) {
288 // printf("%u\n", sz);
289 // return malloc(sz);
291 // void operator delete[](void *p, size_t sz) {
292 // printf("%u\n", sz);
297 // A *p = new A[100];
300 // Whereas it prints "104" and "104" if you give A a destructor.
302 bool requiresArrayCookie(const CXXDeleteExpr *expr,
303 QualType elementType) override;
304 bool requiresArrayCookie(const CXXNewExpr *expr) override;
305 CharUnits getArrayCookieSizeImpl(QualType type) override;
306 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
308 llvm::Value *NumElements,
309 const CXXNewExpr *expr,
310 QualType ElementType) override;
311 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
312 llvm::Value *allocPtr,
313 CharUnits cookieSize) override;
315 friend struct MSRTTIBuilder;
317 bool isImageRelative() const {
318 return CGM.getTarget().getPointerWidth(/*AddressSpace=*/0) == 64;
321 // 5 routines for constructing the llvm types for MS RTTI structs.
322 llvm::StructType *getTypeDescriptorType(StringRef TypeInfoString) {
323 llvm::SmallString<32> TDTypeName("rtti.TypeDescriptor");
324 TDTypeName += llvm::utostr(TypeInfoString.size());
325 llvm::StructType *&TypeDescriptorType =
326 TypeDescriptorTypeMap[TypeInfoString.size()];
327 if (TypeDescriptorType)
328 return TypeDescriptorType;
329 llvm::Type *FieldTypes[] = {
332 llvm::ArrayType::get(CGM.Int8Ty, TypeInfoString.size() + 1)};
334 llvm::StructType::create(CGM.getLLVMContext(), FieldTypes, TDTypeName);
335 return TypeDescriptorType;
338 llvm::Type *getImageRelativeType(llvm::Type *PtrType) {
339 if (!isImageRelative())
344 llvm::StructType *getBaseClassDescriptorType() {
345 if (BaseClassDescriptorType)
346 return BaseClassDescriptorType;
347 llvm::Type *FieldTypes[] = {
348 getImageRelativeType(CGM.Int8PtrTy),
354 getImageRelativeType(getClassHierarchyDescriptorType()->getPointerTo()),
356 BaseClassDescriptorType = llvm::StructType::create(
357 CGM.getLLVMContext(), FieldTypes, "rtti.BaseClassDescriptor");
358 return BaseClassDescriptorType;
361 llvm::StructType *getClassHierarchyDescriptorType() {
362 if (ClassHierarchyDescriptorType)
363 return ClassHierarchyDescriptorType;
364 // Forward-declare RTTIClassHierarchyDescriptor to break a cycle.
365 ClassHierarchyDescriptorType = llvm::StructType::create(
366 CGM.getLLVMContext(), "rtti.ClassHierarchyDescriptor");
367 llvm::Type *FieldTypes[] = {
371 getImageRelativeType(
372 getBaseClassDescriptorType()->getPointerTo()->getPointerTo()),
374 ClassHierarchyDescriptorType->setBody(FieldTypes);
375 return ClassHierarchyDescriptorType;
378 llvm::StructType *getCompleteObjectLocatorType() {
379 if (CompleteObjectLocatorType)
380 return CompleteObjectLocatorType;
381 CompleteObjectLocatorType = llvm::StructType::create(
382 CGM.getLLVMContext(), "rtti.CompleteObjectLocator");
383 llvm::Type *FieldTypes[] = {
387 getImageRelativeType(CGM.Int8PtrTy),
388 getImageRelativeType(getClassHierarchyDescriptorType()->getPointerTo()),
389 getImageRelativeType(CompleteObjectLocatorType),
391 llvm::ArrayRef<llvm::Type *> FieldTypesRef(FieldTypes);
392 if (!isImageRelative())
393 FieldTypesRef = FieldTypesRef.drop_back();
394 CompleteObjectLocatorType->setBody(FieldTypesRef);
395 return CompleteObjectLocatorType;
398 llvm::GlobalVariable *getImageBase() {
399 StringRef Name = "__ImageBase";
400 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name))
403 return new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty,
405 llvm::GlobalValue::ExternalLinkage,
406 /*Initializer=*/nullptr, Name);
409 llvm::Constant *getImageRelativeConstant(llvm::Constant *PtrVal) {
410 if (!isImageRelative())
413 llvm::Constant *ImageBaseAsInt =
414 llvm::ConstantExpr::getPtrToInt(getImageBase(), CGM.IntPtrTy);
415 llvm::Constant *PtrValAsInt =
416 llvm::ConstantExpr::getPtrToInt(PtrVal, CGM.IntPtrTy);
417 llvm::Constant *Diff =
418 llvm::ConstantExpr::getSub(PtrValAsInt, ImageBaseAsInt,
419 /*HasNUW=*/true, /*HasNSW=*/true);
420 return llvm::ConstantExpr::getTrunc(Diff, CGM.IntTy);
424 MicrosoftMangleContext &getMangleContext() {
425 return cast<MicrosoftMangleContext>(CodeGen::CGCXXABI::getMangleContext());
428 llvm::Constant *getZeroInt() {
429 return llvm::ConstantInt::get(CGM.IntTy, 0);
432 llvm::Constant *getAllOnesInt() {
433 return llvm::Constant::getAllOnesValue(CGM.IntTy);
436 llvm::Constant *getConstantOrZeroInt(llvm::Constant *C) {
437 return C ? C : getZeroInt();
440 llvm::Value *getValueOrZeroInt(llvm::Value *C) {
441 return C ? C : getZeroInt();
444 CharUnits getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD);
447 GetNullMemberPointerFields(const MemberPointerType *MPT,
448 llvm::SmallVectorImpl<llvm::Constant *> &fields);
450 /// \brief Shared code for virtual base adjustment. Returns the offset from
451 /// the vbptr to the virtual base. Optionally returns the address of the
453 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
455 llvm::Value *VBPtrOffset,
456 llvm::Value *VBTableOffset,
457 llvm::Value **VBPtr = nullptr);
459 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
462 int32_t VBTableOffset,
463 llvm::Value **VBPtr = nullptr) {
464 assert(VBTableOffset % 4 == 0 && "should be byte offset into table of i32s");
465 llvm::Value *VBPOffset = llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset),
466 *VBTOffset = llvm::ConstantInt::get(CGM.IntTy, VBTableOffset);
467 return GetVBaseOffsetFromVBPtr(CGF, Base, VBPOffset, VBTOffset, VBPtr);
470 /// \brief Performs a full virtual base adjustment. Used to dereference
471 /// pointers to members of virtual bases.
472 llvm::Value *AdjustVirtualBase(CodeGenFunction &CGF, const Expr *E,
473 const CXXRecordDecl *RD, llvm::Value *Base,
474 llvm::Value *VirtualBaseAdjustmentOffset,
475 llvm::Value *VBPtrOffset /* optional */);
477 /// \brief Emits a full member pointer with the fields common to data and
478 /// function member pointers.
479 llvm::Constant *EmitFullMemberPointer(llvm::Constant *FirstField,
480 bool IsMemberFunction,
481 const CXXRecordDecl *RD,
482 CharUnits NonVirtualBaseAdjustment);
484 llvm::Constant *BuildMemberPointer(const CXXRecordDecl *RD,
485 const CXXMethodDecl *MD,
486 CharUnits NonVirtualBaseAdjustment);
488 bool MemberPointerConstantIsNull(const MemberPointerType *MPT,
491 /// \brief - Initialize all vbptrs of 'this' with RD as the complete type.
492 void EmitVBPtrStores(CodeGenFunction &CGF, const CXXRecordDecl *RD);
494 /// \brief Caching wrapper around VBTableBuilder::enumerateVBTables().
495 const VBTableGlobals &enumerateVBTables(const CXXRecordDecl *RD);
497 /// \brief Generate a thunk for calling a virtual member function MD.
498 llvm::Function *EmitVirtualMemPtrThunk(
499 const CXXMethodDecl *MD,
500 const MicrosoftVTableContext::MethodVFTableLocation &ML);
503 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override;
505 bool isZeroInitializable(const MemberPointerType *MPT) override;
507 bool isMemberPointerConvertible(const MemberPointerType *MPT) const override {
508 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
509 return RD->hasAttr<MSInheritanceAttr>();
512 bool isTypeInfoCalculable(QualType Ty) const override {
513 if (!CGCXXABI::isTypeInfoCalculable(Ty))
515 if (const auto *MPT = Ty->getAs<MemberPointerType>()) {
516 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
517 if (!RD->hasAttr<MSInheritanceAttr>())
523 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override;
525 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
526 CharUnits offset) override;
527 llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD) override;
528 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override;
530 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
533 const MemberPointerType *MPT,
534 bool Inequality) override;
536 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
538 const MemberPointerType *MPT) override;
541 EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
542 llvm::Value *Base, llvm::Value *MemPtr,
543 const MemberPointerType *MPT) override;
545 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
547 llvm::Value *Src) override;
549 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
550 llvm::Constant *Src) override;
553 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF, const Expr *E,
554 llvm::Value *&This, llvm::Value *MemPtr,
555 const MemberPointerType *MPT) override;
557 void emitCXXStructor(const CXXMethodDecl *MD, StructorType Type) override;
560 typedef std::pair<const CXXRecordDecl *, CharUnits> VFTableIdTy;
561 typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalVariable *> VTablesMapTy;
562 typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalValue *> VFTablesMapTy;
563 /// \brief All the vftables that have been referenced.
564 VFTablesMapTy VFTablesMap;
565 VTablesMapTy VTablesMap;
567 /// \brief This set holds the record decls we've deferred vtable emission for.
568 llvm::SmallPtrSet<const CXXRecordDecl *, 4> DeferredVFTables;
571 /// \brief All the vbtables which have been referenced.
572 llvm::DenseMap<const CXXRecordDecl *, VBTableGlobals> VBTablesMap;
574 /// Info on the global variable used to guard initialization of static locals.
575 /// The BitIndex field is only used for externally invisible declarations.
577 GuardInfo() : Guard(nullptr), BitIndex(0) {}
578 llvm::GlobalVariable *Guard;
582 /// Map from DeclContext to the current guard variable. We assume that the
583 /// AST is visited in source code order.
584 llvm::DenseMap<const DeclContext *, GuardInfo> GuardVariableMap;
586 llvm::DenseMap<size_t, llvm::StructType *> TypeDescriptorTypeMap;
587 llvm::StructType *BaseClassDescriptorType;
588 llvm::StructType *ClassHierarchyDescriptorType;
589 llvm::StructType *CompleteObjectLocatorType;
594 CGCXXABI::RecordArgABI
595 MicrosoftCXXABI::getRecordArgABI(const CXXRecordDecl *RD) const {
596 switch (CGM.getTarget().getTriple().getArch()) {
598 // FIXME: Implement for other architectures.
601 case llvm::Triple::x86:
602 // All record arguments are passed in memory on x86. Decide whether to
603 // construct the object directly in argument memory, or to construct the
604 // argument elsewhere and copy the bytes during the call.
606 // If C++ prohibits us from making a copy, construct the arguments directly
607 // into argument memory.
608 if (!canCopyArgument(RD))
609 return RAA_DirectInMemory;
611 // Otherwise, construct the argument into a temporary and copy the bytes
612 // into the outgoing argument memory.
615 case llvm::Triple::x86_64:
616 // Win64 passes objects with non-trivial copy ctors indirectly.
617 if (RD->hasNonTrivialCopyConstructor())
620 // If an object has a destructor, we'd really like to pass it indirectly
621 // because it allows us to elide copies. Unfortunately, MSVC makes that
622 // impossible for small types, which it will pass in a single register or
623 // stack slot. Most objects with dtors are large-ish, so handle that early.
624 // We can't call out all large objects as being indirect because there are
625 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
626 // how we pass large POD types.
627 if (RD->hasNonTrivialDestructor() &&
628 getContext().getTypeSize(RD->getTypeForDecl()) > 64)
631 // We have a trivial copy constructor or no copy constructors, but we have
632 // to make sure it isn't deleted.
633 bool CopyDeleted = false;
634 for (const CXXConstructorDecl *CD : RD->ctors()) {
635 if (CD->isCopyConstructor()) {
636 assert(CD->isTrivial());
637 // We had at least one undeleted trivial copy ctor. Return directly.
638 if (!CD->isDeleted())
644 // The trivial copy constructor was deleted. Return indirectly.
648 // There were no copy ctors. Return in RAX.
652 llvm_unreachable("invalid enum");
655 void MicrosoftCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
656 const CXXDeleteExpr *DE,
658 QualType ElementType,
659 const CXXDestructorDecl *Dtor) {
660 // FIXME: Provide a source location here even though there's no
661 // CXXMemberCallExpr for dtor call.
662 bool UseGlobalDelete = DE->isGlobalDelete();
663 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
664 llvm::Value *MDThis =
665 EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, /*CE=*/nullptr);
667 CGF.EmitDeleteCall(DE->getOperatorDelete(), MDThis, ElementType);
670 static llvm::Function *getRethrowFn(CodeGenModule &CGM) {
671 // _CxxThrowException takes two pointer width arguments: a value and a context
672 // object which points to a TypeInfo object.
673 llvm::Type *ArgTypes[] = {CGM.Int8PtrTy, CGM.Int8PtrTy};
674 llvm::FunctionType *FTy =
675 llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
676 auto *Fn = cast<llvm::Function>(
677 CGM.CreateRuntimeFunction(FTy, "_CxxThrowException"));
678 // _CxxThrowException is stdcall on 32-bit x86 platforms.
679 if (CGM.getTarget().getTriple().getArch() == llvm::Triple::x86)
680 Fn->setCallingConv(llvm::CallingConv::X86_StdCall);
684 void MicrosoftCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
685 llvm::Value *Args[] = {llvm::ConstantPointerNull::get(CGM.Int8PtrTy),
686 llvm::ConstantPointerNull::get(CGM.Int8PtrTy)};
687 auto *Fn = getRethrowFn(CGM);
689 CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, Args);
691 CGF.EmitRuntimeCallOrInvoke(Fn, Args);
694 /// \brief Gets the offset to the virtual base that contains the vfptr for
695 /// MS-ABI polymorphic types.
696 static llvm::Value *getPolymorphicOffset(CodeGenFunction &CGF,
697 const CXXRecordDecl *RD,
698 llvm::Value *Value) {
699 const ASTContext &Context = RD->getASTContext();
700 for (const CXXBaseSpecifier &Base : RD->vbases())
701 if (Context.getASTRecordLayout(Base.getType()->getAsCXXRecordDecl())
702 .hasExtendableVFPtr())
703 return CGF.CGM.getCXXABI().GetVirtualBaseClassOffset(
704 CGF, Value, RD, Base.getType()->getAsCXXRecordDecl());
705 llvm_unreachable("One of our vbases should be polymorphic.");
708 static std::pair<llvm::Value *, llvm::Value *>
709 performBaseAdjustment(CodeGenFunction &CGF, llvm::Value *Value,
710 QualType SrcRecordTy) {
711 Value = CGF.Builder.CreateBitCast(Value, CGF.Int8PtrTy);
712 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
714 if (CGF.getContext().getASTRecordLayout(SrcDecl).hasExtendableVFPtr())
715 return std::make_pair(Value, llvm::ConstantInt::get(CGF.Int32Ty, 0));
717 // Perform a base adjustment.
718 llvm::Value *Offset = getPolymorphicOffset(CGF, SrcDecl, Value);
719 Value = CGF.Builder.CreateInBoundsGEP(Value, Offset);
720 Offset = CGF.Builder.CreateTrunc(Offset, CGF.Int32Ty);
721 return std::make_pair(Value, Offset);
724 bool MicrosoftCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
725 QualType SrcRecordTy) {
726 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
728 !CGM.getContext().getASTRecordLayout(SrcDecl).hasExtendableVFPtr();
731 static llvm::CallSite emitRTtypeidCall(CodeGenFunction &CGF,
732 llvm::Value *Argument) {
733 llvm::Type *ArgTypes[] = {CGF.Int8PtrTy};
734 llvm::FunctionType *FTy =
735 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false);
736 llvm::Value *Args[] = {Argument};
737 llvm::Constant *Fn = CGF.CGM.CreateRuntimeFunction(FTy, "__RTtypeid");
738 return CGF.EmitRuntimeCallOrInvoke(Fn, Args);
741 void MicrosoftCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
742 llvm::CallSite Call =
743 emitRTtypeidCall(CGF, llvm::Constant::getNullValue(CGM.VoidPtrTy));
744 Call.setDoesNotReturn();
745 CGF.Builder.CreateUnreachable();
748 llvm::Value *MicrosoftCXXABI::EmitTypeid(CodeGenFunction &CGF,
749 QualType SrcRecordTy,
750 llvm::Value *ThisPtr,
751 llvm::Type *StdTypeInfoPtrTy) {
753 std::tie(ThisPtr, Offset) = performBaseAdjustment(CGF, ThisPtr, SrcRecordTy);
754 return CGF.Builder.CreateBitCast(
755 emitRTtypeidCall(CGF, ThisPtr).getInstruction(), StdTypeInfoPtrTy);
758 bool MicrosoftCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
759 QualType SrcRecordTy) {
760 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
762 !CGM.getContext().getASTRecordLayout(SrcDecl).hasExtendableVFPtr();
765 llvm::Value *MicrosoftCXXABI::EmitDynamicCastCall(
766 CodeGenFunction &CGF, llvm::Value *Value, QualType SrcRecordTy,
767 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
768 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
770 llvm::Value *SrcRTTI =
771 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
772 llvm::Value *DestRTTI =
773 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
776 std::tie(Value, Offset) = performBaseAdjustment(CGF, Value, SrcRecordTy);
778 // PVOID __RTDynamicCast(
784 llvm::Type *ArgTypes[] = {CGF.Int8PtrTy, CGF.Int32Ty, CGF.Int8PtrTy,
785 CGF.Int8PtrTy, CGF.Int32Ty};
786 llvm::Constant *Function = CGF.CGM.CreateRuntimeFunction(
787 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false),
789 llvm::Value *Args[] = {
790 Value, Offset, SrcRTTI, DestRTTI,
791 llvm::ConstantInt::get(CGF.Int32Ty, DestTy->isReferenceType())};
792 Value = CGF.EmitRuntimeCallOrInvoke(Function, Args).getInstruction();
793 return CGF.Builder.CreateBitCast(Value, DestLTy);
797 MicrosoftCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF, llvm::Value *Value,
798 QualType SrcRecordTy,
801 std::tie(Value, Offset) = performBaseAdjustment(CGF, Value, SrcRecordTy);
803 // PVOID __RTCastToVoid(
805 llvm::Type *ArgTypes[] = {CGF.Int8PtrTy};
806 llvm::Constant *Function = CGF.CGM.CreateRuntimeFunction(
807 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false),
809 llvm::Value *Args[] = {Value};
810 return CGF.EmitRuntimeCall(Function, Args);
813 bool MicrosoftCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
817 llvm::Value *MicrosoftCXXABI::GetVirtualBaseClassOffset(
818 CodeGenFunction &CGF, llvm::Value *This, const CXXRecordDecl *ClassDecl,
819 const CXXRecordDecl *BaseClassDecl) {
821 getContext().getASTRecordLayout(ClassDecl).getVBPtrOffset().getQuantity();
822 llvm::Value *VBPtrOffset = llvm::ConstantInt::get(CGM.PtrDiffTy, VBPtrChars);
823 CharUnits IntSize = getContext().getTypeSizeInChars(getContext().IntTy);
824 CharUnits VBTableChars =
826 CGM.getMicrosoftVTableContext().getVBTableIndex(ClassDecl, BaseClassDecl);
827 llvm::Value *VBTableOffset =
828 llvm::ConstantInt::get(CGM.IntTy, VBTableChars.getQuantity());
830 llvm::Value *VBPtrToNewBase =
831 GetVBaseOffsetFromVBPtr(CGF, This, VBPtrOffset, VBTableOffset);
833 CGF.Builder.CreateSExtOrBitCast(VBPtrToNewBase, CGM.PtrDiffTy);
834 return CGF.Builder.CreateNSWAdd(VBPtrOffset, VBPtrToNewBase);
837 bool MicrosoftCXXABI::HasThisReturn(GlobalDecl GD) const {
838 return isa<CXXConstructorDecl>(GD.getDecl());
841 static bool isDeletingDtor(GlobalDecl GD) {
842 return isa<CXXDestructorDecl>(GD.getDecl()) &&
843 GD.getDtorType() == Dtor_Deleting;
846 bool MicrosoftCXXABI::hasMostDerivedReturn(GlobalDecl GD) const {
847 return isDeletingDtor(GD);
850 bool MicrosoftCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
851 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
855 if (FI.isInstanceMethod()) {
856 // If it's an instance method, aggregates are always returned indirectly via
857 // the second parameter.
858 FI.getReturnInfo() = ABIArgInfo::getIndirect(0, /*ByVal=*/false);
859 FI.getReturnInfo().setSRetAfterThis(FI.isInstanceMethod());
861 } else if (!RD->isPOD()) {
862 // If it's a free function, non-POD types are returned indirectly.
863 FI.getReturnInfo() = ABIArgInfo::getIndirect(0, /*ByVal=*/false);
867 // Otherwise, use the C ABI rules.
872 MicrosoftCXXABI::EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
873 const CXXRecordDecl *RD) {
874 llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);
875 assert(IsMostDerivedClass &&
876 "ctor for a class with virtual bases must have an implicit parameter");
877 llvm::Value *IsCompleteObject =
878 CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");
880 llvm::BasicBlock *CallVbaseCtorsBB = CGF.createBasicBlock("ctor.init_vbases");
881 llvm::BasicBlock *SkipVbaseCtorsBB = CGF.createBasicBlock("ctor.skip_vbases");
882 CGF.Builder.CreateCondBr(IsCompleteObject,
883 CallVbaseCtorsBB, SkipVbaseCtorsBB);
885 CGF.EmitBlock(CallVbaseCtorsBB);
887 // Fill in the vbtable pointers here.
888 EmitVBPtrStores(CGF, RD);
890 // CGF will put the base ctor calls in this basic block for us later.
892 return SkipVbaseCtorsBB;
895 void MicrosoftCXXABI::initializeHiddenVirtualInheritanceMembers(
896 CodeGenFunction &CGF, const CXXRecordDecl *RD) {
897 // In most cases, an override for a vbase virtual method can adjust
898 // the "this" parameter by applying a constant offset.
899 // However, this is not enough while a constructor or a destructor of some
900 // class X is being executed if all the following conditions are met:
901 // - X has virtual bases, (1)
902 // - X overrides a virtual method M of a vbase Y, (2)
903 // - X itself is a vbase of the most derived class.
905 // If (1) and (2) are true, the vtorDisp for vbase Y is a hidden member of X
906 // which holds the extra amount of "this" adjustment we must do when we use
907 // the X vftables (i.e. during X ctor or dtor).
908 // Outside the ctors and dtors, the values of vtorDisps are zero.
910 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
911 typedef ASTRecordLayout::VBaseOffsetsMapTy VBOffsets;
912 const VBOffsets &VBaseMap = Layout.getVBaseOffsetsMap();
913 CGBuilderTy &Builder = CGF.Builder;
916 cast<llvm::PointerType>(getThisValue(CGF)->getType())->getAddressSpace();
917 llvm::Value *Int8This = nullptr; // Initialize lazily.
919 for (VBOffsets::const_iterator I = VBaseMap.begin(), E = VBaseMap.end();
921 if (!I->second.hasVtorDisp())
924 llvm::Value *VBaseOffset =
925 GetVirtualBaseClassOffset(CGF, getThisValue(CGF), RD, I->first);
926 // FIXME: it doesn't look right that we SExt in GetVirtualBaseClassOffset()
927 // just to Trunc back immediately.
928 VBaseOffset = Builder.CreateTruncOrBitCast(VBaseOffset, CGF.Int32Ty);
929 uint64_t ConstantVBaseOffset =
930 Layout.getVBaseClassOffset(I->first).getQuantity();
932 // vtorDisp_for_vbase = vbptr[vbase_idx] - offsetof(RD, vbase).
933 llvm::Value *VtorDispValue = Builder.CreateSub(
934 VBaseOffset, llvm::ConstantInt::get(CGM.Int32Ty, ConstantVBaseOffset),
938 Int8This = Builder.CreateBitCast(getThisValue(CGF),
939 CGF.Int8Ty->getPointerTo(AS));
940 llvm::Value *VtorDispPtr = Builder.CreateInBoundsGEP(Int8This, VBaseOffset);
941 // vtorDisp is always the 32-bits before the vbase in the class layout.
942 VtorDispPtr = Builder.CreateConstGEP1_32(VtorDispPtr, -4);
943 VtorDispPtr = Builder.CreateBitCast(
944 VtorDispPtr, CGF.Int32Ty->getPointerTo(AS), "vtordisp.ptr");
946 Builder.CreateStore(VtorDispValue, VtorDispPtr);
950 void MicrosoftCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
951 // There's only one constructor type in this ABI.
952 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
955 void MicrosoftCXXABI::EmitVBPtrStores(CodeGenFunction &CGF,
956 const CXXRecordDecl *RD) {
957 llvm::Value *ThisInt8Ptr =
958 CGF.Builder.CreateBitCast(getThisValue(CGF), CGM.Int8PtrTy, "this.int8");
959 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
961 const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
962 for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) {
963 const VPtrInfo *VBT = (*VBGlobals.VBTables)[I];
964 llvm::GlobalVariable *GV = VBGlobals.Globals[I];
965 const ASTRecordLayout &SubobjectLayout =
966 CGM.getContext().getASTRecordLayout(VBT->BaseWithVPtr);
967 CharUnits Offs = VBT->NonVirtualOffset;
968 Offs += SubobjectLayout.getVBPtrOffset();
969 if (VBT->getVBaseWithVPtr())
970 Offs += Layout.getVBaseClassOffset(VBT->getVBaseWithVPtr());
972 CGF.Builder.CreateConstInBoundsGEP1_64(ThisInt8Ptr, Offs.getQuantity());
973 llvm::Value *GVPtr = CGF.Builder.CreateConstInBoundsGEP2_32(GV, 0, 0);
974 VBPtr = CGF.Builder.CreateBitCast(VBPtr, GVPtr->getType()->getPointerTo(0),
975 "vbptr." + VBT->ReusingBase->getName());
976 CGF.Builder.CreateStore(GVPtr, VBPtr);
981 MicrosoftCXXABI::buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
982 SmallVectorImpl<CanQualType> &ArgTys) {
983 // TODO: 'for base' flag
984 if (T == StructorType::Deleting) {
985 // The scalar deleting destructor takes an implicit int parameter.
986 ArgTys.push_back(CGM.getContext().IntTy);
988 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
992 // All parameters are already in place except is_most_derived, which goes
993 // after 'this' if it's variadic and last if it's not.
995 const CXXRecordDecl *Class = CD->getParent();
996 const FunctionProtoType *FPT = CD->getType()->castAs<FunctionProtoType>();
997 if (Class->getNumVBases()) {
998 if (FPT->isVariadic())
999 ArgTys.insert(ArgTys.begin() + 1, CGM.getContext().IntTy);
1001 ArgTys.push_back(CGM.getContext().IntTy);
1005 void MicrosoftCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
1006 // The TU defining a dtor is only guaranteed to emit a base destructor. All
1007 // other destructor variants are delegating thunks.
1008 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
1012 MicrosoftCXXABI::getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD) {
1013 GD = GD.getCanonicalDecl();
1014 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1016 GlobalDecl LookupGD = GD;
1017 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1018 // Complete destructors take a pointer to the complete object as a
1019 // parameter, thus don't need this adjustment.
1020 if (GD.getDtorType() == Dtor_Complete)
1023 // There's no Dtor_Base in vftable but it shares the this adjustment with
1024 // the deleting one, so look it up instead.
1025 LookupGD = GlobalDecl(DD, Dtor_Deleting);
1028 MicrosoftVTableContext::MethodVFTableLocation ML =
1029 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD);
1030 CharUnits Adjustment = ML.VFPtrOffset;
1032 // Normal virtual instance methods need to adjust from the vfptr that first
1033 // defined the virtual method to the virtual base subobject, but destructors
1034 // do not. The vector deleting destructor thunk applies this adjustment for
1036 if (isa<CXXDestructorDecl>(MD))
1037 Adjustment = CharUnits::Zero();
1040 const ASTRecordLayout &DerivedLayout =
1041 CGM.getContext().getASTRecordLayout(MD->getParent());
1042 Adjustment += DerivedLayout.getVBaseClassOffset(ML.VBase);
1048 llvm::Value *MicrosoftCXXABI::adjustThisArgumentForVirtualFunctionCall(
1049 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This, bool VirtualCall) {
1051 // If the call of a virtual function is not virtual, we just have to
1052 // compensate for the adjustment the virtual function does in its prologue.
1053 CharUnits Adjustment = getVirtualFunctionPrologueThisAdjustment(GD);
1054 if (Adjustment.isZero())
1057 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
1058 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS);
1059 This = CGF.Builder.CreateBitCast(This, charPtrTy);
1060 assert(Adjustment.isPositive());
1061 return CGF.Builder.CreateConstGEP1_32(This, Adjustment.getQuantity());
1064 GD = GD.getCanonicalDecl();
1065 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1067 GlobalDecl LookupGD = GD;
1068 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1069 // Complete dtors take a pointer to the complete object,
1070 // thus don't need adjustment.
1071 if (GD.getDtorType() == Dtor_Complete)
1074 // There's only Dtor_Deleting in vftable but it shares the this adjustment
1075 // with the base one, so look up the deleting one instead.
1076 LookupGD = GlobalDecl(DD, Dtor_Deleting);
1078 MicrosoftVTableContext::MethodVFTableLocation ML =
1079 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD);
1081 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
1082 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS);
1083 CharUnits StaticOffset = ML.VFPtrOffset;
1085 // Base destructors expect 'this' to point to the beginning of the base
1086 // subobject, not the first vfptr that happens to contain the virtual dtor.
1087 // However, we still need to apply the virtual base adjustment.
1088 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
1089 StaticOffset = CharUnits::Zero();
1092 This = CGF.Builder.CreateBitCast(This, charPtrTy);
1093 llvm::Value *VBaseOffset =
1094 GetVirtualBaseClassOffset(CGF, This, MD->getParent(), ML.VBase);
1095 This = CGF.Builder.CreateInBoundsGEP(This, VBaseOffset);
1097 if (!StaticOffset.isZero()) {
1098 assert(StaticOffset.isPositive());
1099 This = CGF.Builder.CreateBitCast(This, charPtrTy);
1101 // Non-virtual adjustment might result in a pointer outside the allocated
1102 // object, e.g. if the final overrider class is laid out after the virtual
1103 // base that declares a method in the most derived class.
1104 // FIXME: Update the code that emits this adjustment in thunks prologues.
1105 This = CGF.Builder.CreateConstGEP1_32(This, StaticOffset.getQuantity());
1107 This = CGF.Builder.CreateConstInBoundsGEP1_32(This,
1108 StaticOffset.getQuantity());
1114 void MicrosoftCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1116 FunctionArgList &Params) {
1117 ASTContext &Context = getContext();
1118 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
1119 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
1120 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
1121 ImplicitParamDecl *IsMostDerived
1122 = ImplicitParamDecl::Create(Context, nullptr,
1123 CGF.CurGD.getDecl()->getLocation(),
1124 &Context.Idents.get("is_most_derived"),
1126 // The 'most_derived' parameter goes second if the ctor is variadic and last
1127 // if it's not. Dtors can't be variadic.
1128 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
1129 if (FPT->isVariadic())
1130 Params.insert(Params.begin() + 1, IsMostDerived);
1132 Params.push_back(IsMostDerived);
1133 getStructorImplicitParamDecl(CGF) = IsMostDerived;
1134 } else if (isDeletingDtor(CGF.CurGD)) {
1135 ImplicitParamDecl *ShouldDelete
1136 = ImplicitParamDecl::Create(Context, nullptr,
1137 CGF.CurGD.getDecl()->getLocation(),
1138 &Context.Idents.get("should_call_delete"),
1140 Params.push_back(ShouldDelete);
1141 getStructorImplicitParamDecl(CGF) = ShouldDelete;
1145 llvm::Value *MicrosoftCXXABI::adjustThisParameterInVirtualFunctionPrologue(
1146 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) {
1147 // In this ABI, every virtual function takes a pointer to one of the
1148 // subobjects that first defines it as the 'this' parameter, rather than a
1149 // pointer to the final overrider subobject. Thus, we need to adjust it back
1150 // to the final overrider subobject before use.
1151 // See comments in the MicrosoftVFTableContext implementation for the details.
1152 CharUnits Adjustment = getVirtualFunctionPrologueThisAdjustment(GD);
1153 if (Adjustment.isZero())
1156 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
1157 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS),
1158 *thisTy = This->getType();
1160 This = CGF.Builder.CreateBitCast(This, charPtrTy);
1161 assert(Adjustment.isPositive());
1163 CGF.Builder.CreateConstInBoundsGEP1_32(This, -Adjustment.getQuantity());
1164 return CGF.Builder.CreateBitCast(This, thisTy);
1167 void MicrosoftCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
1170 /// If this is a function that the ABI specifies returns 'this', initialize
1171 /// the return slot to 'this' at the start of the function.
1173 /// Unlike the setting of return types, this is done within the ABI
1174 /// implementation instead of by clients of CGCXXABI because:
1175 /// 1) getThisValue is currently protected
1176 /// 2) in theory, an ABI could implement 'this' returns some other way;
1177 /// HasThisReturn only specifies a contract, not the implementation
1178 if (HasThisReturn(CGF.CurGD))
1179 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
1180 else if (hasMostDerivedReturn(CGF.CurGD))
1181 CGF.Builder.CreateStore(CGF.EmitCastToVoidPtr(getThisValue(CGF)),
1184 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
1185 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
1186 assert(getStructorImplicitParamDecl(CGF) &&
1187 "no implicit parameter for a constructor with virtual bases?");
1188 getStructorImplicitParamValue(CGF)
1189 = CGF.Builder.CreateLoad(
1190 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
1194 if (isDeletingDtor(CGF.CurGD)) {
1195 assert(getStructorImplicitParamDecl(CGF) &&
1196 "no implicit parameter for a deleting destructor?");
1197 getStructorImplicitParamValue(CGF)
1198 = CGF.Builder.CreateLoad(
1199 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
1200 "should_call_delete");
1204 unsigned MicrosoftCXXABI::addImplicitConstructorArgs(
1205 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1206 bool ForVirtualBase, bool Delegating, CallArgList &Args) {
1207 assert(Type == Ctor_Complete || Type == Ctor_Base);
1209 // Check if we need a 'most_derived' parameter.
1210 if (!D->getParent()->getNumVBases())
1213 // Add the 'most_derived' argument second if we are variadic or last if not.
1214 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
1215 llvm::Value *MostDerivedArg =
1216 llvm::ConstantInt::get(CGM.Int32Ty, Type == Ctor_Complete);
1217 RValue RV = RValue::get(MostDerivedArg);
1218 if (MostDerivedArg) {
1219 if (FPT->isVariadic())
1220 Args.insert(Args.begin() + 1,
1221 CallArg(RV, getContext().IntTy, /*needscopy=*/false));
1223 Args.add(RV, getContext().IntTy);
1226 return 1; // Added one arg.
1229 void MicrosoftCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1230 const CXXDestructorDecl *DD,
1231 CXXDtorType Type, bool ForVirtualBase,
1232 bool Delegating, llvm::Value *This) {
1233 llvm::Value *Callee = CGM.getAddrOfCXXStructor(DD, getFromDtorType(Type));
1235 if (DD->isVirtual()) {
1236 assert(Type != CXXDtorType::Dtor_Deleting &&
1237 "The deleting destructor should only be called via a virtual call");
1238 This = adjustThisArgumentForVirtualFunctionCall(CGF, GlobalDecl(DD, Type),
1242 CGF.EmitCXXStructorCall(DD, Callee, ReturnValueSlot(), This,
1243 /*ImplicitParam=*/nullptr,
1244 /*ImplicitParamTy=*/QualType(), nullptr,
1245 getFromDtorType(Type));
1248 void MicrosoftCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1249 const CXXRecordDecl *RD) {
1250 MicrosoftVTableContext &VFTContext = CGM.getMicrosoftVTableContext();
1251 const VPtrInfoVector &VFPtrs = VFTContext.getVFPtrOffsets(RD);
1253 for (VPtrInfo *Info : VFPtrs) {
1254 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, Info->FullOffsetInMDC);
1255 if (VTable->hasInitializer())
1258 llvm::Constant *RTTI = getContext().getLangOpts().RTTIData
1259 ? getMSCompleteObjectLocator(RD, Info)
1262 const VTableLayout &VTLayout =
1263 VFTContext.getVFTableLayout(RD, Info->FullOffsetInMDC);
1264 llvm::Constant *Init = CGVT.CreateVTableInitializer(
1265 RD, VTLayout.vtable_component_begin(),
1266 VTLayout.getNumVTableComponents(), VTLayout.vtable_thunk_begin(),
1267 VTLayout.getNumVTableThunks(), RTTI);
1269 VTable->setInitializer(Init);
1273 llvm::Value *MicrosoftCXXABI::getVTableAddressPointInStructor(
1274 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1275 const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) {
1276 NeedsVirtualOffset = (NearestVBase != nullptr);
1278 (void)getAddrOfVTable(VTableClass, Base.getBaseOffset());
1279 VFTableIdTy ID(VTableClass, Base.getBaseOffset());
1280 llvm::GlobalValue *VTableAddressPoint = VFTablesMap[ID];
1281 if (!VTableAddressPoint) {
1282 assert(Base.getBase()->getNumVBases() &&
1283 !CGM.getContext().getASTRecordLayout(Base.getBase()).hasOwnVFPtr());
1285 return VTableAddressPoint;
1288 static void mangleVFTableName(MicrosoftMangleContext &MangleContext,
1289 const CXXRecordDecl *RD, const VPtrInfo *VFPtr,
1290 SmallString<256> &Name) {
1291 llvm::raw_svector_ostream Out(Name);
1292 MangleContext.mangleCXXVFTable(RD, VFPtr->MangledPath, Out);
1295 llvm::Constant *MicrosoftCXXABI::getVTableAddressPointForConstExpr(
1296 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1297 (void)getAddrOfVTable(VTableClass, Base.getBaseOffset());
1298 VFTableIdTy ID(VTableClass, Base.getBaseOffset());
1299 llvm::GlobalValue *VFTable = VFTablesMap[ID];
1300 assert(VFTable && "Couldn't find a vftable for the given base?");
1304 llvm::GlobalVariable *MicrosoftCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1305 CharUnits VPtrOffset) {
1306 // getAddrOfVTable may return 0 if asked to get an address of a vtable which
1307 // shouldn't be used in the given record type. We want to cache this result in
1308 // VFTablesMap, thus a simple zero check is not sufficient.
1309 VFTableIdTy ID(RD, VPtrOffset);
1310 VTablesMapTy::iterator I;
1312 std::tie(I, Inserted) = VTablesMap.insert(std::make_pair(ID, nullptr));
1316 llvm::GlobalVariable *&VTable = I->second;
1318 MicrosoftVTableContext &VTContext = CGM.getMicrosoftVTableContext();
1319 const VPtrInfoVector &VFPtrs = VTContext.getVFPtrOffsets(RD);
1321 if (DeferredVFTables.insert(RD).second) {
1322 // We haven't processed this record type before.
1323 // Queue up this v-table for possible deferred emission.
1324 CGM.addDeferredVTable(RD);
1327 // Create all the vftables at once in order to make sure each vftable has
1328 // a unique mangled name.
1329 llvm::StringSet<> ObservedMangledNames;
1330 for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) {
1331 SmallString<256> Name;
1332 mangleVFTableName(getMangleContext(), RD, VFPtrs[J], Name);
1333 if (!ObservedMangledNames.insert(Name.str()).second)
1334 llvm_unreachable("Already saw this mangling before?");
1339 for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) {
1340 if (VFPtrs[J]->FullOffsetInMDC != VPtrOffset)
1342 SmallString<256> VFTableName;
1343 mangleVFTableName(getMangleContext(), RD, VFPtrs[J], VFTableName);
1344 StringRef VTableName = VFTableName;
1346 uint64_t NumVTableSlots =
1347 VTContext.getVFTableLayout(RD, VFPtrs[J]->FullOffsetInMDC)
1348 .getNumVTableComponents();
1349 llvm::GlobalValue::LinkageTypes VTableLinkage =
1350 llvm::GlobalValue::ExternalLinkage;
1351 llvm::ArrayType *VTableType =
1352 llvm::ArrayType::get(CGM.Int8PtrTy, NumVTableSlots);
1353 if (getContext().getLangOpts().RTTIData) {
1354 VTableLinkage = llvm::GlobalValue::PrivateLinkage;
1358 VTable = CGM.getModule().getNamedGlobal(VFTableName);
1360 // Create a backing variable for the contents of VTable. The VTable may
1361 // or may not include space for a pointer to RTTI data.
1362 llvm::GlobalValue *VFTable = VTable = new llvm::GlobalVariable(
1363 CGM.getModule(), VTableType, /*isConstant=*/true, VTableLinkage,
1364 /*Initializer=*/nullptr, VTableName);
1365 VTable->setUnnamedAddr(true);
1367 // Only insert a pointer into the VFTable for RTTI data if we are not
1368 // importing it. We never reference the RTTI data directly so there is no
1369 // need to make room for it.
1370 if (getContext().getLangOpts().RTTIData &&
1371 !RD->hasAttr<DLLImportAttr>()) {
1372 llvm::Value *GEPIndices[] = {llvm::ConstantInt::get(CGM.IntTy, 0),
1373 llvm::ConstantInt::get(CGM.IntTy, 1)};
1374 // Create a GEP which points just after the first entry in the VFTable,
1375 // this should be the location of the first virtual method.
1376 llvm::Constant *VTableGEP =
1377 llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, GEPIndices);
1378 // The symbol for the VFTable is an alias to the GEP. It is
1379 // transparent, to other modules, what the nature of this symbol is; all
1380 // that matters is that the alias be the address of the first virtual
1382 VFTable = llvm::GlobalAlias::create(
1383 cast<llvm::SequentialType>(VTableGEP->getType())->getElementType(),
1384 /*AddressSpace=*/0, llvm::GlobalValue::ExternalLinkage,
1385 VFTableName.str(), VTableGEP, &CGM.getModule());
1387 // We don't need a GlobalAlias to be a symbol for the VTable if we won't
1388 // be referencing any RTTI data. The GlobalVariable will end up being
1389 // an appropriate definition of the VFTable.
1390 VTable->setName(VFTableName.str());
1393 VFTable->setUnnamedAddr(true);
1394 if (RD->hasAttr<DLLImportAttr>())
1395 VFTable->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1396 else if (RD->hasAttr<DLLExportAttr>())
1397 VFTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1399 llvm::GlobalValue::LinkageTypes VFTableLinkage = CGM.getVTableLinkage(RD);
1400 if (VFTable != VTable) {
1401 if (llvm::GlobalValue::isAvailableExternallyLinkage(VFTableLinkage)) {
1402 // AvailableExternally implies that we grabbed the data from another
1403 // executable. No need to stick the alias in a Comdat.
1404 } else if (llvm::GlobalValue::isInternalLinkage(VFTableLinkage) ||
1405 llvm::GlobalValue::isWeakODRLinkage(VFTableLinkage) ||
1406 llvm::GlobalValue::isLinkOnceODRLinkage(VFTableLinkage)) {
1407 // The alias is going to be dropped into a Comdat, no need to make it
1409 if (!llvm::GlobalValue::isInternalLinkage(VFTableLinkage))
1410 VFTableLinkage = llvm::GlobalValue::ExternalLinkage;
1412 CGM.getModule().getOrInsertComdat(VFTable->getName());
1413 // We must indicate which VFTable is larger to support linking between
1414 // translation units which do and do not have RTTI data. The largest
1415 // VFTable contains the RTTI data; translation units which reference
1416 // the smaller VFTable always reference it relative to the first
1418 C->setSelectionKind(llvm::Comdat::Largest);
1419 VTable->setComdat(C);
1421 llvm_unreachable("unexpected linkage for vftable!");
1424 VFTable->setLinkage(VFTableLinkage);
1425 CGM.setGlobalVisibility(VFTable, RD);
1426 VFTablesMap[ID] = VFTable;
1434 llvm::Value *MicrosoftCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1438 GD = GD.getCanonicalDecl();
1439 CGBuilderTy &Builder = CGF.Builder;
1441 Ty = Ty->getPointerTo()->getPointerTo();
1443 adjustThisArgumentForVirtualFunctionCall(CGF, GD, This, true);
1444 llvm::Value *VTable = CGF.GetVTablePtr(VPtr, Ty);
1446 MicrosoftVTableContext::MethodVFTableLocation ML =
1447 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD);
1448 llvm::Value *VFuncPtr =
1449 Builder.CreateConstInBoundsGEP1_64(VTable, ML.Index, "vfn");
1450 return Builder.CreateLoad(VFuncPtr);
1453 llvm::Value *MicrosoftCXXABI::EmitVirtualDestructorCall(
1454 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
1455 llvm::Value *This, const CXXMemberCallExpr *CE) {
1456 assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
1457 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1459 // We have only one destructor in the vftable but can get both behaviors
1460 // by passing an implicit int parameter.
1461 GlobalDecl GD(Dtor, Dtor_Deleting);
1462 const CGFunctionInfo *FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
1463 Dtor, StructorType::Deleting);
1464 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
1465 llvm::Value *Callee = getVirtualFunctionPointer(CGF, GD, This, Ty);
1467 ASTContext &Context = CGF.getContext();
1468 llvm::Value *ImplicitParam = llvm::ConstantInt::get(
1469 llvm::IntegerType::getInt32Ty(CGF.getLLVMContext()),
1470 DtorType == Dtor_Deleting);
1472 This = adjustThisArgumentForVirtualFunctionCall(CGF, GD, This, true);
1473 RValue RV = CGF.EmitCXXStructorCall(Dtor, Callee, ReturnValueSlot(), This,
1474 ImplicitParam, Context.IntTy, CE,
1475 StructorType::Deleting);
1476 return RV.getScalarVal();
1479 const VBTableGlobals &
1480 MicrosoftCXXABI::enumerateVBTables(const CXXRecordDecl *RD) {
1481 // At this layer, we can key the cache off of a single class, which is much
1482 // easier than caching each vbtable individually.
1483 llvm::DenseMap<const CXXRecordDecl*, VBTableGlobals>::iterator Entry;
1485 std::tie(Entry, Added) =
1486 VBTablesMap.insert(std::make_pair(RD, VBTableGlobals()));
1487 VBTableGlobals &VBGlobals = Entry->second;
1491 MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext();
1492 VBGlobals.VBTables = &Context.enumerateVBTables(RD);
1494 // Cache the globals for all vbtables so we don't have to recompute the
1496 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
1497 for (VPtrInfoVector::const_iterator I = VBGlobals.VBTables->begin(),
1498 E = VBGlobals.VBTables->end();
1500 VBGlobals.Globals.push_back(getAddrOfVBTable(**I, RD, Linkage));
1506 llvm::Function *MicrosoftCXXABI::EmitVirtualMemPtrThunk(
1507 const CXXMethodDecl *MD,
1508 const MicrosoftVTableContext::MethodVFTableLocation &ML) {
1509 assert(!isa<CXXConstructorDecl>(MD) && !isa<CXXDestructorDecl>(MD) &&
1510 "can't form pointers to ctors or virtual dtors");
1512 // Calculate the mangled name.
1513 SmallString<256> ThunkName;
1514 llvm::raw_svector_ostream Out(ThunkName);
1515 getMangleContext().mangleVirtualMemPtrThunk(MD, Out);
1518 // If the thunk has been generated previously, just return it.
1519 if (llvm::GlobalValue *GV = CGM.getModule().getNamedValue(ThunkName))
1520 return cast<llvm::Function>(GV);
1522 // Create the llvm::Function.
1523 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeMSMemberPointerThunk(MD);
1524 llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo);
1525 llvm::Function *ThunkFn =
1526 llvm::Function::Create(ThunkTy, llvm::Function::ExternalLinkage,
1527 ThunkName.str(), &CGM.getModule());
1528 assert(ThunkFn->getName() == ThunkName && "name was uniqued!");
1530 ThunkFn->setLinkage(MD->isExternallyVisible()
1531 ? llvm::GlobalValue::LinkOnceODRLinkage
1532 : llvm::GlobalValue::InternalLinkage);
1534 CGM.SetLLVMFunctionAttributes(MD, FnInfo, ThunkFn);
1535 CGM.SetLLVMFunctionAttributesForDefinition(MD, ThunkFn);
1537 // These thunks can be compared, so they are not unnamed.
1538 ThunkFn->setUnnamedAddr(false);
1541 CodeGenFunction CGF(CGM);
1542 CGF.CurGD = GlobalDecl(MD);
1543 CGF.CurFuncIsThunk = true;
1545 // Build FunctionArgs, but only include the implicit 'this' parameter
1547 FunctionArgList FunctionArgs;
1548 buildThisParam(CGF, FunctionArgs);
1550 // Start defining the function.
1551 CGF.StartFunction(GlobalDecl(), FnInfo.getReturnType(), ThunkFn, FnInfo,
1552 FunctionArgs, MD->getLocation(), SourceLocation());
1555 // Load the vfptr and then callee from the vftable. The callee should have
1556 // adjusted 'this' so that the vfptr is at offset zero.
1557 llvm::Value *VTable = CGF.GetVTablePtr(
1558 getThisValue(CGF), ThunkTy->getPointerTo()->getPointerTo());
1559 llvm::Value *VFuncPtr =
1560 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, ML.Index, "vfn");
1561 llvm::Value *Callee = CGF.Builder.CreateLoad(VFuncPtr);
1563 CGF.EmitMustTailThunk(MD, getThisValue(CGF), Callee);
1568 void MicrosoftCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
1569 const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
1570 for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) {
1571 const VPtrInfo *VBT = (*VBGlobals.VBTables)[I];
1572 llvm::GlobalVariable *GV = VBGlobals.Globals[I];
1573 emitVBTableDefinition(*VBT, RD, GV);
1577 llvm::GlobalVariable *
1578 MicrosoftCXXABI::getAddrOfVBTable(const VPtrInfo &VBT, const CXXRecordDecl *RD,
1579 llvm::GlobalVariable::LinkageTypes Linkage) {
1580 SmallString<256> OutName;
1581 llvm::raw_svector_ostream Out(OutName);
1582 getMangleContext().mangleCXXVBTable(RD, VBT.MangledPath, Out);
1584 StringRef Name = OutName.str();
1586 llvm::ArrayType *VBTableType =
1587 llvm::ArrayType::get(CGM.IntTy, 1 + VBT.ReusingBase->getNumVBases());
1589 assert(!CGM.getModule().getNamedGlobal(Name) &&
1590 "vbtable with this name already exists: mangling bug?");
1591 llvm::GlobalVariable *GV =
1592 CGM.CreateOrReplaceCXXRuntimeVariable(Name, VBTableType, Linkage);
1593 GV->setUnnamedAddr(true);
1595 if (RD->hasAttr<DLLImportAttr>())
1596 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1597 else if (RD->hasAttr<DLLExportAttr>())
1598 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1603 void MicrosoftCXXABI::emitVBTableDefinition(const VPtrInfo &VBT,
1604 const CXXRecordDecl *RD,
1605 llvm::GlobalVariable *GV) const {
1606 const CXXRecordDecl *ReusingBase = VBT.ReusingBase;
1608 assert(RD->getNumVBases() && ReusingBase->getNumVBases() &&
1609 "should only emit vbtables for classes with vbtables");
1611 const ASTRecordLayout &BaseLayout =
1612 CGM.getContext().getASTRecordLayout(VBT.BaseWithVPtr);
1613 const ASTRecordLayout &DerivedLayout =
1614 CGM.getContext().getASTRecordLayout(RD);
1616 SmallVector<llvm::Constant *, 4> Offsets(1 + ReusingBase->getNumVBases(),
1619 // The offset from ReusingBase's vbptr to itself always leads.
1620 CharUnits VBPtrOffset = BaseLayout.getVBPtrOffset();
1621 Offsets[0] = llvm::ConstantInt::get(CGM.IntTy, -VBPtrOffset.getQuantity());
1623 MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext();
1624 for (const auto &I : ReusingBase->vbases()) {
1625 const CXXRecordDecl *VBase = I.getType()->getAsCXXRecordDecl();
1626 CharUnits Offset = DerivedLayout.getVBaseClassOffset(VBase);
1627 assert(!Offset.isNegative());
1629 // Make it relative to the subobject vbptr.
1630 CharUnits CompleteVBPtrOffset = VBT.NonVirtualOffset + VBPtrOffset;
1631 if (VBT.getVBaseWithVPtr())
1632 CompleteVBPtrOffset +=
1633 DerivedLayout.getVBaseClassOffset(VBT.getVBaseWithVPtr());
1634 Offset -= CompleteVBPtrOffset;
1636 unsigned VBIndex = Context.getVBTableIndex(ReusingBase, VBase);
1637 assert(Offsets[VBIndex] == nullptr && "The same vbindex seen twice?");
1638 Offsets[VBIndex] = llvm::ConstantInt::get(CGM.IntTy, Offset.getQuantity());
1641 assert(Offsets.size() ==
1642 cast<llvm::ArrayType>(cast<llvm::PointerType>(GV->getType())
1643 ->getElementType())->getNumElements());
1644 llvm::ArrayType *VBTableType =
1645 llvm::ArrayType::get(CGM.IntTy, Offsets.size());
1646 llvm::Constant *Init = llvm::ConstantArray::get(VBTableType, Offsets);
1647 GV->setInitializer(Init);
1649 // Set the right visibility.
1650 CGM.setGlobalVisibility(GV, RD);
1653 llvm::Value *MicrosoftCXXABI::performThisAdjustment(CodeGenFunction &CGF,
1655 const ThisAdjustment &TA) {
1659 llvm::Value *V = CGF.Builder.CreateBitCast(This, CGF.Int8PtrTy);
1661 if (!TA.Virtual.isEmpty()) {
1662 assert(TA.Virtual.Microsoft.VtordispOffset < 0);
1663 // Adjust the this argument based on the vtordisp value.
1664 llvm::Value *VtorDispPtr =
1665 CGF.Builder.CreateConstGEP1_32(V, TA.Virtual.Microsoft.VtordispOffset);
1667 CGF.Builder.CreateBitCast(VtorDispPtr, CGF.Int32Ty->getPointerTo());
1668 llvm::Value *VtorDisp = CGF.Builder.CreateLoad(VtorDispPtr, "vtordisp");
1669 V = CGF.Builder.CreateGEP(V, CGF.Builder.CreateNeg(VtorDisp));
1671 if (TA.Virtual.Microsoft.VBPtrOffset) {
1672 // If the final overrider is defined in a virtual base other than the one
1673 // that holds the vfptr, we have to use a vtordispex thunk which looks up
1674 // the vbtable of the derived class.
1675 assert(TA.Virtual.Microsoft.VBPtrOffset > 0);
1676 assert(TA.Virtual.Microsoft.VBOffsetOffset >= 0);
1678 llvm::Value *VBaseOffset =
1679 GetVBaseOffsetFromVBPtr(CGF, V, -TA.Virtual.Microsoft.VBPtrOffset,
1680 TA.Virtual.Microsoft.VBOffsetOffset, &VBPtr);
1681 V = CGF.Builder.CreateInBoundsGEP(VBPtr, VBaseOffset);
1685 if (TA.NonVirtual) {
1686 // Non-virtual adjustment might result in a pointer outside the allocated
1687 // object, e.g. if the final overrider class is laid out after the virtual
1688 // base that declares a method in the most derived class.
1689 V = CGF.Builder.CreateConstGEP1_32(V, TA.NonVirtual);
1692 // Don't need to bitcast back, the call CodeGen will handle this.
1697 MicrosoftCXXABI::performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
1698 const ReturnAdjustment &RA) {
1702 llvm::Value *V = CGF.Builder.CreateBitCast(Ret, CGF.Int8PtrTy);
1704 if (RA.Virtual.Microsoft.VBIndex) {
1705 assert(RA.Virtual.Microsoft.VBIndex > 0);
1707 getContext().getTypeSizeInChars(getContext().IntTy).getQuantity();
1709 llvm::Value *VBaseOffset =
1710 GetVBaseOffsetFromVBPtr(CGF, V, RA.Virtual.Microsoft.VBPtrOffset,
1711 IntSize * RA.Virtual.Microsoft.VBIndex, &VBPtr);
1712 V = CGF.Builder.CreateInBoundsGEP(VBPtr, VBaseOffset);
1716 V = CGF.Builder.CreateConstInBoundsGEP1_32(V, RA.NonVirtual);
1718 // Cast back to the original type.
1719 return CGF.Builder.CreateBitCast(V, Ret->getType());
1722 bool MicrosoftCXXABI::requiresArrayCookie(const CXXDeleteExpr *expr,
1723 QualType elementType) {
1724 // Microsoft seems to completely ignore the possibility of a
1725 // two-argument usual deallocation function.
1726 return elementType.isDestructedType();
1729 bool MicrosoftCXXABI::requiresArrayCookie(const CXXNewExpr *expr) {
1730 // Microsoft seems to completely ignore the possibility of a
1731 // two-argument usual deallocation function.
1732 return expr->getAllocatedType().isDestructedType();
1735 CharUnits MicrosoftCXXABI::getArrayCookieSizeImpl(QualType type) {
1736 // The array cookie is always a size_t; we then pad that out to the
1737 // alignment of the element type.
1738 ASTContext &Ctx = getContext();
1739 return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()),
1740 Ctx.getTypeAlignInChars(type));
1743 llvm::Value *MicrosoftCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1744 llvm::Value *allocPtr,
1745 CharUnits cookieSize) {
1746 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
1747 llvm::Value *numElementsPtr =
1748 CGF.Builder.CreateBitCast(allocPtr, CGF.SizeTy->getPointerTo(AS));
1749 return CGF.Builder.CreateLoad(numElementsPtr);
1752 llvm::Value* MicrosoftCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1753 llvm::Value *newPtr,
1754 llvm::Value *numElements,
1755 const CXXNewExpr *expr,
1756 QualType elementType) {
1757 assert(requiresArrayCookie(expr));
1759 // The size of the cookie.
1760 CharUnits cookieSize = getArrayCookieSizeImpl(elementType);
1762 // Compute an offset to the cookie.
1763 llvm::Value *cookiePtr = newPtr;
1765 // Write the number of elements into the appropriate slot.
1766 unsigned AS = newPtr->getType()->getPointerAddressSpace();
1767 llvm::Value *numElementsPtr
1768 = CGF.Builder.CreateBitCast(cookiePtr, CGF.SizeTy->getPointerTo(AS));
1769 CGF.Builder.CreateStore(numElements, numElementsPtr);
1771 // Finally, compute a pointer to the actual data buffer by skipping
1772 // over the cookie completely.
1773 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
1774 cookieSize.getQuantity());
1777 static void emitGlobalDtorWithTLRegDtor(CodeGenFunction &CGF, const VarDecl &VD,
1778 llvm::Constant *Dtor,
1779 llvm::Constant *Addr) {
1780 // Create a function which calls the destructor.
1781 llvm::Constant *DtorStub = CGF.createAtExitStub(VD, Dtor, Addr);
1783 // extern "C" int __tlregdtor(void (*f)(void));
1784 llvm::FunctionType *TLRegDtorTy = llvm::FunctionType::get(
1785 CGF.IntTy, DtorStub->getType(), /*IsVarArg=*/false);
1787 llvm::Constant *TLRegDtor =
1788 CGF.CGM.CreateRuntimeFunction(TLRegDtorTy, "__tlregdtor");
1789 if (llvm::Function *TLRegDtorFn = dyn_cast<llvm::Function>(TLRegDtor))
1790 TLRegDtorFn->setDoesNotThrow();
1792 CGF.EmitNounwindRuntimeCall(TLRegDtor, DtorStub);
1795 void MicrosoftCXXABI::registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
1796 llvm::Constant *Dtor,
1797 llvm::Constant *Addr) {
1799 return emitGlobalDtorWithTLRegDtor(CGF, D, Dtor, Addr);
1801 // The default behavior is to use atexit.
1802 CGF.registerGlobalDtorWithAtExit(D, Dtor, Addr);
1805 void MicrosoftCXXABI::EmitThreadLocalInitFuncs(
1807 ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *>>
1809 ArrayRef<llvm::Function *> CXXThreadLocalInits,
1810 ArrayRef<llvm::GlobalVariable *> CXXThreadLocalInitVars) {
1811 // This will create a GV in the .CRT$XDU section. It will point to our
1812 // initialization function. The CRT will call all of these function
1813 // pointers at start-up time and, eventually, at thread-creation time.
1814 auto AddToXDU = [&CGM](llvm::Function *InitFunc) {
1815 llvm::GlobalVariable *InitFuncPtr = new llvm::GlobalVariable(
1816 CGM.getModule(), InitFunc->getType(), /*IsConstant=*/true,
1817 llvm::GlobalVariable::InternalLinkage, InitFunc,
1818 Twine(InitFunc->getName(), "$initializer$"));
1819 InitFuncPtr->setSection(".CRT$XDU");
1820 // This variable has discardable linkage, we have to add it to @llvm.used to
1821 // ensure it won't get discarded.
1822 CGM.addUsedGlobal(InitFuncPtr);
1826 std::vector<llvm::Function *> NonComdatInits;
1827 for (size_t I = 0, E = CXXThreadLocalInitVars.size(); I != E; ++I) {
1828 llvm::GlobalVariable *GV = CXXThreadLocalInitVars[I];
1829 llvm::Function *F = CXXThreadLocalInits[I];
1831 // If the GV is already in a comdat group, then we have to join it.
1832 if (llvm::Comdat *C = GV->getComdat())
1833 AddToXDU(F)->setComdat(C);
1835 NonComdatInits.push_back(F);
1838 if (!NonComdatInits.empty()) {
1839 llvm::FunctionType *FTy =
1840 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
1841 llvm::Function *InitFunc = CGM.CreateGlobalInitOrDestructFunction(
1842 FTy, "__tls_init", SourceLocation(),
1844 CodeGenFunction(CGM).GenerateCXXGlobalInitFunc(InitFunc, NonComdatInits);
1850 LValue MicrosoftCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
1852 QualType LValType) {
1853 CGF.CGM.ErrorUnsupported(VD, "thread wrappers");
1857 void MicrosoftCXXABI::EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
1858 llvm::GlobalVariable *GV,
1860 // MSVC only uses guards for static locals.
1861 if (!D.isStaticLocal()) {
1862 assert(GV->hasWeakLinkage() || GV->hasLinkOnceLinkage());
1863 // GlobalOpt is allowed to discard the initializer, so use linkonce_odr.
1864 CGF.CurFn->setLinkage(llvm::GlobalValue::LinkOnceODRLinkage);
1865 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
1869 // MSVC always uses an i32 bitfield to guard initialization, which is *not*
1870 // threadsafe. Since the user may be linking in inline functions compiled by
1871 // cl.exe, there's no reason to provide a false sense of security by using
1872 // critical sections here.
1875 CGM.ErrorUnsupported(&D, "dynamic TLS initialization");
1877 CGBuilderTy &Builder = CGF.Builder;
1878 llvm::IntegerType *GuardTy = CGF.Int32Ty;
1879 llvm::ConstantInt *Zero = llvm::ConstantInt::get(GuardTy, 0);
1881 // Get the guard variable for this function if we have one already.
1882 GuardInfo *GI = &GuardVariableMap[D.getDeclContext()];
1885 if (D.isStaticLocal() && D.isExternallyVisible()) {
1886 // Externally visible variables have to be numbered in Sema to properly
1887 // handle unreachable VarDecls.
1888 BitIndex = getContext().getStaticLocalNumber(&D);
1889 assert(BitIndex > 0);
1892 // Non-externally visible variables are numbered here in CodeGen.
1893 BitIndex = GI->BitIndex++;
1896 if (BitIndex >= 32) {
1897 if (D.isExternallyVisible())
1898 ErrorUnsupportedABI(CGF, "more than 32 guarded initializations");
1900 GI->Guard = nullptr;
1903 // Lazily create the i32 bitfield for this function.
1905 // Mangle the name for the guard.
1906 SmallString<256> GuardName;
1908 llvm::raw_svector_ostream Out(GuardName);
1909 getMangleContext().mangleStaticGuardVariable(&D, Out);
1913 // Create the guard variable with a zero-initializer. Just absorb linkage,
1914 // visibility and dll storage class from the guarded variable.
1916 new llvm::GlobalVariable(CGM.getModule(), GuardTy, false,
1917 GV->getLinkage(), Zero, GuardName.str());
1918 GI->Guard->setVisibility(GV->getVisibility());
1919 GI->Guard->setDLLStorageClass(GV->getDLLStorageClass());
1921 assert(GI->Guard->getLinkage() == GV->getLinkage() &&
1922 "static local from the same function had different linkage");
1925 // Pseudo code for the test:
1926 // if (!(GuardVar & MyGuardBit)) {
1927 // GuardVar |= MyGuardBit;
1928 // ... initialize the object ...;
1931 // Test our bit from the guard variable.
1932 llvm::ConstantInt *Bit = llvm::ConstantInt::get(GuardTy, 1U << BitIndex);
1933 llvm::LoadInst *LI = Builder.CreateLoad(GI->Guard);
1934 llvm::Value *IsInitialized =
1935 Builder.CreateICmpNE(Builder.CreateAnd(LI, Bit), Zero);
1936 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1937 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1938 Builder.CreateCondBr(IsInitialized, EndBlock, InitBlock);
1940 // Set our bit in the guard variable and emit the initializer and add a global
1941 // destructor if appropriate.
1942 CGF.EmitBlock(InitBlock);
1943 Builder.CreateStore(Builder.CreateOr(LI, Bit), GI->Guard);
1944 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
1945 Builder.CreateBr(EndBlock);
1948 CGF.EmitBlock(EndBlock);
1951 bool MicrosoftCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
1952 // Null-ness for function memptrs only depends on the first field, which is
1953 // the function pointer. The rest don't matter, so we can zero initialize.
1954 if (MPT->isMemberFunctionPointer())
1957 // The virtual base adjustment field is always -1 for null, so if we have one
1958 // we can't zero initialize. The field offset is sometimes also -1 if 0 is a
1959 // valid field offset.
1960 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
1961 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
1962 return (!MSInheritanceAttr::hasVBTableOffsetField(Inheritance) &&
1963 RD->nullFieldOffsetIsZero());
1967 MicrosoftCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
1968 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
1969 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
1970 llvm::SmallVector<llvm::Type *, 4> fields;
1971 if (MPT->isMemberFunctionPointer())
1972 fields.push_back(CGM.VoidPtrTy); // FunctionPointerOrVirtualThunk
1974 fields.push_back(CGM.IntTy); // FieldOffset
1976 if (MSInheritanceAttr::hasNVOffsetField(MPT->isMemberFunctionPointer(),
1978 fields.push_back(CGM.IntTy);
1979 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance))
1980 fields.push_back(CGM.IntTy);
1981 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance))
1982 fields.push_back(CGM.IntTy); // VirtualBaseAdjustmentOffset
1984 if (fields.size() == 1)
1986 return llvm::StructType::get(CGM.getLLVMContext(), fields);
1989 void MicrosoftCXXABI::
1990 GetNullMemberPointerFields(const MemberPointerType *MPT,
1991 llvm::SmallVectorImpl<llvm::Constant *> &fields) {
1992 assert(fields.empty());
1993 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
1994 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
1995 if (MPT->isMemberFunctionPointer()) {
1996 // FunctionPointerOrVirtualThunk
1997 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
1999 if (RD->nullFieldOffsetIsZero())
2000 fields.push_back(getZeroInt()); // FieldOffset
2002 fields.push_back(getAllOnesInt()); // FieldOffset
2005 if (MSInheritanceAttr::hasNVOffsetField(MPT->isMemberFunctionPointer(),
2007 fields.push_back(getZeroInt());
2008 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance))
2009 fields.push_back(getZeroInt());
2010 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance))
2011 fields.push_back(getAllOnesInt());
2015 MicrosoftCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
2016 llvm::SmallVector<llvm::Constant *, 4> fields;
2017 GetNullMemberPointerFields(MPT, fields);
2018 if (fields.size() == 1)
2020 llvm::Constant *Res = llvm::ConstantStruct::getAnon(fields);
2021 assert(Res->getType() == ConvertMemberPointerType(MPT));
2026 MicrosoftCXXABI::EmitFullMemberPointer(llvm::Constant *FirstField,
2027 bool IsMemberFunction,
2028 const CXXRecordDecl *RD,
2029 CharUnits NonVirtualBaseAdjustment)
2031 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
2033 // Single inheritance class member pointer are represented as scalars instead
2035 if (MSInheritanceAttr::hasOnlyOneField(IsMemberFunction, Inheritance))
2038 llvm::SmallVector<llvm::Constant *, 4> fields;
2039 fields.push_back(FirstField);
2041 if (MSInheritanceAttr::hasNVOffsetField(IsMemberFunction, Inheritance))
2042 fields.push_back(llvm::ConstantInt::get(
2043 CGM.IntTy, NonVirtualBaseAdjustment.getQuantity()));
2045 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance)) {
2046 CharUnits Offs = CharUnits::Zero();
2047 if (RD->getNumVBases())
2048 Offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
2049 fields.push_back(llvm::ConstantInt::get(CGM.IntTy, Offs.getQuantity()));
2052 // The rest of the fields are adjusted by conversions to a more derived class.
2053 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance))
2054 fields.push_back(getZeroInt());
2056 return llvm::ConstantStruct::getAnon(fields);
2060 MicrosoftCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
2062 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2063 llvm::Constant *FirstField =
2064 llvm::ConstantInt::get(CGM.IntTy, offset.getQuantity());
2065 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/false, RD,
2069 llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
2070 return BuildMemberPointer(MD->getParent(), MD, CharUnits::Zero());
2073 llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const APValue &MP,
2075 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
2076 const ValueDecl *MPD = MP.getMemberPointerDecl();
2078 return EmitNullMemberPointer(MPT);
2080 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
2082 // FIXME PR15713: Support virtual inheritance paths.
2084 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
2085 return BuildMemberPointer(MPT->getMostRecentCXXRecordDecl(), MD,
2088 CharUnits FieldOffset =
2089 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
2090 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
2094 MicrosoftCXXABI::BuildMemberPointer(const CXXRecordDecl *RD,
2095 const CXXMethodDecl *MD,
2096 CharUnits NonVirtualBaseAdjustment) {
2097 assert(MD->isInstance() && "Member function must not be static!");
2098 MD = MD->getCanonicalDecl();
2099 RD = RD->getMostRecentDecl();
2100 CodeGenTypes &Types = CGM.getTypes();
2102 llvm::Constant *FirstField;
2103 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
2104 if (!MD->isVirtual()) {
2106 // Check whether the function has a computable LLVM signature.
2107 if (Types.isFuncTypeConvertible(FPT)) {
2108 // The function has a computable LLVM signature; use the correct type.
2109 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
2111 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
2112 // function type is incomplete.
2115 FirstField = CGM.GetAddrOfFunction(MD, Ty);
2116 FirstField = llvm::ConstantExpr::getBitCast(FirstField, CGM.VoidPtrTy);
2118 MicrosoftVTableContext::MethodVFTableLocation ML =
2119 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(MD);
2120 if (!CGM.getTypes().isFuncTypeConvertible(
2121 MD->getType()->castAs<FunctionType>())) {
2122 CGM.ErrorUnsupported(MD, "pointer to virtual member function with "
2123 "incomplete return or parameter type");
2124 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
2125 } else if (FPT->getCallConv() == CC_X86FastCall) {
2126 CGM.ErrorUnsupported(MD, "pointer to fastcall virtual member function");
2127 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
2128 } else if (ML.VBase) {
2129 CGM.ErrorUnsupported(MD, "pointer to virtual member function overriding "
2130 "member function in virtual base class");
2131 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
2133 llvm::Function *Thunk = EmitVirtualMemPtrThunk(MD, ML);
2134 FirstField = llvm::ConstantExpr::getBitCast(Thunk, CGM.VoidPtrTy);
2135 // Include the vfptr adjustment if the method is in a non-primary vftable.
2136 NonVirtualBaseAdjustment += ML.VFPtrOffset;
2140 // The rest of the fields are common with data member pointers.
2141 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/true, RD,
2142 NonVirtualBaseAdjustment);
2145 /// Member pointers are the same if they're either bitwise identical *or* both
2146 /// null. Null-ness for function members is determined by the first field,
2147 /// while for data member pointers we must compare all fields.
2149 MicrosoftCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
2152 const MemberPointerType *MPT,
2154 CGBuilderTy &Builder = CGF.Builder;
2156 // Handle != comparisons by switching the sense of all boolean operations.
2157 llvm::ICmpInst::Predicate Eq;
2158 llvm::Instruction::BinaryOps And, Or;
2160 Eq = llvm::ICmpInst::ICMP_NE;
2161 And = llvm::Instruction::Or;
2162 Or = llvm::Instruction::And;
2164 Eq = llvm::ICmpInst::ICMP_EQ;
2165 And = llvm::Instruction::And;
2166 Or = llvm::Instruction::Or;
2169 // If this is a single field member pointer (single inheritance), this is a
2171 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2172 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
2173 if (MSInheritanceAttr::hasOnlyOneField(MPT->isMemberFunctionPointer(),
2175 return Builder.CreateICmp(Eq, L, R);
2177 // Compare the first field.
2178 llvm::Value *L0 = Builder.CreateExtractValue(L, 0, "lhs.0");
2179 llvm::Value *R0 = Builder.CreateExtractValue(R, 0, "rhs.0");
2180 llvm::Value *Cmp0 = Builder.CreateICmp(Eq, L0, R0, "memptr.cmp.first");
2182 // Compare everything other than the first field.
2183 llvm::Value *Res = nullptr;
2184 llvm::StructType *LType = cast<llvm::StructType>(L->getType());
2185 for (unsigned I = 1, E = LType->getNumElements(); I != E; ++I) {
2186 llvm::Value *LF = Builder.CreateExtractValue(L, I);
2187 llvm::Value *RF = Builder.CreateExtractValue(R, I);
2188 llvm::Value *Cmp = Builder.CreateICmp(Eq, LF, RF, "memptr.cmp.rest");
2190 Res = Builder.CreateBinOp(And, Res, Cmp);
2195 // Check if the first field is 0 if this is a function pointer.
2196 if (MPT->isMemberFunctionPointer()) {
2197 // (l1 == r1 && ...) || l0 == 0
2198 llvm::Value *Zero = llvm::Constant::getNullValue(L0->getType());
2199 llvm::Value *IsZero = Builder.CreateICmp(Eq, L0, Zero, "memptr.cmp.iszero");
2200 Res = Builder.CreateBinOp(Or, Res, IsZero);
2203 // Combine the comparison of the first field, which must always be true for
2204 // this comparison to succeeed.
2205 return Builder.CreateBinOp(And, Res, Cmp0, "memptr.cmp");
2209 MicrosoftCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
2210 llvm::Value *MemPtr,
2211 const MemberPointerType *MPT) {
2212 CGBuilderTy &Builder = CGF.Builder;
2213 llvm::SmallVector<llvm::Constant *, 4> fields;
2214 // We only need one field for member functions.
2215 if (MPT->isMemberFunctionPointer())
2216 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
2218 GetNullMemberPointerFields(MPT, fields);
2219 assert(!fields.empty());
2220 llvm::Value *FirstField = MemPtr;
2221 if (MemPtr->getType()->isStructTy())
2222 FirstField = Builder.CreateExtractValue(MemPtr, 0);
2223 llvm::Value *Res = Builder.CreateICmpNE(FirstField, fields[0], "memptr.cmp0");
2225 // For function member pointers, we only need to test the function pointer
2226 // field. The other fields if any can be garbage.
2227 if (MPT->isMemberFunctionPointer())
2230 // Otherwise, emit a series of compares and combine the results.
2231 for (int I = 1, E = fields.size(); I < E; ++I) {
2232 llvm::Value *Field = Builder.CreateExtractValue(MemPtr, I);
2233 llvm::Value *Next = Builder.CreateICmpNE(Field, fields[I], "memptr.cmp");
2234 Res = Builder.CreateOr(Res, Next, "memptr.tobool");
2239 bool MicrosoftCXXABI::MemberPointerConstantIsNull(const MemberPointerType *MPT,
2240 llvm::Constant *Val) {
2241 // Function pointers are null if the pointer in the first field is null.
2242 if (MPT->isMemberFunctionPointer()) {
2243 llvm::Constant *FirstField = Val->getType()->isStructTy() ?
2244 Val->getAggregateElement(0U) : Val;
2245 return FirstField->isNullValue();
2248 // If it's not a function pointer and it's zero initializable, we can easily
2250 if (isZeroInitializable(MPT) && Val->isNullValue())
2253 // Otherwise, break down all the fields for comparison. Hopefully these
2254 // little Constants are reused, while a big null struct might not be.
2255 llvm::SmallVector<llvm::Constant *, 4> Fields;
2256 GetNullMemberPointerFields(MPT, Fields);
2257 if (Fields.size() == 1) {
2258 assert(Val->getType()->isIntegerTy());
2259 return Val == Fields[0];
2263 for (I = 0, E = Fields.size(); I != E; ++I) {
2264 if (Val->getAggregateElement(I) != Fields[I])
2271 MicrosoftCXXABI::GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
2273 llvm::Value *VBPtrOffset,
2274 llvm::Value *VBTableOffset,
2275 llvm::Value **VBPtrOut) {
2276 CGBuilderTy &Builder = CGF.Builder;
2277 // Load the vbtable pointer from the vbptr in the instance.
2278 This = Builder.CreateBitCast(This, CGM.Int8PtrTy);
2279 llvm::Value *VBPtr =
2280 Builder.CreateInBoundsGEP(This, VBPtrOffset, "vbptr");
2281 if (VBPtrOut) *VBPtrOut = VBPtr;
2282 VBPtr = Builder.CreateBitCast(VBPtr,
2283 CGM.Int32Ty->getPointerTo(0)->getPointerTo(0));
2284 llvm::Value *VBTable = Builder.CreateLoad(VBPtr, "vbtable");
2286 // Translate from byte offset to table index. It improves analyzability.
2287 llvm::Value *VBTableIndex = Builder.CreateAShr(
2288 VBTableOffset, llvm::ConstantInt::get(VBTableOffset->getType(), 2),
2289 "vbtindex", /*isExact=*/true);
2291 // Load an i32 offset from the vb-table.
2292 llvm::Value *VBaseOffs = Builder.CreateInBoundsGEP(VBTable, VBTableIndex);
2293 VBaseOffs = Builder.CreateBitCast(VBaseOffs, CGM.Int32Ty->getPointerTo(0));
2294 return Builder.CreateLoad(VBaseOffs, "vbase_offs");
2297 // Returns an adjusted base cast to i8*, since we do more address arithmetic on
2299 llvm::Value *MicrosoftCXXABI::AdjustVirtualBase(
2300 CodeGenFunction &CGF, const Expr *E, const CXXRecordDecl *RD,
2301 llvm::Value *Base, llvm::Value *VBTableOffset, llvm::Value *VBPtrOffset) {
2302 CGBuilderTy &Builder = CGF.Builder;
2303 Base = Builder.CreateBitCast(Base, CGM.Int8PtrTy);
2304 llvm::BasicBlock *OriginalBB = nullptr;
2305 llvm::BasicBlock *SkipAdjustBB = nullptr;
2306 llvm::BasicBlock *VBaseAdjustBB = nullptr;
2308 // In the unspecified inheritance model, there might not be a vbtable at all,
2309 // in which case we need to skip the virtual base lookup. If there is a
2310 // vbtable, the first entry is a no-op entry that gives back the original
2311 // base, so look for a virtual base adjustment offset of zero.
2313 OriginalBB = Builder.GetInsertBlock();
2314 VBaseAdjustBB = CGF.createBasicBlock("memptr.vadjust");
2315 SkipAdjustBB = CGF.createBasicBlock("memptr.skip_vadjust");
2316 llvm::Value *IsVirtual =
2317 Builder.CreateICmpNE(VBTableOffset, getZeroInt(),
2319 Builder.CreateCondBr(IsVirtual, VBaseAdjustBB, SkipAdjustBB);
2320 CGF.EmitBlock(VBaseAdjustBB);
2323 // If we weren't given a dynamic vbptr offset, RD should be complete and we'll
2324 // know the vbptr offset.
2326 CharUnits offs = CharUnits::Zero();
2327 if (!RD->hasDefinition()) {
2328 DiagnosticsEngine &Diags = CGF.CGM.getDiags();
2329 unsigned DiagID = Diags.getCustomDiagID(
2330 DiagnosticsEngine::Error,
2331 "member pointer representation requires a "
2332 "complete class type for %0 to perform this expression");
2333 Diags.Report(E->getExprLoc(), DiagID) << RD << E->getSourceRange();
2334 } else if (RD->getNumVBases())
2335 offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
2336 VBPtrOffset = llvm::ConstantInt::get(CGM.IntTy, offs.getQuantity());
2338 llvm::Value *VBPtr = nullptr;
2339 llvm::Value *VBaseOffs =
2340 GetVBaseOffsetFromVBPtr(CGF, Base, VBPtrOffset, VBTableOffset, &VBPtr);
2341 llvm::Value *AdjustedBase = Builder.CreateInBoundsGEP(VBPtr, VBaseOffs);
2343 // Merge control flow with the case where we didn't have to adjust.
2344 if (VBaseAdjustBB) {
2345 Builder.CreateBr(SkipAdjustBB);
2346 CGF.EmitBlock(SkipAdjustBB);
2347 llvm::PHINode *Phi = Builder.CreatePHI(CGM.Int8PtrTy, 2, "memptr.base");
2348 Phi->addIncoming(Base, OriginalBB);
2349 Phi->addIncoming(AdjustedBase, VBaseAdjustBB);
2352 return AdjustedBase;
2355 llvm::Value *MicrosoftCXXABI::EmitMemberDataPointerAddress(
2356 CodeGenFunction &CGF, const Expr *E, llvm::Value *Base, llvm::Value *MemPtr,
2357 const MemberPointerType *MPT) {
2358 assert(MPT->isMemberDataPointer());
2359 unsigned AS = Base->getType()->getPointerAddressSpace();
2361 CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
2362 CGBuilderTy &Builder = CGF.Builder;
2363 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2364 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
2366 // Extract the fields we need, regardless of model. We'll apply them if we
2368 llvm::Value *FieldOffset = MemPtr;
2369 llvm::Value *VirtualBaseAdjustmentOffset = nullptr;
2370 llvm::Value *VBPtrOffset = nullptr;
2371 if (MemPtr->getType()->isStructTy()) {
2372 // We need to extract values.
2374 FieldOffset = Builder.CreateExtractValue(MemPtr, I++);
2375 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance))
2376 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
2377 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance))
2378 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
2381 if (VirtualBaseAdjustmentOffset) {
2382 Base = AdjustVirtualBase(CGF, E, RD, Base, VirtualBaseAdjustmentOffset,
2387 Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
2389 // Apply the offset, which we assume is non-null.
2391 Builder.CreateInBoundsGEP(Base, FieldOffset, "memptr.offset");
2393 // Cast the address to the appropriate pointer type, adopting the address
2394 // space of the base pointer.
2395 return Builder.CreateBitCast(Addr, PType);
2398 static MSInheritanceAttr::Spelling
2399 getInheritanceFromMemptr(const MemberPointerType *MPT) {
2400 return MPT->getMostRecentCXXRecordDecl()->getMSInheritanceModel();
2404 MicrosoftCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
2407 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
2408 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
2409 E->getCastKind() == CK_ReinterpretMemberPointer);
2411 // Use constant emission if we can.
2412 if (isa<llvm::Constant>(Src))
2413 return EmitMemberPointerConversion(E, cast<llvm::Constant>(Src));
2415 // We may be adding or dropping fields from the member pointer, so we need
2416 // both types and the inheritance models of both records.
2417 const MemberPointerType *SrcTy =
2418 E->getSubExpr()->getType()->castAs<MemberPointerType>();
2419 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
2420 bool IsFunc = SrcTy->isMemberFunctionPointer();
2422 // If the classes use the same null representation, reinterpret_cast is a nop.
2423 bool IsReinterpret = E->getCastKind() == CK_ReinterpretMemberPointer;
2424 if (IsReinterpret && IsFunc)
2427 CXXRecordDecl *SrcRD = SrcTy->getMostRecentCXXRecordDecl();
2428 CXXRecordDecl *DstRD = DstTy->getMostRecentCXXRecordDecl();
2429 if (IsReinterpret &&
2430 SrcRD->nullFieldOffsetIsZero() == DstRD->nullFieldOffsetIsZero())
2433 CGBuilderTy &Builder = CGF.Builder;
2435 // Branch past the conversion if Src is null.
2436 llvm::Value *IsNotNull = EmitMemberPointerIsNotNull(CGF, Src, SrcTy);
2437 llvm::Constant *DstNull = EmitNullMemberPointer(DstTy);
2439 // C++ 5.2.10p9: The null member pointer value is converted to the null member
2440 // pointer value of the destination type.
2441 if (IsReinterpret) {
2442 // For reinterpret casts, sema ensures that src and dst are both functions
2443 // or data and have the same size, which means the LLVM types should match.
2444 assert(Src->getType() == DstNull->getType());
2445 return Builder.CreateSelect(IsNotNull, Src, DstNull);
2448 llvm::BasicBlock *OriginalBB = Builder.GetInsertBlock();
2449 llvm::BasicBlock *ConvertBB = CGF.createBasicBlock("memptr.convert");
2450 llvm::BasicBlock *ContinueBB = CGF.createBasicBlock("memptr.converted");
2451 Builder.CreateCondBr(IsNotNull, ConvertBB, ContinueBB);
2452 CGF.EmitBlock(ConvertBB);
2455 llvm::Value *FirstField = Src;
2456 llvm::Value *NonVirtualBaseAdjustment = nullptr;
2457 llvm::Value *VirtualBaseAdjustmentOffset = nullptr;
2458 llvm::Value *VBPtrOffset = nullptr;
2459 MSInheritanceAttr::Spelling SrcInheritance = SrcRD->getMSInheritanceModel();
2460 if (!MSInheritanceAttr::hasOnlyOneField(IsFunc, SrcInheritance)) {
2461 // We need to extract values.
2463 FirstField = Builder.CreateExtractValue(Src, I++);
2464 if (MSInheritanceAttr::hasNVOffsetField(IsFunc, SrcInheritance))
2465 NonVirtualBaseAdjustment = Builder.CreateExtractValue(Src, I++);
2466 if (MSInheritanceAttr::hasVBPtrOffsetField(SrcInheritance))
2467 VBPtrOffset = Builder.CreateExtractValue(Src, I++);
2468 if (MSInheritanceAttr::hasVBTableOffsetField(SrcInheritance))
2469 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(Src, I++);
2472 // For data pointers, we adjust the field offset directly. For functions, we
2473 // have a separate field.
2474 llvm::Constant *Adj = getMemberPointerAdjustment(E);
2476 Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy);
2477 llvm::Value *&NVAdjustField = IsFunc ? NonVirtualBaseAdjustment : FirstField;
2478 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
2479 if (!NVAdjustField) // If this field didn't exist in src, it's zero.
2480 NVAdjustField = getZeroInt();
2481 if (isDerivedToBase)
2482 NVAdjustField = Builder.CreateNSWSub(NVAdjustField, Adj, "adj");
2484 NVAdjustField = Builder.CreateNSWAdd(NVAdjustField, Adj, "adj");
2487 // FIXME PR15713: Support conversions through virtually derived classes.
2489 // Recompose dst from the null struct and the adjusted fields from src.
2490 MSInheritanceAttr::Spelling DstInheritance = DstRD->getMSInheritanceModel();
2492 if (MSInheritanceAttr::hasOnlyOneField(IsFunc, DstInheritance)) {
2495 Dst = llvm::UndefValue::get(DstNull->getType());
2497 Dst = Builder.CreateInsertValue(Dst, FirstField, Idx++);
2498 if (MSInheritanceAttr::hasNVOffsetField(IsFunc, DstInheritance))
2499 Dst = Builder.CreateInsertValue(
2500 Dst, getValueOrZeroInt(NonVirtualBaseAdjustment), Idx++);
2501 if (MSInheritanceAttr::hasVBPtrOffsetField(DstInheritance))
2502 Dst = Builder.CreateInsertValue(
2503 Dst, getValueOrZeroInt(VBPtrOffset), Idx++);
2504 if (MSInheritanceAttr::hasVBTableOffsetField(DstInheritance))
2505 Dst = Builder.CreateInsertValue(
2506 Dst, getValueOrZeroInt(VirtualBaseAdjustmentOffset), Idx++);
2508 Builder.CreateBr(ContinueBB);
2510 // In the continuation, choose between DstNull and Dst.
2511 CGF.EmitBlock(ContinueBB);
2512 llvm::PHINode *Phi = Builder.CreatePHI(DstNull->getType(), 2, "memptr.converted");
2513 Phi->addIncoming(DstNull, OriginalBB);
2514 Phi->addIncoming(Dst, ConvertBB);
2519 MicrosoftCXXABI::EmitMemberPointerConversion(const CastExpr *E,
2520 llvm::Constant *Src) {
2521 const MemberPointerType *SrcTy =
2522 E->getSubExpr()->getType()->castAs<MemberPointerType>();
2523 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
2525 // If src is null, emit a new null for dst. We can't return src because dst
2526 // might have a new representation.
2527 if (MemberPointerConstantIsNull(SrcTy, Src))
2528 return EmitNullMemberPointer(DstTy);
2530 // We don't need to do anything for reinterpret_casts of non-null member
2531 // pointers. We should only get here when the two type representations have
2533 if (E->getCastKind() == CK_ReinterpretMemberPointer)
2536 MSInheritanceAttr::Spelling SrcInheritance = getInheritanceFromMemptr(SrcTy);
2537 MSInheritanceAttr::Spelling DstInheritance = getInheritanceFromMemptr(DstTy);
2540 llvm::Constant *FirstField = Src;
2541 llvm::Constant *NonVirtualBaseAdjustment = nullptr;
2542 llvm::Constant *VirtualBaseAdjustmentOffset = nullptr;
2543 llvm::Constant *VBPtrOffset = nullptr;
2544 bool IsFunc = SrcTy->isMemberFunctionPointer();
2545 if (!MSInheritanceAttr::hasOnlyOneField(IsFunc, SrcInheritance)) {
2546 // We need to extract values.
2548 FirstField = Src->getAggregateElement(I++);
2549 if (MSInheritanceAttr::hasNVOffsetField(IsFunc, SrcInheritance))
2550 NonVirtualBaseAdjustment = Src->getAggregateElement(I++);
2551 if (MSInheritanceAttr::hasVBPtrOffsetField(SrcInheritance))
2552 VBPtrOffset = Src->getAggregateElement(I++);
2553 if (MSInheritanceAttr::hasVBTableOffsetField(SrcInheritance))
2554 VirtualBaseAdjustmentOffset = Src->getAggregateElement(I++);
2557 // For data pointers, we adjust the field offset directly. For functions, we
2558 // have a separate field.
2559 llvm::Constant *Adj = getMemberPointerAdjustment(E);
2561 Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy);
2562 llvm::Constant *&NVAdjustField =
2563 IsFunc ? NonVirtualBaseAdjustment : FirstField;
2564 bool IsDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
2565 if (!NVAdjustField) // If this field didn't exist in src, it's zero.
2566 NVAdjustField = getZeroInt();
2567 if (IsDerivedToBase)
2568 NVAdjustField = llvm::ConstantExpr::getNSWSub(NVAdjustField, Adj);
2570 NVAdjustField = llvm::ConstantExpr::getNSWAdd(NVAdjustField, Adj);
2573 // FIXME PR15713: Support conversions through virtually derived classes.
2575 // Recompose dst from the null struct and the adjusted fields from src.
2576 if (MSInheritanceAttr::hasOnlyOneField(IsFunc, DstInheritance))
2579 llvm::SmallVector<llvm::Constant *, 4> Fields;
2580 Fields.push_back(FirstField);
2581 if (MSInheritanceAttr::hasNVOffsetField(IsFunc, DstInheritance))
2582 Fields.push_back(getConstantOrZeroInt(NonVirtualBaseAdjustment));
2583 if (MSInheritanceAttr::hasVBPtrOffsetField(DstInheritance))
2584 Fields.push_back(getConstantOrZeroInt(VBPtrOffset));
2585 if (MSInheritanceAttr::hasVBTableOffsetField(DstInheritance))
2586 Fields.push_back(getConstantOrZeroInt(VirtualBaseAdjustmentOffset));
2587 return llvm::ConstantStruct::getAnon(Fields);
2590 llvm::Value *MicrosoftCXXABI::EmitLoadOfMemberFunctionPointer(
2591 CodeGenFunction &CGF, const Expr *E, llvm::Value *&This,
2592 llvm::Value *MemPtr, const MemberPointerType *MPT) {
2593 assert(MPT->isMemberFunctionPointer());
2594 const FunctionProtoType *FPT =
2595 MPT->getPointeeType()->castAs<FunctionProtoType>();
2596 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2597 llvm::FunctionType *FTy =
2598 CGM.getTypes().GetFunctionType(
2599 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
2600 CGBuilderTy &Builder = CGF.Builder;
2602 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
2604 // Extract the fields we need, regardless of model. We'll apply them if we
2606 llvm::Value *FunctionPointer = MemPtr;
2607 llvm::Value *NonVirtualBaseAdjustment = nullptr;
2608 llvm::Value *VirtualBaseAdjustmentOffset = nullptr;
2609 llvm::Value *VBPtrOffset = nullptr;
2610 if (MemPtr->getType()->isStructTy()) {
2611 // We need to extract values.
2613 FunctionPointer = Builder.CreateExtractValue(MemPtr, I++);
2614 if (MSInheritanceAttr::hasNVOffsetField(MPT, Inheritance))
2615 NonVirtualBaseAdjustment = Builder.CreateExtractValue(MemPtr, I++);
2616 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance))
2617 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
2618 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance))
2619 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
2622 if (VirtualBaseAdjustmentOffset) {
2623 This = AdjustVirtualBase(CGF, E, RD, This, VirtualBaseAdjustmentOffset,
2627 if (NonVirtualBaseAdjustment) {
2628 // Apply the adjustment and cast back to the original struct type.
2629 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
2630 Ptr = Builder.CreateInBoundsGEP(Ptr, NonVirtualBaseAdjustment);
2631 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
2634 return Builder.CreateBitCast(FunctionPointer, FTy->getPointerTo());
2637 CGCXXABI *clang::CodeGen::CreateMicrosoftCXXABI(CodeGenModule &CGM) {
2638 return new MicrosoftCXXABI(CGM);
2641 // MS RTTI Overview:
2642 // The run time type information emitted by cl.exe contains 5 distinct types of
2643 // structures. Many of them reference each other.
2645 // TypeInfo: Static classes that are returned by typeid.
2647 // CompleteObjectLocator: Referenced by vftables. They contain information
2648 // required for dynamic casting, including OffsetFromTop. They also contain
2649 // a reference to the TypeInfo for the type and a reference to the
2650 // CompleteHierarchyDescriptor for the type.
2652 // ClassHieararchyDescriptor: Contains information about a class hierarchy.
2653 // Used during dynamic_cast to walk a class hierarchy. References a base
2654 // class array and the size of said array.
2656 // BaseClassArray: Contains a list of classes in a hierarchy. BaseClassArray is
2657 // somewhat of a misnomer because the most derived class is also in the list
2658 // as well as multiple copies of virtual bases (if they occur multiple times
2659 // in the hiearchy.) The BaseClassArray contains one BaseClassDescriptor for
2660 // every path in the hierarchy, in pre-order depth first order. Note, we do
2661 // not declare a specific llvm type for BaseClassArray, it's merely an array
2662 // of BaseClassDescriptor pointers.
2664 // BaseClassDescriptor: Contains information about a class in a class hierarchy.
2665 // BaseClassDescriptor is also somewhat of a misnomer for the same reason that
2666 // BaseClassArray is. It contains information about a class within a
2667 // hierarchy such as: is this base is ambiguous and what is its offset in the
2668 // vbtable. The names of the BaseClassDescriptors have all of their fields
2669 // mangled into them so they can be aggressively deduplicated by the linker.
2671 static llvm::GlobalVariable *getTypeInfoVTable(CodeGenModule &CGM) {
2672 StringRef MangledName("\01??_7type_info@@6B@");
2673 if (auto VTable = CGM.getModule().getNamedGlobal(MangledName))
2675 return new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
2677 llvm::GlobalVariable::ExternalLinkage,
2678 /*Initializer=*/nullptr, MangledName);
2683 /// \brief A Helper struct that stores information about a class in a class
2684 /// hierarchy. The information stored in these structs struct is used during
2685 /// the generation of ClassHierarchyDescriptors and BaseClassDescriptors.
2686 // During RTTI creation, MSRTTIClasses are stored in a contiguous array with
2687 // implicit depth first pre-order tree connectivity. getFirstChild and
2688 // getNextSibling allow us to walk the tree efficiently.
2689 struct MSRTTIClass {
2691 IsPrivateOnPath = 1 | 8,
2695 HasHierarchyDescriptor = 64
2697 MSRTTIClass(const CXXRecordDecl *RD) : RD(RD) {}
2698 uint32_t initialize(const MSRTTIClass *Parent,
2699 const CXXBaseSpecifier *Specifier);
2701 MSRTTIClass *getFirstChild() { return this + 1; }
2702 static MSRTTIClass *getNextChild(MSRTTIClass *Child) {
2703 return Child + 1 + Child->NumBases;
2706 const CXXRecordDecl *RD, *VirtualRoot;
2707 uint32_t Flags, NumBases, OffsetInVBase;
2710 /// \brief Recursively initialize the base class array.
2711 uint32_t MSRTTIClass::initialize(const MSRTTIClass *Parent,
2712 const CXXBaseSpecifier *Specifier) {
2713 Flags = HasHierarchyDescriptor;
2715 VirtualRoot = nullptr;
2718 if (Specifier->getAccessSpecifier() != AS_public)
2719 Flags |= IsPrivate | IsPrivateOnPath;
2720 if (Specifier->isVirtual()) {
2725 if (Parent->Flags & IsPrivateOnPath)
2726 Flags |= IsPrivateOnPath;
2727 VirtualRoot = Parent->VirtualRoot;
2728 OffsetInVBase = Parent->OffsetInVBase + RD->getASTContext()
2729 .getASTRecordLayout(Parent->RD).getBaseClassOffset(RD).getQuantity();
2733 MSRTTIClass *Child = getFirstChild();
2734 for (const CXXBaseSpecifier &Base : RD->bases()) {
2735 NumBases += Child->initialize(this, &Base) + 1;
2736 Child = getNextChild(Child);
2741 static llvm::GlobalValue::LinkageTypes getLinkageForRTTI(QualType Ty) {
2742 switch (Ty->getLinkage()) {
2744 case InternalLinkage:
2745 case UniqueExternalLinkage:
2746 return llvm::GlobalValue::InternalLinkage;
2748 case VisibleNoLinkage:
2749 case ExternalLinkage:
2750 return llvm::GlobalValue::LinkOnceODRLinkage;
2752 llvm_unreachable("Invalid linkage!");
2755 /// \brief An ephemeral helper class for building MS RTTI types. It caches some
2756 /// calls to the module and information about the most derived class in a
2758 struct MSRTTIBuilder {
2760 HasBranchingHierarchy = 1,
2761 HasVirtualBranchingHierarchy = 2,
2762 HasAmbiguousBases = 4
2765 MSRTTIBuilder(MicrosoftCXXABI &ABI, const CXXRecordDecl *RD)
2766 : CGM(ABI.CGM), Context(CGM.getContext()),
2767 VMContext(CGM.getLLVMContext()), Module(CGM.getModule()), RD(RD),
2768 Linkage(getLinkageForRTTI(CGM.getContext().getTagDeclType(RD))),
2771 llvm::GlobalVariable *getBaseClassDescriptor(const MSRTTIClass &Classes);
2772 llvm::GlobalVariable *
2773 getBaseClassArray(SmallVectorImpl<MSRTTIClass> &Classes);
2774 llvm::GlobalVariable *getClassHierarchyDescriptor();
2775 llvm::GlobalVariable *getCompleteObjectLocator(const VPtrInfo *Info);
2778 ASTContext &Context;
2779 llvm::LLVMContext &VMContext;
2780 llvm::Module &Module;
2781 const CXXRecordDecl *RD;
2782 llvm::GlobalVariable::LinkageTypes Linkage;
2783 MicrosoftCXXABI &ABI;
2788 /// \brief Recursively serializes a class hierarchy in pre-order depth first
2790 static void serializeClassHierarchy(SmallVectorImpl<MSRTTIClass> &Classes,
2791 const CXXRecordDecl *RD) {
2792 Classes.push_back(MSRTTIClass(RD));
2793 for (const CXXBaseSpecifier &Base : RD->bases())
2794 serializeClassHierarchy(Classes, Base.getType()->getAsCXXRecordDecl());
2797 /// \brief Find ambiguity among base classes.
2799 detectAmbiguousBases(SmallVectorImpl<MSRTTIClass> &Classes) {
2800 llvm::SmallPtrSet<const CXXRecordDecl *, 8> VirtualBases;
2801 llvm::SmallPtrSet<const CXXRecordDecl *, 8> UniqueBases;
2802 llvm::SmallPtrSet<const CXXRecordDecl *, 8> AmbiguousBases;
2803 for (MSRTTIClass *Class = &Classes.front(); Class <= &Classes.back();) {
2804 if ((Class->Flags & MSRTTIClass::IsVirtual) &&
2805 !VirtualBases.insert(Class->RD).second) {
2806 Class = MSRTTIClass::getNextChild(Class);
2809 if (!UniqueBases.insert(Class->RD).second)
2810 AmbiguousBases.insert(Class->RD);
2813 if (AmbiguousBases.empty())
2815 for (MSRTTIClass &Class : Classes)
2816 if (AmbiguousBases.count(Class.RD))
2817 Class.Flags |= MSRTTIClass::IsAmbiguous;
2820 llvm::GlobalVariable *MSRTTIBuilder::getClassHierarchyDescriptor() {
2821 SmallString<256> MangledName;
2823 llvm::raw_svector_ostream Out(MangledName);
2824 ABI.getMangleContext().mangleCXXRTTIClassHierarchyDescriptor(RD, Out);
2827 // Check to see if we've already declared this ClassHierarchyDescriptor.
2828 if (auto CHD = Module.getNamedGlobal(MangledName))
2831 // Serialize the class hierarchy and initialize the CHD Fields.
2832 SmallVector<MSRTTIClass, 8> Classes;
2833 serializeClassHierarchy(Classes, RD);
2834 Classes.front().initialize(/*Parent=*/nullptr, /*Specifier=*/nullptr);
2835 detectAmbiguousBases(Classes);
2837 for (auto Class : Classes) {
2838 if (Class.RD->getNumBases() > 1)
2839 Flags |= HasBranchingHierarchy;
2840 // Note: cl.exe does not calculate "HasAmbiguousBases" correctly. We
2841 // believe the field isn't actually used.
2842 if (Class.Flags & MSRTTIClass::IsAmbiguous)
2843 Flags |= HasAmbiguousBases;
2845 if ((Flags & HasBranchingHierarchy) && RD->getNumVBases() != 0)
2846 Flags |= HasVirtualBranchingHierarchy;
2847 // These gep indices are used to get the address of the first element of the
2848 // base class array.
2849 llvm::Value *GEPIndices[] = {llvm::ConstantInt::get(CGM.IntTy, 0),
2850 llvm::ConstantInt::get(CGM.IntTy, 0)};
2852 // Forward-declare the class hierarchy descriptor
2853 auto Type = ABI.getClassHierarchyDescriptorType();
2854 auto CHD = new llvm::GlobalVariable(Module, Type, /*Constant=*/true, Linkage,
2855 /*Initializer=*/nullptr,
2856 MangledName.c_str());
2858 // Initialize the base class ClassHierarchyDescriptor.
2859 llvm::Constant *Fields[] = {
2860 llvm::ConstantInt::get(CGM.IntTy, 0), // Unknown
2861 llvm::ConstantInt::get(CGM.IntTy, Flags),
2862 llvm::ConstantInt::get(CGM.IntTy, Classes.size()),
2863 ABI.getImageRelativeConstant(llvm::ConstantExpr::getInBoundsGetElementPtr(
2864 getBaseClassArray(Classes),
2865 llvm::ArrayRef<llvm::Value *>(GEPIndices))),
2867 CHD->setInitializer(llvm::ConstantStruct::get(Type, Fields));
2871 llvm::GlobalVariable *
2872 MSRTTIBuilder::getBaseClassArray(SmallVectorImpl<MSRTTIClass> &Classes) {
2873 SmallString<256> MangledName;
2875 llvm::raw_svector_ostream Out(MangledName);
2876 ABI.getMangleContext().mangleCXXRTTIBaseClassArray(RD, Out);
2879 // Forward-declare the base class array.
2880 // cl.exe pads the base class array with 1 (in 32 bit mode) or 4 (in 64 bit
2881 // mode) bytes of padding. We provide a pointer sized amount of padding by
2882 // adding +1 to Classes.size(). The sections have pointer alignment and are
2883 // marked pick-any so it shouldn't matter.
2884 llvm::Type *PtrType = ABI.getImageRelativeType(
2885 ABI.getBaseClassDescriptorType()->getPointerTo());
2886 auto *ArrType = llvm::ArrayType::get(PtrType, Classes.size() + 1);
2887 auto *BCA = new llvm::GlobalVariable(
2889 /*Constant=*/true, Linkage, /*Initializer=*/nullptr, MangledName.c_str());
2891 // Initialize the BaseClassArray.
2892 SmallVector<llvm::Constant *, 8> BaseClassArrayData;
2893 for (MSRTTIClass &Class : Classes)
2894 BaseClassArrayData.push_back(
2895 ABI.getImageRelativeConstant(getBaseClassDescriptor(Class)));
2896 BaseClassArrayData.push_back(llvm::Constant::getNullValue(PtrType));
2897 BCA->setInitializer(llvm::ConstantArray::get(ArrType, BaseClassArrayData));
2901 llvm::GlobalVariable *
2902 MSRTTIBuilder::getBaseClassDescriptor(const MSRTTIClass &Class) {
2903 // Compute the fields for the BaseClassDescriptor. They are computed up front
2904 // because they are mangled into the name of the object.
2905 uint32_t OffsetInVBTable = 0;
2906 int32_t VBPtrOffset = -1;
2907 if (Class.VirtualRoot) {
2908 auto &VTableContext = CGM.getMicrosoftVTableContext();
2909 OffsetInVBTable = VTableContext.getVBTableIndex(RD, Class.VirtualRoot) * 4;
2910 VBPtrOffset = Context.getASTRecordLayout(RD).getVBPtrOffset().getQuantity();
2913 SmallString<256> MangledName;
2915 llvm::raw_svector_ostream Out(MangledName);
2916 ABI.getMangleContext().mangleCXXRTTIBaseClassDescriptor(
2917 Class.RD, Class.OffsetInVBase, VBPtrOffset, OffsetInVBTable,
2921 // Check to see if we've already declared this object.
2922 if (auto BCD = Module.getNamedGlobal(MangledName))
2925 // Forward-declare the base class descriptor.
2926 auto Type = ABI.getBaseClassDescriptorType();
2927 auto BCD = new llvm::GlobalVariable(Module, Type, /*Constant=*/true, Linkage,
2928 /*Initializer=*/nullptr,
2929 MangledName.c_str());
2931 // Initialize the BaseClassDescriptor.
2932 llvm::Constant *Fields[] = {
2933 ABI.getImageRelativeConstant(
2934 ABI.getAddrOfRTTIDescriptor(Context.getTypeDeclType(Class.RD))),
2935 llvm::ConstantInt::get(CGM.IntTy, Class.NumBases),
2936 llvm::ConstantInt::get(CGM.IntTy, Class.OffsetInVBase),
2937 llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset),
2938 llvm::ConstantInt::get(CGM.IntTy, OffsetInVBTable),
2939 llvm::ConstantInt::get(CGM.IntTy, Class.Flags),
2940 ABI.getImageRelativeConstant(
2941 MSRTTIBuilder(ABI, Class.RD).getClassHierarchyDescriptor()),
2943 BCD->setInitializer(llvm::ConstantStruct::get(Type, Fields));
2947 llvm::GlobalVariable *
2948 MSRTTIBuilder::getCompleteObjectLocator(const VPtrInfo *Info) {
2949 SmallString<256> MangledName;
2951 llvm::raw_svector_ostream Out(MangledName);
2952 ABI.getMangleContext().mangleCXXRTTICompleteObjectLocator(RD, Info->MangledPath, Out);
2955 // Check to see if we've already computed this complete object locator.
2956 if (auto COL = Module.getNamedGlobal(MangledName))
2959 // Compute the fields of the complete object locator.
2960 int OffsetToTop = Info->FullOffsetInMDC.getQuantity();
2961 int VFPtrOffset = 0;
2962 // The offset includes the vtordisp if one exists.
2963 if (const CXXRecordDecl *VBase = Info->getVBaseWithVPtr())
2964 if (Context.getASTRecordLayout(RD)
2965 .getVBaseOffsetsMap()
2967 ->second.hasVtorDisp())
2968 VFPtrOffset = Info->NonVirtualOffset.getQuantity() + 4;
2970 // Forward-declare the complete object locator.
2971 llvm::StructType *Type = ABI.getCompleteObjectLocatorType();
2972 auto COL = new llvm::GlobalVariable(Module, Type, /*Constant=*/true, Linkage,
2973 /*Initializer=*/nullptr, MangledName.c_str());
2975 // Initialize the CompleteObjectLocator.
2976 llvm::Constant *Fields[] = {
2977 llvm::ConstantInt::get(CGM.IntTy, ABI.isImageRelative()),
2978 llvm::ConstantInt::get(CGM.IntTy, OffsetToTop),
2979 llvm::ConstantInt::get(CGM.IntTy, VFPtrOffset),
2980 ABI.getImageRelativeConstant(
2981 CGM.GetAddrOfRTTIDescriptor(Context.getTypeDeclType(RD))),
2982 ABI.getImageRelativeConstant(getClassHierarchyDescriptor()),
2983 ABI.getImageRelativeConstant(COL),
2985 llvm::ArrayRef<llvm::Constant *> FieldsRef(Fields);
2986 if (!ABI.isImageRelative())
2987 FieldsRef = FieldsRef.drop_back();
2988 COL->setInitializer(llvm::ConstantStruct::get(Type, FieldsRef));
2992 /// \brief Gets a TypeDescriptor. Returns a llvm::Constant * rather than a
2993 /// llvm::GlobalVariable * because different type descriptors have different
2994 /// types, and need to be abstracted. They are abstracting by casting the
2995 /// address to an Int8PtrTy.
2996 llvm::Constant *MicrosoftCXXABI::getAddrOfRTTIDescriptor(QualType Type) {
2997 SmallString<256> MangledName, TypeInfoString;
2999 llvm::raw_svector_ostream Out(MangledName);
3000 getMangleContext().mangleCXXRTTI(Type, Out);
3003 // Check to see if we've already declared this TypeDescriptor.
3004 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
3005 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
3007 // Compute the fields for the TypeDescriptor.
3009 llvm::raw_svector_ostream Out(TypeInfoString);
3010 getMangleContext().mangleCXXRTTIName(Type, Out);
3013 // Declare and initialize the TypeDescriptor.
3014 llvm::Constant *Fields[] = {
3015 getTypeInfoVTable(CGM), // VFPtr
3016 llvm::ConstantPointerNull::get(CGM.Int8PtrTy), // Runtime data
3017 llvm::ConstantDataArray::getString(CGM.getLLVMContext(), TypeInfoString)};
3018 llvm::StructType *TypeDescriptorType =
3019 getTypeDescriptorType(TypeInfoString);
3020 return llvm::ConstantExpr::getBitCast(
3021 new llvm::GlobalVariable(
3022 CGM.getModule(), TypeDescriptorType, /*Constant=*/false,
3023 getLinkageForRTTI(Type),
3024 llvm::ConstantStruct::get(TypeDescriptorType, Fields),
3025 MangledName.c_str()),
3029 /// \brief Gets or a creates a Microsoft CompleteObjectLocator.
3030 llvm::GlobalVariable *
3031 MicrosoftCXXABI::getMSCompleteObjectLocator(const CXXRecordDecl *RD,
3032 const VPtrInfo *Info) {
3033 return MSRTTIBuilder(*this, RD).getCompleteObjectLocator(Info);
3036 static void emitCXXConstructor(CodeGenModule &CGM,
3037 const CXXConstructorDecl *ctor,
3038 StructorType ctorType) {
3039 // There are no constructor variants, always emit the complete destructor.
3040 CGM.codegenCXXStructor(ctor, StructorType::Complete);
3043 static void emitCXXDestructor(CodeGenModule &CGM, const CXXDestructorDecl *dtor,
3044 StructorType dtorType) {
3045 // The complete destructor is equivalent to the base destructor for
3046 // classes with no virtual bases, so try to emit it as an alias.
3047 if (!dtor->getParent()->getNumVBases() &&
3048 (dtorType == StructorType::Complete || dtorType == StructorType::Base)) {
3049 bool ProducedAlias = !CGM.TryEmitDefinitionAsAlias(
3050 GlobalDecl(dtor, Dtor_Complete), GlobalDecl(dtor, Dtor_Base), true);
3051 if (ProducedAlias) {
3052 if (dtorType == StructorType::Complete)
3054 if (dtor->isVirtual())
3055 CGM.getVTables().EmitThunks(GlobalDecl(dtor, Dtor_Complete));
3059 // The base destructor is equivalent to the base destructor of its
3060 // base class if there is exactly one non-virtual base class with a
3061 // non-trivial destructor, there are no fields with a non-trivial
3062 // destructor, and the body of the destructor is trivial.
3063 if (dtorType == StructorType::Base && !CGM.TryEmitBaseDestructorAsAlias(dtor))
3066 CGM.codegenCXXStructor(dtor, dtorType);
3069 void MicrosoftCXXABI::emitCXXStructor(const CXXMethodDecl *MD,
3070 StructorType Type) {
3071 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
3072 emitCXXConstructor(CGM, CD, Type);
3075 emitCXXDestructor(CGM, cast<CXXDestructorDecl>(MD), Type);