Rename GetLanguageInfo to GetLanguageSpecificData (#117012)
[llvm-project.git] / clang / lib / CodeGen / MicrosoftCXXABI.cpp
blobd587daac5a88a9ffdbfb2ac14ad1b4cee96698ef
1 //===--- MicrosoftCXXABI.cpp - Emit LLVM Code from ASTs for a Module ------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This provides C++ code generation targeting the Microsoft Visual C++ ABI.
10 // The class in this file generates structures that follow the Microsoft
11 // Visual C++ ABI, which is actually not very well documented at all outside
12 // of Microsoft.
14 //===----------------------------------------------------------------------===//
16 #include "ABIInfo.h"
17 #include "CGCXXABI.h"
18 #include "CGCleanup.h"
19 #include "CGVTables.h"
20 #include "CodeGenModule.h"
21 #include "CodeGenTypes.h"
22 #include "TargetInfo.h"
23 #include "clang/AST/Attr.h"
24 #include "clang/AST/CXXInheritance.h"
25 #include "clang/AST/Decl.h"
26 #include "clang/AST/DeclCXX.h"
27 #include "clang/AST/StmtCXX.h"
28 #include "clang/AST/VTableBuilder.h"
29 #include "clang/CodeGen/ConstantInitBuilder.h"
30 #include "llvm/ADT/StringExtras.h"
31 #include "llvm/ADT/StringSet.h"
32 #include "llvm/IR/Intrinsics.h"
34 using namespace clang;
35 using namespace CodeGen;
37 namespace {
39 /// Holds all the vbtable globals for a given class.
40 struct VBTableGlobals {
41 const VPtrInfoVector *VBTables;
42 SmallVector<llvm::GlobalVariable *, 2> Globals;
45 class MicrosoftCXXABI : public CGCXXABI {
46 public:
47 MicrosoftCXXABI(CodeGenModule &CGM)
48 : CGCXXABI(CGM), BaseClassDescriptorType(nullptr),
49 ClassHierarchyDescriptorType(nullptr),
50 CompleteObjectLocatorType(nullptr), CatchableTypeType(nullptr),
51 ThrowInfoType(nullptr) {
52 assert(!(CGM.getLangOpts().isExplicitDefaultVisibilityExportMapping() ||
53 CGM.getLangOpts().isAllDefaultVisibilityExportMapping()) &&
54 "visibility export mapping option unimplemented in this ABI");
57 bool HasThisReturn(GlobalDecl GD) const override;
58 bool hasMostDerivedReturn(GlobalDecl GD) const override;
60 bool classifyReturnType(CGFunctionInfo &FI) const override;
62 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override;
64 bool isSRetParameterAfterThis() const override { return true; }
66 bool isThisCompleteObject(GlobalDecl GD) const override {
67 // The Microsoft ABI doesn't use separate complete-object vs.
68 // base-object variants of constructors, but it does of destructors.
69 if (isa<CXXDestructorDecl>(GD.getDecl())) {
70 switch (GD.getDtorType()) {
71 case Dtor_Complete:
72 case Dtor_Deleting:
73 return true;
75 case Dtor_Base:
76 return false;
78 case Dtor_Comdat: llvm_unreachable("emitting dtor comdat as function?");
80 llvm_unreachable("bad dtor kind");
83 // No other kinds.
84 return false;
87 size_t getSrcArgforCopyCtor(const CXXConstructorDecl *CD,
88 FunctionArgList &Args) const override {
89 assert(Args.size() >= 2 &&
90 "expected the arglist to have at least two args!");
91 // The 'most_derived' parameter goes second if the ctor is variadic and
92 // has v-bases.
93 if (CD->getParent()->getNumVBases() > 0 &&
94 CD->getType()->castAs<FunctionProtoType>()->isVariadic())
95 return 2;
96 return 1;
99 std::vector<CharUnits> getVBPtrOffsets(const CXXRecordDecl *RD) override {
100 std::vector<CharUnits> VBPtrOffsets;
101 const ASTContext &Context = getContext();
102 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
104 const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
105 for (const std::unique_ptr<VPtrInfo> &VBT : *VBGlobals.VBTables) {
106 const ASTRecordLayout &SubobjectLayout =
107 Context.getASTRecordLayout(VBT->IntroducingObject);
108 CharUnits Offs = VBT->NonVirtualOffset;
109 Offs += SubobjectLayout.getVBPtrOffset();
110 if (VBT->getVBaseWithVPtr())
111 Offs += Layout.getVBaseClassOffset(VBT->getVBaseWithVPtr());
112 VBPtrOffsets.push_back(Offs);
114 llvm::array_pod_sort(VBPtrOffsets.begin(), VBPtrOffsets.end());
115 return VBPtrOffsets;
118 StringRef GetPureVirtualCallName() override { return "_purecall"; }
119 StringRef GetDeletedVirtualCallName() override { return "_purecall"; }
121 void emitVirtualObjectDelete(CodeGenFunction &CGF, const CXXDeleteExpr *DE,
122 Address Ptr, QualType ElementType,
123 const CXXDestructorDecl *Dtor) override;
125 void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) override;
126 void emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) override;
128 void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override;
130 llvm::GlobalVariable *getMSCompleteObjectLocator(const CXXRecordDecl *RD,
131 const VPtrInfo &Info);
133 llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override;
134 CatchTypeInfo
135 getAddrOfCXXCatchHandlerType(QualType Ty, QualType CatchHandlerType) override;
137 /// MSVC needs an extra flag to indicate a catchall.
138 CatchTypeInfo getCatchAllTypeInfo() override {
139 // For -EHa catch(...) must handle HW exception
140 // Adjective = HT_IsStdDotDot (0x40), only catch C++ exceptions
141 if (getContext().getLangOpts().EHAsynch)
142 return CatchTypeInfo{nullptr, 0};
143 else
144 return CatchTypeInfo{nullptr, 0x40};
147 bool shouldTypeidBeNullChecked(QualType SrcRecordTy) override;
148 void EmitBadTypeidCall(CodeGenFunction &CGF) override;
149 llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
150 Address ThisPtr,
151 llvm::Type *StdTypeInfoPtrTy) override;
153 bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
154 QualType SrcRecordTy) override;
156 bool shouldEmitExactDynamicCast(QualType DestRecordTy) override {
157 // TODO: Add support for exact dynamic_casts.
158 return false;
160 llvm::Value *emitExactDynamicCast(CodeGenFunction &CGF, Address Value,
161 QualType SrcRecordTy, QualType DestTy,
162 QualType DestRecordTy,
163 llvm::BasicBlock *CastSuccess,
164 llvm::BasicBlock *CastFail) override {
165 llvm_unreachable("unsupported");
168 llvm::Value *emitDynamicCastCall(CodeGenFunction &CGF, Address Value,
169 QualType SrcRecordTy, QualType DestTy,
170 QualType DestRecordTy,
171 llvm::BasicBlock *CastEnd) override;
173 llvm::Value *emitDynamicCastToVoid(CodeGenFunction &CGF, Address Value,
174 QualType SrcRecordTy) override;
176 bool EmitBadCastCall(CodeGenFunction &CGF) override;
177 bool canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const override {
178 return false;
181 llvm::Value *
182 GetVirtualBaseClassOffset(CodeGenFunction &CGF, Address This,
183 const CXXRecordDecl *ClassDecl,
184 const CXXRecordDecl *BaseClassDecl) override;
186 llvm::BasicBlock *
187 EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
188 const CXXRecordDecl *RD) override;
190 llvm::BasicBlock *
191 EmitDtorCompleteObjectHandler(CodeGenFunction &CGF);
193 void initializeHiddenVirtualInheritanceMembers(CodeGenFunction &CGF,
194 const CXXRecordDecl *RD) override;
196 void EmitCXXConstructors(const CXXConstructorDecl *D) override;
198 // Background on MSVC destructors
199 // ==============================
201 // Both Itanium and MSVC ABIs have destructor variants. The variant names
202 // roughly correspond in the following way:
203 // Itanium Microsoft
204 // Base -> no name, just ~Class
205 // Complete -> vbase destructor
206 // Deleting -> scalar deleting destructor
207 // vector deleting destructor
209 // The base and complete destructors are the same as in Itanium, although the
210 // complete destructor does not accept a VTT parameter when there are virtual
211 // bases. A separate mechanism involving vtordisps is used to ensure that
212 // virtual methods of destroyed subobjects are not called.
214 // The deleting destructors accept an i32 bitfield as a second parameter. Bit
215 // 1 indicates if the memory should be deleted. Bit 2 indicates if the this
216 // pointer points to an array. The scalar deleting destructor assumes that
217 // bit 2 is zero, and therefore does not contain a loop.
219 // For virtual destructors, only one entry is reserved in the vftable, and it
220 // always points to the vector deleting destructor. The vector deleting
221 // destructor is the most general, so it can be used to destroy objects in
222 // place, delete single heap objects, or delete arrays.
224 // A TU defining a non-inline destructor is only guaranteed to emit a base
225 // destructor, and all of the other variants are emitted on an as-needed basis
226 // in COMDATs. Because a non-base destructor can be emitted in a TU that
227 // lacks a definition for the destructor, non-base destructors must always
228 // delegate to or alias the base destructor.
230 AddedStructorArgCounts
231 buildStructorSignature(GlobalDecl GD,
232 SmallVectorImpl<CanQualType> &ArgTys) override;
234 /// Non-base dtors should be emitted as delegating thunks in this ABI.
235 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
236 CXXDtorType DT) const override {
237 return DT != Dtor_Base;
240 void setCXXDestructorDLLStorage(llvm::GlobalValue *GV,
241 const CXXDestructorDecl *Dtor,
242 CXXDtorType DT) const override;
244 llvm::GlobalValue::LinkageTypes
245 getCXXDestructorLinkage(GVALinkage Linkage, const CXXDestructorDecl *Dtor,
246 CXXDtorType DT) const override;
248 void EmitCXXDestructors(const CXXDestructorDecl *D) override;
250 const CXXRecordDecl *getThisArgumentTypeForMethod(GlobalDecl GD) override {
251 auto *MD = cast<CXXMethodDecl>(GD.getDecl());
253 if (MD->isVirtual()) {
254 GlobalDecl LookupGD = GD;
255 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
256 // Complete dtors take a pointer to the complete object,
257 // thus don't need adjustment.
258 if (GD.getDtorType() == Dtor_Complete)
259 return MD->getParent();
261 // There's only Dtor_Deleting in vftable but it shares the this
262 // adjustment with the base one, so look up the deleting one instead.
263 LookupGD = GlobalDecl(DD, Dtor_Deleting);
265 MethodVFTableLocation ML =
266 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD);
268 // The vbases might be ordered differently in the final overrider object
269 // and the complete object, so the "this" argument may sometimes point to
270 // memory that has no particular type (e.g. past the complete object).
271 // In this case, we just use a generic pointer type.
272 // FIXME: might want to have a more precise type in the non-virtual
273 // multiple inheritance case.
274 if (ML.VBase || !ML.VFPtrOffset.isZero())
275 return nullptr;
277 return MD->getParent();
280 Address
281 adjustThisArgumentForVirtualFunctionCall(CodeGenFunction &CGF, GlobalDecl GD,
282 Address This,
283 bool VirtualCall) override;
285 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
286 FunctionArgList &Params) override;
288 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
290 AddedStructorArgs getImplicitConstructorArgs(CodeGenFunction &CGF,
291 const CXXConstructorDecl *D,
292 CXXCtorType Type,
293 bool ForVirtualBase,
294 bool Delegating) override;
296 llvm::Value *getCXXDestructorImplicitParam(CodeGenFunction &CGF,
297 const CXXDestructorDecl *DD,
298 CXXDtorType Type,
299 bool ForVirtualBase,
300 bool Delegating) override;
302 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
303 CXXDtorType Type, bool ForVirtualBase,
304 bool Delegating, Address This,
305 QualType ThisTy) override;
307 void emitVTableTypeMetadata(const VPtrInfo &Info, const CXXRecordDecl *RD,
308 llvm::GlobalVariable *VTable);
310 void emitVTableDefinitions(CodeGenVTables &CGVT,
311 const CXXRecordDecl *RD) override;
313 bool isVirtualOffsetNeededForVTableField(CodeGenFunction &CGF,
314 CodeGenFunction::VPtr Vptr) override;
316 /// Don't initialize vptrs if dynamic class
317 /// is marked with the 'novtable' attribute.
318 bool doStructorsInitializeVPtrs(const CXXRecordDecl *VTableClass) override {
319 return !VTableClass->hasAttr<MSNoVTableAttr>();
322 llvm::Constant *
323 getVTableAddressPoint(BaseSubobject Base,
324 const CXXRecordDecl *VTableClass) override;
326 llvm::Value *getVTableAddressPointInStructor(
327 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
328 BaseSubobject Base, const CXXRecordDecl *NearestVBase) override;
330 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
331 CharUnits VPtrOffset) override;
333 CGCallee getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
334 Address This, llvm::Type *Ty,
335 SourceLocation Loc) override;
337 llvm::Value *
338 EmitVirtualDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *Dtor,
339 CXXDtorType DtorType, Address This,
340 DeleteOrMemberCallExpr E,
341 llvm::CallBase **CallOrInvoke) override;
343 void adjustCallArgsForDestructorThunk(CodeGenFunction &CGF, GlobalDecl GD,
344 CallArgList &CallArgs) override {
345 assert(GD.getDtorType() == Dtor_Deleting &&
346 "Only deleting destructor thunks are available in this ABI");
347 CallArgs.add(RValue::get(getStructorImplicitParamValue(CGF)),
348 getContext().IntTy);
351 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
353 llvm::GlobalVariable *
354 getAddrOfVBTable(const VPtrInfo &VBT, const CXXRecordDecl *RD,
355 llvm::GlobalVariable::LinkageTypes Linkage);
357 llvm::GlobalVariable *
358 getAddrOfVirtualDisplacementMap(const CXXRecordDecl *SrcRD,
359 const CXXRecordDecl *DstRD) {
360 SmallString<256> OutName;
361 llvm::raw_svector_ostream Out(OutName);
362 getMangleContext().mangleCXXVirtualDisplacementMap(SrcRD, DstRD, Out);
363 StringRef MangledName = OutName.str();
365 if (auto *VDispMap = CGM.getModule().getNamedGlobal(MangledName))
366 return VDispMap;
368 MicrosoftVTableContext &VTContext = CGM.getMicrosoftVTableContext();
369 unsigned NumEntries = 1 + SrcRD->getNumVBases();
370 SmallVector<llvm::Constant *, 4> Map(NumEntries,
371 llvm::UndefValue::get(CGM.IntTy));
372 Map[0] = llvm::ConstantInt::get(CGM.IntTy, 0);
373 bool AnyDifferent = false;
374 for (const auto &I : SrcRD->vbases()) {
375 const CXXRecordDecl *VBase = I.getType()->getAsCXXRecordDecl();
376 if (!DstRD->isVirtuallyDerivedFrom(VBase))
377 continue;
379 unsigned SrcVBIndex = VTContext.getVBTableIndex(SrcRD, VBase);
380 unsigned DstVBIndex = VTContext.getVBTableIndex(DstRD, VBase);
381 Map[SrcVBIndex] = llvm::ConstantInt::get(CGM.IntTy, DstVBIndex * 4);
382 AnyDifferent |= SrcVBIndex != DstVBIndex;
384 // This map would be useless, don't use it.
385 if (!AnyDifferent)
386 return nullptr;
388 llvm::ArrayType *VDispMapTy = llvm::ArrayType::get(CGM.IntTy, Map.size());
389 llvm::Constant *Init = llvm::ConstantArray::get(VDispMapTy, Map);
390 llvm::GlobalValue::LinkageTypes Linkage =
391 SrcRD->isExternallyVisible() && DstRD->isExternallyVisible()
392 ? llvm::GlobalValue::LinkOnceODRLinkage
393 : llvm::GlobalValue::InternalLinkage;
394 auto *VDispMap = new llvm::GlobalVariable(
395 CGM.getModule(), VDispMapTy, /*isConstant=*/true, Linkage,
396 /*Initializer=*/Init, MangledName);
397 return VDispMap;
400 void emitVBTableDefinition(const VPtrInfo &VBT, const CXXRecordDecl *RD,
401 llvm::GlobalVariable *GV) const;
403 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable,
404 GlobalDecl GD, bool ReturnAdjustment) override {
405 GVALinkage Linkage =
406 getContext().GetGVALinkageForFunction(cast<FunctionDecl>(GD.getDecl()));
408 if (Linkage == GVA_Internal)
409 Thunk->setLinkage(llvm::GlobalValue::InternalLinkage);
410 else if (ReturnAdjustment)
411 Thunk->setLinkage(llvm::GlobalValue::WeakODRLinkage);
412 else
413 Thunk->setLinkage(llvm::GlobalValue::LinkOnceODRLinkage);
416 bool exportThunk() override { return false; }
418 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, Address This,
419 const CXXRecordDecl * /*UnadjustedClass*/,
420 const ThunkInfo &TI) override;
422 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
423 const CXXRecordDecl * /*UnadjustedClass*/,
424 const ReturnAdjustment &RA) override;
426 void EmitThreadLocalInitFuncs(
427 CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
428 ArrayRef<llvm::Function *> CXXThreadLocalInits,
429 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) override;
431 bool usesThreadWrapperFunction(const VarDecl *VD) const override {
432 return getContext().getLangOpts().isCompatibleWithMSVC(
433 LangOptions::MSVC2019_5) &&
434 CGM.getCodeGenOpts().TlsGuards &&
435 (!isEmittedWithConstantInitializer(VD) || mayNeedDestruction(VD));
437 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
438 QualType LValType) override;
440 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
441 llvm::GlobalVariable *DeclPtr,
442 bool PerformInit) override;
443 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
444 llvm::FunctionCallee Dtor,
445 llvm::Constant *Addr) override;
447 // ==== Notes on array cookies =========
449 // MSVC seems to only use cookies when the class has a destructor; a
450 // two-argument usual array deallocation function isn't sufficient.
452 // For example, this code prints "100" and "1":
453 // struct A {
454 // char x;
455 // void *operator new[](size_t sz) {
456 // printf("%u\n", sz);
457 // return malloc(sz);
458 // }
459 // void operator delete[](void *p, size_t sz) {
460 // printf("%u\n", sz);
461 // free(p);
462 // }
463 // };
464 // int main() {
465 // A *p = new A[100];
466 // delete[] p;
467 // }
468 // Whereas it prints "104" and "104" if you give A a destructor.
470 bool requiresArrayCookie(const CXXDeleteExpr *expr,
471 QualType elementType) override;
472 bool requiresArrayCookie(const CXXNewExpr *expr) override;
473 CharUnits getArrayCookieSizeImpl(QualType type) override;
474 Address InitializeArrayCookie(CodeGenFunction &CGF,
475 Address NewPtr,
476 llvm::Value *NumElements,
477 const CXXNewExpr *expr,
478 QualType ElementType) override;
479 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
480 Address allocPtr,
481 CharUnits cookieSize) override;
483 friend struct MSRTTIBuilder;
485 bool isImageRelative() const {
486 return CGM.getTarget().getPointerWidth(LangAS::Default) == 64;
489 // 5 routines for constructing the llvm types for MS RTTI structs.
490 llvm::StructType *getTypeDescriptorType(StringRef TypeInfoString) {
491 llvm::SmallString<32> TDTypeName("rtti.TypeDescriptor");
492 TDTypeName += llvm::utostr(TypeInfoString.size());
493 llvm::StructType *&TypeDescriptorType =
494 TypeDescriptorTypeMap[TypeInfoString.size()];
495 if (TypeDescriptorType)
496 return TypeDescriptorType;
497 llvm::Type *FieldTypes[] = {
498 CGM.Int8PtrPtrTy,
499 CGM.Int8PtrTy,
500 llvm::ArrayType::get(CGM.Int8Ty, TypeInfoString.size() + 1)};
501 TypeDescriptorType =
502 llvm::StructType::create(CGM.getLLVMContext(), FieldTypes, TDTypeName);
503 return TypeDescriptorType;
506 llvm::Type *getImageRelativeType(llvm::Type *PtrType) {
507 if (!isImageRelative())
508 return PtrType;
509 return CGM.IntTy;
512 llvm::StructType *getBaseClassDescriptorType() {
513 if (BaseClassDescriptorType)
514 return BaseClassDescriptorType;
515 llvm::Type *FieldTypes[] = {
516 getImageRelativeType(CGM.Int8PtrTy),
517 CGM.IntTy,
518 CGM.IntTy,
519 CGM.IntTy,
520 CGM.IntTy,
521 CGM.IntTy,
522 getImageRelativeType(CGM.UnqualPtrTy),
524 BaseClassDescriptorType = llvm::StructType::create(
525 CGM.getLLVMContext(), FieldTypes, "rtti.BaseClassDescriptor");
526 return BaseClassDescriptorType;
529 llvm::StructType *getClassHierarchyDescriptorType() {
530 if (ClassHierarchyDescriptorType)
531 return ClassHierarchyDescriptorType;
532 // Forward-declare RTTIClassHierarchyDescriptor to break a cycle.
533 llvm::Type *FieldTypes[] = {CGM.IntTy, CGM.IntTy, CGM.IntTy,
534 getImageRelativeType(CGM.UnqualPtrTy)};
535 ClassHierarchyDescriptorType =
536 llvm::StructType::create(FieldTypes, "rtti.ClassHierarchyDescriptor");
537 return ClassHierarchyDescriptorType;
540 llvm::StructType *getCompleteObjectLocatorType() {
541 if (CompleteObjectLocatorType)
542 return CompleteObjectLocatorType;
543 llvm::Type *FieldTypes[] = {
544 CGM.IntTy,
545 CGM.IntTy,
546 CGM.IntTy,
547 getImageRelativeType(CGM.Int8PtrTy),
548 getImageRelativeType(CGM.UnqualPtrTy),
549 getImageRelativeType(CGM.VoidTy),
551 llvm::ArrayRef<llvm::Type *> FieldTypesRef(FieldTypes);
552 if (!isImageRelative())
553 FieldTypesRef = FieldTypesRef.drop_back();
554 CompleteObjectLocatorType =
555 llvm::StructType::create(FieldTypesRef, "rtti.CompleteObjectLocator");
556 return CompleteObjectLocatorType;
559 llvm::GlobalVariable *getImageBase() {
560 StringRef Name = "__ImageBase";
561 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name))
562 return GV;
564 auto *GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty,
565 /*isConstant=*/true,
566 llvm::GlobalValue::ExternalLinkage,
567 /*Initializer=*/nullptr, Name);
568 CGM.setDSOLocal(GV);
569 return GV;
572 llvm::Constant *getImageRelativeConstant(llvm::Constant *PtrVal) {
573 if (!isImageRelative())
574 return PtrVal;
576 if (PtrVal->isNullValue())
577 return llvm::Constant::getNullValue(CGM.IntTy);
579 llvm::Constant *ImageBaseAsInt =
580 llvm::ConstantExpr::getPtrToInt(getImageBase(), CGM.IntPtrTy);
581 llvm::Constant *PtrValAsInt =
582 llvm::ConstantExpr::getPtrToInt(PtrVal, CGM.IntPtrTy);
583 llvm::Constant *Diff =
584 llvm::ConstantExpr::getSub(PtrValAsInt, ImageBaseAsInt,
585 /*HasNUW=*/true, /*HasNSW=*/true);
586 return llvm::ConstantExpr::getTrunc(Diff, CGM.IntTy);
589 private:
590 MicrosoftMangleContext &getMangleContext() {
591 return cast<MicrosoftMangleContext>(CodeGen::CGCXXABI::getMangleContext());
594 llvm::Constant *getZeroInt() {
595 return llvm::ConstantInt::get(CGM.IntTy, 0);
598 llvm::Constant *getAllOnesInt() {
599 return llvm::Constant::getAllOnesValue(CGM.IntTy);
602 CharUnits getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD) override;
604 void
605 GetNullMemberPointerFields(const MemberPointerType *MPT,
606 llvm::SmallVectorImpl<llvm::Constant *> &fields);
608 /// Shared code for virtual base adjustment. Returns the offset from
609 /// the vbptr to the virtual base. Optionally returns the address of the
610 /// vbptr itself.
611 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
612 Address Base,
613 llvm::Value *VBPtrOffset,
614 llvm::Value *VBTableOffset,
615 llvm::Value **VBPtr = nullptr);
617 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
618 Address Base,
619 int32_t VBPtrOffset,
620 int32_t VBTableOffset,
621 llvm::Value **VBPtr = nullptr) {
622 assert(VBTableOffset % 4 == 0 && "should be byte offset into table of i32s");
623 llvm::Value *VBPOffset = llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset),
624 *VBTOffset = llvm::ConstantInt::get(CGM.IntTy, VBTableOffset);
625 return GetVBaseOffsetFromVBPtr(CGF, Base, VBPOffset, VBTOffset, VBPtr);
628 std::tuple<Address, llvm::Value *, const CXXRecordDecl *>
629 performBaseAdjustment(CodeGenFunction &CGF, Address Value,
630 QualType SrcRecordTy);
632 /// Performs a full virtual base adjustment. Used to dereference
633 /// pointers to members of virtual bases.
634 llvm::Value *AdjustVirtualBase(CodeGenFunction &CGF, const Expr *E,
635 const CXXRecordDecl *RD, Address Base,
636 llvm::Value *VirtualBaseAdjustmentOffset,
637 llvm::Value *VBPtrOffset /* optional */);
639 /// Emits a full member pointer with the fields common to data and
640 /// function member pointers.
641 llvm::Constant *EmitFullMemberPointer(llvm::Constant *FirstField,
642 bool IsMemberFunction,
643 const CXXRecordDecl *RD,
644 CharUnits NonVirtualBaseAdjustment,
645 unsigned VBTableIndex);
647 bool MemberPointerConstantIsNull(const MemberPointerType *MPT,
648 llvm::Constant *MP);
650 /// - Initialize all vbptrs of 'this' with RD as the complete type.
651 void EmitVBPtrStores(CodeGenFunction &CGF, const CXXRecordDecl *RD);
653 /// Caching wrapper around VBTableBuilder::enumerateVBTables().
654 const VBTableGlobals &enumerateVBTables(const CXXRecordDecl *RD);
656 /// Generate a thunk for calling a virtual member function MD.
657 llvm::Function *EmitVirtualMemPtrThunk(const CXXMethodDecl *MD,
658 const MethodVFTableLocation &ML);
660 llvm::Constant *EmitMemberDataPointer(const CXXRecordDecl *RD,
661 CharUnits offset);
663 public:
664 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override;
666 bool isZeroInitializable(const MemberPointerType *MPT) override;
668 bool isMemberPointerConvertible(const MemberPointerType *MPT) const override {
669 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
670 return RD->hasAttr<MSInheritanceAttr>();
673 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override;
675 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
676 CharUnits offset) override;
677 llvm::Constant *EmitMemberFunctionPointer(const CXXMethodDecl *MD) override;
678 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override;
680 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
681 llvm::Value *L,
682 llvm::Value *R,
683 const MemberPointerType *MPT,
684 bool Inequality) override;
686 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
687 llvm::Value *MemPtr,
688 const MemberPointerType *MPT) override;
690 llvm::Value *
691 EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
692 Address Base, llvm::Value *MemPtr,
693 const MemberPointerType *MPT) override;
695 llvm::Value *EmitNonNullMemberPointerConversion(
696 const MemberPointerType *SrcTy, const MemberPointerType *DstTy,
697 CastKind CK, CastExpr::path_const_iterator PathBegin,
698 CastExpr::path_const_iterator PathEnd, llvm::Value *Src,
699 CGBuilderTy &Builder);
701 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
702 const CastExpr *E,
703 llvm::Value *Src) override;
705 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
706 llvm::Constant *Src) override;
708 llvm::Constant *EmitMemberPointerConversion(
709 const MemberPointerType *SrcTy, const MemberPointerType *DstTy,
710 CastKind CK, CastExpr::path_const_iterator PathBegin,
711 CastExpr::path_const_iterator PathEnd, llvm::Constant *Src);
713 CGCallee
714 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF, const Expr *E,
715 Address This, llvm::Value *&ThisPtrForCall,
716 llvm::Value *MemPtr,
717 const MemberPointerType *MPT) override;
719 void emitCXXStructor(GlobalDecl GD) override;
721 llvm::StructType *getCatchableTypeType() {
722 if (CatchableTypeType)
723 return CatchableTypeType;
724 llvm::Type *FieldTypes[] = {
725 CGM.IntTy, // Flags
726 getImageRelativeType(CGM.Int8PtrTy), // TypeDescriptor
727 CGM.IntTy, // NonVirtualAdjustment
728 CGM.IntTy, // OffsetToVBPtr
729 CGM.IntTy, // VBTableIndex
730 CGM.IntTy, // Size
731 getImageRelativeType(CGM.Int8PtrTy) // CopyCtor
733 CatchableTypeType = llvm::StructType::create(
734 CGM.getLLVMContext(), FieldTypes, "eh.CatchableType");
735 return CatchableTypeType;
738 llvm::StructType *getCatchableTypeArrayType(uint32_t NumEntries) {
739 llvm::StructType *&CatchableTypeArrayType =
740 CatchableTypeArrayTypeMap[NumEntries];
741 if (CatchableTypeArrayType)
742 return CatchableTypeArrayType;
744 llvm::SmallString<23> CTATypeName("eh.CatchableTypeArray.");
745 CTATypeName += llvm::utostr(NumEntries);
746 llvm::Type *CTType = getImageRelativeType(CGM.UnqualPtrTy);
747 llvm::Type *FieldTypes[] = {
748 CGM.IntTy, // NumEntries
749 llvm::ArrayType::get(CTType, NumEntries) // CatchableTypes
751 CatchableTypeArrayType =
752 llvm::StructType::create(CGM.getLLVMContext(), FieldTypes, CTATypeName);
753 return CatchableTypeArrayType;
756 llvm::StructType *getThrowInfoType() {
757 if (ThrowInfoType)
758 return ThrowInfoType;
759 llvm::Type *FieldTypes[] = {
760 CGM.IntTy, // Flags
761 getImageRelativeType(CGM.Int8PtrTy), // CleanupFn
762 getImageRelativeType(CGM.Int8PtrTy), // ForwardCompat
763 getImageRelativeType(CGM.Int8PtrTy) // CatchableTypeArray
765 ThrowInfoType = llvm::StructType::create(CGM.getLLVMContext(), FieldTypes,
766 "eh.ThrowInfo");
767 return ThrowInfoType;
770 llvm::FunctionCallee getThrowFn() {
771 // _CxxThrowException is passed an exception object and a ThrowInfo object
772 // which describes the exception.
773 llvm::Type *Args[] = {CGM.Int8PtrTy, CGM.UnqualPtrTy};
774 llvm::FunctionType *FTy =
775 llvm::FunctionType::get(CGM.VoidTy, Args, /*isVarArg=*/false);
776 llvm::FunctionCallee Throw =
777 CGM.CreateRuntimeFunction(FTy, "_CxxThrowException");
778 // _CxxThrowException is stdcall on 32-bit x86 platforms.
779 if (CGM.getTarget().getTriple().getArch() == llvm::Triple::x86) {
780 if (auto *Fn = dyn_cast<llvm::Function>(Throw.getCallee()))
781 Fn->setCallingConv(llvm::CallingConv::X86_StdCall);
783 return Throw;
786 llvm::Function *getAddrOfCXXCtorClosure(const CXXConstructorDecl *CD,
787 CXXCtorType CT);
789 llvm::Constant *getCatchableType(QualType T,
790 uint32_t NVOffset = 0,
791 int32_t VBPtrOffset = -1,
792 uint32_t VBIndex = 0);
794 llvm::GlobalVariable *getCatchableTypeArray(QualType T);
796 llvm::GlobalVariable *getThrowInfo(QualType T) override;
798 std::pair<llvm::Value *, const CXXRecordDecl *>
799 LoadVTablePtr(CodeGenFunction &CGF, Address This,
800 const CXXRecordDecl *RD) override;
802 bool
803 isPermittedToBeHomogeneousAggregate(const CXXRecordDecl *RD) const override;
805 private:
806 typedef std::pair<const CXXRecordDecl *, CharUnits> VFTableIdTy;
807 typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalVariable *> VTablesMapTy;
808 typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalValue *> VFTablesMapTy;
809 /// All the vftables that have been referenced.
810 VFTablesMapTy VFTablesMap;
811 VTablesMapTy VTablesMap;
813 /// This set holds the record decls we've deferred vtable emission for.
814 llvm::SmallPtrSet<const CXXRecordDecl *, 4> DeferredVFTables;
817 /// All the vbtables which have been referenced.
818 llvm::DenseMap<const CXXRecordDecl *, VBTableGlobals> VBTablesMap;
820 /// Info on the global variable used to guard initialization of static locals.
821 /// The BitIndex field is only used for externally invisible declarations.
822 struct GuardInfo {
823 GuardInfo() = default;
824 llvm::GlobalVariable *Guard = nullptr;
825 unsigned BitIndex = 0;
828 /// Map from DeclContext to the current guard variable. We assume that the
829 /// AST is visited in source code order.
830 llvm::DenseMap<const DeclContext *, GuardInfo> GuardVariableMap;
831 llvm::DenseMap<const DeclContext *, GuardInfo> ThreadLocalGuardVariableMap;
832 llvm::DenseMap<const DeclContext *, unsigned> ThreadSafeGuardNumMap;
834 llvm::DenseMap<size_t, llvm::StructType *> TypeDescriptorTypeMap;
835 llvm::StructType *BaseClassDescriptorType;
836 llvm::StructType *ClassHierarchyDescriptorType;
837 llvm::StructType *CompleteObjectLocatorType;
839 llvm::DenseMap<QualType, llvm::GlobalVariable *> CatchableTypeArrays;
841 llvm::StructType *CatchableTypeType;
842 llvm::DenseMap<uint32_t, llvm::StructType *> CatchableTypeArrayTypeMap;
843 llvm::StructType *ThrowInfoType;
848 CGCXXABI::RecordArgABI
849 MicrosoftCXXABI::getRecordArgABI(const CXXRecordDecl *RD) const {
850 // Use the default C calling convention rules for things that can be passed in
851 // registers, i.e. non-trivially copyable records or records marked with
852 // [[trivial_abi]].
853 if (RD->canPassInRegisters())
854 return RAA_Default;
856 switch (CGM.getTarget().getTriple().getArch()) {
857 default:
858 // FIXME: Implement for other architectures.
859 return RAA_Indirect;
861 case llvm::Triple::thumb:
862 // Pass things indirectly for now because it is simple.
863 // FIXME: This is incompatible with MSVC for arguments with a dtor and no
864 // copy ctor.
865 return RAA_Indirect;
867 case llvm::Triple::x86: {
868 // If the argument has *required* alignment greater than four bytes, pass
869 // it indirectly. Prior to MSVC version 19.14, passing overaligned
870 // arguments was not supported and resulted in a compiler error. In 19.14
871 // and later versions, such arguments are now passed indirectly.
872 TypeInfo Info = getContext().getTypeInfo(RD->getTypeForDecl());
873 if (Info.isAlignRequired() && Info.Align > 4)
874 return RAA_Indirect;
876 // If C++ prohibits us from making a copy, construct the arguments directly
877 // into argument memory.
878 return RAA_DirectInMemory;
881 case llvm::Triple::x86_64:
882 case llvm::Triple::aarch64:
883 return RAA_Indirect;
886 llvm_unreachable("invalid enum");
889 void MicrosoftCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
890 const CXXDeleteExpr *DE,
891 Address Ptr,
892 QualType ElementType,
893 const CXXDestructorDecl *Dtor) {
894 // FIXME: Provide a source location here even though there's no
895 // CXXMemberCallExpr for dtor call.
896 bool UseGlobalDelete = DE->isGlobalDelete();
897 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
898 llvm::Value *MDThis = EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, DE,
899 /*CallOrInvoke=*/nullptr);
900 if (UseGlobalDelete)
901 CGF.EmitDeleteCall(DE->getOperatorDelete(), MDThis, ElementType);
904 void MicrosoftCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
905 llvm::Value *Args[] = {llvm::ConstantPointerNull::get(CGM.Int8PtrTy),
906 llvm::ConstantPointerNull::get(CGM.UnqualPtrTy)};
907 llvm::FunctionCallee Fn = getThrowFn();
908 if (isNoReturn)
909 CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, Args);
910 else
911 CGF.EmitRuntimeCallOrInvoke(Fn, Args);
914 void MicrosoftCXXABI::emitBeginCatch(CodeGenFunction &CGF,
915 const CXXCatchStmt *S) {
916 // In the MS ABI, the runtime handles the copy, and the catch handler is
917 // responsible for destruction.
918 VarDecl *CatchParam = S->getExceptionDecl();
919 llvm::BasicBlock *CatchPadBB = CGF.Builder.GetInsertBlock();
920 llvm::CatchPadInst *CPI =
921 cast<llvm::CatchPadInst>(CatchPadBB->getFirstNonPHI());
922 CGF.CurrentFuncletPad = CPI;
924 // If this is a catch-all or the catch parameter is unnamed, we don't need to
925 // emit an alloca to the object.
926 if (!CatchParam || !CatchParam->getDeclName()) {
927 CGF.EHStack.pushCleanup<CatchRetScope>(NormalCleanup, CPI);
928 return;
931 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
932 CPI->setArgOperand(2, var.getObjectAddress(CGF).emitRawPointer(CGF));
933 CGF.EHStack.pushCleanup<CatchRetScope>(NormalCleanup, CPI);
934 CGF.EmitAutoVarCleanups(var);
937 /// We need to perform a generic polymorphic operation (like a typeid
938 /// or a cast), which requires an object with a vfptr. Adjust the
939 /// address to point to an object with a vfptr.
940 std::tuple<Address, llvm::Value *, const CXXRecordDecl *>
941 MicrosoftCXXABI::performBaseAdjustment(CodeGenFunction &CGF, Address Value,
942 QualType SrcRecordTy) {
943 Value = Value.withElementType(CGF.Int8Ty);
944 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
945 const ASTContext &Context = getContext();
947 // If the class itself has a vfptr, great. This check implicitly
948 // covers non-virtual base subobjects: a class with its own virtual
949 // functions would be a candidate to be a primary base.
950 if (Context.getASTRecordLayout(SrcDecl).hasExtendableVFPtr())
951 return std::make_tuple(Value, llvm::ConstantInt::get(CGF.Int32Ty, 0),
952 SrcDecl);
954 // Okay, one of the vbases must have a vfptr, or else this isn't
955 // actually a polymorphic class.
956 const CXXRecordDecl *PolymorphicBase = nullptr;
957 for (auto &Base : SrcDecl->vbases()) {
958 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
959 if (Context.getASTRecordLayout(BaseDecl).hasExtendableVFPtr()) {
960 PolymorphicBase = BaseDecl;
961 break;
964 assert(PolymorphicBase && "polymorphic class has no apparent vfptr?");
966 llvm::Value *Offset =
967 GetVirtualBaseClassOffset(CGF, Value, SrcDecl, PolymorphicBase);
968 llvm::Value *Ptr = CGF.Builder.CreateInBoundsGEP(
969 Value.getElementType(), Value.emitRawPointer(CGF), Offset);
970 CharUnits VBaseAlign =
971 CGF.CGM.getVBaseAlignment(Value.getAlignment(), SrcDecl, PolymorphicBase);
972 return std::make_tuple(Address(Ptr, CGF.Int8Ty, VBaseAlign), Offset,
973 PolymorphicBase);
976 bool MicrosoftCXXABI::shouldTypeidBeNullChecked(QualType SrcRecordTy) {
977 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
978 return !getContext().getASTRecordLayout(SrcDecl).hasExtendableVFPtr();
981 static llvm::CallBase *emitRTtypeidCall(CodeGenFunction &CGF,
982 llvm::Value *Argument) {
983 llvm::Type *ArgTypes[] = {CGF.Int8PtrTy};
984 llvm::FunctionType *FTy =
985 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false);
986 llvm::Value *Args[] = {Argument};
987 llvm::FunctionCallee Fn = CGF.CGM.CreateRuntimeFunction(FTy, "__RTtypeid");
988 return CGF.EmitRuntimeCallOrInvoke(Fn, Args);
991 void MicrosoftCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
992 llvm::CallBase *Call =
993 emitRTtypeidCall(CGF, llvm::Constant::getNullValue(CGM.VoidPtrTy));
994 Call->setDoesNotReturn();
995 CGF.Builder.CreateUnreachable();
998 llvm::Value *MicrosoftCXXABI::EmitTypeid(CodeGenFunction &CGF,
999 QualType SrcRecordTy,
1000 Address ThisPtr,
1001 llvm::Type *StdTypeInfoPtrTy) {
1002 std::tie(ThisPtr, std::ignore, std::ignore) =
1003 performBaseAdjustment(CGF, ThisPtr, SrcRecordTy);
1004 llvm::CallBase *Typeid = emitRTtypeidCall(CGF, ThisPtr.emitRawPointer(CGF));
1005 return CGF.Builder.CreateBitCast(Typeid, StdTypeInfoPtrTy);
1008 bool MicrosoftCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
1009 QualType SrcRecordTy) {
1010 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
1011 return SrcIsPtr &&
1012 !getContext().getASTRecordLayout(SrcDecl).hasExtendableVFPtr();
1015 llvm::Value *MicrosoftCXXABI::emitDynamicCastCall(
1016 CodeGenFunction &CGF, Address This, QualType SrcRecordTy, QualType DestTy,
1017 QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
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, std::ignore) =
1025 performBaseAdjustment(CGF, This, SrcRecordTy);
1026 llvm::Value *ThisPtr = This.emitRawPointer(CGF);
1027 Offset = CGF.Builder.CreateTrunc(Offset, CGF.Int32Ty);
1029 // PVOID __RTDynamicCast(
1030 // PVOID inptr,
1031 // LONG VfDelta,
1032 // PVOID SrcType,
1033 // PVOID TargetType,
1034 // BOOL isReference)
1035 llvm::Type *ArgTypes[] = {CGF.Int8PtrTy, CGF.Int32Ty, CGF.Int8PtrTy,
1036 CGF.Int8PtrTy, CGF.Int32Ty};
1037 llvm::FunctionCallee Function = CGF.CGM.CreateRuntimeFunction(
1038 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false),
1039 "__RTDynamicCast");
1040 llvm::Value *Args[] = {
1041 ThisPtr, Offset, SrcRTTI, DestRTTI,
1042 llvm::ConstantInt::get(CGF.Int32Ty, DestTy->isReferenceType())};
1043 return CGF.EmitRuntimeCallOrInvoke(Function, Args);
1046 llvm::Value *MicrosoftCXXABI::emitDynamicCastToVoid(CodeGenFunction &CGF,
1047 Address Value,
1048 QualType SrcRecordTy) {
1049 std::tie(Value, std::ignore, std::ignore) =
1050 performBaseAdjustment(CGF, Value, SrcRecordTy);
1052 // PVOID __RTCastToVoid(
1053 // PVOID inptr)
1054 llvm::Type *ArgTypes[] = {CGF.Int8PtrTy};
1055 llvm::FunctionCallee Function = CGF.CGM.CreateRuntimeFunction(
1056 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false),
1057 "__RTCastToVoid");
1058 llvm::Value *Args[] = {Value.emitRawPointer(CGF)};
1059 return CGF.EmitRuntimeCall(Function, Args);
1062 bool MicrosoftCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1063 return false;
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 =
1075 IntSize *
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);
1082 VBPtrToNewBase =
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 static bool isTrivialForMSVC(const CXXRecordDecl *RD, QualType Ty,
1101 CodeGenModule &CGM) {
1102 // On AArch64, HVAs that can be passed in registers can also be returned
1103 // in registers. (Note this is using the MSVC definition of an HVA; see
1104 // isPermittedToBeHomogeneousAggregate().)
1105 const Type *Base = nullptr;
1106 uint64_t NumElts = 0;
1107 if (CGM.getTarget().getTriple().isAArch64() &&
1108 CGM.getABIInfo().isHomogeneousAggregate(Ty, Base, NumElts) &&
1109 isa<VectorType>(Base)) {
1110 return true;
1113 // We use the C++14 definition of an aggregate, so we also
1114 // check for:
1115 // No private or protected non static data members.
1116 // No base classes
1117 // No virtual functions
1118 // Additionally, we need to ensure that there is a trivial copy assignment
1119 // operator, a trivial destructor, no user-provided constructors and no
1120 // deleted copy assignment operator.
1122 // We need to cover two cases when checking for a deleted copy assignment
1123 // operator.
1125 // struct S { int& r; };
1126 // The above will have an implicit copy assignment operator that is deleted
1127 // and there will not be a `CXXMethodDecl` for the copy assignment operator.
1128 // This is handled by the `needsImplicitCopyAssignment()` check below.
1130 // struct S { S& operator=(const S&) = delete; int i; };
1131 // The above will not have an implicit copy assignment operator that is
1132 // deleted but there is a deleted `CXXMethodDecl` for the declared copy
1133 // assignment operator. This is handled by the `isDeleted()` check below.
1135 if (RD->hasProtectedFields() || RD->hasPrivateFields())
1136 return false;
1137 if (RD->getNumBases() > 0)
1138 return false;
1139 if (RD->isPolymorphic())
1140 return false;
1141 if (RD->hasNonTrivialCopyAssignment())
1142 return false;
1143 if (RD->needsImplicitCopyAssignment() && !RD->hasSimpleCopyAssignment())
1144 return false;
1145 for (const Decl *D : RD->decls()) {
1146 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(D)) {
1147 if (Ctor->isUserProvided())
1148 return false;
1149 } else if (auto *Template = dyn_cast<FunctionTemplateDecl>(D)) {
1150 if (isa<CXXConstructorDecl>(Template->getTemplatedDecl()))
1151 return false;
1152 } else if (auto *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
1153 if (MethodDecl->isCopyAssignmentOperator() && MethodDecl->isDeleted())
1154 return false;
1157 if (RD->hasNonTrivialDestructor())
1158 return false;
1159 return true;
1162 bool MicrosoftCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
1163 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
1164 if (!RD)
1165 return false;
1167 bool isTrivialForABI = RD->canPassInRegisters() &&
1168 isTrivialForMSVC(RD, FI.getReturnType(), CGM);
1170 // MSVC always returns structs indirectly from C++ instance methods.
1171 bool isIndirectReturn = !isTrivialForABI || FI.isInstanceMethod();
1173 if (isIndirectReturn) {
1174 CharUnits Align = CGM.getContext().getTypeAlignInChars(FI.getReturnType());
1175 FI.getReturnInfo() = ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
1177 // MSVC always passes `this` before the `sret` parameter.
1178 FI.getReturnInfo().setSRetAfterThis(FI.isInstanceMethod());
1180 // On AArch64, use the `inreg` attribute if the object is considered to not
1181 // be trivially copyable, or if this is an instance method struct return.
1182 FI.getReturnInfo().setInReg(CGM.getTarget().getTriple().isAArch64());
1184 return true;
1187 // Otherwise, use the C ABI rules.
1188 return false;
1191 llvm::BasicBlock *
1192 MicrosoftCXXABI::EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
1193 const CXXRecordDecl *RD) {
1194 llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);
1195 assert(IsMostDerivedClass &&
1196 "ctor for a class with virtual bases must have an implicit parameter");
1197 llvm::Value *IsCompleteObject =
1198 CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");
1200 llvm::BasicBlock *CallVbaseCtorsBB = CGF.createBasicBlock("ctor.init_vbases");
1201 llvm::BasicBlock *SkipVbaseCtorsBB = CGF.createBasicBlock("ctor.skip_vbases");
1202 CGF.Builder.CreateCondBr(IsCompleteObject,
1203 CallVbaseCtorsBB, SkipVbaseCtorsBB);
1205 CGF.EmitBlock(CallVbaseCtorsBB);
1207 // Fill in the vbtable pointers here.
1208 EmitVBPtrStores(CGF, RD);
1210 // CGF will put the base ctor calls in this basic block for us later.
1212 return SkipVbaseCtorsBB;
1215 llvm::BasicBlock *
1216 MicrosoftCXXABI::EmitDtorCompleteObjectHandler(CodeGenFunction &CGF) {
1217 llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);
1218 assert(IsMostDerivedClass &&
1219 "ctor for a class with virtual bases must have an implicit parameter");
1220 llvm::Value *IsCompleteObject =
1221 CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");
1223 llvm::BasicBlock *CallVbaseDtorsBB = CGF.createBasicBlock("Dtor.dtor_vbases");
1224 llvm::BasicBlock *SkipVbaseDtorsBB = CGF.createBasicBlock("Dtor.skip_vbases");
1225 CGF.Builder.CreateCondBr(IsCompleteObject,
1226 CallVbaseDtorsBB, SkipVbaseDtorsBB);
1228 CGF.EmitBlock(CallVbaseDtorsBB);
1229 // CGF will put the base dtor calls in this basic block for us later.
1231 return SkipVbaseDtorsBB;
1234 void MicrosoftCXXABI::initializeHiddenVirtualInheritanceMembers(
1235 CodeGenFunction &CGF, const CXXRecordDecl *RD) {
1236 // In most cases, an override for a vbase virtual method can adjust
1237 // the "this" parameter by applying a constant offset.
1238 // However, this is not enough while a constructor or a destructor of some
1239 // class X is being executed if all the following conditions are met:
1240 // - X has virtual bases, (1)
1241 // - X overrides a virtual method M of a vbase Y, (2)
1242 // - X itself is a vbase of the most derived class.
1244 // If (1) and (2) are true, the vtorDisp for vbase Y is a hidden member of X
1245 // which holds the extra amount of "this" adjustment we must do when we use
1246 // the X vftables (i.e. during X ctor or dtor).
1247 // Outside the ctors and dtors, the values of vtorDisps are zero.
1249 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1250 typedef ASTRecordLayout::VBaseOffsetsMapTy VBOffsets;
1251 const VBOffsets &VBaseMap = Layout.getVBaseOffsetsMap();
1252 CGBuilderTy &Builder = CGF.Builder;
1254 llvm::Value *Int8This = nullptr; // Initialize lazily.
1256 for (const CXXBaseSpecifier &S : RD->vbases()) {
1257 const CXXRecordDecl *VBase = S.getType()->getAsCXXRecordDecl();
1258 auto I = VBaseMap.find(VBase);
1259 assert(I != VBaseMap.end());
1260 if (!I->second.hasVtorDisp())
1261 continue;
1263 llvm::Value *VBaseOffset =
1264 GetVirtualBaseClassOffset(CGF, getThisAddress(CGF), RD, VBase);
1265 uint64_t ConstantVBaseOffset = I->second.VBaseOffset.getQuantity();
1267 // vtorDisp_for_vbase = vbptr[vbase_idx] - offsetof(RD, vbase).
1268 llvm::Value *VtorDispValue = Builder.CreateSub(
1269 VBaseOffset, llvm::ConstantInt::get(CGM.PtrDiffTy, ConstantVBaseOffset),
1270 "vtordisp.value");
1271 VtorDispValue = Builder.CreateTruncOrBitCast(VtorDispValue, CGF.Int32Ty);
1273 if (!Int8This)
1274 Int8This = getThisValue(CGF);
1276 llvm::Value *VtorDispPtr =
1277 Builder.CreateInBoundsGEP(CGF.Int8Ty, Int8This, VBaseOffset);
1278 // vtorDisp is always the 32-bits before the vbase in the class layout.
1279 VtorDispPtr = Builder.CreateConstGEP1_32(CGF.Int8Ty, VtorDispPtr, -4);
1281 Builder.CreateAlignedStore(VtorDispValue, VtorDispPtr,
1282 CharUnits::fromQuantity(4));
1286 static bool hasDefaultCXXMethodCC(ASTContext &Context,
1287 const CXXMethodDecl *MD) {
1288 CallingConv ExpectedCallingConv = Context.getDefaultCallingConvention(
1289 /*IsVariadic=*/false, /*IsCXXMethod=*/true);
1290 CallingConv ActualCallingConv =
1291 MD->getType()->castAs<FunctionProtoType>()->getCallConv();
1292 return ExpectedCallingConv == ActualCallingConv;
1295 void MicrosoftCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1296 // There's only one constructor type in this ABI.
1297 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1299 // Exported default constructors either have a simple call-site where they use
1300 // the typical calling convention and have a single 'this' pointer for an
1301 // argument -or- they get a wrapper function which appropriately thunks to the
1302 // real default constructor. This thunk is the default constructor closure.
1303 if (D->hasAttr<DLLExportAttr>() && D->isDefaultConstructor() &&
1304 D->isDefined()) {
1305 if (!hasDefaultCXXMethodCC(getContext(), D) || D->getNumParams() != 0) {
1306 llvm::Function *Fn = getAddrOfCXXCtorClosure(D, Ctor_DefaultClosure);
1307 Fn->setLinkage(llvm::GlobalValue::WeakODRLinkage);
1308 CGM.setGVProperties(Fn, D);
1313 void MicrosoftCXXABI::EmitVBPtrStores(CodeGenFunction &CGF,
1314 const CXXRecordDecl *RD) {
1315 Address This = getThisAddress(CGF);
1316 This = This.withElementType(CGM.Int8Ty);
1317 const ASTContext &Context = getContext();
1318 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1320 const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
1321 for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) {
1322 const std::unique_ptr<VPtrInfo> &VBT = (*VBGlobals.VBTables)[I];
1323 llvm::GlobalVariable *GV = VBGlobals.Globals[I];
1324 const ASTRecordLayout &SubobjectLayout =
1325 Context.getASTRecordLayout(VBT->IntroducingObject);
1326 CharUnits Offs = VBT->NonVirtualOffset;
1327 Offs += SubobjectLayout.getVBPtrOffset();
1328 if (VBT->getVBaseWithVPtr())
1329 Offs += Layout.getVBaseClassOffset(VBT->getVBaseWithVPtr());
1330 Address VBPtr = CGF.Builder.CreateConstInBoundsByteGEP(This, Offs);
1331 llvm::Value *GVPtr =
1332 CGF.Builder.CreateConstInBoundsGEP2_32(GV->getValueType(), GV, 0, 0);
1333 VBPtr = VBPtr.withElementType(GVPtr->getType());
1334 CGF.Builder.CreateStore(GVPtr, VBPtr);
1338 CGCXXABI::AddedStructorArgCounts
1339 MicrosoftCXXABI::buildStructorSignature(GlobalDecl GD,
1340 SmallVectorImpl<CanQualType> &ArgTys) {
1341 AddedStructorArgCounts Added;
1342 // TODO: 'for base' flag
1343 if (isa<CXXDestructorDecl>(GD.getDecl()) &&
1344 GD.getDtorType() == Dtor_Deleting) {
1345 // The scalar deleting destructor takes an implicit int parameter.
1346 ArgTys.push_back(getContext().IntTy);
1347 ++Added.Suffix;
1349 auto *CD = dyn_cast<CXXConstructorDecl>(GD.getDecl());
1350 if (!CD)
1351 return Added;
1353 // All parameters are already in place except is_most_derived, which goes
1354 // after 'this' if it's variadic and last if it's not.
1356 const CXXRecordDecl *Class = CD->getParent();
1357 const FunctionProtoType *FPT = CD->getType()->castAs<FunctionProtoType>();
1358 if (Class->getNumVBases()) {
1359 if (FPT->isVariadic()) {
1360 ArgTys.insert(ArgTys.begin() + 1, getContext().IntTy);
1361 ++Added.Prefix;
1362 } else {
1363 ArgTys.push_back(getContext().IntTy);
1364 ++Added.Suffix;
1368 return Added;
1371 void MicrosoftCXXABI::setCXXDestructorDLLStorage(llvm::GlobalValue *GV,
1372 const CXXDestructorDecl *Dtor,
1373 CXXDtorType DT) const {
1374 // Deleting destructor variants are never imported or exported. Give them the
1375 // default storage class.
1376 if (DT == Dtor_Deleting) {
1377 GV->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
1378 } else {
1379 const NamedDecl *ND = Dtor;
1380 CGM.setDLLImportDLLExport(GV, ND);
1384 llvm::GlobalValue::LinkageTypes MicrosoftCXXABI::getCXXDestructorLinkage(
1385 GVALinkage Linkage, const CXXDestructorDecl *Dtor, CXXDtorType DT) const {
1386 // Internal things are always internal, regardless of attributes. After this,
1387 // we know the thunk is externally visible.
1388 if (Linkage == GVA_Internal)
1389 return llvm::GlobalValue::InternalLinkage;
1391 switch (DT) {
1392 case Dtor_Base:
1393 // The base destructor most closely tracks the user-declared constructor, so
1394 // we delegate back to the normal declarator case.
1395 return CGM.getLLVMLinkageForDeclarator(Dtor, Linkage);
1396 case Dtor_Complete:
1397 // The complete destructor is like an inline function, but it may be
1398 // imported and therefore must be exported as well. This requires changing
1399 // the linkage if a DLL attribute is present.
1400 if (Dtor->hasAttr<DLLExportAttr>())
1401 return llvm::GlobalValue::WeakODRLinkage;
1402 if (Dtor->hasAttr<DLLImportAttr>())
1403 return llvm::GlobalValue::AvailableExternallyLinkage;
1404 return llvm::GlobalValue::LinkOnceODRLinkage;
1405 case Dtor_Deleting:
1406 // Deleting destructors are like inline functions. They have vague linkage
1407 // and are emitted everywhere they are used. They are internal if the class
1408 // is internal.
1409 return llvm::GlobalValue::LinkOnceODRLinkage;
1410 case Dtor_Comdat:
1411 llvm_unreachable("MS C++ ABI does not support comdat dtors");
1413 llvm_unreachable("invalid dtor type");
1416 void MicrosoftCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
1417 // The TU defining a dtor is only guaranteed to emit a base destructor. All
1418 // other destructor variants are delegating thunks.
1419 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
1421 // If the class is dllexported, emit the complete (vbase) destructor wherever
1422 // the base dtor is emitted.
1423 // FIXME: To match MSVC, this should only be done when the class is exported
1424 // with -fdllexport-inlines enabled.
1425 if (D->getParent()->getNumVBases() > 0 && D->hasAttr<DLLExportAttr>())
1426 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
1429 CharUnits
1430 MicrosoftCXXABI::getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD) {
1431 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1433 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1434 // Complete destructors take a pointer to the complete object as a
1435 // parameter, thus don't need this adjustment.
1436 if (GD.getDtorType() == Dtor_Complete)
1437 return CharUnits();
1439 // There's no Dtor_Base in vftable but it shares the this adjustment with
1440 // the deleting one, so look it up instead.
1441 GD = GlobalDecl(DD, Dtor_Deleting);
1444 MethodVFTableLocation ML =
1445 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD);
1446 CharUnits Adjustment = ML.VFPtrOffset;
1448 // Normal virtual instance methods need to adjust from the vfptr that first
1449 // defined the virtual method to the virtual base subobject, but destructors
1450 // do not. The vector deleting destructor thunk applies this adjustment for
1451 // us if necessary.
1452 if (isa<CXXDestructorDecl>(MD))
1453 Adjustment = CharUnits::Zero();
1455 if (ML.VBase) {
1456 const ASTRecordLayout &DerivedLayout =
1457 getContext().getASTRecordLayout(MD->getParent());
1458 Adjustment += DerivedLayout.getVBaseClassOffset(ML.VBase);
1461 return Adjustment;
1464 Address MicrosoftCXXABI::adjustThisArgumentForVirtualFunctionCall(
1465 CodeGenFunction &CGF, GlobalDecl GD, Address This,
1466 bool VirtualCall) {
1467 if (!VirtualCall) {
1468 // If the call of a virtual function is not virtual, we just have to
1469 // compensate for the adjustment the virtual function does in its prologue.
1470 CharUnits Adjustment = getVirtualFunctionPrologueThisAdjustment(GD);
1471 if (Adjustment.isZero())
1472 return This;
1474 This = This.withElementType(CGF.Int8Ty);
1475 assert(Adjustment.isPositive());
1476 return CGF.Builder.CreateConstByteGEP(This, Adjustment);
1479 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1481 GlobalDecl LookupGD = GD;
1482 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1483 // Complete dtors take a pointer to the complete object,
1484 // thus don't need adjustment.
1485 if (GD.getDtorType() == Dtor_Complete)
1486 return This;
1488 // There's only Dtor_Deleting in vftable but it shares the this adjustment
1489 // with the base one, so look up the deleting one instead.
1490 LookupGD = GlobalDecl(DD, Dtor_Deleting);
1492 MethodVFTableLocation ML =
1493 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD);
1495 CharUnits StaticOffset = ML.VFPtrOffset;
1497 // Base destructors expect 'this' to point to the beginning of the base
1498 // subobject, not the first vfptr that happens to contain the virtual dtor.
1499 // However, we still need to apply the virtual base adjustment.
1500 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
1501 StaticOffset = CharUnits::Zero();
1503 Address Result = This;
1504 if (ML.VBase) {
1505 Result = Result.withElementType(CGF.Int8Ty);
1507 const CXXRecordDecl *Derived = MD->getParent();
1508 const CXXRecordDecl *VBase = ML.VBase;
1509 llvm::Value *VBaseOffset =
1510 GetVirtualBaseClassOffset(CGF, Result, Derived, VBase);
1511 llvm::Value *VBasePtr = CGF.Builder.CreateInBoundsGEP(
1512 Result.getElementType(), Result.emitRawPointer(CGF), VBaseOffset);
1513 CharUnits VBaseAlign =
1514 CGF.CGM.getVBaseAlignment(Result.getAlignment(), Derived, VBase);
1515 Result = Address(VBasePtr, CGF.Int8Ty, VBaseAlign);
1517 if (!StaticOffset.isZero()) {
1518 assert(StaticOffset.isPositive());
1519 Result = Result.withElementType(CGF.Int8Ty);
1520 if (ML.VBase) {
1521 // Non-virtual adjustment might result in a pointer outside the allocated
1522 // object, e.g. if the final overrider class is laid out after the virtual
1523 // base that declares a method in the most derived class.
1524 // FIXME: Update the code that emits this adjustment in thunks prologues.
1525 Result = CGF.Builder.CreateConstByteGEP(Result, StaticOffset);
1526 } else {
1527 Result = CGF.Builder.CreateConstInBoundsByteGEP(Result, StaticOffset);
1530 return Result;
1533 void MicrosoftCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1534 QualType &ResTy,
1535 FunctionArgList &Params) {
1536 ASTContext &Context = getContext();
1537 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
1538 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
1539 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
1540 auto *IsMostDerived = ImplicitParamDecl::Create(
1541 Context, /*DC=*/nullptr, CGF.CurGD.getDecl()->getLocation(),
1542 &Context.Idents.get("is_most_derived"), Context.IntTy,
1543 ImplicitParamKind::Other);
1544 // The 'most_derived' parameter goes second if the ctor is variadic and last
1545 // if it's not. Dtors can't be variadic.
1546 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
1547 if (FPT->isVariadic())
1548 Params.insert(Params.begin() + 1, IsMostDerived);
1549 else
1550 Params.push_back(IsMostDerived);
1551 getStructorImplicitParamDecl(CGF) = IsMostDerived;
1552 } else if (isDeletingDtor(CGF.CurGD)) {
1553 auto *ShouldDelete = ImplicitParamDecl::Create(
1554 Context, /*DC=*/nullptr, CGF.CurGD.getDecl()->getLocation(),
1555 &Context.Idents.get("should_call_delete"), Context.IntTy,
1556 ImplicitParamKind::Other);
1557 Params.push_back(ShouldDelete);
1558 getStructorImplicitParamDecl(CGF) = ShouldDelete;
1562 void MicrosoftCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
1563 // Naked functions have no prolog.
1564 if (CGF.CurFuncDecl && CGF.CurFuncDecl->hasAttr<NakedAttr>())
1565 return;
1567 // Overridden virtual methods of non-primary bases need to adjust the incoming
1568 // 'this' pointer in the prologue. In this hierarchy, C::b will subtract
1569 // sizeof(void*) to adjust from B* to C*:
1570 // struct A { virtual void a(); };
1571 // struct B { virtual void b(); };
1572 // struct C : A, B { virtual void b(); };
1574 // Leave the value stored in the 'this' alloca unadjusted, so that the
1575 // debugger sees the unadjusted value. Microsoft debuggers require this, and
1576 // will apply the ThisAdjustment in the method type information.
1577 // FIXME: Do something better for DWARF debuggers, which won't expect this,
1578 // without making our codegen depend on debug info settings.
1579 llvm::Value *This = loadIncomingCXXThis(CGF);
1580 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
1581 if (!CGF.CurFuncIsThunk && MD->isVirtual()) {
1582 CharUnits Adjustment = getVirtualFunctionPrologueThisAdjustment(CGF.CurGD);
1583 if (!Adjustment.isZero()) {
1584 assert(Adjustment.isPositive());
1585 This = CGF.Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, This,
1586 -Adjustment.getQuantity());
1589 setCXXABIThisValue(CGF, This);
1591 // If this is a function that the ABI specifies returns 'this', initialize
1592 // the return slot to 'this' at the start of the function.
1594 // Unlike the setting of return types, this is done within the ABI
1595 // implementation instead of by clients of CGCXXABI because:
1596 // 1) getThisValue is currently protected
1597 // 2) in theory, an ABI could implement 'this' returns some other way;
1598 // HasThisReturn only specifies a contract, not the implementation
1599 if (HasThisReturn(CGF.CurGD) || hasMostDerivedReturn(CGF.CurGD))
1600 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
1602 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
1603 assert(getStructorImplicitParamDecl(CGF) &&
1604 "no implicit parameter for a constructor with virtual bases?");
1605 getStructorImplicitParamValue(CGF)
1606 = CGF.Builder.CreateLoad(
1607 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
1608 "is_most_derived");
1611 if (isDeletingDtor(CGF.CurGD)) {
1612 assert(getStructorImplicitParamDecl(CGF) &&
1613 "no implicit parameter for a deleting destructor?");
1614 getStructorImplicitParamValue(CGF)
1615 = CGF.Builder.CreateLoad(
1616 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
1617 "should_call_delete");
1621 CGCXXABI::AddedStructorArgs MicrosoftCXXABI::getImplicitConstructorArgs(
1622 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1623 bool ForVirtualBase, bool Delegating) {
1624 assert(Type == Ctor_Complete || Type == Ctor_Base);
1626 // Check if we need a 'most_derived' parameter.
1627 if (!D->getParent()->getNumVBases())
1628 return AddedStructorArgs{};
1630 // Add the 'most_derived' argument second if we are variadic or last if not.
1631 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
1632 llvm::Value *MostDerivedArg;
1633 if (Delegating) {
1634 MostDerivedArg = getStructorImplicitParamValue(CGF);
1635 } else {
1636 MostDerivedArg = llvm::ConstantInt::get(CGM.Int32Ty, Type == Ctor_Complete);
1638 if (FPT->isVariadic()) {
1639 return AddedStructorArgs::prefix({{MostDerivedArg, getContext().IntTy}});
1641 return AddedStructorArgs::suffix({{MostDerivedArg, getContext().IntTy}});
1644 llvm::Value *MicrosoftCXXABI::getCXXDestructorImplicitParam(
1645 CodeGenFunction &CGF, const CXXDestructorDecl *DD, CXXDtorType Type,
1646 bool ForVirtualBase, bool Delegating) {
1647 return nullptr;
1650 void MicrosoftCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1651 const CXXDestructorDecl *DD,
1652 CXXDtorType Type, bool ForVirtualBase,
1653 bool Delegating, Address This,
1654 QualType ThisTy) {
1655 // Use the base destructor variant in place of the complete destructor variant
1656 // if the class has no virtual bases. This effectively implements some of the
1657 // -mconstructor-aliases optimization, but as part of the MS C++ ABI.
1658 if (Type == Dtor_Complete && DD->getParent()->getNumVBases() == 0)
1659 Type = Dtor_Base;
1661 GlobalDecl GD(DD, Type);
1662 CGCallee Callee = CGCallee::forDirect(CGM.getAddrOfCXXStructor(GD), GD);
1664 if (DD->isVirtual()) {
1665 assert(Type != CXXDtorType::Dtor_Deleting &&
1666 "The deleting destructor should only be called via a virtual call");
1667 This = adjustThisArgumentForVirtualFunctionCall(CGF, GlobalDecl(DD, Type),
1668 This, false);
1671 llvm::BasicBlock *BaseDtorEndBB = nullptr;
1672 if (ForVirtualBase && isa<CXXConstructorDecl>(CGF.CurCodeDecl)) {
1673 BaseDtorEndBB = EmitDtorCompleteObjectHandler(CGF);
1676 llvm::Value *Implicit =
1677 getCXXDestructorImplicitParam(CGF, DD, Type, ForVirtualBase,
1678 Delegating); // = nullptr
1679 CGF.EmitCXXDestructorCall(GD, Callee, CGF.getAsNaturalPointerTo(This, ThisTy),
1680 ThisTy,
1681 /*ImplicitParam=*/Implicit,
1682 /*ImplicitParamTy=*/QualType(), /*E=*/nullptr);
1683 if (BaseDtorEndBB) {
1684 // Complete object handler should continue to be the remaining
1685 CGF.Builder.CreateBr(BaseDtorEndBB);
1686 CGF.EmitBlock(BaseDtorEndBB);
1690 void MicrosoftCXXABI::emitVTableTypeMetadata(const VPtrInfo &Info,
1691 const CXXRecordDecl *RD,
1692 llvm::GlobalVariable *VTable) {
1693 // Emit type metadata on vtables with LTO or IR instrumentation.
1694 // In IR instrumentation, the type metadata could be used to find out vtable
1695 // definitions (for type profiling) among all global variables.
1696 if (!CGM.getCodeGenOpts().LTOUnit &&
1697 !CGM.getCodeGenOpts().hasProfileIRInstr())
1698 return;
1700 // TODO: Should VirtualFunctionElimination also be supported here?
1701 // See similar handling in CodeGenModule::EmitVTableTypeMetadata.
1702 if (CGM.getCodeGenOpts().WholeProgramVTables) {
1703 llvm::DenseSet<const CXXRecordDecl *> Visited;
1704 llvm::GlobalObject::VCallVisibility TypeVis =
1705 CGM.GetVCallVisibilityLevel(RD, Visited);
1706 if (TypeVis != llvm::GlobalObject::VCallVisibilityPublic)
1707 VTable->setVCallVisibilityMetadata(TypeVis);
1710 // The location of the first virtual function pointer in the virtual table,
1711 // aka the "address point" on Itanium. This is at offset 0 if RTTI is
1712 // disabled, or sizeof(void*) if RTTI is enabled.
1713 CharUnits AddressPoint =
1714 getContext().getLangOpts().RTTIData
1715 ? getContext().toCharUnitsFromBits(
1716 getContext().getTargetInfo().getPointerWidth(LangAS::Default))
1717 : CharUnits::Zero();
1719 if (Info.PathToIntroducingObject.empty()) {
1720 CGM.AddVTableTypeMetadata(VTable, AddressPoint, RD);
1721 return;
1724 // Add a bitset entry for the least derived base belonging to this vftable.
1725 CGM.AddVTableTypeMetadata(VTable, AddressPoint,
1726 Info.PathToIntroducingObject.back());
1728 // Add a bitset entry for each derived class that is laid out at the same
1729 // offset as the least derived base.
1730 for (unsigned I = Info.PathToIntroducingObject.size() - 1; I != 0; --I) {
1731 const CXXRecordDecl *DerivedRD = Info.PathToIntroducingObject[I - 1];
1732 const CXXRecordDecl *BaseRD = Info.PathToIntroducingObject[I];
1734 const ASTRecordLayout &Layout =
1735 getContext().getASTRecordLayout(DerivedRD);
1736 CharUnits Offset;
1737 auto VBI = Layout.getVBaseOffsetsMap().find(BaseRD);
1738 if (VBI == Layout.getVBaseOffsetsMap().end())
1739 Offset = Layout.getBaseClassOffset(BaseRD);
1740 else
1741 Offset = VBI->second.VBaseOffset;
1742 if (!Offset.isZero())
1743 return;
1744 CGM.AddVTableTypeMetadata(VTable, AddressPoint, DerivedRD);
1747 // Finally do the same for the most derived class.
1748 if (Info.FullOffsetInMDC.isZero())
1749 CGM.AddVTableTypeMetadata(VTable, AddressPoint, RD);
1752 void MicrosoftCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1753 const CXXRecordDecl *RD) {
1754 MicrosoftVTableContext &VFTContext = CGM.getMicrosoftVTableContext();
1755 const VPtrInfoVector &VFPtrs = VFTContext.getVFPtrOffsets(RD);
1757 for (const std::unique_ptr<VPtrInfo>& Info : VFPtrs) {
1758 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, Info->FullOffsetInMDC);
1759 if (VTable->hasInitializer())
1760 continue;
1762 const VTableLayout &VTLayout =
1763 VFTContext.getVFTableLayout(RD, Info->FullOffsetInMDC);
1765 llvm::Constant *RTTI = nullptr;
1766 if (any_of(VTLayout.vtable_components(),
1767 [](const VTableComponent &VTC) { return VTC.isRTTIKind(); }))
1768 RTTI = getMSCompleteObjectLocator(RD, *Info);
1770 ConstantInitBuilder builder(CGM);
1771 auto components = builder.beginStruct();
1772 CGVT.createVTableInitializer(components, VTLayout, RTTI,
1773 VTable->hasLocalLinkage());
1774 components.finishAndSetAsInitializer(VTable);
1776 emitVTableTypeMetadata(*Info, RD, VTable);
1780 bool MicrosoftCXXABI::isVirtualOffsetNeededForVTableField(
1781 CodeGenFunction &CGF, CodeGenFunction::VPtr Vptr) {
1782 return Vptr.NearestVBase != nullptr;
1785 llvm::Value *MicrosoftCXXABI::getVTableAddressPointInStructor(
1786 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1787 const CXXRecordDecl *NearestVBase) {
1788 llvm::Constant *VTableAddressPoint = getVTableAddressPoint(Base, VTableClass);
1789 if (!VTableAddressPoint) {
1790 assert(Base.getBase()->getNumVBases() &&
1791 !getContext().getASTRecordLayout(Base.getBase()).hasOwnVFPtr());
1793 return VTableAddressPoint;
1796 static void mangleVFTableName(MicrosoftMangleContext &MangleContext,
1797 const CXXRecordDecl *RD, const VPtrInfo &VFPtr,
1798 SmallString<256> &Name) {
1799 llvm::raw_svector_ostream Out(Name);
1800 MangleContext.mangleCXXVFTable(RD, VFPtr.MangledPath, Out);
1803 llvm::Constant *
1804 MicrosoftCXXABI::getVTableAddressPoint(BaseSubobject Base,
1805 const CXXRecordDecl *VTableClass) {
1806 (void)getAddrOfVTable(VTableClass, Base.getBaseOffset());
1807 VFTableIdTy ID(VTableClass, Base.getBaseOffset());
1808 return VFTablesMap[ID];
1811 llvm::GlobalVariable *MicrosoftCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1812 CharUnits VPtrOffset) {
1813 // getAddrOfVTable may return 0 if asked to get an address of a vtable which
1814 // shouldn't be used in the given record type. We want to cache this result in
1815 // VFTablesMap, thus a simple zero check is not sufficient.
1817 VFTableIdTy ID(RD, VPtrOffset);
1818 VTablesMapTy::iterator I;
1819 bool Inserted;
1820 std::tie(I, Inserted) = VTablesMap.insert(std::make_pair(ID, nullptr));
1821 if (!Inserted)
1822 return I->second;
1824 llvm::GlobalVariable *&VTable = I->second;
1826 MicrosoftVTableContext &VTContext = CGM.getMicrosoftVTableContext();
1827 const VPtrInfoVector &VFPtrs = VTContext.getVFPtrOffsets(RD);
1829 if (DeferredVFTables.insert(RD).second) {
1830 // We haven't processed this record type before.
1831 // Queue up this vtable for possible deferred emission.
1832 CGM.addDeferredVTable(RD);
1834 #ifndef NDEBUG
1835 // Create all the vftables at once in order to make sure each vftable has
1836 // a unique mangled name.
1837 llvm::StringSet<> ObservedMangledNames;
1838 for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) {
1839 SmallString<256> Name;
1840 mangleVFTableName(getMangleContext(), RD, *VFPtrs[J], Name);
1841 if (!ObservedMangledNames.insert(Name.str()).second)
1842 llvm_unreachable("Already saw this mangling before?");
1844 #endif
1847 const std::unique_ptr<VPtrInfo> *VFPtrI =
1848 llvm::find_if(VFPtrs, [&](const std::unique_ptr<VPtrInfo> &VPI) {
1849 return VPI->FullOffsetInMDC == VPtrOffset;
1851 if (VFPtrI == VFPtrs.end()) {
1852 VFTablesMap[ID] = nullptr;
1853 return nullptr;
1855 const std::unique_ptr<VPtrInfo> &VFPtr = *VFPtrI;
1857 SmallString<256> VFTableName;
1858 mangleVFTableName(getMangleContext(), RD, *VFPtr, VFTableName);
1860 // Classes marked __declspec(dllimport) need vftables generated on the
1861 // import-side in order to support features like constexpr. No other
1862 // translation unit relies on the emission of the local vftable, translation
1863 // units are expected to generate them as needed.
1865 // Because of this unique behavior, we maintain this logic here instead of
1866 // getVTableLinkage.
1867 llvm::GlobalValue::LinkageTypes VFTableLinkage =
1868 RD->hasAttr<DLLImportAttr>() ? llvm::GlobalValue::LinkOnceODRLinkage
1869 : CGM.getVTableLinkage(RD);
1870 bool VFTableComesFromAnotherTU =
1871 llvm::GlobalValue::isAvailableExternallyLinkage(VFTableLinkage) ||
1872 llvm::GlobalValue::isExternalLinkage(VFTableLinkage);
1873 bool VTableAliasIsRequred =
1874 !VFTableComesFromAnotherTU && getContext().getLangOpts().RTTIData;
1876 if (llvm::GlobalValue *VFTable =
1877 CGM.getModule().getNamedGlobal(VFTableName)) {
1878 VFTablesMap[ID] = VFTable;
1879 VTable = VTableAliasIsRequred
1880 ? cast<llvm::GlobalVariable>(
1881 cast<llvm::GlobalAlias>(VFTable)->getAliaseeObject())
1882 : cast<llvm::GlobalVariable>(VFTable);
1883 return VTable;
1886 const VTableLayout &VTLayout =
1887 VTContext.getVFTableLayout(RD, VFPtr->FullOffsetInMDC);
1888 llvm::GlobalValue::LinkageTypes VTableLinkage =
1889 VTableAliasIsRequred ? llvm::GlobalValue::PrivateLinkage : VFTableLinkage;
1891 StringRef VTableName = VTableAliasIsRequred ? StringRef() : VFTableName.str();
1893 llvm::Type *VTableType = CGM.getVTables().getVTableType(VTLayout);
1895 // Create a backing variable for the contents of VTable. The VTable may
1896 // or may not include space for a pointer to RTTI data.
1897 llvm::GlobalValue *VFTable;
1898 VTable = new llvm::GlobalVariable(CGM.getModule(), VTableType,
1899 /*isConstant=*/true, VTableLinkage,
1900 /*Initializer=*/nullptr, VTableName);
1901 VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1903 llvm::Comdat *C = nullptr;
1904 if (!VFTableComesFromAnotherTU &&
1905 llvm::GlobalValue::isWeakForLinker(VFTableLinkage))
1906 C = CGM.getModule().getOrInsertComdat(VFTableName.str());
1908 // Only insert a pointer into the VFTable for RTTI data if we are not
1909 // importing it. We never reference the RTTI data directly so there is no
1910 // need to make room for it.
1911 if (VTableAliasIsRequred) {
1912 llvm::Value *GEPIndices[] = {llvm::ConstantInt::get(CGM.Int32Ty, 0),
1913 llvm::ConstantInt::get(CGM.Int32Ty, 0),
1914 llvm::ConstantInt::get(CGM.Int32Ty, 1)};
1915 // Create a GEP which points just after the first entry in the VFTable,
1916 // this should be the location of the first virtual method.
1917 llvm::Constant *VTableGEP = llvm::ConstantExpr::getInBoundsGetElementPtr(
1918 VTable->getValueType(), VTable, GEPIndices);
1919 if (llvm::GlobalValue::isWeakForLinker(VFTableLinkage)) {
1920 VFTableLinkage = llvm::GlobalValue::ExternalLinkage;
1921 if (C)
1922 C->setSelectionKind(llvm::Comdat::Largest);
1924 VFTable = llvm::GlobalAlias::create(CGM.Int8PtrTy,
1925 /*AddressSpace=*/0, VFTableLinkage,
1926 VFTableName.str(), VTableGEP,
1927 &CGM.getModule());
1928 VFTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1929 } else {
1930 // We don't need a GlobalAlias to be a symbol for the VTable if we won't
1931 // be referencing any RTTI data.
1932 // The GlobalVariable will end up being an appropriate definition of the
1933 // VFTable.
1934 VFTable = VTable;
1936 if (C)
1937 VTable->setComdat(C);
1939 if (RD->hasAttr<DLLExportAttr>())
1940 VFTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1942 VFTablesMap[ID] = VFTable;
1943 return VTable;
1946 CGCallee MicrosoftCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1947 GlobalDecl GD,
1948 Address This,
1949 llvm::Type *Ty,
1950 SourceLocation Loc) {
1951 CGBuilderTy &Builder = CGF.Builder;
1953 Ty = CGF.UnqualPtrTy;
1954 Address VPtr =
1955 adjustThisArgumentForVirtualFunctionCall(CGF, GD, This, true);
1957 auto *MethodDecl = cast<CXXMethodDecl>(GD.getDecl());
1958 llvm::Value *VTable =
1959 CGF.GetVTablePtr(VPtr, CGF.UnqualPtrTy, MethodDecl->getParent());
1961 MicrosoftVTableContext &VFTContext = CGM.getMicrosoftVTableContext();
1962 MethodVFTableLocation ML = VFTContext.getMethodVFTableLocation(GD);
1964 // Compute the identity of the most derived class whose virtual table is
1965 // located at the MethodVFTableLocation ML.
1966 auto getObjectWithVPtr = [&] {
1967 return llvm::find_if(VFTContext.getVFPtrOffsets(
1968 ML.VBase ? ML.VBase : MethodDecl->getParent()),
1969 [&](const std::unique_ptr<VPtrInfo> &Info) {
1970 return Info->FullOffsetInMDC == ML.VFPtrOffset;
1972 ->get()
1973 ->ObjectWithVPtr;
1976 llvm::Value *VFunc;
1977 if (CGF.ShouldEmitVTableTypeCheckedLoad(MethodDecl->getParent())) {
1978 VFunc = CGF.EmitVTableTypeCheckedLoad(
1979 getObjectWithVPtr(), VTable, Ty,
1980 ML.Index *
1981 CGM.getContext().getTargetInfo().getPointerWidth(LangAS::Default) /
1983 } else {
1984 if (CGM.getCodeGenOpts().PrepareForLTO)
1985 CGF.EmitTypeMetadataCodeForVCall(getObjectWithVPtr(), VTable, Loc);
1987 llvm::Value *VFuncPtr =
1988 Builder.CreateConstInBoundsGEP1_64(Ty, VTable, ML.Index, "vfn");
1989 VFunc = Builder.CreateAlignedLoad(Ty, VFuncPtr, CGF.getPointerAlign());
1992 CGCallee Callee(GD, VFunc);
1993 return Callee;
1996 llvm::Value *MicrosoftCXXABI::EmitVirtualDestructorCall(
1997 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
1998 Address This, DeleteOrMemberCallExpr E, llvm::CallBase **CallOrInvoke) {
1999 auto *CE = E.dyn_cast<const CXXMemberCallExpr *>();
2000 auto *D = E.dyn_cast<const CXXDeleteExpr *>();
2001 assert((CE != nullptr) ^ (D != nullptr));
2002 assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
2003 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
2005 // We have only one destructor in the vftable but can get both behaviors
2006 // by passing an implicit int parameter.
2007 GlobalDecl GD(Dtor, Dtor_Deleting);
2008 const CGFunctionInfo *FInfo =
2009 &CGM.getTypes().arrangeCXXStructorDeclaration(GD);
2010 llvm::FunctionType *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
2011 CGCallee Callee = CGCallee::forVirtual(CE, GD, This, Ty);
2013 ASTContext &Context = getContext();
2014 llvm::Value *ImplicitParam = llvm::ConstantInt::get(
2015 llvm::IntegerType::getInt32Ty(CGF.getLLVMContext()),
2016 DtorType == Dtor_Deleting);
2018 QualType ThisTy;
2019 if (CE) {
2020 ThisTy = CE->getObjectType();
2021 } else {
2022 ThisTy = D->getDestroyedType();
2025 This = adjustThisArgumentForVirtualFunctionCall(CGF, GD, This, true);
2026 RValue RV =
2027 CGF.EmitCXXDestructorCall(GD, Callee, This.emitRawPointer(CGF), ThisTy,
2028 ImplicitParam, Context.IntTy, CE, CallOrInvoke);
2029 return RV.getScalarVal();
2032 const VBTableGlobals &
2033 MicrosoftCXXABI::enumerateVBTables(const CXXRecordDecl *RD) {
2034 // At this layer, we can key the cache off of a single class, which is much
2035 // easier than caching each vbtable individually.
2036 llvm::DenseMap<const CXXRecordDecl*, VBTableGlobals>::iterator Entry;
2037 bool Added;
2038 std::tie(Entry, Added) =
2039 VBTablesMap.insert(std::make_pair(RD, VBTableGlobals()));
2040 VBTableGlobals &VBGlobals = Entry->second;
2041 if (!Added)
2042 return VBGlobals;
2044 MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext();
2045 VBGlobals.VBTables = &Context.enumerateVBTables(RD);
2047 // Cache the globals for all vbtables so we don't have to recompute the
2048 // mangled names.
2049 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
2050 for (VPtrInfoVector::const_iterator I = VBGlobals.VBTables->begin(),
2051 E = VBGlobals.VBTables->end();
2052 I != E; ++I) {
2053 VBGlobals.Globals.push_back(getAddrOfVBTable(**I, RD, Linkage));
2056 return VBGlobals;
2059 llvm::Function *
2060 MicrosoftCXXABI::EmitVirtualMemPtrThunk(const CXXMethodDecl *MD,
2061 const MethodVFTableLocation &ML) {
2062 assert(!isa<CXXConstructorDecl>(MD) && !isa<CXXDestructorDecl>(MD) &&
2063 "can't form pointers to ctors or virtual dtors");
2065 // Calculate the mangled name.
2066 SmallString<256> ThunkName;
2067 llvm::raw_svector_ostream Out(ThunkName);
2068 getMangleContext().mangleVirtualMemPtrThunk(MD, ML, Out);
2070 // If the thunk has been generated previously, just return it.
2071 if (llvm::GlobalValue *GV = CGM.getModule().getNamedValue(ThunkName))
2072 return cast<llvm::Function>(GV);
2074 // Create the llvm::Function.
2075 const CGFunctionInfo &FnInfo =
2076 CGM.getTypes().arrangeUnprototypedMustTailThunk(MD);
2077 llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo);
2078 llvm::Function *ThunkFn =
2079 llvm::Function::Create(ThunkTy, llvm::Function::ExternalLinkage,
2080 ThunkName.str(), &CGM.getModule());
2081 assert(ThunkFn->getName() == ThunkName && "name was uniqued!");
2083 ThunkFn->setLinkage(MD->isExternallyVisible()
2084 ? llvm::GlobalValue::LinkOnceODRLinkage
2085 : llvm::GlobalValue::InternalLinkage);
2086 if (MD->isExternallyVisible())
2087 ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));
2089 CGM.SetLLVMFunctionAttributes(MD, FnInfo, ThunkFn, /*IsThunk=*/false);
2090 CGM.SetLLVMFunctionAttributesForDefinition(MD, ThunkFn);
2092 // Add the "thunk" attribute so that LLVM knows that the return type is
2093 // meaningless. These thunks can be used to call functions with differing
2094 // return types, and the caller is required to cast the prototype
2095 // appropriately to extract the correct value.
2096 ThunkFn->addFnAttr("thunk");
2098 // These thunks can be compared, so they are not unnamed.
2099 ThunkFn->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::None);
2101 // Start codegen.
2102 CodeGenFunction CGF(CGM);
2103 CGF.CurGD = GlobalDecl(MD);
2104 CGF.CurFuncIsThunk = true;
2106 // Build FunctionArgs, but only include the implicit 'this' parameter
2107 // declaration.
2108 FunctionArgList FunctionArgs;
2109 buildThisParam(CGF, FunctionArgs);
2111 // Start defining the function.
2112 CGF.StartFunction(GlobalDecl(), FnInfo.getReturnType(), ThunkFn, FnInfo,
2113 FunctionArgs, MD->getLocation(), SourceLocation());
2115 ApplyDebugLocation AL(CGF, MD->getLocation());
2116 setCXXABIThisValue(CGF, loadIncomingCXXThis(CGF));
2118 // Load the vfptr and then callee from the vftable. The callee should have
2119 // adjusted 'this' so that the vfptr is at offset zero.
2120 llvm::Type *ThunkPtrTy = CGF.UnqualPtrTy;
2121 llvm::Value *VTable =
2122 CGF.GetVTablePtr(getThisAddress(CGF), CGF.UnqualPtrTy, MD->getParent());
2124 llvm::Value *VFuncPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
2125 ThunkPtrTy, VTable, ML.Index, "vfn");
2126 llvm::Value *Callee =
2127 CGF.Builder.CreateAlignedLoad(ThunkPtrTy, VFuncPtr, CGF.getPointerAlign());
2129 CGF.EmitMustTailThunk(MD, getThisValue(CGF), {ThunkTy, Callee});
2131 return ThunkFn;
2134 void MicrosoftCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
2135 const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
2136 for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) {
2137 const std::unique_ptr<VPtrInfo>& VBT = (*VBGlobals.VBTables)[I];
2138 llvm::GlobalVariable *GV = VBGlobals.Globals[I];
2139 if (GV->isDeclaration())
2140 emitVBTableDefinition(*VBT, RD, GV);
2144 llvm::GlobalVariable *
2145 MicrosoftCXXABI::getAddrOfVBTable(const VPtrInfo &VBT, const CXXRecordDecl *RD,
2146 llvm::GlobalVariable::LinkageTypes Linkage) {
2147 SmallString<256> OutName;
2148 llvm::raw_svector_ostream Out(OutName);
2149 getMangleContext().mangleCXXVBTable(RD, VBT.MangledPath, Out);
2150 StringRef Name = OutName.str();
2152 llvm::ArrayType *VBTableType =
2153 llvm::ArrayType::get(CGM.IntTy, 1 + VBT.ObjectWithVPtr->getNumVBases());
2155 assert(!CGM.getModule().getNamedGlobal(Name) &&
2156 "vbtable with this name already exists: mangling bug?");
2157 CharUnits Alignment =
2158 CGM.getContext().getTypeAlignInChars(CGM.getContext().IntTy);
2159 llvm::GlobalVariable *GV = CGM.CreateOrReplaceCXXRuntimeVariable(
2160 Name, VBTableType, Linkage, Alignment.getAsAlign());
2161 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2163 if (RD->hasAttr<DLLImportAttr>())
2164 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2165 else if (RD->hasAttr<DLLExportAttr>())
2166 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
2168 if (!GV->hasExternalLinkage())
2169 emitVBTableDefinition(VBT, RD, GV);
2171 return GV;
2174 void MicrosoftCXXABI::emitVBTableDefinition(const VPtrInfo &VBT,
2175 const CXXRecordDecl *RD,
2176 llvm::GlobalVariable *GV) const {
2177 const CXXRecordDecl *ObjectWithVPtr = VBT.ObjectWithVPtr;
2179 assert(RD->getNumVBases() && ObjectWithVPtr->getNumVBases() &&
2180 "should only emit vbtables for classes with vbtables");
2182 const ASTRecordLayout &BaseLayout =
2183 getContext().getASTRecordLayout(VBT.IntroducingObject);
2184 const ASTRecordLayout &DerivedLayout = getContext().getASTRecordLayout(RD);
2186 SmallVector<llvm::Constant *, 4> Offsets(1 + ObjectWithVPtr->getNumVBases(),
2187 nullptr);
2189 // The offset from ObjectWithVPtr's vbptr to itself always leads.
2190 CharUnits VBPtrOffset = BaseLayout.getVBPtrOffset();
2191 Offsets[0] = llvm::ConstantInt::get(CGM.IntTy, -VBPtrOffset.getQuantity());
2193 MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext();
2194 for (const auto &I : ObjectWithVPtr->vbases()) {
2195 const CXXRecordDecl *VBase = I.getType()->getAsCXXRecordDecl();
2196 CharUnits Offset = DerivedLayout.getVBaseClassOffset(VBase);
2197 assert(!Offset.isNegative());
2199 // Make it relative to the subobject vbptr.
2200 CharUnits CompleteVBPtrOffset = VBT.NonVirtualOffset + VBPtrOffset;
2201 if (VBT.getVBaseWithVPtr())
2202 CompleteVBPtrOffset +=
2203 DerivedLayout.getVBaseClassOffset(VBT.getVBaseWithVPtr());
2204 Offset -= CompleteVBPtrOffset;
2206 unsigned VBIndex = Context.getVBTableIndex(ObjectWithVPtr, VBase);
2207 assert(Offsets[VBIndex] == nullptr && "The same vbindex seen twice?");
2208 Offsets[VBIndex] = llvm::ConstantInt::get(CGM.IntTy, Offset.getQuantity());
2211 assert(Offsets.size() ==
2212 cast<llvm::ArrayType>(GV->getValueType())->getNumElements());
2213 llvm::ArrayType *VBTableType =
2214 llvm::ArrayType::get(CGM.IntTy, Offsets.size());
2215 llvm::Constant *Init = llvm::ConstantArray::get(VBTableType, Offsets);
2216 GV->setInitializer(Init);
2218 if (RD->hasAttr<DLLImportAttr>())
2219 GV->setLinkage(llvm::GlobalVariable::AvailableExternallyLinkage);
2222 llvm::Value *MicrosoftCXXABI::performThisAdjustment(
2223 CodeGenFunction &CGF, Address This,
2224 const CXXRecordDecl * /*UnadjustedClass*/, const ThunkInfo &TI) {
2225 const ThisAdjustment &TA = TI.This;
2226 if (TA.isEmpty())
2227 return This.emitRawPointer(CGF);
2229 This = This.withElementType(CGF.Int8Ty);
2231 llvm::Value *V;
2232 if (TA.Virtual.isEmpty()) {
2233 V = This.emitRawPointer(CGF);
2234 } else {
2235 assert(TA.Virtual.Microsoft.VtordispOffset < 0);
2236 // Adjust the this argument based on the vtordisp value.
2237 Address VtorDispPtr =
2238 CGF.Builder.CreateConstInBoundsByteGEP(This,
2239 CharUnits::fromQuantity(TA.Virtual.Microsoft.VtordispOffset));
2240 VtorDispPtr = VtorDispPtr.withElementType(CGF.Int32Ty);
2241 llvm::Value *VtorDisp = CGF.Builder.CreateLoad(VtorDispPtr, "vtordisp");
2242 V = CGF.Builder.CreateGEP(This.getElementType(), This.emitRawPointer(CGF),
2243 CGF.Builder.CreateNeg(VtorDisp));
2245 // Unfortunately, having applied the vtordisp means that we no
2246 // longer really have a known alignment for the vbptr step.
2247 // We'll assume the vbptr is pointer-aligned.
2249 if (TA.Virtual.Microsoft.VBPtrOffset) {
2250 // If the final overrider is defined in a virtual base other than the one
2251 // that holds the vfptr, we have to use a vtordispex thunk which looks up
2252 // the vbtable of the derived class.
2253 assert(TA.Virtual.Microsoft.VBPtrOffset > 0);
2254 assert(TA.Virtual.Microsoft.VBOffsetOffset >= 0);
2255 llvm::Value *VBPtr;
2256 llvm::Value *VBaseOffset = GetVBaseOffsetFromVBPtr(
2257 CGF, Address(V, CGF.Int8Ty, CGF.getPointerAlign()),
2258 -TA.Virtual.Microsoft.VBPtrOffset,
2259 TA.Virtual.Microsoft.VBOffsetOffset, &VBPtr);
2260 V = CGF.Builder.CreateInBoundsGEP(CGF.Int8Ty, VBPtr, VBaseOffset);
2264 if (TA.NonVirtual) {
2265 // Non-virtual adjustment might result in a pointer outside the allocated
2266 // object, e.g. if the final overrider class is laid out after the virtual
2267 // base that declares a method in the most derived class.
2268 V = CGF.Builder.CreateConstGEP1_32(CGF.Int8Ty, V, TA.NonVirtual);
2271 // Don't need to bitcast back, the call CodeGen will handle this.
2272 return V;
2275 llvm::Value *MicrosoftCXXABI::performReturnAdjustment(
2276 CodeGenFunction &CGF, Address Ret,
2277 const CXXRecordDecl * /*UnadjustedClass*/, const ReturnAdjustment &RA) {
2279 if (RA.isEmpty())
2280 return Ret.emitRawPointer(CGF);
2282 Ret = Ret.withElementType(CGF.Int8Ty);
2284 llvm::Value *V = Ret.emitRawPointer(CGF);
2285 if (RA.Virtual.Microsoft.VBIndex) {
2286 assert(RA.Virtual.Microsoft.VBIndex > 0);
2287 int32_t IntSize = CGF.getIntSize().getQuantity();
2288 llvm::Value *VBPtr;
2289 llvm::Value *VBaseOffset =
2290 GetVBaseOffsetFromVBPtr(CGF, Ret, RA.Virtual.Microsoft.VBPtrOffset,
2291 IntSize * RA.Virtual.Microsoft.VBIndex, &VBPtr);
2292 V = CGF.Builder.CreateInBoundsGEP(CGF.Int8Ty, VBPtr, VBaseOffset);
2295 if (RA.NonVirtual)
2296 V = CGF.Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, V, RA.NonVirtual);
2298 return V;
2301 bool MicrosoftCXXABI::requiresArrayCookie(const CXXDeleteExpr *expr,
2302 QualType elementType) {
2303 // Microsoft seems to completely ignore the possibility of a
2304 // two-argument usual deallocation function.
2305 return elementType.isDestructedType();
2308 bool MicrosoftCXXABI::requiresArrayCookie(const CXXNewExpr *expr) {
2309 // Microsoft seems to completely ignore the possibility of a
2310 // two-argument usual deallocation function.
2311 return expr->getAllocatedType().isDestructedType();
2314 CharUnits MicrosoftCXXABI::getArrayCookieSizeImpl(QualType type) {
2315 // The array cookie is always a size_t; we then pad that out to the
2316 // alignment of the element type.
2317 ASTContext &Ctx = getContext();
2318 return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()),
2319 Ctx.getTypeAlignInChars(type));
2322 llvm::Value *MicrosoftCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
2323 Address allocPtr,
2324 CharUnits cookieSize) {
2325 Address numElementsPtr = allocPtr.withElementType(CGF.SizeTy);
2326 return CGF.Builder.CreateLoad(numElementsPtr);
2329 Address MicrosoftCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
2330 Address newPtr,
2331 llvm::Value *numElements,
2332 const CXXNewExpr *expr,
2333 QualType elementType) {
2334 assert(requiresArrayCookie(expr));
2336 // The size of the cookie.
2337 CharUnits cookieSize = getArrayCookieSizeImpl(elementType);
2339 // Compute an offset to the cookie.
2340 Address cookiePtr = newPtr;
2342 // Write the number of elements into the appropriate slot.
2343 Address numElementsPtr = cookiePtr.withElementType(CGF.SizeTy);
2344 CGF.Builder.CreateStore(numElements, numElementsPtr);
2346 // Finally, compute a pointer to the actual data buffer by skipping
2347 // over the cookie completely.
2348 return CGF.Builder.CreateConstInBoundsByteGEP(newPtr, cookieSize);
2351 static void emitGlobalDtorWithTLRegDtor(CodeGenFunction &CGF, const VarDecl &VD,
2352 llvm::FunctionCallee Dtor,
2353 llvm::Constant *Addr) {
2354 // Create a function which calls the destructor.
2355 llvm::Constant *DtorStub = CGF.createAtExitStub(VD, Dtor, Addr);
2357 // extern "C" int __tlregdtor(void (*f)(void));
2358 llvm::FunctionType *TLRegDtorTy = llvm::FunctionType::get(
2359 CGF.IntTy, DtorStub->getType(), /*isVarArg=*/false);
2361 llvm::FunctionCallee TLRegDtor = CGF.CGM.CreateRuntimeFunction(
2362 TLRegDtorTy, "__tlregdtor", llvm::AttributeList(), /*Local=*/true);
2363 if (llvm::Function *TLRegDtorFn =
2364 dyn_cast<llvm::Function>(TLRegDtor.getCallee()))
2365 TLRegDtorFn->setDoesNotThrow();
2367 CGF.EmitNounwindRuntimeCall(TLRegDtor, DtorStub);
2370 void MicrosoftCXXABI::registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
2371 llvm::FunctionCallee Dtor,
2372 llvm::Constant *Addr) {
2373 if (D.isNoDestroy(CGM.getContext()))
2374 return;
2376 if (D.getTLSKind())
2377 return emitGlobalDtorWithTLRegDtor(CGF, D, Dtor, Addr);
2379 // HLSL doesn't support atexit.
2380 if (CGM.getLangOpts().HLSL)
2381 return CGM.AddCXXDtorEntry(Dtor, Addr);
2383 // The default behavior is to use atexit.
2384 CGF.registerGlobalDtorWithAtExit(D, Dtor, Addr);
2387 void MicrosoftCXXABI::EmitThreadLocalInitFuncs(
2388 CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
2389 ArrayRef<llvm::Function *> CXXThreadLocalInits,
2390 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) {
2391 if (CXXThreadLocalInits.empty())
2392 return;
2394 CGM.AppendLinkerOptions(CGM.getTarget().getTriple().getArch() ==
2395 llvm::Triple::x86
2396 ? "/include:___dyn_tls_init@12"
2397 : "/include:__dyn_tls_init");
2399 // This will create a GV in the .CRT$XDU section. It will point to our
2400 // initialization function. The CRT will call all of these function
2401 // pointers at start-up time and, eventually, at thread-creation time.
2402 auto AddToXDU = [&CGM](llvm::Function *InitFunc) {
2403 llvm::GlobalVariable *InitFuncPtr = new llvm::GlobalVariable(
2404 CGM.getModule(), InitFunc->getType(), /*isConstant=*/true,
2405 llvm::GlobalVariable::InternalLinkage, InitFunc,
2406 Twine(InitFunc->getName(), "$initializer$"));
2407 InitFuncPtr->setSection(".CRT$XDU");
2408 // This variable has discardable linkage, we have to add it to @llvm.used to
2409 // ensure it won't get discarded.
2410 CGM.addUsedGlobal(InitFuncPtr);
2411 return InitFuncPtr;
2414 std::vector<llvm::Function *> NonComdatInits;
2415 for (size_t I = 0, E = CXXThreadLocalInitVars.size(); I != E; ++I) {
2416 llvm::GlobalVariable *GV = cast<llvm::GlobalVariable>(
2417 CGM.GetGlobalValue(CGM.getMangledName(CXXThreadLocalInitVars[I])));
2418 llvm::Function *F = CXXThreadLocalInits[I];
2420 // If the GV is already in a comdat group, then we have to join it.
2421 if (llvm::Comdat *C = GV->getComdat())
2422 AddToXDU(F)->setComdat(C);
2423 else
2424 NonComdatInits.push_back(F);
2427 if (!NonComdatInits.empty()) {
2428 llvm::FunctionType *FTy =
2429 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
2430 llvm::Function *InitFunc = CGM.CreateGlobalInitOrCleanUpFunction(
2431 FTy, "__tls_init", CGM.getTypes().arrangeNullaryFunction(),
2432 SourceLocation(), /*TLS=*/true);
2433 CodeGenFunction(CGM).GenerateCXXGlobalInitFunc(InitFunc, NonComdatInits);
2435 AddToXDU(InitFunc);
2439 static llvm::GlobalValue *getTlsGuardVar(CodeGenModule &CGM) {
2440 // __tls_guard comes from the MSVC runtime and reflects
2441 // whether TLS has been initialized for a particular thread.
2442 // It is set from within __dyn_tls_init by the runtime.
2443 // Every library and executable has its own variable.
2444 llvm::Type *VTy = llvm::Type::getInt8Ty(CGM.getLLVMContext());
2445 llvm::Constant *TlsGuardConstant =
2446 CGM.CreateRuntimeVariable(VTy, "__tls_guard");
2447 llvm::GlobalValue *TlsGuard = cast<llvm::GlobalValue>(TlsGuardConstant);
2449 TlsGuard->setThreadLocal(true);
2451 return TlsGuard;
2454 static llvm::FunctionCallee getDynTlsOnDemandInitFn(CodeGenModule &CGM) {
2455 // __dyn_tls_on_demand_init comes from the MSVC runtime and triggers
2456 // dynamic TLS initialization by calling __dyn_tls_init internally.
2457 llvm::FunctionType *FTy =
2458 llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()), {},
2459 /*isVarArg=*/false);
2460 return CGM.CreateRuntimeFunction(
2461 FTy, "__dyn_tls_on_demand_init",
2462 llvm::AttributeList::get(CGM.getLLVMContext(),
2463 llvm::AttributeList::FunctionIndex,
2464 llvm::Attribute::NoUnwind),
2465 /*Local=*/true);
2468 static void emitTlsGuardCheck(CodeGenFunction &CGF, llvm::GlobalValue *TlsGuard,
2469 llvm::BasicBlock *DynInitBB,
2470 llvm::BasicBlock *ContinueBB) {
2471 llvm::LoadInst *TlsGuardValue =
2472 CGF.Builder.CreateLoad(Address(TlsGuard, CGF.Int8Ty, CharUnits::One()));
2473 llvm::Value *CmpResult =
2474 CGF.Builder.CreateICmpEQ(TlsGuardValue, CGF.Builder.getInt8(0));
2475 CGF.Builder.CreateCondBr(CmpResult, DynInitBB, ContinueBB);
2478 static void emitDynamicTlsInitializationCall(CodeGenFunction &CGF,
2479 llvm::GlobalValue *TlsGuard,
2480 llvm::BasicBlock *ContinueBB) {
2481 llvm::FunctionCallee Initializer = getDynTlsOnDemandInitFn(CGF.CGM);
2482 llvm::Function *InitializerFunction =
2483 cast<llvm::Function>(Initializer.getCallee());
2484 llvm::CallInst *CallVal = CGF.Builder.CreateCall(InitializerFunction);
2485 CallVal->setCallingConv(InitializerFunction->getCallingConv());
2487 CGF.Builder.CreateBr(ContinueBB);
2490 static void emitDynamicTlsInitialization(CodeGenFunction &CGF) {
2491 llvm::BasicBlock *DynInitBB =
2492 CGF.createBasicBlock("dyntls.dyn_init", CGF.CurFn);
2493 llvm::BasicBlock *ContinueBB =
2494 CGF.createBasicBlock("dyntls.continue", CGF.CurFn);
2496 llvm::GlobalValue *TlsGuard = getTlsGuardVar(CGF.CGM);
2498 emitTlsGuardCheck(CGF, TlsGuard, DynInitBB, ContinueBB);
2499 CGF.Builder.SetInsertPoint(DynInitBB);
2500 emitDynamicTlsInitializationCall(CGF, TlsGuard, ContinueBB);
2501 CGF.Builder.SetInsertPoint(ContinueBB);
2504 LValue MicrosoftCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
2505 const VarDecl *VD,
2506 QualType LValType) {
2507 // Dynamic TLS initialization works by checking the state of a
2508 // guard variable (__tls_guard) to see whether TLS initialization
2509 // for a thread has happend yet.
2510 // If not, the initialization is triggered on-demand
2511 // by calling __dyn_tls_on_demand_init.
2512 emitDynamicTlsInitialization(CGF);
2514 // Emit the variable just like any regular global variable.
2516 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
2517 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
2519 CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
2520 Address Addr(V, RealVarTy, Alignment);
2522 LValue LV = VD->getType()->isReferenceType()
2523 ? CGF.EmitLoadOfReferenceLValue(Addr, VD->getType(),
2524 AlignmentSource::Decl)
2525 : CGF.MakeAddrLValue(Addr, LValType, AlignmentSource::Decl);
2526 return LV;
2529 static ConstantAddress getInitThreadEpochPtr(CodeGenModule &CGM) {
2530 StringRef VarName("_Init_thread_epoch");
2531 CharUnits Align = CGM.getIntAlign();
2532 if (auto *GV = CGM.getModule().getNamedGlobal(VarName))
2533 return ConstantAddress(GV, GV->getValueType(), Align);
2534 auto *GV = new llvm::GlobalVariable(
2535 CGM.getModule(), CGM.IntTy,
2536 /*isConstant=*/false, llvm::GlobalVariable::ExternalLinkage,
2537 /*Initializer=*/nullptr, VarName,
2538 /*InsertBefore=*/nullptr, llvm::GlobalVariable::GeneralDynamicTLSModel);
2539 GV->setAlignment(Align.getAsAlign());
2540 return ConstantAddress(GV, GV->getValueType(), Align);
2543 static llvm::FunctionCallee getInitThreadHeaderFn(CodeGenModule &CGM) {
2544 llvm::FunctionType *FTy =
2545 llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
2546 CGM.UnqualPtrTy, /*isVarArg=*/false);
2547 return CGM.CreateRuntimeFunction(
2548 FTy, "_Init_thread_header",
2549 llvm::AttributeList::get(CGM.getLLVMContext(),
2550 llvm::AttributeList::FunctionIndex,
2551 llvm::Attribute::NoUnwind),
2552 /*Local=*/true);
2555 static llvm::FunctionCallee getInitThreadFooterFn(CodeGenModule &CGM) {
2556 llvm::FunctionType *FTy =
2557 llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
2558 CGM.UnqualPtrTy, /*isVarArg=*/false);
2559 return CGM.CreateRuntimeFunction(
2560 FTy, "_Init_thread_footer",
2561 llvm::AttributeList::get(CGM.getLLVMContext(),
2562 llvm::AttributeList::FunctionIndex,
2563 llvm::Attribute::NoUnwind),
2564 /*Local=*/true);
2567 static llvm::FunctionCallee getInitThreadAbortFn(CodeGenModule &CGM) {
2568 llvm::FunctionType *FTy =
2569 llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
2570 CGM.UnqualPtrTy, /*isVarArg=*/false);
2571 return CGM.CreateRuntimeFunction(
2572 FTy, "_Init_thread_abort",
2573 llvm::AttributeList::get(CGM.getLLVMContext(),
2574 llvm::AttributeList::FunctionIndex,
2575 llvm::Attribute::NoUnwind),
2576 /*Local=*/true);
2579 namespace {
2580 struct ResetGuardBit final : EHScopeStack::Cleanup {
2581 Address Guard;
2582 unsigned GuardNum;
2583 ResetGuardBit(Address Guard, unsigned GuardNum)
2584 : Guard(Guard), GuardNum(GuardNum) {}
2586 void Emit(CodeGenFunction &CGF, Flags flags) override {
2587 // Reset the bit in the mask so that the static variable may be
2588 // reinitialized.
2589 CGBuilderTy &Builder = CGF.Builder;
2590 llvm::LoadInst *LI = Builder.CreateLoad(Guard);
2591 llvm::ConstantInt *Mask =
2592 llvm::ConstantInt::get(CGF.IntTy, ~(1ULL << GuardNum));
2593 Builder.CreateStore(Builder.CreateAnd(LI, Mask), Guard);
2597 struct CallInitThreadAbort final : EHScopeStack::Cleanup {
2598 llvm::Value *Guard;
2599 CallInitThreadAbort(RawAddress Guard) : Guard(Guard.getPointer()) {}
2601 void Emit(CodeGenFunction &CGF, Flags flags) override {
2602 // Calling _Init_thread_abort will reset the guard's state.
2603 CGF.EmitNounwindRuntimeCall(getInitThreadAbortFn(CGF.CGM), Guard);
2608 void MicrosoftCXXABI::EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
2609 llvm::GlobalVariable *GV,
2610 bool PerformInit) {
2611 // MSVC only uses guards for static locals.
2612 if (!D.isStaticLocal()) {
2613 assert(GV->hasWeakLinkage() || GV->hasLinkOnceLinkage());
2614 // GlobalOpt is allowed to discard the initializer, so use linkonce_odr.
2615 llvm::Function *F = CGF.CurFn;
2616 F->setLinkage(llvm::GlobalValue::LinkOnceODRLinkage);
2617 F->setComdat(CGM.getModule().getOrInsertComdat(F->getName()));
2618 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
2619 return;
2622 bool ThreadlocalStatic = D.getTLSKind();
2623 bool ThreadsafeStatic = getContext().getLangOpts().ThreadsafeStatics;
2625 // Thread-safe static variables which aren't thread-specific have a
2626 // per-variable guard.
2627 bool HasPerVariableGuard = ThreadsafeStatic && !ThreadlocalStatic;
2629 CGBuilderTy &Builder = CGF.Builder;
2630 llvm::IntegerType *GuardTy = CGF.Int32Ty;
2631 llvm::ConstantInt *Zero = llvm::ConstantInt::get(GuardTy, 0);
2632 CharUnits GuardAlign = CharUnits::fromQuantity(4);
2634 // Get the guard variable for this function if we have one already.
2635 GuardInfo *GI = nullptr;
2636 if (ThreadlocalStatic)
2637 GI = &ThreadLocalGuardVariableMap[D.getDeclContext()];
2638 else if (!ThreadsafeStatic)
2639 GI = &GuardVariableMap[D.getDeclContext()];
2641 llvm::GlobalVariable *GuardVar = GI ? GI->Guard : nullptr;
2642 unsigned GuardNum;
2643 if (D.isExternallyVisible()) {
2644 // Externally visible variables have to be numbered in Sema to properly
2645 // handle unreachable VarDecls.
2646 GuardNum = getContext().getStaticLocalNumber(&D);
2647 assert(GuardNum > 0);
2648 GuardNum--;
2649 } else if (HasPerVariableGuard) {
2650 GuardNum = ThreadSafeGuardNumMap[D.getDeclContext()]++;
2651 } else {
2652 // Non-externally visible variables are numbered here in CodeGen.
2653 GuardNum = GI->BitIndex++;
2656 if (!HasPerVariableGuard && GuardNum >= 32) {
2657 if (D.isExternallyVisible())
2658 ErrorUnsupportedABI(CGF, "more than 32 guarded initializations");
2659 GuardNum %= 32;
2660 GuardVar = nullptr;
2663 if (!GuardVar) {
2664 // Mangle the name for the guard.
2665 SmallString<256> GuardName;
2667 llvm::raw_svector_ostream Out(GuardName);
2668 if (HasPerVariableGuard)
2669 getMangleContext().mangleThreadSafeStaticGuardVariable(&D, GuardNum,
2670 Out);
2671 else
2672 getMangleContext().mangleStaticGuardVariable(&D, Out);
2675 // Create the guard variable with a zero-initializer. Just absorb linkage,
2676 // visibility and dll storage class from the guarded variable.
2677 GuardVar =
2678 new llvm::GlobalVariable(CGM.getModule(), GuardTy, /*isConstant=*/false,
2679 GV->getLinkage(), Zero, GuardName.str());
2680 GuardVar->setVisibility(GV->getVisibility());
2681 GuardVar->setDLLStorageClass(GV->getDLLStorageClass());
2682 GuardVar->setAlignment(GuardAlign.getAsAlign());
2683 if (GuardVar->isWeakForLinker())
2684 GuardVar->setComdat(
2685 CGM.getModule().getOrInsertComdat(GuardVar->getName()));
2686 if (D.getTLSKind())
2687 CGM.setTLSMode(GuardVar, D);
2688 if (GI && !HasPerVariableGuard)
2689 GI->Guard = GuardVar;
2692 ConstantAddress GuardAddr(GuardVar, GuardTy, GuardAlign);
2694 assert(GuardVar->getLinkage() == GV->getLinkage() &&
2695 "static local from the same function had different linkage");
2697 if (!HasPerVariableGuard) {
2698 // Pseudo code for the test:
2699 // if (!(GuardVar & MyGuardBit)) {
2700 // GuardVar |= MyGuardBit;
2701 // ... initialize the object ...;
2702 // }
2704 // Test our bit from the guard variable.
2705 llvm::ConstantInt *Bit = llvm::ConstantInt::get(GuardTy, 1ULL << GuardNum);
2706 llvm::LoadInst *LI = Builder.CreateLoad(GuardAddr);
2707 llvm::Value *NeedsInit =
2708 Builder.CreateICmpEQ(Builder.CreateAnd(LI, Bit), Zero);
2709 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
2710 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2711 CGF.EmitCXXGuardedInitBranch(NeedsInit, InitBlock, EndBlock,
2712 CodeGenFunction::GuardKind::VariableGuard, &D);
2714 // Set our bit in the guard variable and emit the initializer and add a global
2715 // destructor if appropriate.
2716 CGF.EmitBlock(InitBlock);
2717 Builder.CreateStore(Builder.CreateOr(LI, Bit), GuardAddr);
2718 CGF.EHStack.pushCleanup<ResetGuardBit>(EHCleanup, GuardAddr, GuardNum);
2719 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
2720 CGF.PopCleanupBlock();
2721 Builder.CreateBr(EndBlock);
2723 // Continue.
2724 CGF.EmitBlock(EndBlock);
2725 } else {
2726 // Pseudo code for the test:
2727 // if (TSS > _Init_thread_epoch) {
2728 // _Init_thread_header(&TSS);
2729 // if (TSS == -1) {
2730 // ... initialize the object ...;
2731 // _Init_thread_footer(&TSS);
2732 // }
2733 // }
2735 // The algorithm is almost identical to what can be found in the appendix
2736 // found in N2325.
2738 // This BasicBLock determines whether or not we have any work to do.
2739 llvm::LoadInst *FirstGuardLoad = Builder.CreateLoad(GuardAddr);
2740 FirstGuardLoad->setOrdering(llvm::AtomicOrdering::Unordered);
2741 llvm::LoadInst *InitThreadEpoch =
2742 Builder.CreateLoad(getInitThreadEpochPtr(CGM));
2743 llvm::Value *IsUninitialized =
2744 Builder.CreateICmpSGT(FirstGuardLoad, InitThreadEpoch);
2745 llvm::BasicBlock *AttemptInitBlock = CGF.createBasicBlock("init.attempt");
2746 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2747 CGF.EmitCXXGuardedInitBranch(IsUninitialized, AttemptInitBlock, EndBlock,
2748 CodeGenFunction::GuardKind::VariableGuard, &D);
2750 // This BasicBlock attempts to determine whether or not this thread is
2751 // responsible for doing the initialization.
2752 CGF.EmitBlock(AttemptInitBlock);
2753 CGF.EmitNounwindRuntimeCall(getInitThreadHeaderFn(CGM),
2754 GuardAddr.getPointer());
2755 llvm::LoadInst *SecondGuardLoad = Builder.CreateLoad(GuardAddr);
2756 SecondGuardLoad->setOrdering(llvm::AtomicOrdering::Unordered);
2757 llvm::Value *ShouldDoInit =
2758 Builder.CreateICmpEQ(SecondGuardLoad, getAllOnesInt());
2759 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
2760 Builder.CreateCondBr(ShouldDoInit, InitBlock, EndBlock);
2762 // Ok, we ended up getting selected as the initializing thread.
2763 CGF.EmitBlock(InitBlock);
2764 CGF.EHStack.pushCleanup<CallInitThreadAbort>(EHCleanup, GuardAddr);
2765 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
2766 CGF.PopCleanupBlock();
2767 CGF.EmitNounwindRuntimeCall(getInitThreadFooterFn(CGM),
2768 GuardAddr.getPointer());
2769 Builder.CreateBr(EndBlock);
2771 CGF.EmitBlock(EndBlock);
2775 bool MicrosoftCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
2776 // Null-ness for function memptrs only depends on the first field, which is
2777 // the function pointer. The rest don't matter, so we can zero initialize.
2778 if (MPT->isMemberFunctionPointer())
2779 return true;
2781 // The virtual base adjustment field is always -1 for null, so if we have one
2782 // we can't zero initialize. The field offset is sometimes also -1 if 0 is a
2783 // valid field offset.
2784 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2785 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
2786 return (!inheritanceModelHasVBTableOffsetField(Inheritance) &&
2787 RD->nullFieldOffsetIsZero());
2790 llvm::Type *
2791 MicrosoftCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
2792 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2793 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
2794 llvm::SmallVector<llvm::Type *, 4> fields;
2795 if (MPT->isMemberFunctionPointer())
2796 fields.push_back(CGM.VoidPtrTy); // FunctionPointerOrVirtualThunk
2797 else
2798 fields.push_back(CGM.IntTy); // FieldOffset
2800 if (inheritanceModelHasNVOffsetField(MPT->isMemberFunctionPointer(),
2801 Inheritance))
2802 fields.push_back(CGM.IntTy);
2803 if (inheritanceModelHasVBPtrOffsetField(Inheritance))
2804 fields.push_back(CGM.IntTy);
2805 if (inheritanceModelHasVBTableOffsetField(Inheritance))
2806 fields.push_back(CGM.IntTy); // VirtualBaseAdjustmentOffset
2808 if (fields.size() == 1)
2809 return fields[0];
2810 return llvm::StructType::get(CGM.getLLVMContext(), fields);
2813 void MicrosoftCXXABI::
2814 GetNullMemberPointerFields(const MemberPointerType *MPT,
2815 llvm::SmallVectorImpl<llvm::Constant *> &fields) {
2816 assert(fields.empty());
2817 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2818 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
2819 if (MPT->isMemberFunctionPointer()) {
2820 // FunctionPointerOrVirtualThunk
2821 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
2822 } else {
2823 if (RD->nullFieldOffsetIsZero())
2824 fields.push_back(getZeroInt()); // FieldOffset
2825 else
2826 fields.push_back(getAllOnesInt()); // FieldOffset
2829 if (inheritanceModelHasNVOffsetField(MPT->isMemberFunctionPointer(),
2830 Inheritance))
2831 fields.push_back(getZeroInt());
2832 if (inheritanceModelHasVBPtrOffsetField(Inheritance))
2833 fields.push_back(getZeroInt());
2834 if (inheritanceModelHasVBTableOffsetField(Inheritance))
2835 fields.push_back(getAllOnesInt());
2838 llvm::Constant *
2839 MicrosoftCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
2840 llvm::SmallVector<llvm::Constant *, 4> fields;
2841 GetNullMemberPointerFields(MPT, fields);
2842 if (fields.size() == 1)
2843 return fields[0];
2844 llvm::Constant *Res = llvm::ConstantStruct::getAnon(fields);
2845 assert(Res->getType() == ConvertMemberPointerType(MPT));
2846 return Res;
2849 llvm::Constant *
2850 MicrosoftCXXABI::EmitFullMemberPointer(llvm::Constant *FirstField,
2851 bool IsMemberFunction,
2852 const CXXRecordDecl *RD,
2853 CharUnits NonVirtualBaseAdjustment,
2854 unsigned VBTableIndex) {
2855 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
2857 // Single inheritance class member pointer are represented as scalars instead
2858 // of aggregates.
2859 if (inheritanceModelHasOnlyOneField(IsMemberFunction, Inheritance))
2860 return FirstField;
2862 llvm::SmallVector<llvm::Constant *, 4> fields;
2863 fields.push_back(FirstField);
2865 if (inheritanceModelHasNVOffsetField(IsMemberFunction, Inheritance))
2866 fields.push_back(llvm::ConstantInt::get(
2867 CGM.IntTy, NonVirtualBaseAdjustment.getQuantity()));
2869 if (inheritanceModelHasVBPtrOffsetField(Inheritance)) {
2870 CharUnits Offs = CharUnits::Zero();
2871 if (VBTableIndex)
2872 Offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
2873 fields.push_back(llvm::ConstantInt::get(CGM.IntTy, Offs.getQuantity()));
2876 // The rest of the fields are adjusted by conversions to a more derived class.
2877 if (inheritanceModelHasVBTableOffsetField(Inheritance))
2878 fields.push_back(llvm::ConstantInt::get(CGM.IntTy, VBTableIndex));
2880 return llvm::ConstantStruct::getAnon(fields);
2883 llvm::Constant *
2884 MicrosoftCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
2885 CharUnits offset) {
2886 return EmitMemberDataPointer(MPT->getMostRecentCXXRecordDecl(), offset);
2889 llvm::Constant *MicrosoftCXXABI::EmitMemberDataPointer(const CXXRecordDecl *RD,
2890 CharUnits offset) {
2891 if (RD->getMSInheritanceModel() ==
2892 MSInheritanceModel::Virtual)
2893 offset -= getContext().getOffsetOfBaseWithVBPtr(RD);
2894 llvm::Constant *FirstField =
2895 llvm::ConstantInt::get(CGM.IntTy, offset.getQuantity());
2896 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/false, RD,
2897 CharUnits::Zero(), /*VBTableIndex=*/0);
2900 llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const APValue &MP,
2901 QualType MPType) {
2902 const MemberPointerType *DstTy = MPType->castAs<MemberPointerType>();
2903 const ValueDecl *MPD = MP.getMemberPointerDecl();
2904 if (!MPD)
2905 return EmitNullMemberPointer(DstTy);
2907 ASTContext &Ctx = getContext();
2908 ArrayRef<const CXXRecordDecl *> MemberPointerPath = MP.getMemberPointerPath();
2910 llvm::Constant *C;
2911 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD)) {
2912 C = EmitMemberFunctionPointer(MD);
2913 } else {
2914 // For a pointer to data member, start off with the offset of the field in
2915 // the class in which it was declared, and convert from there if necessary.
2916 // For indirect field decls, get the outermost anonymous field and use the
2917 // parent class.
2918 CharUnits FieldOffset = Ctx.toCharUnitsFromBits(Ctx.getFieldOffset(MPD));
2919 const FieldDecl *FD = dyn_cast<FieldDecl>(MPD);
2920 if (!FD)
2921 FD = cast<FieldDecl>(*cast<IndirectFieldDecl>(MPD)->chain_begin());
2922 const CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getParent());
2923 RD = RD->getMostRecentNonInjectedDecl();
2924 C = EmitMemberDataPointer(RD, FieldOffset);
2927 if (!MemberPointerPath.empty()) {
2928 const CXXRecordDecl *SrcRD = cast<CXXRecordDecl>(MPD->getDeclContext());
2929 const Type *SrcRecTy = Ctx.getTypeDeclType(SrcRD).getTypePtr();
2930 const MemberPointerType *SrcTy =
2931 Ctx.getMemberPointerType(DstTy->getPointeeType(), SrcRecTy)
2932 ->castAs<MemberPointerType>();
2934 bool DerivedMember = MP.isMemberPointerToDerivedMember();
2935 SmallVector<const CXXBaseSpecifier *, 4> DerivedToBasePath;
2936 const CXXRecordDecl *PrevRD = SrcRD;
2937 for (const CXXRecordDecl *PathElem : MemberPointerPath) {
2938 const CXXRecordDecl *Base = nullptr;
2939 const CXXRecordDecl *Derived = nullptr;
2940 if (DerivedMember) {
2941 Base = PathElem;
2942 Derived = PrevRD;
2943 } else {
2944 Base = PrevRD;
2945 Derived = PathElem;
2947 for (const CXXBaseSpecifier &BS : Derived->bases())
2948 if (BS.getType()->getAsCXXRecordDecl()->getCanonicalDecl() ==
2949 Base->getCanonicalDecl())
2950 DerivedToBasePath.push_back(&BS);
2951 PrevRD = PathElem;
2953 assert(DerivedToBasePath.size() == MemberPointerPath.size());
2955 CastKind CK = DerivedMember ? CK_DerivedToBaseMemberPointer
2956 : CK_BaseToDerivedMemberPointer;
2957 C = EmitMemberPointerConversion(SrcTy, DstTy, CK, DerivedToBasePath.begin(),
2958 DerivedToBasePath.end(), C);
2960 return C;
2963 llvm::Constant *
2964 MicrosoftCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) {
2965 assert(MD->isInstance() && "Member function must not be static!");
2967 CharUnits NonVirtualBaseAdjustment = CharUnits::Zero();
2968 const CXXRecordDecl *RD = MD->getParent()->getMostRecentNonInjectedDecl();
2969 CodeGenTypes &Types = CGM.getTypes();
2971 unsigned VBTableIndex = 0;
2972 llvm::Constant *FirstField;
2973 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
2974 if (!MD->isVirtual()) {
2975 llvm::Type *Ty;
2976 // Check whether the function has a computable LLVM signature.
2977 if (Types.isFuncTypeConvertible(FPT)) {
2978 // The function has a computable LLVM signature; use the correct type.
2979 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
2980 } else {
2981 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
2982 // function type is incomplete.
2983 Ty = CGM.PtrDiffTy;
2985 FirstField = CGM.GetAddrOfFunction(MD, Ty);
2986 } else {
2987 auto &VTableContext = CGM.getMicrosoftVTableContext();
2988 MethodVFTableLocation ML = VTableContext.getMethodVFTableLocation(MD);
2989 FirstField = EmitVirtualMemPtrThunk(MD, ML);
2990 // Include the vfptr adjustment if the method is in a non-primary vftable.
2991 NonVirtualBaseAdjustment += ML.VFPtrOffset;
2992 if (ML.VBase)
2993 VBTableIndex = VTableContext.getVBTableIndex(RD, ML.VBase) * 4;
2996 if (VBTableIndex == 0 &&
2997 RD->getMSInheritanceModel() ==
2998 MSInheritanceModel::Virtual)
2999 NonVirtualBaseAdjustment -= getContext().getOffsetOfBaseWithVBPtr(RD);
3001 // The rest of the fields are common with data member pointers.
3002 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/true, RD,
3003 NonVirtualBaseAdjustment, VBTableIndex);
3006 /// Member pointers are the same if they're either bitwise identical *or* both
3007 /// null. Null-ness for function members is determined by the first field,
3008 /// while for data member pointers we must compare all fields.
3009 llvm::Value *
3010 MicrosoftCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
3011 llvm::Value *L,
3012 llvm::Value *R,
3013 const MemberPointerType *MPT,
3014 bool Inequality) {
3015 CGBuilderTy &Builder = CGF.Builder;
3017 // Handle != comparisons by switching the sense of all boolean operations.
3018 llvm::ICmpInst::Predicate Eq;
3019 llvm::Instruction::BinaryOps And, Or;
3020 if (Inequality) {
3021 Eq = llvm::ICmpInst::ICMP_NE;
3022 And = llvm::Instruction::Or;
3023 Or = llvm::Instruction::And;
3024 } else {
3025 Eq = llvm::ICmpInst::ICMP_EQ;
3026 And = llvm::Instruction::And;
3027 Or = llvm::Instruction::Or;
3030 // If this is a single field member pointer (single inheritance), this is a
3031 // single icmp.
3032 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
3033 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
3034 if (inheritanceModelHasOnlyOneField(MPT->isMemberFunctionPointer(),
3035 Inheritance))
3036 return Builder.CreateICmp(Eq, L, R);
3038 // Compare the first field.
3039 llvm::Value *L0 = Builder.CreateExtractValue(L, 0, "lhs.0");
3040 llvm::Value *R0 = Builder.CreateExtractValue(R, 0, "rhs.0");
3041 llvm::Value *Cmp0 = Builder.CreateICmp(Eq, L0, R0, "memptr.cmp.first");
3043 // Compare everything other than the first field.
3044 llvm::Value *Res = nullptr;
3045 llvm::StructType *LType = cast<llvm::StructType>(L->getType());
3046 for (unsigned I = 1, E = LType->getNumElements(); I != E; ++I) {
3047 llvm::Value *LF = Builder.CreateExtractValue(L, I);
3048 llvm::Value *RF = Builder.CreateExtractValue(R, I);
3049 llvm::Value *Cmp = Builder.CreateICmp(Eq, LF, RF, "memptr.cmp.rest");
3050 if (Res)
3051 Res = Builder.CreateBinOp(And, Res, Cmp);
3052 else
3053 Res = Cmp;
3056 // Check if the first field is 0 if this is a function pointer.
3057 if (MPT->isMemberFunctionPointer()) {
3058 // (l1 == r1 && ...) || l0 == 0
3059 llvm::Value *Zero = llvm::Constant::getNullValue(L0->getType());
3060 llvm::Value *IsZero = Builder.CreateICmp(Eq, L0, Zero, "memptr.cmp.iszero");
3061 Res = Builder.CreateBinOp(Or, Res, IsZero);
3064 // Combine the comparison of the first field, which must always be true for
3065 // this comparison to succeeed.
3066 return Builder.CreateBinOp(And, Res, Cmp0, "memptr.cmp");
3069 llvm::Value *
3070 MicrosoftCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
3071 llvm::Value *MemPtr,
3072 const MemberPointerType *MPT) {
3073 CGBuilderTy &Builder = CGF.Builder;
3074 llvm::SmallVector<llvm::Constant *, 4> fields;
3075 // We only need one field for member functions.
3076 if (MPT->isMemberFunctionPointer())
3077 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
3078 else
3079 GetNullMemberPointerFields(MPT, fields);
3080 assert(!fields.empty());
3081 llvm::Value *FirstField = MemPtr;
3082 if (MemPtr->getType()->isStructTy())
3083 FirstField = Builder.CreateExtractValue(MemPtr, 0);
3084 llvm::Value *Res = Builder.CreateICmpNE(FirstField, fields[0], "memptr.cmp0");
3086 // For function member pointers, we only need to test the function pointer
3087 // field. The other fields if any can be garbage.
3088 if (MPT->isMemberFunctionPointer())
3089 return Res;
3091 // Otherwise, emit a series of compares and combine the results.
3092 for (int I = 1, E = fields.size(); I < E; ++I) {
3093 llvm::Value *Field = Builder.CreateExtractValue(MemPtr, I);
3094 llvm::Value *Next = Builder.CreateICmpNE(Field, fields[I], "memptr.cmp");
3095 Res = Builder.CreateOr(Res, Next, "memptr.tobool");
3097 return Res;
3100 bool MicrosoftCXXABI::MemberPointerConstantIsNull(const MemberPointerType *MPT,
3101 llvm::Constant *Val) {
3102 // Function pointers are null if the pointer in the first field is null.
3103 if (MPT->isMemberFunctionPointer()) {
3104 llvm::Constant *FirstField = Val->getType()->isStructTy() ?
3105 Val->getAggregateElement(0U) : Val;
3106 return FirstField->isNullValue();
3109 // If it's not a function pointer and it's zero initializable, we can easily
3110 // check zero.
3111 if (isZeroInitializable(MPT) && Val->isNullValue())
3112 return true;
3114 // Otherwise, break down all the fields for comparison. Hopefully these
3115 // little Constants are reused, while a big null struct might not be.
3116 llvm::SmallVector<llvm::Constant *, 4> Fields;
3117 GetNullMemberPointerFields(MPT, Fields);
3118 if (Fields.size() == 1) {
3119 assert(Val->getType()->isIntegerTy());
3120 return Val == Fields[0];
3123 unsigned I, E;
3124 for (I = 0, E = Fields.size(); I != E; ++I) {
3125 if (Val->getAggregateElement(I) != Fields[I])
3126 break;
3128 return I == E;
3131 llvm::Value *
3132 MicrosoftCXXABI::GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
3133 Address This,
3134 llvm::Value *VBPtrOffset,
3135 llvm::Value *VBTableOffset,
3136 llvm::Value **VBPtrOut) {
3137 CGBuilderTy &Builder = CGF.Builder;
3138 // Load the vbtable pointer from the vbptr in the instance.
3139 llvm::Value *VBPtr = Builder.CreateInBoundsGEP(
3140 CGM.Int8Ty, This.emitRawPointer(CGF), VBPtrOffset, "vbptr");
3141 if (VBPtrOut)
3142 *VBPtrOut = VBPtr;
3144 CharUnits VBPtrAlign;
3145 if (auto CI = dyn_cast<llvm::ConstantInt>(VBPtrOffset)) {
3146 VBPtrAlign = This.getAlignment().alignmentAtOffset(
3147 CharUnits::fromQuantity(CI->getSExtValue()));
3148 } else {
3149 VBPtrAlign = CGF.getPointerAlign();
3152 llvm::Value *VBTable =
3153 Builder.CreateAlignedLoad(CGM.UnqualPtrTy, VBPtr, VBPtrAlign, "vbtable");
3155 // Translate from byte offset to table index. It improves analyzability.
3156 llvm::Value *VBTableIndex = Builder.CreateAShr(
3157 VBTableOffset, llvm::ConstantInt::get(VBTableOffset->getType(), 2),
3158 "vbtindex", /*isExact=*/true);
3160 // Load an i32 offset from the vb-table.
3161 llvm::Value *VBaseOffs =
3162 Builder.CreateInBoundsGEP(CGM.Int32Ty, VBTable, VBTableIndex);
3163 return Builder.CreateAlignedLoad(CGM.Int32Ty, VBaseOffs,
3164 CharUnits::fromQuantity(4), "vbase_offs");
3167 // Returns an adjusted base cast to i8*, since we do more address arithmetic on
3168 // it.
3169 llvm::Value *MicrosoftCXXABI::AdjustVirtualBase(
3170 CodeGenFunction &CGF, const Expr *E, const CXXRecordDecl *RD,
3171 Address Base, llvm::Value *VBTableOffset, llvm::Value *VBPtrOffset) {
3172 CGBuilderTy &Builder = CGF.Builder;
3173 Base = Base.withElementType(CGM.Int8Ty);
3174 llvm::BasicBlock *OriginalBB = nullptr;
3175 llvm::BasicBlock *SkipAdjustBB = nullptr;
3176 llvm::BasicBlock *VBaseAdjustBB = nullptr;
3178 // In the unspecified inheritance model, there might not be a vbtable at all,
3179 // in which case we need to skip the virtual base lookup. If there is a
3180 // vbtable, the first entry is a no-op entry that gives back the original
3181 // base, so look for a virtual base adjustment offset of zero.
3182 if (VBPtrOffset) {
3183 OriginalBB = Builder.GetInsertBlock();
3184 VBaseAdjustBB = CGF.createBasicBlock("memptr.vadjust");
3185 SkipAdjustBB = CGF.createBasicBlock("memptr.skip_vadjust");
3186 llvm::Value *IsVirtual =
3187 Builder.CreateICmpNE(VBTableOffset, getZeroInt(),
3188 "memptr.is_vbase");
3189 Builder.CreateCondBr(IsVirtual, VBaseAdjustBB, SkipAdjustBB);
3190 CGF.EmitBlock(VBaseAdjustBB);
3193 // If we weren't given a dynamic vbptr offset, RD should be complete and we'll
3194 // know the vbptr offset.
3195 if (!VBPtrOffset) {
3196 CharUnits offs = CharUnits::Zero();
3197 if (!RD->hasDefinition()) {
3198 DiagnosticsEngine &Diags = CGF.CGM.getDiags();
3199 unsigned DiagID = Diags.getCustomDiagID(
3200 DiagnosticsEngine::Error,
3201 "member pointer representation requires a "
3202 "complete class type for %0 to perform this expression");
3203 Diags.Report(E->getExprLoc(), DiagID) << RD << E->getSourceRange();
3204 } else if (RD->getNumVBases())
3205 offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
3206 VBPtrOffset = llvm::ConstantInt::get(CGM.IntTy, offs.getQuantity());
3208 llvm::Value *VBPtr = nullptr;
3209 llvm::Value *VBaseOffs =
3210 GetVBaseOffsetFromVBPtr(CGF, Base, VBPtrOffset, VBTableOffset, &VBPtr);
3211 llvm::Value *AdjustedBase =
3212 Builder.CreateInBoundsGEP(CGM.Int8Ty, VBPtr, VBaseOffs);
3214 // Merge control flow with the case where we didn't have to adjust.
3215 if (VBaseAdjustBB) {
3216 Builder.CreateBr(SkipAdjustBB);
3217 CGF.EmitBlock(SkipAdjustBB);
3218 llvm::PHINode *Phi = Builder.CreatePHI(CGM.Int8PtrTy, 2, "memptr.base");
3219 Phi->addIncoming(Base.emitRawPointer(CGF), OriginalBB);
3220 Phi->addIncoming(AdjustedBase, VBaseAdjustBB);
3221 return Phi;
3223 return AdjustedBase;
3226 llvm::Value *MicrosoftCXXABI::EmitMemberDataPointerAddress(
3227 CodeGenFunction &CGF, const Expr *E, Address Base, llvm::Value *MemPtr,
3228 const MemberPointerType *MPT) {
3229 assert(MPT->isMemberDataPointer());
3230 CGBuilderTy &Builder = CGF.Builder;
3231 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
3232 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
3234 // Extract the fields we need, regardless of model. We'll apply them if we
3235 // have them.
3236 llvm::Value *FieldOffset = MemPtr;
3237 llvm::Value *VirtualBaseAdjustmentOffset = nullptr;
3238 llvm::Value *VBPtrOffset = nullptr;
3239 if (MemPtr->getType()->isStructTy()) {
3240 // We need to extract values.
3241 unsigned I = 0;
3242 FieldOffset = Builder.CreateExtractValue(MemPtr, I++);
3243 if (inheritanceModelHasVBPtrOffsetField(Inheritance))
3244 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
3245 if (inheritanceModelHasVBTableOffsetField(Inheritance))
3246 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
3249 llvm::Value *Addr;
3250 if (VirtualBaseAdjustmentOffset) {
3251 Addr = AdjustVirtualBase(CGF, E, RD, Base, VirtualBaseAdjustmentOffset,
3252 VBPtrOffset);
3253 } else {
3254 Addr = Base.emitRawPointer(CGF);
3257 // Apply the offset, which we assume is non-null.
3258 return Builder.CreateInBoundsGEP(CGF.Int8Ty, Addr, FieldOffset,
3259 "memptr.offset");
3262 llvm::Value *
3263 MicrosoftCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
3264 const CastExpr *E,
3265 llvm::Value *Src) {
3266 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
3267 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
3268 E->getCastKind() == CK_ReinterpretMemberPointer);
3270 // Use constant emission if we can.
3271 if (isa<llvm::Constant>(Src))
3272 return EmitMemberPointerConversion(E, cast<llvm::Constant>(Src));
3274 // We may be adding or dropping fields from the member pointer, so we need
3275 // both types and the inheritance models of both records.
3276 const MemberPointerType *SrcTy =
3277 E->getSubExpr()->getType()->castAs<MemberPointerType>();
3278 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
3279 bool IsFunc = SrcTy->isMemberFunctionPointer();
3281 // If the classes use the same null representation, reinterpret_cast is a nop.
3282 bool IsReinterpret = E->getCastKind() == CK_ReinterpretMemberPointer;
3283 if (IsReinterpret && IsFunc)
3284 return Src;
3286 CXXRecordDecl *SrcRD = SrcTy->getMostRecentCXXRecordDecl();
3287 CXXRecordDecl *DstRD = DstTy->getMostRecentCXXRecordDecl();
3288 if (IsReinterpret &&
3289 SrcRD->nullFieldOffsetIsZero() == DstRD->nullFieldOffsetIsZero())
3290 return Src;
3292 CGBuilderTy &Builder = CGF.Builder;
3294 // Branch past the conversion if Src is null.
3295 llvm::Value *IsNotNull = EmitMemberPointerIsNotNull(CGF, Src, SrcTy);
3296 llvm::Constant *DstNull = EmitNullMemberPointer(DstTy);
3298 // C++ 5.2.10p9: The null member pointer value is converted to the null member
3299 // pointer value of the destination type.
3300 if (IsReinterpret) {
3301 // For reinterpret casts, sema ensures that src and dst are both functions
3302 // or data and have the same size, which means the LLVM types should match.
3303 assert(Src->getType() == DstNull->getType());
3304 return Builder.CreateSelect(IsNotNull, Src, DstNull);
3307 llvm::BasicBlock *OriginalBB = Builder.GetInsertBlock();
3308 llvm::BasicBlock *ConvertBB = CGF.createBasicBlock("memptr.convert");
3309 llvm::BasicBlock *ContinueBB = CGF.createBasicBlock("memptr.converted");
3310 Builder.CreateCondBr(IsNotNull, ConvertBB, ContinueBB);
3311 CGF.EmitBlock(ConvertBB);
3313 llvm::Value *Dst = EmitNonNullMemberPointerConversion(
3314 SrcTy, DstTy, E->getCastKind(), E->path_begin(), E->path_end(), Src,
3315 Builder);
3317 Builder.CreateBr(ContinueBB);
3319 // In the continuation, choose between DstNull and Dst.
3320 CGF.EmitBlock(ContinueBB);
3321 llvm::PHINode *Phi = Builder.CreatePHI(DstNull->getType(), 2, "memptr.converted");
3322 Phi->addIncoming(DstNull, OriginalBB);
3323 Phi->addIncoming(Dst, ConvertBB);
3324 return Phi;
3327 llvm::Value *MicrosoftCXXABI::EmitNonNullMemberPointerConversion(
3328 const MemberPointerType *SrcTy, const MemberPointerType *DstTy, CastKind CK,
3329 CastExpr::path_const_iterator PathBegin,
3330 CastExpr::path_const_iterator PathEnd, llvm::Value *Src,
3331 CGBuilderTy &Builder) {
3332 const CXXRecordDecl *SrcRD = SrcTy->getMostRecentCXXRecordDecl();
3333 const CXXRecordDecl *DstRD = DstTy->getMostRecentCXXRecordDecl();
3334 MSInheritanceModel SrcInheritance = SrcRD->getMSInheritanceModel();
3335 MSInheritanceModel DstInheritance = DstRD->getMSInheritanceModel();
3336 bool IsFunc = SrcTy->isMemberFunctionPointer();
3337 bool IsConstant = isa<llvm::Constant>(Src);
3339 // Decompose src.
3340 llvm::Value *FirstField = Src;
3341 llvm::Value *NonVirtualBaseAdjustment = getZeroInt();
3342 llvm::Value *VirtualBaseAdjustmentOffset = getZeroInt();
3343 llvm::Value *VBPtrOffset = getZeroInt();
3344 if (!inheritanceModelHasOnlyOneField(IsFunc, SrcInheritance)) {
3345 // We need to extract values.
3346 unsigned I = 0;
3347 FirstField = Builder.CreateExtractValue(Src, I++);
3348 if (inheritanceModelHasNVOffsetField(IsFunc, SrcInheritance))
3349 NonVirtualBaseAdjustment = Builder.CreateExtractValue(Src, I++);
3350 if (inheritanceModelHasVBPtrOffsetField(SrcInheritance))
3351 VBPtrOffset = Builder.CreateExtractValue(Src, I++);
3352 if (inheritanceModelHasVBTableOffsetField(SrcInheritance))
3353 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(Src, I++);
3356 bool IsDerivedToBase = (CK == CK_DerivedToBaseMemberPointer);
3357 const MemberPointerType *DerivedTy = IsDerivedToBase ? SrcTy : DstTy;
3358 const CXXRecordDecl *DerivedClass = DerivedTy->getMostRecentCXXRecordDecl();
3360 // For data pointers, we adjust the field offset directly. For functions, we
3361 // have a separate field.
3362 llvm::Value *&NVAdjustField = IsFunc ? NonVirtualBaseAdjustment : FirstField;
3364 // The virtual inheritance model has a quirk: the virtual base table is always
3365 // referenced when dereferencing a member pointer even if the member pointer
3366 // is non-virtual. This is accounted for by adjusting the non-virtual offset
3367 // to point backwards to the top of the MDC from the first VBase. Undo this
3368 // adjustment to normalize the member pointer.
3369 llvm::Value *SrcVBIndexEqZero =
3370 Builder.CreateICmpEQ(VirtualBaseAdjustmentOffset, getZeroInt());
3371 if (SrcInheritance == MSInheritanceModel::Virtual) {
3372 if (int64_t SrcOffsetToFirstVBase =
3373 getContext().getOffsetOfBaseWithVBPtr(SrcRD).getQuantity()) {
3374 llvm::Value *UndoSrcAdjustment = Builder.CreateSelect(
3375 SrcVBIndexEqZero,
3376 llvm::ConstantInt::get(CGM.IntTy, SrcOffsetToFirstVBase),
3377 getZeroInt());
3378 NVAdjustField = Builder.CreateNSWAdd(NVAdjustField, UndoSrcAdjustment);
3382 // A non-zero vbindex implies that we are dealing with a source member in a
3383 // floating virtual base in addition to some non-virtual offset. If the
3384 // vbindex is zero, we are dealing with a source that exists in a non-virtual,
3385 // fixed, base. The difference between these two cases is that the vbindex +
3386 // nvoffset *always* point to the member regardless of what context they are
3387 // evaluated in so long as the vbindex is adjusted. A member inside a fixed
3388 // base requires explicit nv adjustment.
3389 llvm::Constant *BaseClassOffset = llvm::ConstantInt::get(
3390 CGM.IntTy,
3391 CGM.computeNonVirtualBaseClassOffset(DerivedClass, PathBegin, PathEnd)
3392 .getQuantity());
3394 llvm::Value *NVDisp;
3395 if (IsDerivedToBase)
3396 NVDisp = Builder.CreateNSWSub(NVAdjustField, BaseClassOffset, "adj");
3397 else
3398 NVDisp = Builder.CreateNSWAdd(NVAdjustField, BaseClassOffset, "adj");
3400 NVAdjustField = Builder.CreateSelect(SrcVBIndexEqZero, NVDisp, getZeroInt());
3402 // Update the vbindex to an appropriate value in the destination because
3403 // SrcRD's vbtable might not be a strict prefix of the one in DstRD.
3404 llvm::Value *DstVBIndexEqZero = SrcVBIndexEqZero;
3405 if (inheritanceModelHasVBTableOffsetField(DstInheritance) &&
3406 inheritanceModelHasVBTableOffsetField(SrcInheritance)) {
3407 if (llvm::GlobalVariable *VDispMap =
3408 getAddrOfVirtualDisplacementMap(SrcRD, DstRD)) {
3409 llvm::Value *VBIndex = Builder.CreateExactUDiv(
3410 VirtualBaseAdjustmentOffset, llvm::ConstantInt::get(CGM.IntTy, 4));
3411 if (IsConstant) {
3412 llvm::Constant *Mapping = VDispMap->getInitializer();
3413 VirtualBaseAdjustmentOffset =
3414 Mapping->getAggregateElement(cast<llvm::Constant>(VBIndex));
3415 } else {
3416 llvm::Value *Idxs[] = {getZeroInt(), VBIndex};
3417 VirtualBaseAdjustmentOffset = Builder.CreateAlignedLoad(
3418 CGM.IntTy, Builder.CreateInBoundsGEP(VDispMap->getValueType(),
3419 VDispMap, Idxs),
3420 CharUnits::fromQuantity(4));
3423 DstVBIndexEqZero =
3424 Builder.CreateICmpEQ(VirtualBaseAdjustmentOffset, getZeroInt());
3428 // Set the VBPtrOffset to zero if the vbindex is zero. Otherwise, initialize
3429 // it to the offset of the vbptr.
3430 if (inheritanceModelHasVBPtrOffsetField(DstInheritance)) {
3431 llvm::Value *DstVBPtrOffset = llvm::ConstantInt::get(
3432 CGM.IntTy,
3433 getContext().getASTRecordLayout(DstRD).getVBPtrOffset().getQuantity());
3434 VBPtrOffset =
3435 Builder.CreateSelect(DstVBIndexEqZero, getZeroInt(), DstVBPtrOffset);
3438 // Likewise, apply a similar adjustment so that dereferencing the member
3439 // pointer correctly accounts for the distance between the start of the first
3440 // virtual base and the top of the MDC.
3441 if (DstInheritance == MSInheritanceModel::Virtual) {
3442 if (int64_t DstOffsetToFirstVBase =
3443 getContext().getOffsetOfBaseWithVBPtr(DstRD).getQuantity()) {
3444 llvm::Value *DoDstAdjustment = Builder.CreateSelect(
3445 DstVBIndexEqZero,
3446 llvm::ConstantInt::get(CGM.IntTy, DstOffsetToFirstVBase),
3447 getZeroInt());
3448 NVAdjustField = Builder.CreateNSWSub(NVAdjustField, DoDstAdjustment);
3452 // Recompose dst from the null struct and the adjusted fields from src.
3453 llvm::Value *Dst;
3454 if (inheritanceModelHasOnlyOneField(IsFunc, DstInheritance)) {
3455 Dst = FirstField;
3456 } else {
3457 Dst = llvm::UndefValue::get(ConvertMemberPointerType(DstTy));
3458 unsigned Idx = 0;
3459 Dst = Builder.CreateInsertValue(Dst, FirstField, Idx++);
3460 if (inheritanceModelHasNVOffsetField(IsFunc, DstInheritance))
3461 Dst = Builder.CreateInsertValue(Dst, NonVirtualBaseAdjustment, Idx++);
3462 if (inheritanceModelHasVBPtrOffsetField(DstInheritance))
3463 Dst = Builder.CreateInsertValue(Dst, VBPtrOffset, Idx++);
3464 if (inheritanceModelHasVBTableOffsetField(DstInheritance))
3465 Dst = Builder.CreateInsertValue(Dst, VirtualBaseAdjustmentOffset, Idx++);
3467 return Dst;
3470 llvm::Constant *
3471 MicrosoftCXXABI::EmitMemberPointerConversion(const CastExpr *E,
3472 llvm::Constant *Src) {
3473 const MemberPointerType *SrcTy =
3474 E->getSubExpr()->getType()->castAs<MemberPointerType>();
3475 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
3477 CastKind CK = E->getCastKind();
3479 return EmitMemberPointerConversion(SrcTy, DstTy, CK, E->path_begin(),
3480 E->path_end(), Src);
3483 llvm::Constant *MicrosoftCXXABI::EmitMemberPointerConversion(
3484 const MemberPointerType *SrcTy, const MemberPointerType *DstTy, CastKind CK,
3485 CastExpr::path_const_iterator PathBegin,
3486 CastExpr::path_const_iterator PathEnd, llvm::Constant *Src) {
3487 assert(CK == CK_DerivedToBaseMemberPointer ||
3488 CK == CK_BaseToDerivedMemberPointer ||
3489 CK == CK_ReinterpretMemberPointer);
3490 // If src is null, emit a new null for dst. We can't return src because dst
3491 // might have a new representation.
3492 if (MemberPointerConstantIsNull(SrcTy, Src))
3493 return EmitNullMemberPointer(DstTy);
3495 // We don't need to do anything for reinterpret_casts of non-null member
3496 // pointers. We should only get here when the two type representations have
3497 // the same size.
3498 if (CK == CK_ReinterpretMemberPointer)
3499 return Src;
3501 CGBuilderTy Builder(CGM, CGM.getLLVMContext());
3502 auto *Dst = cast<llvm::Constant>(EmitNonNullMemberPointerConversion(
3503 SrcTy, DstTy, CK, PathBegin, PathEnd, Src, Builder));
3505 return Dst;
3508 CGCallee MicrosoftCXXABI::EmitLoadOfMemberFunctionPointer(
3509 CodeGenFunction &CGF, const Expr *E, Address This,
3510 llvm::Value *&ThisPtrForCall, llvm::Value *MemPtr,
3511 const MemberPointerType *MPT) {
3512 assert(MPT->isMemberFunctionPointer());
3513 const FunctionProtoType *FPT =
3514 MPT->getPointeeType()->castAs<FunctionProtoType>();
3515 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
3516 CGBuilderTy &Builder = CGF.Builder;
3518 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
3520 // Extract the fields we need, regardless of model. We'll apply them if we
3521 // have them.
3522 llvm::Value *FunctionPointer = MemPtr;
3523 llvm::Value *NonVirtualBaseAdjustment = nullptr;
3524 llvm::Value *VirtualBaseAdjustmentOffset = nullptr;
3525 llvm::Value *VBPtrOffset = nullptr;
3526 if (MemPtr->getType()->isStructTy()) {
3527 // We need to extract values.
3528 unsigned I = 0;
3529 FunctionPointer = Builder.CreateExtractValue(MemPtr, I++);
3530 if (inheritanceModelHasNVOffsetField(MPT, Inheritance))
3531 NonVirtualBaseAdjustment = Builder.CreateExtractValue(MemPtr, I++);
3532 if (inheritanceModelHasVBPtrOffsetField(Inheritance))
3533 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
3534 if (inheritanceModelHasVBTableOffsetField(Inheritance))
3535 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
3538 if (VirtualBaseAdjustmentOffset) {
3539 ThisPtrForCall = AdjustVirtualBase(CGF, E, RD, This,
3540 VirtualBaseAdjustmentOffset, VBPtrOffset);
3541 } else {
3542 ThisPtrForCall = This.emitRawPointer(CGF);
3545 if (NonVirtualBaseAdjustment)
3546 ThisPtrForCall = Builder.CreateInBoundsGEP(CGF.Int8Ty, ThisPtrForCall,
3547 NonVirtualBaseAdjustment);
3549 CGCallee Callee(FPT, FunctionPointer);
3550 return Callee;
3553 CGCXXABI *clang::CodeGen::CreateMicrosoftCXXABI(CodeGenModule &CGM) {
3554 return new MicrosoftCXXABI(CGM);
3557 // MS RTTI Overview:
3558 // The run time type information emitted by cl.exe contains 5 distinct types of
3559 // structures. Many of them reference each other.
3561 // TypeInfo: Static classes that are returned by typeid.
3563 // CompleteObjectLocator: Referenced by vftables. They contain information
3564 // required for dynamic casting, including OffsetFromTop. They also contain
3565 // a reference to the TypeInfo for the type and a reference to the
3566 // CompleteHierarchyDescriptor for the type.
3568 // ClassHierarchyDescriptor: Contains information about a class hierarchy.
3569 // Used during dynamic_cast to walk a class hierarchy. References a base
3570 // class array and the size of said array.
3572 // BaseClassArray: Contains a list of classes in a hierarchy. BaseClassArray is
3573 // somewhat of a misnomer because the most derived class is also in the list
3574 // as well as multiple copies of virtual bases (if they occur multiple times
3575 // in the hierarchy.) The BaseClassArray contains one BaseClassDescriptor for
3576 // every path in the hierarchy, in pre-order depth first order. Note, we do
3577 // not declare a specific llvm type for BaseClassArray, it's merely an array
3578 // of BaseClassDescriptor pointers.
3580 // BaseClassDescriptor: Contains information about a class in a class hierarchy.
3581 // BaseClassDescriptor is also somewhat of a misnomer for the same reason that
3582 // BaseClassArray is. It contains information about a class within a
3583 // hierarchy such as: is this base is ambiguous and what is its offset in the
3584 // vbtable. The names of the BaseClassDescriptors have all of their fields
3585 // mangled into them so they can be aggressively deduplicated by the linker.
3587 static llvm::GlobalVariable *getTypeInfoVTable(CodeGenModule &CGM) {
3588 StringRef MangledName("??_7type_info@@6B@");
3589 if (auto VTable = CGM.getModule().getNamedGlobal(MangledName))
3590 return VTable;
3591 return new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
3592 /*isConstant=*/true,
3593 llvm::GlobalVariable::ExternalLinkage,
3594 /*Initializer=*/nullptr, MangledName);
3597 namespace {
3599 /// A Helper struct that stores information about a class in a class
3600 /// hierarchy. The information stored in these structs struct is used during
3601 /// the generation of ClassHierarchyDescriptors and BaseClassDescriptors.
3602 // During RTTI creation, MSRTTIClasses are stored in a contiguous array with
3603 // implicit depth first pre-order tree connectivity. getFirstChild and
3604 // getNextSibling allow us to walk the tree efficiently.
3605 struct MSRTTIClass {
3606 enum {
3607 IsPrivateOnPath = 1 | 8,
3608 IsAmbiguous = 2,
3609 IsPrivate = 4,
3610 IsVirtual = 16,
3611 HasHierarchyDescriptor = 64
3613 MSRTTIClass(const CXXRecordDecl *RD) : RD(RD) {}
3614 uint32_t initialize(const MSRTTIClass *Parent,
3615 const CXXBaseSpecifier *Specifier);
3617 MSRTTIClass *getFirstChild() { return this + 1; }
3618 static MSRTTIClass *getNextChild(MSRTTIClass *Child) {
3619 return Child + 1 + Child->NumBases;
3622 const CXXRecordDecl *RD, *VirtualRoot;
3623 uint32_t Flags, NumBases, OffsetInVBase;
3626 /// Recursively initialize the base class array.
3627 uint32_t MSRTTIClass::initialize(const MSRTTIClass *Parent,
3628 const CXXBaseSpecifier *Specifier) {
3629 Flags = HasHierarchyDescriptor;
3630 if (!Parent) {
3631 VirtualRoot = nullptr;
3632 OffsetInVBase = 0;
3633 } else {
3634 if (Specifier->getAccessSpecifier() != AS_public)
3635 Flags |= IsPrivate | IsPrivateOnPath;
3636 if (Specifier->isVirtual()) {
3637 Flags |= IsVirtual;
3638 VirtualRoot = RD;
3639 OffsetInVBase = 0;
3640 } else {
3641 if (Parent->Flags & IsPrivateOnPath)
3642 Flags |= IsPrivateOnPath;
3643 VirtualRoot = Parent->VirtualRoot;
3644 OffsetInVBase = Parent->OffsetInVBase + RD->getASTContext()
3645 .getASTRecordLayout(Parent->RD).getBaseClassOffset(RD).getQuantity();
3648 NumBases = 0;
3649 MSRTTIClass *Child = getFirstChild();
3650 for (const CXXBaseSpecifier &Base : RD->bases()) {
3651 NumBases += Child->initialize(this, &Base) + 1;
3652 Child = getNextChild(Child);
3654 return NumBases;
3657 static llvm::GlobalValue::LinkageTypes getLinkageForRTTI(QualType Ty) {
3658 switch (Ty->getLinkage()) {
3659 case Linkage::Invalid:
3660 llvm_unreachable("Linkage hasn't been computed!");
3662 case Linkage::None:
3663 case Linkage::Internal:
3664 case Linkage::UniqueExternal:
3665 return llvm::GlobalValue::InternalLinkage;
3667 case Linkage::VisibleNone:
3668 case Linkage::Module:
3669 case Linkage::External:
3670 return llvm::GlobalValue::LinkOnceODRLinkage;
3672 llvm_unreachable("Invalid linkage!");
3675 /// An ephemeral helper class for building MS RTTI types. It caches some
3676 /// calls to the module and information about the most derived class in a
3677 /// hierarchy.
3678 struct MSRTTIBuilder {
3679 enum {
3680 HasBranchingHierarchy = 1,
3681 HasVirtualBranchingHierarchy = 2,
3682 HasAmbiguousBases = 4
3685 MSRTTIBuilder(MicrosoftCXXABI &ABI, const CXXRecordDecl *RD)
3686 : CGM(ABI.CGM), Context(CGM.getContext()),
3687 VMContext(CGM.getLLVMContext()), Module(CGM.getModule()), RD(RD),
3688 Linkage(getLinkageForRTTI(CGM.getContext().getTagDeclType(RD))),
3689 ABI(ABI) {}
3691 llvm::GlobalVariable *getBaseClassDescriptor(const MSRTTIClass &Classes);
3692 llvm::GlobalVariable *
3693 getBaseClassArray(SmallVectorImpl<MSRTTIClass> &Classes);
3694 llvm::GlobalVariable *getClassHierarchyDescriptor();
3695 llvm::GlobalVariable *getCompleteObjectLocator(const VPtrInfo &Info);
3697 CodeGenModule &CGM;
3698 ASTContext &Context;
3699 llvm::LLVMContext &VMContext;
3700 llvm::Module &Module;
3701 const CXXRecordDecl *RD;
3702 llvm::GlobalVariable::LinkageTypes Linkage;
3703 MicrosoftCXXABI &ABI;
3706 } // namespace
3708 /// Recursively serializes a class hierarchy in pre-order depth first
3709 /// order.
3710 static void serializeClassHierarchy(SmallVectorImpl<MSRTTIClass> &Classes,
3711 const CXXRecordDecl *RD) {
3712 Classes.push_back(MSRTTIClass(RD));
3713 for (const CXXBaseSpecifier &Base : RD->bases())
3714 serializeClassHierarchy(Classes, Base.getType()->getAsCXXRecordDecl());
3717 /// Find ambiguity among base classes.
3718 static void
3719 detectAmbiguousBases(SmallVectorImpl<MSRTTIClass> &Classes) {
3720 llvm::SmallPtrSet<const CXXRecordDecl *, 8> VirtualBases;
3721 llvm::SmallPtrSet<const CXXRecordDecl *, 8> UniqueBases;
3722 llvm::SmallPtrSet<const CXXRecordDecl *, 8> AmbiguousBases;
3723 for (MSRTTIClass *Class = &Classes.front(); Class <= &Classes.back();) {
3724 if ((Class->Flags & MSRTTIClass::IsVirtual) &&
3725 !VirtualBases.insert(Class->RD).second) {
3726 Class = MSRTTIClass::getNextChild(Class);
3727 continue;
3729 if (!UniqueBases.insert(Class->RD).second)
3730 AmbiguousBases.insert(Class->RD);
3731 Class++;
3733 if (AmbiguousBases.empty())
3734 return;
3735 for (MSRTTIClass &Class : Classes)
3736 if (AmbiguousBases.count(Class.RD))
3737 Class.Flags |= MSRTTIClass::IsAmbiguous;
3740 llvm::GlobalVariable *MSRTTIBuilder::getClassHierarchyDescriptor() {
3741 SmallString<256> MangledName;
3743 llvm::raw_svector_ostream Out(MangledName);
3744 ABI.getMangleContext().mangleCXXRTTIClassHierarchyDescriptor(RD, Out);
3747 // Check to see if we've already declared this ClassHierarchyDescriptor.
3748 if (auto CHD = Module.getNamedGlobal(MangledName))
3749 return CHD;
3751 // Serialize the class hierarchy and initialize the CHD Fields.
3752 SmallVector<MSRTTIClass, 8> Classes;
3753 serializeClassHierarchy(Classes, RD);
3754 Classes.front().initialize(/*Parent=*/nullptr, /*Specifier=*/nullptr);
3755 detectAmbiguousBases(Classes);
3756 int Flags = 0;
3757 for (const MSRTTIClass &Class : Classes) {
3758 if (Class.RD->getNumBases() > 1)
3759 Flags |= HasBranchingHierarchy;
3760 // Note: cl.exe does not calculate "HasAmbiguousBases" correctly. We
3761 // believe the field isn't actually used.
3762 if (Class.Flags & MSRTTIClass::IsAmbiguous)
3763 Flags |= HasAmbiguousBases;
3765 if ((Flags & HasBranchingHierarchy) && RD->getNumVBases() != 0)
3766 Flags |= HasVirtualBranchingHierarchy;
3767 // These gep indices are used to get the address of the first element of the
3768 // base class array.
3769 llvm::Value *GEPIndices[] = {llvm::ConstantInt::get(CGM.IntTy, 0),
3770 llvm::ConstantInt::get(CGM.IntTy, 0)};
3772 // Forward-declare the class hierarchy descriptor
3773 auto Type = ABI.getClassHierarchyDescriptorType();
3774 auto CHD = new llvm::GlobalVariable(Module, Type, /*isConstant=*/true, Linkage,
3775 /*Initializer=*/nullptr,
3776 MangledName);
3777 if (CHD->isWeakForLinker())
3778 CHD->setComdat(CGM.getModule().getOrInsertComdat(CHD->getName()));
3780 auto *Bases = getBaseClassArray(Classes);
3782 // Initialize the base class ClassHierarchyDescriptor.
3783 llvm::Constant *Fields[] = {
3784 llvm::ConstantInt::get(CGM.IntTy, 0), // reserved by the runtime
3785 llvm::ConstantInt::get(CGM.IntTy, Flags),
3786 llvm::ConstantInt::get(CGM.IntTy, Classes.size()),
3787 ABI.getImageRelativeConstant(llvm::ConstantExpr::getInBoundsGetElementPtr(
3788 Bases->getValueType(), Bases,
3789 llvm::ArrayRef<llvm::Value *>(GEPIndices))),
3791 CHD->setInitializer(llvm::ConstantStruct::get(Type, Fields));
3792 return CHD;
3795 llvm::GlobalVariable *
3796 MSRTTIBuilder::getBaseClassArray(SmallVectorImpl<MSRTTIClass> &Classes) {
3797 SmallString<256> MangledName;
3799 llvm::raw_svector_ostream Out(MangledName);
3800 ABI.getMangleContext().mangleCXXRTTIBaseClassArray(RD, Out);
3803 // Forward-declare the base class array.
3804 // cl.exe pads the base class array with 1 (in 32 bit mode) or 4 (in 64 bit
3805 // mode) bytes of padding. We provide a pointer sized amount of padding by
3806 // adding +1 to Classes.size(). The sections have pointer alignment and are
3807 // marked pick-any so it shouldn't matter.
3808 llvm::Type *PtrType = ABI.getImageRelativeType(CGM.UnqualPtrTy);
3809 auto *ArrType = llvm::ArrayType::get(PtrType, Classes.size() + 1);
3810 auto *BCA =
3811 new llvm::GlobalVariable(Module, ArrType,
3812 /*isConstant=*/true, Linkage,
3813 /*Initializer=*/nullptr, MangledName);
3814 if (BCA->isWeakForLinker())
3815 BCA->setComdat(CGM.getModule().getOrInsertComdat(BCA->getName()));
3817 // Initialize the BaseClassArray.
3818 SmallVector<llvm::Constant *, 8> BaseClassArrayData;
3819 for (MSRTTIClass &Class : Classes)
3820 BaseClassArrayData.push_back(
3821 ABI.getImageRelativeConstant(getBaseClassDescriptor(Class)));
3822 BaseClassArrayData.push_back(llvm::Constant::getNullValue(PtrType));
3823 BCA->setInitializer(llvm::ConstantArray::get(ArrType, BaseClassArrayData));
3824 return BCA;
3827 llvm::GlobalVariable *
3828 MSRTTIBuilder::getBaseClassDescriptor(const MSRTTIClass &Class) {
3829 // Compute the fields for the BaseClassDescriptor. They are computed up front
3830 // because they are mangled into the name of the object.
3831 uint32_t OffsetInVBTable = 0;
3832 int32_t VBPtrOffset = -1;
3833 if (Class.VirtualRoot) {
3834 auto &VTableContext = CGM.getMicrosoftVTableContext();
3835 OffsetInVBTable = VTableContext.getVBTableIndex(RD, Class.VirtualRoot) * 4;
3836 VBPtrOffset = Context.getASTRecordLayout(RD).getVBPtrOffset().getQuantity();
3839 SmallString<256> MangledName;
3841 llvm::raw_svector_ostream Out(MangledName);
3842 ABI.getMangleContext().mangleCXXRTTIBaseClassDescriptor(
3843 Class.RD, Class.OffsetInVBase, VBPtrOffset, OffsetInVBTable,
3844 Class.Flags, Out);
3847 // Check to see if we've already declared this object.
3848 if (auto BCD = Module.getNamedGlobal(MangledName))
3849 return BCD;
3851 // Forward-declare the base class descriptor.
3852 auto Type = ABI.getBaseClassDescriptorType();
3853 auto BCD =
3854 new llvm::GlobalVariable(Module, Type, /*isConstant=*/true, Linkage,
3855 /*Initializer=*/nullptr, MangledName);
3856 if (BCD->isWeakForLinker())
3857 BCD->setComdat(CGM.getModule().getOrInsertComdat(BCD->getName()));
3859 // Initialize the BaseClassDescriptor.
3860 llvm::Constant *Fields[] = {
3861 ABI.getImageRelativeConstant(
3862 ABI.getAddrOfRTTIDescriptor(Context.getTypeDeclType(Class.RD))),
3863 llvm::ConstantInt::get(CGM.IntTy, Class.NumBases),
3864 llvm::ConstantInt::get(CGM.IntTy, Class.OffsetInVBase),
3865 llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset),
3866 llvm::ConstantInt::get(CGM.IntTy, OffsetInVBTable),
3867 llvm::ConstantInt::get(CGM.IntTy, Class.Flags),
3868 ABI.getImageRelativeConstant(
3869 MSRTTIBuilder(ABI, Class.RD).getClassHierarchyDescriptor()),
3871 BCD->setInitializer(llvm::ConstantStruct::get(Type, Fields));
3872 return BCD;
3875 llvm::GlobalVariable *
3876 MSRTTIBuilder::getCompleteObjectLocator(const VPtrInfo &Info) {
3877 SmallString<256> MangledName;
3879 llvm::raw_svector_ostream Out(MangledName);
3880 ABI.getMangleContext().mangleCXXRTTICompleteObjectLocator(RD, Info.MangledPath, Out);
3883 // Check to see if we've already computed this complete object locator.
3884 if (auto COL = Module.getNamedGlobal(MangledName))
3885 return COL;
3887 // Compute the fields of the complete object locator.
3888 int OffsetToTop = Info.FullOffsetInMDC.getQuantity();
3889 int VFPtrOffset = 0;
3890 // The offset includes the vtordisp if one exists.
3891 if (const CXXRecordDecl *VBase = Info.getVBaseWithVPtr())
3892 if (Context.getASTRecordLayout(RD)
3893 .getVBaseOffsetsMap()
3894 .find(VBase)
3895 ->second.hasVtorDisp())
3896 VFPtrOffset = Info.NonVirtualOffset.getQuantity() + 4;
3898 // Forward-declare the complete object locator.
3899 llvm::StructType *Type = ABI.getCompleteObjectLocatorType();
3900 auto COL = new llvm::GlobalVariable(Module, Type, /*isConstant=*/true, Linkage,
3901 /*Initializer=*/nullptr, MangledName);
3903 // Initialize the CompleteObjectLocator.
3904 llvm::Constant *Fields[] = {
3905 llvm::ConstantInt::get(CGM.IntTy, ABI.isImageRelative()),
3906 llvm::ConstantInt::get(CGM.IntTy, OffsetToTop),
3907 llvm::ConstantInt::get(CGM.IntTy, VFPtrOffset),
3908 ABI.getImageRelativeConstant(
3909 CGM.GetAddrOfRTTIDescriptor(Context.getTypeDeclType(RD))),
3910 ABI.getImageRelativeConstant(getClassHierarchyDescriptor()),
3911 ABI.getImageRelativeConstant(COL),
3913 llvm::ArrayRef<llvm::Constant *> FieldsRef(Fields);
3914 if (!ABI.isImageRelative())
3915 FieldsRef = FieldsRef.drop_back();
3916 COL->setInitializer(llvm::ConstantStruct::get(Type, FieldsRef));
3917 if (COL->isWeakForLinker())
3918 COL->setComdat(CGM.getModule().getOrInsertComdat(COL->getName()));
3919 return COL;
3922 static QualType decomposeTypeForEH(ASTContext &Context, QualType T,
3923 bool &IsConst, bool &IsVolatile,
3924 bool &IsUnaligned) {
3925 T = Context.getExceptionObjectType(T);
3927 // C++14 [except.handle]p3:
3928 // A handler is a match for an exception object of type E if [...]
3929 // - the handler is of type cv T or const T& where T is a pointer type and
3930 // E is a pointer type that can be converted to T by [...]
3931 // - a qualification conversion
3932 IsConst = false;
3933 IsVolatile = false;
3934 IsUnaligned = false;
3935 QualType PointeeType = T->getPointeeType();
3936 if (!PointeeType.isNull()) {
3937 IsConst = PointeeType.isConstQualified();
3938 IsVolatile = PointeeType.isVolatileQualified();
3939 IsUnaligned = PointeeType.getQualifiers().hasUnaligned();
3942 // Member pointer types like "const int A::*" are represented by having RTTI
3943 // for "int A::*" and separately storing the const qualifier.
3944 if (const auto *MPTy = T->getAs<MemberPointerType>())
3945 T = Context.getMemberPointerType(PointeeType.getUnqualifiedType(),
3946 MPTy->getClass());
3948 // Pointer types like "const int * const *" are represented by having RTTI
3949 // for "const int **" and separately storing the const qualifier.
3950 if (T->isPointerType())
3951 T = Context.getPointerType(PointeeType.getUnqualifiedType());
3953 return T;
3956 CatchTypeInfo
3957 MicrosoftCXXABI::getAddrOfCXXCatchHandlerType(QualType Type,
3958 QualType CatchHandlerType) {
3959 // TypeDescriptors for exceptions never have qualified pointer types,
3960 // qualifiers are stored separately in order to support qualification
3961 // conversions.
3962 bool IsConst, IsVolatile, IsUnaligned;
3963 Type =
3964 decomposeTypeForEH(getContext(), Type, IsConst, IsVolatile, IsUnaligned);
3966 bool IsReference = CatchHandlerType->isReferenceType();
3968 uint32_t Flags = 0;
3969 if (IsConst)
3970 Flags |= 1;
3971 if (IsVolatile)
3972 Flags |= 2;
3973 if (IsUnaligned)
3974 Flags |= 4;
3975 if (IsReference)
3976 Flags |= 8;
3978 return CatchTypeInfo{getAddrOfRTTIDescriptor(Type)->stripPointerCasts(),
3979 Flags};
3982 /// Gets a TypeDescriptor. Returns a llvm::Constant * rather than a
3983 /// llvm::GlobalVariable * because different type descriptors have different
3984 /// types, and need to be abstracted. They are abstracting by casting the
3985 /// address to an Int8PtrTy.
3986 llvm::Constant *MicrosoftCXXABI::getAddrOfRTTIDescriptor(QualType Type) {
3987 SmallString<256> MangledName;
3989 llvm::raw_svector_ostream Out(MangledName);
3990 getMangleContext().mangleCXXRTTI(Type, Out);
3993 // Check to see if we've already declared this TypeDescriptor.
3994 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
3995 return GV;
3997 // Note for the future: If we would ever like to do deferred emission of
3998 // RTTI, check if emitting vtables opportunistically need any adjustment.
4000 // Compute the fields for the TypeDescriptor.
4001 SmallString<256> TypeInfoString;
4003 llvm::raw_svector_ostream Out(TypeInfoString);
4004 getMangleContext().mangleCXXRTTIName(Type, Out);
4007 // Declare and initialize the TypeDescriptor.
4008 llvm::Constant *Fields[] = {
4009 getTypeInfoVTable(CGM), // VFPtr
4010 llvm::ConstantPointerNull::get(CGM.Int8PtrTy), // Runtime data
4011 llvm::ConstantDataArray::getString(CGM.getLLVMContext(), TypeInfoString)};
4012 llvm::StructType *TypeDescriptorType =
4013 getTypeDescriptorType(TypeInfoString);
4014 auto *Var = new llvm::GlobalVariable(
4015 CGM.getModule(), TypeDescriptorType, /*isConstant=*/false,
4016 getLinkageForRTTI(Type),
4017 llvm::ConstantStruct::get(TypeDescriptorType, Fields),
4018 MangledName);
4019 if (Var->isWeakForLinker())
4020 Var->setComdat(CGM.getModule().getOrInsertComdat(Var->getName()));
4021 return Var;
4024 /// Gets or a creates a Microsoft CompleteObjectLocator.
4025 llvm::GlobalVariable *
4026 MicrosoftCXXABI::getMSCompleteObjectLocator(const CXXRecordDecl *RD,
4027 const VPtrInfo &Info) {
4028 return MSRTTIBuilder(*this, RD).getCompleteObjectLocator(Info);
4031 void MicrosoftCXXABI::emitCXXStructor(GlobalDecl GD) {
4032 if (auto *ctor = dyn_cast<CXXConstructorDecl>(GD.getDecl())) {
4033 // There are no constructor variants, always emit the complete destructor.
4034 llvm::Function *Fn =
4035 CGM.codegenCXXStructor(GD.getWithCtorType(Ctor_Complete));
4036 CGM.maybeSetTrivialComdat(*ctor, *Fn);
4037 return;
4040 auto *dtor = cast<CXXDestructorDecl>(GD.getDecl());
4042 // Emit the base destructor if the base and complete (vbase) destructors are
4043 // equivalent. This effectively implements -mconstructor-aliases as part of
4044 // the ABI.
4045 if (GD.getDtorType() == Dtor_Complete &&
4046 dtor->getParent()->getNumVBases() == 0)
4047 GD = GD.getWithDtorType(Dtor_Base);
4049 // The base destructor is equivalent to the base destructor of its
4050 // base class if there is exactly one non-virtual base class with a
4051 // non-trivial destructor, there are no fields with a non-trivial
4052 // destructor, and the body of the destructor is trivial.
4053 if (GD.getDtorType() == Dtor_Base && !CGM.TryEmitBaseDestructorAsAlias(dtor))
4054 return;
4056 llvm::Function *Fn = CGM.codegenCXXStructor(GD);
4057 if (Fn->isWeakForLinker())
4058 Fn->setComdat(CGM.getModule().getOrInsertComdat(Fn->getName()));
4061 llvm::Function *
4062 MicrosoftCXXABI::getAddrOfCXXCtorClosure(const CXXConstructorDecl *CD,
4063 CXXCtorType CT) {
4064 assert(CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure);
4066 // Calculate the mangled name.
4067 SmallString<256> ThunkName;
4068 llvm::raw_svector_ostream Out(ThunkName);
4069 getMangleContext().mangleName(GlobalDecl(CD, CT), Out);
4071 // If the thunk has been generated previously, just return it.
4072 if (llvm::GlobalValue *GV = CGM.getModule().getNamedValue(ThunkName))
4073 return cast<llvm::Function>(GV);
4075 // Create the llvm::Function.
4076 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeMSCtorClosure(CD, CT);
4077 llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo);
4078 const CXXRecordDecl *RD = CD->getParent();
4079 QualType RecordTy = getContext().getRecordType(RD);
4080 llvm::Function *ThunkFn = llvm::Function::Create(
4081 ThunkTy, getLinkageForRTTI(RecordTy), ThunkName.str(), &CGM.getModule());
4082 ThunkFn->setCallingConv(static_cast<llvm::CallingConv::ID>(
4083 FnInfo.getEffectiveCallingConvention()));
4084 if (ThunkFn->isWeakForLinker())
4085 ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));
4086 bool IsCopy = CT == Ctor_CopyingClosure;
4088 // Start codegen.
4089 CodeGenFunction CGF(CGM);
4090 CGF.CurGD = GlobalDecl(CD, Ctor_Complete);
4092 // Build FunctionArgs.
4093 FunctionArgList FunctionArgs;
4095 // A constructor always starts with a 'this' pointer as its first argument.
4096 buildThisParam(CGF, FunctionArgs);
4098 // Following the 'this' pointer is a reference to the source object that we
4099 // are copying from.
4100 ImplicitParamDecl SrcParam(
4101 getContext(), /*DC=*/nullptr, SourceLocation(),
4102 &getContext().Idents.get("src"),
4103 getContext().getLValueReferenceType(RecordTy,
4104 /*SpelledAsLValue=*/true),
4105 ImplicitParamKind::Other);
4106 if (IsCopy)
4107 FunctionArgs.push_back(&SrcParam);
4109 // Constructors for classes which utilize virtual bases have an additional
4110 // parameter which indicates whether or not it is being delegated to by a more
4111 // derived constructor.
4112 ImplicitParamDecl IsMostDerived(getContext(), /*DC=*/nullptr,
4113 SourceLocation(),
4114 &getContext().Idents.get("is_most_derived"),
4115 getContext().IntTy, ImplicitParamKind::Other);
4116 // Only add the parameter to the list if the class has virtual bases.
4117 if (RD->getNumVBases() > 0)
4118 FunctionArgs.push_back(&IsMostDerived);
4120 // Start defining the function.
4121 auto NL = ApplyDebugLocation::CreateEmpty(CGF);
4122 CGF.StartFunction(GlobalDecl(), FnInfo.getReturnType(), ThunkFn, FnInfo,
4123 FunctionArgs, CD->getLocation(), SourceLocation());
4124 // Create a scope with an artificial location for the body of this function.
4125 auto AL = ApplyDebugLocation::CreateArtificial(CGF);
4126 setCXXABIThisValue(CGF, loadIncomingCXXThis(CGF));
4127 llvm::Value *This = getThisValue(CGF);
4129 llvm::Value *SrcVal =
4130 IsCopy ? CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&SrcParam), "src")
4131 : nullptr;
4133 CallArgList Args;
4135 // Push the this ptr.
4136 Args.add(RValue::get(This), CD->getThisType());
4138 // Push the src ptr.
4139 if (SrcVal)
4140 Args.add(RValue::get(SrcVal), SrcParam.getType());
4142 // Add the rest of the default arguments.
4143 SmallVector<const Stmt *, 4> ArgVec;
4144 ArrayRef<ParmVarDecl *> params = CD->parameters().drop_front(IsCopy ? 1 : 0);
4145 for (const ParmVarDecl *PD : params) {
4146 assert(PD->hasDefaultArg() && "ctor closure lacks default args");
4147 ArgVec.push_back(PD->getDefaultArg());
4150 CodeGenFunction::RunCleanupsScope Cleanups(CGF);
4152 const auto *FPT = CD->getType()->castAs<FunctionProtoType>();
4153 CGF.EmitCallArgs(Args, FPT, llvm::ArrayRef(ArgVec), CD, IsCopy ? 1 : 0);
4155 // Insert any ABI-specific implicit constructor arguments.
4156 AddedStructorArgCounts ExtraArgs =
4157 addImplicitConstructorArgs(CGF, CD, Ctor_Complete,
4158 /*ForVirtualBase=*/false,
4159 /*Delegating=*/false, Args);
4160 // Call the destructor with our arguments.
4161 llvm::Constant *CalleePtr =
4162 CGM.getAddrOfCXXStructor(GlobalDecl(CD, Ctor_Complete));
4163 CGCallee Callee =
4164 CGCallee::forDirect(CalleePtr, GlobalDecl(CD, Ctor_Complete));
4165 const CGFunctionInfo &CalleeInfo = CGM.getTypes().arrangeCXXConstructorCall(
4166 Args, CD, Ctor_Complete, ExtraArgs.Prefix, ExtraArgs.Suffix);
4167 CGF.EmitCall(CalleeInfo, Callee, ReturnValueSlot(), Args);
4169 Cleanups.ForceCleanup();
4171 // Emit the ret instruction, remove any temporary instructions created for the
4172 // aid of CodeGen.
4173 CGF.FinishFunction(SourceLocation());
4175 return ThunkFn;
4178 llvm::Constant *MicrosoftCXXABI::getCatchableType(QualType T,
4179 uint32_t NVOffset,
4180 int32_t VBPtrOffset,
4181 uint32_t VBIndex) {
4182 assert(!T->isReferenceType());
4184 CXXRecordDecl *RD = T->getAsCXXRecordDecl();
4185 const CXXConstructorDecl *CD =
4186 RD ? CGM.getContext().getCopyConstructorForExceptionObject(RD) : nullptr;
4187 CXXCtorType CT = Ctor_Complete;
4188 if (CD)
4189 if (!hasDefaultCXXMethodCC(getContext(), CD) || CD->getNumParams() != 1)
4190 CT = Ctor_CopyingClosure;
4192 uint32_t Size = getContext().getTypeSizeInChars(T).getQuantity();
4193 SmallString<256> MangledName;
4195 llvm::raw_svector_ostream Out(MangledName);
4196 getMangleContext().mangleCXXCatchableType(T, CD, CT, Size, NVOffset,
4197 VBPtrOffset, VBIndex, Out);
4199 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
4200 return getImageRelativeConstant(GV);
4202 // The TypeDescriptor is used by the runtime to determine if a catch handler
4203 // is appropriate for the exception object.
4204 llvm::Constant *TD = getImageRelativeConstant(getAddrOfRTTIDescriptor(T));
4206 // The runtime is responsible for calling the copy constructor if the
4207 // exception is caught by value.
4208 llvm::Constant *CopyCtor;
4209 if (CD) {
4210 if (CT == Ctor_CopyingClosure)
4211 CopyCtor = getAddrOfCXXCtorClosure(CD, Ctor_CopyingClosure);
4212 else
4213 CopyCtor = CGM.getAddrOfCXXStructor(GlobalDecl(CD, Ctor_Complete));
4214 } else {
4215 CopyCtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);
4217 CopyCtor = getImageRelativeConstant(CopyCtor);
4219 bool IsScalar = !RD;
4220 bool HasVirtualBases = false;
4221 bool IsStdBadAlloc = false; // std::bad_alloc is special for some reason.
4222 QualType PointeeType = T;
4223 if (T->isPointerType())
4224 PointeeType = T->getPointeeType();
4225 if (const CXXRecordDecl *RD = PointeeType->getAsCXXRecordDecl()) {
4226 HasVirtualBases = RD->getNumVBases() > 0;
4227 if (IdentifierInfo *II = RD->getIdentifier())
4228 IsStdBadAlloc = II->isStr("bad_alloc") && RD->isInStdNamespace();
4231 // Encode the relevant CatchableType properties into the Flags bitfield.
4232 // FIXME: Figure out how bits 2 or 8 can get set.
4233 uint32_t Flags = 0;
4234 if (IsScalar)
4235 Flags |= 1;
4236 if (HasVirtualBases)
4237 Flags |= 4;
4238 if (IsStdBadAlloc)
4239 Flags |= 16;
4241 llvm::Constant *Fields[] = {
4242 llvm::ConstantInt::get(CGM.IntTy, Flags), // Flags
4243 TD, // TypeDescriptor
4244 llvm::ConstantInt::get(CGM.IntTy, NVOffset), // NonVirtualAdjustment
4245 llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset), // OffsetToVBPtr
4246 llvm::ConstantInt::get(CGM.IntTy, VBIndex), // VBTableIndex
4247 llvm::ConstantInt::get(CGM.IntTy, Size), // Size
4248 CopyCtor // CopyCtor
4250 llvm::StructType *CTType = getCatchableTypeType();
4251 auto *GV = new llvm::GlobalVariable(
4252 CGM.getModule(), CTType, /*isConstant=*/true, getLinkageForRTTI(T),
4253 llvm::ConstantStruct::get(CTType, Fields), MangledName);
4254 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4255 GV->setSection(".xdata");
4256 if (GV->isWeakForLinker())
4257 GV->setComdat(CGM.getModule().getOrInsertComdat(GV->getName()));
4258 return getImageRelativeConstant(GV);
4261 llvm::GlobalVariable *MicrosoftCXXABI::getCatchableTypeArray(QualType T) {
4262 assert(!T->isReferenceType());
4264 // See if we've already generated a CatchableTypeArray for this type before.
4265 llvm::GlobalVariable *&CTA = CatchableTypeArrays[T];
4266 if (CTA)
4267 return CTA;
4269 // Ensure that we don't have duplicate entries in our CatchableTypeArray by
4270 // using a SmallSetVector. Duplicates may arise due to virtual bases
4271 // occurring more than once in the hierarchy.
4272 llvm::SmallSetVector<llvm::Constant *, 2> CatchableTypes;
4274 // C++14 [except.handle]p3:
4275 // A handler is a match for an exception object of type E if [...]
4276 // - the handler is of type cv T or cv T& and T is an unambiguous public
4277 // base class of E, or
4278 // - the handler is of type cv T or const T& where T is a pointer type and
4279 // E is a pointer type that can be converted to T by [...]
4280 // - a standard pointer conversion (4.10) not involving conversions to
4281 // pointers to private or protected or ambiguous classes
4282 const CXXRecordDecl *MostDerivedClass = nullptr;
4283 bool IsPointer = T->isPointerType();
4284 if (IsPointer)
4285 MostDerivedClass = T->getPointeeType()->getAsCXXRecordDecl();
4286 else
4287 MostDerivedClass = T->getAsCXXRecordDecl();
4289 // Collect all the unambiguous public bases of the MostDerivedClass.
4290 if (MostDerivedClass) {
4291 const ASTContext &Context = getContext();
4292 const ASTRecordLayout &MostDerivedLayout =
4293 Context.getASTRecordLayout(MostDerivedClass);
4294 MicrosoftVTableContext &VTableContext = CGM.getMicrosoftVTableContext();
4295 SmallVector<MSRTTIClass, 8> Classes;
4296 serializeClassHierarchy(Classes, MostDerivedClass);
4297 Classes.front().initialize(/*Parent=*/nullptr, /*Specifier=*/nullptr);
4298 detectAmbiguousBases(Classes);
4299 for (const MSRTTIClass &Class : Classes) {
4300 // Skip any ambiguous or private bases.
4301 if (Class.Flags &
4302 (MSRTTIClass::IsPrivateOnPath | MSRTTIClass::IsAmbiguous))
4303 continue;
4304 // Write down how to convert from a derived pointer to a base pointer.
4305 uint32_t OffsetInVBTable = 0;
4306 int32_t VBPtrOffset = -1;
4307 if (Class.VirtualRoot) {
4308 OffsetInVBTable =
4309 VTableContext.getVBTableIndex(MostDerivedClass, Class.VirtualRoot)*4;
4310 VBPtrOffset = MostDerivedLayout.getVBPtrOffset().getQuantity();
4313 // Turn our record back into a pointer if the exception object is a
4314 // pointer.
4315 QualType RTTITy = QualType(Class.RD->getTypeForDecl(), 0);
4316 if (IsPointer)
4317 RTTITy = Context.getPointerType(RTTITy);
4318 CatchableTypes.insert(getCatchableType(RTTITy, Class.OffsetInVBase,
4319 VBPtrOffset, OffsetInVBTable));
4323 // C++14 [except.handle]p3:
4324 // A handler is a match for an exception object of type E if
4325 // - The handler is of type cv T or cv T& and E and T are the same type
4326 // (ignoring the top-level cv-qualifiers)
4327 CatchableTypes.insert(getCatchableType(T));
4329 // C++14 [except.handle]p3:
4330 // A handler is a match for an exception object of type E if
4331 // - the handler is of type cv T or const T& where T is a pointer type and
4332 // E is a pointer type that can be converted to T by [...]
4333 // - a standard pointer conversion (4.10) not involving conversions to
4334 // pointers to private or protected or ambiguous classes
4336 // C++14 [conv.ptr]p2:
4337 // A prvalue of type "pointer to cv T," where T is an object type, can be
4338 // converted to a prvalue of type "pointer to cv void".
4339 if (IsPointer && T->getPointeeType()->isObjectType())
4340 CatchableTypes.insert(getCatchableType(getContext().VoidPtrTy));
4342 // C++14 [except.handle]p3:
4343 // A handler is a match for an exception object of type E if [...]
4344 // - the handler is of type cv T or const T& where T is a pointer or
4345 // pointer to member type and E is std::nullptr_t.
4347 // We cannot possibly list all possible pointer types here, making this
4348 // implementation incompatible with the standard. However, MSVC includes an
4349 // entry for pointer-to-void in this case. Let's do the same.
4350 if (T->isNullPtrType())
4351 CatchableTypes.insert(getCatchableType(getContext().VoidPtrTy));
4353 uint32_t NumEntries = CatchableTypes.size();
4354 llvm::Type *CTType = getImageRelativeType(CGM.UnqualPtrTy);
4355 llvm::ArrayType *AT = llvm::ArrayType::get(CTType, NumEntries);
4356 llvm::StructType *CTAType = getCatchableTypeArrayType(NumEntries);
4357 llvm::Constant *Fields[] = {
4358 llvm::ConstantInt::get(CGM.IntTy, NumEntries), // NumEntries
4359 llvm::ConstantArray::get(
4360 AT, llvm::ArrayRef(CatchableTypes.begin(),
4361 CatchableTypes.end())) // CatchableTypes
4363 SmallString<256> MangledName;
4365 llvm::raw_svector_ostream Out(MangledName);
4366 getMangleContext().mangleCXXCatchableTypeArray(T, NumEntries, Out);
4368 CTA = new llvm::GlobalVariable(
4369 CGM.getModule(), CTAType, /*isConstant=*/true, getLinkageForRTTI(T),
4370 llvm::ConstantStruct::get(CTAType, Fields), MangledName);
4371 CTA->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4372 CTA->setSection(".xdata");
4373 if (CTA->isWeakForLinker())
4374 CTA->setComdat(CGM.getModule().getOrInsertComdat(CTA->getName()));
4375 return CTA;
4378 llvm::GlobalVariable *MicrosoftCXXABI::getThrowInfo(QualType T) {
4379 bool IsConst, IsVolatile, IsUnaligned;
4380 T = decomposeTypeForEH(getContext(), T, IsConst, IsVolatile, IsUnaligned);
4382 // The CatchableTypeArray enumerates the various (CV-unqualified) types that
4383 // the exception object may be caught as.
4384 llvm::GlobalVariable *CTA = getCatchableTypeArray(T);
4385 // The first field in a CatchableTypeArray is the number of CatchableTypes.
4386 // This is used as a component of the mangled name which means that we need to
4387 // know what it is in order to see if we have previously generated the
4388 // ThrowInfo.
4389 uint32_t NumEntries =
4390 cast<llvm::ConstantInt>(CTA->getInitializer()->getAggregateElement(0U))
4391 ->getLimitedValue();
4393 SmallString<256> MangledName;
4395 llvm::raw_svector_ostream Out(MangledName);
4396 getMangleContext().mangleCXXThrowInfo(T, IsConst, IsVolatile, IsUnaligned,
4397 NumEntries, Out);
4400 // Reuse a previously generated ThrowInfo if we have generated an appropriate
4401 // one before.
4402 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
4403 return GV;
4405 // The RTTI TypeDescriptor uses an unqualified type but catch clauses must
4406 // be at least as CV qualified. Encode this requirement into the Flags
4407 // bitfield.
4408 uint32_t Flags = 0;
4409 if (IsConst)
4410 Flags |= 1;
4411 if (IsVolatile)
4412 Flags |= 2;
4413 if (IsUnaligned)
4414 Flags |= 4;
4416 // The cleanup-function (a destructor) must be called when the exception
4417 // object's lifetime ends.
4418 llvm::Constant *CleanupFn = llvm::Constant::getNullValue(CGM.Int8PtrTy);
4419 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4420 if (CXXDestructorDecl *DtorD = RD->getDestructor())
4421 if (!DtorD->isTrivial())
4422 CleanupFn = CGM.getAddrOfCXXStructor(GlobalDecl(DtorD, Dtor_Complete));
4423 // This is unused as far as we can tell, initialize it to null.
4424 llvm::Constant *ForwardCompat =
4425 getImageRelativeConstant(llvm::Constant::getNullValue(CGM.Int8PtrTy));
4426 llvm::Constant *PointerToCatchableTypes = getImageRelativeConstant(CTA);
4427 llvm::StructType *TIType = getThrowInfoType();
4428 llvm::Constant *Fields[] = {
4429 llvm::ConstantInt::get(CGM.IntTy, Flags), // Flags
4430 getImageRelativeConstant(CleanupFn), // CleanupFn
4431 ForwardCompat, // ForwardCompat
4432 PointerToCatchableTypes // CatchableTypeArray
4434 auto *GV = new llvm::GlobalVariable(
4435 CGM.getModule(), TIType, /*isConstant=*/true, getLinkageForRTTI(T),
4436 llvm::ConstantStruct::get(TIType, Fields), MangledName.str());
4437 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4438 GV->setSection(".xdata");
4439 if (GV->isWeakForLinker())
4440 GV->setComdat(CGM.getModule().getOrInsertComdat(GV->getName()));
4441 return GV;
4444 void MicrosoftCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
4445 const Expr *SubExpr = E->getSubExpr();
4446 assert(SubExpr && "SubExpr cannot be null");
4447 QualType ThrowType = SubExpr->getType();
4448 // The exception object lives on the stack and it's address is passed to the
4449 // runtime function.
4450 Address AI = CGF.CreateMemTemp(ThrowType);
4451 CGF.EmitAnyExprToMem(SubExpr, AI, ThrowType.getQualifiers(),
4452 /*IsInit=*/true);
4454 // The so-called ThrowInfo is used to describe how the exception object may be
4455 // caught.
4456 llvm::GlobalVariable *TI = getThrowInfo(ThrowType);
4458 // Call into the runtime to throw the exception.
4459 llvm::Value *Args[] = {AI.emitRawPointer(CGF), TI};
4460 CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(), Args);
4463 std::pair<llvm::Value *, const CXXRecordDecl *>
4464 MicrosoftCXXABI::LoadVTablePtr(CodeGenFunction &CGF, Address This,
4465 const CXXRecordDecl *RD) {
4466 std::tie(This, std::ignore, RD) =
4467 performBaseAdjustment(CGF, This, QualType(RD->getTypeForDecl(), 0));
4468 return {CGF.GetVTablePtr(This, CGM.Int8PtrTy, RD), RD};
4471 bool MicrosoftCXXABI::isPermittedToBeHomogeneousAggregate(
4472 const CXXRecordDecl *RD) const {
4473 // All aggregates are permitted to be HFA on non-ARM platforms, which mostly
4474 // affects vectorcall on x64/x86.
4475 if (!CGM.getTarget().getTriple().isAArch64())
4476 return true;
4477 // MSVC Windows on Arm64 has its own rules for determining if a type is HFA
4478 // that are inconsistent with the AAPCS64 ABI. The following are our best
4479 // determination of those rules so far, based on observation of MSVC's
4480 // behavior.
4481 if (RD->isEmpty())
4482 return false;
4483 if (RD->isPolymorphic())
4484 return false;
4485 if (RD->hasNonTrivialCopyAssignment())
4486 return false;
4487 if (RD->hasNonTrivialDestructor())
4488 return false;
4489 if (RD->hasNonTrivialDefaultConstructor())
4490 return false;
4491 // These two are somewhat redundant given the caller
4492 // (ABIInfo::isHomogeneousAggregate) checks the bases and fields, but that
4493 // caller doesn't consider empty bases/fields to be non-homogenous, but it
4494 // looks like Microsoft's AArch64 ABI does care about these empty types &
4495 // anything containing/derived from one is non-homogeneous.
4496 // Instead we could add another CXXABI entry point to query this property and
4497 // have ABIInfo::isHomogeneousAggregate use that property.
4498 // I don't think any other of the features listed above could be true of a
4499 // base/field while not true of the outer struct. For example, if you have a
4500 // base/field that has an non-trivial copy assignment/dtor/default ctor, then
4501 // the outer struct's corresponding operation must be non-trivial.
4502 for (const CXXBaseSpecifier &B : RD->bases()) {
4503 if (const CXXRecordDecl *FRD = B.getType()->getAsCXXRecordDecl()) {
4504 if (!isPermittedToBeHomogeneousAggregate(FRD))
4505 return false;
4508 // empty fields seem to be caught by the ABIInfo::isHomogeneousAggregate
4509 // checking for padding - but maybe there are ways to end up with an empty
4510 // field without padding? Not that I know of, so don't check fields here &
4511 // rely on the padding check.
4512 return true;