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