4535 lines · cpp
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-exception6//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 Microsoft11// Visual C++ ABI, which is actually not very well documented at all outside12// of Microsoft.13//14//===----------------------------------------------------------------------===//15 16#include "ABIInfo.h"17#include "CGCXXABI.h"18#include "CGCleanup.h"19#include "CGDebugInfo.h"20#include "CGVTables.h"21#include "CodeGenModule.h"22#include "CodeGenTypes.h"23#include "TargetInfo.h"24#include "clang/AST/Attr.h"25#include "clang/AST/CXXInheritance.h"26#include "clang/AST/Decl.h"27#include "clang/AST/DeclCXX.h"28#include "clang/AST/StmtCXX.h"29#include "clang/AST/VTableBuilder.h"30#include "clang/CodeGen/ConstantInitBuilder.h"31#include "llvm/ADT/StringExtras.h"32#include "llvm/ADT/StringSet.h"33#include "llvm/IR/Intrinsics.h"34 35using namespace clang;36using namespace CodeGen;37 38namespace {39 40/// Holds all the vbtable globals for a given class.41struct VBTableGlobals {42 const VPtrInfoVector *VBTables;43 SmallVector<llvm::GlobalVariable *, 2> Globals;44};45 46class MicrosoftCXXABI : public CGCXXABI {47public:48 MicrosoftCXXABI(CodeGenModule &CGM)49 : CGCXXABI(CGM), BaseClassDescriptorType(nullptr),50 ClassHierarchyDescriptorType(nullptr),51 CompleteObjectLocatorType(nullptr), CatchableTypeType(nullptr),52 ThrowInfoType(nullptr) {53 assert(!(CGM.getLangOpts().isExplicitDefaultVisibilityExportMapping() ||54 CGM.getLangOpts().isAllDefaultVisibilityExportMapping()) &&55 "visibility export mapping option unimplemented in this ABI");56 }57 58 bool HasThisReturn(GlobalDecl GD) const override;59 bool hasMostDerivedReturn(GlobalDecl GD) const override;60 61 bool classifyReturnType(CGFunctionInfo &FI) const override;62 63 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override;64 65 bool isSRetParameterAfterThis() const override { return true; }66 67 bool isThisCompleteObject(GlobalDecl GD) const override {68 // The Microsoft ABI doesn't use separate complete-object vs.69 // base-object variants of constructors, but it does of destructors.70 if (isa<CXXDestructorDecl>(GD.getDecl())) {71 switch (GD.getDtorType()) {72 case Dtor_Complete:73 case Dtor_Deleting:74 return true;75 76 case Dtor_Base:77 return false;78 79 case Dtor_Comdat: llvm_unreachable("emitting dtor comdat as function?");80 case Dtor_Unified:81 llvm_unreachable("unexpected unified dtor type");82 }83 llvm_unreachable("bad dtor kind");84 }85 86 // No other kinds.87 return false;88 }89 90 size_t getSrcArgforCopyCtor(const CXXConstructorDecl *CD,91 FunctionArgList &Args) const override {92 assert(Args.size() >= 2 &&93 "expected the arglist to have at least two args!");94 // The 'most_derived' parameter goes second if the ctor is variadic and95 // has v-bases.96 if (CD->getParent()->getNumVBases() > 0 &&97 CD->getType()->castAs<FunctionProtoType>()->isVariadic())98 return 2;99 return 1;100 }101 102 std::vector<CharUnits> getVBPtrOffsets(const CXXRecordDecl *RD) override {103 std::vector<CharUnits> VBPtrOffsets;104 const ASTContext &Context = getContext();105 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);106 107 const VBTableGlobals &VBGlobals = enumerateVBTables(RD);108 for (const std::unique_ptr<VPtrInfo> &VBT : *VBGlobals.VBTables) {109 const ASTRecordLayout &SubobjectLayout =110 Context.getASTRecordLayout(VBT->IntroducingObject);111 CharUnits Offs = VBT->NonVirtualOffset;112 Offs += SubobjectLayout.getVBPtrOffset();113 if (VBT->getVBaseWithVPtr())114 Offs += Layout.getVBaseClassOffset(VBT->getVBaseWithVPtr());115 VBPtrOffsets.push_back(Offs);116 }117 llvm::array_pod_sort(VBPtrOffsets.begin(), VBPtrOffsets.end());118 return VBPtrOffsets;119 }120 121 StringRef GetPureVirtualCallName() override { return "_purecall"; }122 StringRef GetDeletedVirtualCallName() override { return "_purecall"; }123 124 void emitVirtualObjectDelete(CodeGenFunction &CGF, const CXXDeleteExpr *DE,125 Address Ptr, QualType ElementType,126 const CXXDestructorDecl *Dtor) override;127 128 void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) override;129 void emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) override;130 131 void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override;132 133 llvm::GlobalVariable *getMSCompleteObjectLocator(const CXXRecordDecl *RD,134 const VPtrInfo &Info);135 136 llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override;137 CatchTypeInfo138 getAddrOfCXXCatchHandlerType(QualType Ty, QualType CatchHandlerType) override;139 140 /// MSVC needs an extra flag to indicate a catchall.141 CatchTypeInfo getCatchAllTypeInfo() override {142 // For -EHa catch(...) must handle HW exception143 // Adjective = HT_IsStdDotDot (0x40), only catch C++ exceptions144 if (getContext().getLangOpts().EHAsynch)145 return CatchTypeInfo{nullptr, 0};146 else147 return CatchTypeInfo{nullptr, 0x40};148 }149 150 bool shouldTypeidBeNullChecked(QualType SrcRecordTy) override;151 void EmitBadTypeidCall(CodeGenFunction &CGF) override;152 llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,153 Address ThisPtr,154 llvm::Type *StdTypeInfoPtrTy) override;155 156 bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,157 QualType SrcRecordTy) override;158 159 bool shouldEmitExactDynamicCast(QualType DestRecordTy) override {160 // TODO: Add support for exact dynamic_casts.161 return false;162 }163 std::optional<ExactDynamicCastInfo>164 getExactDynamicCastInfo(QualType SrcRecordTy, QualType DestTy,165 QualType DestRecordTy) override {166 llvm_unreachable("unsupported");167 }168 llvm::Value *emitExactDynamicCast(CodeGenFunction &CGF, Address Value,169 QualType SrcRecordTy, QualType DestTy,170 QualType DestRecordTy,171 const ExactDynamicCastInfo &CastInfo,172 llvm::BasicBlock *CastSuccess,173 llvm::BasicBlock *CastFail) override {174 llvm_unreachable("unsupported");175 }176 177 llvm::Value *emitDynamicCastCall(CodeGenFunction &CGF, Address Value,178 QualType SrcRecordTy, QualType DestTy,179 QualType DestRecordTy,180 llvm::BasicBlock *CastEnd) override;181 182 llvm::Value *emitDynamicCastToVoid(CodeGenFunction &CGF, Address Value,183 QualType SrcRecordTy) override;184 185 bool EmitBadCastCall(CodeGenFunction &CGF) override;186 bool canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const override {187 return false;188 }189 190 llvm::Value *191 GetVirtualBaseClassOffset(CodeGenFunction &CGF, Address This,192 const CXXRecordDecl *ClassDecl,193 const CXXRecordDecl *BaseClassDecl) override;194 195 llvm::BasicBlock *196 EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,197 const CXXRecordDecl *RD) override;198 199 llvm::BasicBlock *200 EmitDtorCompleteObjectHandler(CodeGenFunction &CGF);201 202 void initializeHiddenVirtualInheritanceMembers(CodeGenFunction &CGF,203 const CXXRecordDecl *RD) override;204 205 void EmitCXXConstructors(const CXXConstructorDecl *D) override;206 207 // Background on MSVC destructors208 // ==============================209 //210 // Both Itanium and MSVC ABIs have destructor variants. The variant names211 // roughly correspond in the following way:212 // Itanium Microsoft213 // Base -> no name, just ~Class214 // Complete -> vbase destructor215 // Deleting -> scalar deleting destructor216 // vector deleting destructor217 //218 // The base and complete destructors are the same as in Itanium, although the219 // complete destructor does not accept a VTT parameter when there are virtual220 // bases. A separate mechanism involving vtordisps is used to ensure that221 // virtual methods of destroyed subobjects are not called.222 //223 // The deleting destructors accept an i32 bitfield as a second parameter. Bit224 // 1 indicates if the memory should be deleted. Bit 2 indicates if the this225 // pointer points to an array. The scalar deleting destructor assumes that226 // bit 2 is zero, and therefore does not contain a loop.227 //228 // For virtual destructors, only one entry is reserved in the vftable, and it229 // always points to the vector deleting destructor. The vector deleting230 // destructor is the most general, so it can be used to destroy objects in231 // place, delete single heap objects, or delete arrays.232 //233 // A TU defining a non-inline destructor is only guaranteed to emit a base234 // destructor, and all of the other variants are emitted on an as-needed basis235 // in COMDATs. Because a non-base destructor can be emitted in a TU that236 // lacks a definition for the destructor, non-base destructors must always237 // delegate to or alias the base destructor.238 239 AddedStructorArgCounts240 buildStructorSignature(GlobalDecl GD,241 SmallVectorImpl<CanQualType> &ArgTys) override;242 243 /// Non-base dtors should be emitted as delegating thunks in this ABI.244 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,245 CXXDtorType DT) const override {246 return DT != Dtor_Base;247 }248 249 void setCXXDestructorDLLStorage(llvm::GlobalValue *GV,250 const CXXDestructorDecl *Dtor,251 CXXDtorType DT) const override;252 253 llvm::GlobalValue::LinkageTypes254 getCXXDestructorLinkage(GVALinkage Linkage, const CXXDestructorDecl *Dtor,255 CXXDtorType DT) const override;256 257 void EmitCXXDestructors(const CXXDestructorDecl *D) override;258 259 const CXXRecordDecl *getThisArgumentTypeForMethod(GlobalDecl GD) override {260 auto *MD = cast<CXXMethodDecl>(GD.getDecl());261 262 if (MD->isVirtual()) {263 GlobalDecl LookupGD = GD;264 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {265 // Complete dtors take a pointer to the complete object,266 // thus don't need adjustment.267 if (GD.getDtorType() == Dtor_Complete)268 return MD->getParent();269 270 // There's only Dtor_Deleting in vftable but it shares the this271 // adjustment with the base one, so look up the deleting one instead.272 LookupGD = GlobalDecl(DD, Dtor_Deleting);273 }274 MethodVFTableLocation ML =275 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD);276 277 // The vbases might be ordered differently in the final overrider object278 // and the complete object, so the "this" argument may sometimes point to279 // memory that has no particular type (e.g. past the complete object).280 // In this case, we just use a generic pointer type.281 // FIXME: might want to have a more precise type in the non-virtual282 // multiple inheritance case.283 if (ML.VBase || !ML.VFPtrOffset.isZero())284 return nullptr;285 }286 return MD->getParent();287 }288 289 Address290 adjustThisArgumentForVirtualFunctionCall(CodeGenFunction &CGF, GlobalDecl GD,291 Address This,292 bool VirtualCall) override;293 294 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,295 FunctionArgList &Params) override;296 297 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;298 299 AddedStructorArgs getImplicitConstructorArgs(CodeGenFunction &CGF,300 const CXXConstructorDecl *D,301 CXXCtorType Type,302 bool ForVirtualBase,303 bool Delegating) override;304 305 llvm::Value *getCXXDestructorImplicitParam(CodeGenFunction &CGF,306 const CXXDestructorDecl *DD,307 CXXDtorType Type,308 bool ForVirtualBase,309 bool Delegating) override;310 311 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,312 CXXDtorType Type, bool ForVirtualBase,313 bool Delegating, Address This,314 QualType ThisTy) override;315 316 void emitVTableTypeMetadata(const VPtrInfo &Info, const CXXRecordDecl *RD,317 llvm::GlobalVariable *VTable);318 319 void emitVTableDefinitions(CodeGenVTables &CGVT,320 const CXXRecordDecl *RD) override;321 322 bool isVirtualOffsetNeededForVTableField(CodeGenFunction &CGF,323 CodeGenFunction::VPtr Vptr) override;324 325 /// Don't initialize vptrs if dynamic class326 /// is marked with the 'novtable' attribute.327 bool doStructorsInitializeVPtrs(const CXXRecordDecl *VTableClass) override {328 return !VTableClass->hasAttr<MSNoVTableAttr>();329 }330 331 llvm::Constant *332 getVTableAddressPoint(BaseSubobject Base,333 const CXXRecordDecl *VTableClass) override;334 335 llvm::Value *getVTableAddressPointInStructor(336 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,337 BaseSubobject Base, const CXXRecordDecl *NearestVBase) override;338 339 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,340 CharUnits VPtrOffset) override;341 342 CGCallee getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,343 Address This, llvm::Type *Ty,344 SourceLocation Loc) override;345 346 llvm::Value *347 EmitVirtualDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *Dtor,348 CXXDtorType DtorType, Address This,349 DeleteOrMemberCallExpr E,350 llvm::CallBase **CallOrInvoke) override;351 352 void adjustCallArgsForDestructorThunk(CodeGenFunction &CGF, GlobalDecl GD,353 CallArgList &CallArgs) override {354 assert(GD.getDtorType() == Dtor_Deleting &&355 "Only deleting destructor thunks are available in this ABI");356 CallArgs.add(RValue::get(getStructorImplicitParamValue(CGF)),357 getContext().IntTy);358 }359 360 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;361 362 llvm::GlobalVariable *363 getAddrOfVBTable(const VPtrInfo &VBT, const CXXRecordDecl *RD,364 llvm::GlobalVariable::LinkageTypes Linkage);365 366 llvm::GlobalVariable *367 getAddrOfVirtualDisplacementMap(const CXXRecordDecl *SrcRD,368 const CXXRecordDecl *DstRD) {369 SmallString<256> OutName;370 llvm::raw_svector_ostream Out(OutName);371 getMangleContext().mangleCXXVirtualDisplacementMap(SrcRD, DstRD, Out);372 StringRef MangledName = OutName.str();373 374 if (auto *VDispMap = CGM.getModule().getNamedGlobal(MangledName))375 return VDispMap;376 377 MicrosoftVTableContext &VTContext = CGM.getMicrosoftVTableContext();378 unsigned NumEntries = 1 + SrcRD->getNumVBases();379 SmallVector<llvm::Constant *, 4> Map(NumEntries,380 llvm::PoisonValue::get(CGM.IntTy));381 Map[0] = llvm::ConstantInt::get(CGM.IntTy, 0);382 bool AnyDifferent = false;383 for (const auto &I : SrcRD->vbases()) {384 const CXXRecordDecl *VBase = I.getType()->getAsCXXRecordDecl();385 if (!DstRD->isVirtuallyDerivedFrom(VBase))386 continue;387 388 unsigned SrcVBIndex = VTContext.getVBTableIndex(SrcRD, VBase);389 unsigned DstVBIndex = VTContext.getVBTableIndex(DstRD, VBase);390 Map[SrcVBIndex] = llvm::ConstantInt::get(CGM.IntTy, DstVBIndex * 4);391 AnyDifferent |= SrcVBIndex != DstVBIndex;392 }393 // This map would be useless, don't use it.394 if (!AnyDifferent)395 return nullptr;396 397 llvm::ArrayType *VDispMapTy = llvm::ArrayType::get(CGM.IntTy, Map.size());398 llvm::Constant *Init = llvm::ConstantArray::get(VDispMapTy, Map);399 llvm::GlobalValue::LinkageTypes Linkage =400 SrcRD->isExternallyVisible() && DstRD->isExternallyVisible()401 ? llvm::GlobalValue::LinkOnceODRLinkage402 : llvm::GlobalValue::InternalLinkage;403 auto *VDispMap = new llvm::GlobalVariable(404 CGM.getModule(), VDispMapTy, /*isConstant=*/true, Linkage,405 /*Initializer=*/Init, MangledName);406 return VDispMap;407 }408 409 void emitVBTableDefinition(const VPtrInfo &VBT, const CXXRecordDecl *RD,410 llvm::GlobalVariable *GV) const;411 412 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable,413 GlobalDecl GD, bool ReturnAdjustment) override {414 GVALinkage Linkage =415 getContext().GetGVALinkageForFunction(cast<FunctionDecl>(GD.getDecl()));416 417 if (Linkage == GVA_Internal)418 Thunk->setLinkage(llvm::GlobalValue::InternalLinkage);419 else if (ReturnAdjustment)420 Thunk->setLinkage(llvm::GlobalValue::WeakODRLinkage);421 else422 Thunk->setLinkage(llvm::GlobalValue::LinkOnceODRLinkage);423 }424 425 bool exportThunk() override { return false; }426 427 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, Address This,428 const CXXRecordDecl * /*UnadjustedClass*/,429 const ThunkInfo &TI) override;430 431 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, Address Ret,432 const CXXRecordDecl * /*UnadjustedClass*/,433 const ReturnAdjustment &RA) override;434 435 void EmitThreadLocalInitFuncs(436 CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,437 ArrayRef<llvm::Function *> CXXThreadLocalInits,438 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) override;439 440 bool usesThreadWrapperFunction(const VarDecl *VD) const override {441 return getContext().getLangOpts().isCompatibleWithMSVC(442 LangOptions::MSVC2019_5) &&443 CGM.getCodeGenOpts().TlsGuards &&444 (!isEmittedWithConstantInitializer(VD) || mayNeedDestruction(VD));445 }446 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,447 QualType LValType) override;448 449 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,450 llvm::GlobalVariable *DeclPtr,451 bool PerformInit) override;452 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,453 llvm::FunctionCallee Dtor,454 llvm::Constant *Addr) override;455 456 // ==== Notes on array cookies =========457 //458 // MSVC seems to only use cookies when the class has a destructor; a459 // two-argument usual array deallocation function isn't sufficient.460 //461 // For example, this code prints "100" and "1":462 // struct A {463 // char x;464 // void *operator new[](size_t sz) {465 // printf("%u\n", sz);466 // return malloc(sz);467 // }468 // void operator delete[](void *p, size_t sz) {469 // printf("%u\n", sz);470 // free(p);471 // }472 // };473 // int main() {474 // A *p = new A[100];475 // delete[] p;476 // }477 // Whereas it prints "104" and "104" if you give A a destructor.478 479 bool requiresArrayCookie(const CXXDeleteExpr *expr,480 QualType elementType) override;481 bool requiresArrayCookie(const CXXNewExpr *expr) override;482 CharUnits getArrayCookieSizeImpl(QualType type) override;483 Address InitializeArrayCookie(CodeGenFunction &CGF,484 Address NewPtr,485 llvm::Value *NumElements,486 const CXXNewExpr *expr,487 QualType ElementType) override;488 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,489 Address allocPtr,490 CharUnits cookieSize) override;491 492 friend struct MSRTTIBuilder;493 494 bool isImageRelative() const {495 return CGM.getTarget().getPointerWidth(LangAS::Default) == 64;496 }497 498 // 5 routines for constructing the llvm types for MS RTTI structs.499 llvm::StructType *getTypeDescriptorType(StringRef TypeInfoString) {500 llvm::SmallString<32> TDTypeName("rtti.TypeDescriptor");501 TDTypeName += llvm::utostr(TypeInfoString.size());502 llvm::StructType *&TypeDescriptorType =503 TypeDescriptorTypeMap[TypeInfoString.size()];504 if (TypeDescriptorType)505 return TypeDescriptorType;506 llvm::Type *FieldTypes[] = {507 CGM.Int8PtrPtrTy,508 CGM.Int8PtrTy,509 llvm::ArrayType::get(CGM.Int8Ty, TypeInfoString.size() + 1)};510 TypeDescriptorType =511 llvm::StructType::create(CGM.getLLVMContext(), FieldTypes, TDTypeName);512 return TypeDescriptorType;513 }514 515 llvm::Type *getImageRelativeType(llvm::Type *PtrType) {516 if (!isImageRelative())517 return PtrType;518 return CGM.IntTy;519 }520 521 llvm::StructType *getBaseClassDescriptorType() {522 if (BaseClassDescriptorType)523 return BaseClassDescriptorType;524 llvm::Type *FieldTypes[] = {525 getImageRelativeType(CGM.Int8PtrTy),526 CGM.IntTy,527 CGM.IntTy,528 CGM.IntTy,529 CGM.IntTy,530 CGM.IntTy,531 getImageRelativeType(CGM.DefaultPtrTy),532 };533 BaseClassDescriptorType = llvm::StructType::create(534 CGM.getLLVMContext(), FieldTypes, "rtti.BaseClassDescriptor");535 return BaseClassDescriptorType;536 }537 538 llvm::StructType *getClassHierarchyDescriptorType() {539 if (ClassHierarchyDescriptorType)540 return ClassHierarchyDescriptorType;541 // Forward-declare RTTIClassHierarchyDescriptor to break a cycle.542 llvm::Type *FieldTypes[] = {CGM.IntTy, CGM.IntTy, CGM.IntTy,543 getImageRelativeType(CGM.DefaultPtrTy)};544 ClassHierarchyDescriptorType =545 llvm::StructType::create(FieldTypes, "rtti.ClassHierarchyDescriptor");546 return ClassHierarchyDescriptorType;547 }548 549 llvm::StructType *getCompleteObjectLocatorType() {550 if (CompleteObjectLocatorType)551 return CompleteObjectLocatorType;552 llvm::Type *FieldTypes[] = {553 CGM.IntTy,554 CGM.IntTy,555 CGM.IntTy,556 getImageRelativeType(CGM.Int8PtrTy),557 getImageRelativeType(CGM.DefaultPtrTy),558 getImageRelativeType(CGM.VoidTy),559 };560 llvm::ArrayRef<llvm::Type *> FieldTypesRef(FieldTypes);561 if (!isImageRelative())562 FieldTypesRef = FieldTypesRef.drop_back();563 CompleteObjectLocatorType =564 llvm::StructType::create(FieldTypesRef, "rtti.CompleteObjectLocator");565 return CompleteObjectLocatorType;566 }567 568 llvm::GlobalVariable *getImageBase() {569 StringRef Name = "__ImageBase";570 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name))571 return GV;572 573 auto *GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty,574 /*isConstant=*/true,575 llvm::GlobalValue::ExternalLinkage,576 /*Initializer=*/nullptr, Name);577 CGM.setDSOLocal(GV);578 return GV;579 }580 581 llvm::Constant *getImageRelativeConstant(llvm::Constant *PtrVal) {582 if (!isImageRelative())583 return PtrVal;584 585 if (PtrVal->isNullValue())586 return llvm::Constant::getNullValue(CGM.IntTy);587 588 llvm::Constant *ImageBaseAsInt =589 llvm::ConstantExpr::getPtrToInt(getImageBase(), CGM.IntPtrTy);590 llvm::Constant *PtrValAsInt =591 llvm::ConstantExpr::getPtrToInt(PtrVal, CGM.IntPtrTy);592 llvm::Constant *Diff =593 llvm::ConstantExpr::getSub(PtrValAsInt, ImageBaseAsInt,594 /*HasNUW=*/true, /*HasNSW=*/true);595 return llvm::ConstantExpr::getTrunc(Diff, CGM.IntTy);596 }597 598private:599 MicrosoftMangleContext &getMangleContext() {600 return cast<MicrosoftMangleContext>(CodeGen::CGCXXABI::getMangleContext());601 }602 603 llvm::Constant *getZeroInt() {604 return llvm::ConstantInt::get(CGM.IntTy, 0);605 }606 607 llvm::Constant *getAllOnesInt() {608 return llvm::Constant::getAllOnesValue(CGM.IntTy);609 }610 611 CharUnits getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD) override;612 613 void614 GetNullMemberPointerFields(const MemberPointerType *MPT,615 llvm::SmallVectorImpl<llvm::Constant *> &fields);616 617 /// Shared code for virtual base adjustment. Returns the offset from618 /// the vbptr to the virtual base. Optionally returns the address of the619 /// vbptr itself.620 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,621 Address Base,622 llvm::Value *VBPtrOffset,623 llvm::Value *VBTableOffset,624 llvm::Value **VBPtr = nullptr);625 626 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,627 Address Base,628 int32_t VBPtrOffset,629 int32_t VBTableOffset,630 llvm::Value **VBPtr = nullptr) {631 assert(VBTableOffset % 4 == 0 && "should be byte offset into table of i32s");632 llvm::Value *VBPOffset = llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset),633 *VBTOffset = llvm::ConstantInt::get(CGM.IntTy, VBTableOffset);634 return GetVBaseOffsetFromVBPtr(CGF, Base, VBPOffset, VBTOffset, VBPtr);635 }636 637 std::tuple<Address, llvm::Value *, const CXXRecordDecl *>638 performBaseAdjustment(CodeGenFunction &CGF, Address Value,639 QualType SrcRecordTy);640 641 /// Performs a full virtual base adjustment. Used to dereference642 /// pointers to members of virtual bases.643 llvm::Value *AdjustVirtualBase(CodeGenFunction &CGF, const Expr *E,644 const CXXRecordDecl *RD, Address Base,645 llvm::Value *VirtualBaseAdjustmentOffset,646 llvm::Value *VBPtrOffset /* optional */);647 648 /// Emits a full member pointer with the fields common to data and649 /// function member pointers.650 llvm::Constant *EmitFullMemberPointer(llvm::Constant *FirstField,651 bool IsMemberFunction,652 const CXXRecordDecl *RD,653 CharUnits NonVirtualBaseAdjustment,654 unsigned VBTableIndex);655 656 bool MemberPointerConstantIsNull(const MemberPointerType *MPT,657 llvm::Constant *MP);658 659 /// - Initialize all vbptrs of 'this' with RD as the complete type.660 void EmitVBPtrStores(CodeGenFunction &CGF, const CXXRecordDecl *RD);661 662 /// Caching wrapper around VBTableBuilder::enumerateVBTables().663 const VBTableGlobals &enumerateVBTables(const CXXRecordDecl *RD);664 665 /// Generate a thunk for calling a virtual member function MD.666 llvm::Function *EmitVirtualMemPtrThunk(const CXXMethodDecl *MD,667 const MethodVFTableLocation &ML);668 669 llvm::Constant *EmitMemberDataPointer(const CXXRecordDecl *RD,670 CharUnits offset);671 672public:673 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override;674 675 bool isZeroInitializable(const MemberPointerType *MPT) override;676 677 bool isMemberPointerConvertible(const MemberPointerType *MPT) const override {678 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();679 return RD->hasAttr<MSInheritanceAttr>();680 }681 682 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override;683 684 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,685 CharUnits offset) override;686 llvm::Constant *EmitMemberFunctionPointer(const CXXMethodDecl *MD) override;687 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override;688 689 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,690 llvm::Value *L,691 llvm::Value *R,692 const MemberPointerType *MPT,693 bool Inequality) override;694 695 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,696 llvm::Value *MemPtr,697 const MemberPointerType *MPT) override;698 699 llvm::Value *EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,700 Address Base, llvm::Value *MemPtr,701 const MemberPointerType *MPT,702 bool IsInBounds) override;703 704 llvm::Value *EmitNonNullMemberPointerConversion(705 const MemberPointerType *SrcTy, const MemberPointerType *DstTy,706 CastKind CK, CastExpr::path_const_iterator PathBegin,707 CastExpr::path_const_iterator PathEnd, llvm::Value *Src,708 CGBuilderTy &Builder);709 710 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,711 const CastExpr *E,712 llvm::Value *Src) override;713 714 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,715 llvm::Constant *Src) override;716 717 llvm::Constant *EmitMemberPointerConversion(718 const MemberPointerType *SrcTy, const MemberPointerType *DstTy,719 CastKind CK, CastExpr::path_const_iterator PathBegin,720 CastExpr::path_const_iterator PathEnd, llvm::Constant *Src);721 722 CGCallee723 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF, const Expr *E,724 Address This, llvm::Value *&ThisPtrForCall,725 llvm::Value *MemPtr,726 const MemberPointerType *MPT) override;727 728 void emitCXXStructor(GlobalDecl GD) override;729 730 llvm::StructType *getCatchableTypeType() {731 if (CatchableTypeType)732 return CatchableTypeType;733 llvm::Type *FieldTypes[] = {734 CGM.IntTy, // Flags735 getImageRelativeType(CGM.Int8PtrTy), // TypeDescriptor736 CGM.IntTy, // NonVirtualAdjustment737 CGM.IntTy, // OffsetToVBPtr738 CGM.IntTy, // VBTableIndex739 CGM.IntTy, // Size740 getImageRelativeType(CGM.Int8PtrTy) // CopyCtor741 };742 CatchableTypeType = llvm::StructType::create(743 CGM.getLLVMContext(), FieldTypes, "eh.CatchableType");744 return CatchableTypeType;745 }746 747 llvm::StructType *getCatchableTypeArrayType(uint32_t NumEntries) {748 llvm::StructType *&CatchableTypeArrayType =749 CatchableTypeArrayTypeMap[NumEntries];750 if (CatchableTypeArrayType)751 return CatchableTypeArrayType;752 753 llvm::SmallString<23> CTATypeName("eh.CatchableTypeArray.");754 CTATypeName += llvm::utostr(NumEntries);755 llvm::Type *CTType = getImageRelativeType(CGM.DefaultPtrTy);756 llvm::Type *FieldTypes[] = {757 CGM.IntTy, // NumEntries758 llvm::ArrayType::get(CTType, NumEntries) // CatchableTypes759 };760 CatchableTypeArrayType =761 llvm::StructType::create(CGM.getLLVMContext(), FieldTypes, CTATypeName);762 return CatchableTypeArrayType;763 }764 765 llvm::StructType *getThrowInfoType() {766 if (ThrowInfoType)767 return ThrowInfoType;768 llvm::Type *FieldTypes[] = {769 CGM.IntTy, // Flags770 getImageRelativeType(CGM.Int8PtrTy), // CleanupFn771 getImageRelativeType(CGM.Int8PtrTy), // ForwardCompat772 getImageRelativeType(CGM.Int8PtrTy) // CatchableTypeArray773 };774 ThrowInfoType = llvm::StructType::create(CGM.getLLVMContext(), FieldTypes,775 "eh.ThrowInfo");776 return ThrowInfoType;777 }778 779 llvm::FunctionCallee getThrowFn() {780 // _CxxThrowException is passed an exception object and a ThrowInfo object781 // which describes the exception.782 llvm::Type *Args[] = {CGM.Int8PtrTy, CGM.DefaultPtrTy};783 llvm::FunctionType *FTy =784 llvm::FunctionType::get(CGM.VoidTy, Args, /*isVarArg=*/false);785 llvm::FunctionCallee Throw =786 CGM.CreateRuntimeFunction(FTy, "_CxxThrowException");787 // _CxxThrowException is stdcall on 32-bit x86 platforms.788 if (CGM.getTarget().getTriple().getArch() == llvm::Triple::x86) {789 if (auto *Fn = dyn_cast<llvm::Function>(Throw.getCallee()))790 Fn->setCallingConv(llvm::CallingConv::X86_StdCall);791 }792 return Throw;793 }794 795 llvm::Function *getAddrOfCXXCtorClosure(const CXXConstructorDecl *CD,796 CXXCtorType CT);797 798 llvm::Constant *getCatchableType(QualType T,799 uint32_t NVOffset = 0,800 int32_t VBPtrOffset = -1,801 uint32_t VBIndex = 0);802 803 llvm::GlobalVariable *getCatchableTypeArray(QualType T);804 805 llvm::GlobalVariable *getThrowInfo(QualType T) override;806 807 std::pair<llvm::Value *, const CXXRecordDecl *>808 LoadVTablePtr(CodeGenFunction &CGF, Address This,809 const CXXRecordDecl *RD) override;810 811 bool812 isPermittedToBeHomogeneousAggregate(const CXXRecordDecl *RD) const override;813 814private:815 typedef std::pair<const CXXRecordDecl *, CharUnits> VFTableIdTy;816 typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalVariable *> VTablesMapTy;817 typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalValue *> VFTablesMapTy;818 /// All the vftables that have been referenced.819 VFTablesMapTy VFTablesMap;820 VTablesMapTy VTablesMap;821 822 /// This set holds the record decls we've deferred vtable emission for.823 llvm::SmallPtrSet<const CXXRecordDecl *, 4> DeferredVFTables;824 825 826 /// All the vbtables which have been referenced.827 llvm::DenseMap<const CXXRecordDecl *, VBTableGlobals> VBTablesMap;828 829 /// Info on the global variable used to guard initialization of static locals.830 /// The BitIndex field is only used for externally invisible declarations.831 struct GuardInfo {832 GuardInfo() = default;833 llvm::GlobalVariable *Guard = nullptr;834 unsigned BitIndex = 0;835 };836 837 /// Map from DeclContext to the current guard variable. We assume that the838 /// AST is visited in source code order.839 llvm::DenseMap<const DeclContext *, GuardInfo> GuardVariableMap;840 llvm::DenseMap<const DeclContext *, GuardInfo> ThreadLocalGuardVariableMap;841 llvm::DenseMap<const DeclContext *, unsigned> ThreadSafeGuardNumMap;842 843 llvm::DenseMap<size_t, llvm::StructType *> TypeDescriptorTypeMap;844 llvm::StructType *BaseClassDescriptorType;845 llvm::StructType *ClassHierarchyDescriptorType;846 llvm::StructType *CompleteObjectLocatorType;847 848 llvm::DenseMap<QualType, llvm::GlobalVariable *> CatchableTypeArrays;849 850 llvm::StructType *CatchableTypeType;851 llvm::DenseMap<uint32_t, llvm::StructType *> CatchableTypeArrayTypeMap;852 llvm::StructType *ThrowInfoType;853};854 855}856 857CGCXXABI::RecordArgABI858MicrosoftCXXABI::getRecordArgABI(const CXXRecordDecl *RD) const {859 // Use the default C calling convention rules for things that can be passed in860 // registers, i.e. non-trivially copyable records or records marked with861 // [[trivial_abi]].862 if (RD->canPassInRegisters())863 return RAA_Default;864 865 switch (CGM.getTarget().getTriple().getArch()) {866 default:867 // FIXME: Implement for other architectures.868 return RAA_Indirect;869 870 case llvm::Triple::thumb:871 // Pass things indirectly for now because it is simple.872 // FIXME: This is incompatible with MSVC for arguments with a dtor and no873 // copy ctor.874 return RAA_Indirect;875 876 case llvm::Triple::x86: {877 // If the argument has *required* alignment greater than four bytes, pass878 // it indirectly. Prior to MSVC version 19.14, passing overaligned879 // arguments was not supported and resulted in a compiler error. In 19.14880 // and later versions, such arguments are now passed indirectly.881 TypeInfo Info =882 getContext().getTypeInfo(getContext().getCanonicalTagType(RD));883 if (Info.isAlignRequired() && Info.Align > 4)884 return RAA_Indirect;885 886 // If C++ prohibits us from making a copy, construct the arguments directly887 // into argument memory.888 return RAA_DirectInMemory;889 }890 891 case llvm::Triple::x86_64:892 case llvm::Triple::aarch64:893 return RAA_Indirect;894 }895 896 llvm_unreachable("invalid enum");897}898 899void MicrosoftCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,900 const CXXDeleteExpr *DE,901 Address Ptr,902 QualType ElementType,903 const CXXDestructorDecl *Dtor) {904 // FIXME: Provide a source location here even though there's no905 // CXXMemberCallExpr for dtor call.906 if (!getContext().getTargetInfo().callGlobalDeleteInDeletingDtor(907 getContext().getLangOpts())) {908 bool UseGlobalDelete = DE->isGlobalDelete();909 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;910 llvm::Value *MDThis =911 EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, DE,912 /*CallOrInvoke=*/nullptr);913 if (UseGlobalDelete)914 CGF.EmitDeleteCall(DE->getOperatorDelete(), MDThis, ElementType);915 } else {916 EmitVirtualDestructorCall(CGF, Dtor, Dtor_Deleting, Ptr, DE,917 /*CallOrInvoke=*/nullptr);918 }919}920 921void MicrosoftCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {922 llvm::Value *Args[] = {llvm::ConstantPointerNull::get(CGM.Int8PtrTy),923 llvm::ConstantPointerNull::get(CGM.DefaultPtrTy)};924 llvm::FunctionCallee Fn = getThrowFn();925 if (isNoReturn)926 CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, Args);927 else928 CGF.EmitRuntimeCallOrInvoke(Fn, Args);929}930 931void MicrosoftCXXABI::emitBeginCatch(CodeGenFunction &CGF,932 const CXXCatchStmt *S) {933 // In the MS ABI, the runtime handles the copy, and the catch handler is934 // responsible for destruction.935 VarDecl *CatchParam = S->getExceptionDecl();936 llvm::BasicBlock *CatchPadBB = CGF.Builder.GetInsertBlock();937 llvm::CatchPadInst *CPI =938 cast<llvm::CatchPadInst>(CatchPadBB->getFirstNonPHIIt());939 CGF.CurrentFuncletPad = CPI;940 941 // If this is a catch-all or the catch parameter is unnamed, we don't need to942 // emit an alloca to the object.943 if (!CatchParam || !CatchParam->getDeclName()) {944 CGF.EHStack.pushCleanup<CatchRetScope>(NormalCleanup, CPI);945 return;946 }947 948 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);949 CPI->setArgOperand(2, var.getObjectAddress(CGF).emitRawPointer(CGF));950 CGF.EHStack.pushCleanup<CatchRetScope>(NormalCleanup, CPI);951 CGF.EmitAutoVarCleanups(var);952}953 954/// We need to perform a generic polymorphic operation (like a typeid955/// or a cast), which requires an object with a vfptr. Adjust the956/// address to point to an object with a vfptr.957std::tuple<Address, llvm::Value *, const CXXRecordDecl *>958MicrosoftCXXABI::performBaseAdjustment(CodeGenFunction &CGF, Address Value,959 QualType SrcRecordTy) {960 Value = Value.withElementType(CGF.Int8Ty);961 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();962 const ASTContext &Context = getContext();963 964 // If the class itself has a vfptr, great. This check implicitly965 // covers non-virtual base subobjects: a class with its own virtual966 // functions would be a candidate to be a primary base.967 if (Context.getASTRecordLayout(SrcDecl).hasExtendableVFPtr())968 return std::make_tuple(Value, llvm::ConstantInt::get(CGF.Int32Ty, 0),969 SrcDecl);970 971 // Okay, one of the vbases must have a vfptr, or else this isn't972 // actually a polymorphic class.973 const CXXRecordDecl *PolymorphicBase = nullptr;974 for (auto &Base : SrcDecl->vbases()) {975 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();976 if (Context.getASTRecordLayout(BaseDecl).hasExtendableVFPtr()) {977 PolymorphicBase = BaseDecl;978 break;979 }980 }981 assert(PolymorphicBase && "polymorphic class has no apparent vfptr?");982 983 llvm::Value *Offset =984 GetVirtualBaseClassOffset(CGF, Value, SrcDecl, PolymorphicBase);985 llvm::Value *Ptr = CGF.Builder.CreateInBoundsGEP(986 Value.getElementType(), Value.emitRawPointer(CGF), Offset);987 CharUnits VBaseAlign =988 CGF.CGM.getVBaseAlignment(Value.getAlignment(), SrcDecl, PolymorphicBase);989 return std::make_tuple(Address(Ptr, CGF.Int8Ty, VBaseAlign), Offset,990 PolymorphicBase);991}992 993bool MicrosoftCXXABI::shouldTypeidBeNullChecked(QualType SrcRecordTy) {994 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();995 return !getContext().getASTRecordLayout(SrcDecl).hasExtendableVFPtr();996}997 998static llvm::CallBase *emitRTtypeidCall(CodeGenFunction &CGF,999 llvm::Value *Argument) {1000 llvm::Type *ArgTypes[] = {CGF.Int8PtrTy};1001 llvm::FunctionType *FTy =1002 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false);1003 llvm::Value *Args[] = {Argument};1004 llvm::FunctionCallee Fn = CGF.CGM.CreateRuntimeFunction(FTy, "__RTtypeid");1005 return CGF.EmitRuntimeCallOrInvoke(Fn, Args);1006}1007 1008void MicrosoftCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {1009 llvm::CallBase *Call =1010 emitRTtypeidCall(CGF, llvm::Constant::getNullValue(CGM.VoidPtrTy));1011 Call->setDoesNotReturn();1012 CGF.Builder.CreateUnreachable();1013}1014 1015llvm::Value *MicrosoftCXXABI::EmitTypeid(CodeGenFunction &CGF,1016 QualType SrcRecordTy,1017 Address ThisPtr,1018 llvm::Type *StdTypeInfoPtrTy) {1019 std::tie(ThisPtr, std::ignore, std::ignore) =1020 performBaseAdjustment(CGF, ThisPtr, SrcRecordTy);1021 llvm::CallBase *Typeid = emitRTtypeidCall(CGF, ThisPtr.emitRawPointer(CGF));1022 return CGF.Builder.CreateBitCast(Typeid, StdTypeInfoPtrTy);1023}1024 1025bool MicrosoftCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,1026 QualType SrcRecordTy) {1027 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();1028 return SrcIsPtr &&1029 !getContext().getASTRecordLayout(SrcDecl).hasExtendableVFPtr();1030}1031 1032llvm::Value *MicrosoftCXXABI::emitDynamicCastCall(1033 CodeGenFunction &CGF, Address This, QualType SrcRecordTy, QualType DestTy,1034 QualType DestRecordTy, llvm::BasicBlock *CastEnd) {1035 llvm::Value *SrcRTTI =1036 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());1037 llvm::Value *DestRTTI =1038 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());1039 1040 llvm::Value *Offset;1041 std::tie(This, Offset, std::ignore) =1042 performBaseAdjustment(CGF, This, SrcRecordTy);1043 llvm::Value *ThisPtr = This.emitRawPointer(CGF);1044 Offset = CGF.Builder.CreateTrunc(Offset, CGF.Int32Ty);1045 1046 // PVOID __RTDynamicCast(1047 // PVOID inptr,1048 // LONG VfDelta,1049 // PVOID SrcType,1050 // PVOID TargetType,1051 // BOOL isReference)1052 llvm::Type *ArgTypes[] = {CGF.Int8PtrTy, CGF.Int32Ty, CGF.Int8PtrTy,1053 CGF.Int8PtrTy, CGF.Int32Ty};1054 llvm::FunctionCallee Function = CGF.CGM.CreateRuntimeFunction(1055 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false),1056 "__RTDynamicCast");1057 llvm::Value *Args[] = {1058 ThisPtr, Offset, SrcRTTI, DestRTTI,1059 llvm::ConstantInt::get(CGF.Int32Ty, DestTy->isReferenceType())};1060 return CGF.EmitRuntimeCallOrInvoke(Function, Args);1061}1062 1063llvm::Value *MicrosoftCXXABI::emitDynamicCastToVoid(CodeGenFunction &CGF,1064 Address Value,1065 QualType SrcRecordTy) {1066 std::tie(Value, std::ignore, std::ignore) =1067 performBaseAdjustment(CGF, Value, SrcRecordTy);1068 1069 // PVOID __RTCastToVoid(1070 // PVOID inptr)1071 llvm::Type *ArgTypes[] = {CGF.Int8PtrTy};1072 llvm::FunctionCallee Function = CGF.CGM.CreateRuntimeFunction(1073 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false),1074 "__RTCastToVoid");1075 llvm::Value *Args[] = {Value.emitRawPointer(CGF)};1076 return CGF.EmitRuntimeCall(Function, Args);1077}1078 1079bool MicrosoftCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {1080 return false;1081}1082 1083llvm::Value *MicrosoftCXXABI::GetVirtualBaseClassOffset(1084 CodeGenFunction &CGF, Address This, const CXXRecordDecl *ClassDecl,1085 const CXXRecordDecl *BaseClassDecl) {1086 const ASTContext &Context = getContext();1087 int64_t VBPtrChars =1088 Context.getASTRecordLayout(ClassDecl).getVBPtrOffset().getQuantity();1089 llvm::Value *VBPtrOffset = llvm::ConstantInt::get(CGM.PtrDiffTy, VBPtrChars);1090 CharUnits IntSize = Context.getTypeSizeInChars(Context.IntTy);1091 CharUnits VBTableChars =1092 IntSize *1093 CGM.getMicrosoftVTableContext().getVBTableIndex(ClassDecl, BaseClassDecl);1094 llvm::Value *VBTableOffset =1095 llvm::ConstantInt::get(CGM.IntTy, VBTableChars.getQuantity());1096 1097 llvm::Value *VBPtrToNewBase =1098 GetVBaseOffsetFromVBPtr(CGF, This, VBPtrOffset, VBTableOffset);1099 VBPtrToNewBase =1100 CGF.Builder.CreateSExtOrBitCast(VBPtrToNewBase, CGM.PtrDiffTy);1101 return CGF.Builder.CreateNSWAdd(VBPtrOffset, VBPtrToNewBase);1102}1103 1104bool MicrosoftCXXABI::HasThisReturn(GlobalDecl GD) const {1105 return isa<CXXConstructorDecl>(GD.getDecl());1106}1107 1108static bool isDeletingDtor(GlobalDecl GD) {1109 return isa<CXXDestructorDecl>(GD.getDecl()) &&1110 GD.getDtorType() == Dtor_Deleting;1111}1112 1113bool MicrosoftCXXABI::hasMostDerivedReturn(GlobalDecl GD) const {1114 return isDeletingDtor(GD);1115}1116 1117static bool isTrivialForMSVC(const CXXRecordDecl *RD, QualType Ty,1118 CodeGenModule &CGM) {1119 // On AArch64, HVAs that can be passed in registers can also be returned1120 // in registers. (Note this is using the MSVC definition of an HVA; see1121 // isPermittedToBeHomogeneousAggregate().)1122 const Type *Base = nullptr;1123 uint64_t NumElts = 0;1124 if (CGM.getTarget().getTriple().isAArch64() &&1125 CGM.getABIInfo().isHomogeneousAggregate(Ty, Base, NumElts) &&1126 isa<VectorType>(Base)) {1127 return true;1128 }1129 1130 // We use the C++14 definition of an aggregate, so we also1131 // check for:1132 // No private or protected non static data members.1133 // No base classes1134 // No virtual functions1135 // Additionally, we need to ensure that there is a trivial copy assignment1136 // operator, a trivial destructor, no user-provided constructors and no1137 // deleted copy assignment operator.1138 1139 // We need to cover two cases when checking for a deleted copy assignment1140 // operator.1141 //1142 // struct S { int& r; };1143 // The above will have an implicit copy assignment operator that is deleted1144 // and there will not be a `CXXMethodDecl` for the copy assignment operator.1145 // This is handled by the `needsImplicitCopyAssignment()` check below.1146 //1147 // struct S { S& operator=(const S&) = delete; int i; };1148 // The above will not have an implicit copy assignment operator that is1149 // deleted but there is a deleted `CXXMethodDecl` for the declared copy1150 // assignment operator. This is handled by the `isDeleted()` check below.1151 1152 if (RD->hasProtectedFields() || RD->hasPrivateFields())1153 return false;1154 if (RD->getNumBases() > 0)1155 return false;1156 if (RD->isPolymorphic())1157 return false;1158 if (RD->hasNonTrivialCopyAssignment())1159 return false;1160 if (RD->needsImplicitCopyAssignment() && !RD->hasSimpleCopyAssignment())1161 return false;1162 for (const Decl *D : RD->decls()) {1163 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(D)) {1164 if (Ctor->isUserProvided())1165 return false;1166 } else if (auto *Template = dyn_cast<FunctionTemplateDecl>(D)) {1167 if (isa<CXXConstructorDecl>(Template->getTemplatedDecl()))1168 return false;1169 } else if (auto *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {1170 if (MethodDecl->isCopyAssignmentOperator() && MethodDecl->isDeleted())1171 return false;1172 }1173 }1174 if (RD->hasNonTrivialDestructor())1175 return false;1176 return true;1177}1178 1179bool MicrosoftCXXABI::classifyReturnType(CGFunctionInfo &FI) const {1180 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();1181 if (!RD)1182 return false;1183 1184 bool isTrivialForABI = RD->canPassInRegisters() &&1185 isTrivialForMSVC(RD, FI.getReturnType(), CGM);1186 1187 // MSVC always returns structs indirectly from C++ instance methods.1188 bool isIndirectReturn = !isTrivialForABI || FI.isInstanceMethod();1189 1190 if (isIndirectReturn) {1191 CharUnits Align = CGM.getContext().getTypeAlignInChars(FI.getReturnType());1192 FI.getReturnInfo() = ABIArgInfo::getIndirect(1193 Align, /*AddrSpace=*/CGM.getDataLayout().getAllocaAddrSpace(),1194 /*ByVal=*/false);1195 1196 // MSVC always passes `this` before the `sret` parameter.1197 FI.getReturnInfo().setSRetAfterThis(FI.isInstanceMethod());1198 1199 // On AArch64, use the `inreg` attribute if the object is considered to not1200 // be trivially copyable, or if this is an instance method struct return.1201 FI.getReturnInfo().setInReg(CGM.getTarget().getTriple().isAArch64());1202 1203 return true;1204 }1205 1206 // Otherwise, use the C ABI rules.1207 return false;1208}1209 1210llvm::BasicBlock *1211MicrosoftCXXABI::EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,1212 const CXXRecordDecl *RD) {1213 llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);1214 assert(IsMostDerivedClass &&1215 "ctor for a class with virtual bases must have an implicit parameter");1216 llvm::Value *IsCompleteObject =1217 CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");1218 1219 llvm::BasicBlock *CallVbaseCtorsBB = CGF.createBasicBlock("ctor.init_vbases");1220 llvm::BasicBlock *SkipVbaseCtorsBB = CGF.createBasicBlock("ctor.skip_vbases");1221 CGF.Builder.CreateCondBr(IsCompleteObject,1222 CallVbaseCtorsBB, SkipVbaseCtorsBB);1223 1224 CGF.EmitBlock(CallVbaseCtorsBB);1225 1226 // Fill in the vbtable pointers here.1227 EmitVBPtrStores(CGF, RD);1228 1229 // CGF will put the base ctor calls in this basic block for us later.1230 1231 return SkipVbaseCtorsBB;1232}1233 1234llvm::BasicBlock *1235MicrosoftCXXABI::EmitDtorCompleteObjectHandler(CodeGenFunction &CGF) {1236 llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);1237 assert(IsMostDerivedClass &&1238 "ctor for a class with virtual bases must have an implicit parameter");1239 llvm::Value *IsCompleteObject =1240 CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");1241 1242 llvm::BasicBlock *CallVbaseDtorsBB = CGF.createBasicBlock("Dtor.dtor_vbases");1243 llvm::BasicBlock *SkipVbaseDtorsBB = CGF.createBasicBlock("Dtor.skip_vbases");1244 CGF.Builder.CreateCondBr(IsCompleteObject,1245 CallVbaseDtorsBB, SkipVbaseDtorsBB);1246 1247 CGF.EmitBlock(CallVbaseDtorsBB);1248 // CGF will put the base dtor calls in this basic block for us later.1249 1250 return SkipVbaseDtorsBB;1251}1252 1253void MicrosoftCXXABI::initializeHiddenVirtualInheritanceMembers(1254 CodeGenFunction &CGF, const CXXRecordDecl *RD) {1255 // In most cases, an override for a vbase virtual method can adjust1256 // the "this" parameter by applying a constant offset.1257 // However, this is not enough while a constructor or a destructor of some1258 // class X is being executed if all the following conditions are met:1259 // - X has virtual bases, (1)1260 // - X overrides a virtual method M of a vbase Y, (2)1261 // - X itself is a vbase of the most derived class.1262 //1263 // If (1) and (2) are true, the vtorDisp for vbase Y is a hidden member of X1264 // which holds the extra amount of "this" adjustment we must do when we use1265 // the X vftables (i.e. during X ctor or dtor).1266 // Outside the ctors and dtors, the values of vtorDisps are zero.1267 1268 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);1269 typedef ASTRecordLayout::VBaseOffsetsMapTy VBOffsets;1270 const VBOffsets &VBaseMap = Layout.getVBaseOffsetsMap();1271 CGBuilderTy &Builder = CGF.Builder;1272 1273 llvm::Value *Int8This = nullptr; // Initialize lazily.1274 1275 for (const CXXBaseSpecifier &S : RD->vbases()) {1276 const CXXRecordDecl *VBase = S.getType()->getAsCXXRecordDecl();1277 auto I = VBaseMap.find(VBase);1278 assert(I != VBaseMap.end());1279 if (!I->second.hasVtorDisp())1280 continue;1281 1282 llvm::Value *VBaseOffset =1283 GetVirtualBaseClassOffset(CGF, getThisAddress(CGF), RD, VBase);1284 uint64_t ConstantVBaseOffset = I->second.VBaseOffset.getQuantity();1285 1286 // vtorDisp_for_vbase = vbptr[vbase_idx] - offsetof(RD, vbase).1287 llvm::Value *VtorDispValue = Builder.CreateSub(1288 VBaseOffset, llvm::ConstantInt::get(CGM.PtrDiffTy, ConstantVBaseOffset),1289 "vtordisp.value");1290 VtorDispValue = Builder.CreateTruncOrBitCast(VtorDispValue, CGF.Int32Ty);1291 1292 if (!Int8This)1293 Int8This = getThisValue(CGF);1294 1295 llvm::Value *VtorDispPtr =1296 Builder.CreateInBoundsGEP(CGF.Int8Ty, Int8This, VBaseOffset);1297 // vtorDisp is always the 32-bits before the vbase in the class layout.1298 VtorDispPtr = Builder.CreateConstGEP1_32(CGF.Int8Ty, VtorDispPtr, -4);1299 1300 Builder.CreateAlignedStore(VtorDispValue, VtorDispPtr,1301 CharUnits::fromQuantity(4));1302 }1303}1304 1305static bool hasDefaultCXXMethodCC(ASTContext &Context,1306 const CXXMethodDecl *MD) {1307 CallingConv ExpectedCallingConv = Context.getDefaultCallingConvention(1308 /*IsVariadic=*/false, /*IsCXXMethod=*/true);1309 CallingConv ActualCallingConv =1310 MD->getType()->castAs<FunctionProtoType>()->getCallConv();1311 return ExpectedCallingConv == ActualCallingConv;1312}1313 1314void MicrosoftCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {1315 // There's only one constructor type in this ABI.1316 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));1317 1318 // Exported default constructors either have a simple call-site where they use1319 // the typical calling convention and have a single 'this' pointer for an1320 // argument -or- they get a wrapper function which appropriately thunks to the1321 // real default constructor. This thunk is the default constructor closure.1322 if (D->hasAttr<DLLExportAttr>() && D->isDefaultConstructor() &&1323 D->isDefined()) {1324 if (!hasDefaultCXXMethodCC(getContext(), D) || D->getNumParams() != 0) {1325 llvm::Function *Fn = getAddrOfCXXCtorClosure(D, Ctor_DefaultClosure);1326 Fn->setLinkage(llvm::GlobalValue::WeakODRLinkage);1327 CGM.setGVProperties(Fn, D);1328 }1329 }1330}1331 1332void MicrosoftCXXABI::EmitVBPtrStores(CodeGenFunction &CGF,1333 const CXXRecordDecl *RD) {1334 Address This = getThisAddress(CGF);1335 This = This.withElementType(CGM.Int8Ty);1336 const ASTContext &Context = getContext();1337 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);1338 1339 const VBTableGlobals &VBGlobals = enumerateVBTables(RD);1340 for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) {1341 const std::unique_ptr<VPtrInfo> &VBT = (*VBGlobals.VBTables)[I];1342 llvm::GlobalVariable *GV = VBGlobals.Globals[I];1343 const ASTRecordLayout &SubobjectLayout =1344 Context.getASTRecordLayout(VBT->IntroducingObject);1345 CharUnits Offs = VBT->NonVirtualOffset;1346 Offs += SubobjectLayout.getVBPtrOffset();1347 if (VBT->getVBaseWithVPtr())1348 Offs += Layout.getVBaseClassOffset(VBT->getVBaseWithVPtr());1349 Address VBPtr = CGF.Builder.CreateConstInBoundsByteGEP(This, Offs);1350 llvm::Value *GVPtr =1351 CGF.Builder.CreateConstInBoundsGEP2_32(GV->getValueType(), GV, 0, 0);1352 VBPtr = VBPtr.withElementType(GVPtr->getType());1353 CGF.Builder.CreateStore(GVPtr, VBPtr);1354 }1355}1356 1357CGCXXABI::AddedStructorArgCounts1358MicrosoftCXXABI::buildStructorSignature(GlobalDecl GD,1359 SmallVectorImpl<CanQualType> &ArgTys) {1360 AddedStructorArgCounts Added;1361 // TODO: 'for base' flag1362 if (isa<CXXDestructorDecl>(GD.getDecl()) &&1363 GD.getDtorType() == Dtor_Deleting) {1364 // The scalar deleting destructor takes an implicit int parameter.1365 ArgTys.push_back(getContext().IntTy);1366 ++Added.Suffix;1367 }1368 auto *CD = dyn_cast<CXXConstructorDecl>(GD.getDecl());1369 if (!CD)1370 return Added;1371 1372 // All parameters are already in place except is_most_derived, which goes1373 // after 'this' if it's variadic and last if it's not.1374 1375 const CXXRecordDecl *Class = CD->getParent();1376 const FunctionProtoType *FPT = CD->getType()->castAs<FunctionProtoType>();1377 if (Class->getNumVBases()) {1378 if (FPT->isVariadic()) {1379 ArgTys.insert(ArgTys.begin() + 1, getContext().IntTy);1380 ++Added.Prefix;1381 } else {1382 ArgTys.push_back(getContext().IntTy);1383 ++Added.Suffix;1384 }1385 }1386 1387 return Added;1388}1389 1390void MicrosoftCXXABI::setCXXDestructorDLLStorage(llvm::GlobalValue *GV,1391 const CXXDestructorDecl *Dtor,1392 CXXDtorType DT) const {1393 // Deleting destructor variants are never imported or exported. Give them the1394 // default storage class.1395 if (DT == Dtor_Deleting) {1396 GV->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);1397 } else {1398 const NamedDecl *ND = Dtor;1399 CGM.setDLLImportDLLExport(GV, ND);1400 }1401}1402 1403llvm::GlobalValue::LinkageTypes MicrosoftCXXABI::getCXXDestructorLinkage(1404 GVALinkage Linkage, const CXXDestructorDecl *Dtor, CXXDtorType DT) const {1405 // Internal things are always internal, regardless of attributes. After this,1406 // we know the thunk is externally visible.1407 if (Linkage == GVA_Internal)1408 return llvm::GlobalValue::InternalLinkage;1409 1410 switch (DT) {1411 case Dtor_Base:1412 // The base destructor most closely tracks the user-declared constructor, so1413 // we delegate back to the normal declarator case.1414 return CGM.getLLVMLinkageForDeclarator(Dtor, Linkage);1415 case Dtor_Complete:1416 // The complete destructor is like an inline function, but it may be1417 // imported and therefore must be exported as well. This requires changing1418 // the linkage if a DLL attribute is present.1419 if (Dtor->hasAttr<DLLExportAttr>())1420 return llvm::GlobalValue::WeakODRLinkage;1421 if (Dtor->hasAttr<DLLImportAttr>())1422 return llvm::GlobalValue::AvailableExternallyLinkage;1423 return llvm::GlobalValue::LinkOnceODRLinkage;1424 case Dtor_Deleting:1425 // Deleting destructors are like inline functions. They have vague linkage1426 // and are emitted everywhere they are used. They are internal if the class1427 // is internal.1428 return llvm::GlobalValue::LinkOnceODRLinkage;1429 case Dtor_Unified:1430 llvm_unreachable("MS C++ ABI does not support unified dtors");1431 case Dtor_Comdat:1432 llvm_unreachable("MS C++ ABI does not support comdat dtors");1433 }1434 llvm_unreachable("invalid dtor type");1435}1436 1437void MicrosoftCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {1438 // The TU defining a dtor is only guaranteed to emit a base destructor. All1439 // other destructor variants are delegating thunks.1440 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));1441 1442 // If the class is dllexported, emit the complete (vbase) destructor wherever1443 // the base dtor is emitted.1444 // FIXME: To match MSVC, this should only be done when the class is exported1445 // with -fdllexport-inlines enabled.1446 if (D->getParent()->getNumVBases() > 0 && D->hasAttr<DLLExportAttr>())1447 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));1448}1449 1450CharUnits1451MicrosoftCXXABI::getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD) {1452 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());1453 1454 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {1455 // Complete destructors take a pointer to the complete object as a1456 // parameter, thus don't need this adjustment.1457 if (GD.getDtorType() == Dtor_Complete)1458 return CharUnits();1459 1460 // There's no Dtor_Base in vftable but it shares the this adjustment with1461 // the deleting one, so look it up instead.1462 GD = GlobalDecl(DD, Dtor_Deleting);1463 }1464 1465 MethodVFTableLocation ML =1466 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD);1467 CharUnits Adjustment = ML.VFPtrOffset;1468 1469 // Normal virtual instance methods need to adjust from the vfptr that first1470 // defined the virtual method to the virtual base subobject, but destructors1471 // do not. The vector deleting destructor thunk applies this adjustment for1472 // us if necessary.1473 if (isa<CXXDestructorDecl>(MD))1474 Adjustment = CharUnits::Zero();1475 1476 if (ML.VBase) {1477 const ASTRecordLayout &DerivedLayout =1478 getContext().getASTRecordLayout(MD->getParent());1479 Adjustment += DerivedLayout.getVBaseClassOffset(ML.VBase);1480 }1481 1482 return Adjustment;1483}1484 1485Address MicrosoftCXXABI::adjustThisArgumentForVirtualFunctionCall(1486 CodeGenFunction &CGF, GlobalDecl GD, Address This,1487 bool VirtualCall) {1488 if (!VirtualCall) {1489 // If the call of a virtual function is not virtual, we just have to1490 // compensate for the adjustment the virtual function does in its prologue.1491 CharUnits Adjustment = getVirtualFunctionPrologueThisAdjustment(GD);1492 if (Adjustment.isZero())1493 return This;1494 1495 This = This.withElementType(CGF.Int8Ty);1496 assert(Adjustment.isPositive());1497 return CGF.Builder.CreateConstByteGEP(This, Adjustment);1498 }1499 1500 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());1501 1502 GlobalDecl LookupGD = GD;1503 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {1504 // Complete dtors take a pointer to the complete object,1505 // thus don't need adjustment.1506 if (GD.getDtorType() == Dtor_Complete)1507 return This;1508 1509 // There's only Dtor_Deleting in vftable but it shares the this adjustment1510 // with the base one, so look up the deleting one instead.1511 LookupGD = GlobalDecl(DD, Dtor_Deleting);1512 }1513 MethodVFTableLocation ML =1514 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD);1515 1516 CharUnits StaticOffset = ML.VFPtrOffset;1517 1518 // Base destructors expect 'this' to point to the beginning of the base1519 // subobject, not the first vfptr that happens to contain the virtual dtor.1520 // However, we still need to apply the virtual base adjustment.1521 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)1522 StaticOffset = CharUnits::Zero();1523 1524 Address Result = This;1525 if (ML.VBase) {1526 Result = Result.withElementType(CGF.Int8Ty);1527 1528 const CXXRecordDecl *Derived = MD->getParent();1529 const CXXRecordDecl *VBase = ML.VBase;1530 llvm::Value *VBaseOffset =1531 GetVirtualBaseClassOffset(CGF, Result, Derived, VBase);1532 llvm::Value *VBasePtr = CGF.Builder.CreateInBoundsGEP(1533 Result.getElementType(), Result.emitRawPointer(CGF), VBaseOffset);1534 CharUnits VBaseAlign =1535 CGF.CGM.getVBaseAlignment(Result.getAlignment(), Derived, VBase);1536 Result = Address(VBasePtr, CGF.Int8Ty, VBaseAlign);1537 }1538 if (!StaticOffset.isZero()) {1539 assert(StaticOffset.isPositive());1540 Result = Result.withElementType(CGF.Int8Ty);1541 if (ML.VBase) {1542 // Non-virtual adjustment might result in a pointer outside the allocated1543 // object, e.g. if the final overrider class is laid out after the virtual1544 // base that declares a method in the most derived class.1545 // FIXME: Update the code that emits this adjustment in thunks prologues.1546 Result = CGF.Builder.CreateConstByteGEP(Result, StaticOffset);1547 } else {1548 Result = CGF.Builder.CreateConstInBoundsByteGEP(Result, StaticOffset);1549 }1550 }1551 return Result;1552}1553 1554void MicrosoftCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,1555 QualType &ResTy,1556 FunctionArgList &Params) {1557 ASTContext &Context = getContext();1558 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());1559 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));1560 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {1561 auto *IsMostDerived = ImplicitParamDecl::Create(1562 Context, /*DC=*/nullptr, CGF.CurGD.getDecl()->getLocation(),1563 &Context.Idents.get("is_most_derived"), Context.IntTy,1564 ImplicitParamKind::Other);1565 // The 'most_derived' parameter goes second if the ctor is variadic and last1566 // if it's not. Dtors can't be variadic.1567 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();1568 if (FPT->isVariadic())1569 Params.insert(Params.begin() + 1, IsMostDerived);1570 else1571 Params.push_back(IsMostDerived);1572 getStructorImplicitParamDecl(CGF) = IsMostDerived;1573 } else if (isDeletingDtor(CGF.CurGD)) {1574 auto *ShouldDelete = ImplicitParamDecl::Create(1575 Context, /*DC=*/nullptr, CGF.CurGD.getDecl()->getLocation(),1576 &Context.Idents.get("should_call_delete"), Context.IntTy,1577 ImplicitParamKind::Other);1578 Params.push_back(ShouldDelete);1579 getStructorImplicitParamDecl(CGF) = ShouldDelete;1580 }1581}1582 1583void MicrosoftCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {1584 // Naked functions have no prolog.1585 if (CGF.CurFuncDecl && CGF.CurFuncDecl->hasAttr<NakedAttr>())1586 return;1587 1588 // Overridden virtual methods of non-primary bases need to adjust the incoming1589 // 'this' pointer in the prologue. In this hierarchy, C::b will subtract1590 // sizeof(void*) to adjust from B* to C*:1591 // struct A { virtual void a(); };1592 // struct B { virtual void b(); };1593 // struct C : A, B { virtual void b(); };1594 //1595 // Leave the value stored in the 'this' alloca unadjusted, so that the1596 // debugger sees the unadjusted value. Microsoft debuggers require this, and1597 // will apply the ThisAdjustment in the method type information.1598 // FIXME: Do something better for DWARF debuggers, which won't expect this,1599 // without making our codegen depend on debug info settings.1600 llvm::Value *This = loadIncomingCXXThis(CGF);1601 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());1602 if (!CGF.CurFuncIsThunk && MD->isVirtual()) {1603 CharUnits Adjustment = getVirtualFunctionPrologueThisAdjustment(CGF.CurGD);1604 if (!Adjustment.isZero()) {1605 assert(Adjustment.isPositive());1606 This = CGF.Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, This,1607 -Adjustment.getQuantity());1608 }1609 }1610 setCXXABIThisValue(CGF, This);1611 1612 // If this is a function that the ABI specifies returns 'this', initialize1613 // the return slot to 'this' at the start of the function.1614 //1615 // Unlike the setting of return types, this is done within the ABI1616 // implementation instead of by clients of CGCXXABI because:1617 // 1) getThisValue is currently protected1618 // 2) in theory, an ABI could implement 'this' returns some other way;1619 // HasThisReturn only specifies a contract, not the implementation1620 if (HasThisReturn(CGF.CurGD) || hasMostDerivedReturn(CGF.CurGD))1621 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);1622 1623 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {1624 assert(getStructorImplicitParamDecl(CGF) &&1625 "no implicit parameter for a constructor with virtual bases?");1626 getStructorImplicitParamValue(CGF)1627 = CGF.Builder.CreateLoad(1628 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),1629 "is_most_derived");1630 }1631 1632 if (isDeletingDtor(CGF.CurGD)) {1633 assert(getStructorImplicitParamDecl(CGF) &&1634 "no implicit parameter for a deleting destructor?");1635 getStructorImplicitParamValue(CGF)1636 = CGF.Builder.CreateLoad(1637 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),1638 "should_call_delete");1639 }1640}1641 1642CGCXXABI::AddedStructorArgs MicrosoftCXXABI::getImplicitConstructorArgs(1643 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,1644 bool ForVirtualBase, bool Delegating) {1645 assert(Type == Ctor_Complete || Type == Ctor_Base);1646 1647 // Check if we need a 'most_derived' parameter.1648 if (!D->getParent()->getNumVBases())1649 return AddedStructorArgs{};1650 1651 // Add the 'most_derived' argument second if we are variadic or last if not.1652 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();1653 llvm::Value *MostDerivedArg;1654 if (Delegating) {1655 MostDerivedArg = getStructorImplicitParamValue(CGF);1656 } else {1657 MostDerivedArg = llvm::ConstantInt::get(CGM.Int32Ty, Type == Ctor_Complete);1658 }1659 if (FPT->isVariadic()) {1660 return AddedStructorArgs::prefix({{MostDerivedArg, getContext().IntTy}});1661 }1662 return AddedStructorArgs::suffix({{MostDerivedArg, getContext().IntTy}});1663}1664 1665llvm::Value *MicrosoftCXXABI::getCXXDestructorImplicitParam(1666 CodeGenFunction &CGF, const CXXDestructorDecl *DD, CXXDtorType Type,1667 bool ForVirtualBase, bool Delegating) {1668 return nullptr;1669}1670 1671void MicrosoftCXXABI::EmitDestructorCall(CodeGenFunction &CGF,1672 const CXXDestructorDecl *DD,1673 CXXDtorType Type, bool ForVirtualBase,1674 bool Delegating, Address This,1675 QualType ThisTy) {1676 // Use the base destructor variant in place of the complete destructor variant1677 // if the class has no virtual bases. This effectively implements some of the1678 // -mconstructor-aliases optimization, but as part of the MS C++ ABI.1679 if (Type == Dtor_Complete && DD->getParent()->getNumVBases() == 0)1680 Type = Dtor_Base;1681 1682 GlobalDecl GD(DD, Type);1683 CGCallee Callee = CGCallee::forDirect(CGM.getAddrOfCXXStructor(GD), GD);1684 1685 if (DD->isVirtual()) {1686 assert(Type != CXXDtorType::Dtor_Deleting &&1687 "The deleting destructor should only be called via a virtual call");1688 This = adjustThisArgumentForVirtualFunctionCall(CGF, GlobalDecl(DD, Type),1689 This, false);1690 }1691 1692 llvm::BasicBlock *BaseDtorEndBB = nullptr;1693 if (ForVirtualBase && isa<CXXConstructorDecl>(CGF.CurCodeDecl)) {1694 BaseDtorEndBB = EmitDtorCompleteObjectHandler(CGF);1695 }1696 1697 llvm::Value *Implicit =1698 getCXXDestructorImplicitParam(CGF, DD, Type, ForVirtualBase,1699 Delegating); // = nullptr1700 CGF.EmitCXXDestructorCall(GD, Callee, CGF.getAsNaturalPointerTo(This, ThisTy),1701 ThisTy,1702 /*ImplicitParam=*/Implicit,1703 /*ImplicitParamTy=*/QualType(), /*E=*/nullptr);1704 if (BaseDtorEndBB) {1705 // Complete object handler should continue to be the remaining1706 CGF.Builder.CreateBr(BaseDtorEndBB);1707 CGF.EmitBlock(BaseDtorEndBB);1708 }1709}1710 1711void MicrosoftCXXABI::emitVTableTypeMetadata(const VPtrInfo &Info,1712 const CXXRecordDecl *RD,1713 llvm::GlobalVariable *VTable) {1714 // Emit type metadata on vtables with LTO or IR instrumentation.1715 // In IR instrumentation, the type metadata could be used to find out vtable1716 // definitions (for type profiling) among all global variables.1717 if (!CGM.getCodeGenOpts().LTOUnit &&1718 !CGM.getCodeGenOpts().hasProfileIRInstr())1719 return;1720 1721 // TODO: Should VirtualFunctionElimination also be supported here?1722 // See similar handling in CodeGenModule::EmitVTableTypeMetadata.1723 if (CGM.getCodeGenOpts().WholeProgramVTables) {1724 llvm::DenseSet<const CXXRecordDecl *> Visited;1725 llvm::GlobalObject::VCallVisibility TypeVis =1726 CGM.GetVCallVisibilityLevel(RD, Visited);1727 if (TypeVis != llvm::GlobalObject::VCallVisibilityPublic)1728 VTable->setVCallVisibilityMetadata(TypeVis);1729 }1730 1731 // The location of the first virtual function pointer in the virtual table,1732 // aka the "address point" on Itanium. This is at offset 0 if RTTI is1733 // disabled, or sizeof(void*) if RTTI is enabled.1734 CharUnits AddressPoint =1735 getContext().getLangOpts().RTTIData1736 ? getContext().toCharUnitsFromBits(1737 getContext().getTargetInfo().getPointerWidth(LangAS::Default))1738 : CharUnits::Zero();1739 1740 if (Info.PathToIntroducingObject.empty()) {1741 CGM.AddVTableTypeMetadata(VTable, AddressPoint, RD);1742 return;1743 }1744 1745 // Add a bitset entry for the least derived base belonging to this vftable.1746 CGM.AddVTableTypeMetadata(VTable, AddressPoint,1747 Info.PathToIntroducingObject.back());1748 1749 // Add a bitset entry for each derived class that is laid out at the same1750 // offset as the least derived base.1751 for (unsigned I = Info.PathToIntroducingObject.size() - 1; I != 0; --I) {1752 const CXXRecordDecl *DerivedRD = Info.PathToIntroducingObject[I - 1];1753 const CXXRecordDecl *BaseRD = Info.PathToIntroducingObject[I];1754 1755 const ASTRecordLayout &Layout =1756 getContext().getASTRecordLayout(DerivedRD);1757 CharUnits Offset;1758 auto VBI = Layout.getVBaseOffsetsMap().find(BaseRD);1759 if (VBI == Layout.getVBaseOffsetsMap().end())1760 Offset = Layout.getBaseClassOffset(BaseRD);1761 else1762 Offset = VBI->second.VBaseOffset;1763 if (!Offset.isZero())1764 return;1765 CGM.AddVTableTypeMetadata(VTable, AddressPoint, DerivedRD);1766 }1767 1768 // Finally do the same for the most derived class.1769 if (Info.FullOffsetInMDC.isZero())1770 CGM.AddVTableTypeMetadata(VTable, AddressPoint, RD);1771}1772 1773void MicrosoftCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,1774 const CXXRecordDecl *RD) {1775 MicrosoftVTableContext &VFTContext = CGM.getMicrosoftVTableContext();1776 const VPtrInfoVector &VFPtrs = VFTContext.getVFPtrOffsets(RD);1777 1778 for (const std::unique_ptr<VPtrInfo>& Info : VFPtrs) {1779 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, Info->FullOffsetInMDC);1780 if (VTable->hasInitializer())1781 continue;1782 1783 const VTableLayout &VTLayout =1784 VFTContext.getVFTableLayout(RD, Info->FullOffsetInMDC);1785 1786 llvm::Constant *RTTI = nullptr;1787 if (any_of(VTLayout.vtable_components(),1788 [](const VTableComponent &VTC) { return VTC.isRTTIKind(); }))1789 RTTI = getMSCompleteObjectLocator(RD, *Info);1790 1791 ConstantInitBuilder builder(CGM);1792 auto components = builder.beginStruct();1793 CGVT.createVTableInitializer(components, VTLayout, RTTI,1794 VTable->hasLocalLinkage());1795 components.finishAndSetAsInitializer(VTable);1796 1797 emitVTableTypeMetadata(*Info, RD, VTable);1798 }1799}1800 1801bool MicrosoftCXXABI::isVirtualOffsetNeededForVTableField(1802 CodeGenFunction &CGF, CodeGenFunction::VPtr Vptr) {1803 return Vptr.NearestVBase != nullptr;1804}1805 1806llvm::Value *MicrosoftCXXABI::getVTableAddressPointInStructor(1807 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,1808 const CXXRecordDecl *NearestVBase) {1809 llvm::Constant *VTableAddressPoint = getVTableAddressPoint(Base, VTableClass);1810 if (!VTableAddressPoint) {1811 assert(Base.getBase()->getNumVBases() &&1812 !getContext().getASTRecordLayout(Base.getBase()).hasOwnVFPtr());1813 }1814 return VTableAddressPoint;1815}1816 1817static void mangleVFTableName(MicrosoftMangleContext &MangleContext,1818 const CXXRecordDecl *RD, const VPtrInfo &VFPtr,1819 SmallString<256> &Name) {1820 llvm::raw_svector_ostream Out(Name);1821 MangleContext.mangleCXXVFTable(RD, VFPtr.MangledPath, Out);1822}1823 1824llvm::Constant *1825MicrosoftCXXABI::getVTableAddressPoint(BaseSubobject Base,1826 const CXXRecordDecl *VTableClass) {1827 (void)getAddrOfVTable(VTableClass, Base.getBaseOffset());1828 VFTableIdTy ID(VTableClass, Base.getBaseOffset());1829 return VFTablesMap[ID];1830}1831 1832llvm::GlobalVariable *MicrosoftCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,1833 CharUnits VPtrOffset) {1834 // getAddrOfVTable may return 0 if asked to get an address of a vtable which1835 // shouldn't be used in the given record type. We want to cache this result in1836 // VFTablesMap, thus a simple zero check is not sufficient.1837 1838 VFTableIdTy ID(RD, VPtrOffset);1839 auto [I, Inserted] = VTablesMap.try_emplace(ID);1840 if (!Inserted)1841 return I->second;1842 1843 llvm::GlobalVariable *&VTable = I->second;1844 1845 MicrosoftVTableContext &VTContext = CGM.getMicrosoftVTableContext();1846 const VPtrInfoVector &VFPtrs = VTContext.getVFPtrOffsets(RD);1847 1848 if (DeferredVFTables.insert(RD).second) {1849 // We haven't processed this record type before.1850 // Queue up this vtable for possible deferred emission.1851 CGM.addDeferredVTable(RD);1852 1853#ifndef NDEBUG1854 // Create all the vftables at once in order to make sure each vftable has1855 // a unique mangled name.1856 llvm::StringSet<> ObservedMangledNames;1857 for (const auto &VFPtr : VFPtrs) {1858 SmallString<256> Name;1859 mangleVFTableName(getMangleContext(), RD, *VFPtr, Name);1860 if (!ObservedMangledNames.insert(Name.str()).second)1861 llvm_unreachable("Already saw this mangling before?");1862 }1863#endif1864 }1865 1866 const std::unique_ptr<VPtrInfo> *VFPtrI =1867 llvm::find_if(VFPtrs, [&](const std::unique_ptr<VPtrInfo> &VPI) {1868 return VPI->FullOffsetInMDC == VPtrOffset;1869 });1870 if (VFPtrI == VFPtrs.end()) {1871 VFTablesMap[ID] = nullptr;1872 return nullptr;1873 }1874 const std::unique_ptr<VPtrInfo> &VFPtr = *VFPtrI;1875 1876 SmallString<256> VFTableName;1877 mangleVFTableName(getMangleContext(), RD, *VFPtr, VFTableName);1878 1879 // Classes marked __declspec(dllimport) need vftables generated on the1880 // import-side in order to support features like constexpr. No other1881 // translation unit relies on the emission of the local vftable, translation1882 // units are expected to generate them as needed.1883 //1884 // Because of this unique behavior, we maintain this logic here instead of1885 // getVTableLinkage.1886 llvm::GlobalValue::LinkageTypes VFTableLinkage =1887 RD->hasAttr<DLLImportAttr>() ? llvm::GlobalValue::LinkOnceODRLinkage1888 : CGM.getVTableLinkage(RD);1889 bool VFTableComesFromAnotherTU =1890 llvm::GlobalValue::isAvailableExternallyLinkage(VFTableLinkage) ||1891 llvm::GlobalValue::isExternalLinkage(VFTableLinkage);1892 bool VTableAliasIsRequred =1893 !VFTableComesFromAnotherTU && getContext().getLangOpts().RTTIData;1894 1895 if (llvm::GlobalValue *VFTable =1896 CGM.getModule().getNamedGlobal(VFTableName)) {1897 VFTablesMap[ID] = VFTable;1898 VTable = VTableAliasIsRequred1899 ? cast<llvm::GlobalVariable>(1900 cast<llvm::GlobalAlias>(VFTable)->getAliaseeObject())1901 : cast<llvm::GlobalVariable>(VFTable);1902 return VTable;1903 }1904 1905 const VTableLayout &VTLayout =1906 VTContext.getVFTableLayout(RD, VFPtr->FullOffsetInMDC);1907 llvm::GlobalValue::LinkageTypes VTableLinkage =1908 VTableAliasIsRequred ? llvm::GlobalValue::PrivateLinkage : VFTableLinkage;1909 1910 StringRef VTableName = VTableAliasIsRequred ? StringRef() : VFTableName.str();1911 1912 llvm::Type *VTableType = CGM.getVTables().getVTableType(VTLayout);1913 1914 // Create a backing variable for the contents of VTable. The VTable may1915 // or may not include space for a pointer to RTTI data.1916 llvm::GlobalValue *VFTable;1917 VTable = new llvm::GlobalVariable(CGM.getModule(), VTableType,1918 /*isConstant=*/true, VTableLinkage,1919 /*Initializer=*/nullptr, VTableName);1920 VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);1921 1922 llvm::Comdat *C = nullptr;1923 if (!VFTableComesFromAnotherTU &&1924 llvm::GlobalValue::isWeakForLinker(VFTableLinkage))1925 C = CGM.getModule().getOrInsertComdat(VFTableName.str());1926 1927 // Only insert a pointer into the VFTable for RTTI data if we are not1928 // importing it. We never reference the RTTI data directly so there is no1929 // need to make room for it.1930 if (VTableAliasIsRequred) {1931 llvm::Value *GEPIndices[] = {llvm::ConstantInt::get(CGM.Int32Ty, 0),1932 llvm::ConstantInt::get(CGM.Int32Ty, 0),1933 llvm::ConstantInt::get(CGM.Int32Ty, 1)};1934 // Create a GEP which points just after the first entry in the VFTable,1935 // this should be the location of the first virtual method.1936 llvm::Constant *VTableGEP = llvm::ConstantExpr::getInBoundsGetElementPtr(1937 VTable->getValueType(), VTable, GEPIndices);1938 if (llvm::GlobalValue::isWeakForLinker(VFTableLinkage)) {1939 VFTableLinkage = llvm::GlobalValue::ExternalLinkage;1940 if (C)1941 C->setSelectionKind(llvm::Comdat::Largest);1942 }1943 VFTable = llvm::GlobalAlias::create(CGM.Int8PtrTy,1944 /*AddressSpace=*/0, VFTableLinkage,1945 VFTableName.str(), VTableGEP,1946 &CGM.getModule());1947 VFTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);1948 } else {1949 // We don't need a GlobalAlias to be a symbol for the VTable if we won't1950 // be referencing any RTTI data.1951 // The GlobalVariable will end up being an appropriate definition of the1952 // VFTable.1953 VFTable = VTable;1954 }1955 if (C)1956 VTable->setComdat(C);1957 1958 if (RD->hasAttr<DLLExportAttr>())1959 VFTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);1960 1961 VFTablesMap[ID] = VFTable;1962 return VTable;1963}1964 1965CGCallee MicrosoftCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,1966 GlobalDecl GD,1967 Address This,1968 llvm::Type *Ty,1969 SourceLocation Loc) {1970 CGBuilderTy &Builder = CGF.Builder;1971 1972 Ty = CGF.DefaultPtrTy;1973 Address VPtr =1974 adjustThisArgumentForVirtualFunctionCall(CGF, GD, This, true);1975 1976 auto *MethodDecl = cast<CXXMethodDecl>(GD.getDecl());1977 llvm::Value *VTable =1978 CGF.GetVTablePtr(VPtr, CGF.DefaultPtrTy, MethodDecl->getParent());1979 1980 MicrosoftVTableContext &VFTContext = CGM.getMicrosoftVTableContext();1981 MethodVFTableLocation ML = VFTContext.getMethodVFTableLocation(GD);1982 1983 // Compute the identity of the most derived class whose virtual table is1984 // located at the MethodVFTableLocation ML.1985 auto getObjectWithVPtr = [&] {1986 return llvm::find_if(VFTContext.getVFPtrOffsets(1987 ML.VBase ? ML.VBase : MethodDecl->getParent()),1988 [&](const std::unique_ptr<VPtrInfo> &Info) {1989 return Info->FullOffsetInMDC == ML.VFPtrOffset;1990 })1991 ->get()1992 ->ObjectWithVPtr;1993 };1994 1995 llvm::Value *VFunc;1996 if (CGF.ShouldEmitVTableTypeCheckedLoad(MethodDecl->getParent())) {1997 VFunc = CGF.EmitVTableTypeCheckedLoad(1998 getObjectWithVPtr(), VTable, Ty,1999 ML.Index *2000 CGM.getContext().getTargetInfo().getPointerWidth(LangAS::Default) /2001 8);2002 } else {2003 if (CGM.getCodeGenOpts().PrepareForLTO)2004 CGF.EmitTypeMetadataCodeForVCall(getObjectWithVPtr(), VTable, Loc);2005 2006 llvm::Value *VFuncPtr =2007 Builder.CreateConstInBoundsGEP1_64(Ty, VTable, ML.Index, "vfn");2008 VFunc = Builder.CreateAlignedLoad(Ty, VFuncPtr, CGF.getPointerAlign());2009 }2010 2011 CGCallee Callee(GD, VFunc);2012 return Callee;2013}2014 2015llvm::Value *MicrosoftCXXABI::EmitVirtualDestructorCall(2016 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,2017 Address This, DeleteOrMemberCallExpr E, llvm::CallBase **CallOrInvoke) {2018 auto *CE = dyn_cast<const CXXMemberCallExpr *>(E);2019 auto *D = dyn_cast<const CXXDeleteExpr *>(E);2020 assert((CE != nullptr) ^ (D != nullptr));2021 assert(CE == nullptr || CE->arguments().empty());2022 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);2023 2024 // We have only one destructor in the vftable but can get both behaviors2025 // by passing an implicit int parameter.2026 GlobalDecl GD(Dtor, Dtor_Deleting);2027 const CGFunctionInfo *FInfo =2028 &CGM.getTypes().arrangeCXXStructorDeclaration(GD);2029 llvm::FunctionType *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);2030 CGCallee Callee = CGCallee::forVirtual(CE, GD, This, Ty);2031 2032 ASTContext &Context = getContext();2033 bool IsDeleting = DtorType == Dtor_Deleting;2034 bool IsGlobalDelete = D && D->isGlobalDelete() &&2035 Context.getTargetInfo().callGlobalDeleteInDeletingDtor(2036 Context.getLangOpts());2037 llvm::Value *ImplicitParam =2038 CGF.Builder.getInt32((IsDeleting ? 1 : 0) | (IsGlobalDelete ? 4 : 0));2039 2040 QualType ThisTy;2041 if (CE) {2042 ThisTy = CE->getObjectType();2043 } else {2044 ThisTy = D->getDestroyedType();2045 }2046 2047 This = adjustThisArgumentForVirtualFunctionCall(CGF, GD, This, true);2048 RValue RV =2049 CGF.EmitCXXDestructorCall(GD, Callee, This.emitRawPointer(CGF), ThisTy,2050 ImplicitParam, Context.IntTy, CE, CallOrInvoke);2051 return RV.getScalarVal();2052}2053 2054const VBTableGlobals &2055MicrosoftCXXABI::enumerateVBTables(const CXXRecordDecl *RD) {2056 // At this layer, we can key the cache off of a single class, which is much2057 // easier than caching each vbtable individually.2058 auto [Entry, Added] = VBTablesMap.try_emplace(RD);2059 VBTableGlobals &VBGlobals = Entry->second;2060 if (!Added)2061 return VBGlobals;2062 2063 MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext();2064 VBGlobals.VBTables = &Context.enumerateVBTables(RD);2065 2066 // Cache the globals for all vbtables so we don't have to recompute the2067 // mangled names.2068 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);2069 for (VPtrInfoVector::const_iterator I = VBGlobals.VBTables->begin(),2070 E = VBGlobals.VBTables->end();2071 I != E; ++I) {2072 VBGlobals.Globals.push_back(getAddrOfVBTable(**I, RD, Linkage));2073 }2074 2075 return VBGlobals;2076}2077 2078llvm::Function *2079MicrosoftCXXABI::EmitVirtualMemPtrThunk(const CXXMethodDecl *MD,2080 const MethodVFTableLocation &ML) {2081 assert(!isa<CXXConstructorDecl>(MD) && !isa<CXXDestructorDecl>(MD) &&2082 "can't form pointers to ctors or virtual dtors");2083 2084 // Calculate the mangled name.2085 SmallString<256> ThunkName;2086 llvm::raw_svector_ostream Out(ThunkName);2087 getMangleContext().mangleVirtualMemPtrThunk(MD, ML, Out);2088 2089 // If the thunk has been generated previously, just return it.2090 if (llvm::GlobalValue *GV = CGM.getModule().getNamedValue(ThunkName))2091 return cast<llvm::Function>(GV);2092 2093 // Create the llvm::Function.2094 const CGFunctionInfo &FnInfo =2095 CGM.getTypes().arrangeUnprototypedMustTailThunk(MD);2096 llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo);2097 llvm::Function *ThunkFn =2098 llvm::Function::Create(ThunkTy, llvm::Function::ExternalLinkage,2099 ThunkName.str(), &CGM.getModule());2100 assert(ThunkFn->getName() == ThunkName && "name was uniqued!");2101 2102 ThunkFn->setLinkage(MD->isExternallyVisible()2103 ? llvm::GlobalValue::LinkOnceODRLinkage2104 : llvm::GlobalValue::InternalLinkage);2105 if (MD->isExternallyVisible())2106 ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));2107 2108 CGM.SetLLVMFunctionAttributes(MD, FnInfo, ThunkFn, /*IsThunk=*/false);2109 CGM.SetLLVMFunctionAttributesForDefinition(MD, ThunkFn);2110 2111 // Add the "thunk" attribute so that LLVM knows that the return type is2112 // meaningless. These thunks can be used to call functions with differing2113 // return types, and the caller is required to cast the prototype2114 // appropriately to extract the correct value.2115 ThunkFn->addFnAttr("thunk");2116 2117 // These thunks can be compared, so they are not unnamed.2118 ThunkFn->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::None);2119 2120 // Start codegen.2121 CodeGenFunction CGF(CGM);2122 CGF.CurGD = GlobalDecl(MD);2123 CGF.CurFuncIsThunk = true;2124 2125 // Build FunctionArgs, but only include the implicit 'this' parameter2126 // declaration.2127 FunctionArgList FunctionArgs;2128 buildThisParam(CGF, FunctionArgs);2129 2130 // Start defining the function.2131 CGF.StartFunction(GlobalDecl(), FnInfo.getReturnType(), ThunkFn, FnInfo,2132 FunctionArgs, MD->getLocation(), SourceLocation());2133 2134 ApplyDebugLocation AL(CGF, MD->getLocation());2135 setCXXABIThisValue(CGF, loadIncomingCXXThis(CGF));2136 2137 // Load the vfptr and then callee from the vftable. The callee should have2138 // adjusted 'this' so that the vfptr is at offset zero.2139 llvm::Type *ThunkPtrTy = CGF.DefaultPtrTy;2140 llvm::Value *VTable =2141 CGF.GetVTablePtr(getThisAddress(CGF), CGF.DefaultPtrTy, MD->getParent());2142 2143 llvm::Value *VFuncPtr = CGF.Builder.CreateConstInBoundsGEP1_64(2144 ThunkPtrTy, VTable, ML.Index, "vfn");2145 llvm::Value *Callee =2146 CGF.Builder.CreateAlignedLoad(ThunkPtrTy, VFuncPtr, CGF.getPointerAlign());2147 2148 CGF.EmitMustTailThunk(MD, getThisValue(CGF), {ThunkTy, Callee});2149 2150 return ThunkFn;2151}2152 2153void MicrosoftCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {2154 const VBTableGlobals &VBGlobals = enumerateVBTables(RD);2155 for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) {2156 const std::unique_ptr<VPtrInfo>& VBT = (*VBGlobals.VBTables)[I];2157 llvm::GlobalVariable *GV = VBGlobals.Globals[I];2158 if (GV->isDeclaration())2159 emitVBTableDefinition(*VBT, RD, GV);2160 }2161}2162 2163llvm::GlobalVariable *2164MicrosoftCXXABI::getAddrOfVBTable(const VPtrInfo &VBT, const CXXRecordDecl *RD,2165 llvm::GlobalVariable::LinkageTypes Linkage) {2166 SmallString<256> OutName;2167 llvm::raw_svector_ostream Out(OutName);2168 getMangleContext().mangleCXXVBTable(RD, VBT.MangledPath, Out);2169 StringRef Name = OutName.str();2170 2171 llvm::ArrayType *VBTableType =2172 llvm::ArrayType::get(CGM.IntTy, 1 + VBT.ObjectWithVPtr->getNumVBases());2173 2174 assert(!CGM.getModule().getNamedGlobal(Name) &&2175 "vbtable with this name already exists: mangling bug?");2176 CharUnits Alignment =2177 CGM.getContext().getTypeAlignInChars(CGM.getContext().IntTy);2178 llvm::GlobalVariable *GV = CGM.CreateOrReplaceCXXRuntimeVariable(2179 Name, VBTableType, Linkage, Alignment.getAsAlign());2180 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);2181 2182 if (RD->hasAttr<DLLImportAttr>())2183 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);2184 else if (RD->hasAttr<DLLExportAttr>())2185 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);2186 2187 if (!GV->hasExternalLinkage())2188 emitVBTableDefinition(VBT, RD, GV);2189 2190 return GV;2191}2192 2193void MicrosoftCXXABI::emitVBTableDefinition(const VPtrInfo &VBT,2194 const CXXRecordDecl *RD,2195 llvm::GlobalVariable *GV) const {2196 const CXXRecordDecl *ObjectWithVPtr = VBT.ObjectWithVPtr;2197 2198 assert(RD->getNumVBases() && ObjectWithVPtr->getNumVBases() &&2199 "should only emit vbtables for classes with vbtables");2200 2201 const ASTRecordLayout &BaseLayout =2202 getContext().getASTRecordLayout(VBT.IntroducingObject);2203 const ASTRecordLayout &DerivedLayout = getContext().getASTRecordLayout(RD);2204 2205 SmallVector<llvm::Constant *, 4> Offsets(1 + ObjectWithVPtr->getNumVBases(),2206 nullptr);2207 2208 // The offset from ObjectWithVPtr's vbptr to itself always leads.2209 CharUnits VBPtrOffset = BaseLayout.getVBPtrOffset();2210 Offsets[0] = llvm::ConstantInt::get(CGM.IntTy, -VBPtrOffset.getQuantity());2211 2212 MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext();2213 for (const auto &I : ObjectWithVPtr->vbases()) {2214 const CXXRecordDecl *VBase = I.getType()->getAsCXXRecordDecl();2215 CharUnits Offset = DerivedLayout.getVBaseClassOffset(VBase);2216 assert(!Offset.isNegative());2217 2218 // Make it relative to the subobject vbptr.2219 CharUnits CompleteVBPtrOffset = VBT.NonVirtualOffset + VBPtrOffset;2220 if (VBT.getVBaseWithVPtr())2221 CompleteVBPtrOffset +=2222 DerivedLayout.getVBaseClassOffset(VBT.getVBaseWithVPtr());2223 Offset -= CompleteVBPtrOffset;2224 2225 unsigned VBIndex = Context.getVBTableIndex(ObjectWithVPtr, VBase);2226 assert(Offsets[VBIndex] == nullptr && "The same vbindex seen twice?");2227 Offsets[VBIndex] = llvm::ConstantInt::get(CGM.IntTy, Offset.getQuantity());2228 }2229 2230 assert(Offsets.size() ==2231 cast<llvm::ArrayType>(GV->getValueType())->getNumElements());2232 llvm::ArrayType *VBTableType =2233 llvm::ArrayType::get(CGM.IntTy, Offsets.size());2234 llvm::Constant *Init = llvm::ConstantArray::get(VBTableType, Offsets);2235 GV->setInitializer(Init);2236 2237 if (RD->hasAttr<DLLImportAttr>())2238 GV->setLinkage(llvm::GlobalVariable::AvailableExternallyLinkage);2239}2240 2241llvm::Value *MicrosoftCXXABI::performThisAdjustment(2242 CodeGenFunction &CGF, Address This,2243 const CXXRecordDecl * /*UnadjustedClass*/, const ThunkInfo &TI) {2244 const ThisAdjustment &TA = TI.This;2245 if (TA.isEmpty())2246 return This.emitRawPointer(CGF);2247 2248 This = This.withElementType(CGF.Int8Ty);2249 2250 llvm::Value *V;2251 if (TA.Virtual.isEmpty()) {2252 V = This.emitRawPointer(CGF);2253 } else {2254 assert(TA.Virtual.Microsoft.VtordispOffset < 0);2255 // Adjust the this argument based on the vtordisp value.2256 Address VtorDispPtr =2257 CGF.Builder.CreateConstInBoundsByteGEP(This,2258 CharUnits::fromQuantity(TA.Virtual.Microsoft.VtordispOffset));2259 VtorDispPtr = VtorDispPtr.withElementType(CGF.Int32Ty);2260 llvm::Value *VtorDisp = CGF.Builder.CreateLoad(VtorDispPtr, "vtordisp");2261 V = CGF.Builder.CreateGEP(This.getElementType(), This.emitRawPointer(CGF),2262 CGF.Builder.CreateNeg(VtorDisp));2263 2264 // Unfortunately, having applied the vtordisp means that we no2265 // longer really have a known alignment for the vbptr step.2266 // We'll assume the vbptr is pointer-aligned.2267 2268 if (TA.Virtual.Microsoft.VBPtrOffset) {2269 // If the final overrider is defined in a virtual base other than the one2270 // that holds the vfptr, we have to use a vtordispex thunk which looks up2271 // the vbtable of the derived class.2272 assert(TA.Virtual.Microsoft.VBPtrOffset > 0);2273 assert(TA.Virtual.Microsoft.VBOffsetOffset >= 0);2274 llvm::Value *VBPtr;2275 llvm::Value *VBaseOffset = GetVBaseOffsetFromVBPtr(2276 CGF, Address(V, CGF.Int8Ty, CGF.getPointerAlign()),2277 -TA.Virtual.Microsoft.VBPtrOffset,2278 TA.Virtual.Microsoft.VBOffsetOffset, &VBPtr);2279 V = CGF.Builder.CreateInBoundsGEP(CGF.Int8Ty, VBPtr, VBaseOffset);2280 }2281 }2282 2283 if (TA.NonVirtual) {2284 // Non-virtual adjustment might result in a pointer outside the allocated2285 // object, e.g. if the final overrider class is laid out after the virtual2286 // base that declares a method in the most derived class.2287 V = CGF.Builder.CreateConstGEP1_32(CGF.Int8Ty, V, TA.NonVirtual);2288 }2289 2290 // Don't need to bitcast back, the call CodeGen will handle this.2291 return V;2292}2293 2294llvm::Value *MicrosoftCXXABI::performReturnAdjustment(2295 CodeGenFunction &CGF, Address Ret,2296 const CXXRecordDecl * /*UnadjustedClass*/, const ReturnAdjustment &RA) {2297 2298 if (RA.isEmpty())2299 return Ret.emitRawPointer(CGF);2300 2301 Ret = Ret.withElementType(CGF.Int8Ty);2302 2303 llvm::Value *V = Ret.emitRawPointer(CGF);2304 if (RA.Virtual.Microsoft.VBIndex) {2305 assert(RA.Virtual.Microsoft.VBIndex > 0);2306 int32_t IntSize = CGF.getIntSize().getQuantity();2307 llvm::Value *VBPtr;2308 llvm::Value *VBaseOffset =2309 GetVBaseOffsetFromVBPtr(CGF, Ret, RA.Virtual.Microsoft.VBPtrOffset,2310 IntSize * RA.Virtual.Microsoft.VBIndex, &VBPtr);2311 V = CGF.Builder.CreateInBoundsGEP(CGF.Int8Ty, VBPtr, VBaseOffset);2312 }2313 2314 if (RA.NonVirtual)2315 V = CGF.Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, V, RA.NonVirtual);2316 2317 return V;2318}2319 2320bool MicrosoftCXXABI::requiresArrayCookie(const CXXDeleteExpr *expr,2321 QualType elementType) {2322 // Microsoft seems to completely ignore the possibility of a2323 // two-argument usual deallocation function.2324 return elementType.isDestructedType();2325}2326 2327bool MicrosoftCXXABI::requiresArrayCookie(const CXXNewExpr *expr) {2328 // Microsoft seems to completely ignore the possibility of a2329 // two-argument usual deallocation function.2330 return expr->getAllocatedType().isDestructedType();2331}2332 2333CharUnits MicrosoftCXXABI::getArrayCookieSizeImpl(QualType type) {2334 // The array cookie is always a size_t; we then pad that out to the2335 // alignment of the element type.2336 ASTContext &Ctx = getContext();2337 return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()),2338 Ctx.getTypeAlignInChars(type));2339}2340 2341llvm::Value *MicrosoftCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,2342 Address allocPtr,2343 CharUnits cookieSize) {2344 Address numElementsPtr = allocPtr.withElementType(CGF.SizeTy);2345 return CGF.Builder.CreateLoad(numElementsPtr);2346}2347 2348Address MicrosoftCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,2349 Address newPtr,2350 llvm::Value *numElements,2351 const CXXNewExpr *expr,2352 QualType elementType) {2353 assert(requiresArrayCookie(expr));2354 2355 // The size of the cookie.2356 CharUnits cookieSize = getArrayCookieSizeImpl(elementType);2357 2358 // Compute an offset to the cookie.2359 Address cookiePtr = newPtr;2360 2361 // Write the number of elements into the appropriate slot.2362 Address numElementsPtr = cookiePtr.withElementType(CGF.SizeTy);2363 CGF.Builder.CreateStore(numElements, numElementsPtr);2364 2365 // Finally, compute a pointer to the actual data buffer by skipping2366 // over the cookie completely.2367 return CGF.Builder.CreateConstInBoundsByteGEP(newPtr, cookieSize);2368}2369 2370static void emitGlobalDtorWithTLRegDtor(CodeGenFunction &CGF, const VarDecl &VD,2371 llvm::FunctionCallee Dtor,2372 llvm::Constant *Addr) {2373 // Create a function which calls the destructor.2374 llvm::Constant *DtorStub = CGF.createAtExitStub(VD, Dtor, Addr);2375 2376 // extern "C" int __tlregdtor(void (*f)(void));2377 llvm::FunctionType *TLRegDtorTy = llvm::FunctionType::get(2378 CGF.IntTy, DtorStub->getType(), /*isVarArg=*/false);2379 2380 llvm::FunctionCallee TLRegDtor = CGF.CGM.CreateRuntimeFunction(2381 TLRegDtorTy, "__tlregdtor", llvm::AttributeList(), /*Local=*/true);2382 if (llvm::Function *TLRegDtorFn =2383 dyn_cast<llvm::Function>(TLRegDtor.getCallee()))2384 TLRegDtorFn->setDoesNotThrow();2385 2386 CGF.EmitNounwindRuntimeCall(TLRegDtor, DtorStub);2387}2388 2389void MicrosoftCXXABI::registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,2390 llvm::FunctionCallee Dtor,2391 llvm::Constant *Addr) {2392 if (D.isNoDestroy(CGM.getContext()))2393 return;2394 2395 if (D.getTLSKind())2396 return emitGlobalDtorWithTLRegDtor(CGF, D, Dtor, Addr);2397 2398 // HLSL doesn't support atexit.2399 if (CGM.getLangOpts().HLSL)2400 return CGM.AddCXXDtorEntry(Dtor, Addr);2401 2402 // The default behavior is to use atexit.2403 CGF.registerGlobalDtorWithAtExit(D, Dtor, Addr);2404}2405 2406void MicrosoftCXXABI::EmitThreadLocalInitFuncs(2407 CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,2408 ArrayRef<llvm::Function *> CXXThreadLocalInits,2409 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) {2410 if (CXXThreadLocalInits.empty())2411 return;2412 2413 CGM.AppendLinkerOptions(CGM.getTarget().getTriple().getArch() ==2414 llvm::Triple::x862415 ? "/include:___dyn_tls_init@12"2416 : "/include:__dyn_tls_init");2417 2418 // This will create a GV in the .CRT$XDU section. It will point to our2419 // initialization function. The CRT will call all of these function2420 // pointers at start-up time and, eventually, at thread-creation time.2421 auto AddToXDU = [&CGM](llvm::Function *InitFunc) {2422 llvm::GlobalVariable *InitFuncPtr = new llvm::GlobalVariable(2423 CGM.getModule(), InitFunc->getType(), /*isConstant=*/true,2424 llvm::GlobalVariable::InternalLinkage, InitFunc,2425 Twine(InitFunc->getName(), "$initializer$"));2426 InitFuncPtr->setSection(".CRT$XDU");2427 // This variable has discardable linkage, we have to add it to @llvm.used to2428 // ensure it won't get discarded.2429 CGM.addUsedGlobal(InitFuncPtr);2430 return InitFuncPtr;2431 };2432 2433 std::vector<llvm::Function *> NonComdatInits;2434 for (size_t I = 0, E = CXXThreadLocalInitVars.size(); I != E; ++I) {2435 llvm::GlobalVariable *GV = cast<llvm::GlobalVariable>(2436 CGM.GetGlobalValue(CGM.getMangledName(CXXThreadLocalInitVars[I])));2437 llvm::Function *F = CXXThreadLocalInits[I];2438 2439 // If the GV is already in a comdat group, then we have to join it.2440 if (llvm::Comdat *C = GV->getComdat())2441 AddToXDU(F)->setComdat(C);2442 else2443 NonComdatInits.push_back(F);2444 }2445 2446 if (!NonComdatInits.empty()) {2447 llvm::FunctionType *FTy =2448 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);2449 llvm::Function *InitFunc = CGM.CreateGlobalInitOrCleanUpFunction(2450 FTy, "__tls_init", CGM.getTypes().arrangeNullaryFunction(),2451 SourceLocation(), /*TLS=*/true);2452 CodeGenFunction(CGM).GenerateCXXGlobalInitFunc(InitFunc, NonComdatInits);2453 2454 AddToXDU(InitFunc);2455 }2456}2457 2458static llvm::GlobalValue *getTlsGuardVar(CodeGenModule &CGM) {2459 // __tls_guard comes from the MSVC runtime and reflects2460 // whether TLS has been initialized for a particular thread.2461 // It is set from within __dyn_tls_init by the runtime.2462 // Every library and executable has its own variable.2463 llvm::Type *VTy = llvm::Type::getInt8Ty(CGM.getLLVMContext());2464 llvm::Constant *TlsGuardConstant =2465 CGM.CreateRuntimeVariable(VTy, "__tls_guard");2466 llvm::GlobalValue *TlsGuard = cast<llvm::GlobalValue>(TlsGuardConstant);2467 2468 TlsGuard->setThreadLocal(true);2469 2470 return TlsGuard;2471}2472 2473static llvm::FunctionCallee getDynTlsOnDemandInitFn(CodeGenModule &CGM) {2474 // __dyn_tls_on_demand_init comes from the MSVC runtime and triggers2475 // dynamic TLS initialization by calling __dyn_tls_init internally.2476 llvm::FunctionType *FTy =2477 llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()), {},2478 /*isVarArg=*/false);2479 return CGM.CreateRuntimeFunction(2480 FTy, "__dyn_tls_on_demand_init",2481 llvm::AttributeList::get(CGM.getLLVMContext(),2482 llvm::AttributeList::FunctionIndex,2483 llvm::Attribute::NoUnwind),2484 /*Local=*/true);2485}2486 2487static void emitTlsGuardCheck(CodeGenFunction &CGF, llvm::GlobalValue *TlsGuard,2488 llvm::BasicBlock *DynInitBB,2489 llvm::BasicBlock *ContinueBB) {2490 llvm::LoadInst *TlsGuardValue =2491 CGF.Builder.CreateLoad(Address(TlsGuard, CGF.Int8Ty, CharUnits::One()));2492 llvm::Value *CmpResult =2493 CGF.Builder.CreateICmpEQ(TlsGuardValue, CGF.Builder.getInt8(0));2494 CGF.Builder.CreateCondBr(CmpResult, DynInitBB, ContinueBB);2495}2496 2497static void emitDynamicTlsInitializationCall(CodeGenFunction &CGF,2498 llvm::GlobalValue *TlsGuard,2499 llvm::BasicBlock *ContinueBB) {2500 llvm::FunctionCallee Initializer = getDynTlsOnDemandInitFn(CGF.CGM);2501 llvm::Function *InitializerFunction =2502 cast<llvm::Function>(Initializer.getCallee());2503 llvm::CallInst *CallVal = CGF.Builder.CreateCall(InitializerFunction);2504 CallVal->setCallingConv(InitializerFunction->getCallingConv());2505 2506 CGF.Builder.CreateBr(ContinueBB);2507}2508 2509static void emitDynamicTlsInitialization(CodeGenFunction &CGF) {2510 llvm::BasicBlock *DynInitBB =2511 CGF.createBasicBlock("dyntls.dyn_init", CGF.CurFn);2512 llvm::BasicBlock *ContinueBB =2513 CGF.createBasicBlock("dyntls.continue", CGF.CurFn);2514 2515 llvm::GlobalValue *TlsGuard = getTlsGuardVar(CGF.CGM);2516 2517 emitTlsGuardCheck(CGF, TlsGuard, DynInitBB, ContinueBB);2518 CGF.Builder.SetInsertPoint(DynInitBB);2519 emitDynamicTlsInitializationCall(CGF, TlsGuard, ContinueBB);2520 CGF.Builder.SetInsertPoint(ContinueBB);2521}2522 2523LValue MicrosoftCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,2524 const VarDecl *VD,2525 QualType LValType) {2526 // Dynamic TLS initialization works by checking the state of a2527 // guard variable (__tls_guard) to see whether TLS initialization2528 // for a thread has happend yet.2529 // If not, the initialization is triggered on-demand2530 // by calling __dyn_tls_on_demand_init.2531 emitDynamicTlsInitialization(CGF);2532 2533 // Emit the variable just like any regular global variable.2534 2535 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);2536 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());2537 2538 CharUnits Alignment = CGF.getContext().getDeclAlign(VD);2539 Address Addr(V, RealVarTy, Alignment);2540 2541 LValue LV = VD->getType()->isReferenceType()2542 ? CGF.EmitLoadOfReferenceLValue(Addr, VD->getType(),2543 AlignmentSource::Decl)2544 : CGF.MakeAddrLValue(Addr, LValType, AlignmentSource::Decl);2545 return LV;2546}2547 2548static ConstantAddress getInitThreadEpochPtr(CodeGenModule &CGM) {2549 StringRef VarName("_Init_thread_epoch");2550 CharUnits Align = CGM.getIntAlign();2551 if (auto *GV = CGM.getModule().getNamedGlobal(VarName))2552 return ConstantAddress(GV, GV->getValueType(), Align);2553 auto *GV = new llvm::GlobalVariable(2554 CGM.getModule(), CGM.IntTy,2555 /*isConstant=*/false, llvm::GlobalVariable::ExternalLinkage,2556 /*Initializer=*/nullptr, VarName,2557 /*InsertBefore=*/nullptr, llvm::GlobalVariable::GeneralDynamicTLSModel);2558 GV->setAlignment(Align.getAsAlign());2559 return ConstantAddress(GV, GV->getValueType(), Align);2560}2561 2562static llvm::FunctionCallee getInitThreadHeaderFn(CodeGenModule &CGM) {2563 llvm::FunctionType *FTy =2564 llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),2565 CGM.DefaultPtrTy, /*isVarArg=*/false);2566 return CGM.CreateRuntimeFunction(2567 FTy, "_Init_thread_header",2568 llvm::AttributeList::get(CGM.getLLVMContext(),2569 llvm::AttributeList::FunctionIndex,2570 llvm::Attribute::NoUnwind),2571 /*Local=*/true);2572}2573 2574static llvm::FunctionCallee getInitThreadFooterFn(CodeGenModule &CGM) {2575 llvm::FunctionType *FTy =2576 llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),2577 CGM.DefaultPtrTy, /*isVarArg=*/false);2578 return CGM.CreateRuntimeFunction(2579 FTy, "_Init_thread_footer",2580 llvm::AttributeList::get(CGM.getLLVMContext(),2581 llvm::AttributeList::FunctionIndex,2582 llvm::Attribute::NoUnwind),2583 /*Local=*/true);2584}2585 2586static llvm::FunctionCallee getInitThreadAbortFn(CodeGenModule &CGM) {2587 llvm::FunctionType *FTy =2588 llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),2589 CGM.DefaultPtrTy, /*isVarArg=*/false);2590 return CGM.CreateRuntimeFunction(2591 FTy, "_Init_thread_abort",2592 llvm::AttributeList::get(CGM.getLLVMContext(),2593 llvm::AttributeList::FunctionIndex,2594 llvm::Attribute::NoUnwind),2595 /*Local=*/true);2596}2597 2598namespace {2599struct ResetGuardBit final : EHScopeStack::Cleanup {2600 Address Guard;2601 unsigned GuardNum;2602 ResetGuardBit(Address Guard, unsigned GuardNum)2603 : Guard(Guard), GuardNum(GuardNum) {}2604 2605 void Emit(CodeGenFunction &CGF, Flags flags) override {2606 // Reset the bit in the mask so that the static variable may be2607 // reinitialized.2608 CGBuilderTy &Builder = CGF.Builder;2609 llvm::LoadInst *LI = Builder.CreateLoad(Guard);2610 llvm::ConstantInt *Mask =2611 llvm::ConstantInt::get(CGF.IntTy, ~(1ULL << GuardNum));2612 Builder.CreateStore(Builder.CreateAnd(LI, Mask), Guard);2613 }2614};2615 2616struct CallInitThreadAbort final : EHScopeStack::Cleanup {2617 llvm::Value *Guard;2618 CallInitThreadAbort(RawAddress Guard) : Guard(Guard.getPointer()) {}2619 2620 void Emit(CodeGenFunction &CGF, Flags flags) override {2621 // Calling _Init_thread_abort will reset the guard's state.2622 CGF.EmitNounwindRuntimeCall(getInitThreadAbortFn(CGF.CGM), Guard);2623 }2624};2625}2626 2627void MicrosoftCXXABI::EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,2628 llvm::GlobalVariable *GV,2629 bool PerformInit) {2630 // MSVC only uses guards for static locals.2631 if (!D.isStaticLocal()) {2632 assert(GV->hasWeakLinkage() || GV->hasLinkOnceLinkage());2633 // GlobalOpt is allowed to discard the initializer, so use linkonce_odr.2634 llvm::Function *F = CGF.CurFn;2635 F->setLinkage(llvm::GlobalValue::LinkOnceODRLinkage);2636 F->setComdat(CGM.getModule().getOrInsertComdat(F->getName()));2637 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);2638 return;2639 }2640 2641 bool ThreadlocalStatic = D.getTLSKind();2642 bool ThreadsafeStatic = getContext().getLangOpts().ThreadsafeStatics;2643 2644 // Thread-safe static variables which aren't thread-specific have a2645 // per-variable guard.2646 bool HasPerVariableGuard = ThreadsafeStatic && !ThreadlocalStatic;2647 2648 CGBuilderTy &Builder = CGF.Builder;2649 llvm::IntegerType *GuardTy = CGF.Int32Ty;2650 llvm::ConstantInt *Zero = llvm::ConstantInt::get(GuardTy, 0);2651 CharUnits GuardAlign = CharUnits::fromQuantity(4);2652 2653 // Get the guard variable for this function if we have one already.2654 GuardInfo *GI = nullptr;2655 if (ThreadlocalStatic)2656 GI = &ThreadLocalGuardVariableMap[D.getDeclContext()];2657 else if (!ThreadsafeStatic)2658 GI = &GuardVariableMap[D.getDeclContext()];2659 2660 llvm::GlobalVariable *GuardVar = GI ? GI->Guard : nullptr;2661 unsigned GuardNum;2662 if (D.isExternallyVisible()) {2663 // Externally visible variables have to be numbered in Sema to properly2664 // handle unreachable VarDecls.2665 GuardNum = getContext().getStaticLocalNumber(&D);2666 assert(GuardNum > 0);2667 GuardNum--;2668 } else if (HasPerVariableGuard) {2669 GuardNum = ThreadSafeGuardNumMap[D.getDeclContext()]++;2670 } else {2671 // Non-externally visible variables are numbered here in CodeGen.2672 GuardNum = GI->BitIndex++;2673 }2674 2675 if (!HasPerVariableGuard && GuardNum >= 32) {2676 if (D.isExternallyVisible())2677 ErrorUnsupportedABI(CGF, "more than 32 guarded initializations");2678 GuardNum %= 32;2679 GuardVar = nullptr;2680 }2681 2682 if (!GuardVar) {2683 // Mangle the name for the guard.2684 SmallString<256> GuardName;2685 {2686 llvm::raw_svector_ostream Out(GuardName);2687 if (HasPerVariableGuard)2688 getMangleContext().mangleThreadSafeStaticGuardVariable(&D, GuardNum,2689 Out);2690 else2691 getMangleContext().mangleStaticGuardVariable(&D, Out);2692 }2693 2694 // Create the guard variable with a zero-initializer. Just absorb linkage,2695 // visibility and dll storage class from the guarded variable.2696 GuardVar =2697 new llvm::GlobalVariable(CGM.getModule(), GuardTy, /*isConstant=*/false,2698 GV->getLinkage(), Zero, GuardName.str());2699 GuardVar->setVisibility(GV->getVisibility());2700 GuardVar->setDLLStorageClass(GV->getDLLStorageClass());2701 GuardVar->setAlignment(GuardAlign.getAsAlign());2702 if (GuardVar->isWeakForLinker())2703 GuardVar->setComdat(2704 CGM.getModule().getOrInsertComdat(GuardVar->getName()));2705 if (D.getTLSKind())2706 CGM.setTLSMode(GuardVar, D);2707 if (GI && !HasPerVariableGuard)2708 GI->Guard = GuardVar;2709 }2710 2711 ConstantAddress GuardAddr(GuardVar, GuardTy, GuardAlign);2712 2713 assert(GuardVar->getLinkage() == GV->getLinkage() &&2714 "static local from the same function had different linkage");2715 2716 if (!HasPerVariableGuard) {2717 // Pseudo code for the test:2718 // if (!(GuardVar & MyGuardBit)) {2719 // GuardVar |= MyGuardBit;2720 // ... initialize the object ...;2721 // }2722 2723 // Test our bit from the guard variable.2724 llvm::ConstantInt *Bit = llvm::ConstantInt::get(GuardTy, 1ULL << GuardNum);2725 llvm::LoadInst *LI = Builder.CreateLoad(GuardAddr);2726 llvm::Value *NeedsInit =2727 Builder.CreateICmpEQ(Builder.CreateAnd(LI, Bit), Zero);2728 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");2729 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");2730 CGF.EmitCXXGuardedInitBranch(NeedsInit, InitBlock, EndBlock,2731 CodeGenFunction::GuardKind::VariableGuard, &D);2732 2733 // Set our bit in the guard variable and emit the initializer and add a global2734 // destructor if appropriate.2735 CGF.EmitBlock(InitBlock);2736 Builder.CreateStore(Builder.CreateOr(LI, Bit), GuardAddr);2737 CGF.EHStack.pushCleanup<ResetGuardBit>(EHCleanup, GuardAddr, GuardNum);2738 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);2739 CGF.PopCleanupBlock();2740 Builder.CreateBr(EndBlock);2741 2742 // Continue.2743 CGF.EmitBlock(EndBlock);2744 } else {2745 // Pseudo code for the test:2746 // if (TSS > _Init_thread_epoch) {2747 // _Init_thread_header(&TSS);2748 // if (TSS == -1) {2749 // ... initialize the object ...;2750 // _Init_thread_footer(&TSS);2751 // }2752 // }2753 //2754 // The algorithm is almost identical to what can be found in the appendix2755 // found in N2325.2756 2757 // This BasicBLock determines whether or not we have any work to do.2758 llvm::LoadInst *FirstGuardLoad = Builder.CreateLoad(GuardAddr);2759 FirstGuardLoad->setOrdering(llvm::AtomicOrdering::Unordered);2760 llvm::LoadInst *InitThreadEpoch =2761 Builder.CreateLoad(getInitThreadEpochPtr(CGM));2762 llvm::Value *IsUninitialized =2763 Builder.CreateICmpSGT(FirstGuardLoad, InitThreadEpoch);2764 llvm::BasicBlock *AttemptInitBlock = CGF.createBasicBlock("init.attempt");2765 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");2766 CGF.EmitCXXGuardedInitBranch(IsUninitialized, AttemptInitBlock, EndBlock,2767 CodeGenFunction::GuardKind::VariableGuard, &D);2768 2769 // This BasicBlock attempts to determine whether or not this thread is2770 // responsible for doing the initialization.2771 CGF.EmitBlock(AttemptInitBlock);2772 CGF.EmitNounwindRuntimeCall(getInitThreadHeaderFn(CGM),2773 GuardAddr.getPointer());2774 llvm::LoadInst *SecondGuardLoad = Builder.CreateLoad(GuardAddr);2775 SecondGuardLoad->setOrdering(llvm::AtomicOrdering::Unordered);2776 llvm::Value *ShouldDoInit =2777 Builder.CreateICmpEQ(SecondGuardLoad, getAllOnesInt());2778 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");2779 Builder.CreateCondBr(ShouldDoInit, InitBlock, EndBlock);2780 2781 // Ok, we ended up getting selected as the initializing thread.2782 CGF.EmitBlock(InitBlock);2783 CGF.EHStack.pushCleanup<CallInitThreadAbort>(EHCleanup, GuardAddr);2784 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);2785 CGF.PopCleanupBlock();2786 CGF.EmitNounwindRuntimeCall(getInitThreadFooterFn(CGM),2787 GuardAddr.getPointer());2788 Builder.CreateBr(EndBlock);2789 2790 CGF.EmitBlock(EndBlock);2791 }2792}2793 2794bool MicrosoftCXXABI::isZeroInitializable(const MemberPointerType *MPT) {2795 // Null-ness for function memptrs only depends on the first field, which is2796 // the function pointer. The rest don't matter, so we can zero initialize.2797 if (MPT->isMemberFunctionPointer())2798 return true;2799 2800 // The virtual base adjustment field is always -1 for null, so if we have one2801 // we can't zero initialize. The field offset is sometimes also -1 if 0 is a2802 // valid field offset.2803 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();2804 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();2805 return (!inheritanceModelHasVBTableOffsetField(Inheritance) &&2806 RD->nullFieldOffsetIsZero());2807}2808 2809llvm::Type *2810MicrosoftCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {2811 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();2812 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();2813 llvm::SmallVector<llvm::Type *, 4> fields;2814 if (MPT->isMemberFunctionPointer())2815 fields.push_back(CGM.VoidPtrTy); // FunctionPointerOrVirtualThunk2816 else2817 fields.push_back(CGM.IntTy); // FieldOffset2818 2819 if (inheritanceModelHasNVOffsetField(MPT->isMemberFunctionPointer(),2820 Inheritance))2821 fields.push_back(CGM.IntTy);2822 if (inheritanceModelHasVBPtrOffsetField(Inheritance))2823 fields.push_back(CGM.IntTy);2824 if (inheritanceModelHasVBTableOffsetField(Inheritance))2825 fields.push_back(CGM.IntTy); // VirtualBaseAdjustmentOffset2826 2827 if (fields.size() == 1)2828 return fields[0];2829 return llvm::StructType::get(CGM.getLLVMContext(), fields);2830}2831 2832void MicrosoftCXXABI::2833GetNullMemberPointerFields(const MemberPointerType *MPT,2834 llvm::SmallVectorImpl<llvm::Constant *> &fields) {2835 assert(fields.empty());2836 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();2837 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();2838 if (MPT->isMemberFunctionPointer()) {2839 // FunctionPointerOrVirtualThunk2840 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));2841 } else {2842 if (RD->nullFieldOffsetIsZero())2843 fields.push_back(getZeroInt()); // FieldOffset2844 else2845 fields.push_back(getAllOnesInt()); // FieldOffset2846 }2847 2848 if (inheritanceModelHasNVOffsetField(MPT->isMemberFunctionPointer(),2849 Inheritance))2850 fields.push_back(getZeroInt());2851 if (inheritanceModelHasVBPtrOffsetField(Inheritance))2852 fields.push_back(getZeroInt());2853 if (inheritanceModelHasVBTableOffsetField(Inheritance))2854 fields.push_back(getAllOnesInt());2855}2856 2857llvm::Constant *2858MicrosoftCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {2859 llvm::SmallVector<llvm::Constant *, 4> fields;2860 GetNullMemberPointerFields(MPT, fields);2861 if (fields.size() == 1)2862 return fields[0];2863 llvm::Constant *Res = llvm::ConstantStruct::getAnon(fields);2864 assert(Res->getType() == ConvertMemberPointerType(MPT));2865 return Res;2866}2867 2868llvm::Constant *2869MicrosoftCXXABI::EmitFullMemberPointer(llvm::Constant *FirstField,2870 bool IsMemberFunction,2871 const CXXRecordDecl *RD,2872 CharUnits NonVirtualBaseAdjustment,2873 unsigned VBTableIndex) {2874 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();2875 2876 // Single inheritance class member pointer are represented as scalars instead2877 // of aggregates.2878 if (inheritanceModelHasOnlyOneField(IsMemberFunction, Inheritance))2879 return FirstField;2880 2881 llvm::SmallVector<llvm::Constant *, 4> fields;2882 fields.push_back(FirstField);2883 2884 if (inheritanceModelHasNVOffsetField(IsMemberFunction, Inheritance))2885 fields.push_back(llvm::ConstantInt::get(2886 CGM.IntTy, NonVirtualBaseAdjustment.getQuantity()));2887 2888 if (inheritanceModelHasVBPtrOffsetField(Inheritance)) {2889 CharUnits Offs = CharUnits::Zero();2890 if (VBTableIndex)2891 Offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();2892 fields.push_back(llvm::ConstantInt::get(CGM.IntTy, Offs.getQuantity()));2893 }2894 2895 // The rest of the fields are adjusted by conversions to a more derived class.2896 if (inheritanceModelHasVBTableOffsetField(Inheritance))2897 fields.push_back(llvm::ConstantInt::get(CGM.IntTy, VBTableIndex));2898 2899 return llvm::ConstantStruct::getAnon(fields);2900}2901 2902llvm::Constant *2903MicrosoftCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,2904 CharUnits offset) {2905 return EmitMemberDataPointer(MPT->getMostRecentCXXRecordDecl(), offset);2906}2907 2908llvm::Constant *MicrosoftCXXABI::EmitMemberDataPointer(const CXXRecordDecl *RD,2909 CharUnits offset) {2910 if (RD->getMSInheritanceModel() ==2911 MSInheritanceModel::Virtual)2912 offset -= getContext().getOffsetOfBaseWithVBPtr(RD);2913 llvm::Constant *FirstField =2914 llvm::ConstantInt::get(CGM.IntTy, offset.getQuantity());2915 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/false, RD,2916 CharUnits::Zero(), /*VBTableIndex=*/0);2917}2918 2919llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const APValue &MP,2920 QualType MPType) {2921 const MemberPointerType *DstTy = MPType->castAs<MemberPointerType>();2922 const ValueDecl *MPD = MP.getMemberPointerDecl();2923 if (!MPD)2924 return EmitNullMemberPointer(DstTy);2925 2926 ASTContext &Ctx = getContext();2927 ArrayRef<const CXXRecordDecl *> MemberPointerPath = MP.getMemberPointerPath();2928 2929 llvm::Constant *C;2930 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD)) {2931 C = EmitMemberFunctionPointer(MD);2932 } else {2933 // For a pointer to data member, start off with the offset of the field in2934 // the class in which it was declared, and convert from there if necessary.2935 // For indirect field decls, get the outermost anonymous field and use the2936 // parent class.2937 CharUnits FieldOffset = Ctx.toCharUnitsFromBits(Ctx.getFieldOffset(MPD));2938 const FieldDecl *FD = dyn_cast<FieldDecl>(MPD);2939 if (!FD)2940 FD = cast<FieldDecl>(*cast<IndirectFieldDecl>(MPD)->chain_begin());2941 const CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getParent());2942 RD = RD->getMostRecentDecl();2943 C = EmitMemberDataPointer(RD, FieldOffset);2944 }2945 2946 if (!MemberPointerPath.empty()) {2947 const CXXRecordDecl *SrcRD = cast<CXXRecordDecl>(MPD->getDeclContext());2948 const MemberPointerType *SrcTy =2949 Ctx.getMemberPointerType(DstTy->getPointeeType(),2950 /*Qualifier=*/std::nullopt, SrcRD)2951 ->castAs<MemberPointerType>();2952 2953 bool DerivedMember = MP.isMemberPointerToDerivedMember();2954 SmallVector<const CXXBaseSpecifier *, 4> DerivedToBasePath;2955 const CXXRecordDecl *PrevRD = SrcRD;2956 for (const CXXRecordDecl *PathElem : MemberPointerPath) {2957 const CXXRecordDecl *Base = nullptr;2958 const CXXRecordDecl *Derived = nullptr;2959 if (DerivedMember) {2960 Base = PathElem;2961 Derived = PrevRD;2962 } else {2963 Base = PrevRD;2964 Derived = PathElem;2965 }2966 for (const CXXBaseSpecifier &BS : Derived->bases())2967 if (BS.getType()->getAsCXXRecordDecl()->getCanonicalDecl() ==2968 Base->getCanonicalDecl())2969 DerivedToBasePath.push_back(&BS);2970 PrevRD = PathElem;2971 }2972 assert(DerivedToBasePath.size() == MemberPointerPath.size());2973 2974 CastKind CK = DerivedMember ? CK_DerivedToBaseMemberPointer2975 : CK_BaseToDerivedMemberPointer;2976 C = EmitMemberPointerConversion(SrcTy, DstTy, CK, DerivedToBasePath.begin(),2977 DerivedToBasePath.end(), C);2978 }2979 return C;2980}2981 2982llvm::Constant *2983MicrosoftCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) {2984 assert(MD->isInstance() && "Member function must not be static!");2985 2986 CharUnits NonVirtualBaseAdjustment = CharUnits::Zero();2987 const CXXRecordDecl *RD = MD->getParent()->getMostRecentDecl();2988 CodeGenTypes &Types = CGM.getTypes();2989 2990 unsigned VBTableIndex = 0;2991 llvm::Constant *FirstField;2992 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();2993 if (!MD->isVirtual()) {2994 llvm::Type *Ty;2995 // Check whether the function has a computable LLVM signature.2996 if (Types.isFuncTypeConvertible(FPT)) {2997 // The function has a computable LLVM signature; use the correct type.2998 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));2999 } else {3000 // Use an arbitrary non-function type to tell GetAddrOfFunction that the3001 // function type is incomplete.3002 Ty = CGM.PtrDiffTy;3003 }3004 FirstField = CGM.GetAddrOfFunction(MD, Ty);3005 } else {3006 auto &VTableContext = CGM.getMicrosoftVTableContext();3007 MethodVFTableLocation ML = VTableContext.getMethodVFTableLocation(MD);3008 FirstField = EmitVirtualMemPtrThunk(MD, ML);3009 // Include the vfptr adjustment if the method is in a non-primary vftable.3010 NonVirtualBaseAdjustment += ML.VFPtrOffset;3011 if (ML.VBase)3012 VBTableIndex = VTableContext.getVBTableIndex(RD, ML.VBase) * 4;3013 }3014 3015 if (VBTableIndex == 0 &&3016 RD->getMSInheritanceModel() ==3017 MSInheritanceModel::Virtual)3018 NonVirtualBaseAdjustment -= getContext().getOffsetOfBaseWithVBPtr(RD);3019 3020 // The rest of the fields are common with data member pointers.3021 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/true, RD,3022 NonVirtualBaseAdjustment, VBTableIndex);3023}3024 3025/// Member pointers are the same if they're either bitwise identical *or* both3026/// null. Null-ness for function members is determined by the first field,3027/// while for data member pointers we must compare all fields.3028llvm::Value *3029MicrosoftCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,3030 llvm::Value *L,3031 llvm::Value *R,3032 const MemberPointerType *MPT,3033 bool Inequality) {3034 CGBuilderTy &Builder = CGF.Builder;3035 3036 // Handle != comparisons by switching the sense of all boolean operations.3037 llvm::ICmpInst::Predicate Eq;3038 llvm::Instruction::BinaryOps And, Or;3039 if (Inequality) {3040 Eq = llvm::ICmpInst::ICMP_NE;3041 And = llvm::Instruction::Or;3042 Or = llvm::Instruction::And;3043 } else {3044 Eq = llvm::ICmpInst::ICMP_EQ;3045 And = llvm::Instruction::And;3046 Or = llvm::Instruction::Or;3047 }3048 3049 // If this is a single field member pointer (single inheritance), this is a3050 // single icmp.3051 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();3052 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();3053 if (inheritanceModelHasOnlyOneField(MPT->isMemberFunctionPointer(),3054 Inheritance))3055 return Builder.CreateICmp(Eq, L, R);3056 3057 // Compare the first field.3058 llvm::Value *L0 = Builder.CreateExtractValue(L, 0, "lhs.0");3059 llvm::Value *R0 = Builder.CreateExtractValue(R, 0, "rhs.0");3060 llvm::Value *Cmp0 = Builder.CreateICmp(Eq, L0, R0, "memptr.cmp.first");3061 3062 // Compare everything other than the first field.3063 llvm::Value *Res = nullptr;3064 llvm::StructType *LType = cast<llvm::StructType>(L->getType());3065 for (unsigned I = 1, E = LType->getNumElements(); I != E; ++I) {3066 llvm::Value *LF = Builder.CreateExtractValue(L, I);3067 llvm::Value *RF = Builder.CreateExtractValue(R, I);3068 llvm::Value *Cmp = Builder.CreateICmp(Eq, LF, RF, "memptr.cmp.rest");3069 if (Res)3070 Res = Builder.CreateBinOp(And, Res, Cmp);3071 else3072 Res = Cmp;3073 }3074 3075 // Check if the first field is 0 if this is a function pointer.3076 if (MPT->isMemberFunctionPointer()) {3077 // (l1 == r1 && ...) || l0 == 03078 llvm::Value *Zero = llvm::Constant::getNullValue(L0->getType());3079 llvm::Value *IsZero = Builder.CreateICmp(Eq, L0, Zero, "memptr.cmp.iszero");3080 Res = Builder.CreateBinOp(Or, Res, IsZero);3081 }3082 3083 // Combine the comparison of the first field, which must always be true for3084 // this comparison to succeeed.3085 return Builder.CreateBinOp(And, Res, Cmp0, "memptr.cmp");3086}3087 3088llvm::Value *3089MicrosoftCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,3090 llvm::Value *MemPtr,3091 const MemberPointerType *MPT) {3092 CGBuilderTy &Builder = CGF.Builder;3093 llvm::SmallVector<llvm::Constant *, 4> fields;3094 // We only need one field for member functions.3095 if (MPT->isMemberFunctionPointer())3096 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));3097 else3098 GetNullMemberPointerFields(MPT, fields);3099 assert(!fields.empty());3100 llvm::Value *FirstField = MemPtr;3101 if (MemPtr->getType()->isStructTy())3102 FirstField = Builder.CreateExtractValue(MemPtr, 0);3103 llvm::Value *Res = Builder.CreateICmpNE(FirstField, fields[0], "memptr.cmp0");3104 3105 // For function member pointers, we only need to test the function pointer3106 // field. The other fields if any can be garbage.3107 if (MPT->isMemberFunctionPointer())3108 return Res;3109 3110 // Otherwise, emit a series of compares and combine the results.3111 for (int I = 1, E = fields.size(); I < E; ++I) {3112 llvm::Value *Field = Builder.CreateExtractValue(MemPtr, I);3113 llvm::Value *Next = Builder.CreateICmpNE(Field, fields[I], "memptr.cmp");3114 Res = Builder.CreateOr(Res, Next, "memptr.tobool");3115 }3116 return Res;3117}3118 3119bool MicrosoftCXXABI::MemberPointerConstantIsNull(const MemberPointerType *MPT,3120 llvm::Constant *Val) {3121 // Function pointers are null if the pointer in the first field is null.3122 if (MPT->isMemberFunctionPointer()) {3123 llvm::Constant *FirstField = Val->getType()->isStructTy() ?3124 Val->getAggregateElement(0U) : Val;3125 return FirstField->isNullValue();3126 }3127 3128 // If it's not a function pointer and it's zero initializable, we can easily3129 // check zero.3130 if (isZeroInitializable(MPT) && Val->isNullValue())3131 return true;3132 3133 // Otherwise, break down all the fields for comparison. Hopefully these3134 // little Constants are reused, while a big null struct might not be.3135 llvm::SmallVector<llvm::Constant *, 4> Fields;3136 GetNullMemberPointerFields(MPT, Fields);3137 if (Fields.size() == 1) {3138 assert(Val->getType()->isIntegerTy());3139 return Val == Fields[0];3140 }3141 3142 unsigned I, E;3143 for (I = 0, E = Fields.size(); I != E; ++I) {3144 if (Val->getAggregateElement(I) != Fields[I])3145 break;3146 }3147 return I == E;3148}3149 3150llvm::Value *3151MicrosoftCXXABI::GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,3152 Address This,3153 llvm::Value *VBPtrOffset,3154 llvm::Value *VBTableOffset,3155 llvm::Value **VBPtrOut) {3156 CGBuilderTy &Builder = CGF.Builder;3157 // Load the vbtable pointer from the vbptr in the instance.3158 llvm::Value *VBPtr = Builder.CreateInBoundsGEP(3159 CGM.Int8Ty, This.emitRawPointer(CGF), VBPtrOffset, "vbptr");3160 if (VBPtrOut)3161 *VBPtrOut = VBPtr;3162 3163 CharUnits VBPtrAlign;3164 if (auto CI = dyn_cast<llvm::ConstantInt>(VBPtrOffset)) {3165 VBPtrAlign = This.getAlignment().alignmentAtOffset(3166 CharUnits::fromQuantity(CI->getSExtValue()));3167 } else {3168 VBPtrAlign = CGF.getPointerAlign();3169 }3170 3171 llvm::Value *VBTable =3172 Builder.CreateAlignedLoad(CGM.DefaultPtrTy, VBPtr, VBPtrAlign, "vbtable");3173 3174 // Translate from byte offset to table index. It improves analyzability.3175 llvm::Value *VBTableIndex = Builder.CreateAShr(3176 VBTableOffset, llvm::ConstantInt::get(VBTableOffset->getType(), 2),3177 "vbtindex", /*isExact=*/true);3178 3179 // Load an i32 offset from the vb-table.3180 llvm::Value *VBaseOffs =3181 Builder.CreateInBoundsGEP(CGM.Int32Ty, VBTable, VBTableIndex);3182 return Builder.CreateAlignedLoad(CGM.Int32Ty, VBaseOffs,3183 CharUnits::fromQuantity(4), "vbase_offs");3184}3185 3186// Returns an adjusted base cast to i8*, since we do more address arithmetic on3187// it.3188llvm::Value *MicrosoftCXXABI::AdjustVirtualBase(3189 CodeGenFunction &CGF, const Expr *E, const CXXRecordDecl *RD,3190 Address Base, llvm::Value *VBTableOffset, llvm::Value *VBPtrOffset) {3191 CGBuilderTy &Builder = CGF.Builder;3192 Base = Base.withElementType(CGM.Int8Ty);3193 llvm::BasicBlock *OriginalBB = nullptr;3194 llvm::BasicBlock *SkipAdjustBB = nullptr;3195 llvm::BasicBlock *VBaseAdjustBB = nullptr;3196 3197 // In the unspecified inheritance model, there might not be a vbtable at all,3198 // in which case we need to skip the virtual base lookup. If there is a3199 // vbtable, the first entry is a no-op entry that gives back the original3200 // base, so look for a virtual base adjustment offset of zero.3201 if (VBPtrOffset) {3202 OriginalBB = Builder.GetInsertBlock();3203 VBaseAdjustBB = CGF.createBasicBlock("memptr.vadjust");3204 SkipAdjustBB = CGF.createBasicBlock("memptr.skip_vadjust");3205 llvm::Value *IsVirtual =3206 Builder.CreateICmpNE(VBTableOffset, getZeroInt(),3207 "memptr.is_vbase");3208 Builder.CreateCondBr(IsVirtual, VBaseAdjustBB, SkipAdjustBB);3209 CGF.EmitBlock(VBaseAdjustBB);3210 }3211 3212 // If we weren't given a dynamic vbptr offset, RD should be complete and we'll3213 // know the vbptr offset.3214 if (!VBPtrOffset) {3215 CharUnits offs = CharUnits::Zero();3216 if (!RD->hasDefinition()) {3217 DiagnosticsEngine &Diags = CGF.CGM.getDiags();3218 unsigned DiagID = Diags.getCustomDiagID(3219 DiagnosticsEngine::Error,3220 "member pointer representation requires a "3221 "complete class type for %0 to perform this expression");3222 Diags.Report(E->getExprLoc(), DiagID) << RD << E->getSourceRange();3223 } else if (RD->getNumVBases())3224 offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();3225 VBPtrOffset = llvm::ConstantInt::get(CGM.IntTy, offs.getQuantity());3226 }3227 llvm::Value *VBPtr = nullptr;3228 llvm::Value *VBaseOffs =3229 GetVBaseOffsetFromVBPtr(CGF, Base, VBPtrOffset, VBTableOffset, &VBPtr);3230 llvm::Value *AdjustedBase =3231 Builder.CreateInBoundsGEP(CGM.Int8Ty, VBPtr, VBaseOffs);3232 3233 // Merge control flow with the case where we didn't have to adjust.3234 if (VBaseAdjustBB) {3235 Builder.CreateBr(SkipAdjustBB);3236 CGF.EmitBlock(SkipAdjustBB);3237 llvm::PHINode *Phi = Builder.CreatePHI(CGM.Int8PtrTy, 2, "memptr.base");3238 Phi->addIncoming(Base.emitRawPointer(CGF), OriginalBB);3239 Phi->addIncoming(AdjustedBase, VBaseAdjustBB);3240 return Phi;3241 }3242 return AdjustedBase;3243}3244 3245llvm::Value *MicrosoftCXXABI::EmitMemberDataPointerAddress(3246 CodeGenFunction &CGF, const Expr *E, Address Base, llvm::Value *MemPtr,3247 const MemberPointerType *MPT, bool IsInBounds) {3248 assert(MPT->isMemberDataPointer());3249 CGBuilderTy &Builder = CGF.Builder;3250 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();3251 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();3252 3253 // Extract the fields we need, regardless of model. We'll apply them if we3254 // have them.3255 llvm::Value *FieldOffset = MemPtr;3256 llvm::Value *VirtualBaseAdjustmentOffset = nullptr;3257 llvm::Value *VBPtrOffset = nullptr;3258 if (MemPtr->getType()->isStructTy()) {3259 // We need to extract values.3260 unsigned I = 0;3261 FieldOffset = Builder.CreateExtractValue(MemPtr, I++);3262 if (inheritanceModelHasVBPtrOffsetField(Inheritance))3263 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);3264 if (inheritanceModelHasVBTableOffsetField(Inheritance))3265 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);3266 }3267 3268 llvm::Value *Addr;3269 if (VirtualBaseAdjustmentOffset) {3270 Addr = AdjustVirtualBase(CGF, E, RD, Base, VirtualBaseAdjustmentOffset,3271 VBPtrOffset);3272 } else {3273 Addr = Base.emitRawPointer(CGF);3274 }3275 3276 // Apply the offset.3277 return Builder.CreateGEP(CGF.Int8Ty, Addr, FieldOffset, "memptr.offset",3278 IsInBounds ? llvm::GEPNoWrapFlags::inBounds()3279 : llvm::GEPNoWrapFlags::none());3280}3281 3282llvm::Value *3283MicrosoftCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,3284 const CastExpr *E,3285 llvm::Value *Src) {3286 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||3287 E->getCastKind() == CK_BaseToDerivedMemberPointer ||3288 E->getCastKind() == CK_ReinterpretMemberPointer);3289 3290 // Use constant emission if we can.3291 if (isa<llvm::Constant>(Src))3292 return EmitMemberPointerConversion(E, cast<llvm::Constant>(Src));3293 3294 // We may be adding or dropping fields from the member pointer, so we need3295 // both types and the inheritance models of both records.3296 const MemberPointerType *SrcTy =3297 E->getSubExpr()->getType()->castAs<MemberPointerType>();3298 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();3299 bool IsFunc = SrcTy->isMemberFunctionPointer();3300 3301 // If the classes use the same null representation, reinterpret_cast is a nop.3302 bool IsReinterpret = E->getCastKind() == CK_ReinterpretMemberPointer;3303 if (IsReinterpret && IsFunc)3304 return Src;3305 3306 CXXRecordDecl *SrcRD = SrcTy->getMostRecentCXXRecordDecl();3307 CXXRecordDecl *DstRD = DstTy->getMostRecentCXXRecordDecl();3308 if (IsReinterpret &&3309 SrcRD->nullFieldOffsetIsZero() == DstRD->nullFieldOffsetIsZero())3310 return Src;3311 3312 CGBuilderTy &Builder = CGF.Builder;3313 3314 // Branch past the conversion if Src is null.3315 llvm::Value *IsNotNull = EmitMemberPointerIsNotNull(CGF, Src, SrcTy);3316 llvm::Constant *DstNull = EmitNullMemberPointer(DstTy);3317 3318 // C++ 5.2.10p9: The null member pointer value is converted to the null member3319 // pointer value of the destination type.3320 if (IsReinterpret) {3321 // For reinterpret casts, sema ensures that src and dst are both functions3322 // or data and have the same size, which means the LLVM types should match.3323 assert(Src->getType() == DstNull->getType());3324 return Builder.CreateSelect(IsNotNull, Src, DstNull);3325 }3326 3327 llvm::BasicBlock *OriginalBB = Builder.GetInsertBlock();3328 llvm::BasicBlock *ConvertBB = CGF.createBasicBlock("memptr.convert");3329 llvm::BasicBlock *ContinueBB = CGF.createBasicBlock("memptr.converted");3330 Builder.CreateCondBr(IsNotNull, ConvertBB, ContinueBB);3331 CGF.EmitBlock(ConvertBB);3332 3333 llvm::Value *Dst = EmitNonNullMemberPointerConversion(3334 SrcTy, DstTy, E->getCastKind(), E->path_begin(), E->path_end(), Src,3335 Builder);3336 3337 Builder.CreateBr(ContinueBB);3338 3339 // In the continuation, choose between DstNull and Dst.3340 CGF.EmitBlock(ContinueBB);3341 llvm::PHINode *Phi = Builder.CreatePHI(DstNull->getType(), 2, "memptr.converted");3342 Phi->addIncoming(DstNull, OriginalBB);3343 Phi->addIncoming(Dst, ConvertBB);3344 return Phi;3345}3346 3347llvm::Value *MicrosoftCXXABI::EmitNonNullMemberPointerConversion(3348 const MemberPointerType *SrcTy, const MemberPointerType *DstTy, CastKind CK,3349 CastExpr::path_const_iterator PathBegin,3350 CastExpr::path_const_iterator PathEnd, llvm::Value *Src,3351 CGBuilderTy &Builder) {3352 const CXXRecordDecl *SrcRD = SrcTy->getMostRecentCXXRecordDecl();3353 const CXXRecordDecl *DstRD = DstTy->getMostRecentCXXRecordDecl();3354 MSInheritanceModel SrcInheritance = SrcRD->getMSInheritanceModel();3355 MSInheritanceModel DstInheritance = DstRD->getMSInheritanceModel();3356 bool IsFunc = SrcTy->isMemberFunctionPointer();3357 bool IsConstant = isa<llvm::Constant>(Src);3358 3359 // Decompose src.3360 llvm::Value *FirstField = Src;3361 llvm::Value *NonVirtualBaseAdjustment = getZeroInt();3362 llvm::Value *VirtualBaseAdjustmentOffset = getZeroInt();3363 llvm::Value *VBPtrOffset = getZeroInt();3364 if (!inheritanceModelHasOnlyOneField(IsFunc, SrcInheritance)) {3365 // We need to extract values.3366 unsigned I = 0;3367 FirstField = Builder.CreateExtractValue(Src, I++);3368 if (inheritanceModelHasNVOffsetField(IsFunc, SrcInheritance))3369 NonVirtualBaseAdjustment = Builder.CreateExtractValue(Src, I++);3370 if (inheritanceModelHasVBPtrOffsetField(SrcInheritance))3371 VBPtrOffset = Builder.CreateExtractValue(Src, I++);3372 if (inheritanceModelHasVBTableOffsetField(SrcInheritance))3373 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(Src, I++);3374 }3375 3376 bool IsDerivedToBase = (CK == CK_DerivedToBaseMemberPointer);3377 const MemberPointerType *DerivedTy = IsDerivedToBase ? SrcTy : DstTy;3378 const CXXRecordDecl *DerivedClass = DerivedTy->getMostRecentCXXRecordDecl();3379 3380 // For data pointers, we adjust the field offset directly. For functions, we3381 // have a separate field.3382 llvm::Value *&NVAdjustField = IsFunc ? NonVirtualBaseAdjustment : FirstField;3383 3384 // The virtual inheritance model has a quirk: the virtual base table is always3385 // referenced when dereferencing a member pointer even if the member pointer3386 // is non-virtual. This is accounted for by adjusting the non-virtual offset3387 // to point backwards to the top of the MDC from the first VBase. Undo this3388 // adjustment to normalize the member pointer.3389 llvm::Value *SrcVBIndexEqZero =3390 Builder.CreateICmpEQ(VirtualBaseAdjustmentOffset, getZeroInt());3391 if (SrcInheritance == MSInheritanceModel::Virtual) {3392 if (int64_t SrcOffsetToFirstVBase =3393 getContext().getOffsetOfBaseWithVBPtr(SrcRD).getQuantity()) {3394 llvm::Value *UndoSrcAdjustment = Builder.CreateSelect(3395 SrcVBIndexEqZero,3396 llvm::ConstantInt::get(CGM.IntTy, SrcOffsetToFirstVBase),3397 getZeroInt());3398 NVAdjustField = Builder.CreateNSWAdd(NVAdjustField, UndoSrcAdjustment);3399 }3400 }3401 3402 // A non-zero vbindex implies that we are dealing with a source member in a3403 // floating virtual base in addition to some non-virtual offset. If the3404 // vbindex is zero, we are dealing with a source that exists in a non-virtual,3405 // fixed, base. The difference between these two cases is that the vbindex +3406 // nvoffset *always* point to the member regardless of what context they are3407 // evaluated in so long as the vbindex is adjusted. A member inside a fixed3408 // base requires explicit nv adjustment.3409 llvm::Constant *BaseClassOffset = llvm::ConstantInt::get(3410 CGM.IntTy,3411 CGM.computeNonVirtualBaseClassOffset(DerivedClass, PathBegin, PathEnd)3412 .getQuantity());3413 3414 llvm::Value *NVDisp;3415 if (IsDerivedToBase)3416 NVDisp = Builder.CreateNSWSub(NVAdjustField, BaseClassOffset, "adj");3417 else3418 NVDisp = Builder.CreateNSWAdd(NVAdjustField, BaseClassOffset, "adj");3419 3420 NVAdjustField = Builder.CreateSelect(SrcVBIndexEqZero, NVDisp, getZeroInt());3421 3422 // Update the vbindex to an appropriate value in the destination because3423 // SrcRD's vbtable might not be a strict prefix of the one in DstRD.3424 llvm::Value *DstVBIndexEqZero = SrcVBIndexEqZero;3425 if (inheritanceModelHasVBTableOffsetField(DstInheritance) &&3426 inheritanceModelHasVBTableOffsetField(SrcInheritance)) {3427 if (llvm::GlobalVariable *VDispMap =3428 getAddrOfVirtualDisplacementMap(SrcRD, DstRD)) {3429 llvm::Value *VBIndex = Builder.CreateExactUDiv(3430 VirtualBaseAdjustmentOffset, llvm::ConstantInt::get(CGM.IntTy, 4));3431 if (IsConstant) {3432 llvm::Constant *Mapping = VDispMap->getInitializer();3433 VirtualBaseAdjustmentOffset =3434 Mapping->getAggregateElement(cast<llvm::Constant>(VBIndex));3435 } else {3436 llvm::Value *Idxs[] = {getZeroInt(), VBIndex};3437 VirtualBaseAdjustmentOffset = Builder.CreateAlignedLoad(3438 CGM.IntTy, Builder.CreateInBoundsGEP(VDispMap->getValueType(),3439 VDispMap, Idxs),3440 CharUnits::fromQuantity(4));3441 }3442 3443 DstVBIndexEqZero =3444 Builder.CreateICmpEQ(VirtualBaseAdjustmentOffset, getZeroInt());3445 }3446 }3447 3448 // Set the VBPtrOffset to zero if the vbindex is zero. Otherwise, initialize3449 // it to the offset of the vbptr.3450 if (inheritanceModelHasVBPtrOffsetField(DstInheritance)) {3451 llvm::Value *DstVBPtrOffset = llvm::ConstantInt::get(3452 CGM.IntTy,3453 getContext().getASTRecordLayout(DstRD).getVBPtrOffset().getQuantity());3454 VBPtrOffset =3455 Builder.CreateSelect(DstVBIndexEqZero, getZeroInt(), DstVBPtrOffset);3456 }3457 3458 // Likewise, apply a similar adjustment so that dereferencing the member3459 // pointer correctly accounts for the distance between the start of the first3460 // virtual base and the top of the MDC.3461 if (DstInheritance == MSInheritanceModel::Virtual) {3462 if (int64_t DstOffsetToFirstVBase =3463 getContext().getOffsetOfBaseWithVBPtr(DstRD).getQuantity()) {3464 llvm::Value *DoDstAdjustment = Builder.CreateSelect(3465 DstVBIndexEqZero,3466 llvm::ConstantInt::get(CGM.IntTy, DstOffsetToFirstVBase),3467 getZeroInt());3468 NVAdjustField = Builder.CreateNSWSub(NVAdjustField, DoDstAdjustment);3469 }3470 }3471 3472 // Recompose dst from the null struct and the adjusted fields from src.3473 llvm::Value *Dst;3474 if (inheritanceModelHasOnlyOneField(IsFunc, DstInheritance)) {3475 Dst = FirstField;3476 } else {3477 Dst = llvm::PoisonValue::get(ConvertMemberPointerType(DstTy));3478 unsigned Idx = 0;3479 Dst = Builder.CreateInsertValue(Dst, FirstField, Idx++);3480 if (inheritanceModelHasNVOffsetField(IsFunc, DstInheritance))3481 Dst = Builder.CreateInsertValue(Dst, NonVirtualBaseAdjustment, Idx++);3482 if (inheritanceModelHasVBPtrOffsetField(DstInheritance))3483 Dst = Builder.CreateInsertValue(Dst, VBPtrOffset, Idx++);3484 if (inheritanceModelHasVBTableOffsetField(DstInheritance))3485 Dst = Builder.CreateInsertValue(Dst, VirtualBaseAdjustmentOffset, Idx++);3486 }3487 return Dst;3488}3489 3490llvm::Constant *3491MicrosoftCXXABI::EmitMemberPointerConversion(const CastExpr *E,3492 llvm::Constant *Src) {3493 const MemberPointerType *SrcTy =3494 E->getSubExpr()->getType()->castAs<MemberPointerType>();3495 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();3496 3497 CastKind CK = E->getCastKind();3498 3499 return EmitMemberPointerConversion(SrcTy, DstTy, CK, E->path_begin(),3500 E->path_end(), Src);3501}3502 3503llvm::Constant *MicrosoftCXXABI::EmitMemberPointerConversion(3504 const MemberPointerType *SrcTy, const MemberPointerType *DstTy, CastKind CK,3505 CastExpr::path_const_iterator PathBegin,3506 CastExpr::path_const_iterator PathEnd, llvm::Constant *Src) {3507 assert(CK == CK_DerivedToBaseMemberPointer ||3508 CK == CK_BaseToDerivedMemberPointer ||3509 CK == CK_ReinterpretMemberPointer);3510 // If src is null, emit a new null for dst. We can't return src because dst3511 // might have a new representation.3512 if (MemberPointerConstantIsNull(SrcTy, Src))3513 return EmitNullMemberPointer(DstTy);3514 3515 // We don't need to do anything for reinterpret_casts of non-null member3516 // pointers. We should only get here when the two type representations have3517 // the same size.3518 if (CK == CK_ReinterpretMemberPointer)3519 return Src;3520 3521 CGBuilderTy Builder(CGM, CGM.getLLVMContext());3522 auto *Dst = cast<llvm::Constant>(EmitNonNullMemberPointerConversion(3523 SrcTy, DstTy, CK, PathBegin, PathEnd, Src, Builder));3524 3525 return Dst;3526}3527 3528CGCallee MicrosoftCXXABI::EmitLoadOfMemberFunctionPointer(3529 CodeGenFunction &CGF, const Expr *E, Address This,3530 llvm::Value *&ThisPtrForCall, llvm::Value *MemPtr,3531 const MemberPointerType *MPT) {3532 assert(MPT->isMemberFunctionPointer());3533 const FunctionProtoType *FPT =3534 MPT->getPointeeType()->castAs<FunctionProtoType>();3535 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();3536 CGBuilderTy &Builder = CGF.Builder;3537 3538 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();3539 3540 // Extract the fields we need, regardless of model. We'll apply them if we3541 // have them.3542 llvm::Value *FunctionPointer = MemPtr;3543 llvm::Value *NonVirtualBaseAdjustment = nullptr;3544 llvm::Value *VirtualBaseAdjustmentOffset = nullptr;3545 llvm::Value *VBPtrOffset = nullptr;3546 if (MemPtr->getType()->isStructTy()) {3547 // We need to extract values.3548 unsigned I = 0;3549 FunctionPointer = Builder.CreateExtractValue(MemPtr, I++);3550 if (inheritanceModelHasNVOffsetField(MPT, Inheritance))3551 NonVirtualBaseAdjustment = Builder.CreateExtractValue(MemPtr, I++);3552 if (inheritanceModelHasVBPtrOffsetField(Inheritance))3553 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);3554 if (inheritanceModelHasVBTableOffsetField(Inheritance))3555 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);3556 }3557 3558 if (VirtualBaseAdjustmentOffset) {3559 ThisPtrForCall = AdjustVirtualBase(CGF, E, RD, This,3560 VirtualBaseAdjustmentOffset, VBPtrOffset);3561 } else {3562 ThisPtrForCall = This.emitRawPointer(CGF);3563 }3564 3565 if (NonVirtualBaseAdjustment)3566 ThisPtrForCall = Builder.CreateInBoundsGEP(CGF.Int8Ty, ThisPtrForCall,3567 NonVirtualBaseAdjustment);3568 3569 CGCallee Callee(FPT, FunctionPointer);3570 return Callee;3571}3572 3573CGCXXABI *clang::CodeGen::CreateMicrosoftCXXABI(CodeGenModule &CGM) {3574 return new MicrosoftCXXABI(CGM);3575}3576 3577// MS RTTI Overview:3578// The run time type information emitted by cl.exe contains 5 distinct types of3579// structures. Many of them reference each other.3580//3581// TypeInfo: Static classes that are returned by typeid.3582//3583// CompleteObjectLocator: Referenced by vftables. They contain information3584// required for dynamic casting, including OffsetFromTop. They also contain3585// a reference to the TypeInfo for the type and a reference to the3586// CompleteHierarchyDescriptor for the type.3587//3588// ClassHierarchyDescriptor: Contains information about a class hierarchy.3589// Used during dynamic_cast to walk a class hierarchy. References a base3590// class array and the size of said array.3591//3592// BaseClassArray: Contains a list of classes in a hierarchy. BaseClassArray is3593// somewhat of a misnomer because the most derived class is also in the list3594// as well as multiple copies of virtual bases (if they occur multiple times3595// in the hierarchy.) The BaseClassArray contains one BaseClassDescriptor for3596// every path in the hierarchy, in pre-order depth first order. Note, we do3597// not declare a specific llvm type for BaseClassArray, it's merely an array3598// of BaseClassDescriptor pointers.3599//3600// BaseClassDescriptor: Contains information about a class in a class hierarchy.3601// BaseClassDescriptor is also somewhat of a misnomer for the same reason that3602// BaseClassArray is. It contains information about a class within a3603// hierarchy such as: is this base is ambiguous and what is its offset in the3604// vbtable. The names of the BaseClassDescriptors have all of their fields3605// mangled into them so they can be aggressively deduplicated by the linker.3606 3607static llvm::GlobalVariable *getTypeInfoVTable(CodeGenModule &CGM) {3608 StringRef MangledName("??_7type_info@@6B@");3609 if (auto VTable = CGM.getModule().getNamedGlobal(MangledName))3610 return VTable;3611 return new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,3612 /*isConstant=*/true,3613 llvm::GlobalVariable::ExternalLinkage,3614 /*Initializer=*/nullptr, MangledName);3615}3616 3617namespace {3618 3619/// A Helper struct that stores information about a class in a class3620/// hierarchy. The information stored in these structs struct is used during3621/// the generation of ClassHierarchyDescriptors and BaseClassDescriptors.3622// During RTTI creation, MSRTTIClasses are stored in a contiguous array with3623// implicit depth first pre-order tree connectivity. getFirstChild and3624// getNextSibling allow us to walk the tree efficiently.3625struct MSRTTIClass {3626 enum {3627 IsPrivateOnPath = 1 | 8,3628 IsAmbiguous = 2,3629 IsPrivate = 4,3630 IsVirtual = 16,3631 HasHierarchyDescriptor = 643632 };3633 MSRTTIClass(const CXXRecordDecl *RD) : RD(RD) {}3634 uint32_t initialize(const MSRTTIClass *Parent,3635 const CXXBaseSpecifier *Specifier);3636 3637 MSRTTIClass *getFirstChild() { return this + 1; }3638 static MSRTTIClass *getNextChild(MSRTTIClass *Child) {3639 return Child + 1 + Child->NumBases;3640 }3641 3642 const CXXRecordDecl *RD, *VirtualRoot;3643 uint32_t Flags, NumBases, OffsetInVBase;3644};3645 3646/// Recursively initialize the base class array.3647uint32_t MSRTTIClass::initialize(const MSRTTIClass *Parent,3648 const CXXBaseSpecifier *Specifier) {3649 Flags = HasHierarchyDescriptor;3650 if (!Parent) {3651 VirtualRoot = nullptr;3652 OffsetInVBase = 0;3653 } else {3654 if (Specifier->getAccessSpecifier() != AS_public)3655 Flags |= IsPrivate | IsPrivateOnPath;3656 if (Specifier->isVirtual()) {3657 Flags |= IsVirtual;3658 VirtualRoot = RD;3659 OffsetInVBase = 0;3660 } else {3661 if (Parent->Flags & IsPrivateOnPath)3662 Flags |= IsPrivateOnPath;3663 VirtualRoot = Parent->VirtualRoot;3664 OffsetInVBase = Parent->OffsetInVBase + RD->getASTContext()3665 .getASTRecordLayout(Parent->RD).getBaseClassOffset(RD).getQuantity();3666 }3667 }3668 NumBases = 0;3669 MSRTTIClass *Child = getFirstChild();3670 for (const CXXBaseSpecifier &Base : RD->bases()) {3671 NumBases += Child->initialize(this, &Base) + 1;3672 Child = getNextChild(Child);3673 }3674 return NumBases;3675}3676 3677static llvm::GlobalValue::LinkageTypes getLinkageForRTTI(QualType Ty) {3678 switch (Ty->getLinkage()) {3679 case Linkage::Invalid:3680 llvm_unreachable("Linkage hasn't been computed!");3681 3682 case Linkage::None:3683 case Linkage::Internal:3684 case Linkage::UniqueExternal:3685 return llvm::GlobalValue::InternalLinkage;3686 3687 case Linkage::VisibleNone:3688 case Linkage::Module:3689 case Linkage::External:3690 return llvm::GlobalValue::LinkOnceODRLinkage;3691 }3692 llvm_unreachable("Invalid linkage!");3693}3694 3695/// An ephemeral helper class for building MS RTTI types. It caches some3696/// calls to the module and information about the most derived class in a3697/// hierarchy.3698struct MSRTTIBuilder {3699 enum {3700 HasBranchingHierarchy = 1,3701 HasVirtualBranchingHierarchy = 2,3702 HasAmbiguousBases = 43703 };3704 3705 MSRTTIBuilder(MicrosoftCXXABI &ABI, const CXXRecordDecl *RD)3706 : CGM(ABI.CGM), Context(CGM.getContext()),3707 VMContext(CGM.getLLVMContext()), Module(CGM.getModule()), RD(RD),3708 Linkage(getLinkageForRTTI(CGM.getContext().getCanonicalTagType(RD))),3709 ABI(ABI) {}3710 3711 llvm::GlobalVariable *getBaseClassDescriptor(const MSRTTIClass &Classes);3712 llvm::GlobalVariable *3713 getBaseClassArray(SmallVectorImpl<MSRTTIClass> &Classes);3714 llvm::GlobalVariable *getClassHierarchyDescriptor();3715 llvm::GlobalVariable *getCompleteObjectLocator(const VPtrInfo &Info);3716 3717 CodeGenModule &CGM;3718 ASTContext &Context;3719 llvm::LLVMContext &VMContext;3720 llvm::Module &Module;3721 const CXXRecordDecl *RD;3722 llvm::GlobalVariable::LinkageTypes Linkage;3723 MicrosoftCXXABI &ABI;3724};3725 3726} // namespace3727 3728/// Recursively serializes a class hierarchy in pre-order depth first3729/// order.3730static void serializeClassHierarchy(SmallVectorImpl<MSRTTIClass> &Classes,3731 const CXXRecordDecl *RD) {3732 Classes.push_back(MSRTTIClass(RD));3733 for (const CXXBaseSpecifier &Base : RD->bases())3734 serializeClassHierarchy(Classes, Base.getType()->getAsCXXRecordDecl());3735}3736 3737/// Find ambiguity among base classes.3738static void3739detectAmbiguousBases(SmallVectorImpl<MSRTTIClass> &Classes) {3740 llvm::SmallPtrSet<const CXXRecordDecl *, 8> VirtualBases;3741 llvm::SmallPtrSet<const CXXRecordDecl *, 8> UniqueBases;3742 llvm::SmallPtrSet<const CXXRecordDecl *, 8> AmbiguousBases;3743 for (MSRTTIClass *Class = &Classes.front(); Class <= &Classes.back();) {3744 if ((Class->Flags & MSRTTIClass::IsVirtual) &&3745 !VirtualBases.insert(Class->RD).second) {3746 Class = MSRTTIClass::getNextChild(Class);3747 continue;3748 }3749 if (!UniqueBases.insert(Class->RD).second)3750 AmbiguousBases.insert(Class->RD);3751 Class++;3752 }3753 if (AmbiguousBases.empty())3754 return;3755 for (MSRTTIClass &Class : Classes)3756 if (AmbiguousBases.count(Class.RD))3757 Class.Flags |= MSRTTIClass::IsAmbiguous;3758}3759 3760llvm::GlobalVariable *MSRTTIBuilder::getClassHierarchyDescriptor() {3761 SmallString<256> MangledName;3762 {3763 llvm::raw_svector_ostream Out(MangledName);3764 ABI.getMangleContext().mangleCXXRTTIClassHierarchyDescriptor(RD, Out);3765 }3766 3767 // Check to see if we've already declared this ClassHierarchyDescriptor.3768 if (auto CHD = Module.getNamedGlobal(MangledName))3769 return CHD;3770 3771 // Serialize the class hierarchy and initialize the CHD Fields.3772 SmallVector<MSRTTIClass, 8> Classes;3773 serializeClassHierarchy(Classes, RD);3774 Classes.front().initialize(/*Parent=*/nullptr, /*Specifier=*/nullptr);3775 detectAmbiguousBases(Classes);3776 int Flags = 0;3777 for (const MSRTTIClass &Class : Classes) {3778 if (Class.RD->getNumBases() > 1)3779 Flags |= HasBranchingHierarchy;3780 // Note: cl.exe does not calculate "HasAmbiguousBases" correctly. We3781 // believe the field isn't actually used.3782 if (Class.Flags & MSRTTIClass::IsAmbiguous)3783 Flags |= HasAmbiguousBases;3784 }3785 if ((Flags & HasBranchingHierarchy) && RD->getNumVBases() != 0)3786 Flags |= HasVirtualBranchingHierarchy;3787 // These gep indices are used to get the address of the first element of the3788 // base class array.3789 llvm::Value *GEPIndices[] = {llvm::ConstantInt::get(CGM.IntTy, 0),3790 llvm::ConstantInt::get(CGM.IntTy, 0)};3791 3792 // Forward-declare the class hierarchy descriptor3793 auto Type = ABI.getClassHierarchyDescriptorType();3794 auto CHD = new llvm::GlobalVariable(Module, Type, /*isConstant=*/true, Linkage,3795 /*Initializer=*/nullptr,3796 MangledName);3797 if (CHD->isWeakForLinker())3798 CHD->setComdat(CGM.getModule().getOrInsertComdat(CHD->getName()));3799 3800 auto *Bases = getBaseClassArray(Classes);3801 3802 // Initialize the base class ClassHierarchyDescriptor.3803 llvm::Constant *Fields[] = {3804 llvm::ConstantInt::get(CGM.IntTy, 0), // reserved by the runtime3805 llvm::ConstantInt::get(CGM.IntTy, Flags),3806 llvm::ConstantInt::get(CGM.IntTy, Classes.size()),3807 ABI.getImageRelativeConstant(llvm::ConstantExpr::getInBoundsGetElementPtr(3808 Bases->getValueType(), Bases,3809 llvm::ArrayRef<llvm::Value *>(GEPIndices))),3810 };3811 CHD->setInitializer(llvm::ConstantStruct::get(Type, Fields));3812 return CHD;3813}3814 3815llvm::GlobalVariable *3816MSRTTIBuilder::getBaseClassArray(SmallVectorImpl<MSRTTIClass> &Classes) {3817 SmallString<256> MangledName;3818 {3819 llvm::raw_svector_ostream Out(MangledName);3820 ABI.getMangleContext().mangleCXXRTTIBaseClassArray(RD, Out);3821 }3822 3823 // Forward-declare the base class array.3824 // cl.exe pads the base class array with 1 (in 32 bit mode) or 4 (in 64 bit3825 // mode) bytes of padding. We provide a pointer sized amount of padding by3826 // adding +1 to Classes.size(). The sections have pointer alignment and are3827 // marked pick-any so it shouldn't matter.3828 llvm::Type *PtrType = ABI.getImageRelativeType(CGM.DefaultPtrTy);3829 auto *ArrType = llvm::ArrayType::get(PtrType, Classes.size() + 1);3830 auto *BCA =3831 new llvm::GlobalVariable(Module, ArrType,3832 /*isConstant=*/true, Linkage,3833 /*Initializer=*/nullptr, MangledName);3834 if (BCA->isWeakForLinker())3835 BCA->setComdat(CGM.getModule().getOrInsertComdat(BCA->getName()));3836 3837 // Initialize the BaseClassArray.3838 SmallVector<llvm::Constant *, 8> BaseClassArrayData;3839 for (MSRTTIClass &Class : Classes)3840 BaseClassArrayData.push_back(3841 ABI.getImageRelativeConstant(getBaseClassDescriptor(Class)));3842 BaseClassArrayData.push_back(llvm::Constant::getNullValue(PtrType));3843 BCA->setInitializer(llvm::ConstantArray::get(ArrType, BaseClassArrayData));3844 return BCA;3845}3846 3847llvm::GlobalVariable *3848MSRTTIBuilder::getBaseClassDescriptor(const MSRTTIClass &Class) {3849 // Compute the fields for the BaseClassDescriptor. They are computed up front3850 // because they are mangled into the name of the object.3851 uint32_t OffsetInVBTable = 0;3852 int32_t VBPtrOffset = -1;3853 if (Class.VirtualRoot) {3854 auto &VTableContext = CGM.getMicrosoftVTableContext();3855 OffsetInVBTable = VTableContext.getVBTableIndex(RD, Class.VirtualRoot) * 4;3856 VBPtrOffset = Context.getASTRecordLayout(RD).getVBPtrOffset().getQuantity();3857 }3858 3859 SmallString<256> MangledName;3860 {3861 llvm::raw_svector_ostream Out(MangledName);3862 ABI.getMangleContext().mangleCXXRTTIBaseClassDescriptor(3863 Class.RD, Class.OffsetInVBase, VBPtrOffset, OffsetInVBTable,3864 Class.Flags, Out);3865 }3866 3867 // Check to see if we've already declared this object.3868 if (auto BCD = Module.getNamedGlobal(MangledName))3869 return BCD;3870 3871 // Forward-declare the base class descriptor.3872 auto Type = ABI.getBaseClassDescriptorType();3873 auto BCD =3874 new llvm::GlobalVariable(Module, Type, /*isConstant=*/true, Linkage,3875 /*Initializer=*/nullptr, MangledName);3876 if (BCD->isWeakForLinker())3877 BCD->setComdat(CGM.getModule().getOrInsertComdat(BCD->getName()));3878 3879 // Initialize the BaseClassDescriptor.3880 llvm::Constant *Fields[] = {3881 ABI.getImageRelativeConstant(3882 ABI.getAddrOfRTTIDescriptor(Context.getCanonicalTagType(Class.RD))),3883 llvm::ConstantInt::get(CGM.IntTy, Class.NumBases),3884 llvm::ConstantInt::get(CGM.IntTy, Class.OffsetInVBase),3885 llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset),3886 llvm::ConstantInt::get(CGM.IntTy, OffsetInVBTable),3887 llvm::ConstantInt::get(CGM.IntTy, Class.Flags),3888 ABI.getImageRelativeConstant(3889 MSRTTIBuilder(ABI, Class.RD).getClassHierarchyDescriptor()),3890 };3891 BCD->setInitializer(llvm::ConstantStruct::get(Type, Fields));3892 return BCD;3893}3894 3895llvm::GlobalVariable *3896MSRTTIBuilder::getCompleteObjectLocator(const VPtrInfo &Info) {3897 SmallString<256> MangledName;3898 {3899 llvm::raw_svector_ostream Out(MangledName);3900 ABI.getMangleContext().mangleCXXRTTICompleteObjectLocator(RD, Info.MangledPath, Out);3901 }3902 3903 // Check to see if we've already computed this complete object locator.3904 if (auto COL = Module.getNamedGlobal(MangledName))3905 return COL;3906 3907 // Compute the fields of the complete object locator.3908 int OffsetToTop = Info.FullOffsetInMDC.getQuantity();3909 int VFPtrOffset = 0;3910 // The offset includes the vtordisp if one exists.3911 if (const CXXRecordDecl *VBase = Info.getVBaseWithVPtr())3912 if (Context.getASTRecordLayout(RD)3913 .getVBaseOffsetsMap()3914 .find(VBase)3915 ->second.hasVtorDisp())3916 VFPtrOffset = Info.NonVirtualOffset.getQuantity() + 4;3917 3918 // Forward-declare the complete object locator.3919 llvm::StructType *Type = ABI.getCompleteObjectLocatorType();3920 auto COL = new llvm::GlobalVariable(Module, Type, /*isConstant=*/true, Linkage,3921 /*Initializer=*/nullptr, MangledName);3922 3923 // Initialize the CompleteObjectLocator.3924 llvm::Constant *Fields[] = {3925 llvm::ConstantInt::get(CGM.IntTy, ABI.isImageRelative()),3926 llvm::ConstantInt::get(CGM.IntTy, OffsetToTop),3927 llvm::ConstantInt::get(CGM.IntTy, VFPtrOffset),3928 ABI.getImageRelativeConstant(3929 CGM.GetAddrOfRTTIDescriptor(Context.getCanonicalTagType(RD))),3930 ABI.getImageRelativeConstant(getClassHierarchyDescriptor()),3931 ABI.getImageRelativeConstant(COL),3932 };3933 llvm::ArrayRef<llvm::Constant *> FieldsRef(Fields);3934 if (!ABI.isImageRelative())3935 FieldsRef = FieldsRef.drop_back();3936 COL->setInitializer(llvm::ConstantStruct::get(Type, FieldsRef));3937 if (COL->isWeakForLinker())3938 COL->setComdat(CGM.getModule().getOrInsertComdat(COL->getName()));3939 return COL;3940}3941 3942static QualType decomposeTypeForEH(ASTContext &Context, QualType T,3943 bool &IsConst, bool &IsVolatile,3944 bool &IsUnaligned) {3945 T = Context.getExceptionObjectType(T);3946 3947 // C++14 [except.handle]p3:3948 // A handler is a match for an exception object of type E if [...]3949 // - the handler is of type cv T or const T& where T is a pointer type and3950 // E is a pointer type that can be converted to T by [...]3951 // - a qualification conversion3952 IsConst = false;3953 IsVolatile = false;3954 IsUnaligned = false;3955 QualType PointeeType = T->getPointeeType();3956 if (!PointeeType.isNull()) {3957 IsConst = PointeeType.isConstQualified();3958 IsVolatile = PointeeType.isVolatileQualified();3959 IsUnaligned = PointeeType.getQualifiers().hasUnaligned();3960 }3961 3962 // Member pointer types like "const int A::*" are represented by having RTTI3963 // for "int A::*" and separately storing the const qualifier.3964 if (const auto *MPTy = T->getAs<MemberPointerType>())3965 T = Context.getMemberPointerType(PointeeType.getUnqualifiedType(),3966 MPTy->getQualifier(),3967 MPTy->getMostRecentCXXRecordDecl());3968 3969 // Pointer types like "const int * const *" are represented by having RTTI3970 // for "const int **" and separately storing the const qualifier.3971 if (T->isPointerType())3972 T = Context.getPointerType(PointeeType.getUnqualifiedType());3973 3974 return T;3975}3976 3977CatchTypeInfo3978MicrosoftCXXABI::getAddrOfCXXCatchHandlerType(QualType Type,3979 QualType CatchHandlerType) {3980 // TypeDescriptors for exceptions never have qualified pointer types,3981 // qualifiers are stored separately in order to support qualification3982 // conversions.3983 bool IsConst, IsVolatile, IsUnaligned;3984 Type =3985 decomposeTypeForEH(getContext(), Type, IsConst, IsVolatile, IsUnaligned);3986 3987 bool IsReference = CatchHandlerType->isReferenceType();3988 3989 uint32_t Flags = 0;3990 if (IsConst)3991 Flags |= 1;3992 if (IsVolatile)3993 Flags |= 2;3994 if (IsUnaligned)3995 Flags |= 4;3996 if (IsReference)3997 Flags |= 8;3998 3999 return CatchTypeInfo{getAddrOfRTTIDescriptor(Type)->stripPointerCasts(),4000 Flags};4001}4002 4003/// Gets a TypeDescriptor. Returns a llvm::Constant * rather than a4004/// llvm::GlobalVariable * because different type descriptors have different4005/// types, and need to be abstracted. They are abstracting by casting the4006/// address to an Int8PtrTy.4007llvm::Constant *MicrosoftCXXABI::getAddrOfRTTIDescriptor(QualType Type) {4008 SmallString<256> MangledName;4009 {4010 llvm::raw_svector_ostream Out(MangledName);4011 getMangleContext().mangleCXXRTTI(Type, Out);4012 }4013 4014 // Check to see if we've already declared this TypeDescriptor.4015 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))4016 return GV;4017 4018 // Note for the future: If we would ever like to do deferred emission of4019 // RTTI, check if emitting vtables opportunistically need any adjustment.4020 4021 // Compute the fields for the TypeDescriptor.4022 SmallString<256> TypeInfoString;4023 {4024 llvm::raw_svector_ostream Out(TypeInfoString);4025 getMangleContext().mangleCXXRTTIName(Type, Out);4026 }4027 4028 // Declare and initialize the TypeDescriptor.4029 llvm::Constant *Fields[] = {4030 getTypeInfoVTable(CGM), // VFPtr4031 llvm::ConstantPointerNull::get(CGM.Int8PtrTy), // Runtime data4032 llvm::ConstantDataArray::getString(CGM.getLLVMContext(), TypeInfoString)};4033 llvm::StructType *TypeDescriptorType =4034 getTypeDescriptorType(TypeInfoString);4035 auto *Var = new llvm::GlobalVariable(4036 CGM.getModule(), TypeDescriptorType, /*isConstant=*/false,4037 getLinkageForRTTI(Type),4038 llvm::ConstantStruct::get(TypeDescriptorType, Fields),4039 MangledName);4040 if (Var->isWeakForLinker())4041 Var->setComdat(CGM.getModule().getOrInsertComdat(Var->getName()));4042 return Var;4043}4044 4045/// Gets or a creates a Microsoft CompleteObjectLocator.4046llvm::GlobalVariable *4047MicrosoftCXXABI::getMSCompleteObjectLocator(const CXXRecordDecl *RD,4048 const VPtrInfo &Info) {4049 return MSRTTIBuilder(*this, RD).getCompleteObjectLocator(Info);4050}4051 4052void MicrosoftCXXABI::emitCXXStructor(GlobalDecl GD) {4053 if (auto *ctor = dyn_cast<CXXConstructorDecl>(GD.getDecl())) {4054 // There are no constructor variants, always emit the complete destructor.4055 llvm::Function *Fn =4056 CGM.codegenCXXStructor(GD.getWithCtorType(Ctor_Complete));4057 CGM.maybeSetTrivialComdat(*ctor, *Fn);4058 return;4059 }4060 4061 auto *dtor = cast<CXXDestructorDecl>(GD.getDecl());4062 4063 // Emit the base destructor if the base and complete (vbase) destructors are4064 // equivalent. This effectively implements -mconstructor-aliases as part of4065 // the ABI.4066 if (GD.getDtorType() == Dtor_Complete &&4067 dtor->getParent()->getNumVBases() == 0)4068 GD = GD.getWithDtorType(Dtor_Base);4069 4070 // The base destructor is equivalent to the base destructor of its4071 // base class if there is exactly one non-virtual base class with a4072 // non-trivial destructor, there are no fields with a non-trivial4073 // destructor, and the body of the destructor is trivial.4074 if (GD.getDtorType() == Dtor_Base && !CGM.TryEmitBaseDestructorAsAlias(dtor))4075 return;4076 4077 llvm::Function *Fn = CGM.codegenCXXStructor(GD);4078 if (Fn->isWeakForLinker())4079 Fn->setComdat(CGM.getModule().getOrInsertComdat(Fn->getName()));4080}4081 4082llvm::Function *4083MicrosoftCXXABI::getAddrOfCXXCtorClosure(const CXXConstructorDecl *CD,4084 CXXCtorType CT) {4085 assert(CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure);4086 4087 // Calculate the mangled name.4088 SmallString<256> ThunkName;4089 llvm::raw_svector_ostream Out(ThunkName);4090 getMangleContext().mangleName(GlobalDecl(CD, CT), Out);4091 4092 // If the thunk has been generated previously, just return it.4093 if (llvm::GlobalValue *GV = CGM.getModule().getNamedValue(ThunkName))4094 return cast<llvm::Function>(GV);4095 4096 // Create the llvm::Function.4097 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeMSCtorClosure(CD, CT);4098 llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo);4099 const CXXRecordDecl *RD = CD->getParent();4100 CanQualType RecordTy = getContext().getCanonicalTagType(RD);4101 llvm::Function *ThunkFn = llvm::Function::Create(4102 ThunkTy, getLinkageForRTTI(RecordTy), ThunkName.str(), &CGM.getModule());4103 ThunkFn->setCallingConv(static_cast<llvm::CallingConv::ID>(4104 FnInfo.getEffectiveCallingConvention()));4105 if (ThunkFn->isWeakForLinker())4106 ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));4107 bool IsCopy = CT == Ctor_CopyingClosure;4108 4109 // Start codegen.4110 CodeGenFunction CGF(CGM);4111 CGF.CurGD = GlobalDecl(CD, Ctor_Complete);4112 4113 // Build FunctionArgs.4114 FunctionArgList FunctionArgs;4115 4116 // A constructor always starts with a 'this' pointer as its first argument.4117 buildThisParam(CGF, FunctionArgs);4118 4119 // Following the 'this' pointer is a reference to the source object that we4120 // are copying from.4121 ImplicitParamDecl SrcParam(4122 getContext(), /*DC=*/nullptr, SourceLocation(),4123 &getContext().Idents.get("src"),4124 getContext().getLValueReferenceType(RecordTy,4125 /*SpelledAsLValue=*/true),4126 ImplicitParamKind::Other);4127 if (IsCopy)4128 FunctionArgs.push_back(&SrcParam);4129 4130 // Constructors for classes which utilize virtual bases have an additional4131 // parameter which indicates whether or not it is being delegated to by a more4132 // derived constructor.4133 ImplicitParamDecl IsMostDerived(getContext(), /*DC=*/nullptr,4134 SourceLocation(),4135 &getContext().Idents.get("is_most_derived"),4136 getContext().IntTy, ImplicitParamKind::Other);4137 // Only add the parameter to the list if the class has virtual bases.4138 if (RD->getNumVBases() > 0)4139 FunctionArgs.push_back(&IsMostDerived);4140 4141 // Start defining the function.4142 auto NL = ApplyDebugLocation::CreateEmpty(CGF);4143 CGF.StartFunction(GlobalDecl(), FnInfo.getReturnType(), ThunkFn, FnInfo,4144 FunctionArgs, CD->getLocation(), SourceLocation());4145 // Create a scope with an artificial location for the body of this function.4146 auto AL = ApplyDebugLocation::CreateArtificial(CGF);4147 setCXXABIThisValue(CGF, loadIncomingCXXThis(CGF));4148 llvm::Value *This = getThisValue(CGF);4149 4150 llvm::Value *SrcVal =4151 IsCopy ? CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&SrcParam), "src")4152 : nullptr;4153 4154 CallArgList Args;4155 4156 // Push the this ptr.4157 Args.add(RValue::get(This), CD->getThisType());4158 4159 // Push the src ptr.4160 if (SrcVal)4161 Args.add(RValue::get(SrcVal), SrcParam.getType());4162 4163 // Add the rest of the default arguments.4164 SmallVector<const Stmt *, 4> ArgVec;4165 ArrayRef<ParmVarDecl *> params = CD->parameters().drop_front(IsCopy ? 1 : 0);4166 for (const ParmVarDecl *PD : params) {4167 assert(PD->hasDefaultArg() && "ctor closure lacks default args");4168 ArgVec.push_back(PD->getDefaultArg());4169 }4170 4171 CodeGenFunction::RunCleanupsScope Cleanups(CGF);4172 4173 const auto *FPT = CD->getType()->castAs<FunctionProtoType>();4174 CGF.EmitCallArgs(Args, FPT, llvm::ArrayRef(ArgVec), CD, IsCopy ? 1 : 0);4175 4176 // Insert any ABI-specific implicit constructor arguments.4177 AddedStructorArgCounts ExtraArgs =4178 addImplicitConstructorArgs(CGF, CD, Ctor_Complete,4179 /*ForVirtualBase=*/false,4180 /*Delegating=*/false, Args);4181 // Call the destructor with our arguments.4182 llvm::Constant *CalleePtr =4183 CGM.getAddrOfCXXStructor(GlobalDecl(CD, Ctor_Complete));4184 CGCallee Callee =4185 CGCallee::forDirect(CalleePtr, GlobalDecl(CD, Ctor_Complete));4186 const CGFunctionInfo &CalleeInfo = CGM.getTypes().arrangeCXXConstructorCall(4187 Args, CD, Ctor_Complete, ExtraArgs.Prefix, ExtraArgs.Suffix);4188 CGF.EmitCall(CalleeInfo, Callee, ReturnValueSlot(), Args);4189 4190 Cleanups.ForceCleanup();4191 4192 // Emit the ret instruction, remove any temporary instructions created for the4193 // aid of CodeGen.4194 CGF.FinishFunction(SourceLocation());4195 4196 return ThunkFn;4197}4198 4199llvm::Constant *MicrosoftCXXABI::getCatchableType(QualType T,4200 uint32_t NVOffset,4201 int32_t VBPtrOffset,4202 uint32_t VBIndex) {4203 assert(!T->isReferenceType());4204 4205 CXXRecordDecl *RD = T->getAsCXXRecordDecl();4206 const CXXConstructorDecl *CD =4207 RD ? CGM.getContext().getCopyConstructorForExceptionObject(RD) : nullptr;4208 CXXCtorType CT = Ctor_Complete;4209 if (CD)4210 if (!hasDefaultCXXMethodCC(getContext(), CD) || CD->getNumParams() != 1)4211 CT = Ctor_CopyingClosure;4212 4213 uint32_t Size = getContext().getTypeSizeInChars(T).getQuantity();4214 SmallString<256> MangledName;4215 {4216 llvm::raw_svector_ostream Out(MangledName);4217 getMangleContext().mangleCXXCatchableType(T, CD, CT, Size, NVOffset,4218 VBPtrOffset, VBIndex, Out);4219 }4220 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))4221 return getImageRelativeConstant(GV);4222 4223 // The TypeDescriptor is used by the runtime to determine if a catch handler4224 // is appropriate for the exception object.4225 llvm::Constant *TD = getImageRelativeConstant(getAddrOfRTTIDescriptor(T));4226 4227 // The runtime is responsible for calling the copy constructor if the4228 // exception is caught by value.4229 llvm::Constant *CopyCtor;4230 if (CD) {4231 if (CT == Ctor_CopyingClosure)4232 CopyCtor = getAddrOfCXXCtorClosure(CD, Ctor_CopyingClosure);4233 else4234 CopyCtor = CGM.getAddrOfCXXStructor(GlobalDecl(CD, Ctor_Complete));4235 } else {4236 CopyCtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);4237 }4238 CopyCtor = getImageRelativeConstant(CopyCtor);4239 4240 bool IsScalar = !RD;4241 bool HasVirtualBases = false;4242 bool IsStdBadAlloc = false; // std::bad_alloc is special for some reason.4243 QualType PointeeType = T;4244 if (T->isPointerType())4245 PointeeType = T->getPointeeType();4246 if (const CXXRecordDecl *RD = PointeeType->getAsCXXRecordDecl()) {4247 HasVirtualBases = RD->getNumVBases() > 0;4248 if (IdentifierInfo *II = RD->getIdentifier())4249 IsStdBadAlloc = II->isStr("bad_alloc") && RD->isInStdNamespace();4250 }4251 4252 // Encode the relevant CatchableType properties into the Flags bitfield.4253 // FIXME: Figure out how bits 2 or 8 can get set.4254 uint32_t Flags = 0;4255 if (IsScalar)4256 Flags |= 1;4257 if (HasVirtualBases)4258 Flags |= 4;4259 if (IsStdBadAlloc)4260 Flags |= 16;4261 4262 llvm::Constant *Fields[] = {4263 llvm::ConstantInt::get(CGM.IntTy, Flags), // Flags4264 TD, // TypeDescriptor4265 llvm::ConstantInt::get(CGM.IntTy, NVOffset), // NonVirtualAdjustment4266 llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset), // OffsetToVBPtr4267 llvm::ConstantInt::get(CGM.IntTy, VBIndex), // VBTableIndex4268 llvm::ConstantInt::get(CGM.IntTy, Size), // Size4269 CopyCtor // CopyCtor4270 };4271 llvm::StructType *CTType = getCatchableTypeType();4272 auto *GV = new llvm::GlobalVariable(4273 CGM.getModule(), CTType, /*isConstant=*/true, getLinkageForRTTI(T),4274 llvm::ConstantStruct::get(CTType, Fields), MangledName);4275 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);4276 GV->setSection(".xdata");4277 if (GV->isWeakForLinker())4278 GV->setComdat(CGM.getModule().getOrInsertComdat(GV->getName()));4279 return getImageRelativeConstant(GV);4280}4281 4282llvm::GlobalVariable *MicrosoftCXXABI::getCatchableTypeArray(QualType T) {4283 assert(!T->isReferenceType());4284 4285 // See if we've already generated a CatchableTypeArray for this type before.4286 llvm::GlobalVariable *&CTA = CatchableTypeArrays[T];4287 if (CTA)4288 return CTA;4289 4290 // Ensure that we don't have duplicate entries in our CatchableTypeArray by4291 // using a SmallSetVector. Duplicates may arise due to virtual bases4292 // occurring more than once in the hierarchy.4293 llvm::SmallSetVector<llvm::Constant *, 2> CatchableTypes;4294 4295 // C++14 [except.handle]p3:4296 // A handler is a match for an exception object of type E if [...]4297 // - the handler is of type cv T or cv T& and T is an unambiguous public4298 // base class of E, or4299 // - the handler is of type cv T or const T& where T is a pointer type and4300 // E is a pointer type that can be converted to T by [...]4301 // - a standard pointer conversion (4.10) not involving conversions to4302 // pointers to private or protected or ambiguous classes4303 const CXXRecordDecl *MostDerivedClass = nullptr;4304 bool IsPointer = T->isPointerType();4305 if (IsPointer)4306 MostDerivedClass = T->getPointeeType()->getAsCXXRecordDecl();4307 else4308 MostDerivedClass = T->getAsCXXRecordDecl();4309 4310 // Collect all the unambiguous public bases of the MostDerivedClass.4311 if (MostDerivedClass) {4312 const ASTContext &Context = getContext();4313 const ASTRecordLayout &MostDerivedLayout =4314 Context.getASTRecordLayout(MostDerivedClass);4315 MicrosoftVTableContext &VTableContext = CGM.getMicrosoftVTableContext();4316 SmallVector<MSRTTIClass, 8> Classes;4317 serializeClassHierarchy(Classes, MostDerivedClass);4318 Classes.front().initialize(/*Parent=*/nullptr, /*Specifier=*/nullptr);4319 detectAmbiguousBases(Classes);4320 for (const MSRTTIClass &Class : Classes) {4321 // Skip any ambiguous or private bases.4322 if (Class.Flags &4323 (MSRTTIClass::IsPrivateOnPath | MSRTTIClass::IsAmbiguous))4324 continue;4325 // Write down how to convert from a derived pointer to a base pointer.4326 uint32_t OffsetInVBTable = 0;4327 int32_t VBPtrOffset = -1;4328 if (Class.VirtualRoot) {4329 OffsetInVBTable =4330 VTableContext.getVBTableIndex(MostDerivedClass, Class.VirtualRoot)*4;4331 VBPtrOffset = MostDerivedLayout.getVBPtrOffset().getQuantity();4332 }4333 4334 // Turn our record back into a pointer if the exception object is a4335 // pointer.4336 CanQualType RTTITy = Context.getCanonicalTagType(Class.RD);4337 if (IsPointer)4338 RTTITy = Context.getPointerType(RTTITy);4339 CatchableTypes.insert(getCatchableType(RTTITy, Class.OffsetInVBase,4340 VBPtrOffset, OffsetInVBTable));4341 }4342 }4343 4344 // C++14 [except.handle]p3:4345 // A handler is a match for an exception object of type E if4346 // - The handler is of type cv T or cv T& and E and T are the same type4347 // (ignoring the top-level cv-qualifiers)4348 CatchableTypes.insert(getCatchableType(T));4349 4350 // C++14 [except.handle]p3:4351 // A handler is a match for an exception object of type E if4352 // - the handler is of type cv T or const T& where T is a pointer type and4353 // E is a pointer type that can be converted to T by [...]4354 // - a standard pointer conversion (4.10) not involving conversions to4355 // pointers to private or protected or ambiguous classes4356 //4357 // C++14 [conv.ptr]p2:4358 // A prvalue of type "pointer to cv T," where T is an object type, can be4359 // converted to a prvalue of type "pointer to cv void".4360 if (IsPointer && T->getPointeeType()->isObjectType())4361 CatchableTypes.insert(getCatchableType(getContext().VoidPtrTy));4362 4363 // C++14 [except.handle]p3:4364 // A handler is a match for an exception object of type E if [...]4365 // - the handler is of type cv T or const T& where T is a pointer or4366 // pointer to member type and E is std::nullptr_t.4367 //4368 // We cannot possibly list all possible pointer types here, making this4369 // implementation incompatible with the standard. However, MSVC includes an4370 // entry for pointer-to-void in this case. Let's do the same.4371 if (T->isNullPtrType())4372 CatchableTypes.insert(getCatchableType(getContext().VoidPtrTy));4373 4374 uint32_t NumEntries = CatchableTypes.size();4375 llvm::Type *CTType = getImageRelativeType(CGM.DefaultPtrTy);4376 llvm::ArrayType *AT = llvm::ArrayType::get(CTType, NumEntries);4377 llvm::StructType *CTAType = getCatchableTypeArrayType(NumEntries);4378 llvm::Constant *Fields[] = {4379 llvm::ConstantInt::get(CGM.IntTy, NumEntries), // NumEntries4380 llvm::ConstantArray::get(4381 AT, llvm::ArrayRef(CatchableTypes.begin(),4382 CatchableTypes.end())) // CatchableTypes4383 };4384 SmallString<256> MangledName;4385 {4386 llvm::raw_svector_ostream Out(MangledName);4387 getMangleContext().mangleCXXCatchableTypeArray(T, NumEntries, Out);4388 }4389 CTA = new llvm::GlobalVariable(4390 CGM.getModule(), CTAType, /*isConstant=*/true, getLinkageForRTTI(T),4391 llvm::ConstantStruct::get(CTAType, Fields), MangledName);4392 CTA->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);4393 CTA->setSection(".xdata");4394 if (CTA->isWeakForLinker())4395 CTA->setComdat(CGM.getModule().getOrInsertComdat(CTA->getName()));4396 return CTA;4397}4398 4399llvm::GlobalVariable *MicrosoftCXXABI::getThrowInfo(QualType T) {4400 bool IsConst, IsVolatile, IsUnaligned;4401 T = decomposeTypeForEH(getContext(), T, IsConst, IsVolatile, IsUnaligned);4402 4403 // The CatchableTypeArray enumerates the various (CV-unqualified) types that4404 // the exception object may be caught as.4405 llvm::GlobalVariable *CTA = getCatchableTypeArray(T);4406 // The first field in a CatchableTypeArray is the number of CatchableTypes.4407 // This is used as a component of the mangled name which means that we need to4408 // know what it is in order to see if we have previously generated the4409 // ThrowInfo.4410 uint32_t NumEntries =4411 cast<llvm::ConstantInt>(CTA->getInitializer()->getAggregateElement(0U))4412 ->getLimitedValue();4413 4414 SmallString<256> MangledName;4415 {4416 llvm::raw_svector_ostream Out(MangledName);4417 getMangleContext().mangleCXXThrowInfo(T, IsConst, IsVolatile, IsUnaligned,4418 NumEntries, Out);4419 }4420 4421 // Reuse a previously generated ThrowInfo if we have generated an appropriate4422 // one before.4423 if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))4424 return GV;4425 4426 // The RTTI TypeDescriptor uses an unqualified type but catch clauses must4427 // be at least as CV qualified. Encode this requirement into the Flags4428 // bitfield.4429 uint32_t Flags = 0;4430 if (IsConst)4431 Flags |= 1;4432 if (IsVolatile)4433 Flags |= 2;4434 if (IsUnaligned)4435 Flags |= 4;4436 4437 // The cleanup-function (a destructor) must be called when the exception4438 // object's lifetime ends.4439 llvm::Constant *CleanupFn = llvm::Constant::getNullValue(CGM.Int8PtrTy);4440 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())4441 if (CXXDestructorDecl *DtorD = RD->getDestructor())4442 if (!DtorD->isTrivial())4443 CleanupFn = CGM.getAddrOfCXXStructor(GlobalDecl(DtorD, Dtor_Complete));4444 // This is unused as far as we can tell, initialize it to null.4445 llvm::Constant *ForwardCompat =4446 getImageRelativeConstant(llvm::Constant::getNullValue(CGM.Int8PtrTy));4447 llvm::Constant *PointerToCatchableTypes = getImageRelativeConstant(CTA);4448 llvm::StructType *TIType = getThrowInfoType();4449 llvm::Constant *Fields[] = {4450 llvm::ConstantInt::get(CGM.IntTy, Flags), // Flags4451 getImageRelativeConstant(CleanupFn), // CleanupFn4452 ForwardCompat, // ForwardCompat4453 PointerToCatchableTypes // CatchableTypeArray4454 };4455 auto *GV = new llvm::GlobalVariable(4456 CGM.getModule(), TIType, /*isConstant=*/true, getLinkageForRTTI(T),4457 llvm::ConstantStruct::get(TIType, Fields), MangledName.str());4458 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);4459 GV->setSection(".xdata");4460 if (GV->isWeakForLinker())4461 GV->setComdat(CGM.getModule().getOrInsertComdat(GV->getName()));4462 return GV;4463}4464 4465void MicrosoftCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {4466 const Expr *SubExpr = E->getSubExpr();4467 assert(SubExpr && "SubExpr cannot be null");4468 QualType ThrowType = SubExpr->getType();4469 // The exception object lives on the stack and it's address is passed to the4470 // runtime function.4471 Address AI = CGF.CreateMemTemp(ThrowType);4472 CGF.EmitAnyExprToMem(SubExpr, AI, ThrowType.getQualifiers(),4473 /*IsInit=*/true);4474 4475 // The so-called ThrowInfo is used to describe how the exception object may be4476 // caught.4477 llvm::GlobalVariable *TI = getThrowInfo(ThrowType);4478 4479 // Call into the runtime to throw the exception.4480 llvm::Value *Args[] = {AI.emitRawPointer(CGF), TI};4481 CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(), Args);4482}4483 4484std::pair<llvm::Value *, const CXXRecordDecl *>4485MicrosoftCXXABI::LoadVTablePtr(CodeGenFunction &CGF, Address This,4486 const CXXRecordDecl *RD) {4487 CanQualType T = CGF.getContext().getCanonicalTagType(RD);4488 std::tie(This, std::ignore, RD) = performBaseAdjustment(CGF, This, T);4489 return {CGF.GetVTablePtr(This, CGM.Int8PtrTy, RD), RD};4490}4491 4492bool MicrosoftCXXABI::isPermittedToBeHomogeneousAggregate(4493 const CXXRecordDecl *RD) const {4494 // All aggregates are permitted to be HFA on non-ARM platforms, which mostly4495 // affects vectorcall on x64/x86.4496 if (!CGM.getTarget().getTriple().isAArch64())4497 return true;4498 // MSVC Windows on Arm64 has its own rules for determining if a type is HFA4499 // that are inconsistent with the AAPCS64 ABI. The following are our best4500 // determination of those rules so far, based on observation of MSVC's4501 // behavior.4502 if (RD->isEmpty())4503 return false;4504 if (RD->isPolymorphic())4505 return false;4506 if (RD->hasNonTrivialCopyAssignment())4507 return false;4508 if (RD->hasNonTrivialDestructor())4509 return false;4510 if (RD->hasNonTrivialDefaultConstructor())4511 return false;4512 // These two are somewhat redundant given the caller4513 // (ABIInfo::isHomogeneousAggregate) checks the bases and fields, but that4514 // caller doesn't consider empty bases/fields to be non-homogenous, but it4515 // looks like Microsoft's AArch64 ABI does care about these empty types &4516 // anything containing/derived from one is non-homogeneous.4517 // Instead we could add another CXXABI entry point to query this property and4518 // have ABIInfo::isHomogeneousAggregate use that property.4519 // I don't think any other of the features listed above could be true of a4520 // base/field while not true of the outer struct. For example, if you have a4521 // base/field that has an non-trivial copy assignment/dtor/default ctor, then4522 // the outer struct's corresponding operation must be non-trivial.4523 for (const CXXBaseSpecifier &B : RD->bases()) {4524 if (const CXXRecordDecl *FRD = B.getType()->getAsCXXRecordDecl()) {4525 if (!isPermittedToBeHomogeneousAggregate(FRD))4526 return false;4527 }4528 }4529 // empty fields seem to be caught by the ABIInfo::isHomogeneousAggregate4530 // checking for padding - but maybe there are ways to end up with an empty4531 // field without padding? Not that I know of, so don't check fields here &4532 // rely on the padding check.4533 return true;4534}4535