clang 20.0.0git
ItaniumCXXABI.cpp
Go to the documentation of this file.
1//===------- ItaniumCXXABI.cpp - AST support for the Itanium C++ ABI ------===//
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++ AST support targeting the Itanium C++ ABI, which is
10// documented at:
11// http://www.codesourcery.com/public/cxx-abi/abi.html
12// http://www.codesourcery.com/public/cxx-abi/abi-eh.html
13//
14// It also supports the closely-related ARM C++ ABI, documented at:
15// http://infocenter.arm.com/help/topic/com.arm.doc.ihi0041c/IHI0041C_cppabi.pdf
16//
17//===----------------------------------------------------------------------===//
18
19#include "CXXABI.h"
21#include "clang/AST/DeclCXX.h"
22#include "clang/AST/Mangle.h"
25#include "clang/AST/Type.h"
27#include "llvm/ADT/iterator.h"
28#include <optional>
29
30using namespace clang;
31
32namespace {
33
34/// According to Itanium C++ ABI 5.1.2:
35/// the name of an anonymous union is considered to be
36/// the name of the first named data member found by a pre-order,
37/// depth-first, declaration-order walk of the data members of
38/// the anonymous union.
39/// If there is no such data member (i.e., if all of the data members
40/// in the union are unnamed), then there is no way for a program to
41/// refer to the anonymous union, and there is therefore no need to mangle its name.
42///
43/// Returns the name of anonymous union VarDecl or nullptr if it is not found.
44static const IdentifierInfo *findAnonymousUnionVarDeclName(const VarDecl& VD) {
45 const RecordType *RT = VD.getType()->getAs<RecordType>();
46 assert(RT && "type of VarDecl is expected to be RecordType.");
47 assert(RT->getDecl()->isUnion() && "RecordType is expected to be a union.");
48 if (const FieldDecl *FD = RT->getDecl()->findFirstNamedDataMember()) {
49 return FD->getIdentifier();
50 }
51
52 return nullptr;
53}
54
55/// The name of a decomposition declaration.
56struct DecompositionDeclName {
57 using BindingArray = ArrayRef<const BindingDecl*>;
58
59 /// Representative example of a set of bindings with these names.
60 BindingArray Bindings;
61
62 /// Iterators over the sequence of identifiers in the name.
63 struct Iterator
64 : llvm::iterator_adaptor_base<Iterator, BindingArray::const_iterator,
65 std::random_access_iterator_tag,
66 const IdentifierInfo *> {
67 Iterator(BindingArray::const_iterator It) : iterator_adaptor_base(It) {}
68 const IdentifierInfo *operator*() const {
69 return (*this->I)->getIdentifier();
70 }
71 };
72 Iterator begin() const { return Iterator(Bindings.begin()); }
73 Iterator end() const { return Iterator(Bindings.end()); }
74};
75}
76
77namespace llvm {
78template <typename T> static bool isDenseMapKeyEmpty(T V) {
79 return llvm::DenseMapInfo<T>::isEqual(
80 V, llvm::DenseMapInfo<T>::getEmptyKey());
81}
82template <typename T> static bool isDenseMapKeyTombstone(T V) {
83 return llvm::DenseMapInfo<T>::isEqual(
84 V, llvm::DenseMapInfo<T>::getTombstoneKey());
85}
86
87template <typename T>
88static std::optional<bool> areDenseMapKeysEqualSpecialValues(T LHS, T RHS) {
89 bool LHSEmpty = isDenseMapKeyEmpty(LHS);
90 bool RHSEmpty = isDenseMapKeyEmpty(RHS);
91 if (LHSEmpty || RHSEmpty)
92 return LHSEmpty && RHSEmpty;
93
94 bool LHSTombstone = isDenseMapKeyTombstone(LHS);
95 bool RHSTombstone = isDenseMapKeyTombstone(RHS);
96 if (LHSTombstone || RHSTombstone)
97 return LHSTombstone && RHSTombstone;
98
99 return std::nullopt;
100}
101
102template<>
103struct DenseMapInfo<DecompositionDeclName> {
104 using ArrayInfo = llvm::DenseMapInfo<ArrayRef<const BindingDecl*>>;
105 static DecompositionDeclName getEmptyKey() {
106 return {ArrayInfo::getEmptyKey()};
107 }
108 static DecompositionDeclName getTombstoneKey() {
109 return {ArrayInfo::getTombstoneKey()};
110 }
111 static unsigned getHashValue(DecompositionDeclName Key) {
112 assert(!isEqual(Key, getEmptyKey()) && !isEqual(Key, getTombstoneKey()));
113 return llvm::hash_combine_range(Key.begin(), Key.end());
114 }
115 static bool isEqual(DecompositionDeclName LHS, DecompositionDeclName RHS) {
116 if (std::optional<bool> Result =
117 areDenseMapKeysEqualSpecialValues(LHS.Bindings, RHS.Bindings))
118 return *Result;
119
120 return LHS.Bindings.size() == RHS.Bindings.size() &&
121 std::equal(LHS.begin(), LHS.end(), RHS.begin());
122 }
123};
124}
125
126namespace {
127
128/// Keeps track of the mangled names of lambda expressions and block
129/// literals within a particular context.
130class ItaniumNumberingContext : public MangleNumberingContext {
131 ItaniumMangleContext *Mangler;
132 llvm::StringMap<unsigned> LambdaManglingNumbers;
133 unsigned BlockManglingNumber = 0;
134 llvm::DenseMap<const IdentifierInfo *, unsigned> VarManglingNumbers;
135 llvm::DenseMap<const IdentifierInfo *, unsigned> TagManglingNumbers;
136 llvm::DenseMap<DecompositionDeclName, unsigned>
137 DecompsitionDeclManglingNumbers;
138
139public:
140 ItaniumNumberingContext(ItaniumMangleContext *Mangler) : Mangler(Mangler) {}
141
142 unsigned getManglingNumber(const CXXMethodDecl *CallOperator) override {
143 const CXXRecordDecl *Lambda = CallOperator->getParent();
144 assert(Lambda->isLambda());
145
146 // Computation of the <lambda-sig> is non-trivial and subtle. Rather than
147 // duplicating it here, just mangle the <lambda-sig> directly.
148 llvm::SmallString<128> LambdaSig;
149 llvm::raw_svector_ostream Out(LambdaSig);
150 Mangler->mangleLambdaSig(Lambda, Out);
151
152 return ++LambdaManglingNumbers[LambdaSig];
153 }
154
155 unsigned getManglingNumber(const BlockDecl *BD) override {
156 return ++BlockManglingNumber;
157 }
158
159 unsigned getStaticLocalNumber(const VarDecl *VD) override {
160 return 0;
161 }
162
163 /// Variable decls are numbered by identifier.
164 unsigned getManglingNumber(const VarDecl *VD, unsigned) override {
165 if (auto *DD = dyn_cast<DecompositionDecl>(VD)) {
166 DecompositionDeclName Name{DD->bindings()};
167 return ++DecompsitionDeclManglingNumbers[Name];
168 }
169
171 if (!Identifier) {
172 // VarDecl without an identifier represents an anonymous union
173 // declaration.
174 Identifier = findAnonymousUnionVarDeclName(*VD);
175 }
176 return ++VarManglingNumbers[Identifier];
177 }
178
179 unsigned getManglingNumber(const TagDecl *TD, unsigned) override {
180 return ++TagManglingNumbers[TD->getIdentifier()];
181 }
182};
183
184// A version of this for SYCL that makes sure that 'device' mangling context
185// matches the lambda mangling number, so that __builtin_sycl_unique_stable_name
186// can be consistently generated between a MS and Itanium host by just referring
187// to the device mangling number.
188class ItaniumSYCLNumberingContext : public ItaniumNumberingContext {
189 llvm::DenseMap<const CXXMethodDecl *, unsigned> ManglingNumbers;
190 using ManglingItr = decltype(ManglingNumbers)::iterator;
191
192public:
193 ItaniumSYCLNumberingContext(ItaniumMangleContext *Mangler)
194 : ItaniumNumberingContext(Mangler) {}
195
196 unsigned getManglingNumber(const CXXMethodDecl *CallOperator) override {
197 unsigned Number = ItaniumNumberingContext::getManglingNumber(CallOperator);
198 std::pair<ManglingItr, bool> emplace_result =
199 ManglingNumbers.try_emplace(CallOperator, Number);
200 (void)emplace_result;
201 assert(emplace_result.second && "Lambda number set multiple times?");
202 return Number;
203 }
204
205 using ItaniumNumberingContext::getManglingNumber;
206
207 unsigned getDeviceManglingNumber(const CXXMethodDecl *CallOperator) override {
208 ManglingItr Itr = ManglingNumbers.find(CallOperator);
209 assert(Itr != ManglingNumbers.end() && "Lambda not yet mangled?");
210
211 return Itr->second;
212 }
213};
214
215class ItaniumCXXABI : public CXXABI {
216private:
217 std::unique_ptr<MangleContext> Mangler;
218protected:
219 ASTContext &Context;
220public:
221 ItaniumCXXABI(ASTContext &Ctx)
222 : Mangler(Ctx.createMangleContext()), Context(Ctx) {}
223
224 MemberPointerInfo
225 getMemberPointerInfo(const MemberPointerType *MPT) const override {
226 const TargetInfo &Target = Context.getTargetInfo();
227 TargetInfo::IntType PtrDiff = Target.getPtrDiffType(LangAS::Default);
228 MemberPointerInfo MPI;
229 MPI.Width = Target.getTypeWidth(PtrDiff);
230 MPI.Align = Target.getTypeAlign(PtrDiff);
231 MPI.HasPadding = false;
232 if (MPT->isMemberFunctionPointer())
233 MPI.Width *= 2;
234 return MPI;
235 }
236
237 CallingConv getDefaultMethodCallConv(bool isVariadic) const override {
238 const llvm::Triple &T = Context.getTargetInfo().getTriple();
239 if (!isVariadic && T.isWindowsGNUEnvironment() &&
240 T.getArch() == llvm::Triple::x86)
241 return CC_X86ThisCall;
242 return Context.getTargetInfo().getDefaultCallingConv();
243 }
244
245 // We cheat and just check that the class has a vtable pointer, and that it's
246 // only big enough to have a vtable pointer and nothing more (or less).
247 bool isNearlyEmpty(const CXXRecordDecl *RD) const override {
248
249 // Check that the class has a vtable pointer.
250 if (!RD->isDynamicClass())
251 return false;
252
253 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
254 CharUnits PointerSize = Context.toCharUnitsFromBits(
255 Context.getTargetInfo().getPointerWidth(LangAS::Default));
256 return Layout.getNonVirtualSize() == PointerSize;
257 }
258
259 const CXXConstructorDecl *
261 return nullptr;
262 }
263
265 CXXConstructorDecl *CD) override {}
266
268 TypedefNameDecl *DD) override {}
269
271 return nullptr;
272 }
273
275 DeclaratorDecl *DD) override {}
276
278 return nullptr;
279 }
280
281 std::unique_ptr<MangleNumberingContext>
282 createMangleNumberingContext() const override {
283 if (Context.getLangOpts().isSYCL())
284 return std::make_unique<ItaniumSYCLNumberingContext>(
285 cast<ItaniumMangleContext>(Mangler.get()));
286 return std::make_unique<ItaniumNumberingContext>(
287 cast<ItaniumMangleContext>(Mangler.get()));
288 }
289};
290}
291
293 return new ItaniumCXXABI(Ctx);
294}
295
296std::unique_ptr<MangleNumberingContext>
298 return std::make_unique<ItaniumNumberingContext>(
299 cast<ItaniumMangleContext>(Mangler));
300}
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3443
clang::CharUnits operator*(clang::CharUnits::QuantityType Scale, const clang::CharUnits &CU)
Definition: CharUnits.h:225
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
StringRef Identifier
Definition: Format.cpp:3040
llvm::MachO::Target Target
Definition: MachO.h:51
C Language Family Type Representation.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:188
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
const LangOptions & getLangOpts() const
Definition: ASTContext.h:834
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:799
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
Definition: RecordLayout.h:38
CharUnits getNonVirtualSize() const
getNonVirtualSize - Get the non-virtual size (in chars) of an object, which is the size of the object...
Definition: RecordLayout.h:210
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4474
Implements C++ ABI-specific semantic analysis functions.
Definition: CXXABI.h:29
virtual void addTypedefNameForUnnamedTagDecl(TagDecl *TD, TypedefNameDecl *DD)=0
virtual MemberPointerInfo getMemberPointerInfo(const MemberPointerType *MPT) const =0
Returns the width and alignment of a member pointer in bits, as well as whether it has padding.
virtual std::unique_ptr< MangleNumberingContext > createMangleNumberingContext() const =0
Returns a new mangling number context for this C++ ABI.
virtual CallingConv getDefaultMethodCallConv(bool isVariadic) const =0
Returns the default calling convention for C++ methods.
virtual void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD)=0
virtual TypedefNameDecl * getTypedefNameForUnnamedTagDecl(const TagDecl *TD)=0
virtual const CXXConstructorDecl * getCopyConstructorForExceptionObject(CXXRecordDecl *)=0
Retrieves the mapping from class to copy constructor for this C++ ABI.
virtual void addCopyConstructorForExceptionObject(CXXRecordDecl *, CXXConstructorDecl *)=0
Adds a mapping from class to copy constructor for this C++ ABI.
virtual DeclaratorDecl * getDeclaratorForUnnamedTagDecl(const TagDecl *TD)=0
virtual bool isNearlyEmpty(const CXXRecordDecl *RD) const =0
Returns whether the given class is nearly empty, with just virtual pointers and no data except possib...
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2553
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2078
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2204
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition: DeclCXX.h:1030
bool isDynamicClass() const
Definition: DeclCXX.h:586
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
Represents a ValueDecl that came out of a declarator.
Definition: Decl.h:735
Represents a member of a struct/union/class.
Definition: Decl.h:3033
One of these records is kept for each identifier that is lexed.
virtual void mangleLambdaSig(const CXXRecordDecl *Lambda, raw_ostream &)=0
bool isSYCL() const
Definition: LangOptions.h:771
MangleContext - Context for tracking state which persists across multiple calls to the C++ name mangl...
Definition: Mangle.h:45
Keeps track of the mangled names of lambda expressions and block literals within a particular context...
virtual unsigned getManglingNumber(const CXXMethodDecl *CallOperator)=0
Retrieve the mangling number of a new lambda expression with the given call operator within this cont...
virtual unsigned getStaticLocalNumber(const VarDecl *VD)=0
Static locals are numbered by source order.
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3519
bool isMemberFunctionPointer() const
Returns true if the member type (i.e.
Definition: Type.h:3539
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:274
const FieldDecl * findFirstNamedDataMember() const
Finds the first data member which has a name.
Definition: Decl.cpp:5210
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:6072
RecordDecl * getDecl() const
Definition: Type.h:6082
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3564
bool isUnion() const
Definition: Decl.h:3770
Exposes information about the current target.
Definition: TargetInfo.h:220
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1262
uint64_t getPointerWidth(LangAS AddrSpace) const
Return the width of pointers on this target, for the specified address space.
Definition: TargetInfo.h:478
virtual CallingConv getDefaultCallingConv() const
Gets the default calling convention for the given target and declaration context.
Definition: TargetInfo.h:1683
IntType getPtrDiffType(LangAS AddrSpace) const
Definition: TargetInfo.h:396
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8731
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3413
QualType getType() const
Definition: Decl.h:682
Represents a variable declaration or definition.
Definition: Decl.h:882
Defines the clang::TargetInfo interface.
The JSON file list parser is used to communicate input to InstallAPI.
std::unique_ptr< MangleNumberingContext > createItaniumNumberingContext(MangleContext *)
CXXABI * CreateItaniumCXXABI(ASTContext &Ctx)
Creates an instance of a C++ ABI class.
const FunctionProtoType * T
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:278
@ CC_X86ThisCall
Definition: Specifiers.h:282
Diagnostic wrappers for TextAPI types for error reporting.
Definition: Dominators.h:30
static bool isDenseMapKeyTombstone(T V)
static bool isDenseMapKeyEmpty(T V)
static std::optional< bool > areDenseMapKeysEqualSpecialValues(T LHS, T RHS)
IntType
===-— Target Data Type Query Methods ----------------------------—===//
Definition: TargetInfo.h:144
static DecompositionDeclName getTombstoneKey()
llvm::DenseMapInfo< ArrayRef< const BindingDecl * > > ArrayInfo
static DecompositionDeclName getEmptyKey()
static bool isEqual(DecompositionDeclName LHS, DecompositionDeclName RHS)
static unsigned getHashValue(DecompositionDeclName Key)