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 "TargetInfo.h"
21 #include "clang/AST/Decl.h"
22 #include "clang/AST/DeclCXX.h"
23 #include "clang/AST/StmtCXX.h"
24 #include "clang/AST/VTableBuilder.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/StringSet.h"
27 #include "llvm/IR/CallSite.h"
28 #include "llvm/IR/Intrinsics.h"
30 using namespace clang;
31 using namespace CodeGen;
35 /// Holds all the vbtable globals for a given class.
36 struct VBTableGlobals {
37 const VPtrInfoVector *VBTables;
38 SmallVector<llvm::GlobalVariable *, 2> Globals;
41 class MicrosoftCXXABI : public CGCXXABI {
43 MicrosoftCXXABI(CodeGenModule &CGM)
44 : CGCXXABI(CGM), BaseClassDescriptorType(nullptr),
45 ClassHierarchyDescriptorType(nullptr),
46 CompleteObjectLocatorType(nullptr) {}
48 bool HasThisReturn(GlobalDecl GD) const override;
49 bool hasMostDerivedReturn(GlobalDecl GD) const override;
51 bool classifyReturnType(CGFunctionInfo &FI) const override;
53 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override;
55 bool isSRetParameterAfterThis() const override { return true; }
57 size_t getSrcArgforCopyCtor(const CXXConstructorDecl *CD,
58 FunctionArgList &Args) const override {
59 assert(Args.size() >= 2 &&
60 "expected the arglist to have at least two args!");
61 // The 'most_derived' parameter goes second if the ctor is variadic and
63 if (CD->getParent()->getNumVBases() > 0 &&
64 CD->getType()->castAs<FunctionProtoType>()->isVariadic())
69 StringRef GetPureVirtualCallName() override { return "_purecall"; }
70 StringRef GetDeletedVirtualCallName() override { return "_purecall"; }
72 void emitVirtualObjectDelete(CodeGenFunction &CGF, const CXXDeleteExpr *DE,
73 llvm::Value *Ptr, QualType ElementType,
74 const CXXDestructorDecl *Dtor) override;
76 void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) override;
78 void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override;
80 llvm::GlobalVariable *getMSCompleteObjectLocator(const CXXRecordDecl *RD,
81 const VPtrInfo *Info);
83 llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override;
85 bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override;
86 void EmitBadTypeidCall(CodeGenFunction &CGF) override;
87 llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
89 llvm::Type *StdTypeInfoPtrTy) override;
91 bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
92 QualType SrcRecordTy) override;
94 llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, llvm::Value *Value,
95 QualType SrcRecordTy, QualType DestTy,
96 QualType DestRecordTy,
97 llvm::BasicBlock *CastEnd) override;
99 llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, llvm::Value *Value,
100 QualType SrcRecordTy,
101 QualType DestTy) override;
103 bool EmitBadCastCall(CodeGenFunction &CGF) override;
106 GetVirtualBaseClassOffset(CodeGenFunction &CGF, llvm::Value *This,
107 const CXXRecordDecl *ClassDecl,
108 const CXXRecordDecl *BaseClassDecl) override;
111 EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
112 const CXXRecordDecl *RD) override;
114 void initializeHiddenVirtualInheritanceMembers(CodeGenFunction &CGF,
115 const CXXRecordDecl *RD) override;
117 void EmitCXXConstructors(const CXXConstructorDecl *D) override;
119 // Background on MSVC destructors
120 // ==============================
122 // Both Itanium and MSVC ABIs have destructor variants. The variant names
123 // roughly correspond in the following way:
125 // Base -> no name, just ~Class
126 // Complete -> vbase destructor
127 // Deleting -> scalar deleting destructor
128 // vector deleting destructor
130 // The base and complete destructors are the same as in Itanium, although the
131 // complete destructor does not accept a VTT parameter when there are virtual
132 // bases. A separate mechanism involving vtordisps is used to ensure that
133 // virtual methods of destroyed subobjects are not called.
135 // The deleting destructors accept an i32 bitfield as a second parameter. Bit
136 // 1 indicates if the memory should be deleted. Bit 2 indicates if the this
137 // pointer points to an array. The scalar deleting destructor assumes that
138 // bit 2 is zero, and therefore does not contain a loop.
140 // For virtual destructors, only one entry is reserved in the vftable, and it
141 // always points to the vector deleting destructor. The vector deleting
142 // destructor is the most general, so it can be used to destroy objects in
143 // place, delete single heap objects, or delete arrays.
145 // A TU defining a non-inline destructor is only guaranteed to emit a base
146 // destructor, and all of the other variants are emitted on an as-needed basis
147 // in COMDATs. Because a non-base destructor can be emitted in a TU that
148 // lacks a definition for the destructor, non-base destructors must always
149 // delegate to or alias the base destructor.
151 void buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
152 SmallVectorImpl<CanQualType> &ArgTys) override;
154 /// Non-base dtors should be emitted as delegating thunks in this ABI.
155 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
156 CXXDtorType DT) const override {
157 return DT != Dtor_Base;
160 void EmitCXXDestructors(const CXXDestructorDecl *D) override;
162 const CXXRecordDecl *
163 getThisArgumentTypeForMethod(const CXXMethodDecl *MD) override {
164 MD = MD->getCanonicalDecl();
165 if (MD->isVirtual() && !isa<CXXDestructorDecl>(MD)) {
166 MicrosoftVTableContext::MethodVFTableLocation ML =
167 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(MD);
168 // The vbases might be ordered differently in the final overrider object
169 // and the complete object, so the "this" argument may sometimes point to
170 // memory that has no particular type (e.g. past the complete object).
171 // In this case, we just use a generic pointer type.
172 // FIXME: might want to have a more precise type in the non-virtual
173 // multiple inheritance case.
174 if (ML.VBase || !ML.VFPtrOffset.isZero())
177 return MD->getParent();
181 adjustThisArgumentForVirtualFunctionCall(CodeGenFunction &CGF, GlobalDecl GD,
183 bool VirtualCall) override;
185 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
186 FunctionArgList &Params) override;
188 llvm::Value *adjustThisParameterInVirtualFunctionPrologue(
189 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) override;
191 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
193 unsigned addImplicitConstructorArgs(CodeGenFunction &CGF,
194 const CXXConstructorDecl *D,
195 CXXCtorType Type, bool ForVirtualBase,
197 CallArgList &Args) override;
199 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
200 CXXDtorType Type, bool ForVirtualBase,
201 bool Delegating, llvm::Value *This) override;
203 void emitVTableDefinitions(CodeGenVTables &CGVT,
204 const CXXRecordDecl *RD) override;
206 llvm::Value *getVTableAddressPointInStructor(
207 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
208 BaseSubobject Base, const CXXRecordDecl *NearestVBase,
209 bool &NeedsVirtualOffset) override;
212 getVTableAddressPointForConstExpr(BaseSubobject Base,
213 const CXXRecordDecl *VTableClass) override;
215 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
216 CharUnits VPtrOffset) override;
218 llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
220 llvm::Type *Ty) override;
222 llvm::Value *EmitVirtualDestructorCall(CodeGenFunction &CGF,
223 const CXXDestructorDecl *Dtor,
224 CXXDtorType DtorType,
226 const CXXMemberCallExpr *CE) override;
228 void adjustCallArgsForDestructorThunk(CodeGenFunction &CGF, GlobalDecl GD,
229 CallArgList &CallArgs) override {
230 assert(GD.getDtorType() == Dtor_Deleting &&
231 "Only deleting destructor thunks are available in this ABI");
232 CallArgs.add(RValue::get(getStructorImplicitParamValue(CGF)),
233 CGM.getContext().IntTy);
236 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
238 llvm::GlobalVariable *
239 getAddrOfVBTable(const VPtrInfo &VBT, const CXXRecordDecl *RD,
240 llvm::GlobalVariable::LinkageTypes Linkage);
242 void emitVBTableDefinition(const VPtrInfo &VBT, const CXXRecordDecl *RD,
243 llvm::GlobalVariable *GV) const;
245 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable,
246 GlobalDecl GD, bool ReturnAdjustment) override {
247 // Never dllimport/dllexport thunks.
248 Thunk->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
251 getContext().GetGVALinkageForFunction(cast<FunctionDecl>(GD.getDecl()));
253 if (Linkage == GVA_Internal)
254 Thunk->setLinkage(llvm::GlobalValue::InternalLinkage);
255 else if (ReturnAdjustment)
256 Thunk->setLinkage(llvm::GlobalValue::WeakODRLinkage);
258 Thunk->setLinkage(llvm::GlobalValue::LinkOnceODRLinkage);
261 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, llvm::Value *This,
262 const ThisAdjustment &TA) override;
264 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
265 const ReturnAdjustment &RA) override;
267 void EmitThreadLocalInitFuncs(
269 ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *>>
271 ArrayRef<llvm::Function *> CXXThreadLocalInits,
272 ArrayRef<llvm::GlobalVariable *> CXXThreadLocalInitVars) override;
274 bool usesThreadWrapperFunction() const override { return false; }
275 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
276 QualType LValType) override;
278 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
279 llvm::GlobalVariable *DeclPtr,
280 bool PerformInit) override;
281 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
282 llvm::Constant *Dtor, llvm::Constant *Addr) override;
284 // ==== Notes on array cookies =========
286 // MSVC seems to only use cookies when the class has a destructor; a
287 // two-argument usual array deallocation function isn't sufficient.
289 // For example, this code prints "100" and "1":
292 // void *operator new[](size_t sz) {
293 // printf("%u\n", sz);
294 // return malloc(sz);
296 // void operator delete[](void *p, size_t sz) {
297 // printf("%u\n", sz);
302 // A *p = new A[100];
305 // Whereas it prints "104" and "104" if you give A a destructor.
307 bool requiresArrayCookie(const CXXDeleteExpr *expr,
308 QualType elementType) override;
309 bool requiresArrayCookie(const CXXNewExpr *expr) override;
310 CharUnits getArrayCookieSizeImpl(QualType type) override;
311 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
313 llvm::Value *NumElements,
314 const CXXNewExpr *expr,
315 QualType ElementType) override;
316 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
317 llvm::Value *allocPtr,
318 CharUnits cookieSize) override;
320 friend struct MSRTTIBuilder;
322 bool isImageRelative() const {
323 return CGM.getTarget().getPointerWidth(/*AddressSpace=*/0) == 64;
326 // 5 routines for constructing the llvm types for MS RTTI structs.
327 llvm::StructType *getTypeDescriptorType(StringRef TypeInfoString) {
328 llvm::SmallString<32> TDTypeName("rtti.TypeDescriptor");
329 TDTypeName += llvm::utostr(TypeInfoString.size());
330 llvm::StructType *&TypeDescriptorType =
331 TypeDescriptorTypeMap[TypeInfoString.size()];
332 if (TypeDescriptorType)
333 return TypeDescriptorType;
334 llvm::Type *FieldTypes[] = {
337 llvm::ArrayType::get(CGM.Int8Ty, TypeInfoString.size() + 1)};
339 llvm::StructType::create(CGM.getLLVMContext(), FieldTypes, TDTypeName);
340 return TypeDescriptorType;
343 llvm::Type *getImageRelativeType(llvm::Type *PtrType) {
344 if (!isImageRelative())
349 llvm::StructType *getBaseClassDescriptorType() {
350 if (BaseClassDescriptorType)
351 return BaseClassDescriptorType;
352 llvm::Type *FieldTypes[] = {
353 getImageRelativeType(CGM.Int8PtrTy),
359 getImageRelativeType(getClassHierarchyDescriptorType()->getPointerTo()),
361 BaseClassDescriptorType = llvm::StructType::create(
362 CGM.getLLVMContext(), FieldTypes, "rtti.BaseClassDescriptor");
363 return BaseClassDescriptorType;
366 llvm::StructType *getClassHierarchyDescriptorType() {
367 if (ClassHierarchyDescriptorType)
368 return ClassHierarchyDescriptorType;
369 // Forward-declare RTTIClassHierarchyDescriptor to break a cycle.
370 ClassHierarchyDescriptorType = llvm::StructType::create(
371 CGM.getLLVMContext(), "rtti.ClassHierarchyDescriptor");
372 llvm::Type *FieldTypes[] = {
376 getImageRelativeType(
377 getBaseClassDescriptorType()->getPointerTo()->getPointerTo()),
379 ClassHierarchyDescriptorType->setBody(FieldTypes);
380 return ClassHierarchyDescriptorType;
383 llvm::StructType *getCompleteObjectLocatorType() {
384 if (CompleteObjectLocatorType)
385 return CompleteObjectLocatorType;
386 CompleteObjectLocatorType = llvm::StructType::create(
387 CGM.getLLVMContext(), "rtti.CompleteObjectLocator");
388 llvm::Type *FieldTypes[] = {
392 getImageRelativeType(CGM.Int8PtrTy),
393 getImageRelativeType(getClassHierarchyDescriptorType()->getPointerTo()),
394 getImageRelativeType(CompleteObjectLocatorType),
396 llvm::ArrayRef<llvm::Type *> FieldTypesRef(FieldTypes);
397 if (!isImageRelative())
398 FieldTypesRef = FieldTypesRef.drop_back();
399 CompleteObjectLocatorType->setBody(FieldTypesRef);
400 return CompleteObjectLocatorType;
403 llvm::GlobalVariable *getImageBase() {
404 StringRef Name = "__ImageBase";
405 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name))
408 return new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty,
410 llvm::GlobalValue::ExternalLinkage,
411 /*Initializer=*/nullptr, Name);
414 llvm::Constant *getImageRelativeConstant(llvm::Constant *PtrVal) {
415 if (!isImageRelative())
418 llvm::Constant *ImageBaseAsInt =
419 llvm::ConstantExpr::getPtrToInt(getImageBase(), CGM.IntPtrTy);
420 llvm::Constant *PtrValAsInt =
421 llvm::ConstantExpr::getPtrToInt(PtrVal, CGM.IntPtrTy);
422 llvm::Constant *Diff =
423 llvm::ConstantExpr::getSub(PtrValAsInt, ImageBaseAsInt,
424 /*HasNUW=*/true, /*HasNSW=*/true);
425 return llvm::ConstantExpr::getTrunc(Diff, CGM.IntTy);
429 MicrosoftMangleContext &getMangleContext() {
430 return cast<MicrosoftMangleContext>(CodeGen::CGCXXABI::getMangleContext());
433 llvm::Constant *getZeroInt() {
434 return llvm::ConstantInt::get(CGM.IntTy, 0);
437 llvm::Constant *getAllOnesInt() {
438 return llvm::Constant::getAllOnesValue(CGM.IntTy);
441 llvm::Constant *getConstantOrZeroInt(llvm::Constant *C) {
442 return C ? C : getZeroInt();
445 llvm::Value *getValueOrZeroInt(llvm::Value *C) {
446 return C ? C : getZeroInt();
449 CharUnits getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD);
452 GetNullMemberPointerFields(const MemberPointerType *MPT,
453 llvm::SmallVectorImpl<llvm::Constant *> &fields);
455 /// \brief Shared code for virtual base adjustment. Returns the offset from
456 /// the vbptr to the virtual base. Optionally returns the address of the
458 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
460 llvm::Value *VBPtrOffset,
461 llvm::Value *VBTableOffset,
462 llvm::Value **VBPtr = nullptr);
464 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
467 int32_t VBTableOffset,
468 llvm::Value **VBPtr = nullptr) {
469 assert(VBTableOffset % 4 == 0 && "should be byte offset into table of i32s");
470 llvm::Value *VBPOffset = llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset),
471 *VBTOffset = llvm::ConstantInt::get(CGM.IntTy, VBTableOffset);
472 return GetVBaseOffsetFromVBPtr(CGF, Base, VBPOffset, VBTOffset, VBPtr);
475 std::pair<llvm::Value *, llvm::Value *>
476 performBaseAdjustment(CodeGenFunction &CGF, llvm::Value *Value,
477 QualType SrcRecordTy);
479 /// \brief Performs a full virtual base adjustment. Used to dereference
480 /// pointers to members of virtual bases.
481 llvm::Value *AdjustVirtualBase(CodeGenFunction &CGF, const Expr *E,
482 const CXXRecordDecl *RD, llvm::Value *Base,
483 llvm::Value *VirtualBaseAdjustmentOffset,
484 llvm::Value *VBPtrOffset /* optional */);
486 /// \brief Emits a full member pointer with the fields common to data and
487 /// function member pointers.
488 llvm::Constant *EmitFullMemberPointer(llvm::Constant *FirstField,
489 bool IsMemberFunction,
490 const CXXRecordDecl *RD,
491 CharUnits NonVirtualBaseAdjustment);
493 llvm::Constant *BuildMemberPointer(const CXXRecordDecl *RD,
494 const CXXMethodDecl *MD,
495 CharUnits NonVirtualBaseAdjustment);
497 bool MemberPointerConstantIsNull(const MemberPointerType *MPT,
500 /// \brief - Initialize all vbptrs of 'this' with RD as the complete type.
501 void EmitVBPtrStores(CodeGenFunction &CGF, const CXXRecordDecl *RD);
503 /// \brief Caching wrapper around VBTableBuilder::enumerateVBTables().
504 const VBTableGlobals &enumerateVBTables(const CXXRecordDecl *RD);
506 /// \brief Generate a thunk for calling a virtual member function MD.
507 llvm::Function *EmitVirtualMemPtrThunk(
508 const CXXMethodDecl *MD,
509 const MicrosoftVTableContext::MethodVFTableLocation &ML);
512 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override;
514 bool isZeroInitializable(const MemberPointerType *MPT) override;
516 bool isMemberPointerConvertible(const MemberPointerType *MPT) const override {
517 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
518 return RD->hasAttr<MSInheritanceAttr>();
521 bool isTypeInfoCalculable(QualType Ty) const override {
522 if (!CGCXXABI::isTypeInfoCalculable(Ty))
524 if (const auto *MPT = Ty->getAs<MemberPointerType>()) {
525 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
526 if (!RD->hasAttr<MSInheritanceAttr>())
532 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override;
534 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
535 CharUnits offset) override;
536 llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD) override;
537 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override;
539 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
542 const MemberPointerType *MPT,
543 bool Inequality) override;
545 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
547 const MemberPointerType *MPT) override;
550 EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
551 llvm::Value *Base, llvm::Value *MemPtr,
552 const MemberPointerType *MPT) override;
554 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
556 llvm::Value *Src) override;
558 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
559 llvm::Constant *Src) override;
562 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF, const Expr *E,
563 llvm::Value *&This, llvm::Value *MemPtr,
564 const MemberPointerType *MPT) override;
566 void emitCXXStructor(const CXXMethodDecl *MD, StructorType Type) override;
569 typedef std::pair<const CXXRecordDecl *, CharUnits> VFTableIdTy;
570 typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalVariable *> VTablesMapTy;
571 typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalValue *> VFTablesMapTy;
572 /// \brief All the vftables that have been referenced.
573 VFTablesMapTy VFTablesMap;
574 VTablesMapTy VTablesMap;
576 /// \brief This set holds the record decls we've deferred vtable emission for.
577 llvm::SmallPtrSet<const CXXRecordDecl *, 4> DeferredVFTables;
580 /// \brief All the vbtables which have been referenced.
581 llvm::DenseMap<const CXXRecordDecl *, VBTableGlobals> VBTablesMap;
583 /// Info on the global variable used to guard initialization of static locals.
584 /// The BitIndex field is only used for externally invisible declarations.
586 GuardInfo() : Guard(nullptr), BitIndex(0) {}
587 llvm::GlobalVariable *Guard;
591 /// Map from DeclContext to the current guard variable. We assume that the
592 /// AST is visited in source code order.
593 llvm::DenseMap<const DeclContext *, GuardInfo> GuardVariableMap;
595 llvm::DenseMap<size_t, llvm::StructType *> TypeDescriptorTypeMap;
596 llvm::StructType *BaseClassDescriptorType;
597 llvm::StructType *ClassHierarchyDescriptorType;
598 llvm::StructType *CompleteObjectLocatorType;
603 CGCXXABI::RecordArgABI
604 MicrosoftCXXABI::getRecordArgABI(const CXXRecordDecl *RD) const {
605 switch (CGM.getTarget().getTriple().getArch()) {
607 // FIXME: Implement for other architectures.
610 case llvm::Triple::x86:
611 // All record arguments are passed in memory on x86. Decide whether to
612 // construct the object directly in argument memory, or to construct the
613 // argument elsewhere and copy the bytes during the call.
615 // If C++ prohibits us from making a copy, construct the arguments directly
616 // into argument memory.
617 if (!canCopyArgument(RD))
618 return RAA_DirectInMemory;
620 // Otherwise, construct the argument into a temporary and copy the bytes
621 // into the outgoing argument memory.
624 case llvm::Triple::x86_64:
625 // Win64 passes objects with non-trivial copy ctors indirectly.
626 if (RD->hasNonTrivialCopyConstructor())
629 // If an object has a destructor, we'd really like to pass it indirectly
630 // because it allows us to elide copies. Unfortunately, MSVC makes that
631 // impossible for small types, which it will pass in a single register or
632 // stack slot. Most objects with dtors are large-ish, so handle that early.
633 // We can't call out all large objects as being indirect because there are
634 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
635 // how we pass large POD types.
636 if (RD->hasNonTrivialDestructor() &&
637 getContext().getTypeSize(RD->getTypeForDecl()) > 64)
640 // We have a trivial copy constructor or no copy constructors, but we have
641 // to make sure it isn't deleted.
642 bool CopyDeleted = false;
643 for (const CXXConstructorDecl *CD : RD->ctors()) {
644 if (CD->isCopyConstructor()) {
645 assert(CD->isTrivial());
646 // We had at least one undeleted trivial copy ctor. Return directly.
647 if (!CD->isDeleted())
653 // The trivial copy constructor was deleted. Return indirectly.
657 // There were no copy ctors. Return in RAX.
661 llvm_unreachable("invalid enum");
664 void MicrosoftCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
665 const CXXDeleteExpr *DE,
667 QualType ElementType,
668 const CXXDestructorDecl *Dtor) {
669 // FIXME: Provide a source location here even though there's no
670 // CXXMemberCallExpr for dtor call.
671 bool UseGlobalDelete = DE->isGlobalDelete();
672 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
673 llvm::Value *MDThis =
674 EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, /*CE=*/nullptr);
676 CGF.EmitDeleteCall(DE->getOperatorDelete(), MDThis, ElementType);
679 static llvm::Function *getRethrowFn(CodeGenModule &CGM) {
680 // _CxxThrowException takes two pointer width arguments: a value and a context
681 // object which points to a TypeInfo object.
682 llvm::Type *ArgTypes[] = {CGM.Int8PtrTy, CGM.Int8PtrTy};
683 llvm::FunctionType *FTy =
684 llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
685 auto *Fn = cast<llvm::Function>(
686 CGM.CreateRuntimeFunction(FTy, "_CxxThrowException"));
687 // _CxxThrowException is stdcall on 32-bit x86 platforms.
688 if (CGM.getTarget().getTriple().getArch() == llvm::Triple::x86)
689 Fn->setCallingConv(llvm::CallingConv::X86_StdCall);
693 void MicrosoftCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
694 llvm::Value *Args[] = {llvm::ConstantPointerNull::get(CGM.Int8PtrTy),
695 llvm::ConstantPointerNull::get(CGM.Int8PtrTy)};
696 auto *Fn = getRethrowFn(CGM);
698 CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, Args);
700 CGF.EmitRuntimeCallOrInvoke(Fn, Args);
704 struct CallEndCatchMSVC : EHScopeStack::Cleanup {
705 CallEndCatchMSVC() {}
706 void Emit(CodeGenFunction &CGF, Flags flags) override {
707 CGF.EmitNounwindRuntimeCall(
708 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_endcatch));
713 void MicrosoftCXXABI::emitBeginCatch(CodeGenFunction &CGF,
714 const CXXCatchStmt *S) {
715 // In the MS ABI, the runtime handles the copy, and the catch handler is
716 // responsible for destruction.
717 VarDecl *CatchParam = S->getExceptionDecl();
718 llvm::Value *Exn = CGF.getExceptionFromSlot();
719 llvm::Function *BeginCatch =
720 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_begincatch);
723 llvm::Value *Args[2] = {Exn, llvm::Constant::getNullValue(CGF.Int8PtrTy)};
724 CGF.EmitNounwindRuntimeCall(BeginCatch, Args);
725 CGF.EHStack.pushCleanup<CallEndCatchMSVC>(NormalAndEHCleanup);
729 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
730 llvm::Value *ParamAddr =
731 CGF.Builder.CreateBitCast(var.getObjectAddress(CGF), CGF.Int8PtrTy);
732 llvm::Value *Args[2] = {Exn, ParamAddr};
733 CGF.EmitNounwindRuntimeCall(BeginCatch, Args);
734 // FIXME: Do we really need exceptional endcatch cleanups?
735 CGF.EHStack.pushCleanup<CallEndCatchMSVC>(NormalAndEHCleanup);
736 CGF.EmitAutoVarCleanups(var);
739 std::pair<llvm::Value *, llvm::Value *>
740 MicrosoftCXXABI::performBaseAdjustment(CodeGenFunction &CGF, llvm::Value *Value,
741 QualType SrcRecordTy) {
742 Value = CGF.Builder.CreateBitCast(Value, CGF.Int8PtrTy);
743 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
744 const ASTContext &Context = CGF.getContext();
746 if (Context.getASTRecordLayout(SrcDecl).hasExtendableVFPtr())
747 return std::make_pair(Value, llvm::ConstantInt::get(CGF.Int32Ty, 0));
749 // Perform a base adjustment.
750 const CXXBaseSpecifier *PolymorphicBase = std::find_if(
751 SrcDecl->vbases_begin(), SrcDecl->vbases_end(),
752 [&](const CXXBaseSpecifier &Base) {
753 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
754 return Context.getASTRecordLayout(BaseDecl).hasExtendableVFPtr();
756 llvm::Value *Offset = GetVirtualBaseClassOffset(
757 CGF, Value, SrcDecl, PolymorphicBase->getType()->getAsCXXRecordDecl());
758 Value = CGF.Builder.CreateInBoundsGEP(Value, Offset);
759 Offset = CGF.Builder.CreateTrunc(Offset, CGF.Int32Ty);
760 return std::make_pair(Value, Offset);
763 bool MicrosoftCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
764 QualType SrcRecordTy) {
765 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
767 !CGM.getContext().getASTRecordLayout(SrcDecl).hasExtendableVFPtr();
770 static llvm::CallSite emitRTtypeidCall(CodeGenFunction &CGF,
771 llvm::Value *Argument) {
772 llvm::Type *ArgTypes[] = {CGF.Int8PtrTy};
773 llvm::FunctionType *FTy =
774 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false);
775 llvm::Value *Args[] = {Argument};
776 llvm::Constant *Fn = CGF.CGM.CreateRuntimeFunction(FTy, "__RTtypeid");
777 return CGF.EmitRuntimeCallOrInvoke(Fn, Args);
780 void MicrosoftCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
781 llvm::CallSite Call =
782 emitRTtypeidCall(CGF, llvm::Constant::getNullValue(CGM.VoidPtrTy));
783 Call.setDoesNotReturn();
784 CGF.Builder.CreateUnreachable();
787 llvm::Value *MicrosoftCXXABI::EmitTypeid(CodeGenFunction &CGF,
788 QualType SrcRecordTy,
789 llvm::Value *ThisPtr,
790 llvm::Type *StdTypeInfoPtrTy) {
792 std::tie(ThisPtr, Offset) = performBaseAdjustment(CGF, ThisPtr, SrcRecordTy);
793 return CGF.Builder.CreateBitCast(
794 emitRTtypeidCall(CGF, ThisPtr).getInstruction(), StdTypeInfoPtrTy);
797 bool MicrosoftCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
798 QualType SrcRecordTy) {
799 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
801 !CGM.getContext().getASTRecordLayout(SrcDecl).hasExtendableVFPtr();
804 llvm::Value *MicrosoftCXXABI::EmitDynamicCastCall(
805 CodeGenFunction &CGF, llvm::Value *Value, QualType SrcRecordTy,
806 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
807 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
809 llvm::Value *SrcRTTI =
810 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
811 llvm::Value *DestRTTI =
812 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
815 std::tie(Value, Offset) = performBaseAdjustment(CGF, Value, SrcRecordTy);
817 // PVOID __RTDynamicCast(
823 llvm::Type *ArgTypes[] = {CGF.Int8PtrTy, CGF.Int32Ty, CGF.Int8PtrTy,
824 CGF.Int8PtrTy, CGF.Int32Ty};
825 llvm::Constant *Function = CGF.CGM.CreateRuntimeFunction(
826 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false),
828 llvm::Value *Args[] = {
829 Value, Offset, SrcRTTI, DestRTTI,
830 llvm::ConstantInt::get(CGF.Int32Ty, DestTy->isReferenceType())};
831 Value = CGF.EmitRuntimeCallOrInvoke(Function, Args).getInstruction();
832 return CGF.Builder.CreateBitCast(Value, DestLTy);
836 MicrosoftCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF, llvm::Value *Value,
837 QualType SrcRecordTy,
840 std::tie(Value, Offset) = performBaseAdjustment(CGF, Value, SrcRecordTy);
842 // PVOID __RTCastToVoid(
844 llvm::Type *ArgTypes[] = {CGF.Int8PtrTy};
845 llvm::Constant *Function = CGF.CGM.CreateRuntimeFunction(
846 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false),
848 llvm::Value *Args[] = {Value};
849 return CGF.EmitRuntimeCall(Function, Args);
852 bool MicrosoftCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
856 llvm::Value *MicrosoftCXXABI::GetVirtualBaseClassOffset(
857 CodeGenFunction &CGF, llvm::Value *This, const CXXRecordDecl *ClassDecl,
858 const CXXRecordDecl *BaseClassDecl) {
860 getContext().getASTRecordLayout(ClassDecl).getVBPtrOffset().getQuantity();
861 llvm::Value *VBPtrOffset = llvm::ConstantInt::get(CGM.PtrDiffTy, VBPtrChars);
862 CharUnits IntSize = getContext().getTypeSizeInChars(getContext().IntTy);
863 CharUnits VBTableChars =
865 CGM.getMicrosoftVTableContext().getVBTableIndex(ClassDecl, BaseClassDecl);
866 llvm::Value *VBTableOffset =
867 llvm::ConstantInt::get(CGM.IntTy, VBTableChars.getQuantity());
869 llvm::Value *VBPtrToNewBase =
870 GetVBaseOffsetFromVBPtr(CGF, This, VBPtrOffset, VBTableOffset);
872 CGF.Builder.CreateSExtOrBitCast(VBPtrToNewBase, CGM.PtrDiffTy);
873 return CGF.Builder.CreateNSWAdd(VBPtrOffset, VBPtrToNewBase);
876 bool MicrosoftCXXABI::HasThisReturn(GlobalDecl GD) const {
877 return isa<CXXConstructorDecl>(GD.getDecl());
880 static bool isDeletingDtor(GlobalDecl GD) {
881 return isa<CXXDestructorDecl>(GD.getDecl()) &&
882 GD.getDtorType() == Dtor_Deleting;
885 bool MicrosoftCXXABI::hasMostDerivedReturn(GlobalDecl GD) const {
886 return isDeletingDtor(GD);
889 bool MicrosoftCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
890 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
894 if (FI.isInstanceMethod()) {
895 // If it's an instance method, aggregates are always returned indirectly via
896 // the second parameter.
897 FI.getReturnInfo() = ABIArgInfo::getIndirect(0, /*ByVal=*/false);
898 FI.getReturnInfo().setSRetAfterThis(FI.isInstanceMethod());
900 } else if (!RD->isPOD()) {
901 // If it's a free function, non-POD types are returned indirectly.
902 FI.getReturnInfo() = ABIArgInfo::getIndirect(0, /*ByVal=*/false);
906 // Otherwise, use the C ABI rules.
911 MicrosoftCXXABI::EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
912 const CXXRecordDecl *RD) {
913 llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);
914 assert(IsMostDerivedClass &&
915 "ctor for a class with virtual bases must have an implicit parameter");
916 llvm::Value *IsCompleteObject =
917 CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");
919 llvm::BasicBlock *CallVbaseCtorsBB = CGF.createBasicBlock("ctor.init_vbases");
920 llvm::BasicBlock *SkipVbaseCtorsBB = CGF.createBasicBlock("ctor.skip_vbases");
921 CGF.Builder.CreateCondBr(IsCompleteObject,
922 CallVbaseCtorsBB, SkipVbaseCtorsBB);
924 CGF.EmitBlock(CallVbaseCtorsBB);
926 // Fill in the vbtable pointers here.
927 EmitVBPtrStores(CGF, RD);
929 // CGF will put the base ctor calls in this basic block for us later.
931 return SkipVbaseCtorsBB;
934 void MicrosoftCXXABI::initializeHiddenVirtualInheritanceMembers(
935 CodeGenFunction &CGF, const CXXRecordDecl *RD) {
936 // In most cases, an override for a vbase virtual method can adjust
937 // the "this" parameter by applying a constant offset.
938 // However, this is not enough while a constructor or a destructor of some
939 // class X is being executed if all the following conditions are met:
940 // - X has virtual bases, (1)
941 // - X overrides a virtual method M of a vbase Y, (2)
942 // - X itself is a vbase of the most derived class.
944 // If (1) and (2) are true, the vtorDisp for vbase Y is a hidden member of X
945 // which holds the extra amount of "this" adjustment we must do when we use
946 // the X vftables (i.e. during X ctor or dtor).
947 // Outside the ctors and dtors, the values of vtorDisps are zero.
949 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
950 typedef ASTRecordLayout::VBaseOffsetsMapTy VBOffsets;
951 const VBOffsets &VBaseMap = Layout.getVBaseOffsetsMap();
952 CGBuilderTy &Builder = CGF.Builder;
955 cast<llvm::PointerType>(getThisValue(CGF)->getType())->getAddressSpace();
956 llvm::Value *Int8This = nullptr; // Initialize lazily.
958 for (VBOffsets::const_iterator I = VBaseMap.begin(), E = VBaseMap.end();
960 if (!I->second.hasVtorDisp())
963 llvm::Value *VBaseOffset =
964 GetVirtualBaseClassOffset(CGF, getThisValue(CGF), RD, I->first);
965 // FIXME: it doesn't look right that we SExt in GetVirtualBaseClassOffset()
966 // just to Trunc back immediately.
967 VBaseOffset = Builder.CreateTruncOrBitCast(VBaseOffset, CGF.Int32Ty);
968 uint64_t ConstantVBaseOffset =
969 Layout.getVBaseClassOffset(I->first).getQuantity();
971 // vtorDisp_for_vbase = vbptr[vbase_idx] - offsetof(RD, vbase).
972 llvm::Value *VtorDispValue = Builder.CreateSub(
973 VBaseOffset, llvm::ConstantInt::get(CGM.Int32Ty, ConstantVBaseOffset),
977 Int8This = Builder.CreateBitCast(getThisValue(CGF),
978 CGF.Int8Ty->getPointerTo(AS));
979 llvm::Value *VtorDispPtr = Builder.CreateInBoundsGEP(Int8This, VBaseOffset);
980 // vtorDisp is always the 32-bits before the vbase in the class layout.
981 VtorDispPtr = Builder.CreateConstGEP1_32(VtorDispPtr, -4);
982 VtorDispPtr = Builder.CreateBitCast(
983 VtorDispPtr, CGF.Int32Ty->getPointerTo(AS), "vtordisp.ptr");
985 Builder.CreateStore(VtorDispValue, VtorDispPtr);
989 void MicrosoftCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
990 // There's only one constructor type in this ABI.
991 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
994 void MicrosoftCXXABI::EmitVBPtrStores(CodeGenFunction &CGF,
995 const CXXRecordDecl *RD) {
996 llvm::Value *ThisInt8Ptr =
997 CGF.Builder.CreateBitCast(getThisValue(CGF), CGM.Int8PtrTy, "this.int8");
998 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1000 const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
1001 for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) {
1002 const VPtrInfo *VBT = (*VBGlobals.VBTables)[I];
1003 llvm::GlobalVariable *GV = VBGlobals.Globals[I];
1004 const ASTRecordLayout &SubobjectLayout =
1005 CGM.getContext().getASTRecordLayout(VBT->BaseWithVPtr);
1006 CharUnits Offs = VBT->NonVirtualOffset;
1007 Offs += SubobjectLayout.getVBPtrOffset();
1008 if (VBT->getVBaseWithVPtr())
1009 Offs += Layout.getVBaseClassOffset(VBT->getVBaseWithVPtr());
1010 llvm::Value *VBPtr =
1011 CGF.Builder.CreateConstInBoundsGEP1_64(ThisInt8Ptr, Offs.getQuantity());
1012 llvm::Value *GVPtr = CGF.Builder.CreateConstInBoundsGEP2_32(GV, 0, 0);
1013 VBPtr = CGF.Builder.CreateBitCast(VBPtr, GVPtr->getType()->getPointerTo(0),
1014 "vbptr." + VBT->ReusingBase->getName());
1015 CGF.Builder.CreateStore(GVPtr, VBPtr);
1020 MicrosoftCXXABI::buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
1021 SmallVectorImpl<CanQualType> &ArgTys) {
1022 // TODO: 'for base' flag
1023 if (T == StructorType::Deleting) {
1024 // The scalar deleting destructor takes an implicit int parameter.
1025 ArgTys.push_back(CGM.getContext().IntTy);
1027 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
1031 // All parameters are already in place except is_most_derived, which goes
1032 // after 'this' if it's variadic and last if it's not.
1034 const CXXRecordDecl *Class = CD->getParent();
1035 const FunctionProtoType *FPT = CD->getType()->castAs<FunctionProtoType>();
1036 if (Class->getNumVBases()) {
1037 if (FPT->isVariadic())
1038 ArgTys.insert(ArgTys.begin() + 1, CGM.getContext().IntTy);
1040 ArgTys.push_back(CGM.getContext().IntTy);
1044 void MicrosoftCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
1045 // The TU defining a dtor is only guaranteed to emit a base destructor. All
1046 // other destructor variants are delegating thunks.
1047 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
1051 MicrosoftCXXABI::getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD) {
1052 GD = GD.getCanonicalDecl();
1053 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1055 GlobalDecl LookupGD = GD;
1056 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1057 // Complete destructors take a pointer to the complete object as a
1058 // parameter, thus don't need this adjustment.
1059 if (GD.getDtorType() == Dtor_Complete)
1062 // There's no Dtor_Base in vftable but it shares the this adjustment with
1063 // the deleting one, so look it up instead.
1064 LookupGD = GlobalDecl(DD, Dtor_Deleting);
1067 MicrosoftVTableContext::MethodVFTableLocation ML =
1068 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD);
1069 CharUnits Adjustment = ML.VFPtrOffset;
1071 // Normal virtual instance methods need to adjust from the vfptr that first
1072 // defined the virtual method to the virtual base subobject, but destructors
1073 // do not. The vector deleting destructor thunk applies this adjustment for
1075 if (isa<CXXDestructorDecl>(MD))
1076 Adjustment = CharUnits::Zero();
1079 const ASTRecordLayout &DerivedLayout =
1080 CGM.getContext().getASTRecordLayout(MD->getParent());
1081 Adjustment += DerivedLayout.getVBaseClassOffset(ML.VBase);
1087 llvm::Value *MicrosoftCXXABI::adjustThisArgumentForVirtualFunctionCall(
1088 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This, bool VirtualCall) {
1090 // If the call of a virtual function is not virtual, we just have to
1091 // compensate for the adjustment the virtual function does in its prologue.
1092 CharUnits Adjustment = getVirtualFunctionPrologueThisAdjustment(GD);
1093 if (Adjustment.isZero())
1096 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
1097 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS);
1098 This = CGF.Builder.CreateBitCast(This, charPtrTy);
1099 assert(Adjustment.isPositive());
1100 return CGF.Builder.CreateConstGEP1_32(This, Adjustment.getQuantity());
1103 GD = GD.getCanonicalDecl();
1104 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1106 GlobalDecl LookupGD = GD;
1107 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1108 // Complete dtors take a pointer to the complete object,
1109 // thus don't need adjustment.
1110 if (GD.getDtorType() == Dtor_Complete)
1113 // There's only Dtor_Deleting in vftable but it shares the this adjustment
1114 // with the base one, so look up the deleting one instead.
1115 LookupGD = GlobalDecl(DD, Dtor_Deleting);
1117 MicrosoftVTableContext::MethodVFTableLocation ML =
1118 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD);
1120 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
1121 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS);
1122 CharUnits StaticOffset = ML.VFPtrOffset;
1124 // Base destructors expect 'this' to point to the beginning of the base
1125 // subobject, not the first vfptr that happens to contain the virtual dtor.
1126 // However, we still need to apply the virtual base adjustment.
1127 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
1128 StaticOffset = CharUnits::Zero();
1131 This = CGF.Builder.CreateBitCast(This, charPtrTy);
1132 llvm::Value *VBaseOffset =
1133 GetVirtualBaseClassOffset(CGF, This, MD->getParent(), ML.VBase);
1134 This = CGF.Builder.CreateInBoundsGEP(This, VBaseOffset);
1136 if (!StaticOffset.isZero()) {
1137 assert(StaticOffset.isPositive());
1138 This = CGF.Builder.CreateBitCast(This, charPtrTy);
1140 // Non-virtual adjustment might result in a pointer outside the allocated
1141 // object, e.g. if the final overrider class is laid out after the virtual
1142 // base that declares a method in the most derived class.
1143 // FIXME: Update the code that emits this adjustment in thunks prologues.
1144 This = CGF.Builder.CreateConstGEP1_32(This, StaticOffset.getQuantity());
1146 This = CGF.Builder.CreateConstInBoundsGEP1_32(This,
1147 StaticOffset.getQuantity());
1153 void MicrosoftCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1155 FunctionArgList &Params) {
1156 ASTContext &Context = getContext();
1157 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
1158 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
1159 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
1160 ImplicitParamDecl *IsMostDerived
1161 = ImplicitParamDecl::Create(Context, nullptr,
1162 CGF.CurGD.getDecl()->getLocation(),
1163 &Context.Idents.get("is_most_derived"),
1165 // The 'most_derived' parameter goes second if the ctor is variadic and last
1166 // if it's not. Dtors can't be variadic.
1167 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
1168 if (FPT->isVariadic())
1169 Params.insert(Params.begin() + 1, IsMostDerived);
1171 Params.push_back(IsMostDerived);
1172 getStructorImplicitParamDecl(CGF) = IsMostDerived;
1173 } else if (isDeletingDtor(CGF.CurGD)) {
1174 ImplicitParamDecl *ShouldDelete
1175 = ImplicitParamDecl::Create(Context, nullptr,
1176 CGF.CurGD.getDecl()->getLocation(),
1177 &Context.Idents.get("should_call_delete"),
1179 Params.push_back(ShouldDelete);
1180 getStructorImplicitParamDecl(CGF) = ShouldDelete;
1184 llvm::Value *MicrosoftCXXABI::adjustThisParameterInVirtualFunctionPrologue(
1185 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) {
1186 // In this ABI, every virtual function takes a pointer to one of the
1187 // subobjects that first defines it as the 'this' parameter, rather than a
1188 // pointer to the final overrider subobject. Thus, we need to adjust it back
1189 // to the final overrider subobject before use.
1190 // See comments in the MicrosoftVFTableContext implementation for the details.
1191 CharUnits Adjustment = getVirtualFunctionPrologueThisAdjustment(GD);
1192 if (Adjustment.isZero())
1195 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
1196 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS),
1197 *thisTy = This->getType();
1199 This = CGF.Builder.CreateBitCast(This, charPtrTy);
1200 assert(Adjustment.isPositive());
1202 CGF.Builder.CreateConstInBoundsGEP1_32(This, -Adjustment.getQuantity());
1203 return CGF.Builder.CreateBitCast(This, thisTy);
1206 void MicrosoftCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
1209 /// If this is a function that the ABI specifies returns 'this', initialize
1210 /// the return slot to 'this' at the start of the function.
1212 /// Unlike the setting of return types, this is done within the ABI
1213 /// implementation instead of by clients of CGCXXABI because:
1214 /// 1) getThisValue is currently protected
1215 /// 2) in theory, an ABI could implement 'this' returns some other way;
1216 /// HasThisReturn only specifies a contract, not the implementation
1217 if (HasThisReturn(CGF.CurGD))
1218 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
1219 else if (hasMostDerivedReturn(CGF.CurGD))
1220 CGF.Builder.CreateStore(CGF.EmitCastToVoidPtr(getThisValue(CGF)),
1223 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
1224 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
1225 assert(getStructorImplicitParamDecl(CGF) &&
1226 "no implicit parameter for a constructor with virtual bases?");
1227 getStructorImplicitParamValue(CGF)
1228 = CGF.Builder.CreateLoad(
1229 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
1233 if (isDeletingDtor(CGF.CurGD)) {
1234 assert(getStructorImplicitParamDecl(CGF) &&
1235 "no implicit parameter for a deleting destructor?");
1236 getStructorImplicitParamValue(CGF)
1237 = CGF.Builder.CreateLoad(
1238 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
1239 "should_call_delete");
1243 unsigned MicrosoftCXXABI::addImplicitConstructorArgs(
1244 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1245 bool ForVirtualBase, bool Delegating, CallArgList &Args) {
1246 assert(Type == Ctor_Complete || Type == Ctor_Base);
1248 // Check if we need a 'most_derived' parameter.
1249 if (!D->getParent()->getNumVBases())
1252 // Add the 'most_derived' argument second if we are variadic or last if not.
1253 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
1254 llvm::Value *MostDerivedArg =
1255 llvm::ConstantInt::get(CGM.Int32Ty, Type == Ctor_Complete);
1256 RValue RV = RValue::get(MostDerivedArg);
1257 if (MostDerivedArg) {
1258 if (FPT->isVariadic())
1259 Args.insert(Args.begin() + 1,
1260 CallArg(RV, getContext().IntTy, /*needscopy=*/false));
1262 Args.add(RV, getContext().IntTy);
1265 return 1; // Added one arg.
1268 void MicrosoftCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1269 const CXXDestructorDecl *DD,
1270 CXXDtorType Type, bool ForVirtualBase,
1271 bool Delegating, llvm::Value *This) {
1272 llvm::Value *Callee = CGM.getAddrOfCXXStructor(DD, getFromDtorType(Type));
1274 if (DD->isVirtual()) {
1275 assert(Type != CXXDtorType::Dtor_Deleting &&
1276 "The deleting destructor should only be called via a virtual call");
1277 This = adjustThisArgumentForVirtualFunctionCall(CGF, GlobalDecl(DD, Type),
1281 CGF.EmitCXXStructorCall(DD, Callee, ReturnValueSlot(), This,
1282 /*ImplicitParam=*/nullptr,
1283 /*ImplicitParamTy=*/QualType(), nullptr,
1284 getFromDtorType(Type));
1287 void MicrosoftCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1288 const CXXRecordDecl *RD) {
1289 MicrosoftVTableContext &VFTContext = CGM.getMicrosoftVTableContext();
1290 const VPtrInfoVector &VFPtrs = VFTContext.getVFPtrOffsets(RD);
1292 for (VPtrInfo *Info : VFPtrs) {
1293 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, Info->FullOffsetInMDC);
1294 if (VTable->hasInitializer())
1297 llvm::Constant *RTTI = getContext().getLangOpts().RTTIData
1298 ? getMSCompleteObjectLocator(RD, Info)
1301 const VTableLayout &VTLayout =
1302 VFTContext.getVFTableLayout(RD, Info->FullOffsetInMDC);
1303 llvm::Constant *Init = CGVT.CreateVTableInitializer(
1304 RD, VTLayout.vtable_component_begin(),
1305 VTLayout.getNumVTableComponents(), VTLayout.vtable_thunk_begin(),
1306 VTLayout.getNumVTableThunks(), RTTI);
1308 VTable->setInitializer(Init);
1312 llvm::Value *MicrosoftCXXABI::getVTableAddressPointInStructor(
1313 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1314 const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) {
1315 NeedsVirtualOffset = (NearestVBase != nullptr);
1317 (void)getAddrOfVTable(VTableClass, Base.getBaseOffset());
1318 VFTableIdTy ID(VTableClass, Base.getBaseOffset());
1319 llvm::GlobalValue *VTableAddressPoint = VFTablesMap[ID];
1320 if (!VTableAddressPoint) {
1321 assert(Base.getBase()->getNumVBases() &&
1322 !CGM.getContext().getASTRecordLayout(Base.getBase()).hasOwnVFPtr());
1324 return VTableAddressPoint;
1327 static void mangleVFTableName(MicrosoftMangleContext &MangleContext,
1328 const CXXRecordDecl *RD, const VPtrInfo *VFPtr,
1329 SmallString<256> &Name) {
1330 llvm::raw_svector_ostream Out(Name);
1331 MangleContext.mangleCXXVFTable(RD, VFPtr->MangledPath, Out);
1334 llvm::Constant *MicrosoftCXXABI::getVTableAddressPointForConstExpr(
1335 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1336 (void)getAddrOfVTable(VTableClass, Base.getBaseOffset());
1337 VFTableIdTy ID(VTableClass, Base.getBaseOffset());
1338 llvm::GlobalValue *VFTable = VFTablesMap[ID];
1339 assert(VFTable && "Couldn't find a vftable for the given base?");
1343 llvm::GlobalVariable *MicrosoftCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1344 CharUnits VPtrOffset) {
1345 // getAddrOfVTable may return 0 if asked to get an address of a vtable which
1346 // shouldn't be used in the given record type. We want to cache this result in
1347 // VFTablesMap, thus a simple zero check is not sufficient.
1348 VFTableIdTy ID(RD, VPtrOffset);
1349 VTablesMapTy::iterator I;
1351 std::tie(I, Inserted) = VTablesMap.insert(std::make_pair(ID, nullptr));
1355 llvm::GlobalVariable *&VTable = I->second;
1357 MicrosoftVTableContext &VTContext = CGM.getMicrosoftVTableContext();
1358 const VPtrInfoVector &VFPtrs = VTContext.getVFPtrOffsets(RD);
1360 if (DeferredVFTables.insert(RD).second) {
1361 // We haven't processed this record type before.
1362 // Queue up this v-table for possible deferred emission.
1363 CGM.addDeferredVTable(RD);
1366 // Create all the vftables at once in order to make sure each vftable has
1367 // a unique mangled name.
1368 llvm::StringSet<> ObservedMangledNames;
1369 for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) {
1370 SmallString<256> Name;
1371 mangleVFTableName(getMangleContext(), RD, VFPtrs[J], Name);
1372 if (!ObservedMangledNames.insert(Name.str()).second)
1373 llvm_unreachable("Already saw this mangling before?");
1378 for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) {
1379 if (VFPtrs[J]->FullOffsetInMDC != VPtrOffset)
1381 SmallString<256> VFTableName;
1382 mangleVFTableName(getMangleContext(), RD, VFPtrs[J], VFTableName);
1383 StringRef VTableName = VFTableName;
1385 uint64_t NumVTableSlots =
1386 VTContext.getVFTableLayout(RD, VFPtrs[J]->FullOffsetInMDC)
1387 .getNumVTableComponents();
1388 llvm::GlobalValue::LinkageTypes VTableLinkage =
1389 llvm::GlobalValue::ExternalLinkage;
1390 llvm::ArrayType *VTableType =
1391 llvm::ArrayType::get(CGM.Int8PtrTy, NumVTableSlots);
1392 if (getContext().getLangOpts().RTTIData) {
1393 VTableLinkage = llvm::GlobalValue::PrivateLinkage;
1397 VTable = CGM.getModule().getNamedGlobal(VFTableName);
1399 // Create a backing variable for the contents of VTable. The VTable may
1400 // or may not include space for a pointer to RTTI data.
1401 llvm::GlobalValue *VFTable = VTable = new llvm::GlobalVariable(
1402 CGM.getModule(), VTableType, /*isConstant=*/true, VTableLinkage,
1403 /*Initializer=*/nullptr, VTableName);
1404 VTable->setUnnamedAddr(true);
1406 // Only insert a pointer into the VFTable for RTTI data if we are not
1407 // importing it. We never reference the RTTI data directly so there is no
1408 // need to make room for it.
1409 if (getContext().getLangOpts().RTTIData &&
1410 !RD->hasAttr<DLLImportAttr>()) {
1411 llvm::Value *GEPIndices[] = {llvm::ConstantInt::get(CGM.IntTy, 0),
1412 llvm::ConstantInt::get(CGM.IntTy, 1)};
1413 // Create a GEP which points just after the first entry in the VFTable,
1414 // this should be the location of the first virtual method.
1415 llvm::Constant *VTableGEP =
1416 llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, GEPIndices);
1417 // The symbol for the VFTable is an alias to the GEP. It is
1418 // transparent, to other modules, what the nature of this symbol is; all
1419 // that matters is that the alias be the address of the first virtual
1421 VFTable = llvm::GlobalAlias::create(
1422 cast<llvm::SequentialType>(VTableGEP->getType())->getElementType(),
1423 /*AddressSpace=*/0, llvm::GlobalValue::ExternalLinkage,
1424 VFTableName.str(), VTableGEP, &CGM.getModule());
1426 // We don't need a GlobalAlias to be a symbol for the VTable if we won't
1427 // be referencing any RTTI data. The GlobalVariable will end up being
1428 // an appropriate definition of the VFTable.
1429 VTable->setName(VFTableName.str());
1432 VFTable->setUnnamedAddr(true);
1433 if (RD->hasAttr<DLLImportAttr>())
1434 VFTable->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1435 else if (RD->hasAttr<DLLExportAttr>())
1436 VFTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1438 llvm::GlobalValue::LinkageTypes VFTableLinkage = CGM.getVTableLinkage(RD);
1439 if (VFTable != VTable) {
1440 if (llvm::GlobalValue::isAvailableExternallyLinkage(VFTableLinkage)) {
1441 // AvailableExternally implies that we grabbed the data from another
1442 // executable. No need to stick the alias in a Comdat.
1443 } else if (llvm::GlobalValue::isInternalLinkage(VFTableLinkage) ||
1444 llvm::GlobalValue::isWeakODRLinkage(VFTableLinkage) ||
1445 llvm::GlobalValue::isLinkOnceODRLinkage(VFTableLinkage)) {
1446 // The alias is going to be dropped into a Comdat, no need to make it
1448 if (!llvm::GlobalValue::isInternalLinkage(VFTableLinkage))
1449 VFTableLinkage = llvm::GlobalValue::ExternalLinkage;
1451 CGM.getModule().getOrInsertComdat(VFTable->getName());
1452 // We must indicate which VFTable is larger to support linking between
1453 // translation units which do and do not have RTTI data. The largest
1454 // VFTable contains the RTTI data; translation units which reference
1455 // the smaller VFTable always reference it relative to the first
1457 C->setSelectionKind(llvm::Comdat::Largest);
1458 VTable->setComdat(C);
1460 llvm_unreachable("unexpected linkage for vftable!");
1463 if (llvm::GlobalValue::isWeakForLinker(VFTableLinkage))
1465 CGM.getModule().getOrInsertComdat(VTable->getName()));
1467 VFTable->setLinkage(VFTableLinkage);
1468 CGM.setGlobalVisibility(VFTable, RD);
1469 VFTablesMap[ID] = VFTable;
1477 llvm::Value *MicrosoftCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1481 GD = GD.getCanonicalDecl();
1482 CGBuilderTy &Builder = CGF.Builder;
1484 Ty = Ty->getPointerTo()->getPointerTo();
1486 adjustThisArgumentForVirtualFunctionCall(CGF, GD, This, true);
1487 llvm::Value *VTable = CGF.GetVTablePtr(VPtr, Ty);
1489 MicrosoftVTableContext::MethodVFTableLocation ML =
1490 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD);
1491 llvm::Value *VFuncPtr =
1492 Builder.CreateConstInBoundsGEP1_64(VTable, ML.Index, "vfn");
1493 return Builder.CreateLoad(VFuncPtr);
1496 llvm::Value *MicrosoftCXXABI::EmitVirtualDestructorCall(
1497 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
1498 llvm::Value *This, const CXXMemberCallExpr *CE) {
1499 assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
1500 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1502 // We have only one destructor in the vftable but can get both behaviors
1503 // by passing an implicit int parameter.
1504 GlobalDecl GD(Dtor, Dtor_Deleting);
1505 const CGFunctionInfo *FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
1506 Dtor, StructorType::Deleting);
1507 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
1508 llvm::Value *Callee = getVirtualFunctionPointer(CGF, GD, This, Ty);
1510 ASTContext &Context = CGF.getContext();
1511 llvm::Value *ImplicitParam = llvm::ConstantInt::get(
1512 llvm::IntegerType::getInt32Ty(CGF.getLLVMContext()),
1513 DtorType == Dtor_Deleting);
1515 This = adjustThisArgumentForVirtualFunctionCall(CGF, GD, This, true);
1516 RValue RV = CGF.EmitCXXStructorCall(Dtor, Callee, ReturnValueSlot(), This,
1517 ImplicitParam, Context.IntTy, CE,
1518 StructorType::Deleting);
1519 return RV.getScalarVal();
1522 const VBTableGlobals &
1523 MicrosoftCXXABI::enumerateVBTables(const CXXRecordDecl *RD) {
1524 // At this layer, we can key the cache off of a single class, which is much
1525 // easier than caching each vbtable individually.
1526 llvm::DenseMap<const CXXRecordDecl*, VBTableGlobals>::iterator Entry;
1528 std::tie(Entry, Added) =
1529 VBTablesMap.insert(std::make_pair(RD, VBTableGlobals()));
1530 VBTableGlobals &VBGlobals = Entry->second;
1534 MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext();
1535 VBGlobals.VBTables = &Context.enumerateVBTables(RD);
1537 // Cache the globals for all vbtables so we don't have to recompute the
1539 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
1540 for (VPtrInfoVector::const_iterator I = VBGlobals.VBTables->begin(),
1541 E = VBGlobals.VBTables->end();
1543 VBGlobals.Globals.push_back(getAddrOfVBTable(**I, RD, Linkage));
1549 llvm::Function *MicrosoftCXXABI::EmitVirtualMemPtrThunk(
1550 const CXXMethodDecl *MD,
1551 const MicrosoftVTableContext::MethodVFTableLocation &ML) {
1552 assert(!isa<CXXConstructorDecl>(MD) && !isa<CXXDestructorDecl>(MD) &&
1553 "can't form pointers to ctors or virtual dtors");
1555 // Calculate the mangled name.
1556 SmallString<256> ThunkName;
1557 llvm::raw_svector_ostream Out(ThunkName);
1558 getMangleContext().mangleVirtualMemPtrThunk(MD, Out);
1561 // If the thunk has been generated previously, just return it.
1562 if (llvm::GlobalValue *GV = CGM.getModule().getNamedValue(ThunkName))
1563 return cast<llvm::Function>(GV);
1565 // Create the llvm::Function.
1566 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeMSMemberPointerThunk(MD);
1567 llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo);
1568 llvm::Function *ThunkFn =
1569 llvm::Function::Create(ThunkTy, llvm::Function::ExternalLinkage,
1570 ThunkName.str(), &CGM.getModule());
1571 assert(ThunkFn->getName() == ThunkName && "name was uniqued!");
1573 ThunkFn->setLinkage(MD->isExternallyVisible()
1574 ? llvm::GlobalValue::LinkOnceODRLinkage
1575 : llvm::GlobalValue::InternalLinkage);
1576 if (MD->isExternallyVisible())
1577 ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));
1579 CGM.SetLLVMFunctionAttributes(MD, FnInfo, ThunkFn);
1580 CGM.SetLLVMFunctionAttributesForDefinition(MD, ThunkFn);
1582 // Add the "thunk" attribute so that LLVM knows that the return type is
1583 // meaningless. These thunks can be used to call functions with differing
1584 // return types, and the caller is required to cast the prototype
1585 // appropriately to extract the correct value.
1586 ThunkFn->addFnAttr("thunk");
1588 // These thunks can be compared, so they are not unnamed.
1589 ThunkFn->setUnnamedAddr(false);
1592 CodeGenFunction CGF(CGM);
1593 CGF.CurGD = GlobalDecl(MD);
1594 CGF.CurFuncIsThunk = true;
1596 // Build FunctionArgs, but only include the implicit 'this' parameter
1598 FunctionArgList FunctionArgs;
1599 buildThisParam(CGF, FunctionArgs);
1601 // Start defining the function.
1602 CGF.StartFunction(GlobalDecl(), FnInfo.getReturnType(), ThunkFn, FnInfo,
1603 FunctionArgs, MD->getLocation(), SourceLocation());
1606 // Load the vfptr and then callee from the vftable. The callee should have
1607 // adjusted 'this' so that the vfptr is at offset zero.
1608 llvm::Value *VTable = CGF.GetVTablePtr(
1609 getThisValue(CGF), ThunkTy->getPointerTo()->getPointerTo());
1610 llvm::Value *VFuncPtr =
1611 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, ML.Index, "vfn");
1612 llvm::Value *Callee = CGF.Builder.CreateLoad(VFuncPtr);
1614 CGF.EmitMustTailThunk(MD, getThisValue(CGF), Callee);
1619 void MicrosoftCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
1620 const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
1621 for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) {
1622 const VPtrInfo *VBT = (*VBGlobals.VBTables)[I];
1623 llvm::GlobalVariable *GV = VBGlobals.Globals[I];
1624 if (GV->isDeclaration())
1625 emitVBTableDefinition(*VBT, RD, GV);
1629 llvm::GlobalVariable *
1630 MicrosoftCXXABI::getAddrOfVBTable(const VPtrInfo &VBT, const CXXRecordDecl *RD,
1631 llvm::GlobalVariable::LinkageTypes Linkage) {
1632 SmallString<256> OutName;
1633 llvm::raw_svector_ostream Out(OutName);
1634 getMangleContext().mangleCXXVBTable(RD, VBT.MangledPath, Out);
1636 StringRef Name = OutName.str();
1638 llvm::ArrayType *VBTableType =
1639 llvm::ArrayType::get(CGM.IntTy, 1 + VBT.ReusingBase->getNumVBases());
1641 assert(!CGM.getModule().getNamedGlobal(Name) &&
1642 "vbtable with this name already exists: mangling bug?");
1643 llvm::GlobalVariable *GV =
1644 CGM.CreateOrReplaceCXXRuntimeVariable(Name, VBTableType, Linkage);
1645 GV->setUnnamedAddr(true);
1647 if (RD->hasAttr<DLLImportAttr>())
1648 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1649 else if (RD->hasAttr<DLLExportAttr>())
1650 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1652 if (!GV->hasExternalLinkage())
1653 emitVBTableDefinition(VBT, RD, GV);
1658 void MicrosoftCXXABI::emitVBTableDefinition(const VPtrInfo &VBT,
1659 const CXXRecordDecl *RD,
1660 llvm::GlobalVariable *GV) const {
1661 const CXXRecordDecl *ReusingBase = VBT.ReusingBase;
1663 assert(RD->getNumVBases() && ReusingBase->getNumVBases() &&
1664 "should only emit vbtables for classes with vbtables");
1666 const ASTRecordLayout &BaseLayout =
1667 CGM.getContext().getASTRecordLayout(VBT.BaseWithVPtr);
1668 const ASTRecordLayout &DerivedLayout =
1669 CGM.getContext().getASTRecordLayout(RD);
1671 SmallVector<llvm::Constant *, 4> Offsets(1 + ReusingBase->getNumVBases(),
1674 // The offset from ReusingBase's vbptr to itself always leads.
1675 CharUnits VBPtrOffset = BaseLayout.getVBPtrOffset();
1676 Offsets[0] = llvm::ConstantInt::get(CGM.IntTy, -VBPtrOffset.getQuantity());
1678 MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext();
1679 for (const auto &I : ReusingBase->vbases()) {
1680 const CXXRecordDecl *VBase = I.getType()->getAsCXXRecordDecl();
1681 CharUnits Offset = DerivedLayout.getVBaseClassOffset(VBase);
1682 assert(!Offset.isNegative());
1684 // Make it relative to the subobject vbptr.
1685 CharUnits CompleteVBPtrOffset = VBT.NonVirtualOffset + VBPtrOffset;
1686 if (VBT.getVBaseWithVPtr())
1687 CompleteVBPtrOffset +=
1688 DerivedLayout.getVBaseClassOffset(VBT.getVBaseWithVPtr());
1689 Offset -= CompleteVBPtrOffset;
1691 unsigned VBIndex = Context.getVBTableIndex(ReusingBase, VBase);
1692 assert(Offsets[VBIndex] == nullptr && "The same vbindex seen twice?");
1693 Offsets[VBIndex] = llvm::ConstantInt::get(CGM.IntTy, Offset.getQuantity());
1696 assert(Offsets.size() ==
1697 cast<llvm::ArrayType>(cast<llvm::PointerType>(GV->getType())
1698 ->getElementType())->getNumElements());
1699 llvm::ArrayType *VBTableType =
1700 llvm::ArrayType::get(CGM.IntTy, Offsets.size());
1701 llvm::Constant *Init = llvm::ConstantArray::get(VBTableType, Offsets);
1702 GV->setInitializer(Init);
1704 // Set the right visibility.
1705 CGM.setGlobalVisibility(GV, RD);
1708 llvm::Value *MicrosoftCXXABI::performThisAdjustment(CodeGenFunction &CGF,
1710 const ThisAdjustment &TA) {
1714 llvm::Value *V = CGF.Builder.CreateBitCast(This, CGF.Int8PtrTy);
1716 if (!TA.Virtual.isEmpty()) {
1717 assert(TA.Virtual.Microsoft.VtordispOffset < 0);
1718 // Adjust the this argument based on the vtordisp value.
1719 llvm::Value *VtorDispPtr =
1720 CGF.Builder.CreateConstGEP1_32(V, TA.Virtual.Microsoft.VtordispOffset);
1722 CGF.Builder.CreateBitCast(VtorDispPtr, CGF.Int32Ty->getPointerTo());
1723 llvm::Value *VtorDisp = CGF.Builder.CreateLoad(VtorDispPtr, "vtordisp");
1724 V = CGF.Builder.CreateGEP(V, CGF.Builder.CreateNeg(VtorDisp));
1726 if (TA.Virtual.Microsoft.VBPtrOffset) {
1727 // If the final overrider is defined in a virtual base other than the one
1728 // that holds the vfptr, we have to use a vtordispex thunk which looks up
1729 // the vbtable of the derived class.
1730 assert(TA.Virtual.Microsoft.VBPtrOffset > 0);
1731 assert(TA.Virtual.Microsoft.VBOffsetOffset >= 0);
1733 llvm::Value *VBaseOffset =
1734 GetVBaseOffsetFromVBPtr(CGF, V, -TA.Virtual.Microsoft.VBPtrOffset,
1735 TA.Virtual.Microsoft.VBOffsetOffset, &VBPtr);
1736 V = CGF.Builder.CreateInBoundsGEP(VBPtr, VBaseOffset);
1740 if (TA.NonVirtual) {
1741 // Non-virtual adjustment might result in a pointer outside the allocated
1742 // object, e.g. if the final overrider class is laid out after the virtual
1743 // base that declares a method in the most derived class.
1744 V = CGF.Builder.CreateConstGEP1_32(V, TA.NonVirtual);
1747 // Don't need to bitcast back, the call CodeGen will handle this.
1752 MicrosoftCXXABI::performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
1753 const ReturnAdjustment &RA) {
1757 llvm::Value *V = CGF.Builder.CreateBitCast(Ret, CGF.Int8PtrTy);
1759 if (RA.Virtual.Microsoft.VBIndex) {
1760 assert(RA.Virtual.Microsoft.VBIndex > 0);
1762 getContext().getTypeSizeInChars(getContext().IntTy).getQuantity();
1764 llvm::Value *VBaseOffset =
1765 GetVBaseOffsetFromVBPtr(CGF, V, RA.Virtual.Microsoft.VBPtrOffset,
1766 IntSize * RA.Virtual.Microsoft.VBIndex, &VBPtr);
1767 V = CGF.Builder.CreateInBoundsGEP(VBPtr, VBaseOffset);
1771 V = CGF.Builder.CreateConstInBoundsGEP1_32(V, RA.NonVirtual);
1773 // Cast back to the original type.
1774 return CGF.Builder.CreateBitCast(V, Ret->getType());
1777 bool MicrosoftCXXABI::requiresArrayCookie(const CXXDeleteExpr *expr,
1778 QualType elementType) {
1779 // Microsoft seems to completely ignore the possibility of a
1780 // two-argument usual deallocation function.
1781 return elementType.isDestructedType();
1784 bool MicrosoftCXXABI::requiresArrayCookie(const CXXNewExpr *expr) {
1785 // Microsoft seems to completely ignore the possibility of a
1786 // two-argument usual deallocation function.
1787 return expr->getAllocatedType().isDestructedType();
1790 CharUnits MicrosoftCXXABI::getArrayCookieSizeImpl(QualType type) {
1791 // The array cookie is always a size_t; we then pad that out to the
1792 // alignment of the element type.
1793 ASTContext &Ctx = getContext();
1794 return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()),
1795 Ctx.getTypeAlignInChars(type));
1798 llvm::Value *MicrosoftCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1799 llvm::Value *allocPtr,
1800 CharUnits cookieSize) {
1801 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
1802 llvm::Value *numElementsPtr =
1803 CGF.Builder.CreateBitCast(allocPtr, CGF.SizeTy->getPointerTo(AS));
1804 return CGF.Builder.CreateLoad(numElementsPtr);
1807 llvm::Value* MicrosoftCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1808 llvm::Value *newPtr,
1809 llvm::Value *numElements,
1810 const CXXNewExpr *expr,
1811 QualType elementType) {
1812 assert(requiresArrayCookie(expr));
1814 // The size of the cookie.
1815 CharUnits cookieSize = getArrayCookieSizeImpl(elementType);
1817 // Compute an offset to the cookie.
1818 llvm::Value *cookiePtr = newPtr;
1820 // Write the number of elements into the appropriate slot.
1821 unsigned AS = newPtr->getType()->getPointerAddressSpace();
1822 llvm::Value *numElementsPtr
1823 = CGF.Builder.CreateBitCast(cookiePtr, CGF.SizeTy->getPointerTo(AS));
1824 CGF.Builder.CreateStore(numElements, numElementsPtr);
1826 // Finally, compute a pointer to the actual data buffer by skipping
1827 // over the cookie completely.
1828 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
1829 cookieSize.getQuantity());
1832 static void emitGlobalDtorWithTLRegDtor(CodeGenFunction &CGF, const VarDecl &VD,
1833 llvm::Constant *Dtor,
1834 llvm::Constant *Addr) {
1835 // Create a function which calls the destructor.
1836 llvm::Constant *DtorStub = CGF.createAtExitStub(VD, Dtor, Addr);
1838 // extern "C" int __tlregdtor(void (*f)(void));
1839 llvm::FunctionType *TLRegDtorTy = llvm::FunctionType::get(
1840 CGF.IntTy, DtorStub->getType(), /*IsVarArg=*/false);
1842 llvm::Constant *TLRegDtor =
1843 CGF.CGM.CreateRuntimeFunction(TLRegDtorTy, "__tlregdtor");
1844 if (llvm::Function *TLRegDtorFn = dyn_cast<llvm::Function>(TLRegDtor))
1845 TLRegDtorFn->setDoesNotThrow();
1847 CGF.EmitNounwindRuntimeCall(TLRegDtor, DtorStub);
1850 void MicrosoftCXXABI::registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
1851 llvm::Constant *Dtor,
1852 llvm::Constant *Addr) {
1854 return emitGlobalDtorWithTLRegDtor(CGF, D, Dtor, Addr);
1856 // The default behavior is to use atexit.
1857 CGF.registerGlobalDtorWithAtExit(D, Dtor, Addr);
1860 void MicrosoftCXXABI::EmitThreadLocalInitFuncs(
1862 ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *>>
1864 ArrayRef<llvm::Function *> CXXThreadLocalInits,
1865 ArrayRef<llvm::GlobalVariable *> CXXThreadLocalInitVars) {
1866 // This will create a GV in the .CRT$XDU section. It will point to our
1867 // initialization function. The CRT will call all of these function
1868 // pointers at start-up time and, eventually, at thread-creation time.
1869 auto AddToXDU = [&CGM](llvm::Function *InitFunc) {
1870 llvm::GlobalVariable *InitFuncPtr = new llvm::GlobalVariable(
1871 CGM.getModule(), InitFunc->getType(), /*IsConstant=*/true,
1872 llvm::GlobalVariable::InternalLinkage, InitFunc,
1873 Twine(InitFunc->getName(), "$initializer$"));
1874 InitFuncPtr->setSection(".CRT$XDU");
1875 // This variable has discardable linkage, we have to add it to @llvm.used to
1876 // ensure it won't get discarded.
1877 CGM.addUsedGlobal(InitFuncPtr);
1881 std::vector<llvm::Function *> NonComdatInits;
1882 for (size_t I = 0, E = CXXThreadLocalInitVars.size(); I != E; ++I) {
1883 llvm::GlobalVariable *GV = CXXThreadLocalInitVars[I];
1884 llvm::Function *F = CXXThreadLocalInits[I];
1886 // If the GV is already in a comdat group, then we have to join it.
1887 if (llvm::Comdat *C = GV->getComdat())
1888 AddToXDU(F)->setComdat(C);
1890 NonComdatInits.push_back(F);
1893 if (!NonComdatInits.empty()) {
1894 llvm::FunctionType *FTy =
1895 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
1896 llvm::Function *InitFunc = CGM.CreateGlobalInitOrDestructFunction(
1897 FTy, "__tls_init", SourceLocation(),
1899 CodeGenFunction(CGM).GenerateCXXGlobalInitFunc(InitFunc, NonComdatInits);
1905 LValue MicrosoftCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
1907 QualType LValType) {
1908 CGF.CGM.ErrorUnsupported(VD, "thread wrappers");
1912 void MicrosoftCXXABI::EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
1913 llvm::GlobalVariable *GV,
1915 // MSVC only uses guards for static locals.
1916 if (!D.isStaticLocal()) {
1917 assert(GV->hasWeakLinkage() || GV->hasLinkOnceLinkage());
1918 // GlobalOpt is allowed to discard the initializer, so use linkonce_odr.
1919 llvm::Function *F = CGF.CurFn;
1920 F->setLinkage(llvm::GlobalValue::LinkOnceODRLinkage);
1921 F->setComdat(CGM.getModule().getOrInsertComdat(F->getName()));
1922 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
1926 // MSVC always uses an i32 bitfield to guard initialization, which is *not*
1927 // threadsafe. Since the user may be linking in inline functions compiled by
1928 // cl.exe, there's no reason to provide a false sense of security by using
1929 // critical sections here.
1932 CGM.ErrorUnsupported(&D, "dynamic TLS initialization");
1934 CGBuilderTy &Builder = CGF.Builder;
1935 llvm::IntegerType *GuardTy = CGF.Int32Ty;
1936 llvm::ConstantInt *Zero = llvm::ConstantInt::get(GuardTy, 0);
1938 // Get the guard variable for this function if we have one already.
1939 GuardInfo *GI = &GuardVariableMap[D.getDeclContext()];
1942 if (D.isStaticLocal() && D.isExternallyVisible()) {
1943 // Externally visible variables have to be numbered in Sema to properly
1944 // handle unreachable VarDecls.
1945 BitIndex = getContext().getStaticLocalNumber(&D);
1946 assert(BitIndex > 0);
1949 // Non-externally visible variables are numbered here in CodeGen.
1950 BitIndex = GI->BitIndex++;
1953 if (BitIndex >= 32) {
1954 if (D.isExternallyVisible())
1955 ErrorUnsupportedABI(CGF, "more than 32 guarded initializations");
1957 GI->Guard = nullptr;
1960 // Lazily create the i32 bitfield for this function.
1962 // Mangle the name for the guard.
1963 SmallString<256> GuardName;
1965 llvm::raw_svector_ostream Out(GuardName);
1966 getMangleContext().mangleStaticGuardVariable(&D, Out);
1970 // Create the guard variable with a zero-initializer. Just absorb linkage,
1971 // visibility and dll storage class from the guarded variable.
1973 new llvm::GlobalVariable(CGM.getModule(), GuardTy, false,
1974 GV->getLinkage(), Zero, GuardName.str());
1975 GI->Guard->setVisibility(GV->getVisibility());
1976 GI->Guard->setDLLStorageClass(GV->getDLLStorageClass());
1977 if (GI->Guard->isWeakForLinker())
1978 GI->Guard->setComdat(
1979 CGM.getModule().getOrInsertComdat(GI->Guard->getName()));
1981 assert(GI->Guard->getLinkage() == GV->getLinkage() &&
1982 "static local from the same function had different linkage");
1985 // Pseudo code for the test:
1986 // if (!(GuardVar & MyGuardBit)) {
1987 // GuardVar |= MyGuardBit;
1988 // ... initialize the object ...;
1991 // Test our bit from the guard variable.
1992 llvm::ConstantInt *Bit = llvm::ConstantInt::get(GuardTy, 1U << BitIndex);
1993 llvm::LoadInst *LI = Builder.CreateLoad(GI->Guard);
1994 llvm::Value *IsInitialized =
1995 Builder.CreateICmpNE(Builder.CreateAnd(LI, Bit), Zero);
1996 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1997 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1998 Builder.CreateCondBr(IsInitialized, EndBlock, InitBlock);
2000 // Set our bit in the guard variable and emit the initializer and add a global
2001 // destructor if appropriate.
2002 CGF.EmitBlock(InitBlock);
2003 Builder.CreateStore(Builder.CreateOr(LI, Bit), GI->Guard);
2004 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
2005 Builder.CreateBr(EndBlock);
2008 CGF.EmitBlock(EndBlock);
2011 bool MicrosoftCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
2012 // Null-ness for function memptrs only depends on the first field, which is
2013 // the function pointer. The rest don't matter, so we can zero initialize.
2014 if (MPT->isMemberFunctionPointer())
2017 // The virtual base adjustment field is always -1 for null, so if we have one
2018 // we can't zero initialize. The field offset is sometimes also -1 if 0 is a
2019 // valid field offset.
2020 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2021 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
2022 return (!MSInheritanceAttr::hasVBTableOffsetField(Inheritance) &&
2023 RD->nullFieldOffsetIsZero());
2027 MicrosoftCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
2028 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2029 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
2030 llvm::SmallVector<llvm::Type *, 4> fields;
2031 if (MPT->isMemberFunctionPointer())
2032 fields.push_back(CGM.VoidPtrTy); // FunctionPointerOrVirtualThunk
2034 fields.push_back(CGM.IntTy); // FieldOffset
2036 if (MSInheritanceAttr::hasNVOffsetField(MPT->isMemberFunctionPointer(),
2038 fields.push_back(CGM.IntTy);
2039 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance))
2040 fields.push_back(CGM.IntTy);
2041 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance))
2042 fields.push_back(CGM.IntTy); // VirtualBaseAdjustmentOffset
2044 if (fields.size() == 1)
2046 return llvm::StructType::get(CGM.getLLVMContext(), fields);
2049 void MicrosoftCXXABI::
2050 GetNullMemberPointerFields(const MemberPointerType *MPT,
2051 llvm::SmallVectorImpl<llvm::Constant *> &fields) {
2052 assert(fields.empty());
2053 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2054 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
2055 if (MPT->isMemberFunctionPointer()) {
2056 // FunctionPointerOrVirtualThunk
2057 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
2059 if (RD->nullFieldOffsetIsZero())
2060 fields.push_back(getZeroInt()); // FieldOffset
2062 fields.push_back(getAllOnesInt()); // FieldOffset
2065 if (MSInheritanceAttr::hasNVOffsetField(MPT->isMemberFunctionPointer(),
2067 fields.push_back(getZeroInt());
2068 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance))
2069 fields.push_back(getZeroInt());
2070 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance))
2071 fields.push_back(getAllOnesInt());
2075 MicrosoftCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
2076 llvm::SmallVector<llvm::Constant *, 4> fields;
2077 GetNullMemberPointerFields(MPT, fields);
2078 if (fields.size() == 1)
2080 llvm::Constant *Res = llvm::ConstantStruct::getAnon(fields);
2081 assert(Res->getType() == ConvertMemberPointerType(MPT));
2086 MicrosoftCXXABI::EmitFullMemberPointer(llvm::Constant *FirstField,
2087 bool IsMemberFunction,
2088 const CXXRecordDecl *RD,
2089 CharUnits NonVirtualBaseAdjustment)
2091 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
2093 // Single inheritance class member pointer are represented as scalars instead
2095 if (MSInheritanceAttr::hasOnlyOneField(IsMemberFunction, Inheritance))
2098 llvm::SmallVector<llvm::Constant *, 4> fields;
2099 fields.push_back(FirstField);
2101 if (MSInheritanceAttr::hasNVOffsetField(IsMemberFunction, Inheritance))
2102 fields.push_back(llvm::ConstantInt::get(
2103 CGM.IntTy, NonVirtualBaseAdjustment.getQuantity()));
2105 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance)) {
2106 CharUnits Offs = CharUnits::Zero();
2107 if (RD->getNumVBases())
2108 Offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
2109 fields.push_back(llvm::ConstantInt::get(CGM.IntTy, Offs.getQuantity()));
2112 // The rest of the fields are adjusted by conversions to a more derived class.
2113 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance))
2114 fields.push_back(getZeroInt());
2116 return llvm::ConstantStruct::getAnon(fields);
2120 MicrosoftCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
2122 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2123 llvm::Constant *FirstField =
2124 llvm::ConstantInt::get(CGM.IntTy, offset.getQuantity());
2125 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/false, RD,
2129 llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
2130 return BuildMemberPointer(MD->getParent(), MD, CharUnits::Zero());
2133 llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const APValue &MP,
2135 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
2136 const ValueDecl *MPD = MP.getMemberPointerDecl();
2138 return EmitNullMemberPointer(MPT);
2140 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
2142 // FIXME PR15713: Support virtual inheritance paths.
2144 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
2145 return BuildMemberPointer(MPT->getMostRecentCXXRecordDecl(), MD,
2148 CharUnits FieldOffset =
2149 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
2150 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
2154 MicrosoftCXXABI::BuildMemberPointer(const CXXRecordDecl *RD,
2155 const CXXMethodDecl *MD,
2156 CharUnits NonVirtualBaseAdjustment) {
2157 assert(MD->isInstance() && "Member function must not be static!");
2158 MD = MD->getCanonicalDecl();
2159 RD = RD->getMostRecentDecl();
2160 CodeGenTypes &Types = CGM.getTypes();
2162 llvm::Constant *FirstField;
2163 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
2164 if (!MD->isVirtual()) {
2166 // Check whether the function has a computable LLVM signature.
2167 if (Types.isFuncTypeConvertible(FPT)) {
2168 // The function has a computable LLVM signature; use the correct type.
2169 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
2171 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
2172 // function type is incomplete.
2175 FirstField = CGM.GetAddrOfFunction(MD, Ty);
2176 FirstField = llvm::ConstantExpr::getBitCast(FirstField, CGM.VoidPtrTy);
2178 MicrosoftVTableContext::MethodVFTableLocation ML =
2179 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(MD);
2180 if (!CGM.getTypes().isFuncTypeConvertible(
2181 MD->getType()->castAs<FunctionType>())) {
2182 CGM.ErrorUnsupported(MD, "pointer to virtual member function with "
2183 "incomplete return or parameter type");
2184 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
2185 } else if (FPT->getCallConv() == CC_X86FastCall) {
2186 CGM.ErrorUnsupported(MD, "pointer to fastcall virtual member function");
2187 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
2188 } else if (ML.VBase) {
2189 CGM.ErrorUnsupported(MD, "pointer to virtual member function overriding "
2190 "member function in virtual base class");
2191 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
2193 llvm::Function *Thunk = EmitVirtualMemPtrThunk(MD, ML);
2194 FirstField = llvm::ConstantExpr::getBitCast(Thunk, CGM.VoidPtrTy);
2195 // Include the vfptr adjustment if the method is in a non-primary vftable.
2196 NonVirtualBaseAdjustment += ML.VFPtrOffset;
2200 // The rest of the fields are common with data member pointers.
2201 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/true, RD,
2202 NonVirtualBaseAdjustment);
2205 /// Member pointers are the same if they're either bitwise identical *or* both
2206 /// null. Null-ness for function members is determined by the first field,
2207 /// while for data member pointers we must compare all fields.
2209 MicrosoftCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
2212 const MemberPointerType *MPT,
2214 CGBuilderTy &Builder = CGF.Builder;
2216 // Handle != comparisons by switching the sense of all boolean operations.
2217 llvm::ICmpInst::Predicate Eq;
2218 llvm::Instruction::BinaryOps And, Or;
2220 Eq = llvm::ICmpInst::ICMP_NE;
2221 And = llvm::Instruction::Or;
2222 Or = llvm::Instruction::And;
2224 Eq = llvm::ICmpInst::ICMP_EQ;
2225 And = llvm::Instruction::And;
2226 Or = llvm::Instruction::Or;
2229 // If this is a single field member pointer (single inheritance), this is a
2231 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2232 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
2233 if (MSInheritanceAttr::hasOnlyOneField(MPT->isMemberFunctionPointer(),
2235 return Builder.CreateICmp(Eq, L, R);
2237 // Compare the first field.
2238 llvm::Value *L0 = Builder.CreateExtractValue(L, 0, "lhs.0");
2239 llvm::Value *R0 = Builder.CreateExtractValue(R, 0, "rhs.0");
2240 llvm::Value *Cmp0 = Builder.CreateICmp(Eq, L0, R0, "memptr.cmp.first");
2242 // Compare everything other than the first field.
2243 llvm::Value *Res = nullptr;
2244 llvm::StructType *LType = cast<llvm::StructType>(L->getType());
2245 for (unsigned I = 1, E = LType->getNumElements(); I != E; ++I) {
2246 llvm::Value *LF = Builder.CreateExtractValue(L, I);
2247 llvm::Value *RF = Builder.CreateExtractValue(R, I);
2248 llvm::Value *Cmp = Builder.CreateICmp(Eq, LF, RF, "memptr.cmp.rest");
2250 Res = Builder.CreateBinOp(And, Res, Cmp);
2255 // Check if the first field is 0 if this is a function pointer.
2256 if (MPT->isMemberFunctionPointer()) {
2257 // (l1 == r1 && ...) || l0 == 0
2258 llvm::Value *Zero = llvm::Constant::getNullValue(L0->getType());
2259 llvm::Value *IsZero = Builder.CreateICmp(Eq, L0, Zero, "memptr.cmp.iszero");
2260 Res = Builder.CreateBinOp(Or, Res, IsZero);
2263 // Combine the comparison of the first field, which must always be true for
2264 // this comparison to succeeed.
2265 return Builder.CreateBinOp(And, Res, Cmp0, "memptr.cmp");
2269 MicrosoftCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
2270 llvm::Value *MemPtr,
2271 const MemberPointerType *MPT) {
2272 CGBuilderTy &Builder = CGF.Builder;
2273 llvm::SmallVector<llvm::Constant *, 4> fields;
2274 // We only need one field for member functions.
2275 if (MPT->isMemberFunctionPointer())
2276 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
2278 GetNullMemberPointerFields(MPT, fields);
2279 assert(!fields.empty());
2280 llvm::Value *FirstField = MemPtr;
2281 if (MemPtr->getType()->isStructTy())
2282 FirstField = Builder.CreateExtractValue(MemPtr, 0);
2283 llvm::Value *Res = Builder.CreateICmpNE(FirstField, fields[0], "memptr.cmp0");
2285 // For function member pointers, we only need to test the function pointer
2286 // field. The other fields if any can be garbage.
2287 if (MPT->isMemberFunctionPointer())
2290 // Otherwise, emit a series of compares and combine the results.
2291 for (int I = 1, E = fields.size(); I < E; ++I) {
2292 llvm::Value *Field = Builder.CreateExtractValue(MemPtr, I);
2293 llvm::Value *Next = Builder.CreateICmpNE(Field, fields[I], "memptr.cmp");
2294 Res = Builder.CreateOr(Res, Next, "memptr.tobool");
2299 bool MicrosoftCXXABI::MemberPointerConstantIsNull(const MemberPointerType *MPT,
2300 llvm::Constant *Val) {
2301 // Function pointers are null if the pointer in the first field is null.
2302 if (MPT->isMemberFunctionPointer()) {
2303 llvm::Constant *FirstField = Val->getType()->isStructTy() ?
2304 Val->getAggregateElement(0U) : Val;
2305 return FirstField->isNullValue();
2308 // If it's not a function pointer and it's zero initializable, we can easily
2310 if (isZeroInitializable(MPT) && Val->isNullValue())
2313 // Otherwise, break down all the fields for comparison. Hopefully these
2314 // little Constants are reused, while a big null struct might not be.
2315 llvm::SmallVector<llvm::Constant *, 4> Fields;
2316 GetNullMemberPointerFields(MPT, Fields);
2317 if (Fields.size() == 1) {
2318 assert(Val->getType()->isIntegerTy());
2319 return Val == Fields[0];
2323 for (I = 0, E = Fields.size(); I != E; ++I) {
2324 if (Val->getAggregateElement(I) != Fields[I])
2331 MicrosoftCXXABI::GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
2333 llvm::Value *VBPtrOffset,
2334 llvm::Value *VBTableOffset,
2335 llvm::Value **VBPtrOut) {
2336 CGBuilderTy &Builder = CGF.Builder;
2337 // Load the vbtable pointer from the vbptr in the instance.
2338 This = Builder.CreateBitCast(This, CGM.Int8PtrTy);
2339 llvm::Value *VBPtr =
2340 Builder.CreateInBoundsGEP(This, VBPtrOffset, "vbptr");
2341 if (VBPtrOut) *VBPtrOut = VBPtr;
2342 VBPtr = Builder.CreateBitCast(VBPtr,
2343 CGM.Int32Ty->getPointerTo(0)->getPointerTo(0));
2344 llvm::Value *VBTable = Builder.CreateLoad(VBPtr, "vbtable");
2346 // Translate from byte offset to table index. It improves analyzability.
2347 llvm::Value *VBTableIndex = Builder.CreateAShr(
2348 VBTableOffset, llvm::ConstantInt::get(VBTableOffset->getType(), 2),
2349 "vbtindex", /*isExact=*/true);
2351 // Load an i32 offset from the vb-table.
2352 llvm::Value *VBaseOffs = Builder.CreateInBoundsGEP(VBTable, VBTableIndex);
2353 VBaseOffs = Builder.CreateBitCast(VBaseOffs, CGM.Int32Ty->getPointerTo(0));
2354 return Builder.CreateLoad(VBaseOffs, "vbase_offs");
2357 // Returns an adjusted base cast to i8*, since we do more address arithmetic on
2359 llvm::Value *MicrosoftCXXABI::AdjustVirtualBase(
2360 CodeGenFunction &CGF, const Expr *E, const CXXRecordDecl *RD,
2361 llvm::Value *Base, llvm::Value *VBTableOffset, llvm::Value *VBPtrOffset) {
2362 CGBuilderTy &Builder = CGF.Builder;
2363 Base = Builder.CreateBitCast(Base, CGM.Int8PtrTy);
2364 llvm::BasicBlock *OriginalBB = nullptr;
2365 llvm::BasicBlock *SkipAdjustBB = nullptr;
2366 llvm::BasicBlock *VBaseAdjustBB = nullptr;
2368 // In the unspecified inheritance model, there might not be a vbtable at all,
2369 // in which case we need to skip the virtual base lookup. If there is a
2370 // vbtable, the first entry is a no-op entry that gives back the original
2371 // base, so look for a virtual base adjustment offset of zero.
2373 OriginalBB = Builder.GetInsertBlock();
2374 VBaseAdjustBB = CGF.createBasicBlock("memptr.vadjust");
2375 SkipAdjustBB = CGF.createBasicBlock("memptr.skip_vadjust");
2376 llvm::Value *IsVirtual =
2377 Builder.CreateICmpNE(VBTableOffset, getZeroInt(),
2379 Builder.CreateCondBr(IsVirtual, VBaseAdjustBB, SkipAdjustBB);
2380 CGF.EmitBlock(VBaseAdjustBB);
2383 // If we weren't given a dynamic vbptr offset, RD should be complete and we'll
2384 // know the vbptr offset.
2386 CharUnits offs = CharUnits::Zero();
2387 if (!RD->hasDefinition()) {
2388 DiagnosticsEngine &Diags = CGF.CGM.getDiags();
2389 unsigned DiagID = Diags.getCustomDiagID(
2390 DiagnosticsEngine::Error,
2391 "member pointer representation requires a "
2392 "complete class type for %0 to perform this expression");
2393 Diags.Report(E->getExprLoc(), DiagID) << RD << E->getSourceRange();
2394 } else if (RD->getNumVBases())
2395 offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
2396 VBPtrOffset = llvm::ConstantInt::get(CGM.IntTy, offs.getQuantity());
2398 llvm::Value *VBPtr = nullptr;
2399 llvm::Value *VBaseOffs =
2400 GetVBaseOffsetFromVBPtr(CGF, Base, VBPtrOffset, VBTableOffset, &VBPtr);
2401 llvm::Value *AdjustedBase = Builder.CreateInBoundsGEP(VBPtr, VBaseOffs);
2403 // Merge control flow with the case where we didn't have to adjust.
2404 if (VBaseAdjustBB) {
2405 Builder.CreateBr(SkipAdjustBB);
2406 CGF.EmitBlock(SkipAdjustBB);
2407 llvm::PHINode *Phi = Builder.CreatePHI(CGM.Int8PtrTy, 2, "memptr.base");
2408 Phi->addIncoming(Base, OriginalBB);
2409 Phi->addIncoming(AdjustedBase, VBaseAdjustBB);
2412 return AdjustedBase;
2415 llvm::Value *MicrosoftCXXABI::EmitMemberDataPointerAddress(
2416 CodeGenFunction &CGF, const Expr *E, llvm::Value *Base, llvm::Value *MemPtr,
2417 const MemberPointerType *MPT) {
2418 assert(MPT->isMemberDataPointer());
2419 unsigned AS = Base->getType()->getPointerAddressSpace();
2421 CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
2422 CGBuilderTy &Builder = CGF.Builder;
2423 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2424 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
2426 // Extract the fields we need, regardless of model. We'll apply them if we
2428 llvm::Value *FieldOffset = MemPtr;
2429 llvm::Value *VirtualBaseAdjustmentOffset = nullptr;
2430 llvm::Value *VBPtrOffset = nullptr;
2431 if (MemPtr->getType()->isStructTy()) {
2432 // We need to extract values.
2434 FieldOffset = Builder.CreateExtractValue(MemPtr, I++);
2435 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance))
2436 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
2437 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance))
2438 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
2441 if (VirtualBaseAdjustmentOffset) {
2442 Base = AdjustVirtualBase(CGF, E, RD, Base, VirtualBaseAdjustmentOffset,
2447 Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
2449 // Apply the offset, which we assume is non-null.
2451 Builder.CreateInBoundsGEP(Base, FieldOffset, "memptr.offset");
2453 // Cast the address to the appropriate pointer type, adopting the address
2454 // space of the base pointer.
2455 return Builder.CreateBitCast(Addr, PType);
2458 static MSInheritanceAttr::Spelling
2459 getInheritanceFromMemptr(const MemberPointerType *MPT) {
2460 return MPT->getMostRecentCXXRecordDecl()->getMSInheritanceModel();
2464 MicrosoftCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
2467 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
2468 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
2469 E->getCastKind() == CK_ReinterpretMemberPointer);
2471 // Use constant emission if we can.
2472 if (isa<llvm::Constant>(Src))
2473 return EmitMemberPointerConversion(E, cast<llvm::Constant>(Src));
2475 // We may be adding or dropping fields from the member pointer, so we need
2476 // both types and the inheritance models of both records.
2477 const MemberPointerType *SrcTy =
2478 E->getSubExpr()->getType()->castAs<MemberPointerType>();
2479 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
2480 bool IsFunc = SrcTy->isMemberFunctionPointer();
2482 // If the classes use the same null representation, reinterpret_cast is a nop.
2483 bool IsReinterpret = E->getCastKind() == CK_ReinterpretMemberPointer;
2484 if (IsReinterpret && IsFunc)
2487 CXXRecordDecl *SrcRD = SrcTy->getMostRecentCXXRecordDecl();
2488 CXXRecordDecl *DstRD = DstTy->getMostRecentCXXRecordDecl();
2489 if (IsReinterpret &&
2490 SrcRD->nullFieldOffsetIsZero() == DstRD->nullFieldOffsetIsZero())
2493 CGBuilderTy &Builder = CGF.Builder;
2495 // Branch past the conversion if Src is null.
2496 llvm::Value *IsNotNull = EmitMemberPointerIsNotNull(CGF, Src, SrcTy);
2497 llvm::Constant *DstNull = EmitNullMemberPointer(DstTy);
2499 // C++ 5.2.10p9: The null member pointer value is converted to the null member
2500 // pointer value of the destination type.
2501 if (IsReinterpret) {
2502 // For reinterpret casts, sema ensures that src and dst are both functions
2503 // or data and have the same size, which means the LLVM types should match.
2504 assert(Src->getType() == DstNull->getType());
2505 return Builder.CreateSelect(IsNotNull, Src, DstNull);
2508 llvm::BasicBlock *OriginalBB = Builder.GetInsertBlock();
2509 llvm::BasicBlock *ConvertBB = CGF.createBasicBlock("memptr.convert");
2510 llvm::BasicBlock *ContinueBB = CGF.createBasicBlock("memptr.converted");
2511 Builder.CreateCondBr(IsNotNull, ConvertBB, ContinueBB);
2512 CGF.EmitBlock(ConvertBB);
2515 llvm::Value *FirstField = Src;
2516 llvm::Value *NonVirtualBaseAdjustment = nullptr;
2517 llvm::Value *VirtualBaseAdjustmentOffset = nullptr;
2518 llvm::Value *VBPtrOffset = nullptr;
2519 MSInheritanceAttr::Spelling SrcInheritance = SrcRD->getMSInheritanceModel();
2520 if (!MSInheritanceAttr::hasOnlyOneField(IsFunc, SrcInheritance)) {
2521 // We need to extract values.
2523 FirstField = Builder.CreateExtractValue(Src, I++);
2524 if (MSInheritanceAttr::hasNVOffsetField(IsFunc, SrcInheritance))
2525 NonVirtualBaseAdjustment = Builder.CreateExtractValue(Src, I++);
2526 if (MSInheritanceAttr::hasVBPtrOffsetField(SrcInheritance))
2527 VBPtrOffset = Builder.CreateExtractValue(Src, I++);
2528 if (MSInheritanceAttr::hasVBTableOffsetField(SrcInheritance))
2529 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(Src, I++);
2532 // For data pointers, we adjust the field offset directly. For functions, we
2533 // have a separate field.
2534 llvm::Constant *Adj = getMemberPointerAdjustment(E);
2536 Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy);
2537 llvm::Value *&NVAdjustField = IsFunc ? NonVirtualBaseAdjustment : FirstField;
2538 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
2539 if (!NVAdjustField) // If this field didn't exist in src, it's zero.
2540 NVAdjustField = getZeroInt();
2541 if (isDerivedToBase)
2542 NVAdjustField = Builder.CreateNSWSub(NVAdjustField, Adj, "adj");
2544 NVAdjustField = Builder.CreateNSWAdd(NVAdjustField, Adj, "adj");
2547 // FIXME PR15713: Support conversions through virtually derived classes.
2549 // Recompose dst from the null struct and the adjusted fields from src.
2550 MSInheritanceAttr::Spelling DstInheritance = DstRD->getMSInheritanceModel();
2552 if (MSInheritanceAttr::hasOnlyOneField(IsFunc, DstInheritance)) {
2555 Dst = llvm::UndefValue::get(DstNull->getType());
2557 Dst = Builder.CreateInsertValue(Dst, FirstField, Idx++);
2558 if (MSInheritanceAttr::hasNVOffsetField(IsFunc, DstInheritance))
2559 Dst = Builder.CreateInsertValue(
2560 Dst, getValueOrZeroInt(NonVirtualBaseAdjustment), Idx++);
2561 if (MSInheritanceAttr::hasVBPtrOffsetField(DstInheritance))
2562 Dst = Builder.CreateInsertValue(
2563 Dst, getValueOrZeroInt(VBPtrOffset), Idx++);
2564 if (MSInheritanceAttr::hasVBTableOffsetField(DstInheritance))
2565 Dst = Builder.CreateInsertValue(
2566 Dst, getValueOrZeroInt(VirtualBaseAdjustmentOffset), Idx++);
2568 Builder.CreateBr(ContinueBB);
2570 // In the continuation, choose between DstNull and Dst.
2571 CGF.EmitBlock(ContinueBB);
2572 llvm::PHINode *Phi = Builder.CreatePHI(DstNull->getType(), 2, "memptr.converted");
2573 Phi->addIncoming(DstNull, OriginalBB);
2574 Phi->addIncoming(Dst, ConvertBB);
2579 MicrosoftCXXABI::EmitMemberPointerConversion(const CastExpr *E,
2580 llvm::Constant *Src) {
2581 const MemberPointerType *SrcTy =
2582 E->getSubExpr()->getType()->castAs<MemberPointerType>();
2583 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
2585 // If src is null, emit a new null for dst. We can't return src because dst
2586 // might have a new representation.
2587 if (MemberPointerConstantIsNull(SrcTy, Src))
2588 return EmitNullMemberPointer(DstTy);
2590 // We don't need to do anything for reinterpret_casts of non-null member
2591 // pointers. We should only get here when the two type representations have
2593 if (E->getCastKind() == CK_ReinterpretMemberPointer)
2596 MSInheritanceAttr::Spelling SrcInheritance = getInheritanceFromMemptr(SrcTy);
2597 MSInheritanceAttr::Spelling DstInheritance = getInheritanceFromMemptr(DstTy);
2600 llvm::Constant *FirstField = Src;
2601 llvm::Constant *NonVirtualBaseAdjustment = nullptr;
2602 llvm::Constant *VirtualBaseAdjustmentOffset = nullptr;
2603 llvm::Constant *VBPtrOffset = nullptr;
2604 bool IsFunc = SrcTy->isMemberFunctionPointer();
2605 if (!MSInheritanceAttr::hasOnlyOneField(IsFunc, SrcInheritance)) {
2606 // We need to extract values.
2608 FirstField = Src->getAggregateElement(I++);
2609 if (MSInheritanceAttr::hasNVOffsetField(IsFunc, SrcInheritance))
2610 NonVirtualBaseAdjustment = Src->getAggregateElement(I++);
2611 if (MSInheritanceAttr::hasVBPtrOffsetField(SrcInheritance))
2612 VBPtrOffset = Src->getAggregateElement(I++);
2613 if (MSInheritanceAttr::hasVBTableOffsetField(SrcInheritance))
2614 VirtualBaseAdjustmentOffset = Src->getAggregateElement(I++);
2617 // For data pointers, we adjust the field offset directly. For functions, we
2618 // have a separate field.
2619 llvm::Constant *Adj = getMemberPointerAdjustment(E);
2621 Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy);
2622 llvm::Constant *&NVAdjustField =
2623 IsFunc ? NonVirtualBaseAdjustment : FirstField;
2624 bool IsDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
2625 if (!NVAdjustField) // If this field didn't exist in src, it's zero.
2626 NVAdjustField = getZeroInt();
2627 if (IsDerivedToBase)
2628 NVAdjustField = llvm::ConstantExpr::getNSWSub(NVAdjustField, Adj);
2630 NVAdjustField = llvm::ConstantExpr::getNSWAdd(NVAdjustField, Adj);
2633 // FIXME PR15713: Support conversions through virtually derived classes.
2635 // Recompose dst from the null struct and the adjusted fields from src.
2636 if (MSInheritanceAttr::hasOnlyOneField(IsFunc, DstInheritance))
2639 llvm::SmallVector<llvm::Constant *, 4> Fields;
2640 Fields.push_back(FirstField);
2641 if (MSInheritanceAttr::hasNVOffsetField(IsFunc, DstInheritance))
2642 Fields.push_back(getConstantOrZeroInt(NonVirtualBaseAdjustment));
2643 if (MSInheritanceAttr::hasVBPtrOffsetField(DstInheritance))
2644 Fields.push_back(getConstantOrZeroInt(VBPtrOffset));
2645 if (MSInheritanceAttr::hasVBTableOffsetField(DstInheritance))
2646 Fields.push_back(getConstantOrZeroInt(VirtualBaseAdjustmentOffset));
2647 return llvm::ConstantStruct::getAnon(Fields);
2650 llvm::Value *MicrosoftCXXABI::EmitLoadOfMemberFunctionPointer(
2651 CodeGenFunction &CGF, const Expr *E, llvm::Value *&This,
2652 llvm::Value *MemPtr, const MemberPointerType *MPT) {
2653 assert(MPT->isMemberFunctionPointer());
2654 const FunctionProtoType *FPT =
2655 MPT->getPointeeType()->castAs<FunctionProtoType>();
2656 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2657 llvm::FunctionType *FTy =
2658 CGM.getTypes().GetFunctionType(
2659 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
2660 CGBuilderTy &Builder = CGF.Builder;
2662 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
2664 // Extract the fields we need, regardless of model. We'll apply them if we
2666 llvm::Value *FunctionPointer = MemPtr;
2667 llvm::Value *NonVirtualBaseAdjustment = nullptr;
2668 llvm::Value *VirtualBaseAdjustmentOffset = nullptr;
2669 llvm::Value *VBPtrOffset = nullptr;
2670 if (MemPtr->getType()->isStructTy()) {
2671 // We need to extract values.
2673 FunctionPointer = Builder.CreateExtractValue(MemPtr, I++);
2674 if (MSInheritanceAttr::hasNVOffsetField(MPT, Inheritance))
2675 NonVirtualBaseAdjustment = Builder.CreateExtractValue(MemPtr, I++);
2676 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance))
2677 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
2678 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance))
2679 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
2682 if (VirtualBaseAdjustmentOffset) {
2683 This = AdjustVirtualBase(CGF, E, RD, This, VirtualBaseAdjustmentOffset,
2687 if (NonVirtualBaseAdjustment) {
2688 // Apply the adjustment and cast back to the original struct type.
2689 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
2690 Ptr = Builder.CreateInBoundsGEP(Ptr, NonVirtualBaseAdjustment);
2691 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
2694 return Builder.CreateBitCast(FunctionPointer, FTy->getPointerTo());
2697 CGCXXABI *clang::CodeGen::CreateMicrosoftCXXABI(CodeGenModule &CGM) {
2698 return new MicrosoftCXXABI(CGM);
2701 // MS RTTI Overview:
2702 // The run time type information emitted by cl.exe contains 5 distinct types of
2703 // structures. Many of them reference each other.
2705 // TypeInfo: Static classes that are returned by typeid.
2707 // CompleteObjectLocator: Referenced by vftables. They contain information
2708 // required for dynamic casting, including OffsetFromTop. They also contain
2709 // a reference to the TypeInfo for the type and a reference to the
2710 // CompleteHierarchyDescriptor for the type.
2712 // ClassHieararchyDescriptor: Contains information about a class hierarchy.
2713 // Used during dynamic_cast to walk a class hierarchy. References a base
2714 // class array and the size of said array.
2716 // BaseClassArray: Contains a list of classes in a hierarchy. BaseClassArray is
2717 // somewhat of a misnomer because the most derived class is also in the list
2718 // as well as multiple copies of virtual bases (if they occur multiple times
2719 // in the hiearchy.) The BaseClassArray contains one BaseClassDescriptor for
2720 // every path in the hierarchy, in pre-order depth first order. Note, we do
2721 // not declare a specific llvm type for BaseClassArray, it's merely an array
2722 // of BaseClassDescriptor pointers.
2724 // BaseClassDescriptor: Contains information about a class in a class hierarchy.
2725 // BaseClassDescriptor is also somewhat of a misnomer for the same reason that
2726 // BaseClassArray is. It contains information about a class within a
2727 // hierarchy such as: is this base is ambiguous and what is its offset in the
2728 // vbtable. The names of the BaseClassDescriptors have all of their fields
2729 // mangled into them so they can be aggressively deduplicated by the linker.
2731 static llvm::GlobalVariable *getTypeInfoVTable(CodeGenModule &CGM) {
2732 StringRef MangledName("\01??_7type_info@@6B@");
2733 if (auto VTable = CGM.getModule().getNamedGlobal(MangledName))
2735 return new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
2737 llvm::GlobalVariable::ExternalLinkage,
2738 /*Initializer=*/nullptr, MangledName);
2743 /// \brief A Helper struct that stores information about a class in a class
2744 /// hierarchy. The information stored in these structs struct is used during
2745 /// the generation of ClassHierarchyDescriptors and BaseClassDescriptors.
2746 // During RTTI creation, MSRTTIClasses are stored in a contiguous array with
2747 // implicit depth first pre-order tree connectivity. getFirstChild and
2748 // getNextSibling allow us to walk the tree efficiently.
2749 struct MSRTTIClass {
2751 IsPrivateOnPath = 1 | 8,
2755 HasHierarchyDescriptor = 64
2757 MSRTTIClass(const CXXRecordDecl *RD) : RD(RD) {}
2758 uint32_t initialize(const MSRTTIClass *Parent,
2759 const CXXBaseSpecifier *Specifier);
2761 MSRTTIClass *getFirstChild() { return this + 1; }
2762 static MSRTTIClass *getNextChild(MSRTTIClass *Child) {
2763 return Child + 1 + Child->NumBases;
2766 const CXXRecordDecl *RD, *VirtualRoot;
2767 uint32_t Flags, NumBases, OffsetInVBase;
2770 /// \brief Recursively initialize the base class array.
2771 uint32_t MSRTTIClass::initialize(const MSRTTIClass *Parent,
2772 const CXXBaseSpecifier *Specifier) {
2773 Flags = HasHierarchyDescriptor;
2775 VirtualRoot = nullptr;
2778 if (Specifier->getAccessSpecifier() != AS_public)
2779 Flags |= IsPrivate | IsPrivateOnPath;
2780 if (Specifier->isVirtual()) {
2785 if (Parent->Flags & IsPrivateOnPath)
2786 Flags |= IsPrivateOnPath;
2787 VirtualRoot = Parent->VirtualRoot;
2788 OffsetInVBase = Parent->OffsetInVBase + RD->getASTContext()
2789 .getASTRecordLayout(Parent->RD).getBaseClassOffset(RD).getQuantity();
2793 MSRTTIClass *Child = getFirstChild();
2794 for (const CXXBaseSpecifier &Base : RD->bases()) {
2795 NumBases += Child->initialize(this, &Base) + 1;
2796 Child = getNextChild(Child);
2801 static llvm::GlobalValue::LinkageTypes getLinkageForRTTI(QualType Ty) {
2802 switch (Ty->getLinkage()) {
2804 case InternalLinkage:
2805 case UniqueExternalLinkage:
2806 return llvm::GlobalValue::InternalLinkage;
2808 case VisibleNoLinkage:
2809 case ExternalLinkage:
2810 return llvm::GlobalValue::LinkOnceODRLinkage;
2812 llvm_unreachable("Invalid linkage!");
2815 /// \brief An ephemeral helper class for building MS RTTI types. It caches some
2816 /// calls to the module and information about the most derived class in a
2818 struct MSRTTIBuilder {
2820 HasBranchingHierarchy = 1,
2821 HasVirtualBranchingHierarchy = 2,
2822 HasAmbiguousBases = 4
2825 MSRTTIBuilder(MicrosoftCXXABI &ABI, const CXXRecordDecl *RD)
2826 : CGM(ABI.CGM), Context(CGM.getContext()),
2827 VMContext(CGM.getLLVMContext()), Module(CGM.getModule()), RD(RD),
2828 Linkage(getLinkageForRTTI(CGM.getContext().getTagDeclType(RD))),
2831 llvm::GlobalVariable *getBaseClassDescriptor(const MSRTTIClass &Classes);
2832 llvm::GlobalVariable *
2833 getBaseClassArray(SmallVectorImpl<MSRTTIClass> &Classes);
2834 llvm::GlobalVariable *getClassHierarchyDescriptor();
2835 llvm::GlobalVariable *getCompleteObjectLocator(const VPtrInfo *Info);
2838 ASTContext &Context;
2839 llvm::LLVMContext &VMContext;
2840 llvm::Module &Module;
2841 const CXXRecordDecl *RD;
2842 llvm::GlobalVariable::LinkageTypes Linkage;
2843 MicrosoftCXXABI &ABI;
2848 /// \brief Recursively serializes a class hierarchy in pre-order depth first
2850 static void serializeClassHierarchy(SmallVectorImpl<MSRTTIClass> &Classes,
2851 const CXXRecordDecl *RD) {
2852 Classes.push_back(MSRTTIClass(RD));
2853 for (const CXXBaseSpecifier &Base : RD->bases())
2854 serializeClassHierarchy(Classes, Base.getType()->getAsCXXRecordDecl());
2857 /// \brief Find ambiguity among base classes.
2859 detectAmbiguousBases(SmallVectorImpl<MSRTTIClass> &Classes) {
2860 llvm::SmallPtrSet<const CXXRecordDecl *, 8> VirtualBases;
2861 llvm::SmallPtrSet<const CXXRecordDecl *, 8> UniqueBases;
2862 llvm::SmallPtrSet<const CXXRecordDecl *, 8> AmbiguousBases;
2863 for (MSRTTIClass *Class = &Classes.front(); Class <= &Classes.back();) {
2864 if ((Class->Flags & MSRTTIClass::IsVirtual) &&
2865 !VirtualBases.insert(Class->RD).second) {
2866 Class = MSRTTIClass::getNextChild(Class);
2869 if (!UniqueBases.insert(Class->RD).second)
2870 AmbiguousBases.insert(Class->RD);
2873 if (AmbiguousBases.empty())
2875 for (MSRTTIClass &Class : Classes)
2876 if (AmbiguousBases.count(Class.RD))
2877 Class.Flags |= MSRTTIClass::IsAmbiguous;
2880 llvm::GlobalVariable *MSRTTIBuilder::getClassHierarchyDescriptor() {
2881 SmallString<256> MangledName;
2883 llvm::raw_svector_ostream Out(MangledName);
2884 ABI.getMangleContext().mangleCXXRTTIClassHierarchyDescriptor(RD, Out);
2887 // Check to see if we've already declared this ClassHierarchyDescriptor.
2888 if (auto CHD = Module.getNamedGlobal(MangledName))
2891 // Serialize the class hierarchy and initialize the CHD Fields.
2892 SmallVector<MSRTTIClass, 8> Classes;
2893 serializeClassHierarchy(Classes, RD);
2894 Classes.front().initialize(/*Parent=*/nullptr, /*Specifier=*/nullptr);
2895 detectAmbiguousBases(Classes);
2897 for (auto Class : Classes) {
2898 if (Class.RD->getNumBases() > 1)
2899 Flags |= HasBranchingHierarchy;
2900 // Note: cl.exe does not calculate "HasAmbiguousBases" correctly. We
2901 // believe the field isn't actually used.
2902 if (Class.Flags & MSRTTIClass::IsAmbiguous)
2903 Flags |= HasAmbiguousBases;
2905 if ((Flags & HasBranchingHierarchy) && RD->getNumVBases() != 0)
2906 Flags |= HasVirtualBranchingHierarchy;
2907 // These gep indices are used to get the address of the first element of the
2908 // base class array.
2909 llvm::Value *GEPIndices[] = {llvm::ConstantInt::get(CGM.IntTy, 0),
2910 llvm::ConstantInt::get(CGM.IntTy, 0)};
2912 // Forward-declare the class hierarchy descriptor
2913 auto Type = ABI.getClassHierarchyDescriptorType();
2914 auto CHD = new llvm::GlobalVariable(Module, Type, /*Constant=*/true, Linkage,
2915 /*Initializer=*/nullptr,
2916 MangledName.c_str());
2917 if (CHD->isWeakForLinker())
2918 CHD->setComdat(CGM.getModule().getOrInsertComdat(CHD->getName()));
2920 // Initialize the base class ClassHierarchyDescriptor.
2921 llvm::Constant *Fields[] = {
2922 llvm::ConstantInt::get(CGM.IntTy, 0), // Unknown
2923 llvm::ConstantInt::get(CGM.IntTy, Flags),
2924 llvm::ConstantInt::get(CGM.IntTy, Classes.size()),
2925 ABI.getImageRelativeConstant(llvm::ConstantExpr::getInBoundsGetElementPtr(
2926 getBaseClassArray(Classes),
2927 llvm::ArrayRef<llvm::Value *>(GEPIndices))),
2929 CHD->setInitializer(llvm::ConstantStruct::get(Type, Fields));
2933 llvm::GlobalVariable *
2934 MSRTTIBuilder::getBaseClassArray(SmallVectorImpl<MSRTTIClass> &Classes) {
2935 SmallString<256> MangledName;
2937 llvm::raw_svector_ostream Out(MangledName);
2938 ABI.getMangleContext().mangleCXXRTTIBaseClassArray(RD, Out);
2941 // Forward-declare the base class array.
2942 // cl.exe pads the base class array with 1 (in 32 bit mode) or 4 (in 64 bit
2943 // mode) bytes of padding. We provide a pointer sized amount of padding by
2944 // adding +1 to Classes.size(). The sections have pointer alignment and are
2945 // marked pick-any so it shouldn't matter.
2946 llvm::Type *PtrType = ABI.getImageRelativeType(
2947 ABI.getBaseClassDescriptorType()->getPointerTo());
2948 auto *ArrType = llvm::ArrayType::get(PtrType, Classes.size() + 1);
2949 auto *BCA = new llvm::GlobalVariable(
2951 /*Constant=*/true, Linkage, /*Initializer=*/nullptr, MangledName.c_str());
2952 if (BCA->isWeakForLinker())
2953 BCA->setComdat(CGM.getModule().getOrInsertComdat(BCA->getName()));
2955 // Initialize the BaseClassArray.
2956 SmallVector<llvm::Constant *, 8> BaseClassArrayData;
2957 for (MSRTTIClass &Class : Classes)
2958 BaseClassArrayData.push_back(
2959 ABI.getImageRelativeConstant(getBaseClassDescriptor(Class)));
2960 BaseClassArrayData.push_back(llvm::Constant::getNullValue(PtrType));
2961 BCA->setInitializer(llvm::ConstantArray::get(ArrType, BaseClassArrayData));
2965 llvm::GlobalVariable *
2966 MSRTTIBuilder::getBaseClassDescriptor(const MSRTTIClass &Class) {
2967 // Compute the fields for the BaseClassDescriptor. They are computed up front
2968 // because they are mangled into the name of the object.
2969 uint32_t OffsetInVBTable = 0;
2970 int32_t VBPtrOffset = -1;
2971 if (Class.VirtualRoot) {
2972 auto &VTableContext = CGM.getMicrosoftVTableContext();
2973 OffsetInVBTable = VTableContext.getVBTableIndex(RD, Class.VirtualRoot) * 4;
2974 VBPtrOffset = Context.getASTRecordLayout(RD).getVBPtrOffset().getQuantity();
2977 SmallString<256> MangledName;
2979 llvm::raw_svector_ostream Out(MangledName);
2980 ABI.getMangleContext().mangleCXXRTTIBaseClassDescriptor(
2981 Class.RD, Class.OffsetInVBase, VBPtrOffset, OffsetInVBTable,
2985 // Check to see if we've already declared this object.
2986 if (auto BCD = Module.getNamedGlobal(MangledName))
2989 // Forward-declare the base class descriptor.
2990 auto Type = ABI.getBaseClassDescriptorType();
2991 auto BCD = new llvm::GlobalVariable(Module, Type, /*Constant=*/true, Linkage,
2992 /*Initializer=*/nullptr,
2993 MangledName.c_str());
2994 if (BCD->isWeakForLinker())
2995 BCD->setComdat(CGM.getModule().getOrInsertComdat(BCD->getName()));
2997 // Initialize the BaseClassDescriptor.
2998 llvm::Constant *Fields[] = {
2999 ABI.getImageRelativeConstant(
3000 ABI.getAddrOfRTTIDescriptor(Context.getTypeDeclType(Class.RD))),
3001 llvm::ConstantInt::get(CGM.IntTy, Class.NumBases),
3002 llvm::ConstantInt::get(CGM.IntTy, Class.OffsetInVBase),
3003 llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset),
3004 llvm::ConstantInt::get(CGM.IntTy, OffsetInVBTable),
3005 llvm::ConstantInt::get(CGM.IntTy, Class.Flags),
3006 ABI.getImageRelativeConstant(
3007 MSRTTIBuilder(ABI, Class.RD).getClassHierarchyDescriptor()),
3009 BCD->setInitializer(llvm::ConstantStruct::get(Type, Fields));
3013 llvm::GlobalVariable *
3014 MSRTTIBuilder::getCompleteObjectLocator(const VPtrInfo *Info) {
3015 SmallString<256> MangledName;
3017 llvm::raw_svector_ostream Out(MangledName);
3018 ABI.getMangleContext().mangleCXXRTTICompleteObjectLocator(RD, Info->MangledPath, Out);
3021 // Check to see if we've already computed this complete object locator.
3022 if (auto COL = Module.getNamedGlobal(MangledName))
3025 // Compute the fields of the complete object locator.
3026 int OffsetToTop = Info->FullOffsetInMDC.getQuantity();
3027 int VFPtrOffset = 0;
3028 // The offset includes the vtordisp if one exists.
3029 if (const CXXRecordDecl *VBase = Info->getVBaseWithVPtr())
3030 if (Context.getASTRecordLayout(RD)
3031 .getVBaseOffsetsMap()
3033 ->second.hasVtorDisp())
3034 VFPtrOffset = Info->NonVirtualOffset.getQuantity() + 4;
3036 // Forward-declare the complete object locator.
3037 llvm::StructType *Type = ABI.getCompleteObjectLocatorType();
3038 auto COL = new llvm::GlobalVariable(Module, Type, /*Constant=*/true, Linkage,
3039 /*Initializer=*/nullptr, MangledName.c_str());
3041 // Initialize the CompleteObjectLocator.
3042 llvm::Constant *Fields[] = {
3043 llvm::ConstantInt::get(CGM.IntTy, ABI.isImageRelative()),
3044 llvm::ConstantInt::get(CGM.IntTy, OffsetToTop),
3045 llvm::ConstantInt::get(CGM.IntTy, VFPtrOffset),
3046 ABI.getImageRelativeConstant(
3047 CGM.GetAddrOfRTTIDescriptor(Context.getTypeDeclType(RD))),
3048 ABI.getImageRelativeConstant(getClassHierarchyDescriptor()),
3049 ABI.getImageRelativeConstant(COL),
3051 llvm::ArrayRef<llvm::Constant *> FieldsRef(Fields);
3052 if (!ABI.isImageRelative())
3053 FieldsRef = FieldsRef.drop_back();
3054 COL->setInitializer(llvm::ConstantStruct::get(Type, FieldsRef));
3055 if (COL->isWeakForLinker())
3056 COL->setComdat(CGM.getModule().getOrInsertComdat(COL->getName()));
3060 /// \brief Gets a TypeDescriptor. Returns a llvm::Constant * rather than a
3061 /// llvm::GlobalVariable * because different type descriptors have different
3062 /// types, and need to be abstracted. They are abstracting by casting the
3063 /// address to an Int8PtrTy.
3064 llvm::Constant *MicrosoftCXXABI::getAddrOfRTTIDescriptor(QualType Type) {
3065 SmallString<256> MangledName, TypeInfoString;
3067 llvm::raw_svector_ostream Out(MangledName);
3068 getMangleContext().mangleCXXRTTI(Type, Out);
3071 // Check to see if we've already declared this TypeDescriptor.
3072 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
3073 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
3075 // Compute the fields for the TypeDescriptor.
3077 llvm::raw_svector_ostream Out(TypeInfoString);
3078 getMangleContext().mangleCXXRTTIName(Type, Out);
3081 // Declare and initialize the TypeDescriptor.
3082 llvm::Constant *Fields[] = {
3083 getTypeInfoVTable(CGM), // VFPtr
3084 llvm::ConstantPointerNull::get(CGM.Int8PtrTy), // Runtime data
3085 llvm::ConstantDataArray::getString(CGM.getLLVMContext(), TypeInfoString)};
3086 llvm::StructType *TypeDescriptorType =
3087 getTypeDescriptorType(TypeInfoString);
3088 auto *Var = new llvm::GlobalVariable(
3089 CGM.getModule(), TypeDescriptorType, /*Constant=*/false,
3090 getLinkageForRTTI(Type),
3091 llvm::ConstantStruct::get(TypeDescriptorType, Fields),
3092 MangledName.c_str());
3093 if (Var->isWeakForLinker())
3094 Var->setComdat(CGM.getModule().getOrInsertComdat(Var->getName()));
3095 return llvm::ConstantExpr::getBitCast(Var, CGM.Int8PtrTy);
3098 /// \brief Gets or a creates a Microsoft CompleteObjectLocator.
3099 llvm::GlobalVariable *
3100 MicrosoftCXXABI::getMSCompleteObjectLocator(const CXXRecordDecl *RD,
3101 const VPtrInfo *Info) {
3102 return MSRTTIBuilder(*this, RD).getCompleteObjectLocator(Info);
3105 static void emitCXXConstructor(CodeGenModule &CGM,
3106 const CXXConstructorDecl *ctor,
3107 StructorType ctorType) {
3108 // There are no constructor variants, always emit the complete destructor.
3109 llvm::Function *Fn = CGM.codegenCXXStructor(ctor, StructorType::Complete);
3110 CGM.maybeSetTrivialComdat(*ctor, *Fn);
3113 static void emitCXXDestructor(CodeGenModule &CGM, const CXXDestructorDecl *dtor,
3114 StructorType dtorType) {
3115 // The complete destructor is equivalent to the base destructor for
3116 // classes with no virtual bases, so try to emit it as an alias.
3117 if (!dtor->getParent()->getNumVBases() &&
3118 (dtorType == StructorType::Complete || dtorType == StructorType::Base)) {
3119 bool ProducedAlias = !CGM.TryEmitDefinitionAsAlias(
3120 GlobalDecl(dtor, Dtor_Complete), GlobalDecl(dtor, Dtor_Base), true);
3121 if (ProducedAlias) {
3122 if (dtorType == StructorType::Complete)
3124 if (dtor->isVirtual())
3125 CGM.getVTables().EmitThunks(GlobalDecl(dtor, Dtor_Complete));
3129 // The base destructor is equivalent to the base destructor of its
3130 // base class if there is exactly one non-virtual base class with a
3131 // non-trivial destructor, there are no fields with a non-trivial
3132 // destructor, and the body of the destructor is trivial.
3133 if (dtorType == StructorType::Base && !CGM.TryEmitBaseDestructorAsAlias(dtor))
3136 llvm::Function *Fn = CGM.codegenCXXStructor(dtor, dtorType);
3137 if (Fn->isWeakForLinker())
3138 Fn->setComdat(CGM.getModule().getOrInsertComdat(Fn->getName()));
3141 void MicrosoftCXXABI::emitCXXStructor(const CXXMethodDecl *MD,
3142 StructorType Type) {
3143 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
3144 emitCXXConstructor(CGM, CD, Type);
3147 emitCXXDestructor(CGM, cast<CXXDestructorDecl>(MD), Type);