clang 19.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/FoldingSet.h"
28#include "llvm/ADT/iterator.h"
29#include <optional>
30
31using namespace clang;
32
33namespace {
34
35/// According to Itanium C++ ABI 5.1.2:
36/// the name of an anonymous union is considered to be
37/// the name of the first named data member found by a pre-order,
38/// depth-first, declaration-order walk of the data members of
39/// the anonymous union.
40/// If there is no such data member (i.e., if all of the data members
41/// in the union are unnamed), then there is no way for a program to
42/// refer to the anonymous union, and there is therefore no need to mangle its name.
43///
44/// Returns the name of anonymous union VarDecl or nullptr if it is not found.
45static const IdentifierInfo *findAnonymousUnionVarDeclName(const VarDecl& VD) {
46 const RecordType *RT = VD.getType()->getAs<RecordType>();
47 assert(RT && "type of VarDecl is expected to be RecordType.");
48 assert(RT->getDecl()->isUnion() && "RecordType is expected to be a union.");
49 if (const FieldDecl *FD = RT->getDecl()->findFirstNamedDataMember()) {
50 return FD->getIdentifier();
51 }
52
53 return nullptr;
54}
55
56/// The name of a decomposition declaration.
57struct DecompositionDeclName {
58 using BindingArray = ArrayRef<const BindingDecl*>;
59
60 /// Representative example of a set of bindings with these names.
61 BindingArray Bindings;
62
63 /// Iterators over the sequence of identifiers in the name.
64 struct Iterator
65 : llvm::iterator_adaptor_base<Iterator, BindingArray::const_iterator,
66 std::random_access_iterator_tag,
67 const IdentifierInfo *> {
68 Iterator(BindingArray::const_iterator It) : iterator_adaptor_base(It) {}
69 const IdentifierInfo *operator*() const {
70 return (*this->I)->getIdentifier();
71 }
72 };
73 Iterator begin() const { return Iterator(Bindings.begin()); }
74 Iterator end() const { return Iterator(Bindings.end()); }
75};
76}
77
78namespace llvm {
79template<typename T> bool isDenseMapKeyEmpty(T V) {
80 return llvm::DenseMapInfo<T>::isEqual(
81 V, llvm::DenseMapInfo<T>::getEmptyKey());
82}
83template<typename T> bool isDenseMapKeyTombstone(T V) {
84 return llvm::DenseMapInfo<T>::isEqual(
85 V, llvm::DenseMapInfo<T>::getTombstoneKey());
86}
87
88template <typename T>
89std::optional<bool> areDenseMapKeysEqualSpecialValues(T LHS, T RHS) {
90 bool LHSEmpty = isDenseMapKeyEmpty(LHS);
91 bool RHSEmpty = isDenseMapKeyEmpty(RHS);
92 if (LHSEmpty || RHSEmpty)
93 return LHSEmpty && RHSEmpty;
94
95 bool LHSTombstone = isDenseMapKeyTombstone(LHS);
96 bool RHSTombstone = isDenseMapKeyTombstone(RHS);
97 if (LHSTombstone || RHSTombstone)
98 return LHSTombstone && RHSTombstone;
99
100 return std::nullopt;
101}
102
103template<>
104struct DenseMapInfo<DecompositionDeclName> {
105 using ArrayInfo = llvm::DenseMapInfo<ArrayRef<const BindingDecl*>>;
106 static DecompositionDeclName getEmptyKey() {
107 return {ArrayInfo::getEmptyKey()};
108 }
109 static DecompositionDeclName getTombstoneKey() {
110 return {ArrayInfo::getTombstoneKey()};
111 }
112 static unsigned getHashValue(DecompositionDeclName Key) {
113 assert(!isEqual(Key, getEmptyKey()) && !isEqual(Key, getTombstoneKey()));
114 return llvm::hash_combine_range(Key.begin(), Key.end());
115 }
116 static bool isEqual(DecompositionDeclName LHS, DecompositionDeclName RHS) {
117 if (std::optional<bool> Result =
118 areDenseMapKeysEqualSpecialValues(LHS.Bindings, RHS.Bindings))
119 return *Result;
120
121 return LHS.Bindings.size() == RHS.Bindings.size() &&
122 std::equal(LHS.begin(), LHS.end(), RHS.begin());
123 }
124};
125}
126
127namespace {
128
129/// Keeps track of the mangled names of lambda expressions and block
130/// literals within a particular context.
131class ItaniumNumberingContext : public MangleNumberingContext {
132 ItaniumMangleContext *Mangler;
133 llvm::StringMap<unsigned> LambdaManglingNumbers;
134 unsigned BlockManglingNumber = 0;
135 llvm::DenseMap<const IdentifierInfo *, unsigned> VarManglingNumbers;
136 llvm::DenseMap<const IdentifierInfo *, unsigned> TagManglingNumbers;
137 llvm::DenseMap<DecompositionDeclName, unsigned>
138 DecompsitionDeclManglingNumbers;
139
140public:
141 ItaniumNumberingContext(ItaniumMangleContext *Mangler) : Mangler(Mangler) {}
142
143 unsigned getManglingNumber(const CXXMethodDecl *CallOperator) override {
144 const CXXRecordDecl *Lambda = CallOperator->getParent();
145 assert(Lambda->isLambda());
146
147 // Computation of the <lambda-sig> is non-trivial and subtle. Rather than
148 // duplicating it here, just mangle the <lambda-sig> directly.
149 llvm::SmallString<128> LambdaSig;
150 llvm::raw_svector_ostream Out(LambdaSig);
151 Mangler->mangleLambdaSig(Lambda, Out);
152
153 return ++LambdaManglingNumbers[LambdaSig];
154 }
155
156 unsigned getManglingNumber(const BlockDecl *BD) override {
157 return ++BlockManglingNumber;
158 }
159
160 unsigned getStaticLocalNumber(const VarDecl *VD) override {
161 return 0;
162 }
163
164 /// Variable decls are numbered by identifier.
165 unsigned getManglingNumber(const VarDecl *VD, unsigned) override {
166 if (auto *DD = dyn_cast<DecompositionDecl>(VD)) {
167 DecompositionDeclName Name{DD->bindings()};
168 return ++DecompsitionDeclManglingNumbers[Name];
169 }
170
172 if (!Identifier) {
173 // VarDecl without an identifier represents an anonymous union
174 // declaration.
175 Identifier = findAnonymousUnionVarDeclName(*VD);
176 }
177 return ++VarManglingNumbers[Identifier];
178 }
179
180 unsigned getManglingNumber(const TagDecl *TD, unsigned) override {
181 return ++TagManglingNumbers[TD->getIdentifier()];
182 }
183};
184
185// A version of this for SYCL that makes sure that 'device' mangling context
186// matches the lambda mangling number, so that __builtin_sycl_unique_stable_name
187// can be consistently generated between a MS and Itanium host by just referring
188// to the device mangling number.
189class ItaniumSYCLNumberingContext : public ItaniumNumberingContext {
190 llvm::DenseMap<const CXXMethodDecl *, unsigned> ManglingNumbers;
191 using ManglingItr = decltype(ManglingNumbers)::iterator;
192
193public:
194 ItaniumSYCLNumberingContext(ItaniumMangleContext *Mangler)
195 : ItaniumNumberingContext(Mangler) {}
196
197 unsigned getManglingNumber(const CXXMethodDecl *CallOperator) override {
198 unsigned Number = ItaniumNumberingContext::getManglingNumber(CallOperator);
199 std::pair<ManglingItr, bool> emplace_result =
200 ManglingNumbers.try_emplace(CallOperator, Number);
201 (void)emplace_result;
202 assert(emplace_result.second && "Lambda number set multiple times?");
203 return Number;
204 }
205
206 using ItaniumNumberingContext::getManglingNumber;
207
208 unsigned getDeviceManglingNumber(const CXXMethodDecl *CallOperator) override {
209 ManglingItr Itr = ManglingNumbers.find(CallOperator);
210 assert(Itr != ManglingNumbers.end() && "Lambda not yet mangled?");
211
212 return Itr->second;
213 }
214};
215
216class ItaniumCXXABI : public CXXABI {
217private:
218 std::unique_ptr<MangleContext> Mangler;
219protected:
220 ASTContext &Context;
221public:
222 ItaniumCXXABI(ASTContext &Ctx)
223 : Mangler(Ctx.createMangleContext()), Context(Ctx) {}
224
225 MemberPointerInfo
226 getMemberPointerInfo(const MemberPointerType *MPT) const override {
227 const TargetInfo &Target = Context.getTargetInfo();
228 TargetInfo::IntType PtrDiff = Target.getPtrDiffType(LangAS::Default);
229 MemberPointerInfo MPI;
230 MPI.Width = Target.getTypeWidth(PtrDiff);
231 MPI.Align = Target.getTypeAlign(PtrDiff);
232 MPI.HasPadding = false;
233 if (MPT->isMemberFunctionPointer())
234 MPI.Width *= 2;
235 return MPI;
236 }
237
238 CallingConv getDefaultMethodCallConv(bool isVariadic) const override {
239 const llvm::Triple &T = Context.getTargetInfo().getTriple();
240 if (!isVariadic && T.isWindowsGNUEnvironment() &&
241 T.getArch() == llvm::Triple::x86)
242 return CC_X86ThisCall;
243 return Context.getTargetInfo().getDefaultCallingConv();
244 }
245
246 // We cheat and just check that the class has a vtable pointer, and that it's
247 // only big enough to have a vtable pointer and nothing more (or less).
248 bool isNearlyEmpty(const CXXRecordDecl *RD) const override {
249
250 // Check that the class has a vtable pointer.
251 if (!RD->isDynamicClass())
252 return false;
253
254 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
255 CharUnits PointerSize = Context.toCharUnitsFromBits(
256 Context.getTargetInfo().getPointerWidth(LangAS::Default));
257 return Layout.getNonVirtualSize() == PointerSize;
258 }
259
260 const CXXConstructorDecl *
262 return nullptr;
263 }
264
266 CXXConstructorDecl *CD) override {}
267
269 TypedefNameDecl *DD) override {}
270
272 return nullptr;
273 }
274
276 DeclaratorDecl *DD) override {}
277
279 return nullptr;
280 }
281
282 std::unique_ptr<MangleNumberingContext>
283 createMangleNumberingContext() const override {
284 if (Context.getLangOpts().isSYCL())
285 return std::make_unique<ItaniumSYCLNumberingContext>(
286 cast<ItaniumMangleContext>(Mangler.get()));
287 return std::make_unique<ItaniumNumberingContext>(
288 cast<ItaniumMangleContext>(Mangler.get()));
289 }
290};
291}
292
294 return new ItaniumCXXABI(Ctx);
295}
296
297std::unique_ptr<MangleNumberingContext>
299 return std::make_unique<ItaniumNumberingContext>(
300 cast<ItaniumMangleContext>(Mangler));
301}
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3273
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:2980
llvm::MachO::Target Target
Definition: MachO.h:48
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:182
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:775
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:757
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:4495
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:2532
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2057
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2183
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:1021
bool isDynamicClass() const
Definition: DeclCXX.h:584
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:770
Represents a member of a struct/union/class.
Definition: Decl.h:3058
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:696
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:3250
bool isMemberFunctionPointer() const
Returns true if the member type (i.e.
Definition: Type.h:3270
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
const FieldDecl * findFirstNamedDataMember() const
Finds the first data member which has a name.
Definition: Decl.cpp:5188
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5339
RecordDecl * getDecl() const
Definition: Type.h:5349
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3585
bool isUnion() const
Definition: Decl.h:3791
Exposes information about the current target.
Definition: TargetInfo.h:213
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1235
uint64_t getPointerWidth(LangAS AddrSpace) const
Return the width of pointers on this target, for the specified address space.
Definition: TargetInfo.h:467
virtual CallingConv getDefaultCallingConv() const
Gets the default calling convention for the given target and declaration context.
Definition: TargetInfo.h:1640
IntType getPtrDiffType(LangAS AddrSpace) const
Definition: TargetInfo.h:385
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:7913
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3433
QualType getType() const
Definition: Decl.h:717
Represents a variable declaration or definition.
Definition: Decl.h:918
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:275
@ CC_X86ThisCall
Definition: Specifiers.h:279
Diagnostic wrappers for TextAPI types for error reporting.
Definition: Dominators.h:30
bool isDenseMapKeyEmpty(T V)
bool isDenseMapKeyTombstone(T V)
std::optional< bool > areDenseMapKeysEqualSpecialValues(T LHS, T RHS)
IntType
===-— Target Data Type Query Methods ----------------------------—===//
Definition: TargetInfo.h:137
static DecompositionDeclName getTombstoneKey()
llvm::DenseMapInfo< ArrayRef< const BindingDecl * > > ArrayInfo
static DecompositionDeclName getEmptyKey()
static bool isEqual(DecompositionDeclName LHS, DecompositionDeclName RHS)
static unsigned getHashValue(DecompositionDeclName Key)