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