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