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.getLangOpts().RelativeCXXABIVTables) {
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.getLangOpts().RelativeCXXABIVTables) {
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 using the target
1385 // hook getSRetAddrSpace to decide the AS.
1386 if (!RD->canPassInRegisters()) {
1387 auto Align = CGM.getContext().getTypeAlignInChars(FI.getReturnType());
1388 LangAS SRetAS = CGM.getTargetCodeGenInfo().getSRetAddrSpace(RD);
1389 unsigned AS = CGM.getContext().getTargetAddressSpace(SRetAS);
1390 FI.getReturnInfo() =
1391 ABIArgInfo::getIndirect(Align, /*AddrSpace=*/AS, /*ByVal=*/false);
1392 return true;
1393 }
1394 return false;
1395}
1396
1397/// The Itanium ABI requires non-zero initialization only for data
1398/// member pointers, for which '0' is a valid offset.
1399bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
1400 return MPT->isMemberFunctionPointer();
1401}
1402
1403/// The Itanium ABI always places an offset to the complete object
1404/// at entry -2 in the vtable.
1405void ItaniumCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
1406 const CXXDeleteExpr *DE,
1407 Address Ptr,
1408 QualType ElementType,
1409 const CXXDestructorDecl *Dtor) {
1410 bool UseGlobalDelete = DE->isGlobalDelete();
1411 if (UseGlobalDelete) {
1412 // Derive the complete-object pointer, which is what we need
1413 // to pass to the deallocation function.
1414
1415 // Grab the vtable pointer as an intptr_t*.
1416 auto *ClassDecl = ElementType->castAsCXXRecordDecl();
1417 llvm::Value *VTable = CGF.GetVTablePtr(Ptr, CGF.DefaultPtrTy, ClassDecl);
1418
1419 // Track back to entry -2 and pull out the offset there.
1420 llvm::Value *OffsetPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
1421 CGF.IntPtrTy, VTable, -2, "complete-offset.ptr");
1422 llvm::Value *Offset = CGF.Builder.CreateAlignedLoad(CGF.IntPtrTy, OffsetPtr,
1423 CGF.getPointerAlign());
1424
1425 // Apply the offset.
1426 llvm::Value *CompletePtr = Ptr.emitRawPointer(CGF);
1427 CompletePtr =
1428 CGF.Builder.CreateInBoundsGEP(CGF.Int8Ty, CompletePtr, Offset);
1429
1430 // If we're supposed to call the global delete, make sure we do so
1431 // even if the destructor throws.
1432 CGF.pushCallObjectDeleteCleanup(DE->getOperatorDelete(), CompletePtr,
1433 ElementType);
1434 }
1435
1436 // FIXME: Provide a source location here even though there's no
1437 // CXXMemberCallExpr for dtor call.
1438 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
1439 EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, DE,
1440 /*CallOrInvoke=*/nullptr);
1441
1442 if (UseGlobalDelete)
1443 CGF.PopCleanupBlock();
1444}
1445
1446void ItaniumCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
1447 // void __cxa_rethrow();
1448
1449 llvm::FunctionType *FTy =
1450 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
1451
1452 llvm::FunctionCallee Fn = CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
1453
1454 if (isNoReturn)
1456 else
1458}
1459
1460static llvm::FunctionCallee getAllocateExceptionFn(CodeGenModule &CGM) {
1461 // void *__cxa_allocate_exception(size_t thrown_size);
1462
1463 llvm::FunctionType *FTy =
1464 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.SizeTy, /*isVarArg=*/false);
1465
1466 return CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
1467}
1468
1469static llvm::FunctionCallee getThrowFn(CodeGenModule &CGM) {
1470 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
1471 // void (*dest) (void *));
1472
1473 llvm::Type *Args[3] = { CGM.Int8PtrTy, CGM.GlobalsInt8PtrTy, CGM.Int8PtrTy };
1474 llvm::FunctionType *FTy =
1475 llvm::FunctionType::get(CGM.VoidTy, Args, /*isVarArg=*/false);
1476
1477 return CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
1478}
1479
1480void ItaniumCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
1481 QualType ThrowType = E->getSubExpr()->getType();
1482 // Now allocate the exception object.
1483 llvm::Type *SizeTy = CGF.ConvertType(getContext().getSizeType());
1484 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
1485
1486 llvm::FunctionCallee AllocExceptionFn = getAllocateExceptionFn(CGM);
1487 llvm::CallInst *ExceptionPtr = CGF.EmitNounwindRuntimeCall(
1488 AllocExceptionFn, llvm::ConstantInt::get(SizeTy, TypeSize), "exception");
1489
1490 CharUnits ExnAlign = CGF.getContext().getExnObjectAlignment();
1491 CGF.EmitAnyExprToExn(
1492 E->getSubExpr(), Address(ExceptionPtr, CGM.Int8Ty, ExnAlign));
1493
1494 // Now throw the exception.
1495 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
1496 /*ForEH=*/true);
1497
1498 // The address of the destructor. If the exception type has a
1499 // trivial destructor (or isn't a record), we just pass null.
1500 llvm::Constant *Dtor = nullptr;
1501 if (const auto *Record = ThrowType->getAsCXXRecordDecl();
1503 // __cxa_throw is declared to take its destructor as void (*)(void *). We
1504 // must match that if function pointers can be authenticated with a
1505 // discriminator based on their type.
1506 const ASTContext &Ctx = getContext();
1507 QualType DtorTy = Ctx.getFunctionType(Ctx.VoidTy, {Ctx.VoidPtrTy},
1508 FunctionProtoType::ExtProtoInfo());
1509
1510 CXXDestructorDecl *DtorD = Record->getDestructor();
1511 Dtor = CGM.getAddrOfCXXStructor(GlobalDecl(DtorD, Dtor_Complete));
1512 Dtor = CGM.getFunctionPointer(Dtor, DtorTy);
1513 }
1514 if (!Dtor) Dtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);
1515
1516 llvm::Value *args[] = { ExceptionPtr, TypeInfo, Dtor };
1518}
1519
1520static llvm::FunctionCallee getItaniumDynamicCastFn(CodeGenFunction &CGF) {
1521 // void *__dynamic_cast(const void *sub,
1522 // global_as const abi::__class_type_info *src,
1523 // global_as const abi::__class_type_info *dst,
1524 // std::ptrdiff_t src2dst_offset);
1525
1526 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
1527 llvm::Type *GlobInt8PtrTy = CGF.GlobalsInt8PtrTy;
1528 llvm::Type *PtrDiffTy =
1530
1531 llvm::Type *Args[4] = { Int8PtrTy, GlobInt8PtrTy, GlobInt8PtrTy, PtrDiffTy };
1532
1533 llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false);
1534
1535 // Mark the function as nounwind willreturn readonly.
1536 llvm::AttrBuilder FuncAttrs(CGF.getLLVMContext());
1537 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1538 FuncAttrs.addAttribute(llvm::Attribute::WillReturn);
1539 FuncAttrs.addMemoryAttr(llvm::MemoryEffects::readOnly());
1540 llvm::AttributeList Attrs = llvm::AttributeList::get(
1541 CGF.getLLVMContext(), llvm::AttributeList::FunctionIndex, FuncAttrs);
1542
1543 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs);
1544}
1545
1546static llvm::FunctionCallee getBadCastFn(CodeGenFunction &CGF) {
1547 // void __cxa_bad_cast();
1548 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1549 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1550}
1551
1552/// Compute the src2dst_offset hint as described in the
1553/// Itanium C++ ABI [2.9.7]
1555 const CXXRecordDecl *Src,
1556 const CXXRecordDecl *Dst) {
1557 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1558 /*DetectVirtual=*/false);
1559
1560 // If Dst is not derived from Src we can skip the whole computation below and
1561 // return that Src is not a public base of Dst. Record all inheritance paths.
1562 if (!Dst->isDerivedFrom(Src, Paths))
1563 return CharUnits::fromQuantity(-2ULL);
1564
1565 unsigned NumPublicPaths = 0;
1566 CharUnits Offset;
1567
1568 // Now walk all possible inheritance paths.
1569 for (const CXXBasePath &Path : Paths) {
1570 if (Path.Access != AS_public) // Ignore non-public inheritance.
1571 continue;
1572
1573 ++NumPublicPaths;
1574
1575 for (const CXXBasePathElement &PathElement : Path) {
1576 // If the path contains a virtual base class we can't give any hint.
1577 // -1: no hint.
1578 if (PathElement.Base->isVirtual())
1579 return CharUnits::fromQuantity(-1ULL);
1580
1581 if (NumPublicPaths > 1) // Won't use offsets, skip computation.
1582 continue;
1583
1584 // Accumulate the base class offsets.
1585 const ASTRecordLayout &L = Context.getASTRecordLayout(PathElement.Class);
1586 Offset += L.getBaseClassOffset(
1587 PathElement.Base->getType()->getAsCXXRecordDecl());
1588 }
1589 }
1590
1591 // -2: Src is not a public base of Dst.
1592 if (NumPublicPaths == 0)
1593 return CharUnits::fromQuantity(-2ULL);
1594
1595 // -3: Src is a multiple public base type but never a virtual base type.
1596 if (NumPublicPaths > 1)
1597 return CharUnits::fromQuantity(-3ULL);
1598
1599 // Otherwise, the Src type is a unique public nonvirtual base type of Dst.
1600 // Return the offset of Src from the origin of Dst.
1601 return Offset;
1602}
1603
1604static llvm::FunctionCallee getBadTypeidFn(CodeGenFunction &CGF) {
1605 // void __cxa_bad_typeid();
1606 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1607
1608 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1609}
1610
1611bool ItaniumCXXABI::shouldTypeidBeNullChecked(QualType SrcRecordTy) {
1612 return true;
1613}
1614
1615void ItaniumCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
1616 llvm::FunctionCallee Fn = getBadTypeidFn(CGF);
1617 llvm::CallBase *Call = CGF.EmitRuntimeCallOrInvoke(Fn);
1618 Call->setDoesNotReturn();
1619 CGF.Builder.CreateUnreachable();
1620}
1621
1622llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF,
1623 QualType SrcRecordTy,
1624 Address ThisPtr,
1625 llvm::Type *StdTypeInfoPtrTy) {
1626 auto *ClassDecl = SrcRecordTy->castAsCXXRecordDecl();
1627 llvm::Value *Value = CGF.GetVTablePtr(ThisPtr, CGM.GlobalsInt8PtrTy,
1628 ClassDecl);
1629
1630 if (CGM.getLangOpts().RelativeCXXABIVTables) {
1631 // Load the type info.
1632 Value = CGF.Builder.CreateCall(
1633 CGM.getIntrinsic(llvm::Intrinsic::load_relative, {CGM.Int32Ty}),
1634 {Value, llvm::ConstantInt::getSigned(CGM.Int32Ty, -4)});
1635 } else {
1636 // Load the type info.
1637 Value =
1638 CGF.Builder.CreateConstInBoundsGEP1_64(StdTypeInfoPtrTy, Value, -1ULL);
1639 }
1640 return CGF.Builder.CreateAlignedLoad(StdTypeInfoPtrTy, Value,
1641 CGF.getPointerAlign());
1642}
1643
1644bool ItaniumCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
1645 QualType SrcRecordTy) {
1646 return SrcIsPtr;
1647}
1648
1649llvm::Value *ItaniumCXXABI::emitDynamicCastCall(
1650 CodeGenFunction &CGF, Address ThisAddr, QualType SrcRecordTy,
1651 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
1652 llvm::Type *PtrDiffLTy =
1654
1655 llvm::Value *SrcRTTI =
1657 llvm::Value *DestRTTI =
1659
1660 // Compute the offset hint.
1661 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
1662 const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
1663 llvm::Value *OffsetHint = llvm::ConstantInt::getSigned(
1664 PtrDiffLTy,
1665 computeOffsetHint(CGF.getContext(), SrcDecl, DestDecl).getQuantity());
1666
1667 // Emit the call to __dynamic_cast.
1668 llvm::Value *Value = ThisAddr.emitRawPointer(CGF);
1669 if (CGM.getCodeGenOpts().PointerAuth.CXXVTablePointers) {
1670 // We perform a no-op load of the vtable pointer here to force an
1671 // authentication. In environments that do not support pointer
1672 // authentication this is a an actual no-op that will be elided. When
1673 // pointer authentication is supported and enforced on vtable pointers this
1674 // load can trap.
1675 llvm::Value *Vtable =
1676 CGF.GetVTablePtr(ThisAddr, CGM.Int8PtrTy, SrcDecl,
1677 CodeGenFunction::VTableAuthMode::MustTrap);
1678 assert(Vtable);
1679 (void)Vtable;
1680 }
1681
1682 llvm::Value *args[] = {Value, SrcRTTI, DestRTTI, OffsetHint};
1684
1685 /// C++ [expr.dynamic.cast]p9:
1686 /// A failed cast to reference type throws std::bad_cast
1687 if (DestTy->isReferenceType()) {
1688 llvm::BasicBlock *BadCastBlock =
1689 CGF.createBasicBlock("dynamic_cast.bad_cast");
1690
1691 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1692 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1693
1694 CGF.EmitBlock(BadCastBlock);
1695 EmitBadCastCall(CGF);
1696 }
1697
1698 return Value;
1699}
1700
1701std::optional<CGCXXABI::ExactDynamicCastInfo>
1702ItaniumCXXABI::getExactDynamicCastInfo(QualType SrcRecordTy, QualType DestTy,
1703 QualType DestRecordTy) {
1704 assert(shouldEmitExactDynamicCast(DestRecordTy));
1705
1706 ASTContext &Context = getContext();
1707
1708 // Find all the inheritance paths.
1709 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
1710 const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
1711 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1712 /*DetectVirtual=*/false);
1713 (void)DestDecl->isDerivedFrom(SrcDecl, Paths);
1714
1715 // Find an offset within `DestDecl` where a `SrcDecl` instance and its vptr
1716 // might appear.
1717 std::optional<CharUnits> Offset;
1718 for (const CXXBasePath &Path : Paths) {
1719 // dynamic_cast only finds public inheritance paths.
1720 if (Path.Access != AS_public)
1721 continue;
1722
1723 CharUnits PathOffset;
1724 for (const CXXBasePathElement &PathElement : Path) {
1725 // Find the offset along this inheritance step.
1726 const CXXRecordDecl *Base =
1727 PathElement.Base->getType()->getAsCXXRecordDecl();
1728 if (PathElement.Base->isVirtual()) {
1729 // For a virtual base class, we know that the derived class is exactly
1730 // DestDecl, so we can use the vbase offset from its layout.
1731 const ASTRecordLayout &L = Context.getASTRecordLayout(DestDecl);
1732 PathOffset = L.getVBaseClassOffset(Base);
1733 } else {
1734 const ASTRecordLayout &L =
1735 Context.getASTRecordLayout(PathElement.Class);
1736 PathOffset += L.getBaseClassOffset(Base);
1737 }
1738 }
1739
1740 if (!Offset)
1741 Offset = PathOffset;
1742 else if (Offset != PathOffset) {
1743 // Base appears in at least two different places.
1744 return ExactDynamicCastInfo{/*RequiresCastToPrimaryBase=*/true,
1745 CharUnits::Zero()};
1746 }
1747 }
1748 if (!Offset)
1749 return std::nullopt;
1750 return ExactDynamicCastInfo{/*RequiresCastToPrimaryBase=*/false, *Offset};
1751}
1752
1753llvm::Value *ItaniumCXXABI::emitExactDynamicCast(
1754 CodeGenFunction &CGF, Address ThisAddr, QualType SrcRecordTy,
1755 QualType DestTy, QualType DestRecordTy,
1756 const ExactDynamicCastInfo &ExactCastInfo, llvm::BasicBlock *CastSuccess,
1757 llvm::BasicBlock *CastFail) {
1758 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
1759 const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
1760 auto AuthenticateVTable = [&](Address ThisAddr, const CXXRecordDecl *Decl) {
1761 if (!CGF.getLangOpts().PointerAuthCalls)
1762 return;
1763 (void)CGF.GetVTablePtr(ThisAddr, CGF.DefaultPtrTy, Decl,
1764 CodeGenFunction::VTableAuthMode::MustTrap);
1765 };
1766
1767 bool PerformPostCastAuthentication = false;
1768 llvm::Value *VTable = nullptr;
1769 if (ExactCastInfo.RequiresCastToPrimaryBase) {
1770 // Base appears in at least two different places. Find the most-derived
1771 // object and see if it's a DestDecl. Note that the most-derived object
1772 // must be at least as aligned as this base class subobject, and must
1773 // have a vptr at offset 0.
1774 llvm::Value *PrimaryBase =
1775 emitDynamicCastToVoid(CGF, ThisAddr, SrcRecordTy);
1776 ThisAddr = Address(PrimaryBase, CGF.VoidPtrTy, ThisAddr.getAlignment());
1777 SrcDecl = DestDecl;
1778 // This unauthenticated load is unavoidable, so we're relying on the
1779 // authenticated load in the dynamic cast to void, and we'll manually
1780 // authenticate the resulting v-table at the end of the cast check.
1781 PerformPostCastAuthentication = CGF.getLangOpts().PointerAuthCalls;
1782 CGPointerAuthInfo StrippingAuthInfo(0, PointerAuthenticationMode::Strip,
1783 false, false, nullptr);
1784 Address VTablePtrPtr = ThisAddr.withElementType(CGF.VoidPtrPtrTy);
1785 VTable = CGF.Builder.CreateLoad(VTablePtrPtr, "vtable");
1786 if (PerformPostCastAuthentication)
1787 VTable = CGF.EmitPointerAuthAuth(StrippingAuthInfo, VTable);
1788 } else
1789 VTable = CGF.GetVTablePtr(ThisAddr, CGF.DefaultPtrTy, SrcDecl);
1790
1791 // Compare the vptr against the expected vptr for the destination type at
1792 // this offset.
1793 llvm::Constant *ExpectedVTable = getVTableAddressPoint(
1794 BaseSubobject(SrcDecl, ExactCastInfo.Offset), DestDecl);
1795 llvm::Value *Success = CGF.Builder.CreateICmpEQ(VTable, ExpectedVTable);
1796 llvm::Value *AdjustedThisPtr = ThisAddr.emitRawPointer(CGF);
1797
1798 if (!ExactCastInfo.Offset.isZero()) {
1799 CharUnits::QuantityType Offset = ExactCastInfo.Offset.getQuantity();
1800 llvm::Constant *OffsetConstant =
1801 llvm::ConstantInt::get(CGF.PtrDiffTy, -Offset);
1802 AdjustedThisPtr = CGF.Builder.CreateInBoundsGEP(CGF.CharTy, AdjustedThisPtr,
1803 OffsetConstant);
1804 PerformPostCastAuthentication = CGF.getLangOpts().PointerAuthCalls;
1805 }
1806
1807 if (PerformPostCastAuthentication) {
1808 // If we've changed the object pointer we authenticate the vtable pointer
1809 // of the resulting object.
1810 llvm::BasicBlock *NonNullBlock = CGF.Builder.GetInsertBlock();
1811 llvm::BasicBlock *PostCastAuthSuccess =
1812 CGF.createBasicBlock("dynamic_cast.postauth.success");
1813 llvm::BasicBlock *PostCastAuthComplete =
1814 CGF.createBasicBlock("dynamic_cast.postauth.complete");
1815 CGF.Builder.CreateCondBr(Success, PostCastAuthSuccess,
1816 PostCastAuthComplete);
1817 CGF.EmitBlock(PostCastAuthSuccess);
1818 Address AdjustedThisAddr =
1819 Address(AdjustedThisPtr, CGF.IntPtrTy, CGF.getPointerAlign());
1820 AuthenticateVTable(AdjustedThisAddr, DestDecl);
1821 CGF.EmitBranch(PostCastAuthComplete);
1822 CGF.EmitBlock(PostCastAuthComplete);
1823 llvm::PHINode *PHI = CGF.Builder.CreatePHI(AdjustedThisPtr->getType(), 2);
1824 PHI->addIncoming(AdjustedThisPtr, PostCastAuthSuccess);
1825 llvm::Value *NullValue =
1826 llvm::Constant::getNullValue(AdjustedThisPtr->getType());
1827 PHI->addIncoming(NullValue, NonNullBlock);
1828 AdjustedThisPtr = PHI;
1829 }
1830 CGF.Builder.CreateCondBr(Success, CastSuccess, CastFail);
1831 return AdjustedThisPtr;
1832}
1833
1834llvm::Value *ItaniumCXXABI::emitDynamicCastToVoid(CodeGenFunction &CGF,
1835 Address ThisAddr,
1836 QualType SrcRecordTy) {
1837 auto *ClassDecl = SrcRecordTy->castAsCXXRecordDecl();
1838 llvm::Value *OffsetToTop;
1839 if (CGM.getLangOpts().RelativeCXXABIVTables) {
1840 // Get the vtable pointer.
1841 llvm::Value *VTable =
1842 CGF.GetVTablePtr(ThisAddr, CGF.DefaultPtrTy, ClassDecl);
1843
1844 // Get the offset-to-top from the vtable.
1845 OffsetToTop =
1846 CGF.Builder.CreateConstInBoundsGEP1_32(CGM.Int32Ty, VTable, -2U);
1847 OffsetToTop = CGF.Builder.CreateAlignedLoad(
1848 CGM.Int32Ty, OffsetToTop, CharUnits::fromQuantity(4), "offset.to.top");
1849 } else {
1850 llvm::Type *PtrDiffLTy =
1852
1853 // Get the vtable pointer.
1854 llvm::Value *VTable =
1855 CGF.GetVTablePtr(ThisAddr, CGF.DefaultPtrTy, ClassDecl);
1856
1857 // Get the offset-to-top from the vtable.
1858 OffsetToTop =
1859 CGF.Builder.CreateConstInBoundsGEP1_64(PtrDiffLTy, VTable, -2ULL);
1860 OffsetToTop = CGF.Builder.CreateAlignedLoad(
1861 PtrDiffLTy, OffsetToTop, CGF.getPointerAlign(), "offset.to.top");
1862 }
1863 // Finally, add the offset to the pointer.
1864 return CGF.Builder.CreateInBoundsGEP(CGF.Int8Ty, ThisAddr.emitRawPointer(CGF),
1865 OffsetToTop);
1866}
1867
1868bool ItaniumCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1869 llvm::FunctionCallee Fn = getBadCastFn(CGF);
1870 llvm::CallBase *Call = CGF.EmitRuntimeCallOrInvoke(Fn);
1871 Call->setDoesNotReturn();
1872 CGF.Builder.CreateUnreachable();
1873 return true;
1874}
1875
1876llvm::Value *
1877ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
1878 Address This,
1879 const CXXRecordDecl *ClassDecl,
1880 const CXXRecordDecl *BaseClassDecl) {
1881 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy, ClassDecl);
1882 CharUnits VBaseOffsetOffset =
1883 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
1884 BaseClassDecl);
1885 llvm::Value *VBaseOffsetPtr =
1886 CGF.Builder.CreateConstGEP1_64(
1887 CGF.Int8Ty, VTablePtr, VBaseOffsetOffset.getQuantity(),
1888 "vbase.offset.ptr");
1889
1890 llvm::Value *VBaseOffset;
1891 if (CGM.getLangOpts().RelativeCXXABIVTables) {
1892 VBaseOffset = CGF.Builder.CreateAlignedLoad(
1893 CGF.Int32Ty, VBaseOffsetPtr, CharUnits::fromQuantity(4),
1894 "vbase.offset");
1895 } else {
1896 VBaseOffset = CGF.Builder.CreateAlignedLoad(
1897 CGM.PtrDiffTy, VBaseOffsetPtr, CGF.getPointerAlign(), "vbase.offset");
1898 }
1899 return VBaseOffset;
1900}
1901
1902void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1903 // Just make sure we're in sync with TargetCXXABI.
1904 assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
1905
1906 // The constructor used for constructing this as a base class;
1907 // ignores virtual bases.
1908 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
1909
1910 // The constructor used for constructing this as a complete class;
1911 // constructs the virtual bases, then calls the base constructor.
1912 if (!D->getParent()->isAbstract()) {
1913 // We don't need to emit the complete ctor if the class is abstract.
1914 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1915 }
1916}
1917
1918CGCXXABI::AddedStructorArgCounts
1919ItaniumCXXABI::buildStructorSignature(GlobalDecl GD,
1920 SmallVectorImpl<CanQualType> &ArgTys) {
1921 ASTContext &Context = getContext();
1922
1923 // All parameters are already in place except VTT, which goes after 'this'.
1924 // These are Clang types, so we don't need to worry about sret yet.
1925
1926 // Check if we need to add a VTT parameter (which has type global void **).
1928 : GD.getDtorType() == Dtor_Base) &&
1929 cast<CXXMethodDecl>(GD.getDecl())->getParent()->getNumVBases() != 0) {
1930 LangAS AS = CGM.GetGlobalVarAddressSpace(nullptr);
1931 QualType Q = Context.getAddrSpaceQualType(Context.VoidPtrTy, AS);
1932 ArgTys.insert(ArgTys.begin() + 1,
1934 return AddedStructorArgCounts::prefix(1);
1935 }
1936 return AddedStructorArgCounts{};
1937}
1938
1939void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
1940 // The destructor used for destructing this as a base class; ignores
1941 // virtual bases.
1942 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
1943
1944 // The destructor used for destructing this as a most-derived class;
1945 // call the base destructor and then destructs any virtual bases.
1946 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
1947
1948 // The destructor in a virtual table is always a 'deleting'
1949 // destructor, which calls the complete destructor and then uses the
1950 // appropriate operator delete.
1951 if (D->isVirtual())
1952 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
1953}
1954
1955void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1956 QualType &ResTy,
1957 FunctionArgList &Params) {
1958 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
1960
1961 // Check if we need a VTT parameter as well.
1962 if (NeedsVTTParameter(CGF.CurGD)) {
1963 ASTContext &Context = getContext();
1964
1965 // FIXME: avoid the fake decl
1966 LangAS AS = CGM.GetGlobalVarAddressSpace(nullptr);
1967 QualType Q = Context.getAddrSpaceQualType(Context.VoidPtrTy, AS);
1968 QualType T = Context.getPointerType(Q);
1969 auto *VTTDecl = ImplicitParamDecl::Create(
1970 Context, /*DC=*/nullptr, MD->getLocation(), &Context.Idents.get("vtt"),
1971 T, ImplicitParamKind::CXXVTT);
1972 Params.insert(Params.begin() + 1, VTTDecl);
1973 getStructorImplicitParamDecl(CGF) = VTTDecl;
1974 }
1975}
1976
1977void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
1978 // Naked functions have no prolog.
1979 if (CGF.CurFuncDecl && CGF.CurFuncDecl->hasAttr<NakedAttr>())
1980 return;
1981
1982 /// Initialize the 'this' slot. In the Itanium C++ ABI, no prologue
1983 /// adjustments are required, because they are all handled by thunks.
1984 setCXXABIThisValue(CGF, loadIncomingCXXThis(CGF));
1985
1986 /// Initialize the 'vtt' slot if needed.
1987 if (getStructorImplicitParamDecl(CGF)) {
1988 getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
1989 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
1990 }
1991
1992 /// If this is a function that the ABI specifies returns 'this', initialize
1993 /// the return slot to 'this' at the start of the function.
1994 ///
1995 /// Unlike the setting of return types, this is done within the ABI
1996 /// implementation instead of by clients of CGCXXABI because:
1997 /// 1) getThisValue is currently protected
1998 /// 2) in theory, an ABI could implement 'this' returns some other way;
1999 /// HasThisReturn only specifies a contract, not the implementation
2000 if (HasThisReturn(CGF.CurGD))
2001 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
2002}
2003
2004CGCXXABI::AddedStructorArgs ItaniumCXXABI::getImplicitConstructorArgs(
2005 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
2006 bool ForVirtualBase, bool Delegating) {
2007 if (!NeedsVTTParameter(GlobalDecl(D, Type)))
2008 return AddedStructorArgs{};
2009
2010 // Insert the implicit 'vtt' argument as the second argument. Make sure to
2011 // correctly reflect its address space, which can differ from generic on
2012 // some targets.
2013 llvm::Value *VTT =
2014 CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating);
2015 LangAS AS = CGM.GetGlobalVarAddressSpace(nullptr);
2016 QualType Q = getContext().getAddrSpaceQualType(getContext().VoidPtrTy, AS);
2017 QualType VTTTy = getContext().getPointerType(Q);
2018 return AddedStructorArgs::prefix({{VTT, VTTTy}});
2019}
2020
2021llvm::Value *ItaniumCXXABI::getCXXDestructorImplicitParam(
2022 CodeGenFunction &CGF, const CXXDestructorDecl *DD, CXXDtorType Type,
2023 bool ForVirtualBase, bool Delegating) {
2024 GlobalDecl GD(DD, Type);
2025 return CGF.GetVTTParameter(GD, ForVirtualBase, Delegating);
2026}
2027
2028void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
2029 const CXXDestructorDecl *DD,
2030 CXXDtorType Type, bool ForVirtualBase,
2031 bool Delegating, Address This,
2032 QualType ThisTy) {
2033 GlobalDecl GD(DD, Type);
2034 llvm::Value *VTT =
2035 getCXXDestructorImplicitParam(CGF, DD, Type, ForVirtualBase, Delegating);
2036 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
2037
2038 CGCallee Callee;
2039 if (getContext().getLangOpts().AppleKext &&
2040 Type != Dtor_Base && DD->isVirtual())
2042 else
2043 Callee = CGCallee::forDirect(CGM.getAddrOfCXXStructor(GD), GD);
2044
2045 CGF.EmitCXXDestructorCall(GD, Callee, CGF.getAsNaturalPointerTo(This, ThisTy),
2046 ThisTy, VTT, VTTTy, nullptr);
2047}
2048
2049// Check if any non-inline method has the specified attribute.
2050template <typename T>
2052 for (const auto *D : RD->noload_decls()) {
2053 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
2054 if (FD->isInlined() || FD->doesThisDeclarationHaveABody() ||
2055 FD->isPureVirtual())
2056 continue;
2057 if (D->hasAttr<T>())
2058 return true;
2059 }
2060 }
2061
2062 return false;
2063}
2064
2066 llvm::GlobalVariable *VTable,
2067 const CXXRecordDecl *RD) {
2068 if (VTable->getDLLStorageClass() !=
2069 llvm::GlobalVariable::DefaultStorageClass ||
2070 RD->hasAttr<DLLImportAttr>() || RD->hasAttr<DLLExportAttr>())
2071 return;
2072
2073 if (CGM.getVTables().isVTableExternal(RD)) {
2075 VTable->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2077 VTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
2078}
2079
2080void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
2081 const CXXRecordDecl *RD) {
2082 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
2083 if (VTable->hasInitializer())
2084 return;
2085
2086 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
2087 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
2088 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
2089 llvm::Constant *RTTI =
2090 CGM.GetAddrOfRTTIDescriptor(CGM.getContext().getCanonicalTagType(RD));
2091
2092 // Create and set the initializer.
2093 ConstantInitBuilder builder(CGM);
2094 auto components = builder.beginStruct();
2095 CGVT.createVTableInitializer(components, VTLayout, RTTI,
2096 llvm::GlobalValue::isLocalLinkage(Linkage));
2097 components.finishAndSetAsInitializer(VTable);
2098
2099 // Set the correct linkage.
2100 VTable->setLinkage(Linkage);
2101
2102 if (CGM.supportsCOMDAT() && VTable->isWeakForLinker())
2103 VTable->setComdat(CGM.getModule().getOrInsertComdat(VTable->getName()));
2104
2105 if (CGM.getTarget().hasPS4DLLImportExport())
2106 setVTableSelectiveDLLImportExport(CGM, VTable, RD);
2107
2108 // Set the right visibility.
2109 CGM.setGVProperties(VTable, RD);
2110
2111 // If this is the magic class __cxxabiv1::__fundamental_type_info,
2112 // we will emit the typeinfo for the fundamental types. This is the
2113 // same behaviour as GCC.
2114 const DeclContext *DC = RD->getDeclContext();
2115 if (RD->getIdentifier() &&
2116 RD->getIdentifier()->isStr("__fundamental_type_info") &&
2117 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
2118 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
2120 EmitFundamentalRTTIDescriptors(RD);
2121
2122 // Always emit type metadata on non-available_externally definitions, and on
2123 // available_externally definitions if we are performing whole program
2124 // devirtualization or speculative devirtualization. We need the type metadata
2125 // on all vtable definitions to ensure we associate derived classes with base
2126 // classes defined in headers but with a strong definition only in a shared
2127 // library.
2128 if (!VTable->isDeclarationForLinker() ||
2129 CGM.getCodeGenOpts().WholeProgramVTables ||
2130 CGM.getCodeGenOpts().DevirtualizeSpeculatively) {
2131 CGM.EmitVTableTypeMetadata(RD, VTable, VTLayout);
2132 // For available_externally definitions, add the vtable to
2133 // @llvm.compiler.used so that it isn't deleted before whole program
2134 // analysis.
2135 if (VTable->isDeclarationForLinker()) {
2136 assert(CGM.getCodeGenOpts().WholeProgramVTables ||
2137 CGM.getCodeGenOpts().DevirtualizeSpeculatively);
2138 CGM.addCompilerUsedGlobal(VTable);
2139 }
2140 }
2141
2142 if (CGM.getLangOpts().RelativeCXXABIVTables) {
2143 CGVT.RemoveHwasanMetadata(VTable);
2144 if (!VTable->isDSOLocal())
2145 CGVT.GenerateRelativeVTableAlias(VTable, VTable->getName());
2146 }
2147
2148 // Emit symbol for debugger only if requested debug info.
2149 if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
2150 DI->emitVTableSymbol(VTable, RD);
2151}
2152
2153bool ItaniumCXXABI::isVirtualOffsetNeededForVTableField(
2154 CodeGenFunction &CGF, CodeGenFunction::VPtr Vptr) {
2155 if (Vptr.NearestVBase == nullptr)
2156 return false;
2157 return NeedsVTTParameter(CGF.CurGD);
2158}
2159
2160llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
2161 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
2162 const CXXRecordDecl *NearestVBase) {
2163
2164 if ((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
2165 NeedsVTTParameter(CGF.CurGD)) {
2166 return getVTableAddressPointInStructorWithVTT(CGF, VTableClass, Base,
2167 NearestVBase);
2168 }
2169 return getVTableAddressPoint(Base, VTableClass);
2170}
2171
2172llvm::Constant *
2173ItaniumCXXABI::getVTableAddressPoint(BaseSubobject Base,
2174 const CXXRecordDecl *VTableClass) {
2175 llvm::GlobalValue *VTable = getAddrOfVTable(VTableClass, CharUnits());
2176
2177 // Find the appropriate vtable within the vtable group, and the address point
2178 // within that vtable.
2179 const VTableLayout &Layout =
2180 CGM.getItaniumVTableContext().getVTableLayout(VTableClass);
2181 VTableLayout::AddressPointLocation AddressPoint =
2182 Layout.getAddressPoint(Base);
2183 llvm::Value *Indices[] = {
2184 llvm::ConstantInt::get(CGM.Int32Ty, 0),
2185 llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint.VTableIndex),
2186 llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint.AddressPointIndex),
2187 };
2188
2189 // Add inrange attribute to indicate that only the VTableIndex can be
2190 // accessed.
2191 unsigned ComponentSize =
2192 CGM.getDataLayout().getTypeAllocSize(CGM.getVTableComponentType());
2193 unsigned VTableSize =
2194 ComponentSize * Layout.getVTableSize(AddressPoint.VTableIndex);
2195 unsigned Offset = ComponentSize * AddressPoint.AddressPointIndex;
2196 llvm::ConstantRange InRange(
2197 llvm::APInt(32, (int)-Offset, true),
2198 llvm::APInt(32, (int)(VTableSize - Offset), true));
2199 return llvm::ConstantExpr::getGetElementPtr(
2200 VTable->getValueType(), VTable, Indices, /*InBounds=*/true, InRange);
2201}
2202
2203llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructorWithVTT(
2204 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
2205 const CXXRecordDecl *NearestVBase) {
2206 assert((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
2207 NeedsVTTParameter(CGF.CurGD) && "This class doesn't have VTT");
2208
2209 // Get the secondary vpointer index.
2210 uint64_t VirtualPointerIndex =
2211 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
2212
2213 /// Load the VTT.
2214 llvm::Value *VTT = CGF.LoadCXXVTT();
2215 if (VirtualPointerIndex)
2216 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(CGF.GlobalsVoidPtrTy, VTT,
2217 VirtualPointerIndex);
2218
2219 // And load the address point from the VTT.
2220 llvm::Value *AP =
2222 CGF.getPointerAlign());
2223
2224 if (auto &Schema = CGF.CGM.getCodeGenOpts().PointerAuth.CXXVTTVTablePointers) {
2225 CGPointerAuthInfo PointerAuth = CGF.EmitPointerAuthInfo(Schema, VTT,
2226 GlobalDecl(),
2227 QualType());
2228 AP = CGF.EmitPointerAuthAuth(PointerAuth, AP);
2229 }
2230
2231 return AP;
2232}
2233
2234llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
2235 CharUnits VPtrOffset) {
2236 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
2237
2238 llvm::GlobalVariable *&VTable = VTables[RD];
2239 if (VTable)
2240 return VTable;
2241
2242 // Queue up this vtable for possible deferred emission.
2243 CGM.addDeferredVTable(RD);
2244
2245 SmallString<256> Name;
2246 llvm::raw_svector_ostream Out(Name);
2247 getMangleContext().mangleCXXVTable(RD, Out);
2248
2249 const VTableLayout &VTLayout =
2250 CGM.getItaniumVTableContext().getVTableLayout(RD);
2251 llvm::Type *VTableType = CGM.getVTables().getVTableType(VTLayout);
2252
2253 // Use pointer to global alignment for the vtable. Otherwise we would align
2254 // them based on the size of the initializer which doesn't make sense as only
2255 // single values are read.
2256 unsigned PAlign = CGM.getVtableGlobalVarAlignment();
2257
2258 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
2259 Name, VTableType, llvm::GlobalValue::ExternalLinkage,
2260 getContext().toCharUnitsFromBits(PAlign).getAsAlign());
2261
2262 if (CGM.getTarget().hasPS4DLLImportExport())
2263 setVTableSelectiveDLLImportExport(CGM, VTable, RD);
2264
2265 CGM.setGVProperties(VTable, RD);
2266 return VTable;
2267}
2268
2269CGCallee ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
2270 GlobalDecl GD,
2271 Address This,
2272 llvm::Type *Ty,
2273 SourceLocation Loc) {
2274 llvm::Type *PtrTy = CGM.GlobalsInt8PtrTy;
2275 auto *MethodDecl = cast<CXXMethodDecl>(GD.getDecl());
2276 llvm::Value *VTable = CGF.GetVTablePtr(This, PtrTy, MethodDecl->getParent());
2277
2278 // For the translation of virtual functions, we need to map the (potential)
2279 // host vtable to the device vtable. This is done by calling the runtime
2280 // function
2281 // __llvm_omp_indirect_call_lookup.
2282 if (CGM.getLangOpts().OpenMPIsTargetDevice) {
2283 auto *NewPtrTy = CGM.VoidPtrTy;
2284 llvm::Type *RtlFnArgs[] = {NewPtrTy};
2285 llvm::FunctionCallee DeviceRtlFn = CGM.CreateRuntimeFunction(
2286 llvm::FunctionType::get(NewPtrTy, RtlFnArgs, false),
2287 "__llvm_omp_indirect_call_lookup");
2288 auto *BackupTy = VTable->getType();
2289 // Need to convert to generic address space
2290 VTable = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(VTable, NewPtrTy);
2291 VTable = CGF.EmitRuntimeCall(DeviceRtlFn, {VTable});
2292 // convert to original address space
2293 VTable = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(VTable, BackupTy);
2294 }
2295
2296 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
2297 llvm::Value *VFunc, *VTableSlotPtr = nullptr;
2298 auto &Schema = CGM.getCodeGenOpts().PointerAuth.CXXVirtualFunctionPointers;
2299
2300 llvm::Type *ComponentTy = CGM.getVTables().getVTableComponentType();
2301 uint64_t ByteOffset =
2302 VTableIndex * CGM.getDataLayout().getTypeSizeInBits(ComponentTy) / 8;
2303
2304 if (!Schema && CGF.ShouldEmitVTableTypeCheckedLoad(MethodDecl->getParent())) {
2305 VFunc = CGF.EmitVTableTypeCheckedLoad(MethodDecl->getParent(), VTable,
2306 PtrTy, ByteOffset);
2307 } else {
2308 CGF.EmitTypeMetadataCodeForVCall(MethodDecl->getParent(), VTable, Loc);
2309
2310 llvm::Value *VFuncLoad;
2311 if (CGM.getLangOpts().RelativeCXXABIVTables) {
2312 VFuncLoad = CGF.Builder.CreateCall(
2313 CGM.getIntrinsic(llvm::Intrinsic::load_relative, {CGM.Int32Ty}),
2314 {VTable, llvm::ConstantInt::get(CGM.Int32Ty, ByteOffset)});
2315 } else {
2316 VTableSlotPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
2317 PtrTy, VTable, VTableIndex, "vfn");
2318 VFuncLoad = CGF.Builder.CreateAlignedLoad(PtrTy, VTableSlotPtr,
2319 CGF.getPointerAlign());
2320 }
2321
2322 // Add !invariant.load md to virtual function load to indicate that
2323 // function didn't change inside vtable.
2324 // It's safe to add it without -fstrict-vtable-pointers, but it would not
2325 // help in devirtualization because it will only matter if we will have 2
2326 // the same virtual function loads from the same vtable load, which won't
2327 // happen without enabled devirtualization with -fstrict-vtable-pointers.
2328 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2329 CGM.getCodeGenOpts().StrictVTablePointers) {
2330 if (auto *VFuncLoadInstr = dyn_cast<llvm::Instruction>(VFuncLoad)) {
2331 VFuncLoadInstr->setMetadata(
2332 llvm::LLVMContext::MD_invariant_load,
2333 llvm::MDNode::get(CGM.getLLVMContext(),
2334 llvm::ArrayRef<llvm::Metadata *>()));
2335 }
2336 }
2337 VFunc = VFuncLoad;
2338 }
2339
2340 CGPointerAuthInfo PointerAuth;
2341 if (Schema) {
2342 assert(VTableSlotPtr && "virtual function pointer not set");
2343 GD = CGM.getItaniumVTableContext().findOriginalMethod(GD.getCanonicalDecl());
2344 PointerAuth = CGF.EmitPointerAuthInfo(Schema, VTableSlotPtr, GD, QualType());
2345 }
2346 CGCallee Callee(GD, VFunc, PointerAuth);
2347 return Callee;
2348}
2349
2350llvm::Value *ItaniumCXXABI::EmitVirtualDestructorCall(
2351 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
2352 Address This, DeleteOrMemberCallExpr E, llvm::CallBase **CallOrInvoke) {
2353 auto *CE = dyn_cast<const CXXMemberCallExpr *>(E);
2354 auto *D = dyn_cast<const CXXDeleteExpr *>(E);
2355 assert((CE != nullptr) ^ (D != nullptr));
2356 assert(CE == nullptr || CE->arguments().empty());
2357 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
2358
2359 GlobalDecl GD(Dtor, DtorType);
2360 const CGFunctionInfo *FInfo =
2361 &CGM.getTypes().arrangeCXXStructorDeclaration(GD);
2362 llvm::FunctionType *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
2363 CGCallee Callee = CGCallee::forVirtual(CE, GD, This, Ty);
2364
2365 QualType ThisTy;
2366 if (CE) {
2367 ThisTy = CE->getObjectType();
2368 } else {
2369 ThisTy = D->getDestroyedType();
2370 }
2371
2372 CGF.EmitCXXDestructorCall(GD, Callee, This.emitRawPointer(CGF), ThisTy,
2373 nullptr, QualType(), nullptr, CallOrInvoke);
2374 return nullptr;
2375}
2376
2377void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
2378 CodeGenVTables &VTables = CGM.getVTables();
2379 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
2380 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
2381}
2382
2383bool ItaniumCXXABI::canSpeculativelyEmitVTableAsBaseClass(
2384 const CXXRecordDecl *RD) const {
2385 // We don't emit available_externally vtables if we are in -fapple-kext mode
2386 // because kext mode does not permit devirtualization.
2387 if (CGM.getLangOpts().AppleKext)
2388 return false;
2389
2390 // If the vtable is hidden then it is not safe to emit an available_externally
2391 // copy of vtable.
2392 if (isVTableHidden(RD))
2393 return false;
2394
2395 if (CGM.getCodeGenOpts().ForceEmitVTables)
2396 return true;
2397
2398 // A speculative vtable can only be generated if all virtual inline functions
2399 // defined by this class are emitted. The vtable in the final program contains
2400 // for each virtual inline function not used in the current TU a function that
2401 // is equivalent to the unused function. The function in the actual vtable
2402 // does not have to be declared under the same symbol (e.g., a virtual
2403 // destructor that can be substituted with its base class's destructor). Since
2404 // inline functions are emitted lazily and this emissions does not account for
2405 // speculative emission of a vtable, we might generate a speculative vtable
2406 // with references to inline functions that are not emitted under that name.
2407 // This can lead to problems when devirtualizing a call to such a function,
2408 // that result in linking errors. Hence, if there are any unused virtual
2409 // inline function, we cannot emit the speculative vtable.
2410 // FIXME we can still emit a copy of the vtable if we
2411 // can emit definition of the inline functions.
2412 if (hasAnyUnusedVirtualInlineFunction(RD))
2413 return false;
2414
2415 // For a class with virtual bases, we must also be able to speculatively
2416 // emit the VTT, because CodeGen doesn't have separate notions of "can emit
2417 // the vtable" and "can emit the VTT". For a base subobject, this means we
2418 // need to be able to emit non-virtual base vtables.
2419 if (RD->getNumVBases()) {
2420 for (const auto &B : RD->bases()) {
2421 auto *BRD = B.getType()->getAsCXXRecordDecl();
2422 assert(BRD && "no class for base specifier");
2423 if (B.isVirtual() || !BRD->isDynamicClass())
2424 continue;
2425 if (!canSpeculativelyEmitVTableAsBaseClass(BRD))
2426 return false;
2427 }
2428 }
2429
2430 return true;
2431}
2432
2433bool ItaniumCXXABI::canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const {
2434 if (!canSpeculativelyEmitVTableAsBaseClass(RD))
2435 return false;
2436
2438 return false;
2439
2440 // For a complete-object vtable (or more specifically, for the VTT), we need
2441 // to be able to speculatively emit the vtables of all dynamic virtual bases.
2442 for (const auto &B : RD->vbases()) {
2443 auto *BRD = B.getType()->getAsCXXRecordDecl();
2444 assert(BRD && "no class for base specifier");
2445 if (!BRD->isDynamicClass())
2446 continue;
2447 if (!canSpeculativelyEmitVTableAsBaseClass(BRD))
2448 return false;
2449 }
2450
2451 return true;
2452}
2454 Address InitialPtr,
2455 const CXXRecordDecl *UnadjustedClass,
2456 int64_t NonVirtualAdjustment,
2457 int64_t VirtualAdjustment,
2458 bool IsReturnAdjustment) {
2459 if (!NonVirtualAdjustment && !VirtualAdjustment)
2460 return InitialPtr.emitRawPointer(CGF);
2461
2462 Address V = InitialPtr.withElementType(CGF.Int8Ty);
2463
2464 // In a base-to-derived cast, the non-virtual adjustment is applied first.
2465 if (NonVirtualAdjustment && !IsReturnAdjustment) {
2467 CharUnits::fromQuantity(NonVirtualAdjustment));
2468 }
2469
2470 // Perform the virtual adjustment if we have one.
2471 llvm::Value *ResultPtr;
2472 if (VirtualAdjustment) {
2473 llvm::Value *VTablePtr =
2474 CGF.GetVTablePtr(V, CGF.Int8PtrTy, UnadjustedClass);
2475
2476 llvm::Value *Offset;
2477 llvm::Value *OffsetPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
2478 CGF.Int8Ty, VTablePtr, VirtualAdjustment);
2479 if (CGF.CGM.getLangOpts().RelativeCXXABIVTables) {
2480 // Load the adjustment offset from the vtable as a 32-bit int.
2481 Offset =
2482 CGF.Builder.CreateAlignedLoad(CGF.Int32Ty, OffsetPtr,
2484 } else {
2485 llvm::Type *PtrDiffTy =
2487
2488 // Load the adjustment offset from the vtable.
2489 Offset = CGF.Builder.CreateAlignedLoad(PtrDiffTy, OffsetPtr,
2490 CGF.getPointerAlign());
2491 }
2492 // Adjust our pointer.
2493 ResultPtr = CGF.Builder.CreateInBoundsGEP(V.getElementType(),
2494 V.emitRawPointer(CGF), Offset);
2495 } else {
2496 ResultPtr = V.emitRawPointer(CGF);
2497 }
2498
2499 // In a derived-to-base conversion, the non-virtual adjustment is
2500 // applied second.
2501 if (NonVirtualAdjustment && IsReturnAdjustment) {
2502 ResultPtr = CGF.Builder.CreateConstInBoundsGEP1_64(CGF.Int8Ty, ResultPtr,
2503 NonVirtualAdjustment);
2504 }
2505
2506 return ResultPtr;
2507}
2508
2509llvm::Value *
2510ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF, Address This,
2511 const CXXRecordDecl *UnadjustedClass,
2512 const ThunkInfo &TI) {
2513 return performTypeAdjustment(CGF, This, UnadjustedClass, TI.This.NonVirtual,
2515 /*IsReturnAdjustment=*/false);
2516}
2517
2518llvm::Value *
2519ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
2520 const CXXRecordDecl *UnadjustedClass,
2521 const ReturnAdjustment &RA) {
2522 return performTypeAdjustment(CGF, Ret, UnadjustedClass, RA.NonVirtual,
2524 /*IsReturnAdjustment=*/true);
2525}
2526
2527void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
2528 RValue RV, QualType ResultType) {
2530 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
2531
2532 // Destructor thunks in the ARM ABI have indeterminate results.
2533 llvm::Type *T = CGF.ReturnValue.getElementType();
2534 RValue Undef = RValue::get(llvm::UndefValue::get(T));
2535 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
2536}
2537
2538/************************** Array allocation cookies **************************/
2539
2540CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
2541 // The array cookie is a size_t; pad that up to the element alignment.
2542 // The cookie is actually right-justified in that space.
2543 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
2544 CGM.getContext().getPreferredTypeAlignInChars(elementType));
2545}
2546
2547Address ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
2548 Address NewPtr,
2549 llvm::Value *NumElements,
2550 const CXXNewExpr *expr,
2551 QualType ElementType) {
2552 assert(requiresArrayCookie(expr));
2553
2554 unsigned AS = NewPtr.getAddressSpace();
2555
2556 ASTContext &Ctx = getContext();
2557 CharUnits SizeSize = CGF.getSizeSize();
2558
2559 // The size of the cookie.
2560 CharUnits CookieSize =
2561 std::max(SizeSize, Ctx.getPreferredTypeAlignInChars(ElementType));
2562 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
2563
2564 // Compute an offset to the cookie.
2565 Address CookiePtr = NewPtr;
2566 CharUnits CookieOffset = CookieSize - SizeSize;
2567 if (!CookieOffset.isZero())
2568 CookiePtr = CGF.Builder.CreateConstInBoundsByteGEP(CookiePtr, CookieOffset);
2569
2570 // Write the number of elements into the appropriate slot.
2571 Address NumElementsPtr = CookiePtr.withElementType(CGF.SizeTy);
2572 llvm::Instruction *SI = CGF.Builder.CreateStore(NumElements, NumElementsPtr);
2573
2574 // Handle the array cookie specially in ASan.
2575 if (CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) && AS == 0 &&
2576 (expr->getOperatorNew()->isReplaceableGlobalAllocationFunction() ||
2577 CGM.getCodeGenOpts().SanitizeAddressPoisonCustomArrayCookie)) {
2578 // The store to the CookiePtr does not need to be instrumented.
2579 SI->setNoSanitizeMetadata();
2580 llvm::FunctionType *FTy =
2581 llvm::FunctionType::get(CGM.VoidTy, NumElementsPtr.getType(), false);
2582 llvm::FunctionCallee F =
2583 CGM.CreateRuntimeFunction(FTy, "__asan_poison_cxx_array_cookie");
2584 CGF.Builder.CreateCall(F, NumElementsPtr.emitRawPointer(CGF));
2585 }
2586
2587 // Finally, compute a pointer to the actual data buffer by skipping
2588 // over the cookie completely.
2589 return CGF.Builder.CreateConstInBoundsByteGEP(NewPtr, CookieSize);
2590}
2591
2592llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
2593 Address allocPtr,
2594 CharUnits cookieSize) {
2595 // The element size is right-justified in the cookie.
2596 Address numElementsPtr = allocPtr;
2597 CharUnits numElementsOffset = cookieSize - CGF.getSizeSize();
2598 if (!numElementsOffset.isZero())
2599 numElementsPtr =
2600 CGF.Builder.CreateConstInBoundsByteGEP(numElementsPtr, numElementsOffset);
2601
2602 unsigned AS = allocPtr.getAddressSpace();
2603 numElementsPtr = numElementsPtr.withElementType(CGF.SizeTy);
2604 if (!CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) || AS != 0)
2605 return CGF.Builder.CreateLoad(numElementsPtr);
2606 // In asan mode emit a function call instead of a regular load and let the
2607 // run-time deal with it: if the shadow is properly poisoned return the
2608 // cookie, otherwise return 0 to avoid an infinite loop calling DTORs.
2609 // We can't simply ignore this load using nosanitize metadata because
2610 // the metadata may be lost.
2611 llvm::FunctionType *FTy =
2612 llvm::FunctionType::get(CGF.SizeTy, CGF.DefaultPtrTy, false);
2613 llvm::FunctionCallee F =
2614 CGM.CreateRuntimeFunction(FTy, "__asan_load_cxx_array_cookie");
2615 return CGF.Builder.CreateCall(F, numElementsPtr.emitRawPointer(CGF));
2616}
2617
2618CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
2619 // ARM says that the cookie is always:
2620 // struct array_cookie {
2621 // std::size_t element_size; // element_size != 0
2622 // std::size_t element_count;
2623 // };
2624 // But the base ABI doesn't give anything an alignment greater than
2625 // 8, so we can dismiss this as typical ABI-author blindness to
2626 // actual language complexity and round up to the element alignment.
2627 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
2628 CGM.getContext().getTypeAlignInChars(elementType));
2629}
2630
2631Address ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
2632 Address newPtr,
2633 llvm::Value *numElements,
2634 const CXXNewExpr *expr,
2635 QualType elementType) {
2636 assert(requiresArrayCookie(expr));
2637
2638 // The cookie is always at the start of the buffer.
2639 Address cookie = newPtr;
2640
2641 // The first element is the element size.
2642 cookie = cookie.withElementType(CGF.SizeTy);
2643 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
2644 getContext().getTypeSizeInChars(elementType).getQuantity());
2645 CGF.Builder.CreateStore(elementSize, cookie);
2646
2647 // The second element is the element count.
2648 cookie = CGF.Builder.CreateConstInBoundsGEP(cookie, 1);
2649 CGF.Builder.CreateStore(numElements, cookie);
2650
2651 // Finally, compute a pointer to the actual data buffer by skipping
2652 // over the cookie completely.
2653 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
2654 return CGF.Builder.CreateConstInBoundsByteGEP(newPtr, cookieSize);
2655}
2656
2657llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
2658 Address allocPtr,
2659 CharUnits cookieSize) {
2660 // The number of elements is at offset sizeof(size_t) relative to
2661 // the allocated pointer.
2662 Address numElementsPtr
2663 = CGF.Builder.CreateConstInBoundsByteGEP(allocPtr, CGF.getSizeSize());
2664
2665 numElementsPtr = numElementsPtr.withElementType(CGF.SizeTy);
2666 return CGF.Builder.CreateLoad(numElementsPtr);
2667}
2668
2669/*********************** Static local initialization **************************/
2670
2671static llvm::FunctionCallee getGuardAcquireFn(CodeGenModule &CGM,
2672 llvm::PointerType *GuardPtrTy) {
2673 // int __cxa_guard_acquire(__guard *guard_object);
2674 llvm::FunctionType *FTy =
2675 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
2676 GuardPtrTy, /*isVarArg=*/false);
2677 return CGM.CreateRuntimeFunction(
2678 FTy, "__cxa_guard_acquire",
2679 llvm::AttributeList::get(CGM.getLLVMContext(),
2680 llvm::AttributeList::FunctionIndex,
2681 llvm::Attribute::NoUnwind));
2682}
2683
2684static llvm::FunctionCallee getGuardReleaseFn(CodeGenModule &CGM,
2685 llvm::PointerType *GuardPtrTy) {
2686 // void __cxa_guard_release(__guard *guard_object);
2687 llvm::FunctionType *FTy =
2688 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
2689 return CGM.CreateRuntimeFunction(
2690 FTy, "__cxa_guard_release",
2691 llvm::AttributeList::get(CGM.getLLVMContext(),
2692 llvm::AttributeList::FunctionIndex,
2693 llvm::Attribute::NoUnwind));
2694}
2695
2696static llvm::FunctionCallee getGuardAbortFn(CodeGenModule &CGM,
2697 llvm::PointerType *GuardPtrTy) {
2698 // void __cxa_guard_abort(__guard *guard_object);
2699 llvm::FunctionType *FTy =
2700 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
2701 return CGM.CreateRuntimeFunction(
2702 FTy, "__cxa_guard_abort",
2703 llvm::AttributeList::get(CGM.getLLVMContext(),
2704 llvm::AttributeList::FunctionIndex,
2705 llvm::Attribute::NoUnwind));
2706}
2707
2708namespace {
2709 struct CallGuardAbort final : EHScopeStack::Cleanup {
2710 llvm::GlobalVariable *Guard;
2711 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
2712
2713 void Emit(CodeGenFunction &CGF, Flags flags) override {
2714 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
2715 Guard);
2716 }
2717 };
2718}
2719
2720/// The ARM code here follows the Itanium code closely enough that we
2721/// just special-case it at particular places.
2722void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
2723 const VarDecl &D,
2724 llvm::GlobalVariable *var,
2725 bool shouldPerformInit) {
2726 CGBuilderTy &Builder = CGF.Builder;
2727
2728 // Inline variables that weren't instantiated from variable templates have
2729 // partially-ordered initialization within their translation unit.
2730 bool NonTemplateInline =
2731 D.isInline() &&
2733
2734 // We only need to use thread-safe statics for local non-TLS variables and
2735 // inline variables; other global initialization is always single-threaded
2736 // or (through lazy dynamic loading in multiple threads) unsequenced.
2737 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
2738 (D.isLocalVarDecl() || NonTemplateInline) &&
2739 !D.getTLSKind();
2740
2741 // If we have a global variable with internal linkage and thread-safe statics
2742 // are disabled, we can just let the guard variable be of type i8.
2743 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
2744
2745 llvm::IntegerType *guardTy;
2746 CharUnits guardAlignment;
2747 if (useInt8GuardVariable) {
2748 guardTy = CGF.Int8Ty;
2749 guardAlignment = CharUnits::One();
2750 } else {
2751 // Guard variables are 64 bits in the generic ABI and size width on ARM
2752 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
2753 if (UseARMGuardVarABI) {
2754 guardTy = CGF.SizeTy;
2755 guardAlignment = CGF.getSizeAlign();
2756 } else {
2757 guardTy = CGF.Int64Ty;
2758 guardAlignment =
2759 CharUnits::fromQuantity(CGM.getDataLayout().getABITypeAlign(guardTy));
2760 }
2761 }
2762 llvm::PointerType *guardPtrTy = llvm::PointerType::get(
2763 CGF.CGM.getLLVMContext(),
2764 CGF.CGM.getDataLayout().getDefaultGlobalsAddressSpace());
2765
2766 // Create the guard variable if we don't already have it (as we
2767 // might if we're double-emitting this function body).
2768 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
2769 if (!guard) {
2770 // Mangle the name for the guard.
2771 SmallString<256> guardName;
2772 {
2773 llvm::raw_svector_ostream out(guardName);
2774 getMangleContext().mangleStaticGuardVariable(&D, out);
2775 }
2776
2777 // Create the guard variable with a zero-initializer.
2778 // Just absorb linkage, visibility and dll storage class from the guarded
2779 // variable.
2780 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
2781 false, var->getLinkage(),
2782 llvm::ConstantInt::get(guardTy, 0),
2783 guardName.str());
2784 guard->setDSOLocal(var->isDSOLocal());
2785 guard->setVisibility(var->getVisibility());
2786 guard->setDLLStorageClass(var->getDLLStorageClass());
2787 // If the variable is thread-local, so is its guard variable.
2788 guard->setThreadLocalMode(var->getThreadLocalMode());
2789 guard->setAlignment(guardAlignment.getAsAlign());
2790
2791 // The ABI says: "It is suggested that it be emitted in the same COMDAT
2792 // group as the associated data object." In practice, this doesn't work for
2793 // non-ELF and non-Wasm object formats, so only do it for ELF and Wasm.
2794 llvm::Comdat *C = var->getComdat();
2795 if (!D.isLocalVarDecl() && C &&
2796 (CGM.getTarget().getTriple().isOSBinFormatELF() ||
2797 CGM.getTarget().getTriple().isOSBinFormatWasm())) {
2798 guard->setComdat(C);
2799 } else if (CGM.supportsCOMDAT() && guard->isWeakForLinker()) {
2800 guard->setComdat(CGM.getModule().getOrInsertComdat(guard->getName()));
2801 }
2802
2803 CGM.setStaticLocalDeclGuardAddress(&D, guard);
2804 }
2805
2806 Address guardAddr = Address(guard, guard->getValueType(), guardAlignment);
2807
2808 // Test whether the variable has completed initialization.
2809 //
2810 // Itanium C++ ABI 3.3.2:
2811 // The following is pseudo-code showing how these functions can be used:
2812 // if (obj_guard.first_byte == 0) {
2813 // if ( __cxa_guard_acquire (&obj_guard) ) {
2814 // try {
2815 // ... initialize the object ...;
2816 // } catch (...) {
2817 // __cxa_guard_abort (&obj_guard);
2818 // throw;
2819 // }
2820 // ... queue object destructor with __cxa_atexit() ...;
2821 // __cxa_guard_release (&obj_guard);
2822 // }
2823 // }
2824 //
2825 // If threadsafe statics are enabled, but we don't have inline atomics, just
2826 // call __cxa_guard_acquire unconditionally. The "inline" check isn't
2827 // actually inline, and the user might not expect calls to __atomic libcalls.
2828
2829 unsigned MaxInlineWidthInBits = CGF.getTarget().getMaxAtomicInlineWidth();
2830 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2831 if (!threadsafe || MaxInlineWidthInBits) {
2832 // Load the first byte of the guard variable.
2833 llvm::LoadInst *LI =
2834 Builder.CreateLoad(guardAddr.withElementType(CGM.Int8Ty));
2835
2836 // Itanium ABI:
2837 // An implementation supporting thread-safety on multiprocessor
2838 // systems must also guarantee that references to the initialized
2839 // object do not occur before the load of the initialization flag.
2840 //
2841 // In LLVM, we do this by marking the load Acquire.
2842 if (threadsafe)
2843 LI->setAtomic(llvm::AtomicOrdering::Acquire);
2844
2845 // For ARM, we should only check the first bit, rather than the entire byte:
2846 //
2847 // ARM C++ ABI 3.2.3.1:
2848 // To support the potential use of initialization guard variables
2849 // as semaphores that are the target of ARM SWP and LDREX/STREX
2850 // synchronizing instructions we define a static initialization
2851 // guard variable to be a 4-byte aligned, 4-byte word with the
2852 // following inline access protocol.
2853 // #define INITIALIZED 1
2854 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
2855 // if (__cxa_guard_acquire(&obj_guard))
2856 // ...
2857 // }
2858 //
2859 // and similarly for ARM64:
2860 //
2861 // ARM64 C++ ABI 3.2.2:
2862 // This ABI instead only specifies the value bit 0 of the static guard
2863 // variable; all other bits are platform defined. Bit 0 shall be 0 when the
2864 // variable is not initialized and 1 when it is.
2865 llvm::Value *V =
2866 (UseARMGuardVarABI && !useInt8GuardVariable)
2867 ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1))
2868 : LI;
2869 llvm::Value *NeedsInit = Builder.CreateIsNull(V, "guard.uninitialized");
2870
2871 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
2872
2873 // Check if the first byte of the guard variable is zero.
2874 CGF.EmitCXXGuardedInitBranch(NeedsInit, InitCheckBlock, EndBlock,
2875 CodeGenFunction::GuardKind::VariableGuard, &D);
2876
2877 CGF.EmitBlock(InitCheckBlock);
2878 }
2879
2880 // The semantics of dynamic initialization of variables with static or thread
2881 // storage duration depends on whether they are declared at block-scope. The
2882 // initialization of such variables at block-scope can be aborted with an
2883 // exception and later retried (per C++20 [stmt.dcl]p4), and recursive entry
2884 // to their initialization has undefined behavior (also per C++20
2885 // [stmt.dcl]p4). For such variables declared at non-block scope, exceptions
2886 // lead to termination (per C++20 [except.terminate]p1), and recursive
2887 // references to the variables are governed only by the lifetime rules (per
2888 // C++20 [class.cdtor]p2), which means such references are perfectly fine as
2889 // long as they avoid touching memory. As a result, block-scope variables must
2890 // not be marked as initialized until after initialization completes (unless
2891 // the mark is reverted following an exception), but non-block-scope variables
2892 // must be marked prior to initialization so that recursive accesses during
2893 // initialization do not restart initialization.
2894
2895 // Variables used when coping with thread-safe statics and exceptions.
2896 if (threadsafe) {
2897 // Call __cxa_guard_acquire.
2898 llvm::Value *V
2899 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
2900
2901 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
2902
2903 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
2904 InitBlock, EndBlock);
2905
2906 // Call __cxa_guard_abort along the exceptional edge.
2907 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
2908
2909 CGF.EmitBlock(InitBlock);
2910 } else if (!D.isLocalVarDecl()) {
2911 // For non-local variables, store 1 into the first byte of the guard
2912 // variable before the object initialization begins so that references
2913 // to the variable during initialization don't restart initialization.
2914 Builder.CreateStore(llvm::ConstantInt::get(CGM.Int8Ty, 1),
2915 guardAddr.withElementType(CGM.Int8Ty));
2916 }
2917
2918 // Emit the initializer and add a global destructor if appropriate.
2919 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
2920
2921 if (threadsafe) {
2922 // Pop the guard-abort cleanup if we pushed one.
2923 CGF.PopCleanupBlock();
2924
2925 // Call __cxa_guard_release. This cannot throw.
2926 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy),
2927 guardAddr.emitRawPointer(CGF));
2928 } else if (D.isLocalVarDecl()) {
2929 // For local variables, store 1 into the first byte of the guard variable
2930 // after the object initialization completes so that initialization is
2931 // retried if initialization is interrupted by an exception.
2932 Builder.CreateStore(llvm::ConstantInt::get(CGM.Int8Ty, 1),
2933 guardAddr.withElementType(CGM.Int8Ty));
2934 }
2935
2936 CGF.EmitBlock(EndBlock);
2937}
2938
2939/// Register a global destructor using __cxa_atexit.
2941 llvm::FunctionCallee dtor,
2942 llvm::Constant *addr, bool TLS) {
2943 assert(!CGF.getTarget().getTriple().isOSAIX() &&
2944 "unexpected call to emitGlobalDtorWithCXAAtExit");
2945 assert((TLS || CGF.getTypes().getCodeGenOpts().CXAAtExit) &&
2946 "__cxa_atexit is disabled");
2947 const char *Name = "__cxa_atexit";
2948 if (TLS) {
2949 const llvm::Triple &T = CGF.getTarget().getTriple();
2950 Name = T.isOSDarwin() ? "_tlv_atexit" : "__cxa_thread_atexit";
2951 }
2952
2953 // We're assuming that the destructor function is something we can
2954 // reasonably call with the default CC.
2955 llvm::Type *dtorTy = CGF.DefaultPtrTy;
2956
2957 // Preserve address space of addr.
2958 auto AddrAS = addr ? addr->getType()->getPointerAddressSpace() : 0;
2959 auto AddrPtrTy = AddrAS ? llvm::PointerType::get(CGF.getLLVMContext(), AddrAS)
2960 : CGF.Int8PtrTy;
2961
2962 // Create a variable that binds the atexit to this shared object.
2963 llvm::Constant *handle =
2964 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
2965 auto *GV = cast<llvm::GlobalValue>(handle->stripPointerCasts());
2966 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
2967
2968 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
2969 llvm::Type *paramTys[] = {dtorTy, AddrPtrTy, handle->getType()};
2970 llvm::FunctionType *atexitTy =
2971 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
2972
2973 // Fetch the actual function.
2974 llvm::FunctionCallee atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
2975 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit.getCallee()))
2976 fn->setDoesNotThrow();
2977
2978 const auto &Context = CGF.CGM.getContext();
2979 FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention(
2980 /*IsVariadic=*/false, /*IsCXXMethod=*/false));
2981 QualType fnType =
2982 Context.getFunctionType(Context.VoidTy, {Context.VoidPtrTy}, EPI);
2983 llvm::Value *dtorCallee = dtor.getCallee();
2984 dtorCallee =
2985 CGF.CGM.getFunctionPointer(cast<llvm::Constant>(dtorCallee), fnType);
2986
2987 if (dtorCallee->getType()->getPointerAddressSpace() != AddrAS)
2988 dtorCallee = CGF.performAddrSpaceCast(dtorCallee, AddrPtrTy);
2989
2990 if (!addr)
2991 // addr is null when we are trying to register a dtor annotated with
2992 // __attribute__((destructor)) in a constructor function. Using null here is
2993 // okay because this argument is just passed back to the destructor
2994 // function.
2995 addr = llvm::Constant::getNullValue(CGF.Int8PtrTy);
2996
2997 llvm::Value *args[] = {dtorCallee, addr, handle};
2998 CGF.EmitNounwindRuntimeCall(atexit, args);
2999}
3000
3002 StringRef FnName) {
3003 // Create a function that registers/unregisters destructors that have the same
3004 // priority.
3005 llvm::FunctionType *FTy = llvm::FunctionType::get(CGM.VoidTy, false);
3006 llvm::Function *GlobalInitOrCleanupFn = CGM.CreateGlobalInitOrCleanUpFunction(
3007 FTy, FnName, CGM.getTypes().arrangeNullaryFunction(), SourceLocation());
3008
3009 return GlobalInitOrCleanupFn;
3010}
3011
3012void CodeGenModule::unregisterGlobalDtorsWithUnAtExit() {
3013 for (const auto &I : DtorsUsingAtExit) {
3014 int Priority = I.first;
3015 std::string GlobalCleanupFnName =
3016 std::string("__GLOBAL_cleanup_") + llvm::to_string(Priority);
3017
3018 llvm::Function *GlobalCleanupFn =
3019 createGlobalInitOrCleanupFn(*this, GlobalCleanupFnName);
3020
3021 CodeGenFunction CGF(*this);
3022 CGF.StartFunction(GlobalDecl(), getContext().VoidTy, GlobalCleanupFn,
3023 getTypes().arrangeNullaryFunction(), FunctionArgList(),
3024 SourceLocation(), SourceLocation());
3026
3027 // Get the destructor function type, void(*)(void).
3028 llvm::FunctionType *dtorFuncTy = llvm::FunctionType::get(CGF.VoidTy, false);
3029
3030 // Destructor functions are run/unregistered in non-ascending
3031 // order of their priorities.
3032 const llvm::TinyPtrVector<llvm::Function *> &Dtors = I.second;
3033 auto itv = Dtors.rbegin();
3034 while (itv != Dtors.rend()) {
3035 llvm::Function *Dtor = *itv;
3036
3037 // We're assuming that the destructor function is something we can
3038 // reasonably call with the correct CC.
3039 llvm::Value *V = CGF.unregisterGlobalDtorWithUnAtExit(Dtor);
3040 llvm::Value *NeedsDestruct =
3041 CGF.Builder.CreateIsNull(V, "needs_destruct");
3042
3043 llvm::BasicBlock *DestructCallBlock =
3044 CGF.createBasicBlock("destruct.call");
3045 llvm::BasicBlock *EndBlock = CGF.createBasicBlock(
3046 (itv + 1) != Dtors.rend() ? "unatexit.call" : "destruct.end");
3047 // Check if unatexit returns a value of 0. If it does, jump to
3048 // DestructCallBlock, otherwise jump to EndBlock directly.
3049 CGF.Builder.CreateCondBr(NeedsDestruct, DestructCallBlock, EndBlock);
3050
3051 CGF.EmitBlock(DestructCallBlock);
3052
3053 // Emit the call to casted Dtor.
3054 llvm::CallInst *CI = CGF.Builder.CreateCall(dtorFuncTy, Dtor);
3055 // Make sure the call and the callee agree on calling convention.
3056 CI->setCallingConv(Dtor->getCallingConv());
3057
3058 CGF.EmitBlock(EndBlock);
3059
3060 itv++;
3061 }
3062
3063 CGF.FinishFunction();
3064 AddGlobalDtor(GlobalCleanupFn, Priority);
3065 }
3066}
3067
3068void CodeGenModule::registerGlobalDtorsWithAtExit() {
3069 for (const auto &I : DtorsUsingAtExit) {
3070 int Priority = I.first;
3071 std::string GlobalInitFnName =
3072 std::string("__GLOBAL_init_") + llvm::to_string(Priority);
3073 llvm::Function *GlobalInitFn =
3074 createGlobalInitOrCleanupFn(*this, GlobalInitFnName);
3075
3076 CodeGenFunction CGF(*this);
3077 CGF.StartFunction(GlobalDecl(), getContext().VoidTy, GlobalInitFn,
3078 getTypes().arrangeNullaryFunction(), FunctionArgList(),
3079 SourceLocation(), SourceLocation());
3081
3082 // Since constructor functions are run in non-descending order of their
3083 // priorities, destructors are registered in non-descending order of their
3084 // priorities, and since destructor functions are run in the reverse order
3085 // of their registration, destructor functions are run in non-ascending
3086 // order of their priorities.
3087 const llvm::TinyPtrVector<llvm::Function *> &Dtors = I.second;
3088 for (auto *Dtor : Dtors) {
3089 // Register the destructor function calling __cxa_atexit if it is
3090 // available. Otherwise fall back on calling atexit.
3091 if (getCodeGenOpts().CXAAtExit) {
3092 emitGlobalDtorWithCXAAtExit(CGF, Dtor, nullptr, false);
3093 } else {
3094 // We're assuming that the destructor function is something we can
3095 // reasonably call with the correct CC.
3097 }
3098 }
3099
3100 CGF.FinishFunction();
3101 AddGlobalCtor(GlobalInitFn, Priority);
3102 }
3103
3104 if (getCXXABI().useSinitAndSterm())
3105 unregisterGlobalDtorsWithUnAtExit();
3106}
3107
3108/// Register a global destructor as best as we know how.
3109void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
3110 llvm::FunctionCallee dtor,
3111 llvm::Constant *addr) {
3112 if (D.isNoDestroy(CGM.getContext()))
3113 return;
3114
3115 // HLSL doesn't support atexit.
3116 if (CGM.getLangOpts().HLSL)
3117 return CGM.AddCXXDtorEntry(dtor, addr);
3118
3119 // OpenMP offloading supports C++ constructors and destructors but we do not
3120 // always have 'atexit' available. Instead lower these to use the LLVM global
3121 // destructors which we can handle directly in the runtime. Note that this is
3122 // not strictly 1-to-1 with using `atexit` because we no longer tear down
3123 // globals in reverse order of when they were constructed.
3124 if (!CGM.getLangOpts().hasAtExit() && !D.isStaticLocal())
3125 return CGF.registerGlobalDtorWithLLVM(D, dtor, addr);
3126
3127 // emitGlobalDtorWithCXAAtExit will emit a call to either __cxa_thread_atexit
3128 // or __cxa_atexit depending on whether this VarDecl is a thread-local storage
3129 // or not. CXAAtExit controls only __cxa_atexit, so use it if it is enabled.
3130 // We can always use __cxa_thread_atexit.
3131 if (CGM.getCodeGenOpts().CXAAtExit || D.getTLSKind())
3132 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
3133
3134 // In Apple kexts, we want to add a global destructor entry.
3135 // FIXME: shouldn't this be guarded by some variable?
3136 if (CGM.getLangOpts().AppleKext) {
3137 // Generate a global destructor entry.
3138 return CGM.AddCXXDtorEntry(dtor, addr);
3139 }
3140
3141 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
3142}
3143
3146 assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!");
3147 // Darwin prefers to have references to thread local variables to go through
3148 // the thread wrapper instead of directly referencing the backing variable.
3149 return VD->getTLSKind() == VarDecl::TLS_Dynamic &&
3150 CGM.getTarget().getTriple().isOSDarwin();
3151}
3152
3153/// Get the appropriate linkage for the wrapper function. This is essentially
3154/// the weak form of the variable's linkage; every translation unit which needs
3155/// the wrapper emits a copy, and we want the linker to merge them.
3156static llvm::GlobalValue::LinkageTypes
3158 llvm::GlobalValue::LinkageTypes VarLinkage =
3160
3161 // For internal linkage variables, we don't need an external or weak wrapper.
3162 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
3163 return VarLinkage;
3164
3165 // If the thread wrapper is replaceable, give it appropriate linkage.
3166 if (isThreadWrapperReplaceable(VD, CGM))
3167 if (!llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) &&
3168 !llvm::GlobalVariable::isWeakODRLinkage(VarLinkage))
3169 return VarLinkage;
3170 return llvm::GlobalValue::WeakODRLinkage;
3171}
3172
3173llvm::Function *
3174ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
3175 llvm::Value *Val) {
3176 // Mangle the name for the thread_local wrapper function.
3177 SmallString<256> WrapperName;
3178 {
3179 llvm::raw_svector_ostream Out(WrapperName);
3180 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
3181 }
3182
3183 // FIXME: If VD is a definition, we should regenerate the function attributes
3184 // before returning.
3185 if (llvm::Value *V = CGM.getModule().getNamedValue(WrapperName))
3186 return cast<llvm::Function>(V);
3187
3188 QualType RetQT = VD->getType();
3189 if (RetQT->isReferenceType())
3190 RetQT = RetQT.getNonReferenceType();
3191
3192 const CGFunctionInfo &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
3193 getContext().getPointerType(RetQT), FunctionArgList());
3194
3195 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FI);
3196 llvm::Function *Wrapper =
3197 llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM),
3198 WrapperName.str(), &CGM.getModule());
3199
3200 if (CGM.supportsCOMDAT() && Wrapper->isWeakForLinker())
3201 Wrapper->setComdat(CGM.getModule().getOrInsertComdat(Wrapper->getName()));
3202
3203 CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, Wrapper, /*IsThunk=*/false);
3204
3205 // Always resolve references to the wrapper at link time.
3206 if (!Wrapper->hasLocalLinkage())
3207 if (!isThreadWrapperReplaceable(VD, CGM) ||
3208 llvm::GlobalVariable::isLinkOnceLinkage(Wrapper->getLinkage()) ||
3209 llvm::GlobalVariable::isWeakODRLinkage(Wrapper->getLinkage()) ||
3211 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
3212
3213 if (isThreadWrapperReplaceable(VD, CGM)) {
3214 Wrapper->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
3215 Wrapper->addFnAttr(llvm::Attribute::NoUnwind);
3216 }
3217
3218 ThreadWrappers.push_back({VD, Wrapper});
3219 return Wrapper;
3220}
3221
3222void ItaniumCXXABI::EmitThreadLocalInitFuncs(
3223 CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
3224 ArrayRef<llvm::Function *> CXXThreadLocalInits,
3225 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) {
3226 llvm::Function *InitFunc = nullptr;
3227
3228 // Separate initializers into those with ordered (or partially-ordered)
3229 // initialization and those with unordered initialization.
3230 llvm::SmallVector<llvm::Function *, 8> OrderedInits;
3231 llvm::SmallDenseMap<const VarDecl *, llvm::Function *> UnorderedInits;
3232 for (unsigned I = 0; I != CXXThreadLocalInits.size(); ++I) {
3234 CXXThreadLocalInitVars[I]->getTemplateSpecializationKind()))
3235 UnorderedInits[CXXThreadLocalInitVars[I]->getCanonicalDecl()] =
3236 CXXThreadLocalInits[I];
3237 else
3238 OrderedInits.push_back(CXXThreadLocalInits[I]);
3239 }
3240
3241 if (!OrderedInits.empty()) {
3242 // Generate a guarded initialization function.
3243 llvm::FunctionType *FTy =
3244 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
3245 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
3246 InitFunc = CGM.CreateGlobalInitOrCleanUpFunction(FTy, "__tls_init", FI,
3247 SourceLocation(),
3248 /*TLS=*/true);
3249 llvm::GlobalVariable *Guard = new llvm::GlobalVariable(
3250 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
3251 llvm::GlobalVariable::InternalLinkage,
3252 llvm::ConstantInt::get(CGM.Int8Ty, 0), "__tls_guard");
3253 Guard->setThreadLocal(true);
3254 Guard->setThreadLocalMode(CGM.GetDefaultLLVMTLSModel());
3255
3256 CharUnits GuardAlign = CharUnits::One();
3257 Guard->setAlignment(GuardAlign.getAsAlign());
3258
3259 CodeGenFunction(CGM).GenerateCXXGlobalInitFunc(
3260 InitFunc, OrderedInits, ConstantAddress(Guard, CGM.Int8Ty, GuardAlign));
3261 // On Darwin platforms, use CXX_FAST_TLS calling convention.
3262 if (CGM.getTarget().getTriple().isOSDarwin()) {
3263 InitFunc->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
3264 InitFunc->addFnAttr(llvm::Attribute::NoUnwind);
3265 }
3266 }
3267
3268 // Create declarations for thread wrappers for all thread-local variables
3269 // with non-discardable definitions in this translation unit.
3270 for (const VarDecl *VD : CXXThreadLocals) {
3271 if (VD->hasDefinition() &&
3272 !isDiscardableGVALinkage(getContext().GetGVALinkageForVariable(VD))) {
3273 llvm::GlobalValue *GV = CGM.GetGlobalValue(CGM.getMangledName(VD));
3274 getOrCreateThreadLocalWrapper(VD, GV);
3275 }
3276 }
3277
3278 // Emit all referenced thread wrappers.
3279 for (auto VDAndWrapper : ThreadWrappers) {
3280 const VarDecl *VD = VDAndWrapper.first;
3281 llvm::GlobalVariable *Var =
3283 llvm::Function *Wrapper = VDAndWrapper.second;
3284
3285 // Some targets require that all access to thread local variables go through
3286 // the thread wrapper. This means that we cannot attempt to create a thread
3287 // wrapper or a thread helper.
3288 if (!VD->hasDefinition()) {
3289 if (isThreadWrapperReplaceable(VD, CGM)) {
3290 Wrapper->setLinkage(llvm::Function::ExternalLinkage);
3291 continue;
3292 }
3293
3294 // If this isn't a TU in which this variable is defined, the thread
3295 // wrapper is discardable.
3296 if (Wrapper->getLinkage() == llvm::Function::WeakODRLinkage)
3297 Wrapper->setLinkage(llvm::Function::LinkOnceODRLinkage);
3298 }
3299
3300 CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Wrapper);
3301
3302 // Mangle the name for the thread_local initialization function.
3303 SmallString<256> InitFnName;
3304 {
3305 llvm::raw_svector_ostream Out(InitFnName);
3306 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
3307 }
3308
3309 llvm::FunctionType *InitFnTy = llvm::FunctionType::get(CGM.VoidTy, false);
3310
3311 // If we have a definition for the variable, emit the initialization
3312 // function as an alias to the global Init function (if any). Otherwise,
3313 // produce a declaration of the initialization function.
3314 llvm::GlobalValue *Init = nullptr;
3315 bool InitIsInitFunc = false;
3316 bool HasConstantInitialization = false;
3317 if (!usesThreadWrapperFunction(VD)) {
3318 HasConstantInitialization = true;
3319 } else if (VD->hasDefinition()) {
3320 InitIsInitFunc = true;
3321 llvm::Function *InitFuncToUse = InitFunc;
3323 InitFuncToUse = UnorderedInits.lookup(VD->getCanonicalDecl());
3324 if (InitFuncToUse)
3325 Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
3326 InitFuncToUse);
3327 } else {
3328 // Emit a weak global function referring to the initialization function.
3329 // This function will not exist if the TU defining the thread_local
3330 // variable in question does not need any dynamic initialization for
3331 // its thread_local variables.
3332 Init = llvm::Function::Create(InitFnTy,
3333 llvm::GlobalVariable::ExternalWeakLinkage,
3334 InitFnName.str(), &CGM.getModule());
3335 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
3337 GlobalDecl(), FI, cast<llvm::Function>(Init), /*IsThunk=*/false);
3338 }
3339
3340 if (Init) {
3341 Init->setVisibility(Var->getVisibility());
3342 // Don't mark an extern_weak function DSO local on windows.
3343 if (!CGM.getTriple().isOSWindows() || !Init->hasExternalWeakLinkage())
3344 Init->setDSOLocal(Var->isDSOLocal());
3345 }
3346
3347 llvm::LLVMContext &Context = CGM.getModule().getContext();
3348
3349 // The linker on AIX is not happy with missing weak symbols. However,
3350 // other TUs will not know whether the initialization routine exists
3351 // so create an empty, init function to satisfy the linker.
3352 // This is needed whenever a thread wrapper function is not used, and
3353 // also when the symbol is weak.
3354 if (CGM.getTriple().isOSAIX() && VD->hasDefinition() &&
3355 isEmittedWithConstantInitializer(VD, true) &&
3356 !mayNeedDestruction(VD)) {
3357 // Init should be null. If it were non-null, then the logic above would
3358 // either be defining the function to be an alias or declaring the
3359 // function with the expectation that the definition of the variable
3360 // is elsewhere.
3361 assert(Init == nullptr && "Expected Init to be null.");
3362
3363 llvm::Function *Func = llvm::Function::Create(
3364 InitFnTy, Var->getLinkage(), InitFnName.str(), &CGM.getModule());
3365 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
3366 CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI,
3368 /*IsThunk=*/false);
3369 // Create a function body that just returns
3370 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Func);
3371 CGBuilderTy Builder(CGM, Entry);
3372 Builder.CreateRetVoid();
3373 }
3374
3375 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
3376 CGBuilderTy Builder(CGM, Entry);
3377 if (HasConstantInitialization) {
3378 // No dynamic initialization to invoke.
3379 } else if (InitIsInitFunc) {
3380 if (Init) {
3381 llvm::CallInst *CallVal = Builder.CreateCall(InitFnTy, Init);
3382 if (isThreadWrapperReplaceable(VD, CGM)) {
3383 CallVal->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
3384 llvm::Function *Fn =
3386 Fn->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
3387 }
3388 }
3389 } else if (CGM.getTriple().isOSAIX()) {
3390 // On AIX, except if constinit and also neither of class type or of
3391 // (possibly multi-dimensional) array of class type, thread_local vars
3392 // will have init routines regardless of whether they are
3393 // const-initialized. Since the routine is guaranteed to exist, we can
3394 // unconditionally call it without testing for its existance. This
3395 // avoids potentially unresolved weak symbols which the AIX linker
3396 // isn't happy with.
3397 Builder.CreateCall(InitFnTy, Init);
3398 } else {
3399 // Don't know whether we have an init function. Call it if it exists.
3400 llvm::Value *Have = Builder.CreateIsNotNull(Init);
3401 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
3402 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
3403 Builder.CreateCondBr(Have, InitBB, ExitBB);
3404
3405 Builder.SetInsertPoint(InitBB);
3406 Builder.CreateCall(InitFnTy, Init);
3407 Builder.CreateBr(ExitBB);
3408
3409 Builder.SetInsertPoint(ExitBB);
3410 }
3411
3412 // For a reference, the result of the wrapper function is a pointer to
3413 // the referenced object.
3414 llvm::Value *Val = Builder.CreateThreadLocalAddress(Var);
3415
3416 if (VD->getType()->isReferenceType()) {
3417 CharUnits Align = CGM.getContext().getDeclAlign(VD);
3418 Val = Builder.CreateAlignedLoad(Var->getValueType(), Val, Align);
3419 }
3420 Val = Builder.CreateAddrSpaceCast(Val, Wrapper->getReturnType());
3421
3422 Builder.CreateRet(Val);
3423 }
3424}
3425
3426LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
3427 const VarDecl *VD,
3428 QualType LValType) {
3429 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD);
3430 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Val);
3431
3432 llvm::CallInst *CallVal = CGF.Builder.CreateCall(Wrapper);
3433 CallVal->setCallingConv(Wrapper->getCallingConv());
3434
3435 LValue LV;
3436 if (VD->getType()->isReferenceType())
3437 LV = CGF.MakeNaturalAlignRawAddrLValue(CallVal, LValType);
3438 else
3439 LV = CGF.MakeRawAddrLValue(CallVal, LValType,
3440 CGF.getContext().getDeclAlign(VD));
3441 // FIXME: need setObjCGCLValueClass?
3442 return LV;
3443}
3444
3445/// Return whether the given global decl needs a VTT parameter, which it does
3446/// if it's a base constructor or destructor with virtual bases.
3447bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
3448 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
3449
3450 // We don't have any virtual bases, just return early.
3451 if (!MD->getParent()->getNumVBases())
3452 return false;
3453
3454 // Check if we have a base constructor.
3456 return true;
3457
3458 // Check if we have a base destructor.
3459 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
3460 return true;
3461
3462 return false;
3463}
3464
3465llvm::Constant *
3466ItaniumCXXABI::getOrCreateVirtualFunctionPointerThunk(const CXXMethodDecl *MD) {
3467 SmallString<256> MethodName;
3468 llvm::raw_svector_ostream Out(MethodName);
3469 getMangleContext().mangleCXXName(MD, Out);
3470 MethodName += "_vfpthunk_";
3471 StringRef ThunkName = MethodName.str();
3472 llvm::Function *ThunkFn;
3473 if ((ThunkFn = cast_or_null<llvm::Function>(
3474 CGM.getModule().getNamedValue(ThunkName))))
3475 return ThunkFn;
3476
3477 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeCXXMethodDeclaration(MD);
3478 llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo);
3479 llvm::GlobalValue::LinkageTypes Linkage =
3480 MD->isExternallyVisible() ? llvm::GlobalValue::LinkOnceODRLinkage
3481 : llvm::GlobalValue::InternalLinkage;
3482 ThunkFn =
3483 llvm::Function::Create(ThunkTy, Linkage, ThunkName, &CGM.getModule());
3484 if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
3485 ThunkFn->setVisibility(llvm::GlobalValue::HiddenVisibility);
3486 assert(ThunkFn->getName() == ThunkName && "name was uniqued!");
3487
3488 CGM.SetLLVMFunctionAttributes(MD, FnInfo, ThunkFn, /*IsThunk=*/true);
3490
3491 // Stack protection sometimes gets inserted after the musttail call.
3492 ThunkFn->removeFnAttr(llvm::Attribute::StackProtect);
3493 ThunkFn->removeFnAttr(llvm::Attribute::StackProtectStrong);
3494 ThunkFn->removeFnAttr(llvm::Attribute::StackProtectReq);
3495
3496 // Start codegen.
3497 CodeGenFunction CGF(CGM);
3498 CGF.CurGD = GlobalDecl(MD);
3499 CGF.CurFuncIsThunk = true;
3500
3501 // Build FunctionArgs.
3502 FunctionArgList FunctionArgs;
3503 CGF.BuildFunctionArgList(CGF.CurGD, FunctionArgs);
3504
3505 CGF.StartFunction(GlobalDecl(), FnInfo.getReturnType(), ThunkFn, FnInfo,
3506 FunctionArgs, MD->getLocation(), SourceLocation());
3507
3508 // Emit an artificial location for this function.
3510
3511 llvm::Value *ThisVal = loadIncomingCXXThis(CGF);
3512 setCXXABIThisValue(CGF, ThisVal);
3513
3514 CallArgList CallArgs;
3515 for (const VarDecl *VD : FunctionArgs)
3516 CGF.EmitDelegateCallArg(CallArgs, VD, SourceLocation());
3517
3518 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
3519 RequiredArgs Required = RequiredArgs::forPrototypePlus(FPT, /*this*/ 1);
3520 const CGFunctionInfo &CallInfo =
3521 CGM.getTypes().arrangeCXXMethodCall(CallArgs, FPT, Required, 0);
3522 CGCallee Callee = CGCallee::forVirtual(nullptr, GlobalDecl(MD),
3523 getThisAddress(CGF), ThunkTy);
3524 llvm::CallBase *CallOrInvoke;
3525 CGF.EmitCall(CallInfo, Callee, ReturnValueSlot(), CallArgs, &CallOrInvoke,
3526 /*IsMustTail=*/true, SourceLocation(), true);
3527 auto *Call = cast<llvm::CallInst>(CallOrInvoke);
3528 Call->setTailCallKind(llvm::CallInst::TCK_MustTail);
3529 if (Call->getType()->isVoidTy())
3530 CGF.Builder.CreateRetVoid();
3531 else
3532 CGF.Builder.CreateRet(Call);
3533
3534 // Finish the function to maintain CodeGenFunction invariants.
3535 // FIXME: Don't emit unreachable code.
3536 CGF.EmitBlock(CGF.createBasicBlock());
3537 CGF.FinishFunction();
3538 return ThunkFn;
3539}
3540
3541namespace {
3542class ItaniumRTTIBuilder {
3543 CodeGenModule &CGM; // Per-module state.
3544 llvm::LLVMContext &VMContext;
3545 const ItaniumCXXABI &CXXABI; // Per-module state.
3546
3547 /// Fields - The fields of the RTTI descriptor currently being built.
3548 SmallVector<llvm::Constant *, 16> Fields;
3549
3550 /// GetAddrOfTypeName - Returns the mangled type name of the given type.
3551 llvm::GlobalVariable *
3552 GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
3553
3554 /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
3555 /// descriptor of the given type.
3556 llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
3557
3558 /// BuildVTablePointer - Build the vtable pointer for the given type.
3559 void BuildVTablePointer(const Type *Ty, llvm::Constant *StorageAddress);
3560
3561 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
3562 /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
3563 void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
3564
3565 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
3566 /// classes with bases that do not satisfy the abi::__si_class_type_info
3567 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
3568 void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
3569
3570 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
3571 /// for pointer types.
3572 void BuildPointerTypeInfo(QualType PointeeTy);
3573
3574 /// BuildObjCObjectTypeInfo - Build the appropriate kind of
3575 /// type_info for an object type.
3576 void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
3577
3578 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
3579 /// struct, used for member pointer types.
3580 void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
3581
3582public:
3583 ItaniumRTTIBuilder(const ItaniumCXXABI &ABI)
3584 : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {}
3585
3586 // Pointer type info flags.
3587 enum {
3588 /// PTI_Const - Type has const qualifier.
3589 PTI_Const = 0x1,
3590
3591 /// PTI_Volatile - Type has volatile qualifier.
3592 PTI_Volatile = 0x2,
3593
3594 /// PTI_Restrict - Type has restrict qualifier.
3595 PTI_Restrict = 0x4,
3596
3597 /// PTI_Incomplete - Type is incomplete.
3598 PTI_Incomplete = 0x8,
3599
3600 /// PTI_ContainingClassIncomplete - Containing class is incomplete.
3601 /// (in pointer to member).
3602 PTI_ContainingClassIncomplete = 0x10,
3603
3604 /// PTI_TransactionSafe - Pointee is transaction_safe function (C++ TM TS).
3605 //PTI_TransactionSafe = 0x20,
3606
3607 /// PTI_Noexcept - Pointee is noexcept function (C++1z).
3608 PTI_Noexcept = 0x40,
3609 };
3610
3611 // VMI type info flags.
3612 enum {
3613 /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
3614 VMI_NonDiamondRepeat = 0x1,
3615
3616 /// VMI_DiamondShaped - Class is diamond shaped.
3617 VMI_DiamondShaped = 0x2
3618 };
3619
3620 // Base class type info flags.
3621 enum {
3622 /// BCTI_Virtual - Base class is virtual.
3623 BCTI_Virtual = 0x1,
3624
3625 /// BCTI_Public - Base class is public.
3626 BCTI_Public = 0x2
3627 };
3628
3629 /// BuildTypeInfo - Build the RTTI type info struct for the given type, or
3630 /// link to an existing RTTI descriptor if one already exists.
3631 llvm::Constant *BuildTypeInfo(QualType Ty);
3632
3633 /// BuildTypeInfo - Build the RTTI type info struct for the given type.
3634 llvm::Constant *BuildTypeInfo(
3635 QualType Ty,
3636 llvm::GlobalVariable::LinkageTypes Linkage,
3637 llvm::GlobalValue::VisibilityTypes Visibility,
3638 llvm::GlobalValue::DLLStorageClassTypes DLLStorageClass);
3639};
3640}
3641
3642llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName(
3643 QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) {
3644 SmallString<256> Name;
3645 llvm::raw_svector_ostream Out(Name);
3647
3648 // We know that the mangled name of the type starts at index 4 of the
3649 // mangled name of the typename, so we can just index into it in order to
3650 // get the mangled name of the type.
3651 llvm::Constant *Init;
3652 if (CGM.getTriple().isOSzOS()) {
3653 // On z/OS, typename is stored as 2 encodings: EBCDIC followed by ASCII.
3654 SmallString<256> DualEncodedName;
3655 llvm::ConverterEBCDIC::convertToEBCDIC(Name.substr(4), DualEncodedName);
3656 DualEncodedName += '\0';
3657 DualEncodedName += Name.substr(4);
3658 Init = llvm::ConstantDataArray::getString(VMContext, DualEncodedName);
3659 } else
3660 Init = llvm::ConstantDataArray::getString(VMContext, Name.substr(4));
3661
3662 auto Align = CGM.getContext().getTypeAlignInChars(CGM.getContext().CharTy);
3663
3664 llvm::GlobalVariable *GV = CGM.CreateOrReplaceCXXRuntimeVariable(
3665 Name, Init->getType(), Linkage, Align.getAsAlign());
3666
3667 GV->setInitializer(Init);
3668
3669 return GV;
3670}
3671
3672llvm::Constant *
3673ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
3674 // Mangle the RTTI name.
3675 SmallString<256> Name;
3676 llvm::raw_svector_ostream Out(Name);
3677 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
3678
3679 // Look for an existing global.
3680 llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
3681
3682 if (!GV) {
3683 // Create a new global variable.
3684 // Note for the future: If we would ever like to do deferred emission of
3685 // RTTI, check if emitting vtables opportunistically need any adjustment.
3686
3687 GV = new llvm::GlobalVariable(
3688 CGM.getModule(), CGM.GlobalsInt8PtrTy,
3689 /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage, nullptr, Name);
3690 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
3691 CGM.setGVProperties(GV, RD);
3692 // Import the typeinfo symbol when all non-inline virtual methods are
3693 // imported.
3694 if (CGM.getTarget().hasPS4DLLImportExport()) {
3696 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
3697 CGM.setDSOLocal(GV);
3698 }
3699 }
3700 }
3701
3702 return GV;
3703}
3704
3705/// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
3706/// info for that type is defined in the standard library.
3708 // Itanium C++ ABI 2.9.2:
3709 // Basic type information (e.g. for "int", "bool", etc.) will be kept in
3710 // the run-time support library. Specifically, the run-time support
3711 // library should contain type_info objects for the types X, X* and
3712 // X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
3713 // unsigned char, signed char, short, unsigned short, int, unsigned int,
3714 // long, unsigned long, long long, unsigned long long, float, double,
3715 // long double, char16_t, char32_t, and the IEEE 754r decimal and
3716 // half-precision floating point types.
3717 //
3718 // GCC also emits RTTI for __int128.
3719 // FIXME: We do not emit RTTI information for decimal types here.
3720
3721 // Types added here must also be added to EmitFundamentalRTTIDescriptors.
3722 switch (Ty->getKind()) {
3723 case BuiltinType::Void:
3724 case BuiltinType::NullPtr:
3725 case BuiltinType::Bool:
3726 case BuiltinType::WChar_S:
3727 case BuiltinType::WChar_U:
3728 case BuiltinType::Char_U:
3729 case BuiltinType::Char_S:
3730 case BuiltinType::UChar:
3731 case BuiltinType::SChar:
3732 case BuiltinType::Short:
3733 case BuiltinType::UShort:
3734 case BuiltinType::Int:
3735 case BuiltinType::UInt:
3736 case BuiltinType::Long:
3737 case BuiltinType::ULong:
3738 case BuiltinType::LongLong:
3739 case BuiltinType::ULongLong:
3740 case BuiltinType::Half:
3741 case BuiltinType::Float:
3742 case BuiltinType::Double:
3743 case BuiltinType::LongDouble:
3744 case BuiltinType::Float16:
3745 case BuiltinType::Float128:
3746 case BuiltinType::Ibm128:
3747 case BuiltinType::Char8:
3748 case BuiltinType::Char16:
3749 case BuiltinType::Char32:
3750 case BuiltinType::Int128:
3751 case BuiltinType::UInt128:
3752 return true;
3753
3754#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3755 case BuiltinType::Id:
3756#include "clang/Basic/OpenCLImageTypes.def"
3757#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
3758 case BuiltinType::Id:
3759#include "clang/Basic/OpenCLExtensionTypes.def"
3760 case BuiltinType::OCLSampler:
3761 case BuiltinType::OCLEvent:
3762 case BuiltinType::OCLClkEvent:
3763 case BuiltinType::OCLQueue:
3764 case BuiltinType::OCLReserveID:
3765#define SVE_TYPE(Name, Id, SingletonId) \
3766 case BuiltinType::Id:
3767#include "clang/Basic/AArch64ACLETypes.def"
3768#define PPC_VECTOR_TYPE(Name, Id, Size) \
3769 case BuiltinType::Id:
3770#include "clang/Basic/PPCTypes.def"
3771#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
3772#include "clang/Basic/RISCVVTypes.def"
3773#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
3774#include "clang/Basic/WebAssemblyReferenceTypes.def"
3775#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
3776#include "clang/Basic/AMDGPUTypes.def"
3777#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
3778#include "clang/Basic/HLSLIntangibleTypes.def"
3779 case BuiltinType::ShortAccum:
3780 case BuiltinType::Accum:
3781 case BuiltinType::LongAccum:
3782 case BuiltinType::UShortAccum:
3783 case BuiltinType::UAccum:
3784 case BuiltinType::ULongAccum:
3785 case BuiltinType::ShortFract:
3786 case BuiltinType::Fract:
3787 case BuiltinType::LongFract:
3788 case BuiltinType::UShortFract:
3789 case BuiltinType::UFract:
3790 case BuiltinType::ULongFract:
3791 case BuiltinType::SatShortAccum:
3792 case BuiltinType::SatAccum:
3793 case BuiltinType::SatLongAccum:
3794 case BuiltinType::SatUShortAccum:
3795 case BuiltinType::SatUAccum:
3796 case BuiltinType::SatULongAccum:
3797 case BuiltinType::SatShortFract:
3798 case BuiltinType::SatFract:
3799 case BuiltinType::SatLongFract:
3800 case BuiltinType::SatUShortFract:
3801 case BuiltinType::SatUFract:
3802 case BuiltinType::SatULongFract:
3803 case BuiltinType::BFloat16:
3804 return false;
3805
3806 case BuiltinType::Dependent:
3807#define BUILTIN_TYPE(Id, SingletonId)
3808#define PLACEHOLDER_TYPE(Id, SingletonId) \
3809 case BuiltinType::Id:
3810#include "clang/AST/BuiltinTypes.def"
3811 llvm_unreachable("asking for RRTI for a placeholder type!");
3812
3813 case BuiltinType::ObjCId:
3814 case BuiltinType::ObjCClass:
3815 case BuiltinType::ObjCSel:
3816 llvm_unreachable("FIXME: Objective-C types are unsupported!");
3817 }
3818
3819 llvm_unreachable("Invalid BuiltinType Kind!");
3820}
3821
3822static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
3823 QualType PointeeTy = PointerTy->getPointeeType();
3824 const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
3825 if (!BuiltinTy)
3826 return false;
3827
3828 // Check the qualifiers.
3829 Qualifiers Quals = PointeeTy.getQualifiers();
3830 Quals.removeConst();
3831
3832 if (!Quals.empty())
3833 return false;
3834
3835 return TypeInfoIsInStandardLibrary(BuiltinTy);
3836}
3837
3838/// IsStandardLibraryRTTIDescriptor - Returns whether the type
3839/// information for the given type exists in the standard library.
3841 // Type info for builtin types is defined in the standard library.
3842 if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
3843 return TypeInfoIsInStandardLibrary(BuiltinTy);
3844
3845 // Type info for some pointer types to builtin types is defined in the
3846 // standard library.
3847 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
3848 return TypeInfoIsInStandardLibrary(PointerTy);
3849
3850 return false;
3851}
3852
3853/// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
3854/// the given type exists somewhere else, and that we should not emit the type
3855/// information in this translation unit. Assumes that it is not a
3856/// standard-library type.
3858 QualType Ty) {
3859 ASTContext &Context = CGM.getContext();
3860
3861 // If RTTI is disabled, assume it might be disabled in the
3862 // translation unit that defines any potential key function, too.
3863 if (!Context.getLangOpts().RTTI) return false;
3864
3865 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
3866 const CXXRecordDecl *RD =
3867 cast<CXXRecordDecl>(RecordTy->getDecl())->getDefinitionOrSelf();
3868 if (!RD->hasDefinition())
3869 return false;
3870
3871 if (!RD->isDynamicClass())
3872 return false;
3873
3874 // FIXME: this may need to be reconsidered if the key function
3875 // changes.
3876 // N.B. We must always emit the RTTI data ourselves if there exists a key
3877 // function.
3878 bool IsDLLImport = RD->hasAttr<DLLImportAttr>();
3879
3880 // Don't import the RTTI but emit it locally.
3881 if (CGM.getTriple().isOSCygMing())
3882 return false;
3883
3884 if (CGM.getVTables().isVTableExternal(RD)) {
3885 if (CGM.getTarget().hasPS4DLLImportExport())
3886 return true;
3887
3888 return IsDLLImport && !CGM.getTriple().isWindowsItaniumEnvironment()
3889 ? false
3890 : true;
3891 }
3892 if (IsDLLImport)
3893 return true;
3894 }
3895
3896 return false;
3897}
3898
3899/// IsIncompleteClassType - Returns whether the given record type is incomplete.
3900static bool IsIncompleteClassType(const RecordType *RecordTy) {
3901 return !RecordTy->getDecl()->getDefinitionOrSelf()->isCompleteDefinition();
3902}
3903
3904/// ContainsIncompleteClassType - Returns whether the given type contains an
3905/// incomplete class type. This is true if
3906///
3907/// * The given type is an incomplete class type.
3908/// * The given type is a pointer type whose pointee type contains an
3909/// incomplete class type.
3910/// * The given type is a member pointer type whose class is an incomplete
3911/// class type.
3912/// * The given type is a member pointer type whoise pointee type contains an
3913/// incomplete class type.
3914/// is an indirect or direct pointer to an incomplete class type.
3916 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
3917 if (IsIncompleteClassType(RecordTy))
3918 return true;
3919 }
3920
3921 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
3922 return ContainsIncompleteClassType(PointerTy->getPointeeType());
3923
3924 if (const MemberPointerType *MemberPointerTy =
3925 dyn_cast<MemberPointerType>(Ty)) {
3926 // Check if the class type is incomplete.
3927 if (!MemberPointerTy->getMostRecentCXXRecordDecl()->hasDefinition())
3928 return true;
3929
3930 return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
3931 }
3932
3933 return false;
3934}
3935
3936// CanUseSingleInheritance - Return whether the given record decl has a "single,
3937// public, non-virtual base at offset zero (i.e. the derived class is dynamic
3938// iff the base is)", according to Itanium C++ ABI, 2.95p6b.
3940 // Check the number of bases.
3941 if (RD->getNumBases() != 1)
3942 return false;
3943
3944 // Get the base.
3946
3947 // Check that the base is not virtual.
3948 if (Base->isVirtual())
3949 return false;
3950
3951 // Check that the base is public.
3952 if (Base->getAccessSpecifier() != AS_public)
3953 return false;
3954
3955 // Check that the class is dynamic iff the base is.
3956 auto *BaseDecl = Base->getType()->castAsCXXRecordDecl();
3957 if (!BaseDecl->isEmpty() &&
3958 BaseDecl->isDynamicClass() != RD->isDynamicClass())
3959 return false;
3960
3961 return true;
3962}
3963
3964void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty,
3965 llvm::Constant *StorageAddress) {
3966 // abi::__class_type_info.
3967 static const char * const ClassTypeInfo =
3968 "_ZTVN10__cxxabiv117__class_type_infoE";
3969 // abi::__si_class_type_info.
3970 static const char * const SIClassTypeInfo =
3971 "_ZTVN10__cxxabiv120__si_class_type_infoE";
3972 // abi::__vmi_class_type_info.
3973 static const char * const VMIClassTypeInfo =
3974 "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
3975
3976 const char *VTableName = nullptr;
3977
3978 switch (Ty->getTypeClass()) {
3979#define TYPE(Class, Base)
3980#define ABSTRACT_TYPE(Class, Base)
3981#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3982#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3983#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3984#include "clang/AST/TypeNodes.inc"
3985 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
3986
3987 case Type::LValueReference:
3988 case Type::RValueReference:
3989 llvm_unreachable("References shouldn't get here");
3990
3991 case Type::Auto:
3992 case Type::DeducedTemplateSpecialization:
3993 llvm_unreachable("Undeduced type shouldn't get here");
3994
3995 case Type::Pipe:
3996 llvm_unreachable("Pipe types shouldn't get here");
3997
3998 case Type::ArrayParameter:
3999 llvm_unreachable("Array Parameter types should not get here.");
4000
4001 case Type::Builtin:
4002 case Type::BitInt:
4003 case Type::OverflowBehavior:
4004 // GCC treats vector and complex types as fundamental types.
4005 case Type::Vector:
4006 case Type::ExtVector:
4007 case Type::ConstantMatrix:
4008 case Type::Complex:
4009 case Type::Atomic:
4010 // FIXME: GCC treats block pointers as fundamental types?!
4011 case Type::BlockPointer:
4012 // abi::__fundamental_type_info.
4013 VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
4014 break;
4015
4016 case Type::ConstantArray:
4017 case Type::IncompleteArray:
4018 case Type::VariableArray:
4019 // abi::__array_type_info.
4020 VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
4021 break;
4022
4023 case Type::FunctionNoProto:
4024 case Type::FunctionProto:
4025 // abi::__function_type_info.
4026 VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
4027 break;
4028
4029 case Type::Enum:
4030 // abi::__enum_type_info.
4031 VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
4032 break;
4033
4034 case Type::Record: {
4035 const auto *RD = cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl())
4036 ->getDefinitionOrSelf();
4037
4038 if (!RD->hasDefinition() || !RD->getNumBases()) {
4039 VTableName = ClassTypeInfo;
4040 } else if (CanUseSingleInheritance(RD)) {
4041 VTableName = SIClassTypeInfo;
4042 } else {
4043 VTableName = VMIClassTypeInfo;
4044 }
4045
4046 break;
4047 }
4048
4049 case Type::ObjCObject:
4050 // Ignore protocol qualifiers.
4051 Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
4052
4053 // Handle id and Class.
4054 if (isa<BuiltinType>(Ty)) {
4055 VTableName = ClassTypeInfo;
4056 break;
4057 }
4058
4059 assert(isa<ObjCInterfaceType>(Ty));
4060 [[fallthrough]];
4061
4062 case Type::ObjCInterface:
4063 if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
4064 VTableName = SIClassTypeInfo;
4065 } else {
4066 VTableName = ClassTypeInfo;
4067 }
4068 break;
4069
4070 case Type::ObjCObjectPointer:
4071 case Type::Pointer:
4072 // abi::__pointer_type_info.
4073 VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
4074 break;
4075
4076 case Type::MemberPointer:
4077 // abi::__pointer_to_member_type_info.
4078 VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
4079 break;
4080
4081 case Type::HLSLAttributedResource:
4082 case Type::HLSLInlineSpirv:
4083 llvm_unreachable("HLSL doesn't support virtual functions");
4084 }
4085
4086 llvm::Constant *VTable = nullptr;
4087
4088 // Check if the alias exists. If it doesn't, then get or create the global.
4089 if (CGM.getLangOpts().RelativeCXXABIVTables)
4090 VTable = CGM.getModule().getNamedAlias(VTableName);
4091 if (!VTable) {
4092 llvm::Type *Ty = llvm::ArrayType::get(CGM.GlobalsInt8PtrTy, 0);
4093 VTable = CGM.getModule().getOrInsertGlobal(VTableName, Ty);
4094 }
4095
4096 CGM.setDSOLocal(cast<llvm::GlobalValue>(VTable->stripPointerCasts()));
4097
4098 llvm::Type *PtrDiffTy =
4100
4101 // The vtable address point is 2.
4102 if (CGM.getLangOpts().RelativeCXXABIVTables) {
4103 // The vtable address point is 8 bytes after its start:
4104 // 4 for the offset to top + 4 for the relative offset to rtti.
4105 llvm::Constant *Eight = llvm::ConstantInt::get(CGM.Int32Ty, 8);
4106 VTable = llvm::ConstantExpr::getInBoundsPtrAdd(VTable, Eight);
4107 } else {
4108 llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
4109 VTable = llvm::ConstantExpr::getInBoundsGetElementPtr(CGM.GlobalsInt8PtrTy,
4110 VTable, Two);
4111 }
4112
4113 if (const auto &Schema =
4115 VTable = CGM.getConstantSignedPointer(
4116 VTable, Schema,
4117 Schema.isAddressDiscriminated() ? StorageAddress : nullptr,
4118 GlobalDecl(), QualType(Ty, 0));
4119
4120 Fields.push_back(VTable);
4121}
4122
4123/// Return the linkage that the type info and type info name constants
4124/// should have for the given type.
4125static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM,
4126 QualType Ty) {
4127 // Itanium C++ ABI 2.9.5p7:
4128 // In addition, it and all of the intermediate abi::__pointer_type_info
4129 // structs in the chain down to the abi::__class_type_info for the
4130 // incomplete class type must be prevented from resolving to the
4131 // corresponding type_info structs for the complete class type, possibly
4132 // by making them local static objects. Finally, a dummy class RTTI is
4133 // generated for the incomplete type that will not resolve to the final
4134 // complete class RTTI (because the latter need not exist), possibly by
4135 // making it a local static object.
4137 return llvm::GlobalValue::InternalLinkage;
4138
4139 switch (Ty->getLinkage()) {
4140 case Linkage::Invalid:
4141 llvm_unreachable("Linkage hasn't been computed!");
4142
4143 case Linkage::None:
4144 case Linkage::Internal:
4146 return llvm::GlobalValue::InternalLinkage;
4147
4149 case Linkage::Module:
4150 case Linkage::External:
4151 // RTTI is not enabled, which means that this type info struct is going
4152 // to be used for exception handling. Give it linkonce_odr linkage.
4153 if (!CGM.getLangOpts().RTTI)
4154 return llvm::GlobalValue::LinkOnceODRLinkage;
4155
4156 if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
4157 const auto *RD =
4158 cast<CXXRecordDecl>(Record->getDecl())->getDefinitionOrSelf();
4159 if (RD->hasAttr<WeakAttr>())
4160 return llvm::GlobalValue::WeakODRLinkage;
4161 if (CGM.getTriple().isWindowsItaniumEnvironment())
4162 if (RD->hasAttr<DLLImportAttr>() &&
4164 return llvm::GlobalValue::ExternalLinkage;
4165 // MinGW always uses LinkOnceODRLinkage for type info.
4166 if (RD->isDynamicClass() &&
4167 !CGM.getContext().getTargetInfo().getTriple().isOSCygMing())
4168 return CGM.getVTableLinkage(RD);
4169 }
4170
4171 return llvm::GlobalValue::LinkOnceODRLinkage;
4172 }
4173
4174 llvm_unreachable("Invalid linkage!");
4175}
4176
4177llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty) {
4178 // We want to operate on the canonical type.
4179 Ty = Ty.getCanonicalType();
4180
4181 // Check if we've already emitted an RTTI descriptor for this type.
4182 SmallString<256> Name;
4183 llvm::raw_svector_ostream Out(Name);
4184 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
4185
4186 llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
4187 if (OldGV && !OldGV->isDeclaration()) {
4188 assert(!OldGV->hasAvailableExternallyLinkage() &&
4189 "available_externally typeinfos not yet implemented");
4190
4191 return OldGV;
4192 }
4193
4194 // Check if there is already an external RTTI descriptor for this type.
4197 return GetAddrOfExternalRTTIDescriptor(Ty);
4198
4199 // Emit the standard library with external linkage.
4200 llvm::GlobalVariable::LinkageTypes Linkage = getTypeInfoLinkage(CGM, Ty);
4201
4202 // Give the type_info object and name the formal visibility of the
4203 // type itself.
4204 llvm::GlobalValue::VisibilityTypes llvmVisibility;
4205 if (llvm::GlobalValue::isLocalLinkage(Linkage))
4206 // If the linkage is local, only default visibility makes sense.
4207 llvmVisibility = llvm::GlobalValue::DefaultVisibility;
4208 else if (CXXABI.classifyRTTIUniqueness(Ty, Linkage) ==
4209 ItaniumCXXABI::RUK_NonUniqueHidden)
4210 llvmVisibility = llvm::GlobalValue::HiddenVisibility;
4211 else
4212 llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility());
4213
4214 llvm::GlobalValue::DLLStorageClassTypes DLLStorageClass =
4215 llvm::GlobalValue::DefaultStorageClass;
4216 if (auto RD = Ty->getAsCXXRecordDecl()) {
4217 if ((CGM.getTriple().isWindowsItaniumEnvironment() &&
4218 RD->hasAttr<DLLExportAttr>()) ||
4220 !llvm::GlobalValue::isLocalLinkage(Linkage) &&
4221 llvmVisibility == llvm::GlobalValue::DefaultVisibility))
4222 DLLStorageClass = llvm::GlobalValue::DLLExportStorageClass;
4223 }
4224 return BuildTypeInfo(Ty, Linkage, llvmVisibility, DLLStorageClass);
4225}
4226
4227llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(
4228 QualType Ty,
4229 llvm::GlobalVariable::LinkageTypes Linkage,
4230 llvm::GlobalValue::VisibilityTypes Visibility,
4231 llvm::GlobalValue::DLLStorageClassTypes DLLStorageClass) {
4232 SmallString<256> Name;
4233 llvm::raw_svector_ostream Out(Name);
4234 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
4235 llvm::Module &M = CGM.getModule();
4236 llvm::GlobalVariable *OldGV = M.getNamedGlobal(Name);
4237 // int8 is an arbitrary type to be replaced later with replaceInitializer.
4238 llvm::GlobalVariable *GV =
4239 new llvm::GlobalVariable(M, CGM.Int8Ty, /*isConstant=*/true, Linkage,
4240 /*Initializer=*/nullptr, Name);
4241
4242 // Add the vtable pointer.
4243 BuildVTablePointer(cast<Type>(Ty), GV);
4244
4245 // And the name.
4246 llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
4247 llvm::Constant *TypeNameField;
4248
4249 // If we're supposed to demote the visibility, be sure to set a flag
4250 // to use a string comparison for type_info comparisons.
4251 ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness =
4252 CXXABI.classifyRTTIUniqueness(Ty, Linkage);
4253 if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) {
4254 // The flag is the sign bit, which on ARM64 is defined to be clear
4255 // for global pointers. This is very ARM64-specific.
4256 TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty);
4257 llvm::Constant *flag =
4258 llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63);
4259 TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag);
4260 TypeNameField =
4261 llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.GlobalsInt8PtrTy);
4262 } else {
4263 TypeNameField = TypeName;
4264 }
4265 Fields.push_back(TypeNameField);
4266
4267 switch (Ty->getTypeClass()) {
4268#define TYPE(Class, Base)
4269#define ABSTRACT_TYPE(Class, Base)
4270#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
4271#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4272#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4273#include "clang/AST/TypeNodes.inc"
4274 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
4275
4276 // GCC treats vector types as fundamental types.
4277 case Type::Builtin:
4278 case Type::Vector:
4279 case Type::ExtVector:
4280 case Type::ConstantMatrix:
4281 case Type::Complex:
4282 case Type::BlockPointer:
4283 // Itanium C++ ABI 2.9.5p4:
4284 // abi::__fundamental_type_info adds no data members to std::type_info.
4285 break;
4286
4287 case Type::LValueReference:
4288 case Type::RValueReference:
4289 llvm_unreachable("References shouldn't get here");
4290
4291 case Type::Auto:
4292 case Type::DeducedTemplateSpecialization:
4293 llvm_unreachable("Undeduced type shouldn't get here");
4294
4295 case Type::Pipe:
4296 break;
4297
4298 case Type::BitInt:
4299 break;
4300
4301 case Type::ConstantArray:
4302 case Type::IncompleteArray:
4303 case Type::VariableArray:
4304 case Type::ArrayParameter:
4305 // Itanium C++ ABI 2.9.5p5:
4306 // abi::__array_type_info adds no data members to std::type_info.
4307 break;
4308
4309 case Type::FunctionNoProto:
4310 case Type::FunctionProto:
4311 // Itanium C++ ABI 2.9.5p5:
4312 // abi::__function_type_info adds no data members to std::type_info.
4313 break;
4314
4315 case Type::Enum:
4316 // Itanium C++ ABI 2.9.5p5:
4317 // abi::__enum_type_info adds no data members to std::type_info.
4318 break;
4319
4320 case Type::Record: {
4321 const auto *RD = cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl())
4322 ->getDefinitionOrSelf();
4323 if (!RD->hasDefinition() || !RD->getNumBases()) {
4324 // We don't need to emit any fields.
4325 break;
4326 }
4327
4329 BuildSIClassTypeInfo(RD);
4330 else
4331 BuildVMIClassTypeInfo(RD);
4332
4333 break;
4334 }
4335
4336 case Type::ObjCObject:
4337 case Type::ObjCInterface:
4338 BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
4339 break;
4340
4341 case Type::ObjCObjectPointer:
4342 BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
4343 break;
4344
4345 case Type::Pointer:
4346 BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
4347 break;
4348
4349 case Type::MemberPointer:
4350 BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
4351 break;
4352
4353 case Type::Atomic:
4354 // No fields, at least for the moment.
4355 break;
4356
4357 case Type::OverflowBehavior:
4358 break;
4359
4360 case Type::HLSLAttributedResource:
4361 case Type::HLSLInlineSpirv:
4362 llvm_unreachable("HLSL doesn't support RTTI");
4363 }
4364
4365 GV->replaceInitializer(llvm::ConstantStruct::getAnon(Fields));
4366
4367 // Export the typeinfo in the same circumstances as the vtable is exported.
4368 auto GVDLLStorageClass = DLLStorageClass;
4369 if (CGM.getTarget().hasPS4DLLImportExport() &&
4370 GVDLLStorageClass != llvm::GlobalVariable::DLLExportStorageClass) {
4371 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
4372 const auto *RD =
4373 cast<CXXRecordDecl>(RecordTy->getDecl())->getDefinitionOrSelf();
4374 if (RD->hasAttr<DLLExportAttr>() ||
4376 GVDLLStorageClass = llvm::GlobalVariable::DLLExportStorageClass;
4377 }
4378 }
4379
4380 // If there's already an old global variable, replace it with the new one.
4381 if (OldGV) {
4382 GV->takeName(OldGV);
4383 OldGV->replaceAllUsesWith(GV);
4384 OldGV->eraseFromParent();
4385 }
4386
4387 if (CGM.supportsCOMDAT() && GV->isWeakForLinker())
4388 GV->setComdat(M.getOrInsertComdat(GV->getName()));
4389
4390 CharUnits Align = CGM.getContext().toCharUnitsFromBits(
4392 GV->setAlignment(Align.getAsAlign());
4393
4394 // The Itanium ABI specifies that type_info objects must be globally
4395 // unique, with one exception: if the type is an incomplete class
4396 // type or a (possibly indirect) pointer to one. That exception
4397 // affects the general case of comparing type_info objects produced
4398 // by the typeid operator, which is why the comparison operators on
4399 // std::type_info generally use the type_info name pointers instead
4400 // of the object addresses. However, the language's built-in uses
4401 // of RTTI generally require class types to be complete, even when
4402 // manipulating pointers to those class types. This allows the
4403 // implementation of dynamic_cast to rely on address equality tests,
4404 // which is much faster.
4405
4406 // All of this is to say that it's important that both the type_info
4407 // object and the type_info name be uniqued when weakly emitted.
4408
4409 TypeName->setVisibility(Visibility);
4410 CGM.setDSOLocal(TypeName);
4411
4412 GV->setVisibility(Visibility);
4413 CGM.setDSOLocal(GV);
4414
4415 TypeName->setDLLStorageClass(DLLStorageClass);
4416 GV->setDLLStorageClass(GVDLLStorageClass);
4417
4418 TypeName->setPartition(CGM.getCodeGenOpts().SymbolPartition);
4419 GV->setPartition(CGM.getCodeGenOpts().SymbolPartition);
4420
4421 return GV;
4422}
4423
4424/// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
4425/// for the given Objective-C object type.
4426void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
4427 // Drop qualifiers.
4428 const Type *T = OT->getBaseType().getTypePtr();
4430
4431 // The builtin types are abi::__class_type_infos and don't require
4432 // extra fields.
4433 if (isa<BuiltinType>(T)) return;
4434
4435 ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
4436 ObjCInterfaceDecl *Super = Class->getSuperClass();
4437
4438 // Root classes are also __class_type_info.
4439 if (!Super) return;
4440
4441 QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
4442
4443 // Everything else is single inheritance.
4444 llvm::Constant *BaseTypeInfo =
4445 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy);
4446 Fields.push_back(BaseTypeInfo);
4447}
4448
4449/// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
4450/// inheritance, according to the Itanium C++ ABI, 2.95p6b.
4451void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
4452 // Itanium C++ ABI 2.9.5p6b:
4453 // It adds to abi::__class_type_info a single member pointing to the
4454 // type_info structure for the base type,
4455 llvm::Constant *BaseTypeInfo =
4456 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType());
4457 Fields.push_back(BaseTypeInfo);
4458}
4459
4460namespace {
4461 /// SeenBases - Contains virtual and non-virtual bases seen when traversing
4462 /// a class hierarchy.
4463 struct SeenBases {
4464 llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
4465 llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
4466 };
4467}
4468
4469/// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
4470/// abi::__vmi_class_type_info.
4471///
4473 SeenBases &Bases) {
4474
4475 unsigned Flags = 0;
4476
4477 auto *BaseDecl = Base->getType()->castAsCXXRecordDecl();
4478 if (Base->isVirtual()) {
4479 // Mark the virtual base as seen.
4480 if (!Bases.VirtualBases.insert(BaseDecl).second) {
4481 // If this virtual base has been seen before, then the class is diamond
4482 // shaped.
4483 Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped;
4484 } else {
4485 if (Bases.NonVirtualBases.count(BaseDecl))
4486 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
4487 }
4488 } else {
4489 // Mark the non-virtual base as seen.
4490 if (!Bases.NonVirtualBases.insert(BaseDecl).second) {
4491 // If this non-virtual base has been seen before, then the class has non-
4492 // diamond shaped repeated inheritance.
4493 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
4494 } else {
4495 if (Bases.VirtualBases.count(BaseDecl))
4496 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
4497 }
4498 }
4499
4500 // Walk all bases.
4501 for (const auto &I : BaseDecl->bases())
4502 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
4503
4504 return Flags;
4505}
4506
4508 unsigned Flags = 0;
4509 SeenBases Bases;
4510
4511 // Walk all bases.
4512 for (const auto &I : RD->bases())
4513 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
4514
4515 return Flags;
4516}
4517
4518/// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
4519/// classes with bases that do not satisfy the abi::__si_class_type_info
4520/// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
4521void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
4522 llvm::Type *UnsignedIntLTy =
4524
4525 // Itanium C++ ABI 2.9.5p6c:
4526 // __flags is a word with flags describing details about the class
4527 // structure, which may be referenced by using the __flags_masks
4528 // enumeration. These flags refer to both direct and indirect bases.
4529 unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
4530 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
4531
4532 // Itanium C++ ABI 2.9.5p6c:
4533 // __base_count is a word with the number of direct proper base class
4534 // descriptions that follow.
4535 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
4536
4537 if (!RD->getNumBases())
4538 return;
4539
4540 // Now add the base class descriptions.
4541
4542 // Itanium C++ ABI 2.9.5p6c:
4543 // __base_info[] is an array of base class descriptions -- one for every
4544 // direct proper base. Each description is of the type:
4545 //
4546 // struct abi::__base_class_type_info {
4547 // public:
4548 // const __class_type_info *__base_type;
4549 // long __offset_flags;
4550 //
4551 // enum __offset_flags_masks {
4552 // __virtual_mask = 0x1,
4553 // __public_mask = 0x2,
4554 // __offset_shift = 8
4555 // };
4556 // };
4557
4558 // If we're in mingw and 'long' isn't wide enough for a pointer, use 'long
4559 // long' instead of 'long' for __offset_flags. libstdc++abi uses long long on
4560 // LLP64 platforms.
4561 // FIXME: Consider updating libc++abi to match, and extend this logic to all
4562 // LLP64 platforms.
4563 QualType OffsetFlagsTy = CGM.getContext().LongTy;
4564 const TargetInfo &TI = CGM.getContext().getTargetInfo();
4565 if (TI.getTriple().isOSCygMing() &&
4566 TI.getPointerWidth(LangAS::Default) > TI.getLongWidth())
4567 OffsetFlagsTy = CGM.getContext().LongLongTy;
4568 llvm::Type *OffsetFlagsLTy =
4569 CGM.getTypes().ConvertType(OffsetFlagsTy);
4570
4571 for (const auto &Base : RD->bases()) {
4572 // The __base_type member points to the RTTI for the base type.
4573 Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType()));
4574
4575 auto *BaseDecl = Base.getType()->castAsCXXRecordDecl();
4576 int64_t OffsetFlags = 0;
4577
4578 // All but the lower 8 bits of __offset_flags are a signed offset.
4579 // For a non-virtual base, this is the offset in the object of the base
4580 // subobject. For a virtual base, this is the offset in the virtual table of
4581 // the virtual base offset for the virtual base referenced (negative).
4582 CharUnits Offset;
4583 if (Base.isVirtual())
4584 Offset =
4586 else {
4587 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
4588 Offset = Layout.getBaseClassOffset(BaseDecl);
4589 };
4590
4591 OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
4592
4593 // The low-order byte of __offset_flags contains flags, as given by the
4594 // masks from the enumeration __offset_flags_masks.
4595 if (Base.isVirtual())
4596 OffsetFlags |= BCTI_Virtual;
4597 if (Base.getAccessSpecifier() == AS_public)
4598 OffsetFlags |= BCTI_Public;
4599
4600 Fields.push_back(llvm::ConstantInt::getSigned(OffsetFlagsLTy, OffsetFlags));
4601 }
4602}
4603
4604/// Compute the flags for a __pbase_type_info, and remove the corresponding
4605/// pieces from \p Type.
4607 unsigned Flags = 0;
4608
4609 if (Type.isConstQualified())
4610 Flags |= ItaniumRTTIBuilder::PTI_Const;
4611 if (Type.isVolatileQualified())
4612 Flags |= ItaniumRTTIBuilder::PTI_Volatile;
4613 if (Type.isRestrictQualified())
4614 Flags |= ItaniumRTTIBuilder::PTI_Restrict;
4615 Type = Type.getUnqualifiedType();
4616
4617 // Itanium C++ ABI 2.9.5p7:
4618 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
4619 // incomplete class type, the incomplete target type flag is set.
4621 Flags |= ItaniumRTTIBuilder::PTI_Incomplete;
4622
4623 if (auto *Proto = Type->getAs<FunctionProtoType>()) {
4624 if (Proto->isNothrow()) {
4625 Flags |= ItaniumRTTIBuilder::PTI_Noexcept;
4627 }
4628 }
4629
4630 return Flags;
4631}
4632
4633/// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
4634/// used for pointer types.
4635void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
4636 // Itanium C++ ABI 2.9.5p7:
4637 // __flags is a flag word describing the cv-qualification and other
4638 // attributes of the type pointed to
4639 unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy);
4640
4641 llvm::Type *UnsignedIntLTy =
4643 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
4644
4645 // Itanium C++ ABI 2.9.5p7:
4646 // __pointee is a pointer to the std::type_info derivation for the
4647 // unqualified type being pointed to.
4648 llvm::Constant *PointeeTypeInfo =
4649 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy);
4650 Fields.push_back(PointeeTypeInfo);
4651}
4652
4653/// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
4654/// struct, used for member pointer types.
4655void
4656ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
4657 QualType PointeeTy = Ty->getPointeeType();
4658
4659 // Itanium C++ ABI 2.9.5p7:
4660 // __flags is a flag word describing the cv-qualification and other
4661 // attributes of the type pointed to.
4662 unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy);
4663
4664 const auto *RD = Ty->getMostRecentCXXRecordDecl();
4665 if (!RD->hasDefinition())
4666 Flags |= PTI_ContainingClassIncomplete;
4667
4668 llvm::Type *UnsignedIntLTy =
4670 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
4671
4672 // Itanium C++ ABI 2.9.5p7:
4673 // __pointee is a pointer to the std::type_info derivation for the
4674 // unqualified type being pointed to.
4675 llvm::Constant *PointeeTypeInfo =
4676 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy);
4677 Fields.push_back(PointeeTypeInfo);
4678
4679 // Itanium C++ ABI 2.9.5p9:
4680 // __context is a pointer to an abi::__class_type_info corresponding to the
4681 // class type containing the member pointed to
4682 // (e.g., the "A" in "int A::*").
4684 Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(T));
4685}
4686
4687llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) {
4688 return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty);
4689}
4690
4691void ItaniumCXXABI::EmitFundamentalRTTIDescriptors(const CXXRecordDecl *RD) {
4692 // Types added here must also be added to TypeInfoIsInStandardLibrary.
4693 QualType FundamentalTypes[] = {
4694 getContext().VoidTy, getContext().NullPtrTy,
4695 getContext().BoolTy, getContext().WCharTy,
4696 getContext().CharTy, getContext().UnsignedCharTy,
4697 getContext().SignedCharTy, getContext().ShortTy,
4698 getContext().UnsignedShortTy, getContext().IntTy,
4699 getContext().UnsignedIntTy, getContext().LongTy,
4700 getContext().UnsignedLongTy, getContext().LongLongTy,
4701 getContext().UnsignedLongLongTy, getContext().Int128Ty,
4702 getContext().UnsignedInt128Ty, getContext().HalfTy,
4703 getContext().FloatTy, getContext().DoubleTy,
4704 getContext().LongDoubleTy, getContext().Float128Ty,
4705 getContext().Char8Ty, getContext().Char16Ty,
4706 getContext().Char32Ty
4707 };
4708 llvm::GlobalValue::DLLStorageClassTypes DLLStorageClass =
4709 RD->hasAttr<DLLExportAttr>() || CGM.shouldMapVisibilityToDLLExport(RD)
4710 ? llvm::GlobalValue::DLLExportStorageClass
4711 : llvm::GlobalValue::DefaultStorageClass;
4712 llvm::GlobalValue::VisibilityTypes Visibility =
4714 for (const QualType &FundamentalType : FundamentalTypes) {
4715 QualType PointerType = getContext().getPointerType(FundamentalType);
4716 QualType PointerTypeConst = getContext().getPointerType(
4717 FundamentalType.withConst());
4718 for (QualType Type : {FundamentalType, PointerType, PointerTypeConst})
4719 ItaniumRTTIBuilder(*this).BuildTypeInfo(
4720 Type, llvm::GlobalValue::ExternalLinkage,
4721 Visibility, DLLStorageClass);
4722 }
4723}
4724
4725/// What sort of uniqueness rules should we use for the RTTI for the
4726/// given type?
4727ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness(
4728 QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const {
4729 if (shouldRTTIBeUnique())
4730 return RUK_Unique;
4731
4732 // It's only necessary for linkonce_odr or weak_odr linkage.
4733 if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage &&
4734 Linkage != llvm::GlobalValue::WeakODRLinkage)
4735 return RUK_Unique;
4736
4737 // It's only necessary with default visibility.
4738 if (CanTy->getVisibility() != DefaultVisibility)
4739 return RUK_Unique;
4740
4741 // If we're not required to publish this symbol, hide it.
4742 if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
4743 return RUK_NonUniqueHidden;
4744
4745 // If we're required to publish this symbol, as we might be under an
4746 // explicit instantiation, leave it with default visibility but
4747 // enable string-comparisons.
4748 assert(Linkage == llvm::GlobalValue::WeakODRLinkage);
4749 return RUK_NonUniqueVisible;
4750}
4751
4752// Find out how to codegen the complete destructor and constructor
4753namespace {
4754enum class StructorCodegen { Emit, RAUW, Alias, COMDAT };
4755}
4756static StructorCodegen getCodegenToUse(CodeGenModule &CGM,
4757 const CXXMethodDecl *MD) {
4758 if (!CGM.getCodeGenOpts().CXXCtorDtorAliases)
4759 return StructorCodegen::Emit;
4760
4761 // The complete and base structors are not equivalent if there are any virtual
4762 // bases, so emit separate functions.
4763 if (MD->getParent()->getNumVBases())
4764 return StructorCodegen::Emit;
4765
4767 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
4769 } else {
4770 const auto *CD = cast<CXXConstructorDecl>(MD);
4772 }
4773 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
4774
4775 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage))
4776 return StructorCodegen::RAUW;
4777
4778 // FIXME: Should we allow available_externally aliases?
4779 if (!llvm::GlobalAlias::isValidLinkage(Linkage))
4780 return StructorCodegen::RAUW;
4781
4782 if (llvm::GlobalValue::isWeakForLinker(Linkage)) {
4783 // Only ELF and wasm support COMDATs with arbitrary names (C5/D5).
4784 if (CGM.getTarget().getTriple().isOSBinFormatELF() ||
4785 CGM.getTarget().getTriple().isOSBinFormatWasm())
4786 return StructorCodegen::COMDAT;
4787 return StructorCodegen::Emit;
4788 }
4789
4790 return StructorCodegen::Alias;
4791}
4792
4795 GlobalDecl TargetDecl) {
4796 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
4797
4798 StringRef MangledName = CGM.getMangledName(AliasDecl);
4799 llvm::GlobalValue *Entry = CGM.GetGlobalValue(MangledName);
4800 if (Entry && !Entry->isDeclaration())
4801 return;
4802
4803 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(TargetDecl));
4804
4805 // Create the alias with no name.
4806 auto *Alias = llvm::GlobalAlias::create(Linkage, "", Aliasee);
4807
4808 // Constructors and destructors are always unnamed_addr.
4809 Alias->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4810
4811 // Switch any previous uses to the alias.
4812 if (Entry) {
4813 assert(Entry->getType() == Aliasee->getType() &&
4814 "declaration exists with different type");
4815 Alias->takeName(Entry);
4816 Entry->replaceAllUsesWith(Alias);
4817 Entry->eraseFromParent();
4818 } else {
4819 Alias->setName(MangledName);
4820 }
4821
4822 // Finally, set up the alias with its proper name and attributes.
4823 CGM.SetCommonAttributes(AliasDecl, Alias);
4824}
4825
4826void ItaniumCXXABI::emitCXXStructor(GlobalDecl GD) {
4827 auto *MD = cast<CXXMethodDecl>(GD.getDecl());
4828 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
4829 const CXXDestructorDecl *DD = CD ? nullptr : cast<CXXDestructorDecl>(MD);
4830
4831 StructorCodegen CGType = getCodegenToUse(CGM, MD);
4832
4833 if (CD ? GD.getCtorType() == Ctor_Complete
4834 : GD.getDtorType() == Dtor_Complete) {
4835 GlobalDecl BaseDecl;
4836 if (CD)
4837 BaseDecl = GD.getWithCtorType(Ctor_Base);
4838 else
4839 BaseDecl = GD.getWithDtorType(Dtor_Base);
4840
4841 if (CGType == StructorCodegen::Alias || CGType == StructorCodegen::COMDAT) {
4842 emitConstructorDestructorAlias(CGM, GD, BaseDecl);
4843 return;
4844 }
4845
4846 if (CGType == StructorCodegen::RAUW) {
4847 StringRef MangledName = CGM.getMangledName(GD);
4848 auto *Aliasee = CGM.GetAddrOfGlobal(BaseDecl);
4849 CGM.addReplacement(MangledName, Aliasee);
4850 return;
4851 }
4852 }
4853
4854 // The base destructor is equivalent to the base destructor of its
4855 // base class if there is exactly one non-virtual base class with a
4856 // non-trivial destructor, there are no fields with a non-trivial
4857 // destructor, and the body of the destructor is trivial.
4858 if (DD && GD.getDtorType() == Dtor_Base &&
4859 CGType != StructorCodegen::COMDAT &&
4861 return;
4862
4863 // FIXME: The deleting destructor is equivalent to the selected operator
4864 // delete if:
4865 // * either the delete is a destroying operator delete or the destructor
4866 // would be trivial if it weren't virtual,
4867 // * the conversion from the 'this' parameter to the first parameter of the
4868 // destructor is equivalent to a bitcast,
4869 // * the destructor does not have an implicit "this" return, and
4870 // * the operator delete has the same calling convention and IR function type
4871 // as the destructor.
4872 // In such cases we should try to emit the deleting dtor as an alias to the
4873 // selected 'operator delete'.
4874
4875 llvm::Function *Fn = CGM.codegenCXXStructor(GD);
4876
4877 if (CGType == StructorCodegen::COMDAT) {
4878 SmallString<256> Buffer;
4879 llvm::raw_svector_ostream Out(Buffer);
4880 if (DD)
4881 getMangleContext().mangleCXXDtorComdat(DD, Out);
4882 else
4883 getMangleContext().mangleCXXCtorComdat(CD, Out);
4884 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(Out.str());
4885 Fn->setComdat(C);
4886 } else {
4887 CGM.maybeSetTrivialComdat(*MD, *Fn);
4888 }
4889}
4890
4891static llvm::FunctionCallee getBeginCatchFn(CodeGenModule &CGM) {
4892 // void *__cxa_begin_catch(void*);
4893 llvm::FunctionType *FTy = llvm::FunctionType::get(
4894 CGM.Int8PtrTy, CGM.Int8PtrTy, /*isVarArg=*/false);
4895
4896 return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
4897}
4898
4899static llvm::FunctionCallee getEndCatchFn(CodeGenModule &CGM) {
4900 // void __cxa_end_catch();
4901 llvm::FunctionType *FTy =
4902 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
4903
4904 return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
4905}
4906
4907static llvm::FunctionCallee getGetExceptionPtrFn(CodeGenModule &CGM) {
4908 // void *__cxa_get_exception_ptr(void*);
4909 llvm::FunctionType *FTy = llvm::FunctionType::get(
4910 CGM.Int8PtrTy, CGM.Int8PtrTy, /*isVarArg=*/false);
4911
4912 return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
4913}
4914
4915namespace {
4916 /// A cleanup to call __cxa_end_catch. In many cases, the caught
4917 /// exception type lets us state definitively that the thrown exception
4918 /// type does not have a destructor. In particular:
4919 /// - Catch-alls tell us nothing, so we have to conservatively
4920 /// assume that the thrown exception might have a destructor.
4921 /// - Catches by reference behave according to their base types.
4922 /// - Catches of non-record types will only trigger for exceptions
4923 /// of non-record types, which never have destructors.
4924 /// - Catches of record types can trigger for arbitrary subclasses
4925 /// of the caught type, so we have to assume the actual thrown
4926 /// exception type might have a throwing destructor, even if the
4927 /// caught type's destructor is trivial or nothrow.
4928 struct CallEndCatch final : EHScopeStack::Cleanup {
4929 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
4930 bool MightThrow;
4931
4932 void Emit(CodeGenFunction &CGF, Flags flags) override {
4933 if (!MightThrow) {
4935 return;
4936 }
4937
4939 }
4940 };
4941}
4942
4943/// Emits a call to __cxa_begin_catch and enters a cleanup to call
4944/// __cxa_end_catch. If -fassume-nothrow-exception-dtor is specified, we assume
4945/// that the exception object's dtor is nothrow, therefore the __cxa_end_catch
4946/// call can be marked as nounwind even if EndMightThrow is true.
4947///
4948/// \param EndMightThrow - true if __cxa_end_catch might throw
4949static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
4950 llvm::Value *Exn,
4951 bool EndMightThrow) {
4952 llvm::CallInst *call =
4954
4955 CGF.EHStack.pushCleanup<CallEndCatch>(
4957 EndMightThrow && !CGF.CGM.getLangOpts().AssumeNothrowExceptionDtor);
4958
4959 return call;
4960}
4961
4962/// A "special initializer" callback for initializing a catch
4963/// parameter during catch initialization.
4965 const VarDecl &CatchParam,
4966 Address ParamAddr,
4967 SourceLocation Loc) {
4968 // Load the exception from where the landing pad saved it.
4969 llvm::Value *Exn = CGF.getExceptionFromSlot();
4970
4971 CanQualType CatchType =
4972 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
4973 llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
4974
4975 // If we're catching by reference, we can just cast the object
4976 // pointer to the appropriate pointer.
4977 if (isa<ReferenceType>(CatchType)) {
4978 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
4979 bool EndCatchMightThrow = CaughtType->isRecordType();
4980
4981 // __cxa_begin_catch returns the adjusted object pointer.
4982 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
4983
4984 // We have no way to tell the personality function that we're
4985 // catching by reference, so if we're catching a pointer,
4986 // __cxa_begin_catch will actually return that pointer by value.
4987 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
4988 QualType PointeeType = PT->getPointeeType();
4989
4990 // When catching by reference, generally we should just ignore
4991 // this by-value pointer and use the exception object instead.
4992 if (!PointeeType->isRecordType()) {
4993
4994 // Exn points to the struct _Unwind_Exception header, which
4995 // we have to skip past in order to reach the exception data.
4996 unsigned HeaderSize =
4998 AdjustedExn =
4999 CGF.Builder.CreateConstGEP1_32(CGF.Int8Ty, Exn, HeaderSize);
5000
5001 // However, if we're catching a pointer-to-record type that won't
5002 // work, because the personality function might have adjusted
5003 // the pointer. There's actually no way for us to fully satisfy
5004 // the language/ABI contract here: we can't use Exn because it
5005 // might have the wrong adjustment, but we can't use the by-value
5006 // pointer because it's off by a level of abstraction.
5007 //
5008 // The current solution is to dump the adjusted pointer into an
5009 // alloca, which breaks language semantics (because changing the
5010 // pointer doesn't change the exception) but at least works.
5011 // The better solution would be to filter out non-exact matches
5012 // and rethrow them, but this is tricky because the rethrow
5013 // really needs to be catchable by other sites at this landing
5014 // pad. The best solution is to fix the personality function.
5015 } else {
5016 // Pull the pointer for the reference type off.
5017 llvm::Type *PtrTy = CGF.ConvertTypeForMem(CaughtType);
5018
5019 // Create the temporary and write the adjusted pointer into it.
5020 Address ExnPtrTmp =
5021 CGF.CreateTempAlloca(PtrTy, CGF.getPointerAlign(), "exn.byref.tmp");
5022 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
5023 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
5024
5025 // Bind the reference to the temporary.
5026 AdjustedExn = ExnPtrTmp.emitRawPointer(CGF);
5027 }
5028 }
5029
5030 llvm::Value *ExnCast =
5031 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
5032 CGF.Builder.CreateStore(ExnCast, ParamAddr);
5033 return;
5034 }
5035
5036 // Scalars and complexes.
5037 TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType);
5038 if (TEK != TEK_Aggregate) {
5039 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
5040
5041 // If the catch type is a pointer type, __cxa_begin_catch returns
5042 // the pointer by value.
5043 if (CatchType->hasPointerRepresentation()) {
5044 llvm::Value *CastExn =
5045 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
5046
5047 switch (CatchType.getQualifiers().getObjCLifetime()) {
5049 CastExn = CGF.EmitARCRetainNonBlock(CastExn);
5050 [[fallthrough]];
5051
5055 CGF.Builder.CreateStore(CastExn, ParamAddr);
5056 return;
5057
5059 CGF.EmitARCInitWeak(ParamAddr, CastExn);
5060 return;
5061 }
5062 llvm_unreachable("bad ownership qualifier!");
5063 }
5064
5065 // Otherwise, it returns a pointer into the exception object.
5066
5067 LValue srcLV = CGF.MakeNaturalAlignAddrLValue(AdjustedExn, CatchType);
5068 LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType);
5069 switch (TEK) {
5070 case TEK_Complex:
5071 CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV,
5072 /*init*/ true);
5073 return;
5074 case TEK_Scalar: {
5075 llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc);
5076 CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true);
5077 return;
5078 }
5079 case TEK_Aggregate:
5080 llvm_unreachable("evaluation kind filtered out!");
5081 }
5082 llvm_unreachable("bad evaluation kind");
5083 }
5084
5085 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
5086 auto catchRD = CatchType->getAsCXXRecordDecl();
5087 CharUnits caughtExnAlignment = CGF.CGM.getClassPointerAlignment(catchRD);
5088
5089 llvm::Type *PtrTy = CGF.DefaultPtrTy;
5090
5091 // Check for a copy expression. If we don't have a copy expression,
5092 // that means a trivial copy is okay.
5093 const Expr *copyExpr = CatchParam.getInit();
5094 if (!copyExpr) {
5095 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
5096 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
5097 LLVMCatchTy, caughtExnAlignment);
5098 LValue Dest = CGF.MakeAddrLValue(ParamAddr, CatchType);
5099 LValue Src = CGF.MakeAddrLValue(adjustedExn, CatchType);
5100 CGF.EmitAggregateCopy(Dest, Src, CatchType, AggValueSlot::DoesNotOverlap);
5101 return;
5102 }
5103
5104 // We have to call __cxa_get_exception_ptr to get the adjusted
5105 // pointer before copying.
5106 llvm::CallInst *rawAdjustedExn =
5108
5109 // Cast that to the appropriate type.
5110 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
5111 LLVMCatchTy, caughtExnAlignment);
5112
5113 // The copy expression is defined in terms of an OpaqueValueExpr.
5114 // Find it and map it to the adjusted expression.
5116 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
5117 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
5118
5119 // Call the copy ctor in a terminate scope.
5120 CGF.EHStack.pushTerminate();
5121
5122 // Perform the copy construction.
5123 CGF.EmitAggExpr(copyExpr,
5124 AggValueSlot::forAddr(ParamAddr, Qualifiers(),
5129
5130 // Leave the terminate scope.
5131 CGF.EHStack.popTerminate();
5132
5133 // Undo the opaque value mapping.
5134 opaque.pop();
5135
5136 // Finally we can call __cxa_begin_catch.
5137 CallBeginCatch(CGF, Exn, true);
5138}
5139
5140/// Begins a catch statement by initializing the catch variable and
5141/// calling __cxa_begin_catch.
5142void ItaniumCXXABI::emitBeginCatch(CodeGenFunction &CGF,
5143 const CXXCatchStmt *S) {
5144 // We have to be very careful with the ordering of cleanups here:
5145 // C++ [except.throw]p4:
5146 // The destruction [of the exception temporary] occurs
5147 // immediately after the destruction of the object declared in
5148 // the exception-declaration in the handler.
5149 //
5150 // So the precise ordering is:
5151 // 1. Construct catch variable.
5152 // 2. __cxa_begin_catch
5153 // 3. Enter __cxa_end_catch cleanup
5154 // 4. Enter dtor cleanup
5155 //
5156 // We do this by using a slightly abnormal initialization process.
5157 // Delegation sequence:
5158 // - ExitCXXTryStmt opens a RunCleanupsScope
5159 // - EmitAutoVarAlloca creates the variable and debug info
5160 // - InitCatchParam initializes the variable from the exception
5161 // - CallBeginCatch calls __cxa_begin_catch
5162 // - CallBeginCatch enters the __cxa_end_catch cleanup
5163 // - EmitAutoVarCleanups enters the variable destructor cleanup
5164 // - EmitCXXTryStmt emits the code for the catch body
5165 // - EmitCXXTryStmt close the RunCleanupsScope
5166
5167 VarDecl *CatchParam = S->getExceptionDecl();
5168 if (!CatchParam) {
5169 llvm::Value *Exn = CGF.getExceptionFromSlot();
5170 CallBeginCatch(CGF, Exn, true);
5171 return;
5172 }
5173
5174 // Emit the local.
5175 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
5176 {
5177 ApplyAtomGroup Grp(CGF.getDebugInfo());
5178 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF),
5179 S->getBeginLoc());
5180 }
5181 CGF.EmitAutoVarCleanups(var);
5182}
5183
5184/// Get or define the following function:
5185/// void @__clang_call_terminate(i8* %exn) nounwind noreturn
5186/// This code is used only in C++.
5187static llvm::FunctionCallee getClangCallTerminateFn(CodeGenModule &CGM) {
5188 ASTContext &C = CGM.getContext();
5190 C.VoidTy, {C.getPointerType(C.CharTy)});
5191 llvm::FunctionType *fnTy = CGM.getTypes().GetFunctionType(FI);
5192 llvm::FunctionCallee fnRef = CGM.CreateRuntimeFunction(
5193 fnTy, "__clang_call_terminate", llvm::AttributeList(), /*Local=*/true);
5194 llvm::Function *fn =
5195 cast<llvm::Function>(fnRef.getCallee()->stripPointerCasts());
5196 if (fn->empty()) {
5197 CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, fn, /*IsThunk=*/false);
5199 fn->setDoesNotThrow();
5200 fn->setDoesNotReturn();
5201
5202 // What we really want is to massively penalize inlining without
5203 // forbidding it completely. The difference between that and
5204 // 'noinline' is negligible.
5205 fn->addFnAttr(llvm::Attribute::NoInline);
5206
5207 // Allow this function to be shared across translation units, but
5208 // we don't want it to turn into an exported symbol.
5209 fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
5210 fn->setVisibility(llvm::Function::HiddenVisibility);
5211 if (CGM.supportsCOMDAT())
5212 fn->setComdat(CGM.getModule().getOrInsertComdat(fn->getName()));
5213
5214 // Set up the function.
5215 llvm::BasicBlock *entry =
5216 llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn);
5217 CGBuilderTy builder(CGM, entry);
5218
5219 // Pull the exception pointer out of the parameter list.
5220 llvm::Value *exn = &*fn->arg_begin();
5221
5222 // Call __cxa_begin_catch(exn).
5223 llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn);
5224 catchCall->setDoesNotThrow();
5225 catchCall->setCallingConv(CGM.getRuntimeCC());
5226
5227 // Call std::terminate().
5228 llvm::CallInst *termCall = builder.CreateCall(CGM.getTerminateFn());
5229 termCall->setDoesNotThrow();
5230 termCall->setDoesNotReturn();
5231 termCall->setCallingConv(CGM.getRuntimeCC());
5232
5233 // std::terminate cannot return.
5234 builder.CreateUnreachable();
5235 }
5236 return fnRef;
5237}
5238
5239llvm::CallInst *
5240ItaniumCXXABI::emitTerminateForUnexpectedException(CodeGenFunction &CGF,
5241 llvm::Value *Exn) {
5242 // In C++, we want to call __cxa_begin_catch() before terminating.
5243 if (Exn) {
5244 assert(CGF.CGM.getLangOpts().CPlusPlus);
5246 }
5247 return CGF.EmitNounwindRuntimeCall(CGF.CGM.getTerminateFn());
5248}
5249
5250std::pair<llvm::Value *, const CXXRecordDecl *>
5251ItaniumCXXABI::LoadVTablePtr(CodeGenFunction &CGF, Address This,
5252 const CXXRecordDecl *RD) {
5253 return {CGF.GetVTablePtr(This, CGM.Int8PtrTy, RD), RD};
5254}
5255
5256llvm::Constant *
5257ItaniumCXXABI::getSignedVirtualMemberFunctionPointer(const CXXMethodDecl *MD) {
5258 const CXXMethodDecl *origMD =
5261 .getDecl());
5262 llvm::Constant *thunk = getOrCreateVirtualFunctionPointerThunk(origMD);
5263 QualType funcType = CGM.getContext().getMemberPointerType(
5264 MD->getType(), /*Qualifier=*/std::nullopt, MD->getParent());
5265 return CGM.getMemberFunctionPointer(thunk, funcType);
5266}
5267
5268void WebAssemblyCXXABI::emitBeginCatch(CodeGenFunction &CGF,
5269 const CXXCatchStmt *C) {
5270 if (CGF.getTarget().hasFeature("exception-handling"))
5271 CGF.EHStack.pushCleanup<CatchRetScope>(
5273 ItaniumCXXABI::emitBeginCatch(CGF, C);
5274}
5275
5276llvm::CallInst *
5277WebAssemblyCXXABI::emitTerminateForUnexpectedException(CodeGenFunction &CGF,
5278 llvm::Value *Exn) {
5279 // Itanium ABI calls __clang_call_terminate(), which __cxa_begin_catch() on
5280 // the violating exception to mark it handled, but it is currently hard to do
5281 // with wasm EH instruction structure with catch/catch_all, we just call
5282 // std::terminate and ignore the violating exception as in CGCXXABI in Wasm EH
5283 // and call __clang_call_terminate only in Emscripten EH.
5284 // TODO Consider code transformation that makes calling __clang_call_terminate
5285 // in Wasm EH possible.
5286 if (Exn && !EHPersonality::get(CGF).isWasmPersonality()) {
5287 assert(CGF.CGM.getLangOpts().CPlusPlus);
5289 }
5291}
5292
5293/// Register a global destructor as best as we know how.
5294void XLCXXABI::registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
5295 llvm::FunctionCallee Dtor,
5296 llvm::Constant *Addr) {
5297 if (D.getTLSKind() != VarDecl::TLS_None) {
5298 llvm::PointerType *PtrTy = CGF.DefaultPtrTy;
5299
5300 // extern "C" int __pt_atexit_np(int flags, int(*)(int,...), ...);
5301 llvm::FunctionType *AtExitTy =
5302 llvm::FunctionType::get(CGM.IntTy, {CGM.IntTy, PtrTy}, true);
5303
5304 // Fetch the actual function.
5305 llvm::FunctionCallee AtExit =
5306 CGM.CreateRuntimeFunction(AtExitTy, "__pt_atexit_np");
5307
5308 // Create __dtor function for the var decl.
5309 llvm::Function *DtorStub = CGF.createTLSAtExitStub(D, Dtor, Addr, AtExit);
5310
5311 // Register above __dtor with atexit().
5312 // First param is flags and must be 0, second param is function ptr
5313 llvm::Value *NV = llvm::Constant::getNullValue(CGM.IntTy);
5314 CGF.EmitNounwindRuntimeCall(AtExit, {NV, DtorStub});
5315
5316 // Cannot unregister TLS __dtor so done
5317 return;
5318 }
5319
5320 // Create __dtor function for the var decl.
5321 llvm::Function *DtorStub =
5323
5324 // Register above __dtor with atexit().
5325 CGF.registerGlobalDtorWithAtExit(DtorStub);
5326
5327 // Emit __finalize function to unregister __dtor and (as appropriate) call
5328 // __dtor.
5329 emitCXXStermFinalizer(D, DtorStub, Addr);
5330}
5331
5332void XLCXXABI::emitCXXStermFinalizer(const VarDecl &D, llvm::Function *dtorStub,
5333 llvm::Constant *addr) {
5334 llvm::FunctionType *FTy = llvm::FunctionType::get(CGM.VoidTy, false);
5335 SmallString<256> FnName;
5336 {
5337 llvm::raw_svector_ostream Out(FnName);
5338 getMangleContext().mangleDynamicStermFinalizer(&D, Out);
5339 }
5340
5341 // Create the finalization action associated with a variable.
5342 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
5343 llvm::Function *StermFinalizer = CGM.CreateGlobalInitOrCleanUpFunction(
5344 FTy, FnName.str(), FI, D.getLocation());
5345
5346 CodeGenFunction CGF(CGM);
5347
5348 CGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, StermFinalizer, FI,
5349 FunctionArgList(), D.getLocation(),
5350 D.getInit()->getExprLoc());
5351
5352 // The unatexit subroutine unregisters __dtor functions that were previously
5353 // registered by the atexit subroutine. If the referenced function is found,
5354 // the unatexit returns a value of 0, meaning that the cleanup is still
5355 // pending (and we should call the __dtor function).
5356 llvm::Value *V = CGF.unregisterGlobalDtorWithUnAtExit(dtorStub);
5357
5358 llvm::Value *NeedsDestruct = CGF.Builder.CreateIsNull(V, "needs_destruct");
5359
5360 llvm::BasicBlock *DestructCallBlock = CGF.createBasicBlock("destruct.call");
5361 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("destruct.end");
5362
5363 // Check if unatexit returns a value of 0. If it does, jump to
5364 // DestructCallBlock, otherwise jump to EndBlock directly.
5365 CGF.Builder.CreateCondBr(NeedsDestruct, DestructCallBlock, EndBlock);
5366
5367 CGF.EmitBlock(DestructCallBlock);
5368
5369 // Emit the call to dtorStub.
5370 llvm::CallInst *CI = CGF.Builder.CreateCall(dtorStub);
5371
5372 // Make sure the call and the callee agree on calling convention.
5373 CI->setCallingConv(dtorStub->getCallingConv());
5374
5375 CGF.EmitBlock(EndBlock);
5376
5377 CGF.FinishFunction();
5378
5379 if (auto *IPA = D.getAttr<InitPriorityAttr>()) {
5380 CGM.AddCXXPrioritizedStermFinalizerEntry(StermFinalizer,
5381 IPA->getPriority());
5383 getContext().GetGVALinkageForVariable(&D) == GVA_DiscardableODR) {
5384 // According to C++ [basic.start.init]p2, class template static data
5385 // members (i.e., implicitly or explicitly instantiated specializations)
5386 // have unordered initialization. As a consequence, we can put them into
5387 // their own llvm.global_dtors entry.
5388 CGM.AddCXXStermFinalizerToGlobalDtor(StermFinalizer, 65535);
5389 } else {
5390 CGM.AddCXXStermFinalizerEntry(StermFinalizer);
5391 }
5392}
#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 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::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 *)
Result
Implement __builtin_bit_cast and related operations.
static cir::GlobalLinkageKind getThreadLocalWrapperLinkage(GlobalOp op, clang::ASTContext &astCtx)
static bool isThreadWrapperReplaceable(cir::TLS_Model tls, clang::ASTContext &astCtx)
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:229
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:807
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:926
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:3226
Kind getKind() const
Definition TypeBase.h:3274
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:2669
bool isGlobalDelete() const
Definition ExprCXX.h:2655
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2132
bool isVirtual() const
Definition DeclCXX.h:2187
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2271
bool isInstance() const
Definition DeclCXX.h:2159
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2241
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:1232
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:388
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:64
static CGCallee forVirtual(const CallExpr *CE, GlobalDecl MD, Address Addr, llvm::FunctionType *FTy)
Definition CGCall.h:148
static CGCallee forDirect(llvm::Constant *functionPtr, const CGCalleeInfo &abstractInfo=CGCalleeInfo())
Definition CGCall.h:138
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:2812
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::Value * performAddrSpaceCast(llvm::Value *Src, llvm::Type *DestTy)
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:2695
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:5265
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:5292
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:4045
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:4474
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:1483
void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type, bool ForVirtualBase, bool Delegating, Address This, QualType ThisTy)
Definition CGClass.cpp:2635
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:3935
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:357
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:4193
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:158
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:5448
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:2884
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:2218
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:2369
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:663
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:4532
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:3071
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:3053
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:643
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:34
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:266
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:381
const CodeGenOptions & getCodeGenOpts() const
llvm::FunctionType * GetFunctionType(const CGFunctionInfo &Info)
GetFunctionType - Get the LLVM function type for.
Definition CGCall.cpp:1873
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:747
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:777
const CGFunctionInfo & arrangeNullaryFunction()
A nullary function is a freestanding function of type 'void ()'.
Definition CGCall.cpp:795
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:646
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:2122
bool isTranslationUnit() const
Definition DeclBase.h:2198
decl_range noload_decls() const
noload_decls_begin/end - Iterate over the declarations stored in this context that are currently load...
Definition DeclBase.h:2394
T * getAttr() const
Definition DeclBase.h:581
SourceLocation getLocation() const
Definition DeclBase.h:447
DeclContext * getDeclContext()
Definition DeclBase.h:456
bool hasAttr() const
Definition DeclBase.h:585
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:282
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:2939
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
Definition Decl.h:2344
bool isPureVirtual() const
Whether this virtual function is pure, i.e.
Definition Decl.h:2371
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5369
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, const IdentifierInfo *Id, QualType T, ImplicitParamKind ParamKind)
Create implicit parameter.
Definition Decl.cpp:5596
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:3715
CXXRecordDecl * getMostRecentCXXRecordDecl() const
Note: this can trigger extra deserialization when external AST sources are used.
Definition Type.cpp:5618
QualType getPointeeType() const
Definition TypeBase.h:3733
bool isMemberFunctionPointer() const
Returns true if the member type (i.e.
Definition TypeBase.h:3737
bool isMemberDataPointer() const
Returns true if the member type (i.e.
Definition TypeBase.h:3743
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:5171
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3390
QualType getPointeeType() const
Definition TypeBase.h:3400
A (possibly-)qualified type.
Definition TypeBase.h:937
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8485
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:8630
QualType getCanonicalType() const
Definition TypeBase.h:8497
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8539
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:4484
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:859
uint64_t getPointerWidth(LangAS AddrSpace) const
Return the width of pointers on this target, for the specified address space.
Definition TargetInfo.h:490
virtual bool hasPS4DLLImportExport() const
uint64_t getPointerAlign(LangAS AddrSpace) const
Definition TargetInfo.h:494
unsigned getLongWidth() const
getLongWidth/Align - Return the size of 'signed long' and 'unsigned long' for this target,...
Definition TargetInfo.h:536
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:1875
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:9342
bool isReferenceType() const
Definition TypeBase.h:8706
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:789
Visibility getVisibility() const
Determine the visibility of this type.
Definition TypeBase.h:3127
bool isMemberFunctionPointerType() const
Definition TypeBase.h:8767
Linkage getLinkage() const
Determine the linkage of this type.
Definition Type.cpp:5022
TypeClass getTypeClass() const
Definition TypeBase.h:2445
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9275
bool isRecordType() const
Definition TypeBase.h:8809
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:924
TLSKind getTLSKind() const
Definition Decl.cpp:2147
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:2236
bool isNoDestroy(const ASTContext &) const
Is destruction of this variable entirely suppressed?
Definition Decl.cpp:2794
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition Decl.h:1206
bool isInline() const
Whether this variable is (C++1z) inline.
Definition Decl.h:1564
const Expr * getInit() const
Definition Decl.h:1381
@ TLS_Dynamic
TLS with a dynamic initializer.
Definition Decl.h:950
@ TLS_None
Not a TLS variable.
Definition Decl.h:944
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition Decl.cpp:2354
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition Decl.h:1266
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:2737
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:3113
@ Address
A pointer to a ValueDecl.
Definition Primitives.h:28
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:213
@ GVA_DiscardableODR
Definition Linkage.h:75
@ Success
Annotation was successful.
Definition Parser.h:65
@ AS_public
Definition Specifiers.h:125
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
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:5979
@ 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
#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:5454
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