[docs] Fix build-docs.sh
[llvm-project.git] / clang / lib / CodeGen / MicrosoftCXXABI.cpp
blobcc6ba4eba6d77ead63744339258a85b33c56fd6c
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 "CGCXXABI.h"
17 #include "CGCleanup.h"
18 #include "CGVTables.h"
19 #include "CodeGenModule.h"
20 #include "CodeGenTypes.h"
21 #include "TargetInfo.h"
22 #include "clang/AST/Attr.h"
23 #include "clang/AST/CXXInheritance.h"
24 #include "clang/AST/Decl.h"
25 #include "clang/AST/DeclCXX.h"
26 #include "clang/AST/StmtCXX.h"
27 #include "clang/AST/VTableBuilder.h"
28 #include "clang/CodeGen/ConstantInitBuilder.h"
29 #include "llvm/ADT/StringExtras.h"
30 #include "llvm/ADT/StringSet.h"
31 #include "llvm/IR/Intrinsics.h"
33 using namespace clang;
34 using namespace CodeGen;
36 namespace {
38 /// Holds all the vbtable globals for a given class.
39 struct VBTableGlobals {
40 const VPtrInfoVector *VBTables;
41 SmallVector<llvm::GlobalVariable *, 2> Globals;
44 class MicrosoftCXXABI : public CGCXXABI {
45 public:
46 MicrosoftCXXABI(CodeGenModule &CGM)
47 : CGCXXABI(CGM), BaseClassDescriptorType(nullptr),
48 ClassHierarchyDescriptorType(nullptr),
49 CompleteObjectLocatorType(nullptr), CatchableTypeType(nullptr),
50 ThrowInfoType(nullptr) {
51 assert(!(CGM.getLangOpts().isExplicitDefaultVisibilityExportMapping() ||
52 CGM.getLangOpts().isAllDefaultVisibilityExportMapping()) &&
53 "visibility export mapping option unimplemented in this ABI");
56 bool HasThisReturn(GlobalDecl GD) const override;
57 bool hasMostDerivedReturn(GlobalDecl GD) const override;
59 bool classifyReturnType(CGFunctionInfo &FI) const override;
61 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override;
63 bool isSRetParameterAfterThis() const override { return true; }
65 bool isThisCompleteObject(GlobalDecl GD) const override {
66 // The Microsoft ABI doesn't use separate complete-object vs.
67 // base-object variants of constructors, but it does of destructors.
68 if (isa<CXXDestructorDecl>(GD.getDecl())) {
69 switch (GD.getDtorType()) {
70 case Dtor_Complete:
71 case Dtor_Deleting:
72 return true;
74 case Dtor_Base:
75 return false;
77 case Dtor_Comdat: llvm_unreachable("emitting dtor comdat as function?");
79 llvm_unreachable("bad dtor kind");
82 // No other kinds.
83 return false;
86 size_t getSrcArgforCopyCtor(const CXXConstructorDecl *CD,
87 FunctionArgList &Args) const override {
88 assert(Args.size() >= 2 &&
89 "expected the arglist to have at least two args!");
90 // The 'most_derived' parameter goes second if the ctor is variadic and
91 // has v-bases.
92 if (CD->getParent()->getNumVBases() > 0 &&
93 CD->getType()->castAs<FunctionProtoType>()->isVariadic())
94 return 2;
95 return 1;
98 std::vector<CharUnits> getVBPtrOffsets(const CXXRecordDecl *RD) override {
99 std::vector<CharUnits> VBPtrOffsets;
100 const ASTContext &Context = getContext();
101 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
103 const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
104 for (const std::unique_ptr<VPtrInfo> &VBT : *VBGlobals.VBTables) {
105 const ASTRecordLayout &SubobjectLayout =
106 Context.getASTRecordLayout(VBT->IntroducingObject);
107 CharUnits Offs = VBT->NonVirtualOffset;
108 Offs += SubobjectLayout.getVBPtrOffset();
109 if (VBT->getVBaseWithVPtr())
110 Offs += Layout.getVBaseClassOffset(VBT->getVBaseWithVPtr());
111 VBPtrOffsets.push_back(Offs);
113 llvm::array_pod_sort(VBPtrOffsets.begin(), VBPtrOffsets.end());
114 return VBPtrOffsets;
117 StringRef GetPureVirtualCallName() override { return "_purecall"; }
118 StringRef GetDeletedVirtualCallName() override { return "_purecall"; }
120 void emitVirtualObjectDelete(CodeGenFunction &CGF, const CXXDeleteExpr *DE,
121 Address Ptr, QualType ElementType,
122 const CXXDestructorDecl *Dtor) override;
124 void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) override;
125 void emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) override;
127 void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override;
129 llvm::GlobalVariable *getMSCompleteObjectLocator(const CXXRecordDecl *RD,
130 const VPtrInfo &Info);
132 llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override;
133 CatchTypeInfo
134 getAddrOfCXXCatchHandlerType(QualType Ty, QualType CatchHandlerType) override;
136 /// MSVC needs an extra flag to indicate a catchall.
137 CatchTypeInfo getCatchAllTypeInfo() override {
138 // For -EHa catch(...) must handle HW exception
139 // Adjective = HT_IsStdDotDot (0x40), only catch C++ exceptions
140 if (getContext().getLangOpts().EHAsynch)
141 return CatchTypeInfo{nullptr, 0};
142 else
143 return CatchTypeInfo{nullptr, 0x40};
146 bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override;
147 void EmitBadTypeidCall(CodeGenFunction &CGF) override;
148 llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
149 Address ThisPtr,
150 llvm::Type *StdTypeInfoPtrTy) override;
152 bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
153 QualType SrcRecordTy) override;
155 llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, Address Value,
156 QualType SrcRecordTy, QualType DestTy,
157 QualType DestRecordTy,
158 llvm::BasicBlock *CastEnd) override;
160 llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, Address Value,
161 QualType SrcRecordTy,
162 QualType DestTy) override;
164 bool EmitBadCastCall(CodeGenFunction &CGF) override;
165 bool canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const override {
166 return false;
169 llvm::Value *
170 GetVirtualBaseClassOffset(CodeGenFunction &CGF, Address This,
171 const CXXRecordDecl *ClassDecl,
172 const CXXRecordDecl *BaseClassDecl) override;
174 llvm::BasicBlock *
175 EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
176 const CXXRecordDecl *RD) override;
178 llvm::BasicBlock *
179 EmitDtorCompleteObjectHandler(CodeGenFunction &CGF);
181 void initializeHiddenVirtualInheritanceMembers(CodeGenFunction &CGF,
182 const CXXRecordDecl *RD) override;
184 void EmitCXXConstructors(const CXXConstructorDecl *D) override;
186 // Background on MSVC destructors
187 // ==============================
189 // Both Itanium and MSVC ABIs have destructor variants. The variant names
190 // roughly correspond in the following way:
191 // Itanium Microsoft
192 // Base -> no name, just ~Class
193 // Complete -> vbase destructor
194 // Deleting -> scalar deleting destructor
195 // vector deleting destructor
197 // The base and complete destructors are the same as in Itanium, although the
198 // complete destructor does not accept a VTT parameter when there are virtual
199 // bases. A separate mechanism involving vtordisps is used to ensure that
200 // virtual methods of destroyed subobjects are not called.
202 // The deleting destructors accept an i32 bitfield as a second parameter. Bit
203 // 1 indicates if the memory should be deleted. Bit 2 indicates if the this
204 // pointer points to an array. The scalar deleting destructor assumes that
205 // bit 2 is zero, and therefore does not contain a loop.
207 // For virtual destructors, only one entry is reserved in the vftable, and it
208 // always points to the vector deleting destructor. The vector deleting
209 // destructor is the most general, so it can be used to destroy objects in
210 // place, delete single heap objects, or delete arrays.
212 // A TU defining a non-inline destructor is only guaranteed to emit a base
213 // destructor, and all of the other variants are emitted on an as-needed basis
214 // in COMDATs. Because a non-base destructor can be emitted in a TU that
215 // lacks a definition for the destructor, non-base destructors must always
216 // delegate to or alias the base destructor.
218 AddedStructorArgCounts
219 buildStructorSignature(GlobalDecl GD,
220 SmallVectorImpl<CanQualType> &ArgTys) override;
222 /// Non-base dtors should be emitted as delegating thunks in this ABI.
223 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
224 CXXDtorType DT) const override {
225 return DT != Dtor_Base;
228 void setCXXDestructorDLLStorage(llvm::GlobalValue *GV,
229 const CXXDestructorDecl *Dtor,
230 CXXDtorType DT) const override;
232 llvm::GlobalValue::LinkageTypes
233 getCXXDestructorLinkage(GVALinkage Linkage, const CXXDestructorDecl *Dtor,
234 CXXDtorType DT) const override;
236 void EmitCXXDestructors(const CXXDestructorDecl *D) override;
238 const CXXRecordDecl *
239 getThisArgumentTypeForMethod(const CXXMethodDecl *MD) override {
240 if (MD->isVirtual() && !isa<CXXDestructorDecl>(MD)) {
241 MethodVFTableLocation ML =
242 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(MD);
243 // The vbases might be ordered differently in the final overrider object
244 // and the complete object, so the "this" argument may sometimes point to
245 // memory that has no particular type (e.g. past the complete object).
246 // In this case, we just use a generic pointer type.
247 // FIXME: might want to have a more precise type in the non-virtual
248 // multiple inheritance case.
249 if (ML.VBase || !ML.VFPtrOffset.isZero())
250 return nullptr;
252 return MD->getParent();
255 Address
256 adjustThisArgumentForVirtualFunctionCall(CodeGenFunction &CGF, GlobalDecl GD,
257 Address This,
258 bool VirtualCall) override;
260 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
261 FunctionArgList &Params) override;
263 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
265 AddedStructorArgs getImplicitConstructorArgs(CodeGenFunction &CGF,
266 const CXXConstructorDecl *D,
267 CXXCtorType Type,
268 bool ForVirtualBase,
269 bool Delegating) override;
271 llvm::Value *getCXXDestructorImplicitParam(CodeGenFunction &CGF,
272 const CXXDestructorDecl *DD,
273 CXXDtorType Type,
274 bool ForVirtualBase,
275 bool Delegating) override;
277 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
278 CXXDtorType Type, bool ForVirtualBase,
279 bool Delegating, Address This,
280 QualType ThisTy) override;
282 void emitVTableTypeMetadata(const VPtrInfo &Info, const CXXRecordDecl *RD,
283 llvm::GlobalVariable *VTable);
285 void emitVTableDefinitions(CodeGenVTables &CGVT,
286 const CXXRecordDecl *RD) override;
288 bool isVirtualOffsetNeededForVTableField(CodeGenFunction &CGF,
289 CodeGenFunction::VPtr Vptr) override;
291 /// Don't initialize vptrs if dynamic class
292 /// is marked with with the 'novtable' attribute.
293 bool doStructorsInitializeVPtrs(const CXXRecordDecl *VTableClass) override {
294 return !VTableClass->hasAttr<MSNoVTableAttr>();
297 llvm::Constant *
298 getVTableAddressPoint(BaseSubobject Base,
299 const CXXRecordDecl *VTableClass) override;
301 llvm::Value *getVTableAddressPointInStructor(
302 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
303 BaseSubobject Base, const CXXRecordDecl *NearestVBase) override;
305 llvm::Constant *
306 getVTableAddressPointForConstExpr(BaseSubobject Base,
307 const CXXRecordDecl *VTableClass) override;
309 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
310 CharUnits VPtrOffset) override;
312 CGCallee getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
313 Address This, llvm::Type *Ty,
314 SourceLocation Loc) override;
316 llvm::Value *EmitVirtualDestructorCall(CodeGenFunction &CGF,
317 const CXXDestructorDecl *Dtor,
318 CXXDtorType DtorType, Address This,
319 DeleteOrMemberCallExpr E) override;
321 void adjustCallArgsForDestructorThunk(CodeGenFunction &CGF, GlobalDecl GD,
322 CallArgList &CallArgs) override {
323 assert(GD.getDtorType() == Dtor_Deleting &&
324 "Only deleting destructor thunks are available in this ABI");
325 CallArgs.add(RValue::get(getStructorImplicitParamValue(CGF)),
326 getContext().IntTy);
329 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
331 llvm::GlobalVariable *
332 getAddrOfVBTable(const VPtrInfo &VBT, const CXXRecordDecl *RD,
333 llvm::GlobalVariable::LinkageTypes Linkage);
335 llvm::GlobalVariable *
336 getAddrOfVirtualDisplacementMap(const CXXRecordDecl *SrcRD,
337 const CXXRecordDecl *DstRD) {
338 SmallString<256> OutName;
339 llvm::raw_svector_ostream Out(OutName);
340 getMangleContext().mangleCXXVirtualDisplacementMap(SrcRD, DstRD, Out);
341 StringRef MangledName = OutName.str();
343 if (auto *VDispMap = CGM.getModule().getNamedGlobal(MangledName))
344 return VDispMap;
346 MicrosoftVTableContext &VTContext = CGM.getMicrosoftVTableContext();
347 unsigned NumEntries = 1 + SrcRD->getNumVBases();
348 SmallVector<llvm::Constant *, 4> Map(NumEntries,
349 llvm::UndefValue::get(CGM.IntTy));
350 Map[0] = llvm::ConstantInt::get(CGM.IntTy, 0);
351 bool AnyDifferent = false;
352 for (const auto &I : SrcRD->vbases()) {
353 const CXXRecordDecl *VBase = I.getType()->getAsCXXRecordDecl();
354 if (!DstRD->isVirtuallyDerivedFrom(VBase))
355 continue;
357 unsigned SrcVBIndex = VTContext.getVBTableIndex(SrcRD, VBase);
358 unsigned DstVBIndex = VTContext.getVBTableIndex(DstRD, VBase);
359 Map[SrcVBIndex] = llvm::ConstantInt::get(CGM.IntTy, DstVBIndex * 4);
360 AnyDifferent |= SrcVBIndex != DstVBIndex;
362 // This map would be useless, don't use it.
363 if (!AnyDifferent)
364 return nullptr;
366 llvm::ArrayType *VDispMapTy = llvm::ArrayType::get(CGM.IntTy, Map.size());
367 llvm::Constant *Init = llvm::ConstantArray::get(VDispMapTy, Map);
368 llvm::GlobalValue::LinkageTypes Linkage =
369 SrcRD->isExternallyVisible() && DstRD->isExternallyVisible()
370 ? llvm::GlobalValue::LinkOnceODRLinkage
371 : llvm::GlobalValue::InternalLinkage;
372 auto *VDispMap = new llvm::GlobalVariable(
373 CGM.getModule(), VDispMapTy, /*isConstant=*/true, Linkage,
374 /*Initializer=*/Init, MangledName);
375 return VDispMap;
378 void emitVBTableDefinition(const VPtrInfo &VBT, const CXXRecordDecl *RD,
379 llvm::GlobalVariable *GV) const;
381 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable,
382 GlobalDecl GD, bool ReturnAdjustment) override {
383 GVALinkage Linkage =
384 getContext().GetGVALinkageForFunction(cast<FunctionDecl>(GD.getDecl()));
386 if (Linkage == GVA_Internal)
387 Thunk->setLinkage(llvm::GlobalValue::InternalLinkage);
388 else if (ReturnAdjustment)
389 Thunk->setLinkage(llvm::GlobalValue::WeakODRLinkage);
390 else
391 Thunk->setLinkage(llvm::GlobalValue::LinkOnceODRLinkage);
394 bool exportThunk() override { return false; }
396 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, Address This,
397 const ThisAdjustment &TA) override;
399 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
400 const ReturnAdjustment &RA) override;
402 void EmitThreadLocalInitFuncs(
403 CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
404 ArrayRef<llvm::Function *> CXXThreadLocalInits,
405 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) override;
407 bool usesThreadWrapperFunction(const VarDecl *VD) const override {
408 return getContext().getLangOpts().isCompatibleWithMSVC(
409 LangOptions::MSVC2019_5) &&
410 (!isEmittedWithConstantInitializer(VD) || mayNeedDestruction(VD));
412 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
413 QualType LValType) override;
415 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
416 llvm::GlobalVariable *DeclPtr,
417 bool PerformInit) override;
418 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
419 llvm::FunctionCallee Dtor,
420 llvm::Constant *Addr) override;
422 // ==== Notes on array cookies =========
424 // MSVC seems to only use cookies when the class has a destructor; a
425 // two-argument usual array deallocation function isn't sufficient.
427 // For example, this code prints "100" and "1":
428 // struct A {
429 // char x;
430 // void *operator new[](size_t sz) {
431 // printf("%u\n", sz);
432 // return malloc(sz);
433 // }
434 // void operator delete[](void *p, size_t sz) {
435 // printf("%u\n", sz);
436 // free(p);
437 // }
438 // };
439 // int main() {
440 // A *p = new A[100];
441 // delete[] p;
442 // }
443 // Whereas it prints "104" and "104" if you give A a destructor.
445 bool requiresArrayCookie(const CXXDeleteExpr *expr,
446 QualType elementType) override;
447 bool requiresArrayCookie(const CXXNewExpr *expr) override;
448 CharUnits getArrayCookieSizeImpl(QualType type) override;
449 Address InitializeArrayCookie(CodeGenFunction &CGF,
450 Address NewPtr,
451 llvm::Value *NumElements,
452 const CXXNewExpr *expr,
453 QualType ElementType) override;
454 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
455 Address allocPtr,
456 CharUnits cookieSize) override;
458 friend struct MSRTTIBuilder;
460 bool isImageRelative() const {
461 return CGM.getTarget().getPointerWidth(/*AddrSpace=*/0) == 64;
464 // 5 routines for constructing the llvm types for MS RTTI structs.
465 llvm::StructType *getTypeDescriptorType(StringRef TypeInfoString) {
466 llvm::SmallString<32> TDTypeName("rtti.TypeDescriptor");
467 TDTypeName += llvm::utostr(TypeInfoString.size());
468 llvm::StructType *&TypeDescriptorType =
469 TypeDescriptorTypeMap[TypeInfoString.size()];
470 if (TypeDescriptorType)
471 return TypeDescriptorType;
472 llvm::Type *FieldTypes[] = {
473 CGM.Int8PtrPtrTy,
474 CGM.Int8PtrTy,
475 llvm::ArrayType::get(CGM.Int8Ty, TypeInfoString.size() + 1)};
476 TypeDescriptorType =
477 llvm::StructType::create(CGM.getLLVMContext(), FieldTypes, TDTypeName);
478 return TypeDescriptorType;
481 llvm::Type *getImageRelativeType(llvm::Type *PtrType) {
482 if (!isImageRelative())
483 return PtrType;
484 return CGM.IntTy;
487 llvm::StructType *getBaseClassDescriptorType() {
488 if (BaseClassDescriptorType)
489 return BaseClassDescriptorType;
490 llvm::Type *FieldTypes[] = {
491 getImageRelativeType(CGM.Int8PtrTy),
492 CGM.IntTy,
493 CGM.IntTy,
494 CGM.IntTy,
495 CGM.IntTy,
496 CGM.IntTy,
497 getImageRelativeType(getClassHierarchyDescriptorType()->getPointerTo()),
499 BaseClassDescriptorType = llvm::StructType::create(
500 CGM.getLLVMContext(), FieldTypes, "rtti.BaseClassDescriptor");
501 return BaseClassDescriptorType;
504 llvm::StructType *getClassHierarchyDescriptorType() {
505 if (ClassHierarchyDescriptorType)
506 return ClassHierarchyDescriptorType;
507 // Forward-declare RTTIClassHierarchyDescriptor to break a cycle.
508 ClassHierarchyDescriptorType = llvm::StructType::create(
509 CGM.getLLVMContext(), "rtti.ClassHierarchyDescriptor");
510 llvm::Type *FieldTypes[] = {
511 CGM.IntTy,
512 CGM.IntTy,
513 CGM.IntTy,
514 getImageRelativeType(
515 getBaseClassDescriptorType()->getPointerTo()->getPointerTo()),
517 ClassHierarchyDescriptorType->setBody(FieldTypes);
518 return ClassHierarchyDescriptorType;
521 llvm::StructType *getCompleteObjectLocatorType() {
522 if (CompleteObjectLocatorType)
523 return CompleteObjectLocatorType;
524 CompleteObjectLocatorType = llvm::StructType::create(
525 CGM.getLLVMContext(), "rtti.CompleteObjectLocator");
526 llvm::Type *FieldTypes[] = {
527 CGM.IntTy,
528 CGM.IntTy,
529 CGM.IntTy,
530 getImageRelativeType(CGM.Int8PtrTy),
531 getImageRelativeType(getClassHierarchyDescriptorType()->getPointerTo()),
532 getImageRelativeType(CompleteObjectLocatorType),
534 llvm::ArrayRef<llvm::Type *> FieldTypesRef(FieldTypes);
535 if (!isImageRelative())
536 FieldTypesRef = FieldTypesRef.drop_back();
537 CompleteObjectLocatorType->setBody(FieldTypesRef);
538 return CompleteObjectLocatorType;
541 llvm::GlobalVariable *getImageBase() {
542 StringRef Name = "__ImageBase";
543 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name))
544 return GV;
546 auto *GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty,
547 /*isConstant=*/true,
548 llvm::GlobalValue::ExternalLinkage,
549 /*Initializer=*/nullptr, Name);
550 CGM.setDSOLocal(GV);
551 return GV;
554 llvm::Constant *getImageRelativeConstant(llvm::Constant *PtrVal) {
555 if (!isImageRelative())
556 return PtrVal;
558 if (PtrVal->isNullValue())
559 return llvm::Constant::getNullValue(CGM.IntTy);
561 llvm::Constant *ImageBaseAsInt =
562 llvm::ConstantExpr::getPtrToInt(getImageBase(), CGM.IntPtrTy);
563 llvm::Constant *PtrValAsInt =
564 llvm::ConstantExpr::getPtrToInt(PtrVal, CGM.IntPtrTy);
565 llvm::Constant *Diff =
566 llvm::ConstantExpr::getSub(PtrValAsInt, ImageBaseAsInt,
567 /*HasNUW=*/true, /*HasNSW=*/true);
568 return llvm::ConstantExpr::getTrunc(Diff, CGM.IntTy);
571 private:
572 MicrosoftMangleContext &getMangleContext() {
573 return cast<MicrosoftMangleContext>(CodeGen::CGCXXABI::getMangleContext());
576 llvm::Constant *getZeroInt() {
577 return llvm::ConstantInt::get(CGM.IntTy, 0);
580 llvm::Constant *getAllOnesInt() {
581 return llvm::Constant::getAllOnesValue(CGM.IntTy);
584 CharUnits getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD) override;
586 void
587 GetNullMemberPointerFields(const MemberPointerType *MPT,
588 llvm::SmallVectorImpl<llvm::Constant *> &fields);
590 /// Shared code for virtual base adjustment. Returns the offset from
591 /// the vbptr to the virtual base. Optionally returns the address of the
592 /// vbptr itself.
593 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
594 Address Base,
595 llvm::Value *VBPtrOffset,
596 llvm::Value *VBTableOffset,
597 llvm::Value **VBPtr = nullptr);
599 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
600 Address Base,
601 int32_t VBPtrOffset,
602 int32_t VBTableOffset,
603 llvm::Value **VBPtr = nullptr) {
604 assert(VBTableOffset % 4 == 0 && "should be byte offset into table of i32s");
605 llvm::Value *VBPOffset = llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset),
606 *VBTOffset = llvm::ConstantInt::get(CGM.IntTy, VBTableOffset);
607 return GetVBaseOffsetFromVBPtr(CGF, Base, VBPOffset, VBTOffset, VBPtr);
610 std::tuple<Address, llvm::Value *, const CXXRecordDecl *>
611 performBaseAdjustment(CodeGenFunction &CGF, Address Value,
612 QualType SrcRecordTy);
614 /// Performs a full virtual base adjustment. Used to dereference
615 /// pointers to members of virtual bases.
616 llvm::Value *AdjustVirtualBase(CodeGenFunction &CGF, const Expr *E,
617 const CXXRecordDecl *RD, Address Base,
618 llvm::Value *VirtualBaseAdjustmentOffset,
619 llvm::Value *VBPtrOffset /* optional */);
621 /// Emits a full member pointer with the fields common to data and
622 /// function member pointers.
623 llvm::Constant *EmitFullMemberPointer(llvm::Constant *FirstField,
624 bool IsMemberFunction,
625 const CXXRecordDecl *RD,
626 CharUnits NonVirtualBaseAdjustment,
627 unsigned VBTableIndex);
629 bool MemberPointerConstantIsNull(const MemberPointerType *MPT,
630 llvm::Constant *MP);
632 /// - Initialize all vbptrs of 'this' with RD as the complete type.
633 void EmitVBPtrStores(CodeGenFunction &CGF, const CXXRecordDecl *RD);
635 /// Caching wrapper around VBTableBuilder::enumerateVBTables().
636 const VBTableGlobals &enumerateVBTables(const CXXRecordDecl *RD);
638 /// Generate a thunk for calling a virtual member function MD.
639 llvm::Function *EmitVirtualMemPtrThunk(const CXXMethodDecl *MD,
640 const MethodVFTableLocation &ML);
642 llvm::Constant *EmitMemberDataPointer(const CXXRecordDecl *RD,
643 CharUnits offset);
645 public:
646 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override;
648 bool isZeroInitializable(const MemberPointerType *MPT) override;
650 bool isMemberPointerConvertible(const MemberPointerType *MPT) const override {
651 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
652 return RD->hasAttr<MSInheritanceAttr>();
655 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override;
657 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
658 CharUnits offset) override;
659 llvm::Constant *EmitMemberFunctionPointer(const CXXMethodDecl *MD) override;
660 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override;
662 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
663 llvm::Value *L,
664 llvm::Value *R,
665 const MemberPointerType *MPT,
666 bool Inequality) override;
668 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
669 llvm::Value *MemPtr,
670 const MemberPointerType *MPT) override;
672 llvm::Value *
673 EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
674 Address Base, llvm::Value *MemPtr,
675 const MemberPointerType *MPT) override;
677 llvm::Value *EmitNonNullMemberPointerConversion(
678 const MemberPointerType *SrcTy, const MemberPointerType *DstTy,
679 CastKind CK, CastExpr::path_const_iterator PathBegin,
680 CastExpr::path_const_iterator PathEnd, llvm::Value *Src,
681 CGBuilderTy &Builder);
683 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
684 const CastExpr *E,
685 llvm::Value *Src) override;
687 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
688 llvm::Constant *Src) override;
690 llvm::Constant *EmitMemberPointerConversion(
691 const MemberPointerType *SrcTy, const MemberPointerType *DstTy,
692 CastKind CK, CastExpr::path_const_iterator PathBegin,
693 CastExpr::path_const_iterator PathEnd, llvm::Constant *Src);
695 CGCallee
696 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF, const Expr *E,
697 Address This, llvm::Value *&ThisPtrForCall,
698 llvm::Value *MemPtr,
699 const MemberPointerType *MPT) override;
701 void emitCXXStructor(GlobalDecl GD) override;
703 llvm::StructType *getCatchableTypeType() {
704 if (CatchableTypeType)
705 return CatchableTypeType;
706 llvm::Type *FieldTypes[] = {
707 CGM.IntTy, // Flags
708 getImageRelativeType(CGM.Int8PtrTy), // TypeDescriptor
709 CGM.IntTy, // NonVirtualAdjustment
710 CGM.IntTy, // OffsetToVBPtr
711 CGM.IntTy, // VBTableIndex
712 CGM.IntTy, // Size
713 getImageRelativeType(CGM.Int8PtrTy) // CopyCtor
715 CatchableTypeType = llvm::StructType::create(
716 CGM.getLLVMContext(), FieldTypes, "eh.CatchableType");
717 return CatchableTypeType;
720 llvm::StructType *getCatchableTypeArrayType(uint32_t NumEntries) {
721 llvm::StructType *&CatchableTypeArrayType =
722 CatchableTypeArrayTypeMap[NumEntries];
723 if (CatchableTypeArrayType)
724 return CatchableTypeArrayType;
726 llvm::SmallString<23> CTATypeName("eh.CatchableTypeArray.");
727 CTATypeName += llvm::utostr(NumEntries);
728 llvm::Type *CTType =
729 getImageRelativeType(getCatchableTypeType()->getPointerTo());
730 llvm::Type *FieldTypes[] = {
731 CGM.IntTy, // NumEntries
732 llvm::ArrayType::get(CTType, NumEntries) // CatchableTypes
734 CatchableTypeArrayType =
735 llvm::StructType::create(CGM.getLLVMContext(), FieldTypes, CTATypeName);
736 return CatchableTypeArrayType;
739 llvm::StructType *getThrowInfoType() {
740 if (ThrowInfoType)
741 return ThrowInfoType;
742 llvm::Type *FieldTypes[] = {
743 CGM.IntTy, // Flags
744 getImageRelativeType(CGM.Int8PtrTy), // CleanupFn
745 getImageRelativeType(CGM.Int8PtrTy), // ForwardCompat
746 getImageRelativeType(CGM.Int8PtrTy) // CatchableTypeArray
748 ThrowInfoType = llvm::StructType::create(CGM.getLLVMContext(), FieldTypes,
749 "eh.ThrowInfo");
750 return ThrowInfoType;
753 llvm::FunctionCallee getThrowFn() {
754 // _CxxThrowException is passed an exception object and a ThrowInfo object
755 // which describes the exception.
756 llvm::Type *Args[] = {CGM.Int8PtrTy, getThrowInfoType()->getPointerTo()};
757 llvm::FunctionType *FTy =
758 llvm::FunctionType::get(CGM.VoidTy, Args, /*isVarArg=*/false);
759 llvm::FunctionCallee Throw =
760 CGM.CreateRuntimeFunction(FTy, "_CxxThrowException");
761 // _CxxThrowException is stdcall on 32-bit x86 platforms.
762 if (CGM.getTarget().getTriple().getArch() == llvm::Triple::x86) {
763 if (auto *Fn = dyn_cast<llvm::Function>(Throw.getCallee()))
764 Fn->setCallingConv(llvm::CallingConv::X86_StdCall);
766 return Throw;
769 llvm::Function *getAddrOfCXXCtorClosure(const CXXConstructorDecl *CD,
770 CXXCtorType CT);
772 llvm::Constant *getCatchableType(QualType T,
773 uint32_t NVOffset = 0,
774 int32_t VBPtrOffset = -1,
775 uint32_t VBIndex = 0);
777 llvm::GlobalVariable *getCatchableTypeArray(QualType T);
779 llvm::GlobalVariable *getThrowInfo(QualType T) override;
781 std::pair<llvm::Value *, const CXXRecordDecl *>
782 LoadVTablePtr(CodeGenFunction &CGF, Address This,
783 const CXXRecordDecl *RD) override;
785 bool
786 isPermittedToBeHomogeneousAggregate(const CXXRecordDecl *RD) const override;
788 private:
789 typedef std::pair<const CXXRecordDecl *, CharUnits> VFTableIdTy;
790 typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalVariable *> VTablesMapTy;
791 typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalValue *> VFTablesMapTy;
792 /// All the vftables that have been referenced.
793 VFTablesMapTy VFTablesMap;
794 VTablesMapTy VTablesMap;
796 /// This set holds the record decls we've deferred vtable emission for.
797 llvm::SmallPtrSet<const CXXRecordDecl *, 4> DeferredVFTables;
800 /// All the vbtables which have been referenced.
801 llvm::DenseMap<const CXXRecordDecl *, VBTableGlobals> VBTablesMap;
803 /// Info on the global variable used to guard initialization of static locals.
804 /// The BitIndex field is only used for externally invisible declarations.
805 struct GuardInfo {
806 GuardInfo() : Guard(nullptr), BitIndex(0) {}
807 llvm::GlobalVariable *Guard;
808 unsigned BitIndex;
811 /// Map from DeclContext to the current guard variable. We assume that the
812 /// AST is visited in source code order.
813 llvm::DenseMap<const DeclContext *, GuardInfo> GuardVariableMap;
814 llvm::DenseMap<const DeclContext *, GuardInfo> ThreadLocalGuardVariableMap;
815 llvm::DenseMap<const DeclContext *, unsigned> ThreadSafeGuardNumMap;
817 llvm::DenseMap<size_t, llvm::StructType *> TypeDescriptorTypeMap;
818 llvm::StructType *BaseClassDescriptorType;
819 llvm::StructType *ClassHierarchyDescriptorType;
820 llvm::StructType *CompleteObjectLocatorType;
822 llvm::DenseMap<QualType, llvm::GlobalVariable *> CatchableTypeArrays;
824 llvm::StructType *CatchableTypeType;
825 llvm::DenseMap<uint32_t, llvm::StructType *> CatchableTypeArrayTypeMap;
826 llvm::StructType *ThrowInfoType;
831 CGCXXABI::RecordArgABI
832 MicrosoftCXXABI::getRecordArgABI(const CXXRecordDecl *RD) const {
833 // Use the default C calling convention rules for things that can be passed in
834 // registers, i.e. non-trivially copyable records or records marked with
835 // [[trivial_abi]].
836 if (RD->canPassInRegisters())
837 return RAA_Default;
839 switch (CGM.getTarget().getTriple().getArch()) {
840 default:
841 // FIXME: Implement for other architectures.
842 return RAA_Indirect;
844 case llvm::Triple::thumb:
845 // Pass things indirectly for now because it is simple.
846 // FIXME: This is incompatible with MSVC for arguments with a dtor and no
847 // copy ctor.
848 return RAA_Indirect;
850 case llvm::Triple::x86: {
851 // If the argument has *required* alignment greater than four bytes, pass
852 // it indirectly. Prior to MSVC version 19.14, passing overaligned
853 // arguments was not supported and resulted in a compiler error. In 19.14
854 // and later versions, such arguments are now passed indirectly.
855 TypeInfo Info = getContext().getTypeInfo(RD->getTypeForDecl());
856 if (Info.isAlignRequired() && Info.Align > 4)
857 return RAA_Indirect;
859 // If C++ prohibits us from making a copy, construct the arguments directly
860 // into argument memory.
861 return RAA_DirectInMemory;
864 case llvm::Triple::x86_64:
865 case llvm::Triple::aarch64:
866 return RAA_Indirect;
869 llvm_unreachable("invalid enum");
872 void MicrosoftCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
873 const CXXDeleteExpr *DE,
874 Address Ptr,
875 QualType ElementType,
876 const CXXDestructorDecl *Dtor) {
877 // FIXME: Provide a source location here even though there's no
878 // CXXMemberCallExpr for dtor call.
879 bool UseGlobalDelete = DE->isGlobalDelete();
880 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
881 llvm::Value *MDThis = EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, DE);
882 if (UseGlobalDelete)
883 CGF.EmitDeleteCall(DE->getOperatorDelete(), MDThis, ElementType);
886 void MicrosoftCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
887 llvm::Value *Args[] = {
888 llvm::ConstantPointerNull::get(CGM.Int8PtrTy),
889 llvm::ConstantPointerNull::get(getThrowInfoType()->getPointerTo())};
890 llvm::FunctionCallee Fn = getThrowFn();
891 if (isNoReturn)
892 CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, Args);
893 else
894 CGF.EmitRuntimeCallOrInvoke(Fn, Args);
897 void MicrosoftCXXABI::emitBeginCatch(CodeGenFunction &CGF,
898 const CXXCatchStmt *S) {
899 // In the MS ABI, the runtime handles the copy, and the catch handler is
900 // responsible for destruction.
901 VarDecl *CatchParam = S->getExceptionDecl();
902 llvm::BasicBlock *CatchPadBB = CGF.Builder.GetInsertBlock();
903 llvm::CatchPadInst *CPI =
904 cast<llvm::CatchPadInst>(CatchPadBB->getFirstNonPHI());
905 CGF.CurrentFuncletPad = CPI;
907 // If this is a catch-all or the catch parameter is unnamed, we don't need to
908 // emit an alloca to the object.
909 if (!CatchParam || !CatchParam->getDeclName()) {
910 CGF.EHStack.pushCleanup<CatchRetScope>(NormalCleanup, CPI);
911 return;
914 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
915 CPI->setArgOperand(2, var.getObjectAddress(CGF).getPointer());
916 CGF.EHStack.pushCleanup<CatchRetScope>(NormalCleanup, CPI);
917 CGF.EmitAutoVarCleanups(var);
920 /// We need to perform a generic polymorphic operation (like a typeid
921 /// or a cast), which requires an object with a vfptr. Adjust the
922 /// address to point to an object with a vfptr.
923 std::tuple<Address, llvm::Value *, const CXXRecordDecl *>
924 MicrosoftCXXABI::performBaseAdjustment(CodeGenFunction &CGF, Address Value,
925 QualType SrcRecordTy) {
926 Value = CGF.Builder.CreateElementBitCast(Value, CGF.Int8Ty);
927 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
928 const ASTContext &Context = getContext();
930 // If the class itself has a vfptr, great. This check implicitly
931 // covers non-virtual base subobjects: a class with its own virtual
932 // functions would be a candidate to be a primary base.
933 if (Context.getASTRecordLayout(SrcDecl).hasExtendableVFPtr())
934 return std::make_tuple(Value, llvm::ConstantInt::get(CGF.Int32Ty, 0),
935 SrcDecl);
937 // Okay, one of the vbases must have a vfptr, or else this isn't
938 // actually a polymorphic class.
939 const CXXRecordDecl *PolymorphicBase = nullptr;
940 for (auto &Base : SrcDecl->vbases()) {
941 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
942 if (Context.getASTRecordLayout(BaseDecl).hasExtendableVFPtr()) {
943 PolymorphicBase = BaseDecl;
944 break;
947 assert(PolymorphicBase && "polymorphic class has no apparent vfptr?");
949 llvm::Value *Offset =
950 GetVirtualBaseClassOffset(CGF, Value, SrcDecl, PolymorphicBase);
951 llvm::Value *Ptr = CGF.Builder.CreateInBoundsGEP(
952 Value.getElementType(), Value.getPointer(), Offset);
953 CharUnits VBaseAlign =
954 CGF.CGM.getVBaseAlignment(Value.getAlignment(), SrcDecl, PolymorphicBase);
955 return std::make_tuple(Address(Ptr, CGF.Int8Ty, VBaseAlign), Offset,
956 PolymorphicBase);
959 bool MicrosoftCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
960 QualType SrcRecordTy) {
961 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
962 return IsDeref &&
963 !getContext().getASTRecordLayout(SrcDecl).hasExtendableVFPtr();
966 static llvm::CallBase *emitRTtypeidCall(CodeGenFunction &CGF,
967 llvm::Value *Argument) {
968 llvm::Type *ArgTypes[] = {CGF.Int8PtrTy};
969 llvm::FunctionType *FTy =
970 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false);
971 llvm::Value *Args[] = {Argument};
972 llvm::FunctionCallee Fn = CGF.CGM.CreateRuntimeFunction(FTy, "__RTtypeid");
973 return CGF.EmitRuntimeCallOrInvoke(Fn, Args);
976 void MicrosoftCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
977 llvm::CallBase *Call =
978 emitRTtypeidCall(CGF, llvm::Constant::getNullValue(CGM.VoidPtrTy));
979 Call->setDoesNotReturn();
980 CGF.Builder.CreateUnreachable();
983 llvm::Value *MicrosoftCXXABI::EmitTypeid(CodeGenFunction &CGF,
984 QualType SrcRecordTy,
985 Address ThisPtr,
986 llvm::Type *StdTypeInfoPtrTy) {
987 std::tie(ThisPtr, std::ignore, std::ignore) =
988 performBaseAdjustment(CGF, ThisPtr, SrcRecordTy);
989 llvm::CallBase *Typeid = emitRTtypeidCall(CGF, ThisPtr.getPointer());
990 return CGF.Builder.CreateBitCast(Typeid, StdTypeInfoPtrTy);
993 bool MicrosoftCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
994 QualType SrcRecordTy) {
995 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
996 return SrcIsPtr &&
997 !getContext().getASTRecordLayout(SrcDecl).hasExtendableVFPtr();
1000 llvm::Value *MicrosoftCXXABI::EmitDynamicCastCall(
1001 CodeGenFunction &CGF, Address This, QualType SrcRecordTy,
1002 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
1003 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1005 llvm::Value *SrcRTTI =
1006 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1007 llvm::Value *DestRTTI =
1008 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1010 llvm::Value *Offset;
1011 std::tie(This, Offset, std::ignore) =
1012 performBaseAdjustment(CGF, This, SrcRecordTy);
1013 llvm::Value *ThisPtr = This.getPointer();
1014 Offset = CGF.Builder.CreateTrunc(Offset, CGF.Int32Ty);
1016 // PVOID __RTDynamicCast(
1017 // PVOID inptr,
1018 // LONG VfDelta,
1019 // PVOID SrcType,
1020 // PVOID TargetType,
1021 // BOOL isReference)
1022 llvm::Type *ArgTypes[] = {CGF.Int8PtrTy, CGF.Int32Ty, CGF.Int8PtrTy,
1023 CGF.Int8PtrTy, CGF.Int32Ty};
1024 llvm::FunctionCallee Function = CGF.CGM.CreateRuntimeFunction(
1025 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false),
1026 "__RTDynamicCast");
1027 llvm::Value *Args[] = {
1028 ThisPtr, Offset, SrcRTTI, DestRTTI,
1029 llvm::ConstantInt::get(CGF.Int32Ty, DestTy->isReferenceType())};
1030 ThisPtr = CGF.EmitRuntimeCallOrInvoke(Function, Args);
1031 return CGF.Builder.CreateBitCast(ThisPtr, DestLTy);
1034 llvm::Value *
1035 MicrosoftCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF, Address Value,
1036 QualType SrcRecordTy,
1037 QualType DestTy) {
1038 std::tie(Value, std::ignore, std::ignore) =
1039 performBaseAdjustment(CGF, Value, SrcRecordTy);
1041 // PVOID __RTCastToVoid(
1042 // PVOID inptr)
1043 llvm::Type *ArgTypes[] = {CGF.Int8PtrTy};
1044 llvm::FunctionCallee Function = CGF.CGM.CreateRuntimeFunction(
1045 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false),
1046 "__RTCastToVoid");
1047 llvm::Value *Args[] = {Value.getPointer()};
1048 return CGF.EmitRuntimeCall(Function, Args);
1051 bool MicrosoftCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1052 return false;
1055 llvm::Value *MicrosoftCXXABI::GetVirtualBaseClassOffset(
1056 CodeGenFunction &CGF, Address This, const CXXRecordDecl *ClassDecl,
1057 const CXXRecordDecl *BaseClassDecl) {
1058 const ASTContext &Context = getContext();
1059 int64_t VBPtrChars =
1060 Context.getASTRecordLayout(ClassDecl).getVBPtrOffset().getQuantity();
1061 llvm::Value *VBPtrOffset = llvm::ConstantInt::get(CGM.PtrDiffTy, VBPtrChars);
1062 CharUnits IntSize = Context.getTypeSizeInChars(Context.IntTy);
1063 CharUnits VBTableChars =
1064 IntSize *
1065 CGM.getMicrosoftVTableContext().getVBTableIndex(ClassDecl, BaseClassDecl);
1066 llvm::Value *VBTableOffset =
1067 llvm::ConstantInt::get(CGM.IntTy, VBTableChars.getQuantity());
1069 llvm::Value *VBPtrToNewBase =
1070 GetVBaseOffsetFromVBPtr(CGF, This, VBPtrOffset, VBTableOffset);
1071 VBPtrToNewBase =
1072 CGF.Builder.CreateSExtOrBitCast(VBPtrToNewBase, CGM.PtrDiffTy);
1073 return CGF.Builder.CreateNSWAdd(VBPtrOffset, VBPtrToNewBase);
1076 bool MicrosoftCXXABI::HasThisReturn(GlobalDecl GD) const {
1077 return isa<CXXConstructorDecl>(GD.getDecl());
1080 static bool isDeletingDtor(GlobalDecl GD) {
1081 return isa<CXXDestructorDecl>(GD.getDecl()) &&
1082 GD.getDtorType() == Dtor_Deleting;
1085 bool MicrosoftCXXABI::hasMostDerivedReturn(GlobalDecl GD) const {
1086 return isDeletingDtor(GD);
1089 static bool isTrivialForAArch64MSVC(const CXXRecordDecl *RD) {
1090 // For AArch64, we use the C++14 definition of an aggregate, so we also
1091 // check for:
1092 // No private or protected non static data members.
1093 // No base classes
1094 // No virtual functions
1095 // Additionally, we need to ensure that there is a trivial copy assignment
1096 // operator, a trivial destructor and no user-provided constructors.
1097 if (RD->hasProtectedFields() || RD->hasPrivateFields())
1098 return false;
1099 if (RD->getNumBases() > 0)
1100 return false;
1101 if (RD->isPolymorphic())
1102 return false;
1103 if (RD->hasNonTrivialCopyAssignment())
1104 return false;
1105 for (const CXXConstructorDecl *Ctor : RD->ctors())
1106 if (Ctor->isUserProvided())
1107 return false;
1108 if (RD->hasNonTrivialDestructor())
1109 return false;
1110 return true;
1113 bool MicrosoftCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
1114 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
1115 if (!RD)
1116 return false;
1118 // Normally, the C++ concept of "is trivially copyable" is used to determine
1119 // if a struct can be returned directly. However, as MSVC and the language
1120 // have evolved, the definition of "trivially copyable" has changed, while the
1121 // ABI must remain stable. AArch64 uses the C++14 concept of an "aggregate",
1122 // while other ISAs use the older concept of "plain old data".
1123 bool isTrivialForABI = RD->isPOD();
1124 bool isAArch64 = CGM.getTarget().getTriple().isAArch64();
1125 if (isAArch64)
1126 isTrivialForABI = RD->canPassInRegisters() && isTrivialForAArch64MSVC(RD);
1128 // MSVC always returns structs indirectly from C++ instance methods.
1129 bool isIndirectReturn = !isTrivialForABI || FI.isInstanceMethod();
1131 if (isIndirectReturn) {
1132 CharUnits Align = CGM.getContext().getTypeAlignInChars(FI.getReturnType());
1133 FI.getReturnInfo() = ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
1135 // MSVC always passes `this` before the `sret` parameter.
1136 FI.getReturnInfo().setSRetAfterThis(FI.isInstanceMethod());
1138 // On AArch64, use the `inreg` attribute if the object is considered to not
1139 // be trivially copyable, or if this is an instance method struct return.
1140 FI.getReturnInfo().setInReg(isAArch64);
1142 return true;
1145 // Otherwise, use the C ABI rules.
1146 return false;
1149 llvm::BasicBlock *
1150 MicrosoftCXXABI::EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
1151 const CXXRecordDecl *RD) {
1152 llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);
1153 assert(IsMostDerivedClass &&
1154 "ctor for a class with virtual bases must have an implicit parameter");
1155 llvm::Value *IsCompleteObject =
1156 CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");
1158 llvm::BasicBlock *CallVbaseCtorsBB = CGF.createBasicBlock("ctor.init_vbases");
1159 llvm::BasicBlock *SkipVbaseCtorsBB = CGF.createBasicBlock("ctor.skip_vbases");
1160 CGF.Builder.CreateCondBr(IsCompleteObject,
1161 CallVbaseCtorsBB, SkipVbaseCtorsBB);
1163 CGF.EmitBlock(CallVbaseCtorsBB);
1165 // Fill in the vbtable pointers here.
1166 EmitVBPtrStores(CGF, RD);
1168 // CGF will put the base ctor calls in this basic block for us later.
1170 return SkipVbaseCtorsBB;
1173 llvm::BasicBlock *
1174 MicrosoftCXXABI::EmitDtorCompleteObjectHandler(CodeGenFunction &CGF) {
1175 llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);
1176 assert(IsMostDerivedClass &&
1177 "ctor for a class with virtual bases must have an implicit parameter");
1178 llvm::Value *IsCompleteObject =
1179 CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");
1181 llvm::BasicBlock *CallVbaseDtorsBB = CGF.createBasicBlock("Dtor.dtor_vbases");
1182 llvm::BasicBlock *SkipVbaseDtorsBB = CGF.createBasicBlock("Dtor.skip_vbases");
1183 CGF.Builder.CreateCondBr(IsCompleteObject,
1184 CallVbaseDtorsBB, SkipVbaseDtorsBB);
1186 CGF.EmitBlock(CallVbaseDtorsBB);
1187 // CGF will put the base dtor calls in this basic block for us later.
1189 return SkipVbaseDtorsBB;
1192 void MicrosoftCXXABI::initializeHiddenVirtualInheritanceMembers(
1193 CodeGenFunction &CGF, const CXXRecordDecl *RD) {
1194 // In most cases, an override for a vbase virtual method can adjust
1195 // the "this" parameter by applying a constant offset.
1196 // However, this is not enough while a constructor or a destructor of some
1197 // class X is being executed if all the following conditions are met:
1198 // - X has virtual bases, (1)
1199 // - X overrides a virtual method M of a vbase Y, (2)
1200 // - X itself is a vbase of the most derived class.
1202 // If (1) and (2) are true, the vtorDisp for vbase Y is a hidden member of X
1203 // which holds the extra amount of "this" adjustment we must do when we use
1204 // the X vftables (i.e. during X ctor or dtor).
1205 // Outside the ctors and dtors, the values of vtorDisps are zero.
1207 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1208 typedef ASTRecordLayout::VBaseOffsetsMapTy VBOffsets;
1209 const VBOffsets &VBaseMap = Layout.getVBaseOffsetsMap();
1210 CGBuilderTy &Builder = CGF.Builder;
1212 unsigned AS = getThisAddress(CGF).getAddressSpace();
1213 llvm::Value *Int8This = nullptr; // Initialize lazily.
1215 for (const CXXBaseSpecifier &S : RD->vbases()) {
1216 const CXXRecordDecl *VBase = S.getType()->getAsCXXRecordDecl();
1217 auto I = VBaseMap.find(VBase);
1218 assert(I != VBaseMap.end());
1219 if (!I->second.hasVtorDisp())
1220 continue;
1222 llvm::Value *VBaseOffset =
1223 GetVirtualBaseClassOffset(CGF, getThisAddress(CGF), RD, VBase);
1224 uint64_t ConstantVBaseOffset = I->second.VBaseOffset.getQuantity();
1226 // vtorDisp_for_vbase = vbptr[vbase_idx] - offsetof(RD, vbase).
1227 llvm::Value *VtorDispValue = Builder.CreateSub(
1228 VBaseOffset, llvm::ConstantInt::get(CGM.PtrDiffTy, ConstantVBaseOffset),
1229 "vtordisp.value");
1230 VtorDispValue = Builder.CreateTruncOrBitCast(VtorDispValue, CGF.Int32Ty);
1232 if (!Int8This)
1233 Int8This = Builder.CreateBitCast(getThisValue(CGF),
1234 CGF.Int8Ty->getPointerTo(AS));
1235 llvm::Value *VtorDispPtr =
1236 Builder.CreateInBoundsGEP(CGF.Int8Ty, Int8This, VBaseOffset);
1237 // vtorDisp is always the 32-bits before the vbase in the class layout.
1238 VtorDispPtr = Builder.CreateConstGEP1_32(CGF.Int8Ty, VtorDispPtr, -4);
1239 VtorDispPtr = Builder.CreateBitCast(
1240 VtorDispPtr, CGF.Int32Ty->getPointerTo(AS), "vtordisp.ptr");
1242 Builder.CreateAlignedStore(VtorDispValue, VtorDispPtr,
1243 CharUnits::fromQuantity(4));
1247 static bool hasDefaultCXXMethodCC(ASTContext &Context,
1248 const CXXMethodDecl *MD) {
1249 CallingConv ExpectedCallingConv = Context.getDefaultCallingConvention(
1250 /*IsVariadic=*/false, /*IsCXXMethod=*/true);
1251 CallingConv ActualCallingConv =
1252 MD->getType()->castAs<FunctionProtoType>()->getCallConv();
1253 return ExpectedCallingConv == ActualCallingConv;
1256 void MicrosoftCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1257 // There's only one constructor type in this ABI.
1258 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1260 // Exported default constructors either have a simple call-site where they use
1261 // the typical calling convention and have a single 'this' pointer for an
1262 // argument -or- they get a wrapper function which appropriately thunks to the
1263 // real default constructor. This thunk is the default constructor closure.
1264 if (D->hasAttr<DLLExportAttr>() && D->isDefaultConstructor() &&
1265 D->isDefined()) {
1266 if (!hasDefaultCXXMethodCC(getContext(), D) || D->getNumParams() != 0) {
1267 llvm::Function *Fn = getAddrOfCXXCtorClosure(D, Ctor_DefaultClosure);
1268 Fn->setLinkage(llvm::GlobalValue::WeakODRLinkage);
1269 CGM.setGVProperties(Fn, D);
1274 void MicrosoftCXXABI::EmitVBPtrStores(CodeGenFunction &CGF,
1275 const CXXRecordDecl *RD) {
1276 Address This = getThisAddress(CGF);
1277 This = CGF.Builder.CreateElementBitCast(This, CGM.Int8Ty, "this.int8");
1278 const ASTContext &Context = getContext();
1279 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1281 const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
1282 for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) {
1283 const std::unique_ptr<VPtrInfo> &VBT = (*VBGlobals.VBTables)[I];
1284 llvm::GlobalVariable *GV = VBGlobals.Globals[I];
1285 const ASTRecordLayout &SubobjectLayout =
1286 Context.getASTRecordLayout(VBT->IntroducingObject);
1287 CharUnits Offs = VBT->NonVirtualOffset;
1288 Offs += SubobjectLayout.getVBPtrOffset();
1289 if (VBT->getVBaseWithVPtr())
1290 Offs += Layout.getVBaseClassOffset(VBT->getVBaseWithVPtr());
1291 Address VBPtr = CGF.Builder.CreateConstInBoundsByteGEP(This, Offs);
1292 llvm::Value *GVPtr =
1293 CGF.Builder.CreateConstInBoundsGEP2_32(GV->getValueType(), GV, 0, 0);
1294 VBPtr = CGF.Builder.CreateElementBitCast(VBPtr, GVPtr->getType(),
1295 "vbptr." + VBT->ObjectWithVPtr->getName());
1296 CGF.Builder.CreateStore(GVPtr, VBPtr);
1300 CGCXXABI::AddedStructorArgCounts
1301 MicrosoftCXXABI::buildStructorSignature(GlobalDecl GD,
1302 SmallVectorImpl<CanQualType> &ArgTys) {
1303 AddedStructorArgCounts Added;
1304 // TODO: 'for base' flag
1305 if (isa<CXXDestructorDecl>(GD.getDecl()) &&
1306 GD.getDtorType() == Dtor_Deleting) {
1307 // The scalar deleting destructor takes an implicit int parameter.
1308 ArgTys.push_back(getContext().IntTy);
1309 ++Added.Suffix;
1311 auto *CD = dyn_cast<CXXConstructorDecl>(GD.getDecl());
1312 if (!CD)
1313 return Added;
1315 // All parameters are already in place except is_most_derived, which goes
1316 // after 'this' if it's variadic and last if it's not.
1318 const CXXRecordDecl *Class = CD->getParent();
1319 const FunctionProtoType *FPT = CD->getType()->castAs<FunctionProtoType>();
1320 if (Class->getNumVBases()) {
1321 if (FPT->isVariadic()) {
1322 ArgTys.insert(ArgTys.begin() + 1, getContext().IntTy);
1323 ++Added.Prefix;
1324 } else {
1325 ArgTys.push_back(getContext().IntTy);
1326 ++Added.Suffix;
1330 return Added;
1333 void MicrosoftCXXABI::setCXXDestructorDLLStorage(llvm::GlobalValue *GV,
1334 const CXXDestructorDecl *Dtor,
1335 CXXDtorType DT) const {
1336 // Deleting destructor variants are never imported or exported. Give them the
1337 // default storage class.
1338 if (DT == Dtor_Deleting) {
1339 GV->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
1340 } else {
1341 const NamedDecl *ND = Dtor;
1342 CGM.setDLLImportDLLExport(GV, ND);
1346 llvm::GlobalValue::LinkageTypes MicrosoftCXXABI::getCXXDestructorLinkage(
1347 GVALinkage Linkage, const CXXDestructorDecl *Dtor, CXXDtorType DT) const {
1348 // Internal things are always internal, regardless of attributes. After this,
1349 // we know the thunk is externally visible.
1350 if (Linkage == GVA_Internal)
1351 return llvm::GlobalValue::InternalLinkage;
1353 switch (DT) {
1354 case Dtor_Base:
1355 // The base destructor most closely tracks the user-declared constructor, so
1356 // we delegate back to the normal declarator case.
1357 return CGM.getLLVMLinkageForDeclarator(Dtor, Linkage,
1358 /*IsConstantVariable=*/false);
1359 case Dtor_Complete:
1360 // The complete destructor is like an inline function, but it may be
1361 // imported and therefore must be exported as well. This requires changing
1362 // the linkage if a DLL attribute is present.
1363 if (Dtor->hasAttr<DLLExportAttr>())
1364 return llvm::GlobalValue::WeakODRLinkage;
1365 if (Dtor->hasAttr<DLLImportAttr>())
1366 return llvm::GlobalValue::AvailableExternallyLinkage;
1367 return llvm::GlobalValue::LinkOnceODRLinkage;
1368 case Dtor_Deleting:
1369 // Deleting destructors are like inline functions. They have vague linkage
1370 // and are emitted everywhere they are used. They are internal if the class
1371 // is internal.
1372 return llvm::GlobalValue::LinkOnceODRLinkage;
1373 case Dtor_Comdat:
1374 llvm_unreachable("MS C++ ABI does not support comdat dtors");
1376 llvm_unreachable("invalid dtor type");
1379 void MicrosoftCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
1380 // The TU defining a dtor is only guaranteed to emit a base destructor. All
1381 // other destructor variants are delegating thunks.
1382 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
1384 // If the class is dllexported, emit the complete (vbase) destructor wherever
1385 // the base dtor is emitted.
1386 // FIXME: To match MSVC, this should only be done when the class is exported
1387 // with -fdllexport-inlines enabled.
1388 if (D->getParent()->getNumVBases() > 0 && D->hasAttr<DLLExportAttr>())
1389 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
1392 CharUnits
1393 MicrosoftCXXABI::getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD) {
1394 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1396 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1397 // Complete destructors take a pointer to the complete object as a
1398 // parameter, thus don't need this adjustment.
1399 if (GD.getDtorType() == Dtor_Complete)
1400 return CharUnits();
1402 // There's no Dtor_Base in vftable but it shares the this adjustment with
1403 // the deleting one, so look it up instead.
1404 GD = GlobalDecl(DD, Dtor_Deleting);
1407 MethodVFTableLocation ML =
1408 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD);
1409 CharUnits Adjustment = ML.VFPtrOffset;
1411 // Normal virtual instance methods need to adjust from the vfptr that first
1412 // defined the virtual method to the virtual base subobject, but destructors
1413 // do not. The vector deleting destructor thunk applies this adjustment for
1414 // us if necessary.
1415 if (isa<CXXDestructorDecl>(MD))
1416 Adjustment = CharUnits::Zero();
1418 if (ML.VBase) {
1419 const ASTRecordLayout &DerivedLayout =
1420 getContext().getASTRecordLayout(MD->getParent());
1421 Adjustment += DerivedLayout.getVBaseClassOffset(ML.VBase);
1424 return Adjustment;
1427 Address MicrosoftCXXABI::adjustThisArgumentForVirtualFunctionCall(
1428 CodeGenFunction &CGF, GlobalDecl GD, Address This,
1429 bool VirtualCall) {
1430 if (!VirtualCall) {
1431 // If the call of a virtual function is not virtual, we just have to
1432 // compensate for the adjustment the virtual function does in its prologue.
1433 CharUnits Adjustment = getVirtualFunctionPrologueThisAdjustment(GD);
1434 if (Adjustment.isZero())
1435 return This;
1437 This = CGF.Builder.CreateElementBitCast(This, CGF.Int8Ty);
1438 assert(Adjustment.isPositive());
1439 return CGF.Builder.CreateConstByteGEP(This, Adjustment);
1442 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1444 GlobalDecl LookupGD = GD;
1445 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1446 // Complete dtors take a pointer to the complete object,
1447 // thus don't need adjustment.
1448 if (GD.getDtorType() == Dtor_Complete)
1449 return This;
1451 // There's only Dtor_Deleting in vftable but it shares the this adjustment
1452 // with the base one, so look up the deleting one instead.
1453 LookupGD = GlobalDecl(DD, Dtor_Deleting);
1455 MethodVFTableLocation ML =
1456 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD);
1458 CharUnits StaticOffset = ML.VFPtrOffset;
1460 // Base destructors expect 'this' to point to the beginning of the base
1461 // subobject, not the first vfptr that happens to contain the virtual dtor.
1462 // However, we still need to apply the virtual base adjustment.
1463 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
1464 StaticOffset = CharUnits::Zero();
1466 Address Result = This;
1467 if (ML.VBase) {
1468 Result = CGF.Builder.CreateElementBitCast(Result, CGF.Int8Ty);
1470 const CXXRecordDecl *Derived = MD->getParent();
1471 const CXXRecordDecl *VBase = ML.VBase;
1472 llvm::Value *VBaseOffset =
1473 GetVirtualBaseClassOffset(CGF, Result, Derived, VBase);
1474 llvm::Value *VBasePtr = CGF.Builder.CreateInBoundsGEP(
1475 Result.getElementType(), Result.getPointer(), VBaseOffset);
1476 CharUnits VBaseAlign =
1477 CGF.CGM.getVBaseAlignment(Result.getAlignment(), Derived, VBase);
1478 Result = Address(VBasePtr, CGF.Int8Ty, VBaseAlign);
1480 if (!StaticOffset.isZero()) {
1481 assert(StaticOffset.isPositive());
1482 Result = CGF.Builder.CreateElementBitCast(Result, CGF.Int8Ty);
1483 if (ML.VBase) {
1484 // Non-virtual adjustment might result in a pointer outside the allocated
1485 // object, e.g. if the final overrider class is laid out after the virtual
1486 // base that declares a method in the most derived class.
1487 // FIXME: Update the code that emits this adjustment in thunks prologues.
1488 Result = CGF.Builder.CreateConstByteGEP(Result, StaticOffset);
1489 } else {
1490 Result = CGF.Builder.CreateConstInBoundsByteGEP(Result, StaticOffset);
1493 return Result;
1496 void MicrosoftCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1497 QualType &ResTy,
1498 FunctionArgList &Params) {
1499 ASTContext &Context = getContext();
1500 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
1501 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
1502 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
1503 auto *IsMostDerived = ImplicitParamDecl::Create(
1504 Context, /*DC=*/nullptr, CGF.CurGD.getDecl()->getLocation(),
1505 &Context.Idents.get("is_most_derived"), Context.IntTy,
1506 ImplicitParamDecl::Other);
1507 // The 'most_derived' parameter goes second if the ctor is variadic and last
1508 // if it's not. Dtors can't be variadic.
1509 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
1510 if (FPT->isVariadic())
1511 Params.insert(Params.begin() + 1, IsMostDerived);
1512 else
1513 Params.push_back(IsMostDerived);
1514 getStructorImplicitParamDecl(CGF) = IsMostDerived;
1515 } else if (isDeletingDtor(CGF.CurGD)) {
1516 auto *ShouldDelete = ImplicitParamDecl::Create(
1517 Context, /*DC=*/nullptr, CGF.CurGD.getDecl()->getLocation(),
1518 &Context.Idents.get("should_call_delete"), Context.IntTy,
1519 ImplicitParamDecl::Other);
1520 Params.push_back(ShouldDelete);
1521 getStructorImplicitParamDecl(CGF) = ShouldDelete;
1525 void MicrosoftCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
1526 // Naked functions have no prolog.
1527 if (CGF.CurFuncDecl && CGF.CurFuncDecl->hasAttr<NakedAttr>())
1528 return;
1530 // Overridden virtual methods of non-primary bases need to adjust the incoming
1531 // 'this' pointer in the prologue. In this hierarchy, C::b will subtract
1532 // sizeof(void*) to adjust from B* to C*:
1533 // struct A { virtual void a(); };
1534 // struct B { virtual void b(); };
1535 // struct C : A, B { virtual void b(); };
1537 // Leave the value stored in the 'this' alloca unadjusted, so that the
1538 // debugger sees the unadjusted value. Microsoft debuggers require this, and
1539 // will apply the ThisAdjustment in the method type information.
1540 // FIXME: Do something better for DWARF debuggers, which won't expect this,
1541 // without making our codegen depend on debug info settings.
1542 llvm::Value *This = loadIncomingCXXThis(CGF);
1543 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
1544 if (!CGF.CurFuncIsThunk && MD->isVirtual()) {
1545 CharUnits Adjustment = getVirtualFunctionPrologueThisAdjustment(CGF.CurGD);
1546 if (!Adjustment.isZero()) {
1547 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
1548 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS),
1549 *thisTy = This->getType();
1550 This = CGF.Builder.CreateBitCast(This, charPtrTy);
1551 assert(Adjustment.isPositive());
1552 This = CGF.Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, This,
1553 -Adjustment.getQuantity());
1554 This = CGF.Builder.CreateBitCast(This, thisTy, "this.adjusted");
1557 setCXXABIThisValue(CGF, This);
1559 // If this is a function that the ABI specifies returns 'this', initialize
1560 // the return slot to 'this' at the start of the function.
1562 // Unlike the setting of return types, this is done within the ABI
1563 // implementation instead of by clients of CGCXXABI because:
1564 // 1) getThisValue is currently protected
1565 // 2) in theory, an ABI could implement 'this' returns some other way;
1566 // HasThisReturn only specifies a contract, not the implementation
1567 if (HasThisReturn(CGF.CurGD))
1568 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
1569 else if (hasMostDerivedReturn(CGF.CurGD))
1570 CGF.Builder.CreateStore(CGF.EmitCastToVoidPtr(getThisValue(CGF)),
1571 CGF.ReturnValue);
1573 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
1574 assert(getStructorImplicitParamDecl(CGF) &&
1575 "no implicit parameter for a constructor with virtual bases?");
1576 getStructorImplicitParamValue(CGF)
1577 = CGF.Builder.CreateLoad(
1578 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
1579 "is_most_derived");
1582 if (isDeletingDtor(CGF.CurGD)) {
1583 assert(getStructorImplicitParamDecl(CGF) &&
1584 "no implicit parameter for a deleting destructor?");
1585 getStructorImplicitParamValue(CGF)
1586 = CGF.Builder.CreateLoad(
1587 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
1588 "should_call_delete");
1592 CGCXXABI::AddedStructorArgs MicrosoftCXXABI::getImplicitConstructorArgs(
1593 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1594 bool ForVirtualBase, bool Delegating) {
1595 assert(Type == Ctor_Complete || Type == Ctor_Base);
1597 // Check if we need a 'most_derived' parameter.
1598 if (!D->getParent()->getNumVBases())
1599 return AddedStructorArgs{};
1601 // Add the 'most_derived' argument second if we are variadic or last if not.
1602 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
1603 llvm::Value *MostDerivedArg;
1604 if (Delegating) {
1605 MostDerivedArg = getStructorImplicitParamValue(CGF);
1606 } else {
1607 MostDerivedArg = llvm::ConstantInt::get(CGM.Int32Ty, Type == Ctor_Complete);
1609 if (FPT->isVariadic()) {
1610 return AddedStructorArgs::prefix({{MostDerivedArg, getContext().IntTy}});
1612 return AddedStructorArgs::suffix({{MostDerivedArg, getContext().IntTy}});
1615 llvm::Value *MicrosoftCXXABI::getCXXDestructorImplicitParam(
1616 CodeGenFunction &CGF, const CXXDestructorDecl *DD, CXXDtorType Type,
1617 bool ForVirtualBase, bool Delegating) {
1618 return nullptr;
1621 void MicrosoftCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1622 const CXXDestructorDecl *DD,
1623 CXXDtorType Type, bool ForVirtualBase,
1624 bool Delegating, Address This,
1625 QualType ThisTy) {
1626 // Use the base destructor variant in place of the complete destructor variant
1627 // if the class has no virtual bases. This effectively implements some of the
1628 // -mconstructor-aliases optimization, but as part of the MS C++ ABI.
1629 if (Type == Dtor_Complete && DD->getParent()->getNumVBases() == 0)
1630 Type = Dtor_Base;
1632 GlobalDecl GD(DD, Type);
1633 CGCallee Callee = CGCallee::forDirect(CGM.getAddrOfCXXStructor(GD), GD);
1635 if (DD->isVirtual()) {
1636 assert(Type != CXXDtorType::Dtor_Deleting &&
1637 "The deleting destructor should only be called via a virtual call");
1638 This = adjustThisArgumentForVirtualFunctionCall(CGF, GlobalDecl(DD, Type),
1639 This, false);
1642 llvm::BasicBlock *BaseDtorEndBB = nullptr;
1643 if (ForVirtualBase && isa<CXXConstructorDecl>(CGF.CurCodeDecl)) {
1644 BaseDtorEndBB = EmitDtorCompleteObjectHandler(CGF);
1647 llvm::Value *Implicit =
1648 getCXXDestructorImplicitParam(CGF, DD, Type, ForVirtualBase,
1649 Delegating); // = nullptr
1650 CGF.EmitCXXDestructorCall(GD, Callee, This.getPointer(), ThisTy,
1651 /*ImplicitParam=*/Implicit,
1652 /*ImplicitParamTy=*/QualType(), nullptr);
1653 if (BaseDtorEndBB) {
1654 // Complete object handler should continue to be the remaining
1655 CGF.Builder.CreateBr(BaseDtorEndBB);
1656 CGF.EmitBlock(BaseDtorEndBB);
1660 void MicrosoftCXXABI::emitVTableTypeMetadata(const VPtrInfo &Info,
1661 const CXXRecordDecl *RD,
1662 llvm::GlobalVariable *VTable) {
1663 if (!CGM.getCodeGenOpts().LTOUnit)
1664 return;
1666 // TODO: Should VirtualFunctionElimination also be supported here?
1667 // See similar handling in CodeGenModule::EmitVTableTypeMetadata.
1668 if (CGM.getCodeGenOpts().WholeProgramVTables) {
1669 llvm::DenseSet<const CXXRecordDecl *> Visited;
1670 llvm::GlobalObject::VCallVisibility TypeVis =
1671 CGM.GetVCallVisibilityLevel(RD, Visited);
1672 if (TypeVis != llvm::GlobalObject::VCallVisibilityPublic)
1673 VTable->setVCallVisibilityMetadata(TypeVis);
1676 // The location of the first virtual function pointer in the virtual table,
1677 // aka the "address point" on Itanium. This is at offset 0 if RTTI is
1678 // disabled, or sizeof(void*) if RTTI is enabled.
1679 CharUnits AddressPoint =
1680 getContext().getLangOpts().RTTIData
1681 ? getContext().toCharUnitsFromBits(
1682 getContext().getTargetInfo().getPointerWidth(0))
1683 : CharUnits::Zero();
1685 if (Info.PathToIntroducingObject.empty()) {
1686 CGM.AddVTableTypeMetadata(VTable, AddressPoint, RD);
1687 return;
1690 // Add a bitset entry for the least derived base belonging to this vftable.
1691 CGM.AddVTableTypeMetadata(VTable, AddressPoint,
1692 Info.PathToIntroducingObject.back());
1694 // Add a bitset entry for each derived class that is laid out at the same
1695 // offset as the least derived base.
1696 for (unsigned I = Info.PathToIntroducingObject.size() - 1; I != 0; --I) {
1697 const CXXRecordDecl *DerivedRD = Info.PathToIntroducingObject[I - 1];
1698 const CXXRecordDecl *BaseRD = Info.PathToIntroducingObject[I];
1700 const ASTRecordLayout &Layout =
1701 getContext().getASTRecordLayout(DerivedRD);
1702 CharUnits Offset;
1703 auto VBI = Layout.getVBaseOffsetsMap().find(BaseRD);
1704 if (VBI == Layout.getVBaseOffsetsMap().end())
1705 Offset = Layout.getBaseClassOffset(BaseRD);
1706 else
1707 Offset = VBI->second.VBaseOffset;
1708 if (!Offset.isZero())
1709 return;
1710 CGM.AddVTableTypeMetadata(VTable, AddressPoint, DerivedRD);
1713 // Finally do the same for the most derived class.
1714 if (Info.FullOffsetInMDC.isZero())
1715 CGM.AddVTableTypeMetadata(VTable, AddressPoint, RD);
1718 void MicrosoftCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1719 const CXXRecordDecl *RD) {
1720 MicrosoftVTableContext &VFTContext = CGM.getMicrosoftVTableContext();
1721 const VPtrInfoVector &VFPtrs = VFTContext.getVFPtrOffsets(RD);
1723 for (const std::unique_ptr<VPtrInfo>& Info : VFPtrs) {
1724 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, Info->FullOffsetInMDC);
1725 if (VTable->hasInitializer())
1726 continue;
1728 const VTableLayout &VTLayout =
1729 VFTContext.getVFTableLayout(RD, Info->FullOffsetInMDC);
1731 llvm::Constant *RTTI = nullptr;
1732 if (any_of(VTLayout.vtable_components(),
1733 [](const VTableComponent &VTC) { return VTC.isRTTIKind(); }))
1734 RTTI = getMSCompleteObjectLocator(RD, *Info);
1736 ConstantInitBuilder builder(CGM);
1737 auto components = builder.beginStruct();
1738 CGVT.createVTableInitializer(components, VTLayout, RTTI,
1739 VTable->hasLocalLinkage());
1740 components.finishAndSetAsInitializer(VTable);
1742 emitVTableTypeMetadata(*Info, RD, VTable);
1746 bool MicrosoftCXXABI::isVirtualOffsetNeededForVTableField(
1747 CodeGenFunction &CGF, CodeGenFunction::VPtr Vptr) {
1748 return Vptr.NearestVBase != nullptr;
1751 llvm::Value *MicrosoftCXXABI::getVTableAddressPointInStructor(
1752 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1753 const CXXRecordDecl *NearestVBase) {
1754 llvm::Constant *VTableAddressPoint = getVTableAddressPoint(Base, VTableClass);
1755 if (!VTableAddressPoint) {
1756 assert(Base.getBase()->getNumVBases() &&
1757 !getContext().getASTRecordLayout(Base.getBase()).hasOwnVFPtr());
1759 return VTableAddressPoint;
1762 static void mangleVFTableName(MicrosoftMangleContext &MangleContext,
1763 const CXXRecordDecl *RD, const VPtrInfo &VFPtr,
1764 SmallString<256> &Name) {
1765 llvm::raw_svector_ostream Out(Name);
1766 MangleContext.mangleCXXVFTable(RD, VFPtr.MangledPath, Out);
1769 llvm::Constant *
1770 MicrosoftCXXABI::getVTableAddressPoint(BaseSubobject Base,
1771 const CXXRecordDecl *VTableClass) {
1772 (void)getAddrOfVTable(VTableClass, Base.getBaseOffset());
1773 VFTableIdTy ID(VTableClass, Base.getBaseOffset());
1774 return VFTablesMap[ID];
1777 llvm::Constant *MicrosoftCXXABI::getVTableAddressPointForConstExpr(
1778 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1779 llvm::Constant *VFTable = getVTableAddressPoint(Base, VTableClass);
1780 assert(VFTable && "Couldn't find a vftable for the given base?");
1781 return VFTable;
1784 llvm::GlobalVariable *MicrosoftCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1785 CharUnits VPtrOffset) {
1786 // getAddrOfVTable may return 0 if asked to get an address of a vtable which
1787 // shouldn't be used in the given record type. We want to cache this result in
1788 // VFTablesMap, thus a simple zero check is not sufficient.
1790 VFTableIdTy ID(RD, VPtrOffset);
1791 VTablesMapTy::iterator I;
1792 bool Inserted;
1793 std::tie(I, Inserted) = VTablesMap.insert(std::make_pair(ID, nullptr));
1794 if (!Inserted)
1795 return I->second;
1797 llvm::GlobalVariable *&VTable = I->second;
1799 MicrosoftVTableContext &VTContext = CGM.getMicrosoftVTableContext();
1800 const VPtrInfoVector &VFPtrs = VTContext.getVFPtrOffsets(RD);
1802 if (DeferredVFTables.insert(RD).second) {
1803 // We haven't processed this record type before.
1804 // Queue up this vtable for possible deferred emission.
1805 CGM.addDeferredVTable(RD);
1807 #ifndef NDEBUG
1808 // Create all the vftables at once in order to make sure each vftable has
1809 // a unique mangled name.
1810 llvm::StringSet<> ObservedMangledNames;
1811 for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) {
1812 SmallString<256> Name;
1813 mangleVFTableName(getMangleContext(), RD, *VFPtrs[J], Name);
1814 if (!ObservedMangledNames.insert(Name.str()).second)
1815 llvm_unreachable("Already saw this mangling before?");
1817 #endif
1820 const std::unique_ptr<VPtrInfo> *VFPtrI =
1821 llvm::find_if(VFPtrs, [&](const std::unique_ptr<VPtrInfo> &VPI) {
1822 return VPI->FullOffsetInMDC == VPtrOffset;
1824 if (VFPtrI == VFPtrs.end()) {
1825 VFTablesMap[ID] = nullptr;
1826 return nullptr;
1828 const std::unique_ptr<VPtrInfo> &VFPtr = *VFPtrI;
1830 SmallString<256> VFTableName;
1831 mangleVFTableName(getMangleContext(), RD, *VFPtr, VFTableName);
1833 // Classes marked __declspec(dllimport) need vftables generated on the
1834 // import-side in order to support features like constexpr. No other
1835 // translation unit relies on the emission of the local vftable, translation
1836 // units are expected to generate them as needed.
1838 // Because of this unique behavior, we maintain this logic here instead of
1839 // getVTableLinkage.
1840 llvm::GlobalValue::LinkageTypes VFTableLinkage =
1841 RD->hasAttr<DLLImportAttr>() ? llvm::GlobalValue::LinkOnceODRLinkage
1842 : CGM.getVTableLinkage(RD);
1843 bool VFTableComesFromAnotherTU =
1844 llvm::GlobalValue::isAvailableExternallyLinkage(VFTableLinkage) ||
1845 llvm::GlobalValue::isExternalLinkage(VFTableLinkage);
1846 bool VTableAliasIsRequred =
1847 !VFTableComesFromAnotherTU && getContext().getLangOpts().RTTIData;
1849 if (llvm::GlobalValue *VFTable =
1850 CGM.getModule().getNamedGlobal(VFTableName)) {
1851 VFTablesMap[ID] = VFTable;
1852 VTable = VTableAliasIsRequred
1853 ? cast<llvm::GlobalVariable>(
1854 cast<llvm::GlobalAlias>(VFTable)->getAliaseeObject())
1855 : cast<llvm::GlobalVariable>(VFTable);
1856 return VTable;
1859 const VTableLayout &VTLayout =
1860 VTContext.getVFTableLayout(RD, VFPtr->FullOffsetInMDC);
1861 llvm::GlobalValue::LinkageTypes VTableLinkage =
1862 VTableAliasIsRequred ? llvm::GlobalValue::PrivateLinkage : VFTableLinkage;
1864 StringRef VTableName = VTableAliasIsRequred ? StringRef() : VFTableName.str();
1866 llvm::Type *VTableType = CGM.getVTables().getVTableType(VTLayout);
1868 // Create a backing variable for the contents of VTable. The VTable may
1869 // or may not include space for a pointer to RTTI data.
1870 llvm::GlobalValue *VFTable;
1871 VTable = new llvm::GlobalVariable(CGM.getModule(), VTableType,
1872 /*isConstant=*/true, VTableLinkage,
1873 /*Initializer=*/nullptr, VTableName);
1874 VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1876 llvm::Comdat *C = nullptr;
1877 if (!VFTableComesFromAnotherTU &&
1878 (llvm::GlobalValue::isWeakForLinker(VFTableLinkage) ||
1879 (llvm::GlobalValue::isLocalLinkage(VFTableLinkage) &&
1880 VTableAliasIsRequred)))
1881 C = CGM.getModule().getOrInsertComdat(VFTableName.str());
1883 // Only insert a pointer into the VFTable for RTTI data if we are not
1884 // importing it. We never reference the RTTI data directly so there is no
1885 // need to make room for it.
1886 if (VTableAliasIsRequred) {
1887 llvm::Value *GEPIndices[] = {llvm::ConstantInt::get(CGM.Int32Ty, 0),
1888 llvm::ConstantInt::get(CGM.Int32Ty, 0),
1889 llvm::ConstantInt::get(CGM.Int32Ty, 1)};
1890 // Create a GEP which points just after the first entry in the VFTable,
1891 // this should be the location of the first virtual method.
1892 llvm::Constant *VTableGEP = llvm::ConstantExpr::getInBoundsGetElementPtr(
1893 VTable->getValueType(), VTable, GEPIndices);
1894 if (llvm::GlobalValue::isWeakForLinker(VFTableLinkage)) {
1895 VFTableLinkage = llvm::GlobalValue::ExternalLinkage;
1896 if (C)
1897 C->setSelectionKind(llvm::Comdat::Largest);
1899 VFTable = llvm::GlobalAlias::create(CGM.Int8PtrTy,
1900 /*AddressSpace=*/0, VFTableLinkage,
1901 VFTableName.str(), VTableGEP,
1902 &CGM.getModule());
1903 VFTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1904 } else {
1905 // We don't need a GlobalAlias to be a symbol for the VTable if we won't
1906 // be referencing any RTTI data.
1907 // The GlobalVariable will end up being an appropriate definition of the
1908 // VFTable.
1909 VFTable = VTable;
1911 if (C)
1912 VTable->setComdat(C);
1914 if (RD->hasAttr<DLLExportAttr>())
1915 VFTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1917 VFTablesMap[ID] = VFTable;
1918 return VTable;
1921 CGCallee MicrosoftCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1922 GlobalDecl GD,
1923 Address This,
1924 llvm::Type *Ty,
1925 SourceLocation Loc) {
1926 CGBuilderTy &Builder = CGF.Builder;
1928 Ty = Ty->getPointerTo();
1929 Address VPtr =
1930 adjustThisArgumentForVirtualFunctionCall(CGF, GD, This, true);
1932 auto *MethodDecl = cast<CXXMethodDecl>(GD.getDecl());
1933 llvm::Value *VTable = CGF.GetVTablePtr(VPtr, Ty->getPointerTo(),
1934 MethodDecl->getParent());
1936 MicrosoftVTableContext &VFTContext = CGM.getMicrosoftVTableContext();
1937 MethodVFTableLocation ML = VFTContext.getMethodVFTableLocation(GD);
1939 // Compute the identity of the most derived class whose virtual table is
1940 // located at the MethodVFTableLocation ML.
1941 auto getObjectWithVPtr = [&] {
1942 return llvm::find_if(VFTContext.getVFPtrOffsets(
1943 ML.VBase ? ML.VBase : MethodDecl->getParent()),
1944 [&](const std::unique_ptr<VPtrInfo> &Info) {
1945 return Info->FullOffsetInMDC == ML.VFPtrOffset;
1947 ->get()
1948 ->ObjectWithVPtr;
1951 llvm::Value *VFunc;
1952 if (CGF.ShouldEmitVTableTypeCheckedLoad(MethodDecl->getParent())) {
1953 VFunc = CGF.EmitVTableTypeCheckedLoad(
1954 getObjectWithVPtr(), VTable, Ty,
1955 ML.Index * CGM.getContext().getTargetInfo().getPointerWidth(0) / 8);
1956 } else {
1957 if (CGM.getCodeGenOpts().PrepareForLTO)
1958 CGF.EmitTypeMetadataCodeForVCall(getObjectWithVPtr(), VTable, Loc);
1960 llvm::Value *VFuncPtr =
1961 Builder.CreateConstInBoundsGEP1_64(Ty, VTable, ML.Index, "vfn");
1962 VFunc = Builder.CreateAlignedLoad(Ty, VFuncPtr, CGF.getPointerAlign());
1965 CGCallee Callee(GD, VFunc);
1966 return Callee;
1969 llvm::Value *MicrosoftCXXABI::EmitVirtualDestructorCall(
1970 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
1971 Address This, DeleteOrMemberCallExpr E) {
1972 auto *CE = E.dyn_cast<const CXXMemberCallExpr *>();
1973 auto *D = E.dyn_cast<const CXXDeleteExpr *>();
1974 assert((CE != nullptr) ^ (D != nullptr));
1975 assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
1976 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1978 // We have only one destructor in the vftable but can get both behaviors
1979 // by passing an implicit int parameter.
1980 GlobalDecl GD(Dtor, Dtor_Deleting);
1981 const CGFunctionInfo *FInfo =
1982 &CGM.getTypes().arrangeCXXStructorDeclaration(GD);
1983 llvm::FunctionType *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
1984 CGCallee Callee = CGCallee::forVirtual(CE, GD, This, Ty);
1986 ASTContext &Context = getContext();
1987 llvm::Value *ImplicitParam = llvm::ConstantInt::get(
1988 llvm::IntegerType::getInt32Ty(CGF.getLLVMContext()),
1989 DtorType == Dtor_Deleting);
1991 QualType ThisTy;
1992 if (CE) {
1993 ThisTy = CE->getObjectType();
1994 } else {
1995 ThisTy = D->getDestroyedType();
1998 This = adjustThisArgumentForVirtualFunctionCall(CGF, GD, This, true);
1999 RValue RV = CGF.EmitCXXDestructorCall(GD, Callee, This.getPointer(), ThisTy,
2000 ImplicitParam, Context.IntTy, CE);
2001 return RV.getScalarVal();
2004 const VBTableGlobals &
2005 MicrosoftCXXABI::enumerateVBTables(const CXXRecordDecl *RD) {
2006 // At this layer, we can key the cache off of a single class, which is much
2007 // easier than caching each vbtable individually.
2008 llvm::DenseMap<const CXXRecordDecl*, VBTableGlobals>::iterator Entry;
2009 bool Added;
2010 std::tie(Entry, Added) =
2011 VBTablesMap.insert(std::make_pair(RD, VBTableGlobals()));
2012 VBTableGlobals &VBGlobals = Entry->second;
2013 if (!Added)
2014 return VBGlobals;
2016 MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext();
2017 VBGlobals.VBTables = &Context.enumerateVBTables(RD);
2019 // Cache the globals for all vbtables so we don't have to recompute the
2020 // mangled names.
2021 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
2022 for (VPtrInfoVector::const_iterator I = VBGlobals.VBTables->begin(),
2023 E = VBGlobals.VBTables->end();
2024 I != E; ++I) {
2025 VBGlobals.Globals.push_back(getAddrOfVBTable(**I, RD, Linkage));
2028 return VBGlobals;
2031 llvm::Function *
2032 MicrosoftCXXABI::EmitVirtualMemPtrThunk(const CXXMethodDecl *MD,
2033 const MethodVFTableLocation &ML) {
2034 assert(!isa<CXXConstructorDecl>(MD) && !isa<CXXDestructorDecl>(MD) &&
2035 "can't form pointers to ctors or virtual dtors");
2037 // Calculate the mangled name.
2038 SmallString<256> ThunkName;
2039 llvm::raw_svector_ostream Out(ThunkName);
2040 getMangleContext().mangleVirtualMemPtrThunk(MD, ML, Out);
2042 // If the thunk has been generated previously, just return it.
2043 if (llvm::GlobalValue *GV = CGM.getModule().getNamedValue(ThunkName))
2044 return cast<llvm::Function>(GV);
2046 // Create the llvm::Function.
2047 const CGFunctionInfo &FnInfo =
2048 CGM.getTypes().arrangeUnprototypedMustTailThunk(MD);
2049 llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo);
2050 llvm::Function *ThunkFn =
2051 llvm::Function::Create(ThunkTy, llvm::Function::ExternalLinkage,
2052 ThunkName.str(), &CGM.getModule());
2053 assert(ThunkFn->getName() == ThunkName && "name was uniqued!");
2055 ThunkFn->setLinkage(MD->isExternallyVisible()
2056 ? llvm::GlobalValue::LinkOnceODRLinkage
2057 : llvm::GlobalValue::InternalLinkage);
2058 if (MD->isExternallyVisible())
2059 ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));
2061 CGM.SetLLVMFunctionAttributes(MD, FnInfo, ThunkFn, /*IsThunk=*/false);
2062 CGM.SetLLVMFunctionAttributesForDefinition(MD, ThunkFn);
2064 // Add the "thunk" attribute so that LLVM knows that the return type is
2065 // meaningless. These thunks can be used to call functions with differing
2066 // return types, and the caller is required to cast the prototype
2067 // appropriately to extract the correct value.
2068 ThunkFn->addFnAttr("thunk");
2070 // These thunks can be compared, so they are not unnamed.
2071 ThunkFn->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::None);
2073 // Start codegen.
2074 CodeGenFunction CGF(CGM);
2075 CGF.CurGD = GlobalDecl(MD);
2076 CGF.CurFuncIsThunk = true;
2078 // Build FunctionArgs, but only include the implicit 'this' parameter
2079 // declaration.
2080 FunctionArgList FunctionArgs;
2081 buildThisParam(CGF, FunctionArgs);
2083 // Start defining the function.
2084 CGF.StartFunction(GlobalDecl(), FnInfo.getReturnType(), ThunkFn, FnInfo,
2085 FunctionArgs, MD->getLocation(), SourceLocation());
2086 setCXXABIThisValue(CGF, loadIncomingCXXThis(CGF));
2088 // Load the vfptr and then callee from the vftable. The callee should have
2089 // adjusted 'this' so that the vfptr is at offset zero.
2090 llvm::Type *ThunkPtrTy = ThunkTy->getPointerTo();
2091 llvm::Value *VTable = CGF.GetVTablePtr(
2092 getThisAddress(CGF), ThunkPtrTy->getPointerTo(), MD->getParent());
2094 llvm::Value *VFuncPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
2095 ThunkPtrTy, VTable, ML.Index, "vfn");
2096 llvm::Value *Callee =
2097 CGF.Builder.CreateAlignedLoad(ThunkPtrTy, VFuncPtr, CGF.getPointerAlign());
2099 CGF.EmitMustTailThunk(MD, getThisValue(CGF), {ThunkTy, Callee});
2101 return ThunkFn;
2104 void MicrosoftCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
2105 const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
2106 for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) {
2107 const std::unique_ptr<VPtrInfo>& VBT = (*VBGlobals.VBTables)[I];
2108 llvm::GlobalVariable *GV = VBGlobals.Globals[I];
2109 if (GV->isDeclaration())
2110 emitVBTableDefinition(*VBT, RD, GV);
2114 llvm::GlobalVariable *
2115 MicrosoftCXXABI::getAddrOfVBTable(const VPtrInfo &VBT, const CXXRecordDecl *RD,
2116 llvm::GlobalVariable::LinkageTypes Linkage) {
2117 SmallString<256> OutName;
2118 llvm::raw_svector_ostream Out(OutName);
2119 getMangleContext().mangleCXXVBTable(RD, VBT.MangledPath, Out);
2120 StringRef Name = OutName.str();
2122 llvm::ArrayType *VBTableType =
2123 llvm::ArrayType::get(CGM.IntTy, 1 + VBT.ObjectWithVPtr->getNumVBases());
2125 assert(!CGM.getModule().getNamedGlobal(Name) &&
2126 "vbtable with this name already exists: mangling bug?");
2127 CharUnits Alignment =
2128 CGM.getContext().getTypeAlignInChars(CGM.getContext().IntTy);
2129 llvm::GlobalVariable *GV = CGM.CreateOrReplaceCXXRuntimeVariable(
2130 Name, VBTableType, Linkage, Alignment.getQuantity());
2131 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2133 if (RD->hasAttr<DLLImportAttr>())
2134 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2135 else if (RD->hasAttr<DLLExportAttr>())
2136 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
2138 if (!GV->hasExternalLinkage())
2139 emitVBTableDefinition(VBT, RD, GV);
2141 return GV;
2144 void MicrosoftCXXABI::emitVBTableDefinition(const VPtrInfo &VBT,
2145 const CXXRecordDecl *RD,
2146 llvm::GlobalVariable *GV) const {
2147 const CXXRecordDecl *ObjectWithVPtr = VBT.ObjectWithVPtr;
2149 assert(RD->getNumVBases() && ObjectWithVPtr->getNumVBases() &&
2150 "should only emit vbtables for classes with vbtables");
2152 const ASTRecordLayout &BaseLayout =
2153 getContext().getASTRecordLayout(VBT.IntroducingObject);
2154 const ASTRecordLayout &DerivedLayout = getContext().getASTRecordLayout(RD);
2156 SmallVector<llvm::Constant *, 4> Offsets(1 + ObjectWithVPtr->getNumVBases(),
2157 nullptr);
2159 // The offset from ObjectWithVPtr's vbptr to itself always leads.
2160 CharUnits VBPtrOffset = BaseLayout.getVBPtrOffset();
2161 Offsets[0] = llvm::ConstantInt::get(CGM.IntTy, -VBPtrOffset.getQuantity());
2163 MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext();
2164 for (const auto &I : ObjectWithVPtr->vbases()) {
2165 const CXXRecordDecl *VBase = I.getType()->getAsCXXRecordDecl();
2166 CharUnits Offset = DerivedLayout.getVBaseClassOffset(VBase);
2167 assert(!Offset.isNegative());
2169 // Make it relative to the subobject vbptr.
2170 CharUnits CompleteVBPtrOffset = VBT.NonVirtualOffset + VBPtrOffset;
2171 if (VBT.getVBaseWithVPtr())
2172 CompleteVBPtrOffset +=
2173 DerivedLayout.getVBaseClassOffset(VBT.getVBaseWithVPtr());
2174 Offset -= CompleteVBPtrOffset;
2176 unsigned VBIndex = Context.getVBTableIndex(ObjectWithVPtr, VBase);
2177 assert(Offsets[VBIndex] == nullptr && "The same vbindex seen twice?");
2178 Offsets[VBIndex] = llvm::ConstantInt::get(CGM.IntTy, Offset.getQuantity());
2181 assert(Offsets.size() ==
2182 cast<llvm::ArrayType>(GV->getValueType())->getNumElements());
2183 llvm::ArrayType *VBTableType =
2184 llvm::ArrayType::get(CGM.IntTy, Offsets.size());
2185 llvm::Constant *Init = llvm::ConstantArray::get(VBTableType, Offsets);
2186 GV->setInitializer(Init);
2188 if (RD->hasAttr<DLLImportAttr>())
2189 GV->setLinkage(llvm::GlobalVariable::AvailableExternallyLinkage);
2192 llvm::Value *MicrosoftCXXABI::performThisAdjustment(CodeGenFunction &CGF,
2193 Address This,
2194 const ThisAdjustment &TA) {
2195 if (TA.isEmpty())
2196 return This.getPointer();
2198 This = CGF.Builder.CreateElementBitCast(This, CGF.Int8Ty);
2200 llvm::Value *V;
2201 if (TA.Virtual.isEmpty()) {
2202 V = This.getPointer();
2203 } else {
2204 assert(TA.Virtual.Microsoft.VtordispOffset < 0);
2205 // Adjust the this argument based on the vtordisp value.
2206 Address VtorDispPtr =
2207 CGF.Builder.CreateConstInBoundsByteGEP(This,
2208 CharUnits::fromQuantity(TA.Virtual.Microsoft.VtordispOffset));
2209 VtorDispPtr = CGF.Builder.CreateElementBitCast(VtorDispPtr, CGF.Int32Ty);
2210 llvm::Value *VtorDisp = CGF.Builder.CreateLoad(VtorDispPtr, "vtordisp");
2211 V = CGF.Builder.CreateGEP(This.getElementType(), This.getPointer(),
2212 CGF.Builder.CreateNeg(VtorDisp));
2214 // Unfortunately, having applied the vtordisp means that we no
2215 // longer really have a known alignment for the vbptr step.
2216 // We'll assume the vbptr is pointer-aligned.
2218 if (TA.Virtual.Microsoft.VBPtrOffset) {
2219 // If the final overrider is defined in a virtual base other than the one
2220 // that holds the vfptr, we have to use a vtordispex thunk which looks up
2221 // the vbtable of the derived class.
2222 assert(TA.Virtual.Microsoft.VBPtrOffset > 0);
2223 assert(TA.Virtual.Microsoft.VBOffsetOffset >= 0);
2224 llvm::Value *VBPtr;
2225 llvm::Value *VBaseOffset = GetVBaseOffsetFromVBPtr(
2226 CGF, Address(V, CGF.Int8Ty, CGF.getPointerAlign()),
2227 -TA.Virtual.Microsoft.VBPtrOffset,
2228 TA.Virtual.Microsoft.VBOffsetOffset, &VBPtr);
2229 V = CGF.Builder.CreateInBoundsGEP(CGF.Int8Ty, VBPtr, VBaseOffset);
2233 if (TA.NonVirtual) {
2234 // Non-virtual adjustment might result in a pointer outside the allocated
2235 // object, e.g. if the final overrider class is laid out after the virtual
2236 // base that declares a method in the most derived class.
2237 V = CGF.Builder.CreateConstGEP1_32(CGF.Int8Ty, V, TA.NonVirtual);
2240 // Don't need to bitcast back, the call CodeGen will handle this.
2241 return V;
2244 llvm::Value *
2245 MicrosoftCXXABI::performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
2246 const ReturnAdjustment &RA) {
2247 if (RA.isEmpty())
2248 return Ret.getPointer();
2250 auto OrigTy = Ret.getType();
2251 Ret = CGF.Builder.CreateElementBitCast(Ret, CGF.Int8Ty);
2253 llvm::Value *V = Ret.getPointer();
2254 if (RA.Virtual.Microsoft.VBIndex) {
2255 assert(RA.Virtual.Microsoft.VBIndex > 0);
2256 int32_t IntSize = CGF.getIntSize().getQuantity();
2257 llvm::Value *VBPtr;
2258 llvm::Value *VBaseOffset =
2259 GetVBaseOffsetFromVBPtr(CGF, Ret, RA.Virtual.Microsoft.VBPtrOffset,
2260 IntSize * RA.Virtual.Microsoft.VBIndex, &VBPtr);
2261 V = CGF.Builder.CreateInBoundsGEP(CGF.Int8Ty, VBPtr, VBaseOffset);
2264 if (RA.NonVirtual)
2265 V = CGF.Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, V, RA.NonVirtual);
2267 // Cast back to the original type.
2268 return CGF.Builder.CreateBitCast(V, OrigTy);
2271 bool MicrosoftCXXABI::requiresArrayCookie(const CXXDeleteExpr *expr,
2272 QualType elementType) {
2273 // Microsoft seems to completely ignore the possibility of a
2274 // two-argument usual deallocation function.
2275 return elementType.isDestructedType();
2278 bool MicrosoftCXXABI::requiresArrayCookie(const CXXNewExpr *expr) {
2279 // Microsoft seems to completely ignore the possibility of a
2280 // two-argument usual deallocation function.
2281 return expr->getAllocatedType().isDestructedType();
2284 CharUnits MicrosoftCXXABI::getArrayCookieSizeImpl(QualType type) {
2285 // The array cookie is always a size_t; we then pad that out to the
2286 // alignment of the element type.
2287 ASTContext &Ctx = getContext();
2288 return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()),
2289 Ctx.getTypeAlignInChars(type));
2292 llvm::Value *MicrosoftCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
2293 Address allocPtr,
2294 CharUnits cookieSize) {
2295 Address numElementsPtr =
2296 CGF.Builder.CreateElementBitCast(allocPtr, CGF.SizeTy);
2297 return CGF.Builder.CreateLoad(numElementsPtr);
2300 Address MicrosoftCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
2301 Address newPtr,
2302 llvm::Value *numElements,
2303 const CXXNewExpr *expr,
2304 QualType elementType) {
2305 assert(requiresArrayCookie(expr));
2307 // The size of the cookie.
2308 CharUnits cookieSize = getArrayCookieSizeImpl(elementType);
2310 // Compute an offset to the cookie.
2311 Address cookiePtr = newPtr;
2313 // Write the number of elements into the appropriate slot.
2314 Address numElementsPtr
2315 = CGF.Builder.CreateElementBitCast(cookiePtr, CGF.SizeTy);
2316 CGF.Builder.CreateStore(numElements, numElementsPtr);
2318 // Finally, compute a pointer to the actual data buffer by skipping
2319 // over the cookie completely.
2320 return CGF.Builder.CreateConstInBoundsByteGEP(newPtr, cookieSize);
2323 static void emitGlobalDtorWithTLRegDtor(CodeGenFunction &CGF, const VarDecl &VD,
2324 llvm::FunctionCallee Dtor,
2325 llvm::Constant *Addr) {
2326 // Create a function which calls the destructor.
2327 llvm::Constant *DtorStub = CGF.createAtExitStub(VD, Dtor, Addr);
2329 // extern "C" int __tlregdtor(void (*f)(void));
2330 llvm::FunctionType *TLRegDtorTy = llvm::FunctionType::get(
2331 CGF.IntTy, DtorStub->getType(), /*isVarArg=*/false);
2333 llvm::FunctionCallee TLRegDtor = CGF.CGM.CreateRuntimeFunction(
2334 TLRegDtorTy, "__tlregdtor", llvm::AttributeList(), /*Local=*/true);
2335 if (llvm::Function *TLRegDtorFn =
2336 dyn_cast<llvm::Function>(TLRegDtor.getCallee()))
2337 TLRegDtorFn->setDoesNotThrow();
2339 CGF.EmitNounwindRuntimeCall(TLRegDtor, DtorStub);
2342 void MicrosoftCXXABI::registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
2343 llvm::FunctionCallee Dtor,
2344 llvm::Constant *Addr) {
2345 if (D.isNoDestroy(CGM.getContext()))
2346 return;
2348 if (D.getTLSKind())
2349 return emitGlobalDtorWithTLRegDtor(CGF, D, Dtor, Addr);
2351 // HLSL doesn't support atexit.
2352 if (CGM.getLangOpts().HLSL)
2353 return CGM.AddCXXDtorEntry(Dtor, Addr);
2355 // The default behavior is to use atexit.
2356 CGF.registerGlobalDtorWithAtExit(D, Dtor, Addr);
2359 void MicrosoftCXXABI::EmitThreadLocalInitFuncs(
2360 CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
2361 ArrayRef<llvm::Function *> CXXThreadLocalInits,
2362 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) {
2363 if (CXXThreadLocalInits.empty())
2364 return;
2366 CGM.AppendLinkerOptions(CGM.getTarget().getTriple().getArch() ==
2367 llvm::Triple::x86
2368 ? "/include:___dyn_tls_init@12"
2369 : "/include:__dyn_tls_init");
2371 // This will create a GV in the .CRT$XDU section. It will point to our
2372 // initialization function. The CRT will call all of these function
2373 // pointers at start-up time and, eventually, at thread-creation time.
2374 auto AddToXDU = [&CGM](llvm::Function *InitFunc) {
2375 llvm::GlobalVariable *InitFuncPtr = new llvm::GlobalVariable(
2376 CGM.getModule(), InitFunc->getType(), /*isConstant=*/true,
2377 llvm::GlobalVariable::InternalLinkage, InitFunc,
2378 Twine(InitFunc->getName(), "$initializer$"));
2379 InitFuncPtr->setSection(".CRT$XDU");
2380 // This variable has discardable linkage, we have to add it to @llvm.used to
2381 // ensure it won't get discarded.
2382 CGM.addUsedGlobal(InitFuncPtr);
2383 return InitFuncPtr;
2386 std::vector<llvm::Function *> NonComdatInits;
2387 for (size_t I = 0, E = CXXThreadLocalInitVars.size(); I != E; ++I) {
2388 llvm::GlobalVariable *GV = cast<llvm::GlobalVariable>(
2389 CGM.GetGlobalValue(CGM.getMangledName(CXXThreadLocalInitVars[I])));
2390 llvm::Function *F = CXXThreadLocalInits[I];
2392 // If the GV is already in a comdat group, then we have to join it.
2393 if (llvm::Comdat *C = GV->getComdat())
2394 AddToXDU(F)->setComdat(C);
2395 else
2396 NonComdatInits.push_back(F);
2399 if (!NonComdatInits.empty()) {
2400 llvm::FunctionType *FTy =
2401 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
2402 llvm::Function *InitFunc = CGM.CreateGlobalInitOrCleanUpFunction(
2403 FTy, "__tls_init", CGM.getTypes().arrangeNullaryFunction(),
2404 SourceLocation(), /*TLS=*/true);
2405 CodeGenFunction(CGM).GenerateCXXGlobalInitFunc(InitFunc, NonComdatInits);
2407 AddToXDU(InitFunc);
2411 static llvm::GlobalValue *getTlsGuardVar(CodeGenModule &CGM) {
2412 // __tls_guard comes from the MSVC runtime and reflects
2413 // whether TLS has been initialized for a particular thread.
2414 // It is set from within __dyn_tls_init by the runtime.
2415 // Every library and executable has its own variable.
2416 llvm::Type *VTy = llvm::Type::getInt8Ty(CGM.getLLVMContext());
2417 llvm::Constant *TlsGuardConstant =
2418 CGM.CreateRuntimeVariable(VTy, "__tls_guard");
2419 llvm::GlobalValue *TlsGuard = cast<llvm::GlobalValue>(TlsGuardConstant);
2421 TlsGuard->setThreadLocal(true);
2423 return TlsGuard;
2426 static llvm::FunctionCallee getDynTlsOnDemandInitFn(CodeGenModule &CGM) {
2427 // __dyn_tls_on_demand_init comes from the MSVC runtime and triggers
2428 // dynamic TLS initialization by calling __dyn_tls_init internally.
2429 llvm::FunctionType *FTy =
2430 llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()), {},
2431 /*isVarArg=*/false);
2432 return CGM.CreateRuntimeFunction(
2433 FTy, "__dyn_tls_on_demand_init",
2434 llvm::AttributeList::get(CGM.getLLVMContext(),
2435 llvm::AttributeList::FunctionIndex,
2436 llvm::Attribute::NoUnwind),
2437 /*Local=*/true);
2440 static void emitTlsGuardCheck(CodeGenFunction &CGF, llvm::GlobalValue *TlsGuard,
2441 llvm::BasicBlock *DynInitBB,
2442 llvm::BasicBlock *ContinueBB) {
2443 llvm::LoadInst *TlsGuardValue =
2444 CGF.Builder.CreateLoad(Address(TlsGuard, CGF.Int8Ty, CharUnits::One()));
2445 llvm::Value *CmpResult =
2446 CGF.Builder.CreateICmpEQ(TlsGuardValue, CGF.Builder.getInt8(0));
2447 CGF.Builder.CreateCondBr(CmpResult, DynInitBB, ContinueBB);
2450 static void emitDynamicTlsInitializationCall(CodeGenFunction &CGF,
2451 llvm::GlobalValue *TlsGuard,
2452 llvm::BasicBlock *ContinueBB) {
2453 llvm::FunctionCallee Initializer = getDynTlsOnDemandInitFn(CGF.CGM);
2454 llvm::Function *InitializerFunction =
2455 cast<llvm::Function>(Initializer.getCallee());
2456 llvm::CallInst *CallVal = CGF.Builder.CreateCall(InitializerFunction);
2457 CallVal->setCallingConv(InitializerFunction->getCallingConv());
2459 CGF.Builder.CreateBr(ContinueBB);
2462 static void emitDynamicTlsInitialization(CodeGenFunction &CGF) {
2463 llvm::BasicBlock *DynInitBB =
2464 CGF.createBasicBlock("dyntls.dyn_init", CGF.CurFn);
2465 llvm::BasicBlock *ContinueBB =
2466 CGF.createBasicBlock("dyntls.continue", CGF.CurFn);
2468 llvm::GlobalValue *TlsGuard = getTlsGuardVar(CGF.CGM);
2470 emitTlsGuardCheck(CGF, TlsGuard, DynInitBB, ContinueBB);
2471 CGF.Builder.SetInsertPoint(DynInitBB);
2472 emitDynamicTlsInitializationCall(CGF, TlsGuard, ContinueBB);
2473 CGF.Builder.SetInsertPoint(ContinueBB);
2476 LValue MicrosoftCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
2477 const VarDecl *VD,
2478 QualType LValType) {
2479 // Dynamic TLS initialization works by checking the state of a
2480 // guard variable (__tls_guard) to see whether TLS initialization
2481 // for a thread has happend yet.
2482 // If not, the initialization is triggered on-demand
2483 // by calling __dyn_tls_on_demand_init.
2484 emitDynamicTlsInitialization(CGF);
2486 // Emit the variable just like any regular global variable.
2488 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
2489 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
2491 unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
2492 V = CGF.Builder.CreateBitCast(V, RealVarTy->getPointerTo(AS));
2494 CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
2495 Address Addr(V, RealVarTy, Alignment);
2497 LValue LV = VD->getType()->isReferenceType()
2498 ? CGF.EmitLoadOfReferenceLValue(Addr, VD->getType(),
2499 AlignmentSource::Decl)
2500 : CGF.MakeAddrLValue(Addr, LValType, AlignmentSource::Decl);
2501 return LV;
2504 static ConstantAddress getInitThreadEpochPtr(CodeGenModule &CGM) {
2505 StringRef VarName("_Init_thread_epoch");
2506 CharUnits Align = CGM.getIntAlign();
2507 if (auto *GV = CGM.getModule().getNamedGlobal(VarName))
2508 return ConstantAddress(GV, GV->getValueType(), Align);
2509 auto *GV = new llvm::GlobalVariable(
2510 CGM.getModule(), CGM.IntTy,
2511 /*isConstant=*/false, llvm::GlobalVariable::ExternalLinkage,
2512 /*Initializer=*/nullptr, VarName,
2513 /*InsertBefore=*/nullptr, llvm::GlobalVariable::GeneralDynamicTLSModel);
2514 GV->setAlignment(Align.getAsAlign());
2515 return ConstantAddress(GV, GV->getValueType(), Align);
2518 static llvm::FunctionCallee getInitThreadHeaderFn(CodeGenModule &CGM) {
2519 llvm::FunctionType *FTy =
2520 llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
2521 CGM.IntTy->getPointerTo(), /*isVarArg=*/false);
2522 return CGM.CreateRuntimeFunction(
2523 FTy, "_Init_thread_header",
2524 llvm::AttributeList::get(CGM.getLLVMContext(),
2525 llvm::AttributeList::FunctionIndex,
2526 llvm::Attribute::NoUnwind),
2527 /*Local=*/true);
2530 static llvm::FunctionCallee getInitThreadFooterFn(CodeGenModule &CGM) {
2531 llvm::FunctionType *FTy =
2532 llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
2533 CGM.IntTy->getPointerTo(), /*isVarArg=*/false);
2534 return CGM.CreateRuntimeFunction(
2535 FTy, "_Init_thread_footer",
2536 llvm::AttributeList::get(CGM.getLLVMContext(),
2537 llvm::AttributeList::FunctionIndex,
2538 llvm::Attribute::NoUnwind),
2539 /*Local=*/true);
2542 static llvm::FunctionCallee getInitThreadAbortFn(CodeGenModule &CGM) {
2543 llvm::FunctionType *FTy =
2544 llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
2545 CGM.IntTy->getPointerTo(), /*isVarArg=*/false);
2546 return CGM.CreateRuntimeFunction(
2547 FTy, "_Init_thread_abort",
2548 llvm::AttributeList::get(CGM.getLLVMContext(),
2549 llvm::AttributeList::FunctionIndex,
2550 llvm::Attribute::NoUnwind),
2551 /*Local=*/true);
2554 namespace {
2555 struct ResetGuardBit final : EHScopeStack::Cleanup {
2556 Address Guard;
2557 unsigned GuardNum;
2558 ResetGuardBit(Address Guard, unsigned GuardNum)
2559 : Guard(Guard), GuardNum(GuardNum) {}
2561 void Emit(CodeGenFunction &CGF, Flags flags) override {
2562 // Reset the bit in the mask so that the static variable may be
2563 // reinitialized.
2564 CGBuilderTy &Builder = CGF.Builder;
2565 llvm::LoadInst *LI = Builder.CreateLoad(Guard);
2566 llvm::ConstantInt *Mask =
2567 llvm::ConstantInt::get(CGF.IntTy, ~(1ULL << GuardNum));
2568 Builder.CreateStore(Builder.CreateAnd(LI, Mask), Guard);
2572 struct CallInitThreadAbort final : EHScopeStack::Cleanup {
2573 llvm::Value *Guard;
2574 CallInitThreadAbort(Address Guard) : Guard(Guard.getPointer()) {}
2576 void Emit(CodeGenFunction &CGF, Flags flags) override {
2577 // Calling _Init_thread_abort will reset the guard's state.
2578 CGF.EmitNounwindRuntimeCall(getInitThreadAbortFn(CGF.CGM), Guard);
2583 void MicrosoftCXXABI::EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
2584 llvm::GlobalVariable *GV,
2585 bool PerformInit) {
2586 // MSVC only uses guards for static locals.
2587 if (!D.isStaticLocal()) {
2588 assert(GV->hasWeakLinkage() || GV->hasLinkOnceLinkage());
2589 // GlobalOpt is allowed to discard the initializer, so use linkonce_odr.
2590 llvm::Function *F = CGF.CurFn;
2591 F->setLinkage(llvm::GlobalValue::LinkOnceODRLinkage);
2592 F->setComdat(CGM.getModule().getOrInsertComdat(F->getName()));
2593 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
2594 return;
2597 bool ThreadlocalStatic = D.getTLSKind();
2598 bool ThreadsafeStatic = getContext().getLangOpts().ThreadsafeStatics;
2600 // Thread-safe static variables which aren't thread-specific have a
2601 // per-variable guard.
2602 bool HasPerVariableGuard = ThreadsafeStatic && !ThreadlocalStatic;
2604 CGBuilderTy &Builder = CGF.Builder;
2605 llvm::IntegerType *GuardTy = CGF.Int32Ty;
2606 llvm::ConstantInt *Zero = llvm::ConstantInt::get(GuardTy, 0);
2607 CharUnits GuardAlign = CharUnits::fromQuantity(4);
2609 // Get the guard variable for this function if we have one already.
2610 GuardInfo *GI = nullptr;
2611 if (ThreadlocalStatic)
2612 GI = &ThreadLocalGuardVariableMap[D.getDeclContext()];
2613 else if (!ThreadsafeStatic)
2614 GI = &GuardVariableMap[D.getDeclContext()];
2616 llvm::GlobalVariable *GuardVar = GI ? GI->Guard : nullptr;
2617 unsigned GuardNum;
2618 if (D.isExternallyVisible()) {
2619 // Externally visible variables have to be numbered in Sema to properly
2620 // handle unreachable VarDecls.
2621 GuardNum = getContext().getStaticLocalNumber(&D);
2622 assert(GuardNum > 0);
2623 GuardNum--;
2624 } else if (HasPerVariableGuard) {
2625 GuardNum = ThreadSafeGuardNumMap[D.getDeclContext()]++;
2626 } else {
2627 // Non-externally visible variables are numbered here in CodeGen.
2628 GuardNum = GI->BitIndex++;
2631 if (!HasPerVariableGuard && GuardNum >= 32) {
2632 if (D.isExternallyVisible())
2633 ErrorUnsupportedABI(CGF, "more than 32 guarded initializations");
2634 GuardNum %= 32;
2635 GuardVar = nullptr;
2638 if (!GuardVar) {
2639 // Mangle the name for the guard.
2640 SmallString<256> GuardName;
2642 llvm::raw_svector_ostream Out(GuardName);
2643 if (HasPerVariableGuard)
2644 getMangleContext().mangleThreadSafeStaticGuardVariable(&D, GuardNum,
2645 Out);
2646 else
2647 getMangleContext().mangleStaticGuardVariable(&D, Out);
2650 // Create the guard variable with a zero-initializer. Just absorb linkage,
2651 // visibility and dll storage class from the guarded variable.
2652 GuardVar =
2653 new llvm::GlobalVariable(CGM.getModule(), GuardTy, /*isConstant=*/false,
2654 GV->getLinkage(), Zero, GuardName.str());
2655 GuardVar->setVisibility(GV->getVisibility());
2656 GuardVar->setDLLStorageClass(GV->getDLLStorageClass());
2657 GuardVar->setAlignment(GuardAlign.getAsAlign());
2658 if (GuardVar->isWeakForLinker())
2659 GuardVar->setComdat(
2660 CGM.getModule().getOrInsertComdat(GuardVar->getName()));
2661 if (D.getTLSKind())
2662 CGM.setTLSMode(GuardVar, D);
2663 if (GI && !HasPerVariableGuard)
2664 GI->Guard = GuardVar;
2667 ConstantAddress GuardAddr(GuardVar, GuardTy, GuardAlign);
2669 assert(GuardVar->getLinkage() == GV->getLinkage() &&
2670 "static local from the same function had different linkage");
2672 if (!HasPerVariableGuard) {
2673 // Pseudo code for the test:
2674 // if (!(GuardVar & MyGuardBit)) {
2675 // GuardVar |= MyGuardBit;
2676 // ... initialize the object ...;
2677 // }
2679 // Test our bit from the guard variable.
2680 llvm::ConstantInt *Bit = llvm::ConstantInt::get(GuardTy, 1ULL << GuardNum);
2681 llvm::LoadInst *LI = Builder.CreateLoad(GuardAddr);
2682 llvm::Value *NeedsInit =
2683 Builder.CreateICmpEQ(Builder.CreateAnd(LI, Bit), Zero);
2684 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
2685 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2686 CGF.EmitCXXGuardedInitBranch(NeedsInit, InitBlock, EndBlock,
2687 CodeGenFunction::GuardKind::VariableGuard, &D);
2689 // Set our bit in the guard variable and emit the initializer and add a global
2690 // destructor if appropriate.
2691 CGF.EmitBlock(InitBlock);
2692 Builder.CreateStore(Builder.CreateOr(LI, Bit), GuardAddr);
2693 CGF.EHStack.pushCleanup<ResetGuardBit>(EHCleanup, GuardAddr, GuardNum);
2694 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
2695 CGF.PopCleanupBlock();
2696 Builder.CreateBr(EndBlock);
2698 // Continue.
2699 CGF.EmitBlock(EndBlock);
2700 } else {
2701 // Pseudo code for the test:
2702 // if (TSS > _Init_thread_epoch) {
2703 // _Init_thread_header(&TSS);
2704 // if (TSS == -1) {
2705 // ... initialize the object ...;
2706 // _Init_thread_footer(&TSS);
2707 // }
2708 // }
2710 // The algorithm is almost identical to what can be found in the appendix
2711 // found in N2325.
2713 // This BasicBLock determines whether or not we have any work to do.
2714 llvm::LoadInst *FirstGuardLoad = Builder.CreateLoad(GuardAddr);
2715 FirstGuardLoad->setOrdering(llvm::AtomicOrdering::Unordered);
2716 llvm::LoadInst *InitThreadEpoch =
2717 Builder.CreateLoad(getInitThreadEpochPtr(CGM));
2718 llvm::Value *IsUninitialized =
2719 Builder.CreateICmpSGT(FirstGuardLoad, InitThreadEpoch);
2720 llvm::BasicBlock *AttemptInitBlock = CGF.createBasicBlock("init.attempt");
2721 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2722 CGF.EmitCXXGuardedInitBranch(IsUninitialized, AttemptInitBlock, EndBlock,
2723 CodeGenFunction::GuardKind::VariableGuard, &D);
2725 // This BasicBlock attempts to determine whether or not this thread is
2726 // responsible for doing the initialization.
2727 CGF.EmitBlock(AttemptInitBlock);
2728 CGF.EmitNounwindRuntimeCall(getInitThreadHeaderFn(CGM),
2729 GuardAddr.getPointer());
2730 llvm::LoadInst *SecondGuardLoad = Builder.CreateLoad(GuardAddr);
2731 SecondGuardLoad->setOrdering(llvm::AtomicOrdering::Unordered);
2732 llvm::Value *ShouldDoInit =
2733 Builder.CreateICmpEQ(SecondGuardLoad, getAllOnesInt());
2734 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
2735 Builder.CreateCondBr(ShouldDoInit, InitBlock, EndBlock);
2737 // Ok, we ended up getting selected as the initializing thread.
2738 CGF.EmitBlock(InitBlock);
2739 CGF.EHStack.pushCleanup<CallInitThreadAbort>(EHCleanup, GuardAddr);
2740 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
2741 CGF.PopCleanupBlock();
2742 CGF.EmitNounwindRuntimeCall(getInitThreadFooterFn(CGM),
2743 GuardAddr.getPointer());
2744 Builder.CreateBr(EndBlock);
2746 CGF.EmitBlock(EndBlock);
2750 bool MicrosoftCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
2751 // Null-ness for function memptrs only depends on the first field, which is
2752 // the function pointer. The rest don't matter, so we can zero initialize.
2753 if (MPT->isMemberFunctionPointer())
2754 return true;
2756 // The virtual base adjustment field is always -1 for null, so if we have one
2757 // we can't zero initialize. The field offset is sometimes also -1 if 0 is a
2758 // valid field offset.
2759 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2760 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
2761 return (!inheritanceModelHasVBTableOffsetField(Inheritance) &&
2762 RD->nullFieldOffsetIsZero());
2765 llvm::Type *
2766 MicrosoftCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
2767 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2768 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
2769 llvm::SmallVector<llvm::Type *, 4> fields;
2770 if (MPT->isMemberFunctionPointer())
2771 fields.push_back(CGM.VoidPtrTy); // FunctionPointerOrVirtualThunk
2772 else
2773 fields.push_back(CGM.IntTy); // FieldOffset
2775 if (inheritanceModelHasNVOffsetField(MPT->isMemberFunctionPointer(),
2776 Inheritance))
2777 fields.push_back(CGM.IntTy);
2778 if (inheritanceModelHasVBPtrOffsetField(Inheritance))
2779 fields.push_back(CGM.IntTy);
2780 if (inheritanceModelHasVBTableOffsetField(Inheritance))
2781 fields.push_back(CGM.IntTy); // VirtualBaseAdjustmentOffset
2783 if (fields.size() == 1)
2784 return fields[0];
2785 return llvm::StructType::get(CGM.getLLVMContext(), fields);
2788 void MicrosoftCXXABI::
2789 GetNullMemberPointerFields(const MemberPointerType *MPT,
2790 llvm::SmallVectorImpl<llvm::Constant *> &fields) {
2791 assert(fields.empty());
2792 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2793 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
2794 if (MPT->isMemberFunctionPointer()) {
2795 // FunctionPointerOrVirtualThunk
2796 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
2797 } else {
2798 if (RD->nullFieldOffsetIsZero())
2799 fields.push_back(getZeroInt()); // FieldOffset
2800 else
2801 fields.push_back(getAllOnesInt()); // FieldOffset
2804 if (inheritanceModelHasNVOffsetField(MPT->isMemberFunctionPointer(),
2805 Inheritance))
2806 fields.push_back(getZeroInt());
2807 if (inheritanceModelHasVBPtrOffsetField(Inheritance))
2808 fields.push_back(getZeroInt());
2809 if (inheritanceModelHasVBTableOffsetField(Inheritance))
2810 fields.push_back(getAllOnesInt());
2813 llvm::Constant *
2814 MicrosoftCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
2815 llvm::SmallVector<llvm::Constant *, 4> fields;
2816 GetNullMemberPointerFields(MPT, fields);
2817 if (fields.size() == 1)
2818 return fields[0];
2819 llvm::Constant *Res = llvm::ConstantStruct::getAnon(fields);
2820 assert(Res->getType() == ConvertMemberPointerType(MPT));
2821 return Res;
2824 llvm::Constant *
2825 MicrosoftCXXABI::EmitFullMemberPointer(llvm::Constant *FirstField,
2826 bool IsMemberFunction,
2827 const CXXRecordDecl *RD,
2828 CharUnits NonVirtualBaseAdjustment,
2829 unsigned VBTableIndex) {
2830 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
2832 // Single inheritance class member pointer are represented as scalars instead
2833 // of aggregates.
2834 if (inheritanceModelHasOnlyOneField(IsMemberFunction, Inheritance))
2835 return FirstField;
2837 llvm::SmallVector<llvm::Constant *, 4> fields;
2838 fields.push_back(FirstField);
2840 if (inheritanceModelHasNVOffsetField(IsMemberFunction, Inheritance))
2841 fields.push_back(llvm::ConstantInt::get(
2842 CGM.IntTy, NonVirtualBaseAdjustment.getQuantity()));
2844 if (inheritanceModelHasVBPtrOffsetField(Inheritance)) {
2845 CharUnits Offs = CharUnits::Zero();
2846 if (VBTableIndex)
2847 Offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
2848 fields.push_back(llvm::ConstantInt::get(CGM.IntTy, Offs.getQuantity()));
2851 // The rest of the fields are adjusted by conversions to a more derived class.
2852 if (inheritanceModelHasVBTableOffsetField(Inheritance))
2853 fields.push_back(llvm::ConstantInt::get(CGM.IntTy, VBTableIndex));
2855 return llvm::ConstantStruct::getAnon(fields);
2858 llvm::Constant *
2859 MicrosoftCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
2860 CharUnits offset) {
2861 return EmitMemberDataPointer(MPT->getMostRecentCXXRecordDecl(), offset);
2864 llvm::Constant *MicrosoftCXXABI::EmitMemberDataPointer(const CXXRecordDecl *RD,
2865 CharUnits offset) {
2866 if (RD->getMSInheritanceModel() ==
2867 MSInheritanceModel::Virtual)
2868 offset -= getContext().getOffsetOfBaseWithVBPtr(RD);
2869 llvm::Constant *FirstField =
2870 llvm::ConstantInt::get(CGM.IntTy, offset.getQuantity());
2871 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/false, RD,
2872 CharUnits::Zero(), /*VBTableIndex=*/0);
2875 llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const APValue &MP,
2876 QualType MPType) {
2877 const MemberPointerType *DstTy = MPType->castAs<MemberPointerType>();
2878 const ValueDecl *MPD = MP.getMemberPointerDecl();
2879 if (!MPD)
2880 return EmitNullMemberPointer(DstTy);
2882 ASTContext &Ctx = getContext();
2883 ArrayRef<const CXXRecordDecl *> MemberPointerPath = MP.getMemberPointerPath();
2885 llvm::Constant *C;
2886 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD)) {
2887 C = EmitMemberFunctionPointer(MD);
2888 } else {
2889 // For a pointer to data member, start off with the offset of the field in
2890 // the class in which it was declared, and convert from there if necessary.
2891 // For indirect field decls, get the outermost anonymous field and use the
2892 // parent class.
2893 CharUnits FieldOffset = Ctx.toCharUnitsFromBits(Ctx.getFieldOffset(MPD));
2894 const FieldDecl *FD = dyn_cast<FieldDecl>(MPD);
2895 if (!FD)
2896 FD = cast<FieldDecl>(*cast<IndirectFieldDecl>(MPD)->chain_begin());
2897 const CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getParent());
2898 RD = RD->getMostRecentNonInjectedDecl();
2899 C = EmitMemberDataPointer(RD, FieldOffset);
2902 if (!MemberPointerPath.empty()) {
2903 const CXXRecordDecl *SrcRD = cast<CXXRecordDecl>(MPD->getDeclContext());
2904 const Type *SrcRecTy = Ctx.getTypeDeclType(SrcRD).getTypePtr();
2905 const MemberPointerType *SrcTy =
2906 Ctx.getMemberPointerType(DstTy->getPointeeType(), SrcRecTy)
2907 ->castAs<MemberPointerType>();
2909 bool DerivedMember = MP.isMemberPointerToDerivedMember();
2910 SmallVector<const CXXBaseSpecifier *, 4> DerivedToBasePath;
2911 const CXXRecordDecl *PrevRD = SrcRD;
2912 for (const CXXRecordDecl *PathElem : MemberPointerPath) {
2913 const CXXRecordDecl *Base = nullptr;
2914 const CXXRecordDecl *Derived = nullptr;
2915 if (DerivedMember) {
2916 Base = PathElem;
2917 Derived = PrevRD;
2918 } else {
2919 Base = PrevRD;
2920 Derived = PathElem;
2922 for (const CXXBaseSpecifier &BS : Derived->bases())
2923 if (BS.getType()->getAsCXXRecordDecl()->getCanonicalDecl() ==
2924 Base->getCanonicalDecl())
2925 DerivedToBasePath.push_back(&BS);
2926 PrevRD = PathElem;
2928 assert(DerivedToBasePath.size() == MemberPointerPath.size());
2930 CastKind CK = DerivedMember ? CK_DerivedToBaseMemberPointer
2931 : CK_BaseToDerivedMemberPointer;
2932 C = EmitMemberPointerConversion(SrcTy, DstTy, CK, DerivedToBasePath.begin(),
2933 DerivedToBasePath.end(), C);
2935 return C;
2938 llvm::Constant *
2939 MicrosoftCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) {
2940 assert(MD->isInstance() && "Member function must not be static!");
2942 CharUnits NonVirtualBaseAdjustment = CharUnits::Zero();
2943 const CXXRecordDecl *RD = MD->getParent()->getMostRecentNonInjectedDecl();
2944 CodeGenTypes &Types = CGM.getTypes();
2946 unsigned VBTableIndex = 0;
2947 llvm::Constant *FirstField;
2948 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
2949 if (!MD->isVirtual()) {
2950 llvm::Type *Ty;
2951 // Check whether the function has a computable LLVM signature.
2952 if (Types.isFuncTypeConvertible(FPT)) {
2953 // The function has a computable LLVM signature; use the correct type.
2954 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
2955 } else {
2956 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
2957 // function type is incomplete.
2958 Ty = CGM.PtrDiffTy;
2960 FirstField = CGM.GetAddrOfFunction(MD, Ty);
2961 } else {
2962 auto &VTableContext = CGM.getMicrosoftVTableContext();
2963 MethodVFTableLocation ML = VTableContext.getMethodVFTableLocation(MD);
2964 FirstField = EmitVirtualMemPtrThunk(MD, ML);
2965 // Include the vfptr adjustment if the method is in a non-primary vftable.
2966 NonVirtualBaseAdjustment += ML.VFPtrOffset;
2967 if (ML.VBase)
2968 VBTableIndex = VTableContext.getVBTableIndex(RD, ML.VBase) * 4;
2971 if (VBTableIndex == 0 &&
2972 RD->getMSInheritanceModel() ==
2973 MSInheritanceModel::Virtual)
2974 NonVirtualBaseAdjustment -= getContext().getOffsetOfBaseWithVBPtr(RD);
2976 // The rest of the fields are common with data member pointers.
2977 FirstField = llvm::ConstantExpr::getBitCast(FirstField, CGM.VoidPtrTy);
2978 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/true, RD,
2979 NonVirtualBaseAdjustment, VBTableIndex);
2982 /// Member pointers are the same if they're either bitwise identical *or* both
2983 /// null. Null-ness for function members is determined by the first field,
2984 /// while for data member pointers we must compare all fields.
2985 llvm::Value *
2986 MicrosoftCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
2987 llvm::Value *L,
2988 llvm::Value *R,
2989 const MemberPointerType *MPT,
2990 bool Inequality) {
2991 CGBuilderTy &Builder = CGF.Builder;
2993 // Handle != comparisons by switching the sense of all boolean operations.
2994 llvm::ICmpInst::Predicate Eq;
2995 llvm::Instruction::BinaryOps And, Or;
2996 if (Inequality) {
2997 Eq = llvm::ICmpInst::ICMP_NE;
2998 And = llvm::Instruction::Or;
2999 Or = llvm::Instruction::And;
3000 } else {
3001 Eq = llvm::ICmpInst::ICMP_EQ;
3002 And = llvm::Instruction::And;
3003 Or = llvm::Instruction::Or;
3006 // If this is a single field member pointer (single inheritance), this is a
3007 // single icmp.
3008 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
3009 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
3010 if (inheritanceModelHasOnlyOneField(MPT->isMemberFunctionPointer(),
3011 Inheritance))
3012 return Builder.CreateICmp(Eq, L, R);
3014 // Compare the first field.
3015 llvm::Value *L0 = Builder.CreateExtractValue(L, 0, "lhs.0");
3016 llvm::Value *R0 = Builder.CreateExtractValue(R, 0, "rhs.0");
3017 llvm::Value *Cmp0 = Builder.CreateICmp(Eq, L0, R0, "memptr.cmp.first");
3019 // Compare everything other than the first field.
3020 llvm::Value *Res = nullptr;
3021 llvm::StructType *LType = cast<llvm::StructType>(L->getType());
3022 for (unsigned I = 1, E = LType->getNumElements(); I != E; ++I) {
3023 llvm::Value *LF = Builder.CreateExtractValue(L, I);
3024 llvm::Value *RF = Builder.CreateExtractValue(R, I);
3025 llvm::Value *Cmp = Builder.CreateICmp(Eq, LF, RF, "memptr.cmp.rest");
3026 if (Res)
3027 Res = Builder.CreateBinOp(And, Res, Cmp);
3028 else
3029 Res = Cmp;
3032 // Check if the first field is 0 if this is a function pointer.
3033 if (MPT->isMemberFunctionPointer()) {
3034 // (l1 == r1 && ...) || l0 == 0
3035 llvm::Value *Zero = llvm::Constant::getNullValue(L0->getType());
3036 llvm::Value *IsZero = Builder.CreateICmp(Eq, L0, Zero, "memptr.cmp.iszero");
3037 Res = Builder.CreateBinOp(Or, Res, IsZero);
3040 // Combine the comparison of the first field, which must always be true for
3041 // this comparison to succeeed.
3042 return Builder.CreateBinOp(And, Res, Cmp0, "memptr.cmp");
3045 llvm::Value *
3046 MicrosoftCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
3047 llvm::Value *MemPtr,
3048 const MemberPointerType *MPT) {
3049 CGBuilderTy &Builder = CGF.Builder;
3050 llvm::SmallVector<llvm::Constant *, 4> fields;
3051 // We only need one field for member functions.
3052 if (MPT->isMemberFunctionPointer())
3053 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
3054 else
3055 GetNullMemberPointerFields(MPT, fields);
3056 assert(!fields.empty());
3057 llvm::Value *FirstField = MemPtr;
3058 if (MemPtr->getType()->isStructTy())
3059 FirstField = Builder.CreateExtractValue(MemPtr, 0);
3060 llvm::Value *Res = Builder.CreateICmpNE(FirstField, fields[0], "memptr.cmp0");
3062 // For function member pointers, we only need to test the function pointer
3063 // field. The other fields if any can be garbage.
3064 if (MPT->isMemberFunctionPointer())
3065 return Res;
3067 // Otherwise, emit a series of compares and combine the results.
3068 for (int I = 1, E = fields.size(); I < E; ++I) {
3069 llvm::Value *Field = Builder.CreateExtractValue(MemPtr, I);
3070 llvm::Value *Next = Builder.CreateICmpNE(Field, fields[I], "memptr.cmp");
3071 Res = Builder.CreateOr(Res, Next, "memptr.tobool");
3073 return Res;
3076 bool MicrosoftCXXABI::MemberPointerConstantIsNull(const MemberPointerType *MPT,
3077 llvm::Constant *Val) {
3078 // Function pointers are null if the pointer in the first field is null.
3079 if (MPT->isMemberFunctionPointer()) {
3080 llvm::Constant *FirstField = Val->getType()->isStructTy() ?
3081 Val->getAggregateElement(0U) : Val;
3082 return FirstField->isNullValue();
3085 // If it's not a function pointer and it's zero initializable, we can easily
3086 // check zero.
3087 if (isZeroInitializable(MPT) && Val->isNullValue())
3088 return true;
3090 // Otherwise, break down all the fields for comparison. Hopefully these
3091 // little Constants are reused, while a big null struct might not be.
3092 llvm::SmallVector<llvm::Constant *, 4> Fields;
3093 GetNullMemberPointerFields(MPT, Fields);
3094 if (Fields.size() == 1) {
3095 assert(Val->getType()->isIntegerTy());
3096 return Val == Fields[0];
3099 unsigned I, E;
3100 for (I = 0, E = Fields.size(); I != E; ++I) {
3101 if (Val->getAggregateElement(I) != Fields[I])
3102 break;
3104 return I == E;
3107 llvm::Value *
3108 MicrosoftCXXABI::GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
3109 Address This,
3110 llvm::Value *VBPtrOffset,
3111 llvm::Value *VBTableOffset,
3112 llvm::Value **VBPtrOut) {
3113 CGBuilderTy &Builder = CGF.Builder;
3114 // Load the vbtable pointer from the vbptr in the instance.
3115 This = Builder.CreateElementBitCast(This, CGM.Int8Ty);
3116 llvm::Value *VBPtr = Builder.CreateInBoundsGEP(
3117 This.getElementType(), This.getPointer(), VBPtrOffset, "vbptr");
3118 if (VBPtrOut) *VBPtrOut = VBPtr;
3119 VBPtr = Builder.CreateBitCast(VBPtr,
3120 CGM.Int32Ty->getPointerTo(0)->getPointerTo(This.getAddressSpace()));
3122 CharUnits VBPtrAlign;
3123 if (auto CI = dyn_cast<llvm::ConstantInt>(VBPtrOffset)) {
3124 VBPtrAlign = This.getAlignment().alignmentAtOffset(
3125 CharUnits::fromQuantity(CI->getSExtValue()));
3126 } else {
3127 VBPtrAlign = CGF.getPointerAlign();
3130 llvm::Value *VBTable = Builder.CreateAlignedLoad(
3131 CGM.Int32Ty->getPointerTo(0), VBPtr, VBPtrAlign, "vbtable");
3133 // Translate from byte offset to table index. It improves analyzability.
3134 llvm::Value *VBTableIndex = Builder.CreateAShr(
3135 VBTableOffset, llvm::ConstantInt::get(VBTableOffset->getType(), 2),
3136 "vbtindex", /*isExact=*/true);
3138 // Load an i32 offset from the vb-table.
3139 llvm::Value *VBaseOffs =
3140 Builder.CreateInBoundsGEP(CGM.Int32Ty, VBTable, VBTableIndex);
3141 VBaseOffs = Builder.CreateBitCast(VBaseOffs, CGM.Int32Ty->getPointerTo(0));
3142 return Builder.CreateAlignedLoad(CGM.Int32Ty, VBaseOffs,
3143 CharUnits::fromQuantity(4), "vbase_offs");
3146 // Returns an adjusted base cast to i8*, since we do more address arithmetic on
3147 // it.
3148 llvm::Value *MicrosoftCXXABI::AdjustVirtualBase(
3149 CodeGenFunction &CGF, const Expr *E, const CXXRecordDecl *RD,
3150 Address Base, llvm::Value *VBTableOffset, llvm::Value *VBPtrOffset) {
3151 CGBuilderTy &Builder = CGF.Builder;
3152 Base = Builder.CreateElementBitCast(Base, CGM.Int8Ty);
3153 llvm::BasicBlock *OriginalBB = nullptr;
3154 llvm::BasicBlock *SkipAdjustBB = nullptr;
3155 llvm::BasicBlock *VBaseAdjustBB = nullptr;
3157 // In the unspecified inheritance model, there might not be a vbtable at all,
3158 // in which case we need to skip the virtual base lookup. If there is a
3159 // vbtable, the first entry is a no-op entry that gives back the original
3160 // base, so look for a virtual base adjustment offset of zero.
3161 if (VBPtrOffset) {
3162 OriginalBB = Builder.GetInsertBlock();
3163 VBaseAdjustBB = CGF.createBasicBlock("memptr.vadjust");
3164 SkipAdjustBB = CGF.createBasicBlock("memptr.skip_vadjust");
3165 llvm::Value *IsVirtual =
3166 Builder.CreateICmpNE(VBTableOffset, getZeroInt(),
3167 "memptr.is_vbase");
3168 Builder.CreateCondBr(IsVirtual, VBaseAdjustBB, SkipAdjustBB);
3169 CGF.EmitBlock(VBaseAdjustBB);
3172 // If we weren't given a dynamic vbptr offset, RD should be complete and we'll
3173 // know the vbptr offset.
3174 if (!VBPtrOffset) {
3175 CharUnits offs = CharUnits::Zero();
3176 if (!RD->hasDefinition()) {
3177 DiagnosticsEngine &Diags = CGF.CGM.getDiags();
3178 unsigned DiagID = Diags.getCustomDiagID(
3179 DiagnosticsEngine::Error,
3180 "member pointer representation requires a "
3181 "complete class type for %0 to perform this expression");
3182 Diags.Report(E->getExprLoc(), DiagID) << RD << E->getSourceRange();
3183 } else if (RD->getNumVBases())
3184 offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
3185 VBPtrOffset = llvm::ConstantInt::get(CGM.IntTy, offs.getQuantity());
3187 llvm::Value *VBPtr = nullptr;
3188 llvm::Value *VBaseOffs =
3189 GetVBaseOffsetFromVBPtr(CGF, Base, VBPtrOffset, VBTableOffset, &VBPtr);
3190 llvm::Value *AdjustedBase =
3191 Builder.CreateInBoundsGEP(CGM.Int8Ty, VBPtr, VBaseOffs);
3193 // Merge control flow with the case where we didn't have to adjust.
3194 if (VBaseAdjustBB) {
3195 Builder.CreateBr(SkipAdjustBB);
3196 CGF.EmitBlock(SkipAdjustBB);
3197 llvm::PHINode *Phi = Builder.CreatePHI(CGM.Int8PtrTy, 2, "memptr.base");
3198 Phi->addIncoming(Base.getPointer(), OriginalBB);
3199 Phi->addIncoming(AdjustedBase, VBaseAdjustBB);
3200 return Phi;
3202 return AdjustedBase;
3205 llvm::Value *MicrosoftCXXABI::EmitMemberDataPointerAddress(
3206 CodeGenFunction &CGF, const Expr *E, Address Base, llvm::Value *MemPtr,
3207 const MemberPointerType *MPT) {
3208 assert(MPT->isMemberDataPointer());
3209 unsigned AS = Base.getAddressSpace();
3210 llvm::Type *PType =
3211 CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
3212 CGBuilderTy &Builder = CGF.Builder;
3213 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
3214 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
3216 // Extract the fields we need, regardless of model. We'll apply them if we
3217 // have them.
3218 llvm::Value *FieldOffset = MemPtr;
3219 llvm::Value *VirtualBaseAdjustmentOffset = nullptr;
3220 llvm::Value *VBPtrOffset = nullptr;
3221 if (MemPtr->getType()->isStructTy()) {
3222 // We need to extract values.
3223 unsigned I = 0;
3224 FieldOffset = Builder.CreateExtractValue(MemPtr, I++);
3225 if (inheritanceModelHasVBPtrOffsetField(Inheritance))
3226 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
3227 if (inheritanceModelHasVBTableOffsetField(Inheritance))
3228 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
3231 llvm::Value *Addr;
3232 if (VirtualBaseAdjustmentOffset) {
3233 Addr = AdjustVirtualBase(CGF, E, RD, Base, VirtualBaseAdjustmentOffset,
3234 VBPtrOffset);
3235 } else {
3236 Addr = Base.getPointer();
3239 // Cast to char*.
3240 Addr = Builder.CreateBitCast(Addr, CGF.Int8Ty->getPointerTo(AS));
3242 // Apply the offset, which we assume is non-null.
3243 Addr = Builder.CreateInBoundsGEP(CGF.Int8Ty, Addr, FieldOffset,
3244 "memptr.offset");
3246 // Cast the address to the appropriate pointer type, adopting the address
3247 // space of the base pointer.
3248 return Builder.CreateBitCast(Addr, PType);
3251 llvm::Value *
3252 MicrosoftCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
3253 const CastExpr *E,
3254 llvm::Value *Src) {
3255 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
3256 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
3257 E->getCastKind() == CK_ReinterpretMemberPointer);
3259 // Use constant emission if we can.
3260 if (isa<llvm::Constant>(Src))
3261 return EmitMemberPointerConversion(E, cast<llvm::Constant>(Src));
3263 // We may be adding or dropping fields from the member pointer, so we need
3264 // both types and the inheritance models of both records.
3265 const MemberPointerType *SrcTy =
3266 E->getSubExpr()->getType()->castAs<MemberPointerType>();
3267 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
3268 bool IsFunc = SrcTy->isMemberFunctionPointer();
3270 // If the classes use the same null representation, reinterpret_cast is a nop.
3271 bool IsReinterpret = E->getCastKind() == CK_ReinterpretMemberPointer;
3272 if (IsReinterpret && IsFunc)
3273 return Src;
3275 CXXRecordDecl *SrcRD = SrcTy->getMostRecentCXXRecordDecl();
3276 CXXRecordDecl *DstRD = DstTy->getMostRecentCXXRecordDecl();
3277 if (IsReinterpret &&
3278 SrcRD->nullFieldOffsetIsZero() == DstRD->nullFieldOffsetIsZero())
3279 return Src;
3281 CGBuilderTy &Builder = CGF.Builder;
3283 // Branch past the conversion if Src is null.
3284 llvm::Value *IsNotNull = EmitMemberPointerIsNotNull(CGF, Src, SrcTy);
3285 llvm::Constant *DstNull = EmitNullMemberPointer(DstTy);
3287 // C++ 5.2.10p9: The null member pointer value is converted to the null member
3288 // pointer value of the destination type.
3289 if (IsReinterpret) {
3290 // For reinterpret casts, sema ensures that src and dst are both functions
3291 // or data and have the same size, which means the LLVM types should match.
3292 assert(Src->getType() == DstNull->getType());
3293 return Builder.CreateSelect(IsNotNull, Src, DstNull);
3296 llvm::BasicBlock *OriginalBB = Builder.GetInsertBlock();
3297 llvm::BasicBlock *ConvertBB = CGF.createBasicBlock("memptr.convert");
3298 llvm::BasicBlock *ContinueBB = CGF.createBasicBlock("memptr.converted");
3299 Builder.CreateCondBr(IsNotNull, ConvertBB, ContinueBB);
3300 CGF.EmitBlock(ConvertBB);
3302 llvm::Value *Dst = EmitNonNullMemberPointerConversion(
3303 SrcTy, DstTy, E->getCastKind(), E->path_begin(), E->path_end(), Src,
3304 Builder);
3306 Builder.CreateBr(ContinueBB);
3308 // In the continuation, choose between DstNull and Dst.
3309 CGF.EmitBlock(ContinueBB);
3310 llvm::PHINode *Phi = Builder.CreatePHI(DstNull->getType(), 2, "memptr.converted");
3311 Phi->addIncoming(DstNull, OriginalBB);
3312 Phi->addIncoming(Dst, ConvertBB);
3313 return Phi;
3316 llvm::Value *MicrosoftCXXABI::EmitNonNullMemberPointerConversion(
3317 const MemberPointerType *SrcTy, const MemberPointerType *DstTy, CastKind CK,
3318 CastExpr::path_const_iterator PathBegin,
3319 CastExpr::path_const_iterator PathEnd, llvm::Value *Src,
3320 CGBuilderTy &Builder) {
3321 const CXXRecordDecl *SrcRD = SrcTy->getMostRecentCXXRecordDecl();
3322 const CXXRecordDecl *DstRD = DstTy->getMostRecentCXXRecordDecl();
3323 MSInheritanceModel SrcInheritance = SrcRD->getMSInheritanceModel();
3324 MSInheritanceModel DstInheritance = DstRD->getMSInheritanceModel();
3325 bool IsFunc = SrcTy->isMemberFunctionPointer();
3326 bool IsConstant = isa<llvm::Constant>(Src);
3328 // Decompose src.
3329 llvm::Value *FirstField = Src;
3330 llvm::Value *NonVirtualBaseAdjustment = getZeroInt();
3331 llvm::Value *VirtualBaseAdjustmentOffset = getZeroInt();
3332 llvm::Value *VBPtrOffset = getZeroInt();
3333 if (!inheritanceModelHasOnlyOneField(IsFunc, SrcInheritance)) {
3334 // We need to extract values.
3335 unsigned I = 0;
3336 FirstField = Builder.CreateExtractValue(Src, I++);
3337 if (inheritanceModelHasNVOffsetField(IsFunc, SrcInheritance))
3338 NonVirtualBaseAdjustment = Builder.CreateExtractValue(Src, I++);
3339 if (inheritanceModelHasVBPtrOffsetField(SrcInheritance))
3340 VBPtrOffset = Builder.CreateExtractValue(Src, I++);
3341 if (inheritanceModelHasVBTableOffsetField(SrcInheritance))
3342 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(Src, I++);
3345 bool IsDerivedToBase = (CK == CK_DerivedToBaseMemberPointer);
3346 const MemberPointerType *DerivedTy = IsDerivedToBase ? SrcTy : DstTy;
3347 const CXXRecordDecl *DerivedClass = DerivedTy->getMostRecentCXXRecordDecl();
3349 // For data pointers, we adjust the field offset directly. For functions, we
3350 // have a separate field.
3351 llvm::Value *&NVAdjustField = IsFunc ? NonVirtualBaseAdjustment : FirstField;
3353 // The virtual inheritance model has a quirk: the virtual base table is always
3354 // referenced when dereferencing a member pointer even if the member pointer
3355 // is non-virtual. This is accounted for by adjusting the non-virtual offset
3356 // to point backwards to the top of the MDC from the first VBase. Undo this
3357 // adjustment to normalize the member pointer.
3358 llvm::Value *SrcVBIndexEqZero =
3359 Builder.CreateICmpEQ(VirtualBaseAdjustmentOffset, getZeroInt());
3360 if (SrcInheritance == MSInheritanceModel::Virtual) {
3361 if (int64_t SrcOffsetToFirstVBase =
3362 getContext().getOffsetOfBaseWithVBPtr(SrcRD).getQuantity()) {
3363 llvm::Value *UndoSrcAdjustment = Builder.CreateSelect(
3364 SrcVBIndexEqZero,
3365 llvm::ConstantInt::get(CGM.IntTy, SrcOffsetToFirstVBase),
3366 getZeroInt());
3367 NVAdjustField = Builder.CreateNSWAdd(NVAdjustField, UndoSrcAdjustment);
3371 // A non-zero vbindex implies that we are dealing with a source member in a
3372 // floating virtual base in addition to some non-virtual offset. If the
3373 // vbindex is zero, we are dealing with a source that exists in a non-virtual,
3374 // fixed, base. The difference between these two cases is that the vbindex +
3375 // nvoffset *always* point to the member regardless of what context they are
3376 // evaluated in so long as the vbindex is adjusted. A member inside a fixed
3377 // base requires explicit nv adjustment.
3378 llvm::Constant *BaseClassOffset = llvm::ConstantInt::get(
3379 CGM.IntTy,
3380 CGM.computeNonVirtualBaseClassOffset(DerivedClass, PathBegin, PathEnd)
3381 .getQuantity());
3383 llvm::Value *NVDisp;
3384 if (IsDerivedToBase)
3385 NVDisp = Builder.CreateNSWSub(NVAdjustField, BaseClassOffset, "adj");
3386 else
3387 NVDisp = Builder.CreateNSWAdd(NVAdjustField, BaseClassOffset, "adj");
3389 NVAdjustField = Builder.CreateSelect(SrcVBIndexEqZero, NVDisp, getZeroInt());
3391 // Update the vbindex to an appropriate value in the destination because
3392 // SrcRD's vbtable might not be a strict prefix of the one in DstRD.
3393 llvm::Value *DstVBIndexEqZero = SrcVBIndexEqZero;
3394 if (inheritanceModelHasVBTableOffsetField(DstInheritance) &&
3395 inheritanceModelHasVBTableOffsetField(SrcInheritance)) {
3396 if (llvm::GlobalVariable *VDispMap =
3397 getAddrOfVirtualDisplacementMap(SrcRD, DstRD)) {
3398 llvm::Value *VBIndex = Builder.CreateExactUDiv(
3399 VirtualBaseAdjustmentOffset, llvm::ConstantInt::get(CGM.IntTy, 4));
3400 if (IsConstant) {
3401 llvm::Constant *Mapping = VDispMap->getInitializer();
3402 VirtualBaseAdjustmentOffset =
3403 Mapping->getAggregateElement(cast<llvm::Constant>(VBIndex));
3404 } else {
3405 llvm::Value *Idxs[] = {getZeroInt(), VBIndex};
3406 VirtualBaseAdjustmentOffset = Builder.CreateAlignedLoad(
3407 CGM.IntTy, Builder.CreateInBoundsGEP(VDispMap->getValueType(),
3408 VDispMap, Idxs),
3409 CharUnits::fromQuantity(4));
3412 DstVBIndexEqZero =
3413 Builder.CreateICmpEQ(VirtualBaseAdjustmentOffset, getZeroInt());
3417 // Set the VBPtrOffset to zero if the vbindex is zero. Otherwise, initialize
3418 // it to the offset of the vbptr.
3419 if (inheritanceModelHasVBPtrOffsetField(DstInheritance)) {
3420 llvm::Value *DstVBPtrOffset = llvm::ConstantInt::get(
3421 CGM.IntTy,
3422 getContext().getASTRecordLayout(DstRD).getVBPtrOffset().getQuantity());
3423 VBPtrOffset =
3424 Builder.CreateSelect(DstVBIndexEqZero, getZeroInt(), DstVBPtrOffset);
3427 // Likewise, apply a similar adjustment so that dereferencing the member
3428 // pointer correctly accounts for the distance between the start of the first
3429 // virtual base and the top of the MDC.
3430 if (DstInheritance == MSInheritanceModel::Virtual) {
3431 if (int64_t DstOffsetToFirstVBase =
3432 getContext().getOffsetOfBaseWithVBPtr(DstRD).getQuantity()) {
3433 llvm::Value *DoDstAdjustment = Builder.CreateSelect(
3434 DstVBIndexEqZero,
3435 llvm::ConstantInt::get(CGM.IntTy, DstOffsetToFirstVBase),
3436 getZeroInt());
3437 NVAdjustField = Builder.CreateNSWSub(NVAdjustField, DoDstAdjustment);
3441 // Recompose dst from the null struct and the adjusted fields from src.
3442 llvm::Value *Dst;
3443 if (inheritanceModelHasOnlyOneField(IsFunc, DstInheritance)) {
3444 Dst = FirstField;
3445 } else {
3446 Dst = llvm::UndefValue::get(ConvertMemberPointerType(DstTy));
3447 unsigned Idx = 0;
3448 Dst = Builder.CreateInsertValue(Dst, FirstField, Idx++);
3449 if (inheritanceModelHasNVOffsetField(IsFunc, DstInheritance))
3450 Dst = Builder.CreateInsertValue(Dst, NonVirtualBaseAdjustment, Idx++);
3451 if (inheritanceModelHasVBPtrOffsetField(DstInheritance))
3452 Dst = Builder.CreateInsertValue(Dst, VBPtrOffset, Idx++);
3453 if (inheritanceModelHasVBTableOffsetField(DstInheritance))
3454 Dst = Builder.CreateInsertValue(Dst, VirtualBaseAdjustmentOffset, Idx++);
3456 return Dst;
3459 llvm::Constant *
3460 MicrosoftCXXABI::EmitMemberPointerConversion(const CastExpr *E,
3461 llvm::Constant *Src) {
3462 const MemberPointerType *SrcTy =
3463 E->getSubExpr()->getType()->castAs<MemberPointerType>();
3464 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
3466 CastKind CK = E->getCastKind();
3468 return EmitMemberPointerConversion(SrcTy, DstTy, CK, E->path_begin(),
3469 E->path_end(), Src);
3472 llvm::Constant *MicrosoftCXXABI::EmitMemberPointerConversion(
3473 const MemberPointerType *SrcTy, const MemberPointerType *DstTy, CastKind CK,
3474 CastExpr::path_const_iterator PathBegin,
3475 CastExpr::path_const_iterator PathEnd, llvm::Constant *Src) {
3476 assert(CK == CK_DerivedToBaseMemberPointer ||
3477 CK == CK_BaseToDerivedMemberPointer ||
3478 CK == CK_ReinterpretMemberPointer);
3479 // If src is null, emit a new null for dst. We can't return src because dst
3480 // might have a new representation.
3481 if (MemberPointerConstantIsNull(SrcTy, Src))
3482 return EmitNullMemberPointer(DstTy);
3484 // We don't need to do anything for reinterpret_casts of non-null member
3485 // pointers. We should only get here when the two type representations have
3486 // the same size.
3487 if (CK == CK_ReinterpretMemberPointer)
3488 return Src;
3490 CGBuilderTy Builder(CGM, CGM.getLLVMContext());
3491 auto *Dst = cast<llvm::Constant>(EmitNonNullMemberPointerConversion(
3492 SrcTy, DstTy, CK, PathBegin, PathEnd, Src, Builder));
3494 return Dst;
3497 CGCallee MicrosoftCXXABI::EmitLoadOfMemberFunctionPointer(
3498 CodeGenFunction &CGF, const Expr *E, Address This,
3499 llvm::Value *&ThisPtrForCall, llvm::Value *MemPtr,
3500 const MemberPointerType *MPT) {
3501 assert(MPT->isMemberFunctionPointer());
3502 const FunctionProtoType *FPT =
3503 MPT->getPointeeType()->castAs<FunctionProtoType>();
3504 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
3505 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(
3506 CGM.getTypes().arrangeCXXMethodType(RD, FPT, /*FD=*/nullptr));
3507 CGBuilderTy &Builder = CGF.Builder;
3509 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
3511 // Extract the fields we need, regardless of model. We'll apply them if we
3512 // have them.
3513 llvm::Value *FunctionPointer = MemPtr;
3514 llvm::Value *NonVirtualBaseAdjustment = nullptr;
3515 llvm::Value *VirtualBaseAdjustmentOffset = nullptr;
3516 llvm::Value *VBPtrOffset = nullptr;
3517 if (MemPtr->getType()->isStructTy()) {
3518 // We need to extract values.
3519 unsigned I = 0;
3520 FunctionPointer = Builder.CreateExtractValue(MemPtr, I++);
3521 if (inheritanceModelHasNVOffsetField(MPT, Inheritance))
3522 NonVirtualBaseAdjustment = Builder.CreateExtractValue(MemPtr, I++);
3523 if (inheritanceModelHasVBPtrOffsetField(Inheritance))
3524 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
3525 if (inheritanceModelHasVBTableOffsetField(Inheritance))
3526 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
3529 if (VirtualBaseAdjustmentOffset) {
3530 ThisPtrForCall = AdjustVirtualBase(CGF, E, RD, This,
3531 VirtualBaseAdjustmentOffset, VBPtrOffset);
3532 } else {
3533 ThisPtrForCall = This.getPointer();
3536 if (NonVirtualBaseAdjustment) {
3537 // Apply the adjustment and cast back to the original struct type.
3538 llvm::Value *Ptr = Builder.CreateBitCast(ThisPtrForCall, CGF.Int8PtrTy);
3539 Ptr = Builder.CreateInBoundsGEP(CGF.Int8Ty, Ptr, NonVirtualBaseAdjustment);
3540 ThisPtrForCall = Builder.CreateBitCast(Ptr, ThisPtrForCall->getType(),
3541 "this.adjusted");
3544 FunctionPointer =
3545 Builder.CreateBitCast(FunctionPointer, FTy->getPointerTo());
3546 CGCallee Callee(FPT, FunctionPointer);
3547 return Callee;
3550 CGCXXABI *clang::CodeGen::CreateMicrosoftCXXABI(CodeGenModule &CGM) {
3551 return new MicrosoftCXXABI(CGM);
3554 // MS RTTI Overview:
3555 // The run time type information emitted by cl.exe contains 5 distinct types of
3556 // structures. Many of them reference each other.
3558 // TypeInfo: Static classes that are returned by typeid.
3560 // CompleteObjectLocator: Referenced by vftables. They contain information
3561 // required for dynamic casting, including OffsetFromTop. They also contain
3562 // a reference to the TypeInfo for the type and a reference to the
3563 // CompleteHierarchyDescriptor for the type.
3565 // ClassHierarchyDescriptor: Contains information about a class hierarchy.
3566 // Used during dynamic_cast to walk a class hierarchy. References a base
3567 // class array and the size of said array.
3569 // BaseClassArray: Contains a list of classes in a hierarchy. BaseClassArray is
3570 // somewhat of a misnomer because the most derived class is also in the list
3571 // as well as multiple copies of virtual bases (if they occur multiple times
3572 // in the hierarchy.) The BaseClassArray contains one BaseClassDescriptor for
3573 // every path in the hierarchy, in pre-order depth first order. Note, we do
3574 // not declare a specific llvm type for BaseClassArray, it's merely an array
3575 // of BaseClassDescriptor pointers.
3577 // BaseClassDescriptor: Contains information about a class in a class hierarchy.
3578 // BaseClassDescriptor is also somewhat of a misnomer for the same reason that
3579 // BaseClassArray is. It contains information about a class within a
3580 // hierarchy such as: is this base is ambiguous and what is its offset in the
3581 // vbtable. The names of the BaseClassDescriptors have all of their fields
3582 // mangled into them so they can be aggressively deduplicated by the linker.
3584 static llvm::GlobalVariable *getTypeInfoVTable(CodeGenModule &CGM) {
3585 StringRef MangledName("??_7type_info@@6B@");
3586 if (auto VTable = CGM.getModule().getNamedGlobal(MangledName))
3587 return VTable;
3588 return new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
3589 /*isConstant=*/true,
3590 llvm::GlobalVariable::ExternalLinkage,
3591 /*Initializer=*/nullptr, MangledName);
3594 namespace {
3596 /// A Helper struct that stores information about a class in a class
3597 /// hierarchy. The information stored in these structs struct is used during
3598 /// the generation of ClassHierarchyDescriptors and BaseClassDescriptors.
3599 // During RTTI creation, MSRTTIClasses are stored in a contiguous array with
3600 // implicit depth first pre-order tree connectivity. getFirstChild and
3601 // getNextSibling allow us to walk the tree efficiently.
3602 struct MSRTTIClass {
3603 enum {
3604 IsPrivateOnPath = 1 | 8,
3605 IsAmbiguous = 2,
3606 IsPrivate = 4,
3607 IsVirtual = 16,
3608 HasHierarchyDescriptor = 64
3610 MSRTTIClass(const CXXRecordDecl *RD) : RD(RD) {}
3611 uint32_t initialize(const MSRTTIClass *Parent,
3612 const CXXBaseSpecifier *Specifier);
3614 MSRTTIClass *getFirstChild() { return this + 1; }
3615 static MSRTTIClass *getNextChild(MSRTTIClass *Child) {
3616 return Child + 1 + Child->NumBases;
3619 const CXXRecordDecl *RD, *VirtualRoot;
3620 uint32_t Flags, NumBases, OffsetInVBase;
3623 /// Recursively initialize the base class array.
3624 uint32_t MSRTTIClass::initialize(const MSRTTIClass *Parent,
3625 const CXXBaseSpecifier *Specifier) {
3626 Flags = HasHierarchyDescriptor;
3627 if (!Parent) {
3628 VirtualRoot = nullptr;
3629 OffsetInVBase = 0;
3630 } else {
3631 if (Specifier->getAccessSpecifier() != AS_public)
3632 Flags |= IsPrivate | IsPrivateOnPath;
3633 if (Specifier->isVirtual()) {
3634 Flags |= IsVirtual;
3635 VirtualRoot = RD;
3636 OffsetInVBase = 0;
3637 } else {
3638 if (Parent->Flags & IsPrivateOnPath)
3639 Flags |= IsPrivateOnPath;
3640 VirtualRoot = Parent->VirtualRoot;
3641 OffsetInVBase = Parent->OffsetInVBase + RD->getASTContext()
3642 .getASTRecordLayout(Parent->RD).getBaseClassOffset(RD).getQuantity();
3645 NumBases = 0;
3646 MSRTTIClass *Child = getFirstChild();
3647 for (const CXXBaseSpecifier &Base : RD->bases()) {
3648 NumBases += Child->initialize(this, &Base) + 1;
3649 Child = getNextChild(Child);
3651 return NumBases;
3654 static llvm::GlobalValue::LinkageTypes getLinkageForRTTI(QualType Ty) {
3655 switch (Ty->getLinkage()) {
3656 case NoLinkage:
3657 case InternalLinkage:
3658 case UniqueExternalLinkage:
3659 return llvm::GlobalValue::InternalLinkage;
3661 case VisibleNoLinkage:
3662 case ModuleInternalLinkage:
3663 case ModuleLinkage:
3664 case ExternalLinkage:
3665 return llvm::GlobalValue::LinkOnceODRLinkage;
3667 llvm_unreachable("Invalid linkage!");
3670 /// An ephemeral helper class for building MS RTTI types. It caches some
3671 /// calls to the module and information about the most derived class in a
3672 /// hierarchy.
3673 struct MSRTTIBuilder {
3674 enum {
3675 HasBranchingHierarchy = 1,
3676 HasVirtualBranchingHierarchy = 2,
3677 HasAmbiguousBases = 4
3680 MSRTTIBuilder(MicrosoftCXXABI &ABI, const CXXRecordDecl *RD)
3681 : CGM(ABI.CGM), Context(CGM.getContext()),
3682 VMContext(CGM.getLLVMContext()), Module(CGM.getModule()), RD(RD),
3683 Linkage(getLinkageForRTTI(CGM.getContext().getTagDeclType(RD))),
3684 ABI(ABI) {}
3686 llvm::GlobalVariable *getBaseClassDescriptor(const MSRTTIClass &Classes);
3687 llvm::GlobalVariable *
3688 getBaseClassArray(SmallVectorImpl<MSRTTIClass> &Classes);
3689 llvm::GlobalVariable *getClassHierarchyDescriptor();
3690 llvm::GlobalVariable *getCompleteObjectLocator(const VPtrInfo &Info);
3692 CodeGenModule &CGM;
3693 ASTContext &Context;
3694 llvm::LLVMContext &VMContext;
3695 llvm::Module &Module;
3696 const CXXRecordDecl *RD;
3697 llvm::GlobalVariable::LinkageTypes Linkage;
3698 MicrosoftCXXABI &ABI;
3701 } // namespace
3703 /// Recursively serializes a class hierarchy in pre-order depth first
3704 /// order.
3705 static void serializeClassHierarchy(SmallVectorImpl<MSRTTIClass> &Classes,
3706 const CXXRecordDecl *RD) {
3707 Classes.push_back(MSRTTIClass(RD));
3708 for (const CXXBaseSpecifier &Base : RD->bases())
3709 serializeClassHierarchy(Classes, Base.getType()->getAsCXXRecordDecl());
3712 /// Find ambiguity among base classes.
3713 static void
3714 detectAmbiguousBases(SmallVectorImpl<MSRTTIClass> &Classes) {
3715 llvm::SmallPtrSet<const CXXRecordDecl *, 8> VirtualBases;
3716 llvm::SmallPtrSet<const CXXRecordDecl *, 8> UniqueBases;
3717 llvm::SmallPtrSet<const CXXRecordDecl *, 8> AmbiguousBases;
3718 for (MSRTTIClass *Class = &Classes.front(); Class <= &Classes.back();) {
3719 if ((Class->Flags & MSRTTIClass::IsVirtual) &&
3720 !VirtualBases.insert(Class->RD).second) {
3721 Class = MSRTTIClass::getNextChild(Class);
3722 continue;
3724 if (!UniqueBases.insert(Class->RD).second)
3725 AmbiguousBases.insert(Class->RD);
3726 Class++;
3728 if (AmbiguousBases.empty())
3729 return;
3730 for (MSRTTIClass &Class : Classes)
3731 if (AmbiguousBases.count(Class.RD))
3732 Class.Flags |= MSRTTIClass::IsAmbiguous;
3735 llvm::GlobalVariable *MSRTTIBuilder::getClassHierarchyDescriptor() {
3736 SmallString<256> MangledName;
3738 llvm::raw_svector_ostream Out(MangledName);
3739 ABI.getMangleContext().mangleCXXRTTIClassHierarchyDescriptor(RD, Out);
3742 // Check to see if we've already declared this ClassHierarchyDescriptor.
3743 if (auto CHD = Module.getNamedGlobal(MangledName))
3744 return CHD;
3746 // Serialize the class hierarchy and initialize the CHD Fields.
3747 SmallVector<MSRTTIClass, 8> Classes;
3748 serializeClassHierarchy(Classes, RD);
3749 Classes.front().initialize(/*Parent=*/nullptr, /*Specifier=*/nullptr);
3750 detectAmbiguousBases(Classes);
3751 int Flags = 0;
3752 for (auto Class : Classes) {
3753 if (Class.RD->getNumBases() > 1)
3754 Flags |= HasBranchingHierarchy;
3755 // Note: cl.exe does not calculate "HasAmbiguousBases" correctly. We
3756 // believe the field isn't actually used.
3757 if (Class.Flags & MSRTTIClass::IsAmbiguous)
3758 Flags |= HasAmbiguousBases;
3760 if ((Flags & HasBranchingHierarchy) && RD->getNumVBases() != 0)
3761 Flags |= HasVirtualBranchingHierarchy;
3762 // These gep indices are used to get the address of the first element of the
3763 // base class array.
3764 llvm::Value *GEPIndices[] = {llvm::ConstantInt::get(CGM.IntTy, 0),
3765 llvm::ConstantInt::get(CGM.IntTy, 0)};
3767 // Forward-declare the class hierarchy descriptor
3768 auto Type = ABI.getClassHierarchyDescriptorType();
3769 auto CHD = new llvm::GlobalVariable(Module, Type, /*isConstant=*/true, Linkage,
3770 /*Initializer=*/nullptr,
3771 MangledName);
3772 if (CHD->isWeakForLinker())
3773 CHD->setComdat(CGM.getModule().getOrInsertComdat(CHD->getName()));
3775 auto *Bases = getBaseClassArray(Classes);
3777 // Initialize the base class ClassHierarchyDescriptor.
3778 llvm::Constant *Fields[] = {
3779 llvm::ConstantInt::get(CGM.IntTy, 0), // reserved by the runtime
3780 llvm::ConstantInt::get(CGM.IntTy, Flags),
3781 llvm::ConstantInt::get(CGM.IntTy, Classes.size()),
3782 ABI.getImageRelativeConstant(llvm::ConstantExpr::getInBoundsGetElementPtr(
3783 Bases->getValueType(), Bases,
3784 llvm::ArrayRef<llvm::Value *>(GEPIndices))),
3786 CHD->setInitializer(llvm::ConstantStruct::get(Type, Fields));
3787 return CHD;
3790 llvm::GlobalVariable *
3791 MSRTTIBuilder::getBaseClassArray(SmallVectorImpl<MSRTTIClass> &Classes) {
3792 SmallString<256> MangledName;
3794 llvm::raw_svector_ostream Out(MangledName);
3795 ABI.getMangleContext().mangleCXXRTTIBaseClassArray(RD, Out);
3798 // Forward-declare the base class array.
3799 // cl.exe pads the base class array with 1 (in 32 bit mode) or 4 (in 64 bit
3800 // mode) bytes of padding. We provide a pointer sized amount of padding by
3801 // adding +1 to Classes.size(). The sections have pointer alignment and are
3802 // marked pick-any so it shouldn't matter.
3803 llvm::Type *PtrType = ABI.getImageRelativeType(
3804 ABI.getBaseClassDescriptorType()->getPointerTo());
3805 auto *ArrType = llvm::ArrayType::get(PtrType, Classes.size() + 1);
3806 auto *BCA =
3807 new llvm::GlobalVariable(Module, ArrType,
3808 /*isConstant=*/true, Linkage,
3809 /*Initializer=*/nullptr, MangledName);
3810 if (BCA->isWeakForLinker())
3811 BCA->setComdat(CGM.getModule().getOrInsertComdat(BCA->getName()));
3813 // Initialize the BaseClassArray.
3814 SmallVector<llvm::Constant *, 8> BaseClassArrayData;
3815 for (MSRTTIClass &Class : Classes)
3816 BaseClassArrayData.push_back(
3817 ABI.getImageRelativeConstant(getBaseClassDescriptor(Class)));
3818 BaseClassArrayData.push_back(llvm::Constant::getNullValue(PtrType));
3819 BCA->setInitializer(llvm::ConstantArray::get(ArrType, BaseClassArrayData));
3820 return BCA;
3823 llvm::GlobalVariable *
3824 MSRTTIBuilder::getBaseClassDescriptor(const MSRTTIClass &Class) {
3825 // Compute the fields for the BaseClassDescriptor. They are computed up front
3826 // because they are mangled into the name of the object.
3827 uint32_t OffsetInVBTable = 0;
3828 int32_t VBPtrOffset = -1;
3829 if (Class.VirtualRoot) {
3830 auto &VTableContext = CGM.getMicrosoftVTableContext();
3831 OffsetInVBTable = VTableContext.getVBTableIndex(RD, Class.VirtualRoot) * 4;
3832 VBPtrOffset = Context.getASTRecordLayout(RD).getVBPtrOffset().getQuantity();
3835 SmallString<256> MangledName;
3837 llvm::raw_svector_ostream Out(MangledName);
3838 ABI.getMangleContext().mangleCXXRTTIBaseClassDescriptor(
3839 Class.RD, Class.OffsetInVBase, VBPtrOffset, OffsetInVBTable,
3840 Class.Flags, Out);
3843 // Check to see if we've already declared this object.
3844 if (auto BCD = Module.getNamedGlobal(MangledName))
3845 return BCD;
3847 // Forward-declare the base class descriptor.
3848 auto Type = ABI.getBaseClassDescriptorType();
3849 auto BCD =
3850 new llvm::GlobalVariable(Module, Type, /*isConstant=*/true, Linkage,
3851 /*Initializer=*/nullptr, MangledName);
3852 if (BCD->isWeakForLinker())
3853 BCD->setComdat(CGM.getModule().getOrInsertComdat(BCD->getName()));
3855 // Initialize the BaseClassDescriptor.
3856 llvm::Constant *Fields[] = {
3857 ABI.getImageRelativeConstant(
3858 ABI.getAddrOfRTTIDescriptor(Context.getTypeDeclType(Class.RD))),
3859 llvm::ConstantInt::get(CGM.IntTy, Class.NumBases),
3860 llvm::ConstantInt::get(CGM.IntTy, Class.OffsetInVBase),
3861 llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset),
3862 llvm::ConstantInt::get(CGM.IntTy, OffsetInVBTable),
3863 llvm::ConstantInt::get(CGM.IntTy, Class.Flags),
3864 ABI.getImageRelativeConstant(
3865 MSRTTIBuilder(ABI, Class.RD).getClassHierarchyDescriptor()),
3867 BCD->setInitializer(llvm::ConstantStruct::get(Type, Fields));
3868 return BCD;
3871 llvm::GlobalVariable *
3872 MSRTTIBuilder::getCompleteObjectLocator(const VPtrInfo &Info) {
3873 SmallString<256> MangledName;
3875 llvm::raw_svector_ostream Out(MangledName);
3876 ABI.getMangleContext().mangleCXXRTTICompleteObjectLocator(RD, Info.MangledPath, Out);
3879 // Check to see if we've already computed this complete object locator.
3880 if (auto COL = Module.getNamedGlobal(MangledName))
3881 return COL;
3883 // Compute the fields of the complete object locator.
3884 int OffsetToTop = Info.FullOffsetInMDC.getQuantity();
3885 int VFPtrOffset = 0;
3886 // The offset includes the vtordisp if one exists.
3887 if (const CXXRecordDecl *VBase = Info.getVBaseWithVPtr())
3888 if (Context.getASTRecordLayout(RD)
3889 .getVBaseOffsetsMap()
3890 .find(VBase)
3891 ->second.hasVtorDisp())
3892 VFPtrOffset = Info.NonVirtualOffset.getQuantity() + 4;
3894 // Forward-declare the complete object locator.
3895 llvm::StructType *Type = ABI.getCompleteObjectLocatorType();
3896 auto COL = new llvm::GlobalVariable(Module, Type, /*isConstant=*/true, Linkage,
3897 /*Initializer=*/nullptr, MangledName);
3899 // Initialize the CompleteObjectLocator.
3900 llvm::Constant *Fields[] = {
3901 llvm::ConstantInt::get(CGM.IntTy, ABI.isImageRelative()),
3902 llvm::ConstantInt::get(CGM.IntTy, OffsetToTop),
3903 llvm::ConstantInt::get(CGM.IntTy, VFPtrOffset),
3904 ABI.getImageRelativeConstant(
3905 CGM.GetAddrOfRTTIDescriptor(Context.getTypeDeclType(RD))),
3906 ABI.getImageRelativeConstant(getClassHierarchyDescriptor()),
3907 ABI.getImageRelativeConstant(COL),
3909 llvm::ArrayRef<llvm::Constant *> FieldsRef(Fields);
3910 if (!ABI.isImageRelative())
3911 FieldsRef = FieldsRef.drop_back();
3912 COL->setInitializer(llvm::ConstantStruct::get(Type, FieldsRef));
3913 if (COL->isWeakForLinker())
3914 COL->setComdat(CGM.getModule().getOrInsertComdat(COL->getName()));
3915 return COL;
3918 static QualType decomposeTypeForEH(ASTContext &Context, QualType T,
3919 bool &IsConst, bool &IsVolatile,
3920 bool &IsUnaligned) {
3921 T = Context.getExceptionObjectType(T);
3923 // C++14 [except.handle]p3:
3924 // A handler is a match for an exception object of type E if [...]
3925 // - the handler is of type cv T or const T& where T is a pointer type and
3926 // E is a pointer type that can be converted to T by [...]
3927 // - a qualification conversion
3928 IsConst = false;
3929 IsVolatile = false;
3930 IsUnaligned = false;
3931 QualType PointeeType = T->getPointeeType();
3932 if (!PointeeType.isNull()) {
3933 IsConst = PointeeType.isConstQualified();
3934 IsVolatile = PointeeType.isVolatileQualified();
3935 IsUnaligned = PointeeType.getQualifiers().hasUnaligned();
3938 // Member pointer types like "const int A::*" are represented by having RTTI
3939 // for "int A::*" and separately storing the const qualifier.
3940 if (const auto *MPTy = T->getAs<MemberPointerType>())
3941 T = Context.getMemberPointerType(PointeeType.getUnqualifiedType(),
3942 MPTy->getClass());
3944 // Pointer types like "const int * const *" are represented by having RTTI
3945 // for "const int **" and separately storing the const qualifier.
3946 if (T->isPointerType())
3947 T = Context.getPointerType(PointeeType.getUnqualifiedType());
3949 return T;
3952 CatchTypeInfo
3953 MicrosoftCXXABI::getAddrOfCXXCatchHandlerType(QualType Type,
3954 QualType CatchHandlerType) {
3955 // TypeDescriptors for exceptions never have qualified pointer types,
3956 // qualifiers are stored separately in order to support qualification
3957 // conversions.
3958 bool IsConst, IsVolatile, IsUnaligned;
3959 Type =
3960 decomposeTypeForEH(getContext(), Type, IsConst, IsVolatile, IsUnaligned);
3962 bool IsReference = CatchHandlerType->isReferenceType();
3964 uint32_t Flags = 0;
3965 if (IsConst)
3966 Flags |= 1;
3967 if (IsVolatile)
3968 Flags |= 2;
3969 if (IsUnaligned)
3970 Flags |= 4;
3971 if (IsReference)
3972 Flags |= 8;
3974 return CatchTypeInfo{getAddrOfRTTIDescriptor(Type)->stripPointerCasts(),
3975 Flags};
3978 /// Gets a TypeDescriptor. Returns a llvm::Constant * rather than a
3979 /// llvm::GlobalVariable * because different type descriptors have different
3980 /// types, and need to be abstracted. They are abstracting by casting the
3981 /// address to an Int8PtrTy.
3982 llvm::Constant *MicrosoftCXXABI::getAddrOfRTTIDescriptor(QualType Type) {
3983 SmallString<256> MangledName;
3985 llvm::raw_svector_ostream Out(MangledName);
3986 getMangleContext().mangleCXXRTTI(Type, Out);
3989 // Check to see if we've already declared this TypeDescriptor.
3990 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
3991 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
3993 // Note for the future: If we would ever like to do deferred emission of
3994 // RTTI, check if emitting vtables opportunistically need any adjustment.
3996 // Compute the fields for the TypeDescriptor.
3997 SmallString<256> TypeInfoString;
3999 llvm::raw_svector_ostream Out(TypeInfoString);
4000 getMangleContext().mangleCXXRTTIName(Type, Out);
4003 // Declare and initialize the TypeDescriptor.
4004 llvm::Constant *Fields[] = {
4005 getTypeInfoVTable(CGM), // VFPtr
4006 llvm::ConstantPointerNull::get(CGM.Int8PtrTy), // Runtime data
4007 llvm::ConstantDataArray::getString(CGM.getLLVMContext(), TypeInfoString)};
4008 llvm::StructType *TypeDescriptorType =
4009 getTypeDescriptorType(TypeInfoString);
4010 auto *Var = new llvm::GlobalVariable(
4011 CGM.getModule(), TypeDescriptorType, /*isConstant=*/false,
4012 getLinkageForRTTI(Type),
4013 llvm::ConstantStruct::get(TypeDescriptorType, Fields),
4014 MangledName);
4015 if (Var->isWeakForLinker())
4016 Var->setComdat(CGM.getModule().getOrInsertComdat(Var->getName()));
4017 return llvm::ConstantExpr::getBitCast(Var, CGM.Int8PtrTy);
4020 /// Gets or a creates a Microsoft CompleteObjectLocator.
4021 llvm::GlobalVariable *
4022 MicrosoftCXXABI::getMSCompleteObjectLocator(const CXXRecordDecl *RD,
4023 const VPtrInfo &Info) {
4024 return MSRTTIBuilder(*this, RD).getCompleteObjectLocator(Info);
4027 void MicrosoftCXXABI::emitCXXStructor(GlobalDecl GD) {
4028 if (auto *ctor = dyn_cast<CXXConstructorDecl>(GD.getDecl())) {
4029 // There are no constructor variants, always emit the complete destructor.
4030 llvm::Function *Fn =
4031 CGM.codegenCXXStructor(GD.getWithCtorType(Ctor_Complete));
4032 CGM.maybeSetTrivialComdat(*ctor, *Fn);
4033 return;
4036 auto *dtor = cast<CXXDestructorDecl>(GD.getDecl());
4038 // Emit the base destructor if the base and complete (vbase) destructors are
4039 // equivalent. This effectively implements -mconstructor-aliases as part of
4040 // the ABI.
4041 if (GD.getDtorType() == Dtor_Complete &&
4042 dtor->getParent()->getNumVBases() == 0)
4043 GD = GD.getWithDtorType(Dtor_Base);
4045 // The base destructor is equivalent to the base destructor of its
4046 // base class if there is exactly one non-virtual base class with a
4047 // non-trivial destructor, there are no fields with a non-trivial
4048 // destructor, and the body of the destructor is trivial.
4049 if (GD.getDtorType() == Dtor_Base && !CGM.TryEmitBaseDestructorAsAlias(dtor))
4050 return;
4052 llvm::Function *Fn = CGM.codegenCXXStructor(GD);
4053 if (Fn->isWeakForLinker())
4054 Fn->setComdat(CGM.getModule().getOrInsertComdat(Fn->getName()));
4057 llvm::Function *
4058 MicrosoftCXXABI::getAddrOfCXXCtorClosure(const CXXConstructorDecl *CD,
4059 CXXCtorType CT) {
4060 assert(CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure);
4062 // Calculate the mangled name.
4063 SmallString<256> ThunkName;
4064 llvm::raw_svector_ostream Out(ThunkName);
4065 getMangleContext().mangleName(GlobalDecl(CD, CT), Out);
4067 // If the thunk has been generated previously, just return it.
4068 if (llvm::GlobalValue *GV = CGM.getModule().getNamedValue(ThunkName))
4069 return cast<llvm::Function>(GV);
4071 // Create the llvm::Function.
4072 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeMSCtorClosure(CD, CT);
4073 llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo);
4074 const CXXRecordDecl *RD = CD->getParent();
4075 QualType RecordTy = getContext().getRecordType(RD);
4076 llvm::Function *ThunkFn = llvm::Function::Create(
4077 ThunkTy, getLinkageForRTTI(RecordTy), ThunkName.str(), &CGM.getModule());
4078 ThunkFn->setCallingConv(static_cast<llvm::CallingConv::ID>(
4079 FnInfo.getEffectiveCallingConvention()));
4080 if (ThunkFn->isWeakForLinker())
4081 ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));
4082 bool IsCopy = CT == Ctor_CopyingClosure;
4084 // Start codegen.
4085 CodeGenFunction CGF(CGM);
4086 CGF.CurGD = GlobalDecl(CD, Ctor_Complete);
4088 // Build FunctionArgs.
4089 FunctionArgList FunctionArgs;
4091 // A constructor always starts with a 'this' pointer as its first argument.
4092 buildThisParam(CGF, FunctionArgs);
4094 // Following the 'this' pointer is a reference to the source object that we
4095 // are copying from.
4096 ImplicitParamDecl SrcParam(
4097 getContext(), /*DC=*/nullptr, SourceLocation(),
4098 &getContext().Idents.get("src"),
4099 getContext().getLValueReferenceType(RecordTy,
4100 /*SpelledAsLValue=*/true),
4101 ImplicitParamDecl::Other);
4102 if (IsCopy)
4103 FunctionArgs.push_back(&SrcParam);
4105 // Constructors for classes which utilize virtual bases have an additional
4106 // parameter which indicates whether or not it is being delegated to by a more
4107 // derived constructor.
4108 ImplicitParamDecl IsMostDerived(getContext(), /*DC=*/nullptr,
4109 SourceLocation(),
4110 &getContext().Idents.get("is_most_derived"),
4111 getContext().IntTy, ImplicitParamDecl::Other);
4112 // Only add the parameter to the list if the class has virtual bases.
4113 if (RD->getNumVBases() > 0)
4114 FunctionArgs.push_back(&IsMostDerived);
4116 // Start defining the function.
4117 auto NL = ApplyDebugLocation::CreateEmpty(CGF);
4118 CGF.StartFunction(GlobalDecl(), FnInfo.getReturnType(), ThunkFn, FnInfo,
4119 FunctionArgs, CD->getLocation(), SourceLocation());
4120 // Create a scope with an artificial location for the body of this function.
4121 auto AL = ApplyDebugLocation::CreateArtificial(CGF);
4122 setCXXABIThisValue(CGF, loadIncomingCXXThis(CGF));
4123 llvm::Value *This = getThisValue(CGF);
4125 llvm::Value *SrcVal =
4126 IsCopy ? CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&SrcParam), "src")
4127 : nullptr;
4129 CallArgList Args;
4131 // Push the this ptr.
4132 Args.add(RValue::get(This), CD->getThisType());
4134 // Push the src ptr.
4135 if (SrcVal)
4136 Args.add(RValue::get(SrcVal), SrcParam.getType());
4138 // Add the rest of the default arguments.
4139 SmallVector<const Stmt *, 4> ArgVec;
4140 ArrayRef<ParmVarDecl *> params = CD->parameters().drop_front(IsCopy ? 1 : 0);
4141 for (const ParmVarDecl *PD : params) {
4142 assert(PD->hasDefaultArg() && "ctor closure lacks default args");
4143 ArgVec.push_back(PD->getDefaultArg());
4146 CodeGenFunction::RunCleanupsScope Cleanups(CGF);
4148 const auto *FPT = CD->getType()->castAs<FunctionProtoType>();
4149 CGF.EmitCallArgs(Args, FPT, llvm::makeArrayRef(ArgVec), CD, IsCopy ? 1 : 0);
4151 // Insert any ABI-specific implicit constructor arguments.
4152 AddedStructorArgCounts ExtraArgs =
4153 addImplicitConstructorArgs(CGF, CD, Ctor_Complete,
4154 /*ForVirtualBase=*/false,
4155 /*Delegating=*/false, Args);
4156 // Call the destructor with our arguments.
4157 llvm::Constant *CalleePtr =
4158 CGM.getAddrOfCXXStructor(GlobalDecl(CD, Ctor_Complete));
4159 CGCallee Callee =
4160 CGCallee::forDirect(CalleePtr, GlobalDecl(CD, Ctor_Complete));
4161 const CGFunctionInfo &CalleeInfo = CGM.getTypes().arrangeCXXConstructorCall(
4162 Args, CD, Ctor_Complete, ExtraArgs.Prefix, ExtraArgs.Suffix);
4163 CGF.EmitCall(CalleeInfo, Callee, ReturnValueSlot(), Args);
4165 Cleanups.ForceCleanup();
4167 // Emit the ret instruction, remove any temporary instructions created for the
4168 // aid of CodeGen.
4169 CGF.FinishFunction(SourceLocation());
4171 return ThunkFn;
4174 llvm::Constant *MicrosoftCXXABI::getCatchableType(QualType T,
4175 uint32_t NVOffset,
4176 int32_t VBPtrOffset,
4177 uint32_t VBIndex) {
4178 assert(!T->isReferenceType());
4180 CXXRecordDecl *RD = T->getAsCXXRecordDecl();
4181 const CXXConstructorDecl *CD =
4182 RD ? CGM.getContext().getCopyConstructorForExceptionObject(RD) : nullptr;
4183 CXXCtorType CT = Ctor_Complete;
4184 if (CD)
4185 if (!hasDefaultCXXMethodCC(getContext(), CD) || CD->getNumParams() != 1)
4186 CT = Ctor_CopyingClosure;
4188 uint32_t Size = getContext().getTypeSizeInChars(T).getQuantity();
4189 SmallString<256> MangledName;
4191 llvm::raw_svector_ostream Out(MangledName);
4192 getMangleContext().mangleCXXCatchableType(T, CD, CT, Size, NVOffset,
4193 VBPtrOffset, VBIndex, Out);
4195 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
4196 return getImageRelativeConstant(GV);
4198 // The TypeDescriptor is used by the runtime to determine if a catch handler
4199 // is appropriate for the exception object.
4200 llvm::Constant *TD = getImageRelativeConstant(getAddrOfRTTIDescriptor(T));
4202 // The runtime is responsible for calling the copy constructor if the
4203 // exception is caught by value.
4204 llvm::Constant *CopyCtor;
4205 if (CD) {
4206 if (CT == Ctor_CopyingClosure)
4207 CopyCtor = getAddrOfCXXCtorClosure(CD, Ctor_CopyingClosure);
4208 else
4209 CopyCtor = CGM.getAddrOfCXXStructor(GlobalDecl(CD, Ctor_Complete));
4211 CopyCtor = llvm::ConstantExpr::getBitCast(CopyCtor, CGM.Int8PtrTy);
4212 } else {
4213 CopyCtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);
4215 CopyCtor = getImageRelativeConstant(CopyCtor);
4217 bool IsScalar = !RD;
4218 bool HasVirtualBases = false;
4219 bool IsStdBadAlloc = false; // std::bad_alloc is special for some reason.
4220 QualType PointeeType = T;
4221 if (T->isPointerType())
4222 PointeeType = T->getPointeeType();
4223 if (const CXXRecordDecl *RD = PointeeType->getAsCXXRecordDecl()) {
4224 HasVirtualBases = RD->getNumVBases() > 0;
4225 if (IdentifierInfo *II = RD->getIdentifier())
4226 IsStdBadAlloc = II->isStr("bad_alloc") && RD->isInStdNamespace();
4229 // Encode the relevant CatchableType properties into the Flags bitfield.
4230 // FIXME: Figure out how bits 2 or 8 can get set.
4231 uint32_t Flags = 0;
4232 if (IsScalar)
4233 Flags |= 1;
4234 if (HasVirtualBases)
4235 Flags |= 4;
4236 if (IsStdBadAlloc)
4237 Flags |= 16;
4239 llvm::Constant *Fields[] = {
4240 llvm::ConstantInt::get(CGM.IntTy, Flags), // Flags
4241 TD, // TypeDescriptor
4242 llvm::ConstantInt::get(CGM.IntTy, NVOffset), // NonVirtualAdjustment
4243 llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset), // OffsetToVBPtr
4244 llvm::ConstantInt::get(CGM.IntTy, VBIndex), // VBTableIndex
4245 llvm::ConstantInt::get(CGM.IntTy, Size), // Size
4246 CopyCtor // CopyCtor
4248 llvm::StructType *CTType = getCatchableTypeType();
4249 auto *GV = new llvm::GlobalVariable(
4250 CGM.getModule(), CTType, /*isConstant=*/true, getLinkageForRTTI(T),
4251 llvm::ConstantStruct::get(CTType, Fields), MangledName);
4252 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4253 GV->setSection(".xdata");
4254 if (GV->isWeakForLinker())
4255 GV->setComdat(CGM.getModule().getOrInsertComdat(GV->getName()));
4256 return getImageRelativeConstant(GV);
4259 llvm::GlobalVariable *MicrosoftCXXABI::getCatchableTypeArray(QualType T) {
4260 assert(!T->isReferenceType());
4262 // See if we've already generated a CatchableTypeArray for this type before.
4263 llvm::GlobalVariable *&CTA = CatchableTypeArrays[T];
4264 if (CTA)
4265 return CTA;
4267 // Ensure that we don't have duplicate entries in our CatchableTypeArray by
4268 // using a SmallSetVector. Duplicates may arise due to virtual bases
4269 // occurring more than once in the hierarchy.
4270 llvm::SmallSetVector<llvm::Constant *, 2> CatchableTypes;
4272 // C++14 [except.handle]p3:
4273 // A handler is a match for an exception object of type E if [...]
4274 // - the handler is of type cv T or cv T& and T is an unambiguous public
4275 // base class of E, or
4276 // - the handler is of type cv T or const T& where T is a pointer type and
4277 // E is a pointer type that can be converted to T by [...]
4278 // - a standard pointer conversion (4.10) not involving conversions to
4279 // pointers to private or protected or ambiguous classes
4280 const CXXRecordDecl *MostDerivedClass = nullptr;
4281 bool IsPointer = T->isPointerType();
4282 if (IsPointer)
4283 MostDerivedClass = T->getPointeeType()->getAsCXXRecordDecl();
4284 else
4285 MostDerivedClass = T->getAsCXXRecordDecl();
4287 // Collect all the unambiguous public bases of the MostDerivedClass.
4288 if (MostDerivedClass) {
4289 const ASTContext &Context = getContext();
4290 const ASTRecordLayout &MostDerivedLayout =
4291 Context.getASTRecordLayout(MostDerivedClass);
4292 MicrosoftVTableContext &VTableContext = CGM.getMicrosoftVTableContext();
4293 SmallVector<MSRTTIClass, 8> Classes;
4294 serializeClassHierarchy(Classes, MostDerivedClass);
4295 Classes.front().initialize(/*Parent=*/nullptr, /*Specifier=*/nullptr);
4296 detectAmbiguousBases(Classes);
4297 for (const MSRTTIClass &Class : Classes) {
4298 // Skip any ambiguous or private bases.
4299 if (Class.Flags &
4300 (MSRTTIClass::IsPrivateOnPath | MSRTTIClass::IsAmbiguous))
4301 continue;
4302 // Write down how to convert from a derived pointer to a base pointer.
4303 uint32_t OffsetInVBTable = 0;
4304 int32_t VBPtrOffset = -1;
4305 if (Class.VirtualRoot) {
4306 OffsetInVBTable =
4307 VTableContext.getVBTableIndex(MostDerivedClass, Class.VirtualRoot)*4;
4308 VBPtrOffset = MostDerivedLayout.getVBPtrOffset().getQuantity();
4311 // Turn our record back into a pointer if the exception object is a
4312 // pointer.
4313 QualType RTTITy = QualType(Class.RD->getTypeForDecl(), 0);
4314 if (IsPointer)
4315 RTTITy = Context.getPointerType(RTTITy);
4316 CatchableTypes.insert(getCatchableType(RTTITy, Class.OffsetInVBase,
4317 VBPtrOffset, OffsetInVBTable));
4321 // C++14 [except.handle]p3:
4322 // A handler is a match for an exception object of type E if
4323 // - The handler is of type cv T or cv T& and E and T are the same type
4324 // (ignoring the top-level cv-qualifiers)
4325 CatchableTypes.insert(getCatchableType(T));
4327 // C++14 [except.handle]p3:
4328 // A handler is a match for an exception object of type E if
4329 // - the handler is of type cv T or const T& where T is a pointer type and
4330 // E is a pointer type that can be converted to T by [...]
4331 // - a standard pointer conversion (4.10) not involving conversions to
4332 // pointers to private or protected or ambiguous classes
4334 // C++14 [conv.ptr]p2:
4335 // A prvalue of type "pointer to cv T," where T is an object type, can be
4336 // converted to a prvalue of type "pointer to cv void".
4337 if (IsPointer && T->getPointeeType()->isObjectType())
4338 CatchableTypes.insert(getCatchableType(getContext().VoidPtrTy));
4340 // C++14 [except.handle]p3:
4341 // A handler is a match for an exception object of type E if [...]
4342 // - the handler is of type cv T or const T& where T is a pointer or
4343 // pointer to member type and E is std::nullptr_t.
4345 // We cannot possibly list all possible pointer types here, making this
4346 // implementation incompatible with the standard. However, MSVC includes an
4347 // entry for pointer-to-void in this case. Let's do the same.
4348 if (T->isNullPtrType())
4349 CatchableTypes.insert(getCatchableType(getContext().VoidPtrTy));
4351 uint32_t NumEntries = CatchableTypes.size();
4352 llvm::Type *CTType =
4353 getImageRelativeType(getCatchableTypeType()->getPointerTo());
4354 llvm::ArrayType *AT = llvm::ArrayType::get(CTType, NumEntries);
4355 llvm::StructType *CTAType = getCatchableTypeArrayType(NumEntries);
4356 llvm::Constant *Fields[] = {
4357 llvm::ConstantInt::get(CGM.IntTy, NumEntries), // NumEntries
4358 llvm::ConstantArray::get(
4359 AT, llvm::makeArrayRef(CatchableTypes.begin(),
4360 CatchableTypes.end())) // CatchableTypes
4362 SmallString<256> MangledName;
4364 llvm::raw_svector_ostream Out(MangledName);
4365 getMangleContext().mangleCXXCatchableTypeArray(T, NumEntries, Out);
4367 CTA = new llvm::GlobalVariable(
4368 CGM.getModule(), CTAType, /*isConstant=*/true, getLinkageForRTTI(T),
4369 llvm::ConstantStruct::get(CTAType, Fields), MangledName);
4370 CTA->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4371 CTA->setSection(".xdata");
4372 if (CTA->isWeakForLinker())
4373 CTA->setComdat(CGM.getModule().getOrInsertComdat(CTA->getName()));
4374 return CTA;
4377 llvm::GlobalVariable *MicrosoftCXXABI::getThrowInfo(QualType T) {
4378 bool IsConst, IsVolatile, IsUnaligned;
4379 T = decomposeTypeForEH(getContext(), T, IsConst, IsVolatile, IsUnaligned);
4381 // The CatchableTypeArray enumerates the various (CV-unqualified) types that
4382 // the exception object may be caught as.
4383 llvm::GlobalVariable *CTA = getCatchableTypeArray(T);
4384 // The first field in a CatchableTypeArray is the number of CatchableTypes.
4385 // This is used as a component of the mangled name which means that we need to
4386 // know what it is in order to see if we have previously generated the
4387 // ThrowInfo.
4388 uint32_t NumEntries =
4389 cast<llvm::ConstantInt>(CTA->getInitializer()->getAggregateElement(0U))
4390 ->getLimitedValue();
4392 SmallString<256> MangledName;
4394 llvm::raw_svector_ostream Out(MangledName);
4395 getMangleContext().mangleCXXThrowInfo(T, IsConst, IsVolatile, IsUnaligned,
4396 NumEntries, Out);
4399 // Reuse a previously generated ThrowInfo if we have generated an appropriate
4400 // one before.
4401 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
4402 return GV;
4404 // The RTTI TypeDescriptor uses an unqualified type but catch clauses must
4405 // be at least as CV qualified. Encode this requirement into the Flags
4406 // bitfield.
4407 uint32_t Flags = 0;
4408 if (IsConst)
4409 Flags |= 1;
4410 if (IsVolatile)
4411 Flags |= 2;
4412 if (IsUnaligned)
4413 Flags |= 4;
4415 // The cleanup-function (a destructor) must be called when the exception
4416 // object's lifetime ends.
4417 llvm::Constant *CleanupFn = llvm::Constant::getNullValue(CGM.Int8PtrTy);
4418 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4419 if (CXXDestructorDecl *DtorD = RD->getDestructor())
4420 if (!DtorD->isTrivial())
4421 CleanupFn = llvm::ConstantExpr::getBitCast(
4422 CGM.getAddrOfCXXStructor(GlobalDecl(DtorD, Dtor_Complete)),
4423 CGM.Int8PtrTy);
4424 // This is unused as far as we can tell, initialize it to null.
4425 llvm::Constant *ForwardCompat =
4426 getImageRelativeConstant(llvm::Constant::getNullValue(CGM.Int8PtrTy));
4427 llvm::Constant *PointerToCatchableTypes = getImageRelativeConstant(
4428 llvm::ConstantExpr::getBitCast(CTA, CGM.Int8PtrTy));
4429 llvm::StructType *TIType = getThrowInfoType();
4430 llvm::Constant *Fields[] = {
4431 llvm::ConstantInt::get(CGM.IntTy, Flags), // Flags
4432 getImageRelativeConstant(CleanupFn), // CleanupFn
4433 ForwardCompat, // ForwardCompat
4434 PointerToCatchableTypes // CatchableTypeArray
4436 auto *GV = new llvm::GlobalVariable(
4437 CGM.getModule(), TIType, /*isConstant=*/true, getLinkageForRTTI(T),
4438 llvm::ConstantStruct::get(TIType, Fields), MangledName.str());
4439 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4440 GV->setSection(".xdata");
4441 if (GV->isWeakForLinker())
4442 GV->setComdat(CGM.getModule().getOrInsertComdat(GV->getName()));
4443 return GV;
4446 void MicrosoftCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
4447 const Expr *SubExpr = E->getSubExpr();
4448 assert(SubExpr && "SubExpr cannot be null");
4449 QualType ThrowType = SubExpr->getType();
4450 // The exception object lives on the stack and it's address is passed to the
4451 // runtime function.
4452 Address AI = CGF.CreateMemTemp(ThrowType);
4453 CGF.EmitAnyExprToMem(SubExpr, AI, ThrowType.getQualifiers(),
4454 /*IsInit=*/true);
4456 // The so-called ThrowInfo is used to describe how the exception object may be
4457 // caught.
4458 llvm::GlobalVariable *TI = getThrowInfo(ThrowType);
4460 // Call into the runtime to throw the exception.
4461 llvm::Value *Args[] = {
4462 CGF.Builder.CreateBitCast(AI.getPointer(), CGM.Int8PtrTy),
4465 CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(), Args);
4468 std::pair<llvm::Value *, const CXXRecordDecl *>
4469 MicrosoftCXXABI::LoadVTablePtr(CodeGenFunction &CGF, Address This,
4470 const CXXRecordDecl *RD) {
4471 std::tie(This, std::ignore, RD) =
4472 performBaseAdjustment(CGF, This, QualType(RD->getTypeForDecl(), 0));
4473 return {CGF.GetVTablePtr(This, CGM.Int8PtrTy, RD), RD};
4476 bool MicrosoftCXXABI::isPermittedToBeHomogeneousAggregate(
4477 const CXXRecordDecl *CXXRD) const {
4478 // MSVC Windows on Arm64 considers a type not HFA if it is not an
4479 // aggregate according to the C++14 spec. This is not consistent with the
4480 // AAPCS64, but is defacto spec on that platform.
4481 return !CGM.getTarget().getTriple().isAArch64() ||
4482 isTrivialForAArch64MSVC(CXXRD);