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