blob: 99556a6e70dd6f53189f23c0de6dca9fd6beea9a [file] [log] [blame]
Guy Benyei11169dd2012-12-18 14:30:41 +00001//===--- ItaniumMangle.cpp - Itanium C++ Name Mangling ----------*- C++ -*-===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Guy Benyei11169dd2012-12-18 14:30:41 +00006//
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//
Vlad Tsyrklevichb1bb99d2017-09-12 00:21:17 +000013// http://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling
Guy Benyei11169dd2012-12-18 14:30:41 +000014//
15//===----------------------------------------------------------------------===//
16#include "clang/AST/Mangle.h"
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"
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000022#include "clang/AST/DeclOpenMP.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000023#include "clang/AST/DeclTemplate.h"
David Majnemer58e5bee2014-03-24 21:43:36 +000024#include "clang/AST/Expr.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000025#include "clang/AST/ExprCXX.h"
26#include "clang/AST/ExprObjC.h"
27#include "clang/AST/TypeLoc.h"
28#include "clang/Basic/ABI.h"
29#include "clang/Basic/SourceManager.h"
30#include "clang/Basic/TargetInfo.h"
31#include "llvm/ADT/StringExtras.h"
32#include "llvm/Support/ErrorHandling.h"
33#include "llvm/Support/raw_ostream.h"
34
Guy Benyei11169dd2012-12-18 14:30:41 +000035using namespace clang;
36
37namespace {
38
Justin Bognere8d762e2015-05-22 06:48:13 +000039/// Retrieve the declaration context that should be used when mangling the given
40/// declaration.
Guy Benyei11169dd2012-12-18 14:30:41 +000041static const DeclContext *getEffectiveDeclContext(const Decl *D) {
Fangrui Song6907ce22018-07-30 19:24:48 +000042 // The ABI assumes that lambda closure types that occur within
Guy Benyei11169dd2012-12-18 14:30:41 +000043 // default arguments live in the context of the function. However, due to
44 // the way in which Clang parses and creates function declarations, this is
Fangrui Song6907ce22018-07-30 19:24:48 +000045 // not the case: the lambda closure type ends up living in the context
Guy Benyei11169dd2012-12-18 14:30:41 +000046 // where the function itself resides, because the function declaration itself
47 // had not yet been created. Fix the context here.
48 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
49 if (RD->isLambda())
50 if (ParmVarDecl *ContextParam
51 = dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
52 return ContextParam->getDeclContext();
53 }
Eli Friedman0cd23352013-07-10 01:33:19 +000054
55 // Perform the same check for block literals.
56 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
57 if (ParmVarDecl *ContextParam
58 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))
59 return ContextParam->getDeclContext();
60 }
Fangrui Song6907ce22018-07-30 19:24:48 +000061
Eli Friedman95f50122013-07-02 17:52:28 +000062 const DeclContext *DC = D->getDeclContext();
Michael Kruse251e1482019-02-01 20:25:04 +000063 if (isa<CapturedDecl>(DC) || isa<OMPDeclareReductionDecl>(DC) ||
64 isa<OMPDeclareMapperDecl>(DC)) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000065 return getEffectiveDeclContext(cast<Decl>(DC));
66 }
Eli Friedman95f50122013-07-02 17:52:28 +000067
David Majnemerf8c02e62015-02-18 19:08:11 +000068 if (const auto *VD = dyn_cast<VarDecl>(D))
69 if (VD->isExternC())
70 return VD->getASTContext().getTranslationUnitDecl();
71
72 if (const auto *FD = dyn_cast<FunctionDecl>(D))
73 if (FD->isExternC())
74 return FD->getASTContext().getTranslationUnitDecl();
75
Richard Smithec24bbe2016-04-29 01:23:20 +000076 return DC->getRedeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +000077}
78
79static const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
80 return getEffectiveDeclContext(cast<Decl>(DC));
81}
Eli Friedman95f50122013-07-02 17:52:28 +000082
83static bool isLocalContainerContext(const DeclContext *DC) {
84 return isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC) || isa<BlockDecl>(DC);
85}
86
Eli Friedmaneecc09a2013-07-05 20:27:40 +000087static const RecordDecl *GetLocalClassDecl(const Decl *D) {
Eli Friedman92821742013-07-02 02:01:18 +000088 const DeclContext *DC = getEffectiveDeclContext(D);
Guy Benyei11169dd2012-12-18 14:30:41 +000089 while (!DC->isNamespace() && !DC->isTranslationUnit()) {
Eli Friedman95f50122013-07-02 17:52:28 +000090 if (isLocalContainerContext(DC))
Eli Friedmaneecc09a2013-07-05 20:27:40 +000091 return dyn_cast<RecordDecl>(D);
Eli Friedman92821742013-07-02 02:01:18 +000092 D = cast<Decl>(DC);
93 DC = getEffectiveDeclContext(D);
Guy Benyei11169dd2012-12-18 14:30:41 +000094 }
Craig Topper36250ad2014-05-12 05:36:57 +000095 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +000096}
97
98static const FunctionDecl *getStructor(const FunctionDecl *fn) {
99 if (const FunctionTemplateDecl *ftd = fn->getPrimaryTemplate())
100 return ftd->getTemplatedDecl();
101
102 return fn;
103}
104
105static const NamedDecl *getStructor(const NamedDecl *decl) {
106 const FunctionDecl *fn = dyn_cast_or_null<FunctionDecl>(decl);
107 return (fn ? getStructor(fn) : decl);
108}
David Majnemer2206bf52014-03-05 08:57:59 +0000109
110static bool isLambda(const NamedDecl *ND) {
111 const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(ND);
112 if (!Record)
113 return false;
114
115 return Record->isLambda();
116}
117
Guy Benyei11169dd2012-12-18 14:30:41 +0000118static const unsigned UnknownArity = ~0U;
119
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000120class ItaniumMangleContextImpl : public ItaniumMangleContext {
Eli Friedman3b7d46c2013-07-10 00:30:46 +0000121 typedef std::pair<const DeclContext*, IdentifierInfo*> DiscriminatorKeyTy;
122 llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;
Guy Benyei11169dd2012-12-18 14:30:41 +0000123 llvm::DenseMap<const NamedDecl*, unsigned> Uniquifier;
Evgeny Astigeevich665027d2014-12-12 16:17:46 +0000124
Guy Benyei11169dd2012-12-18 14:30:41 +0000125public:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000126 explicit ItaniumMangleContextImpl(ASTContext &Context,
127 DiagnosticsEngine &Diags)
128 : ItaniumMangleContext(Context, Diags) {}
Guy Benyei11169dd2012-12-18 14:30:41 +0000129
Guy Benyei11169dd2012-12-18 14:30:41 +0000130 /// @name Mangler Entry Points
131 /// @{
132
Craig Toppercbce6e92014-03-11 06:22:39 +0000133 bool shouldMangleCXXName(const NamedDecl *D) override;
David Majnemer58e5bee2014-03-24 21:43:36 +0000134 bool shouldMangleStringLiteral(const StringLiteral *) override {
135 return false;
136 }
Craig Toppercbce6e92014-03-11 06:22:39 +0000137 void mangleCXXName(const NamedDecl *D, raw_ostream &) override;
138 void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk,
139 raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000140 void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
141 const ThisAdjustment &ThisAdjustment,
Craig Toppercbce6e92014-03-11 06:22:39 +0000142 raw_ostream &) override;
David Majnemerdaff3702014-05-01 17:50:17 +0000143 void mangleReferenceTemporary(const VarDecl *D, unsigned ManglingNumber,
144 raw_ostream &) override;
Craig Toppercbce6e92014-03-11 06:22:39 +0000145 void mangleCXXVTable(const CXXRecordDecl *RD, raw_ostream &) override;
146 void mangleCXXVTT(const CXXRecordDecl *RD, raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000147 void mangleCXXCtorVTable(const CXXRecordDecl *RD, int64_t Offset,
Craig Toppercbce6e92014-03-11 06:22:39 +0000148 const CXXRecordDecl *Type, raw_ostream &) override;
149 void mangleCXXRTTI(QualType T, raw_ostream &) override;
150 void mangleCXXRTTIName(QualType T, raw_ostream &) override;
151 void mangleTypeName(QualType T, raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000152 void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type,
Craig Toppercbce6e92014-03-11 06:22:39 +0000153 raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000154 void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type,
Craig Toppercbce6e92014-03-11 06:22:39 +0000155 raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000156
Rafael Espindola1e4df922014-09-16 15:18:21 +0000157 void mangleCXXCtorComdat(const CXXConstructorDecl *D, raw_ostream &) override;
158 void mangleCXXDtorComdat(const CXXDestructorDecl *D, raw_ostream &) override;
Craig Toppercbce6e92014-03-11 06:22:39 +0000159 void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &) override;
160 void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
161 void mangleDynamicAtExitDestructor(const VarDecl *D,
162 raw_ostream &Out) override;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000163 void mangleSEHFilterExpression(const NamedDecl *EnclosingDecl,
164 raw_ostream &Out) override;
Reid Klecknerebaf28d2015-04-14 20:59:00 +0000165 void mangleSEHFinallyBlock(const NamedDecl *EnclosingDecl,
166 raw_ostream &Out) override;
Craig Toppercbce6e92014-03-11 06:22:39 +0000167 void mangleItaniumThreadLocalInit(const VarDecl *D, raw_ostream &) override;
168 void mangleItaniumThreadLocalWrapper(const VarDecl *D,
169 raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000170
David Majnemer58e5bee2014-03-24 21:43:36 +0000171 void mangleStringLiteral(const StringLiteral *, raw_ostream &) override;
172
Guy Benyei11169dd2012-12-18 14:30:41 +0000173 bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
Eli Friedman3b7d46c2013-07-10 00:30:46 +0000174 // Lambda closure types are already numbered.
David Majnemer2206bf52014-03-05 08:57:59 +0000175 if (isLambda(ND))
176 return false;
Eli Friedman3b7d46c2013-07-10 00:30:46 +0000177
178 // Anonymous tags are already numbered.
179 if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
180 if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl())
181 return false;
182 }
183
184 // Use the canonical number for externally visible decls.
185 if (ND->isExternallyVisible()) {
186 unsigned discriminator = getASTContext().getManglingNumber(ND);
187 if (discriminator == 1)
188 return false;
189 disc = discriminator - 2;
190 return true;
191 }
192
193 // Make up a reasonable number for internal decls.
Guy Benyei11169dd2012-12-18 14:30:41 +0000194 unsigned &discriminator = Uniquifier[ND];
Eli Friedman3b7d46c2013-07-10 00:30:46 +0000195 if (!discriminator) {
196 const DeclContext *DC = getEffectiveDeclContext(ND);
197 discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
198 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000199 if (discriminator == 1)
200 return false;
201 disc = discriminator-2;
202 return true;
203 }
204 /// @}
205};
206
Justin Bognere8d762e2015-05-22 06:48:13 +0000207/// Manage the mangling of a single name.
Guy Benyei11169dd2012-12-18 14:30:41 +0000208class CXXNameMangler {
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000209 ItaniumMangleContextImpl &Context;
Guy Benyei11169dd2012-12-18 14:30:41 +0000210 raw_ostream &Out;
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000211 bool NullOut = false;
212 /// In the "DisableDerivedAbiTags" mode derived ABI tags are not calculated.
213 /// This mode is used when mangler creates another mangler recursively to
214 /// calculate ABI tags for the function return value or the variable type.
215 /// Also it is required to avoid infinite recursion in some cases.
216 bool DisableDerivedAbiTags = false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000217
218 /// The "structor" is the top-level declaration being mangled, if
219 /// that's not a template specialization; otherwise it's the pattern
220 /// for that specialization.
221 const NamedDecl *Structor;
222 unsigned StructorType;
223
Justin Bognere8d762e2015-05-22 06:48:13 +0000224 /// The next substitution sequence number.
Guy Benyei11169dd2012-12-18 14:30:41 +0000225 unsigned SeqID;
226
227 class FunctionTypeDepthState {
228 unsigned Bits;
229
230 enum { InResultTypeMask = 1 };
231
232 public:
233 FunctionTypeDepthState() : Bits(0) {}
234
235 /// The number of function types we're inside.
236 unsigned getDepth() const {
237 return Bits >> 1;
238 }
239
240 /// True if we're in the return type of the innermost function type.
241 bool isInResultType() const {
242 return Bits & InResultTypeMask;
243 }
244
245 FunctionTypeDepthState push() {
246 FunctionTypeDepthState tmp = *this;
247 Bits = (Bits & ~InResultTypeMask) + 2;
248 return tmp;
249 }
250
251 void enterResultType() {
252 Bits |= InResultTypeMask;
253 }
254
255 void leaveResultType() {
256 Bits &= ~InResultTypeMask;
257 }
258
259 void pop(FunctionTypeDepthState saved) {
260 assert(getDepth() == saved.getDepth() + 1);
261 Bits = saved.Bits;
262 }
263
264 } FunctionTypeDepth;
265
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000266 // abi_tag is a gcc attribute, taking one or more strings called "tags".
267 // The goal is to annotate against which version of a library an object was
268 // built and to be able to provide backwards compatibility ("dual abi").
269 // For more information see docs/ItaniumMangleAbiTags.rst.
270 typedef SmallVector<StringRef, 4> AbiTagList;
271
272 // State to gather all implicit and explicit tags used in a mangled name.
273 // Must always have an instance of this while emitting any name to keep
274 // track.
275 class AbiTagState final {
276 public:
277 explicit AbiTagState(AbiTagState *&Head) : LinkHead(Head) {
278 Parent = LinkHead;
279 LinkHead = this;
280 }
281
282 // No copy, no move.
283 AbiTagState(const AbiTagState &) = delete;
284 AbiTagState &operator=(const AbiTagState &) = delete;
285
286 ~AbiTagState() { pop(); }
287
288 void write(raw_ostream &Out, const NamedDecl *ND,
289 const AbiTagList *AdditionalAbiTags) {
290 ND = cast<NamedDecl>(ND->getCanonicalDecl());
291 if (!isa<FunctionDecl>(ND) && !isa<VarDecl>(ND)) {
292 assert(
293 !AdditionalAbiTags &&
294 "only function and variables need a list of additional abi tags");
295 if (const auto *NS = dyn_cast<NamespaceDecl>(ND)) {
296 if (const auto *AbiTag = NS->getAttr<AbiTagAttr>()) {
297 UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(),
298 AbiTag->tags().end());
299 }
300 // Don't emit abi tags for namespaces.
301 return;
302 }
303 }
304
305 AbiTagList TagList;
306 if (const auto *AbiTag = ND->getAttr<AbiTagAttr>()) {
307 UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(),
308 AbiTag->tags().end());
309 TagList.insert(TagList.end(), AbiTag->tags().begin(),
310 AbiTag->tags().end());
311 }
312
313 if (AdditionalAbiTags) {
314 UsedAbiTags.insert(UsedAbiTags.end(), AdditionalAbiTags->begin(),
315 AdditionalAbiTags->end());
316 TagList.insert(TagList.end(), AdditionalAbiTags->begin(),
317 AdditionalAbiTags->end());
318 }
319
Fangrui Song55fab262018-09-26 22:16:28 +0000320 llvm::sort(TagList);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000321 TagList.erase(std::unique(TagList.begin(), TagList.end()), TagList.end());
322
323 writeSortedUniqueAbiTags(Out, TagList);
324 }
325
326 const AbiTagList &getUsedAbiTags() const { return UsedAbiTags; }
327 void setUsedAbiTags(const AbiTagList &AbiTags) {
328 UsedAbiTags = AbiTags;
329 }
330
331 const AbiTagList &getEmittedAbiTags() const {
332 return EmittedAbiTags;
333 }
334
335 const AbiTagList &getSortedUniqueUsedAbiTags() {
Fangrui Song55fab262018-09-26 22:16:28 +0000336 llvm::sort(UsedAbiTags);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000337 UsedAbiTags.erase(std::unique(UsedAbiTags.begin(), UsedAbiTags.end()),
338 UsedAbiTags.end());
339 return UsedAbiTags;
340 }
341
342 private:
343 //! All abi tags used implicitly or explicitly.
344 AbiTagList UsedAbiTags;
345 //! All explicit abi tags (i.e. not from namespace).
346 AbiTagList EmittedAbiTags;
347
348 AbiTagState *&LinkHead;
349 AbiTagState *Parent = nullptr;
350
351 void pop() {
352 assert(LinkHead == this &&
353 "abi tag link head must point to us on destruction");
354 if (Parent) {
355 Parent->UsedAbiTags.insert(Parent->UsedAbiTags.end(),
356 UsedAbiTags.begin(), UsedAbiTags.end());
357 Parent->EmittedAbiTags.insert(Parent->EmittedAbiTags.end(),
358 EmittedAbiTags.begin(),
359 EmittedAbiTags.end());
360 }
361 LinkHead = Parent;
362 }
363
364 void writeSortedUniqueAbiTags(raw_ostream &Out, const AbiTagList &AbiTags) {
365 for (const auto &Tag : AbiTags) {
366 EmittedAbiTags.push_back(Tag);
367 Out << "B";
368 Out << Tag.size();
369 Out << Tag;
370 }
371 }
372 };
373
374 AbiTagState *AbiTags = nullptr;
375 AbiTagState AbiTagsRoot;
376
Guy Benyei11169dd2012-12-18 14:30:41 +0000377 llvm::DenseMap<uintptr_t, unsigned> Substitutions;
Richard Smithdd8b5332017-09-04 05:37:53 +0000378 llvm::DenseMap<StringRef, unsigned> ModuleSubstitutions;
Guy Benyei11169dd2012-12-18 14:30:41 +0000379
380 ASTContext &getASTContext() const { return Context.getASTContext(); }
381
382public:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000383 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000384 const NamedDecl *D = nullptr, bool NullOut_ = false)
385 : Context(C), Out(Out_), NullOut(NullOut_), Structor(getStructor(D)),
386 StructorType(0), SeqID(0), AbiTagsRoot(AbiTags) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000387 // These can't be mangled without a ctor type or dtor type.
388 assert(!D || (!isa<CXXDestructorDecl>(D) &&
389 !isa<CXXConstructorDecl>(D)));
390 }
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000391 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
Guy Benyei11169dd2012-12-18 14:30:41 +0000392 const CXXConstructorDecl *D, CXXCtorType Type)
393 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000394 SeqID(0), AbiTagsRoot(AbiTags) { }
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000395 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
Guy Benyei11169dd2012-12-18 14:30:41 +0000396 const CXXDestructorDecl *D, CXXDtorType Type)
397 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000398 SeqID(0), AbiTagsRoot(AbiTags) { }
399
400 CXXNameMangler(CXXNameMangler &Outer, raw_ostream &Out_)
401 : Context(Outer.Context), Out(Out_), NullOut(false),
402 Structor(Outer.Structor), StructorType(Outer.StructorType),
Alex Lorenz7ba609a2016-10-06 09:37:15 +0000403 SeqID(Outer.SeqID), FunctionTypeDepth(Outer.FunctionTypeDepth),
404 AbiTagsRoot(AbiTags), Substitutions(Outer.Substitutions) {}
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000405
406 CXXNameMangler(CXXNameMangler &Outer, llvm::raw_null_ostream &Out_)
407 : Context(Outer.Context), Out(Out_), NullOut(true),
408 Structor(Outer.Structor), StructorType(Outer.StructorType),
Alex Lorenz7ba609a2016-10-06 09:37:15 +0000409 SeqID(Outer.SeqID), FunctionTypeDepth(Outer.FunctionTypeDepth),
410 AbiTagsRoot(AbiTags), Substitutions(Outer.Substitutions) {}
Guy Benyei11169dd2012-12-18 14:30:41 +0000411
Guy Benyei11169dd2012-12-18 14:30:41 +0000412 raw_ostream &getStream() { return Out; }
413
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000414 void disableDerivedAbiTags() { DisableDerivedAbiTags = true; }
415 static bool shouldHaveAbiTags(ItaniumMangleContextImpl &C, const VarDecl *VD);
416
David Majnemer7ff7eb72015-02-18 07:47:09 +0000417 void mangle(const NamedDecl *D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000418 void mangleCallOffset(int64_t NonVirtual, int64_t Virtual);
419 void mangleNumber(const llvm::APSInt &I);
420 void mangleNumber(int64_t Number);
421 void mangleFloat(const llvm::APFloat &F);
422 void mangleFunctionEncoding(const FunctionDecl *FD);
David Majnemer3b3bdb52014-05-06 22:49:16 +0000423 void mangleSeqID(unsigned SeqID);
Guy Benyei11169dd2012-12-18 14:30:41 +0000424 void mangleName(const NamedDecl *ND);
425 void mangleType(QualType T);
426 void mangleNameOrStandardSubstitution(const NamedDecl *ND);
Fangrui Song6907ce22018-07-30 19:24:48 +0000427
Guy Benyei11169dd2012-12-18 14:30:41 +0000428private:
David Majnemer3b3bdb52014-05-06 22:49:16 +0000429
Guy Benyei11169dd2012-12-18 14:30:41 +0000430 bool mangleSubstitution(const NamedDecl *ND);
431 bool mangleSubstitution(QualType T);
432 bool mangleSubstitution(TemplateName Template);
433 bool mangleSubstitution(uintptr_t Ptr);
434
Guy Benyei11169dd2012-12-18 14:30:41 +0000435 void mangleExistingSubstitution(TemplateName name);
436
437 bool mangleStandardSubstitution(const NamedDecl *ND);
438
439 void addSubstitution(const NamedDecl *ND) {
440 ND = cast<NamedDecl>(ND->getCanonicalDecl());
441
442 addSubstitution(reinterpret_cast<uintptr_t>(ND));
443 }
444 void addSubstitution(QualType T);
445 void addSubstitution(TemplateName Template);
446 void addSubstitution(uintptr_t Ptr);
Dmitry Polukhinfda467b2016-09-21 08:27:03 +0000447 // Destructive copy substitutions from other mangler.
448 void extendSubstitutions(CXXNameMangler* Other);
Guy Benyei11169dd2012-12-18 14:30:41 +0000449
450 void mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
Guy Benyei11169dd2012-12-18 14:30:41 +0000451 bool recursive = false);
452 void mangleUnresolvedName(NestedNameSpecifier *qualifier,
Guy Benyei11169dd2012-12-18 14:30:41 +0000453 DeclarationName name,
Richard Smithafecd832016-10-24 20:47:04 +0000454 const TemplateArgumentLoc *TemplateArgs,
455 unsigned NumTemplateArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +0000456 unsigned KnownArity = UnknownArity);
457
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000458 void mangleFunctionEncodingBareType(const FunctionDecl *FD);
459
460 void mangleNameWithAbiTags(const NamedDecl *ND,
461 const AbiTagList *AdditionalAbiTags);
Richard Smithdd8b5332017-09-04 05:37:53 +0000462 void mangleModuleName(const Module *M);
463 void mangleModuleNamePrefix(StringRef Name);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000464 void mangleTemplateName(const TemplateDecl *TD,
465 const TemplateArgument *TemplateArgs,
466 unsigned NumTemplateArgs);
467 void mangleUnqualifiedName(const NamedDecl *ND,
468 const AbiTagList *AdditionalAbiTags) {
469 mangleUnqualifiedName(ND, ND->getDeclName(), UnknownArity,
470 AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +0000471 }
472 void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name,
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000473 unsigned KnownArity,
474 const AbiTagList *AdditionalAbiTags);
475 void mangleUnscopedName(const NamedDecl *ND,
476 const AbiTagList *AdditionalAbiTags);
477 void mangleUnscopedTemplateName(const TemplateDecl *ND,
478 const AbiTagList *AdditionalAbiTags);
479 void mangleUnscopedTemplateName(TemplateName,
480 const AbiTagList *AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +0000481 void mangleSourceName(const IdentifierInfo *II);
Erich Keane757d3172016-11-02 18:29:35 +0000482 void mangleRegCallName(const IdentifierInfo *II);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000483 void mangleSourceNameWithAbiTags(
484 const NamedDecl *ND, const AbiTagList *AdditionalAbiTags = nullptr);
485 void mangleLocalName(const Decl *D,
486 const AbiTagList *AdditionalAbiTags);
Eli Friedman95f50122013-07-02 17:52:28 +0000487 void mangleBlockForPrefix(const BlockDecl *Block);
488 void mangleUnqualifiedBlock(const BlockDecl *Block);
Hamza Sood8205a812019-05-04 10:49:46 +0000489 void mangleTemplateParamDecl(const NamedDecl *Decl);
Guy Benyei11169dd2012-12-18 14:30:41 +0000490 void mangleLambda(const CXXRecordDecl *Lambda);
491 void mangleNestedName(const NamedDecl *ND, const DeclContext *DC,
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000492 const AbiTagList *AdditionalAbiTags,
Guy Benyei11169dd2012-12-18 14:30:41 +0000493 bool NoFunction=false);
494 void mangleNestedName(const TemplateDecl *TD,
495 const TemplateArgument *TemplateArgs,
496 unsigned NumTemplateArgs);
497 void manglePrefix(NestedNameSpecifier *qualifier);
498 void manglePrefix(const DeclContext *DC, bool NoFunction=false);
499 void manglePrefix(QualType type);
Eli Friedman86af13f02013-07-05 18:41:30 +0000500 void mangleTemplatePrefix(const TemplateDecl *ND, bool NoFunction=false);
Guy Benyei11169dd2012-12-18 14:30:41 +0000501 void mangleTemplatePrefix(TemplateName Template);
David Majnemerb8014dd2015-02-19 02:16:16 +0000502 bool mangleUnresolvedTypeOrSimpleId(QualType DestroyedType,
503 StringRef Prefix = "");
David Majnemera88b3592015-02-18 02:28:01 +0000504 void mangleOperatorName(DeclarationName Name, unsigned Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +0000505 void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity);
John McCall07daf722016-03-01 22:18:03 +0000506 void mangleVendorQualifier(StringRef qualifier);
Andrew Gozillon572bbb02017-10-02 06:25:51 +0000507 void mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST = nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +0000508 void mangleRefQualifier(RefQualifierKind RefQualifier);
509
510 void mangleObjCMethodName(const ObjCMethodDecl *MD);
511
512 // Declare manglers for every type class.
513#define ABSTRACT_TYPE(CLASS, PARENT)
514#define NON_CANONICAL_TYPE(CLASS, PARENT)
515#define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T);
516#include "clang/AST/TypeNodes.def"
517
518 void mangleType(const TagType*);
519 void mangleType(TemplateName);
John McCall07daf722016-03-01 22:18:03 +0000520 static StringRef getCallingConvQualifierName(CallingConv CC);
521 void mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo info);
522 void mangleExtFunctionInfo(const FunctionType *T);
523 void mangleBareFunctionType(const FunctionProtoType *T, bool MangleReturnType,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000524 const FunctionDecl *FD = nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +0000525 void mangleNeonVectorType(const VectorType *T);
Erich Keanef702b022018-07-13 19:46:04 +0000526 void mangleNeonVectorType(const DependentVectorType *T);
Tim Northover2fe823a2013-08-01 09:23:19 +0000527 void mangleAArch64NeonVectorType(const VectorType *T);
Erich Keanef702b022018-07-13 19:46:04 +0000528 void mangleAArch64NeonVectorType(const DependentVectorType *T);
Guy Benyei11169dd2012-12-18 14:30:41 +0000529
530 void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value);
David Majnemer1dabfdc2015-02-14 13:23:54 +0000531 void mangleMemberExprBase(const Expr *base, bool isArrow);
Guy Benyei11169dd2012-12-18 14:30:41 +0000532 void mangleMemberExpr(const Expr *base, bool isArrow,
533 NestedNameSpecifier *qualifier,
534 NamedDecl *firstQualifierLookup,
535 DeclarationName name,
Richard Smithafecd832016-10-24 20:47:04 +0000536 const TemplateArgumentLoc *TemplateArgs,
537 unsigned NumTemplateArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +0000538 unsigned knownArity);
David Majnemer9c775c72014-09-23 04:27:55 +0000539 void mangleCastExpression(const Expr *E, StringRef CastEncoding);
Richard Smith520449d2015-02-05 06:15:50 +0000540 void mangleInitListElements(const InitListExpr *InitList);
Richard Smithb2997f52019-05-21 20:10:50 +0000541 void mangleDeclRefExpr(const NamedDecl *D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000542 void mangleExpression(const Expr *E, unsigned Arity = UnknownArity);
Richard Smith5179eb72016-06-28 19:03:57 +0000543 void mangleCXXCtorType(CXXCtorType T, const CXXRecordDecl *InheritedFrom);
Guy Benyei11169dd2012-12-18 14:30:41 +0000544 void mangleCXXDtorType(CXXDtorType T);
545
James Y Knight04ec5bf2015-12-24 02:59:37 +0000546 void mangleTemplateArgs(const TemplateArgumentLoc *TemplateArgs,
547 unsigned NumTemplateArgs);
Guy Benyei11169dd2012-12-18 14:30:41 +0000548 void mangleTemplateArgs(const TemplateArgument *TemplateArgs,
549 unsigned NumTemplateArgs);
550 void mangleTemplateArgs(const TemplateArgumentList &AL);
551 void mangleTemplateArg(TemplateArgument A);
552
553 void mangleTemplateParameter(unsigned Index);
554
555 void mangleFunctionParam(const ParmVarDecl *parm);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000556
557 void writeAbiTags(const NamedDecl *ND,
558 const AbiTagList *AdditionalAbiTags);
559
560 // Returns sorted unique list of ABI tags.
561 AbiTagList makeFunctionReturnTypeTags(const FunctionDecl *FD);
562 // Returns sorted unique list of ABI tags.
563 AbiTagList makeVariableTypeTags(const VarDecl *VD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000564};
565
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000566}
Guy Benyei11169dd2012-12-18 14:30:41 +0000567
Rafael Espindola002667c2013-10-16 01:40:34 +0000568bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000569 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000570 if (FD) {
571 LanguageLinkage L = FD->getLanguageLinkage();
572 // Overloadable functions need mangling.
573 if (FD->hasAttr<OverloadableAttr>())
574 return true;
575
Rafael Espindola3e0e33d2013-02-14 15:38:59 +0000576 // "main" is not mangled.
577 if (FD->isMain())
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000578 return false;
579
Martin Storsjo92e26612018-07-16 05:42:25 +0000580 // The Windows ABI expects that we would never mangle "typical"
581 // user-defined entry points regardless of visibility or freestanding-ness.
582 //
583 // N.B. This is distinct from asking about "main". "main" has a lot of
584 // special rules associated with it in the standard while these
585 // user-defined entry points are outside of the purview of the standard.
586 // For example, there can be only one definition for "main" in a standards
587 // compliant program; however nothing forbids the existence of wmain and
588 // WinMain in the same translation unit.
589 if (FD->isMSVCRTEntryPoint())
590 return false;
591
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000592 // C++ functions and those whose names are not a simple identifier need
593 // mangling.
594 if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
595 return true;
Rafael Espindola46d2b6b2013-02-14 03:31:26 +0000596
Rafael Espindola3e0e33d2013-02-14 15:38:59 +0000597 // C functions are not mangled.
598 if (L == CLanguageLinkage)
599 return false;
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000600 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000601
602 // Otherwise, no mangling is done outside C++ mode.
603 if (!getASTContext().getLangOpts().CPlusPlus)
604 return false;
605
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000606 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smithbdb84f32016-07-22 23:36:59 +0000607 if (VD && !isa<DecompositionDecl>(D)) {
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000608 // C variables are not mangled.
609 if (VD->isExternC())
610 return false;
611
612 // Variables at global scope with non-internal linkage are not mangled
Guy Benyei11169dd2012-12-18 14:30:41 +0000613 const DeclContext *DC = getEffectiveDeclContext(D);
614 // Check for extern variable declared locally.
615 if (DC->isFunctionOrMethod() && D->hasLinkage())
616 while (!DC->isNamespace() && !DC->isTranslationUnit())
617 DC = getEffectiveParentContext(DC);
Larisse Voufo39a1e502013-08-06 01:03:05 +0000618 if (DC->isTranslationUnit() && D->getFormalLinkage() != InternalLinkage &&
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000619 !CXXNameMangler::shouldHaveAbiTags(*this, VD) &&
Larisse Voufo39a1e502013-08-06 01:03:05 +0000620 !isa<VarTemplateSpecializationDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +0000621 return false;
622 }
623
Guy Benyei11169dd2012-12-18 14:30:41 +0000624 return true;
625}
626
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000627void CXXNameMangler::writeAbiTags(const NamedDecl *ND,
628 const AbiTagList *AdditionalAbiTags) {
629 assert(AbiTags && "require AbiTagState");
630 AbiTags->write(Out, ND, DisableDerivedAbiTags ? nullptr : AdditionalAbiTags);
631}
632
633void CXXNameMangler::mangleSourceNameWithAbiTags(
634 const NamedDecl *ND, const AbiTagList *AdditionalAbiTags) {
635 mangleSourceName(ND->getIdentifier());
636 writeAbiTags(ND, AdditionalAbiTags);
637}
638
David Majnemer7ff7eb72015-02-18 07:47:09 +0000639void CXXNameMangler::mangle(const NamedDecl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000640 // <mangled-name> ::= _Z <encoding>
641 // ::= <data name>
642 // ::= <special-name>
David Majnemer7ff7eb72015-02-18 07:47:09 +0000643 Out << "_Z";
Guy Benyei11169dd2012-12-18 14:30:41 +0000644 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
645 mangleFunctionEncoding(FD);
646 else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
647 mangleName(VD);
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000648 else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
649 mangleName(IFD->getAnonField());
Guy Benyei11169dd2012-12-18 14:30:41 +0000650 else
651 mangleName(cast<FieldDecl>(D));
652}
653
654void CXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) {
655 // <encoding> ::= <function name> <bare-function-type>
Guy Benyei11169dd2012-12-18 14:30:41 +0000656
657 // Don't mangle in the type if this isn't a decl we should typically mangle.
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000658 if (!Context.shouldMangleDeclName(FD)) {
659 mangleName(FD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000660 return;
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000661 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000662
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000663 AbiTagList ReturnTypeAbiTags = makeFunctionReturnTypeTags(FD);
664 if (ReturnTypeAbiTags.empty()) {
665 // There are no tags for return type, the simplest case.
666 mangleName(FD);
667 mangleFunctionEncodingBareType(FD);
668 return;
669 }
670
671 // Mangle function name and encoding to temporary buffer.
672 // We have to output name and encoding to the same mangler to get the same
673 // substitution as it will be in final mangling.
674 SmallString<256> FunctionEncodingBuf;
675 llvm::raw_svector_ostream FunctionEncodingStream(FunctionEncodingBuf);
676 CXXNameMangler FunctionEncodingMangler(*this, FunctionEncodingStream);
677 // Output name of the function.
678 FunctionEncodingMangler.disableDerivedAbiTags();
679 FunctionEncodingMangler.mangleNameWithAbiTags(FD, nullptr);
680
681 // Remember length of the function name in the buffer.
682 size_t EncodingPositionStart = FunctionEncodingStream.str().size();
683 FunctionEncodingMangler.mangleFunctionEncodingBareType(FD);
684
685 // Get tags from return type that are not present in function name or
686 // encoding.
687 const AbiTagList &UsedAbiTags =
688 FunctionEncodingMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
689 AbiTagList AdditionalAbiTags(ReturnTypeAbiTags.size());
690 AdditionalAbiTags.erase(
691 std::set_difference(ReturnTypeAbiTags.begin(), ReturnTypeAbiTags.end(),
692 UsedAbiTags.begin(), UsedAbiTags.end(),
693 AdditionalAbiTags.begin()),
694 AdditionalAbiTags.end());
695
696 // Output name with implicit tags and function encoding from temporary buffer.
697 mangleNameWithAbiTags(FD, &AdditionalAbiTags);
698 Out << FunctionEncodingStream.str().substr(EncodingPositionStart);
Dmitry Polukhinfda467b2016-09-21 08:27:03 +0000699
700 // Function encoding could create new substitutions so we have to add
701 // temp mangled substitutions to main mangler.
702 extendSubstitutions(&FunctionEncodingMangler);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000703}
704
705void CXXNameMangler::mangleFunctionEncodingBareType(const FunctionDecl *FD) {
Nick Lewycky0c2986f2014-04-26 00:14:00 +0000706 if (FD->hasAttr<EnableIfAttr>()) {
707 FunctionTypeDepthState Saved = FunctionTypeDepth.push();
708 Out << "Ua9enable_ifI";
Michael Krusedc5ce722018-08-03 01:21:16 +0000709 for (AttrVec::const_iterator I = FD->getAttrs().begin(),
710 E = FD->getAttrs().end();
Nick Lewycky0c2986f2014-04-26 00:14:00 +0000711 I != E; ++I) {
712 EnableIfAttr *EIA = dyn_cast<EnableIfAttr>(*I);
713 if (!EIA)
714 continue;
715 Out << 'X';
716 mangleExpression(EIA->getCond());
717 Out << 'E';
718 }
719 Out << 'E';
720 FunctionTypeDepth.pop(Saved);
721 }
722
Richard Smith5179eb72016-06-28 19:03:57 +0000723 // When mangling an inheriting constructor, the bare function type used is
724 // that of the inherited constructor.
725 if (auto *CD = dyn_cast<CXXConstructorDecl>(FD))
726 if (auto Inherited = CD->getInheritedConstructor())
727 FD = Inherited.getConstructor();
728
Guy Benyei11169dd2012-12-18 14:30:41 +0000729 // Whether the mangling of a function type includes the return type depends on
730 // the context and the nature of the function. The rules for deciding whether
731 // the return type is included are:
732 //
733 // 1. Template functions (names or types) have return types encoded, with
734 // the exceptions listed below.
735 // 2. Function types not appearing as part of a function name mangling,
736 // e.g. parameters, pointer types, etc., have return type encoded, with the
737 // exceptions listed below.
738 // 3. Non-template function names do not have return types encoded.
739 //
740 // The exceptions mentioned in (1) and (2) above, for which the return type is
741 // never included, are
742 // 1. Constructors.
743 // 2. Destructors.
744 // 3. Conversion operator functions, e.g. operator int.
745 bool MangleReturnType = false;
746 if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) {
747 if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD) ||
748 isa<CXXConversionDecl>(FD)))
749 MangleReturnType = true;
750
751 // Mangle the type of the primary template.
752 FD = PrimaryTemplate->getTemplatedDecl();
753 }
754
John McCall07daf722016-03-01 22:18:03 +0000755 mangleBareFunctionType(FD->getType()->castAs<FunctionProtoType>(),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000756 MangleReturnType, FD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000757}
758
759static const DeclContext *IgnoreLinkageSpecDecls(const DeclContext *DC) {
760 while (isa<LinkageSpecDecl>(DC)) {
761 DC = getEffectiveParentContext(DC);
762 }
763
764 return DC;
765}
766
Justin Bognere8d762e2015-05-22 06:48:13 +0000767/// Return whether a given namespace is the 'std' namespace.
Guy Benyei11169dd2012-12-18 14:30:41 +0000768static bool isStd(const NamespaceDecl *NS) {
769 if (!IgnoreLinkageSpecDecls(getEffectiveParentContext(NS))
770 ->isTranslationUnit())
771 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +0000772
Guy Benyei11169dd2012-12-18 14:30:41 +0000773 const IdentifierInfo *II = NS->getOriginalNamespace()->getIdentifier();
774 return II && II->isStr("std");
775}
776
777// isStdNamespace - Return whether a given decl context is a toplevel 'std'
778// namespace.
779static bool isStdNamespace(const DeclContext *DC) {
780 if (!DC->isNamespace())
781 return false;
782
783 return isStd(cast<NamespaceDecl>(DC));
784}
785
786static const TemplateDecl *
787isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
788 // Check if we have a function template.
Richard Smith5179eb72016-06-28 19:03:57 +0000789 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000790 if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
791 TemplateArgs = FD->getTemplateSpecializationArgs();
792 return TD;
793 }
794 }
795
796 // Check if we have a class template.
797 if (const ClassTemplateSpecializationDecl *Spec =
798 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
799 TemplateArgs = &Spec->getTemplateArgs();
800 return Spec->getSpecializedTemplate();
801 }
802
Larisse Voufo39a1e502013-08-06 01:03:05 +0000803 // Check if we have a variable template.
804 if (const VarTemplateSpecializationDecl *Spec =
805 dyn_cast<VarTemplateSpecializationDecl>(ND)) {
806 TemplateArgs = &Spec->getTemplateArgs();
807 return Spec->getSpecializedTemplate();
808 }
809
Craig Topper36250ad2014-05-12 05:36:57 +0000810 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000811}
812
Guy Benyei11169dd2012-12-18 14:30:41 +0000813void CXXNameMangler::mangleName(const NamedDecl *ND) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000814 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
815 // Variables should have implicit tags from its type.
816 AbiTagList VariableTypeAbiTags = makeVariableTypeTags(VD);
817 if (VariableTypeAbiTags.empty()) {
818 // Simple case no variable type tags.
819 mangleNameWithAbiTags(VD, nullptr);
820 return;
821 }
822
823 // Mangle variable name to null stream to collect tags.
824 llvm::raw_null_ostream NullOutStream;
825 CXXNameMangler VariableNameMangler(*this, NullOutStream);
826 VariableNameMangler.disableDerivedAbiTags();
827 VariableNameMangler.mangleNameWithAbiTags(VD, nullptr);
828
829 // Get tags from variable type that are not present in its name.
830 const AbiTagList &UsedAbiTags =
831 VariableNameMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
832 AbiTagList AdditionalAbiTags(VariableTypeAbiTags.size());
833 AdditionalAbiTags.erase(
834 std::set_difference(VariableTypeAbiTags.begin(),
835 VariableTypeAbiTags.end(), UsedAbiTags.begin(),
836 UsedAbiTags.end(), AdditionalAbiTags.begin()),
837 AdditionalAbiTags.end());
838
839 // Output name with implicit tags.
840 mangleNameWithAbiTags(VD, &AdditionalAbiTags);
841 } else {
842 mangleNameWithAbiTags(ND, nullptr);
843 }
844}
845
846void CXXNameMangler::mangleNameWithAbiTags(const NamedDecl *ND,
847 const AbiTagList *AdditionalAbiTags) {
Richard Smithdd8b5332017-09-04 05:37:53 +0000848 // <name> ::= [<module-name>] <nested-name>
849 // ::= [<module-name>] <unscoped-name>
850 // ::= [<module-name>] <unscoped-template-name> <template-args>
Guy Benyei11169dd2012-12-18 14:30:41 +0000851 // ::= <local-name>
852 //
853 const DeclContext *DC = getEffectiveDeclContext(ND);
854
855 // If this is an extern variable declared locally, the relevant DeclContext
856 // is that of the containing namespace, or the translation unit.
857 // FIXME: This is a hack; extern variables declared locally should have
858 // a proper semantic declaration context!
Eli Friedman95f50122013-07-02 17:52:28 +0000859 if (isLocalContainerContext(DC) && ND->hasLinkage() && !isLambda(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +0000860 while (!DC->isNamespace() && !DC->isTranslationUnit())
861 DC = getEffectiveParentContext(DC);
862 else if (GetLocalClassDecl(ND)) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000863 mangleLocalName(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +0000864 return;
865 }
866
867 DC = IgnoreLinkageSpecDecls(DC);
868
Richard Smithdd8b5332017-09-04 05:37:53 +0000869 if (isLocalContainerContext(DC)) {
870 mangleLocalName(ND, AdditionalAbiTags);
871 return;
872 }
873
874 // Do not mangle the owning module for an external linkage declaration.
875 // This enables backwards-compatibility with non-modular code, and is
876 // a valid choice since conflicts are not permitted by C++ Modules TS
877 // [basic.def.odr]/6.2.
878 if (!ND->hasExternalFormalLinkage())
879 if (Module *M = ND->getOwningModuleForLinkage())
880 mangleModuleName(M);
881
Guy Benyei11169dd2012-12-18 14:30:41 +0000882 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
883 // Check if we have a template.
Craig Topper36250ad2014-05-12 05:36:57 +0000884 const TemplateArgumentList *TemplateArgs = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000885 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000886 mangleUnscopedTemplateName(TD, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +0000887 mangleTemplateArgs(*TemplateArgs);
888 return;
889 }
890
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000891 mangleUnscopedName(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +0000892 return;
893 }
894
Richard Smithdd8b5332017-09-04 05:37:53 +0000895 mangleNestedName(ND, DC, AdditionalAbiTags);
896}
897
898void CXXNameMangler::mangleModuleName(const Module *M) {
899 // Implement the C++ Modules TS name mangling proposal; see
900 // https://gcc.gnu.org/wiki/cxx-modules?action=AttachFile
901 //
902 // <module-name> ::= W <unscoped-name>+ E
903 // ::= W <module-subst> <unscoped-name>* E
904 Out << 'W';
905 mangleModuleNamePrefix(M->Name);
906 Out << 'E';
907}
908
909void CXXNameMangler::mangleModuleNamePrefix(StringRef Name) {
910 // <module-subst> ::= _ <seq-id> # 0 < seq-id < 10
911 // ::= W <seq-id - 10> _ # otherwise
912 auto It = ModuleSubstitutions.find(Name);
913 if (It != ModuleSubstitutions.end()) {
914 if (It->second < 10)
915 Out << '_' << static_cast<char>('0' + It->second);
916 else
917 Out << 'W' << (It->second - 10) << '_';
Guy Benyei11169dd2012-12-18 14:30:41 +0000918 return;
919 }
920
Richard Smithdd8b5332017-09-04 05:37:53 +0000921 // FIXME: Preserve hierarchy in module names rather than flattening
922 // them to strings; use Module*s as substitution keys.
923 auto Parts = Name.rsplit('.');
924 if (Parts.second.empty())
925 Parts.second = Parts.first;
926 else
927 mangleModuleNamePrefix(Parts.first);
928
929 Out << Parts.second.size() << Parts.second;
930 ModuleSubstitutions.insert({Name, ModuleSubstitutions.size()});
Guy Benyei11169dd2012-12-18 14:30:41 +0000931}
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000932
933void CXXNameMangler::mangleTemplateName(const TemplateDecl *TD,
934 const TemplateArgument *TemplateArgs,
935 unsigned NumTemplateArgs) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000936 const DeclContext *DC = IgnoreLinkageSpecDecls(getEffectiveDeclContext(TD));
937
938 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000939 mangleUnscopedTemplateName(TD, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +0000940 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
941 } else {
942 mangleNestedName(TD, TemplateArgs, NumTemplateArgs);
943 }
944}
945
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000946void CXXNameMangler::mangleUnscopedName(const NamedDecl *ND,
947 const AbiTagList *AdditionalAbiTags) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000948 // <unscoped-name> ::= <unqualified-name>
949 // ::= St <unqualified-name> # ::std::
950
951 if (isStdNamespace(IgnoreLinkageSpecDecls(getEffectiveDeclContext(ND))))
952 Out << "St";
953
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000954 mangleUnqualifiedName(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +0000955}
956
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000957void CXXNameMangler::mangleUnscopedTemplateName(
958 const TemplateDecl *ND, const AbiTagList *AdditionalAbiTags) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000959 // <unscoped-template-name> ::= <unscoped-name>
960 // ::= <substitution>
961 if (mangleSubstitution(ND))
962 return;
963
964 // <template-template-param> ::= <template-param>
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000965 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
966 assert(!AdditionalAbiTags &&
967 "template template param cannot have abi tags");
Guy Benyei11169dd2012-12-18 14:30:41 +0000968 mangleTemplateParameter(TTP->getIndex());
David Majnemer6d2b60a2016-07-12 16:48:17 +0000969 } else if (isa<BuiltinTemplateDecl>(ND)) {
970 mangleUnscopedName(ND, AdditionalAbiTags);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000971 } else {
972 mangleUnscopedName(ND->getTemplatedDecl(), AdditionalAbiTags);
973 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000974
Guy Benyei11169dd2012-12-18 14:30:41 +0000975 addSubstitution(ND);
976}
977
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000978void CXXNameMangler::mangleUnscopedTemplateName(
979 TemplateName Template, const AbiTagList *AdditionalAbiTags) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000980 // <unscoped-template-name> ::= <unscoped-name>
981 // ::= <substitution>
982 if (TemplateDecl *TD = Template.getAsTemplateDecl())
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000983 return mangleUnscopedTemplateName(TD, AdditionalAbiTags);
Fangrui Song6907ce22018-07-30 19:24:48 +0000984
Guy Benyei11169dd2012-12-18 14:30:41 +0000985 if (mangleSubstitution(Template))
986 return;
987
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000988 assert(!AdditionalAbiTags &&
989 "dependent template name cannot have abi tags");
990
Guy Benyei11169dd2012-12-18 14:30:41 +0000991 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
992 assert(Dependent && "Not a dependent template name?");
993 if (const IdentifierInfo *Id = Dependent->getIdentifier())
994 mangleSourceName(Id);
995 else
996 mangleOperatorName(Dependent->getOperator(), UnknownArity);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000997
Guy Benyei11169dd2012-12-18 14:30:41 +0000998 addSubstitution(Template);
999}
1000
1001void CXXNameMangler::mangleFloat(const llvm::APFloat &f) {
1002 // ABI:
1003 // Floating-point literals are encoded using a fixed-length
1004 // lowercase hexadecimal string corresponding to the internal
1005 // representation (IEEE on Itanium), high-order bytes first,
1006 // without leading zeroes. For example: "Lf bf800000 E" is -1.0f
1007 // on Itanium.
1008 // The 'without leading zeroes' thing seems to be an editorial
1009 // mistake; see the discussion on cxx-abi-dev beginning on
1010 // 2012-01-16.
1011
1012 // Our requirements here are just barely weird enough to justify
1013 // using a custom algorithm instead of post-processing APInt::toString().
1014
1015 llvm::APInt valueBits = f.bitcastToAPInt();
1016 unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4;
1017 assert(numCharacters != 0);
1018
1019 // Allocate a buffer of the right number of characters.
Benjamin Kramerc9ba1bd2015-08-04 13:34:50 +00001020 SmallVector<char, 20> buffer(numCharacters);
Guy Benyei11169dd2012-12-18 14:30:41 +00001021
1022 // Fill the buffer left-to-right.
1023 for (unsigned stringIndex = 0; stringIndex != numCharacters; ++stringIndex) {
1024 // The bit-index of the next hex digit.
1025 unsigned digitBitIndex = 4 * (numCharacters - stringIndex - 1);
1026
1027 // Project out 4 bits starting at 'digitIndex'.
Craig Topperc396c532017-03-30 05:48:58 +00001028 uint64_t hexDigit = valueBits.getRawData()[digitBitIndex / 64];
1029 hexDigit >>= (digitBitIndex % 64);
Guy Benyei11169dd2012-12-18 14:30:41 +00001030 hexDigit &= 0xF;
1031
1032 // Map that over to a lowercase hex digit.
1033 static const char charForHex[16] = {
1034 '0', '1', '2', '3', '4', '5', '6', '7',
1035 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
1036 };
1037 buffer[stringIndex] = charForHex[hexDigit];
1038 }
1039
1040 Out.write(buffer.data(), numCharacters);
1041}
1042
1043void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
1044 if (Value.isSigned() && Value.isNegative()) {
1045 Out << 'n';
1046 Value.abs().print(Out, /*signed*/ false);
1047 } else {
1048 Value.print(Out, /*signed*/ false);
1049 }
1050}
1051
1052void CXXNameMangler::mangleNumber(int64_t Number) {
1053 // <number> ::= [n] <non-negative decimal integer>
1054 if (Number < 0) {
1055 Out << 'n';
1056 Number = -Number;
1057 }
1058
1059 Out << Number;
1060}
1061
1062void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) {
1063 // <call-offset> ::= h <nv-offset> _
1064 // ::= v <v-offset> _
1065 // <nv-offset> ::= <offset number> # non-virtual base override
1066 // <v-offset> ::= <offset number> _ <virtual offset number>
1067 // # virtual base override, with vcall offset
1068 if (!Virtual) {
1069 Out << 'h';
1070 mangleNumber(NonVirtual);
1071 Out << '_';
1072 return;
1073 }
1074
1075 Out << 'v';
1076 mangleNumber(NonVirtual);
1077 Out << '_';
1078 mangleNumber(Virtual);
1079 Out << '_';
1080}
1081
1082void CXXNameMangler::manglePrefix(QualType type) {
David Majnemera88b3592015-02-18 02:28:01 +00001083 if (const auto *TST = type->getAs<TemplateSpecializationType>()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001084 if (!mangleSubstitution(QualType(TST, 0))) {
1085 mangleTemplatePrefix(TST->getTemplateName());
Fangrui Song6907ce22018-07-30 19:24:48 +00001086
Guy Benyei11169dd2012-12-18 14:30:41 +00001087 // FIXME: GCC does not appear to mangle the template arguments when
1088 // the template in question is a dependent template name. Should we
1089 // emulate that badness?
1090 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
1091 addSubstitution(QualType(TST, 0));
1092 }
David Majnemera88b3592015-02-18 02:28:01 +00001093 } else if (const auto *DTST =
1094 type->getAs<DependentTemplateSpecializationType>()) {
1095 if (!mangleSubstitution(QualType(DTST, 0))) {
1096 TemplateName Template = getASTContext().getDependentTemplateName(
1097 DTST->getQualifier(), DTST->getIdentifier());
1098 mangleTemplatePrefix(Template);
Guy Benyei11169dd2012-12-18 14:30:41 +00001099
David Majnemera88b3592015-02-18 02:28:01 +00001100 // FIXME: GCC does not appear to mangle the template arguments when
1101 // the template in question is a dependent template name. Should we
1102 // emulate that badness?
1103 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
1104 addSubstitution(QualType(DTST, 0));
1105 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001106 } else {
1107 // We use the QualType mangle type variant here because it handles
1108 // substitutions.
1109 mangleType(type);
1110 }
1111}
1112
1113/// Mangle everything prior to the base-unresolved-name in an unresolved-name.
1114///
Guy Benyei11169dd2012-12-18 14:30:41 +00001115/// \param recursive - true if this is being called recursively,
1116/// i.e. if there is more prefix "to the right".
1117void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
Guy Benyei11169dd2012-12-18 14:30:41 +00001118 bool recursive) {
1119
1120 // x, ::x
1121 // <unresolved-name> ::= [gs] <base-unresolved-name>
1122
1123 // T::x / decltype(p)::x
1124 // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name>
1125
1126 // T::N::x /decltype(p)::N::x
1127 // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
1128 // <base-unresolved-name>
1129
1130 // A::x, N::y, A<T>::z; "gs" means leading "::"
1131 // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E
1132 // <base-unresolved-name>
1133
1134 switch (qualifier->getKind()) {
1135 case NestedNameSpecifier::Global:
1136 Out << "gs";
1137
1138 // We want an 'sr' unless this is the entire NNS.
1139 if (recursive)
1140 Out << "sr";
1141
1142 // We never want an 'E' here.
1143 return;
1144
Nikola Smiljanic67860242014-09-26 00:28:20 +00001145 case NestedNameSpecifier::Super:
1146 llvm_unreachable("Can't mangle __super specifier");
1147
Guy Benyei11169dd2012-12-18 14:30:41 +00001148 case NestedNameSpecifier::Namespace:
1149 if (qualifier->getPrefix())
David Majnemerb8014dd2015-02-19 02:16:16 +00001150 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +00001151 /*recursive*/ true);
1152 else
1153 Out << "sr";
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001154 mangleSourceNameWithAbiTags(qualifier->getAsNamespace());
Guy Benyei11169dd2012-12-18 14:30:41 +00001155 break;
1156 case NestedNameSpecifier::NamespaceAlias:
1157 if (qualifier->getPrefix())
David Majnemerb8014dd2015-02-19 02:16:16 +00001158 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +00001159 /*recursive*/ true);
1160 else
1161 Out << "sr";
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001162 mangleSourceNameWithAbiTags(qualifier->getAsNamespaceAlias());
Guy Benyei11169dd2012-12-18 14:30:41 +00001163 break;
1164
1165 case NestedNameSpecifier::TypeSpec:
1166 case NestedNameSpecifier::TypeSpecWithTemplate: {
1167 const Type *type = qualifier->getAsType();
1168
1169 // We only want to use an unresolved-type encoding if this is one of:
1170 // - a decltype
1171 // - a template type parameter
1172 // - a template template parameter with arguments
1173 // In all of these cases, we should have no prefix.
1174 if (qualifier->getPrefix()) {
David Majnemerb8014dd2015-02-19 02:16:16 +00001175 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +00001176 /*recursive*/ true);
1177 } else {
1178 // Otherwise, all the cases want this.
1179 Out << "sr";
1180 }
1181
David Majnemerb8014dd2015-02-19 02:16:16 +00001182 if (mangleUnresolvedTypeOrSimpleId(QualType(type, 0), recursive ? "N" : ""))
Guy Benyei11169dd2012-12-18 14:30:41 +00001183 return;
1184
Guy Benyei11169dd2012-12-18 14:30:41 +00001185 break;
1186 }
1187
1188 case NestedNameSpecifier::Identifier:
1189 // Member expressions can have these without prefixes.
David Majnemerb8014dd2015-02-19 02:16:16 +00001190 if (qualifier->getPrefix())
1191 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +00001192 /*recursive*/ true);
David Majnemerb8014dd2015-02-19 02:16:16 +00001193 else
Guy Benyei11169dd2012-12-18 14:30:41 +00001194 Out << "sr";
Guy Benyei11169dd2012-12-18 14:30:41 +00001195
1196 mangleSourceName(qualifier->getAsIdentifier());
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001197 // An Identifier has no type information, so we can't emit abi tags for it.
Guy Benyei11169dd2012-12-18 14:30:41 +00001198 break;
1199 }
1200
1201 // If this was the innermost part of the NNS, and we fell out to
1202 // here, append an 'E'.
1203 if (!recursive)
1204 Out << 'E';
1205}
1206
1207/// Mangle an unresolved-name, which is generally used for names which
1208/// weren't resolved to specific entities.
Richard Smithafecd832016-10-24 20:47:04 +00001209void CXXNameMangler::mangleUnresolvedName(
1210 NestedNameSpecifier *qualifier, DeclarationName name,
1211 const TemplateArgumentLoc *TemplateArgs, unsigned NumTemplateArgs,
1212 unsigned knownArity) {
David Majnemerb8014dd2015-02-19 02:16:16 +00001213 if (qualifier) mangleUnresolvedPrefix(qualifier);
David Majnemer1dabfdc2015-02-14 13:23:54 +00001214 switch (name.getNameKind()) {
1215 // <base-unresolved-name> ::= <simple-id>
1216 case DeclarationName::Identifier:
David Majnemera88b3592015-02-18 02:28:01 +00001217 mangleSourceName(name.getAsIdentifierInfo());
1218 break;
1219 // <base-unresolved-name> ::= dn <destructor-name>
1220 case DeclarationName::CXXDestructorName:
1221 Out << "dn";
David Majnemerb8014dd2015-02-19 02:16:16 +00001222 mangleUnresolvedTypeOrSimpleId(name.getCXXNameType());
David Majnemer1dabfdc2015-02-14 13:23:54 +00001223 break;
1224 // <base-unresolved-name> ::= on <operator-name>
1225 case DeclarationName::CXXConversionFunctionName:
1226 case DeclarationName::CXXLiteralOperatorName:
1227 case DeclarationName::CXXOperatorName:
1228 Out << "on";
David Majnemera88b3592015-02-18 02:28:01 +00001229 mangleOperatorName(name, knownArity);
David Majnemer1dabfdc2015-02-14 13:23:54 +00001230 break;
David Majnemer1dabfdc2015-02-14 13:23:54 +00001231 case DeclarationName::CXXConstructorName:
1232 llvm_unreachable("Can't mangle a constructor name!");
1233 case DeclarationName::CXXUsingDirective:
1234 llvm_unreachable("Can't mangle a using directive name!");
Richard Smith35845152017-02-07 01:37:30 +00001235 case DeclarationName::CXXDeductionGuideName:
1236 llvm_unreachable("Can't mangle a deduction guide name!");
David Majnemer1dabfdc2015-02-14 13:23:54 +00001237 case DeclarationName::ObjCMultiArgSelector:
1238 case DeclarationName::ObjCOneArgSelector:
1239 case DeclarationName::ObjCZeroArgSelector:
1240 llvm_unreachable("Can't mangle Objective-C selector names here!");
1241 }
Richard Smithafecd832016-10-24 20:47:04 +00001242
1243 // The <simple-id> and on <operator-name> productions end in an optional
1244 // <template-args>.
1245 if (TemplateArgs)
1246 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
Guy Benyei11169dd2012-12-18 14:30:41 +00001247}
1248
Guy Benyei11169dd2012-12-18 14:30:41 +00001249void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
1250 DeclarationName Name,
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001251 unsigned KnownArity,
1252 const AbiTagList *AdditionalAbiTags) {
David Majnemera88b3592015-02-18 02:28:01 +00001253 unsigned Arity = KnownArity;
Guy Benyei11169dd2012-12-18 14:30:41 +00001254 // <unqualified-name> ::= <operator-name>
1255 // ::= <ctor-dtor-name>
1256 // ::= <source-name>
1257 switch (Name.getNameKind()) {
1258 case DeclarationName::Identifier: {
Richard Smithbdb84f32016-07-22 23:36:59 +00001259 const IdentifierInfo *II = Name.getAsIdentifierInfo();
1260
Richard Smithda383632016-08-15 01:33:41 +00001261 // We mangle decomposition declarations as the names of their bindings.
Richard Smithbdb84f32016-07-22 23:36:59 +00001262 if (auto *DD = dyn_cast<DecompositionDecl>(ND)) {
Richard Smithda383632016-08-15 01:33:41 +00001263 // FIXME: Non-standard mangling for decomposition declarations:
1264 //
1265 // <unqualified-name> ::= DC <source-name>* E
1266 //
1267 // These can never be referenced across translation units, so we do
1268 // not need a cross-vendor mangling for anything other than demanglers.
1269 // Proposed on cxx-abi-dev on 2016-08-12
1270 Out << "DC";
1271 for (auto *BD : DD->bindings())
1272 mangleSourceName(BD->getDeclName().getAsIdentifierInfo());
1273 Out << 'E';
1274 writeAbiTags(ND, AdditionalAbiTags);
1275 break;
Richard Smithbdb84f32016-07-22 23:36:59 +00001276 }
1277
1278 if (II) {
Richard Smithdd8b5332017-09-04 05:37:53 +00001279 // Match GCC's naming convention for internal linkage symbols, for
1280 // symbols that are not actually visible outside of this TU. GCC
1281 // distinguishes between internal and external linkage symbols in
1282 // its mangling, to support cases like this that were valid C++ prior
1283 // to DR426:
1284 //
Guy Benyei11169dd2012-12-18 14:30:41 +00001285 // void test() { extern void foo(); }
1286 // static void foo();
Richard Smithdf963a32017-09-22 22:21:44 +00001287 //
1288 // Don't bother with the L marker for names in anonymous namespaces; the
1289 // 12_GLOBAL__N_1 mangling is quite sufficient there, and this better
1290 // matches GCC anyway, because GCC does not treat anonymous namespaces as
1291 // implying internal linkage.
Rafael Espindola3ae00052013-05-13 00:12:11 +00001292 if (ND && ND->getFormalLinkage() == InternalLinkage &&
Richard Smithdd8b5332017-09-04 05:37:53 +00001293 !ND->isExternallyVisible() &&
Richard Smithdf963a32017-09-22 22:21:44 +00001294 getEffectiveDeclContext(ND)->isFileContext() &&
1295 !ND->isInAnonymousNamespace())
Guy Benyei11169dd2012-12-18 14:30:41 +00001296 Out << 'L';
1297
Erich Keane757d3172016-11-02 18:29:35 +00001298 auto *FD = dyn_cast<FunctionDecl>(ND);
1299 bool IsRegCall = FD &&
1300 FD->getType()->castAs<FunctionType>()->getCallConv() ==
1301 clang::CC_X86RegCall;
1302 if (IsRegCall)
1303 mangleRegCallName(II);
1304 else
1305 mangleSourceName(II);
1306
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001307 writeAbiTags(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001308 break;
1309 }
1310
1311 // Otherwise, an anonymous entity. We must have a declaration.
1312 assert(ND && "mangling empty name without declaration");
1313
1314 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
1315 if (NS->isAnonymousNamespace()) {
1316 // This is how gcc mangles these names.
1317 Out << "12_GLOBAL__N_1";
1318 break;
1319 }
1320 }
1321
1322 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
1323 // We must have an anonymous union or struct declaration.
George Burgess IV00f70bd2018-03-01 05:43:23 +00001324 const RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00001325
Guy Benyei11169dd2012-12-18 14:30:41 +00001326 // Itanium C++ ABI 5.1.2:
1327 //
1328 // For the purposes of mangling, the name of an anonymous union is
1329 // considered to be the name of the first named data member found by a
1330 // pre-order, depth-first, declaration-order walk of the data members of
1331 // the anonymous union. If there is no such data member (i.e., if all of
1332 // the data members in the union are unnamed), then there is no way for
1333 // a program to refer to the anonymous union, and there is therefore no
1334 // need to mangle its name.
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00001335 assert(RD->isAnonymousStructOrUnion()
1336 && "Expected anonymous struct or union!");
1337 const FieldDecl *FD = RD->findFirstNamedDataMember();
Guy Benyei11169dd2012-12-18 14:30:41 +00001338
1339 // It's actually possible for various reasons for us to get here
1340 // with an empty anonymous struct / union. Fortunately, it
1341 // doesn't really matter what name we generate.
1342 if (!FD) break;
1343 assert(FD->getIdentifier() && "Data member name isn't an identifier!");
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00001344
Guy Benyei11169dd2012-12-18 14:30:41 +00001345 mangleSourceName(FD->getIdentifier());
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001346 // Not emitting abi tags: internal name anyway.
Guy Benyei11169dd2012-12-18 14:30:41 +00001347 break;
1348 }
John McCall924046f2013-04-10 06:08:21 +00001349
1350 // Class extensions have no name as a category, and it's possible
1351 // for them to be the semantic parent of certain declarations
1352 // (primarily, tag decls defined within declarations). Such
1353 // declarations will always have internal linkage, so the name
1354 // doesn't really matter, but we shouldn't crash on them. For
1355 // safety, just handle all ObjC containers here.
1356 if (isa<ObjCContainerDecl>(ND))
1357 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00001358
Guy Benyei11169dd2012-12-18 14:30:41 +00001359 // We must have an anonymous struct.
1360 const TagDecl *TD = cast<TagDecl>(ND);
1361 if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
1362 assert(TD->getDeclContext() == D->getDeclContext() &&
1363 "Typedef should not be in another decl context!");
1364 assert(D->getDeclName().getAsIdentifierInfo() &&
1365 "Typedef was not named!");
1366 mangleSourceName(D->getDeclName().getAsIdentifierInfo());
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001367 assert(!AdditionalAbiTags && "Type cannot have additional abi tags");
1368 // Explicit abi tags are still possible; take from underlying type, not
1369 // from typedef.
1370 writeAbiTags(TD, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001371 break;
1372 }
1373
1374 // <unnamed-type-name> ::= <closure-type-name>
Fangrui Song6907ce22018-07-30 19:24:48 +00001375 //
Guy Benyei11169dd2012-12-18 14:30:41 +00001376 // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
Hamza Sood8205a812019-05-04 10:49:46 +00001377 // <lambda-sig> ::= <template-param-decl>* <parameter-type>+
1378 // # Parameter types or 'v' for 'void'.
Guy Benyei11169dd2012-12-18 14:30:41 +00001379 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
1380 if (Record->isLambda() && Record->getLambdaManglingNumber()) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001381 assert(!AdditionalAbiTags &&
1382 "Lambda type cannot have additional abi tags");
Guy Benyei11169dd2012-12-18 14:30:41 +00001383 mangleLambda(Record);
1384 break;
1385 }
1386 }
1387
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001388 if (TD->isExternallyVisible()) {
1389 unsigned UnnamedMangle = getASTContext().getManglingNumber(TD);
Guy Benyei11169dd2012-12-18 14:30:41 +00001390 Out << "Ut";
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001391 if (UnnamedMangle > 1)
Benjamin Kramerb42d9a52015-12-24 10:07:37 +00001392 Out << UnnamedMangle - 2;
Guy Benyei11169dd2012-12-18 14:30:41 +00001393 Out << '_';
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001394 writeAbiTags(TD, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001395 break;
1396 }
1397
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001398 // Get a unique id for the anonymous struct. If it is not a real output
1399 // ID doesn't matter so use fake one.
1400 unsigned AnonStructId = NullOut ? 0 : Context.getAnonymousStructId(TD);
Guy Benyei11169dd2012-12-18 14:30:41 +00001401
1402 // Mangle it as a source name in the form
1403 // [n] $_<id>
1404 // where n is the length of the string.
1405 SmallString<8> Str;
1406 Str += "$_";
1407 Str += llvm::utostr(AnonStructId);
1408
1409 Out << Str.size();
Yaron Keren09fb7c62015-03-10 07:33:23 +00001410 Out << Str;
Guy Benyei11169dd2012-12-18 14:30:41 +00001411 break;
1412 }
1413
1414 case DeclarationName::ObjCZeroArgSelector:
1415 case DeclarationName::ObjCOneArgSelector:
1416 case DeclarationName::ObjCMultiArgSelector:
1417 llvm_unreachable("Can't mangle Objective-C selector names here!");
1418
Richard Smith5179eb72016-06-28 19:03:57 +00001419 case DeclarationName::CXXConstructorName: {
1420 const CXXRecordDecl *InheritedFrom = nullptr;
1421 const TemplateArgumentList *InheritedTemplateArgs = nullptr;
1422 if (auto Inherited =
1423 cast<CXXConstructorDecl>(ND)->getInheritedConstructor()) {
1424 InheritedFrom = Inherited.getConstructor()->getParent();
1425 InheritedTemplateArgs =
1426 Inherited.getConstructor()->getTemplateSpecializationArgs();
1427 }
1428
Guy Benyei11169dd2012-12-18 14:30:41 +00001429 if (ND == Structor)
1430 // If the named decl is the C++ constructor we're mangling, use the type
1431 // we were given.
Richard Smith5179eb72016-06-28 19:03:57 +00001432 mangleCXXCtorType(static_cast<CXXCtorType>(StructorType), InheritedFrom);
Guy Benyei11169dd2012-12-18 14:30:41 +00001433 else
1434 // Otherwise, use the complete constructor name. This is relevant if a
1435 // class with a constructor is declared within a constructor.
Richard Smith5179eb72016-06-28 19:03:57 +00001436 mangleCXXCtorType(Ctor_Complete, InheritedFrom);
1437
1438 // FIXME: The template arguments are part of the enclosing prefix or
1439 // nested-name, but it's more convenient to mangle them here.
1440 if (InheritedTemplateArgs)
1441 mangleTemplateArgs(*InheritedTemplateArgs);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001442
1443 writeAbiTags(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001444 break;
Richard Smith5179eb72016-06-28 19:03:57 +00001445 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001446
1447 case DeclarationName::CXXDestructorName:
1448 if (ND == Structor)
1449 // If the named decl is the C++ destructor we're mangling, use the type we
1450 // were given.
1451 mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
1452 else
1453 // Otherwise, use the complete destructor name. This is relevant if a
1454 // class with a destructor is declared within a destructor.
1455 mangleCXXDtorType(Dtor_Complete);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001456 writeAbiTags(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001457 break;
1458
David Majnemera88b3592015-02-18 02:28:01 +00001459 case DeclarationName::CXXOperatorName:
1460 if (ND && Arity == UnknownArity) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001461 Arity = cast<FunctionDecl>(ND)->getNumParams();
1462
David Majnemera88b3592015-02-18 02:28:01 +00001463 // If we have a member function, we need to include the 'this' pointer.
1464 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND))
1465 if (!MD->isStatic())
1466 Arity++;
1467 }
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00001468 LLVM_FALLTHROUGH;
David Majnemera88b3592015-02-18 02:28:01 +00001469 case DeclarationName::CXXConversionFunctionName:
Guy Benyei11169dd2012-12-18 14:30:41 +00001470 case DeclarationName::CXXLiteralOperatorName:
David Majnemera88b3592015-02-18 02:28:01 +00001471 mangleOperatorName(Name, Arity);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001472 writeAbiTags(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001473 break;
1474
Richard Smith35845152017-02-07 01:37:30 +00001475 case DeclarationName::CXXDeductionGuideName:
1476 llvm_unreachable("Can't mangle a deduction guide name!");
1477
Guy Benyei11169dd2012-12-18 14:30:41 +00001478 case DeclarationName::CXXUsingDirective:
1479 llvm_unreachable("Can't mangle a using directive name!");
1480 }
1481}
1482
Erich Keane757d3172016-11-02 18:29:35 +00001483void CXXNameMangler::mangleRegCallName(const IdentifierInfo *II) {
1484 // <source-name> ::= <positive length number> __regcall3__ <identifier>
1485 // <number> ::= [n] <non-negative decimal integer>
1486 // <identifier> ::= <unqualified source code identifier>
1487 Out << II->getLength() + sizeof("__regcall3__") - 1 << "__regcall3__"
1488 << II->getName();
1489}
1490
Guy Benyei11169dd2012-12-18 14:30:41 +00001491void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
1492 // <source-name> ::= <positive length number> <identifier>
1493 // <number> ::= [n] <non-negative decimal integer>
1494 // <identifier> ::= <unqualified source code identifier>
1495 Out << II->getLength() << II->getName();
1496}
1497
1498void CXXNameMangler::mangleNestedName(const NamedDecl *ND,
1499 const DeclContext *DC,
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001500 const AbiTagList *AdditionalAbiTags,
Guy Benyei11169dd2012-12-18 14:30:41 +00001501 bool NoFunction) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001502 // <nested-name>
Guy Benyei11169dd2012-12-18 14:30:41 +00001503 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
Fangrui Song6907ce22018-07-30 19:24:48 +00001504 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
Guy Benyei11169dd2012-12-18 14:30:41 +00001505 // <template-args> E
1506
1507 Out << 'N';
1508 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) {
Anastasia Stulovac61eaa52019-01-28 11:37:49 +00001509 Qualifiers MethodQuals = Method->getMethodQualifiers();
David Majnemer42350df2013-11-03 23:51:28 +00001510 // We do not consider restrict a distinguishing attribute for overloading
1511 // purposes so we must not mangle it.
1512 MethodQuals.removeRestrict();
1513 mangleQualifiers(MethodQuals);
Guy Benyei11169dd2012-12-18 14:30:41 +00001514 mangleRefQualifier(Method->getRefQualifier());
1515 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001516
Guy Benyei11169dd2012-12-18 14:30:41 +00001517 // Check if we have a template.
Craig Topper36250ad2014-05-12 05:36:57 +00001518 const TemplateArgumentList *TemplateArgs = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001519 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
Eli Friedman86af13f02013-07-05 18:41:30 +00001520 mangleTemplatePrefix(TD, NoFunction);
Guy Benyei11169dd2012-12-18 14:30:41 +00001521 mangleTemplateArgs(*TemplateArgs);
1522 }
1523 else {
1524 manglePrefix(DC, NoFunction);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001525 mangleUnqualifiedName(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001526 }
1527
1528 Out << 'E';
1529}
1530void CXXNameMangler::mangleNestedName(const TemplateDecl *TD,
1531 const TemplateArgument *TemplateArgs,
1532 unsigned NumTemplateArgs) {
1533 // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
1534
1535 Out << 'N';
1536
1537 mangleTemplatePrefix(TD);
1538 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
1539
1540 Out << 'E';
1541}
1542
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001543void CXXNameMangler::mangleLocalName(const Decl *D,
1544 const AbiTagList *AdditionalAbiTags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001545 // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
1546 // := Z <function encoding> E s [<discriminator>]
Fangrui Song6907ce22018-07-30 19:24:48 +00001547 // <local-name> := Z <function encoding> E d [ <parameter number> ]
Guy Benyei11169dd2012-12-18 14:30:41 +00001548 // _ <entity name>
1549 // <discriminator> := _ <non-negative number>
Eli Friedman95f50122013-07-02 17:52:28 +00001550 assert(isa<NamedDecl>(D) || isa<BlockDecl>(D));
Eli Friedmaneecc09a2013-07-05 20:27:40 +00001551 const RecordDecl *RD = GetLocalClassDecl(D);
Eli Friedman95f50122013-07-02 17:52:28 +00001552 const DeclContext *DC = getEffectiveDeclContext(RD ? RD : D);
Guy Benyei11169dd2012-12-18 14:30:41 +00001553
1554 Out << 'Z';
1555
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001556 {
1557 AbiTagState LocalAbiTags(AbiTags);
1558
1559 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))
1560 mangleObjCMethodName(MD);
1561 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC))
1562 mangleBlockForPrefix(BD);
1563 else
1564 mangleFunctionEncoding(cast<FunctionDecl>(DC));
1565
1566 // Implicit ABI tags (from namespace) are not available in the following
1567 // entity; reset to actually emitted tags, which are available.
1568 LocalAbiTags.setUsedAbiTags(LocalAbiTags.getEmittedAbiTags());
1569 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001570
Eli Friedman92821742013-07-02 02:01:18 +00001571 Out << 'E';
1572
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001573 // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
1574 // be a bug that is fixed in trunk.
1575
Eli Friedman92821742013-07-02 02:01:18 +00001576 if (RD) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001577 // The parameter number is omitted for the last parameter, 0 for the
1578 // second-to-last parameter, 1 for the third-to-last parameter, etc. The
1579 // <entity name> will of course contain a <closure-type-name>: Its
Guy Benyei11169dd2012-12-18 14:30:41 +00001580 // numbering will be local to the particular argument in which it appears
1581 // -- other default arguments do not affect its encoding.
Eli Friedmaneecc09a2013-07-05 20:27:40 +00001582 const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD);
Richard Smithcb2ba5a2016-07-18 22:37:35 +00001583 if (CXXRD && CXXRD->isLambda()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001584 if (const ParmVarDecl *Parm
Eli Friedmaneecc09a2013-07-05 20:27:40 +00001585 = dyn_cast_or_null<ParmVarDecl>(CXXRD->getLambdaContextDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001586 if (const FunctionDecl *Func
1587 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1588 Out << 'd';
1589 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1590 if (Num > 1)
1591 mangleNumber(Num - 2);
1592 Out << '_';
Guy Benyei11169dd2012-12-18 14:30:41 +00001593 }
1594 }
1595 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001596
Guy Benyei11169dd2012-12-18 14:30:41 +00001597 // Mangle the name relative to the closest enclosing function.
Eli Friedman95f50122013-07-02 17:52:28 +00001598 // equality ok because RD derived from ND above
1599 if (D == RD) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001600 mangleUnqualifiedName(RD, AdditionalAbiTags);
Eli Friedman95f50122013-07-02 17:52:28 +00001601 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1602 manglePrefix(getEffectiveDeclContext(BD), true /*NoFunction*/);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001603 assert(!AdditionalAbiTags && "Block cannot have additional abi tags");
Eli Friedman95f50122013-07-02 17:52:28 +00001604 mangleUnqualifiedBlock(BD);
1605 } else {
1606 const NamedDecl *ND = cast<NamedDecl>(D);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001607 mangleNestedName(ND, getEffectiveDeclContext(ND), AdditionalAbiTags,
1608 true /*NoFunction*/);
Eli Friedman95f50122013-07-02 17:52:28 +00001609 }
Eli Friedman0cd23352013-07-10 01:33:19 +00001610 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1611 // Mangle a block in a default parameter; see above explanation for
1612 // lambdas.
1613 if (const ParmVarDecl *Parm
1614 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) {
1615 if (const FunctionDecl *Func
1616 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1617 Out << 'd';
1618 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1619 if (Num > 1)
1620 mangleNumber(Num - 2);
1621 Out << '_';
1622 }
1623 }
1624
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001625 assert(!AdditionalAbiTags && "Block cannot have additional abi tags");
Eli Friedman0cd23352013-07-10 01:33:19 +00001626 mangleUnqualifiedBlock(BD);
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001627 } else {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001628 mangleUnqualifiedName(cast<NamedDecl>(D), AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001629 }
Eli Friedman0cd23352013-07-10 01:33:19 +00001630
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001631 if (const NamedDecl *ND = dyn_cast<NamedDecl>(RD ? RD : D)) {
1632 unsigned disc;
1633 if (Context.getNextDiscriminator(ND, disc)) {
1634 if (disc < 10)
1635 Out << '_' << disc;
1636 else
1637 Out << "__" << disc << '_';
1638 }
1639 }
Eli Friedman95f50122013-07-02 17:52:28 +00001640}
1641
1642void CXXNameMangler::mangleBlockForPrefix(const BlockDecl *Block) {
1643 if (GetLocalClassDecl(Block)) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001644 mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
Eli Friedman95f50122013-07-02 17:52:28 +00001645 return;
1646 }
1647 const DeclContext *DC = getEffectiveDeclContext(Block);
1648 if (isLocalContainerContext(DC)) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001649 mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
Eli Friedman95f50122013-07-02 17:52:28 +00001650 return;
1651 }
1652 manglePrefix(getEffectiveDeclContext(Block));
1653 mangleUnqualifiedBlock(Block);
1654}
1655
1656void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) {
1657 if (Decl *Context = Block->getBlockManglingContextDecl()) {
1658 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1659 Context->getDeclContext()->isRecord()) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001660 const auto *ND = cast<NamedDecl>(Context);
1661 if (ND->getIdentifier()) {
1662 mangleSourceNameWithAbiTags(ND);
1663 Out << 'M';
Eli Friedman95f50122013-07-02 17:52:28 +00001664 }
1665 }
1666 }
1667
1668 // If we have a block mangling number, use it.
1669 unsigned Number = Block->getBlockManglingNumber();
1670 // Otherwise, just make up a number. It doesn't matter what it is because
1671 // the symbol in question isn't externally visible.
1672 if (!Number)
1673 Number = Context.getBlockId(Block, false);
Richard Smith48b35d92017-09-07 05:41:24 +00001674 else {
1675 // Stored mangling numbers are 1-based.
1676 --Number;
1677 }
Eli Friedman95f50122013-07-02 17:52:28 +00001678 Out << "Ub";
David Majnemer11d24272014-08-04 06:16:50 +00001679 if (Number > 0)
1680 Out << Number - 1;
Eli Friedman95f50122013-07-02 17:52:28 +00001681 Out << '_';
Guy Benyei11169dd2012-12-18 14:30:41 +00001682}
1683
Hamza Sood8205a812019-05-04 10:49:46 +00001684// <template-param-decl>
1685// ::= Ty # template type parameter
1686// ::= Tn <type> # template non-type parameter
1687// ::= Tt <template-param-decl>* E # template template parameter
1688void CXXNameMangler::mangleTemplateParamDecl(const NamedDecl *Decl) {
1689 if (isa<TemplateTypeParmDecl>(Decl)) {
1690 Out << "Ty";
1691 } else if (auto *Tn = dyn_cast<NonTypeTemplateParmDecl>(Decl)) {
1692 Out << "Tn";
1693 mangleType(Tn->getType());
1694 } else if (auto *Tt = dyn_cast<TemplateTemplateParmDecl>(Decl)) {
1695 Out << "Tt";
1696 for (auto *Param : *Tt->getTemplateParameters())
1697 mangleTemplateParamDecl(Param);
1698 Out << "E";
1699 }
1700}
1701
Guy Benyei11169dd2012-12-18 14:30:41 +00001702void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001703 // If the context of a closure type is an initializer for a class member
1704 // (static or nonstatic), it is encoded in a qualified name with a final
Guy Benyei11169dd2012-12-18 14:30:41 +00001705 // <prefix> of the form:
1706 //
1707 // <data-member-prefix> := <member source-name> M
1708 //
1709 // Technically, the data-member-prefix is part of the <prefix>. However,
1710 // since a closure type will always be mangled with a prefix, it's easier
1711 // to emit that last part of the prefix here.
1712 if (Decl *Context = Lambda->getLambdaContextDecl()) {
1713 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
Richard Smithc95d2c52017-09-22 04:25:05 +00001714 !isa<ParmVarDecl>(Context)) {
1715 // FIXME: 'inline auto [a, b] = []{ return ... };' does not get a
1716 // reasonable mangling here.
Guy Benyei11169dd2012-12-18 14:30:41 +00001717 if (const IdentifierInfo *Name
1718 = cast<NamedDecl>(Context)->getIdentifier()) {
1719 mangleSourceName(Name);
Richard Smithc95d2c52017-09-22 04:25:05 +00001720 const TemplateArgumentList *TemplateArgs = nullptr;
Simon Pilgrimb2eda762017-09-22 16:26:17 +00001721 if (isTemplate(cast<NamedDecl>(Context), TemplateArgs))
Richard Smithc95d2c52017-09-22 04:25:05 +00001722 mangleTemplateArgs(*TemplateArgs);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001723 Out << 'M';
Guy Benyei11169dd2012-12-18 14:30:41 +00001724 }
1725 }
1726 }
1727
1728 Out << "Ul";
Hamza Sood8205a812019-05-04 10:49:46 +00001729 for (auto *D : Lambda->getLambdaExplicitTemplateParameters())
1730 mangleTemplateParamDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00001731 const FunctionProtoType *Proto = Lambda->getLambdaTypeInfo()->getType()->
1732 getAs<FunctionProtoType>();
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001733 mangleBareFunctionType(Proto, /*MangleReturnType=*/false,
1734 Lambda->getLambdaStaticInvoker());
Guy Benyei11169dd2012-12-18 14:30:41 +00001735 Out << "E";
Fangrui Song6907ce22018-07-30 19:24:48 +00001736
1737 // The number is omitted for the first closure type with a given
1738 // <lambda-sig> in a given context; it is n-2 for the nth closure type
Guy Benyei11169dd2012-12-18 14:30:41 +00001739 // (in lexical order) with that same <lambda-sig> and context.
1740 //
1741 // The AST keeps track of the number for us.
1742 unsigned Number = Lambda->getLambdaManglingNumber();
1743 assert(Number > 0 && "Lambda should be mangled as an unnamed class");
1744 if (Number > 1)
1745 mangleNumber(Number - 2);
Fangrui Song6907ce22018-07-30 19:24:48 +00001746 Out << '_';
Guy Benyei11169dd2012-12-18 14:30:41 +00001747}
1748
1749void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) {
1750 switch (qualifier->getKind()) {
1751 case NestedNameSpecifier::Global:
1752 // nothing
1753 return;
1754
Nikola Smiljanic67860242014-09-26 00:28:20 +00001755 case NestedNameSpecifier::Super:
1756 llvm_unreachable("Can't mangle __super specifier");
1757
Guy Benyei11169dd2012-12-18 14:30:41 +00001758 case NestedNameSpecifier::Namespace:
1759 mangleName(qualifier->getAsNamespace());
1760 return;
1761
1762 case NestedNameSpecifier::NamespaceAlias:
1763 mangleName(qualifier->getAsNamespaceAlias()->getNamespace());
1764 return;
1765
1766 case NestedNameSpecifier::TypeSpec:
1767 case NestedNameSpecifier::TypeSpecWithTemplate:
1768 manglePrefix(QualType(qualifier->getAsType(), 0));
1769 return;
1770
1771 case NestedNameSpecifier::Identifier:
1772 // Member expressions can have these without prefixes, but that
1773 // should end up in mangleUnresolvedPrefix instead.
1774 assert(qualifier->getPrefix());
1775 manglePrefix(qualifier->getPrefix());
1776
1777 mangleSourceName(qualifier->getAsIdentifier());
1778 return;
1779 }
1780
1781 llvm_unreachable("unexpected nested name specifier");
1782}
1783
1784void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) {
1785 // <prefix> ::= <prefix> <unqualified-name>
1786 // ::= <template-prefix> <template-args>
1787 // ::= <template-param>
1788 // ::= # empty
1789 // ::= <substitution>
1790
1791 DC = IgnoreLinkageSpecDecls(DC);
1792
1793 if (DC->isTranslationUnit())
1794 return;
1795
Eli Friedman95f50122013-07-02 17:52:28 +00001796 if (NoFunction && isLocalContainerContext(DC))
1797 return;
Eli Friedman7e346a82013-07-01 20:22:57 +00001798
Eli Friedman95f50122013-07-02 17:52:28 +00001799 assert(!isLocalContainerContext(DC));
1800
Fangrui Song6907ce22018-07-30 19:24:48 +00001801 const NamedDecl *ND = cast<NamedDecl>(DC);
Guy Benyei11169dd2012-12-18 14:30:41 +00001802 if (mangleSubstitution(ND))
1803 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00001804
Guy Benyei11169dd2012-12-18 14:30:41 +00001805 // Check if we have a template.
Craig Topper36250ad2014-05-12 05:36:57 +00001806 const TemplateArgumentList *TemplateArgs = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001807 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
1808 mangleTemplatePrefix(TD);
1809 mangleTemplateArgs(*TemplateArgs);
Eli Friedman95f50122013-07-02 17:52:28 +00001810 } else {
Guy Benyei11169dd2012-12-18 14:30:41 +00001811 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001812 mangleUnqualifiedName(ND, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001813 }
1814
1815 addSubstitution(ND);
1816}
1817
1818void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) {
1819 // <template-prefix> ::= <prefix> <template unqualified-name>
1820 // ::= <template-param>
1821 // ::= <substitution>
1822 if (TemplateDecl *TD = Template.getAsTemplateDecl())
1823 return mangleTemplatePrefix(TD);
1824
1825 if (QualifiedTemplateName *Qualified = Template.getAsQualifiedTemplateName())
1826 manglePrefix(Qualified->getQualifier());
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001827
Guy Benyei11169dd2012-12-18 14:30:41 +00001828 if (OverloadedTemplateStorage *Overloaded
1829 = Template.getAsOverloadedTemplate()) {
Craig Topper36250ad2014-05-12 05:36:57 +00001830 mangleUnqualifiedName(nullptr, (*Overloaded->begin())->getDeclName(),
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001831 UnknownArity, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001832 return;
1833 }
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001834
Guy Benyei11169dd2012-12-18 14:30:41 +00001835 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
1836 assert(Dependent && "Unknown template name kind?");
David Majnemer1dabfdc2015-02-14 13:23:54 +00001837 if (NestedNameSpecifier *Qualifier = Dependent->getQualifier())
1838 manglePrefix(Qualifier);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001839 mangleUnscopedTemplateName(Template, /* AdditionalAbiTags */ nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001840}
1841
Eli Friedman86af13f02013-07-05 18:41:30 +00001842void CXXNameMangler::mangleTemplatePrefix(const TemplateDecl *ND,
1843 bool NoFunction) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001844 // <template-prefix> ::= <prefix> <template unqualified-name>
1845 // ::= <template-param>
1846 // ::= <substitution>
1847 // <template-template-param> ::= <template-param>
1848 // <substitution>
1849
1850 if (mangleSubstitution(ND))
1851 return;
1852
1853 // <template-template-param> ::= <template-param>
David Majnemer90a3b192014-10-24 20:22:57 +00001854 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001855 mangleTemplateParameter(TTP->getIndex());
David Majnemer90a3b192014-10-24 20:22:57 +00001856 } else {
1857 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
David Majnemer6d2b60a2016-07-12 16:48:17 +00001858 if (isa<BuiltinTemplateDecl>(ND))
1859 mangleUnqualifiedName(ND, nullptr);
1860 else
1861 mangleUnqualifiedName(ND->getTemplatedDecl(), nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001862 }
1863
Guy Benyei11169dd2012-12-18 14:30:41 +00001864 addSubstitution(ND);
1865}
1866
1867/// Mangles a template name under the production <type>. Required for
1868/// template template arguments.
1869/// <type> ::= <class-enum-type>
1870/// ::= <template-param>
1871/// ::= <substitution>
1872void CXXNameMangler::mangleType(TemplateName TN) {
1873 if (mangleSubstitution(TN))
1874 return;
Craig Topper36250ad2014-05-12 05:36:57 +00001875
1876 TemplateDecl *TD = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001877
1878 switch (TN.getKind()) {
1879 case TemplateName::QualifiedTemplate:
1880 TD = TN.getAsQualifiedTemplateName()->getTemplateDecl();
1881 goto HaveDecl;
1882
1883 case TemplateName::Template:
1884 TD = TN.getAsTemplateDecl();
1885 goto HaveDecl;
1886
1887 HaveDecl:
1888 if (isa<TemplateTemplateParmDecl>(TD))
1889 mangleTemplateParameter(cast<TemplateTemplateParmDecl>(TD)->getIndex());
1890 else
1891 mangleName(TD);
1892 break;
1893
1894 case TemplateName::OverloadedTemplate:
Richard Smithb23c5e82019-05-09 03:31:27 +00001895 case TemplateName::AssumedTemplate:
Guy Benyei11169dd2012-12-18 14:30:41 +00001896 llvm_unreachable("can't mangle an overloaded template name as a <type>");
1897
1898 case TemplateName::DependentTemplate: {
1899 const DependentTemplateName *Dependent = TN.getAsDependentTemplateName();
1900 assert(Dependent->isIdentifier());
1901
1902 // <class-enum-type> ::= <name>
1903 // <name> ::= <nested-name>
David Majnemercb34c672015-02-19 05:51:14 +00001904 mangleUnresolvedPrefix(Dependent->getQualifier());
Guy Benyei11169dd2012-12-18 14:30:41 +00001905 mangleSourceName(Dependent->getIdentifier());
1906 break;
1907 }
1908
1909 case TemplateName::SubstTemplateTemplateParm: {
1910 // Substituted template parameters are mangled as the substituted
1911 // template. This will check for the substitution twice, which is
1912 // fine, but we have to return early so that we don't try to *add*
1913 // the substitution twice.
1914 SubstTemplateTemplateParmStorage *subst
1915 = TN.getAsSubstTemplateTemplateParm();
1916 mangleType(subst->getReplacement());
1917 return;
1918 }
1919
1920 case TemplateName::SubstTemplateTemplateParmPack: {
1921 // FIXME: not clear how to mangle this!
1922 // template <template <class> class T...> class A {
1923 // template <template <class> class U...> void foo(B<T,U> x...);
1924 // };
1925 Out << "_SUBSTPACK_";
1926 break;
1927 }
1928 }
1929
1930 addSubstitution(TN);
1931}
1932
David Majnemerb8014dd2015-02-19 02:16:16 +00001933bool CXXNameMangler::mangleUnresolvedTypeOrSimpleId(QualType Ty,
1934 StringRef Prefix) {
1935 // Only certain other types are valid as prefixes; enumerate them.
1936 switch (Ty->getTypeClass()) {
1937 case Type::Builtin:
1938 case Type::Complex:
1939 case Type::Adjusted:
1940 case Type::Decayed:
1941 case Type::Pointer:
1942 case Type::BlockPointer:
1943 case Type::LValueReference:
1944 case Type::RValueReference:
1945 case Type::MemberPointer:
1946 case Type::ConstantArray:
1947 case Type::IncompleteArray:
1948 case Type::VariableArray:
1949 case Type::DependentSizedArray:
Andrew Gozillon572bbb02017-10-02 06:25:51 +00001950 case Type::DependentAddressSpace:
Erich Keanef702b022018-07-13 19:46:04 +00001951 case Type::DependentVector:
David Majnemerb8014dd2015-02-19 02:16:16 +00001952 case Type::DependentSizedExtVector:
1953 case Type::Vector:
1954 case Type::ExtVector:
1955 case Type::FunctionProto:
1956 case Type::FunctionNoProto:
1957 case Type::Paren:
1958 case Type::Attributed:
1959 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00001960 case Type::DeducedTemplateSpecialization:
David Majnemerb8014dd2015-02-19 02:16:16 +00001961 case Type::PackExpansion:
1962 case Type::ObjCObject:
1963 case Type::ObjCInterface:
1964 case Type::ObjCObjectPointer:
Manman Rene6be26c2016-09-13 17:25:08 +00001965 case Type::ObjCTypeParam:
David Majnemerb8014dd2015-02-19 02:16:16 +00001966 case Type::Atomic:
Xiuli Pan9c14e282016-01-09 12:53:17 +00001967 case Type::Pipe:
Leonard Chanc72aaf62019-05-07 03:20:17 +00001968 case Type::MacroQualified:
David Majnemerb8014dd2015-02-19 02:16:16 +00001969 llvm_unreachable("type is illegal as a nested name specifier");
1970
1971 case Type::SubstTemplateTypeParmPack:
1972 // FIXME: not clear how to mangle this!
1973 // template <class T...> class A {
1974 // template <class U...> void foo(decltype(T::foo(U())) x...);
1975 // };
1976 Out << "_SUBSTPACK_";
1977 break;
1978
1979 // <unresolved-type> ::= <template-param>
1980 // ::= <decltype>
1981 // ::= <template-template-param> <template-args>
1982 // (this last is not official yet)
1983 case Type::TypeOfExpr:
1984 case Type::TypeOf:
1985 case Type::Decltype:
1986 case Type::TemplateTypeParm:
1987 case Type::UnaryTransform:
1988 case Type::SubstTemplateTypeParm:
1989 unresolvedType:
1990 // Some callers want a prefix before the mangled type.
1991 Out << Prefix;
1992
1993 // This seems to do everything we want. It's not really
1994 // sanctioned for a substituted template parameter, though.
1995 mangleType(Ty);
1996
1997 // We never want to print 'E' directly after an unresolved-type,
1998 // so we return directly.
1999 return true;
2000
2001 case Type::Typedef:
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00002002 mangleSourceNameWithAbiTags(cast<TypedefType>(Ty)->getDecl());
David Majnemerb8014dd2015-02-19 02:16:16 +00002003 break;
2004
2005 case Type::UnresolvedUsing:
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00002006 mangleSourceNameWithAbiTags(
2007 cast<UnresolvedUsingType>(Ty)->getDecl());
David Majnemerb8014dd2015-02-19 02:16:16 +00002008 break;
2009
2010 case Type::Enum:
2011 case Type::Record:
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00002012 mangleSourceNameWithAbiTags(cast<TagType>(Ty)->getDecl());
David Majnemerb8014dd2015-02-19 02:16:16 +00002013 break;
2014
2015 case Type::TemplateSpecialization: {
2016 const TemplateSpecializationType *TST =
2017 cast<TemplateSpecializationType>(Ty);
David Majnemera88b3592015-02-18 02:28:01 +00002018 TemplateName TN = TST->getTemplateName();
David Majnemerb8014dd2015-02-19 02:16:16 +00002019 switch (TN.getKind()) {
2020 case TemplateName::Template:
2021 case TemplateName::QualifiedTemplate: {
2022 TemplateDecl *TD = TN.getAsTemplateDecl();
2023
2024 // If the base is a template template parameter, this is an
2025 // unresolved type.
2026 assert(TD && "no template for template specialization type");
2027 if (isa<TemplateTemplateParmDecl>(TD))
2028 goto unresolvedType;
2029
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00002030 mangleSourceNameWithAbiTags(TD);
David Majnemerb8014dd2015-02-19 02:16:16 +00002031 break;
David Majnemera88b3592015-02-18 02:28:01 +00002032 }
David Majnemerb8014dd2015-02-19 02:16:16 +00002033
2034 case TemplateName::OverloadedTemplate:
Richard Smithb23c5e82019-05-09 03:31:27 +00002035 case TemplateName::AssumedTemplate:
David Majnemerb8014dd2015-02-19 02:16:16 +00002036 case TemplateName::DependentTemplate:
2037 llvm_unreachable("invalid base for a template specialization type");
2038
2039 case TemplateName::SubstTemplateTemplateParm: {
2040 SubstTemplateTemplateParmStorage *subst =
2041 TN.getAsSubstTemplateTemplateParm();
2042 mangleExistingSubstitution(subst->getReplacement());
2043 break;
2044 }
2045
2046 case TemplateName::SubstTemplateTemplateParmPack: {
2047 // FIXME: not clear how to mangle this!
2048 // template <template <class U> class T...> class A {
2049 // template <class U...> void foo(decltype(T<U>::foo) x...);
2050 // };
2051 Out << "_SUBSTPACK_";
2052 break;
2053 }
2054 }
2055
David Majnemera88b3592015-02-18 02:28:01 +00002056 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
David Majnemerb8014dd2015-02-19 02:16:16 +00002057 break;
David Majnemera88b3592015-02-18 02:28:01 +00002058 }
David Majnemerb8014dd2015-02-19 02:16:16 +00002059
2060 case Type::InjectedClassName:
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00002061 mangleSourceNameWithAbiTags(
2062 cast<InjectedClassNameType>(Ty)->getDecl());
David Majnemerb8014dd2015-02-19 02:16:16 +00002063 break;
2064
2065 case Type::DependentName:
2066 mangleSourceName(cast<DependentNameType>(Ty)->getIdentifier());
2067 break;
2068
2069 case Type::DependentTemplateSpecialization: {
2070 const DependentTemplateSpecializationType *DTST =
2071 cast<DependentTemplateSpecializationType>(Ty);
2072 mangleSourceName(DTST->getIdentifier());
2073 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
2074 break;
2075 }
2076
2077 case Type::Elaborated:
2078 return mangleUnresolvedTypeOrSimpleId(
2079 cast<ElaboratedType>(Ty)->getNamedType(), Prefix);
2080 }
2081
2082 return false;
David Majnemera88b3592015-02-18 02:28:01 +00002083}
2084
2085void CXXNameMangler::mangleOperatorName(DeclarationName Name, unsigned Arity) {
2086 switch (Name.getNameKind()) {
2087 case DeclarationName::CXXConstructorName:
2088 case DeclarationName::CXXDestructorName:
Richard Smith35845152017-02-07 01:37:30 +00002089 case DeclarationName::CXXDeductionGuideName:
David Majnemera88b3592015-02-18 02:28:01 +00002090 case DeclarationName::CXXUsingDirective:
2091 case DeclarationName::Identifier:
2092 case DeclarationName::ObjCMultiArgSelector:
2093 case DeclarationName::ObjCOneArgSelector:
2094 case DeclarationName::ObjCZeroArgSelector:
2095 llvm_unreachable("Not an operator name");
2096
2097 case DeclarationName::CXXConversionFunctionName:
2098 // <operator-name> ::= cv <type> # (cast)
2099 Out << "cv";
2100 mangleType(Name.getCXXNameType());
2101 break;
2102
2103 case DeclarationName::CXXLiteralOperatorName:
2104 Out << "li";
2105 mangleSourceName(Name.getCXXLiteralIdentifier());
2106 return;
2107
2108 case DeclarationName::CXXOperatorName:
2109 mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);
2110 break;
2111 }
2112}
2113
Guy Benyei11169dd2012-12-18 14:30:41 +00002114void
2115CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
2116 switch (OO) {
2117 // <operator-name> ::= nw # new
2118 case OO_New: Out << "nw"; break;
2119 // ::= na # new[]
2120 case OO_Array_New: Out << "na"; break;
2121 // ::= dl # delete
2122 case OO_Delete: Out << "dl"; break;
2123 // ::= da # delete[]
2124 case OO_Array_Delete: Out << "da"; break;
2125 // ::= ps # + (unary)
2126 // ::= pl # + (binary or unknown)
2127 case OO_Plus:
2128 Out << (Arity == 1? "ps" : "pl"); break;
2129 // ::= ng # - (unary)
2130 // ::= mi # - (binary or unknown)
2131 case OO_Minus:
2132 Out << (Arity == 1? "ng" : "mi"); break;
2133 // ::= ad # & (unary)
2134 // ::= an # & (binary or unknown)
2135 case OO_Amp:
2136 Out << (Arity == 1? "ad" : "an"); break;
2137 // ::= de # * (unary)
2138 // ::= ml # * (binary or unknown)
2139 case OO_Star:
2140 // Use binary when unknown.
2141 Out << (Arity == 1? "de" : "ml"); break;
2142 // ::= co # ~
2143 case OO_Tilde: Out << "co"; break;
2144 // ::= dv # /
2145 case OO_Slash: Out << "dv"; break;
2146 // ::= rm # %
2147 case OO_Percent: Out << "rm"; break;
2148 // ::= or # |
2149 case OO_Pipe: Out << "or"; break;
2150 // ::= eo # ^
2151 case OO_Caret: Out << "eo"; break;
2152 // ::= aS # =
2153 case OO_Equal: Out << "aS"; break;
2154 // ::= pL # +=
2155 case OO_PlusEqual: Out << "pL"; break;
2156 // ::= mI # -=
2157 case OO_MinusEqual: Out << "mI"; break;
2158 // ::= mL # *=
2159 case OO_StarEqual: Out << "mL"; break;
2160 // ::= dV # /=
2161 case OO_SlashEqual: Out << "dV"; break;
2162 // ::= rM # %=
2163 case OO_PercentEqual: Out << "rM"; break;
2164 // ::= aN # &=
2165 case OO_AmpEqual: Out << "aN"; break;
2166 // ::= oR # |=
2167 case OO_PipeEqual: Out << "oR"; break;
2168 // ::= eO # ^=
2169 case OO_CaretEqual: Out << "eO"; break;
2170 // ::= ls # <<
2171 case OO_LessLess: Out << "ls"; break;
2172 // ::= rs # >>
2173 case OO_GreaterGreater: Out << "rs"; break;
2174 // ::= lS # <<=
2175 case OO_LessLessEqual: Out << "lS"; break;
2176 // ::= rS # >>=
2177 case OO_GreaterGreaterEqual: Out << "rS"; break;
2178 // ::= eq # ==
2179 case OO_EqualEqual: Out << "eq"; break;
2180 // ::= ne # !=
2181 case OO_ExclaimEqual: Out << "ne"; break;
2182 // ::= lt # <
2183 case OO_Less: Out << "lt"; break;
2184 // ::= gt # >
2185 case OO_Greater: Out << "gt"; break;
2186 // ::= le # <=
2187 case OO_LessEqual: Out << "le"; break;
2188 // ::= ge # >=
2189 case OO_GreaterEqual: Out << "ge"; break;
2190 // ::= nt # !
2191 case OO_Exclaim: Out << "nt"; break;
2192 // ::= aa # &&
2193 case OO_AmpAmp: Out << "aa"; break;
2194 // ::= oo # ||
2195 case OO_PipePipe: Out << "oo"; break;
2196 // ::= pp # ++
2197 case OO_PlusPlus: Out << "pp"; break;
2198 // ::= mm # --
2199 case OO_MinusMinus: Out << "mm"; break;
2200 // ::= cm # ,
2201 case OO_Comma: Out << "cm"; break;
2202 // ::= pm # ->*
2203 case OO_ArrowStar: Out << "pm"; break;
2204 // ::= pt # ->
2205 case OO_Arrow: Out << "pt"; break;
2206 // ::= cl # ()
2207 case OO_Call: Out << "cl"; break;
2208 // ::= ix # []
2209 case OO_Subscript: Out << "ix"; break;
2210
2211 // ::= qu # ?
2212 // The conditional operator can't be overloaded, but we still handle it when
2213 // mangling expressions.
2214 case OO_Conditional: Out << "qu"; break;
Richard Smith9be594e2015-10-22 05:12:22 +00002215 // Proposal on cxx-abi-dev, 2015-10-21.
2216 // ::= aw # co_await
2217 case OO_Coawait: Out << "aw"; break;
Richard Smithd30b23d2017-12-01 02:13:10 +00002218 // Proposed in cxx-abi github issue 43.
2219 // ::= ss # <=>
2220 case OO_Spaceship: Out << "ss"; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002221
2222 case OO_None:
2223 case NUM_OVERLOADED_OPERATORS:
2224 llvm_unreachable("Not an overloaded operator");
2225 }
2226}
2227
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002228void CXXNameMangler::mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST) {
Roger Ferrer Ibanezfd9384a2017-06-02 07:14:34 +00002229 // Vendor qualifiers come first and if they are order-insensitive they must
2230 // be emitted in reversed alphabetical order, see Itanium ABI 5.1.5.
Guy Benyei11169dd2012-12-18 14:30:41 +00002231
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002232 // <type> ::= U <addrspace-expr>
2233 if (DAST) {
2234 Out << "U2ASI";
2235 mangleExpression(DAST->getAddrSpaceExpr());
2236 Out << "E";
2237 }
2238
John McCall07daf722016-03-01 22:18:03 +00002239 // Address space qualifiers start with an ordinary letter.
Guy Benyei11169dd2012-12-18 14:30:41 +00002240 if (Quals.hasAddressSpace()) {
David Tweed31d09b02013-09-13 12:04:22 +00002241 // Address space extension:
Guy Benyei11169dd2012-12-18 14:30:41 +00002242 //
David Tweed31d09b02013-09-13 12:04:22 +00002243 // <type> ::= U <target-addrspace>
2244 // <type> ::= U <OpenCL-addrspace>
2245 // <type> ::= U <CUDA-addrspace>
2246
Guy Benyei11169dd2012-12-18 14:30:41 +00002247 SmallString<64> ASString;
Alexander Richardson6d989432017-10-15 18:48:14 +00002248 LangAS AS = Quals.getAddressSpace();
David Tweed31d09b02013-09-13 12:04:22 +00002249
2250 if (Context.getASTContext().addressSpaceMapManglingFor(AS)) {
2251 // <target-addrspace> ::= "AS" <address-space-number>
2252 unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS);
Yaxun Liub7318e02017-10-13 03:37:48 +00002253 if (TargetAS != 0)
2254 ASString = "AS" + llvm::utostr(TargetAS);
David Tweed31d09b02013-09-13 12:04:22 +00002255 } else {
2256 switch (AS) {
2257 default: llvm_unreachable("Not a language specific address space");
Yaxun Liub7318e02017-10-13 03:37:48 +00002258 // <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" |
2259 // "private"| "generic" ]
David Tweed31d09b02013-09-13 12:04:22 +00002260 case LangAS::opencl_global: ASString = "CLglobal"; break;
2261 case LangAS::opencl_local: ASString = "CLlocal"; break;
2262 case LangAS::opencl_constant: ASString = "CLconstant"; break;
Yaxun Liub7318e02017-10-13 03:37:48 +00002263 case LangAS::opencl_private: ASString = "CLprivate"; break;
Anastasia Stulova81a25e352017-03-10 15:23:07 +00002264 case LangAS::opencl_generic: ASString = "CLgeneric"; break;
David Tweed31d09b02013-09-13 12:04:22 +00002265 // <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]
2266 case LangAS::cuda_device: ASString = "CUdevice"; break;
2267 case LangAS::cuda_constant: ASString = "CUconstant"; break;
2268 case LangAS::cuda_shared: ASString = "CUshared"; break;
2269 }
2270 }
Yaxun Liub7318e02017-10-13 03:37:48 +00002271 if (!ASString.empty())
2272 mangleVendorQualifier(ASString);
Guy Benyei11169dd2012-12-18 14:30:41 +00002273 }
John McCall07daf722016-03-01 22:18:03 +00002274
2275 // The ARC ownership qualifiers start with underscores.
Guy Benyei11169dd2012-12-18 14:30:41 +00002276 // Objective-C ARC Extension:
2277 //
2278 // <type> ::= U "__strong"
2279 // <type> ::= U "__weak"
2280 // <type> ::= U "__autoreleasing"
Roger Ferrer Ibanezfd9384a2017-06-02 07:14:34 +00002281 //
2282 // Note: we emit __weak first to preserve the order as
2283 // required by the Itanium ABI.
2284 if (Quals.getObjCLifetime() == Qualifiers::OCL_Weak)
2285 mangleVendorQualifier("__weak");
2286
2287 // __unaligned (from -fms-extensions)
2288 if (Quals.hasUnaligned())
2289 mangleVendorQualifier("__unaligned");
2290
2291 // Remaining ARC ownership qualifiers.
2292 switch (Quals.getObjCLifetime()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002293 case Qualifiers::OCL_None:
2294 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002295
Guy Benyei11169dd2012-12-18 14:30:41 +00002296 case Qualifiers::OCL_Weak:
Roger Ferrer Ibanezfd9384a2017-06-02 07:14:34 +00002297 // Do nothing as we already handled this case above.
Guy Benyei11169dd2012-12-18 14:30:41 +00002298 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002299
Guy Benyei11169dd2012-12-18 14:30:41 +00002300 case Qualifiers::OCL_Strong:
John McCall07daf722016-03-01 22:18:03 +00002301 mangleVendorQualifier("__strong");
Guy Benyei11169dd2012-12-18 14:30:41 +00002302 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002303
Guy Benyei11169dd2012-12-18 14:30:41 +00002304 case Qualifiers::OCL_Autoreleasing:
John McCall07daf722016-03-01 22:18:03 +00002305 mangleVendorQualifier("__autoreleasing");
Guy Benyei11169dd2012-12-18 14:30:41 +00002306 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002307
Guy Benyei11169dd2012-12-18 14:30:41 +00002308 case Qualifiers::OCL_ExplicitNone:
2309 // The __unsafe_unretained qualifier is *not* mangled, so that
2310 // __unsafe_unretained types in ARC produce the same manglings as the
2311 // equivalent (but, naturally, unqualified) types in non-ARC, providing
2312 // better ABI compatibility.
2313 //
2314 // It's safe to do this because unqualified 'id' won't show up
2315 // in any type signatures that need to be mangled.
2316 break;
2317 }
John McCall07daf722016-03-01 22:18:03 +00002318
2319 // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const
2320 if (Quals.hasRestrict())
2321 Out << 'r';
2322 if (Quals.hasVolatile())
2323 Out << 'V';
2324 if (Quals.hasConst())
2325 Out << 'K';
2326}
2327
2328void CXXNameMangler::mangleVendorQualifier(StringRef name) {
2329 Out << 'U' << name.size() << name;
Guy Benyei11169dd2012-12-18 14:30:41 +00002330}
2331
2332void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
2333 // <ref-qualifier> ::= R # lvalue reference
2334 // ::= O # rvalue-reference
Guy Benyei11169dd2012-12-18 14:30:41 +00002335 switch (RefQualifier) {
2336 case RQ_None:
2337 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002338
Guy Benyei11169dd2012-12-18 14:30:41 +00002339 case RQ_LValue:
2340 Out << 'R';
2341 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002342
Guy Benyei11169dd2012-12-18 14:30:41 +00002343 case RQ_RValue:
2344 Out << 'O';
2345 break;
2346 }
2347}
2348
2349void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
2350 Context.mangleObjCMethodName(MD, Out);
2351}
2352
Erik Pilkingtone7e87722018-04-28 02:40:28 +00002353static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty,
2354 ASTContext &Ctx) {
David Majnemereea02ee2014-11-28 22:22:46 +00002355 if (Quals)
2356 return true;
2357 if (Ty->isSpecificBuiltinType(BuiltinType::ObjCSel))
2358 return true;
2359 if (Ty->isOpenCLSpecificType())
2360 return true;
2361 if (Ty->isBuiltinType())
2362 return false;
Erik Pilkingtone7e87722018-04-28 02:40:28 +00002363 // Through to Clang 6.0, we accidentally treated undeduced auto types as
2364 // substitution candidates.
2365 if (Ctx.getLangOpts().getClangABICompat() > LangOptions::ClangABI::Ver6 &&
2366 isa<AutoType>(Ty))
2367 return false;
David Majnemereea02ee2014-11-28 22:22:46 +00002368 return true;
2369}
2370
Guy Benyei11169dd2012-12-18 14:30:41 +00002371void CXXNameMangler::mangleType(QualType T) {
2372 // If our type is instantiation-dependent but not dependent, we mangle
Fangrui Song6907ce22018-07-30 19:24:48 +00002373 // it as it was written in the source, removing any top-level sugar.
Guy Benyei11169dd2012-12-18 14:30:41 +00002374 // Otherwise, use the canonical type.
2375 //
Fangrui Song6907ce22018-07-30 19:24:48 +00002376 // FIXME: This is an approximation of the instantiation-dependent name
Guy Benyei11169dd2012-12-18 14:30:41 +00002377 // mangling rules, since we should really be using the type as written and
2378 // augmented via semantic analysis (i.e., with implicit conversions and
Fangrui Song6907ce22018-07-30 19:24:48 +00002379 // default template arguments) for any instantiation-dependent type.
Guy Benyei11169dd2012-12-18 14:30:41 +00002380 // Unfortunately, that requires several changes to our AST:
Fangrui Song6907ce22018-07-30 19:24:48 +00002381 // - Instantiation-dependent TemplateSpecializationTypes will need to be
Guy Benyei11169dd2012-12-18 14:30:41 +00002382 // uniqued, so that we can handle substitutions properly
2383 // - Default template arguments will need to be represented in the
2384 // TemplateSpecializationType, since they need to be mangled even though
2385 // they aren't written.
2386 // - Conversions on non-type template arguments need to be expressed, since
2387 // they can affect the mangling of sizeof/alignof.
Richard Smithfda59e52016-10-26 01:05:54 +00002388 //
2389 // FIXME: This is wrong when mapping to the canonical type for a dependent
2390 // type discards instantiation-dependent portions of the type, such as for:
2391 //
2392 // template<typename T, int N> void f(T (&)[sizeof(N)]);
2393 // template<typename T> void f(T() throw(typename T::type)); (pre-C++17)
2394 //
2395 // It's also wrong in the opposite direction when instantiation-dependent,
2396 // canonically-equivalent types differ in some irrelevant portion of inner
2397 // type sugar. In such cases, we fail to form correct substitutions, eg:
2398 //
2399 // template<int N> void f(A<sizeof(N)> *, A<sizeof(N)> (*));
2400 //
2401 // We should instead canonicalize the non-instantiation-dependent parts,
2402 // regardless of whether the type as a whole is dependent or instantiation
2403 // dependent.
Guy Benyei11169dd2012-12-18 14:30:41 +00002404 if (!T->isInstantiationDependentType() || T->isDependentType())
2405 T = T.getCanonicalType();
2406 else {
2407 // Desugar any types that are purely sugar.
2408 do {
2409 // Don't desugar through template specialization types that aren't
2410 // type aliases. We need to mangle the template arguments as written.
Fangrui Song6907ce22018-07-30 19:24:48 +00002411 if (const TemplateSpecializationType *TST
Guy Benyei11169dd2012-12-18 14:30:41 +00002412 = dyn_cast<TemplateSpecializationType>(T))
2413 if (!TST->isTypeAlias())
2414 break;
2415
Fangrui Song6907ce22018-07-30 19:24:48 +00002416 QualType Desugared
Guy Benyei11169dd2012-12-18 14:30:41 +00002417 = T.getSingleStepDesugaredType(Context.getASTContext());
2418 if (Desugared == T)
2419 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002420
Guy Benyei11169dd2012-12-18 14:30:41 +00002421 T = Desugared;
2422 } while (true);
2423 }
2424 SplitQualType split = T.split();
2425 Qualifiers quals = split.Quals;
2426 const Type *ty = split.Ty;
2427
Erik Pilkingtone7e87722018-04-28 02:40:28 +00002428 bool isSubstitutable =
2429 isTypeSubstitutable(quals, ty, Context.getASTContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00002430 if (isSubstitutable && mangleSubstitution(T))
2431 return;
2432
2433 // If we're mangling a qualified array type, push the qualifiers to
2434 // the element type.
2435 if (quals && isa<ArrayType>(T)) {
2436 ty = Context.getASTContext().getAsArrayType(T);
2437 quals = Qualifiers();
2438
2439 // Note that we don't update T: we want to add the
2440 // substitution at the original type.
2441 }
2442
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002443 if (quals || ty->isDependentAddressSpaceType()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00002444 if (const DependentAddressSpaceType *DAST =
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002445 dyn_cast<DependentAddressSpaceType>(ty)) {
2446 SplitQualType splitDAST = DAST->getPointeeType().split();
2447 mangleQualifiers(splitDAST.Quals, DAST);
2448 mangleType(QualType(splitDAST.Ty, 0));
2449 } else {
2450 mangleQualifiers(quals);
2451
2452 // Recurse: even if the qualified type isn't yet substitutable,
2453 // the unqualified type might be.
2454 mangleType(QualType(ty, 0));
2455 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002456 } else {
2457 switch (ty->getTypeClass()) {
2458#define ABSTRACT_TYPE(CLASS, PARENT)
2459#define NON_CANONICAL_TYPE(CLASS, PARENT) \
2460 case Type::CLASS: \
2461 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
2462 return;
2463#define TYPE(CLASS, PARENT) \
2464 case Type::CLASS: \
2465 mangleType(static_cast<const CLASS##Type*>(ty)); \
2466 break;
2467#include "clang/AST/TypeNodes.def"
2468 }
2469 }
2470
2471 // Add the substitution.
2472 if (isSubstitutable)
2473 addSubstitution(T);
2474}
2475
2476void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) {
2477 if (!mangleStandardSubstitution(ND))
2478 mangleName(ND);
2479}
2480
2481void CXXNameMangler::mangleType(const BuiltinType *T) {
2482 // <type> ::= <builtin-type>
2483 // <builtin-type> ::= v # void
2484 // ::= w # wchar_t
2485 // ::= b # bool
2486 // ::= c # char
2487 // ::= a # signed char
2488 // ::= h # unsigned char
2489 // ::= s # short
2490 // ::= t # unsigned short
2491 // ::= i # int
2492 // ::= j # unsigned int
2493 // ::= l # long
2494 // ::= m # unsigned long
2495 // ::= x # long long, __int64
2496 // ::= y # unsigned long long, __int64
2497 // ::= n # __int128
Ekaterina Romanova91b655b2013-11-21 22:25:24 +00002498 // ::= o # unsigned __int128
Guy Benyei11169dd2012-12-18 14:30:41 +00002499 // ::= f # float
2500 // ::= d # double
2501 // ::= e # long double, __float80
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002502 // ::= g # __float128
Guy Benyei11169dd2012-12-18 14:30:41 +00002503 // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits)
2504 // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits)
2505 // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits)
2506 // ::= Dh # IEEE 754r half-precision floating point (16 bits)
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00002507 // ::= DF <number> _ # ISO/IEC TS 18661 binary floating point type _FloatN (N bits);
Guy Benyei11169dd2012-12-18 14:30:41 +00002508 // ::= Di # char32_t
2509 // ::= Ds # char16_t
2510 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
2511 // ::= u <source-name> # vendor extended type
Alexey Bader954ba212016-04-08 13:40:33 +00002512 std::string type_name;
Guy Benyei11169dd2012-12-18 14:30:41 +00002513 switch (T->getKind()) {
Alexey Baderbdf7c842015-09-15 12:18:29 +00002514 case BuiltinType::Void:
2515 Out << 'v';
2516 break;
2517 case BuiltinType::Bool:
2518 Out << 'b';
2519 break;
2520 case BuiltinType::Char_U:
2521 case BuiltinType::Char_S:
2522 Out << 'c';
2523 break;
2524 case BuiltinType::UChar:
2525 Out << 'h';
2526 break;
2527 case BuiltinType::UShort:
2528 Out << 't';
2529 break;
2530 case BuiltinType::UInt:
2531 Out << 'j';
2532 break;
2533 case BuiltinType::ULong:
2534 Out << 'm';
2535 break;
2536 case BuiltinType::ULongLong:
2537 Out << 'y';
2538 break;
2539 case BuiltinType::UInt128:
2540 Out << 'o';
2541 break;
2542 case BuiltinType::SChar:
2543 Out << 'a';
2544 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002545 case BuiltinType::WChar_S:
Alexey Baderbdf7c842015-09-15 12:18:29 +00002546 case BuiltinType::WChar_U:
2547 Out << 'w';
2548 break;
Richard Smith3a8244d2018-05-01 05:02:45 +00002549 case BuiltinType::Char8:
2550 Out << "Du";
2551 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00002552 case BuiltinType::Char16:
2553 Out << "Ds";
2554 break;
2555 case BuiltinType::Char32:
2556 Out << "Di";
2557 break;
2558 case BuiltinType::Short:
2559 Out << 's';
2560 break;
2561 case BuiltinType::Int:
2562 Out << 'i';
2563 break;
2564 case BuiltinType::Long:
2565 Out << 'l';
2566 break;
2567 case BuiltinType::LongLong:
2568 Out << 'x';
2569 break;
2570 case BuiltinType::Int128:
2571 Out << 'n';
2572 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00002573 case BuiltinType::Float16:
2574 Out << "DF16_";
2575 break;
Leonard Chanf921d852018-06-04 16:07:52 +00002576 case BuiltinType::ShortAccum:
2577 case BuiltinType::Accum:
2578 case BuiltinType::LongAccum:
2579 case BuiltinType::UShortAccum:
2580 case BuiltinType::UAccum:
2581 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00002582 case BuiltinType::ShortFract:
2583 case BuiltinType::Fract:
2584 case BuiltinType::LongFract:
2585 case BuiltinType::UShortFract:
2586 case BuiltinType::UFract:
2587 case BuiltinType::ULongFract:
2588 case BuiltinType::SatShortAccum:
2589 case BuiltinType::SatAccum:
2590 case BuiltinType::SatLongAccum:
2591 case BuiltinType::SatUShortAccum:
2592 case BuiltinType::SatUAccum:
2593 case BuiltinType::SatULongAccum:
2594 case BuiltinType::SatShortFract:
2595 case BuiltinType::SatFract:
2596 case BuiltinType::SatLongFract:
2597 case BuiltinType::SatUShortFract:
2598 case BuiltinType::SatUFract:
2599 case BuiltinType::SatULongFract:
Leonard Chanf921d852018-06-04 16:07:52 +00002600 llvm_unreachable("Fixed point types are disabled for c++");
Alexey Baderbdf7c842015-09-15 12:18:29 +00002601 case BuiltinType::Half:
2602 Out << "Dh";
2603 break;
2604 case BuiltinType::Float:
2605 Out << 'f';
2606 break;
2607 case BuiltinType::Double:
2608 Out << 'd';
2609 break;
Alexey Bataev9f3a8052019-06-18 20:29:06 +00002610 case BuiltinType::LongDouble: {
2611 bool UseFloat128Mangling =
2612 getASTContext().getTargetInfo().useFloat128ManglingForLongDouble();
2613 if (getASTContext().getLangOpts().OpenMP &&
2614 getASTContext().getLangOpts().OpenMPIsDevice) {
2615 UseFloat128Mangling = getASTContext()
2616 .getAuxTargetInfo()
2617 ->useFloat128ManglingForLongDouble();
2618 }
2619 Out << (UseFloat128Mangling ? 'g' : 'e');
David Majnemer2617ea62015-06-09 18:05:33 +00002620 break;
Alexey Bataev9f3a8052019-06-18 20:29:06 +00002621 }
2622 case BuiltinType::Float128: {
2623 bool UseFloat128Mangling =
2624 getASTContext().getTargetInfo().useFloat128ManglingForLongDouble();
2625 if (getASTContext().getLangOpts().OpenMP &&
2626 getASTContext().getLangOpts().OpenMPIsDevice) {
2627 UseFloat128Mangling = getASTContext()
2628 .getAuxTargetInfo()
2629 ->useFloat128ManglingForLongDouble();
2630 }
2631 if (UseFloat128Mangling)
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002632 Out << "U10__float128"; // Match the GCC mangling
2633 else
2634 Out << 'g';
2635 break;
Alexey Bataev9f3a8052019-06-18 20:29:06 +00002636 }
Alexey Baderbdf7c842015-09-15 12:18:29 +00002637 case BuiltinType::NullPtr:
2638 Out << "Dn";
2639 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002640
2641#define BUILTIN_TYPE(Id, SingletonId)
2642#define PLACEHOLDER_TYPE(Id, SingletonId) \
2643 case BuiltinType::Id:
2644#include "clang/AST/BuiltinTypes.def"
2645 case BuiltinType::Dependent:
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00002646 if (!NullOut)
2647 llvm_unreachable("mangling a placeholder type");
2648 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00002649 case BuiltinType::ObjCId:
2650 Out << "11objc_object";
2651 break;
2652 case BuiltinType::ObjCClass:
2653 Out << "10objc_class";
2654 break;
2655 case BuiltinType::ObjCSel:
2656 Out << "13objc_selector";
2657 break;
Alexey Bader954ba212016-04-08 13:40:33 +00002658#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2659 case BuiltinType::Id: \
2660 type_name = "ocl_" #ImgType "_" #Suffix; \
2661 Out << type_name.size() << type_name; \
Alexey Baderbdf7c842015-09-15 12:18:29 +00002662 break;
Alexey Baderb62f1442016-04-13 08:33:41 +00002663#include "clang/Basic/OpenCLImageTypes.def"
Alexey Baderbdf7c842015-09-15 12:18:29 +00002664 case BuiltinType::OCLSampler:
2665 Out << "11ocl_sampler";
2666 break;
2667 case BuiltinType::OCLEvent:
2668 Out << "9ocl_event";
2669 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00002670 case BuiltinType::OCLClkEvent:
2671 Out << "12ocl_clkevent";
2672 break;
2673 case BuiltinType::OCLQueue:
2674 Out << "9ocl_queue";
2675 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00002676 case BuiltinType::OCLReserveID:
2677 Out << "13ocl_reserveid";
2678 break;
Andrew Savonichev3fee3512018-11-08 11:25:41 +00002679#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2680 case BuiltinType::Id: \
2681 type_name = "ocl_" #ExtType; \
2682 Out << type_name.size() << type_name; \
2683 break;
2684#include "clang/Basic/OpenCLExtensionTypes.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00002685 }
2686}
2687
John McCall07daf722016-03-01 22:18:03 +00002688StringRef CXXNameMangler::getCallingConvQualifierName(CallingConv CC) {
2689 switch (CC) {
2690 case CC_C:
2691 return "";
2692
John McCall07daf722016-03-01 22:18:03 +00002693 case CC_X86VectorCall:
2694 case CC_X86Pascal:
Erich Keane757d3172016-11-02 18:29:35 +00002695 case CC_X86RegCall:
John McCall07daf722016-03-01 22:18:03 +00002696 case CC_AAPCS:
2697 case CC_AAPCS_VFP:
Sander de Smalen44a22532018-11-26 16:38:37 +00002698 case CC_AArch64VectorCall:
John McCall07daf722016-03-01 22:18:03 +00002699 case CC_IntelOclBicc:
2700 case CC_SpirFunction:
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00002701 case CC_OpenCLKernel:
Roman Levenstein35aa5ce2016-03-16 18:00:46 +00002702 case CC_PreserveMost:
2703 case CC_PreserveAll:
John McCall07daf722016-03-01 22:18:03 +00002704 // FIXME: we should be mangling all of the above.
2705 return "";
John McCall477f2bb2016-03-03 06:39:32 +00002706
Reid Kleckner0a6096b2018-12-21 01:40:29 +00002707 case CC_X86ThisCall:
2708 // FIXME: To match mingw GCC, thiscall should only be mangled in when it is
2709 // used explicitly. At this point, we don't have that much information in
2710 // the AST, since clang tends to bake the convention into the canonical
2711 // function type. thiscall only rarely used explicitly, so don't mangle it
2712 // for now.
2713 return "";
2714
Reid Klecknerf5f62902018-12-14 23:42:59 +00002715 case CC_X86StdCall:
2716 return "stdcall";
2717 case CC_X86FastCall:
2718 return "fastcall";
Reid Klecknerf5f62902018-12-14 23:42:59 +00002719 case CC_X86_64SysV:
2720 return "sysv_abi";
2721 case CC_Win64:
2722 return "ms_abi";
John McCall477f2bb2016-03-03 06:39:32 +00002723 case CC_Swift:
2724 return "swiftcall";
John McCall07daf722016-03-01 22:18:03 +00002725 }
2726 llvm_unreachable("bad calling convention");
2727}
2728
2729void CXXNameMangler::mangleExtFunctionInfo(const FunctionType *T) {
2730 // Fast path.
2731 if (T->getExtInfo() == FunctionType::ExtInfo())
2732 return;
2733
2734 // Vendor-specific qualifiers are emitted in reverse alphabetical order.
2735 // This will get more complicated in the future if we mangle other
2736 // things here; but for now, since we mangle ns_returns_retained as
2737 // a qualifier on the result type, we can get away with this:
2738 StringRef CCQualifier = getCallingConvQualifierName(T->getExtInfo().getCC());
2739 if (!CCQualifier.empty())
2740 mangleVendorQualifier(CCQualifier);
2741
2742 // FIXME: regparm
2743 // FIXME: noreturn
2744}
2745
2746void
2747CXXNameMangler::mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo PI) {
2748 // Vendor-specific qualifiers are emitted in reverse alphabetical order.
2749
2750 // Note that these are *not* substitution candidates. Demanglers might
2751 // have trouble with this if the parameter type is fully substituted.
2752
John McCall477f2bb2016-03-03 06:39:32 +00002753 switch (PI.getABI()) {
2754 case ParameterABI::Ordinary:
2755 break;
2756
2757 // All of these start with "swift", so they come before "ns_consumed".
2758 case ParameterABI::SwiftContext:
2759 case ParameterABI::SwiftErrorResult:
2760 case ParameterABI::SwiftIndirectResult:
2761 mangleVendorQualifier(getParameterABISpelling(PI.getABI()));
2762 break;
2763 }
2764
John McCall07daf722016-03-01 22:18:03 +00002765 if (PI.isConsumed())
John McCall477f2bb2016-03-03 06:39:32 +00002766 mangleVendorQualifier("ns_consumed");
Akira Hatanaka98a49332017-09-22 00:41:05 +00002767
2768 if (PI.isNoEscape())
2769 mangleVendorQualifier("noescape");
John McCall07daf722016-03-01 22:18:03 +00002770}
2771
Guy Benyei11169dd2012-12-18 14:30:41 +00002772// <type> ::= <function-type>
2773// <function-type> ::= [<CV-qualifiers>] F [Y]
2774// <bare-function-type> [<ref-qualifier>] E
Guy Benyei11169dd2012-12-18 14:30:41 +00002775void CXXNameMangler::mangleType(const FunctionProtoType *T) {
John McCall07daf722016-03-01 22:18:03 +00002776 mangleExtFunctionInfo(T);
2777
Guy Benyei11169dd2012-12-18 14:30:41 +00002778 // Mangle CV-qualifiers, if present. These are 'this' qualifiers,
2779 // e.g. "const" in "int (A::*)() const".
Anastasia Stulovac61eaa52019-01-28 11:37:49 +00002780 mangleQualifiers(T->getMethodQuals());
Guy Benyei11169dd2012-12-18 14:30:41 +00002781
Richard Smithfda59e52016-10-26 01:05:54 +00002782 // Mangle instantiation-dependent exception-specification, if present,
2783 // per cxx-abi-dev proposal on 2016-10-11.
2784 if (T->hasInstantiationDependentExceptionSpec()) {
Richard Smitheaf11ad2018-05-03 03:58:32 +00002785 if (isComputedNoexcept(T->getExceptionSpecType())) {
Richard Smithef09aa92016-11-03 00:27:54 +00002786 Out << "DO";
Richard Smithfda59e52016-10-26 01:05:54 +00002787 mangleExpression(T->getNoexceptExpr());
2788 Out << "E";
2789 } else {
2790 assert(T->getExceptionSpecType() == EST_Dynamic);
Richard Smithef09aa92016-11-03 00:27:54 +00002791 Out << "Dw";
Richard Smithfda59e52016-10-26 01:05:54 +00002792 for (auto ExceptTy : T->exceptions())
2793 mangleType(ExceptTy);
2794 Out << "E";
2795 }
Richard Smitheaf11ad2018-05-03 03:58:32 +00002796 } else if (T->isNothrow()) {
Richard Smithef09aa92016-11-03 00:27:54 +00002797 Out << "Do";
Richard Smithfda59e52016-10-26 01:05:54 +00002798 }
2799
Guy Benyei11169dd2012-12-18 14:30:41 +00002800 Out << 'F';
2801
2802 // FIXME: We don't have enough information in the AST to produce the 'Y'
2803 // encoding for extern "C" function types.
2804 mangleBareFunctionType(T, /*MangleReturnType=*/true);
2805
2806 // Mangle the ref-qualifier, if present.
2807 mangleRefQualifier(T->getRefQualifier());
2808
2809 Out << 'E';
2810}
Peter Collingbourneeeebc412015-08-07 23:25:47 +00002811
Guy Benyei11169dd2012-12-18 14:30:41 +00002812void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {
Peter Collingbourneeeebc412015-08-07 23:25:47 +00002813 // Function types without prototypes can arise when mangling a function type
2814 // within an overloadable function in C. We mangle these as the absence of any
2815 // parameter types (not even an empty parameter list).
2816 Out << 'F';
2817
2818 FunctionTypeDepthState saved = FunctionTypeDepth.push();
2819
2820 FunctionTypeDepth.enterResultType();
2821 mangleType(T->getReturnType());
2822 FunctionTypeDepth.leaveResultType();
2823
2824 FunctionTypeDepth.pop(saved);
2825 Out << 'E';
Guy Benyei11169dd2012-12-18 14:30:41 +00002826}
Peter Collingbourneeeebc412015-08-07 23:25:47 +00002827
John McCall07daf722016-03-01 22:18:03 +00002828void CXXNameMangler::mangleBareFunctionType(const FunctionProtoType *Proto,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002829 bool MangleReturnType,
2830 const FunctionDecl *FD) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002831 // Record that we're in a function type. See mangleFunctionParam
2832 // for details on what we're trying to achieve here.
2833 FunctionTypeDepthState saved = FunctionTypeDepth.push();
2834
2835 // <bare-function-type> ::= <signature type>+
2836 if (MangleReturnType) {
2837 FunctionTypeDepth.enterResultType();
John McCall07daf722016-03-01 22:18:03 +00002838
2839 // Mangle ns_returns_retained as an order-sensitive qualifier here.
Nico Weberfb420782016-05-25 14:15:08 +00002840 if (Proto->getExtInfo().getProducesResult() && FD == nullptr)
John McCall07daf722016-03-01 22:18:03 +00002841 mangleVendorQualifier("ns_returns_retained");
2842
2843 // Mangle the return type without any direct ARC ownership qualifiers.
2844 QualType ReturnTy = Proto->getReturnType();
2845 if (ReturnTy.getObjCLifetime()) {
2846 auto SplitReturnTy = ReturnTy.split();
2847 SplitReturnTy.Quals.removeObjCLifetime();
2848 ReturnTy = getASTContext().getQualifiedType(SplitReturnTy);
2849 }
2850 mangleType(ReturnTy);
2851
Guy Benyei11169dd2012-12-18 14:30:41 +00002852 FunctionTypeDepth.leaveResultType();
2853 }
2854
Alp Toker9cacbab2014-01-20 20:26:09 +00002855 if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002856 // <builtin-type> ::= v # void
2857 Out << 'v';
2858
2859 FunctionTypeDepth.pop(saved);
2860 return;
2861 }
2862
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002863 assert(!FD || FD->getNumParams() == Proto->getNumParams());
2864 for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) {
John McCall07daf722016-03-01 22:18:03 +00002865 // Mangle extended parameter info as order-sensitive qualifiers here.
Nico Weberfb420782016-05-25 14:15:08 +00002866 if (Proto->hasExtParameterInfos() && FD == nullptr) {
John McCall07daf722016-03-01 22:18:03 +00002867 mangleExtParameterInfo(Proto->getExtParameterInfo(I));
2868 }
2869
2870 // Mangle the type.
2871 QualType ParamTy = Proto->getParamType(I);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002872 mangleType(Context.getASTContext().getSignatureParameterType(ParamTy));
2873
2874 if (FD) {
2875 if (auto *Attr = FD->getParamDecl(I)->getAttr<PassObjectSizeAttr>()) {
2876 // Attr can only take 1 character, so we can hardcode the length below.
2877 assert(Attr->getType() <= 9 && Attr->getType() >= 0);
Erik Pilkington02d5fb12019-03-19 20:44:18 +00002878 if (Attr->isDynamic())
2879 Out << "U25pass_dynamic_object_size" << Attr->getType();
2880 else
2881 Out << "U17pass_object_size" << Attr->getType();
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002882 }
2883 }
2884 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002885
2886 FunctionTypeDepth.pop(saved);
2887
2888 // <builtin-type> ::= z # ellipsis
2889 if (Proto->isVariadic())
2890 Out << 'z';
2891}
2892
2893// <type> ::= <class-enum-type>
2894// <class-enum-type> ::= <name>
2895void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
2896 mangleName(T->getDecl());
2897}
2898
2899// <type> ::= <class-enum-type>
2900// <class-enum-type> ::= <name>
2901void CXXNameMangler::mangleType(const EnumType *T) {
2902 mangleType(static_cast<const TagType*>(T));
2903}
2904void CXXNameMangler::mangleType(const RecordType *T) {
2905 mangleType(static_cast<const TagType*>(T));
2906}
2907void CXXNameMangler::mangleType(const TagType *T) {
2908 mangleName(T->getDecl());
2909}
2910
2911// <type> ::= <array-type>
2912// <array-type> ::= A <positive dimension number> _ <element type>
2913// ::= A [<dimension expression>] _ <element type>
2914void CXXNameMangler::mangleType(const ConstantArrayType *T) {
2915 Out << 'A' << T->getSize() << '_';
2916 mangleType(T->getElementType());
2917}
2918void CXXNameMangler::mangleType(const VariableArrayType *T) {
2919 Out << 'A';
2920 // decayed vla types (size 0) will just be skipped.
2921 if (T->getSizeExpr())
2922 mangleExpression(T->getSizeExpr());
2923 Out << '_';
2924 mangleType(T->getElementType());
2925}
2926void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
2927 Out << 'A';
2928 mangleExpression(T->getSizeExpr());
2929 Out << '_';
2930 mangleType(T->getElementType());
2931}
2932void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
2933 Out << "A_";
2934 mangleType(T->getElementType());
2935}
2936
2937// <type> ::= <pointer-to-member-type>
2938// <pointer-to-member-type> ::= M <class type> <member type>
2939void CXXNameMangler::mangleType(const MemberPointerType *T) {
2940 Out << 'M';
2941 mangleType(QualType(T->getClass(), 0));
2942 QualType PointeeType = T->getPointeeType();
2943 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
2944 mangleType(FPT);
Fangrui Song6907ce22018-07-30 19:24:48 +00002945
Guy Benyei11169dd2012-12-18 14:30:41 +00002946 // Itanium C++ ABI 5.1.8:
2947 //
2948 // The type of a non-static member function is considered to be different,
2949 // for the purposes of substitution, from the type of a namespace-scope or
2950 // static member function whose type appears similar. The types of two
2951 // non-static member functions are considered to be different, for the
2952 // purposes of substitution, if the functions are members of different
Fangrui Song6907ce22018-07-30 19:24:48 +00002953 // classes. In other words, for the purposes of substitution, the class of
2954 // which the function is a member is considered part of the type of
Guy Benyei11169dd2012-12-18 14:30:41 +00002955 // function.
2956
2957 // Given that we already substitute member function pointers as a
2958 // whole, the net effect of this rule is just to unconditionally
2959 // suppress substitution on the function type in a member pointer.
2960 // We increment the SeqID here to emulate adding an entry to the
2961 // substitution table.
2962 ++SeqID;
2963 } else
2964 mangleType(PointeeType);
2965}
2966
2967// <type> ::= <template-param>
2968void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
2969 mangleTemplateParameter(T->getIndex());
2970}
2971
2972// <type> ::= <template-param>
2973void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {
2974 // FIXME: not clear how to mangle this!
2975 // template <class T...> class A {
2976 // template <class U...> void foo(T(*)(U) x...);
2977 // };
2978 Out << "_SUBSTPACK_";
2979}
2980
2981// <type> ::= P <type> # pointer-to
2982void CXXNameMangler::mangleType(const PointerType *T) {
2983 Out << 'P';
2984 mangleType(T->getPointeeType());
2985}
2986void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
2987 Out << 'P';
2988 mangleType(T->getPointeeType());
2989}
2990
2991// <type> ::= R <type> # reference-to
2992void CXXNameMangler::mangleType(const LValueReferenceType *T) {
2993 Out << 'R';
2994 mangleType(T->getPointeeType());
2995}
2996
2997// <type> ::= O <type> # rvalue reference-to (C++0x)
2998void CXXNameMangler::mangleType(const RValueReferenceType *T) {
2999 Out << 'O';
3000 mangleType(T->getPointeeType());
3001}
3002
3003// <type> ::= C <type> # complex pair (C 2000)
3004void CXXNameMangler::mangleType(const ComplexType *T) {
3005 Out << 'C';
3006 mangleType(T->getElementType());
3007}
3008
3009// ARM's ABI for Neon vector types specifies that they should be mangled as
3010// if they are structs (to match ARM's initial implementation). The
3011// vector type must be one of the special types predefined by ARM.
3012void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {
3013 QualType EltType = T->getElementType();
3014 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
Craig Topper36250ad2014-05-12 05:36:57 +00003015 const char *EltName = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003016 if (T->getVectorKind() == VectorType::NeonPolyVector) {
3017 switch (cast<BuiltinType>(EltType)->getKind()) {
Tim Northovera2ee4332014-03-29 15:09:45 +00003018 case BuiltinType::SChar:
3019 case BuiltinType::UChar:
3020 EltName = "poly8_t";
3021 break;
3022 case BuiltinType::Short:
3023 case BuiltinType::UShort:
3024 EltName = "poly16_t";
3025 break;
3026 case BuiltinType::ULongLong:
3027 EltName = "poly64_t";
3028 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003029 default: llvm_unreachable("unexpected Neon polynomial vector element type");
3030 }
3031 } else {
3032 switch (cast<BuiltinType>(EltType)->getKind()) {
3033 case BuiltinType::SChar: EltName = "int8_t"; break;
3034 case BuiltinType::UChar: EltName = "uint8_t"; break;
3035 case BuiltinType::Short: EltName = "int16_t"; break;
3036 case BuiltinType::UShort: EltName = "uint16_t"; break;
3037 case BuiltinType::Int: EltName = "int32_t"; break;
3038 case BuiltinType::UInt: EltName = "uint32_t"; break;
3039 case BuiltinType::LongLong: EltName = "int64_t"; break;
3040 case BuiltinType::ULongLong: EltName = "uint64_t"; break;
Tim Northovera2ee4332014-03-29 15:09:45 +00003041 case BuiltinType::Double: EltName = "float64_t"; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003042 case BuiltinType::Float: EltName = "float32_t"; break;
Tim Northover2fe823a2013-08-01 09:23:19 +00003043 case BuiltinType::Half: EltName = "float16_t";break;
3044 default:
3045 llvm_unreachable("unexpected Neon vector element type");
Guy Benyei11169dd2012-12-18 14:30:41 +00003046 }
3047 }
Craig Topper36250ad2014-05-12 05:36:57 +00003048 const char *BaseName = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003049 unsigned BitSize = (T->getNumElements() *
3050 getASTContext().getTypeSize(EltType));
3051 if (BitSize == 64)
3052 BaseName = "__simd64_";
3053 else {
3054 assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");
3055 BaseName = "__simd128_";
3056 }
3057 Out << strlen(BaseName) + strlen(EltName);
3058 Out << BaseName << EltName;
3059}
3060
Erich Keanef702b022018-07-13 19:46:04 +00003061void CXXNameMangler::mangleNeonVectorType(const DependentVectorType *T) {
3062 DiagnosticsEngine &Diags = Context.getDiags();
3063 unsigned DiagID = Diags.getCustomDiagID(
3064 DiagnosticsEngine::Error,
3065 "cannot mangle this dependent neon vector type yet");
3066 Diags.Report(T->getAttributeLoc(), DiagID);
3067}
3068
Tim Northover2fe823a2013-08-01 09:23:19 +00003069static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) {
3070 switch (EltType->getKind()) {
3071 case BuiltinType::SChar:
3072 return "Int8";
3073 case BuiltinType::Short:
3074 return "Int16";
3075 case BuiltinType::Int:
3076 return "Int32";
Kevin Qinad64f6d2014-02-24 02:45:03 +00003077 case BuiltinType::Long:
Tim Northovera2ee4332014-03-29 15:09:45 +00003078 case BuiltinType::LongLong:
Tim Northover2fe823a2013-08-01 09:23:19 +00003079 return "Int64";
3080 case BuiltinType::UChar:
3081 return "Uint8";
3082 case BuiltinType::UShort:
3083 return "Uint16";
3084 case BuiltinType::UInt:
3085 return "Uint32";
Kevin Qinad64f6d2014-02-24 02:45:03 +00003086 case BuiltinType::ULong:
Tim Northovera2ee4332014-03-29 15:09:45 +00003087 case BuiltinType::ULongLong:
Tim Northover2fe823a2013-08-01 09:23:19 +00003088 return "Uint64";
3089 case BuiltinType::Half:
3090 return "Float16";
3091 case BuiltinType::Float:
3092 return "Float32";
3093 case BuiltinType::Double:
3094 return "Float64";
3095 default:
3096 llvm_unreachable("Unexpected vector element base type");
3097 }
3098}
3099
3100// AArch64's ABI for Neon vector types specifies that they should be mangled as
3101// the equivalent internal name. The vector type must be one of the special
3102// types predefined by ARM.
3103void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) {
3104 QualType EltType = T->getElementType();
3105 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
3106 unsigned BitSize =
3107 (T->getNumElements() * getASTContext().getTypeSize(EltType));
Daniel Jasper8698af42013-08-01 10:30:11 +00003108 (void)BitSize; // Silence warning.
Tim Northover2fe823a2013-08-01 09:23:19 +00003109
3110 assert((BitSize == 64 || BitSize == 128) &&
3111 "Neon vector type not 64 or 128 bits");
3112
Tim Northover2fe823a2013-08-01 09:23:19 +00003113 StringRef EltName;
3114 if (T->getVectorKind() == VectorType::NeonPolyVector) {
3115 switch (cast<BuiltinType>(EltType)->getKind()) {
3116 case BuiltinType::UChar:
3117 EltName = "Poly8";
3118 break;
3119 case BuiltinType::UShort:
3120 EltName = "Poly16";
3121 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00003122 case BuiltinType::ULong:
Kevin Qin78b86532015-05-14 08:18:05 +00003123 case BuiltinType::ULongLong:
Hao Liu90ee2f12013-11-17 09:14:46 +00003124 EltName = "Poly64";
3125 break;
Tim Northover2fe823a2013-08-01 09:23:19 +00003126 default:
3127 llvm_unreachable("unexpected Neon polynomial vector element type");
3128 }
3129 } else
3130 EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType));
3131
3132 std::string TypeName =
Benjamin Kramerb42d9a52015-12-24 10:07:37 +00003133 ("__" + EltName + "x" + Twine(T->getNumElements()) + "_t").str();
Tim Northover2fe823a2013-08-01 09:23:19 +00003134 Out << TypeName.length() << TypeName;
3135}
Erich Keanef702b022018-07-13 19:46:04 +00003136void CXXNameMangler::mangleAArch64NeonVectorType(const DependentVectorType *T) {
3137 DiagnosticsEngine &Diags = Context.getDiags();
3138 unsigned DiagID = Diags.getCustomDiagID(
3139 DiagnosticsEngine::Error,
3140 "cannot mangle this dependent neon vector type yet");
3141 Diags.Report(T->getAttributeLoc(), DiagID);
3142}
Tim Northover2fe823a2013-08-01 09:23:19 +00003143
Guy Benyei11169dd2012-12-18 14:30:41 +00003144// GNU extension: vector types
3145// <type> ::= <vector-type>
3146// <vector-type> ::= Dv <positive dimension number> _
3147// <extended element type>
3148// ::= Dv [<dimension expression>] _ <element type>
3149// <extended element type> ::= <element type>
3150// ::= p # AltiVec vector pixel
3151// ::= b # Altivec vector bool
3152void CXXNameMangler::mangleType(const VectorType *T) {
3153 if ((T->getVectorKind() == VectorType::NeonVector ||
3154 T->getVectorKind() == VectorType::NeonPolyVector)) {
Tim Northovera2ee4332014-03-29 15:09:45 +00003155 llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
Christian Pirker9b019ae2014-02-25 13:51:00 +00003156 llvm::Triple::ArchType Arch =
3157 getASTContext().getTargetInfo().getTriple().getArch();
Tim Northover25e8a672014-05-24 12:51:25 +00003158 if ((Arch == llvm::Triple::aarch64 ||
Tim Northover40956e62014-07-23 12:32:58 +00003159 Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin())
Tim Northover2fe823a2013-08-01 09:23:19 +00003160 mangleAArch64NeonVectorType(T);
3161 else
3162 mangleNeonVectorType(T);
Guy Benyei11169dd2012-12-18 14:30:41 +00003163 return;
3164 }
3165 Out << "Dv" << T->getNumElements() << '_';
3166 if (T->getVectorKind() == VectorType::AltiVecPixel)
3167 Out << 'p';
3168 else if (T->getVectorKind() == VectorType::AltiVecBool)
3169 Out << 'b';
3170 else
3171 mangleType(T->getElementType());
3172}
Erich Keanef702b022018-07-13 19:46:04 +00003173
3174void CXXNameMangler::mangleType(const DependentVectorType *T) {
3175 if ((T->getVectorKind() == VectorType::NeonVector ||
3176 T->getVectorKind() == VectorType::NeonPolyVector)) {
3177 llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
3178 llvm::Triple::ArchType Arch =
3179 getASTContext().getTargetInfo().getTriple().getArch();
3180 if ((Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_be) &&
3181 !Target.isOSDarwin())
3182 mangleAArch64NeonVectorType(T);
3183 else
3184 mangleNeonVectorType(T);
3185 return;
3186 }
3187
3188 Out << "Dv";
3189 mangleExpression(T->getSizeExpr());
3190 Out << '_';
3191 if (T->getVectorKind() == VectorType::AltiVecPixel)
3192 Out << 'p';
3193 else if (T->getVectorKind() == VectorType::AltiVecBool)
3194 Out << 'b';
3195 else
3196 mangleType(T->getElementType());
3197}
3198
Guy Benyei11169dd2012-12-18 14:30:41 +00003199void CXXNameMangler::mangleType(const ExtVectorType *T) {
3200 mangleType(static_cast<const VectorType*>(T));
3201}
3202void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
3203 Out << "Dv";
3204 mangleExpression(T->getSizeExpr());
3205 Out << '_';
3206 mangleType(T->getElementType());
3207}
3208
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003209void CXXNameMangler::mangleType(const DependentAddressSpaceType *T) {
3210 SplitQualType split = T->getPointeeType().split();
3211 mangleQualifiers(split.Quals, T);
3212 mangleType(QualType(split.Ty, 0));
3213}
3214
Guy Benyei11169dd2012-12-18 14:30:41 +00003215void CXXNameMangler::mangleType(const PackExpansionType *T) {
3216 // <type> ::= Dp <type> # pack expansion (C++0x)
3217 Out << "Dp";
3218 mangleType(T->getPattern());
3219}
3220
3221void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
3222 mangleSourceName(T->getDecl()->getIdentifier());
3223}
3224
3225void CXXNameMangler::mangleType(const ObjCObjectType *T) {
Douglas Gregorab209d82015-07-07 03:58:42 +00003226 // Treat __kindof as a vendor extended type qualifier.
3227 if (T->isKindOfType())
3228 Out << "U8__kindof";
3229
Eli Friedman5f508952013-06-18 22:41:37 +00003230 if (!T->qual_empty()) {
3231 // Mangle protocol qualifiers.
3232 SmallString<64> QualStr;
3233 llvm::raw_svector_ostream QualOS(QualStr);
3234 QualOS << "objcproto";
Aaron Ballman1683f7b2014-03-17 15:55:30 +00003235 for (const auto *I : T->quals()) {
3236 StringRef name = I->getName();
Eli Friedman5f508952013-06-18 22:41:37 +00003237 QualOS << name.size() << name;
3238 }
Eli Friedman5f508952013-06-18 22:41:37 +00003239 Out << 'U' << QualStr.size() << QualStr;
3240 }
Douglas Gregorab209d82015-07-07 03:58:42 +00003241
Guy Benyei11169dd2012-12-18 14:30:41 +00003242 mangleType(T->getBaseType());
Douglas Gregorab209d82015-07-07 03:58:42 +00003243
3244 if (T->isSpecialized()) {
3245 // Mangle type arguments as I <type>+ E
3246 Out << 'I';
3247 for (auto typeArg : T->getTypeArgs())
3248 mangleType(typeArg);
3249 Out << 'E';
3250 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003251}
3252
3253void CXXNameMangler::mangleType(const BlockPointerType *T) {
3254 Out << "U13block_pointer";
3255 mangleType(T->getPointeeType());
3256}
3257
3258void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
3259 // Mangle injected class name types as if the user had written the
3260 // specialization out fully. It may not actually be possible to see
3261 // this mangling, though.
3262 mangleType(T->getInjectedSpecializationType());
3263}
3264
3265void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
3266 if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00003267 mangleTemplateName(TD, T->getArgs(), T->getNumArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00003268 } else {
3269 if (mangleSubstitution(QualType(T, 0)))
3270 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00003271
Guy Benyei11169dd2012-12-18 14:30:41 +00003272 mangleTemplatePrefix(T->getTemplateName());
Fangrui Song6907ce22018-07-30 19:24:48 +00003273
Guy Benyei11169dd2012-12-18 14:30:41 +00003274 // FIXME: GCC does not appear to mangle the template arguments when
3275 // the template in question is a dependent template name. Should we
3276 // emulate that badness?
3277 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
3278 addSubstitution(QualType(T, 0));
3279 }
3280}
3281
3282void CXXNameMangler::mangleType(const DependentNameType *T) {
David Majnemer64e40c52014-04-10 00:49:24 +00003283 // Proposal by cxx-abi-dev, 2014-03-26
3284 // <class-enum-type> ::= <name> # non-dependent or dependent type name or
3285 // # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00003286 // # 'typename'
David Majnemer64e40c52014-04-10 00:49:24 +00003287 // ::= Ts <name> # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00003288 // # 'struct' or 'class'
David Majnemer64e40c52014-04-10 00:49:24 +00003289 // ::= Tu <name> # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00003290 // # 'union'
David Majnemer64e40c52014-04-10 00:49:24 +00003291 // ::= Te <name> # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00003292 // # 'enum'
David Majnemer64e40c52014-04-10 00:49:24 +00003293 switch (T->getKeyword()) {
Richard Smith91fb1f42017-01-20 18:50:12 +00003294 case ETK_None:
David Majnemer64e40c52014-04-10 00:49:24 +00003295 case ETK_Typename:
3296 break;
3297 case ETK_Struct:
3298 case ETK_Class:
3299 case ETK_Interface:
3300 Out << "Ts";
3301 break;
3302 case ETK_Union:
3303 Out << "Tu";
3304 break;
3305 case ETK_Enum:
3306 Out << "Te";
3307 break;
David Majnemer64e40c52014-04-10 00:49:24 +00003308 }
David Majnemer2e159fb2014-04-15 05:51:25 +00003309 // Typename types are always nested
3310 Out << 'N';
Guy Benyei11169dd2012-12-18 14:30:41 +00003311 manglePrefix(T->getQualifier());
David Majnemer64e40c52014-04-10 00:49:24 +00003312 mangleSourceName(T->getIdentifier());
Guy Benyei11169dd2012-12-18 14:30:41 +00003313 Out << 'E';
3314}
3315
3316void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
3317 // Dependently-scoped template types are nested if they have a prefix.
3318 Out << 'N';
3319
3320 // TODO: avoid making this TemplateName.
3321 TemplateName Prefix =
3322 getASTContext().getDependentTemplateName(T->getQualifier(),
3323 T->getIdentifier());
3324 mangleTemplatePrefix(Prefix);
3325
3326 // FIXME: GCC does not appear to mangle the template arguments when
3327 // the template in question is a dependent template name. Should we
3328 // emulate that badness?
Fangrui Song6907ce22018-07-30 19:24:48 +00003329 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00003330 Out << 'E';
3331}
3332
3333void CXXNameMangler::mangleType(const TypeOfType *T) {
3334 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
3335 // "extension with parameters" mangling.
3336 Out << "u6typeof";
3337}
3338
3339void CXXNameMangler::mangleType(const TypeOfExprType *T) {
3340 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
3341 // "extension with parameters" mangling.
3342 Out << "u6typeof";
3343}
3344
3345void CXXNameMangler::mangleType(const DecltypeType *T) {
3346 Expr *E = T->getUnderlyingExpr();
3347
3348 // type ::= Dt <expression> E # decltype of an id-expression
3349 // # or class member access
3350 // ::= DT <expression> E # decltype of an expression
3351
3352 // This purports to be an exhaustive list of id-expressions and
3353 // class member accesses. Note that we do not ignore parentheses;
3354 // parentheses change the semantics of decltype for these
3355 // expressions (and cause the mangler to use the other form).
3356 if (isa<DeclRefExpr>(E) ||
3357 isa<MemberExpr>(E) ||
3358 isa<UnresolvedLookupExpr>(E) ||
3359 isa<DependentScopeDeclRefExpr>(E) ||
3360 isa<CXXDependentScopeMemberExpr>(E) ||
3361 isa<UnresolvedMemberExpr>(E))
3362 Out << "Dt";
3363 else
3364 Out << "DT";
3365 mangleExpression(E);
3366 Out << 'E';
3367}
3368
3369void CXXNameMangler::mangleType(const UnaryTransformType *T) {
3370 // If this is dependent, we need to record that. If not, we simply
3371 // mangle it as the underlying type since they are equivalent.
3372 if (T->isDependentType()) {
3373 Out << 'U';
Fangrui Song6907ce22018-07-30 19:24:48 +00003374
Guy Benyei11169dd2012-12-18 14:30:41 +00003375 switch (T->getUTTKind()) {
3376 case UnaryTransformType::EnumUnderlyingType:
3377 Out << "3eut";
3378 break;
3379 }
3380 }
3381
David Majnemer140065a2016-06-08 00:34:15 +00003382 mangleType(T->getBaseType());
Guy Benyei11169dd2012-12-18 14:30:41 +00003383}
3384
3385void CXXNameMangler::mangleType(const AutoType *T) {
Erik Pilkingtone7e87722018-04-28 02:40:28 +00003386 assert(T->getDeducedType().isNull() &&
3387 "Deduced AutoType shouldn't be handled here!");
3388 assert(T->getKeyword() != AutoTypeKeyword::GNUAutoType &&
3389 "shouldn't need to mangle __auto_type!");
3390 // <builtin-type> ::= Da # auto
3391 // ::= Dc # decltype(auto)
3392 Out << (T->isDecltypeAuto() ? "Dc" : "Da");
Guy Benyei11169dd2012-12-18 14:30:41 +00003393}
3394
Richard Smith600b5262017-01-26 20:40:47 +00003395void CXXNameMangler::mangleType(const DeducedTemplateSpecializationType *T) {
3396 // FIXME: This is not the right mangling. We also need to include a scope
3397 // here in some cases.
3398 QualType D = T->getDeducedType();
3399 if (D.isNull())
3400 mangleUnscopedTemplateName(T->getTemplateName(), nullptr);
3401 else
3402 mangleType(D);
3403}
3404
Guy Benyei11169dd2012-12-18 14:30:41 +00003405void CXXNameMangler::mangleType(const AtomicType *T) {
Nick Lewycky206cc2d2014-03-09 17:09:28 +00003406 // <type> ::= U <source-name> <type> # vendor extended type qualifier
Guy Benyei11169dd2012-12-18 14:30:41 +00003407 // (Until there's a standardized mangling...)
3408 Out << "U7_Atomic";
3409 mangleType(T->getValueType());
3410}
3411
Xiuli Pan9c14e282016-01-09 12:53:17 +00003412void CXXNameMangler::mangleType(const PipeType *T) {
3413 // Pipe type mangling rules are described in SPIR 2.0 specification
3414 // A.1 Data types and A.3 Summary of changes
3415 // <type> ::= 8ocl_pipe
3416 Out << "8ocl_pipe";
3417}
3418
Guy Benyei11169dd2012-12-18 14:30:41 +00003419void CXXNameMangler::mangleIntegerLiteral(QualType T,
3420 const llvm::APSInt &Value) {
3421 // <expr-primary> ::= L <type> <value number> E # integer literal
3422 Out << 'L';
3423
3424 mangleType(T);
3425 if (T->isBooleanType()) {
3426 // Boolean values are encoded as 0/1.
3427 Out << (Value.getBoolValue() ? '1' : '0');
3428 } else {
3429 mangleNumber(Value);
3430 }
3431 Out << 'E';
3432
3433}
3434
David Majnemer1dabfdc2015-02-14 13:23:54 +00003435void CXXNameMangler::mangleMemberExprBase(const Expr *Base, bool IsArrow) {
3436 // Ignore member expressions involving anonymous unions.
3437 while (const auto *RT = Base->getType()->getAs<RecordType>()) {
3438 if (!RT->getDecl()->isAnonymousStructOrUnion())
3439 break;
3440 const auto *ME = dyn_cast<MemberExpr>(Base);
3441 if (!ME)
3442 break;
3443 Base = ME->getBase();
3444 IsArrow = ME->isArrow();
3445 }
3446
3447 if (Base->isImplicitCXXThis()) {
3448 // Note: GCC mangles member expressions to the implicit 'this' as
3449 // *this., whereas we represent them as this->. The Itanium C++ ABI
3450 // does not specify anything here, so we follow GCC.
3451 Out << "dtdefpT";
3452 } else {
3453 Out << (IsArrow ? "pt" : "dt");
3454 mangleExpression(Base);
3455 }
3456}
3457
Guy Benyei11169dd2012-12-18 14:30:41 +00003458/// Mangles a member expression.
3459void CXXNameMangler::mangleMemberExpr(const Expr *base,
3460 bool isArrow,
3461 NestedNameSpecifier *qualifier,
3462 NamedDecl *firstQualifierLookup,
3463 DeclarationName member,
Richard Smithafecd832016-10-24 20:47:04 +00003464 const TemplateArgumentLoc *TemplateArgs,
3465 unsigned NumTemplateArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00003466 unsigned arity) {
3467 // <expression> ::= dt <expression> <unresolved-name>
3468 // ::= pt <expression> <unresolved-name>
David Majnemer1dabfdc2015-02-14 13:23:54 +00003469 if (base)
3470 mangleMemberExprBase(base, isArrow);
Richard Smithafecd832016-10-24 20:47:04 +00003471 mangleUnresolvedName(qualifier, member, TemplateArgs, NumTemplateArgs, arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003472}
3473
3474/// Look at the callee of the given call expression and determine if
3475/// it's a parenthesized id-expression which would have triggered ADL
3476/// otherwise.
3477static bool isParenthesizedADLCallee(const CallExpr *call) {
3478 const Expr *callee = call->getCallee();
3479 const Expr *fn = callee->IgnoreParens();
3480
3481 // Must be parenthesized. IgnoreParens() skips __extension__ nodes,
3482 // too, but for those to appear in the callee, it would have to be
3483 // parenthesized.
3484 if (callee == fn) return false;
3485
3486 // Must be an unresolved lookup.
3487 const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);
3488 if (!lookup) return false;
3489
3490 assert(!lookup->requiresADL());
3491
3492 // Must be an unqualified lookup.
3493 if (lookup->getQualifier()) return false;
3494
3495 // Must not have found a class member. Note that if one is a class
3496 // member, they're all class members.
3497 if (lookup->getNumDecls() > 0 &&
3498 (*lookup->decls_begin())->isCXXClassMember())
3499 return false;
3500
3501 // Otherwise, ADL would have been triggered.
3502 return true;
3503}
3504
David Majnemer9c775c72014-09-23 04:27:55 +00003505void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) {
3506 const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);
3507 Out << CastEncoding;
3508 mangleType(ECE->getType());
3509 mangleExpression(ECE->getSubExpr());
3510}
3511
Richard Smith520449d2015-02-05 06:15:50 +00003512void CXXNameMangler::mangleInitListElements(const InitListExpr *InitList) {
3513 if (auto *Syntactic = InitList->getSyntacticForm())
3514 InitList = Syntactic;
3515 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
3516 mangleExpression(InitList->getInit(i));
3517}
3518
Richard Smithb2997f52019-05-21 20:10:50 +00003519void CXXNameMangler::mangleDeclRefExpr(const NamedDecl *D) {
3520 switch (D->getKind()) {
3521 default:
3522 // <expr-primary> ::= L <mangled-name> E # external name
3523 Out << 'L';
3524 mangle(D);
3525 Out << 'E';
3526 break;
3527
3528 case Decl::ParmVar:
3529 mangleFunctionParam(cast<ParmVarDecl>(D));
3530 break;
3531
3532 case Decl::EnumConstant: {
3533 const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
3534 mangleIntegerLiteral(ED->getType(), ED->getInitVal());
3535 break;
3536 }
3537
3538 case Decl::NonTypeTemplateParm:
3539 const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
3540 mangleTemplateParameter(PD->getIndex());
3541 break;
3542 }
3543}
3544
Guy Benyei11169dd2012-12-18 14:30:41 +00003545void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity) {
3546 // <expression> ::= <unary operator-name> <expression>
3547 // ::= <binary operator-name> <expression> <expression>
3548 // ::= <trinary operator-name> <expression> <expression> <expression>
3549 // ::= cv <type> expression # conversion with one argument
3550 // ::= cv <type> _ <expression>* E # conversion with a different number of arguments
David Majnemer9c775c72014-09-23 04:27:55 +00003551 // ::= dc <type> <expression> # dynamic_cast<type> (expression)
3552 // ::= sc <type> <expression> # static_cast<type> (expression)
3553 // ::= cc <type> <expression> # const_cast<type> (expression)
3554 // ::= rc <type> <expression> # reinterpret_cast<type> (expression)
Guy Benyei11169dd2012-12-18 14:30:41 +00003555 // ::= st <type> # sizeof (a type)
3556 // ::= at <type> # alignof (a type)
3557 // ::= <template-param>
3558 // ::= <function-param>
3559 // ::= sr <type> <unqualified-name> # dependent name
3560 // ::= sr <type> <unqualified-name> <template-args> # dependent template-id
3561 // ::= ds <expression> <expression> # expr.*expr
3562 // ::= sZ <template-param> # size of a parameter pack
3563 // ::= sZ <function-param> # size of a function parameter pack
3564 // ::= <expr-primary>
3565 // <expr-primary> ::= L <type> <value number> E # integer literal
3566 // ::= L <type <value float> E # floating literal
3567 // ::= L <mangled-name> E # external name
3568 // ::= fpT # 'this' expression
3569 QualType ImplicitlyConvertedToType;
Fangrui Song6907ce22018-07-30 19:24:48 +00003570
Guy Benyei11169dd2012-12-18 14:30:41 +00003571recurse:
3572 switch (E->getStmtClass()) {
3573 case Expr::NoStmtClass:
3574#define ABSTRACT_STMT(Type)
3575#define EXPR(Type, Base)
3576#define STMT(Type, Base) \
3577 case Expr::Type##Class:
3578#include "clang/AST/StmtNodes.inc"
3579 // fallthrough
3580
3581 // These all can only appear in local or variable-initialization
3582 // contexts and so should never appear in a mangling.
3583 case Expr::AddrLabelExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00003584 case Expr::DesignatedInitUpdateExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003585 case Expr::ImplicitValueInitExprClass:
Richard Smith410306b2016-12-12 02:53:20 +00003586 case Expr::ArrayInitLoopExprClass:
3587 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00003588 case Expr::NoInitExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003589 case Expr::ParenListExprClass:
3590 case Expr::LambdaExprClass:
John McCall5e77d762013-04-16 07:28:30 +00003591 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +00003592 case Expr::MSPropertySubscriptExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00003593 case Expr::TypoExprClass: // This should no longer exist in the AST by now.
Alexey Bataev1a3320e2015-08-25 14:24:04 +00003594 case Expr::OMPArraySectionExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +00003595 case Expr::CXXInheritedCtorInitExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003596 llvm_unreachable("unexpected statement kind");
3597
Bill Wendling7c44da22018-10-31 03:48:47 +00003598 case Expr::ConstantExprClass:
3599 E = cast<ConstantExpr>(E)->getSubExpr();
3600 goto recurse;
3601
Guy Benyei11169dd2012-12-18 14:30:41 +00003602 // FIXME: invent manglings for all these.
3603 case Expr::BlockExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003604 case Expr::ChooseExprClass:
3605 case Expr::CompoundLiteralExprClass:
3606 case Expr::ExtVectorElementExprClass:
3607 case Expr::GenericSelectionExprClass:
3608 case Expr::ObjCEncodeExprClass:
3609 case Expr::ObjCIsaExprClass:
3610 case Expr::ObjCIvarRefExprClass:
3611 case Expr::ObjCMessageExprClass:
3612 case Expr::ObjCPropertyRefExprClass:
3613 case Expr::ObjCProtocolExprClass:
3614 case Expr::ObjCSelectorExprClass:
3615 case Expr::ObjCStringLiteralClass:
3616 case Expr::ObjCBoxedExprClass:
3617 case Expr::ObjCArrayLiteralClass:
3618 case Expr::ObjCDictionaryLiteralClass:
3619 case Expr::ObjCSubscriptRefExprClass:
3620 case Expr::ObjCIndirectCopyRestoreExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +00003621 case Expr::ObjCAvailabilityCheckExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003622 case Expr::OffsetOfExprClass:
3623 case Expr::PredefinedExprClass:
3624 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00003625 case Expr::ConvertVectorExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003626 case Expr::StmtExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003627 case Expr::TypeTraitExprClass:
3628 case Expr::ArrayTypeTraitExprClass:
3629 case Expr::ExpressionTraitExprClass:
3630 case Expr::VAArgExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003631 case Expr::CUDAKernelCallExprClass:
3632 case Expr::AsTypeExprClass:
3633 case Expr::PseudoObjectExprClass:
3634 case Expr::AtomicExprClass:
Eric Fiselier708afb52019-05-16 21:04:15 +00003635 case Expr::SourceLocExprClass:
Leonard Chandb01c3a2018-06-20 17:19:40 +00003636 case Expr::FixedPointLiteralClass:
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00003637 case Expr::BuiltinBitCastExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003638 {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00003639 if (!NullOut) {
3640 // As bad as this diagnostic is, it's better than crashing.
3641 DiagnosticsEngine &Diags = Context.getDiags();
3642 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3643 "cannot yet mangle expression type %0");
3644 Diags.Report(E->getExprLoc(), DiagID)
3645 << E->getStmtClassName() << E->getSourceRange();
3646 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003647 break;
3648 }
3649
Fariborz Jahanian945a08d2014-09-24 16:28:40 +00003650 case Expr::CXXUuidofExprClass: {
3651 const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E);
3652 if (UE->isTypeOperand()) {
3653 QualType UuidT = UE->getTypeOperand(Context.getASTContext());
3654 Out << "u8__uuidoft";
3655 mangleType(UuidT);
3656 } else {
3657 Expr *UuidExp = UE->getExprOperand();
3658 Out << "u8__uuidofz";
3659 mangleExpression(UuidExp, Arity);
3660 }
3661 break;
3662 }
3663
Guy Benyei11169dd2012-12-18 14:30:41 +00003664 // Even gcc-4.5 doesn't mangle this.
3665 case Expr::BinaryConditionalOperatorClass: {
3666 DiagnosticsEngine &Diags = Context.getDiags();
3667 unsigned DiagID =
3668 Diags.getCustomDiagID(DiagnosticsEngine::Error,
3669 "?: operator with omitted middle operand cannot be mangled");
3670 Diags.Report(E->getExprLoc(), DiagID)
3671 << E->getStmtClassName() << E->getSourceRange();
3672 break;
3673 }
3674
3675 // These are used for internal purposes and cannot be meaningfully mangled.
3676 case Expr::OpaqueValueExprClass:
3677 llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
3678
3679 case Expr::InitListExprClass: {
Guy Benyei11169dd2012-12-18 14:30:41 +00003680 Out << "il";
Richard Smith520449d2015-02-05 06:15:50 +00003681 mangleInitListElements(cast<InitListExpr>(E));
Guy Benyei11169dd2012-12-18 14:30:41 +00003682 Out << "E";
3683 break;
3684 }
3685
Richard Smith39eca9b2017-08-23 22:12:08 +00003686 case Expr::DesignatedInitExprClass: {
3687 auto *DIE = cast<DesignatedInitExpr>(E);
3688 for (const auto &Designator : DIE->designators()) {
3689 if (Designator.isFieldDesignator()) {
3690 Out << "di";
3691 mangleSourceName(Designator.getFieldName());
3692 } else if (Designator.isArrayDesignator()) {
3693 Out << "dx";
3694 mangleExpression(DIE->getArrayIndex(Designator));
3695 } else {
3696 assert(Designator.isArrayRangeDesignator() &&
3697 "unknown designator kind");
3698 Out << "dX";
3699 mangleExpression(DIE->getArrayRangeStart(Designator));
3700 mangleExpression(DIE->getArrayRangeEnd(Designator));
3701 }
3702 }
3703 mangleExpression(DIE->getInit());
3704 break;
3705 }
3706
Guy Benyei11169dd2012-12-18 14:30:41 +00003707 case Expr::CXXDefaultArgExprClass:
3708 mangleExpression(cast<CXXDefaultArgExpr>(E)->getExpr(), Arity);
3709 break;
3710
Richard Smith852c9db2013-04-20 22:23:05 +00003711 case Expr::CXXDefaultInitExprClass:
3712 mangleExpression(cast<CXXDefaultInitExpr>(E)->getExpr(), Arity);
3713 break;
3714
Richard Smithcc1b96d2013-06-12 22:31:48 +00003715 case Expr::CXXStdInitializerListExprClass:
3716 mangleExpression(cast<CXXStdInitializerListExpr>(E)->getSubExpr(), Arity);
3717 break;
3718
Guy Benyei11169dd2012-12-18 14:30:41 +00003719 case Expr::SubstNonTypeTemplateParmExprClass:
3720 mangleExpression(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(),
3721 Arity);
3722 break;
3723
3724 case Expr::UserDefinedLiteralClass:
3725 // We follow g++'s approach of mangling a UDL as a call to the literal
3726 // operator.
3727 case Expr::CXXMemberCallExprClass: // fallthrough
3728 case Expr::CallExprClass: {
3729 const CallExpr *CE = cast<CallExpr>(E);
3730
3731 // <expression> ::= cp <simple-id> <expression>* E
3732 // We use this mangling only when the call would use ADL except
3733 // for being parenthesized. Per discussion with David
3734 // Vandervoorde, 2011.04.25.
3735 if (isParenthesizedADLCallee(CE)) {
3736 Out << "cp";
3737 // The callee here is a parenthesized UnresolvedLookupExpr with
3738 // no qualifier and should always get mangled as a <simple-id>
3739 // anyway.
3740
3741 // <expression> ::= cl <expression>* E
3742 } else {
3743 Out << "cl";
3744 }
3745
David Majnemer67a8ec62015-02-19 21:41:48 +00003746 unsigned CallArity = CE->getNumArgs();
3747 for (const Expr *Arg : CE->arguments())
3748 if (isa<PackExpansionExpr>(Arg))
3749 CallArity = UnknownArity;
3750
3751 mangleExpression(CE->getCallee(), CallArity);
3752 for (const Expr *Arg : CE->arguments())
3753 mangleExpression(Arg);
Guy Benyei11169dd2012-12-18 14:30:41 +00003754 Out << 'E';
3755 break;
3756 }
3757
3758 case Expr::CXXNewExprClass: {
3759 const CXXNewExpr *New = cast<CXXNewExpr>(E);
3760 if (New->isGlobalNew()) Out << "gs";
3761 Out << (New->isArray() ? "na" : "nw");
3762 for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(),
3763 E = New->placement_arg_end(); I != E; ++I)
3764 mangleExpression(*I);
3765 Out << '_';
3766 mangleType(New->getAllocatedType());
3767 if (New->hasInitializer()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003768 if (New->getInitializationStyle() == CXXNewExpr::ListInit)
3769 Out << "il";
3770 else
3771 Out << "pi";
3772 const Expr *Init = New->getInitializer();
3773 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
3774 // Directly inline the initializers.
3775 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
3776 E = CCE->arg_end();
3777 I != E; ++I)
3778 mangleExpression(*I);
3779 } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {
3780 for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)
3781 mangleExpression(PLE->getExpr(i));
3782 } else if (New->getInitializationStyle() == CXXNewExpr::ListInit &&
3783 isa<InitListExpr>(Init)) {
3784 // Only take InitListExprs apart for list-initialization.
Richard Smith520449d2015-02-05 06:15:50 +00003785 mangleInitListElements(cast<InitListExpr>(Init));
Guy Benyei11169dd2012-12-18 14:30:41 +00003786 } else
3787 mangleExpression(Init);
3788 }
3789 Out << 'E';
3790 break;
3791 }
3792
David Majnemer1dabfdc2015-02-14 13:23:54 +00003793 case Expr::CXXPseudoDestructorExprClass: {
3794 const auto *PDE = cast<CXXPseudoDestructorExpr>(E);
3795 if (const Expr *Base = PDE->getBase())
3796 mangleMemberExprBase(Base, PDE->isArrow());
David Majnemerb8014dd2015-02-19 02:16:16 +00003797 NestedNameSpecifier *Qualifier = PDE->getQualifier();
David Majnemerb8014dd2015-02-19 02:16:16 +00003798 if (TypeSourceInfo *ScopeInfo = PDE->getScopeTypeInfo()) {
3799 if (Qualifier) {
3800 mangleUnresolvedPrefix(Qualifier,
3801 /*Recursive=*/true);
3802 mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType());
3803 Out << 'E';
3804 } else {
3805 Out << "sr";
3806 if (!mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType()))
3807 Out << 'E';
3808 }
3809 } else if (Qualifier) {
3810 mangleUnresolvedPrefix(Qualifier);
3811 }
David Majnemer1dabfdc2015-02-14 13:23:54 +00003812 // <base-unresolved-name> ::= dn <destructor-name>
3813 Out << "dn";
David Majnemera88b3592015-02-18 02:28:01 +00003814 QualType DestroyedType = PDE->getDestroyedType();
David Majnemerb8014dd2015-02-19 02:16:16 +00003815 mangleUnresolvedTypeOrSimpleId(DestroyedType);
David Majnemer1dabfdc2015-02-14 13:23:54 +00003816 break;
3817 }
3818
Guy Benyei11169dd2012-12-18 14:30:41 +00003819 case Expr::MemberExprClass: {
3820 const MemberExpr *ME = cast<MemberExpr>(E);
3821 mangleMemberExpr(ME->getBase(), ME->isArrow(),
Craig Topper36250ad2014-05-12 05:36:57 +00003822 ME->getQualifier(), nullptr,
Richard Smithafecd832016-10-24 20:47:04 +00003823 ME->getMemberDecl()->getDeclName(),
3824 ME->getTemplateArgs(), ME->getNumTemplateArgs(),
3825 Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003826 break;
3827 }
3828
3829 case Expr::UnresolvedMemberExprClass: {
3830 const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
Douglas Gregor3c523c42015-05-21 18:28:18 +00003831 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
3832 ME->isArrow(), ME->getQualifier(), nullptr,
Richard Smithafecd832016-10-24 20:47:04 +00003833 ME->getMemberName(),
3834 ME->getTemplateArgs(), ME->getNumTemplateArgs(),
3835 Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003836 break;
3837 }
3838
3839 case Expr::CXXDependentScopeMemberExprClass: {
3840 const CXXDependentScopeMemberExpr *ME
3841 = cast<CXXDependentScopeMemberExpr>(E);
Douglas Gregor3c523c42015-05-21 18:28:18 +00003842 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
3843 ME->isArrow(), ME->getQualifier(),
3844 ME->getFirstQualifierFoundInScope(),
Richard Smithafecd832016-10-24 20:47:04 +00003845 ME->getMember(),
3846 ME->getTemplateArgs(), ME->getNumTemplateArgs(),
3847 Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003848 break;
3849 }
3850
3851 case Expr::UnresolvedLookupExprClass: {
3852 const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
Richard Smithafecd832016-10-24 20:47:04 +00003853 mangleUnresolvedName(ULE->getQualifier(), ULE->getName(),
3854 ULE->getTemplateArgs(), ULE->getNumTemplateArgs(),
3855 Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003856 break;
3857 }
3858
3859 case Expr::CXXUnresolvedConstructExprClass: {
3860 const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
3861 unsigned N = CE->arg_size();
3862
Richard Smith39eca9b2017-08-23 22:12:08 +00003863 if (CE->isListInitialization()) {
3864 assert(N == 1 && "unexpected form for list initialization");
3865 auto *IL = cast<InitListExpr>(CE->getArg(0));
3866 Out << "tl";
3867 mangleType(CE->getType());
3868 mangleInitListElements(IL);
3869 Out << "E";
3870 return;
3871 }
3872
Guy Benyei11169dd2012-12-18 14:30:41 +00003873 Out << "cv";
3874 mangleType(CE->getType());
3875 if (N != 1) Out << '_';
3876 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
3877 if (N != 1) Out << 'E';
3878 break;
3879 }
3880
Guy Benyei11169dd2012-12-18 14:30:41 +00003881 case Expr::CXXConstructExprClass: {
Richard Smith520449d2015-02-05 06:15:50 +00003882 const auto *CE = cast<CXXConstructExpr>(E);
Richard Smithed83ebd2015-02-05 07:02:11 +00003883 if (!CE->isListInitialization() || CE->isStdInitListInitialization()) {
Richard Smith520449d2015-02-05 06:15:50 +00003884 assert(
3885 CE->getNumArgs() >= 1 &&
3886 (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) &&
3887 "implicit CXXConstructExpr must have one argument");
3888 return mangleExpression(cast<CXXConstructExpr>(E)->getArg(0));
3889 }
3890 Out << "il";
3891 for (auto *E : CE->arguments())
3892 mangleExpression(E);
3893 Out << "E";
3894 break;
3895 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003896
Richard Smith520449d2015-02-05 06:15:50 +00003897 case Expr::CXXTemporaryObjectExprClass: {
3898 const auto *CE = cast<CXXTemporaryObjectExpr>(E);
3899 unsigned N = CE->getNumArgs();
3900 bool List = CE->isListInitialization();
3901
3902 if (List)
Guy Benyei11169dd2012-12-18 14:30:41 +00003903 Out << "tl";
3904 else
3905 Out << "cv";
3906 mangleType(CE->getType());
Richard Smith520449d2015-02-05 06:15:50 +00003907 if (!List && N != 1)
3908 Out << '_';
Richard Smithed83ebd2015-02-05 07:02:11 +00003909 if (CE->isStdInitListInitialization()) {
3910 // We implicitly created a std::initializer_list<T> for the first argument
3911 // of a constructor of type U in an expression of the form U{a, b, c}.
3912 // Strip all the semantic gunk off the initializer list.
3913 auto *SILE =
3914 cast<CXXStdInitializerListExpr>(CE->getArg(0)->IgnoreImplicit());
3915 auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit());
3916 mangleInitListElements(ILE);
3917 } else {
3918 for (auto *E : CE->arguments())
3919 mangleExpression(E);
3920 }
Richard Smith520449d2015-02-05 06:15:50 +00003921 if (List || N != 1)
3922 Out << 'E';
Guy Benyei11169dd2012-12-18 14:30:41 +00003923 break;
3924 }
3925
3926 case Expr::CXXScalarValueInitExprClass:
Richard Smith520449d2015-02-05 06:15:50 +00003927 Out << "cv";
Guy Benyei11169dd2012-12-18 14:30:41 +00003928 mangleType(E->getType());
Richard Smith520449d2015-02-05 06:15:50 +00003929 Out << "_E";
Guy Benyei11169dd2012-12-18 14:30:41 +00003930 break;
3931
3932 case Expr::CXXNoexceptExprClass:
3933 Out << "nx";
3934 mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());
3935 break;
3936
3937 case Expr::UnaryExprOrTypeTraitExprClass: {
3938 const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);
Fangrui Song6907ce22018-07-30 19:24:48 +00003939
Guy Benyei11169dd2012-12-18 14:30:41 +00003940 if (!SAE->isInstantiationDependent()) {
3941 // Itanium C++ ABI:
Fangrui Song6907ce22018-07-30 19:24:48 +00003942 // If the operand of a sizeof or alignof operator is not
3943 // instantiation-dependent it is encoded as an integer literal
Guy Benyei11169dd2012-12-18 14:30:41 +00003944 // reflecting the result of the operator.
3945 //
Fangrui Song6907ce22018-07-30 19:24:48 +00003946 // If the result of the operator is implicitly converted to a known
3947 // integer type, that type is used for the literal; otherwise, the type
Guy Benyei11169dd2012-12-18 14:30:41 +00003948 // of std::size_t or std::ptrdiff_t is used.
Fangrui Song6907ce22018-07-30 19:24:48 +00003949 QualType T = (ImplicitlyConvertedToType.isNull() ||
Guy Benyei11169dd2012-12-18 14:30:41 +00003950 !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
3951 : ImplicitlyConvertedToType;
3952 llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());
3953 mangleIntegerLiteral(T, V);
3954 break;
3955 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003956
Guy Benyei11169dd2012-12-18 14:30:41 +00003957 switch(SAE->getKind()) {
3958 case UETT_SizeOf:
3959 Out << 's';
3960 break;
Richard Smith6822bd72018-10-26 19:26:45 +00003961 case UETT_PreferredAlignOf:
Guy Benyei11169dd2012-12-18 14:30:41 +00003962 case UETT_AlignOf:
3963 Out << 'a';
3964 break;
Alexey Bataev00396512015-07-02 03:40:19 +00003965 case UETT_VecStep: {
Guy Benyei11169dd2012-12-18 14:30:41 +00003966 DiagnosticsEngine &Diags = Context.getDiags();
3967 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3968 "cannot yet mangle vec_step expression");
3969 Diags.Report(DiagID);
3970 return;
3971 }
Erich Keaned2143c32019-05-29 17:04:48 +00003972 case UETT_OpenMPRequiredSimdAlign: {
Alexey Bataev00396512015-07-02 03:40:19 +00003973 DiagnosticsEngine &Diags = Context.getDiags();
3974 unsigned DiagID = Diags.getCustomDiagID(
3975 DiagnosticsEngine::Error,
3976 "cannot yet mangle __builtin_omp_required_simd_align expression");
3977 Diags.Report(DiagID);
3978 return;
3979 }
Erich Keaned2143c32019-05-29 17:04:48 +00003980 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003981 if (SAE->isArgumentType()) {
3982 Out << 't';
3983 mangleType(SAE->getArgumentType());
3984 } else {
3985 Out << 'z';
3986 mangleExpression(SAE->getArgumentExpr());
3987 }
3988 break;
3989 }
3990
3991 case Expr::CXXThrowExprClass: {
3992 const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00003993 // <expression> ::= tw <expression> # throw expression
3994 // ::= tr # rethrow
Guy Benyei11169dd2012-12-18 14:30:41 +00003995 if (TE->getSubExpr()) {
3996 Out << "tw";
3997 mangleExpression(TE->getSubExpr());
3998 } else {
3999 Out << "tr";
4000 }
4001 break;
4002 }
4003
4004 case Expr::CXXTypeidExprClass: {
4005 const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00004006 // <expression> ::= ti <type> # typeid (type)
4007 // ::= te <expression> # typeid (expression)
Guy Benyei11169dd2012-12-18 14:30:41 +00004008 if (TIE->isTypeOperand()) {
4009 Out << "ti";
David Majnemer143c55e2013-09-27 07:04:31 +00004010 mangleType(TIE->getTypeOperand(Context.getASTContext()));
Guy Benyei11169dd2012-12-18 14:30:41 +00004011 } else {
4012 Out << "te";
4013 mangleExpression(TIE->getExprOperand());
4014 }
4015 break;
4016 }
4017
4018 case Expr::CXXDeleteExprClass: {
4019 const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00004020 // <expression> ::= [gs] dl <expression> # [::] delete expr
4021 // ::= [gs] da <expression> # [::] delete [] expr
Guy Benyei11169dd2012-12-18 14:30:41 +00004022 if (DE->isGlobalDelete()) Out << "gs";
4023 Out << (DE->isArrayForm() ? "da" : "dl");
4024 mangleExpression(DE->getArgument());
4025 break;
4026 }
4027
4028 case Expr::UnaryOperatorClass: {
4029 const UnaryOperator *UO = cast<UnaryOperator>(E);
4030 mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
4031 /*Arity=*/1);
4032 mangleExpression(UO->getSubExpr());
4033 break;
4034 }
4035
4036 case Expr::ArraySubscriptExprClass: {
4037 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
4038
4039 // Array subscript is treated as a syntactically weird form of
4040 // binary operator.
4041 Out << "ix";
4042 mangleExpression(AE->getLHS());
4043 mangleExpression(AE->getRHS());
4044 break;
4045 }
4046
4047 case Expr::CompoundAssignOperatorClass: // fallthrough
4048 case Expr::BinaryOperatorClass: {
4049 const BinaryOperator *BO = cast<BinaryOperator>(E);
4050 if (BO->getOpcode() == BO_PtrMemD)
4051 Out << "ds";
4052 else
4053 mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
4054 /*Arity=*/2);
4055 mangleExpression(BO->getLHS());
4056 mangleExpression(BO->getRHS());
4057 break;
4058 }
4059
4060 case Expr::ConditionalOperatorClass: {
4061 const ConditionalOperator *CO = cast<ConditionalOperator>(E);
4062 mangleOperatorName(OO_Conditional, /*Arity=*/3);
4063 mangleExpression(CO->getCond());
4064 mangleExpression(CO->getLHS(), Arity);
4065 mangleExpression(CO->getRHS(), Arity);
4066 break;
4067 }
4068
4069 case Expr::ImplicitCastExprClass: {
4070 ImplicitlyConvertedToType = E->getType();
4071 E = cast<ImplicitCastExpr>(E)->getSubExpr();
4072 goto recurse;
4073 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004074
Guy Benyei11169dd2012-12-18 14:30:41 +00004075 case Expr::ObjCBridgedCastExprClass: {
Fangrui Song6907ce22018-07-30 19:24:48 +00004076 // Mangle ownership casts as a vendor extended operator __bridge,
Guy Benyei11169dd2012-12-18 14:30:41 +00004077 // __bridge_transfer, or __bridge_retain.
4078 StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();
4079 Out << "v1U" << Kind.size() << Kind;
4080 }
4081 // Fall through to mangle the cast itself.
Galina Kistanovaf87496d2017-06-03 06:31:42 +00004082 LLVM_FALLTHROUGH;
Fangrui Song6907ce22018-07-30 19:24:48 +00004083
Guy Benyei11169dd2012-12-18 14:30:41 +00004084 case Expr::CStyleCastExprClass:
David Majnemer9c775c72014-09-23 04:27:55 +00004085 mangleCastExpression(E, "cv");
Guy Benyei11169dd2012-12-18 14:30:41 +00004086 break;
David Majnemer9c775c72014-09-23 04:27:55 +00004087
Richard Smith520449d2015-02-05 06:15:50 +00004088 case Expr::CXXFunctionalCastExprClass: {
4089 auto *Sub = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreImplicit();
4090 // FIXME: Add isImplicit to CXXConstructExpr.
4091 if (auto *CCE = dyn_cast<CXXConstructExpr>(Sub))
4092 if (CCE->getParenOrBraceRange().isInvalid())
4093 Sub = CCE->getArg(0)->IgnoreImplicit();
4094 if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Sub))
4095 Sub = StdInitList->getSubExpr()->IgnoreImplicit();
4096 if (auto *IL = dyn_cast<InitListExpr>(Sub)) {
4097 Out << "tl";
4098 mangleType(E->getType());
4099 mangleInitListElements(IL);
4100 Out << "E";
4101 } else {
4102 mangleCastExpression(E, "cv");
4103 }
4104 break;
4105 }
4106
David Majnemer9c775c72014-09-23 04:27:55 +00004107 case Expr::CXXStaticCastExprClass:
4108 mangleCastExpression(E, "sc");
4109 break;
4110 case Expr::CXXDynamicCastExprClass:
4111 mangleCastExpression(E, "dc");
4112 break;
4113 case Expr::CXXReinterpretCastExprClass:
4114 mangleCastExpression(E, "rc");
4115 break;
4116 case Expr::CXXConstCastExprClass:
4117 mangleCastExpression(E, "cc");
4118 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004119
4120 case Expr::CXXOperatorCallExprClass: {
4121 const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
4122 unsigned NumArgs = CE->getNumArgs();
Richard Smith4631be72016-10-24 20:29:40 +00004123 // A CXXOperatorCallExpr for OO_Arrow models only semantics, not syntax
4124 // (the enclosing MemberExpr covers the syntactic portion).
4125 if (CE->getOperator() != OO_Arrow)
4126 mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);
Guy Benyei11169dd2012-12-18 14:30:41 +00004127 // Mangle the arguments.
4128 for (unsigned i = 0; i != NumArgs; ++i)
4129 mangleExpression(CE->getArg(i));
4130 break;
4131 }
4132
4133 case Expr::ParenExprClass:
4134 mangleExpression(cast<ParenExpr>(E)->getSubExpr(), Arity);
4135 break;
4136
Richard Smithb2997f52019-05-21 20:10:50 +00004137 case Expr::DeclRefExprClass:
4138 mangleDeclRefExpr(cast<DeclRefExpr>(E)->getDecl());
Guy Benyei11169dd2012-12-18 14:30:41 +00004139 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004140
4141 case Expr::SubstNonTypeTemplateParmPackExprClass:
4142 // FIXME: not clear how to mangle this!
4143 // template <unsigned N...> class A {
4144 // template <class U...> void foo(U (&x)[N]...);
4145 // };
4146 Out << "_SUBSTPACK_";
4147 break;
4148
4149 case Expr::FunctionParmPackExprClass: {
4150 // FIXME: not clear how to mangle this!
4151 const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);
4152 Out << "v110_SUBSTPACK";
Richard Smithb2997f52019-05-21 20:10:50 +00004153 mangleDeclRefExpr(FPPE->getParameterPack());
Guy Benyei11169dd2012-12-18 14:30:41 +00004154 break;
4155 }
4156
4157 case Expr::DependentScopeDeclRefExprClass: {
4158 const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
Richard Smithafecd832016-10-24 20:47:04 +00004159 mangleUnresolvedName(DRE->getQualifier(), DRE->getDeclName(),
4160 DRE->getTemplateArgs(), DRE->getNumTemplateArgs(),
4161 Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00004162 break;
4163 }
4164
4165 case Expr::CXXBindTemporaryExprClass:
4166 mangleExpression(cast<CXXBindTemporaryExpr>(E)->getSubExpr());
4167 break;
4168
4169 case Expr::ExprWithCleanupsClass:
4170 mangleExpression(cast<ExprWithCleanups>(E)->getSubExpr(), Arity);
4171 break;
4172
4173 case Expr::FloatingLiteralClass: {
4174 const FloatingLiteral *FL = cast<FloatingLiteral>(E);
4175 Out << 'L';
4176 mangleType(FL->getType());
4177 mangleFloat(FL->getValue());
4178 Out << 'E';
4179 break;
4180 }
4181
4182 case Expr::CharacterLiteralClass:
4183 Out << 'L';
4184 mangleType(E->getType());
4185 Out << cast<CharacterLiteral>(E)->getValue();
4186 Out << 'E';
4187 break;
4188
4189 // FIXME. __objc_yes/__objc_no are mangled same as true/false
4190 case Expr::ObjCBoolLiteralExprClass:
4191 Out << "Lb";
4192 Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');
4193 Out << 'E';
4194 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00004195
Guy Benyei11169dd2012-12-18 14:30:41 +00004196 case Expr::CXXBoolLiteralExprClass:
4197 Out << "Lb";
4198 Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
4199 Out << 'E';
4200 break;
4201
4202 case Expr::IntegerLiteralClass: {
4203 llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
4204 if (E->getType()->isSignedIntegerType())
4205 Value.setIsSigned(true);
4206 mangleIntegerLiteral(E->getType(), Value);
4207 break;
4208 }
4209
4210 case Expr::ImaginaryLiteralClass: {
4211 const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
4212 // Mangle as if a complex literal.
4213 // Proposal from David Vandevoorde, 2010.06.30.
4214 Out << 'L';
4215 mangleType(E->getType());
4216 if (const FloatingLiteral *Imag =
4217 dyn_cast<FloatingLiteral>(IE->getSubExpr())) {
4218 // Mangle a floating-point zero of the appropriate type.
4219 mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));
4220 Out << '_';
4221 mangleFloat(Imag->getValue());
4222 } else {
4223 Out << "0_";
4224 llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
4225 if (IE->getSubExpr()->getType()->isSignedIntegerType())
4226 Value.setIsSigned(true);
4227 mangleNumber(Value);
4228 }
4229 Out << 'E';
4230 break;
4231 }
4232
4233 case Expr::StringLiteralClass: {
4234 // Revised proposal from David Vandervoorde, 2010.07.15.
4235 Out << 'L';
4236 assert(isa<ConstantArrayType>(E->getType()));
4237 mangleType(E->getType());
4238 Out << 'E';
4239 break;
4240 }
4241
4242 case Expr::GNUNullExprClass:
4243 // FIXME: should this really be mangled the same as nullptr?
4244 // fallthrough
4245
4246 case Expr::CXXNullPtrLiteralExprClass: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004247 Out << "LDnE";
4248 break;
4249 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004250
Guy Benyei11169dd2012-12-18 14:30:41 +00004251 case Expr::PackExpansionExprClass:
4252 Out << "sp";
4253 mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
4254 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00004255
Guy Benyei11169dd2012-12-18 14:30:41 +00004256 case Expr::SizeOfPackExprClass: {
Richard Smithd784e682015-09-23 21:41:42 +00004257 auto *SPE = cast<SizeOfPackExpr>(E);
4258 if (SPE->isPartiallySubstituted()) {
4259 Out << "sP";
4260 for (const auto &A : SPE->getPartialArguments())
4261 mangleTemplateArg(A);
4262 Out << "E";
4263 break;
4264 }
4265
Guy Benyei11169dd2012-12-18 14:30:41 +00004266 Out << "sZ";
Richard Smithd784e682015-09-23 21:41:42 +00004267 const NamedDecl *Pack = SPE->getPack();
Guy Benyei11169dd2012-12-18 14:30:41 +00004268 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))
4269 mangleTemplateParameter(TTP->getIndex());
4270 else if (const NonTypeTemplateParmDecl *NTTP
4271 = dyn_cast<NonTypeTemplateParmDecl>(Pack))
4272 mangleTemplateParameter(NTTP->getIndex());
4273 else if (const TemplateTemplateParmDecl *TempTP
4274 = dyn_cast<TemplateTemplateParmDecl>(Pack))
4275 mangleTemplateParameter(TempTP->getIndex());
4276 else
4277 mangleFunctionParam(cast<ParmVarDecl>(Pack));
4278 break;
4279 }
Richard Smith0f0af192014-11-08 05:07:16 +00004280
Guy Benyei11169dd2012-12-18 14:30:41 +00004281 case Expr::MaterializeTemporaryExprClass: {
4282 mangleExpression(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr());
4283 break;
4284 }
Richard Smith0f0af192014-11-08 05:07:16 +00004285
4286 case Expr::CXXFoldExprClass: {
4287 auto *FE = cast<CXXFoldExpr>(E);
Richard Smith8e6923b2014-11-10 19:44:15 +00004288 if (FE->isLeftFold())
4289 Out << (FE->getInit() ? "fL" : "fl");
Richard Smith0f0af192014-11-08 05:07:16 +00004290 else
Richard Smith8e6923b2014-11-10 19:44:15 +00004291 Out << (FE->getInit() ? "fR" : "fr");
Richard Smith0f0af192014-11-08 05:07:16 +00004292
4293 if (FE->getOperator() == BO_PtrMemD)
4294 Out << "ds";
4295 else
4296 mangleOperatorName(
4297 BinaryOperator::getOverloadedOperator(FE->getOperator()),
4298 /*Arity=*/2);
4299
4300 if (FE->getLHS())
4301 mangleExpression(FE->getLHS());
4302 if (FE->getRHS())
4303 mangleExpression(FE->getRHS());
4304 break;
4305 }
4306
Guy Benyei11169dd2012-12-18 14:30:41 +00004307 case Expr::CXXThisExprClass:
4308 Out << "fpT";
4309 break;
Richard Smith9f690bd2015-10-27 06:02:45 +00004310
4311 case Expr::CoawaitExprClass:
4312 // FIXME: Propose a non-vendor mangling.
4313 Out << "v18co_await";
4314 mangleExpression(cast<CoawaitExpr>(E)->getOperand());
4315 break;
4316
Eric Fiselier20f25cb2017-03-06 23:38:15 +00004317 case Expr::DependentCoawaitExprClass:
4318 // FIXME: Propose a non-vendor mangling.
4319 Out << "v18co_await";
4320 mangleExpression(cast<DependentCoawaitExpr>(E)->getOperand());
4321 break;
4322
Richard Smith9f690bd2015-10-27 06:02:45 +00004323 case Expr::CoyieldExprClass:
4324 // FIXME: Propose a non-vendor mangling.
4325 Out << "v18co_yield";
4326 mangleExpression(cast<CoawaitExpr>(E)->getOperand());
4327 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004328 }
4329}
4330
4331/// Mangle an expression which refers to a parameter variable.
4332///
4333/// <expression> ::= <function-param>
4334/// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0
4335/// <function-param> ::= fp <top-level CV-qualifiers>
4336/// <parameter-2 non-negative number> _ # L == 0, I > 0
4337/// <function-param> ::= fL <L-1 non-negative number>
4338/// p <top-level CV-qualifiers> _ # L > 0, I == 0
4339/// <function-param> ::= fL <L-1 non-negative number>
4340/// p <top-level CV-qualifiers>
4341/// <I-1 non-negative number> _ # L > 0, I > 0
4342///
4343/// L is the nesting depth of the parameter, defined as 1 if the
4344/// parameter comes from the innermost function prototype scope
4345/// enclosing the current context, 2 if from the next enclosing
4346/// function prototype scope, and so on, with one special case: if
4347/// we've processed the full parameter clause for the innermost
4348/// function type, then L is one less. This definition conveniently
4349/// makes it irrelevant whether a function's result type was written
4350/// trailing or leading, but is otherwise overly complicated; the
4351/// numbering was first designed without considering references to
4352/// parameter in locations other than return types, and then the
4353/// mangling had to be generalized without changing the existing
4354/// manglings.
4355///
4356/// I is the zero-based index of the parameter within its parameter
4357/// declaration clause. Note that the original ABI document describes
4358/// this using 1-based ordinals.
4359void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {
4360 unsigned parmDepth = parm->getFunctionScopeDepth();
4361 unsigned parmIndex = parm->getFunctionScopeIndex();
4362
4363 // Compute 'L'.
4364 // parmDepth does not include the declaring function prototype.
4365 // FunctionTypeDepth does account for that.
4366 assert(parmDepth < FunctionTypeDepth.getDepth());
4367 unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth;
4368 if (FunctionTypeDepth.isInResultType())
4369 nestingDepth--;
4370
4371 if (nestingDepth == 0) {
4372 Out << "fp";
4373 } else {
4374 Out << "fL" << (nestingDepth - 1) << 'p';
4375 }
4376
4377 // Top-level qualifiers. We don't have to worry about arrays here,
4378 // because parameters declared as arrays should already have been
4379 // transformed to have pointer type. FIXME: apparently these don't
4380 // get mangled if used as an rvalue of a known non-class type?
4381 assert(!parm->getType()->isArrayType()
4382 && "parameter's type is still an array type?");
Andrew Gozillon572bbb02017-10-02 06:25:51 +00004383
4384 if (const DependentAddressSpaceType *DAST =
4385 dyn_cast<DependentAddressSpaceType>(parm->getType())) {
4386 mangleQualifiers(DAST->getPointeeType().getQualifiers(), DAST);
4387 } else {
4388 mangleQualifiers(parm->getType().getQualifiers());
4389 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004390
4391 // Parameter index.
4392 if (parmIndex != 0) {
4393 Out << (parmIndex - 1);
4394 }
4395 Out << '_';
4396}
4397
Richard Smith5179eb72016-06-28 19:03:57 +00004398void CXXNameMangler::mangleCXXCtorType(CXXCtorType T,
4399 const CXXRecordDecl *InheritedFrom) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004400 // <ctor-dtor-name> ::= C1 # complete object constructor
4401 // ::= C2 # base object constructor
Richard Smith5179eb72016-06-28 19:03:57 +00004402 // ::= CI1 <type> # complete inheriting constructor
4403 // ::= CI2 <type> # base inheriting constructor
Guy Benyei11169dd2012-12-18 14:30:41 +00004404 //
Rafael Espindola1e4df922014-09-16 15:18:21 +00004405 // In addition, C5 is a comdat name with C1 and C2 in it.
Richard Smith5179eb72016-06-28 19:03:57 +00004406 Out << 'C';
4407 if (InheritedFrom)
4408 Out << 'I';
Guy Benyei11169dd2012-12-18 14:30:41 +00004409 switch (T) {
4410 case Ctor_Complete:
Richard Smith5179eb72016-06-28 19:03:57 +00004411 Out << '1';
Guy Benyei11169dd2012-12-18 14:30:41 +00004412 break;
4413 case Ctor_Base:
Richard Smith5179eb72016-06-28 19:03:57 +00004414 Out << '2';
Guy Benyei11169dd2012-12-18 14:30:41 +00004415 break;
Rafael Espindola1e4df922014-09-16 15:18:21 +00004416 case Ctor_Comdat:
Richard Smith5179eb72016-06-28 19:03:57 +00004417 Out << '5';
Guy Benyei11169dd2012-12-18 14:30:41 +00004418 break;
David Majnemerdfa6d202015-03-11 18:36:39 +00004419 case Ctor_DefaultClosure:
4420 case Ctor_CopyingClosure:
4421 llvm_unreachable("closure constructors don't exist for the Itanium ABI!");
Guy Benyei11169dd2012-12-18 14:30:41 +00004422 }
Richard Smith5179eb72016-06-28 19:03:57 +00004423 if (InheritedFrom)
4424 mangleName(InheritedFrom);
Guy Benyei11169dd2012-12-18 14:30:41 +00004425}
4426
4427void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
4428 // <ctor-dtor-name> ::= D0 # deleting destructor
4429 // ::= D1 # complete object destructor
4430 // ::= D2 # base object destructor
4431 //
Rafael Espindola1e4df922014-09-16 15:18:21 +00004432 // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it.
Guy Benyei11169dd2012-12-18 14:30:41 +00004433 switch (T) {
4434 case Dtor_Deleting:
4435 Out << "D0";
4436 break;
4437 case Dtor_Complete:
4438 Out << "D1";
4439 break;
4440 case Dtor_Base:
4441 Out << "D2";
4442 break;
Rafael Espindola1e4df922014-09-16 15:18:21 +00004443 case Dtor_Comdat:
4444 Out << "D5";
4445 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004446 }
4447}
4448
James Y Knight04ec5bf2015-12-24 02:59:37 +00004449void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentLoc *TemplateArgs,
4450 unsigned NumTemplateArgs) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004451 // <template-args> ::= I <template-arg>+ E
4452 Out << 'I';
James Y Knight04ec5bf2015-12-24 02:59:37 +00004453 for (unsigned i = 0; i != NumTemplateArgs; ++i)
4454 mangleTemplateArg(TemplateArgs[i].getArgument());
Guy Benyei11169dd2012-12-18 14:30:41 +00004455 Out << 'E';
4456}
4457
4458void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentList &AL) {
4459 // <template-args> ::= I <template-arg>+ E
4460 Out << 'I';
4461 for (unsigned i = 0, e = AL.size(); i != e; ++i)
4462 mangleTemplateArg(AL[i]);
4463 Out << 'E';
4464}
4465
4466void CXXNameMangler::mangleTemplateArgs(const TemplateArgument *TemplateArgs,
4467 unsigned NumTemplateArgs) {
4468 // <template-args> ::= I <template-arg>+ E
4469 Out << 'I';
4470 for (unsigned i = 0; i != NumTemplateArgs; ++i)
4471 mangleTemplateArg(TemplateArgs[i]);
4472 Out << 'E';
4473}
4474
4475void CXXNameMangler::mangleTemplateArg(TemplateArgument A) {
4476 // <template-arg> ::= <type> # type or template
4477 // ::= X <expression> E # expression
4478 // ::= <expr-primary> # simple expressions
4479 // ::= J <template-arg>* E # argument pack
Guy Benyei11169dd2012-12-18 14:30:41 +00004480 if (!A.isInstantiationDependent() || A.isDependent())
4481 A = Context.getASTContext().getCanonicalTemplateArgument(A);
Fangrui Song6907ce22018-07-30 19:24:48 +00004482
Guy Benyei11169dd2012-12-18 14:30:41 +00004483 switch (A.getKind()) {
4484 case TemplateArgument::Null:
4485 llvm_unreachable("Cannot mangle NULL template argument");
Fangrui Song6907ce22018-07-30 19:24:48 +00004486
Guy Benyei11169dd2012-12-18 14:30:41 +00004487 case TemplateArgument::Type:
4488 mangleType(A.getAsType());
4489 break;
4490 case TemplateArgument::Template:
4491 // This is mangled as <type>.
4492 mangleType(A.getAsTemplate());
4493 break;
4494 case TemplateArgument::TemplateExpansion:
4495 // <type> ::= Dp <type> # pack expansion (C++0x)
4496 Out << "Dp";
4497 mangleType(A.getAsTemplateOrTemplatePattern());
4498 break;
4499 case TemplateArgument::Expression: {
4500 // It's possible to end up with a DeclRefExpr here in certain
4501 // dependent cases, in which case we should mangle as a
4502 // declaration.
Richard Smith07ed9cf2019-06-20 19:49:13 +00004503 const Expr *E = A.getAsExpr()->IgnoreParenImpCasts();
Guy Benyei11169dd2012-12-18 14:30:41 +00004504 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
4505 const ValueDecl *D = DRE->getDecl();
4506 if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {
David Majnemera16d4702015-02-18 19:08:14 +00004507 Out << 'L';
David Majnemer7ff7eb72015-02-18 07:47:09 +00004508 mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004509 Out << 'E';
4510 break;
4511 }
4512 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004513
Guy Benyei11169dd2012-12-18 14:30:41 +00004514 Out << 'X';
4515 mangleExpression(E);
4516 Out << 'E';
4517 break;
4518 }
4519 case TemplateArgument::Integral:
4520 mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral());
4521 break;
4522 case TemplateArgument::Declaration: {
4523 // <expr-primary> ::= L <mangled-name> E # external name
4524 // Clang produces AST's where pointer-to-member-function expressions
4525 // and pointer-to-function expressions are represented as a declaration not
4526 // an expression. We compensate for it here to produce the correct mangling.
4527 ValueDecl *D = A.getAsDecl();
David Blaikie952a9b12014-10-17 18:00:12 +00004528 bool compensateMangling = !A.getParamTypeForDecl()->isReferenceType();
Guy Benyei11169dd2012-12-18 14:30:41 +00004529 if (compensateMangling) {
4530 Out << 'X';
4531 mangleOperatorName(OO_Amp, 1);
4532 }
4533
4534 Out << 'L';
4535 // References to external entities use the mangled name; if the name would
Nico Weberfb420782016-05-25 14:15:08 +00004536 // not normally be mangled then mangle it as unqualified.
David Majnemer7ff7eb72015-02-18 07:47:09 +00004537 mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004538 Out << 'E';
4539
4540 if (compensateMangling)
4541 Out << 'E';
4542
4543 break;
4544 }
4545 case TemplateArgument::NullPtr: {
4546 // <expr-primary> ::= L <type> 0 E
4547 Out << 'L';
4548 mangleType(A.getNullPtrType());
4549 Out << "0E";
4550 break;
4551 }
4552 case TemplateArgument::Pack: {
Richard Smitheb0133c2013-08-27 01:03:46 +00004553 // <template-arg> ::= J <template-arg>* E
Guy Benyei11169dd2012-12-18 14:30:41 +00004554 Out << 'J';
Aaron Ballman2a89e852014-07-15 21:32:31 +00004555 for (const auto &P : A.pack_elements())
4556 mangleTemplateArg(P);
Guy Benyei11169dd2012-12-18 14:30:41 +00004557 Out << 'E';
4558 }
4559 }
4560}
4561
4562void CXXNameMangler::mangleTemplateParameter(unsigned Index) {
4563 // <template-param> ::= T_ # first template parameter
4564 // ::= T <parameter-2 non-negative number> _
4565 if (Index == 0)
4566 Out << "T_";
4567 else
4568 Out << 'T' << (Index - 1) << '_';
4569}
4570
David Majnemer3b3bdb52014-05-06 22:49:16 +00004571void CXXNameMangler::mangleSeqID(unsigned SeqID) {
4572 if (SeqID == 1)
4573 Out << '0';
4574 else if (SeqID > 1) {
4575 SeqID--;
4576
4577 // <seq-id> is encoded in base-36, using digits and upper case letters.
4578 char Buffer[7]; // log(2**32) / log(36) ~= 7
Craig Toppere3d2ecbe2014-06-28 23:22:33 +00004579 MutableArrayRef<char> BufferRef(Buffer);
4580 MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
David Majnemer3b3bdb52014-05-06 22:49:16 +00004581
4582 for (; SeqID != 0; SeqID /= 36) {
4583 unsigned C = SeqID % 36;
4584 *I++ = (C < 10 ? '0' + C : 'A' + C - 10);
4585 }
4586
4587 Out.write(I.base(), I - BufferRef.rbegin());
4588 }
4589 Out << '_';
4590}
4591
Guy Benyei11169dd2012-12-18 14:30:41 +00004592void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) {
4593 bool result = mangleSubstitution(tname);
4594 assert(result && "no existing substitution for template name");
4595 (void) result;
4596}
4597
4598// <substitution> ::= S <seq-id> _
4599// ::= S_
4600bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {
4601 // Try one of the standard substitutions first.
4602 if (mangleStandardSubstitution(ND))
4603 return true;
4604
4605 ND = cast<NamedDecl>(ND->getCanonicalDecl());
4606 return mangleSubstitution(reinterpret_cast<uintptr_t>(ND));
4607}
4608
Justin Bognere8d762e2015-05-22 06:48:13 +00004609/// Determine whether the given type has any qualifiers that are relevant for
4610/// substitutions.
Guy Benyei11169dd2012-12-18 14:30:41 +00004611static bool hasMangledSubstitutionQualifiers(QualType T) {
4612 Qualifiers Qs = T.getQualifiers();
Roger Ferrer Ibanezfd9384a2017-06-02 07:14:34 +00004613 return Qs.getCVRQualifiers() || Qs.hasAddressSpace() || Qs.hasUnaligned();
Guy Benyei11169dd2012-12-18 14:30:41 +00004614}
4615
4616bool CXXNameMangler::mangleSubstitution(QualType T) {
4617 if (!hasMangledSubstitutionQualifiers(T)) {
4618 if (const RecordType *RT = T->getAs<RecordType>())
4619 return mangleSubstitution(RT->getDecl());
4620 }
4621
4622 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
4623
4624 return mangleSubstitution(TypePtr);
4625}
4626
4627bool CXXNameMangler::mangleSubstitution(TemplateName Template) {
4628 if (TemplateDecl *TD = Template.getAsTemplateDecl())
4629 return mangleSubstitution(TD);
Fangrui Song6907ce22018-07-30 19:24:48 +00004630
Guy Benyei11169dd2012-12-18 14:30:41 +00004631 Template = Context.getASTContext().getCanonicalTemplateName(Template);
4632 return mangleSubstitution(
4633 reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
4634}
4635
4636bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) {
4637 llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr);
4638 if (I == Substitutions.end())
4639 return false;
4640
4641 unsigned SeqID = I->second;
David Majnemer3b3bdb52014-05-06 22:49:16 +00004642 Out << 'S';
4643 mangleSeqID(SeqID);
Guy Benyei11169dd2012-12-18 14:30:41 +00004644
4645 return true;
4646}
4647
4648static bool isCharType(QualType T) {
4649 if (T.isNull())
4650 return false;
4651
4652 return T->isSpecificBuiltinType(BuiltinType::Char_S) ||
4653 T->isSpecificBuiltinType(BuiltinType::Char_U);
4654}
4655
Justin Bognere8d762e2015-05-22 06:48:13 +00004656/// Returns whether a given type is a template specialization of a given name
4657/// with a single argument of type char.
Guy Benyei11169dd2012-12-18 14:30:41 +00004658static bool isCharSpecialization(QualType T, const char *Name) {
4659 if (T.isNull())
4660 return false;
4661
4662 const RecordType *RT = T->getAs<RecordType>();
4663 if (!RT)
4664 return false;
4665
4666 const ClassTemplateSpecializationDecl *SD =
4667 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
4668 if (!SD)
4669 return false;
4670
4671 if (!isStdNamespace(getEffectiveDeclContext(SD)))
4672 return false;
4673
4674 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4675 if (TemplateArgs.size() != 1)
4676 return false;
4677
4678 if (!isCharType(TemplateArgs[0].getAsType()))
4679 return false;
4680
4681 return SD->getIdentifier()->getName() == Name;
4682}
4683
4684template <std::size_t StrLen>
4685static bool isStreamCharSpecialization(const ClassTemplateSpecializationDecl*SD,
4686 const char (&Str)[StrLen]) {
4687 if (!SD->getIdentifier()->isStr(Str))
4688 return false;
4689
4690 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4691 if (TemplateArgs.size() != 2)
4692 return false;
4693
4694 if (!isCharType(TemplateArgs[0].getAsType()))
4695 return false;
4696
4697 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
4698 return false;
4699
4700 return true;
4701}
4702
4703bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {
4704 // <substitution> ::= St # ::std::
4705 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
4706 if (isStd(NS)) {
4707 Out << "St";
4708 return true;
4709 }
4710 }
4711
4712 if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) {
4713 if (!isStdNamespace(getEffectiveDeclContext(TD)))
4714 return false;
4715
4716 // <substitution> ::= Sa # ::std::allocator
4717 if (TD->getIdentifier()->isStr("allocator")) {
4718 Out << "Sa";
4719 return true;
4720 }
4721
4722 // <<substitution> ::= Sb # ::std::basic_string
4723 if (TD->getIdentifier()->isStr("basic_string")) {
4724 Out << "Sb";
4725 return true;
4726 }
4727 }
4728
4729 if (const ClassTemplateSpecializationDecl *SD =
4730 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
4731 if (!isStdNamespace(getEffectiveDeclContext(SD)))
4732 return false;
4733
4734 // <substitution> ::= Ss # ::std::basic_string<char,
4735 // ::std::char_traits<char>,
4736 // ::std::allocator<char> >
4737 if (SD->getIdentifier()->isStr("basic_string")) {
4738 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4739
4740 if (TemplateArgs.size() != 3)
4741 return false;
4742
4743 if (!isCharType(TemplateArgs[0].getAsType()))
4744 return false;
4745
4746 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
4747 return false;
4748
4749 if (!isCharSpecialization(TemplateArgs[2].getAsType(), "allocator"))
4750 return false;
4751
4752 Out << "Ss";
4753 return true;
4754 }
4755
4756 // <substitution> ::= Si # ::std::basic_istream<char,
4757 // ::std::char_traits<char> >
4758 if (isStreamCharSpecialization(SD, "basic_istream")) {
4759 Out << "Si";
4760 return true;
4761 }
4762
4763 // <substitution> ::= So # ::std::basic_ostream<char,
4764 // ::std::char_traits<char> >
4765 if (isStreamCharSpecialization(SD, "basic_ostream")) {
4766 Out << "So";
4767 return true;
4768 }
4769
4770 // <substitution> ::= Sd # ::std::basic_iostream<char,
4771 // ::std::char_traits<char> >
4772 if (isStreamCharSpecialization(SD, "basic_iostream")) {
4773 Out << "Sd";
4774 return true;
4775 }
4776 }
4777 return false;
4778}
4779
4780void CXXNameMangler::addSubstitution(QualType T) {
4781 if (!hasMangledSubstitutionQualifiers(T)) {
4782 if (const RecordType *RT = T->getAs<RecordType>()) {
4783 addSubstitution(RT->getDecl());
4784 return;
4785 }
4786 }
4787
4788 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
4789 addSubstitution(TypePtr);
4790}
4791
4792void CXXNameMangler::addSubstitution(TemplateName Template) {
4793 if (TemplateDecl *TD = Template.getAsTemplateDecl())
4794 return addSubstitution(TD);
Fangrui Song6907ce22018-07-30 19:24:48 +00004795
Guy Benyei11169dd2012-12-18 14:30:41 +00004796 Template = Context.getASTContext().getCanonicalTemplateName(Template);
4797 addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
4798}
4799
4800void CXXNameMangler::addSubstitution(uintptr_t Ptr) {
4801 assert(!Substitutions.count(Ptr) && "Substitution already exists!");
4802 Substitutions[Ptr] = SeqID++;
4803}
4804
Dmitry Polukhinfda467b2016-09-21 08:27:03 +00004805void CXXNameMangler::extendSubstitutions(CXXNameMangler* Other) {
4806 assert(Other->SeqID >= SeqID && "Must be superset of substitutions!");
4807 if (Other->SeqID > SeqID) {
4808 Substitutions.swap(Other->Substitutions);
4809 SeqID = Other->SeqID;
4810 }
4811}
4812
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00004813CXXNameMangler::AbiTagList
4814CXXNameMangler::makeFunctionReturnTypeTags(const FunctionDecl *FD) {
4815 // When derived abi tags are disabled there is no need to make any list.
4816 if (DisableDerivedAbiTags)
4817 return AbiTagList();
4818
4819 llvm::raw_null_ostream NullOutStream;
4820 CXXNameMangler TrackReturnTypeTags(*this, NullOutStream);
4821 TrackReturnTypeTags.disableDerivedAbiTags();
4822
4823 const FunctionProtoType *Proto =
4824 cast<FunctionProtoType>(FD->getType()->getAs<FunctionType>());
Dmitry Polukhind4b3bbc2017-06-14 09:47:47 +00004825 FunctionTypeDepthState saved = TrackReturnTypeTags.FunctionTypeDepth.push();
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00004826 TrackReturnTypeTags.FunctionTypeDepth.enterResultType();
4827 TrackReturnTypeTags.mangleType(Proto->getReturnType());
4828 TrackReturnTypeTags.FunctionTypeDepth.leaveResultType();
Dmitry Polukhind4b3bbc2017-06-14 09:47:47 +00004829 TrackReturnTypeTags.FunctionTypeDepth.pop(saved);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00004830
4831 return TrackReturnTypeTags.AbiTagsRoot.getSortedUniqueUsedAbiTags();
4832}
4833
4834CXXNameMangler::AbiTagList
4835CXXNameMangler::makeVariableTypeTags(const VarDecl *VD) {
4836 // When derived abi tags are disabled there is no need to make any list.
4837 if (DisableDerivedAbiTags)
4838 return AbiTagList();
4839
4840 llvm::raw_null_ostream NullOutStream;
4841 CXXNameMangler TrackVariableType(*this, NullOutStream);
4842 TrackVariableType.disableDerivedAbiTags();
4843
4844 TrackVariableType.mangleType(VD->getType());
4845
4846 return TrackVariableType.AbiTagsRoot.getSortedUniqueUsedAbiTags();
4847}
4848
4849bool CXXNameMangler::shouldHaveAbiTags(ItaniumMangleContextImpl &C,
4850 const VarDecl *VD) {
4851 llvm::raw_null_ostream NullOutStream;
4852 CXXNameMangler TrackAbiTags(C, NullOutStream, nullptr, true);
4853 TrackAbiTags.mangle(VD);
4854 return TrackAbiTags.AbiTagsRoot.getUsedAbiTags().size();
4855}
4856
Guy Benyei11169dd2012-12-18 14:30:41 +00004857//
4858
Justin Bognere8d762e2015-05-22 06:48:13 +00004859/// Mangles the name of the declaration D and emits that name to the given
4860/// output stream.
Guy Benyei11169dd2012-12-18 14:30:41 +00004861///
4862/// If the declaration D requires a mangled name, this routine will emit that
4863/// mangled name to \p os and return true. Otherwise, \p os will be unchanged
4864/// and this routine will return false. In this case, the caller should just
4865/// emit the identifier of the declaration (\c D->getIdentifier()) as its
4866/// name.
Rafael Espindola002667c2013-10-16 01:40:34 +00004867void ItaniumMangleContextImpl::mangleCXXName(const NamedDecl *D,
4868 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004869 assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
4870 "Invalid mangleName() call, argument is not a variable or function!");
4871 assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
4872 "Invalid mangleName() call on 'structor decl!");
4873
4874 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
4875 getASTContext().getSourceManager(),
4876 "Mangling declaration");
4877
4878 CXXNameMangler Mangler(*this, Out, D);
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00004879 Mangler.mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004880}
4881
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004882void ItaniumMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D,
4883 CXXCtorType Type,
4884 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004885 CXXNameMangler Mangler(*this, Out, D, Type);
4886 Mangler.mangle(D);
4887}
4888
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004889void ItaniumMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D,
4890 CXXDtorType Type,
4891 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004892 CXXNameMangler Mangler(*this, Out, D, Type);
4893 Mangler.mangle(D);
4894}
4895
Rafael Espindola1e4df922014-09-16 15:18:21 +00004896void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D,
4897 raw_ostream &Out) {
4898 CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat);
4899 Mangler.mangle(D);
4900}
4901
4902void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D,
4903 raw_ostream &Out) {
4904 CXXNameMangler Mangler(*this, Out, D, Dtor_Comdat);
4905 Mangler.mangle(D);
4906}
4907
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004908void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
4909 const ThunkInfo &Thunk,
4910 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004911 // <special-name> ::= T <call-offset> <base encoding>
4912 // # base is the nominal target function of thunk
4913 // <special-name> ::= Tc <call-offset> <call-offset> <base encoding>
4914 // # base is the nominal target function of thunk
4915 // # first call-offset is 'this' adjustment
4916 // # second call-offset is result adjustment
Fangrui Song6907ce22018-07-30 19:24:48 +00004917
Guy Benyei11169dd2012-12-18 14:30:41 +00004918 assert(!isa<CXXDestructorDecl>(MD) &&
4919 "Use mangleCXXDtor for destructor decls!");
4920 CXXNameMangler Mangler(*this, Out);
4921 Mangler.getStream() << "_ZT";
4922 if (!Thunk.Return.isEmpty())
4923 Mangler.getStream() << 'c';
Fangrui Song6907ce22018-07-30 19:24:48 +00004924
Guy Benyei11169dd2012-12-18 14:30:41 +00004925 // Mangle the 'this' pointer adjustment.
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00004926 Mangler.mangleCallOffset(Thunk.This.NonVirtual,
4927 Thunk.This.Virtual.Itanium.VCallOffsetOffset);
4928
Guy Benyei11169dd2012-12-18 14:30:41 +00004929 // Mangle the return pointer adjustment if there is one.
4930 if (!Thunk.Return.isEmpty())
4931 Mangler.mangleCallOffset(Thunk.Return.NonVirtual,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00004932 Thunk.Return.Virtual.Itanium.VBaseOffsetOffset);
4933
Guy Benyei11169dd2012-12-18 14:30:41 +00004934 Mangler.mangleFunctionEncoding(MD);
4935}
4936
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004937void ItaniumMangleContextImpl::mangleCXXDtorThunk(
4938 const CXXDestructorDecl *DD, CXXDtorType Type,
4939 const ThisAdjustment &ThisAdjustment, raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004940 // <special-name> ::= T <call-offset> <base encoding>
4941 // # base is the nominal target function of thunk
4942 CXXNameMangler Mangler(*this, Out, DD, Type);
4943 Mangler.getStream() << "_ZT";
4944
4945 // Mangle the 'this' pointer adjustment.
Fangrui Song6907ce22018-07-30 19:24:48 +00004946 Mangler.mangleCallOffset(ThisAdjustment.NonVirtual,
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00004947 ThisAdjustment.Virtual.Itanium.VCallOffsetOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00004948
4949 Mangler.mangleFunctionEncoding(DD);
4950}
4951
Justin Bognere8d762e2015-05-22 06:48:13 +00004952/// Returns the mangled name for a guard variable for the passed in VarDecl.
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004953void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D,
4954 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004955 // <special-name> ::= GV <object name> # Guard variable for one-time
4956 // # initialization
4957 CXXNameMangler Mangler(*this, Out);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00004958 // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
4959 // be a bug that is fixed in trunk.
Guy Benyei11169dd2012-12-18 14:30:41 +00004960 Mangler.getStream() << "_ZGV";
4961 Mangler.mangleName(D);
4962}
4963
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004964void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD,
4965 raw_ostream &Out) {
Reid Kleckner1ece9fc2013-09-10 20:43:12 +00004966 // These symbols are internal in the Itanium ABI, so the names don't matter.
4967 // Clang has traditionally used this symbol and allowed LLVM to adjust it to
4968 // avoid duplicate symbols.
4969 Out << "__cxx_global_var_init";
4970}
4971
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004972void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
4973 raw_ostream &Out) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00004974 // Prefix the mangling of D with __dtor_.
4975 CXXNameMangler Mangler(*this, Out);
4976 Mangler.getStream() << "__dtor_";
4977 if (shouldMangleDeclName(D))
4978 Mangler.mangle(D);
4979 else
4980 Mangler.getStream() << D->getName();
4981}
4982
Reid Kleckner1d59f992015-01-22 01:36:17 +00004983void ItaniumMangleContextImpl::mangleSEHFilterExpression(
4984 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
4985 CXXNameMangler Mangler(*this, Out);
4986 Mangler.getStream() << "__filt_";
4987 if (shouldMangleDeclName(EnclosingDecl))
4988 Mangler.mangle(EnclosingDecl);
4989 else
4990 Mangler.getStream() << EnclosingDecl->getName();
4991}
4992
Reid Klecknerebaf28d2015-04-14 20:59:00 +00004993void ItaniumMangleContextImpl::mangleSEHFinallyBlock(
4994 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
4995 CXXNameMangler Mangler(*this, Out);
4996 Mangler.getStream() << "__fin_";
4997 if (shouldMangleDeclName(EnclosingDecl))
4998 Mangler.mangle(EnclosingDecl);
4999 else
5000 Mangler.getStream() << EnclosingDecl->getName();
5001}
5002
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00005003void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D,
5004 raw_ostream &Out) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00005005 // <special-name> ::= TH <object name>
5006 CXXNameMangler Mangler(*this, Out);
5007 Mangler.getStream() << "_ZTH";
5008 Mangler.mangleName(D);
5009}
5010
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00005011void
5012ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D,
5013 raw_ostream &Out) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00005014 // <special-name> ::= TW <object name>
5015 CXXNameMangler Mangler(*this, Out);
5016 Mangler.getStream() << "_ZTW";
5017 Mangler.mangleName(D);
5018}
5019
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00005020void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D,
David Majnemerdaff3702014-05-01 17:50:17 +00005021 unsigned ManglingNumber,
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00005022 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005023 // We match the GCC mangling here.
5024 // <special-name> ::= GR <object name>
5025 CXXNameMangler Mangler(*this, Out);
5026 Mangler.getStream() << "_ZGR";
5027 Mangler.mangleName(D);
David Majnemerdaff3702014-05-01 17:50:17 +00005028 assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!");
David Majnemer3b3bdb52014-05-06 22:49:16 +00005029 Mangler.mangleSeqID(ManglingNumber - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00005030}
5031
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00005032void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD,
5033 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005034 // <special-name> ::= TV <type> # virtual table
5035 CXXNameMangler Mangler(*this, Out);
5036 Mangler.getStream() << "_ZTV";
5037 Mangler.mangleNameOrStandardSubstitution(RD);
5038}
5039
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00005040void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD,
5041 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005042 // <special-name> ::= TT <type> # VTT structure
5043 CXXNameMangler Mangler(*this, Out);
5044 Mangler.getStream() << "_ZTT";
5045 Mangler.mangleNameOrStandardSubstitution(RD);
5046}
5047
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00005048void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD,
5049 int64_t Offset,
5050 const CXXRecordDecl *Type,
5051 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005052 // <special-name> ::= TC <type> <offset number> _ <base type>
5053 CXXNameMangler Mangler(*this, Out);
5054 Mangler.getStream() << "_ZTC";
5055 Mangler.mangleNameOrStandardSubstitution(RD);
5056 Mangler.getStream() << Offset;
5057 Mangler.getStream() << '_';
5058 Mangler.mangleNameOrStandardSubstitution(Type);
5059}
5060
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00005061void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005062 // <special-name> ::= TI <type> # typeinfo structure
5063 assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers");
5064 CXXNameMangler Mangler(*this, Out);
5065 Mangler.getStream() << "_ZTI";
5066 Mangler.mangleType(Ty);
5067}
5068
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00005069void ItaniumMangleContextImpl::mangleCXXRTTIName(QualType Ty,
5070 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005071 // <special-name> ::= TS <type> # typeinfo name (null terminated byte string)
5072 CXXNameMangler Mangler(*this, Out);
5073 Mangler.getStream() << "_ZTS";
5074 Mangler.mangleType(Ty);
5075}
5076
Reid Klecknercc99e262013-11-19 23:23:00 +00005077void ItaniumMangleContextImpl::mangleTypeName(QualType Ty, raw_ostream &Out) {
5078 mangleCXXRTTIName(Ty, Out);
5079}
5080
David Majnemer58e5bee2014-03-24 21:43:36 +00005081void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) {
5082 llvm_unreachable("Can't mangle string literals");
5083}
5084
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00005085ItaniumMangleContext *
5086ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
5087 return new ItaniumMangleContextImpl(Context, Diags);
Guy Benyei11169dd2012-12-18 14:30:41 +00005088}