1 //===------- ItaniumCXXABI.cpp - Emit LLVM Code from ASTs for a Module ----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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
13 // http://www.codesourcery.com/public/cxx-abi/abi.html
14 // http://www.codesourcery.com/public/cxx-abi/abi-eh.html
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
19 //===----------------------------------------------------------------------===//
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"
38 using namespace clang;
39 using namespace CodeGen;
42 class ItaniumCXXABI : public CodeGen::CGCXXABI {
43 /// VTables - All the vtables which have been defined.
44 llvm::DenseMap<const CXXRecordDecl *, llvm::GlobalVariable *> VTables;
47 bool UseARMMethodPtrABI;
48 bool UseARMGuardVarABI;
49 bool Use32BitVTableOffsetABI;
51 ItaniumMangleContext &getMangleContext() {
52 return cast<ItaniumMangleContext>(CodeGen::CGCXXABI::getMangleContext());
56 ItaniumCXXABI(CodeGen::CodeGenModule &CGM,
57 bool UseARMMethodPtrABI = false,
58 bool UseARMGuardVarABI = false) :
59 CGCXXABI(CGM), UseARMMethodPtrABI(UseARMMethodPtrABI),
60 UseARMGuardVarABI(UseARMGuardVarABI),
61 Use32BitVTableOffsetABI(false) { }
63 bool classifyReturnType(CGFunctionInfo &FI) const override;
65 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override {
66 // Structures with either a non-trivial destructor or a non-trivial
67 // copy constructor are always indirect.
68 // FIXME: Use canCopyArgument() when it is fixed to handle lazily declared
70 if (RD->hasNonTrivialDestructor() || RD->hasNonTrivialCopyConstructor())
75 bool isThisCompleteObject(GlobalDecl GD) const override {
76 // The Itanium ABI has separate complete-object vs. base-object
77 // variants of both constructors and destructors.
78 if (isa<CXXDestructorDecl>(GD.getDecl())) {
79 switch (GD.getDtorType()) {
88 llvm_unreachable("emitting dtor comdat as function?");
90 llvm_unreachable("bad dtor kind");
92 if (isa<CXXConstructorDecl>(GD.getDecl())) {
93 switch (GD.getCtorType()) {
100 case Ctor_CopyingClosure:
101 case Ctor_DefaultClosure:
102 llvm_unreachable("closure ctors in Itanium ABI?");
105 llvm_unreachable("emitting ctor comdat as function?");
107 llvm_unreachable("bad dtor kind");
114 bool isZeroInitializable(const MemberPointerType *MPT) override;
116 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override;
119 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
122 llvm::Value *&ThisPtrForCall,
123 llvm::Value *MemFnPtr,
124 const MemberPointerType *MPT) override;
127 EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
130 const MemberPointerType *MPT) override;
132 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
134 llvm::Value *Src) override;
135 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
136 llvm::Constant *Src) override;
138 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override;
140 llvm::Constant *EmitMemberFunctionPointer(const CXXMethodDecl *MD) override;
141 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
142 CharUnits offset) override;
143 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override;
144 llvm::Constant *BuildMemberPointer(const CXXMethodDecl *MD,
145 CharUnits ThisAdjustment);
147 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
148 llvm::Value *L, llvm::Value *R,
149 const MemberPointerType *MPT,
150 bool Inequality) override;
152 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
154 const MemberPointerType *MPT) override;
156 void emitVirtualObjectDelete(CodeGenFunction &CGF, const CXXDeleteExpr *DE,
157 Address Ptr, QualType ElementType,
158 const CXXDestructorDecl *Dtor) override;
160 CharUnits getAlignmentOfExnObject() {
161 unsigned Align = CGM.getContext().getTargetInfo().getExnObjectAlignment();
162 return CGM.getContext().toCharUnitsFromBits(Align);
165 void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) override;
166 void emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) override;
168 void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override;
171 emitTerminateForUnexpectedException(CodeGenFunction &CGF,
172 llvm::Value *Exn) override;
174 void EmitFundamentalRTTIDescriptor(QualType Type, bool DLLExport);
175 void EmitFundamentalRTTIDescriptors(bool DLLExport);
176 llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override;
178 getAddrOfCXXCatchHandlerType(QualType Ty,
179 QualType CatchHandlerType) override {
180 return CatchTypeInfo{getAddrOfRTTIDescriptor(Ty), 0};
183 bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override;
184 void EmitBadTypeidCall(CodeGenFunction &CGF) override;
185 llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
187 llvm::Type *StdTypeInfoPtrTy) override;
189 bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
190 QualType SrcRecordTy) override;
192 llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, Address Value,
193 QualType SrcRecordTy, QualType DestTy,
194 QualType DestRecordTy,
195 llvm::BasicBlock *CastEnd) override;
197 llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, Address Value,
198 QualType SrcRecordTy,
199 QualType DestTy) override;
201 bool EmitBadCastCall(CodeGenFunction &CGF) override;
204 GetVirtualBaseClassOffset(CodeGenFunction &CGF, Address This,
205 const CXXRecordDecl *ClassDecl,
206 const CXXRecordDecl *BaseClassDecl) override;
208 void EmitCXXConstructors(const CXXConstructorDecl *D) override;
211 buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
212 SmallVectorImpl<CanQualType> &ArgTys) override;
214 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
215 CXXDtorType DT) const override {
216 // Itanium does not emit any destructor variant as an inline thunk.
217 // Delegating may occur as an optimization, but all variants are either
218 // emitted with external linkage or as linkonce if they are inline and used.
222 void EmitCXXDestructors(const CXXDestructorDecl *D) override;
224 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
225 FunctionArgList &Params) override;
227 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
230 addImplicitConstructorArgs(CodeGenFunction &CGF, const CXXConstructorDecl *D,
231 CXXCtorType Type, bool ForVirtualBase,
232 bool Delegating, CallArgList &Args) override;
234 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
235 CXXDtorType Type, bool ForVirtualBase,
236 bool Delegating, Address This) override;
238 void emitVTableDefinitions(CodeGenVTables &CGVT,
239 const CXXRecordDecl *RD) override;
241 bool isVirtualOffsetNeededForVTableField(CodeGenFunction &CGF,
242 CodeGenFunction::VPtr Vptr) override;
244 bool doStructorsInitializeVPtrs(const CXXRecordDecl *VTableClass) override {
249 getVTableAddressPoint(BaseSubobject Base,
250 const CXXRecordDecl *VTableClass) override;
252 llvm::Value *getVTableAddressPointInStructor(
253 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
254 BaseSubobject Base, const CXXRecordDecl *NearestVBase) override;
256 llvm::Value *getVTableAddressPointInStructorWithVTT(
257 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
258 BaseSubobject Base, const CXXRecordDecl *NearestVBase);
261 getVTableAddressPointForConstExpr(BaseSubobject Base,
262 const CXXRecordDecl *VTableClass) override;
264 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
265 CharUnits VPtrOffset) override;
267 CGCallee getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
268 Address This, llvm::Type *Ty,
269 SourceLocation Loc) override;
271 llvm::Value *EmitVirtualDestructorCall(CodeGenFunction &CGF,
272 const CXXDestructorDecl *Dtor,
273 CXXDtorType DtorType,
275 const CXXMemberCallExpr *CE) override;
277 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
279 bool canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const override;
281 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, GlobalDecl GD,
282 bool ReturnAdjustment) override {
283 // Allow inlining of thunks by emitting them with available_externally
284 // linkage together with vtables when needed.
285 if (ForVTable && !Thunk->hasLocalLinkage())
286 Thunk->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
289 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, Address This,
290 const ThisAdjustment &TA) override;
292 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
293 const ReturnAdjustment &RA) override;
295 size_t getSrcArgforCopyCtor(const CXXConstructorDecl *,
296 FunctionArgList &Args) const override {
297 assert(!Args.empty() && "expected the arglist to not be empty!");
298 return Args.size() - 1;
301 StringRef GetPureVirtualCallName() override { return "__cxa_pure_virtual"; }
302 StringRef GetDeletedVirtualCallName() override
303 { return "__cxa_deleted_virtual"; }
305 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
306 Address InitializeArrayCookie(CodeGenFunction &CGF,
308 llvm::Value *NumElements,
309 const CXXNewExpr *expr,
310 QualType ElementType) override;
311 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
313 CharUnits cookieSize) override;
315 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
316 llvm::GlobalVariable *DeclPtr,
317 bool PerformInit) override;
318 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
319 llvm::Constant *dtor, llvm::Constant *addr) override;
321 llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
323 void EmitThreadLocalInitFuncs(
325 ArrayRef<const VarDecl *> CXXThreadLocals,
326 ArrayRef<llvm::Function *> CXXThreadLocalInits,
327 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) override;
329 bool usesThreadWrapperFunction() const override { return true; }
330 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
331 QualType LValType) override;
333 bool NeedsVTTParameter(GlobalDecl GD) override;
335 /**************************** RTTI Uniqueness ******************************/
338 /// Returns true if the ABI requires RTTI type_info objects to be unique
339 /// across a program.
340 virtual bool shouldRTTIBeUnique() const { return true; }
343 /// What sort of unique-RTTI behavior should we use?
344 enum RTTIUniquenessKind {
345 /// We are guaranteeing, or need to guarantee, that the RTTI string
349 /// We are not guaranteeing uniqueness for the RTTI string, so we
350 /// can demote to hidden visibility but must use string comparisons.
353 /// We are not guaranteeing uniqueness for the RTTI string, so we
354 /// have to use string comparisons, but we also have to emit it with
355 /// non-hidden visibility.
359 /// Return the required visibility status for the given type and linkage in
362 classifyRTTIUniqueness(QualType CanTy,
363 llvm::GlobalValue::LinkageTypes Linkage) const;
364 friend class ItaniumRTTIBuilder;
366 void emitCXXStructor(const CXXMethodDecl *MD, StructorType Type) override;
369 bool hasAnyVirtualInlineFunction(const CXXRecordDecl *RD) const {
370 const auto &VtableLayout =
371 CGM.getItaniumVTableContext().getVTableLayout(RD);
373 for (const auto &VtableComponent : VtableLayout.vtable_components()) {
375 if (!VtableComponent.isUsedFunctionPointerKind())
378 const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
379 if (Method->getCanonicalDecl()->isInlined())
385 bool isVTableHidden(const CXXRecordDecl *RD) const {
386 const auto &VtableLayout =
387 CGM.getItaniumVTableContext().getVTableLayout(RD);
389 for (const auto &VtableComponent : VtableLayout.vtable_components()) {
390 if (VtableComponent.isRTTIKind()) {
391 const CXXRecordDecl *RTTIDecl = VtableComponent.getRTTIDecl();
392 if (RTTIDecl->getVisibility() == Visibility::HiddenVisibility)
394 } else if (VtableComponent.isUsedFunctionPointerKind()) {
395 const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
396 if (Method->getVisibility() == Visibility::HiddenVisibility &&
397 !Method->isDefined())
405 class ARMCXXABI : public ItaniumCXXABI {
407 ARMCXXABI(CodeGen::CodeGenModule &CGM) :
408 ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
409 /* UseARMGuardVarABI = */ true) {}
411 bool HasThisReturn(GlobalDecl GD) const override {
412 return (isa<CXXConstructorDecl>(GD.getDecl()) || (
413 isa<CXXDestructorDecl>(GD.getDecl()) &&
414 GD.getDtorType() != Dtor_Deleting));
417 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV,
418 QualType ResTy) override;
420 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
421 Address InitializeArrayCookie(CodeGenFunction &CGF,
423 llvm::Value *NumElements,
424 const CXXNewExpr *expr,
425 QualType ElementType) override;
426 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, Address allocPtr,
427 CharUnits cookieSize) override;
430 class iOS64CXXABI : public ARMCXXABI {
432 iOS64CXXABI(CodeGen::CodeGenModule &CGM) : ARMCXXABI(CGM) {
433 Use32BitVTableOffsetABI = true;
436 // ARM64 libraries are prepared for non-unique RTTI.
437 bool shouldRTTIBeUnique() const override { return false; }
440 class WebAssemblyCXXABI final : public ItaniumCXXABI {
442 explicit WebAssemblyCXXABI(CodeGen::CodeGenModule &CGM)
443 : ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true,
444 /*UseARMGuardVarABI=*/true) {}
447 bool HasThisReturn(GlobalDecl GD) const override {
448 return isa<CXXConstructorDecl>(GD.getDecl()) ||
449 (isa<CXXDestructorDecl>(GD.getDecl()) &&
450 GD.getDtorType() != Dtor_Deleting);
452 bool canCallMismatchedFunctionType() const override { return false; }
456 CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
457 switch (CGM.getTarget().getCXXABI().getKind()) {
458 // For IR-generation purposes, there's no significant difference
459 // between the ARM and iOS ABIs.
460 case TargetCXXABI::GenericARM:
461 case TargetCXXABI::iOS:
462 case TargetCXXABI::WatchOS:
463 return new ARMCXXABI(CGM);
465 case TargetCXXABI::iOS64:
466 return new iOS64CXXABI(CGM);
468 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
469 // include the other 32-bit ARM oddities: constructor/destructor return values
470 // and array cookies.
471 case TargetCXXABI::GenericAArch64:
472 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
473 /* UseARMGuardVarABI = */ true);
475 case TargetCXXABI::GenericMIPS:
476 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true);
478 case TargetCXXABI::WebAssembly:
479 return new WebAssemblyCXXABI(CGM);
481 case TargetCXXABI::GenericItanium:
482 if (CGM.getContext().getTargetInfo().getTriple().getArch()
483 == llvm::Triple::le32) {
484 // For PNaCl, use ARM-style method pointers so that PNaCl code
485 // does not assume anything about the alignment of function
487 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
488 /* UseARMGuardVarABI = */ false);
490 return new ItaniumCXXABI(CGM);
492 case TargetCXXABI::Microsoft:
493 llvm_unreachable("Microsoft ABI is not Itanium-based");
495 llvm_unreachable("bad ABI kind");
499 ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
500 if (MPT->isMemberDataPointer())
501 return CGM.PtrDiffTy;
502 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy);
505 /// In the Itanium and ARM ABIs, method pointers have the form:
506 /// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
508 /// In the Itanium ABI:
509 /// - method pointers are virtual if (memptr.ptr & 1) is nonzero
510 /// - the this-adjustment is (memptr.adj)
511 /// - the virtual offset is (memptr.ptr - 1)
514 /// - method pointers are virtual if (memptr.adj & 1) is nonzero
515 /// - the this-adjustment is (memptr.adj >> 1)
516 /// - the virtual offset is (memptr.ptr)
517 /// ARM uses 'adj' for the virtual flag because Thumb functions
518 /// may be only single-byte aligned.
520 /// If the member is virtual, the adjusted 'this' pointer points
521 /// to a vtable pointer from which the virtual offset is applied.
523 /// If the member is non-virtual, memptr.ptr is the address of
524 /// the function to call.
525 CGCallee ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(
526 CodeGenFunction &CGF, const Expr *E, Address ThisAddr,
527 llvm::Value *&ThisPtrForCall,
528 llvm::Value *MemFnPtr, const MemberPointerType *MPT) {
529 CGBuilderTy &Builder = CGF.Builder;
531 const FunctionProtoType *FPT =
532 MPT->getPointeeType()->getAs<FunctionProtoType>();
533 const CXXRecordDecl *RD =
534 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
536 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(
537 CGM.getTypes().arrangeCXXMethodType(RD, FPT, /*FD=*/nullptr));
539 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
541 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
542 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
543 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
545 // Extract memptr.adj, which is in the second field.
546 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
548 // Compute the true adjustment.
549 llvm::Value *Adj = RawAdj;
550 if (UseARMMethodPtrABI)
551 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
553 // Apply the adjustment and cast back to the original struct type
555 llvm::Value *This = ThisAddr.getPointer();
556 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
557 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
558 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
559 ThisPtrForCall = This;
561 // Load the function pointer.
562 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
564 // If the LSB in the function pointer is 1, the function pointer points to
565 // a virtual function.
566 llvm::Value *IsVirtual;
567 if (UseARMMethodPtrABI)
568 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
570 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
571 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
572 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
574 // In the virtual path, the adjustment left 'This' pointing to the
575 // vtable of the correct base subobject. The "function pointer" is an
576 // offset within the vtable (+1 for the virtual flag on non-ARM).
577 CGF.EmitBlock(FnVirtual);
579 // Cast the adjusted this to a pointer to vtable pointer and load.
580 llvm::Type *VTableTy = Builder.getInt8PtrTy();
581 CharUnits VTablePtrAlign =
582 CGF.CGM.getDynamicOffsetAlignment(ThisAddr.getAlignment(), RD,
583 CGF.getPointerAlign());
584 llvm::Value *VTable =
585 CGF.GetVTablePtr(Address(This, VTablePtrAlign), VTableTy, RD);
588 // On ARM64, to reserve extra space in virtual member function pointers,
589 // we only pay attention to the low 32 bits of the offset.
590 llvm::Value *VTableOffset = FnAsInt;
591 if (!UseARMMethodPtrABI)
592 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
593 if (Use32BitVTableOffsetABI) {
594 VTableOffset = Builder.CreateTrunc(VTableOffset, CGF.Int32Ty);
595 VTableOffset = Builder.CreateZExt(VTableOffset, CGM.PtrDiffTy);
597 VTable = Builder.CreateGEP(VTable, VTableOffset);
599 // Load the virtual function to call.
600 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
601 llvm::Value *VirtualFn =
602 Builder.CreateAlignedLoad(VTable, CGF.getPointerAlign(),
604 CGF.EmitBranch(FnEnd);
606 // In the non-virtual path, the function pointer is actually a
608 CGF.EmitBlock(FnNonVirtual);
609 llvm::Value *NonVirtualFn =
610 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
613 CGF.EmitBlock(FnEnd);
614 llvm::PHINode *CalleePtr = Builder.CreatePHI(FTy->getPointerTo(), 2);
615 CalleePtr->addIncoming(VirtualFn, FnVirtual);
616 CalleePtr->addIncoming(NonVirtualFn, FnNonVirtual);
618 CGCallee Callee(FPT, CalleePtr);
622 /// Compute an l-value by applying the given pointer-to-member to a
624 llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(
625 CodeGenFunction &CGF, const Expr *E, Address Base, llvm::Value *MemPtr,
626 const MemberPointerType *MPT) {
627 assert(MemPtr->getType() == CGM.PtrDiffTy);
629 CGBuilderTy &Builder = CGF.Builder;
632 Base = Builder.CreateElementBitCast(Base, CGF.Int8Ty);
634 // Apply the offset, which we assume is non-null.
636 Builder.CreateInBoundsGEP(Base.getPointer(), MemPtr, "memptr.offset");
638 // Cast the address to the appropriate pointer type, adopting the
639 // address space of the base pointer.
640 llvm::Type *PType = CGF.ConvertTypeForMem(MPT->getPointeeType())
641 ->getPointerTo(Base.getAddressSpace());
642 return Builder.CreateBitCast(Addr, PType);
645 /// Perform a bitcast, derived-to-base, or base-to-derived member pointer
648 /// Bitcast conversions are always a no-op under Itanium.
650 /// Obligatory offset/adjustment diagram:
651 /// <-- offset --> <-- adjustment -->
652 /// |--------------------------|----------------------|--------------------|
653 /// ^Derived address point ^Base address point ^Member address point
655 /// So when converting a base member pointer to a derived member pointer,
656 /// we add the offset to the adjustment because the address point has
657 /// decreased; and conversely, when converting a derived MP to a base MP
658 /// we subtract the offset from the adjustment because the address point
661 /// The standard forbids (at compile time) conversion to and from
662 /// virtual bases, which is why we don't have to consider them here.
664 /// The standard forbids (at run time) casting a derived MP to a base
665 /// MP when the derived MP does not point to a member of the base.
666 /// This is why -1 is a reasonable choice for null data member
669 ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
672 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
673 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
674 E->getCastKind() == CK_ReinterpretMemberPointer);
676 // Under Itanium, reinterprets don't require any additional processing.
677 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
679 // Use constant emission if we can.
680 if (isa<llvm::Constant>(src))
681 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
683 llvm::Constant *adj = getMemberPointerAdjustment(E);
684 if (!adj) return src;
686 CGBuilderTy &Builder = CGF.Builder;
687 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
689 const MemberPointerType *destTy =
690 E->getType()->castAs<MemberPointerType>();
692 // For member data pointers, this is just a matter of adding the
693 // offset if the source is non-null.
694 if (destTy->isMemberDataPointer()) {
697 dst = Builder.CreateNSWSub(src, adj, "adj");
699 dst = Builder.CreateNSWAdd(src, adj, "adj");
702 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
703 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
704 return Builder.CreateSelect(isNull, src, dst);
707 // The this-adjustment is left-shifted by 1 on ARM.
708 if (UseARMMethodPtrABI) {
709 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
711 adj = llvm::ConstantInt::get(adj->getType(), offset);
714 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
717 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
719 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
721 return Builder.CreateInsertValue(src, dstAdj, 1);
725 ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
726 llvm::Constant *src) {
727 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
728 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
729 E->getCastKind() == CK_ReinterpretMemberPointer);
731 // Under Itanium, reinterprets don't require any additional processing.
732 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
734 // If the adjustment is trivial, we don't need to do anything.
735 llvm::Constant *adj = getMemberPointerAdjustment(E);
736 if (!adj) return src;
738 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
740 const MemberPointerType *destTy =
741 E->getType()->castAs<MemberPointerType>();
743 // For member data pointers, this is just a matter of adding the
744 // offset if the source is non-null.
745 if (destTy->isMemberDataPointer()) {
746 // null maps to null.
747 if (src->isAllOnesValue()) return src;
750 return llvm::ConstantExpr::getNSWSub(src, adj);
752 return llvm::ConstantExpr::getNSWAdd(src, adj);
755 // The this-adjustment is left-shifted by 1 on ARM.
756 if (UseARMMethodPtrABI) {
757 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
759 adj = llvm::ConstantInt::get(adj->getType(), offset);
762 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
763 llvm::Constant *dstAdj;
765 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
767 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
769 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
773 ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
774 // Itanium C++ ABI 2.3:
775 // A NULL pointer is represented as -1.
776 if (MPT->isMemberDataPointer())
777 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
779 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
780 llvm::Constant *Values[2] = { Zero, Zero };
781 return llvm::ConstantStruct::getAnon(Values);
785 ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
787 // Itanium C++ ABI 2.3:
788 // A pointer to data member is an offset from the base address of
789 // the class object containing it, represented as a ptrdiff_t
790 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
794 ItaniumCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) {
795 return BuildMemberPointer(MD, CharUnits::Zero());
798 llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
799 CharUnits ThisAdjustment) {
800 assert(MD->isInstance() && "Member function must not be static!");
801 MD = MD->getCanonicalDecl();
803 CodeGenTypes &Types = CGM.getTypes();
805 // Get the function pointer (or index if this is a virtual function).
806 llvm::Constant *MemPtr[2];
807 if (MD->isVirtual()) {
808 uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
810 const ASTContext &Context = getContext();
811 CharUnits PointerWidth =
812 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
813 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
815 if (UseARMMethodPtrABI) {
816 // ARM C++ ABI 3.2.1:
817 // This ABI specifies that adj contains twice the this
818 // adjustment, plus 1 if the member function is virtual. The
819 // least significant bit of adj then makes exactly the same
820 // discrimination as the least significant bit of ptr does for
822 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
823 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
824 2 * ThisAdjustment.getQuantity() + 1);
826 // Itanium C++ ABI 2.3:
827 // For a virtual function, [the pointer field] is 1 plus the
828 // virtual table offset (in bytes) of the function,
829 // represented as a ptrdiff_t.
830 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
831 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
832 ThisAdjustment.getQuantity());
835 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
837 // Check whether the function has a computable LLVM signature.
838 if (Types.isFuncTypeConvertible(FPT)) {
839 // The function has a computable LLVM signature; use the correct type.
840 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
842 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
843 // function type is incomplete.
846 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
848 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
849 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
850 (UseARMMethodPtrABI ? 2 : 1) *
851 ThisAdjustment.getQuantity());
854 return llvm::ConstantStruct::getAnon(MemPtr);
857 llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
859 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
860 const ValueDecl *MPD = MP.getMemberPointerDecl();
862 return EmitNullMemberPointer(MPT);
864 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
866 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
867 return BuildMemberPointer(MD, ThisAdjustment);
869 CharUnits FieldOffset =
870 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
871 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
874 /// The comparison algorithm is pretty easy: the member pointers are
875 /// the same if they're either bitwise identical *or* both null.
877 /// ARM is different here only because null-ness is more complicated.
879 ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
882 const MemberPointerType *MPT,
884 CGBuilderTy &Builder = CGF.Builder;
886 llvm::ICmpInst::Predicate Eq;
887 llvm::Instruction::BinaryOps And, Or;
889 Eq = llvm::ICmpInst::ICMP_NE;
890 And = llvm::Instruction::Or;
891 Or = llvm::Instruction::And;
893 Eq = llvm::ICmpInst::ICMP_EQ;
894 And = llvm::Instruction::And;
895 Or = llvm::Instruction::Or;
898 // Member data pointers are easy because there's a unique null
899 // value, so it just comes down to bitwise equality.
900 if (MPT->isMemberDataPointer())
901 return Builder.CreateICmp(Eq, L, R);
903 // For member function pointers, the tautologies are more complex.
904 // The Itanium tautology is:
905 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
906 // The ARM tautology is:
907 // (L == R) <==> (L.ptr == R.ptr &&
908 // (L.adj == R.adj ||
909 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
910 // The inequality tautologies have exactly the same structure, except
911 // applying De Morgan's laws.
913 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
914 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
916 // This condition tests whether L.ptr == R.ptr. This must always be
917 // true for equality to hold.
918 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
920 // This condition, together with the assumption that L.ptr == R.ptr,
921 // tests whether the pointers are both null. ARM imposes an extra
923 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
924 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
926 // This condition tests whether L.adj == R.adj. If this isn't
927 // true, the pointers are unequal unless they're both null.
928 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
929 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
930 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
932 // Null member function pointers on ARM clear the low bit of Adj,
933 // so the zero condition has to check that neither low bit is set.
934 if (UseARMMethodPtrABI) {
935 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
937 // Compute (l.adj | r.adj) & 1 and test it against zero.
938 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
939 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
940 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
942 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
945 // Tie together all our conditions.
946 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
947 Result = Builder.CreateBinOp(And, PtrEq, Result,
948 Inequality ? "memptr.ne" : "memptr.eq");
953 ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
955 const MemberPointerType *MPT) {
956 CGBuilderTy &Builder = CGF.Builder;
958 /// For member data pointers, this is just a check against -1.
959 if (MPT->isMemberDataPointer()) {
960 assert(MemPtr->getType() == CGM.PtrDiffTy);
961 llvm::Value *NegativeOne =
962 llvm::Constant::getAllOnesValue(MemPtr->getType());
963 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
966 // In Itanium, a member function pointer is not null if 'ptr' is not null.
967 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
969 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
970 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
972 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
973 // (the virtual bit) is set.
974 if (UseARMMethodPtrABI) {
975 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
976 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
977 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
978 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
980 Result = Builder.CreateOr(Result, IsVirtual);
986 bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
987 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
991 // Return indirectly if we have a non-trivial copy ctor or non-trivial dtor.
992 // FIXME: Use canCopyArgument() when it is fixed to handle lazily declared
994 if (RD->hasNonTrivialDestructor() || RD->hasNonTrivialCopyConstructor()) {
995 auto Align = CGM.getContext().getTypeAlignInChars(FI.getReturnType());
996 FI.getReturnInfo() = ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
1002 /// The Itanium ABI requires non-zero initialization only for data
1003 /// member pointers, for which '0' is a valid offset.
1004 bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
1005 return MPT->isMemberFunctionPointer();
1008 /// The Itanium ABI always places an offset to the complete object
1009 /// at entry -2 in the vtable.
1010 void ItaniumCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
1011 const CXXDeleteExpr *DE,
1013 QualType ElementType,
1014 const CXXDestructorDecl *Dtor) {
1015 bool UseGlobalDelete = DE->isGlobalDelete();
1016 if (UseGlobalDelete) {
1017 // Derive the complete-object pointer, which is what we need
1018 // to pass to the deallocation function.
1020 // Grab the vtable pointer as an intptr_t*.
1022 cast<CXXRecordDecl>(ElementType->getAs<RecordType>()->getDecl());
1023 llvm::Value *VTable =
1024 CGF.GetVTablePtr(Ptr, CGF.IntPtrTy->getPointerTo(), ClassDecl);
1026 // Track back to entry -2 and pull out the offset there.
1027 llvm::Value *OffsetPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
1028 VTable, -2, "complete-offset.ptr");
1029 llvm::Value *Offset =
1030 CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
1032 // Apply the offset.
1033 llvm::Value *CompletePtr =
1034 CGF.Builder.CreateBitCast(Ptr.getPointer(), CGF.Int8PtrTy);
1035 CompletePtr = CGF.Builder.CreateInBoundsGEP(CompletePtr, Offset);
1037 // If we're supposed to call the global delete, make sure we do so
1038 // even if the destructor throws.
1039 CGF.pushCallObjectDeleteCleanup(DE->getOperatorDelete(), CompletePtr,
1043 // FIXME: Provide a source location here even though there's no
1044 // CXXMemberCallExpr for dtor call.
1045 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
1046 EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, /*CE=*/nullptr);
1048 if (UseGlobalDelete)
1049 CGF.PopCleanupBlock();
1052 void ItaniumCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
1053 // void __cxa_rethrow();
1055 llvm::FunctionType *FTy =
1056 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
1058 llvm::Constant *Fn = CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
1061 CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, None);
1063 CGF.EmitRuntimeCallOrInvoke(Fn);
1066 static llvm::Constant *getAllocateExceptionFn(CodeGenModule &CGM) {
1067 // void *__cxa_allocate_exception(size_t thrown_size);
1069 llvm::FunctionType *FTy =
1070 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.SizeTy, /*IsVarArgs=*/false);
1072 return CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
1075 static llvm::Constant *getThrowFn(CodeGenModule &CGM) {
1076 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
1077 // void (*dest) (void *));
1079 llvm::Type *Args[3] = { CGM.Int8PtrTy, CGM.Int8PtrTy, CGM.Int8PtrTy };
1080 llvm::FunctionType *FTy =
1081 llvm::FunctionType::get(CGM.VoidTy, Args, /*IsVarArgs=*/false);
1083 return CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
1086 void ItaniumCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
1087 QualType ThrowType = E->getSubExpr()->getType();
1088 // Now allocate the exception object.
1089 llvm::Type *SizeTy = CGF.ConvertType(getContext().getSizeType());
1090 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
1092 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(CGM);
1093 llvm::CallInst *ExceptionPtr = CGF.EmitNounwindRuntimeCall(
1094 AllocExceptionFn, llvm::ConstantInt::get(SizeTy, TypeSize), "exception");
1096 CharUnits ExnAlign = getAlignmentOfExnObject();
1097 CGF.EmitAnyExprToExn(E->getSubExpr(), Address(ExceptionPtr, ExnAlign));
1099 // Now throw the exception.
1100 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
1103 // The address of the destructor. If the exception type has a
1104 // trivial destructor (or isn't a record), we just pass null.
1105 llvm::Constant *Dtor = nullptr;
1106 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
1107 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
1108 if (!Record->hasTrivialDestructor()) {
1109 CXXDestructorDecl *DtorD = Record->getDestructor();
1110 Dtor = CGM.getAddrOfCXXStructor(DtorD, StructorType::Complete);
1111 Dtor = llvm::ConstantExpr::getBitCast(Dtor, CGM.Int8PtrTy);
1114 if (!Dtor) Dtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);
1116 llvm::Value *args[] = { ExceptionPtr, TypeInfo, Dtor };
1117 CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(CGM), args);
1120 static llvm::Constant *getItaniumDynamicCastFn(CodeGenFunction &CGF) {
1121 // void *__dynamic_cast(const void *sub,
1122 // const abi::__class_type_info *src,
1123 // const abi::__class_type_info *dst,
1124 // std::ptrdiff_t src2dst_offset);
1126 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
1127 llvm::Type *PtrDiffTy =
1128 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1130 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
1132 llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false);
1134 // Mark the function as nounwind readonly.
1135 llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind,
1136 llvm::Attribute::ReadOnly };
1137 llvm::AttributeList Attrs = llvm::AttributeList::get(
1138 CGF.getLLVMContext(), llvm::AttributeList::FunctionIndex, FuncAttrs);
1140 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs);
1143 static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
1144 // void __cxa_bad_cast();
1145 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1146 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1149 /// \brief Compute the src2dst_offset hint as described in the
1150 /// Itanium C++ ABI [2.9.7]
1151 static CharUnits computeOffsetHint(ASTContext &Context,
1152 const CXXRecordDecl *Src,
1153 const CXXRecordDecl *Dst) {
1154 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1155 /*DetectVirtual=*/false);
1157 // If Dst is not derived from Src we can skip the whole computation below and
1158 // return that Src is not a public base of Dst. Record all inheritance paths.
1159 if (!Dst->isDerivedFrom(Src, Paths))
1160 return CharUnits::fromQuantity(-2ULL);
1162 unsigned NumPublicPaths = 0;
1165 // Now walk all possible inheritance paths.
1166 for (const CXXBasePath &Path : Paths) {
1167 if (Path.Access != AS_public) // Ignore non-public inheritance.
1172 for (const CXXBasePathElement &PathElement : Path) {
1173 // If the path contains a virtual base class we can't give any hint.
1175 if (PathElement.Base->isVirtual())
1176 return CharUnits::fromQuantity(-1ULL);
1178 if (NumPublicPaths > 1) // Won't use offsets, skip computation.
1181 // Accumulate the base class offsets.
1182 const ASTRecordLayout &L = Context.getASTRecordLayout(PathElement.Class);
1183 Offset += L.getBaseClassOffset(
1184 PathElement.Base->getType()->getAsCXXRecordDecl());
1188 // -2: Src is not a public base of Dst.
1189 if (NumPublicPaths == 0)
1190 return CharUnits::fromQuantity(-2ULL);
1192 // -3: Src is a multiple public base type but never a virtual base type.
1193 if (NumPublicPaths > 1)
1194 return CharUnits::fromQuantity(-3ULL);
1196 // Otherwise, the Src type is a unique public nonvirtual base type of Dst.
1197 // Return the offset of Src from the origin of Dst.
1201 static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
1202 // void __cxa_bad_typeid();
1203 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1205 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1208 bool ItaniumCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
1209 QualType SrcRecordTy) {
1213 void ItaniumCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
1214 llvm::Value *Fn = getBadTypeidFn(CGF);
1215 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1216 CGF.Builder.CreateUnreachable();
1219 llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF,
1220 QualType SrcRecordTy,
1222 llvm::Type *StdTypeInfoPtrTy) {
1224 cast<CXXRecordDecl>(SrcRecordTy->getAs<RecordType>()->getDecl());
1225 llvm::Value *Value =
1226 CGF.GetVTablePtr(ThisPtr, StdTypeInfoPtrTy->getPointerTo(), ClassDecl);
1228 // Load the type info.
1229 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
1230 return CGF.Builder.CreateAlignedLoad(Value, CGF.getPointerAlign());
1233 bool ItaniumCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
1234 QualType SrcRecordTy) {
1238 llvm::Value *ItaniumCXXABI::EmitDynamicCastCall(
1239 CodeGenFunction &CGF, Address ThisAddr, QualType SrcRecordTy,
1240 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
1241 llvm::Type *PtrDiffLTy =
1242 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1243 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1245 llvm::Value *SrcRTTI =
1246 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1247 llvm::Value *DestRTTI =
1248 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1250 // Compute the offset hint.
1251 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
1252 const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
1253 llvm::Value *OffsetHint = llvm::ConstantInt::get(
1255 computeOffsetHint(CGF.getContext(), SrcDecl, DestDecl).getQuantity());
1257 // Emit the call to __dynamic_cast.
1258 llvm::Value *Value = ThisAddr.getPointer();
1259 Value = CGF.EmitCastToVoidPtr(Value);
1261 llvm::Value *args[] = {Value, SrcRTTI, DestRTTI, OffsetHint};
1262 Value = CGF.EmitNounwindRuntimeCall(getItaniumDynamicCastFn(CGF), args);
1263 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1265 /// C++ [expr.dynamic.cast]p9:
1266 /// A failed cast to reference type throws std::bad_cast
1267 if (DestTy->isReferenceType()) {
1268 llvm::BasicBlock *BadCastBlock =
1269 CGF.createBasicBlock("dynamic_cast.bad_cast");
1271 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1272 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1274 CGF.EmitBlock(BadCastBlock);
1275 EmitBadCastCall(CGF);
1281 llvm::Value *ItaniumCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF,
1283 QualType SrcRecordTy,
1285 llvm::Type *PtrDiffLTy =
1286 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1287 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1290 cast<CXXRecordDecl>(SrcRecordTy->getAs<RecordType>()->getDecl());
1291 // Get the vtable pointer.
1292 llvm::Value *VTable = CGF.GetVTablePtr(ThisAddr, PtrDiffLTy->getPointerTo(),
1295 // Get the offset-to-top from the vtable.
1296 llvm::Value *OffsetToTop =
1297 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
1299 CGF.Builder.CreateAlignedLoad(OffsetToTop, CGF.getPointerAlign(),
1302 // Finally, add the offset to the pointer.
1303 llvm::Value *Value = ThisAddr.getPointer();
1304 Value = CGF.EmitCastToVoidPtr(Value);
1305 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1307 return CGF.Builder.CreateBitCast(Value, DestLTy);
1310 bool ItaniumCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1311 llvm::Value *Fn = getBadCastFn(CGF);
1312 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1313 CGF.Builder.CreateUnreachable();
1318 ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
1320 const CXXRecordDecl *ClassDecl,
1321 const CXXRecordDecl *BaseClassDecl) {
1322 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy, ClassDecl);
1323 CharUnits VBaseOffsetOffset =
1324 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
1327 llvm::Value *VBaseOffsetPtr =
1328 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1329 "vbase.offset.ptr");
1330 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
1331 CGM.PtrDiffTy->getPointerTo());
1333 llvm::Value *VBaseOffset =
1334 CGF.Builder.CreateAlignedLoad(VBaseOffsetPtr, CGF.getPointerAlign(),
1340 void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1341 // Just make sure we're in sync with TargetCXXABI.
1342 assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
1344 // The constructor used for constructing this as a base class;
1345 // ignores virtual bases.
1346 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
1348 // The constructor used for constructing this as a complete class;
1349 // constructs the virtual bases, then calls the base constructor.
1350 if (!D->getParent()->isAbstract()) {
1351 // We don't need to emit the complete ctor if the class is abstract.
1352 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1356 CGCXXABI::AddedStructorArgs
1357 ItaniumCXXABI::buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
1358 SmallVectorImpl<CanQualType> &ArgTys) {
1359 ASTContext &Context = getContext();
1361 // All parameters are already in place except VTT, which goes after 'this'.
1362 // These are Clang types, so we don't need to worry about sret yet.
1364 // Check if we need to add a VTT parameter (which has type void **).
1365 if (T == StructorType::Base && MD->getParent()->getNumVBases() != 0) {
1366 ArgTys.insert(ArgTys.begin() + 1,
1367 Context.getPointerType(Context.VoidPtrTy));
1368 return AddedStructorArgs::prefix(1);
1370 return AddedStructorArgs{};
1373 void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
1374 // The destructor used for destructing this as a base class; ignores
1376 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
1378 // The destructor used for destructing this as a most-derived class;
1379 // call the base destructor and then destructs any virtual bases.
1380 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
1382 // The destructor in a virtual table is always a 'deleting'
1383 // destructor, which calls the complete destructor and then uses the
1384 // appropriate operator delete.
1386 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
1389 void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1391 FunctionArgList &Params) {
1392 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
1393 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
1395 // Check if we need a VTT parameter as well.
1396 if (NeedsVTTParameter(CGF.CurGD)) {
1397 ASTContext &Context = getContext();
1399 // FIXME: avoid the fake decl
1400 QualType T = Context.getPointerType(Context.VoidPtrTy);
1401 ImplicitParamDecl *VTTDecl
1402 = ImplicitParamDecl::Create(Context, nullptr, MD->getLocation(),
1403 &Context.Idents.get("vtt"), T);
1404 Params.insert(Params.begin() + 1, VTTDecl);
1405 getStructorImplicitParamDecl(CGF) = VTTDecl;
1409 void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
1410 // Naked functions have no prolog.
1411 if (CGF.CurFuncDecl && CGF.CurFuncDecl->hasAttr<NakedAttr>())
1414 /// Initialize the 'this' slot.
1417 /// Initialize the 'vtt' slot if needed.
1418 if (getStructorImplicitParamDecl(CGF)) {
1419 getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
1420 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
1423 /// If this is a function that the ABI specifies returns 'this', initialize
1424 /// the return slot to 'this' at the start of the function.
1426 /// Unlike the setting of return types, this is done within the ABI
1427 /// implementation instead of by clients of CGCXXABI because:
1428 /// 1) getThisValue is currently protected
1429 /// 2) in theory, an ABI could implement 'this' returns some other way;
1430 /// HasThisReturn only specifies a contract, not the implementation
1431 if (HasThisReturn(CGF.CurGD))
1432 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
1435 CGCXXABI::AddedStructorArgs ItaniumCXXABI::addImplicitConstructorArgs(
1436 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1437 bool ForVirtualBase, bool Delegating, CallArgList &Args) {
1438 if (!NeedsVTTParameter(GlobalDecl(D, Type)))
1439 return AddedStructorArgs{};
1441 // Insert the implicit 'vtt' argument as the second argument.
1443 CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating);
1444 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1445 Args.insert(Args.begin() + 1,
1446 CallArg(RValue::get(VTT), VTTTy, /*needscopy=*/false));
1447 return AddedStructorArgs::prefix(1); // Added one arg.
1450 void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1451 const CXXDestructorDecl *DD,
1452 CXXDtorType Type, bool ForVirtualBase,
1453 bool Delegating, Address This) {
1454 GlobalDecl GD(DD, Type);
1455 llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating);
1456 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1459 if (getContext().getLangOpts().AppleKext &&
1460 Type != Dtor_Base && DD->isVirtual())
1461 Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent());
1464 CGCallee::forDirect(CGM.getAddrOfCXXStructor(DD, getFromDtorType(Type)),
1467 CGF.EmitCXXMemberOrOperatorCall(DD, Callee, ReturnValueSlot(),
1468 This.getPointer(), VTT, VTTTy,
1472 void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1473 const CXXRecordDecl *RD) {
1474 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
1475 if (VTable->hasInitializer())
1478 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
1479 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
1480 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
1481 llvm::Constant *RTTI =
1482 CGM.GetAddrOfRTTIDescriptor(CGM.getContext().getTagDeclType(RD));
1484 // Create and set the initializer.
1485 ConstantInitBuilder Builder(CGM);
1486 auto Components = Builder.beginStruct();
1487 CGVT.createVTableInitializer(Components, VTLayout, RTTI);
1488 Components.finishAndSetAsInitializer(VTable);
1490 // Set the correct linkage.
1491 VTable->setLinkage(Linkage);
1493 if (CGM.supportsCOMDAT() && VTable->isWeakForLinker())
1494 VTable->setComdat(CGM.getModule().getOrInsertComdat(VTable->getName()));
1496 // Set the right visibility.
1497 CGM.setGlobalVisibility(VTable, RD);
1499 // Use pointer alignment for the vtable. Otherwise we would align them based
1500 // on the size of the initializer which doesn't make sense as only single
1502 unsigned PAlign = CGM.getTarget().getPointerAlign(0);
1503 VTable->setAlignment(getContext().toCharUnitsFromBits(PAlign).getQuantity());
1505 // If this is the magic class __cxxabiv1::__fundamental_type_info,
1506 // we will emit the typeinfo for the fundamental types. This is the
1507 // same behaviour as GCC.
1508 const DeclContext *DC = RD->getDeclContext();
1509 if (RD->getIdentifier() &&
1510 RD->getIdentifier()->isStr("__fundamental_type_info") &&
1511 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
1512 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
1513 DC->getParent()->isTranslationUnit())
1514 EmitFundamentalRTTIDescriptors(RD->hasAttr<DLLExportAttr>());
1516 if (!VTable->isDeclarationForLinker())
1517 CGM.EmitVTableTypeMetadata(VTable, VTLayout);
1520 bool ItaniumCXXABI::isVirtualOffsetNeededForVTableField(
1521 CodeGenFunction &CGF, CodeGenFunction::VPtr Vptr) {
1522 if (Vptr.NearestVBase == nullptr)
1524 return NeedsVTTParameter(CGF.CurGD);
1527 llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
1528 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1529 const CXXRecordDecl *NearestVBase) {
1531 if ((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
1532 NeedsVTTParameter(CGF.CurGD)) {
1533 return getVTableAddressPointInStructorWithVTT(CGF, VTableClass, Base,
1536 return getVTableAddressPoint(Base, VTableClass);
1540 ItaniumCXXABI::getVTableAddressPoint(BaseSubobject Base,
1541 const CXXRecordDecl *VTableClass) {
1542 llvm::GlobalValue *VTable = getAddrOfVTable(VTableClass, CharUnits());
1544 // Find the appropriate vtable within the vtable group, and the address point
1545 // within that vtable.
1546 VTableLayout::AddressPointLocation AddressPoint =
1547 CGM.getItaniumVTableContext()
1548 .getVTableLayout(VTableClass)
1549 .getAddressPoint(Base);
1550 llvm::Value *Indices[] = {
1551 llvm::ConstantInt::get(CGM.Int32Ty, 0),
1552 llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint.VTableIndex),
1553 llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint.AddressPointIndex),
1556 return llvm::ConstantExpr::getGetElementPtr(VTable->getValueType(), VTable,
1557 Indices, /*InBounds=*/true,
1558 /*InRangeIndex=*/1);
1561 llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructorWithVTT(
1562 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1563 const CXXRecordDecl *NearestVBase) {
1564 assert((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
1565 NeedsVTTParameter(CGF.CurGD) && "This class doesn't have VTT");
1567 // Get the secondary vpointer index.
1568 uint64_t VirtualPointerIndex =
1569 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1572 llvm::Value *VTT = CGF.LoadCXXVTT();
1573 if (VirtualPointerIndex)
1574 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1576 // And load the address point from the VTT.
1577 return CGF.Builder.CreateAlignedLoad(VTT, CGF.getPointerAlign());
1580 llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
1581 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1582 return getVTableAddressPoint(Base, VTableClass);
1585 llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1586 CharUnits VPtrOffset) {
1587 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
1589 llvm::GlobalVariable *&VTable = VTables[RD];
1593 // Queue up this vtable for possible deferred emission.
1594 CGM.addDeferredVTable(RD);
1596 SmallString<256> Name;
1597 llvm::raw_svector_ostream Out(Name);
1598 getMangleContext().mangleCXXVTable(RD, Out);
1600 const VTableLayout &VTLayout =
1601 CGM.getItaniumVTableContext().getVTableLayout(RD);
1602 llvm::Type *VTableType = CGM.getVTables().getVTableType(VTLayout);
1604 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
1605 Name, VTableType, llvm::GlobalValue::ExternalLinkage);
1606 VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1608 if (RD->hasAttr<DLLImportAttr>())
1609 VTable->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1610 else if (RD->hasAttr<DLLExportAttr>())
1611 VTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1616 CGCallee ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1620 SourceLocation Loc) {
1621 GD = GD.getCanonicalDecl();
1622 Ty = Ty->getPointerTo()->getPointerTo();
1623 auto *MethodDecl = cast<CXXMethodDecl>(GD.getDecl());
1624 llvm::Value *VTable = CGF.GetVTablePtr(This, Ty, MethodDecl->getParent());
1626 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
1628 if (CGF.ShouldEmitVTableTypeCheckedLoad(MethodDecl->getParent())) {
1629 VFunc = CGF.EmitVTableTypeCheckedLoad(
1630 MethodDecl->getParent(), VTable,
1631 VTableIndex * CGM.getContext().getTargetInfo().getPointerWidth(0) / 8);
1633 CGF.EmitTypeMetadataCodeForVCall(MethodDecl->getParent(), VTable, Loc);
1635 llvm::Value *VFuncPtr =
1636 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
1638 CGF.Builder.CreateAlignedLoad(VFuncPtr, CGF.getPointerAlign());
1640 // Add !invariant.load md to virtual function load to indicate that
1641 // function didn't change inside vtable.
1642 // It's safe to add it without -fstrict-vtable-pointers, but it would not
1643 // help in devirtualization because it will only matter if we will have 2
1644 // the same virtual function loads from the same vtable load, which won't
1645 // happen without enabled devirtualization with -fstrict-vtable-pointers.
1646 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1647 CGM.getCodeGenOpts().StrictVTablePointers)
1648 VFuncLoad->setMetadata(
1649 llvm::LLVMContext::MD_invariant_load,
1650 llvm::MDNode::get(CGM.getLLVMContext(),
1651 llvm::ArrayRef<llvm::Metadata *>()));
1655 CGCallee Callee(MethodDecl, VFunc);
1659 llvm::Value *ItaniumCXXABI::EmitVirtualDestructorCall(
1660 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
1661 Address This, const CXXMemberCallExpr *CE) {
1662 assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
1663 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1665 const CGFunctionInfo *FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
1666 Dtor, getFromDtorType(DtorType));
1667 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
1669 getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, DtorType), This, Ty,
1670 CE ? CE->getLocStart() : SourceLocation());
1672 CGF.EmitCXXMemberOrOperatorCall(Dtor, Callee, ReturnValueSlot(),
1673 This.getPointer(), /*ImplicitParam=*/nullptr,
1674 QualType(), CE, nullptr);
1678 void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
1679 CodeGenVTables &VTables = CGM.getVTables();
1680 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
1681 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
1684 bool ItaniumCXXABI::canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const {
1685 // We don't emit available_externally vtables if we are in -fapple-kext mode
1686 // because kext mode does not permit devirtualization.
1687 if (CGM.getLangOpts().AppleKext)
1690 // If we don't have any inline virtual functions, and if vtable is not hidden,
1691 // then we are safe to emit available_externally copy of vtable.
1692 // FIXME we can still emit a copy of the vtable if we
1693 // can emit definition of the inline functions.
1694 return !hasAnyVirtualInlineFunction(RD) && !isVTableHidden(RD);
1696 static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
1698 int64_t NonVirtualAdjustment,
1699 int64_t VirtualAdjustment,
1700 bool IsReturnAdjustment) {
1701 if (!NonVirtualAdjustment && !VirtualAdjustment)
1702 return InitialPtr.getPointer();
1704 Address V = CGF.Builder.CreateElementBitCast(InitialPtr, CGF.Int8Ty);
1706 // In a base-to-derived cast, the non-virtual adjustment is applied first.
1707 if (NonVirtualAdjustment && !IsReturnAdjustment) {
1708 V = CGF.Builder.CreateConstInBoundsByteGEP(V,
1709 CharUnits::fromQuantity(NonVirtualAdjustment));
1712 // Perform the virtual adjustment if we have one.
1713 llvm::Value *ResultPtr;
1714 if (VirtualAdjustment) {
1715 llvm::Type *PtrDiffTy =
1716 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1718 Address VTablePtrPtr = CGF.Builder.CreateElementBitCast(V, CGF.Int8PtrTy);
1719 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
1721 llvm::Value *OffsetPtr =
1722 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
1724 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
1726 // Load the adjustment offset from the vtable.
1727 llvm::Value *Offset =
1728 CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
1730 // Adjust our pointer.
1731 ResultPtr = CGF.Builder.CreateInBoundsGEP(V.getPointer(), Offset);
1733 ResultPtr = V.getPointer();
1736 // In a derived-to-base conversion, the non-virtual adjustment is
1738 if (NonVirtualAdjustment && IsReturnAdjustment) {
1739 ResultPtr = CGF.Builder.CreateConstInBoundsGEP1_64(ResultPtr,
1740 NonVirtualAdjustment);
1743 // Cast back to the original type.
1744 return CGF.Builder.CreateBitCast(ResultPtr, InitialPtr.getType());
1747 llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
1749 const ThisAdjustment &TA) {
1750 return performTypeAdjustment(CGF, This, TA.NonVirtual,
1751 TA.Virtual.Itanium.VCallOffsetOffset,
1752 /*IsReturnAdjustment=*/false);
1756 ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
1757 const ReturnAdjustment &RA) {
1758 return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
1759 RA.Virtual.Itanium.VBaseOffsetOffset,
1760 /*IsReturnAdjustment=*/true);
1763 void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1764 RValue RV, QualType ResultType) {
1765 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1766 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
1768 // Destructor thunks in the ARM ABI have indeterminate results.
1769 llvm::Type *T = CGF.ReturnValue.getElementType();
1770 RValue Undef = RValue::get(llvm::UndefValue::get(T));
1771 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
1774 /************************** Array allocation cookies **************************/
1776 CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1777 // The array cookie is a size_t; pad that up to the element alignment.
1778 // The cookie is actually right-justified in that space.
1779 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
1780 CGM.getContext().getTypeAlignInChars(elementType));
1783 Address ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1785 llvm::Value *NumElements,
1786 const CXXNewExpr *expr,
1787 QualType ElementType) {
1788 assert(requiresArrayCookie(expr));
1790 unsigned AS = NewPtr.getAddressSpace();
1792 ASTContext &Ctx = getContext();
1793 CharUnits SizeSize = CGF.getSizeSize();
1795 // The size of the cookie.
1796 CharUnits CookieSize =
1797 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
1798 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
1800 // Compute an offset to the cookie.
1801 Address CookiePtr = NewPtr;
1802 CharUnits CookieOffset = CookieSize - SizeSize;
1803 if (!CookieOffset.isZero())
1804 CookiePtr = CGF.Builder.CreateConstInBoundsByteGEP(CookiePtr, CookieOffset);
1806 // Write the number of elements into the appropriate slot.
1807 Address NumElementsPtr =
1808 CGF.Builder.CreateElementBitCast(CookiePtr, CGF.SizeTy);
1809 llvm::Instruction *SI = CGF.Builder.CreateStore(NumElements, NumElementsPtr);
1811 // Handle the array cookie specially in ASan.
1812 if (CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) && AS == 0 &&
1813 expr->getOperatorNew()->isReplaceableGlobalAllocationFunction()) {
1814 // The store to the CookiePtr does not need to be instrumented.
1815 CGM.getSanitizerMetadata()->disableSanitizerForInstruction(SI);
1816 llvm::FunctionType *FTy =
1817 llvm::FunctionType::get(CGM.VoidTy, NumElementsPtr.getType(), false);
1819 CGM.CreateRuntimeFunction(FTy, "__asan_poison_cxx_array_cookie");
1820 CGF.Builder.CreateCall(F, NumElementsPtr.getPointer());
1823 // Finally, compute a pointer to the actual data buffer by skipping
1824 // over the cookie completely.
1825 return CGF.Builder.CreateConstInBoundsByteGEP(NewPtr, CookieSize);
1828 llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1830 CharUnits cookieSize) {
1831 // The element size is right-justified in the cookie.
1832 Address numElementsPtr = allocPtr;
1833 CharUnits numElementsOffset = cookieSize - CGF.getSizeSize();
1834 if (!numElementsOffset.isZero())
1836 CGF.Builder.CreateConstInBoundsByteGEP(numElementsPtr, numElementsOffset);
1838 unsigned AS = allocPtr.getAddressSpace();
1839 numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
1840 if (!CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) || AS != 0)
1841 return CGF.Builder.CreateLoad(numElementsPtr);
1842 // In asan mode emit a function call instead of a regular load and let the
1843 // run-time deal with it: if the shadow is properly poisoned return the
1844 // cookie, otherwise return 0 to avoid an infinite loop calling DTORs.
1845 // We can't simply ignore this load using nosanitize metadata because
1846 // the metadata may be lost.
1847 llvm::FunctionType *FTy =
1848 llvm::FunctionType::get(CGF.SizeTy, CGF.SizeTy->getPointerTo(0), false);
1850 CGM.CreateRuntimeFunction(FTy, "__asan_load_cxx_array_cookie");
1851 return CGF.Builder.CreateCall(F, numElementsPtr.getPointer());
1854 CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1855 // ARM says that the cookie is always:
1856 // struct array_cookie {
1857 // std::size_t element_size; // element_size != 0
1858 // std::size_t element_count;
1860 // But the base ABI doesn't give anything an alignment greater than
1861 // 8, so we can dismiss this as typical ABI-author blindness to
1862 // actual language complexity and round up to the element alignment.
1863 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
1864 CGM.getContext().getTypeAlignInChars(elementType));
1867 Address ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1869 llvm::Value *numElements,
1870 const CXXNewExpr *expr,
1871 QualType elementType) {
1872 assert(requiresArrayCookie(expr));
1874 // The cookie is always at the start of the buffer.
1875 Address cookie = newPtr;
1877 // The first element is the element size.
1878 cookie = CGF.Builder.CreateElementBitCast(cookie, CGF.SizeTy);
1879 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
1880 getContext().getTypeSizeInChars(elementType).getQuantity());
1881 CGF.Builder.CreateStore(elementSize, cookie);
1883 // The second element is the element count.
1884 cookie = CGF.Builder.CreateConstInBoundsGEP(cookie, 1, CGF.getSizeSize());
1885 CGF.Builder.CreateStore(numElements, cookie);
1887 // Finally, compute a pointer to the actual data buffer by skipping
1888 // over the cookie completely.
1889 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
1890 return CGF.Builder.CreateConstInBoundsByteGEP(newPtr, cookieSize);
1893 llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1895 CharUnits cookieSize) {
1896 // The number of elements is at offset sizeof(size_t) relative to
1897 // the allocated pointer.
1898 Address numElementsPtr
1899 = CGF.Builder.CreateConstInBoundsByteGEP(allocPtr, CGF.getSizeSize());
1901 numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
1902 return CGF.Builder.CreateLoad(numElementsPtr);
1905 /*********************** Static local initialization **************************/
1907 static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
1908 llvm::PointerType *GuardPtrTy) {
1909 // int __cxa_guard_acquire(__guard *guard_object);
1910 llvm::FunctionType *FTy =
1911 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
1912 GuardPtrTy, /*isVarArg=*/false);
1913 return CGM.CreateRuntimeFunction(
1914 FTy, "__cxa_guard_acquire",
1915 llvm::AttributeList::get(CGM.getLLVMContext(),
1916 llvm::AttributeList::FunctionIndex,
1917 llvm::Attribute::NoUnwind));
1920 static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
1921 llvm::PointerType *GuardPtrTy) {
1922 // void __cxa_guard_release(__guard *guard_object);
1923 llvm::FunctionType *FTy =
1924 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
1925 return CGM.CreateRuntimeFunction(
1926 FTy, "__cxa_guard_release",
1927 llvm::AttributeList::get(CGM.getLLVMContext(),
1928 llvm::AttributeList::FunctionIndex,
1929 llvm::Attribute::NoUnwind));
1932 static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
1933 llvm::PointerType *GuardPtrTy) {
1934 // void __cxa_guard_abort(__guard *guard_object);
1935 llvm::FunctionType *FTy =
1936 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
1937 return CGM.CreateRuntimeFunction(
1938 FTy, "__cxa_guard_abort",
1939 llvm::AttributeList::get(CGM.getLLVMContext(),
1940 llvm::AttributeList::FunctionIndex,
1941 llvm::Attribute::NoUnwind));
1945 struct CallGuardAbort final : EHScopeStack::Cleanup {
1946 llvm::GlobalVariable *Guard;
1947 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
1949 void Emit(CodeGenFunction &CGF, Flags flags) override {
1950 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1956 /// The ARM code here follows the Itanium code closely enough that we
1957 /// just special-case it at particular places.
1958 void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1960 llvm::GlobalVariable *var,
1961 bool shouldPerformInit) {
1962 CGBuilderTy &Builder = CGF.Builder;
1964 // Inline variables that weren't instantiated from variable templates have
1965 // partially-ordered initialization within their translation unit.
1966 bool NonTemplateInline =
1968 !isTemplateInstantiation(D.getTemplateSpecializationKind());
1970 // We only need to use thread-safe statics for local non-TLS variables and
1971 // inline variables; other global initialization is always single-threaded
1972 // or (through lazy dynamic loading in multiple threads) unsequenced.
1973 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
1974 (D.isLocalVarDecl() || NonTemplateInline) &&
1977 // If we have a global variable with internal linkage and thread-safe statics
1978 // are disabled, we can just let the guard variable be of type i8.
1979 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
1981 llvm::IntegerType *guardTy;
1982 CharUnits guardAlignment;
1983 if (useInt8GuardVariable) {
1984 guardTy = CGF.Int8Ty;
1985 guardAlignment = CharUnits::One();
1987 // Guard variables are 64 bits in the generic ABI and size width on ARM
1988 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
1989 if (UseARMGuardVarABI) {
1990 guardTy = CGF.SizeTy;
1991 guardAlignment = CGF.getSizeAlign();
1993 guardTy = CGF.Int64Ty;
1994 guardAlignment = CharUnits::fromQuantity(
1995 CGM.getDataLayout().getABITypeAlignment(guardTy));
1998 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
2000 // Create the guard variable if we don't already have it (as we
2001 // might if we're double-emitting this function body).
2002 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
2004 // Mangle the name for the guard.
2005 SmallString<256> guardName;
2007 llvm::raw_svector_ostream out(guardName);
2008 getMangleContext().mangleStaticGuardVariable(&D, out);
2011 // Create the guard variable with a zero-initializer.
2012 // Just absorb linkage and visibility from the guarded variable.
2013 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
2014 false, var->getLinkage(),
2015 llvm::ConstantInt::get(guardTy, 0),
2017 guard->setVisibility(var->getVisibility());
2018 // If the variable is thread-local, so is its guard variable.
2019 guard->setThreadLocalMode(var->getThreadLocalMode());
2020 guard->setAlignment(guardAlignment.getQuantity());
2022 // The ABI says: "It is suggested that it be emitted in the same COMDAT
2023 // group as the associated data object." In practice, this doesn't work for
2024 // non-ELF and non-Wasm object formats, so only do it for ELF and Wasm.
2025 llvm::Comdat *C = var->getComdat();
2026 if (!D.isLocalVarDecl() && C &&
2027 (CGM.getTarget().getTriple().isOSBinFormatELF() ||
2028 CGM.getTarget().getTriple().isOSBinFormatWasm())) {
2029 guard->setComdat(C);
2030 // An inline variable's guard function is run from the per-TU
2031 // initialization function, not via a dedicated global ctor function, so
2032 // we can't put it in a comdat.
2033 if (!NonTemplateInline)
2034 CGF.CurFn->setComdat(C);
2035 } else if (CGM.supportsCOMDAT() && guard->isWeakForLinker()) {
2036 guard->setComdat(CGM.getModule().getOrInsertComdat(guard->getName()));
2039 CGM.setStaticLocalDeclGuardAddress(&D, guard);
2042 Address guardAddr = Address(guard, guardAlignment);
2044 // Test whether the variable has completed initialization.
2046 // Itanium C++ ABI 3.3.2:
2047 // The following is pseudo-code showing how these functions can be used:
2048 // if (obj_guard.first_byte == 0) {
2049 // if ( __cxa_guard_acquire (&obj_guard) ) {
2051 // ... initialize the object ...;
2053 // __cxa_guard_abort (&obj_guard);
2056 // ... queue object destructor with __cxa_atexit() ...;
2057 // __cxa_guard_release (&obj_guard);
2061 // Load the first byte of the guard variable.
2062 llvm::LoadInst *LI =
2063 Builder.CreateLoad(Builder.CreateElementBitCast(guardAddr, CGM.Int8Ty));
2066 // An implementation supporting thread-safety on multiprocessor
2067 // systems must also guarantee that references to the initialized
2068 // object do not occur before the load of the initialization flag.
2070 // In LLVM, we do this by marking the load Acquire.
2072 LI->setAtomic(llvm::AtomicOrdering::Acquire);
2074 // For ARM, we should only check the first bit, rather than the entire byte:
2076 // ARM C++ ABI 3.2.3.1:
2077 // To support the potential use of initialization guard variables
2078 // as semaphores that are the target of ARM SWP and LDREX/STREX
2079 // synchronizing instructions we define a static initialization
2080 // guard variable to be a 4-byte aligned, 4-byte word with the
2081 // following inline access protocol.
2082 // #define INITIALIZED 1
2083 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
2084 // if (__cxa_guard_acquire(&obj_guard))
2088 // and similarly for ARM64:
2090 // ARM64 C++ ABI 3.2.2:
2091 // This ABI instead only specifies the value bit 0 of the static guard
2092 // variable; all other bits are platform defined. Bit 0 shall be 0 when the
2093 // variable is not initialized and 1 when it is.
2095 (UseARMGuardVarABI && !useInt8GuardVariable)
2096 ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1))
2098 llvm::Value *isInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
2100 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
2101 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2103 // Check if the first byte of the guard variable is zero.
2104 Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock);
2106 CGF.EmitBlock(InitCheckBlock);
2108 // Variables used when coping with thread-safe statics and exceptions.
2110 // Call __cxa_guard_acquire.
2112 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
2114 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
2116 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
2117 InitBlock, EndBlock);
2119 // Call __cxa_guard_abort along the exceptional edge.
2120 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
2122 CGF.EmitBlock(InitBlock);
2125 // Emit the initializer and add a global destructor if appropriate.
2126 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
2129 // Pop the guard-abort cleanup if we pushed one.
2130 CGF.PopCleanupBlock();
2132 // Call __cxa_guard_release. This cannot throw.
2133 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy),
2134 guardAddr.getPointer());
2136 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guardAddr);
2139 CGF.EmitBlock(EndBlock);
2142 /// Register a global destructor using __cxa_atexit.
2143 static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
2144 llvm::Constant *dtor,
2145 llvm::Constant *addr,
2147 const char *Name = "__cxa_atexit";
2149 const llvm::Triple &T = CGF.getTarget().getTriple();
2150 Name = T.isOSDarwin() ? "_tlv_atexit" : "__cxa_thread_atexit";
2153 // We're assuming that the destructor function is something we can
2154 // reasonably call with the default CC. Go ahead and cast it to the
2156 llvm::Type *dtorTy =
2157 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
2159 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
2160 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
2161 llvm::FunctionType *atexitTy =
2162 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
2164 // Fetch the actual function.
2165 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
2166 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
2167 fn->setDoesNotThrow();
2169 // Create a variable that binds the atexit to this shared object.
2170 llvm::Constant *handle =
2171 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
2172 auto *GV = cast<llvm::GlobalValue>(handle->stripPointerCasts());
2173 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
2175 llvm::Value *args[] = {
2176 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
2177 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
2180 CGF.EmitNounwindRuntimeCall(atexit, args);
2183 /// Register a global destructor as best as we know how.
2184 void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
2186 llvm::Constant *dtor,
2187 llvm::Constant *addr) {
2188 // Use __cxa_atexit if available.
2189 if (CGM.getCodeGenOpts().CXAAtExit)
2190 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
2193 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
2195 // In Apple kexts, we want to add a global destructor entry.
2196 // FIXME: shouldn't this be guarded by some variable?
2197 if (CGM.getLangOpts().AppleKext) {
2198 // Generate a global destructor entry.
2199 return CGM.AddCXXDtorEntry(dtor, addr);
2202 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
2205 static bool isThreadWrapperReplaceable(const VarDecl *VD,
2206 CodeGen::CodeGenModule &CGM) {
2207 assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!");
2208 // Darwin prefers to have references to thread local variables to go through
2209 // the thread wrapper instead of directly referencing the backing variable.
2210 return VD->getTLSKind() == VarDecl::TLS_Dynamic &&
2211 CGM.getTarget().getTriple().isOSDarwin();
2214 /// Get the appropriate linkage for the wrapper function. This is essentially
2215 /// the weak form of the variable's linkage; every translation unit which needs
2216 /// the wrapper emits a copy, and we want the linker to merge them.
2217 static llvm::GlobalValue::LinkageTypes
2218 getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) {
2219 llvm::GlobalValue::LinkageTypes VarLinkage =
2220 CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false);
2222 // For internal linkage variables, we don't need an external or weak wrapper.
2223 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
2226 // If the thread wrapper is replaceable, give it appropriate linkage.
2227 if (isThreadWrapperReplaceable(VD, CGM))
2228 if (!llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) &&
2229 !llvm::GlobalVariable::isWeakODRLinkage(VarLinkage))
2231 return llvm::GlobalValue::WeakODRLinkage;
2235 ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
2237 // Mangle the name for the thread_local wrapper function.
2238 SmallString<256> WrapperName;
2240 llvm::raw_svector_ostream Out(WrapperName);
2241 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
2244 // FIXME: If VD is a definition, we should regenerate the function attributes
2245 // before returning.
2246 if (llvm::Value *V = CGM.getModule().getNamedValue(WrapperName))
2247 return cast<llvm::Function>(V);
2249 QualType RetQT = VD->getType();
2250 if (RetQT->isReferenceType())
2251 RetQT = RetQT.getNonReferenceType();
2253 const CGFunctionInfo &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2254 getContext().getPointerType(RetQT), FunctionArgList());
2256 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FI);
2257 llvm::Function *Wrapper =
2258 llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM),
2259 WrapperName.str(), &CGM.getModule());
2261 CGM.SetLLVMFunctionAttributes(nullptr, FI, Wrapper);
2263 if (VD->hasDefinition())
2264 CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Wrapper);
2266 // Always resolve references to the wrapper at link time.
2267 if (!Wrapper->hasLocalLinkage() && !(isThreadWrapperReplaceable(VD, CGM) &&
2268 !llvm::GlobalVariable::isLinkOnceLinkage(Wrapper->getLinkage()) &&
2269 !llvm::GlobalVariable::isWeakODRLinkage(Wrapper->getLinkage())))
2270 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
2272 if (isThreadWrapperReplaceable(VD, CGM)) {
2273 Wrapper->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2274 Wrapper->addFnAttr(llvm::Attribute::NoUnwind);
2279 void ItaniumCXXABI::EmitThreadLocalInitFuncs(
2280 CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
2281 ArrayRef<llvm::Function *> CXXThreadLocalInits,
2282 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) {
2283 llvm::Function *InitFunc = nullptr;
2285 // Separate initializers into those with ordered (or partially-ordered)
2286 // initialization and those with unordered initialization.
2287 llvm::SmallVector<llvm::Function *, 8> OrderedInits;
2288 llvm::SmallDenseMap<const VarDecl *, llvm::Function *> UnorderedInits;
2289 for (unsigned I = 0; I != CXXThreadLocalInits.size(); ++I) {
2290 if (isTemplateInstantiation(
2291 CXXThreadLocalInitVars[I]->getTemplateSpecializationKind()))
2292 UnorderedInits[CXXThreadLocalInitVars[I]->getCanonicalDecl()] =
2293 CXXThreadLocalInits[I];
2295 OrderedInits.push_back(CXXThreadLocalInits[I]);
2298 if (!OrderedInits.empty()) {
2299 // Generate a guarded initialization function.
2300 llvm::FunctionType *FTy =
2301 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
2302 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2303 InitFunc = CGM.CreateGlobalInitOrDestructFunction(FTy, "__tls_init", FI,
2306 llvm::GlobalVariable *Guard = new llvm::GlobalVariable(
2307 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
2308 llvm::GlobalVariable::InternalLinkage,
2309 llvm::ConstantInt::get(CGM.Int8Ty, 0), "__tls_guard");
2310 Guard->setThreadLocal(true);
2312 CharUnits GuardAlign = CharUnits::One();
2313 Guard->setAlignment(GuardAlign.getQuantity());
2315 CodeGenFunction(CGM).GenerateCXXGlobalInitFunc(InitFunc, OrderedInits,
2316 Address(Guard, GuardAlign));
2317 // On Darwin platforms, use CXX_FAST_TLS calling convention.
2318 if (CGM.getTarget().getTriple().isOSDarwin()) {
2319 InitFunc->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2320 InitFunc->addFnAttr(llvm::Attribute::NoUnwind);
2324 // Emit thread wrappers.
2325 for (const VarDecl *VD : CXXThreadLocals) {
2326 llvm::GlobalVariable *Var =
2327 cast<llvm::GlobalVariable>(CGM.GetGlobalValue(CGM.getMangledName(VD)));
2328 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
2330 // Some targets require that all access to thread local variables go through
2331 // the thread wrapper. This means that we cannot attempt to create a thread
2332 // wrapper or a thread helper.
2333 if (isThreadWrapperReplaceable(VD, CGM) && !VD->hasDefinition()) {
2334 Wrapper->setLinkage(llvm::Function::ExternalLinkage);
2338 // Mangle the name for the thread_local initialization function.
2339 SmallString<256> InitFnName;
2341 llvm::raw_svector_ostream Out(InitFnName);
2342 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
2345 // If we have a definition for the variable, emit the initialization
2346 // function as an alias to the global Init function (if any). Otherwise,
2347 // produce a declaration of the initialization function.
2348 llvm::GlobalValue *Init = nullptr;
2349 bool InitIsInitFunc = false;
2350 if (VD->hasDefinition()) {
2351 InitIsInitFunc = true;
2352 llvm::Function *InitFuncToUse = InitFunc;
2353 if (isTemplateInstantiation(VD->getTemplateSpecializationKind()))
2354 InitFuncToUse = UnorderedInits.lookup(VD->getCanonicalDecl());
2356 Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
2359 // Emit a weak global function referring to the initialization function.
2360 // This function will not exist if the TU defining the thread_local
2361 // variable in question does not need any dynamic initialization for
2362 // its thread_local variables.
2363 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
2364 Init = llvm::Function::Create(FnTy,
2365 llvm::GlobalVariable::ExternalWeakLinkage,
2366 InitFnName.str(), &CGM.getModule());
2367 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2368 CGM.SetLLVMFunctionAttributes(nullptr, FI, cast<llvm::Function>(Init));
2372 Init->setVisibility(Var->getVisibility());
2374 llvm::LLVMContext &Context = CGM.getModule().getContext();
2375 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
2376 CGBuilderTy Builder(CGM, Entry);
2377 if (InitIsInitFunc) {
2379 llvm::CallInst *CallVal = Builder.CreateCall(Init);
2380 if (isThreadWrapperReplaceable(VD, CGM))
2381 CallVal->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
2384 // Don't know whether we have an init function. Call it if it exists.
2385 llvm::Value *Have = Builder.CreateIsNotNull(Init);
2386 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2387 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
2388 Builder.CreateCondBr(Have, InitBB, ExitBB);
2390 Builder.SetInsertPoint(InitBB);
2391 Builder.CreateCall(Init);
2392 Builder.CreateBr(ExitBB);
2394 Builder.SetInsertPoint(ExitBB);
2397 // For a reference, the result of the wrapper function is a pointer to
2398 // the referenced object.
2399 llvm::Value *Val = Var;
2400 if (VD->getType()->isReferenceType()) {
2401 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2402 Val = Builder.CreateAlignedLoad(Val, Align);
2404 if (Val->getType() != Wrapper->getReturnType())
2405 Val = Builder.CreatePointerBitCastOrAddrSpaceCast(
2406 Val, Wrapper->getReturnType(), "");
2407 Builder.CreateRet(Val);
2411 LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
2413 QualType LValType) {
2414 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD);
2415 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Val);
2417 llvm::CallInst *CallVal = CGF.Builder.CreateCall(Wrapper);
2418 CallVal->setCallingConv(Wrapper->getCallingConv());
2421 if (VD->getType()->isReferenceType())
2422 LV = CGF.MakeNaturalAlignAddrLValue(CallVal, LValType);
2424 LV = CGF.MakeAddrLValue(CallVal, LValType,
2425 CGF.getContext().getDeclAlign(VD));
2426 // FIXME: need setObjCGCLValueClass?
2430 /// Return whether the given global decl needs a VTT parameter, which it does
2431 /// if it's a base constructor or destructor with virtual bases.
2432 bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
2433 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
2435 // We don't have any virtual bases, just return early.
2436 if (!MD->getParent()->getNumVBases())
2439 // Check if we have a base constructor.
2440 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
2443 // Check if we have a base destructor.
2444 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
2451 class ItaniumRTTIBuilder {
2452 CodeGenModule &CGM; // Per-module state.
2453 llvm::LLVMContext &VMContext;
2454 const ItaniumCXXABI &CXXABI; // Per-module state.
2456 /// Fields - The fields of the RTTI descriptor currently being built.
2457 SmallVector<llvm::Constant *, 16> Fields;
2459 /// GetAddrOfTypeName - Returns the mangled type name of the given type.
2460 llvm::GlobalVariable *
2461 GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
2463 /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
2464 /// descriptor of the given type.
2465 llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
2467 /// BuildVTablePointer - Build the vtable pointer for the given type.
2468 void BuildVTablePointer(const Type *Ty);
2470 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2471 /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
2472 void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
2474 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2475 /// classes with bases that do not satisfy the abi::__si_class_type_info
2476 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2477 void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
2479 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
2480 /// for pointer types.
2481 void BuildPointerTypeInfo(QualType PointeeTy);
2483 /// BuildObjCObjectTypeInfo - Build the appropriate kind of
2484 /// type_info for an object type.
2485 void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
2487 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
2488 /// struct, used for member pointer types.
2489 void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
2492 ItaniumRTTIBuilder(const ItaniumCXXABI &ABI)
2493 : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {}
2495 // Pointer type info flags.
2497 /// PTI_Const - Type has const qualifier.
2500 /// PTI_Volatile - Type has volatile qualifier.
2503 /// PTI_Restrict - Type has restrict qualifier.
2506 /// PTI_Incomplete - Type is incomplete.
2507 PTI_Incomplete = 0x8,
2509 /// PTI_ContainingClassIncomplete - Containing class is incomplete.
2510 /// (in pointer to member).
2511 PTI_ContainingClassIncomplete = 0x10,
2513 /// PTI_TransactionSafe - Pointee is transaction_safe function (C++ TM TS).
2514 //PTI_TransactionSafe = 0x20,
2516 /// PTI_Noexcept - Pointee is noexcept function (C++1z).
2517 PTI_Noexcept = 0x40,
2520 // VMI type info flags.
2522 /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
2523 VMI_NonDiamondRepeat = 0x1,
2525 /// VMI_DiamondShaped - Class is diamond shaped.
2526 VMI_DiamondShaped = 0x2
2529 // Base class type info flags.
2531 /// BCTI_Virtual - Base class is virtual.
2534 /// BCTI_Public - Base class is public.
2538 /// BuildTypeInfo - Build the RTTI type info struct for the given type.
2540 /// \param Force - true to force the creation of this RTTI value
2541 /// \param DLLExport - true to mark the RTTI value as DLLExport
2542 llvm::Constant *BuildTypeInfo(QualType Ty, bool Force = false,
2543 bool DLLExport = false);
2547 llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName(
2548 QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) {
2549 SmallString<256> Name;
2550 llvm::raw_svector_ostream Out(Name);
2551 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
2553 // We know that the mangled name of the type starts at index 4 of the
2554 // mangled name of the typename, so we can just index into it in order to
2555 // get the mangled name of the type.
2556 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
2559 llvm::GlobalVariable *GV =
2560 CGM.CreateOrReplaceCXXRuntimeVariable(Name, Init->getType(), Linkage);
2562 GV->setInitializer(Init);
2568 ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
2569 // Mangle the RTTI name.
2570 SmallString<256> Name;
2571 llvm::raw_svector_ostream Out(Name);
2572 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
2574 // Look for an existing global.
2575 llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
2578 // Create a new global variable.
2579 GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
2581 llvm::GlobalValue::ExternalLinkage, nullptr,
2583 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2584 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2585 if (RD->hasAttr<DLLImportAttr>())
2586 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2590 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2593 /// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
2594 /// info for that type is defined in the standard library.
2595 static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
2596 // Itanium C++ ABI 2.9.2:
2597 // Basic type information (e.g. for "int", "bool", etc.) will be kept in
2598 // the run-time support library. Specifically, the run-time support
2599 // library should contain type_info objects for the types X, X* and
2600 // X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
2601 // unsigned char, signed char, short, unsigned short, int, unsigned int,
2602 // long, unsigned long, long long, unsigned long long, float, double,
2603 // long double, char16_t, char32_t, and the IEEE 754r decimal and
2604 // half-precision floating point types.
2606 // GCC also emits RTTI for __int128.
2607 // FIXME: We do not emit RTTI information for decimal types here.
2609 // Types added here must also be added to EmitFundamentalRTTIDescriptors.
2610 switch (Ty->getKind()) {
2611 case BuiltinType::Void:
2612 case BuiltinType::NullPtr:
2613 case BuiltinType::Bool:
2614 case BuiltinType::WChar_S:
2615 case BuiltinType::WChar_U:
2616 case BuiltinType::Char_U:
2617 case BuiltinType::Char_S:
2618 case BuiltinType::UChar:
2619 case BuiltinType::SChar:
2620 case BuiltinType::Short:
2621 case BuiltinType::UShort:
2622 case BuiltinType::Int:
2623 case BuiltinType::UInt:
2624 case BuiltinType::Long:
2625 case BuiltinType::ULong:
2626 case BuiltinType::LongLong:
2627 case BuiltinType::ULongLong:
2628 case BuiltinType::Half:
2629 case BuiltinType::Float:
2630 case BuiltinType::Double:
2631 case BuiltinType::LongDouble:
2632 case BuiltinType::Float128:
2633 case BuiltinType::Char16:
2634 case BuiltinType::Char32:
2635 case BuiltinType::Int128:
2636 case BuiltinType::UInt128:
2639 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2640 case BuiltinType::Id:
2641 #include "clang/Basic/OpenCLImageTypes.def"
2642 case BuiltinType::OCLSampler:
2643 case BuiltinType::OCLEvent:
2644 case BuiltinType::OCLClkEvent:
2645 case BuiltinType::OCLQueue:
2646 case BuiltinType::OCLReserveID:
2649 case BuiltinType::Dependent:
2650 #define BUILTIN_TYPE(Id, SingletonId)
2651 #define PLACEHOLDER_TYPE(Id, SingletonId) \
2652 case BuiltinType::Id:
2653 #include "clang/AST/BuiltinTypes.def"
2654 llvm_unreachable("asking for RRTI for a placeholder type!");
2656 case BuiltinType::ObjCId:
2657 case BuiltinType::ObjCClass:
2658 case BuiltinType::ObjCSel:
2659 llvm_unreachable("FIXME: Objective-C types are unsupported!");
2662 llvm_unreachable("Invalid BuiltinType Kind!");
2665 static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
2666 QualType PointeeTy = PointerTy->getPointeeType();
2667 const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
2671 // Check the qualifiers.
2672 Qualifiers Quals = PointeeTy.getQualifiers();
2673 Quals.removeConst();
2678 return TypeInfoIsInStandardLibrary(BuiltinTy);
2681 /// IsStandardLibraryRTTIDescriptor - Returns whether the type
2682 /// information for the given type exists in the standard library.
2683 static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
2684 // Type info for builtin types is defined in the standard library.
2685 if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
2686 return TypeInfoIsInStandardLibrary(BuiltinTy);
2688 // Type info for some pointer types to builtin types is defined in the
2689 // standard library.
2690 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2691 return TypeInfoIsInStandardLibrary(PointerTy);
2696 /// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
2697 /// the given type exists somewhere else, and that we should not emit the type
2698 /// information in this translation unit. Assumes that it is not a
2699 /// standard-library type.
2700 static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM,
2702 ASTContext &Context = CGM.getContext();
2704 // If RTTI is disabled, assume it might be disabled in the
2705 // translation unit that defines any potential key function, too.
2706 if (!Context.getLangOpts().RTTI) return false;
2708 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2709 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2710 if (!RD->hasDefinition())
2713 if (!RD->isDynamicClass())
2716 // FIXME: this may need to be reconsidered if the key function
2718 // N.B. We must always emit the RTTI data ourselves if there exists a key
2720 bool IsDLLImport = RD->hasAttr<DLLImportAttr>();
2721 if (CGM.getVTables().isVTableExternal(RD))
2722 return IsDLLImport ? false : true;
2731 /// IsIncompleteClassType - Returns whether the given record type is incomplete.
2732 static bool IsIncompleteClassType(const RecordType *RecordTy) {
2733 return !RecordTy->getDecl()->isCompleteDefinition();
2736 /// ContainsIncompleteClassType - Returns whether the given type contains an
2737 /// incomplete class type. This is true if
2739 /// * The given type is an incomplete class type.
2740 /// * The given type is a pointer type whose pointee type contains an
2741 /// incomplete class type.
2742 /// * The given type is a member pointer type whose class is an incomplete
2744 /// * The given type is a member pointer type whoise pointee type contains an
2745 /// incomplete class type.
2746 /// is an indirect or direct pointer to an incomplete class type.
2747 static bool ContainsIncompleteClassType(QualType Ty) {
2748 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2749 if (IsIncompleteClassType(RecordTy))
2753 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2754 return ContainsIncompleteClassType(PointerTy->getPointeeType());
2756 if (const MemberPointerType *MemberPointerTy =
2757 dyn_cast<MemberPointerType>(Ty)) {
2758 // Check if the class type is incomplete.
2759 const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass());
2760 if (IsIncompleteClassType(ClassType))
2763 return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
2769 // CanUseSingleInheritance - Return whether the given record decl has a "single,
2770 // public, non-virtual base at offset zero (i.e. the derived class is dynamic
2771 // iff the base is)", according to Itanium C++ ABI, 2.95p6b.
2772 static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
2773 // Check the number of bases.
2774 if (RD->getNumBases() != 1)
2778 CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
2780 // Check that the base is not virtual.
2781 if (Base->isVirtual())
2784 // Check that the base is public.
2785 if (Base->getAccessSpecifier() != AS_public)
2788 // Check that the class is dynamic iff the base is.
2789 const CXXRecordDecl *BaseDecl =
2790 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2791 if (!BaseDecl->isEmpty() &&
2792 BaseDecl->isDynamicClass() != RD->isDynamicClass())
2798 void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty) {
2799 // abi::__class_type_info.
2800 static const char * const ClassTypeInfo =
2801 "_ZTVN10__cxxabiv117__class_type_infoE";
2802 // abi::__si_class_type_info.
2803 static const char * const SIClassTypeInfo =
2804 "_ZTVN10__cxxabiv120__si_class_type_infoE";
2805 // abi::__vmi_class_type_info.
2806 static const char * const VMIClassTypeInfo =
2807 "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
2809 const char *VTableName = nullptr;
2811 switch (Ty->getTypeClass()) {
2812 #define TYPE(Class, Base)
2813 #define ABSTRACT_TYPE(Class, Base)
2814 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2815 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2816 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
2817 #include "clang/AST/TypeNodes.def"
2818 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2820 case Type::LValueReference:
2821 case Type::RValueReference:
2822 llvm_unreachable("References shouldn't get here");
2825 case Type::DeducedTemplateSpecialization:
2826 llvm_unreachable("Undeduced type shouldn't get here");
2829 llvm_unreachable("Pipe types shouldn't get here");
2832 // GCC treats vector and complex types as fundamental types.
2834 case Type::ExtVector:
2837 // FIXME: GCC treats block pointers as fundamental types?!
2838 case Type::BlockPointer:
2839 // abi::__fundamental_type_info.
2840 VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
2843 case Type::ConstantArray:
2844 case Type::IncompleteArray:
2845 case Type::VariableArray:
2846 // abi::__array_type_info.
2847 VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
2850 case Type::FunctionNoProto:
2851 case Type::FunctionProto:
2852 // abi::__function_type_info.
2853 VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
2857 // abi::__enum_type_info.
2858 VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
2861 case Type::Record: {
2862 const CXXRecordDecl *RD =
2863 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2865 if (!RD->hasDefinition() || !RD->getNumBases()) {
2866 VTableName = ClassTypeInfo;
2867 } else if (CanUseSingleInheritance(RD)) {
2868 VTableName = SIClassTypeInfo;
2870 VTableName = VMIClassTypeInfo;
2876 case Type::ObjCObject:
2877 // Ignore protocol qualifiers.
2878 Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
2880 // Handle id and Class.
2881 if (isa<BuiltinType>(Ty)) {
2882 VTableName = ClassTypeInfo;
2886 assert(isa<ObjCInterfaceType>(Ty));
2889 case Type::ObjCInterface:
2890 if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
2891 VTableName = SIClassTypeInfo;
2893 VTableName = ClassTypeInfo;
2897 case Type::ObjCObjectPointer:
2899 // abi::__pointer_type_info.
2900 VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
2903 case Type::MemberPointer:
2904 // abi::__pointer_to_member_type_info.
2905 VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
2909 llvm::Constant *VTable =
2910 CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
2912 llvm::Type *PtrDiffTy =
2913 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
2915 // The vtable address point is 2.
2916 llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
2918 llvm::ConstantExpr::getInBoundsGetElementPtr(CGM.Int8PtrTy, VTable, Two);
2919 VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
2921 Fields.push_back(VTable);
2924 /// \brief Return the linkage that the type info and type info name constants
2925 /// should have for the given type.
2926 static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM,
2928 // Itanium C++ ABI 2.9.5p7:
2929 // In addition, it and all of the intermediate abi::__pointer_type_info
2930 // structs in the chain down to the abi::__class_type_info for the
2931 // incomplete class type must be prevented from resolving to the
2932 // corresponding type_info structs for the complete class type, possibly
2933 // by making them local static objects. Finally, a dummy class RTTI is
2934 // generated for the incomplete type that will not resolve to the final
2935 // complete class RTTI (because the latter need not exist), possibly by
2936 // making it a local static object.
2937 if (ContainsIncompleteClassType(Ty))
2938 return llvm::GlobalValue::InternalLinkage;
2940 switch (Ty->getLinkage()) {
2942 case InternalLinkage:
2943 case UniqueExternalLinkage:
2944 return llvm::GlobalValue::InternalLinkage;
2946 case VisibleNoLinkage:
2947 case ExternalLinkage:
2948 // RTTI is not enabled, which means that this type info struct is going
2949 // to be used for exception handling. Give it linkonce_odr linkage.
2950 if (!CGM.getLangOpts().RTTI)
2951 return llvm::GlobalValue::LinkOnceODRLinkage;
2953 if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
2954 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2955 if (RD->hasAttr<WeakAttr>())
2956 return llvm::GlobalValue::WeakODRLinkage;
2957 if (CGM.getTriple().isWindowsItaniumEnvironment())
2958 if (RD->hasAttr<DLLImportAttr>())
2959 return llvm::GlobalValue::ExternalLinkage;
2960 if (RD->isDynamicClass()) {
2961 llvm::GlobalValue::LinkageTypes LT = CGM.getVTableLinkage(RD);
2962 // MinGW won't export the RTTI information when there is a key function.
2963 // Make sure we emit our own copy instead of attempting to dllimport it.
2964 if (RD->hasAttr<DLLImportAttr>() &&
2965 llvm::GlobalValue::isAvailableExternallyLinkage(LT))
2966 LT = llvm::GlobalValue::LinkOnceODRLinkage;
2971 return llvm::GlobalValue::LinkOnceODRLinkage;
2974 llvm_unreachable("Invalid linkage!");
2977 llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty, bool Force,
2979 // We want to operate on the canonical type.
2980 Ty = Ty.getCanonicalType();
2982 // Check if we've already emitted an RTTI descriptor for this type.
2983 SmallString<256> Name;
2984 llvm::raw_svector_ostream Out(Name);
2985 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
2987 llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
2988 if (OldGV && !OldGV->isDeclaration()) {
2989 assert(!OldGV->hasAvailableExternallyLinkage() &&
2990 "available_externally typeinfos not yet implemented");
2992 return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
2995 // Check if there is already an external RTTI descriptor for this type.
2996 bool IsStdLib = IsStandardLibraryRTTIDescriptor(Ty);
2997 if (!Force && (IsStdLib || ShouldUseExternalRTTIDescriptor(CGM, Ty)))
2998 return GetAddrOfExternalRTTIDescriptor(Ty);
3000 // Emit the standard library with external linkage.
3001 llvm::GlobalVariable::LinkageTypes Linkage;
3003 Linkage = llvm::GlobalValue::ExternalLinkage;
3005 Linkage = getTypeInfoLinkage(CGM, Ty);
3007 // Add the vtable pointer.
3008 BuildVTablePointer(cast<Type>(Ty));
3011 llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
3012 llvm::Constant *TypeNameField;
3014 // If we're supposed to demote the visibility, be sure to set a flag
3015 // to use a string comparison for type_info comparisons.
3016 ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness =
3017 CXXABI.classifyRTTIUniqueness(Ty, Linkage);
3018 if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) {
3019 // The flag is the sign bit, which on ARM64 is defined to be clear
3020 // for global pointers. This is very ARM64-specific.
3021 TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty);
3022 llvm::Constant *flag =
3023 llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63);
3024 TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag);
3026 llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.Int8PtrTy);
3028 TypeNameField = llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy);
3030 Fields.push_back(TypeNameField);
3032 switch (Ty->getTypeClass()) {
3033 #define TYPE(Class, Base)
3034 #define ABSTRACT_TYPE(Class, Base)
3035 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3036 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3037 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3038 #include "clang/AST/TypeNodes.def"
3039 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
3041 // GCC treats vector types as fundamental types.
3044 case Type::ExtVector:
3046 case Type::BlockPointer:
3047 // Itanium C++ ABI 2.9.5p4:
3048 // abi::__fundamental_type_info adds no data members to std::type_info.
3051 case Type::LValueReference:
3052 case Type::RValueReference:
3053 llvm_unreachable("References shouldn't get here");
3056 case Type::DeducedTemplateSpecialization:
3057 llvm_unreachable("Undeduced type shouldn't get here");
3060 llvm_unreachable("Pipe type shouldn't get here");
3062 case Type::ConstantArray:
3063 case Type::IncompleteArray:
3064 case Type::VariableArray:
3065 // Itanium C++ ABI 2.9.5p5:
3066 // abi::__array_type_info adds no data members to std::type_info.
3069 case Type::FunctionNoProto:
3070 case Type::FunctionProto:
3071 // Itanium C++ ABI 2.9.5p5:
3072 // abi::__function_type_info adds no data members to std::type_info.
3076 // Itanium C++ ABI 2.9.5p5:
3077 // abi::__enum_type_info adds no data members to std::type_info.
3080 case Type::Record: {
3081 const CXXRecordDecl *RD =
3082 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
3083 if (!RD->hasDefinition() || !RD->getNumBases()) {
3084 // We don't need to emit any fields.
3088 if (CanUseSingleInheritance(RD))
3089 BuildSIClassTypeInfo(RD);
3091 BuildVMIClassTypeInfo(RD);
3096 case Type::ObjCObject:
3097 case Type::ObjCInterface:
3098 BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
3101 case Type::ObjCObjectPointer:
3102 BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
3106 BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
3109 case Type::MemberPointer:
3110 BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
3114 // No fields, at least for the moment.
3118 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
3120 llvm::Module &M = CGM.getModule();
3121 llvm::GlobalVariable *GV =
3122 new llvm::GlobalVariable(M, Init->getType(),
3123 /*Constant=*/true, Linkage, Init, Name);
3125 // If there's already an old global variable, replace it with the new one.
3127 GV->takeName(OldGV);
3128 llvm::Constant *NewPtr =
3129 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
3130 OldGV->replaceAllUsesWith(NewPtr);
3131 OldGV->eraseFromParent();
3134 if (CGM.supportsCOMDAT() && GV->isWeakForLinker())
3135 GV->setComdat(M.getOrInsertComdat(GV->getName()));
3137 // The Itanium ABI specifies that type_info objects must be globally
3138 // unique, with one exception: if the type is an incomplete class
3139 // type or a (possibly indirect) pointer to one. That exception
3140 // affects the general case of comparing type_info objects produced
3141 // by the typeid operator, which is why the comparison operators on
3142 // std::type_info generally use the type_info name pointers instead
3143 // of the object addresses. However, the language's built-in uses
3144 // of RTTI generally require class types to be complete, even when
3145 // manipulating pointers to those class types. This allows the
3146 // implementation of dynamic_cast to rely on address equality tests,
3147 // which is much faster.
3149 // All of this is to say that it's important that both the type_info
3150 // object and the type_info name be uniqued when weakly emitted.
3152 // Give the type_info object and name the formal visibility of the
3154 llvm::GlobalValue::VisibilityTypes llvmVisibility;
3155 if (llvm::GlobalValue::isLocalLinkage(Linkage))
3156 // If the linkage is local, only default visibility makes sense.
3157 llvmVisibility = llvm::GlobalValue::DefaultVisibility;
3158 else if (RTTIUniqueness == ItaniumCXXABI::RUK_NonUniqueHidden)
3159 llvmVisibility = llvm::GlobalValue::HiddenVisibility;
3161 llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility());
3163 TypeName->setVisibility(llvmVisibility);
3164 GV->setVisibility(llvmVisibility);
3166 if (CGM.getTriple().isWindowsItaniumEnvironment()) {
3167 auto RD = Ty->getAsCXXRecordDecl();
3168 if (DLLExport || (RD && RD->hasAttr<DLLExportAttr>())) {
3169 TypeName->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
3170 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
3171 } else if (CGM.getLangOpts().RTTI && RD && RD->hasAttr<DLLImportAttr>()) {
3172 TypeName->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3173 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3175 // Because the typename and the typeinfo are DLL import, convert them to
3176 // declarations rather than definitions. The initializers still need to
3177 // be constructed to calculate the type for the declarations.
3178 TypeName->setInitializer(nullptr);
3179 GV->setInitializer(nullptr);
3183 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
3186 /// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
3187 /// for the given Objective-C object type.
3188 void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
3190 const Type *T = OT->getBaseType().getTypePtr();
3191 assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
3193 // The builtin types are abi::__class_type_infos and don't require
3195 if (isa<BuiltinType>(T)) return;
3197 ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
3198 ObjCInterfaceDecl *Super = Class->getSuperClass();
3200 // Root classes are also __class_type_info.
3203 QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
3205 // Everything else is single inheritance.
3206 llvm::Constant *BaseTypeInfo =
3207 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy);
3208 Fields.push_back(BaseTypeInfo);
3211 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
3212 /// inheritance, according to the Itanium C++ ABI, 2.95p6b.
3213 void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
3214 // Itanium C++ ABI 2.9.5p6b:
3215 // It adds to abi::__class_type_info a single member pointing to the
3216 // type_info structure for the base type,
3217 llvm::Constant *BaseTypeInfo =
3218 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType());
3219 Fields.push_back(BaseTypeInfo);
3223 /// SeenBases - Contains virtual and non-virtual bases seen when traversing
3224 /// a class hierarchy.
3226 llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
3227 llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
3231 /// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
3232 /// abi::__vmi_class_type_info.
3234 static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
3239 const CXXRecordDecl *BaseDecl =
3240 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
3242 if (Base->isVirtual()) {
3243 // Mark the virtual base as seen.
3244 if (!Bases.VirtualBases.insert(BaseDecl).second) {
3245 // If this virtual base has been seen before, then the class is diamond
3247 Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped;
3249 if (Bases.NonVirtualBases.count(BaseDecl))
3250 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3253 // Mark the non-virtual base as seen.
3254 if (!Bases.NonVirtualBases.insert(BaseDecl).second) {
3255 // If this non-virtual base has been seen before, then the class has non-
3256 // diamond shaped repeated inheritance.
3257 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3259 if (Bases.VirtualBases.count(BaseDecl))
3260 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
3265 for (const auto &I : BaseDecl->bases())
3266 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3271 static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
3276 for (const auto &I : RD->bases())
3277 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
3282 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
3283 /// classes with bases that do not satisfy the abi::__si_class_type_info
3284 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
3285 void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
3286 llvm::Type *UnsignedIntLTy =
3287 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3289 // Itanium C++ ABI 2.9.5p6c:
3290 // __flags is a word with flags describing details about the class
3291 // structure, which may be referenced by using the __flags_masks
3292 // enumeration. These flags refer to both direct and indirect bases.
3293 unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
3294 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3296 // Itanium C++ ABI 2.9.5p6c:
3297 // __base_count is a word with the number of direct proper base class
3298 // descriptions that follow.
3299 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
3301 if (!RD->getNumBases())
3304 // Now add the base class descriptions.
3306 // Itanium C++ ABI 2.9.5p6c:
3307 // __base_info[] is an array of base class descriptions -- one for every
3308 // direct proper base. Each description is of the type:
3310 // struct abi::__base_class_type_info {
3312 // const __class_type_info *__base_type;
3313 // long __offset_flags;
3315 // enum __offset_flags_masks {
3316 // __virtual_mask = 0x1,
3317 // __public_mask = 0x2,
3318 // __offset_shift = 8
3322 // If we're in mingw and 'long' isn't wide enough for a pointer, use 'long
3323 // long' instead of 'long' for __offset_flags. libstdc++abi uses long long on
3325 // FIXME: Consider updating libc++abi to match, and extend this logic to all
3327 QualType OffsetFlagsTy = CGM.getContext().LongTy;
3328 const TargetInfo &TI = CGM.getContext().getTargetInfo();
3329 if (TI.getTriple().isOSCygMing() && TI.getPointerWidth(0) > TI.getLongWidth())
3330 OffsetFlagsTy = CGM.getContext().LongLongTy;
3331 llvm::Type *OffsetFlagsLTy =
3332 CGM.getTypes().ConvertType(OffsetFlagsTy);
3334 for (const auto &Base : RD->bases()) {
3335 // The __base_type member points to the RTTI for the base type.
3336 Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType()));
3338 const CXXRecordDecl *BaseDecl =
3339 cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
3341 int64_t OffsetFlags = 0;
3343 // All but the lower 8 bits of __offset_flags are a signed offset.
3344 // For a non-virtual base, this is the offset in the object of the base
3345 // subobject. For a virtual base, this is the offset in the virtual table of
3346 // the virtual base offset for the virtual base referenced (negative).
3348 if (Base.isVirtual())
3350 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
3352 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
3353 Offset = Layout.getBaseClassOffset(BaseDecl);
3356 OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
3358 // The low-order byte of __offset_flags contains flags, as given by the
3359 // masks from the enumeration __offset_flags_masks.
3360 if (Base.isVirtual())
3361 OffsetFlags |= BCTI_Virtual;
3362 if (Base.getAccessSpecifier() == AS_public)
3363 OffsetFlags |= BCTI_Public;
3365 Fields.push_back(llvm::ConstantInt::get(OffsetFlagsLTy, OffsetFlags));
3369 /// Compute the flags for a __pbase_type_info, and remove the corresponding
3370 /// pieces from \p Type.
3371 static unsigned extractPBaseFlags(ASTContext &Ctx, QualType &Type) {
3374 if (Type.isConstQualified())
3375 Flags |= ItaniumRTTIBuilder::PTI_Const;
3376 if (Type.isVolatileQualified())
3377 Flags |= ItaniumRTTIBuilder::PTI_Volatile;
3378 if (Type.isRestrictQualified())
3379 Flags |= ItaniumRTTIBuilder::PTI_Restrict;
3380 Type = Type.getUnqualifiedType();
3382 // Itanium C++ ABI 2.9.5p7:
3383 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
3384 // incomplete class type, the incomplete target type flag is set.
3385 if (ContainsIncompleteClassType(Type))
3386 Flags |= ItaniumRTTIBuilder::PTI_Incomplete;
3388 if (auto *Proto = Type->getAs<FunctionProtoType>()) {
3389 if (Proto->isNothrow(Ctx)) {
3390 Flags |= ItaniumRTTIBuilder::PTI_Noexcept;
3391 Type = Ctx.getFunctionType(
3392 Proto->getReturnType(), Proto->getParamTypes(),
3393 Proto->getExtProtoInfo().withExceptionSpec(EST_None));
3400 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
3401 /// used for pointer types.
3402 void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
3403 // Itanium C++ ABI 2.9.5p7:
3404 // __flags is a flag word describing the cv-qualification and other
3405 // attributes of the type pointed to
3406 unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy);
3408 llvm::Type *UnsignedIntLTy =
3409 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3410 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3412 // Itanium C++ ABI 2.9.5p7:
3413 // __pointee is a pointer to the std::type_info derivation for the
3414 // unqualified type being pointed to.
3415 llvm::Constant *PointeeTypeInfo =
3416 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy);
3417 Fields.push_back(PointeeTypeInfo);
3420 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
3421 /// struct, used for member pointer types.
3423 ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
3424 QualType PointeeTy = Ty->getPointeeType();
3426 // Itanium C++ ABI 2.9.5p7:
3427 // __flags is a flag word describing the cv-qualification and other
3428 // attributes of the type pointed to.
3429 unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy);
3431 const RecordType *ClassType = cast<RecordType>(Ty->getClass());
3432 if (IsIncompleteClassType(ClassType))
3433 Flags |= PTI_ContainingClassIncomplete;
3435 llvm::Type *UnsignedIntLTy =
3436 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
3437 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
3439 // Itanium C++ ABI 2.9.5p7:
3440 // __pointee is a pointer to the std::type_info derivation for the
3441 // unqualified type being pointed to.
3442 llvm::Constant *PointeeTypeInfo =
3443 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy);
3444 Fields.push_back(PointeeTypeInfo);
3446 // Itanium C++ ABI 2.9.5p9:
3447 // __context is a pointer to an abi::__class_type_info corresponding to the
3448 // class type containing the member pointed to
3449 // (e.g., the "A" in "int A::*").
3451 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(QualType(ClassType, 0)));
3454 llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) {
3455 return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty);
3458 void ItaniumCXXABI::EmitFundamentalRTTIDescriptor(QualType Type,
3460 QualType PointerType = getContext().getPointerType(Type);
3461 QualType PointerTypeConst = getContext().getPointerType(Type.withConst());
3462 ItaniumRTTIBuilder(*this).BuildTypeInfo(Type, /*Force=*/true, DLLExport);
3463 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerType, /*Force=*/true,
3465 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerTypeConst, /*Force=*/true,
3469 void ItaniumCXXABI::EmitFundamentalRTTIDescriptors(bool DLLExport) {
3470 // Types added here must also be added to TypeInfoIsInStandardLibrary.
3471 QualType FundamentalTypes[] = {
3472 getContext().VoidTy, getContext().NullPtrTy,
3473 getContext().BoolTy, getContext().WCharTy,
3474 getContext().CharTy, getContext().UnsignedCharTy,
3475 getContext().SignedCharTy, getContext().ShortTy,
3476 getContext().UnsignedShortTy, getContext().IntTy,
3477 getContext().UnsignedIntTy, getContext().LongTy,
3478 getContext().UnsignedLongTy, getContext().LongLongTy,
3479 getContext().UnsignedLongLongTy, getContext().Int128Ty,
3480 getContext().UnsignedInt128Ty, getContext().HalfTy,
3481 getContext().FloatTy, getContext().DoubleTy,
3482 getContext().LongDoubleTy, getContext().Float128Ty,
3483 getContext().Char16Ty, getContext().Char32Ty
3485 for (const QualType &FundamentalType : FundamentalTypes)
3486 EmitFundamentalRTTIDescriptor(FundamentalType, DLLExport);
3489 /// What sort of uniqueness rules should we use for the RTTI for the
3491 ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness(
3492 QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const {
3493 if (shouldRTTIBeUnique())
3496 // It's only necessary for linkonce_odr or weak_odr linkage.
3497 if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage &&
3498 Linkage != llvm::GlobalValue::WeakODRLinkage)
3501 // It's only necessary with default visibility.
3502 if (CanTy->getVisibility() != DefaultVisibility)
3505 // If we're not required to publish this symbol, hide it.
3506 if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
3507 return RUK_NonUniqueHidden;
3509 // If we're required to publish this symbol, as we might be under an
3510 // explicit instantiation, leave it with default visibility but
3511 // enable string-comparisons.
3512 assert(Linkage == llvm::GlobalValue::WeakODRLinkage);
3513 return RUK_NonUniqueVisible;
3516 // Find out how to codegen the complete destructor and constructor
3518 enum class StructorCodegen { Emit, RAUW, Alias, COMDAT };
3520 static StructorCodegen getCodegenToUse(CodeGenModule &CGM,
3521 const CXXMethodDecl *MD) {
3522 if (!CGM.getCodeGenOpts().CXXCtorDtorAliases)
3523 return StructorCodegen::Emit;
3525 // The complete and base structors are not equivalent if there are any virtual
3526 // bases, so emit separate functions.
3527 if (MD->getParent()->getNumVBases())
3528 return StructorCodegen::Emit;
3530 GlobalDecl AliasDecl;
3531 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
3532 AliasDecl = GlobalDecl(DD, Dtor_Complete);
3534 const auto *CD = cast<CXXConstructorDecl>(MD);
3535 AliasDecl = GlobalDecl(CD, Ctor_Complete);
3537 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3539 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage))
3540 return StructorCodegen::RAUW;
3542 // FIXME: Should we allow available_externally aliases?
3543 if (!llvm::GlobalAlias::isValidLinkage(Linkage))
3544 return StructorCodegen::RAUW;
3546 if (llvm::GlobalValue::isWeakForLinker(Linkage)) {
3547 // Only ELF and wasm support COMDATs with arbitrary names (C5/D5).
3548 if (CGM.getTarget().getTriple().isOSBinFormatELF() ||
3549 CGM.getTarget().getTriple().isOSBinFormatWasm())
3550 return StructorCodegen::COMDAT;
3551 return StructorCodegen::Emit;
3554 return StructorCodegen::Alias;
3557 static void emitConstructorDestructorAlias(CodeGenModule &CGM,
3558 GlobalDecl AliasDecl,
3559 GlobalDecl TargetDecl) {
3560 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3562 StringRef MangledName = CGM.getMangledName(AliasDecl);
3563 llvm::GlobalValue *Entry = CGM.GetGlobalValue(MangledName);
3564 if (Entry && !Entry->isDeclaration())
3567 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(TargetDecl));
3569 // Create the alias with no name.
3570 auto *Alias = llvm::GlobalAlias::create(Linkage, "", Aliasee);
3572 // Switch any previous uses to the alias.
3574 assert(Entry->getType() == Aliasee->getType() &&
3575 "declaration exists with different type");
3576 Alias->takeName(Entry);
3577 Entry->replaceAllUsesWith(Alias);
3578 Entry->eraseFromParent();
3580 Alias->setName(MangledName);
3583 // Finally, set up the alias with its proper name and attributes.
3584 CGM.setAliasAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);
3587 void ItaniumCXXABI::emitCXXStructor(const CXXMethodDecl *MD,
3588 StructorType Type) {
3589 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
3590 const CXXDestructorDecl *DD = CD ? nullptr : cast<CXXDestructorDecl>(MD);
3592 StructorCodegen CGType = getCodegenToUse(CGM, MD);
3594 if (Type == StructorType::Complete) {
3595 GlobalDecl CompleteDecl;
3596 GlobalDecl BaseDecl;
3598 CompleteDecl = GlobalDecl(CD, Ctor_Complete);
3599 BaseDecl = GlobalDecl(CD, Ctor_Base);
3601 CompleteDecl = GlobalDecl(DD, Dtor_Complete);
3602 BaseDecl = GlobalDecl(DD, Dtor_Base);
3605 if (CGType == StructorCodegen::Alias || CGType == StructorCodegen::COMDAT) {
3606 emitConstructorDestructorAlias(CGM, CompleteDecl, BaseDecl);
3610 if (CGType == StructorCodegen::RAUW) {
3611 StringRef MangledName = CGM.getMangledName(CompleteDecl);
3612 auto *Aliasee = CGM.GetAddrOfGlobal(BaseDecl);
3613 CGM.addReplacement(MangledName, Aliasee);
3618 // The base destructor is equivalent to the base destructor of its
3619 // base class if there is exactly one non-virtual base class with a
3620 // non-trivial destructor, there are no fields with a non-trivial
3621 // destructor, and the body of the destructor is trivial.
3622 if (DD && Type == StructorType::Base && CGType != StructorCodegen::COMDAT &&
3623 !CGM.TryEmitBaseDestructorAsAlias(DD))
3626 llvm::Function *Fn = CGM.codegenCXXStructor(MD, Type);
3628 if (CGType == StructorCodegen::COMDAT) {
3629 SmallString<256> Buffer;
3630 llvm::raw_svector_ostream Out(Buffer);
3632 getMangleContext().mangleCXXDtorComdat(DD, Out);
3634 getMangleContext().mangleCXXCtorComdat(CD, Out);
3635 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(Out.str());
3638 CGM.maybeSetTrivialComdat(*MD, *Fn);
3642 static llvm::Constant *getBeginCatchFn(CodeGenModule &CGM) {
3643 // void *__cxa_begin_catch(void*);
3644 llvm::FunctionType *FTy = llvm::FunctionType::get(
3645 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3647 return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
3650 static llvm::Constant *getEndCatchFn(CodeGenModule &CGM) {
3651 // void __cxa_end_catch();
3652 llvm::FunctionType *FTy =
3653 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
3655 return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
3658 static llvm::Constant *getGetExceptionPtrFn(CodeGenModule &CGM) {
3659 // void *__cxa_get_exception_ptr(void*);
3660 llvm::FunctionType *FTy = llvm::FunctionType::get(
3661 CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3663 return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
3667 /// A cleanup to call __cxa_end_catch. In many cases, the caught
3668 /// exception type lets us state definitively that the thrown exception
3669 /// type does not have a destructor. In particular:
3670 /// - Catch-alls tell us nothing, so we have to conservatively
3671 /// assume that the thrown exception might have a destructor.
3672 /// - Catches by reference behave according to their base types.
3673 /// - Catches of non-record types will only trigger for exceptions
3674 /// of non-record types, which never have destructors.
3675 /// - Catches of record types can trigger for arbitrary subclasses
3676 /// of the caught type, so we have to assume the actual thrown
3677 /// exception type might have a throwing destructor, even if the
3678 /// caught type's destructor is trivial or nothrow.
3679 struct CallEndCatch final : EHScopeStack::Cleanup {
3680 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
3683 void Emit(CodeGenFunction &CGF, Flags flags) override {
3685 CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM));
3689 CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM));
3694 /// Emits a call to __cxa_begin_catch and enters a cleanup to call
3695 /// __cxa_end_catch.
3697 /// \param EndMightThrow - true if __cxa_end_catch might throw
3698 static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
3700 bool EndMightThrow) {
3701 llvm::CallInst *call =
3702 CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn);
3704 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
3709 /// A "special initializer" callback for initializing a catch
3710 /// parameter during catch initialization.
3711 static void InitCatchParam(CodeGenFunction &CGF,
3712 const VarDecl &CatchParam,
3714 SourceLocation Loc) {
3715 // Load the exception from where the landing pad saved it.
3716 llvm::Value *Exn = CGF.getExceptionFromSlot();
3718 CanQualType CatchType =
3719 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
3720 llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
3722 // If we're catching by reference, we can just cast the object
3723 // pointer to the appropriate pointer.
3724 if (isa<ReferenceType>(CatchType)) {
3725 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
3726 bool EndCatchMightThrow = CaughtType->isRecordType();
3728 // __cxa_begin_catch returns the adjusted object pointer.
3729 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
3731 // We have no way to tell the personality function that we're
3732 // catching by reference, so if we're catching a pointer,
3733 // __cxa_begin_catch will actually return that pointer by value.
3734 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
3735 QualType PointeeType = PT->getPointeeType();
3737 // When catching by reference, generally we should just ignore
3738 // this by-value pointer and use the exception object instead.
3739 if (!PointeeType->isRecordType()) {
3741 // Exn points to the struct _Unwind_Exception header, which
3742 // we have to skip past in order to reach the exception data.
3743 unsigned HeaderSize =
3744 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
3745 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
3747 // However, if we're catching a pointer-to-record type that won't
3748 // work, because the personality function might have adjusted
3749 // the pointer. There's actually no way for us to fully satisfy
3750 // the language/ABI contract here: we can't use Exn because it
3751 // might have the wrong adjustment, but we can't use the by-value
3752 // pointer because it's off by a level of abstraction.
3754 // The current solution is to dump the adjusted pointer into an
3755 // alloca, which breaks language semantics (because changing the
3756 // pointer doesn't change the exception) but at least works.
3757 // The better solution would be to filter out non-exact matches
3758 // and rethrow them, but this is tricky because the rethrow
3759 // really needs to be catchable by other sites at this landing
3760 // pad. The best solution is to fix the personality function.
3762 // Pull the pointer for the reference type off.
3764 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
3766 // Create the temporary and write the adjusted pointer into it.
3768 CGF.CreateTempAlloca(PtrTy, CGF.getPointerAlign(), "exn.byref.tmp");
3769 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3770 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
3772 // Bind the reference to the temporary.
3773 AdjustedExn = ExnPtrTmp.getPointer();
3777 llvm::Value *ExnCast =
3778 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
3779 CGF.Builder.CreateStore(ExnCast, ParamAddr);
3783 // Scalars and complexes.
3784 TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType);
3785 if (TEK != TEK_Aggregate) {
3786 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
3788 // If the catch type is a pointer type, __cxa_begin_catch returns
3789 // the pointer by value.
3790 if (CatchType->hasPointerRepresentation()) {
3791 llvm::Value *CastExn =
3792 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
3794 switch (CatchType.getQualifiers().getObjCLifetime()) {
3795 case Qualifiers::OCL_Strong:
3796 CastExn = CGF.EmitARCRetainNonBlock(CastExn);
3799 case Qualifiers::OCL_None:
3800 case Qualifiers::OCL_ExplicitNone:
3801 case Qualifiers::OCL_Autoreleasing:
3802 CGF.Builder.CreateStore(CastExn, ParamAddr);
3805 case Qualifiers::OCL_Weak:
3806 CGF.EmitARCInitWeak(ParamAddr, CastExn);
3809 llvm_unreachable("bad ownership qualifier!");
3812 // Otherwise, it returns a pointer into the exception object.
3814 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3815 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
3817 LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType);
3818 LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType);
3821 CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV,
3825 llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc);
3826 CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true);
3830 llvm_unreachable("evaluation kind filtered out!");
3832 llvm_unreachable("bad evaluation kind");
3835 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
3836 auto catchRD = CatchType->getAsCXXRecordDecl();
3837 CharUnits caughtExnAlignment = CGF.CGM.getClassPointerAlignment(catchRD);
3839 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
3841 // Check for a copy expression. If we don't have a copy expression,
3842 // that means a trivial copy is okay.
3843 const Expr *copyExpr = CatchParam.getInit();
3845 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
3846 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
3847 caughtExnAlignment);
3848 CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType);
3852 // We have to call __cxa_get_exception_ptr to get the adjusted
3853 // pointer before copying.
3854 llvm::CallInst *rawAdjustedExn =
3855 CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn);
3857 // Cast that to the appropriate type.
3858 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
3859 caughtExnAlignment);
3861 // The copy expression is defined in terms of an OpaqueValueExpr.
3862 // Find it and map it to the adjusted expression.
3863 CodeGenFunction::OpaqueValueMapping
3864 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
3865 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
3867 // Call the copy ctor in a terminate scope.
3868 CGF.EHStack.pushTerminate();
3870 // Perform the copy construction.
3871 CGF.EmitAggExpr(copyExpr,
3872 AggValueSlot::forAddr(ParamAddr, Qualifiers(),
3873 AggValueSlot::IsNotDestructed,
3874 AggValueSlot::DoesNotNeedGCBarriers,
3875 AggValueSlot::IsNotAliased));
3877 // Leave the terminate scope.
3878 CGF.EHStack.popTerminate();
3880 // Undo the opaque value mapping.
3883 // Finally we can call __cxa_begin_catch.
3884 CallBeginCatch(CGF, Exn, true);
3887 /// Begins a catch statement by initializing the catch variable and
3888 /// calling __cxa_begin_catch.
3889 void ItaniumCXXABI::emitBeginCatch(CodeGenFunction &CGF,
3890 const CXXCatchStmt *S) {
3891 // We have to be very careful with the ordering of cleanups here:
3892 // C++ [except.throw]p4:
3893 // The destruction [of the exception temporary] occurs
3894 // immediately after the destruction of the object declared in
3895 // the exception-declaration in the handler.
3897 // So the precise ordering is:
3898 // 1. Construct catch variable.
3899 // 2. __cxa_begin_catch
3900 // 3. Enter __cxa_end_catch cleanup
3901 // 4. Enter dtor cleanup
3903 // We do this by using a slightly abnormal initialization process.
3904 // Delegation sequence:
3905 // - ExitCXXTryStmt opens a RunCleanupsScope
3906 // - EmitAutoVarAlloca creates the variable and debug info
3907 // - InitCatchParam initializes the variable from the exception
3908 // - CallBeginCatch calls __cxa_begin_catch
3909 // - CallBeginCatch enters the __cxa_end_catch cleanup
3910 // - EmitAutoVarCleanups enters the variable destructor cleanup
3911 // - EmitCXXTryStmt emits the code for the catch body
3912 // - EmitCXXTryStmt close the RunCleanupsScope
3914 VarDecl *CatchParam = S->getExceptionDecl();
3916 llvm::Value *Exn = CGF.getExceptionFromSlot();
3917 CallBeginCatch(CGF, Exn, true);
3922 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
3923 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getLocStart());
3924 CGF.EmitAutoVarCleanups(var);
3927 /// Get or define the following function:
3928 /// void @__clang_call_terminate(i8* %exn) nounwind noreturn
3929 /// This code is used only in C++.
3930 static llvm::Constant *getClangCallTerminateFn(CodeGenModule &CGM) {
3931 llvm::FunctionType *fnTy =
3932 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
3933 llvm::Constant *fnRef = CGM.CreateRuntimeFunction(
3934 fnTy, "__clang_call_terminate", llvm::AttributeList(), /*Local=*/true);
3936 llvm::Function *fn = dyn_cast<llvm::Function>(fnRef);
3937 if (fn && fn->empty()) {
3938 fn->setDoesNotThrow();
3939 fn->setDoesNotReturn();
3941 // What we really want is to massively penalize inlining without
3942 // forbidding it completely. The difference between that and
3943 // 'noinline' is negligible.
3944 fn->addFnAttr(llvm::Attribute::NoInline);
3946 // Allow this function to be shared across translation units, but
3947 // we don't want it to turn into an exported symbol.
3948 fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
3949 fn->setVisibility(llvm::Function::HiddenVisibility);
3950 if (CGM.supportsCOMDAT())
3951 fn->setComdat(CGM.getModule().getOrInsertComdat(fn->getName()));
3953 // Set up the function.
3954 llvm::BasicBlock *entry =
3955 llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn);
3956 CGBuilderTy builder(CGM, entry);
3958 // Pull the exception pointer out of the parameter list.
3959 llvm::Value *exn = &*fn->arg_begin();
3961 // Call __cxa_begin_catch(exn).
3962 llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn);
3963 catchCall->setDoesNotThrow();
3964 catchCall->setCallingConv(CGM.getRuntimeCC());
3966 // Call std::terminate().
3967 llvm::CallInst *termCall = builder.CreateCall(CGM.getTerminateFn());
3968 termCall->setDoesNotThrow();
3969 termCall->setDoesNotReturn();
3970 termCall->setCallingConv(CGM.getRuntimeCC());
3972 // std::terminate cannot return.
3973 builder.CreateUnreachable();
3980 ItaniumCXXABI::emitTerminateForUnexpectedException(CodeGenFunction &CGF,
3982 // In C++, we want to call __cxa_begin_catch() before terminating.
3984 assert(CGF.CGM.getLangOpts().CPlusPlus);
3985 return CGF.EmitNounwindRuntimeCall(getClangCallTerminateFn(CGF.CGM), Exn);
3987 return CGF.EmitNounwindRuntimeCall(CGF.CGM.getTerminateFn());