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