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 if (!CGM.shouldEmitRTTI())
2262 VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2263
2264 if (CGM.getTarget().hasPS4DLLImportExport())
2265 setVTableSelectiveDLLImportExport(CGM, VTable, RD);
2266
2267 CGM.setGVProperties(VTable, RD);
2268 return VTable;
2269}
2270
2271CGCallee ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
2272 GlobalDecl GD,
2273 Address This,
2274 llvm::Type *Ty,
2275 SourceLocation Loc) {
2276 llvm::Type *PtrTy = CGM.GlobalsInt8PtrTy;
2277 auto *MethodDecl = cast<CXXMethodDecl>(GD.getDecl());
2278 llvm::Value *VTable = CGF.GetVTablePtr(This, PtrTy, MethodDecl->getParent());
2279
2280 // For the translation of virtual functions, we need to map the (potential)
2281 // host vtable to the device vtable. This is done by calling the runtime
2282 // function
2283 // __llvm_omp_indirect_call_lookup.
2284 if (CGM.getLangOpts().OpenMPIsTargetDevice) {
2285 auto *NewPtrTy = CGM.VoidPtrTy;
2286 llvm::Type *RtlFnArgs[] = {NewPtrTy};
2287 llvm::FunctionCallee DeviceRtlFn = CGM.CreateRuntimeFunction(
2288 llvm::FunctionType::get(NewPtrTy, RtlFnArgs, false),
2289 "__llvm_omp_indirect_call_lookup");
2290 auto *BackupTy = VTable->getType();
2291 // Need to convert to generic address space
2292 VTable = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(VTable, NewPtrTy);
2293 VTable = CGF.EmitRuntimeCall(DeviceRtlFn, {VTable});
2294 // convert to original address space
2295 VTable = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(VTable, BackupTy);
2296 }
2297
2298 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
2299 llvm::Value *VFunc, *VTableSlotPtr = nullptr;
2300 auto &Schema = CGM.getCodeGenOpts().PointerAuth.CXXVirtualFunctionPointers;
2301
2302 llvm::Type *ComponentTy = CGM.getVTables().getVTableComponentType();
2303 uint64_t ByteOffset =
2304 VTableIndex * CGM.getDataLayout().getTypeSizeInBits(ComponentTy) / 8;
2305
2306 if (!Schema && CGF.ShouldEmitVTableTypeCheckedLoad(MethodDecl->getParent())) {
2307 VFunc = CGF.EmitVTableTypeCheckedLoad(MethodDecl->getParent(), VTable,
2308 PtrTy, ByteOffset);
2309 } else {
2310 CGF.EmitTypeMetadataCodeForVCall(MethodDecl->getParent(), VTable, Loc);
2311
2312 llvm::Value *VFuncLoad;
2313 if (CGM.getLangOpts().RelativeCXXABIVTables) {
2314 VFuncLoad = CGF.Builder.CreateCall(
2315 CGM.getIntrinsic(llvm::Intrinsic::load_relative, {CGM.Int32Ty}),
2316 {VTable, llvm::ConstantInt::get(CGM.Int32Ty, ByteOffset)});
2317 } else {
2318 VTableSlotPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
2319 PtrTy, VTable, VTableIndex, "vfn");
2320 VFuncLoad = CGF.Builder.CreateAlignedLoad(PtrTy, VTableSlotPtr,
2321 CGF.getPointerAlign());
2322 }
2323
2324 // Add !invariant.load md to virtual function load to indicate that
2325 // function didn't change inside vtable.
2326 // It's safe to add it without -fstrict-vtable-pointers, but it would not
2327 // help in devirtualization because it will only matter if we will have 2
2328 // the same virtual function loads from the same vtable load, which won't
2329 // happen without enabled devirtualization with -fstrict-vtable-pointers.
2330 if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2331 CGM.getCodeGenOpts().StrictVTablePointers) {
2332 if (auto *VFuncLoadInstr = dyn_cast<llvm::Instruction>(VFuncLoad)) {
2333 VFuncLoadInstr->setMetadata(
2334 llvm::LLVMContext::MD_invariant_load,
2335 llvm::MDNode::get(CGM.getLLVMContext(),
2336 llvm::ArrayRef<llvm::Metadata *>()));
2337 }
2338 }
2339 VFunc = VFuncLoad;
2340 }
2341
2342 CGPointerAuthInfo PointerAuth;
2343 if (Schema) {
2344 assert(VTableSlotPtr && "virtual function pointer not set");
2345 GD = CGM.getItaniumVTableContext().findOriginalMethod(GD.getCanonicalDecl());
2346 PointerAuth = CGF.EmitPointerAuthInfo(Schema, VTableSlotPtr, GD, QualType());
2347 }
2348 CGCallee Callee(GD, VFunc, PointerAuth);
2349 return Callee;
2350}
2351
2352llvm::Value *ItaniumCXXABI::EmitVirtualDestructorCall(
2353 CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
2354 Address This, DeleteOrMemberCallExpr E, llvm::CallBase **CallOrInvoke) {
2355 auto *CE = dyn_cast<const CXXMemberCallExpr *>(E);
2356 auto *D = dyn_cast<const CXXDeleteExpr *>(E);
2357 assert((CE != nullptr) ^ (D != nullptr));
2358 assert(CE == nullptr || CE->arguments().empty());
2359 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
2360
2361 GlobalDecl GD(Dtor, DtorType);
2362 const CGFunctionInfo *FInfo =
2363 &CGM.getTypes().arrangeCXXStructorDeclaration(GD);
2364 llvm::FunctionType *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
2365 CGCallee Callee = CGCallee::forVirtual(CE, GD, This, Ty);
2366
2367 QualType ThisTy;
2368 if (CE) {
2369 ThisTy = CE->getObjectType();
2370 } else {
2371 ThisTy = D->getDestroyedType();
2372 }
2373
2374 CGF.EmitCXXDestructorCall(GD, Callee, This.emitRawPointer(CGF), ThisTy,
2375 nullptr, QualType(), nullptr, CallOrInvoke);
2376 return nullptr;
2377}
2378
2379void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
2380 CodeGenVTables &VTables = CGM.getVTables();
2381 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
2382 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
2383}
2384
2385bool ItaniumCXXABI::canSpeculativelyEmitVTableAsBaseClass(
2386 const CXXRecordDecl *RD) const {
2387 // We don't emit available_externally vtables if we are in -fapple-kext mode
2388 // because kext mode does not permit devirtualization.
2389 if (CGM.getLangOpts().AppleKext)
2390 return false;
2391
2392 // If the vtable is hidden then it is not safe to emit an available_externally
2393 // copy of vtable.
2394 if (isVTableHidden(RD))
2395 return false;
2396
2397 if (CGM.getCodeGenOpts().ForceEmitVTables)
2398 return true;
2399
2400 // A speculative vtable can only be generated if all virtual inline functions
2401 // defined by this class are emitted. The vtable in the final program contains
2402 // for each virtual inline function not used in the current TU a function that
2403 // is equivalent to the unused function. The function in the actual vtable
2404 // does not have to be declared under the same symbol (e.g., a virtual
2405 // destructor that can be substituted with its base class's destructor). Since
2406 // inline functions are emitted lazily and this emissions does not account for
2407 // speculative emission of a vtable, we might generate a speculative vtable
2408 // with references to inline functions that are not emitted under that name.
2409 // This can lead to problems when devirtualizing a call to such a function,
2410 // that result in linking errors. Hence, if there are any unused virtual
2411 // inline function, we cannot emit the speculative vtable.
2412 // FIXME we can still emit a copy of the vtable if we
2413 // can emit definition of the inline functions.
2414 if (hasAnyUnusedVirtualInlineFunction(RD))
2415 return false;
2416
2417 // For a class with virtual bases, we must also be able to speculatively
2418 // emit the VTT, because CodeGen doesn't have separate notions of "can emit
2419 // the vtable" and "can emit the VTT". For a base subobject, this means we
2420 // need to be able to emit non-virtual base vtables.
2421 if (RD->getNumVBases()) {
2422 for (const auto &B : RD->bases()) {
2423 auto *BRD = B.getType()->getAsCXXRecordDecl();
2424 assert(BRD && "no class for base specifier");
2425 if (B.isVirtual() || !BRD->isDynamicClass())
2426 continue;
2427 if (!canSpeculativelyEmitVTableAsBaseClass(BRD))
2428 return false;
2429 }
2430 }
2431
2432 return true;
2433}
2434
2435bool ItaniumCXXABI::canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const {
2436 if (!canSpeculativelyEmitVTableAsBaseClass(RD))
2437 return false;
2438
2440 return false;
2441
2442 // For a complete-object vtable (or more specifically, for the VTT), we need
2443 // to be able to speculatively emit the vtables of all dynamic virtual bases.
2444 for (const auto &B : RD->vbases()) {
2445 auto *BRD = B.getType()->getAsCXXRecordDecl();
2446 assert(BRD && "no class for base specifier");
2447 if (!BRD->isDynamicClass())
2448 continue;
2449 if (!canSpeculativelyEmitVTableAsBaseClass(BRD))
2450 return false;
2451 }
2452
2453 return true;
2454}
2456 Address InitialPtr,
2457 const CXXRecordDecl *UnadjustedClass,
2458 int64_t NonVirtualAdjustment,
2459 int64_t VirtualAdjustment,
2460 bool IsReturnAdjustment) {
2461 if (!NonVirtualAdjustment && !VirtualAdjustment)
2462 return InitialPtr.emitRawPointer(CGF);
2463
2464 Address V = InitialPtr.withElementType(CGF.Int8Ty);
2465
2466 // In a base-to-derived cast, the non-virtual adjustment is applied first.
2467 if (NonVirtualAdjustment && !IsReturnAdjustment) {
2469 CharUnits::fromQuantity(NonVirtualAdjustment));
2470 }
2471
2472 // Perform the virtual adjustment if we have one.
2473 llvm::Value *ResultPtr;
2474 if (VirtualAdjustment) {
2475 llvm::Value *VTablePtr =
2476 CGF.GetVTablePtr(V, CGF.Int8PtrTy, UnadjustedClass);
2477
2478 llvm::Value *Offset;
2479 llvm::Value *OffsetPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
2480 CGF.Int8Ty, VTablePtr, VirtualAdjustment);
2481 if (CGF.CGM.getLangOpts().RelativeCXXABIVTables) {
2482 // Load the adjustment offset from the vtable as a 32-bit int.
2483 Offset =
2484 CGF.Builder.CreateAlignedLoad(CGF.Int32Ty, OffsetPtr,
2486 } else {
2487 llvm::Type *PtrDiffTy =
2489
2490 // Load the adjustment offset from the vtable.
2491 Offset = CGF.Builder.CreateAlignedLoad(PtrDiffTy, OffsetPtr,
2492 CGF.getPointerAlign());
2493 }
2494 // Adjust our pointer.
2495 ResultPtr = CGF.Builder.CreateInBoundsGEP(V.getElementType(),
2496 V.emitRawPointer(CGF), Offset);
2497 } else {
2498 ResultPtr = V.emitRawPointer(CGF);
2499 }
2500
2501 // In a derived-to-base conversion, the non-virtual adjustment is
2502 // applied second.
2503 if (NonVirtualAdjustment && IsReturnAdjustment) {
2504 ResultPtr = CGF.Builder.CreateConstInBoundsGEP1_64(CGF.Int8Ty, ResultPtr,
2505 NonVirtualAdjustment);
2506 }
2507
2508 return ResultPtr;
2509}
2510
2511llvm::Value *
2512ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF, Address This,
2513 const CXXRecordDecl *UnadjustedClass,
2514 const ThunkInfo &TI) {
2515 return performTypeAdjustment(CGF, This, UnadjustedClass, TI.This.NonVirtual,
2517 /*IsReturnAdjustment=*/false);
2518}
2519
2520llvm::Value *
2521ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
2522 const CXXRecordDecl *UnadjustedClass,
2523 const ReturnAdjustment &RA) {
2524 return performTypeAdjustment(CGF, Ret, UnadjustedClass, RA.NonVirtual,
2526 /*IsReturnAdjustment=*/true);
2527}
2528
2529void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
2530 RValue RV, QualType ResultType) {
2532 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
2533
2534 // Destructor thunks in the ARM ABI have indeterminate results.
2535 llvm::Type *T = CGF.ReturnValue.getElementType();
2536 RValue Undef = RValue::get(llvm::UndefValue::get(T));
2537 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
2538}
2539
2540/************************** Array allocation cookies **************************/
2541
2542CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
2543 // The array cookie is a size_t; pad that up to the element alignment.
2544 // The cookie is actually right-justified in that space.
2545 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
2546 CGM.getContext().getPreferredTypeAlignInChars(elementType));
2547}
2548
2549Address ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
2550 Address NewPtr,
2551 llvm::Value *NumElements,
2552 const CXXNewExpr *expr,
2553 QualType ElementType) {
2554 assert(requiresArrayCookie(expr));
2555
2556 unsigned AS = NewPtr.getAddressSpace();
2557
2558 ASTContext &Ctx = getContext();
2559 CharUnits SizeSize = CGF.getSizeSize();
2560
2561 // The size of the cookie.
2562 CharUnits CookieSize =
2563 std::max(SizeSize, Ctx.getPreferredTypeAlignInChars(ElementType));
2564 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
2565
2566 // Compute an offset to the cookie.
2567 Address CookiePtr = NewPtr;
2568 CharUnits CookieOffset = CookieSize - SizeSize;
2569 if (!CookieOffset.isZero())
2570 CookiePtr = CGF.Builder.CreateConstInBoundsByteGEP(CookiePtr, CookieOffset);
2571
2572 // Write the number of elements into the appropriate slot.
2573 Address NumElementsPtr = CookiePtr.withElementType(CGF.SizeTy);
2574 llvm::Instruction *SI = CGF.Builder.CreateStore(NumElements, NumElementsPtr);
2575
2576 // Handle the array cookie specially in ASan.
2577 if (CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) && AS == 0 &&
2578 (expr->getOperatorNew()->isReplaceableGlobalAllocationFunction() ||
2579 CGM.getCodeGenOpts().SanitizeAddressPoisonCustomArrayCookie)) {
2580 // The store to the CookiePtr does not need to be instrumented.
2581 SI->setNoSanitizeMetadata();
2582 llvm::FunctionType *FTy =
2583 llvm::FunctionType::get(CGM.VoidTy, NumElementsPtr.getType(), false);
2584 llvm::FunctionCallee F =
2585 CGM.CreateRuntimeFunction(FTy, "__asan_poison_cxx_array_cookie");
2586 CGF.Builder.CreateCall(F, NumElementsPtr.emitRawPointer(CGF));
2587 }
2588
2589 // Finally, compute a pointer to the actual data buffer by skipping
2590 // over the cookie completely.
2591 return CGF.Builder.CreateConstInBoundsByteGEP(NewPtr, CookieSize);
2592}
2593
2594llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
2595 Address allocPtr,
2596 CharUnits cookieSize) {
2597 // The element size is right-justified in the cookie.
2598 Address numElementsPtr = allocPtr;
2599 CharUnits numElementsOffset = cookieSize - CGF.getSizeSize();
2600 if (!numElementsOffset.isZero())
2601 numElementsPtr =
2602 CGF.Builder.CreateConstInBoundsByteGEP(numElementsPtr, numElementsOffset);
2603
2604 unsigned AS = allocPtr.getAddressSpace();
2605 numElementsPtr = numElementsPtr.withElementType(CGF.SizeTy);
2606 if (!CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) || AS != 0)
2607 return CGF.Builder.CreateLoad(numElementsPtr);
2608 // In asan mode emit a function call instead of a regular load and let the
2609 // run-time deal with it: if the shadow is properly poisoned return the
2610 // cookie, otherwise return 0 to avoid an infinite loop calling DTORs.
2611 // We can't simply ignore this load using nosanitize metadata because
2612 // the metadata may be lost.
2613 llvm::FunctionType *FTy =
2614 llvm::FunctionType::get(CGF.SizeTy, CGF.DefaultPtrTy, false);
2615 llvm::FunctionCallee F =
2616 CGM.CreateRuntimeFunction(FTy, "__asan_load_cxx_array_cookie");
2617 return CGF.Builder.CreateCall(F, numElementsPtr.emitRawPointer(CGF));
2618}
2619
2620CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
2621 // ARM says that the cookie is always:
2622 // struct array_cookie {
2623 // std::size_t element_size; // element_size != 0
2624 // std::size_t element_count;
2625 // };
2626 // But the base ABI doesn't give anything an alignment greater than
2627 // 8, so we can dismiss this as typical ABI-author blindness to
2628 // actual language complexity and round up to the element alignment.
2629 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
2630 CGM.getContext().getTypeAlignInChars(elementType));
2631}
2632
2633Address ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
2634 Address newPtr,
2635 llvm::Value *numElements,
2636 const CXXNewExpr *expr,
2637 QualType elementType) {
2638 assert(requiresArrayCookie(expr));
2639
2640 // The cookie is always at the start of the buffer.
2641 Address cookie = newPtr;
2642
2643 // The first element is the element size.
2644 cookie = cookie.withElementType(CGF.SizeTy);
2645 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
2646 getContext().getTypeSizeInChars(elementType).getQuantity());
2647 CGF.Builder.CreateStore(elementSize, cookie);
2648
2649 // The second element is the element count.
2650 cookie = CGF.Builder.CreateConstInBoundsGEP(cookie, 1);
2651 CGF.Builder.CreateStore(numElements, cookie);
2652
2653 // Finally, compute a pointer to the actual data buffer by skipping
2654 // over the cookie completely.
2655 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
2656 return CGF.Builder.CreateConstInBoundsByteGEP(newPtr, cookieSize);
2657}
2658
2659llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
2660 Address allocPtr,
2661 CharUnits cookieSize) {
2662 // The number of elements is at offset sizeof(size_t) relative to
2663 // the allocated pointer.
2664 Address numElementsPtr
2665 = CGF.Builder.CreateConstInBoundsByteGEP(allocPtr, CGF.getSizeSize());
2666
2667 numElementsPtr = numElementsPtr.withElementType(CGF.SizeTy);
2668 return CGF.Builder.CreateLoad(numElementsPtr);
2669}
2670
2671/*********************** Static local initialization **************************/
2672
2673static llvm::FunctionCallee getGuardAcquireFn(CodeGenModule &CGM,
2674 llvm::PointerType *GuardPtrTy) {
2675 // int __cxa_guard_acquire(__guard *guard_object);
2676 llvm::FunctionType *FTy =
2677 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
2678 GuardPtrTy, /*isVarArg=*/false);
2679 return CGM.CreateRuntimeFunction(
2680 FTy, "__cxa_guard_acquire",
2681 llvm::AttributeList::get(CGM.getLLVMContext(),
2682 llvm::AttributeList::FunctionIndex,
2683 llvm::Attribute::NoUnwind));
2684}
2685
2686static llvm::FunctionCallee getGuardReleaseFn(CodeGenModule &CGM,
2687 llvm::PointerType *GuardPtrTy) {
2688 // void __cxa_guard_release(__guard *guard_object);
2689 llvm::FunctionType *FTy =
2690 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
2691 return CGM.CreateRuntimeFunction(
2692 FTy, "__cxa_guard_release",
2693 llvm::AttributeList::get(CGM.getLLVMContext(),
2694 llvm::AttributeList::FunctionIndex,
2695 llvm::Attribute::NoUnwind));
2696}
2697
2698static llvm::FunctionCallee getGuardAbortFn(CodeGenModule &CGM,
2699 llvm::PointerType *GuardPtrTy) {
2700 // void __cxa_guard_abort(__guard *guard_object);
2701 llvm::FunctionType *FTy =
2702 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
2703 return CGM.CreateRuntimeFunction(
2704 FTy, "__cxa_guard_abort",
2705 llvm::AttributeList::get(CGM.getLLVMContext(),
2706 llvm::AttributeList::FunctionIndex,
2707 llvm::Attribute::NoUnwind));
2708}
2709
2710namespace {
2711 struct CallGuardAbort final : EHScopeStack::Cleanup {
2712 llvm::GlobalVariable *Guard;
2713 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
2714
2715 void Emit(CodeGenFunction &CGF, Flags flags) override {
2716 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
2717 Guard);
2718 }
2719 };
2720}
2721
2722/// The ARM code here follows the Itanium code closely enough that we
2723/// just special-case it at particular places.
2724void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
2725 const VarDecl &D,
2726 llvm::GlobalVariable *var,
2727 bool shouldPerformInit) {
2728 CGBuilderTy &Builder = CGF.Builder;
2729
2730 // Inline variables that weren't instantiated from variable templates have
2731 // partially-ordered initialization within their translation unit.
2732 bool NonTemplateInline =
2733 D.isInline() &&
2735
2736 // We only need to use thread-safe statics for local non-TLS variables and
2737 // inline variables; other global initialization is always single-threaded
2738 // or (through lazy dynamic loading in multiple threads) unsequenced.
2739 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
2740 (D.isLocalVarDecl() || NonTemplateInline) &&
2741 !D.getTLSKind();
2742
2743 // If we have a global variable with internal linkage and thread-safe statics
2744 // are disabled, we can just let the guard variable be of type i8.
2745 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
2746
2747 llvm::IntegerType *guardTy;
2748 CharUnits guardAlignment;
2749 if (useInt8GuardVariable) {
2750 guardTy = CGF.Int8Ty;
2751 guardAlignment = CharUnits::One();
2752 } else {
2753 // Guard variables are 64 bits in the generic ABI and size width on ARM
2754 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
2755 if (UseARMGuardVarABI) {
2756 guardTy = CGF.SizeTy;
2757 guardAlignment = CGF.getSizeAlign();
2758 } else {
2759 guardTy = CGF.Int64Ty;
2760 guardAlignment =
2761 CharUnits::fromQuantity(CGM.getDataLayout().getABITypeAlign(guardTy));
2762 }
2763 }
2764 llvm::PointerType *guardPtrTy = llvm::PointerType::get(
2765 CGF.CGM.getLLVMContext(),
2766 CGF.CGM.getDataLayout().getDefaultGlobalsAddressSpace());
2767
2768 // Create the guard variable if we don't already have it (as we
2769 // might if we're double-emitting this function body).
2770 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
2771 if (!guard) {
2772 // Mangle the name for the guard.
2773 SmallString<256> guardName;
2774 {
2775 llvm::raw_svector_ostream out(guardName);
2776 getMangleContext().mangleStaticGuardVariable(&D, out);
2777 }
2778
2779 // Create the guard variable with a zero-initializer.
2780 // Just absorb linkage, visibility and dll storage class from the guarded
2781 // variable.
2782 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
2783 false, var->getLinkage(),
2784 llvm::ConstantInt::get(guardTy, 0),
2785 guardName.str());
2786 guard->setDSOLocal(var->isDSOLocal());
2787 guard->setVisibility(var->getVisibility());
2788 guard->setDLLStorageClass(var->getDLLStorageClass());
2789 // If the variable is thread-local, so is its guard variable.
2790 guard->setThreadLocalMode(var->getThreadLocalMode());
2791 guard->setAlignment(guardAlignment.getAsAlign());
2792
2793 // The ABI says: "It is suggested that it be emitted in the same COMDAT
2794 // group as the associated data object." In practice, this doesn't work for
2795 // non-ELF and non-Wasm object formats, so only do it for ELF and Wasm.
2796 llvm::Comdat *C = var->getComdat();
2797 if (!D.isLocalVarDecl() && C &&
2798 (CGM.getTarget().getTriple().isOSBinFormatELF() ||
2799 CGM.getTarget().getTriple().isOSBinFormatWasm())) {
2800 guard->setComdat(C);
2801 } else if (CGM.supportsCOMDAT() && guard->isWeakForLinker()) {
2802 guard->setComdat(CGM.getModule().getOrInsertComdat(guard->getName()));
2803 }
2804
2805 CGM.setStaticLocalDeclGuardAddress(&D, guard);
2806 }
2807
2808 Address guardAddr = Address(guard, guard->getValueType(), guardAlignment);
2809
2810 // Test whether the variable has completed initialization.
2811 //
2812 // Itanium C++ ABI 3.3.2:
2813 // The following is pseudo-code showing how these functions can be used:
2814 // if (obj_guard.first_byte == 0) {
2815 // if ( __cxa_guard_acquire (&obj_guard) ) {
2816 // try {
2817 // ... initialize the object ...;
2818 // } catch (...) {
2819 // __cxa_guard_abort (&obj_guard);
2820 // throw;
2821 // }
2822 // ... queue object destructor with __cxa_atexit() ...;
2823 // __cxa_guard_release (&obj_guard);
2824 // }
2825 // }
2826 //
2827 // If threadsafe statics are enabled, but we don't have inline atomics, just
2828 // call __cxa_guard_acquire unconditionally. The "inline" check isn't
2829 // actually inline, and the user might not expect calls to __atomic libcalls.
2830
2831 unsigned MaxInlineWidthInBits = CGF.getTarget().getMaxAtomicInlineWidth();
2832 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2833 if (!threadsafe || MaxInlineWidthInBits) {
2834 // Load the first byte of the guard variable.
2835 llvm::LoadInst *LI =
2836 Builder.CreateLoad(guardAddr.withElementType(CGM.Int8Ty));
2837
2838 // Itanium ABI:
2839 // An implementation supporting thread-safety on multiprocessor
2840 // systems must also guarantee that references to the initialized
2841 // object do not occur before the load of the initialization flag.
2842 //
2843 // In LLVM, we do this by marking the load Acquire.
2844 if (threadsafe)
2845 LI->setAtomic(llvm::AtomicOrdering::Acquire);
2846
2847 // For ARM, we should only check the first bit, rather than the entire byte:
2848 //
2849 // ARM C++ ABI 3.2.3.1:
2850 // To support the potential use of initialization guard variables
2851 // as semaphores that are the target of ARM SWP and LDREX/STREX
2852 // synchronizing instructions we define a static initialization
2853 // guard variable to be a 4-byte aligned, 4-byte word with the
2854 // following inline access protocol.
2855 // #define INITIALIZED 1
2856 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
2857 // if (__cxa_guard_acquire(&obj_guard))
2858 // ...
2859 // }
2860 //
2861 // and similarly for ARM64:
2862 //
2863 // ARM64 C++ ABI 3.2.2:
2864 // This ABI instead only specifies the value bit 0 of the static guard
2865 // variable; all other bits are platform defined. Bit 0 shall be 0 when the
2866 // variable is not initialized and 1 when it is.
2867 llvm::Value *V =
2868 (UseARMGuardVarABI && !useInt8GuardVariable)
2869 ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1))
2870 : LI;
2871 llvm::Value *NeedsInit = Builder.CreateIsNull(V, "guard.uninitialized");
2872
2873 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
2874
2875 // Check if the first byte of the guard variable is zero.
2876 CGF.EmitCXXGuardedInitBranch(NeedsInit, InitCheckBlock, EndBlock,
2877 CodeGenFunction::GuardKind::VariableGuard, &D);
2878
2879 CGF.EmitBlock(InitCheckBlock);
2880 }
2881
2882 // The semantics of dynamic initialization of variables with static or thread
2883 // storage duration depends on whether they are declared at block-scope. The
2884 // initialization of such variables at block-scope can be aborted with an
2885 // exception and later retried (per C++20 [stmt.dcl]p4), and recursive entry
2886 // to their initialization has undefined behavior (also per C++20
2887 // [stmt.dcl]p4). For such variables declared at non-block scope, exceptions
2888 // lead to termination (per C++20 [except.terminate]p1), and recursive
2889 // references to the variables are governed only by the lifetime rules (per
2890 // C++20 [class.cdtor]p2), which means such references are perfectly fine as
2891 // long as they avoid touching memory. As a result, block-scope variables must
2892 // not be marked as initialized until after initialization completes (unless
2893 // the mark is reverted following an exception), but non-block-scope variables
2894 // must be marked prior to initialization so that recursive accesses during
2895 // initialization do not restart initialization.
2896
2897 // Variables used when coping with thread-safe statics and exceptions.
2898 if (threadsafe) {
2899 // Call __cxa_guard_acquire.
2900 llvm::Value *V
2901 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
2902
2903 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
2904
2905 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
2906 InitBlock, EndBlock);
2907
2908 // Call __cxa_guard_abort along the exceptional edge.
2909 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
2910
2911 CGF.EmitBlock(InitBlock);
2912 } else if (!D.isLocalVarDecl()) {
2913 // For non-local variables, store 1 into the first byte of the guard
2914 // variable before the object initialization begins so that references
2915 // to the variable during initialization don't restart initialization.
2916 Builder.CreateStore(llvm::ConstantInt::get(CGM.Int8Ty, 1),
2917 guardAddr.withElementType(CGM.Int8Ty));
2918 }
2919
2920 // Emit the initializer and add a global destructor if appropriate.
2921 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
2922
2923 if (threadsafe) {
2924 // Pop the guard-abort cleanup if we pushed one.
2925 CGF.PopCleanupBlock();
2926
2927 // Call __cxa_guard_release. This cannot throw.
2928 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy),
2929 guardAddr.emitRawPointer(CGF));
2930 } else if (D.isLocalVarDecl()) {
2931 // For local variables, store 1 into the first byte of the guard variable
2932 // after the object initialization completes so that initialization is
2933 // retried if initialization is interrupted by an exception.
2934 Builder.CreateStore(llvm::ConstantInt::get(CGM.Int8Ty, 1),
2935 guardAddr.withElementType(CGM.Int8Ty));
2936 }
2937
2938 CGF.EmitBlock(EndBlock);
2939}
2940
2941/// Register a global destructor using __cxa_atexit.
2943 llvm::FunctionCallee dtor,
2944 llvm::Constant *addr, bool TLS) {
2945 assert(!CGF.getTarget().getTriple().isOSAIX() &&
2946 "unexpected call to emitGlobalDtorWithCXAAtExit");
2947 assert((TLS || CGF.getTypes().getCodeGenOpts().CXAAtExit) &&
2948 "__cxa_atexit is disabled");
2949 const char *Name = "__cxa_atexit";
2950 if (TLS) {
2951 const llvm::Triple &T = CGF.getTarget().getTriple();
2952 Name = T.isOSDarwin() ? "_tlv_atexit" : "__cxa_thread_atexit";
2953 }
2954
2955 // We're assuming that the destructor function is something we can
2956 // reasonably call with the default CC.
2957 llvm::Type *dtorTy = CGF.DefaultPtrTy;
2958
2959 // Preserve address space of addr.
2960 auto AddrAS = addr ? addr->getType()->getPointerAddressSpace() : 0;
2961 auto AddrPtrTy = AddrAS ? llvm::PointerType::get(CGF.getLLVMContext(), AddrAS)
2962 : CGF.Int8PtrTy;
2963
2964 // Create a variable that binds the atexit to this shared object.
2965 llvm::Constant *handle =
2966 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
2967 auto *GV = cast<llvm::GlobalValue>(handle->stripPointerCasts());
2968 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
2969
2970 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
2971 llvm::Type *paramTys[] = {dtorTy, AddrPtrTy, handle->getType()};
2972 llvm::FunctionType *atexitTy =
2973 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
2974
2975 // Fetch the actual function.
2976 llvm::FunctionCallee atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
2977 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit.getCallee()))
2978 fn->setDoesNotThrow();
2979
2980 const auto &Context = CGF.CGM.getContext();
2981 FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention(
2982 /*IsVariadic=*/false, /*IsCXXMethod=*/false));
2983 QualType fnType =
2984 Context.getFunctionType(Context.VoidTy, {Context.VoidPtrTy}, EPI);
2985 llvm::Value *dtorCallee = dtor.getCallee();
2986 dtorCallee =
2987 CGF.CGM.getFunctionPointer(cast<llvm::Constant>(dtorCallee), fnType);
2988
2989 if (dtorCallee->getType()->getPointerAddressSpace() != AddrAS)
2990 dtorCallee = CGF.performAddrSpaceCast(dtorCallee, AddrPtrTy);
2991
2992 if (!addr)
2993 // addr is null when we are trying to register a dtor annotated with
2994 // __attribute__((destructor)) in a constructor function. Using null here is
2995 // okay because this argument is just passed back to the destructor
2996 // function.
2997 addr = llvm::Constant::getNullValue(CGF.Int8PtrTy);
2998
2999 llvm::Value *args[] = {dtorCallee, addr, handle};
3000 CGF.EmitNounwindRuntimeCall(atexit, args);
3001}
3002
3004 StringRef FnName) {
3005 // Create a function that registers/unregisters destructors that have the same
3006 // priority.
3007 llvm::FunctionType *FTy = llvm::FunctionType::get(CGM.VoidTy, false);
3008 llvm::Function *GlobalInitOrCleanupFn = CGM.CreateGlobalInitOrCleanUpFunction(
3009 FTy, FnName, CGM.getTypes().arrangeNullaryFunction(), SourceLocation());
3010
3011 return GlobalInitOrCleanupFn;
3012}
3013
3014void CodeGenModule::unregisterGlobalDtorsWithUnAtExit() {
3015 for (const auto &I : DtorsUsingAtExit) {
3016 int Priority = I.first;
3017 std::string GlobalCleanupFnName =
3018 std::string("__GLOBAL_cleanup_") + llvm::to_string(Priority);
3019
3020 llvm::Function *GlobalCleanupFn =
3021 createGlobalInitOrCleanupFn(*this, GlobalCleanupFnName);
3022
3023 CodeGenFunction CGF(*this);
3024 CGF.StartFunction(GlobalDecl(), getContext().VoidTy, GlobalCleanupFn,
3025 getTypes().arrangeNullaryFunction(), FunctionArgList(),
3026 SourceLocation(), SourceLocation());
3028
3029 // Get the destructor function type, void(*)(void).
3030 llvm::FunctionType *dtorFuncTy = llvm::FunctionType::get(CGF.VoidTy, false);
3031
3032 // Destructor functions are run/unregistered in non-ascending
3033 // order of their priorities.
3034 const llvm::TinyPtrVector<llvm::Function *> &Dtors = I.second;
3035 auto itv = Dtors.rbegin();
3036 while (itv != Dtors.rend()) {
3037 llvm::Function *Dtor = *itv;
3038
3039 // We're assuming that the destructor function is something we can
3040 // reasonably call with the correct CC.
3041 llvm::Value *V = CGF.unregisterGlobalDtorWithUnAtExit(Dtor);
3042 llvm::Value *NeedsDestruct =
3043 CGF.Builder.CreateIsNull(V, "needs_destruct");
3044
3045 llvm::BasicBlock *DestructCallBlock =
3046 CGF.createBasicBlock("destruct.call");
3047 llvm::BasicBlock *EndBlock = CGF.createBasicBlock(
3048 (itv + 1) != Dtors.rend() ? "unatexit.call" : "destruct.end");
3049 // Check if unatexit returns a value of 0. If it does, jump to
3050 // DestructCallBlock, otherwise jump to EndBlock directly.
3051 CGF.Builder.CreateCondBr(NeedsDestruct, DestructCallBlock, EndBlock);
3052
3053 CGF.EmitBlock(DestructCallBlock);
3054
3055 // Emit the call to casted Dtor.
3056 llvm::CallInst *CI = CGF.Builder.CreateCall(dtorFuncTy, Dtor);
3057 // Make sure the call and the callee agree on calling convention.
3058 CI->setCallingConv(Dtor->getCallingConv());
3059
3060 CGF.EmitBlock(EndBlock);
3061
3062 itv++;
3063 }
3064
3065 CGF.FinishFunction();
3066 AddGlobalDtor(GlobalCleanupFn, Priority);
3067 }
3068}
3069
3070void CodeGenModule::registerGlobalDtorsWithAtExit() {
3071 for (const auto &I : DtorsUsingAtExit) {
3072 int Priority = I.first;
3073 std::string GlobalInitFnName =
3074 std::string("__GLOBAL_init_") + llvm::to_string(Priority);
3075 llvm::Function *GlobalInitFn =
3076 createGlobalInitOrCleanupFn(*this, GlobalInitFnName);
3077
3078 CodeGenFunction CGF(*this);
3079 CGF.StartFunction(GlobalDecl(), getContext().VoidTy, GlobalInitFn,
3080 getTypes().arrangeNullaryFunction(), FunctionArgList(),
3081 SourceLocation(), SourceLocation());
3083
3084 // Since constructor functions are run in non-descending order of their
3085 // priorities, destructors are registered in non-descending order of their
3086 // priorities, and since destructor functions are run in the reverse order
3087 // of their registration, destructor functions are run in non-ascending
3088 // order of their priorities.
3089 const llvm::TinyPtrVector<llvm::Function *> &Dtors = I.second;
3090 for (auto *Dtor : Dtors) {
3091 // Register the destructor function calling __cxa_atexit if it is
3092 // available. Otherwise fall back on calling atexit.
3093 if (getCodeGenOpts().CXAAtExit) {
3094 emitGlobalDtorWithCXAAtExit(CGF, Dtor, nullptr, false);
3095 } else {
3096 // We're assuming that the destructor function is something we can
3097 // reasonably call with the correct CC.
3099 }
3100 }
3101
3102 CGF.FinishFunction();
3103 AddGlobalCtor(GlobalInitFn, Priority);
3104 }
3105
3106 if (getCXXABI().useSinitAndSterm())
3107 unregisterGlobalDtorsWithUnAtExit();
3108}
3109
3110/// Register a global destructor as best as we know how.
3111void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
3112 llvm::FunctionCallee dtor,
3113 llvm::Constant *addr) {
3114 if (D.isNoDestroy(CGM.getContext()))
3115 return;
3116
3117 // HLSL doesn't support atexit.
3118 if (CGM.getLangOpts().HLSL)
3119 return CGM.AddCXXDtorEntry(dtor, addr);
3120
3121 // OpenMP offloading supports C++ constructors and destructors but we do not
3122 // always have 'atexit' available. Instead lower these to use the LLVM global
3123 // destructors which we can handle directly in the runtime. Note that this is
3124 // not strictly 1-to-1 with using `atexit` because we no longer tear down
3125 // globals in reverse order of when they were constructed.
3126 if (!CGM.getLangOpts().hasAtExit() && !D.isStaticLocal())
3127 return CGF.registerGlobalDtorWithLLVM(D, dtor, addr);
3128
3129 // emitGlobalDtorWithCXAAtExit will emit a call to either __cxa_thread_atexit
3130 // or __cxa_atexit depending on whether this VarDecl is a thread-local storage
3131 // or not. CXAAtExit controls only __cxa_atexit, so use it if it is enabled.
3132 // We can always use __cxa_thread_atexit.
3133 if (CGM.getCodeGenOpts().CXAAtExit || D.getTLSKind())
3134 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
3135
3136 // In Apple kexts, we want to add a global destructor entry.
3137 // FIXME: shouldn't this be guarded by some variable?
3138 if (CGM.getLangOpts().AppleKext) {
3139 // Generate a global destructor entry.
3140 return CGM.AddCXXDtorEntry(dtor, addr);
3141 }
3142
3143 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
3144}
3145
3148 assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!");
3149 // Darwin prefers to have references to thread local variables to go through
3150 // the thread wrapper instead of directly referencing the backing variable.
3151 return VD->getTLSKind() == VarDecl::TLS_Dynamic &&
3152 CGM.getTarget().getTriple().isOSDarwin();
3153}
3154
3155/// Get the appropriate linkage for the wrapper function. This is essentially
3156/// the weak form of the variable's linkage; every translation unit which needs
3157/// the wrapper emits a copy, and we want the linker to merge them.
3158static llvm::GlobalValue::LinkageTypes
3160 llvm::GlobalValue::LinkageTypes VarLinkage =
3162
3163 // For internal linkage variables, we don't need an external or weak wrapper.
3164 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
3165 return VarLinkage;
3166
3167 // If the thread wrapper is replaceable, give it appropriate linkage.
3168 if (isThreadWrapperReplaceable(VD, CGM))
3169 if (!llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) &&
3170 !llvm::GlobalVariable::isWeakODRLinkage(VarLinkage))
3171 return VarLinkage;
3172 return llvm::GlobalValue::WeakODRLinkage;
3173}
3174
3175llvm::Function *
3176ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
3177 llvm::Value *Val) {
3178 // Mangle the name for the thread_local wrapper function.
3179 SmallString<256> WrapperName;
3180 {
3181 llvm::raw_svector_ostream Out(WrapperName);
3182 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
3183 }
3184
3185 // FIXME: If VD is a definition, we should regenerate the function attributes
3186 // before returning.
3187 if (llvm::Value *V = CGM.getModule().getNamedValue(WrapperName))
3188 return cast<llvm::Function>(V);
3189
3190 QualType RetQT = VD->getType();
3191 if (RetQT->isReferenceType())
3192 RetQT = RetQT.getNonReferenceType();
3193
3194 const CGFunctionInfo &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
3195 getContext().getPointerType(RetQT), FunctionArgList());
3196
3197 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FI);
3198 llvm::Function *Wrapper =
3199 llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM),
3200 WrapperName.str(), &CGM.getModule());
3201
3202 if (CGM.supportsCOMDAT() && Wrapper->isWeakForLinker())
3203 Wrapper->setComdat(CGM.getModule().getOrInsertComdat(Wrapper->getName()));
3204
3205 CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, Wrapper, /*IsThunk=*/false);
3206
3207 // Always resolve references to the wrapper at link time.
3208 if (!Wrapper->hasLocalLinkage())
3209 if (!isThreadWrapperReplaceable(VD, CGM) ||
3210 llvm::GlobalVariable::isLinkOnceLinkage(Wrapper->getLinkage()) ||
3211 llvm::GlobalVariable::isWeakODRLinkage(Wrapper->getLinkage()) ||
3213 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
3214
3215 if (isThreadWrapperReplaceable(VD, CGM)) {
3216 Wrapper->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
3217 Wrapper->addFnAttr(llvm::Attribute::NoUnwind);
3218 }
3219
3220 ThreadWrappers.push_back({VD, Wrapper});
3221 return Wrapper;
3222}
3223
3224void ItaniumCXXABI::EmitThreadLocalInitFuncs(
3225 CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
3226 ArrayRef<llvm::Function *> CXXThreadLocalInits,
3227 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) {
3228 llvm::Function *InitFunc = nullptr;
3229
3230 // Separate initializers into those with ordered (or partially-ordered)
3231 // initialization and those with unordered initialization.
3232 llvm::SmallVector<llvm::Function *, 8> OrderedInits;
3233 llvm::SmallDenseMap<const VarDecl *, llvm::Function *> UnorderedInits;
3234 for (unsigned I = 0; I != CXXThreadLocalInits.size(); ++I) {
3236 CXXThreadLocalInitVars[I]->getTemplateSpecializationKind()))
3237 UnorderedInits[CXXThreadLocalInitVars[I]->getCanonicalDecl()] =
3238 CXXThreadLocalInits[I];
3239 else
3240 OrderedInits.push_back(CXXThreadLocalInits[I]);
3241 }
3242
3243 if (!OrderedInits.empty()) {
3244 // Generate a guarded initialization function.
3245 llvm::FunctionType *FTy =
3246 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
3247 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
3248 InitFunc = CGM.CreateGlobalInitOrCleanUpFunction(FTy, "__tls_init", FI,
3249 SourceLocation(),
3250 /*TLS=*/true);
3251 llvm::GlobalVariable *Guard = new llvm::GlobalVariable(
3252 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
3253 llvm::GlobalVariable::InternalLinkage,
3254 llvm::ConstantInt::get(CGM.Int8Ty, 0), "__tls_guard");
3255 Guard->setThreadLocal(true);
3256 Guard->setThreadLocalMode(CGM.GetDefaultLLVMTLSModel());
3257
3258 CharUnits GuardAlign = CharUnits::One();
3259 Guard->setAlignment(GuardAlign.getAsAlign());
3260
3261 CodeGenFunction(CGM).GenerateCXXGlobalInitFunc(
3262 InitFunc, OrderedInits, ConstantAddress(Guard, CGM.Int8Ty, GuardAlign));
3263 // On Darwin platforms, use CXX_FAST_TLS calling convention.
3264 if (CGM.getTarget().getTriple().isOSDarwin()) {
3265 InitFunc->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
3266 InitFunc->addFnAttr(llvm::Attribute::NoUnwind);
3267 }
3268 }
3269
3270 // Create declarations for thread wrappers for all thread-local variables
3271 // with non-discardable definitions in this translation unit.
3272 for (const VarDecl *VD : CXXThreadLocals) {
3273 if (VD->hasDefinition() &&
3274 !isDiscardableGVALinkage(getContext().GetGVALinkageForVariable(VD))) {
3275 llvm::GlobalValue *GV = CGM.GetGlobalValue(CGM.getMangledName(VD));
3276 getOrCreateThreadLocalWrapper(VD, GV);
3277 }
3278 }
3279
3280 // Emit all referenced thread wrappers.
3281 for (auto VDAndWrapper : ThreadWrappers) {
3282 const VarDecl *VD = VDAndWrapper.first;
3283 llvm::GlobalVariable *Var =
3285 llvm::Function *Wrapper = VDAndWrapper.second;
3286
3287 // Some targets require that all access to thread local variables go through
3288 // the thread wrapper. This means that we cannot attempt to create a thread
3289 // wrapper or a thread helper.
3290 if (!VD->hasDefinition()) {
3291 if (isThreadWrapperReplaceable(VD, CGM)) {
3292 Wrapper->setLinkage(llvm::Function::ExternalLinkage);
3293 continue;
3294 }
3295
3296 // If this isn't a TU in which this variable is defined, the thread
3297 // wrapper is discardable.
3298 if (Wrapper->getLinkage() == llvm::Function::WeakODRLinkage)
3299 Wrapper->setLinkage(llvm::Function::LinkOnceODRLinkage);
3300 }
3301
3302 CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Wrapper);
3303
3304 // Mangle the name for the thread_local initialization function.
3305 SmallString<256> InitFnName;
3306 {
3307 llvm::raw_svector_ostream Out(InitFnName);
3308 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
3309 }
3310
3311 llvm::FunctionType *InitFnTy = llvm::FunctionType::get(CGM.VoidTy, false);
3312
3313 // If we have a definition for the variable, emit the initialization
3314 // function as an alias to the global Init function (if any). Otherwise,
3315 // produce a declaration of the initialization function.
3316 llvm::GlobalValue *Init = nullptr;
3317 bool InitIsInitFunc = false;
3318 bool HasConstantInitialization = false;
3319 if (!usesThreadWrapperFunction(VD)) {
3320 HasConstantInitialization = true;
3321 } else if (VD->hasDefinition()) {
3322 InitIsInitFunc = true;
3323 llvm::Function *InitFuncToUse = InitFunc;
3325 InitFuncToUse = UnorderedInits.lookup(VD->getCanonicalDecl());
3326 if (InitFuncToUse)
3327 Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
3328 InitFuncToUse);
3329 } else {
3330 // Emit a weak global function referring to the initialization function.
3331 // This function will not exist if the TU defining the thread_local
3332 // variable in question does not need any dynamic initialization for
3333 // its thread_local variables.
3334 Init = llvm::Function::Create(InitFnTy,
3335 llvm::GlobalVariable::ExternalWeakLinkage,
3336 InitFnName.str(), &CGM.getModule());
3337 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
3339 GlobalDecl(), FI, cast<llvm::Function>(Init), /*IsThunk=*/false);
3340 }
3341
3342 if (Init) {
3343 Init->setVisibility(Var->getVisibility());
3344 // Don't mark an extern_weak function DSO local on windows.
3345 if (!CGM.getTriple().isOSWindows() || !Init->hasExternalWeakLinkage())
3346 Init->setDSOLocal(Var->isDSOLocal());
3347 }
3348
3349 llvm::LLVMContext &Context = CGM.getModule().getContext();
3350
3351 // The linker on AIX is not happy with missing weak symbols. However,
3352 // other TUs will not know whether the initialization routine exists
3353 // so create an empty, init function to satisfy the linker.
3354 // This is needed whenever a thread wrapper function is not used, and
3355 // also when the symbol is weak.
3356 if (CGM.getTriple().isOSAIX() && VD->hasDefinition() &&
3357 isEmittedWithConstantInitializer(VD, true) &&
3358 !mayNeedDestruction(VD)) {
3359 // Init should be null. If it were non-null, then the logic above would
3360 // either be defining the function to be an alias or declaring the
3361 // function with the expectation that the definition of the variable
3362 // is elsewhere.
3363 assert(Init == nullptr && "Expected Init to be null.");
3364
3365 llvm::Function *Func = llvm::Function::Create(
3366 InitFnTy, Var->getLinkage(), InitFnName.str(), &CGM.getModule());
3367 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
3368 CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI,
3370 /*IsThunk=*/false);
3371 // Create a function body that just returns
3372 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Func);
3373 CGBuilderTy Builder(CGM, Entry);
3374 Builder.CreateRetVoid();
3375 }
3376
3377 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
3378 CGBuilderTy Builder(CGM, Entry);
3379 if (HasConstantInitialization) {
3380 // No dynamic initialization to invoke.
3381 } else if (InitIsInitFunc) {
3382 if (Init) {
3383 llvm::CallInst *CallVal = Builder.CreateCall(InitFnTy, Init);
3384 if (isThreadWrapperReplaceable(VD, CGM)) {
3385 CallVal->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
3386 llvm::Function *Fn =
3388 Fn->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
3389 }
3390 }
3391 } else if (CGM.getTriple().isOSAIX()) {
3392 // On AIX, except if constinit and also neither of class type or of
3393 // (possibly multi-dimensional) array of class type, thread_local vars
3394 // will have init routines regardless of whether they are
3395 // const-initialized. Since the routine is guaranteed to exist, we can
3396 // unconditionally call it without testing for its existance. This
3397 // avoids potentially unresolved weak symbols which the AIX linker
3398 // isn't happy with.
3399 Builder.CreateCall(InitFnTy, Init);
3400 } else {
3401 // Don't know whether we have an init function. Call it if it exists.
3402 llvm::Value *Have = Builder.CreateIsNotNull(Init);
3403 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
3404 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
3405 Builder.CreateCondBr(Have, InitBB, ExitBB);
3406
3407 Builder.SetInsertPoint(InitBB);
3408 Builder.CreateCall(InitFnTy, Init);
3409 Builder.CreateBr(ExitBB);
3410
3411 Builder.SetInsertPoint(ExitBB);
3412 }
3413
3414 // For a reference, the result of the wrapper function is a pointer to
3415 // the referenced object.
3416 llvm::Value *Val = Builder.CreateThreadLocalAddress(Var);
3417
3418 if (VD->getType()->isReferenceType()) {
3419 CharUnits Align = CGM.getContext().getDeclAlign(VD);
3420 Val = Builder.CreateAlignedLoad(Var->getValueType(), Val, Align);
3421 }
3422 Val = Builder.CreateAddrSpaceCast(Val, Wrapper->getReturnType());
3423
3424 Builder.CreateRet(Val);
3425 }
3426}
3427
3428LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
3429 const VarDecl *VD,
3430 QualType LValType) {
3431 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD);
3432 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Val);
3433
3434 llvm::CallInst *CallVal = CGF.Builder.CreateCall(Wrapper);
3435 CallVal->setCallingConv(Wrapper->getCallingConv());
3436
3437 LValue LV;
3438 if (VD->getType()->isReferenceType())
3439 LV = CGF.MakeNaturalAlignRawAddrLValue(CallVal, LValType);
3440 else
3441 LV = CGF.MakeRawAddrLValue(CallVal, LValType,
3442 CGF.getContext().getDeclAlign(VD));
3443 // FIXME: need setObjCGCLValueClass?
3444 return LV;
3445}
3446
3447/// Return whether the given global decl needs a VTT parameter, which it does
3448/// if it's a base constructor or destructor with virtual bases.
3449bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
3450 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
3451
3452 // We don't have any virtual bases, just return early.
3453 if (!MD->getParent()->getNumVBases())
3454 return false;
3455
3456 // Check if we have a base constructor.
3458 return true;
3459
3460 // Check if we have a base destructor.
3461 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
3462 return true;
3463
3464 return false;
3465}
3466
3467llvm::Constant *
3468ItaniumCXXABI::getOrCreateVirtualFunctionPointerThunk(const CXXMethodDecl *MD) {
3469 SmallString<256> MethodName;
3470 llvm::raw_svector_ostream Out(MethodName);
3471 getMangleContext().mangleCXXName(MD, Out);
3472 MethodName += "_vfpthunk_";
3473 StringRef ThunkName = MethodName.str();
3474 llvm::Function *ThunkFn;
3475 if ((ThunkFn = cast_or_null<llvm::Function>(
3476 CGM.getModule().getNamedValue(ThunkName))))
3477 return ThunkFn;
3478
3479 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeCXXMethodDeclaration(MD);
3480 llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo);
3481 llvm::GlobalValue::LinkageTypes Linkage =
3482 MD->isExternallyVisible() ? llvm::GlobalValue::LinkOnceODRLinkage
3483 : llvm::GlobalValue::InternalLinkage;
3484 ThunkFn =
3485 llvm::Function::Create(ThunkTy, Linkage, ThunkName, &CGM.getModule());
3486 if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
3487 ThunkFn->setVisibility(llvm::GlobalValue::HiddenVisibility);
3488 assert(ThunkFn->getName() == ThunkName && "name was uniqued!");
3489
3490 CGM.SetLLVMFunctionAttributes(MD, FnInfo, ThunkFn, /*IsThunk=*/true);
3492
3493 // Stack protection sometimes gets inserted after the musttail call.
3494 ThunkFn->removeFnAttr(llvm::Attribute::StackProtect);
3495 ThunkFn->removeFnAttr(llvm::Attribute::StackProtectStrong);
3496 ThunkFn->removeFnAttr(llvm::Attribute::StackProtectReq);
3497
3498 // Start codegen.
3499 CodeGenFunction CGF(CGM);
3500 CGF.CurGD = GlobalDecl(MD);
3501 CGF.CurFuncIsThunk = true;
3502
3503 // Build FunctionArgs.
3504 FunctionArgList FunctionArgs;
3505 CGF.BuildFunctionArgList(CGF.CurGD, FunctionArgs);
3506
3507 CGF.StartFunction(GlobalDecl(), FnInfo.getReturnType(), ThunkFn, FnInfo,
3508 FunctionArgs, MD->getLocation(), SourceLocation());
3509
3510 // Emit an artificial location for this function.
3512
3513 llvm::Value *ThisVal = loadIncomingCXXThis(CGF);
3514 setCXXABIThisValue(CGF, ThisVal);
3515
3516 CallArgList CallArgs;
3517 for (const VarDecl *VD : FunctionArgs)
3518 CGF.EmitDelegateCallArg(CallArgs, VD, SourceLocation());
3519
3520 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
3521 RequiredArgs Required = RequiredArgs::forPrototypePlus(FPT, /*this*/ 1);
3522 const CGFunctionInfo &CallInfo =
3523 CGM.getTypes().arrangeCXXMethodCall(CallArgs, FPT, Required, 0);
3524 CGCallee Callee = CGCallee::forVirtual(nullptr, GlobalDecl(MD),
3525 getThisAddress(CGF), ThunkTy);
3526 llvm::CallBase *CallOrInvoke;
3527 CGF.EmitCall(CallInfo, Callee, ReturnValueSlot(), CallArgs, &CallOrInvoke,
3528 /*IsMustTail=*/true, SourceLocation(), true);
3529 auto *Call = cast<llvm::CallInst>(CallOrInvoke);
3530 Call->setTailCallKind(llvm::CallInst::TCK_MustTail);
3531 if (Call->getType()->isVoidTy())
3532 CGF.Builder.CreateRetVoid();
3533 else
3534 CGF.Builder.CreateRet(Call);
3535
3536 // Finish the function to maintain CodeGenFunction invariants.
3537 // FIXME: Don't emit unreachable code.
3538 CGF.EmitBlock(CGF.createBasicBlock());
3539 CGF.FinishFunction();
3540 return ThunkFn;
3541}
3542
3543namespace {
3544class ItaniumRTTIBuilder {
3545 CodeGenModule &CGM; // Per-module state.
3546 llvm::LLVMContext &VMContext;
3547 const ItaniumCXXABI &CXXABI; // Per-module state.
3548
3549 /// Fields - The fields of the RTTI descriptor currently being built.
3550 SmallVector<llvm::Constant *, 16> Fields;
3551
3552 /// GetAddrOfTypeName - Returns the mangled type name of the given type.
3553 llvm::GlobalVariable *
3554 GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
3555
3556 /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
3557 /// descriptor of the given type.
3558 llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
3559
3560 /// BuildVTablePointer - Build the vtable pointer for the given type.
3561 void BuildVTablePointer(const Type *Ty, llvm::Constant *StorageAddress);
3562
3563 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
3564 /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
3565 void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
3566
3567 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
3568 /// classes with bases that do not satisfy the abi::__si_class_type_info
3569 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
3570 void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
3571
3572 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
3573 /// for pointer types.
3574 void BuildPointerTypeInfo(QualType PointeeTy);
3575
3576 /// BuildObjCObjectTypeInfo - Build the appropriate kind of
3577 /// type_info for an object type.
3578 void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
3579
3580 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
3581 /// struct, used for member pointer types.
3582 void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
3583
3584public:
3585 ItaniumRTTIBuilder(const ItaniumCXXABI &ABI)
3586 : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {}
3587
3588 // Pointer type info flags.
3589 enum {
3590 /// PTI_Const - Type has const qualifier.
3591 PTI_Const = 0x1,
3592
3593 /// PTI_Volatile - Type has volatile qualifier.
3594 PTI_Volatile = 0x2,
3595
3596 /// PTI_Restrict - Type has restrict qualifier.
3597 PTI_Restrict = 0x4,
3598
3599 /// PTI_Incomplete - Type is incomplete.
3600 PTI_Incomplete = 0x8,
3601
3602 /// PTI_ContainingClassIncomplete - Containing class is incomplete.
3603 /// (in pointer to member).
3604 PTI_ContainingClassIncomplete = 0x10,
3605
3606 /// PTI_TransactionSafe - Pointee is transaction_safe function (C++ TM TS).
3607 //PTI_TransactionSafe = 0x20,
3608
3609 /// PTI_Noexcept - Pointee is noexcept function (C++1z).
3610 PTI_Noexcept = 0x40,
3611 };
3612
3613 // VMI type info flags.
3614 enum {
3615 /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
3616 VMI_NonDiamondRepeat = 0x1,
3617
3618 /// VMI_DiamondShaped - Class is diamond shaped.
3619 VMI_DiamondShaped = 0x2
3620 };
3621
3622 // Base class type info flags.
3623 enum {
3624 /// BCTI_Virtual - Base class is virtual.
3625 BCTI_Virtual = 0x1,
3626
3627 /// BCTI_Public - Base class is public.
3628 BCTI_Public = 0x2
3629 };
3630
3631 /// BuildTypeInfo - Build the RTTI type info struct for the given type, or
3632 /// link to an existing RTTI descriptor if one already exists.
3633 llvm::Constant *BuildTypeInfo(QualType Ty);
3634
3635 /// BuildTypeInfo - Build the RTTI type info struct for the given type.
3636 llvm::Constant *BuildTypeInfo(
3637 QualType Ty,
3638 llvm::GlobalVariable::LinkageTypes Linkage,
3639 llvm::GlobalValue::VisibilityTypes Visibility,
3640 llvm::GlobalValue::DLLStorageClassTypes DLLStorageClass);
3641};
3642}
3643
3644llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName(
3645 QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) {
3646 SmallString<256> Name;
3647 llvm::raw_svector_ostream Out(Name);
3649
3650 // We know that the mangled name of the type starts at index 4 of the
3651 // mangled name of the typename, so we can just index into it in order to
3652 // get the mangled name of the type.
3653 llvm::Constant *Init;
3654 if (CGM.getTriple().isOSzOS()) {
3655 // On z/OS, typename is stored as 2 encodings: EBCDIC followed by ASCII.
3656 SmallString<256> DualEncodedName;
3657 llvm::ConverterEBCDIC::convertToEBCDIC(Name.substr(4), DualEncodedName);
3658 DualEncodedName += '\0';
3659 DualEncodedName += Name.substr(4);
3660 Init = llvm::ConstantDataArray::getString(VMContext, DualEncodedName);
3661 } else
3662 Init = llvm::ConstantDataArray::getString(VMContext, Name.substr(4));
3663
3664 auto Align = CGM.getContext().getTypeAlignInChars(CGM.getContext().CharTy);
3665
3666 llvm::GlobalVariable *GV = CGM.CreateOrReplaceCXXRuntimeVariable(
3667 Name, Init->getType(), Linkage, Align.getAsAlign());
3668
3669 GV->setInitializer(Init);
3670
3671 return GV;
3672}
3673
3674llvm::Constant *
3675ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
3676 // Mangle the RTTI name.
3677 SmallString<256> Name;
3678 llvm::raw_svector_ostream Out(Name);
3679 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
3680
3681 // Look for an existing global.
3682 llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
3683
3684 if (!GV) {
3685 // Create a new global variable.
3686 // Note for the future: If we would ever like to do deferred emission of
3687 // RTTI, check if emitting vtables opportunistically need any adjustment.
3688
3689 GV = new llvm::GlobalVariable(
3690 CGM.getModule(), CGM.GlobalsInt8PtrTy,
3691 /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage, nullptr, Name);
3692 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
3693 CGM.setGVProperties(GV, RD);
3694 // Import the typeinfo symbol when all non-inline virtual methods are
3695 // imported.
3696 if (CGM.getTarget().hasPS4DLLImportExport()) {
3698 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
3699 CGM.setDSOLocal(GV);
3700 }
3701 }
3702 }
3703
3704 return GV;
3705}
3706
3707/// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
3708/// info for that type is defined in the standard library.
3710 // Itanium C++ ABI 2.9.2:
3711 // Basic type information (e.g. for "int", "bool", etc.) will be kept in
3712 // the run-time support library. Specifically, the run-time support
3713 // library should contain type_info objects for the types X, X* and
3714 // X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
3715 // unsigned char, signed char, short, unsigned short, int, unsigned int,
3716 // long, unsigned long, long long, unsigned long long, float, double,
3717 // long double, char16_t, char32_t, and the IEEE 754r decimal and
3718 // half-precision floating point types.
3719 //
3720 // GCC also emits RTTI for __int128.
3721 // FIXME: We do not emit RTTI information for decimal types here.
3722
3723 // Types added here must also be added to EmitFundamentalRTTIDescriptors.
3724 switch (Ty->getKind()) {
3725 case BuiltinType::Void:
3726 case BuiltinType::NullPtr:
3727 case BuiltinType::Bool:
3728 case BuiltinType::WChar_S:
3729 case BuiltinType::WChar_U:
3730 case BuiltinType::Char_U:
3731 case BuiltinType::Char_S:
3732 case BuiltinType::UChar:
3733 case BuiltinType::SChar:
3734 case BuiltinType::Short:
3735 case BuiltinType::UShort:
3736 case BuiltinType::Int:
3737 case BuiltinType::UInt:
3738 case BuiltinType::Long:
3739 case BuiltinType::ULong:
3740 case BuiltinType::LongLong:
3741 case BuiltinType::ULongLong:
3742 case BuiltinType::Half:
3743 case BuiltinType::Float:
3744 case BuiltinType::Double:
3745 case BuiltinType::LongDouble:
3746 case BuiltinType::Float16:
3747 case BuiltinType::Float128:
3748 case BuiltinType::Ibm128:
3749 case BuiltinType::Char8:
3750 case BuiltinType::Char16:
3751 case BuiltinType::Char32:
3752 case BuiltinType::Int128:
3753 case BuiltinType::UInt128:
3754 return true;
3755
3756#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3757 case BuiltinType::Id:
3758#include "clang/Basic/OpenCLImageTypes.def"
3759#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
3760 case BuiltinType::Id:
3761#include "clang/Basic/OpenCLExtensionTypes.def"
3762 case BuiltinType::OCLSampler:
3763 case BuiltinType::OCLEvent:
3764 case BuiltinType::OCLClkEvent:
3765 case BuiltinType::OCLQueue:
3766 case BuiltinType::OCLReserveID:
3767#define SVE_TYPE(Name, Id, SingletonId) \
3768 case BuiltinType::Id:
3769#include "clang/Basic/AArch64ACLETypes.def"
3770#define PPC_VECTOR_TYPE(Name, Id, Size) \
3771 case BuiltinType::Id:
3772#include "clang/Basic/PPCTypes.def"
3773#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
3774#include "clang/Basic/RISCVVTypes.def"
3775#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
3776#include "clang/Basic/WebAssemblyReferenceTypes.def"
3777#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
3778#include "clang/Basic/AMDGPUTypes.def"
3779#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
3780#include "clang/Basic/HLSLIntangibleTypes.def"
3781 case BuiltinType::ShortAccum:
3782 case BuiltinType::Accum:
3783 case BuiltinType::LongAccum:
3784 case BuiltinType::UShortAccum:
3785 case BuiltinType::UAccum:
3786 case BuiltinType::ULongAccum:
3787 case BuiltinType::ShortFract:
3788 case BuiltinType::Fract:
3789 case BuiltinType::LongFract:
3790 case BuiltinType::UShortFract:
3791 case BuiltinType::UFract:
3792 case BuiltinType::ULongFract:
3793 case BuiltinType::SatShortAccum:
3794 case BuiltinType::SatAccum:
3795 case BuiltinType::SatLongAccum:
3796 case BuiltinType::SatUShortAccum:
3797 case BuiltinType::SatUAccum:
3798 case BuiltinType::SatULongAccum:
3799 case BuiltinType::SatShortFract:
3800 case BuiltinType::SatFract:
3801 case BuiltinType::SatLongFract:
3802 case BuiltinType::SatUShortFract:
3803 case BuiltinType::SatUFract:
3804 case BuiltinType::SatULongFract:
3805 case BuiltinType::BFloat16:
3806 return false;
3807
3808 case BuiltinType::Dependent:
3809#define BUILTIN_TYPE(Id, SingletonId)
3810#define PLACEHOLDER_TYPE(Id, SingletonId) \
3811 case BuiltinType::Id:
3812#include "clang/AST/BuiltinTypes.def"
3813 llvm_unreachable("asking for RRTI for a placeholder type!");
3814
3815 case BuiltinType::ObjCId:
3816 case BuiltinType::ObjCClass:
3817 case BuiltinType::ObjCSel:
3818 llvm_unreachable("FIXME: Objective-C types are unsupported!");
3819 }
3820
3821 llvm_unreachable("Invalid BuiltinType Kind!");
3822}
3823
3824static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
3825 QualType PointeeTy = PointerTy->getPointeeType();
3826 const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
3827 if (!BuiltinTy)
3828 return false;
3829
3830 // Check the qualifiers.
3831 Qualifiers Quals = PointeeTy.getQualifiers();
3832 Quals.removeConst();
3833
3834 if (!Quals.empty())
3835 return false;
3836
3837 return TypeInfoIsInStandardLibrary(BuiltinTy);
3838}
3839
3840/// IsStandardLibraryRTTIDescriptor - Returns whether the type
3841/// information for the given type exists in the standard library.
3843 // Type info for builtin types is defined in the standard library.
3844 if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
3845 return TypeInfoIsInStandardLibrary(BuiltinTy);
3846
3847 // Type info for some pointer types to builtin types is defined in the
3848 // standard library.
3849 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
3850 return TypeInfoIsInStandardLibrary(PointerTy);
3851
3852 return false;
3853}
3854
3855/// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
3856/// the given type exists somewhere else, and that we should not emit the type
3857/// information in this translation unit. Assumes that it is not a
3858/// standard-library type.
3860 QualType Ty) {
3861 ASTContext &Context = CGM.getContext();
3862
3863 // If RTTI is disabled, assume it might be disabled in the
3864 // translation unit that defines any potential key function, too.
3865 if (!Context.getLangOpts().RTTI) return false;
3866
3867 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
3868 const CXXRecordDecl *RD =
3869 cast<CXXRecordDecl>(RecordTy->getDecl())->getDefinitionOrSelf();
3870 if (!RD->hasDefinition())
3871 return false;
3872
3873 if (!RD->isDynamicClass())
3874 return false;
3875
3876 // FIXME: this may need to be reconsidered if the key function
3877 // changes.
3878 // N.B. We must always emit the RTTI data ourselves if there exists a key
3879 // function.
3880 bool IsDLLImport = RD->hasAttr<DLLImportAttr>();
3881
3882 // Don't import the RTTI but emit it locally.
3883 if (CGM.getTriple().isOSCygMing())
3884 return false;
3885
3886 if (CGM.getVTables().isVTableExternal(RD)) {
3887 if (CGM.getTarget().hasPS4DLLImportExport())
3888 return true;
3889
3890 return IsDLLImport && !CGM.getTriple().isWindowsItaniumEnvironment()
3891 ? false
3892 : true;
3893 }
3894 if (IsDLLImport)
3895 return true;
3896 }
3897
3898 return false;
3899}
3900
3901/// IsIncompleteClassType - Returns whether the given record type is incomplete.
3902static bool IsIncompleteClassType(const RecordType *RecordTy) {
3903 return !RecordTy->getDecl()->getDefinitionOrSelf()->isCompleteDefinition();
3904}
3905
3906/// ContainsIncompleteClassType - Returns whether the given type contains an
3907/// incomplete class type. This is true if
3908///
3909/// * The given type is an incomplete class type.
3910/// * The given type is a pointer type whose pointee type contains an
3911/// incomplete class type.
3912/// * The given type is a member pointer type whose class is an incomplete
3913/// class type.
3914/// * The given type is a member pointer type whoise pointee type contains an
3915/// incomplete class type.
3916/// is an indirect or direct pointer to an incomplete class type.
3918 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
3919 if (IsIncompleteClassType(RecordTy))
3920 return true;
3921 }
3922
3923 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
3924 return ContainsIncompleteClassType(PointerTy->getPointeeType());
3925
3926 if (const MemberPointerType *MemberPointerTy =
3927 dyn_cast<MemberPointerType>(Ty)) {
3928 // Check if the class type is incomplete.
3929 if (!MemberPointerTy->getMostRecentCXXRecordDecl()->hasDefinition())
3930 return true;
3931
3932 return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
3933 }
3934
3935 return false;
3936}
3937
3938// CanUseSingleInheritance - Return whether the given record decl has a "single,
3939// public, non-virtual base at offset zero (i.e. the derived class is dynamic
3940// iff the base is)", according to Itanium C++ ABI, 2.95p6b.
3942 // Check the number of bases.
3943 if (RD->getNumBases() != 1)
3944 return false;
3945
3946 // Get the base.
3948
3949 // Check that the base is not virtual.
3950 if (Base->isVirtual())
3951 return false;
3952
3953 // Check that the base is public.
3954 if (Base->getAccessSpecifier() != AS_public)
3955 return false;
3956
3957 // Check that the class is dynamic iff the base is.
3958 auto *BaseDecl = Base->getType()->castAsCXXRecordDecl();
3959 if (!BaseDecl->isEmpty() &&
3960 BaseDecl->isDynamicClass() != RD->isDynamicClass())
3961 return false;
3962
3963 return true;
3964}
3965
3966void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty,
3967 llvm::Constant *StorageAddress) {
3968 // abi::__class_type_info.
3969 static const char * const ClassTypeInfo =
3970 "_ZTVN10__cxxabiv117__class_type_infoE";
3971 // abi::__si_class_type_info.
3972 static const char * const SIClassTypeInfo =
3973 "_ZTVN10__cxxabiv120__si_class_type_infoE";
3974 // abi::__vmi_class_type_info.
3975 static const char * const VMIClassTypeInfo =
3976 "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
3977
3978 const char *VTableName = nullptr;
3979
3980 switch (Ty->getTypeClass()) {
3981#define TYPE(Class, Base)
3982#define ABSTRACT_TYPE(Class, Base)
3983#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3984#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3985#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3986#include "clang/AST/TypeNodes.inc"
3987 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
3988
3989 case Type::LValueReference:
3990 case Type::RValueReference:
3991 llvm_unreachable("References shouldn't get here");
3992
3993 case Type::Auto:
3994 case Type::DeducedTemplateSpecialization:
3995 llvm_unreachable("Undeduced type shouldn't get here");
3996
3997 case Type::Pipe:
3998 llvm_unreachable("Pipe types shouldn't get here");
3999
4000 case Type::ArrayParameter:
4001 llvm_unreachable("Array Parameter types should not get here.");
4002
4003 case Type::Builtin:
4004 case Type::BitInt:
4005 case Type::OverflowBehavior:
4006 // GCC treats vector and complex types as fundamental types.
4007 case Type::Vector:
4008 case Type::ExtVector:
4009 case Type::ConstantMatrix:
4010 case Type::Complex:
4011 case Type::Atomic:
4012 // FIXME: GCC treats block pointers as fundamental types?!
4013 case Type::BlockPointer:
4014 // abi::__fundamental_type_info.
4015 VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
4016 break;
4017
4018 case Type::ConstantArray:
4019 case Type::IncompleteArray:
4020 case Type::VariableArray:
4021 // abi::__array_type_info.
4022 VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
4023 break;
4024
4025 case Type::FunctionNoProto:
4026 case Type::FunctionProto:
4027 // abi::__function_type_info.
4028 VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
4029 break;
4030
4031 case Type::Enum:
4032 // abi::__enum_type_info.
4033 VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
4034 break;
4035
4036 case Type::Record: {
4037 const auto *RD = cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl())
4038 ->getDefinitionOrSelf();
4039
4040 if (!RD->hasDefinition() || !RD->getNumBases()) {
4041 VTableName = ClassTypeInfo;
4042 } else if (CanUseSingleInheritance(RD)) {
4043 VTableName = SIClassTypeInfo;
4044 } else {
4045 VTableName = VMIClassTypeInfo;
4046 }
4047
4048 break;
4049 }
4050
4051 case Type::ObjCObject:
4052 // Ignore protocol qualifiers.
4053 Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
4054
4055 // Handle id and Class.
4056 if (isa<BuiltinType>(Ty)) {
4057 VTableName = ClassTypeInfo;
4058 break;
4059 }
4060
4061 assert(isa<ObjCInterfaceType>(Ty));
4062 [[fallthrough]];
4063
4064 case Type::ObjCInterface:
4065 if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
4066 VTableName = SIClassTypeInfo;
4067 } else {
4068 VTableName = ClassTypeInfo;
4069 }
4070 break;
4071
4072 case Type::ObjCObjectPointer:
4073 case Type::Pointer:
4074 // abi::__pointer_type_info.
4075 VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
4076 break;
4077
4078 case Type::MemberPointer:
4079 // abi::__pointer_to_member_type_info.
4080 VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
4081 break;
4082
4083 case Type::HLSLAttributedResource:
4084 case Type::HLSLInlineSpirv:
4085 llvm_unreachable("HLSL doesn't support virtual functions");
4086 }
4087
4088 llvm::Constant *VTable = nullptr;
4089
4090 // Check if the alias exists. If it doesn't, then get or create the global.
4091 if (CGM.getLangOpts().RelativeCXXABIVTables)
4092 VTable = CGM.getModule().getNamedAlias(VTableName);
4093 if (!VTable) {
4094 llvm::Type *Ty = llvm::ArrayType::get(CGM.GlobalsInt8PtrTy, 0);
4095 VTable = CGM.getModule().getOrInsertGlobal(VTableName, Ty);
4096 }
4097
4098 CGM.setDSOLocal(cast<llvm::GlobalValue>(VTable->stripPointerCasts()));
4099
4100 llvm::Type *PtrDiffTy =
4102
4103 // The vtable address point is 2.
4104 if (CGM.getLangOpts().RelativeCXXABIVTables) {
4105 // The vtable address point is 8 bytes after its start:
4106 // 4 for the offset to top + 4 for the relative offset to rtti.
4107 llvm::Constant *Eight = llvm::ConstantInt::get(CGM.Int32Ty, 8);
4108 VTable = llvm::ConstantExpr::getInBoundsPtrAdd(VTable, Eight);
4109 } else {
4110 llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
4111 VTable = llvm::ConstantExpr::getInBoundsGetElementPtr(CGM.GlobalsInt8PtrTy,
4112 VTable, Two);
4113 }
4114
4115 if (const auto &Schema =
4117 VTable = CGM.getConstantSignedPointer(
4118 VTable, Schema,
4119 Schema.isAddressDiscriminated() ? StorageAddress : nullptr,
4120 GlobalDecl(), QualType(Ty, 0));
4121
4122 Fields.push_back(VTable);
4123}
4124
4125/// Return the linkage that the type info and type info name constants
4126/// should have for the given type.
4127static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM,
4128 QualType Ty) {
4129 // Itanium C++ ABI 2.9.5p7:
4130 // In addition, it and all of the intermediate abi::__pointer_type_info
4131 // structs in the chain down to the abi::__class_type_info for the
4132 // incomplete class type must be prevented from resolving to the
4133 // corresponding type_info structs for the complete class type, possibly
4134 // by making them local static objects. Finally, a dummy class RTTI is
4135 // generated for the incomplete type that will not resolve to the final
4136 // complete class RTTI (because the latter need not exist), possibly by
4137 // making it a local static object.
4139 return llvm::GlobalValue::InternalLinkage;
4140
4141 switch (Ty->getLinkage()) {
4142 case Linkage::Invalid:
4143 llvm_unreachable("Linkage hasn't been computed!");
4144
4145 case Linkage::None:
4146 case Linkage::Internal:
4148 return llvm::GlobalValue::InternalLinkage;
4149
4151 case Linkage::Module:
4152 case Linkage::External:
4153 // RTTI is not enabled, which means that this type info struct is going
4154 // to be used for exception handling. Give it linkonce_odr linkage.
4155 if (!CGM.getLangOpts().RTTI)
4156 return llvm::GlobalValue::LinkOnceODRLinkage;
4157
4158 if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
4159 const auto *RD =
4160 cast<CXXRecordDecl>(Record->getDecl())->getDefinitionOrSelf();
4161 if (RD->hasAttr<WeakAttr>())
4162 return llvm::GlobalValue::WeakODRLinkage;
4163 if (CGM.getTriple().isWindowsItaniumEnvironment())
4164 if (RD->hasAttr<DLLImportAttr>() &&
4166 return llvm::GlobalValue::ExternalLinkage;
4167 // MinGW always uses LinkOnceODRLinkage for type info.
4168 if (RD->isDynamicClass() &&
4169 !CGM.getContext().getTargetInfo().getTriple().isOSCygMing())
4170 return CGM.getVTableLinkage(RD);
4171 }
4172
4173 return llvm::GlobalValue::LinkOnceODRLinkage;
4174 }
4175
4176 llvm_unreachable("Invalid linkage!");
4177}
4178
4179llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty) {
4180 // We want to operate on the canonical type.
4181 Ty = Ty.getCanonicalType();
4182
4183 // Check if we've already emitted an RTTI descriptor for this type.
4184 SmallString<256> Name;
4185 llvm::raw_svector_ostream Out(Name);
4186 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
4187
4188 llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
4189 if (OldGV && !OldGV->isDeclaration()) {
4190 assert(!OldGV->hasAvailableExternallyLinkage() &&
4191 "available_externally typeinfos not yet implemented");
4192
4193 return OldGV;
4194 }
4195
4196 // Check if there is already an external RTTI descriptor for this type.
4199 return GetAddrOfExternalRTTIDescriptor(Ty);
4200
4201 // Emit the standard library with external linkage.
4202 llvm::GlobalVariable::LinkageTypes Linkage = getTypeInfoLinkage(CGM, Ty);
4203
4204 // Give the type_info object and name the formal visibility of the
4205 // type itself.
4206 llvm::GlobalValue::VisibilityTypes llvmVisibility;
4207 if (llvm::GlobalValue::isLocalLinkage(Linkage))
4208 // If the linkage is local, only default visibility makes sense.
4209 llvmVisibility = llvm::GlobalValue::DefaultVisibility;
4210 else if (CXXABI.classifyRTTIUniqueness(Ty, Linkage) ==
4211 ItaniumCXXABI::RUK_NonUniqueHidden)
4212 llvmVisibility = llvm::GlobalValue::HiddenVisibility;
4213 else
4214 llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility());
4215
4216 llvm::GlobalValue::DLLStorageClassTypes DLLStorageClass =
4217 llvm::GlobalValue::DefaultStorageClass;
4218 if (auto RD = Ty->getAsCXXRecordDecl()) {
4219 if ((CGM.getTriple().isWindowsItaniumEnvironment() &&
4220 RD->hasAttr<DLLExportAttr>()) ||
4222 !llvm::GlobalValue::isLocalLinkage(Linkage) &&
4223 llvmVisibility == llvm::GlobalValue::DefaultVisibility))
4224 DLLStorageClass = llvm::GlobalValue::DLLExportStorageClass;
4225 }
4226 return BuildTypeInfo(Ty, Linkage, llvmVisibility, DLLStorageClass);
4227}
4228
4229llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(
4230 QualType Ty,
4231 llvm::GlobalVariable::LinkageTypes Linkage,
4232 llvm::GlobalValue::VisibilityTypes Visibility,
4233 llvm::GlobalValue::DLLStorageClassTypes DLLStorageClass) {
4234 SmallString<256> Name;
4235 llvm::raw_svector_ostream Out(Name);
4236 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
4237 llvm::Module &M = CGM.getModule();
4238 llvm::GlobalVariable *OldGV = M.getNamedGlobal(Name);
4239 // int8 is an arbitrary type to be replaced later with replaceInitializer.
4240 llvm::GlobalVariable *GV =
4241 new llvm::GlobalVariable(M, CGM.Int8Ty, /*isConstant=*/true, Linkage,
4242 /*Initializer=*/nullptr, Name);
4243
4244 // Add the vtable pointer.
4245 BuildVTablePointer(cast<Type>(Ty), GV);
4246
4247 // And the name.
4248 llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
4249 llvm::Constant *TypeNameField;
4250
4251 // If we're supposed to demote the visibility, be sure to set a flag
4252 // to use a string comparison for type_info comparisons.
4253 ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness =
4254 CXXABI.classifyRTTIUniqueness(Ty, Linkage);
4255 if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) {
4256 // The flag is the sign bit, which on ARM64 is defined to be clear
4257 // for global pointers. This is very ARM64-specific.
4258 TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty);
4259 llvm::Constant *flag =
4260 llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63);
4261 TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag);
4262 TypeNameField =
4263 llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.GlobalsInt8PtrTy);
4264 } else {
4265 TypeNameField = TypeName;
4266 }
4267 Fields.push_back(TypeNameField);
4268
4269 switch (Ty->getTypeClass()) {
4270#define TYPE(Class, Base)
4271#define ABSTRACT_TYPE(Class, Base)
4272#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
4273#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4274#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4275#include "clang/AST/TypeNodes.inc"
4276 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
4277
4278 // GCC treats vector types as fundamental types.
4279 case Type::Builtin:
4280 case Type::Vector:
4281 case Type::ExtVector:
4282 case Type::ConstantMatrix:
4283 case Type::Complex:
4284 case Type::BlockPointer:
4285 // Itanium C++ ABI 2.9.5p4:
4286 // abi::__fundamental_type_info adds no data members to std::type_info.
4287 break;
4288
4289 case Type::LValueReference:
4290 case Type::RValueReference:
4291 llvm_unreachable("References shouldn't get here");
4292
4293 case Type::Auto:
4294 case Type::DeducedTemplateSpecialization:
4295 llvm_unreachable("Undeduced type shouldn't get here");
4296
4297 case Type::Pipe:
4298 break;
4299
4300 case Type::BitInt:
4301 break;
4302
4303 case Type::ConstantArray:
4304 case Type::IncompleteArray:
4305 case Type::VariableArray:
4306 case Type::ArrayParameter:
4307 // Itanium C++ ABI 2.9.5p5:
4308 // abi::__array_type_info adds no data members to std::type_info.
4309 break;
4310
4311 case Type::FunctionNoProto:
4312 case Type::FunctionProto:
4313 // Itanium C++ ABI 2.9.5p5:
4314 // abi::__function_type_info adds no data members to std::type_info.
4315 break;
4316
4317 case Type::Enum:
4318 // Itanium C++ ABI 2.9.5p5:
4319 // abi::__enum_type_info adds no data members to std::type_info.
4320 break;
4321
4322 case Type::Record: {
4323 const auto *RD = cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl())
4324 ->getDefinitionOrSelf();
4325 if (!RD->hasDefinition() || !RD->getNumBases()) {
4326 // We don't need to emit any fields.
4327 break;
4328 }
4329
4331 BuildSIClassTypeInfo(RD);
4332 else
4333 BuildVMIClassTypeInfo(RD);
4334
4335 break;
4336 }
4337
4338 case Type::ObjCObject:
4339 case Type::ObjCInterface:
4340 BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
4341 break;
4342
4343 case Type::ObjCObjectPointer:
4344 BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
4345 break;
4346
4347 case Type::Pointer:
4348 BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
4349 break;
4350
4351 case Type::MemberPointer:
4352 BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
4353 break;
4354
4355 case Type::Atomic:
4356 // No fields, at least for the moment.
4357 break;
4358
4359 case Type::OverflowBehavior:
4360 break;
4361
4362 case Type::HLSLAttributedResource:
4363 case Type::HLSLInlineSpirv:
4364 llvm_unreachable("HLSL doesn't support RTTI");
4365 }
4366
4367 GV->replaceInitializer(llvm::ConstantStruct::getAnon(Fields));
4368
4369 // Export the typeinfo in the same circumstances as the vtable is exported.
4370 auto GVDLLStorageClass = DLLStorageClass;
4371 if (CGM.getTarget().hasPS4DLLImportExport() &&
4372 GVDLLStorageClass != llvm::GlobalVariable::DLLExportStorageClass) {
4373 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
4374 const auto *RD =
4375 cast<CXXRecordDecl>(RecordTy->getDecl())->getDefinitionOrSelf();
4376 if (RD->hasAttr<DLLExportAttr>() ||
4378 GVDLLStorageClass = llvm::GlobalVariable::DLLExportStorageClass;
4379 }
4380 }
4381
4382 // If there's already an old global variable, replace it with the new one.
4383 if (OldGV) {
4384 GV->takeName(OldGV);
4385 OldGV->replaceAllUsesWith(GV);
4386 OldGV->eraseFromParent();
4387 }
4388
4389 if (CGM.supportsCOMDAT() && GV->isWeakForLinker())
4390 GV->setComdat(M.getOrInsertComdat(GV->getName()));
4391
4392 CharUnits Align = CGM.getContext().toCharUnitsFromBits(
4394 GV->setAlignment(Align.getAsAlign());
4395
4396 // The Itanium ABI specifies that type_info objects must be globally
4397 // unique, with one exception: if the type is an incomplete class
4398 // type or a (possibly indirect) pointer to one. That exception
4399 // affects the general case of comparing type_info objects produced
4400 // by the typeid operator, which is why the comparison operators on
4401 // std::type_info generally use the type_info name pointers instead
4402 // of the object addresses. However, the language's built-in uses
4403 // of RTTI generally require class types to be complete, even when
4404 // manipulating pointers to those class types. This allows the
4405 // implementation of dynamic_cast to rely on address equality tests,
4406 // which is much faster.
4407
4408 // All of this is to say that it's important that both the type_info
4409 // object and the type_info name be uniqued when weakly emitted.
4410
4411 TypeName->setVisibility(Visibility);
4412 CGM.setDSOLocal(TypeName);
4413
4414 GV->setVisibility(Visibility);
4415 CGM.setDSOLocal(GV);
4416
4417 TypeName->setDLLStorageClass(DLLStorageClass);
4418 GV->setDLLStorageClass(GVDLLStorageClass);
4419
4420 TypeName->setPartition(CGM.getCodeGenOpts().SymbolPartition);
4421 GV->setPartition(CGM.getCodeGenOpts().SymbolPartition);
4422
4423 return GV;
4424}
4425
4426/// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
4427/// for the given Objective-C object type.
4428void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
4429 // Drop qualifiers.
4430 const Type *T = OT->getBaseType().getTypePtr();
4432
4433 // The builtin types are abi::__class_type_infos and don't require
4434 // extra fields.
4435 if (isa<BuiltinType>(T)) return;
4436
4437 ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
4438 ObjCInterfaceDecl *Super = Class->getSuperClass();
4439
4440 // Root classes are also __class_type_info.
4441 if (!Super) return;
4442
4443 QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
4444
4445 // Everything else is single inheritance.
4446 llvm::Constant *BaseTypeInfo =
4447 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy);
4448 Fields.push_back(BaseTypeInfo);
4449}
4450
4451/// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
4452/// inheritance, according to the Itanium C++ ABI, 2.95p6b.
4453void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
4454 // Itanium C++ ABI 2.9.5p6b:
4455 // It adds to abi::__class_type_info a single member pointing to the
4456 // type_info structure for the base type,
4457 llvm::Constant *BaseTypeInfo =
4458 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType());
4459 Fields.push_back(BaseTypeInfo);
4460}
4461
4462namespace {
4463 /// SeenBases - Contains virtual and non-virtual bases seen when traversing
4464 /// a class hierarchy.
4465 struct SeenBases {
4466 llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
4467 llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
4468 };
4469}
4470
4471/// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
4472/// abi::__vmi_class_type_info.
4473///
4475 SeenBases &Bases) {
4476
4477 unsigned Flags = 0;
4478
4479 auto *BaseDecl = Base->getType()->castAsCXXRecordDecl();
4480 if (Base->isVirtual()) {
4481 // Mark the virtual base as seen.
4482 if (!Bases.VirtualBases.insert(BaseDecl).second) {
4483 // If this virtual base has been seen before, then the class is diamond
4484 // shaped.
4485 Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped;
4486 } else {
4487 if (Bases.NonVirtualBases.count(BaseDecl))
4488 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
4489 }
4490 } else {
4491 // Mark the non-virtual base as seen.
4492 if (!Bases.NonVirtualBases.insert(BaseDecl).second) {
4493 // If this non-virtual base has been seen before, then the class has non-
4494 // diamond shaped repeated inheritance.
4495 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
4496 } else {
4497 if (Bases.VirtualBases.count(BaseDecl))
4498 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
4499 }
4500 }
4501
4502 // Walk all bases.
4503 for (const auto &I : BaseDecl->bases())
4504 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
4505
4506 return Flags;
4507}
4508
4510 unsigned Flags = 0;
4511 SeenBases Bases;
4512
4513 // Walk all bases.
4514 for (const auto &I : RD->bases())
4515 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
4516
4517 return Flags;
4518}
4519
4520/// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
4521/// classes with bases that do not satisfy the abi::__si_class_type_info
4522/// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
4523void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
4524 llvm::Type *UnsignedIntLTy =
4526
4527 // Itanium C++ ABI 2.9.5p6c:
4528 // __flags is a word with flags describing details about the class
4529 // structure, which may be referenced by using the __flags_masks
4530 // enumeration. These flags refer to both direct and indirect bases.
4531 unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
4532 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
4533
4534 // Itanium C++ ABI 2.9.5p6c:
4535 // __base_count is a word with the number of direct proper base class
4536 // descriptions that follow.
4537 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
4538
4539 if (!RD->getNumBases())
4540 return;
4541
4542 // Now add the base class descriptions.
4543
4544 // Itanium C++ ABI 2.9.5p6c:
4545 // __base_info[] is an array of base class descriptions -- one for every
4546 // direct proper base. Each description is of the type:
4547 //
4548 // struct abi::__base_class_type_info {
4549 // public:
4550 // const __class_type_info *__base_type;
4551 // long __offset_flags;
4552 //
4553 // enum __offset_flags_masks {
4554 // __virtual_mask = 0x1,
4555 // __public_mask = 0x2,
4556 // __offset_shift = 8
4557 // };
4558 // };
4559
4560 // If we're in mingw and 'long' isn't wide enough for a pointer, use 'long
4561 // long' instead of 'long' for __offset_flags. libstdc++abi uses long long on
4562 // LLP64 platforms.
4563 // FIXME: Consider updating libc++abi to match, and extend this logic to all
4564 // LLP64 platforms.
4565 QualType OffsetFlagsTy = CGM.getContext().LongTy;
4566 const TargetInfo &TI = CGM.getContext().getTargetInfo();
4567 if (TI.getTriple().isOSCygMing() &&
4568 TI.getPointerWidth(LangAS::Default) > TI.getLongWidth())
4569 OffsetFlagsTy = CGM.getContext().LongLongTy;
4570 llvm::Type *OffsetFlagsLTy =
4571 CGM.getTypes().ConvertType(OffsetFlagsTy);
4572
4573 for (const auto &Base : RD->bases()) {
4574 // The __base_type member points to the RTTI for the base type.
4575 Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType()));
4576
4577 auto *BaseDecl = Base.getType()->castAsCXXRecordDecl();
4578 int64_t OffsetFlags = 0;
4579
4580 // All but the lower 8 bits of __offset_flags are a signed offset.
4581 // For a non-virtual base, this is the offset in the object of the base
4582 // subobject. For a virtual base, this is the offset in the virtual table of
4583 // the virtual base offset for the virtual base referenced (negative).
4584 CharUnits Offset;
4585 if (Base.isVirtual())
4586 Offset =
4588 else {
4589 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
4590 Offset = Layout.getBaseClassOffset(BaseDecl);
4591 };
4592
4593 OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
4594
4595 // The low-order byte of __offset_flags contains flags, as given by the
4596 // masks from the enumeration __offset_flags_masks.
4597 if (Base.isVirtual())
4598 OffsetFlags |= BCTI_Virtual;
4599 if (Base.getAccessSpecifier() == AS_public)
4600 OffsetFlags |= BCTI_Public;
4601
4602 Fields.push_back(llvm::ConstantInt::getSigned(OffsetFlagsLTy, OffsetFlags));
4603 }
4604}
4605
4606/// Compute the flags for a __pbase_type_info, and remove the corresponding
4607/// pieces from \p Type.
4609 unsigned Flags = 0;
4610
4611 if (Type.isConstQualified())
4612 Flags |= ItaniumRTTIBuilder::PTI_Const;
4613 if (Type.isVolatileQualified())
4614 Flags |= ItaniumRTTIBuilder::PTI_Volatile;
4615 if (Type.isRestrictQualified())
4616 Flags |= ItaniumRTTIBuilder::PTI_Restrict;
4617 Type = Type.getUnqualifiedType();
4618
4619 // Itanium C++ ABI 2.9.5p7:
4620 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
4621 // incomplete class type, the incomplete target type flag is set.
4623 Flags |= ItaniumRTTIBuilder::PTI_Incomplete;
4624
4625 if (auto *Proto = Type->getAs<FunctionProtoType>()) {
4626 if (Proto->isNothrow()) {
4627 Flags |= ItaniumRTTIBuilder::PTI_Noexcept;
4629 }
4630 }
4631
4632 return Flags;
4633}
4634
4635/// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
4636/// used for pointer types.
4637void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
4638 // Itanium C++ ABI 2.9.5p7:
4639 // __flags is a flag word describing the cv-qualification and other
4640 // attributes of the type pointed to
4641 unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy);
4642
4643 llvm::Type *UnsignedIntLTy =
4645 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
4646
4647 // Itanium C++ ABI 2.9.5p7:
4648 // __pointee is a pointer to the std::type_info derivation for the
4649 // unqualified type being pointed to.
4650 llvm::Constant *PointeeTypeInfo =
4651 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy);
4652 Fields.push_back(PointeeTypeInfo);
4653}
4654
4655/// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
4656/// struct, used for member pointer types.
4657void
4658ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
4659 QualType PointeeTy = Ty->getPointeeType();
4660
4661 // Itanium C++ ABI 2.9.5p7:
4662 // __flags is a flag word describing the cv-qualification and other
4663 // attributes of the type pointed to.
4664 unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy);
4665
4666 const auto *RD = Ty->getMostRecentCXXRecordDecl();
4667 if (!RD->hasDefinition())
4668 Flags |= PTI_ContainingClassIncomplete;
4669
4670 llvm::Type *UnsignedIntLTy =
4672 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
4673
4674 // Itanium C++ ABI 2.9.5p7:
4675 // __pointee is a pointer to the std::type_info derivation for the
4676 // unqualified type being pointed to.
4677 llvm::Constant *PointeeTypeInfo =
4678 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy);
4679 Fields.push_back(PointeeTypeInfo);
4680
4681 // Itanium C++ ABI 2.9.5p9:
4682 // __context is a pointer to an abi::__class_type_info corresponding to the
4683 // class type containing the member pointed to
4684 // (e.g., the "A" in "int A::*").
4686 Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(T));
4687}
4688
4689llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) {
4690 return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty);
4691}
4692
4693void ItaniumCXXABI::EmitFundamentalRTTIDescriptors(const CXXRecordDecl *RD) {
4694 // Types added here must also be added to TypeInfoIsInStandardLibrary.
4695 QualType FundamentalTypes[] = {
4696 getContext().VoidTy, getContext().NullPtrTy,
4697 getContext().BoolTy, getContext().WCharTy,
4698 getContext().CharTy, getContext().UnsignedCharTy,
4699 getContext().SignedCharTy, getContext().ShortTy,
4700 getContext().UnsignedShortTy, getContext().IntTy,
4701 getContext().UnsignedIntTy, getContext().LongTy,
4702 getContext().UnsignedLongTy, getContext().LongLongTy,
4703 getContext().UnsignedLongLongTy, getContext().Int128Ty,
4704 getContext().UnsignedInt128Ty, getContext().HalfTy,
4705 getContext().FloatTy, getContext().DoubleTy,
4706 getContext().LongDoubleTy, getContext().Float128Ty,
4707 getContext().Char8Ty, getContext().Char16Ty,
4708 getContext().Char32Ty
4709 };
4710 llvm::GlobalValue::DLLStorageClassTypes DLLStorageClass =
4711 RD->hasAttr<DLLExportAttr>() || CGM.shouldMapVisibilityToDLLExport(RD)
4712 ? llvm::GlobalValue::DLLExportStorageClass
4713 : llvm::GlobalValue::DefaultStorageClass;
4714 llvm::GlobalValue::VisibilityTypes Visibility =
4716 for (const QualType &FundamentalType : FundamentalTypes) {
4717 QualType PointerType = getContext().getPointerType(FundamentalType);
4718 QualType PointerTypeConst = getContext().getPointerType(
4719 FundamentalType.withConst());
4720 for (QualType Type : {FundamentalType, PointerType, PointerTypeConst})
4721 ItaniumRTTIBuilder(*this).BuildTypeInfo(
4722 Type, llvm::GlobalValue::ExternalLinkage,
4723 Visibility, DLLStorageClass);
4724 }
4725}
4726
4727/// What sort of uniqueness rules should we use for the RTTI for the
4728/// given type?
4729ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness(
4730 QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const {
4731 if (shouldRTTIBeUnique())
4732 return RUK_Unique;
4733
4734 // It's only necessary for linkonce_odr or weak_odr linkage.
4735 if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage &&
4736 Linkage != llvm::GlobalValue::WeakODRLinkage)
4737 return RUK_Unique;
4738
4739 // It's only necessary with default visibility.
4740 if (CanTy->getVisibility() != DefaultVisibility)
4741 return RUK_Unique;
4742
4743 // If we're not required to publish this symbol, hide it.
4744 if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
4745 return RUK_NonUniqueHidden;
4746
4747 // If we're required to publish this symbol, as we might be under an
4748 // explicit instantiation, leave it with default visibility but
4749 // enable string-comparisons.
4750 assert(Linkage == llvm::GlobalValue::WeakODRLinkage);
4751 return RUK_NonUniqueVisible;
4752}
4753
4754// Find out how to codegen the complete destructor and constructor
4755namespace {
4756enum class StructorCodegen { Emit, RAUW, Alias, COMDAT };
4757}
4758static StructorCodegen getCodegenToUse(CodeGenModule &CGM,
4759 const CXXMethodDecl *MD) {
4760 if (!CGM.getCodeGenOpts().CXXCtorDtorAliases)
4761 return StructorCodegen::Emit;
4762
4763 // The complete and base structors are not equivalent if there are any virtual
4764 // bases, so emit separate functions.
4765 if (MD->getParent()->getNumVBases())
4766 return StructorCodegen::Emit;
4767
4769 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
4771 } else {
4772 const auto *CD = cast<CXXConstructorDecl>(MD);
4774 }
4775 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
4776
4777 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage))
4778 return StructorCodegen::RAUW;
4779
4780 // FIXME: Should we allow available_externally aliases?
4781 if (!llvm::GlobalAlias::isValidLinkage(Linkage))
4782 return StructorCodegen::RAUW;
4783
4784 if (llvm::GlobalValue::isWeakForLinker(Linkage)) {
4785 // Only ELF and wasm support COMDATs with arbitrary names (C5/D5).
4786 if (CGM.getTarget().getTriple().isOSBinFormatELF() ||
4787 CGM.getTarget().getTriple().isOSBinFormatWasm())
4788 return StructorCodegen::COMDAT;
4789 return StructorCodegen::Emit;
4790 }
4791
4792 return StructorCodegen::Alias;
4793}
4794
4797 GlobalDecl TargetDecl) {
4798 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
4799
4800 StringRef MangledName = CGM.getMangledName(AliasDecl);
4801 llvm::GlobalValue *Entry = CGM.GetGlobalValue(MangledName);
4802 if (Entry && !Entry->isDeclaration())
4803 return;
4804
4805 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(TargetDecl));
4806
4807 // Create the alias with no name.
4808 auto *Alias = llvm::GlobalAlias::create(Linkage, "", Aliasee);
4809
4810 // Constructors and destructors are always unnamed_addr.
4811 Alias->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4812
4813 // Switch any previous uses to the alias.
4814 if (Entry) {
4815 assert(Entry->getType() == Aliasee->getType() &&
4816 "declaration exists with different type");
4817 Alias->takeName(Entry);
4818 Entry->replaceAllUsesWith(Alias);
4819 Entry->eraseFromParent();
4820 } else {
4821 Alias->setName(MangledName);
4822 }
4823
4824 // Finally, set up the alias with its proper name and attributes.
4825 CGM.SetCommonAttributes(AliasDecl, Alias);
4826}
4827
4828void ItaniumCXXABI::emitCXXStructor(GlobalDecl GD) {
4829 auto *MD = cast<CXXMethodDecl>(GD.getDecl());
4830 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
4831 const CXXDestructorDecl *DD = CD ? nullptr : cast<CXXDestructorDecl>(MD);
4832
4833 StructorCodegen CGType = getCodegenToUse(CGM, MD);
4834
4835 if (CD ? GD.getCtorType() == Ctor_Complete
4836 : GD.getDtorType() == Dtor_Complete) {
4837 GlobalDecl BaseDecl;
4838 if (CD)
4839 BaseDecl = GD.getWithCtorType(Ctor_Base);
4840 else
4841 BaseDecl = GD.getWithDtorType(Dtor_Base);
4842
4843 if (CGType == StructorCodegen::Alias || CGType == StructorCodegen::COMDAT) {
4844 emitConstructorDestructorAlias(CGM, GD, BaseDecl);
4845 return;
4846 }
4847
4848 if (CGType == StructorCodegen::RAUW) {
4849 StringRef MangledName = CGM.getMangledName(GD);
4850 auto *Aliasee = CGM.GetAddrOfGlobal(BaseDecl);
4851 CGM.addReplacement(MangledName, Aliasee);
4852 return;
4853 }
4854 }
4855
4856 // The base destructor is equivalent to the base destructor of its
4857 // base class if there is exactly one non-virtual base class with a
4858 // non-trivial destructor, there are no fields with a non-trivial
4859 // destructor, and the body of the destructor is trivial.
4860 if (DD && GD.getDtorType() == Dtor_Base &&
4861 CGType != StructorCodegen::COMDAT &&
4863 return;
4864
4865 // FIXME: The deleting destructor is equivalent to the selected operator
4866 // delete if:
4867 // * either the delete is a destroying operator delete or the destructor
4868 // would be trivial if it weren't virtual,
4869 // * the conversion from the 'this' parameter to the first parameter of the
4870 // destructor is equivalent to a bitcast,
4871 // * the destructor does not have an implicit "this" return, and
4872 // * the operator delete has the same calling convention and IR function type
4873 // as the destructor.
4874 // In such cases we should try to emit the deleting dtor as an alias to the
4875 // selected 'operator delete'.
4876
4877 llvm::Function *Fn = CGM.codegenCXXStructor(GD);
4878
4879 if (CGType == StructorCodegen::COMDAT) {
4880 SmallString<256> Buffer;
4881 llvm::raw_svector_ostream Out(Buffer);
4882 if (DD)
4883 getMangleContext().mangleCXXDtorComdat(DD, Out);
4884 else
4885 getMangleContext().mangleCXXCtorComdat(CD, Out);
4886 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(Out.str());
4887 Fn->setComdat(C);
4888 } else {
4889 CGM.maybeSetTrivialComdat(*MD, *Fn);
4890 }
4891}
4892
4893static llvm::FunctionCallee getBeginCatchFn(CodeGenModule &CGM) {
4894 // void *__cxa_begin_catch(void*);
4895 llvm::FunctionType *FTy = llvm::FunctionType::get(
4896 CGM.Int8PtrTy, CGM.Int8PtrTy, /*isVarArg=*/false);
4897
4898 return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
4899}
4900
4901static llvm::FunctionCallee getEndCatchFn(CodeGenModule &CGM) {
4902 // void __cxa_end_catch();
4903 llvm::FunctionType *FTy =
4904 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
4905
4906 return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
4907}
4908
4909static llvm::FunctionCallee getGetExceptionPtrFn(CodeGenModule &CGM) {
4910 // void *__cxa_get_exception_ptr(void*);
4911 llvm::FunctionType *FTy = llvm::FunctionType::get(
4912 CGM.Int8PtrTy, CGM.Int8PtrTy, /*isVarArg=*/false);
4913
4914 return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
4915}
4916
4917namespace {
4918 /// A cleanup to call __cxa_end_catch. In many cases, the caught
4919 /// exception type lets us state definitively that the thrown exception
4920 /// type does not have a destructor. In particular:
4921 /// - Catch-alls tell us nothing, so we have to conservatively
4922 /// assume that the thrown exception might have a destructor.
4923 /// - Catches by reference behave according to their base types.
4924 /// - Catches of non-record types will only trigger for exceptions
4925 /// of non-record types, which never have destructors.
4926 /// - Catches of record types can trigger for arbitrary subclasses
4927 /// of the caught type, so we have to assume the actual thrown
4928 /// exception type might have a throwing destructor, even if the
4929 /// caught type's destructor is trivial or nothrow.
4930 struct CallEndCatch final : EHScopeStack::Cleanup {
4931 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
4932 bool MightThrow;
4933
4934 void Emit(CodeGenFunction &CGF, Flags flags) override {
4935 if (!MightThrow) {
4937 return;
4938 }
4939
4941 }
4942 };
4943}
4944
4945/// Emits a call to __cxa_begin_catch and enters a cleanup to call
4946/// __cxa_end_catch. If -fassume-nothrow-exception-dtor is specified, we assume
4947/// that the exception object's dtor is nothrow, therefore the __cxa_end_catch
4948/// call can be marked as nounwind even if EndMightThrow is true.
4949///
4950/// \param EndMightThrow - true if __cxa_end_catch might throw
4951static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
4952 llvm::Value *Exn,
4953 bool EndMightThrow) {
4954 llvm::CallInst *call =
4956
4957 CGF.EHStack.pushCleanup<CallEndCatch>(
4959 EndMightThrow && !CGF.CGM.getLangOpts().AssumeNothrowExceptionDtor);
4960
4961 return call;
4962}
4963
4964/// A "special initializer" callback for initializing a catch
4965/// parameter during catch initialization.
4967 const VarDecl &CatchParam,
4968 Address ParamAddr,
4969 SourceLocation Loc) {
4970 // Load the exception from where the landing pad saved it.
4971 llvm::Value *Exn = CGF.getExceptionFromSlot();
4972
4973 CanQualType CatchType =
4974 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
4975 llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
4976
4977 // If we're catching by reference, we can just cast the object
4978 // pointer to the appropriate pointer.
4979 if (isa<ReferenceType>(CatchType)) {
4980 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
4981 bool EndCatchMightThrow = CaughtType->isRecordType();
4982
4983 // __cxa_begin_catch returns the adjusted object pointer.
4984 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
4985
4986 // We have no way to tell the personality function that we're
4987 // catching by reference, so if we're catching a pointer,
4988 // __cxa_begin_catch will actually return that pointer by value.
4989 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
4990 QualType PointeeType = PT->getPointeeType();
4991
4992 // When catching by reference, generally we should just ignore
4993 // this by-value pointer and use the exception object instead.
4994 if (!PointeeType->isRecordType()) {
4995
4996 // Exn points to the struct _Unwind_Exception header, which
4997 // we have to skip past in order to reach the exception data.
4998 unsigned HeaderSize =
5000 AdjustedExn =
5001 CGF.Builder.CreateConstGEP1_32(CGF.Int8Ty, Exn, HeaderSize);
5002
5003 // However, if we're catching a pointer-to-record type that won't
5004 // work, because the personality function might have adjusted
5005 // the pointer. There's actually no way for us to fully satisfy
5006 // the language/ABI contract here: we can't use Exn because it
5007 // might have the wrong adjustment, but we can't use the by-value
5008 // pointer because it's off by a level of abstraction.
5009 //
5010 // The current solution is to dump the adjusted pointer into an
5011 // alloca, which breaks language semantics (because changing the
5012 // pointer doesn't change the exception) but at least works.
5013 // The better solution would be to filter out non-exact matches
5014 // and rethrow them, but this is tricky because the rethrow
5015 // really needs to be catchable by other sites at this landing
5016 // pad. The best solution is to fix the personality function.
5017 } else {
5018 // Pull the pointer for the reference type off.
5019 llvm::Type *PtrTy = CGF.ConvertTypeForMem(CaughtType);
5020
5021 // Create the temporary and write the adjusted pointer into it.
5022 Address ExnPtrTmp =
5023 CGF.CreateTempAlloca(PtrTy, CGF.getPointerAlign(), "exn.byref.tmp");
5024 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
5025 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
5026
5027 // Bind the reference to the temporary.
5028 AdjustedExn = ExnPtrTmp.emitRawPointer(CGF);
5029 }
5030 }
5031
5032 llvm::Value *ExnCast =
5033 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
5034 CGF.Builder.CreateStore(ExnCast, ParamAddr);
5035 return;
5036 }
5037
5038 // Scalars and complexes.
5039 TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType);
5040 if (TEK != TEK_Aggregate) {
5041 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
5042
5043 // If the catch type is a pointer type, __cxa_begin_catch returns
5044 // the pointer by value.
5045 if (CatchType->hasPointerRepresentation()) {
5046 llvm::Value *CastExn =
5047 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
5048
5049 switch (CatchType.getQualifiers().getObjCLifetime()) {
5051 CastExn = CGF.EmitARCRetainNonBlock(CastExn);
5052 [[fallthrough]];
5053
5057 CGF.Builder.CreateStore(CastExn, ParamAddr);
5058 return;
5059
5061 CGF.EmitARCInitWeak(ParamAddr, CastExn);
5062 return;
5063 }
5064 llvm_unreachable("bad ownership qualifier!");
5065 }
5066
5067 // Otherwise, it returns a pointer into the exception object.
5068
5069 LValue srcLV = CGF.MakeNaturalAlignAddrLValue(AdjustedExn, CatchType);
5070 LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType);
5071 switch (TEK) {
5072 case TEK_Complex:
5073 CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV,
5074 /*init*/ true);
5075 return;
5076 case TEK_Scalar: {
5077 llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc);
5078 CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true);
5079 return;
5080 }
5081 case TEK_Aggregate:
5082 llvm_unreachable("evaluation kind filtered out!");
5083 }
5084 llvm_unreachable("bad evaluation kind");
5085 }
5086
5087 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
5088 auto catchRD = CatchType->getAsCXXRecordDecl();
5089 CharUnits caughtExnAlignment = CGF.CGM.getClassPointerAlignment(catchRD);
5090
5091 llvm::Type *PtrTy = CGF.DefaultPtrTy;
5092
5093 // Check for a copy expression. If we don't have a copy expression,
5094 // that means a trivial copy is okay.
5095 const Expr *copyExpr = CatchParam.getInit();
5096 if (!copyExpr) {
5097 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
5098 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
5099 LLVMCatchTy, caughtExnAlignment);
5100 LValue Dest = CGF.MakeAddrLValue(ParamAddr, CatchType);
5101 LValue Src = CGF.MakeAddrLValue(adjustedExn, CatchType);
5102 CGF.EmitAggregateCopy(Dest, Src, CatchType, AggValueSlot::DoesNotOverlap);
5103 return;
5104 }
5105
5106 // We have to call __cxa_get_exception_ptr to get the adjusted
5107 // pointer before copying.
5108 llvm::CallInst *rawAdjustedExn =
5110
5111 // Cast that to the appropriate type.
5112 Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
5113 LLVMCatchTy, caughtExnAlignment);
5114
5115 // The copy expression is defined in terms of an OpaqueValueExpr.
5116 // Find it and map it to the adjusted expression.
5118 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
5119 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
5120
5121 // Call the copy ctor in a terminate scope.
5122 CGF.EHStack.pushTerminate();
5123
5124 // Perform the copy construction.
5125 CGF.EmitAggExpr(copyExpr,
5126 AggValueSlot::forAddr(ParamAddr, Qualifiers(),
5131
5132 // Leave the terminate scope.
5133 CGF.EHStack.popTerminate();
5134
5135 // Undo the opaque value mapping.
5136 opaque.pop();
5137
5138 // Finally we can call __cxa_begin_catch.
5139 CallBeginCatch(CGF, Exn, true);
5140}
5141
5142/// Begins a catch statement by initializing the catch variable and
5143/// calling __cxa_begin_catch.
5144void ItaniumCXXABI::emitBeginCatch(CodeGenFunction &CGF,
5145 const CXXCatchStmt *S) {
5146 // We have to be very careful with the ordering of cleanups here:
5147 // C++ [except.throw]p4:
5148 // The destruction [of the exception temporary] occurs
5149 // immediately after the destruction of the object declared in
5150 // the exception-declaration in the handler.
5151 //
5152 // So the precise ordering is:
5153 // 1. Construct catch variable.
5154 // 2. __cxa_begin_catch
5155 // 3. Enter __cxa_end_catch cleanup
5156 // 4. Enter dtor cleanup
5157 //
5158 // We do this by using a slightly abnormal initialization process.
5159 // Delegation sequence:
5160 // - ExitCXXTryStmt opens a RunCleanupsScope
5161 // - EmitAutoVarAlloca creates the variable and debug info
5162 // - InitCatchParam initializes the variable from the exception
5163 // - CallBeginCatch calls __cxa_begin_catch
5164 // - CallBeginCatch enters the __cxa_end_catch cleanup
5165 // - EmitAutoVarCleanups enters the variable destructor cleanup
5166 // - EmitCXXTryStmt emits the code for the catch body
5167 // - EmitCXXTryStmt close the RunCleanupsScope
5168
5169 VarDecl *CatchParam = S->getExceptionDecl();
5170 if (!CatchParam) {
5171 llvm::Value *Exn = CGF.getExceptionFromSlot();
5172 CallBeginCatch(CGF, Exn, true);
5173 return;
5174 }
5175
5176 // Emit the local.
5177 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
5178 {
5179 ApplyAtomGroup Grp(CGF.getDebugInfo());
5180 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF),
5181 S->getBeginLoc());
5182 }
5183 CGF.EmitAutoVarCleanups(var);
5184}
5185
5186/// Get or define the following function:
5187/// void @__clang_call_terminate(i8* %exn) nounwind noreturn
5188/// This code is used only in C++.
5189static llvm::FunctionCallee getClangCallTerminateFn(CodeGenModule &CGM) {
5190 ASTContext &C = CGM.getContext();
5192 C.VoidTy, {C.getPointerType(C.CharTy)});
5193 llvm::FunctionType *fnTy = CGM.getTypes().GetFunctionType(FI);
5194 llvm::FunctionCallee fnRef = CGM.CreateRuntimeFunction(
5195 fnTy, "__clang_call_terminate", llvm::AttributeList(), /*Local=*/true);
5196 llvm::Function *fn =
5197 cast<llvm::Function>(fnRef.getCallee()->stripPointerCasts());
5198 if (fn->empty()) {
5199 CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, fn, /*IsThunk=*/false);
5201 fn->setDoesNotThrow();
5202 fn->setDoesNotReturn();
5203
5204 // What we really want is to massively penalize inlining without
5205 // forbidding it completely. The difference between that and
5206 // 'noinline' is negligible.
5207 fn->addFnAttr(llvm::Attribute::NoInline);
5208
5209 // Allow this function to be shared across translation units, but
5210 // we don't want it to turn into an exported symbol.
5211 fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
5212 fn->setVisibility(llvm::Function::HiddenVisibility);
5213 if (CGM.supportsCOMDAT())
5214 fn->setComdat(CGM.getModule().getOrInsertComdat(fn->getName()));
5215
5216 // Set up the function.
5217 llvm::BasicBlock *entry =
5218 llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn);
5219 CGBuilderTy builder(CGM, entry);
5220
5221 // Pull the exception pointer out of the parameter list.
5222 llvm::Value *exn = &*fn->arg_begin();
5223
5224 // Call __cxa_begin_catch(exn).
5225 llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn);
5226 catchCall->setDoesNotThrow();
5227 catchCall->setCallingConv(CGM.getRuntimeCC());
5228
5229 // Call std::terminate().
5230 llvm::CallInst *termCall = builder.CreateCall(CGM.getTerminateFn());
5231 termCall->setDoesNotThrow();
5232 termCall->setDoesNotReturn();
5233 termCall->setCallingConv(CGM.getRuntimeCC());
5234
5235 // std::terminate cannot return.
5236 builder.CreateUnreachable();
5237 }
5238 return fnRef;
5239}
5240
5241llvm::CallInst *
5242ItaniumCXXABI::emitTerminateForUnexpectedException(CodeGenFunction &CGF,
5243 llvm::Value *Exn) {
5244 // In C++, we want to call __cxa_begin_catch() before terminating.
5245 if (Exn) {
5246 assert(CGF.CGM.getLangOpts().CPlusPlus);
5248 }
5249 return CGF.EmitNounwindRuntimeCall(CGF.CGM.getTerminateFn());
5250}
5251
5252std::pair<llvm::Value *, const CXXRecordDecl *>
5253ItaniumCXXABI::LoadVTablePtr(CodeGenFunction &CGF, Address This,
5254 const CXXRecordDecl *RD) {
5255 return {CGF.GetVTablePtr(This, CGM.Int8PtrTy, RD), RD};
5256}
5257
5258llvm::Constant *
5259ItaniumCXXABI::getSignedVirtualMemberFunctionPointer(const CXXMethodDecl *MD) {
5260 const CXXMethodDecl *origMD =
5263 .getDecl());
5264 llvm::Constant *thunk = getOrCreateVirtualFunctionPointerThunk(origMD);
5265 QualType funcType = CGM.getContext().getMemberPointerType(
5266 MD->getType(), /*Qualifier=*/std::nullopt, MD->getParent());
5267 return CGM.getMemberFunctionPointer(thunk, funcType);
5268}
5269
5270void WebAssemblyCXXABI::emitBeginCatch(CodeGenFunction &CGF,
5271 const CXXCatchStmt *C) {
5272 if (CGF.getTarget().hasFeature("exception-handling"))
5273 CGF.EHStack.pushCleanup<CatchRetScope>(
5275 ItaniumCXXABI::emitBeginCatch(CGF, C);
5276}
5277
5278llvm::CallInst *
5279WebAssemblyCXXABI::emitTerminateForUnexpectedException(CodeGenFunction &CGF,
5280 llvm::Value *Exn) {
5281 // Itanium ABI calls __clang_call_terminate(), which __cxa_begin_catch() on
5282 // the violating exception to mark it handled, but it is currently hard to do
5283 // with wasm EH instruction structure with catch/catch_all, we just call
5284 // std::terminate and ignore the violating exception as in CGCXXABI in Wasm EH
5285 // and call __clang_call_terminate only in Emscripten EH.
5286 // TODO Consider code transformation that makes calling __clang_call_terminate
5287 // in Wasm EH possible.
5288 if (Exn && !EHPersonality::get(CGF).isWasmPersonality()) {
5289 assert(CGF.CGM.getLangOpts().CPlusPlus);
5291 }
5293}
5294
5295/// Register a global destructor as best as we know how.
5296void XLCXXABI::registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
5297 llvm::FunctionCallee Dtor,
5298 llvm::Constant *Addr) {
5299 if (D.getTLSKind() != VarDecl::TLS_None) {
5300 llvm::PointerType *PtrTy = CGF.DefaultPtrTy;
5301
5302 // extern "C" int __pt_atexit_np(int flags, int(*)(int,...), ...);
5303 llvm::FunctionType *AtExitTy =
5304 llvm::FunctionType::get(CGM.IntTy, {CGM.IntTy, PtrTy}, true);
5305
5306 // Fetch the actual function.
5307 llvm::FunctionCallee AtExit =
5308 CGM.CreateRuntimeFunction(AtExitTy, "__pt_atexit_np");
5309
5310 // Create __dtor function for the var decl.
5311 llvm::Function *DtorStub = CGF.createTLSAtExitStub(D, Dtor, Addr, AtExit);
5312
5313 // Register above __dtor with atexit().
5314 // First param is flags and must be 0, second param is function ptr
5315 llvm::Value *NV = llvm::Constant::getNullValue(CGM.IntTy);
5316 CGF.EmitNounwindRuntimeCall(AtExit, {NV, DtorStub});
5317
5318 // Cannot unregister TLS __dtor so done
5319 return;
5320 }
5321
5322 // Create __dtor function for the var decl.
5323 llvm::Function *DtorStub =
5325
5326 // Register above __dtor with atexit().
5327 CGF.registerGlobalDtorWithAtExit(DtorStub);
5328
5329 // Emit __finalize function to unregister __dtor and (as appropriate) call
5330 // __dtor.
5331 emitCXXStermFinalizer(D, DtorStub, Addr);
5332}
5333
5334void XLCXXABI::emitCXXStermFinalizer(const VarDecl &D, llvm::Function *dtorStub,
5335 llvm::Constant *addr) {
5336 llvm::FunctionType *FTy = llvm::FunctionType::get(CGM.VoidTy, false);
5337 SmallString<256> FnName;
5338 {
5339 llvm::raw_svector_ostream Out(FnName);
5340 getMangleContext().mangleDynamicStermFinalizer(&D, Out);
5341 }
5342
5343 // Create the finalization action associated with a variable.
5344 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
5345 llvm::Function *StermFinalizer = CGM.CreateGlobalInitOrCleanUpFunction(
5346 FTy, FnName.str(), FI, D.getLocation());
5347
5348 CodeGenFunction CGF(CGM);
5349
5350 CGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, StermFinalizer, FI,
5351 FunctionArgList(), D.getLocation(),
5352 D.getInit()->getExprLoc());
5353
5354 // The unatexit subroutine unregisters __dtor functions that were previously
5355 // registered by the atexit subroutine. If the referenced function is found,
5356 // the unatexit returns a value of 0, meaning that the cleanup is still
5357 // pending (and we should call the __dtor function).
5358 llvm::Value *V = CGF.unregisterGlobalDtorWithUnAtExit(dtorStub);
5359
5360 llvm::Value *NeedsDestruct = CGF.Builder.CreateIsNull(V, "needs_destruct");
5361
5362 llvm::BasicBlock *DestructCallBlock = CGF.createBasicBlock("destruct.call");
5363 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("destruct.end");
5364
5365 // Check if unatexit returns a value of 0. If it does, jump to
5366 // DestructCallBlock, otherwise jump to EndBlock directly.
5367 CGF.Builder.CreateCondBr(NeedsDestruct, DestructCallBlock, EndBlock);
5368
5369 CGF.EmitBlock(DestructCallBlock);
5370
5371 // Emit the call to dtorStub.
5372 llvm::CallInst *CI = CGF.Builder.CreateCall(dtorStub);
5373
5374 // Make sure the call and the callee agree on calling convention.
5375 CI->setCallingConv(dtorStub->getCallingConv());
5376
5377 CGF.EmitBlock(EndBlock);
5378
5379 CGF.FinishFunction();
5380
5381 if (auto *IPA = D.getAttr<InitPriorityAttr>()) {
5382 CGM.AddCXXPrioritizedStermFinalizerEntry(StermFinalizer,
5383 IPA->getPriority());
5385 getContext().GetGVALinkageForVariable(&D) == GVA_DiscardableODR) {
5386 // According to C++ [basic.start.init]p2, class template static data
5387 // members (i.e., implicitly or explicitly instantiated specializations)
5388 // have unordered initialization. As a consequence, we can put them into
5389 // their own llvm.global_dtors entry.
5390 CGM.AddCXXStermFinalizerToGlobalDtor(StermFinalizer, 65535);
5391 } else {
5392 CGM.AddCXXStermFinalizerEntry(StermFinalizer);
5393 }
5394}
#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:1084
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:223
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:802
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:921
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:3228
Kind getKind() const
Definition TypeBase.h:3276
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:2145
bool isVirtual() const
Definition DeclCXX.h:2200
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2284
bool isInstance() const
Definition DeclCXX.h:2172
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2254
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:1377
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:1226
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:3726
Expr * getSubExpr()
Definition Expr.h:3732
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:5270
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:5297
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:4040
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:4475
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:3930
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:4188
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:159
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:5453
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:4527
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:283
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:5371
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:5598
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:3717
CXXRecordDecl * getMostRecentCXXRecordDecl() const
Note: this can trigger extra deserialization when external AST sources are used.
Definition Type.cpp:5642
QualType getPointeeType() const
Definition TypeBase.h:3735
bool isMemberFunctionPointer() const
Returns true if the member type (i.e.
Definition TypeBase.h:3739
bool isMemberDataPointer() const
Returns true if the member type (i.e.
Definition TypeBase.h:3745
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:5173
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3392
QualType getPointeeType() const
Definition TypeBase.h:3402
A (possibly-)qualified type.
Definition TypeBase.h:937
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8487
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:8632
QualType getCanonicalType() const
Definition TypeBase.h:8499
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8541
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:9344
bool isReferenceType() const
Definition TypeBase.h:8708
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:3129
bool isMemberFunctionPointerType() const
Definition TypeBase.h:8769
Linkage getLinkage() const
Determine the linkage of this type.
Definition Type.cpp:5026
TypeClass getTypeClass() const
Definition TypeBase.h:2445
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9277
bool isRecordType() const
Definition TypeBase.h:8811
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:2796
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:2739
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:3167
@ 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:5981
@ 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:5456
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