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