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