Bug Summary

File:build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/clang/lib/AST/ItaniumMangle.cpp
Warning:line 296, column 28
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name ItaniumMangle.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm -resource-dir /usr/lib/llvm-16/lib/clang/16.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/clang/lib/AST -I /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/clang/include -I tools/clang/include -I include -I /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-16/lib/clang/16.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-10-03-140002-15933-1 -x c++ /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/clang/lib/AST/ItaniumMangle.cpp
1//===--- ItaniumMangle.cpp - Itanium C++ Name Mangling ----------*- C++ -*-===//
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// Implements C++ name mangling according to the Itanium C++ ABI,
10// which is used in GCC 3.2 and newer (and many compilers that are
11// ABI-compatible with GCC):
12//
13// http://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling
14//
15//===----------------------------------------------------------------------===//
16
17#include "clang/AST/ASTContext.h"
18#include "clang/AST/Attr.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclObjC.h"
22#include "clang/AST/DeclOpenMP.h"
23#include "clang/AST/DeclTemplate.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
26#include "clang/AST/ExprConcepts.h"
27#include "clang/AST/ExprObjC.h"
28#include "clang/AST/Mangle.h"
29#include "clang/AST/TypeLoc.h"
30#include "clang/Basic/ABI.h"
31#include "clang/Basic/Module.h"
32#include "clang/Basic/SourceManager.h"
33#include "clang/Basic/TargetInfo.h"
34#include "clang/Basic/Thunk.h"
35#include "llvm/ADT/StringExtras.h"
36#include "llvm/Support/ErrorHandling.h"
37#include "llvm/Support/raw_ostream.h"
38
39using namespace clang;
40
41namespace {
42
43static bool isLocalContainerContext(const DeclContext *DC) {
44 return isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC) || isa<BlockDecl>(DC);
45}
46
47static const FunctionDecl *getStructor(const FunctionDecl *fn) {
48 if (const FunctionTemplateDecl *ftd = fn->getPrimaryTemplate())
49 return ftd->getTemplatedDecl();
50
51 return fn;
52}
53
54static const NamedDecl *getStructor(const NamedDecl *decl) {
55 const FunctionDecl *fn = dyn_cast_or_null<FunctionDecl>(decl);
56 return (fn ? getStructor(fn) : decl);
57}
58
59static bool isLambda(const NamedDecl *ND) {
60 const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(ND);
61 if (!Record)
62 return false;
63
64 return Record->isLambda();
65}
66
67static const unsigned UnknownArity = ~0U;
68
69class ItaniumMangleContextImpl : public ItaniumMangleContext {
70 typedef std::pair<const DeclContext*, IdentifierInfo*> DiscriminatorKeyTy;
71 llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;
72 llvm::DenseMap<const NamedDecl*, unsigned> Uniquifier;
73 const DiscriminatorOverrideTy DiscriminatorOverride = nullptr;
74 NamespaceDecl *StdNamespace = nullptr;
75
76 bool NeedsUniqueInternalLinkageNames = false;
77
78public:
79 explicit ItaniumMangleContextImpl(
80 ASTContext &Context, DiagnosticsEngine &Diags,
81 DiscriminatorOverrideTy DiscriminatorOverride, bool IsAux = false)
82 : ItaniumMangleContext(Context, Diags, IsAux),
83 DiscriminatorOverride(DiscriminatorOverride) {}
84
85 /// @name Mangler Entry Points
86 /// @{
87
88 bool shouldMangleCXXName(const NamedDecl *D) override;
89 bool shouldMangleStringLiteral(const StringLiteral *) override {
90 return false;
91 }
92
93 bool isUniqueInternalLinkageDecl(const NamedDecl *ND) override;
94 void needsUniqueInternalLinkageNames() override {
95 NeedsUniqueInternalLinkageNames = true;
96 }
97
98 void mangleCXXName(GlobalDecl GD, raw_ostream &) override;
99 void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk,
100 raw_ostream &) override;
101 void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
102 const ThisAdjustment &ThisAdjustment,
103 raw_ostream &) override;
104 void mangleReferenceTemporary(const VarDecl *D, unsigned ManglingNumber,
105 raw_ostream &) override;
106 void mangleCXXVTable(const CXXRecordDecl *RD, raw_ostream &) override;
107 void mangleCXXVTT(const CXXRecordDecl *RD, raw_ostream &) override;
108 void mangleCXXCtorVTable(const CXXRecordDecl *RD, int64_t Offset,
109 const CXXRecordDecl *Type, raw_ostream &) override;
110 void mangleCXXRTTI(QualType T, raw_ostream &) override;
111 void mangleCXXRTTIName(QualType T, raw_ostream &) override;
112 void mangleTypeName(QualType T, raw_ostream &) override;
113
114 void mangleCXXCtorComdat(const CXXConstructorDecl *D, raw_ostream &) override;
115 void mangleCXXDtorComdat(const CXXDestructorDecl *D, raw_ostream &) override;
116 void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &) override;
117 void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
118 void mangleDynamicAtExitDestructor(const VarDecl *D,
119 raw_ostream &Out) override;
120 void mangleDynamicStermFinalizer(const VarDecl *D, raw_ostream &Out) override;
121 void mangleSEHFilterExpression(const NamedDecl *EnclosingDecl,
122 raw_ostream &Out) override;
123 void mangleSEHFinallyBlock(const NamedDecl *EnclosingDecl,
124 raw_ostream &Out) override;
125 void mangleItaniumThreadLocalInit(const VarDecl *D, raw_ostream &) override;
126 void mangleItaniumThreadLocalWrapper(const VarDecl *D,
127 raw_ostream &) override;
128
129 void mangleStringLiteral(const StringLiteral *, raw_ostream &) override;
130
131 void mangleLambdaSig(const CXXRecordDecl *Lambda, raw_ostream &) override;
132
133 void mangleModuleInitializer(const Module *Module, raw_ostream &) override;
134
135 bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
136 // Lambda closure types are already numbered.
137 if (isLambda(ND))
138 return false;
139
140 // Anonymous tags are already numbered.
141 if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
142 if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl())
143 return false;
144 }
145
146 // Use the canonical number for externally visible decls.
147 if (ND->isExternallyVisible()) {
148 unsigned discriminator = getASTContext().getManglingNumber(ND, isAux());
149 if (discriminator == 1)
150 return false;
151 disc = discriminator - 2;
152 return true;
153 }
154
155 // Make up a reasonable number for internal decls.
156 unsigned &discriminator = Uniquifier[ND];
157 if (!discriminator) {
158 const DeclContext *DC = getEffectiveDeclContext(ND);
159 discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
160 }
161 if (discriminator == 1)
162 return false;
163 disc = discriminator-2;
164 return true;
165 }
166
167 std::string getLambdaString(const CXXRecordDecl *Lambda) override {
168 // This function matches the one in MicrosoftMangle, which returns
169 // the string that is used in lambda mangled names.
170 assert(Lambda->isLambda() && "RD must be a lambda!")(static_cast <bool> (Lambda->isLambda() && "RD must be a lambda!"
) ? void (0) : __assert_fail ("Lambda->isLambda() && \"RD must be a lambda!\""
, "clang/lib/AST/ItaniumMangle.cpp", 170, __extension__ __PRETTY_FUNCTION__
))
;
171 std::string Name("<lambda");
172 Decl *LambdaContextDecl = Lambda->getLambdaContextDecl();
173 unsigned LambdaManglingNumber = Lambda->getLambdaManglingNumber();
174 unsigned LambdaId;
175 const ParmVarDecl *Parm = dyn_cast_or_null<ParmVarDecl>(LambdaContextDecl);
176 const FunctionDecl *Func =
177 Parm ? dyn_cast<FunctionDecl>(Parm->getDeclContext()) : nullptr;
178
179 if (Func) {
180 unsigned DefaultArgNo =
181 Func->getNumParams() - Parm->getFunctionScopeIndex();
182 Name += llvm::utostr(DefaultArgNo);
183 Name += "_";
184 }
185
186 if (LambdaManglingNumber)
187 LambdaId = LambdaManglingNumber;
188 else
189 LambdaId = getAnonymousStructIdForDebugInfo(Lambda);
190
191 Name += llvm::utostr(LambdaId);
192 Name += '>';
193 return Name;
194 }
195
196 DiscriminatorOverrideTy getDiscriminatorOverride() const override {
197 return DiscriminatorOverride;
198 }
199
200 NamespaceDecl *getStdNamespace();
201
202 const DeclContext *getEffectiveDeclContext(const Decl *D);
203 const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
204 return getEffectiveDeclContext(cast<Decl>(DC));
205 }
206
207 bool isInternalLinkageDecl(const NamedDecl *ND);
208 const DeclContext *IgnoreLinkageSpecDecls(const DeclContext *DC);
209
210 /// @}
211};
212
213/// Manage the mangling of a single name.
214class CXXNameMangler {
215 ItaniumMangleContextImpl &Context;
216 raw_ostream &Out;
217 bool NullOut = false;
218 /// In the "DisableDerivedAbiTags" mode derived ABI tags are not calculated.
219 /// This mode is used when mangler creates another mangler recursively to
220 /// calculate ABI tags for the function return value or the variable type.
221 /// Also it is required to avoid infinite recursion in some cases.
222 bool DisableDerivedAbiTags = false;
223
224 /// The "structor" is the top-level declaration being mangled, if
225 /// that's not a template specialization; otherwise it's the pattern
226 /// for that specialization.
227 const NamedDecl *Structor;
228 unsigned StructorType = 0;
229
230 /// The next substitution sequence number.
231 unsigned SeqID = 0;
232
233 class FunctionTypeDepthState {
234 unsigned Bits;
235
236 enum { InResultTypeMask = 1 };
237
238 public:
239 FunctionTypeDepthState() : Bits(0) {}
240
241 /// The number of function types we're inside.
242 unsigned getDepth() const {
243 return Bits >> 1;
244 }
245
246 /// True if we're in the return type of the innermost function type.
247 bool isInResultType() const {
248 return Bits & InResultTypeMask;
249 }
250
251 FunctionTypeDepthState push() {
252 FunctionTypeDepthState tmp = *this;
253 Bits = (Bits & ~InResultTypeMask) + 2;
254 return tmp;
255 }
256
257 void enterResultType() {
258 Bits |= InResultTypeMask;
259 }
260
261 void leaveResultType() {
262 Bits &= ~InResultTypeMask;
263 }
264
265 void pop(FunctionTypeDepthState saved) {
266 assert(getDepth() == saved.getDepth() + 1)(static_cast <bool> (getDepth() == saved.getDepth() + 1
) ? void (0) : __assert_fail ("getDepth() == saved.getDepth() + 1"
, "clang/lib/AST/ItaniumMangle.cpp", 266, __extension__ __PRETTY_FUNCTION__
))
;
267 Bits = saved.Bits;
268 }
269
270 } FunctionTypeDepth;
271
272 // abi_tag is a gcc attribute, taking one or more strings called "tags".
273 // The goal is to annotate against which version of a library an object was
274 // built and to be able to provide backwards compatibility ("dual abi").
275 // For more information see docs/ItaniumMangleAbiTags.rst.
276 typedef SmallVector<StringRef, 4> AbiTagList;
277
278 // State to gather all implicit and explicit tags used in a mangled name.
279 // Must always have an instance of this while emitting any name to keep
280 // track.
281 class AbiTagState final {
282 public:
283 explicit AbiTagState(AbiTagState *&Head) : LinkHead(Head) {
284 Parent = LinkHead;
285 LinkHead = this;
286 }
287
288 // No copy, no move.
289 AbiTagState(const AbiTagState &) = delete;
290 AbiTagState &operator=(const AbiTagState &) = delete;
291
292 ~AbiTagState() { pop(); }
293
294 void write(raw_ostream &Out, const NamedDecl *ND,
295 const AbiTagList *AdditionalAbiTags) {
296 ND = cast<NamedDecl>(ND->getCanonicalDecl());
14
Called C++ object pointer is null
297 if (!isa<FunctionDecl>(ND) && !isa<VarDecl>(ND)) {
298 assert((static_cast <bool> (!AdditionalAbiTags && "only function and variables need a list of additional abi tags"
) ? void (0) : __assert_fail ("!AdditionalAbiTags && \"only function and variables need a list of additional abi tags\""
, "clang/lib/AST/ItaniumMangle.cpp", 300, __extension__ __PRETTY_FUNCTION__
))
299 !AdditionalAbiTags &&(static_cast <bool> (!AdditionalAbiTags && "only function and variables need a list of additional abi tags"
) ? void (0) : __assert_fail ("!AdditionalAbiTags && \"only function and variables need a list of additional abi tags\""
, "clang/lib/AST/ItaniumMangle.cpp", 300, __extension__ __PRETTY_FUNCTION__
))
300 "only function and variables need a list of additional abi tags")(static_cast <bool> (!AdditionalAbiTags && "only function and variables need a list of additional abi tags"
) ? void (0) : __assert_fail ("!AdditionalAbiTags && \"only function and variables need a list of additional abi tags\""
, "clang/lib/AST/ItaniumMangle.cpp", 300, __extension__ __PRETTY_FUNCTION__
))
;
301 if (const auto *NS = dyn_cast<NamespaceDecl>(ND)) {
302 if (const auto *AbiTag = NS->getAttr<AbiTagAttr>()) {
303 UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(),
304 AbiTag->tags().end());
305 }
306 // Don't emit abi tags for namespaces.
307 return;
308 }
309 }
310
311 AbiTagList TagList;
312 if (const auto *AbiTag = ND->getAttr<AbiTagAttr>()) {
313 UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(),
314 AbiTag->tags().end());
315 TagList.insert(TagList.end(), AbiTag->tags().begin(),
316 AbiTag->tags().end());
317 }
318
319 if (AdditionalAbiTags) {
320 UsedAbiTags.insert(UsedAbiTags.end(), AdditionalAbiTags->begin(),
321 AdditionalAbiTags->end());
322 TagList.insert(TagList.end(), AdditionalAbiTags->begin(),
323 AdditionalAbiTags->end());
324 }
325
326 llvm::sort(TagList);
327 TagList.erase(std::unique(TagList.begin(), TagList.end()), TagList.end());
328
329 writeSortedUniqueAbiTags(Out, TagList);
330 }
331
332 const AbiTagList &getUsedAbiTags() const { return UsedAbiTags; }
333 void setUsedAbiTags(const AbiTagList &AbiTags) {
334 UsedAbiTags = AbiTags;
335 }
336
337 const AbiTagList &getEmittedAbiTags() const {
338 return EmittedAbiTags;
339 }
340
341 const AbiTagList &getSortedUniqueUsedAbiTags() {
342 llvm::sort(UsedAbiTags);
343 UsedAbiTags.erase(std::unique(UsedAbiTags.begin(), UsedAbiTags.end()),
344 UsedAbiTags.end());
345 return UsedAbiTags;
346 }
347
348 private:
349 //! All abi tags used implicitly or explicitly.
350 AbiTagList UsedAbiTags;
351 //! All explicit abi tags (i.e. not from namespace).
352 AbiTagList EmittedAbiTags;
353
354 AbiTagState *&LinkHead;
355 AbiTagState *Parent = nullptr;
356
357 void pop() {
358 assert(LinkHead == this &&(static_cast <bool> (LinkHead == this && "abi tag link head must point to us on destruction"
) ? void (0) : __assert_fail ("LinkHead == this && \"abi tag link head must point to us on destruction\""
, "clang/lib/AST/ItaniumMangle.cpp", 359, __extension__ __PRETTY_FUNCTION__
))
359 "abi tag link head must point to us on destruction")(static_cast <bool> (LinkHead == this && "abi tag link head must point to us on destruction"
) ? void (0) : __assert_fail ("LinkHead == this && \"abi tag link head must point to us on destruction\""
, "clang/lib/AST/ItaniumMangle.cpp", 359, __extension__ __PRETTY_FUNCTION__
))
;
360 if (Parent) {
361 Parent->UsedAbiTags.insert(Parent->UsedAbiTags.end(),
362 UsedAbiTags.begin(), UsedAbiTags.end());
363 Parent->EmittedAbiTags.insert(Parent->EmittedAbiTags.end(),
364 EmittedAbiTags.begin(),
365 EmittedAbiTags.end());
366 }
367 LinkHead = Parent;
368 }
369
370 void writeSortedUniqueAbiTags(raw_ostream &Out, const AbiTagList &AbiTags) {
371 for (const auto &Tag : AbiTags) {
372 EmittedAbiTags.push_back(Tag);
373 Out << "B";
374 Out << Tag.size();
375 Out << Tag;
376 }
377 }
378 };
379
380 AbiTagState *AbiTags = nullptr;
381 AbiTagState AbiTagsRoot;
382
383 llvm::DenseMap<uintptr_t, unsigned> Substitutions;
384 llvm::DenseMap<StringRef, unsigned> ModuleSubstitutions;
385
386 ASTContext &getASTContext() const { return Context.getASTContext(); }
387
388 bool isStd(const NamespaceDecl *NS);
389 bool isStdNamespace(const DeclContext *DC);
390
391 const RecordDecl *GetLocalClassDecl(const Decl *D);
392 const DeclContext *IgnoreLinkageSpecDecls(const DeclContext *DC);
393 bool isSpecializedAs(QualType S, llvm::StringRef Name, QualType A);
394 bool isStdCharSpecialization(const ClassTemplateSpecializationDecl *SD,
395 llvm::StringRef Name, bool HasAllocator);
396
397public:
398 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
399 const NamedDecl *D = nullptr, bool NullOut_ = false)
400 : Context(C), Out(Out_), NullOut(NullOut_), Structor(getStructor(D)),
401 AbiTagsRoot(AbiTags) {
402 // These can't be mangled without a ctor type or dtor type.
403 assert(!D || (!isa<CXXDestructorDecl>(D) &&(static_cast <bool> (!D || (!isa<CXXDestructorDecl>
(D) && !isa<CXXConstructorDecl>(D))) ? void (0)
: __assert_fail ("!D || (!isa<CXXDestructorDecl>(D) && !isa<CXXConstructorDecl>(D))"
, "clang/lib/AST/ItaniumMangle.cpp", 404, __extension__ __PRETTY_FUNCTION__
))
404 !isa<CXXConstructorDecl>(D)))(static_cast <bool> (!D || (!isa<CXXDestructorDecl>
(D) && !isa<CXXConstructorDecl>(D))) ? void (0)
: __assert_fail ("!D || (!isa<CXXDestructorDecl>(D) && !isa<CXXConstructorDecl>(D))"
, "clang/lib/AST/ItaniumMangle.cpp", 404, __extension__ __PRETTY_FUNCTION__
))
;
405 }
406 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
407 const CXXConstructorDecl *D, CXXCtorType Type)
408 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
409 AbiTagsRoot(AbiTags) {}
410 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
411 const CXXDestructorDecl *D, CXXDtorType Type)
412 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
413 AbiTagsRoot(AbiTags) {}
414
415 CXXNameMangler(CXXNameMangler &Outer, raw_ostream &Out_)
416 : Context(Outer.Context), Out(Out_), Structor(Outer.Structor),
417 StructorType(Outer.StructorType), SeqID(Outer.SeqID),
418 FunctionTypeDepth(Outer.FunctionTypeDepth), AbiTagsRoot(AbiTags),
419 Substitutions(Outer.Substitutions),
420 ModuleSubstitutions(Outer.ModuleSubstitutions) {}
421
422 CXXNameMangler(CXXNameMangler &Outer, llvm::raw_null_ostream &Out_)
423 : CXXNameMangler(Outer, (raw_ostream &)Out_) {
424 NullOut = true;
425 }
426
427 raw_ostream &getStream() { return Out; }
428
429 void disableDerivedAbiTags() { DisableDerivedAbiTags = true; }
430 static bool shouldHaveAbiTags(ItaniumMangleContextImpl &C, const VarDecl *VD);
431
432 void mangle(GlobalDecl GD);
433 void mangleCallOffset(int64_t NonVirtual, int64_t Virtual);
434 void mangleNumber(const llvm::APSInt &I);
435 void mangleNumber(int64_t Number);
436 void mangleFloat(const llvm::APFloat &F);
437 void mangleFunctionEncoding(GlobalDecl GD);
438 void mangleSeqID(unsigned SeqID);
439 void mangleName(GlobalDecl GD);
440 void mangleType(QualType T);
441 void mangleNameOrStandardSubstitution(const NamedDecl *ND);
442 void mangleLambdaSig(const CXXRecordDecl *Lambda);
443 void mangleModuleNamePrefix(StringRef Name, bool IsPartition = false);
444
445private:
446
447 bool mangleSubstitution(const NamedDecl *ND);
448 bool mangleSubstitution(NestedNameSpecifier *NNS);
449 bool mangleSubstitution(QualType T);
450 bool mangleSubstitution(TemplateName Template);
451 bool mangleSubstitution(uintptr_t Ptr);
452
453 void mangleExistingSubstitution(TemplateName name);
454
455 bool mangleStandardSubstitution(const NamedDecl *ND);
456
457 void addSubstitution(const NamedDecl *ND) {
458 ND = cast<NamedDecl>(ND->getCanonicalDecl());
459
460 addSubstitution(reinterpret_cast<uintptr_t>(ND));
461 }
462 void addSubstitution(NestedNameSpecifier *NNS) {
463 NNS = Context.getASTContext().getCanonicalNestedNameSpecifier(NNS);
464
465 addSubstitution(reinterpret_cast<uintptr_t>(NNS));
466 }
467 void addSubstitution(QualType T);
468 void addSubstitution(TemplateName Template);
469 void addSubstitution(uintptr_t Ptr);
470 // Destructive copy substitutions from other mangler.
471 void extendSubstitutions(CXXNameMangler* Other);
472
473 void mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
474 bool recursive = false);
475 void mangleUnresolvedName(NestedNameSpecifier *qualifier,
476 DeclarationName name,
477 const TemplateArgumentLoc *TemplateArgs,
478 unsigned NumTemplateArgs,
479 unsigned KnownArity = UnknownArity);
480
481 void mangleFunctionEncodingBareType(const FunctionDecl *FD);
482
483 void mangleNameWithAbiTags(GlobalDecl GD,
484 const AbiTagList *AdditionalAbiTags);
485 void mangleModuleName(const NamedDecl *ND);
486 void mangleTemplateName(const TemplateDecl *TD,
487 const TemplateArgument *TemplateArgs,
488 unsigned NumTemplateArgs);
489 void mangleUnqualifiedName(GlobalDecl GD, const DeclContext *DC,
490 const AbiTagList *AdditionalAbiTags) {
491 mangleUnqualifiedName(GD, cast<NamedDecl>(GD.getDecl())->getDeclName(), DC,
492 UnknownArity, AdditionalAbiTags);
493 }
494 void mangleUnqualifiedName(GlobalDecl GD, DeclarationName Name,
495 const DeclContext *DC, unsigned KnownArity,
496 const AbiTagList *AdditionalAbiTags);
497 void mangleUnscopedName(GlobalDecl GD, const DeclContext *DC,
498 const AbiTagList *AdditionalAbiTags);
499 void mangleUnscopedTemplateName(GlobalDecl GD, const DeclContext *DC,
500 const AbiTagList *AdditionalAbiTags);
501 void mangleSourceName(const IdentifierInfo *II);
502 void mangleRegCallName(const IdentifierInfo *II);
503 void mangleDeviceStubName(const IdentifierInfo *II);
504 void mangleSourceNameWithAbiTags(
505 const NamedDecl *ND, const AbiTagList *AdditionalAbiTags = nullptr);
506 void mangleLocalName(GlobalDecl GD,
507 const AbiTagList *AdditionalAbiTags);
508 void mangleBlockForPrefix(const BlockDecl *Block);
509 void mangleUnqualifiedBlock(const BlockDecl *Block);
510 void mangleTemplateParamDecl(const NamedDecl *Decl);
511 void mangleLambda(const CXXRecordDecl *Lambda);
512 void mangleNestedName(GlobalDecl GD, const DeclContext *DC,
513 const AbiTagList *AdditionalAbiTags,
514 bool NoFunction=false);
515 void mangleNestedName(const TemplateDecl *TD,
516 const TemplateArgument *TemplateArgs,
517 unsigned NumTemplateArgs);
518 void mangleNestedNameWithClosurePrefix(GlobalDecl GD,
519 const NamedDecl *PrefixND,
520 const AbiTagList *AdditionalAbiTags);
521 void manglePrefix(NestedNameSpecifier *qualifier);
522 void manglePrefix(const DeclContext *DC, bool NoFunction=false);
523 void manglePrefix(QualType type);
524 void mangleTemplatePrefix(GlobalDecl GD, bool NoFunction=false);
525 void mangleTemplatePrefix(TemplateName Template);
526 const NamedDecl *getClosurePrefix(const Decl *ND);
527 void mangleClosurePrefix(const NamedDecl *ND, bool NoFunction = false);
528 bool mangleUnresolvedTypeOrSimpleId(QualType DestroyedType,
529 StringRef Prefix = "");
530 void mangleOperatorName(DeclarationName Name, unsigned Arity);
531 void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity);
532 void mangleVendorQualifier(StringRef qualifier);
533 void mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST = nullptr);
534 void mangleRefQualifier(RefQualifierKind RefQualifier);
535
536 void mangleObjCMethodName(const ObjCMethodDecl *MD);
537
538 // Declare manglers for every type class.
539#define ABSTRACT_TYPE(CLASS, PARENT)
540#define NON_CANONICAL_TYPE(CLASS, PARENT)
541#define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T);
542#include "clang/AST/TypeNodes.inc"
543
544 void mangleType(const TagType*);
545 void mangleType(TemplateName);
546 static StringRef getCallingConvQualifierName(CallingConv CC);
547 void mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo info);
548 void mangleExtFunctionInfo(const FunctionType *T);
549 void mangleBareFunctionType(const FunctionProtoType *T, bool MangleReturnType,
550 const FunctionDecl *FD = nullptr);
551 void mangleNeonVectorType(const VectorType *T);
552 void mangleNeonVectorType(const DependentVectorType *T);
553 void mangleAArch64NeonVectorType(const VectorType *T);
554 void mangleAArch64NeonVectorType(const DependentVectorType *T);
555 void mangleAArch64FixedSveVectorType(const VectorType *T);
556 void mangleAArch64FixedSveVectorType(const DependentVectorType *T);
557
558 void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value);
559 void mangleFloatLiteral(QualType T, const llvm::APFloat &V);
560 void mangleFixedPointLiteral();
561 void mangleNullPointer(QualType T);
562
563 void mangleMemberExprBase(const Expr *base, bool isArrow);
564 void mangleMemberExpr(const Expr *base, bool isArrow,
565 NestedNameSpecifier *qualifier,
566 NamedDecl *firstQualifierLookup,
567 DeclarationName name,
568 const TemplateArgumentLoc *TemplateArgs,
569 unsigned NumTemplateArgs,
570 unsigned knownArity);
571 void mangleCastExpression(const Expr *E, StringRef CastEncoding);
572 void mangleInitListElements(const InitListExpr *InitList);
573 void mangleExpression(const Expr *E, unsigned Arity = UnknownArity,
574 bool AsTemplateArg = false);
575 void mangleCXXCtorType(CXXCtorType T, const CXXRecordDecl *InheritedFrom);
576 void mangleCXXDtorType(CXXDtorType T);
577
578 void mangleTemplateArgs(TemplateName TN,
579 const TemplateArgumentLoc *TemplateArgs,
580 unsigned NumTemplateArgs);
581 void mangleTemplateArgs(TemplateName TN, const TemplateArgument *TemplateArgs,
582 unsigned NumTemplateArgs);
583 void mangleTemplateArgs(TemplateName TN, const TemplateArgumentList &AL);
584 void mangleTemplateArg(TemplateArgument A, bool NeedExactType);
585 void mangleTemplateArgExpr(const Expr *E);
586 void mangleValueInTemplateArg(QualType T, const APValue &V, bool TopLevel,
587 bool NeedExactType = false);
588
589 void mangleTemplateParameter(unsigned Depth, unsigned Index);
590
591 void mangleFunctionParam(const ParmVarDecl *parm);
592
593 void writeAbiTags(const NamedDecl *ND,
594 const AbiTagList *AdditionalAbiTags);
595
596 // Returns sorted unique list of ABI tags.
597 AbiTagList makeFunctionReturnTypeTags(const FunctionDecl *FD);
598 // Returns sorted unique list of ABI tags.
599 AbiTagList makeVariableTypeTags(const VarDecl *VD);
600};
601
602}
603
604NamespaceDecl *ItaniumMangleContextImpl::getStdNamespace() {
605 if (!StdNamespace) {
606 StdNamespace = NamespaceDecl::Create(
607 getASTContext(), getASTContext().getTranslationUnitDecl(),
608 /*Inline*/ false, SourceLocation(), SourceLocation(),
609 &getASTContext().Idents.get("std"),
610 /*PrevDecl*/ nullptr);
611 StdNamespace->setImplicit();
612 }
613 return StdNamespace;
614}
615
616/// Retrieve the declaration context that should be used when mangling the given
617/// declaration.
618const DeclContext *
619ItaniumMangleContextImpl::getEffectiveDeclContext(const Decl *D) {
620 // The ABI assumes that lambda closure types that occur within
621 // default arguments live in the context of the function. However, due to
622 // the way in which Clang parses and creates function declarations, this is
623 // not the case: the lambda closure type ends up living in the context
624 // where the function itself resides, because the function declaration itself
625 // had not yet been created. Fix the context here.
626 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
627 if (RD->isLambda())
628 if (ParmVarDecl *ContextParam =
629 dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
630 return ContextParam->getDeclContext();
631 }
632
633 // Perform the same check for block literals.
634 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
635 if (ParmVarDecl *ContextParam =
636 dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))
637 return ContextParam->getDeclContext();
638 }
639
640 // On ARM and AArch64, the va_list tag is always mangled as if in the std
641 // namespace. We do not represent va_list as actually being in the std
642 // namespace in C because this would result in incorrect debug info in C,
643 // among other things. It is important for both languages to have the same
644 // mangling in order for -fsanitize=cfi-icall to work.
645 if (D == getASTContext().getVaListTagDecl()) {
646 const llvm::Triple &T = getASTContext().getTargetInfo().getTriple();
647 if (T.isARM() || T.isThumb() || T.isAArch64())
648 return getStdNamespace();
649 }
650
651 const DeclContext *DC = D->getDeclContext();
652 if (isa<CapturedDecl>(DC) || isa<OMPDeclareReductionDecl>(DC) ||
653 isa<OMPDeclareMapperDecl>(DC)) {
654 return getEffectiveDeclContext(cast<Decl>(DC));
655 }
656
657 if (const auto *VD = dyn_cast<VarDecl>(D))
658 if (VD->isExternC())
659 return getASTContext().getTranslationUnitDecl();
660
661 if (const auto *FD = dyn_cast<FunctionDecl>(D))
662 if (FD->isExternC())
663 return getASTContext().getTranslationUnitDecl();
664
665 return DC->getRedeclContext();
666}
667
668bool ItaniumMangleContextImpl::isInternalLinkageDecl(const NamedDecl *ND) {
669 if (ND && ND->getFormalLinkage() == InternalLinkage &&
670 !ND->isExternallyVisible() &&
671 getEffectiveDeclContext(ND)->isFileContext() &&
672 !ND->isInAnonymousNamespace())
673 return true;
674 return false;
675}
676
677// Check if this Function Decl needs a unique internal linkage name.
678bool ItaniumMangleContextImpl::isUniqueInternalLinkageDecl(
679 const NamedDecl *ND) {
680 if (!NeedsUniqueInternalLinkageNames || !ND)
681 return false;
682
683 const auto *FD = dyn_cast<FunctionDecl>(ND);
684 if (!FD)
685 return false;
686
687 // For C functions without prototypes, return false as their
688 // names should not be mangled.
689 if (!FD->getType()->getAs<FunctionProtoType>())
690 return false;
691
692 if (isInternalLinkageDecl(ND))
693 return true;
694
695 return false;
696}
697
698bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
699 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
700 LanguageLinkage L = FD->getLanguageLinkage();
701 // Overloadable functions need mangling.
702 if (FD->hasAttr<OverloadableAttr>())
703 return true;
704
705 // "main" is not mangled.
706 if (FD->isMain())
707 return false;
708
709 // The Windows ABI expects that we would never mangle "typical"
710 // user-defined entry points regardless of visibility or freestanding-ness.
711 //
712 // N.B. This is distinct from asking about "main". "main" has a lot of
713 // special rules associated with it in the standard while these
714 // user-defined entry points are outside of the purview of the standard.
715 // For example, there can be only one definition for "main" in a standards
716 // compliant program; however nothing forbids the existence of wmain and
717 // WinMain in the same translation unit.
718 if (FD->isMSVCRTEntryPoint())
719 return false;
720
721 // C++ functions and those whose names are not a simple identifier need
722 // mangling.
723 if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
724 return true;
725
726 // C functions are not mangled.
727 if (L == CLanguageLinkage)
728 return false;
729 }
730
731 // Otherwise, no mangling is done outside C++ mode.
732 if (!getASTContext().getLangOpts().CPlusPlus)
733 return false;
734
735 if (const auto *VD = dyn_cast<VarDecl>(D)) {
736 // Decompositions are mangled.
737 if (isa<DecompositionDecl>(VD))
738 return true;
739
740 // C variables are not mangled.
741 if (VD->isExternC())
742 return false;
743
744 // Variables at global scope are not mangled unless they have internal
745 // linkage or are specializations or are attached to a named module.
746 const DeclContext *DC = getEffectiveDeclContext(D);
747 // Check for extern variable declared locally.
748 if (DC->isFunctionOrMethod() && D->hasLinkage())
749 while (!DC->isFileContext())
750 DC = getEffectiveParentContext(DC);
751 if (DC->isTranslationUnit() && D->getFormalLinkage() != InternalLinkage &&
752 !CXXNameMangler::shouldHaveAbiTags(*this, VD) &&
753 !isa<VarTemplateSpecializationDecl>(VD) &&
754 !VD->getOwningModuleForLinkage())
755 return false;
756 }
757
758 return true;
759}
760
761void CXXNameMangler::writeAbiTags(const NamedDecl *ND,
762 const AbiTagList *AdditionalAbiTags) {
763 assert(AbiTags && "require AbiTagState")(static_cast <bool> (AbiTags && "require AbiTagState"
) ? void (0) : __assert_fail ("AbiTags && \"require AbiTagState\""
, "clang/lib/AST/ItaniumMangle.cpp", 763, __extension__ __PRETTY_FUNCTION__
))
;
8
Assuming field 'AbiTags' is non-null
9
'?' condition is true
764 AbiTags->write(Out, ND, DisableDerivedAbiTags ? nullptr : AdditionalAbiTags);
10
Assuming field 'DisableDerivedAbiTags' is true
11
'?' condition is true
12
Passing null pointer value via 2nd parameter 'ND'
13
Calling 'AbiTagState::write'
765}
766
767void CXXNameMangler::mangleSourceNameWithAbiTags(
768 const NamedDecl *ND, const AbiTagList *AdditionalAbiTags) {
769 mangleSourceName(ND->getIdentifier());
770 writeAbiTags(ND, AdditionalAbiTags);
771}
772
773void CXXNameMangler::mangle(GlobalDecl GD) {
774 // <mangled-name> ::= _Z <encoding>
775 // ::= <data name>
776 // ::= <special-name>
777 Out << "_Z";
778 if (isa<FunctionDecl>(GD.getDecl()))
779 mangleFunctionEncoding(GD);
780 else if (isa<VarDecl, FieldDecl, MSGuidDecl, TemplateParamObjectDecl,
781 BindingDecl>(GD.getDecl()))
782 mangleName(GD);
783 else if (const IndirectFieldDecl *IFD =
784 dyn_cast<IndirectFieldDecl>(GD.getDecl()))
785 mangleName(IFD->getAnonField());
786 else
787 llvm_unreachable("unexpected kind of global decl")::llvm::llvm_unreachable_internal("unexpected kind of global decl"
, "clang/lib/AST/ItaniumMangle.cpp", 787)
;
788}
789
790void CXXNameMangler::mangleFunctionEncoding(GlobalDecl GD) {
791 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
792 // <encoding> ::= <function name> <bare-function-type>
793
794 // Don't mangle in the type if this isn't a decl we should typically mangle.
795 if (!Context.shouldMangleDeclName(FD)) {
796 mangleName(GD);
797 return;
798 }
799
800 AbiTagList ReturnTypeAbiTags = makeFunctionReturnTypeTags(FD);
801 if (ReturnTypeAbiTags.empty()) {
802 // There are no tags for return type, the simplest case.
803 mangleName(GD);
804 mangleFunctionEncodingBareType(FD);
805 return;
806 }
807
808 // Mangle function name and encoding to temporary buffer.
809 // We have to output name and encoding to the same mangler to get the same
810 // substitution as it will be in final mangling.
811 SmallString<256> FunctionEncodingBuf;
812 llvm::raw_svector_ostream FunctionEncodingStream(FunctionEncodingBuf);
813 CXXNameMangler FunctionEncodingMangler(*this, FunctionEncodingStream);
814 // Output name of the function.
815 FunctionEncodingMangler.disableDerivedAbiTags();
816 FunctionEncodingMangler.mangleNameWithAbiTags(FD, nullptr);
817
818 // Remember length of the function name in the buffer.
819 size_t EncodingPositionStart = FunctionEncodingStream.str().size();
820 FunctionEncodingMangler.mangleFunctionEncodingBareType(FD);
821
822 // Get tags from return type that are not present in function name or
823 // encoding.
824 const AbiTagList &UsedAbiTags =
825 FunctionEncodingMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
826 AbiTagList AdditionalAbiTags(ReturnTypeAbiTags.size());
827 AdditionalAbiTags.erase(
828 std::set_difference(ReturnTypeAbiTags.begin(), ReturnTypeAbiTags.end(),
829 UsedAbiTags.begin(), UsedAbiTags.end(),
830 AdditionalAbiTags.begin()),
831 AdditionalAbiTags.end());
832
833 // Output name with implicit tags and function encoding from temporary buffer.
834 mangleNameWithAbiTags(FD, &AdditionalAbiTags);
835 Out << FunctionEncodingStream.str().substr(EncodingPositionStart);
836
837 // Function encoding could create new substitutions so we have to add
838 // temp mangled substitutions to main mangler.
839 extendSubstitutions(&FunctionEncodingMangler);
840}
841
842void CXXNameMangler::mangleFunctionEncodingBareType(const FunctionDecl *FD) {
843 if (FD->hasAttr<EnableIfAttr>()) {
844 FunctionTypeDepthState Saved = FunctionTypeDepth.push();
845 Out << "Ua9enable_ifI";
846 for (AttrVec::const_iterator I = FD->getAttrs().begin(),
847 E = FD->getAttrs().end();
848 I != E; ++I) {
849 EnableIfAttr *EIA = dyn_cast<EnableIfAttr>(*I);
850 if (!EIA)
851 continue;
852 if (Context.getASTContext().getLangOpts().getClangABICompat() >
853 LangOptions::ClangABI::Ver11) {
854 mangleTemplateArgExpr(EIA->getCond());
855 } else {
856 // Prior to Clang 12, we hardcoded the X/E around enable-if's argument,
857 // even though <template-arg> should not include an X/E around
858 // <expr-primary>.
859 Out << 'X';
860 mangleExpression(EIA->getCond());
861 Out << 'E';
862 }
863 }
864 Out << 'E';
865 FunctionTypeDepth.pop(Saved);
866 }
867
868 // When mangling an inheriting constructor, the bare function type used is
869 // that of the inherited constructor.
870 if (auto *CD = dyn_cast<CXXConstructorDecl>(FD))
871 if (auto Inherited = CD->getInheritedConstructor())
872 FD = Inherited.getConstructor();
873
874 // Whether the mangling of a function type includes the return type depends on
875 // the context and the nature of the function. The rules for deciding whether
876 // the return type is included are:
877 //
878 // 1. Template functions (names or types) have return types encoded, with
879 // the exceptions listed below.
880 // 2. Function types not appearing as part of a function name mangling,
881 // e.g. parameters, pointer types, etc., have return type encoded, with the
882 // exceptions listed below.
883 // 3. Non-template function names do not have return types encoded.
884 //
885 // The exceptions mentioned in (1) and (2) above, for which the return type is
886 // never included, are
887 // 1. Constructors.
888 // 2. Destructors.
889 // 3. Conversion operator functions, e.g. operator int.
890 bool MangleReturnType = false;
891 if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) {
892 if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD) ||
893 isa<CXXConversionDecl>(FD)))
894 MangleReturnType = true;
895
896 // Mangle the type of the primary template.
897 FD = PrimaryTemplate->getTemplatedDecl();
898 }
899
900 mangleBareFunctionType(FD->getType()->castAs<FunctionProtoType>(),
901 MangleReturnType, FD);
902}
903
904/// Return whether a given namespace is the 'std' namespace.
905bool CXXNameMangler::isStd(const NamespaceDecl *NS) {
906 if (!Context.getEffectiveParentContext(NS)->isTranslationUnit())
907 return false;
908
909 const IdentifierInfo *II = NS->getOriginalNamespace()->getIdentifier();
910 return II && II->isStr("std");
911}
912
913// isStdNamespace - Return whether a given decl context is a toplevel 'std'
914// namespace.
915bool CXXNameMangler::isStdNamespace(const DeclContext *DC) {
916 if (!DC->isNamespace())
917 return false;
918
919 return isStd(cast<NamespaceDecl>(DC));
920}
921
922static const GlobalDecl
923isTemplate(GlobalDecl GD, const TemplateArgumentList *&TemplateArgs) {
924 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
925 // Check if we have a function template.
926 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
927 if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
928 TemplateArgs = FD->getTemplateSpecializationArgs();
929 return GD.getWithDecl(TD);
930 }
931 }
932
933 // Check if we have a class template.
934 if (const ClassTemplateSpecializationDecl *Spec =
935 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
936 TemplateArgs = &Spec->getTemplateArgs();
937 return GD.getWithDecl(Spec->getSpecializedTemplate());
938 }
939
940 // Check if we have a variable template.
941 if (const VarTemplateSpecializationDecl *Spec =
942 dyn_cast<VarTemplateSpecializationDecl>(ND)) {
943 TemplateArgs = &Spec->getTemplateArgs();
944 return GD.getWithDecl(Spec->getSpecializedTemplate());
945 }
946
947 return GlobalDecl();
948}
949
950static TemplateName asTemplateName(GlobalDecl GD) {
951 const TemplateDecl *TD = dyn_cast_or_null<TemplateDecl>(GD.getDecl());
952 return TemplateName(const_cast<TemplateDecl*>(TD));
953}
954
955void CXXNameMangler::mangleName(GlobalDecl GD) {
956 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
957 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
958 // Variables should have implicit tags from its type.
959 AbiTagList VariableTypeAbiTags = makeVariableTypeTags(VD);
960 if (VariableTypeAbiTags.empty()) {
961 // Simple case no variable type tags.
962 mangleNameWithAbiTags(VD, nullptr);
963 return;
964 }
965
966 // Mangle variable name to null stream to collect tags.
967 llvm::raw_null_ostream NullOutStream;
968 CXXNameMangler VariableNameMangler(*this, NullOutStream);
969 VariableNameMangler.disableDerivedAbiTags();
970 VariableNameMangler.mangleNameWithAbiTags(VD, nullptr);
971
972 // Get tags from variable type that are not present in its name.
973 const AbiTagList &UsedAbiTags =
974 VariableNameMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
975 AbiTagList AdditionalAbiTags(VariableTypeAbiTags.size());
976 AdditionalAbiTags.erase(
977 std::set_difference(VariableTypeAbiTags.begin(),
978 VariableTypeAbiTags.end(), UsedAbiTags.begin(),
979 UsedAbiTags.end(), AdditionalAbiTags.begin()),
980 AdditionalAbiTags.end());
981
982 // Output name with implicit tags.
983 mangleNameWithAbiTags(VD, &AdditionalAbiTags);
984 } else {
985 mangleNameWithAbiTags(GD, nullptr);
986 }
987}
988
989const RecordDecl *CXXNameMangler::GetLocalClassDecl(const Decl *D) {
990 const DeclContext *DC = Context.getEffectiveDeclContext(D);
991 while (!DC->isNamespace() && !DC->isTranslationUnit()) {
992 if (isLocalContainerContext(DC))
993 return dyn_cast<RecordDecl>(D);
994 D = cast<Decl>(DC);
995 DC = Context.getEffectiveDeclContext(D);
996 }
997 return nullptr;
998}
999
1000void CXXNameMangler::mangleNameWithAbiTags(GlobalDecl GD,
1001 const AbiTagList *AdditionalAbiTags) {
1002 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
1003 // <name> ::= [<module-name>] <nested-name>
1004 // ::= [<module-name>] <unscoped-name>
1005 // ::= [<module-name>] <unscoped-template-name> <template-args>
1006 // ::= <local-name>
1007 //
1008 const DeclContext *DC = Context.getEffectiveDeclContext(ND);
1009
1010 // If this is an extern variable declared locally, the relevant DeclContext
1011 // is that of the containing namespace, or the translation unit.
1012 // FIXME: This is a hack; extern variables declared locally should have
1013 // a proper semantic declaration context!
1014 if (isLocalContainerContext(DC) && ND->hasLinkage() && !isLambda(ND))
1015 while (!DC->isNamespace() && !DC->isTranslationUnit())
1016 DC = Context.getEffectiveParentContext(DC);
1017 else if (GetLocalClassDecl(ND)) {
1018 mangleLocalName(GD, AdditionalAbiTags);
1019 return;
1020 }
1021
1022 assert(!isa<LinkageSpecDecl>(DC) && "context cannot be LinkageSpecDecl")(static_cast <bool> (!isa<LinkageSpecDecl>(DC) &&
"context cannot be LinkageSpecDecl") ? void (0) : __assert_fail
("!isa<LinkageSpecDecl>(DC) && \"context cannot be LinkageSpecDecl\""
, "clang/lib/AST/ItaniumMangle.cpp", 1022, __extension__ __PRETTY_FUNCTION__
))
;
1023
1024 if (isLocalContainerContext(DC)) {
1025 mangleLocalName(GD, AdditionalAbiTags);
1026 return;
1027 }
1028
1029 // Closures can require a nested-name mangling even if they're semantically
1030 // in the global namespace.
1031 if (const NamedDecl *PrefixND = getClosurePrefix(ND)) {
1032 mangleNestedNameWithClosurePrefix(GD, PrefixND, AdditionalAbiTags);
1033 return;
1034 }
1035
1036 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
1037 // Check if we have a template.
1038 const TemplateArgumentList *TemplateArgs = nullptr;
1039 if (GlobalDecl TD = isTemplate(GD, TemplateArgs)) {
1040 mangleUnscopedTemplateName(TD, DC, AdditionalAbiTags);
1041 mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);
1042 return;
1043 }
1044
1045 mangleUnscopedName(GD, DC, AdditionalAbiTags);
1046 return;
1047 }
1048
1049 mangleNestedName(GD, DC, AdditionalAbiTags);
1050}
1051
1052void CXXNameMangler::mangleModuleName(const NamedDecl *ND) {
1053 if (ND->isExternallyVisible())
1054 if (Module *M = ND->getOwningModuleForLinkage())
1055 mangleModuleNamePrefix(M->getPrimaryModuleInterfaceName());
1056}
1057
1058// <module-name> ::= <module-subname>
1059// ::= <module-name> <module-subname>
1060// ::= <substitution>
1061// <module-subname> ::= W <source-name>
1062// ::= W P <source-name>
1063void CXXNameMangler::mangleModuleNamePrefix(StringRef Name, bool IsPartition) {
1064 // <substitution> ::= S <seq-id> _
1065 auto It = ModuleSubstitutions.find(Name);
1066 if (It != ModuleSubstitutions.end()) {
1067 Out << 'S';
1068 mangleSeqID(It->second);
1069 return;
1070 }
1071
1072 // FIXME: Preserve hierarchy in module names rather than flattening
1073 // them to strings; use Module*s as substitution keys.
1074 auto Parts = Name.rsplit('.');
1075 if (Parts.second.empty())
1076 Parts.second = Parts.first;
1077 else {
1078 mangleModuleNamePrefix(Parts.first, IsPartition);
1079 IsPartition = false;
1080 }
1081
1082 Out << 'W';
1083 if (IsPartition)
1084 Out << 'P';
1085 Out << Parts.second.size() << Parts.second;
1086 ModuleSubstitutions.insert({Name, SeqID++});
1087}
1088
1089void CXXNameMangler::mangleTemplateName(const TemplateDecl *TD,
1090 const TemplateArgument *TemplateArgs,
1091 unsigned NumTemplateArgs) {
1092 const DeclContext *DC = Context.getEffectiveDeclContext(TD);
1093
1094 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
1095 mangleUnscopedTemplateName(TD, DC, nullptr);
1096 mangleTemplateArgs(asTemplateName(TD), TemplateArgs, NumTemplateArgs);
1097 } else {
1098 mangleNestedName(TD, TemplateArgs, NumTemplateArgs);
1099 }
1100}
1101
1102void CXXNameMangler::mangleUnscopedName(GlobalDecl GD, const DeclContext *DC,
1103 const AbiTagList *AdditionalAbiTags) {
1104 // <unscoped-name> ::= <unqualified-name>
1105 // ::= St <unqualified-name> # ::std::
1106
1107 assert(!isa<LinkageSpecDecl>(DC) && "unskipped LinkageSpecDecl")(static_cast <bool> (!isa<LinkageSpecDecl>(DC) &&
"unskipped LinkageSpecDecl") ? void (0) : __assert_fail ("!isa<LinkageSpecDecl>(DC) && \"unskipped LinkageSpecDecl\""
, "clang/lib/AST/ItaniumMangle.cpp", 1107, __extension__ __PRETTY_FUNCTION__
))
;
1108 if (isStdNamespace(DC))
1109 Out << "St";
1110
1111 mangleUnqualifiedName(GD, DC, AdditionalAbiTags);
1112}
1113
1114void CXXNameMangler::mangleUnscopedTemplateName(
1115 GlobalDecl GD, const DeclContext *DC, const AbiTagList *AdditionalAbiTags) {
1116 const TemplateDecl *ND = cast<TemplateDecl>(GD.getDecl());
1117 // <unscoped-template-name> ::= <unscoped-name>
1118 // ::= <substitution>
1119 if (mangleSubstitution(ND))
1120 return;
1121
1122 // <template-template-param> ::= <template-param>
1123 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
1124 assert(!AdditionalAbiTags &&(static_cast <bool> (!AdditionalAbiTags && "template template param cannot have abi tags"
) ? void (0) : __assert_fail ("!AdditionalAbiTags && \"template template param cannot have abi tags\""
, "clang/lib/AST/ItaniumMangle.cpp", 1125, __extension__ __PRETTY_FUNCTION__
))
1125 "template template param cannot have abi tags")(static_cast <bool> (!AdditionalAbiTags && "template template param cannot have abi tags"
) ? void (0) : __assert_fail ("!AdditionalAbiTags && \"template template param cannot have abi tags\""
, "clang/lib/AST/ItaniumMangle.cpp", 1125, __extension__ __PRETTY_FUNCTION__
))
;
1126 mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
1127 } else if (isa<BuiltinTemplateDecl>(ND) || isa<ConceptDecl>(ND)) {
1128 mangleUnscopedName(GD, DC, AdditionalAbiTags);
1129 } else {
1130 mangleUnscopedName(GD.getWithDecl(ND->getTemplatedDecl()), DC,
1131 AdditionalAbiTags);
1132 }
1133
1134 addSubstitution(ND);
1135}
1136
1137void CXXNameMangler::mangleFloat(const llvm::APFloat &f) {
1138 // ABI:
1139 // Floating-point literals are encoded using a fixed-length
1140 // lowercase hexadecimal string corresponding to the internal
1141 // representation (IEEE on Itanium), high-order bytes first,
1142 // without leading zeroes. For example: "Lf bf800000 E" is -1.0f
1143 // on Itanium.
1144 // The 'without leading zeroes' thing seems to be an editorial
1145 // mistake; see the discussion on cxx-abi-dev beginning on
1146 // 2012-01-16.
1147
1148 // Our requirements here are just barely weird enough to justify
1149 // using a custom algorithm instead of post-processing APInt::toString().
1150
1151 llvm::APInt valueBits = f.bitcastToAPInt();
1152 unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4;
1153 assert(numCharacters != 0)(static_cast <bool> (numCharacters != 0) ? void (0) : __assert_fail
("numCharacters != 0", "clang/lib/AST/ItaniumMangle.cpp", 1153
, __extension__ __PRETTY_FUNCTION__))
;
1154
1155 // Allocate a buffer of the right number of characters.
1156 SmallVector<char, 20> buffer(numCharacters);
1157
1158 // Fill the buffer left-to-right.
1159 for (unsigned stringIndex = 0; stringIndex != numCharacters; ++stringIndex) {
1160 // The bit-index of the next hex digit.
1161 unsigned digitBitIndex = 4 * (numCharacters - stringIndex - 1);
1162
1163 // Project out 4 bits starting at 'digitIndex'.
1164 uint64_t hexDigit = valueBits.getRawData()[digitBitIndex / 64];
1165 hexDigit >>= (digitBitIndex % 64);
1166 hexDigit &= 0xF;
1167
1168 // Map that over to a lowercase hex digit.
1169 static const char charForHex[16] = {
1170 '0', '1', '2', '3', '4', '5', '6', '7',
1171 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
1172 };
1173 buffer[stringIndex] = charForHex[hexDigit];
1174 }
1175
1176 Out.write(buffer.data(), numCharacters);
1177}
1178
1179void CXXNameMangler::mangleFloatLiteral(QualType T, const llvm::APFloat &V) {
1180 Out << 'L';
1181 mangleType(T);
1182 mangleFloat(V);
1183 Out << 'E';
1184}
1185
1186void CXXNameMangler::mangleFixedPointLiteral() {
1187 DiagnosticsEngine &Diags = Context.getDiags();
1188 unsigned DiagID = Diags.getCustomDiagID(
1189 DiagnosticsEngine::Error, "cannot mangle fixed point literals yet");
1190 Diags.Report(DiagID);
1191}
1192
1193void CXXNameMangler::mangleNullPointer(QualType T) {
1194 // <expr-primary> ::= L <type> 0 E
1195 Out << 'L';
1196 mangleType(T);
1197 Out << "0E";
1198}
1199
1200void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
1201 if (Value.isSigned() && Value.isNegative()) {
1202 Out << 'n';
1203 Value.abs().print(Out, /*signed*/ false);
1204 } else {
1205 Value.print(Out, /*signed*/ false);
1206 }
1207}
1208
1209void CXXNameMangler::mangleNumber(int64_t Number) {
1210 // <number> ::= [n] <non-negative decimal integer>
1211 if (Number < 0) {
1212 Out << 'n';
1213 Number = -Number;
1214 }
1215
1216 Out << Number;
1217}
1218
1219void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) {
1220 // <call-offset> ::= h <nv-offset> _
1221 // ::= v <v-offset> _
1222 // <nv-offset> ::= <offset number> # non-virtual base override
1223 // <v-offset> ::= <offset number> _ <virtual offset number>
1224 // # virtual base override, with vcall offset
1225 if (!Virtual) {
1226 Out << 'h';
1227 mangleNumber(NonVirtual);
1228 Out << '_';
1229 return;
1230 }
1231
1232 Out << 'v';
1233 mangleNumber(NonVirtual);
1234 Out << '_';
1235 mangleNumber(Virtual);
1236 Out << '_';
1237}
1238
1239void CXXNameMangler::manglePrefix(QualType type) {
1240 if (const auto *TST = type->getAs<TemplateSpecializationType>()) {
1241 if (!mangleSubstitution(QualType(TST, 0))) {
1242 mangleTemplatePrefix(TST->getTemplateName());
1243
1244 // FIXME: GCC does not appear to mangle the template arguments when
1245 // the template in question is a dependent template name. Should we
1246 // emulate that badness?
1247 mangleTemplateArgs(TST->getTemplateName(), TST->getArgs(),
1248 TST->getNumArgs());
1249 addSubstitution(QualType(TST, 0));
1250 }
1251 } else if (const auto *DTST =
1252 type->getAs<DependentTemplateSpecializationType>()) {
1253 if (!mangleSubstitution(QualType(DTST, 0))) {
1254 TemplateName Template = getASTContext().getDependentTemplateName(
1255 DTST->getQualifier(), DTST->getIdentifier());
1256 mangleTemplatePrefix(Template);
1257
1258 // FIXME: GCC does not appear to mangle the template arguments when
1259 // the template in question is a dependent template name. Should we
1260 // emulate that badness?
1261 mangleTemplateArgs(Template, DTST->getArgs(), DTST->getNumArgs());
1262 addSubstitution(QualType(DTST, 0));
1263 }
1264 } else {
1265 // We use the QualType mangle type variant here because it handles
1266 // substitutions.
1267 mangleType(type);
1268 }
1269}
1270
1271/// Mangle everything prior to the base-unresolved-name in an unresolved-name.
1272///
1273/// \param recursive - true if this is being called recursively,
1274/// i.e. if there is more prefix "to the right".
1275void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
1276 bool recursive) {
1277
1278 // x, ::x
1279 // <unresolved-name> ::= [gs] <base-unresolved-name>
1280
1281 // T::x / decltype(p)::x
1282 // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name>
1283
1284 // T::N::x /decltype(p)::N::x
1285 // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
1286 // <base-unresolved-name>
1287
1288 // A::x, N::y, A<T>::z; "gs" means leading "::"
1289 // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E
1290 // <base-unresolved-name>
1291
1292 switch (qualifier->getKind()) {
1293 case NestedNameSpecifier::Global:
1294 Out << "gs";
1295
1296 // We want an 'sr' unless this is the entire NNS.
1297 if (recursive)
1298 Out << "sr";
1299
1300 // We never want an 'E' here.
1301 return;
1302
1303 case NestedNameSpecifier::Super:
1304 llvm_unreachable("Can't mangle __super specifier")::llvm::llvm_unreachable_internal("Can't mangle __super specifier"
, "clang/lib/AST/ItaniumMangle.cpp", 1304)
;
1305
1306 case NestedNameSpecifier::Namespace:
1307 if (qualifier->getPrefix())
1308 mangleUnresolvedPrefix(qualifier->getPrefix(),
1309 /*recursive*/ true);
1310 else
1311 Out << "sr";
1312 mangleSourceNameWithAbiTags(qualifier->getAsNamespace());
1313 break;
1314 case NestedNameSpecifier::NamespaceAlias:
1315 if (qualifier->getPrefix())
1316 mangleUnresolvedPrefix(qualifier->getPrefix(),
1317 /*recursive*/ true);
1318 else
1319 Out << "sr";
1320 mangleSourceNameWithAbiTags(qualifier->getAsNamespaceAlias());
1321 break;
1322
1323 case NestedNameSpecifier::TypeSpec:
1324 case NestedNameSpecifier::TypeSpecWithTemplate: {
1325 const Type *type = qualifier->getAsType();
1326
1327 // We only want to use an unresolved-type encoding if this is one of:
1328 // - a decltype
1329 // - a template type parameter
1330 // - a template template parameter with arguments
1331 // In all of these cases, we should have no prefix.
1332 if (qualifier->getPrefix()) {
1333 mangleUnresolvedPrefix(qualifier->getPrefix(),
1334 /*recursive*/ true);
1335 } else {
1336 // Otherwise, all the cases want this.
1337 Out << "sr";
1338 }
1339
1340 if (mangleUnresolvedTypeOrSimpleId(QualType(type, 0), recursive ? "N" : ""))
1341 return;
1342
1343 break;
1344 }
1345
1346 case NestedNameSpecifier::Identifier:
1347 // Member expressions can have these without prefixes.
1348 if (qualifier->getPrefix())
1349 mangleUnresolvedPrefix(qualifier->getPrefix(),
1350 /*recursive*/ true);
1351 else
1352 Out << "sr";
1353
1354 mangleSourceName(qualifier->getAsIdentifier());
1355 // An Identifier has no type information, so we can't emit abi tags for it.
1356 break;
1357 }
1358
1359 // If this was the innermost part of the NNS, and we fell out to
1360 // here, append an 'E'.
1361 if (!recursive)
1362 Out << 'E';
1363}
1364
1365/// Mangle an unresolved-name, which is generally used for names which
1366/// weren't resolved to specific entities.
1367void CXXNameMangler::mangleUnresolvedName(
1368 NestedNameSpecifier *qualifier, DeclarationName name,
1369 const TemplateArgumentLoc *TemplateArgs, unsigned NumTemplateArgs,
1370 unsigned knownArity) {
1371 if (qualifier) mangleUnresolvedPrefix(qualifier);
1372 switch (name.getNameKind()) {
1373 // <base-unresolved-name> ::= <simple-id>
1374 case DeclarationName::Identifier:
1375 mangleSourceName(name.getAsIdentifierInfo());
1376 break;
1377 // <base-unresolved-name> ::= dn <destructor-name>
1378 case DeclarationName::CXXDestructorName:
1379 Out << "dn";
1380 mangleUnresolvedTypeOrSimpleId(name.getCXXNameType());
1381 break;
1382 // <base-unresolved-name> ::= on <operator-name>
1383 case DeclarationName::CXXConversionFunctionName:
1384 case DeclarationName::CXXLiteralOperatorName:
1385 case DeclarationName::CXXOperatorName:
1386 Out << "on";
1387 mangleOperatorName(name, knownArity);
1388 break;
1389 case DeclarationName::CXXConstructorName:
1390 llvm_unreachable("Can't mangle a constructor name!")::llvm::llvm_unreachable_internal("Can't mangle a constructor name!"
, "clang/lib/AST/ItaniumMangle.cpp", 1390)
;
1391 case DeclarationName::CXXUsingDirective:
1392 llvm_unreachable("Can't mangle a using directive name!")::llvm::llvm_unreachable_internal("Can't mangle a using directive name!"
, "clang/lib/AST/ItaniumMangle.cpp", 1392)
;
1393 case DeclarationName::CXXDeductionGuideName:
1394 llvm_unreachable("Can't mangle a deduction guide name!")::llvm::llvm_unreachable_internal("Can't mangle a deduction guide name!"
, "clang/lib/AST/ItaniumMangle.cpp", 1394)
;
1395 case DeclarationName::ObjCMultiArgSelector:
1396 case DeclarationName::ObjCOneArgSelector:
1397 case DeclarationName::ObjCZeroArgSelector:
1398 llvm_unreachable("Can't mangle Objective-C selector names here!")::llvm::llvm_unreachable_internal("Can't mangle Objective-C selector names here!"
, "clang/lib/AST/ItaniumMangle.cpp", 1398)
;
1399 }
1400
1401 // The <simple-id> and on <operator-name> productions end in an optional
1402 // <template-args>.
1403 if (TemplateArgs)
1404 mangleTemplateArgs(TemplateName(), TemplateArgs, NumTemplateArgs);
1405}
1406
1407void CXXNameMangler::mangleUnqualifiedName(
1408 GlobalDecl GD, DeclarationName Name, const DeclContext *DC,
1409 unsigned KnownArity, const AbiTagList *AdditionalAbiTags) {
1410 const NamedDecl *ND = cast_or_null<NamedDecl>(GD.getDecl());
1
Assuming null pointer is passed into cast
2
'ND' initialized to a null pointer value
1411 // <unqualified-name> ::= [<module-name>] <operator-name>
1412 // ::= <ctor-dtor-name>
1413 // ::= [<module-name>] <source-name>
1414 // ::= [<module-name>] DC <source-name>* E
1415
1416 if (ND
2.1
'ND' is null
&& DC && DC->isFileContext())
1417 mangleModuleName(ND);
1418
1419 unsigned Arity = KnownArity;
1420 switch (Name.getNameKind()) {
3
Control jumps to 'case CXXDestructorName:' at line 1641
1421 case DeclarationName::Identifier: {
1422 const IdentifierInfo *II = Name.getAsIdentifierInfo();
1423
1424 // We mangle decomposition declarations as the names of their bindings.
1425 if (auto *DD = dyn_cast<DecompositionDecl>(ND)) {
1426 // FIXME: Non-standard mangling for decomposition declarations:
1427 //
1428 // <unqualified-name> ::= DC <source-name>* E
1429 //
1430 // Proposed on cxx-abi-dev on 2016-08-12
1431 Out << "DC";
1432 for (auto *BD : DD->bindings())
1433 mangleSourceName(BD->getDeclName().getAsIdentifierInfo());
1434 Out << 'E';
1435 writeAbiTags(ND, AdditionalAbiTags);
1436 break;
1437 }
1438
1439 if (auto *GD = dyn_cast<MSGuidDecl>(ND)) {
1440 // We follow MSVC in mangling GUID declarations as if they were variables
1441 // with a particular reserved name. Continue the pretense here.
1442 SmallString<sizeof("_GUID_12345678_1234_1234_1234_1234567890ab")> GUID;
1443 llvm::raw_svector_ostream GUIDOS(GUID);
1444 Context.mangleMSGuidDecl(GD, GUIDOS);
1445 Out << GUID.size() << GUID;
1446 break;
1447 }
1448
1449 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
1450 // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/63.
1451 Out << "TA";
1452 mangleValueInTemplateArg(TPO->getType().getUnqualifiedType(),
1453 TPO->getValue(), /*TopLevel=*/true);
1454 break;
1455 }
1456
1457 if (II) {
1458 // Match GCC's naming convention for internal linkage symbols, for
1459 // symbols that are not actually visible outside of this TU. GCC
1460 // distinguishes between internal and external linkage symbols in
1461 // its mangling, to support cases like this that were valid C++ prior
1462 // to DR426:
1463 //
1464 // void test() { extern void foo(); }
1465 // static void foo();
1466 //
1467 // Don't bother with the L marker for names in anonymous namespaces; the
1468 // 12_GLOBAL__N_1 mangling is quite sufficient there, and this better
1469 // matches GCC anyway, because GCC does not treat anonymous namespaces as
1470 // implying internal linkage.
1471 if (Context.isInternalLinkageDecl(ND))
1472 Out << 'L';
1473
1474 auto *FD = dyn_cast<FunctionDecl>(ND);
1475 bool IsRegCall = FD &&
1476 FD->getType()->castAs<FunctionType>()->getCallConv() ==
1477 clang::CC_X86RegCall;
1478 bool IsDeviceStub =
1479 FD && FD->hasAttr<CUDAGlobalAttr>() &&
1480 GD.getKernelReferenceKind() == KernelReferenceKind::Stub;
1481 if (IsDeviceStub)
1482 mangleDeviceStubName(II);
1483 else if (IsRegCall)
1484 mangleRegCallName(II);
1485 else
1486 mangleSourceName(II);
1487
1488 writeAbiTags(ND, AdditionalAbiTags);
1489 break;
1490 }
1491
1492 // Otherwise, an anonymous entity. We must have a declaration.
1493 assert(ND && "mangling empty name without declaration")(static_cast <bool> (ND && "mangling empty name without declaration"
) ? void (0) : __assert_fail ("ND && \"mangling empty name without declaration\""
, "clang/lib/AST/ItaniumMangle.cpp", 1493, __extension__ __PRETTY_FUNCTION__
))
;
1494
1495 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
1496 if (NS->isAnonymousNamespace()) {
1497 // This is how gcc mangles these names.
1498 Out << "12_GLOBAL__N_1";
1499 break;
1500 }
1501 }
1502
1503 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
1504 // We must have an anonymous union or struct declaration.
1505 const RecordDecl *RD = VD->getType()->castAs<RecordType>()->getDecl();
1506
1507 // Itanium C++ ABI 5.1.2:
1508 //
1509 // For the purposes of mangling, the name of an anonymous union is
1510 // considered to be the name of the first named data member found by a
1511 // pre-order, depth-first, declaration-order walk of the data members of
1512 // the anonymous union. If there is no such data member (i.e., if all of
1513 // the data members in the union are unnamed), then there is no way for
1514 // a program to refer to the anonymous union, and there is therefore no
1515 // need to mangle its name.
1516 assert(RD->isAnonymousStructOrUnion()(static_cast <bool> (RD->isAnonymousStructOrUnion() &&
"Expected anonymous struct or union!") ? void (0) : __assert_fail
("RD->isAnonymousStructOrUnion() && \"Expected anonymous struct or union!\""
, "clang/lib/AST/ItaniumMangle.cpp", 1517, __extension__ __PRETTY_FUNCTION__
))
1517 && "Expected anonymous struct or union!")(static_cast <bool> (RD->isAnonymousStructOrUnion() &&
"Expected anonymous struct or union!") ? void (0) : __assert_fail
("RD->isAnonymousStructOrUnion() && \"Expected anonymous struct or union!\""
, "clang/lib/AST/ItaniumMangle.cpp", 1517, __extension__ __PRETTY_FUNCTION__
))
;
1518 const FieldDecl *FD = RD->findFirstNamedDataMember();
1519
1520 // It's actually possible for various reasons for us to get here
1521 // with an empty anonymous struct / union. Fortunately, it
1522 // doesn't really matter what name we generate.
1523 if (!FD) break;
1524 assert(FD->getIdentifier() && "Data member name isn't an identifier!")(static_cast <bool> (FD->getIdentifier() && "Data member name isn't an identifier!"
) ? void (0) : __assert_fail ("FD->getIdentifier() && \"Data member name isn't an identifier!\""
, "clang/lib/AST/ItaniumMangle.cpp", 1524, __extension__ __PRETTY_FUNCTION__
))
;
1525
1526 mangleSourceName(FD->getIdentifier());
1527 // Not emitting abi tags: internal name anyway.
1528 break;
1529 }
1530
1531 // Class extensions have no name as a category, and it's possible
1532 // for them to be the semantic parent of certain declarations
1533 // (primarily, tag decls defined within declarations). Such
1534 // declarations will always have internal linkage, so the name
1535 // doesn't really matter, but we shouldn't crash on them. For
1536 // safety, just handle all ObjC containers here.
1537 if (isa<ObjCContainerDecl>(ND))
1538 break;
1539
1540 // We must have an anonymous struct.
1541 const TagDecl *TD = cast<TagDecl>(ND);
1542 if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
1543 assert(TD->getDeclContext() == D->getDeclContext() &&(static_cast <bool> (TD->getDeclContext() == D->getDeclContext
() && "Typedef should not be in another decl context!"
) ? void (0) : __assert_fail ("TD->getDeclContext() == D->getDeclContext() && \"Typedef should not be in another decl context!\""
, "clang/lib/AST/ItaniumMangle.cpp", 1544, __extension__ __PRETTY_FUNCTION__
))
1544 "Typedef should not be in another decl context!")(static_cast <bool> (TD->getDeclContext() == D->getDeclContext
() && "Typedef should not be in another decl context!"
) ? void (0) : __assert_fail ("TD->getDeclContext() == D->getDeclContext() && \"Typedef should not be in another decl context!\""
, "clang/lib/AST/ItaniumMangle.cpp", 1544, __extension__ __PRETTY_FUNCTION__
))
;
1545 assert(D->getDeclName().getAsIdentifierInfo() &&(static_cast <bool> (D->getDeclName().getAsIdentifierInfo
() && "Typedef was not named!") ? void (0) : __assert_fail
("D->getDeclName().getAsIdentifierInfo() && \"Typedef was not named!\""
, "clang/lib/AST/ItaniumMangle.cpp", 1546, __extension__ __PRETTY_FUNCTION__
))
1546 "Typedef was not named!")(static_cast <bool> (D->getDeclName().getAsIdentifierInfo
() && "Typedef was not named!") ? void (0) : __assert_fail
("D->getDeclName().getAsIdentifierInfo() && \"Typedef was not named!\""
, "clang/lib/AST/ItaniumMangle.cpp", 1546, __extension__ __PRETTY_FUNCTION__
))
;
1547 mangleSourceName(D->getDeclName().getAsIdentifierInfo());
1548 assert(!AdditionalAbiTags && "Type cannot have additional abi tags")(static_cast <bool> (!AdditionalAbiTags && "Type cannot have additional abi tags"
) ? void (0) : __assert_fail ("!AdditionalAbiTags && \"Type cannot have additional abi tags\""
, "clang/lib/AST/ItaniumMangle.cpp", 1548, __extension__ __PRETTY_FUNCTION__
))
;
1549 // Explicit abi tags are still possible; take from underlying type, not
1550 // from typedef.
1551 writeAbiTags(TD, nullptr);
1552 break;
1553 }
1554
1555 // <unnamed-type-name> ::= <closure-type-name>
1556 //
1557 // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
1558 // <lambda-sig> ::= <template-param-decl>* <parameter-type>+
1559 // # Parameter types or 'v' for 'void'.
1560 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
1561 llvm::Optional<unsigned> DeviceNumber =
1562 Context.getDiscriminatorOverride()(Context.getASTContext(), Record);
1563
1564 // If we have a device-number via the discriminator, use that to mangle
1565 // the lambda, otherwise use the typical lambda-mangling-number. In either
1566 // case, a '0' should be mangled as a normal unnamed class instead of as a
1567 // lambda.
1568 if (Record->isLambda() &&
1569 ((DeviceNumber && *DeviceNumber > 0) ||
1570 (!DeviceNumber && Record->getLambdaManglingNumber() > 0))) {
1571 assert(!AdditionalAbiTags &&(static_cast <bool> (!AdditionalAbiTags && "Lambda type cannot have additional abi tags"
) ? void (0) : __assert_fail ("!AdditionalAbiTags && \"Lambda type cannot have additional abi tags\""
, "clang/lib/AST/ItaniumMangle.cpp", 1572, __extension__ __PRETTY_FUNCTION__
))
1572 "Lambda type cannot have additional abi tags")(static_cast <bool> (!AdditionalAbiTags && "Lambda type cannot have additional abi tags"
) ? void (0) : __assert_fail ("!AdditionalAbiTags && \"Lambda type cannot have additional abi tags\""
, "clang/lib/AST/ItaniumMangle.cpp", 1572, __extension__ __PRETTY_FUNCTION__
))
;
1573 mangleLambda(Record);
1574 break;
1575 }
1576 }
1577
1578 if (TD->isExternallyVisible()) {
1579 unsigned UnnamedMangle =
1580 getASTContext().getManglingNumber(TD, Context.isAux());
1581 Out << "Ut";
1582 if (UnnamedMangle > 1)
1583 Out << UnnamedMangle - 2;
1584 Out << '_';
1585 writeAbiTags(TD, AdditionalAbiTags);
1586 break;
1587 }
1588
1589 // Get a unique id for the anonymous struct. If it is not a real output
1590 // ID doesn't matter so use fake one.
1591 unsigned AnonStructId = NullOut ? 0 : Context.getAnonymousStructId(TD);
1592
1593 // Mangle it as a source name in the form
1594 // [n] $_<id>
1595 // where n is the length of the string.
1596 SmallString<8> Str;
1597 Str += "$_";
1598 Str += llvm::utostr(AnonStructId);
1599
1600 Out << Str.size();
1601 Out << Str;
1602 break;
1603 }
1604
1605 case DeclarationName::ObjCZeroArgSelector:
1606 case DeclarationName::ObjCOneArgSelector:
1607 case DeclarationName::ObjCMultiArgSelector:
1608 llvm_unreachable("Can't mangle Objective-C selector names here!")::llvm::llvm_unreachable_internal("Can't mangle Objective-C selector names here!"
, "clang/lib/AST/ItaniumMangle.cpp", 1608)
;
1609
1610 case DeclarationName::CXXConstructorName: {
1611 const CXXRecordDecl *InheritedFrom = nullptr;
1612 TemplateName InheritedTemplateName;
1613 const TemplateArgumentList *InheritedTemplateArgs = nullptr;
1614 if (auto Inherited =
1615 cast<CXXConstructorDecl>(ND)->getInheritedConstructor()) {
1616 InheritedFrom = Inherited.getConstructor()->getParent();
1617 InheritedTemplateName =
1618 TemplateName(Inherited.getConstructor()->getPrimaryTemplate());
1619 InheritedTemplateArgs =
1620 Inherited.getConstructor()->getTemplateSpecializationArgs();
1621 }
1622
1623 if (ND == Structor)
1624 // If the named decl is the C++ constructor we're mangling, use the type
1625 // we were given.
1626 mangleCXXCtorType(static_cast<CXXCtorType>(StructorType), InheritedFrom);
1627 else
1628 // Otherwise, use the complete constructor name. This is relevant if a
1629 // class with a constructor is declared within a constructor.
1630 mangleCXXCtorType(Ctor_Complete, InheritedFrom);
1631
1632 // FIXME: The template arguments are part of the enclosing prefix or
1633 // nested-name, but it's more convenient to mangle them here.
1634 if (InheritedTemplateArgs)
1635 mangleTemplateArgs(InheritedTemplateName, *InheritedTemplateArgs);
1636
1637 writeAbiTags(ND, AdditionalAbiTags);
1638 break;
1639 }
1640
1641 case DeclarationName::CXXDestructorName:
1642 if (ND == Structor)
4
Assuming 'ND' is not equal to field 'Structor'
5
Taking false branch
1643 // If the named decl is the C++ destructor we're mangling, use the type we
1644 // were given.
1645 mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
1646 else
1647 // Otherwise, use the complete destructor name. This is relevant if a
1648 // class with a destructor is declared within a destructor.
1649 mangleCXXDtorType(Dtor_Complete);
1650 writeAbiTags(ND, AdditionalAbiTags);
6
Passing null pointer value via 1st parameter 'ND'
7
Calling 'CXXNameMangler::writeAbiTags'
1651 break;
1652
1653 case DeclarationName::CXXOperatorName:
1654 if (ND && Arity == UnknownArity) {
1655 Arity = cast<FunctionDecl>(ND)->getNumParams();
1656
1657 // If we have a member function, we need to include the 'this' pointer.
1658 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND))
1659 if (!MD->isStatic())
1660 Arity++;
1661 }
1662 [[fallthrough]];
1663 case DeclarationName::CXXConversionFunctionName:
1664 case DeclarationName::CXXLiteralOperatorName:
1665 mangleOperatorName(Name, Arity);
1666 writeAbiTags(ND, AdditionalAbiTags);
1667 break;
1668
1669 case DeclarationName::CXXDeductionGuideName:
1670 llvm_unreachable("Can't mangle a deduction guide name!")::llvm::llvm_unreachable_internal("Can't mangle a deduction guide name!"
, "clang/lib/AST/ItaniumMangle.cpp", 1670)
;
1671
1672 case DeclarationName::CXXUsingDirective:
1673 llvm_unreachable("Can't mangle a using directive name!")::llvm::llvm_unreachable_internal("Can't mangle a using directive name!"
, "clang/lib/AST/ItaniumMangle.cpp", 1673)
;
1674 }
1675}
1676
1677void CXXNameMangler::mangleRegCallName(const IdentifierInfo *II) {
1678 // <source-name> ::= <positive length number> __regcall3__ <identifier>
1679 // <number> ::= [n] <non-negative decimal integer>
1680 // <identifier> ::= <unqualified source code identifier>
1681 Out << II->getLength() + sizeof("__regcall3__") - 1 << "__regcall3__"
1682 << II->getName();
1683}
1684
1685void CXXNameMangler::mangleDeviceStubName(const IdentifierInfo *II) {
1686 // <source-name> ::= <positive length number> __device_stub__ <identifier>
1687 // <number> ::= [n] <non-negative decimal integer>
1688 // <identifier> ::= <unqualified source code identifier>
1689 Out << II->getLength() + sizeof("__device_stub__") - 1 << "__device_stub__"
1690 << II->getName();
1691}
1692
1693void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
1694 // <source-name> ::= <positive length number> <identifier>
1695 // <number> ::= [n] <non-negative decimal integer>
1696 // <identifier> ::= <unqualified source code identifier>
1697 Out << II->getLength() << II->getName();
1698}
1699
1700void CXXNameMangler::mangleNestedName(GlobalDecl GD,
1701 const DeclContext *DC,
1702 const AbiTagList *AdditionalAbiTags,
1703 bool NoFunction) {
1704 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
1705 // <nested-name>
1706 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
1707 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
1708 // <template-args> E
1709
1710 Out << 'N';
1711 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) {
1712 Qualifiers MethodQuals = Method->getMethodQualifiers();
1713 // We do not consider restrict a distinguishing attribute for overloading
1714 // purposes so we must not mangle it.
1715 MethodQuals.removeRestrict();
1716 mangleQualifiers(MethodQuals);
1717 mangleRefQualifier(Method->getRefQualifier());
1718 }
1719
1720 // Check if we have a template.
1721 const TemplateArgumentList *TemplateArgs = nullptr;
1722 if (GlobalDecl TD = isTemplate(GD, TemplateArgs)) {
1723 mangleTemplatePrefix(TD, NoFunction);
1724 mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);
1725 } else {
1726 manglePrefix(DC, NoFunction);
1727 mangleUnqualifiedName(GD, DC, AdditionalAbiTags);
1728 }
1729
1730 Out << 'E';
1731}
1732void CXXNameMangler::mangleNestedName(const TemplateDecl *TD,
1733 const TemplateArgument *TemplateArgs,
1734 unsigned NumTemplateArgs) {
1735 // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
1736
1737 Out << 'N';
1738
1739 mangleTemplatePrefix(TD);
1740 mangleTemplateArgs(asTemplateName(TD), TemplateArgs, NumTemplateArgs);
1741
1742 Out << 'E';
1743}
1744
1745void CXXNameMangler::mangleNestedNameWithClosurePrefix(
1746 GlobalDecl GD, const NamedDecl *PrefixND,
1747 const AbiTagList *AdditionalAbiTags) {
1748 // A <closure-prefix> represents a variable or field, not a regular
1749 // DeclContext, so needs special handling. In this case we're mangling a
1750 // limited form of <nested-name>:
1751 //
1752 // <nested-name> ::= N <closure-prefix> <closure-type-name> E
1753
1754 Out << 'N';
1755
1756 mangleClosurePrefix(PrefixND);
1757 mangleUnqualifiedName(GD, nullptr, AdditionalAbiTags);
1758
1759 Out << 'E';
1760}
1761
1762static GlobalDecl getParentOfLocalEntity(const DeclContext *DC) {
1763 GlobalDecl GD;
1764 // The Itanium spec says:
1765 // For entities in constructors and destructors, the mangling of the
1766 // complete object constructor or destructor is used as the base function
1767 // name, i.e. the C1 or D1 version.
1768 if (auto *CD = dyn_cast<CXXConstructorDecl>(DC))
1769 GD = GlobalDecl(CD, Ctor_Complete);
1770 else if (auto *DD = dyn_cast<CXXDestructorDecl>(DC))
1771 GD = GlobalDecl(DD, Dtor_Complete);
1772 else
1773 GD = GlobalDecl(cast<FunctionDecl>(DC));
1774 return GD;
1775}
1776
1777void CXXNameMangler::mangleLocalName(GlobalDecl GD,
1778 const AbiTagList *AdditionalAbiTags) {
1779 const Decl *D = GD.getDecl();
1780 // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
1781 // := Z <function encoding> E s [<discriminator>]
1782 // <local-name> := Z <function encoding> E d [ <parameter number> ]
1783 // _ <entity name>
1784 // <discriminator> := _ <non-negative number>
1785 assert(isa<NamedDecl>(D) || isa<BlockDecl>(D))(static_cast <bool> (isa<NamedDecl>(D) || isa<
BlockDecl>(D)) ? void (0) : __assert_fail ("isa<NamedDecl>(D) || isa<BlockDecl>(D)"
, "clang/lib/AST/ItaniumMangle.cpp", 1785, __extension__ __PRETTY_FUNCTION__
))
;
1786 const RecordDecl *RD = GetLocalClassDecl(D);
1787 const DeclContext *DC = Context.getEffectiveDeclContext(RD ? RD : D);
1788
1789 Out << 'Z';
1790
1791 {
1792 AbiTagState LocalAbiTags(AbiTags);
1793
1794 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))
1795 mangleObjCMethodName(MD);
1796 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC))
1797 mangleBlockForPrefix(BD);
1798 else
1799 mangleFunctionEncoding(getParentOfLocalEntity(DC));
1800
1801 // Implicit ABI tags (from namespace) are not available in the following
1802 // entity; reset to actually emitted tags, which are available.
1803 LocalAbiTags.setUsedAbiTags(LocalAbiTags.getEmittedAbiTags());
1804 }
1805
1806 Out << 'E';
1807
1808 // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
1809 // be a bug that is fixed in trunk.
1810
1811 if (RD) {
1812 // The parameter number is omitted for the last parameter, 0 for the
1813 // second-to-last parameter, 1 for the third-to-last parameter, etc. The
1814 // <entity name> will of course contain a <closure-type-name>: Its
1815 // numbering will be local to the particular argument in which it appears
1816 // -- other default arguments do not affect its encoding.
1817 const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD);
1818 if (CXXRD && CXXRD->isLambda()) {
1819 if (const ParmVarDecl *Parm
1820 = dyn_cast_or_null<ParmVarDecl>(CXXRD->getLambdaContextDecl())) {
1821 if (const FunctionDecl *Func
1822 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1823 Out << 'd';
1824 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1825 if (Num > 1)
1826 mangleNumber(Num - 2);
1827 Out << '_';
1828 }
1829 }
1830 }
1831
1832 // Mangle the name relative to the closest enclosing function.
1833 // equality ok because RD derived from ND above
1834 if (D == RD) {
1835 mangleUnqualifiedName(RD, DC, AdditionalAbiTags);
1836 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1837 if (const NamedDecl *PrefixND = getClosurePrefix(BD))
1838 mangleClosurePrefix(PrefixND, true /*NoFunction*/);
1839 else
1840 manglePrefix(Context.getEffectiveDeclContext(BD), true /*NoFunction*/);
1841 assert(!AdditionalAbiTags && "Block cannot have additional abi tags")(static_cast <bool> (!AdditionalAbiTags && "Block cannot have additional abi tags"
) ? void (0) : __assert_fail ("!AdditionalAbiTags && \"Block cannot have additional abi tags\""
, "clang/lib/AST/ItaniumMangle.cpp", 1841, __extension__ __PRETTY_FUNCTION__
))
;
1842 mangleUnqualifiedBlock(BD);
1843 } else {
1844 const NamedDecl *ND = cast<NamedDecl>(D);
1845 mangleNestedName(GD, Context.getEffectiveDeclContext(ND),
1846 AdditionalAbiTags, true /*NoFunction*/);
1847 }
1848 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1849 // Mangle a block in a default parameter; see above explanation for
1850 // lambdas.
1851 if (const ParmVarDecl *Parm
1852 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) {
1853 if (const FunctionDecl *Func
1854 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1855 Out << 'd';
1856 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1857 if (Num > 1)
1858 mangleNumber(Num - 2);
1859 Out << '_';
1860 }
1861 }
1862
1863 assert(!AdditionalAbiTags && "Block cannot have additional abi tags")(static_cast <bool> (!AdditionalAbiTags && "Block cannot have additional abi tags"
) ? void (0) : __assert_fail ("!AdditionalAbiTags && \"Block cannot have additional abi tags\""
, "clang/lib/AST/ItaniumMangle.cpp", 1863, __extension__ __PRETTY_FUNCTION__
))
;
1864 mangleUnqualifiedBlock(BD);
1865 } else {
1866 mangleUnqualifiedName(GD, DC, AdditionalAbiTags);
1867 }
1868
1869 if (const NamedDecl *ND = dyn_cast<NamedDecl>(RD ? RD : D)) {
1870 unsigned disc;
1871 if (Context.getNextDiscriminator(ND, disc)) {
1872 if (disc < 10)
1873 Out << '_' << disc;
1874 else
1875 Out << "__" << disc << '_';
1876 }
1877 }
1878}
1879
1880void CXXNameMangler::mangleBlockForPrefix(const BlockDecl *Block) {
1881 if (GetLocalClassDecl(Block)) {
1882 mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
1883 return;
1884 }
1885 const DeclContext *DC = Context.getEffectiveDeclContext(Block);
1886 if (isLocalContainerContext(DC)) {
1887 mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
1888 return;
1889 }
1890 if (const NamedDecl *PrefixND = getClosurePrefix(Block))
1891 mangleClosurePrefix(PrefixND);
1892 else
1893 manglePrefix(DC);
1894 mangleUnqualifiedBlock(Block);
1895}
1896
1897void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) {
1898 // When trying to be ABI-compatibility with clang 12 and before, mangle a
1899 // <data-member-prefix> now, with no substitutions and no <template-args>.
1900 if (Decl *Context = Block->getBlockManglingContextDecl()) {
1901 if (getASTContext().getLangOpts().getClangABICompat() <=
1902 LangOptions::ClangABI::Ver12 &&
1903 (isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1904 Context->getDeclContext()->isRecord()) {
1905 const auto *ND = cast<NamedDecl>(Context);
1906 if (ND->getIdentifier()) {
1907 mangleSourceNameWithAbiTags(ND);
1908 Out << 'M';
1909 }
1910 }
1911 }
1912
1913 // If we have a block mangling number, use it.
1914 unsigned Number = Block->getBlockManglingNumber();
1915 // Otherwise, just make up a number. It doesn't matter what it is because
1916 // the symbol in question isn't externally visible.
1917 if (!Number)
1918 Number = Context.getBlockId(Block, false);
1919 else {
1920 // Stored mangling numbers are 1-based.
1921 --Number;
1922 }
1923 Out << "Ub";
1924 if (Number > 0)
1925 Out << Number - 1;
1926 Out << '_';
1927}
1928
1929// <template-param-decl>
1930// ::= Ty # template type parameter
1931// ::= Tn <type> # template non-type parameter
1932// ::= Tt <template-param-decl>* E # template template parameter
1933// ::= Tp <template-param-decl> # template parameter pack
1934void CXXNameMangler::mangleTemplateParamDecl(const NamedDecl *Decl) {
1935 if (auto *Ty = dyn_cast<TemplateTypeParmDecl>(Decl)) {
1936 if (Ty->isParameterPack())
1937 Out << "Tp";
1938 Out << "Ty";
1939 } else if (auto *Tn = dyn_cast<NonTypeTemplateParmDecl>(Decl)) {
1940 if (Tn->isExpandedParameterPack()) {
1941 for (unsigned I = 0, N = Tn->getNumExpansionTypes(); I != N; ++I) {
1942 Out << "Tn";
1943 mangleType(Tn->getExpansionType(I));
1944 }
1945 } else {
1946 QualType T = Tn->getType();
1947 if (Tn->isParameterPack()) {
1948 Out << "Tp";
1949 if (auto *PackExpansion = T->getAs<PackExpansionType>())
1950 T = PackExpansion->getPattern();
1951 }
1952 Out << "Tn";
1953 mangleType(T);
1954 }
1955 } else if (auto *Tt = dyn_cast<TemplateTemplateParmDecl>(Decl)) {
1956 if (Tt->isExpandedParameterPack()) {
1957 for (unsigned I = 0, N = Tt->getNumExpansionTemplateParameters(); I != N;
1958 ++I) {
1959 Out << "Tt";
1960 for (auto *Param : *Tt->getExpansionTemplateParameters(I))
1961 mangleTemplateParamDecl(Param);
1962 Out << "E";
1963 }
1964 } else {
1965 if (Tt->isParameterPack())
1966 Out << "Tp";
1967 Out << "Tt";
1968 for (auto *Param : *Tt->getTemplateParameters())
1969 mangleTemplateParamDecl(Param);
1970 Out << "E";
1971 }
1972 }
1973}
1974
1975void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) {
1976 // When trying to be ABI-compatibility with clang 12 and before, mangle a
1977 // <data-member-prefix> now, with no substitutions.
1978 if (Decl *Context = Lambda->getLambdaContextDecl()) {
1979 if (getASTContext().getLangOpts().getClangABICompat() <=
1980 LangOptions::ClangABI::Ver12 &&
1981 (isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1982 !isa<ParmVarDecl>(Context)) {
1983 if (const IdentifierInfo *Name
1984 = cast<NamedDecl>(Context)->getIdentifier()) {
1985 mangleSourceName(Name);
1986 const TemplateArgumentList *TemplateArgs = nullptr;
1987 if (GlobalDecl TD = isTemplate(cast<NamedDecl>(Context), TemplateArgs))
1988 mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);
1989 Out << 'M';
1990 }
1991 }
1992 }
1993
1994 Out << "Ul";
1995 mangleLambdaSig(Lambda);
1996 Out << "E";
1997
1998 // The number is omitted for the first closure type with a given
1999 // <lambda-sig> in a given context; it is n-2 for the nth closure type
2000 // (in lexical order) with that same <lambda-sig> and context.
2001 //
2002 // The AST keeps track of the number for us.
2003 //
2004 // In CUDA/HIP, to ensure the consistent lamba numbering between the device-
2005 // and host-side compilations, an extra device mangle context may be created
2006 // if the host-side CXX ABI has different numbering for lambda. In such case,
2007 // if the mangle context is that device-side one, use the device-side lambda
2008 // mangling number for this lambda.
2009 llvm::Optional<unsigned> DeviceNumber =
2010 Context.getDiscriminatorOverride()(Context.getASTContext(), Lambda);
2011 unsigned Number =
2012 DeviceNumber ? *DeviceNumber : Lambda->getLambdaManglingNumber();
2013
2014 assert(Number > 0 && "Lambda should be mangled as an unnamed class")(static_cast <bool> (Number > 0 && "Lambda should be mangled as an unnamed class"
) ? void (0) : __assert_fail ("Number > 0 && \"Lambda should be mangled as an unnamed class\""
, "clang/lib/AST/ItaniumMangle.cpp", 2014, __extension__ __PRETTY_FUNCTION__
))
;
2015 if (Number > 1)
2016 mangleNumber(Number - 2);
2017 Out << '_';
2018}
2019
2020void CXXNameMangler::mangleLambdaSig(const CXXRecordDecl *Lambda) {
2021 for (auto *D : Lambda->getLambdaExplicitTemplateParameters())
2022 mangleTemplateParamDecl(D);
2023 auto *Proto =
2024 Lambda->getLambdaTypeInfo()->getType()->castAs<FunctionProtoType>();
2025 mangleBareFunctionType(Proto, /*MangleReturnType=*/false,
2026 Lambda->getLambdaStaticInvoker());
2027}
2028
2029void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) {
2030 switch (qualifier->getKind()) {
2031 case NestedNameSpecifier::Global:
2032 // nothing
2033 return;
2034
2035 case NestedNameSpecifier::Super:
2036 llvm_unreachable("Can't mangle __super specifier")::llvm::llvm_unreachable_internal("Can't mangle __super specifier"
, "clang/lib/AST/ItaniumMangle.cpp", 2036)
;
2037
2038 case NestedNameSpecifier::Namespace:
2039 mangleName(qualifier->getAsNamespace());
2040 return;
2041
2042 case NestedNameSpecifier::NamespaceAlias:
2043 mangleName(qualifier->getAsNamespaceAlias()->getNamespace());
2044 return;
2045
2046 case NestedNameSpecifier::TypeSpec:
2047 case NestedNameSpecifier::TypeSpecWithTemplate:
2048 manglePrefix(QualType(qualifier->getAsType(), 0));
2049 return;
2050
2051 case NestedNameSpecifier::Identifier:
2052 // Clang 14 and before did not consider this substitutable.
2053 bool Clang14Compat = getASTContext().getLangOpts().getClangABICompat() <=
2054 LangOptions::ClangABI::Ver14;
2055 if (!Clang14Compat && mangleSubstitution(qualifier))
2056 return;
2057
2058 // Member expressions can have these without prefixes, but that
2059 // should end up in mangleUnresolvedPrefix instead.
2060 assert(qualifier->getPrefix())(static_cast <bool> (qualifier->getPrefix()) ? void (
0) : __assert_fail ("qualifier->getPrefix()", "clang/lib/AST/ItaniumMangle.cpp"
, 2060, __extension__ __PRETTY_FUNCTION__))
;
2061 manglePrefix(qualifier->getPrefix());
2062
2063 mangleSourceName(qualifier->getAsIdentifier());
2064
2065 if (!Clang14Compat)
2066 addSubstitution(qualifier);
2067 return;
2068 }
2069
2070 llvm_unreachable("unexpected nested name specifier")::llvm::llvm_unreachable_internal("unexpected nested name specifier"
, "clang/lib/AST/ItaniumMangle.cpp", 2070)
;
2071}
2072
2073void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) {
2074 // <prefix> ::= <prefix> <unqualified-name>
2075 // ::= <template-prefix> <template-args>
2076 // ::= <closure-prefix>
2077 // ::= <template-param>
2078 // ::= # empty
2079 // ::= <substitution>
2080
2081 assert(!isa<LinkageSpecDecl>(DC) && "prefix cannot be LinkageSpecDecl")(static_cast <bool> (!isa<LinkageSpecDecl>(DC) &&
"prefix cannot be LinkageSpecDecl") ? void (0) : __assert_fail
("!isa<LinkageSpecDecl>(DC) && \"prefix cannot be LinkageSpecDecl\""
, "clang/lib/AST/ItaniumMangle.cpp", 2081, __extension__ __PRETTY_FUNCTION__
))
;
2082
2083 if (DC->isTranslationUnit())
2084 return;
2085
2086 if (NoFunction && isLocalContainerContext(DC))
2087 return;
2088
2089 assert(!isLocalContainerContext(DC))(static_cast <bool> (!isLocalContainerContext(DC)) ? void
(0) : __assert_fail ("!isLocalContainerContext(DC)", "clang/lib/AST/ItaniumMangle.cpp"
, 2089, __extension__ __PRETTY_FUNCTION__))
;
2090
2091 const NamedDecl *ND = cast<NamedDecl>(DC);
2092 if (mangleSubstitution(ND))
2093 return;
2094
2095 // Check if we have a template-prefix or a closure-prefix.
2096 const TemplateArgumentList *TemplateArgs = nullptr;
2097 if (GlobalDecl TD = isTemplate(ND, TemplateArgs)) {
2098 mangleTemplatePrefix(TD);
2099 mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);
2100 } else if (const NamedDecl *PrefixND = getClosurePrefix(ND)) {
2101 mangleClosurePrefix(PrefixND, NoFunction);
2102 mangleUnqualifiedName(ND, nullptr, nullptr);
2103 } else {
2104 const DeclContext *DC = Context.getEffectiveDeclContext(ND);
2105 manglePrefix(DC, NoFunction);
2106 mangleUnqualifiedName(ND, DC, nullptr);
2107 }
2108
2109 addSubstitution(ND);
2110}
2111
2112void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) {
2113 // <template-prefix> ::= <prefix> <template unqualified-name>
2114 // ::= <template-param>
2115 // ::= <substitution>
2116 if (TemplateDecl *TD = Template.getAsTemplateDecl())
2117 return mangleTemplatePrefix(TD);
2118
2119 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
2120 assert(Dependent && "unexpected template name kind")(static_cast <bool> (Dependent && "unexpected template name kind"
) ? void (0) : __assert_fail ("Dependent && \"unexpected template name kind\""
, "clang/lib/AST/ItaniumMangle.cpp", 2120, __extension__ __PRETTY_FUNCTION__
))
;
2121
2122 // Clang 11 and before mangled the substitution for a dependent template name
2123 // after already having emitted (a substitution for) the prefix.
2124 bool Clang11Compat = getASTContext().getLangOpts().getClangABICompat() <=
2125 LangOptions::ClangABI::Ver11;
2126 if (!Clang11Compat && mangleSubstitution(Template))
2127 return;
2128
2129 if (NestedNameSpecifier *Qualifier = Dependent->getQualifier())
2130 manglePrefix(Qualifier);
2131
2132 if (Clang11Compat && mangleSubstitution(Template))
2133 return;
2134
2135 if (const IdentifierInfo *Id = Dependent->getIdentifier())
2136 mangleSourceName(Id);
2137 else
2138 mangleOperatorName(Dependent->getOperator(), UnknownArity);
2139
2140 addSubstitution(Template);
2141}
2142
2143void CXXNameMangler::mangleTemplatePrefix(GlobalDecl GD,
2144 bool NoFunction) {
2145 const TemplateDecl *ND = cast<TemplateDecl>(GD.getDecl());
2146 // <template-prefix> ::= <prefix> <template unqualified-name>
2147 // ::= <template-param>
2148 // ::= <substitution>
2149 // <template-template-param> ::= <template-param>
2150 // <substitution>
2151
2152 if (mangleSubstitution(ND))
2153 return;
2154
2155 // <template-template-param> ::= <template-param>
2156 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
2157 mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
2158 } else {
2159 const DeclContext *DC = Context.getEffectiveDeclContext(ND);
2160 manglePrefix(DC, NoFunction);
2161 if (isa<BuiltinTemplateDecl>(ND) || isa<ConceptDecl>(ND))
2162 mangleUnqualifiedName(GD, DC, nullptr);
2163 else
2164 mangleUnqualifiedName(GD.getWithDecl(ND->getTemplatedDecl()), DC,
2165 nullptr);
2166 }
2167
2168 addSubstitution(ND);
2169}
2170
2171const NamedDecl *CXXNameMangler::getClosurePrefix(const Decl *ND) {
2172 if (getASTContext().getLangOpts().getClangABICompat() <=
2173 LangOptions::ClangABI::Ver12)
2174 return nullptr;
2175
2176 const NamedDecl *Context = nullptr;
2177 if (auto *Block = dyn_cast<BlockDecl>(ND)) {
2178 Context = dyn_cast_or_null<NamedDecl>(Block->getBlockManglingContextDecl());
2179 } else if (auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
2180 if (RD->isLambda())
2181 Context = dyn_cast_or_null<NamedDecl>(RD->getLambdaContextDecl());
2182 }
2183 if (!Context)
2184 return nullptr;
2185
2186 // Only lambdas within the initializer of a non-local variable or non-static
2187 // data member get a <closure-prefix>.
2188 if ((isa<VarDecl>(Context) && cast<VarDecl>(Context)->hasGlobalStorage()) ||
2189 isa<FieldDecl>(Context))
2190 return Context;
2191
2192 return nullptr;
2193}
2194
2195void CXXNameMangler::mangleClosurePrefix(const NamedDecl *ND, bool NoFunction) {
2196 // <closure-prefix> ::= [ <prefix> ] <unqualified-name> M
2197 // ::= <template-prefix> <template-args> M
2198 if (mangleSubstitution(ND))
2199 return;
2200
2201 const TemplateArgumentList *TemplateArgs = nullptr;
2202 if (GlobalDecl TD = isTemplate(ND, TemplateArgs)) {
2203 mangleTemplatePrefix(TD, NoFunction);
2204 mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);
2205 } else {
2206 const auto *DC = Context.getEffectiveDeclContext(ND);
2207 manglePrefix(DC, NoFunction);
2208 mangleUnqualifiedName(ND, DC, nullptr);
2209 }
2210
2211 Out << 'M';
2212
2213 addSubstitution(ND);
2214}
2215
2216/// Mangles a template name under the production <type>. Required for
2217/// template template arguments.
2218/// <type> ::= <class-enum-type>
2219/// ::= <template-param>
2220/// ::= <substitution>
2221void CXXNameMangler::mangleType(TemplateName TN) {
2222 if (mangleSubstitution(TN))
2223 return;
2224
2225 TemplateDecl *TD = nullptr;
2226
2227 switch (TN.getKind()) {
2228 case TemplateName::QualifiedTemplate:
2229 case TemplateName::UsingTemplate:
2230 case TemplateName::Template:
2231 TD = TN.getAsTemplateDecl();
2232 goto HaveDecl;
2233
2234 HaveDecl:
2235 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TD))
2236 mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
2237 else
2238 mangleName(TD);
2239 break;
2240
2241 case TemplateName::OverloadedTemplate:
2242 case TemplateName::AssumedTemplate:
2243 llvm_unreachable("can't mangle an overloaded template name as a <type>")::llvm::llvm_unreachable_internal("can't mangle an overloaded template name as a <type>"
, "clang/lib/AST/ItaniumMangle.cpp", 2243)
;
2244
2245 case TemplateName::DependentTemplate: {
2246 const DependentTemplateName *Dependent = TN.getAsDependentTemplateName();
2247 assert(Dependent->isIdentifier())(static_cast <bool> (Dependent->isIdentifier()) ? void
(0) : __assert_fail ("Dependent->isIdentifier()", "clang/lib/AST/ItaniumMangle.cpp"
, 2247, __extension__ __PRETTY_FUNCTION__))
;
2248
2249 // <class-enum-type> ::= <name>
2250 // <name> ::= <nested-name>
2251 mangleUnresolvedPrefix(Dependent->getQualifier());
2252 mangleSourceName(Dependent->getIdentifier());
2253 break;
2254 }
2255
2256 case TemplateName::SubstTemplateTemplateParm: {
2257 // Substituted template parameters are mangled as the substituted
2258 // template. This will check for the substitution twice, which is
2259 // fine, but we have to return early so that we don't try to *add*
2260 // the substitution twice.
2261 SubstTemplateTemplateParmStorage *subst
2262 = TN.getAsSubstTemplateTemplateParm();
2263 mangleType(subst->getReplacement());
2264 return;
2265 }
2266
2267 case TemplateName::SubstTemplateTemplateParmPack: {
2268 // FIXME: not clear how to mangle this!
2269 // template <template <class> class T...> class A {
2270 // template <template <class> class U...> void foo(B<T,U> x...);
2271 // };
2272 Out << "_SUBSTPACK_";
2273 break;
2274 }
2275 }
2276
2277 addSubstitution(TN);
2278}
2279
2280bool CXXNameMangler::mangleUnresolvedTypeOrSimpleId(QualType Ty,
2281 StringRef Prefix) {
2282 // Only certain other types are valid as prefixes; enumerate them.
2283 switch (Ty->getTypeClass()) {
2284 case Type::Builtin:
2285 case Type::Complex:
2286 case Type::Adjusted:
2287 case Type::Decayed:
2288 case Type::Pointer:
2289 case Type::BlockPointer:
2290 case Type::LValueReference:
2291 case Type::RValueReference:
2292 case Type::MemberPointer:
2293 case Type::ConstantArray:
2294 case Type::IncompleteArray:
2295 case Type::VariableArray:
2296 case Type::DependentSizedArray:
2297 case Type::DependentAddressSpace:
2298 case Type::DependentVector:
2299 case Type::DependentSizedExtVector:
2300 case Type::Vector:
2301 case Type::ExtVector:
2302 case Type::ConstantMatrix:
2303 case Type::DependentSizedMatrix:
2304 case Type::FunctionProto:
2305 case Type::FunctionNoProto:
2306 case Type::Paren:
2307 case Type::Attributed:
2308 case Type::BTFTagAttributed:
2309 case Type::Auto:
2310 case Type::DeducedTemplateSpecialization:
2311 case Type::PackExpansion:
2312 case Type::ObjCObject:
2313 case Type::ObjCInterface:
2314 case Type::ObjCObjectPointer:
2315 case Type::ObjCTypeParam:
2316 case Type::Atomic:
2317 case Type::Pipe:
2318 case Type::MacroQualified:
2319 case Type::BitInt:
2320 case Type::DependentBitInt:
2321 llvm_unreachable("type is illegal as a nested name specifier")::llvm::llvm_unreachable_internal("type is illegal as a nested name specifier"
, "clang/lib/AST/ItaniumMangle.cpp", 2321)
;
2322
2323 case Type::SubstTemplateTypeParmPack:
2324 // FIXME: not clear how to mangle this!
2325 // template <class T...> class A {
2326 // template <class U...> void foo(decltype(T::foo(U())) x...);
2327 // };
2328 Out << "_SUBSTPACK_";
2329 break;
2330
2331 // <unresolved-type> ::= <template-param>
2332 // ::= <decltype>
2333 // ::= <template-template-param> <template-args>
2334 // (this last is not official yet)
2335 case Type::TypeOfExpr:
2336 case Type::TypeOf:
2337 case Type::Decltype:
2338 case Type::TemplateTypeParm:
2339 case Type::UnaryTransform:
2340 case Type::SubstTemplateTypeParm:
2341 unresolvedType:
2342 // Some callers want a prefix before the mangled type.
2343 Out << Prefix;
2344
2345 // This seems to do everything we want. It's not really
2346 // sanctioned for a substituted template parameter, though.
2347 mangleType(Ty);
2348
2349 // We never want to print 'E' directly after an unresolved-type,
2350 // so we return directly.
2351 return true;
2352
2353 case Type::Typedef:
2354 mangleSourceNameWithAbiTags(cast<TypedefType>(Ty)->getDecl());
2355 break;
2356
2357 case Type::UnresolvedUsing:
2358 mangleSourceNameWithAbiTags(
2359 cast<UnresolvedUsingType>(Ty)->getDecl());
2360 break;
2361
2362 case Type::Enum:
2363 case Type::Record:
2364 mangleSourceNameWithAbiTags(cast<TagType>(Ty)->getDecl());
2365 break;
2366
2367 case Type::TemplateSpecialization: {
2368 const TemplateSpecializationType *TST =
2369 cast<TemplateSpecializationType>(Ty);
2370 TemplateName TN = TST->getTemplateName();
2371 switch (TN.getKind()) {
2372 case TemplateName::Template:
2373 case TemplateName::QualifiedTemplate: {
2374 TemplateDecl *TD = TN.getAsTemplateDecl();
2375
2376 // If the base is a template template parameter, this is an
2377 // unresolved type.
2378 assert(TD && "no template for template specialization type")(static_cast <bool> (TD && "no template for template specialization type"
) ? void (0) : __assert_fail ("TD && \"no template for template specialization type\""
, "clang/lib/AST/ItaniumMangle.cpp", 2378, __extension__ __PRETTY_FUNCTION__
))
;
2379 if (isa<TemplateTemplateParmDecl>(TD))
2380 goto unresolvedType;
2381
2382 mangleSourceNameWithAbiTags(TD);
2383 break;
2384 }
2385
2386 case TemplateName::OverloadedTemplate:
2387 case TemplateName::AssumedTemplate:
2388 case TemplateName::DependentTemplate:
2389 llvm_unreachable("invalid base for a template specialization type")::llvm::llvm_unreachable_internal("invalid base for a template specialization type"
, "clang/lib/AST/ItaniumMangle.cpp", 2389)
;
2390
2391 case TemplateName::SubstTemplateTemplateParm: {
2392 SubstTemplateTemplateParmStorage *subst =
2393 TN.getAsSubstTemplateTemplateParm();
2394 mangleExistingSubstitution(subst->getReplacement());
2395 break;
2396 }
2397
2398 case TemplateName::SubstTemplateTemplateParmPack: {
2399 // FIXME: not clear how to mangle this!
2400 // template <template <class U> class T...> class A {
2401 // template <class U...> void foo(decltype(T<U>::foo) x...);
2402 // };
2403 Out << "_SUBSTPACK_";
2404 break;
2405 }
2406 case TemplateName::UsingTemplate: {
2407 TemplateDecl *TD = TN.getAsTemplateDecl();
2408 assert(TD && !isa<TemplateTemplateParmDecl>(TD))(static_cast <bool> (TD && !isa<TemplateTemplateParmDecl
>(TD)) ? void (0) : __assert_fail ("TD && !isa<TemplateTemplateParmDecl>(TD)"
, "clang/lib/AST/ItaniumMangle.cpp", 2408, __extension__ __PRETTY_FUNCTION__
))
;
2409 mangleSourceNameWithAbiTags(TD);
2410 break;
2411 }
2412 }
2413
2414 // Note: we don't pass in the template name here. We are mangling the
2415 // original source-level template arguments, so we shouldn't consider
2416 // conversions to the corresponding template parameter.
2417 // FIXME: Other compilers mangle partially-resolved template arguments in
2418 // unresolved-qualifier-levels.
2419 mangleTemplateArgs(TemplateName(), TST->getArgs(), TST->getNumArgs());
2420 break;
2421 }
2422
2423 case Type::InjectedClassName:
2424 mangleSourceNameWithAbiTags(
2425 cast<InjectedClassNameType>(Ty)->getDecl());
2426 break;
2427
2428 case Type::DependentName:
2429 mangleSourceName(cast<DependentNameType>(Ty)->getIdentifier());
2430 break;
2431
2432 case Type::DependentTemplateSpecialization: {
2433 const DependentTemplateSpecializationType *DTST =
2434 cast<DependentTemplateSpecializationType>(Ty);
2435 TemplateName Template = getASTContext().getDependentTemplateName(
2436 DTST->getQualifier(), DTST->getIdentifier());
2437 mangleSourceName(DTST->getIdentifier());
2438 mangleTemplateArgs(Template, DTST->getArgs(), DTST->getNumArgs());
2439 break;
2440 }
2441
2442 case Type::Using:
2443 return mangleUnresolvedTypeOrSimpleId(cast<UsingType>(Ty)->desugar(),
2444 Prefix);
2445 case Type::Elaborated:
2446 return mangleUnresolvedTypeOrSimpleId(
2447 cast<ElaboratedType>(Ty)->getNamedType(), Prefix);
2448 }
2449
2450 return false;
2451}
2452
2453void CXXNameMangler::mangleOperatorName(DeclarationName Name, unsigned Arity) {
2454 switch (Name.getNameKind()) {
2455 case DeclarationName::CXXConstructorName:
2456 case DeclarationName::CXXDestructorName:
2457 case DeclarationName::CXXDeductionGuideName:
2458 case DeclarationName::CXXUsingDirective:
2459 case DeclarationName::Identifier:
2460 case DeclarationName::ObjCMultiArgSelector:
2461 case DeclarationName::ObjCOneArgSelector:
2462 case DeclarationName::ObjCZeroArgSelector:
2463 llvm_unreachable("Not an operator name")::llvm::llvm_unreachable_internal("Not an operator name", "clang/lib/AST/ItaniumMangle.cpp"
, 2463)
;
2464
2465 case DeclarationName::CXXConversionFunctionName:
2466 // <operator-name> ::= cv <type> # (cast)
2467 Out << "cv";
2468 mangleType(Name.getCXXNameType());
2469 break;
2470
2471 case DeclarationName::CXXLiteralOperatorName:
2472 Out << "li";
2473 mangleSourceName(Name.getCXXLiteralIdentifier());
2474 return;
2475
2476 case DeclarationName::CXXOperatorName:
2477 mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);
2478 break;
2479 }
2480}
2481
2482void
2483CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
2484 switch (OO) {
2485 // <operator-name> ::= nw # new
2486 case OO_New: Out << "nw"; break;
2487 // ::= na # new[]
2488 case OO_Array_New: Out << "na"; break;
2489 // ::= dl # delete
2490 case OO_Delete: Out << "dl"; break;
2491 // ::= da # delete[]
2492 case OO_Array_Delete: Out << "da"; break;
2493 // ::= ps # + (unary)
2494 // ::= pl # + (binary or unknown)
2495 case OO_Plus:
2496 Out << (Arity == 1? "ps" : "pl"); break;
2497 // ::= ng # - (unary)
2498 // ::= mi # - (binary or unknown)
2499 case OO_Minus:
2500 Out << (Arity == 1? "ng" : "mi"); break;
2501 // ::= ad # & (unary)
2502 // ::= an # & (binary or unknown)
2503 case OO_Amp:
2504 Out << (Arity == 1? "ad" : "an"); break;
2505 // ::= de # * (unary)
2506 // ::= ml # * (binary or unknown)
2507 case OO_Star:
2508 // Use binary when unknown.
2509 Out << (Arity == 1? "de" : "ml"); break;
2510 // ::= co # ~
2511 case OO_Tilde: Out << "co"; break;
2512 // ::= dv # /
2513 case OO_Slash: Out << "dv"; break;
2514 // ::= rm # %
2515 case OO_Percent: Out << "rm"; break;
2516 // ::= or # |
2517 case OO_Pipe: Out << "or"; break;
2518 // ::= eo # ^
2519 case OO_Caret: Out << "eo"; break;
2520 // ::= aS # =
2521 case OO_Equal: Out << "aS"; break;
2522 // ::= pL # +=
2523 case OO_PlusEqual: Out << "pL"; break;
2524 // ::= mI # -=
2525 case OO_MinusEqual: Out << "mI"; break;
2526 // ::= mL # *=
2527 case OO_StarEqual: Out << "mL"; break;
2528 // ::= dV # /=
2529 case OO_SlashEqual: Out << "dV"; break;
2530 // ::= rM # %=
2531 case OO_PercentEqual: Out << "rM"; break;
2532 // ::= aN # &=
2533 case OO_AmpEqual: Out << "aN"; break;
2534 // ::= oR # |=
2535 case OO_PipeEqual: Out << "oR"; break;
2536 // ::= eO # ^=
2537 case OO_CaretEqual: Out << "eO"; break;
2538 // ::= ls # <<
2539 case OO_LessLess: Out << "ls"; break;
2540 // ::= rs # >>
2541 case OO_GreaterGreater: Out << "rs"; break;
2542 // ::= lS # <<=
2543 case OO_LessLessEqual: Out << "lS"; break;
2544 // ::= rS # >>=
2545 case OO_GreaterGreaterEqual: Out << "rS"; break;
2546 // ::= eq # ==
2547 case OO_EqualEqual: Out << "eq"; break;
2548 // ::= ne # !=
2549 case OO_ExclaimEqual: Out << "ne"; break;
2550 // ::= lt # <
2551 case OO_Less: Out << "lt"; break;
2552 // ::= gt # >
2553 case OO_Greater: Out << "gt"; break;
2554 // ::= le # <=
2555 case OO_LessEqual: Out << "le"; break;
2556 // ::= ge # >=
2557 case OO_GreaterEqual: Out << "ge"; break;
2558 // ::= nt # !
2559 case OO_Exclaim: Out << "nt"; break;
2560 // ::= aa # &&
2561 case OO_AmpAmp: Out << "aa"; break;
2562 // ::= oo # ||
2563 case OO_PipePipe: Out << "oo"; break;
2564 // ::= pp # ++
2565 case OO_PlusPlus: Out << "pp"; break;
2566 // ::= mm # --
2567 case OO_MinusMinus: Out << "mm"; break;
2568 // ::= cm # ,
2569 case OO_Comma: Out << "cm"; break;
2570 // ::= pm # ->*
2571 case OO_ArrowStar: Out << "pm"; break;
2572 // ::= pt # ->
2573 case OO_Arrow: Out << "pt"; break;
2574 // ::= cl # ()
2575 case OO_Call: Out << "cl"; break;
2576 // ::= ix # []
2577 case OO_Subscript: Out << "ix"; break;
2578
2579 // ::= qu # ?
2580 // The conditional operator can't be overloaded, but we still handle it when
2581 // mangling expressions.
2582 case OO_Conditional: Out << "qu"; break;
2583 // Proposal on cxx-abi-dev, 2015-10-21.
2584 // ::= aw # co_await
2585 case OO_Coawait: Out << "aw"; break;
2586 // Proposed in cxx-abi github issue 43.
2587 // ::= ss # <=>
2588 case OO_Spaceship: Out << "ss"; break;
2589
2590 case OO_None:
2591 case NUM_OVERLOADED_OPERATORS:
2592 llvm_unreachable("Not an overloaded operator")::llvm::llvm_unreachable_internal("Not an overloaded operator"
, "clang/lib/AST/ItaniumMangle.cpp", 2592)
;
2593 }
2594}
2595
2596void CXXNameMangler::mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST) {
2597 // Vendor qualifiers come first and if they are order-insensitive they must
2598 // be emitted in reversed alphabetical order, see Itanium ABI 5.1.5.
2599
2600 // <type> ::= U <addrspace-expr>
2601 if (DAST) {
2602 Out << "U2ASI";
2603 mangleExpression(DAST->getAddrSpaceExpr());
2604 Out << "E";
2605 }
2606
2607 // Address space qualifiers start with an ordinary letter.
2608 if (Quals.hasAddressSpace()) {
2609 // Address space extension:
2610 //
2611 // <type> ::= U <target-addrspace>
2612 // <type> ::= U <OpenCL-addrspace>
2613 // <type> ::= U <CUDA-addrspace>
2614
2615 SmallString<64> ASString;
2616 LangAS AS = Quals.getAddressSpace();
2617
2618 if (Context.getASTContext().addressSpaceMapManglingFor(AS)) {
2619 // <target-addrspace> ::= "AS" <address-space-number>
2620 unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS);
2621 if (TargetAS != 0 ||
2622 Context.getASTContext().getTargetAddressSpace(LangAS::Default) != 0)
2623 ASString = "AS" + llvm::utostr(TargetAS);
2624 } else {
2625 switch (AS) {
2626 default: llvm_unreachable("Not a language specific address space")::llvm::llvm_unreachable_internal("Not a language specific address space"
, "clang/lib/AST/ItaniumMangle.cpp", 2626)
;
2627 // <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" |
2628 // "private"| "generic" | "device" |
2629 // "host" ]
2630 case LangAS::opencl_global:
2631 ASString = "CLglobal";
2632 break;
2633 case LangAS::opencl_global_device:
2634 ASString = "CLdevice";
2635 break;
2636 case LangAS::opencl_global_host:
2637 ASString = "CLhost";
2638 break;
2639 case LangAS::opencl_local:
2640 ASString = "CLlocal";
2641 break;
2642 case LangAS::opencl_constant:
2643 ASString = "CLconstant";
2644 break;
2645 case LangAS::opencl_private:
2646 ASString = "CLprivate";
2647 break;
2648 case LangAS::opencl_generic:
2649 ASString = "CLgeneric";
2650 break;
2651 // <SYCL-addrspace> ::= "SY" [ "global" | "local" | "private" |
2652 // "device" | "host" ]
2653 case LangAS::sycl_global:
2654 ASString = "SYglobal";
2655 break;
2656 case LangAS::sycl_global_device:
2657 ASString = "SYdevice";
2658 break;
2659 case LangAS::sycl_global_host:
2660 ASString = "SYhost";
2661 break;
2662 case LangAS::sycl_local:
2663 ASString = "SYlocal";
2664 break;
2665 case LangAS::sycl_private:
2666 ASString = "SYprivate";
2667 break;
2668 // <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]
2669 case LangAS::cuda_device:
2670 ASString = "CUdevice";
2671 break;
2672 case LangAS::cuda_constant:
2673 ASString = "CUconstant";
2674 break;
2675 case LangAS::cuda_shared:
2676 ASString = "CUshared";
2677 break;
2678 // <ptrsize-addrspace> ::= [ "ptr32_sptr" | "ptr32_uptr" | "ptr64" ]
2679 case LangAS::ptr32_sptr:
2680 ASString = "ptr32_sptr";
2681 break;
2682 case LangAS::ptr32_uptr:
2683 ASString = "ptr32_uptr";
2684 break;
2685 case LangAS::ptr64:
2686 ASString = "ptr64";
2687 break;
2688 }
2689 }
2690 if (!ASString.empty())
2691 mangleVendorQualifier(ASString);
2692 }
2693
2694 // The ARC ownership qualifiers start with underscores.
2695 // Objective-C ARC Extension:
2696 //
2697 // <type> ::= U "__strong"
2698 // <type> ::= U "__weak"
2699 // <type> ::= U "__autoreleasing"
2700 //
2701 // Note: we emit __weak first to preserve the order as
2702 // required by the Itanium ABI.
2703 if (Quals.getObjCLifetime() == Qualifiers::OCL_Weak)
2704 mangleVendorQualifier("__weak");
2705
2706 // __unaligned (from -fms-extensions)
2707 if (Quals.hasUnaligned())
2708 mangleVendorQualifier("__unaligned");
2709
2710 // Remaining ARC ownership qualifiers.
2711 switch (Quals.getObjCLifetime()) {
2712 case Qualifiers::OCL_None:
2713 break;
2714
2715 case Qualifiers::OCL_Weak:
2716 // Do nothing as we already handled this case above.
2717 break;
2718
2719 case Qualifiers::OCL_Strong:
2720 mangleVendorQualifier("__strong");
2721 break;
2722
2723 case Qualifiers::OCL_Autoreleasing:
2724 mangleVendorQualifier("__autoreleasing");
2725 break;
2726
2727 case Qualifiers::OCL_ExplicitNone:
2728 // The __unsafe_unretained qualifier is *not* mangled, so that
2729 // __unsafe_unretained types in ARC produce the same manglings as the
2730 // equivalent (but, naturally, unqualified) types in non-ARC, providing
2731 // better ABI compatibility.
2732 //
2733 // It's safe to do this because unqualified 'id' won't show up
2734 // in any type signatures that need to be mangled.
2735 break;
2736 }
2737
2738 // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const
2739 if (Quals.hasRestrict())
2740 Out << 'r';
2741 if (Quals.hasVolatile())
2742 Out << 'V';
2743 if (Quals.hasConst())
2744 Out << 'K';
2745}
2746
2747void CXXNameMangler::mangleVendorQualifier(StringRef name) {
2748 Out << 'U' << name.size() << name;
2749}
2750
2751void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
2752 // <ref-qualifier> ::= R # lvalue reference
2753 // ::= O # rvalue-reference
2754 switch (RefQualifier) {
2755 case RQ_None:
2756 break;
2757
2758 case RQ_LValue:
2759 Out << 'R';
2760 break;
2761
2762 case RQ_RValue:
2763 Out << 'O';
2764 break;
2765 }
2766}
2767
2768void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
2769 Context.mangleObjCMethodNameAsSourceName(MD, Out);
2770}
2771
2772static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty,
2773 ASTContext &Ctx) {
2774 if (Quals)
2775 return true;
2776 if (Ty->isSpecificBuiltinType(BuiltinType::ObjCSel))
2777 return true;
2778 if (Ty->isOpenCLSpecificType())
2779 return true;
2780 if (Ty->isBuiltinType())
2781 return false;
2782 // Through to Clang 6.0, we accidentally treated undeduced auto types as
2783 // substitution candidates.
2784 if (Ctx.getLangOpts().getClangABICompat() > LangOptions::ClangABI::Ver6 &&
2785 isa<AutoType>(Ty))
2786 return false;
2787 // A placeholder type for class template deduction is substitutable with
2788 // its corresponding template name; this is handled specially when mangling
2789 // the type.
2790 if (auto *DeducedTST = Ty->getAs<DeducedTemplateSpecializationType>())
2791 if (DeducedTST->getDeducedType().isNull())
2792 return false;
2793 return true;
2794}
2795
2796void CXXNameMangler::mangleType(QualType T) {
2797 // If our type is instantiation-dependent but not dependent, we mangle
2798 // it as it was written in the source, removing any top-level sugar.
2799 // Otherwise, use the canonical type.
2800 //
2801 // FIXME: This is an approximation of the instantiation-dependent name
2802 // mangling rules, since we should really be using the type as written and
2803 // augmented via semantic analysis (i.e., with implicit conversions and
2804 // default template arguments) for any instantiation-dependent type.
2805 // Unfortunately, that requires several changes to our AST:
2806 // - Instantiation-dependent TemplateSpecializationTypes will need to be
2807 // uniqued, so that we can handle substitutions properly
2808 // - Default template arguments will need to be represented in the
2809 // TemplateSpecializationType, since they need to be mangled even though
2810 // they aren't written.
2811 // - Conversions on non-type template arguments need to be expressed, since
2812 // they can affect the mangling of sizeof/alignof.
2813 //
2814 // FIXME: This is wrong when mapping to the canonical type for a dependent
2815 // type discards instantiation-dependent portions of the type, such as for:
2816 //
2817 // template<typename T, int N> void f(T (&)[sizeof(N)]);
2818 // template<typename T> void f(T() throw(typename T::type)); (pre-C++17)
2819 //
2820 // It's also wrong in the opposite direction when instantiation-dependent,
2821 // canonically-equivalent types differ in some irrelevant portion of inner
2822 // type sugar. In such cases, we fail to form correct substitutions, eg:
2823 //
2824 // template<int N> void f(A<sizeof(N)> *, A<sizeof(N)> (*));
2825 //
2826 // We should instead canonicalize the non-instantiation-dependent parts,
2827 // regardless of whether the type as a whole is dependent or instantiation
2828 // dependent.
2829 if (!T->isInstantiationDependentType() || T->isDependentType())
2830 T = T.getCanonicalType();
2831 else {
2832 // Desugar any types that are purely sugar.
2833 do {
2834 // Don't desugar through template specialization types that aren't
2835 // type aliases. We need to mangle the template arguments as written.
2836 if (const TemplateSpecializationType *TST
2837 = dyn_cast<TemplateSpecializationType>(T))
2838 if (!TST->isTypeAlias())
2839 break;
2840
2841 // FIXME: We presumably shouldn't strip off ElaboratedTypes with
2842 // instantation-dependent qualifiers. See
2843 // https://github.com/itanium-cxx-abi/cxx-abi/issues/114.
2844
2845 QualType Desugared
2846 = T.getSingleStepDesugaredType(Context.getASTContext());
2847 if (Desugared == T)
2848 break;
2849
2850 T = Desugared;
2851 } while (true);
2852 }
2853 SplitQualType split = T.split();
2854 Qualifiers quals = split.Quals;
2855 const Type *ty = split.Ty;
2856
2857 bool isSubstitutable =
2858 isTypeSubstitutable(quals, ty, Context.getASTContext());
2859 if (isSubstitutable && mangleSubstitution(T))
2860 return;
2861
2862 // If we're mangling a qualified array type, push the qualifiers to
2863 // the element type.
2864 if (quals && isa<ArrayType>(T)) {
2865 ty = Context.getASTContext().getAsArrayType(T);
2866 quals = Qualifiers();
2867
2868 // Note that we don't update T: we want to add the
2869 // substitution at the original type.
2870 }
2871
2872 if (quals || ty->isDependentAddressSpaceType()) {
2873 if (const DependentAddressSpaceType *DAST =
2874 dyn_cast<DependentAddressSpaceType>(ty)) {
2875 SplitQualType splitDAST = DAST->getPointeeType().split();
2876 mangleQualifiers(splitDAST.Quals, DAST);
2877 mangleType(QualType(splitDAST.Ty, 0));
2878 } else {
2879 mangleQualifiers(quals);
2880
2881 // Recurse: even if the qualified type isn't yet substitutable,
2882 // the unqualified type might be.
2883 mangleType(QualType(ty, 0));
2884 }
2885 } else {
2886 switch (ty->getTypeClass()) {
2887#define ABSTRACT_TYPE(CLASS, PARENT)
2888#define NON_CANONICAL_TYPE(CLASS, PARENT) \
2889 case Type::CLASS: \
2890 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type")::llvm::llvm_unreachable_internal("can't mangle non-canonical type "
#CLASS "Type", "clang/lib/AST/ItaniumMangle.cpp", 2890)
; \
2891 return;
2892#define TYPE(CLASS, PARENT) \
2893 case Type::CLASS: \
2894 mangleType(static_cast<const CLASS##Type*>(ty)); \
2895 break;
2896#include "clang/AST/TypeNodes.inc"
2897 }
2898 }
2899
2900 // Add the substitution.
2901 if (isSubstitutable)
2902 addSubstitution(T);
2903}
2904
2905void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) {
2906 if (!mangleStandardSubstitution(ND))
2907 mangleName(ND);
2908}
2909
2910void CXXNameMangler::mangleType(const BuiltinType *T) {
2911 // <type> ::= <builtin-type>
2912 // <builtin-type> ::= v # void
2913 // ::= w # wchar_t
2914 // ::= b # bool
2915 // ::= c # char
2916 // ::= a # signed char
2917 // ::= h # unsigned char
2918 // ::= s # short
2919 // ::= t # unsigned short
2920 // ::= i # int
2921 // ::= j # unsigned int
2922 // ::= l # long
2923 // ::= m # unsigned long
2924 // ::= x # long long, __int64
2925 // ::= y # unsigned long long, __int64
2926 // ::= n # __int128
2927 // ::= o # unsigned __int128
2928 // ::= f # float
2929 // ::= d # double
2930 // ::= e # long double, __float80
2931 // ::= g # __float128
2932 // ::= g # __ibm128
2933 // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits)
2934 // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits)
2935 // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits)
2936 // ::= Dh # IEEE 754r half-precision floating point (16 bits)
2937 // ::= DF <number> _ # ISO/IEC TS 18661 binary floating point type _FloatN (N bits);
2938 // ::= Di # char32_t
2939 // ::= Ds # char16_t
2940 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
2941 // ::= u <source-name> # vendor extended type
2942 std::string type_name;
2943 switch (T->getKind()) {
2944 case BuiltinType::Void:
2945 Out << 'v';
2946 break;
2947 case BuiltinType::Bool:
2948 Out << 'b';
2949 break;
2950 case BuiltinType::Char_U:
2951 case BuiltinType::Char_S:
2952 Out << 'c';
2953 break;
2954 case BuiltinType::UChar:
2955 Out << 'h';
2956 break;
2957 case BuiltinType::UShort:
2958 Out << 't';
2959 break;
2960 case BuiltinType::UInt:
2961 Out << 'j';
2962 break;
2963 case BuiltinType::ULong:
2964 Out << 'm';
2965 break;
2966 case BuiltinType::ULongLong:
2967 Out << 'y';
2968 break;
2969 case BuiltinType::UInt128:
2970 Out << 'o';
2971 break;
2972 case BuiltinType::SChar:
2973 Out << 'a';
2974 break;
2975 case BuiltinType::WChar_S:
2976 case BuiltinType::WChar_U:
2977 Out << 'w';
2978 break;
2979 case BuiltinType::Char8:
2980 Out << "Du";
2981 break;
2982 case BuiltinType::Char16:
2983 Out << "Ds";
2984 break;
2985 case BuiltinType::Char32:
2986 Out << "Di";
2987 break;
2988 case BuiltinType::Short:
2989 Out << 's';
2990 break;
2991 case BuiltinType::Int:
2992 Out << 'i';
2993 break;
2994 case BuiltinType::Long:
2995 Out << 'l';
2996 break;
2997 case BuiltinType::LongLong:
2998 Out << 'x';
2999 break;
3000 case BuiltinType::Int128:
3001 Out << 'n';
3002 break;
3003 case BuiltinType::Float16:
3004 Out << "DF16_";
3005 break;
3006 case BuiltinType::ShortAccum:
3007 case BuiltinType::Accum:
3008 case BuiltinType::LongAccum:
3009 case BuiltinType::UShortAccum:
3010 case BuiltinType::UAccum:
3011 case BuiltinType::ULongAccum:
3012 case BuiltinType::ShortFract:
3013 case BuiltinType::Fract:
3014 case BuiltinType::LongFract:
3015 case BuiltinType::UShortFract:
3016 case BuiltinType::UFract:
3017 case BuiltinType::ULongFract:
3018 case BuiltinType::SatShortAccum:
3019 case BuiltinType::SatAccum:
3020 case BuiltinType::SatLongAccum:
3021 case BuiltinType::SatUShortAccum:
3022 case BuiltinType::SatUAccum:
3023 case BuiltinType::SatULongAccum:
3024 case BuiltinType::SatShortFract:
3025 case BuiltinType::SatFract:
3026 case BuiltinType::SatLongFract:
3027 case BuiltinType::SatUShortFract:
3028 case BuiltinType::SatUFract:
3029 case BuiltinType::SatULongFract:
3030 llvm_unreachable("Fixed point types are disabled for c++")::llvm::llvm_unreachable_internal("Fixed point types are disabled for c++"
, "clang/lib/AST/ItaniumMangle.cpp", 3030)
;
3031 case BuiltinType::Half:
3032 Out << "Dh";
3033 break;
3034 case BuiltinType::Float:
3035 Out << 'f';
3036 break;
3037 case BuiltinType::Double:
3038 Out << 'd';
3039 break;
3040 case BuiltinType::LongDouble: {
3041 const TargetInfo *TI = getASTContext().getLangOpts().OpenMP &&
3042 getASTContext().getLangOpts().OpenMPIsDevice
3043 ? getASTContext().getAuxTargetInfo()
3044 : &getASTContext().getTargetInfo();
3045 Out << TI->getLongDoubleMangling();
3046 break;
3047 }
3048 case BuiltinType::Float128: {
3049 const TargetInfo *TI = getASTContext().getLangOpts().OpenMP &&
3050 getASTContext().getLangOpts().OpenMPIsDevice
3051 ? getASTContext().getAuxTargetInfo()
3052 : &getASTContext().getTargetInfo();
3053 Out << TI->getFloat128Mangling();
3054 break;
3055 }
3056 case BuiltinType::BFloat16: {
3057 const TargetInfo *TI = &getASTContext().getTargetInfo();
3058 Out << TI->getBFloat16Mangling();
3059 break;
3060 }
3061 case BuiltinType::Ibm128: {
3062 const TargetInfo *TI = &getASTContext().getTargetInfo();
3063 Out << TI->getIbm128Mangling();
3064 break;
3065 }
3066 case BuiltinType::NullPtr:
3067 Out << "Dn";
3068 break;
3069
3070#define BUILTIN_TYPE(Id, SingletonId)
3071#define PLACEHOLDER_TYPE(Id, SingletonId) \
3072 case BuiltinType::Id:
3073#include "clang/AST/BuiltinTypes.def"
3074 case BuiltinType::Dependent:
3075 if (!NullOut)
3076 llvm_unreachable("mangling a placeholder type")::llvm::llvm_unreachable_internal("mangling a placeholder type"
, "clang/lib/AST/ItaniumMangle.cpp", 3076)
;
3077 break;
3078 case BuiltinType::ObjCId:
3079 Out << "11objc_object";
3080 break;
3081 case BuiltinType::ObjCClass:
3082 Out << "10objc_class";
3083 break;
3084 case BuiltinType::ObjCSel:
3085 Out << "13objc_selector";
3086 break;
3087#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3088 case BuiltinType::Id: \
3089 type_name = "ocl_" #ImgType "_" #Suffix; \
3090 Out << type_name.size() << type_name; \
3091 break;
3092#include "clang/Basic/OpenCLImageTypes.def"
3093 case BuiltinType::OCLSampler:
3094 Out << "11ocl_sampler";
3095 break;
3096 case BuiltinType::OCLEvent:
3097 Out << "9ocl_event";
3098 break;
3099 case BuiltinType::OCLClkEvent:
3100 Out << "12ocl_clkevent";
3101 break;
3102 case BuiltinType::OCLQueue:
3103 Out << "9ocl_queue";
3104 break;
3105 case BuiltinType::OCLReserveID:
3106 Out << "13ocl_reserveid";
3107 break;
3108#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
3109 case BuiltinType::Id: \
3110 type_name = "ocl_" #ExtType; \
3111 Out << type_name.size() << type_name; \
3112 break;
3113#include "clang/Basic/OpenCLExtensionTypes.def"
3114 // The SVE types are effectively target-specific. The mangling scheme
3115 // is defined in the appendices to the Procedure Call Standard for the
3116 // Arm Architecture.
3117#define SVE_VECTOR_TYPE(InternalName, MangledName, Id, SingletonId, NumEls, \
3118 ElBits, IsSigned, IsFP, IsBF) \
3119 case BuiltinType::Id: \
3120 type_name = MangledName; \
3121 Out << (type_name == InternalName ? "u" : "") << type_name.size() \
3122 << type_name; \
3123 break;
3124#define SVE_PREDICATE_TYPE(InternalName, MangledName, Id, SingletonId, NumEls) \
3125 case BuiltinType::Id: \
3126 type_name = MangledName; \
3127 Out << (type_name == InternalName ? "u" : "") << type_name.size() \
3128 << type_name; \
3129 break;
3130#include "clang/Basic/AArch64SVEACLETypes.def"
3131#define PPC_VECTOR_TYPE(Name, Id, Size) \
3132 case BuiltinType::Id: \
3133 type_name = #Name; \
3134 Out << 'u' << type_name.size() << type_name; \
3135 break;
3136#include "clang/Basic/PPCTypes.def"
3137 // TODO: Check the mangling scheme for RISC-V V.
3138#define RVV_TYPE(Name, Id, SingletonId) \
3139 case BuiltinType::Id: \
3140 type_name = Name; \
3141 Out << 'u' << type_name.size() << type_name; \
3142 break;
3143#include "clang/Basic/RISCVVTypes.def"
3144 }
3145}
3146
3147StringRef CXXNameMangler::getCallingConvQualifierName(CallingConv CC) {
3148 switch (CC) {
3149 case CC_C:
3150 return "";
3151
3152 case CC_X86VectorCall:
3153 case CC_X86Pascal:
3154 case CC_X86RegCall:
3155 case CC_AAPCS:
3156 case CC_AAPCS_VFP:
3157 case CC_AArch64VectorCall:
3158 case CC_AArch64SVEPCS:
3159 case CC_AMDGPUKernelCall:
3160 case CC_IntelOclBicc:
3161 case CC_SpirFunction:
3162 case CC_OpenCLKernel:
3163 case CC_PreserveMost:
3164 case CC_PreserveAll:
3165 // FIXME: we should be mangling all of the above.
3166 return "";
3167
3168 case CC_X86ThisCall:
3169 // FIXME: To match mingw GCC, thiscall should only be mangled in when it is
3170 // used explicitly. At this point, we don't have that much information in
3171 // the AST, since clang tends to bake the convention into the canonical
3172 // function type. thiscall only rarely used explicitly, so don't mangle it
3173 // for now.
3174 return "";
3175
3176 case CC_X86StdCall:
3177 return "stdcall";
3178 case CC_X86FastCall:
3179 return "fastcall";
3180 case CC_X86_64SysV:
3181 return "sysv_abi";
3182 case CC_Win64:
3183 return "ms_abi";
3184 case CC_Swift:
3185 return "swiftcall";
3186 case CC_SwiftAsync:
3187 return "swiftasynccall";
3188 }
3189 llvm_unreachable("bad calling convention")::llvm::llvm_unreachable_internal("bad calling convention", "clang/lib/AST/ItaniumMangle.cpp"
, 3189)
;
3190}
3191
3192void CXXNameMangler::mangleExtFunctionInfo(const FunctionType *T) {
3193 // Fast path.
3194 if (T->getExtInfo() == FunctionType::ExtInfo())
3195 return;
3196
3197 // Vendor-specific qualifiers are emitted in reverse alphabetical order.
3198 // This will get more complicated in the future if we mangle other
3199 // things here; but for now, since we mangle ns_returns_retained as
3200 // a qualifier on the result type, we can get away with this:
3201 StringRef CCQualifier = getCallingConvQualifierName(T->getExtInfo().getCC());
3202 if (!CCQualifier.empty())
3203 mangleVendorQualifier(CCQualifier);
3204
3205 // FIXME: regparm
3206 // FIXME: noreturn
3207}
3208
3209void
3210CXXNameMangler::mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo PI) {
3211 // Vendor-specific qualifiers are emitted in reverse alphabetical order.
3212
3213 // Note that these are *not* substitution candidates. Demanglers might
3214 // have trouble with this if the parameter type is fully substituted.
3215
3216 switch (PI.getABI()) {
3217 case ParameterABI::Ordinary:
3218 break;
3219
3220 // All of these start with "swift", so they come before "ns_consumed".
3221 case ParameterABI::SwiftContext:
3222 case ParameterABI::SwiftAsyncContext:
3223 case ParameterABI::SwiftErrorResult:
3224 case ParameterABI::SwiftIndirectResult:
3225 mangleVendorQualifier(getParameterABISpelling(PI.getABI()));
3226 break;
3227 }
3228
3229 if (PI.isConsumed())
3230 mangleVendorQualifier("ns_consumed");
3231
3232 if (PI.isNoEscape())
3233 mangleVendorQualifier("noescape");
3234}
3235
3236// <type> ::= <function-type>
3237// <function-type> ::= [<CV-qualifiers>] F [Y]
3238// <bare-function-type> [<ref-qualifier>] E
3239void CXXNameMangler::mangleType(const FunctionProtoType *T) {
3240 mangleExtFunctionInfo(T);
3241
3242 // Mangle CV-qualifiers, if present. These are 'this' qualifiers,
3243 // e.g. "const" in "int (A::*)() const".
3244 mangleQualifiers(T->getMethodQuals());
3245
3246 // Mangle instantiation-dependent exception-specification, if present,
3247 // per cxx-abi-dev proposal on 2016-10-11.
3248 if (T->hasInstantiationDependentExceptionSpec()) {
3249 if (isComputedNoexcept(T->getExceptionSpecType())) {
3250 Out << "DO";
3251 mangleExpression(T->getNoexceptExpr());
3252 Out << "E";
3253 } else {
3254 assert(T->getExceptionSpecType() == EST_Dynamic)(static_cast <bool> (T->getExceptionSpecType() == EST_Dynamic
) ? void (0) : __assert_fail ("T->getExceptionSpecType() == EST_Dynamic"
, "clang/lib/AST/ItaniumMangle.cpp", 3254, __extension__ __PRETTY_FUNCTION__
))
;
3255 Out << "Dw";
3256 for (auto ExceptTy : T->exceptions())
3257 mangleType(ExceptTy);
3258 Out << "E";
3259 }
3260 } else if (T->isNothrow()) {
3261 Out << "Do";
3262 }
3263
3264 Out << 'F';
3265
3266 // FIXME: We don't have enough information in the AST to produce the 'Y'
3267 // encoding for extern "C" function types.
3268 mangleBareFunctionType(T, /*MangleReturnType=*/true);
3269
3270 // Mangle the ref-qualifier, if present.
3271 mangleRefQualifier(T->getRefQualifier());
3272
3273 Out << 'E';
3274}
3275
3276void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {
3277 // Function types without prototypes can arise when mangling a function type
3278 // within an overloadable function in C. We mangle these as the absence of any
3279 // parameter types (not even an empty parameter list).
3280 Out << 'F';
3281
3282 FunctionTypeDepthState saved = FunctionTypeDepth.push();
3283
3284 FunctionTypeDepth.enterResultType();
3285 mangleType(T->getReturnType());
3286 FunctionTypeDepth.leaveResultType();
3287
3288 FunctionTypeDepth.pop(saved);
3289 Out << 'E';
3290}
3291
3292void CXXNameMangler::mangleBareFunctionType(const FunctionProtoType *Proto,
3293 bool MangleReturnType,
3294 const FunctionDecl *FD) {
3295 // Record that we're in a function type. See mangleFunctionParam
3296 // for details on what we're trying to achieve here.
3297 FunctionTypeDepthState saved = FunctionTypeDepth.push();
3298
3299 // <bare-function-type> ::= <signature type>+
3300 if (MangleReturnType) {
3301 FunctionTypeDepth.enterResultType();
3302
3303 // Mangle ns_returns_retained as an order-sensitive qualifier here.
3304 if (Proto->getExtInfo().getProducesResult() && FD == nullptr)
3305 mangleVendorQualifier("ns_returns_retained");
3306
3307 // Mangle the return type without any direct ARC ownership qualifiers.
3308 QualType ReturnTy = Proto->getReturnType();
3309 if (ReturnTy.getObjCLifetime()) {
3310 auto SplitReturnTy = ReturnTy.split();
3311 SplitReturnTy.Quals.removeObjCLifetime();
3312 ReturnTy = getASTContext().getQualifiedType(SplitReturnTy);
3313 }
3314 mangleType(ReturnTy);
3315
3316 FunctionTypeDepth.leaveResultType();
3317 }
3318
3319 if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
3320 // <builtin-type> ::= v # void
3321 Out << 'v';
3322
3323 FunctionTypeDepth.pop(saved);
3324 return;
3325 }
3326
3327 assert(!FD || FD->getNumParams() == Proto->getNumParams())(static_cast <bool> (!FD || FD->getNumParams() == Proto
->getNumParams()) ? void (0) : __assert_fail ("!FD || FD->getNumParams() == Proto->getNumParams()"
, "clang/lib/AST/ItaniumMangle.cpp", 3327, __extension__ __PRETTY_FUNCTION__
))
;
3328 for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) {
3329 // Mangle extended parameter info as order-sensitive qualifiers here.
3330 if (Proto->hasExtParameterInfos() && FD == nullptr) {
3331 mangleExtParameterInfo(Proto->getExtParameterInfo(I));
3332 }
3333
3334 // Mangle the type.
3335 QualType ParamTy = Proto->getParamType(I);
3336 mangleType(Context.getASTContext().getSignatureParameterType(ParamTy));
3337
3338 if (FD) {
3339 if (auto *Attr = FD->getParamDecl(I)->getAttr<PassObjectSizeAttr>()) {
3340 // Attr can only take 1 character, so we can hardcode the length below.
3341 assert(Attr->getType() <= 9 && Attr->getType() >= 0)(static_cast <bool> (Attr->getType() <= 9 &&
Attr->getType() >= 0) ? void (0) : __assert_fail ("Attr->getType() <= 9 && Attr->getType() >= 0"
, "clang/lib/AST/ItaniumMangle.cpp", 3341, __extension__ __PRETTY_FUNCTION__
))
;
3342 if (Attr->isDynamic())
3343 Out << "U25pass_dynamic_object_size" << Attr->getType();
3344 else
3345 Out << "U17pass_object_size" << Attr->getType();
3346 }
3347 }
3348 }
3349
3350 FunctionTypeDepth.pop(saved);
3351
3352 // <builtin-type> ::= z # ellipsis
3353 if (Proto->isVariadic())
3354 Out << 'z';
3355}
3356
3357// <type> ::= <class-enum-type>
3358// <class-enum-type> ::= <name>
3359void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
3360 mangleName(T->getDecl());
3361}
3362
3363// <type> ::= <class-enum-type>
3364// <class-enum-type> ::= <name>
3365void CXXNameMangler::mangleType(const EnumType *T) {
3366 mangleType(static_cast<const TagType*>(T));
3367}
3368void CXXNameMangler::mangleType(const RecordType *T) {
3369 mangleType(static_cast<const TagType*>(T));
3370}
3371void CXXNameMangler::mangleType(const TagType *T) {
3372 mangleName(T->getDecl());
3373}
3374
3375// <type> ::= <array-type>
3376// <array-type> ::= A <positive dimension number> _ <element type>
3377// ::= A [<dimension expression>] _ <element type>
3378void CXXNameMangler::mangleType(const ConstantArrayType *T) {
3379 Out << 'A' << T->getSize() << '_';
3380 mangleType(T->getElementType());
3381}
3382void CXXNameMangler::mangleType(const VariableArrayType *T) {
3383 Out << 'A';
3384 // decayed vla types (size 0) will just be skipped.
3385 if (T->getSizeExpr())
3386 mangleExpression(T->getSizeExpr());
3387 Out << '_';
3388 mangleType(T->getElementType());
3389}
3390void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
3391 Out << 'A';
3392 // A DependentSizedArrayType might not have size expression as below
3393 //
3394 // template<int ...N> int arr[] = {N...};
3395 if (T->getSizeExpr())
3396 mangleExpression(T->getSizeExpr());
3397 Out << '_';
3398 mangleType(T->getElementType());
3399}
3400void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
3401 Out << "A_";
3402 mangleType(T->getElementType());
3403}
3404
3405// <type> ::= <pointer-to-member-type>
3406// <pointer-to-member-type> ::= M <class type> <member type>
3407void CXXNameMangler::mangleType(const MemberPointerType *T) {
3408 Out << 'M';
3409 mangleType(QualType(T->getClass(), 0));
3410 QualType PointeeType = T->getPointeeType();
3411 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
3412 mangleType(FPT);
3413
3414 // Itanium C++ ABI 5.1.8:
3415 //
3416 // The type of a non-static member function is considered to be different,
3417 // for the purposes of substitution, from the type of a namespace-scope or
3418 // static member function whose type appears similar. The types of two
3419 // non-static member functions are considered to be different, for the
3420 // purposes of substitution, if the functions are members of different
3421 // classes. In other words, for the purposes of substitution, the class of
3422 // which the function is a member is considered part of the type of
3423 // function.
3424
3425 // Given that we already substitute member function pointers as a
3426 // whole, the net effect of this rule is just to unconditionally
3427 // suppress substitution on the function type in a member pointer.
3428 // We increment the SeqID here to emulate adding an entry to the
3429 // substitution table.
3430 ++SeqID;
3431 } else
3432 mangleType(PointeeType);
3433}
3434
3435// <type> ::= <template-param>
3436void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
3437 mangleTemplateParameter(T->getDepth(), T->getIndex());
3438}
3439
3440// <type> ::= <template-param>
3441void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {
3442 // FIXME: not clear how to mangle this!
3443 // template <class T...> class A {
3444 // template <class U...> void foo(T(*)(U) x...);
3445 // };
3446 Out << "_SUBSTPACK_";
3447}
3448
3449// <type> ::= P <type> # pointer-to
3450void CXXNameMangler::mangleType(const PointerType *T) {
3451 Out << 'P';
3452 mangleType(T->getPointeeType());
3453}
3454void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
3455 Out << 'P';
3456 mangleType(T->getPointeeType());
3457}
3458
3459// <type> ::= R <type> # reference-to
3460void CXXNameMangler::mangleType(const LValueReferenceType *T) {
3461 Out << 'R';
3462 mangleType(T->getPointeeType());
3463}
3464
3465// <type> ::= O <type> # rvalue reference-to (C++0x)
3466void CXXNameMangler::mangleType(const RValueReferenceType *T) {
3467 Out << 'O';
3468 mangleType(T->getPointeeType());
3469}
3470
3471// <type> ::= C <type> # complex pair (C 2000)
3472void CXXNameMangler::mangleType(const ComplexType *T) {
3473 Out << 'C';
3474 mangleType(T->getElementType());
3475}
3476
3477// ARM's ABI for Neon vector types specifies that they should be mangled as
3478// if they are structs (to match ARM's initial implementation). The
3479// vector type must be one of the special types predefined by ARM.
3480void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {
3481 QualType EltType = T->getElementType();
3482 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType")(static_cast <bool> (EltType->isBuiltinType() &&
"Neon vector element not a BuiltinType") ? void (0) : __assert_fail
("EltType->isBuiltinType() && \"Neon vector element not a BuiltinType\""
, "clang/lib/AST/ItaniumMangle.cpp", 3482, __extension__ __PRETTY_FUNCTION__
))
;
3483 const char *EltName = nullptr;
3484 if (T->getVectorKind() == VectorType::NeonPolyVector) {
3485 switch (cast<BuiltinType>(EltType)->getKind()) {
3486 case BuiltinType::SChar:
3487 case BuiltinType::UChar:
3488 EltName = "poly8_t";
3489 break;
3490 case BuiltinType::Short:
3491 case BuiltinType::UShort:
3492 EltName = "poly16_t";
3493 break;
3494 case BuiltinType::LongLong:
3495 case BuiltinType::ULongLong:
3496 EltName = "poly64_t";
3497 break;
3498 default: llvm_unreachable("unexpected Neon polynomial vector element type")::llvm::llvm_unreachable_internal("unexpected Neon polynomial vector element type"
, "clang/lib/AST/ItaniumMangle.cpp", 3498)
;
3499 }
3500 } else {
3501 switch (cast<BuiltinType>(EltType)->getKind()) {
3502 case BuiltinType::SChar: EltName = "int8_t"; break;
3503 case BuiltinType::UChar: EltName = "uint8_t"; break;
3504 case BuiltinType::Short: EltName = "int16_t"; break;
3505 case BuiltinType::UShort: EltName = "uint16_t"; break;
3506 case BuiltinType::Int: EltName = "int32_t"; break;
3507 case BuiltinType::UInt: EltName = "uint32_t"; break;
3508 case BuiltinType::LongLong: EltName = "int64_t"; break;
3509 case BuiltinType::ULongLong: EltName = "uint64_t"; break;
3510 case BuiltinType::Double: EltName = "float64_t"; break;
3511 case BuiltinType::Float: EltName = "float32_t"; break;
3512 case BuiltinType::Half: EltName = "float16_t"; break;
3513 case BuiltinType::BFloat16: EltName = "bfloat16_t"; break;
3514 default:
3515 llvm_unreachable("unexpected Neon vector element type")::llvm::llvm_unreachable_internal("unexpected Neon vector element type"
, "clang/lib/AST/ItaniumMangle.cpp", 3515)
;
3516 }
3517 }
3518 const char *BaseName = nullptr;
3519 unsigned BitSize = (T->getNumElements() *
3520 getASTContext().getTypeSize(EltType));
3521 if (BitSize == 64)
3522 BaseName = "__simd64_";
3523 else {
3524 assert(BitSize == 128 && "Neon vector type not 64 or 128 bits")(static_cast <bool> (BitSize == 128 && "Neon vector type not 64 or 128 bits"
) ? void (0) : __assert_fail ("BitSize == 128 && \"Neon vector type not 64 or 128 bits\""
, "clang/lib/AST/ItaniumMangle.cpp", 3524, __extension__ __PRETTY_FUNCTION__
))
;
3525 BaseName = "__simd128_";
3526 }
3527 Out << strlen(BaseName) + strlen(EltName);
3528 Out << BaseName << EltName;
3529}
3530
3531void CXXNameMangler::mangleNeonVectorType(const DependentVectorType *T) {
3532 DiagnosticsEngine &Diags = Context.getDiags();
3533 unsigned DiagID = Diags.getCustomDiagID(
3534 DiagnosticsEngine::Error,
3535 "cannot mangle this dependent neon vector type yet");
3536 Diags.Report(T->getAttributeLoc(), DiagID);
3537}
3538
3539static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) {
3540 switch (EltType->getKind()) {
3541 case BuiltinType::SChar:
3542 return "Int8";
3543 case BuiltinType::Short:
3544 return "Int16";
3545 case BuiltinType::Int:
3546 return "Int32";
3547 case BuiltinType::Long:
3548 case BuiltinType::LongLong:
3549 return "Int64";
3550 case BuiltinType::UChar:
3551 return "Uint8";
3552 case BuiltinType::UShort:
3553 return "Uint16";
3554 case BuiltinType::UInt:
3555 return "Uint32";
3556 case BuiltinType::ULong:
3557 case BuiltinType::ULongLong:
3558 return "Uint64";
3559 case BuiltinType::Half:
3560 return "Float16";
3561 case BuiltinType::Float:
3562 return "Float32";
3563 case BuiltinType::Double:
3564 return "Float64";
3565 case BuiltinType::BFloat16:
3566 return "Bfloat16";
3567 default:
3568 llvm_unreachable("Unexpected vector element base type")::llvm::llvm_unreachable_internal("Unexpected vector element base type"
, "clang/lib/AST/ItaniumMangle.cpp", 3568)
;
3569 }
3570}
3571
3572// AArch64's ABI for Neon vector types specifies that they should be mangled as
3573// the equivalent internal name. The vector type must be one of the special
3574// types predefined by ARM.
3575void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) {
3576 QualType EltType = T->getElementType();
3577 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType")(static_cast <bool> (EltType->isBuiltinType() &&
"Neon vector element not a BuiltinType") ? void (0) : __assert_fail
("EltType->isBuiltinType() && \"Neon vector element not a BuiltinType\""
, "clang/lib/AST/ItaniumMangle.cpp", 3577, __extension__ __PRETTY_FUNCTION__
))
;
3578 unsigned BitSize =
3579 (T->getNumElements() * getASTContext().getTypeSize(EltType));
3580 (void)BitSize; // Silence warning.
3581
3582 assert((BitSize == 64 || BitSize == 128) &&(static_cast <bool> ((BitSize == 64 || BitSize == 128) &&
"Neon vector type not 64 or 128 bits") ? void (0) : __assert_fail
("(BitSize == 64 || BitSize == 128) && \"Neon vector type not 64 or 128 bits\""
, "clang/lib/AST/ItaniumMangle.cpp", 3583, __extension__ __PRETTY_FUNCTION__
))
3583 "Neon vector type not 64 or 128 bits")(static_cast <bool> ((BitSize == 64 || BitSize == 128) &&
"Neon vector type not 64 or 128 bits") ? void (0) : __assert_fail
("(BitSize == 64 || BitSize == 128) && \"Neon vector type not 64 or 128 bits\""
, "clang/lib/AST/ItaniumMangle.cpp", 3583, __extension__ __PRETTY_FUNCTION__
))
;
3584
3585 StringRef EltName;
3586 if (T->getVectorKind() == VectorType::NeonPolyVector) {
3587 switch (cast<BuiltinType>(EltType)->getKind()) {
3588 case BuiltinType::UChar:
3589 EltName = "Poly8";
3590 break;
3591 case BuiltinType::UShort:
3592 EltName = "Poly16";
3593 break;
3594 case BuiltinType::ULong:
3595 case BuiltinType::ULongLong:
3596 EltName = "Poly64";
3597 break;
3598 default:
3599 llvm_unreachable("unexpected Neon polynomial vector element type")::llvm::llvm_unreachable_internal("unexpected Neon polynomial vector element type"
, "clang/lib/AST/ItaniumMangle.cpp", 3599)
;
3600 }
3601 } else
3602 EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType));
3603
3604 std::string TypeName =
3605 ("__" + EltName + "x" + Twine(T->getNumElements()) + "_t").str();
3606 Out << TypeName.length() << TypeName;
3607}
3608void CXXNameMangler::mangleAArch64NeonVectorType(const DependentVectorType *T) {
3609 DiagnosticsEngine &Diags = Context.getDiags();
3610 unsigned DiagID = Diags.getCustomDiagID(
3611 DiagnosticsEngine::Error,
3612 "cannot mangle this dependent neon vector type yet");
3613 Diags.Report(T->getAttributeLoc(), DiagID);
3614}
3615
3616// The AArch64 ACLE specifies that fixed-length SVE vector and predicate types
3617// defined with the 'arm_sve_vector_bits' attribute map to the same AAPCS64
3618// type as the sizeless variants.
3619//
3620// The mangling scheme for VLS types is implemented as a "pseudo" template:
3621//
3622// '__SVE_VLS<<type>, <vector length>>'
3623//
3624// Combining the existing SVE type and a specific vector length (in bits).
3625// For example:
3626//
3627// typedef __SVInt32_t foo __attribute__((arm_sve_vector_bits(512)));
3628//
3629// is described as '__SVE_VLS<__SVInt32_t, 512u>' and mangled as:
3630//
3631// "9__SVE_VLSI" + base type mangling + "Lj" + __ARM_FEATURE_SVE_BITS + "EE"
3632//
3633// i.e. 9__SVE_VLSIu11__SVInt32_tLj512EE
3634//
3635// The latest ACLE specification (00bet5) does not contain details of this
3636// mangling scheme, it will be specified in the next revision. The mangling
3637// scheme is otherwise defined in the appendices to the Procedure Call Standard
3638// for the Arm Architecture, see
3639// https://github.com/ARM-software/abi-aa/blob/main/aapcs64/aapcs64.rst#appendix-c-mangling
3640void CXXNameMangler::mangleAArch64FixedSveVectorType(const VectorType *T) {
3641 assert((T->getVectorKind() == VectorType::SveFixedLengthDataVector ||(static_cast <bool> ((T->getVectorKind() == VectorType
::SveFixedLengthDataVector || T->getVectorKind() == VectorType
::SveFixedLengthPredicateVector) && "expected fixed-length SVE vector!"
) ? void (0) : __assert_fail ("(T->getVectorKind() == VectorType::SveFixedLengthDataVector || T->getVectorKind() == VectorType::SveFixedLengthPredicateVector) && \"expected fixed-length SVE vector!\""
, "clang/lib/AST/ItaniumMangle.cpp", 3643, __extension__ __PRETTY_FUNCTION__
))
3642 T->getVectorKind() == VectorType::SveFixedLengthPredicateVector) &&(static_cast <bool> ((T->getVectorKind() == VectorType
::SveFixedLengthDataVector || T->getVectorKind() == VectorType
::SveFixedLengthPredicateVector) && "expected fixed-length SVE vector!"
) ? void (0) : __assert_fail ("(T->getVectorKind() == VectorType::SveFixedLengthDataVector || T->getVectorKind() == VectorType::SveFixedLengthPredicateVector) && \"expected fixed-length SVE vector!\""
, "clang/lib/AST/ItaniumMangle.cpp", 3643, __extension__ __PRETTY_FUNCTION__
))
3643 "expected fixed-length SVE vector!")(static_cast <bool> ((T->getVectorKind() == VectorType
::SveFixedLengthDataVector || T->getVectorKind() == VectorType
::SveFixedLengthPredicateVector) && "expected fixed-length SVE vector!"
) ? void (0) : __assert_fail ("(T->getVectorKind() == VectorType::SveFixedLengthDataVector || T->getVectorKind() == VectorType::SveFixedLengthPredicateVector) && \"expected fixed-length SVE vector!\""
, "clang/lib/AST/ItaniumMangle.cpp", 3643, __extension__ __PRETTY_FUNCTION__
))
;
3644
3645 QualType EltType = T->getElementType();
3646 assert(EltType->isBuiltinType() &&(static_cast <bool> (EltType->isBuiltinType() &&
"expected builtin type for fixed-length SVE vector!") ? void
(0) : __assert_fail ("EltType->isBuiltinType() && \"expected builtin type for fixed-length SVE vector!\""
, "clang/lib/AST/ItaniumMangle.cpp", 3647, __extension__ __PRETTY_FUNCTION__
))
3647 "expected builtin type for fixed-length SVE vector!")(static_cast <bool> (EltType->isBuiltinType() &&
"expected builtin type for fixed-length SVE vector!") ? void
(0) : __assert_fail ("EltType->isBuiltinType() && \"expected builtin type for fixed-length SVE vector!\""
, "clang/lib/AST/ItaniumMangle.cpp", 3647, __extension__ __PRETTY_FUNCTION__
))
;
3648
3649 StringRef TypeName;
3650 switch (cast<BuiltinType>(EltType)->getKind()) {
3651 case BuiltinType::SChar:
3652 TypeName = "__SVInt8_t";
3653 break;
3654 case BuiltinType::UChar: {
3655 if (T->getVectorKind() == VectorType::SveFixedLengthDataVector)
3656 TypeName = "__SVUint8_t";
3657 else
3658 TypeName = "__SVBool_t";
3659 break;
3660 }
3661 case BuiltinType::Short:
3662 TypeName = "__SVInt16_t";
3663 break;
3664 case BuiltinType::UShort:
3665 TypeName = "__SVUint16_t";
3666 break;
3667 case BuiltinType::Int:
3668 TypeName = "__SVInt32_t";
3669 break;
3670 case BuiltinType::UInt:
3671 TypeName = "__SVUint32_t";
3672 break;
3673 case BuiltinType::Long:
3674 TypeName = "__SVInt64_t";
3675 break;
3676 case BuiltinType::ULong:
3677 TypeName = "__SVUint64_t";
3678 break;
3679 case BuiltinType::Half:
3680 TypeName = "__SVFloat16_t";
3681 break;
3682 case BuiltinType::Float:
3683 TypeName = "__SVFloat32_t";
3684 break;
3685 case BuiltinType::Double:
3686 TypeName = "__SVFloat64_t";
3687 break;
3688 case BuiltinType::BFloat16:
3689 TypeName = "__SVBfloat16_t";
3690 break;
3691 default:
3692 llvm_unreachable("unexpected element type for fixed-length SVE vector!")::llvm::llvm_unreachable_internal("unexpected element type for fixed-length SVE vector!"
, "clang/lib/AST/ItaniumMangle.cpp", 3692)
;
3693 }
3694
3695 unsigned VecSizeInBits = getASTContext().getTypeInfo(T).Width;
3696
3697 if (T->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
3698 VecSizeInBits *= 8;
3699
3700 Out << "9__SVE_VLSI" << 'u' << TypeName.size() << TypeName << "Lj"
3701 << VecSizeInBits << "EE";
3702}
3703
3704void CXXNameMangler::mangleAArch64FixedSveVectorType(
3705 const DependentVectorType *T) {
3706 DiagnosticsEngine &Diags = Context.getDiags();
3707 unsigned DiagID = Diags.getCustomDiagID(
3708 DiagnosticsEngine::Error,
3709 "cannot mangle this dependent fixed-length SVE vector type yet");
3710 Diags.Report(T->getAttributeLoc(), DiagID);
3711}
3712
3713// GNU extension: vector types
3714// <type> ::= <vector-type>
3715// <vector-type> ::= Dv <positive dimension number> _
3716// <extended element type>
3717// ::= Dv [<dimension expression>] _ <element type>
3718// <extended element type> ::= <element type>
3719// ::= p # AltiVec vector pixel
3720// ::= b # Altivec vector bool
3721void CXXNameMangler::mangleType(const VectorType *T) {
3722 if ((T->getVectorKind() == VectorType::NeonVector ||
3723 T->getVectorKind() == VectorType::NeonPolyVector)) {
3724 llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
3725 llvm::Triple::ArchType Arch =
3726 getASTContext().getTargetInfo().getTriple().getArch();
3727 if ((Arch == llvm::Triple::aarch64 ||
3728 Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin())
3729 mangleAArch64NeonVectorType(T);
3730 else
3731 mangleNeonVectorType(T);
3732 return;
3733 } else if (T->getVectorKind() == VectorType::SveFixedLengthDataVector ||
3734 T->getVectorKind() == VectorType::SveFixedLengthPredicateVector) {
3735 mangleAArch64FixedSveVectorType(T);
3736 return;
3737 }
3738 Out << "Dv" << T->getNumElements() << '_';
3739 if (T->getVectorKind() == VectorType::AltiVecPixel)
3740 Out << 'p';
3741 else if (T->getVectorKind() == VectorType::AltiVecBool)
3742 Out << 'b';
3743 else
3744 mangleType(T->getElementType());
3745}
3746
3747void CXXNameMangler::mangleType(const DependentVectorType *T) {
3748 if ((T->getVectorKind() == VectorType::NeonVector ||
3749 T->getVectorKind() == VectorType::NeonPolyVector)) {
3750 llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
3751 llvm::Triple::ArchType Arch =
3752 getASTContext().getTargetInfo().getTriple().getArch();
3753 if ((Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_be) &&
3754 !Target.isOSDarwin())
3755 mangleAArch64NeonVectorType(T);
3756 else
3757 mangleNeonVectorType(T);
3758 return;
3759 } else if (T->getVectorKind() == VectorType::SveFixedLengthDataVector ||
3760 T->getVectorKind() == VectorType::SveFixedLengthPredicateVector) {
3761 mangleAArch64FixedSveVectorType(T);
3762 return;
3763 }
3764
3765 Out << "Dv";
3766 mangleExpression(T->getSizeExpr());
3767 Out << '_';
3768 if (T->getVectorKind() == VectorType::AltiVecPixel)
3769 Out << 'p';
3770 else if (T->getVectorKind() == VectorType::AltiVecBool)
3771 Out << 'b';
3772 else
3773 mangleType(T->getElementType());
3774}
3775
3776void CXXNameMangler::mangleType(const ExtVectorType *T) {
3777 mangleType(static_cast<const VectorType*>(T));
3778}
3779void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
3780 Out << "Dv";
3781 mangleExpression(T->getSizeExpr());
3782 Out << '_';
3783 mangleType(T->getElementType());
3784}
3785
3786void CXXNameMangler::mangleType(const ConstantMatrixType *T) {
3787 // Mangle matrix types as a vendor extended type:
3788 // u<Len>matrix_typeI<Rows><Columns><element type>E
3789
3790 StringRef VendorQualifier = "matrix_type";
3791 Out << "u" << VendorQualifier.size() << VendorQualifier;
3792
3793 Out << "I";
3794 auto &ASTCtx = getASTContext();
3795 unsigned BitWidth = ASTCtx.getTypeSize(ASTCtx.getSizeType());
3796 llvm::APSInt Rows(BitWidth);
3797 Rows = T->getNumRows();
3798 mangleIntegerLiteral(ASTCtx.getSizeType(), Rows);
3799 llvm::APSInt Columns(BitWidth);
3800 Columns = T->getNumColumns();
3801 mangleIntegerLiteral(ASTCtx.getSizeType(), Columns);
3802 mangleType(T->getElementType());
3803 Out << "E";
3804}
3805
3806void CXXNameMangler::mangleType(const DependentSizedMatrixType *T) {
3807 // Mangle matrix types as a vendor extended type:
3808 // u<Len>matrix_typeI<row expr><column expr><element type>E
3809 StringRef VendorQualifier = "matrix_type";
3810 Out << "u" << VendorQualifier.size() << VendorQualifier;
3811
3812 Out << "I";
3813 mangleTemplateArgExpr(T->getRowExpr());
3814 mangleTemplateArgExpr(T->getColumnExpr());
3815 mangleType(T->getElementType());
3816 Out << "E";
3817}
3818
3819void CXXNameMangler::mangleType(const DependentAddressSpaceType *T) {
3820 SplitQualType split = T->getPointeeType().split();
3821 mangleQualifiers(split.Quals, T);
3822 mangleType(QualType(split.Ty, 0));
3823}
3824
3825void CXXNameMangler::mangleType(const PackExpansionType *T) {
3826 // <type> ::= Dp <type> # pack expansion (C++0x)
3827 Out << "Dp";
3828 mangleType(T->getPattern());
3829}
3830
3831void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
3832 mangleSourceName(T->getDecl()->getIdentifier());
3833}
3834
3835void CXXNameMangler::mangleType(const ObjCObjectType *T) {
3836 // Treat __kindof as a vendor extended type qualifier.
3837 if (T->isKindOfType())
3838 Out << "U8__kindof";
3839
3840 if (!T->qual_empty()) {
3841 // Mangle protocol qualifiers.
3842 SmallString<64> QualStr;
3843 llvm::raw_svector_ostream QualOS(QualStr);
3844 QualOS << "objcproto";
3845 for (const auto *I : T->quals()) {
3846 StringRef name = I->getName();
3847 QualOS << name.size() << name;
3848 }
3849 Out << 'U' << QualStr.size() << QualStr;
3850 }
3851
3852 mangleType(T->getBaseType());
3853
3854 if (T->isSpecialized()) {
3855 // Mangle type arguments as I <type>+ E
3856 Out << 'I';
3857 for (auto typeArg : T->getTypeArgs())
3858 mangleType(typeArg);
3859 Out << 'E';
3860 }
3861}
3862
3863void CXXNameMangler::mangleType(const BlockPointerType *T) {
3864 Out << "U13block_pointer";
3865 mangleType(T->getPointeeType());
3866}
3867
3868void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
3869 // Mangle injected class name types as if the user had written the
3870 // specialization out fully. It may not actually be possible to see
3871 // this mangling, though.
3872 mangleType(T->getInjectedSpecializationType());
3873}
3874
3875void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
3876 if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
3877 mangleTemplateName(TD, T->getArgs(), T->getNumArgs());
3878 } else {
3879 if (mangleSubstitution(QualType(T, 0)))
3880 return;
3881
3882 mangleTemplatePrefix(T->getTemplateName());
3883
3884 // FIXME: GCC does not appear to mangle the template arguments when
3885 // the template in question is a dependent template name. Should we
3886 // emulate that badness?
3887 mangleTemplateArgs(T->getTemplateName(), T->getArgs(), T->getNumArgs());
3888 addSubstitution(QualType(T, 0));
3889 }
3890}
3891
3892void CXXNameMangler::mangleType(const DependentNameType *T) {
3893 // Proposal by cxx-abi-dev, 2014-03-26
3894 // <class-enum-type> ::= <name> # non-dependent or dependent type name or
3895 // # dependent elaborated type specifier using
3896 // # 'typename'
3897 // ::= Ts <name> # dependent elaborated type specifier using
3898 // # 'struct' or 'class'
3899 // ::= Tu <name> # dependent elaborated type specifier using
3900 // # 'union'
3901 // ::= Te <name> # dependent elaborated type specifier using
3902 // # 'enum'
3903 switch (T->getKeyword()) {
3904 case ETK_None:
3905 case ETK_Typename:
3906 break;
3907 case ETK_Struct:
3908 case ETK_Class:
3909 case ETK_Interface:
3910 Out << "Ts";
3911 break;
3912 case ETK_Union:
3913 Out << "Tu";
3914 break;
3915 case ETK_Enum:
3916 Out << "Te";
3917 break;
3918 }
3919 // Typename types are always nested
3920 Out << 'N';
3921 manglePrefix(T->getQualifier());
3922 mangleSourceName(T->getIdentifier());
3923 Out << 'E';
3924}
3925
3926void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
3927 // Dependently-scoped template types are nested if they have a prefix.
3928 Out << 'N';
3929
3930 // TODO: avoid making this TemplateName.
3931 TemplateName Prefix =
3932 getASTContext().getDependentTemplateName(T->getQualifier(),
3933 T->getIdentifier());
3934 mangleTemplatePrefix(Prefix);
3935
3936 // FIXME: GCC does not appear to mangle the template arguments when
3937 // the template in question is a dependent template name. Should we
3938 // emulate that badness?
3939 mangleTemplateArgs(Prefix, T->getArgs(), T->getNumArgs());
3940 Out << 'E';
3941}
3942
3943void CXXNameMangler::mangleType(const TypeOfType *T) {
3944 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
3945 // "extension with parameters" mangling.
3946 Out << "u6typeof";
3947}
3948
3949void CXXNameMangler::mangleType(const TypeOfExprType *T) {
3950 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
3951 // "extension with parameters" mangling.
3952 Out << "u6typeof";
3953}
3954
3955void CXXNameMangler::mangleType(const DecltypeType *T) {
3956 Expr *E = T->getUnderlyingExpr();
3957
3958 // type ::= Dt <expression> E # decltype of an id-expression
3959 // # or class member access
3960 // ::= DT <expression> E # decltype of an expression
3961
3962 // This purports to be an exhaustive list of id-expressions and
3963 // class member accesses. Note that we do not ignore parentheses;
3964 // parentheses change the semantics of decltype for these
3965 // expressions (and cause the mangler to use the other form).
3966 if (isa<DeclRefExpr>(E) ||
3967 isa<MemberExpr>(E) ||
3968 isa<UnresolvedLookupExpr>(E) ||
3969 isa<DependentScopeDeclRefExpr>(E) ||
3970 isa<CXXDependentScopeMemberExpr>(E) ||
3971 isa<UnresolvedMemberExpr>(E))
3972 Out << "Dt";
3973 else
3974 Out << "DT";
3975 mangleExpression(E);
3976 Out << 'E';
3977}
3978
3979void CXXNameMangler::mangleType(const UnaryTransformType *T) {
3980 // If this is dependent, we need to record that. If not, we simply
3981 // mangle it as the underlying type since they are equivalent.
3982 if (T->isDependentType()) {
3983 Out << "u";
3984
3985 StringRef BuiltinName;
3986 switch (T->getUTTKind()) {
3987#define TRANSFORM_TYPE_TRAIT_DEF(Enum, Trait) \
3988 case UnaryTransformType::Enum: \
3989 BuiltinName = "__" #Trait; \
3990 break;
3991#include "clang/Basic/TransformTypeTraits.def"
3992 }
3993 Out << BuiltinName.size() << BuiltinName;
3994 }
3995
3996 Out << "I";
3997 mangleType(T->getBaseType());
3998 Out << "E";
3999}
4000
4001void CXXNameMangler::mangleType(const AutoType *T) {
4002 assert(T->getDeducedType().isNull() &&(static_cast <bool> (T->getDeducedType().isNull() &&
"Deduced AutoType shouldn't be handled here!") ? void (0) : __assert_fail
("T->getDeducedType().isNull() && \"Deduced AutoType shouldn't be handled here!\""
, "clang/lib/AST/ItaniumMangle.cpp", 4003, __extension__ __PRETTY_FUNCTION__
))
4003 "Deduced AutoType shouldn't be handled here!")(static_cast <bool> (T->getDeducedType().isNull() &&
"Deduced AutoType shouldn't be handled here!") ? void (0) : __assert_fail
("T->getDeducedType().isNull() && \"Deduced AutoType shouldn't be handled here!\""
, "clang/lib/AST/ItaniumMangle.cpp", 4003, __extension__ __PRETTY_FUNCTION__
))
;
4004 assert(T->getKeyword() != AutoTypeKeyword::GNUAutoType &&(static_cast <bool> (T->getKeyword() != AutoTypeKeyword
::GNUAutoType && "shouldn't need to mangle __auto_type!"
) ? void (0) : __assert_fail ("T->getKeyword() != AutoTypeKeyword::GNUAutoType && \"shouldn't need to mangle __auto_type!\""
, "clang/lib/AST/ItaniumMangle.cpp", 4005, __extension__ __PRETTY_FUNCTION__
))
4005 "shouldn't need to mangle __auto_type!")(static_cast <bool> (T->getKeyword() != AutoTypeKeyword
::GNUAutoType && "shouldn't need to mangle __auto_type!"
) ? void (0) : __assert_fail ("T->getKeyword() != AutoTypeKeyword::GNUAutoType && \"shouldn't need to mangle __auto_type!\""
, "clang/lib/AST/ItaniumMangle.cpp", 4005, __extension__ __PRETTY_FUNCTION__
))
;
4006 // <builtin-type> ::= Da # auto
4007 // ::= Dc # decltype(auto)
4008 Out << (T->isDecltypeAuto() ? "Dc" : "Da");
4009}
4010
4011void CXXNameMangler::mangleType(const DeducedTemplateSpecializationType *T) {
4012 QualType Deduced = T->getDeducedType();
4013 if (!Deduced.isNull())
4014 return mangleType(Deduced);
4015
4016 TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl();
4017 assert(TD && "shouldn't form deduced TST unless we know we have a template")(static_cast <bool> (TD && "shouldn't form deduced TST unless we know we have a template"
) ? void (0) : __assert_fail ("TD && \"shouldn't form deduced TST unless we know we have a template\""
, "clang/lib/AST/ItaniumMangle.cpp", 4017, __extension__ __PRETTY_FUNCTION__
))
;
4018
4019 if (mangleSubstitution(TD))
4020 return;
4021
4022 mangleName(GlobalDecl(TD));
4023 addSubstitution(TD);
4024}
4025
4026void CXXNameMangler::mangleType(const AtomicType *T) {
4027 // <type> ::= U <source-name> <type> # vendor extended type qualifier
4028 // (Until there's a standardized mangling...)
4029 Out << "U7_Atomic";
4030 mangleType(T->getValueType());
4031}
4032
4033void CXXNameMangler::mangleType(const PipeType *T) {
4034 // Pipe type mangling rules are described in SPIR 2.0 specification
4035 // A.1 Data types and A.3 Summary of changes
4036 // <type> ::= 8ocl_pipe
4037 Out << "8ocl_pipe";
4038}
4039
4040void CXXNameMangler::mangleType(const BitIntType *T) {
4041 // 5.1.5.2 Builtin types
4042 // <type> ::= DB <number | instantiation-dependent expression> _
4043 // ::= DU <number | instantiation-dependent expression> _
4044 Out << "D" << (T->isUnsigned() ? "U" : "B") << T->getNumBits() << "_";
4045}
4046
4047void CXXNameMangler::mangleType(const DependentBitIntType *T) {
4048 // 5.1.5.2 Builtin types
4049 // <type> ::= DB <number | instantiation-dependent expression> _
4050 // ::= DU <number | instantiation-dependent expression> _
4051 Out << "D" << (T->isUnsigned() ? "U" : "B");
4052 mangleExpression(T->getNumBitsExpr());
4053 Out << "_";
4054}
4055
4056void CXXNameMangler::mangleIntegerLiteral(QualType T,
4057 const llvm::APSInt &Value) {
4058 // <expr-primary> ::= L <type> <value number> E # integer literal
4059 Out << 'L';
4060
4061 mangleType(T);
4062 if (T->isBooleanType()) {
4063 // Boolean values are encoded as 0/1.
4064 Out << (Value.getBoolValue() ? '1' : '0');
4065 } else {
4066 mangleNumber(Value);
4067 }
4068 Out << 'E';
4069
4070}
4071
4072void CXXNameMangler::mangleMemberExprBase(const Expr *Base, bool IsArrow) {
4073 // Ignore member expressions involving anonymous unions.
4074 while (const auto *RT = Base->getType()->getAs<RecordType>()) {
4075 if (!RT->getDecl()->isAnonymousStructOrUnion())
4076 break;
4077 const auto *ME = dyn_cast<MemberExpr>(Base);
4078 if (!ME)
4079 break;
4080 Base = ME->getBase();
4081 IsArrow = ME->isArrow();
4082 }
4083
4084 if (Base->isImplicitCXXThis()) {
4085 // Note: GCC mangles member expressions to the implicit 'this' as
4086 // *this., whereas we represent them as this->. The Itanium C++ ABI
4087 // does not specify anything here, so we follow GCC.
4088 Out << "dtdefpT";
4089 } else {
4090 Out << (IsArrow ? "pt" : "dt");
4091 mangleExpression(Base);
4092 }
4093}
4094
4095/// Mangles a member expression.
4096void CXXNameMangler::mangleMemberExpr(const Expr *base,
4097 bool isArrow,
4098 NestedNameSpecifier *qualifier,
4099 NamedDecl *firstQualifierLookup,
4100 DeclarationName member,
4101 const TemplateArgumentLoc *TemplateArgs,
4102 unsigned NumTemplateArgs,
4103 unsigned arity) {
4104 // <expression> ::= dt <expression> <unresolved-name>
4105 // ::= pt <expression> <unresolved-name>
4106 if (base)
4107 mangleMemberExprBase(base, isArrow);
4108 mangleUnresolvedName(qualifier, member, TemplateArgs, NumTemplateArgs, arity);
4109}
4110
4111/// Look at the callee of the given call expression and determine if
4112/// it's a parenthesized id-expression which would have triggered ADL
4113/// otherwise.
4114static bool isParenthesizedADLCallee(const CallExpr *call) {
4115 const Expr *callee = call->getCallee();
4116 const Expr *fn = callee->IgnoreParens();
4117
4118 // Must be parenthesized. IgnoreParens() skips __extension__ nodes,
4119 // too, but for those to appear in the callee, it would have to be
4120 // parenthesized.
4121 if (callee == fn) return false;
4122
4123 // Must be an unresolved lookup.
4124 const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);
4125 if (!lookup) return false;
4126
4127 assert(!lookup->requiresADL())(static_cast <bool> (!lookup->requiresADL()) ? void (
0) : __assert_fail ("!lookup->requiresADL()", "clang/lib/AST/ItaniumMangle.cpp"
, 4127, __extension__ __PRETTY_FUNCTION__))
;
4128
4129 // Must be an unqualified lookup.
4130 if (lookup->getQualifier()) return false;
4131
4132 // Must not have found a class member. Note that if one is a class
4133 // member, they're all class members.
4134 if (lookup->getNumDecls() > 0 &&
4135 (*lookup->decls_begin())->isCXXClassMember())
4136 return false;
4137
4138 // Otherwise, ADL would have been triggered.
4139 return true;
4140}
4141
4142void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) {
4143 const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);
4144 Out << CastEncoding;
4145 mangleType(ECE->getType());
4146 mangleExpression(ECE->getSubExpr());
4147}
4148
4149void CXXNameMangler::mangleInitListElements(const InitListExpr *InitList) {
4150 if (auto *Syntactic = InitList->getSyntacticForm())
4151 InitList = Syntactic;
4152 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
4153 mangleExpression(InitList->getInit(i));
4154}
4155
4156void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity,
4157 bool AsTemplateArg) {
4158 // <expression> ::= <unary operator-name> <expression>
4159 // ::= <binary operator-name> <expression> <expression>
4160 // ::= <trinary operator-name> <expression> <expression> <expression>
4161 // ::= cv <type> expression # conversion with one argument
4162 // ::= cv <type> _ <expression>* E # conversion with a different number of arguments
4163 // ::= dc <type> <expression> # dynamic_cast<type> (expression)
4164 // ::= sc <type> <expression> # static_cast<type> (expression)
4165 // ::= cc <type> <expression> # const_cast<type> (expression)
4166 // ::= rc <type> <expression> # reinterpret_cast<type> (expression)
4167 // ::= st <type> # sizeof (a type)
4168 // ::= at <type> # alignof (a type)
4169 // ::= <template-param>
4170 // ::= <function-param>
4171 // ::= fpT # 'this' expression (part of <function-param>)
4172 // ::= sr <type> <unqualified-name> # dependent name
4173 // ::= sr <type> <unqualified-name> <template-args> # dependent template-id
4174 // ::= ds <expression> <expression> # expr.*expr
4175 // ::= sZ <template-param> # size of a parameter pack
4176 // ::= sZ <function-param> # size of a function parameter pack
4177 // ::= u <source-name> <template-arg>* E # vendor extended expression
4178 // ::= <expr-primary>
4179 // <expr-primary> ::= L <type> <value number> E # integer literal
4180 // ::= L <type> <value float> E # floating literal
4181 // ::= L <type> <string type> E # string literal
4182 // ::= L <nullptr type> E # nullptr literal "LDnE"
4183 // ::= L <pointer type> 0 E # null pointer template argument
4184 // ::= L <type> <real-part float> _ <imag-part float> E # complex floating point literal (C99); not used by clang
4185 // ::= L <mangled-name> E # external name
4186 QualType ImplicitlyConvertedToType;
4187
4188 // A top-level expression that's not <expr-primary> needs to be wrapped in
4189 // X...E in a template arg.
4190 bool IsPrimaryExpr = true;
4191 auto NotPrimaryExpr = [&] {
4192 if (AsTemplateArg && IsPrimaryExpr)
4193 Out << 'X';
4194 IsPrimaryExpr = false;
4195 };
4196
4197 auto MangleDeclRefExpr = [&](const NamedDecl *D) {
4198 switch (D->getKind()) {
4199 default:
4200 // <expr-primary> ::= L <mangled-name> E # external name
4201 Out << 'L';
4202 mangle(D);
4203 Out << 'E';
4204 break;
4205
4206 case Decl::ParmVar:
4207 NotPrimaryExpr();
4208 mangleFunctionParam(cast<ParmVarDecl>(D));
4209 break;
4210
4211 case Decl::EnumConstant: {
4212 // <expr-primary>
4213 const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
4214 mangleIntegerLiteral(ED->getType(), ED->getInitVal());
4215 break;
4216 }
4217
4218 case Decl::NonTypeTemplateParm:
4219 NotPrimaryExpr();
4220 const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
4221 mangleTemplateParameter(PD->getDepth(), PD->getIndex());
4222 break;
4223 }
4224 };
4225
4226 // 'goto recurse' is used when handling a simple "unwrapping" node which
4227 // produces no output, where ImplicitlyConvertedToType and AsTemplateArg need
4228 // to be preserved.
4229recurse:
4230 switch (E->getStmtClass()) {
4231 case Expr::NoStmtClass:
4232#define ABSTRACT_STMT(Type)
4233#define EXPR(Type, Base)
4234#define STMT(Type, Base) \
4235 case Expr::Type##Class:
4236#include "clang/AST/StmtNodes.inc"
4237 // fallthrough
4238
4239 // These all can only appear in local or variable-initialization
4240 // contexts and so should never appear in a mangling.
4241 case Expr::AddrLabelExprClass:
4242 case Expr::DesignatedInitUpdateExprClass:
4243 case Expr::ImplicitValueInitExprClass:
4244 case Expr::ArrayInitLoopExprClass:
4245 case Expr::ArrayInitIndexExprClass:
4246 case Expr::NoInitExprClass:
4247 case Expr::ParenListExprClass:
4248 case Expr::MSPropertyRefExprClass:
4249 case Expr::MSPropertySubscriptExprClass:
4250 case Expr::TypoExprClass: // This should no longer exist in the AST by now.
4251 case Expr::RecoveryExprClass:
4252 case Expr::OMPArraySectionExprClass:
4253 case Expr::OMPArrayShapingExprClass:
4254 case Expr::OMPIteratorExprClass:
4255 case Expr::CXXInheritedCtorInitExprClass:
4256 llvm_unreachable("unexpected statement kind")::llvm::llvm_unreachable_internal("unexpected statement kind"
, "clang/lib/AST/ItaniumMangle.cpp", 4256)
;
4257
4258 case Expr::ConstantExprClass:
4259 E = cast<ConstantExpr>(E)->getSubExpr();
4260 goto recurse;
4261
4262 // FIXME: invent manglings for all these.
4263 case Expr::BlockExprClass:
4264 case Expr::ChooseExprClass:
4265 case Expr::CompoundLiteralExprClass:
4266 case Expr::ExtVectorElementExprClass:
4267 case Expr::GenericSelectionExprClass:
4268 case Expr::ObjCEncodeExprClass:
4269 case Expr::ObjCIsaExprClass:
4270 case Expr::ObjCIvarRefExprClass:
4271 case Expr::ObjCMessageExprClass:
4272 case Expr::ObjCPropertyRefExprClass:
4273 case Expr::ObjCProtocolExprClass:
4274 case Expr::ObjCSelectorExprClass:
4275 case Expr::ObjCStringLiteralClass:
4276 case Expr::ObjCBoxedExprClass:
4277 case Expr::ObjCArrayLiteralClass:
4278 case Expr::ObjCDictionaryLiteralClass:
4279 case Expr::ObjCSubscriptRefExprClass:
4280 case Expr::ObjCIndirectCopyRestoreExprClass:
4281 case Expr::ObjCAvailabilityCheckExprClass:
4282 case Expr::OffsetOfExprClass:
4283 case Expr::PredefinedExprClass:
4284 case Expr::ShuffleVectorExprClass:
4285 case Expr::ConvertVectorExprClass:
4286 case Expr::StmtExprClass:
4287 case Expr::TypeTraitExprClass:
4288 case Expr::RequiresExprClass:
4289 case Expr::ArrayTypeTraitExprClass:
4290 case Expr::ExpressionTraitExprClass:
4291 case Expr::VAArgExprClass:
4292 case Expr::CUDAKernelCallExprClass:
4293 case Expr::AsTypeExprClass:
4294 case Expr::PseudoObjectExprClass:
4295 case Expr::AtomicExprClass:
4296 case Expr::SourceLocExprClass:
4297 case Expr::BuiltinBitCastExprClass:
4298 {
4299 NotPrimaryExpr();
4300 if (!NullOut) {
4301 // As bad as this diagnostic is, it's better than crashing.
4302 DiagnosticsEngine &Diags = Context.getDiags();
4303 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
4304 "cannot yet mangle expression type %0");
4305 Diags.Report(E->getExprLoc(), DiagID)
4306 << E->getStmtClassName() << E->getSourceRange();
4307 return;
4308 }
4309 break;
4310 }
4311
4312 case Expr::CXXUuidofExprClass: {
4313 NotPrimaryExpr();
4314 const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E);
4315 // As of clang 12, uuidof uses the vendor extended expression
4316 // mangling. Previously, it used a special-cased nonstandard extension.
4317 if (Context.getASTContext().getLangOpts().getClangABICompat() >
4318 LangOptions::ClangABI::Ver11) {
4319 Out << "u8__uuidof";
4320 if (UE->isTypeOperand())
4321 mangleType(UE->getTypeOperand(Context.getASTContext()));
4322 else
4323 mangleTemplateArgExpr(UE->getExprOperand());
4324 Out << 'E';
4325 } else {
4326 if (UE->isTypeOperand()) {
4327 QualType UuidT = UE->getTypeOperand(Context.getASTContext());
4328 Out << "u8__uuidoft";
4329 mangleType(UuidT);
4330 } else {
4331 Expr *UuidExp = UE->getExprOperand();
4332 Out << "u8__uuidofz";
4333 mangleExpression(UuidExp);
4334 }
4335 }
4336 break;
4337 }
4338
4339 // Even gcc-4.5 doesn't mangle this.
4340 case Expr::BinaryConditionalOperatorClass: {
4341 NotPrimaryExpr();
4342 DiagnosticsEngine &Diags = Context.getDiags();
4343 unsigned DiagID =
4344 Diags.getCustomDiagID(DiagnosticsEngine::Error,
4345 "?: operator with omitted middle operand cannot be mangled");
4346 Diags.Report(E->getExprLoc(), DiagID)
4347 << E->getStmtClassName() << E->getSourceRange();
4348 return;
4349 }
4350
4351 // These are used for internal purposes and cannot be meaningfully mangled.
4352 case Expr::OpaqueValueExprClass:
4353 llvm_unreachable("cannot mangle opaque value; mangling wrong thing?")::llvm::llvm_unreachable_internal("cannot mangle opaque value; mangling wrong thing?"
, "clang/lib/AST/ItaniumMangle.cpp", 4353)
;
4354
4355 case Expr::InitListExprClass: {
4356 NotPrimaryExpr();
4357 Out << "il";
4358 mangleInitListElements(cast<InitListExpr>(E));
4359 Out << "E";
4360 break;
4361 }
4362
4363 case Expr::DesignatedInitExprClass: {
4364 NotPrimaryExpr();
4365 auto *DIE = cast<DesignatedInitExpr>(E);
4366 for (const auto &Designator : DIE->designators()) {
4367 if (Designator.isFieldDesignator()) {
4368 Out << "di";
4369 mangleSourceName(Designator.getFieldName());
4370 } else if (Designator.isArrayDesignator()) {
4371 Out << "dx";
4372 mangleExpression(DIE->getArrayIndex(Designator));
4373 } else {
4374 assert(Designator.isArrayRangeDesignator() &&(static_cast <bool> (Designator.isArrayRangeDesignator(
) && "unknown designator kind") ? void (0) : __assert_fail
("Designator.isArrayRangeDesignator() && \"unknown designator kind\""
, "clang/lib/AST/ItaniumMangle.cpp", 4375, __extension__ __PRETTY_FUNCTION__
))
4375 "unknown designator kind")(static_cast <bool> (Designator.isArrayRangeDesignator(
) && "unknown designator kind") ? void (0) : __assert_fail
("Designator.isArrayRangeDesignator() && \"unknown designator kind\""
, "clang/lib/AST/ItaniumMangle.cpp", 4375, __extension__ __PRETTY_FUNCTION__
))
;
4376 Out << "dX";
4377 mangleExpression(DIE->getArrayRangeStart(Designator));
4378 mangleExpression(DIE->getArrayRangeEnd(Designator));
4379 }
4380 }
4381 mangleExpression(DIE->getInit());
4382 break;
4383 }
4384
4385 case Expr::CXXDefaultArgExprClass:
4386 E = cast<CXXDefaultArgExpr>(E)->getExpr();
4387 goto recurse;
4388
4389 case Expr::CXXDefaultInitExprClass:
4390 E = cast<CXXDefaultInitExpr>(E)->getExpr();
4391 goto recurse;
4392
4393 case Expr::CXXStdInitializerListExprClass:
4394 E = cast<CXXStdInitializerListExpr>(E)->getSubExpr();
4395 goto recurse;
4396
4397 case Expr::SubstNonTypeTemplateParmExprClass:
4398 E = cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement();
4399 goto recurse;
4400
4401 case Expr::UserDefinedLiteralClass:
4402 // We follow g++'s approach of mangling a UDL as a call to the literal
4403 // operator.
4404 case Expr::CXXMemberCallExprClass: // fallthrough
4405 case Expr::CallExprClass: {
4406 NotPrimaryExpr();
4407 const CallExpr *CE = cast<CallExpr>(E);
4408
4409 // <expression> ::= cp <simple-id> <expression>* E
4410 // We use this mangling only when the call would use ADL except
4411 // for being parenthesized. Per discussion with David
4412 // Vandervoorde, 2011.04.25.
4413 if (isParenthesizedADLCallee(CE)) {
4414 Out << "cp";
4415 // The callee here is a parenthesized UnresolvedLookupExpr with
4416 // no qualifier and should always get mangled as a <simple-id>
4417 // anyway.
4418
4419 // <expression> ::= cl <expression>* E
4420 } else {
4421 Out << "cl";
4422 }
4423
4424 unsigned CallArity = CE->getNumArgs();
4425 for (const Expr *Arg : CE->arguments())
4426 if (isa<PackExpansionExpr>(Arg))
4427 CallArity = UnknownArity;
4428
4429 mangleExpression(CE->getCallee(), CallArity);
4430 for (const Expr *Arg : CE->arguments())
4431 mangleExpression(Arg);
4432 Out << 'E';
4433 break;
4434 }
4435
4436 case Expr::CXXNewExprClass: {
4437 NotPrimaryExpr();
4438 const CXXNewExpr *New = cast<CXXNewExpr>(E);
4439 if (New->isGlobalNew()) Out << "gs";
4440 Out << (New->isArray() ? "na" : "nw");
4441 for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(),
4442 E = New->placement_arg_end(); I != E; ++I)
4443 mangleExpression(*I);
4444 Out << '_';
4445 mangleType(New->getAllocatedType());
4446 if (New->hasInitializer()) {
4447 if (New->getInitializationStyle() == CXXNewExpr::ListInit)
4448 Out << "il";
4449 else
4450 Out << "pi";
4451 const Expr *Init = New->getInitializer();
4452 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
4453 // Directly inline the initializers.
4454 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
4455 E = CCE->arg_end();
4456 I != E; ++I)
4457 mangleExpression(*I);
4458 } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {
4459 for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)
4460 mangleExpression(PLE->getExpr(i));
4461 } else if (New->getInitializationStyle() == CXXNewExpr::ListInit &&
4462 isa<InitListExpr>(Init)) {
4463 // Only take InitListExprs apart for list-initialization.
4464 mangleInitListElements(cast<InitListExpr>(Init));
4465 } else
4466 mangleExpression(Init);
4467 }
4468 Out << 'E';
4469 break;
4470 }
4471
4472 case Expr::CXXPseudoDestructorExprClass: {
4473 NotPrimaryExpr();
4474 const auto *PDE = cast<CXXPseudoDestructorExpr>(E);
4475 if (const Expr *Base = PDE->getBase())
4476 mangleMemberExprBase(Base, PDE->isArrow());
4477 NestedNameSpecifier *Qualifier = PDE->getQualifier();
4478 if (TypeSourceInfo *ScopeInfo = PDE->getScopeTypeInfo()) {
4479 if (Qualifier) {
4480 mangleUnresolvedPrefix(Qualifier,
4481 /*recursive=*/true);
4482 mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType());
4483 Out << 'E';
4484 } else {
4485 Out << "sr";
4486 if (!mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType()))
4487 Out << 'E';
4488 }
4489 } else if (Qualifier) {
4490 mangleUnresolvedPrefix(Qualifier);
4491 }
4492 // <base-unresolved-name> ::= dn <destructor-name>
4493 Out << "dn";
4494 QualType DestroyedType = PDE->getDestroyedType();
4495 mangleUnresolvedTypeOrSimpleId(DestroyedType);
4496 break;
4497 }
4498
4499 case Expr::MemberExprClass: {
4500 NotPrimaryExpr();
4501 const MemberExpr *ME = cast<MemberExpr>(E);
4502 mangleMemberExpr(ME->getBase(), ME->isArrow(),
4503 ME->getQualifier(), nullptr,
4504 ME->getMemberDecl()->getDeclName(),
4505 ME->getTemplateArgs(), ME->getNumTemplateArgs(),
4506 Arity);
4507 break;
4508 }
4509
4510 case Expr::UnresolvedMemberExprClass: {
4511 NotPrimaryExpr();
4512 const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
4513 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
4514 ME->isArrow(), ME->getQualifier(), nullptr,
4515 ME->getMemberName(),
4516 ME->getTemplateArgs(), ME->getNumTemplateArgs(),
4517 Arity);
4518 break;
4519 }
4520
4521 case Expr::CXXDependentScopeMemberExprClass: {
4522 NotPrimaryExpr();
4523 const CXXDependentScopeMemberExpr *ME
4524 = cast<CXXDependentScopeMemberExpr>(E);
4525 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
4526 ME->isArrow(), ME->getQualifier(),
4527 ME->getFirstQualifierFoundInScope(),
4528 ME->getMember(),
4529 ME->getTemplateArgs(), ME->getNumTemplateArgs(),
4530 Arity);
4531 break;
4532 }
4533
4534 case Expr::UnresolvedLookupExprClass: {
4535 NotPrimaryExpr();
4536 const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
4537 mangleUnresolvedName(ULE->getQualifier(), ULE->getName(),
4538 ULE->getTemplateArgs(), ULE->getNumTemplateArgs(),
4539 Arity);
4540 break;
4541 }
4542
4543 case Expr::CXXUnresolvedConstructExprClass: {
4544 NotPrimaryExpr();
4545 const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
4546 unsigned N = CE->getNumArgs();
4547
4548 if (CE->isListInitialization()) {
4549 assert(N == 1 && "unexpected form for list initialization")(static_cast <bool> (N == 1 && "unexpected form for list initialization"
) ? void (0) : __assert_fail ("N == 1 && \"unexpected form for list initialization\""
, "clang/lib/AST/ItaniumMangle.cpp", 4549, __extension__ __PRETTY_FUNCTION__
))
;
4550 auto *IL = cast<InitListExpr>(CE->getArg(0));
4551 Out << "tl";
4552 mangleType(CE->getType());
4553 mangleInitListElements(IL);
4554 Out << "E";
4555 break;
4556 }
4557
4558 Out << "cv";
4559 mangleType(CE->getType());
4560 if (N != 1) Out << '_';
4561 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
4562 if (N != 1) Out << 'E';
4563 break;
4564 }
4565
4566 case Expr::CXXConstructExprClass: {
4567 // An implicit cast is silent, thus may contain <expr-primary>.
4568 const auto *CE = cast<CXXConstructExpr>(E);
4569 if (!CE->isListInitialization() || CE->isStdInitListInitialization()) {
4570 assert((static_cast <bool> (CE->getNumArgs() >= 1 &&
(CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE
->getArg(1))) && "implicit CXXConstructExpr must have one argument"
) ? void (0) : __assert_fail ("CE->getNumArgs() >= 1 && (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) && \"implicit CXXConstructExpr must have one argument\""
, "clang/lib/AST/ItaniumMangle.cpp", 4573, __extension__ __PRETTY_FUNCTION__
))
4571 CE->getNumArgs() >= 1 &&(static_cast <bool> (CE->getNumArgs() >= 1 &&
(CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE
->getArg(1))) && "implicit CXXConstructExpr must have one argument"
) ? void (0) : __assert_fail ("CE->getNumArgs() >= 1 && (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) && \"implicit CXXConstructExpr must have one argument\""
, "clang/lib/AST/ItaniumMangle.cpp", 4573, __extension__ __PRETTY_FUNCTION__
))
4572 (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) &&(static_cast <bool> (CE->getNumArgs() >= 1 &&
(CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE
->getArg(1))) && "implicit CXXConstructExpr must have one argument"
) ? void (0) : __assert_fail ("CE->getNumArgs() >= 1 && (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) && \"implicit CXXConstructExpr must have one argument\""
, "clang/lib/AST/ItaniumMangle.cpp", 4573, __extension__ __PRETTY_FUNCTION__
))
4573 "implicit CXXConstructExpr must have one argument")(static_cast <bool> (CE->getNumArgs() >= 1 &&
(CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE
->getArg(1))) && "implicit CXXConstructExpr must have one argument"
) ? void (0) : __assert_fail ("CE->getNumArgs() >= 1 && (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) && \"implicit CXXConstructExpr must have one argument\""
, "clang/lib/AST/ItaniumMangle.cpp", 4573, __extension__ __PRETTY_FUNCTION__
))
;
4574 E = cast<CXXConstructExpr>(E)->getArg(0);
4575 goto recurse;
4576 }
4577 NotPrimaryExpr();
4578 Out << "il";
4579 for (auto *E : CE->arguments())
4580 mangleExpression(E);
4581 Out << "E";
4582 break;
4583 }
4584
4585 case Expr::CXXTemporaryObjectExprClass: {
4586 NotPrimaryExpr();
4587 const auto *CE = cast<CXXTemporaryObjectExpr>(E);
4588 unsigned N = CE->getNumArgs();
4589 bool List = CE->isListInitialization();
4590
4591 if (List)
4592 Out << "tl";
4593 else
4594 Out << "cv";
4595 mangleType(CE->getType());
4596 if (!List && N != 1)
4597 Out << '_';
4598 if (CE->isStdInitListInitialization()) {
4599 // We implicitly created a std::initializer_list<T> for the first argument
4600 // of a constructor of type U in an expression of the form U{a, b, c}.
4601 // Strip all the semantic gunk off the initializer list.
4602 auto *SILE =
4603 cast<CXXStdInitializerListExpr>(CE->getArg(0)->IgnoreImplicit());
4604 auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit());
4605 mangleInitListElements(ILE);
4606 } else {
4607 for (auto *E : CE->arguments())
4608 mangleExpression(E);
4609 }
4610 if (List || N != 1)
4611 Out << 'E';
4612 break;
4613 }
4614
4615 case Expr::CXXScalarValueInitExprClass:
4616 NotPrimaryExpr();
4617 Out << "cv";
4618 mangleType(E->getType());
4619 Out << "_E";
4620 break;
4621
4622 case Expr::CXXNoexceptExprClass:
4623 NotPrimaryExpr();
4624 Out << "nx";
4625 mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());
4626 break;
4627
4628 case Expr::UnaryExprOrTypeTraitExprClass: {
4629 // Non-instantiation-dependent traits are an <expr-primary> integer literal.
4630 const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);
4631
4632 if (!SAE->isInstantiationDependent()) {
4633 // Itanium C++ ABI:
4634 // If the operand of a sizeof or alignof operator is not
4635 // instantiation-dependent it is encoded as an integer literal
4636 // reflecting the result of the operator.
4637 //
4638 // If the result of the operator is implicitly converted to a known
4639 // integer type, that type is used for the literal; otherwise, the type
4640 // of std::size_t or std::ptrdiff_t is used.
4641 QualType T = (ImplicitlyConvertedToType.isNull() ||
4642 !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
4643 : ImplicitlyConvertedToType;
4644 llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());
4645 mangleIntegerLiteral(T, V);
4646 break;
4647 }
4648
4649 NotPrimaryExpr(); // But otherwise, they are not.
4650
4651 auto MangleAlignofSizeofArg = [&] {
4652 if (SAE->isArgumentType()) {
4653 Out << 't';
4654 mangleType(SAE->getArgumentType());
4655 } else {
4656 Out << 'z';
4657 mangleExpression(SAE->getArgumentExpr());
4658 }
4659 };
4660
4661 switch(SAE->getKind()) {
4662 case UETT_SizeOf:
4663 Out << 's';
4664 MangleAlignofSizeofArg();
4665 break;
4666 case UETT_PreferredAlignOf:
4667 // As of clang 12, we mangle __alignof__ differently than alignof. (They
4668 // have acted differently since Clang 8, but were previously mangled the
4669 // same.)
4670 if (Context.getASTContext().getLangOpts().getClangABICompat() >
4671 LangOptions::ClangABI::Ver11) {
4672 Out << "u11__alignof__";
4673 if (SAE->isArgumentType())
4674 mangleType(SAE->getArgumentType());
4675 else
4676 mangleTemplateArgExpr(SAE->getArgumentExpr());
4677 Out << 'E';
4678 break;
4679 }
4680 [[fallthrough]];
4681 case UETT_AlignOf:
4682 Out << 'a';
4683 MangleAlignofSizeofArg();
4684 break;
4685 case UETT_VecStep: {
4686 DiagnosticsEngine &Diags = Context.getDiags();
4687 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
4688 "cannot yet mangle vec_step expression");
4689 Diags.Report(DiagID);
4690 return;
4691 }
4692 case UETT_OpenMPRequiredSimdAlign: {
4693 DiagnosticsEngine &Diags = Context.getDiags();
4694 unsigned DiagID = Diags.getCustomDiagID(
4695 DiagnosticsEngine::Error,
4696 "cannot yet mangle __builtin_omp_required_simd_align expression");
4697 Diags.Report(DiagID);
4698 return;
4699 }
4700 }
4701 break;
4702 }
4703
4704 case Expr::CXXThrowExprClass: {
4705 NotPrimaryExpr();
4706 const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
4707 // <expression> ::= tw <expression> # throw expression
4708 // ::= tr # rethrow
4709 if (TE->getSubExpr()) {
4710 Out << "tw";
4711 mangleExpression(TE->getSubExpr());
4712 } else {
4713 Out << "tr";
4714 }
4715 break;
4716 }
4717
4718 case Expr::CXXTypeidExprClass: {
4719 NotPrimaryExpr();
4720 const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
4721 // <expression> ::= ti <type> # typeid (type)
4722 // ::= te <expression> # typeid (expression)
4723 if (TIE->isTypeOperand()) {
4724 Out << "ti";
4725 mangleType(TIE->getTypeOperand(Context.getASTContext()));
4726 } else {
4727 Out << "te";
4728 mangleExpression(TIE->getExprOperand());
4729 }
4730 break;
4731 }
4732
4733 case Expr::CXXDeleteExprClass: {
4734 NotPrimaryExpr();
4735 const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
4736 // <expression> ::= [gs] dl <expression> # [::] delete expr
4737 // ::= [gs] da <expression> # [::] delete [] expr
4738 if (DE->isGlobalDelete()) Out << "gs";
4739 Out << (DE->isArrayForm() ? "da" : "dl");
4740 mangleExpression(DE->getArgument());
4741 break;
4742 }
4743
4744 case Expr::UnaryOperatorClass: {
4745 NotPrimaryExpr();
4746 const UnaryOperator *UO = cast<UnaryOperator>(E);
4747 mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
4748 /*Arity=*/1);
4749 mangleExpression(UO->getSubExpr());
4750 break;
4751 }
4752
4753 case Expr::ArraySubscriptExprClass: {
4754 NotPrimaryExpr();
4755 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
4756
4757 // Array subscript is treated as a syntactically weird form of
4758 // binary operator.
4759 Out << "ix";
4760 mangleExpression(AE->getLHS());
4761 mangleExpression(AE->getRHS());
4762 break;
4763 }
4764
4765 case Expr::MatrixSubscriptExprClass: {
4766 NotPrimaryExpr();
4767 const MatrixSubscriptExpr *ME = cast<MatrixSubscriptExpr>(E);
4768 Out << "ixix";
4769 mangleExpression(ME->getBase());
4770 mangleExpression(ME->getRowIdx());
4771 mangleExpression(ME->getColumnIdx());
4772 break;
4773 }
4774
4775 case Expr::CompoundAssignOperatorClass: // fallthrough
4776 case Expr::BinaryOperatorClass: {
4777 NotPrimaryExpr();
4778 const BinaryOperator *BO = cast<BinaryOperator>(E);
4779 if (BO->getOpcode() == BO_PtrMemD)
4780 Out << "ds";
4781 else
4782 mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
4783 /*Arity=*/2);
4784 mangleExpression(BO->getLHS());
4785 mangleExpression(BO->getRHS());
4786 break;
4787 }
4788
4789 case Expr::CXXRewrittenBinaryOperatorClass: {
4790 NotPrimaryExpr();
4791 // The mangled form represents the original syntax.
4792 CXXRewrittenBinaryOperator::DecomposedForm Decomposed =
4793 cast<CXXRewrittenBinaryOperator>(E)->getDecomposedForm();
4794 mangleOperatorName(BinaryOperator::getOverloadedOperator(Decomposed.Opcode),
4795 /*Arity=*/2);
4796 mangleExpression(Decomposed.LHS);
4797 mangleExpression(Decomposed.RHS);
4798 break;
4799 }
4800
4801 case Expr::ConditionalOperatorClass: {
4802 NotPrimaryExpr();
4803 const ConditionalOperator *CO = cast<ConditionalOperator>(E);
4804 mangleOperatorName(OO_Conditional, /*Arity=*/3);
4805 mangleExpression(CO->getCond());
4806 mangleExpression(CO->getLHS(), Arity);
4807 mangleExpression(CO->getRHS(), Arity);
4808 break;
4809 }
4810
4811 case Expr::ImplicitCastExprClass: {
4812 ImplicitlyConvertedToType = E->getType();
4813 E = cast<ImplicitCastExpr>(E)->getSubExpr();
4814 goto recurse;
4815 }
4816
4817 case Expr::ObjCBridgedCastExprClass: {
4818 NotPrimaryExpr();
4819 // Mangle ownership casts as a vendor extended operator __bridge,
4820 // __bridge_transfer, or __bridge_retain.
4821 StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();
4822 Out << "v1U" << Kind.size() << Kind;
4823 mangleCastExpression(E, "cv");
4824 break;
4825 }
4826
4827 case Expr::CStyleCastExprClass:
4828 NotPrimaryExpr();
4829 mangleCastExpression(E, "cv");
4830 break;
4831
4832 case Expr::CXXFunctionalCastExprClass: {
4833 NotPrimaryExpr();
4834 auto *Sub = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreImplicit();
4835 // FIXME: Add isImplicit to CXXConstructExpr.
4836 if (auto *CCE = dyn_cast<CXXConstructExpr>(Sub))
4837 if (CCE->getParenOrBraceRange().isInvalid())
4838 Sub = CCE->getArg(0)->IgnoreImplicit();
4839 if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Sub))
4840 Sub = StdInitList->getSubExpr()->IgnoreImplicit();
4841 if (auto *IL = dyn_cast<InitListExpr>(Sub)) {
4842 Out << "tl";
4843 mangleType(E->getType());
4844 mangleInitListElements(IL);
4845 Out << "E";
4846 } else {
4847 mangleCastExpression(E, "cv");
4848 }
4849 break;
4850 }
4851
4852 case Expr::CXXStaticCastExprClass:
4853 NotPrimaryExpr();
4854 mangleCastExpression(E, "sc");
4855 break;
4856 case Expr::CXXDynamicCastExprClass:
4857 NotPrimaryExpr();
4858 mangleCastExpression(E, "dc");
4859 break;
4860 case Expr::CXXReinterpretCastExprClass:
4861 NotPrimaryExpr();
4862 mangleCastExpression(E, "rc");
4863 break;
4864 case Expr::CXXConstCastExprClass:
4865 NotPrimaryExpr();
4866 mangleCastExpression(E, "cc");
4867 break;
4868 case Expr::CXXAddrspaceCastExprClass:
4869 NotPrimaryExpr();
4870 mangleCastExpression(E, "ac");
4871 break;
4872
4873 case Expr::CXXOperatorCallExprClass: {
4874 NotPrimaryExpr();
4875 const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
4876 unsigned NumArgs = CE->getNumArgs();
4877 // A CXXOperatorCallExpr for OO_Arrow models only semantics, not syntax
4878 // (the enclosing MemberExpr covers the syntactic portion).
4879 if (CE->getOperator() != OO_Arrow)
4880 mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);
4881 // Mangle the arguments.
4882 for (unsigned i = 0; i != NumArgs; ++i)
4883 mangleExpression(CE->getArg(i));
4884 break;
4885 }
4886
4887 case Expr::ParenExprClass:
4888 E = cast<ParenExpr>(E)->getSubExpr();
4889 goto recurse;
4890
4891 case Expr::ConceptSpecializationExprClass: {
4892 // <expr-primary> ::= L <mangled-name> E # external name
4893 Out << "L_Z";
4894 auto *CSE = cast<ConceptSpecializationExpr>(E);
4895 mangleTemplateName(CSE->getNamedConcept(),
4896 CSE->getTemplateArguments().data(),
4897 CSE->getTemplateArguments().size());
4898 Out << 'E';
4899 break;
4900 }
4901
4902 case Expr::DeclRefExprClass:
4903 // MangleDeclRefExpr helper handles primary-vs-nonprimary
4904 MangleDeclRefExpr(cast<DeclRefExpr>(E)->getDecl());
4905 break;
4906
4907 case Expr::SubstNonTypeTemplateParmPackExprClass:
4908 NotPrimaryExpr();
4909 // FIXME: not clear how to mangle this!
4910 // template <unsigned N...> class A {
4911 // template <class U...> void foo(U (&x)[N]...);
4912 // };
4913 Out << "_SUBSTPACK_";
4914 break;
4915
4916 case Expr::FunctionParmPackExprClass: {
4917 NotPrimaryExpr();
4918 // FIXME: not clear how to mangle this!
4919 const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);
4920 Out << "v110_SUBSTPACK";
4921 MangleDeclRefExpr(FPPE->getParameterPack());
4922 break;
4923 }
4924
4925 case Expr::DependentScopeDeclRefExprClass: {
4926 NotPrimaryExpr();
4927 const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
4928 mangleUnresolvedName(DRE->getQualifier(), DRE->getDeclName(),
4929 DRE->getTemplateArgs(), DRE->getNumTemplateArgs(),
4930 Arity);
4931 break;
4932 }
4933
4934 case Expr::CXXBindTemporaryExprClass:
4935 E = cast<CXXBindTemporaryExpr>(E)->getSubExpr();
4936 goto recurse;
4937
4938 case Expr::ExprWithCleanupsClass:
4939 E = cast<ExprWithCleanups>(E)->getSubExpr();
4940 goto recurse;
4941
4942 case Expr::FloatingLiteralClass: {
4943 // <expr-primary>
4944 const FloatingLiteral *FL = cast<FloatingLiteral>(E);
4945 mangleFloatLiteral(FL->getType(), FL->getValue());
4946 break;
4947 }
4948
4949 case Expr::FixedPointLiteralClass:
4950 // Currently unimplemented -- might be <expr-primary> in future?
4951 mangleFixedPointLiteral();
4952 break;
4953
4954 case Expr::CharacterLiteralClass:
4955 // <expr-primary>
4956 Out << 'L';
4957 mangleType(E->getType());
4958 Out << cast<CharacterLiteral>(E)->getValue();
4959 Out << 'E';
4960 break;
4961
4962 // FIXME. __objc_yes/__objc_no are mangled same as true/false
4963 case Expr::ObjCBoolLiteralExprClass:
4964 // <expr-primary>
4965 Out << "Lb";
4966 Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');
4967 Out << 'E';
4968 break;
4969
4970 case Expr::CXXBoolLiteralExprClass:
4971 // <expr-primary>
4972 Out << "Lb";
4973 Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
4974 Out << 'E';
4975 break;
4976
4977 case Expr::IntegerLiteralClass: {
4978 // <expr-primary>
4979 llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
4980 if (E->getType()->isSignedIntegerType())
4981 Value.setIsSigned(true);
4982 mangleIntegerLiteral(E->getType(), Value);
4983 break;
4984 }
4985
4986 case Expr::ImaginaryLiteralClass: {
4987 // <expr-primary>
4988 const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
4989 // Mangle as if a complex literal.
4990 // Proposal from David Vandevoorde, 2010.06.30.
4991 Out << 'L';
4992 mangleType(E->getType());
4993 if (const FloatingLiteral *Imag =
4994 dyn_cast<FloatingLiteral>(IE->getSubExpr())) {
4995 // Mangle a floating-point zero of the appropriate type.
4996 mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));
4997 Out << '_';
4998 mangleFloat(Imag->getValue());
4999 } else {
5000 Out << "0_";
5001 llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
5002 if (IE->getSubExpr()->getType()->isSignedIntegerType())
5003 Value.setIsSigned(true);
5004 mangleNumber(Value);
5005 }
5006 Out << 'E';
5007 break;
5008 }
5009
5010 case Expr::StringLiteralClass: {
5011 // <expr-primary>
5012 // Revised proposal from David Vandervoorde, 2010.07.15.
5013 Out << 'L';
5014 assert(isa<ConstantArrayType>(E->getType()))(static_cast <bool> (isa<ConstantArrayType>(E->
getType())) ? void (0) : __assert_fail ("isa<ConstantArrayType>(E->getType())"
, "clang/lib/AST/ItaniumMangle.cpp", 5014, __extension__ __PRETTY_FUNCTION__
))
;
5015 mangleType(E->getType());
5016 Out << 'E';
5017 break;
5018 }
5019
5020 case Expr::GNUNullExprClass:
5021 // <expr-primary>
5022 // Mangle as if an integer literal 0.
5023 mangleIntegerLiteral(E->getType(), llvm::APSInt(32));
5024 break;
5025
5026 case Expr::CXXNullPtrLiteralExprClass: {
5027 // <expr-primary>
5028 Out << "LDnE";
5029 break;
5030 }
5031
5032 case Expr::LambdaExprClass: {
5033 // A lambda-expression can't appear in the signature of an
5034 // externally-visible declaration, so there's no standard mangling for
5035 // this, but mangling as a literal of the closure type seems reasonable.
5036 Out << "L";
5037 mangleType(Context.getASTContext().getRecordType(cast<LambdaExpr>(E)->getLambdaClass()));
5038 Out << "E";
5039 break;
5040 }
5041
5042 case Expr::PackExpansionExprClass:
5043 NotPrimaryExpr();
5044 Out << "sp";
5045 mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
5046 break;
5047
5048 case Expr::SizeOfPackExprClass: {
5049 NotPrimaryExpr();
5050 auto *SPE = cast<SizeOfPackExpr>(E);
5051 if (SPE->isPartiallySubstituted()) {
5052 Out << "sP";
5053 for (const auto &A : SPE->getPartialArguments())
5054 mangleTemplateArg(A, false);
5055 Out << "E";
5056 break;
5057 }
5058
5059 Out << "sZ";
5060 const NamedDecl *Pack = SPE->getPack();
5061 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))
5062 mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
5063 else if (const NonTypeTemplateParmDecl *NTTP
5064 = dyn_cast<NonTypeTemplateParmDecl>(Pack))
5065 mangleTemplateParameter(NTTP->getDepth(), NTTP->getIndex());
5066 else if (const TemplateTemplateParmDecl *TempTP
5067 = dyn_cast<TemplateTemplateParmDecl>(Pack))
5068 mangleTemplateParameter(TempTP->getDepth(), TempTP->getIndex());
5069 else
5070 mangleFunctionParam(cast<ParmVarDecl>(Pack));
5071 break;
5072 }
5073
5074 case Expr::MaterializeTemporaryExprClass:
5075 E = cast<MaterializeTemporaryExpr>(E)->getSubExpr();
5076 goto recurse;
5077
5078 case Expr::CXXFoldExprClass: {
5079 NotPrimaryExpr();
5080 auto *FE = cast<CXXFoldExpr>(E);
5081 if (FE->isLeftFold())
5082 Out << (FE->getInit() ? "fL" : "fl");
5083 else
5084 Out << (FE->getInit() ? "fR" : "fr");
5085
5086 if (FE->getOperator() == BO_PtrMemD)
5087 Out << "ds";
5088 else
5089 mangleOperatorName(
5090 BinaryOperator::getOverloadedOperator(FE->getOperator()),
5091 /*Arity=*/2);
5092
5093 if (FE->getLHS())
5094 mangleExpression(FE->getLHS());
5095 if (FE->getRHS())
5096 mangleExpression(FE->getRHS());
5097 break;
5098 }
5099
5100 case Expr::CXXThisExprClass:
5101 NotPrimaryExpr();
5102 Out << "fpT";
5103 break;
5104
5105 case Expr::CoawaitExprClass:
5106 // FIXME: Propose a non-vendor mangling.
5107 NotPrimaryExpr();
5108 Out << "v18co_await";
5109 mangleExpression(cast<CoawaitExpr>(E)->getOperand());
5110 break;
5111
5112 case Expr::DependentCoawaitExprClass:
5113 // FIXME: Propose a non-vendor mangling.
5114 NotPrimaryExpr();
5115 Out << "v18co_await";
5116 mangleExpression(cast<DependentCoawaitExpr>(E)->getOperand());
5117 break;
5118
5119 case Expr::CoyieldExprClass:
5120 // FIXME: Propose a non-vendor mangling.
5121 NotPrimaryExpr();
5122 Out << "v18co_yield";
5123 mangleExpression(cast<CoawaitExpr>(E)->getOperand());
5124 break;
5125 case Expr::SYCLUniqueStableNameExprClass: {
5126 const auto *USN = cast<SYCLUniqueStableNameExpr>(E);
5127 NotPrimaryExpr();
5128
5129 Out << "u33__builtin_sycl_unique_stable_name";
5130 mangleType(USN->getTypeSourceInfo()->getType());
5131
5132 Out << "E";
5133 break;
5134 }
5135 }
5136
5137 if (AsTemplateArg && !IsPrimaryExpr)
5138 Out << 'E';
5139}
5140
5141/// Mangle an expression which refers to a parameter variable.
5142///
5143/// <expression> ::= <function-param>
5144/// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0
5145/// <function-param> ::= fp <top-level CV-qualifiers>
5146/// <parameter-2 non-negative number> _ # L == 0, I > 0
5147/// <function-param> ::= fL <L-1 non-negative number>
5148/// p <top-level CV-qualifiers> _ # L > 0, I == 0
5149/// <function-param> ::= fL <L-1 non-negative number>
5150/// p <top-level CV-qualifiers>
5151/// <I-1 non-negative number> _ # L > 0, I > 0
5152///
5153/// L is the nesting depth of the parameter, defined as 1 if the
5154/// parameter comes from the innermost function prototype scope
5155/// enclosing the current context, 2 if from the next enclosing
5156/// function prototype scope, and so on, with one special case: if
5157/// we've processed the full parameter clause for the innermost
5158/// function type, then L is one less. This definition conveniently
5159/// makes it irrelevant whether a function's result type was written
5160/// trailing or leading, but is otherwise overly complicated; the
5161/// numbering was first designed without considering references to
5162/// parameter in locations other than return types, and then the
5163/// mangling had to be generalized without changing the existing
5164/// manglings.
5165///
5166/// I is the zero-based index of the parameter within its parameter
5167/// declaration clause. Note that the original ABI document describes
5168/// this using 1-based ordinals.
5169void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {
5170 unsigned parmDepth = parm->getFunctionScopeDepth();
5171 unsigned parmIndex = parm->getFunctionScopeIndex();
5172
5173 // Compute 'L'.
5174 // parmDepth does not include the declaring function prototype.
5175 // FunctionTypeDepth does account for that.
5176 assert(parmDepth < FunctionTypeDepth.getDepth())(static_cast <bool> (parmDepth < FunctionTypeDepth.getDepth
()) ? void (0) : __assert_fail ("parmDepth < FunctionTypeDepth.getDepth()"
, "clang/lib/AST/ItaniumMangle.cpp", 5176, __extension__ __PRETTY_FUNCTION__
))
;
5177 unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth;
5178 if (FunctionTypeDepth.isInResultType())
5179 nestingDepth--;
5180
5181 if (nestingDepth == 0) {
5182 Out << "fp";
5183 } else {
5184 Out << "fL" << (nestingDepth - 1) << 'p';
5185 }
5186
5187 // Top-level qualifiers. We don't have to worry about arrays here,
5188 // because parameters declared as arrays should already have been
5189 // transformed to have pointer type. FIXME: apparently these don't
5190 // get mangled if used as an rvalue of a known non-class type?
5191 assert(!parm->getType()->isArrayType()(static_cast <bool> (!parm->getType()->isArrayType
() && "parameter's type is still an array type?") ? void
(0) : __assert_fail ("!parm->getType()->isArrayType() && \"parameter's type is still an array type?\""
, "clang/lib/AST/ItaniumMangle.cpp", 5192, __extension__ __PRETTY_FUNCTION__
))
5192 && "parameter's type is still an array type?")(static_cast <bool> (!parm->getType()->isArrayType
() && "parameter's type is still an array type?") ? void
(0) : __assert_fail ("!parm->getType()->isArrayType() && \"parameter's type is still an array type?\""
, "clang/lib/AST/ItaniumMangle.cpp", 5192, __extension__ __PRETTY_FUNCTION__
))
;
5193
5194 if (const DependentAddressSpaceType *DAST =
5195 dyn_cast<DependentAddressSpaceType>(parm->getType())) {
5196 mangleQualifiers(DAST->getPointeeType().getQualifiers(), DAST);
5197 } else {
5198 mangleQualifiers(parm->getType().getQualifiers());
5199 }
5200
5201 // Parameter index.
5202 if (parmIndex != 0) {
5203 Out << (parmIndex - 1);
5204 }
5205 Out << '_';
5206}
5207
5208void CXXNameMangler::mangleCXXCtorType(CXXCtorType T,
5209 const CXXRecordDecl *InheritedFrom) {
5210 // <ctor-dtor-name> ::= C1 # complete object constructor
5211 // ::= C2 # base object constructor
5212 // ::= CI1 <type> # complete inheriting constructor
5213 // ::= CI2 <type> # base inheriting constructor
5214 //
5215 // In addition, C5 is a comdat name with C1 and C2 in it.
5216 Out << 'C';
5217 if (InheritedFrom)
5218 Out << 'I';
5219 switch (T) {
5220 case Ctor_Complete:
5221 Out << '1';
5222 break;
5223 case Ctor_Base:
5224 Out << '2';
5225 break;
5226 case Ctor_Comdat:
5227 Out << '5';
5228 break;
5229 case Ctor_DefaultClosure:
5230 case Ctor_CopyingClosure:
5231 llvm_unreachable("closure constructors don't exist for the Itanium ABI!")::llvm::llvm_unreachable_internal("closure constructors don't exist for the Itanium ABI!"
, "clang/lib/AST/ItaniumMangle.cpp", 5231)
;
5232 }
5233 if (InheritedFrom)
5234 mangleName(InheritedFrom);
5235}
5236
5237void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
5238 // <ctor-dtor-name> ::= D0 # deleting destructor
5239 // ::= D1 # complete object destructor
5240 // ::= D2 # base object destructor
5241 //
5242 // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it.
5243 switch (T) {
5244 case Dtor_Deleting:
5245 Out << "D0";
5246 break;
5247 case Dtor_Complete:
5248 Out << "D1";
5249 break;
5250 case Dtor_Base:
5251 Out << "D2";
5252 break;
5253 case Dtor_Comdat:
5254 Out << "D5";
5255 break;
5256 }
5257}
5258
5259namespace {
5260// Helper to provide ancillary information on a template used to mangle its
5261// arguments.
5262struct TemplateArgManglingInfo {
5263 TemplateDecl *ResolvedTemplate = nullptr;
5264 bool SeenPackExpansionIntoNonPack = false;
5265 const NamedDecl *UnresolvedExpandedPack = nullptr;
5266
5267 TemplateArgManglingInfo(TemplateName TN) {
5268 if (TemplateDecl *TD = TN.getAsTemplateDecl())
5269 ResolvedTemplate = TD;
5270 }
5271
5272 /// Do we need to mangle template arguments with exactly correct types?
5273 ///
5274 /// This should be called exactly once for each parameter / argument pair, in
5275 /// order.
5276 bool needExactType(unsigned ParamIdx, const TemplateArgument &Arg) {
5277 // We need correct types when the template-name is unresolved or when it
5278 // names a template that is able to be overloaded.
5279 if (!ResolvedTemplate || SeenPackExpansionIntoNonPack)
5280 return true;
5281
5282 // Move to the next parameter.
5283 const NamedDecl *Param = UnresolvedExpandedPack;
5284 if (!Param) {
5285 assert(ParamIdx < ResolvedTemplate->getTemplateParameters()->size() &&(static_cast <bool> (ParamIdx < ResolvedTemplate->
getTemplateParameters()->size() && "no parameter for argument"
) ? void (0) : __assert_fail ("ParamIdx < ResolvedTemplate->getTemplateParameters()->size() && \"no parameter for argument\""
, "clang/lib/AST/ItaniumMangle.cpp", 5286, __extension__ __PRETTY_FUNCTION__
))
5286 "no parameter for argument")(static_cast <bool> (ParamIdx < ResolvedTemplate->
getTemplateParameters()->size() && "no parameter for argument"
) ? void (0) : __assert_fail ("ParamIdx < ResolvedTemplate->getTemplateParameters()->size() && \"no parameter for argument\""
, "clang/lib/AST/ItaniumMangle.cpp", 5286, __extension__ __PRETTY_FUNCTION__
))
;
5287 Param = ResolvedTemplate->getTemplateParameters()->getParam(ParamIdx);
5288
5289 // If we reach an expanded parameter pack whose argument isn't in pack
5290 // form, that means Sema couldn't figure out which arguments belonged to
5291 // it, because it contains a pack expansion. Track the expanded pack for
5292 // all further template arguments until we hit that pack expansion.
5293 if (Param->isParameterPack() && Arg.getKind() != TemplateArgument::Pack) {
5294 assert(getExpandedPackSize(Param) &&(static_cast <bool> (getExpandedPackSize(Param) &&
"failed to form pack argument for parameter pack") ? void (0
) : __assert_fail ("getExpandedPackSize(Param) && \"failed to form pack argument for parameter pack\""
, "clang/lib/AST/ItaniumMangle.cpp", 5295, __extension__ __PRETTY_FUNCTION__
))
5295 "failed to form pack argument for parameter pack")(static_cast <bool> (getExpandedPackSize(Param) &&
"failed to form pack argument for parameter pack") ? void (0
) : __assert_fail ("getExpandedPackSize(Param) && \"failed to form pack argument for parameter pack\""
, "clang/lib/AST/ItaniumMangle.cpp", 5295, __extension__ __PRETTY_FUNCTION__
))
;
5296 UnresolvedExpandedPack = Param;
5297 }
5298 }
5299
5300 // If we encounter a pack argument that is expanded into a non-pack
5301 // parameter, we can no longer track parameter / argument correspondence,
5302 // and need to use exact types from this point onwards.
5303 if (Arg.isPackExpansion() &&
5304 (!Param->isParameterPack() || UnresolvedExpandedPack)) {
5305 SeenPackExpansionIntoNonPack = true;
5306 return true;
5307 }
5308
5309 // We need exact types for function template arguments because they might be
5310 // overloaded on template parameter type. As a special case, a member
5311 // function template of a generic lambda is not overloadable.
5312 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ResolvedTemplate)) {
5313 auto *RD = dyn_cast<CXXRecordDecl>(FTD->getDeclContext());
5314 if (!RD || !RD->isGenericLambda())
5315 return true;
5316 }
5317
5318 // Otherwise, we only need a correct type if the parameter has a deduced
5319 // type.
5320 //
5321 // Note: for an expanded parameter pack, getType() returns the type prior
5322 // to expansion. We could ask for the expanded type with getExpansionType(),
5323 // but it doesn't matter because substitution and expansion don't affect
5324 // whether a deduced type appears in the type.
5325 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param);
5326 return NTTP && NTTP->getType()->getContainedDeducedType();
5327 }
5328};
5329}
5330
5331void CXXNameMangler::mangleTemplateArgs(TemplateName TN,
5332 const TemplateArgumentLoc *TemplateArgs,
5333 unsigned NumTemplateArgs) {
5334 // <template-args> ::= I <template-arg>+ E
5335 Out << 'I';
5336 TemplateArgManglingInfo Info(TN);
5337 for (unsigned i = 0; i != NumTemplateArgs; ++i)
5338 mangleTemplateArg(TemplateArgs[i].getArgument(),
5339 Info.needExactType(i, TemplateArgs[i].getArgument()));
5340 Out << 'E';
5341}
5342
5343void CXXNameMangler::mangleTemplateArgs(TemplateName TN,
5344 const TemplateArgumentList &AL) {
5345 // <template-args> ::= I <template-arg>+ E
5346 Out << 'I';
5347 TemplateArgManglingInfo Info(TN);
5348 for (unsigned i = 0, e = AL.size(); i != e; ++i)
5349 mangleTemplateArg(AL[i], Info.needExactType(i, AL[i]));
5350 Out << 'E';
5351}
5352
5353void CXXNameMangler::mangleTemplateArgs(TemplateName TN,
5354 const TemplateArgument *TemplateArgs,
5355 unsigned NumTemplateArgs) {
5356 // <template-args> ::= I <template-arg>+ E
5357 Out << 'I';
5358 TemplateArgManglingInfo Info(TN);
5359 for (unsigned i = 0; i != NumTemplateArgs; ++i)
5360 mangleTemplateArg(TemplateArgs[i], Info.needExactType(i, TemplateArgs[i]));
5361 Out << 'E';
5362}
5363
5364void CXXNameMangler::mangleTemplateArg(TemplateArgument A, bool NeedExactType) {
5365 // <template-arg> ::= <type> # type or template
5366 // ::= X <expression> E # expression
5367 // ::= <expr-primary> # simple expressions
5368 // ::= J <template-arg>* E # argument pack
5369 if (!A.isInstantiationDependent() || A.isDependent())
5370 A = Context.getASTContext().getCanonicalTemplateArgument(A);
5371
5372 switch (A.getKind()) {
5373 case TemplateArgument::Null:
5374 llvm_unreachable("Cannot mangle NULL template argument")::llvm::llvm_unreachable_internal("Cannot mangle NULL template argument"
, "clang/lib/AST/ItaniumMangle.cpp", 5374)
;
5375
5376 case TemplateArgument::Type:
5377 mangleType(A.getAsType());
5378 break;
5379 case TemplateArgument::Template:
5380 // This is mangled as <type>.
5381 mangleType(A.getAsTemplate());
5382 break;
5383 case TemplateArgument::TemplateExpansion:
5384 // <type> ::= Dp <type> # pack expansion (C++0x)
5385 Out << "Dp";
5386 mangleType(A.getAsTemplateOrTemplatePattern());
5387 break;
5388 case TemplateArgument::Expression:
5389 mangleTemplateArgExpr(A.getAsExpr());
5390 break;
5391 case TemplateArgument::Integral:
5392 mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral());
5393 break;
5394 case TemplateArgument::Declaration: {
5395 // <expr-primary> ::= L <mangled-name> E # external name
5396 ValueDecl *D = A.getAsDecl();
5397
5398 // Template parameter objects are modeled by reproducing a source form
5399 // produced as if by aggregate initialization.
5400 if (A.getParamTypeForDecl()->isRecordType()) {
5401 auto *TPO = cast<TemplateParamObjectDecl>(D);
5402 mangleValueInTemplateArg(TPO->getType().getUnqualifiedType(),
5403 TPO->getValue(), /*TopLevel=*/true,
5404 NeedExactType);
5405 break;
5406 }
5407
5408 ASTContext &Ctx = Context.getASTContext();
5409 APValue Value;
5410 if (D->isCXXInstanceMember())
5411 // Simple pointer-to-member with no conversion.
5412 Value = APValue(D, /*IsDerivedMember=*/false, /*Path=*/{});
5413 else if (D->getType()->isArrayType() &&
5414 Ctx.hasSimilarType(Ctx.getDecayedType(D->getType()),
5415 A.getParamTypeForDecl()) &&
5416 Ctx.getLangOpts().getClangABICompat() >
5417 LangOptions::ClangABI::Ver11)
5418 // Build a value corresponding to this implicit array-to-pointer decay.
5419 Value = APValue(APValue::LValueBase(D), CharUnits::Zero(),
5420 {APValue::LValuePathEntry::ArrayIndex(0)},
5421 /*OnePastTheEnd=*/false);
5422 else
5423 // Regular pointer or reference to a declaration.
5424 Value = APValue(APValue::LValueBase(D), CharUnits::Zero(),
5425 ArrayRef<APValue::LValuePathEntry>(),
5426 /*OnePastTheEnd=*/false);
5427 mangleValueInTemplateArg(A.getParamTypeForDecl(), Value, /*TopLevel=*/true,
5428 NeedExactType);
5429 break;
5430 }
5431 case TemplateArgument::NullPtr: {
5432 mangleNullPointer(A.getNullPtrType());
5433 break;
5434 }
5435 case TemplateArgument::Pack: {
5436 // <template-arg> ::= J <template-arg>* E
5437 Out << 'J';
5438 for (const auto &P : A.pack_elements())
5439 mangleTemplateArg(P, NeedExactType);
5440 Out << 'E';
5441 }
5442 }
5443}
5444
5445void CXXNameMangler::mangleTemplateArgExpr(const Expr *E) {
5446 ASTContext &Ctx = Context.getASTContext();
5447 if (Ctx.getLangOpts().getClangABICompat() > LangOptions::ClangABI::Ver11) {
5448 mangleExpression(E, UnknownArity, /*AsTemplateArg=*/true);
5449 return;
5450 }
5451
5452 // Prior to Clang 12, we didn't omit the X .. E around <expr-primary>
5453 // correctly in cases where the template argument was
5454 // constructed from an expression rather than an already-evaluated
5455 // literal. In such a case, we would then e.g. emit 'XLi0EE' instead of
5456 // 'Li0E'.
5457 //
5458 // We did special-case DeclRefExpr to attempt to DTRT for that one
5459 // expression-kind, but while doing so, unfortunately handled ParmVarDecl
5460 // (subtype of VarDecl) _incorrectly_, and emitted 'L_Z .. E' instead of
5461 // the proper 'Xfp_E'.
5462 E = E->IgnoreParenImpCasts();
5463 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
5464 const ValueDecl *D = DRE->getDecl();
5465 if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {
5466 Out << 'L';
5467 mangle(D);
5468 Out << 'E';
5469 return;
5470 }
5471 }
5472 Out << 'X';
5473 mangleExpression(E);
5474 Out << 'E';
5475}
5476
5477/// Determine whether a given value is equivalent to zero-initialization for
5478/// the purpose of discarding a trailing portion of a 'tl' mangling.
5479///
5480/// Note that this is not in general equivalent to determining whether the
5481/// value has an all-zeroes bit pattern.
5482static bool isZeroInitialized(QualType T, const APValue &V) {
5483 // FIXME: mangleValueInTemplateArg has quadratic time complexity in
5484 // pathological cases due to using this, but it's a little awkward
5485 // to do this in linear time in general.
5486 switch (V.getKind()) {
5487 case APValue::None:
5488 case APValue::Indeterminate:
5489 case APValue::AddrLabelDiff:
5490 return false;
5491
5492 case APValue::Struct: {
5493 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
5494 assert(RD && "unexpected type for record value")(static_cast <bool> (RD && "unexpected type for record value"
) ? void (0) : __assert_fail ("RD && \"unexpected type for record value\""
, "clang/lib/AST/ItaniumMangle.cpp", 5494, __extension__ __PRETTY_FUNCTION__
))
;
5495 unsigned I = 0;
5496 for (const CXXBaseSpecifier &BS : RD->bases()) {
5497 if (!isZeroInitialized(BS.getType(), V.getStructBase(I)))
5498 return false;
5499 ++I;
5500 }
5501 I = 0;
5502 for (const FieldDecl *FD : RD->fields()) {
5503 if (!FD->isUnnamedBitfield() &&
5504 !isZeroInitialized(FD->getType(), V.getStructField(I)))
5505 return false;
5506 ++I;
5507 }
5508 return true;
5509 }
5510
5511 case APValue::Union: {
5512 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
5513 assert(RD && "unexpected type for union value")(static_cast <bool> (RD && "unexpected type for union value"
) ? void (0) : __assert_fail ("RD && \"unexpected type for union value\""
, "clang/lib/AST/ItaniumMangle.cpp", 5513, __extension__ __PRETTY_FUNCTION__
))
;
5514 // Zero-initialization zeroes the first non-unnamed-bitfield field, if any.
5515 for (const FieldDecl *FD : RD->fields()) {
5516 if (!FD->isUnnamedBitfield())
5517 return V.getUnionField() && declaresSameEntity(FD, V.getUnionField()) &&
5518 isZeroInitialized(FD->getType(), V.getUnionValue());
5519 }
5520 // If there are no fields (other than unnamed bitfields), the value is
5521 // necessarily zero-initialized.
5522 return true;
5523 }
5524
5525 case APValue::Array: {
5526 QualType ElemT(T->getArrayElementTypeNoTypeQual(), 0);
5527 for (unsigned I = 0, N = V.getArrayInitializedElts(); I != N; ++I)
5528 if (!isZeroInitialized(ElemT, V.getArrayInitializedElt(I)))
5529 return false;
5530 return !V.hasArrayFiller() || isZeroInitialized(ElemT, V.getArrayFiller());
5531 }
5532
5533 case APValue::Vector: {
5534 const VectorType *VT = T->castAs<VectorType>();
5535 for (unsigned I = 0, N = V.getVectorLength(); I != N; ++I)
5536 if (!isZeroInitialized(VT->getElementType(), V.getVectorElt(I)))
5537 return false;
5538 return true;
5539 }
5540
5541 case APValue::Int:
5542 return !V.getInt();
5543
5544 case APValue::Float:
5545 return V.getFloat().isPosZero();
5546
5547 case APValue::FixedPoint:
5548 return !V.getFixedPoint().getValue();
5549
5550 case APValue::ComplexFloat:
5551 return V.getComplexFloatReal().isPosZero() &&
5552 V.getComplexFloatImag().isPosZero();
5553
5554 case APValue::ComplexInt:
5555 return !V.getComplexIntReal() && !V.getComplexIntImag();
5556
5557 case APValue::LValue:
5558 return V.isNullPointer();
5559
5560 case APValue::MemberPointer:
5561 return !V.getMemberPointerDecl();
5562 }
5563
5564 llvm_unreachable("Unhandled APValue::ValueKind enum")::llvm::llvm_unreachable_internal("Unhandled APValue::ValueKind enum"
, "clang/lib/AST/ItaniumMangle.cpp", 5564)
;
5565}
5566
5567static QualType getLValueType(ASTContext &Ctx, const APValue &LV) {
5568 QualType T = LV.getLValueBase().getType();
5569 for (APValue::LValuePathEntry E : LV.getLValuePath()) {
5570 if (const ArrayType *AT = Ctx.getAsArrayType(T))
5571 T = AT->getElementType();
5572 else if (const FieldDecl *FD =
5573 dyn_cast<FieldDecl>(E.getAsBaseOrMember().getPointer()))
5574 T = FD->getType();
5575 else
5576 T = Ctx.getRecordType(
5577 cast<CXXRecordDecl>(E.getAsBaseOrMember().getPointer()));
5578 }
5579 return T;
5580}
5581
5582static IdentifierInfo *getUnionInitName(SourceLocation UnionLoc,
5583 DiagnosticsEngine &Diags,
5584 const FieldDecl *FD) {
5585 // According to:
5586 // http://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling.anonymous
5587 // For the purposes of mangling, the name of an anonymous union is considered
5588 // to be the name of the first named data member found by a pre-order,
5589 // depth-first, declaration-order walk of the data members of the anonymous
5590 // union.
5591
5592 if (FD->getIdentifier())
5593 return FD->getIdentifier();
5594
5595 // The only cases where the identifer of a FieldDecl would be blank is if the
5596 // field represents an anonymous record type or if it is an unnamed bitfield.
5597 // There is no type to descend into in the case of a bitfield, so we can just
5598 // return nullptr in that case.
5599 if (FD->isBitField())
5600 return nullptr;
5601 const CXXRecordDecl *RD = FD->getType()->getAsCXXRecordDecl();
5602
5603 // Consider only the fields in declaration order, searched depth-first. We
5604 // don't care about the active member of the union, as all we are doing is
5605 // looking for a valid name. We also don't check bases, due to guidance from
5606 // the Itanium ABI folks.
5607 for (const FieldDecl *RDField : RD->fields()) {
5608 if (IdentifierInfo *II = getUnionInitName(UnionLoc, Diags, RDField))
5609 return II;
5610 }
5611
5612 // According to the Itanium ABI: If there is no such data member (i.e., if all
5613 // of the data members in the union are unnamed), then there is no way for a
5614 // program to refer to the anonymous union, and there is therefore no need to
5615 // mangle its name. However, we should diagnose this anyway.
5616 unsigned DiagID = Diags.getCustomDiagID(
5617 DiagnosticsEngine::Error, "cannot mangle this unnamed union NTTP yet");
5618 Diags.Report(UnionLoc, DiagID);
5619
5620 return nullptr;
5621}
5622
5623void CXXNameMangler::mangleValueInTemplateArg(QualType T, const APValue &V,
5624 bool TopLevel,
5625 bool NeedExactType) {
5626 // Ignore all top-level cv-qualifiers, to match GCC.
5627 Qualifiers Quals;
5628 T = getASTContext().getUnqualifiedArrayType(T, Quals);
5629
5630 // A top-level expression that's not a primary expression is wrapped in X...E.
5631 bool IsPrimaryExpr = true;
5632 auto NotPrimaryExpr = [&] {
5633 if (TopLevel && IsPrimaryExpr)
5634 Out << 'X';
5635 IsPrimaryExpr = false;
5636 };
5637
5638 // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/63.
5639 switch (V.getKind()) {
5640 case APValue::None:
5641 case APValue::Indeterminate:
5642 Out << 'L';
5643 mangleType(T);
5644 Out << 'E';
5645 break;
5646
5647 case APValue::AddrLabelDiff:
5648 llvm_unreachable("unexpected value kind in template argument")::llvm::llvm_unreachable_internal("unexpected value kind in template argument"
, "clang/lib/AST/ItaniumMangle.cpp", 5648)
;
5649
5650 case APValue::Struct: {
5651 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
5652 assert(RD && "unexpected type for record value")(static_cast <bool> (RD && "unexpected type for record value"
) ? void (0) : __assert_fail ("RD && \"unexpected type for record value\""
, "clang/lib/AST/ItaniumMangle.cpp", 5652, __extension__ __PRETTY_FUNCTION__
))
;
5653
5654 // Drop trailing zero-initialized elements.
5655 llvm::SmallVector<const FieldDecl *, 16> Fields(RD->fields());
5656 while (
5657 !Fields.empty() &&
5658 (Fields.back()->isUnnamedBitfield() ||
5659 isZeroInitialized(Fields.back()->getType(),
5660 V.getStructField(Fields.back()->getFieldIndex())))) {
5661 Fields.pop_back();
5662 }
5663 llvm::ArrayRef<CXXBaseSpecifier> Bases(RD->bases_begin(), RD->bases_end());
5664 if (Fields.empty()) {
5665 while (!Bases.empty() &&
5666 isZeroInitialized(Bases.back().getType(),
5667 V.getStructBase(Bases.size() - 1)))
5668 Bases = Bases.drop_back();
5669 }
5670
5671 // <expression> ::= tl <type> <braced-expression>* E
5672 NotPrimaryExpr();
5673 Out << "tl";
5674 mangleType(T);
5675 for (unsigned I = 0, N = Bases.size(); I != N; ++I)
5676 mangleValueInTemplateArg(Bases[I].getType(), V.getStructBase(I), false);
5677 for (unsigned I = 0, N = Fields.size(); I != N; ++I) {
5678 if (Fields[I]->isUnnamedBitfield())
5679 continue;
5680 mangleValueInTemplateArg(Fields[I]->getType(),
5681 V.getStructField(Fields[I]->getFieldIndex()),
5682 false);
5683 }
5684 Out << 'E';
5685 break;
5686 }
5687
5688 case APValue::Union: {
5689 assert(T->getAsCXXRecordDecl() && "unexpected type for union value")(static_cast <bool> (T->getAsCXXRecordDecl() &&
"unexpected type for union value") ? void (0) : __assert_fail
("T->getAsCXXRecordDecl() && \"unexpected type for union value\""
, "clang/lib/AST/ItaniumMangle.cpp", 5689, __extension__ __PRETTY_FUNCTION__
))
;
5690 const FieldDecl *FD = V.getUnionField();
5691
5692 if (!FD) {
5693 Out << 'L';
5694 mangleType(T);
5695 Out << 'E';
5696 break;
5697 }
5698
5699 // <braced-expression> ::= di <field source-name> <braced-expression>
5700 NotPrimaryExpr();
5701 Out << "tl";
5702 mangleType(T);
5703 if (!isZeroInitialized(T, V)) {
5704 Out << "di";
5705 IdentifierInfo *II = (getUnionInitName(
5706 T->getAsCXXRecordDecl()->getLocation(), Context.getDiags(), FD));
5707 if (II)
5708 mangleSourceName(II);
5709 mangleValueInTemplateArg(FD->getType(), V.getUnionValue(), false);
5710 }
5711 Out << 'E';
5712 break;
5713 }
5714
5715 case APValue::Array: {
5716 QualType ElemT(T->getArrayElementTypeNoTypeQual(), 0);
5717
5718 NotPrimaryExpr();
5719 Out << "tl";
5720 mangleType(T);
5721
5722 // Drop trailing zero-initialized elements.
5723 unsigned N = V.getArraySize();
5724 if (!V.hasArrayFiller() || isZeroInitialized(ElemT, V.getArrayFiller())) {
5725 N = V.getArrayInitializedElts();
5726 while (N && isZeroInitialized(ElemT, V.getArrayInitializedElt(N - 1)))
5727 --N;
5728 }
5729
5730 for (unsigned I = 0; I != N; ++I) {
5731 const APValue &Elem = I < V.getArrayInitializedElts()
5732 ? V.getArrayInitializedElt(I)
5733 : V.getArrayFiller();
5734 mangleValueInTemplateArg(ElemT, Elem, false);
5735 }
5736 Out << 'E';
5737 break;
5738 }
5739
5740 case APValue::Vector: {
5741 const VectorType *VT = T->castAs<VectorType>();
5742
5743 NotPrimaryExpr();
5744 Out << "tl";
5745 mangleType(T);
5746 unsigned N = V.getVectorLength();
5747 while (N && isZeroInitialized(VT->getElementType(), V.getVectorElt(N - 1)))
5748 --N;
5749 for (unsigned I = 0; I != N; ++I)
5750 mangleValueInTemplateArg(VT->getElementType(), V.getVectorElt(I), false);
5751 Out << 'E';
5752 break;
5753 }
5754
5755 case APValue::Int:
5756 mangleIntegerLiteral(T, V.getInt());
5757 break;
5758
5759 case APValue::Float:
5760 mangleFloatLiteral(T, V.getFloat());
5761 break;
5762
5763 case APValue::FixedPoint:
5764 mangleFixedPointLiteral();
5765 break;
5766
5767 case APValue::ComplexFloat: {
5768 const ComplexType *CT = T->castAs<ComplexType>();
5769 NotPrimaryExpr();
5770 Out << "tl";
5771 mangleType(T);
5772 if (!V.getComplexFloatReal().isPosZero() ||
5773 !V.getComplexFloatImag().isPosZero())
5774 mangleFloatLiteral(CT->getElementType(), V.getComplexFloatReal());
5775 if (!V.getComplexFloatImag().isPosZero())
5776 mangleFloatLiteral(CT->getElementType(), V.getComplexFloatImag());
5777 Out << 'E';
5778 break;
5779 }
5780
5781 case APValue::ComplexInt: {
5782 const ComplexType *CT = T->castAs<ComplexType>();
5783 NotPrimaryExpr();
5784 Out << "tl";
5785 mangleType(T);
5786 if (V.getComplexIntReal().getBoolValue() ||
5787 V.getComplexIntImag().getBoolValue())
5788 mangleIntegerLiteral(CT->getElementType(), V.getComplexIntReal());
5789 if (V.getComplexIntImag().getBoolValue())
5790 mangleIntegerLiteral(CT->getElementType(), V.getComplexIntImag());
5791 Out << 'E';
5792 break;
5793 }
5794
5795 case APValue::LValue: {
5796 // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/47.
5797 assert((T->isPointerType() || T->isReferenceType()) &&(static_cast <bool> ((T->isPointerType() || T->isReferenceType
()) && "unexpected type for LValue template arg") ? void
(0) : __assert_fail ("(T->isPointerType() || T->isReferenceType()) && \"unexpected type for LValue template arg\""
, "clang/lib/AST/ItaniumMangle.cpp", 5798, __extension__ __PRETTY_FUNCTION__
))
5798 "unexpected type for LValue template arg")(static_cast <bool> ((T->isPointerType() || T->isReferenceType
()) && "unexpected type for LValue template arg") ? void
(0) : __assert_fail ("(T->isPointerType() || T->isReferenceType()) && \"unexpected type for LValue template arg\""
, "clang/lib/AST/ItaniumMangle.cpp", 5798, __extension__ __PRETTY_FUNCTION__
))
;
5799
5800 if (V.isNullPointer()) {
5801 mangleNullPointer(T);
5802 break;
5803 }
5804
5805 APValue::LValueBase B = V.getLValueBase();
5806 if (!B) {
5807 // Non-standard mangling for integer cast to a pointer; this can only
5808 // occur as an extension.
5809 CharUnits Offset = V.getLValueOffset();
5810 if (Offset.isZero()) {
5811 // This is reinterpret_cast<T*>(0), not a null pointer. Mangle this as
5812 // a cast, because L <type> 0 E means something else.
5813 NotPrimaryExpr();
5814 Out << "rc";
5815 mangleType(T);
5816 Out << "Li0E";
5817 if (TopLevel)
5818 Out << 'E';
5819 } else {
5820 Out << "L";
5821 mangleType(T);
5822 Out << Offset.getQuantity() << 'E';
5823 }
5824 break;
5825 }
5826
5827 ASTContext &Ctx = Context.getASTContext();
5828
5829 enum { Base, Offset, Path } Kind;
5830 if (!V.hasLValuePath()) {
5831 // Mangle as (T*)((char*)&base + N).
5832 if (T->isReferenceType()) {
5833 NotPrimaryExpr();
5834 Out << "decvP";
5835 mangleType(T->getPointeeType());
5836 } else {
5837 NotPrimaryExpr();
5838 Out << "cv";
5839 mangleType(T);
5840 }
5841 Out << "plcvPcad";
5842 Kind = Offset;
5843 } else {
5844 if (!V.getLValuePath().empty() || V.isLValueOnePastTheEnd()) {
5845 NotPrimaryExpr();
5846 // A final conversion to the template parameter's type is usually
5847 // folded into the 'so' mangling, but we can't do that for 'void*'
5848 // parameters without introducing collisions.
5849 if (NeedExactType && T->isVoidPointerType()) {
5850 Out << "cv";
5851 mangleType(T);
5852 }
5853 if (T->isPointerType())
5854 Out << "ad";
5855 Out << "so";
5856 mangleType(T->isVoidPointerType()
5857 ? getLValueType(Ctx, V).getUnqualifiedType()
5858 : T->getPointeeType());
5859 Kind = Path;
5860 } else {
5861 if (NeedExactType &&
5862 !Ctx.hasSameType(T->getPointeeType(), getLValueType(Ctx, V)) &&
5863 Ctx.getLangOpts().getClangABICompat() >
5864 LangOptions::ClangABI::Ver11) {
5865 NotPrimaryExpr();
5866 Out << "cv";
5867 mangleType(T);
5868 }
5869 if (T->isPointerType()) {
5870 NotPrimaryExpr();
5871 Out << "ad";
5872 }
5873 Kind = Base;
5874 }
5875 }
5876
5877 QualType TypeSoFar = B.getType();
5878 if (auto *VD = B.dyn_cast<const ValueDecl*>()) {
5879 Out << 'L';
5880 mangle(VD);
5881 Out << 'E';
5882 } else if (auto *E = B.dyn_cast<const Expr*>()) {
5883 NotPrimaryExpr();
5884 mangleExpression(E);
5885 } else if (auto TI = B.dyn_cast<TypeInfoLValue>()) {
5886 NotPrimaryExpr();
5887 Out << "ti";
5888 mangleType(QualType(TI.getType(), 0));
5889 } else {
5890 // We should never see dynamic allocations here.
5891 llvm_unreachable("unexpected lvalue base kind in template argument")::llvm::llvm_unreachable_internal("unexpected lvalue base kind in template argument"
, "clang/lib/AST/ItaniumMangle.cpp", 5891)
;
5892 }
5893
5894 switch (Kind) {
5895 case Base:
5896 break;
5897
5898 case Offset:
5899 Out << 'L';
5900 mangleType(Ctx.getPo