1 //===--- MicrosoftCXXABI.cpp - Emit LLVM Code from ASTs for a Module ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This provides C++ code generation targeting the Microsoft Visual C++ ABI.
11 // The class in this file generates structures that follow the Microsoft
12 // Visual C++ ABI, which is actually not very well documented at all outside
15 //===----------------------------------------------------------------------===//
18 #include "CGVTables.h"
19 #include "CodeGenModule.h"
20 #include "CodeGenTypes.h"
21 #include "TargetInfo.h"
22 #include "clang/AST/Decl.h"
23 #include "clang/AST/DeclCXX.h"
24 #include "clang/AST/StmtCXX.h"
25 #include "clang/AST/VTableBuilder.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringSet.h"
28 #include "llvm/IR/CallSite.h"
29 #include "llvm/IR/Intrinsics.h"
31 using namespace clang;
32 using namespace CodeGen;
36 /// Holds all the vbtable globals for a given class.
37 struct VBTableGlobals {
38 const VPtrInfoVector *VBTables;
39 SmallVector<llvm::GlobalVariable *, 2> Globals;
42 class MicrosoftCXXABI : public CGCXXABI {
44 MicrosoftCXXABI(CodeGenModule &CGM)
45 : CGCXXABI(CGM), BaseClassDescriptorType(nullptr),
46 ClassHierarchyDescriptorType(nullptr),
47 CompleteObjectLocatorType(nullptr), CatchableTypeType(nullptr),
48 ThrowInfoType(nullptr), CatchHandlerTypeType(nullptr) {}
50 bool HasThisReturn(GlobalDecl GD) const override;
51 bool hasMostDerivedReturn(GlobalDecl GD) const override;
53 bool classifyReturnType(CGFunctionInfo &FI) const override;
55 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override;
57 bool isSRetParameterAfterThis() const override { return true; }
59 bool isThisCompleteObject(GlobalDecl GD) const override {
60 // The Microsoft ABI doesn't use separate complete-object vs.
61 // base-object variants of constructors, but it does of destructors.
62 if (isa<CXXDestructorDecl>(GD.getDecl())) {
63 switch (GD.getDtorType()) {
71 case Dtor_Comdat: llvm_unreachable("emitting dtor comdat as function?");
73 llvm_unreachable("bad dtor kind");
80 size_t getSrcArgforCopyCtor(const CXXConstructorDecl *CD,
81 FunctionArgList &Args) const override {
82 assert(Args.size() >= 2 &&
83 "expected the arglist to have at least two args!");
84 // The 'most_derived' parameter goes second if the ctor is variadic and
86 if (CD->getParent()->getNumVBases() > 0 &&
87 CD->getType()->castAs<FunctionProtoType>()->isVariadic())
92 StringRef GetPureVirtualCallName() override { return "_purecall"; }
93 StringRef GetDeletedVirtualCallName() override { return "_purecall"; }
95 void emitVirtualObjectDelete(CodeGenFunction &CGF, const CXXDeleteExpr *DE,
96 Address Ptr, QualType ElementType,
97 const CXXDestructorDecl *Dtor) override;
99 void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) override;
100 void emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) override;
102 void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override;
104 llvm::GlobalVariable *getMSCompleteObjectLocator(const CXXRecordDecl *RD,
105 const VPtrInfo *Info);
107 llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override;
109 getAddrOfCXXCatchHandlerType(QualType Ty, QualType CatchHandlerType) override;
111 bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override;
112 void EmitBadTypeidCall(CodeGenFunction &CGF) override;
113 llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
115 llvm::Type *StdTypeInfoPtrTy) override;
117 bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
118 QualType SrcRecordTy) override;
120 llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, Address Value,
121 QualType SrcRecordTy, QualType DestTy,
122 QualType DestRecordTy,
123 llvm::BasicBlock *CastEnd) override;
125 llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, Address Value,
126 QualType SrcRecordTy,
127 QualType DestTy) override;
129 bool EmitBadCastCall(CodeGenFunction &CGF) override;
130 bool canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const override {
135 GetVirtualBaseClassOffset(CodeGenFunction &CGF, Address This,
136 const CXXRecordDecl *ClassDecl,
137 const CXXRecordDecl *BaseClassDecl) override;
140 EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
141 const CXXRecordDecl *RD) override;
143 void initializeHiddenVirtualInheritanceMembers(CodeGenFunction &CGF,
144 const CXXRecordDecl *RD) override;
146 void EmitCXXConstructors(const CXXConstructorDecl *D) override;
148 // Background on MSVC destructors
149 // ==============================
151 // Both Itanium and MSVC ABIs have destructor variants. The variant names
152 // roughly correspond in the following way:
154 // Base -> no name, just ~Class
155 // Complete -> vbase destructor
156 // Deleting -> scalar deleting destructor
157 // vector deleting destructor
159 // The base and complete destructors are the same as in Itanium, although the
160 // complete destructor does not accept a VTT parameter when there are virtual
161 // bases. A separate mechanism involving vtordisps is used to ensure that
162 // virtual methods of destroyed subobjects are not called.
164 // The deleting destructors accept an i32 bitfield as a second parameter. Bit
165 // 1 indicates if the memory should be deleted. Bit 2 indicates if the this
166 // pointer points to an array. The scalar deleting destructor assumes that
167 // bit 2 is zero, and therefore does not contain a loop.
169 // For virtual destructors, only one entry is reserved in the vftable, and it
170 // always points to the vector deleting destructor. The vector deleting
171 // destructor is the most general, so it can be used to destroy objects in
172 // place, delete single heap objects, or delete arrays.
174 // A TU defining a non-inline destructor is only guaranteed to emit a base
175 // destructor, and all of the other variants are emitted on an as-needed basis
176 // in COMDATs. Because a non-base destructor can be emitted in a TU that
177 // lacks a definition for the destructor, non-base destructors must always
178 // delegate to or alias the base destructor.
180 void buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
181 SmallVectorImpl<CanQualType> &ArgTys) override;
183 /// Non-base dtors should be emitted as delegating thunks in this ABI.
184 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
185 CXXDtorType DT) const override {
186 return DT != Dtor_Base;
189 void EmitCXXDestructors(const CXXDestructorDecl *D) override;
191 const CXXRecordDecl *
192 getThisArgumentTypeForMethod(const CXXMethodDecl *MD) override {
193 MD = MD->getCanonicalDecl();
194 if (MD->isVirtual() && !isa<CXXDestructorDecl>(MD)) {
195 MicrosoftVTableContext::MethodVFTableLocation ML =
196 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(MD);
197 // The vbases might be ordered differently in the final overrider object
198 // and the complete object, so the "this" argument may sometimes point to
199 // memory that has no particular type (e.g. past the complete object).
200 // In this case, we just use a generic pointer type.
201 // FIXME: might want to have a more precise type in the non-virtual
202 // multiple inheritance case.
203 if (ML.VBase || !ML.VFPtrOffset.isZero())
206 return MD->getParent();
210 adjustThisArgumentForVirtualFunctionCall(CodeGenFunction &CGF, GlobalDecl GD,
212 bool VirtualCall) override;
214 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
215 FunctionArgList &Params) override;
217 llvm::Value *adjustThisParameterInVirtualFunctionPrologue(
218 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) override;
220 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
222 unsigned addImplicitConstructorArgs(CodeGenFunction &CGF,
223 const CXXConstructorDecl *D,
224 CXXCtorType Type, bool ForVirtualBase,
226 CallArgList &Args) override;
228 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
229 CXXDtorType Type, bool ForVirtualBase,
230 bool Delegating, Address This) override;
232 void emitVTableBitSetEntries(VPtrInfo *Info, const CXXRecordDecl *RD,
233 llvm::GlobalVariable *VTable);
235 void emitVTableDefinitions(CodeGenVTables &CGVT,
236 const CXXRecordDecl *RD) override;
238 bool isVirtualOffsetNeededForVTableField(CodeGenFunction &CGF,
239 CodeGenFunction::VPtr Vptr) override;
241 /// Don't initialize vptrs if dynamic class
242 /// is marked with with the 'novtable' attribute.
243 bool doStructorsInitializeVPtrs(const CXXRecordDecl *VTableClass) override {
244 return !VTableClass->hasAttr<MSNoVTableAttr>();
248 getVTableAddressPoint(BaseSubobject Base,
249 const CXXRecordDecl *VTableClass) override;
251 llvm::Value *getVTableAddressPointInStructor(
252 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
253 BaseSubobject Base, const CXXRecordDecl *NearestVBase) override;
256 getVTableAddressPointForConstExpr(BaseSubobject Base,
257 const CXXRecordDecl *VTableClass) override;
259 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
260 CharUnits VPtrOffset) override;
262 llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
263 Address This, llvm::Type *Ty,
264 SourceLocation Loc) override;
266 llvm::Value *EmitVirtualDestructorCall(CodeGenFunction &CGF,
267 const CXXDestructorDecl *Dtor,
268 CXXDtorType DtorType,
270 const CXXMemberCallExpr *CE) override;
272 void adjustCallArgsForDestructorThunk(CodeGenFunction &CGF, GlobalDecl GD,
273 CallArgList &CallArgs) override {
274 assert(GD.getDtorType() == Dtor_Deleting &&
275 "Only deleting destructor thunks are available in this ABI");
276 CallArgs.add(RValue::get(getStructorImplicitParamValue(CGF)),
280 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
282 llvm::GlobalVariable *
283 getAddrOfVBTable(const VPtrInfo &VBT, const CXXRecordDecl *RD,
284 llvm::GlobalVariable::LinkageTypes Linkage);
286 llvm::GlobalVariable *
287 getAddrOfVirtualDisplacementMap(const CXXRecordDecl *SrcRD,
288 const CXXRecordDecl *DstRD) {
289 SmallString<256> OutName;
290 llvm::raw_svector_ostream Out(OutName);
291 getMangleContext().mangleCXXVirtualDisplacementMap(SrcRD, DstRD, Out);
292 StringRef MangledName = OutName.str();
294 if (auto *VDispMap = CGM.getModule().getNamedGlobal(MangledName))
297 MicrosoftVTableContext &VTContext = CGM.getMicrosoftVTableContext();
298 unsigned NumEntries = 1 + SrcRD->getNumVBases();
299 SmallVector<llvm::Constant *, 4> Map(NumEntries,
300 llvm::UndefValue::get(CGM.IntTy));
301 Map[0] = llvm::ConstantInt::get(CGM.IntTy, 0);
302 bool AnyDifferent = false;
303 for (const auto &I : SrcRD->vbases()) {
304 const CXXRecordDecl *VBase = I.getType()->getAsCXXRecordDecl();
305 if (!DstRD->isVirtuallyDerivedFrom(VBase))
308 unsigned SrcVBIndex = VTContext.getVBTableIndex(SrcRD, VBase);
309 unsigned DstVBIndex = VTContext.getVBTableIndex(DstRD, VBase);
310 Map[SrcVBIndex] = llvm::ConstantInt::get(CGM.IntTy, DstVBIndex * 4);
311 AnyDifferent |= SrcVBIndex != DstVBIndex;
313 // This map would be useless, don't use it.
317 llvm::ArrayType *VDispMapTy = llvm::ArrayType::get(CGM.IntTy, Map.size());
318 llvm::Constant *Init = llvm::ConstantArray::get(VDispMapTy, Map);
319 llvm::GlobalValue::LinkageTypes Linkage =
320 SrcRD->isExternallyVisible() && DstRD->isExternallyVisible()
321 ? llvm::GlobalValue::LinkOnceODRLinkage
322 : llvm::GlobalValue::InternalLinkage;
323 auto *VDispMap = new llvm::GlobalVariable(
324 CGM.getModule(), VDispMapTy, /*Constant=*/true, Linkage,
325 /*Initializer=*/Init, MangledName);
329 void emitVBTableDefinition(const VPtrInfo &VBT, const CXXRecordDecl *RD,
330 llvm::GlobalVariable *GV) const;
332 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable,
333 GlobalDecl GD, bool ReturnAdjustment) override {
334 // Never dllimport/dllexport thunks.
335 Thunk->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
338 getContext().GetGVALinkageForFunction(cast<FunctionDecl>(GD.getDecl()));
340 if (Linkage == GVA_Internal)
341 Thunk->setLinkage(llvm::GlobalValue::InternalLinkage);
342 else if (ReturnAdjustment)
343 Thunk->setLinkage(llvm::GlobalValue::WeakODRLinkage);
345 Thunk->setLinkage(llvm::GlobalValue::LinkOnceODRLinkage);
348 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, Address This,
349 const ThisAdjustment &TA) override;
351 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
352 const ReturnAdjustment &RA) override;
354 void EmitThreadLocalInitFuncs(
356 ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *>>
358 ArrayRef<llvm::Function *> CXXThreadLocalInits,
359 ArrayRef<llvm::GlobalVariable *> CXXThreadLocalInitVars) override;
361 bool usesThreadWrapperFunction() const override { return false; }
362 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
363 QualType LValType) override;
365 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
366 llvm::GlobalVariable *DeclPtr,
367 bool PerformInit) override;
368 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
369 llvm::Constant *Dtor, llvm::Constant *Addr) override;
371 // ==== Notes on array cookies =========
373 // MSVC seems to only use cookies when the class has a destructor; a
374 // two-argument usual array deallocation function isn't sufficient.
376 // For example, this code prints "100" and "1":
379 // void *operator new[](size_t sz) {
380 // printf("%u\n", sz);
381 // return malloc(sz);
383 // void operator delete[](void *p, size_t sz) {
384 // printf("%u\n", sz);
389 // A *p = new A[100];
392 // Whereas it prints "104" and "104" if you give A a destructor.
394 bool requiresArrayCookie(const CXXDeleteExpr *expr,
395 QualType elementType) override;
396 bool requiresArrayCookie(const CXXNewExpr *expr) override;
397 CharUnits getArrayCookieSizeImpl(QualType type) override;
398 Address InitializeArrayCookie(CodeGenFunction &CGF,
400 llvm::Value *NumElements,
401 const CXXNewExpr *expr,
402 QualType ElementType) override;
403 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
405 CharUnits cookieSize) override;
407 friend struct MSRTTIBuilder;
409 bool isImageRelative() const {
410 return CGM.getTarget().getPointerWidth(/*AddressSpace=*/0) == 64;
413 // 5 routines for constructing the llvm types for MS RTTI structs.
414 llvm::StructType *getTypeDescriptorType(StringRef TypeInfoString) {
415 llvm::SmallString<32> TDTypeName("rtti.TypeDescriptor");
416 TDTypeName += llvm::utostr(TypeInfoString.size());
417 llvm::StructType *&TypeDescriptorType =
418 TypeDescriptorTypeMap[TypeInfoString.size()];
419 if (TypeDescriptorType)
420 return TypeDescriptorType;
421 llvm::Type *FieldTypes[] = {
424 llvm::ArrayType::get(CGM.Int8Ty, TypeInfoString.size() + 1)};
426 llvm::StructType::create(CGM.getLLVMContext(), FieldTypes, TDTypeName);
427 return TypeDescriptorType;
430 llvm::Type *getImageRelativeType(llvm::Type *PtrType) {
431 if (!isImageRelative())
436 llvm::StructType *getBaseClassDescriptorType() {
437 if (BaseClassDescriptorType)
438 return BaseClassDescriptorType;
439 llvm::Type *FieldTypes[] = {
440 getImageRelativeType(CGM.Int8PtrTy),
446 getImageRelativeType(getClassHierarchyDescriptorType()->getPointerTo()),
448 BaseClassDescriptorType = llvm::StructType::create(
449 CGM.getLLVMContext(), FieldTypes, "rtti.BaseClassDescriptor");
450 return BaseClassDescriptorType;
453 llvm::StructType *getClassHierarchyDescriptorType() {
454 if (ClassHierarchyDescriptorType)
455 return ClassHierarchyDescriptorType;
456 // Forward-declare RTTIClassHierarchyDescriptor to break a cycle.
457 ClassHierarchyDescriptorType = llvm::StructType::create(
458 CGM.getLLVMContext(), "rtti.ClassHierarchyDescriptor");
459 llvm::Type *FieldTypes[] = {
463 getImageRelativeType(
464 getBaseClassDescriptorType()->getPointerTo()->getPointerTo()),
466 ClassHierarchyDescriptorType->setBody(FieldTypes);
467 return ClassHierarchyDescriptorType;
470 llvm::StructType *getCompleteObjectLocatorType() {
471 if (CompleteObjectLocatorType)
472 return CompleteObjectLocatorType;
473 CompleteObjectLocatorType = llvm::StructType::create(
474 CGM.getLLVMContext(), "rtti.CompleteObjectLocator");
475 llvm::Type *FieldTypes[] = {
479 getImageRelativeType(CGM.Int8PtrTy),
480 getImageRelativeType(getClassHierarchyDescriptorType()->getPointerTo()),
481 getImageRelativeType(CompleteObjectLocatorType),
483 llvm::ArrayRef<llvm::Type *> FieldTypesRef(FieldTypes);
484 if (!isImageRelative())
485 FieldTypesRef = FieldTypesRef.drop_back();
486 CompleteObjectLocatorType->setBody(FieldTypesRef);
487 return CompleteObjectLocatorType;
490 llvm::GlobalVariable *getImageBase() {
491 StringRef Name = "__ImageBase";
492 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name))
495 return new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty,
497 llvm::GlobalValue::ExternalLinkage,
498 /*Initializer=*/nullptr, Name);
501 llvm::Constant *getImageRelativeConstant(llvm::Constant *PtrVal) {
502 if (!isImageRelative())
505 if (PtrVal->isNullValue())
506 return llvm::Constant::getNullValue(CGM.IntTy);
508 llvm::Constant *ImageBaseAsInt =
509 llvm::ConstantExpr::getPtrToInt(getImageBase(), CGM.IntPtrTy);
510 llvm::Constant *PtrValAsInt =
511 llvm::ConstantExpr::getPtrToInt(PtrVal, CGM.IntPtrTy);
512 llvm::Constant *Diff =
513 llvm::ConstantExpr::getSub(PtrValAsInt, ImageBaseAsInt,
514 /*HasNUW=*/true, /*HasNSW=*/true);
515 return llvm::ConstantExpr::getTrunc(Diff, CGM.IntTy);
519 MicrosoftMangleContext &getMangleContext() {
520 return cast<MicrosoftMangleContext>(CodeGen::CGCXXABI::getMangleContext());
523 llvm::Constant *getZeroInt() {
524 return llvm::ConstantInt::get(CGM.IntTy, 0);
527 llvm::Constant *getAllOnesInt() {
528 return llvm::Constant::getAllOnesValue(CGM.IntTy);
531 llvm::Constant *getConstantOrZeroInt(llvm::Constant *C) {
532 return C ? C : getZeroInt();
535 llvm::Value *getValueOrZeroInt(llvm::Value *C) {
536 return C ? C : getZeroInt();
539 CharUnits getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD);
542 GetNullMemberPointerFields(const MemberPointerType *MPT,
543 llvm::SmallVectorImpl<llvm::Constant *> &fields);
545 /// \brief Shared code for virtual base adjustment. Returns the offset from
546 /// the vbptr to the virtual base. Optionally returns the address of the
548 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
550 llvm::Value *VBPtrOffset,
551 llvm::Value *VBTableOffset,
552 llvm::Value **VBPtr = nullptr);
554 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
557 int32_t VBTableOffset,
558 llvm::Value **VBPtr = nullptr) {
559 assert(VBTableOffset % 4 == 0 && "should be byte offset into table of i32s");
560 llvm::Value *VBPOffset = llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset),
561 *VBTOffset = llvm::ConstantInt::get(CGM.IntTy, VBTableOffset);
562 return GetVBaseOffsetFromVBPtr(CGF, Base, VBPOffset, VBTOffset, VBPtr);
565 std::pair<Address, llvm::Value *>
566 performBaseAdjustment(CodeGenFunction &CGF, Address Value,
567 QualType SrcRecordTy);
569 /// \brief Performs a full virtual base adjustment. Used to dereference
570 /// pointers to members of virtual bases.
571 llvm::Value *AdjustVirtualBase(CodeGenFunction &CGF, const Expr *E,
572 const CXXRecordDecl *RD, Address Base,
573 llvm::Value *VirtualBaseAdjustmentOffset,
574 llvm::Value *VBPtrOffset /* optional */);
576 /// \brief Emits a full member pointer with the fields common to data and
577 /// function member pointers.
578 llvm::Constant *EmitFullMemberPointer(llvm::Constant *FirstField,
579 bool IsMemberFunction,
580 const CXXRecordDecl *RD,
581 CharUnits NonVirtualBaseAdjustment,
582 unsigned VBTableIndex);
584 bool MemberPointerConstantIsNull(const MemberPointerType *MPT,
587 /// \brief - Initialize all vbptrs of 'this' with RD as the complete type.
588 void EmitVBPtrStores(CodeGenFunction &CGF, const CXXRecordDecl *RD);
590 /// \brief Caching wrapper around VBTableBuilder::enumerateVBTables().
591 const VBTableGlobals &enumerateVBTables(const CXXRecordDecl *RD);
593 /// \brief Generate a thunk for calling a virtual member function MD.
594 llvm::Function *EmitVirtualMemPtrThunk(
595 const CXXMethodDecl *MD,
596 const MicrosoftVTableContext::MethodVFTableLocation &ML);
599 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override;
601 bool isZeroInitializable(const MemberPointerType *MPT) override;
603 bool isMemberPointerConvertible(const MemberPointerType *MPT) const override {
604 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
605 return RD->hasAttr<MSInheritanceAttr>();
608 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override;
610 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
611 CharUnits offset) override;
612 llvm::Constant *EmitMemberFunctionPointer(const CXXMethodDecl *MD) override;
613 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override;
615 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
618 const MemberPointerType *MPT,
619 bool Inequality) override;
621 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
623 const MemberPointerType *MPT) override;
626 EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
627 Address Base, llvm::Value *MemPtr,
628 const MemberPointerType *MPT) override;
630 llvm::Value *EmitNonNullMemberPointerConversion(
631 const MemberPointerType *SrcTy, const MemberPointerType *DstTy,
632 CastKind CK, CastExpr::path_const_iterator PathBegin,
633 CastExpr::path_const_iterator PathEnd, llvm::Value *Src,
634 CGBuilderTy &Builder);
636 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
638 llvm::Value *Src) override;
640 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
641 llvm::Constant *Src) override;
643 llvm::Constant *EmitMemberPointerConversion(
644 const MemberPointerType *SrcTy, const MemberPointerType *DstTy,
645 CastKind CK, CastExpr::path_const_iterator PathBegin,
646 CastExpr::path_const_iterator PathEnd, llvm::Constant *Src);
649 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF, const Expr *E,
650 Address This, llvm::Value *&ThisPtrForCall,
652 const MemberPointerType *MPT) override;
654 void emitCXXStructor(const CXXMethodDecl *MD, StructorType Type) override;
656 llvm::StructType *getCatchHandlerTypeType() {
657 if (!CatchHandlerTypeType) {
658 llvm::Type *FieldTypes[] = {
660 CGM.Int8PtrTy, // TypeDescriptor
662 CatchHandlerTypeType = llvm::StructType::create(
663 CGM.getLLVMContext(), FieldTypes, "eh.CatchHandlerType");
665 return CatchHandlerTypeType;
668 llvm::StructType *getCatchableTypeType() {
669 if (CatchableTypeType)
670 return CatchableTypeType;
671 llvm::Type *FieldTypes[] = {
673 getImageRelativeType(CGM.Int8PtrTy), // TypeDescriptor
674 CGM.IntTy, // NonVirtualAdjustment
675 CGM.IntTy, // OffsetToVBPtr
676 CGM.IntTy, // VBTableIndex
678 getImageRelativeType(CGM.Int8PtrTy) // CopyCtor
680 CatchableTypeType = llvm::StructType::create(
681 CGM.getLLVMContext(), FieldTypes, "eh.CatchableType");
682 return CatchableTypeType;
685 llvm::StructType *getCatchableTypeArrayType(uint32_t NumEntries) {
686 llvm::StructType *&CatchableTypeArrayType =
687 CatchableTypeArrayTypeMap[NumEntries];
688 if (CatchableTypeArrayType)
689 return CatchableTypeArrayType;
691 llvm::SmallString<23> CTATypeName("eh.CatchableTypeArray.");
692 CTATypeName += llvm::utostr(NumEntries);
694 getImageRelativeType(getCatchableTypeType()->getPointerTo());
695 llvm::Type *FieldTypes[] = {
696 CGM.IntTy, // NumEntries
697 llvm::ArrayType::get(CTType, NumEntries) // CatchableTypes
699 CatchableTypeArrayType =
700 llvm::StructType::create(CGM.getLLVMContext(), FieldTypes, CTATypeName);
701 return CatchableTypeArrayType;
704 llvm::StructType *getThrowInfoType() {
706 return ThrowInfoType;
707 llvm::Type *FieldTypes[] = {
709 getImageRelativeType(CGM.Int8PtrTy), // CleanupFn
710 getImageRelativeType(CGM.Int8PtrTy), // ForwardCompat
711 getImageRelativeType(CGM.Int8PtrTy) // CatchableTypeArray
713 ThrowInfoType = llvm::StructType::create(CGM.getLLVMContext(), FieldTypes,
715 return ThrowInfoType;
718 llvm::Constant *getThrowFn() {
719 // _CxxThrowException is passed an exception object and a ThrowInfo object
720 // which describes the exception.
721 llvm::Type *Args[] = {CGM.Int8PtrTy, getThrowInfoType()->getPointerTo()};
722 llvm::FunctionType *FTy =
723 llvm::FunctionType::get(CGM.VoidTy, Args, /*IsVarArgs=*/false);
724 auto *Fn = cast<llvm::Function>(
725 CGM.CreateRuntimeFunction(FTy, "_CxxThrowException"));
726 // _CxxThrowException is stdcall on 32-bit x86 platforms.
727 if (CGM.getTarget().getTriple().getArch() == llvm::Triple::x86)
728 Fn->setCallingConv(llvm::CallingConv::X86_StdCall);
732 llvm::Function *getAddrOfCXXCtorClosure(const CXXConstructorDecl *CD,
735 llvm::Constant *getCatchableType(QualType T,
736 uint32_t NVOffset = 0,
737 int32_t VBPtrOffset = -1,
738 uint32_t VBIndex = 0);
740 llvm::GlobalVariable *getCatchableTypeArray(QualType T);
742 llvm::GlobalVariable *getThrowInfo(QualType T) override;
745 typedef std::pair<const CXXRecordDecl *, CharUnits> VFTableIdTy;
746 typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalVariable *> VTablesMapTy;
747 typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalValue *> VFTablesMapTy;
748 /// \brief All the vftables that have been referenced.
749 VFTablesMapTy VFTablesMap;
750 VTablesMapTy VTablesMap;
752 /// \brief This set holds the record decls we've deferred vtable emission for.
753 llvm::SmallPtrSet<const CXXRecordDecl *, 4> DeferredVFTables;
756 /// \brief All the vbtables which have been referenced.
757 llvm::DenseMap<const CXXRecordDecl *, VBTableGlobals> VBTablesMap;
759 /// Info on the global variable used to guard initialization of static locals.
760 /// The BitIndex field is only used for externally invisible declarations.
762 GuardInfo() : Guard(nullptr), BitIndex(0) {}
763 llvm::GlobalVariable *Guard;
767 /// Map from DeclContext to the current guard variable. We assume that the
768 /// AST is visited in source code order.
769 llvm::DenseMap<const DeclContext *, GuardInfo> GuardVariableMap;
770 llvm::DenseMap<const DeclContext *, GuardInfo> ThreadLocalGuardVariableMap;
771 llvm::DenseMap<const DeclContext *, unsigned> ThreadSafeGuardNumMap;
773 llvm::DenseMap<size_t, llvm::StructType *> TypeDescriptorTypeMap;
774 llvm::StructType *BaseClassDescriptorType;
775 llvm::StructType *ClassHierarchyDescriptorType;
776 llvm::StructType *CompleteObjectLocatorType;
778 llvm::DenseMap<QualType, llvm::GlobalVariable *> CatchableTypeArrays;
780 llvm::StructType *CatchableTypeType;
781 llvm::DenseMap<uint32_t, llvm::StructType *> CatchableTypeArrayTypeMap;
782 llvm::StructType *ThrowInfoType;
783 llvm::StructType *CatchHandlerTypeType;
788 CGCXXABI::RecordArgABI
789 MicrosoftCXXABI::getRecordArgABI(const CXXRecordDecl *RD) const {
790 switch (CGM.getTarget().getTriple().getArch()) {
792 // FIXME: Implement for other architectures.
795 case llvm::Triple::x86:
796 // All record arguments are passed in memory on x86. Decide whether to
797 // construct the object directly in argument memory, or to construct the
798 // argument elsewhere and copy the bytes during the call.
800 // If C++ prohibits us from making a copy, construct the arguments directly
801 // into argument memory.
802 if (!canCopyArgument(RD))
803 return RAA_DirectInMemory;
805 // Otherwise, construct the argument into a temporary and copy the bytes
806 // into the outgoing argument memory.
809 case llvm::Triple::x86_64:
810 // Win64 passes objects with non-trivial copy ctors indirectly.
811 if (RD->hasNonTrivialCopyConstructor())
814 // If an object has a destructor, we'd really like to pass it indirectly
815 // because it allows us to elide copies. Unfortunately, MSVC makes that
816 // impossible for small types, which it will pass in a single register or
817 // stack slot. Most objects with dtors are large-ish, so handle that early.
818 // We can't call out all large objects as being indirect because there are
819 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
820 // how we pass large POD types.
821 if (RD->hasNonTrivialDestructor() &&
822 getContext().getTypeSize(RD->getTypeForDecl()) > 64)
825 // We have a trivial copy constructor or no copy constructors, but we have
826 // to make sure it isn't deleted.
827 bool CopyDeleted = false;
828 for (const CXXConstructorDecl *CD : RD->ctors()) {
829 if (CD->isCopyConstructor()) {
830 assert(CD->isTrivial());
831 // We had at least one undeleted trivial copy ctor. Return directly.
832 if (!CD->isDeleted())
838 // The trivial copy constructor was deleted. Return indirectly.
842 // There were no copy ctors. Return in RAX.
846 llvm_unreachable("invalid enum");
849 void MicrosoftCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
850 const CXXDeleteExpr *DE,
852 QualType ElementType,
853 const CXXDestructorDecl *Dtor) {
854 // FIXME: Provide a source location here even though there's no
855 // CXXMemberCallExpr for dtor call.
856 bool UseGlobalDelete = DE->isGlobalDelete();
857 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
858 llvm::Value *MDThis =
859 EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, /*CE=*/nullptr);
861 CGF.EmitDeleteCall(DE->getOperatorDelete(), MDThis, ElementType);
864 void MicrosoftCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
865 llvm::Value *Args[] = {
866 llvm::ConstantPointerNull::get(CGM.Int8PtrTy),
867 llvm::ConstantPointerNull::get(getThrowInfoType()->getPointerTo())};
868 auto *Fn = getThrowFn();
870 CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, Args);
872 CGF.EmitRuntimeCallOrInvoke(Fn, Args);
876 struct CallEndCatchMSVC final : EHScopeStack::Cleanup {
877 llvm::CatchPadInst *CPI;
879 CallEndCatchMSVC(llvm::CatchPadInst *CPI) : CPI(CPI) {}
881 void Emit(CodeGenFunction &CGF, Flags flags) override {
882 if (CGF.CGM.getCodeGenOpts().NewMSEH) {
883 llvm::BasicBlock *BB = CGF.createBasicBlock("catchret.dest");
884 CGF.Builder.CreateCatchRet(CPI, BB);
887 CGF.EmitNounwindRuntimeCall(
888 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_endcatch));
894 void MicrosoftCXXABI::emitBeginCatch(CodeGenFunction &CGF,
895 const CXXCatchStmt *S) {
896 // In the MS ABI, the runtime handles the copy, and the catch handler is
897 // responsible for destruction.
898 VarDecl *CatchParam = S->getExceptionDecl();
899 llvm::Value *Exn = nullptr;
900 llvm::Function *BeginCatch = nullptr;
901 llvm::CatchPadInst *CPI = nullptr;
902 bool NewEH = CGF.CGM.getCodeGenOpts().NewMSEH;
904 Exn = CGF.getExceptionFromSlot();
905 BeginCatch = CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_begincatch);
907 llvm::BasicBlock *CatchPadBB =
908 CGF.Builder.GetInsertBlock()->getSinglePredecessor();
909 CPI = cast<llvm::CatchPadInst>(CatchPadBB->getFirstNonPHI());
911 // If this is a catch-all or the catch parameter is unnamed, we don't need to
912 // emit an alloca to the object.
913 if (!CatchParam || !CatchParam->getDeclName()) {
915 llvm::Value *Args[2] = {Exn, llvm::Constant::getNullValue(CGF.Int8PtrTy)};
916 CGF.EmitNounwindRuntimeCall(BeginCatch, Args);
918 CGF.EHStack.pushCleanup<CallEndCatchMSVC>(NormalCleanup, CPI);
922 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
925 CGF.Builder.CreateElementBitCast(var.getObjectAddress(CGF), CGF.Int8Ty);
926 llvm::Value *Args[2] = {Exn, ParamAddr.getPointer()};
927 CGF.EmitNounwindRuntimeCall(BeginCatch, Args);
929 CPI->setArgOperand(1, var.getObjectAddress(CGF).getPointer());
931 CGF.EHStack.pushCleanup<CallEndCatchMSVC>(NormalCleanup, CPI);
932 CGF.EmitAutoVarCleanups(var);
935 /// We need to perform a generic polymorphic operation (like a typeid
936 /// or a cast), which requires an object with a vfptr. Adjust the
937 /// address to point to an object with a vfptr.
938 std::pair<Address, llvm::Value *>
939 MicrosoftCXXABI::performBaseAdjustment(CodeGenFunction &CGF, Address Value,
940 QualType SrcRecordTy) {
941 Value = CGF.Builder.CreateBitCast(Value, CGF.Int8PtrTy);
942 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
943 const ASTContext &Context = getContext();
945 // If the class itself has a vfptr, great. This check implicitly
946 // covers non-virtual base subobjects: a class with its own virtual
947 // functions would be a candidate to be a primary base.
948 if (Context.getASTRecordLayout(SrcDecl).hasExtendableVFPtr())
949 return std::make_pair(Value, llvm::ConstantInt::get(CGF.Int32Ty, 0));
951 // Okay, one of the vbases must have a vfptr, or else this isn't
952 // actually a polymorphic class.
953 const CXXRecordDecl *PolymorphicBase = nullptr;
954 for (auto &Base : SrcDecl->vbases()) {
955 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
956 if (Context.getASTRecordLayout(BaseDecl).hasExtendableVFPtr()) {
957 PolymorphicBase = BaseDecl;
961 assert(PolymorphicBase && "polymorphic class has no apparent vfptr?");
963 llvm::Value *Offset =
964 GetVirtualBaseClassOffset(CGF, Value, SrcDecl, PolymorphicBase);
965 llvm::Value *Ptr = CGF.Builder.CreateInBoundsGEP(Value.getPointer(), Offset);
966 Offset = CGF.Builder.CreateTrunc(Offset, CGF.Int32Ty);
967 CharUnits VBaseAlign =
968 CGF.CGM.getVBaseAlignment(Value.getAlignment(), SrcDecl, PolymorphicBase);
969 return std::make_pair(Address(Ptr, VBaseAlign), Offset);
972 bool MicrosoftCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
973 QualType SrcRecordTy) {
974 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
976 !getContext().getASTRecordLayout(SrcDecl).hasExtendableVFPtr();
979 static llvm::CallSite emitRTtypeidCall(CodeGenFunction &CGF,
980 llvm::Value *Argument) {
981 llvm::Type *ArgTypes[] = {CGF.Int8PtrTy};
982 llvm::FunctionType *FTy =
983 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false);
984 llvm::Value *Args[] = {Argument};
985 llvm::Constant *Fn = CGF.CGM.CreateRuntimeFunction(FTy, "__RTtypeid");
986 return CGF.EmitRuntimeCallOrInvoke(Fn, Args);
989 void MicrosoftCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
990 llvm::CallSite Call =
991 emitRTtypeidCall(CGF, llvm::Constant::getNullValue(CGM.VoidPtrTy));
992 Call.setDoesNotReturn();
993 CGF.Builder.CreateUnreachable();
996 llvm::Value *MicrosoftCXXABI::EmitTypeid(CodeGenFunction &CGF,
997 QualType SrcRecordTy,
999 llvm::Type *StdTypeInfoPtrTy) {
1000 llvm::Value *Offset;
1001 std::tie(ThisPtr, Offset) = performBaseAdjustment(CGF, ThisPtr, SrcRecordTy);
1002 auto Typeid = emitRTtypeidCall(CGF, ThisPtr.getPointer()).getInstruction();
1003 return CGF.Builder.CreateBitCast(Typeid, StdTypeInfoPtrTy);
1006 bool MicrosoftCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
1007 QualType SrcRecordTy) {
1008 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
1010 !getContext().getASTRecordLayout(SrcDecl).hasExtendableVFPtr();
1013 llvm::Value *MicrosoftCXXABI::EmitDynamicCastCall(
1014 CodeGenFunction &CGF, Address This, QualType SrcRecordTy,
1015 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
1016 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1018 llvm::Value *SrcRTTI =
1019 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1020 llvm::Value *DestRTTI =
1021 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1023 llvm::Value *Offset;
1024 std::tie(This, Offset) = performBaseAdjustment(CGF, This, SrcRecordTy);
1025 llvm::Value *ThisPtr = This.getPointer();
1027 // PVOID __RTDynamicCast(
1031 // PVOID TargetType,
1032 // BOOL isReference)
1033 llvm::Type *ArgTypes[] = {CGF.Int8PtrTy, CGF.Int32Ty, CGF.Int8PtrTy,
1034 CGF.Int8PtrTy, CGF.Int32Ty};
1035 llvm::Constant *Function = CGF.CGM.CreateRuntimeFunction(
1036 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false),
1038 llvm::Value *Args[] = {
1039 ThisPtr, Offset, SrcRTTI, DestRTTI,
1040 llvm::ConstantInt::get(CGF.Int32Ty, DestTy->isReferenceType())};
1041 ThisPtr = CGF.EmitRuntimeCallOrInvoke(Function, Args).getInstruction();
1042 return CGF.Builder.CreateBitCast(ThisPtr, DestLTy);
1046 MicrosoftCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF, Address Value,
1047 QualType SrcRecordTy,
1049 llvm::Value *Offset;
1050 std::tie(Value, Offset) = performBaseAdjustment(CGF, Value, SrcRecordTy);
1052 // PVOID __RTCastToVoid(
1054 llvm::Type *ArgTypes[] = {CGF.Int8PtrTy};
1055 llvm::Constant *Function = CGF.CGM.CreateRuntimeFunction(
1056 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false),
1058 llvm::Value *Args[] = {Value.getPointer()};
1059 return CGF.EmitRuntimeCall(Function, Args);
1062 bool MicrosoftCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1066 llvm::Value *MicrosoftCXXABI::GetVirtualBaseClassOffset(
1067 CodeGenFunction &CGF, Address This, const CXXRecordDecl *ClassDecl,
1068 const CXXRecordDecl *BaseClassDecl) {
1069 const ASTContext &Context = getContext();
1070 int64_t VBPtrChars =
1071 Context.getASTRecordLayout(ClassDecl).getVBPtrOffset().getQuantity();
1072 llvm::Value *VBPtrOffset = llvm::ConstantInt::get(CGM.PtrDiffTy, VBPtrChars);
1073 CharUnits IntSize = Context.getTypeSizeInChars(Context.IntTy);
1074 CharUnits VBTableChars =
1076 CGM.getMicrosoftVTableContext().getVBTableIndex(ClassDecl, BaseClassDecl);
1077 llvm::Value *VBTableOffset =
1078 llvm::ConstantInt::get(CGM.IntTy, VBTableChars.getQuantity());
1080 llvm::Value *VBPtrToNewBase =
1081 GetVBaseOffsetFromVBPtr(CGF, This, VBPtrOffset, VBTableOffset);
1083 CGF.Builder.CreateSExtOrBitCast(VBPtrToNewBase, CGM.PtrDiffTy);
1084 return CGF.Builder.CreateNSWAdd(VBPtrOffset, VBPtrToNewBase);
1087 bool MicrosoftCXXABI::HasThisReturn(GlobalDecl GD) const {
1088 return isa<CXXConstructorDecl>(GD.getDecl());
1091 static bool isDeletingDtor(GlobalDecl GD) {
1092 return isa<CXXDestructorDecl>(GD.getDecl()) &&
1093 GD.getDtorType() == Dtor_Deleting;
1096 bool MicrosoftCXXABI::hasMostDerivedReturn(GlobalDecl GD) const {
1097 return isDeletingDtor(GD);
1100 bool MicrosoftCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
1101 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
1105 CharUnits Align = CGM.getContext().getTypeAlignInChars(FI.getReturnType());
1106 if (FI.isInstanceMethod()) {
1107 // If it's an instance method, aggregates are always returned indirectly via
1108 // the second parameter.
1109 FI.getReturnInfo() = ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
1110 FI.getReturnInfo().setSRetAfterThis(FI.isInstanceMethod());
1112 } else if (!RD->isPOD()) {
1113 // If it's a free function, non-POD types are returned indirectly.
1114 FI.getReturnInfo() = ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
1118 // Otherwise, use the C ABI rules.
1123 MicrosoftCXXABI::EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
1124 const CXXRecordDecl *RD) {
1125 llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);
1126 assert(IsMostDerivedClass &&
1127 "ctor for a class with virtual bases must have an implicit parameter");
1128 llvm::Value *IsCompleteObject =
1129 CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");
1131 llvm::BasicBlock *CallVbaseCtorsBB = CGF.createBasicBlock("ctor.init_vbases");
1132 llvm::BasicBlock *SkipVbaseCtorsBB = CGF.createBasicBlock("ctor.skip_vbases");
1133 CGF.Builder.CreateCondBr(IsCompleteObject,
1134 CallVbaseCtorsBB, SkipVbaseCtorsBB);
1136 CGF.EmitBlock(CallVbaseCtorsBB);
1138 // Fill in the vbtable pointers here.
1139 EmitVBPtrStores(CGF, RD);
1141 // CGF will put the base ctor calls in this basic block for us later.
1143 return SkipVbaseCtorsBB;
1146 void MicrosoftCXXABI::initializeHiddenVirtualInheritanceMembers(
1147 CodeGenFunction &CGF, const CXXRecordDecl *RD) {
1148 // In most cases, an override for a vbase virtual method can adjust
1149 // the "this" parameter by applying a constant offset.
1150 // However, this is not enough while a constructor or a destructor of some
1151 // class X is being executed if all the following conditions are met:
1152 // - X has virtual bases, (1)
1153 // - X overrides a virtual method M of a vbase Y, (2)
1154 // - X itself is a vbase of the most derived class.
1156 // If (1) and (2) are true, the vtorDisp for vbase Y is a hidden member of X
1157 // which holds the extra amount of "this" adjustment we must do when we use
1158 // the X vftables (i.e. during X ctor or dtor).
1159 // Outside the ctors and dtors, the values of vtorDisps are zero.
1161 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1162 typedef ASTRecordLayout::VBaseOffsetsMapTy VBOffsets;
1163 const VBOffsets &VBaseMap = Layout.getVBaseOffsetsMap();
1164 CGBuilderTy &Builder = CGF.Builder;
1166 unsigned AS = getThisAddress(CGF).getAddressSpace();
1167 llvm::Value *Int8This = nullptr; // Initialize lazily.
1169 for (VBOffsets::const_iterator I = VBaseMap.begin(), E = VBaseMap.end();
1171 if (!I->second.hasVtorDisp())
1174 llvm::Value *VBaseOffset =
1175 GetVirtualBaseClassOffset(CGF, getThisAddress(CGF), RD, I->first);
1176 // FIXME: it doesn't look right that we SExt in GetVirtualBaseClassOffset()
1177 // just to Trunc back immediately.
1178 VBaseOffset = Builder.CreateTruncOrBitCast(VBaseOffset, CGF.Int32Ty);
1179 uint64_t ConstantVBaseOffset =
1180 Layout.getVBaseClassOffset(I->first).getQuantity();
1182 // vtorDisp_for_vbase = vbptr[vbase_idx] - offsetof(RD, vbase).
1183 llvm::Value *VtorDispValue = Builder.CreateSub(
1184 VBaseOffset, llvm::ConstantInt::get(CGM.Int32Ty, ConstantVBaseOffset),
1188 Int8This = Builder.CreateBitCast(getThisValue(CGF),
1189 CGF.Int8Ty->getPointerTo(AS));
1190 llvm::Value *VtorDispPtr = Builder.CreateInBoundsGEP(Int8This, VBaseOffset);
1191 // vtorDisp is always the 32-bits before the vbase in the class layout.
1192 VtorDispPtr = Builder.CreateConstGEP1_32(VtorDispPtr, -4);
1193 VtorDispPtr = Builder.CreateBitCast(
1194 VtorDispPtr, CGF.Int32Ty->getPointerTo(AS), "vtordisp.ptr");
1196 Builder.CreateAlignedStore(VtorDispValue, VtorDispPtr,
1197 CharUnits::fromQuantity(4));
1201 static bool hasDefaultCXXMethodCC(ASTContext &Context,
1202 const CXXMethodDecl *MD) {
1203 CallingConv ExpectedCallingConv = Context.getDefaultCallingConvention(
1204 /*IsVariadic=*/false, /*IsCXXMethod=*/true);
1205 CallingConv ActualCallingConv =
1206 MD->getType()->getAs<FunctionProtoType>()->getCallConv();
1207 return ExpectedCallingConv == ActualCallingConv;
1210 void MicrosoftCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1211 // There's only one constructor type in this ABI.
1212 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1214 // Exported default constructors either have a simple call-site where they use
1215 // the typical calling convention and have a single 'this' pointer for an
1216 // argument -or- they get a wrapper function which appropriately thunks to the
1217 // real default constructor. This thunk is the default constructor closure.
1218 if (D->hasAttr<DLLExportAttr>() && D->isDefaultConstructor())
1219 if (!hasDefaultCXXMethodCC(getContext(), D) || D->getNumParams() != 0) {
1220 llvm::Function *Fn = getAddrOfCXXCtorClosure(D, Ctor_DefaultClosure);
1221 Fn->setLinkage(llvm::GlobalValue::WeakODRLinkage);
1222 Fn->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1226 void MicrosoftCXXABI::EmitVBPtrStores(CodeGenFunction &CGF,
1227 const CXXRecordDecl *RD) {
1228 Address This = getThisAddress(CGF);
1229 This = CGF.Builder.CreateElementBitCast(This, CGM.Int8Ty, "this.int8");
1230 const ASTContext &Context = getContext();
1231 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1233 const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
1234 for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) {
1235 const VPtrInfo *VBT = (*VBGlobals.VBTables)[I];
1236 llvm::GlobalVariable *GV = VBGlobals.Globals[I];
1237 const ASTRecordLayout &SubobjectLayout =
1238 Context.getASTRecordLayout(VBT->BaseWithVPtr);
1239 CharUnits Offs = VBT->NonVirtualOffset;
1240 Offs += SubobjectLayout.getVBPtrOffset();
1241 if (VBT->getVBaseWithVPtr())
1242 Offs += Layout.getVBaseClassOffset(VBT->getVBaseWithVPtr());
1243 Address VBPtr = CGF.Builder.CreateConstInBoundsByteGEP(This, Offs);
1244 llvm::Value *GVPtr =
1245 CGF.Builder.CreateConstInBoundsGEP2_32(GV->getValueType(), GV, 0, 0);
1246 VBPtr = CGF.Builder.CreateElementBitCast(VBPtr, GVPtr->getType(),
1247 "vbptr." + VBT->ReusingBase->getName());
1248 CGF.Builder.CreateStore(GVPtr, VBPtr);
1253 MicrosoftCXXABI::buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
1254 SmallVectorImpl<CanQualType> &ArgTys) {
1255 // TODO: 'for base' flag
1256 if (T == StructorType::Deleting) {
1257 // The scalar deleting destructor takes an implicit int parameter.
1258 ArgTys.push_back(getContext().IntTy);
1260 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
1264 // All parameters are already in place except is_most_derived, which goes
1265 // after 'this' if it's variadic and last if it's not.
1267 const CXXRecordDecl *Class = CD->getParent();
1268 const FunctionProtoType *FPT = CD->getType()->castAs<FunctionProtoType>();
1269 if (Class->getNumVBases()) {
1270 if (FPT->isVariadic())
1271 ArgTys.insert(ArgTys.begin() + 1, getContext().IntTy);
1273 ArgTys.push_back(getContext().IntTy);
1277 void MicrosoftCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
1278 // The TU defining a dtor is only guaranteed to emit a base destructor. All
1279 // other destructor variants are delegating thunks.
1280 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
1284 MicrosoftCXXABI::getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD) {
1285 GD = GD.getCanonicalDecl();
1286 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1288 GlobalDecl LookupGD = GD;
1289 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1290 // Complete destructors take a pointer to the complete object as a
1291 // parameter, thus don't need this adjustment.
1292 if (GD.getDtorType() == Dtor_Complete)
1295 // There's no Dtor_Base in vftable but it shares the this adjustment with
1296 // the deleting one, so look it up instead.
1297 LookupGD = GlobalDecl(DD, Dtor_Deleting);
1300 MicrosoftVTableContext::MethodVFTableLocation ML =
1301 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD);
1302 CharUnits Adjustment = ML.VFPtrOffset;
1304 // Normal virtual instance methods need to adjust from the vfptr that first
1305 // defined the virtual method to the virtual base subobject, but destructors
1306 // do not. The vector deleting destructor thunk applies this adjustment for
1308 if (isa<CXXDestructorDecl>(MD))
1309 Adjustment = CharUnits::Zero();
1312 const ASTRecordLayout &DerivedLayout =
1313 getContext().getASTRecordLayout(MD->getParent());
1314 Adjustment += DerivedLayout.getVBaseClassOffset(ML.VBase);
1320 Address MicrosoftCXXABI::adjustThisArgumentForVirtualFunctionCall(
1321 CodeGenFunction &CGF, GlobalDecl GD, Address This,
1324 // If the call of a virtual function is not virtual, we just have to
1325 // compensate for the adjustment the virtual function does in its prologue.
1326 CharUnits Adjustment = getVirtualFunctionPrologueThisAdjustment(GD);
1327 if (Adjustment.isZero())
1330 This = CGF.Builder.CreateElementBitCast(This, CGF.Int8Ty);
1331 assert(Adjustment.isPositive());
1332 return CGF.Builder.CreateConstByteGEP(This, Adjustment);
1335 GD = GD.getCanonicalDecl();
1336 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1338 GlobalDecl LookupGD = GD;
1339 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1340 // Complete dtors take a pointer to the complete object,
1341 // thus don't need adjustment.
1342 if (GD.getDtorType() == Dtor_Complete)
1345 // There's only Dtor_Deleting in vftable but it shares the this adjustment
1346 // with the base one, so look up the deleting one instead.
1347 LookupGD = GlobalDecl(DD, Dtor_Deleting);
1349 MicrosoftVTableContext::MethodVFTableLocation ML =
1350 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD);
1352 CharUnits StaticOffset = ML.VFPtrOffset;
1354 // Base destructors expect 'this' to point to the beginning of the base
1355 // subobject, not the first vfptr that happens to contain the virtual dtor.
1356 // However, we still need to apply the virtual base adjustment.
1357 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
1358 StaticOffset = CharUnits::Zero();
1360 Address Result = This;
1362 Result = CGF.Builder.CreateElementBitCast(Result, CGF.Int8Ty);
1364 const CXXRecordDecl *Derived = MD->getParent();
1365 const CXXRecordDecl *VBase = ML.VBase;
1366 llvm::Value *VBaseOffset =
1367 GetVirtualBaseClassOffset(CGF, Result, Derived, VBase);
1368 llvm::Value *VBasePtr =
1369 CGF.Builder.CreateInBoundsGEP(Result.getPointer(), VBaseOffset);
1370 CharUnits VBaseAlign =
1371 CGF.CGM.getVBaseAlignment(Result.getAlignment(), Derived, VBase);
1372 Result = Address(VBasePtr, VBaseAlign);
1374 if (!StaticOffset.isZero()) {
1375 assert(StaticOffset.isPositive());
1376 Result = CGF.Builder.CreateElementBitCast(Result, CGF.Int8Ty);
1378 // Non-virtual adjustment might result in a pointer outside the allocated
1379 // object, e.g. if the final overrider class is laid out after the virtual
1380 // base that declares a method in the most derived class.
1381 // FIXME: Update the code that emits this adjustment in thunks prologues.
1382 Result = CGF.Builder.CreateConstByteGEP(Result, StaticOffset);
1384 Result = CGF.Builder.CreateConstInBoundsByteGEP(Result, StaticOffset);
1390 void MicrosoftCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1392 FunctionArgList &Params) {
1393 ASTContext &Context = getContext();
1394 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
1395 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
1396 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
1397 ImplicitParamDecl *IsMostDerived
1398 = ImplicitParamDecl::Create(Context, nullptr,
1399 CGF.CurGD.getDecl()->getLocation(),
1400 &Context.Idents.get("is_most_derived"),
1402 // The 'most_derived' parameter goes second if the ctor is variadic and last
1403 // if it's not. Dtors can't be variadic.
1404 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
1405 if (FPT->isVariadic())
1406 Params.insert(Params.begin() + 1, IsMostDerived);
1408 Params.push_back(IsMostDerived);
1409 getStructorImplicitParamDecl(CGF) = IsMostDerived;
1410 } else if (isDeletingDtor(CGF.CurGD)) {
1411 ImplicitParamDecl *ShouldDelete
1412 = ImplicitParamDecl::Create(Context, nullptr,
1413 CGF.CurGD.getDecl()->getLocation(),
1414 &Context.Idents.get("should_call_delete"),
1416 Params.push_back(ShouldDelete);
1417 getStructorImplicitParamDecl(CGF) = ShouldDelete;
1421 llvm::Value *MicrosoftCXXABI::adjustThisParameterInVirtualFunctionPrologue(
1422 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) {
1423 // In this ABI, every virtual function takes a pointer to one of the
1424 // subobjects that first defines it as the 'this' parameter, rather than a
1425 // pointer to the final overrider subobject. Thus, we need to adjust it back
1426 // to the final overrider subobject before use.
1427 // See comments in the MicrosoftVFTableContext implementation for the details.
1428 CharUnits Adjustment = getVirtualFunctionPrologueThisAdjustment(GD);
1429 if (Adjustment.isZero())
1432 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
1433 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS),
1434 *thisTy = This->getType();
1436 This = CGF.Builder.CreateBitCast(This, charPtrTy);
1437 assert(Adjustment.isPositive());
1438 This = CGF.Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, This,
1439 -Adjustment.getQuantity());
1440 return CGF.Builder.CreateBitCast(This, thisTy);
1443 void MicrosoftCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
1446 /// If this is a function that the ABI specifies returns 'this', initialize
1447 /// the return slot to 'this' at the start of the function.
1449 /// Unlike the setting of return types, this is done within the ABI
1450 /// implementation instead of by clients of CGCXXABI because:
1451 /// 1) getThisValue is currently protected
1452 /// 2) in theory, an ABI could implement 'this' returns some other way;
1453 /// HasThisReturn only specifies a contract, not the implementation
1454 if (HasThisReturn(CGF.CurGD))
1455 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
1456 else if (hasMostDerivedReturn(CGF.CurGD))
1457 CGF.Builder.CreateStore(CGF.EmitCastToVoidPtr(getThisValue(CGF)),
1460 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
1461 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
1462 assert(getStructorImplicitParamDecl(CGF) &&
1463 "no implicit parameter for a constructor with virtual bases?");
1464 getStructorImplicitParamValue(CGF)
1465 = CGF.Builder.CreateLoad(
1466 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
1470 if (isDeletingDtor(CGF.CurGD)) {
1471 assert(getStructorImplicitParamDecl(CGF) &&
1472 "no implicit parameter for a deleting destructor?");
1473 getStructorImplicitParamValue(CGF)
1474 = CGF.Builder.CreateLoad(
1475 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
1476 "should_call_delete");
1480 unsigned MicrosoftCXXABI::addImplicitConstructorArgs(
1481 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1482 bool ForVirtualBase, bool Delegating, CallArgList &Args) {
1483 assert(Type == Ctor_Complete || Type == Ctor_Base);
1485 // Check if we need a 'most_derived' parameter.
1486 if (!D->getParent()->getNumVBases())
1489 // Add the 'most_derived' argument second if we are variadic or last if not.
1490 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
1491 llvm::Value *MostDerivedArg =
1492 llvm::ConstantInt::get(CGM.Int32Ty, Type == Ctor_Complete);
1493 RValue RV = RValue::get(MostDerivedArg);
1494 if (MostDerivedArg) {
1495 if (FPT->isVariadic())
1496 Args.insert(Args.begin() + 1,
1497 CallArg(RV, getContext().IntTy, /*needscopy=*/false));
1499 Args.add(RV, getContext().IntTy);
1502 return 1; // Added one arg.
1505 void MicrosoftCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1506 const CXXDestructorDecl *DD,
1507 CXXDtorType Type, bool ForVirtualBase,
1508 bool Delegating, Address This) {
1509 llvm::Value *Callee = CGM.getAddrOfCXXStructor(DD, getFromDtorType(Type));
1511 if (DD->isVirtual()) {
1512 assert(Type != CXXDtorType::Dtor_Deleting &&
1513 "The deleting destructor should only be called via a virtual call");
1514 This = adjustThisArgumentForVirtualFunctionCall(CGF, GlobalDecl(DD, Type),
1518 CGF.EmitCXXStructorCall(DD, Callee, ReturnValueSlot(), This.getPointer(),
1519 /*ImplicitParam=*/nullptr,
1520 /*ImplicitParamTy=*/QualType(), nullptr,
1521 getFromDtorType(Type));
1524 void MicrosoftCXXABI::emitVTableBitSetEntries(VPtrInfo *Info,
1525 const CXXRecordDecl *RD,
1526 llvm::GlobalVariable *VTable) {
1527 if (!getContext().getLangOpts().Sanitize.has(SanitizerKind::CFIVCall) &&
1528 !getContext().getLangOpts().Sanitize.has(SanitizerKind::CFINVCall) &&
1529 !getContext().getLangOpts().Sanitize.has(SanitizerKind::CFIDerivedCast) &&
1530 !getContext().getLangOpts().Sanitize.has(SanitizerKind::CFIUnrelatedCast))
1533 llvm::NamedMDNode *BitsetsMD =
1534 CGM.getModule().getOrInsertNamedMetadata("llvm.bitsets");
1536 // The location of the first virtual function pointer in the virtual table,
1537 // aka the "address point" on Itanium. This is at offset 0 if RTTI is
1538 // disabled, or sizeof(void*) if RTTI is enabled.
1539 CharUnits AddressPoint =
1540 getContext().getLangOpts().RTTIData
1541 ? getContext().toCharUnitsFromBits(
1542 getContext().getTargetInfo().getPointerWidth(0))
1543 : CharUnits::Zero();
1545 if (Info->PathToBaseWithVPtr.empty()) {
1546 if (!CGM.IsCFIBlacklistedRecord(RD))
1547 BitsetsMD->addOperand(
1548 CGM.CreateVTableBitSetEntry(VTable, AddressPoint, RD));
1552 // Add a bitset entry for the least derived base belonging to this vftable.
1553 if (!CGM.IsCFIBlacklistedRecord(Info->PathToBaseWithVPtr.back()))
1554 BitsetsMD->addOperand(CGM.CreateVTableBitSetEntry(
1555 VTable, AddressPoint, Info->PathToBaseWithVPtr.back()));
1557 // Add a bitset entry for each derived class that is laid out at the same
1558 // offset as the least derived base.
1559 for (unsigned I = Info->PathToBaseWithVPtr.size() - 1; I != 0; --I) {
1560 const CXXRecordDecl *DerivedRD = Info->PathToBaseWithVPtr[I - 1];
1561 const CXXRecordDecl *BaseRD = Info->PathToBaseWithVPtr[I];
1563 const ASTRecordLayout &Layout =
1564 getContext().getASTRecordLayout(DerivedRD);
1566 auto VBI = Layout.getVBaseOffsetsMap().find(BaseRD);
1567 if (VBI == Layout.getVBaseOffsetsMap().end())
1568 Offset = Layout.getBaseClassOffset(BaseRD);
1570 Offset = VBI->second.VBaseOffset;
1571 if (!Offset.isZero())
1573 if (!CGM.IsCFIBlacklistedRecord(DerivedRD))
1574 BitsetsMD->addOperand(
1575 CGM.CreateVTableBitSetEntry(VTable, AddressPoint, DerivedRD));
1578 // Finally do the same for the most derived class.
1579 if (Info->FullOffsetInMDC.isZero() && !CGM.IsCFIBlacklistedRecord(RD))
1580 BitsetsMD->addOperand(
1581 CGM.CreateVTableBitSetEntry(VTable, AddressPoint, RD));
1584 void MicrosoftCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1585 const CXXRecordDecl *RD) {
1586 MicrosoftVTableContext &VFTContext = CGM.getMicrosoftVTableContext();
1587 const VPtrInfoVector &VFPtrs = VFTContext.getVFPtrOffsets(RD);
1589 for (VPtrInfo *Info : VFPtrs) {
1590 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, Info->FullOffsetInMDC);
1591 if (VTable->hasInitializer())
1594 llvm::Constant *RTTI = getContext().getLangOpts().RTTIData
1595 ? getMSCompleteObjectLocator(RD, Info)
1598 const VTableLayout &VTLayout =
1599 VFTContext.getVFTableLayout(RD, Info->FullOffsetInMDC);
1600 llvm::Constant *Init = CGVT.CreateVTableInitializer(
1601 RD, VTLayout.vtable_component_begin(),
1602 VTLayout.getNumVTableComponents(), VTLayout.vtable_thunk_begin(),
1603 VTLayout.getNumVTableThunks(), RTTI);
1605 VTable->setInitializer(Init);
1607 emitVTableBitSetEntries(Info, RD, VTable);
1611 bool MicrosoftCXXABI::isVirtualOffsetNeededForVTableField(
1612 CodeGenFunction &CGF, CodeGenFunction::VPtr Vptr) {
1613 return Vptr.NearestVBase != nullptr;
1616 llvm::Value *MicrosoftCXXABI::getVTableAddressPointInStructor(
1617 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1618 const CXXRecordDecl *NearestVBase) {
1619 llvm::Constant *VTableAddressPoint = getVTableAddressPoint(Base, VTableClass);
1620 if (!VTableAddressPoint) {
1621 assert(Base.getBase()->getNumVBases() &&
1622 !getContext().getASTRecordLayout(Base.getBase()).hasOwnVFPtr());
1624 return VTableAddressPoint;
1627 static void mangleVFTableName(MicrosoftMangleContext &MangleContext,
1628 const CXXRecordDecl *RD, const VPtrInfo *VFPtr,
1629 SmallString<256> &Name) {
1630 llvm::raw_svector_ostream Out(Name);
1631 MangleContext.mangleCXXVFTable(RD, VFPtr->MangledPath, Out);
1635 MicrosoftCXXABI::getVTableAddressPoint(BaseSubobject Base,
1636 const CXXRecordDecl *VTableClass) {
1637 (void)getAddrOfVTable(VTableClass, Base.getBaseOffset());
1638 VFTableIdTy ID(VTableClass, Base.getBaseOffset());
1639 return VFTablesMap[ID];
1642 llvm::Constant *MicrosoftCXXABI::getVTableAddressPointForConstExpr(
1643 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1644 llvm::Constant *VFTable = getVTableAddressPoint(Base, VTableClass);
1645 assert(VFTable && "Couldn't find a vftable for the given base?");
1649 llvm::GlobalVariable *MicrosoftCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1650 CharUnits VPtrOffset) {
1651 // getAddrOfVTable may return 0 if asked to get an address of a vtable which
1652 // shouldn't be used in the given record type. We want to cache this result in
1653 // VFTablesMap, thus a simple zero check is not sufficient.
1655 VFTableIdTy ID(RD, VPtrOffset);
1656 VTablesMapTy::iterator I;
1658 std::tie(I, Inserted) = VTablesMap.insert(std::make_pair(ID, nullptr));
1662 llvm::GlobalVariable *&VTable = I->second;
1664 MicrosoftVTableContext &VTContext = CGM.getMicrosoftVTableContext();
1665 const VPtrInfoVector &VFPtrs = VTContext.getVFPtrOffsets(RD);
1667 if (DeferredVFTables.insert(RD).second) {
1668 // We haven't processed this record type before.
1669 // Queue up this v-table for possible deferred emission.
1670 CGM.addDeferredVTable(RD);
1673 // Create all the vftables at once in order to make sure each vftable has
1674 // a unique mangled name.
1675 llvm::StringSet<> ObservedMangledNames;
1676 for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) {
1677 SmallString<256> Name;
1678 mangleVFTableName(getMangleContext(), RD, VFPtrs[J], Name);
1679 if (!ObservedMangledNames.insert(Name.str()).second)
1680 llvm_unreachable("Already saw this mangling before?");
1685 VPtrInfo *const *VFPtrI =
1686 std::find_if(VFPtrs.begin(), VFPtrs.end(), [&](VPtrInfo *VPI) {
1687 return VPI->FullOffsetInMDC == VPtrOffset;
1689 if (VFPtrI == VFPtrs.end()) {
1690 VFTablesMap[ID] = nullptr;
1693 VPtrInfo *VFPtr = *VFPtrI;
1695 SmallString<256> VFTableName;
1696 mangleVFTableName(getMangleContext(), RD, VFPtr, VFTableName);
1698 llvm::GlobalValue::LinkageTypes VFTableLinkage = CGM.getVTableLinkage(RD);
1699 bool VFTableComesFromAnotherTU =
1700 llvm::GlobalValue::isAvailableExternallyLinkage(VFTableLinkage) ||
1701 llvm::GlobalValue::isExternalLinkage(VFTableLinkage);
1702 bool VTableAliasIsRequred =
1703 !VFTableComesFromAnotherTU && getContext().getLangOpts().RTTIData;
1705 if (llvm::GlobalValue *VFTable =
1706 CGM.getModule().getNamedGlobal(VFTableName)) {
1707 VFTablesMap[ID] = VFTable;
1708 VTable = VTableAliasIsRequred
1709 ? cast<llvm::GlobalVariable>(
1710 cast<llvm::GlobalAlias>(VFTable)->getBaseObject())
1711 : cast<llvm::GlobalVariable>(VFTable);
1715 uint64_t NumVTableSlots =
1716 VTContext.getVFTableLayout(RD, VFPtr->FullOffsetInMDC)
1717 .getNumVTableComponents();
1718 llvm::GlobalValue::LinkageTypes VTableLinkage =
1719 VTableAliasIsRequred ? llvm::GlobalValue::PrivateLinkage : VFTableLinkage;
1721 StringRef VTableName = VTableAliasIsRequred ? StringRef() : VFTableName.str();
1723 llvm::ArrayType *VTableType =
1724 llvm::ArrayType::get(CGM.Int8PtrTy, NumVTableSlots);
1726 // Create a backing variable for the contents of VTable. The VTable may
1727 // or may not include space for a pointer to RTTI data.
1728 llvm::GlobalValue *VFTable;
1729 VTable = new llvm::GlobalVariable(CGM.getModule(), VTableType,
1730 /*isConstant=*/true, VTableLinkage,
1731 /*Initializer=*/nullptr, VTableName);
1732 VTable->setUnnamedAddr(true);
1734 llvm::Comdat *C = nullptr;
1735 if (!VFTableComesFromAnotherTU &&
1736 (llvm::GlobalValue::isWeakForLinker(VFTableLinkage) ||
1737 (llvm::GlobalValue::isLocalLinkage(VFTableLinkage) &&
1738 VTableAliasIsRequred)))
1739 C = CGM.getModule().getOrInsertComdat(VFTableName.str());
1741 // Only insert a pointer into the VFTable for RTTI data if we are not
1742 // importing it. We never reference the RTTI data directly so there is no
1743 // need to make room for it.
1744 if (VTableAliasIsRequred) {
1745 llvm::Value *GEPIndices[] = {llvm::ConstantInt::get(CGM.IntTy, 0),
1746 llvm::ConstantInt::get(CGM.IntTy, 1)};
1747 // Create a GEP which points just after the first entry in the VFTable,
1748 // this should be the location of the first virtual method.
1749 llvm::Constant *VTableGEP = llvm::ConstantExpr::getInBoundsGetElementPtr(
1750 VTable->getValueType(), VTable, GEPIndices);
1751 if (llvm::GlobalValue::isWeakForLinker(VFTableLinkage)) {
1752 VFTableLinkage = llvm::GlobalValue::ExternalLinkage;
1754 C->setSelectionKind(llvm::Comdat::Largest);
1756 VFTable = llvm::GlobalAlias::create(CGM.Int8PtrTy,
1757 /*AddressSpace=*/0, VFTableLinkage,
1758 VFTableName.str(), VTableGEP,
1760 VFTable->setUnnamedAddr(true);
1762 // We don't need a GlobalAlias to be a symbol for the VTable if we won't
1763 // be referencing any RTTI data.
1764 // The GlobalVariable will end up being an appropriate definition of the
1769 VTable->setComdat(C);
1771 if (RD->hasAttr<DLLImportAttr>())
1772 VFTable->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1773 else if (RD->hasAttr<DLLExportAttr>())
1774 VFTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1776 VFTablesMap[ID] = VFTable;
1780 // Compute the identity of the most derived class whose virtual table is located
1781 // at the given offset into RD.
1782 static const CXXRecordDecl *getClassAtVTableLocation(ASTContext &Ctx,
1783 const CXXRecordDecl *RD,
1785 if (Offset.isZero())
1788 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(RD);
1789 const CXXRecordDecl *MaxBase = nullptr;
1790 CharUnits MaxBaseOffset;
1791 for (auto &&B : RD->bases()) {
1792 const CXXRecordDecl *Base = B.getType()->getAsCXXRecordDecl();
1793 CharUnits BaseOffset = Layout.getBaseClassOffset(Base);
1794 if (BaseOffset <= Offset && BaseOffset >= MaxBaseOffset) {
1796 MaxBaseOffset = BaseOffset;
1799 for (auto &&B : RD->vbases()) {
1800 const CXXRecordDecl *Base = B.getType()->getAsCXXRecordDecl();
1801 CharUnits BaseOffset = Layout.getVBaseClassOffset(Base);
1802 if (BaseOffset <= Offset && BaseOffset >= MaxBaseOffset) {
1804 MaxBaseOffset = BaseOffset;
1808 return getClassAtVTableLocation(Ctx, MaxBase, Offset - MaxBaseOffset);
1811 // Compute the identity of the most derived class whose virtual table is located
1812 // at the MethodVFTableLocation ML.
1813 static const CXXRecordDecl *
1814 getClassAtVTableLocation(ASTContext &Ctx, GlobalDecl GD,
1815 MicrosoftVTableContext::MethodVFTableLocation &ML) {
1816 const CXXRecordDecl *RD = ML.VBase;
1818 RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
1820 return getClassAtVTableLocation(Ctx, RD, ML.VFPtrOffset);
1823 llvm::Value *MicrosoftCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1827 SourceLocation Loc) {
1828 GD = GD.getCanonicalDecl();
1829 CGBuilderTy &Builder = CGF.Builder;
1831 Ty = Ty->getPointerTo()->getPointerTo();
1833 adjustThisArgumentForVirtualFunctionCall(CGF, GD, This, true);
1835 auto *MethodDecl = cast<CXXMethodDecl>(GD.getDecl());
1836 llvm::Value *VTable = CGF.GetVTablePtr(VPtr, Ty, MethodDecl->getParent());
1838 MicrosoftVTableContext::MethodVFTableLocation ML =
1839 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD);
1840 if (CGF.SanOpts.has(SanitizerKind::CFIVCall))
1841 CGF.EmitVTablePtrCheck(getClassAtVTableLocation(getContext(), GD, ML),
1842 VTable, CodeGenFunction::CFITCK_VCall, Loc);
1844 llvm::Value *VFuncPtr =
1845 Builder.CreateConstInBoundsGEP1_64(VTable, ML.Index, "vfn");
1846 return Builder.CreateAlignedLoad(VFuncPtr, CGF.getPointerAlign());
1849 llvm::Value *MicrosoftCXXABI::EmitVirtualDestructorCall(
1850 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
1851 Address This, const CXXMemberCallExpr *CE) {
1852 assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
1853 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1855 // We have only one destructor in the vftable but can get both behaviors
1856 // by passing an implicit int parameter.
1857 GlobalDecl GD(Dtor, Dtor_Deleting);
1858 const CGFunctionInfo *FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
1859 Dtor, StructorType::Deleting);
1860 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
1861 llvm::Value *Callee = getVirtualFunctionPointer(
1862 CGF, GD, This, Ty, CE ? CE->getLocStart() : SourceLocation());
1864 ASTContext &Context = getContext();
1865 llvm::Value *ImplicitParam = llvm::ConstantInt::get(
1866 llvm::IntegerType::getInt32Ty(CGF.getLLVMContext()),
1867 DtorType == Dtor_Deleting);
1869 This = adjustThisArgumentForVirtualFunctionCall(CGF, GD, This, true);
1870 RValue RV = CGF.EmitCXXStructorCall(Dtor, Callee, ReturnValueSlot(),
1872 ImplicitParam, Context.IntTy, CE,
1873 StructorType::Deleting);
1874 return RV.getScalarVal();
1877 const VBTableGlobals &
1878 MicrosoftCXXABI::enumerateVBTables(const CXXRecordDecl *RD) {
1879 // At this layer, we can key the cache off of a single class, which is much
1880 // easier than caching each vbtable individually.
1881 llvm::DenseMap<const CXXRecordDecl*, VBTableGlobals>::iterator Entry;
1883 std::tie(Entry, Added) =
1884 VBTablesMap.insert(std::make_pair(RD, VBTableGlobals()));
1885 VBTableGlobals &VBGlobals = Entry->second;
1889 MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext();
1890 VBGlobals.VBTables = &Context.enumerateVBTables(RD);
1892 // Cache the globals for all vbtables so we don't have to recompute the
1894 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
1895 for (VPtrInfoVector::const_iterator I = VBGlobals.VBTables->begin(),
1896 E = VBGlobals.VBTables->end();
1898 VBGlobals.Globals.push_back(getAddrOfVBTable(**I, RD, Linkage));
1904 llvm::Function *MicrosoftCXXABI::EmitVirtualMemPtrThunk(
1905 const CXXMethodDecl *MD,
1906 const MicrosoftVTableContext::MethodVFTableLocation &ML) {
1907 assert(!isa<CXXConstructorDecl>(MD) && !isa<CXXDestructorDecl>(MD) &&
1908 "can't form pointers to ctors or virtual dtors");
1910 // Calculate the mangled name.
1911 SmallString<256> ThunkName;
1912 llvm::raw_svector_ostream Out(ThunkName);
1913 getMangleContext().mangleVirtualMemPtrThunk(MD, Out);
1915 // If the thunk has been generated previously, just return it.
1916 if (llvm::GlobalValue *GV = CGM.getModule().getNamedValue(ThunkName))
1917 return cast<llvm::Function>(GV);
1919 // Create the llvm::Function.
1920 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeMSMemberPointerThunk(MD);
1921 llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo);
1922 llvm::Function *ThunkFn =
1923 llvm::Function::Create(ThunkTy, llvm::Function::ExternalLinkage,
1924 ThunkName.str(), &CGM.getModule());
1925 assert(ThunkFn->getName() == ThunkName && "name was uniqued!");
1927 ThunkFn->setLinkage(MD->isExternallyVisible()
1928 ? llvm::GlobalValue::LinkOnceODRLinkage
1929 : llvm::GlobalValue::InternalLinkage);
1930 if (MD->isExternallyVisible())
1931 ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));
1933 CGM.SetLLVMFunctionAttributes(MD, FnInfo, ThunkFn);
1934 CGM.SetLLVMFunctionAttributesForDefinition(MD, ThunkFn);
1936 // Add the "thunk" attribute so that LLVM knows that the return type is
1937 // meaningless. These thunks can be used to call functions with differing
1938 // return types, and the caller is required to cast the prototype
1939 // appropriately to extract the correct value.
1940 ThunkFn->addFnAttr("thunk");
1942 // These thunks can be compared, so they are not unnamed.
1943 ThunkFn->setUnnamedAddr(false);
1946 CodeGenFunction CGF(CGM);
1947 CGF.CurGD = GlobalDecl(MD);
1948 CGF.CurFuncIsThunk = true;
1950 // Build FunctionArgs, but only include the implicit 'this' parameter
1952 FunctionArgList FunctionArgs;
1953 buildThisParam(CGF, FunctionArgs);
1955 // Start defining the function.
1956 CGF.StartFunction(GlobalDecl(), FnInfo.getReturnType(), ThunkFn, FnInfo,
1957 FunctionArgs, MD->getLocation(), SourceLocation());
1960 // Load the vfptr and then callee from the vftable. The callee should have
1961 // adjusted 'this' so that the vfptr is at offset zero.
1962 llvm::Value *VTable = CGF.GetVTablePtr(
1963 getThisAddress(CGF), ThunkTy->getPointerTo()->getPointerTo(), MD->getParent());
1965 llvm::Value *VFuncPtr =
1966 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, ML.Index, "vfn");
1967 llvm::Value *Callee =
1968 CGF.Builder.CreateAlignedLoad(VFuncPtr, CGF.getPointerAlign());
1970 CGF.EmitMustTailThunk(MD, getThisValue(CGF), Callee);
1975 void MicrosoftCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
1976 const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
1977 for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) {
1978 const VPtrInfo *VBT = (*VBGlobals.VBTables)[I];
1979 llvm::GlobalVariable *GV = VBGlobals.Globals[I];
1980 if (GV->isDeclaration())
1981 emitVBTableDefinition(*VBT, RD, GV);
1985 llvm::GlobalVariable *
1986 MicrosoftCXXABI::getAddrOfVBTable(const VPtrInfo &VBT, const CXXRecordDecl *RD,
1987 llvm::GlobalVariable::LinkageTypes Linkage) {
1988 SmallString<256> OutName;
1989 llvm::raw_svector_ostream Out(OutName);
1990 getMangleContext().mangleCXXVBTable(RD, VBT.MangledPath, Out);
1991 StringRef Name = OutName.str();
1993 llvm::ArrayType *VBTableType =
1994 llvm::ArrayType::get(CGM.IntTy, 1 + VBT.ReusingBase->getNumVBases());
1996 assert(!CGM.getModule().getNamedGlobal(Name) &&
1997 "vbtable with this name already exists: mangling bug?");
1998 llvm::GlobalVariable *GV =
1999 CGM.CreateOrReplaceCXXRuntimeVariable(Name, VBTableType, Linkage);
2000 GV->setUnnamedAddr(true);
2002 if (RD->hasAttr<DLLImportAttr>())
2003 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2004 else if (RD->hasAttr<DLLExportAttr>())
2005 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
2007 if (!GV->hasExternalLinkage())
2008 emitVBTableDefinition(VBT, RD, GV);
2013 void MicrosoftCXXABI::emitVBTableDefinition(const VPtrInfo &VBT,
2014 const CXXRecordDecl *RD,
2015 llvm::GlobalVariable *GV) const {
2016 const CXXRecordDecl *ReusingBase = VBT.ReusingBase;
2018 assert(RD->getNumVBases() && ReusingBase->getNumVBases() &&
2019 "should only emit vbtables for classes with vbtables");
2021 const ASTRecordLayout &BaseLayout =
2022 getContext().getASTRecordLayout(VBT.BaseWithVPtr);
2023 const ASTRecordLayout &DerivedLayout = getContext().getASTRecordLayout(RD);
2025 SmallVector<llvm::Constant *, 4> Offsets(1 + ReusingBase->getNumVBases(),
2028 // The offset from ReusingBase's vbptr to itself always leads.
2029 CharUnits VBPtrOffset = BaseLayout.getVBPtrOffset();
2030 Offsets[0] = llvm::ConstantInt::get(CGM.IntTy, -VBPtrOffset.getQuantity());
2032 MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext();
2033 for (const auto &I : ReusingBase->vbases()) {
2034 const CXXRecordDecl *VBase = I.getType()->getAsCXXRecordDecl();
2035 CharUnits Offset = DerivedLayout.getVBaseClassOffset(VBase);
2036 assert(!Offset.isNegative());
2038 // Make it relative to the subobject vbptr.
2039 CharUnits CompleteVBPtrOffset = VBT.NonVirtualOffset + VBPtrOffset;
2040 if (VBT.getVBaseWithVPtr())
2041 CompleteVBPtrOffset +=
2042 DerivedLayout.getVBaseClassOffset(VBT.getVBaseWithVPtr());
2043 Offset -= CompleteVBPtrOffset;
2045 unsigned VBIndex = Context.getVBTableIndex(ReusingBase, VBase);
2046 assert(Offsets[VBIndex] == nullptr && "The same vbindex seen twice?");
2047 Offsets[VBIndex] = llvm::ConstantInt::get(CGM.IntTy, Offset.getQuantity());
2050 assert(Offsets.size() ==
2051 cast<llvm::ArrayType>(cast<llvm::PointerType>(GV->getType())
2052 ->getElementType())->getNumElements());
2053 llvm::ArrayType *VBTableType =
2054 llvm::ArrayType::get(CGM.IntTy, Offsets.size());
2055 llvm::Constant *Init = llvm::ConstantArray::get(VBTableType, Offsets);
2056 GV->setInitializer(Init);
2059 llvm::Value *MicrosoftCXXABI::performThisAdjustment(CodeGenFunction &CGF,
2061 const ThisAdjustment &TA) {
2063 return This.getPointer();
2065 This = CGF.Builder.CreateElementBitCast(This, CGF.Int8Ty);
2068 if (TA.Virtual.isEmpty()) {
2069 V = This.getPointer();
2071 assert(TA.Virtual.Microsoft.VtordispOffset < 0);
2072 // Adjust the this argument based on the vtordisp value.
2073 Address VtorDispPtr =
2074 CGF.Builder.CreateConstInBoundsByteGEP(This,
2075 CharUnits::fromQuantity(TA.Virtual.Microsoft.VtordispOffset));
2076 VtorDispPtr = CGF.Builder.CreateElementBitCast(VtorDispPtr, CGF.Int32Ty);
2077 llvm::Value *VtorDisp = CGF.Builder.CreateLoad(VtorDispPtr, "vtordisp");
2078 V = CGF.Builder.CreateGEP(This.getPointer(),
2079 CGF.Builder.CreateNeg(VtorDisp));
2081 // Unfortunately, having applied the vtordisp means that we no
2082 // longer really have a known alignment for the vbptr step.
2083 // We'll assume the vbptr is pointer-aligned.
2085 if (TA.Virtual.Microsoft.VBPtrOffset) {
2086 // If the final overrider is defined in a virtual base other than the one
2087 // that holds the vfptr, we have to use a vtordispex thunk which looks up
2088 // the vbtable of the derived class.
2089 assert(TA.Virtual.Microsoft.VBPtrOffset > 0);
2090 assert(TA.Virtual.Microsoft.VBOffsetOffset >= 0);
2092 llvm::Value *VBaseOffset =
2093 GetVBaseOffsetFromVBPtr(CGF, Address(V, CGF.getPointerAlign()),
2094 -TA.Virtual.Microsoft.VBPtrOffset,
2095 TA.Virtual.Microsoft.VBOffsetOffset, &VBPtr);
2096 V = CGF.Builder.CreateInBoundsGEP(VBPtr, VBaseOffset);
2100 if (TA.NonVirtual) {
2101 // Non-virtual adjustment might result in a pointer outside the allocated
2102 // object, e.g. if the final overrider class is laid out after the virtual
2103 // base that declares a method in the most derived class.
2104 V = CGF.Builder.CreateConstGEP1_32(V, TA.NonVirtual);
2107 // Don't need to bitcast back, the call CodeGen will handle this.
2112 MicrosoftCXXABI::performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
2113 const ReturnAdjustment &RA) {
2115 return Ret.getPointer();
2117 auto OrigTy = Ret.getType();
2118 Ret = CGF.Builder.CreateElementBitCast(Ret, CGF.Int8Ty);
2120 llvm::Value *V = Ret.getPointer();
2121 if (RA.Virtual.Microsoft.VBIndex) {
2122 assert(RA.Virtual.Microsoft.VBIndex > 0);
2123 int32_t IntSize = CGF.getIntSize().getQuantity();
2125 llvm::Value *VBaseOffset =
2126 GetVBaseOffsetFromVBPtr(CGF, Ret, RA.Virtual.Microsoft.VBPtrOffset,
2127 IntSize * RA.Virtual.Microsoft.VBIndex, &VBPtr);
2128 V = CGF.Builder.CreateInBoundsGEP(VBPtr, VBaseOffset);
2132 V = CGF.Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, V, RA.NonVirtual);
2134 // Cast back to the original type.
2135 return CGF.Builder.CreateBitCast(V, OrigTy);
2138 bool MicrosoftCXXABI::requiresArrayCookie(const CXXDeleteExpr *expr,
2139 QualType elementType) {
2140 // Microsoft seems to completely ignore the possibility of a
2141 // two-argument usual deallocation function.
2142 return elementType.isDestructedType();
2145 bool MicrosoftCXXABI::requiresArrayCookie(const CXXNewExpr *expr) {
2146 // Microsoft seems to completely ignore the possibility of a
2147 // two-argument usual deallocation function.
2148 return expr->getAllocatedType().isDestructedType();
2151 CharUnits MicrosoftCXXABI::getArrayCookieSizeImpl(QualType type) {
2152 // The array cookie is always a size_t; we then pad that out to the
2153 // alignment of the element type.
2154 ASTContext &Ctx = getContext();
2155 return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()),
2156 Ctx.getTypeAlignInChars(type));
2159 llvm::Value *MicrosoftCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
2161 CharUnits cookieSize) {
2162 Address numElementsPtr =
2163 CGF.Builder.CreateElementBitCast(allocPtr, CGF.SizeTy);
2164 return CGF.Builder.CreateLoad(numElementsPtr);
2167 Address MicrosoftCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
2169 llvm::Value *numElements,
2170 const CXXNewExpr *expr,
2171 QualType elementType) {
2172 assert(requiresArrayCookie(expr));
2174 // The size of the cookie.
2175 CharUnits cookieSize = getArrayCookieSizeImpl(elementType);
2177 // Compute an offset to the cookie.
2178 Address cookiePtr = newPtr;
2180 // Write the number of elements into the appropriate slot.
2181 Address numElementsPtr
2182 = CGF.Builder.CreateElementBitCast(cookiePtr, CGF.SizeTy);
2183 CGF.Builder.CreateStore(numElements, numElementsPtr);
2185 // Finally, compute a pointer to the actual data buffer by skipping
2186 // over the cookie completely.
2187 return CGF.Builder.CreateConstInBoundsByteGEP(newPtr, cookieSize);
2190 static void emitGlobalDtorWithTLRegDtor(CodeGenFunction &CGF, const VarDecl &VD,
2191 llvm::Constant *Dtor,
2192 llvm::Constant *Addr) {
2193 // Create a function which calls the destructor.
2194 llvm::Constant *DtorStub = CGF.createAtExitStub(VD, Dtor, Addr);
2196 // extern "C" int __tlregdtor(void (*f)(void));
2197 llvm::FunctionType *TLRegDtorTy = llvm::FunctionType::get(
2198 CGF.IntTy, DtorStub->getType(), /*IsVarArg=*/false);
2200 llvm::Constant *TLRegDtor =
2201 CGF.CGM.CreateRuntimeFunction(TLRegDtorTy, "__tlregdtor");
2202 if (llvm::Function *TLRegDtorFn = dyn_cast<llvm::Function>(TLRegDtor))
2203 TLRegDtorFn->setDoesNotThrow();
2205 CGF.EmitNounwindRuntimeCall(TLRegDtor, DtorStub);
2208 void MicrosoftCXXABI::registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
2209 llvm::Constant *Dtor,
2210 llvm::Constant *Addr) {
2212 return emitGlobalDtorWithTLRegDtor(CGF, D, Dtor, Addr);
2214 // The default behavior is to use atexit.
2215 CGF.registerGlobalDtorWithAtExit(D, Dtor, Addr);
2218 void MicrosoftCXXABI::EmitThreadLocalInitFuncs(
2220 ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *>>
2222 ArrayRef<llvm::Function *> CXXThreadLocalInits,
2223 ArrayRef<llvm::GlobalVariable *> CXXThreadLocalInitVars) {
2224 // This will create a GV in the .CRT$XDU section. It will point to our
2225 // initialization function. The CRT will call all of these function
2226 // pointers at start-up time and, eventually, at thread-creation time.
2227 auto AddToXDU = [&CGM](llvm::Function *InitFunc) {
2228 llvm::GlobalVariable *InitFuncPtr = new llvm::GlobalVariable(
2229 CGM.getModule(), InitFunc->getType(), /*IsConstant=*/true,
2230 llvm::GlobalVariable::InternalLinkage, InitFunc,
2231 Twine(InitFunc->getName(), "$initializer$"));
2232 InitFuncPtr->setSection(".CRT$XDU");
2233 // This variable has discardable linkage, we have to add it to @llvm.used to
2234 // ensure it won't get discarded.
2235 CGM.addUsedGlobal(InitFuncPtr);
2239 std::vector<llvm::Function *> NonComdatInits;
2240 for (size_t I = 0, E = CXXThreadLocalInitVars.size(); I != E; ++I) {
2241 llvm::GlobalVariable *GV = CXXThreadLocalInitVars[I];
2242 llvm::Function *F = CXXThreadLocalInits[I];
2244 // If the GV is already in a comdat group, then we have to join it.
2245 if (llvm::Comdat *C = GV->getComdat())
2246 AddToXDU(F)->setComdat(C);
2248 NonComdatInits.push_back(F);
2251 if (!NonComdatInits.empty()) {
2252 llvm::FunctionType *FTy =
2253 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
2254 llvm::Function *InitFunc = CGM.CreateGlobalInitOrDestructFunction(
2255 FTy, "__tls_init", SourceLocation(),
2257 CodeGenFunction(CGM).GenerateCXXGlobalInitFunc(InitFunc, NonComdatInits);
2263 LValue MicrosoftCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
2265 QualType LValType) {
2266 CGF.CGM.ErrorUnsupported(VD, "thread wrappers");
2270 static ConstantAddress getInitThreadEpochPtr(CodeGenModule &CGM) {
2271 StringRef VarName("_Init_thread_epoch");
2272 CharUnits Align = CGM.getIntAlign();
2273 if (auto *GV = CGM.getModule().getNamedGlobal(VarName))
2274 return ConstantAddress(GV, Align);
2275 auto *GV = new llvm::GlobalVariable(
2276 CGM.getModule(), CGM.IntTy,
2277 /*Constant=*/false, llvm::GlobalVariable::ExternalLinkage,
2278 /*Initializer=*/nullptr, VarName,
2279 /*InsertBefore=*/nullptr, llvm::GlobalVariable::GeneralDynamicTLSModel);
2280 GV->setAlignment(Align.getQuantity());
2281 return ConstantAddress(GV, Align);
2284 static llvm::Constant *getInitThreadHeaderFn(CodeGenModule &CGM) {
2285 llvm::FunctionType *FTy =
2286 llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
2287 CGM.IntTy->getPointerTo(), /*isVarArg=*/false);
2288 return CGM.CreateRuntimeFunction(
2289 FTy, "_Init_thread_header",
2290 llvm::AttributeSet::get(CGM.getLLVMContext(),
2291 llvm::AttributeSet::FunctionIndex,
2292 llvm::Attribute::NoUnwind));
2295 static llvm::Constant *getInitThreadFooterFn(CodeGenModule &CGM) {
2296 llvm::FunctionType *FTy =
2297 llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
2298 CGM.IntTy->getPointerTo(), /*isVarArg=*/false);
2299 return CGM.CreateRuntimeFunction(
2300 FTy, "_Init_thread_footer",
2301 llvm::AttributeSet::get(CGM.getLLVMContext(),
2302 llvm::AttributeSet::FunctionIndex,
2303 llvm::Attribute::NoUnwind));
2306 static llvm::Constant *getInitThreadAbortFn(CodeGenModule &CGM) {
2307 llvm::FunctionType *FTy =
2308 llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
2309 CGM.IntTy->getPointerTo(), /*isVarArg=*/false);
2310 return CGM.CreateRuntimeFunction(
2311 FTy, "_Init_thread_abort",
2312 llvm::AttributeSet::get(CGM.getLLVMContext(),
2313 llvm::AttributeSet::FunctionIndex,
2314 llvm::Attribute::NoUnwind));
2318 struct ResetGuardBit final : EHScopeStack::Cleanup {
2321 ResetGuardBit(Address Guard, unsigned GuardNum)
2322 : Guard(Guard), GuardNum(GuardNum) {}
2324 void Emit(CodeGenFunction &CGF, Flags flags) override {
2325 // Reset the bit in the mask so that the static variable may be
2327 CGBuilderTy &Builder = CGF.Builder;
2328 llvm::LoadInst *LI = Builder.CreateLoad(Guard);
2329 llvm::ConstantInt *Mask =
2330 llvm::ConstantInt::get(CGF.IntTy, ~(1U << GuardNum));
2331 Builder.CreateStore(Builder.CreateAnd(LI, Mask), Guard);
2335 struct CallInitThreadAbort final : EHScopeStack::Cleanup {
2337 CallInitThreadAbort(Address Guard) : Guard(Guard.getPointer()) {}
2339 void Emit(CodeGenFunction &CGF, Flags flags) override {
2340 // Calling _Init_thread_abort will reset the guard's state.
2341 CGF.EmitNounwindRuntimeCall(getInitThreadAbortFn(CGF.CGM), Guard);
2346 void MicrosoftCXXABI::EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
2347 llvm::GlobalVariable *GV,
2349 // MSVC only uses guards for static locals.
2350 if (!D.isStaticLocal()) {
2351 assert(GV->hasWeakLinkage() || GV->hasLinkOnceLinkage());
2352 // GlobalOpt is allowed to discard the initializer, so use linkonce_odr.
2353 llvm::Function *F = CGF.CurFn;
2354 F->setLinkage(llvm::GlobalValue::LinkOnceODRLinkage);
2355 F->setComdat(CGM.getModule().getOrInsertComdat(F->getName()));
2356 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
2360 bool ThreadlocalStatic = D.getTLSKind();
2361 bool ThreadsafeStatic = getContext().getLangOpts().ThreadsafeStatics;
2363 // Thread-safe static variables which aren't thread-specific have a
2364 // per-variable guard.
2365 bool HasPerVariableGuard = ThreadsafeStatic && !ThreadlocalStatic;
2367 CGBuilderTy &Builder = CGF.Builder;
2368 llvm::IntegerType *GuardTy = CGF.Int32Ty;
2369 llvm::ConstantInt *Zero = llvm::ConstantInt::get(GuardTy, 0);
2370 CharUnits GuardAlign = CharUnits::fromQuantity(4);
2372 // Get the guard variable for this function if we have one already.
2373 GuardInfo *GI = nullptr;
2374 if (ThreadlocalStatic)
2375 GI = &ThreadLocalGuardVariableMap[D.getDeclContext()];
2376 else if (!ThreadsafeStatic)
2377 GI = &GuardVariableMap[D.getDeclContext()];
2379 llvm::GlobalVariable *GuardVar = GI ? GI->Guard : nullptr;
2381 if (D.isExternallyVisible()) {
2382 // Externally visible variables have to be numbered in Sema to properly
2383 // handle unreachable VarDecls.
2384 GuardNum = getContext().getStaticLocalNumber(&D);
2385 assert(GuardNum > 0);
2387 } else if (HasPerVariableGuard) {
2388 GuardNum = ThreadSafeGuardNumMap[D.getDeclContext()]++;
2390 // Non-externally visible variables are numbered here in CodeGen.
2391 GuardNum = GI->BitIndex++;
2394 if (!HasPerVariableGuard && GuardNum >= 32) {
2395 if (D.isExternallyVisible())
2396 ErrorUnsupportedABI(CGF, "more than 32 guarded initializations");
2402 // Mangle the name for the guard.
2403 SmallString<256> GuardName;
2405 llvm::raw_svector_ostream Out(GuardName);
2406 if (HasPerVariableGuard)
2407 getMangleContext().mangleThreadSafeStaticGuardVariable(&D, GuardNum,
2410 getMangleContext().mangleStaticGuardVariable(&D, Out);
2413 // Create the guard variable with a zero-initializer. Just absorb linkage,
2414 // visibility and dll storage class from the guarded variable.
2416 new llvm::GlobalVariable(CGM.getModule(), GuardTy, /*isConstant=*/false,
2417 GV->getLinkage(), Zero, GuardName.str());
2418 GuardVar->setVisibility(GV->getVisibility());
2419 GuardVar->setDLLStorageClass(GV->getDLLStorageClass());
2420 GuardVar->setAlignment(GuardAlign.getQuantity());
2421 if (GuardVar->isWeakForLinker())
2422 GuardVar->setComdat(
2423 CGM.getModule().getOrInsertComdat(GuardVar->getName()));
2425 GuardVar->setThreadLocal(true);
2426 if (GI && !HasPerVariableGuard)
2427 GI->Guard = GuardVar;
2430 ConstantAddress GuardAddr(GuardVar, GuardAlign);
2432 assert(GuardVar->getLinkage() == GV->getLinkage() &&
2433 "static local from the same function had different linkage");
2435 if (!HasPerVariableGuard) {
2436 // Pseudo code for the test:
2437 // if (!(GuardVar & MyGuardBit)) {
2438 // GuardVar |= MyGuardBit;
2439 // ... initialize the object ...;
2442 // Test our bit from the guard variable.
2443 llvm::ConstantInt *Bit = llvm::ConstantInt::get(GuardTy, 1U << GuardNum);
2444 llvm::LoadInst *LI = Builder.CreateLoad(GuardAddr);
2445 llvm::Value *IsInitialized =
2446 Builder.CreateICmpNE(Builder.CreateAnd(LI, Bit), Zero);
2447 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
2448 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2449 Builder.CreateCondBr(IsInitialized, EndBlock, InitBlock);
2451 // Set our bit in the guard variable and emit the initializer and add a global
2452 // destructor if appropriate.
2453 CGF.EmitBlock(InitBlock);
2454 Builder.CreateStore(Builder.CreateOr(LI, Bit), GuardAddr);
2455 CGF.EHStack.pushCleanup<ResetGuardBit>(EHCleanup, GuardAddr, GuardNum);
2456 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
2457 CGF.PopCleanupBlock();
2458 Builder.CreateBr(EndBlock);
2461 CGF.EmitBlock(EndBlock);
2463 // Pseudo code for the test:
2464 // if (TSS > _Init_thread_epoch) {
2465 // _Init_thread_header(&TSS);
2467 // ... initialize the object ...;
2468 // _Init_thread_footer(&TSS);
2472 // The algorithm is almost identical to what can be found in the appendix
2475 // This BasicBLock determines whether or not we have any work to do.
2476 llvm::LoadInst *FirstGuardLoad = Builder.CreateLoad(GuardAddr);
2477 FirstGuardLoad->setOrdering(llvm::AtomicOrdering::Unordered);
2478 llvm::LoadInst *InitThreadEpoch =
2479 Builder.CreateLoad(getInitThreadEpochPtr(CGM));
2480 llvm::Value *IsUninitialized =
2481 Builder.CreateICmpSGT(FirstGuardLoad, InitThreadEpoch);
2482 llvm::BasicBlock *AttemptInitBlock = CGF.createBasicBlock("init.attempt");
2483 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2484 Builder.CreateCondBr(IsUninitialized, AttemptInitBlock, EndBlock);
2486 // This BasicBlock attempts to determine whether or not this thread is
2487 // responsible for doing the initialization.
2488 CGF.EmitBlock(AttemptInitBlock);
2489 CGF.EmitNounwindRuntimeCall(getInitThreadHeaderFn(CGM),
2490 GuardAddr.getPointer());
2491 llvm::LoadInst *SecondGuardLoad = Builder.CreateLoad(GuardAddr);
2492 SecondGuardLoad->setOrdering(llvm::AtomicOrdering::Unordered);
2493 llvm::Value *ShouldDoInit =
2494 Builder.CreateICmpEQ(SecondGuardLoad, getAllOnesInt());
2495 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
2496 Builder.CreateCondBr(ShouldDoInit, InitBlock, EndBlock);
2498 // Ok, we ended up getting selected as the initializing thread.
2499 CGF.EmitBlock(InitBlock);
2500 CGF.EHStack.pushCleanup<CallInitThreadAbort>(EHCleanup, GuardAddr);
2501 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
2502 CGF.PopCleanupBlock();
2503 CGF.EmitNounwindRuntimeCall(getInitThreadFooterFn(CGM),
2504 GuardAddr.getPointer());
2505 Builder.CreateBr(EndBlock);
2507 CGF.EmitBlock(EndBlock);
2511 bool MicrosoftCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
2512 // Null-ness for function memptrs only depends on the first field, which is
2513 // the function pointer. The rest don't matter, so we can zero initialize.
2514 if (MPT->isMemberFunctionPointer())
2517 // The virtual base adjustment field is always -1 for null, so if we have one
2518 // we can't zero initialize. The field offset is sometimes also -1 if 0 is a
2519 // valid field offset.
2520 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2521 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
2522 return (!MSInheritanceAttr::hasVBTableOffsetField(Inheritance) &&
2523 RD->nullFieldOffsetIsZero());
2527 MicrosoftCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
2528 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2529 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
2530 llvm::SmallVector<llvm::Type *, 4> fields;
2531 if (MPT->isMemberFunctionPointer())
2532 fields.push_back(CGM.VoidPtrTy); // FunctionPointerOrVirtualThunk
2534 fields.push_back(CGM.IntTy); // FieldOffset
2536 if (MSInheritanceAttr::hasNVOffsetField(MPT->isMemberFunctionPointer(),
2538 fields.push_back(CGM.IntTy);
2539 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance))
2540 fields.push_back(CGM.IntTy);
2541 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance))
2542 fields.push_back(CGM.IntTy); // VirtualBaseAdjustmentOffset
2544 if (fields.size() == 1)
2546 return llvm::StructType::get(CGM.getLLVMContext(), fields);
2549 void MicrosoftCXXABI::
2550 GetNullMemberPointerFields(const MemberPointerType *MPT,
2551 llvm::SmallVectorImpl<llvm::Constant *> &fields) {
2552 assert(fields.empty());
2553 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2554 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
2555 if (MPT->isMemberFunctionPointer()) {
2556 // FunctionPointerOrVirtualThunk
2557 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
2559 if (RD->nullFieldOffsetIsZero())
2560 fields.push_back(getZeroInt()); // FieldOffset
2562 fields.push_back(getAllOnesInt()); // FieldOffset
2565 if (MSInheritanceAttr::hasNVOffsetField(MPT->isMemberFunctionPointer(),
2567 fields.push_back(getZeroInt());
2568 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance))
2569 fields.push_back(getZeroInt());
2570 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance))
2571 fields.push_back(getAllOnesInt());
2575 MicrosoftCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
2576 llvm::SmallVector<llvm::Constant *, 4> fields;
2577 GetNullMemberPointerFields(MPT, fields);
2578 if (fields.size() == 1)
2580 llvm::Constant *Res = llvm::ConstantStruct::getAnon(fields);
2581 assert(Res->getType() == ConvertMemberPointerType(MPT));
2586 MicrosoftCXXABI::EmitFullMemberPointer(llvm::Constant *FirstField,
2587 bool IsMemberFunction,
2588 const CXXRecordDecl *RD,
2589 CharUnits NonVirtualBaseAdjustment,
2590 unsigned VBTableIndex) {
2591 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
2593 // Single inheritance class member pointer are represented as scalars instead
2595 if (MSInheritanceAttr::hasOnlyOneField(IsMemberFunction, Inheritance))
2598 llvm::SmallVector<llvm::Constant *, 4> fields;
2599 fields.push_back(FirstField);
2601 if (MSInheritanceAttr::hasNVOffsetField(IsMemberFunction, Inheritance))
2602 fields.push_back(llvm::ConstantInt::get(
2603 CGM.IntTy, NonVirtualBaseAdjustment.getQuantity()));
2605 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance)) {
2606 CharUnits Offs = CharUnits::Zero();
2608 Offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
2609 fields.push_back(llvm::ConstantInt::get(CGM.IntTy, Offs.getQuantity()));
2612 // The rest of the fields are adjusted by conversions to a more derived class.
2613 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance))
2614 fields.push_back(llvm::ConstantInt::get(CGM.IntTy, VBTableIndex));
2616 return llvm::ConstantStruct::getAnon(fields);
2620 MicrosoftCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
2622 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2623 if (RD->getMSInheritanceModel() ==
2624 MSInheritanceAttr::Keyword_virtual_inheritance)
2625 offset -= getContext().getOffsetOfBaseWithVBPtr(RD);
2626 llvm::Constant *FirstField =
2627 llvm::ConstantInt::get(CGM.IntTy, offset.getQuantity());
2628 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/false, RD,
2629 CharUnits::Zero(), /*VBTableIndex=*/0);
2632 llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const APValue &MP,
2634 const MemberPointerType *DstTy = MPType->castAs<MemberPointerType>();
2635 const ValueDecl *MPD = MP.getMemberPointerDecl();
2637 return EmitNullMemberPointer(DstTy);
2639 ASTContext &Ctx = getContext();
2640 ArrayRef<const CXXRecordDecl *> MemberPointerPath = MP.getMemberPointerPath();
2643 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD)) {
2644 C = EmitMemberFunctionPointer(MD);
2646 CharUnits FieldOffset = Ctx.toCharUnitsFromBits(Ctx.getFieldOffset(MPD));
2647 C = EmitMemberDataPointer(DstTy, FieldOffset);
2650 if (!MemberPointerPath.empty()) {
2651 const CXXRecordDecl *SrcRD = cast<CXXRecordDecl>(MPD->getDeclContext());
2652 const Type *SrcRecTy = Ctx.getTypeDeclType(SrcRD).getTypePtr();
2653 const MemberPointerType *SrcTy =
2654 Ctx.getMemberPointerType(DstTy->getPointeeType(), SrcRecTy)
2655 ->castAs<MemberPointerType>();
2657 bool DerivedMember = MP.isMemberPointerToDerivedMember();
2658 SmallVector<const CXXBaseSpecifier *, 4> DerivedToBasePath;
2659 const CXXRecordDecl *PrevRD = SrcRD;
2660 for (const CXXRecordDecl *PathElem : MemberPointerPath) {
2661 const CXXRecordDecl *Base = nullptr;
2662 const CXXRecordDecl *Derived = nullptr;
2663 if (DerivedMember) {
2670 for (const CXXBaseSpecifier &BS : Derived->bases())
2671 if (BS.getType()->getAsCXXRecordDecl()->getCanonicalDecl() ==
2672 Base->getCanonicalDecl())
2673 DerivedToBasePath.push_back(&BS);
2676 assert(DerivedToBasePath.size() == MemberPointerPath.size());
2678 CastKind CK = DerivedMember ? CK_DerivedToBaseMemberPointer
2679 : CK_BaseToDerivedMemberPointer;
2680 C = EmitMemberPointerConversion(SrcTy, DstTy, CK, DerivedToBasePath.begin(),
2681 DerivedToBasePath.end(), C);
2687 MicrosoftCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) {
2688 assert(MD->isInstance() && "Member function must not be static!");
2690 MD = MD->getCanonicalDecl();
2691 CharUnits NonVirtualBaseAdjustment = CharUnits::Zero();
2692 const CXXRecordDecl *RD = MD->getParent()->getMostRecentDecl();
2693 CodeGenTypes &Types = CGM.getTypes();
2695 unsigned VBTableIndex = 0;
2696 llvm::Constant *FirstField;
2697 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
2698 if (!MD->isVirtual()) {
2700 // Check whether the function has a computable LLVM signature.
2701 if (Types.isFuncTypeConvertible(FPT)) {
2702 // The function has a computable LLVM signature; use the correct type.
2703 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
2705 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
2706 // function type is incomplete.
2709 FirstField = CGM.GetAddrOfFunction(MD, Ty);
2711 auto &VTableContext = CGM.getMicrosoftVTableContext();
2712 MicrosoftVTableContext::MethodVFTableLocation ML =
2713 VTableContext.getMethodVFTableLocation(MD);
2714 FirstField = EmitVirtualMemPtrThunk(MD, ML);
2715 // Include the vfptr adjustment if the method is in a non-primary vftable.
2716 NonVirtualBaseAdjustment += ML.VFPtrOffset;
2718 VBTableIndex = VTableContext.getVBTableIndex(RD, ML.VBase) * 4;
2721 if (VBTableIndex == 0 &&
2722 RD->getMSInheritanceModel() ==
2723 MSInheritanceAttr::Keyword_virtual_inheritance)
2724 NonVirtualBaseAdjustment -= getContext().getOffsetOfBaseWithVBPtr(RD);
2726 // The rest of the fields are common with data member pointers.
2727 FirstField = llvm::ConstantExpr::getBitCast(FirstField, CGM.VoidPtrTy);
2728 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/true, RD,
2729 NonVirtualBaseAdjustment, VBTableIndex);
2732 /// Member pointers are the same if they're either bitwise identical *or* both
2733 /// null. Null-ness for function members is determined by the first field,
2734 /// while for data member pointers we must compare all fields.
2736 MicrosoftCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
2739 const MemberPointerType *MPT,
2741 CGBuilderTy &Builder = CGF.Builder;
2743 // Handle != comparisons by switching the sense of all boolean operations.
2744 llvm::ICmpInst::Predicate Eq;
2745 llvm::Instruction::BinaryOps And, Or;
2747 Eq = llvm::ICmpInst::ICMP_NE;
2748 And = llvm::Instruction::Or;
2749 Or = llvm::Instruction::And;
2751 Eq = llvm::ICmpInst::ICMP_EQ;
2752 And = llvm::Instruction::And;
2753 Or = llvm::Instruction::Or;
2756 // If this is a single field member pointer (single inheritance), this is a
2758 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2759 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
2760 if (MSInheritanceAttr::hasOnlyOneField(MPT->isMemberFunctionPointer(),
2762 return Builder.CreateICmp(Eq, L, R);
2764 // Compare the first field.
2765 llvm::Value *L0 = Builder.CreateExtractValue(L, 0, "lhs.0");
2766 llvm::Value *R0 = Builder.CreateExtractValue(R, 0, "rhs.0");
2767 llvm::Value *Cmp0 = Builder.CreateICmp(Eq, L0, R0, "memptr.cmp.first");
2769 // Compare everything other than the first field.
2770 llvm::Value *Res = nullptr;
2771 llvm::StructType *LType = cast<llvm::StructType>(L->getType());
2772 for (unsigned I = 1, E = LType->getNumElements(); I != E; ++I) {
2773 llvm::Value *LF = Builder.CreateExtractValue(L, I);
2774 llvm::Value *RF = Builder.CreateExtractValue(R, I);
2775 llvm::Value *Cmp = Builder.CreateICmp(Eq, LF, RF, "memptr.cmp.rest");
2777 Res = Builder.CreateBinOp(And, Res, Cmp);
2782 // Check if the first field is 0 if this is a function pointer.
2783 if (MPT->isMemberFunctionPointer()) {
2784 // (l1 == r1 && ...) || l0 == 0
2785 llvm::Value *Zero = llvm::Constant::getNullValue(L0->getType());
2786 llvm::Value *IsZero = Builder.CreateICmp(Eq, L0, Zero, "memptr.cmp.iszero");
2787 Res = Builder.CreateBinOp(Or, Res, IsZero);
2790 // Combine the comparison of the first field, which must always be true for
2791 // this comparison to succeeed.
2792 return Builder.CreateBinOp(And, Res, Cmp0, "memptr.cmp");
2796 MicrosoftCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
2797 llvm::Value *MemPtr,
2798 const MemberPointerType *MPT) {
2799 CGBuilderTy &Builder = CGF.Builder;
2800 llvm::SmallVector<llvm::Constant *, 4> fields;
2801 // We only need one field for member functions.
2802 if (MPT->isMemberFunctionPointer())
2803 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
2805 GetNullMemberPointerFields(MPT, fields);
2806 assert(!fields.empty());
2807 llvm::Value *FirstField = MemPtr;
2808 if (MemPtr->getType()->isStructTy())
2809 FirstField = Builder.CreateExtractValue(MemPtr, 0);
2810 llvm::Value *Res = Builder.CreateICmpNE(FirstField, fields[0], "memptr.cmp0");
2812 // For function member pointers, we only need to test the function pointer
2813 // field. The other fields if any can be garbage.
2814 if (MPT->isMemberFunctionPointer())
2817 // Otherwise, emit a series of compares and combine the results.
2818 for (int I = 1, E = fields.size(); I < E; ++I) {
2819 llvm::Value *Field = Builder.CreateExtractValue(MemPtr, I);
2820 llvm::Value *Next = Builder.CreateICmpNE(Field, fields[I], "memptr.cmp");
2821 Res = Builder.CreateOr(Res, Next, "memptr.tobool");
2826 bool MicrosoftCXXABI::MemberPointerConstantIsNull(const MemberPointerType *MPT,
2827 llvm::Constant *Val) {
2828 // Function pointers are null if the pointer in the first field is null.
2829 if (MPT->isMemberFunctionPointer()) {
2830 llvm::Constant *FirstField = Val->getType()->isStructTy() ?
2831 Val->getAggregateElement(0U) : Val;
2832 return FirstField->isNullValue();
2835 // If it's not a function pointer and it's zero initializable, we can easily
2837 if (isZeroInitializable(MPT) && Val->isNullValue())
2840 // Otherwise, break down all the fields for comparison. Hopefully these
2841 // little Constants are reused, while a big null struct might not be.
2842 llvm::SmallVector<llvm::Constant *, 4> Fields;
2843 GetNullMemberPointerFields(MPT, Fields);
2844 if (Fields.size() == 1) {
2845 assert(Val->getType()->isIntegerTy());
2846 return Val == Fields[0];
2850 for (I = 0, E = Fields.size(); I != E; ++I) {
2851 if (Val->getAggregateElement(I) != Fields[I])
2858 MicrosoftCXXABI::GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
2860 llvm::Value *VBPtrOffset,
2861 llvm::Value *VBTableOffset,
2862 llvm::Value **VBPtrOut) {
2863 CGBuilderTy &Builder = CGF.Builder;
2864 // Load the vbtable pointer from the vbptr in the instance.
2865 This = Builder.CreateElementBitCast(This, CGM.Int8Ty);
2866 llvm::Value *VBPtr =
2867 Builder.CreateInBoundsGEP(This.getPointer(), VBPtrOffset, "vbptr");
2868 if (VBPtrOut) *VBPtrOut = VBPtr;
2869 VBPtr = Builder.CreateBitCast(VBPtr,
2870 CGM.Int32Ty->getPointerTo(0)->getPointerTo(This.getAddressSpace()));
2872 CharUnits VBPtrAlign;
2873 if (auto CI = dyn_cast<llvm::ConstantInt>(VBPtrOffset)) {
2874 VBPtrAlign = This.getAlignment().alignmentAtOffset(
2875 CharUnits::fromQuantity(CI->getSExtValue()));
2877 VBPtrAlign = CGF.getPointerAlign();
2880 llvm::Value *VBTable = Builder.CreateAlignedLoad(VBPtr, VBPtrAlign, "vbtable");
2882 // Translate from byte offset to table index. It improves analyzability.
2883 llvm::Value *VBTableIndex = Builder.CreateAShr(
2884 VBTableOffset, llvm::ConstantInt::get(VBTableOffset->getType(), 2),
2885 "vbtindex", /*isExact=*/true);
2887 // Load an i32 offset from the vb-table.
2888 llvm::Value *VBaseOffs = Builder.CreateInBoundsGEP(VBTable, VBTableIndex);
2889 VBaseOffs = Builder.CreateBitCast(VBaseOffs, CGM.Int32Ty->getPointerTo(0));
2890 return Builder.CreateAlignedLoad(VBaseOffs, CharUnits::fromQuantity(4),
2894 // Returns an adjusted base cast to i8*, since we do more address arithmetic on
2896 llvm::Value *MicrosoftCXXABI::AdjustVirtualBase(
2897 CodeGenFunction &CGF, const Expr *E, const CXXRecordDecl *RD,
2898 Address Base, llvm::Value *VBTableOffset, llvm::Value *VBPtrOffset) {
2899 CGBuilderTy &Builder = CGF.Builder;
2900 Base = Builder.CreateElementBitCast(Base, CGM.Int8Ty);
2901 llvm::BasicBlock *OriginalBB = nullptr;
2902 llvm::BasicBlock *SkipAdjustBB = nullptr;
2903 llvm::BasicBlock *VBaseAdjustBB = nullptr;
2905 // In the unspecified inheritance model, there might not be a vbtable at all,
2906 // in which case we need to skip the virtual base lookup. If there is a
2907 // vbtable, the first entry is a no-op entry that gives back the original
2908 // base, so look for a virtual base adjustment offset of zero.
2910 OriginalBB = Builder.GetInsertBlock();
2911 VBaseAdjustBB = CGF.createBasicBlock("memptr.vadjust");
2912 SkipAdjustBB = CGF.createBasicBlock("memptr.skip_vadjust");
2913 llvm::Value *IsVirtual =
2914 Builder.CreateICmpNE(VBTableOffset, getZeroInt(),
2916 Builder.CreateCondBr(IsVirtual, VBaseAdjustBB, SkipAdjustBB);
2917 CGF.EmitBlock(VBaseAdjustBB);
2920 // If we weren't given a dynamic vbptr offset, RD should be complete and we'll
2921 // know the vbptr offset.
2923 CharUnits offs = CharUnits::Zero();
2924 if (!RD->hasDefinition()) {
2925 DiagnosticsEngine &Diags = CGF.CGM.getDiags();
2926 unsigned DiagID = Diags.getCustomDiagID(
2927 DiagnosticsEngine::Error,
2928 "member pointer representation requires a "
2929 "complete class type for %0 to perform this expression");
2930 Diags.Report(E->getExprLoc(), DiagID) << RD << E->getSourceRange();
2931 } else if (RD->getNumVBases())
2932 offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
2933 VBPtrOffset = llvm::ConstantInt::get(CGM.IntTy, offs.getQuantity());
2935 llvm::Value *VBPtr = nullptr;
2936 llvm::Value *VBaseOffs =
2937 GetVBaseOffsetFromVBPtr(CGF, Base, VBPtrOffset, VBTableOffset, &VBPtr);
2938 llvm::Value *AdjustedBase = Builder.CreateInBoundsGEP(VBPtr, VBaseOffs);
2940 // Merge control flow with the case where we didn't have to adjust.
2941 if (VBaseAdjustBB) {
2942 Builder.CreateBr(SkipAdjustBB);
2943 CGF.EmitBlock(SkipAdjustBB);
2944 llvm::PHINode *Phi = Builder.CreatePHI(CGM.Int8PtrTy, 2, "memptr.base");
2945 Phi->addIncoming(Base.getPointer(), OriginalBB);
2946 Phi->addIncoming(AdjustedBase, VBaseAdjustBB);
2949 return AdjustedBase;
2952 llvm::Value *MicrosoftCXXABI::EmitMemberDataPointerAddress(
2953 CodeGenFunction &CGF, const Expr *E, Address Base, llvm::Value *MemPtr,
2954 const MemberPointerType *MPT) {
2955 assert(MPT->isMemberDataPointer());
2956 unsigned AS = Base.getAddressSpace();
2958 CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
2959 CGBuilderTy &Builder = CGF.Builder;
2960 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2961 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
2963 // Extract the fields we need, regardless of model. We'll apply them if we
2965 llvm::Value *FieldOffset = MemPtr;
2966 llvm::Value *VirtualBaseAdjustmentOffset = nullptr;
2967 llvm::Value *VBPtrOffset = nullptr;
2968 if (MemPtr->getType()->isStructTy()) {
2969 // We need to extract values.
2971 FieldOffset = Builder.CreateExtractValue(MemPtr, I++);
2972 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance))
2973 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
2974 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance))
2975 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
2979 if (VirtualBaseAdjustmentOffset) {
2980 Addr = AdjustVirtualBase(CGF, E, RD, Base, VirtualBaseAdjustmentOffset,
2983 Addr = Base.getPointer();
2987 Addr = Builder.CreateBitCast(Addr, CGF.Int8Ty->getPointerTo(AS));
2989 // Apply the offset, which we assume is non-null.
2990 Addr = Builder.CreateInBoundsGEP(Addr, FieldOffset, "memptr.offset");
2992 // Cast the address to the appropriate pointer type, adopting the address
2993 // space of the base pointer.
2994 return Builder.CreateBitCast(Addr, PType);
2998 MicrosoftCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
3001 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
3002 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
3003 E->getCastKind() == CK_ReinterpretMemberPointer);
3005 // Use constant emission if we can.
3006 if (isa<llvm::Constant>(Src))
3007 return EmitMemberPointerConversion(E, cast<llvm::Constant>(Src));
3009 // We may be adding or dropping fields from the member pointer, so we need
3010 // both types and the inheritance models of both records.
3011 const MemberPointerType *SrcTy =
3012 E->getSubExpr()->getType()->castAs<MemberPointerType>();
3013 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
3014 bool IsFunc = SrcTy->isMemberFunctionPointer();
3016 // If the classes use the same null representation, reinterpret_cast is a nop.
3017 bool IsReinterpret = E->getCastKind() == CK_ReinterpretMemberPointer;
3018 if (IsReinterpret && IsFunc)
3021 CXXRecordDecl *SrcRD = SrcTy->getMostRecentCXXRecordDecl();
3022 CXXRecordDecl *DstRD = DstTy->getMostRecentCXXRecordDecl();
3023 if (IsReinterpret &&
3024 SrcRD->nullFieldOffsetIsZero() == DstRD->nullFieldOffsetIsZero())
3027 CGBuilderTy &Builder = CGF.Builder;
3029 // Branch past the conversion if Src is null.
3030 llvm::Value *IsNotNull = EmitMemberPointerIsNotNull(CGF, Src, SrcTy);
3031 llvm::Constant *DstNull = EmitNullMemberPointer(DstTy);
3033 // C++ 5.2.10p9: The null member pointer value is converted to the null member
3034 // pointer value of the destination type.
3035 if (IsReinterpret) {
3036 // For reinterpret casts, sema ensures that src and dst are both functions
3037 // or data and have the same size, which means the LLVM types should match.
3038 assert(Src->getType() == DstNull->getType());
3039 return Builder.CreateSelect(IsNotNull, Src, DstNull);
3042 llvm::BasicBlock *OriginalBB = Builder.GetInsertBlock();
3043 llvm::BasicBlock *ConvertBB = CGF.createBasicBlock("memptr.convert");
3044 llvm::BasicBlock *ContinueBB = CGF.createBasicBlock("memptr.converted");
3045 Builder.CreateCondBr(IsNotNull, ConvertBB, ContinueBB);
3046 CGF.EmitBlock(ConvertBB);
3048 llvm::Value *Dst = EmitNonNullMemberPointerConversion(
3049 SrcTy, DstTy, E->getCastKind(), E->path_begin(), E->path_end(), Src,
3052 Builder.CreateBr(ContinueBB);
3054 // In the continuation, choose between DstNull and Dst.
3055 CGF.EmitBlock(ContinueBB);
3056 llvm::PHINode *Phi = Builder.CreatePHI(DstNull->getType(), 2, "memptr.converted");
3057 Phi->addIncoming(DstNull, OriginalBB);
3058 Phi->addIncoming(Dst, ConvertBB);
3062 llvm::Value *MicrosoftCXXABI::EmitNonNullMemberPointerConversion(
3063 const MemberPointerType *SrcTy, const MemberPointerType *DstTy, CastKind CK,
3064 CastExpr::path_const_iterator PathBegin,
3065 CastExpr::path_const_iterator PathEnd, llvm::Value *Src,
3066 CGBuilderTy &Builder) {
3067 const CXXRecordDecl *SrcRD = SrcTy->getMostRecentCXXRecordDecl();
3068 const CXXRecordDecl *DstRD = DstTy->getMostRecentCXXRecordDecl();
3069 MSInheritanceAttr::Spelling SrcInheritance = SrcRD->getMSInheritanceModel();
3070 MSInheritanceAttr::Spelling DstInheritance = DstRD->getMSInheritanceModel();
3071 bool IsFunc = SrcTy->isMemberFunctionPointer();
3072 bool IsConstant = isa<llvm::Constant>(Src);
3075 llvm::Value *FirstField = Src;
3076 llvm::Value *NonVirtualBaseAdjustment = getZeroInt();
3077 llvm::Value *VirtualBaseAdjustmentOffset = getZeroInt();
3078 llvm::Value *VBPtrOffset = getZeroInt();
3079 if (!MSInheritanceAttr::hasOnlyOneField(IsFunc, SrcInheritance)) {
3080 // We need to extract values.
3082 FirstField = Builder.CreateExtractValue(Src, I++);
3083 if (MSInheritanceAttr::hasNVOffsetField(IsFunc, SrcInheritance))
3084 NonVirtualBaseAdjustment = Builder.CreateExtractValue(Src, I++);
3085 if (MSInheritanceAttr::hasVBPtrOffsetField(SrcInheritance))
3086 VBPtrOffset = Builder.CreateExtractValue(Src, I++);
3087 if (MSInheritanceAttr::hasVBTableOffsetField(SrcInheritance))
3088 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(Src, I++);
3091 bool IsDerivedToBase = (CK == CK_DerivedToBaseMemberPointer);
3092 const MemberPointerType *DerivedTy = IsDerivedToBase ? SrcTy : DstTy;
3093 const CXXRecordDecl *DerivedClass = DerivedTy->getMostRecentCXXRecordDecl();
3095 // For data pointers, we adjust the field offset directly. For functions, we
3096 // have a separate field.
3097 llvm::Value *&NVAdjustField = IsFunc ? NonVirtualBaseAdjustment : FirstField;
3099 // The virtual inheritance model has a quirk: the virtual base table is always
3100 // referenced when dereferencing a member pointer even if the member pointer
3101 // is non-virtual. This is accounted for by adjusting the non-virtual offset
3102 // to point backwards to the top of the MDC from the first VBase. Undo this
3103 // adjustment to normalize the member pointer.
3104 llvm::Value *SrcVBIndexEqZero =
3105 Builder.CreateICmpEQ(VirtualBaseAdjustmentOffset, getZeroInt());
3106 if (SrcInheritance == MSInheritanceAttr::Keyword_virtual_inheritance) {
3107 if (int64_t SrcOffsetToFirstVBase =
3108 getContext().getOffsetOfBaseWithVBPtr(SrcRD).getQuantity()) {
3109 llvm::Value *UndoSrcAdjustment = Builder.CreateSelect(
3111 llvm::ConstantInt::get(CGM.IntTy, SrcOffsetToFirstVBase),
3113 NVAdjustField = Builder.CreateNSWAdd(NVAdjustField, UndoSrcAdjustment);
3117 // A non-zero vbindex implies that we are dealing with a source member in a
3118 // floating virtual base in addition to some non-virtual offset. If the
3119 // vbindex is zero, we are dealing with a source that exists in a non-virtual,
3120 // fixed, base. The difference between these two cases is that the vbindex +
3121 // nvoffset *always* point to the member regardless of what context they are
3122 // evaluated in so long as the vbindex is adjusted. A member inside a fixed
3123 // base requires explicit nv adjustment.
3124 llvm::Constant *BaseClassOffset = llvm::ConstantInt::get(
3126 CGM.computeNonVirtualBaseClassOffset(DerivedClass, PathBegin, PathEnd)
3129 llvm::Value *NVDisp;
3130 if (IsDerivedToBase)
3131 NVDisp = Builder.CreateNSWSub(NVAdjustField, BaseClassOffset, "adj");
3133 NVDisp = Builder.CreateNSWAdd(NVAdjustField, BaseClassOffset, "adj");
3135 NVAdjustField = Builder.CreateSelect(SrcVBIndexEqZero, NVDisp, getZeroInt());
3137 // Update the vbindex to an appropriate value in the destination because
3138 // SrcRD's vbtable might not be a strict prefix of the one in DstRD.
3139 llvm::Value *DstVBIndexEqZero = SrcVBIndexEqZero;
3140 if (MSInheritanceAttr::hasVBTableOffsetField(DstInheritance) &&
3141 MSInheritanceAttr::hasVBTableOffsetField(SrcInheritance)) {
3142 if (llvm::GlobalVariable *VDispMap =
3143 getAddrOfVirtualDisplacementMap(SrcRD, DstRD)) {
3144 llvm::Value *VBIndex = Builder.CreateExactUDiv(
3145 VirtualBaseAdjustmentOffset, llvm::ConstantInt::get(CGM.IntTy, 4));
3147 llvm::Constant *Mapping = VDispMap->getInitializer();
3148 VirtualBaseAdjustmentOffset =
3149 Mapping->getAggregateElement(cast<llvm::Constant>(VBIndex));
3151 llvm::Value *Idxs[] = {getZeroInt(), VBIndex};
3152 VirtualBaseAdjustmentOffset =
3153 Builder.CreateAlignedLoad(Builder.CreateInBoundsGEP(VDispMap, Idxs),
3154 CharUnits::fromQuantity(4));
3158 Builder.CreateICmpEQ(VirtualBaseAdjustmentOffset, getZeroInt());
3162 // Set the VBPtrOffset to zero if the vbindex is zero. Otherwise, initialize
3163 // it to the offset of the vbptr.
3164 if (MSInheritanceAttr::hasVBPtrOffsetField(DstInheritance)) {
3165 llvm::Value *DstVBPtrOffset = llvm::ConstantInt::get(
3167 getContext().getASTRecordLayout(DstRD).getVBPtrOffset().getQuantity());
3169 Builder.CreateSelect(DstVBIndexEqZero, getZeroInt(), DstVBPtrOffset);
3172 // Likewise, apply a similar adjustment so that dereferencing the member
3173 // pointer correctly accounts for the distance between the start of the first
3174 // virtual base and the top of the MDC.
3175 if (DstInheritance == MSInheritanceAttr::Keyword_virtual_inheritance) {
3176 if (int64_t DstOffsetToFirstVBase =
3177 getContext().getOffsetOfBaseWithVBPtr(DstRD).getQuantity()) {
3178 llvm::Value *DoDstAdjustment = Builder.CreateSelect(
3180 llvm::ConstantInt::get(CGM.IntTy, DstOffsetToFirstVBase),
3182 NVAdjustField = Builder.CreateNSWSub(NVAdjustField, DoDstAdjustment);
3186 // Recompose dst from the null struct and the adjusted fields from src.
3188 if (MSInheritanceAttr::hasOnlyOneField(IsFunc, DstInheritance)) {
3191 Dst = llvm::UndefValue::get(ConvertMemberPointerType(DstTy));
3193 Dst = Builder.CreateInsertValue(Dst, FirstField, Idx++);
3194 if (MSInheritanceAttr::hasNVOffsetField(IsFunc, DstInheritance))
3195 Dst = Builder.CreateInsertValue(Dst, NonVirtualBaseAdjustment, Idx++);
3196 if (MSInheritanceAttr::hasVBPtrOffsetField(DstInheritance))
3197 Dst = Builder.CreateInsertValue(Dst, VBPtrOffset, Idx++);
3198 if (MSInheritanceAttr::hasVBTableOffsetField(DstInheritance))
3199 Dst = Builder.CreateInsertValue(Dst, VirtualBaseAdjustmentOffset, Idx++);
3205 MicrosoftCXXABI::EmitMemberPointerConversion(const CastExpr *E,
3206 llvm::Constant *Src) {
3207 const MemberPointerType *SrcTy =
3208 E->getSubExpr()->getType()->castAs<MemberPointerType>();
3209 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
3211 CastKind CK = E->getCastKind();
3213 return EmitMemberPointerConversion(SrcTy, DstTy, CK, E->path_begin(),
3214 E->path_end(), Src);
3217 llvm::Constant *MicrosoftCXXABI::EmitMemberPointerConversion(
3218 const MemberPointerType *SrcTy, const MemberPointerType *DstTy, CastKind CK,
3219 CastExpr::path_const_iterator PathBegin,
3220 CastExpr::path_const_iterator PathEnd, llvm::Constant *Src) {
3221 assert(CK == CK_DerivedToBaseMemberPointer ||
3222 CK == CK_BaseToDerivedMemberPointer ||
3223 CK == CK_ReinterpretMemberPointer);
3224 // If src is null, emit a new null for dst. We can't return src because dst
3225 // might have a new representation.
3226 if (MemberPointerConstantIsNull(SrcTy, Src))
3227 return EmitNullMemberPointer(DstTy);
3229 // We don't need to do anything for reinterpret_casts of non-null member
3230 // pointers. We should only get here when the two type representations have
3232 if (CK == CK_ReinterpretMemberPointer)
3235 CGBuilderTy Builder(CGM, CGM.getLLVMContext());
3236 auto *Dst = cast<llvm::Constant>(EmitNonNullMemberPointerConversion(
3237 SrcTy, DstTy, CK, PathBegin, PathEnd, Src, Builder));
3242 llvm::Value *MicrosoftCXXABI::EmitLoadOfMemberFunctionPointer(
3243 CodeGenFunction &CGF, const Expr *E, Address This,
3244 llvm::Value *&ThisPtrForCall, llvm::Value *MemPtr,
3245 const MemberPointerType *MPT) {
3246 assert(MPT->isMemberFunctionPointer());
3247 const FunctionProtoType *FPT =
3248 MPT->getPointeeType()->castAs<FunctionProtoType>();
3249 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
3250 llvm::FunctionType *FTy =
3251 CGM.getTypes().GetFunctionType(
3252 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
3253 CGBuilderTy &Builder = CGF.Builder;
3255 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
3257 // Extract the fields we need, regardless of model. We'll apply them if we
3259 llvm::Value *FunctionPointer = MemPtr;
3260 llvm::Value *NonVirtualBaseAdjustment = nullptr;
3261 llvm::Value *VirtualBaseAdjustmentOffset = nullptr;
3262 llvm::Value *VBPtrOffset = nullptr;
3263 if (MemPtr->getType()->isStructTy()) {
3264 // We need to extract values.
3266 FunctionPointer = Builder.CreateExtractValue(MemPtr, I++);
3267 if (MSInheritanceAttr::hasNVOffsetField(MPT, Inheritance))
3268 NonVirtualBaseAdjustment = Builder.CreateExtractValue(MemPtr, I++);
3269 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance))
3270 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
3271 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance))
3272 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
3275 if (VirtualBaseAdjustmentOffset) {
3276 ThisPtrForCall = AdjustVirtualBase(CGF, E, RD, This,
3277 VirtualBaseAdjustmentOffset, VBPtrOffset);
3279 ThisPtrForCall = This.getPointer();
3282 if (NonVirtualBaseAdjustment) {
3283 // Apply the adjustment and cast back to the original struct type.
3284 llvm::Value *Ptr = Builder.CreateBitCast(ThisPtrForCall, CGF.Int8PtrTy);
3285 Ptr = Builder.CreateInBoundsGEP(Ptr, NonVirtualBaseAdjustment);
3286 ThisPtrForCall = Builder.CreateBitCast(Ptr, ThisPtrForCall->getType(),
3290 return Builder.CreateBitCast(FunctionPointer, FTy->getPointerTo());
3293 CGCXXABI *clang::CodeGen::CreateMicrosoftCXXABI(CodeGenModule &CGM) {
3294 return new MicrosoftCXXABI(CGM);
3297 // MS RTTI Overview:
3298 // The run time type information emitted by cl.exe contains 5 distinct types of
3299 // structures. Many of them reference each other.
3301 // TypeInfo: Static classes that are returned by typeid.
3303 // CompleteObjectLocator: Referenced by vftables. They contain information
3304 // required for dynamic casting, including OffsetFromTop. They also contain
3305 // a reference to the TypeInfo for the type and a reference to the
3306 // CompleteHierarchyDescriptor for the type.
3308 // ClassHieararchyDescriptor: Contains information about a class hierarchy.
3309 // Used during dynamic_cast to walk a class hierarchy. References a base
3310 // class array and the size of said array.
3312 // BaseClassArray: Contains a list of classes in a hierarchy. BaseClassArray is
3313 // somewhat of a misnomer because the most derived class is also in the list
3314 // as well as multiple copies of virtual bases (if they occur multiple times
3315 // in the hiearchy.) The BaseClassArray contains one BaseClassDescriptor for
3316 // every path in the hierarchy, in pre-order depth first order. Note, we do
3317 // not declare a specific llvm type for BaseClassArray, it's merely an array
3318 // of BaseClassDescriptor pointers.
3320 // BaseClassDescriptor: Contains information about a class in a class hierarchy.
3321 // BaseClassDescriptor is also somewhat of a misnomer for the same reason that
3322 // BaseClassArray is. It contains information about a class within a
3323 // hierarchy such as: is this base is ambiguous and what is its offset in the
3324 // vbtable. The names of the BaseClassDescriptors have all of their fields
3325 // mangled into them so they can be aggressively deduplicated by the linker.
3327 static llvm::GlobalVariable *getTypeInfoVTable(CodeGenModule &CGM) {
3328 StringRef MangledName("\01??_7type_info@@6B@");
3329 if (auto VTable = CGM.getModule().getNamedGlobal(MangledName))
3331 return new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
3333 llvm::GlobalVariable::ExternalLinkage,
3334 /*Initializer=*/nullptr, MangledName);
3339 /// \brief A Helper struct that stores information about a class in a class
3340 /// hierarchy. The information stored in these structs struct is used during
3341 /// the generation of ClassHierarchyDescriptors and BaseClassDescriptors.
3342 // During RTTI creation, MSRTTIClasses are stored in a contiguous array with
3343 // implicit depth first pre-order tree connectivity. getFirstChild and
3344 // getNextSibling allow us to walk the tree efficiently.
3345 struct MSRTTIClass {
3347 IsPrivateOnPath = 1 | 8,
3351 HasHierarchyDescriptor = 64
3353 MSRTTIClass(const CXXRecordDecl *RD) : RD(RD) {}
3354 uint32_t initialize(const MSRTTIClass *Parent,
3355 const CXXBaseSpecifier *Specifier);
3357 MSRTTIClass *getFirstChild() { return this + 1; }
3358 static MSRTTIClass *getNextChild(MSRTTIClass *Child) {
3359 return Child + 1 + Child->NumBases;
3362 const CXXRecordDecl *RD, *VirtualRoot;
3363 uint32_t Flags, NumBases, OffsetInVBase;
3366 /// \brief Recursively initialize the base class array.
3367 uint32_t MSRTTIClass::initialize(const MSRTTIClass *Parent,
3368 const CXXBaseSpecifier *Specifier) {
3369 Flags = HasHierarchyDescriptor;
3371 VirtualRoot = nullptr;
3374 if (Specifier->getAccessSpecifier() != AS_public)
3375 Flags |= IsPrivate | IsPrivateOnPath;
3376 if (Specifier->isVirtual()) {
3381 if (Parent->Flags & IsPrivateOnPath)
3382 Flags |= IsPrivateOnPath;
3383 VirtualRoot = Parent->VirtualRoot;
3384 OffsetInVBase = Parent->OffsetInVBase + RD->getASTContext()
3385 .getASTRecordLayout(Parent->RD).getBaseClassOffset(RD).getQuantity();
3389 MSRTTIClass *Child = getFirstChild();
3390 for (const CXXBaseSpecifier &Base : RD->bases()) {
3391 NumBases += Child->initialize(this, &Base) + 1;
3392 Child = getNextChild(Child);
3397 static llvm::GlobalValue::LinkageTypes getLinkageForRTTI(QualType Ty) {
3398 switch (Ty->getLinkage()) {
3400 case InternalLinkage:
3401 case UniqueExternalLinkage:
3402 return llvm::GlobalValue::InternalLinkage;
3404 case VisibleNoLinkage:
3405 case ExternalLinkage:
3406 return llvm::GlobalValue::LinkOnceODRLinkage;
3408 llvm_unreachable("Invalid linkage!");
3411 /// \brief An ephemeral helper class for building MS RTTI types. It caches some
3412 /// calls to the module and information about the most derived class in a
3414 struct MSRTTIBuilder {
3416 HasBranchingHierarchy = 1,
3417 HasVirtualBranchingHierarchy = 2,
3418 HasAmbiguousBases = 4
3421 MSRTTIBuilder(MicrosoftCXXABI &ABI, const CXXRecordDecl *RD)
3422 : CGM(ABI.CGM), Context(CGM.getContext()),
3423 VMContext(CGM.getLLVMContext()), Module(CGM.getModule()), RD(RD),
3424 Linkage(getLinkageForRTTI(CGM.getContext().getTagDeclType(RD))),
3427 llvm::GlobalVariable *getBaseClassDescriptor(const MSRTTIClass &Classes);
3428 llvm::GlobalVariable *
3429 getBaseClassArray(SmallVectorImpl<MSRTTIClass> &Classes);
3430 llvm::GlobalVariable *getClassHierarchyDescriptor();
3431 llvm::GlobalVariable *getCompleteObjectLocator(const VPtrInfo *Info);
3434 ASTContext &Context;
3435 llvm::LLVMContext &VMContext;
3436 llvm::Module &Module;
3437 const CXXRecordDecl *RD;
3438 llvm::GlobalVariable::LinkageTypes Linkage;
3439 MicrosoftCXXABI &ABI;
3444 /// \brief Recursively serializes a class hierarchy in pre-order depth first
3446 static void serializeClassHierarchy(SmallVectorImpl<MSRTTIClass> &Classes,
3447 const CXXRecordDecl *RD) {
3448 Classes.push_back(MSRTTIClass(RD));
3449 for (const CXXBaseSpecifier &Base : RD->bases())
3450 serializeClassHierarchy(Classes, Base.getType()->getAsCXXRecordDecl());
3453 /// \brief Find ambiguity among base classes.
3455 detectAmbiguousBases(SmallVectorImpl<MSRTTIClass> &Classes) {
3456 llvm::SmallPtrSet<const CXXRecordDecl *, 8> VirtualBases;
3457 llvm::SmallPtrSet<const CXXRecordDecl *, 8> UniqueBases;
3458 llvm::SmallPtrSet<const CXXRecordDecl *, 8> AmbiguousBases;
3459 for (MSRTTIClass *Class = &Classes.front(); Class <= &Classes.back();) {
3460 if ((Class->Flags & MSRTTIClass::IsVirtual) &&
3461 !VirtualBases.insert(Class->RD).second) {
3462 Class = MSRTTIClass::getNextChild(Class);
3465 if (!UniqueBases.insert(Class->RD).second)
3466 AmbiguousBases.insert(Class->RD);
3469 if (AmbiguousBases.empty())
3471 for (MSRTTIClass &Class : Classes)
3472 if (AmbiguousBases.count(Class.RD))
3473 Class.Flags |= MSRTTIClass::IsAmbiguous;
3476 llvm::GlobalVariable *MSRTTIBuilder::getClassHierarchyDescriptor() {
3477 SmallString<256> MangledName;
3479 llvm::raw_svector_ostream Out(MangledName);
3480 ABI.getMangleContext().mangleCXXRTTIClassHierarchyDescriptor(RD, Out);
3483 // Check to see if we've already declared this ClassHierarchyDescriptor.
3484 if (auto CHD = Module.getNamedGlobal(MangledName))
3487 // Serialize the class hierarchy and initialize the CHD Fields.
3488 SmallVector<MSRTTIClass, 8> Classes;
3489 serializeClassHierarchy(Classes, RD);
3490 Classes.front().initialize(/*Parent=*/nullptr, /*Specifier=*/nullptr);
3491 detectAmbiguousBases(Classes);
3493 for (auto Class : Classes) {
3494 if (Class.RD->getNumBases() > 1)
3495 Flags |= HasBranchingHierarchy;
3496 // Note: cl.exe does not calculate "HasAmbiguousBases" correctly. We
3497 // believe the field isn't actually used.
3498 if (Class.Flags & MSRTTIClass::IsAmbiguous)
3499 Flags |= HasAmbiguousBases;
3501 if ((Flags & HasBranchingHierarchy) && RD->getNumVBases() != 0)
3502 Flags |= HasVirtualBranchingHierarchy;
3503 // These gep indices are used to get the address of the first element of the
3504 // base class array.
3505 llvm::Value *GEPIndices[] = {llvm::ConstantInt::get(CGM.IntTy, 0),
3506 llvm::ConstantInt::get(CGM.IntTy, 0)};
3508 // Forward-declare the class hierarchy descriptor
3509 auto Type = ABI.getClassHierarchyDescriptorType();
3510 auto CHD = new llvm::GlobalVariable(Module, Type, /*Constant=*/true, Linkage,
3511 /*Initializer=*/nullptr,
3512 StringRef(MangledName));
3513 if (CHD->isWeakForLinker())
3514 CHD->setComdat(CGM.getModule().getOrInsertComdat(CHD->getName()));
3516 auto *Bases = getBaseClassArray(Classes);
3518 // Initialize the base class ClassHierarchyDescriptor.
3519 llvm::Constant *Fields[] = {
3520 llvm::ConstantInt::get(CGM.IntTy, 0), // Unknown
3521 llvm::ConstantInt::get(CGM.IntTy, Flags),
3522 llvm::ConstantInt::get(CGM.IntTy, Classes.size()),
3523 ABI.getImageRelativeConstant(llvm::ConstantExpr::getInBoundsGetElementPtr(
3524 Bases->getValueType(), Bases,
3525 llvm::ArrayRef<llvm::Value *>(GEPIndices))),
3527 CHD->setInitializer(llvm::ConstantStruct::get(Type, Fields));
3531 llvm::GlobalVariable *
3532 MSRTTIBuilder::getBaseClassArray(SmallVectorImpl<MSRTTIClass> &Classes) {
3533 SmallString<256> MangledName;
3535 llvm::raw_svector_ostream Out(MangledName);
3536 ABI.getMangleContext().mangleCXXRTTIBaseClassArray(RD, Out);
3539 // Forward-declare the base class array.
3540 // cl.exe pads the base class array with 1 (in 32 bit mode) or 4 (in 64 bit
3541 // mode) bytes of padding. We provide a pointer sized amount of padding by
3542 // adding +1 to Classes.size(). The sections have pointer alignment and are
3543 // marked pick-any so it shouldn't matter.
3544 llvm::Type *PtrType = ABI.getImageRelativeType(
3545 ABI.getBaseClassDescriptorType()->getPointerTo());
3546 auto *ArrType = llvm::ArrayType::get(PtrType, Classes.size() + 1);
3548 new llvm::GlobalVariable(Module, ArrType,
3549 /*Constant=*/true, Linkage,
3550 /*Initializer=*/nullptr, StringRef(MangledName));
3551 if (BCA->isWeakForLinker())
3552 BCA->setComdat(CGM.getModule().getOrInsertComdat(BCA->getName()));
3554 // Initialize the BaseClassArray.
3555 SmallVector<llvm::Constant *, 8> BaseClassArrayData;
3556 for (MSRTTIClass &Class : Classes)
3557 BaseClassArrayData.push_back(
3558 ABI.getImageRelativeConstant(getBaseClassDescriptor(Class)));
3559 BaseClassArrayData.push_back(llvm::Constant::getNullValue(PtrType));
3560 BCA->setInitializer(llvm::ConstantArray::get(ArrType, BaseClassArrayData));
3564 llvm::GlobalVariable *
3565 MSRTTIBuilder::getBaseClassDescriptor(const MSRTTIClass &Class) {
3566 // Compute the fields for the BaseClassDescriptor. They are computed up front
3567 // because they are mangled into the name of the object.
3568 uint32_t OffsetInVBTable = 0;
3569 int32_t VBPtrOffset = -1;
3570 if (Class.VirtualRoot) {
3571 auto &VTableContext = CGM.getMicrosoftVTableContext();
3572 OffsetInVBTable = VTableContext.getVBTableIndex(RD, Class.VirtualRoot) * 4;
3573 VBPtrOffset = Context.getASTRecordLayout(RD).getVBPtrOffset().getQuantity();
3576 SmallString<256> MangledName;
3578 llvm::raw_svector_ostream Out(MangledName);
3579 ABI.getMangleContext().mangleCXXRTTIBaseClassDescriptor(
3580 Class.RD, Class.OffsetInVBase, VBPtrOffset, OffsetInVBTable,
3584 // Check to see if we've already declared this object.
3585 if (auto BCD = Module.getNamedGlobal(MangledName))
3588 // Forward-declare the base class descriptor.
3589 auto Type = ABI.getBaseClassDescriptorType();
3591 new llvm::GlobalVariable(Module, Type, /*Constant=*/true, Linkage,
3592 /*Initializer=*/nullptr, StringRef(MangledName));
3593 if (BCD->isWeakForLinker())
3594 BCD->setComdat(CGM.getModule().getOrInsertComdat(BCD->getName()));
3596 // Initialize the BaseClassDescriptor.
3597 llvm::Constant *Fields[] = {
3598 ABI.getImageRelativeConstant(
3599 ABI.getAddrOfRTTIDescriptor(Context.getTypeDeclType(Class.RD))),
3600 llvm::ConstantInt::get(CGM.IntTy, Class.NumBases),
3601 llvm::ConstantInt::get(CGM.IntTy, Class.OffsetInVBase),
3602 llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset),
3603 llvm::ConstantInt::get(CGM.IntTy, OffsetInVBTable),
3604 llvm::ConstantInt::get(CGM.IntTy, Class.Flags),
3605 ABI.getImageRelativeConstant(
3606 MSRTTIBuilder(ABI, Class.RD).getClassHierarchyDescriptor()),
3608 BCD->setInitializer(llvm::ConstantStruct::get(Type, Fields));
3612 llvm::GlobalVariable *
3613 MSRTTIBuilder::getCompleteObjectLocator(const VPtrInfo *Info) {
3614 SmallString<256> MangledName;
3616 llvm::raw_svector_ostream Out(MangledName);
3617 ABI.getMangleContext().mangleCXXRTTICompleteObjectLocator(RD, Info->MangledPath, Out);
3620 // Check to see if we've already computed this complete object locator.
3621 if (auto COL = Module.getNamedGlobal(MangledName))
3624 // Compute the fields of the complete object locator.
3625 int OffsetToTop = Info->FullOffsetInMDC.getQuantity();
3626 int VFPtrOffset = 0;
3627 // The offset includes the vtordisp if one exists.
3628 if (const CXXRecordDecl *VBase = Info->getVBaseWithVPtr())
3629 if (Context.getASTRecordLayout(RD)
3630 .getVBaseOffsetsMap()
3632 ->second.hasVtorDisp())
3633 VFPtrOffset = Info->NonVirtualOffset.getQuantity() + 4;
3635 // Forward-declare the complete object locator.
3636 llvm::StructType *Type = ABI.getCompleteObjectLocatorType();
3637 auto COL = new llvm::GlobalVariable(Module, Type, /*Constant=*/true, Linkage,
3638 /*Initializer=*/nullptr, StringRef(MangledName));
3640 // Initialize the CompleteObjectLocator.
3641 llvm::Constant *Fields[] = {
3642 llvm::ConstantInt::get(CGM.IntTy, ABI.isImageRelative()),
3643 llvm::ConstantInt::get(CGM.IntTy, OffsetToTop),
3644 llvm::ConstantInt::get(CGM.IntTy, VFPtrOffset),
3645 ABI.getImageRelativeConstant(
3646 CGM.GetAddrOfRTTIDescriptor(Context.getTypeDeclType(RD))),
3647 ABI.getImageRelativeConstant(getClassHierarchyDescriptor()),
3648 ABI.getImageRelativeConstant(COL),
3650 llvm::ArrayRef<llvm::Constant *> FieldsRef(Fields);
3651 if (!ABI.isImageRelative())
3652 FieldsRef = FieldsRef.drop_back();
3653 COL->setInitializer(llvm::ConstantStruct::get(Type, FieldsRef));
3654 if (COL->isWeakForLinker())
3655 COL->setComdat(CGM.getModule().getOrInsertComdat(COL->getName()));
3659 static QualType decomposeTypeForEH(ASTContext &Context, QualType T,
3660 bool &IsConst, bool &IsVolatile) {
3661 T = Context.getExceptionObjectType(T);
3663 // C++14 [except.handle]p3:
3664 // A handler is a match for an exception object of type E if [...]
3665 // - the handler is of type cv T or const T& where T is a pointer type and
3666 // E is a pointer type that can be converted to T by [...]
3667 // - a qualification conversion
3670 QualType PointeeType = T->getPointeeType();
3671 if (!PointeeType.isNull()) {
3672 IsConst = PointeeType.isConstQualified();
3673 IsVolatile = PointeeType.isVolatileQualified();
3676 // Member pointer types like "const int A::*" are represented by having RTTI
3677 // for "int A::*" and separately storing the const qualifier.
3678 if (const auto *MPTy = T->getAs<MemberPointerType>())
3679 T = Context.getMemberPointerType(PointeeType.getUnqualifiedType(),
3682 // Pointer types like "const int * const *" are represented by having RTTI
3683 // for "const int **" and separately storing the const qualifier.
3684 if (T->isPointerType())
3685 T = Context.getPointerType(PointeeType.getUnqualifiedType());
3691 MicrosoftCXXABI::getAddrOfCXXCatchHandlerType(QualType Type,
3692 QualType CatchHandlerType) {
3693 // TypeDescriptors for exceptions never have qualified pointer types,
3694 // qualifiers are stored seperately in order to support qualification
3696 bool IsConst, IsVolatile;
3697 Type = decomposeTypeForEH(getContext(), Type, IsConst, IsVolatile);
3699 bool IsReference = CatchHandlerType->isReferenceType();
3709 SmallString<256> MangledName;
3711 llvm::raw_svector_ostream Out(MangledName);
3712 getMangleContext().mangleCXXCatchHandlerType(Type, Flags, Out);
3715 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
3716 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
3718 llvm::Constant *Fields[] = {
3719 llvm::ConstantInt::get(CGM.IntTy, Flags), // Flags
3720 getAddrOfRTTIDescriptor(Type), // TypeDescriptor
3722 llvm::StructType *CatchHandlerTypeType = getCatchHandlerTypeType();
3723 auto *Var = new llvm::GlobalVariable(
3724 CGM.getModule(), CatchHandlerTypeType, /*Constant=*/true,
3725 llvm::GlobalValue::PrivateLinkage,
3726 llvm::ConstantStruct::get(CatchHandlerTypeType, Fields),
3727 StringRef(MangledName));
3728 Var->setUnnamedAddr(true);
3729 Var->setSection("llvm.metadata");
3733 /// \brief Gets a TypeDescriptor. Returns a llvm::Constant * rather than a
3734 /// llvm::GlobalVariable * because different type descriptors have different
3735 /// types, and need to be abstracted. They are abstracting by casting the
3736 /// address to an Int8PtrTy.
3737 llvm::Constant *MicrosoftCXXABI::getAddrOfRTTIDescriptor(QualType Type) {
3738 SmallString<256> MangledName;
3740 llvm::raw_svector_ostream Out(MangledName);
3741 getMangleContext().mangleCXXRTTI(Type, Out);
3744 // Check to see if we've already declared this TypeDescriptor.
3745 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
3746 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
3748 // Compute the fields for the TypeDescriptor.
3749 SmallString<256> TypeInfoString;
3751 llvm::raw_svector_ostream Out(TypeInfoString);
3752 getMangleContext().mangleCXXRTTIName(Type, Out);
3755 // Declare and initialize the TypeDescriptor.
3756 llvm::Constant *Fields[] = {
3757 getTypeInfoVTable(CGM), // VFPtr
3758 llvm::ConstantPointerNull::get(CGM.Int8PtrTy), // Runtime data
3759 llvm::ConstantDataArray::getString(CGM.getLLVMContext(), TypeInfoString)};
3760 llvm::StructType *TypeDescriptorType =
3761 getTypeDescriptorType(TypeInfoString);
3762 auto *Var = new llvm::GlobalVariable(
3763 CGM.getModule(), TypeDescriptorType, /*Constant=*/false,
3764 getLinkageForRTTI(Type),
3765 llvm::ConstantStruct::get(TypeDescriptorType, Fields),
3766 StringRef(MangledName));
3767 if (Var->isWeakForLinker())
3768 Var->setComdat(CGM.getModule().getOrInsertComdat(Var->getName()));
3769 return llvm::ConstantExpr::getBitCast(Var, CGM.Int8PtrTy);
3772 /// \brief Gets or a creates a Microsoft CompleteObjectLocator.
3773 llvm::GlobalVariable *
3774 MicrosoftCXXABI::getMSCompleteObjectLocator(const CXXRecordDecl *RD,
3775 const VPtrInfo *Info) {
3776 return MSRTTIBuilder(*this, RD).getCompleteObjectLocator(Info);
3779 static void emitCXXConstructor(CodeGenModule &CGM,
3780 const CXXConstructorDecl *ctor,
3781 StructorType ctorType) {
3782 // There are no constructor variants, always emit the complete destructor.
3783 llvm::Function *Fn = CGM.codegenCXXStructor(ctor, StructorType::Complete);
3784 CGM.maybeSetTrivialComdat(*ctor, *Fn);
3787 static void emitCXXDestructor(CodeGenModule &CGM, const CXXDestructorDecl *dtor,
3788 StructorType dtorType) {
3789 // The complete destructor is equivalent to the base destructor for
3790 // classes with no virtual bases, so try to emit it as an alias.
3791 if (!dtor->getParent()->getNumVBases() &&
3792 (dtorType == StructorType::Complete || dtorType == StructorType::Base)) {
3793 bool ProducedAlias = !CGM.TryEmitDefinitionAsAlias(
3794 GlobalDecl(dtor, Dtor_Complete), GlobalDecl(dtor, Dtor_Base), true);
3795 if (ProducedAlias) {
3796 if (dtorType == StructorType::Complete)
3798 if (dtor->isVirtual())
3799 CGM.getVTables().EmitThunks(GlobalDecl(dtor, Dtor_Complete));
3803 // The base destructor is equivalent to the base destructor of its
3804 // base class if there is exactly one non-virtual base class with a
3805 // non-trivial destructor, there are no fields with a non-trivial
3806 // destructor, and the body of the destructor is trivial.
3807 if (dtorType == StructorType::Base && !CGM.TryEmitBaseDestructorAsAlias(dtor))
3810 llvm::Function *Fn = CGM.codegenCXXStructor(dtor, dtorType);
3811 if (Fn->isWeakForLinker())
3812 Fn->setComdat(CGM.getModule().getOrInsertComdat(Fn->getName()));
3815 void MicrosoftCXXABI::emitCXXStructor(const CXXMethodDecl *MD,
3816 StructorType Type) {
3817 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
3818 emitCXXConstructor(CGM, CD, Type);
3821 emitCXXDestructor(CGM, cast<CXXDestructorDecl>(MD), Type);
3825 MicrosoftCXXABI::getAddrOfCXXCtorClosure(const CXXConstructorDecl *CD,
3827 assert(CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure);
3829 // Calculate the mangled name.
3830 SmallString<256> ThunkName;
3831 llvm::raw_svector_ostream Out(ThunkName);
3832 getMangleContext().mangleCXXCtor(CD, CT, Out);
3834 // If the thunk has been generated previously, just return it.
3835 if (llvm::GlobalValue *GV = CGM.getModule().getNamedValue(ThunkName))
3836 return cast<llvm::Function>(GV);
3838 // Create the llvm::Function.
3839 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeMSCtorClosure(CD, CT);
3840 llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo);
3841 const CXXRecordDecl *RD = CD->getParent();
3842 QualType RecordTy = getContext().getRecordType(RD);
3843 llvm::Function *ThunkFn = llvm::Function::Create(
3844 ThunkTy, getLinkageForRTTI(RecordTy), ThunkName.str(), &CGM.getModule());
3845 ThunkFn->setCallingConv(static_cast<llvm::CallingConv::ID>(
3846 FnInfo.getEffectiveCallingConvention()));
3847 if (ThunkFn->isWeakForLinker())
3848 ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));
3849 bool IsCopy = CT == Ctor_CopyingClosure;
3852 CodeGenFunction CGF(CGM);
3853 CGF.CurGD = GlobalDecl(CD, Ctor_Complete);
3855 // Build FunctionArgs.
3856 FunctionArgList FunctionArgs;
3858 // A constructor always starts with a 'this' pointer as its first argument.
3859 buildThisParam(CGF, FunctionArgs);
3861 // Following the 'this' pointer is a reference to the source object that we
3862 // are copying from.
3863 ImplicitParamDecl SrcParam(
3864 getContext(), nullptr, SourceLocation(), &getContext().Idents.get("src"),
3865 getContext().getLValueReferenceType(RecordTy,
3866 /*SpelledAsLValue=*/true));
3868 FunctionArgs.push_back(&SrcParam);
3870 // Constructors for classes which utilize virtual bases have an additional
3871 // parameter which indicates whether or not it is being delegated to by a more
3872 // derived constructor.
3873 ImplicitParamDecl IsMostDerived(getContext(), nullptr, SourceLocation(),
3874 &getContext().Idents.get("is_most_derived"),
3875 getContext().IntTy);
3876 // Only add the parameter to the list if thie class has virtual bases.
3877 if (RD->getNumVBases() > 0)
3878 FunctionArgs.push_back(&IsMostDerived);
3880 // Start defining the function.
3881 CGF.StartFunction(GlobalDecl(), FnInfo.getReturnType(), ThunkFn, FnInfo,
3882 FunctionArgs, CD->getLocation(), SourceLocation());
3884 llvm::Value *This = getThisValue(CGF);
3886 llvm::Value *SrcVal =
3887 IsCopy ? CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&SrcParam), "src")
3892 // Push the this ptr.
3893 Args.add(RValue::get(This), CD->getThisType(getContext()));
3895 // Push the src ptr.
3897 Args.add(RValue::get(SrcVal), SrcParam.getType());
3899 // Add the rest of the default arguments.
3900 std::vector<Stmt *> ArgVec;
3901 for (unsigned I = IsCopy ? 1 : 0, E = CD->getNumParams(); I != E; ++I) {
3902 Stmt *DefaultArg = getContext().getDefaultArgExprForConstructor(CD, I);
3903 assert(DefaultArg && "sema forgot to instantiate default args");
3904 ArgVec.push_back(DefaultArg);
3907 CodeGenFunction::RunCleanupsScope Cleanups(CGF);
3909 const auto *FPT = CD->getType()->castAs<FunctionProtoType>();
3910 CGF.EmitCallArgs(Args, FPT, llvm::makeArrayRef(ArgVec), CD, IsCopy ? 1 : 0);
3912 // Insert any ABI-specific implicit constructor arguments.
3913 unsigned ExtraArgs = addImplicitConstructorArgs(CGF, CD, Ctor_Complete,
3914 /*ForVirtualBase=*/false,
3915 /*Delegating=*/false, Args);
3917 // Call the destructor with our arguments.
3918 llvm::Value *CalleeFn = CGM.getAddrOfCXXStructor(CD, StructorType::Complete);
3919 const CGFunctionInfo &CalleeInfo = CGM.getTypes().arrangeCXXConstructorCall(
3920 Args, CD, Ctor_Complete, ExtraArgs);
3921 CGF.EmitCall(CalleeInfo, CalleeFn, ReturnValueSlot(), Args, CD);
3923 Cleanups.ForceCleanup();
3925 // Emit the ret instruction, remove any temporary instructions created for the
3927 CGF.FinishFunction(SourceLocation());
3932 llvm::Constant *MicrosoftCXXABI::getCatchableType(QualType T,
3934 int32_t VBPtrOffset,
3936 assert(!T->isReferenceType());
3938 CXXRecordDecl *RD = T->getAsCXXRecordDecl();
3939 const CXXConstructorDecl *CD =
3940 RD ? CGM.getContext().getCopyConstructorForExceptionObject(RD) : nullptr;
3941 CXXCtorType CT = Ctor_Complete;
3943 if (!hasDefaultCXXMethodCC(getContext(), CD) || CD->getNumParams() != 1)
3944 CT = Ctor_CopyingClosure;
3946 uint32_t Size = getContext().getTypeSizeInChars(T).getQuantity();
3947 SmallString<256> MangledName;
3949 llvm::raw_svector_ostream Out(MangledName);
3950 getMangleContext().mangleCXXCatchableType(T, CD, CT, Size, NVOffset,
3951 VBPtrOffset, VBIndex, Out);
3953 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
3954 return getImageRelativeConstant(GV);
3956 // The TypeDescriptor is used by the runtime to determine if a catch handler
3957 // is appropriate for the exception object.
3958 llvm::Constant *TD = getImageRelativeConstant(getAddrOfRTTIDescriptor(T));
3960 // The runtime is responsible for calling the copy constructor if the
3961 // exception is caught by value.
3962 llvm::Constant *CopyCtor;
3964 if (CT == Ctor_CopyingClosure)
3965 CopyCtor = getAddrOfCXXCtorClosure(CD, Ctor_CopyingClosure);
3967 CopyCtor = CGM.getAddrOfCXXStructor(CD, StructorType::Complete);
3969 CopyCtor = llvm::ConstantExpr::getBitCast(CopyCtor, CGM.Int8PtrTy);
3971 CopyCtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);
3973 CopyCtor = getImageRelativeConstant(CopyCtor);
3975 bool IsScalar = !RD;
3976 bool HasVirtualBases = false;
3977 bool IsStdBadAlloc = false; // std::bad_alloc is special for some reason.
3978 QualType PointeeType = T;
3979 if (T->isPointerType())
3980 PointeeType = T->getPointeeType();
3981 if (const CXXRecordDecl *RD = PointeeType->getAsCXXRecordDecl()) {
3982 HasVirtualBases = RD->getNumVBases() > 0;
3983 if (IdentifierInfo *II = RD->getIdentifier())
3984 IsStdBadAlloc = II->isStr("bad_alloc") && RD->isInStdNamespace();
3987 // Encode the relevant CatchableType properties into the Flags bitfield.
3988 // FIXME: Figure out how bits 2 or 8 can get set.
3992 if (HasVirtualBases)
3997 llvm::Constant *Fields[] = {
3998 llvm::ConstantInt::get(CGM.IntTy, Flags), // Flags
3999 TD, // TypeDescriptor
4000 llvm::ConstantInt::get(CGM.IntTy, NVOffset), // NonVirtualAdjustment
4001 llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset), // OffsetToVBPtr
4002 llvm::ConstantInt::get(CGM.IntTy, VBIndex), // VBTableIndex
4003 llvm::ConstantInt::get(CGM.IntTy, Size), // Size
4004 CopyCtor // CopyCtor
4006 llvm::StructType *CTType = getCatchableTypeType();
4007 auto *GV = new llvm::GlobalVariable(
4008 CGM.getModule(), CTType, /*Constant=*/true, getLinkageForRTTI(T),
4009 llvm::ConstantStruct::get(CTType, Fields), StringRef(MangledName));
4010 GV->setUnnamedAddr(true);
4011 GV->setSection(".xdata");
4012 if (GV->isWeakForLinker())
4013 GV->setComdat(CGM.getModule().getOrInsertComdat(GV->getName()));
4014 return getImageRelativeConstant(GV);
4017 llvm::GlobalVariable *MicrosoftCXXABI::getCatchableTypeArray(QualType T) {
4018 assert(!T->isReferenceType());
4020 // See if we've already generated a CatchableTypeArray for this type before.
4021 llvm::GlobalVariable *&CTA = CatchableTypeArrays[T];
4025 // Ensure that we don't have duplicate entries in our CatchableTypeArray by
4026 // using a SmallSetVector. Duplicates may arise due to virtual bases
4027 // occurring more than once in the hierarchy.
4028 llvm::SmallSetVector<llvm::Constant *, 2> CatchableTypes;
4030 // C++14 [except.handle]p3:
4031 // A handler is a match for an exception object of type E if [...]
4032 // - the handler is of type cv T or cv T& and T is an unambiguous public
4033 // base class of E, or
4034 // - the handler is of type cv T or const T& where T is a pointer type and
4035 // E is a pointer type that can be converted to T by [...]
4036 // - a standard pointer conversion (4.10) not involving conversions to
4037 // pointers to private or protected or ambiguous classes
4038 const CXXRecordDecl *MostDerivedClass = nullptr;
4039 bool IsPointer = T->isPointerType();
4041 MostDerivedClass = T->getPointeeType()->getAsCXXRecordDecl();
4043 MostDerivedClass = T->getAsCXXRecordDecl();
4045 // Collect all the unambiguous public bases of the MostDerivedClass.
4046 if (MostDerivedClass) {
4047 const ASTContext &Context = getContext();
4048 const ASTRecordLayout &MostDerivedLayout =
4049 Context.getASTRecordLayout(MostDerivedClass);
4050 MicrosoftVTableContext &VTableContext = CGM.getMicrosoftVTableContext();
4051 SmallVector<MSRTTIClass, 8> Classes;
4052 serializeClassHierarchy(Classes, MostDerivedClass);
4053 Classes.front().initialize(/*Parent=*/nullptr, /*Specifier=*/nullptr);
4054 detectAmbiguousBases(Classes);
4055 for (const MSRTTIClass &Class : Classes) {
4056 // Skip any ambiguous or private bases.
4058 (MSRTTIClass::IsPrivateOnPath | MSRTTIClass::IsAmbiguous))
4060 // Write down how to convert from a derived pointer to a base pointer.
4061 uint32_t OffsetInVBTable = 0;
4062 int32_t VBPtrOffset = -1;
4063 if (Class.VirtualRoot) {
4065 VTableContext.getVBTableIndex(MostDerivedClass, Class.VirtualRoot)*4;
4066 VBPtrOffset = MostDerivedLayout.getVBPtrOffset().getQuantity();
4069 // Turn our record back into a pointer if the exception object is a
4071 QualType RTTITy = QualType(Class.RD->getTypeForDecl(), 0);
4073 RTTITy = Context.getPointerType(RTTITy);
4074 CatchableTypes.insert(getCatchableType(RTTITy, Class.OffsetInVBase,
4075 VBPtrOffset, OffsetInVBTable));
4079 // C++14 [except.handle]p3:
4080 // A handler is a match for an exception object of type E if
4081 // - The handler is of type cv T or cv T& and E and T are the same type
4082 // (ignoring the top-level cv-qualifiers)
4083 CatchableTypes.insert(getCatchableType(T));
4085 // C++14 [except.handle]p3:
4086 // A handler is a match for an exception object of type E if
4087 // - the handler is of type cv T or const T& where T is a pointer type and
4088 // E is a pointer type that can be converted to T by [...]
4089 // - a standard pointer conversion (4.10) not involving conversions to
4090 // pointers to private or protected or ambiguous classes
4092 // C++14 [conv.ptr]p2:
4093 // A prvalue of type "pointer to cv T," where T is an object type, can be
4094 // converted to a prvalue of type "pointer to cv void".
4095 if (IsPointer && T->getPointeeType()->isObjectType())
4096 CatchableTypes.insert(getCatchableType(getContext().VoidPtrTy));
4098 // C++14 [except.handle]p3:
4099 // A handler is a match for an exception object of type E if [...]
4100 // - the handler is of type cv T or const T& where T is a pointer or
4101 // pointer to member type and E is std::nullptr_t.
4103 // We cannot possibly list all possible pointer types here, making this
4104 // implementation incompatible with the standard. However, MSVC includes an
4105 // entry for pointer-to-void in this case. Let's do the same.
4106 if (T->isNullPtrType())
4107 CatchableTypes.insert(getCatchableType(getContext().VoidPtrTy));
4109 uint32_t NumEntries = CatchableTypes.size();
4110 llvm::Type *CTType =
4111 getImageRelativeType(getCatchableTypeType()->getPointerTo());
4112 llvm::ArrayType *AT = llvm::ArrayType::get(CTType, NumEntries);
4113 llvm::StructType *CTAType = getCatchableTypeArrayType(NumEntries);
4114 llvm::Constant *Fields[] = {
4115 llvm::ConstantInt::get(CGM.IntTy, NumEntries), // NumEntries
4116 llvm::ConstantArray::get(
4117 AT, llvm::makeArrayRef(CatchableTypes.begin(),
4118 CatchableTypes.end())) // CatchableTypes
4120 SmallString<256> MangledName;
4122 llvm::raw_svector_ostream Out(MangledName);
4123 getMangleContext().mangleCXXCatchableTypeArray(T, NumEntries, Out);
4125 CTA = new llvm::GlobalVariable(
4126 CGM.getModule(), CTAType, /*Constant=*/true, getLinkageForRTTI(T),
4127 llvm::ConstantStruct::get(CTAType, Fields), StringRef(MangledName));
4128 CTA->setUnnamedAddr(true);
4129 CTA->setSection(".xdata");
4130 if (CTA->isWeakForLinker())
4131 CTA->setComdat(CGM.getModule().getOrInsertComdat(CTA->getName()));
4135 llvm::GlobalVariable *MicrosoftCXXABI::getThrowInfo(QualType T) {
4136 bool IsConst, IsVolatile;
4137 T = decomposeTypeForEH(getContext(), T, IsConst, IsVolatile);
4139 // The CatchableTypeArray enumerates the various (CV-unqualified) types that
4140 // the exception object may be caught as.
4141 llvm::GlobalVariable *CTA = getCatchableTypeArray(T);
4142 // The first field in a CatchableTypeArray is the number of CatchableTypes.
4143 // This is used as a component of the mangled name which means that we need to
4144 // know what it is in order to see if we have previously generated the
4146 uint32_t NumEntries =
4147 cast<llvm::ConstantInt>(CTA->getInitializer()->getAggregateElement(0U))
4148 ->getLimitedValue();
4150 SmallString<256> MangledName;
4152 llvm::raw_svector_ostream Out(MangledName);
4153 getMangleContext().mangleCXXThrowInfo(T, IsConst, IsVolatile, NumEntries,
4157 // Reuse a previously generated ThrowInfo if we have generated an appropriate
4159 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
4162 // The RTTI TypeDescriptor uses an unqualified type but catch clauses must
4163 // be at least as CV qualified. Encode this requirement into the Flags
4171 // The cleanup-function (a destructor) must be called when the exception
4172 // object's lifetime ends.
4173 llvm::Constant *CleanupFn = llvm::Constant::getNullValue(CGM.Int8PtrTy);
4174 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4175 if (CXXDestructorDecl *DtorD = RD->getDestructor())
4176 if (!DtorD->isTrivial())
4177 CleanupFn = llvm::ConstantExpr::getBitCast(
4178 CGM.getAddrOfCXXStructor(DtorD, StructorType::Complete),
4180 // This is unused as far as we can tell, initialize it to null.
4181 llvm::Constant *ForwardCompat =
4182 getImageRelativeConstant(llvm::Constant::getNullValue(CGM.Int8PtrTy));
4183 llvm::Constant *PointerToCatchableTypes = getImageRelativeConstant(
4184 llvm::ConstantExpr::getBitCast(CTA, CGM.Int8PtrTy));
4185 llvm::StructType *TIType = getThrowInfoType();
4186 llvm::Constant *Fields[] = {
4187 llvm::ConstantInt::get(CGM.IntTy, Flags), // Flags
4188 getImageRelativeConstant(CleanupFn), // CleanupFn
4189 ForwardCompat, // ForwardCompat
4190 PointerToCatchableTypes // CatchableTypeArray
4192 auto *GV = new llvm::GlobalVariable(
4193 CGM.getModule(), TIType, /*Constant=*/true, getLinkageForRTTI(T),
4194 llvm::ConstantStruct::get(TIType, Fields), StringRef(MangledName));
4195 GV->setUnnamedAddr(true);
4196 GV->setSection(".xdata");
4197 if (GV->isWeakForLinker())
4198 GV->setComdat(CGM.getModule().getOrInsertComdat(GV->getName()));
4202 void MicrosoftCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
4203 const Expr *SubExpr = E->getSubExpr();
4204 QualType ThrowType = SubExpr->getType();
4205 // The exception object lives on the stack and it's address is passed to the
4206 // runtime function.
4207 Address AI = CGF.CreateMemTemp(ThrowType);
4208 CGF.EmitAnyExprToMem(SubExpr, AI, ThrowType.getQualifiers(),
4211 // The so-called ThrowInfo is used to describe how the exception object may be
4213 llvm::GlobalVariable *TI = getThrowInfo(ThrowType);
4215 // Call into the runtime to throw the exception.
4216 llvm::Value *Args[] = {
4217 CGF.Builder.CreateBitCast(AI.getPointer(), CGM.Int8PtrTy),
4220 CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(), Args);