[AMDGPU][AsmParser][NFC] Get rid of custom default operand handlers.
[llvm-project.git] / clang / lib / CodeGen / MicrosoftCXXABI.cpp
blobe5a2b35c0b3967670e391cdd3ebb6991cd056611
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 *getThisArgumentTypeForMethod(GlobalDecl GD) override {
239 auto *MD = cast<CXXMethodDecl>(GD.getDecl());
241 if (MD->isVirtual()) {
242 GlobalDecl LookupGD = GD;
243 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
244 // Complete dtors take a pointer to the complete object,
245 // thus don't need adjustment.
246 if (GD.getDtorType() == Dtor_Complete)
247 return MD->getParent();
249 // There's only Dtor_Deleting in vftable but it shares the this
250 // adjustment with the base one, so look up the deleting one instead.
251 LookupGD = GlobalDecl(DD, Dtor_Deleting);
253 MethodVFTableLocation ML =
254 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD);
256 // The vbases might be ordered differently in the final overrider object
257 // and the complete object, so the "this" argument may sometimes point to
258 // memory that has no particular type (e.g. past the complete object).
259 // In this case, we just use a generic pointer type.
260 // FIXME: might want to have a more precise type in the non-virtual
261 // multiple inheritance case.
262 if (ML.VBase || !ML.VFPtrOffset.isZero())
263 return nullptr;
265 return MD->getParent();
268 Address
269 adjustThisArgumentForVirtualFunctionCall(CodeGenFunction &CGF, GlobalDecl GD,
270 Address This,
271 bool VirtualCall) override;
273 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
274 FunctionArgList &Params) override;
276 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
278 AddedStructorArgs getImplicitConstructorArgs(CodeGenFunction &CGF,
279 const CXXConstructorDecl *D,
280 CXXCtorType Type,
281 bool ForVirtualBase,
282 bool Delegating) override;
284 llvm::Value *getCXXDestructorImplicitParam(CodeGenFunction &CGF,
285 const CXXDestructorDecl *DD,
286 CXXDtorType Type,
287 bool ForVirtualBase,
288 bool Delegating) override;
290 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
291 CXXDtorType Type, bool ForVirtualBase,
292 bool Delegating, Address This,
293 QualType ThisTy) override;
295 void emitVTableTypeMetadata(const VPtrInfo &Info, const CXXRecordDecl *RD,
296 llvm::GlobalVariable *VTable);
298 void emitVTableDefinitions(CodeGenVTables &CGVT,
299 const CXXRecordDecl *RD) override;
301 bool isVirtualOffsetNeededForVTableField(CodeGenFunction &CGF,
302 CodeGenFunction::VPtr Vptr) override;
304 /// Don't initialize vptrs if dynamic class
305 /// is marked with the 'novtable' attribute.
306 bool doStructorsInitializeVPtrs(const CXXRecordDecl *VTableClass) override {
307 return !VTableClass->hasAttr<MSNoVTableAttr>();
310 llvm::Constant *
311 getVTableAddressPoint(BaseSubobject Base,
312 const CXXRecordDecl *VTableClass) override;
314 llvm::Value *getVTableAddressPointInStructor(
315 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
316 BaseSubobject Base, const CXXRecordDecl *NearestVBase) override;
318 llvm::Constant *
319 getVTableAddressPointForConstExpr(BaseSubobject Base,
320 const CXXRecordDecl *VTableClass) override;
322 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
323 CharUnits VPtrOffset) override;
325 CGCallee getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
326 Address This, llvm::Type *Ty,
327 SourceLocation Loc) override;
329 llvm::Value *EmitVirtualDestructorCall(CodeGenFunction &CGF,
330 const CXXDestructorDecl *Dtor,
331 CXXDtorType DtorType, Address This,
332 DeleteOrMemberCallExpr E) override;
334 void adjustCallArgsForDestructorThunk(CodeGenFunction &CGF, GlobalDecl GD,
335 CallArgList &CallArgs) override {
336 assert(GD.getDtorType() == Dtor_Deleting &&
337 "Only deleting destructor thunks are available in this ABI");
338 CallArgs.add(RValue::get(getStructorImplicitParamValue(CGF)),
339 getContext().IntTy);
342 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
344 llvm::GlobalVariable *
345 getAddrOfVBTable(const VPtrInfo &VBT, const CXXRecordDecl *RD,
346 llvm::GlobalVariable::LinkageTypes Linkage);
348 llvm::GlobalVariable *
349 getAddrOfVirtualDisplacementMap(const CXXRecordDecl *SrcRD,
350 const CXXRecordDecl *DstRD) {
351 SmallString<256> OutName;
352 llvm::raw_svector_ostream Out(OutName);
353 getMangleContext().mangleCXXVirtualDisplacementMap(SrcRD, DstRD, Out);
354 StringRef MangledName = OutName.str();
356 if (auto *VDispMap = CGM.getModule().getNamedGlobal(MangledName))
357 return VDispMap;
359 MicrosoftVTableContext &VTContext = CGM.getMicrosoftVTableContext();
360 unsigned NumEntries = 1 + SrcRD->getNumVBases();
361 SmallVector<llvm::Constant *, 4> Map(NumEntries,
362 llvm::UndefValue::get(CGM.IntTy));
363 Map[0] = llvm::ConstantInt::get(CGM.IntTy, 0);
364 bool AnyDifferent = false;
365 for (const auto &I : SrcRD->vbases()) {
366 const CXXRecordDecl *VBase = I.getType()->getAsCXXRecordDecl();
367 if (!DstRD->isVirtuallyDerivedFrom(VBase))
368 continue;
370 unsigned SrcVBIndex = VTContext.getVBTableIndex(SrcRD, VBase);
371 unsigned DstVBIndex = VTContext.getVBTableIndex(DstRD, VBase);
372 Map[SrcVBIndex] = llvm::ConstantInt::get(CGM.IntTy, DstVBIndex * 4);
373 AnyDifferent |= SrcVBIndex != DstVBIndex;
375 // This map would be useless, don't use it.
376 if (!AnyDifferent)
377 return nullptr;
379 llvm::ArrayType *VDispMapTy = llvm::ArrayType::get(CGM.IntTy, Map.size());
380 llvm::Constant *Init = llvm::ConstantArray::get(VDispMapTy, Map);
381 llvm::GlobalValue::LinkageTypes Linkage =
382 SrcRD->isExternallyVisible() && DstRD->isExternallyVisible()
383 ? llvm::GlobalValue::LinkOnceODRLinkage
384 : llvm::GlobalValue::InternalLinkage;
385 auto *VDispMap = new llvm::GlobalVariable(
386 CGM.getModule(), VDispMapTy, /*isConstant=*/true, Linkage,
387 /*Initializer=*/Init, MangledName);
388 return VDispMap;
391 void emitVBTableDefinition(const VPtrInfo &VBT, const CXXRecordDecl *RD,
392 llvm::GlobalVariable *GV) const;
394 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable,
395 GlobalDecl GD, bool ReturnAdjustment) override {
396 GVALinkage Linkage =
397 getContext().GetGVALinkageForFunction(cast<FunctionDecl>(GD.getDecl()));
399 if (Linkage == GVA_Internal)
400 Thunk->setLinkage(llvm::GlobalValue::InternalLinkage);
401 else if (ReturnAdjustment)
402 Thunk->setLinkage(llvm::GlobalValue::WeakODRLinkage);
403 else
404 Thunk->setLinkage(llvm::GlobalValue::LinkOnceODRLinkage);
407 bool exportThunk() override { return false; }
409 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, Address This,
410 const ThisAdjustment &TA) override;
412 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
413 const ReturnAdjustment &RA) override;
415 void EmitThreadLocalInitFuncs(
416 CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
417 ArrayRef<llvm::Function *> CXXThreadLocalInits,
418 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) override;
420 bool usesThreadWrapperFunction(const VarDecl *VD) const override {
421 return getContext().getLangOpts().isCompatibleWithMSVC(
422 LangOptions::MSVC2019_5) &&
423 (!isEmittedWithConstantInitializer(VD) || mayNeedDestruction(VD));
425 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
426 QualType LValType) override;
428 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
429 llvm::GlobalVariable *DeclPtr,
430 bool PerformInit) override;
431 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
432 llvm::FunctionCallee Dtor,
433 llvm::Constant *Addr) override;
435 // ==== Notes on array cookies =========
437 // MSVC seems to only use cookies when the class has a destructor; a
438 // two-argument usual array deallocation function isn't sufficient.
440 // For example, this code prints "100" and "1":
441 // struct A {
442 // char x;
443 // void *operator new[](size_t sz) {
444 // printf("%u\n", sz);
445 // return malloc(sz);
446 // }
447 // void operator delete[](void *p, size_t sz) {
448 // printf("%u\n", sz);
449 // free(p);
450 // }
451 // };
452 // int main() {
453 // A *p = new A[100];
454 // delete[] p;
455 // }
456 // Whereas it prints "104" and "104" if you give A a destructor.
458 bool requiresArrayCookie(const CXXDeleteExpr *expr,
459 QualType elementType) override;
460 bool requiresArrayCookie(const CXXNewExpr *expr) override;
461 CharUnits getArrayCookieSizeImpl(QualType type) override;
462 Address InitializeArrayCookie(CodeGenFunction &CGF,
463 Address NewPtr,
464 llvm::Value *NumElements,
465 const CXXNewExpr *expr,
466 QualType ElementType) override;
467 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
468 Address allocPtr,
469 CharUnits cookieSize) override;
471 friend struct MSRTTIBuilder;
473 bool isImageRelative() const {
474 return CGM.getTarget().getPointerWidth(LangAS::Default) == 64;
477 // 5 routines for constructing the llvm types for MS RTTI structs.
478 llvm::StructType *getTypeDescriptorType(StringRef TypeInfoString) {
479 llvm::SmallString<32> TDTypeName("rtti.TypeDescriptor");
480 TDTypeName += llvm::utostr(TypeInfoString.size());
481 llvm::StructType *&TypeDescriptorType =
482 TypeDescriptorTypeMap[TypeInfoString.size()];
483 if (TypeDescriptorType)
484 return TypeDescriptorType;
485 llvm::Type *FieldTypes[] = {
486 CGM.Int8PtrPtrTy,
487 CGM.Int8PtrTy,
488 llvm::ArrayType::get(CGM.Int8Ty, TypeInfoString.size() + 1)};
489 TypeDescriptorType =
490 llvm::StructType::create(CGM.getLLVMContext(), FieldTypes, TDTypeName);
491 return TypeDescriptorType;
494 llvm::Type *getImageRelativeType(llvm::Type *PtrType) {
495 if (!isImageRelative())
496 return PtrType;
497 return CGM.IntTy;
500 llvm::StructType *getBaseClassDescriptorType() {
501 if (BaseClassDescriptorType)
502 return BaseClassDescriptorType;
503 llvm::Type *FieldTypes[] = {
504 getImageRelativeType(CGM.Int8PtrTy),
505 CGM.IntTy,
506 CGM.IntTy,
507 CGM.IntTy,
508 CGM.IntTy,
509 CGM.IntTy,
510 getImageRelativeType(getClassHierarchyDescriptorType()->getPointerTo()),
512 BaseClassDescriptorType = llvm::StructType::create(
513 CGM.getLLVMContext(), FieldTypes, "rtti.BaseClassDescriptor");
514 return BaseClassDescriptorType;
517 llvm::StructType *getClassHierarchyDescriptorType() {
518 if (ClassHierarchyDescriptorType)
519 return ClassHierarchyDescriptorType;
520 // Forward-declare RTTIClassHierarchyDescriptor to break a cycle.
521 ClassHierarchyDescriptorType = llvm::StructType::create(
522 CGM.getLLVMContext(), "rtti.ClassHierarchyDescriptor");
523 llvm::Type *FieldTypes[] = {
524 CGM.IntTy,
525 CGM.IntTy,
526 CGM.IntTy,
527 getImageRelativeType(
528 getBaseClassDescriptorType()->getPointerTo()->getPointerTo()),
530 ClassHierarchyDescriptorType->setBody(FieldTypes);
531 return ClassHierarchyDescriptorType;
534 llvm::StructType *getCompleteObjectLocatorType() {
535 if (CompleteObjectLocatorType)
536 return CompleteObjectLocatorType;
537 CompleteObjectLocatorType = llvm::StructType::create(
538 CGM.getLLVMContext(), "rtti.CompleteObjectLocator");
539 llvm::Type *FieldTypes[] = {
540 CGM.IntTy,
541 CGM.IntTy,
542 CGM.IntTy,
543 getImageRelativeType(CGM.Int8PtrTy),
544 getImageRelativeType(getClassHierarchyDescriptorType()->getPointerTo()),
545 getImageRelativeType(CompleteObjectLocatorType),
547 llvm::ArrayRef<llvm::Type *> FieldTypesRef(FieldTypes);
548 if (!isImageRelative())
549 FieldTypesRef = FieldTypesRef.drop_back();
550 CompleteObjectLocatorType->setBody(FieldTypesRef);
551 return CompleteObjectLocatorType;
554 llvm::GlobalVariable *getImageBase() {
555 StringRef Name = "__ImageBase";
556 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name))
557 return GV;
559 auto *GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty,
560 /*isConstant=*/true,
561 llvm::GlobalValue::ExternalLinkage,
562 /*Initializer=*/nullptr, Name);
563 CGM.setDSOLocal(GV);
564 return GV;
567 llvm::Constant *getImageRelativeConstant(llvm::Constant *PtrVal) {
568 if (!isImageRelative())
569 return PtrVal;
571 if (PtrVal->isNullValue())
572 return llvm::Constant::getNullValue(CGM.IntTy);
574 llvm::Constant *ImageBaseAsInt =
575 llvm::ConstantExpr::getPtrToInt(getImageBase(), CGM.IntPtrTy);
576 llvm::Constant *PtrValAsInt =
577 llvm::ConstantExpr::getPtrToInt(PtrVal, CGM.IntPtrTy);
578 llvm::Constant *Diff =
579 llvm::ConstantExpr::getSub(PtrValAsInt, ImageBaseAsInt,
580 /*HasNUW=*/true, /*HasNSW=*/true);
581 return llvm::ConstantExpr::getTrunc(Diff, CGM.IntTy);
584 private:
585 MicrosoftMangleContext &getMangleContext() {
586 return cast<MicrosoftMangleContext>(CodeGen::CGCXXABI::getMangleContext());
589 llvm::Constant *getZeroInt() {
590 return llvm::ConstantInt::get(CGM.IntTy, 0);
593 llvm::Constant *getAllOnesInt() {
594 return llvm::Constant::getAllOnesValue(CGM.IntTy);
597 CharUnits getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD) override;
599 void
600 GetNullMemberPointerFields(const MemberPointerType *MPT,
601 llvm::SmallVectorImpl<llvm::Constant *> &fields);
603 /// Shared code for virtual base adjustment. Returns the offset from
604 /// the vbptr to the virtual base. Optionally returns the address of the
605 /// vbptr itself.
606 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
607 Address Base,
608 llvm::Value *VBPtrOffset,
609 llvm::Value *VBTableOffset,
610 llvm::Value **VBPtr = nullptr);
612 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
613 Address Base,
614 int32_t VBPtrOffset,
615 int32_t VBTableOffset,
616 llvm::Value **VBPtr = nullptr) {
617 assert(VBTableOffset % 4 == 0 && "should be byte offset into table of i32s");
618 llvm::Value *VBPOffset = llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset),
619 *VBTOffset = llvm::ConstantInt::get(CGM.IntTy, VBTableOffset);
620 return GetVBaseOffsetFromVBPtr(CGF, Base, VBPOffset, VBTOffset, VBPtr);
623 std::tuple<Address, llvm::Value *, const CXXRecordDecl *>
624 performBaseAdjustment(CodeGenFunction &CGF, Address Value,
625 QualType SrcRecordTy);
627 /// Performs a full virtual base adjustment. Used to dereference
628 /// pointers to members of virtual bases.
629 llvm::Value *AdjustVirtualBase(CodeGenFunction &CGF, const Expr *E,
630 const CXXRecordDecl *RD, Address Base,
631 llvm::Value *VirtualBaseAdjustmentOffset,
632 llvm::Value *VBPtrOffset /* optional */);
634 /// Emits a full member pointer with the fields common to data and
635 /// function member pointers.
636 llvm::Constant *EmitFullMemberPointer(llvm::Constant *FirstField,
637 bool IsMemberFunction,
638 const CXXRecordDecl *RD,
639 CharUnits NonVirtualBaseAdjustment,
640 unsigned VBTableIndex);
642 bool MemberPointerConstantIsNull(const MemberPointerType *MPT,
643 llvm::Constant *MP);
645 /// - Initialize all vbptrs of 'this' with RD as the complete type.
646 void EmitVBPtrStores(CodeGenFunction &CGF, const CXXRecordDecl *RD);
648 /// Caching wrapper around VBTableBuilder::enumerateVBTables().
649 const VBTableGlobals &enumerateVBTables(const CXXRecordDecl *RD);
651 /// Generate a thunk for calling a virtual member function MD.
652 llvm::Function *EmitVirtualMemPtrThunk(const CXXMethodDecl *MD,
653 const MethodVFTableLocation &ML);
655 llvm::Constant *EmitMemberDataPointer(const CXXRecordDecl *RD,
656 CharUnits offset);
658 public:
659 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override;
661 bool isZeroInitializable(const MemberPointerType *MPT) override;
663 bool isMemberPointerConvertible(const MemberPointerType *MPT) const override {
664 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
665 return RD->hasAttr<MSInheritanceAttr>();
668 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override;
670 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
671 CharUnits offset) override;
672 llvm::Constant *EmitMemberFunctionPointer(const CXXMethodDecl *MD) override;
673 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override;
675 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
676 llvm::Value *L,
677 llvm::Value *R,
678 const MemberPointerType *MPT,
679 bool Inequality) override;
681 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
682 llvm::Value *MemPtr,
683 const MemberPointerType *MPT) override;
685 llvm::Value *
686 EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
687 Address Base, llvm::Value *MemPtr,
688 const MemberPointerType *MPT) override;
690 llvm::Value *EmitNonNullMemberPointerConversion(
691 const MemberPointerType *SrcTy, const MemberPointerType *DstTy,
692 CastKind CK, CastExpr::path_const_iterator PathBegin,
693 CastExpr::path_const_iterator PathEnd, llvm::Value *Src,
694 CGBuilderTy &Builder);
696 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
697 const CastExpr *E,
698 llvm::Value *Src) override;
700 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
701 llvm::Constant *Src) override;
703 llvm::Constant *EmitMemberPointerConversion(
704 const MemberPointerType *SrcTy, const MemberPointerType *DstTy,
705 CastKind CK, CastExpr::path_const_iterator PathBegin,
706 CastExpr::path_const_iterator PathEnd, llvm::Constant *Src);
708 CGCallee
709 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF, const Expr *E,
710 Address This, llvm::Value *&ThisPtrForCall,
711 llvm::Value *MemPtr,
712 const MemberPointerType *MPT) override;
714 void emitCXXStructor(GlobalDecl GD) override;
716 llvm::StructType *getCatchableTypeType() {
717 if (CatchableTypeType)
718 return CatchableTypeType;
719 llvm::Type *FieldTypes[] = {
720 CGM.IntTy, // Flags
721 getImageRelativeType(CGM.Int8PtrTy), // TypeDescriptor
722 CGM.IntTy, // NonVirtualAdjustment
723 CGM.IntTy, // OffsetToVBPtr
724 CGM.IntTy, // VBTableIndex
725 CGM.IntTy, // Size
726 getImageRelativeType(CGM.Int8PtrTy) // CopyCtor
728 CatchableTypeType = llvm::StructType::create(
729 CGM.getLLVMContext(), FieldTypes, "eh.CatchableType");
730 return CatchableTypeType;
733 llvm::StructType *getCatchableTypeArrayType(uint32_t NumEntries) {
734 llvm::StructType *&CatchableTypeArrayType =
735 CatchableTypeArrayTypeMap[NumEntries];
736 if (CatchableTypeArrayType)
737 return CatchableTypeArrayType;
739 llvm::SmallString<23> CTATypeName("eh.CatchableTypeArray.");
740 CTATypeName += llvm::utostr(NumEntries);
741 llvm::Type *CTType =
742 getImageRelativeType(getCatchableTypeType()->getPointerTo());
743 llvm::Type *FieldTypes[] = {
744 CGM.IntTy, // NumEntries
745 llvm::ArrayType::get(CTType, NumEntries) // CatchableTypes
747 CatchableTypeArrayType =
748 llvm::StructType::create(CGM.getLLVMContext(), FieldTypes, CTATypeName);
749 return CatchableTypeArrayType;
752 llvm::StructType *getThrowInfoType() {
753 if (ThrowInfoType)
754 return ThrowInfoType;
755 llvm::Type *FieldTypes[] = {
756 CGM.IntTy, // Flags
757 getImageRelativeType(CGM.Int8PtrTy), // CleanupFn
758 getImageRelativeType(CGM.Int8PtrTy), // ForwardCompat
759 getImageRelativeType(CGM.Int8PtrTy) // CatchableTypeArray
761 ThrowInfoType = llvm::StructType::create(CGM.getLLVMContext(), FieldTypes,
762 "eh.ThrowInfo");
763 return ThrowInfoType;
766 llvm::FunctionCallee getThrowFn() {
767 // _CxxThrowException is passed an exception object and a ThrowInfo object
768 // which describes the exception.
769 llvm::Type *Args[] = {CGM.Int8PtrTy, getThrowInfoType()->getPointerTo()};
770 llvm::FunctionType *FTy =
771 llvm::FunctionType::get(CGM.VoidTy, Args, /*isVarArg=*/false);
772 llvm::FunctionCallee Throw =
773 CGM.CreateRuntimeFunction(FTy, "_CxxThrowException");
774 // _CxxThrowException is stdcall on 32-bit x86 platforms.
775 if (CGM.getTarget().getTriple().getArch() == llvm::Triple::x86) {
776 if (auto *Fn = dyn_cast<llvm::Function>(Throw.getCallee()))
777 Fn->setCallingConv(llvm::CallingConv::X86_StdCall);
779 return Throw;
782 llvm::Function *getAddrOfCXXCtorClosure(const CXXConstructorDecl *CD,
783 CXXCtorType CT);
785 llvm::Constant *getCatchableType(QualType T,
786 uint32_t NVOffset = 0,
787 int32_t VBPtrOffset = -1,
788 uint32_t VBIndex = 0);
790 llvm::GlobalVariable *getCatchableTypeArray(QualType T);
792 llvm::GlobalVariable *getThrowInfo(QualType T) override;
794 std::pair<llvm::Value *, const CXXRecordDecl *>
795 LoadVTablePtr(CodeGenFunction &CGF, Address This,
796 const CXXRecordDecl *RD) override;
798 bool
799 isPermittedToBeHomogeneousAggregate(const CXXRecordDecl *RD) const override;
801 private:
802 typedef std::pair<const CXXRecordDecl *, CharUnits> VFTableIdTy;
803 typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalVariable *> VTablesMapTy;
804 typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalValue *> VFTablesMapTy;
805 /// All the vftables that have been referenced.
806 VFTablesMapTy VFTablesMap;
807 VTablesMapTy VTablesMap;
809 /// This set holds the record decls we've deferred vtable emission for.
810 llvm::SmallPtrSet<const CXXRecordDecl *, 4> DeferredVFTables;
813 /// All the vbtables which have been referenced.
814 llvm::DenseMap<const CXXRecordDecl *, VBTableGlobals> VBTablesMap;
816 /// Info on the global variable used to guard initialization of static locals.
817 /// The BitIndex field is only used for externally invisible declarations.
818 struct GuardInfo {
819 GuardInfo() : Guard(nullptr), BitIndex(0) {}
820 llvm::GlobalVariable *Guard;
821 unsigned BitIndex;
824 /// Map from DeclContext to the current guard variable. We assume that the
825 /// AST is visited in source code order.
826 llvm::DenseMap<const DeclContext *, GuardInfo> GuardVariableMap;
827 llvm::DenseMap<const DeclContext *, GuardInfo> ThreadLocalGuardVariableMap;
828 llvm::DenseMap<const DeclContext *, unsigned> ThreadSafeGuardNumMap;
830 llvm::DenseMap<size_t, llvm::StructType *> TypeDescriptorTypeMap;
831 llvm::StructType *BaseClassDescriptorType;
832 llvm::StructType *ClassHierarchyDescriptorType;
833 llvm::StructType *CompleteObjectLocatorType;
835 llvm::DenseMap<QualType, llvm::GlobalVariable *> CatchableTypeArrays;
837 llvm::StructType *CatchableTypeType;
838 llvm::DenseMap<uint32_t, llvm::StructType *> CatchableTypeArrayTypeMap;
839 llvm::StructType *ThrowInfoType;
844 CGCXXABI::RecordArgABI
845 MicrosoftCXXABI::getRecordArgABI(const CXXRecordDecl *RD) const {
846 // Use the default C calling convention rules for things that can be passed in
847 // registers, i.e. non-trivially copyable records or records marked with
848 // [[trivial_abi]].
849 if (RD->canPassInRegisters())
850 return RAA_Default;
852 switch (CGM.getTarget().getTriple().getArch()) {
853 default:
854 // FIXME: Implement for other architectures.
855 return RAA_Indirect;
857 case llvm::Triple::thumb:
858 // Pass things indirectly for now because it is simple.
859 // FIXME: This is incompatible with MSVC for arguments with a dtor and no
860 // copy ctor.
861 return RAA_Indirect;
863 case llvm::Triple::x86: {
864 // If the argument has *required* alignment greater than four bytes, pass
865 // it indirectly. Prior to MSVC version 19.14, passing overaligned
866 // arguments was not supported and resulted in a compiler error. In 19.14
867 // and later versions, such arguments are now passed indirectly.
868 TypeInfo Info = getContext().getTypeInfo(RD->getTypeForDecl());
869 if (Info.isAlignRequired() && Info.Align > 4)
870 return RAA_Indirect;
872 // If C++ prohibits us from making a copy, construct the arguments directly
873 // into argument memory.
874 return RAA_DirectInMemory;
877 case llvm::Triple::x86_64:
878 case llvm::Triple::aarch64:
879 return RAA_Indirect;
882 llvm_unreachable("invalid enum");
885 void MicrosoftCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
886 const CXXDeleteExpr *DE,
887 Address Ptr,
888 QualType ElementType,
889 const CXXDestructorDecl *Dtor) {
890 // FIXME: Provide a source location here even though there's no
891 // CXXMemberCallExpr for dtor call.
892 bool UseGlobalDelete = DE->isGlobalDelete();
893 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
894 llvm::Value *MDThis = EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, DE);
895 if (UseGlobalDelete)
896 CGF.EmitDeleteCall(DE->getOperatorDelete(), MDThis, ElementType);
899 void MicrosoftCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
900 llvm::Value *Args[] = {
901 llvm::ConstantPointerNull::get(CGM.Int8PtrTy),
902 llvm::ConstantPointerNull::get(getThrowInfoType()->getPointerTo())};
903 llvm::FunctionCallee Fn = getThrowFn();
904 if (isNoReturn)
905 CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, Args);
906 else
907 CGF.EmitRuntimeCallOrInvoke(Fn, Args);
910 void MicrosoftCXXABI::emitBeginCatch(CodeGenFunction &CGF,
911 const CXXCatchStmt *S) {
912 // In the MS ABI, the runtime handles the copy, and the catch handler is
913 // responsible for destruction.
914 VarDecl *CatchParam = S->getExceptionDecl();
915 llvm::BasicBlock *CatchPadBB = CGF.Builder.GetInsertBlock();
916 llvm::CatchPadInst *CPI =
917 cast<llvm::CatchPadInst>(CatchPadBB->getFirstNonPHI());
918 CGF.CurrentFuncletPad = CPI;
920 // If this is a catch-all or the catch parameter is unnamed, we don't need to
921 // emit an alloca to the object.
922 if (!CatchParam || !CatchParam->getDeclName()) {
923 CGF.EHStack.pushCleanup<CatchRetScope>(NormalCleanup, CPI);
924 return;
927 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
928 CPI->setArgOperand(2, var.getObjectAddress(CGF).getPointer());
929 CGF.EHStack.pushCleanup<CatchRetScope>(NormalCleanup, CPI);
930 CGF.EmitAutoVarCleanups(var);
933 /// We need to perform a generic polymorphic operation (like a typeid
934 /// or a cast), which requires an object with a vfptr. Adjust the
935 /// address to point to an object with a vfptr.
936 std::tuple<Address, llvm::Value *, const CXXRecordDecl *>
937 MicrosoftCXXABI::performBaseAdjustment(CodeGenFunction &CGF, Address Value,
938 QualType SrcRecordTy) {
939 Value = CGF.Builder.CreateElementBitCast(Value, CGF.Int8Ty);
940 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
941 const ASTContext &Context = getContext();
943 // If the class itself has a vfptr, great. This check implicitly
944 // covers non-virtual base subobjects: a class with its own virtual
945 // functions would be a candidate to be a primary base.
946 if (Context.getASTRecordLayout(SrcDecl).hasExtendableVFPtr())
947 return std::make_tuple(Value, llvm::ConstantInt::get(CGF.Int32Ty, 0),
948 SrcDecl);
950 // Okay, one of the vbases must have a vfptr, or else this isn't
951 // actually a polymorphic class.
952 const CXXRecordDecl *PolymorphicBase = nullptr;
953 for (auto &Base : SrcDecl->vbases()) {
954 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
955 if (Context.getASTRecordLayout(BaseDecl).hasExtendableVFPtr()) {
956 PolymorphicBase = BaseDecl;
957 break;
960 assert(PolymorphicBase && "polymorphic class has no apparent vfptr?");
962 llvm::Value *Offset =
963 GetVirtualBaseClassOffset(CGF, Value, SrcDecl, PolymorphicBase);
964 llvm::Value *Ptr = CGF.Builder.CreateInBoundsGEP(
965 Value.getElementType(), Value.getPointer(), Offset);
966 CharUnits VBaseAlign =
967 CGF.CGM.getVBaseAlignment(Value.getAlignment(), SrcDecl, PolymorphicBase);
968 return std::make_tuple(Address(Ptr, CGF.Int8Ty, VBaseAlign), Offset,
969 PolymorphicBase);
972 bool MicrosoftCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
973 QualType SrcRecordTy) {
974 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
975 return IsDeref &&
976 !getContext().getASTRecordLayout(SrcDecl).hasExtendableVFPtr();
979 static llvm::CallBase *emitRTtypeidCall(CodeGenFunction &CGF,
980 llvm::Value *Argument) {
981 llvm::Type *ArgTypes[] = {CGF.Int8PtrTy};
982 llvm::FunctionType *FTy =
983 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false);
984 llvm::Value *Args[] = {Argument};
985 llvm::FunctionCallee Fn = CGF.CGM.CreateRuntimeFunction(FTy, "__RTtypeid");
986 return CGF.EmitRuntimeCallOrInvoke(Fn, Args);
989 void MicrosoftCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
990 llvm::CallBase *Call =
991 emitRTtypeidCall(CGF, llvm::Constant::getNullValue(CGM.VoidPtrTy));
992 Call->setDoesNotReturn();
993 CGF.Builder.CreateUnreachable();
996 llvm::Value *MicrosoftCXXABI::EmitTypeid(CodeGenFunction &CGF,
997 QualType SrcRecordTy,
998 Address ThisPtr,
999 llvm::Type *StdTypeInfoPtrTy) {
1000 std::tie(ThisPtr, std::ignore, std::ignore) =
1001 performBaseAdjustment(CGF, ThisPtr, SrcRecordTy);
1002 llvm::CallBase *Typeid = emitRTtypeidCall(CGF, ThisPtr.getPointer());
1003 return CGF.Builder.CreateBitCast(Typeid, StdTypeInfoPtrTy);
1006 bool MicrosoftCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
1007 QualType SrcRecordTy) {
1008 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
1009 return SrcIsPtr &&
1010 !getContext().getASTRecordLayout(SrcDecl).hasExtendableVFPtr();
1013 llvm::Value *MicrosoftCXXABI::EmitDynamicCastCall(
1014 CodeGenFunction &CGF, Address This, QualType SrcRecordTy,
1015 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
1016 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1018 llvm::Value *SrcRTTI =
1019 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1020 llvm::Value *DestRTTI =
1021 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1023 llvm::Value *Offset;
1024 std::tie(This, Offset, std::ignore) =
1025 performBaseAdjustment(CGF, This, SrcRecordTy);
1026 llvm::Value *ThisPtr = This.getPointer();
1027 Offset = CGF.Builder.CreateTrunc(Offset, CGF.Int32Ty);
1029 // PVOID __RTDynamicCast(
1030 // PVOID inptr,
1031 // LONG VfDelta,
1032 // PVOID SrcType,
1033 // PVOID TargetType,
1034 // BOOL isReference)
1035 llvm::Type *ArgTypes[] = {CGF.Int8PtrTy, CGF.Int32Ty, CGF.Int8PtrTy,
1036 CGF.Int8PtrTy, CGF.Int32Ty};
1037 llvm::FunctionCallee Function = CGF.CGM.CreateRuntimeFunction(
1038 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false),
1039 "__RTDynamicCast");
1040 llvm::Value *Args[] = {
1041 ThisPtr, Offset, SrcRTTI, DestRTTI,
1042 llvm::ConstantInt::get(CGF.Int32Ty, DestTy->isReferenceType())};
1043 ThisPtr = CGF.EmitRuntimeCallOrInvoke(Function, Args);
1044 return CGF.Builder.CreateBitCast(ThisPtr, DestLTy);
1047 llvm::Value *
1048 MicrosoftCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF, Address Value,
1049 QualType SrcRecordTy,
1050 QualType DestTy) {
1051 std::tie(Value, std::ignore, std::ignore) =
1052 performBaseAdjustment(CGF, Value, SrcRecordTy);
1054 // PVOID __RTCastToVoid(
1055 // PVOID inptr)
1056 llvm::Type *ArgTypes[] = {CGF.Int8PtrTy};
1057 llvm::FunctionCallee Function = CGF.CGM.CreateRuntimeFunction(
1058 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false),
1059 "__RTCastToVoid");
1060 llvm::Value *Args[] = {Value.getPointer()};
1061 return CGF.EmitRuntimeCall(Function, Args);
1064 bool MicrosoftCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1065 return false;
1068 llvm::Value *MicrosoftCXXABI::GetVirtualBaseClassOffset(
1069 CodeGenFunction &CGF, Address This, const CXXRecordDecl *ClassDecl,
1070 const CXXRecordDecl *BaseClassDecl) {
1071 const ASTContext &Context = getContext();
1072 int64_t VBPtrChars =
1073 Context.getASTRecordLayout(ClassDecl).getVBPtrOffset().getQuantity();
1074 llvm::Value *VBPtrOffset = llvm::ConstantInt::get(CGM.PtrDiffTy, VBPtrChars);
1075 CharUnits IntSize = Context.getTypeSizeInChars(Context.IntTy);
1076 CharUnits VBTableChars =
1077 IntSize *
1078 CGM.getMicrosoftVTableContext().getVBTableIndex(ClassDecl, BaseClassDecl);
1079 llvm::Value *VBTableOffset =
1080 llvm::ConstantInt::get(CGM.IntTy, VBTableChars.getQuantity());
1082 llvm::Value *VBPtrToNewBase =
1083 GetVBaseOffsetFromVBPtr(CGF, This, VBPtrOffset, VBTableOffset);
1084 VBPtrToNewBase =
1085 CGF.Builder.CreateSExtOrBitCast(VBPtrToNewBase, CGM.PtrDiffTy);
1086 return CGF.Builder.CreateNSWAdd(VBPtrOffset, VBPtrToNewBase);
1089 bool MicrosoftCXXABI::HasThisReturn(GlobalDecl GD) const {
1090 return isa<CXXConstructorDecl>(GD.getDecl());
1093 static bool isDeletingDtor(GlobalDecl GD) {
1094 return isa<CXXDestructorDecl>(GD.getDecl()) &&
1095 GD.getDtorType() == Dtor_Deleting;
1098 bool MicrosoftCXXABI::hasMostDerivedReturn(GlobalDecl GD) const {
1099 return isDeletingDtor(GD);
1102 static bool isTrivialForMSVC(const CXXRecordDecl *RD) {
1103 // We use the C++14 definition of an aggregate, so we also
1104 // check for:
1105 // No private or protected non static data members.
1106 // No base classes
1107 // No virtual functions
1108 // Additionally, we need to ensure that there is a trivial copy assignment
1109 // operator, a trivial destructor and no user-provided constructors.
1110 if (RD->hasProtectedFields() || RD->hasPrivateFields())
1111 return false;
1112 if (RD->getNumBases() > 0)
1113 return false;
1114 if (RD->isPolymorphic())
1115 return false;
1116 if (RD->hasNonTrivialCopyAssignment())
1117 return false;
1118 for (const CXXConstructorDecl *Ctor : RD->ctors())
1119 if (Ctor->isUserProvided())
1120 return false;
1121 if (RD->hasNonTrivialDestructor())
1122 return false;
1123 return true;
1126 bool MicrosoftCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
1127 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
1128 if (!RD)
1129 return false;
1131 bool isTrivialForABI = RD->canPassInRegisters() && isTrivialForMSVC(RD);
1133 // MSVC always returns structs indirectly from C++ instance methods.
1134 bool isIndirectReturn = !isTrivialForABI || FI.isInstanceMethod();
1136 if (isIndirectReturn) {
1137 CharUnits Align = CGM.getContext().getTypeAlignInChars(FI.getReturnType());
1138 FI.getReturnInfo() = ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
1140 // MSVC always passes `this` before the `sret` parameter.
1141 FI.getReturnInfo().setSRetAfterThis(FI.isInstanceMethod());
1143 // On AArch64, use the `inreg` attribute if the object is considered to not
1144 // be trivially copyable, or if this is an instance method struct return.
1145 FI.getReturnInfo().setInReg(CGM.getTarget().getTriple().isAArch64());
1147 return true;
1150 // Otherwise, use the C ABI rules.
1151 return false;
1154 llvm::BasicBlock *
1155 MicrosoftCXXABI::EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
1156 const CXXRecordDecl *RD) {
1157 llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);
1158 assert(IsMostDerivedClass &&
1159 "ctor for a class with virtual bases must have an implicit parameter");
1160 llvm::Value *IsCompleteObject =
1161 CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");
1163 llvm::BasicBlock *CallVbaseCtorsBB = CGF.createBasicBlock("ctor.init_vbases");
1164 llvm::BasicBlock *SkipVbaseCtorsBB = CGF.createBasicBlock("ctor.skip_vbases");
1165 CGF.Builder.CreateCondBr(IsCompleteObject,
1166 CallVbaseCtorsBB, SkipVbaseCtorsBB);
1168 CGF.EmitBlock(CallVbaseCtorsBB);
1170 // Fill in the vbtable pointers here.
1171 EmitVBPtrStores(CGF, RD);
1173 // CGF will put the base ctor calls in this basic block for us later.
1175 return SkipVbaseCtorsBB;
1178 llvm::BasicBlock *
1179 MicrosoftCXXABI::EmitDtorCompleteObjectHandler(CodeGenFunction &CGF) {
1180 llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);
1181 assert(IsMostDerivedClass &&
1182 "ctor for a class with virtual bases must have an implicit parameter");
1183 llvm::Value *IsCompleteObject =
1184 CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");
1186 llvm::BasicBlock *CallVbaseDtorsBB = CGF.createBasicBlock("Dtor.dtor_vbases");
1187 llvm::BasicBlock *SkipVbaseDtorsBB = CGF.createBasicBlock("Dtor.skip_vbases");
1188 CGF.Builder.CreateCondBr(IsCompleteObject,
1189 CallVbaseDtorsBB, SkipVbaseDtorsBB);
1191 CGF.EmitBlock(CallVbaseDtorsBB);
1192 // CGF will put the base dtor calls in this basic block for us later.
1194 return SkipVbaseDtorsBB;
1197 void MicrosoftCXXABI::initializeHiddenVirtualInheritanceMembers(
1198 CodeGenFunction &CGF, const CXXRecordDecl *RD) {
1199 // In most cases, an override for a vbase virtual method can adjust
1200 // the "this" parameter by applying a constant offset.
1201 // However, this is not enough while a constructor or a destructor of some
1202 // class X is being executed if all the following conditions are met:
1203 // - X has virtual bases, (1)
1204 // - X overrides a virtual method M of a vbase Y, (2)
1205 // - X itself is a vbase of the most derived class.
1207 // If (1) and (2) are true, the vtorDisp for vbase Y is a hidden member of X
1208 // which holds the extra amount of "this" adjustment we must do when we use
1209 // the X vftables (i.e. during X ctor or dtor).
1210 // Outside the ctors and dtors, the values of vtorDisps are zero.
1212 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1213 typedef ASTRecordLayout::VBaseOffsetsMapTy VBOffsets;
1214 const VBOffsets &VBaseMap = Layout.getVBaseOffsetsMap();
1215 CGBuilderTy &Builder = CGF.Builder;
1217 unsigned AS = getThisAddress(CGF).getAddressSpace();
1218 llvm::Value *Int8This = nullptr; // Initialize lazily.
1220 for (const CXXBaseSpecifier &S : RD->vbases()) {
1221 const CXXRecordDecl *VBase = S.getType()->getAsCXXRecordDecl();
1222 auto I = VBaseMap.find(VBase);
1223 assert(I != VBaseMap.end());
1224 if (!I->second.hasVtorDisp())
1225 continue;
1227 llvm::Value *VBaseOffset =
1228 GetVirtualBaseClassOffset(CGF, getThisAddress(CGF), RD, VBase);
1229 uint64_t ConstantVBaseOffset = I->second.VBaseOffset.getQuantity();
1231 // vtorDisp_for_vbase = vbptr[vbase_idx] - offsetof(RD, vbase).
1232 llvm::Value *VtorDispValue = Builder.CreateSub(
1233 VBaseOffset, llvm::ConstantInt::get(CGM.PtrDiffTy, ConstantVBaseOffset),
1234 "vtordisp.value");
1235 VtorDispValue = Builder.CreateTruncOrBitCast(VtorDispValue, CGF.Int32Ty);
1237 if (!Int8This)
1238 Int8This = Builder.CreateBitCast(getThisValue(CGF),
1239 CGF.Int8Ty->getPointerTo(AS));
1240 llvm::Value *VtorDispPtr =
1241 Builder.CreateInBoundsGEP(CGF.Int8Ty, Int8This, VBaseOffset);
1242 // vtorDisp is always the 32-bits before the vbase in the class layout.
1243 VtorDispPtr = Builder.CreateConstGEP1_32(CGF.Int8Ty, VtorDispPtr, -4);
1244 VtorDispPtr = Builder.CreateBitCast(
1245 VtorDispPtr, CGF.Int32Ty->getPointerTo(AS), "vtordisp.ptr");
1247 Builder.CreateAlignedStore(VtorDispValue, VtorDispPtr,
1248 CharUnits::fromQuantity(4));
1252 static bool hasDefaultCXXMethodCC(ASTContext &Context,
1253 const CXXMethodDecl *MD) {
1254 CallingConv ExpectedCallingConv = Context.getDefaultCallingConvention(
1255 /*IsVariadic=*/false, /*IsCXXMethod=*/true);
1256 CallingConv ActualCallingConv =
1257 MD->getType()->castAs<FunctionProtoType>()->getCallConv();
1258 return ExpectedCallingConv == ActualCallingConv;
1261 void MicrosoftCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1262 // There's only one constructor type in this ABI.
1263 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1265 // Exported default constructors either have a simple call-site where they use
1266 // the typical calling convention and have a single 'this' pointer for an
1267 // argument -or- they get a wrapper function which appropriately thunks to the
1268 // real default constructor. This thunk is the default constructor closure.
1269 if (D->hasAttr<DLLExportAttr>() && D->isDefaultConstructor() &&
1270 D->isDefined()) {
1271 if (!hasDefaultCXXMethodCC(getContext(), D) || D->getNumParams() != 0) {
1272 llvm::Function *Fn = getAddrOfCXXCtorClosure(D, Ctor_DefaultClosure);
1273 Fn->setLinkage(llvm::GlobalValue::WeakODRLinkage);
1274 CGM.setGVProperties(Fn, D);
1279 void MicrosoftCXXABI::EmitVBPtrStores(CodeGenFunction &CGF,
1280 const CXXRecordDecl *RD) {
1281 Address This = getThisAddress(CGF);
1282 This = CGF.Builder.CreateElementBitCast(This, CGM.Int8Ty, "this.int8");
1283 const ASTContext &Context = getContext();
1284 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1286 const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
1287 for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) {
1288 const std::unique_ptr<VPtrInfo> &VBT = (*VBGlobals.VBTables)[I];
1289 llvm::GlobalVariable *GV = VBGlobals.Globals[I];
1290 const ASTRecordLayout &SubobjectLayout =
1291 Context.getASTRecordLayout(VBT->IntroducingObject);
1292 CharUnits Offs = VBT->NonVirtualOffset;
1293 Offs += SubobjectLayout.getVBPtrOffset();
1294 if (VBT->getVBaseWithVPtr())
1295 Offs += Layout.getVBaseClassOffset(VBT->getVBaseWithVPtr());
1296 Address VBPtr = CGF.Builder.CreateConstInBoundsByteGEP(This, Offs);
1297 llvm::Value *GVPtr =
1298 CGF.Builder.CreateConstInBoundsGEP2_32(GV->getValueType(), GV, 0, 0);
1299 VBPtr = CGF.Builder.CreateElementBitCast(VBPtr, GVPtr->getType(),
1300 "vbptr." + VBT->ObjectWithVPtr->getName());
1301 CGF.Builder.CreateStore(GVPtr, VBPtr);
1305 CGCXXABI::AddedStructorArgCounts
1306 MicrosoftCXXABI::buildStructorSignature(GlobalDecl GD,
1307 SmallVectorImpl<CanQualType> &ArgTys) {
1308 AddedStructorArgCounts Added;
1309 // TODO: 'for base' flag
1310 if (isa<CXXDestructorDecl>(GD.getDecl()) &&
1311 GD.getDtorType() == Dtor_Deleting) {
1312 // The scalar deleting destructor takes an implicit int parameter.
1313 ArgTys.push_back(getContext().IntTy);
1314 ++Added.Suffix;
1316 auto *CD = dyn_cast<CXXConstructorDecl>(GD.getDecl());
1317 if (!CD)
1318 return Added;
1320 // All parameters are already in place except is_most_derived, which goes
1321 // after 'this' if it's variadic and last if it's not.
1323 const CXXRecordDecl *Class = CD->getParent();
1324 const FunctionProtoType *FPT = CD->getType()->castAs<FunctionProtoType>();
1325 if (Class->getNumVBases()) {
1326 if (FPT->isVariadic()) {
1327 ArgTys.insert(ArgTys.begin() + 1, getContext().IntTy);
1328 ++Added.Prefix;
1329 } else {
1330 ArgTys.push_back(getContext().IntTy);
1331 ++Added.Suffix;
1335 return Added;
1338 void MicrosoftCXXABI::setCXXDestructorDLLStorage(llvm::GlobalValue *GV,
1339 const CXXDestructorDecl *Dtor,
1340 CXXDtorType DT) const {
1341 // Deleting destructor variants are never imported or exported. Give them the
1342 // default storage class.
1343 if (DT == Dtor_Deleting) {
1344 GV->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
1345 } else {
1346 const NamedDecl *ND = Dtor;
1347 CGM.setDLLImportDLLExport(GV, ND);
1351 llvm::GlobalValue::LinkageTypes MicrosoftCXXABI::getCXXDestructorLinkage(
1352 GVALinkage Linkage, const CXXDestructorDecl *Dtor, CXXDtorType DT) const {
1353 // Internal things are always internal, regardless of attributes. After this,
1354 // we know the thunk is externally visible.
1355 if (Linkage == GVA_Internal)
1356 return llvm::GlobalValue::InternalLinkage;
1358 switch (DT) {
1359 case Dtor_Base:
1360 // The base destructor most closely tracks the user-declared constructor, so
1361 // we delegate back to the normal declarator case.
1362 return CGM.getLLVMLinkageForDeclarator(Dtor, Linkage,
1363 /*IsConstantVariable=*/false);
1364 case Dtor_Complete:
1365 // The complete destructor is like an inline function, but it may be
1366 // imported and therefore must be exported as well. This requires changing
1367 // the linkage if a DLL attribute is present.
1368 if (Dtor->hasAttr<DLLExportAttr>())
1369 return llvm::GlobalValue::WeakODRLinkage;
1370 if (Dtor->hasAttr<DLLImportAttr>())
1371 return llvm::GlobalValue::AvailableExternallyLinkage;
1372 return llvm::GlobalValue::LinkOnceODRLinkage;
1373 case Dtor_Deleting:
1374 // Deleting destructors are like inline functions. They have vague linkage
1375 // and are emitted everywhere they are used. They are internal if the class
1376 // is internal.
1377 return llvm::GlobalValue::LinkOnceODRLinkage;
1378 case Dtor_Comdat:
1379 llvm_unreachable("MS C++ ABI does not support comdat dtors");
1381 llvm_unreachable("invalid dtor type");
1384 void MicrosoftCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
1385 // The TU defining a dtor is only guaranteed to emit a base destructor. All
1386 // other destructor variants are delegating thunks.
1387 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
1389 // If the class is dllexported, emit the complete (vbase) destructor wherever
1390 // the base dtor is emitted.
1391 // FIXME: To match MSVC, this should only be done when the class is exported
1392 // with -fdllexport-inlines enabled.
1393 if (D->getParent()->getNumVBases() > 0 && D->hasAttr<DLLExportAttr>())
1394 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
1397 CharUnits
1398 MicrosoftCXXABI::getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD) {
1399 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1401 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1402 // Complete destructors take a pointer to the complete object as a
1403 // parameter, thus don't need this adjustment.
1404 if (GD.getDtorType() == Dtor_Complete)
1405 return CharUnits();
1407 // There's no Dtor_Base in vftable but it shares the this adjustment with
1408 // the deleting one, so look it up instead.
1409 GD = GlobalDecl(DD, Dtor_Deleting);
1412 MethodVFTableLocation ML =
1413 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD);
1414 CharUnits Adjustment = ML.VFPtrOffset;
1416 // Normal virtual instance methods need to adjust from the vfptr that first
1417 // defined the virtual method to the virtual base subobject, but destructors
1418 // do not. The vector deleting destructor thunk applies this adjustment for
1419 // us if necessary.
1420 if (isa<CXXDestructorDecl>(MD))
1421 Adjustment = CharUnits::Zero();
1423 if (ML.VBase) {
1424 const ASTRecordLayout &DerivedLayout =
1425 getContext().getASTRecordLayout(MD->getParent());
1426 Adjustment += DerivedLayout.getVBaseClassOffset(ML.VBase);
1429 return Adjustment;
1432 Address MicrosoftCXXABI::adjustThisArgumentForVirtualFunctionCall(
1433 CodeGenFunction &CGF, GlobalDecl GD, Address This,
1434 bool VirtualCall) {
1435 if (!VirtualCall) {
1436 // If the call of a virtual function is not virtual, we just have to
1437 // compensate for the adjustment the virtual function does in its prologue.
1438 CharUnits Adjustment = getVirtualFunctionPrologueThisAdjustment(GD);
1439 if (Adjustment.isZero())
1440 return This;
1442 This = CGF.Builder.CreateElementBitCast(This, CGF.Int8Ty);
1443 assert(Adjustment.isPositive());
1444 return CGF.Builder.CreateConstByteGEP(This, Adjustment);
1447 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1449 GlobalDecl LookupGD = GD;
1450 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1451 // Complete dtors take a pointer to the complete object,
1452 // thus don't need adjustment.
1453 if (GD.getDtorType() == Dtor_Complete)
1454 return This;
1456 // There's only Dtor_Deleting in vftable but it shares the this adjustment
1457 // with the base one, so look up the deleting one instead.
1458 LookupGD = GlobalDecl(DD, Dtor_Deleting);
1460 MethodVFTableLocation ML =
1461 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD);
1463 CharUnits StaticOffset = ML.VFPtrOffset;
1465 // Base destructors expect 'this' to point to the beginning of the base
1466 // subobject, not the first vfptr that happens to contain the virtual dtor.
1467 // However, we still need to apply the virtual base adjustment.
1468 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
1469 StaticOffset = CharUnits::Zero();
1471 Address Result = This;
1472 if (ML.VBase) {
1473 Result = CGF.Builder.CreateElementBitCast(Result, CGF.Int8Ty);
1475 const CXXRecordDecl *Derived = MD->getParent();
1476 const CXXRecordDecl *VBase = ML.VBase;
1477 llvm::Value *VBaseOffset =
1478 GetVirtualBaseClassOffset(CGF, Result, Derived, VBase);
1479 llvm::Value *VBasePtr = CGF.Builder.CreateInBoundsGEP(
1480 Result.getElementType(), Result.getPointer(), VBaseOffset);
1481 CharUnits VBaseAlign =
1482 CGF.CGM.getVBaseAlignment(Result.getAlignment(), Derived, VBase);
1483 Result = Address(VBasePtr, CGF.Int8Ty, VBaseAlign);
1485 if (!StaticOffset.isZero()) {
1486 assert(StaticOffset.isPositive());
1487 Result = CGF.Builder.CreateElementBitCast(Result, CGF.Int8Ty);
1488 if (ML.VBase) {
1489 // Non-virtual adjustment might result in a pointer outside the allocated
1490 // object, e.g. if the final overrider class is laid out after the virtual
1491 // base that declares a method in the most derived class.
1492 // FIXME: Update the code that emits this adjustment in thunks prologues.
1493 Result = CGF.Builder.CreateConstByteGEP(Result, StaticOffset);
1494 } else {
1495 Result = CGF.Builder.CreateConstInBoundsByteGEP(Result, StaticOffset);
1498 return Result;
1501 void MicrosoftCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1502 QualType &ResTy,
1503 FunctionArgList &Params) {
1504 ASTContext &Context = getContext();
1505 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
1506 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
1507 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
1508 auto *IsMostDerived = ImplicitParamDecl::Create(
1509 Context, /*DC=*/nullptr, CGF.CurGD.getDecl()->getLocation(),
1510 &Context.Idents.get("is_most_derived"), Context.IntTy,
1511 ImplicitParamDecl::Other);
1512 // The 'most_derived' parameter goes second if the ctor is variadic and last
1513 // if it's not. Dtors can't be variadic.
1514 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
1515 if (FPT->isVariadic())
1516 Params.insert(Params.begin() + 1, IsMostDerived);
1517 else
1518 Params.push_back(IsMostDerived);
1519 getStructorImplicitParamDecl(CGF) = IsMostDerived;
1520 } else if (isDeletingDtor(CGF.CurGD)) {
1521 auto *ShouldDelete = ImplicitParamDecl::Create(
1522 Context, /*DC=*/nullptr, CGF.CurGD.getDecl()->getLocation(),
1523 &Context.Idents.get("should_call_delete"), Context.IntTy,
1524 ImplicitParamDecl::Other);
1525 Params.push_back(ShouldDelete);
1526 getStructorImplicitParamDecl(CGF) = ShouldDelete;
1530 void MicrosoftCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
1531 // Naked functions have no prolog.
1532 if (CGF.CurFuncDecl && CGF.CurFuncDecl->hasAttr<NakedAttr>())
1533 return;
1535 // Overridden virtual methods of non-primary bases need to adjust the incoming
1536 // 'this' pointer in the prologue. In this hierarchy, C::b will subtract
1537 // sizeof(void*) to adjust from B* to C*:
1538 // struct A { virtual void a(); };
1539 // struct B { virtual void b(); };
1540 // struct C : A, B { virtual void b(); };
1542 // Leave the value stored in the 'this' alloca unadjusted, so that the
1543 // debugger sees the unadjusted value. Microsoft debuggers require this, and
1544 // will apply the ThisAdjustment in the method type information.
1545 // FIXME: Do something better for DWARF debuggers, which won't expect this,
1546 // without making our codegen depend on debug info settings.
1547 llvm::Value *This = loadIncomingCXXThis(CGF);
1548 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
1549 if (!CGF.CurFuncIsThunk && MD->isVirtual()) {
1550 CharUnits Adjustment = getVirtualFunctionPrologueThisAdjustment(CGF.CurGD);
1551 if (!Adjustment.isZero()) {
1552 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
1553 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS),
1554 *thisTy = This->getType();
1555 This = CGF.Builder.CreateBitCast(This, charPtrTy);
1556 assert(Adjustment.isPositive());
1557 This = CGF.Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, This,
1558 -Adjustment.getQuantity());
1559 This = CGF.Builder.CreateBitCast(This, thisTy, "this.adjusted");
1562 setCXXABIThisValue(CGF, This);
1564 // If this is a function that the ABI specifies returns 'this', initialize
1565 // the return slot to 'this' at the start of the function.
1567 // Unlike the setting of return types, this is done within the ABI
1568 // implementation instead of by clients of CGCXXABI because:
1569 // 1) getThisValue is currently protected
1570 // 2) in theory, an ABI could implement 'this' returns some other way;
1571 // HasThisReturn only specifies a contract, not the implementation
1572 if (HasThisReturn(CGF.CurGD))
1573 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
1574 else if (hasMostDerivedReturn(CGF.CurGD))
1575 CGF.Builder.CreateStore(CGF.EmitCastToVoidPtr(getThisValue(CGF)),
1576 CGF.ReturnValue);
1578 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
1579 assert(getStructorImplicitParamDecl(CGF) &&
1580 "no implicit parameter for a constructor with virtual bases?");
1581 getStructorImplicitParamValue(CGF)
1582 = CGF.Builder.CreateLoad(
1583 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
1584 "is_most_derived");
1587 if (isDeletingDtor(CGF.CurGD)) {
1588 assert(getStructorImplicitParamDecl(CGF) &&
1589 "no implicit parameter for a deleting destructor?");
1590 getStructorImplicitParamValue(CGF)
1591 = CGF.Builder.CreateLoad(
1592 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
1593 "should_call_delete");
1597 CGCXXABI::AddedStructorArgs MicrosoftCXXABI::getImplicitConstructorArgs(
1598 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1599 bool ForVirtualBase, bool Delegating) {
1600 assert(Type == Ctor_Complete || Type == Ctor_Base);
1602 // Check if we need a 'most_derived' parameter.
1603 if (!D->getParent()->getNumVBases())
1604 return AddedStructorArgs{};
1606 // Add the 'most_derived' argument second if we are variadic or last if not.
1607 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
1608 llvm::Value *MostDerivedArg;
1609 if (Delegating) {
1610 MostDerivedArg = getStructorImplicitParamValue(CGF);
1611 } else {
1612 MostDerivedArg = llvm::ConstantInt::get(CGM.Int32Ty, Type == Ctor_Complete);
1614 if (FPT->isVariadic()) {
1615 return AddedStructorArgs::prefix({{MostDerivedArg, getContext().IntTy}});
1617 return AddedStructorArgs::suffix({{MostDerivedArg, getContext().IntTy}});
1620 llvm::Value *MicrosoftCXXABI::getCXXDestructorImplicitParam(
1621 CodeGenFunction &CGF, const CXXDestructorDecl *DD, CXXDtorType Type,
1622 bool ForVirtualBase, bool Delegating) {
1623 return nullptr;
1626 void MicrosoftCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1627 const CXXDestructorDecl *DD,
1628 CXXDtorType Type, bool ForVirtualBase,
1629 bool Delegating, Address This,
1630 QualType ThisTy) {
1631 // Use the base destructor variant in place of the complete destructor variant
1632 // if the class has no virtual bases. This effectively implements some of the
1633 // -mconstructor-aliases optimization, but as part of the MS C++ ABI.
1634 if (Type == Dtor_Complete && DD->getParent()->getNumVBases() == 0)
1635 Type = Dtor_Base;
1637 GlobalDecl GD(DD, Type);
1638 CGCallee Callee = CGCallee::forDirect(CGM.getAddrOfCXXStructor(GD), GD);
1640 if (DD->isVirtual()) {
1641 assert(Type != CXXDtorType::Dtor_Deleting &&
1642 "The deleting destructor should only be called via a virtual call");
1643 This = adjustThisArgumentForVirtualFunctionCall(CGF, GlobalDecl(DD, Type),
1644 This, false);
1647 llvm::BasicBlock *BaseDtorEndBB = nullptr;
1648 if (ForVirtualBase && isa<CXXConstructorDecl>(CGF.CurCodeDecl)) {
1649 BaseDtorEndBB = EmitDtorCompleteObjectHandler(CGF);
1652 llvm::Value *Implicit =
1653 getCXXDestructorImplicitParam(CGF, DD, Type, ForVirtualBase,
1654 Delegating); // = nullptr
1655 CGF.EmitCXXDestructorCall(GD, Callee, This.getPointer(), ThisTy,
1656 /*ImplicitParam=*/Implicit,
1657 /*ImplicitParamTy=*/QualType(), nullptr);
1658 if (BaseDtorEndBB) {
1659 // Complete object handler should continue to be the remaining
1660 CGF.Builder.CreateBr(BaseDtorEndBB);
1661 CGF.EmitBlock(BaseDtorEndBB);
1665 void MicrosoftCXXABI::emitVTableTypeMetadata(const VPtrInfo &Info,
1666 const CXXRecordDecl *RD,
1667 llvm::GlobalVariable *VTable) {
1668 if (!CGM.getCodeGenOpts().LTOUnit)
1669 return;
1671 // TODO: Should VirtualFunctionElimination also be supported here?
1672 // See similar handling in CodeGenModule::EmitVTableTypeMetadata.
1673 if (CGM.getCodeGenOpts().WholeProgramVTables) {
1674 llvm::DenseSet<const CXXRecordDecl *> Visited;
1675 llvm::GlobalObject::VCallVisibility TypeVis =
1676 CGM.GetVCallVisibilityLevel(RD, Visited);
1677 if (TypeVis != llvm::GlobalObject::VCallVisibilityPublic)
1678 VTable->setVCallVisibilityMetadata(TypeVis);
1681 // The location of the first virtual function pointer in the virtual table,
1682 // aka the "address point" on Itanium. This is at offset 0 if RTTI is
1683 // disabled, or sizeof(void*) if RTTI is enabled.
1684 CharUnits AddressPoint =
1685 getContext().getLangOpts().RTTIData
1686 ? getContext().toCharUnitsFromBits(
1687 getContext().getTargetInfo().getPointerWidth(LangAS::Default))
1688 : CharUnits::Zero();
1690 if (Info.PathToIntroducingObject.empty()) {
1691 CGM.AddVTableTypeMetadata(VTable, AddressPoint, RD);
1692 return;
1695 // Add a bitset entry for the least derived base belonging to this vftable.
1696 CGM.AddVTableTypeMetadata(VTable, AddressPoint,
1697 Info.PathToIntroducingObject.back());
1699 // Add a bitset entry for each derived class that is laid out at the same
1700 // offset as the least derived base.
1701 for (unsigned I = Info.PathToIntroducingObject.size() - 1; I != 0; --I) {
1702 const CXXRecordDecl *DerivedRD = Info.PathToIntroducingObject[I - 1];
1703 const CXXRecordDecl *BaseRD = Info.PathToIntroducingObject[I];
1705 const ASTRecordLayout &Layout =
1706 getContext().getASTRecordLayout(DerivedRD);
1707 CharUnits Offset;
1708 auto VBI = Layout.getVBaseOffsetsMap().find(BaseRD);
1709 if (VBI == Layout.getVBaseOffsetsMap().end())
1710 Offset = Layout.getBaseClassOffset(BaseRD);
1711 else
1712 Offset = VBI->second.VBaseOffset;
1713 if (!Offset.isZero())
1714 return;
1715 CGM.AddVTableTypeMetadata(VTable, AddressPoint, DerivedRD);
1718 // Finally do the same for the most derived class.
1719 if (Info.FullOffsetInMDC.isZero())
1720 CGM.AddVTableTypeMetadata(VTable, AddressPoint, RD);
1723 void MicrosoftCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1724 const CXXRecordDecl *RD) {
1725 MicrosoftVTableContext &VFTContext = CGM.getMicrosoftVTableContext();
1726 const VPtrInfoVector &VFPtrs = VFTContext.getVFPtrOffsets(RD);
1728 for (const std::unique_ptr<VPtrInfo>& Info : VFPtrs) {
1729 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, Info->FullOffsetInMDC);
1730 if (VTable->hasInitializer())
1731 continue;
1733 const VTableLayout &VTLayout =
1734 VFTContext.getVFTableLayout(RD, Info->FullOffsetInMDC);
1736 llvm::Constant *RTTI = nullptr;
1737 if (any_of(VTLayout.vtable_components(),
1738 [](const VTableComponent &VTC) { return VTC.isRTTIKind(); }))
1739 RTTI = getMSCompleteObjectLocator(RD, *Info);
1741 ConstantInitBuilder builder(CGM);
1742 auto components = builder.beginStruct();
1743 CGVT.createVTableInitializer(components, VTLayout, RTTI,
1744 VTable->hasLocalLinkage());
1745 components.finishAndSetAsInitializer(VTable);
1747 emitVTableTypeMetadata(*Info, RD, VTable);
1751 bool MicrosoftCXXABI::isVirtualOffsetNeededForVTableField(
1752 CodeGenFunction &CGF, CodeGenFunction::VPtr Vptr) {
1753 return Vptr.NearestVBase != nullptr;
1756 llvm::Value *MicrosoftCXXABI::getVTableAddressPointInStructor(
1757 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1758 const CXXRecordDecl *NearestVBase) {
1759 llvm::Constant *VTableAddressPoint = getVTableAddressPoint(Base, VTableClass);
1760 if (!VTableAddressPoint) {
1761 assert(Base.getBase()->getNumVBases() &&
1762 !getContext().getASTRecordLayout(Base.getBase()).hasOwnVFPtr());
1764 return VTableAddressPoint;
1767 static void mangleVFTableName(MicrosoftMangleContext &MangleContext,
1768 const CXXRecordDecl *RD, const VPtrInfo &VFPtr,
1769 SmallString<256> &Name) {
1770 llvm::raw_svector_ostream Out(Name);
1771 MangleContext.mangleCXXVFTable(RD, VFPtr.MangledPath, Out);
1774 llvm::Constant *
1775 MicrosoftCXXABI::getVTableAddressPoint(BaseSubobject Base,
1776 const CXXRecordDecl *VTableClass) {
1777 (void)getAddrOfVTable(VTableClass, Base.getBaseOffset());
1778 VFTableIdTy ID(VTableClass, Base.getBaseOffset());
1779 return VFTablesMap[ID];
1782 llvm::Constant *MicrosoftCXXABI::getVTableAddressPointForConstExpr(
1783 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1784 llvm::Constant *VFTable = getVTableAddressPoint(Base, VTableClass);
1785 assert(VFTable && "Couldn't find a vftable for the given base?");
1786 return VFTable;
1789 llvm::GlobalVariable *MicrosoftCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1790 CharUnits VPtrOffset) {
1791 // getAddrOfVTable may return 0 if asked to get an address of a vtable which
1792 // shouldn't be used in the given record type. We want to cache this result in
1793 // VFTablesMap, thus a simple zero check is not sufficient.
1795 VFTableIdTy ID(RD, VPtrOffset);
1796 VTablesMapTy::iterator I;
1797 bool Inserted;
1798 std::tie(I, Inserted) = VTablesMap.insert(std::make_pair(ID, nullptr));
1799 if (!Inserted)
1800 return I->second;
1802 llvm::GlobalVariable *&VTable = I->second;
1804 MicrosoftVTableContext &VTContext = CGM.getMicrosoftVTableContext();
1805 const VPtrInfoVector &VFPtrs = VTContext.getVFPtrOffsets(RD);
1807 if (DeferredVFTables.insert(RD).second) {
1808 // We haven't processed this record type before.
1809 // Queue up this vtable for possible deferred emission.
1810 CGM.addDeferredVTable(RD);
1812 #ifndef NDEBUG
1813 // Create all the vftables at once in order to make sure each vftable has
1814 // a unique mangled name.
1815 llvm::StringSet<> ObservedMangledNames;
1816 for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) {
1817 SmallString<256> Name;
1818 mangleVFTableName(getMangleContext(), RD, *VFPtrs[J], Name);
1819 if (!ObservedMangledNames.insert(Name.str()).second)
1820 llvm_unreachable("Already saw this mangling before?");
1822 #endif
1825 const std::unique_ptr<VPtrInfo> *VFPtrI =
1826 llvm::find_if(VFPtrs, [&](const std::unique_ptr<VPtrInfo> &VPI) {
1827 return VPI->FullOffsetInMDC == VPtrOffset;
1829 if (VFPtrI == VFPtrs.end()) {
1830 VFTablesMap[ID] = nullptr;
1831 return nullptr;
1833 const std::unique_ptr<VPtrInfo> &VFPtr = *VFPtrI;
1835 SmallString<256> VFTableName;
1836 mangleVFTableName(getMangleContext(), RD, *VFPtr, VFTableName);
1838 // Classes marked __declspec(dllimport) need vftables generated on the
1839 // import-side in order to support features like constexpr. No other
1840 // translation unit relies on the emission of the local vftable, translation
1841 // units are expected to generate them as needed.
1843 // Because of this unique behavior, we maintain this logic here instead of
1844 // getVTableLinkage.
1845 llvm::GlobalValue::LinkageTypes VFTableLinkage =
1846 RD->hasAttr<DLLImportAttr>() ? llvm::GlobalValue::LinkOnceODRLinkage
1847 : CGM.getVTableLinkage(RD);
1848 bool VFTableComesFromAnotherTU =
1849 llvm::GlobalValue::isAvailableExternallyLinkage(VFTableLinkage) ||
1850 llvm::GlobalValue::isExternalLinkage(VFTableLinkage);
1851 bool VTableAliasIsRequred =
1852 !VFTableComesFromAnotherTU && getContext().getLangOpts().RTTIData;
1854 if (llvm::GlobalValue *VFTable =
1855 CGM.getModule().getNamedGlobal(VFTableName)) {
1856 VFTablesMap[ID] = VFTable;
1857 VTable = VTableAliasIsRequred
1858 ? cast<llvm::GlobalVariable>(
1859 cast<llvm::GlobalAlias>(VFTable)->getAliaseeObject())
1860 : cast<llvm::GlobalVariable>(VFTable);
1861 return VTable;
1864 const VTableLayout &VTLayout =
1865 VTContext.getVFTableLayout(RD, VFPtr->FullOffsetInMDC);
1866 llvm::GlobalValue::LinkageTypes VTableLinkage =
1867 VTableAliasIsRequred ? llvm::GlobalValue::PrivateLinkage : VFTableLinkage;
1869 StringRef VTableName = VTableAliasIsRequred ? StringRef() : VFTableName.str();
1871 llvm::Type *VTableType = CGM.getVTables().getVTableType(VTLayout);
1873 // Create a backing variable for the contents of VTable. The VTable may
1874 // or may not include space for a pointer to RTTI data.
1875 llvm::GlobalValue *VFTable;
1876 VTable = new llvm::GlobalVariable(CGM.getModule(), VTableType,
1877 /*isConstant=*/true, VTableLinkage,
1878 /*Initializer=*/nullptr, VTableName);
1879 VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1881 llvm::Comdat *C = nullptr;
1882 if (!VFTableComesFromAnotherTU &&
1883 (llvm::GlobalValue::isWeakForLinker(VFTableLinkage) ||
1884 (llvm::GlobalValue::isLocalLinkage(VFTableLinkage) &&
1885 VTableAliasIsRequred)))
1886 C = CGM.getModule().getOrInsertComdat(VFTableName.str());
1888 // Only insert a pointer into the VFTable for RTTI data if we are not
1889 // importing it. We never reference the RTTI data directly so there is no
1890 // need to make room for it.
1891 if (VTableAliasIsRequred) {
1892 llvm::Value *GEPIndices[] = {llvm::ConstantInt::get(CGM.Int32Ty, 0),
1893 llvm::ConstantInt::get(CGM.Int32Ty, 0),
1894 llvm::ConstantInt::get(CGM.Int32Ty, 1)};
1895 // Create a GEP which points just after the first entry in the VFTable,
1896 // this should be the location of the first virtual method.
1897 llvm::Constant *VTableGEP = llvm::ConstantExpr::getInBoundsGetElementPtr(
1898 VTable->getValueType(), VTable, GEPIndices);
1899 if (llvm::GlobalValue::isWeakForLinker(VFTableLinkage)) {
1900 VFTableLinkage = llvm::GlobalValue::ExternalLinkage;
1901 if (C)
1902 C->setSelectionKind(llvm::Comdat::Largest);
1904 VFTable = llvm::GlobalAlias::create(CGM.Int8PtrTy,
1905 /*AddressSpace=*/0, VFTableLinkage,
1906 VFTableName.str(), VTableGEP,
1907 &CGM.getModule());
1908 VFTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1909 } else {
1910 // We don't need a GlobalAlias to be a symbol for the VTable if we won't
1911 // be referencing any RTTI data.
1912 // The GlobalVariable will end up being an appropriate definition of the
1913 // VFTable.
1914 VFTable = VTable;
1916 if (C)
1917 VTable->setComdat(C);
1919 if (RD->hasAttr<DLLExportAttr>())
1920 VFTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1922 VFTablesMap[ID] = VFTable;
1923 return VTable;
1926 CGCallee MicrosoftCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1927 GlobalDecl GD,
1928 Address This,
1929 llvm::Type *Ty,
1930 SourceLocation Loc) {
1931 CGBuilderTy &Builder = CGF.Builder;
1933 Ty = Ty->getPointerTo();
1934 Address VPtr =
1935 adjustThisArgumentForVirtualFunctionCall(CGF, GD, This, true);
1937 auto *MethodDecl = cast<CXXMethodDecl>(GD.getDecl());
1938 llvm::Value *VTable = CGF.GetVTablePtr(VPtr, Ty->getPointerTo(),
1939 MethodDecl->getParent());
1941 MicrosoftVTableContext &VFTContext = CGM.getMicrosoftVTableContext();
1942 MethodVFTableLocation ML = VFTContext.getMethodVFTableLocation(GD);
1944 // Compute the identity of the most derived class whose virtual table is
1945 // located at the MethodVFTableLocation ML.
1946 auto getObjectWithVPtr = [&] {
1947 return llvm::find_if(VFTContext.getVFPtrOffsets(
1948 ML.VBase ? ML.VBase : MethodDecl->getParent()),
1949 [&](const std::unique_ptr<VPtrInfo> &Info) {
1950 return Info->FullOffsetInMDC == ML.VFPtrOffset;
1952 ->get()
1953 ->ObjectWithVPtr;
1956 llvm::Value *VFunc;
1957 if (CGF.ShouldEmitVTableTypeCheckedLoad(MethodDecl->getParent())) {
1958 VFunc = CGF.EmitVTableTypeCheckedLoad(
1959 getObjectWithVPtr(), VTable, Ty,
1960 ML.Index *
1961 CGM.getContext().getTargetInfo().getPointerWidth(LangAS::Default) /
1963 } else {
1964 if (CGM.getCodeGenOpts().PrepareForLTO)
1965 CGF.EmitTypeMetadataCodeForVCall(getObjectWithVPtr(), VTable, Loc);
1967 llvm::Value *VFuncPtr =
1968 Builder.CreateConstInBoundsGEP1_64(Ty, VTable, ML.Index, "vfn");
1969 VFunc = Builder.CreateAlignedLoad(Ty, VFuncPtr, CGF.getPointerAlign());
1972 CGCallee Callee(GD, VFunc);
1973 return Callee;
1976 llvm::Value *MicrosoftCXXABI::EmitVirtualDestructorCall(
1977 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
1978 Address This, DeleteOrMemberCallExpr E) {
1979 auto *CE = E.dyn_cast<const CXXMemberCallExpr *>();
1980 auto *D = E.dyn_cast<const CXXDeleteExpr *>();
1981 assert((CE != nullptr) ^ (D != nullptr));
1982 assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
1983 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1985 // We have only one destructor in the vftable but can get both behaviors
1986 // by passing an implicit int parameter.
1987 GlobalDecl GD(Dtor, Dtor_Deleting);
1988 const CGFunctionInfo *FInfo =
1989 &CGM.getTypes().arrangeCXXStructorDeclaration(GD);
1990 llvm::FunctionType *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
1991 CGCallee Callee = CGCallee::forVirtual(CE, GD, This, Ty);
1993 ASTContext &Context = getContext();
1994 llvm::Value *ImplicitParam = llvm::ConstantInt::get(
1995 llvm::IntegerType::getInt32Ty(CGF.getLLVMContext()),
1996 DtorType == Dtor_Deleting);
1998 QualType ThisTy;
1999 if (CE) {
2000 ThisTy = CE->getObjectType();
2001 } else {
2002 ThisTy = D->getDestroyedType();
2005 This = adjustThisArgumentForVirtualFunctionCall(CGF, GD, This, true);
2006 RValue RV = CGF.EmitCXXDestructorCall(GD, Callee, This.getPointer(), ThisTy,
2007 ImplicitParam, Context.IntTy, CE);
2008 return RV.getScalarVal();
2011 const VBTableGlobals &
2012 MicrosoftCXXABI::enumerateVBTables(const CXXRecordDecl *RD) {
2013 // At this layer, we can key the cache off of a single class, which is much
2014 // easier than caching each vbtable individually.
2015 llvm::DenseMap<const CXXRecordDecl*, VBTableGlobals>::iterator Entry;
2016 bool Added;
2017 std::tie(Entry, Added) =
2018 VBTablesMap.insert(std::make_pair(RD, VBTableGlobals()));
2019 VBTableGlobals &VBGlobals = Entry->second;
2020 if (!Added)
2021 return VBGlobals;
2023 MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext();
2024 VBGlobals.VBTables = &Context.enumerateVBTables(RD);
2026 // Cache the globals for all vbtables so we don't have to recompute the
2027 // mangled names.
2028 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
2029 for (VPtrInfoVector::const_iterator I = VBGlobals.VBTables->begin(),
2030 E = VBGlobals.VBTables->end();
2031 I != E; ++I) {
2032 VBGlobals.Globals.push_back(getAddrOfVBTable(**I, RD, Linkage));
2035 return VBGlobals;
2038 llvm::Function *
2039 MicrosoftCXXABI::EmitVirtualMemPtrThunk(const CXXMethodDecl *MD,
2040 const MethodVFTableLocation &ML) {
2041 assert(!isa<CXXConstructorDecl>(MD) && !isa<CXXDestructorDecl>(MD) &&
2042 "can't form pointers to ctors or virtual dtors");
2044 // Calculate the mangled name.
2045 SmallString<256> ThunkName;
2046 llvm::raw_svector_ostream Out(ThunkName);
2047 getMangleContext().mangleVirtualMemPtrThunk(MD, ML, Out);
2049 // If the thunk has been generated previously, just return it.
2050 if (llvm::GlobalValue *GV = CGM.getModule().getNamedValue(ThunkName))
2051 return cast<llvm::Function>(GV);
2053 // Create the llvm::Function.
2054 const CGFunctionInfo &FnInfo =
2055 CGM.getTypes().arrangeUnprototypedMustTailThunk(MD);
2056 llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo);
2057 llvm::Function *ThunkFn =
2058 llvm::Function::Create(ThunkTy, llvm::Function::ExternalLinkage,
2059 ThunkName.str(), &CGM.getModule());
2060 assert(ThunkFn->getName() == ThunkName && "name was uniqued!");
2062 ThunkFn->setLinkage(MD->isExternallyVisible()
2063 ? llvm::GlobalValue::LinkOnceODRLinkage
2064 : llvm::GlobalValue::InternalLinkage);
2065 if (MD->isExternallyVisible())
2066 ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));
2068 CGM.SetLLVMFunctionAttributes(MD, FnInfo, ThunkFn, /*IsThunk=*/false);
2069 CGM.SetLLVMFunctionAttributesForDefinition(MD, ThunkFn);
2071 // Add the "thunk" attribute so that LLVM knows that the return type is
2072 // meaningless. These thunks can be used to call functions with differing
2073 // return types, and the caller is required to cast the prototype
2074 // appropriately to extract the correct value.
2075 ThunkFn->addFnAttr("thunk");
2077 // These thunks can be compared, so they are not unnamed.
2078 ThunkFn->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::None);
2080 // Start codegen.
2081 CodeGenFunction CGF(CGM);
2082 CGF.CurGD = GlobalDecl(MD);
2083 CGF.CurFuncIsThunk = true;
2085 // Build FunctionArgs, but only include the implicit 'this' parameter
2086 // declaration.
2087 FunctionArgList FunctionArgs;
2088 buildThisParam(CGF, FunctionArgs);
2090 // Start defining the function.
2091 CGF.StartFunction(GlobalDecl(), FnInfo.getReturnType(), ThunkFn, FnInfo,
2092 FunctionArgs, MD->getLocation(), SourceLocation());
2094 ApplyDebugLocation AL(CGF, MD->getLocation());
2095 setCXXABIThisValue(CGF, loadIncomingCXXThis(CGF));
2097 // Load the vfptr and then callee from the vftable. The callee should have
2098 // adjusted 'this' so that the vfptr is at offset zero.
2099 llvm::Type *ThunkPtrTy = ThunkTy->getPointerTo();
2100 llvm::Value *VTable = CGF.GetVTablePtr(
2101 getThisAddress(CGF), ThunkPtrTy->getPointerTo(), MD->getParent());
2103 llvm::Value *VFuncPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
2104 ThunkPtrTy, VTable, ML.Index, "vfn");
2105 llvm::Value *Callee =
2106 CGF.Builder.CreateAlignedLoad(ThunkPtrTy, VFuncPtr, CGF.getPointerAlign());
2108 CGF.EmitMustTailThunk(MD, getThisValue(CGF), {ThunkTy, Callee});
2110 return ThunkFn;
2113 void MicrosoftCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
2114 const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
2115 for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) {
2116 const std::unique_ptr<VPtrInfo>& VBT = (*VBGlobals.VBTables)[I];
2117 llvm::GlobalVariable *GV = VBGlobals.Globals[I];
2118 if (GV->isDeclaration())
2119 emitVBTableDefinition(*VBT, RD, GV);
2123 llvm::GlobalVariable *
2124 MicrosoftCXXABI::getAddrOfVBTable(const VPtrInfo &VBT, const CXXRecordDecl *RD,
2125 llvm::GlobalVariable::LinkageTypes Linkage) {
2126 SmallString<256> OutName;
2127 llvm::raw_svector_ostream Out(OutName);
2128 getMangleContext().mangleCXXVBTable(RD, VBT.MangledPath, Out);
2129 StringRef Name = OutName.str();
2131 llvm::ArrayType *VBTableType =
2132 llvm::ArrayType::get(CGM.IntTy, 1 + VBT.ObjectWithVPtr->getNumVBases());
2134 assert(!CGM.getModule().getNamedGlobal(Name) &&
2135 "vbtable with this name already exists: mangling bug?");
2136 CharUnits Alignment =
2137 CGM.getContext().getTypeAlignInChars(CGM.getContext().IntTy);
2138 llvm::GlobalVariable *GV = CGM.CreateOrReplaceCXXRuntimeVariable(
2139 Name, VBTableType, Linkage, Alignment.getAsAlign());
2140 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2142 if (RD->hasAttr<DLLImportAttr>())
2143 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2144 else if (RD->hasAttr<DLLExportAttr>())
2145 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
2147 if (!GV->hasExternalLinkage())
2148 emitVBTableDefinition(VBT, RD, GV);
2150 return GV;
2153 void MicrosoftCXXABI::emitVBTableDefinition(const VPtrInfo &VBT,
2154 const CXXRecordDecl *RD,
2155 llvm::GlobalVariable *GV) const {
2156 const CXXRecordDecl *ObjectWithVPtr = VBT.ObjectWithVPtr;
2158 assert(RD->getNumVBases() && ObjectWithVPtr->getNumVBases() &&
2159 "should only emit vbtables for classes with vbtables");
2161 const ASTRecordLayout &BaseLayout =
2162 getContext().getASTRecordLayout(VBT.IntroducingObject);
2163 const ASTRecordLayout &DerivedLayout = getContext().getASTRecordLayout(RD);
2165 SmallVector<llvm::Constant *, 4> Offsets(1 + ObjectWithVPtr->getNumVBases(),
2166 nullptr);
2168 // The offset from ObjectWithVPtr's vbptr to itself always leads.
2169 CharUnits VBPtrOffset = BaseLayout.getVBPtrOffset();
2170 Offsets[0] = llvm::ConstantInt::get(CGM.IntTy, -VBPtrOffset.getQuantity());
2172 MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext();
2173 for (const auto &I : ObjectWithVPtr->vbases()) {
2174 const CXXRecordDecl *VBase = I.getType()->getAsCXXRecordDecl();
2175 CharUnits Offset = DerivedLayout.getVBaseClassOffset(VBase);
2176 assert(!Offset.isNegative());
2178 // Make it relative to the subobject vbptr.
2179 CharUnits CompleteVBPtrOffset = VBT.NonVirtualOffset + VBPtrOffset;
2180 if (VBT.getVBaseWithVPtr())
2181 CompleteVBPtrOffset +=
2182 DerivedLayout.getVBaseClassOffset(VBT.getVBaseWithVPtr());
2183 Offset -= CompleteVBPtrOffset;
2185 unsigned VBIndex = Context.getVBTableIndex(ObjectWithVPtr, VBase);
2186 assert(Offsets[VBIndex] == nullptr && "The same vbindex seen twice?");
2187 Offsets[VBIndex] = llvm::ConstantInt::get(CGM.IntTy, Offset.getQuantity());
2190 assert(Offsets.size() ==
2191 cast<llvm::ArrayType>(GV->getValueType())->getNumElements());
2192 llvm::ArrayType *VBTableType =
2193 llvm::ArrayType::get(CGM.IntTy, Offsets.size());
2194 llvm::Constant *Init = llvm::ConstantArray::get(VBTableType, Offsets);
2195 GV->setInitializer(Init);
2197 if (RD->hasAttr<DLLImportAttr>())
2198 GV->setLinkage(llvm::GlobalVariable::AvailableExternallyLinkage);
2201 llvm::Value *MicrosoftCXXABI::performThisAdjustment(CodeGenFunction &CGF,
2202 Address This,
2203 const ThisAdjustment &TA) {
2204 if (TA.isEmpty())
2205 return This.getPointer();
2207 This = CGF.Builder.CreateElementBitCast(This, CGF.Int8Ty);
2209 llvm::Value *V;
2210 if (TA.Virtual.isEmpty()) {
2211 V = This.getPointer();
2212 } else {
2213 assert(TA.Virtual.Microsoft.VtordispOffset < 0);
2214 // Adjust the this argument based on the vtordisp value.
2215 Address VtorDispPtr =
2216 CGF.Builder.CreateConstInBoundsByteGEP(This,
2217 CharUnits::fromQuantity(TA.Virtual.Microsoft.VtordispOffset));
2218 VtorDispPtr = CGF.Builder.CreateElementBitCast(VtorDispPtr, CGF.Int32Ty);
2219 llvm::Value *VtorDisp = CGF.Builder.CreateLoad(VtorDispPtr, "vtordisp");
2220 V = CGF.Builder.CreateGEP(This.getElementType(), This.getPointer(),
2221 CGF.Builder.CreateNeg(VtorDisp));
2223 // Unfortunately, having applied the vtordisp means that we no
2224 // longer really have a known alignment for the vbptr step.
2225 // We'll assume the vbptr is pointer-aligned.
2227 if (TA.Virtual.Microsoft.VBPtrOffset) {
2228 // If the final overrider is defined in a virtual base other than the one
2229 // that holds the vfptr, we have to use a vtordispex thunk which looks up
2230 // the vbtable of the derived class.
2231 assert(TA.Virtual.Microsoft.VBPtrOffset > 0);
2232 assert(TA.Virtual.Microsoft.VBOffsetOffset >= 0);
2233 llvm::Value *VBPtr;
2234 llvm::Value *VBaseOffset = GetVBaseOffsetFromVBPtr(
2235 CGF, Address(V, CGF.Int8Ty, CGF.getPointerAlign()),
2236 -TA.Virtual.Microsoft.VBPtrOffset,
2237 TA.Virtual.Microsoft.VBOffsetOffset, &VBPtr);
2238 V = CGF.Builder.CreateInBoundsGEP(CGF.Int8Ty, VBPtr, VBaseOffset);
2242 if (TA.NonVirtual) {
2243 // Non-virtual adjustment might result in a pointer outside the allocated
2244 // object, e.g. if the final overrider class is laid out after the virtual
2245 // base that declares a method in the most derived class.
2246 V = CGF.Builder.CreateConstGEP1_32(CGF.Int8Ty, V, TA.NonVirtual);
2249 // Don't need to bitcast back, the call CodeGen will handle this.
2250 return V;
2253 llvm::Value *
2254 MicrosoftCXXABI::performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
2255 const ReturnAdjustment &RA) {
2256 if (RA.isEmpty())
2257 return Ret.getPointer();
2259 auto OrigTy = Ret.getType();
2260 Ret = CGF.Builder.CreateElementBitCast(Ret, CGF.Int8Ty);
2262 llvm::Value *V = Ret.getPointer();
2263 if (RA.Virtual.Microsoft.VBIndex) {
2264 assert(RA.Virtual.Microsoft.VBIndex > 0);
2265 int32_t IntSize = CGF.getIntSize().getQuantity();
2266 llvm::Value *VBPtr;
2267 llvm::Value *VBaseOffset =
2268 GetVBaseOffsetFromVBPtr(CGF, Ret, RA.Virtual.Microsoft.VBPtrOffset,
2269 IntSize * RA.Virtual.Microsoft.VBIndex, &VBPtr);
2270 V = CGF.Builder.CreateInBoundsGEP(CGF.Int8Ty, VBPtr, VBaseOffset);
2273 if (RA.NonVirtual)
2274 V = CGF.Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, V, RA.NonVirtual);
2276 // Cast back to the original type.
2277 return CGF.Builder.CreateBitCast(V, OrigTy);
2280 bool MicrosoftCXXABI::requiresArrayCookie(const CXXDeleteExpr *expr,
2281 QualType elementType) {
2282 // Microsoft seems to completely ignore the possibility of a
2283 // two-argument usual deallocation function.
2284 return elementType.isDestructedType();
2287 bool MicrosoftCXXABI::requiresArrayCookie(const CXXNewExpr *expr) {
2288 // Microsoft seems to completely ignore the possibility of a
2289 // two-argument usual deallocation function.
2290 return expr->getAllocatedType().isDestructedType();
2293 CharUnits MicrosoftCXXABI::getArrayCookieSizeImpl(QualType type) {
2294 // The array cookie is always a size_t; we then pad that out to the
2295 // alignment of the element type.
2296 ASTContext &Ctx = getContext();
2297 return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()),
2298 Ctx.getTypeAlignInChars(type));
2301 llvm::Value *MicrosoftCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
2302 Address allocPtr,
2303 CharUnits cookieSize) {
2304 Address numElementsPtr =
2305 CGF.Builder.CreateElementBitCast(allocPtr, CGF.SizeTy);
2306 return CGF.Builder.CreateLoad(numElementsPtr);
2309 Address MicrosoftCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
2310 Address newPtr,
2311 llvm::Value *numElements,
2312 const CXXNewExpr *expr,
2313 QualType elementType) {
2314 assert(requiresArrayCookie(expr));
2316 // The size of the cookie.
2317 CharUnits cookieSize = getArrayCookieSizeImpl(elementType);
2319 // Compute an offset to the cookie.
2320 Address cookiePtr = newPtr;
2322 // Write the number of elements into the appropriate slot.
2323 Address numElementsPtr
2324 = CGF.Builder.CreateElementBitCast(cookiePtr, CGF.SizeTy);
2325 CGF.Builder.CreateStore(numElements, numElementsPtr);
2327 // Finally, compute a pointer to the actual data buffer by skipping
2328 // over the cookie completely.
2329 return CGF.Builder.CreateConstInBoundsByteGEP(newPtr, cookieSize);
2332 static void emitGlobalDtorWithTLRegDtor(CodeGenFunction &CGF, const VarDecl &VD,
2333 llvm::FunctionCallee Dtor,
2334 llvm::Constant *Addr) {
2335 // Create a function which calls the destructor.
2336 llvm::Constant *DtorStub = CGF.createAtExitStub(VD, Dtor, Addr);
2338 // extern "C" int __tlregdtor(void (*f)(void));
2339 llvm::FunctionType *TLRegDtorTy = llvm::FunctionType::get(
2340 CGF.IntTy, DtorStub->getType(), /*isVarArg=*/false);
2342 llvm::FunctionCallee TLRegDtor = CGF.CGM.CreateRuntimeFunction(
2343 TLRegDtorTy, "__tlregdtor", llvm::AttributeList(), /*Local=*/true);
2344 if (llvm::Function *TLRegDtorFn =
2345 dyn_cast<llvm::Function>(TLRegDtor.getCallee()))
2346 TLRegDtorFn->setDoesNotThrow();
2348 CGF.EmitNounwindRuntimeCall(TLRegDtor, DtorStub);
2351 void MicrosoftCXXABI::registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
2352 llvm::FunctionCallee Dtor,
2353 llvm::Constant *Addr) {
2354 if (D.isNoDestroy(CGM.getContext()))
2355 return;
2357 if (D.getTLSKind())
2358 return emitGlobalDtorWithTLRegDtor(CGF, D, Dtor, Addr);
2360 // HLSL doesn't support atexit.
2361 if (CGM.getLangOpts().HLSL)
2362 return CGM.AddCXXDtorEntry(Dtor, Addr);
2364 // The default behavior is to use atexit.
2365 CGF.registerGlobalDtorWithAtExit(D, Dtor, Addr);
2368 void MicrosoftCXXABI::EmitThreadLocalInitFuncs(
2369 CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
2370 ArrayRef<llvm::Function *> CXXThreadLocalInits,
2371 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) {
2372 if (CXXThreadLocalInits.empty())
2373 return;
2375 CGM.AppendLinkerOptions(CGM.getTarget().getTriple().getArch() ==
2376 llvm::Triple::x86
2377 ? "/include:___dyn_tls_init@12"
2378 : "/include:__dyn_tls_init");
2380 // This will create a GV in the .CRT$XDU section. It will point to our
2381 // initialization function. The CRT will call all of these function
2382 // pointers at start-up time and, eventually, at thread-creation time.
2383 auto AddToXDU = [&CGM](llvm::Function *InitFunc) {
2384 llvm::GlobalVariable *InitFuncPtr = new llvm::GlobalVariable(
2385 CGM.getModule(), InitFunc->getType(), /*isConstant=*/true,
2386 llvm::GlobalVariable::InternalLinkage, InitFunc,
2387 Twine(InitFunc->getName(), "$initializer$"));
2388 InitFuncPtr->setSection(".CRT$XDU");
2389 // This variable has discardable linkage, we have to add it to @llvm.used to
2390 // ensure it won't get discarded.
2391 CGM.addUsedGlobal(InitFuncPtr);
2392 return InitFuncPtr;
2395 std::vector<llvm::Function *> NonComdatInits;
2396 for (size_t I = 0, E = CXXThreadLocalInitVars.size(); I != E; ++I) {
2397 llvm::GlobalVariable *GV = cast<llvm::GlobalVariable>(
2398 CGM.GetGlobalValue(CGM.getMangledName(CXXThreadLocalInitVars[I])));
2399 llvm::Function *F = CXXThreadLocalInits[I];
2401 // If the GV is already in a comdat group, then we have to join it.
2402 if (llvm::Comdat *C = GV->getComdat())
2403 AddToXDU(F)->setComdat(C);
2404 else
2405 NonComdatInits.push_back(F);
2408 if (!NonComdatInits.empty()) {
2409 llvm::FunctionType *FTy =
2410 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
2411 llvm::Function *InitFunc = CGM.CreateGlobalInitOrCleanUpFunction(
2412 FTy, "__tls_init", CGM.getTypes().arrangeNullaryFunction(),
2413 SourceLocation(), /*TLS=*/true);
2414 CodeGenFunction(CGM).GenerateCXXGlobalInitFunc(InitFunc, NonComdatInits);
2416 AddToXDU(InitFunc);
2420 static llvm::GlobalValue *getTlsGuardVar(CodeGenModule &CGM) {
2421 // __tls_guard comes from the MSVC runtime and reflects
2422 // whether TLS has been initialized for a particular thread.
2423 // It is set from within __dyn_tls_init by the runtime.
2424 // Every library and executable has its own variable.
2425 llvm::Type *VTy = llvm::Type::getInt8Ty(CGM.getLLVMContext());
2426 llvm::Constant *TlsGuardConstant =
2427 CGM.CreateRuntimeVariable(VTy, "__tls_guard");
2428 llvm::GlobalValue *TlsGuard = cast<llvm::GlobalValue>(TlsGuardConstant);
2430 TlsGuard->setThreadLocal(true);
2432 return TlsGuard;
2435 static llvm::FunctionCallee getDynTlsOnDemandInitFn(CodeGenModule &CGM) {
2436 // __dyn_tls_on_demand_init comes from the MSVC runtime and triggers
2437 // dynamic TLS initialization by calling __dyn_tls_init internally.
2438 llvm::FunctionType *FTy =
2439 llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()), {},
2440 /*isVarArg=*/false);
2441 return CGM.CreateRuntimeFunction(
2442 FTy, "__dyn_tls_on_demand_init",
2443 llvm::AttributeList::get(CGM.getLLVMContext(),
2444 llvm::AttributeList::FunctionIndex,
2445 llvm::Attribute::NoUnwind),
2446 /*Local=*/true);
2449 static void emitTlsGuardCheck(CodeGenFunction &CGF, llvm::GlobalValue *TlsGuard,
2450 llvm::BasicBlock *DynInitBB,
2451 llvm::BasicBlock *ContinueBB) {
2452 llvm::LoadInst *TlsGuardValue =
2453 CGF.Builder.CreateLoad(Address(TlsGuard, CGF.Int8Ty, CharUnits::One()));
2454 llvm::Value *CmpResult =
2455 CGF.Builder.CreateICmpEQ(TlsGuardValue, CGF.Builder.getInt8(0));
2456 CGF.Builder.CreateCondBr(CmpResult, DynInitBB, ContinueBB);
2459 static void emitDynamicTlsInitializationCall(CodeGenFunction &CGF,
2460 llvm::GlobalValue *TlsGuard,
2461 llvm::BasicBlock *ContinueBB) {
2462 llvm::FunctionCallee Initializer = getDynTlsOnDemandInitFn(CGF.CGM);
2463 llvm::Function *InitializerFunction =
2464 cast<llvm::Function>(Initializer.getCallee());
2465 llvm::CallInst *CallVal = CGF.Builder.CreateCall(InitializerFunction);
2466 CallVal->setCallingConv(InitializerFunction->getCallingConv());
2468 CGF.Builder.CreateBr(ContinueBB);
2471 static void emitDynamicTlsInitialization(CodeGenFunction &CGF) {
2472 llvm::BasicBlock *DynInitBB =
2473 CGF.createBasicBlock("dyntls.dyn_init", CGF.CurFn);
2474 llvm::BasicBlock *ContinueBB =
2475 CGF.createBasicBlock("dyntls.continue", CGF.CurFn);
2477 llvm::GlobalValue *TlsGuard = getTlsGuardVar(CGF.CGM);
2479 emitTlsGuardCheck(CGF, TlsGuard, DynInitBB, ContinueBB);
2480 CGF.Builder.SetInsertPoint(DynInitBB);
2481 emitDynamicTlsInitializationCall(CGF, TlsGuard, ContinueBB);
2482 CGF.Builder.SetInsertPoint(ContinueBB);
2485 LValue MicrosoftCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
2486 const VarDecl *VD,
2487 QualType LValType) {
2488 // Dynamic TLS initialization works by checking the state of a
2489 // guard variable (__tls_guard) to see whether TLS initialization
2490 // for a thread has happend yet.
2491 // If not, the initialization is triggered on-demand
2492 // by calling __dyn_tls_on_demand_init.
2493 emitDynamicTlsInitialization(CGF);
2495 // Emit the variable just like any regular global variable.
2497 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
2498 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
2500 unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
2501 V = CGF.Builder.CreateBitCast(V, RealVarTy->getPointerTo(AS));
2503 CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
2504 Address Addr(V, RealVarTy, Alignment);
2506 LValue LV = VD->getType()->isReferenceType()
2507 ? CGF.EmitLoadOfReferenceLValue(Addr, VD->getType(),
2508 AlignmentSource::Decl)
2509 : CGF.MakeAddrLValue(Addr, LValType, AlignmentSource::Decl);
2510 return LV;
2513 static ConstantAddress getInitThreadEpochPtr(CodeGenModule &CGM) {
2514 StringRef VarName("_Init_thread_epoch");
2515 CharUnits Align = CGM.getIntAlign();
2516 if (auto *GV = CGM.getModule().getNamedGlobal(VarName))
2517 return ConstantAddress(GV, GV->getValueType(), Align);
2518 auto *GV = new llvm::GlobalVariable(
2519 CGM.getModule(), CGM.IntTy,
2520 /*isConstant=*/false, llvm::GlobalVariable::ExternalLinkage,
2521 /*Initializer=*/nullptr, VarName,
2522 /*InsertBefore=*/nullptr, llvm::GlobalVariable::GeneralDynamicTLSModel);
2523 GV->setAlignment(Align.getAsAlign());
2524 return ConstantAddress(GV, GV->getValueType(), Align);
2527 static llvm::FunctionCallee getInitThreadHeaderFn(CodeGenModule &CGM) {
2528 llvm::FunctionType *FTy =
2529 llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
2530 CGM.IntTy->getPointerTo(), /*isVarArg=*/false);
2531 return CGM.CreateRuntimeFunction(
2532 FTy, "_Init_thread_header",
2533 llvm::AttributeList::get(CGM.getLLVMContext(),
2534 llvm::AttributeList::FunctionIndex,
2535 llvm::Attribute::NoUnwind),
2536 /*Local=*/true);
2539 static llvm::FunctionCallee getInitThreadFooterFn(CodeGenModule &CGM) {
2540 llvm::FunctionType *FTy =
2541 llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
2542 CGM.IntTy->getPointerTo(), /*isVarArg=*/false);
2543 return CGM.CreateRuntimeFunction(
2544 FTy, "_Init_thread_footer",
2545 llvm::AttributeList::get(CGM.getLLVMContext(),
2546 llvm::AttributeList::FunctionIndex,
2547 llvm::Attribute::NoUnwind),
2548 /*Local=*/true);
2551 static llvm::FunctionCallee getInitThreadAbortFn(CodeGenModule &CGM) {
2552 llvm::FunctionType *FTy =
2553 llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
2554 CGM.IntTy->getPointerTo(), /*isVarArg=*/false);
2555 return CGM.CreateRuntimeFunction(
2556 FTy, "_Init_thread_abort",
2557 llvm::AttributeList::get(CGM.getLLVMContext(),
2558 llvm::AttributeList::FunctionIndex,
2559 llvm::Attribute::NoUnwind),
2560 /*Local=*/true);
2563 namespace {
2564 struct ResetGuardBit final : EHScopeStack::Cleanup {
2565 Address Guard;
2566 unsigned GuardNum;
2567 ResetGuardBit(Address Guard, unsigned GuardNum)
2568 : Guard(Guard), GuardNum(GuardNum) {}
2570 void Emit(CodeGenFunction &CGF, Flags flags) override {
2571 // Reset the bit in the mask so that the static variable may be
2572 // reinitialized.
2573 CGBuilderTy &Builder = CGF.Builder;
2574 llvm::LoadInst *LI = Builder.CreateLoad(Guard);
2575 llvm::ConstantInt *Mask =
2576 llvm::ConstantInt::get(CGF.IntTy, ~(1ULL << GuardNum));
2577 Builder.CreateStore(Builder.CreateAnd(LI, Mask), Guard);
2581 struct CallInitThreadAbort final : EHScopeStack::Cleanup {
2582 llvm::Value *Guard;
2583 CallInitThreadAbort(Address Guard) : Guard(Guard.getPointer()) {}
2585 void Emit(CodeGenFunction &CGF, Flags flags) override {
2586 // Calling _Init_thread_abort will reset the guard's state.
2587 CGF.EmitNounwindRuntimeCall(getInitThreadAbortFn(CGF.CGM), Guard);
2592 void MicrosoftCXXABI::EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
2593 llvm::GlobalVariable *GV,
2594 bool PerformInit) {
2595 // MSVC only uses guards for static locals.
2596 if (!D.isStaticLocal()) {
2597 assert(GV->hasWeakLinkage() || GV->hasLinkOnceLinkage());
2598 // GlobalOpt is allowed to discard the initializer, so use linkonce_odr.
2599 llvm::Function *F = CGF.CurFn;
2600 F->setLinkage(llvm::GlobalValue::LinkOnceODRLinkage);
2601 F->setComdat(CGM.getModule().getOrInsertComdat(F->getName()));
2602 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
2603 return;
2606 bool ThreadlocalStatic = D.getTLSKind();
2607 bool ThreadsafeStatic = getContext().getLangOpts().ThreadsafeStatics;
2609 // Thread-safe static variables which aren't thread-specific have a
2610 // per-variable guard.
2611 bool HasPerVariableGuard = ThreadsafeStatic && !ThreadlocalStatic;
2613 CGBuilderTy &Builder = CGF.Builder;
2614 llvm::IntegerType *GuardTy = CGF.Int32Ty;
2615 llvm::ConstantInt *Zero = llvm::ConstantInt::get(GuardTy, 0);
2616 CharUnits GuardAlign = CharUnits::fromQuantity(4);
2618 // Get the guard variable for this function if we have one already.
2619 GuardInfo *GI = nullptr;
2620 if (ThreadlocalStatic)
2621 GI = &ThreadLocalGuardVariableMap[D.getDeclContext()];
2622 else if (!ThreadsafeStatic)
2623 GI = &GuardVariableMap[D.getDeclContext()];
2625 llvm::GlobalVariable *GuardVar = GI ? GI->Guard : nullptr;
2626 unsigned GuardNum;
2627 if (D.isExternallyVisible()) {
2628 // Externally visible variables have to be numbered in Sema to properly
2629 // handle unreachable VarDecls.
2630 GuardNum = getContext().getStaticLocalNumber(&D);
2631 assert(GuardNum > 0);
2632 GuardNum--;
2633 } else if (HasPerVariableGuard) {
2634 GuardNum = ThreadSafeGuardNumMap[D.getDeclContext()]++;
2635 } else {
2636 // Non-externally visible variables are numbered here in CodeGen.
2637 GuardNum = GI->BitIndex++;
2640 if (!HasPerVariableGuard && GuardNum >= 32) {
2641 if (D.isExternallyVisible())
2642 ErrorUnsupportedABI(CGF, "more than 32 guarded initializations");
2643 GuardNum %= 32;
2644 GuardVar = nullptr;
2647 if (!GuardVar) {
2648 // Mangle the name for the guard.
2649 SmallString<256> GuardName;
2651 llvm::raw_svector_ostream Out(GuardName);
2652 if (HasPerVariableGuard)
2653 getMangleContext().mangleThreadSafeStaticGuardVariable(&D, GuardNum,
2654 Out);
2655 else
2656 getMangleContext().mangleStaticGuardVariable(&D, Out);
2659 // Create the guard variable with a zero-initializer. Just absorb linkage,
2660 // visibility and dll storage class from the guarded variable.
2661 GuardVar =
2662 new llvm::GlobalVariable(CGM.getModule(), GuardTy, /*isConstant=*/false,
2663 GV->getLinkage(), Zero, GuardName.str());
2664 GuardVar->setVisibility(GV->getVisibility());
2665 GuardVar->setDLLStorageClass(GV->getDLLStorageClass());
2666 GuardVar->setAlignment(GuardAlign.getAsAlign());
2667 if (GuardVar->isWeakForLinker())
2668 GuardVar->setComdat(
2669 CGM.getModule().getOrInsertComdat(GuardVar->getName()));
2670 if (D.getTLSKind())
2671 CGM.setTLSMode(GuardVar, D);
2672 if (GI && !HasPerVariableGuard)
2673 GI->Guard = GuardVar;
2676 ConstantAddress GuardAddr(GuardVar, GuardTy, GuardAlign);
2678 assert(GuardVar->getLinkage() == GV->getLinkage() &&
2679 "static local from the same function had different linkage");
2681 if (!HasPerVariableGuard) {
2682 // Pseudo code for the test:
2683 // if (!(GuardVar & MyGuardBit)) {
2684 // GuardVar |= MyGuardBit;
2685 // ... initialize the object ...;
2686 // }
2688 // Test our bit from the guard variable.
2689 llvm::ConstantInt *Bit = llvm::ConstantInt::get(GuardTy, 1ULL << GuardNum);
2690 llvm::LoadInst *LI = Builder.CreateLoad(GuardAddr);
2691 llvm::Value *NeedsInit =
2692 Builder.CreateICmpEQ(Builder.CreateAnd(LI, Bit), Zero);
2693 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
2694 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2695 CGF.EmitCXXGuardedInitBranch(NeedsInit, InitBlock, EndBlock,
2696 CodeGenFunction::GuardKind::VariableGuard, &D);
2698 // Set our bit in the guard variable and emit the initializer and add a global
2699 // destructor if appropriate.
2700 CGF.EmitBlock(InitBlock);
2701 Builder.CreateStore(Builder.CreateOr(LI, Bit), GuardAddr);
2702 CGF.EHStack.pushCleanup<ResetGuardBit>(EHCleanup, GuardAddr, GuardNum);
2703 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
2704 CGF.PopCleanupBlock();
2705 Builder.CreateBr(EndBlock);
2707 // Continue.
2708 CGF.EmitBlock(EndBlock);
2709 } else {
2710 // Pseudo code for the test:
2711 // if (TSS > _Init_thread_epoch) {
2712 // _Init_thread_header(&TSS);
2713 // if (TSS == -1) {
2714 // ... initialize the object ...;
2715 // _Init_thread_footer(&TSS);
2716 // }
2717 // }
2719 // The algorithm is almost identical to what can be found in the appendix
2720 // found in N2325.
2722 // This BasicBLock determines whether or not we have any work to do.
2723 llvm::LoadInst *FirstGuardLoad = Builder.CreateLoad(GuardAddr);
2724 FirstGuardLoad->setOrdering(llvm::AtomicOrdering::Unordered);
2725 llvm::LoadInst *InitThreadEpoch =
2726 Builder.CreateLoad(getInitThreadEpochPtr(CGM));
2727 llvm::Value *IsUninitialized =
2728 Builder.CreateICmpSGT(FirstGuardLoad, InitThreadEpoch);
2729 llvm::BasicBlock *AttemptInitBlock = CGF.createBasicBlock("init.attempt");
2730 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2731 CGF.EmitCXXGuardedInitBranch(IsUninitialized, AttemptInitBlock, EndBlock,
2732 CodeGenFunction::GuardKind::VariableGuard, &D);
2734 // This BasicBlock attempts to determine whether or not this thread is
2735 // responsible for doing the initialization.
2736 CGF.EmitBlock(AttemptInitBlock);
2737 CGF.EmitNounwindRuntimeCall(getInitThreadHeaderFn(CGM),
2738 GuardAddr.getPointer());
2739 llvm::LoadInst *SecondGuardLoad = Builder.CreateLoad(GuardAddr);
2740 SecondGuardLoad->setOrdering(llvm::AtomicOrdering::Unordered);
2741 llvm::Value *ShouldDoInit =
2742 Builder.CreateICmpEQ(SecondGuardLoad, getAllOnesInt());
2743 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
2744 Builder.CreateCondBr(ShouldDoInit, InitBlock, EndBlock);
2746 // Ok, we ended up getting selected as the initializing thread.
2747 CGF.EmitBlock(InitBlock);
2748 CGF.EHStack.pushCleanup<CallInitThreadAbort>(EHCleanup, GuardAddr);
2749 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
2750 CGF.PopCleanupBlock();
2751 CGF.EmitNounwindRuntimeCall(getInitThreadFooterFn(CGM),
2752 GuardAddr.getPointer());
2753 Builder.CreateBr(EndBlock);
2755 CGF.EmitBlock(EndBlock);
2759 bool MicrosoftCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
2760 // Null-ness for function memptrs only depends on the first field, which is
2761 // the function pointer. The rest don't matter, so we can zero initialize.
2762 if (MPT->isMemberFunctionPointer())
2763 return true;
2765 // The virtual base adjustment field is always -1 for null, so if we have one
2766 // we can't zero initialize. The field offset is sometimes also -1 if 0 is a
2767 // valid field offset.
2768 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2769 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
2770 return (!inheritanceModelHasVBTableOffsetField(Inheritance) &&
2771 RD->nullFieldOffsetIsZero());
2774 llvm::Type *
2775 MicrosoftCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
2776 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2777 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
2778 llvm::SmallVector<llvm::Type *, 4> fields;
2779 if (MPT->isMemberFunctionPointer())
2780 fields.push_back(CGM.VoidPtrTy); // FunctionPointerOrVirtualThunk
2781 else
2782 fields.push_back(CGM.IntTy); // FieldOffset
2784 if (inheritanceModelHasNVOffsetField(MPT->isMemberFunctionPointer(),
2785 Inheritance))
2786 fields.push_back(CGM.IntTy);
2787 if (inheritanceModelHasVBPtrOffsetField(Inheritance))
2788 fields.push_back(CGM.IntTy);
2789 if (inheritanceModelHasVBTableOffsetField(Inheritance))
2790 fields.push_back(CGM.IntTy); // VirtualBaseAdjustmentOffset
2792 if (fields.size() == 1)
2793 return fields[0];
2794 return llvm::StructType::get(CGM.getLLVMContext(), fields);
2797 void MicrosoftCXXABI::
2798 GetNullMemberPointerFields(const MemberPointerType *MPT,
2799 llvm::SmallVectorImpl<llvm::Constant *> &fields) {
2800 assert(fields.empty());
2801 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2802 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
2803 if (MPT->isMemberFunctionPointer()) {
2804 // FunctionPointerOrVirtualThunk
2805 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
2806 } else {
2807 if (RD->nullFieldOffsetIsZero())
2808 fields.push_back(getZeroInt()); // FieldOffset
2809 else
2810 fields.push_back(getAllOnesInt()); // FieldOffset
2813 if (inheritanceModelHasNVOffsetField(MPT->isMemberFunctionPointer(),
2814 Inheritance))
2815 fields.push_back(getZeroInt());
2816 if (inheritanceModelHasVBPtrOffsetField(Inheritance))
2817 fields.push_back(getZeroInt());
2818 if (inheritanceModelHasVBTableOffsetField(Inheritance))
2819 fields.push_back(getAllOnesInt());
2822 llvm::Constant *
2823 MicrosoftCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
2824 llvm::SmallVector<llvm::Constant *, 4> fields;
2825 GetNullMemberPointerFields(MPT, fields);
2826 if (fields.size() == 1)
2827 return fields[0];
2828 llvm::Constant *Res = llvm::ConstantStruct::getAnon(fields);
2829 assert(Res->getType() == ConvertMemberPointerType(MPT));
2830 return Res;
2833 llvm::Constant *
2834 MicrosoftCXXABI::EmitFullMemberPointer(llvm::Constant *FirstField,
2835 bool IsMemberFunction,
2836 const CXXRecordDecl *RD,
2837 CharUnits NonVirtualBaseAdjustment,
2838 unsigned VBTableIndex) {
2839 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
2841 // Single inheritance class member pointer are represented as scalars instead
2842 // of aggregates.
2843 if (inheritanceModelHasOnlyOneField(IsMemberFunction, Inheritance))
2844 return FirstField;
2846 llvm::SmallVector<llvm::Constant *, 4> fields;
2847 fields.push_back(FirstField);
2849 if (inheritanceModelHasNVOffsetField(IsMemberFunction, Inheritance))
2850 fields.push_back(llvm::ConstantInt::get(
2851 CGM.IntTy, NonVirtualBaseAdjustment.getQuantity()));
2853 if (inheritanceModelHasVBPtrOffsetField(Inheritance)) {
2854 CharUnits Offs = CharUnits::Zero();
2855 if (VBTableIndex)
2856 Offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
2857 fields.push_back(llvm::ConstantInt::get(CGM.IntTy, Offs.getQuantity()));
2860 // The rest of the fields are adjusted by conversions to a more derived class.
2861 if (inheritanceModelHasVBTableOffsetField(Inheritance))
2862 fields.push_back(llvm::ConstantInt::get(CGM.IntTy, VBTableIndex));
2864 return llvm::ConstantStruct::getAnon(fields);
2867 llvm::Constant *
2868 MicrosoftCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
2869 CharUnits offset) {
2870 return EmitMemberDataPointer(MPT->getMostRecentCXXRecordDecl(), offset);
2873 llvm::Constant *MicrosoftCXXABI::EmitMemberDataPointer(const CXXRecordDecl *RD,
2874 CharUnits offset) {
2875 if (RD->getMSInheritanceModel() ==
2876 MSInheritanceModel::Virtual)
2877 offset -= getContext().getOffsetOfBaseWithVBPtr(RD);
2878 llvm::Constant *FirstField =
2879 llvm::ConstantInt::get(CGM.IntTy, offset.getQuantity());
2880 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/false, RD,
2881 CharUnits::Zero(), /*VBTableIndex=*/0);
2884 llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const APValue &MP,
2885 QualType MPType) {
2886 const MemberPointerType *DstTy = MPType->castAs<MemberPointerType>();
2887 const ValueDecl *MPD = MP.getMemberPointerDecl();
2888 if (!MPD)
2889 return EmitNullMemberPointer(DstTy);
2891 ASTContext &Ctx = getContext();
2892 ArrayRef<const CXXRecordDecl *> MemberPointerPath = MP.getMemberPointerPath();
2894 llvm::Constant *C;
2895 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD)) {
2896 C = EmitMemberFunctionPointer(MD);
2897 } else {
2898 // For a pointer to data member, start off with the offset of the field in
2899 // the class in which it was declared, and convert from there if necessary.
2900 // For indirect field decls, get the outermost anonymous field and use the
2901 // parent class.
2902 CharUnits FieldOffset = Ctx.toCharUnitsFromBits(Ctx.getFieldOffset(MPD));
2903 const FieldDecl *FD = dyn_cast<FieldDecl>(MPD);
2904 if (!FD)
2905 FD = cast<FieldDecl>(*cast<IndirectFieldDecl>(MPD)->chain_begin());
2906 const CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getParent());
2907 RD = RD->getMostRecentNonInjectedDecl();
2908 C = EmitMemberDataPointer(RD, FieldOffset);
2911 if (!MemberPointerPath.empty()) {
2912 const CXXRecordDecl *SrcRD = cast<CXXRecordDecl>(MPD->getDeclContext());
2913 const Type *SrcRecTy = Ctx.getTypeDeclType(SrcRD).getTypePtr();
2914 const MemberPointerType *SrcTy =
2915 Ctx.getMemberPointerType(DstTy->getPointeeType(), SrcRecTy)
2916 ->castAs<MemberPointerType>();
2918 bool DerivedMember = MP.isMemberPointerToDerivedMember();
2919 SmallVector<const CXXBaseSpecifier *, 4> DerivedToBasePath;
2920 const CXXRecordDecl *PrevRD = SrcRD;
2921 for (const CXXRecordDecl *PathElem : MemberPointerPath) {
2922 const CXXRecordDecl *Base = nullptr;
2923 const CXXRecordDecl *Derived = nullptr;
2924 if (DerivedMember) {
2925 Base = PathElem;
2926 Derived = PrevRD;
2927 } else {
2928 Base = PrevRD;
2929 Derived = PathElem;
2931 for (const CXXBaseSpecifier &BS : Derived->bases())
2932 if (BS.getType()->getAsCXXRecordDecl()->getCanonicalDecl() ==
2933 Base->getCanonicalDecl())
2934 DerivedToBasePath.push_back(&BS);
2935 PrevRD = PathElem;
2937 assert(DerivedToBasePath.size() == MemberPointerPath.size());
2939 CastKind CK = DerivedMember ? CK_DerivedToBaseMemberPointer
2940 : CK_BaseToDerivedMemberPointer;
2941 C = EmitMemberPointerConversion(SrcTy, DstTy, CK, DerivedToBasePath.begin(),
2942 DerivedToBasePath.end(), C);
2944 return C;
2947 llvm::Constant *
2948 MicrosoftCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) {
2949 assert(MD->isInstance() && "Member function must not be static!");
2951 CharUnits NonVirtualBaseAdjustment = CharUnits::Zero();
2952 const CXXRecordDecl *RD = MD->getParent()->getMostRecentNonInjectedDecl();
2953 CodeGenTypes &Types = CGM.getTypes();
2955 unsigned VBTableIndex = 0;
2956 llvm::Constant *FirstField;
2957 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
2958 if (!MD->isVirtual()) {
2959 llvm::Type *Ty;
2960 // Check whether the function has a computable LLVM signature.
2961 if (Types.isFuncTypeConvertible(FPT)) {
2962 // The function has a computable LLVM signature; use the correct type.
2963 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
2964 } else {
2965 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
2966 // function type is incomplete.
2967 Ty = CGM.PtrDiffTy;
2969 FirstField = CGM.GetAddrOfFunction(MD, Ty);
2970 } else {
2971 auto &VTableContext = CGM.getMicrosoftVTableContext();
2972 MethodVFTableLocation ML = VTableContext.getMethodVFTableLocation(MD);
2973 FirstField = EmitVirtualMemPtrThunk(MD, ML);
2974 // Include the vfptr adjustment if the method is in a non-primary vftable.
2975 NonVirtualBaseAdjustment += ML.VFPtrOffset;
2976 if (ML.VBase)
2977 VBTableIndex = VTableContext.getVBTableIndex(RD, ML.VBase) * 4;
2980 if (VBTableIndex == 0 &&
2981 RD->getMSInheritanceModel() ==
2982 MSInheritanceModel::Virtual)
2983 NonVirtualBaseAdjustment -= getContext().getOffsetOfBaseWithVBPtr(RD);
2985 // The rest of the fields are common with data member pointers.
2986 FirstField = llvm::ConstantExpr::getBitCast(FirstField, CGM.VoidPtrTy);
2987 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/true, RD,
2988 NonVirtualBaseAdjustment, VBTableIndex);
2991 /// Member pointers are the same if they're either bitwise identical *or* both
2992 /// null. Null-ness for function members is determined by the first field,
2993 /// while for data member pointers we must compare all fields.
2994 llvm::Value *
2995 MicrosoftCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
2996 llvm::Value *L,
2997 llvm::Value *R,
2998 const MemberPointerType *MPT,
2999 bool Inequality) {
3000 CGBuilderTy &Builder = CGF.Builder;
3002 // Handle != comparisons by switching the sense of all boolean operations.
3003 llvm::ICmpInst::Predicate Eq;
3004 llvm::Instruction::BinaryOps And, Or;
3005 if (Inequality) {
3006 Eq = llvm::ICmpInst::ICMP_NE;
3007 And = llvm::Instruction::Or;
3008 Or = llvm::Instruction::And;
3009 } else {
3010 Eq = llvm::ICmpInst::ICMP_EQ;
3011 And = llvm::Instruction::And;
3012 Or = llvm::Instruction::Or;
3015 // If this is a single field member pointer (single inheritance), this is a
3016 // single icmp.
3017 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
3018 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
3019 if (inheritanceModelHasOnlyOneField(MPT->isMemberFunctionPointer(),
3020 Inheritance))
3021 return Builder.CreateICmp(Eq, L, R);
3023 // Compare the first field.
3024 llvm::Value *L0 = Builder.CreateExtractValue(L, 0, "lhs.0");
3025 llvm::Value *R0 = Builder.CreateExtractValue(R, 0, "rhs.0");
3026 llvm::Value *Cmp0 = Builder.CreateICmp(Eq, L0, R0, "memptr.cmp.first");
3028 // Compare everything other than the first field.
3029 llvm::Value *Res = nullptr;
3030 llvm::StructType *LType = cast<llvm::StructType>(L->getType());
3031 for (unsigned I = 1, E = LType->getNumElements(); I != E; ++I) {
3032 llvm::Value *LF = Builder.CreateExtractValue(L, I);
3033 llvm::Value *RF = Builder.CreateExtractValue(R, I);
3034 llvm::Value *Cmp = Builder.CreateICmp(Eq, LF, RF, "memptr.cmp.rest");
3035 if (Res)
3036 Res = Builder.CreateBinOp(And, Res, Cmp);
3037 else
3038 Res = Cmp;
3041 // Check if the first field is 0 if this is a function pointer.
3042 if (MPT->isMemberFunctionPointer()) {
3043 // (l1 == r1 && ...) || l0 == 0
3044 llvm::Value *Zero = llvm::Constant::getNullValue(L0->getType());
3045 llvm::Value *IsZero = Builder.CreateICmp(Eq, L0, Zero, "memptr.cmp.iszero");
3046 Res = Builder.CreateBinOp(Or, Res, IsZero);
3049 // Combine the comparison of the first field, which must always be true for
3050 // this comparison to succeeed.
3051 return Builder.CreateBinOp(And, Res, Cmp0, "memptr.cmp");
3054 llvm::Value *
3055 MicrosoftCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
3056 llvm::Value *MemPtr,
3057 const MemberPointerType *MPT) {
3058 CGBuilderTy &Builder = CGF.Builder;
3059 llvm::SmallVector<llvm::Constant *, 4> fields;
3060 // We only need one field for member functions.
3061 if (MPT->isMemberFunctionPointer())
3062 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
3063 else
3064 GetNullMemberPointerFields(MPT, fields);
3065 assert(!fields.empty());
3066 llvm::Value *FirstField = MemPtr;
3067 if (MemPtr->getType()->isStructTy())
3068 FirstField = Builder.CreateExtractValue(MemPtr, 0);
3069 llvm::Value *Res = Builder.CreateICmpNE(FirstField, fields[0], "memptr.cmp0");
3071 // For function member pointers, we only need to test the function pointer
3072 // field. The other fields if any can be garbage.
3073 if (MPT->isMemberFunctionPointer())
3074 return Res;
3076 // Otherwise, emit a series of compares and combine the results.
3077 for (int I = 1, E = fields.size(); I < E; ++I) {
3078 llvm::Value *Field = Builder.CreateExtractValue(MemPtr, I);
3079 llvm::Value *Next = Builder.CreateICmpNE(Field, fields[I], "memptr.cmp");
3080 Res = Builder.CreateOr(Res, Next, "memptr.tobool");
3082 return Res;
3085 bool MicrosoftCXXABI::MemberPointerConstantIsNull(const MemberPointerType *MPT,
3086 llvm::Constant *Val) {
3087 // Function pointers are null if the pointer in the first field is null.
3088 if (MPT->isMemberFunctionPointer()) {
3089 llvm::Constant *FirstField = Val->getType()->isStructTy() ?
3090 Val->getAggregateElement(0U) : Val;
3091 return FirstField->isNullValue();
3094 // If it's not a function pointer and it's zero initializable, we can easily
3095 // check zero.
3096 if (isZeroInitializable(MPT) && Val->isNullValue())
3097 return true;
3099 // Otherwise, break down all the fields for comparison. Hopefully these
3100 // little Constants are reused, while a big null struct might not be.
3101 llvm::SmallVector<llvm::Constant *, 4> Fields;
3102 GetNullMemberPointerFields(MPT, Fields);
3103 if (Fields.size() == 1) {
3104 assert(Val->getType()->isIntegerTy());
3105 return Val == Fields[0];
3108 unsigned I, E;
3109 for (I = 0, E = Fields.size(); I != E; ++I) {
3110 if (Val->getAggregateElement(I) != Fields[I])
3111 break;
3113 return I == E;
3116 llvm::Value *
3117 MicrosoftCXXABI::GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
3118 Address This,
3119 llvm::Value *VBPtrOffset,
3120 llvm::Value *VBTableOffset,
3121 llvm::Value **VBPtrOut) {
3122 CGBuilderTy &Builder = CGF.Builder;
3123 // Load the vbtable pointer from the vbptr in the instance.
3124 This = Builder.CreateElementBitCast(This, CGM.Int8Ty);
3125 llvm::Value *VBPtr = Builder.CreateInBoundsGEP(
3126 This.getElementType(), This.getPointer(), VBPtrOffset, "vbptr");
3127 if (VBPtrOut) *VBPtrOut = VBPtr;
3128 VBPtr = Builder.CreateBitCast(VBPtr,
3129 CGM.Int32Ty->getPointerTo(0)->getPointerTo(This.getAddressSpace()));
3131 CharUnits VBPtrAlign;
3132 if (auto CI = dyn_cast<llvm::ConstantInt>(VBPtrOffset)) {
3133 VBPtrAlign = This.getAlignment().alignmentAtOffset(
3134 CharUnits::fromQuantity(CI->getSExtValue()));
3135 } else {
3136 VBPtrAlign = CGF.getPointerAlign();
3139 llvm::Value *VBTable = Builder.CreateAlignedLoad(
3140 CGM.Int32Ty->getPointerTo(0), VBPtr, VBPtrAlign, "vbtable");
3142 // Translate from byte offset to table index. It improves analyzability.
3143 llvm::Value *VBTableIndex = Builder.CreateAShr(
3144 VBTableOffset, llvm::ConstantInt::get(VBTableOffset->getType(), 2),
3145 "vbtindex", /*isExact=*/true);
3147 // Load an i32 offset from the vb-table.
3148 llvm::Value *VBaseOffs =
3149 Builder.CreateInBoundsGEP(CGM.Int32Ty, VBTable, VBTableIndex);
3150 VBaseOffs = Builder.CreateBitCast(VBaseOffs, CGM.Int32Ty->getPointerTo(0));
3151 return Builder.CreateAlignedLoad(CGM.Int32Ty, VBaseOffs,
3152 CharUnits::fromQuantity(4), "vbase_offs");
3155 // Returns an adjusted base cast to i8*, since we do more address arithmetic on
3156 // it.
3157 llvm::Value *MicrosoftCXXABI::AdjustVirtualBase(
3158 CodeGenFunction &CGF, const Expr *E, const CXXRecordDecl *RD,
3159 Address Base, llvm::Value *VBTableOffset, llvm::Value *VBPtrOffset) {
3160 CGBuilderTy &Builder = CGF.Builder;
3161 Base = Builder.CreateElementBitCast(Base, CGM.Int8Ty);
3162 llvm::BasicBlock *OriginalBB = nullptr;
3163 llvm::BasicBlock *SkipAdjustBB = nullptr;
3164 llvm::BasicBlock *VBaseAdjustBB = nullptr;
3166 // In the unspecified inheritance model, there might not be a vbtable at all,
3167 // in which case we need to skip the virtual base lookup. If there is a
3168 // vbtable, the first entry is a no-op entry that gives back the original
3169 // base, so look for a virtual base adjustment offset of zero.
3170 if (VBPtrOffset) {
3171 OriginalBB = Builder.GetInsertBlock();
3172 VBaseAdjustBB = CGF.createBasicBlock("memptr.vadjust");
3173 SkipAdjustBB = CGF.createBasicBlock("memptr.skip_vadjust");
3174 llvm::Value *IsVirtual =
3175 Builder.CreateICmpNE(VBTableOffset, getZeroInt(),
3176 "memptr.is_vbase");
3177 Builder.CreateCondBr(IsVirtual, VBaseAdjustBB, SkipAdjustBB);
3178 CGF.EmitBlock(VBaseAdjustBB);
3181 // If we weren't given a dynamic vbptr offset, RD should be complete and we'll
3182 // know the vbptr offset.
3183 if (!VBPtrOffset) {
3184 CharUnits offs = CharUnits::Zero();
3185 if (!RD->hasDefinition()) {
3186 DiagnosticsEngine &Diags = CGF.CGM.getDiags();
3187 unsigned DiagID = Diags.getCustomDiagID(
3188 DiagnosticsEngine::Error,
3189 "member pointer representation requires a "
3190 "complete class type for %0 to perform this expression");
3191 Diags.Report(E->getExprLoc(), DiagID) << RD << E->getSourceRange();
3192 } else if (RD->getNumVBases())
3193 offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
3194 VBPtrOffset = llvm::ConstantInt::get(CGM.IntTy, offs.getQuantity());
3196 llvm::Value *VBPtr = nullptr;
3197 llvm::Value *VBaseOffs =
3198 GetVBaseOffsetFromVBPtr(CGF, Base, VBPtrOffset, VBTableOffset, &VBPtr);
3199 llvm::Value *AdjustedBase =
3200 Builder.CreateInBoundsGEP(CGM.Int8Ty, VBPtr, VBaseOffs);
3202 // Merge control flow with the case where we didn't have to adjust.
3203 if (VBaseAdjustBB) {
3204 Builder.CreateBr(SkipAdjustBB);
3205 CGF.EmitBlock(SkipAdjustBB);
3206 llvm::PHINode *Phi = Builder.CreatePHI(CGM.Int8PtrTy, 2, "memptr.base");
3207 Phi->addIncoming(Base.getPointer(), OriginalBB);
3208 Phi->addIncoming(AdjustedBase, VBaseAdjustBB);
3209 return Phi;
3211 return AdjustedBase;
3214 llvm::Value *MicrosoftCXXABI::EmitMemberDataPointerAddress(
3215 CodeGenFunction &CGF, const Expr *E, Address Base, llvm::Value *MemPtr,
3216 const MemberPointerType *MPT) {
3217 assert(MPT->isMemberDataPointer());
3218 unsigned AS = Base.getAddressSpace();
3219 llvm::Type *PType =
3220 CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
3221 CGBuilderTy &Builder = CGF.Builder;
3222 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
3223 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
3225 // Extract the fields we need, regardless of model. We'll apply them if we
3226 // have them.
3227 llvm::Value *FieldOffset = MemPtr;
3228 llvm::Value *VirtualBaseAdjustmentOffset = nullptr;
3229 llvm::Value *VBPtrOffset = nullptr;
3230 if (MemPtr->getType()->isStructTy()) {
3231 // We need to extract values.
3232 unsigned I = 0;
3233 FieldOffset = Builder.CreateExtractValue(MemPtr, I++);
3234 if (inheritanceModelHasVBPtrOffsetField(Inheritance))
3235 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
3236 if (inheritanceModelHasVBTableOffsetField(Inheritance))
3237 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
3240 llvm::Value *Addr;
3241 if (VirtualBaseAdjustmentOffset) {
3242 Addr = AdjustVirtualBase(CGF, E, RD, Base, VirtualBaseAdjustmentOffset,
3243 VBPtrOffset);
3244 } else {
3245 Addr = Base.getPointer();
3248 // Cast to char*.
3249 Addr = Builder.CreateBitCast(Addr, CGF.Int8Ty->getPointerTo(AS));
3251 // Apply the offset, which we assume is non-null.
3252 Addr = Builder.CreateInBoundsGEP(CGF.Int8Ty, Addr, FieldOffset,
3253 "memptr.offset");
3255 // Cast the address to the appropriate pointer type, adopting the address
3256 // space of the base pointer.
3257 return Builder.CreateBitCast(Addr, PType);
3260 llvm::Value *
3261 MicrosoftCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
3262 const CastExpr *E,
3263 llvm::Value *Src) {
3264 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
3265 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
3266 E->getCastKind() == CK_ReinterpretMemberPointer);
3268 // Use constant emission if we can.
3269 if (isa<llvm::Constant>(Src))
3270 return EmitMemberPointerConversion(E, cast<llvm::Constant>(Src));
3272 // We may be adding or dropping fields from the member pointer, so we need
3273 // both types and the inheritance models of both records.
3274 const MemberPointerType *SrcTy =
3275 E->getSubExpr()->getType()->castAs<MemberPointerType>();
3276 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
3277 bool IsFunc = SrcTy->isMemberFunctionPointer();
3279 // If the classes use the same null representation, reinterpret_cast is a nop.
3280 bool IsReinterpret = E->getCastKind() == CK_ReinterpretMemberPointer;
3281 if (IsReinterpret && IsFunc)
3282 return Src;
3284 CXXRecordDecl *SrcRD = SrcTy->getMostRecentCXXRecordDecl();
3285 CXXRecordDecl *DstRD = DstTy->getMostRecentCXXRecordDecl();
3286 if (IsReinterpret &&
3287 SrcRD->nullFieldOffsetIsZero() == DstRD->nullFieldOffsetIsZero())
3288 return Src;
3290 CGBuilderTy &Builder = CGF.Builder;
3292 // Branch past the conversion if Src is null.
3293 llvm::Value *IsNotNull = EmitMemberPointerIsNotNull(CGF, Src, SrcTy);
3294 llvm::Constant *DstNull = EmitNullMemberPointer(DstTy);
3296 // C++ 5.2.10p9: The null member pointer value is converted to the null member
3297 // pointer value of the destination type.
3298 if (IsReinterpret) {
3299 // For reinterpret casts, sema ensures that src and dst are both functions
3300 // or data and have the same size, which means the LLVM types should match.
3301 assert(Src->getType() == DstNull->getType());
3302 return Builder.CreateSelect(IsNotNull, Src, DstNull);
3305 llvm::BasicBlock *OriginalBB = Builder.GetInsertBlock();
3306 llvm::BasicBlock *ConvertBB = CGF.createBasicBlock("memptr.convert");
3307 llvm::BasicBlock *ContinueBB = CGF.createBasicBlock("memptr.converted");
3308 Builder.CreateCondBr(IsNotNull, ConvertBB, ContinueBB);
3309 CGF.EmitBlock(ConvertBB);
3311 llvm::Value *Dst = EmitNonNullMemberPointerConversion(
3312 SrcTy, DstTy, E->getCastKind(), E->path_begin(), E->path_end(), Src,
3313 Builder);
3315 Builder.CreateBr(ContinueBB);
3317 // In the continuation, choose between DstNull and Dst.
3318 CGF.EmitBlock(ContinueBB);
3319 llvm::PHINode *Phi = Builder.CreatePHI(DstNull->getType(), 2, "memptr.converted");
3320 Phi->addIncoming(DstNull, OriginalBB);
3321 Phi->addIncoming(Dst, ConvertBB);
3322 return Phi;
3325 llvm::Value *MicrosoftCXXABI::EmitNonNullMemberPointerConversion(
3326 const MemberPointerType *SrcTy, const MemberPointerType *DstTy, CastKind CK,
3327 CastExpr::path_const_iterator PathBegin,
3328 CastExpr::path_const_iterator PathEnd, llvm::Value *Src,
3329 CGBuilderTy &Builder) {
3330 const CXXRecordDecl *SrcRD = SrcTy->getMostRecentCXXRecordDecl();
3331 const CXXRecordDecl *DstRD = DstTy->getMostRecentCXXRecordDecl();
3332 MSInheritanceModel SrcInheritance = SrcRD->getMSInheritanceModel();
3333 MSInheritanceModel DstInheritance = DstRD->getMSInheritanceModel();
3334 bool IsFunc = SrcTy->isMemberFunctionPointer();
3335 bool IsConstant = isa<llvm::Constant>(Src);
3337 // Decompose src.
3338 llvm::Value *FirstField = Src;
3339 llvm::Value *NonVirtualBaseAdjustment = getZeroInt();
3340 llvm::Value *VirtualBaseAdjustmentOffset = getZeroInt();
3341 llvm::Value *VBPtrOffset = getZeroInt();
3342 if (!inheritanceModelHasOnlyOneField(IsFunc, SrcInheritance)) {
3343 // We need to extract values.
3344 unsigned I = 0;
3345 FirstField = Builder.CreateExtractValue(Src, I++);
3346 if (inheritanceModelHasNVOffsetField(IsFunc, SrcInheritance))
3347 NonVirtualBaseAdjustment = Builder.CreateExtractValue(Src, I++);
3348 if (inheritanceModelHasVBPtrOffsetField(SrcInheritance))
3349 VBPtrOffset = Builder.CreateExtractValue(Src, I++);
3350 if (inheritanceModelHasVBTableOffsetField(SrcInheritance))
3351 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(Src, I++);
3354 bool IsDerivedToBase = (CK == CK_DerivedToBaseMemberPointer);
3355 const MemberPointerType *DerivedTy = IsDerivedToBase ? SrcTy : DstTy;
3356 const CXXRecordDecl *DerivedClass = DerivedTy->getMostRecentCXXRecordDecl();
3358 // For data pointers, we adjust the field offset directly. For functions, we
3359 // have a separate field.
3360 llvm::Value *&NVAdjustField = IsFunc ? NonVirtualBaseAdjustment : FirstField;
3362 // The virtual inheritance model has a quirk: the virtual base table is always
3363 // referenced when dereferencing a member pointer even if the member pointer
3364 // is non-virtual. This is accounted for by adjusting the non-virtual offset
3365 // to point backwards to the top of the MDC from the first VBase. Undo this
3366 // adjustment to normalize the member pointer.
3367 llvm::Value *SrcVBIndexEqZero =
3368 Builder.CreateICmpEQ(VirtualBaseAdjustmentOffset, getZeroInt());
3369 if (SrcInheritance == MSInheritanceModel::Virtual) {
3370 if (int64_t SrcOffsetToFirstVBase =
3371 getContext().getOffsetOfBaseWithVBPtr(SrcRD).getQuantity()) {
3372 llvm::Value *UndoSrcAdjustment = Builder.CreateSelect(
3373 SrcVBIndexEqZero,
3374 llvm::ConstantInt::get(CGM.IntTy, SrcOffsetToFirstVBase),
3375 getZeroInt());
3376 NVAdjustField = Builder.CreateNSWAdd(NVAdjustField, UndoSrcAdjustment);
3380 // A non-zero vbindex implies that we are dealing with a source member in a
3381 // floating virtual base in addition to some non-virtual offset. If the
3382 // vbindex is zero, we are dealing with a source that exists in a non-virtual,
3383 // fixed, base. The difference between these two cases is that the vbindex +
3384 // nvoffset *always* point to the member regardless of what context they are
3385 // evaluated in so long as the vbindex is adjusted. A member inside a fixed
3386 // base requires explicit nv adjustment.
3387 llvm::Constant *BaseClassOffset = llvm::ConstantInt::get(
3388 CGM.IntTy,
3389 CGM.computeNonVirtualBaseClassOffset(DerivedClass, PathBegin, PathEnd)
3390 .getQuantity());
3392 llvm::Value *NVDisp;
3393 if (IsDerivedToBase)
3394 NVDisp = Builder.CreateNSWSub(NVAdjustField, BaseClassOffset, "adj");
3395 else
3396 NVDisp = Builder.CreateNSWAdd(NVAdjustField, BaseClassOffset, "adj");
3398 NVAdjustField = Builder.CreateSelect(SrcVBIndexEqZero, NVDisp, getZeroInt());
3400 // Update the vbindex to an appropriate value in the destination because
3401 // SrcRD's vbtable might not be a strict prefix of the one in DstRD.
3402 llvm::Value *DstVBIndexEqZero = SrcVBIndexEqZero;
3403 if (inheritanceModelHasVBTableOffsetField(DstInheritance) &&
3404 inheritanceModelHasVBTableOffsetField(SrcInheritance)) {
3405 if (llvm::GlobalVariable *VDispMap =
3406 getAddrOfVirtualDisplacementMap(SrcRD, DstRD)) {
3407 llvm::Value *VBIndex = Builder.CreateExactUDiv(
3408 VirtualBaseAdjustmentOffset, llvm::ConstantInt::get(CGM.IntTy, 4));
3409 if (IsConstant) {
3410 llvm::Constant *Mapping = VDispMap->getInitializer();
3411 VirtualBaseAdjustmentOffset =
3412 Mapping->getAggregateElement(cast<llvm::Constant>(VBIndex));
3413 } else {
3414 llvm::Value *Idxs[] = {getZeroInt(), VBIndex};
3415 VirtualBaseAdjustmentOffset = Builder.CreateAlignedLoad(
3416 CGM.IntTy, Builder.CreateInBoundsGEP(VDispMap->getValueType(),
3417 VDispMap, Idxs),
3418 CharUnits::fromQuantity(4));
3421 DstVBIndexEqZero =
3422 Builder.CreateICmpEQ(VirtualBaseAdjustmentOffset, getZeroInt());
3426 // Set the VBPtrOffset to zero if the vbindex is zero. Otherwise, initialize
3427 // it to the offset of the vbptr.
3428 if (inheritanceModelHasVBPtrOffsetField(DstInheritance)) {
3429 llvm::Value *DstVBPtrOffset = llvm::ConstantInt::get(
3430 CGM.IntTy,
3431 getContext().getASTRecordLayout(DstRD).getVBPtrOffset().getQuantity());
3432 VBPtrOffset =
3433 Builder.CreateSelect(DstVBIndexEqZero, getZeroInt(), DstVBPtrOffset);
3436 // Likewise, apply a similar adjustment so that dereferencing the member
3437 // pointer correctly accounts for the distance between the start of the first
3438 // virtual base and the top of the MDC.
3439 if (DstInheritance == MSInheritanceModel::Virtual) {
3440 if (int64_t DstOffsetToFirstVBase =
3441 getContext().getOffsetOfBaseWithVBPtr(DstRD).getQuantity()) {
3442 llvm::Value *DoDstAdjustment = Builder.CreateSelect(
3443 DstVBIndexEqZero,
3444 llvm::ConstantInt::get(CGM.IntTy, DstOffsetToFirstVBase),
3445 getZeroInt());
3446 NVAdjustField = Builder.CreateNSWSub(NVAdjustField, DoDstAdjustment);
3450 // Recompose dst from the null struct and the adjusted fields from src.
3451 llvm::Value *Dst;
3452 if (inheritanceModelHasOnlyOneField(IsFunc, DstInheritance)) {
3453 Dst = FirstField;
3454 } else {
3455 Dst = llvm::UndefValue::get(ConvertMemberPointerType(DstTy));
3456 unsigned Idx = 0;
3457 Dst = Builder.CreateInsertValue(Dst, FirstField, Idx++);
3458 if (inheritanceModelHasNVOffsetField(IsFunc, DstInheritance))
3459 Dst = Builder.CreateInsertValue(Dst, NonVirtualBaseAdjustment, Idx++);
3460 if (inheritanceModelHasVBPtrOffsetField(DstInheritance))
3461 Dst = Builder.CreateInsertValue(Dst, VBPtrOffset, Idx++);
3462 if (inheritanceModelHasVBTableOffsetField(DstInheritance))
3463 Dst = Builder.CreateInsertValue(Dst, VirtualBaseAdjustmentOffset, Idx++);
3465 return Dst;
3468 llvm::Constant *
3469 MicrosoftCXXABI::EmitMemberPointerConversion(const CastExpr *E,
3470 llvm::Constant *Src) {
3471 const MemberPointerType *SrcTy =
3472 E->getSubExpr()->getType()->castAs<MemberPointerType>();
3473 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
3475 CastKind CK = E->getCastKind();
3477 return EmitMemberPointerConversion(SrcTy, DstTy, CK, E->path_begin(),
3478 E->path_end(), Src);
3481 llvm::Constant *MicrosoftCXXABI::EmitMemberPointerConversion(
3482 const MemberPointerType *SrcTy, const MemberPointerType *DstTy, CastKind CK,
3483 CastExpr::path_const_iterator PathBegin,
3484 CastExpr::path_const_iterator PathEnd, llvm::Constant *Src) {
3485 assert(CK == CK_DerivedToBaseMemberPointer ||
3486 CK == CK_BaseToDerivedMemberPointer ||
3487 CK == CK_ReinterpretMemberPointer);
3488 // If src is null, emit a new null for dst. We can't return src because dst
3489 // might have a new representation.
3490 if (MemberPointerConstantIsNull(SrcTy, Src))
3491 return EmitNullMemberPointer(DstTy);
3493 // We don't need to do anything for reinterpret_casts of non-null member
3494 // pointers. We should only get here when the two type representations have
3495 // the same size.
3496 if (CK == CK_ReinterpretMemberPointer)
3497 return Src;
3499 CGBuilderTy Builder(CGM, CGM.getLLVMContext());
3500 auto *Dst = cast<llvm::Constant>(EmitNonNullMemberPointerConversion(
3501 SrcTy, DstTy, CK, PathBegin, PathEnd, Src, Builder));
3503 return Dst;
3506 CGCallee MicrosoftCXXABI::EmitLoadOfMemberFunctionPointer(
3507 CodeGenFunction &CGF, const Expr *E, Address This,
3508 llvm::Value *&ThisPtrForCall, llvm::Value *MemPtr,
3509 const MemberPointerType *MPT) {
3510 assert(MPT->isMemberFunctionPointer());
3511 const FunctionProtoType *FPT =
3512 MPT->getPointeeType()->castAs<FunctionProtoType>();
3513 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
3514 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(
3515 CGM.getTypes().arrangeCXXMethodType(RD, FPT, /*FD=*/nullptr));
3516 CGBuilderTy &Builder = CGF.Builder;
3518 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
3520 // Extract the fields we need, regardless of model. We'll apply them if we
3521 // have them.
3522 llvm::Value *FunctionPointer = MemPtr;
3523 llvm::Value *NonVirtualBaseAdjustment = nullptr;
3524 llvm::Value *VirtualBaseAdjustmentOffset = nullptr;
3525 llvm::Value *VBPtrOffset = nullptr;
3526 if (MemPtr->getType()->isStructTy()) {
3527 // We need to extract values.
3528 unsigned I = 0;
3529 FunctionPointer = Builder.CreateExtractValue(MemPtr, I++);
3530 if (inheritanceModelHasNVOffsetField(MPT, Inheritance))
3531 NonVirtualBaseAdjustment = Builder.CreateExtractValue(MemPtr, I++);
3532 if (inheritanceModelHasVBPtrOffsetField(Inheritance))
3533 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
3534 if (inheritanceModelHasVBTableOffsetField(Inheritance))
3535 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
3538 if (VirtualBaseAdjustmentOffset) {
3539 ThisPtrForCall = AdjustVirtualBase(CGF, E, RD, This,
3540 VirtualBaseAdjustmentOffset, VBPtrOffset);
3541 } else {
3542 ThisPtrForCall = This.getPointer();
3545 if (NonVirtualBaseAdjustment) {
3546 // Apply the adjustment and cast back to the original struct type.
3547 llvm::Value *Ptr = Builder.CreateBitCast(ThisPtrForCall, CGF.Int8PtrTy);
3548 Ptr = Builder.CreateInBoundsGEP(CGF.Int8Ty, Ptr, NonVirtualBaseAdjustment);
3549 ThisPtrForCall = Builder.CreateBitCast(Ptr, ThisPtrForCall->getType(),
3550 "this.adjusted");
3553 FunctionPointer =
3554 Builder.CreateBitCast(FunctionPointer, FTy->getPointerTo());
3555 CGCallee Callee(FPT, FunctionPointer);
3556 return Callee;
3559 CGCXXABI *clang::CodeGen::CreateMicrosoftCXXABI(CodeGenModule &CGM) {
3560 return new MicrosoftCXXABI(CGM);
3563 // MS RTTI Overview:
3564 // The run time type information emitted by cl.exe contains 5 distinct types of
3565 // structures. Many of them reference each other.
3567 // TypeInfo: Static classes that are returned by typeid.
3569 // CompleteObjectLocator: Referenced by vftables. They contain information
3570 // required for dynamic casting, including OffsetFromTop. They also contain
3571 // a reference to the TypeInfo for the type and a reference to the
3572 // CompleteHierarchyDescriptor for the type.
3574 // ClassHierarchyDescriptor: Contains information about a class hierarchy.
3575 // Used during dynamic_cast to walk a class hierarchy. References a base
3576 // class array and the size of said array.
3578 // BaseClassArray: Contains a list of classes in a hierarchy. BaseClassArray is
3579 // somewhat of a misnomer because the most derived class is also in the list
3580 // as well as multiple copies of virtual bases (if they occur multiple times
3581 // in the hierarchy.) The BaseClassArray contains one BaseClassDescriptor for
3582 // every path in the hierarchy, in pre-order depth first order. Note, we do
3583 // not declare a specific llvm type for BaseClassArray, it's merely an array
3584 // of BaseClassDescriptor pointers.
3586 // BaseClassDescriptor: Contains information about a class in a class hierarchy.
3587 // BaseClassDescriptor is also somewhat of a misnomer for the same reason that
3588 // BaseClassArray is. It contains information about a class within a
3589 // hierarchy such as: is this base is ambiguous and what is its offset in the
3590 // vbtable. The names of the BaseClassDescriptors have all of their fields
3591 // mangled into them so they can be aggressively deduplicated by the linker.
3593 static llvm::GlobalVariable *getTypeInfoVTable(CodeGenModule &CGM) {
3594 StringRef MangledName("??_7type_info@@6B@");
3595 if (auto VTable = CGM.getModule().getNamedGlobal(MangledName))
3596 return VTable;
3597 return new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
3598 /*isConstant=*/true,
3599 llvm::GlobalVariable::ExternalLinkage,
3600 /*Initializer=*/nullptr, MangledName);
3603 namespace {
3605 /// A Helper struct that stores information about a class in a class
3606 /// hierarchy. The information stored in these structs struct is used during
3607 /// the generation of ClassHierarchyDescriptors and BaseClassDescriptors.
3608 // During RTTI creation, MSRTTIClasses are stored in a contiguous array with
3609 // implicit depth first pre-order tree connectivity. getFirstChild and
3610 // getNextSibling allow us to walk the tree efficiently.
3611 struct MSRTTIClass {
3612 enum {
3613 IsPrivateOnPath = 1 | 8,
3614 IsAmbiguous = 2,
3615 IsPrivate = 4,
3616 IsVirtual = 16,
3617 HasHierarchyDescriptor = 64
3619 MSRTTIClass(const CXXRecordDecl *RD) : RD(RD) {}
3620 uint32_t initialize(const MSRTTIClass *Parent,
3621 const CXXBaseSpecifier *Specifier);
3623 MSRTTIClass *getFirstChild() { return this + 1; }
3624 static MSRTTIClass *getNextChild(MSRTTIClass *Child) {
3625 return Child + 1 + Child->NumBases;
3628 const CXXRecordDecl *RD, *VirtualRoot;
3629 uint32_t Flags, NumBases, OffsetInVBase;
3632 /// Recursively initialize the base class array.
3633 uint32_t MSRTTIClass::initialize(const MSRTTIClass *Parent,
3634 const CXXBaseSpecifier *Specifier) {
3635 Flags = HasHierarchyDescriptor;
3636 if (!Parent) {
3637 VirtualRoot = nullptr;
3638 OffsetInVBase = 0;
3639 } else {
3640 if (Specifier->getAccessSpecifier() != AS_public)
3641 Flags |= IsPrivate | IsPrivateOnPath;
3642 if (Specifier->isVirtual()) {
3643 Flags |= IsVirtual;
3644 VirtualRoot = RD;
3645 OffsetInVBase = 0;
3646 } else {
3647 if (Parent->Flags & IsPrivateOnPath)
3648 Flags |= IsPrivateOnPath;
3649 VirtualRoot = Parent->VirtualRoot;
3650 OffsetInVBase = Parent->OffsetInVBase + RD->getASTContext()
3651 .getASTRecordLayout(Parent->RD).getBaseClassOffset(RD).getQuantity();
3654 NumBases = 0;
3655 MSRTTIClass *Child = getFirstChild();
3656 for (const CXXBaseSpecifier &Base : RD->bases()) {
3657 NumBases += Child->initialize(this, &Base) + 1;
3658 Child = getNextChild(Child);
3660 return NumBases;
3663 static llvm::GlobalValue::LinkageTypes getLinkageForRTTI(QualType Ty) {
3664 switch (Ty->getLinkage()) {
3665 case NoLinkage:
3666 case InternalLinkage:
3667 case UniqueExternalLinkage:
3668 return llvm::GlobalValue::InternalLinkage;
3670 case VisibleNoLinkage:
3671 case ModuleLinkage:
3672 case ExternalLinkage:
3673 return llvm::GlobalValue::LinkOnceODRLinkage;
3675 llvm_unreachable("Invalid linkage!");
3678 /// An ephemeral helper class for building MS RTTI types. It caches some
3679 /// calls to the module and information about the most derived class in a
3680 /// hierarchy.
3681 struct MSRTTIBuilder {
3682 enum {
3683 HasBranchingHierarchy = 1,
3684 HasVirtualBranchingHierarchy = 2,
3685 HasAmbiguousBases = 4
3688 MSRTTIBuilder(MicrosoftCXXABI &ABI, const CXXRecordDecl *RD)
3689 : CGM(ABI.CGM), Context(CGM.getContext()),
3690 VMContext(CGM.getLLVMContext()), Module(CGM.getModule()), RD(RD),
3691 Linkage(getLinkageForRTTI(CGM.getContext().getTagDeclType(RD))),
3692 ABI(ABI) {}
3694 llvm::GlobalVariable *getBaseClassDescriptor(const MSRTTIClass &Classes);
3695 llvm::GlobalVariable *
3696 getBaseClassArray(SmallVectorImpl<MSRTTIClass> &Classes);
3697 llvm::GlobalVariable *getClassHierarchyDescriptor();
3698 llvm::GlobalVariable *getCompleteObjectLocator(const VPtrInfo &Info);
3700 CodeGenModule &CGM;
3701 ASTContext &Context;
3702 llvm::LLVMContext &VMContext;
3703 llvm::Module &Module;
3704 const CXXRecordDecl *RD;
3705 llvm::GlobalVariable::LinkageTypes Linkage;
3706 MicrosoftCXXABI &ABI;
3709 } // namespace
3711 /// Recursively serializes a class hierarchy in pre-order depth first
3712 /// order.
3713 static void serializeClassHierarchy(SmallVectorImpl<MSRTTIClass> &Classes,
3714 const CXXRecordDecl *RD) {
3715 Classes.push_back(MSRTTIClass(RD));
3716 for (const CXXBaseSpecifier &Base : RD->bases())
3717 serializeClassHierarchy(Classes, Base.getType()->getAsCXXRecordDecl());
3720 /// Find ambiguity among base classes.
3721 static void
3722 detectAmbiguousBases(SmallVectorImpl<MSRTTIClass> &Classes) {
3723 llvm::SmallPtrSet<const CXXRecordDecl *, 8> VirtualBases;
3724 llvm::SmallPtrSet<const CXXRecordDecl *, 8> UniqueBases;
3725 llvm::SmallPtrSet<const CXXRecordDecl *, 8> AmbiguousBases;
3726 for (MSRTTIClass *Class = &Classes.front(); Class <= &Classes.back();) {
3727 if ((Class->Flags & MSRTTIClass::IsVirtual) &&
3728 !VirtualBases.insert(Class->RD).second) {
3729 Class = MSRTTIClass::getNextChild(Class);
3730 continue;
3732 if (!UniqueBases.insert(Class->RD).second)
3733 AmbiguousBases.insert(Class->RD);
3734 Class++;
3736 if (AmbiguousBases.empty())
3737 return;
3738 for (MSRTTIClass &Class : Classes)
3739 if (AmbiguousBases.count(Class.RD))
3740 Class.Flags |= MSRTTIClass::IsAmbiguous;
3743 llvm::GlobalVariable *MSRTTIBuilder::getClassHierarchyDescriptor() {
3744 SmallString<256> MangledName;
3746 llvm::raw_svector_ostream Out(MangledName);
3747 ABI.getMangleContext().mangleCXXRTTIClassHierarchyDescriptor(RD, Out);
3750 // Check to see if we've already declared this ClassHierarchyDescriptor.
3751 if (auto CHD = Module.getNamedGlobal(MangledName))
3752 return CHD;
3754 // Serialize the class hierarchy and initialize the CHD Fields.
3755 SmallVector<MSRTTIClass, 8> Classes;
3756 serializeClassHierarchy(Classes, RD);
3757 Classes.front().initialize(/*Parent=*/nullptr, /*Specifier=*/nullptr);
3758 detectAmbiguousBases(Classes);
3759 int Flags = 0;
3760 for (const MSRTTIClass &Class : Classes) {
3761 if (Class.RD->getNumBases() > 1)
3762 Flags |= HasBranchingHierarchy;
3763 // Note: cl.exe does not calculate "HasAmbiguousBases" correctly. We
3764 // believe the field isn't actually used.
3765 if (Class.Flags & MSRTTIClass::IsAmbiguous)
3766 Flags |= HasAmbiguousBases;
3768 if ((Flags & HasBranchingHierarchy) && RD->getNumVBases() != 0)
3769 Flags |= HasVirtualBranchingHierarchy;
3770 // These gep indices are used to get the address of the first element of the
3771 // base class array.
3772 llvm::Value *GEPIndices[] = {llvm::ConstantInt::get(CGM.IntTy, 0),
3773 llvm::ConstantInt::get(CGM.IntTy, 0)};
3775 // Forward-declare the class hierarchy descriptor
3776 auto Type = ABI.getClassHierarchyDescriptorType();
3777 auto CHD = new llvm::GlobalVariable(Module, Type, /*isConstant=*/true, Linkage,
3778 /*Initializer=*/nullptr,
3779 MangledName);
3780 if (CHD->isWeakForLinker())
3781 CHD->setComdat(CGM.getModule().getOrInsertComdat(CHD->getName()));
3783 auto *Bases = getBaseClassArray(Classes);
3785 // Initialize the base class ClassHierarchyDescriptor.
3786 llvm::Constant *Fields[] = {
3787 llvm::ConstantInt::get(CGM.IntTy, 0), // reserved by the runtime
3788 llvm::ConstantInt::get(CGM.IntTy, Flags),
3789 llvm::ConstantInt::get(CGM.IntTy, Classes.size()),
3790 ABI.getImageRelativeConstant(llvm::ConstantExpr::getInBoundsGetElementPtr(
3791 Bases->getValueType(), Bases,
3792 llvm::ArrayRef<llvm::Value *>(GEPIndices))),
3794 CHD->setInitializer(llvm::ConstantStruct::get(Type, Fields));
3795 return CHD;
3798 llvm::GlobalVariable *
3799 MSRTTIBuilder::getBaseClassArray(SmallVectorImpl<MSRTTIClass> &Classes) {
3800 SmallString<256> MangledName;
3802 llvm::raw_svector_ostream Out(MangledName);
3803 ABI.getMangleContext().mangleCXXRTTIBaseClassArray(RD, Out);
3806 // Forward-declare the base class array.
3807 // cl.exe pads the base class array with 1 (in 32 bit mode) or 4 (in 64 bit
3808 // mode) bytes of padding. We provide a pointer sized amount of padding by
3809 // adding +1 to Classes.size(). The sections have pointer alignment and are
3810 // marked pick-any so it shouldn't matter.
3811 llvm::Type *PtrType = ABI.getImageRelativeType(
3812 ABI.getBaseClassDescriptorType()->getPointerTo());
3813 auto *ArrType = llvm::ArrayType::get(PtrType, Classes.size() + 1);
3814 auto *BCA =
3815 new llvm::GlobalVariable(Module, ArrType,
3816 /*isConstant=*/true, Linkage,
3817 /*Initializer=*/nullptr, MangledName);
3818 if (BCA->isWeakForLinker())
3819 BCA->setComdat(CGM.getModule().getOrInsertComdat(BCA->getName()));
3821 // Initialize the BaseClassArray.
3822 SmallVector<llvm::Constant *, 8> BaseClassArrayData;
3823 for (MSRTTIClass &Class : Classes)
3824 BaseClassArrayData.push_back(
3825 ABI.getImageRelativeConstant(getBaseClassDescriptor(Class)));
3826 BaseClassArrayData.push_back(llvm::Constant::getNullValue(PtrType));
3827 BCA->setInitializer(llvm::ConstantArray::get(ArrType, BaseClassArrayData));
3828 return BCA;
3831 llvm::GlobalVariable *
3832 MSRTTIBuilder::getBaseClassDescriptor(const MSRTTIClass &Class) {
3833 // Compute the fields for the BaseClassDescriptor. They are computed up front
3834 // because they are mangled into the name of the object.
3835 uint32_t OffsetInVBTable = 0;
3836 int32_t VBPtrOffset = -1;
3837 if (Class.VirtualRoot) {
3838 auto &VTableContext = CGM.getMicrosoftVTableContext();
3839 OffsetInVBTable = VTableContext.getVBTableIndex(RD, Class.VirtualRoot) * 4;
3840 VBPtrOffset = Context.getASTRecordLayout(RD).getVBPtrOffset().getQuantity();
3843 SmallString<256> MangledName;
3845 llvm::raw_svector_ostream Out(MangledName);
3846 ABI.getMangleContext().mangleCXXRTTIBaseClassDescriptor(
3847 Class.RD, Class.OffsetInVBase, VBPtrOffset, OffsetInVBTable,
3848 Class.Flags, Out);
3851 // Check to see if we've already declared this object.
3852 if (auto BCD = Module.getNamedGlobal(MangledName))
3853 return BCD;
3855 // Forward-declare the base class descriptor.
3856 auto Type = ABI.getBaseClassDescriptorType();
3857 auto BCD =
3858 new llvm::GlobalVariable(Module, Type, /*isConstant=*/true, Linkage,
3859 /*Initializer=*/nullptr, MangledName);
3860 if (BCD->isWeakForLinker())
3861 BCD->setComdat(CGM.getModule().getOrInsertComdat(BCD->getName()));
3863 // Initialize the BaseClassDescriptor.
3864 llvm::Constant *Fields[] = {
3865 ABI.getImageRelativeConstant(
3866 ABI.getAddrOfRTTIDescriptor(Context.getTypeDeclType(Class.RD))),
3867 llvm::ConstantInt::get(CGM.IntTy, Class.NumBases),
3868 llvm::ConstantInt::get(CGM.IntTy, Class.OffsetInVBase),
3869 llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset),
3870 llvm::ConstantInt::get(CGM.IntTy, OffsetInVBTable),
3871 llvm::ConstantInt::get(CGM.IntTy, Class.Flags),
3872 ABI.getImageRelativeConstant(
3873 MSRTTIBuilder(ABI, Class.RD).getClassHierarchyDescriptor()),
3875 BCD->setInitializer(llvm::ConstantStruct::get(Type, Fields));
3876 return BCD;
3879 llvm::GlobalVariable *
3880 MSRTTIBuilder::getCompleteObjectLocator(const VPtrInfo &Info) {
3881 SmallString<256> MangledName;
3883 llvm::raw_svector_ostream Out(MangledName);
3884 ABI.getMangleContext().mangleCXXRTTICompleteObjectLocator(RD, Info.MangledPath, Out);
3887 // Check to see if we've already computed this complete object locator.
3888 if (auto COL = Module.getNamedGlobal(MangledName))
3889 return COL;
3891 // Compute the fields of the complete object locator.
3892 int OffsetToTop = Info.FullOffsetInMDC.getQuantity();
3893 int VFPtrOffset = 0;
3894 // The offset includes the vtordisp if one exists.
3895 if (const CXXRecordDecl *VBase = Info.getVBaseWithVPtr())
3896 if (Context.getASTRecordLayout(RD)
3897 .getVBaseOffsetsMap()
3898 .find(VBase)
3899 ->second.hasVtorDisp())
3900 VFPtrOffset = Info.NonVirtualOffset.getQuantity() + 4;
3902 // Forward-declare the complete object locator.
3903 llvm::StructType *Type = ABI.getCompleteObjectLocatorType();
3904 auto COL = new llvm::GlobalVariable(Module, Type, /*isConstant=*/true, Linkage,
3905 /*Initializer=*/nullptr, MangledName);
3907 // Initialize the CompleteObjectLocator.
3908 llvm::Constant *Fields[] = {
3909 llvm::ConstantInt::get(CGM.IntTy, ABI.isImageRelative()),
3910 llvm::ConstantInt::get(CGM.IntTy, OffsetToTop),
3911 llvm::ConstantInt::get(CGM.IntTy, VFPtrOffset),
3912 ABI.getImageRelativeConstant(
3913 CGM.GetAddrOfRTTIDescriptor(Context.getTypeDeclType(RD))),
3914 ABI.getImageRelativeConstant(getClassHierarchyDescriptor()),
3915 ABI.getImageRelativeConstant(COL),
3917 llvm::ArrayRef<llvm::Constant *> FieldsRef(Fields);
3918 if (!ABI.isImageRelative())
3919 FieldsRef = FieldsRef.drop_back();
3920 COL->setInitializer(llvm::ConstantStruct::get(Type, FieldsRef));
3921 if (COL->isWeakForLinker())
3922 COL->setComdat(CGM.getModule().getOrInsertComdat(COL->getName()));
3923 return COL;
3926 static QualType decomposeTypeForEH(ASTContext &Context, QualType T,
3927 bool &IsConst, bool &IsVolatile,
3928 bool &IsUnaligned) {
3929 T = Context.getExceptionObjectType(T);
3931 // C++14 [except.handle]p3:
3932 // A handler is a match for an exception object of type E if [...]
3933 // - the handler is of type cv T or const T& where T is a pointer type and
3934 // E is a pointer type that can be converted to T by [...]
3935 // - a qualification conversion
3936 IsConst = false;
3937 IsVolatile = false;
3938 IsUnaligned = false;
3939 QualType PointeeType = T->getPointeeType();
3940 if (!PointeeType.isNull()) {
3941 IsConst = PointeeType.isConstQualified();
3942 IsVolatile = PointeeType.isVolatileQualified();
3943 IsUnaligned = PointeeType.getQualifiers().hasUnaligned();
3946 // Member pointer types like "const int A::*" are represented by having RTTI
3947 // for "int A::*" and separately storing the const qualifier.
3948 if (const auto *MPTy = T->getAs<MemberPointerType>())
3949 T = Context.getMemberPointerType(PointeeType.getUnqualifiedType(),
3950 MPTy->getClass());
3952 // Pointer types like "const int * const *" are represented by having RTTI
3953 // for "const int **" and separately storing the const qualifier.
3954 if (T->isPointerType())
3955 T = Context.getPointerType(PointeeType.getUnqualifiedType());
3957 return T;
3960 CatchTypeInfo
3961 MicrosoftCXXABI::getAddrOfCXXCatchHandlerType(QualType Type,
3962 QualType CatchHandlerType) {
3963 // TypeDescriptors for exceptions never have qualified pointer types,
3964 // qualifiers are stored separately in order to support qualification
3965 // conversions.
3966 bool IsConst, IsVolatile, IsUnaligned;
3967 Type =
3968 decomposeTypeForEH(getContext(), Type, IsConst, IsVolatile, IsUnaligned);
3970 bool IsReference = CatchHandlerType->isReferenceType();
3972 uint32_t Flags = 0;
3973 if (IsConst)
3974 Flags |= 1;
3975 if (IsVolatile)
3976 Flags |= 2;
3977 if (IsUnaligned)
3978 Flags |= 4;
3979 if (IsReference)
3980 Flags |= 8;
3982 return CatchTypeInfo{getAddrOfRTTIDescriptor(Type)->stripPointerCasts(),
3983 Flags};
3986 /// Gets a TypeDescriptor. Returns a llvm::Constant * rather than a
3987 /// llvm::GlobalVariable * because different type descriptors have different
3988 /// types, and need to be abstracted. They are abstracting by casting the
3989 /// address to an Int8PtrTy.
3990 llvm::Constant *MicrosoftCXXABI::getAddrOfRTTIDescriptor(QualType Type) {
3991 SmallString<256> MangledName;
3993 llvm::raw_svector_ostream Out(MangledName);
3994 getMangleContext().mangleCXXRTTI(Type, Out);
3997 // Check to see if we've already declared this TypeDescriptor.
3998 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
3999 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
4001 // Note for the future: If we would ever like to do deferred emission of
4002 // RTTI, check if emitting vtables opportunistically need any adjustment.
4004 // Compute the fields for the TypeDescriptor.
4005 SmallString<256> TypeInfoString;
4007 llvm::raw_svector_ostream Out(TypeInfoString);
4008 getMangleContext().mangleCXXRTTIName(Type, Out);
4011 // Declare and initialize the TypeDescriptor.
4012 llvm::Constant *Fields[] = {
4013 getTypeInfoVTable(CGM), // VFPtr
4014 llvm::ConstantPointerNull::get(CGM.Int8PtrTy), // Runtime data
4015 llvm::ConstantDataArray::getString(CGM.getLLVMContext(), TypeInfoString)};
4016 llvm::StructType *TypeDescriptorType =
4017 getTypeDescriptorType(TypeInfoString);
4018 auto *Var = new llvm::GlobalVariable(
4019 CGM.getModule(), TypeDescriptorType, /*isConstant=*/false,
4020 getLinkageForRTTI(Type),
4021 llvm::ConstantStruct::get(TypeDescriptorType, Fields),
4022 MangledName);
4023 if (Var->isWeakForLinker())
4024 Var->setComdat(CGM.getModule().getOrInsertComdat(Var->getName()));
4025 return llvm::ConstantExpr::getBitCast(Var, CGM.Int8PtrTy);
4028 /// Gets or a creates a Microsoft CompleteObjectLocator.
4029 llvm::GlobalVariable *
4030 MicrosoftCXXABI::getMSCompleteObjectLocator(const CXXRecordDecl *RD,
4031 const VPtrInfo &Info) {
4032 return MSRTTIBuilder(*this, RD).getCompleteObjectLocator(Info);
4035 void MicrosoftCXXABI::emitCXXStructor(GlobalDecl GD) {
4036 if (auto *ctor = dyn_cast<CXXConstructorDecl>(GD.getDecl())) {
4037 // There are no constructor variants, always emit the complete destructor.
4038 llvm::Function *Fn =
4039 CGM.codegenCXXStructor(GD.getWithCtorType(Ctor_Complete));
4040 CGM.maybeSetTrivialComdat(*ctor, *Fn);
4041 return;
4044 auto *dtor = cast<CXXDestructorDecl>(GD.getDecl());
4046 // Emit the base destructor if the base and complete (vbase) destructors are
4047 // equivalent. This effectively implements -mconstructor-aliases as part of
4048 // the ABI.
4049 if (GD.getDtorType() == Dtor_Complete &&
4050 dtor->getParent()->getNumVBases() == 0)
4051 GD = GD.getWithDtorType(Dtor_Base);
4053 // The base destructor is equivalent to the base destructor of its
4054 // base class if there is exactly one non-virtual base class with a
4055 // non-trivial destructor, there are no fields with a non-trivial
4056 // destructor, and the body of the destructor is trivial.
4057 if (GD.getDtorType() == Dtor_Base && !CGM.TryEmitBaseDestructorAsAlias(dtor))
4058 return;
4060 llvm::Function *Fn = CGM.codegenCXXStructor(GD);
4061 if (Fn->isWeakForLinker())
4062 Fn->setComdat(CGM.getModule().getOrInsertComdat(Fn->getName()));
4065 llvm::Function *
4066 MicrosoftCXXABI::getAddrOfCXXCtorClosure(const CXXConstructorDecl *CD,
4067 CXXCtorType CT) {
4068 assert(CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure);
4070 // Calculate the mangled name.
4071 SmallString<256> ThunkName;
4072 llvm::raw_svector_ostream Out(ThunkName);
4073 getMangleContext().mangleName(GlobalDecl(CD, CT), Out);
4075 // If the thunk has been generated previously, just return it.
4076 if (llvm::GlobalValue *GV = CGM.getModule().getNamedValue(ThunkName))
4077 return cast<llvm::Function>(GV);
4079 // Create the llvm::Function.
4080 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeMSCtorClosure(CD, CT);
4081 llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo);
4082 const CXXRecordDecl *RD = CD->getParent();
4083 QualType RecordTy = getContext().getRecordType(RD);
4084 llvm::Function *ThunkFn = llvm::Function::Create(
4085 ThunkTy, getLinkageForRTTI(RecordTy), ThunkName.str(), &CGM.getModule());
4086 ThunkFn->setCallingConv(static_cast<llvm::CallingConv::ID>(
4087 FnInfo.getEffectiveCallingConvention()));
4088 if (ThunkFn->isWeakForLinker())
4089 ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));
4090 bool IsCopy = CT == Ctor_CopyingClosure;
4092 // Start codegen.
4093 CodeGenFunction CGF(CGM);
4094 CGF.CurGD = GlobalDecl(CD, Ctor_Complete);
4096 // Build FunctionArgs.
4097 FunctionArgList FunctionArgs;
4099 // A constructor always starts with a 'this' pointer as its first argument.
4100 buildThisParam(CGF, FunctionArgs);
4102 // Following the 'this' pointer is a reference to the source object that we
4103 // are copying from.
4104 ImplicitParamDecl SrcParam(
4105 getContext(), /*DC=*/nullptr, SourceLocation(),
4106 &getContext().Idents.get("src"),
4107 getContext().getLValueReferenceType(RecordTy,
4108 /*SpelledAsLValue=*/true),
4109 ImplicitParamDecl::Other);
4110 if (IsCopy)
4111 FunctionArgs.push_back(&SrcParam);
4113 // Constructors for classes which utilize virtual bases have an additional
4114 // parameter which indicates whether or not it is being delegated to by a more
4115 // derived constructor.
4116 ImplicitParamDecl IsMostDerived(getContext(), /*DC=*/nullptr,
4117 SourceLocation(),
4118 &getContext().Idents.get("is_most_derived"),
4119 getContext().IntTy, ImplicitParamDecl::Other);
4120 // Only add the parameter to the list if the class has virtual bases.
4121 if (RD->getNumVBases() > 0)
4122 FunctionArgs.push_back(&IsMostDerived);
4124 // Start defining the function.
4125 auto NL = ApplyDebugLocation::CreateEmpty(CGF);
4126 CGF.StartFunction(GlobalDecl(), FnInfo.getReturnType(), ThunkFn, FnInfo,
4127 FunctionArgs, CD->getLocation(), SourceLocation());
4128 // Create a scope with an artificial location for the body of this function.
4129 auto AL = ApplyDebugLocation::CreateArtificial(CGF);
4130 setCXXABIThisValue(CGF, loadIncomingCXXThis(CGF));
4131 llvm::Value *This = getThisValue(CGF);
4133 llvm::Value *SrcVal =
4134 IsCopy ? CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&SrcParam), "src")
4135 : nullptr;
4137 CallArgList Args;
4139 // Push the this ptr.
4140 Args.add(RValue::get(This), CD->getThisType());
4142 // Push the src ptr.
4143 if (SrcVal)
4144 Args.add(RValue::get(SrcVal), SrcParam.getType());
4146 // Add the rest of the default arguments.
4147 SmallVector<const Stmt *, 4> ArgVec;
4148 ArrayRef<ParmVarDecl *> params = CD->parameters().drop_front(IsCopy ? 1 : 0);
4149 for (const ParmVarDecl *PD : params) {
4150 assert(PD->hasDefaultArg() && "ctor closure lacks default args");
4151 ArgVec.push_back(PD->getDefaultArg());
4154 CodeGenFunction::RunCleanupsScope Cleanups(CGF);
4156 const auto *FPT = CD->getType()->castAs<FunctionProtoType>();
4157 CGF.EmitCallArgs(Args, FPT, llvm::ArrayRef(ArgVec), CD, IsCopy ? 1 : 0);
4159 // Insert any ABI-specific implicit constructor arguments.
4160 AddedStructorArgCounts ExtraArgs =
4161 addImplicitConstructorArgs(CGF, CD, Ctor_Complete,
4162 /*ForVirtualBase=*/false,
4163 /*Delegating=*/false, Args);
4164 // Call the destructor with our arguments.
4165 llvm::Constant *CalleePtr =
4166 CGM.getAddrOfCXXStructor(GlobalDecl(CD, Ctor_Complete));
4167 CGCallee Callee =
4168 CGCallee::forDirect(CalleePtr, GlobalDecl(CD, Ctor_Complete));
4169 const CGFunctionInfo &CalleeInfo = CGM.getTypes().arrangeCXXConstructorCall(
4170 Args, CD, Ctor_Complete, ExtraArgs.Prefix, ExtraArgs.Suffix);
4171 CGF.EmitCall(CalleeInfo, Callee, ReturnValueSlot(), Args);
4173 Cleanups.ForceCleanup();
4175 // Emit the ret instruction, remove any temporary instructions created for the
4176 // aid of CodeGen.
4177 CGF.FinishFunction(SourceLocation());
4179 return ThunkFn;
4182 llvm::Constant *MicrosoftCXXABI::getCatchableType(QualType T,
4183 uint32_t NVOffset,
4184 int32_t VBPtrOffset,
4185 uint32_t VBIndex) {
4186 assert(!T->isReferenceType());
4188 CXXRecordDecl *RD = T->getAsCXXRecordDecl();
4189 const CXXConstructorDecl *CD =
4190 RD ? CGM.getContext().getCopyConstructorForExceptionObject(RD) : nullptr;
4191 CXXCtorType CT = Ctor_Complete;
4192 if (CD)
4193 if (!hasDefaultCXXMethodCC(getContext(), CD) || CD->getNumParams() != 1)
4194 CT = Ctor_CopyingClosure;
4196 uint32_t Size = getContext().getTypeSizeInChars(T).getQuantity();
4197 SmallString<256> MangledName;
4199 llvm::raw_svector_ostream Out(MangledName);
4200 getMangleContext().mangleCXXCatchableType(T, CD, CT, Size, NVOffset,
4201 VBPtrOffset, VBIndex, Out);
4203 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
4204 return getImageRelativeConstant(GV);
4206 // The TypeDescriptor is used by the runtime to determine if a catch handler
4207 // is appropriate for the exception object.
4208 llvm::Constant *TD = getImageRelativeConstant(getAddrOfRTTIDescriptor(T));
4210 // The runtime is responsible for calling the copy constructor if the
4211 // exception is caught by value.
4212 llvm::Constant *CopyCtor;
4213 if (CD) {
4214 if (CT == Ctor_CopyingClosure)
4215 CopyCtor = getAddrOfCXXCtorClosure(CD, Ctor_CopyingClosure);
4216 else
4217 CopyCtor = CGM.getAddrOfCXXStructor(GlobalDecl(CD, Ctor_Complete));
4219 CopyCtor = llvm::ConstantExpr::getBitCast(CopyCtor, CGM.Int8PtrTy);
4220 } else {
4221 CopyCtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);
4223 CopyCtor = getImageRelativeConstant(CopyCtor);
4225 bool IsScalar = !RD;
4226 bool HasVirtualBases = false;
4227 bool IsStdBadAlloc = false; // std::bad_alloc is special for some reason.
4228 QualType PointeeType = T;
4229 if (T->isPointerType())
4230 PointeeType = T->getPointeeType();
4231 if (const CXXRecordDecl *RD = PointeeType->getAsCXXRecordDecl()) {
4232 HasVirtualBases = RD->getNumVBases() > 0;
4233 if (IdentifierInfo *II = RD->getIdentifier())
4234 IsStdBadAlloc = II->isStr("bad_alloc") && RD->isInStdNamespace();
4237 // Encode the relevant CatchableType properties into the Flags bitfield.
4238 // FIXME: Figure out how bits 2 or 8 can get set.
4239 uint32_t Flags = 0;
4240 if (IsScalar)
4241 Flags |= 1;
4242 if (HasVirtualBases)
4243 Flags |= 4;
4244 if (IsStdBadAlloc)
4245 Flags |= 16;
4247 llvm::Constant *Fields[] = {
4248 llvm::ConstantInt::get(CGM.IntTy, Flags), // Flags
4249 TD, // TypeDescriptor
4250 llvm::ConstantInt::get(CGM.IntTy, NVOffset), // NonVirtualAdjustment
4251 llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset), // OffsetToVBPtr
4252 llvm::ConstantInt::get(CGM.IntTy, VBIndex), // VBTableIndex
4253 llvm::ConstantInt::get(CGM.IntTy, Size), // Size
4254 CopyCtor // CopyCtor
4256 llvm::StructType *CTType = getCatchableTypeType();
4257 auto *GV = new llvm::GlobalVariable(
4258 CGM.getModule(), CTType, /*isConstant=*/true, getLinkageForRTTI(T),
4259 llvm::ConstantStruct::get(CTType, Fields), MangledName);
4260 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4261 GV->setSection(".xdata");
4262 if (GV->isWeakForLinker())
4263 GV->setComdat(CGM.getModule().getOrInsertComdat(GV->getName()));
4264 return getImageRelativeConstant(GV);
4267 llvm::GlobalVariable *MicrosoftCXXABI::getCatchableTypeArray(QualType T) {
4268 assert(!T->isReferenceType());
4270 // See if we've already generated a CatchableTypeArray for this type before.
4271 llvm::GlobalVariable *&CTA = CatchableTypeArrays[T];
4272 if (CTA)
4273 return CTA;
4275 // Ensure that we don't have duplicate entries in our CatchableTypeArray by
4276 // using a SmallSetVector. Duplicates may arise due to virtual bases
4277 // occurring more than once in the hierarchy.
4278 llvm::SmallSetVector<llvm::Constant *, 2> CatchableTypes;
4280 // C++14 [except.handle]p3:
4281 // A handler is a match for an exception object of type E if [...]
4282 // - the handler is of type cv T or cv T& and T is an unambiguous public
4283 // base class of E, or
4284 // - the handler is of type cv T or const T& where T is a pointer type and
4285 // E is a pointer type that can be converted to T by [...]
4286 // - a standard pointer conversion (4.10) not involving conversions to
4287 // pointers to private or protected or ambiguous classes
4288 const CXXRecordDecl *MostDerivedClass = nullptr;
4289 bool IsPointer = T->isPointerType();
4290 if (IsPointer)
4291 MostDerivedClass = T->getPointeeType()->getAsCXXRecordDecl();
4292 else
4293 MostDerivedClass = T->getAsCXXRecordDecl();
4295 // Collect all the unambiguous public bases of the MostDerivedClass.
4296 if (MostDerivedClass) {
4297 const ASTContext &Context = getContext();
4298 const ASTRecordLayout &MostDerivedLayout =
4299 Context.getASTRecordLayout(MostDerivedClass);
4300 MicrosoftVTableContext &VTableContext = CGM.getMicrosoftVTableContext();
4301 SmallVector<MSRTTIClass, 8> Classes;
4302 serializeClassHierarchy(Classes, MostDerivedClass);
4303 Classes.front().initialize(/*Parent=*/nullptr, /*Specifier=*/nullptr);
4304 detectAmbiguousBases(Classes);
4305 for (const MSRTTIClass &Class : Classes) {
4306 // Skip any ambiguous or private bases.
4307 if (Class.Flags &
4308 (MSRTTIClass::IsPrivateOnPath | MSRTTIClass::IsAmbiguous))
4309 continue;
4310 // Write down how to convert from a derived pointer to a base pointer.
4311 uint32_t OffsetInVBTable = 0;
4312 int32_t VBPtrOffset = -1;
4313 if (Class.VirtualRoot) {
4314 OffsetInVBTable =
4315 VTableContext.getVBTableIndex(MostDerivedClass, Class.VirtualRoot)*4;
4316 VBPtrOffset = MostDerivedLayout.getVBPtrOffset().getQuantity();
4319 // Turn our record back into a pointer if the exception object is a
4320 // pointer.
4321 QualType RTTITy = QualType(Class.RD->getTypeForDecl(), 0);
4322 if (IsPointer)
4323 RTTITy = Context.getPointerType(RTTITy);
4324 CatchableTypes.insert(getCatchableType(RTTITy, Class.OffsetInVBase,
4325 VBPtrOffset, OffsetInVBTable));
4329 // C++14 [except.handle]p3:
4330 // A handler is a match for an exception object of type E if
4331 // - The handler is of type cv T or cv T& and E and T are the same type
4332 // (ignoring the top-level cv-qualifiers)
4333 CatchableTypes.insert(getCatchableType(T));
4335 // C++14 [except.handle]p3:
4336 // A handler is a match for an exception object of type E if
4337 // - the handler is of type cv T or const T& where T is a pointer type and
4338 // E is a pointer type that can be converted to T by [...]
4339 // - a standard pointer conversion (4.10) not involving conversions to
4340 // pointers to private or protected or ambiguous classes
4342 // C++14 [conv.ptr]p2:
4343 // A prvalue of type "pointer to cv T," where T is an object type, can be
4344 // converted to a prvalue of type "pointer to cv void".
4345 if (IsPointer && T->getPointeeType()->isObjectType())
4346 CatchableTypes.insert(getCatchableType(getContext().VoidPtrTy));
4348 // C++14 [except.handle]p3:
4349 // A handler is a match for an exception object of type E if [...]
4350 // - the handler is of type cv T or const T& where T is a pointer or
4351 // pointer to member type and E is std::nullptr_t.
4353 // We cannot possibly list all possible pointer types here, making this
4354 // implementation incompatible with the standard. However, MSVC includes an
4355 // entry for pointer-to-void in this case. Let's do the same.
4356 if (T->isNullPtrType())
4357 CatchableTypes.insert(getCatchableType(getContext().VoidPtrTy));
4359 uint32_t NumEntries = CatchableTypes.size();
4360 llvm::Type *CTType =
4361 getImageRelativeType(getCatchableTypeType()->getPointerTo());
4362 llvm::ArrayType *AT = llvm::ArrayType::get(CTType, NumEntries);
4363 llvm::StructType *CTAType = getCatchableTypeArrayType(NumEntries);
4364 llvm::Constant *Fields[] = {
4365 llvm::ConstantInt::get(CGM.IntTy, NumEntries), // NumEntries
4366 llvm::ConstantArray::get(
4367 AT, llvm::ArrayRef(CatchableTypes.begin(),
4368 CatchableTypes.end())) // CatchableTypes
4370 SmallString<256> MangledName;
4372 llvm::raw_svector_ostream Out(MangledName);
4373 getMangleContext().mangleCXXCatchableTypeArray(T, NumEntries, Out);
4375 CTA = new llvm::GlobalVariable(
4376 CGM.getModule(), CTAType, /*isConstant=*/true, getLinkageForRTTI(T),
4377 llvm::ConstantStruct::get(CTAType, Fields), MangledName);
4378 CTA->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4379 CTA->setSection(".xdata");
4380 if (CTA->isWeakForLinker())
4381 CTA->setComdat(CGM.getModule().getOrInsertComdat(CTA->getName()));
4382 return CTA;
4385 llvm::GlobalVariable *MicrosoftCXXABI::getThrowInfo(QualType T) {
4386 bool IsConst, IsVolatile, IsUnaligned;
4387 T = decomposeTypeForEH(getContext(), T, IsConst, IsVolatile, IsUnaligned);
4389 // The CatchableTypeArray enumerates the various (CV-unqualified) types that
4390 // the exception object may be caught as.
4391 llvm::GlobalVariable *CTA = getCatchableTypeArray(T);
4392 // The first field in a CatchableTypeArray is the number of CatchableTypes.
4393 // This is used as a component of the mangled name which means that we need to
4394 // know what it is in order to see if we have previously generated the
4395 // ThrowInfo.
4396 uint32_t NumEntries =
4397 cast<llvm::ConstantInt>(CTA->getInitializer()->getAggregateElement(0U))
4398 ->getLimitedValue();
4400 SmallString<256> MangledName;
4402 llvm::raw_svector_ostream Out(MangledName);
4403 getMangleContext().mangleCXXThrowInfo(T, IsConst, IsVolatile, IsUnaligned,
4404 NumEntries, Out);
4407 // Reuse a previously generated ThrowInfo if we have generated an appropriate
4408 // one before.
4409 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
4410 return GV;
4412 // The RTTI TypeDescriptor uses an unqualified type but catch clauses must
4413 // be at least as CV qualified. Encode this requirement into the Flags
4414 // bitfield.
4415 uint32_t Flags = 0;
4416 if (IsConst)
4417 Flags |= 1;
4418 if (IsVolatile)
4419 Flags |= 2;
4420 if (IsUnaligned)
4421 Flags |= 4;
4423 // The cleanup-function (a destructor) must be called when the exception
4424 // object's lifetime ends.
4425 llvm::Constant *CleanupFn = llvm::Constant::getNullValue(CGM.Int8PtrTy);
4426 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4427 if (CXXDestructorDecl *DtorD = RD->getDestructor())
4428 if (!DtorD->isTrivial())
4429 CleanupFn = llvm::ConstantExpr::getBitCast(
4430 CGM.getAddrOfCXXStructor(GlobalDecl(DtorD, Dtor_Complete)),
4431 CGM.Int8PtrTy);
4432 // This is unused as far as we can tell, initialize it to null.
4433 llvm::Constant *ForwardCompat =
4434 getImageRelativeConstant(llvm::Constant::getNullValue(CGM.Int8PtrTy));
4435 llvm::Constant *PointerToCatchableTypes = getImageRelativeConstant(
4436 llvm::ConstantExpr::getBitCast(CTA, CGM.Int8PtrTy));
4437 llvm::StructType *TIType = getThrowInfoType();
4438 llvm::Constant *Fields[] = {
4439 llvm::ConstantInt::get(CGM.IntTy, Flags), // Flags
4440 getImageRelativeConstant(CleanupFn), // CleanupFn
4441 ForwardCompat, // ForwardCompat
4442 PointerToCatchableTypes // CatchableTypeArray
4444 auto *GV = new llvm::GlobalVariable(
4445 CGM.getModule(), TIType, /*isConstant=*/true, getLinkageForRTTI(T),
4446 llvm::ConstantStruct::get(TIType, Fields), MangledName.str());
4447 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4448 GV->setSection(".xdata");
4449 if (GV->isWeakForLinker())
4450 GV->setComdat(CGM.getModule().getOrInsertComdat(GV->getName()));
4451 return GV;
4454 void MicrosoftCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
4455 const Expr *SubExpr = E->getSubExpr();
4456 assert(SubExpr && "SubExpr cannot be null");
4457 QualType ThrowType = SubExpr->getType();
4458 // The exception object lives on the stack and it's address is passed to the
4459 // runtime function.
4460 Address AI = CGF.CreateMemTemp(ThrowType);
4461 CGF.EmitAnyExprToMem(SubExpr, AI, ThrowType.getQualifiers(),
4462 /*IsInit=*/true);
4464 // The so-called ThrowInfo is used to describe how the exception object may be
4465 // caught.
4466 llvm::GlobalVariable *TI = getThrowInfo(ThrowType);
4468 // Call into the runtime to throw the exception.
4469 llvm::Value *Args[] = {
4470 CGF.Builder.CreateBitCast(AI.getPointer(), CGM.Int8PtrTy),
4473 CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(), Args);
4476 std::pair<llvm::Value *, const CXXRecordDecl *>
4477 MicrosoftCXXABI::LoadVTablePtr(CodeGenFunction &CGF, Address This,
4478 const CXXRecordDecl *RD) {
4479 std::tie(This, std::ignore, RD) =
4480 performBaseAdjustment(CGF, This, QualType(RD->getTypeForDecl(), 0));
4481 return {CGF.GetVTablePtr(This, CGM.Int8PtrTy, RD), RD};
4484 bool MicrosoftCXXABI::isPermittedToBeHomogeneousAggregate(
4485 const CXXRecordDecl *RD) const {
4486 // All aggregates are permitted to be HFA on non-ARM platforms, which mostly
4487 // affects vectorcall on x64/x86.
4488 if (!CGM.getTarget().getTriple().isAArch64())
4489 return true;
4490 // MSVC Windows on Arm64 has its own rules for determining if a type is HFA
4491 // that are inconsistent with the AAPCS64 ABI. The following are our best
4492 // determination of those rules so far, based on observation of MSVC's
4493 // behavior.
4494 if (RD->isEmpty())
4495 return false;
4496 if (RD->isPolymorphic())
4497 return false;
4498 if (RD->hasNonTrivialCopyAssignment())
4499 return false;
4500 if (RD->hasNonTrivialDestructor())
4501 return false;
4502 if (RD->hasNonTrivialDefaultConstructor())
4503 return false;
4504 // These two are somewhat redundant given the caller
4505 // (ABIInfo::isHomogeneousAggregate) checks the bases and fields, but that
4506 // caller doesn't consider empty bases/fields to be non-homogenous, but it
4507 // looks like Microsoft's AArch64 ABI does care about these empty types &
4508 // anything containing/derived from one is non-homogeneous.
4509 // Instead we could add another CXXABI entry point to query this property and
4510 // have ABIInfo::isHomogeneousAggregate use that property.
4511 // I don't think any other of the features listed above could be true of a
4512 // base/field while not true of the outer struct. For example, if you have a
4513 // base/field that has an non-trivial copy assignment/dtor/default ctor, then
4514 // the outer struct's corresponding operation must be non-trivial.
4515 for (const CXXBaseSpecifier &B : RD->bases()) {
4516 if (const CXXRecordDecl *FRD = B.getType()->getAsCXXRecordDecl()) {
4517 if (!isPermittedToBeHomogeneousAggregate(FRD))
4518 return false;
4521 // empty fields seem to be caught by the ABIInfo::isHomogeneousAggregate
4522 // checking for padding - but maybe there are ways to end up with an empty
4523 // field without padding? Not that I know of, so don't check fields here &
4524 // rely on the padding check.
4525 return true;