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