1 //===------- ItaniumCXXABI.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 Itanium C++ ABI. The class 11 // in this file generates structures that follow the Itanium C++ ABI, which is 12 // documented at: 13 // http://www.codesourcery.com/public/cxx-abi/abi.html 14 // http://www.codesourcery.com/public/cxx-abi/abi-eh.html 15 // 16 // It also supports the closely-related ARM ABI, documented at: 17 // http://infocenter.arm.com/help/topic/com.arm.doc.ihi0041c/IHI0041C_cppabi.pdf 18 // 19 //===----------------------------------------------------------------------===// 20 21 #include "CGCXXABI.h" 22 #include "CGCleanup.h" 23 #include "CGRecordLayout.h" 24 #include "CGVTables.h" 25 #include "CodeGenFunction.h" 26 #include "CodeGenModule.h" 27 #include "TargetInfo.h" 28 #include "clang/CodeGen/ConstantInitBuilder.h" 29 #include "clang/AST/Mangle.h" 30 #include "clang/AST/Type.h" 31 #include "clang/AST/StmtCXX.h" 32 #include "llvm/IR/CallSite.h" 33 #include "llvm/IR/DataLayout.h" 34 #include "llvm/IR/Instructions.h" 35 #include "llvm/IR/Intrinsics.h" 36 #include "llvm/IR/Value.h" 37 #include "llvm/Support/ScopedPrinter.h" 38 39 using namespace clang; 40 using namespace CodeGen; 41 42 namespace { 43 class ItaniumCXXABI : public CodeGen::CGCXXABI { 44 /// VTables - All the vtables which have been defined. 45 llvm::DenseMap<const CXXRecordDecl *, llvm::GlobalVariable *> VTables; 46 47 protected: 48 bool UseARMMethodPtrABI; 49 bool UseARMGuardVarABI; 50 bool Use32BitVTableOffsetABI; 51 52 ItaniumMangleContext &getMangleContext() { 53 return cast<ItaniumMangleContext>(CodeGen::CGCXXABI::getMangleContext()); 54 } 55 56 public: 57 ItaniumCXXABI(CodeGen::CodeGenModule &CGM, 58 bool UseARMMethodPtrABI = false, 59 bool UseARMGuardVarABI = false) : 60 CGCXXABI(CGM), UseARMMethodPtrABI(UseARMMethodPtrABI), 61 UseARMGuardVarABI(UseARMGuardVarABI), 62 Use32BitVTableOffsetABI(false) { } 63 64 bool classifyReturnType(CGFunctionInfo &FI) const override; 65 66 bool passClassIndirect(const CXXRecordDecl *RD) const { 67 return !canCopyArgument(RD); 68 } 69 70 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override { 71 // If C++ prohibits us from making a copy, pass by address. 72 if (passClassIndirect(RD)) 73 return RAA_Indirect; 74 return RAA_Default; 75 } 76 77 bool isThisCompleteObject(GlobalDecl GD) const override { 78 // The Itanium ABI has separate complete-object vs. base-object 79 // variants of both constructors and destructors. 80 if (isa<CXXDestructorDecl>(GD.getDecl())) { 81 switch (GD.getDtorType()) { 82 case Dtor_Complete: 83 case Dtor_Deleting: 84 return true; 85 86 case Dtor_Base: 87 return false; 88 89 case Dtor_Comdat: 90 llvm_unreachable("emitting dtor comdat as function?"); 91 } 92 llvm_unreachable("bad dtor kind"); 93 } 94 if (isa<CXXConstructorDecl>(GD.getDecl())) { 95 switch (GD.getCtorType()) { 96 case Ctor_Complete: 97 return true; 98 99 case Ctor_Base: 100 return false; 101 102 case Ctor_CopyingClosure: 103 case Ctor_DefaultClosure: 104 llvm_unreachable("closure ctors in Itanium ABI?"); 105 106 case Ctor_Comdat: 107 llvm_unreachable("emitting ctor comdat as function?"); 108 } 109 llvm_unreachable("bad dtor kind"); 110 } 111 112 // No other kinds. 113 return false; 114 } 115 116 bool isZeroInitializable(const MemberPointerType *MPT) override; 117 118 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override; 119 120 CGCallee 121 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF, 122 const Expr *E, 123 Address This, 124 llvm::Value *&ThisPtrForCall, 125 llvm::Value *MemFnPtr, 126 const MemberPointerType *MPT) override; 127 128 llvm::Value * 129 EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E, 130 Address Base, 131 llvm::Value *MemPtr, 132 const MemberPointerType *MPT) override; 133 134 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF, 135 const CastExpr *E, 136 llvm::Value *Src) override; 137 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E, 138 llvm::Constant *Src) override; 139 140 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override; 141 142 llvm::Constant *EmitMemberFunctionPointer(const CXXMethodDecl *MD) override; 143 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT, 144 CharUnits offset) override; 145 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override; 146 llvm::Constant *BuildMemberPointer(const CXXMethodDecl *MD, 147 CharUnits ThisAdjustment); 148 149 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF, 150 llvm::Value *L, llvm::Value *R, 151 const MemberPointerType *MPT, 152 bool Inequality) override; 153 154 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF, 155 llvm::Value *Addr, 156 const MemberPointerType *MPT) override; 157 158 void emitVirtualObjectDelete(CodeGenFunction &CGF, const CXXDeleteExpr *DE, 159 Address Ptr, QualType ElementType, 160 const CXXDestructorDecl *Dtor) override; 161 162 /// Itanium says that an _Unwind_Exception has to be "double-word" 163 /// aligned (and thus the end of it is also so-aligned), meaning 16 164 /// bytes. Of course, that was written for the actual Itanium, 165 /// which is a 64-bit platform. Classically, the ABI doesn't really 166 /// specify the alignment on other platforms, but in practice 167 /// libUnwind declares the struct with __attribute__((aligned)), so 168 /// we assume that alignment here. (It's generally 16 bytes, but 169 /// some targets overwrite it.) 170 CharUnits getAlignmentOfExnObject() { 171 auto align = CGM.getContext().getTargetDefaultAlignForAttributeAligned(); 172 return CGM.getContext().toCharUnitsFromBits(align); 173 } 174 175 void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) override; 176 void emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) override; 177 178 void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override; 179 180 llvm::CallInst * 181 emitTerminateForUnexpectedException(CodeGenFunction &CGF, 182 llvm::Value *Exn) override; 183 184 void EmitFundamentalRTTIDescriptor(QualType Type, bool DLLExport); 185 void EmitFundamentalRTTIDescriptors(bool DLLExport); 186 llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override; 187 CatchTypeInfo 188 getAddrOfCXXCatchHandlerType(QualType Ty, 189 QualType CatchHandlerType) override { 190 return CatchTypeInfo{getAddrOfRTTIDescriptor(Ty), 0}; 191 } 192 193 bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override; 194 void EmitBadTypeidCall(CodeGenFunction &CGF) override; 195 llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy, 196 Address ThisPtr, 197 llvm::Type *StdTypeInfoPtrTy) override; 198 199 bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr, 200 QualType SrcRecordTy) override; 201 202 llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, Address Value, 203 QualType SrcRecordTy, QualType DestTy, 204 QualType DestRecordTy, 205 llvm::BasicBlock *CastEnd) override; 206 207 llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, Address Value, 208 QualType SrcRecordTy, 209 QualType DestTy) override; 210 211 bool EmitBadCastCall(CodeGenFunction &CGF) override; 212 213 llvm::Value * 214 GetVirtualBaseClassOffset(CodeGenFunction &CGF, Address This, 215 const CXXRecordDecl *ClassDecl, 216 const CXXRecordDecl *BaseClassDecl) override; 217 218 void EmitCXXConstructors(const CXXConstructorDecl *D) override; 219 220 AddedStructorArgs 221 buildStructorSignature(const CXXMethodDecl *MD, StructorType T, 222 SmallVectorImpl<CanQualType> &ArgTys) override; 223 224 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor, 225 CXXDtorType DT) const override { 226 // Itanium does not emit any destructor variant as an inline thunk. 227 // Delegating may occur as an optimization, but all variants are either 228 // emitted with external linkage or as linkonce if they are inline and used. 229 return false; 230 } 231 232 void EmitCXXDestructors(const CXXDestructorDecl *D) override; 233 234 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy, 235 FunctionArgList &Params) override; 236 237 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override; 238 239 AddedStructorArgs 240 addImplicitConstructorArgs(CodeGenFunction &CGF, const CXXConstructorDecl *D, 241 CXXCtorType Type, bool ForVirtualBase, 242 bool Delegating, CallArgList &Args) override; 243 244 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD, 245 CXXDtorType Type, bool ForVirtualBase, 246 bool Delegating, Address This) override; 247 248 void emitVTableDefinitions(CodeGenVTables &CGVT, 249 const CXXRecordDecl *RD) override; 250 251 bool isVirtualOffsetNeededForVTableField(CodeGenFunction &CGF, 252 CodeGenFunction::VPtr Vptr) override; 253 254 bool doStructorsInitializeVPtrs(const CXXRecordDecl *VTableClass) override { 255 return true; 256 } 257 258 llvm::Constant * 259 getVTableAddressPoint(BaseSubobject Base, 260 const CXXRecordDecl *VTableClass) override; 261 262 llvm::Value *getVTableAddressPointInStructor( 263 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, 264 BaseSubobject Base, const CXXRecordDecl *NearestVBase) override; 265 266 llvm::Value *getVTableAddressPointInStructorWithVTT( 267 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, 268 BaseSubobject Base, const CXXRecordDecl *NearestVBase); 269 270 llvm::Constant * 271 getVTableAddressPointForConstExpr(BaseSubobject Base, 272 const CXXRecordDecl *VTableClass) override; 273 274 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD, 275 CharUnits VPtrOffset) override; 276 277 CGCallee getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD, 278 Address This, llvm::Type *Ty, 279 SourceLocation Loc) override; 280 281 llvm::Value *EmitVirtualDestructorCall(CodeGenFunction &CGF, 282 const CXXDestructorDecl *Dtor, 283 CXXDtorType DtorType, 284 Address This, 285 const CXXMemberCallExpr *CE) override; 286 287 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override; 288 289 bool canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const override; 290 291 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, GlobalDecl GD, 292 bool ReturnAdjustment) override { 293 // Allow inlining of thunks by emitting them with available_externally 294 // linkage together with vtables when needed. 295 if (ForVTable && !Thunk->hasLocalLinkage()) 296 Thunk->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage); 297 CGM.setGVProperties(Thunk, GD); 298 } 299 300 bool exportThunk() override { return true; } 301 302 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, Address This, 303 const ThisAdjustment &TA) override; 304 305 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, Address Ret, 306 const ReturnAdjustment &RA) override; 307 308 size_t getSrcArgforCopyCtor(const CXXConstructorDecl *, 309 FunctionArgList &Args) const override { 310 assert(!Args.empty() && "expected the arglist to not be empty!"); 311 return Args.size() - 1; 312 } 313 314 StringRef GetPureVirtualCallName() override { return "__cxa_pure_virtual"; } 315 StringRef GetDeletedVirtualCallName() override 316 { return "__cxa_deleted_virtual"; } 317 318 CharUnits getArrayCookieSizeImpl(QualType elementType) override; 319 Address InitializeArrayCookie(CodeGenFunction &CGF, 320 Address NewPtr, 321 llvm::Value *NumElements, 322 const CXXNewExpr *expr, 323 QualType ElementType) override; 324 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, 325 Address allocPtr, 326 CharUnits cookieSize) override; 327 328 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D, 329 llvm::GlobalVariable *DeclPtr, 330 bool PerformInit) override; 331 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D, 332 llvm::Constant *dtor, llvm::Constant *addr) override; 333 334 llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD, 335 llvm::Value *Val); 336 void EmitThreadLocalInitFuncs( 337 CodeGenModule &CGM, 338 ArrayRef<const VarDecl *> CXXThreadLocals, 339 ArrayRef<llvm::Function *> CXXThreadLocalInits, 340 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) override; 341 342 bool usesThreadWrapperFunction() const override { return true; } 343 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD, 344 QualType LValType) override; 345 346 bool NeedsVTTParameter(GlobalDecl GD) override; 347 348 /**************************** RTTI Uniqueness ******************************/ 349 350 protected: 351 /// Returns true if the ABI requires RTTI type_info objects to be unique 352 /// across a program. 353 virtual bool shouldRTTIBeUnique() const { return true; } 354 355 public: 356 /// What sort of unique-RTTI behavior should we use? 357 enum RTTIUniquenessKind { 358 /// We are guaranteeing, or need to guarantee, that the RTTI string 359 /// is unique. 360 RUK_Unique, 361 362 /// We are not guaranteeing uniqueness for the RTTI string, so we 363 /// can demote to hidden visibility but must use string comparisons. 364 RUK_NonUniqueHidden, 365 366 /// We are not guaranteeing uniqueness for the RTTI string, so we 367 /// have to use string comparisons, but we also have to emit it with 368 /// non-hidden visibility. 369 RUK_NonUniqueVisible 370 }; 371 372 /// Return the required visibility status for the given type and linkage in 373 /// the current ABI. 374 RTTIUniquenessKind 375 classifyRTTIUniqueness(QualType CanTy, 376 llvm::GlobalValue::LinkageTypes Linkage) const; 377 friend class ItaniumRTTIBuilder; 378 379 void emitCXXStructor(const CXXMethodDecl *MD, StructorType Type) override; 380 381 std::pair<llvm::Value *, const CXXRecordDecl *> 382 LoadVTablePtr(CodeGenFunction &CGF, Address This, 383 const CXXRecordDecl *RD) override; 384 385 private: 386 bool hasAnyUnusedVirtualInlineFunction(const CXXRecordDecl *RD) const { 387 const auto &VtableLayout = 388 CGM.getItaniumVTableContext().getVTableLayout(RD); 389 390 for (const auto &VtableComponent : VtableLayout.vtable_components()) { 391 // Skip empty slot. 392 if (!VtableComponent.isUsedFunctionPointerKind()) 393 continue; 394 395 const CXXMethodDecl *Method = VtableComponent.getFunctionDecl(); 396 if (!Method->getCanonicalDecl()->isInlined()) 397 continue; 398 399 StringRef Name = CGM.getMangledName(VtableComponent.getGlobalDecl()); 400 auto *Entry = CGM.GetGlobalValue(Name); 401 // This checks if virtual inline function has already been emitted. 402 // Note that it is possible that this inline function would be emitted 403 // after trying to emit vtable speculatively. Because of this we do 404 // an extra pass after emitting all deferred vtables to find and emit 405 // these vtables opportunistically. 406 if (!Entry || Entry->isDeclaration()) 407 return true; 408 } 409 return false; 410 } 411 412 bool isVTableHidden(const CXXRecordDecl *RD) const { 413 const auto &VtableLayout = 414 CGM.getItaniumVTableContext().getVTableLayout(RD); 415 416 for (const auto &VtableComponent : VtableLayout.vtable_components()) { 417 if (VtableComponent.isRTTIKind()) { 418 const CXXRecordDecl *RTTIDecl = VtableComponent.getRTTIDecl(); 419 if (RTTIDecl->getVisibility() == Visibility::HiddenVisibility) 420 return true; 421 } else if (VtableComponent.isUsedFunctionPointerKind()) { 422 const CXXMethodDecl *Method = VtableComponent.getFunctionDecl(); 423 if (Method->getVisibility() == Visibility::HiddenVisibility && 424 !Method->isDefined()) 425 return true; 426 } 427 } 428 return false; 429 } 430 }; 431 432 class ARMCXXABI : public ItaniumCXXABI { 433 public: 434 ARMCXXABI(CodeGen::CodeGenModule &CGM) : 435 ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true, 436 /* UseARMGuardVarABI = */ true) {} 437 438 bool HasThisReturn(GlobalDecl GD) const override { 439 return (isa<CXXConstructorDecl>(GD.getDecl()) || ( 440 isa<CXXDestructorDecl>(GD.getDecl()) && 441 GD.getDtorType() != Dtor_Deleting)); 442 } 443 444 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV, 445 QualType ResTy) override; 446 447 CharUnits getArrayCookieSizeImpl(QualType elementType) override; 448 Address InitializeArrayCookie(CodeGenFunction &CGF, 449 Address NewPtr, 450 llvm::Value *NumElements, 451 const CXXNewExpr *expr, 452 QualType ElementType) override; 453 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, Address allocPtr, 454 CharUnits cookieSize) override; 455 }; 456 457 class iOS64CXXABI : public ARMCXXABI { 458 public: 459 iOS64CXXABI(CodeGen::CodeGenModule &CGM) : ARMCXXABI(CGM) { 460 Use32BitVTableOffsetABI = true; 461 } 462 463 // ARM64 libraries are prepared for non-unique RTTI. 464 bool shouldRTTIBeUnique() const override { return false; } 465 }; 466 467 class WebAssemblyCXXABI final : public ItaniumCXXABI { 468 public: 469 explicit WebAssemblyCXXABI(CodeGen::CodeGenModule &CGM) 470 : ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true, 471 /*UseARMGuardVarABI=*/true) {} 472 473 private: 474 bool HasThisReturn(GlobalDecl GD) const override { 475 return isa<CXXConstructorDecl>(GD.getDecl()) || 476 (isa<CXXDestructorDecl>(GD.getDecl()) && 477 GD.getDtorType() != Dtor_Deleting); 478 } 479 bool canCallMismatchedFunctionType() const override { return false; } 480 }; 481 } 482 483 CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) { 484 switch (CGM.getTarget().getCXXABI().getKind()) { 485 // For IR-generation purposes, there's no significant difference 486 // between the ARM and iOS ABIs. 487 case TargetCXXABI::GenericARM: 488 case TargetCXXABI::iOS: 489 case TargetCXXABI::WatchOS: 490 return new ARMCXXABI(CGM); 491 492 case TargetCXXABI::iOS64: 493 return new iOS64CXXABI(CGM); 494 495 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't 496 // include the other 32-bit ARM oddities: constructor/destructor return values 497 // and array cookies. 498 case TargetCXXABI::GenericAArch64: 499 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true, 500 /* UseARMGuardVarABI = */ true); 501 502 case TargetCXXABI::GenericMIPS: 503 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true); 504 505 case TargetCXXABI::WebAssembly: 506 return new WebAssemblyCXXABI(CGM); 507 508 case TargetCXXABI::GenericItanium: 509 if (CGM.getContext().getTargetInfo().getTriple().getArch() 510 == llvm::Triple::le32) { 511 // For PNaCl, use ARM-style method pointers so that PNaCl code 512 // does not assume anything about the alignment of function 513 // pointers. 514 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true, 515 /* UseARMGuardVarABI = */ false); 516 } 517 return new ItaniumCXXABI(CGM); 518 519 case TargetCXXABI::Microsoft: 520 llvm_unreachable("Microsoft ABI is not Itanium-based"); 521 } 522 llvm_unreachable("bad ABI kind"); 523 } 524 525 llvm::Type * 526 ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) { 527 if (MPT->isMemberDataPointer()) 528 return CGM.PtrDiffTy; 529 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy); 530 } 531 532 /// In the Itanium and ARM ABIs, method pointers have the form: 533 /// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr; 534 /// 535 /// In the Itanium ABI: 536 /// - method pointers are virtual if (memptr.ptr & 1) is nonzero 537 /// - the this-adjustment is (memptr.adj) 538 /// - the virtual offset is (memptr.ptr - 1) 539 /// 540 /// In the ARM ABI: 541 /// - method pointers are virtual if (memptr.adj & 1) is nonzero 542 /// - the this-adjustment is (memptr.adj >> 1) 543 /// - the virtual offset is (memptr.ptr) 544 /// ARM uses 'adj' for the virtual flag because Thumb functions 545 /// may be only single-byte aligned. 546 /// 547 /// If the member is virtual, the adjusted 'this' pointer points 548 /// to a vtable pointer from which the virtual offset is applied. 549 /// 550 /// If the member is non-virtual, memptr.ptr is the address of 551 /// the function to call. 552 CGCallee ItaniumCXXABI::EmitLoadOfMemberFunctionPointer( 553 CodeGenFunction &CGF, const Expr *E, Address ThisAddr, 554 llvm::Value *&ThisPtrForCall, 555 llvm::Value *MemFnPtr, const MemberPointerType *MPT) { 556 CGBuilderTy &Builder = CGF.Builder; 557 558 const FunctionProtoType *FPT = 559 MPT->getPointeeType()->getAs<FunctionProtoType>(); 560 const CXXRecordDecl *RD = 561 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl()); 562 563 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType( 564 CGM.getTypes().arrangeCXXMethodType(RD, FPT, /*FD=*/nullptr)); 565 566 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1); 567 568 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual"); 569 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual"); 570 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end"); 571 572 // Extract memptr.adj, which is in the second field. 573 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj"); 574 575 // Compute the true adjustment. 576 llvm::Value *Adj = RawAdj; 577 if (UseARMMethodPtrABI) 578 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted"); 579 580 // Apply the adjustment and cast back to the original struct type 581 // for consistency. 582 llvm::Value *This = ThisAddr.getPointer(); 583 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy()); 584 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj); 585 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted"); 586 ThisPtrForCall = This; 587 588 // Load the function pointer. 589 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr"); 590 591 // If the LSB in the function pointer is 1, the function pointer points to 592 // a virtual function. 593 llvm::Value *IsVirtual; 594 if (UseARMMethodPtrABI) 595 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1); 596 else 597 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1); 598 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual"); 599 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual); 600 601 // In the virtual path, the adjustment left 'This' pointing to the 602 // vtable of the correct base subobject. The "function pointer" is an 603 // offset within the vtable (+1 for the virtual flag on non-ARM). 604 CGF.EmitBlock(FnVirtual); 605 606 // Cast the adjusted this to a pointer to vtable pointer and load. 607 llvm::Type *VTableTy = Builder.getInt8PtrTy(); 608 CharUnits VTablePtrAlign = 609 CGF.CGM.getDynamicOffsetAlignment(ThisAddr.getAlignment(), RD, 610 CGF.getPointerAlign()); 611 llvm::Value *VTable = 612 CGF.GetVTablePtr(Address(This, VTablePtrAlign), VTableTy, RD); 613 614 // Apply the offset. 615 // On ARM64, to reserve extra space in virtual member function pointers, 616 // we only pay attention to the low 32 bits of the offset. 617 llvm::Value *VTableOffset = FnAsInt; 618 if (!UseARMMethodPtrABI) 619 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1); 620 if (Use32BitVTableOffsetABI) { 621 VTableOffset = Builder.CreateTrunc(VTableOffset, CGF.Int32Ty); 622 VTableOffset = Builder.CreateZExt(VTableOffset, CGM.PtrDiffTy); 623 } 624 VTable = Builder.CreateGEP(VTable, VTableOffset); 625 626 // Load the virtual function to call. 627 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo()); 628 llvm::Value *VirtualFn = 629 Builder.CreateAlignedLoad(VTable, CGF.getPointerAlign(), 630 "memptr.virtualfn"); 631 CGF.EmitBranch(FnEnd); 632 633 // In the non-virtual path, the function pointer is actually a 634 // function pointer. 635 CGF.EmitBlock(FnNonVirtual); 636 llvm::Value *NonVirtualFn = 637 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn"); 638 639 // We're done. 640 CGF.EmitBlock(FnEnd); 641 llvm::PHINode *CalleePtr = Builder.CreatePHI(FTy->getPointerTo(), 2); 642 CalleePtr->addIncoming(VirtualFn, FnVirtual); 643 CalleePtr->addIncoming(NonVirtualFn, FnNonVirtual); 644 645 CGCallee Callee(FPT, CalleePtr); 646 return Callee; 647 } 648 649 /// Compute an l-value by applying the given pointer-to-member to a 650 /// base object. 651 llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress( 652 CodeGenFunction &CGF, const Expr *E, Address Base, llvm::Value *MemPtr, 653 const MemberPointerType *MPT) { 654 assert(MemPtr->getType() == CGM.PtrDiffTy); 655 656 CGBuilderTy &Builder = CGF.Builder; 657 658 // Cast to char*. 659 Base = Builder.CreateElementBitCast(Base, CGF.Int8Ty); 660 661 // Apply the offset, which we assume is non-null. 662 llvm::Value *Addr = 663 Builder.CreateInBoundsGEP(Base.getPointer(), MemPtr, "memptr.offset"); 664 665 // Cast the address to the appropriate pointer type, adopting the 666 // address space of the base pointer. 667 llvm::Type *PType = CGF.ConvertTypeForMem(MPT->getPointeeType()) 668 ->getPointerTo(Base.getAddressSpace()); 669 return Builder.CreateBitCast(Addr, PType); 670 } 671 672 /// Perform a bitcast, derived-to-base, or base-to-derived member pointer 673 /// conversion. 674 /// 675 /// Bitcast conversions are always a no-op under Itanium. 676 /// 677 /// Obligatory offset/adjustment diagram: 678 /// <-- offset --> <-- adjustment --> 679 /// |--------------------------|----------------------|--------------------| 680 /// ^Derived address point ^Base address point ^Member address point 681 /// 682 /// So when converting a base member pointer to a derived member pointer, 683 /// we add the offset to the adjustment because the address point has 684 /// decreased; and conversely, when converting a derived MP to a base MP 685 /// we subtract the offset from the adjustment because the address point 686 /// has increased. 687 /// 688 /// The standard forbids (at compile time) conversion to and from 689 /// virtual bases, which is why we don't have to consider them here. 690 /// 691 /// The standard forbids (at run time) casting a derived MP to a base 692 /// MP when the derived MP does not point to a member of the base. 693 /// This is why -1 is a reasonable choice for null data member 694 /// pointers. 695 llvm::Value * 696 ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF, 697 const CastExpr *E, 698 llvm::Value *src) { 699 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer || 700 E->getCastKind() == CK_BaseToDerivedMemberPointer || 701 E->getCastKind() == CK_ReinterpretMemberPointer); 702 703 // Under Itanium, reinterprets don't require any additional processing. 704 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src; 705 706 // Use constant emission if we can. 707 if (isa<llvm::Constant>(src)) 708 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src)); 709 710 llvm::Constant *adj = getMemberPointerAdjustment(E); 711 if (!adj) return src; 712 713 CGBuilderTy &Builder = CGF.Builder; 714 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer); 715 716 const MemberPointerType *destTy = 717 E->getType()->castAs<MemberPointerType>(); 718 719 // For member data pointers, this is just a matter of adding the 720 // offset if the source is non-null. 721 if (destTy->isMemberDataPointer()) { 722 llvm::Value *dst; 723 if (isDerivedToBase) 724 dst = Builder.CreateNSWSub(src, adj, "adj"); 725 else 726 dst = Builder.CreateNSWAdd(src, adj, "adj"); 727 728 // Null check. 729 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType()); 730 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull"); 731 return Builder.CreateSelect(isNull, src, dst); 732 } 733 734 // The this-adjustment is left-shifted by 1 on ARM. 735 if (UseARMMethodPtrABI) { 736 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue(); 737 offset <<= 1; 738 adj = llvm::ConstantInt::get(adj->getType(), offset); 739 } 740 741 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj"); 742 llvm::Value *dstAdj; 743 if (isDerivedToBase) 744 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj"); 745 else 746 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj"); 747 748 return Builder.CreateInsertValue(src, dstAdj, 1); 749 } 750 751 llvm::Constant * 752 ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E, 753 llvm::Constant *src) { 754 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer || 755 E->getCastKind() == CK_BaseToDerivedMemberPointer || 756 E->getCastKind() == CK_ReinterpretMemberPointer); 757 758 // Under Itanium, reinterprets don't require any additional processing. 759 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src; 760 761 // If the adjustment is trivial, we don't need to do anything. 762 llvm::Constant *adj = getMemberPointerAdjustment(E); 763 if (!adj) return src; 764 765 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer); 766 767 const MemberPointerType *destTy = 768 E->getType()->castAs<MemberPointerType>(); 769 770 // For member data pointers, this is just a matter of adding the 771 // offset if the source is non-null. 772 if (destTy->isMemberDataPointer()) { 773 // null maps to null. 774 if (src->isAllOnesValue()) return src; 775 776 if (isDerivedToBase) 777 return llvm::ConstantExpr::getNSWSub(src, adj); 778 else 779 return llvm::ConstantExpr::getNSWAdd(src, adj); 780 } 781 782 // The this-adjustment is left-shifted by 1 on ARM. 783 if (UseARMMethodPtrABI) { 784 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue(); 785 offset <<= 1; 786 adj = llvm::ConstantInt::get(adj->getType(), offset); 787 } 788 789 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1); 790 llvm::Constant *dstAdj; 791 if (isDerivedToBase) 792 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj); 793 else 794 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj); 795 796 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1); 797 } 798 799 llvm::Constant * 800 ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) { 801 // Itanium C++ ABI 2.3: 802 // A NULL pointer is represented as -1. 803 if (MPT->isMemberDataPointer()) 804 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true); 805 806 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0); 807 llvm::Constant *Values[2] = { Zero, Zero }; 808 return llvm::ConstantStruct::getAnon(Values); 809 } 810 811 llvm::Constant * 812 ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT, 813 CharUnits offset) { 814 // Itanium C++ ABI 2.3: 815 // A pointer to data member is an offset from the base address of 816 // the class object containing it, represented as a ptrdiff_t 817 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity()); 818 } 819 820 llvm::Constant * 821 ItaniumCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) { 822 return BuildMemberPointer(MD, CharUnits::Zero()); 823 } 824 825 llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD, 826 CharUnits ThisAdjustment) { 827 assert(MD->isInstance() && "Member function must not be static!"); 828 MD = MD->getCanonicalDecl(); 829 830 CodeGenTypes &Types = CGM.getTypes(); 831 832 // Get the function pointer (or index if this is a virtual function). 833 llvm::Constant *MemPtr[2]; 834 if (MD->isVirtual()) { 835 uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD); 836 837 const ASTContext &Context = getContext(); 838 CharUnits PointerWidth = 839 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0)); 840 uint64_t VTableOffset = (Index * PointerWidth.getQuantity()); 841 842 if (UseARMMethodPtrABI) { 843 // ARM C++ ABI 3.2.1: 844 // This ABI specifies that adj contains twice the this 845 // adjustment, plus 1 if the member function is virtual. The 846 // least significant bit of adj then makes exactly the same 847 // discrimination as the least significant bit of ptr does for 848 // Itanium. 849 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset); 850 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy, 851 2 * ThisAdjustment.getQuantity() + 1); 852 } else { 853 // Itanium C++ ABI 2.3: 854 // For a virtual function, [the pointer field] is 1 plus the 855 // virtual table offset (in bytes) of the function, 856 // represented as a ptrdiff_t. 857 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1); 858 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy, 859 ThisAdjustment.getQuantity()); 860 } 861 } else { 862 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 863 llvm::Type *Ty; 864 // Check whether the function has a computable LLVM signature. 865 if (Types.isFuncTypeConvertible(FPT)) { 866 // The function has a computable LLVM signature; use the correct type. 867 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD)); 868 } else { 869 // Use an arbitrary non-function type to tell GetAddrOfFunction that the 870 // function type is incomplete. 871 Ty = CGM.PtrDiffTy; 872 } 873 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty); 874 875 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy); 876 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy, 877 (UseARMMethodPtrABI ? 2 : 1) * 878 ThisAdjustment.getQuantity()); 879 } 880 881 return llvm::ConstantStruct::getAnon(MemPtr); 882 } 883 884 llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP, 885 QualType MPType) { 886 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>(); 887 const ValueDecl *MPD = MP.getMemberPointerDecl(); 888 if (!MPD) 889 return EmitNullMemberPointer(MPT); 890 891 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP); 892 893 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD)) 894 return BuildMemberPointer(MD, ThisAdjustment); 895 896 CharUnits FieldOffset = 897 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD)); 898 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset); 899 } 900 901 /// The comparison algorithm is pretty easy: the member pointers are 902 /// the same if they're either bitwise identical *or* both null. 903 /// 904 /// ARM is different here only because null-ness is more complicated. 905 llvm::Value * 906 ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF, 907 llvm::Value *L, 908 llvm::Value *R, 909 const MemberPointerType *MPT, 910 bool Inequality) { 911 CGBuilderTy &Builder = CGF.Builder; 912 913 llvm::ICmpInst::Predicate Eq; 914 llvm::Instruction::BinaryOps And, Or; 915 if (Inequality) { 916 Eq = llvm::ICmpInst::ICMP_NE; 917 And = llvm::Instruction::Or; 918 Or = llvm::Instruction::And; 919 } else { 920 Eq = llvm::ICmpInst::ICMP_EQ; 921 And = llvm::Instruction::And; 922 Or = llvm::Instruction::Or; 923 } 924 925 // Member data pointers are easy because there's a unique null 926 // value, so it just comes down to bitwise equality. 927 if (MPT->isMemberDataPointer()) 928 return Builder.CreateICmp(Eq, L, R); 929 930 // For member function pointers, the tautologies are more complex. 931 // The Itanium tautology is: 932 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj)) 933 // The ARM tautology is: 934 // (L == R) <==> (L.ptr == R.ptr && 935 // (L.adj == R.adj || 936 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0))) 937 // The inequality tautologies have exactly the same structure, except 938 // applying De Morgan's laws. 939 940 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr"); 941 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr"); 942 943 // This condition tests whether L.ptr == R.ptr. This must always be 944 // true for equality to hold. 945 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr"); 946 947 // This condition, together with the assumption that L.ptr == R.ptr, 948 // tests whether the pointers are both null. ARM imposes an extra 949 // condition. 950 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType()); 951 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null"); 952 953 // This condition tests whether L.adj == R.adj. If this isn't 954 // true, the pointers are unequal unless they're both null. 955 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj"); 956 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj"); 957 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj"); 958 959 // Null member function pointers on ARM clear the low bit of Adj, 960 // so the zero condition has to check that neither low bit is set. 961 if (UseARMMethodPtrABI) { 962 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1); 963 964 // Compute (l.adj | r.adj) & 1 and test it against zero. 965 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj"); 966 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One); 967 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero, 968 "cmp.or.adj"); 969 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero); 970 } 971 972 // Tie together all our conditions. 973 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq); 974 Result = Builder.CreateBinOp(And, PtrEq, Result, 975 Inequality ? "memptr.ne" : "memptr.eq"); 976 return Result; 977 } 978 979 llvm::Value * 980 ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF, 981 llvm::Value *MemPtr, 982 const MemberPointerType *MPT) { 983 CGBuilderTy &Builder = CGF.Builder; 984 985 /// For member data pointers, this is just a check against -1. 986 if (MPT->isMemberDataPointer()) { 987 assert(MemPtr->getType() == CGM.PtrDiffTy); 988 llvm::Value *NegativeOne = 989 llvm::Constant::getAllOnesValue(MemPtr->getType()); 990 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool"); 991 } 992 993 // In Itanium, a member function pointer is not null if 'ptr' is not null. 994 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr"); 995 996 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0); 997 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool"); 998 999 // On ARM, a member function pointer is also non-null if the low bit of 'adj' 1000 // (the virtual bit) is set. 1001 if (UseARMMethodPtrABI) { 1002 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1); 1003 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj"); 1004 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit"); 1005 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero, 1006 "memptr.isvirtual"); 1007 Result = Builder.CreateOr(Result, IsVirtual); 1008 } 1009 1010 return Result; 1011 } 1012 1013 bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const { 1014 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl(); 1015 if (!RD) 1016 return false; 1017 1018 // If C++ prohibits us from making a copy, return by address. 1019 if (passClassIndirect(RD)) { 1020 auto Align = CGM.getContext().getTypeAlignInChars(FI.getReturnType()); 1021 FI.getReturnInfo() = ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 1022 return true; 1023 } 1024 return false; 1025 } 1026 1027 /// The Itanium ABI requires non-zero initialization only for data 1028 /// member pointers, for which '0' is a valid offset. 1029 bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) { 1030 return MPT->isMemberFunctionPointer(); 1031 } 1032 1033 /// The Itanium ABI always places an offset to the complete object 1034 /// at entry -2 in the vtable. 1035 void ItaniumCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF, 1036 const CXXDeleteExpr *DE, 1037 Address Ptr, 1038 QualType ElementType, 1039 const CXXDestructorDecl *Dtor) { 1040 bool UseGlobalDelete = DE->isGlobalDelete(); 1041 if (UseGlobalDelete) { 1042 // Derive the complete-object pointer, which is what we need 1043 // to pass to the deallocation function. 1044 1045 // Grab the vtable pointer as an intptr_t*. 1046 auto *ClassDecl = 1047 cast<CXXRecordDecl>(ElementType->getAs<RecordType>()->getDecl()); 1048 llvm::Value *VTable = 1049 CGF.GetVTablePtr(Ptr, CGF.IntPtrTy->getPointerTo(), ClassDecl); 1050 1051 // Track back to entry -2 and pull out the offset there. 1052 llvm::Value *OffsetPtr = CGF.Builder.CreateConstInBoundsGEP1_64( 1053 VTable, -2, "complete-offset.ptr"); 1054 llvm::Value *Offset = 1055 CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign()); 1056 1057 // Apply the offset. 1058 llvm::Value *CompletePtr = 1059 CGF.Builder.CreateBitCast(Ptr.getPointer(), CGF.Int8PtrTy); 1060 CompletePtr = CGF.Builder.CreateInBoundsGEP(CompletePtr, Offset); 1061 1062 // If we're supposed to call the global delete, make sure we do so 1063 // even if the destructor throws. 1064 CGF.pushCallObjectDeleteCleanup(DE->getOperatorDelete(), CompletePtr, 1065 ElementType); 1066 } 1067 1068 // FIXME: Provide a source location here even though there's no 1069 // CXXMemberCallExpr for dtor call. 1070 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting; 1071 EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, /*CE=*/nullptr); 1072 1073 if (UseGlobalDelete) 1074 CGF.PopCleanupBlock(); 1075 } 1076 1077 void ItaniumCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) { 1078 // void __cxa_rethrow(); 1079 1080 llvm::FunctionType *FTy = 1081 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false); 1082 1083 llvm::Constant *Fn = CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow"); 1084 1085 if (isNoReturn) 1086 CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, None); 1087 else 1088 CGF.EmitRuntimeCallOrInvoke(Fn); 1089 } 1090 1091 static llvm::Constant *getAllocateExceptionFn(CodeGenModule &CGM) { 1092 // void *__cxa_allocate_exception(size_t thrown_size); 1093 1094 llvm::FunctionType *FTy = 1095 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.SizeTy, /*IsVarArgs=*/false); 1096 1097 return CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception"); 1098 } 1099 1100 static llvm::Constant *getThrowFn(CodeGenModule &CGM) { 1101 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo, 1102 // void (*dest) (void *)); 1103 1104 llvm::Type *Args[3] = { CGM.Int8PtrTy, CGM.Int8PtrTy, CGM.Int8PtrTy }; 1105 llvm::FunctionType *FTy = 1106 llvm::FunctionType::get(CGM.VoidTy, Args, /*IsVarArgs=*/false); 1107 1108 return CGM.CreateRuntimeFunction(FTy, "__cxa_throw"); 1109 } 1110 1111 void ItaniumCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) { 1112 QualType ThrowType = E->getSubExpr()->getType(); 1113 // Now allocate the exception object. 1114 llvm::Type *SizeTy = CGF.ConvertType(getContext().getSizeType()); 1115 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity(); 1116 1117 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(CGM); 1118 llvm::CallInst *ExceptionPtr = CGF.EmitNounwindRuntimeCall( 1119 AllocExceptionFn, llvm::ConstantInt::get(SizeTy, TypeSize), "exception"); 1120 1121 CharUnits ExnAlign = getAlignmentOfExnObject(); 1122 CGF.EmitAnyExprToExn(E->getSubExpr(), Address(ExceptionPtr, ExnAlign)); 1123 1124 // Now throw the exception. 1125 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType, 1126 /*ForEH=*/true); 1127 1128 // The address of the destructor. If the exception type has a 1129 // trivial destructor (or isn't a record), we just pass null. 1130 llvm::Constant *Dtor = nullptr; 1131 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) { 1132 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl()); 1133 if (!Record->hasTrivialDestructor()) { 1134 CXXDestructorDecl *DtorD = Record->getDestructor(); 1135 Dtor = CGM.getAddrOfCXXStructor(DtorD, StructorType::Complete); 1136 Dtor = llvm::ConstantExpr::getBitCast(Dtor, CGM.Int8PtrTy); 1137 } 1138 } 1139 if (!Dtor) Dtor = llvm::Constant::getNullValue(CGM.Int8PtrTy); 1140 1141 llvm::Value *args[] = { ExceptionPtr, TypeInfo, Dtor }; 1142 CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(CGM), args); 1143 } 1144 1145 static llvm::Constant *getItaniumDynamicCastFn(CodeGenFunction &CGF) { 1146 // void *__dynamic_cast(const void *sub, 1147 // const abi::__class_type_info *src, 1148 // const abi::__class_type_info *dst, 1149 // std::ptrdiff_t src2dst_offset); 1150 1151 llvm::Type *Int8PtrTy = CGF.Int8PtrTy; 1152 llvm::Type *PtrDiffTy = 1153 CGF.ConvertType(CGF.getContext().getPointerDiffType()); 1154 1155 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy }; 1156 1157 llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false); 1158 1159 // Mark the function as nounwind readonly. 1160 llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind, 1161 llvm::Attribute::ReadOnly }; 1162 llvm::AttributeList Attrs = llvm::AttributeList::get( 1163 CGF.getLLVMContext(), llvm::AttributeList::FunctionIndex, FuncAttrs); 1164 1165 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs); 1166 } 1167 1168 static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) { 1169 // void __cxa_bad_cast(); 1170 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false); 1171 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast"); 1172 } 1173 1174 /// Compute the src2dst_offset hint as described in the 1175 /// Itanium C++ ABI [2.9.7] 1176 static CharUnits computeOffsetHint(ASTContext &Context, 1177 const CXXRecordDecl *Src, 1178 const CXXRecordDecl *Dst) { 1179 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1180 /*DetectVirtual=*/false); 1181 1182 // If Dst is not derived from Src we can skip the whole computation below and 1183 // return that Src is not a public base of Dst. Record all inheritance paths. 1184 if (!Dst->isDerivedFrom(Src, Paths)) 1185 return CharUnits::fromQuantity(-2ULL); 1186 1187 unsigned NumPublicPaths = 0; 1188 CharUnits Offset; 1189 1190 // Now walk all possible inheritance paths. 1191 for (const CXXBasePath &Path : Paths) { 1192 if (Path.Access != AS_public) // Ignore non-public inheritance. 1193 continue; 1194 1195 ++NumPublicPaths; 1196 1197 for (const CXXBasePathElement &PathElement : Path) { 1198 // If the path contains a virtual base class we can't give any hint. 1199 // -1: no hint. 1200 if (PathElement.Base->isVirtual()) 1201 return CharUnits::fromQuantity(-1ULL); 1202 1203 if (NumPublicPaths > 1) // Won't use offsets, skip computation. 1204 continue; 1205 1206 // Accumulate the base class offsets. 1207 const ASTRecordLayout &L = Context.getASTRecordLayout(PathElement.Class); 1208 Offset += L.getBaseClassOffset( 1209 PathElement.Base->getType()->getAsCXXRecordDecl()); 1210 } 1211 } 1212 1213 // -2: Src is not a public base of Dst. 1214 if (NumPublicPaths == 0) 1215 return CharUnits::fromQuantity(-2ULL); 1216 1217 // -3: Src is a multiple public base type but never a virtual base type. 1218 if (NumPublicPaths > 1) 1219 return CharUnits::fromQuantity(-3ULL); 1220 1221 // Otherwise, the Src type is a unique public nonvirtual base type of Dst. 1222 // Return the offset of Src from the origin of Dst. 1223 return Offset; 1224 } 1225 1226 static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) { 1227 // void __cxa_bad_typeid(); 1228 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false); 1229 1230 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid"); 1231 } 1232 1233 bool ItaniumCXXABI::shouldTypeidBeNullChecked(bool IsDeref, 1234 QualType SrcRecordTy) { 1235 return IsDeref; 1236 } 1237 1238 void ItaniumCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) { 1239 llvm::Value *Fn = getBadTypeidFn(CGF); 1240 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn(); 1241 CGF.Builder.CreateUnreachable(); 1242 } 1243 1244 llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF, 1245 QualType SrcRecordTy, 1246 Address ThisPtr, 1247 llvm::Type *StdTypeInfoPtrTy) { 1248 auto *ClassDecl = 1249 cast<CXXRecordDecl>(SrcRecordTy->getAs<RecordType>()->getDecl()); 1250 llvm::Value *Value = 1251 CGF.GetVTablePtr(ThisPtr, StdTypeInfoPtrTy->getPointerTo(), ClassDecl); 1252 1253 // Load the type info. 1254 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL); 1255 return CGF.Builder.CreateAlignedLoad(Value, CGF.getPointerAlign()); 1256 } 1257 1258 bool ItaniumCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr, 1259 QualType SrcRecordTy) { 1260 return SrcIsPtr; 1261 } 1262 1263 llvm::Value *ItaniumCXXABI::EmitDynamicCastCall( 1264 CodeGenFunction &CGF, Address ThisAddr, QualType SrcRecordTy, 1265 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) { 1266 llvm::Type *PtrDiffLTy = 1267 CGF.ConvertType(CGF.getContext().getPointerDiffType()); 1268 llvm::Type *DestLTy = CGF.ConvertType(DestTy); 1269 1270 llvm::Value *SrcRTTI = 1271 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType()); 1272 llvm::Value *DestRTTI = 1273 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType()); 1274 1275 // Compute the offset hint. 1276 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl(); 1277 const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl(); 1278 llvm::Value *OffsetHint = llvm::ConstantInt::get( 1279 PtrDiffLTy, 1280 computeOffsetHint(CGF.getContext(), SrcDecl, DestDecl).getQuantity()); 1281 1282 // Emit the call to __dynamic_cast. 1283 llvm::Value *Value = ThisAddr.getPointer(); 1284 Value = CGF.EmitCastToVoidPtr(Value); 1285 1286 llvm::Value *args[] = {Value, SrcRTTI, DestRTTI, OffsetHint}; 1287 Value = CGF.EmitNounwindRuntimeCall(getItaniumDynamicCastFn(CGF), args); 1288 Value = CGF.Builder.CreateBitCast(Value, DestLTy); 1289 1290 /// C++ [expr.dynamic.cast]p9: 1291 /// A failed cast to reference type throws std::bad_cast 1292 if (DestTy->isReferenceType()) { 1293 llvm::BasicBlock *BadCastBlock = 1294 CGF.createBasicBlock("dynamic_cast.bad_cast"); 1295 1296 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value); 1297 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd); 1298 1299 CGF.EmitBlock(BadCastBlock); 1300 EmitBadCastCall(CGF); 1301 } 1302 1303 return Value; 1304 } 1305 1306 llvm::Value *ItaniumCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF, 1307 Address ThisAddr, 1308 QualType SrcRecordTy, 1309 QualType DestTy) { 1310 llvm::Type *PtrDiffLTy = 1311 CGF.ConvertType(CGF.getContext().getPointerDiffType()); 1312 llvm::Type *DestLTy = CGF.ConvertType(DestTy); 1313 1314 auto *ClassDecl = 1315 cast<CXXRecordDecl>(SrcRecordTy->getAs<RecordType>()->getDecl()); 1316 // Get the vtable pointer. 1317 llvm::Value *VTable = CGF.GetVTablePtr(ThisAddr, PtrDiffLTy->getPointerTo(), 1318 ClassDecl); 1319 1320 // Get the offset-to-top from the vtable. 1321 llvm::Value *OffsetToTop = 1322 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL); 1323 OffsetToTop = 1324 CGF.Builder.CreateAlignedLoad(OffsetToTop, CGF.getPointerAlign(), 1325 "offset.to.top"); 1326 1327 // Finally, add the offset to the pointer. 1328 llvm::Value *Value = ThisAddr.getPointer(); 1329 Value = CGF.EmitCastToVoidPtr(Value); 1330 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop); 1331 1332 return CGF.Builder.CreateBitCast(Value, DestLTy); 1333 } 1334 1335 bool ItaniumCXXABI::EmitBadCastCall(CodeGenFunction &CGF) { 1336 llvm::Value *Fn = getBadCastFn(CGF); 1337 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn(); 1338 CGF.Builder.CreateUnreachable(); 1339 return true; 1340 } 1341 1342 llvm::Value * 1343 ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF, 1344 Address This, 1345 const CXXRecordDecl *ClassDecl, 1346 const CXXRecordDecl *BaseClassDecl) { 1347 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy, ClassDecl); 1348 CharUnits VBaseOffsetOffset = 1349 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl, 1350 BaseClassDecl); 1351 1352 llvm::Value *VBaseOffsetPtr = 1353 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(), 1354 "vbase.offset.ptr"); 1355 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr, 1356 CGM.PtrDiffTy->getPointerTo()); 1357 1358 llvm::Value *VBaseOffset = 1359 CGF.Builder.CreateAlignedLoad(VBaseOffsetPtr, CGF.getPointerAlign(), 1360 "vbase.offset"); 1361 1362 return VBaseOffset; 1363 } 1364 1365 void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) { 1366 // Just make sure we're in sync with TargetCXXABI. 1367 assert(CGM.getTarget().getCXXABI().hasConstructorVariants()); 1368 1369 // The constructor used for constructing this as a base class; 1370 // ignores virtual bases. 1371 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base)); 1372 1373 // The constructor used for constructing this as a complete class; 1374 // constructs the virtual bases, then calls the base constructor. 1375 if (!D->getParent()->isAbstract()) { 1376 // We don't need to emit the complete ctor if the class is abstract. 1377 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete)); 1378 } 1379 } 1380 1381 CGCXXABI::AddedStructorArgs 1382 ItaniumCXXABI::buildStructorSignature(const CXXMethodDecl *MD, StructorType T, 1383 SmallVectorImpl<CanQualType> &ArgTys) { 1384 ASTContext &Context = getContext(); 1385 1386 // All parameters are already in place except VTT, which goes after 'this'. 1387 // These are Clang types, so we don't need to worry about sret yet. 1388 1389 // Check if we need to add a VTT parameter (which has type void **). 1390 if (T == StructorType::Base && MD->getParent()->getNumVBases() != 0) { 1391 ArgTys.insert(ArgTys.begin() + 1, 1392 Context.getPointerType(Context.VoidPtrTy)); 1393 return AddedStructorArgs::prefix(1); 1394 } 1395 return AddedStructorArgs{}; 1396 } 1397 1398 void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) { 1399 // The destructor used for destructing this as a base class; ignores 1400 // virtual bases. 1401 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base)); 1402 1403 // The destructor used for destructing this as a most-derived class; 1404 // call the base destructor and then destructs any virtual bases. 1405 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete)); 1406 1407 // The destructor in a virtual table is always a 'deleting' 1408 // destructor, which calls the complete destructor and then uses the 1409 // appropriate operator delete. 1410 if (D->isVirtual()) 1411 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting)); 1412 } 1413 1414 void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF, 1415 QualType &ResTy, 1416 FunctionArgList &Params) { 1417 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl()); 1418 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)); 1419 1420 // Check if we need a VTT parameter as well. 1421 if (NeedsVTTParameter(CGF.CurGD)) { 1422 ASTContext &Context = getContext(); 1423 1424 // FIXME: avoid the fake decl 1425 QualType T = Context.getPointerType(Context.VoidPtrTy); 1426 auto *VTTDecl = ImplicitParamDecl::Create( 1427 Context, /*DC=*/nullptr, MD->getLocation(), &Context.Idents.get("vtt"), 1428 T, ImplicitParamDecl::CXXVTT); 1429 Params.insert(Params.begin() + 1, VTTDecl); 1430 getStructorImplicitParamDecl(CGF) = VTTDecl; 1431 } 1432 } 1433 1434 void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) { 1435 // Naked functions have no prolog. 1436 if (CGF.CurFuncDecl && CGF.CurFuncDecl->hasAttr<NakedAttr>()) 1437 return; 1438 1439 /// Initialize the 'this' slot. In the Itanium C++ ABI, no prologue 1440 /// adjustments are required, because they are all handled by thunks. 1441 setCXXABIThisValue(CGF, loadIncomingCXXThis(CGF)); 1442 1443 /// Initialize the 'vtt' slot if needed. 1444 if (getStructorImplicitParamDecl(CGF)) { 1445 getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad( 1446 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt"); 1447 } 1448 1449 /// If this is a function that the ABI specifies returns 'this', initialize 1450 /// the return slot to 'this' at the start of the function. 1451 /// 1452 /// Unlike the setting of return types, this is done within the ABI 1453 /// implementation instead of by clients of CGCXXABI because: 1454 /// 1) getThisValue is currently protected 1455 /// 2) in theory, an ABI could implement 'this' returns some other way; 1456 /// HasThisReturn only specifies a contract, not the implementation 1457 if (HasThisReturn(CGF.CurGD)) 1458 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue); 1459 } 1460 1461 CGCXXABI::AddedStructorArgs ItaniumCXXABI::addImplicitConstructorArgs( 1462 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type, 1463 bool ForVirtualBase, bool Delegating, CallArgList &Args) { 1464 if (!NeedsVTTParameter(GlobalDecl(D, Type))) 1465 return AddedStructorArgs{}; 1466 1467 // Insert the implicit 'vtt' argument as the second argument. 1468 llvm::Value *VTT = 1469 CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating); 1470 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy); 1471 Args.insert(Args.begin() + 1, CallArg(RValue::get(VTT), VTTTy)); 1472 return AddedStructorArgs::prefix(1); // Added one arg. 1473 } 1474 1475 void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF, 1476 const CXXDestructorDecl *DD, 1477 CXXDtorType Type, bool ForVirtualBase, 1478 bool Delegating, Address This) { 1479 GlobalDecl GD(DD, Type); 1480 llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating); 1481 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy); 1482 1483 CGCallee Callee; 1484 if (getContext().getLangOpts().AppleKext && 1485 Type != Dtor_Base && DD->isVirtual()) 1486 Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent()); 1487 else 1488 Callee = 1489 CGCallee::forDirect(CGM.getAddrOfCXXStructor(DD, getFromDtorType(Type)), 1490 DD); 1491 1492 CGF.EmitCXXMemberOrOperatorCall(DD, Callee, ReturnValueSlot(), 1493 This.getPointer(), VTT, VTTTy, 1494 nullptr, nullptr); 1495 } 1496 1497 void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT, 1498 const CXXRecordDecl *RD) { 1499 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits()); 1500 if (VTable->hasInitializer()) 1501 return; 1502 1503 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext(); 1504 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD); 1505 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD); 1506 llvm::Constant *RTTI = 1507 CGM.GetAddrOfRTTIDescriptor(CGM.getContext().getTagDeclType(RD)); 1508 1509 // Create and set the initializer. 1510 ConstantInitBuilder Builder(CGM); 1511 auto Components = Builder.beginStruct(); 1512 CGVT.createVTableInitializer(Components, VTLayout, RTTI); 1513 Components.finishAndSetAsInitializer(VTable); 1514 1515 // Set the correct linkage. 1516 VTable->setLinkage(Linkage); 1517 1518 if (CGM.supportsCOMDAT() && VTable->isWeakForLinker()) 1519 VTable->setComdat(CGM.getModule().getOrInsertComdat(VTable->getName())); 1520 1521 // Set the right visibility. 1522 CGM.setGVProperties(VTable, RD); 1523 1524 // Use pointer alignment for the vtable. Otherwise we would align them based 1525 // on the size of the initializer which doesn't make sense as only single 1526 // values are read. 1527 unsigned PAlign = CGM.getTarget().getPointerAlign(0); 1528 VTable->setAlignment(getContext().toCharUnitsFromBits(PAlign).getQuantity()); 1529 1530 // If this is the magic class __cxxabiv1::__fundamental_type_info, 1531 // we will emit the typeinfo for the fundamental types. This is the 1532 // same behaviour as GCC. 1533 const DeclContext *DC = RD->getDeclContext(); 1534 if (RD->getIdentifier() && 1535 RD->getIdentifier()->isStr("__fundamental_type_info") && 1536 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() && 1537 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") && 1538 DC->getParent()->isTranslationUnit()) 1539 EmitFundamentalRTTIDescriptors(RD->hasAttr<DLLExportAttr>()); 1540 1541 if (!VTable->isDeclarationForLinker()) 1542 CGM.EmitVTableTypeMetadata(VTable, VTLayout); 1543 } 1544 1545 bool ItaniumCXXABI::isVirtualOffsetNeededForVTableField( 1546 CodeGenFunction &CGF, CodeGenFunction::VPtr Vptr) { 1547 if (Vptr.NearestVBase == nullptr) 1548 return false; 1549 return NeedsVTTParameter(CGF.CurGD); 1550 } 1551 1552 llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor( 1553 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base, 1554 const CXXRecordDecl *NearestVBase) { 1555 1556 if ((Base.getBase()->getNumVBases() || NearestVBase != nullptr) && 1557 NeedsVTTParameter(CGF.CurGD)) { 1558 return getVTableAddressPointInStructorWithVTT(CGF, VTableClass, Base, 1559 NearestVBase); 1560 } 1561 return getVTableAddressPoint(Base, VTableClass); 1562 } 1563 1564 llvm::Constant * 1565 ItaniumCXXABI::getVTableAddressPoint(BaseSubobject Base, 1566 const CXXRecordDecl *VTableClass) { 1567 llvm::GlobalValue *VTable = getAddrOfVTable(VTableClass, CharUnits()); 1568 1569 // Find the appropriate vtable within the vtable group, and the address point 1570 // within that vtable. 1571 VTableLayout::AddressPointLocation AddressPoint = 1572 CGM.getItaniumVTableContext() 1573 .getVTableLayout(VTableClass) 1574 .getAddressPoint(Base); 1575 llvm::Value *Indices[] = { 1576 llvm::ConstantInt::get(CGM.Int32Ty, 0), 1577 llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint.VTableIndex), 1578 llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint.AddressPointIndex), 1579 }; 1580 1581 return llvm::ConstantExpr::getGetElementPtr(VTable->getValueType(), VTable, 1582 Indices, /*InBounds=*/true, 1583 /*InRangeIndex=*/1); 1584 } 1585 1586 llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructorWithVTT( 1587 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base, 1588 const CXXRecordDecl *NearestVBase) { 1589 assert((Base.getBase()->getNumVBases() || NearestVBase != nullptr) && 1590 NeedsVTTParameter(CGF.CurGD) && "This class doesn't have VTT"); 1591 1592 // Get the secondary vpointer index. 1593 uint64_t VirtualPointerIndex = 1594 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base); 1595 1596 /// Load the VTT. 1597 llvm::Value *VTT = CGF.LoadCXXVTT(); 1598 if (VirtualPointerIndex) 1599 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex); 1600 1601 // And load the address point from the VTT. 1602 return CGF.Builder.CreateAlignedLoad(VTT, CGF.getPointerAlign()); 1603 } 1604 1605 llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr( 1606 BaseSubobject Base, const CXXRecordDecl *VTableClass) { 1607 return getVTableAddressPoint(Base, VTableClass); 1608 } 1609 1610 llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD, 1611 CharUnits VPtrOffset) { 1612 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets"); 1613 1614 llvm::GlobalVariable *&VTable = VTables[RD]; 1615 if (VTable) 1616 return VTable; 1617 1618 // Queue up this vtable for possible deferred emission. 1619 CGM.addDeferredVTable(RD); 1620 1621 SmallString<256> Name; 1622 llvm::raw_svector_ostream Out(Name); 1623 getMangleContext().mangleCXXVTable(RD, Out); 1624 1625 const VTableLayout &VTLayout = 1626 CGM.getItaniumVTableContext().getVTableLayout(RD); 1627 llvm::Type *VTableType = CGM.getVTables().getVTableType(VTLayout); 1628 1629 VTable = CGM.CreateOrReplaceCXXRuntimeVariable( 1630 Name, VTableType, llvm::GlobalValue::ExternalLinkage); 1631 VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 1632 1633 CGM.setGVProperties(VTable, RD); 1634 1635 return VTable; 1636 } 1637 1638 CGCallee ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF, 1639 GlobalDecl GD, 1640 Address This, 1641 llvm::Type *Ty, 1642 SourceLocation Loc) { 1643 GD = GD.getCanonicalDecl(); 1644 Ty = Ty->getPointerTo()->getPointerTo(); 1645 auto *MethodDecl = cast<CXXMethodDecl>(GD.getDecl()); 1646 llvm::Value *VTable = CGF.GetVTablePtr(This, Ty, MethodDecl->getParent()); 1647 1648 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD); 1649 llvm::Value *VFunc; 1650 if (CGF.ShouldEmitVTableTypeCheckedLoad(MethodDecl->getParent())) { 1651 VFunc = CGF.EmitVTableTypeCheckedLoad( 1652 MethodDecl->getParent(), VTable, 1653 VTableIndex * CGM.getContext().getTargetInfo().getPointerWidth(0) / 8); 1654 } else { 1655 CGF.EmitTypeMetadataCodeForVCall(MethodDecl->getParent(), VTable, Loc); 1656 1657 llvm::Value *VFuncPtr = 1658 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn"); 1659 auto *VFuncLoad = 1660 CGF.Builder.CreateAlignedLoad(VFuncPtr, CGF.getPointerAlign()); 1661 1662 // Add !invariant.load md to virtual function load to indicate that 1663 // function didn't change inside vtable. 1664 // It's safe to add it without -fstrict-vtable-pointers, but it would not 1665 // help in devirtualization because it will only matter if we will have 2 1666 // the same virtual function loads from the same vtable load, which won't 1667 // happen without enabled devirtualization with -fstrict-vtable-pointers. 1668 if (CGM.getCodeGenOpts().OptimizationLevel > 0 && 1669 CGM.getCodeGenOpts().StrictVTablePointers) 1670 VFuncLoad->setMetadata( 1671 llvm::LLVMContext::MD_invariant_load, 1672 llvm::MDNode::get(CGM.getLLVMContext(), 1673 llvm::ArrayRef<llvm::Metadata *>())); 1674 VFunc = VFuncLoad; 1675 } 1676 1677 CGCallee Callee(MethodDecl, VFunc); 1678 return Callee; 1679 } 1680 1681 llvm::Value *ItaniumCXXABI::EmitVirtualDestructorCall( 1682 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType, 1683 Address This, const CXXMemberCallExpr *CE) { 1684 assert(CE == nullptr || CE->arg_begin() == CE->arg_end()); 1685 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete); 1686 1687 const CGFunctionInfo *FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration( 1688 Dtor, getFromDtorType(DtorType)); 1689 llvm::FunctionType *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo); 1690 CGCallee Callee = 1691 CGCallee::forVirtual(CE, GlobalDecl(Dtor, DtorType), This, Ty); 1692 1693 CGF.EmitCXXMemberOrOperatorCall(Dtor, Callee, ReturnValueSlot(), 1694 This.getPointer(), /*ImplicitParam=*/nullptr, 1695 QualType(), CE, nullptr); 1696 return nullptr; 1697 } 1698 1699 void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) { 1700 CodeGenVTables &VTables = CGM.getVTables(); 1701 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD); 1702 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD); 1703 } 1704 1705 bool ItaniumCXXABI::canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const { 1706 // We don't emit available_externally vtables if we are in -fapple-kext mode 1707 // because kext mode does not permit devirtualization. 1708 if (CGM.getLangOpts().AppleKext) 1709 return false; 1710 1711 // If we don't have any not emitted inline virtual function, and if vtable is 1712 // not hidden, then we are safe to emit available_externally copy of vtable. 1713 // FIXME we can still emit a copy of the vtable if we 1714 // can emit definition of the inline functions. 1715 return !hasAnyUnusedVirtualInlineFunction(RD) && !isVTableHidden(RD); 1716 } 1717 static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF, 1718 Address InitialPtr, 1719 int64_t NonVirtualAdjustment, 1720 int64_t VirtualAdjustment, 1721 bool IsReturnAdjustment) { 1722 if (!NonVirtualAdjustment && !VirtualAdjustment) 1723 return InitialPtr.getPointer(); 1724 1725 Address V = CGF.Builder.CreateElementBitCast(InitialPtr, CGF.Int8Ty); 1726 1727 // In a base-to-derived cast, the non-virtual adjustment is applied first. 1728 if (NonVirtualAdjustment && !IsReturnAdjustment) { 1729 V = CGF.Builder.CreateConstInBoundsByteGEP(V, 1730 CharUnits::fromQuantity(NonVirtualAdjustment)); 1731 } 1732 1733 // Perform the virtual adjustment if we have one. 1734 llvm::Value *ResultPtr; 1735 if (VirtualAdjustment) { 1736 llvm::Type *PtrDiffTy = 1737 CGF.ConvertType(CGF.getContext().getPointerDiffType()); 1738 1739 Address VTablePtrPtr = CGF.Builder.CreateElementBitCast(V, CGF.Int8PtrTy); 1740 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr); 1741 1742 llvm::Value *OffsetPtr = 1743 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment); 1744 1745 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo()); 1746 1747 // Load the adjustment offset from the vtable. 1748 llvm::Value *Offset = 1749 CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign()); 1750 1751 // Adjust our pointer. 1752 ResultPtr = CGF.Builder.CreateInBoundsGEP(V.getPointer(), Offset); 1753 } else { 1754 ResultPtr = V.getPointer(); 1755 } 1756 1757 // In a derived-to-base conversion, the non-virtual adjustment is 1758 // applied second. 1759 if (NonVirtualAdjustment && IsReturnAdjustment) { 1760 ResultPtr = CGF.Builder.CreateConstInBoundsGEP1_64(ResultPtr, 1761 NonVirtualAdjustment); 1762 } 1763 1764 // Cast back to the original type. 1765 return CGF.Builder.CreateBitCast(ResultPtr, InitialPtr.getType()); 1766 } 1767 1768 llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF, 1769 Address This, 1770 const ThisAdjustment &TA) { 1771 return performTypeAdjustment(CGF, This, TA.NonVirtual, 1772 TA.Virtual.Itanium.VCallOffsetOffset, 1773 /*IsReturnAdjustment=*/false); 1774 } 1775 1776 llvm::Value * 1777 ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, Address Ret, 1778 const ReturnAdjustment &RA) { 1779 return performTypeAdjustment(CGF, Ret, RA.NonVirtual, 1780 RA.Virtual.Itanium.VBaseOffsetOffset, 1781 /*IsReturnAdjustment=*/true); 1782 } 1783 1784 void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF, 1785 RValue RV, QualType ResultType) { 1786 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl())) 1787 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType); 1788 1789 // Destructor thunks in the ARM ABI have indeterminate results. 1790 llvm::Type *T = CGF.ReturnValue.getElementType(); 1791 RValue Undef = RValue::get(llvm::UndefValue::get(T)); 1792 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType); 1793 } 1794 1795 /************************** Array allocation cookies **************************/ 1796 1797 CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) { 1798 // The array cookie is a size_t; pad that up to the element alignment. 1799 // The cookie is actually right-justified in that space. 1800 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes), 1801 CGM.getContext().getTypeAlignInChars(elementType)); 1802 } 1803 1804 Address ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF, 1805 Address NewPtr, 1806 llvm::Value *NumElements, 1807 const CXXNewExpr *expr, 1808 QualType ElementType) { 1809 assert(requiresArrayCookie(expr)); 1810 1811 unsigned AS = NewPtr.getAddressSpace(); 1812 1813 ASTContext &Ctx = getContext(); 1814 CharUnits SizeSize = CGF.getSizeSize(); 1815 1816 // The size of the cookie. 1817 CharUnits CookieSize = 1818 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType)); 1819 assert(CookieSize == getArrayCookieSizeImpl(ElementType)); 1820 1821 // Compute an offset to the cookie. 1822 Address CookiePtr = NewPtr; 1823 CharUnits CookieOffset = CookieSize - SizeSize; 1824 if (!CookieOffset.isZero()) 1825 CookiePtr = CGF.Builder.CreateConstInBoundsByteGEP(CookiePtr, CookieOffset); 1826 1827 // Write the number of elements into the appropriate slot. 1828 Address NumElementsPtr = 1829 CGF.Builder.CreateElementBitCast(CookiePtr, CGF.SizeTy); 1830 llvm::Instruction *SI = CGF.Builder.CreateStore(NumElements, NumElementsPtr); 1831 1832 // Handle the array cookie specially in ASan. 1833 if (CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) && AS == 0 && 1834 (expr->getOperatorNew()->isReplaceableGlobalAllocationFunction() || 1835 CGM.getCodeGenOpts().SanitizeAddressPoisonClassMemberArrayNewCookie)) { 1836 // The store to the CookiePtr does not need to be instrumented. 1837 CGM.getSanitizerMetadata()->disableSanitizerForInstruction(SI); 1838 llvm::FunctionType *FTy = 1839 llvm::FunctionType::get(CGM.VoidTy, NumElementsPtr.getType(), false); 1840 llvm::Constant *F = 1841 CGM.CreateRuntimeFunction(FTy, "__asan_poison_cxx_array_cookie"); 1842 CGF.Builder.CreateCall(F, NumElementsPtr.getPointer()); 1843 } 1844 1845 // Finally, compute a pointer to the actual data buffer by skipping 1846 // over the cookie completely. 1847 return CGF.Builder.CreateConstInBoundsByteGEP(NewPtr, CookieSize); 1848 } 1849 1850 llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF, 1851 Address allocPtr, 1852 CharUnits cookieSize) { 1853 // The element size is right-justified in the cookie. 1854 Address numElementsPtr = allocPtr; 1855 CharUnits numElementsOffset = cookieSize - CGF.getSizeSize(); 1856 if (!numElementsOffset.isZero()) 1857 numElementsPtr = 1858 CGF.Builder.CreateConstInBoundsByteGEP(numElementsPtr, numElementsOffset); 1859 1860 unsigned AS = allocPtr.getAddressSpace(); 1861 numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy); 1862 if (!CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) || AS != 0) 1863 return CGF.Builder.CreateLoad(numElementsPtr); 1864 // In asan mode emit a function call instead of a regular load and let the 1865 // run-time deal with it: if the shadow is properly poisoned return the 1866 // cookie, otherwise return 0 to avoid an infinite loop calling DTORs. 1867 // We can't simply ignore this load using nosanitize metadata because 1868 // the metadata may be lost. 1869 llvm::FunctionType *FTy = 1870 llvm::FunctionType::get(CGF.SizeTy, CGF.SizeTy->getPointerTo(0), false); 1871 llvm::Constant *F = 1872 CGM.CreateRuntimeFunction(FTy, "__asan_load_cxx_array_cookie"); 1873 return CGF.Builder.CreateCall(F, numElementsPtr.getPointer()); 1874 } 1875 1876 CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) { 1877 // ARM says that the cookie is always: 1878 // struct array_cookie { 1879 // std::size_t element_size; // element_size != 0 1880 // std::size_t element_count; 1881 // }; 1882 // But the base ABI doesn't give anything an alignment greater than 1883 // 8, so we can dismiss this as typical ABI-author blindness to 1884 // actual language complexity and round up to the element alignment. 1885 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes), 1886 CGM.getContext().getTypeAlignInChars(elementType)); 1887 } 1888 1889 Address ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF, 1890 Address newPtr, 1891 llvm::Value *numElements, 1892 const CXXNewExpr *expr, 1893 QualType elementType) { 1894 assert(requiresArrayCookie(expr)); 1895 1896 // The cookie is always at the start of the buffer. 1897 Address cookie = newPtr; 1898 1899 // The first element is the element size. 1900 cookie = CGF.Builder.CreateElementBitCast(cookie, CGF.SizeTy); 1901 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy, 1902 getContext().getTypeSizeInChars(elementType).getQuantity()); 1903 CGF.Builder.CreateStore(elementSize, cookie); 1904 1905 // The second element is the element count. 1906 cookie = CGF.Builder.CreateConstInBoundsGEP(cookie, 1, CGF.getSizeSize()); 1907 CGF.Builder.CreateStore(numElements, cookie); 1908 1909 // Finally, compute a pointer to the actual data buffer by skipping 1910 // over the cookie completely. 1911 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType); 1912 return CGF.Builder.CreateConstInBoundsByteGEP(newPtr, cookieSize); 1913 } 1914 1915 llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF, 1916 Address allocPtr, 1917 CharUnits cookieSize) { 1918 // The number of elements is at offset sizeof(size_t) relative to 1919 // the allocated pointer. 1920 Address numElementsPtr 1921 = CGF.Builder.CreateConstInBoundsByteGEP(allocPtr, CGF.getSizeSize()); 1922 1923 numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy); 1924 return CGF.Builder.CreateLoad(numElementsPtr); 1925 } 1926 1927 /*********************** Static local initialization **************************/ 1928 1929 static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM, 1930 llvm::PointerType *GuardPtrTy) { 1931 // int __cxa_guard_acquire(__guard *guard_object); 1932 llvm::FunctionType *FTy = 1933 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy), 1934 GuardPtrTy, /*isVarArg=*/false); 1935 return CGM.CreateRuntimeFunction( 1936 FTy, "__cxa_guard_acquire", 1937 llvm::AttributeList::get(CGM.getLLVMContext(), 1938 llvm::AttributeList::FunctionIndex, 1939 llvm::Attribute::NoUnwind)); 1940 } 1941 1942 static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM, 1943 llvm::PointerType *GuardPtrTy) { 1944 // void __cxa_guard_release(__guard *guard_object); 1945 llvm::FunctionType *FTy = 1946 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false); 1947 return CGM.CreateRuntimeFunction( 1948 FTy, "__cxa_guard_release", 1949 llvm::AttributeList::get(CGM.getLLVMContext(), 1950 llvm::AttributeList::FunctionIndex, 1951 llvm::Attribute::NoUnwind)); 1952 } 1953 1954 static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM, 1955 llvm::PointerType *GuardPtrTy) { 1956 // void __cxa_guard_abort(__guard *guard_object); 1957 llvm::FunctionType *FTy = 1958 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false); 1959 return CGM.CreateRuntimeFunction( 1960 FTy, "__cxa_guard_abort", 1961 llvm::AttributeList::get(CGM.getLLVMContext(), 1962 llvm::AttributeList::FunctionIndex, 1963 llvm::Attribute::NoUnwind)); 1964 } 1965 1966 namespace { 1967 struct CallGuardAbort final : EHScopeStack::Cleanup { 1968 llvm::GlobalVariable *Guard; 1969 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {} 1970 1971 void Emit(CodeGenFunction &CGF, Flags flags) override { 1972 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()), 1973 Guard); 1974 } 1975 }; 1976 } 1977 1978 /// The ARM code here follows the Itanium code closely enough that we 1979 /// just special-case it at particular places. 1980 void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF, 1981 const VarDecl &D, 1982 llvm::GlobalVariable *var, 1983 bool shouldPerformInit) { 1984 CGBuilderTy &Builder = CGF.Builder; 1985 1986 // Inline variables that weren't instantiated from variable templates have 1987 // partially-ordered initialization within their translation unit. 1988 bool NonTemplateInline = 1989 D.isInline() && 1990 !isTemplateInstantiation(D.getTemplateSpecializationKind()); 1991 1992 // We only need to use thread-safe statics for local non-TLS variables and 1993 // inline variables; other global initialization is always single-threaded 1994 // or (through lazy dynamic loading in multiple threads) unsequenced. 1995 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics && 1996 (D.isLocalVarDecl() || NonTemplateInline) && 1997 !D.getTLSKind(); 1998 1999 // If we have a global variable with internal linkage and thread-safe statics 2000 // are disabled, we can just let the guard variable be of type i8. 2001 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage(); 2002 2003 llvm::IntegerType *guardTy; 2004 CharUnits guardAlignment; 2005 if (useInt8GuardVariable) { 2006 guardTy = CGF.Int8Ty; 2007 guardAlignment = CharUnits::One(); 2008 } else { 2009 // Guard variables are 64 bits in the generic ABI and size width on ARM 2010 // (i.e. 32-bit on AArch32, 64-bit on AArch64). 2011 if (UseARMGuardVarABI) { 2012 guardTy = CGF.SizeTy; 2013 guardAlignment = CGF.getSizeAlign(); 2014 } else { 2015 guardTy = CGF.Int64Ty; 2016 guardAlignment = CharUnits::fromQuantity( 2017 CGM.getDataLayout().getABITypeAlignment(guardTy)); 2018 } 2019 } 2020 llvm::PointerType *guardPtrTy = guardTy->getPointerTo(); 2021 2022 // Create the guard variable if we don't already have it (as we 2023 // might if we're double-emitting this function body). 2024 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D); 2025 if (!guard) { 2026 // Mangle the name for the guard. 2027 SmallString<256> guardName; 2028 { 2029 llvm::raw_svector_ostream out(guardName); 2030 getMangleContext().mangleStaticGuardVariable(&D, out); 2031 } 2032 2033 // Create the guard variable with a zero-initializer. 2034 // Just absorb linkage and visibility from the guarded variable. 2035 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy, 2036 false, var->getLinkage(), 2037 llvm::ConstantInt::get(guardTy, 0), 2038 guardName.str()); 2039 guard->setDSOLocal(var->isDSOLocal()); 2040 guard->setVisibility(var->getVisibility()); 2041 // If the variable is thread-local, so is its guard variable. 2042 guard->setThreadLocalMode(var->getThreadLocalMode()); 2043 guard->setAlignment(guardAlignment.getQuantity()); 2044 2045 // The ABI says: "It is suggested that it be emitted in the same COMDAT 2046 // group as the associated data object." In practice, this doesn't work for 2047 // non-ELF and non-Wasm object formats, so only do it for ELF and Wasm. 2048 llvm::Comdat *C = var->getComdat(); 2049 if (!D.isLocalVarDecl() && C && 2050 (CGM.getTarget().getTriple().isOSBinFormatELF() || 2051 CGM.getTarget().getTriple().isOSBinFormatWasm())) { 2052 guard->setComdat(C); 2053 // An inline variable's guard function is run from the per-TU 2054 // initialization function, not via a dedicated global ctor function, so 2055 // we can't put it in a comdat. 2056 if (!NonTemplateInline) 2057 CGF.CurFn->setComdat(C); 2058 } else if (CGM.supportsCOMDAT() && guard->isWeakForLinker()) { 2059 guard->setComdat(CGM.getModule().getOrInsertComdat(guard->getName())); 2060 } 2061 2062 CGM.setStaticLocalDeclGuardAddress(&D, guard); 2063 } 2064 2065 Address guardAddr = Address(guard, guardAlignment); 2066 2067 // Test whether the variable has completed initialization. 2068 // 2069 // Itanium C++ ABI 3.3.2: 2070 // The following is pseudo-code showing how these functions can be used: 2071 // if (obj_guard.first_byte == 0) { 2072 // if ( __cxa_guard_acquire (&obj_guard) ) { 2073 // try { 2074 // ... initialize the object ...; 2075 // } catch (...) { 2076 // __cxa_guard_abort (&obj_guard); 2077 // throw; 2078 // } 2079 // ... queue object destructor with __cxa_atexit() ...; 2080 // __cxa_guard_release (&obj_guard); 2081 // } 2082 // } 2083 2084 // Load the first byte of the guard variable. 2085 llvm::LoadInst *LI = 2086 Builder.CreateLoad(Builder.CreateElementBitCast(guardAddr, CGM.Int8Ty)); 2087 2088 // Itanium ABI: 2089 // An implementation supporting thread-safety on multiprocessor 2090 // systems must also guarantee that references to the initialized 2091 // object do not occur before the load of the initialization flag. 2092 // 2093 // In LLVM, we do this by marking the load Acquire. 2094 if (threadsafe) 2095 LI->setAtomic(llvm::AtomicOrdering::Acquire); 2096 2097 // For ARM, we should only check the first bit, rather than the entire byte: 2098 // 2099 // ARM C++ ABI 3.2.3.1: 2100 // To support the potential use of initialization guard variables 2101 // as semaphores that are the target of ARM SWP and LDREX/STREX 2102 // synchronizing instructions we define a static initialization 2103 // guard variable to be a 4-byte aligned, 4-byte word with the 2104 // following inline access protocol. 2105 // #define INITIALIZED 1 2106 // if ((obj_guard & INITIALIZED) != INITIALIZED) { 2107 // if (__cxa_guard_acquire(&obj_guard)) 2108 // ... 2109 // } 2110 // 2111 // and similarly for ARM64: 2112 // 2113 // ARM64 C++ ABI 3.2.2: 2114 // This ABI instead only specifies the value bit 0 of the static guard 2115 // variable; all other bits are platform defined. Bit 0 shall be 0 when the 2116 // variable is not initialized and 1 when it is. 2117 llvm::Value *V = 2118 (UseARMGuardVarABI && !useInt8GuardVariable) 2119 ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1)) 2120 : LI; 2121 llvm::Value *NeedsInit = Builder.CreateIsNull(V, "guard.uninitialized"); 2122 2123 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check"); 2124 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end"); 2125 2126 // Check if the first byte of the guard variable is zero. 2127 CGF.EmitCXXGuardedInitBranch(NeedsInit, InitCheckBlock, EndBlock, 2128 CodeGenFunction::GuardKind::VariableGuard, &D); 2129 2130 CGF.EmitBlock(InitCheckBlock); 2131 2132 // Variables used when coping with thread-safe statics and exceptions. 2133 if (threadsafe) { 2134 // Call __cxa_guard_acquire. 2135 llvm::Value *V 2136 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard); 2137 2138 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init"); 2139 2140 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"), 2141 InitBlock, EndBlock); 2142 2143 // Call __cxa_guard_abort along the exceptional edge. 2144 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard); 2145 2146 CGF.EmitBlock(InitBlock); 2147 } 2148 2149 // Emit the initializer and add a global destructor if appropriate. 2150 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit); 2151 2152 if (threadsafe) { 2153 // Pop the guard-abort cleanup if we pushed one. 2154 CGF.PopCleanupBlock(); 2155 2156 // Call __cxa_guard_release. This cannot throw. 2157 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy), 2158 guardAddr.getPointer()); 2159 } else { 2160 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guardAddr); 2161 } 2162 2163 CGF.EmitBlock(EndBlock); 2164 } 2165 2166 /// Register a global destructor using __cxa_atexit. 2167 static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF, 2168 llvm::Constant *dtor, 2169 llvm::Constant *addr, 2170 bool TLS) { 2171 const char *Name = "__cxa_atexit"; 2172 if (TLS) { 2173 const llvm::Triple &T = CGF.getTarget().getTriple(); 2174 Name = T.isOSDarwin() ? "_tlv_atexit" : "__cxa_thread_atexit"; 2175 } 2176 2177 // We're assuming that the destructor function is something we can 2178 // reasonably call with the default CC. Go ahead and cast it to the 2179 // right prototype. 2180 llvm::Type *dtorTy = 2181 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo(); 2182 2183 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d); 2184 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy }; 2185 llvm::FunctionType *atexitTy = 2186 llvm::FunctionType::get(CGF.IntTy, paramTys, false); 2187 2188 // Fetch the actual function. 2189 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name); 2190 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit)) 2191 fn->setDoesNotThrow(); 2192 2193 // Create a variable that binds the atexit to this shared object. 2194 llvm::Constant *handle = 2195 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle"); 2196 auto *GV = cast<llvm::GlobalValue>(handle->stripPointerCasts()); 2197 GV->setVisibility(llvm::GlobalValue::HiddenVisibility); 2198 2199 if (!addr) 2200 // addr is null when we are trying to register a dtor annotated with 2201 // __attribute__((destructor)) in a constructor function. Using null here is 2202 // okay because this argument is just passed back to the destructor 2203 // function. 2204 addr = llvm::Constant::getNullValue(CGF.Int8PtrTy); 2205 2206 llvm::Value *args[] = { 2207 llvm::ConstantExpr::getBitCast(dtor, dtorTy), 2208 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy), 2209 handle 2210 }; 2211 CGF.EmitNounwindRuntimeCall(atexit, args); 2212 } 2213 2214 void CodeGenModule::registerGlobalDtorsWithAtExit() { 2215 for (const auto I : DtorsUsingAtExit) { 2216 int Priority = I.first; 2217 const llvm::TinyPtrVector<llvm::Function *> &Dtors = I.second; 2218 2219 // Create a function that registers destructors that have the same priority. 2220 // 2221 // Since constructor functions are run in non-descending order of their 2222 // priorities, destructors are registered in non-descending order of their 2223 // priorities, and since destructor functions are run in the reverse order 2224 // of their registration, destructor functions are run in non-ascending 2225 // order of their priorities. 2226 CodeGenFunction CGF(*this); 2227 std::string GlobalInitFnName = 2228 std::string("__GLOBAL_init_") + llvm::to_string(Priority); 2229 llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false); 2230 llvm::Function *GlobalInitFn = CreateGlobalInitOrDestructFunction( 2231 FTy, GlobalInitFnName, getTypes().arrangeNullaryFunction(), 2232 SourceLocation()); 2233 ASTContext &Ctx = getContext(); 2234 FunctionDecl *FD = FunctionDecl::Create( 2235 Ctx, Ctx.getTranslationUnitDecl(), SourceLocation(), SourceLocation(), 2236 &Ctx.Idents.get(GlobalInitFnName), Ctx.VoidTy, nullptr, SC_Static, 2237 false, false); 2238 CGF.StartFunction(GlobalDecl(FD), getContext().VoidTy, GlobalInitFn, 2239 getTypes().arrangeNullaryFunction(), FunctionArgList(), 2240 SourceLocation(), SourceLocation()); 2241 2242 for (auto *Dtor : Dtors) { 2243 // Register the destructor function calling __cxa_atexit if it is 2244 // available. Otherwise fall back on calling atexit. 2245 if (getCodeGenOpts().CXAAtExit) 2246 emitGlobalDtorWithCXAAtExit(CGF, Dtor, nullptr, false); 2247 else 2248 CGF.registerGlobalDtorWithAtExit(Dtor); 2249 } 2250 2251 CGF.FinishFunction(); 2252 AddGlobalCtor(GlobalInitFn, Priority, nullptr); 2253 } 2254 } 2255 2256 /// Register a global destructor as best as we know how. 2257 void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF, 2258 const VarDecl &D, 2259 llvm::Constant *dtor, 2260 llvm::Constant *addr) { 2261 // Use __cxa_atexit if available. 2262 if (CGM.getCodeGenOpts().CXAAtExit) 2263 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind()); 2264 2265 if (D.getTLSKind()) 2266 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction"); 2267 2268 // In Apple kexts, we want to add a global destructor entry. 2269 // FIXME: shouldn't this be guarded by some variable? 2270 if (CGM.getLangOpts().AppleKext) { 2271 // Generate a global destructor entry. 2272 return CGM.AddCXXDtorEntry(dtor, addr); 2273 } 2274 2275 CGF.registerGlobalDtorWithAtExit(D, dtor, addr); 2276 } 2277 2278 static bool isThreadWrapperReplaceable(const VarDecl *VD, 2279 CodeGen::CodeGenModule &CGM) { 2280 assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!"); 2281 // Darwin prefers to have references to thread local variables to go through 2282 // the thread wrapper instead of directly referencing the backing variable. 2283 return VD->getTLSKind() == VarDecl::TLS_Dynamic && 2284 CGM.getTarget().getTriple().isOSDarwin(); 2285 } 2286 2287 /// Get the appropriate linkage for the wrapper function. This is essentially 2288 /// the weak form of the variable's linkage; every translation unit which needs 2289 /// the wrapper emits a copy, and we want the linker to merge them. 2290 static llvm::GlobalValue::LinkageTypes 2291 getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) { 2292 llvm::GlobalValue::LinkageTypes VarLinkage = 2293 CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false); 2294 2295 // For internal linkage variables, we don't need an external or weak wrapper. 2296 if (llvm::GlobalValue::isLocalLinkage(VarLinkage)) 2297 return VarLinkage; 2298 2299 // If the thread wrapper is replaceable, give it appropriate linkage. 2300 if (isThreadWrapperReplaceable(VD, CGM)) 2301 if (!llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) && 2302 !llvm::GlobalVariable::isWeakODRLinkage(VarLinkage)) 2303 return VarLinkage; 2304 return llvm::GlobalValue::WeakODRLinkage; 2305 } 2306 2307 llvm::Function * 2308 ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD, 2309 llvm::Value *Val) { 2310 // Mangle the name for the thread_local wrapper function. 2311 SmallString<256> WrapperName; 2312 { 2313 llvm::raw_svector_ostream Out(WrapperName); 2314 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out); 2315 } 2316 2317 // FIXME: If VD is a definition, we should regenerate the function attributes 2318 // before returning. 2319 if (llvm::Value *V = CGM.getModule().getNamedValue(WrapperName)) 2320 return cast<llvm::Function>(V); 2321 2322 QualType RetQT = VD->getType(); 2323 if (RetQT->isReferenceType()) 2324 RetQT = RetQT.getNonReferenceType(); 2325 2326 const CGFunctionInfo &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration( 2327 getContext().getPointerType(RetQT), FunctionArgList()); 2328 2329 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FI); 2330 llvm::Function *Wrapper = 2331 llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM), 2332 WrapperName.str(), &CGM.getModule()); 2333 2334 CGM.SetLLVMFunctionAttributes(nullptr, FI, Wrapper); 2335 2336 if (VD->hasDefinition()) 2337 CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Wrapper); 2338 2339 // Always resolve references to the wrapper at link time. 2340 if (!Wrapper->hasLocalLinkage() && !(isThreadWrapperReplaceable(VD, CGM) && 2341 !llvm::GlobalVariable::isLinkOnceLinkage(Wrapper->getLinkage()) && 2342 !llvm::GlobalVariable::isWeakODRLinkage(Wrapper->getLinkage()))) 2343 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility); 2344 2345 if (isThreadWrapperReplaceable(VD, CGM)) { 2346 Wrapper->setCallingConv(llvm::CallingConv::CXX_FAST_TLS); 2347 Wrapper->addFnAttr(llvm::Attribute::NoUnwind); 2348 } 2349 return Wrapper; 2350 } 2351 2352 void ItaniumCXXABI::EmitThreadLocalInitFuncs( 2353 CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals, 2354 ArrayRef<llvm::Function *> CXXThreadLocalInits, 2355 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) { 2356 llvm::Function *InitFunc = nullptr; 2357 2358 // Separate initializers into those with ordered (or partially-ordered) 2359 // initialization and those with unordered initialization. 2360 llvm::SmallVector<llvm::Function *, 8> OrderedInits; 2361 llvm::SmallDenseMap<const VarDecl *, llvm::Function *> UnorderedInits; 2362 for (unsigned I = 0; I != CXXThreadLocalInits.size(); ++I) { 2363 if (isTemplateInstantiation( 2364 CXXThreadLocalInitVars[I]->getTemplateSpecializationKind())) 2365 UnorderedInits[CXXThreadLocalInitVars[I]->getCanonicalDecl()] = 2366 CXXThreadLocalInits[I]; 2367 else 2368 OrderedInits.push_back(CXXThreadLocalInits[I]); 2369 } 2370 2371 if (!OrderedInits.empty()) { 2372 // Generate a guarded initialization function. 2373 llvm::FunctionType *FTy = 2374 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false); 2375 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction(); 2376 InitFunc = CGM.CreateGlobalInitOrDestructFunction(FTy, "__tls_init", FI, 2377 SourceLocation(), 2378 /*TLS=*/true); 2379 llvm::GlobalVariable *Guard = new llvm::GlobalVariable( 2380 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false, 2381 llvm::GlobalVariable::InternalLinkage, 2382 llvm::ConstantInt::get(CGM.Int8Ty, 0), "__tls_guard"); 2383 Guard->setThreadLocal(true); 2384 2385 CharUnits GuardAlign = CharUnits::One(); 2386 Guard->setAlignment(GuardAlign.getQuantity()); 2387 2388 CodeGenFunction(CGM).GenerateCXXGlobalInitFunc(InitFunc, OrderedInits, 2389 Address(Guard, GuardAlign)); 2390 // On Darwin platforms, use CXX_FAST_TLS calling convention. 2391 if (CGM.getTarget().getTriple().isOSDarwin()) { 2392 InitFunc->setCallingConv(llvm::CallingConv::CXX_FAST_TLS); 2393 InitFunc->addFnAttr(llvm::Attribute::NoUnwind); 2394 } 2395 } 2396 2397 // Emit thread wrappers. 2398 for (const VarDecl *VD : CXXThreadLocals) { 2399 llvm::GlobalVariable *Var = 2400 cast<llvm::GlobalVariable>(CGM.GetGlobalValue(CGM.getMangledName(VD))); 2401 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var); 2402 2403 // Some targets require that all access to thread local variables go through 2404 // the thread wrapper. This means that we cannot attempt to create a thread 2405 // wrapper or a thread helper. 2406 if (isThreadWrapperReplaceable(VD, CGM) && !VD->hasDefinition()) { 2407 Wrapper->setLinkage(llvm::Function::ExternalLinkage); 2408 continue; 2409 } 2410 2411 // Mangle the name for the thread_local initialization function. 2412 SmallString<256> InitFnName; 2413 { 2414 llvm::raw_svector_ostream Out(InitFnName); 2415 getMangleContext().mangleItaniumThreadLocalInit(VD, Out); 2416 } 2417 2418 // If we have a definition for the variable, emit the initialization 2419 // function as an alias to the global Init function (if any). Otherwise, 2420 // produce a declaration of the initialization function. 2421 llvm::GlobalValue *Init = nullptr; 2422 bool InitIsInitFunc = false; 2423 if (VD->hasDefinition()) { 2424 InitIsInitFunc = true; 2425 llvm::Function *InitFuncToUse = InitFunc; 2426 if (isTemplateInstantiation(VD->getTemplateSpecializationKind())) 2427 InitFuncToUse = UnorderedInits.lookup(VD->getCanonicalDecl()); 2428 if (InitFuncToUse) 2429 Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(), 2430 InitFuncToUse); 2431 } else { 2432 // Emit a weak global function referring to the initialization function. 2433 // This function will not exist if the TU defining the thread_local 2434 // variable in question does not need any dynamic initialization for 2435 // its thread_local variables. 2436 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false); 2437 Init = llvm::Function::Create(FnTy, 2438 llvm::GlobalVariable::ExternalWeakLinkage, 2439 InitFnName.str(), &CGM.getModule()); 2440 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction(); 2441 CGM.SetLLVMFunctionAttributes(nullptr, FI, cast<llvm::Function>(Init)); 2442 } 2443 2444 if (Init) { 2445 Init->setVisibility(Var->getVisibility()); 2446 Init->setDSOLocal(Var->isDSOLocal()); 2447 } 2448 2449 llvm::LLVMContext &Context = CGM.getModule().getContext(); 2450 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper); 2451 CGBuilderTy Builder(CGM, Entry); 2452 if (InitIsInitFunc) { 2453 if (Init) { 2454 llvm::CallInst *CallVal = Builder.CreateCall(Init); 2455 if (isThreadWrapperReplaceable(VD, CGM)) 2456 CallVal->setCallingConv(llvm::CallingConv::CXX_FAST_TLS); 2457 } 2458 } else { 2459 // Don't know whether we have an init function. Call it if it exists. 2460 llvm::Value *Have = Builder.CreateIsNotNull(Init); 2461 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper); 2462 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper); 2463 Builder.CreateCondBr(Have, InitBB, ExitBB); 2464 2465 Builder.SetInsertPoint(InitBB); 2466 Builder.CreateCall(Init); 2467 Builder.CreateBr(ExitBB); 2468 2469 Builder.SetInsertPoint(ExitBB); 2470 } 2471 2472 // For a reference, the result of the wrapper function is a pointer to 2473 // the referenced object. 2474 llvm::Value *Val = Var; 2475 if (VD->getType()->isReferenceType()) { 2476 CharUnits Align = CGM.getContext().getDeclAlign(VD); 2477 Val = Builder.CreateAlignedLoad(Val, Align); 2478 } 2479 if (Val->getType() != Wrapper->getReturnType()) 2480 Val = Builder.CreatePointerBitCastOrAddrSpaceCast( 2481 Val, Wrapper->getReturnType(), ""); 2482 Builder.CreateRet(Val); 2483 } 2484 } 2485 2486 LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, 2487 const VarDecl *VD, 2488 QualType LValType) { 2489 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD); 2490 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Val); 2491 2492 llvm::CallInst *CallVal = CGF.Builder.CreateCall(Wrapper); 2493 CallVal->setCallingConv(Wrapper->getCallingConv()); 2494 2495 LValue LV; 2496 if (VD->getType()->isReferenceType()) 2497 LV = CGF.MakeNaturalAlignAddrLValue(CallVal, LValType); 2498 else 2499 LV = CGF.MakeAddrLValue(CallVal, LValType, 2500 CGF.getContext().getDeclAlign(VD)); 2501 // FIXME: need setObjCGCLValueClass? 2502 return LV; 2503 } 2504 2505 /// Return whether the given global decl needs a VTT parameter, which it does 2506 /// if it's a base constructor or destructor with virtual bases. 2507 bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) { 2508 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl()); 2509 2510 // We don't have any virtual bases, just return early. 2511 if (!MD->getParent()->getNumVBases()) 2512 return false; 2513 2514 // Check if we have a base constructor. 2515 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base) 2516 return true; 2517 2518 // Check if we have a base destructor. 2519 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base) 2520 return true; 2521 2522 return false; 2523 } 2524 2525 namespace { 2526 class ItaniumRTTIBuilder { 2527 CodeGenModule &CGM; // Per-module state. 2528 llvm::LLVMContext &VMContext; 2529 const ItaniumCXXABI &CXXABI; // Per-module state. 2530 2531 /// Fields - The fields of the RTTI descriptor currently being built. 2532 SmallVector<llvm::Constant *, 16> Fields; 2533 2534 /// GetAddrOfTypeName - Returns the mangled type name of the given type. 2535 llvm::GlobalVariable * 2536 GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage); 2537 2538 /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI 2539 /// descriptor of the given type. 2540 llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty); 2541 2542 /// BuildVTablePointer - Build the vtable pointer for the given type. 2543 void BuildVTablePointer(const Type *Ty); 2544 2545 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single 2546 /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b. 2547 void BuildSIClassTypeInfo(const CXXRecordDecl *RD); 2548 2549 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for 2550 /// classes with bases that do not satisfy the abi::__si_class_type_info 2551 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c. 2552 void BuildVMIClassTypeInfo(const CXXRecordDecl *RD); 2553 2554 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used 2555 /// for pointer types. 2556 void BuildPointerTypeInfo(QualType PointeeTy); 2557 2558 /// BuildObjCObjectTypeInfo - Build the appropriate kind of 2559 /// type_info for an object type. 2560 void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty); 2561 2562 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info 2563 /// struct, used for member pointer types. 2564 void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty); 2565 2566 public: 2567 ItaniumRTTIBuilder(const ItaniumCXXABI &ABI) 2568 : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {} 2569 2570 // Pointer type info flags. 2571 enum { 2572 /// PTI_Const - Type has const qualifier. 2573 PTI_Const = 0x1, 2574 2575 /// PTI_Volatile - Type has volatile qualifier. 2576 PTI_Volatile = 0x2, 2577 2578 /// PTI_Restrict - Type has restrict qualifier. 2579 PTI_Restrict = 0x4, 2580 2581 /// PTI_Incomplete - Type is incomplete. 2582 PTI_Incomplete = 0x8, 2583 2584 /// PTI_ContainingClassIncomplete - Containing class is incomplete. 2585 /// (in pointer to member). 2586 PTI_ContainingClassIncomplete = 0x10, 2587 2588 /// PTI_TransactionSafe - Pointee is transaction_safe function (C++ TM TS). 2589 //PTI_TransactionSafe = 0x20, 2590 2591 /// PTI_Noexcept - Pointee is noexcept function (C++1z). 2592 PTI_Noexcept = 0x40, 2593 }; 2594 2595 // VMI type info flags. 2596 enum { 2597 /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance. 2598 VMI_NonDiamondRepeat = 0x1, 2599 2600 /// VMI_DiamondShaped - Class is diamond shaped. 2601 VMI_DiamondShaped = 0x2 2602 }; 2603 2604 // Base class type info flags. 2605 enum { 2606 /// BCTI_Virtual - Base class is virtual. 2607 BCTI_Virtual = 0x1, 2608 2609 /// BCTI_Public - Base class is public. 2610 BCTI_Public = 0x2 2611 }; 2612 2613 /// BuildTypeInfo - Build the RTTI type info struct for the given type. 2614 /// 2615 /// \param Force - true to force the creation of this RTTI value 2616 /// \param DLLExport - true to mark the RTTI value as DLLExport 2617 llvm::Constant *BuildTypeInfo(QualType Ty, bool Force = false, 2618 bool DLLExport = false); 2619 }; 2620 } 2621 2622 llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName( 2623 QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) { 2624 SmallString<256> Name; 2625 llvm::raw_svector_ostream Out(Name); 2626 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out); 2627 2628 // We know that the mangled name of the type starts at index 4 of the 2629 // mangled name of the typename, so we can just index into it in order to 2630 // get the mangled name of the type. 2631 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext, 2632 Name.substr(4)); 2633 2634 llvm::GlobalVariable *GV = 2635 CGM.CreateOrReplaceCXXRuntimeVariable(Name, Init->getType(), Linkage); 2636 2637 GV->setInitializer(Init); 2638 2639 return GV; 2640 } 2641 2642 llvm::Constant * 2643 ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) { 2644 // Mangle the RTTI name. 2645 SmallString<256> Name; 2646 llvm::raw_svector_ostream Out(Name); 2647 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out); 2648 2649 // Look for an existing global. 2650 llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name); 2651 2652 if (!GV) { 2653 // Create a new global variable. 2654 // Note for the future: If we would ever like to do deferred emission of 2655 // RTTI, check if emitting vtables opportunistically need any adjustment. 2656 2657 GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy, 2658 /*Constant=*/true, 2659 llvm::GlobalValue::ExternalLinkage, nullptr, 2660 Name); 2661 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 2662 CGM.setGVProperties(GV, RD); 2663 } 2664 2665 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy); 2666 } 2667 2668 /// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type 2669 /// info for that type is defined in the standard library. 2670 static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) { 2671 // Itanium C++ ABI 2.9.2: 2672 // Basic type information (e.g. for "int", "bool", etc.) will be kept in 2673 // the run-time support library. Specifically, the run-time support 2674 // library should contain type_info objects for the types X, X* and 2675 // X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char, 2676 // unsigned char, signed char, short, unsigned short, int, unsigned int, 2677 // long, unsigned long, long long, unsigned long long, float, double, 2678 // long double, char16_t, char32_t, and the IEEE 754r decimal and 2679 // half-precision floating point types. 2680 // 2681 // GCC also emits RTTI for __int128. 2682 // FIXME: We do not emit RTTI information for decimal types here. 2683 2684 // Types added here must also be added to EmitFundamentalRTTIDescriptors. 2685 switch (Ty->getKind()) { 2686 case BuiltinType::Void: 2687 case BuiltinType::NullPtr: 2688 case BuiltinType::Bool: 2689 case BuiltinType::WChar_S: 2690 case BuiltinType::WChar_U: 2691 case BuiltinType::Char_U: 2692 case BuiltinType::Char_S: 2693 case BuiltinType::UChar: 2694 case BuiltinType::SChar: 2695 case BuiltinType::Short: 2696 case BuiltinType::UShort: 2697 case BuiltinType::Int: 2698 case BuiltinType::UInt: 2699 case BuiltinType::Long: 2700 case BuiltinType::ULong: 2701 case BuiltinType::LongLong: 2702 case BuiltinType::ULongLong: 2703 case BuiltinType::Half: 2704 case BuiltinType::Float: 2705 case BuiltinType::Double: 2706 case BuiltinType::LongDouble: 2707 case BuiltinType::Float16: 2708 case BuiltinType::Float128: 2709 case BuiltinType::Char8: 2710 case BuiltinType::Char16: 2711 case BuiltinType::Char32: 2712 case BuiltinType::Int128: 2713 case BuiltinType::UInt128: 2714 return true; 2715 2716 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 2717 case BuiltinType::Id: 2718 #include "clang/Basic/OpenCLImageTypes.def" 2719 case BuiltinType::OCLSampler: 2720 case BuiltinType::OCLEvent: 2721 case BuiltinType::OCLClkEvent: 2722 case BuiltinType::OCLQueue: 2723 case BuiltinType::OCLReserveID: 2724 return false; 2725 2726 case BuiltinType::Dependent: 2727 #define BUILTIN_TYPE(Id, SingletonId) 2728 #define PLACEHOLDER_TYPE(Id, SingletonId) \ 2729 case BuiltinType::Id: 2730 #include "clang/AST/BuiltinTypes.def" 2731 llvm_unreachable("asking for RRTI for a placeholder type!"); 2732 2733 case BuiltinType::ObjCId: 2734 case BuiltinType::ObjCClass: 2735 case BuiltinType::ObjCSel: 2736 llvm_unreachable("FIXME: Objective-C types are unsupported!"); 2737 } 2738 2739 llvm_unreachable("Invalid BuiltinType Kind!"); 2740 } 2741 2742 static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) { 2743 QualType PointeeTy = PointerTy->getPointeeType(); 2744 const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy); 2745 if (!BuiltinTy) 2746 return false; 2747 2748 // Check the qualifiers. 2749 Qualifiers Quals = PointeeTy.getQualifiers(); 2750 Quals.removeConst(); 2751 2752 if (!Quals.empty()) 2753 return false; 2754 2755 return TypeInfoIsInStandardLibrary(BuiltinTy); 2756 } 2757 2758 /// IsStandardLibraryRTTIDescriptor - Returns whether the type 2759 /// information for the given type exists in the standard library. 2760 static bool IsStandardLibraryRTTIDescriptor(QualType Ty) { 2761 // Type info for builtin types is defined in the standard library. 2762 if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty)) 2763 return TypeInfoIsInStandardLibrary(BuiltinTy); 2764 2765 // Type info for some pointer types to builtin types is defined in the 2766 // standard library. 2767 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty)) 2768 return TypeInfoIsInStandardLibrary(PointerTy); 2769 2770 return false; 2771 } 2772 2773 /// ShouldUseExternalRTTIDescriptor - Returns whether the type information for 2774 /// the given type exists somewhere else, and that we should not emit the type 2775 /// information in this translation unit. Assumes that it is not a 2776 /// standard-library type. 2777 static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM, 2778 QualType Ty) { 2779 ASTContext &Context = CGM.getContext(); 2780 2781 // If RTTI is disabled, assume it might be disabled in the 2782 // translation unit that defines any potential key function, too. 2783 if (!Context.getLangOpts().RTTI) return false; 2784 2785 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) { 2786 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 2787 if (!RD->hasDefinition()) 2788 return false; 2789 2790 if (!RD->isDynamicClass()) 2791 return false; 2792 2793 // FIXME: this may need to be reconsidered if the key function 2794 // changes. 2795 // N.B. We must always emit the RTTI data ourselves if there exists a key 2796 // function. 2797 bool IsDLLImport = RD->hasAttr<DLLImportAttr>(); 2798 2799 // Don't import the RTTI but emit it locally. 2800 if (CGM.getTriple().isWindowsGNUEnvironment() && IsDLLImport) 2801 return false; 2802 2803 if (CGM.getVTables().isVTableExternal(RD)) 2804 return IsDLLImport && !CGM.getTriple().isWindowsItaniumEnvironment() 2805 ? false 2806 : true; 2807 2808 if (IsDLLImport) 2809 return true; 2810 } 2811 2812 return false; 2813 } 2814 2815 /// IsIncompleteClassType - Returns whether the given record type is incomplete. 2816 static bool IsIncompleteClassType(const RecordType *RecordTy) { 2817 return !RecordTy->getDecl()->isCompleteDefinition(); 2818 } 2819 2820 /// ContainsIncompleteClassType - Returns whether the given type contains an 2821 /// incomplete class type. This is true if 2822 /// 2823 /// * The given type is an incomplete class type. 2824 /// * The given type is a pointer type whose pointee type contains an 2825 /// incomplete class type. 2826 /// * The given type is a member pointer type whose class is an incomplete 2827 /// class type. 2828 /// * The given type is a member pointer type whoise pointee type contains an 2829 /// incomplete class type. 2830 /// is an indirect or direct pointer to an incomplete class type. 2831 static bool ContainsIncompleteClassType(QualType Ty) { 2832 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) { 2833 if (IsIncompleteClassType(RecordTy)) 2834 return true; 2835 } 2836 2837 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty)) 2838 return ContainsIncompleteClassType(PointerTy->getPointeeType()); 2839 2840 if (const MemberPointerType *MemberPointerTy = 2841 dyn_cast<MemberPointerType>(Ty)) { 2842 // Check if the class type is incomplete. 2843 const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass()); 2844 if (IsIncompleteClassType(ClassType)) 2845 return true; 2846 2847 return ContainsIncompleteClassType(MemberPointerTy->getPointeeType()); 2848 } 2849 2850 return false; 2851 } 2852 2853 // CanUseSingleInheritance - Return whether the given record decl has a "single, 2854 // public, non-virtual base at offset zero (i.e. the derived class is dynamic 2855 // iff the base is)", according to Itanium C++ ABI, 2.95p6b. 2856 static bool CanUseSingleInheritance(const CXXRecordDecl *RD) { 2857 // Check the number of bases. 2858 if (RD->getNumBases() != 1) 2859 return false; 2860 2861 // Get the base. 2862 CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(); 2863 2864 // Check that the base is not virtual. 2865 if (Base->isVirtual()) 2866 return false; 2867 2868 // Check that the base is public. 2869 if (Base->getAccessSpecifier() != AS_public) 2870 return false; 2871 2872 // Check that the class is dynamic iff the base is. 2873 const CXXRecordDecl *BaseDecl = 2874 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 2875 if (!BaseDecl->isEmpty() && 2876 BaseDecl->isDynamicClass() != RD->isDynamicClass()) 2877 return false; 2878 2879 return true; 2880 } 2881 2882 void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty) { 2883 // abi::__class_type_info. 2884 static const char * const ClassTypeInfo = 2885 "_ZTVN10__cxxabiv117__class_type_infoE"; 2886 // abi::__si_class_type_info. 2887 static const char * const SIClassTypeInfo = 2888 "_ZTVN10__cxxabiv120__si_class_type_infoE"; 2889 // abi::__vmi_class_type_info. 2890 static const char * const VMIClassTypeInfo = 2891 "_ZTVN10__cxxabiv121__vmi_class_type_infoE"; 2892 2893 const char *VTableName = nullptr; 2894 2895 switch (Ty->getTypeClass()) { 2896 #define TYPE(Class, Base) 2897 #define ABSTRACT_TYPE(Class, Base) 2898 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class: 2899 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 2900 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 2901 #include "clang/AST/TypeNodes.def" 2902 llvm_unreachable("Non-canonical and dependent types shouldn't get here"); 2903 2904 case Type::LValueReference: 2905 case Type::RValueReference: 2906 llvm_unreachable("References shouldn't get here"); 2907 2908 case Type::Auto: 2909 case Type::DeducedTemplateSpecialization: 2910 llvm_unreachable("Undeduced type shouldn't get here"); 2911 2912 case Type::Pipe: 2913 llvm_unreachable("Pipe types shouldn't get here"); 2914 2915 case Type::Builtin: 2916 // GCC treats vector and complex types as fundamental types. 2917 case Type::Vector: 2918 case Type::ExtVector: 2919 case Type::Complex: 2920 case Type::Atomic: 2921 // FIXME: GCC treats block pointers as fundamental types?! 2922 case Type::BlockPointer: 2923 // abi::__fundamental_type_info. 2924 VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE"; 2925 break; 2926 2927 case Type::ConstantArray: 2928 case Type::IncompleteArray: 2929 case Type::VariableArray: 2930 // abi::__array_type_info. 2931 VTableName = "_ZTVN10__cxxabiv117__array_type_infoE"; 2932 break; 2933 2934 case Type::FunctionNoProto: 2935 case Type::FunctionProto: 2936 // abi::__function_type_info. 2937 VTableName = "_ZTVN10__cxxabiv120__function_type_infoE"; 2938 break; 2939 2940 case Type::Enum: 2941 // abi::__enum_type_info. 2942 VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE"; 2943 break; 2944 2945 case Type::Record: { 2946 const CXXRecordDecl *RD = 2947 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl()); 2948 2949 if (!RD->hasDefinition() || !RD->getNumBases()) { 2950 VTableName = ClassTypeInfo; 2951 } else if (CanUseSingleInheritance(RD)) { 2952 VTableName = SIClassTypeInfo; 2953 } else { 2954 VTableName = VMIClassTypeInfo; 2955 } 2956 2957 break; 2958 } 2959 2960 case Type::ObjCObject: 2961 // Ignore protocol qualifiers. 2962 Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr(); 2963 2964 // Handle id and Class. 2965 if (isa<BuiltinType>(Ty)) { 2966 VTableName = ClassTypeInfo; 2967 break; 2968 } 2969 2970 assert(isa<ObjCInterfaceType>(Ty)); 2971 // Fall through. 2972 2973 case Type::ObjCInterface: 2974 if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) { 2975 VTableName = SIClassTypeInfo; 2976 } else { 2977 VTableName = ClassTypeInfo; 2978 } 2979 break; 2980 2981 case Type::ObjCObjectPointer: 2982 case Type::Pointer: 2983 // abi::__pointer_type_info. 2984 VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE"; 2985 break; 2986 2987 case Type::MemberPointer: 2988 // abi::__pointer_to_member_type_info. 2989 VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE"; 2990 break; 2991 } 2992 2993 llvm::Constant *VTable = 2994 CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy); 2995 CGM.setDSOLocal(cast<llvm::GlobalValue>(VTable->stripPointerCasts())); 2996 2997 llvm::Type *PtrDiffTy = 2998 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType()); 2999 3000 // The vtable address point is 2. 3001 llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2); 3002 VTable = 3003 llvm::ConstantExpr::getInBoundsGetElementPtr(CGM.Int8PtrTy, VTable, Two); 3004 VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy); 3005 3006 Fields.push_back(VTable); 3007 } 3008 3009 /// Return the linkage that the type info and type info name constants 3010 /// should have for the given type. 3011 static std::pair<llvm::GlobalVariable::LinkageTypes, 3012 llvm::GlobalVariable::LinkageTypes> 3013 getTypeInfoLinkage(CodeGenModule &CGM, QualType Ty) { 3014 llvm::GlobalValue::LinkageTypes TypeLinkage = [&]() { 3015 switch (Ty->getLinkage()) { 3016 case NoLinkage: 3017 case InternalLinkage: 3018 case UniqueExternalLinkage: 3019 return llvm::GlobalValue::InternalLinkage; 3020 3021 case VisibleNoLinkage: 3022 case ModuleInternalLinkage: 3023 case ModuleLinkage: 3024 case ExternalLinkage: 3025 // RTTI is not enabled, which means that this type info struct is going 3026 // to be used for exception handling. Give it linkonce_odr linkage. 3027 if (!CGM.getLangOpts().RTTI) 3028 return llvm::GlobalValue::LinkOnceODRLinkage; 3029 3030 if (const RecordType *Record = dyn_cast<RecordType>(Ty)) { 3031 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 3032 if (RD->hasAttr<WeakAttr>()) 3033 return llvm::GlobalValue::WeakODRLinkage; 3034 if (CGM.getTriple().isWindowsItaniumEnvironment()) 3035 if (RD->hasAttr<DLLImportAttr>() && 3036 ShouldUseExternalRTTIDescriptor(CGM, Ty)) 3037 return llvm::GlobalValue::ExternalLinkage; 3038 // MinGW always uses LinkOnceODRLinkage for type info. 3039 if (RD->isCompleteDefinition() && RD->isDynamicClass() && 3040 !CGM.getContext() 3041 .getTargetInfo() 3042 .getTriple() 3043 .isWindowsGNUEnvironment()) 3044 return CGM.getVTableLinkage(RD); 3045 } 3046 3047 return llvm::GlobalValue::LinkOnceODRLinkage; 3048 } 3049 llvm_unreachable("Invalid linkage!"); 3050 }(); 3051 // Itanium C++ ABI 2.9.5p7: 3052 // In addition, it and all of the intermediate abi::__pointer_type_info 3053 // structs in the chain down to the abi::__class_type_info for the 3054 // incomplete class type must be prevented from resolving to the 3055 // corresponding type_info structs for the complete class type, possibly 3056 // by making them local static objects. Finally, a dummy class RTTI is 3057 // generated for the incomplete type that will not resolve to the final 3058 // complete class RTTI (because the latter need not exist), possibly by 3059 // making it a local static object. 3060 if (ContainsIncompleteClassType(Ty)) 3061 return {llvm::GlobalValue::InternalLinkage, TypeLinkage}; 3062 return {TypeLinkage, TypeLinkage}; 3063 } 3064 3065 llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty, bool Force, 3066 bool DLLExport) { 3067 // We want to operate on the canonical type. 3068 Ty = Ty.getCanonicalType(); 3069 3070 // Check if we've already emitted an RTTI descriptor for this type. 3071 SmallString<256> Name; 3072 llvm::raw_svector_ostream Out(Name); 3073 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out); 3074 3075 llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name); 3076 if (OldGV && !OldGV->isDeclaration()) { 3077 assert(!OldGV->hasAvailableExternallyLinkage() && 3078 "available_externally typeinfos not yet implemented"); 3079 3080 return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy); 3081 } 3082 3083 // Check if there is already an external RTTI descriptor for this type. 3084 bool IsStdLib = IsStandardLibraryRTTIDescriptor(Ty); 3085 if (!Force && (IsStdLib || ShouldUseExternalRTTIDescriptor(CGM, Ty))) 3086 return GetAddrOfExternalRTTIDescriptor(Ty); 3087 3088 // Emit the standard library with external linkage. 3089 llvm::GlobalVariable::LinkageTypes InfoLinkage, NameLinkage; 3090 if (IsStdLib) 3091 InfoLinkage = NameLinkage = llvm::GlobalValue::ExternalLinkage; 3092 else { 3093 auto LinkagePair = getTypeInfoLinkage(CGM, Ty); 3094 InfoLinkage = LinkagePair.first; 3095 NameLinkage = LinkagePair.second; 3096 } 3097 // Add the vtable pointer. 3098 BuildVTablePointer(cast<Type>(Ty)); 3099 3100 // And the name. 3101 llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, NameLinkage); 3102 llvm::Constant *TypeNameField; 3103 3104 // If we're supposed to demote the visibility, be sure to set a flag 3105 // to use a string comparison for type_info comparisons. 3106 ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness = 3107 CXXABI.classifyRTTIUniqueness(Ty, NameLinkage); 3108 if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) { 3109 // The flag is the sign bit, which on ARM64 is defined to be clear 3110 // for global pointers. This is very ARM64-specific. 3111 TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty); 3112 llvm::Constant *flag = 3113 llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63); 3114 TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag); 3115 TypeNameField = 3116 llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.Int8PtrTy); 3117 } else { 3118 TypeNameField = llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy); 3119 } 3120 Fields.push_back(TypeNameField); 3121 3122 switch (Ty->getTypeClass()) { 3123 #define TYPE(Class, Base) 3124 #define ABSTRACT_TYPE(Class, Base) 3125 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class: 3126 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 3127 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 3128 #include "clang/AST/TypeNodes.def" 3129 llvm_unreachable("Non-canonical and dependent types shouldn't get here"); 3130 3131 // GCC treats vector types as fundamental types. 3132 case Type::Builtin: 3133 case Type::Vector: 3134 case Type::ExtVector: 3135 case Type::Complex: 3136 case Type::BlockPointer: 3137 // Itanium C++ ABI 2.9.5p4: 3138 // abi::__fundamental_type_info adds no data members to std::type_info. 3139 break; 3140 3141 case Type::LValueReference: 3142 case Type::RValueReference: 3143 llvm_unreachable("References shouldn't get here"); 3144 3145 case Type::Auto: 3146 case Type::DeducedTemplateSpecialization: 3147 llvm_unreachable("Undeduced type shouldn't get here"); 3148 3149 case Type::Pipe: 3150 llvm_unreachable("Pipe type shouldn't get here"); 3151 3152 case Type::ConstantArray: 3153 case Type::IncompleteArray: 3154 case Type::VariableArray: 3155 // Itanium C++ ABI 2.9.5p5: 3156 // abi::__array_type_info adds no data members to std::type_info. 3157 break; 3158 3159 case Type::FunctionNoProto: 3160 case Type::FunctionProto: 3161 // Itanium C++ ABI 2.9.5p5: 3162 // abi::__function_type_info adds no data members to std::type_info. 3163 break; 3164 3165 case Type::Enum: 3166 // Itanium C++ ABI 2.9.5p5: 3167 // abi::__enum_type_info adds no data members to std::type_info. 3168 break; 3169 3170 case Type::Record: { 3171 const CXXRecordDecl *RD = 3172 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl()); 3173 if (!RD->hasDefinition() || !RD->getNumBases()) { 3174 // We don't need to emit any fields. 3175 break; 3176 } 3177 3178 if (CanUseSingleInheritance(RD)) 3179 BuildSIClassTypeInfo(RD); 3180 else 3181 BuildVMIClassTypeInfo(RD); 3182 3183 break; 3184 } 3185 3186 case Type::ObjCObject: 3187 case Type::ObjCInterface: 3188 BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty)); 3189 break; 3190 3191 case Type::ObjCObjectPointer: 3192 BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType()); 3193 break; 3194 3195 case Type::Pointer: 3196 BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType()); 3197 break; 3198 3199 case Type::MemberPointer: 3200 BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty)); 3201 break; 3202 3203 case Type::Atomic: 3204 // No fields, at least for the moment. 3205 break; 3206 } 3207 3208 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields); 3209 3210 llvm::Module &M = CGM.getModule(); 3211 llvm::GlobalVariable *GV = 3212 new llvm::GlobalVariable(M, Init->getType(), 3213 /*Constant=*/true, InfoLinkage, Init, Name); 3214 3215 // If there's already an old global variable, replace it with the new one. 3216 if (OldGV) { 3217 GV->takeName(OldGV); 3218 llvm::Constant *NewPtr = 3219 llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); 3220 OldGV->replaceAllUsesWith(NewPtr); 3221 OldGV->eraseFromParent(); 3222 } 3223 3224 if (CGM.supportsCOMDAT() && GV->isWeakForLinker()) 3225 GV->setComdat(M.getOrInsertComdat(GV->getName())); 3226 3227 // The Itanium ABI specifies that type_info objects must be globally 3228 // unique, with one exception: if the type is an incomplete class 3229 // type or a (possibly indirect) pointer to one. That exception 3230 // affects the general case of comparing type_info objects produced 3231 // by the typeid operator, which is why the comparison operators on 3232 // std::type_info generally use the type_info name pointers instead 3233 // of the object addresses. However, the language's built-in uses 3234 // of RTTI generally require class types to be complete, even when 3235 // manipulating pointers to those class types. This allows the 3236 // implementation of dynamic_cast to rely on address equality tests, 3237 // which is much faster. 3238 3239 // All of this is to say that it's important that both the type_info 3240 // object and the type_info name be uniqued when weakly emitted. 3241 3242 // Give the type_info object and name the formal visibility of the 3243 // type itself. 3244 auto computeVisibility = [&](llvm::GlobalValue::LinkageTypes Linkage) { 3245 if (llvm::GlobalValue::isLocalLinkage(Linkage)) 3246 // If the linkage is local, only default visibility makes sense. 3247 return llvm::GlobalValue::DefaultVisibility; 3248 else if (RTTIUniqueness == ItaniumCXXABI::RUK_NonUniqueHidden) 3249 return llvm::GlobalValue::HiddenVisibility; 3250 else 3251 return CodeGenModule::GetLLVMVisibility(Ty->getVisibility()); 3252 }; 3253 3254 TypeName->setVisibility(computeVisibility(NameLinkage)); 3255 CGM.setDSOLocal(TypeName); 3256 3257 GV->setVisibility(computeVisibility(InfoLinkage)); 3258 CGM.setDSOLocal(GV); 3259 3260 if (CGM.getTriple().isWindowsItaniumEnvironment()) { 3261 auto RD = Ty->getAsCXXRecordDecl(); 3262 if (DLLExport || (RD && RD->hasAttr<DLLExportAttr>())) { 3263 TypeName->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 3264 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 3265 } else if (RD && RD->hasAttr<DLLImportAttr>() && 3266 ShouldUseExternalRTTIDescriptor(CGM, Ty)) { 3267 TypeName->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 3268 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 3269 3270 // Because the typename and the typeinfo are DLL import, convert them to 3271 // declarations rather than definitions. The initializers still need to 3272 // be constructed to calculate the type for the declarations. 3273 TypeName->setInitializer(nullptr); 3274 GV->setInitializer(nullptr); 3275 } 3276 } 3277 3278 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy); 3279 } 3280 3281 /// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info 3282 /// for the given Objective-C object type. 3283 void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) { 3284 // Drop qualifiers. 3285 const Type *T = OT->getBaseType().getTypePtr(); 3286 assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T)); 3287 3288 // The builtin types are abi::__class_type_infos and don't require 3289 // extra fields. 3290 if (isa<BuiltinType>(T)) return; 3291 3292 ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl(); 3293 ObjCInterfaceDecl *Super = Class->getSuperClass(); 3294 3295 // Root classes are also __class_type_info. 3296 if (!Super) return; 3297 3298 QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super); 3299 3300 // Everything else is single inheritance. 3301 llvm::Constant *BaseTypeInfo = 3302 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy); 3303 Fields.push_back(BaseTypeInfo); 3304 } 3305 3306 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single 3307 /// inheritance, according to the Itanium C++ ABI, 2.95p6b. 3308 void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) { 3309 // Itanium C++ ABI 2.9.5p6b: 3310 // It adds to abi::__class_type_info a single member pointing to the 3311 // type_info structure for the base type, 3312 llvm::Constant *BaseTypeInfo = 3313 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType()); 3314 Fields.push_back(BaseTypeInfo); 3315 } 3316 3317 namespace { 3318 /// SeenBases - Contains virtual and non-virtual bases seen when traversing 3319 /// a class hierarchy. 3320 struct SeenBases { 3321 llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases; 3322 llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases; 3323 }; 3324 } 3325 3326 /// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in 3327 /// abi::__vmi_class_type_info. 3328 /// 3329 static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base, 3330 SeenBases &Bases) { 3331 3332 unsigned Flags = 0; 3333 3334 const CXXRecordDecl *BaseDecl = 3335 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 3336 3337 if (Base->isVirtual()) { 3338 // Mark the virtual base as seen. 3339 if (!Bases.VirtualBases.insert(BaseDecl).second) { 3340 // If this virtual base has been seen before, then the class is diamond 3341 // shaped. 3342 Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped; 3343 } else { 3344 if (Bases.NonVirtualBases.count(BaseDecl)) 3345 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat; 3346 } 3347 } else { 3348 // Mark the non-virtual base as seen. 3349 if (!Bases.NonVirtualBases.insert(BaseDecl).second) { 3350 // If this non-virtual base has been seen before, then the class has non- 3351 // diamond shaped repeated inheritance. 3352 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat; 3353 } else { 3354 if (Bases.VirtualBases.count(BaseDecl)) 3355 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat; 3356 } 3357 } 3358 3359 // Walk all bases. 3360 for (const auto &I : BaseDecl->bases()) 3361 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases); 3362 3363 return Flags; 3364 } 3365 3366 static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) { 3367 unsigned Flags = 0; 3368 SeenBases Bases; 3369 3370 // Walk all bases. 3371 for (const auto &I : RD->bases()) 3372 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases); 3373 3374 return Flags; 3375 } 3376 3377 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for 3378 /// classes with bases that do not satisfy the abi::__si_class_type_info 3379 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c. 3380 void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) { 3381 llvm::Type *UnsignedIntLTy = 3382 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy); 3383 3384 // Itanium C++ ABI 2.9.5p6c: 3385 // __flags is a word with flags describing details about the class 3386 // structure, which may be referenced by using the __flags_masks 3387 // enumeration. These flags refer to both direct and indirect bases. 3388 unsigned Flags = ComputeVMIClassTypeInfoFlags(RD); 3389 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags)); 3390 3391 // Itanium C++ ABI 2.9.5p6c: 3392 // __base_count is a word with the number of direct proper base class 3393 // descriptions that follow. 3394 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases())); 3395 3396 if (!RD->getNumBases()) 3397 return; 3398 3399 // Now add the base class descriptions. 3400 3401 // Itanium C++ ABI 2.9.5p6c: 3402 // __base_info[] is an array of base class descriptions -- one for every 3403 // direct proper base. Each description is of the type: 3404 // 3405 // struct abi::__base_class_type_info { 3406 // public: 3407 // const __class_type_info *__base_type; 3408 // long __offset_flags; 3409 // 3410 // enum __offset_flags_masks { 3411 // __virtual_mask = 0x1, 3412 // __public_mask = 0x2, 3413 // __offset_shift = 8 3414 // }; 3415 // }; 3416 3417 // If we're in mingw and 'long' isn't wide enough for a pointer, use 'long 3418 // long' instead of 'long' for __offset_flags. libstdc++abi uses long long on 3419 // LLP64 platforms. 3420 // FIXME: Consider updating libc++abi to match, and extend this logic to all 3421 // LLP64 platforms. 3422 QualType OffsetFlagsTy = CGM.getContext().LongTy; 3423 const TargetInfo &TI = CGM.getContext().getTargetInfo(); 3424 if (TI.getTriple().isOSCygMing() && TI.getPointerWidth(0) > TI.getLongWidth()) 3425 OffsetFlagsTy = CGM.getContext().LongLongTy; 3426 llvm::Type *OffsetFlagsLTy = 3427 CGM.getTypes().ConvertType(OffsetFlagsTy); 3428 3429 for (const auto &Base : RD->bases()) { 3430 // The __base_type member points to the RTTI for the base type. 3431 Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType())); 3432 3433 const CXXRecordDecl *BaseDecl = 3434 cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 3435 3436 int64_t OffsetFlags = 0; 3437 3438 // All but the lower 8 bits of __offset_flags are a signed offset. 3439 // For a non-virtual base, this is the offset in the object of the base 3440 // subobject. For a virtual base, this is the offset in the virtual table of 3441 // the virtual base offset for the virtual base referenced (negative). 3442 CharUnits Offset; 3443 if (Base.isVirtual()) 3444 Offset = 3445 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl); 3446 else { 3447 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD); 3448 Offset = Layout.getBaseClassOffset(BaseDecl); 3449 }; 3450 3451 OffsetFlags = uint64_t(Offset.getQuantity()) << 8; 3452 3453 // The low-order byte of __offset_flags contains flags, as given by the 3454 // masks from the enumeration __offset_flags_masks. 3455 if (Base.isVirtual()) 3456 OffsetFlags |= BCTI_Virtual; 3457 if (Base.getAccessSpecifier() == AS_public) 3458 OffsetFlags |= BCTI_Public; 3459 3460 Fields.push_back(llvm::ConstantInt::get(OffsetFlagsLTy, OffsetFlags)); 3461 } 3462 } 3463 3464 /// Compute the flags for a __pbase_type_info, and remove the corresponding 3465 /// pieces from \p Type. 3466 static unsigned extractPBaseFlags(ASTContext &Ctx, QualType &Type) { 3467 unsigned Flags = 0; 3468 3469 if (Type.isConstQualified()) 3470 Flags |= ItaniumRTTIBuilder::PTI_Const; 3471 if (Type.isVolatileQualified()) 3472 Flags |= ItaniumRTTIBuilder::PTI_Volatile; 3473 if (Type.isRestrictQualified()) 3474 Flags |= ItaniumRTTIBuilder::PTI_Restrict; 3475 Type = Type.getUnqualifiedType(); 3476 3477 // Itanium C++ ABI 2.9.5p7: 3478 // When the abi::__pbase_type_info is for a direct or indirect pointer to an 3479 // incomplete class type, the incomplete target type flag is set. 3480 if (ContainsIncompleteClassType(Type)) 3481 Flags |= ItaniumRTTIBuilder::PTI_Incomplete; 3482 3483 if (auto *Proto = Type->getAs<FunctionProtoType>()) { 3484 if (Proto->isNothrow()) { 3485 Flags |= ItaniumRTTIBuilder::PTI_Noexcept; 3486 Type = Ctx.getFunctionTypeWithExceptionSpec(Type, EST_None); 3487 } 3488 } 3489 3490 return Flags; 3491 } 3492 3493 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, 3494 /// used for pointer types. 3495 void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) { 3496 // Itanium C++ ABI 2.9.5p7: 3497 // __flags is a flag word describing the cv-qualification and other 3498 // attributes of the type pointed to 3499 unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy); 3500 3501 llvm::Type *UnsignedIntLTy = 3502 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy); 3503 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags)); 3504 3505 // Itanium C++ ABI 2.9.5p7: 3506 // __pointee is a pointer to the std::type_info derivation for the 3507 // unqualified type being pointed to. 3508 llvm::Constant *PointeeTypeInfo = 3509 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy); 3510 Fields.push_back(PointeeTypeInfo); 3511 } 3512 3513 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info 3514 /// struct, used for member pointer types. 3515 void 3516 ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) { 3517 QualType PointeeTy = Ty->getPointeeType(); 3518 3519 // Itanium C++ ABI 2.9.5p7: 3520 // __flags is a flag word describing the cv-qualification and other 3521 // attributes of the type pointed to. 3522 unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy); 3523 3524 const RecordType *ClassType = cast<RecordType>(Ty->getClass()); 3525 if (IsIncompleteClassType(ClassType)) 3526 Flags |= PTI_ContainingClassIncomplete; 3527 3528 llvm::Type *UnsignedIntLTy = 3529 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy); 3530 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags)); 3531 3532 // Itanium C++ ABI 2.9.5p7: 3533 // __pointee is a pointer to the std::type_info derivation for the 3534 // unqualified type being pointed to. 3535 llvm::Constant *PointeeTypeInfo = 3536 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy); 3537 Fields.push_back(PointeeTypeInfo); 3538 3539 // Itanium C++ ABI 2.9.5p9: 3540 // __context is a pointer to an abi::__class_type_info corresponding to the 3541 // class type containing the member pointed to 3542 // (e.g., the "A" in "int A::*"). 3543 Fields.push_back( 3544 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(QualType(ClassType, 0))); 3545 } 3546 3547 llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) { 3548 return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty); 3549 } 3550 3551 void ItaniumCXXABI::EmitFundamentalRTTIDescriptor(QualType Type, 3552 bool DLLExport) { 3553 QualType PointerType = getContext().getPointerType(Type); 3554 QualType PointerTypeConst = getContext().getPointerType(Type.withConst()); 3555 ItaniumRTTIBuilder(*this).BuildTypeInfo(Type, /*Force=*/true, DLLExport); 3556 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerType, /*Force=*/true, 3557 DLLExport); 3558 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerTypeConst, /*Force=*/true, 3559 DLLExport); 3560 } 3561 3562 void ItaniumCXXABI::EmitFundamentalRTTIDescriptors(bool DLLExport) { 3563 // Types added here must also be added to TypeInfoIsInStandardLibrary. 3564 QualType FundamentalTypes[] = { 3565 getContext().VoidTy, getContext().NullPtrTy, 3566 getContext().BoolTy, getContext().WCharTy, 3567 getContext().CharTy, getContext().UnsignedCharTy, 3568 getContext().SignedCharTy, getContext().ShortTy, 3569 getContext().UnsignedShortTy, getContext().IntTy, 3570 getContext().UnsignedIntTy, getContext().LongTy, 3571 getContext().UnsignedLongTy, getContext().LongLongTy, 3572 getContext().UnsignedLongLongTy, getContext().Int128Ty, 3573 getContext().UnsignedInt128Ty, getContext().HalfTy, 3574 getContext().FloatTy, getContext().DoubleTy, 3575 getContext().LongDoubleTy, getContext().Float128Ty, 3576 getContext().Char8Ty, getContext().Char16Ty, 3577 getContext().Char32Ty 3578 }; 3579 for (const QualType &FundamentalType : FundamentalTypes) 3580 EmitFundamentalRTTIDescriptor(FundamentalType, DLLExport); 3581 } 3582 3583 /// What sort of uniqueness rules should we use for the RTTI for the 3584 /// given type? 3585 ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness( 3586 QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const { 3587 if (shouldRTTIBeUnique()) 3588 return RUK_Unique; 3589 3590 // It's only necessary for linkonce_odr or weak_odr linkage. 3591 if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage && 3592 Linkage != llvm::GlobalValue::WeakODRLinkage) 3593 return RUK_Unique; 3594 3595 // It's only necessary with default visibility. 3596 if (CanTy->getVisibility() != DefaultVisibility) 3597 return RUK_Unique; 3598 3599 // If we're not required to publish this symbol, hide it. 3600 if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage) 3601 return RUK_NonUniqueHidden; 3602 3603 // If we're required to publish this symbol, as we might be under an 3604 // explicit instantiation, leave it with default visibility but 3605 // enable string-comparisons. 3606 assert(Linkage == llvm::GlobalValue::WeakODRLinkage); 3607 return RUK_NonUniqueVisible; 3608 } 3609 3610 // Find out how to codegen the complete destructor and constructor 3611 namespace { 3612 enum class StructorCodegen { Emit, RAUW, Alias, COMDAT }; 3613 } 3614 static StructorCodegen getCodegenToUse(CodeGenModule &CGM, 3615 const CXXMethodDecl *MD) { 3616 if (!CGM.getCodeGenOpts().CXXCtorDtorAliases) 3617 return StructorCodegen::Emit; 3618 3619 // The complete and base structors are not equivalent if there are any virtual 3620 // bases, so emit separate functions. 3621 if (MD->getParent()->getNumVBases()) 3622 return StructorCodegen::Emit; 3623 3624 GlobalDecl AliasDecl; 3625 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) { 3626 AliasDecl = GlobalDecl(DD, Dtor_Complete); 3627 } else { 3628 const auto *CD = cast<CXXConstructorDecl>(MD); 3629 AliasDecl = GlobalDecl(CD, Ctor_Complete); 3630 } 3631 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl); 3632 3633 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage)) 3634 return StructorCodegen::RAUW; 3635 3636 // FIXME: Should we allow available_externally aliases? 3637 if (!llvm::GlobalAlias::isValidLinkage(Linkage)) 3638 return StructorCodegen::RAUW; 3639 3640 if (llvm::GlobalValue::isWeakForLinker(Linkage)) { 3641 // Only ELF and wasm support COMDATs with arbitrary names (C5/D5). 3642 if (CGM.getTarget().getTriple().isOSBinFormatELF() || 3643 CGM.getTarget().getTriple().isOSBinFormatWasm()) 3644 return StructorCodegen::COMDAT; 3645 return StructorCodegen::Emit; 3646 } 3647 3648 return StructorCodegen::Alias; 3649 } 3650 3651 static void emitConstructorDestructorAlias(CodeGenModule &CGM, 3652 GlobalDecl AliasDecl, 3653 GlobalDecl TargetDecl) { 3654 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl); 3655 3656 StringRef MangledName = CGM.getMangledName(AliasDecl); 3657 llvm::GlobalValue *Entry = CGM.GetGlobalValue(MangledName); 3658 if (Entry && !Entry->isDeclaration()) 3659 return; 3660 3661 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(TargetDecl)); 3662 3663 // Create the alias with no name. 3664 auto *Alias = llvm::GlobalAlias::create(Linkage, "", Aliasee); 3665 3666 // Switch any previous uses to the alias. 3667 if (Entry) { 3668 assert(Entry->getType() == Aliasee->getType() && 3669 "declaration exists with different type"); 3670 Alias->takeName(Entry); 3671 Entry->replaceAllUsesWith(Alias); 3672 Entry->eraseFromParent(); 3673 } else { 3674 Alias->setName(MangledName); 3675 } 3676 3677 // Finally, set up the alias with its proper name and attributes. 3678 CGM.SetCommonAttributes(AliasDecl, Alias); 3679 } 3680 3681 void ItaniumCXXABI::emitCXXStructor(const CXXMethodDecl *MD, 3682 StructorType Type) { 3683 auto *CD = dyn_cast<CXXConstructorDecl>(MD); 3684 const CXXDestructorDecl *DD = CD ? nullptr : cast<CXXDestructorDecl>(MD); 3685 3686 StructorCodegen CGType = getCodegenToUse(CGM, MD); 3687 3688 if (Type == StructorType::Complete) { 3689 GlobalDecl CompleteDecl; 3690 GlobalDecl BaseDecl; 3691 if (CD) { 3692 CompleteDecl = GlobalDecl(CD, Ctor_Complete); 3693 BaseDecl = GlobalDecl(CD, Ctor_Base); 3694 } else { 3695 CompleteDecl = GlobalDecl(DD, Dtor_Complete); 3696 BaseDecl = GlobalDecl(DD, Dtor_Base); 3697 } 3698 3699 if (CGType == StructorCodegen::Alias || CGType == StructorCodegen::COMDAT) { 3700 emitConstructorDestructorAlias(CGM, CompleteDecl, BaseDecl); 3701 return; 3702 } 3703 3704 if (CGType == StructorCodegen::RAUW) { 3705 StringRef MangledName = CGM.getMangledName(CompleteDecl); 3706 auto *Aliasee = CGM.GetAddrOfGlobal(BaseDecl); 3707 CGM.addReplacement(MangledName, Aliasee); 3708 return; 3709 } 3710 } 3711 3712 // The base destructor is equivalent to the base destructor of its 3713 // base class if there is exactly one non-virtual base class with a 3714 // non-trivial destructor, there are no fields with a non-trivial 3715 // destructor, and the body of the destructor is trivial. 3716 if (DD && Type == StructorType::Base && CGType != StructorCodegen::COMDAT && 3717 !CGM.TryEmitBaseDestructorAsAlias(DD)) 3718 return; 3719 3720 // FIXME: The deleting destructor is equivalent to the selected operator 3721 // delete if: 3722 // * either the delete is a destroying operator delete or the destructor 3723 // would be trivial if it weren't virtual, 3724 // * the conversion from the 'this' parameter to the first parameter of the 3725 // destructor is equivalent to a bitcast, 3726 // * the destructor does not have an implicit "this" return, and 3727 // * the operator delete has the same calling convention and IR function type 3728 // as the destructor. 3729 // In such cases we should try to emit the deleting dtor as an alias to the 3730 // selected 'operator delete'. 3731 3732 llvm::Function *Fn = CGM.codegenCXXStructor(MD, Type); 3733 3734 if (CGType == StructorCodegen::COMDAT) { 3735 SmallString<256> Buffer; 3736 llvm::raw_svector_ostream Out(Buffer); 3737 if (DD) 3738 getMangleContext().mangleCXXDtorComdat(DD, Out); 3739 else 3740 getMangleContext().mangleCXXCtorComdat(CD, Out); 3741 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(Out.str()); 3742 Fn->setComdat(C); 3743 } else { 3744 CGM.maybeSetTrivialComdat(*MD, *Fn); 3745 } 3746 } 3747 3748 static llvm::Constant *getBeginCatchFn(CodeGenModule &CGM) { 3749 // void *__cxa_begin_catch(void*); 3750 llvm::FunctionType *FTy = llvm::FunctionType::get( 3751 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false); 3752 3753 return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch"); 3754 } 3755 3756 static llvm::Constant *getEndCatchFn(CodeGenModule &CGM) { 3757 // void __cxa_end_catch(); 3758 llvm::FunctionType *FTy = 3759 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false); 3760 3761 return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch"); 3762 } 3763 3764 static llvm::Constant *getGetExceptionPtrFn(CodeGenModule &CGM) { 3765 // void *__cxa_get_exception_ptr(void*); 3766 llvm::FunctionType *FTy = llvm::FunctionType::get( 3767 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false); 3768 3769 return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr"); 3770 } 3771 3772 namespace { 3773 /// A cleanup to call __cxa_end_catch. In many cases, the caught 3774 /// exception type lets us state definitively that the thrown exception 3775 /// type does not have a destructor. In particular: 3776 /// - Catch-alls tell us nothing, so we have to conservatively 3777 /// assume that the thrown exception might have a destructor. 3778 /// - Catches by reference behave according to their base types. 3779 /// - Catches of non-record types will only trigger for exceptions 3780 /// of non-record types, which never have destructors. 3781 /// - Catches of record types can trigger for arbitrary subclasses 3782 /// of the caught type, so we have to assume the actual thrown 3783 /// exception type might have a throwing destructor, even if the 3784 /// caught type's destructor is trivial or nothrow. 3785 struct CallEndCatch final : EHScopeStack::Cleanup { 3786 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {} 3787 bool MightThrow; 3788 3789 void Emit(CodeGenFunction &CGF, Flags flags) override { 3790 if (!MightThrow) { 3791 CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM)); 3792 return; 3793 } 3794 3795 CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM)); 3796 } 3797 }; 3798 } 3799 3800 /// Emits a call to __cxa_begin_catch and enters a cleanup to call 3801 /// __cxa_end_catch. 3802 /// 3803 /// \param EndMightThrow - true if __cxa_end_catch might throw 3804 static llvm::Value *CallBeginCatch(CodeGenFunction &CGF, 3805 llvm::Value *Exn, 3806 bool EndMightThrow) { 3807 llvm::CallInst *call = 3808 CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn); 3809 3810 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow); 3811 3812 return call; 3813 } 3814 3815 /// A "special initializer" callback for initializing a catch 3816 /// parameter during catch initialization. 3817 static void InitCatchParam(CodeGenFunction &CGF, 3818 const VarDecl &CatchParam, 3819 Address ParamAddr, 3820 SourceLocation Loc) { 3821 // Load the exception from where the landing pad saved it. 3822 llvm::Value *Exn = CGF.getExceptionFromSlot(); 3823 3824 CanQualType CatchType = 3825 CGF.CGM.getContext().getCanonicalType(CatchParam.getType()); 3826 llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType); 3827 3828 // If we're catching by reference, we can just cast the object 3829 // pointer to the appropriate pointer. 3830 if (isa<ReferenceType>(CatchType)) { 3831 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType(); 3832 bool EndCatchMightThrow = CaughtType->isRecordType(); 3833 3834 // __cxa_begin_catch returns the adjusted object pointer. 3835 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow); 3836 3837 // We have no way to tell the personality function that we're 3838 // catching by reference, so if we're catching a pointer, 3839 // __cxa_begin_catch will actually return that pointer by value. 3840 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) { 3841 QualType PointeeType = PT->getPointeeType(); 3842 3843 // When catching by reference, generally we should just ignore 3844 // this by-value pointer and use the exception object instead. 3845 if (!PointeeType->isRecordType()) { 3846 3847 // Exn points to the struct _Unwind_Exception header, which 3848 // we have to skip past in order to reach the exception data. 3849 unsigned HeaderSize = 3850 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException(); 3851 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize); 3852 3853 // However, if we're catching a pointer-to-record type that won't 3854 // work, because the personality function might have adjusted 3855 // the pointer. There's actually no way for us to fully satisfy 3856 // the language/ABI contract here: we can't use Exn because it 3857 // might have the wrong adjustment, but we can't use the by-value 3858 // pointer because it's off by a level of abstraction. 3859 // 3860 // The current solution is to dump the adjusted pointer into an 3861 // alloca, which breaks language semantics (because changing the 3862 // pointer doesn't change the exception) but at least works. 3863 // The better solution would be to filter out non-exact matches 3864 // and rethrow them, but this is tricky because the rethrow 3865 // really needs to be catchable by other sites at this landing 3866 // pad. The best solution is to fix the personality function. 3867 } else { 3868 // Pull the pointer for the reference type off. 3869 llvm::Type *PtrTy = 3870 cast<llvm::PointerType>(LLVMCatchTy)->getElementType(); 3871 3872 // Create the temporary and write the adjusted pointer into it. 3873 Address ExnPtrTmp = 3874 CGF.CreateTempAlloca(PtrTy, CGF.getPointerAlign(), "exn.byref.tmp"); 3875 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy); 3876 CGF.Builder.CreateStore(Casted, ExnPtrTmp); 3877 3878 // Bind the reference to the temporary. 3879 AdjustedExn = ExnPtrTmp.getPointer(); 3880 } 3881 } 3882 3883 llvm::Value *ExnCast = 3884 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref"); 3885 CGF.Builder.CreateStore(ExnCast, ParamAddr); 3886 return; 3887 } 3888 3889 // Scalars and complexes. 3890 TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType); 3891 if (TEK != TEK_Aggregate) { 3892 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false); 3893 3894 // If the catch type is a pointer type, __cxa_begin_catch returns 3895 // the pointer by value. 3896 if (CatchType->hasPointerRepresentation()) { 3897 llvm::Value *CastExn = 3898 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted"); 3899 3900 switch (CatchType.getQualifiers().getObjCLifetime()) { 3901 case Qualifiers::OCL_Strong: 3902 CastExn = CGF.EmitARCRetainNonBlock(CastExn); 3903 // fallthrough 3904 3905 case Qualifiers::OCL_None: 3906 case Qualifiers::OCL_ExplicitNone: 3907 case Qualifiers::OCL_Autoreleasing: 3908 CGF.Builder.CreateStore(CastExn, ParamAddr); 3909 return; 3910 3911 case Qualifiers::OCL_Weak: 3912 CGF.EmitARCInitWeak(ParamAddr, CastExn); 3913 return; 3914 } 3915 llvm_unreachable("bad ownership qualifier!"); 3916 } 3917 3918 // Otherwise, it returns a pointer into the exception object. 3919 3920 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok 3921 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy); 3922 3923 LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType); 3924 LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType); 3925 switch (TEK) { 3926 case TEK_Complex: 3927 CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV, 3928 /*init*/ true); 3929 return; 3930 case TEK_Scalar: { 3931 llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc); 3932 CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true); 3933 return; 3934 } 3935 case TEK_Aggregate: 3936 llvm_unreachable("evaluation kind filtered out!"); 3937 } 3938 llvm_unreachable("bad evaluation kind"); 3939 } 3940 3941 assert(isa<RecordType>(CatchType) && "unexpected catch type!"); 3942 auto catchRD = CatchType->getAsCXXRecordDecl(); 3943 CharUnits caughtExnAlignment = CGF.CGM.getClassPointerAlignment(catchRD); 3944 3945 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok 3946 3947 // Check for a copy expression. If we don't have a copy expression, 3948 // that means a trivial copy is okay. 3949 const Expr *copyExpr = CatchParam.getInit(); 3950 if (!copyExpr) { 3951 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true); 3952 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy), 3953 caughtExnAlignment); 3954 LValue Dest = CGF.MakeAddrLValue(ParamAddr, CatchType); 3955 LValue Src = CGF.MakeAddrLValue(adjustedExn, CatchType); 3956 CGF.EmitAggregateCopy(Dest, Src, CatchType, AggValueSlot::DoesNotOverlap); 3957 return; 3958 } 3959 3960 // We have to call __cxa_get_exception_ptr to get the adjusted 3961 // pointer before copying. 3962 llvm::CallInst *rawAdjustedExn = 3963 CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn); 3964 3965 // Cast that to the appropriate type. 3966 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy), 3967 caughtExnAlignment); 3968 3969 // The copy expression is defined in terms of an OpaqueValueExpr. 3970 // Find it and map it to the adjusted expression. 3971 CodeGenFunction::OpaqueValueMapping 3972 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr), 3973 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType())); 3974 3975 // Call the copy ctor in a terminate scope. 3976 CGF.EHStack.pushTerminate(); 3977 3978 // Perform the copy construction. 3979 CGF.EmitAggExpr(copyExpr, 3980 AggValueSlot::forAddr(ParamAddr, Qualifiers(), 3981 AggValueSlot::IsNotDestructed, 3982 AggValueSlot::DoesNotNeedGCBarriers, 3983 AggValueSlot::IsNotAliased, 3984 AggValueSlot::DoesNotOverlap)); 3985 3986 // Leave the terminate scope. 3987 CGF.EHStack.popTerminate(); 3988 3989 // Undo the opaque value mapping. 3990 opaque.pop(); 3991 3992 // Finally we can call __cxa_begin_catch. 3993 CallBeginCatch(CGF, Exn, true); 3994 } 3995 3996 /// Begins a catch statement by initializing the catch variable and 3997 /// calling __cxa_begin_catch. 3998 void ItaniumCXXABI::emitBeginCatch(CodeGenFunction &CGF, 3999 const CXXCatchStmt *S) { 4000 // We have to be very careful with the ordering of cleanups here: 4001 // C++ [except.throw]p4: 4002 // The destruction [of the exception temporary] occurs 4003 // immediately after the destruction of the object declared in 4004 // the exception-declaration in the handler. 4005 // 4006 // So the precise ordering is: 4007 // 1. Construct catch variable. 4008 // 2. __cxa_begin_catch 4009 // 3. Enter __cxa_end_catch cleanup 4010 // 4. Enter dtor cleanup 4011 // 4012 // We do this by using a slightly abnormal initialization process. 4013 // Delegation sequence: 4014 // - ExitCXXTryStmt opens a RunCleanupsScope 4015 // - EmitAutoVarAlloca creates the variable and debug info 4016 // - InitCatchParam initializes the variable from the exception 4017 // - CallBeginCatch calls __cxa_begin_catch 4018 // - CallBeginCatch enters the __cxa_end_catch cleanup 4019 // - EmitAutoVarCleanups enters the variable destructor cleanup 4020 // - EmitCXXTryStmt emits the code for the catch body 4021 // - EmitCXXTryStmt close the RunCleanupsScope 4022 4023 VarDecl *CatchParam = S->getExceptionDecl(); 4024 if (!CatchParam) { 4025 llvm::Value *Exn = CGF.getExceptionFromSlot(); 4026 CallBeginCatch(CGF, Exn, true); 4027 return; 4028 } 4029 4030 // Emit the local. 4031 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam); 4032 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getLocStart()); 4033 CGF.EmitAutoVarCleanups(var); 4034 } 4035 4036 /// Get or define the following function: 4037 /// void @__clang_call_terminate(i8* %exn) nounwind noreturn 4038 /// This code is used only in C++. 4039 static llvm::Constant *getClangCallTerminateFn(CodeGenModule &CGM) { 4040 llvm::FunctionType *fnTy = 4041 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false); 4042 llvm::Constant *fnRef = CGM.CreateRuntimeFunction( 4043 fnTy, "__clang_call_terminate", llvm::AttributeList(), /*Local=*/true); 4044 4045 llvm::Function *fn = dyn_cast<llvm::Function>(fnRef); 4046 if (fn && fn->empty()) { 4047 fn->setDoesNotThrow(); 4048 fn->setDoesNotReturn(); 4049 4050 // What we really want is to massively penalize inlining without 4051 // forbidding it completely. The difference between that and 4052 // 'noinline' is negligible. 4053 fn->addFnAttr(llvm::Attribute::NoInline); 4054 4055 // Allow this function to be shared across translation units, but 4056 // we don't want it to turn into an exported symbol. 4057 fn->setLinkage(llvm::Function::LinkOnceODRLinkage); 4058 fn->setVisibility(llvm::Function::HiddenVisibility); 4059 if (CGM.supportsCOMDAT()) 4060 fn->setComdat(CGM.getModule().getOrInsertComdat(fn->getName())); 4061 4062 // Set up the function. 4063 llvm::BasicBlock *entry = 4064 llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn); 4065 CGBuilderTy builder(CGM, entry); 4066 4067 // Pull the exception pointer out of the parameter list. 4068 llvm::Value *exn = &*fn->arg_begin(); 4069 4070 // Call __cxa_begin_catch(exn). 4071 llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn); 4072 catchCall->setDoesNotThrow(); 4073 catchCall->setCallingConv(CGM.getRuntimeCC()); 4074 4075 // Call std::terminate(). 4076 llvm::CallInst *termCall = builder.CreateCall(CGM.getTerminateFn()); 4077 termCall->setDoesNotThrow(); 4078 termCall->setDoesNotReturn(); 4079 termCall->setCallingConv(CGM.getRuntimeCC()); 4080 4081 // std::terminate cannot return. 4082 builder.CreateUnreachable(); 4083 } 4084 4085 return fnRef; 4086 } 4087 4088 llvm::CallInst * 4089 ItaniumCXXABI::emitTerminateForUnexpectedException(CodeGenFunction &CGF, 4090 llvm::Value *Exn) { 4091 // In C++, we want to call __cxa_begin_catch() before terminating. 4092 if (Exn) { 4093 assert(CGF.CGM.getLangOpts().CPlusPlus); 4094 return CGF.EmitNounwindRuntimeCall(getClangCallTerminateFn(CGF.CGM), Exn); 4095 } 4096 return CGF.EmitNounwindRuntimeCall(CGF.CGM.getTerminateFn()); 4097 } 4098 4099 std::pair<llvm::Value *, const CXXRecordDecl *> 4100 ItaniumCXXABI::LoadVTablePtr(CodeGenFunction &CGF, Address This, 4101 const CXXRecordDecl *RD) { 4102 return {CGF.GetVTablePtr(This, CGM.Int8PtrTy, RD), RD}; 4103 } 4104