clang 23.0.0git
ItaniumCXXABI.cpp
Go to the documentation of this file.
1//===------- ItaniumCXXABI.cpp - Emit LLVM Code from ASTs for a Module ----===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This provides C++ code generation targeting the Itanium C++ ABI. The class
10// in this file generates structures that follow the Itanium C++ ABI, which is
11// documented at:
12// https://itanium-cxx-abi.github.io/cxx-abi/abi.html
13// https://itanium-cxx-abi.github.io/cxx-abi/abi-eh.html
14//
15// It also supports the closely-related ARM ABI, documented at:
16// https://developer.arm.com/documentation/ihi0041/g/
17//
18//===----------------------------------------------------------------------===//
19
20#include "CGCXXABI.h"
21#include "CGCleanup.h"
22#include "CGDebugInfo.h"
23#include "CGRecordLayout.h"
24#include "CGVTables.h"
25#include "CodeGenFunction.h"
26#include "CodeGenModule.h"
27#include "TargetInfo.h"
28#include "clang/AST/Attr.h"
29#include "clang/AST/Mangle.h"
30#include "clang/AST/StmtCXX.h"
31#include "clang/AST/Type.h"
33#include "llvm/IR/DataLayout.h"
34#include "llvm/IR/GlobalValue.h"
35#include "llvm/IR/Instructions.h"
36#include "llvm/IR/Intrinsics.h"
37#include "llvm/IR/Value.h"
38#include "llvm/Support/ConvertEBCDIC.h"
39#include "llvm/Support/ScopedPrinter.h"
40
41#include <optional>
42
43using namespace clang;
44using namespace CodeGen;
45
46namespace {
47class ItaniumCXXABI : public CodeGen::CGCXXABI {
48 /// VTables - All the vtables which have been defined.
49 llvm::DenseMap<const CXXRecordDecl *, llvm::GlobalVariable *> VTables;
50
51 /// All the thread wrapper functions that have been used.
52 llvm::SmallVector<std::pair<const VarDecl *, llvm::Function *>, 8>
53 ThreadWrappers;
54
55protected:
56 bool UseARMMethodPtrABI;
57 bool UseARMGuardVarABI;
58 bool Use32BitVTableOffsetABI;
59
60 ItaniumMangleContext &getMangleContext() {
62 }
63
64public:
65 ItaniumCXXABI(CodeGen::CodeGenModule &CGM,
66 bool UseARMMethodPtrABI = false,
67 bool UseARMGuardVarABI = false) :
68 CGCXXABI(CGM), UseARMMethodPtrABI(UseARMMethodPtrABI),
69 UseARMGuardVarABI(UseARMGuardVarABI),
70 Use32BitVTableOffsetABI(false) { }
71
72 bool classifyReturnType(CGFunctionInfo &FI) const override;
73
74 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override {
75 // If C++ prohibits us from making a copy, pass by address.
76 if (!RD->canPassInRegisters())
77 return RAA_Indirect;
78 return RAA_Default;
79 }
80
81 bool isThisCompleteObject(GlobalDecl GD) const override {
82 // The Itanium ABI has separate complete-object vs. base-object
83 // variants of both constructors and destructors.
85 switch (GD.getDtorType()) {
86 case Dtor_Complete:
87 case Dtor_Deleting:
88 return true;
89
90 case Dtor_Base:
91 return false;
92
93 case Dtor_Comdat:
94 llvm_unreachable("emitting dtor comdat as function?");
95 case Dtor_Unified:
96 llvm_unreachable("emitting unified dtor as function?");
98 llvm_unreachable("unexpected dtor kind for this ABI");
99 }
100 llvm_unreachable("bad dtor kind");
101 }
103 switch (GD.getCtorType()) {
104 case Ctor_Complete:
105 return true;
106
107 case Ctor_Base:
108 return false;
109
112 llvm_unreachable("closure ctors in Itanium ABI?");
113
114 case Ctor_Comdat:
115 llvm_unreachable("emitting ctor comdat as function?");
116
117 case Ctor_Unified:
118 llvm_unreachable("emitting unified ctor as function?");
119 }
120 llvm_unreachable("bad dtor kind");
121 }
122
123 // No other kinds.
124 return false;
125 }
126
127 bool isZeroInitializable(const MemberPointerType *MPT) override;
128
129 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override;
130
131 CGCallee
132 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
133 const Expr *E,
134 Address This,
135 llvm::Value *&ThisPtrForCall,
136 llvm::Value *MemFnPtr,
137 const MemberPointerType *MPT) override;
138
139 llvm::Value *EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
140 Address Base, llvm::Value *MemPtr,
141 const MemberPointerType *MPT,
142 bool IsInBounds) override;
143
144 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
145 const CastExpr *E,
146 llvm::Value *Src) override;
147 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
148 llvm::Constant *Src) override;
149
150 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override;
151
152 llvm::Constant *EmitMemberFunctionPointer(const CXXMethodDecl *MD) override;
153 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
154 CharUnits offset) override;
155 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override;
156 llvm::Constant *BuildMemberPointer(const CXXMethodDecl *MD,
157 CharUnits ThisAdjustment);
158
159 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
160 llvm::Value *L, llvm::Value *R,
161 const MemberPointerType *MPT,
162 bool Inequality) override;
163
164 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
165 llvm::Value *Addr,
166 const MemberPointerType *MPT) override;
167
168 void emitVirtualObjectDelete(CodeGenFunction &CGF, const CXXDeleteExpr *DE,
169 Address Ptr, QualType ElementType,
170 const CXXDestructorDecl *Dtor) override;
171
172 void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) override;
173 void emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) override;
174
175 void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override;
176
177 llvm::CallInst *
178 emitTerminateForUnexpectedException(CodeGenFunction &CGF,
179 llvm::Value *Exn) override;
180
181 void EmitFundamentalRTTIDescriptors(const CXXRecordDecl *RD);
182 llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override;
183 CatchTypeInfo
184 getAddrOfCXXCatchHandlerType(QualType Ty,
185 QualType CatchHandlerType) override {
186 return CatchTypeInfo{getAddrOfRTTIDescriptor(Ty), 0};
187 }
188
189 bool shouldTypeidBeNullChecked(QualType SrcRecordTy) override;
190 void EmitBadTypeidCall(CodeGenFunction &CGF) override;
191 llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
192 Address ThisPtr,
193 llvm::Type *StdTypeInfoPtrTy) override;
194
195 bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
196 QualType SrcRecordTy) override;
197
198 /// Determine whether we know that all instances of type RecordTy will have
199 /// the same vtable pointer values, that is distinct from all other vtable
200 /// pointers. While this is required by the Itanium ABI, it doesn't happen in
201 /// practice in some cases due to language extensions.
202 bool hasUniqueVTablePointer(QualType RecordTy) {
203 const CXXRecordDecl *RD = RecordTy->getAsCXXRecordDecl();
204
205 // Under -fapple-kext, multiple definitions of the same vtable may be
206 // emitted.
207 if (!CGM.getCodeGenOpts().AssumeUniqueVTables ||
208 getContext().getLangOpts().AppleKext)
209 return false;
210
211 // If the type_info* would be null, the vtable might be merged with that of
212 // another type.
213 if (!CGM.shouldEmitRTTI())
214 return false;
215
216 // If there's only one definition of the vtable in the program, it has a
217 // unique address.
218 if (!llvm::GlobalValue::isWeakForLinker(CGM.getVTableLinkage(RD)))
219 return true;
220
221 // Even if there are multiple definitions of the vtable, they are required
222 // by the ABI to use the same symbol name, so should be merged at load
223 // time. However, if the class has hidden visibility, there can be
224 // different versions of the class in different modules, and the ABI
225 // library might treat them as being the same.
226 if (CGM.GetLLVMVisibility(RD->getVisibility()) !=
227 llvm::GlobalValue::DefaultVisibility)
228 return false;
229
230 return true;
231 }
232
233 bool shouldEmitExactDynamicCast(QualType DestRecordTy) override {
234 return hasUniqueVTablePointer(DestRecordTy);
235 }
236
237 std::optional<ExactDynamicCastInfo>
238 getExactDynamicCastInfo(QualType SrcRecordTy, QualType DestTy,
239 QualType DestRecordTy) override;
240
241 llvm::Value *emitDynamicCastCall(CodeGenFunction &CGF, Address Value,
242 QualType SrcRecordTy, QualType DestTy,
243 QualType DestRecordTy,
244 llvm::BasicBlock *CastEnd) override;
245
246 llvm::Value *emitExactDynamicCast(CodeGenFunction &CGF, Address ThisAddr,
247 QualType SrcRecordTy, QualType DestTy,
248 QualType DestRecordTy,
249 const ExactDynamicCastInfo &CastInfo,
250 llvm::BasicBlock *CastSuccess,
251 llvm::BasicBlock *CastFail) override;
252
253 llvm::Value *emitDynamicCastToVoid(CodeGenFunction &CGF, Address Value,
254 QualType SrcRecordTy) override;
255
256 bool EmitBadCastCall(CodeGenFunction &CGF) override;
257
258 llvm::Value *
259 GetVirtualBaseClassOffset(CodeGenFunction &CGF, Address This,
260 const CXXRecordDecl *ClassDecl,
261 const CXXRecordDecl *BaseClassDecl) override;
262
263 void EmitCXXConstructors(const CXXConstructorDecl *D) override;
264
265 AddedStructorArgCounts
266 buildStructorSignature(GlobalDecl GD,
267 SmallVectorImpl<CanQualType> &ArgTys) override;
268
269 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
270 CXXDtorType DT) const override {
271 // Itanium does not emit any destructor variant as an inline thunk.
272 // Delegating may occur as an optimization, but all variants are either
273 // emitted with external linkage or as linkonce if they are inline and used.
274 return false;
275 }
276
277 void EmitCXXDestructors(const CXXDestructorDecl *D) override;
278
279 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
280 FunctionArgList &Params) override;
281
282 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
283
284 AddedStructorArgs getImplicitConstructorArgs(CodeGenFunction &CGF,
285 const CXXConstructorDecl *D,
287 bool ForVirtualBase,
288 bool Delegating) override;
289
290 llvm::Value *getCXXDestructorImplicitParam(CodeGenFunction &CGF,
291 const CXXDestructorDecl *DD,
293 bool ForVirtualBase,
294 bool Delegating) override;
295
296 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
297 CXXDtorType Type, bool ForVirtualBase,
298 bool Delegating, Address This,
299 QualType ThisTy) override;
300
301 void emitVTableDefinitions(CodeGenVTables &CGVT,
302 const CXXRecordDecl *RD) override;
303
304 bool isVirtualOffsetNeededForVTableField(CodeGenFunction &CGF,
305 CodeGenFunction::VPtr Vptr) override;
306
307 bool doStructorsInitializeVPtrs(const CXXRecordDecl *VTableClass) override {
308 return true;
309 }
310
311 llvm::Constant *
312 getVTableAddressPoint(BaseSubobject Base,
313 const CXXRecordDecl *VTableClass) override;
314
315 llvm::Value *getVTableAddressPointInStructor(
316 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
317 BaseSubobject Base, const CXXRecordDecl *NearestVBase) override;
318
319 llvm::Value *getVTableAddressPointInStructorWithVTT(
320 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
321 BaseSubobject Base, const CXXRecordDecl *NearestVBase);
322
323 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
324 CharUnits VPtrOffset) override;
325
326 CGCallee getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
327 Address This, llvm::Type *Ty,
328 SourceLocation Loc) override;
329
330 llvm::Value *
331 EmitVirtualDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *Dtor,
332 CXXDtorType DtorType, Address This,
333 DeleteOrMemberCallExpr E,
334 llvm::CallBase **CallOrInvoke) override;
335
336 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
337
338 bool canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const override;
339 bool canSpeculativelyEmitVTableAsBaseClass(const CXXRecordDecl *RD) const;
340
341 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, GlobalDecl GD,
342 bool ReturnAdjustment) override {
343 // Allow inlining of thunks by emitting them with available_externally
344 // linkage together with vtables when needed.
345 if (ForVTable && !Thunk->hasLocalLinkage())
346 Thunk->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
347 CGM.setGVProperties(Thunk, GD);
348 }
349
350 bool exportThunk() override { return true; }
351
352 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, Address This,
353 const CXXRecordDecl *UnadjustedThisClass,
354 const ThunkInfo &TI) override;
355
356 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
357 const CXXRecordDecl *UnadjustedRetClass,
358 const ReturnAdjustment &RA) override;
359
360 size_t getSrcArgforCopyCtor(const CXXConstructorDecl *,
361 FunctionArgList &Args) const override {
362 assert(!Args.empty() && "expected the arglist to not be empty!");
363 return Args.size() - 1;
364 }
365
366 StringRef GetPureVirtualCallName() override { return "__cxa_pure_virtual"; }
367 StringRef GetDeletedVirtualCallName() override
368 { return "__cxa_deleted_virtual"; }
369
370 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
371 Address InitializeArrayCookie(CodeGenFunction &CGF,
372 Address NewPtr,
373 llvm::Value *NumElements,
374 const CXXNewExpr *expr,
375 QualType ElementType) override;
376 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
377 Address allocPtr,
378 CharUnits cookieSize) override;
379
380 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
381 llvm::GlobalVariable *DeclPtr,
382 bool PerformInit) override;
383 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
384 llvm::FunctionCallee dtor,
385 llvm::Constant *addr) override;
386
387 llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
388 llvm::Value *Val);
389 void EmitThreadLocalInitFuncs(
390 CodeGenModule &CGM,
391 ArrayRef<const VarDecl *> CXXThreadLocals,
392 ArrayRef<llvm::Function *> CXXThreadLocalInits,
393 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) override;
394
395 bool usesThreadWrapperFunction(const VarDecl *VD) const override {
396 return !isEmittedWithConstantInitializer(VD) ||
397 mayNeedDestruction(VD);
398 }
399 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
400 QualType LValType) override;
401
402 bool NeedsVTTParameter(GlobalDecl GD) override;
403
404 llvm::Constant *
405 getOrCreateVirtualFunctionPointerThunk(const CXXMethodDecl *MD);
406
407 /**************************** RTTI Uniqueness ******************************/
408
409protected:
410 /// Returns true if the ABI requires RTTI type_info objects to be unique
411 /// across a program.
412 virtual bool shouldRTTIBeUnique() const { return true; }
413
414public:
415 /// What sort of unique-RTTI behavior should we use?
416 enum RTTIUniquenessKind {
417 /// We are guaranteeing, or need to guarantee, that the RTTI string
418 /// is unique.
419 RUK_Unique,
420
421 /// We are not guaranteeing uniqueness for the RTTI string, so we
422 /// can demote to hidden visibility but must use string comparisons.
423 RUK_NonUniqueHidden,
424
425 /// We are not guaranteeing uniqueness for the RTTI string, so we
426 /// have to use string comparisons, but we also have to emit it with
427 /// non-hidden visibility.
428 RUK_NonUniqueVisible
429 };
430
431 /// Return the required visibility status for the given type and linkage in
432 /// the current ABI.
433 RTTIUniquenessKind
434 classifyRTTIUniqueness(QualType CanTy,
435 llvm::GlobalValue::LinkageTypes Linkage) const;
436 friend class ItaniumRTTIBuilder;
437
438 void emitCXXStructor(GlobalDecl GD) override;
439
440 std::pair<llvm::Value *, const CXXRecordDecl *>
441 LoadVTablePtr(CodeGenFunction &CGF, Address This,
442 const CXXRecordDecl *RD) override;
443
444 private:
445 llvm::Constant *
446 getSignedVirtualMemberFunctionPointer(const CXXMethodDecl *MD);
447
448 bool hasAnyUnusedVirtualInlineFunction(const CXXRecordDecl *RD) const {
449 const auto &VtableLayout =
450 CGM.getItaniumVTableContext().getVTableLayout(RD);
451
452 for (const auto &VtableComponent : VtableLayout.vtable_components()) {
453 // Skip empty slot.
454 if (!VtableComponent.isUsedFunctionPointerKind())
455 continue;
456
457 const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
458 const FunctionDecl *FD = Method->getDefinition();
459 const bool IsInlined =
460 Method->getCanonicalDecl()->isInlined() || (FD && FD->isInlined());
461 if (!IsInlined)
462 continue;
463
464 StringRef Name = CGM.getMangledName(
465 VtableComponent.getGlobalDecl(/*HasVectorDeletingDtors=*/false));
466 auto *Entry = CGM.GetGlobalValue(Name);
467 // This checks if virtual inline function has already been emitted.
468 // Note that it is possible that this inline function would be emitted
469 // after trying to emit vtable speculatively. Because of this we do
470 // an extra pass after emitting all deferred vtables to find and emit
471 // these vtables opportunistically.
472 if (!Entry || Entry->isDeclaration())
473 return true;
474 }
475 return false;
476 }
477
478 bool isVTableHidden(const CXXRecordDecl *RD) const {
479 const auto &VtableLayout =
480 CGM.getItaniumVTableContext().getVTableLayout(RD);
481
482 for (const auto &VtableComponent : VtableLayout.vtable_components()) {
483 if (VtableComponent.isRTTIKind()) {
484 const CXXRecordDecl *RTTIDecl = VtableComponent.getRTTIDecl();
485 if (RTTIDecl->getVisibility() == Visibility::HiddenVisibility)
486 return true;
487 } else if (VtableComponent.isUsedFunctionPointerKind()) {
488 const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
489 if (Method->getVisibility() == Visibility::HiddenVisibility &&
490 !Method->isDefined())
491 return true;
492 }
493 }
494 return false;
495 }
496};
497
498class ARMCXXABI : public ItaniumCXXABI {
499public:
500 ARMCXXABI(CodeGen::CodeGenModule &CGM) :
501 ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true,
502 /*UseARMGuardVarABI=*/true) {}
503
504 bool constructorsAndDestructorsReturnThis() const override { return true; }
505
506 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV,
507 QualType ResTy) override;
508
509 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
510 Address InitializeArrayCookie(CodeGenFunction &CGF,
511 Address NewPtr,
512 llvm::Value *NumElements,
513 const CXXNewExpr *expr,
514 QualType ElementType) override;
515 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, Address allocPtr,
516 CharUnits cookieSize) override;
517};
518
519class AppleARM64CXXABI : public ARMCXXABI {
520public:
521 AppleARM64CXXABI(CodeGen::CodeGenModule &CGM) : ARMCXXABI(CGM) {
522 Use32BitVTableOffsetABI = true;
523 }
524
525 // ARM64 libraries are prepared for non-unique RTTI.
526 bool shouldRTTIBeUnique() const override { return false; }
527};
528
529class FuchsiaCXXABI final : public ItaniumCXXABI {
530public:
531 explicit FuchsiaCXXABI(CodeGen::CodeGenModule &CGM)
532 : ItaniumCXXABI(CGM) {}
533
534private:
535 bool constructorsAndDestructorsReturnThis() const override { return true; }
536};
537
538class WebAssemblyCXXABI final : public ItaniumCXXABI {
539public:
540 explicit WebAssemblyCXXABI(CodeGen::CodeGenModule &CGM)
541 : ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true,
542 /*UseARMGuardVarABI=*/true) {}
543 void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override;
544 llvm::CallInst *
545 emitTerminateForUnexpectedException(CodeGenFunction &CGF,
546 llvm::Value *Exn) override;
547
548private:
549 bool constructorsAndDestructorsReturnThis() const override { return true; }
550 bool canCallMismatchedFunctionType() const override { return false; }
551};
552
553class XLCXXABI final : public ItaniumCXXABI {
554public:
555 explicit XLCXXABI(CodeGen::CodeGenModule &CGM)
556 : ItaniumCXXABI(CGM) {}
557
558 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
559 llvm::FunctionCallee dtor,
560 llvm::Constant *addr) override;
561
562 bool useSinitAndSterm() const override { return true; }
563
564private:
565 void emitCXXStermFinalizer(const VarDecl &D, llvm::Function *dtorStub,
566 llvm::Constant *addr);
567};
568}
569
571 switch (CGM.getContext().getCXXABIKind()) {
572 // For IR-generation purposes, there's no significant difference
573 // between the ARM and iOS ABIs.
574 case TargetCXXABI::GenericARM:
575 case TargetCXXABI::iOS:
576 case TargetCXXABI::WatchOS:
577 return new ARMCXXABI(CGM);
578
579 case TargetCXXABI::AppleARM64:
580 return new AppleARM64CXXABI(CGM);
581
582 case TargetCXXABI::Fuchsia:
583 return new FuchsiaCXXABI(CGM);
584
585 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
586 // include the other 32-bit ARM oddities: constructor/destructor return values
587 // and array cookies.
588 case TargetCXXABI::GenericAArch64:
589 return new ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true,
590 /*UseARMGuardVarABI=*/true);
591
592 case TargetCXXABI::GenericMIPS:
593 return new ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true);
594
595 case TargetCXXABI::WebAssembly:
596 return new WebAssemblyCXXABI(CGM);
597
598 case TargetCXXABI::XL:
599 return new XLCXXABI(CGM);
600
601 case TargetCXXABI::GenericItanium:
602 return new ItaniumCXXABI(CGM);
603
604 case TargetCXXABI::Microsoft:
605 llvm_unreachable("Microsoft ABI is not Itanium-based");
606 }
607 llvm_unreachable("bad ABI kind");
608}
609
610llvm::Type *
611ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
612 if (MPT->isMemberDataPointer())
613 return CGM.PtrDiffTy;
614 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy);
615}
616
617/// In the Itanium and ARM ABIs, method pointers have the form:
618/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
619///
620/// In the Itanium ABI:
621/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
622/// - the this-adjustment is (memptr.adj)
623/// - the virtual offset is (memptr.ptr - 1)
624///
625/// In the ARM ABI:
626/// - method pointers are virtual if (memptr.adj & 1) is nonzero
627/// - the this-adjustment is (memptr.adj >> 1)
628/// - the virtual offset is (memptr.ptr)
629/// ARM uses 'adj' for the virtual flag because Thumb functions
630/// may be only single-byte aligned.
631///
632/// If the member is virtual, the adjusted 'this' pointer points
633/// to a vtable pointer from which the virtual offset is applied.
634///
635/// If the member is non-virtual, memptr.ptr is the address of
636/// the function to call.
637CGCallee ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(
638 CodeGenFunction &CGF, const Expr *E, Address ThisAddr,
639 llvm::Value *&ThisPtrForCall,
640 llvm::Value *MemFnPtr, const MemberPointerType *MPT) {
641 CGBuilderTy &Builder = CGF.Builder;
642
643 const FunctionProtoType *FPT =
645 auto *RD = MPT->getMostRecentCXXRecordDecl();
646
647 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
648
649 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
650 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
651 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
652
653 // Extract memptr.adj, which is in the second field.
654 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
655
656 // Compute the true adjustment.
657 llvm::Value *Adj = RawAdj;
658 if (UseARMMethodPtrABI)
659 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
660
661 // Apply the adjustment and cast back to the original struct type
662 // for consistency.
663 llvm::Value *This = ThisAddr.emitRawPointer(CGF);
664 This = Builder.CreateInBoundsGEP(Builder.getInt8Ty(), This, Adj);
665 ThisPtrForCall = This;
666
667 // Load the function pointer.
668 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
669
670 // If the LSB in the function pointer is 1, the function pointer points to
671 // a virtual function.
672 llvm::Value *IsVirtual;
673 if (UseARMMethodPtrABI)
674 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
675 else
676 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
677 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
678 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
679
680 // In the virtual path, the adjustment left 'This' pointing to the
681 // vtable of the correct base subobject. The "function pointer" is an
682 // offset within the vtable (+1 for the virtual flag on non-ARM).
683 CGF.EmitBlock(FnVirtual);
684
685 // Cast the adjusted this to a pointer to vtable pointer and load.
686 llvm::Type *VTableTy = CGF.CGM.GlobalsInt8PtrTy;
687 CharUnits VTablePtrAlign =
688 CGF.CGM.getDynamicOffsetAlignment(ThisAddr.getAlignment(), RD,
689 CGF.getPointerAlign());
690 llvm::Value *VTable = CGF.GetVTablePtr(
691 Address(This, ThisAddr.getElementType(), VTablePtrAlign), VTableTy, RD);
692
693 // Apply the offset.
694 // On ARM64, to reserve extra space in virtual member function pointers,
695 // we only pay attention to the low 32 bits of the offset.
696 llvm::Value *VTableOffset = FnAsInt;
697 if (!UseARMMethodPtrABI)
698 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
699 if (Use32BitVTableOffsetABI) {
700 VTableOffset = Builder.CreateTrunc(VTableOffset, CGF.Int32Ty);
701 VTableOffset = Builder.CreateZExt(VTableOffset, CGM.PtrDiffTy);
702 }
703
704 // Check the address of the function pointer if CFI on member function
705 // pointers is enabled.
706 llvm::Constant *CheckSourceLocation;
707 llvm::Constant *CheckTypeDesc;
708 bool ShouldEmitCFICheck = CGF.SanOpts.has(SanitizerKind::CFIMFCall) &&
709 CGM.HasHiddenLTOVisibility(RD);
710
711 if (ShouldEmitCFICheck) {
712 if (const auto *BinOp = dyn_cast<BinaryOperator>(E)) {
713 if (BinOp->isPtrMemOp() &&
714 BinOp->getRHS()
715 ->getType()
716 ->hasPointeeToCFIUncheckedCalleeFunctionType())
717 ShouldEmitCFICheck = false;
718 }
719 }
720
721 bool ShouldEmitVFEInfo = CGM.getCodeGenOpts().VirtualFunctionElimination &&
722 CGM.HasHiddenLTOVisibility(RD);
723 // TODO: Update this name not to be restricted to WPD only
724 // as we now emit the vtable info info for speculative devirtualization as
725 // well.
726 bool ShouldEmitWPDInfo =
727 (CGM.getCodeGenOpts().WholeProgramVTables &&
728 // Don't insert type tests if we are forcing public visibility.
729 !CGM.AlwaysHasLTOVisibilityPublic(RD)) ||
730 CGM.getCodeGenOpts().DevirtualizeSpeculatively;
731 llvm::Value *VirtualFn = nullptr;
732
733 {
734 auto CheckOrdinal = SanitizerKind::SO_CFIMFCall;
735 auto CheckHandler = SanitizerHandler::CFICheckFail;
736 SanitizerDebugLocation SanScope(&CGF, {CheckOrdinal}, CheckHandler);
737
738 llvm::Value *TypeId = nullptr;
739 llvm::Value *CheckResult = nullptr;
740
741 if (ShouldEmitCFICheck || ShouldEmitVFEInfo || ShouldEmitWPDInfo) {
742 // If doing CFI, VFE or WPD, we will need the metadata node to check
743 // against.
744 llvm::Metadata *MD =
745 CGM.CreateMetadataIdentifierForVirtualMemPtrType(QualType(MPT, 0));
746 TypeId = llvm::MetadataAsValue::get(CGF.getLLVMContext(), MD);
747 }
748
749 if (ShouldEmitVFEInfo) {
750 llvm::Value *VFPAddr =
751 Builder.CreateGEP(CGF.Int8Ty, VTable, VTableOffset);
752
753 // If doing VFE, load from the vtable with a type.checked.load intrinsic
754 // call. Note that we use the GEP to calculate the address to load from
755 // and pass 0 as the offset to the intrinsic. This is because every
756 // vtable slot of the correct type is marked with matching metadata, and
757 // we know that the load must be from one of these slots.
758 llvm::Value *CheckedLoad = Builder.CreateCall(
759 CGM.getIntrinsic(llvm::Intrinsic::type_checked_load),
760 {VFPAddr, llvm::ConstantInt::get(CGM.Int32Ty, 0), TypeId});
761 CheckResult = Builder.CreateExtractValue(CheckedLoad, 1);
762 VirtualFn = Builder.CreateExtractValue(CheckedLoad, 0);
763 } else {
764 // When not doing VFE, emit a normal load, as it allows more
765 // optimisations than type.checked.load.
766 if (ShouldEmitCFICheck || ShouldEmitWPDInfo) {
767 llvm::Value *VFPAddr =
768 Builder.CreateGEP(CGF.Int8Ty, VTable, VTableOffset);
769 llvm::Intrinsic::ID IID = CGM.HasHiddenLTOVisibility(RD)
770 ? llvm::Intrinsic::type_test
771 : llvm::Intrinsic::public_type_test;
772
773 CheckResult =
774 Builder.CreateCall(CGM.getIntrinsic(IID), {VFPAddr, TypeId});
775 }
776
777 if (CGM.getItaniumVTableContext().isRelativeLayout()) {
778 VirtualFn = CGF.Builder.CreateCall(
779 CGM.getIntrinsic(llvm::Intrinsic::load_relative,
780 {VTableOffset->getType()}),
781 {VTable, VTableOffset});
782 } else {
783 llvm::Value *VFPAddr =
784 CGF.Builder.CreateGEP(CGF.Int8Ty, VTable, VTableOffset);
785 VirtualFn = CGF.Builder.CreateAlignedLoad(CGF.DefaultPtrTy, VFPAddr,
786 CGF.getPointerAlign(),
787 "memptr.virtualfn");
788 }
789 }
790 assert(VirtualFn && "Virtual fuction pointer not created!");
791 assert((!ShouldEmitCFICheck || !ShouldEmitVFEInfo || !ShouldEmitWPDInfo ||
792 CheckResult) &&
793 "Check result required but not created!");
794
795 if (ShouldEmitCFICheck) {
796 // If doing CFI, emit the check.
797 CheckSourceLocation = CGF.EmitCheckSourceLocation(E->getBeginLoc());
798 CheckTypeDesc = CGF.EmitCheckTypeDescriptor(QualType(MPT, 0));
799 llvm::Constant *StaticData[] = {
800 llvm::ConstantInt::get(CGF.Int8Ty, CodeGenFunction::CFITCK_VMFCall),
801 CheckSourceLocation,
802 CheckTypeDesc,
803 };
804
805 if (CGM.getCodeGenOpts().SanitizeTrap.has(SanitizerKind::CFIMFCall)) {
806 CGF.EmitTrapCheck(CheckResult, CheckHandler);
807 } else {
808 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
809 CGM.getLLVMContext(),
810 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
811 llvm::Value *ValidVtable = Builder.CreateCall(
812 CGM.getIntrinsic(llvm::Intrinsic::type_test), {VTable, AllVtables});
813 CGF.EmitCheck(std::make_pair(CheckResult, CheckOrdinal), CheckHandler,
814 StaticData, {VTable, ValidVtable});
815 }
816
817 FnVirtual = Builder.GetInsertBlock();
818 }
819 } // End of sanitizer scope
820
821 CGF.EmitBranch(FnEnd);
822
823 // In the non-virtual path, the function pointer is actually a
824 // function pointer.
825 CGF.EmitBlock(FnNonVirtual);
826 llvm::Value *NonVirtualFn =
827 Builder.CreateIntToPtr(FnAsInt, CGF.DefaultPtrTy, "memptr.nonvirtualfn");
828
829 // Check the function pointer if CFI on member function pointers is enabled.
830 if (ShouldEmitCFICheck) {
831 CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
832 if (RD->hasDefinition()) {
833 auto CheckOrdinal = SanitizerKind::SO_CFIMFCall;
834 auto CheckHandler = SanitizerHandler::CFICheckFail;
835 SanitizerDebugLocation SanScope(&CGF, {CheckOrdinal}, CheckHandler);
836
837 llvm::Constant *StaticData[] = {
838 llvm::ConstantInt::get(CGF.Int8Ty, CodeGenFunction::CFITCK_NVMFCall),
839 CheckSourceLocation,
840 CheckTypeDesc,
841 };
842
843 llvm::Value *Bit = Builder.getFalse();
844 for (const CXXRecordDecl *Base : CGM.getMostBaseClasses(RD)) {
845 llvm::Metadata *MD = CGM.CreateMetadataIdentifierForType(
846 getContext().getMemberPointerType(MPT->getPointeeType(),
847 /*Qualifier=*/std::nullopt,
848 Base->getCanonicalDecl()));
849 llvm::Value *TypeId =
850 llvm::MetadataAsValue::get(CGF.getLLVMContext(), MD);
851
852 llvm::Value *TypeTest =
853 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
854 {NonVirtualFn, TypeId});
855 Bit = Builder.CreateOr(Bit, TypeTest);
856 }
857
858 CGF.EmitCheck(std::make_pair(Bit, CheckOrdinal), CheckHandler, StaticData,
859 {NonVirtualFn, llvm::UndefValue::get(CGF.IntPtrTy)});
860
861 FnNonVirtual = Builder.GetInsertBlock();
862 }
863 }
864
865 // We're done.
866 CGF.EmitBlock(FnEnd);
867 llvm::PHINode *CalleePtr = Builder.CreatePHI(CGF.DefaultPtrTy, 2);
868 CalleePtr->addIncoming(VirtualFn, FnVirtual);
869 CalleePtr->addIncoming(NonVirtualFn, FnNonVirtual);
870
871 CGPointerAuthInfo PointerAuth;
872
873 if (const auto &Schema =
874 CGM.getCodeGenOpts().PointerAuth.CXXMemberFunctionPointers) {
875 llvm::PHINode *DiscriminatorPHI = Builder.CreatePHI(CGF.IntPtrTy, 2);
876 DiscriminatorPHI->addIncoming(llvm::ConstantInt::get(CGF.IntPtrTy, 0),
877 FnVirtual);
878 const auto &AuthInfo =
879 CGM.getMemberFunctionPointerAuthInfo(QualType(MPT, 0));
880 assert(Schema.getKey() == AuthInfo.getKey() &&
881 "Keys for virtual and non-virtual member functions must match");
882 auto *NonVirtualDiscriminator = AuthInfo.getDiscriminator();
883 DiscriminatorPHI->addIncoming(NonVirtualDiscriminator, FnNonVirtual);
884 PointerAuth = CGPointerAuthInfo(
885 Schema.getKey(), Schema.getAuthenticationMode(), Schema.isIsaPointer(),
886 Schema.authenticatesNullValues(), DiscriminatorPHI);
887 }
888
889 CGCallee Callee(FPT, CalleePtr, PointerAuth);
890 return Callee;
891}
892
893/// Compute an l-value by applying the given pointer-to-member to a
894/// base object.
895llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(
896 CodeGenFunction &CGF, const Expr *E, Address Base, llvm::Value *MemPtr,
897 const MemberPointerType *MPT, bool IsInBounds) {
898 assert(MemPtr->getType() == CGM.PtrDiffTy);
899
900 CGBuilderTy &Builder = CGF.Builder;
901
902 // Apply the offset.
903 llvm::Value *BaseAddr = Base.emitRawPointer(CGF);
904 return Builder.CreateGEP(CGF.Int8Ty, BaseAddr, MemPtr, "memptr.offset",
905 IsInBounds ? llvm::GEPNoWrapFlags::inBounds()
906 : llvm::GEPNoWrapFlags::none());
907}
908
909// See if it's possible to return a constant signed pointer.
910static llvm::Constant *pointerAuthResignConstant(
911 llvm::Value *Ptr, const CGPointerAuthInfo &CurAuthInfo,
912 const CGPointerAuthInfo &NewAuthInfo, CodeGenModule &CGM) {
913 const auto *CPA = dyn_cast<llvm::ConstantPtrAuth>(Ptr);
914
915 if (!CPA)
916 return nullptr;
917
918 assert(CPA->getKey()->getZExtValue() == CurAuthInfo.getKey() &&
919 CPA->getAddrDiscriminator()->isNullValue() &&
920 CPA->getDiscriminator() == CurAuthInfo.getDiscriminator() &&
921 "unexpected key or discriminators");
922
923 return CGM.getConstantSignedPointer(
924 CPA->getPointer(), NewAuthInfo.getKey(), nullptr,
926}
927
928/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
929/// conversion.
930///
931/// Bitcast conversions are always a no-op under Itanium.
932///
933/// Obligatory offset/adjustment diagram:
934/// <-- offset --> <-- adjustment -->
935/// |--------------------------|----------------------|--------------------|
936/// ^Derived address point ^Base address point ^Member address point
937///
938/// So when converting a base member pointer to a derived member pointer,
939/// we add the offset to the adjustment because the address point has
940/// decreased; and conversely, when converting a derived MP to a base MP
941/// we subtract the offset from the adjustment because the address point
942/// has increased.
943///
944/// The standard forbids (at compile time) conversion to and from
945/// virtual bases, which is why we don't have to consider them here.
946///
947/// The standard forbids (at run time) casting a derived MP to a base
948/// MP when the derived MP does not point to a member of the base.
949/// This is why -1 is a reasonable choice for null data member
950/// pointers.
951llvm::Value *
952ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
953 const CastExpr *E,
954 llvm::Value *src) {
955 // Use constant emission if we can.
956 if (isa<llvm::Constant>(src))
957 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
958
959 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
960 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
961 E->getCastKind() == CK_ReinterpretMemberPointer);
962
963 CGBuilderTy &Builder = CGF.Builder;
964 QualType DstType = E->getType();
965
966 if (DstType->isMemberFunctionPointerType()) {
967 if (const auto &NewAuthInfo =
968 CGM.getMemberFunctionPointerAuthInfo(DstType)) {
969 QualType SrcType = E->getSubExpr()->getType();
970 assert(SrcType->isMemberFunctionPointerType());
971 const auto &CurAuthInfo = CGM.getMemberFunctionPointerAuthInfo(SrcType);
972 llvm::Value *MemFnPtr = Builder.CreateExtractValue(src, 0, "memptr.ptr");
973 llvm::Type *OrigTy = MemFnPtr->getType();
974
975 llvm::BasicBlock *StartBB = Builder.GetInsertBlock();
976 llvm::BasicBlock *ResignBB = CGF.createBasicBlock("resign");
977 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("merge");
978
979 // Check whether we have a virtual offset or a pointer to a function.
980 assert(UseARMMethodPtrABI && "ARM ABI expected");
981 llvm::Value *Adj = Builder.CreateExtractValue(src, 1, "memptr.adj");
982 llvm::Constant *Ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
983 llvm::Value *AndVal = Builder.CreateAnd(Adj, Ptrdiff_1);
984 llvm::Value *IsVirtualOffset =
985 Builder.CreateIsNotNull(AndVal, "is.virtual.offset");
986 Builder.CreateCondBr(IsVirtualOffset, MergeBB, ResignBB);
987
988 CGF.EmitBlock(ResignBB);
989 llvm::Type *PtrTy = llvm::PointerType::getUnqual(CGM.getLLVMContext());
990 MemFnPtr = Builder.CreateIntToPtr(MemFnPtr, PtrTy);
991 MemFnPtr =
992 CGF.emitPointerAuthResign(MemFnPtr, SrcType, CurAuthInfo, NewAuthInfo,
994 MemFnPtr = Builder.CreatePtrToInt(MemFnPtr, OrigTy);
995 llvm::Value *ResignedVal = Builder.CreateInsertValue(src, MemFnPtr, 0);
996 ResignBB = Builder.GetInsertBlock();
997
998 CGF.EmitBlock(MergeBB);
999 llvm::PHINode *NewSrc = Builder.CreatePHI(src->getType(), 2);
1000 NewSrc->addIncoming(src, StartBB);
1001 NewSrc->addIncoming(ResignedVal, ResignBB);
1002 src = NewSrc;
1003 }
1004 }
1005
1006 // Under Itanium, reinterprets don't require any additional processing.
1007 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
1008
1009 llvm::Constant *adj = getMemberPointerAdjustment(E);
1010 if (!adj) return src;
1011
1012 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
1013
1014 const MemberPointerType *destTy =
1015 E->getType()->castAs<MemberPointerType>();
1016
1017 // For member data pointers, this is just a matter of adding the
1018 // offset if the source is non-null.
1019 if (destTy->isMemberDataPointer()) {
1020 llvm::Value *dst;
1021 if (isDerivedToBase)
1022 dst = Builder.CreateNSWSub(src, adj, "adj");
1023 else
1024 dst = Builder.CreateNSWAdd(src, adj, "adj");
1025
1026 // Null check.
1027 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
1028 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
1029 return Builder.CreateSelect(isNull, src, dst);
1030 }
1031
1032 // The this-adjustment is left-shifted by 1 on ARM.
1033 if (UseARMMethodPtrABI) {
1034 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
1035 offset <<= 1;
1036 adj = llvm::ConstantInt::get(adj->getType(), offset);
1037 }
1038
1039 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
1040 llvm::Value *dstAdj;
1041 if (isDerivedToBase)
1042 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
1043 else
1044 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
1045
1046 return Builder.CreateInsertValue(src, dstAdj, 1);
1047}
1048
1049static llvm::Constant *
1051 QualType SrcType, CodeGenModule &CGM) {
1052 assert(DestType->isMemberFunctionPointerType() &&
1053 SrcType->isMemberFunctionPointerType() &&
1054 "member function pointers expected");
1055 if (DestType == SrcType)
1056 return Src;
1057
1058 const auto &NewAuthInfo = CGM.getMemberFunctionPointerAuthInfo(DestType);
1059 const auto &CurAuthInfo = CGM.getMemberFunctionPointerAuthInfo(SrcType);
1060
1061 if (!NewAuthInfo && !CurAuthInfo)
1062 return Src;
1063
1064 llvm::Constant *MemFnPtr = Src->getAggregateElement(0u);
1065 if (MemFnPtr->getNumOperands() == 0) {
1066 // src must be a pair of null pointers.
1067 assert(isa<llvm::ConstantInt>(MemFnPtr) && "constant int expected");
1068 return Src;
1069 }
1070
1071 llvm::Constant *ConstPtr = pointerAuthResignConstant(
1072 cast<llvm::User>(MemFnPtr)->getOperand(0), CurAuthInfo, NewAuthInfo, CGM);
1073 ConstPtr = llvm::ConstantExpr::getPtrToInt(ConstPtr, MemFnPtr->getType());
1074 return ConstantFoldInsertValueInstruction(Src, ConstPtr, 0);
1075}
1076
1077llvm::Constant *
1078ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
1079 llvm::Constant *src) {
1080 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
1081 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
1082 E->getCastKind() == CK_ReinterpretMemberPointer);
1083
1084 QualType DstType = E->getType();
1085
1086 if (DstType->isMemberFunctionPointerType())
1088 src, DstType, E->getSubExpr()->getType(), CGM);
1089
1090 // Under Itanium, reinterprets don't require any additional processing.
1091 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
1092
1093 // If the adjustment is trivial, we don't need to do anything.
1094 llvm::Constant *adj = getMemberPointerAdjustment(E);
1095 if (!adj) return src;
1096
1097 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
1098
1099 const MemberPointerType *destTy =
1100 E->getType()->castAs<MemberPointerType>();
1101
1102 // For member data pointers, this is just a matter of adding the
1103 // offset if the source is non-null.
1104 if (destTy->isMemberDataPointer()) {
1105 // null maps to null.
1106 if (src->isAllOnesValue()) return src;
1107
1108 if (isDerivedToBase)
1109 return llvm::ConstantExpr::getNSWSub(src, adj);
1110 else
1111 return llvm::ConstantExpr::getNSWAdd(src, adj);
1112 }
1113
1114 // The this-adjustment is left-shifted by 1 on ARM.
1115 if (UseARMMethodPtrABI) {
1116 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
1117 offset <<= 1;
1118 adj = llvm::ConstantInt::get(adj->getType(), offset);
1119 }
1120
1121 llvm::Constant *srcAdj = src->getAggregateElement(1);
1122 llvm::Constant *dstAdj;
1123 if (isDerivedToBase)
1124 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
1125 else
1126 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
1127
1128 llvm::Constant *res = ConstantFoldInsertValueInstruction(src, dstAdj, 1);
1129 assert(res != nullptr && "Folding must succeed");
1130 return res;
1131}
1132
1133llvm::Constant *
1134ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
1135 // Itanium C++ ABI 2.3:
1136 // A NULL pointer is represented as -1.
1137 if (MPT->isMemberDataPointer())
1138 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
1139
1140 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
1141 llvm::Constant *Values[2] = { Zero, Zero };
1142 return llvm::ConstantStruct::getAnon(Values);
1143}
1144
1145llvm::Constant *
1146ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
1147 CharUnits offset) {
1148 // Itanium C++ ABI 2.3:
1149 // A pointer to data member is an offset from the base address of
1150 // the class object containing it, represented as a ptrdiff_t
1151 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
1152}
1153
1154llvm::Constant *
1155ItaniumCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) {
1156 return BuildMemberPointer(MD, CharUnits::Zero());
1157}
1158
1159llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
1160 CharUnits ThisAdjustment) {
1161 assert(MD->isInstance() && "Member function must not be static!");
1162
1163 CodeGenTypes &Types = CGM.getTypes();
1164
1165 // Get the function pointer (or index if this is a virtual function).
1166 llvm::Constant *MemPtr[2];
1167 if (MD->isVirtual()) {
1168 uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
1169 uint64_t VTableOffset;
1170 if (CGM.getItaniumVTableContext().isRelativeLayout()) {
1171 // Multiply by 4-byte relative offsets.
1172 VTableOffset = Index * 4;
1173 } else {
1174 const ASTContext &Context = getContext();
1175 CharUnits PointerWidth = Context.toCharUnitsFromBits(
1176 Context.getTargetInfo().getPointerWidth(LangAS::Default));
1177 VTableOffset = Index * PointerWidth.getQuantity();
1178 }
1179
1180 if (UseARMMethodPtrABI) {
1181 // ARM C++ ABI 3.2.1:
1182 // This ABI specifies that adj contains twice the this
1183 // adjustment, plus 1 if the member function is virtual. The
1184 // least significant bit of adj then makes exactly the same
1185 // discrimination as the least significant bit of ptr does for
1186 // Itanium.
1187
1188 // We cannot use the Itanium ABI's representation for virtual member
1189 // function pointers under pointer authentication because it would
1190 // require us to store both the virtual offset and the constant
1191 // discriminator in the pointer, which would be immediately vulnerable
1192 // to attack. Instead we introduce a thunk that does the virtual dispatch
1193 // and store it as if it were a non-virtual member function. This means
1194 // that virtual function pointers may not compare equal anymore, but
1195 // fortunately they aren't required to by the standard, and we do make
1196 // a best-effort attempt to re-use the thunk.
1197 //
1198 // To support interoperation with code in which pointer authentication
1199 // is disabled, derefencing a member function pointer must still handle
1200 // the virtual case, but it can use a discriminator which should never
1201 // be valid.
1202 const auto &Schema =
1203 CGM.getCodeGenOpts().PointerAuth.CXXMemberFunctionPointers;
1204 if (Schema)
1205 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(
1206 getSignedVirtualMemberFunctionPointer(MD), CGM.PtrDiffTy);
1207 else
1208 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
1209 // Don't set the LSB of adj to 1 if pointer authentication for member
1210 // function pointers is enabled.
1211 MemPtr[1] = llvm::ConstantInt::get(
1212 CGM.PtrDiffTy, 2 * ThisAdjustment.getQuantity() + !Schema);
1213 } else {
1214 // Itanium C++ ABI 2.3:
1215 // For a virtual function, [the pointer field] is 1 plus the
1216 // virtual table offset (in bytes) of the function,
1217 // represented as a ptrdiff_t.
1218 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
1219 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
1220 ThisAdjustment.getQuantity());
1221 }
1222 } else {
1223 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
1224 llvm::Type *Ty;
1225 // Check whether the function has a computable LLVM signature.
1226 if (Types.isFuncTypeConvertible(FPT)) {
1227 // The function has a computable LLVM signature; use the correct type.
1228 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
1229 } else {
1230 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
1231 // function type is incomplete.
1232 Ty = CGM.PtrDiffTy;
1233 }
1234 llvm::Constant *addr = CGM.getMemberFunctionPointer(MD, Ty);
1235
1236 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
1237 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
1238 (UseARMMethodPtrABI ? 2 : 1) *
1239 ThisAdjustment.getQuantity());
1240 }
1241
1242 return llvm::ConstantStruct::getAnon(MemPtr);
1243}
1244
1245llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
1246 QualType MPType) {
1247 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
1248 const ValueDecl *MPD = MP.getMemberPointerDecl();
1249 if (!MPD)
1250 return EmitNullMemberPointer(MPT);
1251
1252 CharUnits ThisAdjustment = getContext().getMemberPointerPathAdjustment(MP);
1253
1254 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD)) {
1255 llvm::Constant *Src = BuildMemberPointer(MD, ThisAdjustment);
1256 QualType SrcType = getContext().getMemberPointerType(
1257 MD->getType(), /*Qualifier=*/std::nullopt, MD->getParent());
1258 return pointerAuthResignMemberFunctionPointer(Src, MPType, SrcType, CGM);
1259 }
1260
1261 getContext().recordMemberDataPointerEvaluation(MPD);
1262 CharUnits FieldOffset =
1263 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
1264 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
1265}
1266
1267/// The comparison algorithm is pretty easy: the member pointers are
1268/// the same if they're either bitwise identical *or* both null.
1269///
1270/// ARM is different here only because null-ness is more complicated.
1271llvm::Value *
1272ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
1273 llvm::Value *L,
1274 llvm::Value *R,
1275 const MemberPointerType *MPT,
1276 bool Inequality) {
1277 CGBuilderTy &Builder = CGF.Builder;
1278
1279 llvm::ICmpInst::Predicate Eq;
1280 llvm::Instruction::BinaryOps And, Or;
1281 if (Inequality) {
1282 Eq = llvm::ICmpInst::ICMP_NE;
1283 And = llvm::Instruction::Or;
1284 Or = llvm::Instruction::And;
1285 } else {
1286 Eq = llvm::ICmpInst::ICMP_EQ;
1287 And = llvm::Instruction::And;
1288 Or = llvm::Instruction::Or;
1289 }
1290
1291 // Member data pointers are easy because there's a unique null
1292 // value, so it just comes down to bitwise equality.
1293 if (MPT->isMemberDataPointer())
1294 return Builder.CreateICmp(Eq, L, R);
1295
1296 // For member function pointers, the tautologies are more complex.
1297 // The Itanium tautology is:
1298 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
1299 // The ARM tautology is:
1300 // (L == R) <==> (L.ptr == R.ptr &&
1301 // (L.adj == R.adj ||
1302 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
1303 // The inequality tautologies have exactly the same structure, except
1304 // applying De Morgan's laws.
1305
1306 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
1307 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
1308
1309 // This condition tests whether L.ptr == R.ptr. This must always be
1310 // true for equality to hold.
1311 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
1312
1313 // This condition, together with the assumption that L.ptr == R.ptr,
1314 // tests whether the pointers are both null. ARM imposes an extra
1315 // condition.
1316 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
1317 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
1318
1319 // This condition tests whether L.adj == R.adj. If this isn't
1320 // true, the pointers are unequal unless they're both null.
1321 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
1322 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
1323 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
1324
1325 // Null member function pointers on ARM clear the low bit of Adj,
1326 // so the zero condition has to check that neither low bit is set.
1327 if (UseARMMethodPtrABI) {
1328 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
1329
1330 // Compute (l.adj | r.adj) & 1 and test it against zero.
1331 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
1332 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
1333 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
1334 "cmp.or.adj");
1335 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
1336 }
1337
1338 // Tie together all our conditions.
1339 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
1340 Result = Builder.CreateBinOp(And, PtrEq, Result,
1341 Inequality ? "memptr.ne" : "memptr.eq");
1342 return Result;
1343}
1344
1345llvm::Value *
1346ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
1347 llvm::Value *MemPtr,
1348 const MemberPointerType *MPT) {
1349 CGBuilderTy &Builder = CGF.Builder;
1350
1351 /// For member data pointers, this is just a check against -1.
1352 if (MPT->isMemberDataPointer()) {
1353 assert(MemPtr->getType() == CGM.PtrDiffTy);
1354 llvm::Value *NegativeOne =
1355 llvm::Constant::getAllOnesValue(MemPtr->getType());
1356 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
1357 }
1358
1359 // In Itanium, a member function pointer is not null if 'ptr' is not null.
1360 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
1361
1362 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
1363 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
1364
1365 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
1366 // (the virtual bit) is set.
1367 if (UseARMMethodPtrABI) {
1368 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
1369 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
1370 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
1371 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
1372 "memptr.isvirtual");
1373 Result = Builder.CreateOr(Result, IsVirtual);
1374 }
1375
1376 return Result;
1377}
1378
1379bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
1380 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
1381 if (!RD)
1382 return false;
1383
1384 // If C++ prohibits us from making a copy, return by address.
1385 if (!RD->canPassInRegisters()) {
1386 auto Align = CGM.getContext().getTypeAlignInChars(FI.getReturnType());
1388 Align, /*AddrSpace=*/CGM.getDataLayout().getAllocaAddrSpace(),
1389 /*ByVal=*/false);
1390 return true;
1391 }
1392 return false;
1393}
1394
1395/// The Itanium ABI requires non-zero initialization only for data
1396/// member pointers, for which '0' is a valid offset.
1397bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
1398 return MPT->isMemberFunctionPointer();
1399}
1400
1401/// The Itanium ABI always places an offset to the complete object
1402/// at entry -2 in the vtable.
1403void ItaniumCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
1404 const CXXDeleteExpr *DE,
1405 Address Ptr,
1406 QualType ElementType,
1407 const CXXDestructorDecl *Dtor) {
1408 bool UseGlobalDelete = DE->isGlobalDelete();
1409 if (UseGlobalDelete) {
1410 // Derive the complete-object pointer, which is what we need
1411 // to pass to the deallocation function.
1412
1413 // Grab the vtable pointer as an intptr_t*.
1414 auto *ClassDecl = ElementType->castAsCXXRecordDecl();
1415 llvm::Value *VTable = CGF.GetVTablePtr(Ptr, CGF.DefaultPtrTy, ClassDecl);
1416
1417 // Track back to entry -2 and pull out the offset there.
1418 llvm::Value *OffsetPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
1419 CGF.IntPtrTy, VTable, -2, "complete-offset.ptr");
1420 llvm::Value *Offset = CGF.Builder.CreateAlignedLoad(CGF.IntPtrTy, OffsetPtr,
1421 CGF.getPointerAlign());
1422
1423 // Apply the offset.
1424 llvm::Value *CompletePtr = Ptr.emitRawPointer(CGF);
1425 CompletePtr =
1426 CGF.Builder.CreateInBoundsGEP(CGF.Int8Ty, CompletePtr, Offset);
1427
1428 // If we're supposed to call the global delete, make sure we do so
1429 // even if the destructor throws.
1430 CGF.pushCallObjectDeleteCleanup(DE->getOperatorDelete(), CompletePtr,
1431 ElementType);
1432 }
1433
1434 // FIXME: Provide a source location here even though there's no
1435 // CXXMemberCallExpr for dtor call.
1436 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
1437 EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, DE,
1438 /*CallOrInvoke=*/nullptr);
1439
1440 if (UseGlobalDelete)
1441 CGF.PopCleanupBlock();
1442}
1443
1444void ItaniumCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
1445 // void __cxa_rethrow();
1446
1447 llvm::FunctionType *FTy =
1448 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
1449
1450 llvm::FunctionCallee Fn = CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
1451
1452 if (isNoReturn)
1454 else
1456}
1457
1458static llvm::FunctionCallee getAllocateExceptionFn(CodeGenModule &CGM) {
1459 // void *__cxa_allocate_exception(size_t thrown_size);
1460
1461 llvm::FunctionType *FTy =
1462 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.SizeTy, /*isVarArg=*/false);
1463
1464 return CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
1465}
1466
1467static llvm::FunctionCallee getThrowFn(CodeGenModule &CGM) {
1468 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
1469 // void (*dest) (void *));
1470
1471 llvm::Type *Args[3] = { CGM.Int8PtrTy, CGM.GlobalsInt8PtrTy, CGM.Int8PtrTy };
1472 llvm::FunctionType *FTy =
1473 llvm::FunctionType::get(CGM.VoidTy, Args, /*isVarArg=*/false);
1474
1475 return CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
1476}
1477
1478void ItaniumCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
1479 QualType ThrowType = E->getSubExpr()->getType();
1480 // Now allocate the exception object.
1481 llvm::Type *SizeTy = CGF.ConvertType(getContext().getSizeType());
1482 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
1483
1484 llvm::FunctionCallee AllocExceptionFn = getAllocateExceptionFn(CGM);
1485 llvm::CallInst *ExceptionPtr = CGF.EmitNounwindRuntimeCall(
1486 AllocExceptionFn, llvm::ConstantInt::get(SizeTy, TypeSize), "exception");
1487
1488 CharUnits ExnAlign = CGF.getContext().getExnObjectAlignment();
1489 CGF.EmitAnyExprToExn(
1490 E->getSubExpr(), Address(ExceptionPtr, CGM.Int8Ty, ExnAlign));
1491
1492 // Now throw the exception.
1493 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
1494 /*ForEH=*/true);
1495
1496 // The address of the destructor. If the exception type has a
1497 // trivial destructor (or isn't a record), we just pass null.
1498 llvm::Constant *Dtor = nullptr;
1499 if (const auto *Record = ThrowType->getAsCXXRecordDecl();
1501 // __cxa_throw is declared to take its destructor as void (*)(void *). We
1502 // must match that if function pointers can be authenticated with a
1503 // discriminator based on their type.
1504 const ASTContext &Ctx = getContext();
1505 QualType DtorTy = Ctx.getFunctionType(Ctx.VoidTy, {Ctx.VoidPtrTy},
1506 FunctionProtoType::ExtProtoInfo());
1507
1508 CXXDestructorDecl *DtorD = Record->getDestructor();
1509 Dtor = CGM.getAddrOfCXXStructor(GlobalDecl(DtorD, Dtor_Complete));
1510 Dtor = CGM.getFunctionPointer(Dtor, DtorTy);
1511 }
1512 if (!Dtor) Dtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);
1513
1514 llvm::Value *args[] = { ExceptionPtr, TypeInfo, Dtor };
1516}
1517
1518static llvm::FunctionCallee getItaniumDynamicCastFn(CodeGenFunction &CGF) {
1519 // void *__dynamic_cast(const void *sub,
1520 // global_as const abi::__class_type_info *src,
1521 // global_as const abi::__class_type_info *dst,
1522 // std::ptrdiff_t src2dst_offset);
1523
1524 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
1525 llvm::Type *GlobInt8PtrTy = CGF.GlobalsInt8PtrTy;
1526 llvm::Type *PtrDiffTy =
1528
1529 llvm::Type *Args[4] = { Int8PtrTy, GlobInt8PtrTy, GlobInt8PtrTy, PtrDiffTy };
1530
1531 llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false);
1532
1533 // Mark the function as nounwind willreturn readonly.
1534 llvm::AttrBuilder FuncAttrs(CGF.getLLVMContext());
1535 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1536 FuncAttrs.addAttribute(llvm::Attribute::WillReturn);
1537 FuncAttrs.addMemoryAttr(llvm::MemoryEffects::readOnly());
1538 llvm::AttributeList Attrs = llvm::AttributeList::get(
1539 CGF.getLLVMContext(), llvm::AttributeList::FunctionIndex, FuncAttrs);
1540
1541 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs);
1542}
1543
1544static llvm::FunctionCallee getBadCastFn(CodeGenFunction &CGF) {
1545 // void __cxa_bad_cast();
1546 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1547 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1548}
1549
1550/// Compute the src2dst_offset hint as described in the
1551/// Itanium C++ ABI [2.9.7]
1553 const CXXRecordDecl *Src,
1554 const CXXRecordDecl *Dst) {
1555 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1556 /*DetectVirtual=*/false);
1557
1558 // If Dst is not derived from Src we can skip the whole computation below and
1559 // return that Src is not a public base of Dst. Record all inheritance paths.
1560 if (!Dst->isDerivedFrom(Src, Paths))
1561 return CharUnits::fromQuantity(-2ULL);
1562
1563 unsigned NumPublicPaths = 0;
1564 CharUnits Offset;
1565
1566 // Now walk all possible inheritance paths.
1567 for (const CXXBasePath &Path : Paths) {
1568 if (Path.Access != AS_public) // Ignore non-public inheritance.
1569 continue;
1570
1571 ++NumPublicPaths;
1572
1573 for (const CXXBasePathElement &PathElement : Path) {
1574 // If the path contains a virtual base class we can't give any hint.
1575 // -1: no hint.
1576 if (PathElement.Base->isVirtual())
1577 return CharUnits::fromQuantity(-1ULL);
1578
1579 if (NumPublicPaths > 1) // Won't use offsets, skip computation.
1580 continue;
1581
1582 // Accumulate the base class offsets.
1583 const ASTRecordLayout &L = Context.getASTRecordLayout(PathElement.Class);
1584 Offset += L.getBaseClassOffset(
1585 PathElement.Base->getType()->getAsCXXRecordDecl());
1586 }
1587 }
1588
1589 // -2: Src is not a public base of Dst.
1590 if (NumPublicPaths == 0)
1591 return CharUnits::fromQuantity(-2ULL);
1592
1593 // -3: Src is a multiple public base type but never a virtual base type.
1594 if (NumPublicPaths > 1)
1595 return CharUnits::fromQuantity(-3ULL);
1596
1597 // Otherwise, the Src type is a unique public nonvirtual base type of Dst.
1598 // Return the offset of Src from the origin of Dst.
1599 return Offset;
1600}
1601
1602static llvm::FunctionCallee getBadTypeidFn(CodeGenFunction &CGF) {
1603 // void __cxa_bad_typeid();
1604 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1605
1606 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1607}
1608
1609bool ItaniumCXXABI::shouldTypeidBeNullChecked(QualType SrcRecordTy) {
1610 return true;
1611}
1612
1613void ItaniumCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
1614 llvm::FunctionCallee Fn = getBadTypeidFn(CGF);
1615 llvm::CallBase *Call = CGF.EmitRuntimeCallOrInvoke(Fn);
1616 Call->setDoesNotReturn();
1617 CGF.Builder.CreateUnreachable();
1618}
1619
1620llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF,
1621 QualType SrcRecordTy,
1622 Address ThisPtr,
1623 llvm::Type *StdTypeInfoPtrTy) {
1624 auto *ClassDecl = SrcRecordTy->castAsCXXRecordDecl();
1625 llvm::Value *Value = CGF.GetVTablePtr(ThisPtr, CGM.GlobalsInt8PtrTy,
1626 ClassDecl);
1627
1628 if (CGM.getItaniumVTableContext().isRelativeLayout()) {
1629 // Load the type info.
1630 Value = CGF.Builder.CreateCall(
1631 CGM.getIntrinsic(llvm::Intrinsic::load_relative, {CGM.Int32Ty}),
1632 {Value, llvm::ConstantInt::getSigned(CGM.Int32Ty, -4)});
1633 } else {
1634 // Load the type info.
1635 Value =
1636 CGF.Builder.CreateConstInBoundsGEP1_64(StdTypeInfoPtrTy, Value, -1ULL);
1637 }
1638 return CGF.Builder.CreateAlignedLoad(StdTypeInfoPtrTy, Value,
1639 CGF.getPointerAlign());
1640}
1641
1642bool ItaniumCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
1643 QualType SrcRecordTy) {
1644 return SrcIsPtr;
1645}
1646
1647llvm::Value *ItaniumCXXABI::emitDynamicCastCall(
1648 CodeGenFunction &CGF, Address ThisAddr, QualType SrcRecordTy,
1649 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
1650 llvm::Type *PtrDiffLTy =
1652
1653 llvm::Value *SrcRTTI =
1655 llvm::Value *DestRTTI =
1657
1658 // Compute the offset hint.
1659 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
1660 const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
1661 llvm::Value *OffsetHint = llvm::ConstantInt::getSigned(
1662 PtrDiffLTy,
1663 computeOffsetHint(CGF.getContext(), SrcDecl, DestDecl).getQuantity());
1664
1665 // Emit the call to __dynamic_cast.
1666 llvm::Value *Value = ThisAddr.emitRawPointer(CGF);
1667 if (CGM.getCodeGenOpts().PointerAuth.CXXVTablePointers) {
1668 // We perform a no-op load of the vtable pointer here to force an
1669 // authentication. In environments that do not support pointer
1670 // authentication this is a an actual no-op that will be elided. When
1671 // pointer authentication is supported and enforced on vtable pointers this
1672 // load can trap.
1673 llvm::Value *Vtable =
1674 CGF.GetVTablePtr(ThisAddr, CGM.Int8PtrTy, SrcDecl,
1675 CodeGenFunction::VTableAuthMode::MustTrap);
1676 assert(Vtable);
1677 (void)Vtable;
1678 }
1679
1680 llvm::Value *args[] = {Value, SrcRTTI, DestRTTI, OffsetHint};
1682
1683 /// C++ [expr.dynamic.cast]p9:
1684 /// A failed cast to reference type throws std::bad_cast
1685 if (DestTy->isReferenceType()) {
1686 llvm::BasicBlock *BadCastBlock =
1687 CGF.createBasicBlock("dynamic_cast.bad_cast");
1688
1689 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1690 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1691
1692 CGF.EmitBlock(BadCastBlock);
1693 EmitBadCastCall(CGF);
1694 }
1695
1696 return Value;
1697}
1698
1699std::optional<CGCXXABI::ExactDynamicCastInfo>
1700ItaniumCXXABI::getExactDynamicCastInfo(QualType SrcRecordTy, QualType DestTy,
1701 QualType DestRecordTy) {
1702 assert(shouldEmitExactDynamicCast(DestRecordTy));
1703
1704 ASTContext &Context = getContext();
1705
1706 // Find all the inheritance paths.
1707 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
1708 const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
1709 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1710 /*DetectVirtual=*/false);
1711 (void)DestDecl->isDerivedFrom(SrcDecl, Paths);
1712
1713 // Find an offset within `DestDecl` where a `SrcDecl` instance and its vptr
1714 // might appear.
1715 std::optional<CharUnits> Offset;
1716 for (const CXXBasePath &Path : Paths) {
1717 // dynamic_cast only finds public inheritance paths.
1718 if (Path.Access != AS_public)
1719 continue;
1720
1721 CharUnits PathOffset;
1722 for (const CXXBasePathElement &PathElement : Path) {
1723 // Find the offset along this inheritance step.
1724 const CXXRecordDecl *Base =
1725 PathElement.Base->getType()->getAsCXXRecordDecl();
1726 if (PathElement.Base->isVirtual()) {
1727 // For a virtual base class, we know that the derived class is exactly
1728 // DestDecl, so we can use the vbase offset from its layout.
1729 const ASTRecordLayout &L = Context.getASTRecordLayout(DestDecl);
1730 PathOffset = L.getVBaseClassOffset(Base);
1731 } else {
1732 const ASTRecordLayout &L =
1733 Context.getASTRecordLayout(PathElement.Class);
1734 PathOffset += L.getBaseClassOffset(Base);
1735 }
1736 }
1737
1738 if (!Offset)
1739 Offset = PathOffset;
1740 else if (Offset != PathOffset) {
1741 // Base appears in at least two different places.
1742 return ExactDynamicCastInfo{/*RequiresCastToPrimaryBase=*/true,
1743 CharUnits::Zero()};
1744 }
1745 }
1746 if (!Offset)
1747 return std::nullopt;
1748 return ExactDynamicCastInfo{/*RequiresCastToPrimaryBase=*/false, *Offset};
1749}
1750
1751llvm::Value *ItaniumCXXABI::emitExactDynamicCast(
1752 CodeGenFunction &CGF, Address ThisAddr, QualType SrcRecordTy,
1753 QualType DestTy, QualType DestRecordTy,
1754 const ExactDynamicCastInfo &ExactCastInfo, llvm::BasicBlock *CastSuccess,
1755 llvm::BasicBlock *CastFail) {
1756 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
1757 const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
1758 auto AuthenticateVTable = [&](Address ThisAddr, const CXXRecordDecl *Decl) {
1759 if (!CGF.getLangOpts().PointerAuthCalls)
1760 return;
1761 (void)CGF.GetVTablePtr(ThisAddr, CGF.DefaultPtrTy, Decl,
1762 CodeGenFunction::VTableAuthMode::MustTrap);
1763 };
1764
1765 bool PerformPostCastAuthentication = false;
1766 llvm::Value *VTable = nullptr;
1767 if (ExactCastInfo.RequiresCastToPrimaryBase) {
1768 // Base appears in at least two different places. Find the most-derived
1769 // object and see if it's a DestDecl. Note that the most-derived object
1770 // must be at least as aligned as this base class subobject, and must
1771 // have a vptr at offset 0.
1772 llvm::Value *PrimaryBase =
1773 emitDynamicCastToVoid(CGF, ThisAddr, SrcRecordTy);
1774 ThisAddr = Address(PrimaryBase, CGF.VoidPtrTy, ThisAddr.getAlignment());
1775 SrcDecl = DestDecl;
1776 // This unauthenticated load is unavoidable, so we're relying on the
1777 // authenticated load in the dynamic cast to void, and we'll manually
1778 // authenticate the resulting v-table at the end of the cast check.
1779 PerformPostCastAuthentication = CGF.getLangOpts().PointerAuthCalls;
1780 CGPointerAuthInfo StrippingAuthInfo(0, PointerAuthenticationMode::Strip,
1781 false, false, nullptr);
1782 Address VTablePtrPtr = ThisAddr.withElementType(CGF.VoidPtrPtrTy);
1783 VTable = CGF.Builder.CreateLoad(VTablePtrPtr, "vtable");
1784 if (PerformPostCastAuthentication)
1785 VTable = CGF.EmitPointerAuthAuth(StrippingAuthInfo, VTable);
1786 } else
1787 VTable = CGF.GetVTablePtr(ThisAddr, CGF.DefaultPtrTy, SrcDecl);
1788
1789 // Compare the vptr against the expected vptr for the destination type at
1790 // this offset.
1791 llvm::Constant *ExpectedVTable = getVTableAddressPoint(
1792 BaseSubobject(SrcDecl, ExactCastInfo.Offset), DestDecl);
1793 llvm::Value *Success = CGF.Builder.CreateICmpEQ(VTable, ExpectedVTable);
1794 llvm::Value *AdjustedThisPtr = ThisAddr.emitRawPointer(CGF);
1795
1796 if (!ExactCastInfo.Offset.isZero()) {
1797 CharUnits::QuantityType Offset = ExactCastInfo.Offset.getQuantity();
1798 llvm::Constant *OffsetConstant =
1799 llvm::ConstantInt::get(CGF.PtrDiffTy, -Offset);
1800 AdjustedThisPtr = CGF.Builder.CreateInBoundsGEP(CGF.CharTy, AdjustedThisPtr,
1801 OffsetConstant);
1802 PerformPostCastAuthentication = CGF.getLangOpts().PointerAuthCalls;
1803 }
1804
1805 if (PerformPostCastAuthentication) {
1806 // If we've changed the object pointer we authenticate the vtable pointer
1807 // of the resulting object.
1808 llvm::BasicBlock *NonNullBlock = CGF.Builder.GetInsertBlock();
1809 llvm::BasicBlock *PostCastAuthSuccess =
1810 CGF.createBasicBlock("dynamic_cast.postauth.success");
1811 llvm::BasicBlock *PostCastAuthComplete =
1812 CGF.createBasicBlock("dynamic_cast.postauth.complete");
1813 CGF.Builder.CreateCondBr(Success, PostCastAuthSuccess,
1814 PostCastAuthComplete);
1815 CGF.EmitBlock(PostCastAuthSuccess);
1816 Address AdjustedThisAddr =
1817 Address(AdjustedThisPtr, CGF.IntPtrTy, CGF.getPointerAlign());
1818 AuthenticateVTable(AdjustedThisAddr, DestDecl);
1819 CGF.EmitBranch(PostCastAuthComplete);
1820 CGF.EmitBlock(PostCastAuthComplete);
1821 llvm::PHINode *PHI = CGF.Builder.CreatePHI(AdjustedThisPtr->getType(), 2);
1822 PHI->addIncoming(AdjustedThisPtr, PostCastAuthSuccess);
1823 llvm::Value *NullValue =
1824 llvm::Constant::getNullValue(AdjustedThisPtr->getType());
1825 PHI->addIncoming(NullValue, NonNullBlock);
1826 AdjustedThisPtr = PHI;
1827 }
1828 CGF.Builder.CreateCondBr(Success, CastSuccess, CastFail);
1829 return AdjustedThisPtr;
1830}
1831
1832llvm::Value *ItaniumCXXABI::emitDynamicCastToVoid(CodeGenFunction &CGF,
1833 Address ThisAddr,
1834 QualType SrcRecordTy) {
1835 auto *ClassDecl = SrcRecordTy->castAsCXXRecordDecl();
1836 llvm::Value *OffsetToTop;
1837 if (CGM.getItaniumVTableContext().isRelativeLayout()) {
1838 // Get the vtable pointer.
1839 llvm::Value *VTable =
1840 CGF.GetVTablePtr(ThisAddr, CGF.DefaultPtrTy, ClassDecl);
1841
1842 // Get the offset-to-top from the vtable.
1843 OffsetToTop =
1844 CGF.Builder.CreateConstInBoundsGEP1_32(CGM.Int32Ty, VTable, -2U);
1845 OffsetToTop = CGF.Builder.CreateAlignedLoad(
1846 CGM.Int32Ty, OffsetToTop, CharUnits::fromQuantity(4), "offset.to.top");
1847 } else {
1848 llvm::Type *PtrDiffLTy =
1850
1851 // Get the vtable pointer.
1852 llvm::Value *VTable =
1853 CGF.GetVTablePtr(ThisAddr, CGF.DefaultPtrTy, ClassDecl);
1854
1855 // Get the offset-to-top from the vtable.
1856 OffsetToTop =
1857 CGF.Builder.CreateConstInBoundsGEP1_64(PtrDiffLTy, VTable, -2ULL);
1858 OffsetToTop = CGF.Builder.CreateAlignedLoad(
1859 PtrDiffLTy, OffsetToTop, CGF.getPointerAlign(), "offset.to.top");
1860 }
1861 // Finally, add the offset to the pointer.
1862 return CGF.Builder.CreateInBoundsGEP(CGF.Int8Ty, ThisAddr.emitRawPointer(CGF),
1863 OffsetToTop);
1864}
1865
1866bool ItaniumCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1867 llvm::FunctionCallee Fn = getBadCastFn(CGF);
1868 llvm::CallBase *Call = CGF.EmitRuntimeCallOrInvoke(Fn);
1869 Call->setDoesNotReturn();
1870 CGF.Builder.CreateUnreachable();
1871 return true;
1872}
1873
1874llvm::Value *
1875ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
1876 Address This,
1877 const CXXRecordDecl *ClassDecl,
1878 const CXXRecordDecl *BaseClassDecl) {
1879 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy, ClassDecl);
1880 CharUnits VBaseOffsetOffset =
1881 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
1882 BaseClassDecl);
1883 llvm::Value *VBaseOffsetPtr =
1884 CGF.Builder.CreateConstGEP1_64(
1885 CGF.Int8Ty, VTablePtr, VBaseOffsetOffset.getQuantity(),
1886 "vbase.offset.ptr");
1887
1888 llvm::Value *VBaseOffset;
1889 if (CGM.getItaniumVTableContext().isRelativeLayout()) {
1890 VBaseOffset = CGF.Builder.CreateAlignedLoad(
1891 CGF.Int32Ty, VBaseOffsetPtr, CharUnits::fromQuantity(4),
1892 "vbase.offset");
1893 } else {
1894 VBaseOffset = CGF.Builder.CreateAlignedLoad(
1895 CGM.PtrDiffTy, VBaseOffsetPtr, CGF.getPointerAlign(), "vbase.offset");
1896 }
1897 return VBaseOffset;
1898}
1899
1900void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1901 // Just make sure we're in sync with TargetCXXABI.
1902 assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
1903
1904 // The constructor used for constructing this as a base class;
1905 // ignores virtual bases.
1906 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
1907
1908 // The constructor used for constructing this as a complete class;
1909 // constructs the virtual bases, then calls the base constructor.
1910 if (!D->getParent()->isAbstract()) {
1911 // We don't need to emit the complete ctor if the class is abstract.
1912 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1913 }
1914}
1915
1916CGCXXABI::AddedStructorArgCounts
1917ItaniumCXXABI::buildStructorSignature(GlobalDecl GD,
1918 SmallVectorImpl<CanQualType> &ArgTys) {
1919 ASTContext &Context = getContext();
1920
1921 // All parameters are already in place except VTT, which goes after 'this'.
1922 // These are Clang types, so we don't need to worry about sret yet.
1923
1924 // Check if we need to add a VTT parameter (which has type global void **).
1926 : GD.getDtorType() == Dtor_Base) &&
1927 cast<CXXMethodDecl>(GD.getDecl())->getParent()->getNumVBases() != 0) {
1928 LangAS AS = CGM.GetGlobalVarAddressSpace(nullptr);
1929 QualType Q = Context.getAddrSpaceQualType(Context.VoidPtrTy, AS);
1930 ArgTys.insert(ArgTys.begin() + 1,
1932 return AddedStructorArgCounts::prefix(1);
1933 }
1934 return AddedStructorArgCounts{};
1935}
1936
1937void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
1938 // The destructor used for destructing this as a base class; ignores
1939 // virtual bases.
1940 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
1941
1942 // The destructor used for destructing this as a most-derived class;
1943 // call the base destructor and then destructs any virtual bases.
1944 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
1945
1946 // The destructor in a virtual table is always a 'deleting'
1947 // destructor, which calls the complete destructor and then uses the
1948 // appropriate operator delete.
1949 if (D->isVirtual())
1950 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
1951}
1952
1953void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1954 QualType &ResTy,
1955 FunctionArgList &Params) {
1956 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
1958
1959 // Check if we need a VTT parameter as well.
1960 if (NeedsVTTParameter(CGF.CurGD)) {
1961 ASTContext &Context = getContext();
1962
1963 // FIXME: avoid the fake decl
1964 LangAS AS = CGM.GetGlobalVarAddressSpace(nullptr);
1965 QualType Q = Context.getAddrSpaceQualType(Context.VoidPtrTy, AS);
1966 QualType T = Context.getPointerType(Q);
1967 auto *VTTDecl = ImplicitParamDecl::Create(
1968 Context, /*DC=*/nullptr, MD->getLocation(), &Context.Idents.get("vtt"),
1969 T, ImplicitParamKind::CXXVTT);
1970 Params.insert(Params.begin() + 1, VTTDecl);
1971 getStructorImplicitParamDecl(CGF) = VTTDecl;
1972 }
1973}
1974
1975void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
1976 // Naked functions have no prolog.
1977 if (CGF.CurFuncDecl && CGF.CurFuncDecl->hasAttr<NakedAttr>())
1978 return;
1979
1980 /// Initialize the 'this' slot. In the Itanium C++ ABI, no prologue
1981 /// adjustments are required, because they are all handled by thunks.
1982 setCXXABIThisValue(CGF, loadIncomingCXXThis(CGF));
1983
1984 /// Initialize the 'vtt' slot if needed.
1985 if (getStructorImplicitParamDecl(CGF)) {
1986 getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
1987 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
1988 }
1989
1990 /// If this is a function that the ABI specifies returns 'this', initialize
1991 /// the return slot to 'this' at the start of the function.
1992 ///
1993 /// Unlike the setting of return types, this is done within the ABI
1994 /// implementation instead of by clients of CGCXXABI because:
1995 /// 1) getThisValue is currently protected
1996 /// 2) in theory, an ABI could implement 'this' returns some other way;
1997 /// HasThisReturn only specifies a contract, not the implementation
1998 if (HasThisReturn(CGF.CurGD))
1999 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
2000}
2001
2002CGCXXABI::AddedStructorArgs ItaniumCXXABI::getImplicitConstructorArgs(
2003 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
2004 bool ForVirtualBase, bool Delegating) {
2005 if (!NeedsVTTParameter(GlobalDecl(D, Type)))
2006 return AddedStructorArgs{};
2007
2008 // Insert the implicit 'vtt' argument as the second argument. Make sure to
2009 // correctly reflect its address space, which can differ from generic on
2010 // some targets.
2011 llvm::Value *VTT =
2012 CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating);
2013 LangAS AS = CGM.GetGlobalVarAddressSpace(nullptr);
2014 QualType Q = getContext().getAddrSpaceQualType(getContext().VoidPtrTy, AS);
2015 QualType VTTTy = getContext().getPointerType(Q);
2016 return AddedStructorArgs::prefix({{VTT, VTTTy}});
2017}
2018
2019llvm::Value *ItaniumCXXABI::getCXXDestructorImplicitParam(
2020 CodeGenFunction &CGF, const CXXDestructorDecl *DD, CXXDtorType Type,
2021 bool ForVirtualBase, bool Delegating) {
2022 GlobalDecl GD(DD, Type);
2023 return CGF.GetVTTParameter(GD, ForVirtualBase, Delegating);
2024}
2025
2026void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
2027 const CXXDestructorDecl *DD,
2028 CXXDtorType Type, bool ForVirtualBase,
2029 bool Delegating, Address This,
2030 QualType ThisTy) {
2031 GlobalDecl GD(DD, Type);
2032 llvm::Value *VTT =
2033 getCXXDestructorImplicitParam(CGF, DD, Type, ForVirtualBase, Delegating);
2034 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
2035
2036 CGCallee Callee;
2037 if (getContext().getLangOpts().AppleKext &&
2038 Type != Dtor_Base && DD->isVirtual())
2040 else
2041 Callee = CGCallee::forDirect(CGM.getAddrOfCXXStructor(GD), GD);
2042
2043 CGF.EmitCXXDestructorCall(GD, Callee, CGF.getAsNaturalPointerTo(This, ThisTy),
2044 ThisTy, VTT, VTTTy, nullptr);
2045}
2046
2047// Check if any non-inline method has the specified attribute.
2048template <typename T>
2050 for (const auto *D : RD->noload_decls()) {
2051 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
2052 if (FD->isInlined() || FD->doesThisDeclarationHaveABody() ||
2053 FD->isPureVirtual())
2054 continue;
2055 if (D->hasAttr<T>())
2056 return true;
2057 }
2058 }
2059
2060 return false;
2061}
2062
2064 llvm::GlobalVariable *VTable,
2065 const CXXRecordDecl *RD) {
2066 if (VTable->getDLLStorageClass() !=
2067 llvm::GlobalVariable::DefaultStorageClass ||
2068 RD->hasAttr<DLLImportAttr>() || RD->hasAttr<DLLExportAttr>())
2069 return;
2070
2071 if (CGM.getVTables().isVTableExternal(RD)) {
2073 VTable->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2075 VTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
2076}
2077
2078void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
2079 const CXXRecordDecl *RD) {
2080 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
2081 if (VTable->hasInitializer())
2082 return;
2083
2084 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
2085 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
2086 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
2087 llvm::Constant *RTTI =
2088 CGM.GetAddrOfRTTIDescriptor(CGM.getContext().getCanonicalTagType(RD));
2089
2090 // Create and set the initializer.
2091 ConstantInitBuilder builder(CGM);
2092 auto components = builder.beginStruct();
2093 CGVT.createVTableInitializer(components, VTLayout, RTTI,
2094 llvm::GlobalValue::isLocalLinkage(Linkage));
2095 components.finishAndSetAsInitializer(VTable);
2096
2097 // Set the correct linkage.
2098 VTable->setLinkage(Linkage);
2099
2100 if (CGM.supportsCOMDAT() && VTable->isWeakForLinker())
2101 VTable->setComdat(CGM.getModule().getOrInsertComdat(VTable->getName()));
2102
2103 if (CGM.getTarget().hasPS4DLLImportExport())
2104 setVTableSelectiveDLLImportExport(CGM, VTable, RD);
2105
2106 // Set the right visibility.
2107 CGM.setGVProperties(VTable, RD);
2108
2109 // If this is the magic class __cxxabiv1::__fundamental_type_info,
2110 // we will emit the typeinfo for the fundamental types. This is the
2111 // same behaviour as GCC.
2112 const DeclContext *DC = RD->getDeclContext();
2113 if (RD->getIdentifier() &&
2114 RD->getIdentifier()->isStr("__fundamental_type_info") &&
2115 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
2116 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
2118 EmitFundamentalRTTIDescriptors(RD);
2119
2120 // Always emit type metadata on non-available_externally definitions, and on
2121 // available_externally definitions if we are performing whole program
2122 // devirtualization or speculative devirtualization. We need the type metadata
2123 // on all vtable definitions to ensure we associate derived classes with base
2124 // classes defined in headers but with a strong definition only in a shared
2125 // library.
2126 if (!VTable->isDeclarationForLinker() ||
2127 CGM.getCodeGenOpts().WholeProgramVTables ||
2128 CGM.getCodeGenOpts().DevirtualizeSpeculatively) {
2129 CGM.EmitVTableTypeMetadata(RD, VTable, VTLayout);
2130 // For available_externally definitions, add the vtable to
2131 // @llvm.compiler.used so that it isn't deleted before whole program
2132 // analysis.
2133 if (VTable->isDeclarationForLinker()) {
2134 assert(CGM.getCodeGenOpts().WholeProgramVTables ||
2135 CGM.getCodeGenOpts().DevirtualizeSpeculatively);
2136 CGM.addCompilerUsedGlobal(VTable);
2137 }
2138 }
2139
2140 if (VTContext.isRelativeLayout()) {
2141 CGVT.RemoveHwasanMetadata(VTable);
2142 if (!VTable->isDSOLocal())
2143 CGVT.GenerateRelativeVTableAlias(VTable, VTable->getName());
2144 }
2145
2146 // Emit symbol for debugger only if requested debug info.
2147 if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
2148 DI->emitVTableSymbol(VTable, RD);
2149}
2150
2151bool ItaniumCXXABI::isVirtualOffsetNeededForVTableField(
2152 CodeGenFunction &CGF, CodeGenFunction::VPtr Vptr) {
2153 if (Vptr.NearestVBase == nullptr)
2154 return false;
2155 return NeedsVTTParameter(CGF.CurGD);
2156}
2157
2158llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
2159 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
2160 const CXXRecordDecl *NearestVBase) {
2161
2162 if ((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
2163 NeedsVTTParameter(CGF.CurGD)) {
2164 return getVTableAddressPointInStructorWithVTT(CGF, VTableClass, Base,
2165 NearestVBase);
2166 }
2167 return getVTableAddressPoint(Base, VTableClass);
2168}
2169
2170llvm::Constant *
2171ItaniumCXXABI::getVTableAddressPoint(BaseSubobject Base,
2172 const CXXRecordDecl *VTableClass) {
2173 llvm::GlobalValue *VTable = getAddrOfVTable(VTableClass, CharUnits());
2174
2175 // Find the appropriate vtable within the vtable group, and the address point
2176 // within that vtable.
2177 const VTableLayout &Layout =
2178 CGM.getItaniumVTableContext().getVTableLayout(VTableClass);
2179 VTableLayout::AddressPointLocation AddressPoint =
2180 Layout.getAddressPoint(Base);
2181 llvm::Value *Indices[] = {
2182 llvm::ConstantInt::get(CGM.Int32Ty, 0),
2183 llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint.VTableIndex),
2184 llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint.AddressPointIndex),
2185 };
2186
2187 // Add inrange attribute to indicate that only the VTableIndex can be
2188 // accessed.
2189 unsigned ComponentSize =
2190 CGM.getDataLayout().getTypeAllocSize(CGM.getVTableComponentType());
2191 unsigned VTableSize =
2192 ComponentSize * Layout.getVTableSize(AddressPoint.VTableIndex);
2193 unsigned Offset = ComponentSize * AddressPoint.AddressPointIndex;
2194 llvm::ConstantRange InRange(
2195 llvm::APInt(32, (int)-Offset, true),
2196 llvm::APInt(32, (int)(VTableSize - Offset), true));
2197 return llvm::ConstantExpr::getGetElementPtr(
2198 VTable->getValueType(), VTable, Indices, /*InBounds=*/true, InRange);
2199}
2200
2201llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructorWithVTT(
2202 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
2203 const CXXRecordDecl *NearestVBase) {
2204 assert((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
2205 NeedsVTTParameter(CGF.CurGD) && "This class doesn't have VTT");
2206
2207 // Get the secondary vpointer index.
2208 uint64_t VirtualPointerIndex =
2209 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
2210
2211 /// Load the VTT.
2212 llvm::Value *VTT = CGF.LoadCXXVTT();
2213 if (VirtualPointerIndex)
2214 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(CGF.GlobalsVoidPtrTy, VTT,
2215 VirtualPointerIndex);
2216
2217 // And load the address point from the VTT.
2218 llvm::Value *AP =
2220 CGF.getPointerAlign());
2221
2222 if (auto &Schema = CGF.CGM.getCodeGenOpts().PointerAuth.CXXVTTVTablePointers) {
2223 CGPointerAuthInfo PointerAuth = CGF.EmitPointerAuthInfo(Schema, VTT,
2224 GlobalDecl(),
2225 QualType());
2226 AP = CGF.EmitPointerAuthAuth(PointerAuth, AP);
2227 }
2228
2229 return AP;
2230}
2231
2232llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
2233 CharUnits VPtrOffset) {
2234 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
2235
2236 llvm::GlobalVariable *&VTable = VTables[RD];
2237 if (VTable)
2238 return VTable;
2239
2240 // Queue up this vtable for possible deferred emission.
2241 CGM.addDeferredVTable(RD);
2242
2243 SmallString<256> Name;
2244 llvm::raw_svector_ostream Out(Name);
2245 getMangleContext().mangleCXXVTable(RD, Out);
2246
2247 const VTableLayout &VTLayout =
2248 CGM.getItaniumVTableContext().getVTableLayout(RD);
2249 llvm::Type *VTableType = CGM.getVTables().getVTableType(VTLayout);
2250
2251 // Use pointer to global alignment for the vtable. Otherwise we would align
2252 // them based on the size of the initializer which doesn't make sense as only
2253 // single values are read.
2254 unsigned PAlign = CGM.getVtableGlobalVarAlignment();
2255
2256 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
2257 Name, VTableType, llvm::GlobalValue::ExternalLinkage,
2258 getContext().toCharUnitsFromBits(PAlign).getAsAlign());
2259 VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2260
2261 if (CGM.getTarget().hasPS4DLLImportExport())
2262 setVTableSelectiveDLLImportExport(CGM, VTable, RD);
2263
2264 CGM.setGVProperties(VTable, RD);
2265 return VTable;
2266}
2267
2268CGCallee ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
2269 GlobalDecl GD,
2270 Address This,
2271 llvm::Type *Ty,
2272 SourceLocation Loc) {
2273 llvm::Type *PtrTy = CGM.GlobalsInt8PtrTy;
2274 auto *MethodDecl = cast<CXXMethodDecl>(GD.getDecl());
2275 llvm::Value *VTable = CGF.GetVTablePtr(This, PtrTy, MethodDecl->getParent());
2276
2277 // For the translation of virtual functions, we need to map the (potential)
2278 // host vtable to the device vtable. This is done by calling the runtime
2279 // function
2280 // __llvm_omp_indirect_call_lookup.
2281 if (CGM.getLangOpts().OpenMPIsTargetDevice) {
2282 auto *NewPtrTy = CGM.VoidPtrTy;
2283 llvm::Type *RtlFnArgs[] = {NewPtrTy};
2284 llvm::FunctionCallee DeviceRtlFn = CGM.CreateRuntimeFunction(
2285 llvm::FunctionType::get(NewPtrTy, RtlFnArgs, false),
2286 "__llvm_omp_indirect_call_lookup");
2287 auto *BackupTy = VTable->getType();
2288 // Need to convert to generic address space
2289 VTable = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(VTable, NewPtrTy);
2290 VTable = CGF.EmitRuntimeCall(DeviceRtlFn, {VTable});
2291 // convert to original address space
2292 VTable = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(VTable, BackupTy);
2293 }
2294
2295 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
2296 llvm::Value *VFunc, *VTableSlotPtr = nullptr;
2297 auto &Schema = CGM.getCodeGenOpts().PointerAuth.CXXVirtualFunctionPointers;
2298
2299 llvm::Type *ComponentTy = CGM.getVTables().getVTableComponentType();
2300 uint64_t ByteOffset =
2301 VTableIndex * CGM.getDataLayout().getTypeSizeInBits(ComponentTy) / 8;
2302
2303 if (!Schema && CGF.ShouldEmitVTableTypeCheckedLoad(MethodDecl->getParent())) {
2304 VFunc = CGF.EmitVTableTypeCheckedLoad(MethodDecl->getParent(), VTable,
2305 PtrTy, ByteOffset);
2306 } else {
2307 CGF.EmitTypeMetadataCodeForVCall(MethodDecl->getParent(), VTable, Loc);
2308
2309 llvm::Value *VFuncLoad;
2310 if (CGM.getItaniumVTableContext().isRelativeLayout()) {
2311 VFuncLoad = CGF.Builder.CreateCall(
2312 CGM.getIntrinsic(llvm::Intrinsic::load_relative, {CGM.Int32Ty}),
2313 {VTable, llvm::ConstantInt::get(CGM.Int32Ty, ByteOffset)});
2314 } else {
2315 VTableSlotPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
2316 PtrTy, VTable, VTableIndex, "vfn");
2317 VFuncLoad = CGF.Builder.CreateAlignedLoad(PtrTy, VTableSlotPtr,
2318 CGF.getPointerAlign());
2319 }
2320
2321 // Add !invariant.load md to virtual function load to indicate that
2322 // function didn't change inside vtable.
2323 // It's safe to add it without -fstrict-vtable-pointers, but it would not
2324 // help in devirtualization because it will only matter if we will have 2
2325 // the same virtual function loads from the same vtable load, which won't
2326 // happen without enabled devirtualization with -fstrict-vtable-pointers.
2327 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2328 CGM.getCodeGenOpts().StrictVTablePointers) {
2329 if (auto *VFuncLoadInstr = dyn_cast<llvm::Instruction>(VFuncLoad)) {
2330 VFuncLoadInstr->setMetadata(
2331 llvm::LLVMContext::MD_invariant_load,
2332 llvm::MDNode::get(CGM.getLLVMContext(),
2333 llvm::ArrayRef<llvm::Metadata *>()));
2334 }
2335 }
2336 VFunc = VFuncLoad;
2337 }
2338
2339 CGPointerAuthInfo PointerAuth;
2340 if (Schema) {
2341 assert(VTableSlotPtr && "virtual function pointer not set");
2342 GD = CGM.getItaniumVTableContext().findOriginalMethod(GD.getCanonicalDecl());
2343 PointerAuth = CGF.EmitPointerAuthInfo(Schema, VTableSlotPtr, GD, QualType());
2344 }
2345 CGCallee Callee(GD, VFunc, PointerAuth);
2346 return Callee;
2347}
2348
2349llvm::Value *ItaniumCXXABI::EmitVirtualDestructorCall(
2350 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
2351 Address This, DeleteOrMemberCallExpr E, llvm::CallBase **CallOrInvoke) {
2352 auto *CE = dyn_cast<const CXXMemberCallExpr *>(E);
2353 auto *D = dyn_cast<const CXXDeleteExpr *>(E);
2354 assert((CE != nullptr) ^ (D != nullptr));
2355 assert(CE == nullptr || CE->arguments().empty());
2356 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
2357
2358 GlobalDecl GD(Dtor, DtorType);
2359 const CGFunctionInfo *FInfo =
2360 &CGM.getTypes().arrangeCXXStructorDeclaration(GD);
2361 llvm::FunctionType *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
2362 CGCallee Callee = CGCallee::forVirtual(CE, GD, This, Ty);
2363
2364 QualType ThisTy;
2365 if (CE) {
2366 ThisTy = CE->getObjectType();
2367 } else {
2368 ThisTy = D->getDestroyedType();
2369 }
2370
2371 CGF.EmitCXXDestructorCall(GD, Callee, This.emitRawPointer(CGF), ThisTy,
2372 nullptr, QualType(), nullptr, CallOrInvoke);
2373 return nullptr;
2374}
2375
2376void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
2377 CodeGenVTables &VTables = CGM.getVTables();
2378 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
2379 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
2380}
2381
2382bool ItaniumCXXABI::canSpeculativelyEmitVTableAsBaseClass(
2383 const CXXRecordDecl *RD) const {
2384 // We don't emit available_externally vtables if we are in -fapple-kext mode
2385 // because kext mode does not permit devirtualization.
2386 if (CGM.getLangOpts().AppleKext)
2387 return false;
2388
2389 // If the vtable is hidden then it is not safe to emit an available_externally
2390 // copy of vtable.
2391 if (isVTableHidden(RD))
2392 return false;
2393
2394 if (CGM.getCodeGenOpts().ForceEmitVTables)
2395 return true;
2396
2397 // A speculative vtable can only be generated if all virtual inline functions
2398 // defined by this class are emitted. The vtable in the final program contains
2399 // for each virtual inline function not used in the current TU a function that
2400 // is equivalent to the unused function. The function in the actual vtable
2401 // does not have to be declared under the same symbol (e.g., a virtual
2402 // destructor that can be substituted with its base class's destructor). Since
2403 // inline functions are emitted lazily and this emissions does not account for
2404 // speculative emission of a vtable, we might generate a speculative vtable
2405 // with references to inline functions that are not emitted under that name.
2406 // This can lead to problems when devirtualizing a call to such a function,
2407 // that result in linking errors. Hence, if there are any unused virtual
2408 // inline function, we cannot emit the speculative vtable.
2409 // FIXME we can still emit a copy of the vtable if we
2410 // can emit definition of the inline functions.
2411 if (hasAnyUnusedVirtualInlineFunction(RD))
2412 return false;
2413
2414 // For a class with virtual bases, we must also be able to speculatively
2415 // emit the VTT, because CodeGen doesn't have separate notions of "can emit
2416 // the vtable" and "can emit the VTT". For a base subobject, this means we
2417 // need to be able to emit non-virtual base vtables.
2418 if (RD->getNumVBases()) {
2419 for (const auto &B : RD->bases()) {
2420 auto *BRD = B.getType()->getAsCXXRecordDecl();
2421 assert(BRD && "no class for base specifier");
2422 if (B.isVirtual() || !BRD->isDynamicClass())
2423 continue;
2424 if (!canSpeculativelyEmitVTableAsBaseClass(BRD))
2425 return false;
2426 }
2427 }
2428
2429 return true;
2430}
2431
2432bool ItaniumCXXABI::canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const {
2433 if (!canSpeculativelyEmitVTableAsBaseClass(RD))
2434 return false;
2435
2437 return false;
2438
2439 // For a complete-object vtable (or more specifically, for the VTT), we need
2440 // to be able to speculatively emit the vtables of all dynamic virtual bases.
2441 for (const auto &B : RD->vbases()) {
2442 auto *BRD = B.getType()->getAsCXXRecordDecl();
2443 assert(BRD && "no class for base specifier");
2444 if (!BRD->isDynamicClass())
2445 continue;
2446 if (!canSpeculativelyEmitVTableAsBaseClass(BRD))
2447 return false;
2448 }
2449
2450 return true;
2451}
2453 Address InitialPtr,
2454 const CXXRecordDecl *UnadjustedClass,
2455 int64_t NonVirtualAdjustment,
2456 int64_t VirtualAdjustment,
2457 bool IsReturnAdjustment) {
2458 if (!NonVirtualAdjustment && !VirtualAdjustment)
2459 return InitialPtr.emitRawPointer(CGF);
2460
2461 Address V = InitialPtr.withElementType(CGF.Int8Ty);
2462
2463 // In a base-to-derived cast, the non-virtual adjustment is applied first.
2464 if (NonVirtualAdjustment && !IsReturnAdjustment) {
2466 CharUnits::fromQuantity(NonVirtualAdjustment));
2467 }
2468
2469 // Perform the virtual adjustment if we have one.
2470 llvm::Value *ResultPtr;
2471 if (VirtualAdjustment) {
2472 llvm::Value *VTablePtr =
2473 CGF.GetVTablePtr(V, CGF.Int8PtrTy, UnadjustedClass);
2474
2475 llvm::Value *Offset;
2476 llvm::Value *OffsetPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
2477 CGF.Int8Ty, VTablePtr, VirtualAdjustment);
2479 // Load the adjustment offset from the vtable as a 32-bit int.
2480 Offset =
2481 CGF.Builder.CreateAlignedLoad(CGF.Int32Ty, OffsetPtr,
2483 } else {
2484 llvm::Type *PtrDiffTy =
2486
2487 // Load the adjustment offset from the vtable.
2488 Offset = CGF.Builder.CreateAlignedLoad(PtrDiffTy, OffsetPtr,
2489 CGF.getPointerAlign());
2490 }
2491 // Adjust our pointer.
2492 ResultPtr = CGF.Builder.CreateInBoundsGEP(V.getElementType(),
2493 V.emitRawPointer(CGF), Offset);
2494 } else {
2495 ResultPtr = V.emitRawPointer(CGF);
2496 }
2497
2498 // In a derived-to-base conversion, the non-virtual adjustment is
2499 // applied second.
2500 if (NonVirtualAdjustment && IsReturnAdjustment) {
2501 ResultPtr = CGF.Builder.CreateConstInBoundsGEP1_64(CGF.Int8Ty, ResultPtr,
2502 NonVirtualAdjustment);
2503 }
2504
2505 return ResultPtr;
2506}
2507
2508llvm::Value *
2509ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF, Address This,
2510 const CXXRecordDecl *UnadjustedClass,
2511 const ThunkInfo &TI) {
2512 return performTypeAdjustment(CGF, This, UnadjustedClass, TI.This.NonVirtual,
2514 /*IsReturnAdjustment=*/false);
2515}
2516
2517llvm::Value *
2518ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
2519 const CXXRecordDecl *UnadjustedClass,
2520 const ReturnAdjustment &RA) {
2521 return performTypeAdjustment(CGF, Ret, UnadjustedClass, RA.NonVirtual,
2523 /*IsReturnAdjustment=*/true);
2524}
2525
2526void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
2527 RValue RV, QualType ResultType) {
2529 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
2530
2531 // Destructor thunks in the ARM ABI have indeterminate results.
2532 llvm::Type *T = CGF.ReturnValue.getElementType();
2533 RValue Undef = RValue::get(llvm::UndefValue::get(T));
2534 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
2535}
2536
2537/************************** Array allocation cookies **************************/
2538
2539CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
2540 // The array cookie is a size_t; pad that up to the element alignment.
2541 // The cookie is actually right-justified in that space.
2542 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
2543 CGM.getContext().getPreferredTypeAlignInChars(elementType));
2544}
2545
2546Address ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
2547 Address NewPtr,
2548 llvm::Value *NumElements,
2549 const CXXNewExpr *expr,
2550 QualType ElementType) {
2551 assert(requiresArrayCookie(expr));
2552
2553 unsigned AS = NewPtr.getAddressSpace();
2554
2555 ASTContext &Ctx = getContext();
2556 CharUnits SizeSize = CGF.getSizeSize();
2557
2558 // The size of the cookie.
2559 CharUnits CookieSize =
2560 std::max(SizeSize, Ctx.getPreferredTypeAlignInChars(ElementType));
2561 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
2562
2563 // Compute an offset to the cookie.
2564 Address CookiePtr = NewPtr;
2565 CharUnits CookieOffset = CookieSize - SizeSize;
2566 if (!CookieOffset.isZero())
2567 CookiePtr = CGF.Builder.CreateConstInBoundsByteGEP(CookiePtr, CookieOffset);
2568
2569 // Write the number of elements into the appropriate slot.
2570 Address NumElementsPtr = CookiePtr.withElementType(CGF.SizeTy);
2571 llvm::Instruction *SI = CGF.Builder.CreateStore(NumElements, NumElementsPtr);
2572
2573 // Handle the array cookie specially in ASan.
2574 if (CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) && AS == 0 &&
2575 (expr->getOperatorNew()->isReplaceableGlobalAllocationFunction() ||
2576 CGM.getCodeGenOpts().SanitizeAddressPoisonCustomArrayCookie)) {
2577 // The store to the CookiePtr does not need to be instrumented.
2578 SI->setNoSanitizeMetadata();
2579 llvm::FunctionType *FTy =
2580 llvm::FunctionType::get(CGM.VoidTy, NumElementsPtr.getType(), false);
2581 llvm::FunctionCallee F =
2582 CGM.CreateRuntimeFunction(FTy, "__asan_poison_cxx_array_cookie");
2583 CGF.Builder.CreateCall(F, NumElementsPtr.emitRawPointer(CGF));
2584 }
2585
2586 // Finally, compute a pointer to the actual data buffer by skipping
2587 // over the cookie completely.
2588 return CGF.Builder.CreateConstInBoundsByteGEP(NewPtr, CookieSize);
2589}
2590
2591llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
2592 Address allocPtr,
2593 CharUnits cookieSize) {
2594 // The element size is right-justified in the cookie.
2595 Address numElementsPtr = allocPtr;
2596 CharUnits numElementsOffset = cookieSize - CGF.getSizeSize();
2597 if (!numElementsOffset.isZero())
2598 numElementsPtr =
2599 CGF.Builder.CreateConstInBoundsByteGEP(numElementsPtr, numElementsOffset);
2600
2601 unsigned AS = allocPtr.getAddressSpace();
2602 numElementsPtr = numElementsPtr.withElementType(CGF.SizeTy);
2603 if (!CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) || AS != 0)
2604 return CGF.Builder.CreateLoad(numElementsPtr);
2605 // In asan mode emit a function call instead of a regular load and let the
2606 // run-time deal with it: if the shadow is properly poisoned return the
2607 // cookie, otherwise return 0 to avoid an infinite loop calling DTORs.
2608 // We can't simply ignore this load using nosanitize metadata because
2609 // the metadata may be lost.
2610 llvm::FunctionType *FTy =
2611 llvm::FunctionType::get(CGF.SizeTy, CGF.DefaultPtrTy, false);
2612 llvm::FunctionCallee F =
2613 CGM.CreateRuntimeFunction(FTy, "__asan_load_cxx_array_cookie");
2614 return CGF.Builder.CreateCall(F, numElementsPtr.emitRawPointer(CGF));
2615}
2616
2617CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
2618 // ARM says that the cookie is always:
2619 // struct array_cookie {
2620 // std::size_t element_size; // element_size != 0
2621 // std::size_t element_count;
2622 // };
2623 // But the base ABI doesn't give anything an alignment greater than
2624 // 8, so we can dismiss this as typical ABI-author blindness to
2625 // actual language complexity and round up to the element alignment.
2626 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
2627 CGM.getContext().getTypeAlignInChars(elementType));
2628}
2629
2630Address ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
2631 Address newPtr,
2632 llvm::Value *numElements,
2633 const CXXNewExpr *expr,
2634 QualType elementType) {
2635 assert(requiresArrayCookie(expr));
2636
2637 // The cookie is always at the start of the buffer.
2638 Address cookie = newPtr;
2639
2640 // The first element is the element size.
2641 cookie = cookie.withElementType(CGF.SizeTy);
2642 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
2643 getContext().getTypeSizeInChars(elementType).getQuantity());
2644 CGF.Builder.CreateStore(elementSize, cookie);
2645
2646 // The second element is the element count.
2647 cookie = CGF.Builder.CreateConstInBoundsGEP(cookie, 1);
2648 CGF.Builder.CreateStore(numElements, cookie);
2649
2650 // Finally, compute a pointer to the actual data buffer by skipping
2651 // over the cookie completely.
2652 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
2653 return CGF.Builder.CreateConstInBoundsByteGEP(newPtr, cookieSize);
2654}
2655
2656llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
2657 Address allocPtr,
2658 CharUnits cookieSize) {
2659 // The number of elements is at offset sizeof(size_t) relative to
2660 // the allocated pointer.
2661 Address numElementsPtr
2662 = CGF.Builder.CreateConstInBoundsByteGEP(allocPtr, CGF.getSizeSize());
2663
2664 numElementsPtr = numElementsPtr.withElementType(CGF.SizeTy);
2665 return CGF.Builder.CreateLoad(numElementsPtr);
2666}
2667
2668/*********************** Static local initialization **************************/
2669
2670static llvm::FunctionCallee getGuardAcquireFn(CodeGenModule &CGM,
2671 llvm::PointerType *GuardPtrTy) {
2672 // int __cxa_guard_acquire(__guard *guard_object);
2673 llvm::FunctionType *FTy =
2674 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
2675 GuardPtrTy, /*isVarArg=*/false);
2676 return CGM.CreateRuntimeFunction(
2677 FTy, "__cxa_guard_acquire",
2678 llvm::AttributeList::get(CGM.getLLVMContext(),
2679 llvm::AttributeList::FunctionIndex,
2680 llvm::Attribute::NoUnwind));
2681}
2682
2683static llvm::FunctionCallee getGuardReleaseFn(CodeGenModule &CGM,
2684 llvm::PointerType *GuardPtrTy) {
2685 // void __cxa_guard_release(__guard *guard_object);
2686 llvm::FunctionType *FTy =
2687 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
2688 return CGM.CreateRuntimeFunction(
2689 FTy, "__cxa_guard_release",
2690 llvm::AttributeList::get(CGM.getLLVMContext(),
2691 llvm::AttributeList::FunctionIndex,
2692 llvm::Attribute::NoUnwind));
2693}
2694
2695static llvm::FunctionCallee getGuardAbortFn(CodeGenModule &CGM,
2696 llvm::PointerType *GuardPtrTy) {
2697 // void __cxa_guard_abort(__guard *guard_object);
2698 llvm::FunctionType *FTy =
2699 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
2700 return CGM.CreateRuntimeFunction(
2701 FTy, "__cxa_guard_abort",
2702 llvm::AttributeList::get(CGM.getLLVMContext(),
2703 llvm::AttributeList::FunctionIndex,
2704 llvm::Attribute::NoUnwind));
2705}
2706
2707namespace {
2708 struct CallGuardAbort final : EHScopeStack::Cleanup {
2709 llvm::GlobalVariable *Guard;
2710 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
2711
2712 void Emit(CodeGenFunction &CGF, Flags flags) override {
2713 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
2714 Guard);
2715 }
2716 };
2717}
2718
2719/// The ARM code here follows the Itanium code closely enough that we
2720/// just special-case it at particular places.
2721void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
2722 const VarDecl &D,
2723 llvm::GlobalVariable *var,
2724 bool shouldPerformInit) {
2725 CGBuilderTy &Builder = CGF.Builder;
2726
2727 // Inline variables that weren't instantiated from variable templates have
2728 // partially-ordered initialization within their translation unit.
2729 bool NonTemplateInline =
2730 D.isInline() &&
2732
2733 // We only need to use thread-safe statics for local non-TLS variables and
2734 // inline variables; other global initialization is always single-threaded
2735 // or (through lazy dynamic loading in multiple threads) unsequenced.
2736 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
2737 (D.isLocalVarDecl() || NonTemplateInline) &&
2738 !D.getTLSKind();
2739
2740 // If we have a global variable with internal linkage and thread-safe statics
2741 // are disabled, we can just let the guard variable be of type i8.
2742 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
2743
2744 llvm::IntegerType *guardTy;
2745 CharUnits guardAlignment;
2746 if (useInt8GuardVariable) {
2747 guardTy = CGF.Int8Ty;
2748 guardAlignment = CharUnits::One();
2749 } else {
2750 // Guard variables are 64 bits in the generic ABI and size width on ARM
2751 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
2752 if (UseARMGuardVarABI) {
2753 guardTy = CGF.SizeTy;
2754 guardAlignment = CGF.getSizeAlign();
2755 } else {
2756 guardTy = CGF.Int64Ty;
2757 guardAlignment =
2758 CharUnits::fromQuantity(CGM.getDataLayout().getABITypeAlign(guardTy));
2759 }
2760 }
2761 llvm::PointerType *guardPtrTy = llvm::PointerType::get(
2762 CGF.CGM.getLLVMContext(),
2763 CGF.CGM.getDataLayout().getDefaultGlobalsAddressSpace());
2764
2765 // Create the guard variable if we don't already have it (as we
2766 // might if we're double-emitting this function body).
2767 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
2768 if (!guard) {
2769 // Mangle the name for the guard.
2770 SmallString<256> guardName;
2771 {
2772 llvm::raw_svector_ostream out(guardName);
2773 getMangleContext().mangleStaticGuardVariable(&D, out);
2774 }
2775
2776 // Create the guard variable with a zero-initializer.
2777 // Just absorb linkage, visibility and dll storage class from the guarded
2778 // variable.
2779 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
2780 false, var->getLinkage(),
2781 llvm::ConstantInt::get(guardTy, 0),
2782 guardName.str());
2783 guard->setDSOLocal(var->isDSOLocal());
2784 guard->setVisibility(var->getVisibility());
2785 guard->setDLLStorageClass(var->getDLLStorageClass());
2786 // If the variable is thread-local, so is its guard variable.
2787 guard->setThreadLocalMode(var->getThreadLocalMode());
2788 guard->setAlignment(guardAlignment.getAsAlign());
2789
2790 // The ABI says: "It is suggested that it be emitted in the same COMDAT
2791 // group as the associated data object." In practice, this doesn't work for
2792 // non-ELF and non-Wasm object formats, so only do it for ELF and Wasm.
2793 llvm::Comdat *C = var->getComdat();
2794 if (!D.isLocalVarDecl() && C &&
2795 (CGM.getTarget().getTriple().isOSBinFormatELF() ||
2796 CGM.getTarget().getTriple().isOSBinFormatWasm())) {
2797 guard->setComdat(C);
2798 } else if (CGM.supportsCOMDAT() && guard->isWeakForLinker()) {
2799 guard->setComdat(CGM.getModule().getOrInsertComdat(guard->getName()));
2800 }
2801
2802 CGM.setStaticLocalDeclGuardAddress(&D, guard);
2803 }
2804
2805 Address guardAddr = Address(guard, guard->getValueType(), guardAlignment);
2806
2807 // Test whether the variable has completed initialization.
2808 //
2809 // Itanium C++ ABI 3.3.2:
2810 // The following is pseudo-code showing how these functions can be used:
2811 // if (obj_guard.first_byte == 0) {
2812 // if ( __cxa_guard_acquire (&obj_guard) ) {
2813 // try {
2814 // ... initialize the object ...;
2815 // } catch (...) {
2816 // __cxa_guard_abort (&obj_guard);
2817 // throw;
2818 // }
2819 // ... queue object destructor with __cxa_atexit() ...;
2820 // __cxa_guard_release (&obj_guard);
2821 // }
2822 // }
2823 //
2824 // If threadsafe statics are enabled, but we don't have inline atomics, just
2825 // call __cxa_guard_acquire unconditionally. The "inline" check isn't
2826 // actually inline, and the user might not expect calls to __atomic libcalls.
2827
2828 unsigned MaxInlineWidthInBits = CGF.getTarget().getMaxAtomicInlineWidth();
2829 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2830 if (!threadsafe || MaxInlineWidthInBits) {
2831 // Load the first byte of the guard variable.
2832 llvm::LoadInst *LI =
2833 Builder.CreateLoad(guardAddr.withElementType(CGM.Int8Ty));
2834
2835 // Itanium ABI:
2836 // An implementation supporting thread-safety on multiprocessor
2837 // systems must also guarantee that references to the initialized
2838 // object do not occur before the load of the initialization flag.
2839 //
2840 // In LLVM, we do this by marking the load Acquire.
2841 if (threadsafe)
2842 LI->setAtomic(llvm::AtomicOrdering::Acquire);
2843
2844 // For ARM, we should only check the first bit, rather than the entire byte:
2845 //
2846 // ARM C++ ABI 3.2.3.1:
2847 // To support the potential use of initialization guard variables
2848 // as semaphores that are the target of ARM SWP and LDREX/STREX
2849 // synchronizing instructions we define a static initialization
2850 // guard variable to be a 4-byte aligned, 4-byte word with the
2851 // following inline access protocol.
2852 // #define INITIALIZED 1
2853 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
2854 // if (__cxa_guard_acquire(&obj_guard))
2855 // ...
2856 // }
2857 //
2858 // and similarly for ARM64:
2859 //
2860 // ARM64 C++ ABI 3.2.2:
2861 // This ABI instead only specifies the value bit 0 of the static guard
2862 // variable; all other bits are platform defined. Bit 0 shall be 0 when the
2863 // variable is not initialized and 1 when it is.
2864 llvm::Value *V =
2865 (UseARMGuardVarABI && !useInt8GuardVariable)
2866 ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1))
2867 : LI;
2868 llvm::Value *NeedsInit = Builder.CreateIsNull(V, "guard.uninitialized");
2869
2870 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
2871
2872 // Check if the first byte of the guard variable is zero.
2873 CGF.EmitCXXGuardedInitBranch(NeedsInit, InitCheckBlock, EndBlock,
2874 CodeGenFunction::GuardKind::VariableGuard, &D);
2875
2876 CGF.EmitBlock(InitCheckBlock);
2877 }
2878
2879 // The semantics of dynamic initialization of variables with static or thread
2880 // storage duration depends on whether they are declared at block-scope. The
2881 // initialization of such variables at block-scope can be aborted with an
2882 // exception and later retried (per C++20 [stmt.dcl]p4), and recursive entry
2883 // to their initialization has undefined behavior (also per C++20
2884 // [stmt.dcl]p4). For such variables declared at non-block scope, exceptions
2885 // lead to termination (per C++20 [except.terminate]p1), and recursive
2886 // references to the variables are governed only by the lifetime rules (per
2887 // C++20 [class.cdtor]p2), which means such references are perfectly fine as
2888 // long as they avoid touching memory. As a result, block-scope variables must
2889 // not be marked as initialized until after initialization completes (unless
2890 // the mark is reverted following an exception), but non-block-scope variables
2891 // must be marked prior to initialization so that recursive accesses during
2892 // initialization do not restart initialization.
2893
2894 // Variables used when coping with thread-safe statics and exceptions.
2895 if (threadsafe) {
2896 // Call __cxa_guard_acquire.
2897 llvm::Value *V
2898 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
2899
2900 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
2901
2902 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
2903 InitBlock, EndBlock);
2904
2905 // Call __cxa_guard_abort along the exceptional edge.
2906 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
2907
2908 CGF.EmitBlock(InitBlock);
2909 } else if (!D.isLocalVarDecl()) {
2910 // For non-local variables, store 1 into the first byte of the guard
2911 // variable before the object initialization begins so that references
2912 // to the variable during initialization don't restart initialization.
2913 Builder.CreateStore(llvm::ConstantInt::get(CGM.Int8Ty, 1),
2914 guardAddr.withElementType(CGM.Int8Ty));
2915 }
2916
2917 // Emit the initializer and add a global destructor if appropriate.
2918 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
2919
2920 if (threadsafe) {
2921 // Pop the guard-abort cleanup if we pushed one.
2922 CGF.PopCleanupBlock();
2923
2924 // Call __cxa_guard_release. This cannot throw.
2925 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy),
2926 guardAddr.emitRawPointer(CGF));
2927 } else if (D.isLocalVarDecl()) {
2928 // For local variables, store 1 into the first byte of the guard variable
2929 // after the object initialization completes so that initialization is
2930 // retried if initialization is interrupted by an exception.
2931 Builder.CreateStore(llvm::ConstantInt::get(CGM.Int8Ty, 1),
2932 guardAddr.withElementType(CGM.Int8Ty));
2933 }
2934
2935 CGF.EmitBlock(EndBlock);
2936}
2937
2938/// Register a global destructor using __cxa_atexit.
2940 llvm::FunctionCallee dtor,
2941 llvm::Constant *addr, bool TLS) {
2942 assert(!CGF.getTarget().getTriple().isOSAIX() &&
2943 "unexpected call to emitGlobalDtorWithCXAAtExit");
2944 assert((TLS || CGF.getTypes().getCodeGenOpts().CXAAtExit) &&
2945 "__cxa_atexit is disabled");
2946 const char *Name = "__cxa_atexit";
2947 if (TLS) {
2948 const llvm::Triple &T = CGF.getTarget().getTriple();
2949 Name = T.isOSDarwin() ? "_tlv_atexit" : "__cxa_thread_atexit";
2950 }
2951
2952 // We're assuming that the destructor function is something we can
2953 // reasonably call with the default CC.
2954 llvm::Type *dtorTy = CGF.DefaultPtrTy;
2955
2956 // Preserve address space of addr.
2957 auto AddrAS = addr ? addr->getType()->getPointerAddressSpace() : 0;
2958 auto AddrPtrTy = AddrAS ? llvm::PointerType::get(CGF.getLLVMContext(), AddrAS)
2959 : CGF.Int8PtrTy;
2960
2961 // Create a variable that binds the atexit to this shared object.
2962 llvm::Constant *handle =
2963 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
2964 auto *GV = cast<llvm::GlobalValue>(handle->stripPointerCasts());
2965 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
2966
2967 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
2968 llvm::Type *paramTys[] = {dtorTy, AddrPtrTy, handle->getType()};
2969 llvm::FunctionType *atexitTy =
2970 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
2971
2972 // Fetch the actual function.
2973 llvm::FunctionCallee atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
2974 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit.getCallee()))
2975 fn->setDoesNotThrow();
2976
2977 const auto &Context = CGF.CGM.getContext();
2978 FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention(
2979 /*IsVariadic=*/false, /*IsCXXMethod=*/false));
2980 QualType fnType =
2981 Context.getFunctionType(Context.VoidTy, {Context.VoidPtrTy}, EPI);
2982 llvm::Constant *dtorCallee = cast<llvm::Constant>(dtor.getCallee());
2983 dtorCallee = CGF.CGM.getFunctionPointer(dtorCallee, fnType);
2984
2985 if (!addr)
2986 // addr is null when we are trying to register a dtor annotated with
2987 // __attribute__((destructor)) in a constructor function. Using null here is
2988 // okay because this argument is just passed back to the destructor
2989 // function.
2990 addr = llvm::Constant::getNullValue(CGF.Int8PtrTy);
2991
2992 llvm::Value *args[] = {dtorCallee, addr, handle};
2993 CGF.EmitNounwindRuntimeCall(atexit, args);
2994}
2995
2997 StringRef FnName) {
2998 // Create a function that registers/unregisters destructors that have the same
2999 // priority.
3000 llvm::FunctionType *FTy = llvm::FunctionType::get(CGM.VoidTy, false);
3001 llvm::Function *GlobalInitOrCleanupFn = CGM.CreateGlobalInitOrCleanUpFunction(
3002 FTy, FnName, CGM.getTypes().arrangeNullaryFunction(), SourceLocation());
3003
3004 return GlobalInitOrCleanupFn;
3005}
3006
3007void CodeGenModule::unregisterGlobalDtorsWithUnAtExit() {
3008 for (const auto &I : DtorsUsingAtExit) {
3009 int Priority = I.first;
3010 std::string GlobalCleanupFnName =
3011 std::string("__GLOBAL_cleanup_") + llvm::to_string(Priority);
3012
3013 llvm::Function *GlobalCleanupFn =
3014 createGlobalInitOrCleanupFn(*this, GlobalCleanupFnName);
3015
3016 CodeGenFunction CGF(*this);
3017 CGF.StartFunction(GlobalDecl(), getContext().VoidTy, GlobalCleanupFn,
3018 getTypes().arrangeNullaryFunction(), FunctionArgList(),
3019 SourceLocation(), SourceLocation());
3021
3022 // Get the destructor function type, void(*)(void).
3023 llvm::FunctionType *dtorFuncTy = llvm::FunctionType::get(CGF.VoidTy, false);
3024
3025 // Destructor functions are run/unregistered in non-ascending
3026 // order of their priorities.
3027 const llvm::TinyPtrVector<llvm::Function *> &Dtors = I.second;
3028 auto itv = Dtors.rbegin();
3029 while (itv != Dtors.rend()) {
3030 llvm::Function *Dtor = *itv;
3031
3032 // We're assuming that the destructor function is something we can
3033 // reasonably call with the correct CC.
3034 llvm::Value *V = CGF.unregisterGlobalDtorWithUnAtExit(Dtor);
3035 llvm::Value *NeedsDestruct =
3036 CGF.Builder.CreateIsNull(V, "needs_destruct");
3037
3038 llvm::BasicBlock *DestructCallBlock =
3039 CGF.createBasicBlock("destruct.call");
3040 llvm::BasicBlock *EndBlock = CGF.createBasicBlock(
3041 (itv + 1) != Dtors.rend() ? "unatexit.call" : "destruct.end");
3042 // Check if unatexit returns a value of 0. If it does, jump to
3043 // DestructCallBlock, otherwise jump to EndBlock directly.
3044 CGF.Builder.CreateCondBr(NeedsDestruct, DestructCallBlock, EndBlock);
3045
3046 CGF.EmitBlock(DestructCallBlock);
3047
3048 // Emit the call to casted Dtor.
3049 llvm::CallInst *CI = CGF.Builder.CreateCall(dtorFuncTy, Dtor);
3050 // Make sure the call and the callee agree on calling convention.
3051 CI->setCallingConv(Dtor->getCallingConv());
3052
3053 CGF.EmitBlock(EndBlock);
3054
3055 itv++;
3056 }
3057
3058 CGF.FinishFunction();
3059 AddGlobalDtor(GlobalCleanupFn, Priority);
3060 }
3061}
3062
3063void CodeGenModule::registerGlobalDtorsWithAtExit() {
3064 for (const auto &I : DtorsUsingAtExit) {
3065 int Priority = I.first;
3066 std::string GlobalInitFnName =
3067 std::string("__GLOBAL_init_") + llvm::to_string(Priority);
3068 llvm::Function *GlobalInitFn =
3069 createGlobalInitOrCleanupFn(*this, GlobalInitFnName);
3070
3071 CodeGenFunction CGF(*this);
3072 CGF.StartFunction(GlobalDecl(), getContext().VoidTy, GlobalInitFn,
3073 getTypes().arrangeNullaryFunction(), FunctionArgList(),
3074 SourceLocation(), SourceLocation());
3076
3077 // Since constructor functions are run in non-descending order of their
3078 // priorities, destructors are registered in non-descending order of their
3079 // priorities, and since destructor functions are run in the reverse order
3080 // of their registration, destructor functions are run in non-ascending
3081 // order of their priorities.
3082 const llvm::TinyPtrVector<llvm::Function *> &Dtors = I.second;
3083 for (auto *Dtor : Dtors) {
3084 // Register the destructor function calling __cxa_atexit if it is
3085 // available. Otherwise fall back on calling atexit.
3086 if (getCodeGenOpts().CXAAtExit) {
3087 emitGlobalDtorWithCXAAtExit(CGF, Dtor, nullptr, false);
3088 } else {
3089 // We're assuming that the destructor function is something we can
3090 // reasonably call with the correct CC.
3092 }
3093 }
3094
3095 CGF.FinishFunction();
3096 AddGlobalCtor(GlobalInitFn, Priority);
3097 }
3098
3099 if (getCXXABI().useSinitAndSterm())
3100 unregisterGlobalDtorsWithUnAtExit();
3101}
3102
3103/// Register a global destructor as best as we know how.
3104void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
3105 llvm::FunctionCallee dtor,
3106 llvm::Constant *addr) {
3107 if (D.isNoDestroy(CGM.getContext()))
3108 return;
3109
3110 // HLSL doesn't support atexit.
3111 if (CGM.getLangOpts().HLSL)
3112 return CGM.AddCXXDtorEntry(dtor, addr);
3113
3114 // OpenMP offloading supports C++ constructors and destructors but we do not
3115 // always have 'atexit' available. Instead lower these to use the LLVM global
3116 // destructors which we can handle directly in the runtime. Note that this is
3117 // not strictly 1-to-1 with using `atexit` because we no longer tear down
3118 // globals in reverse order of when they were constructed.
3119 if (!CGM.getLangOpts().hasAtExit() && !D.isStaticLocal())
3120 return CGF.registerGlobalDtorWithLLVM(D, dtor, addr);
3121
3122 // emitGlobalDtorWithCXAAtExit will emit a call to either __cxa_thread_atexit
3123 // or __cxa_atexit depending on whether this VarDecl is a thread-local storage
3124 // or not. CXAAtExit controls only __cxa_atexit, so use it if it is enabled.
3125 // We can always use __cxa_thread_atexit.
3126 if (CGM.getCodeGenOpts().CXAAtExit || D.getTLSKind())
3127 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
3128
3129 // In Apple kexts, we want to add a global destructor entry.
3130 // FIXME: shouldn't this be guarded by some variable?
3131 if (CGM.getLangOpts().AppleKext) {
3132 // Generate a global destructor entry.
3133 return CGM.AddCXXDtorEntry(dtor, addr);
3134 }
3135
3136 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
3137}
3138
3141 assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!");
3142 // Darwin prefers to have references to thread local variables to go through
3143 // the thread wrapper instead of directly referencing the backing variable.
3144 return VD->getTLSKind() == VarDecl::TLS_Dynamic &&
3145 CGM.getTarget().getTriple().isOSDarwin();
3146}
3147
3148/// Get the appropriate linkage for the wrapper function. This is essentially
3149/// the weak form of the variable's linkage; every translation unit which needs
3150/// the wrapper emits a copy, and we want the linker to merge them.
3151static llvm::GlobalValue::LinkageTypes
3153 llvm::GlobalValue::LinkageTypes VarLinkage =
3155
3156 // For internal linkage variables, we don't need an external or weak wrapper.
3157 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
3158 return VarLinkage;
3159
3160 // If the thread wrapper is replaceable, give it appropriate linkage.
3161 if (isThreadWrapperReplaceable(VD, CGM))
3162 if (!llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) &&
3163 !llvm::GlobalVariable::isWeakODRLinkage(VarLinkage))
3164 return VarLinkage;
3165 return llvm::GlobalValue::WeakODRLinkage;
3166}
3167
3168llvm::Function *
3169ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
3170 llvm::Value *Val) {
3171 // Mangle the name for the thread_local wrapper function.
3172 SmallString<256> WrapperName;
3173 {
3174 llvm::raw_svector_ostream Out(WrapperName);
3175 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
3176 }
3177
3178 // FIXME: If VD is a definition, we should regenerate the function attributes
3179 // before returning.
3180 if (llvm::Value *V = CGM.getModule().getNamedValue(WrapperName))
3181 return cast<llvm::Function>(V);
3182
3183 QualType RetQT = VD->getType();
3184 if (RetQT->isReferenceType())
3185 RetQT = RetQT.getNonReferenceType();
3186
3187 const CGFunctionInfo &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
3188 getContext().getPointerType(RetQT), FunctionArgList());
3189
3190 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FI);
3191 llvm::Function *Wrapper =
3192 llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM),
3193 WrapperName.str(), &CGM.getModule());
3194
3195 if (CGM.supportsCOMDAT() && Wrapper->isWeakForLinker())
3196 Wrapper->setComdat(CGM.getModule().getOrInsertComdat(Wrapper->getName()));
3197
3198 CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, Wrapper, /*IsThunk=*/false);
3199
3200 // Always resolve references to the wrapper at link time.
3201 if (!Wrapper->hasLocalLinkage())
3202 if (!isThreadWrapperReplaceable(VD, CGM) ||
3203 llvm::GlobalVariable::isLinkOnceLinkage(Wrapper->getLinkage()) ||
3204 llvm::GlobalVariable::isWeakODRLinkage(Wrapper->getLinkage()) ||
3206 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
3207
3208 if (isThreadWrapperReplaceable(VD, CGM)) {
3209 Wrapper->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
3210 Wrapper->addFnAttr(llvm::Attribute::NoUnwind);
3211 }
3212
3213 ThreadWrappers.push_back({VD, Wrapper});
3214 return Wrapper;
3215}
3216
3217void ItaniumCXXABI::EmitThreadLocalInitFuncs(
3218 CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
3219 ArrayRef<llvm::Function *> CXXThreadLocalInits,
3220 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) {
3221 llvm::Function *InitFunc = nullptr;
3222
3223 // Separate initializers into those with ordered (or partially-ordered)
3224 // initialization and those with unordered initialization.
3225 llvm::SmallVector<llvm::Function *, 8> OrderedInits;
3226 llvm::SmallDenseMap<const VarDecl *, llvm::Function *> UnorderedInits;
3227 for (unsigned I = 0; I != CXXThreadLocalInits.size(); ++I) {
3229 CXXThreadLocalInitVars[I]->getTemplateSpecializationKind()))
3230 UnorderedInits[CXXThreadLocalInitVars[I]->getCanonicalDecl()] =
3231 CXXThreadLocalInits[I];
3232 else
3233 OrderedInits.push_back(CXXThreadLocalInits[I]);
3234 }
3235
3236 if (!OrderedInits.empty()) {
3237 // Generate a guarded initialization function.
3238 llvm::FunctionType *FTy =
3239 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
3240 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
3241 InitFunc = CGM.CreateGlobalInitOrCleanUpFunction(FTy, "__tls_init", FI,
3242 SourceLocation(),
3243 /*TLS=*/true);
3244 llvm::GlobalVariable *Guard = new llvm::GlobalVariable(
3245 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
3246 llvm::GlobalVariable::InternalLinkage,
3247 llvm::ConstantInt::get(CGM.Int8Ty, 0), "__tls_guard");
3248 Guard->setThreadLocal(true);
3249 Guard->setThreadLocalMode(CGM.GetDefaultLLVMTLSModel());
3250
3251 CharUnits GuardAlign = CharUnits::One();
3252 Guard->setAlignment(GuardAlign.getAsAlign());
3253
3254 CodeGenFunction(CGM).GenerateCXXGlobalInitFunc(
3255 InitFunc, OrderedInits, ConstantAddress(Guard, CGM.Int8Ty, GuardAlign));
3256 // On Darwin platforms, use CXX_FAST_TLS calling convention.
3257 if (CGM.getTarget().getTriple().isOSDarwin()) {
3258 InitFunc->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
3259 InitFunc->addFnAttr(llvm::Attribute::NoUnwind);
3260 }
3261 }
3262
3263 // Create declarations for thread wrappers for all thread-local variables
3264 // with non-discardable definitions in this translation unit.
3265 for (const VarDecl *VD : CXXThreadLocals) {
3266 if (VD->hasDefinition() &&
3267 !isDiscardableGVALinkage(getContext().GetGVALinkageForVariable(VD))) {
3268 llvm::GlobalValue *GV = CGM.GetGlobalValue(CGM.getMangledName(VD));
3269 getOrCreateThreadLocalWrapper(VD, GV);
3270 }
3271 }
3272
3273 // Emit all referenced thread wrappers.
3274 for (auto VDAndWrapper : ThreadWrappers) {
3275 const VarDecl *VD = VDAndWrapper.first;
3276 llvm::GlobalVariable *Var =
3278 llvm::Function *Wrapper = VDAndWrapper.second;
3279
3280 // Some targets require that all access to thread local variables go through
3281 // the thread wrapper. This means that we cannot attempt to create a thread
3282 // wrapper or a thread helper.
3283 if (!VD->hasDefinition()) {
3284 if (isThreadWrapperReplaceable(VD, CGM)) {
3285 Wrapper->setLinkage(llvm::Function::ExternalLinkage);
3286 continue;
3287 }
3288
3289 // If this isn't a TU in which this variable is defined, the thread
3290 // wrapper is discardable.
3291 if (Wrapper->getLinkage() == llvm::Function::WeakODRLinkage)
3292 Wrapper->setLinkage(llvm::Function::LinkOnceODRLinkage);
3293 }
3294
3295 CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Wrapper);
3296
3297 // Mangle the name for the thread_local initialization function.
3298 SmallString<256> InitFnName;
3299 {
3300 llvm::raw_svector_ostream Out(InitFnName);
3301 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
3302 }
3303
3304 llvm::FunctionType *InitFnTy = llvm::FunctionType::get(CGM.VoidTy, false);
3305
3306 // If we have a definition for the variable, emit the initialization
3307 // function as an alias to the global Init function (if any). Otherwise,
3308 // produce a declaration of the initialization function.
3309 llvm::GlobalValue *Init = nullptr;
3310 bool InitIsInitFunc = false;
3311 bool HasConstantInitialization = false;
3312 if (!usesThreadWrapperFunction(VD)) {
3313 HasConstantInitialization = true;
3314 } else if (VD->hasDefinition()) {
3315 InitIsInitFunc = true;
3316 llvm::Function *InitFuncToUse = InitFunc;
3318 InitFuncToUse = UnorderedInits.lookup(VD->getCanonicalDecl());
3319 if (InitFuncToUse)
3320 Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
3321 InitFuncToUse);
3322 } else {
3323 // Emit a weak global function referring to the initialization function.
3324 // This function will not exist if the TU defining the thread_local
3325 // variable in question does not need any dynamic initialization for
3326 // its thread_local variables.
3327 Init = llvm::Function::Create(InitFnTy,
3328 llvm::GlobalVariable::ExternalWeakLinkage,
3329 InitFnName.str(), &CGM.getModule());
3330 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
3332 GlobalDecl(), FI, cast<llvm::Function>(Init), /*IsThunk=*/false);
3333 }
3334
3335 if (Init) {
3336 Init->setVisibility(Var->getVisibility());
3337 // Don't mark an extern_weak function DSO local on windows.
3338 if (!CGM.getTriple().isOSWindows() || !Init->hasExternalWeakLinkage())
3339 Init->setDSOLocal(Var->isDSOLocal());
3340 }
3341
3342 llvm::LLVMContext &Context = CGM.getModule().getContext();
3343
3344 // The linker on AIX is not happy with missing weak symbols. However,
3345 // other TUs will not know whether the initialization routine exists
3346 // so create an empty, init function to satisfy the linker.
3347 // This is needed whenever a thread wrapper function is not used, and
3348 // also when the symbol is weak.
3349 if (CGM.getTriple().isOSAIX() && VD->hasDefinition() &&
3350 isEmittedWithConstantInitializer(VD, true) &&
3351 !mayNeedDestruction(VD)) {
3352 // Init should be null. If it were non-null, then the logic above would
3353 // either be defining the function to be an alias or declaring the
3354 // function with the expectation that the definition of the variable
3355 // is elsewhere.
3356 assert(Init == nullptr && "Expected Init to be null.");
3357
3358 llvm::Function *Func = llvm::Function::Create(
3359 InitFnTy, Var->getLinkage(), InitFnName.str(), &CGM.getModule());
3360 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
3361 CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI,
3363 /*IsThunk=*/false);
3364 // Create a function body that just returns
3365 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Func);
3366 CGBuilderTy Builder(CGM, Entry);
3367 Builder.CreateRetVoid();
3368 }
3369
3370 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
3371 CGBuilderTy Builder(CGM, Entry);
3372 if (HasConstantInitialization) {
3373 // No dynamic initialization to invoke.
3374 } else if (InitIsInitFunc) {
3375 if (Init) {
3376 llvm::CallInst *CallVal = Builder.CreateCall(InitFnTy, Init);
3377 if (isThreadWrapperReplaceable(VD, CGM)) {
3378 CallVal->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
3379 llvm::Function *Fn =
3381 Fn->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
3382 }
3383 }
3384 } else if (CGM.getTriple().isOSAIX()) {
3385 // On AIX, except if constinit and also neither of class type or of
3386 // (possibly multi-dimensional) array of class type, thread_local vars
3387 // will have init routines regardless of whether they are
3388 // const-initialized. Since the routine is guaranteed to exist, we can
3389 // unconditionally call it without testing for its existance. This
3390 // avoids potentially unresolved weak symbols which the AIX linker
3391 // isn't happy with.
3392 Builder.CreateCall(InitFnTy, Init);
3393 } else {
3394 // Don't know whether we have an init function. Call it if it exists.
3395 llvm::Value *Have = Builder.CreateIsNotNull(Init);
3396 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
3397 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
3398 Builder.CreateCondBr(Have, InitBB, ExitBB);
3399
3400 Builder.SetInsertPoint(InitBB);
3401 Builder.CreateCall(InitFnTy, Init);
3402 Builder.CreateBr(ExitBB);
3403
3404 Builder.SetInsertPoint(ExitBB);
3405 }
3406
3407 // For a reference, the result of the wrapper function is a pointer to
3408 // the referenced object.
3409 llvm::Value *Val = Builder.CreateThreadLocalAddress(Var);
3410
3411 if (VD->getType()->isReferenceType()) {
3412 CharUnits Align = CGM.getContext().getDeclAlign(VD);
3413 Val = Builder.CreateAlignedLoad(Var->getValueType(), Val, Align);
3414 }
3415 Val = Builder.CreateAddrSpaceCast(Val, Wrapper->getReturnType());
3416
3417 Builder.CreateRet(Val);
3418 }
3419}
3420
3421LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
3422 const VarDecl *VD,
3423 QualType LValType) {
3424 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD);
3425 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Val);
3426
3427 llvm::CallInst *CallVal = CGF.Builder.CreateCall(Wrapper);
3428 CallVal->setCallingConv(Wrapper->getCallingConv());
3429
3430 LValue LV;
3431 if (VD->getType()->isReferenceType())
3432 LV = CGF.MakeNaturalAlignRawAddrLValue(CallVal, LValType);
3433 else
3434 LV = CGF.MakeRawAddrLValue(CallVal, LValType,
3435 CGF.getContext().getDeclAlign(VD));
3436 // FIXME: need setObjCGCLValueClass?
3437 return LV;
3438}
3439
3440/// Return whether the given global decl needs a VTT parameter, which it does
3441/// if it's a base constructor or destructor with virtual bases.
3442bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
3443 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
3444
3445 // We don't have any virtual bases, just return early.
3446 if (!MD->getParent()->getNumVBases())
3447 return false;
3448
3449 // Check if we have a base constructor.
3451 return true;
3452
3453 // Check if we have a base destructor.
3454 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
3455 return true;
3456
3457 return false;
3458}
3459
3460llvm::Constant *
3461ItaniumCXXABI::getOrCreateVirtualFunctionPointerThunk(const CXXMethodDecl *MD) {
3462 SmallString<256> MethodName;
3463 llvm::raw_svector_ostream Out(MethodName);
3464 getMangleContext().mangleCXXName(MD, Out);
3465 MethodName += "_vfpthunk_";
3466 StringRef ThunkName = MethodName.str();
3467 llvm::Function *ThunkFn;
3468 if ((ThunkFn = cast_or_null<llvm::Function>(
3469 CGM.getModule().getNamedValue(ThunkName))))
3470 return ThunkFn;
3471
3472 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeCXXMethodDeclaration(MD);
3473 llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo);
3474 llvm::GlobalValue::LinkageTypes Linkage =
3475 MD->isExternallyVisible() ? llvm::GlobalValue::LinkOnceODRLinkage
3476 : llvm::GlobalValue::InternalLinkage;
3477 ThunkFn =
3478 llvm::Function::Create(ThunkTy, Linkage, ThunkName, &CGM.getModule());
3479 if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
3480 ThunkFn->setVisibility(llvm::GlobalValue::HiddenVisibility);
3481 assert(ThunkFn->getName() == ThunkName && "name was uniqued!");
3482
3483 CGM.SetLLVMFunctionAttributes(MD, FnInfo, ThunkFn, /*IsThunk=*/true);
3485
3486 // Stack protection sometimes gets inserted after the musttail call.
3487 ThunkFn->removeFnAttr(llvm::Attribute::StackProtect);
3488 ThunkFn->removeFnAttr(llvm::Attribute::StackProtectStrong);
3489 ThunkFn->removeFnAttr(llvm::Attribute::StackProtectReq);
3490
3491 // Start codegen.
3492 CodeGenFunction CGF(CGM);
3493 CGF.CurGD = GlobalDecl(MD);
3494 CGF.CurFuncIsThunk = true;
3495
3496 // Build FunctionArgs.
3497 FunctionArgList FunctionArgs;
3498 CGF.BuildFunctionArgList(CGF.CurGD, FunctionArgs);
3499
3500 CGF.StartFunction(GlobalDecl(), FnInfo.getReturnType(), ThunkFn, FnInfo,
3501 FunctionArgs, MD->getLocation(), SourceLocation());
3502
3503 // Emit an artificial location for this function.
3505
3506 llvm::Value *ThisVal = loadIncomingCXXThis(CGF);
3507 setCXXABIThisValue(CGF, ThisVal);
3508
3509 CallArgList CallArgs;
3510 for (const VarDecl *VD : FunctionArgs)
3511 CGF.EmitDelegateCallArg(CallArgs, VD, SourceLocation());
3512
3513 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
3514 RequiredArgs Required = RequiredArgs::forPrototypePlus(FPT, /*this*/ 1);
3515 const CGFunctionInfo &CallInfo =
3516 CGM.getTypes().arrangeCXXMethodCall(CallArgs, FPT, Required, 0);
3517 CGCallee Callee = CGCallee::forVirtual(nullptr, GlobalDecl(MD),
3518 getThisAddress(CGF), ThunkTy);
3519 llvm::CallBase *CallOrInvoke;
3520 CGF.EmitCall(CallInfo, Callee, ReturnValueSlot(), CallArgs, &CallOrInvoke,
3521 /*IsMustTail=*/true, SourceLocation(), true);
3522 auto *Call = cast<llvm::CallInst>(CallOrInvoke);
3523 Call->setTailCallKind(llvm::CallInst::TCK_MustTail);
3524 if (Call->getType()->isVoidTy())
3525 CGF.Builder.CreateRetVoid();
3526 else
3527 CGF.Builder.CreateRet(Call);
3528
3529 // Finish the function to maintain CodeGenFunction invariants.
3530 // FIXME: Don't emit unreachable code.
3531 CGF.EmitBlock(CGF.createBasicBlock());
3532 CGF.FinishFunction();
3533 return ThunkFn;
3534}
3535
3536namespace {
3537class ItaniumRTTIBuilder {
3538 CodeGenModule &CGM; // Per-module state.
3539 llvm::LLVMContext &VMContext;
3540 const ItaniumCXXABI &CXXABI; // Per-module state.
3541
3542 /// Fields - The fields of the RTTI descriptor currently being built.
3543 SmallVector<llvm::Constant *, 16> Fields;
3544
3545 /// GetAddrOfTypeName - Returns the mangled type name of the given type.
3546 llvm::GlobalVariable *
3547 GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
3548
3549 /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
3550 /// descriptor of the given type.
3551 llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
3552
3553 /// BuildVTablePointer - Build the vtable pointer for the given type.
3554 void BuildVTablePointer(const Type *Ty, llvm::Constant *StorageAddress);
3555
3556 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
3557 /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
3558 void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
3559
3560 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
3561 /// classes with bases that do not satisfy the abi::__si_class_type_info
3562 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
3563 void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
3564
3565 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
3566 /// for pointer types.
3567 void BuildPointerTypeInfo(QualType PointeeTy);
3568
3569 /// BuildObjCObjectTypeInfo - Build the appropriate kind of
3570 /// type_info for an object type.
3571 void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
3572
3573 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
3574 /// struct, used for member pointer types.
3575 void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
3576
3577public:
3578 ItaniumRTTIBuilder(const ItaniumCXXABI &ABI)
3579 : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {}
3580
3581 // Pointer type info flags.
3582 enum {
3583 /// PTI_Const - Type has const qualifier.
3584 PTI_Const = 0x1,
3585
3586 /// PTI_Volatile - Type has volatile qualifier.
3587 PTI_Volatile = 0x2,
3588
3589 /// PTI_Restrict - Type has restrict qualifier.
3590 PTI_Restrict = 0x4,
3591
3592 /// PTI_Incomplete - Type is incomplete.
3593 PTI_Incomplete = 0x8,
3594
3595 /// PTI_ContainingClassIncomplete - Containing class is incomplete.
3596 /// (in pointer to member).
3597 PTI_ContainingClassIncomplete = 0x10,
3598
3599 /// PTI_TransactionSafe - Pointee is transaction_safe function (C++ TM TS).
3600 //PTI_TransactionSafe = 0x20,
3601
3602 /// PTI_Noexcept - Pointee is noexcept function (C++1z).
3603 PTI_Noexcept = 0x40,
3604 };
3605
3606 // VMI type info flags.
3607 enum {
3608 /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
3609 VMI_NonDiamondRepeat = 0x1,
3610
3611 /// VMI_DiamondShaped - Class is diamond shaped.
3612 VMI_DiamondShaped = 0x2
3613 };
3614
3615 // Base class type info flags.
3616 enum {
3617 /// BCTI_Virtual - Base class is virtual.
3618 BCTI_Virtual = 0x1,
3619
3620 /// BCTI_Public - Base class is public.
3621 BCTI_Public = 0x2
3622 };
3623
3624 /// BuildTypeInfo - Build the RTTI type info struct for the given type, or
3625 /// link to an existing RTTI descriptor if one already exists.
3626 llvm::Constant *BuildTypeInfo(QualType Ty);
3627
3628 /// BuildTypeInfo - Build the RTTI type info struct for the given type.
3629 llvm::Constant *BuildTypeInfo(
3630 QualType Ty,
3631 llvm::GlobalVariable::LinkageTypes Linkage,
3632 llvm::GlobalValue::VisibilityTypes Visibility,
3633 llvm::GlobalValue::DLLStorageClassTypes DLLStorageClass);
3634};
3635}
3636
3637llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName(
3638 QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) {
3639 SmallString<256> Name;
3640 llvm::raw_svector_ostream Out(Name);
3642
3643 // We know that the mangled name of the type starts at index 4 of the
3644 // mangled name of the typename, so we can just index into it in order to
3645 // get the mangled name of the type.
3646 llvm::Constant *Init;
3647 if (CGM.getTriple().isOSzOS()) {
3648 // On z/OS, typename is stored as 2 encodings: EBCDIC followed by ASCII.
3649 SmallString<256> DualEncodedName;
3650 llvm::ConverterEBCDIC::convertToEBCDIC(Name.substr(4), DualEncodedName);
3651 DualEncodedName += '\0';
3652 DualEncodedName += Name.substr(4);
3653 Init = llvm::ConstantDataArray::getString(VMContext, DualEncodedName);
3654 } else
3655 Init = llvm::ConstantDataArray::getString(VMContext, Name.substr(4));
3656
3657 auto Align = CGM.getContext().getTypeAlignInChars(CGM.getContext().CharTy);
3658
3659 llvm::GlobalVariable *GV = CGM.CreateOrReplaceCXXRuntimeVariable(
3660 Name, Init->getType(), Linkage, Align.getAsAlign());
3661
3662 GV->setInitializer(Init);
3663
3664 return GV;
3665}
3666
3667llvm::Constant *
3668ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
3669 // Mangle the RTTI name.
3670 SmallString<256> Name;
3671 llvm::raw_svector_ostream Out(Name);
3672 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
3673
3674 // Look for an existing global.
3675 llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
3676
3677 if (!GV) {
3678 // Create a new global variable.
3679 // Note for the future: If we would ever like to do deferred emission of
3680 // RTTI, check if emitting vtables opportunistically need any adjustment.
3681
3682 GV = new llvm::GlobalVariable(
3683 CGM.getModule(), CGM.GlobalsInt8PtrTy,
3684 /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage, nullptr, Name);
3685 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
3686 CGM.setGVProperties(GV, RD);
3687 // Import the typeinfo symbol when all non-inline virtual methods are
3688 // imported.
3689 if (CGM.getTarget().hasPS4DLLImportExport()) {
3691 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
3692 CGM.setDSOLocal(GV);
3693 }
3694 }
3695 }
3696
3697 return GV;
3698}
3699
3700/// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
3701/// info for that type is defined in the standard library.
3703 // Itanium C++ ABI 2.9.2:
3704 // Basic type information (e.g. for "int", "bool", etc.) will be kept in
3705 // the run-time support library. Specifically, the run-time support
3706 // library should contain type_info objects for the types X, X* and
3707 // X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
3708 // unsigned char, signed char, short, unsigned short, int, unsigned int,
3709 // long, unsigned long, long long, unsigned long long, float, double,
3710 // long double, char16_t, char32_t, and the IEEE 754r decimal and
3711 // half-precision floating point types.
3712 //
3713 // GCC also emits RTTI for __int128.
3714 // FIXME: We do not emit RTTI information for decimal types here.
3715
3716 // Types added here must also be added to EmitFundamentalRTTIDescriptors.
3717 switch (Ty->getKind()) {
3718 case BuiltinType::Void:
3719 case BuiltinType::NullPtr:
3720 case BuiltinType::Bool:
3721 case BuiltinType::WChar_S:
3722 case BuiltinType::WChar_U:
3723 case BuiltinType::Char_U:
3724 case BuiltinType::Char_S:
3725 case BuiltinType::UChar:
3726 case BuiltinType::SChar:
3727 case BuiltinType::Short:
3728 case BuiltinType::UShort:
3729 case BuiltinType::Int:
3730 case BuiltinType::UInt:
3731 case BuiltinType::Long:
3732 case BuiltinType::ULong:
3733 case BuiltinType::LongLong:
3734 case BuiltinType::ULongLong:
3735 case BuiltinType::Half:
3736 case BuiltinType::Float:
3737 case BuiltinType::Double:
3738 case BuiltinType::LongDouble:
3739 case BuiltinType::Float16:
3740 case BuiltinType::Float128:
3741 case BuiltinType::Ibm128:
3742 case BuiltinType::Char8:
3743 case BuiltinType::Char16:
3744 case BuiltinType::Char32:
3745 case BuiltinType::Int128:
3746 case BuiltinType::UInt128:
3747 return true;
3748
3749#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3750 case BuiltinType::Id:
3751#include "clang/Basic/OpenCLImageTypes.def"
3752#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
3753 case BuiltinType::Id:
3754#include "clang/Basic/OpenCLExtensionTypes.def"
3755 case BuiltinType::OCLSampler:
3756 case BuiltinType::OCLEvent:
3757 case BuiltinType::OCLClkEvent:
3758 case BuiltinType::OCLQueue:
3759 case BuiltinType::OCLReserveID:
3760#define SVE_TYPE(Name, Id, SingletonId) \
3761 case BuiltinType::Id:
3762#include "clang/Basic/AArch64ACLETypes.def"
3763#define PPC_VECTOR_TYPE(Name, Id, Size) \
3764 case BuiltinType::Id:
3765#include "clang/Basic/PPCTypes.def"
3766#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
3767#include "clang/Basic/RISCVVTypes.def"
3768#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
3769#include "clang/Basic/WebAssemblyReferenceTypes.def"
3770#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
3771#include "clang/Basic/AMDGPUTypes.def"
3772#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
3773#include "clang/Basic/HLSLIntangibleTypes.def"
3774 case BuiltinType::ShortAccum:
3775 case BuiltinType::Accum:
3776 case BuiltinType::LongAccum:
3777 case BuiltinType::UShortAccum:
3778 case BuiltinType::UAccum:
3779 case BuiltinType::ULongAccum:
3780 case BuiltinType::ShortFract:
3781 case BuiltinType::Fract:
3782 case BuiltinType::LongFract:
3783 case BuiltinType::UShortFract:
3784 case BuiltinType::UFract:
3785 case BuiltinType::ULongFract:
3786 case BuiltinType::SatShortAccum:
3787 case BuiltinType::SatAccum:
3788 case BuiltinType::SatLongAccum:
3789 case BuiltinType::SatUShortAccum:
3790 case BuiltinType::SatUAccum:
3791 case BuiltinType::SatULongAccum:
3792 case BuiltinType::SatShortFract:
3793 case BuiltinType::SatFract:
3794 case BuiltinType::SatLongFract:
3795 case BuiltinType::SatUShortFract:
3796 case BuiltinType::SatUFract:
3797 case BuiltinType::SatULongFract:
3798 case BuiltinType::BFloat16:
3799 return false;
3800
3801 case BuiltinType::Dependent:
3802#define BUILTIN_TYPE(Id, SingletonId)
3803#define PLACEHOLDER_TYPE(Id, SingletonId) \
3804 case BuiltinType::Id:
3805#include "clang/AST/BuiltinTypes.def"
3806 llvm_unreachable("asking for RRTI for a placeholder type!");
3807
3808 case BuiltinType::ObjCId:
3809 case BuiltinType::ObjCClass:
3810 case BuiltinType::ObjCSel:
3811 llvm_unreachable("FIXME: Objective-C types are unsupported!");
3812 }
3813
3814 llvm_unreachable("Invalid BuiltinType Kind!");
3815}
3816
3817static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
3818 QualType PointeeTy = PointerTy->getPointeeType();
3819 const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
3820 if (!BuiltinTy)
3821 return false;
3822
3823 // Check the qualifiers.
3824 Qualifiers Quals = PointeeTy.getQualifiers();
3825 Quals.removeConst();
3826
3827 if (!Quals.empty())
3828 return false;
3829
3830 return TypeInfoIsInStandardLibrary(BuiltinTy);
3831}
3832
3833/// IsStandardLibraryRTTIDescriptor - Returns whether the type
3834/// information for the given type exists in the standard library.
3836 // Type info for builtin types is defined in the standard library.
3837 if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
3838 return TypeInfoIsInStandardLibrary(BuiltinTy);
3839
3840 // Type info for some pointer types to builtin types is defined in the
3841 // standard library.
3842 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
3843 return TypeInfoIsInStandardLibrary(PointerTy);
3844
3845 return false;
3846}
3847
3848/// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
3849/// the given type exists somewhere else, and that we should not emit the type
3850/// information in this translation unit. Assumes that it is not a
3851/// standard-library type.
3853 QualType Ty) {
3854 ASTContext &Context = CGM.getContext();
3855
3856 // If RTTI is disabled, assume it might be disabled in the
3857 // translation unit that defines any potential key function, too.
3858 if (!Context.getLangOpts().RTTI) return false;
3859
3860 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
3861 const CXXRecordDecl *RD =
3862 cast<CXXRecordDecl>(RecordTy->getDecl())->getDefinitionOrSelf();
3863 if (!RD->hasDefinition())
3864 return false;
3865
3866 if (!RD->isDynamicClass())
3867 return false;
3868
3869 // FIXME: this may need to be reconsidered if the key function
3870 // changes.
3871 // N.B. We must always emit the RTTI data ourselves if there exists a key
3872 // function.
3873 bool IsDLLImport = RD->hasAttr<DLLImportAttr>();
3874
3875 // Don't import the RTTI but emit it locally.
3876 if (CGM.getTriple().isOSCygMing())
3877 return false;
3878
3879 if (CGM.getVTables().isVTableExternal(RD)) {
3880 if (CGM.getTarget().hasPS4DLLImportExport())
3881 return true;
3882
3883 return IsDLLImport && !CGM.getTriple().isWindowsItaniumEnvironment()
3884 ? false
3885 : true;
3886 }
3887 if (IsDLLImport)
3888 return true;
3889 }
3890
3891 return false;
3892}
3893
3894/// IsIncompleteClassType - Returns whether the given record type is incomplete.
3895static bool IsIncompleteClassType(const RecordType *RecordTy) {
3896 return !RecordTy->getDecl()->getDefinitionOrSelf()->isCompleteDefinition();
3897}
3898
3899/// ContainsIncompleteClassType - Returns whether the given type contains an
3900/// incomplete class type. This is true if
3901///
3902/// * The given type is an incomplete class type.
3903/// * The given type is a pointer type whose pointee type contains an
3904/// incomplete class type.
3905/// * The given type is a member pointer type whose class is an incomplete
3906/// class type.
3907/// * The given type is a member pointer type whoise pointee type contains an
3908/// incomplete class type.
3909/// is an indirect or direct pointer to an incomplete class type.
3911 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
3912 if (IsIncompleteClassType(RecordTy))
3913 return true;
3914 }
3915
3916 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
3917 return ContainsIncompleteClassType(PointerTy->getPointeeType());
3918
3919 if (const MemberPointerType *MemberPointerTy =
3920 dyn_cast<MemberPointerType>(Ty)) {
3921 // Check if the class type is incomplete.
3922 if (!MemberPointerTy->getMostRecentCXXRecordDecl()->hasDefinition())
3923 return true;
3924
3925 return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
3926 }
3927
3928 return false;
3929}
3930
3931// CanUseSingleInheritance - Return whether the given record decl has a "single,
3932// public, non-virtual base at offset zero (i.e. the derived class is dynamic
3933// iff the base is)", according to Itanium C++ ABI, 2.95p6b.
3935 // Check the number of bases.
3936 if (RD->getNumBases() != 1)
3937 return false;
3938
3939 // Get the base.
3941
3942 // Check that the base is not virtual.
3943 if (Base->isVirtual())
3944 return false;
3945
3946 // Check that the base is public.
3947 if (Base->getAccessSpecifier() != AS_public)
3948 return false;
3949
3950 // Check that the class is dynamic iff the base is.
3951 auto *BaseDecl = Base->getType()->castAsCXXRecordDecl();
3952 if (!BaseDecl->isEmpty() &&
3953 BaseDecl->isDynamicClass() != RD->isDynamicClass())
3954 return false;
3955
3956 return true;
3957}
3958
3959void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty,
3960 llvm::Constant *StorageAddress) {
3961 // abi::__class_type_info.
3962 static const char * const ClassTypeInfo =
3963 "_ZTVN10__cxxabiv117__class_type_infoE";
3964 // abi::__si_class_type_info.
3965 static const char * const SIClassTypeInfo =
3966 "_ZTVN10__cxxabiv120__si_class_type_infoE";
3967 // abi::__vmi_class_type_info.
3968 static const char * const VMIClassTypeInfo =
3969 "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
3970
3971 const char *VTableName = nullptr;
3972
3973 switch (Ty->getTypeClass()) {
3974#define TYPE(Class, Base)
3975#define ABSTRACT_TYPE(Class, Base)
3976#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3977#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3978#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3979#include "clang/AST/TypeNodes.inc"
3980 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
3981
3982 case Type::LValueReference:
3983 case Type::RValueReference:
3984 llvm_unreachable("References shouldn't get here");
3985
3986 case Type::Auto:
3987 case Type::DeducedTemplateSpecialization:
3988 llvm_unreachable("Undeduced type shouldn't get here");
3989
3990 case Type::Pipe:
3991 llvm_unreachable("Pipe types shouldn't get here");
3992
3993 case Type::ArrayParameter:
3994 llvm_unreachable("Array Parameter types should not get here.");
3995
3996 case Type::Builtin:
3997 case Type::BitInt:
3998 case Type::OverflowBehavior:
3999 // GCC treats vector and complex types as fundamental types.
4000 case Type::Vector:
4001 case Type::ExtVector:
4002 case Type::ConstantMatrix:
4003 case Type::Complex:
4004 case Type::Atomic:
4005 // FIXME: GCC treats block pointers as fundamental types?!
4006 case Type::BlockPointer:
4007 // abi::__fundamental_type_info.
4008 VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
4009 break;
4010
4011 case Type::ConstantArray:
4012 case Type::IncompleteArray:
4013 case Type::VariableArray:
4014 // abi::__array_type_info.
4015 VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
4016 break;
4017
4018 case Type::FunctionNoProto:
4019 case Type::FunctionProto:
4020 // abi::__function_type_info.
4021 VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
4022 break;
4023
4024 case Type::Enum:
4025 // abi::__enum_type_info.
4026 VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
4027 break;
4028
4029 case Type::Record: {
4030 const auto *RD = cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl())
4031 ->getDefinitionOrSelf();
4032
4033 if (!RD->hasDefinition() || !RD->getNumBases()) {
4034 VTableName = ClassTypeInfo;
4035 } else if (CanUseSingleInheritance(RD)) {
4036 VTableName = SIClassTypeInfo;
4037 } else {
4038 VTableName = VMIClassTypeInfo;
4039 }
4040
4041 break;
4042 }
4043
4044 case Type::ObjCObject:
4045 // Ignore protocol qualifiers.
4046 Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
4047
4048 // Handle id and Class.
4049 if (isa<BuiltinType>(Ty)) {
4050 VTableName = ClassTypeInfo;
4051 break;
4052 }
4053
4054 assert(isa<ObjCInterfaceType>(Ty));
4055 [[fallthrough]];
4056
4057 case Type::ObjCInterface:
4058 if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
4059 VTableName = SIClassTypeInfo;
4060 } else {
4061 VTableName = ClassTypeInfo;
4062 }
4063 break;
4064
4065 case Type::ObjCObjectPointer:
4066 case Type::Pointer:
4067 // abi::__pointer_type_info.
4068 VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
4069 break;
4070
4071 case Type::MemberPointer:
4072 // abi::__pointer_to_member_type_info.
4073 VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
4074 break;
4075
4076 case Type::HLSLAttributedResource:
4077 case Type::HLSLInlineSpirv:
4078 llvm_unreachable("HLSL doesn't support virtual functions");
4079 }
4080
4081 llvm::Constant *VTable = nullptr;
4082
4083 // Check if the alias exists. If it doesn't, then get or create the global.
4085 VTable = CGM.getModule().getNamedAlias(VTableName);
4086 if (!VTable) {
4087 llvm::Type *Ty = llvm::ArrayType::get(CGM.GlobalsInt8PtrTy, 0);
4088 VTable = CGM.getModule().getOrInsertGlobal(VTableName, Ty);
4089 }
4090
4091 CGM.setDSOLocal(cast<llvm::GlobalValue>(VTable->stripPointerCasts()));
4092
4093 llvm::Type *PtrDiffTy =
4095
4096 // The vtable address point is 2.
4098 // The vtable address point is 8 bytes after its start:
4099 // 4 for the offset to top + 4 for the relative offset to rtti.
4100 llvm::Constant *Eight = llvm::ConstantInt::get(CGM.Int32Ty, 8);
4101 VTable = llvm::ConstantExpr::getInBoundsPtrAdd(VTable, Eight);
4102 } else {
4103 llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
4104 VTable = llvm::ConstantExpr::getInBoundsGetElementPtr(CGM.GlobalsInt8PtrTy,
4105 VTable, Two);
4106 }
4107
4108 if (const auto &Schema =
4110 VTable = CGM.getConstantSignedPointer(
4111 VTable, Schema,
4112 Schema.isAddressDiscriminated() ? StorageAddress : nullptr,
4113 GlobalDecl(), QualType(Ty, 0));
4114
4115 Fields.push_back(VTable);
4116}
4117
4118/// Return the linkage that the type info and type info name constants
4119/// should have for the given type.
4120static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM,
4121 QualType Ty) {
4122 // Itanium C++ ABI 2.9.5p7:
4123 // In addition, it and all of the intermediate abi::__pointer_type_info
4124 // structs in the chain down to the abi::__class_type_info for the
4125 // incomplete class type must be prevented from resolving to the
4126 // corresponding type_info structs for the complete class type, possibly
4127 // by making them local static objects. Finally, a dummy class RTTI is
4128 // generated for the incomplete type that will not resolve to the final
4129 // complete class RTTI (because the latter need not exist), possibly by
4130 // making it a local static object.
4132 return llvm::GlobalValue::InternalLinkage;
4133
4134 switch (Ty->getLinkage()) {
4135 case Linkage::Invalid:
4136 llvm_unreachable("Linkage hasn't been computed!");
4137
4138 case Linkage::None:
4139 case Linkage::Internal:
4141 return llvm::GlobalValue::InternalLinkage;
4142
4144 case Linkage::Module:
4145 case Linkage::External:
4146 // RTTI is not enabled, which means that this type info struct is going
4147 // to be used for exception handling. Give it linkonce_odr linkage.
4148 if (!CGM.getLangOpts().RTTI)
4149 return llvm::GlobalValue::LinkOnceODRLinkage;
4150
4151 if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
4152 const auto *RD =
4153 cast<CXXRecordDecl>(Record->getDecl())->getDefinitionOrSelf();
4154 if (RD->hasAttr<WeakAttr>())
4155 return llvm::GlobalValue::WeakODRLinkage;
4156 if (CGM.getTriple().isWindowsItaniumEnvironment())
4157 if (RD->hasAttr<DLLImportAttr>() &&
4159 return llvm::GlobalValue::ExternalLinkage;
4160 // MinGW always uses LinkOnceODRLinkage for type info.
4161 if (RD->isDynamicClass() &&
4162 !CGM.getContext().getTargetInfo().getTriple().isOSCygMing())
4163 return CGM.getVTableLinkage(RD);
4164 }
4165
4166 return llvm::GlobalValue::LinkOnceODRLinkage;
4167 }
4168
4169 llvm_unreachable("Invalid linkage!");
4170}
4171
4172llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty) {
4173 // We want to operate on the canonical type.
4174 Ty = Ty.getCanonicalType();
4175
4176 // Check if we've already emitted an RTTI descriptor for this type.
4177 SmallString<256> Name;
4178 llvm::raw_svector_ostream Out(Name);
4179 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
4180
4181 llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
4182 if (OldGV && !OldGV->isDeclaration()) {
4183 assert(!OldGV->hasAvailableExternallyLinkage() &&
4184 "available_externally typeinfos not yet implemented");
4185
4186 return OldGV;
4187 }
4188
4189 // Check if there is already an external RTTI descriptor for this type.
4192 return GetAddrOfExternalRTTIDescriptor(Ty);
4193
4194 // Emit the standard library with external linkage.
4195 llvm::GlobalVariable::LinkageTypes Linkage = getTypeInfoLinkage(CGM, Ty);
4196
4197 // Give the type_info object and name the formal visibility of the
4198 // type itself.
4199 llvm::GlobalValue::VisibilityTypes llvmVisibility;
4200 if (llvm::GlobalValue::isLocalLinkage(Linkage))
4201 // If the linkage is local, only default visibility makes sense.
4202 llvmVisibility = llvm::GlobalValue::DefaultVisibility;
4203 else if (CXXABI.classifyRTTIUniqueness(Ty, Linkage) ==
4204 ItaniumCXXABI::RUK_NonUniqueHidden)
4205 llvmVisibility = llvm::GlobalValue::HiddenVisibility;
4206 else
4207 llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility());
4208
4209 llvm::GlobalValue::DLLStorageClassTypes DLLStorageClass =
4210 llvm::GlobalValue::DefaultStorageClass;
4211 if (auto RD = Ty->getAsCXXRecordDecl()) {
4212 if ((CGM.getTriple().isWindowsItaniumEnvironment() &&
4213 RD->hasAttr<DLLExportAttr>()) ||
4215 !llvm::GlobalValue::isLocalLinkage(Linkage) &&
4216 llvmVisibility == llvm::GlobalValue::DefaultVisibility))
4217 DLLStorageClass = llvm::GlobalValue::DLLExportStorageClass;
4218 }
4219 return BuildTypeInfo(Ty, Linkage, llvmVisibility, DLLStorageClass);
4220}
4221
4222llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(
4223 QualType Ty,
4224 llvm::GlobalVariable::LinkageTypes Linkage,
4225 llvm::GlobalValue::VisibilityTypes Visibility,
4226 llvm::GlobalValue::DLLStorageClassTypes DLLStorageClass) {
4227 SmallString<256> Name;
4228 llvm::raw_svector_ostream Out(Name);
4229 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
4230 llvm::Module &M = CGM.getModule();
4231 llvm::GlobalVariable *OldGV = M.getNamedGlobal(Name);
4232 // int8 is an arbitrary type to be replaced later with replaceInitializer.
4233 llvm::GlobalVariable *GV =
4234 new llvm::GlobalVariable(M, CGM.Int8Ty, /*isConstant=*/true, Linkage,
4235 /*Initializer=*/nullptr, Name);
4236
4237 // Add the vtable pointer.
4238 BuildVTablePointer(cast<Type>(Ty), GV);
4239
4240 // And the name.
4241 llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
4242 llvm::Constant *TypeNameField;
4243
4244 // If we're supposed to demote the visibility, be sure to set a flag
4245 // to use a string comparison for type_info comparisons.
4246 ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness =
4247 CXXABI.classifyRTTIUniqueness(Ty, Linkage);
4248 if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) {
4249 // The flag is the sign bit, which on ARM64 is defined to be clear
4250 // for global pointers. This is very ARM64-specific.
4251 TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty);
4252 llvm::Constant *flag =
4253 llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63);
4254 TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag);
4255 TypeNameField =
4256 llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.GlobalsInt8PtrTy);
4257 } else {
4258 TypeNameField = TypeName;
4259 }
4260 Fields.push_back(TypeNameField);
4261
4262 switch (Ty->getTypeClass()) {
4263#define TYPE(Class, Base)
4264#define ABSTRACT_TYPE(Class, Base)
4265#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
4266#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4267#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4268#include "clang/AST/TypeNodes.inc"
4269 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
4270
4271 // GCC treats vector types as fundamental types.
4272 case Type::Builtin:
4273 case Type::Vector:
4274 case Type::ExtVector:
4275 case Type::ConstantMatrix:
4276 case Type::Complex:
4277 case Type::BlockPointer:
4278 // Itanium C++ ABI 2.9.5p4:
4279 // abi::__fundamental_type_info adds no data members to std::type_info.
4280 break;
4281
4282 case Type::LValueReference:
4283 case Type::RValueReference:
4284 llvm_unreachable("References shouldn't get here");
4285
4286 case Type::Auto:
4287 case Type::DeducedTemplateSpecialization:
4288 llvm_unreachable("Undeduced type shouldn't get here");
4289
4290 case Type::Pipe:
4291 break;
4292
4293 case Type::BitInt:
4294 break;
4295
4296 case Type::ConstantArray:
4297 case Type::IncompleteArray:
4298 case Type::VariableArray:
4299 case Type::ArrayParameter:
4300 // Itanium C++ ABI 2.9.5p5:
4301 // abi::__array_type_info adds no data members to std::type_info.
4302 break;
4303
4304 case Type::FunctionNoProto:
4305 case Type::FunctionProto:
4306 // Itanium C++ ABI 2.9.5p5:
4307 // abi::__function_type_info adds no data members to std::type_info.
4308 break;
4309
4310 case Type::Enum:
4311 // Itanium C++ ABI 2.9.5p5:
4312 // abi::__enum_type_info adds no data members to std::type_info.
4313 break;
4314
4315 case Type::Record: {
4316 const auto *RD = cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl())
4317 ->getDefinitionOrSelf();
4318 if (!RD->hasDefinition() || !RD->getNumBases()) {
4319 // We don't need to emit any fields.
4320 break;
4321 }
4322
4324 BuildSIClassTypeInfo(RD);
4325 else
4326 BuildVMIClassTypeInfo(RD);
4327
4328 break;
4329 }
4330
4331 case Type::ObjCObject:
4332 case Type::ObjCInterface:
4333 BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
4334 break;
4335
4336 case Type::ObjCObjectPointer:
4337 BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
4338 break;
4339
4340 case Type::Pointer:
4341 BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
4342 break;
4343
4344 case Type::MemberPointer:
4345 BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
4346 break;
4347
4348 case Type::Atomic:
4349 // No fields, at least for the moment.
4350 break;
4351
4352 case Type::OverflowBehavior:
4353 break;
4354
4355 case Type::HLSLAttributedResource:
4356 case Type::HLSLInlineSpirv:
4357 llvm_unreachable("HLSL doesn't support RTTI");
4358 }
4359
4360 GV->replaceInitializer(llvm::ConstantStruct::getAnon(Fields));
4361
4362 // Export the typeinfo in the same circumstances as the vtable is exported.
4363 auto GVDLLStorageClass = DLLStorageClass;
4364 if (CGM.getTarget().hasPS4DLLImportExport() &&
4365 GVDLLStorageClass != llvm::GlobalVariable::DLLExportStorageClass) {
4366 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
4367 const auto *RD =
4368 cast<CXXRecordDecl>(RecordTy->getDecl())->getDefinitionOrSelf();
4369 if (RD->hasAttr<DLLExportAttr>() ||
4371 GVDLLStorageClass = llvm::GlobalVariable::DLLExportStorageClass;
4372 }
4373 }
4374
4375 // If there's already an old global variable, replace it with the new one.
4376 if (OldGV) {
4377 GV->takeName(OldGV);
4378 OldGV->replaceAllUsesWith(GV);
4379 OldGV->eraseFromParent();
4380 }
4381
4382 if (CGM.supportsCOMDAT() && GV->isWeakForLinker())
4383 GV->setComdat(M.getOrInsertComdat(GV->getName()));
4384
4385 CharUnits Align = CGM.getContext().toCharUnitsFromBits(
4387 GV->setAlignment(Align.getAsAlign());
4388
4389 // The Itanium ABI specifies that type_info objects must be globally
4390 // unique, with one exception: if the type is an incomplete class
4391 // type or a (possibly indirect) pointer to one. That exception
4392 // affects the general case of comparing type_info objects produced
4393 // by the typeid operator, which is why the comparison operators on
4394 // std::type_info generally use the type_info name pointers instead
4395 // of the object addresses. However, the language's built-in uses
4396 // of RTTI generally require class types to be complete, even when
4397 // manipulating pointers to those class types. This allows the
4398 // implementation of dynamic_cast to rely on address equality tests,
4399 // which is much faster.
4400
4401 // All of this is to say that it's important that both the type_info
4402 // object and the type_info name be uniqued when weakly emitted.
4403
4404 TypeName->setVisibility(Visibility);
4405 CGM.setDSOLocal(TypeName);
4406
4407 GV->setVisibility(Visibility);
4408 CGM.setDSOLocal(GV);
4409
4410 TypeName->setDLLStorageClass(DLLStorageClass);
4411 GV->setDLLStorageClass(GVDLLStorageClass);
4412
4413 TypeName->setPartition(CGM.getCodeGenOpts().SymbolPartition);
4414 GV->setPartition(CGM.getCodeGenOpts().SymbolPartition);
4415
4416 return GV;
4417}
4418
4419/// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
4420/// for the given Objective-C object type.
4421void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
4422 // Drop qualifiers.
4423 const Type *T = OT->getBaseType().getTypePtr();
4425
4426 // The builtin types are abi::__class_type_infos and don't require
4427 // extra fields.
4428 if (isa<BuiltinType>(T)) return;
4429
4430 ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
4431 ObjCInterfaceDecl *Super = Class->getSuperClass();
4432
4433 // Root classes are also __class_type_info.
4434 if (!Super) return;
4435
4436 QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
4437
4438 // Everything else is single inheritance.
4439 llvm::Constant *BaseTypeInfo =
4440 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy);
4441 Fields.push_back(BaseTypeInfo);
4442}
4443
4444/// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
4445/// inheritance, according to the Itanium C++ ABI, 2.95p6b.
4446void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
4447 // Itanium C++ ABI 2.9.5p6b:
4448 // It adds to abi::__class_type_info a single member pointing to the
4449 // type_info structure for the base type,
4450 llvm::Constant *BaseTypeInfo =
4451 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType());
4452 Fields.push_back(BaseTypeInfo);
4453}
4454
4455namespace {
4456 /// SeenBases - Contains virtual and non-virtual bases seen when traversing
4457 /// a class hierarchy.
4458 struct SeenBases {
4459 llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
4460 llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
4461 };
4462}
4463
4464/// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
4465/// abi::__vmi_class_type_info.
4466///
4468 SeenBases &Bases) {
4469
4470 unsigned Flags = 0;
4471
4472 auto *BaseDecl = Base->getType()->castAsCXXRecordDecl();
4473 if (Base->isVirtual()) {
4474 // Mark the virtual base as seen.
4475 if (!Bases.VirtualBases.insert(BaseDecl).second) {
4476 // If this virtual base has been seen before, then the class is diamond
4477 // shaped.
4478 Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped;
4479 } else {
4480 if (Bases.NonVirtualBases.count(BaseDecl))
4481 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
4482 }
4483 } else {
4484 // Mark the non-virtual base as seen.
4485 if (!Bases.NonVirtualBases.insert(BaseDecl).second) {
4486 // If this non-virtual base has been seen before, then the class has non-
4487 // diamond shaped repeated inheritance.
4488 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
4489 } else {
4490 if (Bases.VirtualBases.count(BaseDecl))
4491 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
4492 }
4493 }
4494
4495 // Walk all bases.
4496 for (const auto &I : BaseDecl->bases())
4497 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
4498
4499 return Flags;
4500}
4501
4503 unsigned Flags = 0;
4504 SeenBases Bases;
4505
4506 // Walk all bases.
4507 for (const auto &I : RD->bases())
4508 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
4509
4510 return Flags;
4511}
4512
4513/// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
4514/// classes with bases that do not satisfy the abi::__si_class_type_info
4515/// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
4516void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
4517 llvm::Type *UnsignedIntLTy =
4519
4520 // Itanium C++ ABI 2.9.5p6c:
4521 // __flags is a word with flags describing details about the class
4522 // structure, which may be referenced by using the __flags_masks
4523 // enumeration. These flags refer to both direct and indirect bases.
4524 unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
4525 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
4526
4527 // Itanium C++ ABI 2.9.5p6c:
4528 // __base_count is a word with the number of direct proper base class
4529 // descriptions that follow.
4530 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
4531
4532 if (!RD->getNumBases())
4533 return;
4534
4535 // Now add the base class descriptions.
4536
4537 // Itanium C++ ABI 2.9.5p6c:
4538 // __base_info[] is an array of base class descriptions -- one for every
4539 // direct proper base. Each description is of the type:
4540 //
4541 // struct abi::__base_class_type_info {
4542 // public:
4543 // const __class_type_info *__base_type;
4544 // long __offset_flags;
4545 //
4546 // enum __offset_flags_masks {
4547 // __virtual_mask = 0x1,
4548 // __public_mask = 0x2,
4549 // __offset_shift = 8
4550 // };
4551 // };
4552
4553 // If we're in mingw and 'long' isn't wide enough for a pointer, use 'long
4554 // long' instead of 'long' for __offset_flags. libstdc++abi uses long long on
4555 // LLP64 platforms.
4556 // FIXME: Consider updating libc++abi to match, and extend this logic to all
4557 // LLP64 platforms.
4558 QualType OffsetFlagsTy = CGM.getContext().LongTy;
4559 const TargetInfo &TI = CGM.getContext().getTargetInfo();
4560 if (TI.getTriple().isOSCygMing() &&
4561 TI.getPointerWidth(LangAS::Default) > TI.getLongWidth())
4562 OffsetFlagsTy = CGM.getContext().LongLongTy;
4563 llvm::Type *OffsetFlagsLTy =
4564 CGM.getTypes().ConvertType(OffsetFlagsTy);
4565
4566 for (const auto &Base : RD->bases()) {
4567 // The __base_type member points to the RTTI for the base type.
4568 Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType()));
4569
4570 auto *BaseDecl = Base.getType()->castAsCXXRecordDecl();
4571 int64_t OffsetFlags = 0;
4572
4573 // All but the lower 8 bits of __offset_flags are a signed offset.
4574 // For a non-virtual base, this is the offset in the object of the base
4575 // subobject. For a virtual base, this is the offset in the virtual table of
4576 // the virtual base offset for the virtual base referenced (negative).
4577 CharUnits Offset;
4578 if (Base.isVirtual())
4579 Offset =
4581 else {
4582 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
4583 Offset = Layout.getBaseClassOffset(BaseDecl);
4584 };
4585
4586 OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
4587
4588 // The low-order byte of __offset_flags contains flags, as given by the
4589 // masks from the enumeration __offset_flags_masks.
4590 if (Base.isVirtual())
4591 OffsetFlags |= BCTI_Virtual;
4592 if (Base.getAccessSpecifier() == AS_public)
4593 OffsetFlags |= BCTI_Public;
4594
4595 Fields.push_back(llvm::ConstantInt::getSigned(OffsetFlagsLTy, OffsetFlags));
4596 }
4597}
4598
4599/// Compute the flags for a __pbase_type_info, and remove the corresponding
4600/// pieces from \p Type.
4602 unsigned Flags = 0;
4603
4604 if (Type.isConstQualified())
4605 Flags |= ItaniumRTTIBuilder::PTI_Const;
4606 if (Type.isVolatileQualified())
4607 Flags |= ItaniumRTTIBuilder::PTI_Volatile;
4608 if (Type.isRestrictQualified())
4609 Flags |= ItaniumRTTIBuilder::PTI_Restrict;
4610 Type = Type.getUnqualifiedType();
4611
4612 // Itanium C++ ABI 2.9.5p7:
4613 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
4614 // incomplete class type, the incomplete target type flag is set.
4616 Flags |= ItaniumRTTIBuilder::PTI_Incomplete;
4617
4618 if (auto *Proto = Type->getAs<FunctionProtoType>()) {
4619 if (Proto->isNothrow()) {
4620 Flags |= ItaniumRTTIBuilder::PTI_Noexcept;
4622 }
4623 }
4624
4625 return Flags;
4626}
4627
4628/// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
4629/// used for pointer types.
4630void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
4631 // Itanium C++ ABI 2.9.5p7:
4632 // __flags is a flag word describing the cv-qualification and other
4633 // attributes of the type pointed to
4634 unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy);
4635
4636 llvm::Type *UnsignedIntLTy =
4638 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
4639
4640 // Itanium C++ ABI 2.9.5p7:
4641 // __pointee is a pointer to the std::type_info derivation for the
4642 // unqualified type being pointed to.
4643 llvm::Constant *PointeeTypeInfo =
4644 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy);
4645 Fields.push_back(PointeeTypeInfo);
4646}
4647
4648/// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
4649/// struct, used for member pointer types.
4650void
4651ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
4652 QualType PointeeTy = Ty->getPointeeType();
4653
4654 // Itanium C++ ABI 2.9.5p7:
4655 // __flags is a flag word describing the cv-qualification and other
4656 // attributes of the type pointed to.
4657 unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy);
4658
4659 const auto *RD = Ty->getMostRecentCXXRecordDecl();
4660 if (!RD->hasDefinition())
4661 Flags |= PTI_ContainingClassIncomplete;
4662
4663 llvm::Type *UnsignedIntLTy =
4665 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
4666
4667 // Itanium C++ ABI 2.9.5p7:
4668 // __pointee is a pointer to the std::type_info derivation for the
4669 // unqualified type being pointed to.
4670 llvm::Constant *PointeeTypeInfo =
4671 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy);
4672 Fields.push_back(PointeeTypeInfo);
4673
4674 // Itanium C++ ABI 2.9.5p9:
4675 // __context is a pointer to an abi::__class_type_info corresponding to the
4676 // class type containing the member pointed to
4677 // (e.g., the "A" in "int A::*").
4679 Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(T));
4680}
4681
4682llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) {
4683 return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty);
4684}
4685
4686void ItaniumCXXABI::EmitFundamentalRTTIDescriptors(const CXXRecordDecl *RD) {
4687 // Types added here must also be added to TypeInfoIsInStandardLibrary.
4688 QualType FundamentalTypes[] = {
4689 getContext().VoidTy, getContext().NullPtrTy,
4690 getContext().BoolTy, getContext().WCharTy,
4691 getContext().CharTy, getContext().UnsignedCharTy,
4692 getContext().SignedCharTy, getContext().ShortTy,
4693 getContext().UnsignedShortTy, getContext().IntTy,
4694 getContext().UnsignedIntTy, getContext().LongTy,
4695 getContext().UnsignedLongTy, getContext().LongLongTy,
4696 getContext().UnsignedLongLongTy, getContext().Int128Ty,
4697 getContext().UnsignedInt128Ty, getContext().HalfTy,
4698 getContext().FloatTy, getContext().DoubleTy,
4699 getContext().LongDoubleTy, getContext().Float128Ty,
4700 getContext().Char8Ty, getContext().Char16Ty,
4701 getContext().Char32Ty
4702 };
4703 llvm::GlobalValue::DLLStorageClassTypes DLLStorageClass =
4704 RD->hasAttr<DLLExportAttr>() || CGM.shouldMapVisibilityToDLLExport(RD)
4705 ? llvm::GlobalValue::DLLExportStorageClass
4706 : llvm::GlobalValue::DefaultStorageClass;
4707 llvm::GlobalValue::VisibilityTypes Visibility =
4709 for (const QualType &FundamentalType : FundamentalTypes) {
4710 QualType PointerType = getContext().getPointerType(FundamentalType);
4711 QualType PointerTypeConst = getContext().getPointerType(
4712 FundamentalType.withConst());
4713 for (QualType Type : {FundamentalType, PointerType, PointerTypeConst})
4714 ItaniumRTTIBuilder(*this).BuildTypeInfo(
4715 Type, llvm::GlobalValue::ExternalLinkage,
4716 Visibility, DLLStorageClass);
4717 }
4718}
4719
4720/// What sort of uniqueness rules should we use for the RTTI for the
4721/// given type?
4722ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness(
4723 QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const {
4724 if (shouldRTTIBeUnique())
4725 return RUK_Unique;
4726
4727 // It's only necessary for linkonce_odr or weak_odr linkage.
4728 if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage &&
4729 Linkage != llvm::GlobalValue::WeakODRLinkage)
4730 return RUK_Unique;
4731
4732 // It's only necessary with default visibility.
4733 if (CanTy->getVisibility() != DefaultVisibility)
4734 return RUK_Unique;
4735
4736 // If we're not required to publish this symbol, hide it.
4737 if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
4738 return RUK_NonUniqueHidden;
4739
4740 // If we're required to publish this symbol, as we might be under an
4741 // explicit instantiation, leave it with default visibility but
4742 // enable string-comparisons.
4743 assert(Linkage == llvm::GlobalValue::WeakODRLinkage);
4744 return RUK_NonUniqueVisible;
4745}
4746
4747// Find out how to codegen the complete destructor and constructor
4748namespace {
4749enum class StructorCodegen { Emit, RAUW, Alias, COMDAT };
4750}
4751static StructorCodegen getCodegenToUse(CodeGenModule &CGM,
4752 const CXXMethodDecl *MD) {
4753 if (!CGM.getCodeGenOpts().CXXCtorDtorAliases)
4754 return StructorCodegen::Emit;
4755
4756 // The complete and base structors are not equivalent if there are any virtual
4757 // bases, so emit separate functions.
4758 if (MD->getParent()->getNumVBases())
4759 return StructorCodegen::Emit;
4760
4762 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
4764 } else {
4765 const auto *CD = cast<CXXConstructorDecl>(MD);
4767 }
4768 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
4769
4770 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage))
4771 return StructorCodegen::RAUW;
4772
4773 // FIXME: Should we allow available_externally aliases?
4774 if (!llvm::GlobalAlias::isValidLinkage(Linkage))
4775 return StructorCodegen::RAUW;
4776
4777 if (llvm::GlobalValue::isWeakForLinker(Linkage)) {
4778 // Only ELF and wasm support COMDATs with arbitrary names (C5/D5).
4779 if (CGM.getTarget().getTriple().isOSBinFormatELF() ||
4780 CGM.getTarget().getTriple().isOSBinFormatWasm())
4781 return StructorCodegen::COMDAT;
4782 return StructorCodegen::Emit;
4783 }
4784
4785 return StructorCodegen::Alias;
4786}
4787
4790 GlobalDecl TargetDecl) {
4791 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
4792
4793 StringRef MangledName = CGM.getMangledName(AliasDecl);
4794 llvm::GlobalValue *Entry = CGM.GetGlobalValue(MangledName);
4795 if (Entry && !Entry->isDeclaration())
4796 return;
4797
4798 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(TargetDecl));
4799
4800 // Create the alias with no name.
4801 auto *Alias = llvm::GlobalAlias::create(Linkage, "", Aliasee);
4802
4803 // Constructors and destructors are always unnamed_addr.
4804 Alias->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4805
4806 // Switch any previous uses to the alias.
4807 if (Entry) {
4808 assert(Entry->getType() == Aliasee->getType() &&
4809 "declaration exists with different type");
4810 Alias->takeName(Entry);
4811 Entry->replaceAllUsesWith(Alias);
4812 Entry->eraseFromParent();
4813 } else {
4814 Alias->setName(MangledName);
4815 }
4816
4817 // Finally, set up the alias with its proper name and attributes.
4818 CGM.SetCommonAttributes(AliasDecl, Alias);
4819}
4820
4821void ItaniumCXXABI::emitCXXStructor(GlobalDecl GD) {
4822 auto *MD = cast<CXXMethodDecl>(GD.getDecl());
4823 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
4824 const CXXDestructorDecl *DD = CD ? nullptr : cast<CXXDestructorDecl>(MD);
4825
4826 StructorCodegen CGType = getCodegenToUse(CGM, MD);
4827
4828 if (CD ? GD.getCtorType() == Ctor_Complete
4829 : GD.getDtorType() == Dtor_Complete) {
4830 GlobalDecl BaseDecl;
4831 if (CD)
4832 BaseDecl = GD.getWithCtorType(Ctor_Base);
4833 else
4834 BaseDecl = GD.getWithDtorType(Dtor_Base);
4835
4836 if (CGType == StructorCodegen::Alias || CGType == StructorCodegen::COMDAT) {
4837 emitConstructorDestructorAlias(CGM, GD, BaseDecl);
4838 return;
4839 }
4840
4841 if (CGType == StructorCodegen::RAUW) {
4842 StringRef MangledName = CGM.getMangledName(GD);
4843 auto *Aliasee = CGM.GetAddrOfGlobal(BaseDecl);
4844 CGM.addReplacement(MangledName, Aliasee);
4845 return;
4846 }
4847 }
4848
4849 // The base destructor is equivalent to the base destructor of its
4850 // base class if there is exactly one non-virtual base class with a
4851 // non-trivial destructor, there are no fields with a non-trivial
4852 // destructor, and the body of the destructor is trivial.
4853 if (DD && GD.getDtorType() == Dtor_Base &&
4854 CGType != StructorCodegen::COMDAT &&
4856 return;
4857
4858 // FIXME: The deleting destructor is equivalent to the selected operator
4859 // delete if:
4860 // * either the delete is a destroying operator delete or the destructor
4861 // would be trivial if it weren't virtual,
4862 // * the conversion from the 'this' parameter to the first parameter of the
4863 // destructor is equivalent to a bitcast,
4864 // * the destructor does not have an implicit "this" return, and
4865 // * the operator delete has the same calling convention and IR function type
4866 // as the destructor.
4867 // In such cases we should try to emit the deleting dtor as an alias to the
4868 // selected 'operator delete'.
4869
4870 llvm::Function *Fn = CGM.codegenCXXStructor(GD);
4871
4872 if (CGType == StructorCodegen::COMDAT) {
4873 SmallString<256> Buffer;
4874 llvm::raw_svector_ostream Out(Buffer);
4875 if (DD)
4876 getMangleContext().mangleCXXDtorComdat(DD, Out);
4877 else
4878 getMangleContext().mangleCXXCtorComdat(CD, Out);
4879 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(Out.str());
4880 Fn->setComdat(C);
4881 } else {
4882 CGM.maybeSetTrivialComdat(*MD, *Fn);
4883 }
4884}
4885
4886static llvm::FunctionCallee getBeginCatchFn(CodeGenModule &CGM) {
4887 // void *__cxa_begin_catch(void*);
4888 llvm::FunctionType *FTy = llvm::FunctionType::get(
4889 CGM.Int8PtrTy, CGM.Int8PtrTy, /*isVarArg=*/false);
4890
4891 return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
4892}
4893
4894static llvm::FunctionCallee getEndCatchFn(CodeGenModule &CGM) {
4895 // void __cxa_end_catch();
4896 llvm::FunctionType *FTy =
4897 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
4898
4899 return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
4900}
4901
4902static llvm::FunctionCallee getGetExceptionPtrFn(CodeGenModule &CGM) {
4903 // void *__cxa_get_exception_ptr(void*);
4904 llvm::FunctionType *FTy = llvm::FunctionType::get(
4905 CGM.Int8PtrTy, CGM.Int8PtrTy, /*isVarArg=*/false);
4906
4907 return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
4908}
4909
4910namespace {
4911 /// A cleanup to call __cxa_end_catch. In many cases, the caught
4912 /// exception type lets us state definitively that the thrown exception
4913 /// type does not have a destructor. In particular:
4914 /// - Catch-alls tell us nothing, so we have to conservatively
4915 /// assume that the thrown exception might have a destructor.
4916 /// - Catches by reference behave according to their base types.
4917 /// - Catches of non-record types will only trigger for exceptions
4918 /// of non-record types, which never have destructors.
4919 /// - Catches of record types can trigger for arbitrary subclasses
4920 /// of the caught type, so we have to assume the actual thrown
4921 /// exception type might have a throwing destructor, even if the
4922 /// caught type's destructor is trivial or nothrow.
4923 struct CallEndCatch final : EHScopeStack::Cleanup {
4924 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
4925 bool MightThrow;
4926
4927 void Emit(CodeGenFunction &CGF, Flags flags) override {
4928 if (!MightThrow) {
4930 return;
4931 }
4932
4934 }
4935 };
4936}
4937
4938/// Emits a call to __cxa_begin_catch and enters a cleanup to call
4939/// __cxa_end_catch. If -fassume-nothrow-exception-dtor is specified, we assume
4940/// that the exception object's dtor is nothrow, therefore the __cxa_end_catch
4941/// call can be marked as nounwind even if EndMightThrow is true.
4942///
4943/// \param EndMightThrow - true if __cxa_end_catch might throw
4944static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
4945 llvm::Value *Exn,
4946 bool EndMightThrow) {
4947 llvm::CallInst *call =
4949
4950 CGF.EHStack.pushCleanup<CallEndCatch>(
4952 EndMightThrow && !CGF.CGM.getLangOpts().AssumeNothrowExceptionDtor);
4953
4954 return call;
4955}
4956
4957/// A "special initializer" callback for initializing a catch
4958/// parameter during catch initialization.
4960 const VarDecl &CatchParam,
4961 Address ParamAddr,
4962 SourceLocation Loc) {
4963 // Load the exception from where the landing pad saved it.
4964 llvm::Value *Exn = CGF.getExceptionFromSlot();
4965
4966 CanQualType CatchType =
4967 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
4968 llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
4969
4970 // If we're catching by reference, we can just cast the object
4971 // pointer to the appropriate pointer.
4972 if (isa<ReferenceType>(CatchType)) {
4973 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
4974 bool EndCatchMightThrow = CaughtType->isRecordType();
4975
4976 // __cxa_begin_catch returns the adjusted object pointer.
4977 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
4978
4979 // We have no way to tell the personality function that we're
4980 // catching by reference, so if we're catching a pointer,
4981 // __cxa_begin_catch will actually return that pointer by value.
4982 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
4983 QualType PointeeType = PT->getPointeeType();
4984
4985 // When catching by reference, generally we should just ignore
4986 // this by-value pointer and use the exception object instead.
4987 if (!PointeeType->isRecordType()) {
4988
4989 // Exn points to the struct _Unwind_Exception header, which
4990 // we have to skip past in order to reach the exception data.
4991 unsigned HeaderSize =
4993 AdjustedExn =
4994 CGF.Builder.CreateConstGEP1_32(CGF.Int8Ty, Exn, HeaderSize);
4995
4996 // However, if we're catching a pointer-to-record type that won't
4997 // work, because the personality function might have adjusted
4998 // the pointer. There's actually no way for us to fully satisfy
4999 // the language/ABI contract here: we can't use Exn because it
5000 // might have the wrong adjustment, but we can't use the by-value
5001 // pointer because it's off by a level of abstraction.
5002 //
5003 // The current solution is to dump the adjusted pointer into an
5004 // alloca, which breaks language semantics (because changing the
5005 // pointer doesn't change the exception) but at least works.
5006 // The better solution would be to filter out non-exact matches
5007 // and rethrow them, but this is tricky because the rethrow
5008 // really needs to be catchable by other sites at this landing
5009 // pad. The best solution is to fix the personality function.
5010 } else {
5011 // Pull the pointer for the reference type off.
5012 llvm::Type *PtrTy = CGF.ConvertTypeForMem(CaughtType);
5013
5014 // Create the temporary and write the adjusted pointer into it.
5015 Address ExnPtrTmp =
5016 CGF.CreateTempAlloca(PtrTy, CGF.getPointerAlign(), "exn.byref.tmp");
5017 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
5018 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
5019
5020 // Bind the reference to the temporary.
5021 AdjustedExn = ExnPtrTmp.emitRawPointer(CGF);
5022 }
5023 }
5024
5025 llvm::Value *ExnCast =
5026 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
5027 CGF.Builder.CreateStore(ExnCast, ParamAddr);
5028 return;
5029 }
5030
5031 // Scalars and complexes.
5032 TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType);
5033 if (TEK != TEK_Aggregate) {
5034 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
5035
5036 // If the catch type is a pointer type, __cxa_begin_catch returns
5037 // the pointer by value.
5038 if (CatchType->hasPointerRepresentation()) {
5039 llvm::Value *CastExn =
5040 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
5041
5042 switch (CatchType.getQualifiers().getObjCLifetime()) {
5044 CastExn = CGF.EmitARCRetainNonBlock(CastExn);
5045 [[fallthrough]];
5046
5050 CGF.Builder.CreateStore(CastExn, ParamAddr);
5051 return;
5052
5054 CGF.EmitARCInitWeak(ParamAddr, CastExn);
5055 return;
5056 }
5057 llvm_unreachable("bad ownership qualifier!");
5058 }
5059
5060 // Otherwise, it returns a pointer into the exception object.
5061
5062 LValue srcLV = CGF.MakeNaturalAlignAddrLValue(AdjustedExn, CatchType);
5063 LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType);
5064 switch (TEK) {
5065 case TEK_Complex:
5066 CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV,
5067 /*init*/ true);
5068 return;
5069 case TEK_Scalar: {
5070 llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc);
5071 CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true);
5072 return;
5073 }
5074 case TEK_Aggregate:
5075 llvm_unreachable("evaluation kind filtered out!");
5076 }
5077 llvm_unreachable("bad evaluation kind");
5078 }
5079
5080 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
5081 auto catchRD = CatchType->getAsCXXRecordDecl();
5082 CharUnits caughtExnAlignment = CGF.CGM.getClassPointerAlignment(catchRD);
5083
5084 llvm::Type *PtrTy = CGF.DefaultPtrTy;
5085
5086 // Check for a copy expression. If we don't have a copy expression,
5087 // that means a trivial copy is okay.
5088 const Expr *copyExpr = CatchParam.getInit();
5089 if (!copyExpr) {
5090 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
5091 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
5092 LLVMCatchTy, caughtExnAlignment);
5093 LValue Dest = CGF.MakeAddrLValue(ParamAddr, CatchType);
5094 LValue Src = CGF.MakeAddrLValue(adjustedExn, CatchType);
5095 CGF.EmitAggregateCopy(Dest, Src, CatchType, AggValueSlot::DoesNotOverlap);
5096 return;
5097 }
5098
5099 // We have to call __cxa_get_exception_ptr to get the adjusted
5100 // pointer before copying.
5101 llvm::CallInst *rawAdjustedExn =
5103
5104 // Cast that to the appropriate type.
5105 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
5106 LLVMCatchTy, caughtExnAlignment);
5107
5108 // The copy expression is defined in terms of an OpaqueValueExpr.
5109 // Find it and map it to the adjusted expression.
5111 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
5112 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
5113
5114 // Call the copy ctor in a terminate scope.
5115 CGF.EHStack.pushTerminate();
5116
5117 // Perform the copy construction.
5118 CGF.EmitAggExpr(copyExpr,
5119 AggValueSlot::forAddr(ParamAddr, Qualifiers(),
5124
5125 // Leave the terminate scope.
5126 CGF.EHStack.popTerminate();
5127
5128 // Undo the opaque value mapping.
5129 opaque.pop();
5130
5131 // Finally we can call __cxa_begin_catch.
5132 CallBeginCatch(CGF, Exn, true);
5133}
5134
5135/// Begins a catch statement by initializing the catch variable and
5136/// calling __cxa_begin_catch.
5137void ItaniumCXXABI::emitBeginCatch(CodeGenFunction &CGF,
5138 const CXXCatchStmt *S) {
5139 // We have to be very careful with the ordering of cleanups here:
5140 // C++ [except.throw]p4:
5141 // The destruction [of the exception temporary] occurs
5142 // immediately after the destruction of the object declared in
5143 // the exception-declaration in the handler.
5144 //
5145 // So the precise ordering is:
5146 // 1. Construct catch variable.
5147 // 2. __cxa_begin_catch
5148 // 3. Enter __cxa_end_catch cleanup
5149 // 4. Enter dtor cleanup
5150 //
5151 // We do this by using a slightly abnormal initialization process.
5152 // Delegation sequence:
5153 // - ExitCXXTryStmt opens a RunCleanupsScope
5154 // - EmitAutoVarAlloca creates the variable and debug info
5155 // - InitCatchParam initializes the variable from the exception
5156 // - CallBeginCatch calls __cxa_begin_catch
5157 // - CallBeginCatch enters the __cxa_end_catch cleanup
5158 // - EmitAutoVarCleanups enters the variable destructor cleanup
5159 // - EmitCXXTryStmt emits the code for the catch body
5160 // - EmitCXXTryStmt close the RunCleanupsScope
5161
5162 VarDecl *CatchParam = S->getExceptionDecl();
5163 if (!CatchParam) {
5164 llvm::Value *Exn = CGF.getExceptionFromSlot();
5165 CallBeginCatch(CGF, Exn, true);
5166 return;
5167 }
5168
5169 // Emit the local.
5170 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
5171 {
5172 ApplyAtomGroup Grp(CGF.getDebugInfo());
5173 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF),
5174 S->getBeginLoc());
5175 }
5176 CGF.EmitAutoVarCleanups(var);
5177}
5178
5179/// Get or define the following function:
5180/// void @__clang_call_terminate(i8* %exn) nounwind noreturn
5181/// This code is used only in C++.
5182static llvm::FunctionCallee getClangCallTerminateFn(CodeGenModule &CGM) {
5183 ASTContext &C = CGM.getContext();
5185 C.VoidTy, {C.getPointerType(C.CharTy)});
5186 llvm::FunctionType *fnTy = CGM.getTypes().GetFunctionType(FI);
5187 llvm::FunctionCallee fnRef = CGM.CreateRuntimeFunction(
5188 fnTy, "__clang_call_terminate", llvm::AttributeList(), /*Local=*/true);
5189 llvm::Function *fn =
5190 cast<llvm::Function>(fnRef.getCallee()->stripPointerCasts());
5191 if (fn->empty()) {
5192 CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, fn, /*IsThunk=*/false);
5194 fn->setDoesNotThrow();
5195 fn->setDoesNotReturn();
5196
5197 // What we really want is to massively penalize inlining without
5198 // forbidding it completely. The difference between that and
5199 // 'noinline' is negligible.
5200 fn->addFnAttr(llvm::Attribute::NoInline);
5201
5202 // Allow this function to be shared across translation units, but
5203 // we don't want it to turn into an exported symbol.
5204 fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
5205 fn->setVisibility(llvm::Function::HiddenVisibility);
5206 if (CGM.supportsCOMDAT())
5207 fn->setComdat(CGM.getModule().getOrInsertComdat(fn->getName()));
5208
5209 // Set up the function.
5210 llvm::BasicBlock *entry =
5211 llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn);
5212 CGBuilderTy builder(CGM, entry);
5213
5214 // Pull the exception pointer out of the parameter list.
5215 llvm::Value *exn = &*fn->arg_begin();
5216
5217 // Call __cxa_begin_catch(exn).
5218 llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn);
5219 catchCall->setDoesNotThrow();
5220 catchCall->setCallingConv(CGM.getRuntimeCC());
5221
5222 // Call std::terminate().
5223 llvm::CallInst *termCall = builder.CreateCall(CGM.getTerminateFn());
5224 termCall->setDoesNotThrow();
5225 termCall->setDoesNotReturn();
5226 termCall->setCallingConv(CGM.getRuntimeCC());
5227
5228 // std::terminate cannot return.
5229 builder.CreateUnreachable();
5230 }
5231 return fnRef;
5232}
5233
5234llvm::CallInst *
5235ItaniumCXXABI::emitTerminateForUnexpectedException(CodeGenFunction &CGF,
5236 llvm::Value *Exn) {
5237 // In C++, we want to call __cxa_begin_catch() before terminating.
5238 if (Exn) {
5239 assert(CGF.CGM.getLangOpts().CPlusPlus);
5241 }
5242 return CGF.EmitNounwindRuntimeCall(CGF.CGM.getTerminateFn());
5243}
5244
5245std::pair<llvm::Value *, const CXXRecordDecl *>
5246ItaniumCXXABI::LoadVTablePtr(CodeGenFunction &CGF, Address This,
5247 const CXXRecordDecl *RD) {
5248 return {CGF.GetVTablePtr(This, CGM.Int8PtrTy, RD), RD};
5249}
5250
5251llvm::Constant *
5252ItaniumCXXABI::getSignedVirtualMemberFunctionPointer(const CXXMethodDecl *MD) {
5253 const CXXMethodDecl *origMD =
5256 .getDecl());
5257 llvm::Constant *thunk = getOrCreateVirtualFunctionPointerThunk(origMD);
5258 QualType funcType = CGM.getContext().getMemberPointerType(
5259 MD->getType(), /*Qualifier=*/std::nullopt, MD->getParent());
5260 return CGM.getMemberFunctionPointer(thunk, funcType);
5261}
5262
5263void WebAssemblyCXXABI::emitBeginCatch(CodeGenFunction &CGF,
5264 const CXXCatchStmt *C) {
5265 if (CGF.getTarget().hasFeature("exception-handling"))
5266 CGF.EHStack.pushCleanup<CatchRetScope>(
5268 ItaniumCXXABI::emitBeginCatch(CGF, C);
5269}
5270
5271llvm::CallInst *
5272WebAssemblyCXXABI::emitTerminateForUnexpectedException(CodeGenFunction &CGF,
5273 llvm::Value *Exn) {
5274 // Itanium ABI calls __clang_call_terminate(), which __cxa_begin_catch() on
5275 // the violating exception to mark it handled, but it is currently hard to do
5276 // with wasm EH instruction structure with catch/catch_all, we just call
5277 // std::terminate and ignore the violating exception as in CGCXXABI in Wasm EH
5278 // and call __clang_call_terminate only in Emscripten EH.
5279 // TODO Consider code transformation that makes calling __clang_call_terminate
5280 // in Wasm EH possible.
5281 if (Exn && !EHPersonality::get(CGF).isWasmPersonality()) {
5282 assert(CGF.CGM.getLangOpts().CPlusPlus);
5284 }
5286}
5287
5288/// Register a global destructor as best as we know how.
5289void XLCXXABI::registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
5290 llvm::FunctionCallee Dtor,
5291 llvm::Constant *Addr) {
5292 if (D.getTLSKind() != VarDecl::TLS_None) {
5293 llvm::PointerType *PtrTy = CGF.DefaultPtrTy;
5294
5295 // extern "C" int __pt_atexit_np(int flags, int(*)(int,...), ...);
5296 llvm::FunctionType *AtExitTy =
5297 llvm::FunctionType::get(CGM.IntTy, {CGM.IntTy, PtrTy}, true);
5298
5299 // Fetch the actual function.
5300 llvm::FunctionCallee AtExit =
5301 CGM.CreateRuntimeFunction(AtExitTy, "__pt_atexit_np");
5302
5303 // Create __dtor function for the var decl.
5304 llvm::Function *DtorStub = CGF.createTLSAtExitStub(D, Dtor, Addr, AtExit);
5305
5306 // Register above __dtor with atexit().
5307 // First param is flags and must be 0, second param is function ptr
5308 llvm::Value *NV = llvm::Constant::getNullValue(CGM.IntTy);
5309 CGF.EmitNounwindRuntimeCall(AtExit, {NV, DtorStub});
5310
5311 // Cannot unregister TLS __dtor so done
5312 return;
5313 }
5314
5315 // Create __dtor function for the var decl.
5316 llvm::Function *DtorStub =
5318
5319 // Register above __dtor with atexit().
5320 CGF.registerGlobalDtorWithAtExit(DtorStub);
5321
5322 // Emit __finalize function to unregister __dtor and (as appropriate) call
5323 // __dtor.
5324 emitCXXStermFinalizer(D, DtorStub, Addr);
5325}
5326
5327void XLCXXABI::emitCXXStermFinalizer(const VarDecl &D, llvm::Function *dtorStub,
5328 llvm::Constant *addr) {
5329 llvm::FunctionType *FTy = llvm::FunctionType::get(CGM.VoidTy, false);
5330 SmallString<256> FnName;
5331 {
5332 llvm::raw_svector_ostream Out(FnName);
5333 getMangleContext().mangleDynamicStermFinalizer(&D, Out);
5334 }
5335
5336 // Create the finalization action associated with a variable.
5337 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
5338 llvm::Function *StermFinalizer = CGM.CreateGlobalInitOrCleanUpFunction(
5339 FTy, FnName.str(), FI, D.getLocation());
5340
5341 CodeGenFunction CGF(CGM);
5342
5343 CGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, StermFinalizer, FI,
5344 FunctionArgList(), D.getLocation(),
5345 D.getInit()->getExprLoc());
5346
5347 // The unatexit subroutine unregisters __dtor functions that were previously
5348 // registered by the atexit subroutine. If the referenced function is found,
5349 // the unatexit returns a value of 0, meaning that the cleanup is still
5350 // pending (and we should call the __dtor function).
5351 llvm::Value *V = CGF.unregisterGlobalDtorWithUnAtExit(dtorStub);
5352
5353 llvm::Value *NeedsDestruct = CGF.Builder.CreateIsNull(V, "needs_destruct");
5354
5355 llvm::BasicBlock *DestructCallBlock = CGF.createBasicBlock("destruct.call");
5356 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("destruct.end");
5357
5358 // Check if unatexit returns a value of 0. If it does, jump to
5359 // DestructCallBlock, otherwise jump to EndBlock directly.
5360 CGF.Builder.CreateCondBr(NeedsDestruct, DestructCallBlock, EndBlock);
5361
5362 CGF.EmitBlock(DestructCallBlock);
5363
5364 // Emit the call to dtorStub.
5365 llvm::CallInst *CI = CGF.Builder.CreateCall(dtorStub);
5366
5367 // Make sure the call and the callee agree on calling convention.
5368 CI->setCallingConv(dtorStub->getCallingConv());
5369
5370 CGF.EmitBlock(EndBlock);
5371
5372 CGF.FinishFunction();
5373
5374 if (auto *IPA = D.getAttr<InitPriorityAttr>()) {
5375 CGM.AddCXXPrioritizedStermFinalizerEntry(StermFinalizer,
5376 IPA->getPriority());
5378 getContext().GetGVALinkageForVariable(&D) == GVA_DiscardableODR) {
5379 // According to C++ [basic.start.init]p2, class template static data
5380 // members (i.e., implicitly or explicitly instantiated specializations)
5381 // have unordered initialization. As a consequence, we can put them into
5382 // their own llvm.global_dtors entry.
5383 CGM.AddCXXStermFinalizerToGlobalDtor(StermFinalizer, 65535);
5384 } else {
5385 CGM.AddCXXStermFinalizerEntry(StermFinalizer);
5386 }
5387}
#define V(N, I)
static void emitConstructorDestructorAlias(CIRGenModule &cgm, GlobalDecl aliasDecl, GlobalDecl targetDecl)
static CharUnits computeOffsetHint(ASTContext &astContext, const CXXRecordDecl *src, const CXXRecordDecl *dst)
static Address emitDynamicCastToVoid(CIRGenFunction &cgf, mlir::Location loc, QualType srcRecordTy, Address src)
static cir::GlobalLinkageKind getTypeInfoLinkage(CIRGenModule &cgm, QualType ty)
Return the linkage that the type info and type info name constants should have for the given type.
static mlir::Value performTypeAdjustment(CIRGenFunction &cgf, Address initialPtr, const CXXRecordDecl *unadjustedClass, int64_t nonVirtualAdjustment, int64_t virtualAdjustment, bool isReturnAdjustment)
static mlir::Value emitExactDynamicCast(CIRGenItaniumCXXABI &abi, CIRGenFunction &cgf, mlir::Location loc, QualType srcRecordTy, QualType destRecordTy, cir::PointerType destCIRTy, bool isRefCast, Address src)
static cir::FuncOp getItaniumDynamicCastFn(CIRGenFunction &cgf)
static cir::FuncOp getBadCastFn(CIRGenFunction &cgf)
static RValue performReturnAdjustment(CIRGenFunction &cgf, QualType resultType, RValue rv, const ThunkInfo &thunk)
static StructorCodegen getCodegenToUse(CodeGenModule &CGM, const CXXMethodDecl *MD)
static llvm::FunctionCallee getClangCallTerminateFn(CodeGenModule &CGM)
Get or define the following function: void @__clang_call_terminate(i8* exn) nounwind noreturn This co...
static bool CXXRecordNonInlineHasAttr(const CXXRecordDecl *RD)
static unsigned extractPBaseFlags(ASTContext &Ctx, QualType &Type)
Compute the flags for a __pbase_type_info, and remove the corresponding pieces from Type.
static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM, QualType Ty)
ShouldUseExternalRTTIDescriptor - Returns whether the type information for the given type exists some...
static bool IsIncompleteClassType(const RecordType *RecordTy)
IsIncompleteClassType - Returns whether the given record type is incomplete.
static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base, SeenBases &Bases)
ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in abi::__vmi_class_type_info.
static llvm::FunctionCallee getBadTypeidFn(CodeGenFunction &CGF)
static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF, llvm::FunctionCallee dtor, llvm::Constant *addr, bool TLS)
Register a global destructor using __cxa_atexit.
static llvm::FunctionCallee getBeginCatchFn(CodeGenModule &CGM)
static llvm::Constant * pointerAuthResignMemberFunctionPointer(llvm::Constant *Src, QualType DestType, QualType SrcType, CodeGenModule &CGM)
static llvm::FunctionCallee getGuardReleaseFn(CodeGenModule &CGM, llvm::PointerType *GuardPtrTy)
static llvm::Function * createGlobalInitOrCleanupFn(CodeGen::CodeGenModule &CGM, StringRef FnName)
static llvm::FunctionCallee getAllocateExceptionFn(CodeGenModule &CGM)
static bool IsStandardLibraryRTTIDescriptor(QualType Ty)
IsStandardLibraryRTTIDescriptor - Returns whether the type information for the given type exists in t...
static llvm::Value * CallBeginCatch(CodeGenFunction &CGF, llvm::Value *Exn, bool EndMightThrow)
Emits a call to __cxa_begin_catch and enters a cleanup to call __cxa_end_catch.
static llvm::FunctionCallee getGuardAbortFn(CodeGenModule &CGM, llvm::PointerType *GuardPtrTy)
static bool isThreadWrapperReplaceable(const VarDecl *VD, CodeGen::CodeGenModule &CGM)
static void InitCatchParam(CodeGenFunction &CGF, const VarDecl &CatchParam, Address ParamAddr, SourceLocation Loc)
A "special initializer" callback for initializing a catch parameter during catch initialization.
static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty)
TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type info for that type is de...
static bool CanUseSingleInheritance(const CXXRecordDecl *RD)
static llvm::FunctionCallee getEndCatchFn(CodeGenModule &CGM)
static llvm::GlobalValue::LinkageTypes getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM)
Get the appropriate linkage for the wrapper function.
static llvm::FunctionCallee getThrowFn(CodeGenModule &CGM)
static void setVTableSelectiveDLLImportExport(CodeGenModule &CGM, llvm::GlobalVariable *VTable, const CXXRecordDecl *RD)
static llvm::FunctionCallee getGuardAcquireFn(CodeGenModule &CGM, llvm::PointerType *GuardPtrTy)
static bool ContainsIncompleteClassType(QualType Ty)
ContainsIncompleteClassType - Returns whether the given type contains an incomplete class type.
static llvm::Constant * pointerAuthResignConstant(llvm::Value *Ptr, const CGPointerAuthInfo &CurAuthInfo, const CGPointerAuthInfo &NewAuthInfo, CodeGenModule &CGM)
static llvm::FunctionCallee getGetExceptionPtrFn(CodeGenModule &CGM)
static void dtorTy(Block *, std::byte *Ptr, const Descriptor *)
llvm::MachO::Record Record
Definition MachO.h:31
static uint64_t getFieldOffset(const ASTContext &C, const FieldDecl *FD)
static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D)
Determine what kind of template specialization the given declaration is.
static QualType getPointeeType(const MemRegion *R)
#define CXXABI(Name, Str)
C Language Family Type Representation.
a trap message and trap category.
const ValueDecl * getMemberPointerDecl() const
Definition APValue.cpp:1098
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:226
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
CanQualType LongTy
QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl, ObjCInterfaceDecl *PrevDecl=nullptr) const
getObjCInterfaceType - Return the unique reference to the type for the specified ObjC interface decl.
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
CanQualType VoidPtrTy
IdentifierTable & Idents
Definition ASTContext.h:797
QualType getFunctionTypeWithExceptionSpec(QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const
Get a function type and produce the equivalent function type with the specified exception specificati...
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
CanQualType CharTy
CanQualType IntTy
CharUnits getExnObjectAlignment() const
Return the alignment (in bytes) of the thrown exception object.
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
CharUnits getPreferredTypeAlignInChars(QualType T) const
Return the PreferredAlignment of a (complete) type T, in characters.
CanQualType VoidTy
CanQualType UnsignedIntTy
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
QualType getMemberPointerType(QualType T, NestedNameSpecifier Qualifier, const CXXRecordDecl *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:916
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
TargetCXXABI::Kind getCXXABIKind() const
Return the C++ ABI kind that should be used.
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
CanQualType LongLongTy
CanQualType getCanonicalTagType(const TagDecl *TD) const
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
CharUnits getVBaseClassOffset(const CXXRecordDecl *VBase) const
getVBaseClassOffset - Get the offset, in chars, for the given base class.
This class is used for builtin types like 'int'.
Definition TypeBase.h:3172
Kind getKind() const
Definition TypeBase.h:3220
Represents a path from a specific derived class (which is not represented as part of the path) to a p...
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
Represents a base class of a C++ class.
Definition DeclCXX.h:146
QualType getType() const
Retrieves the type of the base class.
Definition DeclCXX.h:249
SourceLocation getBeginLoc() const LLVM_READONLY
Definition StmtCXX.h:43
VarDecl * getExceptionDecl() const
Definition StmtCXX.h:49
FunctionDecl * getOperatorDelete() const
Definition ExprCXX.h:2666
bool isGlobalDelete() const
Definition ExprCXX.h:2652
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2136
bool isVirtual() const
Definition DeclCXX.h:2191
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2262
bool isInstance() const
Definition DeclCXX.h:2163
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2232
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition DeclCXX.h:1372
base_class_range bases()
Definition DeclCXX.h:608
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition DeclCXX.h:602
base_class_iterator bases_begin()
Definition DeclCXX.h:615
const CXXBaseSpecifier * base_class_const_iterator
Iterator that traverses the base classes of a class.
Definition DeclCXX.h:520
base_class_range vbases()
Definition DeclCXX.h:625
bool isAbstract() const
Determine whether this class has a pure virtual function.
Definition DeclCXX.h:1221
bool isDynamicClass() const
Definition DeclCXX.h:574
bool hasDefinition() const
Definition DeclCXX.h:561
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition DeclCXX.h:623
bool isDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is derived from the class Base.
const Expr * getSubExpr() const
Definition ExprCXX.h:1229
static CanQual< Type > CreateUnsafe(QualType Other)
Qualifiers getQualifiers() const
Retrieve all qualifiers.
CastKind getCastKind() const
Definition Expr.h:3723
Expr * getSubExpr()
Definition Expr.h:3729
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
int64_t QuantityType
Definition CharUnits.h:40
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition CharUnits.h:122
llvm::Align getAsAlign() const
getAsAlign - Returns Quantity as a valid llvm::Align, Beware llvm::Align assumes power of two 8-bit b...
Definition CharUnits.h:189
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
static CharUnits One()
One - Construct a CharUnits quantity of one.
Definition CharUnits.h:58
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:63
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition CharUnits.h:53
PointerAuthOptions PointerAuth
Configuration for pointer-signing.
std::string SymbolPartition
The name of the partition that symbols are assigned to, specified with -fsymbol-partition (see https:...
static ABIArgInfo getIndirect(CharUnits Alignment, unsigned AddrSpace, bool ByVal=true, bool Realign=false, llvm::Type *Padding=nullptr)
Like RawAddress, an abstract representation of an aligned address, but the pointer contained in this ...
Definition Address.h:128
llvm::Value * emitRawPointer(CodeGenFunction &CGF) const
Return the pointer contained in this class after authenticating it and adding offset to it if necessa...
Definition Address.h:253
CharUnits getAlignment() const
Definition Address.h:194
llvm::Type * getElementType() const
Return the type of the values stored in this address.
Definition Address.h:209
Address withElementType(llvm::Type *ElemTy) const
Return address with different element type, but same pointer and alignment.
Definition Address.h:276
unsigned getAddressSpace() const
Return the address space that this address resides in.
Definition Address.h:215
llvm::PointerType * getType() const
Return the type of the pointer value.
Definition Address.h:204
static AggValueSlot forAddr(Address addr, Qualifiers quals, IsDestructed_t isDestructed, NeedsGCBarriers_t needsGC, IsAliased_t isAliased, Overlap_t mayOverlap, IsZeroed_t isZeroed=IsNotZeroed, IsSanitizerChecked_t isChecked=IsNotSanitizerChecked)
forAddr - Make a slot for an aggregate value.
Definition CGValue.h:634
static ApplyDebugLocation CreateArtificial(CodeGenFunction &CGF)
Apply TemporaryLocation if it is valid.
llvm::StoreInst * CreateStore(llvm::Value *Val, Address Addr, bool IsVolatile=false)
Definition CGBuilder.h:146
Address CreateConstInBoundsByteGEP(Address Addr, CharUnits Offset, const llvm::Twine &Name="")
Given a pointer to i8, adjust it by a given constant offset.
Definition CGBuilder.h:315
llvm::Value * CreateIsNull(Address Addr, const Twine &Name="")
Definition CGBuilder.h:366
Address CreateGEP(CodeGenFunction &CGF, Address Addr, llvm::Value *Index, const llvm::Twine &Name="")
Definition CGBuilder.h:302
Address CreatePointerBitCastOrAddrSpaceCast(Address Addr, llvm::Type *Ty, llvm::Type *ElementTy, const llvm::Twine &Name="")
Definition CGBuilder.h:213
llvm::LoadInst * CreateLoad(Address Addr, const llvm::Twine &Name="")
Definition CGBuilder.h:118
llvm::LoadInst * CreateAlignedLoad(llvm::Type *Ty, llvm::Value *Addr, CharUnits Align, const llvm::Twine &Name="")
Definition CGBuilder.h:138
Address CreateConstInBoundsGEP(Address Addr, uint64_t Index, const llvm::Twine &Name="")
Given addr = T* ... produce name = getelementptr inbounds addr, i64 index where i64 is actually the t...
Definition CGBuilder.h:271
Address CreateInBoundsGEP(Address Addr, ArrayRef< llvm::Value * > IdxList, llvm::Type *ElementType, CharUnits Align, const Twine &Name="")
Definition CGBuilder.h:356
Implements C++ ABI-specific code generation functions.
Definition CGCXXABI.h:43
virtual llvm::CallInst * emitTerminateForUnexpectedException(CodeGenFunction &CGF, llvm::Value *Exn)
Definition CGCXXABI.cpp:340
MangleContext & getMangleContext()
Gets the mangle context.
Definition CGCXXABI.h:113
All available information about a concrete callee.
Definition CGCall.h:63
static CGCallee forVirtual(const CallExpr *CE, GlobalDecl MD, Address Addr, llvm::FunctionType *FTy)
Definition CGCall.h:147
static CGCallee forDirect(llvm::Constant *functionPtr, const CGCalleeInfo &abstractInfo=CGCalleeInfo())
Definition CGCall.h:137
CGFunctionInfo - Class to encapsulate the information about a function definition.
CanQualType getReturnType() const
llvm::Value * getDiscriminator() const
An RAII object to set (and then clear) a mapping for an OpaqueValueExpr.
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
llvm::Value * GetVTablePtr(Address This, llvm::Type *VTableTy, const CXXRecordDecl *VTableClass, VTableAuthMode AuthMode=VTableAuthMode::Authenticate)
GetVTablePtr - Return the Value of the vtable pointer member pointed to by This.
Definition CGClass.cpp:2838
GlobalDecl CurGD
CurGD - The GlobalDecl for the current function being compiled.
llvm::Constant * createAtExitStub(const VarDecl &VD, llvm::FunctionCallee Dtor, llvm::Constant *Addr)
Create a stub function, suitable for being passed to atexit, which passes the given address to the gi...
llvm::Function * createTLSAtExitStub(const VarDecl &VD, llvm::FunctionCallee Dtor, llvm::Constant *Addr, llvm::FunctionCallee &AtExit)
Create a stub function, suitable for being passed to __pt_atexit_np, which passes the given address t...
SanitizerSet SanOpts
Sanitizers enabled for this function.
void EmitARCInitWeak(Address addr, llvm::Value *value)
i8* @objc_initWeak(i8** addr, i8* value) Returns value.
Definition CGObjC.cpp:2663
llvm::Value * getExceptionFromSlot()
Returns the contents of the function's exception object and selector slots.
llvm::Type * ConvertType(QualType T)
void EmitNoreturnRuntimeCallOrInvoke(llvm::FunctionCallee callee, ArrayRef< llvm::Value * > args)
Emits a call or invoke to the given noreturn runtime function.
Definition CGCall.cpp:5159
llvm::CallBase * EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee, ArrayRef< llvm::Value * > args, const Twine &name="")
Emits a call or invoke instruction to the given runtime function.
Definition CGCall.cpp:5186
ComplexPairTy EmitLoadOfComplex(LValue src, SourceLocation loc)
EmitLoadOfComplex - Load a complex number from the specified l-value.
bool CurFuncIsThunk
In C++, whether we are code generating a thunk.
void registerGlobalDtorWithAtExit(const VarDecl &D, llvm::FunctionCallee fn, llvm::Constant *addr)
Call atexit() with a function that passes the given argument to the given function.
llvm::Constant * EmitCheckSourceLocation(SourceLocation Loc)
Emit a description of a source location in a format suitable for passing to a runtime sanitizer handl...
Definition CGExpr.cpp:3973
llvm::Value * getAsNaturalPointerTo(Address Addr, QualType PointeeType)
void EmitDelegateCallArg(CallArgList &args, const VarDecl *param, SourceLocation loc)
EmitDelegateCallArg - We are performing a delegate call; that is, the current function is delegating ...
Definition CGCall.cpp:4392
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
const LangOptions & getLangOpts() const
LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
AutoVarEmission EmitAutoVarAlloca(const VarDecl &var)
EmitAutoVarAlloca - Emit the alloca and debug information for a local variable.
Definition CGDecl.cpp:1482
void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type, bool ForVirtualBase, bool Delegating, Address This, QualType ThisTy)
Definition CGClass.cpp:2661
void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::GlobalVariable *GV, bool PerformInit)
EmitCXXGlobalVarDeclInit - Create the initializer for a C++ variable with global storage.
void pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete, llvm::Value *CompletePtr, QualType ElementType)
llvm::Constant * EmitCheckTypeDescriptor(QualType T)
Emit a description of a type in a format suitable for passing to a runtime sanitizer handler.
Definition CGExpr.cpp:3863
void EmitAnyExprToExn(const Expr *E, Address Addr)
void EmitAggregateCopy(LValue Dest, LValue Src, QualType EltTy, AggValueSlot::Overlap_t MayOverlap, bool isVolatile=false)
EmitAggregateCopy - Emit an aggregate copy.
const TargetInfo & getTarget() const
CGCallee BuildAppleKextVirtualDestructorCall(const CXXDestructorDecl *DD, CXXDtorType Type, const CXXRecordDecl *RD)
BuildVirtualCall - This routine makes indirect vtable call for call to virtual destructors.
Definition CGCXX.cpp:328
void StartFunction(GlobalDecl GD, QualType RetTy, llvm::Function *Fn, const CGFunctionInfo &FnInfo, const FunctionArgList &Args, SourceLocation Loc=SourceLocation(), SourceLocation StartLoc=SourceLocation())
Emit code for the start of a function.
void EmitCheck(ArrayRef< std::pair< llvm::Value *, SanitizerKind::SanitizerOrdinal > > Checked, SanitizerHandler Check, ArrayRef< llvm::Constant * > StaticArgs, ArrayRef< llvm::Value * > DynamicArgs, const TrapReason *TR=nullptr)
Create a basic block that will either trap or call a handler function in the UBSan runtime with the p...
Definition CGExpr.cpp:4121
void EmitCXXGuardedInitBranch(llvm::Value *NeedsInit, llvm::BasicBlock *InitBlock, llvm::BasicBlock *NoInitBlock, GuardKind Kind, const VarDecl *D)
Emit a branch to select whether or not to perform guarded initialization.
LValue MakeRawAddrLValue(llvm::Value *V, QualType T, CharUnits Alignment, AlignmentSource Source=AlignmentSource::Type)
Same as MakeAddrLValue above except that the pointer is known to be unsigned.
llvm::AllocaInst * CreateTempAlloca(llvm::Type *Ty, const Twine &Name="tmp", llvm::Value *ArraySize=nullptr)
CreateTempAlloca - This creates an alloca and inserts it into the entry block if ArraySize is nullptr...
Definition CGExpr.cpp:153
RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee, ReturnValueSlot ReturnValue, const CallArgList &Args, llvm::CallBase **CallOrInvoke, bool IsMustTail, SourceLocation Loc, bool IsVirtualFunctionPointerThunk=false)
EmitCall - Generate a call of the given function, expecting the given result type,...
Definition CGCall.cpp:5342
CGPointerAuthInfo EmitPointerAuthInfo(const PointerAuthSchema &Schema, llvm::Value *StorageAddress, GlobalDecl SchemaDecl, QualType SchemaType)
Emit the concrete pointer authentication informaton for the given authentication schema.
void EmitTypeMetadataCodeForVCall(const CXXRecordDecl *RD, llvm::Value *VTable, SourceLocation Loc)
If whole-program virtual table optimization is enabled, emit an assumption that VTable is a member of...
Definition CGClass.cpp:2910
llvm::Value * unregisterGlobalDtorWithUnAtExit(llvm::Constant *dtorStub)
Call unatexit() with function dtorStub.
llvm::Value * emitPointerAuthResign(llvm::Value *Pointer, QualType PointerType, const CGPointerAuthInfo &CurAuthInfo, const CGPointerAuthInfo &NewAuthInfo, bool IsKnownNonNull)
llvm::CallInst * EmitNounwindRuntimeCall(llvm::FunctionCallee callee, const Twine &name="")
llvm::Value * EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty, SourceLocation Loc, AlignmentSource Source=AlignmentSource::Type, bool isNontemporal=false)
EmitLoadOfScalar - Load a scalar value from an address, taking care to appropriately convert from the...
void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit)
EmitStoreOfComplex - Store a complex number into the specified l-value.
const Decl * CurFuncDecl
CurFuncDecl - Holds the Decl for the current outermost non-closure context.
void EmitAutoVarCleanups(const AutoVarEmission &emission)
Definition CGDecl.cpp:2217
void registerGlobalDtorWithLLVM(const VarDecl &D, llvm::FunctionCallee fn, llvm::Constant *addr)
Registers the dtor using 'llvm.global_dtors' for platforms that do not support an 'atexit()' function...
llvm::Value * LoadCXXVTT()
LoadCXXVTT - Load the VTT parameter to base constructors/destructors have virtual bases.
llvm::CallInst * EmitRuntimeCall(llvm::FunctionCallee callee, const Twine &name="")
llvm::Value * EmitARCRetainNonBlock(llvm::Value *value)
Retain the given object, with normal retain semantics.
Definition CGObjC.cpp:2337
llvm::Type * ConvertTypeForMem(QualType T)
CodeGenTypes & getTypes() const
static TypeEvaluationKind getEvaluationKind(QualType T)
getEvaluationKind - Return the TypeEvaluationKind of QualType T.
void EmitBranch(llvm::BasicBlock *Block)
EmitBranch - Emit a branch to the specified basic block from the current insert block,...
Definition CGStmt.cpp:660
void EmitAggExpr(const Expr *E, AggValueSlot AS)
EmitAggExpr - Emit the computation of the specified expression of aggregate type.
llvm::Value * GetVTTParameter(GlobalDecl GD, bool ForVirtualBase, bool Delegating)
GetVTTParameter - Return the VTT parameter that should be passed to a base constructor/destructor wit...
Definition CGClass.cpp:446
LValue MakeAddrLValue(Address Addr, QualType T, AlignmentSource Source=AlignmentSource::Type)
void EmitTrapCheck(llvm::Value *Checked, SanitizerHandler CheckHandlerID, bool NoMerge=false, const TrapReason *TR=nullptr)
Create a basic block that will call the trap intrinsic, and emit a conditional branch to it,...
Definition CGExpr.cpp:4463
void FinishFunction(SourceLocation EndLoc=SourceLocation())
FinishFunction - Complete IR generation of the current function.
Address GetAddrOfLocalVar(const VarDecl *VD)
GetAddrOfLocalVar - Return the address of a local variable.
llvm::Value * EmitVTableTypeCheckedLoad(const CXXRecordDecl *RD, llvm::Value *VTable, llvm::Type *VTableTy, uint64_t VTableByteOffset)
Emit a type checked load from the given vtable.
Definition CGClass.cpp:3097
Address ReturnValue
ReturnValue - The temporary alloca to hold the return value.
llvm::Instruction * CurrentFuncletPad
bool ShouldEmitVTableTypeCheckedLoad(const CXXRecordDecl *RD)
Returns whether we should perform a type checked load when loading a virtual function for virtual cal...
Definition CGClass.cpp:3079
llvm::LLVMContext & getLLVMContext()
void PopCleanupBlock(bool FallThroughIsBranchThrough=false, bool ForDeactivation=false)
PopCleanupBlock - Will pop the cleanup entry on the stack and process all branch fixups.
void EmitStoreOfScalar(llvm::Value *Value, Address Addr, bool Volatile, QualType Ty, AlignmentSource Source=AlignmentSource::Type, bool isInit=false, bool isNontemporal=false)
EmitStoreOfScalar - Store a scalar value to an address, taking care to appropriately convert from the...
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
Definition CGStmt.cpp:640
LValue MakeNaturalAlignRawAddrLValue(llvm::Value *V, QualType T)
QualType BuildFunctionArgList(GlobalDecl GD, FunctionArgList &Args)
llvm::Value * EmitPointerAuthAuth(const CGPointerAuthInfo &Info, llvm::Value *Pointer)
This class organizes the cross-function state that is used while generating LLVM code.
void AddCXXPrioritizedStermFinalizerEntry(llvm::Function *StermFinalizer, int Priority)
void setGVProperties(llvm::GlobalValue *GV, GlobalDecl GD) const
Set visibility, dllimport/dllexport and dso_local.
void AddCXXStermFinalizerToGlobalDtor(llvm::Function *StermFinalizer, int Priority)
Add an sterm finalizer to its own llvm.global_dtors entry.
llvm::GlobalVariable::ThreadLocalMode GetDefaultLLVMTLSModel() const
Get LLVM TLS mode from CodeGenOptions.
void setDSOLocal(llvm::GlobalValue *GV) const
llvm::Module & getModule() const
llvm::FunctionCallee CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name, llvm::AttributeList ExtraAttrs=llvm::AttributeList(), bool Local=false, bool AssumeConvergent=false)
Create or return a runtime function declaration with the specified type and name.
CodeGenVTables & getVTables()
void AddCXXStermFinalizerEntry(llvm::FunctionCallee DtorFn)
Add an sterm finalizer to the C++ global cleanup function.
llvm::Constant * GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH=false)
Get the address of the RTTI descriptor for the given type.
llvm::Constant * getFunctionPointer(GlobalDecl GD, llvm::Type *Ty=nullptr)
Return the ABI-correct function pointer value for a reference to the given function.
CGPointerAuthInfo getMemberFunctionPointerAuthInfo(QualType FT)
const LangOptions & getLangOpts() const
bool shouldMapVisibilityToDLLExport(const NamedDecl *D) const
const TargetInfo & getTarget() const
bool TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D)
Try to emit a base destructor as an alias to its primary base-class destructor.
Definition CGCXX.cpp:32
llvm::GlobalValue::LinkageTypes getLLVMLinkageVarDefinition(const VarDecl *VD)
Returns LLVM linkage for a declarator.
const llvm::DataLayout & getDataLayout() const
static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V)
llvm::Constant * getMemberFunctionPointer(const FunctionDecl *FD, llvm::Type *Ty=nullptr)
llvm::Function * codegenCXXStructor(GlobalDecl GD)
Definition CGCXX.cpp:238
CharUnits getClassPointerAlignment(const CXXRecordDecl *CD)
Returns the assumed alignment of an opaque pointer to the given class.
Definition CGClass.cpp:40
const llvm::Triple & getTriple() const
llvm::GlobalVariable::LinkageTypes getFunctionLinkage(GlobalDecl GD)
llvm::Constant * CreateRuntimeVariable(llvm::Type *Ty, StringRef Name)
Create a new runtime global variable with the specified type and name.
CharUnits getDynamicOffsetAlignment(CharUnits ActualAlign, const CXXRecordDecl *Class, CharUnits ExpectedTargetAlign)
Given a class pointer with an actual known alignment, and the expected alignment of an object at a dy...
Definition CGClass.cpp:91
llvm::Constant * GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition=NotForDefinition)
ItaniumVTableContext & getItaniumVTableContext()
ASTContext & getContext() const
llvm::Constant * GetAddrOfGlobalVar(const VarDecl *D, llvm::Type *Ty=nullptr, ForDefinition_t IsForDefinition=NotForDefinition)
Return the llvm::Constant for the address of the given global variable.
const TargetCodeGenInfo & getTargetCodeGenInfo()
const CodeGenOptions & getCodeGenOpts() const
StringRef getMangledName(GlobalDecl GD)
void SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV)
Set attributes which are common to any form of a global definition (alias, Objective-C method,...
llvm::GlobalVariable * CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage, llvm::Align Alignment)
Will return a global variable of the given type.
llvm::FunctionCallee getTerminateFn()
Get the declaration of std::terminate for the platform.
llvm::LLVMContext & getLLVMContext()
llvm::GlobalValue * GetGlobalValue(StringRef Ref)
void maybeSetTrivialComdat(const Decl &D, llvm::GlobalObject &GO)
LangAS GetGlobalVarAddressSpace(const VarDecl *D)
Return the AST address space of the underlying global variable for D, as determined by its declaratio...
llvm::GlobalVariable::LinkageTypes getVTableLinkage(const CXXRecordDecl *RD)
Return the appropriate linkage for the vtable, VTT, and type information of the given class.
void SetLLVMFunctionAttributes(GlobalDecl GD, const CGFunctionInfo &Info, llvm::Function *F, bool IsThunk)
Set the LLVM function attributes (sext, zext, etc).
void addReplacement(StringRef Name, llvm::Constant *C)
llvm::Constant * getConstantSignedPointer(llvm::Constant *Pointer, const PointerAuthSchema &Schema, llvm::Constant *StorageAddress, GlobalDecl SchemaDecl, QualType SchemaType)
Sign a constant pointer using the given scheme, producing a constant with the same IR type.
void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F)
Set the LLVM function attributes which only apply to a function definition.
llvm::Function * CreateGlobalInitOrCleanUpFunction(llvm::FunctionType *ty, const Twine &name, const CGFunctionInfo &FI, SourceLocation Loc=SourceLocation(), bool TLS=false, llvm::GlobalVariable::LinkageTypes Linkage=llvm::GlobalVariable::InternalLinkage)
llvm::Type * ConvertType(QualType T)
ConvertType - Convert type T into a llvm::Type.
const CGFunctionInfo & arrangeCXXMethodDeclaration(const CXXMethodDecl *MD)
C++ methods have some special rules and also have implicit parameters.
Definition CGCall.cpp:376
const CodeGenOptions & getCodeGenOpts() const
llvm::FunctionType * GetFunctionType(const CGFunctionInfo &Info)
GetFunctionType - Get the LLVM function type for.
Definition CGCall.cpp:1801
bool isFuncTypeConvertible(const FunctionType *FT)
isFuncTypeConvertible - Utility to check whether a function type can be converted to an LLVM type (i....
const CGFunctionInfo & arrangeBuiltinFunctionDeclaration(QualType resultType, const FunctionArgList &args)
A builtin function is a freestanding function using the default C conventions.
Definition CGCall.cpp:742
const CGFunctionInfo & arrangeCXXMethodCall(const CallArgList &args, const FunctionProtoType *type, RequiredArgs required, unsigned numPrefixArgs)
Arrange a call to a C++ method, passing the given arguments.
Definition CGCall.cpp:772
const CGFunctionInfo & arrangeNullaryFunction()
A nullary function is a freestanding function of type 'void ()'.
Definition CGCall.cpp:790
llvm::GlobalVariable * GetAddrOfVTT(const CXXRecordDecl *RD)
GetAddrOfVTT - Get the address of the VTT for the given record decl.
Definition CGVTT.cpp:118
void createVTableInitializer(ConstantStructBuilder &builder, const VTableLayout &layout, llvm::Constant *rtti, bool vtableHasLocalLinkage)
Add vtable components for the given vtable layout to the given global initializer.
void GenerateRelativeVTableAlias(llvm::GlobalVariable *VTable, llvm::StringRef AliasNameRef)
Generate a public facing alias for the vtable and make the vtable either hidden or private.
bool isVTableExternal(const CXXRecordDecl *RD)
At this point in the translation unit, does it appear that can we rely on the vtable being defined el...
void RemoveHwasanMetadata(llvm::GlobalValue *GV) const
Specify a global should not be instrumented with hwasan.
void EmitVTTDefinition(llvm::GlobalVariable *VTT, llvm::GlobalVariable::LinkageTypes Linkage, const CXXRecordDecl *RD)
EmitVTTDefinition - Emit the definition of the given vtable.
Definition CGVTT.cpp:41
void pushTerminate()
Push a terminate handler on the stack.
void popTerminate()
Pops a terminate handler off the stack.
Definition CGCleanup.h:639
static RValue get(llvm::Value *V)
Definition CGValue.h:99
static RequiredArgs forPrototypePlus(const FunctionProtoType *prototype, unsigned additional)
Compute the arguments required by the given formal prototype, given that there may be some additional...
virtual unsigned getSizeOfUnwindException() const
Determines the size of struct _Unwind_Exception on this platform, in 8-bit units.
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2109
bool isTranslationUnit() const
Definition DeclBase.h:2185
decl_range noload_decls() const
noload_decls_begin/end - Iterate over the declarations stored in this context that are currently load...
Definition DeclBase.h:2381
T * getAttr() const
Definition DeclBase.h:573
SourceLocation getLocation() const
Definition DeclBase.h:439
DeclContext * getDeclContext()
Definition DeclBase.h:448
bool hasAttr() const
Definition DeclBase.h:577
bool shouldEmitInExternalSource() const
Whether the definition of the declaration should be emitted in external sources.
This represents one expression.
Definition Expr.h:112
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:277
QualType getType() const
Definition Expr.h:144
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition Decl.h:2921
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
Definition Decl.h:2326
bool isPureVirtual() const
Whether this virtual function is pure, i.e.
Definition Decl.h:2353
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5315
GlobalDecl - represents a global declaration.
Definition GlobalDecl.h:57
GlobalDecl getWithCtorType(CXXCtorType Type)
Definition GlobalDecl.h:178
CXXCtorType getCtorType() const
Definition GlobalDecl.h:108
GlobalDecl getCanonicalDecl() const
Definition GlobalDecl.h:97
GlobalDecl getWithDtorType(CXXDtorType Type)
Definition GlobalDecl.h:185
CXXDtorType getDtorType() const
Definition GlobalDecl.h:113
const Decl * getDecl() const
Definition GlobalDecl.h:106
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
static ImplicitParamDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, ImplicitParamKind ParamKind)
Create implicit parameter.
Definition Decl.cpp:5603
const VTableLayout & getVTableLayout(const CXXRecordDecl *RD)
CharUnits getVirtualBaseOffsetOffset(const CXXRecordDecl *RD, const CXXRecordDecl *VBase)
Return the offset in chars (relative to the vtable address point) where the offset of the virtual bas...
GlobalDecl findOriginalMethod(GlobalDecl GD)
Return the method that added the v-table slot that will be used to call the given method.
virtual void mangleCXXRTTI(QualType T, raw_ostream &)=0
virtual void mangleCXXRTTIName(QualType T, raw_ostream &, bool NormalizeIntegers=false)=0
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3661
CXXRecordDecl * getMostRecentCXXRecordDecl() const
Note: this can trigger extra deserialization when external AST sources are used.
Definition Type.cpp:5530
QualType getPointeeType() const
Definition TypeBase.h:3679
bool isMemberFunctionPointer() const
Returns true if the member type (i.e.
Definition TypeBase.h:3683
bool isMemberDataPointer() const
Returns true if the member type (i.e.
Definition TypeBase.h:3689
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
Visibility getVisibility() const
Determines the visibility of this entity.
Definition Decl.h:444
bool isExternallyVisible() const
Definition Decl.h:433
static const OpaqueValueExpr * findInCopyConstruct(const Expr *expr)
Given an expression which invokes a copy constructor — i.e.
Definition Expr.cpp:5145
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3336
QualType getPointeeType() const
Definition TypeBase.h:3346
A (possibly-)qualified type.
Definition TypeBase.h:937
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8428
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition TypeBase.h:8573
QualType getCanonicalType() const
Definition TypeBase.h:8440
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8482
The collection of all-type qualifiers we support.
Definition TypeBase.h:331
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:361
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition TypeBase.h:354
@ OCL_None
There is no lifetime qualification on this type.
Definition TypeBase.h:350
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition TypeBase.h:364
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition TypeBase.h:367
ObjCLifetime getObjCLifetime() const
Definition TypeBase.h:545
bool empty() const
Definition TypeBase.h:647
bool canPassInRegisters() const
Determine whether this class can be passed in registers.
Definition Decl.h:4464
Encodes a location in the source.
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
unsigned getMaxAtomicInlineWidth() const
Return the maximum width lock-free atomic operation which can be inlined given the supported features...
Definition TargetInfo.h:858
uint64_t getPointerWidth(LangAS AddrSpace) const
Return the width of pointers on this target, for the specified address space.
Definition TargetInfo.h:489
virtual bool hasPS4DLLImportExport() const
uint64_t getPointerAlign(LangAS AddrSpace) const
Definition TargetInfo.h:493
unsigned getLongWidth() const
getLongWidth/Align - Return the size of 'signed long' and 'unsigned long' for this target,...
Definition TargetInfo.h:535
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
The base class of the type hierarchy.
Definition TypeBase.h:1839
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
CXXRecordDecl * castAsCXXRecordDecl() const
Definition Type.h:36
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9285
bool isReferenceType() const
Definition TypeBase.h:8649
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:753
Visibility getVisibility() const
Determine the visibility of this type.
Definition TypeBase.h:3073
bool isMemberFunctionPointerType() const
Definition TypeBase.h:8710
Linkage getLinkage() const
Determine the linkage of this type.
Definition Type.cpp:4968
TypeClass getTypeClass() const
Definition TypeBase.h:2391
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9218
bool isRecordType() const
Definition TypeBase.h:8752
AddressPointLocation getAddressPoint(BaseSubobject Base) const
size_t getVTableSize(size_t i) const
QualType getType() const
Definition Decl.h:723
Represents a variable declaration or definition.
Definition Decl.h:926
TLSKind getTLSKind() const
Definition Decl.cpp:2180
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:2269
bool isNoDestroy(const ASTContext &) const
Is destruction of this variable entirely suppressed?
Definition Decl.cpp:2848
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition Decl.h:1208
bool isInline() const
Whether this variable is (C++1z) inline.
Definition Decl.h:1551
const Expr * getInit() const
Definition Decl.h:1368
@ TLS_Dynamic
TLS with a dynamic initializer.
Definition Decl.h:952
@ TLS_None
Not a TLS variable.
Definition Decl.h:946
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition Decl.cpp:2387
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition Decl.h:1253
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition Decl.cpp:2791
llvm::Value * getCXXDestructorImplicitParam(CodeGenModule &CGM, llvm::BasicBlock *InsertBlock, llvm::BasicBlock::iterator InsertPoint, const CXXDestructorDecl *D, CXXDtorType Type, bool ForVirtualBase, bool Delegating)
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
Definition CGValue.h:146
CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT, CGCXXABI &CXXABI)
bool classifyReturnType(const CGCXXABI &CXXABI, CGFunctionInfo &FI, const ABIInfo &Info)
TypeEvaluationKind
The kind of evaluation to perform on values of a particular type.
@ NormalCleanup
Denotes a cleanup that should run when a scope is exited using normal control flow (falling off the e...
@ EHCleanup
Denotes a cleanup that should run when a scope is exited using exceptional control flow (a throw stat...
CGCXXABI * CreateItaniumCXXABI(CodeGenModule &CGM)
Creates an Itanium-family ABI.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
constexpr Variable var(Literal L)
Returns the variable of L.
Definition CNFFormula.h:64
bool This(InterpState &S, CodePtr OpPC)
Definition Interp.h:2844
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
CXXCtorType
C++ constructor types.
Definition ABI.h:24
@ Ctor_Base
Base object ctor.
Definition ABI.h:26
@ Ctor_DefaultClosure
Default closure variant of a ctor.
Definition ABI.h:29
@ Ctor_CopyingClosure
Copying closure variant of a ctor.
Definition ABI.h:28
@ Ctor_Complete
Complete object ctor.
Definition ABI.h:25
@ Ctor_Comdat
The COMDAT used for ctors.
Definition ABI.h:27
@ Ctor_Unified
GCC-style unified dtor.
Definition ABI.h:30
bool isa(CodeGen::Address addr)
Definition Address.h:330
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition Specifiers.h:212
@ GVA_DiscardableODR
Definition Linkage.h:75
@ Success
Annotation was successful.
Definition Parser.h:65
@ AS_public
Definition Specifiers.h:124
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have.
Definition Linkage.h:24
@ VisibleNone
No linkage according to the standard, but is visible from other translation units because of types de...
Definition Linkage.h:48
@ None
No linkage, which means that the entity is unique and can only be referred to from within its scope.
Definition Linkage.h:30
@ UniqueExternal
External linkage within a unique namespace.
Definition Linkage.h:44
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition Linkage.h:35
@ External
External linkage, which indicates that the entity can be referred to from other translation units.
Definition Linkage.h:58
@ Module
Module linkage, which indicates that the entity can be referred to from other translation units withi...
Definition Linkage.h:54
@ Result
The result type of a method or function.
Definition TypeBase.h:905
CXXDtorType
C++ destructor types.
Definition ABI.h:34
@ Dtor_VectorDeleting
Vector deleting dtor.
Definition ABI.h:40
@ Dtor_Comdat
The COMDAT used for dtors.
Definition ABI.h:38
@ Dtor_Unified
GCC-style unified dtor.
Definition ABI.h:39
@ Dtor_Base
Base object dtor.
Definition ABI.h:37
@ Dtor_Complete
Complete object dtor.
Definition ABI.h:36
@ Dtor_Deleting
Deleting dtor.
Definition ABI.h:35
bool isDiscardableGVALinkage(GVALinkage L)
Definition Linkage.h:80
@ Type
The name was classified as a type.
Definition Sema.h:564
LangAS
Defines the address space values used by the address space qualifier of QualType.
U cast(CodeGen::Address addr)
Definition Address.h:327
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5925
@ EST_None
no exception specification
Visibility
Describes the different kinds of visibility that a declaration may have.
Definition Visibility.h:34
@ HiddenVisibility
Objects with "hidden" visibility are not seen by the dynamic linker.
Definition Visibility.h:37
@ DefaultVisibility
Objects with "default" visibility are seen by the dynamic linker and act like normal objects.
Definition Visibility.h:46
unsigned long uint64_t
long int64_t
const half4 dst(half4 Src0, half4 Src1)
#define false
Definition stdbool.h:26
#define true
Definition stdbool.h:25
Represents an element in a path from a derived class to a base class.
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
llvm::IntegerType * CharTy
char
llvm::CallingConv::ID getRuntimeCC() const
static const EHPersonality & get(CodeGenModule &CGM, const FunctionDecl *FD)
Extra information about a function prototype.
Definition TypeBase.h:5400
PointerAuthSchema CXXVTTVTablePointers
The ABI for C++ virtual table pointers as installed in a VTT.
PointerAuthSchema CXXTypeInfoVTablePointer
TypeInfo has external ABI requirements and is emitted without actually having parsed the libcxx defin...
union clang::ReturnAdjustment::VirtualAdjustment Virtual
int64_t NonVirtual
The non-virtual adjustment from the derived object to its nearest virtual base.
Definition Thunk.h:30
bool has(SanitizerMask K) const
Check if a certain (single) sanitizer is enabled.
Definition Sanitizers.h:174
union clang::ThisAdjustment::VirtualAdjustment Virtual
int64_t NonVirtual
The non-virtual adjustment from the derived object to its nearest virtual base.
Definition Thunk.h:95
ThisAdjustment This
The this pointer adjustment.
Definition Thunk.h:159
struct clang::ReturnAdjustment::VirtualAdjustment::@103031170252120233124322035264172076254313213024 Itanium
int64_t VBaseOffsetOffset
The offset (in bytes), relative to the address point of the virtual base class offset.
Definition Thunk.h:39
struct clang::ThisAdjustment::VirtualAdjustment::@106065375072164260365214033034320247050276346205 Itanium
int64_t VCallOffsetOffset
The offset (in bytes), relative to the address point, of the virtual call offset.
Definition Thunk.h:104