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