clang 24.0.0git
CIRGenItaniumCXXABI.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
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 "CIRGenCXXABI.h"
21#include "CIRGenFunction.h"
22
23#include "clang/AST/ExprCXX.h"
25#include "clang/AST/Mangle.h"
26#include "clang/AST/TypeBase.h"
30#include "llvm/ADT/SmallString.h"
31#include "llvm/Support/ErrorHandling.h"
32#include "llvm/Support/raw_ostream.h"
33
34using namespace clang;
35using namespace clang::CIRGen;
36
37namespace {
38
39class CIRGenItaniumCXXABI : public CIRGenCXXABI {
40protected:
41 /// All the vtables which have been defined.
42 llvm::DenseMap<const CXXRecordDecl *, cir::GlobalOp> vtables;
43
44public:
45 CIRGenItaniumCXXABI(CIRGenModule &cgm) : CIRGenCXXABI(cgm) {
48 }
49
50 AddedStructorArgs getImplicitConstructorArgs(CIRGenFunction &cgf,
51 const CXXConstructorDecl *d,
53 bool forVirtualBase,
54 bool delegating) override;
55
56 bool needsVTTParameter(clang::GlobalDecl gd) override;
57
58 AddedStructorArgCounts
59 buildStructorSignature(GlobalDecl gd,
60 llvm::SmallVectorImpl<CanQualType> &argTys) override;
61
62 void emitInstanceFunctionProlog(SourceLocation loc,
63 CIRGenFunction &cgf) override;
64
65 void addImplicitStructorParams(CIRGenFunction &cgf, QualType &resTy,
66 FunctionArgList &params) override;
67 mlir::Value getCXXDestructorImplicitParam(CIRGenFunction &cgf,
68 const CXXDestructorDecl *dd,
70 bool forVirtualBase,
71 bool delegating) override;
72 void emitCXXConstructors(const clang::CXXConstructorDecl *d) override;
73 void emitCXXDestructors(const clang::CXXDestructorDecl *d) override;
74 void emitCXXStructor(clang::GlobalDecl gd) override;
75
76 void emitDestructorCall(CIRGenFunction &cgf, const CXXDestructorDecl *dd,
77 CXXDtorType type, bool forVirtualBase,
78 bool delegating, Address thisAddr,
79 QualType thisTy) override;
80 void registerGlobalDtor(const VarDecl *vd, cir::FuncOp dtor,
81 mlir::Value addr) override;
82 void emitVirtualObjectDelete(CIRGenFunction &cgf, const CXXDeleteExpr *de,
83 Address ptr, QualType elementType,
84 const CXXDestructorDecl *dtor) override;
85
86 void emitRethrow(CIRGenFunction &cgf, bool isNoReturn) override;
87 void emitThrow(CIRGenFunction &cgf, const CXXThrowExpr *e) override;
88
89 bool useThunkForDtorVariant(const CXXDestructorDecl *dtor,
90 CXXDtorType dt) const override {
91 // Itanium does not emit any destructor variant as an inline thunk.
92 // Delegating may occur as an optimization, but all variants are either
93 // emitted with external linkage or as linkonce if they are inline and used.
94 return false;
95 }
96
97 bool isVirtualOffsetNeededForVTableField(CIRGenFunction &cgf,
98 CIRGenFunction::VPtr vptr) override;
99
100 cir::GlobalOp getAddrOfVTable(const CXXRecordDecl *rd,
101 CharUnits vptrOffset) override;
102 CIRGenCallee getVirtualFunctionPointer(CIRGenFunction &cgf,
103 clang::GlobalDecl gd, Address thisAddr,
104 mlir::Type ty,
105 SourceLocation loc) override;
106 mlir::Value emitVirtualDestructorCall(CIRGenFunction &cgf,
107 const CXXDestructorDecl *dtor,
108 CXXDtorType dtorType, Address thisAddr,
109 DeleteOrMemberCallExpr e) override;
110
111 bool canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const override;
112 bool canSpeculativelyEmitVTableAsBaseClass(const CXXRecordDecl *RD) const;
113
114 mlir::Value getVTableAddressPoint(BaseSubobject base,
115 const CXXRecordDecl *vtableClass) override;
116 cir::GlobalViewAttr
117 getVTableAddressPointAttr(BaseSubobject base,
118 const CXXRecordDecl *vtableClass) override;
119 mlir::Value getVTableAddressPointInStructorWithVTT(
120 CIRGenFunction &cgf, const CXXRecordDecl *vtableClass, BaseSubobject base,
121 const CXXRecordDecl *nearestVBase);
122
123 mlir::Value getVTableAddressPointInStructor(
124 CIRGenFunction &cgf, const clang::CXXRecordDecl *vtableClass,
125 clang::BaseSubobject base,
126 const clang::CXXRecordDecl *nearestVBase) override;
127 void emitVTableDefinitions(CIRGenVTables &cgvt,
128 const CXXRecordDecl *rd) override;
129 void emitVirtualInheritanceTables(const CXXRecordDecl *rd) override;
130
131 void setThunkLinkage(cir::FuncOp thunk, bool forVTable, GlobalDecl gd,
132 bool returnAdjustment) override {
133 if (forVTable && !thunk.hasLocalLinkage())
134 thunk.setLinkage(cir::GlobalLinkageKind::AvailableExternallyLinkage);
135 const auto *nd = cast<NamedDecl>(gd.getDecl());
136 cgm.setGVProperties(thunk, nd);
137 }
138
139 bool exportThunk() override { return true; }
140
141 mlir::Value performThisAdjustment(CIRGenFunction &cgf, Address thisAddr,
142 const CXXRecordDecl *unadjustedClass,
143 const ThunkInfo &ti) override;
144
145 mlir::Value performReturnAdjustment(CIRGenFunction &cgf, Address ret,
146 const CXXRecordDecl *unadjustedClass,
147 const ReturnAdjustment &ra) override;
148
149 bool shouldTypeidBeNullChecked(QualType srcTy) override;
150 mlir::Value emitTypeid(CIRGenFunction &cgf, QualType SrcRecordTy,
151 Address thisPtr, mlir::Type StdTypeInfoPtrTy) override;
152 void emitBadTypeidCall(CIRGenFunction &cgf, mlir::Location loc) override;
153
154 mlir::Attribute getAddrOfRTTIDescriptor(mlir::Location loc,
155 QualType ty) override;
156
157 StringRef getPureVirtualCallName() override { return "__cxa_pure_virtual"; }
158 StringRef getDeletedVirtualCallName() override {
159 return "__cxa_deleted_virtual";
160 }
161
162 CatchTypeInfo
163 getAddrOfCXXCatchHandlerType(mlir::Location loc, QualType ty,
164 QualType catchHandlerType) override {
165 auto rtti = dyn_cast<cir::GlobalViewAttr>(getAddrOfRTTIDescriptor(loc, ty));
166 assert(rtti && "expected GlobalViewAttr");
167 return CatchTypeInfo{rtti, 0};
168 }
169
170 bool doStructorsInitializeVPtrs(const CXXRecordDecl *vtableClass) override {
171 return true;
172 }
173
174 size_t getSrcArgforCopyCtor(const CXXConstructorDecl *,
175 FunctionArgList &args) const override {
176 assert(!args.empty() && "expected the arglist to not be empty!");
177 return args.size() - 1;
178 }
179
180 void emitBadCastCall(CIRGenFunction &cgf, mlir::Location loc) override;
181
182 mlir::Value
183 getVirtualBaseClassOffset(mlir::Location loc, CIRGenFunction &cgf,
184 Address thisAddr, const CXXRecordDecl *classDecl,
185 const CXXRecordDecl *baseClassDecl) override;
186
187 // The traditional clang CodeGen emits calls to `__dynamic_cast` directly into
188 // LLVM in the `emitDynamicCastCall` function. In CIR, `dynamic_cast`
189 // expressions are lowered to `cir.dyn_cast` ops instead of calls to runtime
190 // functions. So during CIRGen we don't need the `emitDynamicCastCall`
191 // function that clang CodeGen has.
192 mlir::Value emitDynamicCast(CIRGenFunction &cgf, mlir::Location loc,
193 QualType srcRecordTy, QualType destRecordTy,
194 cir::PointerType destCIRTy, bool isRefCast,
195 Address src) override;
196
197 cir::MethodAttr buildVirtualMethodAttr(cir::MethodType methodTy,
198 const CXXMethodDecl *md) override;
199
200 Address initializeArrayCookie(CIRGenFunction &cgf, Address newPtr,
201 mlir::Value numElements, const CXXNewExpr *e,
202 QualType elementType) override;
203
204 bool isZeroInitializable(const MemberPointerType *MPT) override;
205
206protected:
207 CharUnits getArrayCookieSizeImpl(QualType elementType) override;
208
209 /**************************** RTTI Uniqueness ******************************/
210 /// Returns true if the ABI requires RTTI type_info objects to be unique
211 /// across a program.
212 virtual bool shouldRTTIBeUnique() const { return true; }
213
214public:
215 /// What sort of unique-RTTI behavior should we use?
216 enum RTTIUniquenessKind {
217 /// We are guaranteeing, or need to guarantee, that the RTTI string
218 /// is unique.
219 RUK_Unique,
220
221 /// We are not guaranteeing uniqueness for the RTTI string, so we
222 /// can demote to hidden visibility but must use string comparisons.
223 RUK_NonUniqueHidden,
224
225 /// We are not guaranteeing uniqueness for the RTTI string, so we
226 /// have to use string comparisons, but we also have to emit it with
227 /// non-hidden visibility.
228 RUK_NonUniqueVisible
229 };
230
231 /// Return the required visibility status for the given type and linkage in
232 /// the current ABI.
233 RTTIUniquenessKind
234 classifyRTTIUniqueness(QualType canTy, cir::GlobalLinkageKind linkage) const;
235
236private:
237 bool hasAnyUnusedVirtualInlineFunction(const CXXRecordDecl *rd) const;
238 bool isVTableHidden(const CXXRecordDecl *rd) const;
239};
240
241} // namespace
242
243void CIRGenItaniumCXXABI::emitInstanceFunctionProlog(SourceLocation loc,
244 CIRGenFunction &cgf) {
245 // Naked functions have no prolog.
246 if (cgf.curFuncDecl && cgf.curFuncDecl->hasAttr<NakedAttr>()) {
248 "emitInstanceFunctionProlog: Naked");
249 }
250
251 /// Initialize the 'this' slot. In the Itanium C++ ABI, no prologue
252 /// adjustments are required, because they are all handled by thunks.
253 setCXXABIThisValue(cgf, loadIncomingCXXThis(cgf));
254
255 /// Initialize the 'vtt' slot if needed.
256 if (getStructorImplicitParamDecl(cgf)) {
257 cir::LoadOp val = cgf.getBuilder().createLoad(
258 cgf.getLoc(loc),
259 cgf.getAddrOfLocalVar(getStructorImplicitParamDecl(cgf)));
260 setStructorImplicitParamValue(cgf, val);
261 }
262
263 /// If this is a function that the ABI specifies returns 'this', initialize
264 /// the return slot to this' at the start of the function.
265 ///
266 /// Unlike the setting of return types, this is done within the ABI
267 /// implementation instead of by clients of CIRGenCXXBI because:
268 /// 1) getThisValue is currently protected
269 /// 2) in theory, an ABI could implement 'this' returns some other way;
270 /// HasThisReturn only specifies a contract, not the implementation
271 if (hasThisReturn(cgf.curGD))
272 cgf.getBuilder().createStore(cgf.getLoc(loc), cgf.cxxabiThisValue,
273 cgf.returnValue);
274}
275
276CIRGenCXXABI::AddedStructorArgCounts
277CIRGenItaniumCXXABI::buildStructorSignature(
278 GlobalDecl gd, llvm::SmallVectorImpl<CanQualType> &argTys) {
279 clang::ASTContext &astContext = cgm.getASTContext();
280
281 // All parameters are already in place except VTT, which goes after 'this'.
282 // These are clang types, so we don't need to worry about sret yet.
283
284 // Check if we need to add a VTT parameter (which has type global void **).
286 : gd.getDtorType() == Dtor_Base) &&
287 cast<CXXMethodDecl>(gd.getDecl())->getParent()->getNumVBases() != 0) {
288 LangAS as = cgm.getGlobalVarAddressSpace(nullptr);
289 QualType q = astContext.getAddrSpaceQualType(astContext.VoidPtrTy, as);
290 argTys.insert(argTys.begin() + 1,
292 return AddedStructorArgCounts::withPrefix(1);
293 }
294
295 return AddedStructorArgCounts{};
296}
297
298// Find out how to cirgen the complete destructor and constructor
299namespace {
300enum class StructorCIRGen { Emit, RAUW, Alias, COMDAT };
301}
302
303static StructorCIRGen getCIRGenToUse(CIRGenModule &cgm,
304 const CXXMethodDecl *md) {
305 if (!cgm.getCodeGenOpts().CXXCtorDtorAliases)
306 return StructorCIRGen::Emit;
307
308 // The complete and base structors are not equivalent if there are any virtual
309 // bases, so emit separate functions.
310 if (md->getParent()->getNumVBases())
311 return StructorCIRGen::Emit;
312
313 GlobalDecl aliasDecl;
314 if (const auto *dd = dyn_cast<CXXDestructorDecl>(md)) {
315 aliasDecl = GlobalDecl(dd, Dtor_Complete);
316 } else {
317 const auto *cd = cast<CXXConstructorDecl>(md);
318 aliasDecl = GlobalDecl(cd, Ctor_Complete);
319 }
320
321 cir::GlobalLinkageKind linkage = cgm.getFunctionLinkage(aliasDecl);
322
323 if (cir::isDiscardableIfUnused(linkage))
324 return StructorCIRGen::RAUW;
325
326 // FIXME: Should we allow available_externally aliases?
327 if (!cir::isValidLinkage(linkage))
328 return StructorCIRGen::RAUW;
329
330 if (cir::isWeakForLinker(linkage)) {
331 // Only ELF and wasm support COMDATs with arbitrary names (C5/D5).
332 if (cgm.getTarget().getTriple().isOSBinFormatELF() ||
333 cgm.getTarget().getTriple().isOSBinFormatWasm())
334 return StructorCIRGen::COMDAT;
335 return StructorCIRGen::Emit;
336 }
337
338 return StructorCIRGen::Alias;
339}
340
342 GlobalDecl aliasDecl,
343 GlobalDecl targetDecl) {
344 cir::GlobalLinkageKind linkage = cgm.getFunctionLinkage(aliasDecl);
345
346 // Does this function alias already exists?
347 StringRef mangledName = cgm.getMangledName(aliasDecl);
348 auto globalValue = dyn_cast_or_null<cir::CIRGlobalValueInterface>(
349 cgm.getGlobalValue(mangledName));
350 if (globalValue && !globalValue.isDeclaration())
351 return;
352
353 auto entry = cast_or_null<cir::FuncOp>(cgm.getGlobalValue(mangledName));
354
355 // Retrieve aliasee info.
356 auto aliasee = cast<cir::FuncOp>(cgm.getAddrOfGlobal(targetDecl));
357
358 // Populate actual alias.
359 cir::FuncOp alias =
360 cgm.emitAliasForGlobal(mangledName, entry, aliasDecl, aliasee, linkage);
361
362 // Alias constructors and destructors are always unnamed_addr.
363 alias.setUnnamedAddr(true);
364}
365
366void CIRGenItaniumCXXABI::emitCXXStructor(GlobalDecl gd) {
367 auto *md = cast<CXXMethodDecl>(gd.getDecl());
368 StructorCIRGen cirGenType = getCIRGenToUse(cgm, md);
369 const auto *cd = dyn_cast<CXXConstructorDecl>(md);
370 const CXXDestructorDecl *dd = cd ? nullptr : cast<CXXDestructorDecl>(md);
371
372 if (cd ? gd.getCtorType() == Ctor_Complete
373 : gd.getDtorType() == Dtor_Complete) {
374 GlobalDecl baseDecl =
376 ;
377
378 if (cirGenType == StructorCIRGen::Alias ||
379 cirGenType == StructorCIRGen::COMDAT) {
380 emitConstructorDestructorAlias(cgm, gd, baseDecl);
381 return;
382 }
383
384 if (cirGenType == StructorCIRGen::RAUW) {
385 StringRef mangledName = cgm.getMangledName(gd);
386 mlir::Operation *aliasee = cgm.getAddrOfGlobal(baseDecl);
387 cgm.addReplacement(mangledName, aliasee);
388 return;
389 }
390 }
391
392 auto fn = cgm.codegenCXXStructor(gd);
393
394 if (cirGenType == StructorCIRGen::COMDAT) {
395 llvm::SmallString<256> comdatKey;
396 llvm::raw_svector_ostream out(comdatKey);
397 ItaniumMangleContext &mangler =
399 if (dd)
400 mangler.mangleCXXDtorComdat(dd, out);
401 else
402 mangler.mangleCXXCtorComdat(cd, out);
403 fn.setComdat(llvm::StringRef(comdatKey));
404 } else {
405 cgm.maybeSetTrivialComdat(*md, fn);
406 }
407}
408
409void CIRGenItaniumCXXABI::addImplicitStructorParams(CIRGenFunction &cgf,
410 QualType &resTy,
411 FunctionArgList &params) {
412 const auto *md = cast<CXXMethodDecl>(cgf.curGD.getDecl());
414
415 // Check if we need a VTT parameter as well.
416 if (needsVTTParameter(cgf.curGD)) {
417 ASTContext &astContext = cgm.getASTContext();
418
419 // FIXME: avoid the fake decl
420 LangAS as = cgm.getGlobalVarAddressSpace(nullptr);
421 QualType q = astContext.getAddrSpaceQualType(astContext.VoidPtrTy, as);
422 QualType t = astContext.getPointerType(q);
423 auto *vttDecl = ImplicitParamDecl::Create(
424 astContext, /*DC=*/nullptr, md->getLocation(),
425 &astContext.Idents.get("vtt"), t, ImplicitParamKind::CXXVTT);
426 params.insert(params.begin() + 1, vttDecl);
427 getStructorImplicitParamDecl(cgf) = vttDecl;
428 }
429}
430
431void CIRGenItaniumCXXABI::emitCXXConstructors(const CXXConstructorDecl *d) {
432 // Just make sure we're in sync with TargetCXXABI.
434
435 // The constructor used for constructing this as a base class;
436 // ignores virtual bases.
437 cgm.emitGlobal(GlobalDecl(d, Ctor_Base));
438
439 // The constructor used for constructing this as a complete class;
440 // constructs the virtual bases, then calls the base constructor.
441 if (!d->getParent()->isAbstract()) {
442 // We don't need to emit the complete ctro if the class is abstract.
443 cgm.emitGlobal(GlobalDecl(d, Ctor_Complete));
444 }
445}
446
447void CIRGenItaniumCXXABI::emitCXXDestructors(const CXXDestructorDecl *d) {
448 // The destructor used for destructing this as a base class; ignores
449 // virtual bases.
450 cgm.emitGlobal(GlobalDecl(d, Dtor_Base));
451
452 // The destructor used for destructing this as a most-derived class;
453 // call the base destructor and then destructs any virtual bases.
454 cgm.emitGlobal(GlobalDecl(d, Dtor_Complete));
455
456 // The destructor in a virtual table is always a 'deleting'
457 // destructor, which calls the complete destructor and then uses the
458 // appropriate operator delete.
459 if (d->isVirtual())
460 cgm.emitGlobal(GlobalDecl(d, Dtor_Deleting));
461}
462
463CIRGenCXXABI::AddedStructorArgs CIRGenItaniumCXXABI::getImplicitConstructorArgs(
464 CIRGenFunction &cgf, const CXXConstructorDecl *d, CXXCtorType type,
465 bool forVirtualBase, bool delegating) {
466 if (!needsVTTParameter(GlobalDecl(d, type)))
467 return AddedStructorArgs{};
468
469 // Insert the implicit 'vtt' argument as the second argument. Make sure to
470 // correctly reflect its address space, which can differ from generic on
471 // some targets.
472 mlir::Value vtt =
473 cgf.getVTTParameter(GlobalDecl(d, type), forVirtualBase, delegating);
474 ASTContext &astContext = cgm.getASTContext();
475 LangAS as = cgm.getGlobalVarAddressSpace(nullptr);
476 QualType q = astContext.getAddrSpaceQualType(astContext.VoidPtrTy, as);
477 QualType vttTy = astContext.getPointerType(q);
478 return AddedStructorArgs::withPrefix({{vtt, vttTy}});
479}
480
481/// Return whether the given global decl needs a VTT (virtual table table)
482/// parameter, which it does if it's a base constructor or destructor with
483/// virtual bases.
484bool CIRGenItaniumCXXABI::needsVTTParameter(GlobalDecl gd) {
485 auto *md = cast<CXXMethodDecl>(gd.getDecl());
486
487 // We don't have any virtual bases, just return early.
488 if (!md->getParent()->getNumVBases())
489 return false;
490
491 // Check if we have a base constructor.
493 return true;
494
495 // Check if we have a base destructor.
497 return true;
498
499 return false;
500}
501
502void CIRGenItaniumCXXABI::emitVTableDefinitions(CIRGenVTables &cgvt,
503 const CXXRecordDecl *rd) {
504 cir::GlobalOp vtable = getAddrOfVTable(rd, CharUnits());
505 if (vtable.hasInitializer())
506 return;
507
508 ItaniumVTableContext &vtContext = cgm.getItaniumVTableContext();
509 const VTableLayout &vtLayout = vtContext.getVTableLayout(rd);
510 cir::GlobalLinkageKind linkage = cgm.getVTableLinkage(rd);
511 mlir::Attribute rtti =
514
515 // Classic codegen uses ConstantInitBuilder here, which is a very general
516 // and feature-rich class to generate initializers for global values.
517 // For now, this is using a simpler approach to create the initializer in CIR.
518 cgvt.createVTableInitializer(vtable, vtLayout, rtti,
519 cir::isLocalLinkage(linkage));
520
521 // Set the correct linkage. The global was created as a declaration, which
522 // MLIR requires to be private, so the visibility has to follow the linkage of
523 // the definition.
524 vtable.setLinkage(linkage);
525 mlir::SymbolTable::setSymbolVisibility(
526 vtable, CIRGenModule::getMLIRVisibility(vtable));
527
528 if (cgm.mayVTableBeDuplicated(linkage))
529 vtable.setUnnamedAddr(true);
530
531 if (cgm.supportsCOMDAT() && cir::isWeakForLinker(linkage))
532 vtable.setSelfComdat();
533
534 // Set the right visibility.
535 cgm.setGVProperties(vtable, rd);
536
537 // If this is the magic class __cxxabiv1::__fundamental_type_info,
538 // we will emit the typeinfo for the fundamental types. This is the
539 // same behaviour as GCC.
540 const DeclContext *DC = rd->getDeclContext();
541 if (rd->getIdentifier() &&
542 rd->getIdentifier()->isStr("__fundamental_type_info") &&
543 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
544 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
545 DC->getParent()->isTranslationUnit()) {
546 cgm.errorNYI(rd->getSourceRange(),
547 "emitVTableDefinitions: __fundamental_type_info");
548 }
549
550 [[maybe_unused]] auto vtableAsGlobalValue =
551 dyn_cast<cir::CIRGlobalValueInterface>(*vtable);
552 assert(vtableAsGlobalValue && "VTable must support CIRGlobalValueInterface");
553 // Always emit type metadata on non-available_externally definitions, and on
554 // available_externally definitions if we are performing whole program
555 // devirtualization. For WPD we need the type metadata on all vtable
556 // definitions to ensure we associate derived classes with base classes
557 // defined in headers but with a strong definition only in a shared
558 // library.
560 if (cgm.getCodeGenOpts().WholeProgramVTables) {
561 cgm.errorNYI(rd->getSourceRange(),
562 "emitVTableDefinitions: WholeProgramVTables");
563 }
564
566 if (cgm.getLangOpts().RelativeCXXABIVTables) {
567 cgm.errorNYI(rd->getSourceRange(), "vtableRelativeLayout");
568 }
569}
570
571mlir::Value CIRGenItaniumCXXABI::emitVirtualDestructorCall(
572 CIRGenFunction &cgf, const CXXDestructorDecl *dtor, CXXDtorType dtorType,
573 Address thisAddr, DeleteOrMemberCallExpr expr) {
574 auto *callExpr = dyn_cast<const CXXMemberCallExpr *>(expr);
575 auto *delExpr = dyn_cast<const CXXDeleteExpr *>(expr);
576 assert((callExpr != nullptr) ^ (delExpr != nullptr));
577 assert(callExpr == nullptr || callExpr->arg_begin() == callExpr->arg_end());
578 assert(dtorType == Dtor_Deleting || dtorType == Dtor_Complete);
579
580 GlobalDecl globalDecl(dtor, dtorType);
581 const CIRGenFunctionInfo *fnInfo =
582 &cgm.getTypes().arrangeCXXStructorDeclaration(globalDecl);
583 const cir::FuncType &fnTy = cgm.getTypes().getFunctionType(*fnInfo);
584 auto callee = CIRGenCallee::forVirtual(callExpr, globalDecl, thisAddr, fnTy);
585
586 QualType thisTy =
587 callExpr ? callExpr->getObjectType() : delExpr->getDestroyedType();
588
589 cgf.emitCXXDestructorCall(globalDecl, callee, thisAddr.emitRawPointer(),
590 thisTy, nullptr, QualType(), nullptr);
591 return nullptr;
592}
593
594void CIRGenItaniumCXXABI::emitVirtualInheritanceTables(
595 const CXXRecordDecl *rd) {
596 CIRGenVTables &vtables = cgm.getVTables();
597 cir::GlobalOp vtt = vtables.getAddrOfVTT(rd);
598 vtables.emitVTTDefinition(vtt, cgm.getVTableLinkage(rd), rd);
599}
600
601namespace {
602class CIRGenItaniumRTTIBuilder {
603 CIRGenModule &cgm; // Per-module state.
604 const CIRGenItaniumCXXABI &cxxABI; // Per-module state.
605
606 /// The fields of the RTTI descriptor currently being built.
607 SmallVector<mlir::Attribute, 16> fields;
608
609 // Returns the mangled type name of the given type.
610 cir::GlobalOp getAddrOfTypeName(mlir::Location loc, QualType ty,
611 cir::GlobalLinkageKind linkage);
612
613 /// descriptor of the given type.
614 mlir::Attribute getAddrOfExternalRTTIDescriptor(mlir::Location loc,
615 QualType ty);
616
617 /// Build the vtable pointer for the given type.
618 void buildVTablePointer(mlir::Location loc, const Type *ty);
619
620 /// Build an abi::__si_class_type_info, used for single inheritance, according
621 /// to the Itanium C++ ABI, 2.9.5p6b.
622 void buildSIClassTypeInfo(mlir::Location loc, const CXXRecordDecl *rd);
623
624 /// Build an abi::__vmi_class_type_info, used for
625 /// classes with bases that do not satisfy the abi::__si_class_type_info
626 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
627 void buildVMIClassTypeInfo(mlir::Location loc, const CXXRecordDecl *rd);
628
629 /// Build an abi::__pointer_type_info, used for pointer types, according
630 /// to the Itanium C++ ABI, 2.9.4p7.
631 void buildPointerTypeInfo(mlir::Location loc, QualType ty);
632
633 /// Build an abi::__pointer_to_member_type_info, used for pointer to member
634 /// types, according to the Itanium C++ ABI, 2.9.4p9.
635
636 /// Build an abi::__pointer_to_member_type_info
637 /// struct, used for member pointer types.
638 void buildPointerToMemberTypeInfo(mlir::Location loc,
639 const MemberPointerType *ty);
640
641public:
642 CIRGenItaniumRTTIBuilder(const CIRGenItaniumCXXABI &abi, CIRGenModule &cgm)
643 : cgm(cgm), cxxABI(abi) {}
644
645 /// Build the RTTI type info struct for the given type, or
646 /// link to an existing RTTI descriptor if one already exists.
647 mlir::Attribute buildTypeInfo(mlir::Location loc, QualType ty);
648
649 /// Build the RTTI type info struct for the given type.
650 mlir::Attribute buildTypeInfo(mlir::Location loc, QualType ty,
651 cir::GlobalLinkageKind linkage,
652 cir::VisibilityKind globalVisibility);
653};
654
655/// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
656/// the given type exists somewhere else, and that we should not emit the type
657/// information in this translation unit. Assumes that it is not a
658/// standard-library type.
659static bool shouldUseExternalRttiDescriptor(CIRGenModule &cgm, QualType ty) {
660 ASTContext &context = cgm.getASTContext();
661
662 // If RTTI is disabled, assume it might be disabled in the
663 // translation unit that defines any potential key function, too.
664 if (!context.getLangOpts().RTTI)
665 return false;
666
667 if (const auto *recordTy = dyn_cast<RecordType>(ty)) {
668 const auto *rd =
669 cast<CXXRecordDecl>(recordTy->getDecl())->getDefinitionOrSelf();
670 if (!rd->hasDefinition())
671 return false;
672
673 if (!rd->isDynamicClass())
674 return false;
675
676 // FIXME: this may need to be reconsidered if the key function
677 // changes.
678 // N.B. We must always emit the RTTI data ourselves if there exists a key
679 // function.
680 bool isDLLImport = rd->hasAttr<DLLImportAttr>();
681
682 // Don't import the RTTI but emit it locally.
683 if (cgm.getTriple().isOSCygMing())
684 return false;
685
686 if (cgm.getVTables().isVTableExternal(rd)) {
688 return true;
689
690 return !isDLLImport || cgm.getTriple().isWindowsItaniumEnvironment();
691 }
692
693 if (isDLLImport)
694 return true;
695 }
696
697 return false;
698}
699
700const char *vTableClassNameForType(const CIRGenModule &cgm, const Type *ty) {
701 // abi::__class_type_info.
702 static const char *const classTypeInfo =
703 "_ZTVN10__cxxabiv117__class_type_infoE";
704 // abi::__si_class_type_info.
705 static const char *const siClassTypeInfo =
706 "_ZTVN10__cxxabiv120__si_class_type_infoE";
707 // abi::__vmi_class_type_info.
708 static const char *const vmiClassTypeInfo =
709 "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
710
711 switch (ty->getTypeClass()) {
712#define TYPE(Class, Base)
713#define ABSTRACT_TYPE(Class, Base)
714#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
715#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
716#define DEPENDENT_TYPE(Class, Base) case Type::Class:
717#include "clang/AST/TypeNodes.inc"
718 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
719
720 case Type::LValueReference:
721 case Type::RValueReference:
722 llvm_unreachable("References shouldn't get here");
723
724 case Type::Auto:
725 case Type::DeducedTemplateSpecialization:
726 llvm_unreachable("Undeduced type shouldn't get here");
727
728 case Type::Pipe:
729 llvm_unreachable("Pipe types shouldn't get here");
730
731 case Type::ArrayParameter:
732 llvm_unreachable("Array Parameter types should not get here.");
733
734 case Type::Builtin:
735 case Type::BitInt:
736 case Type::OverflowBehavior:
737 // GCC treats vector and complex types as fundamental types.
738 case Type::Vector:
739 case Type::ExtVector:
740 case Type::ConstantMatrix:
741 case Type::Complex:
742 case Type::Atomic:
743 // FIXME: GCC treats block pointers as fundamental types?!
744 case Type::BlockPointer:
745 return "_ZTVN10__cxxabiv123__fundamental_type_infoE";
746 case Type::ConstantArray:
747 case Type::IncompleteArray:
748 case Type::VariableArray:
749 // abi::__array_type_info.
750 return "_ZTVN10__cxxabiv117__array_type_infoE";
751
752 case Type::FunctionNoProto:
753 case Type::FunctionProto:
754 // abi::__function_type_info.
755 return "_ZTVN10__cxxabiv120__function_type_infoE";
756
757 case Type::Enum:
758 return "_ZTVN10__cxxabiv116__enum_type_infoE";
759
760 case Type::Record: {
761 const auto *rd = cast<CXXRecordDecl>(cast<RecordType>(ty)->getDecl())
762 ->getDefinitionOrSelf();
763
764 if (!rd->hasDefinition() || !rd->getNumBases()) {
765 return classTypeInfo;
766 }
767
769 return siClassTypeInfo;
770 }
771
772 return vmiClassTypeInfo;
773 }
774
775 case Type::ObjCObject:
776 cgm.errorNYI("VTableClassNameForType: ObjCObject");
777 break;
778
779 case Type::ObjCInterface:
780 cgm.errorNYI("VTableClassNameForType: ObjCInterface");
781 break;
782
783 case Type::ObjCObjectPointer:
784 case Type::Pointer:
785 // abi::__pointer_type_info.
786 return "_ZTVN10__cxxabiv119__pointer_type_infoE";
787
788 case Type::MemberPointer:
789 // abi::__pointer_to_member_type_info.
790 return "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
791
792 case Type::HLSLAttributedResource:
793 case Type::HLSLInlineSpirv:
794 llvm_unreachable("HLSL doesn't support virtual functions");
795 }
796
797 return nullptr;
798}
799} // namespace
800
801/// Return the linkage that the type info and type info name constants
802/// should have for the given type.
803static cir::GlobalLinkageKind getTypeInfoLinkage(CIRGenModule &cgm,
804 QualType ty) {
805 // In addition, it and all of the intermediate abi::__pointer_type_info
806 // structs in the chain down to the abi::__class_type_info for the
807 // incomplete class type must be prevented from resolving to the
808 // corresponding type_info structs for the complete class type, possibly
809 // by making them local static objects. Finally, a dummy class RTTI is
810 // generated for the incomplete type that will not resolve to the final
811 // complete class RTTI (because the latter need not exist), possibly by
812 // making it a local static object.
814 return cir::GlobalLinkageKind::InternalLinkage;
815
816 switch (ty->getLinkage()) {
817 case Linkage::Invalid:
818 llvm_unreachable("Linkage hasn't been computed!");
819
820 case Linkage::None:
823 return cir::GlobalLinkageKind::InternalLinkage;
824
826 case Linkage::Module:
828 // RTTI is not enabled, which means that this type info struct is going
829 // to be used for exception handling. Give it linkonce_odr linkage.
830 if (!cgm.getLangOpts().RTTI)
831 return cir::GlobalLinkageKind::LinkOnceODRLinkage;
832
833 if (const RecordType *record = dyn_cast<RecordType>(ty)) {
834 const auto *rd =
835 cast<CXXRecordDecl>(record->getDecl())->getDefinitionOrSelf();
836 if (rd->hasAttr<WeakAttr>())
837 return cir::GlobalLinkageKind::WeakODRLinkage;
838
839 if (cgm.getTriple().isWindowsItaniumEnvironment())
840 if (rd->hasAttr<DLLImportAttr>() &&
841 shouldUseExternalRttiDescriptor(cgm, ty))
842 return cir::GlobalLinkageKind::ExternalLinkage;
843
844 // MinGW always uses LinkOnceODRLinkage for type info.
845 if (rd->isDynamicClass() && !cgm.getASTContext()
847 .getTriple()
848 .isWindowsGNUEnvironment())
849 return cgm.getVTableLinkage(rd);
850 }
851
852 return cir::GlobalLinkageKind::LinkOnceODRLinkage;
853 }
854
855 llvm_unreachable("Invalid linkage!");
856}
857
858cir::GlobalOp
859CIRGenItaniumRTTIBuilder::getAddrOfTypeName(mlir::Location loc, QualType ty,
860 cir::GlobalLinkageKind linkage) {
861 CIRGenBuilderTy &builder = cgm.getBuilder();
862 SmallString<256> name;
863 llvm::raw_svector_ostream out(name);
865
866 // We know that the mangled name of the type starts at index 4 of the
867 // mangled name of the typename, so we can just index into it in order to
868 // get the mangled name of the type.
869 mlir::Attribute init = builder.getString(
870 name.substr(4), cgm.convertType(cgm.getASTContext().CharTy),
871 std::nullopt);
872
873 CharUnits align =
875
876 // builder.getString can return a #cir.zero if the string given to it only
877 // contains null bytes. However, type names cannot be full of null bytes.
878 // So cast Init to a ConstArrayAttr should be safe.
879 auto initStr = cast<cir::ConstArrayAttr>(init);
880
881 cir::GlobalOp gv = cgm.createOrReplaceCXXRuntimeVariable(
882 loc, name, initStr.getType(), linkage, align);
884 return gv;
885}
886
887mlir::Attribute
888CIRGenItaniumRTTIBuilder::getAddrOfExternalRTTIDescriptor(mlir::Location loc,
889 QualType ty) {
890 // Mangle the RTTI name.
891 SmallString<256> name;
892 llvm::raw_svector_ostream out(name);
894 CIRGenBuilderTy &builder = cgm.getBuilder();
895
896 // Look for an existing global.
897 cir::GlobalOp gv = dyn_cast_or_null<cir::GlobalOp>(cgm.getGlobalValue(name));
898
899 if (!gv) {
900 // Create a new global variable.
901 // From LLVM codegen => Note for the future: If we would ever like to do
902 // deferred emission of RTTI, check if emitting vtables opportunistically
903 // need any adjustment.
904 gv = cgm.createGlobalOp(loc, name, builder.getUInt8PtrTy(),
905 /*isConstant=*/true);
906 const CXXRecordDecl *rd = ty->getAsCXXRecordDecl();
907 cgm.setGVProperties(gv, rd);
908
909 // Import the typeinfo symbol when all non-inline virtual methods are
910 // imported.
911 if (cgm.getTarget().hasPS4DLLImportExport()) {
912 cgm.errorNYI("getAddrOfExternalRTTIDescriptor: hasPS4DLLImportExport");
913 }
914 }
915
916 return builder.getGlobalViewAttr(builder.getUInt8PtrTy(), gv);
917}
918
919void CIRGenItaniumRTTIBuilder::buildVTablePointer(mlir::Location loc,
920 const Type *ty) {
921 CIRGenBuilderTy &builder = cgm.getBuilder();
922 const char *vTableName = vTableClassNameForType(cgm, ty);
923
924 // Check if the alias exists. If it doesn't, then get or create the global.
925 if (cgm.getLangOpts().RelativeCXXABIVTables) {
926 cgm.errorNYI("buildVTablePointer: isRelativeLayout");
927 return;
928 }
929
930 mlir::Type vtableGlobalTy = builder.getPointerTo(builder.getUInt8PtrTy());
931 llvm::Align align = cgm.getDataLayout().getABITypeAlign(vtableGlobalTy);
932 cir::GlobalOp vTable = cgm.createOrReplaceCXXRuntimeVariable(
933 loc, vTableName, vtableGlobalTy, cir::GlobalLinkageKind::ExternalLinkage,
935 // Note: createOrReplaceCXXRuntimeVariable isn't exactly what classic-codegen
936 // does here: it just does a getOrInsertGlobal at the module level. However,
937 // the above function does MOST of what we want, except it sets the global as
938 // constant, when we don't want that. So set it here instead.
939 vTable.setConstant(false);
940
941 // The vtable address point is 2.
942 mlir::Attribute field{};
943 if (cgm.getLangOpts().RelativeCXXABIVTables) {
944 cgm.errorNYI("buildVTablePointer: isRelativeLayout");
945 } else {
946 SmallVector<mlir::Attribute, 4> offsets{
947 cgm.getBuilder().getI32IntegerAttr(2)};
948 auto indices = mlir::ArrayAttr::get(builder.getContext(), offsets);
950 vTable, indices);
951 }
952
953 assert(field && "expected attribute");
954 fields.push_back(field);
955}
956
957/// Build an abi::__si_class_type_info, used for single inheritance, according
958/// to the Itanium C++ ABI, 2.95p6b.
959void CIRGenItaniumRTTIBuilder::buildSIClassTypeInfo(mlir::Location loc,
960 const CXXRecordDecl *rd) {
961 // Itanium C++ ABI 2.9.5p6b:
962 // It adds to abi::__class_type_info a single member pointing to the
963 // type_info structure for the base type,
964 mlir::Attribute baseTypeInfo =
965 CIRGenItaniumRTTIBuilder(cxxABI, cgm)
966 .buildTypeInfo(loc, rd->bases_begin()->getType());
967 fields.push_back(baseTypeInfo);
968}
969
970/// Build an abi::__vmi_class_type_info, used for
971/// classes with bases that do not satisfy the abi::__si_class_type_info
972/// constraints, according to the Itanium C++ ABI, 2.9.5p5c.
973void CIRGenItaniumRTTIBuilder::buildVMIClassTypeInfo(mlir::Location loc,
974 const CXXRecordDecl *rd) {
975 mlir::Type unsignedIntLTy =
977
978 // Itanium C++ ABI 2.9.5p6c:
979 // __flags is a word with flags describing details about the class
980 // structure, which may be referenced by using the __flags_masks
981 // enumeration. These flags refer to both direct and indirect bases.
983 fields.push_back(cir::IntAttr::get(unsignedIntLTy, flags));
984
985 // Itanium C++ ABI 2.9.5p6c:
986 // __base_count is a word with the number of direct proper base class
987 // descriptions that follow.
988 fields.push_back(cir::IntAttr::get(unsignedIntLTy, rd->getNumBases()));
989
990 if (!rd->getNumBases())
991 return;
992
993 // Now add the base class descriptions.
994
995 // Itanium C++ ABI 2.9.5p6c:
996 // __base_info[] is an array of base class descriptions -- one for every
997 // direct proper base. Each description is of the type:
998 //
999 // struct abi::__base_class_type_info {
1000 // public:
1001 // const __class_type_info *__base_type;
1002 // long __offset_flags;
1003 //
1004 // enum __offset_flags_masks {
1005 // __virtual_mask = 0x1,
1006 // __public_mask = 0x2,
1007 // __offset_shift = 8
1008 // };
1009 // };
1010
1011 // If we're in mingw and 'long' isn't wide enough for a pointer, use 'long
1012 // long' instead of 'long' for __offset_flags. libstdc++abi uses long long on
1013 // LLP64 platforms.
1014 // FIXME: Consider updating libc++abi to match, and extend this logic to all
1015 // LLP64 platforms.
1016 QualType offsetFlagsTy = cgm.getASTContext().LongTy;
1017 const TargetInfo &ti = cgm.getASTContext().getTargetInfo();
1018 if (ti.getTriple().isOSCygMing() &&
1019 ti.getPointerWidth(LangAS::Default) > ti.getLongWidth())
1020 offsetFlagsTy = cgm.getASTContext().LongLongTy;
1021 mlir::Type offsetFlagsLTy = cgm.convertType(offsetFlagsTy);
1022
1023 for (const CXXBaseSpecifier &base : rd->bases()) {
1024 // The __base_type member points to the RTTI for the base type.
1025 fields.push_back(CIRGenItaniumRTTIBuilder(cxxABI, cgm)
1026 .buildTypeInfo(loc, base.getType()));
1027
1028 CXXRecordDecl *baseDecl = base.getType()->castAsCXXRecordDecl();
1029 int64_t offsetFlags = 0;
1030
1031 // All but the lower 8 bits of __offset_flags are a signed offset.
1032 // For a non-virtual base, this is the offset in the object of the base
1033 // subobject. For a virtual base, this is the offset in the virtual table of
1034 // the virtual base offset for the virtual base referenced (negative).
1035 CharUnits offset;
1036 if (base.isVirtual())
1038 rd, baseDecl);
1039 else {
1040 const ASTRecordLayout &layout =
1042 offset = layout.getBaseClassOffset(baseDecl);
1043 }
1044 offsetFlags = uint64_t(offset.getQuantity()) << 8;
1045
1046 // The low-order byte of __offset_flags contains flags, as given by the
1047 // masks from the enumeration __offset_flags_masks.
1048 if (base.isVirtual())
1049 offsetFlags |= CodeGenUtils::BCTI_Virtual;
1050 if (base.getAccessSpecifier() == AS_public)
1051 offsetFlags |= CodeGenUtils::BCTI_Public;
1052
1053 fields.push_back(cir::IntAttr::get(offsetFlagsLTy, offsetFlags));
1054 }
1055}
1056
1057void CIRGenItaniumRTTIBuilder::buildPointerTypeInfo(mlir::Location loc,
1058 QualType ty) {
1059 // Itanium C++ ABI 2.9.4p7:
1060 // abi::__pbase_type_info is a base for both pointer types and
1061 // pointer-to-member types. It adds two data members:
1062 //
1063 // class __pbase_type_info : public std::type_info {
1064 // public:
1065 // unsigned int __flags;
1066 // const std::type_info *__pointee;
1067 //
1068 // enum __masks {
1069 // __const_mask = 0x1,
1070 // __volatile_mask = 0x2,
1071 // __restrict_mask = 0x4,
1072 // __incomplete_mask = 0x8,
1073 // __incomplete_class_mask = 0x10,
1074 // __transaction_safe_mask = 0x20
1075 // __noexcept_mask = 0x40
1076 // };
1077 // };
1078 const unsigned int flags =
1080
1081 mlir::Type unsignedIntTy = cgm.convertType(cgm.getASTContext().UnsignedIntTy);
1082 mlir::Attribute flagsAttr = cir::IntAttr::get(unsignedIntTy, flags);
1083 fields.push_back(flagsAttr);
1084
1085 mlir::Attribute pointeeTypeInfo =
1086 CIRGenItaniumRTTIBuilder(cxxABI, cgm).buildTypeInfo(loc, ty);
1087 fields.push_back(pointeeTypeInfo);
1088}
1089
1090void CIRGenItaniumRTTIBuilder::buildPointerToMemberTypeInfo(
1091 mlir::Location loc, const MemberPointerType *ty) {
1092
1093 // The abi::__pointer_to_member_type_info type adds one field to
1094 // abi::__pbase_type_info:
1095 //
1096 // class __pointer_to_member_type_info : public __pbase_type_info {
1097 // public:
1098 // const abi::__class_type_info *__context;
1099 // };
1100 QualType pointeeTy = ty->getPointeeType();
1101
1102 unsigned flags =
1104
1105 const auto *rd = ty->getMostRecentCXXRecordDecl();
1106 if (!rd->hasDefinition())
1108
1109 mlir::Type unsignedIntTy = cgm.convertType(cgm.getASTContext().UnsignedIntTy);
1110 mlir::Attribute flagsAttr = cir::IntAttr::get(unsignedIntTy, flags);
1111 fields.push_back(flagsAttr);
1112
1113 mlir::Attribute pointeeTypeInfo =
1114 CIRGenItaniumRTTIBuilder(cxxABI, cgm).buildTypeInfo(loc, pointeeTy);
1115 fields.push_back(pointeeTypeInfo);
1116
1117 CanQualType contextTy = cgm.getASTContext().getCanonicalTagType(rd);
1118 mlir::Attribute classTypeInfo =
1119 CIRGenItaniumRTTIBuilder(cxxABI, cgm).buildTypeInfo(loc, contextTy);
1120 fields.push_back(classTypeInfo);
1121}
1122
1123mlir::Attribute CIRGenItaniumRTTIBuilder::buildTypeInfo(mlir::Location loc,
1124 QualType ty) {
1125 // We want to operate on the canonical type.
1126 ty = ty.getCanonicalType();
1127
1128 // Check if we've already emitted an RTTI descriptor for this type.
1129 SmallString<256> name;
1130 llvm::raw_svector_ostream out(name);
1132
1133 auto oldGV = dyn_cast_or_null<cir::GlobalOp>(cgm.getGlobalValue(name));
1134
1135 if (oldGV && !oldGV.isDeclaration()) {
1136 assert(!oldGV.hasAvailableExternallyLinkage() &&
1137 "available_externally typeinfos not yet implemented");
1139 oldGV);
1140 }
1141
1142 // Check if there is already an external RTTI descriptor for this type.
1144 shouldUseExternalRttiDescriptor(cgm, ty))
1145 return getAddrOfExternalRTTIDescriptor(loc, ty);
1146
1147 // Emit the standard library with external linkage.
1148 cir::GlobalLinkageKind linkage = getTypeInfoLinkage(cgm, ty);
1149
1150 // Give the type_info object and name the formal visibility of the
1151 // type itself.
1152 cir::VisibilityKind globalVisibility;
1153 if (cir::isLocalLinkage(linkage)) {
1154 // If the linkage is local, only default visibility makes sense.
1155 globalVisibility = cir::VisibilityKind::Default;
1156 } else if (cxxABI.classifyRTTIUniqueness(ty, linkage) ==
1157 CIRGenItaniumCXXABI::RUK_NonUniqueHidden) {
1158 cgm.errorNYI(
1159 "buildTypeInfo: classifyRTTIUniqueness == RUK_NonUniqueHidden");
1160 globalVisibility = cir::VisibilityKind::Hidden;
1161 } else {
1162 globalVisibility = CIRGenModule::getCIRVisibilityKind(ty->getVisibility());
1163 }
1164
1165 return buildTypeInfo(loc, ty, linkage, globalVisibility);
1166}
1167
1168mlir::Attribute
1169CIRGenItaniumRTTIBuilder::buildTypeInfo(mlir::Location loc, QualType ty,
1170 cir::GlobalLinkageKind linkage,
1171 cir::VisibilityKind globalVisibility) {
1172 CIRGenBuilderTy &builder = cgm.getBuilder();
1173
1175
1176 // Add the vtable pointer.
1177 buildVTablePointer(loc, cast<Type>(ty));
1178
1179 // And the name.
1180 cir::GlobalOp typeName = getAddrOfTypeName(loc, ty, linkage);
1181 mlir::Attribute typeNameField;
1182
1183 // If we're supposed to demote the visibility, be sure to set a flag
1184 // to use a string comparison for type_info comparisons.
1185 CIRGenItaniumCXXABI::RTTIUniquenessKind rttiUniqueness =
1186 cxxABI.classifyRTTIUniqueness(ty, linkage);
1187 if (rttiUniqueness != CIRGenItaniumCXXABI::RUK_Unique) {
1188 // The flag is the sign bit, which on ARM64 is defined to be clear
1189 // for global pointers. This is very ARM64-specific.
1190 cgm.errorNYI(
1191 "buildTypeInfo: rttiUniqueness != CIRGenItaniumCXXABI::RUK_Unique");
1192 } else {
1193 typeNameField =
1194 builder.getGlobalViewAttr(builder.getUInt8PtrTy(), typeName);
1195 }
1196
1197 fields.push_back(typeNameField);
1198
1199 switch (ty->getTypeClass()) {
1200#define TYPE(Class, Base)
1201#define ABSTRACT_TYPE(Class, Base)
1202#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
1203#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1204#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1205#include "clang/AST/TypeNodes.inc"
1206 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
1207
1208 // GCC treats vector types as fundamental types.
1209 case Type::Builtin:
1210 case Type::Vector:
1211 case Type::ExtVector:
1212 case Type::ConstantMatrix:
1213 case Type::Complex:
1214 case Type::BlockPointer:
1215 // Itanium C++ ABI 2.9.5p4:
1216 // abi::__fundamental_type_info adds no data members to std::type_info.
1217 break;
1218
1219 case Type::LValueReference:
1220 case Type::RValueReference:
1221 llvm_unreachable("References shouldn't get here");
1222
1223 case Type::Auto:
1224 case Type::DeducedTemplateSpecialization:
1225 llvm_unreachable("Undeduced type shouldn't get here");
1226
1227 case Type::Pipe:
1228 break;
1229
1230 case Type::BitInt:
1231 break;
1232
1233 case Type::OverflowBehavior:
1234 break;
1235
1236 case Type::ConstantArray:
1237 case Type::IncompleteArray:
1238 case Type::VariableArray:
1239 case Type::ArrayParameter:
1240 // Itanium C++ ABI 2.9.5p5:
1241 // abi::__array_type_info adds no data members to std::type_info.
1242 break;
1243
1244 case Type::FunctionNoProto:
1245 case Type::FunctionProto:
1246 // Itanium C++ ABI 2.9.5p5:
1247 // abi::__function_type_info adds no data members to std::type_info.
1248 break;
1249
1250 case Type::Enum:
1251 // Itanium C++ ABI 2.9.5p5:
1252 // abi::__enum_type_info adds no data members to std::type_info.
1253 break;
1254
1255 case Type::Record: {
1256 const auto *rd = cast<CXXRecordDecl>(cast<RecordType>(ty)->getDecl())
1257 ->getDefinitionOrSelf();
1258 if (!rd->hasDefinition() || !rd->getNumBases()) {
1259 // We don't need to emit any fields.
1260 break;
1261 }
1262
1264 buildSIClassTypeInfo(loc, rd);
1265 } else {
1266 buildVMIClassTypeInfo(loc, rd);
1267 }
1268
1269 break;
1270 }
1271
1272 case Type::ObjCObject:
1273 case Type::ObjCInterface:
1274 cgm.errorNYI("buildTypeInfo: ObjCObject & ObjCInterface");
1275 break;
1276
1277 case Type::ObjCObjectPointer:
1278 cgm.errorNYI("buildTypeInfo: ObjCObjectPointer");
1279 break;
1280
1281 case Type::Pointer:
1282 // We need to get the type info for the pointee type.
1283 buildPointerTypeInfo(loc, cast<PointerType>(ty)->getPointeeType());
1284 break;
1285
1286 case Type::MemberPointer:
1287 buildPointerToMemberTypeInfo(loc, cast<MemberPointerType>(ty));
1288 break;
1289
1290 case Type::Atomic:
1291 // No fields, at least for the moment.
1292 break;
1293
1294 case Type::HLSLAttributedResource:
1295 case Type::HLSLInlineSpirv:
1296 llvm_unreachable("HLSL doesn't support RTTI");
1297 }
1298
1300 cir::TypeInfoAttr init = builder.getTypeInfo(builder.getArrayAttr(fields));
1301
1302 SmallString<256> name;
1303 llvm::raw_svector_ostream out(name);
1305
1306 // Create new global and search for an existing global.
1307 auto oldGV = dyn_cast_or_null<cir::GlobalOp>(cgm.getGlobalValue(name));
1308
1309 cir::GlobalOp gv = cgm.createGlobalOp(loc, name, init.getType(),
1310 /*isConstant=*/true);
1311 gv.setLinkage(linkage);
1312
1313 // Export the typeinfo in the same circumstances as the vtable is
1314 // exported.
1315 if (cgm.getTarget().hasPS4DLLImportExport()) {
1316 cgm.errorNYI("buildTypeInfo: target hasPS4DLLImportExport");
1317 return {};
1318 }
1319
1320 // If there's already an old global variable, replace it with the new one.
1321 if (oldGV) {
1322 // Replace occurrences of the old variable if needed.
1323 gv.setName(oldGV.getName());
1324 if (!oldGV->use_empty()) {
1325 cgm.errorNYI("buildTypeInfo: old GV !use_empty");
1326 return {};
1327 }
1328 cgm.eraseGlobalSymbol(oldGV);
1329 oldGV->erase();
1330 }
1331
1332 if (cgm.supportsCOMDAT() && cir::isWeakForLinker(linkage))
1333 gv.setSelfComdat();
1334
1335 CharUnits align = cgm.getASTContext().toCharUnitsFromBits(
1336 cgm.getTarget().getPointerAlign(LangAS::Default));
1337 gv.setAlignmentAttr(cgm.getSize(align));
1338
1339 // The Itanium ABI specifies that type_info objects must be globally
1340 // unique, with one exception: if the type is an incomplete class
1341 // type or a (possibly indirect) pointer to one. That exception
1342 // affects the general case of comparing type_info objects produced
1343 // by the typeid operator, which is why the comparison operators on
1344 // std::type_info generally use the type_info name pointers instead
1345 // of the object addresses. However, the language's built-in uses
1346 // of RTTI generally require class types to be complete, even when
1347 // manipulating pointers to those class types. This allows the
1348 // implementation of dynamic_cast to rely on address equality tests,
1349 // which is much faster.
1350
1351 // All of this is to say that it's important that both the type_info
1352 // object and the type_info name be uniqued when weakly emitted.
1353
1354 mlir::SymbolTable::setSymbolVisibility(
1356 typeName.setGlobalVisibility(globalVisibility);
1359 cgm.setDSOLocal(static_cast<mlir::Operation *>(typeName));
1360
1361 mlir::SymbolTable::setSymbolVisibility(
1363 gv.setGlobalVisibility(globalVisibility);
1366 cgm.setDSOLocal(static_cast<mlir::Operation *>(gv));
1367
1369 return builder.getGlobalViewAttr(builder.getUInt8PtrTy(), gv);
1370}
1371
1372bool CIRGenItaniumCXXABI::shouldTypeidBeNullChecked(QualType srcTy) {
1373 return true;
1374}
1375
1376void CIRGenItaniumCXXABI::emitBadTypeidCall(CIRGenFunction &cgf,
1377 mlir::Location loc) {
1378 // void __cxa_bad_typeid();
1379 cir::FuncType fnTy =
1380 cgf.getBuilder().getFuncType({}, cgf.getBuilder().getVoidTy());
1381 mlir::NamedAttrList attrs;
1382 attrs.set(cir::CIRDialect::getNoReturnAttrName(),
1383 mlir::UnitAttr::get(&cgf.cgm.getMLIRContext()));
1384
1385 cgf.emitRuntimeCall(
1386 loc, cgf.cgm.createRuntimeFunction(fnTy, "__cxa_bad_typeid", attrs), {},
1387 attrs);
1388 cir::UnreachableOp::create(cgf.getBuilder(), loc);
1389}
1390
1391mlir::Value CIRGenItaniumCXXABI::emitTypeid(CIRGenFunction &cgf, QualType srcTy,
1392 Address thisPtr,
1393 mlir::Type typeInfoPtrTy) {
1394 auto *classDecl = srcTy->castAsCXXRecordDecl();
1395 mlir::Location loc = cgm.getLoc(classDecl->getSourceRange());
1396 mlir::Value vptr = cgf.getVTablePtr(loc, thisPtr, classDecl);
1397 return cir::VTableGetTypeInfoOp::create(cgf.getBuilder(), loc, typeInfoPtrTy,
1398 vptr);
1399}
1400
1401mlir::Attribute CIRGenItaniumCXXABI::getAddrOfRTTIDescriptor(mlir::Location loc,
1402 QualType ty) {
1403 return CIRGenItaniumRTTIBuilder(*this, cgm).buildTypeInfo(loc, ty);
1404}
1405
1406/// What sort of uniqueness rules should we use for the RTTI for the
1407/// given type?
1408CIRGenItaniumCXXABI::RTTIUniquenessKind
1409CIRGenItaniumCXXABI::classifyRTTIUniqueness(
1410 QualType canTy, cir::GlobalLinkageKind linkage) const {
1411 if (shouldRTTIBeUnique())
1412 return RUK_Unique;
1413
1414 // It's only necessary for linkonce_odr or weak_odr linkage.
1415 if (linkage != cir::GlobalLinkageKind::LinkOnceODRLinkage &&
1416 linkage != cir::GlobalLinkageKind::WeakODRLinkage)
1417 return RUK_Unique;
1418
1419 // It's only necessary with default visibility.
1420 if (canTy->getVisibility() != DefaultVisibility)
1421 return RUK_Unique;
1422
1423 // If we're not required to publish this symbol, hide it.
1424 if (linkage == cir::GlobalLinkageKind::LinkOnceODRLinkage)
1425 return RUK_NonUniqueHidden;
1426
1427 // If we're required to publish this symbol, as we might be under an
1428 // explicit instantiation, leave it with default visibility but
1429 // enable string-comparisons.
1430 assert(linkage == cir::GlobalLinkageKind::WeakODRLinkage);
1431 return RUK_NonUniqueVisible;
1432}
1433
1434void CIRGenItaniumCXXABI::emitDestructorCall(
1435 CIRGenFunction &cgf, const CXXDestructorDecl *dd, CXXDtorType type,
1436 bool forVirtualBase, bool delegating, Address thisAddr, QualType thisTy) {
1437 GlobalDecl gd(dd, type);
1438 mlir::Value vtt =
1439 getCXXDestructorImplicitParam(cgf, dd, type, forVirtualBase, delegating);
1440 ASTContext &astContext = cgm.getASTContext();
1441 QualType vttTy = astContext.getPointerType(astContext.VoidPtrTy);
1443 CIRGenCallee callee =
1445
1446 cgf.emitCXXDestructorCall(gd, callee, thisAddr.getPointer(), thisTy, vtt,
1447 vttTy, nullptr);
1448}
1449
1450void CIRGenItaniumCXXABI::registerGlobalDtor(const VarDecl *vd,
1451 cir::FuncOp dtor,
1452 mlir::Value addr) {
1453 if (vd->isNoDestroy(cgm.getASTContext()))
1454 return;
1455
1456 // HLSL doesn't support atexit.
1457 if (cgm.getLangOpts().HLSL) {
1458 cgm.errorNYI(vd->getSourceRange(), "registerGlobalDtor: HLSL");
1459 return;
1460 }
1461
1462 // The default behavior is to use atexit. This is handled in lowering
1463 // prepare. Nothing to be done for CIR here.
1464}
1465
1466mlir::Value CIRGenItaniumCXXABI::getCXXDestructorImplicitParam(
1467 CIRGenFunction &cgf, const CXXDestructorDecl *dd, CXXDtorType type,
1468 bool forVirtualBase, bool delegating) {
1469 GlobalDecl gd(dd, type);
1470 return cgf.getVTTParameter(gd, forVirtualBase, delegating);
1471}
1472
1473// The idea here is creating a separate block for the throw with an
1474// `UnreachableOp` as the terminator. So, we branch from the current block
1475// to the throw block and create a block for the remaining operations.
1476static void insertThrowAndSplit(mlir::OpBuilder &builder, mlir::Location loc,
1477 mlir::Value exceptionPtr = {},
1478 mlir::FlatSymbolRefAttr typeInfo = {},
1479 mlir::FlatSymbolRefAttr dtor = {}) {
1480 mlir::Block *currentBlock = builder.getInsertionBlock();
1481 mlir::Region *region = currentBlock->getParent();
1482
1483 if (currentBlock->empty()) {
1484 cir::ThrowOp::create(builder, loc, exceptionPtr, typeInfo, dtor);
1485 cir::UnreachableOp::create(builder, loc);
1486 } else {
1487 mlir::Block *throwBlock = builder.createBlock(region);
1488
1489 cir::ThrowOp::create(builder, loc, exceptionPtr, typeInfo, dtor);
1490 cir::UnreachableOp::create(builder, loc);
1491
1492 builder.setInsertionPointToEnd(currentBlock);
1493 cir::BrOp::create(builder, loc, throwBlock);
1494 }
1495
1496 (void)builder.createBlock(region);
1497}
1498
1499void CIRGenItaniumCXXABI::emitRethrow(CIRGenFunction &cgf, bool isNoReturn) {
1500 // void __cxa_rethrow();
1501 if (isNoReturn) {
1502 CIRGenBuilderTy &builder = cgf.getBuilder();
1503 assert(cgf.currSrcLoc && "expected source location");
1504 mlir::Location loc = cgf.getLoc(*cgf.currSrcLoc);
1505 insertThrowAndSplit(builder, loc);
1506 } else {
1507 cgm.errorNYI("emitRethrow with isNoReturn false");
1508 }
1509}
1510
1511void CIRGenItaniumCXXABI::emitThrow(CIRGenFunction &cgf,
1512 const CXXThrowExpr *e) {
1513 // This differs a bit from LLVM codegen, CIR has native operations for some
1514 // cxa functions, and defers allocation size computation, always pass the dtor
1515 // symbol, etc. CIRGen also does not use getAllocateExceptionFn / getThrowFn.
1516
1517 // Now allocate the exception object.
1518 CIRGenBuilderTy &builder = cgf.getBuilder();
1519 QualType clangThrowType = e->getSubExpr()->getType();
1520 cir::PointerType throwTy =
1521 builder.getPointerTo(cgf.convertType(clangThrowType));
1522 uint64_t typeSize =
1523 cgf.getContext().getTypeSizeInChars(clangThrowType).getQuantity();
1524 mlir::Location subExprLoc = cgf.getLoc(e->getSubExpr()->getSourceRange());
1525
1526 // Defer computing allocation size to some later lowering pass.
1527 mlir::TypedValue<cir::PointerType> exceptionPtr =
1528 cir::AllocExceptionOp::create(builder, subExprLoc, throwTy,
1529 builder.getI64IntegerAttr(typeSize))
1530 .getAddr();
1531
1532 // Build expression and store its result into exceptionPtr.
1533 CharUnits exnAlign = cgf.getContext().getExnObjectAlignment();
1534 cgf.emitAnyExprToExn(e->getSubExpr(), Address(exceptionPtr, exnAlign));
1535
1536 // Get the RTTI symbol address.
1537 auto typeInfo = mlir::cast<cir::GlobalViewAttr>(
1538 cgm.getAddrOfRTTIDescriptor(subExprLoc, clangThrowType,
1539 /*forEH=*/true));
1540 assert(!typeInfo.getIndices() && "expected no indirection");
1541
1542 // The address of the destructor.
1543 //
1544 // Note: LLVM codegen already optimizes out the dtor if the
1545 // type is a record with trivial dtor (by passing down a
1546 // null dtor). In CIR, we forward this info and allow for
1547 // Lowering pass to skip passing the trivial function.
1548 //
1549 const auto *cxxrd = clangThrowType->getAsCXXRecordDecl();
1550 mlir::FlatSymbolRefAttr dtor{};
1551 if (cxxrd && !cxxrd->hasTrivialDestructor()) {
1552 // __cxa_throw is declared to take its destructor as void (*)(void *). We
1553 // must match that if function pointers can be authenticated with a
1554 // discriminator based on their type.
1556 CXXDestructorDecl *dtorD = cxxrd->getDestructor();
1557 dtor = mlir::FlatSymbolRefAttr::get(
1558 cgm.getAddrOfCXXStructor(GlobalDecl(dtorD, Dtor_Complete))
1559 .getSymNameAttr());
1560 }
1561
1562 // Now throw the exception.
1563 mlir::Location loc = cgf.getLoc(e->getSourceRange());
1564 insertThrowAndSplit(builder, loc, exceptionPtr, typeInfo.getSymbol(), dtor);
1565}
1566
1568 switch (cgm.getASTContext().getCXXABIKind()) {
1569 case TargetCXXABI::GenericItanium:
1570 case TargetCXXABI::GenericAArch64:
1571 case TargetCXXABI::GenericARM:
1572 return new CIRGenItaniumCXXABI(cgm);
1573
1574 case TargetCXXABI::AppleARM64:
1575 // The general Itanium ABI will do until we implement something that
1576 // requires special handling.
1578 return new CIRGenItaniumCXXABI(cgm);
1579
1580 default:
1581 llvm_unreachable("bad or NYI ABI kind");
1582 }
1583}
1584
1585cir::GlobalOp CIRGenItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *rd,
1586 CharUnits vptrOffset) {
1587 assert(vptrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
1588 cir::GlobalOp &vtable = vtables[rd];
1589 if (vtable)
1590 return vtable;
1591
1592 // Queue up this vtable for possible deferred emission.
1593 cgm.addDeferredVTable(rd);
1594
1595 SmallString<256> name;
1596 llvm::raw_svector_ostream out(name);
1597 getMangleContext().mangleCXXVTable(rd, out);
1598
1599 const VTableLayout &vtLayout =
1601 mlir::Type vtableType = cgm.getVTables().getVTableType(vtLayout);
1602
1603 // Use pointer alignment for the vtable. Otherwise we would align them based
1604 // on the size of the initializer which doesn't make sense as only single
1605 // values are read.
1606 unsigned ptrAlign = cgm.getLangOpts().RelativeCXXABIVTables
1607 ? 32
1609
1611 cgm.getLoc(rd->getSourceRange()), name, vtableType,
1612 cir::GlobalLinkageKind::ExternalLinkage,
1613 cgm.getASTContext().toCharUnitsFromBits(ptrAlign));
1614 if (!cgm.shouldEmitRTTI())
1615 vtable.setUnnamedAddr(true);
1616
1617 // In MS C++ if you have a class with virtual functions in which you are using
1618 // selective member import/export, then all virtual functions must be exported
1619 // unless they are inline, otherwise a link error will result. To match this
1620 // behavior, for such classes, we dllimport the vtable if it is defined
1621 // externally and all the non-inline virtual methods are marked dllimport, and
1622 // we dllexport the vtable if it is defined in this TU and all the non-inline
1623 // virtual methods are marked dllexport.
1624 if (cgm.getTarget().hasPS4DLLImportExport())
1625 cgm.errorNYI(rd->getSourceRange(),
1626 "getAddrOfVTable: PS4 DLL import/export");
1627
1628 cgm.setGVProperties(vtable, rd);
1629 return vtable;
1630}
1631
1632CIRGenCallee CIRGenItaniumCXXABI::getVirtualFunctionPointer(
1633 CIRGenFunction &cgf, clang::GlobalDecl gd, Address thisAddr, mlir::Type ty,
1634 SourceLocation srcLoc) {
1635 CIRGenBuilderTy &builder = cgm.getBuilder();
1636 mlir::Location loc = cgf.getLoc(srcLoc);
1637 cir::PointerType tyPtr = builder.getPointerTo(ty);
1638 auto *methodDecl = cast<CXXMethodDecl>(gd.getDecl());
1639 mlir::Value vtable = cgf.getVTablePtr(loc, thisAddr, methodDecl->getParent());
1640
1642 mlir::Value vfunc{};
1643 if (cgf.shouldEmitVTableTypeCheckedLoad(methodDecl->getParent())) {
1644 cgm.errorNYI(loc, "getVirtualFunctionPointer: emitVTableTypeCheckedLoad");
1645 } else {
1647
1648 auto vfuncOp = cir::VTableGetVirtualFnOp::create(builder, loc, tyPtr,
1649 vtable, vtableIndex);
1650
1651 // Set invariant on the virtual function pointer load to indicate that
1652 // function didn't change inside vtable.
1653 // It's safe to add it without -fstrict-vtable-pointers, but it would not
1654 // help in devirtualization because it will only matter if we will have 2
1655 // the same virtual function loads from the same vtable load, which won't
1656 // happen without enabled devirtualization with -fstrict-vtable-pointers.
1657 if (cgm.getCodeGenOpts().OptimizationLevel > 0 &&
1658 cgm.getCodeGenOpts().StrictVTablePointers)
1659 vfuncOp.setInvariant(true);
1660
1661 vfunc = vfuncOp;
1662 }
1663
1664 CIRGenCallee callee(gd, vfunc.getDefiningOp());
1665 return callee;
1666}
1667
1668mlir::Value CIRGenItaniumCXXABI::getVTableAddressPointInStructorWithVTT(
1669 CIRGenFunction &cgf, const CXXRecordDecl *vtableClass, BaseSubobject base,
1670 const CXXRecordDecl *nearestVBase) {
1671 assert((base.getBase()->getNumVBases() || nearestVBase != nullptr) &&
1672 needsVTTParameter(cgf.curGD) && "This class doesn't have VTT");
1673
1674 // Get the secondary vpointer index.
1675 uint64_t virtualPointerIndex =
1676 cgm.getVTables().getSecondaryVirtualPointerIndex(vtableClass, base);
1677
1678 /// Load the VTT.
1679 mlir::Value vttPtr = cgf.loadCXXVTT();
1680 mlir::Location loc = cgf.getLoc(vtableClass->getSourceRange());
1681 // Calculate the address point from the VTT, and the offset may be zero.
1682 vttPtr = cgf.getBuilder().createVTTAddrPoint(loc, vttPtr.getType(), vttPtr,
1683 virtualPointerIndex);
1684 // And load the address point from the VTT.
1685 auto vptrType = cir::VPtrType::get(cgf.getBuilder().getContext());
1686 return cgf.getBuilder().createAlignedLoad(loc, vptrType, vttPtr,
1687 cgf.getPointerAlign());
1688}
1689
1690mlir::Value
1691CIRGenItaniumCXXABI::getVTableAddressPoint(BaseSubobject base,
1692 const CXXRecordDecl *vtableClass) {
1693 cir::GlobalOp vtable = getAddrOfVTable(vtableClass, CharUnits());
1694
1695 // Find the appropriate vtable within the vtable group, and the address point
1696 // within that vtable.
1697 VTableLayout::AddressPointLocation addressPoint =
1699 .getVTableLayout(vtableClass)
1700 .getAddressPoint(base);
1701
1702 mlir::OpBuilder &builder = cgm.getBuilder();
1703 auto vtablePtrTy = cir::VPtrType::get(builder.getContext());
1704
1705 return cir::VTableAddrPointOp::create(
1706 builder, cgm.getLoc(vtableClass->getSourceRange()), vtablePtrTy,
1707 mlir::FlatSymbolRefAttr::get(vtable.getSymNameAttr()),
1708 cir::AddressPointAttr::get(cgm.getBuilder().getContext(),
1709 addressPoint.VTableIndex,
1710 addressPoint.AddressPointIndex));
1711}
1712
1713cir::GlobalViewAttr CIRGenItaniumCXXABI::getVTableAddressPointAttr(
1714 BaseSubobject base, const CXXRecordDecl *vtableClass) {
1715 cir::GlobalOp vtable = getAddrOfVTable(vtableClass, CharUnits());
1716
1717 // Find the appropriate vtable within the vtable group, and the address point
1718 // within that vtable.
1719 VTableLayout::AddressPointLocation addressPoint =
1721 .getVTableLayout(vtableClass)
1722 .getAddressPoint(base);
1723
1724 CIRGenBuilderTy &builder = cgm.getBuilder();
1725 mlir::ArrayAttr indices = builder.getArrayAttr(
1726 {builder.getI32IntegerAttr(addressPoint.VTableIndex),
1727 builder.getI32IntegerAttr(addressPoint.AddressPointIndex)});
1728 return cir::GlobalViewAttr::get(
1729 cir::VPtrType::get(builder.getContext()),
1730 mlir::FlatSymbolRefAttr::get(vtable.getSymNameAttr()), indices,
1731 /*addressPoint=*/true);
1732}
1733
1734mlir::Value CIRGenItaniumCXXABI::getVTableAddressPointInStructor(
1735 CIRGenFunction &cgf, const clang::CXXRecordDecl *vtableClass,
1736 clang::BaseSubobject base, const clang::CXXRecordDecl *nearestVBase) {
1737
1738 if ((base.getBase()->getNumVBases() || nearestVBase != nullptr) &&
1739 needsVTTParameter(cgf.curGD)) {
1740 return getVTableAddressPointInStructorWithVTT(cgf, vtableClass, base,
1741 nearestVBase);
1742 }
1743 return getVTableAddressPoint(base, vtableClass);
1744}
1745
1746bool CIRGenItaniumCXXABI::isVirtualOffsetNeededForVTableField(
1747 CIRGenFunction &cgf, CIRGenFunction::VPtr vptr) {
1748 if (vptr.nearestVBase == nullptr)
1749 return false;
1750 return needsVTTParameter(cgf.curGD);
1751}
1752
1754 int64_t entrySize =
1756 assert(byteOffset % entrySize == 0 && "unaligned vtable entry offset");
1757 return byteOffset / entrySize;
1758}
1759
1760mlir::Value CIRGenItaniumCXXABI::getVirtualBaseClassOffset(
1761 mlir::Location loc, CIRGenFunction &cgf, Address thisAddr,
1762 const CXXRecordDecl *classDecl, const CXXRecordDecl *baseClassDecl) {
1763 CIRGenBuilderTy &builder = cgf.getBuilder();
1764 mlir::Value vtablePtr = cgf.getVTablePtr(loc, thisAddr, classDecl);
1765 CharUnits vbaseOffsetOffset =
1767 baseClassDecl);
1768 return cir::VTableGetOffsetOp::create(
1769 builder, loc, cgm.ptrDiffTy, vtablePtr,
1770 getVTableEntryIndex(cgm, vbaseOffsetOffset.getQuantity()));
1771}
1772
1773static cir::FuncOp getBadCastFn(CIRGenFunction &cgf) {
1774 // Prototype: void __cxa_bad_cast();
1775
1776 // TODO(cir): set the calling convention of the runtime function.
1778
1779 cir::FuncType fnTy =
1780 cgf.getBuilder().getFuncType({}, cgf.getBuilder().getVoidTy());
1781 return cgf.cgm.createRuntimeFunction(fnTy, "__cxa_bad_cast");
1782}
1783
1784static void emitCallToBadCast(CIRGenFunction &cgf, mlir::Location loc) {
1785 // TODO(cir): set the calling convention to the runtime function.
1787
1788 mlir::NamedAttrList attrs;
1789 attrs.set(cir::CIRDialect::getNoReturnAttrName(),
1790 mlir::UnitAttr::get(&cgf.cgm.getMLIRContext()));
1791
1792 cgf.emitRuntimeCall(loc, getBadCastFn(cgf), {}, attrs);
1793 cir::UnreachableOp::create(cgf.getBuilder(), loc);
1794 cgf.getBuilder().clearInsertionPoint();
1795}
1796
1797void CIRGenItaniumCXXABI::emitBadCastCall(CIRGenFunction &cgf,
1798 mlir::Location loc) {
1799 emitCallToBadCast(cgf, loc);
1800}
1801
1802static cir::FuncOp getItaniumDynamicCastFn(CIRGenFunction &cgf) {
1803 // Prototype:
1804 // void *__dynamic_cast(const void *sub,
1805 // global_as const abi::__class_type_info *src,
1806 // global_as const abi::__class_type_info *dst,
1807 // std::ptrdiff_t src2dst_offset);
1808
1809 mlir::Type voidPtrTy = cgf.getBuilder().getVoidPtrTy();
1810 mlir::Type rttiPtrTy = cgf.getBuilder().getUInt8PtrTy();
1811 mlir::Type ptrDiffTy = cgf.convertType(cgf.getContext().getPointerDiffType());
1812
1813 // TODO(cir): mark the function as willreturn readonly.
1816
1817 // TODO(cir): set the calling convention of the runtime function.
1819
1820 cir::FuncType FTy = cgf.getBuilder().getFuncType(
1821 {voidPtrTy, rttiPtrTy, rttiPtrTy, ptrDiffTy}, voidPtrTy);
1822 cir::FuncOp fn = cgf.cgm.createRuntimeFunction(FTy, "__dynamic_cast");
1823 fn->setAttr(cir::CIRDialect::getNoThrowAttrName(),
1824 mlir::UnitAttr::get(cgf.getBuilder().getContext()));
1825 return fn;
1826}
1827
1828static Address emitDynamicCastToVoid(CIRGenFunction &cgf, mlir::Location loc,
1829 QualType srcRecordTy, Address src) {
1830 mlir::Value ptr = cgf.getBuilder().createDynCastToVoid(loc, src.getPointer());
1831 return Address{ptr, src.getAlignment()};
1832}
1833
1834static mlir::Value emitExactDynamicCast(CIRGenItaniumCXXABI &abi,
1835 CIRGenFunction &cgf, mlir::Location loc,
1836 QualType srcRecordTy,
1837 QualType destRecordTy,
1838 cir::PointerType destCIRTy,
1839 bool isRefCast, Address src) {
1840 // Find all the inheritance paths from SrcRecordTy to DestRecordTy.
1841 const CXXRecordDecl *srcDecl = srcRecordTy->getAsCXXRecordDecl();
1842 const CXXRecordDecl *destDecl = destRecordTy->getAsCXXRecordDecl();
1843 CXXBasePaths paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1844 /*DetectVirtual=*/false);
1845 (void)destDecl->isDerivedFrom(srcDecl, paths);
1846
1847 // Find an offset within `destDecl` where a `srcDecl` instance and its vptr
1848 // might appear.
1849 std::optional<CharUnits> offset;
1850 for (const CXXBasePath &path : paths) {
1851 // dynamic_cast only finds public inheritance paths.
1852 if (path.Access != AS_public)
1853 continue;
1854
1855 CharUnits pathOffset;
1856 for (const CXXBasePathElement &pathElement : path) {
1857 // Find the offset along this inheritance step.
1858 const CXXRecordDecl *base =
1859 pathElement.Base->getType()->getAsCXXRecordDecl();
1860 if (pathElement.Base->isVirtual()) {
1861 // For a virtual base class, we know that the derived class is exactly
1862 // destDecl, so we can use the vbase offset from its layout.
1863 const ASTRecordLayout &layout =
1864 cgf.getContext().getASTRecordLayout(destDecl);
1865 pathOffset = layout.getVBaseClassOffset(base);
1866 } else {
1867 const ASTRecordLayout &layout =
1868 cgf.getContext().getASTRecordLayout(pathElement.Class);
1869 pathOffset += layout.getBaseClassOffset(base);
1870 }
1871 }
1872
1873 if (!offset) {
1874 offset = pathOffset;
1875 } else if (offset != pathOffset) {
1876 // base appears in at least two different places. Find the most-derived
1877 // object and see if it's a DestDecl. Note that the most-derived object
1878 // must be at least as aligned as this base class subobject, and must
1879 // have a vptr at offset 0.
1880 src = emitDynamicCastToVoid(cgf, loc, srcRecordTy, src);
1881 srcDecl = destDecl;
1882 offset = CharUnits::Zero();
1883 break;
1884 }
1885 }
1886
1887 CIRGenBuilderTy &builder = cgf.getBuilder();
1888
1889 if (!offset) {
1890 // If there are no public inheritance paths, the cast always fails.
1891 mlir::Value nullPtrValue = builder.getNullPtr(destCIRTy, loc);
1892 if (isRefCast) {
1893 mlir::Region *currentRegion = builder.getBlock()->getParent();
1894 emitCallToBadCast(cgf, loc);
1895
1896 // The call to bad_cast will terminate the block. Create a new block to
1897 // hold any follow up code.
1898 builder.createBlock(currentRegion, currentRegion->end());
1899 }
1900
1901 return nullPtrValue;
1902 }
1903
1904 // Compare the vptr against the expected vptr for the destination type at
1905 // this offset. Note that we do not know what type src points to in the case
1906 // where the derived class multiply inherits from the base class so we can't
1907 // use getVTablePtr, so we load the vptr directly instead.
1908
1909 mlir::Value expectedVPtr =
1910 abi.getVTableAddressPoint(BaseSubobject(srcDecl, *offset), destDecl);
1911
1912 // TODO(cir): handle address space here.
1914 mlir::Type vptrTy = expectedVPtr.getType();
1915 mlir::Type vptrPtrTy = builder.getPointerTo(vptrTy);
1916 Address srcVPtrPtr(builder.createBitcast(src.getPointer(), vptrPtrTy),
1917 src.getAlignment());
1918 mlir::Value srcVPtr = builder.createLoad(loc, srcVPtrPtr);
1919
1920 // TODO(cir): decorate SrcVPtr with TBAA info.
1922
1923 mlir::Value success =
1924 builder.createCompare(loc, cir::CmpOpKind::eq, srcVPtr, expectedVPtr);
1925
1926 auto emitCastResult = [&] {
1927 if (offset->isZero())
1928 return builder.createBitcast(src.getPointer(), destCIRTy);
1929
1930 // TODO(cir): handle address space here.
1932 mlir::Type u8PtrTy = builder.getUInt8PtrTy();
1933
1934 mlir::Value strideToApply =
1935 builder.getConstInt(loc, builder.getUInt64Ty(), -offset->getQuantity());
1936 mlir::Value srcU8Ptr = builder.createBitcast(src.getPointer(), u8PtrTy);
1937 mlir::Value resultU8Ptr = cir::PtrStrideOp::create(builder, loc, u8PtrTy,
1938 srcU8Ptr, strideToApply);
1939 return builder.createBitcast(resultU8Ptr, destCIRTy);
1940 };
1941
1942 if (isRefCast) {
1943 mlir::Value failed = builder.createNot(success);
1944 cir::IfOp::create(builder, loc, failed, /*withElseRegion=*/false,
1945 [&](mlir::OpBuilder &, mlir::Location) {
1946 emitCallToBadCast(cgf, loc);
1947 });
1948 return emitCastResult();
1949 }
1950
1951 return cir::TernaryOp::create(
1952 builder, loc, success,
1953 [&](mlir::OpBuilder &, mlir::Location) {
1954 auto result = emitCastResult();
1955 builder.createYield(loc, result);
1956 },
1957 [&](mlir::OpBuilder &, mlir::Location) {
1958 mlir::Value nullPtrValue = builder.getNullPtr(destCIRTy, loc);
1959 builder.createYield(loc, nullPtrValue);
1960 })
1961 .getResult();
1962}
1963
1964static cir::DynamicCastInfoAttr emitDynamicCastInfo(CIRGenFunction &cgf,
1965 mlir::Location loc,
1966 QualType srcRecordTy,
1967 QualType destRecordTy) {
1968 auto srcRtti = mlir::cast<cir::GlobalViewAttr>(
1969 cgf.cgm.getAddrOfRTTIDescriptor(loc, srcRecordTy.getUnqualifiedType()));
1970 auto destRtti = mlir::cast<cir::GlobalViewAttr>(
1971 cgf.cgm.getAddrOfRTTIDescriptor(loc, destRecordTy.getUnqualifiedType()));
1972
1973 cir::FuncOp runtimeFuncOp = getItaniumDynamicCastFn(cgf);
1974 cir::FuncOp badCastFuncOp = getBadCastFn(cgf);
1975 auto runtimeFuncRef = mlir::FlatSymbolRefAttr::get(runtimeFuncOp);
1976 auto badCastFuncRef = mlir::FlatSymbolRefAttr::get(badCastFuncOp);
1977
1978 const CXXRecordDecl *srcDecl = srcRecordTy->getAsCXXRecordDecl();
1979 const CXXRecordDecl *destDecl = destRecordTy->getAsCXXRecordDecl();
1980 CharUnits offsetHint =
1981 CodeGenUtils::computeOffsetHint(cgf.getContext(), srcDecl, destDecl);
1982
1983 mlir::Type ptrdiffTy = cgf.convertType(cgf.getContext().getPointerDiffType());
1984 auto offsetHintAttr = cir::IntAttr::get(ptrdiffTy, offsetHint.getQuantity());
1985
1986 return cir::DynamicCastInfoAttr::get(srcRtti, destRtti, runtimeFuncRef,
1987 badCastFuncRef, offsetHintAttr);
1988}
1989
1990mlir::Value CIRGenItaniumCXXABI::emitDynamicCast(CIRGenFunction &cgf,
1991 mlir::Location loc,
1992 QualType srcRecordTy,
1993 QualType destRecordTy,
1994 cir::PointerType destCIRTy,
1995 bool isRefCast, Address src) {
1996 bool isCastToVoid = destRecordTy.isNull();
1997 assert((!isCastToVoid || !isRefCast) && "cannot cast to void reference");
1998
1999 if (isCastToVoid)
2000 return emitDynamicCastToVoid(cgf, loc, srcRecordTy, src).getPointer();
2001
2002 // If the destination is effectively final, the cast succeeds if and only
2003 // if the dynamic type of the pointer is exactly the destination type.
2004 if (destRecordTy->getAsCXXRecordDecl()->isEffectivelyFinal() &&
2005 cgf.cgm.getCodeGenOpts().OptimizationLevel > 0) {
2006 CIRGenBuilderTy &builder = cgf.getBuilder();
2007 // If this isn't a reference cast, check the pointer to see if it's null.
2008 if (!isRefCast) {
2009 mlir::Value srcPtrIsNull = builder.createPtrIsNull(src.getPointer());
2010 return cir::TernaryOp::create(
2011 builder, loc, srcPtrIsNull,
2012 [&](mlir::OpBuilder, mlir::Location) {
2013 builder.createYield(
2014 loc, builder.getNullPtr(destCIRTy, loc).getResult());
2015 },
2016 [&](mlir::OpBuilder &, mlir::Location) {
2017 mlir::Value exactCast = emitExactDynamicCast(
2018 *this, cgf, loc, srcRecordTy, destRecordTy, destCIRTy,
2019 isRefCast, src);
2020 builder.createYield(loc, exactCast);
2021 })
2022 .getResult();
2023 }
2024
2025 return emitExactDynamicCast(*this, cgf, loc, srcRecordTy, destRecordTy,
2026 destCIRTy, isRefCast, src);
2027 }
2028
2029 cir::DynamicCastInfoAttr castInfo =
2030 emitDynamicCastInfo(cgf, loc, srcRecordTy, destRecordTy);
2031 return cgf.getBuilder().createDynCast(loc, src.getPointer(), destCIRTy,
2032 isRefCast, castInfo);
2033}
2034
2035cir::MethodAttr
2036CIRGenItaniumCXXABI::buildVirtualMethodAttr(cir::MethodType methodTy,
2037 const CXXMethodDecl *md) {
2038 assert(md->isVirtual() && "only deal with virtual member functions");
2039
2041 return cir::MethodAttr::get(methodTy, index);
2042}
2043/// The Itanium ABI always places an offset to the complete object
2044/// at entry -2 in the vtable.
2045void CIRGenItaniumCXXABI::emitVirtualObjectDelete(
2046 CIRGenFunction &cgf, const CXXDeleteExpr *delExpr, Address ptr,
2047 QualType elementType, const CXXDestructorDecl *dtor) {
2048 bool useGlobalDelete = delExpr->isGlobalDelete();
2049 if (useGlobalDelete) {
2050 cgf.cgm.errorNYI(delExpr->getSourceRange(),
2051 "emitVirtualObjectDelete: global delete");
2052 }
2053
2054 CXXDtorType dtorType = useGlobalDelete ? Dtor_Complete : Dtor_Deleting;
2055 emitVirtualDestructorCall(cgf, dtor, dtorType, ptr, delExpr);
2056}
2057
2058/************************** Array allocation cookies **************************/
2059
2060CharUnits CIRGenItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
2061 // The array cookie is a size_t; pad that up to the element alignment.
2062 // The cookie is actually right-justified in that space.
2063 return std::max(
2064 cgm.getSizeSize(),
2065 cgm.getASTContext().getPreferredTypeAlignInChars(elementType));
2066}
2067
2068Address CIRGenItaniumCXXABI::initializeArrayCookie(CIRGenFunction &cgf,
2069 Address newPtr,
2070 mlir::Value numElements,
2071 const CXXNewExpr *e,
2072 QualType elementType) {
2073 assert(requiresArrayCookie(e));
2074
2075 // TODO: When sanitizer support is implemented, we'll need to
2076 // get the address space from `newPtr`.
2078
2079 ASTContext &ctx = cgm.getASTContext();
2080 CharUnits sizeSize = cgf.getSizeSize();
2081 mlir::Location loc = cgf.getLoc(e->getSourceRange());
2082
2083 // The size of the cookie.
2084 CharUnits cookieSize =
2085 std::max(sizeSize, ctx.getPreferredTypeAlignInChars(elementType));
2086 assert(cookieSize == getArrayCookieSizeImpl(elementType));
2087
2088 mlir::Type u8Ty = cgf.getBuilder().getUInt8Ty();
2089 mlir::Value baseBytePtr =
2090 cgf.getBuilder().createPtrBitcast(newPtr.getPointer(), u8Ty);
2091
2092 // Compute an offset to the cookie.
2093 CharUnits cookieOffset = cookieSize - sizeSize;
2094 mlir::Value cookiePtrValue = baseBytePtr;
2095 if (!cookieOffset.isZero()) {
2096 mlir::Value offsetOp = cgf.getBuilder().getSignedInt(
2097 loc, cookieOffset.getQuantity(), /*width=*/32);
2098 cookiePtrValue =
2099 cgf.getBuilder().createPtrStride(loc, cookiePtrValue, offsetOp);
2100 }
2101
2102 CharUnits baseAlignment = newPtr.getAlignment();
2103 CharUnits cookiePtrAlignment = baseAlignment.alignmentAtOffset(cookieOffset);
2104 Address cookiePtr(cookiePtrValue, u8Ty, cookiePtrAlignment);
2105
2106 // Write the number of elements into the appropriate slot.
2107 Address numElementsPtr =
2108 cookiePtr.withElementType(cgf.getBuilder(), cgf.sizeTy);
2109 cgf.getBuilder().createStore(loc, numElements, numElementsPtr);
2110
2111 // Finally, compute a pointer to the actual data buffer by skipping
2112 // over the cookie completely.
2113 mlir::Value dataOffset =
2114 cgf.getBuilder().getSignedInt(loc, cookieSize.getQuantity(),
2115 /*width=*/32);
2116 mlir::Value dataPtr =
2117 cgf.getBuilder().createPtrStride(loc, baseBytePtr, dataOffset);
2118 mlir::Value finalPtr =
2119 cgf.getBuilder().createPtrBitcast(dataPtr, newPtr.getElementType());
2120 CharUnits finalAlignment = baseAlignment.alignmentAtOffset(cookieSize);
2121 return Address(finalPtr, newPtr.getElementType(), finalAlignment);
2122}
2123
2124bool CIRGenItaniumCXXABI::hasAnyUnusedVirtualInlineFunction(
2125 const CXXRecordDecl *rd) const {
2126 const auto &vtableLayout = cgm.getItaniumVTableContext().getVTableLayout(rd);
2127
2128 for (const auto &vtableComponent : vtableLayout.vtable_components()) {
2129 // Skip empty slot.
2130 if (!vtableComponent.isUsedFunctionPointerKind())
2131 continue;
2132
2133 const CXXMethodDecl *method = vtableComponent.getFunctionDecl();
2134 const FunctionDecl *fd = method->getDefinition();
2135 const bool isInlined =
2136 method->getCanonicalDecl()->isInlined() || (fd && fd->isInlined());
2137 if (!isInlined)
2138 continue;
2139
2140 StringRef name = cgm.getMangledName(
2141 vtableComponent.getGlobalDecl(/*HasVectorDeletingDtors=*/false));
2142 auto entry = dyn_cast_or_null<cir::GlobalOp>(cgm.getGlobalValue(name));
2143 // This checks if virtual inline function has already been emitted.
2144 // Note that it is possible that this inline function would be emitted
2145 // after trying to emit vtable speculatively. Because of this we do
2146 // an extra pass after emitting all deferred vtables to find and emit
2147 // these vtables opportunistically.
2148 if (!entry || entry.isDeclaration())
2149 return true;
2150 }
2151 return false;
2152}
2153
2154bool CIRGenItaniumCXXABI::isVTableHidden(const CXXRecordDecl *rd) const {
2155 const auto &vtableLayout = cgm.getItaniumVTableContext().getVTableLayout(rd);
2156
2157 for (const auto &vtableComponent : vtableLayout.vtable_components()) {
2158 if (vtableComponent.isRTTIKind()) {
2159 const CXXRecordDecl *rttiDecl = vtableComponent.getRTTIDecl();
2160 if (rttiDecl->getVisibility() == Visibility::HiddenVisibility)
2161 return true;
2162 } else if (vtableComponent.isUsedFunctionPointerKind()) {
2163 const CXXMethodDecl *method = vtableComponent.getFunctionDecl();
2164 if (method->getVisibility() == Visibility::HiddenVisibility &&
2165 !method->isDefined())
2166 return true;
2167 }
2168 }
2169 return false;
2170}
2171
2172bool CIRGenItaniumCXXABI::canSpeculativelyEmitVTableAsBaseClass(
2173 const CXXRecordDecl *rd) const {
2174 // We don't emit available_externally vtables if we are in -fapple-kext mode
2175 // because kext mode does not permit devirtualization.
2176 if (cgm.getLangOpts().AppleKext)
2177 return false;
2178
2179 // If the vtable is hidden then it is not safe to emit an available_externally
2180 // copy of vtable.
2181 if (isVTableHidden(rd))
2182 return false;
2183
2184 if (cgm.getCodeGenOpts().ForceEmitVTables)
2185 return true;
2186
2187 // A speculative vtable can only be generated if all virtual inline functions
2188 // defined by this class are emitted. The vtable in the final program contains
2189 // for each virtual inline function not used in the current TU a function that
2190 // is equivalent to the unused function. The function in the actual vtable
2191 // does not have to be declared under the same symbol (e.g., a virtual
2192 // destructor that can be substituted with its base class's destructor). Since
2193 // inline functions are emitted lazily and this emissions does not account for
2194 // speculative emission of a vtable, we might generate a speculative vtable
2195 // with references to inline functions that are not emitted under that name.
2196 // This can lead to problems when devirtualizing a call to such a function,
2197 // that result in linking errors. Hence, if there are any unused virtual
2198 // inline function, we cannot emit the speculative vtable.
2199 // FIXME we can still emit a copy of the vtable if we
2200 // can emit definition of the inline functions.
2201 if (hasAnyUnusedVirtualInlineFunction(rd))
2202 return false;
2203
2204 // For a class with virtual bases, we must also be able to speculatively
2205 // emit the VTT, because CodeGen doesn't have separate notions of "can emit
2206 // the vtable" and "can emit the VTT". For a base subobject, this means we
2207 // need to be able to emit non-virtual base vtables.
2208 if (rd->getNumVBases()) {
2209 for (const auto &b : rd->bases()) {
2210 auto *brd = b.getType()->getAsCXXRecordDecl();
2211 assert(brd && "no class for base specifier");
2212 if (b.isVirtual() || !brd->isDynamicClass())
2213 continue;
2214 if (!canSpeculativelyEmitVTableAsBaseClass(brd))
2215 return false;
2216 }
2217 }
2218
2219 return true;
2220}
2221
2222bool CIRGenItaniumCXXABI::canSpeculativelyEmitVTable(
2223 const CXXRecordDecl *rd) const {
2224 if (!canSpeculativelyEmitVTableAsBaseClass(rd))
2225 return false;
2226
2228 return false;
2229
2230 // For a complete-object vtable (or more specifically, for the VTT), we need
2231 // to be able to speculatively emit the vtables of all dynamic virtual bases.
2232 for (const auto &b : rd->vbases()) {
2233 auto *brd = b.getType()->getAsCXXRecordDecl();
2234 assert(brd && "no class for base specifier");
2235 if (!brd->isDynamicClass())
2236 continue;
2237 if (!canSpeculativelyEmitVTableAsBaseClass(brd))
2238 return false;
2239 }
2240
2241 return true;
2242}
2243
2245 Address initialPtr,
2246 const CXXRecordDecl *unadjustedClass,
2247 int64_t nonVirtualAdjustment,
2248 int64_t virtualAdjustment,
2249 bool isReturnAdjustment) {
2250 if (!nonVirtualAdjustment && !virtualAdjustment)
2251 return initialPtr.getPointer();
2252
2253 CIRGenBuilderTy &builder = cgf.getBuilder();
2254 mlir::Location loc = builder.getUnknownLoc();
2255 mlir::Value v =
2256 builder.createPtrBitcast(initialPtr.getPointer(), builder.getUInt8Ty());
2257 auto i8PtrTy = mlir::cast<cir::PointerType>(v.getType());
2258
2259 // In a base-to-derived cast, the non-virtual adjustment is applied first.
2260 if (nonVirtualAdjustment && !isReturnAdjustment) {
2261 cir::ConstantOp offsetConst = builder.getSInt64(nonVirtualAdjustment, loc);
2262 v = cir::PtrStrideOp::create(builder, loc, i8PtrTy, v, offsetConst);
2263 }
2264
2265 // Perform the virtual adjustment if we have one.
2266 mlir::Value resultPtr;
2267 if (virtualAdjustment) {
2268 mlir::Value vtablePtr = cgf.getVTablePtr(
2269 loc, Address(v, clang::CharUnits::One()), unadjustedClass);
2270
2271 mlir::Value offset = cir::VTableGetOffsetOp::create(
2272 builder, loc, cgf.ptrDiffTy, vtablePtr,
2273 getVTableEntryIndex(cgf.cgm, virtualAdjustment));
2274
2275 resultPtr = cir::PtrStrideOp::create(builder, loc, i8PtrTy, v, offset);
2276 } else {
2277 resultPtr = v;
2278 }
2279
2280 // In a derived-to-base conversion, the non-virtual adjustment is
2281 // applied second.
2282 if (nonVirtualAdjustment && isReturnAdjustment) {
2283 cir::ConstantOp offsetConst = builder.getSInt64(nonVirtualAdjustment, loc);
2284 resultPtr =
2285 cir::PtrStrideOp::create(builder, loc, i8PtrTy, resultPtr, offsetConst);
2286 }
2287
2288 // Cast back to original pointer type.
2289 return builder.createBitcast(resultPtr, initialPtr.getType());
2290}
2291
2292mlir::Value CIRGenItaniumCXXABI::performThisAdjustment(
2293 CIRGenFunction &cgf, Address thisAddr, const CXXRecordDecl *unadjustedClass,
2294 const ThunkInfo &ti) {
2295 return performTypeAdjustment(cgf, thisAddr, unadjustedClass,
2296 ti.This.NonVirtual,
2298 /*isReturnAdjustment=*/false);
2299}
2300
2301mlir::Value CIRGenItaniumCXXABI::performReturnAdjustment(
2302 CIRGenFunction &cgf, Address ret, const CXXRecordDecl *unadjustedClass,
2303 const ReturnAdjustment &ra) {
2304 return performTypeAdjustment(cgf, ret, unadjustedClass, ra.NonVirtual,
2306 /*isReturnAdjustment=*/true);
2307}
2308
2309bool CIRGenItaniumCXXABI::isZeroInitializable(const MemberPointerType *mpt) {
2310 return mpt->isMemberFunctionPointer();
2311}
static void emitConstructorDestructorAlias(CIRGenModule &cgm, GlobalDecl aliasDecl, GlobalDecl targetDecl)
static void insertThrowAndSplit(mlir::OpBuilder &builder, mlir::Location loc, mlir::Value exceptionPtr={}, mlir::FlatSymbolRefAttr typeInfo={}, mlir::FlatSymbolRefAttr dtor={})
static Address emitDynamicCastToVoid(CIRGenFunction &cgf, mlir::Location loc, QualType srcRecordTy, Address src)
static cir::DynamicCastInfoAttr emitDynamicCastInfo(CIRGenFunction &cgf, mlir::Location loc, QualType srcRecordTy, QualType destRecordTy)
static int64_t getVTableEntryIndex(CIRGenModule &cgm, int64_t byteOffset)
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 void emitCallToBadCast(CIRGenFunction &cgf, mlir::Location loc)
static cir::FuncOp getItaniumDynamicCastFn(CIRGenFunction &cgf)
static StructorCIRGen getCIRGenToUse(CIRGenModule &cgm, const CXXMethodDecl *md)
static cir::FuncOp getBadCastFn(CIRGenFunction &cgf)
static RValue performReturnAdjustment(CIRGenFunction &cgf, QualType resultType, RValue rv, const ThunkInfo &thunk)
Defines the clang::Expr interface and subclasses for C++ expressions.
static QualType getPointeeType(const MemRegion *R)
C Language Family Type Representation.
cir::GlobalViewAttr getGlobalViewAttr(cir::GlobalOp globalOp, mlir::ArrayAttr indices={})
Get constant address of a global variable as an MLIR attribute.
mlir::Value createPtrIsNull(mlir::Value ptr)
cir::PtrStrideOp createPtrStride(mlir::Location loc, mlir::Value base, mlir::Value stride)
cir::PointerType getPointerTo(mlir::Type ty)
cir::ConstantOp getNullPtr(mlir::Type ty, mlir::Location loc)
mlir::Value createPtrBitcast(mlir::Value src, mlir::Type newPointeeTy)
mlir::Value getSignedInt(mlir::Location loc, int64_t val, unsigned numBits)
mlir::Value createBitcast(mlir::Value src, mlir::Type newTy)
cir::CmpOp createCompare(mlir::Location loc, cir::CmpOpKind kind, mlir::Value lhs, mlir::Value rhs)
mlir::Value createNot(mlir::Location loc, mlir::Value value)
cir::PointerType getVoidPtrTy(clang::LangAS langAS=clang::LangAS::Default)
cir::YieldOp createYield(mlir::Location loc, mlir::ValueRange value={})
Create a yield operation.
mlir::DataLayout layout
llvm::Align getABITypeAlign(mlir::Type ty) const
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
CanQualType LongTy
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:855
const LangOptions & getLangOpts() const
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
CanQualType CharTy
CharUnits getExnObjectAlignment() const
Return the alignment (in bytes) of the thrown exception object.
CharUnits getPreferredTypeAlignInChars(QualType T) const
Return the PreferredAlignment of a (complete) type T, in characters.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CanQualType UnsignedIntTy
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:974
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.
const CXXRecordDecl * getBase() const
getBase - Returns the base class declaration.
mlir::Value getPointer() const
Definition Address.h:98
mlir::Type getElementType() const
Definition Address.h:125
clang::CharUnits getAlignment() const
Definition Address.h:138
mlir::Type getType() const
Definition Address.h:117
mlir::Value emitRawPointer() const
Return the pointer contained in this class after authenticating it and adding offset to it if necessa...
Definition Address.h:112
cir::TypeInfoAttr getTypeInfo(mlir::ArrayAttr fieldsAttr)
cir::ConstantOp getSInt64(uint64_t c, mlir::Location loc)
cir::PointerType getUInt8PtrTy()
cir::LoadOp createLoad(mlir::Location loc, Address addr, bool isVolatile=false, bool isNontemporal=false)
cir::StoreOp createStore(mlir::Location loc, mlir::Value val, Address dst, bool isVolatile=false, bool isNontemporal=false, mlir::IntegerAttr align={}, cir::SyncScopeKindAttr scope={}, cir::MemOrderAttr order={})
cir::LoadOp createAlignedLoad(mlir::Location loc, mlir::Type ty, mlir::Value ptr, llvm::MaybeAlign align)
cir::FuncType getFuncType(llvm::ArrayRef< mlir::Type > params, mlir::Type retTy, bool isVarArg=false)
mlir::Value createDynCast(mlir::Location loc, mlir::Value src, cir::PointerType destType, bool isRefCast, cir::DynamicCastInfoAttr info)
mlir::Attribute getString(llvm::StringRef str, mlir::Type eltTy, std::optional< size_t > size, bool ensureNullTerm=true)
Get a cir::ConstArrayAttr for a string literal.
cir::ConstantOp getConstInt(mlir::Location loc, llvm::APSInt intVal)
mlir::Value createVTTAddrPoint(mlir::Location loc, mlir::Type retTy, mlir::Value addr, uint64_t offset)
mlir::Value createDynCastToVoid(mlir::Location loc, mlir::Value src)
Implements C++ ABI-specific code generation functions.
clang::MangleContext & getMangleContext()
Gets the mangle context.
static CIRGenCallee forDirect(mlir::Operation *funcPtr, const CIRGenCalleeInfo &abstractInfo=CIRGenCalleeInfo())
Definition CIRGenCall.h:92
static CIRGenCallee forVirtual(const clang::CallExpr *ce, clang::GlobalDecl md, Address addr, cir::FuncType fTy)
Definition CIRGenCall.h:156
mlir::Type convertType(clang::QualType t)
clang::GlobalDecl curGD
The GlobalDecl for the current function being compiled or the global variable currently being initial...
const clang::Decl * curFuncDecl
Address getAddrOfLocalVar(const clang::VarDecl *vd)
Return the address of a local variable.
void emitAnyExprToExn(const Expr *e, Address addr)
mlir::Value getVTTParameter(GlobalDecl gd, bool forVirtualBase, bool delegating)
Return the VTT parameter that should be passed to a base constructor/destructor with virtual bases.
mlir::Location getLoc(clang::SourceLocation srcLoc)
Helpers to convert Clang's SourceLocation to a MLIR Location.
mlir::Value loadCXXVTT()
Load the VTT parameter to base constructors/destructors have virtual bases.
Address returnValue
The temporary alloca to hold the return value.
mlir::Value getVTablePtr(mlir::Location loc, Address thisAddr, const clang::CXXRecordDecl *vtableClass)
Return the Value of the vtable pointer member pointed to by thisAddr.
bool shouldEmitVTableTypeCheckedLoad(const CXXRecordDecl *rd)
Returns whether we should perform a type checked load when loading a virtual function for virtual cal...
CIRGenBuilderTy & getBuilder()
mlir::Value emitRuntimeCall(mlir::Location loc, cir::FuncOp callee, llvm::ArrayRef< mlir::Value > args={}, mlir::NamedAttrList attrs={})
std::optional< SourceRange > currSrcLoc
Use to track source locations across nested visitor traversals.
void emitCXXDestructorCall(const CXXDestructorDecl *dd, CXXDtorType type, bool forVirtualBase, bool delegating, Address thisAddr, QualType thisTy)
clang::ASTContext & getContext() const
This class organizes the cross-function state that is used while generating CIR code.
llvm::StringRef getMangledName(clang::GlobalDecl gd)
DiagnosticBuilder errorNYI(SourceLocation, llvm::StringRef)
Helpers to emit "not yet implemented" error diagnostics.
clang::ASTContext & getASTContext() const
cir::FuncOp getAddrOfCXXStructor(clang::GlobalDecl gd, const CIRGenFunctionInfo *fnInfo=nullptr, cir::FuncType fnType=nullptr, bool dontDefer=false, ForDefinition_t isForDefinition=NotForDefinition)
void addReplacement(llvm::StringRef name, mlir::Operation *op)
mlir::Type convertType(clang::QualType type)
bool shouldEmitRTTI(bool forEH=false)
mlir::IntegerAttr getSize(CharUnits size)
CIRGenBuilderTy & getBuilder()
void setDSOLocal(mlir::Operation *op) const
ItaniumVTableContext & getItaniumVTableContext()
void setGVProperties(mlir::Operation *op, const NamedDecl *d) const
Set visibility, dllimport/dllexport and dso_local.
cir::FuncOp emitAliasForGlobal(llvm::StringRef mangledName, mlir::Operation *op, GlobalDecl aliasGD, cir::FuncOp aliasee, cir::GlobalLinkageKind linkage)
Emit aliasGD as an alias of aliasee, replacing any existing declaration op, and return the alias.
mlir::Attribute getAddrOfRTTIDescriptor(mlir::Location loc, QualType ty, bool forEH=false)
Get the address of the RTTI descriptor for the given type.
static mlir::SymbolTable::Visibility getMLIRVisibilityFromCIRLinkage(cir::GlobalLinkageKind GLK)
const clang::TargetInfo & getTarget() const
static mlir::SymbolTable::Visibility getMLIRVisibility(cir::GlobalOp op)
const llvm::Triple & getTriple() const
const cir::CIRDataLayout & getDataLayout() const
cir::GlobalOp createOrReplaceCXXRuntimeVariable(mlir::Location loc, llvm::StringRef name, mlir::Type ty, cir::GlobalLinkageKind linkage, clang::CharUnits alignment)
Will return a global variable of the given type.
cir::FuncOp createRuntimeFunction(cir::FuncType ty, llvm::StringRef name, mlir::NamedAttrList extraAttrs={}, bool isLocal=false, bool assumeConvergent=false)
LangAS getGlobalVarAddressSpace(const VarDecl *decl)
Return the AST address space of the underlying global variable for D, as determined by its declaratio...
void eraseGlobalSymbol(mlir::Operation *op)
static void setInitializer(cir::GlobalOp &op, mlir::Attribute value)
cir::GlobalLinkageKind getFunctionLinkage(GlobalDecl gd)
const clang::CodeGenOptions & getCodeGenOpts() const
const clang::LangOptions & getLangOpts() const
bool mayVTableBeDuplicated(cir::GlobalLinkageKind linkage) const
Return true if a vtable with the given linkage may have more than one address in the program,...
cir::GlobalOp createGlobalOp(mlir::Location loc, llvm::StringRef name, mlir::Type t, bool isConstant=false, mlir::ptr::MemorySpaceAttrInterface addrSpace={}, mlir::Operation *insertPoint=nullptr)
static cir::VisibilityKind getCIRVisibilityKind(Visibility v)
void addDeferredVTable(const CXXRecordDecl *rd)
cir::FuncOp codegenCXXStructor(clang::GlobalDecl gd)
mlir::Location getLoc(clang::SourceLocation cLoc)
Helpers to convert the presumed location of Clang's SourceLocation to an MLIR Location.
mlir::Operation * getGlobalValue(llvm::StringRef ref)
mlir::ModuleOp getModule() const
mlir::MLIRContext & getMLIRContext()
mlir::Operation * getAddrOfGlobal(clang::GlobalDecl gd, ForDefinition_t isForDefinition=NotForDefinition)
void maybeSetTrivialComdat(const clang::Decl &d, mlir::Operation *op)
CIRGenCXXABI & getCXXABI() const
void emitGlobal(clang::GlobalDecl gd)
Emit code for a single global function or variable declaration.
CIRGenVTables & getVTables()
cir::GlobalLinkageKind getVTableLinkage(const CXXRecordDecl *rd)
Return the appropriate linkage for the vtable, VTT, and type information of the given class.
const CIRGenFunctionInfo & arrangeCXXStructorDeclaration(clang::GlobalDecl gd)
cir::FuncType getFunctionType(const CIRGenFunctionInfo &info)
Get the CIR function type for.
cir::RecordType getVTableType(const clang::VTableLayout &layout)
Returns the type of a vtable with the given layout.
void createVTableInitializer(cir::GlobalOp &vtable, const clang::VTableLayout &layout, mlir::Attribute rtti, bool vtableHasLocalLinkage)
Add vtable components for the given vtable layout to the given global initializer.
void emitVTTDefinition(cir::GlobalOp vttOp, cir::GlobalLinkageKind linkage, const CXXRecordDecl *rd)
Emit the definition of the given vtable.
cir::GlobalOp getAddrOfVTT(const CXXRecordDecl *rd)
Get the address of the VTT for the given record decl.
bool isVTableExternal(const clang::CXXRecordDecl *rd)
At this point in the translation unit, does it appear that can we rely on the vtable being defined el...
uint64_t getSecondaryVirtualPointerIndex(const CXXRecordDecl *rd, BaseSubobject base)
Return the index in the VTT where the virtual pointer for the given subobject is located.
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...
QualType getType() const
Retrieves the type of the base class.
Definition DeclCXX.h:249
bool isGlobalDelete() const
Definition ExprCXX.h:2656
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2153
bool isVirtual() const
Definition DeclCXX.h:2208
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2296
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2266
SourceRange getSourceRange() const
Definition ExprCXX.h:2615
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool isEffectivelyFinal() const
Determine whether it's impossible for a class to be derived from this class.
Definition DeclCXX.cpp:2341
base_class_range bases()
Definition DeclCXX.h:609
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition DeclCXX.h:603
base_class_iterator bases_begin()
Definition DeclCXX.h:616
base_class_range vbases()
Definition DeclCXX.h:626
bool isAbstract() const
Determine whether this class has a pure virtual function.
Definition DeclCXX.h:1231
bool isDynamicClass() const
Definition DeclCXX.h:575
bool hasDefinition() const
Definition DeclCXX.h:562
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition DeclCXX.h:624
bool isDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is derived from the class Base.
const Expr * getSubExpr() const
Definition ExprCXX.h:1233
static CanQual< Type > CreateUnsafe(QualType Other)
This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
CharUnits alignmentAtOffset(CharUnits offset) const
Given that this is a non-zero alignment value, what is the alignment at the given offset?
Definition CharUnits.h:177
bool isZero() const
Test whether the quantity equals zero.
Definition CharUnits.h:101
QuantityType getQuantity() const
Get the raw integer representation of this quantity.
Definition CharUnits.h:155
static CharUnits One()
Construct a CharUnits quantity of one.
Definition CharUnits.h:55
static CharUnits fromQuantity(QuantityType Quantity)
Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:58
static CharUnits Zero()
Construct a CharUnits quantity of zero.
Definition CharUnits.h:52
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2110
bool isTranslationUnit() const
Definition DeclBase.h:2206
SourceLocation getLocation() const
Definition DeclBase.h:448
DeclContext * getDeclContext()
Definition DeclBase.h:457
bool hasAttr() const
Definition DeclBase.h:586
bool shouldEmitInExternalSource() const
Whether the definition of the declaration should be emitted in external sources.
QualType getType() const
Definition Expr.h:146
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition Decl.h:3098
FunctionDecl * getDefinition()
Get the definition for this declaration.
Definition Decl.h:2438
bool isDefined(const FunctionDecl *&Definition, bool CheckForPendingFriendDefinition=false) const
Returns true if the function has a definition that does not need to be instantiated.
Definition Decl.cpp:3254
GlobalDecl - represents a global declaration.
Definition GlobalDecl.h:60
GlobalDecl getWithCtorType(CXXCtorType Type)
Definition GlobalDecl.h:176
CXXCtorType getCtorType() const
Definition GlobalDecl.h:117
GlobalDecl getWithDtorType(CXXDtorType Type)
Definition GlobalDecl.h:183
CXXDtorType getDtorType() const
Definition GlobalDecl.h:122
const Decl * getDecl() const
Definition GlobalDecl.h:115
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:5712
virtual void mangleCXXCtorComdat(const CXXConstructorDecl *D, raw_ostream &)=0
virtual void mangleCXXDtorComdat(const CXXDestructorDecl *D, raw_ostream &)=0
uint64_t getMethodVTableIndex(GlobalDecl GD)
Locate a virtual function in the vtable.
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...
virtual void mangleCXXRTTI(QualType T, raw_ostream &)=0
virtual void mangleCXXRTTIName(QualType T, raw_ostream &, bool NormalizeIntegers=false)=0
CXXRecordDecl * getMostRecentCXXRecordDecl() const
Note: this can trigger extra deserialization when external AST sources are used.
Definition Type.cpp:5852
QualType getPointeeType() const
Definition TypeBase.h:3769
bool isMemberFunctionPointer() const
Returns true if the member type (i.e.
Definition TypeBase.h:3773
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:297
Visibility getVisibility() const
Determines the visibility of this entity.
Definition Decl.h:446
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
QualType getCanonicalType() const
Definition TypeBase.h:8630
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8672
Encodes a location in the source.
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:5004
bool hasConstructorVariants() const
Does this ABI have different entrypoints for complete-object and base-subobject constructors?
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
uint64_t getPointerWidth(LangAS AddrSpace) const
Return the width of pointers on this target, for the specified address space.
Definition TargetInfo.h:497
virtual bool hasPS4DLLImportExport() const
uint64_t getPointerAlign(LangAS AddrSpace) const
Definition TargetInfo.h:501
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
unsigned getLongWidth() const
getLongWidth/Align - Return the size of 'signed long' and 'unsigned long' for this target,...
Definition TargetInfo.h:543
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:3728
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
Visibility getVisibility() const
Determine the visibility of this type.
Definition TypeBase.h:3146
Linkage getLinkage() const
Determine the linkage of this type.
Definition Type.cpp:5207
TypeClass getTypeClass() const
Definition TypeBase.h:2449
AddressPointLocation getAddressPoint(BaseSubobject Base) const
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2173
bool isNoDestroy(const ASTContext &) const
Is destruction of this variable entirely suppressed?
Definition Decl.cpp:2830
static bool isLocalLinkage(GlobalLinkageKind linkage)
Definition CIROpsEnums.h:51
static bool isValidLinkage(GlobalLinkageKind gl)
uint64_t getVTableEntrySize(mlir::ModuleOp mod, const mlir::DataLayout &dataLayout)
The size in bytes of an entry of a C++ vtable in module.
static bool isWeakForLinker(GlobalLinkageKind linkage)
Whether the definition of this global may be replaced at link time.
static bool isDiscardableIfUnused(GlobalLinkageKind linkage)
Whether the definition of this global may be discarded if it is not used in its compilation unit.
Definition CIROpsEnums.h:95
CIRGenCXXABI * CreateCIRGenItaniumCXXABI(CIRGenModule &cgm)
Creates and Itanium-family ABI.
unsigned extractPBaseFlags(const ASTContext &Ctx, QualType &Type)
Compute the flags for a __pbase_type_info, and remove the corresponding pieces from Type.
bool containsIncompleteClassType(QualType Ty)
Returns whether the given type contains an incomplete class type.
bool canUseSingleInheritance(const CXXRecordDecl *RD)
Return whether the given record decl has a "single, public, non-virtual base at offset zero (i....
unsigned computeVMIClassTypeInfoFlags(const CXXRecordDecl *RD)
Compute the value of the flags member in abi::__vmi_class_type_info.
CharUnits computeOffsetHint(ASTContext &Ctx, const CXXRecordDecl *Src, const CXXRecordDecl *Dst)
Compute the src2dst_offset hint as described in the Itanium C++ ABI [2.9.7].
bool isStandardLibraryRTTIDescriptor(QualType Ty)
Returns whether the type information for the given type exists in the standard library.
@ BCTI_Virtual
BCTI_Virtual - Base class is virtual.
@ BCTI_Public
BCTI_Public - Base class is public.
@ PTI_ContainingClassIncomplete
PTI_ContainingClassIncomplete - Containing class is incomplete.
llvm::Value * getCXXDestructorImplicitParam(CodeGenModule &CGM, llvm::BasicBlock *InsertBlock, llvm::BasicBlock::iterator InsertPoint, const CXXDestructorDecl *D, CXXDtorType Type, bool ForVirtualBase, bool Delegating)
const internal::VariadicDynCastAllOfMatcher< Stmt, CallExpr > callExpr
Matches call expressions.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
constexpr size_t align(size_t Size)
Aligns a size to the pointer alignment.
Definition PrimType.h:218
@ Address
A pointer to a ValueDecl.
Definition Primitives.h:28
RangeSelector name(std::string ID)
Given a node with a "name", (like NamedDecl, DeclRefExpr, CxxCtorInitializer, and TypeLoc) selects th...
Top level wrappers for InstallAPI frontend operations.
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_Complete
Complete object ctor.
Definition ABI.h:25
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ AS_public
Definition Specifiers.h:128
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ 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_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
LangAS
Defines the address space values used by the address space qualifier of QualType.
U cast(CodeGen::Address addr)
Definition Address.h:327
@ DefaultVisibility
Objects with "default" visibility are seen by the dynamic linker and act like normal objects.
Definition Visibility.h:46
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t int64_t
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 uint64_t
static bool addressSpace()
static bool vtableEmitMetadata()
static bool emitTypeMetadataCodeForVCall()
static bool opFuncReadOnly()
static bool setDLLStorageClass()
static bool cxxabiAppleARM64CXXABI()
static bool opGlobalDLLImportExport()
static bool opGlobalPartition()
static bool pointerAuthentication()
static bool opFuncCallingConv()
static bool opFuncWillReturn()
static bool cxxabiUseARMGuardVarABI()
static bool cxxabiUseARMMethodPtrABI()
static bool vtableRelativeLayout()
const clang::CXXRecordDecl * nearestVBase
clang::CharUnits getPointerAlign() const
clang::CharUnits getSizeSize() const
Represents an element in a path from a derived class to a base class.
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
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